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): Control and Unlimited in the dialog, typing on the chip, owner controls
reviewc80ed70926a4
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex d3c717be1..b416a4a14 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -246,7 +246,7 @@ import { UpgradeDialog } from '../components/UpgradeDialog'import { LiveLinkDialog } from '../components/LiveLinkDialog'import { requireProOr } from '../state/upgradeGate'import { startWatchLinkSync, useWatchLinks } from '../state/watchLinks'-import { noticeText } from '../lib/liveLink'+import { liveLinkNoticeEffect } from '../lib/liveLink'import {liveLinkCommands,liveLinkMenuItemsFor,@@ -3636,19 +3636,30 @@ export function Canvas() {}, [api, persist])// ── Live links (Task 17) ────────────────────────────────────────────────────────────────────- // A read-only, expiring browser view of ONE terminal. The store (state/watchLinks) mirrors this- // machine's core registry — `window.nodeTerminal`, never a relay session's api: links are made on- // the machine that runs the terminal. Started ONCE per Canvas mount; without it the store stays- // empty and no LIVE chip ever appears. `not-persistent` stays on screen (it is shown after every- // create while links cannot be saved); the rest fade like any info strip.+ // A browser view of ONE terminal. The store (state/watchLinks) mirrors this machine's core+ // registry — `window.nodeTerminal`, never a relay session's api: links are made on the machine+ // that runs the terminal. Started ONCE per Canvas mount; without it the store stays empty and no+ // LIVE chip ever appears. What a notice does is lib/liveLink's `liveLinkNoticeEffect` (tested+ // there): the info strip — `not-persistent` and `control-locked` stay on screen — and, for+ // `control-taken`, an OS notification under the agent-done consent, once per link per 5 s.+ const liveNotifyAtRef = useRef(new Map<string, number>())useEffect(() =>startWatchLinkSync(window.nodeTerminal, (n) => {- const text = noticeText(n)- if (text) setNotice({ kind: 'info', text, sticky: n.kind === 'not-persistent' })+ const fx = liveLinkNoticeEffect(n, useSettings.getState().settings, Date.now(), liveNotifyAtRef.current)+ if (fx.strip) setNotice({ kind: 'info', ...fx.strip })+ if (fx.os) void window.nodeTerminal.notify(fx.os)}),[])+ // The popover's "Open chat" (`nodeterm:live-chat`, `{ linkId }`). A STUB that opens nothing yet:+ // Task 8 replaces it with the Live chat drawer. It exists so the event is heard+ // (lib/nodeterm-events.test.ts pairs every dispatch with a listener).+ useEffect(() => {+ const on = (): void => {}+ window.addEventListener('nodeterm:live-chat', on)+ return () => window.removeEventListener('nodeterm:live-chat', on)+ }, [])const [liveLinkDialog, setLiveLinkDialog] = useState<LiveLinkTarget | null>(null)const closeLiveLinkDialog = useCallback(() => setLiveLinkDialog(null), [])/** The facts the ONE availability rule reads, for the node's OWN project (H4): a node of a relaydiff --git a/src/renderer/canvas/live-link-wiring.test.ts b/src/renderer/canvas/live-link-wiring.test.tsindex 97e41766d..167f9f4f8 100644--- a/src/renderer/canvas/live-link-wiring.test.ts+++ b/src/renderer/canvas/live-link-wiring.test.ts@@ -28,6 +28,16 @@ describe('Canvas live-link wiring', () => {expect(src).toMatch(/startWatchLinkSync\(window\.nodeTerminal,[\s\S]{0,400}?\n {4}\[\]\n {2}\)/)})+ it('notices: the strip and the OS notification come from ONE decision (liveLinkNoticeEffect)', () => {+ const sync = src.slice(src.indexOf('startWatchLinkSync(window.nodeTerminal,'))+ const body = sync.slice(0, 400)+ // The consent gate, the per-link cooldown and the copy are the lib's (behaviour-tested there):+ // Canvas hands it the LIVE settings and the clock, and does what it answers.+ expect(body).toContain('liveLinkNoticeEffect(n, useSettings.getState().settings, Date.now(), liveNotifyAtRef.current)')+ expect(body).toContain("if (fx.strip) setNotice({ kind: 'info', ...fx.strip })")+ expect(body).toContain('if (fx.os) void window.nodeTerminal.notify(fx.os)')+ })+it('the dialog is shown ONLY through openLiveLink (availability, then the Pro gate)', () => {// The only writers of the dialog state: the opener's `show`, and close.expect(count('setLiveLinkDialog(')).toBe(1) // closeLiveLinkDialog → setLiveLinkDialog(null)diff --git a/src/renderer/components/LiveLinkChip.test.tsx b/src/renderer/components/LiveLinkChip.test.tsxindex 2b8829856..c40399c7c 100644--- a/src/renderer/components/LiveLinkChip.test.tsx+++ b/src/renderer/components/LiveLinkChip.test.tsx@@ -11,9 +11,12 @@ import { useProjects } from '../state/projects'import { popDialog, pushDialog, resetDialogStack } from './dialog-stack'import {CHAT_NOT_SENT_MESSAGE,+ CONTROL_LOCKED_TEXT,KICK_FAILED_MESSAGE,KICK_NOT_DONE_MESSAGE,KICK_NOTE,+ PASSWORD_SEPARATE_NOTE,+ PASSWORD_SHOWN_ONCE,STOP_FAILED_MESSAGE} from '../lib/liveLink'@@ -57,7 +60,10 @@ const api = {at: 0,from: 'sharer'})),- chatHistory: vi.fn(async (_l: string): Promise<WatchChatMessage[]> => [])+ chatHistory: vi.fn(async (_l: string): Promise<WatchChatMessage[]> => []),+ setControl: vi.fn(async (_l: string, _on: boolean) => true),+ setPassword: vi.fn(async (_l: string, _pw: string) => true),+ allowControl: vi.fn(async (_l: string) => true)}const writeText = vi.fn()@@ -70,6 +76,9 @@ beforeEach(() => {vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })for (const f of Object.values(api)) f.mockClear()api.revoke.mockImplementation(async () => {})+ api.setControl.mockImplementation(async () => true)+ api.setPassword.mockImplementation(async () => true)+ api.allowControl.mockImplementation(async () => true)writeText.mockClear();(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { watchLink: api, clipboard: { writeText } }host = document.createElement('div')@@ -523,3 +532,189 @@ describe('LiveLinkPopover — Commenter chat', () => {expect(pop()!.querySelector('.live-pop__copy')).toBeNull()})})++// ---- Control (spec 2026-10-03 §2.5, §2.6) -------------------------------------------------------++const controller = (over: Partial<WatchLinkView> = {}): WatchLinkView =>+ link({ role: 'controller', control: { enabled: true, locked: false }, ...over })+const typist = (id: string, name: string, typing = true) => ({+ viewerId: id,+ name,+ joinedAt: 0,+ waiting: false,+ controlling: true,+ typing+})+const typeInto = (input: HTMLInputElement, v: string): void =>+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, v)+ input.dispatchEvent(new Event('input', { bubbles: true }))+ })++describe('LiveLinkChip — typing and unread', () => {+ it('says how many are typing, and its title names who, as claims', () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([+ controller({+ viewers: [+ typist('a', 'Mert'),+ typist('b', 'Ayşe'),+ { viewerId: 'c', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }+ ]+ })+ ])+ expect(chip()!.textContent).toBe('LIVE · 3 · 2 typing')+ expect(chip()!.title).toBe(+ '“Mert” and “Ayşe” are typing. This terminal is shared by a live link — 3 watching.'+ )+ })++ it('unread is a count summed over the node\'s links, not a dot', () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([link({ role: 'commenter' }), controller({ linkId: 'M' })])+ act(() => useWatchLinks.getState().addChat('L', msg('1')))+ expect(host.querySelector('.live-chip__unread')!.textContent).toBe('1')+ act(() => useWatchLinks.getState().addChat('M', msg('2')))+ act(() => useWatchLinks.getState().addChat('M', msg('3')))+ expect(host.querySelector('.live-chip__unread')!.textContent).toBe('3')+ expect(chip()!.getAttribute('aria-label')).toBe('LIVE, 3 unread chat messages')+ })+})++describe('LiveLinkPopover — a Control link', () => {+ it('names the role, the time left (none for Unlimited), and who can type', () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([+ controller({+ expiresAt: null,+ viewers: [+ typist('a', 'Mert'),+ typist('b', 'Cy', false),+ { viewerId: 'c', name: 'Dee', joinedAt: 0, waiting: false, controlling: false, typing: false }+ ]+ })+ ])+ click(chip()!)+ const p = pop()!+ expect(p.querySelector('.live-pop__role')!.textContent).toBe('Control')+ expect(p.querySelector('.live-pop__time')!.textContent).toBe('No end time')+ const rows = [...p.querySelectorAll('.live-pop__viewers li')]+ expect(rows[0].textContent).toContain('can type')+ expect(rows[1].textContent).toContain('can type')+ expect(rows[2].textContent).not.toContain('can type')+ // The typing dot: only on the one typing now.+ expect(rows.map((r) => r.querySelector('.live-pop__typing') !== null)).toEqual([true, false, false])+ // The chat is a Commenter link's, and a Control link's too.+ expect(p.querySelector('.live-pop__chat')).not.toBeNull()+ })++ it('the Typing switch turns typing off and on through setControl', async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ const sw = pop()!.querySelector<HTMLButtonElement>('[role="switch"]')!+ expect(sw.getAttribute('aria-checked')).toBe('true')+ click(sw)+ await flush()+ expect(api.setControl).toHaveBeenCalledWith('L', false)+ setLinks([controller({ control: { enabled: false, locked: false } })])+ const off = pop()!.querySelector<HTMLButtonElement>('[role="switch"]')!+ expect(off.getAttribute('aria-checked')).toBe('false')+ click(off)+ await flush()+ expect(api.setControl).toHaveBeenLastCalledWith('L', true)+ })++ it('a change that did not take says so', async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ api.setControl.mockImplementationOnce(async () => false)+ click(pop()!.querySelector('[role="switch"]')!)+ await flush()+ expect(pop()!.querySelector('[role="alert"]')!.textContent).toMatch(/try again/)+ })++ it('Allow control again appears only while locked, and calls allowControl', async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ expect(pop()!.textContent).not.toContain(CONTROL_LOCKED_TEXT)+ expect(button('Allow control again')).toBeUndefined()+ setLinks([controller({ control: { enabled: true, locked: true } })])+ expect(pop()!.textContent).toContain(CONTROL_LOCKED_TEXT)+ click(button('Allow control again'))+ await flush()+ expect(api.allowControl).toHaveBeenCalledWith('L')+ })++ it('Change password validates, calls setPassword, and shows the new password once', async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ click(button('Change password…'))+ const input = pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!+ expect(input.getAttribute('autocomplete')).toBe('off')+ expect(input.maxLength).toBe(128)+ expect(button('Save').disabled).toBe(true)+ typeInto(input, 'short')+ expect(button('Save').disabled).toBe(true)+ expect(pop()!.querySelector('.live-pop__invalid')!.textContent).toBe('Use at least 8 characters.')+ click(button('Generate'))+ const generated = input.value+ expect(generated).toMatch(/^[0-9abcdefghjkmnpqrstvwxyz]{16}$/)+ click(button('Save'))+ await flush()+ expect(api.setPassword).toHaveBeenCalledWith('L', generated)+ // Shown once, read-only, with Copy and the once-only wording.+ const shown = pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!+ expect(shown.readOnly).toBe(true)+ expect(shown.value).toBe(generated)+ expect(pop()!.textContent).toContain(PASSWORD_SHOWN_ONCE)+ expect(pop()!.textContent).toContain(PASSWORD_SEPARATE_NOTE)+ click(button('Copy password'))+ expect(writeText).toHaveBeenCalledWith(generated)+ // Done hides it; nothing in the popover still holds it.+ click(button('Done'))+ expect([...document.querySelectorAll('input')].map((i) => i.value)).not.toContain(generated)+ })++ it('a password core refused is not shown as set', async () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ click(button('Change password…'))+ typeInto(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!, 'longenough1')+ api.setPassword.mockImplementationOnce(async () => false)+ click(button('Save'))+ await flush()+ expect(pop()!.textContent).not.toContain(PASSWORD_SHOWN_ONCE)+ expect(pop()!.querySelector('[role="alert"]')!.textContent).toMatch(/wasn't changed/)+ // The draft is kept to try again.+ expect(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!.value).toBe('longenough1')+ })++ it('Open chat dispatches nodeterm:live-chat with the link id', () => {+ const heard = vi.fn()+ const on = (e: Event): void => heard((e as CustomEvent).detail)+ window.addEventListener('nodeterm:live-chat', on)+ try {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([controller()])+ click(chip()!)+ click(button('Open chat'))+ expect(heard).toHaveBeenCalledWith({ linkId: 'L' })+ } finally {+ window.removeEventListener('nodeterm:live-chat', on)+ }+ })++ it('a viewer link has no Open chat and no control section', () => {+ render(<LiveLinkChip nodeId="n1" source="local" />)+ setLinks([link()])+ click(chip()!)+ expect(button('Open chat')).toBeUndefined()+ expect(pop()!.querySelector('[role="switch"]')).toBeNull()+ expect(button('Change password…')).toBeUndefined()+ })+})diff --git a/src/renderer/components/LiveLinkChip.tsx b/src/renderer/components/LiveLinkChip.tsxindex 2ecfcd43e..db50851b4 100644--- a/src/renderer/components/LiveLinkChip.tsx+++ b/src/renderer/components/LiveLinkChip.tsx@@ -92,7 +92,13 @@ export const LiveLinkChip = memo(function LiveLinkChip({{/* The broadcast dot is the LIVE state's (spec: `● LIVE`); offline and refused carry none. */}{view.tone === 'live' && <span className="live-chip__dot" aria-hidden="true" />}{view.label}- {unread > 0 && <span className="live-chip__unread" aria-hidden="true" />}+ {/* A COUNT, summed over the node's links (a dot said "something", never how much). The+ button's aria-label carries it in words. */}+ {unread > 0 && (+ <span className="live-chip__unread" aria-hidden="true">+ {unread > 99 ? '99+' : unread}+ </span>+ )}</button>{anchor && <LiveLinkPopover nodeId={nodeId} anchor={anchor} onClose={close} />}</>diff --git a/src/renderer/components/LiveLinkDialog.test.tsx b/src/renderer/components/LiveLinkDialog.test.tsxindex 6856b8341..9ef8b13ee 100644--- a/src/renderer/components/LiveLinkDialog.test.tsx+++ b/src/renderer/components/LiveLinkDialog.test.tsx@@ -3,9 +3,19 @@ import { act } from 'react'import { createRoot, type Root } from 'react-dom/client'import { renderToStaticMarkup } from 'react-dom/server'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { CreateWatchLinkRequest, CreateWatchLinkResult } from '@shared/watch-link-types'+import type { ControlSupport, CreateWatchLinkRequest, CreateWatchLinkResult } from '@shared/watch-link-types'import { LiveLinkDialog, LiveLinkDialogBody } from './LiveLinkDialog'-import { formatClock, LIVE_LINK_WARNING, SAVE_FIRST_MESSAGE, STOP_FAILED_MESSAGE } from '../lib/liveLink'+import {+ CONTROL_UNSUPPORTED_REASON,+ CONTROL_WARNING,+ formatClock,+ LIVE_LINK_WARNING,+ PASSWORD_SEPARATE_NOTE,+ PASSWORD_SHOWN_ONCE,+ SAVE_FIRST_MESSAGE,+ STOP_FAILED_MESSAGE,+ UNLIMITED_NOTE+} from '../lib/liveLink'import { resetDialogStack } from './dialog-stack';(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true@@ -15,7 +25,7 @@ const body = (state: Parameters<typeof LiveLinkDialogBody>[0]['state'], extra: PrenderToStaticMarkup(<LiveLinkDialogBody title="build" state={state} onChange={noop} onSubmit={noop} onClose={noop} onStop={noop} {...extra} />)-const FORM = { phase: 'form', role: 'viewer', ttl: 3600, label: 'Ada', busy: false, error: null } as const+const FORM = { phase: 'form', role: 'viewer', ttl: 3600, label: 'Ada', password: '', busy: false, error: null } as constdescribe('LiveLinkDialogBody', () => {it('shows the role and expiry choices with the defaults, and the warning always', () => {@@ -23,7 +33,12 @@ describe('LiveLinkDialogBody', () => {expect(html).toContain('Share a live link to build')expect(html).toContain('Can watch')expect(html).toContain('Can watch and chat')- for (const t of ['15 min', '1 hour', '8 hours', '24 hours']) expect(html).toContain(t)+ for (const t of ['15 min', '1 hour', '8 hours', '24 hours', 'Unlimited']) expect(html).toContain(t)+ // Spec §2.7: Viewer / Commenter / Control.+ for (const r of ['Viewer', 'Commenter', 'Control']) expect(html).toContain(r)+ // Neither Control's password field nor its warning until Control is picked.+ expect(html).not.toContain('live-dialog__password')+ expect(html).not.toContain(CONTROL_WARNING)expect(html).toContain(LIVE_LINK_WARNING.replace(/'/g, '''))expect(html).toContain('Create live link')})@@ -95,6 +110,7 @@ const created = (url = 'https://nodeterm.dev/s/abc#1.k'): CreateWatchLinkResultlet api: {create: ReturnType<typeof vi.fn<(r: CreateWatchLinkRequest) => Promise<CreateWatchLinkResult>>>revoke: ReturnType<typeof vi.fn<(id: string) => Promise<void>>>+ controlSupport: ReturnType<typeof vi.fn<(nodeId: string) => Promise<ControlSupport>>>}/** What the local core's `tmuxStatus` reports (R63); `undefined` = the read rejects. */let persistence: { enabled: boolean; backend: string | null } | undefined@@ -106,7 +122,11 @@ let host: HTMLDivElementlet root: RootbeforeEach(() => {resetDialogStack()- api = { create: vi.fn(async () => created()), revoke: vi.fn(async () => {}) }+ api = {+ create: vi.fn(async () => created()),+ revoke: vi.fn(async () => {}),+ controlSupport: vi.fn(async () => 'ok' as const)+ }persistence = { enabled: true, backend: 'tmux' };(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {watchLink: api,@@ -316,3 +336,244 @@ describe('LiveLinkDialog', () => {expect(window.nodeTerminal.clipboard.writeText).toHaveBeenCalledWith('https://nodeterm.dev/s/abc#1.k')})})++// ---- Control and Unlimited (spec 2026-10-03 §2.7, §3) -------------------------------------------++const radio = (text: string): HTMLInputElement =>+ [...document.querySelectorAll<HTMLLabelElement>('.live-dialog__group label')]+ .find((l) => l.textContent?.includes(text))!+ .querySelector('input')!+const pick = (text: string): void => click(radio(text))+const pwInput = (): HTMLInputElement | null => document.querySelector<HTMLInputElement>('.live-dialog__password input')+const typeInto = (input: HTMLInputElement, v: string): void =>+ act(() => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, v)+ input.dispatchEvent(new Event('input', { bubbles: true }))+ })+const warning = (): string | null => document.querySelector('.live-dialog__warning')?.textContent ?? null+const createWith = (over: Partial<CreateWatchLinkRequest> = {}): CreateWatchLinkResult => ({+ ok: true,+ link: {+ ...(created() as { ok: true; link: import('@shared/watch-link-types').WatchLinkView }).link,+ role: over.role ?? 'viewer',+ expiresAt: over.ttlSeconds === 0 ? null : Date.now() + 3_600_000,+ control: over.role === 'controller' ? { enabled: true, locked: false } : null+ }+})++describe('LiveLinkDialog — Control', () => {+ it('Control shows the password field with Generate, and its own warning in place of the watch warning', async () => {+ mount()+ await flush()+ expect(pwInput()).toBeNull()+ expect(warning()).toBe(LIVE_LINK_WARNING)+ pick('Control')+ const input = pwInput()!+ expect(input.type).toBe('text')+ expect(input.getAttribute('autocomplete')).toBe('off')+ expect(input.getAttribute('spellcheck')).toBe('false')+ expect(input.maxLength).toBe(128)+ expect(warning()).toBe(CONTROL_WARNING)+ expect(btn('Generate')).toBeTruthy()+ // Back to Viewer: the watch warning again, no password field.+ pick('Viewer')+ expect(pwInput()).toBeNull()+ expect(warning()).toBe(LIVE_LINK_WARNING)+ })++ it('Generate fills 16 symbols from crypto.getRandomValues', async () => {+ const spy = vi.spyOn(crypto, 'getRandomValues')+ mount()+ await flush()+ setLabel('Ada')+ pick('Control')+ expect(btn('Create live link').disabled).toBe(true)+ click(btn('Generate'))+ expect(spy).toHaveBeenCalled()+ expect(pwInput()!.value).toMatch(/^[0-9abcdefghjkmnpqrstvwxyz]{16}$/)+ expect(btn('Create live link').disabled).toBe(false)+ spy.mockRestore()+ })++ it('Create stays disabled until the password is acceptable, and says why', async () => {+ mount()+ await flush()+ setLabel('Ada')+ pick('Control')+ const create = (): HTMLButtonElement => btn('Create live link')+ const problem = (): string | null => document.querySelector('.live-dialog__invalid')?.textContent ?? null+ // Empty: disabled, nothing nagging yet.+ expect(create().disabled).toBe(true)+ expect(problem()).toBeNull()+ typeInto(pwInput()!, 'short')+ expect(create().disabled).toBe(true)+ expect(problem()).toBe('Use at least 8 characters.')+ typeInto(pwInput()!, 'long\tenough')+ expect(create().disabled).toBe(true)+ expect(problem()).toBe('Line breaks and control characters are not allowed.')+ typeInto(pwInput()!, 'longenough1')+ expect(create().disabled).toBe(false)+ expect(problem()).toBeNull()+ })++ it('sends the password only for Control', async () => {+ api.create.mockImplementation(async (r) => createWith(r))+ mount()+ await flush()+ setLabel('Ada')+ pick('Control')+ typeInto(pwInput()!, 'longenough1')+ // A password typed, then the owner switched to Commenter: nothing of it leaves the dialog.+ pick('Commenter')+ click(btn('Create live link'))+ await flush()+ expect(api.create).toHaveBeenCalledTimes(1)+ expect(api.create.mock.calls[0][0]).toEqual({ nodeId: 'n1', role: 'commenter', ttlSeconds: 3600, label: 'Ada', title: 'build' })+ expect('password' in api.create.mock.calls[0][0]).toBe(false)++ act(() => root.unmount())+ root = createRoot(host)+ api.create.mockClear()+ mount()+ await flush()+ setLabel('Ada')+ pick('Control')+ typeInto(pwInput()!, 'longenough1')+ click(btn('Create live link'))+ await flush()+ expect(api.create).toHaveBeenCalledWith({+ nodeId: 'n1',+ role: 'controller',+ ttlSeconds: 3600,+ label: 'Ada',+ title: 'build',+ password: 'longenough1'+ })+ })++ it("Control is disabled, with the reason, when the terminal can't take input — asked once, for this node", async () => {+ api.controlSupport.mockResolvedValue('unsupported')+ mount()+ await flush()+ expect(api.controlSupport).toHaveBeenCalledTimes(1)+ expect(api.controlSupport).toHaveBeenCalledWith('n1')+ expect(radio('Control').disabled).toBe(true)+ expect(document.querySelector('.live-dialog__reason')!.textContent).toBe(CONTROL_UNSUPPORTED_REASON)+ expect(radio('Viewer').disabled).toBe(false)+ })++ it("'unknown' (and a rejected or missing answer) keeps Control offered: the create decides", async () => {+ for (const answer of ['unknown', 'reject', 'missing'] as const) {+ act(() => root.unmount())+ root = createRoot(host)+ if (answer === 'unknown') api.controlSupport.mockResolvedValue('unknown')+ else if (answer === 'reject') api.controlSupport.mockRejectedValue(new Error('socket'))+ else (api as { controlSupport?: unknown }).controlSupport = undefined+ mount()+ await flush()+ expect(radio('Control').disabled, answer).toBe(false)+ expect(document.querySelector('.live-dialog__reason'), answer).toBeNull()+ }+ })++ it('an answer that lands after Control was picked moves the choice off it', async () => {+ let answer!: (s: ControlSupport) => void+ api.controlSupport.mockImplementation(() => new Promise((r) => (answer = r)))+ mount()+ await flush()+ pick('Control')+ typeInto(pwInput()!, 'longenough1')+ await act(async () => answer('unsupported'))+ expect(radio('Control').checked).toBe(false)+ expect(radio('Control').disabled).toBe(true)+ expect(pwInput()).toBeNull()+ })++ it('the done step shows the password once, with Copy password and the separate-send note', async () => {+ api.create.mockImplementation(async (r) => createWith(r))+ mount()+ await flush()+ setLabel('Ada')+ pick('Control')+ typeInto(pwInput()!, 'longenough1')+ pick('Unlimited')+ click(btn('Create live link'))+ await flush()+ const field = document.querySelector<HTMLInputElement>('.live-dialog__password input')!+ expect(field.readOnly).toBe(true)+ expect(field.value).toBe('longenough1')+ const text = document.querySelector('.live-dialog')!.textContent!+ expect(text).toContain(PASSWORD_SHOWN_ONCE)+ expect(text).toContain(PASSWORD_SEPARATE_NOTE)+ expect(text).toContain('Anyone with this link and the password can type until you stop it.')+ click(btn('Copy password'))+ expect(window.nodeTerminal.clipboard.writeText).toHaveBeenCalledWith('longenough1')+ expect(btn('Copied!')).toBeTruthy()+ // The link keeps its own Copy.+ expect(document.querySelector<HTMLInputElement>('.live-dialog__url input')!.value).toBe('https://nodeterm.dev/s/abc#1.k')+ })++ it('closing drops the password: nothing on screen keeps it, nothing stored it', async () => {+ api.create.mockImplementation(async (r) => createWith(r))+ const { onClose } = mount()+ await flush()+ setLabel('Ada')+ pick('Control')+ typeInto(pwInput()!, 'longenough1')+ click(btn('Create live link'))+ await flush()+ expect(pwInput()!.value).toBe('longenough1')+ click(btn('Done'))+ expect(onClose).toHaveBeenCalledTimes(1)+ const values = [...document.querySelectorAll('input')].map((i) => i.value)+ expect(values).not.toContain('longenough1')+ expect(document.body.textContent).not.toContain('longenough1')+ for (const store of [localStorage, sessionStorage]) {+ for (let i = 0; i < store.length; i++) expect(store.getItem(store.key(i)!)).not.toContain('longenough1')+ }+ })++ it('a form closed before creating drops the typed password too', async () => {+ const { onClose } = mount()+ await flush()+ pick('Control')+ typeInto(pwInput()!, 'longenough1')+ escape()+ expect(onClose).toHaveBeenCalledTimes(1)+ expect([...document.querySelectorAll('input')].map((i) => i.value)).not.toContain('longenough1')+ })+})++describe('LiveLinkDialog — Unlimited', () => {+ it('sends ttlSeconds 0 and says the link works until it is stopped', async () => {+ mount()+ await flush()+ setLabel('Ada')+ const notes = (): string[] => [...document.querySelectorAll('.live-dialog__note')].map((e) => e.textContent ?? '')+ expect(notes()).not.toContain(UNLIMITED_NOTE)+ pick('Unlimited')+ expect(notes()).toContain(UNLIMITED_NOTE)+ click(btn('Create live link'))+ await flush()+ expect(api.create).toHaveBeenCalledWith(expect.objectContaining({ ttlSeconds: 0 }))+ })++ it('an older server refusing Unlimited says to pick an end time', async () => {+ api.create.mockResolvedValue({ ok: false, error: 'ttl-unsupported' })+ mount()+ await flush()+ setLabel('Ada')+ pick('Unlimited')+ click(btn('Create live link'))+ await flush()+ expect(document.querySelector('.live-dialog__error')!.textContent).toBe(+ 'Unlimited links need a newer server. Pick an end time.'+ )+ })++ it('the done step of an Unlimited watch link says until it is stopped', () => {+ const html = body({ phase: 'done', url: 'https://nodeterm.dev/s/x#1.y', linkId: 'x', expiresAt: null })+ expect(html).toContain('Anyone with this link can watch until you stop it.')+ expect(html).not.toContain('live-dialog__password')+ })+})diff --git a/src/renderer/components/LiveLinkDialog.tsx b/src/renderer/components/LiveLinkDialog.tsxindex d6c63713d..fc92e8e21 100644--- a/src/renderer/components/LiveLinkDialog.tsx+++ b/src/renderer/components/LiveLinkDialog.tsx@@ -6,25 +6,75 @@//// The URL carries the link's secret. It is shown HERE, once created, and in the chip's popover —// never in a notice, a log line or the Settings list (which only copies it).+//+// A Control link's PASSWORD is plaintext only in this component's state: typed or generated in the+// form, shown once in the done step, and dropped on every close (`dismiss`) and with the component.+// It is never written to localStorage, settings, a log or a notice; core keeps only its hash.import { useCallback, useEffect, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { useDialogStack } from './dialog-stack'import {capUnits,+ CONTROL_UNSUPPORTED_REASON,+ CONTROL_WARNING,createErrorMessage,DEFAULT_TTL,formatUntil,LIVE_LINK_WARNING,+ PASSWORD_SEPARATE_NOTE,+ PASSWORD_SHOWN_ONCE,+ passwordProblemText,ROLE_LABEL,+ ROLE_NAME,SAVE_FIRST_MESSAGE,TTL_OPTIONS,+ UNLIMITED_NOTE,watchableOnlyWhileOpen,watchWhileOpenNote,type LiveLinkSurface} from '../lib/liveLink'import { stopLiveLinks } from '../lib/liveLinkEntry'import { loadIdentity } from '../state/presence'-import { LABEL_MAX, stripBidiControls, type WatchLinkRole, type WatchLinkTtl } from '@shared/watch-link-types'+import {+ LABEL_MAX,+ stripBidiControls,+ UNLIMITED_TTL,+ type CreateWatchLinkRequest,+ type WatchLinkRole,+ type WatchLinkTtl+} from '@shared/watch-link-types'+import { PASSWORD_MAX } from '@shared/watch-link/protocol'+import { generateControlPassword } from '@shared/watch-link-password'++/** Generate: 16 symbols from the platform CSPRNG (spec §2.2). */+export function newControlPassword(): string {+ return generateControlPassword((n) => crypto.getRandomValues(new Uint8Array(n)))+}++/** The password field shared by the form and the done step (and, read-only, the popover's change). */+export function PasswordField(p: {+ value: string+ readOnly?: boolean+ disabled?: boolean+ onChange?: (v: string) => void+ label?: string+}): React.JSX.Element {+ return (+ <input+ className="confirm__input"+ type="text"+ autoComplete="off"+ spellCheck={false}+ maxLength={PASSWORD_MAX}+ aria-label={p.label ?? 'Password'}+ value={p.value}+ readOnly={p.readOnly}+ disabled={p.disabled}+ onFocus={p.readOnly ? (e) => e.currentTarget.select() : undefined}+ onChange={p.onChange ? (e) => p.onChange?.(e.target.value) : undefined}+ />+ )+}export type DialogState =| {@@ -32,6 +82,9 @@ export type DialogState =role: WatchLinkRolettl: WatchLinkTtllabel: string+ /** A Control link's password, as typed or generated. Kept while the owner switches roles (they+ * may switch back); sent only for Control. */+ password: string/** A prepare or a create is in flight: the dialog cannot be dismissed (H24) — a link created* behind a closed dialog would be broadcasting with a URL its owner never saw. */busy: boolean@@ -46,7 +99,10 @@ export type DialogState =linkId: string/** null: an Unlimited link. */expiresAt: number | null+ /** A Control link's password, shown this once (core keeps only its hash). Absent otherwise. */+ password?: stringcopied?: boolean+ passwordCopied?: booleanstopping?: booleanerror?: string | null}@@ -59,7 +115,11 @@ export function LiveLinkDialogBody(p: {onClose: () => voidonStop: (linkId: string) => voidonCopy?: (url: string) => void+ onCopyPassword?: (password: string) => voidonUpgrade?: () => void+ /** `watchLink.controlSupport` said this node's terminal cannot take typed input (a Zellij session):+ * Control is shown disabled, with its reason. Absent / false: offered (unknown is offered too). */+ controlUnsupported?: boolean/** R63: on a machine with no watcher client for this node, the link works only while the terminal* is open in this app — said before the owner creates it. Absent: nothing to say (or not known). */whileOpenNote?: string | null@@ -86,8 +146,22 @@ export function LiveLinkDialogBody(p: {{s.copied ? 'Copied!' : 'Copy'}</button></div>+ {s.password !== undefined && (+ <>+ <div className="live-dialog__url live-dialog__password">+ <PasswordField value={s.password} readOnly />+ <button className="confirm__btn" onClick={() => p.onCopyPassword?.(s.password ?? '')}>+ {s.passwordCopied ? 'Copied!' : 'Copy password'}+ </button>+ </div>+ <p className="live-dialog__note live-dialog__note--tight">{PASSWORD_SHOWN_ONCE}</p>+ <p className="live-dialog__note live-dialog__note--tight">{PASSWORD_SEPARATE_NOTE}</p>+ </>+ )}<p className="live-dialog__note">- Anyone with this link can watch until {formatUntil(s.expiresAt, p.now ?? Date.now())}.+ {s.password !== undefined+ ? `Anyone with this link and the password can type until ${formatUntil(s.expiresAt, p.now ?? Date.now())}.`+ : `Anyone with this link can watch until ${formatUntil(s.expiresAt, p.now ?? Date.now())}.`}</p>{s.error && (<p className="live-dialog__error" role="alert">@@ -105,18 +179,42 @@ export function LiveLinkDialogBody(p: {</div>)}+ const control = s.role === 'controller'+ const problem = control ? passwordProblemText(s.password) : nullreturn (<div className="confirm live-dialog" onClick={(e) => e.stopPropagation()}><p className="confirm__msg live-dialog__title">Share a live link to {title}</p><fieldset className="live-dialog__group" disabled={s.busy}><legend>Viewers</legend>- {(['viewer', 'commenter'] as const).map((r) => (- <label key={r}>- <input type="radio" name="live-role" checked={s.role === r} onChange={() => p.onChange({ ...s, role: r })} />{' '}- {ROLE_LABEL[r]}- </label>- ))}+ {(['viewer', 'commenter', 'controller'] as const).map((r) => {+ const off = r === 'controller' && !!p.controlUnsupported+ return (+ <label key={r} className={off ? 'live-dialog__off' : undefined} title={off ? CONTROL_UNSUPPORTED_REASON : undefined}>+ <input+ type="radio"+ name="live-role"+ checked={s.role === r}+ disabled={off}+ onChange={() => p.onChange({ ...s, role: r })}+ />{' '}+ {ROLE_NAME[r]} <span className="live-dialog__hint">· {ROLE_LABEL[r]}</span>+ </label>+ )+ })}+ {p.controlUnsupported && <p className="live-dialog__reason">{CONTROL_UNSUPPORTED_REASON}</p>}</fieldset>+ {control && (+ <div className="live-dialog__pw">+ Password+ <div className="live-dialog__url live-dialog__password">+ <PasswordField value={s.password} disabled={s.busy} onChange={(v) => p.onChange({ ...s, password: v })} />+ <button className="confirm__btn" disabled={s.busy} onClick={() => p.onChange({ ...s, password: newControlPassword() })}>+ Generate+ </button>+ </div>+ {s.password !== '' && problem && <p className="live-dialog__invalid">{problem}</p>}+ </div>+ )}<fieldset className="live-dialog__group" disabled={s.busy}><legend>Ends after</legend>{TTL_OPTIONS.map((o) => (@@ -126,6 +224,7 @@ export function LiveLinkDialogBody(p: {</label>))}</fieldset>+ {s.ttl === UNLIMITED_TTL && <p className="live-dialog__note live-dialog__note--tight">{UNLIMITED_NOTE}</p>}<label className="live-dialog__label">Shown to viewers as{/* Keyboard focus lands here when the dialog opens (D2/M3): keys stay inside the dialog@@ -139,7 +238,7 @@ export function LiveLinkDialogBody(p: {onChange={(e) => p.onChange({ ...s, label: e.target.value })}/></label>- <p className="live-dialog__warning">{LIVE_LINK_WARNING}</p>+ <p className="live-dialog__warning">{control ? CONTROL_WARNING : LIVE_LINK_WARNING}</p>{p.whileOpenNote && <p className="live-dialog__note">{p.whileOpenNote}</p>}{s.error && (<p className="live-dialog__error" role="alert">@@ -155,7 +254,11 @@ export function LiveLinkDialogBody(p: {<button className="confirm__btn" disabled={s.busy} onClick={p.onClose}>Cancel</button>- <button className="confirm__btn primary" disabled={s.busy || !s.label.trim()} onClick={p.onSubmit}>+ <button+ className="confirm__btn primary"+ disabled={s.busy || !s.label.trim() || (control && (problem !== null || !!p.controlUnsupported))}+ onClick={p.onSubmit}+ >{s.busy ? 'Creating…' : 'Create live link'}</button></div>@@ -194,6 +297,7 @@ export function LiveLinkDialog({role: 'viewer',ttl: DEFAULT_TTL,label: capUnits(loadIdentity()?.name ?? '', LABEL_MAX),+ password: '',busy: false,error: null}))@@ -221,6 +325,27 @@ export function LiveLinkDialog({live = false}}, [remoteNode, readPersistence])+ // Can this node's terminal take a Control link's input? Asked ONCE, on open. Only a definite+ // 'unsupported' (a Zellij session) disables Control; 'unknown', a rejection or an api without the+ // call keep it offered — the create decides, and says why if it refuses.+ const [controlUnsupported, setControlUnsupported] = useState(false)+ useEffect(() => {+ let live = true+ Promise.resolve()+ .then(() => window.nodeTerminal.watchLink.controlSupport(nodeId))+ .then(+ (answer) => {+ if (!live || answer !== 'unsupported') return+ setControlUnsupported(true)+ // Picked before the answer landed: move off it (and drop the password with it).+ setState((s) => (s.phase === 'form' && !s.busy && s.role === 'controller' ? { ...s, role: 'viewer', password: '' } : s))+ },+ () => {}+ )+ return () => {+ live = false+ }+ }, [nodeId])// D2/M3: focus lands in the dialog — the label on open, Copy once created — so keys stay inside// it (a bare-key canvas command could otherwise fire behind the overlay).const panelRef = useRef<HTMLDivElement>(null)@@ -229,10 +354,14 @@ export function LiveLinkDialog({}, [state.phase])const busy = state.phase === 'form' && state.busy- // Every dismissal goes through here: a create in flight cannot be walked away from (H24).+ // Every dismissal goes through here: a create in flight cannot be walked away from (H24). The+ // password goes with it, before the owner hands the dialog back — never left in state behind it.const dismiss = useCallback(() => {const s = stateRef.currentif (s.phase === 'form' && s.busy) return+ const dropped: DialogState = s.phase === 'form' ? { ...s, password: '' } : { ...s, password: undefined }+ stateRef.current = dropped+ setState(dropped)onClose()}, [onClose])@@ -259,16 +388,27 @@ export function LiveLinkDialog({refused = SAVE_FIRST_MESSAGE}if (refused) return fail(refused)+ const control = form.role === 'controller'+ const req: CreateWatchLinkRequest = {+ nodeId,+ role: form.role,+ ttlSeconds: form.ttl,+ label: form.label.trim(),+ title,+ // Only a Control link carries a password: a viewer or commenter request never holds one.+ ...(control ? { password: form.password } : {})+ }try {- const r = await window.nodeTerminal.watchLink.create({- nodeId,- role: form.role,- ttlSeconds: form.ttl,- label: form.label.trim(),- title- })- if (r.ok) setState({ phase: 'done', url: r.link.url, linkId: r.link.linkId, expiresAt: r.link.expiresAt })- else fail(createErrorMessage(r.error, surface), r.error === 'not-entitled')+ const r = await window.nodeTerminal.watchLink.create(req)+ if (r.ok) {+ setState({+ phase: 'done',+ url: r.link.url,+ linkId: r.link.linkId,+ expiresAt: r.link.expiresAt,+ ...(control ? { password: form.password } : {})+ })+ } else fail(createErrorMessage(r.error, surface), r.error === 'not-entitled')} catch {// Desktop IPC and the ws-bridge both answer instead of rejecting; this is the belt.fail(createErrorMessage('network', surface))@@ -292,6 +432,17 @@ export function LiveLinkDialog({clearTimeout(copiedTimer.current)copiedTimer.current = setTimeout(() => setState((s) => (s.phase === 'done' ? { ...s, copied: false } : s)), 1500)}+ const passwordCopiedTimer = useRef<ReturnType<typeof setTimeout>>()+ useEffect(() => () => clearTimeout(passwordCopiedTimer.current), [])+ const copyPassword = (password: string): void => {+ window.nodeTerminal.clipboard.writeText(password)+ setState((s) => (s.phase === 'done' ? { ...s, passwordCopied: true } : s))+ clearTimeout(passwordCopiedTimer.current)+ passwordCopiedTimer.current = setTimeout(+ () => setState((s) => (s.phase === 'done' ? { ...s, passwordCopied: false } : s)),+ 1500+ )+ }return createPortal(<div className="confirm-overlay" ref={panelRef} onClick={dismiss}>@@ -306,7 +457,9 @@ export function LiveLinkDialog({onClose={dismiss}onStop={(id) => void stop(id)}onCopy={copy}+ onCopyPassword={copyPassword}onUpgrade={onUpgrade}+ controlUnsupported={controlUnsupported}/></div>,document.bodydiff --git a/src/renderer/components/LiveLinkPopover.tsx b/src/renderer/components/LiveLinkPopover.tsxindex 06c68902d..0fc68c495 100644--- a/src/renderer/components/LiveLinkPopover.tsx+++ b/src/renderer/components/LiveLinkPopover.tsx@@ -1,20 +1,30 @@import { memo, useEffect, useRef, useState } from 'react'import { createPortal } from 'react-dom'import type { NodeTerminalApi } from '@shared/types'-import type { WatchLinkView } from '@shared/watch-link-types'+import type { WatchLinkControlView, WatchLinkRole, WatchLinkView } from '@shared/watch-link-types'import { stripBidiControls } from '@shared/watch-link-types'import { CHAT_TEXT_MAX, type WatchChatMessage } from '@shared/watch-link/protocol'import { useDialogStack } from './dialog-stack'+import { newControlPassword, PasswordField } from './LiveLinkDialog'import { useMenuFlip } from '../ui/useMenuFlip'+import { Switch } from '../ui/Switch'import {CHAT_NOT_SENT_MESSAGE,commentFromChat,+ CONTROL_CHANGE_FAILED_MESSAGE,+ CONTROL_LOCKED_TEXT,formatClock,formatRemaining,KICK_FAILED_MESSAGE,KICK_NOT_DONE_MESSAGE,KICK_NOTE,+ PASSWORD_CHANGE_FAILED_MESSAGE,+ PASSWORD_CHANGE_NOTE,+ PASSWORD_SEPARATE_NOTE,+ PASSWORD_SHOWN_ONCE,+ passwordProblemText,ROLE_LABEL,+ ROLE_NAME,statusLine,STOP_FAILED_MESSAGE,viewerName,@@ -88,11 +98,17 @@ function commentTarget(nodeId: string): { projectId: string; api: NodeTerminalApreturn null}+/** The roles whose viewers can chat: a Control link is a Commenter link plus typing (spec §2.1). */+export function hasChat(role: WatchLinkRole): boolean {+ return role === 'commenter' || role === 'controller'+}+/**- * Per-link controls for one node: copy, stop, the viewer list with Kick, and — for a Commenter- * link — the thread with a reply box and "Copy to card comments" (the owner's explicit act; nothing- * a viewer writes is ever stored automatically, spec D2). Every string someone else wrote (label,- * title, viewer names and chat) is rendered as React TEXT, bidi-stripped — never as HTML.+ * Per-link controls for one node: copy, stop, the viewer list with Kick, and — for a Commenter or+ * Control link — the thread with a reply box and "Copy to card comments" (the owner's explicit act;+ * nothing a viewer writes is ever stored automatically, spec D2) plus Open chat. A Control link adds+ * its owner controls (`ControlSection`). Every string someone else wrote (label, title, viewer names+ * and chat) is rendered as React TEXT, bidi-stripped — never as HTML.** It is a modal in the dialog stack, so Escape (and the board's keys) belong to it while it is* up — the card modal it can open over stands aside (`isTopDialog`).@@ -160,7 +176,7 @@ export function LiveLinkPopover({tabIndex={-1}>{links.map((l) => (- <LinkBlock key={l.linkId} link={l} now={now} nodeId={nodeId} />+ <LinkBlock key={l.linkId} link={l} now={now} nodeId={nodeId} onClose={onClose} />))}</div></>,@@ -171,11 +187,13 @@ export function LiveLinkPopover({const LinkBlock = memo(function LinkBlock({link,now,- nodeId+ nodeId,+ onClose}: {link: WatchLinkViewnow: numbernodeId: string+ onClose: () => void}): React.JSX.Element {const api = window.nodeTerminal.watchLinkconst [copied, setCopied] = useState(false)@@ -190,7 +208,10 @@ const LinkBlock = memo(function LinkBlock({return (<section className="live-pop__link" data-link-id={link.linkId}><header className="live-pop__head">- <span className="live-pop__role">{ROLE_LABEL[link.role]}</span>+ <span>+ <span className="live-pop__role">{ROLE_NAME[link.role]}</span>{' '}+ <span className="live-pop__muted">{ROLE_LABEL[link.role]}</span>+ </span><span className="live-pop__time">{formatRemaining(link.expiresAt, now)}</span></header><p className="live-pop__muted live-pop__label">@@ -212,6 +233,19 @@ const LinkBlock = memo(function LinkBlock({>{copied ? 'Copied!' : 'Copy link'}</button>+ {hasChat(link.role) && (+ <button+ type="button"+ className="confirm__btn live-pop__btn"+ onClick={() => {+ // The Live chat drawer (Task 8) listens; the popover gives way to it.+ window.dispatchEvent(new CustomEvent('nodeterm:live-chat', { detail: { linkId: link.linkId } }))+ onClose()+ }}+ >+ Open chat+ </button>+ )}<buttontype="button"className="confirm__btn danger live-pop__btn"@@ -230,6 +264,7 @@ const LinkBlock = memo(function LinkBlock({{error}</p>)}+ {link.control && <ControlSection linkId={link.linkId} control={link.control} />}<div className="live-pop__viewers">{link.viewers.length === 0 ? (<p className="live-pop__muted">Nobody is watching right now.</p>@@ -238,9 +273,11 @@ const LinkBlock = memo(function LinkBlock({<ul>{link.viewers.map((v, i) => (<li key={v.viewerId}>+ {v.typing && <span className="live-pop__typing" role="img" aria-label="Typing now" title="Typing now" />}<span className="live-pop__who">{viewerName(v, i)}</span><span className="live-pop__muted">since {formatClock(v.joinedAt)}+ {v.controlling ? ' · can type' : ''}{v.waiting ? ' · waiting for the terminal' : ''}</span><button@@ -266,12 +303,160 @@ const LinkBlock = memo(function LinkBlock({</>)}</div>- {link.role === 'commenter' && <ChatThread linkId={link.linkId} nodeId={nodeId} />}+ {hasChat(link.role) && <ChatThread linkId={link.linkId} nodeId={nodeId} />}</section>)})-function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string }): React.JSX.Element {+/**+ * A Control link's owner controls (spec §2.6): the Typing switch, Change password (a new one is shown+ * ONCE, then only its hash exists — core keeps no plaintext), and Allow control again while the link+ * is locked by wrong passwords. Exported for the Live chat drawer.+ *+ * The switch shows core's state (the next push), never an optimistic one: a change core refused must+ * not look applied. A typed or new password lives only in this component's state and goes with it.+ */+export function ControlSection({ linkId, control }: { linkId: string; control: WatchLinkControlView }): React.JSX.Element {+ const api = window.nodeTerminal.watchLink+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [editing, setEditing] = useState(false)+ const [draft, setDraft] = useState('')+ const [shown, setShown] = useState<string | null>(null)+ const [copied, setCopied] = useState(false)+ useEffect(() => {+ if (!copied) return+ const t = setTimeout(() => setCopied(false), 1500)+ return () => clearTimeout(t)+ }, [copied])+ const run = (call: () => Promise<boolean>, failed: string, done?: () => void): void => {+ setBusy(true)+ setError(null)+ void Promise.resolve()+ .then(call)+ .then(+ (ok) => (ok ? done?.() : setError(failed)),+ () => setError(failed)+ )+ .finally(() => setBusy(false))+ }+ const problem = passwordProblemText(draft)+ return (+ <div className="live-pop__control">+ {control.locked && (+ <div className="live-pop__locked">+ <p className="live-pop__status" role="status">+ {CONTROL_LOCKED_TEXT}+ </p>+ <button+ type="button"+ className="confirm__btn live-pop__btn"+ disabled={busy}+ onClick={() => run(() => api.allowControl(linkId), CONTROL_CHANGE_FAILED_MESSAGE)}+ >+ Allow control again+ </button>+ </div>+ )}+ <div className="live-pop__toggle">+ <span>+ <span className="live-pop__who">Typing</span>{' '}+ <span className="live-pop__muted">+ {control.enabled ? 'Anyone with the password can type.' : 'Off: viewers can watch and chat.'}+ </span>+ </span>+ <Switch+ checked={control.enabled}+ ariaLabel="Typing"+ disabled={busy}+ onChange={(on) => run(() => api.setControl(linkId, on), CONTROL_CHANGE_FAILED_MESSAGE)}+ />+ </div>+ {shown !== null ? (+ <>+ <div className="live-pop__password">+ <PasswordField value={shown} readOnly label="New password" />+ <button+ type="button"+ className="confirm__btn live-pop__btn"+ onClick={() => {+ window.nodeTerminal.clipboard.writeText(shown)+ setCopied(true)+ }}+ >+ {copied ? 'Copied!' : 'Copy password'}+ </button>+ </div>+ <p className="live-pop__muted live-pop__note">{PASSWORD_SHOWN_ONCE}</p>+ <p className="live-pop__muted live-pop__note">{PASSWORD_SEPARATE_NOTE}</p>+ <div className="live-pop__actions">+ <button type="button" className="confirm__btn live-pop__btn" onClick={() => setShown(null)}>+ Done+ </button>+ </div>+ </>+ ) : editing ? (+ <>+ <div className="live-pop__password">+ <PasswordField value={draft} disabled={busy} onChange={setDraft} label="New password" />+ <button type="button" className="confirm__btn live-pop__btn" disabled={busy} onClick={() => setDraft(newControlPassword())}>+ Generate+ </button>+ </div>+ {draft !== '' && problem && <p className="live-pop__invalid">{problem}</p>}+ <p className="live-pop__muted live-pop__note">{PASSWORD_CHANGE_NOTE}</p>+ <div className="live-pop__actions">+ <button+ type="button"+ className="confirm__btn live-pop__btn"+ disabled={busy}+ onClick={() => {+ setEditing(false)+ setDraft('')+ setError(null)+ }}+ >+ Cancel+ </button>+ <button+ type="button"+ className="confirm__btn primary live-pop__btn"+ disabled={busy || problem !== null}+ onClick={() => {+ const next = draft+ run(+ () => api.setPassword(linkId, next),+ PASSWORD_CHANGE_FAILED_MESSAGE,+ () => {+ setShown(next)+ setDraft('')+ setEditing(false)+ }+ )+ }}+ >+ Save+ </button>+ </div>+ </>+ ) : (+ <div className="live-pop__actions">+ <button type="button" className="confirm__btn live-pop__btn" onClick={() => setEditing(true)}>+ Change password…+ </button>+ </div>+ )}+ {error && (+ <p className="live-pop__error" role="alert">+ {error}+ </p>+ )}+ </div>+ )+}++/** A Commenter or Control link's thread with the owner's reply box. Exported for the Live chat drawer. */+export function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string }): React.JSX.Element {const api = window.nodeTerminal.watchLinkconst chat = useWatchLinks((s) => s.chats[linkId] ?? EMPTY_CHAT)const onBoard = useProjects((s) => s.projects.some((p) => p.nodes.some((n) => n.id === nodeId)))diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.tsindex 0f0696555..b0fdc4364 100644--- a/src/renderer/lib/liveLink.test.ts+++ b/src/renderer/lib/liveLink.test.ts@@ -29,10 +29,21 @@ import {STOP_FAILED_MESSAGE,stopAllConfirmMessage,TTL_OPTIONS,- viewerName+ viewerName,+ CONTROL_LOCKED_TEXT,+ CONTROL_UNSUPPORTED_REASON,+ CONTROL_WARNING,+ controlTakenText,+ liveLinkNoticeEffect,+ PASSWORD_SEPARATE_NOTE,+ PASSWORD_SHOWN_ONCE,+ passwordProblemText,+ ROLE_NAME,+ typingNames,+ UNLIMITED_NOTE} from './liveLink'import type { CreateWatchLinkError, WatchLinkView } from '@shared/watch-link-types'-import { DEFAULT_WATCH_LINK_TTL, UNLIMITED_TTL, WATCH_LINK_TTLS } 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'@@ -157,6 +168,10 @@ describe('time', () => {it('an Unlimited link has no end time', () => {expect(formatRemaining(null, 5)).toBe('No end time')expect(formatUntil(null, 5)).toBe('you stop it')+ // "now" defaults to the clock.+ expect(formatRemaining(null)).toBe('No end time')+ expect(formatUntil(null)).toBe('you stop it')+ expect(formatRemaining(Date.now() + 42 * 60_000 + 30_000)).toBe('ends in 42 min')})it('a clock time is hours and minutes, never seconds (H25)', () => {const at = new Date(2026, 9, 1, 15, 42, 37).getTime()@@ -207,7 +222,8 @@ describe('createErrorMessage', () => {it('the Unlimited and Control refusals', () => {expect(createErrorMessage('ttl-unsupported', 'desktop')).toBe('Unlimited links need a newer server. Pick an end time.')- expect(createErrorMessage('control-unsupported', 'desktop')).toBe(+ expect(createErrorMessage('control-unsupported', 'desktop')).toBe(CONTROL_UNSUPPORTED_REASON)+ expect(CONTROL_UNSUPPORTED_REASON).toBe("Control isn't available for this terminal: its Zellij session's key bindings would reach every session.")expect(createErrorMessage('bad-password', 'desktop')).toBe('The password must be 8 to 128 characters, with no line breaks.')@@ -264,12 +280,13 @@ describe('noticeText', () => {describe('fixed lists (H19)', () => {it('TTL options come from the shared list, in order, with the labels the spec names', () => {- // Unlimited is in the shared list but not offered yet: the dialog does not explain it.- expect(TTL_OPTIONS.map((o) => o.value)).toEqual(WATCH_LINK_TTLS.filter((v) => v !== UNLIMITED_TTL))- 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(TTL_OPTIONS.map((o) => o.value)).toEqual([...WATCH_LINK_TTLS])+ // Unlimited is offered, last.+ expect(TTL_OPTIONS.map((o) => o.value)).toEqual([900, 3600, 28800, 86400, 0])+ expect(TTL_OPTIONS.map((o) => o.label)).toEqual(['15 min', '1 hour', '8 hours', '24 hours', 'Unlimited'])expect(DEFAULT_TTL).toBe(DEFAULT_WATCH_LINK_TTL)expect(ROLE_LABEL).toEqual({ viewer: 'Can watch', commenter: 'Can watch and chat', controller: 'Can watch, chat and type' })+ expect(ROLE_NAME).toEqual({ viewer: 'Viewer', commenter: 'Commenter', controller: 'Control' })})})@@ -359,3 +376,144 @@ describe('the create warning', () => {expect(LIVE_LINK_WARNING).toMatch(/switch sessions/)})})++// ---- Control and Unlimited (spec 2026-10-03) -----------------------------------------------------++describe('Control and Unlimited copy', () => {+ it('is the exact ruled text', () => {+ // Spec §2.7, verbatim.+ expect(CONTROL_WARNING).toBe(+ 'Anyone with this link and the password can type in this terminal as you. In a shell that means running any command on this machine; in an agent session, giving the agent any instruction. Send the password separately from the link.'+ )+ expect(PASSWORD_SEPARATE_NOTE).toBe('Send the password separately from the link.')+ expect(PASSWORD_SHOWN_ONCE).toBe(+ 'This is the only time the password is shown. Change it later from the LIVE chip.'+ )+ expect(UNLIMITED_NOTE).toBe('This link works until you stop it.')+ expect(CONTROL_LOCKED_TEXT).toBe('Control locked after 10 wrong passwords.')+ })++ it('names every password problem the shared validator can find, and nothing for a good one', () => {+ expect(passwordProblemText('short')).toBe('Use at least 8 characters.')+ expect(passwordProblemText('')).toBe('Use at least 8 characters.')+ expect(passwordProblemText('x'.repeat(129))).toBe('Use at most 128 characters.')+ expect(passwordProblemText('longenough\nx')).toBe('Line breaks and control characters are not allowed.')+ expect(passwordProblemText('longenough')).toBeNull()+ // Code points, as a person counts: eight emoji are eight characters.+ expect(passwordProblemText('\u{1F600}'.repeat(8))).toBeNull()+ })+})++describe('who is typing', () => {+ const typing = (id: string, name: string | null) => ({ ...viewer(id), name, controlling: true, typing: true })++ it('typingNames lists the typing viewers of every link, bidi stripped, in list order', () => {+ expect(typingNames([link({ viewers: [viewer('a')] })])).toEqual([])+ expect(+ typingNames([+ link({ viewers: [viewer('a'), typing('b', 'Mert')] }),+ link({ linkId: 'M', viewers: [typing('c', 'Ayşe'), { ...viewer('d'), controlling: true }] })+ ])+ ).toEqual(['Mert', 'Ayşe'])+ })++ it('the chip counts who types, and its title names them as claims', () => {+ expect(chipView([link({ viewers: [viewer('a'), typing('b', 'Mert'), viewer('c')] })])).toEqual({+ label: 'LIVE · 3 · 1 typing',+ tone: 'live',+ title: '“Mert” is typing. This terminal is shared by a live link — 3 watching.'+ })+ expect(chipView([link({ viewers: [typing('a', 'Mert'), typing('b', 'Ayşe')] })]).title).toBe(+ '“Mert” and “Ayşe” are typing. This terminal is shared by a live link — 2 watching.'+ )+ expect(chipView([link({ viewers: [typing('a', 'A'), typing('b', 'B'), typing('c', 'C')] })])).toMatchObject({+ label: 'LIVE · 3 · 3 typing',+ title: '“A”, “B” and “C” are typing. This terminal is shared by a live link — 3 watching.'+ })+ })++ it('the worst state still wins: refused > offline > waiting > typing > count', () => {+ const t = typing('t', 'Mert')+ const w = { ...viewer('w'), waiting: true }+ expect(chipView([link({ status: 'refused', viewers: [t] })]).label).toBe('LIVE · refused')+ expect(chipView([link({ status: 'reconnecting', viewers: [t] })]).label).toBe('LIVE · offline')+ expect(chipView([link({ viewers: [t, w] })]).label).toBe('LIVE · 1 waiting')+ expect(chipView([link({ viewers: [t] })]).label).toBe('LIVE · 1 · 1 typing')+ expect(chipView([link({ viewers: [{ ...t, typing: false }] })]).label).toBe('LIVE · 1')+ })+})++describe('control notices', () => {+ it('control-taken quotes the name the viewer gave itself: a claim, not an identity', () => {+ expect(controlTakenText({ name: 'Mert', title: 'api-server' })).toBe(+ 'Someone using the name “Mert” can now type in api-server.'+ )+ expect(controlTakenText({ name: 'Mert', title: 'api-server' })).toBe(+ 'Someone using the name “Mert” can now type in api-server.'+ )+ // No name to quote: say only what is known.+ expect(controlTakenText({ name: ' ', title: 'api-server' })).toBe('Someone can now type in api-server.')+ expect(noticeText({ kind: 'control-taken', linkId: 'L', nodeId: 'n', title: 'api-server', name: 'Mert' })).toBe(+ 'Someone using the name “Mert” can now type in api-server.'+ )+ })++ it('control-locked says how to undo it', () => {+ expect(noticeText({ kind: 'control-locked', linkId: 'L', nodeId: 'n', title: 'api-server' })).toBe(+ 'Control of api-server was locked after 10 wrong passwords. Allow it again from the LIVE chip.'+ )+ })+})++describe('liveLinkNoticeEffect', () => {+ const CONSENT = { notifyOnClaudeDone: true, notifyConsentAsked: true }+ const taken = (linkId = 'L') =>+ ({ kind: 'control-taken', linkId, nodeId: 'n', title: 'api-server', name: 'Mert' }) as const++ it('every kind lands in the info strip; not-persistent and control-locked stay on screen', () => {+ expect(liveLinkNoticeEffect({ kind: 'joined', linkId: 'L', nodeId: 'n', title: 't', viewers: 1 }, CONSENT, 0, new Map())).toEqual({+ strip: { text: 'Someone started watching t (1 watching).', sticky: false },+ os: null+ })+ expect(liveLinkNoticeEffect({ kind: 'not-persistent' }, CONSENT, 0, new Map()).strip?.sticky).toBe(true)+ expect(+ liveLinkNoticeEffect({ kind: 'control-locked', linkId: 'L', nodeId: 'n', title: 't' }, CONSENT, 0, new Map())+ ).toEqual({+ strip: { text: 'Control of t was locked after 10 wrong passwords. Allow it again from the LIVE chip.', sticky: true },+ os: null+ })+ expect(liveLinkNoticeEffect({ kind: 'from-a-newer-core' } as never, CONSENT, 0, new Map())).toEqual({ strip: null, os: null })+ })++ it('control-taken also raises an OS notification, under the agent-done consent gate', () => {+ const text = 'Someone using the name “Mert” can now type in api-server.'+ expect(liveLinkNoticeEffect(taken(), CONSENT, 0, new Map())).toEqual({+ strip: { text, sticky: false },+ os: { title: 'Live link', body: text, nodeId: 'n' }+ })+ for (const prefs of [+ { notifyOnClaudeDone: false, notifyConsentAsked: true },+ { notifyOnClaudeDone: true, notifyConsentAsked: false },+ {}+ ]) {+ const fx = liveLinkNoticeEffect(taken(), prefs, 0, new Map())+ expect(fx.os, JSON.stringify(prefs)).toBeNull()+ expect(fx.strip?.text).toBe(text)+ }+ })++ it('one OS notification per link per 5 s; the strip still says it every time', () => {+ const at = new Map<string, number>()+ expect(liveLinkNoticeEffect(taken(), CONSENT, 1000, at).os).not.toBeNull()+ const again = liveLinkNoticeEffect(taken(), CONSENT, 5999, at)+ expect(again.os).toBeNull()+ expect(again.strip).not.toBeNull()+ // Another link is its own.+ expect(liveLinkNoticeEffect(taken('M'), CONSENT, 2000, at).os).not.toBeNull()+ expect(liveLinkNoticeEffect(taken(), CONSENT, 6000, at).os).not.toBeNull()+ // A notification the consent gate held back does not start the cooldown.+ const held = new Map<string, number>()+ liveLinkNoticeEffect(taken(), {}, 0, held)+ expect(liveLinkNoticeEffect(taken(), CONSENT, 1, held).os).not.toBeNull()+ })+})diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.tsindex dcd79a083..f75f7db76 100644--- a/src/renderer/lib/liveLink.ts+++ b/src/renderer/lib/liveLink.ts@@ -20,9 +20,9 @@ import {DEFAULT_WATCH_LINK_TTL,MAX_LINKS_PER_MACHINE,stripBidiControls,- UNLIMITED_TTL,WATCH_LINK_TTLS} from '@shared/watch-link-types'+import { controlPasswordProblem, type ControlPasswordProblem } from '@shared/watch-link-password'import { otherMachines, thisMachine } from './machineName'export const ROLE_LABEL: Record<WatchLinkRole, string> = {@@ -30,6 +30,12 @@ export const ROLE_LABEL: Record<WatchLinkRole, string> = {commenter: 'Can watch and chat',controller: 'Can watch, chat and type'}+/** The role's name, as the create dialog's choice and the popover's role line say it (spec §2.1). */+export const ROLE_NAME: Record<WatchLinkRole, string> = {+ viewer: 'Viewer',+ commenter: 'Commenter',+ controller: 'Control'+}/** 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> = {@@ -39,15 +45,15 @@ const TTL_LABEL: Record<WatchLinkTtl, string> = {86400: '24 hours',0: 'Unlimited'}-/** The create dialog's expiry choices — derived from the list core validates against (H19). Unlimited- * is not offered yet: the dialog does not say what a link with no end time means. */-export const TTL_OPTIONS: { value: WatchLinkTtl; label: string }[] = WATCH_LINK_TTLS.filter(- (value) => value !== UNLIMITED_TTL-).map((value) => ({+/** The create dialog's expiry choices — derived from the list core validates against (H19), so+ * Unlimited (`0`) comes last, as the shared list orders it. */+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+/** Under the expiry choices while Unlimited is picked. */+export const UNLIMITED_NOTE = 'This link works until you stop it.'/** Always on the create dialog. "Everything this terminal shows" is meant literally (R64/M3): the* stream is the terminal CLIENT's output, so tmux's session chooser (`C-b s` / `C-b w`, a live@@ -58,6 +64,40 @@ export const LIVE_LINK_WARNING =export const KICK_NOTE ='Kick ends this connection; anyone with the link can rejoin. Stop sharing to end it for everyone.'+/** The create dialog's warning while Control is picked, in place of `LIVE_LINK_WARNING` — spec §2.7,+ * verbatim. "This machine" is the neutral noun: no brand is assumed (lib/machineName). */+export const CONTROL_WARNING =+ 'Anyone with this link and the password can type in this terminal as you. In a shell that means running any command on this machine; in an agent session, giving the agent any instruction. Send the password separately from the link.'+/** Beside a password shown once (the create dialog's done step, a changed password in the popover). */+export const PASSWORD_SEPARATE_NOTE = 'Send the password separately from the link.'+/** Core keeps only a hash (spec §2.2): there is no "show again". */+export const PASSWORD_SHOWN_ONCE = 'This is the only time the password is shown. Change it later from the LIVE chip.'+/** Why Control is not offered on a node — the dialog's disabled option and the create error alike. */+export const CONTROL_UNSUPPORTED_REASON =+ "Control isn't available for this terminal: its Zellij session's key bindings would reach every session."+/** A Control link locked by wrong passwords (spec §2.3), beside "Allow control again". */+export const CONTROL_LOCKED_TEXT = 'Control locked after 10 wrong passwords.'+/** The popover's Change password form: a new password demotes every controller (Task 4 ruling). */+export const PASSWORD_CHANGE_NOTE = 'Anyone typing now goes back to watching until they unlock with the new password.'+/** `setControl` / `allowControl` answered false, or did not answer. */+export const CONTROL_CHANGE_FAILED_MESSAGE = "That change didn't take — try again."+/** `setPassword` answered false, or did not answer: the old password still works. */+export const PASSWORD_CHANGE_FAILED_MESSAGE = "The password wasn't changed — try again. The old one still works."++const PASSWORD_PROBLEM_TEXT: Record<ControlPasswordProblem, string> = {+ // Not reachable from a text field; named so a `Record` over the shared union compiles.+ type: 'Use at least 8 characters.',+ short: 'Use at least 8 characters.',+ long: 'Use at most 128 characters.',+ control: 'Line breaks and control characters are not allowed.'+}+/** What is wrong with a typed Control password, in words — null when core will take it. The rule is+ * the shared one core checks (`controlPasswordProblem`), so the field and the create cannot differ. */+export function passwordProblemText(pw: string): string | null {+ const problem = controlPasswordProblem(pw)+ return problem === null ? null : PASSWORD_PROBLEM_TEXT[problem]+}+/** 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'@@ -141,11 +181,32 @@ export function waitingViewers(links: readonly Pick<WatchLinkView, 'viewers'>[])return links.reduce((n, l) => n + l.viewers.filter((v) => v.waiting === true).length, 0)}+/**+ * The names of the viewers typing right now, across a node's links, in list order (a controller's+ * name is the one it unlocked with). Bidi-stripped; a nameless one is "Viewer N" like in the list.+ */+export function typingNames(links: readonly Pick<WatchLinkView, 'viewers'>[]): string[] {+ const out: string[] = []+ for (const l of links) l.viewers.forEach((v, i) => v.typing && out.push(viewerName(v, i)))+ return out+}++/** A viewer's name is a claim it made about itself, so a sentence about the person quotes it. */+function quoted(name: string): string {+ return `\u201c${name}\u201d`+}+/** "“A” is typing." / "“A” and “B” are typing." / "“A”, “B” and “C” are typing." */+function typingSentence(names: readonly string[]): string {+ const q = names.map(quoted)+ if (q.length === 1) return `${q[0]} is typing.`+ return `${q.slice(0, -1).join(', ')} and ${q[q.length - 1]} are typing.`+}+/*** 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; `waiting` (R63) needs the owner to open the- * terminal. The titles send the owner to the popover, which carries the status line that explains- * it (H9).+ * terminal. Then someone typing (a Control link), then the plain count. 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)@@ -166,10 +227,19 @@ export function chipView(links: readonly WatchLinkView[]): { label: string; tone}if (waiting > 0) return { label: `LIVE · ${waiting} waiting`, tone: 'waiting', title: VIEWERS_WAITING_MESSAGE }const shared = links.length > 1 ? `This terminal is shared by ${links.length} live links` : 'This terminal is shared by a live link'+ const watching = viewers > 0 ? `${shared} — ${viewers} watching.` : `${shared}.`+ const typing = typingNames(links)+ if (typing.length > 0) {+ return {+ label: `LIVE · ${viewers} · ${typing.length} typing`,+ tone: 'live',+ title: `${typingSentence(typing)} ${watching}`+ }+ }return {label: viewers > 0 ? `LIVE · ${viewers}` : 'LIVE',tone: 'live',- title: viewers > 0 ? `${shared} — ${viewers} watching.` : `${shared}.`+ title: watching}}@@ -187,7 +257,7 @@ export function statusLine(link: Pick<WatchLinkView, 'status' | 'viewers'>): str/** How long a link still runs. Hours AND minutes past the hour: a floored "1 h" for 1 h 59 min* understated by up to an hour the one figure that says how long a broadcast goes on. `null` is an* Unlimited link. */-export function formatRemaining(expiresAt: number | null, now: number): string {+export function formatRemaining(expiresAt: number | null, now: number = Date.now()): string {if (expiresAt === null) return 'No end time'const ms = expiresAt - nowif (ms <= 0) return 'ended'@@ -210,7 +280,7 @@ export function formatClock(ms: number): string {* link past midnight read like today. So a different day is named — "tomorrow 15:43", or the weekday* and date further out. An Unlimited link (`null`) runs "until you stop it".*/-export function formatUntil(expiresAt: number | null, now: number): string {+export function formatUntil(expiresAt: number | null, now: number = Date.now()): string {if (expiresAt === null) return 'you stop it'const end = new Date(expiresAt)const today = new Date(now)@@ -293,7 +363,7 @@ export function createErrorMessage(e: CreateWatchLinkError, surface: LiveLinkSurcase 'ttl-unsupported':return 'Unlimited links need a newer server. Pick an end time.'case 'control-unsupported':- return "Control isn't available for this terminal: its Zellij session's key bindings would reach every session."+ return CONTROL_UNSUPPORTED_REASONcase 'bad-password':return 'The password must be 8 to 128 characters, with no line breaks.'}@@ -312,7 +382,21 @@ export function shareDisabledReason(o: { serverEdition: boolean; relayTab: boolereturn null}-/** The info strip for a notice from core; null for a kind this build does not know. */+/**+ * "Someone using the name “Mert” can now type in api-server." The name is the one the viewer gave+ * itself when it unlocked: a claim, quoted as one, never presented as who it is.+ */+export function controlTakenText(n: { name: string; title: string }): string {+ const name = stripBidiControls(n.name).trim()+ const title = stripBidiControls(n.title)+ return name ? `Someone using the name ${quoted(name)} can now type in ${title}.` : `Someone can now type in ${title}.`+}++/**+ * The info strip for a notice from core; null for a kind this build does not know (a newer core).+ * Exhaustive over the kinds this build knows: a kind added to `WatchLinkNotice` fails to compile+ * here until it has copy — a `default: return null` once let two kinds render nothing.+ */export function noticeText(n: WatchLinkNotice): string | null {switch (n.kind) {case 'joined':@@ -331,11 +415,55 @@ export function noticeText(n: WatchLinkNotice): string | null {// 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:+ case 'control-taken':+ return controlTakenText(n)+ case 'control-locked':+ return `Control of ${stripBidiControls(n.title)} was locked after 10 wrong passwords. Allow it again from the LIVE chip.`+ default: {+ // Compile-time: every known kind is handled above. Runtime: a newer core's kind is no notice.+ const unknown: never = n+ void unknownreturn null+ }}}+/** One OS notification per link per this long (the agent-done notification's per-node cooldown). */+const NOTIFY_COOLDOWN_MS = 5000++export interface LiveLinkNoticeEffect {+ /** The info strip; `sticky` = it stays until dismissed. */+ strip: { text: string; sticky: boolean } | null+ /** An OS notification (`window.nodeTerminal.notify`), or null. */+ os: { title: string; body: string; nodeId: string } | null+}++/**+ * What Canvas does with a notice from core — ONE decision, so the strip, the consent gate and the+ * cooldown are tested here rather than inside Canvas. Sticky: `not-persistent` (shown after every+ * create while links cannot be saved) and `control-locked` (nobody can unlock until the owner+ * allows it again). `control-taken` — someone can now type in this terminal — also raises an OS+ * notification, under the SAME consent the agent-done notification uses (`notifyOnClaudeDone &&+ * notifyConsentAsked`; main shows it only while the window is unfocused) and at most once per link+ * per 5 s. `lastOsAt` is the caller's per-link cooldown record; it is written only when a+ * notification is raised.+ */+export function liveLinkNoticeEffect(+ n: WatchLinkNotice,+ prefs: { notifyOnClaudeDone?: boolean; notifyConsentAsked?: boolean },+ now: number,+ lastOsAt: Map<string, number>+): LiveLinkNoticeEffect {+ const text = noticeText(n)+ if (text === null) return { strip: null, os: null }+ const strip = { text, sticky: n.kind === 'not-persistent' || n.kind === 'control-locked' }+ if (n.kind !== 'control-taken' || !(prefs.notifyOnClaudeDone && prefs.notifyConsentAsked)) return { strip, os: null }+ for (const [id, at] of lastOsAt) if (now - at >= NOTIFY_COOLDOWN_MS) lastOsAt.delete(id)+ if (lastOsAt.has(n.linkId)) return { strip, os: null }+ lastOsAt.set(n.linkId, now)+ return { strip, os: { title: 'Live link', body: text, nodeId: n.nodeId } }+}+/** 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()diff --git a/src/renderer/state/watchLinks.test.ts b/src/renderer/state/watchLinks.test.tsindex 5518c346b..f3e89aa1a 100644--- a/src/renderer/state/watchLinks.test.ts+++ b/src/renderer/state/watchLinks.test.ts@@ -274,3 +274,27 @@ describe('startWatchLinkSync', () => {stop2()})})++describe('watchLinks store — Control links', () => {+ it('counts a Control link\'s viewer messages exactly like a Commenter link\'s', () => {+ const s = useWatchLinks.getState()+ s.setLinks([link('c', 'n1', { role: 'controller', control: { enabled: true, locked: false } })])+ s.addChat('c', msg('1'))+ s.addChat('c', msg('2', 'sharer'))+ s.addChat('c', msg('3'))+ expect(useWatchLinks.getState().unread.c).toBe(2)+ const sig = liveChipSig(useWatchLinks.getState(), 'n1')+ expect(sig.endsWith('\u00012')).toBe(true)+ useWatchLinks.getState().markRead('c')+ expect(useWatchLinks.getState().unread.c).toBe(0)+ })++ it('the chip signature follows who is typing', () => {+ const s = useWatchLinks.getState()+ const v = { viewerId: 'v', name: 'Mert', joinedAt: 0, waiting: false, controlling: true, typing: false }+ s.setLinks([link('c', 'n1', { role: 'controller', control: { enabled: true, locked: false }, viewers: [v] })])+ const idle = liveChipSig(useWatchLinks.getState(), 'n1')+ s.setLinks([link('c', 'n1', { role: 'controller', control: { enabled: true, locked: false }, viewers: [{ ...v, typing: true }] })])+ expect(liveChipSig(useWatchLinks.getState(), 'n1')).not.toBe(idle)+ })+})diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 937600e7d..4b6fa5328 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -11655,8 +11655,7 @@ button.pull-checks__name {.live-chip:hover {background: color-mix(in srgb, var(--live-tone) 20%, transparent);}-.live-chip__dot,-.live-chip__unread {+.live-chip__dot {flex: 0 0 auto;width: 6px;height: 6px;@@ -11676,8 +11675,23 @@ button.pull-checks__name {--live-tone: var(--muted);color: var(--muted);}+/* Unread chat: a COUNT (summed over the node's links), ink on an unread wash — the status-chip+ recipe, so it reads on the default look and under Liquid Glass alike. Fits the 16px sidebar chip. */.live-chip__unread {- background: var(--state-unread);+ flex: 0 0 auto;+ box-sizing: border-box;+ min-width: 13px;+ height: 13px;+ padding: 0 3px;+ border: 1px solid color-mix(in srgb, var(--state-unread) 70%, transparent);+ border-radius: 7px;+ background: color-mix(in srgb, var(--state-unread) 28%, transparent);+ color: var(--text);+ font-size: 9px;+ font-weight: 700;+ font-variant-numeric: tabular-nums;+ line-height: 11px;+ text-align: center;}.kanban-card__live,.kanban-modal__live {@@ -11834,6 +11848,53 @@ button.pull-checks__name {padding: 4px 8px;font-size: 12px;}+/* A Control link's owner controls in the popover (ControlSection): the Typing switch row, the+ locked line with Allow control again, and the Change password field (a new one shown once). */+.live-pop__control {+ margin: 8px 0;+ padding: 8px 0;+ border-top: 1px solid var(--border);+ border-bottom: 1px solid var(--border);+}+.live-pop__locked {+ margin-bottom: 8px;+}+.live-pop__locked .live-pop__btn {+ margin-top: 6px;+}+.live-pop__toggle {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+}+.live-pop__password {+ display: flex;+ gap: 6px;+ align-items: center;+ margin-top: 8px;+}+.live-pop__password .confirm__input {+ flex: 1 1 auto;+ min-width: 0;+ margin: 0;+ padding: 4px 8px;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+}+.live-pop p.live-pop__invalid {+ margin: 4px 0 0;+ color: var(--danger);+ font-size: 11px;+}+/* A viewer typing right now (a Control link): the working role, never animated (Idle energy). */+.live-pop__typing {+ flex: 0 0 auto;+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: var(--state-working);+}/* The create dialog (LiveLinkDialog): the `.confirm` shell, a little wider for the URL. */.confirm.live-dialog {width: 460px;@@ -11906,6 +11967,41 @@ button.pull-checks__name {color: var(--muted);font-size: 12px;}+/* A note that belongs to the control just above it (Unlimited's, a password shown once). */+.live-dialog__note.live-dialog__note--tight {+ margin: -4px 0 10px;+}+/* The role choice: "Viewer · Can watch". */+.live-dialog__hint {+ color: var(--muted);+}+/* Control on a terminal that cannot take typed input (a Zellij session): shown, disabled, with why. */+.live-dialog__group label.live-dialog__off {+ cursor: not-allowed;+ opacity: 0.55;+}+.live-dialog__reason {+ width: 100%;+ margin: 2px 0 0;+ color: var(--muted);+ font-size: 11px;+}+/* A Control link's password: the form's field with Generate, and the done step's copy of it. */+.live-dialog__pw {+ color: var(--muted);+ font-size: 11px;+}+.live-dialog__url.live-dialog__password {+ margin: 4px 0 10px;+}+.live-dialog__password .confirm__input {+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+}+.live-dialog__invalid {+ margin: -6px 0 10px;+ color: var(--danger);+ font-size: 11px;+}/* "Share with team" (ShareTeamDialog): the `.confirm` shell, wider for the lists, with the body asthe scrolling region so Share / Close stay on screen however long the lists are. */.confirm.share-team {