Skip to content

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.

fix(watch-link): no capture sends no keyframe; stop never mints; a join without a size is refused

review0bc99cde7f56
diff --git a/src/core/relay/relay-trust.ts b/src/core/relay/relay-trust.ts
index 29879c1f4..5ce39f2b0 100644
--- a/src/core/relay/relay-trust.ts
+++ b/src/core/relay/relay-trust.ts
@@ -26,12 +26,14 @@
// its own `onTunnel` — so a confirm arriving on session A's tunnel is physically unable to reach
// session B's state, and `recordApproval` can only ever pin the key bound into the state it is given.
//
-// LOCAL confirms have exactly five call sites, three on the HOST side and two on the CLIENT side.
+// LOCAL confirms have exactly six call sites, four on the HOST side and two on the CLIENT side.
// Host side: `confirmHere()` from the desktop's Team Access dialog (`relay:host:confirm`), the host's
-// `autoApprove` for a key its pin store holds (the hosted team's `team.json`), and a hosted owner's
-// `relay:hosted:approve`. Client side: the joining human's `relay:client:confirm`, and the client's
-// `autoApprove` for a hosted team's approved bookmark (src/main/remote/hosted-join.ts). A sixth is a
-// design change.
+// `autoApprove` for a key its pin store holds (the hosted team's `team.json`), a hosted owner's
+// `relay:hosted:approve`, and a live link's `autoApprove` for the ONE viewer key derived from that
+// link's own secret, read from the host's own link record (src/core/watch-link/link-host.ts; any
+// other key is denied at once, never asked). Client side: the joining human's
+// `relay:client:confirm`, and the client's `autoApprove` for a hosted team's approved bookmark
+// (src/main/remote/hosted-join.ts). A seventh is a design change.
import {
confirmLocal,
confirmRemote,
diff --git a/src/core/watch-link/capture-route.test.ts b/src/core/watch-link/capture-route.test.ts
index 1ee480437..0fdac7fad 100644
--- a/src/core/watch-link/capture-route.test.ts
+++ b/src/core/watch-link/capture-route.test.ts
@@ -122,8 +122,14 @@ describe('parseVisibleCapture', () => {
})
describe('unavailableCapture', () => {
- it('is an empty screen with nothing known', () => {
- expect(unavailableCapture()).toEqual({ screen: '', cursor: null })
+ it('is NO capture: flagged, with an empty screen and nothing known', () => {
+ expect(unavailableCapture()).toEqual({ screen: '', cursor: null, unavailable: true })
+ })
+
+ it('a real capture of an empty pane is not "no capture" (R36): it carries no flag', () => {
+ expect(parseVisibleCapture('0 0\n')).toEqual({ screen: '', cursor: { x: 0, y: 0 } })
+ expect(parseVisibleCapture('')).toEqual({ screen: '', cursor: null })
+ expect('unavailable' in parseVisibleCapture('\n\n0 0\n')).toBe(false)
})
it('is a fresh object each time (a caller may mutate what it was handed)', () => {
diff --git a/src/core/watch-link/capture-route.ts b/src/core/watch-link/capture-route.ts
index dd2b223a3..df3574e08 100644
--- a/src/core/watch-link/capture-route.ts
+++ b/src/core/watch-link/capture-route.ts
@@ -41,11 +41,18 @@ export interface VisibleCapture {
screen: string
/** The pane's cursor at capture time, 0-based (`#{cursor_x}`, `#{cursor_y}`); null when unread. */
cursor: { x: number; y: number } | null
+ /**
+ * There is NO capture: the backend has no visible-only one, or the capture failed. Set only by
+ * `unavailableCapture()`; a real capture of an empty pane never carries it. The difference matters
+ * (controller ruling R36): a viewer paints a keyframe as reset + clear, so an empty keyframe sent for
+ * "no capture" would erase everything the stream had drawn. The link host sends no keyframe for it.
+ */
+ unavailable?: true
}
-/** A session with no visible-only capture, or one that failed: an empty screen, nothing known. */
+/** A session with no visible-only capture, or one that failed: nothing to paint, nothing known. */
export function unavailableCapture(): VisibleCapture {
- return { screen: '', cursor: null }
+ return { screen: '', cursor: null, unavailable: true }
}
export function visibleCaptureRoute(
diff --git a/src/core/watch-link/chat-cast.guard.test.ts b/src/core/watch-link/chat-cast.guard.test.ts
index 2ea6293eb..2a0069e6f 100644
--- a/src/core/watch-link/chat-cast.guard.test.ts
+++ b/src/core/watch-link/chat-cast.guard.test.ts
@@ -6,18 +6,22 @@
// Viewer link's refusal would no longer be the only door.
//
// So this names every file allowed to mention the cast, and fails on any other, with its reason. The
-// event of the same name (`WATCH_EVENT.chat`, host → viewer) is written only through the link host too.
+// event of the same name (`WATCH_EVENT.chat`, host → viewer) is the same string, so a handler
+// registered under it would be the same door: it is matched too, and only the link host writes it.
import { describe, expect, it } from 'vitest'
import { readFileSync, readdirSync, statSync } from 'node:fs'
import { join, relative } from 'node:path'
const SRC = join(__dirname, '..', '..')
+/** The cast, the event of the same string, or the string itself. */
+const MENTIONS = /WATCH_CHAT_CAST|WATCH_EVENT\s*\.\s*chat\b|WATCH_EVENT\s*\[\s*['"`]chat['"`]\s*\]|['"`]watch:chat['"`]/
+
const ALLOWED: Record<string, string> = {
'shared/watch-link/protocol.ts': 'defines the cast and the event',
'shared/watch-link/client.ts': "the viewer's browser client sends the cast",
'core/watch-link/watcher-policy.ts': 'admits the cast for a Commenter link only',
- 'core/watch-link/link-host.ts': "answers the cast on the link's own relay session"
+ 'core/watch-link/link-host.ts': "answers the cast on the link's own relay session, and sends the event"
}
function sources(dir: string, out: string[] = []): string[] {
@@ -36,15 +40,30 @@ describe('the watch:chat cast', () => {
for (const file of sources(SRC)) {
const rel = relative(SRC, file).replace(/\\/g, '/')
const text = readFileSync(file, 'utf8').replace(/\r\n/g, '\n')
- if (/WATCH_CHAT_CAST|['"`]watch:chat['"`]/.test(text) && !(rel in ALLOWED)) offenders.push(rel)
+ if (MENTIONS.test(text) && !(rel in ALLOWED)) offenders.push(rel)
}
expect(offenders).toEqual([])
})
+ it('matches every spelling of it', () => {
+ for (const text of [
+ 'WATCH_CHAT_CAST',
+ 'WATCH_EVENT.chat',
+ 'WATCH_EVENT .chat',
+ "WATCH_EVENT['chat']",
+ "'watch:chat'",
+ '"watch:chat"',
+ '`watch:chat`'
+ ]) {
+ expect(MENTIONS.test(text), text).toBe(true)
+ }
+ for (const text of ["'watchLink:chat'", 'WATCH_EVENT.chatty', "'watch:chat-history'"]) expect(MENTIONS.test(text), text).toBe(false)
+ })
+
it('every allowlisted file still exists and still mentions it (a stale entry is a hole)', () => {
for (const rel of Object.keys(ALLOWED)) {
const text = readFileSync(join(SRC, rel), 'utf8')
- expect(/WATCH_CHAT_CAST|['"`]watch:chat['"`]/.test(text), rel).toBe(true)
+ expect(MENTIONS.test(text), rel).toBe(true)
}
})
})
diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.ts
index 41e36b59f..60f9d8844 100644
--- a/src/core/watch-link/link-host.test.ts
+++ b/src/core/watch-link/link-host.test.ts
@@ -29,7 +29,7 @@ import {
type WatchPty
} from './link-host'
import type { HostTokenResult } from './api'
-import type { VisibleCapture } from './capture-route'
+import { unavailableCapture, type VisibleCapture } from './capture-route'
import type { WatchLinkRecord } from './store'
import type { UiSink } from '../ui-sink-registry'
@@ -200,6 +200,13 @@ async function openViewer(t: Setup, n = 0): Promise<Viewer> {
await vi.waitFor(() => expect(v.keyframes().length).toBeGreaterThanOrEqual(1))
return v
}
+/** Open the n-th listener's viewer and wait for its meta (a no-capture backend sends no keyframe). */
+async function openViewerMeta(t: Setup, n = 0): Promise<Viewer> {
+ await vi.waitFor(() => expect(t.peers.length).toBeGreaterThan(n))
+ const v = viewer(t.peers[n], t.keys)
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.meta).length).toBeGreaterThanOrEqual(1))
+ return v
+}
const pty = (sink: UiSink, sid: string, data: string): void => sink.sendBinary(encodePtyData(sid, data))
const ptyEvent = (sink: UiSink, channel: string, ...args: unknown[]): void =>
sink.sendText(JSON.stringify({ t: 'ev', channel, args }))
@@ -244,7 +251,7 @@ describe('createLinkHost — a viewer session', () => {
})
})
- it('a keyframe of a backend with no visible capture is an empty screen, and altScreen follows the join', async () => {
+ it("a REAL capture of an empty screen still sends a keyframe with screen '' (R36), and altScreen follows the join", async () => {
const t = setup({
join: () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: false }),
capture: () => ({ screen: '', cursor: null })
@@ -415,7 +422,7 @@ describe('createLinkHost — joining, waiting, rejoining', () => {
await clock.flush()
}
await exitCurrent()
- const expected = [2_000, 4_000, 8_000, 15_000, 30_000, 30_000]
+ const expected = [2_000, 4_000, 8_000, 15_000, 15_000, 15_000]
for (const d of expected) {
await clock.advance(d)
await exitCurrent()
@@ -423,7 +430,7 @@ describe('createLinkHost — joining, waiting, rejoining', () => {
const deltas = t.joinTimes.slice(1).map((x, i) => x - t.joinTimes[i])
expect(deltas).toEqual(expected)
// This one stays up for REJOIN_STABLE_MS from its join keyframe: the backoff resets.
- await clock.advance(30_000)
+ await clock.advance(15_000)
await vi.waitFor(() => expect(v.keyframes().map((k) => k.sessionId)).toContain(`s${n}`))
await clock.advance(REJOIN_STABLE_MS)
ptyEvent(sink, IPC.ptyExit(`s${n}`), 0)
@@ -433,7 +440,7 @@ describe('createLinkHost — joining, waiting, rejoining', () => {
expect(t.joinTimes).toHaveLength(before + 1)
})
- it('a join that throws is "waiting" and backs off; a capture that throws is an empty keyframe', async () => {
+ it('a join that throws is "waiting" and backs off; a capture that throws sends NO keyframe and the viewer streams (R36)', async () => {
const clock = manualClock()
let fail = true
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
@@ -453,8 +460,35 @@ describe('createLinkHost — joining, waiting, rejoining', () => {
await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
fail = false
await clock.advance(REJOIN_BACKOFF_MS[0])
- await vi.waitFor(() => expect(v.keyframes()).toHaveLength(1))
- expect(v.keyframes()[0]).toEqual({ sessionId: 's1', screen: '', altScreen: true })
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.meta)).toHaveLength(1))
+ await clock.flush()
+ expect(v.keyframes()).toEqual([])
+ pty(t.sink(), 's1', `${ESC}[Hstreams`)
+ expect(v.log.pty).toEqual([`${ESC}[Hstreams`])
+ expect(warn).toHaveBeenCalled()
+ })
+
+ it('a join answering no valid size is REFUSED — left, waiting, retried — never given a guessed size', async () => {
+ const clock = manualClock()
+ let size = { cols: 0, rows: 24 }
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const t = setup({ clock, join: () => ({ sessionId: 's1', ...size, altScreen: true }) })
+ t.host.start()
+ await vi.waitFor(() => expect(t.peers).toHaveLength(1))
+ const v = viewer(t.peers[0], t.keys)
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.waiting)).toHaveLength(1))
+ expect(v.named(WATCH_EVENT.meta)).toEqual([])
+ expect(t.left).toEqual([`s1/${t.host.viewers()[0].viewerId}`])
+ expect(t.calls).not.toContain('capture:s1')
+ for (const bad of [{ cols: 80, rows: Number.NaN }, { cols: 80.5, rows: 24 }, { cols: -1, rows: 24 }]) {
+ size = bad
+ await clock.advance(60_000)
+ }
+ expect(v.named(WATCH_EVENT.meta)).toEqual([])
+ size = { cols: 132, rows: 40 }
+ await clock.advance(60_000)
+ await vi.waitFor(() => expect(v.named(WATCH_EVENT.meta)).toHaveLength(1))
+ expect(v.named(WATCH_EVENT.meta)[0]).toMatchObject({ cols: 132, rows: 40 })
expect(warn).toHaveBeenCalled()
})
@@ -628,6 +662,69 @@ describe('createLinkHost — keyframes and the stream', () => {
expect(v.log.pty).toEqual([])
})
+ it('a backend with NO visible capture never gets a watch:keyframe — join, 2 s bound, settle follow-up, throttle — and keeps streaming (R36)', async () => {
+ const clock = manualClock()
+ let buffered = 0
+ const t = setup({ clock, capture: () => unavailableCapture(), buffered: () => buffered })
+ t.host.start()
+ const v = await openViewerMeta(t)
+ await clock.flush()
+ const captures = () => t.calls.filter((c) => c === 'capture:s1').length
+ expect(captures()).toBe(1)
+ expect(v.keyframes()).toEqual([])
+ const sink = t.sink()
+ pty(sink, 's1', 'lost') // mid-stream: swallowed until the first escape
+ await clock.advance(SETTLE_BOUND_MS) // the 2 s bound: a capture, nothing sent
+ expect(captures()).toBe(2)
+ expect(v.keyframes()).toEqual([])
+ pty(sink, 's1', `${ESC}[Ha`) // settles; streaming, with no keyframe ever sent
+ expect(v.log.pty).toEqual([`${ESC}[Ha`])
+ await clock.advance(1_000) // the settle follow-up: a capture, nothing sent, still streaming
+ expect(captures()).toBe(3)
+ pty(sink, 's1', 'b')
+ // Throttled: dropped while over budget, then streaming RESUMES without a keyframe.
+ buffered = 600 * 1024
+ pty(sink, 's1', 'dropped')
+ buffered = 0
+ pty(sink, 's1', 'still-dropped')
+ await clock.advance(1_000)
+ expect(captures()).toBe(4)
+ pty(sink, 's1', 'resumed')
+ expect(v.log.pty).toEqual([`${ESC}[Ha`, 'b', 'resumed'])
+ expect(v.keyframes()).toEqual([])
+ expect(v.log.events.map((e) => e[0]).filter((c) => c === WATCH_EVENT.keyframe)).toEqual([])
+ })
+
+ it('a FAILED capture on a capture-capable backend sends no keyframe, and the stream resumes (R36)', async () => {
+ const clock = manualClock()
+ let buffered = 0
+ let fail = false
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const t = setup({
+ clock,
+ buffered: () => buffered,
+ capture: () => {
+ if (fail) throw new Error('ssh: master gone')
+ return { screen: 'SCREEN', cursor: null }
+ }
+ })
+ t.host.start()
+ const v = await openViewer(t)
+ const sink = t.sink()
+ fail = true
+ pty(sink, 's1', `${ESC}[H`) // settles: the follow-up capture fails
+ await clock.advance(1_000)
+ expect(v.keyframes()).toHaveLength(1)
+ pty(sink, 's1', 'a')
+ buffered = 600 * 1024
+ pty(sink, 's1', 'dropped') // throttled; its repaint capture fails too
+ buffered = 0
+ await clock.advance(1_000)
+ pty(sink, 's1', 'b')
+ expect(v.keyframes()).toHaveLength(1)
+ expect(v.log.pty).toEqual([`${ESC}[H`, 'a', 'b'])
+ })
+
it("one capture per session is shared by the link's viewers joining it together (R27)", async () => {
const clock = manualClock()
const releases: ((c: VisibleCapture) => void)[] = []
@@ -790,9 +887,37 @@ describe('createLinkHost — ending', () => {
expect(status).toHaveBeenCalledTimes(1)
expect(t.gone).toEqual([])
state = 'revoked'
+ // On a FULL link any viewer ending while the scheduler still runs would re-mint a listener: the
+ // revoke's stop must end them only after the scheduler stopped (F1, R37).
+ const minted = t.mints()
await clock.advance(FULL_STATUS_POLL_MS)
expect(status).toHaveBeenCalledTimes(2)
expect(t.gone).toEqual(['revoked'])
for (const v of vs) expect(v.named(WATCH_EVENT.end)).toEqual([{ reason: 'revoked' }])
+ await clock.advance(60_000)
+ expect(t.mints()).toBe(minted)
+ expect(t.peers).toHaveLength(MAX_VIEWERS_PER_LINK)
+ })
+
+ it('stop on a full link with a viewer over 8 MiB behind mints nothing; that viewer is closed without an end (R37)', async () => {
+ const clock = manualClock()
+ const buffered: number[] = []
+ const t = setup({ clock, buffered: (i) => buffered[i] ?? 0 })
+ t.host.start()
+ const vs: Viewer[] = []
+ for (let i = 0; i < MAX_VIEWERS_PER_LINK; i++) vs.push(await openViewer(t, i))
+ await clock.flush()
+ const minted = t.mints()
+ buffered[3] = 9 * 1024 * 1024
+ t.host.stop('revoked')
+ await clock.advance(60_000)
+ expect(t.mints()).toBe(minted)
+ expect(vs[3].named(WATCH_EVENT.end)).toEqual([])
+ await vi.waitFor(() => expect(vs[3].log.closed).toBe(1))
+ vs.forEach((v, i) => {
+ if (i !== 3) expect(v.named(WATCH_EVENT.end)).toEqual([{ reason: 'revoked' }])
+ })
+ expect(t.sinks.size).toBe(0)
+ expect(t.left).toHaveLength(MAX_VIEWERS_PER_LINK)
})
})
diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.ts
index cc6f5bd83..fab64367e 100644
--- a/src/core/watch-link/link-host.ts
+++ b/src/core/watch-link/link-host.ts
@@ -33,6 +33,13 @@
// keyframe needs a capture STARTED after it asked. A per-viewer sequence makes sure an older result
// is never painted after a newer one, and streaming resumes only on the newest.
//
+// NO CAPTURE IS NOT AN EMPTY SCREEN (R36). A backend with no visible-only capture (the Windows session
+// host, a direct Windows pty, a plain shell) and a capture that failed answer `unavailable`, and then
+// NO keyframe is sent: the viewer paints a keyframe as reset + clear, so an empty one would erase what
+// the stream had drawn. The viewer follows the stream instead (at the join it still gets meta), and a
+// throttled viewer resumes streaming without a repaint. Residual: on such a backend a throttled
+// viewer shows gaps until the application repaints them.
+//
// SIZE. A viewer never sizes anything. Its meta carries the joined session's CURRENT size (R25). A
// watcher's OWN tmux client (spawned when no owner Session is held) attaches with `ignore-size`, but
// tmux honours that only while some client WITHOUT the flag is attached to the server (measured,
@@ -98,8 +105,9 @@ export const FULL_STATUS_POLL_MS = 5 * 60_000
export const CHAT_MIN_INTERVAL_MS = 2_000
export const CHAT_HISTORY_MAX = 200
export const KEYFRAME_MIN_INTERVAL_MS = 1_000
-/** Rejoin delays, by attempt. The last repeats (R26: an instant-exit loop climbs to the 30 s cap). */
-export const REJOIN_BACKOFF_MS = [2_000, 4_000, 8_000, 15_000, 30_000]
+/** Rejoin delays, by attempt. The last repeats: an instant-exit loop climbs to 15 s (R26, R35), and a
+ * viewer waiting for a terminal to start sees it within 15 s. */
+export const REJOIN_BACKOFF_MS = [2_000, 4_000, 8_000, 15_000]
/** A joined session that stayed up this long (from its join keyframe) resets the rejoin backoff. */
export const REJOIN_STABLE_MS = 30_000
/** An unsettled mid-stream filter gets one more keyframe this long after the join (R23). */
@@ -206,12 +214,14 @@ interface Conn {
bucket: TokenBucket
/** The current session's mid-stream filter has left its unknown start state. */
settled: boolean
- /** Take one more keyframe when it does (it had not when the join keyframe was painted). */
+ /** Take one more keyframe when it does (it had not when the join keyframe was delivered). */
followUpOnSettle: boolean
- /** The current session's first keyframe was painted. */
- painted: boolean
+ /** The current session's first keyframe step is done: painted, or skipped because there was no
+ * capture (R36). From here the viewer streams. */
+ joinKeyframeDone: boolean
kfSeq: number
kfDelivered: number
+ /** When the last keyframe step was done (painted or skipped): keyframes and resumes are ≤ 1/s. */
lastKeyframeAt: number
keyframeTimer: unknown
settleTimer: unknown
@@ -229,16 +239,27 @@ interface CaptureSlot {
const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
+/** The session a join attached to, if it answered one (a refused join may still have attached). */
+function joinedSessionId(r: unknown): string | null {
+ const sid = r && typeof r === 'object' ? (r as { sessionId?: unknown }).sessionId : undefined
+ return typeof sid === 'string' && sid ? sid : null
+}
+
+/** A usable join, or null. A join without a valid size is REFUSED, never given a guessed one (R20, R37):
+ * a wiring slip then shows as "waiting", loudly, instead of a viewer laid out at a wrong size for the
+ * rest of the session (its join-time `pty:size` was already recorded as shown and is not resent). */
function normalizeJoin(r: unknown): WatchJoin | null {
- if (!r || typeof r !== 'object') return null
+ const sessionId = joinedSessionId(r)
+ if (sessionId === null) return null
const o = r as Partial<WatchJoin>
- if (typeof o.sessionId !== 'string' || !o.sessionId) return null
- const dim = (n: unknown, d: number): number => (Number.isInteger(n) && (n as number) > 0 ? (n as number) : d)
- return { sessionId: o.sessionId, cols: dim(o.cols, 80), rows: dim(o.rows, 24), altScreen: o.altScreen === true }
+ const dim = (n: unknown): boolean => Number.isInteger(n) && (n as number) > 0
+ if (!dim(o.cols) || !dim(o.rows)) return null
+ return { sessionId, cols: o.cols as number, rows: o.rows as number, altScreen: o.altScreen === true }
}
function normalizeCapture(c: unknown): VisibleCapture {
if (!c || typeof c !== 'object' || typeof (c as VisibleCapture).screen !== 'string') return unavailableCapture()
+ if ((c as VisibleCapture).unavailable === true) return unavailableCapture()
const cur = (c as VisibleCapture).cursor
const ok = !!cur && Number.isInteger(cur.x) && Number.isInteger(cur.y) && cur.x >= 0 && cur.y >= 0
return { screen: (c as VisibleCapture).screen, cursor: ok ? { x: cur!.x, y: cur!.y } : null }
@@ -301,6 +322,9 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
return true
}
function dropStalled(c: Conn): void {
+ // While stopping, the scheduler may still be running (the end notices go out first): closing now
+ // would re-mint a listener on a full link. `stop` closes every viewer a moment later anyway (R37).
+ if (stopped) return
warn(null, 'a viewer stopped draining its socket; closed it', `backlog over ${VIEWER_BACKLOG_CLOSE} bytes`)
c.session?.close()
ended(c)
@@ -417,19 +441,24 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
sessionOver(c)
return
}
- const kf: WatchKeyframe = {
- sessionId: sid,
- // A FRESH filter: the capture starts in ground state, and carries OSC 8 links verbatim (R9).
- screen: createStreamFilter().push(cap.screen),
- altScreen: c.altScreen,
- ...(cap.cursor ? { cursor: { x: cap.cursor.x, y: cap.cursor.y } } : {})
+ // No capture (R36): nothing is painted — an empty keyframe would erase what the stream drew — but
+ // the step still counts as done, so the viewer streams (it must not wait for a keyframe that never
+ // comes) and the next request waits out the minimum interval like a painted one.
+ if (!cap.unavailable) {
+ const kf: WatchKeyframe = {
+ sessionId: sid,
+ // A FRESH filter: the capture starts in ground state, and carries OSC 8 links verbatim (R9).
+ screen: createStreamFilter().push(cap.screen),
+ altScreen: c.altScreen,
+ ...(cap.cursor ? { cursor: { x: cap.cursor.x, y: cap.cursor.y } } : {})
+ }
+ if (!send(c, WATCH_EVENT.keyframe, kf)) return
}
- if (!send(c, WATCH_EVENT.keyframe, kf)) return
c.kfDelivered = seq
c.lastKeyframeAt = deps.now()
if (seq === c.kfSeq) c.streaming = true
- if (!c.painted) {
- c.painted = true
+ if (!c.joinKeyframeDone) {
+ c.joinKeyframeDone = true
c.followUpOnSettle = !c.settled
clearTimer(c.stableTimer)
c.stableTimer = deps.setTimeout(() => {
@@ -498,17 +527,20 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
c.joining = true
const clientId = c.clientId
let res: WatchJoin | null = null
+ let attached: string | null = null
try {
- res = normalizeJoin(await deps.pty.join(clientId, record.nodeId, c.viewerId))
+ const raw = await deps.pty.join(clientId, record.nodeId, c.viewerId)
+ attached = joinedSessionId(raw)
+ res = normalizeJoin(raw)
+ if (!res && attached !== null) warn(c, 'a join answered no valid size; refused', `session ${attached}`)
} catch (err) {
warn(c, 'joining the node session failed', errorText(err))
} finally {
c.joining = false
}
- if (c.ended || stopped) {
- if (res) leave(clientId, res.sessionId, c.viewerId, c)
- return
- }
+ // Refused, or this viewer went away meanwhile: never stay subscribed to what the join attached.
+ if (attached !== null && (!res || c.ended || stopped)) leave(clientId, attached, c.viewerId, c)
+ if (c.ended || stopped) return
// An exit that raced the join was delivered before this viewer knew its session id, and dropped.
if (res && !aliveOf(c, res.sessionId)) {
leave(clientId, res.sessionId, c.viewerId, c)
@@ -525,7 +557,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
c.sessionId = sid
c.altScreen = res.altScreen
c.streaming = false
- c.painted = false
+ c.joinKeyframeDone = false
c.settled = false
c.followUpOnSettle = false
c.waiting = false
@@ -653,7 +685,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
bucket: createTokenBucket({ ratePerSec: RATE, burst: BURST, now: deps.now }),
settled: false,
followUpOnSettle: false,
- painted: false,
+ joinKeyframeDone: false,
kfSeq: 0,
kfDelivered: 0,
lastKeyframeAt: -Infinity,