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(pty): paint a co-attaching client's terminal from the current screen
enese977b2ec5f7f
diff --git a/docs/team-presence.md b/docs/team-presence.mdindex b2aa8346d..240c0cd23 100644--- a/docs/team-presence.md+++ b/docs/team-presence.md@@ -180,6 +180,32 @@ Changes:terminal. An empty/failed capture keeps the client desynced and is retried with backoff(250 ms → 10 s cap). `pty:resync` payloads are therefore guaranteed non-empty.+### Painting the joiner++A joining client gets `fresh:false`, which is what tells the renderer *not* to replay the persisted+scrollback (tmux is live; a replay would duplicate it). But co-attach adds **no tmux client** — the+session already has one — so nothing redraws for the joiner either, *unless* the join happens to+resize the pty: tmux repaints on SIGWINCH, and only a joiner strictly **smaller** than the current+grid causes one. **Equal is the expected case** (both clients render the node's persisted geometry+with the same font; canvas zoom is a CSS transform and does not change `clientWidth`), and equal or+larger resizes nothing. Left alone, the headline path of the feature — open the same terminal in a+second client — lands on a **blank but live** terminal until the next byte of output, nondeterministically+(a ±1-cell measurement difference between two machines silently hides the bug).++So a join that did **not** resize the pty carries the session's **current screen** on+`PtyCreateResult.screen`, captured with the same `captureForResync` (`tmux capture-pane -e`) the+drop-and-redraw path uses; the renderer writes it into its empty xterm before the live stream starts.+Three rules:++- It rides the **create result**, not a `pty:resync` event: the renderer only subscribes to a+ session's channels *after* `create()` resolves, so an event pushed at join time would land on no+ listener.+- A join that **did** resize gets nothing — tmux is already painting it, and two paints would splice+ two different points in time onto one screen.+- An **empty capture is omitted**, never sent as `''` (same contract as `pty:resync`). A solo user+ never reaches this path at all: a fresh spawn has nothing to paint, and a warm reattach starts a+ tmux client, which redraws by itself.+### Typing attribution — and why it is server-side`cast()` currently discards the sender (`platform-server.ts:136`, `void uiId`). We route@@ -535,10 +561,10 @@ sees no change) is the one that must never regress.- **Cursor traffic** is 20 Hz × peers: comfortable for a 5–10 person team, not for a public room.- **Plain-shell (no tmux) co-attach shows a joiner a blank-but-live terminal** until the next outputarrives (pressing Enter paints it). A joiner gets `fresh:false`, so it skips the cold-restore- replay, and with no tmux there is no client to redraw the screen for it either. Named in the code- (`src/core/pty-manager.ts:594`); a join-time repaint needs a new `PtyCreateResult` field plus- renderer replay, i.e. a cross-surface contract change. A plain-shell session has no cross-client- continuity to inherit anyway — that is what "no tmux = no persistence" already means everywhere.+ replay, and with no tmux there is nothing to capture its current screen from either. With tmux —+ i.e. every normal install — the joiner IS painted: the create result carries the screen (see+ [Painting the joiner](#painting-the-joiner)). A plain-shell session has no cross-client continuity+ to inherit anyway; that is what "no tmux = no persistence" already means everywhere else.- **A deleted node can still be resurrected across a core restart.** The respawn guard is twolayers: the `pty:closed` event (subscribers only) and the in-memory `tombstones` map (everyoneelse, for as long as the core process lives). Restart the core — the Server Edition process, thediff --git a/src/core/pty-coattach.test.ts b/src/core/pty-coattach.test.tsindex 0de9bc762..715d25f75 100644--- a/src/core/pty-coattach.test.ts+++ b/src/core/pty-coattach.test.ts@@ -796,6 +796,93 @@ describe('node recycled (worktree move) while co-viewed', () => {})})+// ── A joiner's screen has to be PAINTED ───────────────────────────────────────────────────────+// A co-attaching client gets `fresh:false` (no cold-restore replay) and joins an existing tmux+// client, so the ONLY thing that could paint its empty xterm is a tmux redraw — and tmux only+// redraws on SIGWINCH, i.e. when the join actually RESIZES the pty. A joiner whose grid is EQUAL+// (the expected case: same persisted node geometry, same font) or LARGER resizes nothing, so it+// would stare at a blank-but-live terminal until the next byte of output. The join therefore+// carries the CURRENT SCREEN, captured from tmux — the same bytes the drop-and-redraw path uses.+describe('a joiner is painted from the current screen', () => {+ let fake: FakePlatform++ beforeEach(() => {+ spawned.length = 0+ failNextSpawn = false+ fake = fakePlatform()+ initPlatform(fake)+ vi.useFakeTimers()+ })+ afterEach(() => {+ vi.useRealTimers()+ resetPlatformForTests()+ })++ async function manager() {+ const { PtyManager } = await import('./pty-manager')+ const m = new PtyManager()+ m.registerIpc()+ return m+ }+ const create = (clientId: number, cols = 80, rows = 24, persistKey = 'node-1') =>+ fake.handlers[IPC.ptyCreate](clientId, { cols, rows, persistKey }) as Promise<{+ sessionId: string+ fresh: boolean+ screen?: string+ }>++ it('paints a joiner whose grid EQUALS the pty (nothing is resized, so tmux never redraws)', async () => {+ const m = await manager()+ const capture = vi.spyOn(m, 'captureForResync').mockResolvedValue('$ ls\r\nREADME.md')+ const a = await create(ALICE, 80, 24)++ const b = await create(BOB, 80, 24)+ expect(b.sessionId).toBe(a.sessionId)+ expect(spawned[0].resizes).toEqual([]) // equal grids → no SIGWINCH → no tmux redraw+ expect(capture).toHaveBeenCalledWith(a.sessionId)+ expect(b.screen).toBe('$ ls\r\nREADME.md') // …so the screen rides the create result instead+ })++ it('paints a joiner BIGGER than the pty (it letterboxes; the pty is not resized)', async () => {+ const m = await manager()+ vi.spyOn(m, 'captureForResync').mockResolvedValue('current screen')+ await create(ALICE, 80, 24)++ const b = await create(BOB, 120, 40)+ expect(spawned[0].resizes).toEqual([])+ expect(b.screen).toBe('current screen')+ })++ it('does NOT paint a joiner that shrinks the pty — tmux redraws it, and two paints would splice', async () => {+ const m = await manager()+ const capture = vi.spyOn(m, 'captureForResync').mockResolvedValue('current screen')+ await create(ALICE, 120, 40)++ const b = await create(BOB, 80, 24) // strictly smaller → the pty resizes → tmux redraws+ expect(spawned[0].resizes.at(-1)).toEqual({ cols: 80, rows: 24 })+ expect(capture).not.toHaveBeenCalled()+ expect(b.screen).toBeUndefined()+ })++ it('never paints a SOLO user: a fresh spawn has nothing to paint, and a reattach gets tmux own redraw', async () => {+ const m = await manager()+ const capture = vi.spyOn(m, 'captureForResync').mockResolvedValue('current screen')+ const a = await create(ALICE, 80, 24)+ expect(a.screen).toBeUndefined()+ expect(capture).not.toHaveBeenCalled()+ })++ it('omits the screen when the capture comes back empty (plain shell / tmux unavailable)', async () => {+ const m = await manager()+ vi.spyOn(m, 'captureForResync').mockResolvedValue('')+ await create(ALICE, 80, 24)++ const b = await create(BOB, 80, 24)+ expect(b.screen).toBeUndefined() // never an empty payload — the renderer would reset for nothing+ expect(b.fresh).toBe(false)+ })+})+describe('tmuxAttachFlags', () => {it("keeps -D for the app's own client: exactly ONE tmux client per session", async () => {const { tmuxAttachFlags } = await import('./pty-manager')diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex db22da7b5..8dfa0b224 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -567,13 +567,33 @@ export class PtyManager {/*** Subscribe `clientId` to the live session for this node id, if there is one. Returns the* create() result (`fresh:false` — the renderer joined a live session: no cold-restore- * scrollback replay, no agent resume; tmux redraws instead), or undefined if none exists.+ * scrollback replay, no agent resume), or undefined if none exists.+ *+ * WHAT PAINTS THE JOINER'S SCREEN. Its xterm is brand-new and empty, and `fresh:false` has just+ * told it to skip the scrollback replay. The only other thing that could paint it is a tmux+ * redraw — and tmux redraws on SIGWINCH, i.e. only when `applySize` below actually RESIZES the+ * pty, which happens only for a joiner strictly SMALLER than the current grid. Equal is the+ * EXPECTED case (the node's persisted geometry and the font settings are the same on both+ * clients, and canvas zoom is a CSS transform that doesn't change `clientWidth`), and equal or+ * larger resizes nothing — so the headline path of the whole feature, "open the same terminal in+ * a second client", would land on a blank-but-live terminal until the next byte of output.+ *+ * So a join that did NOT resize carries the current screen (`PtyCreateResult.screen`), captured+ * from tmux with the same `captureForResync` the drop-and-redraw path already uses. It rides the+ * create RESULT rather than a `pty:resync` event on purpose: the renderer only subscribes to this+ * session's channels AFTER create() resolves, so an event pushed here would land on no listener.+ * A join that DID resize gets nothing — tmux paints it, and two paints would splice two different+ * points in time onto one screen.+ *+ * The capture is skipped entirely (not just discarded) when the pty resized, so the solo paths+ * pay nothing: a solo user never reaches `join` at all (a fresh spawn has nothing to paint, and a+ * warm reattach spawns a tmux client, which redraws by itself).*/private join(clientId: ClientId,options: PtyCreateOptions,persistKey: string- ): PtyCreateResult | undefined {+ ): Promise<PtyCreateResult> | undefined {const existingId = this.byPersistKey.get(persistKey)const existing = existingId ? this.sessions.get(existingId) : undefinedif (!existingId || !existing) return undefined@@ -584,25 +604,27 @@ export class PtyManager {const size = normalizeSize(options.cols, options.rows)existing.sizes.set(clientId, size)existing.shown.set(clientId, size)+ const before = existing.appliedSizethis.applySize(existingId, existing)+ const resized =+ before?.cols !== existing.appliedSize?.cols || before?.rows !== existing.appliedSize?.rows// A (re)joining client's backlog is empty by definition, so its fresh page will never issue a// resume its PREVIOUS page owed us — a renderer reload keeps the same ClientId, so without this// the reloaded terminal would stay frozen forever with no data arriving to unstick it. Return// only THIS client's owed pause: a pause owed by a DIFFERENT client that is still here and// still drowning stays in place (invariant (b) on `pausedBy`).this.releaseFlow(existing, clientId)- // KNOWN GAP — plain-shell (tmux disabled / unavailable) co-attach: `fresh:false` makes the- // renderer skip the cold-restore scrollback replay, and with no tmux there is no client to- // redraw the screen either, so this joiner sees a blank-but-live terminal until the next- // output arrives (typing Enter paints it). Not fixed here on purpose: the renderer only- // subscribes to `pty:data:<id>` AFTER create() resolves, so a join-time repaint cannot be- // pushed on the wire — it needs a new field on PtyCreateResult plus renderer replay, i.e. a- // cross-surface contract change that belongs with the per-client backlog work (Task 5), not- // in a bugfix. A plain-shell session has no cross-client continuity to inherit anyway (it is- // exactly what "no tmux = no persistence" already means everywhere else in this file).- return existing.accountFallback+ const base: PtyCreateResult = existing.accountFallback? { sessionId: existingId, fresh: false, accountFallback: true }: { sessionId: existingId, fresh: false }+ if (resized) return Promise.resolve(base) // tmux is redrawing this client — do not paint twice+ // An empty capture (plain shell — no tmux to capture; a tmux/ssh blip) is OMITTED, never sent+ // as '': the renderer must not reset a terminal for nothing. A plain-shell joiner therefore+ // still lands on a blank-but-live screen — there is no source of truth for its past output,+ // which is exactly what "no tmux = no continuity" already means everywhere else here.+ return this.captureForResync(existingId)+ .catch(() => '')+ .then((screen) => (screen ? { ...base, screen } : base))}/** Spawn a brand-new session for this client (the non-co-attach path). */diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 9af615ab3..fcc777032 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -664,7 +664,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNaccountId: data.accountId,sshRemote})- .then(async ({ sessionId: sid, fresh, accountFallback: fellBack, closed }) => {+ .then(async ({ sessionId: sid, fresh, accountFallback: fellBack, closed, screen }) => {// REFUSED: core's tombstone says another client deleted this node while we weren't// subscribed (our project was closed/inactive, so no `pty:closed` could reach us). Nothing// was spawned — land in the same "closed by <name>" state a subscribed co-viewer gets.@@ -738,6 +738,13 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNterm.write('\r\n\x1b[90m── session restarted by another user (moved to a new folder) ──\x1b[0m\r\n')+ // CO-ATTACH: we joined a session somebody else already has open, so this xterm is empty and+ // nothing else will fill it — `fresh:false` skips the scrollback replay, and tmux only+ // redraws when the join actually resized the pty (i.e. when we are the new smallest client).+ // The create result carries the current screen for exactly the case where it did not, so+ // write it: the terminal opens on what our teammate is looking at, not on a blank rectangle.+ // Guarded like a resync (never paint an empty capture); no reset — the buffer IS empty.+ if (shouldApplyResync(screen)) term.write(toXtermText(screen as string))// We fell so far behind that the server discarded our queued output and redrew us from// tmux. The capture IS the current screen, so reset the emulator and write it — writing it// on top of a stale buffer would splice two different points in time. An EMPTY payload isdiff --git a/src/shared/types.ts b/src/shared/types.tsindex 1012d8927..62333d501 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -44,6 +44,23 @@ export interface PtyCreateResult {/** Set when the node's `accountId` had no config dir at spawn, so the session fell back to the* system account. The renderer flags the account chip (folder-missing warning) when true. */accountFallback?: boolean+ /**+ * The CURRENT SCREEN of a session this create JOINED (co-attach), captured from tmux — write it+ * into the fresh xterm before the live stream starts.+ *+ * Only a co-attaching client ever gets it, and only when the join left the pty's grid unchanged.+ * A joiner is `fresh:false`, so it skips the cold-restore scrollback replay; the only other thing+ * that could paint its empty terminal is a tmux redraw, and tmux only redraws on SIGWINCH — i.e.+ * when the joiner is strictly SMALLER and actually resizes the pty. Equal (the expected case: the+ * node's persisted geometry and the font settings are the same on both clients) or larger resizes+ * nothing, so without this the second viewer would sit on a blank-but-live terminal until the next+ * byte of output. When the join DOES resize, this is deliberately absent: tmux paints it, and+ * painting twice would splice two points in time.+ *+ * Guaranteed non-empty when present (an empty/failed capture is omitted, exactly like `pty:resync`+ * — a plain-shell session has no tmux to capture and simply gets nothing).+ */+ screen?: string/*** REFUSED: this node's session was permanently destroyed by ANOTHER client, so nothing was* spawned (`sessionId` is empty) — the terminal shows the "closed by <name>" state instead.