diff --git a/apps/mobile/src/ext/flows/ui/Editor.tsx b/apps/mobile/src/ext/flows/ui/Editor.tsx index 3bda003..003e51b 100644 --- a/apps/mobile/src/ext/flows/ui/Editor.tsx +++ b/apps/mobile/src/ext/flows/ui/Editor.tsx @@ -7,7 +7,8 @@ import { addKeyframe, addMarker, addTrack, fmtSeconds, FlowPlayer, patchMarker, patchTrack, removeKeys, removeTrack, setDuration, setKeyframe, DEFAULT_VIEW, START_KEYFRAME, VIEW_LABELS, type Flow, type FlowBody, type FlowView, type Keyframe, type KeyframeSize, } from "@openclapper/ext-flows"; -import { ApiError, canCall, lockFile, unlockFile } from "../../../api"; +import { ApiError, authHeaders, canCall, lockFile, unlockFile } from "../../../api"; +import { API_URL } from "../../../config"; import { log } from "../../../log"; import { useBack } from "../../../shell/back"; import { Banner, Block, Button, Header, Hint, IconButton, Input, ListRow, makeStyles, Seg, Sheet, SheetList, Slider, Toggle, type, useTheme } from "../../../ui"; @@ -76,7 +77,23 @@ export function FlowEditor({ flow, back }: { flow: LocalFlow; back: () => void } }; void take(); const h = setInterval(() => void take(), RENEW_MS); - return () => { stop = true; clearInterval(h); if (holderRef.current) void unlockFile(flow.id, holderRef.current).catch(() => undefined); }; + // The file's live room (#426): who edits is never stale. Freed: take it at once; saved elsewhere: read it again. + let ws: WebSocket | null = null, retry: ReturnType | undefined; + const open = () => { + if (stop || flow.updatedAt === null || !canCall()) return; + // React Native's WebSocket takes headers: the session goes as it does for every call (link.ts). + const s = new (WebSocket as unknown as new (url: string, protocols: string[] | null, opts: { headers: Record }) => WebSocket)(`${API_URL.replace(/^http/, "ws")}/api/canvases/${flow.id}/live?holder=${holder}`, null, { headers: authHeaders() }); + ws = s; + s.onmessage = (e) => { + let m: { type?: string; by?: string | null }; + try { m = JSON.parse(String(e.data)) as typeof m; } catch { return; } + if (m.type === "editor" && !m.by && !holderRef.current) void take(); + else if (m.type === "saved" && !holderRef.current) void loadFlows(flow.projectId); + }; + s.onclose = () => { if (ws === s) ws = null; if (!stop) retry = setTimeout(open, 5000); }; + }; + open(); + return () => { stop = true; clearInterval(h); clearTimeout(retry); ws?.close(); if (holderRef.current) void unlockFile(flow.id, holderRef.current).catch(() => undefined); }; }, [flow.id]); const locked = lock.state === "theirs" || lock.state === "asking"; // Read-only, it shows the flow as its editor last saved it. diff --git a/apps/studio/src/apps/CanvasApp.tsx b/apps/studio/src/apps/CanvasApp.tsx index d0f0f65..4dd4a07 100644 --- a/apps/studio/src/apps/CanvasApp.tsx +++ b/apps/studio/src/apps/CanvasApp.tsx @@ -114,9 +114,11 @@ export function Editing({ file, files, projectId, me, nameOf, active, hosted, li }; const apply = (b: CanvasBody, bid: string | null) => { setDoc(b); setBaseId(bid); latest.current = { doc: b, baseId: bid }; setRev((r) => r + 1); }; - // The live socket: the editor when this window holds the lock, else a viewer; opened again on Edit and Stop editing, and after a drop. + // The live socket: the editor when this window holds the lock, else a viewer; opened again on Edit and Stop editing, and + // after a drop. In every project, so who edits is never stale (#426); strokes and the canvas stream only in a realtime one. + const streaming = useRef(live === "realtime"); + streaming.current = live === "realtime"; useEffect(() => { - if (live !== "realtime") return; let ws: WebSocket | null = null, done = false, retry: ReturnType | undefined; const open = () => { const s = new WebSocket(`${location.origin.replace(/^http/, "ws")}/api/canvases/${file.id}/live?holder=${holder}`); @@ -126,18 +128,19 @@ export function Editing({ file, files, projectId, me, nameOf, active, hosted, li if (held.current) return; let m: { type?: string; body?: CanvasBody; base?: string | null; draft?: Draft | null; by?: string | null }; try { m = JSON.parse(String(e.data)) as typeof m; } catch { return; } - if (m.type === "doc" && m.body) { apply(m.body, m.base ?? null); setRemoteDraft(null); } - else if (m.type === "draft") setRemoteDraft(m.draft ?? null); + if (m.type === "doc" && m.body) { if (streaming.current) { apply(m.body, m.base ?? null); setRemoteDraft(null); } } + else if (m.type === "draft") { if (streaming.current) setRemoteDraft(m.draft ?? null); } else if (m.type === "saved") void reread(false).catch(() => {}); - else if (m.type === "editor") { setLockedBy(m.by ? nameOf(m.by) : null); if (!m.by) setRemoteDraft(null); } + else if (m.type === "editor") { setLockedBy(m.by ? nameOf(m.by) : null); if (!m.by) { setRemoteDraft(null); void reread(false).catch(() => {}); } } }; s.onclose = () => { if (sock.current === s) { sock.current = null; setConnected(false); } if (!done) retry = setTimeout(open, 3000); }; }; open(); return () => { done = true; clearTimeout(retry); if (sock.current === ws) { sock.current = null; setConnected(false); } ws?.close(); }; - }, [live, editing]); + }, [editing]); /** Sends the canvas (or the stroke being drawn) to the viewers, at most every SEND_MS; the last state always goes. */ const send = (what: { doc: true } | { draft: Draft | null }) => { + if (!streaming.current) return; const st = sendState.current; if ("doc" in what) { st.doc = true; st.draft = null; } else st.draft = what.draft; if (st.timer) return; diff --git a/apps/studio/src/lock.ts b/apps/studio/src/lock.ts index 35e7bf8..adad937 100644 --- a/apps/studio/src/lock.ts +++ b/apps/studio/src/lock.ts @@ -86,9 +86,12 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o return () => { clearInterval(renew); clearInterval(look); window.removeEventListener("pagehide", bye); bye(); }; }, [file.id]); - // The live room: opened again when this window starts or stops editing (its role changes), and after a drop. + // The live room: opened again when this window starts or stops editing (its role changes), and after a drop. In every + // project, so who edits is never stale (#426); the content itself streams only in a realtime project. + const realtime = useRef(opts.realtime); + realtime.current = opts.realtime; useEffect(() => { - if (!opts.realtime || opts.off) return; + if (opts.off) return; let ws: WebSocket | null = null, done = false, retry: ReturnType | undefined; const open = () => { const s = new WebSocket(`${location.origin.replace(/^http/, "ws")}/api/canvases/${file.id}/live?holder=${holder}`); @@ -98,16 +101,18 @@ export function useEditLock(file: FileRec, nameOf: (userId: string) => string, o if (held.current) return; let m: { type?: string; body?: Record; refs?: LiveDoc["refs"]; by?: string | null }; try { m = JSON.parse(String(e.data)) as typeof m; } catch { return; } - if (m.type === "doc" && m.body) remote.current?.({ body: m.body, refs: m.refs }); + if (m.type === "doc" && m.body) { if (realtime.current) remote.current?.({ body: m.body, refs: m.refs }); } else if (m.type === "saved") void reread(false).catch(() => {}); - else if (m.type === "editor") setBy(m.by ? nameOf(m.by) : null); + // Let go or run out: free to edit now, and the last save is read. + else if (m.type === "editor") { setBy(m.by ? nameOf(m.by) : null); if (!m.by) void reread(false).catch(() => {}); } }; s.onclose = () => { if (sock.current === s) { sock.current = null; setLive(false); } if (!done) retry = setTimeout(open, 3000); }; }; open(); return () => { done = true; clearTimeout(retry); if (sock.current === ws) { sock.current = null; setLive(false); } ws?.close(); }; - }, [opts.realtime, editing, file.id]); + }, [opts.off, editing, file.id]); const send = (doc: () => LiveDoc) => { + if (!realtime.current) return; const st = sending.current; st.doc = doc; if (st.timer) return; diff --git a/apps/worker/src/canvas.ts b/apps/worker/src/canvas.ts index 550ec43..9b4c1f0 100644 --- a/apps/worker/src/canvas.ts +++ b/apps/worker/src/canvas.ts @@ -3,6 +3,7 @@ * frames table kept from a canvas's body, the edit lock (one editor at a time, for every lockable * type), a canvas's render and thumbnail, and the additive rule of presets. */ +import { tellRoom } from "./live.ts"; import { assertUuid, HttpError, json, readJson, type Router } from "@openclapper/service-kit"; import { fileType, presetChangeError, type CanvasBody, type PresetBody, type ShotBody } from "@openclapper/model"; import { accessFile, fileOut } from "./files.ts"; @@ -132,6 +133,7 @@ export function registerCanvasRoutes(r: Router) { ).bind(f.id, tenant.userId, holder, until, now()).run(); const row = await env.DB.prepare("SELECT lock_by, lock_until FROM files WHERE id = ?1").bind(f.id).first<{ lock_by: string; lock_until: string }>(); if (!took.meta.changes) return json({ error: "someone else is editing this file", lock: { by: row!.lock_by, until: row!.lock_until } }, 423); + await tellRoom(env, f.id, { type: "lock", by: row!.lock_by, until: row!.lock_until }); return json({ lock: { by: row!.lock_by, until: row!.lock_until } }); }); @@ -139,7 +141,8 @@ export function registerCanvasRoutes(r: Router) { r.on("DELETE", "/api/files/:id/lock", async (ctx, { id }) => { const f = await accessFile(ctx, assertUuid(id, "id"), "viewer"); const holder = readHolder(ctx.url.searchParams.get("holder")); - await ctx.env.DB.prepare("UPDATE files SET lock_by = NULL, lock_holder = NULL, lock_until = NULL WHERE id = ?1 AND lock_by = ?2 AND lock_holder = ?3").bind(f.id, ctx.tenant.userId, holder).run(); + const letGo = await ctx.env.DB.prepare("UPDATE files SET lock_by = NULL, lock_holder = NULL, lock_until = NULL WHERE id = ?1 AND lock_by = ?2 AND lock_holder = ?3").bind(f.id, ctx.tenant.userId, holder).run(); + if (letGo.meta.changes) await tellRoom(ctx.env, f.id, { type: "lock", by: null, until: null }); return new Response(null, { status: 204 }); }); diff --git a/apps/worker/src/files.ts b/apps/worker/src/files.ts index 9406244..cb83987 100644 --- a/apps/worker/src/files.ts +++ b/apps/worker/src/files.ts @@ -1,6 +1,7 @@ import { BIN_RETENTION_DAYS, canBeInternal, checkFile, containerTypes, defaultName, matchesSearch, FIXED_FOLDERS, fileType, SETTINGS_PAGE_NAMES, SETTINGS_PAGES, type SettingsPage, fileTypes, MAX_BULK, MAX_CONTAINER_DEPTH, MAX_FILE_NAME, nameError, placementError, type Body, type CanvasBody, type FileType, type PresetBody, type Ref, type RootKind, type ShotBody, keepGuarded } from "@openclapper/model"; +import { tellRoom } from "./live.ts"; import { assertUuid, HttpError, json, readJson, type Router } from "@openclapper/service-kit"; import type { Ctx, Env } from "./index.ts"; import { assertNotLocked, assertPresetChange, assertPresetsFree, copyFrames, copyRenders, frameStatements, removeRenders, renderKeys, shotFrameStatements } from "./canvas.ts"; @@ -453,6 +454,8 @@ export function registerFileRoutes(r: Router) { await env.DB.batch(stmts); // A changed definition: values that no longer fit it are fitted or dropped. if (t.type === "property" && stored && save && root.projectId) await refitValues(env, root.projectId, fid); + // Whoever watches a lockable file hears at once that it was saved (#426: from any client, the device's too). + if (stored && t.lockable) await tellRoom(env, fid, { type: "saved" }); return json({ file: await fileOut(env, fid) }, stored ? 200 : 201); }); diff --git a/apps/worker/src/live.ts b/apps/worker/src/live.ts index dae6fa3..5051b38 100644 --- a/apps/worker/src/live.ts +++ b/apps/worker/src/live.ts @@ -17,6 +17,10 @@ import type { Ctx, Env } from "./index.ts"; * `{ type: "saved" }` (after a save, when the canvas was too large to send). * Room → viewers: the same `doc`, `draft` and `saved`, and `{ type: "editor", by }` when an editor connects, renews * or leaves (by: a user id, or null). + * + * The lock itself is live in every project (#426): the lock routes tell the room when it is taken, renewed or let + * go, a save tells it `saved`, and an alarm at the lock's end says when it ran out, so who edits is never stale on + * any client, the device's Flows editor included. Only the content (`doc`, `draft`) waits for a realtime project. */ /** Larger messages are dropped: the editor then sends none and viewers read the canvas from the API after each save. */ @@ -28,19 +32,16 @@ const readHolder = (v: string | null) => { }; export function registerLiveRoutes(r: Router) { - /** - * The live socket of a canvas (`?holder=`): the editor when this window holds the lock, else a viewer. - * `409` when the project watches its canvases every 5 seconds instead. - */ + /** The live socket of a lockable file (`?holder=`): the editor when this window holds the lock, else a viewer. */ r.on("GET", "/api/canvases/:id/live", async (ctx, { id }) => { const { env, request, url, tenant } = ctx; if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") throw new HttpError(426, "websocket upgrade expected"); const f = await accessFile(ctx, assertUuid(id, "id"), "viewer"); if (!fileType(f.type)?.lockable) throw new HttpError(400, "only a file edited under a lock is watched live"); const holder = readHolder(url.searchParams.get("holder")); - const row = await env.DB.prepare("SELECT f.lock_by, f.lock_holder, f.lock_until, p.canvas_live FROM files f JOIN projects p ON p.id = f.project_id WHERE f.id = ?1") - .bind(f.id).first<{ lock_by: string | null; lock_holder: string | null; lock_until: string | null; canvas_live: string }>(); - if (row?.canvas_live !== "realtime") throw new HttpError(409, "this project's canvases are not watched in realtime"); + const row = await env.DB.prepare("SELECT lock_by, lock_holder, lock_until FROM files WHERE id = ?1") + .bind(f.id).first<{ lock_by: string | null; lock_holder: string | null; lock_until: string | null }>(); + if (!row) throw new HttpError(404, "file not found"); const editor = row.lock_by === tenant.userId && row.lock_holder === holder && !!row.lock_until && row.lock_until > new Date().toISOString(); const to = new URL(request.url); to.search = new URLSearchParams({ role: editor ? "editor" : "viewer", user: tenant.userId, holder }).toString(); @@ -48,12 +49,24 @@ export function registerLiveRoutes(r: Router) { }); } +/** + * Tells a file's room what changed outside it: the lock (who holds it now, and until when) or a save. Never fails + * the request that changed it: the room is a convenience, the database is the truth. + */ +export async function tellRoom(env: Env, fileId: string, msg: { type: "lock"; by: string | null; until: string | null } | { type: "saved" }) { + try { + await env.CANVAS_LIVE.get(env.CANVAS_LIVE.idFromName(fileId)).fetch(new Request("https://room/notify", { method: "POST", body: JSON.stringify({ file: fileId, ...msg }) })); + } catch (e) { console.warn("live: room not told", fileId, e); } +} + type Role = "editor" | "viewer"; interface Who { user: string; holder: string } export class CanvasRoom extends DurableObject { async fetch(request: Request): Promise { - const q = new URL(request.url).searchParams; + const url = new URL(request.url); + if (url.pathname === "/notify") return this.notify(await request.json()); + const q = url.searchParams; const role = q.get("role") === "editor" ? "editor" : "viewer"; const who: Who = { user: q.get("user") ?? "", holder: q.get("holder") ?? "" }; const { 0: client, 1: server } = new WebSocketPair(); @@ -63,8 +76,11 @@ export class CanvasRoom extends DurableObject { server.serializeAttachment(who); if (role === "editor") this.send("viewer", { type: "editor", by: who.user }); else { + // Who edits: the editor's socket, else the lock as the routes last told it (one taken without a socket: the device). const ed = this.open("editor")[0]; - server.send(JSON.stringify({ type: "editor", by: ed ? (ed.deserializeAttachment() as Who).user : null })); + const lock = await this.ctx.storage.get<{ by: string; until: string }>("lock"); + const held = lock && new Date(lock.until).getTime() > Date.now() ? lock.by : null; + server.send(JSON.stringify({ type: "editor", by: ed ? (ed.deserializeAttachment() as Who).user : held })); } return new Response(null, { status: 101, webSocket: client }); } @@ -89,6 +105,29 @@ export class CanvasRoom extends DurableObject { if (this.ctx.getTags(ws)[0] === "editor" && this.open("editor", ws).length === 0) this.send("viewer", { type: "editor", by: null }); } + /** From the lock routes and saves: every socket hears who edits now; a lock's end is watched with an alarm. */ + private async notify(m: { file: string; type: string; by?: string | null; until?: string | null }): Promise { + if (m.type === "saved") { this.sendAll({ type: "saved" }); return new Response(null, { status: 204 }); } + await this.ctx.storage.put("file", m.file); + this.sendAll({ type: "editor", by: m.by ?? null }); + if (m.by && m.until) { await this.ctx.storage.put("lock", { by: m.by, until: m.until }); await this.ctx.storage.setAlarm(new Date(m.until).getTime() + 1000); } + else { await this.ctx.storage.delete("lock"); await this.ctx.storage.deleteAlarm(); } + return new Response(null, { status: 204 }); + } + + /** The lock's end passed: unless it was renewed, it ran out, and everyone hears it is free. */ + async alarm() { + const file = await this.ctx.storage.get("file"); + if (!file) return; + const row = await this.env.DB.prepare("SELECT lock_by, lock_until FROM files WHERE id = ?1").bind(file).first<{ lock_by: string | null; lock_until: string | null }>(); + const until = row?.lock_until ? new Date(row.lock_until).getTime() : 0; + if (row?.lock_by && until > Date.now()) { await this.ctx.storage.setAlarm(until + 1000); return; } + await this.ctx.storage.delete("lock"); + this.sendAll({ type: "editor", by: null }); + } + + private sendAll(msg: unknown) { this.send("viewer", msg); this.send("editor", msg); } + async webSocketError(ws: WebSocket) { await this.webSocketClose(ws, 1011); } diff --git a/apps/worker/test/routes/canvas.test.ts b/apps/worker/test/routes/canvas.test.ts index 431dba9..618ef8f 100644 --- a/apps/worker/test/routes/canvas.test.ts +++ b/apps/worker/test/routes/canvas.test.ts @@ -112,10 +112,29 @@ describe("live updates", () => { viewer.send(JSON.stringify({ type: "doc", body: { forged: true }, base: null })); editor.send(JSON.stringify({ type: "draft", draft: null })); await new Promise((r) => setTimeout(r, 200)); - expect(inbox).toEqual([{ type: "editor", by: null }, { type: "editor", by: u.id }, { type: "doc", body, base: null }, { type: "draft", draft: null }]); + // The lock was taken before the viewer came: it hears who holds it at once (#426). + expect(inbox).toEqual([{ type: "editor", by: u.id }, { type: "editor", by: u.id }, { type: "doc", body, base: null }, { type: "draft", draft: null }]); editor.close(1000); viewer.close(1000); + // A project that watches the content every 5 seconds still gets the lock live. await ok(api(u.token, "PUT", `/api/projects/${project}`, { name: `P ${project}`, canvas_live: "gradual" })); - expect((await live("wviewer000001")).status).toBe(409); + expect((await live("wviewer000002")).status).toBe(101); + }); + + test("the lock is live without an editor's socket: taken, saved and let go reach every watcher (#426)", async () => { + await newProject(); + const c = uuid(); + const body = { surface: { kind: "blank", aspect: 1.5, color: 0 }, objects: [], frames: [], picture: null, linkCentres: true, comments: [] }; + await put(c, { type: "canvas", project_id: project, body }, 201); + const inbox: unknown[] = []; + const viewer = (await api(u.token, "GET", `/api/canvases/${c}/live?holder=wviewer000003`, undefined, { Upgrade: "websocket" })).webSocket!; + viewer.accept(); + viewer.addEventListener("message", (e) => { inbox.push(JSON.parse(String(e.data))); }); + await ok(api(u.token, "POST", `/api/files/${c}/lock`, { holder: "wdevice000001" })); + await ok(api(u.token, "PUT", `/api/files/${c}`, { body }, { "x-lock-holder": "wdevice000001" })); + expect((await api(u.token, "DELETE", `/api/files/${c}/lock?holder=wdevice000001`)).status).toBe(204); + await new Promise((r) => setTimeout(r, 200)); + expect(inbox).toEqual([{ type: "editor", by: null }, { type: "editor", by: u.id }, { type: "saved" }, { type: "editor", by: null }]); + viewer.close(1000); }); }); diff --git a/docs/api.md b/docs/api.md index b8d7f2e..4b6db2f 100644 --- a/docs/api.md +++ b/docs/api.md @@ -86,7 +86,7 @@ A new project starts with the default properties in its Settings folder (`PUT /a | --- | --- | --- | | POST | `/api/files/:id/lock` | `{ holder }` (the editing window's token) → `{ lock: { by, until } }`: taken when free, run out or this window's; renewed the same way (it holds 60 s). `423` with `lock` when someone else holds it. Lockable types only (a canvas) | | DELETE | `/api/files/:id/lock?holder=` | Lets go; only the holder's call changes anything. `204` | -| GET | `/api/canvases/:id/live?holder=` | WebSocket (`426` without the upgrade) to the file's `CanvasRoom` (`live.ts`; any lockable file: canvas, shot, timeline, else `400`): the editor when the window `holder` holds the lock, else a viewer (viewer access is enough). `409` when the project's `canvas_live` is `gradual`. Editor sends `doc { body, base?, refs? }`, `draft { draft }`, `saved`, `held`; viewers get those and `editor { by }` (a user id or null). Other messages, and anything a viewer sends, are dropped | +| GET | `/api/canvases/:id/live?holder=` | WebSocket (`426` without the upgrade) to the file's `CanvasRoom` (`live.ts`; any lockable file: canvas, shot, timeline, else `400`): the editor when the window `holder` holds the lock, else a viewer (viewer access is enough), in every project (#426; `canvas_live` only decides whether clients stream the content). Editor sends `doc { body, base?, refs? }`, `draft { draft }`, `saved`, `held`; viewers get those and `editor { by }` (a user id or null). The room also hears the lock routes (taken, renewed, let go: `editor` to every socket, and to a viewer that joins), every save of the file (`saved`), and the lock running out (an alarm at its end: `editor { by: null }`). Other messages, and anything a viewer sends, are dropped | | PUT | `/api/canvases/:id/render`, `/thumbnail` | The body is the image (PNG, JPEG, WebP; 12 MB and 600 KB). Replaces the one stored | | GET | `/api/web?to=` | The bearer session (the phone's) as the cookie of the same session, and a `302` to that path of this site (for the Studio in the phone's web view). `400` for a path that is not of this site or without a bearer token | | GET | `/api/canvases/:id/image?size=render\|thumbnail` | Default `render`. An ETag; with `?v=` (the file's `updated_at`) cached for good, else revalidated. `404` until made | diff --git a/docs/features/canvas.md b/docs/features/canvas.md index 0bb8a1e..d771d57 100644 --- a/docs/features/canvas.md +++ b/docs/features/canvas.md @@ -46,7 +46,8 @@ One window per canvas (`#/canvas/`), opened from Files (double-click), made - **Saving**: automatic, 0.7 s after the last change, with the body and its references (base and placed); then the render (2048 px on the long side) and the thumbnail (400 px) are drawn in the browser (`canvas/render.ts`, the editor's geometry on a 2D canvas) and uploaded. The status bar says Changed, Saving…, Saved or Not saved. Pen strokes keep a point every few pixels and coordinates are rounded to four decimals, so a body stays small. - **Undo and redo** (Ctrl+Z, Ctrl+Shift+Z or Ctrl+Y): the window's own history of bodies, a drag being one step, up to 100. - **The lock, editing and watching**: the window takes the lock when it opens (its own token, so a second window of the same person is someone else), renews it every 20 s and lets it go when it closes. **Stop editing** (in the toolbar) saves, lets the lock go and keeps the window open as a viewer. A viewer shows the canvas read-only: zoom, pan, view modes and Compare work; the tools, the Layers and Frames panels, undo, redo and Snap cannot be used and look disabled (muted text, dashed controls); comments can be read, opened on the canvas and listed, but not written, answered or resolved with who edits it, **Edit** (when nobody does: takes the lock and starts from the canvas as the server has it now). A viewer never takes the lock on its own: watching the Studio while drawing on the tablet stays that way. -- **Live updates** (Project, General, "Canvases while someone edits them"; `projects.canvas_live`): **Realtime** or **Every 5 seconds**. Every 5 seconds: a viewer reads the canvas again (`GET /api/files/:id`) every 5 s while its page is shown; it sees each save and when the lock is let go. Realtime (`apps/worker/src/live.ts`): every window of the canvas opens a live socket (`GET /api/canvases/:id/live`) to one Durable Object per canvas, `CanvasRoom` (the same room serves every lockable file: shots and timelines send their body and references, `lock.ts` in the Studio); the window that holds the lock is its editor, every other one a viewer. The editor sends the canvas after each change and the stroke or box being drawn, at most every 120 ms; viewers show both at once, and who edits (also when the editor leaves). Nothing is stored in the room: saves still go to D1 under the lock. A canvas over 1 MB of JSON is not sent whole: viewers read it again after each save. A viewer whose socket dropped reads every 5 s until it is back (it retries every 3 s). The status bar says "live" while the socket is open. +- **Who edits is always live** (#426): in every project, every window of a lockable file (canvas, shot, timeline, flow; the device's Flows editor too) opens its room's socket (`GET /api/canvases/:id/live`). The lock routes tell the room when the lock is taken, renewed or let go, every save of the file tells it `saved`, and an alarm at the lock's end says when it ran out; a viewer that joins hears who holds it at once. So a window shows at once who edits, that it is free (and reads the last save), and every save, without a reload. +- **Live content** (Project, General, "Canvases while someone edits them"; `projects.canvas_live`): **Realtime** or **Every 5 seconds**. Every 5 seconds: no content streams; a viewer reads the file again after each save (the room's `saved`) and every 5 s while its socket is down. Realtime (`apps/worker/src/live.ts`): every window of the canvas opens a live socket (`GET /api/canvases/:id/live`) to one Durable Object per canvas, `CanvasRoom` (the same room serves every lockable file: shots and timelines send their body and references, `lock.ts` in the Studio); the window that holds the lock is its editor, every other one a viewer. The editor sends the canvas after each change and the stroke or box being drawn, at most every 120 ms; viewers show both at once, and who edits (also when the editor leaves). Nothing is stored in the room: saves still go to D1 under the lock. A canvas over 1 MB of JSON is not sent whole: viewers read it again after each save. A viewer whose socket dropped reads every 5 s until it is back (it retries every 3 s). The status bar says "live" while the socket is open. - Thumbnails of canvases show in Files once a canvas was saved. A canvas with a picture has its thumbnail cropped to the picture (Crop); the render is always the whole surface. ## On the phone and the tablet diff --git a/docs/features/flows.md b/docs/features/flows.md index 9d09177..40dcad0 100644 --- a/docs/features/flows.md +++ b/docs/features/flows.md @@ -41,7 +41,7 @@ The app **Flows** (one window for the project's flows): the list of flows in a p The app **Flows** (a tab like any other while the project has the extension on), with its own **native editor** (#426: no web view; the device that edits or runs a flow is the one connected to the lights, often without a connection to the server): - **The project's flows** (`store.ts`): kept on the device (`flows.v1`), so they open, change and play offline. **New flow** works offline too. A row says when a change is not on the server yet; **Run** (online, saved flows) runs it on the device that holds the connections, as the Studio's Run on device. -- **Saving** (`store.ts`): every change is kept on the device at once (`flowEdits.v1`) and sent about a second later, or with the next sync. While online the editor holds the **edit lock** (renewed every 30 s) and saves under it; when someone else holds it, the flow is read-only on the device and shows their saves. Offline it edits freely. When the server's flow changed meanwhile, or was deleted, the device's version is saved **beside it as a copy** ("… (from this device)"): nothing made on the device is lost, nothing made elsewhere is overwritten. A change the server refuses stays on the device with the reason, and is tried again after the next change. +- **Saving** (`store.ts`): every change is kept on the device at once (`flowEdits.v1`) and sent about a second later, or with the next sync. While online the editor holds the **edit lock** (renewed every 30 s) and saves under it; when someone else holds it, the flow is read-only on the device and shows their saves. Offline it edits freely. It also joins the file's live room: when the lock is let go or runs out it takes it at once, and while someone else edits, each of their saves is read at once. When the server's flow changed meanwhile, or was deleted, the device's version is saved **beside it as a copy** ("… (from this device)"): nothing made on the device is lost, nothing made elsewhere is overwritten. A change the server refuses stays on the device with the reason, and is tried again after the next change. - **The editor** (`ui/Editor.tsx`, `ui/Lanes.tsx`, `ui/Inspect.tsx`; the editing rules shared with the Studio in `packages/ext-flows/src/edit.ts`): the ruler (tap: the playhead), the marker strip and one lane per track, with the track labels beside them. Under the bar, the same two **Size** boxes as in the Studio (width 1× to 32× with Fit; track height with Fit). **View** (an eye in the bar) has the Studio's switches: intensity graph (a light's keyframes sit at their level on the line, and dragging one up or down sets its intensity, shown while dragging), light colour (a dot filled with what the light shows there), value labels, effect and power badges; and the keyframe size, small for a pen, large for a finger. All of it is kept on this device (`flows.view.v1`). The drawing rules are shared with the Studio (`packages/ext-flows/src/look.ts`). **Select** or **Insert** mode: in Insert a tap on a lane adds a keyframe (with the intensity the track has there) and a tap on the strip a marker. A keyframe is tapped to choose it and dragged sideways to move it; the strip between two keyframes chooses the fade. What is chosen opens in a sheet: a light's keyframe (power, intensity, white or colour, effect, dimming curve), a camera's keyframe (the catalogue controls), the fade (jump or fade, curve, run by the light or in steps), a marker (name, where, a range), a track (name, the device it drives, muted, colour, delete). **Add a track** lists the light and camera models. The flow's name, length and loop are in its settings sheet. - **Play and Live on this device**: the shared player through this device's own connections; **Hold the connections here** switches the proxy on when it is off. Live (on by default) shows the flow at the playhead on the lights while stopped and follows every edit; recording on a camera starts only while playing. - **The run** (`run.ts`, kept from the first app's `sequenceRun.ts`): the proxy phone fetches the named revision (asked again a few times while the server still has the previous one), plays it with the shared player through its own connections, reports its state, and keeps playing when the Studio closes. A banner shows it with **Stop**, here and in the Studio. It stops when the proxy lets go of its connections: the proxy switched off, or a pairing taking the radio.