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
feat(live-links): a controller types into the pane; the host shows who is typing
review34fbb5f1b790
diff --git a/src/core/watch-link/control-input.test.ts b/src/core/watch-link/control-input.test.tsnew file mode 100644index 000000000..8c6a2d34c--- /dev/null+++ b/src/core/watch-link/control-input.test.ts@@ -0,0 +1,221 @@+import { describe, it, expect } from 'vitest'+import type { ControlInputChunk } from './pane-input'+import {+ PASTE_END,+ PASTE_MAX,+ PASTE_START,+ TYPING_WINDOW_MS,+ createInputSplitter,+ createTypingTracker,+ type InputSplitter+} from './control-input'++const keys = (data: string): ControlInputChunk => ({ kind: 'keys', data })+const paste = (text: string): ControlInputChunk => ({ kind: 'paste', text })+const ESC = '\x1b'++/** Adjacent keys chunks joined: two pushes of plain keys are two chunks, one push is one, and what+ * reaches the pane is the same bytes either way. Only a paste boundary separates keys. */+function merged(chunks: ControlInputChunk[]): ControlInputChunk[] {+ const out: ControlInputChunk[] = []+ for (const c of chunks) {+ const last = out.at(-1)+ if (c.kind === 'keys' && last?.kind === 'keys') out[out.length - 1] = keys(last.data + c.data)+ else out.push(c)+ }+ return out+}+/** Push every part, then drain what is still held (the host's flush). */+function run(s: InputSplitter, ...parts: string[]): ControlInputChunk[] {+ const out: ControlInputChunk[] = []+ for (const p of parts) out.push(...s.push(p))+ out.push(...s.drain())+ return out+}++describe('createInputSplitter', () => {+ it('plain typing is one keys chunk per push, byte for byte (control bytes and escapes included)', () => {+ const s = createInputSplitter()+ expect(s.push('ls -la\r')).toEqual([keys('ls -la\r')])+ expect(s.push('\x03')).toEqual([keys('\x03')])+ expect(s.push(`${ESC}[A${ESC}OB\x7f`)).toEqual([keys(`${ESC}[A${ESC}OB\x7f`)])+ expect(s.push('çé漢🙂')).toEqual([keys('çé漢🙂')])+ })++ it('a paste in one push is one paste chunk; keys around it stay keys, in order', () => {+ const s = createInputSplitter()+ expect(s.push(`${PASTE_START}echo hi\nls${PASTE_END}`)).toEqual([paste('echo hi\nls')])+ expect(s.push(`ab${PASTE_START}x${ESC}[Ay${PASTE_END}\r`)).toEqual([keys('ab'), paste(`x${ESC}[Ay`), keys('\r')])+ // Two pastes back to back stay two pastes.+ expect(s.push(`${PASTE_START}1${PASTE_END}${PASTE_START}2${PASTE_END}`)).toEqual([paste('1'), paste('2')])+ })++ it('an empty paste yields nothing (there is nothing to deliver)', () => {+ const s = createInputSplitter()+ expect(s.push(`${PASTE_START}${PASTE_END}`)).toEqual([])+ expect(s.push('a')).toEqual([keys('a')])+ })++ it('markers split at EVERY boundary across two pushes give the same chunks as one push', () => {+ const input = `ab${PASTE_START}one\ntwo${PASTE_END}cd${PASTE_START}x${PASTE_END}`+ const want = [keys('ab'), paste('one\ntwo'), keys('cd'), paste('x')]+ expect(run(createInputSplitter(), input)).toEqual(want)+ for (let i = 1; i < input.length; i++) {+ const got = run(createInputSplitter(), input.slice(0, i), input.slice(i))+ expect(merged(got), `split at ${i}`).toEqual(want)+ }+ })++ it('a marker split over three pushes is still a marker', () => {+ const s = createInputSplitter()+ expect(s.push(`${ESC}[2`)).toEqual([])+ expect(s.push('00')).toEqual([])+ expect(s.push(`~hi${ESC}`)).toEqual([])+ expect(s.push('[201~')).toEqual([paste('hi')])+ })++ it('a held marker prefix that turns out not to be a marker comes out as keys', () => {+ const s = createInputSplitter()+ expect(s.push(`a${ESC}[20`)).toEqual([keys('a')])+ expect(s.push('x')).toEqual([keys(`${ESC}[20x`)])+ // F9 and Insert start like the marker and are not it.+ expect(s.push(`${ESC}[20~`)).toEqual([keys(`${ESC}[20~`)])+ expect(s.push(`${ESC}[2~`)).toEqual([keys(`${ESC}[2~`)])+ })++ it('a lone Esc (a prefix of the paste marker) is held, and drain() hands it over as keys', () => {+ const s = createInputSplitter()+ expect(s.push(ESC)).toEqual([])+ expect(s.drain()).toEqual([keys(ESC)])+ expect(s.drain()).toEqual([])+ // Drained, it is gone: the next push does not repeat it.+ expect(s.push('[A')).toEqual([keys('[A')])+ })++ 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([])+ expect(s.drain()).toEqual([])+ // The held part completes the end marker.+ expect(s.push('1~z')).toEqual([paste('abc'), keys('z')])+ // A held part that does not end it is paste text.+ expect(s.push(`${PASTE_START}d${ESC}[20`)).toEqual([])+ expect(s.drain()).toEqual([])+ expect(s.push(`9${PASTE_END}`)).toEqual([paste(`d${ESC}[209`)])+ })++ it('a PASTE_END outside a paste is keys, passed through as typed', () => {+ const s = createInputSplitter()+ expect(s.push(`a${PASTE_END}b`)).toEqual([keys(`a${PASTE_END}b`)])+ })++ it('a PASTE_START inside a paste is paste text', () => {+ const s = createInputSplitter()+ expect(s.push(`${PASTE_START}a${PASTE_START}b${PASTE_END}`)).toEqual([paste(`a${PASTE_START}b`)])+ })++ it('a high surrogate at the end of a push waits for its pair (an emoji split across two casts)', () => {+ const s = createInputSplitter()+ const emoji = '🙂'+ expect(s.push(`a${emoji[0]}`)).toEqual([keys('a')])+ expect(s.push(`${emoji[1]}b`)).toEqual([keys(`${emoji}b`)])+ })++ it('a paste over PASTE_MAX is cut to PASTE_MAX; the rest up to its end is discarded, and typing goes on', () => {+ const s = createInputSplitter()+ const half = 'x'.repeat(PASTE_MAX / 2 + 10)+ expect(s.push(PASTE_START + half)).toEqual([])+ expect(s.push(half)).toEqual([])+ expect(s.push('y'.repeat(1000))).toEqual([])+ const out = s.push(`${PASTE_END}ls\r`)+ expect(out).toHaveLength(2)+ expect(out[0].kind).toBe('paste')+ expect((out[0] as { text: string }).text).toBe('x'.repeat(PASTE_MAX))+ expect(out[1]).toEqual(keys('ls\r'))+ })++ it('a paste cut at PASTE_MAX never ends on half a surrogate pair', () => {+ const s = createInputSplitter()+ const text = 'a'.repeat(PASTE_MAX - 1) + '🙂🙂'+ const out = s.push(`${PASTE_START}${text}${PASTE_END}`)+ expect(out).toEqual([paste('a'.repeat(PASTE_MAX - 1))])+ })++ it('reset() drops an open paste and a held prefix', () => {+ const s = createInputSplitter()+ expect(s.push(`${PASTE_START}secret`)).toEqual([])+ s.reset()+ expect(s.push(`more${PASTE_END}`)).toEqual([keys(`more${PASTE_END}`)])+ expect(s.push(ESC)).toEqual([])+ s.reset()+ expect(s.drain()).toEqual([])+ })++ it('discard() keeps the framing: a paste any dropped part of which was dropped is discarded whole, and the next keys come through', () => {+ const s = createInputSplitter()+ expect(s.push(`${PASTE_START}head`)).toEqual([])+ s.discard('middle') // over budget: dropped+ expect(s.push(`tail${PASTE_END}ls\r`)).toEqual([keys('ls\r')])+ // A paste whose END was dropped: closed by the discard, nothing left open.+ expect(s.push(`${PASTE_START}a`)).toEqual([])+ s.discard(`b${PASTE_END}`)+ expect(s.push('x')).toEqual([keys('x')])+ // A paste whose START was dropped: the rest is not typed as keys either.+ s.discard(`${PASTE_START}evil\n`)+ expect(s.push(`rm -rf /\n${PASTE_END}y`)).toEqual([keys('y')])+ })++ it('discard() drops keys, and a held prefix with them', () => {+ const s = createInputSplitter()+ expect(s.push(`a${ESC}`)).toEqual([keys('a')])+ s.discard('dropped')+ expect(s.drain()).toEqual([])+ expect(s.push('b')).toEqual([keys('b')])+ // A dropped cast that ENDS in a prefix holds nothing either.+ s.discard(`dropped${ESC}`)+ expect(s.drain()).toEqual([])+ expect(s.push('[A')).toEqual([keys('[A')])+ })+})++describe('createTypingTracker', () => {+ it('names who typed in the window, most recent first, one entry per viewer', () => {+ const t = createTypingTracker()+ t.note('v1', 'Ada', 1000)+ t.note('v2', 'Bob', 1500)+ t.note('v1', 'Ada', 2000)+ expect(t.names(2100)).toEqual(['Ada', 'Bob'])+ t.note('v2', 'Bob', 2200)+ expect(t.names(2300)).toEqual(['Bob', 'Ada'])+ expect(t.typing('v1', 2300)).toBe(true)+ expect(t.typing('v3', 2300)).toBe(false)+ })++ it('two viewers under one name are named once', () => {+ const t = createTypingTracker()+ t.note('v1', 'Ada', 1000)+ t.note('v2', 'Ada', 1100)+ expect(t.names(1200)).toEqual(['Ada'])+ })++ it('a name outside the window disappears', () => {+ const t = createTypingTracker()+ t.note('v1', 'Ada', 1000)+ t.note('v2', 'Bob', 3000)+ expect(t.names(1000 + TYPING_WINDOW_MS - 1)).toEqual(['Bob', 'Ada'])+ expect(t.names(1000 + TYPING_WINDOW_MS)).toEqual(['Bob'])+ expect(t.typing('v1', 1000 + TYPING_WINDOW_MS)).toBe(false)+ expect(t.names(3000 + TYPING_WINDOW_MS)).toEqual([])+ })++ it('drop removes a viewer at once', () => {+ const t = createTypingTracker()+ t.note('v1', 'Ada', 1000)+ t.note('v2', 'Bob', 1000)+ t.drop('v1')+ expect(t.names(1001)).toEqual(['Bob'])+ expect(t.typing('v1', 1001)).toBe(false)+ t.drop('nobody')+ expect(t.names(1001)).toEqual(['Bob'])+ })+})diff --git a/src/core/watch-link/control-input.ts b/src/core/watch-link/control-input.tsnew file mode 100644index 000000000..2c4acb45e--- /dev/null+++ b/src/core/watch-link/control-input.ts@@ -0,0 +1,198 @@+// A live link controller's input before it reaches the pane: which bytes are KEYS (typed byte for+// byte, pane-input.ts's keys plan) and which are a PASTE (text tmux frames per the pane's own+// bracketed-paste state, `paste-buffer -p`), and who typed in the last few seconds. Pure: no timers,+// no I/O — the link host owns both (link-host.ts).+//+// THE SPLITTER. While controlling, the viewer page holds its xterm in bracketed-paste mode, so every+// paste arrives framed `ESC[200~ … ESC[201~` and the host can tell a paste from typing. Everything+// outside a frame is keys, which is also where every control byte belongs: tmux 3.7 passes paste+// buffer content through vis(3), so a Ctrl-C inside a paste would arrive as the text `^C`+// (pane-input.ts, measured). The splitter keeps state across pushes because the page splits a long+// input into casts of at most INPUT_MAX units, so a marker (or a surrogate pair) can straddle two.+//+// 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 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.+import type { ControlInputChunk } from './pane-input'++export const PASTE_START = '\x1b[200~'+export const PASTE_END = '\x1b[201~'+/** The longest paste delivered, in UTF-16 units; the rest of a longer one is discarded. */+export const PASTE_MAX = 256 * 1024+/** A name is in the typing set for this long after that viewer's last accepted input. */+export const TYPING_WINDOW_MS = 4000++export interface InputSplitter {+ /** Accepted input: the chunks it completes, in order. Consecutive keys in one push are one chunk. */+ 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). */+ drain(): ControlInputChunk[]+ /** Control lost or the connection ended: forget an open paste and anything held. */+ reset(): void+}++const isHighSurrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdbff++/** The length of the longest proper prefix of `marker` that `s` ends with. */+function heldMarkerPrefix(s: string, marker: string): number {+ for (let k = Math.min(marker.length - 1, s.length); k > 0; k--) {+ if (s.endsWith(marker.slice(0, k))) return k+ }+ return 0+}++export function createInputSplitter(): InputSplitter {+ let inPaste = false+ /** The tail of the last push that may combine with the next one. */+ let held = ''+ let parts: string[] = []+ let pasteLen = 0+ /** The open paste reached PASTE_MAX: nothing more is appended. */+ let full = false+ /** Part of the open paste was dropped: it is discarded at its end. */+ let poisoned = false++ function openPaste(): void {+ inPaste = true+ parts = []+ pasteLen = 0+ full = false+ poisoned = false+ }+ function appendPaste(s: string): void {+ if (full || poisoned || s.length === 0) return+ const room = PASTE_MAX - pasteLen+ if (s.length <= room) {+ parts.push(s)+ pasteLen += s.length+ return+ }+ parts.push(s.slice(0, room))+ pasteLen = PASTE_MAX+ full = true+ }+ /** The paste just closed: its text, or null when there is nothing to deliver. */+ function closePaste(): string | null {+ inPaste = false+ let text = poisoned ? '' : parts.join('')+ parts = []+ pasteLen = 0+ // A cut that fell between the halves of a pair leaves a lone high surrogate: drop it.+ if (full && text.length > 0 && isHighSurrogate(text.charCodeAt(text.length - 1))) text = text.slice(0, -1)+ return text.length > 0 ? text : null+ }++ /** One scan over `held + data`. `deliver` false: track the framing, deliver nothing. */+ function scan(data: string, deliver: boolean): ControlInputChunk[] {+ let s = held + data+ held = ''+ const out: ControlInputChunk[] = []+ let keys = ''+ const flushKeys = (): void => {+ if (keys.length > 0 && deliver) out.push({ kind: 'keys', data: keys })+ keys = ''+ }+ if (!deliver && inPaste) poisoned = true+ while (s.length > 0) {+ if (!inPaste) {+ const i = s.indexOf(PASTE_START)+ if (i < 0) {+ let h = heldMarkerPrefix(s, PASTE_START)+ if (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)+ break+ }+ keys += s.slice(0, i)+ flushKeys()+ openPaste()+ if (!deliver) poisoned = true+ s = s.slice(i + PASTE_START.length)+ } else {+ const i = s.indexOf(PASTE_END)+ if (i < 0) {+ const h = heldMarkerPrefix(s, PASTE_END)+ appendPaste(s.slice(0, s.length - h))+ // Inside a paste the held part is paste text or the end marker: keep it either way.+ held = s.slice(s.length - h)+ break+ }+ appendPaste(s.slice(0, i))+ const text = closePaste()+ if (text !== null && deliver) out.push({ kind: 'paste', text })+ s = s.slice(i + PASTE_END.length)+ }+ }+ flushKeys()+ return out+ }++ return {+ push: (data) => scan(data, true),+ discard(data) {+ scan(data, false)+ },+ drain() {+ if (inPaste || held.length === 0) return []+ const data = held+ held = ''+ return [{ kind: 'keys', data }]+ },+ reset() {+ inPaste = false+ held = ''+ parts = []+ pasteLen = 0+ full = false+ poisoned = false+ }+ }+}++export interface TypingTracker {+ /** `viewerId` (named `name`) gave accepted input at `at`. */+ note(viewerId: string, name: string, at: number): void+ /** The viewer stopped controlling or left: out of the set at once. */+ drop(viewerId: string): void+ /** Names with input in the TYPING_WINDOW_MS before `at`, most recent first, each name once. */+ names(at: number): string[]+ typing(viewerId: string, at: number): boolean+}++export function createTypingTracker(): TypingTracker {+ // Insertion order is recency: `note` re-inserts, so the last entry is the most recent typist.+ const last = new Map<string, { name: string; at: number }>()+ const recent = (e: { at: number }, at: number): boolean => at - e.at < TYPING_WINDOW_MS+ return {+ note(viewerId, name, at) {+ last.delete(viewerId)+ last.set(viewerId, { name, at })+ },+ drop(viewerId) {+ last.delete(viewerId)+ },+ names(at) {+ const out: string[] = []+ for (const e of [...last.values()].reverse()) if (recent(e, at) && !out.includes(e.name)) out.push(e.name)+ return out+ },+ typing(viewerId, at) {+ const e = last.get(viewerId)+ return !!e && recent(e, at)+ }+ }+}diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.tsindex 320660daa..d7f2f74ad 100644--- a/src/core/watch-link/link-host.test.ts+++ b/src/core/watch-link/link-host.test.ts@@ -15,6 +15,8 @@ import { isHostOnlyChannel } from '../../shared/host-control'import { connectWatchClient } from '../../shared/watch-link/client'import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'import {+ INPUT_MAX,+ TYPING_NAMES_MAX,WATCH_EVENT,WATCH_INPUT_CAST,WATCH_RELEASE_CAST,@@ -27,6 +29,12 @@ import {import {createLinkHost,CONFIRM_DEADLINE_MS,+ DROPPED_NOTICE_MIN_MS,+ INPUT_BATCH_MS,+ INPUT_BURST,+ INPUT_GRACE_MS,+ INPUT_RATE,+ TYPING_EVENT_MIN_MS,FULL_STATUS_POLL_MS,MAX_VIEWERS_PER_LINK,REJOIN_BACKOFF_MS,@@ -45,6 +53,8 @@ import { unavailableCapture, type VisibleCapture } from './capture-route'import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'import type { WatchLinkControlRecord, WatchLinkRecord } from './store'import type { UiSink } from '../ui-sink-registry'+import type { ControlInputChunk, WatcherInputRoute } from './pane-input'+import { PASTE_END, PASTE_START, TYPING_WINDOW_MS } from './control-input'const ESC = '\x1b'const TRUST_CONFIRM = '{"t":"cast","method":"trust:confirm","args":[]}'@@ -72,6 +82,8 @@ function manualClock() {clearTimeout: (h: unknown) => {timers.delete(h as number)},+ /** How many timers are armed and not yet fired or cleared. */+ pending: (): number => timers.size,async advance(ms: number): Promise<void> {const end = t + msfor (;;) {@@ -93,6 +105,9 @@ function manualClock() {}type ManualClock = ReturnType<typeof manualClock>+/** A join answer as a custom `join` writes it: the input route may be left to `SetupOpts.route`. */+type JoinAnswer = Omit<WatchJoin, 'input'> & { input?: WatchJoin['input'] }+interface SetupOpts {role?: WatchLinkRole/** A Control link's record state (the test mutates it the way the service does). */@@ -102,12 +117,17 @@ interface SetupOpts {verifyPassword?: (pw: string) => Promise<boolean>/** Replaces the service's lock (which sets `record.control.locked`); still counted in `locks()`. */onControlLocked?: () => void- join?: (clientId: number, nodeId: string, viewerId: string) => Promise<WatchJoin | null> | WatchJoin | null+ join?: (clientId: number, nodeId: string, viewerId: string) => Promise<JoinAnswer | null> | JoinAnswer | nullcapture?: (sid: string) => Promise<VisibleCapture> | VisibleCapturealive?: (sid: string) => boolean/** The host side's socket backlog, per listener (in the order listeners were opened). */buffered?: (listener: number) => numberclock?: ManualClock+ /** The pane delivery (`WatchPty.input`). Default: resolves true. Every call is recorded first. */+ input?: (sid: string, chunk: ControlInputChunk) => Promise<boolean> | boolean+ /** The input route the default join answers, and the one added to a custom join's answer that has+ * none. 'missing': leave the field out (the host must read that as 'none'). Default 'tmux'. */+ route?: WatcherInputRoute | 'missing'mint?: () => Promise<HostTokenResult>status?: () => Promise<'live' | 'revoked' | 'expired' | 'unknown'>}@@ -126,6 +146,8 @@ function setup(o: SetupOpts = {}) {const calls: string[] = []const joinArgs: [number, string, string][] = []const joinTimes: number[] = []+ /** Every `pty.input` call, in order: [sessionId, chunk]. */+ const inputs: [string, ControlInputChunk][] = []let mints = 0let changes = 0let verifies = 0@@ -138,7 +160,11 @@ function setup(o: SetupOpts = {}) {calls.push('join')joinArgs.push([clientId, nodeId, viewerId])joinTimes.push(now())- return o.join ? o.join(clientId, nodeId, viewerId) : { sessionId: 's1', cols: 100, rows: 30, altScreen: true }+ const route = o.route ?? 'tmux'+ const r = o.join ? await o.join(clientId, nodeId, viewerId) : { sessionId: 's1', cols: 100, rows: 30, altScreen: true }+ // 'missing' hands the host an answer with no route, as a wiring slip would.+ if (!r || 'input' in r || route === 'missing') return r as WatchJoin | null+ return { ...r, input: route }},leave: (_c, sid, vid) => {left.push(`${sid}/${vid}`)@@ -151,7 +177,11 @@ function setup(o: SetupOpts = {}) {calls.push(`sync:${sid}`)return true},- alive: (sid) => (o.alive ? o.alive(sid) : true)+ alive: (sid) => (o.alive ? o.alive(sid) : true),+ input: async (sid, chunk) => {+ inputs.push([sid, chunk])+ return o.input ? o.input(sid, chunk) : true+ }}const chats: unknown[] = []const joined: number[] = []@@ -206,7 +236,7 @@ function setup(o: SetupOpts = {}) {})hosts.push(host)return {- record, host, peers, sinks, left, calls, joinArgs, joinTimes, chats, joined, gone,+ record, host, peers, sinks, left, calls, joinArgs, joinTimes, inputs, chats, joined, gone,keys: deriveWatchLinkKeys(secret),mints: () => mints,/** How many times the host reported a change to the registry (`onChange`). */@@ -1490,7 +1520,7 @@ describe('createLinkHost — control', () => {expect(t.host.viewers()).toHaveLength(1)})- it('input from a viewer that is not controlling closes it; from a controller it is accepted, and reaches no pty yet', async () => {+ it('input from a viewer that is not controlling closes it; from a controller it reaches the pane; after a release it is dropped for 5 s, then a breach', async () => {const clock = manualClock()vi.spyOn(console, 'warn').mockImplementation(() => {})const t = controller({ clock })@@ -1501,17 +1531,22 @@ describe('createLinkHost — control', () => {await vi.waitFor(() => expect(b.log.closed).toBe(1))expect(t.host.viewers()).toHaveLength(1)expect(await unlock(a, 'Ada', PW)).toEqual({ state: 'controlling' })- const calls = t.calls.lengthexpect(a.c.sendInput('ls\r')).toBe(true)- await settleReal()+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.inputs).toEqual([['s1', { kind: 'keys', data: 'ls\r' }]]))expect(a.log.closed).toBe(0)- expect(t.host.viewers()).toHaveLength(1)- expect(t.calls.slice(calls)).toEqual([])- // Released: the same input is now a breach.+ // Released: a keystroke still in flight is dropped, and the connection stays.expect(await ask(a, () => a.c.release())).toEqual({ state: 'available' })- expect(a.c.sendInput('ls\r')).toBe(true)+ expect(a.c.sendInput('x')).toBe(true)+ await clock.advance(INPUT_GRACE_MS)+ expect(a.log.closed).toBe(0)+ expect(t.inputs).toHaveLength(1)+ // Past the grace it is a breach.+ await clock.advance(100)+ expect(a.c.sendInput('x')).toBe(true)await vi.waitFor(() => expect(a.log.closed).toBe(1))expect(t.host.viewers()).toEqual([])+ expect(t.inputs).toHaveLength(1)})it('on a Commenter link, unlock, input and release casts from a raw peer are refused before the host: nothing comes back, nothing is verified', async () => {@@ -1620,4 +1655,532 @@ describe('createLinkHost — control', () => {t.record.control!.enabled = trueexpect(t.host.viewers()[0].controlling).toBe(true)})++ // --- typing: the input path and the typing set ------------------------------------------------------++ describe('control typing', () => {+ /** A Control link whose password check is instant (the scrypt one is tested above). */+ const typist = (o: SetupOpts = {}): Setup => controller({ clock: manualClock(), verifyPassword: async (pw) => pw === PW, ...o })+ const dropped = (v: Viewer): WatchControlEvent[] => controlOf(v).filter((e) => e.reason === 'dropped')+ const typingOf = (v: Viewer): string[][] => (v.named(WATCH_EVENT.typing) as { names: string[] }[]).map((e) => e.names)+ /** Cast one input and let the host take it (the in-process transport delivers synchronously). */+ async function type(v: Viewer, data: string, clock: ManualClock): Promise<void> {+ expect(v.c.sendInput(data)).toBe(true)+ await clock.flush()+ }+ /** A typist link with one or more controllers, already unlocked. */+ async function controllers(names: string[], o: SetupOpts = {}) {+ const clock = o.clock ?? manualClock()+ const t = typist({ ...o, clock })+ t.host.start()+ const vs: Viewer[] = []+ for (let i = 0; i < names.length; i++) {+ const v = await openViewer(t, i)+ expect(await unlock(v, names[i], PW)).toEqual({ state: 'controlling' })+ vs.push(v)+ }+ return { t, clock, vs }+ }+ const delivered = (t: Setup): string[] =>+ t.inputs.map(([sid, c]) => `${sid}:${c.kind}:${c.kind === 'keys' ? c.data : c.text}`)++ it('a controller types `ls\\r`: one keys chunk to the joined session, after INPUT_BATCH_MS', async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ await type(vs[0], 'l', clock)+ await type(vs[0], 's', clock)+ await type(vs[0], '\r', clock)+ await clock.advance(INPUT_BATCH_MS - 1)+ expect(t.inputs).toEqual([])+ await clock.advance(1)+ await vi.waitFor(() => expect(t.inputs).toEqual([['s1', { kind: 'keys', data: 'ls\r' }]]))+ expect(t.host.viewers()[0]).toMatchObject({ controlling: true, typing: true })+ expect(dropped(vs[0])).toEqual([])+ })++ it('a paste arrives as one paste chunk between the keys around it', async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ await type(vs[0], `a${PASTE_START}echo 1\necho 2${PASTE_END}b`, clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:paste:echo 1\necho 2', 's1:keys:b']))+ })++ it('a lone Esc reaches the pane within one batch (it is held as a marker prefix, then drained)', async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ await type(vs[0], ESC, clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(delivered(t)).toEqual([`s1:keys:${ESC}`]))+ })++ it("a non-controlling viewer's input closes it and delivers nothing", async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const b = await openViewer(t, 1)+ await type(b, 'rm -rf ~\r', clock)+ await vi.waitFor(() => expect(b.log.closed).toBe(1))+ await clock.advance(INPUT_BATCH_MS)+ expect(t.inputs).toEqual([])+ expect(vs[0].log.closed).toBe(0)+ })++ it('malformed input from a controller is a breach: not a string, empty, or over INPUT_MAX', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ for (const args of [[{ data: 5 }], [{ data: '' }], [{ data: 'x'.repeat(INPUT_MAX + 1) }], [null], []]) {+ 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_INPUT_CAST, args)+ await vi.waitFor(() => expect(p.closed()).toBe(1))+ await clock.advance(INPUT_BATCH_MS)+ expect(t.inputs).toEqual([])+ t.host.stop('revoked')+ }+ })++ it("a terminal's own answer (DA) is dropped, never counted against the budget, and is not typing", async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ await type(vs[0], `${ESC}[?1;2c`, clock)+ await clock.advance(INPUT_BATCH_MS)+ expect(t.inputs).toEqual([])+ expect(t.host.viewers()[0].typing).toBe(false)+ // Well past the burst in answers, and a keystroke still goes through.+ const answers = `${ESC}[?1;2c`.repeat(INPUT_MAX / 8)+ for (let i = 0; i < 20; i++) await type(vs[0], answers, clock)+ await type(vs[0], 'x', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:x']))+ expect(dropped(vs[0])).toEqual([])+ })++ it('bucket: 300 KiB in one burst delivers INPUT_BURST, and sends ONE dropped notice', async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ const total = 300 * 1024+ for (let sent = 0; sent < total; sent += INPUT_MAX) await type(vs[0], 'a'.repeat(Math.min(INPUT_MAX, total - sent)), clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.inputs.reduce((n, [, c]) => n + (c.kind === 'keys' ? c.data.length : 0), 0)).toBe(INPUT_BURST))+ expect(dropped(vs[0])).toEqual([{ state: 'controlling', reason: 'dropped' }])+ expect(vs[0].log.closed).toBe(0)+ // The bucket refills at INPUT_RATE: a second's worth goes through again.+ await clock.advance(1000)+ await type(vs[0], 'b'.repeat(INPUT_RATE / 4), clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(delivered(t).some((d) => d.startsWith('s1:keys:b'))).toBe(true))+ })++ it('a 1 MB paste over the budget is discarded whole (never typed as keys), and typing after it works', async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ const body = `${PASTE_START}${'echo pwned\n'.repeat(96 * 1024)}${PASTE_END}`+ for (let i = 0; i < body.length; i += INPUT_MAX) await type(vs[0], body.slice(i, i + INPUT_MAX), clock)+ await clock.advance(INPUT_BATCH_MS)+ await clock.advance(1000)+ await type(vs[0], 'x', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:x']))+ expect(dropped(vs[0])).toHaveLength(1)+ })++ it("two controllers' batches arrive whole and in flush order", async () => {+ const held = deferred<boolean>()+ let first = true+ const { t, clock, vs } = await controllers(['Ada', 'Bob'], {+ input: () => {+ if (!first) return true+ first = false+ return held.promise+ }+ })+ await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, 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)+ // 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)+ 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 { t, clock, vs } = await controllers(['Ada'], {+ input: () => {+ if (!first) return true+ first = false+ return held.promise+ }+ })+ await type(vs[0], 'a', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.inputs).toHaveLength(1))+ for (const k of ['b', 'c', 'd']) {+ await type(vs[0], k, clock)+ await clock.advance(INPUT_BATCH_MS)+ }+ expect(delivered(t)).toEqual(['s1:keys:a'])+ held.resolve(true)+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s1:keys:a', 's1:keys:bcd']))+ })++ it('control turned off while a batch is pending: nothing delivered; a keystroke in flight is dropped and the viewer stays', async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ await type(vs[0], 'x', clock)+ t.record.control!.enabled = false+ t.host.controlChanged()+ await type(vs[0], 'y', clock) // in flight when control went off+ await clock.advance(INPUT_BATCH_MS)+ await clock.advance(1000)+ expect(t.inputs).toEqual([])+ expect(vs[0].log.closed).toBe(0)+ expect(t.host.viewers()[0]).toMatchObject({ controlling: false, typing: false })+ expect(dropped(vs[0])).toEqual([])+ })++ it('a batch already queued behind another is not delivered once its sender lost control', async () => {+ const held = deferred<boolean>()+ let first = true+ const { t, clock, vs } = await controllers(['Ada', 'Bob'], {+ input: () => {+ if (!first) return true+ first = false+ return held.promise+ }+ })+ 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(await ask(vs[1], () => vs[1].c.release())).toEqual({ state: 'available' })+ held.resolve(true)+ 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 { t, clock, vs } = await controllers(['Ada', 'Bob'], {+ input: () => {+ if (!first) return true+ first = false+ return held.promise+ }+ })+ 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)+ 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)+ 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']))+ // Voided by the release it was told about: no "dropped" on top.+ expect(dropped(vs[1])).toEqual([])+ })++ 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+ 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+ }+ })+ await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.inputs).toHaveLength(1))+ ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)+ 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)+ await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))+ expect(delivered(t)).toEqual(['s1:keys:a'])+ })++ it('a paste open when its session ended is discarded whole, even when its end arrives at the next session', async () => {+ let n = 0+ const { t, clock, vs } = await controllers(['Ada'], { join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })+ await type(vs[0], `${PASTE_START}first half `, clock)+ ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)+ await clock.flush()+ await clock.advance(REJOIN_BACKOFF_MS[0])+ await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))+ 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']))+ })++ it('in-flight input after a release is dropped silently; 5.1 s later it is a breach', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ const { t, clock, vs } = await controllers(['Ada'])+ expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })+ await type(vs[0], 'x', clock)+ await clock.advance(INPUT_BATCH_MS)+ expect(vs[0].log.closed).toBe(0)+ expect(t.inputs).toEqual([])+ expect(dropped(vs[0])).toEqual([])+ await clock.advance(INPUT_GRACE_MS + 100)+ await type(vs[0], 'x', clock)+ await vi.waitFor(() => expect(vs[0].log.closed).toBe(1))+ expect(t.inputs).toEqual([])+ })++ it('the session changes (exit, then a rejoin to s2): the next input goes to s2', async () => {+ let n = 0+ const { t, clock, vs } = await controllers(['Ada'], { join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })+ ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)+ await clock.flush()+ await clock.advance(REJOIN_BACKOFF_MS[0])+ await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))+ expect(metaOf(vs[0], 1).control).toEqual({ state: 'controlling' })+ await type(vs[0], 'pwd\r', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(delivered(t)).toEqual(['s2:keys:pwd\r']))+ })++ it('no session (waiting): dropped with a notice, and nothing is delivered after a later join', async () => {+ let n = 0+ let refuse = false+ const { t, clock, vs } = await controllers(['Ada'], {+ join: () => (refuse ? null : { sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true })+ })+ refuse = true+ ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)+ await clock.flush()+ await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.waiting)).toHaveLength(1))+ await type(vs[0], 'held?\r', clock)+ await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))+ refuse = false+ await clock.advance(REJOIN_BACKOFF_MS[0])+ await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))+ await clock.advance(INPUT_BATCH_MS * 10)+ expect(t.inputs).toEqual([])+ })++ it('a pending batch for a session that ended is dropped with a notice, never typed into the next one', async () => {+ let n = 0+ const { t, clock, vs } = await controllers(['Ada'], { join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })+ await type(vs[0], 'x', clock)+ ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)+ await clock.flush()+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))+ await clock.advance(REJOIN_BACKOFF_MS[0])+ await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))+ await clock.advance(INPUT_BATCH_MS)+ expect(t.inputs).toEqual([])+ })++ it('a pane delivery answering false stops the batch and sends a dropped notice, at most one per DROPPED_NOTICE_MIN_MS', async () => {+ const { t, clock, vs } = await controllers(['Ada'], { input: () => false })+ await type(vs[0], `a${PASTE_START}P${PASTE_END}b`, clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))+ expect(delivered(t)).toEqual(['s1:keys:a'])+ await type(vs[0], 'c', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.inputs).toHaveLength(2))+ expect(dropped(vs[0])).toHaveLength(1)+ await clock.advance(DROPPED_NOTICE_MIN_MS)+ await type(vs[0], 'd', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(2))+ expect(vs[0].log.closed).toBe(0)+ })++ it('a pane delivery that rejects counts as false, and nothing typed is logged', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const { t, clock, vs } = await controllers(['Ada'], {+ input: () => Promise.reject(new Error('pane gone while typing hunter2-secret'))+ })+ await type(vs[0], 'hunter2-secret\r', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(dropped(vs[0])).toHaveLength(1))+ expect(t.inputs).toHaveLength(1)+ for (const call of [...warn.mock.calls, ...error.mock.calls]) {+ for (const arg of call) expect(String(arg)).not.toContain('hunter2')+ }+ })++ it('typing: two controllers type, every viewer gets watch:typing names, at most once a second; after 4 s of silence, names []', async () => {+ const { t, clock, vs } = await controllers(['Ada', 'Bob'])+ const watcher = await openViewer(t, 2)+ const changes = t.changes()+ await type(vs[0], 'a', clock)+ await vi.waitFor(() => expect(typingOf(watcher)).toEqual([['Ada']]))+ expect(t.changes()).toBeGreaterThan(changes)+ // A burst inside one second is one event.+ for (let i = 0; i < 5; i++) {+ await clock.advance(100)+ await type(vs[1], 'b', clock)+ await type(vs[0], 'a', clock)+ }+ expect(typingOf(watcher)).toEqual([['Ada']])+ await clock.advance(TYPING_EVENT_MIN_MS)+ await vi.waitFor(() => expect(typingOf(watcher)).toHaveLength(2))+ expect([...typingOf(watcher)[1]].sort()).toEqual(['Ada', 'Bob'])+ for (const v of [...vs, watcher]) expect(typingOf(v).at(-1)!.sort()).toEqual(['Ada', 'Bob'])+ expect(t.host.viewers().map((x) => x.typing)).toEqual([true, true, false])+ // Silence: cleared within the window plus one tick, then no more timer work for typing.+ await clock.advance(TYPING_WINDOW_MS + TYPING_EVENT_MIN_MS)+ expect(typingOf(watcher).at(-1)).toEqual([])+ expect(t.host.viewers().map((x) => x.typing)).toEqual([false, false, false])+ const n = typingOf(watcher).length+ await clock.advance(10 * TYPING_EVENT_MIN_MS)+ expect(typingOf(watcher)).toHaveLength(n)+ })++ it('a controller that releases leaves the typing set at the next tick', async () => {+ 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']]))+ expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })+ expect(t.host.viewers()[0].typing).toBe(false)+ await clock.advance(TYPING_EVENT_MIN_MS)+ expect(typingOf(watcher)).toEqual([['Ada'], []])+ })++ it('a viewer that joins (or rejoins) while someone types gets the typing set right after its meta', async () => {+ let n = 0+ const { t, clock, vs } = await controllers(['Ada'], { join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true }) })+ await type(vs[0], 'a', clock)+ await vi.waitFor(() => expect(typingOf(vs[0])).toEqual([['Ada']]))+ const late = await openViewer(t, 1)+ const names = late.log.events.map((e) => e[0])+ const meta = names.indexOf(WATCH_EVENT.meta)+ expect(names[meta + 1]).toBe(WATCH_EVENT.typing)+ expect(typingOf(late)).toEqual([['Ada']])+ // A rejoin of the typist itself: the set rides its new meta too.+ ptyEvent(t.sink(0), IPC.ptyExit('s1'), 0)+ await clock.flush()+ await clock.advance(REJOIN_BACKOFF_MS[0])+ await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))+ const ev = vs[0].log.events.map((e) => e[0])+ expect(ev[ev.lastIndexOf(WATCH_EVENT.meta) + 1]).toBe(WATCH_EVENT.typing)+ // Nobody typing: no typing event after a meta.+ const quiet = typist()+ quiet.host.start()+ const q = await openViewer(quiet)+ expect(q.named(WATCH_EVENT.typing)).toEqual([])+ })++ it('ten typists at once (the most a link holds) are all named, within TYPING_NAMES_MAX', async () => {+ const names = Array.from({ length: TYPING_NAMES_MAX }, (_, i) => `N${i}`)+ const { clock, vs } = await controllers(names)+ for (const v of vs) await type(v, 'a', clock)+ await clock.advance(TYPING_EVENT_MIN_MS)+ expect(typingOf(vs[0]).at(-1)).toHaveLength(TYPING_NAMES_MAX)+ })++ it("an input route of 'none' (or none, or an unknown one, answered): meta says off/unsupported, and an unlock is refused with it, never counted", async () => {+ const cases: SetupOpts[] = [+ { route: 'none' },+ { route: 'missing' },+ { join: () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true, input: 'zellij' as never }) }+ ]+ for (const o of cases) {+ const t = typist(o)+ t.host.start()+ const v = await openViewer(t)+ expect(metaOf(v).control).toEqual({ state: 'off', reason: 'unsupported' })+ // Answered as it stands: no throttle, no count, no verification.+ for (let i = 0; i < WRONG_PER_CONN + 1; i++) {+ expect(await unlock(v, 'Ada', PW)).toEqual({ state: 'off', reason: 'unsupported' })+ }+ expect(t.verifies()).toBe(0)+ expect(v.log.closed).toBe(0)+ expect(t.host.viewers()[0].controlling).toBe(false)+ }+ })++ it("a controller whose rejoin answers 'none' is demoted: its meta says unsupported, and input in flight is dropped", async () => {+ let n = 0+ const { t, clock, vs } = await controllers(['Ada'], {+ join: () => ({ sessionId: `s${++n}`, cols: 80, rows: 24, altScreen: true, input: n === 1 ? 'tmux' : 'none' })+ })+ ptyEvent(t.sink(), IPC.ptyExit('s1'), 0)+ await clock.flush()+ await clock.advance(REJOIN_BACKOFF_MS[0])+ await vi.waitFor(() => expect(vs[0].named(WATCH_EVENT.meta)).toHaveLength(2))+ expect(metaOf(vs[0], 1).control).toEqual({ state: 'off', reason: 'unsupported' })+ expect(t.host.viewers()[0].controlling).toBe(false)+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ await type(vs[0], 'x', clock)+ await clock.advance(INPUT_BATCH_MS)+ expect(vs[0].log.closed).toBe(0)+ expect(t.inputs).toEqual([])+ // It stopped controlling at that join: past the grace, input is the breach it is from anyone.+ await clock.advance(INPUT_GRACE_MS + 100)+ await type(vs[0], 'x', clock)+ await vi.waitFor(() => expect(vs[0].log.closed).toBe(1))+ expect(t.inputs).toEqual([])+ })++ 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 { t, clock, vs } = await controllers(['Ada'], {+ input: () => {+ if (!first) return true+ first = false+ return held.promise+ }+ })+ await type(vs[0], 'a', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.inputs).toHaveLength(1))+ // Inside the bucket (1 byte spent): 15 full casts.+ for (let i = 0; i < 15; i++) await type(vs[0], 'b'.repeat(INPUT_MAX), clock)+ expect(dropped(vs[0])).toEqual([])+ // A second later the bucket has room again, but the batch waiting for the pane is full.+ await clock.advance(1000)+ 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)+ 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))+ await settleReal()+ expect(size()).toBe(1 + INPUT_BURST)+ expect(delivered(t).some((d) => d.includes('d'))).toBe(false)+ })++ 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)+ await type(vs[1], 'b', clock)+ expect(clock.pending()).toBeGreaterThan(0)+ t.host.stop('revoked')+ await clock.flush()+ expect(clock.pending()).toBe(0)+ await clock.advance(60_000)+ expect(t.inputs).toEqual([])+ })++ it('a viewer that ends with a pending batch: its timer is cleared and nothing is delivered', async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ await type(vs[0], 'a', clock)+ const before = clock.pending()+ expect(t.host.kick(t.host.viewers()[0].viewerId)).toBe(true)+ expect(clock.pending()).toBeLessThan(before)+ await clock.advance(INPUT_BATCH_MS * 10)+ expect(t.inputs).toEqual([])+ })+ })})diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.tsindex c4efa136f..248549557 100644--- a/src/core/watch-link/link-host.ts+++ b/src/core/watch-link/link-host.ts@@ -11,9 +11,10 @@// it forwards nothing to any platform, and a request, or a cast the link's role does not admit, that// reaches it anyway means the access policy failed, so the session is CLOSED (fail closed, as// relay-host does for a throwing wrapSink). Input from a viewer that is not controlling is the same-// breach. No viewer size or resize reaches a pty, and no viewer byte does yet (accepted input is not-// delivered): the join, the size sync and the capture take only ids the host chose. No `interceptReq`-// is ever supplied (it would bypass `access`).+// breach (but for the GRACE below). No viewer size or resize reaches a pty; the only viewer bytes that+// reach anything are a controller's input, into the pane of the session the host joined (TYPING+// below). The join, the size sync, the capture and the input take only ids the host chose. No+// `interceptReq` is ever supplied (it would bypass `access`).//// CONTROL (a Control link, role 'controller') is per CONNECTION: a viewer that unlocks with the link's// password (`watch:unlock`) is `controlling` until it releases, disconnects or is kicked, or until the@@ -26,7 +27,39 @@// attempts end that connection (`attempts`), WRONG_PER_LINK across the link lock it. The link count// lives in memory and only `allowControl` resets it. A verification is re-checked after its await: an// ended viewer, a stopped host, or any change to control meanwhile (off, locked, a new password — the-// control epoch) voids it, uncounted.+// control epoch) voids it, uncounted. A join whose input route is `none` (Zellij, an unknown session;+// also what a missing or unknown route reads as) makes that viewer's state `off`/`unsupported`: its+// meta says so, an unlock is answered so (uncounted), and a controller is demoted.+//+// TYPING (`watch:input` from a controller). A cast whose data is not a string of 1..INPUT_MAX units is a+// breach. A terminal's own answer to the pane's query (`isTerminalReport`: DA, CPR, a colour — every+// controller's emulator answers every query) is dropped, uncounted. Then the connection's own token+// bucket (INPUT_RATE / INPUT_BURST, UTF-8 bytes), a session to type into, and a batch the panes have+// not taken yet holding at most INPUT_BURST decide; dropped input still goes through the splitter's+// `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.+//+// 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+// 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.+//+// THE TYPING SET: the names with accepted input in the last TYPING_WINDOW_MS. It is recomputed at+// most once per TYPING_EVENT_MIN_MS while anyone is in it (which is also what clears it), sent as+// `watch:typing` to every joined viewer when the SET changes (a new order alone is no news), and to a+// viewer right after its meta on every (re)join while it is not empty — otherwise a viewer that+// reconnects mid-typing would never learn it. A connection that loses control or ends leaves it at+// once (the event follows within a tick).//// relay-host never tells us about ends it caused itself (`deny`, `close`): every such path goes// through `ended()`, which reports to the scheduler exactly once (the hosted-service pattern).@@ -95,7 +128,9 @@ import type { RpcErr } from '../../shared/rpc'import { bytesToB64, bytesToHex } from '../../shared/watch-link/bytes'import { deriveWatchLinkKeys } from '../../shared/watch-link/keys'import {+ INPUT_MAX,PASSWORD_MAX,+ TYPING_NAMES_MAX,WATCH_CHAT_CAST,WATCH_EVENT,WATCH_INPUT_CAST,@@ -112,6 +147,9 @@ import {} from '../../shared/watch-link/protocol'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 { isTerminalReport } from '../terminal-reports'import { createStreamFilter, type StreamFilter } from './stream-filter'import { createTokenBucket, type TokenBucket } from './token-bucket'import {@@ -149,6 +187,18 @@ export const VIEWER_BACKLOG_CLOSE = 8 * 1024 * 1024export const UNLOCK_MIN_INTERVAL_MS = 2_000export const WRONG_PER_CONN = 3export const WRONG_PER_LINK = 10+/** A controller's input budget (UTF-8 bytes): its own token bucket, separate from the stream's. */+export const INPUT_RATE = 64 * 1024+export const INPUT_BURST = 256 * 1024+/** Input is collected this long per connection, then delivered as one batch. */+export const INPUT_BATCH_MS = 20+/** The typing set is recomputed (and sent, when it changed) at most this often. */+export const TYPING_EVENT_MIN_MS = 1000+/** A viewer is told its input was dropped at most this often. */+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 = 5000const RATE = 256 * 1024const BURST = 1024 * 1024@@ -161,6 +211,9 @@ export interface WatchJoin {/** The stream is a tmux client's output (`PtyCreateResult.tmuxClient`), which tmux paints on the* alternate screen whatever the pane's application does (R18). */altScreen: boolean+ /** How a controller's input reaches this session's pane (`PtyManager.watcherInputRoute`). `none`+ * (Zellij, an unknown session; also what a missing or unknown answer reads as) refuses control. */+ input: WatcherInputRoute}/**@@ -183,6 +236,9 @@ export interface WatchPty {syncSize(sessionId: string): Promise<boolean>/** The session is still known to the pty layer (an exit can race the join or a capture — R30). */alive(sessionId: string): boolean+ /** Deliver one chunk of a controller's input to the session's PANE (`PtyManager.controlInput`, never+ * a tmux client's key table). Whether it was delivered; a rejection counts as false. */+ input(sessionId: string, chunk: ControlInputChunk): Promise<boolean>}export interface QuietClients {attach(sink: UiSink): number@@ -223,7 +279,7 @@ export interface LinkViewer {waiting: boolean/** Unlocked this Control link with its password and has not lost control since. */controlling: boolean- /** Typed in the last few seconds. False until input is delivered. */+ /** Gave accepted input in the last TYPING_WINDOW_MS, while controlling. */typing: boolean}export interface LinkHost {@@ -264,6 +320,22 @@ interface Conn {wrong: number/** When this viewer's last unlock attempt was taken (a too-soon one is not). */lastUnlockAt: number+ /** When this connection last stopped controlling (INPUT_GRACE_MS); null while it never did. */+ controlStoppedAt: number | null+ /** Bumped every time this connection loses control: a batch from before is never delivered. */+ controlGen: number+ /** The last landed join's input route; null before the first one. */+ input: WatcherInputRoute | null+ splitter: InputSplitter+ inputBucket: TokenBucket+ /** Input collected since the last flush: its chunks, the session it was typed at, its UTF-8 bytes. */+ batch: ControlInputChunk[]+ batchSession: string | null+ batchBytes: number+ batchTimer: unknown+ /** A batch of this connection is in the host-wide flush chain and has not finished. */+ inChain: boolean+ lastDroppedAt: number// The watched session (null while waiting).sessionId: string | nullaltScreen: boolean@@ -300,6 +372,12 @@ interface CaptureSlot {}const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))+/** The same members, in any order (the typing set is a set: a new order alone is no news). */+function sameMembers(a: string[], b: string[]): boolean {+ if (a.length !== b.length) return false+ const set = new Set(b)+ return a.every((x) => set.has(x))+}/** The session a join attached to, if it answered one (a refused join may still have attached). */function joinedSessionId(r: unknown): string | null {@@ -316,8 +394,11 @@ function normalizeJoin(r: unknown): WatchJoin | null {const o = r as Partial<WatchJoin>const dim = (n: unknown): boolean => Number.isInteger(n) && (n as number) > 0if (!dim(o.cols) || !dim(o.rows)) return null- return { sessionId, cols: o.cols as number, rows: o.rows as number, altScreen: o.altScreen === true }+ // 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'+ 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@@ -359,6 +440,15 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin/** Bumped by every change to control (off/on, a new password, the lock, allowControl): a check that* started under an older epoch is void when it returns. */let controlEpoch = 0+ /** One delivery at a time across the link: every controller's batch reaches the pane whole, in+ * flush order. Never rejects (each link is caught), so a failure cannot stall the chain. */+ let inputChain: Promise<void> = Promise.resolve()+ const tracker = createTypingTracker()+ /** The typing set as last sent (names) and the viewers in it (for the owner's view). */+ let typingNames: string[] = []+ let typingIds: string[] = []+ let typingTimer: unknown = null+ let lastTypingAt = -Infinityconst clearTimer = (h: unknown): void => {if (h !== null) deps.clearTimeout(h)@@ -437,6 +527,9 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linc.sessionId = nullc.streaming = falsec.controlling = false+ clearInput(c)+ c.splitter.reset()+ forgetTyping(c)if (sid !== null) leave(c.clientId, sid, c.viewerId, c)safe('the scheduler', () => c.ev.onClose())updateSyncTimer()@@ -652,6 +745,11 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linc.settled = falsec.followUpOnSettle = falsec.waiting = false+ c.input = res.input+ // A terminal that cannot take input: whoever controls it stops (its keystrokes in flight get the+ // grace), and the meta below says `unsupported`.+ const demoted = res.input === 'none' && c.controlling+ if (demoted) loseControl(c)// Meta after EVERY (re)attach: the viewer leaves `waiting` on it (R14).const meta: WatchMeta = {v: WATCH_PROTOCOL_VERSION,@@ -665,6 +763,10 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin// A Control link's state for THIS viewer rides every (re)join; absent on every other role.if (record.role === 'controller') meta.control = controlStateFor(c)if (!send(c, WATCH_EVENT.meta, meta)) return+ // The typing set is otherwise sent only when it changes: a viewer (re)joining mid-typing would+ // never learn it.+ if (typingNames.length > 0) send(c, WATCH_EVENT.typing, { names: typingNames })+ if (demoted) safe('onChange', deps.onChange)clearTimer(c.settleTimer)c.settleTimer = deps.setTimeout(() => {c.settleTimer = null@@ -685,6 +787,8 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linconst clientId = c.clientId// Deferred: a lifecycle event arrives from inside PtyManager's own delivery loop for that session.queueMicrotask(() => leave(clientId, sid, c.viewerId, c))+ // Input typed at this session's screen never reaches the next session.+ abandonInput(c)enterWaiting(c)scheduleRejoin(c)updateSyncTimer()@@ -741,7 +845,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linreturn}if (method === WATCH_INPUT_CAST) {- onInput(c)+ onInput(c, args)return}if (method === WATCH_RELEASE_CAST) {@@ -770,6 +874,8 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin/** This viewer's control state, as meta and every unprompted `watch:control` carry it. */function controlStateFor(c: Conn): WatchControlEvent {const ctl = record.control+ // The watched terminal cannot take input (Zellij, an unknown session): no password changes that.+ if (c.input === 'none') return { state: 'off', reason: 'unsupported' }if (c.controlling && ctl && ctl.enabled && !ctl.locked) return { state: 'controlling' }if (ctl?.locked) return { state: 'locked' }if (!ctl || !ctl.enabled) return { state: 'off' }@@ -789,7 +895,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linreturn}if (state.state === 'locked' || state.state === 'off') {- sendControl(c, { state: state.state, reason: state.state })+ sendControl(c, { state: state.state, reason: state.reason ?? state.state })return}const now = deps.now()@@ -835,9 +941,9 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin/** A check whose answer no longer applies (control changed under it, or it failed): void, not* wrong. Nothing is counted, and the viewer may try again. */function refuseVoid(c: Conn): void {- const state = controlStateFor(c).state- if (state === 'locked' || state === 'off') sendControl(c, { state, reason: state })- else sendControl(c, { state, reason: 'too-soon' })+ const state = controlStateFor(c)+ if (state.state === 'locked' || state.state === 'off') sendControl(c, { state: state.state, reason: state.reason ?? state.state })+ else sendControl(c, { state: state.state, reason: 'too-soon' })}function wrongAttempt(c: Conn): void {c.wrong++@@ -855,7 +961,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin// wiring slip), the next attempt would be verified again: say so loudly, and still demote and tell.if (record.control?.locked !== true) console.error('[watch-link] onControlLocked did not lock the link')for (const c of joinedConns()) {- c.controlling = false+ loseControl(c)sendControl(c, { state: 'locked', reason: 'locked' })}safe('onChange', deps.onChange)@@ -866,24 +972,188 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linconst ctl = record.controlconst usable = !!ctl && ctl.enabled && !ctl.lockedfor (const c of joinedConns()) {- if (!usable) c.controlling = false+ if (!usable) loseControl(c)sendControl(c, controlStateFor(c))}safe('onChange', deps.onChange)}function onRelease(c: Conn): void {if (c.ended || c.joinedAt === null || !c.controlling) return- c.controlling = false+ loseControl(c)sendControl(c, controlStateFor(c))safe('onChange', deps.onChange)}- function onInput(c: Conn): void {++ // --- typing: the input path ---------------------------------------------------------------------------++ /** This connection stops controlling: its pending input is discarded, an open paste forgotten, it+ * leaves the typing set, and its keystrokes still in flight get INPUT_GRACE_MS of silence. */+ function loseControl(c: Conn): void {+ if (!c.controlling) return+ c.controlling = false+ c.controlStoppedAt = deps.now()+ c.controlGen+++ clearInput(c)+ c.splitter.reset()+ forgetTyping(c)+ }+ function clearInput(c: Conn): void {+ clearTimer(c.batchTimer)+ c.batchTimer = null+ c.batch = []+ c.batchBytes = 0+ c.batchSession = null+ }+ /** 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+ clearInput(c)+ c.splitter.discard('')+ if (had) noteDropped(c)+ }+ /** "Some of your input did not reach the terminal", at most once per DROPPED_NOTICE_MIN_MS, and only+ * to a connection that is still controlling (one that lost control was told its new state). */+ function noteDropped(c: Conn): void {+ if (c.ended || controlStateFor(c).state !== 'controlling') return+ const now = deps.now()+ if (now - c.lastDroppedAt < DROPPED_NOTICE_MIN_MS) return+ c.lastDroppedAt = now+ sendControl(c, { state: 'controlling', reason: 'dropped' })+ }+ const withinGrace = (c: Conn): boolean => c.controlStoppedAt !== null && deps.now() - c.controlStoppedAt <= INPUT_GRACE_MS++ function onInput(c: Conn, args: unknown[]): void {if (c.ended) returnif (controlStateFor(c).state !== 'controlling') {+ // Keystrokes in flight when control ended (released, demoted, or the record changed and the+ // host has not been told yet) are dropped silently. From anyone else, or later, a breach.+ if (c.controlling || withinGrace(c)) returnpolicyBreach(c, `cast ${WATCH_INPUT_CAST}`)return}- // Accepted from a controller, and not delivered yet: no viewer byte reaches the pane.+ const p = args[0]+ const data = p && typeof p === 'object' ? (p as { data?: unknown }).data : undefined+ if (typeof data !== 'string' || data.length === 0 || data.length > INPUT_MAX) {+ policyBreach(c, `malformed ${WATCH_INPUT_CAST}`)+ return+ }+ // The viewer's emulator answering the pane's own queries (DA, CPR, a colour) is not typing: every+ // controller would answer every query again into the pane. Not counted against the budget.+ if (isTerminalReport(data)) return+ const bytes = Buffer.byteLength(data, 'utf8')+ const sid = c.sessionId+ // No session to type into (waiting), or over budget — the bucket, or a batch the panes have not+ // taken yet already holding a burst: dropped, and the viewer told. Input is never held for a+ // later session. The splitter still sees it, so a paste it belonged to is discarded whole.+ if (sid === null || c.batchBytes + bytes > INPUT_BURST || !c.inputBucket.take(bytes)) {+ c.splitter.discard(data)+ noteDropped(c)+ return+ }+ if (c.batchSession !== null && c.batchSession !== sid) abandonInput(c)+ c.batchSession = sid+ c.batchBytes += bytes+ appendChunks(c, c.splitter.push(data))+ if (c.name) tracker.note(c.viewerId, c.name, deps.now())+ scheduleTyping()+ if (c.batchTimer === null) {+ c.batchTimer = deps.setTimeout(() => {+ c.batchTimer = null+ flushBatch(c)+ }, INPUT_BATCH_MS)+ }+ }+ /** Adjacent keys merge (up to INPUT_MAX units): one pane delivery per run of typing, not per cast. */+ function appendChunks(c: Conn, chunks: ControlInputChunk[]): void {+ for (const ch of chunks) {+ const last = c.batch[c.batch.length - 1]+ if (ch.kind === 'keys' && last?.kind === 'keys' && last.data.length + ch.data.length <= INPUT_MAX) {+ c.batch[c.batch.length - 1] = { kind: 'keys', data: last.data + ch.data }+ } else c.batch.push(ch)+ }+ }+ /** Hand the connection's batch to the host-wide chain. While its previous batch is still there, this+ * one waits (and keeps collecting) and follows it the moment it finishes: one batch per connection+ * 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).+ appendChunks(c, c.splitter.drain())+ const chunks = c.batch+ const session = c.batchSession+ c.batch = []+ c.batchBytes = 0+ c.batchSession = null+ if (chunks.length === 0 || session === null) return+ const batch = { chunks, session, gen: c.controlGen }+ c.inChain = true+ // A rejection here would skip every later batch of every controller: caught, by name only.+ inputChain = inputChain+ .then(() => deliverBatch(c, batch))+ .catch((err) => warn(null, 'the input chain failed', err instanceof Error ? err.name : 'not an Error'))+ }+ /** Deliver one batch whole, chunk by chunk, re-checking before each that its sender still controls,+ * under the same control period, the session it typed at. A false (or a rejection) stops it. */+ async function deliverBatch(c: Conn, b: { chunks: ControlInputChunk[]; session: string; gen: number }): Promise<void> {+ try {+ for (const chunk of b.chunks) {+ // Control ended since it was typed (and the viewer was told its new state): void, silently.+ if (stopped || c.ended || c.controlGen !== b.gen || controlStateFor(c).state !== 'controlling') return+ // The session it was typed at is gone: what is left did not reach the terminal.+ if (c.sessionId !== b.session) {+ 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')+ }+ if (!ok) {+ noteDropped(c)+ return+ }+ }+ } finally {+ c.inChain = false+ // What it collected meanwhile, when its own timer has already fired.+ if (c.batchTimer === null) safe('an input flush', () => flushBatch(c))+ }+ }++ // --- typing: who is typing --------------------------------------------------------------------------++ function forgetTyping(c: Conn): void {+ tracker.drop(c.viewerId)+ scheduleTyping()+ }+ /** Recompute the typing set now, or at most TYPING_EVENT_MIN_MS after the last time. */+ function scheduleTyping(): void {+ if (stopped || typingTimer !== null) return+ const wait = TYPING_EVENT_MIN_MS - (deps.now() - lastTypingAt)+ if (wait <= 0) evaluateTyping()+ else typingTimer = deps.setTimeout(evaluateTyping, wait)+ }+ function evaluateTyping(): void {+ typingTimer = null+ if (stopped) return+ const now = deps.now()+ lastTypingAt = now+ const names = tracker.names(now).slice(0, TYPING_NAMES_MAX)+ const ids = joinedConns()+ .filter((c) => tracker.typing(c.viewerId, now))+ .map((c) => c.viewerId)+ const namesChanged = !sameMembers(names, typingNames)+ const idsChanged = !sameMembers(ids, typingIds)+ typingNames = names+ typingIds = ids+ if (namesChanged) for (const c of joinedConns()) send(c, WATCH_EVENT.typing, { names })+ if (namesChanged || idsChanged) safe('onChange', deps.onChange)+ // While anyone is in the set, look again in a second (that is also what clears it).+ if (names.length > 0 && typingTimer === null && !stopped) typingTimer = deps.setTimeout(evaluateTyping, TYPING_EVENT_MIN_MS)}// --- listeners and viewer sessions ----------------------------------------------------------------@@ -911,6 +1181,17 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lincontrolling: false,wrong: 0,lastUnlockAt: -Infinity,+ controlStoppedAt: null,+ controlGen: 0,+ input: null,+ splitter: createInputSplitter(),+ inputBucket: createTokenBucket({ ratePerSec: INPUT_RATE, burst: INPUT_BURST, now: deps.now }),+ batch: [],+ batchSession: null,+ batchBytes: 0,+ batchTimer: null,+ inChain: false,+ lastDroppedAt: -Infinity,sessionId: null,altScreen: false,joining: false,@@ -1037,6 +1318,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linfunction viewers(): LinkViewer[] {const out: LinkViewer[] = []+ const now = deps.now()for (const c of conns) {if (c.joinedAt === null || c.ended) continueout.push({@@ -1046,7 +1328,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linwaiting: c.joinRefused && c.sessionId === null,// The effective state: a flag the host has not yet been told to clear never reads as control.controlling: controlStateFor(c).state === 'controlling',- typing: false+ typing: tracker.typing(c.viewerId, now)})}return out@@ -1120,6 +1402,10 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linc.session?.close()ended(c)}+ clearTimer(typingTimer)+ typingTimer = null+ typingNames = []+ typingIds = []safe('onChange', deps.onChange)}diff --git a/src/core/watch-link/pty-seam.test.ts b/src/core/watch-link/pty-seam.test.tsindex 4d601b495..acb601dfb 100644--- a/src/core/watch-link/pty-seam.test.ts+++ b/src/core/watch-link/pty-seam.test.ts@@ -18,7 +18,7 @@ describe('createWatchPty — the WatchPty seam both shells wire (R39)', () => {it('joins with the host ids only (never a size), and reports the JOINED session size and tmux-ness', async () => {const m = fakeManager()const pty = createWatchPty(m as unknown as WatchPtyManager)- expect(await pty.join(7, 'n1', 'v-1')).toEqual({ sessionId: 's1', cols: 120, rows: 40, altScreen: true })+ expect(await pty.join(7, 'n1', 'v-1')).toEqual({ sessionId: 's1', cols: 120, rows: 40, altScreen: true, input: 'none' })expect(m.joinAsWatcher).toHaveBeenCalledWith(7, { persistKey: 'n1', viewerId: 'v-1' })expect(m.sessionSize).toHaveBeenCalledWith('s1')expect(m.kill).not.toHaveBeenCalled()diff --git a/src/core/watch-link/pty-seam.ts b/src/core/watch-link/pty-seam.tsindex e6e5aa047..95224ea6b 100644--- a/src/core/watch-link/pty-seam.ts+++ b/src/core/watch-link/pty-seam.ts@@ -41,11 +41,14 @@ export function createWatchPty(pty: WatchPtyManager, remoteFor: (nodeId: string)pty.kill(clientId, res.sessionId, viewerId)return null}- return { sessionId: res.sessionId, cols: size.cols, rows: size.rows, altScreen: res.tmuxClient === true }+ // Control is not wired to the pane yet: every join answers `none` (control refused) and no+ // input is delivered (fail closed).+ return { sessionId: res.sessionId, cols: size.cols, rows: size.rows, altScreen: res.tmuxClient === true, input: 'none' }},leave: (clientId, sessionId, viewerId) => pty.kill(clientId, sessionId, viewerId),captureVisible: (sessionId) => pty.captureVisible(sessionId),syncSize: (sessionId) => pty.syncWatcherClientSize(sessionId),- alive: (sessionId) => pty.hasSession(sessionId)+ alive: (sessionId) => pty.hasSession(sessionId),+ input: async () => false}}diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.tsindex 9dec131a7..3f8794393 100644--- a/src/core/watch-link/service.test.ts+++ b/src/core/watch-link/service.test.ts@@ -90,11 +90,12 @@ function fakeHosts() {}const fakePty = (over: Partial<WatchPty> = {}): WatchPty => ({- join: async () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true }),+ join: async () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true, input: 'tmux' }),leave: () => {},captureVisible: async () => ({ screen: '', cursor: null }),syncSize: async () => true,alive: () => true,+ input: async () => true,...over})@@ -755,7 +756,7 @@ describe('createWatchLinkService — the host seams', () => {})it('checks the node before every join: absent ends the link (node-gone + revoke), unknown joins (R29/G8)', async () => {- const join = vi.fn(async () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true }))+ const join = vi.fn(async () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: true, input: 'tmux' as const }))const t = service({ pty: fakePty({ join }) })const r = await t.s.create(req())if (!r.ok) throw new Error('create failed')diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.tsindex 3cfcfb742..39da61e2e 100644--- a/src/core/watch-link/service.ts+++ b/src/core/watch-link/service.ts@@ -387,7 +387,8 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerleave: (clientId, sessionId, viewerId) => deps.pty.leave(clientId, sessionId, viewerId),captureVisible: (sessionId) => deps.pty.captureVisible(sessionId),syncSize: (sessionId) => deps.pty.syncSize(sessionId),- alive: (sessionId) => deps.pty.alive(sessionId)+ alive: (sessionId) => deps.pty.alive(sessionId),+ input: (sessionId, chunk) => deps.pty.input(sessionId, chunk)}}diff --git a/src/core/watch-link/service.workspace.test.ts b/src/core/watch-link/service.workspace.test.tsindex 0b3aba56c..4459145b6 100644--- a/src/core/watch-link/service.workspace.test.ts+++ b/src/core/watch-link/service.workspace.test.ts@@ -65,7 +65,7 @@ function linksOver(store: WorkspaceStore) {clients: { attach: () => 1, detach: () => {} },pty: {join: async () => null, leave: () => {}, captureVisible: async () => ({ screen: '', cursor: null }),- syncSize: async () => true, alive: () => true+ syncSize: async () => true, alive: () => true, input: async () => false},emit: () => {},createHost: (): LinkHost => ({