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(live-links): password change loses control like every other path; input hardening

reviewe1b6842a5da0
diff --git a/src/core/watch-link/control-input.test.ts b/src/core/watch-link/control-input.test.ts
index 8c6a2d34c..9aaa4fa2b 100644
--- a/src/core/watch-link/control-input.test.ts
+++ b/src/core/watch-link/control-input.test.ts
@@ -92,6 +92,41 @@ describe('createInputSplitter', () => {
expect(s.push('[A')).toEqual([keys('[A')])
})
+ it('drain() hands over only what a key press can end on (Esc, Alt+[); a longer marker prefix waits for the next input', () => {
+ const s = createInputSplitter()
+ expect(s.push(`${ESC}[`)).toEqual([])
+ expect(s.drain()).toEqual([keys(`${ESC}[`)])
+ for (const prefix of [`${ESC}[2`, `${ESC}[20`, `${ESC}[200`]) {
+ expect(s.push(`a${prefix}`)).toEqual([keys('a')])
+ expect(s.drain()).toEqual([])
+ // The rest of the marker, a whole batch later: still a paste.
+ expect(s.push(`${PASTE_START.slice(prefix.length)}hi${PASTE_END}`)).toEqual([paste('hi')])
+ }
+ // A held prefix that the next input does not complete comes out then, as keys.
+ expect(s.push(`${ESC}[20`)).toEqual([])
+ expect(s.drain()).toEqual([])
+ expect(s.push('x')).toEqual([keys(`${ESC}[20x`)])
+ })
+
+ it('drain() never hands over a held high surrogate (no key press ends on half a character)', () => {
+ const s = createInputSplitter()
+ expect(s.push('a\ud83d')).toEqual([keys('a')])
+ expect(s.drain()).toEqual([])
+ expect(s.push('\ude42')).toEqual([keys('\ud83d\ude42')])
+ })
+
+ it('pasteOpen() tells whether a paste is waiting for its end', () => {
+ const s = createInputSplitter()
+ expect(s.pasteOpen()).toBe(false)
+ s.push(`${PASTE_START}x`)
+ expect(s.pasteOpen()).toBe(true)
+ s.push(PASTE_END)
+ expect(s.pasteOpen()).toBe(false)
+ s.push(`${PASTE_START}x`)
+ s.reset()
+ expect(s.pasteOpen()).toBe(false)
+ })
+
it('drain() inside a paste hands over nothing: an open paste waits for its end', () => {
const s = createInputSplitter()
expect(s.push(`${PASTE_START}abc${ESC}[20`)).toEqual([])
@@ -165,6 +200,24 @@ describe('createInputSplitter', () => {
expect(s.push(`rm -rf /\n${PASTE_END}y`)).toEqual([keys('y')])
})
+ it('discard() keeps a start-marker prefix it ends on: completed by the next input, that paste is discarded whole', () => {
+ const s = createInputSplitter()
+ for (const prefix of [ESC, `${ESC}[`, `${ESC}[2`, `${ESC}[20`, `${ESC}[200`]) {
+ s.discard(`dropped${prefix}`)
+ expect(s.drain()).toEqual([]) // a dropped byte is never handed over
+ expect(s.push(`${PASTE_START.slice(prefix.length)}rm -rf ~\n${PASTE_END}ok`)).toEqual([keys('ok')])
+ }
+ // Not completed: the dropped prefix is dropped, the rest is keys.
+ s.discard(`dropped${ESC}[2`)
+ expect(s.push('x')).toEqual([keys('x')])
+ // Extended a character at a time by tiny casts: still the dropped paste's start.
+ s.discard(`dropped${ESC}`)
+ expect(s.push('[')).toEqual([])
+ expect(s.drain()).toEqual([])
+ expect(s.push('2')).toEqual([])
+ expect(s.push(`00~evil${PASTE_END}ok`)).toEqual([keys('ok')])
+ })
+
it('discard() drops keys, and a held prefix with them', () => {
const s = createInputSplitter()
expect(s.push(`a${ESC}`)).toEqual([keys('a')])
diff --git a/src/core/watch-link/control-input.ts b/src/core/watch-link/control-input.ts
index 2c4acb45e..13e57c422 100644
--- a/src/core/watch-link/control-input.ts
+++ b/src/core/watch-link/control-input.ts
@@ -12,18 +12,24 @@
//
// Four rules beyond "find the markers":
// - A trailing PREFIX of the marker being looked for is held until the next push. A lone Esc is such
-// a prefix, and so is Alt+[ (`ESC [`): `drain()` hands a held prefix over as keys, and the host
-// calls it when it flushes a batch, so an Esc reaches the pane within one batch instead of waiting
-// for the next key (an agent CLI's "Esc to interrupt" must not need a second key).
-// - A trailing high surrogate outside a paste is held the same way, so an emoji split across two
-// casts is not typed as two replacement characters.
+// a prefix, and so is Alt+[ (`ESC [`) — the only two a single key press can end on — so `drain()`
+// hands exactly those over as keys, and the host calls it when it flushes a batch: an Esc reaches
+// the pane within one batch instead of waiting for the next key (an agent CLI's "Esc to interrupt"
+// must not need a second key). A longer prefix (`ESC [ 2`, `ESC [ 2 0`, `ESC [ 2 0 0`) is no key: it
+// stays held for the next input, so a start marker split across two casts with a batch flush in
+// between is still a paste. Residual: one split right after `ESC` or `ESC [` that waits longer than
+// a batch interval for its second cast is typed as keys (the same bytes, unframed by tmux).
+// - A trailing high surrogate outside a paste is held the same way (and never drained: no key ends on
+// half a character), so an emoji split across two casts is not typed as two replacement characters.
// - A paste is cut at PASTE_MAX units (never between the halves of a surrogate pair); the rest up to
// its end is discarded, and the splitter keeps looking for the end, so typing after it is keys.
// - Input the host DROPPED (over budget, no session to type into) is fed to `discard()`, which keeps
// the framing and delivers nothing: a paste that any dropped part belonged to is discarded WHOLE.
// Without it a paste whose end marker was dropped would stay open for good and swallow every key
// typed after it, and a paste whose start was dropped would have its text typed as KEYS — each
-// newline a command run in the shell.
+// newline a command run in the shell. A dropped input that ENDS in a start-marker prefix keeps that
+// prefix, marked dropped: completed by the next input it opens a paste that is discarded whole;
+// not completed, it is dropped (never typed, never drained).
import type { ControlInputChunk } from './pane-input'
export const PASTE_START = '\x1b[200~'
@@ -38,12 +44,18 @@ export interface InputSplitter {
push(data: string): ControlInputChunk[]
/** Input that was dropped: tracked for framing, never delivered (see the header). */
discard(data: string): void
- /** A held marker prefix or surrogate, as keys (an open paste keeps waiting for its end). */
+ /** A held Esc or Alt+[ (`ESC [`) as keys — what a key press can end on. A longer marker prefix, a
+ * held surrogate, a prefix kept from dropped input and an open paste all keep waiting. */
drain(): ControlInputChunk[]
+ /** A paste is open, waiting for its end. */
+ pasteOpen(): boolean
/** Control lost or the connection ended: forget an open paste and anything held. */
reset(): void
}
+/** The held prefixes `drain()` hands over: a key press can end on these, never on a longer one. */
+const DRAINABLE = new Set(['\x1b', '\x1b['])
+
const isHighSurrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdbff
/** The length of the longest proper prefix of `marker` that `s` ends with. */
@@ -58,6 +70,8 @@ export function createInputSplitter(): InputSplitter {
let inPaste = false
/** The tail of the last push that may combine with the next one. */
let held = ''
+ /** `held` came from dropped input (a start-marker prefix `discard` kept): never keys. */
+ let heldDropped = false
let parts: string[] = []
let pasteLen = 0
/** The open paste reached PASTE_MAX: nothing more is appended. */
@@ -98,7 +112,10 @@ export function createInputSplitter(): InputSplitter {
/** One scan over `held + data`. `deliver` false: track the framing, deliver nothing. */
function scan(data: string, deliver: boolean): ControlInputChunk[] {
let s = held + data
+ // How many leading characters of `s` were dropped input (a prefix `discard` kept, outside a paste).
+ let droppedHead = heldDropped ? held.length : 0
held = ''
+ heldDropped = false
const out: ControlInputChunk[] = []
let keys = ''
const flushKeys = (): void => {
@@ -109,12 +126,33 @@ export function createInputSplitter(): InputSplitter {
while (s.length > 0) {
if (!inPaste) {
const i = s.indexOf(PASTE_START)
+ if (droppedHead > 0) {
+ const head = droppedHead
+ droppedHead = 0
+ if (i >= 0 && i < head) {
+ // A start marker that began in dropped input: the paste it opens is discarded whole.
+ openPaste()
+ poisoned = true
+ s = s.slice(i + PASTE_START.length)
+ continue
+ }
+ const h = heldMarkerPrefix(s, PASTE_START)
+ if (i < 0 && s.length - h < head) {
+ // The dropped prefix grew and is still only a prefix: held, still dropped.
+ held = s.slice(s.length - h)
+ heldDropped = true
+ break
+ }
+ s = s.slice(head) // dropped bytes are never keys
+ continue
+ }
if (i < 0) {
let h = heldMarkerPrefix(s, PASTE_START)
- if (h === 0 && isHighSurrogate(s.charCodeAt(s.length - 1))) h = 1
+ // A surrogate is held for accepted input only: dropped input keeps only a marker prefix.
+ if (deliver && h === 0 && isHighSurrogate(s.charCodeAt(s.length - 1))) h = 1
keys += s.slice(0, s.length - h)
- // Dropped input holds nothing back: what it held is dropped with it.
- if (deliver) held = s.slice(s.length - h)
+ held = s.slice(s.length - h)
+ heldDropped = !deliver && h > 0
break
}
keys += s.slice(0, i)
@@ -147,14 +185,16 @@ export function createInputSplitter(): InputSplitter {
scan(data, false)
},
drain() {
- if (inPaste || held.length === 0) return []
+ if (inPaste || heldDropped || !DRAINABLE.has(held)) return []
const data = held
held = ''
return [{ kind: 'keys', data }]
},
+ pasteOpen: () => inPaste,
reset() {
inPaste = false
held = ''
+ heldDropped = false
parts = []
pasteLen = 0
full = false
diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.ts
index d7f2f74ad..e659ee063 100644
--- a/src/core/watch-link/link-host.test.ts
+++ b/src/core/watch-link/link-host.test.ts
@@ -32,6 +32,7 @@ import {
DROPPED_NOTICE_MIN_MS,
INPUT_BATCH_MS,
INPUT_BURST,
+ INPUT_DELIVERY_TIMEOUT_MS,
INPUT_GRACE_MS,
INPUT_RATE,
TYPING_EVENT_MIN_MS,
@@ -1079,6 +1080,19 @@ function deferred<T>() {
return { promise, resolve }
}
const settleReal = (ms = 40): Promise<void> => new Promise((r) => setTimeout(r, ms))
+/** A pane delivery whose FIRST call waits for `release()` (true); every later call answers true. */
+function holdFirst() {
+ const held = deferred<boolean>()
+ let first = true
+ return {
+ input: (): Promise<boolean> | boolean => {
+ if (!first) return true
+ first = false
+ return held.promise
+ },
+ release: () => held.resolve(true)
+ }
+}
// A Control link: unlocking with the link's password, the host-side throttles and the lock. The
// password check is the real scrypt one (`verifyControlPassword` against `record.control`, read at
@@ -1782,14 +1796,9 @@ describe('createLinkHost — control', () => {
})
it("two controllers' batches arrive whole and in flush order", async () => {
- const held = deferred<boolean>()
- let first = true
+ const held = holdFirst()
const { t, clock, vs } = await controllers(['Ada', 'Bob'], {
- input: () => {
- if (!first) return true
- first = false
- return held.promise
- }
+ input: held.input
})
await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, clock)
await clock.advance(INPUT_BATCH_MS)
@@ -1798,19 +1807,14 @@ describe('createLinkHost — control', () => {
await clock.advance(INPUT_BATCH_MS)
// Bob's batch waits behind Ada's, whose first chunk is still in the pane.
expect(delivered(t)).toEqual(['s1:keys:a'])
- held.resolve(true)
+ held.release()
await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:paste:P', 's1:keys:b', 's1:keys:z']))
})
it('one controller types on while its previous batch is still in the pane: its input waits, then goes as one batch', async () => {
- const held = deferred<boolean>()
- let first = true
+ const held = holdFirst()
const { t, clock, vs } = await controllers(['Ada'], {
- input: () => {
- if (!first) return true
- first = false
- return held.promise
- }
+ input: held.input
})
await type(vs[0], 'a', clock)
await clock.advance(INPUT_BATCH_MS)
@@ -1820,7 +1824,7 @@ describe('createLinkHost — control', () => {
await clock.advance(INPUT_BATCH_MS)
}
expect(delivered(t)).toEqual(['s1:keys:a'])
- held.resolve(true)
+ held.release()
await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:bcd']))
})
@@ -1839,14 +1843,9 @@ describe('createLinkHost — control', () => {
})
it('a batch already queued behind another is not delivered once its sender lost control', async () => {
- const held = deferred<boolean>()
- let first = true
+ const held = holdFirst()
const { t, clock, vs } = await controllers(['Ada', 'Bob'], {
- input: () => {
- if (!first) return true
- first = false
- return held.promise
- }
+ input: held.input
})
await type(vs[0], 'a', clock)
await clock.advance(INPUT_BATCH_MS)
@@ -1854,21 +1853,16 @@ describe('createLinkHost — control', () => {
await type(vs[1], 'z', clock)
await clock.advance(INPUT_BATCH_MS)
expect(await ask(vs[1], () => vs[1].c.release())).toEqual({ state: 'available' })
- held.resolve(true)
+ held.release()
await clock.flush()
await settleReal()
expect(delivered(t)).toEqual(['s1:keys:a'])
})
it('a batch queued from before a release is not delivered after the same viewer unlocks again', async () => {
- const held = deferred<boolean>()
- let first = true
+ const held = holdFirst()
const { t, clock, vs } = await controllers(['Ada', 'Bob'], {
- input: () => {
- if (!first) return true
- first = false
- return held.promise
- }
+ input: held.input
})
await type(vs[0], 'a', clock)
await clock.advance(INPUT_BATCH_MS)
@@ -1878,7 +1872,7 @@ describe('createLinkHost — control', () => {
expect(await ask(vs[1], () => vs[1].c.release())).toEqual({ state: 'available' })
await clock.advance(UNLOCK_MIN_INTERVAL_MS)
expect(await unlock(vs[1], 'Bob', PW)).toEqual({ state: 'controlling' })
- held.resolve(true)
+ held.release()
await type(vs[1], 'new', clock)
await clock.advance(INPUT_BATCH_MS)
await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:new']))
@@ -1887,16 +1881,11 @@ describe('createLinkHost — control', () => {
})
it('a batch already in the chain whose session ended is not typed into the next session', async () => {
- const held = deferred<boolean>()
- let first = true
+ const held = holdFirst()
let n = 0
const { t, clock, vs } = await controllers(['Ada'], {
join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }),
- input: () => {
- if (!first) return true
- first = false
- return held.promise
- }
+ input: held.input
})
await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, clock)
await clock.advance(INPUT_BATCH_MS)
@@ -1905,7 +1894,7 @@ describe('createLinkHost — control', () => {
await clock.flush()
await clock.advance(REJOIN_BACKOFF_MS[0])
await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))
- held.resolve(true)
+ held.release()
await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
expect(delivered(t)).toEqual(['s1:keys:a'])
})
@@ -1921,6 +1910,8 @@ describe('createLinkHost — control', () => {
await type(vs[0], `second half${PASTE_END}ok`, clock)
await clock.advance(INPUT_BATCH_MS)
await vi.waitFor(() => expect(delivered(t)).toEqual(['s2:keys:ok']))
+ // The pending batch was empty (the paste had not ended), and the paste was still lost: told.
+ expect(dropped(vs[0])).toHaveLength(1)
})
it('in-flight input after a release is dropped silently; 5.1 s later it is a breach', async () => {
@@ -2132,14 +2123,9 @@ describe('createLinkHost — control', () => {
})
it('while the panes have not taken its last batch, a controller collects at most INPUT_BURST more; past it, dropped', async () => {
- const held = deferred<boolean>()
- let first = true
+ const held = holdFirst()
const { t, clock, vs } = await controllers(['Ada'], {
- input: () => {
- if (!first) return true
- first = false
- return held.promise
- }
+ input: held.input
})
await type(vs[0], 'a', clock)
await clock.advance(INPUT_BATCH_MS)
@@ -2152,7 +2138,7 @@ describe('createLinkHost — control', () => {
await type(vs[0], 'c'.repeat(INPUT_MAX), clock) // fills the batch to INPUT_BURST exactly
await type(vs[0], 'd'.repeat(INPUT_MAX), clock) // over: dropped
await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
- held.resolve(true)
+ held.release()
await clock.advance(INPUT_BATCH_MS) // the batch's own timer, armed by the last accepted cast
const size = (): number => t.inputs.reduce((n, [, c]) => n + (c.kind === 'keys' ? c.data.length : 0), 0)
await vi.waitFor(() => expect(size()).toBe(1 + INPUT_BURST))
@@ -2161,6 +2147,171 @@ describe('createLinkHost — control', () => {
expect(delivered(t).some((d) => d.includes('d'))).toBe(false)
})
+ // --- losing control: a password change and the lock take the same path as every other --------------
+
+ it('a password change: the pending batch is not delivered, a keystroke in flight is dropped, the viewer stays and leaves the typing set; 5 s later input is a breach', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { t, clock, vs } = await controllers(['Ada'])
+ const watcher = await openViewer(t, 1)
+ await type(vs[0], 'a', clock)
+ await vi.waitFor(() => expect(typingOf(watcher)).toEqual([['Ada']]))
+ t.host.passwordChanged()
+ await vi.waitFor(() => expect(controlOf(vs[0]).at(-1)).toEqual({ state: 'available' }))
+ expect(t.host.viewers()[0]).toMatchObject({ controlling: false, typing: false })
+ await type(vs[0], 'b', clock) // in flight when the password changed
+ await clock.advance(INPUT_BATCH_MS)
+ expect(t.inputs).toEqual([])
+ expect(vs[0].log.closed).toBe(0)
+ await clock.advance(TYPING_EVENT_MIN_MS)
+ expect(typingOf(watcher).at(-1)).toEqual([])
+ await clock.advance(INPUT_GRACE_MS)
+ await type(vs[0], 'c', clock)
+ await vi.waitFor(() => expect(vs[0].log.closed).toBe(1))
+ expect(t.inputs).toEqual([])
+ })
+
+ it('a password change voids a batch queued in the chain, even after its sender unlocks with the new password', async () => {
+ const held = holdFirst()
+ let password = PW
+ const { t, clock, vs } = await controllers(['Ada', 'Bob'], { input: held.input, verifyPassword: async (pw) => pw === password })
+ await type(vs[0], 'a', clock)
+ await clock.advance(INPUT_BATCH_MS)
+ await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
+ await type(vs[1], 'old', clock)
+ await clock.advance(INPUT_BATCH_MS)
+ password = 'a-new-password'
+ t.host.passwordChanged()
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ expect(await unlock(vs[1], 'Bob', 'a-new-password')).toEqual({ state: 'controlling' })
+ held.release()
+ await type(vs[1], 'new', clock)
+ await clock.advance(INPUT_BATCH_MS)
+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:new']))
+ await settleReal()
+ expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:new'])
+ })
+
+ it('the lock: a keystroke in flight is dropped and the controller stays; 5 s later input is a breach', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const { t, clock, vs } = await controllers(['Ada'])
+ await type(vs[0], 'a', clock)
+ let n = 1
+ for (let wrong = 0; wrong < WRONG_PER_LINK; ) {
+ const v = await openViewer(t, n++)
+ for (let i = 0; i < WRONG_PER_CONN && wrong < WRONG_PER_LINK; i++, wrong++) {
+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)
+ await unlock(v, 'Eve', WRONG)
+ }
+ }
+ expect(t.locks()).toBe(1)
+ await vi.waitFor(() => expect(controlOf(vs[0]).at(-1)).toEqual({ state: 'locked', reason: 'locked' }))
+ await type(vs[0], 'b', clock)
+ await clock.advance(INPUT_BATCH_MS)
+ expect(vs[0].log.closed).toBe(0)
+ await clock.advance(INPUT_GRACE_MS + 100)
+ await type(vs[0], 'c', clock)
+ await vi.waitFor(() => expect(vs[0].log.closed).toBe(1))
+ // 'a' flushed (still controlling) during the first throttle wait; nothing after the lock did.
+ expect(delivered(t)).toEqual(['s1:keys:a'])
+ })
+
+ it('malformed input inside the grace window is a silent drop too, not a breach', async () => {
+ const clock = manualClock()
+ const t = typist({ clock })
+ t.host.start()
+ const p = await openRaw(t, 0)
+ p.cast(WATCH_UNLOCK_CAST, [{ name: 'Ada', password: PW }])
+ await vi.waitFor(() => expect(controlOf(p)).toEqual([{ state: 'controlling' }]))
+ p.cast(WATCH_RELEASE_CAST, [])
+ await vi.waitFor(() => expect(controlOf(p)).toHaveLength(2))
+ p.cast(WATCH_INPUT_CAST, [{ data: 5 }])
+ p.cast(WATCH_INPUT_CAST, [{ data: 'x'.repeat(INPUT_MAX + 1) }])
+ await clock.advance(INPUT_BATCH_MS)
+ await settleReal()
+ expect(p.closed()).toBe(0)
+ expect(t.inputs).toEqual([])
+ })
+
+ // --- the splitter across batches and drops ---------------------------------------------------------
+
+ it('a start marker split across two casts with a batch in between is still a paste', async () => {
+ const { t, clock, vs } = await controllers(['Ada'])
+ await type(vs[0], `a${ESC}[20`, clock)
+ await clock.advance(INPUT_BATCH_MS)
+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a']))
+ await type(vs[0], `0~line 1\nline 2${PASTE_END}`, clock)
+ await clock.advance(INPUT_BATCH_MS)
+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:paste:line 1\nline 2']))
+ })
+
+ it('a dropped cast that ends in a start-marker prefix: the paste it begins is discarded, never typed as keys', async () => {
+ const { t, clock, vs } = await controllers(['Ada'])
+ for (let i = 0; i < INPUT_BURST / INPUT_MAX; i++) await type(vs[0], 'a'.repeat(INPUT_MAX), clock)
+ await type(vs[0], `b${ESC}[20`, clock) // over budget: dropped
+ await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))
+ await clock.advance(INPUT_BATCH_MS)
+ await clock.advance(1000)
+ await type(vs[0], `0~rm -rf ~\n${PASTE_END}ok`, clock)
+ await clock.advance(INPUT_BATCH_MS)
+ await vi.waitFor(() => expect(delivered(t).at(-1)).toBe('s1:keys:ok'))
+ expect(delivered(t).filter((d) => !d.startsWith('s1:keys:a'))).toEqual(['s1:keys:ok'])
+ })
+
+ // --- a pane that never answers --------------------------------------------------------------------
+
+ it('a pane delivery that never settles times out after INPUT_DELIVERY_TIMEOUT_MS: dropped notice, the chain moves on, a late answer is ignored', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {})
+ const late = deferred<boolean>()
+ let calls = 0
+ const { t, clock, vs } = await controllers(['Ada', 'Bob'], { input: () => (++calls === 1 ? late.promise : true) })
+ await type(vs[0], `a${PASTE_START}P${PASTE_END}`, clock)
+ await clock.advance(INPUT_BATCH_MS)
+ await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
+ await type(vs[1], 'z', clock)
+ await clock.advance(INPUT_BATCH_MS)
+ // Ada's chunk went to the pane one batch interval ago: its deadline is that far closer.
+ await clock.advance(INPUT_DELIVERY_TIMEOUT_MS - INPUT_BATCH_MS - 1)
+ expect(delivered(t)).toEqual(['s1:keys:a'])
+ await clock.advance(1)
+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:z']))
+ expect(dropped(vs[0])).toHaveLength(1)
+ expect(dropped(vs[1])).toEqual([])
+ // The answer arrives after all: nothing more is delivered, nobody is told twice.
+ late.resolve(true)
+ await settleReal()
+ expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:z'])
+ expect(dropped(vs[0])).toHaveLength(1)
+ })
+
+ it('a connection that ends while its delivery hangs releases the chain at once; stop() leaves no delivery timer', async () => {
+ const { t, clock, vs } = await controllers(['Ada', 'Bob'], { input: (_s, c) => (c.kind === 'keys' && c.data === 'a' ? new Promise<boolean>(() => {}) : true) })
+ await type(vs[0], 'a', clock)
+ await clock.advance(INPUT_BATCH_MS)
+ await vi.waitFor(() => expect(t.inputs).toHaveLength(1))
+ await type(vs[1], 'z', clock)
+ await clock.advance(INPUT_BATCH_MS)
+ expect(t.host.kick(t.host.viewers()[0].viewerId)).toBe(true)
+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:z']))
+ // A hung delivery when the link stops: its timer goes with it.
+ await type(vs[1], 'a', clock)
+ await clock.advance(INPUT_BATCH_MS)
+ await vi.waitFor(() => expect(t.inputs).toHaveLength(3))
+ t.host.stop('revoked')
+ await clock.flush()
+ expect(clock.pending()).toBe(0)
+ })
+
+ // --- the typing name -------------------------------------------------------------------------------
+
+ it('the typing set names the name control was taken under, not a later chat name', async () => {
+ const { t, clock, vs } = await controllers(['Ada'])
+ const watcher = await openViewer(t, 1)
+ expect(vs[0].c.sendChat('Bob', 'hi')).toBe(true)
+ await vi.waitFor(() => expect(t.chats).toHaveLength(1))
+ await type(vs[0], 'a', clock)
+ await vi.waitFor(() => expect(typingOf(watcher)).toEqual([['Ada']]))
+ })
+
it('stop() with a pending batch and a live typing set leaves no timer behind', async () => {
const { t, clock, vs } = await controllers(['Ada', 'Bob'])
await type(vs[0], 'a', clock)
diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.ts
index 248549557..06fcaa0b7 100644
--- a/src/core/watch-link/link-host.ts
+++ b/src/core/watch-link/link-host.ts
@@ -39,18 +39,24 @@
// `discard` (a paste any part of which was dropped is discarded whole), and the viewer is told
// `{controlling, dropped}` at most once per DROPPED_NOTICE_MIN_MS. Accepted data goes through the
// connection's SPLITTER (control-input.ts: keys vs a bracketed paste) into its BATCH; the batch flushes
-// INPUT_BATCH_MS after its first input into ONE flush CHAIN per link host, so every controller's batch
-// reaches the pane whole and in flush order through `pty.input` (PtyManager's pane delivery, never a
-// tmux client's key table). A connection has at most one batch in the chain: while it waits there,
-// new input keeps collecting, so a slow pane coalesces input instead of piling up deliveries. Each
-// chunk is re-checked before it goes — same control period (`controlGen`, bumped by every loss of
-// control), still controlling, still the session it was typed at — and a false or a rejection stops
-// the batch with the `dropped` notice (an SSH host without tmux answers false on every chunk: never
-// silence). Input is never held for a later session: a session that ends drops the pending batch and
-// discards an open paste. Nothing typed is ever logged.
+// INPUT_BATCH_MS after its first input into ONE flush CHAIN per link host, through `pty.input`
+// (PtyManager's pane delivery, never a tmux client's key table). A connection has at most one batch in
+// the chain: while it waits there, new input keeps collecting, so a slow pane coalesces input instead
+// of piling up deliveries. ORDER: a connection's input reaches the pane in the order it was typed, and
+// every batch arrives whole (no other controller's chunk inside it); ACROSS controllers it is roughly
+// flush order — a connection whose previous batch is still in the chain re-enters only when that batch
+// finishes, behind whatever other controllers flushed meanwhile. Each chunk is re-checked before it
+// goes — same control period (`controlGen`, bumped by every loss of control), still controlling,
+// still the session it was typed at — and a false, a rejection, or no answer within
+// INPUT_DELIVERY_TIMEOUT_MS stops the batch with the `dropped` notice (an SSH host without tmux answers
+// false on every chunk: never silence) and the chain moves on. Input is never held for a later
+// session: a session that ends drops the pending batch and discards an open paste (told either way).
+// The typing set names a controller by the name it unlocked under, not a later chat name. Nothing
+// typed is ever logged.
//
// GRACE. Keystrokes are in flight when control ends (a release, the owner turning typing off, a new
-// password, the lock, a join whose terminal cannot take input): input from a connection that stopped
+// password, the lock, a join whose terminal cannot take input — every one of them goes through
+// `loseControl`): input from a connection that stopped
// controlling within INPUT_GRACE_MS is dropped silently — not delivered, not counted, not a breach.
// From a connection that never controlled, or later than that, it is a breach as before.
//
@@ -148,7 +154,7 @@ import {
import type { HostTokenResult } from './api'
import { unavailableCapture, type VisibleCapture } from './capture-route'
import { createInputSplitter, createTypingTracker, type InputSplitter } from './control-input'
-import type { ControlInputChunk, WatcherInputRoute } from './pane-input'
+import { WATCHER_INPUT_ROUTES, type ControlInputChunk, type WatcherInputRoute } from './pane-input'
import { isTerminalReport } from '../terminal-reports'
import { createStreamFilter, type StreamFilter } from './stream-filter'
import { createTokenBucket, type TokenBucket } from './token-bucket'
@@ -199,6 +205,9 @@ export const DROPPED_NOTICE_MIN_MS = 10_000
/** Input from a connection that stopped controlling this recently is dropped silently: keystrokes in
* flight when control ended are not a breach. Later than this, they are. */
export const INPUT_GRACE_MS = 5000
+/** A pane delivery that has not answered by now counts as failed: the batch stops (`dropped`) and the
+ * link's chain moves on. A late answer is ignored. */
+export const INPUT_DELIVERY_TIMEOUT_MS = 20_000
const RATE = 256 * 1024
const BURST = 1024 * 1024
@@ -335,7 +344,11 @@ interface Conn {
batchTimer: unknown
/** A batch of this connection is in the host-wide flush chain and has not finished. */
inChain: boolean
+ /** The chunk being delivered now: its deadline timer, and how to settle it early (end, stop). */
+ delivery: { timer: unknown; settle(ok: boolean): void } | null
lastDroppedAt: number
+ /** The name control was taken under (the unlock's); a later chat name does not change who typed. */
+ controlName: string | null
// The watched session (null while waiting).
sessionId: string | null
altScreen: boolean
@@ -395,10 +408,9 @@ function normalizeJoin(r: unknown): WatchJoin | null {
const dim = (n: unknown): boolean => Number.isInteger(n) && (n as number) > 0
if (!dim(o.cols) || !dim(o.rows)) return null
// A missing or unknown route refuses control: typing must never be guessed onto a backend.
- const input = (INPUT_ROUTES as readonly unknown[]).includes(o.input) ? (o.input as WatcherInputRoute) : 'none'
+ const input = (WATCHER_INPUT_ROUTES as readonly unknown[]).includes(o.input) ? (o.input as WatcherInputRoute) : 'none'
return { sessionId, cols: o.cols as number, rows: o.rows as number, altScreen: o.altScreen === true, input }
}
-const INPUT_ROUTES: readonly WatcherInputRoute[] = ['tmux', 'ssh', 'write', 'none']
/** A well-formed unlock payload, or null. The password is bounded before anything else reads it: over
* PASSWORD_MAX code points is malformed, and the cheap UTF-16 test first means a huge string is never
@@ -529,6 +541,8 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
c.controlling = false
clearInput(c)
c.splitter.reset()
+ // A delivery still waiting for the pane must not hold every other controller's batch.
+ c.delivery?.settle(false)
forgetTyping(c)
if (sid !== null) leave(c.clientId, sid, c.viewerId, c)
safe('the scheduler', () => c.ev.onClose())
@@ -932,6 +946,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
c.controlling = true
c.wrong = 0
c.name = attempt.name
+ c.controlName = attempt.name
sendControl(c, { state: 'controlling' })
// That send can end the connection (a backlog past VIEWER_BACKLOG_CLOSE): then nobody took control.
if (c.ended) return
@@ -1007,7 +1022,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
/** The watched session ended: pending input is dropped (and the controller told), and an open paste
* is discarded whole when its end arrives. */
function abandonInput(c: Conn): void {
- const had = c.batch.length > 0
+ const had = c.batch.length > 0 || c.splitter.pasteOpen()
clearInput(c)
c.splitter.discard('')
if (had) noteDropped(c)
@@ -1055,7 +1070,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
c.batchSession = sid
c.batchBytes += bytes
appendChunks(c, c.splitter.push(data))
- if (c.name) tracker.note(c.viewerId, c.name, deps.now())
+ if (c.controlName) tracker.note(c.viewerId, c.controlName, deps.now())
scheduleTyping()
if (c.batchTimer === null) {
c.batchTimer = deps.setTimeout(() => {
@@ -1078,7 +1093,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
* in the chain at most, so a slow pane cannot pile up deliveries. */
function flushBatch(c: Conn): void {
if (c.ended || stopped || c.inChain) return
- // A marker prefix still held after a whole batch interval is keys (a lone Esc).
+ // A held Esc or Alt+[ is a key press by now; a longer marker prefix keeps waiting (control-input.ts).
appendChunks(c, c.splitter.drain())
const chunks = c.batch
const session = c.batchSession
@@ -1105,13 +1120,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
noteDropped(c)
return
}
- let ok = false
- try {
- ok = (await deps.pty.input(b.session, chunk)) === true
- } catch (err) {
- // Never the error's text: what failed to type may be in it.
- warn(c, 'delivering input failed', err instanceof Error ? err.name : 'not an Error')
- }
+ const ok = await deliverChunk(c, b.session, chunk)
if (!ok) {
noteDropped(c)
return
@@ -1124,6 +1133,42 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
}
}
+ /** One chunk to the pane, answered within INPUT_DELIVERY_TIMEOUT_MS. A rejection, a throw, or no
+ * answer in time is false; an answer after that is ignored. `ended` settles it at once (false), so a
+ * pane that never answers cannot hold the link's chain beyond its deadline. */
+ function deliverChunk(c: Conn, session: string, chunk: ControlInputChunk): Promise<boolean> {
+ return new Promise<boolean>((resolve) => {
+ let settled = false
+ const slot: { timer: unknown; settle(ok: boolean): void } = {
+ timer: null,
+ settle(ok) {
+ if (settled) return
+ settled = true
+ clearTimer(slot.timer)
+ slot.timer = null
+ if (c.delivery === slot) c.delivery = null
+ resolve(ok)
+ }
+ }
+ c.delivery = slot
+ slot.timer = deps.setTimeout(() => {
+ slot.timer = null
+ warn(c, 'a pane delivery timed out', `no answer in ${INPUT_DELIVERY_TIMEOUT_MS} ms`)
+ slot.settle(false)
+ }, INPUT_DELIVERY_TIMEOUT_MS)
+ const failed = (err: unknown): void => {
+ // Never the error's text: what failed to type may be in it.
+ warn(c, 'delivering input failed', err instanceof Error ? err.name : 'not an Error')
+ slot.settle(false)
+ }
+ try {
+ void Promise.resolve(deps.pty.input(session, chunk)).then((ok) => slot.settle(ok === true), failed)
+ } catch (err) {
+ failed(err)
+ }
+ })
+ }
+
// --- typing: who is typing --------------------------------------------------------------------------
function forgetTyping(c: Conn): void {
@@ -1191,7 +1236,9 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
batchBytes: 0,
batchTimer: null,
inChain: false,
+ delivery: null,
lastDroppedAt: -Infinity,
+ controlName: null,
sessionId: null,
altScreen: false,
joining: false,
@@ -1447,7 +1494,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin
controlEpoch++
for (const c of joinedConns()) {
if (!c.controlling) continue
- c.controlling = false
+ loseControl(c)
sendControl(c, controlStateFor(c))
}
safe('onChange', deps.onChange)
diff --git a/src/core/watch-link/pane-input.ts b/src/core/watch-link/pane-input.ts
index 06bd298c9..4b9d3ace8 100644
--- a/src/core/watch-link/pane-input.ts
+++ b/src/core/watch-link/pane-input.ts
@@ -98,6 +98,8 @@ export type ControlInputChunk = { kind: 'keys'; data: string } | { kind: 'paste'
* - `none` — refused (Zellij: its key bindings are session-wide; an unknown session).
*/
export type WatcherInputRoute = 'tmux' | 'ssh' | 'write' | 'none'
+/** Every route, for a reader that must check one it did not produce (link-host.ts `normalizeJoin`). */
+export const WATCHER_INPUT_ROUTES = ['tmux', 'ssh', 'write', 'none'] as const satisfies readonly WatcherInputRoute[]
/** Bytes per `send-keys -H` line: 3 characters each on the line, so ~3 KiB a line. */
export const KEYS_PER_COMMAND = 1024