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(renderer): live-link store and the copy the owner reads
review9e5090854ca3
diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.tsnew file mode 100644index 000000000..c10e91104--- /dev/null+++ b/src/renderer/lib/liveLink.test.ts@@ -0,0 +1,248 @@+// @vitest-environment jsdom+// jsdom so `pinNeutralMachineNoun` can pin the machine noun: several sentences name the machine+// through lib/machineName, and a literal "this computer" must not depend on the OS running the suite.+import { describe, it, expect } from 'vitest'+import {+ chipView,+ commentFromChat,+ createErrorMessage,+ DEFAULT_TTL,+ formatClock,+ formatRemaining,+ noticeText,+ NOT_IN_OPEN_PROJECT,+ PRO_GATE_FEATURE,+ ROLE_LABEL,+ SAVE_FIRST_MESSAGE,+ SERVER_EDITION_UNSUPPORTED,+ shareDisabledReason,+ statusLine,+ STOP_ALL_BUTTON,+ STOP_ALL_PALETTE_LABEL,+ STOP_FAILED_MESSAGE,+ stopAllConfirmMessage,+ TTL_OPTIONS,+ viewerName+} from './liveLink'+import type { CreateWatchLinkError, WatchLinkView } from '@shared/watch-link-types'+import { DEFAULT_WATCH_LINK_TTL, WATCH_LINK_TTLS } from '@shared/watch-link-types'+import { commentSegments } from '@shared/board-comment'+import { pinNeutralMachineNoun } from './testMachineNoun'++pinNeutralMachineNoun()++const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({+ linkId: 'L',+ nodeId: 'n',+ role: 'viewer',+ label: 'Ada',+ title: 't',+ createdAt: 0,+ expiresAt: 0,+ url: 'u',+ status: 'live',+ viewers: [],+ ...over+})+const viewer = (id: string) => ({ viewerId: id, name: null, joinedAt: 0 })++const RELAY_SENTENCE = 'Live links are created on the machine that runs this terminal.'+const R43 = 'Live links need a Pro license on this server — not available in the Server Edition yet'+const ALL_ERRORS: CreateWatchLinkError[] = [+ 'not-entitled',+ 'limit-machine',+ 'limit-active',+ 'limit-daily',+ 'rate-limited',+ 'network',+ 'license-check',+ 'relay-unavailable',+ 'node-missing',+ 'bad-request',+ 'persist-failed',+ 'unsupported'+]++describe('chipView', () => {+ it('reads LIVE, the watcher count, offline and refused', () => {+ expect(chipView([link()])).toMatchObject({ label: 'LIVE', tone: 'live' })+ expect(chipView([link({ viewers: [viewer('a')] }), link({ viewers: [viewer('b')] })])).toMatchObject({+ label: 'LIVE · 2',+ tone: 'live'+ })+ expect(chipView([link({ status: 'reconnecting' })])).toMatchObject({ label: 'LIVE · offline', tone: 'offline' })+ // The worst state wins: refused needs the owner; reconnecting comes back on its own.+ expect(chipView([link({ status: 'refused' }), link({ status: 'reconnecting' })])).toMatchObject({+ label: 'LIVE · refused',+ tone: 'refused'+ })+ })++ it('points at the popover for details, which now carries a status line (H9)', () => {+ expect(chipView([link({ status: 'refused' })]).title).toMatch(/Open it for details\.$/)+ expect(chipView([link({ status: 'reconnecting' })]).title).toMatch(/Open it for details\.$/)+ expect(chipView([link()]).title).toBe('This terminal is shared by a live link.')+ expect(chipView([link({ viewers: [viewer('a'), viewer('b')] })]).title).toBe(+ 'This terminal is shared by a live link — 2 watching.'+ )+ expect(chipView([link(), link({ linkId: 'M' })]).title).toBe('This terminal is shared by 2 live links.')+ })+})++describe('statusLine (H9)', () => {+ it('explains reconnecting and refused, and says nothing for a live link', () => {+ expect(statusLine('live')).toBeNull()+ expect(statusLine('reconnecting')).toBe(+ "Reconnecting to nodeterm's relay — viewers see no updates until it's back."+ )+ expect(statusLine('refused')).toBe(+ "nodeterm's service won't host this link — the Pro plan may have lapsed, or this build can't relay. Viewers can't join."+ )+ })+})++describe('time', () => {+ it('remaining time', () => {+ expect(formatRemaining(60 * 60_000 + 1, 0)).toBe('ends in 1 h')+ expect(formatRemaining(42 * 60_000, 0)).toBe('ends in 42 min')+ expect(formatRemaining(30_000, 0)).toBe('ends in under a minute')+ expect(formatRemaining(0, 5)).toBe('ended')+ })+ it('a clock time is hours and minutes, never seconds (H25)', () => {+ const at = new Date(2026, 9, 1, 15, 42, 37).getTime()+ expect(formatClock(at)).toBe(new Date(at).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }))+ expect(formatClock(at)).not.toContain('37')+ })+})++describe('createErrorMessage', () => {+ it('has copy for every kind', () => {+ for (const e of ALL_ERRORS) {+ for (const s of ['desktop', 'server', 'relay'] as const) expect(createErrorMessage(e, s).length).toBeGreaterThan(10)+ }+ })++ it('network never says offline, and says nothing was shared', () => {+ expect(createErrorMessage('network', 'desktop')).toBe("Couldn't reach nodeterm's service. Nothing was shared.")+ for (const e of ALL_ERRORS) expect(createErrorMessage(e, 'desktop')).not.toMatch(/offline/i)+ })++ it('unsupported depends on the surface (H1 / R43)', () => {+ expect(createErrorMessage('unsupported', 'server')).toBe(R43)+ expect(createErrorMessage('unsupported', 'relay')).toBe(RELAY_SENTENCE)+ expect(createErrorMessage('unsupported', 'desktop')).toBe("Live links can't be created here right now.")+ // Every other kind reads the same on every surface.+ for (const e of ALL_ERRORS.filter((k) => k !== 'unsupported')) {+ expect(createErrorMessage(e, 'server')).toBe(createErrorMessage(e, 'desktop'))+ }+ })++ it('node-missing names what it knows, not one cause (H8)', () => {+ expect(createErrorMessage('node-missing', 'desktop')).toBe(+ "nodeterm couldn't find that terminal in a saved project. Nothing was shared."+ )+ })++ it('persist-failed names the machine through machineName (H26)', () => {+ expect(createErrorMessage('persist-failed', 'desktop')).toBe(+ "Couldn't save the link on this computer, so it was stopped. Nothing was shared."+ )+ })++ it('the not-entitled and limit sentences', () => {+ expect(createErrorMessage('not-entitled', 'desktop')).toBe('Live links need an active Pro plan.')+ expect(createErrorMessage('limit-machine', 'desktop')).toBe('Stop a live link first — 5 can be active at once.')+ expect(createErrorMessage('relay-unavailable', 'desktop')).toBe('Live links need the installed app.')+ })+})++describe('shareDisabledReason (H1)', () => {+ it('answers in order: Server Edition, relay tab, the limit', () => {+ expect(shareDisabledReason({ serverEdition: true, relayTab: true, activeLinks: 5 })).toBe(R43)+ expect(SERVER_EDITION_UNSUPPORTED).toBe(R43)+ expect(shareDisabledReason({ serverEdition: false, relayTab: true, activeLinks: 5 })).toBe(RELAY_SENTENCE)+ expect(shareDisabledReason({ serverEdition: false, relayTab: false, activeLinks: 5 })).toBe(+ 'Stop a live link first — 5 can be active at once.'+ )+ expect(shareDisabledReason({ serverEdition: false, relayTab: false, activeLinks: 4 })).toBeNull()+ })+})++describe('noticeText', () => {+ it('joined and every end reason', () => {+ expect(noticeText({ kind: 'joined', linkId: 'L', nodeId: 'n', title: 'build', viewers: 2 })).toBe(+ 'Someone started watching build (2 watching).'+ )+ expect(noticeText({ kind: 'ended', linkId: 'L', nodeId: 'n', title: 'build', reason: 'expired' })).toBe(+ 'The live link to build expired.'+ )+ expect(noticeText({ kind: 'ended', linkId: 'L', nodeId: 'n', title: 'build', reason: 'node-gone' })).toBe(+ 'The live link to build ended — the terminal is no longer on any canvas.'+ )+ expect(noticeText({ kind: 'ended', linkId: 'L', nodeId: 'n', title: 'build', reason: 'revoked' })).toBe(+ "nodeterm's service ended the live link to build."+ )+ })++ it('not-persistent names no cause it did not measure (H7, H26)', () => {+ expect(noticeText({ kind: 'not-persistent' })).toBe(+ "Live links aren't being saved on this computer right now. They keep working until you quit."+ )+ })++ it('an unknown kind is no notice', () => {+ expect(noticeText({ kind: 'from-a-newer-core' } as never)).toBeNull()+ })++ it('strips bidi controls from a title before it reaches the strip', () => {+ const t = noticeText({ kind: 'joined', linkId: 'L', nodeId: 'n', title: 'ab', viewers: 1 })+ expect(t).toBe('Someone started watching ab (1 watching).')+ })+})++describe('fixed lists (H19)', () => {+ it('TTL options come from the shared list, in order, with the labels the spec names', () => {+ expect(TTL_OPTIONS.map((o) => o.value)).toEqual([...WATCH_LINK_TTLS])+ expect(TTL_OPTIONS.map((o) => o.value)).toEqual([900, 3600, 28800, 86400])+ expect(TTL_OPTIONS.map((o) => o.label)).toEqual(['15 min', '1 hour', '8 hours', '24 hours'])+ expect(DEFAULT_TTL).toBe(DEFAULT_WATCH_LINK_TTL)+ expect(ROLE_LABEL).toEqual({ viewer: 'Can watch', commenter: 'Can watch and chat' })+ })+})++describe('copy Task 17 reads (R47, R48, R52, H11, H23, H26)', () => {+ it('is the exact ruled text', () => {+ expect(SAVE_FIRST_MESSAGE).toBe("Save the canvas first — this terminal isn't saved yet. Nothing was shared.")+ expect(STOP_ALL_PALETTE_LABEL).toBe('Stop all live links (every machine on this license)')+ expect(STOP_ALL_BUTTON).toBe('Stop all')+ expect(stopAllConfirmMessage()).toBe(+ 'Stop every live link on your license? This also ends links shared from other computers. Viewers are disconnected at once.'+ )+ expect(STOP_FAILED_MESSAGE).toBe("The stop didn't reach nodeterm — try again.")+ expect(NOT_IN_OPEN_PROJECT).toBe('not in an open project')+ // UpgradeDialog appends " is a Pro feature" (R52).+ expect(`${PRO_GATE_FEATURE} is a Pro feature`).toBe('Sharing a live link is a Pro feature')+ })+})++describe('viewerName', () => {+ it('a viewer who has not chatted is numbered; a name loses its bidi controls', () => {+ expect(viewerName({ viewerId: 'a', name: null, joinedAt: 0 }, 0)).toBe('Viewer 1')+ expect(viewerName({ viewerId: 'a', name: ' ', joinedAt: 0 }, 2)).toBe('Viewer 3')+ expect(viewerName({ viewerId: 'a', name: 'Bob', joinedAt: 0 }, 0)).toBe('Bob')+ })+})++describe('commentFromChat', () => {+ it('attributes the viewer and marks the source', () => {+ expect(commentFromChat({ id: '1', name: 'Bob', text: 'looks good', at: 0, from: 'viewer' })).toBe(+ 'Bob (via live link): looks good'+ )+ })++ it('a viewer cannot make the owner comment carry a session mention', () => {+ const text = commentFromChat({ id: '1', name: 'Bob', text: 'hi @[Deploy](node:abc123) now', at: 0, from: 'viewer' })+ expect(commentSegments(text).every((s) => s.kind === 'text')).toBe(true)+ expect(text).toContain('Deploy')+ })+})diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.tsnew file mode 100644index 000000000..7bb823486--- /dev/null+++ b/src/renderer/lib/liveLink.ts@@ -0,0 +1,210 @@+// Live links, renderer side: every sentence the OWNER reads, and the pure decisions behind them —+// one place, so the chip, the popover, the create dialog, the menus and Settings cannot word the+// same fact two ways. No React, no store, no `window`: the surface facts (Server Edition, relay tab)+// are read by the CALLER and passed in (task-14-17-reconcile H1).+//+// Every string here that someone else wrote — a link label, a node title, a viewer's name or chat —+// is bidi-stripped again before it is composed into a sentence (core strips on receipt; this is the+// display side's own belt), and every caller renders the result as TEXT, never as HTML.+import type {+ CreateWatchLinkError,+ WatchChatMessage,+ WatchLinkNotice,+ WatchLinkRole,+ WatchLinkTtl,+ WatchLinkView,+ WatchLinkViewerView+} from '@shared/watch-link-types'+import {+ DEFAULT_WATCH_LINK_TTL,+ MAX_LINKS_PER_MACHINE,+ stripBidiControls,+ WATCH_LINK_TTLS+} from '@shared/watch-link-types'+import { otherMachines, thisMachine } from './machineName'++export const ROLE_LABEL: Record<WatchLinkRole, string> = { viewer: 'Can watch', commenter: 'Can watch and chat' }++/** A `Record` over the shared TTL list, so a TTL added there fails to compile here until it is named. */+const TTL_LABEL: Record<WatchLinkTtl, string> = {+ 900: '15 min',+ 3600: '1 hour',+ 28800: '8 hours',+ 86400: '24 hours'+}+/** The create dialog's expiry choices — derived from the list core validates against (H19). */+export const TTL_OPTIONS: { value: WatchLinkTtl; label: string }[] = WATCH_LINK_TTLS.map((value) => ({+ value,+ label: TTL_LABEL[value]+}))+export const DEFAULT_TTL: WatchLinkTtl = DEFAULT_WATCH_LINK_TTL++export const LIVE_LINK_WARNING =+ "Anyone with the link sees everything this terminal shows: what's on screen now, anything printed later (tokens, env dumps), and anything you scroll back to. 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.'++/** The R43 sentence — the Server Edition has no license layer yet. Never paired with an Upgrade button. */+export const SERVER_EDITION_UNSUPPORTED =+ 'Live links need a Pro license on this server — not available in the Server Edition yet'+const RELAY_TAB_UNSUPPORTED = 'Live links are created on the machine that runs this terminal.'+const LIMIT_MACHINE = `Stop a live link first — ${MAX_LINKS_PER_MACHINE} can be active at once.`++/** `requireProOr`'s feature argument: UpgradeDialog renders "<feature> is a Pro feature" (R52). */+export const PRO_GATE_FEATURE = 'Sharing a live link'+/** R47: the create dialog's flush before create failed (or the canvas is under a conflict). */+export const SAVE_FIRST_MESSAGE = "Save the canvas first — this terminal isn't saved yet. Nothing was shared."+/** H23: `revoke`/`revokeAll` rejected (the Server Edition's socket was down). */+export const STOP_FAILED_MESSAGE = "The stop didn't reach nodeterm — try again."+/** R48: Stop all revokes every link of the LICENSE, other machines included — both entry points confirm. */+export const STOP_ALL_PALETTE_LABEL = 'Stop all live links (every machine on this license)'+export const STOP_ALL_BUTTON = 'Stop all'+export function stopAllConfirmMessage(): string {+ return `Stop every live link on your license? This also ends links shared from ${otherMachines()}. Viewers are disconnected at once.`+}+/** H11: a Settings row whose node no open project holds. */+export const NOT_IN_OPEN_PROJECT = 'not in an open project'++export type LiveLinkTone = 'live' | 'offline' | 'refused'++/**+ * What the chip says for one node's links. The WORST state wins: `refused` will not come back on+ * its own and needs the owner; `reconnecting` will. The titles send the owner to the popover, which+ * carries the status line that explains it (H9).+ */+export function chipView(links: readonly WatchLinkView[]): { label: string; tone: LiveLinkTone; title: string } {+ const viewers = links.reduce((n, l) => n + l.viewers.length, 0)+ if (links.some((l) => l.status === 'refused')) {+ return {+ label: 'LIVE · refused',+ tone: 'refused',+ title: "nodeterm's service won't host a live link on this terminal. Open it for details."+ }+ }+ if (links.some((l) => l.status === 'reconnecting')) {+ return {+ label: 'LIVE · offline',+ tone: 'offline',+ title: "A live link on this terminal is reconnecting to nodeterm's relay. Open it for details."+ }+ }+ const shared = links.length > 1 ? `This terminal is shared by ${links.length} live links` : 'This terminal is shared by a live link'+ return {+ label: viewers > 0 ? `LIVE · ${viewers}` : 'LIVE',+ tone: 'live',+ title: viewers > 0 ? `${shared} — ${viewers} watching.` : `${shared}.`+ }+}++/** One line per link in the popover explaining a state that is not `live` (H9); null when live. */+export function statusLine(status: WatchLinkView['status']): string | null {+ if (status === 'reconnecting') return "Reconnecting to nodeterm's relay — viewers see no updates until it's back."+ if (status === 'refused') {+ return "nodeterm's service won't host this link — the Pro plan may have lapsed, or this build can't relay. Viewers can't join."+ }+ return null+}++export function formatRemaining(expiresAt: number, now: number): string {+ const ms = expiresAt - now+ if (ms <= 0) return 'ended'+ if (ms < 60_000) return 'ends in under a minute'+ const min = Math.floor(ms / 60_000)+ return min >= 60 ? `ends in ${Math.floor(min / 60)} h` : `ends in ${min} min`+}++/** A wall-clock time for "until 15:42" / "since 14:05" — hours and minutes, in the user's locale (H25). */+export function formatClock(ms: number): string {+ return new Date(ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })+}++/** Which surface a create or a share affordance is on — read by the caller, never by this module. */+export type LiveLinkSurface = 'desktop' | 'server' | 'relay'++/** The create dialog's error line. `unsupported` depends on the surface (H1, R43). */+export function createErrorMessage(e: CreateWatchLinkError, surface: LiveLinkSurface): string {+ switch (e) {+ case 'not-entitled':+ return 'Live links need an active Pro plan.'+ case 'limit-machine':+ return LIMIT_MACHINE+ // The API's 429 by scope — per license ≤ 15 active, ≤ 50 created per 24 h, per IP 30/min+ // (spec §Routes, POST /v1/watch-links).+ case 'limit-active':+ return 'Your license already has 15 active live links. Stop one first.'+ case 'limit-daily':+ return 'Your license created 50 live links in the last day. Try again later.'+ case 'rate-limited':+ return "nodeterm's service is limiting requests from this network. Try again in a minute."+ // A timeout, a thrown fetch, a 5xx, a malformed reply or a dropped socket — never "offline".+ case 'network':+ return "Couldn't reach nodeterm's service. Nothing was shared."+ case 'license-check':+ return "nodeterm's service couldn't confirm your license right now. Nothing was shared; try again shortly."+ case 'relay-unavailable':+ return 'Live links need the installed app.'+ // Absent AND unknown both answer node-missing, so the copy names neither (H8).+ case 'node-missing':+ return "nodeterm couldn't find that terminal in a saved project. Nothing was shared."+ case 'bad-request':+ return 'That live link request was not valid. Nothing was shared.'+ case 'persist-failed':+ return `Couldn't save the link on ${thisMachine()}, so it was stopped. Nothing was shared.`+ case 'unsupported':+ if (surface === 'server') return SERVER_EDITION_UNSUPPORTED+ if (surface === 'relay') return RELAY_TAB_UNSUPPORTED+ return "Live links can't be created here right now."+ }+}++/**+ * Why "Share live link…" is disabled, or null. ONE availability rule for every opener, checked+ * BEFORE the Pro gate so a Server Edition or relay tab never sees an Upgrade dialog (H1).+ * `serverEdition` is `isBrowserRuntime()`, `relayTab` the node's project session — both read by the+ * caller.+ */+export function shareDisabledReason(o: { serverEdition: boolean; relayTab: boolean; activeLinks: number }): string | null {+ if (o.serverEdition) return SERVER_EDITION_UNSUPPORTED+ if (o.relayTab) return RELAY_TAB_UNSUPPORTED+ if (o.activeLinks >= MAX_LINKS_PER_MACHINE) return LIMIT_MACHINE+ return null+}++/** The info strip for a notice from core; null for a kind this build does not know. */+export function noticeText(n: WatchLinkNotice): string | null {+ switch (n.kind) {+ case 'joined':+ return `Someone started watching ${stripBidiControls(n.title)} (${n.viewers} watching).`+ // It covers "the keychain refused to seal" AND "the links file could not be read", and carries+ // no reason — so it names neither (H7).+ case 'not-persistent':+ return `Live links aren't being saved on ${thisMachine()} right now. They keep working until you quit.`+ case 'ended': {+ const title = stripBidiControls(n.title)+ if (n.reason === 'expired') return `The live link to ${title} expired.`+ // Core ends a link for node-gone only on a DEFINITE absence (no project in the index holds it).+ if (n.reason === 'node-gone') return `The live link to ${title} ended — the terminal is no longer on any canvas.`+ // A server-side revoke: the service ended it. Which person or machine asked is not known here.+ return `nodeterm's service ended the live link to ${title}.`+ }+ default:+ return null+ }+}++/** A viewer as the popover lists them: the name they chatted under, else "Viewer N" (1-based). */+export function viewerName(v: WatchLinkViewerView, index: number): string {+ const name = v.name === null ? '' : stripBidiControls(v.name).trim()+ return name || `Viewer ${index + 1}`+}++/**+ * "Copy to card comments": the owner's explicit act of keeping a viewer's message (spec D2 —+ * nothing a viewer writes is stored automatically). The comment is the OWNER's, so a viewer's text+ * must not carry a board-comment mention token into it: `@[`…`](node:…)` would render as the owner+ * mentioning a session. Breaking the `@[` adjacency keeps every character and defuses the token.+ */+export function commentFromChat(m: WatchChatMessage): string {+ const text = `${stripBidiControls(m.name)} (via live link): ${stripBidiControls(m.text)}`+ return text.replace(/@\[/g, '@ [')+}diff --git a/src/renderer/state/watchLinks.test.ts b/src/renderer/state/watchLinks.test.tsnew file mode 100644index 000000000..500d09b39--- /dev/null+++ b/src/renderer/state/watchLinks.test.ts@@ -0,0 +1,196 @@+import { describe, it, expect, beforeEach } from 'vitest'+import { EMPTY_LINKS, liveChipSig, startWatchLinkSync, useWatchLinks } from './watchLinks'+import type { WatchChatMessage, WatchLinkNotice, WatchLinkView } from '@shared/watch-link-types'++const link = (id: string, nodeId: string, over: Partial<WatchLinkView> = {}): WatchLinkView => ({+ linkId: id,+ nodeId,+ role: 'commenter',+ label: 'A',+ title: 't',+ createdAt: 0,+ expiresAt: 0,+ url: 'u',+ status: 'live',+ viewers: [],+ ...over+})+const msg = (id: string, from: 'viewer' | 'sharer' = 'viewer', at = 0): WatchChatMessage => ({+ id,+ name: from === 'viewer' ? 'V' : 'A',+ text: 'x',+ at,+ from+})++beforeEach(() => useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {} }))++describe('watchLinks store', () => {+ it('indexes by node, in list order', () => {+ useWatchLinks.getState().setLinks([link('a', 'n1'), link('b', 'n1'), link('c', 'n2')])+ const s = useWatchLinks.getState()+ expect(s.byNode.n1.map((l) => l.linkId)).toEqual(['a', 'b'])+ expect(s.byNode.n2.map((l) => l.linkId)).toEqual(['c'])+ expect(s.byNode.n3).toBeUndefined()+ })++ it('keeps references for what did not change — a push for one node re-renders nothing else', () => {+ const s = useWatchLinks.getState()+ s.setLinks([link('a', 'n1'), link('c', 'n2')])+ const before = useWatchLinks.getState()+ // A fresh deserialized list (new objects, same content) except n2's link gained a viewer.+ s.setLinks([link('a', 'n1'), link('c', 'n2', { viewers: [{ viewerId: 'v', name: null, joinedAt: 1 }] })])+ const after = useWatchLinks.getState()+ expect(after.byNode.n1).toBe(before.byNode.n1)+ expect(after.byNode.n1[0]).toBe(before.byNode.n1[0])+ expect(after.byNode.n2).not.toBe(before.byNode.n2)+ // A push identical in content changes nothing at all.+ s.setLinks([link('a', 'n1'), link('c', 'n2', { viewers: [{ viewerId: 'v', name: null, joinedAt: 1 }] })])+ expect(useWatchLinks.getState()).toBe(after)+ })++ it('counts unread viewer messages, not the sharer\'s own', () => {+ const s = useWatchLinks.getState()+ s.addChat('a', msg('1'))+ s.addChat('a', msg('2', 'sharer'))+ expect(useWatchLinks.getState().unread.a).toBe(1)+ useWatchLinks.getState().markRead('a')+ expect(useWatchLinks.getState().unread.a).toBe(0)+ // Marking a read link read again is not a store change.+ const st = useWatchLinks.getState()+ useWatchLinks.getState().markRead('a')+ expect(useWatchLinks.getState()).toBe(st)+ })++ it('a dropped link takes its chat and unread count with it (H21)', () => {+ const s = useWatchLinks.getState()+ s.setLinks([link('a', 'n1'), link('b', 'n1')])+ s.addChat('a', msg('1'))+ s.addChat('b', msg('2'))+ s.setLinks([link('b', 'n1')])+ const st = useWatchLinks.getState()+ expect(st.chats.a).toBeUndefined()+ expect(st.unread.a).toBeUndefined()+ expect(st.chats.b).toHaveLength(1)+ expect(st.unread.b).toBe(1)+ })++ it('a history answer never drops a message that arrived while it was in flight', () => {+ const s = useWatchLinks.getState()+ s.addChat('a', msg('3', 'viewer', 30)) // pushed after the history snapshot was taken+ s.setChat('a', [msg('1', 'viewer', 10), msg('2', 'sharer', 20)])+ expect(useWatchLinks.getState().chats.a.map((m) => m.id)).toEqual(['1', '2', '3'])+ // The same message twice (history + push) is kept once.+ s.setChat('a', [msg('1', 'viewer', 10), msg('2', 'sharer', 20), msg('3', 'viewer', 30)])+ expect(useWatchLinks.getState().chats.a.map((m) => m.id)).toEqual(['1', '2', '3'])+ })++ it('a push that lands after a history answer already holding it is not a second message', () => {+ const s = useWatchLinks.getState()+ s.setChat('a', [msg('1', 'viewer', 10)])+ s.addChat('a', msg('1', 'viewer', 10))+ expect(useWatchLinks.getState().chats.a).toHaveLength(1)+ expect(useWatchLinks.getState().unread.a ?? 0).toBe(0)+ })++ it('keeps the last 200 messages', () => {+ const s = useWatchLinks.getState()+ for (let i = 0; i < 205; i++) s.addChat('a', msg(String(i), 'viewer', i))+ const chat = useWatchLinks.getState().chats.a+ expect(chat).toHaveLength(200)+ expect(chat[0].id).toBe('5')+ expect(chat[199].id).toBe('204')+ })++ it('the chip signature changes with what the chip shows, and is empty without a link', () => {+ const s = useWatchLinks.getState()+ expect(liveChipSig(useWatchLinks.getState(), 'n1')).toBe('')+ s.setLinks([link('a', 'n1')])+ const one = liveChipSig(useWatchLinks.getState(), 'n1')+ expect(one).not.toBe('')+ s.addChat('a', msg('1'))+ expect(liveChipSig(useWatchLinks.getState(), 'n1')).not.toBe(one)+ // Another node's change does not move this node's signature.+ const mine = liveChipSig(useWatchLinks.getState(), 'n1')+ s.setLinks([link('a', 'n1'), link('z', 'n9', { status: 'refused' })])+ expect(liveChipSig(useWatchLinks.getState(), 'n1')).toBe(mine)+ expect(EMPTY_LINKS).toHaveLength(0)+ })+})++describe('startWatchLinkSync', () => {+ function fakeApi(list: () => Promise<WatchLinkView[]>) {+ const h: {+ state: ((l: WatchLinkView[]) => void) | null+ chat: ((id: string, m: WatchChatMessage) => void) | null+ notice: ((n: WatchLinkNotice) => void) | null+ unsubscribed: number+ } = { state: null, chat: null, notice: null, unsubscribed: 0 }+ const api = {+ watchLink: {+ list,+ onState: (cb: (l: WatchLinkView[]) => void) => {+ h.state = cb+ return () => h.unsubscribed+++ },+ onChat: (cb: (id: string, m: WatchChatMessage) => void) => {+ h.chat = cb+ return () => h.unsubscribed+++ },+ onNotice: (cb: (n: WatchLinkNotice) => void) => {+ h.notice = cb+ return () => h.unsubscribed+++ }+ }+ }+ return { api: api as never, h }+ }++ it('hydrates from list() and follows state, chat and notice events', async () => {+ const notices: WatchLinkNotice[] = []+ const { api, h } = fakeApi(async () => [link('a', 'n1')])+ const stop = startWatchLinkSync(api, (n) => notices.push(n))+ await Promise.resolve()+ await Promise.resolve()+ expect(useWatchLinks.getState().links).toHaveLength(1)+ h.state!([])+ expect(useWatchLinks.getState().links).toHaveLength(0)+ h.chat!('a', msg('1'))+ expect(useWatchLinks.getState().chats.a).toHaveLength(1)+ h.notice!({ kind: 'not-persistent' })+ expect(notices).toEqual([{ kind: 'not-persistent' }])+ stop()+ expect(h.unsubscribed).toBe(3)+ })++ it('a list() answer that lands after a state push is ignored (H20)', async () => {+ let answer!: (l: WatchLinkView[]) => void+ const { api, h } = fakeApi(() => new Promise((r) => (answer = r)))+ const stop = startWatchLinkSync(api, () => {})+ // The newer state arrives first on its own channel: the link was stopped.+ h.state!([])+ // The slow list() then answers with the list from before the stop.+ answer([link('a', 'n1')])+ await Promise.resolve()+ await Promise.resolve()+ expect(useWatchLinks.getState().links).toHaveLength(0)+ stop()+ })++ it('nothing lands after stop, and a rejected list() is quiet', async () => {+ let answer!: (l: WatchLinkView[]) => void+ const { api } = fakeApi(() => new Promise((r) => (answer = r)))+ const stop = startWatchLinkSync(api, () => {})+ stop()+ answer([link('a', 'n1')])+ await Promise.resolve()+ await Promise.resolve()+ expect(useWatchLinks.getState().links).toHaveLength(0)+ const rejecting = fakeApi(() => Promise.reject(new Error('socket down')))+ const stop2 = startWatchLinkSync(rejecting.api, () => {})+ await Promise.resolve()+ await Promise.resolve()+ expect(useWatchLinks.getState().links).toHaveLength(0)+ stop2()+ })+})diff --git a/src/renderer/state/watchLinks.ts b/src/renderer/state/watchLinks.tsnew file mode 100644index 000000000..a9aa4b443--- /dev/null+++ b/src/renderer/state/watchLinks.ts@@ -0,0 +1,163 @@+// Live links, renderer side: a TRANSIENT mirror of the core registry's list (src/core/watch-link/+// service.ts), fed by `watchLink:state` / `watchLink:chat`, plus the owner's view of Commenter chat.+//+// Machine-local by construction: the list is per MACHINE (not per project), nothing here is ever+// serialized into a project, a canvas op or the board — link state is not canvas content, and a+// guard test (lib/live-link.guard.test.ts) keeps it out of every shared type. A reload rebuilds it+// from `list()`; chat history comes back from `chatHistory()` (core keeps it in memory only).+import { create } from 'zustand'+import type { NodeTerminalApi } from '@shared/types'+import type { WatchChatMessage, WatchLinkNotice, WatchLinkView } from '@shared/watch-link-types'+import { chipView } from '../lib/liveLink'++/** The shared empty list — a selector for a node with no link returns this exact array. Never mutate. */+export const EMPTY_LINKS: WatchLinkView[] = []+/** What core keeps per link (spec §Commenter chat), and so what the owner's thread can show. */+const CHAT_KEEP = 200++interface WatchLinksState {+ links: WatchLinkView[]+ /** The same links grouped by node, in list order. A node with no link has no key. */+ byNode: Record<string, WatchLinkView[]>+ chats: Record<string, WatchChatMessage[]>+ /** Viewer messages the owner has not seen in that link's popover yet. */+ unread: Record<string, number>+ setLinks(links: WatchLinkView[]): void+ addChat(linkId: string, msg: WatchChatMessage): void+ setChat(linkId: string, msgs: WatchChatMessage[]): void+ markRead(linkId: string): void+}++function sameLink(a: WatchLinkView, b: WatchLinkView): boolean {+ if (+ a.linkId !== b.linkId ||+ a.nodeId !== b.nodeId ||+ a.role !== b.role ||+ a.label !== b.label ||+ a.title !== b.title ||+ a.createdAt !== b.createdAt ||+ a.expiresAt !== b.expiresAt ||+ a.url !== b.url ||+ a.status !== b.status ||+ a.viewers.length !== b.viewers.length+ ) {+ return false+ }+ return a.viewers.every((v, i) => {+ const w = b.viewers[i]+ return v.viewerId === w.viewerId && v.name === w.name && v.joinedAt === w.joinedAt+ })+}++function sameItems<T>(a: readonly T[] | undefined, b: readonly T[]): boolean {+ return !!a && a.length === b.length && a.every((x, i) => x === b[i])+}++/** `rec` without the keys `keep` rejects — the same object when there is nothing to drop. */+function pruned<V>(rec: Record<string, V>, keep: (id: string) => boolean): Record<string, V> {+ if (Object.keys(rec).every(keep)) return rec+ return Object.fromEntries(Object.entries(rec).filter(([id]) => keep(id)))+}++export const useWatchLinks = create<WatchLinksState>((set) => ({+ links: [],+ byNode: {},+ chats: {},+ unread: {},++ // Every push is the FULL list, freshly deserialized. Objects whose content did not change keep+ // their identity (and so does each node's array), so a push about one link re-renders only the+ // surfaces of that link's node — every node header on the canvas subscribes to this store.+ setLinks: (incoming) =>+ set((s) => {+ const prev = new Map(s.links.map((l) => [l.linkId, l]))+ const next = incoming.map((l) => {+ const p = prev.get(l.linkId)+ return p && sameLink(p, l) ? p : l+ })+ const links = sameItems(s.links, next) ? s.links : next+ let byNode = s.byNode+ if (links !== s.links) {+ const grouped: Record<string, WatchLinkView[]> = {}+ for (const l of links) (grouped[l.nodeId] ??= []).push(l)+ byNode = {}+ for (const [nodeId, list] of Object.entries(grouped)) {+ byNode[nodeId] = sameItems(s.byNode[nodeId], list) ? s.byNode[nodeId] : list+ }+ }+ // A link that is gone takes its thread and its unread count with it (H21).+ const live = new Set(links.map((l) => l.linkId))+ const chats = pruned(s.chats, (id) => live.has(id))+ const unread = pruned(s.unread, (id) => live.has(id))+ if (links === s.links && chats === s.chats && unread === s.unread) return s+ return { links, byNode, chats, unread }+ }),++ addChat: (linkId, msg) =>+ set((s) => {+ const chat = s.chats[linkId] ?? []+ // The same message can reach us twice: pushed, and inside a history answer that raced it.+ if (chat.some((m) => m.id === msg.id)) return s+ return {+ chats: { ...s.chats, [linkId]: [...chat, msg].slice(-CHAT_KEEP) },+ unread: msg.from === 'viewer' ? { ...s.unread, [linkId]: (s.unread[linkId] ?? 0) + 1 } : s.unread+ }+ }),++ // A history answer and the chat pushes travel on different channels, so a message pushed after+ // core took the snapshot can land BEFORE the answer. Merge by id instead of replacing: a replace+ // would drop it. Ordered by core's timestamp; the sort is stable, so equal times keep their order.+ setChat: (linkId, msgs) =>+ set((s) => {+ const ids = new Set(msgs.map((m) => m.id))+ const extra = (s.chats[linkId] ?? []).filter((m) => !ids.has(m.id))+ const merged = [...msgs, ...extra].sort((a, b) => a.at - b.at).slice(-CHAT_KEEP)+ return { chats: { ...s.chats, [linkId]: merged } }+ }),++ markRead: (linkId) => set((s) => (s.unread[linkId] ? { unread: { ...s.unread, [linkId]: 0 } } : s))+}))++/**+ * A PRIMITIVE signature of everything one node's chip shows (tone, label, title, unread count) —+ * '' when the node has no link. The chip subscribes to this, never to a map: a string compares by+ * value, so another node's push leaves this node's header alone (the `noticeSigFor` discipline).+ */+export function liveChipSig(s: Pick<WatchLinksState, 'byNode' | 'unread'>, nodeId: string): string {+ const links = s.byNode[nodeId]+ if (!links || links.length === 0) return ''+ const v = chipView(links)+ const unread = links.reduce((n, l) => n + (s.unread[l.linkId] ?? 0), 0)+ return `${v.tone}\u0001${v.label}\u0001${v.title}\u0001${unread}`+}++/**+ * Follow core: subscribe to the pushes FIRST, then ask for the current list. The two travel on+ * different channels, so a `list()` answer can arrive after a newer state push — it is ignored once+ * any push has landed (H20), and after `stop()`. Notices go to `onNotice` (Canvas's info strip).+ */+export function startWatchLinkSync(+ api: Pick<NodeTerminalApi, 'watchLink'>,+ onNotice: (n: WatchLinkNotice) => void+): () => void {+ let pushed = false+ let stopped = false+ const offState = api.watchLink.onState((links) => {+ pushed = true+ useWatchLinks.getState().setLinks(links)+ })+ const offChat = api.watchLink.onChat((linkId, msg) => useWatchLinks.getState().addChat(linkId, msg))+ const offNotice = api.watchLink.onNotice(onNotice)+ void api.watchLink.list().then(+ (links) => {+ if (!pushed && !stopped) useWatchLinks.getState().setLinks(links)+ },+ () => {}+ )+ return () => {+ stopped = true+ offState()+ offChat()+ offNotice()+ }+}