Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(live-links): final review — the brake holds, persisted attempts, remote binding, small edges
reviewa459df601e78
diff --git a/CLAUDE.md b/CLAUDE.mdindex d03df4050..1cdeef29e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -5808,10 +5808,13 @@ one is Pro and the backend is the gate. Reference: **`docs/live-links.md`**. Invon a real tmux: `pane-input.realtmux.test.ts`.- The Control password is a scrypt hash only (no plaintext kept or logged anywhere; every scrypt run inone FIFO gate of 2; `timingSafeEqual`). Host throttles: 1 attempt per 2 s per viewer, 3 wrong end the- connection, 10 wrong across the link lock it (lock persisted, count in memory, only Allow control- again clears it). Owner changes go by direction: narrowing (typing off, a new password) applies at- once, widening (typing on, allow again) only after the write; a failed new-password save rolls back to- the OLD password and the owner is told.+ connection, 10 wrong across the link lock it (lock AND count persisted in the record, so a restart+ resets neither; only Allow control again clears the lock; it and a new password reset the count).+ Owner changes go by direction: narrowing (typing off, a new password) applies at once and is NEVER+ undone by a failed or hung write — the brake must not fail open; the owner is told `'unsaved'` (holds+ until a restart unless a later write lands; Stop ends it for good) — widening (typing on, allow again)+ only after the write. A chunk handed to `PtyManager.controlInput` carries `isCurrent`, asked right+ before it spawns, so it never lands after control ended; a batch holds at most 64 chunks.- Unlimited = `ttlSeconds: 0` → `expiresAt: null`: no expiry timer, never pruned for time. The backendgrants it only with no TTL cap and asks the license's liveness at host-token at most once per 24 h perlicense (dead → 402 → the host stops minting, the view reads `refused`; keygen unreachable failsdiff --git a/docs/live-links.md b/docs/live-links.mdindex 36c9bcfe8..1426fff55 100644--- a/docs/live-links.md+++ b/docs/live-links.md@@ -168,10 +168,18 @@ so it has its own two-line policy rather than a row in a table built for teammat**Why no argument comes from the viewer.** The host joins the node's session itself, and acontroller's input goes to the session the HOST joined, through ids the host chose:`joinAsWatcher(clientId, {persistKey: nodeId, viewerId: v-<8 hex>})` with `joinOnly: true` and-`sizeVote: false` forced after any spread, and for an SSH-project node `requireRemote: true` plus the-`sshRemote` of that project's own ControlMaster from THIS machine's records (a downed master must not-let the local strict probe attach a same-named local orphan). The hosted Viewer path strips a-peer-supplied `sshRemote`; here there is nothing to strip, because nothing is taken.+`sizeVote: false` forced after any spread, and for a node whose session lives in a HOST's tmux+`requireRemote: true` plus the `sshRemote` of the master THIS machine holds for it, from its own+records (a downed master must not let the local strict probe attach a same-named local orphan). Such a+node is every node of an SSH project (that project's own ControlMaster) AND a remote-tmux node in a+LOCAL project (`ssh` + `sshRemoteTmux` on the node, any persisted copy; its master is the one the canvas+spawns it over, `sshConnectionIdForProject` — the project's host attachment). One rule for both,+`watchRemoteFor` (`core/watch-link/pty-seam.ts`); with the master down the join is `requireRemote` with+no master, so an unheld such node never joins the LOCAL socket. Both shells build its records the same+way (`watchRemoteRecords`; the Server Edition has no masters, so such a node is joinable there only while+that core holds its session), and both shells' `controlSupport` asks the same rule (a node in a host's+tmux is not decided by this machine's Zellij choice). The hosted Viewer+path strips a peer-supplied `sshRemote`; here there is nothing to strip, because nothing is taken.## Backpressure and the stream filter@@ -370,19 +378,24 @@ reason?}`. In order:or over 128 code points) counts as wrong and is never verified: an over-long password neverreaches scrypt.5. A wrong password counts. **3 wrong on one connection end it** (`watch:end attempts`; it may- reconnect through the link). **10 wrong across the link LOCK control** (`locked` is persisted in- the record; the count is in memory, so an app restart resets the count, never the lock). The lock- demotes every controller and tells every viewer; the 11th attempt is answered `locked` unverified.- The link keeps working as a Commenter link. Only the owner's **Allow control again** clears the- lock, and it resets the count.+ reconnect through the link). **10 wrong across the link LOCK control.** Both the lock and the+ link-wide count are persisted in the record (`control.locked`, `control.wrong` 0–10): the host+ starts from the record's count and reports each new one (`onWrongAttempt`), which the service puts+ on the record and writes — at most 10 writes per link, the 10th riding the lock's own write — so an+ app restart resets neither (a file written before the count existed reads as 0). The lock demotes+ every controller and tells every viewer; the 11th attempt is answered `locked` unverified. The link+ keeps working as a Commenter link. Only the owner's **Allow control again** clears the lock, and it+ resets the count; a **new password** resets the count too.6. A check is re-checked after its await. An ended viewer, a stopped host, or any change to controlmeanwhile (typing off, a new password, the lock: the control epoch) voids it, uncounted (`too-soon`,or the new state).7. A right password: the viewer is controlling under the name it gave, `{controlling}` is sent, and theowner gets the `control-taken` notice ("Someone using the name “Mert” can now type in- api-server.") and an OS notification, with the existing notification consent, at most one per link- per 5 s, and only while the window is unfocused (main's rule). The name is a claim and is quoted- as one.+ api-server.") and an OS notification. That is a SECURITY event, not an agent finishing, so the+ notification is gated on the notification consent alone (`notifyConsentAsked`: the one-time+ question was answered), never on the agent-done preference (`notifyOnClaudeDone`); at most one per+ link per 5 s, and only while the window is unfocused (main's rule). The name is a claim and is+ quoted as one.**What ends control:** the viewer's Release (`watch:release`), its disconnect, a kick, the ownerturning typing off, a password change, the lock, or a rejoin whose terminal cannot take input. Every@@ -418,13 +431,23 @@ host closes the connection.`INPUT_BATCH_MS` (20 ms) after its first input into ONE delivery chain per link. A connection has atmost one batch in the chain; while it waits there, new input keeps collecting, so a slow panecoalesces input instead of piling up deliveries. Adjacent keys merge, up to `INPUT_MAX`.+- **A batch holds at most `INPUT_CHUNKS_MAX` (64) chunks.** Every chunk is one pane delivery (one tmux+ spawn), and a paste/keys alternation would otherwise cost one per chunk. Past the cap the rest of+ THAT batch is dropped in whole chunks (a paste is never cut; what the splitter still holds — an open+ paste, a held prefix — is discarded with it), later input is dropped until the batch is flushed, and+ the viewer gets the rate-limited `dropped` notice. The next batch starts clean.- **Order**: a connection's input reaches the pane in the order it was typed, and every batch arriveswhole (no other controller's chunk inside it). Across controllers it is roughly flush order.- **Every chunk is re-checked before it goes**: the same control period (`controlGen`, bumped by everyloss of control), still controlling (the record is read live, so typing turned off reaches a batch- mid-way even before the host is told), and still the session it was typed at. A false, a rejection,- or no answer within `PANE_INPUT_DEADLINE_MS` (20 s, counted from hand-over, the same constant in- `PtyManager.controlInput`) stops the batch with the `dropped` notice, and the chain moves on.+ mid-way even before the host is told), and still the session it was typed at. **The same check rides+ the chunk into PtyManager** as `isCurrent`, asked right before the step spawns (or writes), after any+ wait in the per-session chain: a chunk handed over while its sender controlled, still waiting behind a+ slow step (another link's, say) when control ends — Stop, typing off, a new password, the lock, a+ release, a kick — is never delivered (a throwing predicate reads as not current). A false, a+ rejection, or no answer within `PANE_INPUT_DEADLINE_MS` (20 s, counted from hand-over, the same+ constant in `PtyManager.controlInput`) stops the batch with the `dropped` notice, and the chain moves+ on.- A session that ends drops the pending batch and discards an open paste (the viewer is told). Input isnever held for a later session.- Nothing typed is ever logged. The path's three warnings carry an error's name or a fixed sentence@@ -563,8 +586,10 @@ and the drawer put a typing dot on that viewer's row and "can type" on every con### The owner's controlsPer link, in the chip's popover and in the Live chat drawer (one `ControlSection` for both):-**Typing** on/off, **Change password…**, and **Allow control again** while locked. Per viewer: Kick.-Stop ends everything.+**Typing** on/off, **Change password…**, and **Allow control again** while locked. Per viewer: Kick+(on a viewer who is controlling, its note adds "They can unlock again — change the password or turn+typing off to keep them out.": a kicked controller with the password rejoins and unlocks). Stop ends+everything.- **A change that NARROWS access applies at once; one that WIDENS it applies only after the write.**Turning typing off and a new password reach the record and the link host immediately (a leaked@@ -572,11 +597,19 @@ Stop ends everything.on and Allow control again are written first, from a copy of the record, and reach the record andthe host only once that write has landed: nobody can unlock and type during a write the owner is thentold failed. A later change to the same field supersedes one still being written.-- **A failed write answers false, and the owner is told.** A narrowing change is undone when its write- fails or does not answer within 10 s. **A failed save of a new password rolls back to the OLD- password**: the old one unlocks again, and the popover says "The password wasn't changed — try- again. The old one still works." Controllers demoted by the attempt stay demoted and unlock again- with the old password.+- **A narrowing change is the owner's brake, and it never fails open.** It is NEVER undone by a write+ that fails or does not answer within 10 s: typing stays off, the new password stays in force (the old+ one is refused). The call answers `'unsaved'` (`ControlChangeResult`), and the popover and the drawer+ say "Applied, but couldn't be saved — it will undo when nodeterm restarts. Stop the link to end it for+ good." with **Stop sharing** right there (the drawer has no Stop of its own otherwise). A new password+ answered `'unsaved'` is shown once like a saved one. Every write carries the whole list as memory+ holds it, so the next write that lands — any change, a lock, another link — saves the narrowed state,+ and the notice goes with the next change the owner makes that is saved. A **widening** change whose+ write fails answers `false` and changes nothing ("That change didn't take — try again."). A new+ password `false` (refused by the rule, or its hash failed) says "The password wasn't changed — try+ again. The old one still works."+- The done step of a **Control** link's create dialog ignores a click on the scrim until **Copy+ password** was pressed (it holds the only copy of the password); Escape and Done still close it.- A password save in flight holds the popover open (an outside click and Escape do nothing) for up to30 s; after that the owner sees "Couldn't confirm the new password. Check the link before sharing it."- The lock is set on the record synchronously when the host asks for it, written, and never undone by@@ -1002,12 +1035,17 @@ Found while building them:until the broker ends the bridge at its token's lifetime (unverified, item 15). Stop ends it at once.A keygen outage fails open: a lapse during it is noticed once keygen answers again (re-asked every10 min).-- **The wrong-attempt count lives in memory**: an app restart resets it toward the lock (the lock itself- is persisted). Each connection is still held to 1 attempt per 2 s and 3 wrong.+- **The wrong-attempt count is persisted with the lock**, so an app restart no longer resets it (it used+ to: with Unlimited links, nine fresh guesses per restart). What remains: a write of the count that+ fails (logged) or a crash inside the write leaves the disk one count behind, and a new password starts+ the count over by design. Each connection is still held to 1 attempt per 2 s and 3 wrong.- **The hash is not sealed by the keychain**: a person who can read userData can guess offline at scryptspeed. A generated password (~80 bits) is out of reach of that; a typed 8-character one may not be.-- **A failed save of a new password rolls back to the OLD password** (possibly the leaked one); the- owner is told the change failed. Turning typing off is the narrowing that never waits on the disk.+- **A narrowing change that could not be saved holds until a restart, not beyond it.** Typing off and a+ new password are applied at once and never undone by a failed or hung write (the owner is told+ `'unsaved'`), but if no later write lands before nodeterm restarts, the restart brings back the state+ on disk: typing on, or the OLD (possibly leaked) password. The notice says so and puts Stop at hand,+ which ends the link for good.- **The grace**: a connection that lost control has 5 s in which its input is dropped silently ratherthan treated as a breach. A malicious ex-controller gets 5 s of discarded input instead of adisconnect.@@ -1106,9 +1144,9 @@ The Control role, Unlimited links and the Live chat drawer. From the spec (§9):35. **Mac, a shell:** create a Control link to a shell node, open it in a browser on a secondcomputer, Take control with the password, type `ls` and Enter. Expect: the command runs in the- owner's terminal, every viewer sees the output, the owner gets the "can now type" strip and, with- notifications enabled (`notifyOnClaudeDone` on and its one-time consent answered) and the window- unfocused, an OS notification.+ owner's terminal, every viewer sees the output, the owner gets the "can now type" strip and, once the+ one-time notification question has been answered (whatever the agent-done preference says) and with+ the window unfocused, an OS notification.36. **Mac, a Claude session:** the same on a Claude node: type a prompt and Enter, then press Esc whileit works. Expect: the prompt is submitted, Esc interrupts the turn within one batch (no second keyneeded).@@ -1279,3 +1317,28 @@ The Live chat drawer:(stop the last link: the entry is gone).91. An unpinned drawer open on the last link: stop that link. Expect: the drawer stays open and says "Nolive links." (only a PINNED drawer disappears with the last link), and × still closes it.++The final review's fixes:++92. **The brake holds on a failing disk:** make `watch-links.json`'s directory read-only (or the disk+ full), then, with a controller connected, turn Typing off and Change password…. Expect: the+ controller drops back to watching at once, the old password is refused and the new one opens, and+ both the popover and the drawer show "Applied, but couldn't be saved — it will undo when nodeterm+ restarts. Stop the link to end it for good." with a Stop sharing button that stops the link. Make+ the directory writable again and change anything (another link): the notice goes with the next+ saved change, and a restart keeps typing off and the new password.+93. **The count survives a restart:** from a viewer, 3 wrong passwords, reconnect, 3 more, reconnect, 3+ more (9), quit nodeterm and start it again. Expect: the 10th wrong attempt locks the link.+94. **A remote-tmux node in a local project:** in a LOCAL project attach a terminal to an SSH host+ (remote tmux), share it as a Viewer link, then switch the project away so the node is not held, and+ open the link. Expect: the viewer watches the HOST's session (over the attachment's master); with the+ master down the viewer waits, and no `nt-<id>` session appears on the local `node-terminal` socket.+95. **Kick a controller:** the Kick button's tooltip on a controlling viewer (popover and drawer) and the+ popover's note under the list read "… Stop sharing to end it for everyone. They can unlock again —+ change the password or turn typing off to keep them out."; a watcher's Kick reads the first part only.+96. **The done step of a Control link:** after Create, click outside the dialog. Expect: it stays open;+ after Copy password, a click outside closes it; Escape and Done close it at any time.+97. **A paste/keys flood:** as a controller, send a cast alternating 100 one-key presses and 100 short+ pastes in under 20 ms (a script on the viewer page). Expect: the first 64 chunks land, the rest of that+ batch does not, the viewer sees "Some of your input didn't reach the terminal.", and typing right after+ works.diff --git a/src/core/pty-manager.control-input.test.ts b/src/core/pty-manager.control-input.test.tsindex 5d28c9df9..9f9a3428f 100644--- a/src/core/pty-manager.control-input.test.ts+++ b/src/core/pty-manager.control-input.test.ts@@ -82,7 +82,7 @@ type Mgr = {released: Map<string, unknown>getSettings: () => typeof DEFAULT_SETTINGSwatcherInputRoute(id: string): string- controlInput(id: string, chunk: unknown): Promise<boolean>+ controlInput(id: string, chunk: unknown, isCurrent?: () => boolean): Promise<boolean>nodeControlSupport(persistKey: string): string}@@ -379,6 +379,70 @@ describe('controlInput — refusals and order', () => {})})+// Final review, Minor 3: a chunk already handed over waits in the session's chain (behind a slow step+// of another link, say). Its sender may lose control meanwhile — a stop, a demotion — and the link host+// can no longer recall it. `isCurrent`, asked right before the step spawns (or writes), drops it there.+describe('controlInput — isCurrent, asked right before the step runs', () => {+ it('a chunk whose sender stopped controlling while it waited behind a slow step never runs; the chain moves on', async () => {+ let release!: () => void+ const held = new Promise<{ stdout: string }>((r) => (release = () => r({ stdout: '' })))+ let n = 0+ script.answer = () => (++n === 1 ? held : { stdout: '' })+ const { mgr } = await manager({})+ let current = true+ let asked = 0+ const first = mgr.controlInput('sess-1', { kind: 'keys', data: 'a' })+ const keys = mgr.controlInput('sess-1', { kind: 'keys', data: 'b' }, () => (asked++, current))+ const paste = mgr.controlInput('sess-1', { kind: 'paste', text: 'p' }, () => (asked++, current))+ const later = mgr.controlInput('sess-1', { kind: 'keys', data: 'c' }, () => true)+ for (let i = 0; i < 5; i++) await flush()+ expect(calls).toHaveLength(1)+ expect(asked).toBe(0) // not asked at hand-over: only when its turn comes+ current = false // the owner turned typing off, or the link stopped, while they waited+ release()+ expect(await first).toBe(true)+ expect(await keys).toBe(false)+ expect(await paste).toBe(false)+ expect(await later).toBe(true)+ expect(asked).toBe(2)+ expect(calls.map((c) => c.input)).toEqual([keysCommandText(NAME, 'a'), keysCommandText(NAME, 'c')])+ })++ it('a predicate that throws reads as not current (fail closed)', async () => {+ const { mgr } = await manager({})+ expect(+ await mgr.controlInput('sess-1', { kind: 'keys', data: 'a' }, () => {+ throw new Error('boom')+ })+ ).toBe(false)+ expect(calls).toEqual([])+ })++ it('every route honours it: ssh, the plain-shell write, the session host and a direct Windows pane', async () => {+ const sendText = vi.fn(async () => true)+ for (const session of [+ { sshRemote: SSH_REMOTE },+ { tmuxBacked: false },+ { sessionHost: true },+ { nativeWindowsPane: { sendText }, tmuxBacked: false, persistKey: undefined }+ ]) {+ const { mgr, write } = await manager(session)+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'a' }, () => false), JSON.stringify(session)).toBe(false)+ expect(await mgr.controlInput('sess-1', { kind: 'paste', text: 'p' }, () => false)).toBe(false)+ expect(write).not.toHaveBeenCalled()+ }+ expect(calls).toEqual([])+ expect(hostSendKeys).not.toHaveBeenCalled()+ expect(sendText).not.toHaveBeenCalled()+ })++ it('a current chunk runs as before', async () => {+ const { mgr } = await manager({})+ expect(await mgr.controlInput('sess-1', { kind: 'keys', data: 'a' }, () => true)).toBe(true)+ expect(calls.map((c) => c.input)).toEqual([keysCommandText(NAME, 'a')])+ })+})+describe('nodeControlSupport', () => {it('Zellij is unsupported, whether known from a record or from a live session', async () => {const a = await manager(null)diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 85fa9fe9d..e77664783 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -5000,14 +5000,19 @@ export class PtyManager {* waited 15 s behind a slow one has 5 s), answers false when it runs out (a late delivery may still* land, as with any timed-out one), and a chunk with nothing left when its turn comes is dropped* undelivered: whoever handed it over has given up on it.+ *+ * `isCurrent` (the link host's: its sender still controls, in the period it typed in) is asked right+ * before the step runs — after any wait behind a slow step, immediately before the spawn or the+ * write, nothing awaited in between: false (or a throw) and the chunk is never delivered (false).+ * A chunk handed over while its sender controlled must not land after a stop or a demotion.*/- controlInput(sessionId: string, chunk: ControlInputChunk): Promise<boolean> {+ controlInput(sessionId: string, chunk: ControlInputChunk, isCurrent?: () => boolean): Promise<boolean> {const handedAt = Date.now()const prev = this.controlInputChains.get(sessionId) ?? Promise.resolve(true)const step = prev.then(() => {const left = PANE_INPUT_DEADLINE_MS - (Date.now() - handedAt)- return left <= 0 ? false : settleWithin(this.deliverControlInput(sessionId, chunk), left)+ return left <= 0 ? false : settleWithin(this.deliverControlInput(sessionId, chunk, isCurrent), left)}).catch(() => false)this.controlInputChains.set(sessionId, step)@@ -5020,7 +5025,11 @@ export class PtyManager {/** The tail of each session's `controlInput` chain; deleted when the tail settles. */private readonly controlInputChains = new Map<string, Promise<boolean>>()- private async deliverControlInput(sessionId: string, chunk: ControlInputChunk): Promise<boolean> {+ private async deliverControlInput(+ sessionId: string,+ chunk: ControlInputChunk,+ isCurrent?: () => boolean+ ): Promise<boolean> {// The chunk arrives from a viewer over the network: its shape is checked, not assumed.const c = chunk as { kind?: unknown; data?: unknown; text?: unknown } | nullconst keys = c?.kind === 'keys' && typeof c.data === 'string'@@ -5033,6 +5042,17 @@ export class PtyManager {// a paste that sanitizes to nothing has nothing to do.if (keys && (c.data as string).length === 0) return falseif (paste && sanitizePasteText(c.text as string).length === 0) return true+ // Right before the spawn or the write (synchronous from here to it, on every route): a sender that+ // stopped controlling while this chunk waited never gets it delivered. A throw reads as not current.+ if (isCurrent) {+ let current = false+ try {+ current = isCurrent() === true+ } catch {+ current = false+ }+ if (!current) return false+ }try {switch (route) {case 'tmux': {diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.tsindex 21c4341ef..10565cee2 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_CHUNKS_MAX,INPUT_DELIVERY_TIMEOUT_MS,INPUT_GRACE_MS,INPUT_RATE,@@ -118,6 +119,8 @@ interface SetupOpts {verifyPassword?: (pw: string) => Promise<boolean>/** Replaces the service's lock (which sets `record.control.locked`); still counted in `locks()`. */onControlLocked?: () => void+ /** Replaces the service's record of the link-wide wrong count; still recorded in `wrongs`. */+ onWrongAttempt?: (count: number) => voidjoin?: (clientId: number, nodeId: string, viewerId: string) => Promise<JoinAnswer | null> | JoinAnswer | nullcapture?: (sid: string) => Promise<VisibleCapture> | VisibleCapturealive?: (sid: string) => boolean@@ -149,6 +152,10 @@ function setup(o: SetupOpts = {}) {const joinTimes: number[] = []/** Every `pty.input` call, in order: [sessionId, chunk]. */const inputs: [string, ControlInputChunk][] = []+ /** Every `pty.input` call's `isCurrent` predicate, in the same order. */+ const currents: ((() => boolean) | undefined)[] = []+ /** Every link-wide wrong count the host reported (`onWrongAttempt`), in order. */+ const wrongs: number[] = []let mints = 0let changes = 0let verifies = 0@@ -179,8 +186,9 @@ function setup(o: SetupOpts = {}) {return true},alive: (sid) => (o.alive ? o.alive(sid) : true),- input: async (sid, chunk) => {+ input: async (sid, chunk, isCurrent) => {inputs.push([sid, chunk])+ currents.push(isCurrent)return o.input ? o.input(sid, chunk) : true}}@@ -233,11 +241,17 @@ function setup(o: SetupOpts = {}) {locks++if (o.onControlLocked) o.onControlLocked()else if (record.control) record.control.locked = true+ },+ // What the service does: the count goes on the record (and to disk).+ onWrongAttempt: (count) => {+ wrongs.push(count)+ if (o.onWrongAttempt) o.onWrongAttempt(count)+ else if (record.control) record.control.wrong = count}})hosts.push(host)return {- record, host, peers, sinks, left, calls, joinArgs, joinTimes, inputs, chats, joined, gone,+ record, host, peers, sinks, left, calls, joinArgs, joinTimes, inputs, currents, wrongs, chats, joined, gone,keys: deriveWatchLinkKeys(secret),mints: () => mints,/** How many times the host reported a change to the registry (`onChange`). */@@ -1105,7 +1119,7 @@ describe('createLinkHost — control', () => {beforeAll(async () => {HASH = await hashControlPassword(PW)})- const ctl = (over: Partial<WatchLinkControlRecord> = {}): WatchLinkControlRecord => ({ enabled: true, locked: false, ...HASH, ...over })+ const ctl = (over: Partial<WatchLinkControlRecord> = {}): WatchLinkControlRecord => ({ enabled: true, locked: false, wrong: 0, ...HASH, ...over })const controlOf = (v: Viewer | RawPeer): WatchControlEvent[] => v.named(WATCH_EVENT.control) as WatchControlEvent[]const metaOf = (v: Viewer, n = 0): WatchMeta => v.named(WATCH_EVENT.meta)[n] as WatchMeta/** Send one cast and wait for the `watch:control` that answers it. */@@ -1451,6 +1465,68 @@ describe('createLinkHost — control', () => {expect(await unlock(watcher, 'Ada', PW)).toEqual({ state: 'controlling' })})+ // Final review, Minor 2: the link-wide wrong count is the service's to keep (persisted beside+ // `locked`), so an app restart no longer hands out nine fresh guesses. The host starts from the+ // record's count and reports every new one.+ it('the link-wide count starts from the record: a host built from a record at 9 (a restart) locks on its next wrong attempt', async () => {+ const clock = manualClock()+ const t = controller({ clock, control: ctl({ wrong: WRONG_PER_LINK - 1 }), verifyPassword: async (pw) => pw === PW })+ t.host.start()+ const v = await openViewer(t, 0)+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)+ const before = controlOf(v).length+ expect(v.c.unlock('Eve', WRONG)).toBe(true)+ await vi.waitFor(() => expect(controlOf(v).slice(before)).toEqual([+ { state: 'available', reason: 'wrong' },+ { state: 'locked', reason: 'locked' }+ ]))+ expect(t.locks()).toBe(1)+ expect(t.wrongs).toEqual([WRONG_PER_LINK])+ })++ it('every wrong attempt reports the new link-wide count, from the one the record holds', async () => {+ const clock = manualClock()+ const t = controller({ clock, control: ctl({ wrong: 4 }), verifyPassword: async (pw) => pw === PW })+ t.host.start()+ const v = await openViewer(t, 0)+ for (let i = 0; i < 2; i++) {+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)+ expect(await unlock(v, 'Eve', WRONG)).toEqual({ state: 'available', reason: 'wrong' })+ }+ // A malformed attempt counts too.+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)+ expect(await unlock(v, 'Eve', '')).toEqual({ state: 'available', reason: 'wrong' })+ expect(t.wrongs).toEqual([5, 6, 7])+ expect(t.record.control!.wrong).toBe(7)+ expect(t.locks()).toBe(0)+ })++ it('a password change resets the link-wide count: a host at 9 does not lock on the next wrong attempt', async () => {+ const clock = manualClock()+ const t = controller({ clock, control: ctl({ wrong: WRONG_PER_LINK - 1 }), verifyPassword: async (pw) => pw === PW })+ t.host.start()+ const v = await openViewer(t, 0)+ t.record.control!.wrong = 0 // what the service does with the new hash+ t.host.passwordChanged()+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)+ expect(await unlock(v, 'Eve', WRONG)).toEqual({ state: 'available', reason: 'wrong' })+ expect(t.locks()).toBe(0)+ expect(t.wrongs).toEqual([1])+ })++ it('a record count outside 0..10 (a hand edit) is read as the nearest bound, never as more guesses', async () => {+ for (const [wrong, next] of [[-5, 1], [Number.NaN, 1], [1.5, 2], [99, WRONG_PER_LINK]] as const) {+ const clock = manualClock()+ const t = controller({ clock, control: ctl({ wrong }), verifyPassword: async (pw) => pw === PW })+ t.host.start()+ const v = await openViewer(t, 0)+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)+ await unlock(v, 'Eve', WRONG)+ expect(t.wrongs, String(wrong)).toEqual([next])+ t.host.stop('revoked')+ }+ })+// --- release and the owner's changes ----------------------------------------------------------------it('release drops a controller back to available; from anyone else it is ignored', async () => {@@ -2376,5 +2452,87 @@ describe('createLinkHost — control', () => {await clock.advance(INPUT_BATCH_MS * 10)expect(t.inputs).toEqual([])})++ // Final review, Minor 3: a chunk already handed to PtyManager waits in its per-session chain (a+ // slow step of another link, say). The host gives it a predicate PtyManager asks right before it+ // spawns: false from the moment its sender stops controlling, so it never lands after control ended.+ it('every chunk handed to the pane carries a predicate that turns false the moment control ends', async () => {+ for (const end of ['record-off', 'off', 'release', 'password', 'lock', 'kick', 'stop'] as const) {+ const held = holdFirst()+ const { t, clock, vs } = await controllers(['Ada'], { input: held.input })+ await type(vs[0], 'a', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.currents).toHaveLength(1))+ const isCurrent = t.currents[0]+ expect(typeof isCurrent, end).toBe('function')+ expect(isCurrent!(), end).toBe(true)+ if (end === 'record-off') t.record.control!.enabled = false // read live, before the host is told+ else if (end === 'off') {+ t.record.control!.enabled = false+ t.host.controlChanged()+ } else if (end === 'release') expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })+ else if (end === 'password') t.host.passwordChanged()+ else if (end === 'lock') {+ t.record.control!.locked = true+ t.host.controlChanged()+ } else if (end === 'kick') expect(t.host.kick(t.host.viewers()[0].viewerId)).toBe(true)+ else t.host.stop('revoked')+ expect(isCurrent!(), end).toBe(false)+ held.release()+ t.host.stop('revoked')+ }+ })++ it('a predicate never answers true for a sender that unlocked AGAIN: the period it was typed in is over', async () => {+ const held = holdFirst()+ const { t, clock, vs } = await controllers(['Ada'], { input: held.input })+ await type(vs[0], 'a', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.currents).toHaveLength(1))+ const isCurrent = t.currents[0]!+ expect(await ask(vs[0], () => vs[0].c.release())).toEqual({ state: 'available' })+ await clock.advance(UNLOCK_MIN_INTERVAL_MS)+ expect(await unlock(vs[0], 'Ada', PW)).toEqual({ state: 'controlling' })+ expect(isCurrent()).toBe(false)+ held.release()+ })++ // Final review, Minor 8: a paste/keys alternation costs one pane delivery (one tmux spawn) per+ // chunk. A batch holds at most INPUT_CHUNKS_MAX; the rest of THAT batch is dropped in whole chunks+ // (a paste is never cut), with the rate-limited dropped notice, and the next batch works.+ it(`a batch holds at most INPUT_CHUNKS_MAX (${INPUT_CHUNKS_MAX}) chunks: the rest of it is dropped whole, with one notice`, async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ const pair = (i: number): string => `k${i}${PASTE_START}p${i}${PASTE_END}`+ const flood = Array.from({ length: INPUT_CHUNKS_MAX }, (_, i) => pair(i)).join('')+ expect(flood.length).toBeLessThanOrEqual(INPUT_MAX)+ await type(vs[0], flood, clock) // 2 × INPUT_CHUNKS_MAX chunks in one cast+ // More of the same batch, before it flushes: a paste opened here and closed in the next cast…+ await type(vs[0], `late${PASTE_START}half`, clock)+ await type(vs[0], `-of-a-paste${PASTE_END}tail`, clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.inputs).toHaveLength(INPUT_CHUNKS_MAX))+ await clock.flush()+ await settleReal()+ const want = Array.from({ length: INPUT_CHUNKS_MAX / 2 }, (_, i) => [`s1:keys:k${i}`, `s1:paste:p${i}`]).flat()+ expect(delivered(t)).toEqual(want)+ // …is dropped whole: no part of the late paste, nothing typed after it in that batch.+ expect(delivered(t).some((d) => /late|half|tail/.test(d))).toBe(false)+ expect(dropped(vs[0])).toEqual([{ state: 'controlling', reason: 'dropped' }])+ expect(vs[0].log.closed).toBe(0)+ // The next batch is a new one.+ await type(vs[0], 'x', clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(delivered(t).at(-1)).toBe('s1:keys:x'))+ })++ it('a batch of exactly INPUT_CHUNKS_MAX chunks is delivered whole, with no notice', async () => {+ const { t, clock, vs } = await controllers(['Ada'])+ const flood = Array.from({ length: INPUT_CHUNKS_MAX / 2 }, (_, i) => `k${i}${PASTE_START}p${i}${PASTE_END}`).join('')+ await type(vs[0], flood, clock)+ await clock.advance(INPUT_BATCH_MS)+ await vi.waitFor(() => expect(t.inputs).toHaveLength(INPUT_CHUNKS_MAX))+ await settleReal()+ expect(dropped(vs[0])).toEqual([])+ })})})diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.tsindex f835322dd..e7f9b5ecb 100644--- a/src/core/watch-link/link-host.ts+++ b/src/core/watch-link/link-host.ts@@ -24,8 +24,10 @@// (`watch:control`), and every throttle is here: one attempt per UNLOCK_MIN_INTERVAL_MS per viewer and// one verification in flight per link (both `too-soon`, not counted); a malformed attempt counts as// wrong and is never verified, so an over-long password never reaches scrypt; WRONG_PER_CONN wrong-// 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+// attempts end that connection (`attempts`), WRONG_PER_LINK across the link lock it. The link count is+// the record's: the host starts from `record.control.wrong` and reports every new count to the service+// (`onWrongAttempt`), which writes it — an app restart does not reset it. `allowControl` and a password+// change reset 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. 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@@ -37,7 +39,10 @@// 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+// `{controlling, dropped}` at most once per DROPPED_NOTICE_MIN_MS. A batch holds at most+// INPUT_CHUNKS_MAX chunks (each chunk is one pane delivery — a tmux spawn — and a paste/keys alternation+// would otherwise cost one per chunk): past it, the rest of THAT batch is dropped in whole chunks, the+// same way and with the same notice. 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, through `pty.input`// (PtyManager's pane delivery, never a tmux client's key table). A connection has at most one batch in@@ -47,7 +52,10 @@// 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+// still the session it was typed at. The same check rides the chunk as a predicate (`isCurrent`), which+// PtyManager asks right before the step spawns: a chunk handed over and still waiting in its per-session+// chain (behind a slow step) never lands after its sender stopped controlling. 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).@@ -165,7 +173,7 @@ import {watcherAccess,wrapWatcherSink} from './watcher-policy'-import type { WatchLinkRecord } from './store'+import { CONTROL_WRONG_MAX, type WatchLinkRecord } from './store'export const MAX_VIEWERS_PER_LINK = 10/** While the link is full (no idle listener, so no mint), how often the API is asked whether the link@@ -192,12 +200,15 @@ export const VIEWER_BACKLOG_CLOSE = 8 * 1024 * 1024* 10 wrong across the link lock control until the owner allows it again. */export const UNLOCK_MIN_INTERVAL_MS = 2_000export const WRONG_PER_CONN = 3-export const WRONG_PER_LINK = 10+export const WRONG_PER_LINK = CONTROL_WRONG_MAX/** A controller's input budget (UTF-8 bytes): its own token bucket, separate from the stream's. */export const INPUT_RATE = 64 * 1024export const INPUT_BURST = 256 * 1024/** Input is collected this long per connection, then delivered as one batch. */export const INPUT_BATCH_MS = 20+/** At most this many chunks in one batch: each is a pane delivery (a tmux spawn). Past it, the rest of+ * that batch is dropped (whole chunks: a paste is never cut) with the `dropped` notice. */+export const INPUT_CHUNKS_MAX = 64/** 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. */@@ -246,8 +257,10 @@ export interface WatchPty {/** 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>+ * a tmux client's key table). Whether it was delivered; a rejection counts as false. `isCurrent` is+ * asked right before the delivery runs (the chunk may wait behind a slow one): false — its sender no+ * longer controls, in the period it typed in — and it is never delivered. */+ input(sessionId: string, chunk: ControlInputChunk, isCurrent?: () => boolean): Promise<boolean>}export interface QuietClients {attach(sink: UiSink): number@@ -275,6 +288,10 @@ export interface LinkHostDeps {/** WRONG_PER_LINK wrong attempts across the link. The service sets `record.control.locked = true`* before it returns (the host reads the record live and never writes it). */onControlLocked(): void+ /** A wrong unlock attempt: the link-wide count is now `count` (1..WRONG_PER_LINK). The service puts it+ * on `record.control.wrong` and writes it (the 10th rides the lock's own write), so a restart does+ * not reset it. Called before `onControlLocked`. */+ onWrongAttempt(count: number): void}export type LinkRuntimeStatus = 'live' | 'reconnecting' | 'refused'export interface LinkViewer {@@ -303,7 +320,8 @@ export interface LinkHost {/** The service changed `record.control.enabled` (or cleared `locked`): off or locked demotes every* controller, and every joined viewer is told its state. */controlChanged(): void- /** The password was replaced: every controller is demoted and must unlock with the new one. */+ /** The password was replaced: every controller is demoted and must unlock with the new one, and the+ * link-wide wrong count starts over (the service resets the record's). */passwordChanged(): void/** The owner cleared the lock: the link-wide wrong count starts over, then as `controlChanged`. */allowControl(): void@@ -340,6 +358,8 @@ interface Conn {inputBucket: TokenBucket/** Input collected since the last flush: its chunks, the session it was typed at, its UTF-8 bytes. */batch: ControlInputChunk[]+ /** The batch reached INPUT_CHUNKS_MAX: the rest of it is dropped until it is flushed. */+ batchFull: booleanbatchSession: string | nullbatchBytes: numberbatchTimer: unknown@@ -379,6 +399,13 @@ interface Conn {warned: Set<string>}+/** One connection's batch in the flush chain: its chunks, the session typed at, the control period. */+interface Batch {+ chunks: ControlInputChunk[]+ session: string+ gen: number+}+interface CaptureSlot {current: { epoch: number; result: Promise<VisibleCapture> } | null/** The one rerun queued behind `current`, shared by every keyframe that needs a newer capture. */@@ -425,6 +452,14 @@ function readUnlock(p: unknown): { name: string; password: string } | null {return { name, password }}+/** The link-wide wrong count a record holds, as an integer 0..WRONG_PER_LINK: a hand edit cannot buy+ * guesses (the store refuses anything else on load; this is the host's own belt). */+function storedWrong(r: WatchLinkRecord): number {+ const n = r.control?.wrong+ if (typeof n !== 'number' || Number.isNaN(n)) return 0+ return Math.min(WRONG_PER_LINK, Math.max(0, Math.floor(n)))+}+function normalizeCapture(c: unknown): VisibleCapture {if (!c || typeof c !== 'object' || typeof (c as VisibleCapture).screen !== 'string') return unavailableCapture()if ((c as VisibleCapture).unavailable === true) return unavailableCapture()@@ -446,8 +481,9 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linlet syncTimer: unknown = nulllet stopped = falseconst warnedHost = new Set<string>()- /** Wrong unlock attempts across the link (in memory: only the lock is persisted, by the service). */- let linkWrong = 0+ /** Wrong unlock attempts across the link, starting from the record's (the service persists every new+ * count, so an app restart does not reset it). */+ let linkWrong = storedWrong(record)/** A password check is in flight: one per link. */let verifying = false/** Bumped by every change to control (off/on, a new password, the lock, allowControl): a check that@@ -964,6 +1000,9 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linfunction wrongAttempt(c: Conn): void {c.wrong++linkWrong+++ // The service records (and writes) the link-wide count before any lock below.+ const count = Math.min(linkWrong, WRONG_PER_LINK)+ safe('onWrongAttempt', () => deps.onWrongAttempt(count))sendControl(c, { state: controlStateFor(c).state, reason: 'wrong' })if (linkWrong >= WRONG_PER_LINK) lockLink()if (c.wrong >= WRONG_PER_CONN) endConn(c, 'attempts')@@ -1017,6 +1056,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): LinclearTimer(c.batchTimer)c.batchTimer = nullc.batch = []+ c.batchFull = falsec.batchBytes = 0c.batchSession = null}@@ -1059,10 +1099,11 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linif (isTerminalReport(data)) returnconst 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)) {+ // No session to type into (waiting), or over budget — a batch already holding INPUT_CHUNKS_MAX+ // chunks, 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.batchFull || c.batchBytes + bytes > INPUT_BURST || !c.inputBucket.take(bytes)) {c.splitter.discard(data)noteDropped(c)return@@ -1080,15 +1121,28 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin}, INPUT_BATCH_MS)}}- /** Adjacent keys merge (up to INPUT_MAX units): one pane delivery per run of typing, not per cast. */+ /** Adjacent keys merge (up to INPUT_MAX units): one pane delivery per run of typing, not per cast. A+ * batch holds at most INPUT_CHUNKS_MAX chunks: the first chunk past it ends the batch's intake. */function appendChunks(c: Conn, chunks: ControlInputChunk[]): void {for (const ch of chunks) {+ if (c.batchFull) returnconst 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 if (c.batch.length >= INPUT_CHUNKS_MAX) {+ batchFilled(c)+ return} else c.batch.push(ch)}}+ /** The batch is full: this chunk and the rest of the batch are dropped, in whole chunks — what the+ * splitter still holds belongs to that rest (an open paste is discarded whole, a held prefix is never+ * keys), and later input is dropped until the batch is flushed. The viewer is told. */+ function batchFilled(c: Conn): void {+ c.batchFull = true+ c.splitter.discard('')+ noteDropped(c)+ }/** 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. */@@ -1099,6 +1153,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linconst chunks = c.batchconst session = c.batchSessionc.batch = []+ c.batchFull = falsec.batchBytes = 0c.batchSession = nullif (chunks.length === 0 || session === null) return@@ -1109,19 +1164,22 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin.then(() => deliverBatch(c, batch)).catch((err) => warn(null, 'the input chain failed', err instanceof Error ? err.name : 'not an Error'))}+ /** The batch's sender still controls, in the control period it typed in. */+ const stillControls = (c: Conn, b: Batch): boolean =>+ !stopped && !c.ended && c.controlGen === b.gen && controlStateFor(c).state === 'controlling'/** 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> {+ async function deliverBatch(c: Conn, b: Batch): 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+ if (!stillControls(c, b)) 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}- const ok = await deliverChunk(c, b.session, chunk)+ const ok = await deliverChunk(c, b, chunk)if (!ok) {noteDropped(c)return@@ -1137,7 +1195,7 @@ 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> {+ function deliverChunk(c: Conn, b: Batch, chunk: ControlInputChunk): Promise<boolean> {return new Promise<boolean>((resolve) => {let settled = falseconst slot: { timer: unknown; settle(ok: boolean): void } = {@@ -1162,8 +1220,11 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linwarn(c, 'delivering input failed', err instanceof Error ? err.name : 'not an Error')slot.settle(false)}+ // The same check as before this chunk, asked again by PtyManager right before it runs: a chunk+ // still waiting in its per-session chain when its sender stops controlling never lands.+ const isCurrent = (): boolean => stillControls(c, b) && c.sessionId === b.sessiontry {- void Promise.resolve(deps.pty.input(session, chunk)).then((ok) => slot.settle(ok === true), failed)+ void Promise.resolve(deps.pty.input(b.session, chunk, isCurrent)).then((ok) => slot.settle(ok === true), failed)} catch (err) {failed(err)}@@ -1233,6 +1294,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linsplitter: createInputSplitter(),inputBucket: createTokenBucket({ ratePerSec: INPUT_RATE, burst: INPUT_BURST, now: deps.now }),batch: [],+ batchFull: false,batchSession: null,batchBytes: 0,batchTimer: null,@@ -1495,6 +1557,8 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin},passwordChanged() {if (stopped || record.role !== 'controller') return+ // A new password starts the link-wide count over (the service resets the record's too).+ linkWrong = 0controlEpoch++for (const c of joinedConns()) {if (!c.controlling) continuediff --git a/src/core/watch-link/pty-seam.test.ts b/src/core/watch-link/pty-seam.test.tsindex 8feee2781..fa8deacc2 100644--- a/src/core/watch-link/pty-seam.test.ts+++ b/src/core/watch-link/pty-seam.test.ts@@ -1,5 +1,6 @@import { describe, it, expect, vi } from 'vitest'-import { createWatchPty, type WatchPtyManager } from './pty-seam'+import { createWatchPty, watchRemoteFor, watchRemoteRecords, type WatchPtyManager, type WatchRemoteRecords } from './pty-seam'+import { sshAttachmentId } from '../../shared/ssh'import type { PtyCreateResult } from '../../shared/types'function fakeManager(over: Partial<Record<keyof WatchPtyManager, unknown>> = {}) {@@ -95,9 +96,147 @@ describe('createWatchPty — the WatchPty seam both shells wire (R39)', () => {const m = fakeManager()const pty = createWatchPty(m as unknown as WatchPtyManager)expect(await pty.input('s1', { kind: 'keys', data: 'ls\r' })).toBe(true)- expect(m.controlInput).toHaveBeenCalledWith('s1', { kind: 'keys', data: 'ls\r' })+ expect(m.controlInput.mock.calls[0].slice(0, 2)).toEqual(['s1', { kind: 'keys', data: 'ls\r' }])m.controlInput.mockResolvedValueOnce(false)expect(await pty.input('s1', { kind: 'paste', text: 'x' })).toBe(false)- expect(m.controlInput).toHaveBeenLastCalledWith('s1', { kind: 'paste', text: 'x' })+ expect(m.controlInput.mock.calls[1].slice(0, 2)).toEqual(['s1', { kind: 'paste', text: 'x' }])+ })++ it("the link host's isCurrent predicate reaches controlInput unchanged (asked right before the step runs)", async () => {+ const m = fakeManager()+ const pty = createWatchPty(m as unknown as WatchPtyManager)+ const isCurrent = (): boolean => false+ await pty.input('s1', { kind: 'keys', data: 'a' }, isCurrent)+ expect(m.controlInput).toHaveBeenCalledWith('s1', { kind: 'keys', data: 'a' }, isCurrent)+ })+})++// Final review, Minor 4: a watcher join must never reach the LOCAL socket for a node whose session+// lives in a HOST's tmux — an SSH project's node, and also a remote-tmux node in a LOCAL project+// (`ssh` + `sshRemoteTmux` on the node), whose master is the project's host attachment.+describe('watchRemoteFor — where a watcher join goes, from the shell\'s own records', () => {+ const server = { host: 'box', user: 'alice' }+ const other = { host: 'other', user: 'bob', port: 2222 }+ const ref = (conn: object, controlPath: string, remoteCwd?: string) => ({ conn: conn as never, controlPath, remoteCwd })+ function records(o: {+ sshProject?: string+ copies?: { projectId: string; projectServer?: unknown; ssh?: unknown; sshRemoteTmux?: unknown }[]+ refs?: Record<string, ReturnType<typeof ref>>+ }): WatchRemoteRecords & { asked: string[] } {+ const asked: string[] = []+ return {+ asked,+ sshProjectIdForNode: () => o.sshProject,+ nodeCopies: () => o.copies ?? [],+ refFor: (id) => {+ asked.push(id)+ return o.refs?.[id]+ }+ }+ }++ it('an SSH project\'s node: requireRemote, over that project\'s master when it is up', () => {+ expect(watchRemoteFor('n1', records({ sshProject: 'p-ssh', refs: { 'p-ssh': ref(server, '/cm/1', '/srv') } }))).toEqual({+ requireRemote: true,+ sshRemote: { conn: server, controlPath: '/cm/1', remoteCwd: '/srv' }+ })+ expect(watchRemoteFor('n1', records({ sshProject: 'p-ssh' }))).toEqual({ requireRemote: true })+ })++ it('a remote-tmux node in a LOCAL project: requireRemote, over its host attachment (`sshAttachmentId`)', () => {+ const attachment = sshAttachmentId('p-local', other as never)+ const r = records({+ copies: [{ projectId: 'p-local', ssh: other, sshRemoteTmux: true }],+ refs: { [attachment]: ref(other, '/cm/2') }+ })+ expect(watchRemoteFor('n1', r)).toEqual({+ requireRemote: true,+ sshRemote: { conn: other, controlPath: '/cm/2', remoteCwd: '~' }+ })+ expect(r.asked).toEqual([attachment])+ })++ it('an unheld remote-tmux node whose master is down still never joins the LOCAL socket', () => {+ expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local', ssh: other, sshRemoteTmux: true }] }))).toEqual({+ requireRemote: true+ })+ // `sshRemoteTmux` alone (a binding that lost its host) is remote all the same — the renderer's rule.+ expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local', ssh: { user: 'x' }, sshRemoteTmux: true }] }))).toEqual({+ requireRemote: true+ })+ })++ it("a remote-tmux node on its own project's host goes over the PROJECT's master (`sshConnectionIdForProject`)", () => {+ const r = records({+ copies: [{ projectId: 'p-x', projectServer: server, ssh: { host: 'box', user: 'someone-else' }, sshRemoteTmux: true }],+ refs: { 'p-x': ref(server, '/cm/3', '/home/alice') }+ })+ expect(watchRemoteFor('n1', r)).toEqual({+ requireRemote: true,+ sshRemote: { conn: server, controlPath: '/cm/3', remoteCwd: '/home/alice' }+ })+ })++ it('a local node, and a standalone ssh terminal node (its ssh runs in LOCAL tmux), are local', () => {+ expect(watchRemoteFor('n1', records({}))).toEqual({})+ expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local' }] }))).toEqual({})+ expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local', ssh: other }] }))).toEqual({})+ expect(watchRemoteFor('n1', records({ copies: [{ projectId: 'p-local', ssh: other, sshRemoteTmux: 'true' }] }))).toEqual({})+ })++ it('any copy that says remote-tmux makes the join remote (fail closed), and the first copy with a live master serves it', () => {+ const attachment = sshAttachmentId('p-b', other as never)+ const r = records({+ copies: [+ { projectId: 'p-a' },+ { projectId: 'p-b', ssh: other, sshRemoteTmux: true }+ ],+ refs: { [attachment]: ref(other, '/cm/4') }+ })+ expect(watchRemoteFor('n1', r)).toMatchObject({ requireRemote: true, sshRemote: { controlPath: '/cm/4' } })+ })++ it("both shells read the records the same way: the workspace store's own copies, each with its project's server", () => {+ const canvases = [+ { id: 'p-a', nodes: [{ id: 'n1' }] },+ { id: 'p-b', nodes: [{ id: 'n2' }, { id: 'n1', ssh: other, sshRemoteTmux: true }] }+ ]+ let scans = 0+ const store = {+ sshProjectIdForNode: (id: string) => (id === 'n-ssh' ? 'p-ssh' : undefined),+ projectIdsForNode: (id: string) => (id === 'n1' ? ['p-a', 'p-b'] : []),+ persistedCanvases: () => {+ scans+++ return canvases as never+ },+ projectTargetInfo: (id: string) => (id === 'p-b' ? { ssh: { server, remoteCwd: '~' }, name: 'B' } : { name: id })+ }+ const asked: string[] = []+ const recs = watchRemoteRecords(store, (id) => {+ asked.push(id)+ return undefined+ })+ expect(recs.sshProjectIdForNode('n-ssh')).toBe('p-ssh')+ expect(recs.nodeCopies('n1')).toEqual([+ { projectId: 'p-a', projectServer: undefined, ssh: undefined, sshRemoteTmux: undefined },+ { projectId: 'p-b', projectServer: server, ssh: other, sshRemoteTmux: true }+ ])+ // A node no project holds costs no scan of every project file.+ scans = 0+ expect(recs.nodeCopies('nowhere')).toEqual([])+ expect(scans).toBe(0)+ expect(watchRemoteFor('n1', recs)).toEqual({ requireRemote: true })+ expect(asked).toEqual([sshAttachmentId('p-b', other as never)])+ })++ it('records that throw read as remote-unknown: requireRemote, never the local socket', () => {+ const bad: WatchRemoteRecords = {+ sshProjectIdForNode: () => {+ throw new Error('index not loaded')+ },+ nodeCopies: () => [],+ refFor: () => undefined+ }+ expect(watchRemoteFor('n1', bad)).toEqual({ requireRemote: true })})})diff --git a/src/core/watch-link/pty-seam.ts b/src/core/watch-link/pty-seam.tsindex 0adcab5e9..76640bfab 100644--- a/src/core/watch-link/pty-seam.ts+++ b/src/core/watch-link/pty-seam.ts@@ -11,9 +11,17 @@// - `alive` is PtyManager's explicit `hasSession` (R38), `syncSize` its per-session serialized sync (R24);// - a join reports how a controller's input reaches the JOINED session's PANE// (`watcherInputRoute`: `none` for Zellij or a session it no longer holds, which refuses control),-// and `input` is `controlInput` — the pane, never a tmux client's key table.+// and `input` is `controlInput` — the pane, never a tmux client's key table — with the link host's+// `isCurrent` predicate, asked right before the step runs.+//+// WHERE a node's session lives is `watchRemoteFor`, also ONE definition: an SSH project's node and a+// remote-tmux node in a LOCAL project (`ssh` + `sshRemoteTmux` on the node, served by the project's host+// attachment) are both watched on their HOST, over the master this machine already holds for them, or+// not at all (`requireRemote`): an unheld one must never join a same-named session on the LOCAL socket.import type { PtyCreateOptions } from '../../shared/types'+import { sshConnectionIdForProject, type SshConnection } from '../../shared/ssh'import type { PtyManager } from '../pty-manager'+import type { WorkspaceStore } from '../workspace-store'import type { WatchPty } from './link-host'export type WatchPtyManager = Pick<@@ -35,6 +43,84 @@ export interface WatchRemote {requireRemote?: boolean}+/** The shell's own records `watchRemoteFor` reads. Nothing here comes from a viewer. */+export interface WatchRemoteRecords {+ /** The SSH project that holds the node (`WorkspaceStore.sshProjectIdForNode`). */+ sshProjectIdForNode(nodeId: string): string | undefined+ /** Every persisted copy of the node: the machine-local id of the project holding it, that project's+ * own SSH server (absent for a local project), and the node's binding fields as stored. */+ nodeCopies(nodeId: string): readonly { projectId: string; projectServer?: unknown; ssh?: unknown; sshRemoteTmux?: unknown }[]+ /** The live master of a connection id (`SshProjectManager.refForProject`); undefined when it is down. */+ refFor(connectionId: string): { conn: SshConnection; controlPath: string; remoteCwd?: string } | undefined+}++/**+ * The records over the workspace store — the same in both shells; only the masters differ (the desktop's+ * SSH-project manager; the Server Edition has none). The copies come from every project holding the+ * node (`projectIdsForNode`, memoized, answers "none" without a scan of every project file), each with+ * that project's own SSH server.+ */+export function watchRemoteRecords(+ store: Pick<WorkspaceStore, 'sshProjectIdForNode' | 'projectIdsForNode' | 'persistedCanvases' | 'projectTargetInfo'>,+ refFor: WatchRemoteRecords['refFor']+): WatchRemoteRecords {+ return {+ sshProjectIdForNode: (id) => store.sshProjectIdForNode(id),+ nodeCopies: (id) => {+ if (store.projectIdsForNode(id).length === 0) return []+ return store.persistedCanvases().flatMap((c) => {+ const n = c.nodes.find((x) => x.id === id)+ if (!n) return []+ return [{ projectId: c.id, projectServer: store.projectTargetInfo(c.id)?.ssh?.server, ssh: n.ssh, sshRemoteTmux: n.sshRemoteTmux }]+ })+ },+ refFor+ }+}++/** A binding read from hand-editable, git-shared data: an object with a non-empty string host. */+function sshConnOf(v: unknown): SshConnection | null {+ if (typeof v !== 'object' || v === null) return null+ const host = (v as { host?: unknown }).host+ return typeof host === 'string' && host ? (v as SshConnection) : null+}++/**+ * Where a watcher join for `nodeId` goes, from the shell's own records:+ * - a node of an SSH project: that project's master (`requireRemote` always);+ * - a node with `sshRemoteTmux` in any persisted copy — a remote-tmux node in a LOCAL project — its+ * connection's master, chosen the way the canvas chooses it (`sshConnectionIdForProject`: the+ * project's own when the hosts match, else the project × endpoint attachment), `requireRemote`+ * whether or not that master is up (the renderer's own rule for the node's spawn);+ * - anything else (a local node, a standalone ssh terminal whose `ssh` runs in LOCAL tmux): local.+ * Records that throw answer `requireRemote` with no master: a join that cannot be placed never reaches+ * the local socket (it joins a session this process already holds, or waits).+ */+export function watchRemoteFor(nodeId: string, r: WatchRemoteRecords): WatchRemote {+ try {+ const sshProject = r.sshProjectIdForNode(nodeId)+ if (sshProject) return remoteOver(r.refFor(sshProject))+ let remote = false+ for (const copy of r.nodeCopies(nodeId)) {+ if (copy.sshRemoteTmux !== true) continue+ remote = true+ const conn = sshConnOf(copy.ssh)+ if (!conn) continue+ const ref = r.refFor(sshConnectionIdForProject(copy.projectId, conn, sshConnOf(copy.projectServer) ?? undefined))+ if (ref) return remoteOver(ref)+ }+ return remote ? { requireRemote: true } : {}+ } catch {+ return { requireRemote: true }+ }+}+function remoteOver(ref: ReturnType<WatchRemoteRecords['refFor']>): WatchRemote {+ return {+ requireRemote: true,+ ...(ref ? { sshRemote: { conn: ref.conn, controlPath: ref.controlPath, remoteCwd: ref.remoteCwd ?? '~' } } : {})+ }+}+export function createWatchPty(pty: WatchPtyManager, remoteFor: (nodeId: string) => WatchRemote = () => ({})): WatchPty {return {async join(clientId, nodeId, viewerId) {@@ -63,6 +149,6 @@ export function createWatchPty(pty: WatchPtyManager, remoteFor: (nodeId: string)captureVisible: (sessionId) => pty.captureVisible(sessionId),syncSize: (sessionId) => pty.syncWatcherClientSize(sessionId),alive: (sessionId) => pty.hasSession(sessionId),- input: (sessionId, chunk) => pty.controlInput(sessionId, chunk)+ input: (sessionId, chunk, isCurrent) => pty.controlInput(sessionId, chunk, isCurrent)}}diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.tsindex 3d05620cc..544d4a1f0 100644--- a/src/core/watch-link/service.test.ts+++ b/src/core/watch-link/service.test.ts@@ -15,7 +15,7 @@ import {} from './service'import { WatchLinkStore, WatchLinkStoreUnreadable, type WatchLinkRecord, type SaveOutcome } from './store'import type { WatchLinkApi as ApiClient } from './api'-import type { LinkHost, LinkHostDeps, LinkRuntimeStatus, LinkViewer, WatchPty } from './link-host'+import { WRONG_PER_LINK, type LinkHost, type LinkHostDeps, type LinkRuntimeStatus, type LinkViewer, type WatchPty } from './link-host'import type { WatchChatMessage } from '../../shared/watch-link/protocol'import type { ControlSupport, WatchLinkNotice, WatchLinkView } from '../../shared/watch-link-types'import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'@@ -1022,7 +1022,7 @@ describe('createWatchLinkService — creating a Control link', () => {expect(text).not.toContain(Buffer.from(PW).toString('base64'))expect(text).not.toContain(Buffer.from(PW).toString('hex'))const [loaded] = await t.store.load()- expect(Object.keys(loaded.control ?? {}).sort()).toEqual(['enabled', 'hash', 'locked', 'salt'])+ expect(Object.keys(loaded.control ?? {}).sort()).toEqual(['enabled', 'hash', 'locked', 'salt', 'wrong'])expect(loaded.control).toMatchObject({ enabled: true, locked: false })expect(await verifyControlPassword(PW, loaded.control!)).toBe(true)const h = t.hosts.made[0]@@ -1169,6 +1169,77 @@ describe('createWatchLinkService — the Control host seams', () => {warn.mockRestore()})+ // Final review, Minor 2: the link-wide wrong count is persisted beside `locked`, so an app restart+ // no longer resets it toward the lock (with Unlimited links that was 9 fresh guesses per restart).+ it('each wrong attempt puts the link-wide count on the record and writes it — at most 10 writes, the 10th rides the lock', async () => {+ const written: (WatchLinkRecord['control'] | undefined)[] = []+ const f = fakeStore({+ save: async (recs) => {+ written.push(recs[0]?.control ? { ...recs[0].control } : undefined)+ return 'saved'+ }+ })+ const t = service({ store: f.store, hashPassword: fastHash })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const h = t.hosts.made[0]+ expect(h.record.control?.wrong).toBe(0)+ const saves = f.saves.length+ for (let n = 1; n <= WRONG_PER_LINK; n++) {+ h.deps.onWrongAttempt(n)+ expect(h.record.control?.wrong).toBe(n) // synchronously: the record is the count's home+ if (n === WRONG_PER_LINK) h.deps.onControlLocked() // what the host does at the 10th+ }+ await flush()+ expect(f.saves.length - saves).toBe(WRONG_PER_LINK)+ expect(written.slice(saves).map((c) => c?.wrong)).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])+ expect(written.at(-1)).toMatchObject({ wrong: WRONG_PER_LINK, locked: true })+ })++ it('a count outside 0..10 is clamped onto the record (the store would refuse to write it)', async () => {+ const t = service({ hashPassword: fastHash })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const h = t.hosts.made[0]+ h.deps.onWrongAttempt(99)+ expect(h.record.control?.wrong).toBe(WRONG_PER_LINK)+ h.deps.onWrongAttempt(-3)+ expect(h.record.control?.wrong).toBe(0)+ h.deps.onWrongAttempt(Number.NaN)+ expect(h.record.control?.wrong).toBe(0)+ await flush()+ expect((await t.store.load())[0].control?.wrong).toBe(0)+ })++ it('the count survives a restart: a host resumed from the saved record starts from it', async () => {+ const t = service({ hashPassword: fastHash })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ for (let n = 1; n <= 9; n++) t.hosts.made[0].deps.onWrongAttempt(n)+ await flush()+ expect((await t.store.load())[0].control?.wrong).toBe(9)+ await t.s.shutdown()+ const again = service({ store: new WatchLinkStore({ file: t.file }) })+ await again.s.init()+ expect(again.hosts.made[0].record.control?.wrong).toBe(9)+ })++ it('a new password and Allow control again reset the count, on the record and on disk', async () => {+ const t = service({ hashPassword: fastHash })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const h = t.hosts.made[0]+ for (let n = 1; n <= 5; n++) h.deps.onWrongAttempt(n)+ expect(await t.s.setPassword(r.link.linkId, NEW_PW)).toBe(true)+ expect(h.record.control?.wrong).toBe(0)+ expect((await t.store.load())[0].control?.wrong).toBe(0)+ for (let n = 1; n <= WRONG_PER_LINK; n++) h.deps.onWrongAttempt(n)+ h.deps.onControlLocked()+ expect(await t.s.allowControl(r.link.linkId)).toBe(true)+ expect(h.record.control).toMatchObject({ locked: false, wrong: 0 })+ expect((await t.store.load())[0].control).toMatchObject({ locked: false, wrong: 0 })+ })+it('a viewer taking control tells the owner, under the name it gave (bidi stripped)', async () => {const t = service()const r = await t.s.create(ctlReq())@@ -1251,50 +1322,119 @@ describe('createWatchLinkService — the owner controls a Control link', () => {expect(await t.s.allowControl('Nope000000000000000000')).toBe(false)})- it('a change whose write fails is undone in memory and at the host, and answers false; a lock is never undone', async () => {+ // THE BRAKE HOLDS (final review, Important 1): a change that NARROWS access is the owner's emergency+ // brake. It stays in force whatever the disk does, and the owner is told 'unsaved' (applied now, gone+ // at a restart); the next write that lands carries it. A widening still changes nothing on a failure.+ function snapStore(o: { save: () => Promise<SaveOutcome> }) {+ /** What each write carried for the first record, copied AT CALL TIME (the store snapshots then). */+ const written: (WatchLinkRecord['control'] | undefined)[] = []+ const f = fakeStore({+ save: (recs) => {+ written.push(recs[0]?.control ? { ...recs[0].control } : undefined)+ return o.save()+ }+ })+ return { ...f, written }+ }++ it("typing OFF whose write fails stays off at the host and in memory, answers 'unsaved', and the next write that lands carries it", async () => {const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})let outcome: SaveOutcome = 'saved'- const f = fakeStore({ save: async () => outcome })- const t = service({ store: f.store })+ const f = snapStore({ save: async () => outcome })+ const t = service({ store: f.store, hashPassword: fastHash })const r = await t.s.create(ctlReq())if (!r.ok) throw new Error(r.error)const id = r.link.linkIdconst h = t.hosts.made[0]outcome = 'failed'const saves = f.saves.length- expect(await t.s.setControl(id, false)).toBe(false)- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false })- expect(h.hooks).toEqual(['controlChanged', 'controlChanged']) // told, then told it is back- expect(f.saves.length).toBe(saves + 2) // the write that failed, and the corrected list behind it- expect(f.saves.at(-1)?.[0].control?.enabled).toBe(true)- h.hooks.length = 0- expect(await t.s.setPassword(id, NEW_PW)).toBe(false)- expect(h.hooks).toEqual(['passwordChanged', 'passwordChanged'])- expect(await h.deps.verifyPassword(PW)).toBe(true)- expect(await h.deps.verifyPassword(NEW_PW)).toBe(false)- h.hooks.length = 0- h.deps.onControlLocked() // its own write fails too: the lock holds- expect(await t.s.allowControl(id)).toBe(false)- expect(h.hooks).toEqual([]) // a widening the write refused never reached the host- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: true })- const c = h.record.control!+ expect(await t.s.setControl(id, false)).toBe('unsaved')+ // Never undone: the record the host reads, the owner's view, and the host told once.+ expect(h.record.control?.enabled).toBe(false)+ expect(t.s.list()[0].control).toEqual({ enabled: false, locked: false })+ expect(h.hooks).toEqual(['controlChanged'])+ expect(f.saves.length).toBe(saves + 1) // no "corrected" list queued behind it+ expect(f.written.at(-1)?.enabled).toBe(false)+ // The next write that lands (any change: here a second link) carries the narrowed state.+ outcome = 'saved'+ const other = await t.s.create(req({ nodeId: 'n2' }))+ expect(other.ok).toBe(true)+ expect(f.written.at(-1)?.enabled).toBe(false)+ expect(t.s.list().find((l) => l.linkId === id)?.control).toEqual({ enabled: false, locked: false })+ expect(allLogged([warn])).not.toMatch(new RegExp(PW.replace(/[+/=]/g, '\\$&')))+ warn.mockRestore()+ })++ it("a new password whose write fails is in force — the old one refused, the new one opens — answers 'unsaved', and the next write that lands carries its hash", async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ let outcome: SaveOutcome = 'saved'+ const f = snapStore({ save: async () => outcome })+ const t = service({ store: f.store })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const id = r.link.linkId+ const h = t.hosts.made[0]+ const before = { ...h.record.control! }+ outcome = 'failed'+ expect(await t.s.setPassword(id, NEW_PW)).toBe('unsaved')+ expect(h.hooks).toEqual(['passwordChanged']) // every controller demoted, never re-told+ expect(await h.deps.verifyPassword(PW)).toBe(false)+ expect(await h.deps.verifyPassword(NEW_PW)).toBe(true)+ const now = h.record.control!+ expect(now.hash).not.toBe(before.hash)+ outcome = 'saved'+ h.deps.onControlLocked() // any later write: this one is the lock's+ await flush()+ expect(f.written.at(-1)).toMatchObject({ salt: now.salt, hash: now.hash, locked: true })expect(allLogged([warn])).not.toMatch(- new RegExp([PW, NEW_PW, c.salt, c.hash].map((x) => x.replace(/[+/=]/g, '\\$&')).join('|'))+ new RegExp([PW, NEW_PW, now.salt, now.hash].map((x) => x.replace(/[+/=]/g, '\\$&')).join('|')))warn.mockRestore()})- it('a change whose write does not answer is bounded: undone, false', async () => {- const held = deferred<SaveOutcome>()- let hang = false- const f = fakeStore({ save: () => (hang ? held.promise : Promise.resolve('saved')) })+ it("a narrowing whose write HANGS is bounded: 'unsaved' at the bound, still in force, and the next write that lands carries it", async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ let held: ReturnType<typeof deferred<SaveOutcome>> | null = null+ const f = snapStore({ save: () => (held ? held.promise : Promise.resolve('saved')) })const t = service({ store: f.store, persistTimeoutMs: 20, hashPassword: fastHash })const r = await t.s.create(ctlReq())if (!r.ok) throw new Error(r.error)- hang = true- expect(await t.s.setControl(r.link.linkId, false)).toBe(false)- expect(t.s.list()[0].control).toEqual({ enabled: true, locked: false })- held.resolve('saved')+ const id = r.link.linkId+ const h = t.hosts.made[0]+ held = deferred<SaveOutcome>()+ expect(await t.s.setControl(id, false)).toBe('unsaved')+ expect(h.record.control?.enabled).toBe(false)+ expect(h.hooks).toEqual(['controlChanged'])+ expect(await t.s.setPassword(id, NEW_PW)).toBe('unsaved')+ expect(h.hooks).toEqual(['controlChanged', 'passwordChanged'])+ const after = { ...h.record.control! }+ expect(t.s.list()[0].control).toEqual({ enabled: false, locked: false })+ // The disk answers again: the hung writes land, and the next write carries both changes.+ const d = held+ held = null+ d.resolve('failed')+ await flush()+ const other = await t.s.create(req({ nodeId: 'n2' }))+ expect(other.ok).toBe(true)+ expect(f.written.at(-1)).toMatchObject({ enabled: false, salt: after.salt, hash: after.hash })+ expect(h.record.control).toMatchObject({ enabled: false, salt: after.salt, hash: after.hash })+ })++ it('a widening whose write fails changes nothing and answers false; a lock is never undone', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ let outcome: SaveOutcome = 'saved'+ const f = fakeStore({ save: async () => outcome })+ const t = service({ store: f.store, hashPassword: fastHash })+ const r = await t.s.create(ctlReq())+ if (!r.ok) throw new Error(r.error)+ const id = r.link.linkId+ const h = t.hosts.made[0]+ outcome = 'failed'+ h.deps.onControlLocked() // its own write fails too: the lock holds+ expect(await t.s.allowControl(id)).toBe(false)+ expect(h.hooks).toEqual([]) // a widening the write refused never reached the host+ expect(t.s.list()[0].control).toEqual({ enabled: true, locked: true })+ warn.mockRestore()})})diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.tsindex 578ba284c..017fec684 100644--- a/src/core/watch-link/service.ts+++ b/src/core/watch-link/service.ts@@ -40,14 +40,19 @@// through ONE FIFO gate of SCRYPT_SLOTS (each run is ~32 MiB and ~80 ms on libuv's 4-thread pool, and// unlock attempts arrive from strangers): a run waits for a slot, it is never refused. The lock the// link host asks for (`onControlLocked`) is set on the record synchronously — the host reads the record-// live — and is never undone by a failed write. The owner's changes go by DIRECTION. One that NARROWS-// access (typing off, a new password) reaches the record and the host at once — a leaked password or-// an unwanted typist must not wait on the disk — and is undone when its write fails or does not answer-// within PERSIST_TIMEOUT_MS. One that WIDENS it (typing on, allow again) is written first, from a copy-// of the record, and reaches the record and the host only once that write landed: nobody can unlock-// and type during a write the owner is then told failed. Either way a failed write answers false: the-// owner is never told a change was kept that the next launch would not have. A later change to the-// same field supersedes an earlier one still being written (its undo or its late apply is skipped).+// live — and is never undone by a failed write. So is the link-wide count of wrong attempts the host+// reports (`onWrongAttempt`): it goes on the record and is written, at most WRONG_PER_LINK writes per+// link (the last rides the lock's), so an app restart does not reset it; a new password and Allow+// control again reset it. The owner's changes go by DIRECTION. One that NARROWS access (typing off, a+// new password) is the owner's brake: it reaches the record and the host at once — a leaked password or+// an unwanted typist must not wait on the disk — and is NEVER undone: a write that fails or does not+// answer within PERSIST_TIMEOUT_MS answers 'unsaved' (in force now, undone by a restart unless a later+// write lands — every write carries the whole list from memory, so the next one that lands saves it;+// Stop ends it for good). One that WIDENS it (typing on, allow again) is written first, from a copy of+// the record, and reaches the record and the host only once that write landed: nobody can unlock and+// type during a write the owner is then told failed, which answers false. The owner is never told a+// change was kept that the next launch would not have. A later change to the same field supersedes an+// earlier one still being written (its late apply is skipped).//// AN UNLIMITED LINK (`ttlSeconds` 0) has `expiresAt: null`: no expiry timer, no expiry check on a host// change, never pruned for time at launch. It ends like any link otherwise, and when its owner's Pro@@ -73,6 +78,7 @@ import {WATCH_LINK_TTLS,stripBidiControls,type ControlSupport,+ type ControlChangeResult,type CreateWatchLinkError,type CreateWatchLinkRequest,type CreateWatchLinkResult,@@ -83,7 +89,7 @@ import {} from '../../shared/watch-link-types'import { controlPasswordProblem } from '../../shared/watch-link-password'import type { HostTokenResult, WatchLinkApi as WatchLinkApiClient } from './api'-import { createLinkHost, type LinkHost, type QuietClients, type WatchPty } from './link-host'+import { WRONG_PER_LINK, createLinkHost, type LinkHost, type QuietClients, type WatchPty } from './link-host'import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'import {WatchLinkStoreUnreadable,@@ -161,12 +167,14 @@ export interface WatchLinkService {onWorkspaceChanged(): void/** After the license layer reports a change: re-arm every host the API refused. */onEntitlementChanged(): void- /** A live Control link: turn typing on or off. False for any other link, or when it could not be- * saved (then nothing changed). */- setControl(linkId: string, enabled: boolean): Promise<boolean>- /** A live Control link: replace its password (every controller drops back to watching). False for- * a password `controlPasswordProblem` refuses, any other link, or a change that could not be saved. */- setPassword(linkId: string, pw: string): Promise<boolean>+ /** A live Control link: turn typing on or off (`ControlChangeResult`). False for any other link, or+ * typing ON that could not be saved (then nothing changed); 'unsaved' for typing OFF that could not+ * be saved (it holds all the same). */+ setControl(linkId: string, enabled: boolean): Promise<ControlChangeResult>+ /** A live Control link: replace its password (every controller drops back to watching, the link-wide+ * wrong count starts over). False for a password `controlPasswordProblem` refuses, any other link,+ * or a hash that failed; 'unsaved' for a new password in force that could not be saved. */+ setPassword(linkId: string, pw: string): Promise<ControlChangeResult>/** A live Control link locked by wrong passwords: allow unlocking again. False as setControl. */allowControl(linkId: string): Promise<boolean>/** Whether this node's terminal can take a Control link's input (the create dialog asks). */@@ -511,7 +519,7 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSercaptureVisible: (sessionId) => deps.pty.captureVisible(sessionId),syncSize: (sessionId) => deps.pty.syncSize(sessionId),alive: (sessionId) => deps.pty.alive(sessionId),- input: (sessionId, chunk) => deps.pty.input(sessionId, chunk)+ input: (sessionId, chunk, isCurrent) => deps.pty.input(sessionId, chunk, isCurrent)}}@@ -580,6 +588,18 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer}notice({ kind: 'control-locked', linkId: r.linkId, nodeId: r.nodeId, title: stripBidiControls(r.title) })emitState()+ },+ onWrongAttempt: (count) => {+ // On the record SYNCHRONOUSLY (a later write snapshots it), as an integer 0..WRONG_PER_LINK:+ // the store refuses to write anything else.+ if (!r.control || typeof count !== 'number' || Number.isNaN(count)) return+ r.control.wrong = Math.min(WRONG_PER_LINK, Math.max(0, Math.floor(count)))+ // The count that locks rides the lock's own write (`onControlLocked`, which follows): at most+ // WRONG_PER_LINK writes per link between resets.+ if (r.control.wrong >= WRONG_PER_LINK || records.get(r.linkId) !== r) return+ void persist().then((saved) => {+ if (!saved) warn("a Control link's wrong-attempt count could not be saved; an app restart would reset it")+ })}})} catch (err) {@@ -701,8 +721,9 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSer}}- /** Each owner change (and a lock) takes a TURN on the field it touches; an earlier change to the- * same field still being written sees it lost its turn and neither undoes nor applies anything. */+ /** Each owner change (and a lock) takes a TURN on the field it touches; an earlier WIDENING of the+ * same field still being written sees it lost its turn and does not apply (a narrowing applies at+ * once and is never undone, so it has nothing to skip). */type ControlField = 'enabled' | 'locked' | 'password'const turns = new WeakMap<WatchLinkRecord, Record<ControlField, number>>()function takeTurn(r: WatchLinkRecord, f: ControlField): number {@@ -713,31 +734,25 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerconst hasTurn = (r: WatchLinkRecord, f: ControlField, n: number): boolean => turns.get(r)?.[f] === n/**- * An owner's change that NARROWS access (typing off, a new password): applied in memory and told to- * the host AT ONCE, then written. A write that fails, or does not answer within PERSIST_TIMEOUT_MS,- * undoes the change — only while it still holds the field's turn, and `undo` restores only what is- * still this change's own value — tells the host again, queues the corrected list behind the write,- * and answers false.+ * An owner's change that NARROWS access (typing off, a new password): the owner's BRAKE. Applied in+ * memory and told to the host AT ONCE, then written — and NEVER undone. A write that fails, or does+ * not answer within PERSIST_TIMEOUT_MS, answers 'unsaved': the change holds until nodeterm quits, and+ * the next write that lands (every write carries the whole list as memory holds it) saves it. Undoing+ * it instead would hand typing back, or re-open a possibly leaked password, because a disk hiccuped.*/async function narrowControl(r: ControlRecord,field: ControlField,- o: { apply(): void; undo(): void; host(h: LinkHost): void; undoHost(h: LinkHost): void }- ): Promise<boolean> {- const turn = takeTurn(r, field)+ o: { apply(): void; host(h: LinkHost): void }+ ): Promise<true | 'unsaved'> {+ takeTurn(r, field) // a widening of this field still being written must not land over ito.apply()tellHost(r.linkId, o.host)emitState()const written = await within(persist(), persistTimeoutMs)if (written === true) return true- if (hasTurn(r, field, turn)) {- o.undo()- tellHost(r.linkId, o.undoHost)- }- if (records.get(r.linkId) === r) void persist()- emitState()- warn("an owner's change to a Control link could not be saved; it was undone")- return false+ warn("an owner's change to a Control link could not be saved; it holds until nodeterm quits")+ return 'unsaved'}/**@@ -815,7 +830,7 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerreturn fail('unsupported')}parsed.password = null- control = { enabled: true, locked: false, salt: h.salt, hash: h.hash }+ control = { enabled: true, locked: false, wrong: 0, salt: h.salt, hash: h.hash }}const secret = newWatchLinkSecret()const joinKeyHash = await sha256Hex(deriveWatchLinkKeys(secret).joinKey)@@ -981,11 +996,7 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerapply: () => {c.enabled = false},- undo: () => {- if (c.enabled === false) c.enabled = true- },- host: (h) => h.controlChanged(),- undoHost: (h) => h.controlChanged()+ host: (h) => h.controlChanged()})},@@ -1002,21 +1013,15 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerconst r = liveControl(linkId)if (!r) return falseconst c = r.control- const before = { salt: c.salt, hash: c.hash }return narrowControl(r, 'password', {apply: () => {c.salt = h.saltc.hash = h.hash+ // A new password starts the link-wide wrong count over (the host resets its own).+ c.wrong = 0},- undo: () => {- if (c.hash !== h.hash) return // a later password replaced this one meanwhile- c.salt = before.salt- c.hash = before.hash- },- // Either way every controller drops back to watching: one that unlocked with the new password- // during the write must unlock again with the one that holds.- host: (x) => x.passwordChanged(),- undoHost: (x) => x.passwordChanged()+ // Every controller drops back to watching and must unlock with the new password.+ host: (x) => x.passwordChanged()})},@@ -1030,6 +1035,7 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSerreturn widenControl(r, 'locked', {change: (x) => {x.locked = false+ x.wrong = 0 // the count starts over with the lock (the host resets its own)},host: (h) => h.allowControl()})diff --git a/src/core/watch-link/store.test.ts b/src/core/watch-link/store.test.tsindex c9a1997b8..a757560e0 100644--- a/src/core/watch-link/store.test.ts+++ b/src/core/watch-link/store.test.ts@@ -528,7 +528,7 @@ describe('a keychain that stops sealing mid-run (R45)', () => {describe('controller records and unlimited expiry', () => {const SALT = b64(new Uint8Array(16).fill(1))const HASH = b64(new Uint8Array(32).fill(2))- const control = { enabled: true, salt: SALT, hash: HASH, locked: false }+ const control = { enabled: true, salt: SALT, hash: HASH, locked: false, wrong: 0 }const ctl = (over: Partial<WatchLinkRecord> = {}) => rec({ role: 'controller', control, expiresAt: null, ...over })it('round-trips a controller record with no expiry through save and a fresh store', async () => {@@ -538,7 +538,7 @@ describe('controller records and unlimited expiry', () => {expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([ctl()])}const f = file()- const locked = ctl({ control: { enabled: false, salt: SALT, hash: HASH, locked: true } })+ const locked = ctl({ control: { enabled: false, salt: SALT, hash: HASH, locked: true, wrong: 10 } })expect(await new WatchLinkStore({ file: f, seal, unseal }).save([locked])).toBe('saved')expect(await new WatchLinkStore({ file: f, seal, unseal }).load()).toEqual([locked])})@@ -577,14 +577,36 @@ describe('controller records and unlimited expiry', () => {{ ...control, enabled: 1 },{ ...control, locked: 'false' },{ salt: SALT, hash: HASH, locked: false },- { enabled: true, salt: SALT, hash: HASH }+ { enabled: true, salt: SALT, hash: HASH },+ // The link-wide wrong count (final review, Minor 2): an integer 0..10 when present.+ { ...control, wrong: 11 },+ { ...control, wrong: -1 },+ { ...control, wrong: 1.5 },+ { ...control, wrong: '3' },+ { ...control, wrong: null },+ { ...control, wrong: Number.MAX_SAFE_INTEGER }]const f = file()writeLinks(f, [...bad.map((c, i) => rawEntry({ linkId: id(i), role: 'controller', control: c, expiresAt: null })), rawEntry()])expect(await new WatchLinkStore({ file: f }).load()).toEqual([rec()])})- it('keeps only the four control fields: an extra one is not loaded or carried', async () => {+ // Final review, Minor 2: the link-wide wrong-attempt count is persisted beside `locked`, so an app+ // restart no longer resets it. A file written before it existed has no `wrong`: it reads as 0.+ it('round-trips the link-wide wrong count, and reads a control written without one (an older file) as 0', async () => {+ for (const opts of [{ seal, unseal }, {}]) {+ const f = file()+ const seven = ctl({ control: { ...control, wrong: 7 } })+ expect(await new WatchLinkStore({ file: f, ...opts }).save([seven])).toBe('saved')+ expect(await new WatchLinkStore({ file: f, ...opts }).load()).toEqual([seven])+ }+ const f = file()+ const older = { enabled: true, salt: SALT, hash: HASH, locked: false }+ writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: older })])+ expect(await new WatchLinkStore({ file: f }).load()).toEqual([ctl()])+ })++ it('keeps only the five control fields: an extra one is not loaded or carried', async () => {const f = file()writeLinks(f, [rawEntry({ role: 'controller', expiresAt: null, control: { ...control, password: 'hunter22' } })])const s = new WatchLinkStore({ file: f })@@ -593,7 +615,7 @@ describe('controller records and unlimited expiry', () => {expect(readFileSync(f, 'utf8')).not.toContain('hunter22')})- it('writes only the four control fields of a record', async () => {+ it('writes only the five control fields of a record', async () => {const f = file()const withExtra = ctl({ control: { ...control, password: 'hunter22' } as WatchLinkRecord['control'] })expect(await new WatchLinkStore({ file: f, seal, unseal }).save([withExtra])).toBe('saved')@@ -615,7 +637,10 @@ describe('controller records and unlimited expiry', () => {ctl({ control: { ...control, salt: b64(new Uint8Array(15).fill(1)) } }),ctl({ control: { ...control, hash: 'not base64!' } }),ctl({ control: { ...control, enabled: 'yes' } as unknown as WatchLinkRecord['control'] }),- ctl({ control: { ...control, locked: undefined } as unknown as WatchLinkRecord['control'] })+ ctl({ control: { ...control, locked: undefined } as unknown as WatchLinkRecord['control'] }),+ ctl({ control: { ...control, wrong: 11 } }),+ ctl({ control: { ...control, wrong: -1 } }),+ ctl({ control: { ...control, wrong: 2.5 } })]for (const r of broken) {expect(await s.save([rec({ linkId: 'OtherLinkIjKlMnOpQrStU' }), r]), JSON.stringify(r.control ?? r.role)).toBe('failed')@@ -629,7 +654,7 @@ describe('controller records and unlimited expiry', () => {it('never writes the plaintext password: the file holds only its salt and scrypt hash', async () => {const password = 'correct horse battery staple'const h = await hashControlPassword(password)- const r = ctl({ control: { enabled: true, salt: h.salt, hash: h.hash, locked: false } })+ const r = ctl({ control: { enabled: true, salt: h.salt, hash: h.hash, locked: false, wrong: 0 } })for (const opts of [{ seal, unseal }, {}]) {const f = file()expect(await new WatchLinkStore({ file: f, ...opts }).save([r])).toBe('saved')diff --git a/src/core/watch-link/store.ts b/src/core/watch-link/store.tsindex 94849250c..1216988f0 100644--- a/src/core/watch-link/store.ts+++ b/src/core/watch-link/store.ts@@ -39,7 +39,10 @@// at boot and links sealed earlier stay on disk, and a link no longer in the list is still dropped.//// A CONTROL LINK (role 'controller') carries `control`: whether typing is on, the password's scrypt-// salt and hash (./password.ts — never the plaintext), and whether wrong attempts locked it. It is+// salt and hash (./password.ts — never the plaintext), whether wrong attempts locked it, and the+// link-wide count of wrong attempts toward that lock (`wrong`, 0..CONTROL_WRONG_MAX — persisted, so an+// app restart does not hand an attacker who holds the link fresh guesses; a file written before the+// count existed reads as 0). It is// written as it is, not sealed: the hash is scrypt'd, and anyone who can read this 0600 file under// userData is already this user. `control` is present IFF the role is 'controller', and a load drops// any entry that breaks that rule: a hand-edited file cannot give a viewer link a password, and a@@ -55,12 +58,18 @@ import { LINK_ID_RE } from '../../shared/watch-link/link'import type { WatchLinkRole } from '../../shared/watch-link/protocol'import { isSafeNodeId } from '../../shared/safe-id'+/** Wrong unlock attempts across a Control link that lock it (link-host.ts `WRONG_PER_LINK`). */+export const CONTROL_WRONG_MAX = 10+/** A Control link's typing state. The salt and hash are base64 (16 and 32 bytes). */export interface WatchLinkControlRecord {enabled: booleansalt: stringhash: stringlocked: boolean+ /** Wrong unlock attempts across the link since the last reset (a new password, Allow control+ * again): an integer 0..CONTROL_WRONG_MAX. */+ wrong: number}export interface WatchLinkRecord {@@ -145,13 +154,16 @@ function isB64Of(v: unknown, bytes: number): v is string {return b.length === bytes && b.toString('base64') === v}-/** A Control link's `control`, rebuilt from its four fields (nothing else is carried), or null. */+/** A Control link's `control`, rebuilt from its five fields (nothing else is carried), or null. An+ * absent `wrong` is 0 (a file written before the count was persisted); a present one must be an+ * integer 0..CONTROL_WRONG_MAX. */function readControl(v: unknown): WatchLinkControlRecord | null {if (!v || typeof v !== 'object' || Array.isArray(v)) return null- const { enabled, salt, hash, locked } = v as Record<string, unknown>+ const { enabled, salt, hash, locked, wrong = 0 } = v as Record<string, unknown>if (typeof enabled !== 'boolean' || typeof locked !== 'boolean') return nullif (!isB64Of(salt, CONTROL_SALT_BYTES) || !isB64Of(hash, CONTROL_HASH_BYTES)) return null- return { enabled, salt, hash, locked }+ if (!Number.isInteger(wrong) || (wrong as number) < 0 || (wrong as number) > CONTROL_WRONG_MAX) return null+ return { enabled, salt, hash, locked, wrong: wrong as number }}export class WatchLinkStore {@@ -339,9 +351,10 @@ export class WatchLinkStore {}sealedNext.set(r.linkId, { digest, sealed: secret })}- // Only the four control fields are written: nothing else that rides on the object reaches disk.- const c = r.control- const control = c ? { control: { enabled: c.enabled, salt: c.salt, hash: c.hash, locked: c.locked } } : {}+ // Only the five control fields are written (as `readControl` read them above): nothing else that+ // rides on the object reaches disk.+ const c = r.control ? readControl(r.control) : null+ const control = c ? { control: c } : {}links.push({linkId: r.linkId, nodeId: r.nodeId, role: r.role, label: r.label, title: r.title,createdAt: r.createdAt, expiresAt: r.expiresAt, ...control, secret, sealed: !!this.o.sealdiff --git a/src/main/index.ts b/src/main/index.tsindex bd935b59e..80a9a477f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -119,7 +119,7 @@ import {} from '../core/watch-link/service'import { createWatchLinkApi } from '../core/watch-link/api'import { WatchLinkStore } from '../core/watch-link/store'-import { createWatchPty } from '../core/watch-link/pty-seam'+import { createWatchPty, watchRemoteFor, watchRemoteRecords, type WatchRemote } from '../core/watch-link/pty-seam'import { SshStore } from './ssh-store'import { GitService } from '../core/git-service'import { ProjectTrustStore } from '../core/project-trust-store'@@ -3275,6 +3275,9 @@ app.whenReady().then(async () => {// broadcast, never a pause ticket); the pty seam and the node-gone rule are core's, shared with the// Server Edition. `init()` decides nothing before the boot workspace load (R40): an empty answer// while the index is still being read is not evidence that a node is gone.+ // Where a watcher join goes (core's ONE rule, over this machine's records and its live masters).+ const watchRemote = (nodeId: string): WatchRemote =>+ watchRemoteFor(nodeId, watchRemoteRecords(workspaceStore, (connectionId) => sshProjectManager?.refForProject(connectionId)))watchLinks = createWatchLinkService({api: createWatchLinkApi({ apiBase: RELAY_API_BASE }),relayUrl: RELAY_URL,@@ -3298,21 +3301,15 @@ app.whenReady().then(async () => {// → presenceHub.leave (a no-op for an id that never joined) and PtyManager.dropClient.detach: (id) => unregisterPeerSink(id)},- // A node of an SSH project is watched on ITS host over that project's master, or not at all:- // `requireRemote` for every such node, and the remote fields from this machine's own records.- pty: createWatchPty(ptyManager, (nodeId) => {- const projectId = workspaceStore.sshProjectIdForNode(nodeId)- if (!projectId) return {}- const ref = sshProjectManager?.refForProject(projectId)- return {- requireRemote: true,- ...(ref ? { sshRemote: { conn: ref.conn, controlPath: ref.controlPath, remoteCwd: ref.remoteCwd ?? '~' } } : {})- }- }),- // Can a Control link type into this node? A node of an SSH project runs in its HOST's tmux (Zellij- // is a local-only backend), so this machine's backend choice says nothing about it: 'ok' (a host+ // A node whose session lives in a HOST's tmux — every node of an SSH project, and a remote-tmux node+ // in a LOCAL project (`ssh` + `sshRemoteTmux`, served by the project's host attachment) — is watched+ // on that host over the master this machine holds for it, or not at all: `requireRemote` for every+ // such node, the remote fields from this machine's own records (core's `watchRemoteFor`).+ pty: createWatchPty(ptyManager, watchRemote),+ // Can a Control link type into this node? A node in a HOST's tmux (the same `watchRemoteFor` answer:+ // Zellij is a local-only backend) is not decided by this machine's backend choice: 'ok' (a host// with no tmux at all answers every keystroke false, which the link host reports as dropped).- controlSupport: (nodeId) => (workspaceStore.sshProjectIdForNode(nodeId) ? 'ok' : ptyManager.nodeControlSupport(nodeId)),+ controlSupport: (nodeId) => (watchRemote(nodeId).requireRemote ? 'ok' : ptyManager.nodeControlSupport(nodeId)),emit: (channel, ...args) => sendToOwners(corePlatform, channel, ...args)})registerWatchLinkIpc(corePlatform, watchLinks)diff --git a/src/main/watch-link-control-wiring.test.ts b/src/main/watch-link-control-wiring.test.tsindex a77f58668..476763210 100644--- a/src/main/watch-link-control-wiring.test.ts+++ b/src/main/watch-link-control-wiring.test.ts@@ -31,8 +31,11 @@ describe('live-link Control wiring', () => {const block = blockAfter(read(shell), 'watchLinks = createWatchLinkService({', ' ')expect(block).toMatch(/controlSupport: \(nodeId\) =>/)expect(block).toMatch(/ptyManager\.nodeControlSupport\(nodeId\)/)- // A node of an SSH project runs in its HOST's tmux: the local backend choice says nothing about it.- expect(block).toMatch(/workspaceStore\.sshProjectIdForNode\(nodeId\) \? 'ok' : ptyManager\.nodeControlSupport\(nodeId\)/)+ // A node in a HOST's tmux (an SSH project's, or a remote-tmux node in a local project — core's+ // `watchRemoteFor`, the rule the join uses): the local backend choice says nothing about it.+ expect(block).toMatch(/watchRemote\(nodeId\)\.requireRemote \? 'ok' : ptyManager\.nodeControlSupport\(nodeId\)/)+ expect(block).toMatch(/pty: createWatchPty\(ptyManager, watchRemote\)/)+ expect(read(shell)).toMatch(/const watchRemote = \(nodeId: string\): WatchRemote =>\s*watchRemoteFor\(nodeId, watchRemoteRecords\(workspaceStore, /)})}@@ -65,6 +68,7 @@ describe('live-link Control wiring', () => {it('the pty seam hands joins their input route and input to the pane, from PtyManager', () => {const seam = read('src/core/watch-link/pty-seam.ts')expect(seam).toMatch(/input: pty\.watcherInputRoute\(res\.sessionId\)/)- expect(seam).toMatch(/input: \(sessionId, chunk\) => pty\.controlInput\(sessionId, chunk\)/)+ // The link host's `isCurrent` rides along: PtyManager asks it right before the step runs.+ expect(seam).toMatch(/input: \(sessionId, chunk, isCurrent\) => pty\.controlInput\(sessionId, chunk, isCurrent\)/)})})diff --git a/src/main/watch-link-wiring.test.ts b/src/main/watch-link-wiring.test.tsindex 803c45e90..8a5ba3dbe 100644--- a/src/main/watch-link-wiring.test.ts+++ b/src/main/watch-link-wiring.test.ts@@ -50,11 +50,15 @@ describe('live-link wiring', () => {expect(s).toMatch(/workspaceReady: \(\) => bootWorkspaceLoad/)expect(s).toMatch(/entitlement: getStoredEntitlement/)expect(s).toMatch(/initLicense\(\(\) => watchLinks\?\.onEntitlementChanged\(\)\)/)- // A node of an SSH project is watched on its host, or not at all.- const remote = blockAfter(s, 'pty: createWatchPty(ptyManager,', ' ')- expect(remote).toMatch(/workspaceStore\.sshProjectIdForNode\(nodeId\)/)- expect(remote).toMatch(/requireRemote: true/)- expect(remote).toMatch(/sshProjectManager\?\.refForProject\(projectId\)/)+ // A node in a HOST's tmux is watched on its host, or not at all — an SSH project's node AND a+ // remote-tmux node in a local project (final review, Minor 4): core's ONE rule, fed the shell's own+ // records — the SSH project, every persisted copy's binding with its project's server, the masters.+ expect(s).toMatch(/pty: createWatchPty\(ptyManager, watchRemote\)/)+ expect(s).toMatch(+ /const watchRemote = \(nodeId: string\): WatchRemote =>\s*watchRemoteFor\(nodeId, watchRemoteRecords\(workspaceStore, \(connectionId\) => sshProjectManager\?\.refForProject\(connectionId\)\)\)/+ )+ // Control support asks the same rule: a node in a host's tmux is not decided by local Zellij.+ expect(s).toMatch(/controlSupport: \(nodeId\) => \(watchRemote\(nodeId\)\.requireRemote \? 'ok' : ptyManager\.nodeControlSupport\(nodeId\)\)/)// The secret is sealed through the keychain seam.expect(s).toMatch(/seal: corePlatform\.sealSecret\?\.bind\(corePlatform\)/)expect(s).toMatch(/unseal: corePlatform\.unsealSecret\?\.bind\(corePlatform\)/)diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex a71cbfc68..beadac3d6 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -78,6 +78,7 @@ import { sanitizeStationNotices } from '@shared/station-notice'import { sanitizeOutcomeRecords } from '@shared/station-outcome'import { sanitizeHandoverRecords } from '@shared/station-handover'import type {+ ControlChangeResult,ControlSupport,CreateWatchLinkResult,RevokeAllOutcome,@@ -1033,9 +1034,9 @@ export function buildWatchLinkApi(client: RpcClient): Pick<NodeTerminalApi, 'watchatHistory: (linkId) =>(client.request(IPC.watchLinkChatHistory, linkId) as Promise<WatchChatMessage[]>).catch(() => []),setControl: (linkId, enabled) =>- (client.request(IPC.watchLinkSetControl, linkId, enabled) as Promise<boolean>).catch(() => false),+ (client.request(IPC.watchLinkSetControl, linkId, enabled) as Promise<ControlChangeResult>).catch(() => false),setPassword: (linkId, password) =>- (client.request(IPC.watchLinkSetPassword, linkId, password) as Promise<boolean>).catch(() => false),+ (client.request(IPC.watchLinkSetPassword, linkId, password) as Promise<ControlChangeResult>).catch(() => false),allowControl: (linkId) => (client.request(IPC.watchLinkAllowControl, linkId) as Promise<boolean>).catch(() => false),controlSupport: (nodeId) =>(client.request(IPC.watchLinkControlSupport, nodeId) as Promise<ControlSupport>).catch((): ControlSupport => 'unknown'),diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 59e354c4c..8c92443c0 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -3653,7 +3653,8 @@ export function Canvas() {// that runs the terminal. Started ONCE per Canvas mount; without it the store stays empty and no// LIVE chip ever appears. What a notice does is lib/liveLink's `liveLinkNoticeEffect` (tested// there): the info strip — `not-persistent` and `control-locked` stay on screen — and, for- // `control-taken`, an OS notification under the agent-done consent, once per link per 5 s.+ // `control-taken` (a security event), an OS notification under the notification consent alone — not+ // the agent-done preference — once per link per 5 s.const liveNotifyAtRef = useRef(new Map<string, number>())useEffect(() =>diff --git a/src/renderer/components/LiveChatDrawer.test.tsx b/src/renderer/components/LiveChatDrawer.test.tsxindex f6a36befe..d4cb786ab 100644--- a/src/renderer/components/LiveChatDrawer.test.tsx+++ b/src/renderer/components/LiveChatDrawer.test.tsx@@ -7,7 +7,14 @@ import { CHAT_TEXT_MAX } from '@shared/watch-link/protocol'import { LiveChatDrawer } from './LiveChatDrawer'import { liveChipSig, useWatchLinks } from '../state/watchLinks'import { openDialogCount, popDialog, pushDialog, resetDialogStack } from './dialog-stack'-import { CHAT_NOT_SENT_MESSAGE, CONTROL_LOCKED_TEXT, KICK_NOT_DONE_MESSAGE } from '../lib/liveLink'+import {+ CHAT_NOT_SENT_MESSAGE,+ CONTROL_CHANGE_UNSAVED_MESSAGE,+ CONTROL_LOCKED_TEXT,+ KICK_CONTROLLER_NOTE,+ KICK_NOT_DONE_MESSAGE,+ KICK_NOTE+} from '../lib/liveLink'import { chatNameColor } from '../lib/liveChatLook'// Spied, with the real implementation: how often the message list was RENDERED (one call per line).@@ -52,8 +59,8 @@ const api = {from: 'sharer'})),chatHistory: vi.fn(async (_l: string): Promise<WatchChatMessage[]> => []),- setControl: vi.fn(async (_l: string, _on: boolean) => true),- setPassword: vi.fn(async (_l: string, _pw: string) => true),+ setControl: vi.fn(async (_l: string, _on: boolean): Promise<boolean | 'unsaved'> => true),+ setPassword: vi.fn(async (_l: string, _pw: string): Promise<boolean | 'unsaved'> => true),allowControl: vi.fn(async (_l: string) => true)}@@ -347,6 +354,39 @@ describe('LiveChatDrawer', () => {expect(button('Change password…')).toBeTruthy()})+ // Final review, Important 1: the drawer carries the same owner controls, so the same notice — and,+ // since the drawer has no Stop of its own, the notice brings Stop sharing with it.+ it("typing OFF answered 'unsaved': the drawer says it applied but will undo at a restart, with Stop sharing at hand", async () => {+ setLinks([link({ role: 'controller', control: { enabled: true, locked: false } })])+ render(props())+ api.setControl.mockImplementationOnce(async () => 'unsaved')+ click(drawer().querySelector<HTMLButtonElement>('[role="switch"]')!)+ await flush()+ const notice = drawer().querySelector<HTMLElement>('.live-pop__unsaved')!+ expect(notice.getAttribute('role')).toBe('alert')+ expect(notice.textContent).toContain(CONTROL_CHANGE_UNSAVED_MESSAGE)+ click([...notice.querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === 'Stop sharing')!)+ await flush()+ expect(api.revoke).toHaveBeenCalledWith('L')+ })++ it('the Kick of a viewer who is controlling says they can unlock again', () => {+ setLinks([+ link({+ role: 'controller',+ control: { enabled: true, locked: false },+ viewers: [+ { viewerId: 'v1', name: 'Mert', joinedAt: 1, waiting: false, controlling: true, typing: false },+ { viewerId: 'v2', name: null, joinedAt: 2, waiting: false, controlling: false, typing: false }+ ]+ })+ ])+ render(props())+ const kicks = [...drawer().querySelectorAll<HTMLButtonElement>('.live-chat__people li button')]+ expect(kicks[0].title).toBe(`${KICK_NOTE} ${KICK_CONTROLLER_NOTE}`)+ expect(kicks[1].title).toBe(KICK_NOTE)+ })+it('mounting on a link reads it: markRead, so the chip\'s unread count clears; what lands while shown is read too', async () => {setLinks([link()])addChat('L', msg('1'))diff --git a/src/renderer/components/LiveChatDrawer.tsx b/src/renderer/components/LiveChatDrawer.tsxindex d6d1d2dff..180283ce2 100644--- a/src/renderer/components/LiveChatDrawer.tsx+++ b/src/renderer/components/LiveChatDrawer.tsx@@ -6,7 +6,7 @@ import { CHAT_TEXT_MAX } from '@shared/watch-link/protocol'import { isTopDialog, nextDialogId, popDialog, pushDialog } from './dialog-stack'import { ControlHold, ControlSection, hasChat, kickViewer, type ControlHoldKind } from './LiveLinkControls'import { IconClose, IconPin } from './icons'-import { CHAT_NOT_SENT_MESSAGE, KICK_NOTE, ROLE_NAME, statusLine, viewerName, waitingViewers } from '../lib/liveLink'+import { CHAT_NOT_SENT_MESSAGE, kickNote, ROLE_NAME, statusLine, viewerName, waitingViewers } from '../lib/liveLink'import { chatClock, chatNameColor, nearBottom, newMessagesLabel } from '../lib/liveChatLook'import { chatLinkOptionLabels, inLiveChatDrawer, LIVE_CHAT_DRAWER_ATTR, pickChatLink } from '../lib/liveChatPin'import { useLinkThread, useWatchLinks } from '../state/watchLinks'@@ -268,7 +268,7 @@ function People({ link, only }: { link: WatchLinkView; only: boolean }): React.J<buttontype="button"className="confirm__btn live-pop__btn live-pop__kick"- title={KICK_NOTE}+ title={kickNote(v)}onClick={() => kickViewer(api, link.linkId, v.viewerId, setError)}>Kickdiff --git a/src/renderer/components/LiveLinkChip.test.tsx b/src/renderer/components/LiveLinkChip.test.tsxindex f10314b88..902501a9d 100644--- a/src/renderer/components/LiveLinkChip.test.tsx+++ b/src/renderer/components/LiveLinkChip.test.tsx@@ -15,6 +15,8 @@ import {KICK_FAILED_MESSAGE,KICK_NOT_DONE_MESSAGE,KICK_NOTE,+ KICK_CONTROLLER_NOTE,+ CONTROL_CHANGE_UNSAVED_MESSAGE,PASSWORD_SEPARATE_NOTE,PASSWORD_SHOWN_ONCE,STOP_FAILED_MESSAGE@@ -61,8 +63,8 @@ const api = {from: 'sharer'})),chatHistory: vi.fn(async (_l: string): Promise<WatchChatMessage[]> => []),- setControl: vi.fn(async (_l: string, _on: boolean) => true),- setPassword: vi.fn(async (_l: string, _pw: string) => true),+ setControl: vi.fn(async (_l: string, _on: boolean): Promise<boolean | 'unsaved'> => true),+ setPassword: vi.fn(async (_l: string, _pw: string): Promise<boolean | 'unsaved'> => true),allowControl: vi.fn(async (_l: string) => true)}const writeText = vi.fn()@@ -630,6 +632,88 @@ describe('LiveLinkPopover — a Control link', () => {expect(api.setControl).toHaveBeenLastCalledWith('L', true)})+ // Final review, Important 1: a narrowing change is in force even when it could not be saved. The+ // owner is told so — it undoes at a restart — with Stop at hand to end it for good.+ it("typing OFF answered 'unsaved': says it applied but will undo at a restart, with Stop sharing at hand", async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ api.setControl.mockImplementationOnce(async () => 'unsaved')+ click(pop()!.querySelector('[role="switch"]')!)+ await flush()+ const notice = pop()!.querySelector<HTMLElement>('.live-pop__unsaved')!+ expect(notice.getAttribute('role')).toBe('alert')+ expect(notice.textContent).toContain(CONTROL_CHANGE_UNSAVED_MESSAGE)+ expect(pop()!.textContent).not.toMatch(/didn't take/)+ const stop = [...notice.querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === 'Stop sharing')!+ click(stop)+ await flush()+ expect(api.revoke).toHaveBeenCalledWith('L')+ })++ it("a stop from the unsaved notice that did not reach nodeterm says so", async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ api.setControl.mockImplementationOnce(async () => 'unsaved')+ click(pop()!.querySelector('[role="switch"]')!)+ await flush()+ api.revoke.mockImplementationOnce(async () => {+ throw new Error('socket down')+ })+ click([...pop()!.querySelectorAll<HTMLButtonElement>('.live-pop__unsaved button')].find((b) => b.textContent === 'Stop sharing')!)+ await flush()+ expect(pop()!.querySelector('.live-pop__unsaved')!.textContent).toContain(STOP_FAILED_MESSAGE)+ })++ it("the unsaved notice goes once a later change is saved", async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ api.setControl.mockImplementationOnce(async () => 'unsaved')+ click(pop()!.querySelector('[role="switch"]')!)+ await flush()+ expect(pop()!.querySelector('.live-pop__unsaved')).not.toBeNull()+ setLinks([controller({ control: { enabled: false, locked: false } })])+ // A widening that fails changes nothing: the earlier change is still unsaved.+ api.setControl.mockImplementationOnce(async () => false)+ click(pop()!.querySelector('[role="switch"]')!)+ await flush()+ expect(pop()!.querySelector('.live-pop__unsaved')).not.toBeNull()+ // One that lands writes everything memory holds: nothing is unsaved any more.+ click(pop()!.querySelector('[role="switch"]')!)+ await flush()+ expect(pop()!.querySelector('.live-pop__unsaved')).toBeNull()+ })++ it("a new password answered 'unsaved' is in force: it is shown once, with the unsaved notice", async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ click(button('Change password…'))+ typeInto(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!, 'longenough1')+ api.setPassword.mockImplementationOnce(async () => 'unsaved')+ click(button('Save'))+ await flush()+ expect(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!.value).toBe('longenough1')+ expect(pop()!.textContent).toContain(PASSWORD_SHOWN_ONCE)+ expect(pop()!.querySelector('.live-pop__unsaved')!.textContent).toContain(CONTROL_CHANGE_UNSAVED_MESSAGE)+ expect(pop()!.textContent).not.toMatch(/wasn't changed/)+ })++ it('the Kick of a viewer who is controlling says they can unlock again; a watcher\'s does not', () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller({ viewers: [typist('a', 'Mert'), { viewerId: 'c', name: 'Dee', joinedAt: 0, waiting: false, controlling: false, typing: false }] })])+ click(chip()!)+ const kicks = [...pop()!.querySelectorAll<HTMLButtonElement>('.live-pop__kick')]+ expect(kicks[0].title).toBe(`${KICK_NOTE} ${KICK_CONTROLLER_NOTE}`)+ expect(kicks[1].title).toBe(KICK_NOTE)+ // The note under the list says it too while someone controls.+ expect(pop()!.querySelector('.live-pop__viewers .live-pop__note')!.textContent).toBe(`${KICK_NOTE} ${KICK_CONTROLLER_NOTE}`)+ setLinks([controller({ viewers: [{ viewerId: 'c', name: 'Dee', joinedAt: 0, waiting: false, controlling: false, typing: false }] })])+ expect(pop()!.querySelector('.live-pop__viewers .live-pop__note')!.textContent).toBe(KICK_NOTE)+ })+it('a change that did not take says so', async () => {render(<LiveLinkChip nodeId="n1" source="local" />)setLinks([controller()])diff --git a/src/renderer/components/LiveLinkControls.tsx b/src/renderer/components/LiveLinkControls.tsxindex 610591145..ed551269f 100644--- a/src/renderer/components/LiveLinkControls.tsx+++ b/src/renderer/components/LiveLinkControls.tsx@@ -4,11 +4,12 @@// as React TEXT; a new password lives only in `ControlSection`'s state and goes with it.import { createContext, useContext, useEffect, useId, useRef, useState } from 'react'import type { NodeTerminalApi } from '@shared/types'-import type { WatchLinkControlView, WatchLinkRole } from '@shared/watch-link-types'+import type { ControlChangeResult, WatchLinkControlView, WatchLinkRole } from '@shared/watch-link-types'import { newControlPassword, PasswordField, useCopied } from './LiveLinkPassword'import { Switch } from '../ui/Switch'import {CONTROL_CHANGE_FAILED_MESSAGE,+ CONTROL_CHANGE_UNSAVED_MESSAGE,CONTROL_LOCKED_TEXT,KICK_FAILED_MESSAGE,KICK_NOT_DONE_MESSAGE,@@ -18,7 +19,8 @@ import {PASSWORD_SEPARATE_NOTE,PASSWORD_SHOWN_ONCE,PASSWORD_UNCONFIRMED_MESSAGE,- passwordProblemText+ passwordProblemText,+ STOP_FAILED_MESSAGE} from '../lib/liveLink'/**@@ -71,6 +73,11 @@ export function kickViewer(** The switch shows core's state (the next push), never an optimistic one: a change core refused must* not look applied. A typed or new password lives only in this component's state and goes with it.+ *+ * A NARROWING change (typing off, a new password) that core answered 'unsaved' is in force but would be+ * undone by a restart: the section says so, with Stop sharing right there — the one thing that ends it+ * for good — in the popover and the drawer alike (the drawer has no Stop of its own). The notice stays+ * until a later change is saved (every write carries the whole list, so that one saved this one too).*/export function ControlSection({ linkId, control }: { linkId: string; control: WatchLinkControlView }): React.JSX.Element {const api = window.nodeTerminal.watchLink@@ -80,6 +87,10 @@ export function ControlSection({ linkId, control }: { linkId: string; control: W/** A password save is in flight: the surface holds open, Save reads "Saving…". */const [saving, setSaving] = useState(false)const [error, setError] = useState<string | null>(null)+ /** A narrowing change is in force but unsaved (`ControlChangeResult` 'unsaved'). */+ const [unsaved, setUnsaved] = useState(false)+ /** The unsaved notice's Stop did not reach nodeterm. */+ const [stopFailed, setStopFailed] = useState(false)const [editing, setEditing] = useState(false)const [draft, setDraft] = useState('')const [shown, setShown] = useState<string | null>(null)@@ -113,17 +124,30 @@ export function ControlSection({ linkId, control }: { linkId: string; control: W)/** Which save is current: a late answer to an older one is not shown. */const saveGen = useRef(0)- const run = (call: () => Promise<boolean>, failed: string): void => {+ /** Core's answer to a change: saved clears an earlier unsaved notice (that write carried it too),+ * 'unsaved' raises it, anything else is a change that did not take. */+ const settled = (r: ControlChangeResult, failed: string): void => {+ if (r === 'unsaved') setUnsaved(true)+ else if (r === true) setUnsaved(false)+ else setError(failed)+ }+ const run = (call: () => Promise<ControlChangeResult>, failed: string): void => {setBusy(true)setError(null)void Promise.resolve().then(call).then(- (ok) => !ok && setError(failed),+ (r) => settled(r, failed),() => setError(failed)).finally(() => setBusy(false))}+ /** The notice's Stop: what the popover's Stop sharing does (the desktop's stop is immediate, and the+ * state push removes the link); the Server Edition rejects when its socket is down — say so. */+ const stopLink = (): void => {+ setStopFailed(false)+ api.revoke(linkId).catch(() => setStopFailed(true))+ }/*** Save a new password, holding the surface (popover or drawer) open until the answer is in and, on* success, shown — its plaintext exists nowhere else. Bounded: with no answer after@@ -167,6 +191,8 @@ export function ControlSection({ linkId, control }: { linkId: string; control: Wsettle()if (!current) returnif (ok) {+ // In force either way: shown once. 'unsaved' adds that a restart would undo it.+ setUnsaved(ok === 'unsaved')setError(null)setShown(next)setDraft('')@@ -299,6 +325,17 @@ export function ControlSection({ linkId, control }: { linkId: string; control: W</button></div>)}+ {unsaved && (+ <div className="live-pop__unsaved" role="alert">+ <p className="live-pop__error">{CONTROL_CHANGE_UNSAVED_MESSAGE}</p>+ <div className="live-pop__actions">+ <button type="button" className="confirm__btn danger live-pop__btn" onClick={stopLink}>+ Stop sharing+ </button>+ </div>+ {stopFailed && <p className="live-pop__error">{STOP_FAILED_MESSAGE}</p>}+ </div>+ )}{error && (<p className="live-pop__error" role="alert">{error}diff --git a/src/renderer/components/LiveLinkDialog.test.tsx b/src/renderer/components/LiveLinkDialog.test.tsxindex ae0185295..63a678d9d 100644--- a/src/renderer/components/LiveLinkDialog.test.tsx+++ b/src/renderer/components/LiveLinkDialog.test.tsx@@ -560,6 +560,49 @@ describe('LiveLinkDialog — Control', () => {expect(document.querySelector<HTMLInputElement>('.live-dialog__url input')!.value).toBe('https://nodeterm.dev/s/abc#1.k')})+ // Final review, Minor 6: a stray click beside the done step must not throw away the only copy of a+ // Control link's password. The scrim does nothing until Copy password was pressed; Escape and Done+ // still close (deliberate gestures).+ it('the done step of a Control link ignores the scrim until Copy password is pressed', async () => {+ api.create.mockImplementation(async (r) => createWith(r))+ const { onClose } = mount()+ await flush()+ setLabel('Ada')+ pick('Control')+ typeInto(pwInput()!, 'longenough1')+ click(btn('Create live link'))+ await flush()+ click(document.querySelector('.confirm-overlay')!)+ expect(onClose).not.toHaveBeenCalled()+ expect(pwInput()!.value).toBe('longenough1')+ click(btn('Copy password'))+ click(document.querySelector('.confirm-overlay')!)+ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('the done step of a Control link: Escape still closes before the password was copied', async () => {+ api.create.mockImplementation(async (r) => createWith(r))+ const { onClose } = mount()+ await flush()+ setLabel('Ada')+ pick('Control')+ typeInto(pwInput()!, 'longenough1')+ click(btn('Create live link'))+ await flush()+ escape()+ expect(onClose).toHaveBeenCalledTimes(1)+ })++ it('the done step of a watch link closes on the scrim as before', async () => {+ const { onClose } = mount()+ await flush()+ setLabel('Ada')+ click(btn('Create live link'))+ await flush()+ click(document.querySelector('.confirm-overlay')!)+ expect(onClose).toHaveBeenCalledTimes(1)+ })+it('closing drops the password: nothing on screen keeps it, nothing stored it', async () => {api.create.mockImplementation(async (r) => createWith(r))const { onClose } = mount()diff --git a/src/renderer/components/LiveLinkDialog.tsx b/src/renderer/components/LiveLinkDialog.tsxindex 850766f23..73b17e489 100644--- a/src/renderer/components/LiveLinkDialog.tsx+++ b/src/renderer/components/LiveLinkDialog.tsx@@ -381,6 +381,23 @@ export function LiveLinkDialog({onClose()}, [onClose])+ // A Control link's done step holds the ONLY copy of its password (core keeps a hash): a stray click+ // beside the dialog must not throw it away. The scrim does nothing there until Copy password was+ // pressed; Escape and Done still close — those are deliberate.+ const passwordCopiedRef = useRef(false)+ const scrimClick = useCallback(() => {+ const s = stateRef.current+ if (s.phase === 'done' && s.role === 'controller' && !passwordCopiedRef.current) return+ dismiss()+ }, [dismiss])+ const onCopyPassword = useCallback(+ (pw: string) => {+ passwordCopiedRef.current = true+ copyPassword(pw)+ },+ [copyPassword]+ )+useEffect(() => {const onKey = (e: KeyboardEvent): void => {if (e.key === 'Escape' && isTop()) dismiss()@@ -444,7 +461,7 @@ export function LiveLinkDialog({}return createPortal(- <div className="confirm-overlay" ref={panelRef} onClick={dismiss}>+ <div className="confirm-overlay" ref={panelRef} onClick={scrimClick}><LiveLinkDialogBodytitle={title}whileOpenNote={whileOpenOnly ? watchWhileOpenNote() : null}@@ -456,7 +473,7 @@ export function LiveLinkDialog({onClose={dismiss}onStop={(id) => void stop(id)}onCopy={copy}- onCopyPassword={copyPassword}+ onCopyPassword={onCopyPassword}copied={copied}passwordCopied={passwordCopied}onUpgrade={onUpgrade}diff --git a/src/renderer/components/LiveLinkPopover.tsx b/src/renderer/components/LiveLinkPopover.tsxindex 13317f72b..19db7137e 100644--- a/src/renderer/components/LiveLinkPopover.tsx+++ b/src/renderer/components/LiveLinkPopover.tsx@@ -13,7 +13,7 @@ import {commentFromChat,formatClock,formatRemaining,- KICK_NOTE,+ kickNote,ROLE_LABEL,ROLE_NAME,statusLine,@@ -286,7 +286,7 @@ const LinkBlock = memo(function LinkBlock({<buttontype="button"className="confirm__btn live-pop__btn live-pop__kick"- title={KICK_NOTE}+ title={kickNote(v)}onClick={() => kickViewer(api, link.linkId, v.viewerId, setError)}>Kick@@ -294,7 +294,8 @@ const LinkBlock = memo(function LinkBlock({</li>))}</ul>- <p className="live-pop__muted live-pop__note">{KICK_NOTE}</p>+ {/* While anyone controls, the note also says a kicked controller can unlock again. */}+ <p className="live-pop__muted live-pop__note">{kickNote({ controlling: link.viewers.some((v) => v.controlling) })}</p></>)}</div>diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.tsindex fb19395e1..149122c56 100644--- a/src/renderer/lib/liveLink.test.ts+++ b/src/renderer/lib/liveLink.test.ts@@ -43,7 +43,11 @@ import {passwordProblemText,ROLE_NAME,typingNames,- UNLIMITED_NOTE+ UNLIMITED_NOTE,+ CONTROL_CHANGE_UNSAVED_MESSAGE,+ KICK_CONTROLLER_NOTE,+ KICK_NOTE,+ kickNote} from './liveLink'import type { CreateWatchLinkError, WatchLinkView } from '@shared/watch-link-types'import { DEFAULT_WATCH_LINK_TTL, WATCH_LINK_TTLS } from '@shared/watch-link-types'@@ -502,6 +506,20 @@ describe('control notices', () => {})})+describe('final review copy', () => {+ it("an owner's narrowing change that could not be saved: applied, undone by a restart, Stop ends it", () => {+ expect(CONTROL_CHANGE_UNSAVED_MESSAGE).toBe(+ "Applied, but couldn't be saved — it will undo when nodeterm restarts. Stop the link to end it for good."+ )+ })++ it('the Kick note of a viewer who is controlling says they can unlock again, and how to keep them out', () => {+ expect(KICK_CONTROLLER_NOTE).toBe('They can unlock again — change the password or turn typing off to keep them out.')+ expect(kickNote({ controlling: false })).toBe(KICK_NOTE)+ expect(kickNote({ controlling: true })).toBe(`${KICK_NOTE} ${KICK_CONTROLLER_NOTE}`)+ })+})+describe('liveLinkNoticeEffect', () => {const CONSENT = { notifyOnClaudeDone: true, notifyConsentAsked: true }const taken = (linkId = 'L') =>@@ -522,17 +540,25 @@ describe('liveLinkNoticeEffect', () => {expect(liveLinkNoticeEffect({ kind: 'from-a-newer-core' } as never, CONSENT, 0, new Map())).toEqual({ strip: null, os: null })})- it('control-taken also raises an OS notification, under the agent-done consent gate', () => {+ // Final review, Minor 7: someone taking control of a terminal is a SECURITY event, not an agent+ // finishing: it notifies once the one-time notification question was answered, whatever the+ // agent-done preference says.+ it('control-taken also raises an OS notification, gated on the notification consent only', () => {const text = 'Someone using the name “Mert” can now type in api-server.'expect(liveLinkNoticeEffect(taken(), CONSENT, 0, new Map())).toEqual({strip: { text, sticky: false },os: { title: 'Live link', body: text, nodeId: 'n' }})- for (const prefs of [- { notifyOnClaudeDone: false, notifyConsentAsked: true },- { notifyOnClaudeDone: true, notifyConsentAsked: false },- {}- ]) {+ // The agent-done preference off: still notified (the caller hands over the whole settings).+ const agentDoneOff = { notifyOnClaudeDone: false, notifyConsentAsked: true }+ expect(liveLinkNoticeEffect(taken(), agentDoneOff, 0, new Map()).os).toEqual({+ title: 'Live link',+ body: text,+ nodeId: 'n'+ })+ // The consent question not answered yet: no OS notification (it would raise the OS prompt out of+ // nowhere), whatever the preference says.+ for (const prefs of [{ notifyOnClaudeDone: true, notifyConsentAsked: false }, {}]) {const fx = liveLinkNoticeEffect(taken(), prefs, 0, new Map())expect(fx.os, JSON.stringify(prefs)).toBeNull()expect(fx.strip?.text).toBe(text)diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.tsindex 1bbd62840..1991d1455 100644--- a/src/renderer/lib/liveLink.ts+++ b/src/renderer/lib/liveLink.ts@@ -64,6 +64,13 @@ export const LIVE_LINK_EXPOSURE =export const LIVE_LINK_WARNING = `${LIVE_LINK_EXPOSURE} They can't type or resize it.`export const KICK_NOTE ='Kick ends this connection; anyone with the link can rejoin. Stop sharing to end it for everyone.'+/** After `KICK_NOTE` for a viewer who is controlling: a kicked controller who has the password unlocks+ * again as soon as it rejoins. */+export const KICK_CONTROLLER_NOTE = 'They can unlock again — change the password or turn typing off to keep them out.'+/** What Kick does to THIS viewer (the button's title, and the list's note while anyone controls). */+export function kickNote(v: { controlling: boolean }): string {+ return v.controlling ? `${KICK_NOTE} ${KICK_CONTROLLER_NOTE}` : KICK_NOTE+}/*** The create dialog's typing warning while Control is picked — spec §2.7, with the machine named@@ -105,6 +112,10 @@ export const CONTROL_LOCKED_TEXT = 'Control locked after 10 wrong passwords.'export const PASSWORD_CHANGE_NOTE = 'Anyone typing now goes back to watching until they unlock with the new password.'/** `setControl` / `allowControl` answered false, or did not answer. */export const CONTROL_CHANGE_FAILED_MESSAGE = "That change didn't take — try again."+/** A NARROWING change (typing off, a new password) answered 'unsaved': it is in force, but the next+ * launch would not have it — beside Stop sharing, which ends the link for good. */+export const CONTROL_CHANGE_UNSAVED_MESSAGE =+ "Applied, but couldn't be saved — it will undo when nodeterm restarts. Stop the link to end it for good."/** `setPassword` answered false, or did not answer: the old password still works. */export const PASSWORD_CHANGE_FAILED_MESSAGE = "The password wasn't changed — try again. The old one still works."/** How long a password save may hold the popover open before it lets go (`PASSWORD_UNCONFIRMED_MESSAGE`). */@@ -484,21 +495,22 @@ export interface LiveLinkNoticeEffect {* cooldown are tested here rather than inside Canvas. Sticky: `not-persistent` (shown after every* create while links cannot be saved) and `control-locked` (nobody can unlock until the owner* allows it again). `control-taken` — someone can now type in this terminal — also raises an OS- * notification, under the SAME consent the agent-done notification uses (`notifyOnClaudeDone &&- * notifyConsentAsked`; main shows it only while the window is unfocused) and at most once per link- * per 5 s. `lastOsAt` is the caller's per-link cooldown record; it is written only when a- * notification is raised.+ * notification. It is a SECURITY event, not an agent finishing, so it is gated on the notification+ * consent alone (`notifyConsentAsked`: the one-time question was answered, so no OS prompt comes out of+ * nowhere), never on the agent-done preference (`notifyOnClaudeDone`); main shows it only while the+ * window is unfocused, and at most once per link per 5 s. `lastOsAt` is the caller's per-link cooldown+ * record; it is written only when a notification is raised.*/export function liveLinkNoticeEffect(n: WatchLinkNotice,- prefs: { notifyOnClaudeDone?: boolean; notifyConsentAsked?: boolean },+ prefs: { notifyConsentAsked?: boolean },now: number,lastOsAt: Map<string, number>): LiveLinkNoticeEffect {const text = noticeText(n)if (text === null) return { strip: null, os: null }const strip = { text, sticky: n.kind === 'not-persistent' || n.kind === 'control-locked' }- if (n.kind !== 'control-taken' || !(prefs.notifyOnClaudeDone && prefs.notifyConsentAsked)) return { strip, os: null }+ if (n.kind !== 'control-taken' || prefs.notifyConsentAsked !== true) return { strip, os: null }for (const [id, at] of lastOsAt) if (now - at >= NOTIFY_COOLDOWN_MS) lastOsAt.delete(id)if (lastOsAt.has(n.linkId)) return { strip, os: null }lastOsAt.set(n.linkId, now)diff --git a/src/server/index.ts b/src/server/index.tsindex 4ad027800..55f22031f 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -134,7 +134,7 @@ import {} from '../core/watch-link/service'import { createWatchLinkApi } from '../core/watch-link/api'import { WatchLinkStore } from '../core/watch-link/store'-import { createWatchPty } from '../core/watch-link/pty-seam'+import { createWatchPty, watchRemoteFor, watchRemoteRecords, type WatchRemote } from '../core/watch-link/pty-seam'// Same env-override + default as src/core/check.ts / license.ts / src/main/telemetry.ts — each// shell derives it locally rather than sharing an import (src/server must not import src/main).@@ -1099,6 +1099,7 @@ export async function startServer(// license layer (a named follow-up) changes `entitlement` and drops `unsupported`, nothing else.// Headless, no keychain: the links file is a 0600 file in the data dir (spec D8). The workspace// index was read above, so there is no load to wait for.+ const watchRemote = (nodeId: string): WatchRemote => watchRemoteFor(nodeId, watchRemoteRecords(workspaceStore, () => undefined))watchLinks = createWatchLinkService({api: createWatchLinkApi({ apiBase: API_BASE }),relayUrl: RELAY_URL,@@ -1114,12 +1115,13 @@ export async function startServer(platform.detach(id)}},- // No SSH-project manager here: a node of an SSH project is joinable only while this core holds- // its session live (join-only never spawns), and never through the local tmux.- pty: createWatchPty(ptyManager, (nodeId) => (workspaceStore.sshProjectIdForNode(nodeId) ? { requireRemote: true } : {})),- // The same check as the desktop (links stay unsupported here, but the member answers): a node of an- // SSH project would run in its host's tmux, never this core's Zellij.- controlSupport: (nodeId) => (workspaceStore.sshProjectIdForNode(nodeId) ? 'ok' : ptyManager.nodeControlSupport(nodeId)),+ // The desktop's rule (core's `watchRemoteFor`), with no SSH-project manager here (no master): a node+ // in a HOST's tmux — an SSH project's, or a remote-tmux node in a local project — is joinable only+ // while this core holds its session live (join-only never spawns), and never through the local tmux.+ pty: createWatchPty(ptyManager, watchRemote),+ // The same check as the desktop (links stay unsupported here, but the member answers): a node in a+ // host's tmux would run there, never in this core's Zellij.+ controlSupport: (nodeId) => (watchRemote(nodeId).requireRemote ? 'ok' : ptyManager.nodeControlSupport(nodeId)),emit: (channel, ...args) => sendToOwners(platform, channel, ...args),unsupported: true})diff --git a/src/shared/watch-link-types.ts b/src/shared/watch-link-types.tsindex f5f5e162f..68d7260c6 100644--- a/src/shared/watch-link-types.ts+++ b/src/shared/watch-link-types.ts@@ -152,6 +152,18 @@ export type ControlSupport = 'ok' | 'unsupported' | 'unknown'*/export type RevokeAllOutcome = 'stopped' | 'no-entitlement' | 'failed' | 'unsupported'+/**+ * What an owner's change to a Control link did:+ * - `true` — applied and saved;+ * - `false` — refused, nothing changed (not a live Control link, a password the rule refuses, a hash+ * that failed, or a WIDENING change — typing on, allow again — whose write failed);+ * - `'unsaved'` — a NARROWING change (typing off, a new password) that is in force now but could not+ * be saved: it is never undone on a failed write (the owner's brake must not fail open), so it holds+ * until nodeterm quits and would be undone by a restart unless a later write lands first. Stopping+ * the link ends it for good.+ */+export type ControlChangeResult = boolean | 'unsaved'+/** `window.nodeTerminal.watchLink`. Desktop: real (preload). Server Edition: real bridge, and create* answers `unsupported` until that edition has a license layer. Relay tab: an inert stub. */export interface WatchLinkApi {@@ -164,11 +176,12 @@ export interface WatchLinkApi {/** A Commenter link's owner reply; null when the link is not a Commenter link or the text is empty. */sendChat(linkId: string, text: string): Promise<WatchChatMessage | null>chatHistory(linkId: string): Promise<WatchChatMessage[]>- /** A Control link: turn typing on or off. False when the link is not a live Control link or the- * change could not be saved. */- setControl(linkId: string, enabled: boolean): Promise<boolean>- /** A Control link: replace its password (every current controller drops back to watching). */- setPassword(linkId: string, password: string): Promise<boolean>+ /** A Control link: turn typing on or off (`ControlChangeResult`: off is a narrowing change, on a+ * widening one). */+ setControl(linkId: string, enabled: boolean): Promise<ControlChangeResult>+ /** A Control link: replace its password (every current controller drops back to watching, and the+ * link-wide wrong count starts over). A narrowing change: `ControlChangeResult`. */+ setPassword(linkId: string, password: string): Promise<ControlChangeResult>/** A Control link locked by wrong passwords: allow unlocking again (and reset the count). */allowControl(linkId: string): Promise<boolean>/** Whether this node's terminal can take a Control link's input (the dialog asks once on open). */