Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(live-links): viewers read back the agent's conversation since the link was shared
review1094da594440
diff --git a/src/core/watch-link/client.test.ts b/src/core/watch-link/client.test.tsindex 2149073de..40129499b 100644--- a/src/core/watch-link/client.test.ts+++ b/src/core/watch-link/client.test.ts@@ -149,6 +149,23 @@ describe('connectWatchClient against the real relay socket', () => {expect(h.tunnel.at(-1)).toBe(JSON.stringify({ t: 'cast', method: 'watch:chat', args: [{ name: 'Ada', text: 'hi' }] }))})+ it('asks for read-back only while open, with the cursor only when one is given', async () => {+ const h = hostWith()+ const c = connectWatchClient({ socket: h.peerT, keys: h.keys, events: events().ev })+ expect(c.requestHistory()).toBe(false)+ await vi.waitFor(() => expect(h.tunnel).toContain(TRUST_CONFIRM_JSON))+ h.confirm()+ expect(c.requestHistory()).toBe(true)+ expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:history","args":[{}]}')+ expect(c.requestHistory(4096)).toBe(true)+ expect(h.tunnel.at(-1)).toBe('{"t":"cast","method":"watch:history","args":[{"before":4096}]}')+ // A cursor the host would refuse never leaves the client.+ const n = h.tunnel.length+ expect(c.requestHistory(-1)).toBe(false)+ expect(c.requestHistory(1.5)).toBe(false)+ expect(h.tunnel).toHaveLength(n)+ })+it('sends the control casts only while open, exactly as the host reads them', async () => {const h = hostWith()const { socket, sent } = counting(h.peerT)diff --git a/src/core/watch-link/history.test.ts b/src/core/watch-link/history.test.tsnew file mode 100644index 000000000..aee8d5d72--- /dev/null+++ b/src/core/watch-link/history.test.ts@@ -0,0 +1,94 @@+import { describe, expect, it } from 'vitest'+import type { ChatMessage, ChatTranscriptResult } from '../../shared/types'+import { HISTORY_MESSAGES_MAX } from '../../shared/watch-link/protocol'+import { historyPageFrom } from './history'++const SINCE = 10_000+const text = (role: 'user' | 'assistant', at: number | undefined, t: string, key?: number): ChatMessage => ({+ role,+ parts: [{ kind: 'text', text: t }],+ ...(at === undefined ? {} : { at }),+ ...(key === undefined ? {} : { key })+})+const read = (messages: ChatMessage[], olderCursor: number | null = null, found = true): { kind: 'page'; result: ChatTranscriptResult } => ({+ kind: 'page',+ result: { messages, found, olderCursor, unmatchedResults: [] }+})++describe('historyPageFrom', () => {+ it('keeps only what was written at or after the link was created', () => {+ const p = historyPageFrom(read([text('user', 9_999, 'before'), text('user', 10_000, 'at'), text('assistant', 12_000, 'after')], 400), SINCE, null)+ expect(p.status).toBe('ok')+ expect(p.messages.map((m) => (m.parts[0] as { text: string }).text)).toEqual(['at', 'after'])+ // The window reached the link's creation: no paging past it, whatever the transcript says.+ expect(p.olderCursor).toBeNull()+ expect(p.start).toBe('shared')+ })++ it('pages on while the window is entirely after the link', () => {+ const p = historyPageFrom(read([text('user', 11_000, 'a'), text('assistant', 12_000, 'b')], 4096), SINCE, null)+ expect(p.olderCursor).toBe(4096)+ expect(p.start).toBeNull()+ })++ it('says the conversation started when the transcript has nothing older', () => {+ const p = historyPageFrom(read([text('user', 11_000, 'a')], null), SINCE, 9000)+ expect(p).toMatchObject({ before: 9000, olderCursor: null, start: 'conversation' })+ })++ it('never sends a message with no time, and calls a wholly untimed conversation untimed', () => {+ expect(historyPageFrom(read([text('user', undefined, 'x'), text('assistant', 11_000, 'y')]), SINCE, null).messages).toHaveLength(1)+ const p = historyPageFrom(read([text('user', undefined, 'x'), text('assistant', undefined, 'y')]), SINCE, null)+ expect(p.status).toBe('untimed')+ expect(p.messages).toEqual([])+ })++ it('sends tool names and arguments, a plan body, but never a result or thinking', () => {+ const m: ChatMessage = {+ role: 'assistant',+ at: 11_000,+ parts: [+ { kind: 'thinking', text: 'secret reasoning' },+ { kind: 'tool', name: 'Bash', arg: 'cat .env', result: 'TOKEN=abc' },+ { kind: 'tool', name: 'ExitPlanMode', arg: '', body: '## Plan\n1. do it' }+ ]+ }+ const p = historyPageFrom(read([m]), SINCE, null)+ expect(p.messages[0].parts).toEqual([+ { kind: 'tool', name: 'Bash', arg: 'cat .env' },+ { kind: 'tool', name: 'ExitPlanMode', arg: '' },+ { kind: 'text', text: '## Plan\n1. do it' }+ ])+ expect(JSON.stringify(p)).not.toContain('TOKEN=abc')+ expect(JSON.stringify(p)).not.toContain('secret reasoning')+ })++ it('a newest page with no transcript is an empty conversation; an older one is a failed read', () => {+ expect(historyPageFrom(read([], null, false), SINCE, null)).toMatchObject({ status: 'ok', messages: [], start: 'conversation' })+ expect(historyPageFrom(read([], null, false), SINCE, 500).status).toBe('error')+ })++ it('reports a failed read and a node with no conversation', () => {+ expect(historyPageFrom(null, SINCE, null).status).toBe('error')+ expect(historyPageFrom({ kind: 'unsupported' }, SINCE, null).status).toBe('unsupported')+ })++ it('past the message cap, pages on from the oldest message kept', () => {+ const many = Array.from({ length: HISTORY_MESSAGES_MAX + 3 }, (_, i) => text('assistant', 11_000 + i, `m${i}`, 1000 + i * 10))+ const p = historyPageFrom(read(many, 900), SINCE, null)+ expect(p.messages).toHaveLength(HISTORY_MESSAGES_MAX)+ expect((p.messages[0].parts[0] as { text: string }).text).toBe('m3')+ expect(p.olderCursor).toBe(1030)+ })++ it('past the message cap on a reader that does not page, says it was cut', () => {+ const many = Array.from({ length: HISTORY_MESSAGES_MAX + 1 }, (_, i) => text('assistant', 11_000 + i, `m${i}`))+ const p = historyPageFrom(read(many, null), SINCE, null)+ expect(p).toMatchObject({ olderCursor: null, start: 'cut' })+ })++ it('cleans what it sends: no escape sequence reaches the page', () => {+ const p = historyPageFrom(read([text('assistant', 11_000, 'ok\x1b]52;c;Zm9v\x07 done')]), SINCE, null)+ expect((p.messages[0].parts[0] as { text: string }).text).toBe('ok]52;c;Zm9v done')+ })+})diff --git a/src/core/watch-link/history.ts b/src/core/watch-link/history.tsnew file mode 100644index 000000000..89e73a431--- /dev/null+++ b/src/core/watch-link/history.ts@@ -0,0 +1,91 @@+// A live link's read-back (`watch:history`, src/shared/watch-link/protocol.ts): one page of the+// watched agent's conversation, cut to what was written after the link was created.+//+// Why a conversation and not the terminal's history: the viewer's stream is a tmux CLIENT, which paints+// on the alternate screen, so the viewer's emulator never has lines to scroll; a keyframe is the+// visible screen and never history (docs/live-links.md → Keyframes). And on an agent node the terminal's+// history would not help anyway: Claude's fullscreen TUI keeps its conversation on the pane's alternate+// screen, where tmux records no history at all.+//+// The read itself is the ⌘M panel's (`readChatTranscript` behind the phone's `chat.page`, wired by the+// desktop shell); this module only turns its answer into a page, and holds the cutoff:+// - a message older than the link, or with no time, never reaches a page (nothing proves it came+// after the link);+// - only text and tool names/arguments travel: tool results and thinking never do;+// - paging stops at the link's creation even when the transcript goes further back.+import type { ChatMessage, ChatTranscriptResult } from '../../shared/types'+import {+ HISTORY_MESSAGES_MAX,+ readHistoryPage,+ type WatchHistoryMessage,+ type WatchHistoryPage,+ type WatchHistoryPart,+ type WatchHistoryStart,+ type WatchHistoryStatus+} from '../../shared/watch-link/protocol'++/** How large a transcript window one page reads (the ⌘M panel's older-page size). */+export const HISTORY_READ_BYTES = 512 * 1024++/** What the shell's reader answered: a transcript page, or a node with no conversation to read. A+ * failed read is a rejection, never an empty page. */+export type HistoryRead = { kind: 'page'; result: ChatTranscriptResult } | { kind: 'unsupported' }++function partsOf(m: ChatMessage): WatchHistoryPart[] {+ const out: WatchHistoryPart[] = []+ for (const p of m.parts) {+ if (p.kind === 'text') out.push({ kind: 'text', text: p.text })+ else if (p.kind === 'tool') {+ out.push({ kind: 'tool', name: p.name, arg: p.arg })+ // A plan or a question is read in full on the screen (it is what the card shows); its result is not.+ if (p.body) out.push({ kind: 'text', text: p.body })+ }+ // thinking: never+ }+ return out+}++const empty = (before: number | null, since: number, status: WatchHistoryStatus): WatchHistoryPage => ({+ before,+ status,+ since,+ messages: [],+ olderCursor: null,+ start: status === 'ok' ? 'conversation' : null+})++/** The page for one read. `since` is the link's `createdAt`; `before` the cursor the viewer asked for.+ * A null `read` is a failed read. */+export function historyPageFrom(read: HistoryRead | null, since: number, before: number | null): WatchHistoryPage {+ if (read === null) return empty(before, since, 'error')+ if (read.kind === 'unsupported') return empty(before, since, 'unsupported')+ const { result } = read+ if (!result.found) {+ // The NEWEST page found nothing: no conversation was written yet. An OLDER page that finds nothing+ // is a failed read (the transcript reader's own contract), never "the start".+ return before === null ? empty(before, since, 'ok') : empty(before, since, 'error')+ }+ const all = result.messages+ const timed = all.filter((m) => typeof m.at === 'number' && Number.isFinite(m.at))+ if (all.length > 0 && timed.length === 0) return empty(before, since, 'untimed')+ const reachedShare = timed.some((m) => (m.at as number) < since)+ let kept: ChatMessage[] = timed.filter((m) => (m.at as number) >= since)+ let olderCursor: number | null = reachedShare ? null : typeof result.olderCursor === 'number' ? result.olderCursor : null+ let start: WatchHistoryStart | null = olderCursor !== null ? null : reachedShare ? 'shared' : 'conversation'+ if (kept.length > HISTORY_MESSAGES_MAX) {+ kept = kept.slice(-HISTORY_MESSAGES_MAX)+ // Page on from the oldest message kept when its line's offset is known; a reader that does not+ // page cannot go back further.+ const key = kept[0].key+ if (typeof key === 'number' && Number.isInteger(key) && key >= 0) {+ olderCursor = key+ start = null+ } else {+ olderCursor = null+ start = 'cut'+ }+ }+ const messages: WatchHistoryMessage[] = kept.map((m) => ({ role: m.role, at: m.at as number, parts: partsOf(m) }))+ // Through the protocol's own reader: the same cleaning and bounds the viewer applies.+ return readHistoryPage({ before, status: 'ok', since, messages, olderCursor, start }) ?? empty(before, since, 'error')+}diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.tsindex ac8284ba6..a87316111 100644--- a/src/core/watch-link/link-host.test.ts+++ b/src/core/watch-link/link-host.test.ts@@ -18,6 +18,7 @@ import {INPUT_MAX,TYPING_NAMES_MAX,WATCH_EVENT,+ WATCH_HISTORY_CAST,WATCH_INPUT_CAST,WATCH_RELEASE_CAST,WATCH_UNLOCK_CAST,@@ -57,6 +58,9 @@ import type { WatchLinkControlRecord, WatchLinkRecord } from './store'import type { UiSink } from '../ui-sink-registry'import type { ControlInputChunk, WatcherInputRoute } from './pane-input'import { PASTE_END, PASTE_START, TYPING_WINDOW_MS } from './control-input'+import type { HistoryRead } from './history'+import type { ChatMessage } from '../../shared/types'+import type { WatchHistoryPage } from '../../shared/watch-link/protocol'const ESC = '\x1b'const TRUST_CONFIRM = '{"t":"cast","method":"trust:confirm","args":[]}'@@ -134,6 +138,9 @@ interface SetupOpts {route?: WatcherInputRoute | 'missing'mint?: () => Promise<HostTokenResult>status?: () => Promise<'live' | 'revoked' | 'expired' | 'unknown'>+ /** The read-back seam (`LinkHostDeps.history`); absent = no read-back. Every call is recorded. */+ history?: (before: number | null) => Promise<HistoryRead>+ historySupported?: () => boolean}function setup(o: SetupOpts = {}) {@@ -195,7 +202,18 @@ function setup(o: SetupOpts = {}) {const chats: unknown[] = []const joined: number[] = []const gone: string[] = []+ /** Every read-back read, by the cursor it was asked for. */+ const reads: (number | null)[] = []const host = createLinkHost(record, {+ ...(o.history+ ? {+ history: (before: number | null) => {+ reads.push(before)+ return o.history!(before)+ }+ }+ : {}),+ ...(o.historySupported ? { historySupported: o.historySupported } : {}),relayUrl: 'wss://relay.test',mint: async () => {mints++@@ -251,7 +269,7 @@ function setup(o: SetupOpts = {}) {})hosts.push(host)return {- record, host, peers, sinks, left, calls, joinArgs, joinTimes, inputs, currents, wrongs, chats, joined, gone,+ record, host, peers, sinks, left, calls, joinArgs, joinTimes, inputs, currents, wrongs, chats, joined, gone, reads,keys: deriveWatchLinkKeys(secret),mints: () => mints,/** How many times the host reported a change to the registry (`onChange`). */@@ -1062,6 +1080,112 @@ describe('createLinkHost — ending', () => {})})+describe('createLinkHost — read-back (watch:history)', () => {+ const say = (role: 'user' | 'assistant', at: number, text: string): ChatMessage => ({ role, at, parts: [{ kind: 'text', text }] })+ const page = (messages: ChatMessage[], olderCursor: number | null = null): HistoryRead => ({+ kind: 'page',+ result: { messages, found: true, olderCursor, unmatchedResults: [] }+ })+ const pages = (v: Viewer) => v.named(WATCH_EVENT.history) as WatchHistoryPage[]++ it('tells the viewer in its meta whether read-back is there, on every link', async () => {+ const on = setup({ role: 'viewer', historySupported: () => true })+ on.host.start()+ const a = await openViewer(on)+ expect((a.named(WATCH_EVENT.meta)[0] as WatchMeta).history).toBe(true)+ const off = setup({ role: 'viewer' })+ off.host.start()+ const b = await openViewer(off)+ expect((b.named(WATCH_EVENT.meta)[0] as WatchMeta).history).toBeUndefined()+ const throws = setup({ role: 'viewer', historySupported: () => { throw new Error('boom') } })+ throws.host.start()+ const c = await openViewer(throws)+ expect((c.named(WATCH_EVENT.meta)[0] as WatchMeta).history).toBeUndefined()+ })++ it('answers a Viewer link with what was written after the link was created, and nothing before', async () => {+ const t = setup({ role: 'viewer', history: async () => page([say('user', 9_000, 'before the link'), say('assistant', 12_000, 'after the link')], 64) })+ t.record.createdAt = 10_000+ t.host.start()+ const v = await openViewer(t)+ expect(v.c.requestHistory()).toBe(true)+ await vi.waitFor(() => expect(pages(v)).toHaveLength(1))+ expect(t.reads).toEqual([null])+ expect(pages(v)[0]).toMatchObject({ before: null, status: 'ok', since: 10_000, olderCursor: null, start: 'shared' })+ expect(JSON.stringify(pages(v)[0])).not.toContain('before the link')+ expect(pages(v)[0].messages.map((m) => (m.parts[0] as { text: string }).text)).toEqual(['after the link'])+ // Only the asker hears the answer: it is not a broadcast.+ expect(t.host.viewers()).toHaveLength(1)+ })++ it('passes the cursor through, and answers it with the page it asked for', async () => {+ const t = setup({ role: 'commenter', history: async (before) => page([say('user', 5_000, `b${before}`)], 0) })+ t.host.start()+ const v = await openViewer(t)+ v.c.requestHistory(4096)+ await vi.waitFor(() => expect(pages(v)).toHaveLength(1))+ expect(t.reads).toEqual([4096])+ expect(pages(v)[0]).toMatchObject({ before: 4096, olderCursor: 0, start: null })+ })++ it('says unsupported with no reader, and error on a failed read; the viewer stays connected', async () => {+ const none = setup({ role: 'viewer' })+ none.host.start()+ const a = await openViewer(none)+ a.c.requestHistory()+ await vi.waitFor(() => expect(pages(a)).toHaveLength(1))+ expect(pages(a)[0].status).toBe('unsupported')+ const failing = setup({ role: 'viewer', history: async () => { throw new Error('ssh: master is gone') } })+ failing.host.start()+ const b = await openViewer(failing)+ b.c.requestHistory()+ await vi.waitFor(() => expect(pages(b)).toHaveLength(1))+ expect(pages(b)[0]).toMatchObject({ status: 'error', messages: [] })+ expect(b.log.closed).toBe(0)+ expect(failing.host.viewers()).toHaveLength(1)+ })++ it('reads one page at a time per viewer, and runs only the latest request that waited', async () => {+ let release!: () => void+ const held = new Promise<void>((r) => (release = r))+ let first = true+ const t = setup({+ role: 'viewer',+ history: async (before) => {+ if (first) {+ first = false+ await held+ }+ return page([say('user', 5_000, `b${before}`)], null)+ }+ })+ t.host.start()+ const v = await openViewer(t)+ v.c.requestHistory()+ await vi.waitFor(() => expect(t.reads).toEqual([null]))+ v.c.requestHistory(10)+ v.c.requestHistory(20)+ await settleReal()+ expect(t.reads).toEqual([null])+ release()+ await vi.waitFor(() => expect(pages(v)).toHaveLength(2), { timeout: 3000 })+ expect(t.reads).toEqual([null, 20])+ expect(pages(v).map((p) => p.before)).toEqual([null, 20])+ })++ it('ignores a malformed request: no read, no answer, no disconnect', async () => {+ const t = setup({ role: 'viewer', history: async () => page([]) })+ t.host.start()+ const p = await openRaw(t)+ p.cast(WATCH_HISTORY_CAST, [{ before: -5 }])+ p.cast(WATCH_HISTORY_CAST, ['nope'])+ await settleReal()+ expect(t.reads).toEqual([])+ expect(p.named(WATCH_EVENT.history)).toHaveLength(0)+ expect(p.closed()).toBe(0)+ })+})+/** A raw relay client with the link's viewer key: it sends whatever casts the test chooses (the real* client cannot send a malformed one), and records every event the host sends it. */function rawPeer(t: Setup, n = 0) {diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.tsindex faecb520c..1f03284ed 100644--- a/src/core/watch-link/link-host.ts+++ b/src/core/watch-link/link-host.ts@@ -147,10 +147,12 @@ import {TYPING_NAMES_MAX,WATCH_CHAT_CAST,WATCH_EVENT,+ WATCH_HISTORY_CAST,WATCH_INPUT_CAST,WATCH_PROTOCOL_VERSION,WATCH_RELEASE_CAST,WATCH_UNLOCK_CAST,+ readHistoryRequest,sanitizeChatName,sanitizeChatText,type WatchChatMessage,@@ -165,6 +167,7 @@ import { createInputSplitter, createTypingTracker, type InputSplitter } from './import { PANE_INPUT_DEADLINE_MS, WATCHER_INPUT_ROUTES, type ControlInputChunk, type WatcherInputRoute } from './pane-input'import { isTerminalReport } from '../terminal-reports'import { createStreamFilter, type StreamFilter } from './stream-filter'+import { historyPageFrom, type HistoryRead } from './history'import { createTokenBucket, type TokenBucket } from './token-bucket'import {WATCHER_BUFFER_LIMIT,@@ -214,6 +217,10 @@ export const INPUT_CHUNKS_MAX = 64export const TYPING_EVENT_MIN_MS = 1000/** A viewer is told its input was dropped at most this often. */export const DROPPED_NOTICE_MIN_MS = 10_000+/** Read-back reads start at most this often per viewer; one runs at a time, and a request that arrives+ * meanwhile waits (the newest one wins). Each read is a transcript read on the host (an ssh round trip+ * for an SSH node), so a viewer that asks in a loop must not turn into a read loop. */+export const HISTORY_MIN_INTERVAL_MS = 500/** Input from a connection that stopped controlling this recently is dropped silently: keystrokes in* flight when control ended are not a breach. Later than this, they are. */export const INPUT_GRACE_MS = 5000@@ -293,6 +300,12 @@ export interface LinkHostDeps {* 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+ /** Read-back (`watch:history`, ./history.ts): one transcript page of the link's node ending at+ * `before` (null: the newest). Rejects on a failed read. Absent: every request is answered+ * `unsupported`. The cutoff at the link's creation is applied HERE, not by the reader. */+ history?(before: number | null): Promise<HistoryRead>+ /** Whether the node is an agent with a readable conversation; asked for every (re)join's meta. */+ historySupported?(): boolean}export type LinkRuntimeStatus = 'live' | 'reconnecting' | 'refused'export interface LinkViewer {@@ -397,6 +410,12 @@ interface Conn {stableTimer: unknownrejoinAttempt: numberrejoinTimer: unknown+ /** Read-back: a read is running; the request that arrived meanwhile (the newest wins); when the last+ * read started; the timer holding the next one to HISTORY_MIN_INTERVAL_MS. */+ historyBusy: boolean+ historyNext: { before: number | null } | null+ historyLastAt: number+ historyTimer: unknownwarned: Set<string>}@@ -575,8 +594,9 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linif (c.ended) returnc.ended = trueconns.delete(c)- for (const h of [c.confirmTimer, c.rejoinTimer, c.keyframeTimer, c.settleTimer, c.stableTimer]) clearTimer(h)- c.confirmTimer = c.rejoinTimer = c.keyframeTimer = c.settleTimer = c.stableTimer = null+ for (const h of [c.confirmTimer, c.rejoinTimer, c.keyframeTimer, c.settleTimer, c.stableTimer, c.historyTimer]) clearTimer(h)+ c.confirmTimer = c.rejoinTimer = c.keyframeTimer = c.settleTimer = c.stableTimer = c.historyTimer = null+ c.historyNext = nullconst sid = c.sessionIdc.sessionId = nullc.streaming = false@@ -819,6 +839,7 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin}// A Control link's state for THIS viewer rides every (re)join; absent on every other role.if (record.role === 'controller') meta.control = controlStateFor(c)+ if (historySupported()) meta.history = trueif (!send(c, WATCH_EVENT.meta, meta)) return// The typing set is otherwise sent only when it changes: a viewer (re)joining mid-typing would// never learn it.@@ -891,6 +912,10 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Lin}function onViewerCast(c: Conn, method: string, args: unknown[]): void {// relay-host's access hook admits exactly these (watcherAccess); anything else got past it.+ if (method === WATCH_HISTORY_CAST) {+ onHistory(c, args)+ return+ }if (method === WATCH_CHAT_CAST && (record.role === 'commenter' || record.role === 'controller')) {onChat(c, args)return@@ -926,6 +951,56 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): Linpublish({ id: bytesToHex(nacl.randomBytes(8)), name, text, at: now, from: 'viewer' })}+ // --- read-back (./history.ts) ---------------------------------------------------------------------++ function historySupported(): boolean {+ try {+ return deps.historySupported?.() === true+ } catch (err) {+ warn(null, 'asking whether read-back is there failed', errorText(err))+ return false+ }+ }+ function onHistory(c: Conn, args: unknown[]): void {+ if (c.ended || c.joinedAt === null || stopped) return+ // A malformed request is ignored, like a malformed chat line: the cast itself is admitted.+ const req = readHistoryRequest(args[0])+ if (!req) return+ c.historyNext = req+ pumpHistory(c)+ }+ function pumpHistory(c: Conn): void {+ if (c.ended || stopped || c.historyBusy || c.historyTimer !== null || c.historyNext === null) return+ const wait = HISTORY_MIN_INTERVAL_MS - (deps.now() - c.historyLastAt)+ if (wait > 0) {+ c.historyTimer = deps.setTimeout(() => {+ c.historyTimer = null+ pumpHistory(c)+ }, wait)+ return+ }+ const { before } = c.historyNext+ c.historyNext = null+ c.historyBusy = true+ c.historyLastAt = deps.now()+ const read = async (): Promise<HistoryRead | null> => {+ if (!deps.history) return { kind: 'unsupported' }+ try {+ return await deps.history(before)+ } catch (err) {+ warn(c, 'a read-back failed', errorText(err))+ return null+ }+ }+ void read().then((r) => {+ c.historyBusy = false+ if (c.ended || stopped) return+ // The record is read now: the cutoff is the link's creation, whatever the reader returned.+ send(c, WATCH_EVENT.history, historyPageFrom(r, record.createdAt, before))+ pumpHistory(c)+ })+ }+// --- control (a Control link) -----------------------------------------------------------------------/** This viewer's control state, as meta and every unprompted `watch:control` carry it. */@@ -1327,6 +1402,10 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): LinstableTimer: null,rejoinAttempt: 0,rejoinTimer: null,+ historyBusy: false,+ historyNext: null,+ historyLastAt: -Infinity,+ historyTimer: null,warned: new Set()}conns.add(c)diff --git a/src/core/watch-link/service.test.ts b/src/core/watch-link/service.test.tsindex 0ef620ba2..f89f26e0b 100644--- a/src/core/watch-link/service.test.ts+++ b/src/core/watch-link/service.test.ts@@ -131,6 +131,8 @@ interface Opts {verifyPassword?: (pw: string, h: ControlPasswordHash) => Promise<boolean>/** The REAL link host (and a relay transport no test reaches) instead of the fake. */realHost?: boolean+ history?: WatchLinkServiceDeps['history']+ historySupported?: WatchLinkServiceDeps['historySupported']}function service(o: Opts = {}) {const file = join(testTmpDir('wls-'), 'watch-links.json')@@ -162,6 +164,8 @@ function service(o: Opts = {}) {...(o.hashPassword ? { hashPassword: o.hashPassword } : {}),...(o.verifyPassword ? { verifyPassword: o.verifyPassword } : {}),...(o.unsupported ? { unsupported: true } : {}),+ ...(o.history ? { history: o.history } : {}),+ ...(o.historySupported ? { historySupported: o.historySupported } : {}),...(o.persistTimeoutMs ? { persistTimeoutMs: o.persistTimeoutMs } : {}),...(o.workspaceWaitMs ? { workspaceWaitMs: o.workspaceWaitMs } : {}),...(o.now ? { now: o.now } : {})@@ -561,6 +565,27 @@ describe('createWatchLinkService — ending a link', () => {expect(t.s.list()).toHaveLength(1)})+ it('binds read-back to the link\'s own node: a viewer names only a cursor', async () => {+ const reads: [string, number | null][] = []+ const t = service({+ history: async (nodeId, before) => {+ reads.push([nodeId, before])+ return { kind: 'unsupported' }+ },+ historySupported: (nodeId) => nodeId === 'n2'+ })+ expect((await t.s.create(req({ nodeId: 'n2' }))).ok).toBe(true)+ const deps = t.hosts.made[0].deps+ expect(deps.historySupported?.()).toBe(true)+ await deps.history?.(77)+ expect(reads).toEqual([['n2', 77]])+ // Without the shell's reader there is no read-back at all.+ const bare = service()+ expect((await bare.s.create(req())).ok).toBe(true)+ expect(bare.hosts.made[0].deps.history).toBeUndefined()+ expect(bare.hosts.made[0].deps.historySupported).toBeUndefined()+ })+it('a server-side end (onGone) ends the link locally, tells the owner, and does not revoke again', async () => {const t = service()const r = await t.s.create(req())diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.tsindex 8fc941b74..4f6e73627 100644--- a/src/core/watch-link/service.ts+++ b/src/core/watch-link/service.ts@@ -90,6 +90,7 @@ import {import { controlPasswordProblem } from '../../shared/watch-link-password'import type { HostTokenResult, WatchLinkApi as WatchLinkApiClient } from './api'import { WRONG_PER_LINK, createLinkHost, type LinkHost, type QuietClients, type WatchPty } from './link-host'+import type { HistoryRead } from './history'import { hashControlPassword, verifyControlPassword, type ControlPasswordHash } from './password'import {WatchLinkStoreUnreadable,@@ -133,6 +134,13 @@ export interface WatchLinkServiceDeps {/** Can this node's terminal take a Control link's input (`PtyManager.nodeControlSupport`)? Absent,* throwing or anything else answers `unknown`, which leaves the create to decide. */controlSupport?(nodeId: string): ControlSupport+ /** Read-back (`watch:history`): one transcript page of `nodeId`'s conversation ending at `before`+ * (null: the newest), through the SAME reader as the ⌘M panel and the phone's `chat.page`. Rejects+ * on a failed read. The link host cuts every page at the link's creation (./history.ts); the reader+ * knows nothing of links. Absent: viewers are told read-back is not available. */+ history?(nodeId: string, before: number | null): Promise<HistoryRead>+ /** Is `nodeId` an agent whose conversation `history` can read? Rides every join's meta. */+ historySupported?(nodeId: string): boolean/** This shell cannot host links (the Server Edition until it has a license layer — R43). */unsupported?: booleannow?(): number@@ -565,6 +573,9 @@ export function createWatchLinkService(deps: WatchLinkServiceDeps): WatchLinkSernotice({ kind: 'joined', linkId: r.linkId, nodeId: r.nodeId, title: stripBidiControls(r.title), viewers: count }),onGone: (reason) => end(r.linkId, reason, { serverRevoke: false, notify: true }),verifyPassword: (pw) => checkPassword(r, pw),+ // Bound to THIS link's node: a viewer names no node, only a cursor.+ ...(deps.history ? { history: (before: number | null) => deps.history!(r.nodeId, before) } : {}),+ ...(deps.historySupported ? { historySupported: () => deps.historySupported!(r.nodeId) } : {}),onControlTaken: (name) => {notice({kind: 'control-taken',diff --git a/src/core/watch-link/watcher-policy.test.ts b/src/core/watch-link/watcher-policy.test.tsindex fd7530797..0bd2dbe88 100644--- a/src/core/watch-link/watcher-policy.test.ts+++ b/src/core/watch-link/watcher-policy.test.ts@@ -4,6 +4,7 @@ import { encodePtyData, decodePtyData } from '../../shared/rpc'import {WATCH_CHAT_CAST,WATCH_EVENT,+ WATCH_HISTORY_CAST,WATCH_INPUT_CAST,WATCH_RELEASE_CAST,WATCH_UNLOCK_CAST,@@ -39,15 +40,18 @@ describe('watcherAccess', () => {// The whole inbound surface, three roles by every viewer method there is (plus one that is not),// as a request and as a cast. Exactly these are admitted; everything else is the same refusal.- it('admits exactly: chat for commenter and controller, unlock / input / release for controller, all as casts', () => {+ it('admits exactly: history for every role, chat for commenter and controller, unlock / input / release for controller, all as casts', () => {const admitted = new Set([+ `cast ${WATCH_HISTORY_CAST} viewer`,+ `cast ${WATCH_HISTORY_CAST} commenter`,+ `cast ${WATCH_HISTORY_CAST} controller`,`cast ${WATCH_CHAT_CAST} commenter`,`cast ${WATCH_CHAT_CAST} controller`,`cast ${WATCH_UNLOCK_CAST} controller`,`cast ${WATCH_INPUT_CAST} controller`,`cast ${WATCH_RELEASE_CAST} controller`])- const methods = [WATCH_CHAT_CAST, WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, 'watch:anything']+ const methods = [WATCH_CHAT_CAST, WATCH_HISTORY_CAST, WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, 'watch:anything']let allowed = 0for (const kind of ['req', 'cast'] as const) {for (const method of methods) {diff --git a/src/core/watch-link/watcher-policy.ts b/src/core/watch-link/watcher-policy.tsindex c457893ca..9ec32dbc5 100644--- a/src/core/watch-link/watcher-policy.ts+++ b/src/core/watch-link/watcher-policy.ts@@ -1,8 +1,10 @@// The `watcher` relay role, as two RelayHostHooks pieces. It deliberately does NOT go through// access-policy.ts's `decideAccess`: that function evaluates any non-editor role against the whole// VIEW table (files, git, presence, board log), and a live link may reach none of it.-// - Inbound: every request and cast is refused, except the chat cast on a Commenter or Control-// link, and the unlock / input / release casts on a Control link. The policy knows only the role:+// - Inbound: every request and cast is refused, except the read-back cast (`watch:history`) on+// every link, the chat cast on a Commenter or Control link, and the unlock / input / release casts+// on a Control link. The read-back is only ever the watched agent's conversation since the link+// was created (./history.ts), which every role was shown live. The policy knows only the role:// whether THIS viewer may type (it unlocked with the link's password) is the link host's// per-connection state, and the link host refuses input from a viewer that is not controlling.// - Outbound, deny by default too: `watch:*` events, this viewer's own pty data frames (filtered,@@ -21,6 +23,7 @@ import { decodePtyData, decodePtyDataSessionId, encodePtyData } from '../../sharimport {WATCH_CHAT_CAST,WATCH_EVENT_PREFIX,+ WATCH_HISTORY_CAST,WATCH_INPUT_CAST,WATCH_RELEASE_CAST,WATCH_UNLOCK_CAST,@@ -37,10 +40,11 @@ export const WATCHER_RESUME_BELOW = 256 * 1024const CONTROL_CASTS: ReadonlySet<string> = new Set([WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST])-/** The ONLY admits: chat for a Commenter or Control link, unlock / input / release for a Control- * link, all as casts. Every request, and everything else, is refused. */+/** The ONLY admits: the read-back for every link, chat for a Commenter or Control link, unlock /+ * input / release for a Control link, all as casts. Every request, and everything else, is refused. */export function watcherAccess(kind: 'req' | 'cast', method: string, role: WatchLinkRole): AccessDecision {if (kind !== 'cast') return { allow: false, message: WATCHER_REFUSAL }+ if (method === WATCH_HISTORY_CAST) return { allow: true }if (method === WATCH_CHAT_CAST && (role === 'commenter' || role === 'controller')) return { allow: true }if (CONTROL_CASTS.has(method) && role === 'controller') return { allow: true }return { allow: false, message: WATCHER_REFUSAL }diff --git a/src/main/index.ts b/src/main/index.tsindex 74389b509..cb6a07eaa 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -124,6 +124,7 @@ import {} from '../core/watch-link/service'import { createWatchLinkApi } from '../core/watch-link/api'import { WatchLinkStore } from '../core/watch-link/store'+import { HISTORY_READ_BYTES } from '../core/watch-link/history'import { createWatchPty, watchRemoteFor, watchRemoteRecords, type WatchRemote } from '../core/watch-link/pty-seam'import { SshStore } from './ssh-store'import { GitService } from '../core/git-service'@@ -297,7 +298,7 @@ import { codexHome } from '../core/usage/codex-usage'import { isAsyncSubagentLaunch, isCursorPayload, grokRawFields, type NormalizedAgentEvent } from '../shared/agents/normalize'import { applyGrokHookSession } from '../core/grok-hook-session'import { agentAccountColor } from '../shared/agents/account-color'-import { capabilityAgentId } from '../shared/agents/config'+import { canChat, capabilityAgentId } from '../shared/agents/config'import {setRemoteTranscriptReader,TITLE_TAIL_BYTES,@@ -415,7 +416,8 @@ import {loadOrCreateKeyPair,relayAllowed,API_BASE as RELAY_API_BASE,- RELAY_URL+ RELAY_URL,+ type HostChatOps} from './remote/host-service'import { initStandingHost } from './remote/standing-host'import { initRelayHost } from './remote/relay-host-service'@@ -3616,6 +3618,12 @@ app.whenReady().then(async () => {// 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).+ // Read-back for a link's viewers (docs/live-links.md → Read-back) reads through the phone Chat+ // screen's page reader (host-chat.ts, `hostBridge.chat` below): the node from this machine's+ // records, the renderer's session id first, an SSH node read on its host and never here. That reader+ // is built later in boot, so it is bound late; a read-back before it exists is a failed read the+ // viewer may repeat. The link host cuts every page at the link's creation; this only reads.+ let watchHistoryChat: Pick<HostChatOps, 'page'> | null = nullconst watchRemote = (nodeId: string): WatchRemote =>watchRemoteFor(nodeId, watchRemoteRecords(workspaceStore, (connectionId) => sshProjectManager?.refForProject(connectionId)))watchLinks = createWatchLinkService({@@ -3650,6 +3658,17 @@ app.whenReady().then(async () => {// 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) => (watchRemote(nodeId).requireRemote ? 'ok' : ptyManager.nodeControlSupport(nodeId)),+ history: async (nodeId, before) => {+ const chat = watchHistoryChat+ if (!chat) throw new Error('read-back is not ready yet')+ const page = await chat.page(nodeId, before === null ? { maxBytes: HISTORY_READ_BYTES } : { before, maxBytes: HISTORY_READ_BYTES })+ return page === null || page === 'unsupported' ? { kind: 'unsupported' } : { kind: 'page', result: page }+ },+ // The same question host-chat's page asks before it reads: an agent the ⌘M view can render.+ historySupported: (nodeId) => {+ const agentId = workspaceStore.getNodeResolved(nodeId)?.agentId ?? mirrorEntry(nodeId)?.agentId+ return !!agentId && canChat(capabilityAgentId(agentId))+ },emit: (channel, ...args) => sendToOwners(corePlatform, channel, ...args)})registerWatchLinkIpc(corePlatform, watchLinks)@@ -5027,6 +5046,7 @@ app.whenReady().then(async () => {// to have focused (that gap read as "cwd is outside the shared project roots" on the phone).workspaceRoots: () => workspaceStore.localProjectCwds()}+ watchHistoryChat = hostBridge.chat// The renderer owns the Eco hibernation flag (persisted in ITS localStorage) and main only// mirrors it — same direction as `terminalFocused`. Feeds the agent-status mirror so the phone// renders SLEEPING (and re-fed at renderer boot from the persisted store, so a desktop restartdiff --git a/src/main/watch-link-wiring.test.ts b/src/main/watch-link-wiring.test.tsindex 8a5ba3dbe..a5eea6a20 100644--- a/src/main/watch-link-wiring.test.ts+++ b/src/main/watch-link-wiring.test.ts@@ -64,6 +64,21 @@ describe('live-link wiring', () => {expect(s).toMatch(/unseal: corePlatform\.unsealSecret\?\.bind\(corePlatform\)/)})+ it('the desktop wires read-back through the phone Chat screen\'s page reader, bound late', () => {+ const s = read(MAIN)+ const block = blockAfter(s, 'watchLinks = createWatchLinkService({', ' ')+ // Both deps are optional: dropping either compiles and ships read-back inert.+ expect(block).toMatch(/history: async \(nodeId, before\) => \{/)+ expect(block).toMatch(/chat\.page\(nodeId, /)+ expect(block).toMatch(/historySupported: \(nodeId\) => \{/)+ expect(block).toMatch(/canChat\(capabilityAgentId\(agentId\)\)/)+ // Declared before the service, assigned once host-chat exists (a later const would be a TDZ throw).+ const decl = s.indexOf("let watchHistoryChat: Pick<HostChatOps, 'page'> | null = null")+ expect(decl).toBeGreaterThan(-1)+ expect(decl).toBeLessThan(s.indexOf('watchLinks = createWatchLinkService({'))+ expect(s.indexOf('watchHistoryChat = hostBridge.chat')).toBeGreaterThan(s.indexOf('chat: createHostChat({'))+ })+it('the desktop stops the hosts on the FIRST quit pass, inside the raced flush and before killAll', () => {const s = read(MAIN)const quit = s.slice(s.indexOf("app.on('before-quit'"))diff --git a/src/shared/host-control.test.ts b/src/shared/host-control.test.tsindex d67e23bcb..f5553a5c8 100644--- a/src/shared/host-control.test.ts+++ b/src/shared/host-control.test.ts@@ -1,7 +1,7 @@import { describe, it, expect } from 'vitest'import { IPC } from './ipc'import { HOST_ONLY_REFUSAL, isHostOnlyChannel } from './host-control'-import { WATCH_CHAT_CAST, WATCH_EVENT, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST } from './watch-link/protocol'+import { WATCH_CHAT_CAST, WATCH_EVENT, WATCH_HISTORY_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST } from './watch-link/protocol'/*** The ONE list both shells consult. It exists so the desktop's relay admission and any future@@ -93,7 +93,7 @@ describe('isHostOnlyChannel', () => {expect(isHostOnlyChannel('watch:meta')).toBe(false)// Every viewer message, Control's included (unlock, input, release, the per-viewer control state// and the typing set).- const viewer = [...Object.values(WATCH_EVENT), WATCH_CHAT_CAST, WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST]+ const viewer = [...Object.values(WATCH_EVENT), WATCH_CHAT_CAST, WATCH_HISTORY_CAST, WATCH_UNLOCK_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST]for (const ch of viewer) {expect(ch.startsWith('watch:'), ch).toBe(true)expect(isHostOnlyChannel(ch), ch).toBe(false)diff --git a/src/shared/watch-link/client.ts b/src/shared/watch-link/client.tsindex 3ef635b79..6091bc117 100644--- a/src/shared/watch-link/client.ts+++ b/src/shared/watch-link/client.ts@@ -1,15 +1,15 @@// The browser half of a live link: the CLIENT role of src/core/relay/relay-socket.ts (handshake,// sealed frames, keepalive) plus the trust gate's client obligation (send our own trust:confirm,// open only once the host's arrives). After the handshake it sends only its own trust:confirm,-// keepalives, and the viewer's casts: chat (`sendChat`) and, on a Control link, unlock / input /-// release. Whether a cast is accepted is the link host's decision, and an obligation on it: chat only+// keepalives, and the viewer's casts: read-back (`requestHistory`), chat (`sendChat`) and, on a+// Control link, unlock / input / release. Whether a cast is accepted is the link host's decision, and an obligation on it: chat only// on a Commenter or Control link, input only from a viewer that unlocked with the link's password.// Nothing on this side enforces that; `sendInput`'s size cap only keeps an oversized cast off the wire.import nacl from 'tweetnacl'import { b64ToBytes, bytesToB64, concatBytes, utf8 } from './bytes'import { hkdfSha256 } from './hkdf'import type { WatchLinkKeys } from './keys'-import { INPUT_MAX, WATCH_CHAT_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST } from './protocol'+import { INPUT_MAX, WATCH_CHAT_CAST, WATCH_HISTORY_CAST, WATCH_INPUT_CAST, WATCH_RELEASE_CAST, WATCH_UNLOCK_CAST, readHistoryRequest } from './protocol'import {NONCE_BYTES, RELAY_SESSION_INFO, ROLE_CLIENT, ROLE_HOST, TAG_RPC, TAG_TUNNEL_BIN, TAG_TUNNEL_TEXT,decodePtyFrame, openBox, parseTunnelJson, readHeader, sealBox, withHeader@@ -44,6 +44,10 @@ export interface WatchClientEvents {* own the client never reaches a terminal event: no `onOpen`, `onDenied` or `onClose`.*/export interface WatchClient {+ /** Ask for a page of the agent's conversation since the link was shared: the newest, or the one+ * before `before` (a page's `olderCursor`). The answer is a `watch:history` event. A cursor the host+ * would refuse is refused here (false, nothing sent). */+ requestHistory(before?: number): booleansendChat(name: string, text: string): boolean/** Ask to type, with the link's password. The answer is a `watch:control` event, not a return value. */unlock(name: string, password: string): boolean@@ -216,6 +220,11 @@ export function connectWatchClient(opts: {}return {+ requestHistory(before) {+ const arg = before === undefined ? {} : { before }+ if (readHistoryRequest(arg) === null) return false+ return cast(WATCH_HISTORY_CAST, [arg])+ },sendChat: (name, text) => cast(WATCH_CHAT_CAST, [{ name, text }]),unlock: (name, password) => cast(WATCH_UNLOCK_CAST, [{ name, password }]),sendInput(data) {diff --git a/src/shared/watch-link/protocol.history.test.ts b/src/shared/watch-link/protocol.history.test.tsnew file mode 100644index 000000000..5aac97657--- /dev/null+++ b/src/shared/watch-link/protocol.history.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from 'vitest'+import {+ HISTORY_MESSAGES_MAX,+ HISTORY_PARTS_MAX,+ HISTORY_TEXT_MAX,+ HISTORY_TOOL_ARG_MAX,+ WATCH_EVENT,+ WATCH_HISTORY_CAST,+ readHistoryPage,+ readHistoryRequest,+ sanitizeHistoryText+} from './protocol'++const msg = (role: 'user' | 'assistant', at: number, text: string) => ({ role, at, parts: [{ kind: 'text', text }] })+const page = (over: Record<string, unknown> = {}) => ({+ before: null,+ status: 'ok',+ since: 1000,+ messages: [msg('user', 1500, 'hi')],+ olderCursor: null,+ start: 'shared',+ ...over+})++describe('watch:history names', () => {+ it('is a watch: cast and event, never the owner namespace', () => {+ expect(WATCH_HISTORY_CAST).toBe('watch:history')+ expect(WATCH_EVENT.history).toBe('watch:history')+ expect(WATCH_HISTORY_CAST.startsWith('watchLink:')).toBe(false)+ })+})++describe('sanitizeHistoryText', () => {+ it('keeps newlines and tabs, drops CR, other controls, ESC and bidi controls', () => {+ expect(sanitizeHistoryText('a\r\nb\tc\x1b[31mde\u0007', 100)).toBe('a\nb\tc[31mde')+ })+ it('caps by code point and marks the cut', () => {+ const out = sanitizeHistoryText('😀'.repeat(10), 7)+ expect(out).toBe('😀😀😀…')+ expect(out!.length).toBeLessThanOrEqual(7)+ })+ it('answers null for a non-string or an empty result', () => {+ expect(sanitizeHistoryText(5, 10)).toBeNull()+ expect(sanitizeHistoryText('\x00\x01', 10)).toBeNull()+ })+})++describe('readHistoryRequest', () => {+ it('reads an absent or a non-negative integer cursor', () => {+ expect(readHistoryRequest(undefined)).toEqual({ before: null })+ expect(readHistoryRequest({})).toEqual({ before: null })+ expect(readHistoryRequest({ before: 42 })).toEqual({ before: 42 })+ })+ it('refuses anything else', () => {+ for (const before of [-1, 1.5, '3', Number.NaN, Number.MAX_SAFE_INTEGER + 1, null]) {+ expect(readHistoryRequest({ before })).toBeNull()+ }+ expect(readHistoryRequest('x')).toBeNull()+ })+})++describe('readHistoryPage', () => {+ it('reads a well-formed page', () => {+ expect(readHistoryPage(page())).toEqual(page())+ })+ it('refuses an unknown status or start, or a bad cursor', () => {+ expect(readHistoryPage(page({ status: 'nope' }))).toBeNull()+ expect(readHistoryPage(page({ start: 'nope' }))).toBeNull()+ expect(readHistoryPage(page({ olderCursor: -3 }))).toBeNull()+ expect(readHistoryPage(page({ before: 'x' }))).toBeNull()+ expect(readHistoryPage(null)).toBeNull()+ })+ it('drops a message before the link was shared, or with no time', () => {+ const p = readHistoryPage(page({ messages: [msg('user', 999, 'old'), { role: 'user', parts: [] }, msg('assistant', 1000, 'new')] }))+ expect(p!.messages).toEqual([msg('assistant', 1000, 'new')])+ })+ it('drops a malformed part and a message left with none', () => {+ const p = readHistoryPage(+ page({+ messages: [+ { role: 'assistant', at: 1200, parts: [{ kind: 'html', text: '<b>' }, { kind: 'text', text: 'ok' }] },+ { role: 'assistant', at: 1300, parts: [{ kind: 'text', text: '\x00' }] },+ { role: 'system', at: 1400, parts: [{ kind: 'text', text: 'x' }] }+ ]+ })+ )+ expect(p!.messages).toEqual([{ role: 'assistant', at: 1200, parts: [{ kind: 'text', text: 'ok' }] }])+ })+ it('caps tool names and args, parts and messages', () => {+ const p = readHistoryPage(+ page({+ messages: Array.from({ length: HISTORY_MESSAGES_MAX + 5 }, (_, i) => ({+ role: 'assistant',+ at: 2000 + i,+ parts: Array.from({ length: HISTORY_PARTS_MAX + 3 }, () => ({ kind: 'tool', name: 'Bash', arg: 'x'.repeat(HISTORY_TOOL_ARG_MAX * 2) }))+ }))+ })+ )+ expect(p!.messages).toHaveLength(HISTORY_MESSAGES_MAX)+ // The NEWEST are kept: the oldest five go.+ expect(p!.messages[0].at).toBe(2005)+ expect(p!.messages[0].parts).toHaveLength(HISTORY_PARTS_MAX)+ const tool = p!.messages[0].parts[0] as { arg: string }+ expect(tool.arg.length).toBeLessThanOrEqual(HISTORY_TOOL_ARG_MAX)+ })+ it('caps a text part', () => {+ const p = readHistoryPage(page({ messages: [msg('assistant', 1500, 'y'.repeat(HISTORY_TEXT_MAX + 50))] }))+ const text = (p!.messages[0].parts[0] as { text: string }).text+ expect(text.length).toBeLessThanOrEqual(HISTORY_TEXT_MAX)+ expect(text.endsWith('…')).toBe(true)+ })+ it('a status other than ok carries no messages', () => {+ expect(readHistoryPage(page({ status: 'error' }))!.messages).toEqual([])+ })+})diff --git a/src/shared/watch-link/protocol.ts b/src/shared/watch-link/protocol.tsindex c9e23fdbb..9b3597b01 100644--- a/src/shared/watch-link/protocol.ts+++ b/src/shared/watch-link/protocol.ts@@ -14,7 +14,9 @@ export const WATCH_EVENT = {* under it (turned off, locked). The initial state rides `watch:meta`. */control: 'watch:control',/** To every joined viewer: who typed in the last few seconds (`WatchTypingEvent`). */- typing: 'watch:typing'+ typing: 'watch:typing',+ /** To ONE viewer, the answer to its `watch:history` cast (`WatchHistoryPage`). */+ history: 'watch:history'} as const/** A viewer's chat line (Commenter and Control links). */export const WATCH_CHAT_CAST = 'watch:chat'@@ -47,6 +49,20 @@ export const WATCH_UNLOCK_CAST = 'watch:unlock'export const WATCH_INPUT_CAST = 'watch:input'/** Control links only: drop the sender back to watching. No arguments. */export const WATCH_RELEASE_CAST = 'watch:release'+/**+ * Every role: one page of the watched agent's CONVERSATION, never the terminal's history. The stream+ * is a tmux client painting on the alternate screen, so the viewer's emulator has nothing to scroll;+ * this is how a viewer reads back. `{ before?: number }` (`readHistoryRequest`): absent for the+ * newest page, else the `olderCursor` of the previous answer. Answered to that viewer alone with+ * `watch:history`.+ *+ * THE CUTOFF. A page holds only messages written at or after the moment the link was created+ * (`WatchHistoryPage.since`, the host's clock). A message with no time is never sent: nothing proves+ * it came after. What the link exposes is therefore what the terminal showed while it was shared, as+ * text, and nothing from before. Tool results are never sent (the screen shows a few lines of them+ * at most), and neither is the agent's thinking.+ */+export const WATCH_HISTORY_CAST = 'watch:history'/** A Control link (`controller`) is a Commenter link plus typing for whoever unlocks it with the* link's password. Every addition to this protocol is additive, so `WATCH_PROTOCOL_VERSION` stays 1:@@ -71,6 +87,9 @@ export interface WatchMeta {rows: number/** A Control link's state for THIS viewer at join; absent on every other role. */control?: WatchControlEvent+ /** Present (true) when the watched node is an agent whose conversation `watch:history` can read+ * back. Absent: a plain terminal, or a host older than read-back. */+ history?: true}/** `controlling`: this viewer may type. `available`: a Control link this viewer may unlock.@@ -189,3 +208,153 @@ function clean(raw: unknown, max: number): string | null {}export const sanitizeChatText = (raw: unknown): string | null => clean(raw, CHAT_TEXT_MAX)export const sanitizeChatName = (raw: unknown): string | null => clean(raw, CHAT_NAME_MAX)++// --- read-back (`watch:history`) --------------------------------------------------------------------++/** Why a page holds no messages: `unsupported` — the node is not an agent with a readable+ * conversation; `untimed` — its conversation states no times, so nothing in it can be shown as+ * written after the link was shared; `error` — the host could not read it (try again). */+export const HISTORY_STATUSES = ['ok', 'unsupported', 'untimed', 'error'] as const+export type WatchHistoryStatus = (typeof HISTORY_STATUSES)[number]+/** Why there is nothing older (only when `olderCursor` is null): `shared` — the page reached the+ * moment the link was created; `conversation` — it reached the start of the conversation;+ * `cut` — the host's reader for this agent cannot page further back. */+export const HISTORY_STARTS = ['shared', 'conversation', 'cut'] as const+export type WatchHistoryStart = (typeof HISTORY_STARTS)[number]+export type WatchHistoryPart = { kind: 'text'; text: string } | { kind: 'tool'; name: string; arg: string }+export interface WatchHistoryMessage {+ role: 'user' | 'assistant'+ /** When the line was written, epoch ms on the host's clock; never before `since`. */+ at: number+ parts: WatchHistoryPart[]+}+export interface WatchHistoryPage {+ /** The cursor this page answers (`null`: the newest page). */+ before: number | null+ status: WatchHistoryStatus+ /** When the link was created (the host's clock): nothing older is ever on a page. */+ since: number+ /** Oldest first. */+ messages: WatchHistoryMessage[]+ /** Ask for this as `before` to read older messages; null when there is nothing older to show. */+ olderCursor: number | null+ /** Why there is nothing older; null while `olderCursor` is set. */+ start: WatchHistoryStart | null+}++/** One text part, in UTF-16 units (the cut ends in `…`). */+export const HISTORY_TEXT_MAX = 20_000+export const HISTORY_TOOL_NAME_MAX = 64+export const HISTORY_TOOL_ARG_MAX = 200+export const HISTORY_PARTS_MAX = 64+/** Messages on one page; the NEWEST are kept. */+export const HISTORY_MESSAGES_MAX = 200+/** All the text on one page. Past it, the OLDER messages' text is cut to `…` (they keep their place). */+export const HISTORY_PAGE_TEXT_MAX = 400_000+const HISTORY_CURSOR_MAX = Number.MAX_SAFE_INTEGER+// Every C0 control but TAB and LF (CR is folded into LF first), DEL and the C1 controls. ESC goes with+// them: the page renders text, never a terminal sequence.+const HISTORY_CONTROLS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g++const isCursor = (x: unknown): x is number => typeof x === 'number' && Number.isInteger(x) && x >= 0 && x <= HISTORY_CURSOR_MAX++/** Multi-line text a viewer may read: LF and TAB kept, CR folded into LF, every other control and+ * every bidi control removed, at most `max` UTF-16 units (a cut ends in `…`). Null when nothing is+ * left. */+export function sanitizeHistoryText(raw: unknown, max: number): string | null {+ if (typeof raw !== 'string' || max < 2) return null+ const s = capUnits(raw, max * RAW_FACTOR)+ .replace(/\r\n?/g, '\n')+ .replace(HISTORY_CONTROLS, '')+ .replace(BIDI_CONTROLS, '')+ .replace(/^\n+/, '')+ .replace(/\s+$/, '')+ if (!s) return null+ return s.length <= max ? s : `${capUnits(s, max - 1)}…`+}++/** A `watch:history` cast's argument, or null when it is not one. */+export function readHistoryRequest(x: unknown): { before: number | null } | null {+ if (x === undefined) return { before: null }+ if (!x || typeof x !== 'object') return null+ const before = (x as Record<string, unknown>).before+ if (before === undefined) return { before: null }+ return isCursor(before) ? { before } : null+}++function readHistoryPart(x: unknown): WatchHistoryPart | null {+ if (!x || typeof x !== 'object') return null+ const p = x as Record<string, unknown>+ if (p.kind === 'text') {+ const text = sanitizeHistoryText(p.text, HISTORY_TEXT_MAX)+ return text === null ? null : { kind: 'text', text }+ }+ if (p.kind === 'tool') {+ const name = clean(p.name, HISTORY_TOOL_NAME_MAX)+ if (name === null) return null+ return { kind: 'tool', name, arg: clean(p.arg, HISTORY_TOOL_ARG_MAX) ?? '' }+ }+ return null+}++function readHistoryMessage(x: unknown, since: number): WatchHistoryMessage | null {+ if (!x || typeof x !== 'object') return null+ const m = x as Record<string, unknown>+ if (m.role !== 'user' && m.role !== 'assistant') return null+ // The cutoff, enforced on BOTH ends: the host builds pages with it and the page re-reads them with it.+ if (typeof m.at !== 'number' || !Number.isFinite(m.at) || m.at < since) return null+ if (!Array.isArray(m.parts)) return null+ const parts: WatchHistoryPart[] = []+ for (const raw of m.parts) {+ if (parts.length >= HISTORY_PARTS_MAX) break+ const part = readHistoryPart(raw)+ if (part) parts.push(part)+ }+ return parts.length > 0 ? { role: m.role, at: m.at, parts } : null+}++/** A `watch:history` page, cleaned and bounded, or null when it is not one. The host builds every page+ * through this too, so both ends hold the same limits. */+export function readHistoryPage(x: unknown): WatchHistoryPage | null {+ if (!x || typeof x !== 'object') return null+ const p = x as Record<string, unknown>+ if (!(HISTORY_STATUSES as readonly unknown[]).includes(p.status)) return null+ if (p.before !== null && !isCursor(p.before)) return null+ if (p.olderCursor !== null && !isCursor(p.olderCursor)) return null+ if (p.start !== null && !(HISTORY_STARTS as readonly unknown[]).includes(p.start)) return null+ if (typeof p.since !== 'number' || !Number.isFinite(p.since) || p.since < 0) return null+ const since = p.since+ const messages: WatchHistoryMessage[] = []+ if (p.status === 'ok' && Array.isArray(p.messages)) {+ for (const raw of p.messages) {+ const m = readHistoryMessage(raw, since)+ if (m) messages.push(m)+ }+ }+ const kept = messages.slice(-HISTORY_MESSAGES_MAX)+ // The page's text budget, spent newest first: an older message past it keeps its place, as `…`.+ let budget = HISTORY_PAGE_TEXT_MAX+ for (let i = kept.length - 1; i >= 0; i--) {+ kept[i] = {+ ...kept[i],+ parts: kept[i].parts.map((part) => {+ if (part.kind !== 'text') return part+ if (part.text.length <= budget) {+ budget -= part.text.length+ return part+ }+ const text = budget >= 2 ? `${capUnits(part.text, budget - 1)}…` : '…'+ budget = 0+ return { kind: 'text', text }+ })+ }+ }+ return {+ before: p.before as number | null,+ status: p.status as WatchHistoryStatus,+ since,+ messages: kept,+ olderCursor: p.olderCursor as number | null,+ start: p.start as WatchHistoryStart | null+ }+}