Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(canvas-authority): send an un-diffable outside edit whole, one log per failure streak (N5, N7, N6, D9)
review8a6dea704bf0
diff --git a/docs/hosted-team-relay.md b/docs/hosted-team-relay.mdindex 9b14e6149..b1d262c2f 100644--- a/docs/hosted-team-relay.md+++ b/docs/hosted-team-relay.md@@ -367,8 +367,10 @@ whole-workspace saves still write them.not yet written, through the store's atomic content write (`WorkspaceStore.writeProjectContent`: itbumps `rev` like a save, and the file is byte-identical to a save's apart from `rev` and `savedAt`).A failed write keeps every op and retries-after 1 s, 2 s, 4 s and so on, capped at 30 s. Both server shutdown paths write what is pending-before they exit, so a crash loses only what was not written yet: normally at most the last 5 s.+after 1 s, 2 s, 4 s and so on, capped at 30 s. The journal says so once when a failure streak+begins and once when a write lands again, not on every retry. Both server shutdown paths write what+is pending before they exit, so a crash loses only what was not written yet: normally at most the+last 5 s.Before the authority stops, the shutdown ends the browser connections and waits for the savesalready queued (`WorkspaceStore.idle`): a save that ran after the authority was detached would bewritten un-overlaid, over its final write.@@ -382,7 +384,10 @@ browser tabs are told the new governed set (`canvas:authority-changed`). A sharecannot be read stays governed, so its clients keep publishing, but the authority writes nothing forit and saves of it pass through unchanged until it can be read. The journal says so once:"[canvas-authority] project <id> is shared, but its content could not be read …". `team share` does-not check the id, so a shared id that is not a project on this core logs the same line.+not check the id, so a shared id that is not a project on this core logs the same line. When an+outside edit makes the file readable again (a pull that resolves conflict markers), the authority+adopts the edited file as its first baseline, so it has no difference to publish as ops: the project+is sent whole on `workspace:external-change` instead, as for an ungoverned project.**Publishing when alone.** A client normally casts nothing while no teammate is attached. On agoverned project that would lose every edit, so a client publishes whenever the project is governed:@@ -429,6 +434,11 @@ it is a new way to use it.- **Board edits reach only the active tab's core.** A client casts only to the core its active tabis on. An edit on the Omni board to a lane of a project on another core (a hosted lane while alocal tab is active, or the reverse) is not cast, so on a hosted core it is not written either.+- **Load-time repairs are not cast.** What a client derives while it loads a project (a missing+ `--after` dependency rope it heals, a legacy node migrated to its current shape) becomes that+ client's baseline and is never cast, so on a governed project it never reaches disk: every load+ derives it again. The repairs are deterministic, so this costs nothing visible, but a repair that+ must persist on a shared project has to be cast.- **The card modal's comments on a relay tab** (`BoardLogPanel`) still read and write the local core'sboard log, not the host's, because the modal renders outside the tab's session. This predates theauthority; it is a follow-up.diff --git a/src/core/canvas-authority.test.ts b/src/core/canvas-authority.test.tsindex d5019ea2f..fba9500e7 100644--- a/src/core/canvas-authority.test.ts+++ b/src/core/canvas-authority.test.ts@@ -177,7 +177,7 @@ describe('canvas authority — governing', () => {expect(byId(h.writes[1].content.nodes, 'a')?.position.x).toBe(7000)})- it('5. applies ops in the total order, including rule 4 (a stale frame cannot resurrect a delete)', async () => {+ it('5. applies ops in the total order, including the order\'s causal delete (a stale frame cannot resurrect a delete)', async () => {const h = harness({ disk: { P: content([at('a', 1), at('b', 1)]) } })h.authority.onReflected('P', { op: 'remove', id: 'a', seq: 5 })h.authority.onReflected('P', { op: 'upsert', node: at('a', 42), seq: 6, seen: 3 })@@ -190,7 +190,7 @@ describe('canvas authority — governing', () => {expect(byId(h.writes[0].content.nodes, 'b')?.position.x).toBe(10)})- it('5c. rule 4 holds for an edge: a stale re-upsert cannot bring back a removed link', async () => {+ it('5c. the causal delete holds for an edge: a stale re-upsert cannot bring back a removed link', async () => {const e1 = { id: 'e1', source: 'a', target: 'b' }const h = harness({ disk: { P: content([node('a'), node('b')], { bridges: [e1] }) } })h.authority.onReflected('P', { op: 'edge-remove', kind: 'bridge', id: 'e1', seq: 5 })@@ -201,7 +201,7 @@ describe('canvas authority — governing', () => {expect(h.writes[0].content.ropes).toEqual([])})- it('5d. rule 4 holds for a board column: a stale re-upsert cannot bring back a removed column', async () => {+ it('5d. the causal delete holds for a board column: a stale re-upsert cannot bring back a removed column', async () => {const c1 = { id: 'c1', title: 'One', color: '#fff' }const c2 = { id: 'c2', title: 'Two', color: '#fff' }const h = harness({ disk: { P: content([node('a')], { kanban: { columns: [c1, c2], assignments: [] } }) } })@@ -412,14 +412,15 @@ describe('canvas authority — outside edits', () => {await h.authority.overlayLoad(ws(project({ nodes: [node('a'), node('b')] })))h.cast({ op: 'upsert', node: node('c') })await settle()- const persisted = await h.authority.adoptOutsideEdit(+ const adopted = await h.authority.adoptOutsideEdit(project({name: 'Renamed',defaultPermissionMode: 'manual',nodes: [node('a', { shell: '/bin/zsh' }), node('d')]}))- expect(persisted).not.toBeNull()+ expect(adopted?.asOps).toBe(true)+ const persisted = adopted?.project// The non-content fields come from the edit: they are what a stale tab would otherwise revert.expect(persisted?.name).toBe('Renamed')expect(persisted?.defaultPermissionMode).toBe('manual')@@ -455,6 +456,35 @@ describe('canvas authority — outside edits', () => {})})+describe('canvas authority — an outside edit with no baseline to diff (N5)', () => {+ // A shared project whose file could not be read holds no state, so an edit that makes it readable+ // (a pull resolving conflict markers) adopts the edited file AS its baseline and has no difference+ // to publish. No op can carry it to a client, so it is answered as a WHOLE project to send.+ it('adopts it, publishes no op, and answers it as a whole project to send', async () => {+ const h = harness({ disk: {} })+ h.authority.sharedChanged()+ await settle()+ expect(h.logs).toHaveLength(1) // unreadable: said once+ h.disk.set('P', content([node('a'), node('b')]))+ const adopted = await h.authority.adoptOutsideEdit(project({ name: 'Fixed', nodes: [node('a'), node('b')] }))+ expect(h.published).toEqual([])+ expect(adopted?.asOps).toBe(false)+ expect(adopted?.project.name).toBe('Fixed')+ expect(ids(adopted?.project.nodes ?? [])).toEqual(['a', 'b'])+ expect(h.authority.adoptedIds()).toEqual(['P'])+ // From here on it is an ordinary governed project: the next edit is diffed.+ h.disk.set('P', content([node('a')]))+ const next = await h.authority.adoptOutsideEdit(project({ nodes: [node('a')] }))+ expect(next?.asOps).toBe(true)+ expect(h.published.map((x) => x.m)).toEqual([{ op: 'remove', id: 'b' }])+ })++ it('answers null when nothing adopted it (still unreadable), so the edit is sent as for an ungoverned project', async () => {+ const h = harness({ disk: {} })+ expect(await h.authority.adoptOutsideEdit(project({ nodes: [node('a')] }))).toBeNull()+ })+})+describe('canvas authority — exec stays out of the state (R9)', () => {it('a read that carries this machine\'s shell is stripped: never written, and a sanitized echo is a no-op', async () => {const h = harness({ disk: { P: content([node('a', { shell: '/bin/zsh' })]) } })@@ -506,6 +536,22 @@ describe('canvas authority — flushing and lifecycle', () => {expect(h.logs).toHaveLength(2) // one per failed write})+ // N7: a write that fails for good (the file is gone or unreadable) retried every 30 s and logged+ // every time, forever. One line when a failure streak starts, one when it ends.+ it('12b. logs a failing write once per failure streak, and once on recovery', async () => {+ const h = harness({ disk: { P: content([node('a')]) }, writeResults: [false, false, false, false, true, false, true] })+ h.cast({ op: 'upsert', node: node('b') })+ await h.clock.advanceTo(20_000) // fails at 1 s, 2 s, 4 s, 8 s; lands at 16 s+ expect(h.writes).toHaveLength(5)+ expect(h.logs.filter((l) => l.includes('failed'))).toHaveLength(1)+ expect(h.logs.filter((l) => l.includes('succeeded'))).toHaveLength(1)+ // A new streak says so again.+ h.cast({ op: 'upsert', node: node('c') })+ await h.clock.advance(10_000)+ expect(h.logs.filter((l) => l.includes('failed'))).toHaveLength(2)+ expect(h.logs.filter((l) => l.includes('succeeded'))).toHaveLength(2)+ })+it('13. unsharing flushes the pending state once, then releases the project', async () => {const h = harness({ disk: { P: content([node('a')]) } })h.cast({ op: 'upsert', node: node('b') })diff --git a/src/core/canvas-authority.ts b/src/core/canvas-authority.tsindex e54da5af2..bea3153a1 100644--- a/src/core/canvas-authority.ts+++ b/src/core/canvas-authority.ts@@ -32,7 +32,8 @@// edit, because disk has the edit and not them.//// 4. A FAILED READ GOVERNS NOTHING. A shared project whose content cannot be read keeps `governs`-// true (the clients must keep publishing), drops its ops, and says so once.+// true (the clients must keep publishing), drops its ops, and says so once. (Not to be confused+// with canvas-order's rule 4, the causal delete, which this module applies through its order.)//// One accepted exception to "content comes only from ops": a node too large to travel as an op// (over the byte cap every cast is held to) can only ever arrive in a save, so a save may contribute@@ -67,6 +68,18 @@ export interface CanvasAuthorityDeps {log?: (msg: string) => void}+/** What `adoptOutsideEdit` did with an edit it adopted. */+export interface AdoptedOutsideEdit {+ /** The project exactly as a load now returns it: the edit's own non-content fields, overlaid with+ * the authority's content. */+ project: Project+ /** true = the difference went out as ops, so what is left to send is the project's other fields+ * (`workspace:server-change`). false = there was no baseline to diff against (the file could not+ * be read before this edit), so no op carried it and the project must be sent whole+ * (`workspace:external-change`). */+ asOps: boolean+}+export interface CanvasAuthority {/** Is this project's content written by the authority? Shared and not stopped; true before the* project is first adopted, and true even when its content cannot be read. */@@ -83,10 +96,10 @@ export interface CanvasAuthority {/** Governed projects' content fields replaced by the authority's (the store's load hook). */overlayLoad(ws: Workspace): Promise<Workspace>/** A project re-read after an outside edit (a git pull, a hand edit): its content is adopted and- * the difference published as ops. Answers the project exactly as a load now returns it (the- * edit's own non-content fields, overlaid with the authority's content), for the shell to send to- * every client on `workspace:server-change`; null = nothing was adopted. */- adoptOutsideEdit(project: Project): Promise<Project | null>+ * the difference published as ops. Answers what is left for the shell to send (see+ * `AdoptedOutsideEdit`); null = nothing adopted it (not governed, or still unreadable), and it is+ * sent as for an ungoverned project. */+ adoptOutsideEdit(project: Project): Promise<AdoptedOutsideEdit | null>/** The shared set changed: flush and release what left it, adopt what joined it. */sharedChanged(): void/** Write every dirty project now. */@@ -112,8 +125,8 @@ interface Governed {* The order's own tag. EMPTY on purpose: the reflector strips every `src` that is not a ref id* (`stampMutation`), and `accept` compares with `m.src && m.src === src`, so no reflected op,* honest or forged, is ever taken for this authority's own echo (rule 2 in the header). It never- * calls `onLocal`, so for it the order is exactly "highest seq wins per key" plus rule 4's causal- * delete, the same verdicts every client reaches.+ * calls `onLocal`, so for it the order is exactly "highest seq wins per key" plus canvas-order's+ * causal delete (that module's rule 4), the same verdicts every client reaches.*/const AUTHORITY_ORDER_TAG = ''@@ -190,7 +203,8 @@ export function createCanvasAuthority(deps: CanvasAuthorityDeps): CanvasAuthoritconst isShared = (id: string): boolean => deps.sharedProjectIds().has(id)// `governs` asks only "shared, and not stopped", on purpose: a shared project whose content cannot// be read must still read as governed, so its clients keep publishing ops (rule 4). That includes a- // shared SSH project, which the authority never overlays (`overlayable`) and cannot read (the+ // shared SSH project: `governedIds()` lists it (every shared id, adopted or not), so its clients+ // publish for it, yet the authority never overlays it (`overlayable`) and cannot read it (the// store refuses SSH content), so its eager adoption logs once that its content could not be read.// Harmless: the Server Edition has no SSH-project manager, so it never opens an SSH project, and// such an entry can only come from a hand-copied index. Its saves pass through un-overlaid, which@@ -314,17 +328,24 @@ export function createCanvasAuthority(deps: CanvasAuthorityDeps): CanvasAuthoritg.flushing = nullif (ok) {g.unflushed.splice(0, written)+ // A failure streak said so once when it began (below); its end is said once too.+ if (g.attempt > 0) log(`writing project ${id} succeeded again, after ${g.attempt} attempt(s)`)g.attempt = 0// Anything applied while the write was in flight is still owed.if (g.dirty) schedule(id, g)else release(id, g)return}- // Rule 3: keep the content and every unflushed op, and try again later.+ // Rule 3: keep the content and every unflushed op, and try again later. Said ONCE per failure+ // streak: a file that is gone for good fails every retry, and a line every 30 s forever buries+ // the journal (the recovery is said once too, above).g.dirty = trueclearTimers(g)- const wait = retryMs(g.attempt++)- log(`writing project ${id} failed; its content is kept and the write is retried in ${wait} ms`)+ const wait = retryMs(g.attempt)+ if (g.attempt === 0) {+ log(`writing project ${id} failed; its content is kept and the write is retried (first in ${wait} ms, backing off to 30 s); nothing more is said until a write lands`)+ }+ g.attempt++if (!stopped) {g.retryTimer = setTimer(() => {g.retryTimer = null@@ -354,7 +375,9 @@ export function createCanvasAuthority(deps: CanvasAuthorityDeps): CanvasAuthorit// Its limits, which follow from it having no place in the total order:// (a) A STALE SAVE REVIVES A REMOVED BIG NODE. A client's save issued before that client// applied a `remove` of the node still carries it, and the save is not ordered against- // the remove, so the node is adopted back and written. The window is one save debounce.+ // the remove, so the node is adopted back and written, and it stays on disk until someone+ // removes it again (the window in which such a save can be issued is one save debounce;+ // the revival itself does not expire).// (b) AN OUTSIDE EDIT OF A BIG NODE REACHES NO CLIENT, AND THE NEXT SAVE UNDOES IT. The// published upsert is refused by the reflector (too large), so every client keeps its old// copy, and the next save from any of them re-adopts that copy: a git-pulled change to a@@ -423,8 +446,13 @@ export function createCanvasAuthority(deps: CanvasAuthorityDeps): CanvasAuthoritreturn { ...ws, projects }},- async adoptOutsideEdit(project: Project): Promise<Project | null> {+ async adoptOutsideEdit(project: Project): Promise<AdoptedOutsideEdit | null> {if (!overlayable(project) || !governs(project.id)) return null+ // The diff below is against a baseline HELD before this edit. Without one (the file could not+ // be read until now, or its first read is still in flight) the adoption reads the edited file+ // itself, so it finds no difference: no op can carry the edit, and it is answered for sending+ // whole (N5), rather than swallowed.+ const hadBaseline = governed.has(project.id)const g = await adopt(project.id)if (!g || !governs(project.id) || governed.get(project.id) !== g) return nullconst before = g.content@@ -439,8 +467,8 @@ export function createCanvasAuthority(deps: CanvasAuthorityDeps): CanvasAuthoritif (g.unflushed.length) markDirty(project.id, g)// The ops carry the content; the edit's OTHER fields (name, colour, icon, layouts, the// permission default, the capability flags, the board's github mapping) reach no client- // through them. Answered as a load would answer it, so the shell can send it whole.- return overlayProject(project, g, 'load')+ // through them. Answered as a load would answer it, so the shell can send it.+ return { project: overlayProject(project, g, 'load'), asOps: hadBaseline }},sharedChanged(): void {diff --git a/src/server/workspace-external-watch.test.ts b/src/server/workspace-external-watch.test.tsindex a126dd994..cf863bc47 100644--- a/src/server/workspace-external-watch.test.ts+++ b/src/server/workspace-external-watch.test.ts@@ -287,6 +287,26 @@ describe('Server Edition external workspace watcher', () => {}})+ // N5: an edit the authority could not turn into ops is still delivered — whole, on the channel the+ // ungoverned path uses — instead of being swallowed.+ it('routes by what the authority did: ops → server change; no baseline → whole project; nothing → as ungoverned', async () => {+ const external: Project[] = []+ const server: Project[] = []+ const p = { id: 'g', name: 'g', color: '#000', viewport: { x: 0, y: 0, zoom: 1 }, nodes: [] } as Project+ const persisted = { ...p, name: 'persisted' }+ for (const answer of [{ project: persisted, asOps: true }, { project: persisted, asOps: false }, null]) {+ const route = outsideEditPublisher(+ () => ({ governs: () => true, adoptOutsideEdit: async () => answer }),+ (x) => external.push(x),+ (x) => server.push(x)+ )+ route(p)+ await new Promise((r) => setImmediate(r))+ }+ expect(server).toEqual([persisted])+ expect(external).toEqual([persisted, p])+ })+it('with no authority (another server owns this data dir), every outside edit is broadcast', () => {const sent: Project[] = []const route = outsideEditPublisher(() => null, (p) => sent.push(p), () => {diff --git a/src/server/workspace-external-watch.ts b/src/server/workspace-external-watch.tsindex dbb16722e..9311183c8 100644--- a/src/server/workspace-external-watch.ts+++ b/src/server/workspace-external-watch.ts@@ -63,6 +63,15 @@ export function createServerWorkspaceWatcher(* those fields are security-relevant (a pull that drops a `bypassPermissions` default or turns a* capability off must not be undone by the next autosave). The ops go out first, so a client* merging the project already holds its content.+ *+ * An edit the authority could not turn into ops is NOT swallowed (N5). With no baseline held before+ * it (the file was unreadable until this edit, say a pull that resolved conflict markers) the+ * adoption reads the edited file itself and finds no difference, so the project goes out WHOLE on+ * `workspace:external-change`, as for an ungoverned project: the clients hold content the authority+ * never saw, so only the whole project can bring them up to date, and that channel reloads a clean+ * canvas. Its conflict bar is safe here: the project is adopted now, so a "Keep mine" save is+ * overlaid and cannot write stale content back. When nothing adopted it at all (still unreadable, or+ * no longer governed), the raw project goes out exactly as for an ungoverned one.*/export function outsideEditPublisher(authority: () => Pick<CanvasAuthority, 'governs' | 'adoptOutsideEdit'> | null,@@ -74,8 +83,10 @@ export function outsideEditPublisher(if (a?.governs(project.id)) {void a.adoptOutsideEdit(project)- .then((persisted) => {- if (persisted) serverChange(persisted)+ .then((adopted) => {+ if (!adopted) broadcast(project)+ else if (adopted.asOps) serverChange(adopted.project)+ else broadcast(adopted.project)}).catch((error: unknown) => {console.warn('[nodeterm-server] the canvas authority could not adopt an outside edit', error)