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): remove the live links UI, its Pro row and the upgrade gate
reviewc86b49cd990f
diff --git a/src/renderer/boot.tsx b/src/renderer/boot.tsxindex 830128d6a..1699d283b 100644--- a/src/renderer/boot.tsx+++ b/src/renderer/boot.tsx@@ -8,6 +8,8 @@ import { initAgentResolver } from './state/agent-resolver'import { refreshAgentEnv } from './lib/agentEnv'import { applyWindowChrome } from './lib/windowChrome'import { installMarkdownLinkGuard, LOCAL_LINK_MESSAGE, openExternalQuietly } from './lib/markdownLinks'+import { removeRetiredStorageKeys } from './lib/retiredStorage'+import { removeLocal } from './lib/localStore'import './styles.css'import './tailwind.css'@@ -32,6 +34,10 @@ installMarkdownLinkGuard(document, {)})+// Live links were retired: drop the localStorage keys they kept. Through lib/localStore, so a+// storage that is missing, method-less or throws never stops the boot.+removeRetiredStorageKeys({ removeItem: removeLocal })+// Register the custom-agent → baseAgent resolver so the capability predicates (hasHooks, canResume,// canControlCanvas, …) resolve a custom agent's inherited harness. Reads the live settings store.initAgentResolver()diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 3af4243da..392732952 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -152,8 +152,6 @@ import { CommandPalette, type Command } from '../components/CommandPalette'import { Tooltip } from '../components/Tooltip'import {IconBranch,- IconBroadcast,- IconChat,IconCanvasView,IconClose,IconCollapse,@@ -197,7 +195,6 @@ import {SettingsPage,SourceControlPanel,ExplorerPanel,- LiveChatDrawer,ShortcutsPanel,OnboardingFlow,DictationOverlay,@@ -287,7 +284,6 @@ import { peerApprovalView } from '@shared/remote/approval'import { admitPendingPeer } from '../lib/pendingPeerAdmission'import { SAS_COMPARE_HINT } from '@shared/remote/sas'import { promptDialog } from '../components/promptDialog'-import { UpgradeDialog } from '../components/UpgradeDialog'import { AnnouncementPopup } from '../components/AnnouncementPopup'import { ProjectLimitDialog } from '../components/ProjectLimitDialog'import {@@ -298,21 +294,6 @@ import {} from '../lib/projectLimitGate'import { countOpenProjects, decideOpen } from '@shared/project-limit'import { opensProject, type OpenAction } from '../lib/projectOpens'-import { LiveLinkDialog } from '../components/LiveLinkDialog'-import { requireProOr } from '../state/upgradeGate'-import { startWatchLinkSync, useWatchLinks } from '../state/watchLinks'-import { liveLinkNoticeEffect } from '../lib/liveLink'-import {- liveLinkCommands,- liveLinkMenuItemsFor,- liveLinkPrepare,- liveLinkRemoteFacts,- openLiveLink,- stopAllConfirm,- stopAllLiveLinks,- type LiveLinkAvailabilityFacts,- type LiveLinkTarget-} from '../lib/liveLinkEntry'import { RemotePicker } from '../components/RemotePicker'import { WorktreeDialog } from '../components/WorktreeDialog'import { SpawnTeamDialog } from '../components/SpawnTeamDialog'@@ -508,15 +489,6 @@ const sshDisconnect = (scopeId: string): Promise<unknown> =>import { opensInEditor } from '../lib/openTarget'import { displacedFilesPatch } from '../lib/filesNode'import { newEntryPath, parentDir } from '../lib/explorerCreate'-import {- liveChatShown,- nextLiveChat,- readLiveChatLink,- readLiveChatPinned,- writeLiveChatLink,- writeLiveChatPinned,- type LiveChatState-} from '../lib/liveChatPin'import {explorerIsOpen,nextExplorerPin,@@ -3896,186 +3868,8 @@ export function Canvas() {// eslint-disable-next-line react-hooks/exhaustive-deps -- refs are read at call time}, [api, persist])- // ── Live links (Task 17) ────────────────────────────────────────────────────────────────────- // 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` (a security event), an OS notification under the notification consent alone — not- // the agent-done preference — once per link per 5 s.- const liveNotifyAtRef = useRef(new Map<string, number>())- useEffect(- () =>- startWatchLinkSync(window.nodeTerminal, (n) => {- 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 Live chat drawer (lib/liveChatPin — the Explorer's pin pattern, its own keys): which link it- // follows and whether it is docked are this machine's view state, in localStorage only. Opened by- // the popover's "Open chat" (`nodeterm:live-chat`, `{ linkId }` — this is its ONE listener, pinned- // in lib/nodeterm-events.test.ts) and by the palette's "Live chat".- const [liveChat, setLiveChat] = useState<LiveChatState>(() => ({- pinned: readLiveChatPinned(),- dismissed: false,- open: false,- linkId: readLiveChatLink()- }))- // A primitive count, not the list: a push about one link's viewers must not re-render the canvas.- // A pinned drawer is rendered only while a link is live (`liveChatShown`); the pin is kept.- const liveLinkCount = useWatchLinks((s) => s.links.length)- const liveChatRef = useRef(liveChat)- liveChatRef.current = liveChat- useEffect(() => {- const on = (e: Event): void => {- const linkId = (e as CustomEvent<{ linkId?: unknown }>).detail?.linkId- if (typeof linkId !== 'string' || !linkId) return- // Open chat on a chip IS a pick: the drawer comes back to this link next time.- writeLiveChatLink(linkId)- setLiveChat((s) => nextLiveChat(s, { kind: 'open', linkId }))- }- window.addEventListener('nodeterm:live-chat', on)- return () => window.removeEventListener('nodeterm:live-chat', on)- }, [])- const pickLiveChatLink = useCallback((linkId: string) => {- writeLiveChatLink(linkId)- setLiveChat((s) => nextLiveChat(s, { kind: 'open', linkId }))- }, [])- const closeLiveChat = useCallback(() => setLiveChat((s) => nextLiveChat(s, { kind: 'close' })), [])- const toggleLiveChatPin = useCallback(() => {- setLiveChat((s) => {- const next = nextLiveChat(s, { kind: 'pin' })- writeLiveChatPinned(next.pinned)- return next- })- }, [])- /** True while a kanban card modal is open (either board): the drawer then sits above its scrim. */+ /** True while a kanban card modal is open (either board): a check-feed popup waits for it. */const [cardModalOpen, setCardModalOpen] = useState(false)- 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 relay- * tab — shown on the Omni board or in the sidebar while a local tab is active — is judged by the- * relay session, not by whichever tab is on screen. Read at call time, never memoized. */- const liveLinkFacts = useCallback(- (projectId: string): LiveLinkAvailabilityFacts => ({- serverEdition: isBrowserRuntime(),- source: sessionForProject(projectId).source,- activeLinks: useWatchLinks.getState().links.length- }),- []- )- /** Every entry point ends here: availability (with its reason in the info strip), THEN the Pro- * gate, then the dialog — see lib/liveLinkEntry `openLiveLink`. */- const openLiveLinkFor = useCallback(- (target: LiveLinkTarget) =>- openLiveLink(- {- facts: liveLinkFacts,- requirePro: requireProOr,- show: setLiveLinkDialog,- notice: (text) => setNotice({ kind: 'info', text })- },- target- ),- [liveLinkFacts]- )- // The card modal's "Share live link" action (it cannot reach Canvas state). Its detail names the- // card's PROJECT, so an Omni-board card of another tab is judged by its own session.- useEffect(() => {- const on = (e: Event): void => {- const d = (e as CustomEvent<{ nodeId?: unknown; title?: unknown; projectId?: unknown }>).detail- if (typeof d?.nodeId !== 'string' || typeof d.projectId !== 'string') return- const title = typeof d.title === 'string' && d.title.trim() ? d.title : 'Terminal'- openLiveLinkFor({ nodeId: d.nodeId, title, projectId: d.projectId })- }- window.addEventListener('nodeterm:live-link', on)- return () => window.removeEventListener('nodeterm:live-link', on)- }, [openLiveLinkFor])- /**- * The "Share live link…" row for one node — ONE builder behind the canvas node menu, the- * sessions-sidebar row of ANY project, and both boards' card menus (R49). The active project's- * node comes from the live canvas; any other project's from its stored copy: a link does not- * need the node on screen (core attaches join-only). Declared before `selectionItems`, which- * lists it in its deps (a stale closure otherwise).- */- const liveLinkMenuItems = useCallback(- (nodeId: string, projectId?: string): MenuItem[] => {- const store = useProjects.getState()- // The composition (which project, which node, whose facts) is lib/liveLinkEntry's, where it is- // behaviour-tested: the facts are the NODE's project's, never the active tab's (D2/M1).- return liveLinkMenuItemsFor({- nodeId,- projectId,- activeProjectId: store.activeProjectId,- live: nodesRef.current,- stored: (pid) => store.getProject(pid)?.nodes,- hidden: useSettings.getState().settings.hiddenNodeMenuItems,- facts: liveLinkFacts,- icon: <IconBroadcast />,- open: openLiveLinkFor- })- },- [liveLinkFacts, openLiveLinkFor]- )- /**- * R47: before core looks the node up, publish pending edits of the canvas on screen — a node- * opened seconds ago is not in the saved project yet and would answer `node-missing`. The same- * rule a board comment's delivery uses (`syncMessageScope`): never saved over an unresolved- * external-edit conflict. A background project's node needs no flush: its stored copy is what was- * last written.- */- const liveLinkPrepareFor = useCallback(- (target: LiveLinkTarget) => (): Promise<string | null> =>- liveLinkPrepare({- needed:- target.projectId === useProjects.getState().activeProjectId &&- dirtyRef.current &&- nodesRef.current.some((n) => n.id === target.nodeId),- conflict: !!conflictRef.current,- save: persist- }),- [persist]- )-- /** R63: the create dialog's "only while open" note reads the LOCAL core's session protection — the- * core that hosts the link (never a relay tab's peer). Stable, so the dialog reads it once. */- const readLocalPersistence = useCallback(() => localSession.api.pty.tmuxStatus(), [])- /** Where the dialog's node runs — R63 (`remoteNode`) and the machine the Control warning names- * (`sshTarget`) — from the NODE's own SSH binding first, then its project's (lib/liveLinkEntry).- * The node is read from the live canvas for the active project, else the stored copy. */- const liveLinkRemoteFor = useCallback((target: LiveLinkTarget) => {- const store = useProjects.getState()- const project = store.getProject(target.projectId)- return liveLinkRemoteFacts({- nodeId: target.nodeId,- projectId: target.projectId,- activeProjectId: store.activeProjectId,- live: nodesRef.current,- stored: project?.nodes,- projectSsh: project?.ssh?.server- })- }, [])-- /** R48: "Stop all" revokes every link of the LICENSE — other machines' included — and cannot be- * undone, so the palette asks first, with the same sentence and danger button as Settings. R62:- * what it reached is ALWAYS said — a success too, since with no link listed here nothing else on- * screen changes, and a server call that failed leaves other machines' links running. */- const confirmStopAllLiveLinks = useCallback(- () =>- setConfirm(- stopAllConfirm({- close: () => setConfirm(null),- stop: () =>- void stopAllLiveLinks(() => window.nodeTerminal.watchLink.revokeAll()).then((r) =>- setNotice({ kind: r.ok ? 'info' : 'error', text: r.text })- )- })- ),- [setConfirm]- )/** Re-runs the active-project load effect by bumping the store's `reloadNonce`.*@@ -11232,7 +11026,6 @@ export function Canvas() {toggleCollapseNodes,toggleMarkdown,reloadTerminals,- liveLinkMenuItems: (nodeId) => liveLinkMenuItems(nodeId),branchClaude,transferConversation,restartAgentNode,@@ -11259,7 +11052,6 @@ export function Canvas() {toggleCollapseNodes,toggleMarkdown,reloadTerminals,- liveLinkMenuItems,branchClaude,transferConversation,restartAgentNode,@@ -11290,13 +11082,11 @@ export function Canvas() {const nodeActionCtxFor = useCallback((projectId: string): NodeActionCtx => {const writes = nodeWritesFor(projectId)- const liveLink = (nodeId: string): MenuItem[] => liveLinkMenuItems(nodeId, projectId)if (liveCanvasHolds(nodesProjectIdRef.current, useProjects.getState().activeProjectId, projectId)) {return {...liveNodeActionCtx(),setNodesColor: writes.setColor,- pickNodeIcon: writes.pickIcon,- liveLinkMenuItems: liveLink+ pickNodeIcon: writes.pickIcon}}const project = useProjects.getState().getProject(projectId)@@ -11309,7 +11099,6 @@ export function Canvas() {grokModels: () => grokModelList(),cursorModels: () => cursorModelList(),writes,- liveLinkMenuItems: liveLink,connectedProjectIdForHost,refuse: () =>window.dispatchEvent(@@ -11317,7 +11106,7 @@ export function Canvas() {)})},- [nodeWritesFor, liveLinkMenuItems, liveNodeActionCtx, gatewayModels, gatewayStatus, gatewayError, connectedProjectIdForHost]+ [nodeWritesFor, liveNodeActionCtx, gatewayModels, gatewayStatus, gatewayError, connectedProjectIdForHost])/** A kanban card's rows from the node builder (BOARD_NODE_ACTION_IDS), for a node of `projectId`. */@@ -17316,8 +17105,6 @@ export function Canvas() {void writeDisk()}},- // Works for any project: a live link needs no node on screen (R49).- ...liveLinkMenuItems(id, projectId),{ type: 'separator' },{ label: 'End session', icon: <IconTrash />, danger: true, onClick: () => closeSession(projectId, id) }]@@ -17329,8 +17116,7 @@ export function Canvas() {renameSession,closeSession,writeDisk,- selectionItems,- liveLinkMenuItems+ selectionItems])@@ -18380,23 +18166,6 @@ export function Canvas() {travelToNodeRef.current = travelToNode})- /** The Live chat drawer sits above a kanban card modal (z 57 over 55) — opened from the card's LIVE- * chip — but never above Settings, which stays on top. `kanbanOpen` too: the per-project board- * reports a closed modal on change, not on unmount, so a board closed with its card open would- * leave the flag behind. */- const liveChatRaised = cardModalOpen && kanbanOpen && !settingsOpen-- /** The Live chat drawer's "Go to terminal": a modal drawer gives way to the canvas first (its scrim- * would cover the node); a docked one stays. The project switch, a closed project's reopen and the- * board's "open the card" are `travelToNode`'s. */- const goToLiveChatNode = useCallback(- (nodeId: string) => {- if (!liveChatRef.current.pinned) setLiveChat((s) => nextLiveChat(s, { kind: 'close' }))- travelToNode(nodeId)- },- [travelToNode]- )-// Prepare-for-update (Windows session host, issue #829). Opened from the update card or ⌘K via// `nodeterm:prepare-update`. `prepareUpdateAvailable` gates the ⌘K entry: the main process answers// `unsupported` off Windows, when the session host is not the backend, and in the Server Edition.@@ -19466,21 +19235,6 @@ export function Canvas() {)]),{ id: 'save', label: 'Save', icon: <IconSave />, run: () => void persist() },- // Live links: Manage (the Settings section), and Stop all — which CONFIRMS (R48).- ...liveLinkCommands({- activeLinks: useWatchLinks.getState().links.length,- entitled: useEntitlement.getState().isPremium,- serverEdition: isBrowserRuntime(),- icon: <IconBroadcast />,- chatIcon: <IconChat />,- manage: () => {- setSettingsSection('live-links')- setSettingsNonce((n) => n + 1)- setSettingsOpen(true)- },- openChat: () => setLiveChat((s) => nextLiveChat(s, { kind: 'open' })),- confirmStopAll: confirmStopAllLiveLinks- }),// Hidden when the canvas has no restartable agent node — the row would have nothing to act// on. `hint` is searchable, so "new model" / "update" find it too....(hasRestartableAgents()@@ -19608,7 +19362,6 @@ export function Canvas() {hostedBookmarks,copyHostedInviteCode,forgetHostedTeam,- confirmStopAllLiveLinks,shareBlockedReason,openShareWithTeam,prepareUpdateAvailable@@ -20494,19 +20247,6 @@ export function Canvas() {/>)}- {liveChatShown(liveChat, liveLinkCount) && (- <LiveChatDrawer- linkId={liveChat.linkId}- pinned={liveChat.pinned}- raised={liveChatRaised}- beside={liveChat.pinned && explorerOpen && explorer.pinned && !liveChatRaised}- onPickLink={pickLiveChatLink}- onClose={closeLiveChat}- onTogglePin={toggleLiveChatPin}- onGoToNode={goToLiveChatNode}- />- )}-<SessionsSidebaropen={sessionsOpen}pinned={sessionsPinned}@@ -20751,7 +20491,6 @@ export function Canvas() {/>)}- <UpgradeDialog />{/* The surfaces below are not on the dialog stack, so the popup is told about them here: itmust not land on the setup tour, Settings, the palette, a dictation in progress, …. Thekanban card modal registers on the stack itself; `cardModalOpen` is belt and braces. */}@@ -20774,30 +20513,6 @@ export function Canvas() {{/* The free-tier limit moment (docs/project-limit.md). Close is the ordinary non-destructive close — never`endSessions`: the limit only ever blocks a NEW open, it never ends anything. */}<ProjectLimitDialog onCloseProject={(id) => performCloseProject(id)} />- {liveLinkDialog && (- <LiveLinkDialog- key={`${liveLinkDialog.projectId}:${liveLinkDialog.nodeId}`}- nodeId={liveLinkDialog.nodeId}- title={liveLinkDialog.title}- surface={- isBrowserRuntime()- ? 'server'- : sessionForProject(liveLinkDialog.projectId).source === 'relay'- ? 'relay'- : 'desktop'- }- // R63: a node in a HOST's tmux gets a viewer client of its own (the "only while open" note- // is about this machine's local terminals); the Control warning names where a- // controller's commands run. Both from where the NODE runs, not only its project.- {...liveLinkRemoteFor(liveLinkDialog)}- readPersistence={readLocalPersistence}- prepare={liveLinkPrepareFor(liveLinkDialog)}- // No license layer in the Server Edition (R43): never an Upgrade button there.- onUpgrade={isBrowserRuntime() ? undefined : () => void useEntitlement.getState().upgrade('pro')}- onClose={closeLiveLinkDialog}- />- )}-{remotePicker && (<RemotePickerx={remotePicker.x}diff --git a/src/renderer/canvas/live-link-wiring.test.ts b/src/renderer/canvas/live-link-wiring.test.tsdeleted file mode 100644index 69badb263..000000000--- a/src/renderer/canvas/live-link-wiring.test.ts+++ /dev/null@@ -1,184 +0,0 @@-// Live links: how Canvas wires the entry points (Task 17). Canvas.tsx is ~18k lines and cannot be-// mounted here, so what matters about its WIRING is pinned at source level — the decisions-// themselves are behaviour-tested in lib/liveLinkEntry(.gate).test and the dialog/section tests.-//-// Each assertion is a way an entry point could skip a rule and still compile:-// - a dialog opened other than through `openLiveLink` skips availability-before-the-Pro-gate;-// - a `revokeAll` outside the confirm skips R48;-// - a create without `prepare` skips R47 (a just-opened node answers node-missing);-// - the sync never started leaves the store empty and no chip ever shows.-import { describe, expect, it } from 'vitest'-import { readFileSync } from 'node:fs'-import { join } from 'node:path'--const src = readFileSync(join(__dirname, 'Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')-const count = (needle: string | RegExp): number =>- typeof needle === 'string' ? src.split(needle).length - 1 : (src.match(new RegExp(needle, 'g')) ?? []).length-/** The source of one `const name = useCallback(…)` up to the next top-level-ish `const`. */-function callback(name: string): string {- const at = src.indexOf(`const ${name} = useCallback(`)- expect(at, name).toBeGreaterThan(-1)- const end = src.indexOf('\n const ', at + 10)- return src.slice(at, end === -1 ? undefined : end)-}--describe('Canvas live-link wiring', () => {- it('starts the watch-link sync exactly once, in a mount-only effect', () => {- expect(count('startWatchLinkSync(')).toBe(1)- 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)- expect(src).toContain('show: setLiveLinkDialog')- expect(count('requireProOr')).toBe(2) // the import, and `requirePro: requireProOr` in the opener- expect(callback('openLiveLinkFor')).toMatch(/openLiveLink\(\s*\{\s*facts: liveLinkFacts,\s*requirePro: requireProOr/)- })-- it('judges availability by the NODE\'s project session, and the dialog\'s surface the same way', () => {- expect(callback('liveLinkFacts')).toContain('source: sessionForProject(projectId).source')- expect(callback('liveLinkFacts')).toContain('serverEdition: isBrowserRuntime()')- expect(src).toMatch(/sessionForProject\(liveLinkDialog\.projectId\)\.source === 'relay'/)- })-- it('R47: the dialog gets a prepare that saves the canvas on screen, never over a conflict', () => {- const prep = callback('liveLinkPrepareFor')- expect(prep).toContain('liveLinkPrepare({')- expect(prep).toContain('conflict: !!conflictRef.current')- expect(prep).toContain('save: persist')- expect(prep).toMatch(/dirtyRef\.current &&\s*nodesRef\.current\.some\(\(n\) => n\.id === target\.nodeId\)/)- expect(src).toContain('prepare={liveLinkPrepareFor(liveLinkDialog)}')- })-- it("R63 and the Control warning: where the NODE runs — its own SSH binding, then its project's", () => {- // One decision (lib/liveLinkEntry, behaviour-tested there) gives the dialog both facts: a node- // attached to an SSH host in a LOCAL project, or a standalone ssh node, is not "this machine".- expect(src).toContain('{...liveLinkRemoteFor(liveLinkDialog)}')- const remote = callback('liveLinkRemoteFor')- expect(remote).toContain('liveLinkRemoteFacts({')- expect(remote).toContain('live: nodesRef.current,')- expect(remote).toContain('stored: project?.nodes,')- expect(remote).toContain('projectSsh: project?.ssh?.server')- expect(src).not.toContain('remoteNode={!!useProjects.getState().getProject(liveLinkDialog.projectId)?.ssh}')- // …and reads THIS machine's session protection from the local core, never a relay peer's.- expect(src).toContain('readPersistence={readLocalPersistence}')- expect(callback('readLocalPersistence')).toContain('localSession.api.pty.tmuxStatus()')- })-- it('R43: no Upgrade button from the dialog on the Server Edition', () => {- expect(src).toContain("onUpgrade={isBrowserRuntime() ? undefined : () => void useEntitlement.getState().upgrade('pro')}")- })-- it('R48: the palette\'s Stop all goes through the confirm; revoke-all runs nowhere else', () => {- expect(count('watchLink.revokeAll(')).toBe(1)- const confirm = callback('confirmStopAllLiveLinks')- expect(confirm).toMatch(/setConfirm\(\s*stopAllConfirm\(\{/)- expect(confirm).toContain('window.nodeTerminal.watchLink.revokeAll()')- expect(src).toContain('confirmStopAll: confirmStopAllLiveLinks')- })-- it('R62: what Stop all reached is always said, and it is offered to a Pro owner with no link here', () => {- const confirm = callback('confirmStopAllLiveLinks')- expect(confirm).toMatch(/stopAllLiveLinks\(\(\) => window\.nodeTerminal\.watchLink\.revokeAll\(\)\)\.then\(\(r\) =>\s*setNotice\(\{ kind: r\.ok \? 'info' : 'error', text: r\.text \}\)/)- const cmds = src.slice(src.indexOf('...liveLinkCommands({'))- expect(cmds.slice(0, 400)).toContain('entitled: useEntitlement.getState().isPremium,')- expect(cmds.slice(0, 400)).toContain('serverEdition: isBrowserRuntime(),')- })-- it("D2/M1: the row is composed by the lib with the facts FUNCTION (the node's project's facts)", () => {- const items = callback('liveLinkMenuItems')- expect(items).toContain('liveLinkMenuItemsFor({')- expect(items).toContain('facts: liveLinkFacts,')- expect(items).toContain('projectId,')- })-- it('one row builder, declared before the node action context and listed in its deps (H15)', () => {- const builder = src.indexOf('const liveLinkMenuItems = useCallback(')- const ctx = src.indexOf('const liveNodeActionCtx = useCallback(')- expect(builder).toBeGreaterThan(-1)- expect(builder).toBeLessThan(ctx)- const body = src.slice(ctx, src.indexOf('const selectionItems = useCallback(', ctx))- expect(body).toContain('liveLinkMenuItems: (nodeId) => liveLinkMenuItems(nodeId),')- expect(body).toMatch(/\n {6}liveLinkMenuItems,\n/)- // After "Refresh terminal", single terminal only — in the shared builder now.- const rows = readFileSync(join(__dirname, '../lib/nodeActionItems.tsx'), 'utf8').replace(/\r\n/g, '\n')- const row = "{ id: 'live-link', items: anyTerminal && ids.length === 1 ? ctx.liveLinkMenuItems(ids[0]) : [] }"- expect(rows.indexOf(row)).toBeGreaterThan(rows.indexOf("label: 'Refresh terminal'"))- })-- it('R49: every surface gets the row — non-active sidebar projects, both boards', () => {- const row = src.slice(src.indexOf('const onRowContextMenu = useCallback('))- expect(row.slice(0, row.indexOf('\n // Stream live subagent'))).toContain('...liveLinkMenuItems(id, projectId),')- // Both boards take the node rows from the builder, built for the CARD's project.- const ctx = src.slice(src.indexOf('const nodeActionCtxFor = useCallback('))- expect(ctx.slice(0, ctx.indexOf('\n const boardNodeActionItems'))).toContain(- 'const liveLink = (nodeId: string): MenuItem[] => liveLinkMenuItems(nodeId, projectId)'- )- expect(src).toContain('nodeActionItems={activeBoardNodeActionItems}')- expect(src).toMatch(/<GlobalKanbanView[\s\S]{0,200}nodeActionItems=\{boardNodeActionItems\}/)- })-- it('the card modal\'s action reaches the opener with its project', () => {- expect(src).toContain("window.addEventListener('nodeterm:live-link', on)")- expect(src).toMatch(/openLiveLinkFor\(\{ nodeId: d\.nodeId, title, projectId: d\.projectId \}\)/)- })-- // ── The Live chat drawer (Task 8) ──- it('the drawer is lazy-loaded like the Explorer and mounted only while open', () => {- const lazyImport = src.slice(0, src.indexOf("} from '../components/lazyPanels'"))- expect(lazyImport.slice(lazyImport.lastIndexOf('import {'))).toContain('LiveChatDrawer')- expect(src).toMatch(/\{liveChatShown\(liveChat, liveLinkCount\) && \(\s*<LiveChatDrawer/)- })-- it('a pinned drawer is rendered only while a link is live (ruling, concern 3): Canvas reads the COUNT', () => {- // A primitive selector: a push about one link's viewers does not re-render the canvas.- expect(src).toContain('const liveLinkCount = useWatchLinks((s) => s.links.length)')- // `beside` follows the drawer actually on screen, not just the pin.- const mount = src.slice(src.indexOf('<LiveChatDrawer'))- expect(mount.slice(0, mount.indexOf('/>'))).toContain('beside={liveChat.pinned && explorerOpen && explorer.pinned && !liveChatRaised}')- })-- it('raised only over a card modal on an open board, and never over Settings (hardening 3/4)', () => {- // Settings (z 55) stays on top: the drawer is not lifted to 57 while it is open. Raised, the- // drawer is not docked beside the Explorer either — the Explorer sits under the card modal.- expect(src).toContain('const liveChatRaised = cardModalOpen && kanbanOpen && !settingsOpen')- })-- it('raised while a card modal is open, beside only when BOTH drawers are pinned', () => {- const mount = src.slice(src.indexOf('<LiveChatDrawer'))- const props = mount.slice(0, mount.indexOf('/>'))- expect(props).toContain('linkId={liveChat.linkId}')- expect(props).toContain('pinned={liveChat.pinned}')- expect(props).toContain('raised={liveChatRaised}')- expect(props).toContain('beside={liveChat.pinned && explorerOpen && explorer.pinned && !liveChatRaised}')- expect(props).toContain('onGoToNode={goToLiveChatNode}')- // The card modal's open state is published where every board reports it.- expect(callback('setKanbanModalNode')).toContain('setCardModalOpen(id !== null)')- })-- it('the pin is persisted by the toggle; Go to terminal travels (closing a modal drawer first)', () => {- expect(callback('toggleLiveChatPin')).toContain('writeLiveChatPinned(next.pinned)')- const go = callback('goToLiveChatNode')- expect(go).toContain("if (!liveChatRef.current.pinned) setLiveChat((s) => nextLiveChat(s, { kind: 'close' }))")- expect(go).toContain('travelToNode(nodeId)')- expect(callback('pickLiveChatLink')).toContain('writeLiveChatLink(linkId)')- })-- it('the palette opens it; nothing about chat raises an OS notification', () => {- const cmds = src.slice(src.indexOf('...liveLinkCommands({'))- expect(cmds.slice(0, 600)).toContain("openChat: () => setLiveChat((s) => nextLiveChat(s, { kind: 'open' })),")- const drawerSrc = readFileSync(join(__dirname, '../components/LiveChatDrawer.tsx'), 'utf8').replace(/\r\n/g, '\n')- expect(drawerSrc).not.toMatch(/notify\(/)- })-})diff --git a/src/renderer/canvas/node-action-ctx-for.source.test.ts b/src/renderer/canvas/node-action-ctx-for.source.test.tsindex 3280751b7..221b3d2f7 100644--- a/src/renderer/canvas/node-action-ctx-for.source.test.ts+++ b/src/renderer/canvas/node-action-ctx-for.source.test.ts@@ -28,7 +28,6 @@ describe('Canvas nodeActionCtxFor', () => {expect(live).toContain('...liveNodeActionCtx()')expect(live).toContain('setNodesColor: writes.setColor')expect(live).toContain('pickNodeIcon: writes.pickIcon')- expect(live).toContain('liveLinkMenuItems: liveLink')})it('every other project gets the stored copy, its own session source and its own router', () => {diff --git a/src/renderer/components/AnnouncementPopup.test.tsx b/src/renderer/components/AnnouncementPopup.test.tsxindex 3b9990bcf..6e6ebaca7 100644--- a/src/renderer/components/AnnouncementPopup.test.tsx+++ b/src/renderer/components/AnnouncementPopup.test.tsx@@ -7,7 +7,6 @@ import { AnnouncementPopup } from './AnnouncementPopup'import { popDialog, pushDialog, resetDialogStack } from './dialog-stack'import { useEntitlement } from '../state/entitlement'import { useSettings } from '../state/settings'-import { useUpgradeGate } from '../state/upgradeGate'import { KEY_QUIET_MS, PENDING_RECHECK_MS, loadSeenPopups } from '../lib/announcementPopup'// The real store subscribes to the license bridge when it is created; the popup reads the bits and@@ -71,7 +70,6 @@ afterEach(async () => {vi.useRealTimers()useEntitlement.setState({ isPremium: false, known: true, upgrade: async () => {} })useSettings.setState({ hydrated: false })- useUpgradeGate.setState({ open: false })localStorage.clear()vi.restoreAllMocks()})@@ -130,16 +128,6 @@ it('waits while Canvas reports a surface of its own open', async () => {expect(dialog()?.textContent).toContain('Title a')})-it('waits while the upgrade dialog is open', async () => {- useUpgradeGate.setState({ open: true })- setFeed([pop('a')])- await mount()- await act(async () => vi.advanceTimersByTime(10_000))- expect(dialog()).toBeNull()- await act(async () => useUpgradeGate.setState({ open: false }))- expect(dialog()?.textContent).toContain('Title a')-})-// First launch decides the setup tour from settings; a popup that beat it would sit on the tour.it('waits for settings to load', async () => {useSettings.setState({ hydrated: false })diff --git a/src/renderer/components/AnnouncementPopup.tsx b/src/renderer/components/AnnouncementPopup.tsxindex fbfedca36..6574c6b52 100644--- a/src/renderer/components/AnnouncementPopup.tsx+++ b/src/renderer/components/AnnouncementPopup.tsx@@ -3,7 +3,6 @@ import { createPortal } from 'react-dom'import type { PopupAnnouncement } from '@shared/types'import { useEntitlement } from '../state/entitlement'import { useSettings } from '../state/settings'-import { useUpgradeGate } from '../state/upgradeGate'import {PENDING_RECHECK_MS,loadSeenPopups,@@ -44,13 +43,12 @@ async function readyPopup(items: PopupAnnouncement[], isPremium: boolean): Promi* reach a Pro user on the default `isPremium: false`).** `blocked`: Canvas's own surfaces that are not on the dialog stack (the setup tour, Settings, the- * command palette, the shortcuts panel, …). The upgrade gate is read here.+ * command palette, the shortcuts panel, …).*/export function AnnouncementPopup({ blocked }: { blocked: boolean }): React.JSX.Element | null {const isPremium = useEntitlement((s) => s.isPremium)const licenseKnown = useEntitlement((s) => s.known)const settingsKnown = useSettings((s) => s.hydrated)- const upgradeOpen = useUpgradeGate((s) => s.open)const [pending, setPending] = useState<ReadyPopup | null>(null)const [shown, setShown] = useState<ReadyPopup | null>(null)const lastKeyAt = useRef(0)@@ -101,7 +99,7 @@ export function AnnouncementPopup({ blocked }: { blocked: boolean }): React.JSX.return () => window.removeEventListener('keydown', onKey, true)}, [])- const held = blocked || upgradeOpen || !settingsKnown+ const held = blocked || !settingsKnownuseEffect(() => {if (!pending || shown) returnconst tryShow = (): boolean => {diff --git a/src/renderer/components/LiveChatDrawer.test.tsx b/src/renderer/components/LiveChatDrawer.test.tsxdeleted file mode 100644index d4cb786ab..000000000--- a/src/renderer/components/LiveChatDrawer.test.tsx+++ /dev/null@@ -1,587 +0,0 @@-// @vitest-environment jsdom-import { act } from 'react'-import { createRoot, type Root } from 'react-dom/client'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { WatchChatMessage, WatchLinkView } from '@shared/watch-link-types'-import { CHAT_TEXT_MAX } from '@shared/watch-link/protocol'-import { LiveChatDrawer } from './LiveChatDrawer'-import { liveChipSig, useWatchLinks } from '../state/watchLinks'-import { openDialogCount, popDialog, pushDialog, resetDialogStack } from './dialog-stack'-import {- CHAT_NOT_SENT_MESSAGE,- CONTROL_CHANGE_UNSAVED_MESSAGE,- CONTROL_LOCKED_TEXT,- KICK_CONTROLLER_NOTE,- KICK_NOT_DONE_MESSAGE,- KICK_NOTE-} from '../lib/liveLink'-import { chatNameColor } from '../lib/liveChatLook'--// Spied, with the real implementation: how often the message list was RENDERED (one call per line).-vi.mock('../lib/liveChatLook', async (importOriginal) => {- const real = await importOriginal<typeof import('../lib/liveChatLook')>()- return { ...real, chatNameColor: vi.fn(real.chatNameColor) }-})--;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true--const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({- linkId: 'L',- nodeId: 'n1',- role: 'commenter',- label: 'Ada',- title: 'build',- createdAt: 0,- expiresAt: null,- url: 'https://nodeterm.dev/s/L#1.secret',- status: 'live',- viewers: [],- control: null,- ...over-})-const msg = (id: string, over: Partial<WatchChatMessage> = {}): WatchChatMessage => ({- id,- name: 'Bob',- text: 'hello',- at: Number(id),- from: 'viewer',- ...over-})--const api = {- revoke: vi.fn(async (_id: string) => {}),- kick: vi.fn(async (_l: string, _v: string) => true),- sendChat: vi.fn(async (_l: string, t: string): Promise<WatchChatMessage | null> => ({- id: 's',- name: 'Ada',- text: t,- at: 0,- from: 'sharer'- })),- chatHistory: vi.fn(async (_l: string): Promise<WatchChatMessage[]> => []),- setControl: vi.fn(async (_l: string, _on: boolean): Promise<boolean | 'unsaved'> => true),- setPassword: vi.fn(async (_l: string, _pw: string): Promise<boolean | 'unsaved'> => true),- allowControl: vi.fn(async (_l: string) => true)-}--let host: HTMLDivElement-let root: Root-beforeEach(() => {- resetDialogStack()- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })- for (const f of Object.values(api)) f.mockClear()- api.kick.mockImplementation(async () => true)- api.sendChat.mockImplementation(async (_l: string, t: string) => ({ id: 's', name: 'Ada', text: t, at: 0, from: 'sharer' }))- api.setPassword.mockImplementation(async () => true)- // A focused, visible window: someone can see the drawer (the read-state rule, useLinkThread).- vi.spyOn(document, 'hasFocus').mockReturnValue(true)- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { watchLink: api, clipboard: { writeText: vi.fn() } }- host = document.createElement('div')- document.body.append(host)- root = createRoot(host)-})-afterEach(() => {- act(() => root.unmount())- document.body.innerHTML = ''- resetDialogStack()- vi.restoreAllMocks()- delete (document as { visibilityState?: unknown }).visibilityState-})--const noop = (): void => {}-const props = (over: Partial<Parameters<typeof LiveChatDrawer>[0]> = {}): Parameters<typeof LiveChatDrawer>[0] => ({- linkId: 'L',- pinned: false,- raised: false,- onPickLink: noop,- onClose: noop,- onTogglePin: noop,- onGoToNode: noop,- ...over-})-const render = (p: Parameters<typeof LiveChatDrawer>[0]): void => act(() => root.render(<LiveChatDrawer {...p} />))-const setLinks = (links: WatchLinkView[]): void => act(() => useWatchLinks.getState().setLinks(links))-const addChat = (linkId: string, m: WatchChatMessage): void => act(() => useWatchLinks.getState().addChat(linkId, m))-const drawer = (): HTMLElement => document.querySelector<HTMLElement>('.live-chat')!-const overlay = (): HTMLElement => document.querySelector<HTMLElement>('.drawer-overlay')!-const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))-const button = (label: string): HTMLButtonElement =>- [...drawer().querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === label)!-const flush = (): Promise<void> => act(async () => {})-const type = (input: HTMLInputElement, value: string): void =>- act(() => {- const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!- set.call(input, value)- input.dispatchEvent(new Event('input', { bubbles: true }))- })-/** A key with nothing focused: its target is the body. */-const keydown = (key: string): void =>- act(() => void document.body.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })))--describe('LiveChatDrawer', () => {- it('is the Explorer drawer: titled Live chat, a pin button with aria-pressed, and a close', () => {- setLinks([link()])- const onClose = vi.fn()- const onTogglePin = vi.fn()- render(props({ onClose, onTogglePin }))- expect(drawer().classList.contains('drawer')).toBe(true)- expect(drawer().querySelector('.drawer__head h2')?.textContent).toBe('Live chat')- const pin = drawer().querySelector<HTMLButtonElement>('button[aria-label="Pin"]')!- expect(pin.getAttribute('aria-pressed')).toBe('false')- click(pin)- expect(onTogglePin).toHaveBeenCalledTimes(1)- click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('unpinned: a modal with a scrim that closes it; a click inside does not', () => {- setLinks([link()])- const onClose = vi.fn()- render(props({ onClose }))- expect(overlay().className).toBe('drawer-overlay live-chat-overlay')- expect(drawer().classList.contains('drawer--pinned')).toBe(false)- click(drawer())- expect(onClose).not.toHaveBeenCalled()- click(overlay())- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('pinned: docked (drawer--pinned, overlay --pinned), no scrim close, the pin pressed', () => {- setLinks([link()])- const onClose = vi.fn()- render(props({ onClose, pinned: true }))- expect(overlay().classList.contains('drawer-overlay--pinned')).toBe(true)- expect(drawer().classList.contains('drawer--pinned')).toBe(true)- expect(drawer().querySelector('button[aria-label="Unpin"]')?.getAttribute('aria-pressed')).toBe('true')- click(overlay())- expect(onClose).not.toHaveBeenCalled()- })-- it('raised (a card modal is open) and beside (the pinned Explorer is open) are class names on the overlay', () => {- setLinks([link()])- render(props({ raised: true }))- expect(overlay().classList.contains('drawer-overlay--raised')).toBe(true)- expect(overlay().classList.contains('drawer-overlay--beside')).toBe(false)- render(props({ raised: true, pinned: true, beside: true }))- expect(overlay().classList.contains('drawer-overlay--raised')).toBe(true)- expect(overlay().classList.contains('drawer-overlay--pinned')).toBe(true)- expect(overlay().classList.contains('drawer-overlay--beside')).toBe(true)- // `beside` is a docked arrangement: an unpinned modal is never moved for the Explorer.- render(props({ pinned: false, beside: true }))- expect(overlay().classList.contains('drawer-overlay--beside')).toBe(false)- })-- it('shows "No live links." when none is live, and still closes', () => {- const onClose = vi.fn()- render(props({ onClose, linkId: null }))- expect(drawer().textContent).toContain('No live links.')- click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('messages: time, name, text, a Sharer badge on the owner\'s lines; names are TEXT, coloured like the viewer page', () => {- setLinks([link()])- useWatchLinks.getState().setChat('L', [- msg('1', { name: '<b>Mallory</b>', text: '<i>hi</i>' }),- msg('2', { name: 'Ada', text: 'welcome', from: 'sharer' }),- msg('3', { name: 'Eve', text: 'x' })- ])- render(props())- const lines = [...drawer().querySelectorAll<HTMLElement>('.live-chat__msg')]- expect(lines).toHaveLength(3)- // A name is a claim, shown as written — never parsed as markup.- expect(lines[0].querySelector('b')).toBeNull()- expect(lines[0].querySelector('i')).toBeNull()- expect(lines[0].querySelector('.live-chat__name')?.textContent).toBe('<b>Mallory</b>')- expect(lines[0].querySelector('.live-chat__text')?.textContent).toBe('<i>hi</i>')- expect(lines[0].querySelector('.live-chat__badge')).toBeNull()- expect(lines[0].querySelector<HTMLElement>('.live-chat__name')!.style.getPropertyValue('--live-name')).toBe(chatNameColor('<b>Mallory</b>'))- expect(lines[0].querySelector('time')).not.toBeNull()- // The owner's own line: the badge, and no viewer colour (the sharer's look is the HOST's word).- expect(lines[1].classList.contains('live-chat__msg--sharer')).toBe(true)- expect(lines[1].querySelector('.live-chat__badge')?.textContent).toBe('Sharer')- expect(lines[1].querySelector<HTMLElement>('.live-chat__name')!.style.getPropertyValue('--live-name')).toBe('')- // Bidi controls never reach the screen.- expect(lines[2].querySelector('.live-chat__name')?.textContent).toBe('Eve')- })-- it('stays at the newest message; scrolled up, a "N new messages ↓" pill appears and takes you down', () => {- setLinks([link()])- useWatchLinks.getState().setChat('L', [msg('1')])- render(props())- const list = drawer().querySelector<HTMLElement>('.live-chat__list')!- // jsdom has no layout: give the list one, scrolled up.- Object.defineProperty(list, 'scrollHeight', { configurable: true, value: 1000 })- Object.defineProperty(list, 'clientHeight', { configurable: true, value: 200 })- list.scrollTop = 100- act(() => void list.dispatchEvent(new Event('scroll')))- expect(drawer().querySelector('.live-chat__more')).toBeNull()- addChat('L', msg('2'))- addChat('L', msg('3'))- const pill = drawer().querySelector<HTMLButtonElement>('.live-chat__more')!- expect(pill.textContent).toBe('2 new messages ↓')- expect(list.scrollTop).toBe(100)- click(pill)- expect(list.scrollTop).toBe(1000)- expect(drawer().querySelector('.live-chat__more')).toBeNull()- })-- it('at the bottom, a new message keeps it at the bottom and raises no pill', () => {- setLinks([link()])- render(props())- const list = drawer().querySelector<HTMLElement>('.live-chat__list')!- Object.defineProperty(list, 'scrollHeight', { configurable: true, value: 1000 })- Object.defineProperty(list, 'clientHeight', { configurable: true, value: 200 })- list.scrollTop = 800- act(() => void list.dispatchEvent(new Event('scroll')))- addChat('L', msg('5'))- expect(drawer().querySelector('.live-chat__more')).toBeNull()- expect(list.scrollTop).toBe(1000)- })-- it('the composer posts as the sharer with api.sendChat, capped at CHAT_TEXT_MAX; a refused send says so', async () => {- setLinks([link()])- render(props())- const input = drawer().querySelector<HTMLInputElement>('.live-chat__reply input')!- expect(input.maxLength).toBe(CHAT_TEXT_MAX)- type(input, ' hello there ')- act(() => void drawer().querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })))- await flush()- expect(api.sendChat).toHaveBeenCalledWith('L', 'hello there')- expect(input.value).toBe('')- api.sendChat.mockImplementation(async () => null)- type(input, 'again')- act(() => void drawer().querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })))- await flush()- expect(drawer().querySelector('[role="alert"]')?.textContent).toBe(CHAT_NOT_SENT_MESSAGE)- expect(input.value).toBe('again')- })-- it('a link picker only when more than one link is live: "{title} · {role}", and a pick is reported', () => {- setLinks([link()])- const onPickLink = vi.fn()- render(props({ onPickLink }))- expect(drawer().querySelector('select')).toBeNull()- setLinks([- link(),- link({ linkId: 'M', nodeId: 'n2', title: 'api-server', role: 'controller', control: { enabled: true, locked: false }, createdAt: 5 }),- link({ linkId: 'V', nodeId: 'n3', title: 'logs', role: 'viewer', createdAt: 1 })- ])- const select = drawer().querySelector<HTMLSelectElement>('select')!- expect([...select.options].map((o) => o.textContent)).toEqual(['build · Commenter', 'api-server · Control', 'logs · Viewer'])- expect(select.value).toBe('L')- act(() => {- select.value = 'M'- select.dispatchEvent(new Event('change', { bubbles: true }))- })- expect(onPickLink).toHaveBeenCalledWith('M')- })-- it('two links that would read the same are told apart in the picker (label, then start time)', () => {- setLinks([- link({ linkId: 'A', label: 'Ada', createdAt: Date.UTC(2026, 9, 3, 12, 5) }),- link({ linkId: 'B', label: 'Ada', createdAt: Date.UTC(2026, 9, 3, 13, 40) }),- link({ linkId: 'C', label: 'Team', createdAt: 9 })- ])- render(props({ linkId: 'A' }))- const texts = [...drawer().querySelectorAll('option')].map((o) => o.textContent)- expect(new Set(texts).size).toBe(3)- expect(texts[2]).toBe('build · Commenter · shown as Team')- expect(texts[0]).toMatch(/^build · Commenter · shown as Ada · since /)- })-- it('marks itself as the Live chat drawer (the card modal leaves Escape typed inside it alone)', () => {- setLinks([link()])- render(props())- expect(drawer().hasAttribute('data-live-chat-drawer')).toBe(true)- })-- it('a link that is not live any more falls back to the most recent one', () => {- setLinks([link({ linkId: 'A', createdAt: 1, title: 'old' }), link({ linkId: 'B', createdAt: 9, title: 'new' })])- render(props({ linkId: 'gone' }))- expect(drawer().querySelector<HTMLSelectElement>('select')!.value).toBe('B')- })-- it('a Viewer link shows People only — no thread, no composer', () => {- setLinks([link({ role: 'viewer', viewers: [{ viewerId: 'v1', name: null, joinedAt: 1, waiting: false, controlling: false, typing: false }] })])- render(props())- expect(drawer().querySelector('.live-chat__list')).toBeNull()- expect(drawer().querySelector('.live-chat__reply')).toBeNull()- expect(drawer().querySelector('.live-chat__people')?.textContent).toContain('Viewer 1')- expect(api.chatHistory).not.toHaveBeenCalled()- })-- it('People: each viewer watching or able to type, a typing dot, and Kick', async () => {- setLinks([- link({- role: 'controller',- control: { enabled: true, locked: false },- viewers: [- { viewerId: 'v1', name: 'Mert', joinedAt: 1, waiting: false, controlling: true, typing: true },- { viewerId: 'v2', name: null, joinedAt: 2, waiting: false, controlling: false, typing: false }- ]- })- ])- render(props())- const rows = [...drawer().querySelectorAll<HTMLElement>('.live-chat__people li')]- expect(rows).toHaveLength(2)- expect(rows[0].textContent).toContain('Mert')- expect(rows[0].textContent).toContain('can type')- expect(rows[0].querySelector('.live-pop__typing')).not.toBeNull()- expect(rows[1].textContent).toContain('Viewer 2')- expect(rows[1].textContent).toContain('watching')- expect(rows[1].querySelector('.live-pop__typing')).toBeNull()- click(rows[1].querySelector('button')!)- await flush()- expect(api.kick).toHaveBeenCalledWith('L', 'v2')- api.kick.mockImplementation(async () => false)- click(rows[0].querySelector('button')!)- await flush()- expect(drawer().textContent).toContain(KICK_NOT_DONE_MESSAGE)- })-- it("a Control link: the popover's owner controls — Typing calls setControl, Allow again only while locked", async () => {- setLinks([link({ role: 'controller', control: { enabled: true, locked: true } })])- render(props())- const sw = drawer().querySelector<HTMLButtonElement>('[role="switch"]')!- click(sw)- await flush()- expect(api.setControl).toHaveBeenCalledWith('L', false)- expect(drawer().textContent).toContain(CONTROL_LOCKED_TEXT)- click(button('Allow control again'))- await flush()- expect(api.allowControl).toHaveBeenCalledWith('L')- expect(button('Change password…')).toBeTruthy()- })-- // Final review, Important 1: the drawer carries the same owner controls, so the same notice — and,- // since the drawer has no Stop of its own, the notice brings Stop sharing with it.- it("typing OFF answered 'unsaved': the drawer says it applied but will undo at a restart, with Stop sharing at hand", async () => {- setLinks([link({ role: 'controller', control: { enabled: true, locked: false } })])- render(props())- api.setControl.mockImplementationOnce(async () => 'unsaved')- click(drawer().querySelector<HTMLButtonElement>('[role="switch"]')!)- await flush()- const notice = drawer().querySelector<HTMLElement>('.live-pop__unsaved')!- expect(notice.getAttribute('role')).toBe('alert')- expect(notice.textContent).toContain(CONTROL_CHANGE_UNSAVED_MESSAGE)- click([...notice.querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === 'Stop sharing')!)- await flush()- expect(api.revoke).toHaveBeenCalledWith('L')- })-- it('the Kick of a viewer who is controlling says they can unlock again', () => {- setLinks([- link({- role: 'controller',- control: { enabled: true, locked: false },- viewers: [- { viewerId: 'v1', name: 'Mert', joinedAt: 1, waiting: false, controlling: true, typing: false },- { viewerId: 'v2', name: null, joinedAt: 2, waiting: false, controlling: false, typing: false }- ]- })- ])- render(props())- const kicks = [...drawer().querySelectorAll<HTMLButtonElement>('.live-chat__people li button')]- expect(kicks[0].title).toBe(`${KICK_NOTE} ${KICK_CONTROLLER_NOTE}`)- expect(kicks[1].title).toBe(KICK_NOTE)- })-- it('mounting on a link reads it: markRead, so the chip\'s unread count clears; what lands while shown is read too', async () => {- setLinks([link()])- addChat('L', msg('1'))- addChat('L', msg('2'))- expect(useWatchLinks.getState().unread.L).toBe(2)- expect(liveChipSig(useWatchLinks.getState(), 'n1').endsWith('\u00012')).toBe(true)- render(props())- expect(useWatchLinks.getState().unread.L).toBe(0)- expect(liveChipSig(useWatchLinks.getState(), 'n1').endsWith('\u00010')).toBe(true)- addChat('L', msg('3'))- expect(useWatchLinks.getState().unread.L).toBe(0)- // Core's history is asked once for the thread on screen.- await flush()- expect(api.chatHistory).toHaveBeenCalledWith('L')- // Closed: a new message counts again.- act(() => root.render(<></>))- addChat('L', msg('4'))- expect(useWatchLinks.getState().unread.L).toBe(1)- })-- it('Go to terminal hands the link\'s node to the caller', () => {- setLinks([link({ nodeId: 'node-7' })])- const onGoToNode = vi.fn()- render(props({ onGoToNode }))- click(button('Go to terminal'))- expect(onGoToNode).toHaveBeenCalledWith('node-7')- })-- it('Escape closes the unpinned drawer only while it is the top dialog; pinned, Escape does nothing', () => {- setLinks([link()])- const onClose = vi.fn()- render(props({ onClose }))- pushDialog('other')- keydown('Escape')- expect(onClose).not.toHaveBeenCalled()- popDialog('other')- keydown('Escape')- expect(onClose).toHaveBeenCalledTimes(1)- onClose.mockClear()- render(props({ onClose, pinned: true }))- keydown('Escape')- expect(onClose).not.toHaveBeenCalled()- })-- it('pinned, it is not a modal: it takes no place in the dialog stack (the board keeps its keys)', () => {- setLinks([link()])- render(props({ pinned: true }))- expect(openDialogCount()).toBe(0)- render(props({ pinned: false }))- expect(openDialogCount()).toBe(1)- render(props({ pinned: true }))- expect(openDialogCount()).toBe(0)- })-- it('a new password on its way is not lost: × and Escape wait while the save is in flight', async () => {- setLinks([link({ role: 'controller', control: { enabled: true, locked: false } })])- let answer: (ok: boolean) => void = () => {}- api.setPassword.mockImplementation(() => new Promise<boolean>((r) => (answer = r)))- const onClose = vi.fn()- render(props({ onClose }))- click(button('Change password…'))- click(button('Generate'))- click(button('Save'))- await flush()- expect(button('Saving…')).toBeTruthy()- click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)- keydown('Escape')- click(overlay())- expect(onClose).not.toHaveBeenCalled()- await act(async () => answer(true))- expect(button('Copy password')).toBeTruthy()- click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)- expect(onClose).toHaveBeenCalledTimes(1)- })-- // ── Hardening round ──- it('Escape typed OUTSIDE the drawer (the palette, Settings — not on the dialog stack) is not the drawer\'s', () => {- setLinks([link()])- const onClose = vi.fn()- render(props({ onClose }))- const palette = document.createElement('input')- document.body.append(palette)- palette.focus()- act(() => void palette.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))- expect(onClose).not.toHaveBeenCalled()- // …and the palette keeps the keyboard (no focus restore pulled out from under it).- expect(document.activeElement).toBe(palette)- // On the body (nothing focused) with the drawer as the top dialog: it is the drawer's.- keydown('Escape')- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('Escape inside the drawer closes it when it is the top dialog', () => {- setLinks([link()])- const onClose = vi.fn()- render(props({ onClose }))- const input = drawer().querySelector<HTMLInputElement>('.live-chat__reply input')!- input.focus()- act(() => void input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))- expect(onClose).toHaveBeenCalledTimes(1)- })-- const controlLinks = (): WatchLinkView[] => [- link({ role: 'controller', control: { enabled: true, locked: false } }),- link({ linkId: 'M', nodeId: 'n2', title: 'other', createdAt: 5 })- ]- const startSave = async (): Promise<(ok: boolean) => void> => {- let answer: (ok: boolean) => void = () => {}- api.setPassword.mockImplementation(() => new Promise<boolean>((r) => (answer = r)))- click(button('Change password…'))- click(button('Generate'))- click(button('Save'))- await flush()- expect(button('Saving…')).toBeTruthy()- return (ok) => answer(ok)- }- const shown = (): string => drawer().querySelector<HTMLSelectElement>('select')!.value-- it('a password save in flight keeps the drawer on its link: an open on another link waits (refused save → then it moves)', async () => {- setLinks(controlLinks())- const onPickLink = vi.fn()- render(props({ linkId: 'L', onPickLink }))- const answer = await startSave()- // Canvas's `nodeterm:live-chat` listener opens the drawer on M meanwhile.- render(props({ linkId: 'M', onPickLink }))- expect(shown()).toBe('L')- expect(button('Saving…')).toBeTruthy()- expect(drawer().querySelector('select')!.disabled).toBe(true)- await act(async () => answer(false))- expect(shown()).toBe('M')- // The drawer followed Canvas's link; it never asked Canvas to change it back.- expect(onPickLink).not.toHaveBeenCalled()- })-- it('a password that took stays on screen (its plaintext exists nowhere else) until Done, then the drawer moves', async () => {- setLinks(controlLinks())- render(props({ linkId: 'L' }))- const answer = await startSave()- render(props({ linkId: 'M' }))- await act(async () => answer(true))- expect(shown()).toBe('L')- expect(button('Copy password')).toBeTruthy()- click(button('Done'))- expect(shown()).toBe('M')- })-- it('when the remembered link is gone, the drawer adopts what it shows (Canvas state and the pick agree)', () => {- setLinks([link({ linkId: 'A', createdAt: 1 }), link({ linkId: 'B', createdAt: 9 })])- const onPickLink = vi.fn()- render(props({ linkId: 'gone', onPickLink }))- expect(onPickLink).toHaveBeenCalledWith('B')- onPickLink.mockClear()- render(props({ linkId: 'B', onPickLink }))- expect(onPickLink).not.toHaveBeenCalled()- })-- it('a message counts as read only while someone can see it: hidden or unfocused, the chip\'s count grows', () => {- setLinks([link()])- addChat('L', msg('1'))- vi.mocked(document.hasFocus).mockReturnValue(false)- render(props({ pinned: true }))- expect(useWatchLinks.getState().unread.L).toBe(1)- addChat('L', msg('2'))- expect(useWatchLinks.getState().unread.L).toBe(2)- // The window gains focus: what is on screen is read.- vi.mocked(document.hasFocus).mockReturnValue(true)- act(() => void window.dispatchEvent(new Event('focus')))- expect(useWatchLinks.getState().unread.L).toBe(0)- addChat('L', msg('3'))- expect(useWatchLinks.getState().unread.L).toBe(0)- // Blurred: it counts again.- vi.mocked(document.hasFocus).mockReturnValue(false)- act(() => void window.dispatchEvent(new Event('blur')))- addChat('L', msg('4'))- expect(useWatchLinks.getState().unread.L).toBe(1)- // Focused but HIDDEN (minimized, another Space): still counts.- vi.mocked(document.hasFocus).mockReturnValue(true)- act(() => void window.dispatchEvent(new Event('focus')))- expect(useWatchLinks.getState().unread.L).toBe(0)- Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' })- act(() => void document.dispatchEvent(new Event('visibilitychange')))- addChat('L', msg('5'))- expect(useWatchLinks.getState().unread.L).toBe(1)- })-- it('a viewer typing push does not re-render the message list', () => {- setLinks([link({ viewers: [{ viewerId: 'v1', name: 'Mert', joinedAt: 1, waiting: false, controlling: false, typing: false }] })])- useWatchLinks.getState().setChat('L', [msg('1'), msg('2'), msg('3')])- render(props())- const color = vi.mocked(chatNameColor)- color.mockClear()- setLinks([link({ viewers: [{ viewerId: 'v1', name: 'Mert', joinedAt: 1, waiting: false, controlling: false, typing: true }] })])- expect(drawer().querySelector('.live-pop__typing')).not.toBeNull()- expect(color).not.toHaveBeenCalled()- addChat('L', msg('4'))- expect(color).toHaveBeenCalled()- })-})diff --git a/src/renderer/components/LiveChatDrawer.tsx b/src/renderer/components/LiveChatDrawer.tsxdeleted file mode 100644index f6ebe22fa..000000000--- a/src/renderer/components/LiveChatDrawer.tsx+++ /dev/null@@ -1,423 +0,0 @@-import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from 'react'-import { createPortal } from 'react-dom'-import type { WatchChatMessage, WatchLinkView } from '@shared/watch-link-types'-import { stripBidiControls } from '@shared/watch-link-types'-import { CHAT_TEXT_MAX } from '@shared/watch-link/protocol'-import { isTopDialog, nextDialogId, popDialog, pushDialog } from './dialog-stack'-import { ControlHold, ControlSection, hasChat, kickViewer, type ControlHoldKind } from './LiveLinkControls'-import { IconClose, IconPin } from './icons'-import { CHAT_NOT_SENT_MESSAGE, kickNote, ROLE_NAME, statusLine, viewerName, waitingViewers } from '../lib/liveLink'-import { chatClock, chatNameColor, nearBottom } from '../lib/liveChatLook'-import { newMessagesLabel } from '../lib/chatLabels'-import { chatLinkOptionLabels, inLiveChatDrawer, LIVE_CHAT_DRAWER_ATTR, pickChatLink } from '../lib/liveChatPin'-import { useLinkThread, useWatchLinks } from '../state/watchLinks'--const EMPTY_CHAT: WatchChatMessage[] = []--export interface LiveChatDrawerProps {- /** The link the owner picked last; the drawer shows it while it is live, else the most recent. */- linkId: string | null- /** Docked (no scrim, the canvas stays usable) — the Explorer's pin. */- pinned: boolean- /** A kanban card modal is open (z 55): sit above it, whatever the pin. */- raised: boolean- /** The pinned Explorer is open too: dock to its left. Only meaningful while this drawer is pinned. */- beside?: boolean- onPickLink(id: string): void- onClose(): void- onTogglePin(): void- onGoToNode(nodeId: string): void-}--/** "build" for the head: the node title as viewers see it, never empty. */-function linkTitle(l: Pick<WatchLinkView, 'title'>): string {- return stripBidiControls(l.title).trim() || 'Terminal'-}--/**- * The Live chat drawer (spec §4): follow and answer a live link's chat, and manage who can type —- * the Explorer drawer's shape and pin, on the right. A Commenter or Control link shows its thread in- * the viewer page's live-chat look (lib/liveChatLook) with a composer that posts as the sharer, plus- * People; a Viewer link has no chat, so People only.- *- * Every string someone else wrote — a name, a message, a title — is React TEXT, bidi-stripped. A- * name is a claim; the People list shows it as a label, the way the popover does. Nothing here ever- * raises an OS notification: chat raises the chip's unread count, and only `control-taken` notifies.- *- * Unpinned it is a modal in the dialog stack (Escape and the scrim close it while it is the top- * dialog); pinned it is docked chrome and takes no place in the stack, so the board and the card- * modal keep their keys.- */-export function LiveChatDrawer(p: LiveChatDrawerProps): React.JSX.Element {- const { pinned, raised, onClose, onPickLink } = p- const links = useWatchLinks((s) => s.links)-- // A new Control password holds the drawer (`ControlHold`) — its plaintext exists nowhere else once- // core takes it. `saves` counts the saves in flight: they keep the drawer from closing AND on its- // link. `pins` counts every hold (a save, or a new password on screen until Done): they keep the- // drawer on its link, whatever an Open chat for another link or the fallback says meanwhile. The- // counters are refs (read in handlers); the held link is state, because it decides what renders.- const saves = useRef(0)- const pins = useRef(0)- const [heldLink, setHeldLink] = useState<string | null>(null)- const wanted = pickChatLink(links, p.linkId)- const shownId = heldLink !== null && links.some((l) => l.linkId === heldLink) ? heldLink : wanted- const link = shownId === null ? null : (links.find((l) => l.linkId === shownId) ?? null)- const shownRef = useRef(shownId)- shownRef.current = shownId- const hold = useCallback((kind: ControlHoldKind = 'save'): (() => void) => {- if (kind === 'save') saves.current++- if (++pins.current === 1) setHeldLink(shownRef.current)- let released = false- return () => {- if (released) return- released = true- if (kind === 'save') saves.current--- if (--pins.current === 0) setHeldLink(null)- }- }, [])- // The remembered link is gone (or none was remembered): the drawer shows the most recent one, and- // ADOPTS it, so Canvas's state and the remembered pick say what is on screen. Never while held:- // there the difference is an open on another link waiting for the hold to end.- useEffect(() => {- if (heldLink !== null || shownId === null || shownId === p.linkId) return- onPickLink(shownId)- }, [heldLink, shownId, p.linkId, onPickLink])- /** Close unless something is held. Every close gesture of the owner comes here. */- const requestClose = useCallback((): void => {- if (saves.current > 0) return- onClose()- }, [onClose])-- // A modal only while unpinned: docked, it must not take the keyboard from the board or a dialog.- const dialogIdRef = useRef<string>()- if (!dialogIdRef.current) dialogIdRef.current = nextDialogId()- const dialogId = dialogIdRef.current- useEffect(() => {- if (pinned) return- pushDialog(dialogId)- return () => popDialog(dialogId)- }, [pinned, dialogId])- useEffect(() => {- if (pinned) return- const onKey = (e: KeyboardEvent): void => {- if (e.key !== 'Escape' || !isTopDialog(dialogId)) return- // Only an Escape that is the drawer's: typed inside it, or with nothing focused. The palette and- // Settings are not on the dialog stack — an Escape typed there is theirs, and closing the drawer- // underneath would also pull the keyboard out of them (the drawer gives focus back on close).- if (!inLiveChatDrawer(e.target) && e.target !== document.body) return- e.preventDefault()- e.stopPropagation()- requestClose()- }- // Capture phase: beat the canvas's own keydown listeners (and xterm) to the Escape.- window.addEventListener('keydown', onKey, true)- return () => window.removeEventListener('keydown', onKey, true)- }, [pinned, dialogId, requestClose])-- // Opened as a modal, keyboard users land in it (a body portal: Tab from the chip would never reach- // it) and go back where they were when it closes. Docked, it takes nothing.- const asideRef = useRef<HTMLElement>(null)- const pinnedAtMount = useRef(pinned)- useEffect(() => {- if (pinnedAtMount.current) return- const before = document.activeElement instanceof HTMLElement ? document.activeElement : null- asideRef.current?.focus({ preventScroll: true })- return () => {- if (before?.isConnected) before.focus({ preventScroll: true })- }- }, [])-- const overlayClass = [- 'drawer-overlay',- 'live-chat-overlay',- pinned && 'drawer-overlay--pinned',- pinned && p.beside && 'drawer-overlay--beside',- raised && 'drawer-overlay--raised'- ]- .filter(Boolean)- .join(' ')-- return createPortal(- <div- className={overlayClass}- // Pinned: no handler, and the overlay is pointer-events:none (styles.css) — both halves are- // what keep a docked drawer from stealing or dismissing on canvas clicks (the Explorer's rule).- onClick={pinned ? undefined : requestClose}- >- <aside- ref={asideRef}- className={pinned ? 'drawer drawer--pinned live-chat' : 'drawer live-chat'}- role={pinned ? undefined : 'dialog'}- aria-label="Live chat"- tabIndex={-1}- // The kanban card modal leaves an Escape typed in here alone (it may be the top dialog while- // this drawer is docked over it).- {...{ [LIVE_CHAT_DRAWER_ATTR]: '' }}- onClick={(e) => e.stopPropagation()}- >- <div className="drawer__head">- <h2>Live chat</h2>- <div className="ex-head-actions">- <button- type="button"- className={pinned ? 'is-on' : ''}- title={pinned ? 'Unpin' : 'Pin'}- aria-label={pinned ? 'Unpin' : 'Pin'}- aria-pressed={pinned}- onClick={p.onTogglePin}- >- <IconPin />- </button>- <button type="button" className="drawer__close" title="Close" aria-label="Close" onClick={requestClose}>- <IconClose />- </button>- </div>- </div>- {link === null ? (- <div className="drawer__body">- <p className="set-note">No live links.</p>- </div>- ) : (- <ControlHold.Provider value={hold}>- <div className="live-chat__body">- <div className="live-chat__link">- {links.length > 1 && (- <select- className="confirm__input live-chat__select"- aria-label="Live link"- value={link.linkId}- // Switching links unmounts the controls: not while a new password is on its way or- // on screen.- disabled={heldLink !== null}- title={heldLink !== null ? 'Finish the password change first.' : undefined}- onChange={(e) => {- if (pins.current > 0) return- onPickLink(e.target.value)- }}- >- {chatLinkOptionLabels(links).map((text, i) => (- <option key={links[i].linkId} value={links[i].linkId}>- {text}- </option>- ))}- </select>- )}- <div className="live-chat__linkhead">- <span>- <span className="live-pop__who">{linkTitle(link)}</span>{' '}- <span className="live-pop__muted">{ROLE_NAME[link.role]}</span>- </span>- <button- type="button"- className="live-chat__goto"- onClick={() => {- // A modal drawer gives way to the canvas — unless a new password is still on- // its way to being shown here.- if (!pinned && saves.current > 0) return- p.onGoToNode(link.nodeId)- }}- >- Go to terminal- </button>- </div>- <LinkStatus link={link} />- </div>- <People key={`people-${link.linkId}`} link={link} only={!hasChat(link.role)} />- {hasChat(link.role) && <Thread key={link.linkId} linkId={link.linkId} />}- </div>- </ControlHold.Provider>- )}- </aside>- </div>,- document.body- )-}--function LinkStatus({ link }: { link: WatchLinkView }): React.JSX.Element | null {- const status = statusLine(link)- if (!status) return null- const tone = link.status === 'live' && waitingViewers([link]) > 0 ? 'waiting' : link.status- return (- <p className={`live-pop__status live-pop__status--${tone}`} role="status">- {status}- </p>- )-}--/** Who is connected: each viewer watching or able to type, a typing dot, Kick — and, for a Control- * link, the owner controls the popover has (one `ControlSection`). */-function People({ link, only }: { link: WatchLinkView; only: boolean }): React.JSX.Element {- const api = window.nodeTerminal.watchLink- const [error, setError] = useState<string | null>(null)- return (- <section className={only ? 'live-chat__people live-chat__people--only' : 'live-chat__people'} aria-label="People">- <h3 className="live-chat__heading">People</h3>- {link.control && <ControlSection linkId={link.linkId} control={link.control} />}- {link.viewers.length === 0 ? (- <p className="live-pop__muted">Nobody is watching right now.</p>- ) : (- <ul className="live-chat__viewers">- {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">- {v.controlling ? 'can type' : 'watching'}- {v.waiting ? ' · waiting for the terminal' : ''}- </span>- <button- type="button"- className="confirm__btn live-pop__btn live-pop__kick"- title={kickNote(v)}- onClick={() => kickViewer(api, link.linkId, v.viewerId, setError)}- >- Kick- </button>- </li>- ))}- </ul>- )}- {error && (- <p className="live-pop__error" role="alert">- {error}- </p>- )}- </section>- )-}--/** "14:02" with the full date in the tooltip; nothing for a time no Date can hold. */-function MessageTime({ at }: { at: number }): React.JSX.Element | null {- const date = new Date(at)- if (!Number.isFinite(date.getTime())) return null- const clock = chatClock(at)- if (!clock) return null- return (- <time className="live-chat__time" dateTime={date.toISOString()} title={date.toLocaleString()}>- {clock}- </time>- )-}--/**- * The thread, the viewer page's live chat: one dense line per message, a Sharer badge on the owner's- * own lines (the HOST's word, `from === 'sharer'` — never a name), and a list that stays at the newest- * message unless the owner scrolled up, then says how many arrived ("N new messages ↓").- *- * `memo`: its only prop is the link id, and it reads the thread from the store itself — so a push- * about the link's viewers (a typing dot, every few seconds while someone types) does not re-render- * the whole message list.- */-const Thread = memo(function Thread({ linkId }: { linkId: string }): React.JSX.Element {- const api = window.nodeTerminal.watchLink- const chat = useWatchLinks((s) => s.chats[linkId] ?? EMPTY_CHAT)- const [draft, setDraft] = useState('')- const [sendError, setSendError] = useState(false)- const [unseen, setUnseen] = useState(0)- const listRef = useRef<HTMLOListElement>(null)- /** Reading the newest message (within NEAR_BOTTOM_PX of the end), as of the last scroll. */- const stick = useRef(true)- // On screen = read (the chip's count clears), and core's history asked once — the popover's rule.- useLinkThread(linkId, api)-- const toBottom = (): void => {- const el = listRef.current- if (el) el.scrollTop = el.scrollHeight- stick.current = true- setUnseen(0)- }- // Keyed on the LAST message's id, not the length: at the store's cap the length stops changing.- const lastId = chat.length > 0 ? chat[chat.length - 1].id : ''- const prevLast = useRef('')- useLayoutEffect(() => {- const before = prevLast.current- prevLast.current = lastId- if (lastId === '') return- if (stick.current || before === '') {- toBottom()- return- }- const at = chat.findIndex((m) => m.id === before)- const added = at === -1 ? 1 : chat.length - 1 - at- if (added > 0) setUnseen((n) => n + added)- // eslint-disable-next-line react-hooks/exhaustive-deps -- runs per new last message, reads the list then- }, [lastId])-- return (- <div className="live-chat__chat">- <div className="live-chat__listwrap">- {chat.length === 0 && <p className="live-pop__muted live-chat__empty">No messages yet. Viewers of this link can chat with you here.</p>}- <ol- className="live-chat__list"- ref={listRef}- onScroll={(e) => {- stick.current = nearBottom(e.currentTarget)- if (stick.current && unseen > 0) toBottom()- }}- >- {chat.map((m) => {- const sharer = m.from === 'sharer'- return (- <li key={m.id} className={sharer ? 'live-chat__msg live-chat__msg--sharer' : 'live-chat__msg'}>- <MessageTime at={m.at} />- {sharer && <span className="live-chat__badge">Sharer</span>}- <span- className="live-chat__name"- // The page's colour for this name, hashed from the name as the viewer sent it.- style={sharer ? undefined : ({ '--live-name': chatNameColor(m.name) } as CSSProperties)}- >- {stripBidiControls(m.name)}- </span>- <span className="live-chat__colon">: </span>- <span className="live-chat__text">{stripBidiControls(m.text)}</span>- </li>- )- })}- </ol>- {unseen > 0 && (- <button type="button" className="confirm__btn primary live-chat__more" onClick={toBottom}>- {`${newMessagesLabel(unseen)} ↓`}- </button>- )}- </div>- {sendError && (- <p className="live-pop__error" role="alert">- {CHAT_NOT_SENT_MESSAGE}- </p>- )}- <form- className="live-chat__reply"- onSubmit={(e) => {- e.preventDefault()- const text = draft.trim()- if (!text) return- setSendError(false)- // The reply comes back through the chat push (core echoes the owner's own message): be at- // the end for it. The box is cleared only once core took it (unless the owner typed on);- // a null answer or a rejection keeps the draft and says so — the popover's rule.- toBottom()- api.sendChat(linkId, text).then(- (sent) => {- if (sent) setDraft((d) => (d.trim() === text ? '' : d))- else setSendError(true)- },- () => setSendError(true)- )- }}- >- <input- className="confirm__input live-chat__input"- value={draft}- maxLength={CHAT_TEXT_MAX}- placeholder="Reply to viewers…"- aria-label="Reply to viewers"- onChange={(e) => setDraft(e.target.value)}- />- <button type="submit" className="confirm__btn live-pop__btn" disabled={!draft.trim()}>- Send- </button>- </form>- </div>- )-})diff --git a/src/renderer/components/LiveLinkChip.surfaces.test.tsx b/src/renderer/components/LiveLinkChip.surfaces.test.tsxdeleted file mode 100644index 65fe4e7b3..000000000--- a/src/renderer/components/LiveLinkChip.surfaces.test.tsx+++ /dev/null@@ -1,238 +0,0 @@-// @vitest-environment jsdom-//-// The LIVE chip on the surfaces that show a node — the kanban card, the card modal header and the-// sessions sidebar row (the canvas node header is pinned at source level by lib/live-link.guard.test.ts:-// TerminalNode is too large to mount here). Each renders the SAME component, and each keeps the-// popover's clicks away from what the surface itself does with a click.-import { act } from 'react'-import { createRoot, type Root } from 'react-dom/client'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ProjectKanban } from '@shared/types'-import type { WatchLinkView } from '@shared/watch-link-types'-import { resetDialogStack } from './dialog-stack'-import { useWatchLinks } from '../state/watchLinks'-import { useAgentStatus } from '../state/agentStatus'-import { useProjects } from '../state/projects'-import { SessionCard } from './kanban/SessionCard'-import { CardModal } from './kanban/CardModal'-import { SessionRow } from './SessionRow'-import type { KanbanSession } from './kanban/KanbanView'-import type { SessionRowVM } from '../lib/sessionList'--vi.mock('../session/session', async () => {- // The agent-status reads now resolve a store per project / per session (bug D, covered in- // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.- const { defaultAgentStatus } = await import('../state/agentStatus')- return {- useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } }),- sessionForProject: () => ({ source: 'local', api: {} }),- agentStatusForProject: () => defaultAgentStatus,- useSessionRegistryVersion: () => 0,- useSessionStores: () => ({ agentStatus: defaultAgentStatus })- }-})-vi.mock('./kanban/BoardLogPanel', () => ({ BoardLogPanel: () => null }))-vi.mock('./ContextMeter', () => ({ ContextMeter: () => null }))-vi.mock('./kanban/ModalTerminal', () => ({ ModalTerminal: () => <div className="kanban-modal__term" /> }))-vi.mock('../nodes/BrowserSurface', () => ({ BrowserSurface: () => null }))--;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true--const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({- linkId: 'L',- nodeId: 'n1',- role: 'viewer',- label: 'Ada',- title: 'build',- createdAt: 0,- expiresAt: Date.now() + 3_600_000,- url: 'u',- status: 'live',- viewers: [{ viewerId: 'v', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }],- control: null,- ...over-})-const session: KanbanSession = { id: 'n1', title: 'build', color: '#fff', kind: 'terminal', spawn: {} } as KanbanSession-const row: SessionRowVM = {- id: 'n1',- title: 'build',- color: '#888',- isAgent: false,- statusKind: 'unknown',- stateLabel: 'Unknown',- unread: false,- usesContext: false,- projectId: 'p1'-} as SessionRowVM-const board = { columns: [], assignments: [] } as unknown as ProjectKanban--let host: HTMLDivElement-let root: Root-beforeEach(() => {- resetDialogStack()- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })- useAgentStatus.setState({ byId: {} } as never)- useProjects.setState({ activeProjectId: 'p1', projects: [] } as never)- vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {- onMarkdownToggle: () => () => {},- boardLog: { list: async () => [], onChanged: () => () => {} },- watchLink: { revoke: async () => {}, kick: async () => true, chatHistory: async () => [], sendChat: async () => null },- clipboard: { writeText: () => {} }- }- host = document.createElement('div')- document.body.append(host)- root = createRoot(host)-})-afterEach(() => {- act(() => root.unmount())- document.body.innerHTML = ''- resetDialogStack()- vi.unstubAllGlobals()-})--const render = (ui: React.ReactElement): void => act(() => root.render(ui))-const setLinks = (links: WatchLinkView[]): void => act(() => useWatchLinks.getState().setLinks(links))-const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))-const pop = (): HTMLElement | null => document.querySelector<HTMLElement>('.live-pop')--function card(onOpen = vi.fn(), onDropAt = vi.fn(), liveLinkSource: 'local' | 'relay' = 'local') {- return (- <SessionCard- session={session}- liveLinkSource={liveLinkSource}- onOpen={onOpen}- onDragStart={vi.fn()}- onDragEnd={vi.fn()}- onDropAt={onDropAt}- onContext={vi.fn()}- />- )-}--describe('LIVE chip — kanban card', () => {- it('a link alone is detail enough to show; no link, no chip and no empty detail row', () => {- render(card())- expect(host.querySelector('.live-chip')).toBeNull()- expect(host.querySelector('.kanban-card__detail')).toBeNull()- setLinks([link()])- const chip = host.querySelector('.kanban-card__detail .live-chip.kanban-card__live')- expect(chip?.textContent).toBe('LIVE · 1')- setLinks([])- expect(host.querySelector('.kanban-card__detail')).toBeNull()- })-- // R57: a relay tab's board shows another machine's nodes, and a git-shared project opened both- // locally and over the relay carries the SAME node ids — this machine's link must not light up- // (or add a detail row to) the relay copy of the card.- it('a card on a relay project shows no chip and no detail row for a colliding node id', () => {- render(card(vi.fn(), vi.fn(), 'relay'))- setLinks([link()])- expect(host.querySelector('.live-chip')).toBeNull()- expect(host.querySelector('.kanban-card__detail')).toBeNull()- })-- it('opening the popover and clicking inside it never opens the card', () => {- const onOpen = vi.fn()- render(card(onOpen))- setLinks([link()])- click(host.querySelector('.live-chip')!)- expect(pop()).not.toBeNull()- click(pop()!)- click(document.querySelector('.live-pop__scrim')!)- expect(onOpen).not.toHaveBeenCalled()- })-- it('another card dragged over this card\'s chip can still be dropped on the card (I1)', () => {- const onDropAt = vi.fn()- render(card(vi.fn(), onDropAt))- setLinks([link()])- const chip = host.querySelector('.live-chip')!- const over = new Event('dragover', { bubbles: true, cancelable: true })- act(() => void chip.dispatchEvent(over))- // The card's handler ran: it accepted the drop and drew its drop line.- expect(over.defaultPrevented).toBe(true)- expect(host.querySelector('.kanban-card')!.className).toMatch(/kanban-card--drop-(before|after)/)- act(() => void chip.dispatchEvent(new Event('drop', { bubbles: true, cancelable: true })))- expect(onDropAt).toHaveBeenCalledWith('n1', expect.stringMatching(/before|after/))- })-})--describe('LIVE chip — card modal header', () => {- it('shows in the header, and Escape closes the popover, not the modal', () => {- const onClose = vi.fn()- render(- <CardModal projectId="p1"- session={session}- columnTitle="Doing"- board={board}- onChangeBoard={vi.fn()}- onClose={onClose}- onOpenCanvas={vi.fn()}- onRename={vi.fn()}- onEditSticky={vi.fn()}- onSetIcon={vi.fn()}- onBrowserNav={vi.fn()}- />- )- expect(document.querySelector('.kanban-modal__header .live-chip')).toBeNull()- setLinks([link({ status: 'reconnecting' })])- const chip = document.querySelector('.kanban-modal__header .live-chip.kanban-modal__live')!- expect(chip.textContent).toBe('LIVE · offline')- click(chip)- expect(pop()).not.toBeNull()- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- expect(pop()).toBeNull()- expect(onClose).not.toHaveBeenCalled()- // With the popover gone, Escape is the modal's again.- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- expect(onClose).toHaveBeenCalledTimes(1)- })-})--describe('LIVE chip — sessions sidebar row', () => {- it('shows on the row; a click or a middle press in the popover neither travels nor ends the session', () => {- const onClick = vi.fn()- const onClose = vi.fn()- render(- <SessionRow- row={row}- liveLinkSource="local"- onClick={onClick}- onClose={onClose}- onRename={vi.fn()}- onAiName={vi.fn()}- onContextMenu={vi.fn()}- onDragStart={vi.fn()}- onDragEnd={vi.fn()}- />- )- expect(host.querySelector('.live-chip')).toBeNull()- setLinks([link({ status: 'refused' })])- const chip = host.querySelector('.ss-row .live-chip.ss-live')!- expect(chip.textContent).toBe('LIVE · refused')- click(chip)- act(() => void pop()!.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 1 })))- click(pop()!)- expect(onClick).not.toHaveBeenCalled()- expect(onClose).not.toHaveBeenCalled()- })-- it('R57: a row of a relay project shows no chip for a colliding node id', () => {- render(- <SessionRow- row={row}- liveLinkSource="relay"- onClick={vi.fn()}- onClose={vi.fn()}- onRename={vi.fn()}- onAiName={vi.fn()}- onContextMenu={vi.fn()}- onDragStart={vi.fn()}- onDragEnd={vi.fn()}- />- )- setLinks([link()])- expect(host.querySelector('.live-chip')).toBeNull()- })-})diff --git a/src/renderer/components/LiveLinkChip.test.tsx b/src/renderer/components/LiveLinkChip.test.tsxdeleted file mode 100644index a7c281585..000000000--- a/src/renderer/components/LiveLinkChip.test.tsx+++ /dev/null@@ -1,951 +0,0 @@-// @vitest-environment jsdom-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 { WatchChatMessage, WatchLinkView } from '@shared/watch-link-types'-import { LiveLinkChip, showsLiveLinks } from './LiveLinkChip'-import { projectSessionSource } from '../lib/projectSessionSource'-import { useWatchLinks } from '../state/watchLinks'-import { useBoardLog } from '../state/boardLog'-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,- KICK_CONTROLLER_NOTE,- CONTROL_CHANGE_UNSAVED_MESSAGE,- PASSWORD_SEPARATE_NOTE,- PASSWORD_SHOWN_ONCE,- STOP_FAILED_MESSAGE-} from '../lib/liveLink'--const boardApi = { tag: 'local-api' }-vi.mock('../session/session', () => ({- sessionForProject: (id: string) => ({ source: id === 'p-relay' ? 'relay' : 'local', api: boardApi })-}))--;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true--const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({- linkId: 'L',- nodeId: 'n1',- role: 'viewer',- label: 'Ada',- title: 'build',- createdAt: 0,- expiresAt: Date.now() + 42 * 60_000 + 30_000,- url: 'https://nodeterm.dev/s/L#1.secret',- status: 'live',- viewers: [],- control: null,- ...over-})-const msg = (id: string, over: Partial<WatchChatMessage> = {}): WatchChatMessage => ({- id,- name: 'Bob',- text: 'hello',- at: Number(id),- from: 'viewer',- ...over-})--const api = {- revoke: vi.fn(async (_id: string) => {}),- kick: vi.fn(async (_l: string, _v: string) => true),- sendChat: vi.fn(async (_l: string, t: string): Promise<WatchChatMessage | null> => ({- id: 's',- name: 'Ada',- text: t,- at: 0,- from: 'sharer'- })),- chatHistory: vi.fn(async (_l: string): Promise<WatchChatMessage[]> => []),- setControl: vi.fn(async (_l: string, _on: boolean): Promise<boolean | 'unsaved'> => true),- setPassword: vi.fn(async (_l: string, _pw: string): Promise<boolean | 'unsaved'> => true),- allowControl: vi.fn(async (_l: string) => true)-}-const writeText = vi.fn()--let host: HTMLDivElement-let root: Root-beforeEach(() => {- resetDialogStack()- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })- useProjects.setState({ projects: [] } as never)- 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()- // A focused, visible window: the thread counts as read only while someone can see it- // (useLinkThread). jsdom answers `hasFocus()` from whatever an EARLIER test focused, which made the- // read tests pass in a full run and fail alone.- vi.spyOn(document, 'hasFocus').mockReturnValue(true)- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { watchLink: api, clipboard: { writeText } }- host = document.createElement('div')- document.body.append(host)- root = createRoot(host)-})-afterEach(() => {- act(() => root.unmount())- document.body.innerHTML = ''- resetDialogStack()- vi.unstubAllGlobals()- vi.restoreAllMocks()-})--const render = (ui: React.ReactElement): void => act(() => root.render(ui))-const chip = (): HTMLButtonElement | null => host.querySelector<HTMLButtonElement>('.live-chip')-const pop = (): HTMLElement | null => document.querySelector<HTMLElement>('.live-pop')-const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))-const setLinks = (links: WatchLinkView[]): void => act(() => useWatchLinks.getState().setLinks(links))-const button = (label: string): HTMLButtonElement =>- [...document.querySelectorAll<HTMLButtonElement>('.live-pop button')].find((b) => b.textContent === label)!-const flush = (): Promise<void> => act(async () => {})--describe('LiveLinkChip', () => {- it('renders nothing for a node with no link', () => {- expect(renderToStaticMarkup(<LiveLinkChip nodeId="n1" source="local" />)).toBe('')- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ nodeId: 'other' })])- expect(host.innerHTML).toBe('')- })-- // R57: the store lists THIS machine's links by node id. A relay tab shows another machine's- // canvas, and a git-shared project opened both locally and over the relay carries the SAME node- // ids — so a surface viewed through anything but the local session shows no chip at all.- it('shows nothing for a node viewed through a relay (or unresolved) session, even with a link on that id', () => {- render(- <>- <LiveLinkChip nodeId="n1" source="relay" />- <LiveLinkChip nodeId="n1" source={null} />- </>- )- setLinks([link()])- expect(host.querySelector('.live-chip')).toBeNull()- render(<LiveLinkChip nodeId="n1" source="local" />)- expect(chip()).not.toBeNull()- })-- it('the shared rule: only a LOCAL session shows this machine\'s links; a project resolves through its session', () => {- expect(showsLiveLinks('local')).toBe(true)- expect(showsLiveLinks('relay')).toBe(false)- expect(showsLiveLinks('server')).toBe(false)- expect(showsLiveLinks(null)).toBe(false)- expect(projectSessionSource('p-local')).toBe('local')- expect(projectSessionSource('p-relay')).toBe('relay')- })-- // Rendered in the DOM, not to a string: zustand answers a server render from the store's INITIAL- // state (empty), so `renderToStaticMarkup` can never show a link.- it('shows LIVE with the viewer count, as a no-drag button', () => {- render(<LiveLinkChip nodeId="n1" source="local" className="extra" />)- setLinks([link({ viewers: [{ viewerId: 'v', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }] })])- const c = chip()!- expect(c.tagName).toBe('BUTTON')- expect(c.textContent).toBe('LIVE · 1')- expect(c.className).toContain('nodrag')- expect(c.className).toContain('live-chip--live')- expect(c.className).toContain('extra')- expect(c.title).toBe('This terminal is shared by a live link — 1 watching.')- })-- it('follows the store: offline, refused, the unread dot, and gone again', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link()])- expect(host.querySelector('.live-chip__dot')).not.toBeNull()- setLinks([link({ status: 'reconnecting' })])- expect(chip()!.className).toContain('live-chip--offline')- expect(chip()!.textContent).toBe('LIVE · offline')- // The broadcast dot is LIVE's alone (N6).- expect(host.querySelector('.live-chip__dot')).toBeNull()- setLinks([link({ status: 'refused' })])- expect(chip()!.className).toContain('live-chip--refused')- expect(host.querySelector('.live-chip__dot')).toBeNull()- expect(host.querySelector('.live-chip__unread')).toBeNull()- act(() => useWatchLinks.getState().addChat('L', msg('1')))- expect(host.querySelector('.live-chip__unread')).not.toBeNull()- expect(chip()!.getAttribute('aria-label')).toBe('LIVE · refused, 1 unread chat message')- setLinks([])- expect(chip()).toBeNull()- })-})--describe('LiveLinkPopover', () => {- it('opens on click with role, time, the controls and the kick note', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }, { viewerId: 'v2', name: 'Cy', joinedAt: 0, waiting: false, controlling: false, typing: false }] })])- click(chip()!)- const p = pop()!- expect(p.textContent).toContain('Can watch')- expect(p.textContent).toContain('ends in 42 min')- expect(p.textContent).toContain('Shown to viewers as Ada')- expect([...p.querySelectorAll('.live-pop__who')].map((e) => e.textContent)).toEqual(['Viewer 1', 'Cy'])- expect(p.textContent).toContain(KICK_NOTE)- // A live link needs no status line; a viewer link has no chat.- expect(p.querySelector('.live-pop__status')).toBeNull()- expect(p.querySelector('.live-pop__chat')).toBeNull()- click(button('Copy link'))- expect(writeText).toHaveBeenCalledWith('https://nodeterm.dev/s/L#1.secret')- click(p.querySelectorAll<HTMLButtonElement>('.live-pop__kick')[1])- expect(api.kick).toHaveBeenCalledWith('L', 'v2')- })-- it('takes the keyboard focus while open and gives it back to the chip', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link()])- act(() => chip()!.focus())- click(chip()!)- expect(document.activeElement).toBe(pop())- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- expect(document.activeElement).toBe(chip())- })-- it('explains a link that is not live (H9)', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ status: 'refused' })])- click(chip()!)- expect(pop()!.querySelector('.live-pop__status')!.textContent).toContain("won't host this link")- })-- // R63: a viewer with no session to join is the owner's to fix — the chip and the popover say how.- it('viewers waiting for the terminal: an amber chip, a status line and the viewer marked', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([- link({- viewers: [- { viewerId: 'v1', name: null, joinedAt: 0, waiting: true, controlling: false, typing: false },- { viewerId: 'v2', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }- ]- })- ])- const c = chip()!- expect(c.textContent).toBe('LIVE · 1 waiting')- expect(c.className).toContain('live-chip--waiting')- expect(c.title).toBe('Viewers are waiting — open this terminal in nodeterm to let them watch.')- click(c)- const p = pop()!- expect(p.querySelector('.live-pop__status')!.textContent).toBe(- 'Viewers are waiting — open this terminal in nodeterm to let them watch.'- )- expect(p.querySelector('.live-pop__status')!.className).toContain('live-pop__status--waiting')- const rows = [...p.querySelectorAll('.live-pop__viewers li')].map((e) => e.textContent)- expect(rows[0]).toContain('waiting for the terminal')- expect(rows[1]).not.toContain('waiting')- })-- it('Stop sharing revokes; a stop that did not reach nodeterm says so (H23)', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link()])- click(chip()!)- api.revoke.mockImplementationOnce(async () => {- throw new Error('socket down')- })- click(button('Stop sharing'))- await flush()- expect(api.revoke).toHaveBeenCalledWith('L')- expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(STOP_FAILED_MESSAGE)- // The state push that removes the link closes the popover, and it stays closed.- setLinks([])- expect(pop()).toBeNull()- setLinks([link({ linkId: 'M' })])- expect(chip()).not.toBeNull()- expect(pop()).toBeNull()- })-- it('Escape closes it, and only when it is the top dialog', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link()])- click(chip()!)- // A dialog raised above it owns the key.- pushDialog('above')- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- expect(pop()).not.toBeNull()- popDialog('above')- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- expect(pop()).toBeNull()- })-- it('takes the Escape before the canvas\'s own window listeners see it', () => {- const globalKeys = vi.fn()- window.addEventListener('keydown', globalKeys)- try {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link()])- click(chip()!)- act(() => void document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })))- expect(pop()).toBeNull()- expect(globalKeys).not.toHaveBeenCalled()- } finally {- window.removeEventListener('keydown', globalKeys)- }- })-- it('keys pressed on the chip reach the window — also after the popover hands focus back (I1)', () => {- const globalKeys = vi.fn()- window.addEventListener('keydown', globalKeys)- try {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link()])- act(() => chip()!.focus())- click(chip()!)- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- expect(pop()).toBeNull()- expect(document.activeElement).toBe(chip())- globalKeys.mockClear()- act(() => void chip()!.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', metaKey: true, bubbles: true })))- expect(globalKeys).toHaveBeenCalledTimes(1)- } finally {- window.removeEventListener('keydown', globalKeys)- }- })-- it('a drag over the chip reaches the surface under it (I1)', () => {- const onDragOver = vi.fn()- const onDrop = vi.fn()- render(- <div onDragOver={onDragOver} onDrop={onDrop}>- <LiveLinkChip nodeId="n1" source="local" />- </div>- )- setLinks([link()])- act(() => void chip()!.dispatchEvent(new Event('dragover', { bubbles: true, cancelable: true })))- act(() => void chip()!.dispatchEvent(new Event('drop', { bubbles: true, cancelable: true })))- expect(onDragOver).toHaveBeenCalledTimes(1)- expect(onDrop).toHaveBeenCalledTimes(1)- })-- it('keys typed inside the popover reach neither the surface nor the window', () => {- const globalKeys = vi.fn()- const onKeyDown = vi.fn()- window.addEventListener('keydown', globalKeys)- try {- render(- <div onKeyDown={onKeyDown}>- <LiveLinkChip nodeId="n1" source="local" />- </div>- )- setLinks([link({ role: 'commenter' })])- click(chip()!)- const input = pop()!.querySelector<HTMLInputElement>('.live-pop__input')!- act(() => void input.dispatchEvent(new KeyboardEvent('keydown', { key: 'j', bubbles: true })))- act(() => void input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })))- expect(onKeyDown).not.toHaveBeenCalled()- expect(globalKeys).not.toHaveBeenCalled()- expect(pop()).not.toBeNull()- } finally {- window.removeEventListener('keydown', globalKeys)- }- })-- it('a failed Kick says so: not reached, or nobody to kick (M3)', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }] })])- click(chip()!)- api.kick.mockImplementationOnce(async () => {- throw new Error('socket down')- })- click(pop()!.querySelector('.live-pop__kick')!)- await flush()- expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(KICK_FAILED_MESSAGE)- api.kick.mockImplementationOnce(async () => false)- click(pop()!.querySelector('.live-pop__kick')!)- await flush()- expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(KICK_NOT_DONE_MESSAGE)- click(pop()!.querySelector('.live-pop__kick')!)- await flush()- expect(pop()!.querySelector('[role="alert"]')).toBeNull()- })-- it('a click or middle press on the chip or inside the popover never reaches the surface it sits in', () => {- const onClick = vi.fn()- const onMouseDown = vi.fn()- render(- <div onClick={onClick} onMouseDown={onMouseDown}>- <LiveLinkChip nodeId="n1" source="local" />- </div>- )- setLinks([link()])- // The chip's own press and click stop too (a sessions row ends the session on a middle press).- act(() => void chip()!.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 1 })))- click(chip()!)- act(() => void pop()!.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 1 })))- click(pop()!)- click(document.querySelector('.live-pop__scrim')!)- expect(onClick).not.toHaveBeenCalled()- expect(onMouseDown).not.toHaveBeenCalled()- expect(pop()).toBeNull()- })-})--describe('LiveLinkPopover — Commenter chat', () => {- it('renders every viewer string as text, never as markup', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter', label: '<b>Ada</b>', viewers: [{ viewerId: 'v', name: '<i>Eve</i>', joinedAt: 0, waiting: false, controlling: false, typing: false }] })])- act(() => useWatchLinks.getState().addChat('L', msg('1', { name: '<u>Eve</u>', text: '<img src=x onerror=alert(1)>' })))- click(chip()!)- const p = pop()!- expect(p.querySelector('img, b, i, u')).toBeNull()- expect(p.querySelector('.live-pop__text')!.textContent).toBe('<img src=x onerror=alert(1)>')- expect(p.querySelector('.live-pop__msg .live-pop__who')!.textContent).toBe('<u>Eve</u>')- expect(p.querySelector('.live-pop__viewers .live-pop__who')!.textContent).toBe('<i>Eve</i>')- expect(p.textContent).toContain('Shown to viewers as <b>Ada</b>')- expect(p.textContent).toContain('(link viewer)')- })-- it('strips bidi controls from what viewers wrote', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter' })])- act(() => useWatchLinks.getState().addChat('L', msg('1', { name: 'Ev\u202ee', text: 'a\u2067b' })))- click(chip()!)- expect(pop()!.querySelector('.live-pop__who')!.textContent).toBe('Eve')- expect(pop()!.querySelector('.live-pop__text')!.textContent).toBe('ab')- })-- it('opening marks the link read, and so does every message that lands while it is open (H21)', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter' })])- act(() => useWatchLinks.getState().addChat('L', msg('1')))- expect(useWatchLinks.getState().unread.L).toBe(1)- click(chip()!)- await flush()- expect(useWatchLinks.getState().unread.L).toBe(0)- expect(api.chatHistory).toHaveBeenCalledWith('L')- act(() => useWatchLinks.getState().addChat('L', msg('2')))- expect(useWatchLinks.getState().unread.L).toBe(0)- expect(host.querySelector('.live-chip__unread')).toBeNull()- })-- it('stays read at the 200-message cap, where the thread length stops changing', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter' })])- act(() => {- for (let i = 1; i <= 200; i++) useWatchLinks.getState().addChat('L', msg(String(i)))- })- click(chip()!)- await flush()- act(() => useWatchLinks.getState().addChat('L', msg('201')))- expect(useWatchLinks.getState().chats.L).toHaveLength(200)- expect(useWatchLinks.getState().unread.L).toBe(0)- })-- it('sends a reply and clears the box; the echo comes back through the push', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter' })])- click(chip()!)- const input = pop()!.querySelector<HTMLInputElement>('.live-pop__input')!- expect(input.maxLength).toBe(500)- act(() => {- const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!- set.call(input, ' on it ')- input.dispatchEvent(new Event('input', { bubbles: true }))- })- act(() => void pop()!.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })))- await flush()- expect(api.sendChat).toHaveBeenCalledWith('L', 'on it')- expect(input.value).toBe('')- expect(useWatchLinks.getState().chats.L ?? []).toHaveLength(0)- expect(pop()!.querySelector('[role="alert"]')).toBeNull()- })-- it('a reply core did not take keeps the draft and says so (M3)', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter' })])- click(chip()!)- const input = pop()!.querySelector<HTMLInputElement>('.live-pop__input')!- const type = (v: string): void =>- act(() => {- Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, v)- input.dispatchEvent(new Event('input', { bubbles: true }))- })- const submit = (): void =>- act(() => void pop()!.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })))- type('hello')- api.sendChat.mockImplementationOnce(async () => null)- submit()- await flush()- expect(input.value).toBe('hello')- expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(CHAT_NOT_SENT_MESSAGE)- api.sendChat.mockImplementationOnce(async () => {- throw new Error('socket down')- })- submit()- await flush()- expect(input.value).toBe('hello')- expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(CHAT_NOT_SENT_MESSAGE)- submit()- await flush()- expect(input.value).toBe('')- expect(pop()!.querySelector('[role="alert"]')).toBeNull()- })-- it('while the thread is open a new message never shows as unread, not even for one render (N2)', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter' })])- click(chip()!)- await flush()- const counts: number[] = []- const off = useWatchLinks.subscribe((st) => counts.push(st.unread.L ?? 0))- act(() => useWatchLinks.getState().addChat('L', msg('1')))- act(() => useWatchLinks.getState().addChat('L', msg('2')))- off()- expect(counts.every((n) => n === 0)).toBe(true)- expect(host.querySelector('.live-chip__unread')).toBeNull()- // Closed: the next one counts again.- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- act(() => useWatchLinks.getState().addChat('L', msg('3')))- expect(useWatchLinks.getState().unread.L).toBe(1)- })-- it('"Copy to card comments" writes one comment as the owner, on this machine\'s project', () => {- const append = vi.fn()- const realAppend = useBoardLog.getState().append- useBoardLog.setState({ append } as never)- useProjects.setState({- projects: [- { id: 'p-relay', nodes: [{ id: 'n1' }] },- { id: 'p-local', nodes: [{ id: 'n1' }] }- ]- } as never)- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter' })])- act(() => useWatchLinks.getState().addChat('L', msg('1', { text: 'ship it @[x](node:abc)' })))- act(() => useWatchLinks.getState().addChat('L', msg('2', { from: 'sharer', name: 'Ada', text: 'ok' })))- click(chip()!)- // Only a viewer's line can be copied (the owner's own reply is already theirs).- const copies = pop()!.querySelectorAll<HTMLButtonElement>('.live-pop__copy')- expect(copies).toHaveLength(1)- click(copies[0])- expect(append).toHaveBeenCalledTimes(1)- expect(append).toHaveBeenCalledWith(boardApi, 'p-local', {- kind: 'comment',- nodeId: 'n1',- text: 'Bob (via live link): ship it @ [x](node:abc)'- })- expect(copies[0].disabled).toBe(true)- useBoardLog.setState({ append: realAppend } as never)- })-- it('offers no copy when no project holds the node', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([link({ role: 'commenter' })])- act(() => useWatchLinks.getState().addChat('L', msg('1')))- click(chip()!)- 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)- })-- // Final review, Important 1: a narrowing change is in force even when it could not be saved. The- // owner is told so — it undoes at a restart — with Stop at hand to end it for good.- it("typing OFF answered 'unsaved': says it applied but will undo at a restart, with Stop sharing at hand", async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- api.setControl.mockImplementationOnce(async () => 'unsaved')- click(pop()!.querySelector('[role="switch"]')!)- await flush()- const notice = pop()!.querySelector<HTMLElement>('.live-pop__unsaved')!- expect(notice.getAttribute('role')).toBe('alert')- expect(notice.textContent).toContain(CONTROL_CHANGE_UNSAVED_MESSAGE)- expect(pop()!.textContent).not.toMatch(/didn't take/)- const stop = [...notice.querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === 'Stop sharing')!- click(stop)- await flush()- expect(api.revoke).toHaveBeenCalledWith('L')- })-- it("a stop from the unsaved notice that did not reach nodeterm says so", async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- api.setControl.mockImplementationOnce(async () => 'unsaved')- click(pop()!.querySelector('[role="switch"]')!)- await flush()- api.revoke.mockImplementationOnce(async () => {- throw new Error('socket down')- })- click([...pop()!.querySelectorAll<HTMLButtonElement>('.live-pop__unsaved button')].find((b) => b.textContent === 'Stop sharing')!)- await flush()- expect(pop()!.querySelector('.live-pop__unsaved')!.textContent).toContain(STOP_FAILED_MESSAGE)- })-- it("the unsaved notice goes once a later change is saved", async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- api.setControl.mockImplementationOnce(async () => 'unsaved')- click(pop()!.querySelector('[role="switch"]')!)- await flush()- expect(pop()!.querySelector('.live-pop__unsaved')).not.toBeNull()- setLinks([controller({ control: { enabled: false, locked: false } })])- // A widening that fails changes nothing: the earlier change is still unsaved.- api.setControl.mockImplementationOnce(async () => false)- click(pop()!.querySelector('[role="switch"]')!)- await flush()- expect(pop()!.querySelector('.live-pop__unsaved')).not.toBeNull()- // One that lands writes everything memory holds: nothing is unsaved any more.- click(pop()!.querySelector('[role="switch"]')!)- await flush()- expect(pop()!.querySelector('.live-pop__unsaved')).toBeNull()- })-- it("a new password answered 'unsaved' is in force: it is shown once, with the unsaved notice", async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- click(button('Change password…'))- typeInto(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!, 'longenough1')- api.setPassword.mockImplementationOnce(async () => 'unsaved')- click(button('Save'))- await flush()- expect(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!.value).toBe('longenough1')- expect(pop()!.textContent).toContain(PASSWORD_SHOWN_ONCE)- expect(pop()!.querySelector('.live-pop__unsaved')!.textContent).toContain(CONTROL_CHANGE_UNSAVED_MESSAGE)- expect(pop()!.textContent).not.toMatch(/wasn't changed/)- })-- it('the Kick of a viewer who is controlling says they can unlock again; a watcher\'s does not', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller({ viewers: [typist('a', 'Mert'), { viewerId: 'c', name: 'Dee', joinedAt: 0, waiting: false, controlling: false, typing: false }] })])- click(chip()!)- const kicks = [...pop()!.querySelectorAll<HTMLButtonElement>('.live-pop__kick')]- expect(kicks[0].title).toBe(`${KICK_NOTE} ${KICK_CONTROLLER_NOTE}`)- expect(kicks[1].title).toBe(KICK_NOTE)- // The note under the list says it too while someone controls.- expect(pop()!.querySelector('.live-pop__viewers .live-pop__note')!.textContent).toBe(`${KICK_NOTE} ${KICK_CONTROLLER_NOTE}`)- setLinks([controller({ viewers: [{ viewerId: 'c', name: 'Dee', joinedAt: 0, waiting: false, controlling: false, typing: false }] })])- expect(pop()!.querySelector('.live-pop__viewers .live-pop__note')!.textContent).toBe(KICK_NOTE)- })-- it('a change that did not take says so', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- 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('while a password save is in flight the popover stays: an outside click and Escape are ignored', async () => {- let answer!: (ok: boolean) => void- api.setPassword.mockImplementationOnce(() => new Promise<boolean>((r) => (answer = r)))- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- click(button('Change password…'))- typeInto(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!, 'longenough1')- click(button('Save'))- await flush()- expect(button('Saving…')).toBeTruthy()- expect(button('Saving…').disabled).toBe(true)- click(document.querySelector('.live-pop__scrim')!)- expect(pop()).not.toBeNull()- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- expect(pop()).not.toBeNull()- // Open chat would hand over to the drawer: not while the new password is still owed.- click(button('Open chat'))- expect(pop()).not.toBeNull()- await act(async () => answer(true))- expect(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!.value).toBe('longenough1')- expect(pop()!.textContent).toContain(PASSWORD_SHOWN_ONCE)- // Saved and shown: closing works again.- act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))- expect(pop()).toBeNull()- })-- it('a save that fails releases the popover too', async () => {- let answer!: (ok: boolean) => void- api.setPassword.mockImplementationOnce(() => new Promise<boolean>((r) => (answer = r)))- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- click(button('Change password…'))- typeInto(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!, 'longenough1')- click(button('Save'))- await flush()- click(document.querySelector('.live-pop__scrim')!)- expect(pop()).not.toBeNull()- await act(async () => answer(false))- click(document.querySelector('.live-pop__scrim')!)- expect(pop()).toBeNull()- })-- it('the link going away mid-save closes it: nothing is owed for a link that no longer exists', async () => {- api.setPassword.mockImplementationOnce(() => new Promise<boolean>(() => {}))- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- click(button('Change password…'))- typeInto(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!, 'longenough1')- click(button('Save'))- await flush()- setLinks([])- expect(pop()).toBeNull()- })-- it('keyboard focus follows the Change password flow', async () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- const field = (): HTMLInputElement => pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!- // Entering the flow: the new field.- click(button('Change password…'))- expect(document.activeElement).toBe(field())- // Cancel: back to "Change password…".- click(button('Cancel'))- expect(document.activeElement).toBe(button('Change password…'))- // Saved: Copy password, the one thing to do next.- click(button('Change password…'))- typeInto(field(), 'longenough1')- click(button('Save'))- await flush()- expect(document.activeElement).toBe(button('Copy password'))- // Done: back to "Change password…".- click(button('Done'))- expect(document.activeElement).toBe(button('Change password…'))- })-- it('the validation line is tied to the field (aria-describedby)', () => {- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- click(button('Change password…'))- const field = pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!- typeInto(field, 'short')- const id = field.getAttribute('aria-describedby')!- expect(document.getElementById(id)!.textContent).toBe('Use at least 8 characters.')- typeInto(field, 'longenough1')- expect(field.hasAttribute('aria-describedby')).toBe(false)- })-- it('the Typing switch stays focusable while a change is in flight, and ignores clicks then', async () => {- let answer!: (ok: boolean) => void- api.setControl.mockImplementationOnce(() => new Promise<boolean>((r) => (answer = r)))- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- const sw = (): HTMLButtonElement => pop()!.querySelector<HTMLButtonElement>('[role="switch"]')!- act(() => sw().focus())- click(sw())- await flush()- expect(sw().disabled).toBe(false)- expect(sw().getAttribute('aria-disabled')).toBe('true')- expect(document.activeElement).toBe(sw())- click(sw())- await flush()- expect(api.setControl).toHaveBeenCalledTimes(1)- await act(async () => answer(true))- expect(sw().hasAttribute('aria-disabled')).toBe(false)- click(sw())- await flush()- expect(api.setControl).toHaveBeenCalledTimes(2)- })-- it('a password save that never settles lets the popover go after 30 s, and says what to check', async () => {- api.setPassword.mockImplementationOnce(() => new Promise<boolean>(() => {}))- render(<LiveLinkChip nodeId="n1" source="local" />)- setLinks([controller()])- click(chip()!)- click(button('Change password…'))- typeInto(pop()!.querySelector<HTMLInputElement>('.live-pop__password input')!, 'longenough1')- vi.useFakeTimers()- try {- click(button('Save'))- await act(async () => {})- act(() => vi.advanceTimersByTime(29_999))- click(document.querySelector('.live-pop__scrim')!)- expect(pop()).not.toBeNull()- act(() => vi.advanceTimersByTime(1))- expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(- "Couldn't confirm the new password. Check the link before sharing it."- )- expect(button('Save')).toBeTruthy()- click(document.querySelector('.live-pop__scrim')!)- expect(pop()).toBeNull()- } finally {- vi.useRealTimers()- }- })-- 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.tsxdeleted file mode 100644index c9bce4947..000000000--- a/src/renderer/components/LiveLinkChip.tsx+++ /dev/null@@ -1,92 +0,0 @@-import { memo, useCallback, useEffect, useState } from 'react'-import { chipView } from '../lib/liveLink'-import type { SessionSource } from '../session/session'-import { EMPTY_LINKS, liveChipSig, useWatchLinks } from '../state/watchLinks'-import { LiveLinkPopover, type PopoverAnchor } from './LiveLinkPopover'--/**- * R57 — THE rule for whether a surface may show THIS machine's live links for a node. The store is- * keyed by node id and lists only links this machine created; a relay tab shows ANOTHER machine's- * canvas, and a git-shared project opened both locally and over the relay carries the same node- * ids. So only a node viewed through the LOCAL session shows the chip (and counts as "has a live- * link" on a kanban card). Unknown (null) shows nothing.- */-export function showsLiveLinks(source: SessionSource | null): boolean {- return source === 'local'-}--/**- * "This terminal is being broadcast." ONE component on the canvas node header, the kanban card, the- * card modal header and the sessions sidebar row, so one session seen four times speaks with one- * voice (CONTRIBUTING: the canvas and the board are two views of the same nodes). It is deliberately- * NOT user-hideable (lib/live-link.guard.test.ts): it is the owner's signal that someone may be- * watching this terminal right now.- *- * It subscribes to a PRIMITIVE signature of its own node's links (`liveChipSig`), never to a map,- * so a push about another node's link — or any hook event — re-renders nothing here.- */-export const LiveLinkChip = memo(function LiveLinkChip({- nodeId,- source,- className-}: {- nodeId: string- /** The session this node is viewed through (R57). Required, so no surface can forget it: a- * relay-sourced surface passes 'relay' and the chip stays empty for a colliding node id. */- source: SessionSource | null- className?: string-}): React.JSX.Element | null {- const local = showsLiveLinks(source)- const sig = useWatchLinks((s) => (local ? liveChipSig(s, nodeId) : ''))- const [anchor, setAnchor] = useState<PopoverAnchor | null>(null)- const close = useCallback(() => setAnchor(null), [])- // The last link went away while the popover was open: forget it was open, or the NEXT link on- // this node would bring the popover back by itself.- useEffect(() => {- if (!sig) setAnchor(null)- }, [sig])- if (!sig) return null- const s = useWatchLinks.getState()- const links = s.byNode[nodeId] ?? EMPTY_LINKS- const view = chipView(links)- const unread = links.reduce((n, l) => n + (s.unread[l.linkId] ?? 0), 0)- const stop = (e: React.SyntheticEvent): void => e.stopPropagation()- return (- <>- {/* The chip sits INSIDE a clickable card, a draggable node header and a sessions row that- closes on a middle click, so its own click-related events stop here. Only those: keys, drags- and the wheel pass, or with focus on the chip (where the popover hands it back) every global- shortcut went dead, and a card dragged over another card's chip could not be dropped. The- popover isolates ITS events at its own portal roots (LiveLinkPopover). */}- <button- type="button"- className={`live-chip live-chip--${view.tone} nodrag${className ? ` ${className}` : ''}`}- title={view.title}- aria-label={unread > 0 ? `${view.label}, ${unread} unread chat ${unread === 1 ? 'message' : 'messages'}` : view.label}- aria-haspopup="dialog"- aria-expanded={!!anchor}- onMouseDown={stop}- onPointerDown={stop}- onDoubleClick={stop}- onContextMenu={stop}- onClick={(e) => {- e.stopPropagation()- const r = e.currentTarget.getBoundingClientRect()- setAnchor((cur) => (cur ? null : { top: r.top, bottom: r.bottom, left: r.left }))- }}- >- {/* 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}- {/* 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/LiveLinkControls.tsx b/src/renderer/components/LiveLinkControls.tsxdeleted file mode 100644index c453381af..000000000--- a/src/renderer/components/LiveLinkControls.tsx+++ /dev/null@@ -1,346 +0,0 @@-// A live link's owner controls, shared by the LIVE chip's popover (LiveLinkPopover) and the Live chat-// drawer (LiveChatDrawer): one implementation, so the two surfaces cannot disagree about what a-// Control link's switch, password change or unlock does. Every string someone else wrote is rendered-// as React TEXT; a new password lives only in `ControlSection`'s state and goes with it.-import { createContext, useContext, useEffect, useId, useRef, useState } from 'react'-import type { NodeTerminalApi } from '@shared/types'-import type { ControlChangeResult, WatchLinkControlView, WatchLinkRole } from '@shared/watch-link-types'-import { newControlPassword, PasswordField, useCopied } from './LiveLinkPassword'-import { Switch } from '../ui/Switch'-import {- CONTROL_CHANGE_FAILED_MESSAGE,- CONTROL_CHANGE_UNSAVED_MESSAGE,- controlLockedText,- KICK_FAILED_MESSAGE,- KICK_NOT_DONE_MESSAGE,- PASSWORD_CHANGE_FAILED_MESSAGE,- PASSWORD_CHANGE_NOTE,- PASSWORD_SAVE_TIMEOUT_MS,- PASSWORD_SEPARATE_NOTE,- PASSWORD_SHOWN_ONCE,- PASSWORD_UNCONFIRMED_MESSAGE,- passwordProblemText,- STOP_FAILED_MESSAGE-} from '../lib/liveLink'--/**- * What a section holds its surface for:- * - `save`: a new Control password's save is in flight. Once core takes it, its plaintext exists- * nowhere else, so a surface closed under it would lose a password that was changed: the surface- * must not close on the owner's close gestures, nor switch away from this link.- * - `shown`: the new password is on screen until Done. Closing is the owner's own gesture (they have- * it in front of them), but a surface that switches LINKS by itself (the drawer, on an Open chat- * for another link) must not take it away first.- */-export type ControlHoldKind = 'save' | 'shown'--/**- * `hold(kind)` holds the surface until the returned release runs (see `ControlHoldKind`). The link- * going away still closes the popover (nothing is owed for a link that no longer exists). Absent:- * nothing to hold.- */-export const ControlHold = createContext<((kind?: ControlHoldKind) => () => void) | null>(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'-}--/**- * Kick one viewer, reporting what did not happen: `false` from core (they may already have left) and- * a rejection (the Server Edition's socket was down) say different things. `onError(null)` first- * clears an earlier message.- */-export function kickViewer(- api: Pick<NodeTerminalApi['watchLink'], 'kick'>,- linkId: string,- viewerId: string,- onError: (text: string | null) => void-): void {- onError(null)- api.kick(linkId, viewerId).then(- (ok) => {- if (!ok) onError(KICK_NOT_DONE_MESSAGE)- },- () => onError(KICK_FAILED_MESSAGE)- )-}--/**- * 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. Shared by the chip's popover and 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.- *- * A NARROWING change (typing off, a new password) that core answered 'unsaved' is in force but would be- * undone by a restart: the section says so, with Stop sharing right there — the one thing that ends it- * for good — in the popover and the drawer alike (the drawer has no Stop of its own). The notice stays- * until a later change is saved (every write carries the whole list, so that one saved this one too).- */-export function ControlSection({ linkId, control }: { linkId: string; control: WatchLinkControlView }): React.JSX.Element {- const api = window.nodeTerminal.watchLink- const hold = useContext(ControlHold)- const invalidId = useId()- const [busy, setBusy] = useState(false)- /** A password save is in flight: the surface holds open, Save reads "Saving…". */- const [saving, setSaving] = useState(false)- const [error, setError] = useState<string | null>(null)- /** A narrowing change is in force but unsaved (`ControlChangeResult` 'unsaved'). */- const [unsaved, setUnsaved] = useState(false)- /** The unsaved notice's Stop did not reach nodeterm. */- const [stopFailed, setStopFailed] = useState(false)- const [editing, setEditing] = useState(false)- const [draft, setDraft] = useState('')- const [shown, setShown] = useState<string | null>(null)- const [copied, copy] = useCopied()- // Keyboard focus follows the flow: the new field on entering it, Copy password once a new one is- // shown, "Change password…" again on Cancel or Done (whose button would otherwise take the focus- // with it as it unmounts). Applied after the render that mounts the target.- const [focusTo, setFocusTo] = useState<'field' | 'copy' | 'change' | null>(null)- const fieldRef = useRef<HTMLInputElement>(null)- const copyRef = useRef<HTMLButtonElement>(null)- const changeRef = useRef<HTMLButtonElement>(null)- useEffect(() => {- if (!focusTo) return- const el = focusTo === 'field' ? fieldRef.current : focusTo === 'copy' ? copyRef.current : changeRef.current- el?.focus({ preventScroll: true })- setFocusTo(null)- }, [focusTo])- // A hold and a deadline this section took and has not given back — both go on unmount too (the- // link went away: nothing is owed for it).- const releaseRef = useRef<(() => void) | null>(null)- /** The `shown` hold while a new password is on screen (released by Done, or on unmount). */- const shownReleaseRef = useRef<(() => void) | null>(null)- const deadlineRef = useRef<ReturnType<typeof setTimeout>>()- useEffect(- () => () => {- releaseRef.current?.()- shownReleaseRef.current?.()- clearTimeout(deadlineRef.current)- },- []- )- /** Which save is current: a late answer to an older one is not shown. */- const saveGen = useRef(0)- /** Core's answer to a change: saved clears an earlier unsaved notice (that write carried it too),- * 'unsaved' raises it, anything else is a change that did not take. */- const settled = (r: ControlChangeResult, failed: string): void => {- if (r === 'unsaved') setUnsaved(true)- else if (r === true) setUnsaved(false)- else setError(failed)- }- const run = (call: () => Promise<ControlChangeResult>, failed: string): void => {- setBusy(true)- setError(null)- void Promise.resolve()- .then(call)- .then(- (r) => settled(r, failed),- () => setError(failed)- )- .finally(() => setBusy(false))- }- /** The notice's Stop: what the popover's Stop sharing does (the desktop's stop is immediate, and the- * state push removes the link); the Server Edition rejects when its socket is down — say so. */- const stopLink = (): void => {- setStopFailed(false)- api.revoke(linkId).catch(() => setStopFailed(true))- }- /**- * Save a new password, holding the surface (popover or drawer) open until the answer is in and, on- * success, shown — its plaintext exists nowhere else. Bounded: with no answer after- * `PASSWORD_SAVE_TIMEOUT_MS` the hold is released and the owner is told the outcome is unknown. An- * answer that lands later still counts: a new password that did take is shown, one refused says so.- */- const save = (): void => {- const next = draft- const gen = ++saveGen.current- const release = hold?.() ?? null- releaseRef.current = release- let open = true- const settle = (): void => {- if (!open) return- open = false- clearTimeout(deadlineRef.current)- setSaving(false)- setBusy(false)- release?.()- if (releaseRef.current === release) releaseRef.current = null- }- setSaving(true)- setBusy(true)- setError(null)- deadlineRef.current = setTimeout(() => {- if (!open) return- settle()- setError(PASSWORD_UNCONFIRMED_MESSAGE)- }, PASSWORD_SAVE_TIMEOUT_MS)- void Promise.resolve()- .then(() => api.setPassword(linkId, next))- .then(- (ok) => {- const current = gen === saveGen.current- // A password that took is held on screen until Done — taken BEFORE the save's hold goes, so- // there is no moment in which the drawer may switch to another link and drop it.- if (ok && current) {- shownReleaseRef.current?.()- shownReleaseRef.current = hold?.('shown') ?? null- }- settle()- if (!current) return- if (ok) {- // In force either way: shown once. 'unsaved' adds that a restart would undo it.- setUnsaved(ok === 'unsaved')- setError(null)- setShown(next)- setDraft('')- setEditing(false)- setFocusTo('copy')- } else setError(PASSWORD_CHANGE_FAILED_MESSAGE)- },- () => {- settle()- if (gen === saveGen.current) setError(PASSWORD_CHANGE_FAILED_MESSAGE)- }- )- }- const problem = passwordProblemText(draft)- const showProblem = draft !== '' && problem !== null- return (- <div className="live-pop__control">- {control.locked && (- <div className="live-pop__locked">- <p className="live-pop__status" role="status">- {controlLockedText(control.lockedUntil)}- </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>- {/* `pending`, not `disabled`: a switch the owner just toggled from the keyboard keeps the focus. */}- <Switch- checked={control.enabled}- ariaLabel="Typing"- pending={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" ref={copyRef} className="confirm__btn live-pop__btn" onClick={() => copy(shown)}>- {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={() => {- shownReleaseRef.current?.()- shownReleaseRef.current = null- setShown(null)- setFocusTo('change')- }}- >- Done- </button>- </div>- </>- ) : editing ? (- <>- <div className="live-pop__password">- <PasswordField- inputRef={fieldRef}- value={draft}- disabled={busy}- onChange={setDraft}- label="New password"- describedBy={showProblem ? invalidId : undefined}- />- <button type="button" className="confirm__btn live-pop__btn" disabled={busy} onClick={() => setDraft(newControlPassword())}>- Generate- </button>- </div>- {showProblem && (- <p className="live-pop__invalid" id={invalidId}>- {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)- setFocusTo('change')- }}- >- Cancel- </button>- <button- type="button"- className="confirm__btn primary live-pop__btn"- disabled={busy || problem !== null}- onClick={save}- >- {saving ? 'Saving…' : 'Save'}- </button>- </div>- </>- ) : (- <div className="live-pop__actions">- <button- type="button"- ref={changeRef}- className="confirm__btn live-pop__btn"- onClick={() => {- setEditing(true)- setFocusTo('field')- }}- >- Change password…- </button>- </div>- )}- {unsaved && (- <div className="live-pop__unsaved" role="alert">- <p className="live-pop__error">{CONTROL_CHANGE_UNSAVED_MESSAGE}</p>- <div className="live-pop__actions">- <button type="button" className="confirm__btn danger live-pop__btn" onClick={stopLink}>- Stop sharing- </button>- </div>- {stopFailed && <p className="live-pop__error">{STOP_FAILED_MESSAGE}</p>}- </div>- )}- {error && (- <p className="live-pop__error" role="alert">- {error}- </p>- )}- </div>- )-}diff --git a/src/renderer/components/LiveLinkDialog.test.tsx b/src/renderer/components/LiveLinkDialog.test.tsxdeleted file mode 100644index 5aacb0889..000000000--- a/src/renderer/components/LiveLinkDialog.test.tsx+++ /dev/null@@ -1,816 +0,0 @@-// @vitest-environment jsdom-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 { ControlSupport, CreateWatchLinkRequest, CreateWatchLinkResult } from '@shared/watch-link-types'-import { LiveLinkDialog, LiveLinkDialogBody } from './LiveLinkDialog'-import {- CONTROL_UNSUPPORTED_REASON,- controlWarningText,- formatClock,- LIVE_LINK_EXPOSURE,- PASSWORD_SEPARATE_NOTE,- PASSWORD_SHOWN_ONCE,- SAVE_FIRST_MESSAGE,- STOP_FAILED_MESSAGE,- UNLIMITED_NOTE-} from '../lib/liveLink'-import { LIVE_LINK_DEFAULTS_KEY } from '../lib/liveLinkDefaults'-import { resetDialogStack } from './dialog-stack'-import { pinNeutralMachineNoun } from '../lib/testMachineNoun'--;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true-pinNeutralMachineNoun()--const noop = (): void => {}-const body = (state: Parameters<typeof LiveLinkDialogBody>[0]['state'], extra: Partial<Parameters<typeof LiveLinkDialogBody>[0]> = {}) =>- renderToStaticMarkup(- <LiveLinkDialogBody title="build" state={state} onChange={noop} onSubmit={noop} onClose={noop} onStop={noop} {...extra} />- )-const FORM = { phase: 'form', role: 'viewer', ttl: 3600, label: 'Ada', password: '', busy: false, error: null } as const--describe('LiveLinkDialogBody', () => {- it('reads as rows: who can use the link, when it expires, the name — and the exposure always', () => {- const html = body(FORM)- expect(html).toContain('Share “build”')- expect(html).toContain('Anyone with the link')- expect(html).toContain('can watch')- expect(html).toContain('Expires')- expect(html).toContain('in 1 hour')- expect(html).toContain('Viewers see you as')- // The menus are closed: their choices are not on the page until one is opened.- expect(html).not.toContain('menu-select__menu')- // Neither Control's password row nor its warning until Control is picked.- expect(html).not.toContain('live-dialog__password')- expect(html).not.toContain('live-dialog__warning')- expect(html).toContain(LIVE_LINK_EXPOSURE)- expect(html).toContain('Create live link')- })-- it('shows the URL with Copy and Stop, and until when anyone with it can watch (H25)', () => {- const expiresAt = new Date(2026, 9, 1, 15, 42, 0).getTime()- const now = new Date(2026, 9, 1, 14, 42, 0).getTime()- const html = body({ phase: 'done', role: 'viewer', url: 'https://nodeterm.dev/s/x#1.y', linkId: 'x', expiresAt }, { now })- expect(html).toContain('https://nodeterm.dev/s/x#1.y')- expect(html).toContain('Copy link')- expect(html).toContain('Stop sharing')- expect(html).toContain(`Anyone with this link can watch until ${formatClock(expiresAt)}.`)- })-- // R64/M1: a 24 h link made at 15:43 read "until 15:43" — it looks like it ends now.- it('names the day when the link ends on another day', () => {- const now = new Date(2026, 9, 1, 15, 43, 0).getTime()- const expiresAt = now + 24 * 3_600_000- const html = body({ phase: 'done', role: 'viewer', url: 'https://nodeterm.dev/s/x#1.y', linkId: 'x', expiresAt }, { now })- expect(html).toContain(`Anyone with this link can watch until tomorrow ${formatClock(expiresAt)}.`)- })-- it('Control: the "and" of the typing warning is bold, and the machine is the one the caller names', () => {- const html = body({ ...FORM, role: 'controller' }, { controlMachine: '[email protected]' })- expect(html).toContain('<strong>and</strong>')- expect(html).toContain('run any command on [email protected],')- // The exposure stays under it: anyone with the link alone still watches a Control link.- expect(html).toContain(LIVE_LINK_EXPOSURE)- })-- it('R63: the "only while open" note shows in the form when the caller has one', () => {- expect(body(FORM, { whileOpenNote: 'NOTE-X' })).toContain('NOTE-X')- expect(body(FORM)).not.toContain('live-dialog__note')- })-- it('the header title loses its bidi controls (H26)', () => {- const html = renderToStaticMarkup(- <LiveLinkDialogBody title={'bu\u202eild'} state={FORM} onChange={noop} onSubmit={noop} onClose={noop} onStop={noop} />- )- expect(html).toContain('Share “build”')- })-- it('offers Upgrade only for a not-entitled error AND only when the caller can upgrade (H12, R43)', () => {- const err = { ...FORM, error: 'Live links need an active Pro plan.', offerUpgrade: true }- expect(body(err, { onUpgrade: noop })).toContain('Upgrade to Pro')- // The Server Edition passes no onUpgrade: never an Upgrade button there.- expect(body(err)).not.toContain('Upgrade to Pro')- expect(body({ ...err, offerUpgrade: false }, { onUpgrade: noop })).not.toContain('Upgrade to Pro')- })-- it('while busy, Cancel cannot close and Create says so (H24)', () => {- const html = body({ ...FORM, busy: true })- expect(html).toMatch(/<button class="confirm__btn" disabled="">Cancel<\/button>/)- expect(html).toContain('Creating…')- })-})--// ---- the mounted dialog ------------------------------------------------------------------------const created = (url = 'https://nodeterm.dev/s/abc#1.k'): CreateWatchLinkResult => ({- ok: true,- link: {- linkId: 'abc',- nodeId: 'n1',- role: 'viewer',- label: 'Ada',- title: 'build',- createdAt: 0,- expiresAt: Date.now() + 3_600_000,- url,- status: 'live',- viewers: [],- control: null- }-})--let 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-const readPersistence = async () => {- if (!persistence) throw new Error('no core')- return { persistence }-}-let host: HTMLDivElement-let root: Root-beforeEach(() => {- resetDialogStack()- 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,- clipboard: { writeText: vi.fn() }- }- localStorage.clear()- host = document.createElement('div')- document.body.append(host)- root = createRoot(host)-})-afterEach(() => {- act(() => root.unmount())- document.body.innerHTML = ''- resetDialogStack()-})--const flush = (): Promise<void> => act(async () => {})-const btn = (label: string): HTMLButtonElement =>- [...document.querySelectorAll<HTMLButtonElement>('.live-dialog button')].find((b) => b.textContent === label)!-const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))-const escape = (): void => act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))-const setLabel = (v: string): void => {- const input = document.querySelector<HTMLInputElement>('.live-dialog__label input')!- act(() => {- const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!- set.call(input, v)- input.dispatchEvent(new Event('input', { bubbles: true }))- })-}--/** A row's menu trigger, by the row's label ("Anyone with the link", "Expires"). */-const trigger = (row: string): HTMLButtonElement =>- document.querySelector<HTMLButtonElement>(`.menu-select__trigger[aria-label^="${row}:"]`)!-/** An option of the OPEN menu, by its label. */-const option = (label: string): HTMLButtonElement | undefined =>- [...document.querySelectorAll<HTMLButtonElement>('.menu-select__item')].find(- (b) => b.querySelector('.menu-select__label')?.textContent === label- )-/** Open a row's menu and pick an option, the way a person does. */-const choose = (row: string, label: string): void => {- click(trigger(row))- click(option(label)!)-}-const pickRole = (label: 'can watch' | 'can chat' | 'can type'): void => choose('Anyone with the link', label)-const roleValue = (): string => trigger('Anyone with the link').querySelector('.menu-select__value')!.textContent!--function mount(o: {- prepare?: () => Promise<string | null>- onUpgrade?: () => void- onClose?: () => void- surface?: 'desktop' | 'server' | 'relay'- remoteNode?: boolean- sshTarget?: { user: string; host: string } | null-} = {}): { onClose: ReturnType<typeof vi.fn> } {- const onClose = vi.fn(o.onClose ?? (() => {}))- act(() =>- root.render(- <LiveLinkDialog- nodeId="n1"- title="build"- surface={o.surface ?? 'desktop'}- remoteNode={o.remoteNode}- sshTarget={o.sshTarget}- readPersistence={readPersistence}- prepare={o.prepare ?? (async () => null)}- onUpgrade={o.onUpgrade}- onClose={onClose}- />- )- )- return { onClose }-}--describe('LiveLinkDialog', () => {- it('prefills "Shown to viewers as" with the presence name, capped to the label limit', () => {- localStorage.setItem('nodeterm.presence.me', JSON.stringify({ name: 'Ada Lovelace', color: '#fff' }))- mount()- const input = document.querySelector<HTMLInputElement>('.live-dialog__label input')!- expect(input.value).toBe('Ada Lovelace')- expect(input.maxLength).toBe(40)- act(() => root.unmount())- root = createRoot(host)- localStorage.setItem('nodeterm.presence.me', JSON.stringify({ name: 'x'.repeat(60), color: '#fff' }))- mount()- expect(document.querySelector<HTMLInputElement>('.live-dialog__label input')!.value).toBe('x'.repeat(40))- })-- it('D2/M3: the prefill never splits an emoji at the label limit', () => {- localStorage.setItem('nodeterm.presence.me', JSON.stringify({ name: 'x'.repeat(39) + '\u{1F600}', color: '#fff' }))- mount()- expect(document.querySelector<HTMLInputElement>('.live-dialog__label input')!.value).toBe('x'.repeat(39))- })-- it('D2/M3: focus lands in the dialog — the role menu on open, Copy link once created', async () => {- mount()- expect(document.activeElement).toBe(trigger('Anyone with the link'))- setLabel('Ada')- click(btn('Create live link'))- await flush()- expect(document.activeElement).toBe(btn('Copy link'))- })-- // R63: on a machine with no watcher client for a local node (Windows' session host, tmux off or- // missing, Zellij), a link works only while the terminal is open here — said before it is created.- it('R63: says "only while open" where this machine has no watcher client, and nowhere else', async () => {- const note = (): string | null =>- [...document.querySelectorAll('.live-dialog__note')].map((e) => e.textContent).join('|') || null- for (const [p, remote, shown] of [- [{ enabled: true, backend: 'session-host' }, false, true],- [{ enabled: true, backend: 'zellij' }, false, true],- [{ enabled: false, backend: 'tmux' }, false, true],- [{ enabled: true, backend: null }, false, true],- [{ enabled: true, backend: 'tmux' }, false, false],- [{ enabled: true, backend: 'session-host' }, true, false], // an SSH node: the host's tmux- [undefined, false, false] // unknown claims nothing- ] as const) {- persistence = p- act(() => root.unmount())- root = createRoot(host)- mount({ remoteNode: remote })- await flush()- if (shown) expect(note(), JSON.stringify(p)).toMatch(/only while it is open in nodeterm/)- else expect(note(), JSON.stringify(p)).toBeNull()- }- })-- it('R47: prepares BEFORE create, then creates this node with the chosen options', async () => {- const order: string[] = []- const prepare = vi.fn(async () => {- order.push('prepare')- return null- })- api.create.mockImplementation(async (r) => {- order.push('create')- return created()- })- mount({ prepare })- setLabel(' Ada ')- click(btn('Create live link'))- await flush()- expect(order).toEqual(['prepare', 'create'])- expect(api.create).toHaveBeenCalledWith({ nodeId: 'n1', role: 'viewer', ttlSeconds: 3600, label: 'Ada', title: 'build' })- // The URL appears in the dialog, and only once created.- expect(document.querySelector<HTMLInputElement>('.live-dialog__url input')!.value).toBe('https://nodeterm.dev/s/abc#1.k')- })-- it('R47: a refused prepare (unsaved canvas, or a conflict) shows the sentence and NEVER calls create', async () => {- mount({ prepare: async () => SAVE_FIRST_MESSAGE })- setLabel('Ada')- click(btn('Create live link'))- await flush()- expect(api.create).not.toHaveBeenCalled()- expect(document.querySelector('.live-dialog__error')!.textContent).toBe(SAVE_FIRST_MESSAGE)- // Not stuck busy: Create works again.- expect(btn('Create live link').disabled).toBe(false)- })-- it('H24: cannot be dismissed while busy — not by Escape, the scrim or Cancel — and can once it is done', async () => {- let release!: (v: string | null) => void- const { onClose } = mount({ prepare: () => new Promise((r) => (release = r)) })- setLabel('Ada')- click(btn('Create live link'))- escape()- click(document.querySelector('.confirm-overlay')!)- click(btn('Cancel'))- expect(onClose).not.toHaveBeenCalled()- await act(async () => release(null))- await flush()- // Done now: Escape closes.- escape()- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('shows the error for a refused create, with Upgrade for not-entitled when offered', async () => {- const onUpgrade = vi.fn()- api.create.mockResolvedValue({ ok: false, error: 'not-entitled' })- mount({ onUpgrade })- setLabel('Ada')- click(btn('Create live link'))- await flush()- expect(document.querySelector('.live-dialog__error')!.textContent).toBe('Live links need an active Pro plan.')- click(btn('Upgrade to Pro'))- expect(onUpgrade).toHaveBeenCalledTimes(1)- })-- it('words `unsupported` for the surface it was opened on, and a rejected create as the network sentence', async () => {- api.create.mockResolvedValue({ ok: false, error: 'unsupported' })- mount({ surface: 'relay' })- setLabel('Ada')- click(btn('Create live link'))- await flush()- expect(document.querySelector('.live-dialog__error')!.textContent).toBe(- 'Live links are created on the machine that runs this terminal.'- )- api.create.mockRejectedValue(new Error('socket'))- click(btn('Create live link'))- await flush()- expect(document.querySelector('.live-dialog__error')!.textContent).toBe(- "Couldn't reach nodeterm's service. Nothing was shared."- )- })-- it('Stop sharing revokes this link and closes; a rejected stop says so and stays open (H23)', async () => {- const { onClose } = mount()- setLabel('Ada')- click(btn('Create live link'))- await flush()- api.revoke.mockRejectedValueOnce(new Error('down'))- click(btn('Stop sharing'))- await flush()- expect(api.revoke).toHaveBeenCalledWith('abc')- expect(onClose).not.toHaveBeenCalled()- expect(document.querySelector('.live-dialog__error')!.textContent).toBe(STOP_FAILED_MESSAGE)- click(btn('Stop sharing'))- await flush()- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('Copy puts the URL on the clipboard', async () => {- mount()- setLabel('Ada')- click(btn('Create live link'))- await flush()- click(btn('Copy link'))- expect(window.nodeTerminal.clipboard.writeText).toHaveBeenCalledWith('https://nodeterm.dev/s/abc#1.k')- })-})--// ---- Control and Unlimited (spec 2026-10-03 §2.7, §3) ---------------------------------------------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 warnings = (): string[] => [...document.querySelectorAll('.live-dialog__warning')].map((e) => e.textContent ?? '')-const exposure = (): string | null => document.querySelector('.live-dialog__exposure')?.textContent ?? null-const GENERATED = /^[0-9abcdefghjkmnpqrstvwxyz]{16}$/-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 — the menus', () => {- it('the role menu lists the three roles, each with what it grants, the current one checked', async () => {- mount()- await flush()- click(trigger('Anyone with the link'))- const items = [...document.querySelectorAll<HTMLButtonElement>('.menu-select__item')]- expect(items.map((b) => b.querySelector('.menu-select__label')!.textContent)).toEqual(['can watch', 'can chat', 'can type'])- expect(items.map((b) => b.querySelector('.menu-select__hint')!.textContent)).toEqual([- 'Sees the terminal',- 'Watches and chats with you',- 'Also types, with a password'- ])- expect(items.map((b) => b.getAttribute('aria-checked'))).toEqual(['true', 'false', 'false'])- })-- it('the expiry menu ends on "never", whose hint says it works until stopped', async () => {- mount()- await flush()- click(trigger('Expires'))- const labels = [...document.querySelectorAll('.menu-select__item .menu-select__label')].map((e) => e.textContent)- expect(labels).toEqual(['in 15 minutes', 'in 1 hour', 'in 8 hours', 'in 24 hours', 'never'])- expect(option('never')!.querySelector('.menu-select__hint')!.textContent).toBe(UNLIMITED_NOTE)- })-- it("Escape in an open menu closes the menu, not the dialog", async () => {- const { onClose } = mount()- await flush()- click(trigger('Expires'))- const focused = document.activeElement!- expect(focused.className).toContain('menu-select__item')- act(() => void focused.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })))- expect(document.querySelector('.menu-select__menu')).toBeNull()- expect(onClose).not.toHaveBeenCalled()- expect(document.activeElement).toBe(trigger('Expires'))- })-})--describe('LiveLinkDialog — Control', () => {- it('picking "can type" fills a generated password and shows the typing warning above the exposure', async () => {- mount()- await flush()- expect(pwInput()).toBeNull()- expect(warnings()).toEqual([])- expect(exposure()).toBe(LIVE_LINK_EXPOSURE)- pickRole('can type')- expect(roleValue()).toBe('can type')- const input = pwInput()!- expect(input.value).toMatch(GENERATED)- expect(input.type).toBe('text')- expect(input.getAttribute('autocomplete')).toBe('off')- expect(input.getAttribute('spellcheck')).toBe('false')- expect(input.maxLength).toBe(128)- // Anyone with the link alone still WATCHES a Control link: the exposure stays, the typing- // warning comes first.- expect(warnings()).toEqual([controlWarningText('this computer')])- expect(document.querySelector('.live-dialog__warning strong')!.textContent).toBe('and')- expect(exposure()).toBe(LIVE_LINK_EXPOSURE)- const order = [...document.querySelectorAll('.live-dialog__warning, .live-dialog__exposure')].map((e) => e.className)- expect(order).toEqual(['live-dialog__warning', 'live-dialog__exposure'])- // Ready to create at once: the generated password passes the rule.- setLabel('Ada')- expect(btn('Create live link').disabled).toBe(false)- // Back to watching: no password row, no typing warning.- pickRole('can watch')- expect(pwInput()).toBeNull()- expect(warnings()).toEqual([])- })-- it('a password already there is kept when "can type" is picked again', async () => {- mount()- await flush()- pickRole('can type')- typeInto(pwInput()!, 'longenough1')- pickRole('can chat')- pickRole('can type')- expect(pwInput()!.value).toBe('longenough1')- })-- it('"New password" replaces it with 16 symbols from crypto.getRandomValues', async () => {- mount()- await flush()- pickRole('can type')- typeInto(pwInput()!, 'longenough1')- const spy = vi.spyOn(crypto, 'getRandomValues')- click(document.querySelector<HTMLButtonElement>('button[aria-label="New password"]')!)- expect(spy).toHaveBeenCalled()- expect(pwInput()!.value).toMatch(GENERATED)- spy.mockRestore()- })-- it('the validation line is tied to the password field (aria-describedby)', async () => {- mount()- await flush()- setLabel('Ada')- pickRole('can type')- expect(pwInput()!.hasAttribute('aria-describedby')).toBe(false)- typeInto(pwInput()!, 'short')- const id = pwInput()!.getAttribute('aria-describedby')!- expect(document.getElementById(id)!.textContent).toBe('Use at least 8 characters.')- expect(document.getElementById(id)!.className).toContain('live-dialog__invalid')- typeInto(pwInput()!, 'longenough1')- expect(pwInput()!.hasAttribute('aria-describedby')).toBe(false)- })-- it('Create stays disabled until the password is acceptable, and says why', async () => {- mount()- await flush()- setLabel('Ada')- pickRole('can type')- const create = (): HTMLButtonElement => btn('Create live link')- const problem = (): string | null => document.querySelector('.live-dialog__invalid')?.textContent ?? null- // Cleared: disabled, nothing nagging yet.- typeInto(pwInput()!, '')- 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("an SSH project's node: the typing warning names the host its shell runs on", async () => {- mount({ remoteNode: true, sshTarget: { user: 'ada', host: 'build.example' } })- await flush()- pickRole('can type')- expect(warnings()).toEqual([controlWarningText('[email protected]')])- expect(warnings()[0]).toContain('run any command on [email protected],')- expect(warnings()[0]).not.toContain('this computer')- })-- it('sends the password only for Control', async () => {- api.create.mockImplementation(async (r) => createWith(r))- mount()- await flush()- setLabel('Ada')- pickRole('can type')- typeInto(pwInput()!, 'longenough1')- // A password typed, then the owner switched to "can chat": nothing of it leaves the dialog.- pickRole('can chat')- 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()- localStorage.removeItem(LIVE_LINK_DEFAULTS_KEY)- mount()- await flush()- setLabel('Ada')- pickRole('can type')- 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("\"can type\" is shown disabled, with the reason as its hint, when the terminal can't take input — asked once", async () => {- api.controlSupport.mockResolvedValue('unsupported')- mount()- await flush()- expect(api.controlSupport).toHaveBeenCalledTimes(1)- expect(api.controlSupport).toHaveBeenCalledWith('n1')- click(trigger('Anyone with the link'))- const off = option('can type')!- expect(off.getAttribute('aria-disabled')).toBe('true')- expect(off.querySelector('.menu-select__hint')!.textContent).toBe(CONTROL_UNSUPPORTED_REASON)- expect(option('can watch')!.hasAttribute('aria-disabled')).toBe(false)- // Clicking it changes nothing.- click(off)- expect(roleValue()).toBe('can watch')- expect(pwInput()).toBeNull()- })-- 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()- click(trigger('Anyone with the link'))- expect(option('can type')!.hasAttribute('aria-disabled'), answer).toBe(false)- expect(option('can type')!.querySelector('.menu-select__hint')!.textContent, answer).not.toBe(CONTROL_UNSUPPORTED_REASON)- }- })-- 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()- pickRole('can type')- typeInto(pwInput()!, 'longenough1')- await act(async () => answer('unsupported'))- expect(roleValue()).toBe('can watch')- expect(pwInput()).toBeNull()- click(trigger('Anyone with the link'))- expect(option('can type')!.getAttribute('aria-disabled')).toBe('true')- })-- 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')- pickRole('can type')- typeInto(pwInput()!, 'longenough1')- choose('Expires', 'never')- 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')- })-- // Final review, Minor 6: a stray click beside the done step must not throw away the only copy of a- // Control link's password. The scrim does nothing until Copy password was pressed; Escape, Done and- // the head's close button still close (deliberate gestures).- it('the done step of a Control link ignores the scrim until Copy password is pressed', async () => {- api.create.mockImplementation(async (r) => createWith(r))- const { onClose } = mount()- await flush()- setLabel('Ada')- pickRole('can type')- typeInto(pwInput()!, 'longenough1')- click(btn('Create live link'))- await flush()- click(document.querySelector('.confirm-overlay')!)- expect(onClose).not.toHaveBeenCalled()- expect(pwInput()!.value).toBe('longenough1')- click(btn('Copy password'))- click(document.querySelector('.confirm-overlay')!)- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('the done step of a Control link: Escape and the close button still close before the password was copied', async () => {- api.create.mockImplementation(async (r) => createWith(r))- const { onClose } = mount()- await flush()- setLabel('Ada')- pickRole('can type')- click(btn('Create live link'))- await flush()- escape()- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('the head close button closes the form, and is disabled while a create is in flight', async () => {- let release!: (v: string | null) => void- const { onClose } = mount({ prepare: () => new Promise((r) => (release = r)) })- await flush()- setLabel('Ada')- click(btn('Create live link'))- const close = document.querySelector<HTMLButtonElement>('.live-dialog__close')!- expect(close.disabled).toBe(true)- await act(async () => release('refused'))- await flush()- click(document.querySelector<HTMLButtonElement>('.live-dialog__close')!)- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('the done step of a watch link closes on the scrim as before', async () => {- const { onClose } = mount()- await flush()- setLabel('Ada')- click(btn('Create live link'))- await flush()- click(document.querySelector('.confirm-overlay')!)- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('closing drops the password: nothing on screen keeps it, nothing stored it', async () => {- api.create.mockImplementation(async (r) => createWith(r))- const { onClose } = mount()- await flush()- setLabel('Ada')- pickRole('can type')- 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()- pickRole('can type')- typeInto(pwInput()!, 'longenough1')- escape()- expect(onClose).toHaveBeenCalledTimes(1)- expect([...document.querySelectorAll('input')].map((i) => i.value)).not.toContain('longenough1')- })-})--describe('LiveLinkDialog — Unlimited', () => {- it('"never" sends ttlSeconds 0', async () => {- mount()- await flush()- setLabel('Ada')- choose('Expires', 'never')- expect(trigger('Expires').textContent).toBe('never')- 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')- choose('Expires', 'never')- 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 tells Control apart by its ROLE', () => {- const done = { phase: 'done', url: 'https://nodeterm.dev/s/x#1.y', linkId: 'x', expiresAt: null } as const- const control = body({ ...done, role: 'controller', password: 'longenough1' })- expect(control).toContain('Anyone with this link and the password can type until you stop it.')- expect(control).toContain('live-dialog__password')- // A password on a non-Control state (none is ever built) shows nothing of it.- const watch = body({ ...done, role: 'viewer', password: 'longenough1' })- expect(watch).toContain('Anyone with this link can watch until you stop it.')- expect(watch).not.toContain('longenough1')- })-- it('the done step of an Unlimited watch link says until it is stopped', () => {- const html = body({ phase: 'done', role: 'viewer', 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')- })-})--// ---- the remembered role and expiry (lib/liveLinkDefaults) -----------------------------------------describe('LiveLinkDialog — remembered choices', () => {- it('the first dialog opens on "can watch" for an hour', async () => {- mount()- await flush()- expect(roleValue()).toBe('can watch')- expect(trigger('Expires').textContent).toBe('in 1 hour')- })-- it('a created link remembers its role and expiry; the next dialog opens on them, Control with a fresh password', async () => {- api.create.mockImplementation(async (r) => createWith(r))- mount()- await flush()- setLabel('Ada')- pickRole('can type')- const first = pwInput()!.value- choose('Expires', 'in 8 hours')- click(btn('Create live link'))- await flush()- expect(JSON.parse(localStorage.getItem(LIVE_LINK_DEFAULTS_KEY)!)).toEqual({ role: 'controller', ttl: 28800 })-- act(() => root.unmount())- root = createRoot(host)- mount()- await flush()- expect(roleValue()).toBe('can type')- expect(trigger('Expires').textContent).toBe('in 8 hours')- // A fresh password, never the last one, and the typing warning is on screen from the start.- expect(pwInput()!.value).toMatch(GENERATED)- expect(pwInput()!.value).not.toBe(first)- expect(warnings()).toEqual([controlWarningText('this computer')])- })-- it('a refused create remembers nothing', async () => {- api.create.mockResolvedValue({ ok: false, error: 'not-entitled' })- mount()- await flush()- setLabel('Ada')- pickRole('can chat')- click(btn('Create live link'))- await flush()- expect(localStorage.getItem(LIVE_LINK_DEFAULTS_KEY)).toBeNull()- })-- it('a remembered Control on a terminal that cannot take input opens on "can watch"', async () => {- localStorage.setItem(LIVE_LINK_DEFAULTS_KEY, JSON.stringify({ role: 'controller', ttl: 3600 }))- api.controlSupport.mockResolvedValue('unsupported')- mount()- await flush()- expect(roleValue()).toBe('can watch')- expect(pwInput()).toBeNull()- })-})diff --git a/src/renderer/components/LiveLinkDialog.tsx b/src/renderer/components/LiveLinkDialog.tsxdeleted file mode 100644index dee1f8f14..000000000--- a/src/renderer/components/LiveLinkDialog.tsx+++ /dev/null@@ -1,523 +0,0 @@-// Create a live link to one terminal. Opened only through `openLiveLink` (lib/liveLinkEntry): the-// availability rule and the Pro gate have already run by the time this mounts.-//-// Figma's share-dialog shape: one row per choice, each reading as a sentence ("Anyone with the link-// can watch", "Expires in 1 hour"), the choices in small menus instead of radio lists.-//-// The warning is always visible (not a checkbox): the owner must read what a link exposes every-// time, because "the screen" includes whatever is printed next.-//-// 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, useId, useRef, useState } from 'react'-import { createPortal } from 'react-dom'-import { useDialogStack } from './dialog-stack'-import { IconClock, IconClose, IconLock, IconReload, IconUser, IconWeb } from './icons'-import { MenuSelect } from './MenuSelect'-import { newControlPassword, PasswordField, useCopied } from './LiveLinkPassword'-import {- capUnits,- CONTROL_UNSUPPORTED_REASON,- controlWarning,- controlWarningMachine,- createErrorMessage,- formatUntil,- LIVE_LINK_EXPOSURE,- PASSWORD_SEPARATE_NOTE,- PASSWORD_SHOWN_ONCE,- passwordProblemText,- ROLE_CHOICE,- ROLE_ORDER,- SAVE_FIRST_MESSAGE,- TTL_OPTIONS,- watchableOnlyWhileOpen,- watchWhileOpenNote,- type LiveLinkSurface-} from '../lib/liveLink'-import { loadLiveLinkDefaults, saveLiveLinkDefaults } from '../lib/liveLinkDefaults'-import { stopLiveLinks } from '../lib/liveLinkEntry'-import { loadIdentity } from '../state/presence'-import {- LABEL_MAX,- stripBidiControls,- type CreateWatchLinkRequest,- type WatchLinkRole,- type WatchLinkTtl-} from '@shared/watch-link-types'--/** Spec §2.7's typing warning, its "and" stressed. Text only: the machine is our own wording. */-function ControlWarning({ machine }: { machine: string }): React.JSX.Element {- const [before, and, after] = controlWarning(machine)- return (- <p className="live-dialog__warning">- {before}- <strong>{and}</strong>- {after}- </p>- )-}--/** The dialog's head: the node's title and a close button (which every dismissal rule still owns). */-function DialogHead(p: { title: string; onClose: () => void; disabled?: boolean }): React.JSX.Element {- return (- <div className="live-dialog__head">- <p className="live-dialog__title" title={p.title}>- Share “{p.title}”- </p>- <button type="button" className="live-dialog__close" aria-label="Close" disabled={p.disabled} onClick={p.onClose}>- <IconClose />- </button>- </div>- )-}--export type DialogState =- | {- phase: 'form'- role: WatchLinkRole- ttl: WatchLinkTtl- label: 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- error: string | null- /** The error is `not-entitled`: offer Upgrade (when the caller can — never on the Server- * Edition, which passes no `onUpgrade`). */- offerUpgrade?: boolean- }- | {- phase: 'done'- /** The link's role: the done step reads Control off THIS, never off whether a password is set. */- role: WatchLinkRole- url: string- 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?: string- stopping?: boolean- error?: string | null- }--export function LiveLinkDialogBody(p: {- title: string- state: DialogState- onChange: (s: DialogState) => void- onSubmit: () => void- onClose: () => void- onStop: (linkId: string) => void- onCopy?: (url: string) => void- onCopyPassword?: (password: string) => void- /** The "Copied!" flashes of the link's and the password's Copy buttons. */- copied?: boolean- passwordCopied?: boolean- onUpgrade?: () => 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- /** Where a controller's commands would run, for the typing warning (`controlWarningMachine`).- * Absent: this machine. */- controlMachine?: string- /** 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- /** "now" for the end's day (tomorrow, a weekday): the caller's clock. */- now?: number-}): React.JSX.Element {- const s = p.state- // The id for aria-describedby: the password's validation line.- const invalidId = useId()- // The title is the node's own (git-shared, hand-editable): shown as TEXT, bidi controls stripped.- const title = stripBidiControls(p.title)- if (s.phase === 'done') {- const control = s.role === 'controller'- const until = formatUntil(s.expiresAt, p.now ?? Date.now())- return (- <div className="confirm live-dialog" onClick={(e) => e.stopPropagation()}>- <DialogHead title={title} onClose={p.onClose} disabled={!!s.stopping} />- <p className="live-dialog__status">- <span className="live-dialog__dot" aria-hidden="true" />- {control- ? `Anyone with this link and the password can type until ${until}.`- : `Anyone with this link can watch until ${until}.`}- </p>- <div className="live-dialog__url">- <input- className="confirm__input"- readOnly- aria-label="Live link"- value={s.url}- onFocus={(e) => e.currentTarget.select()}- />- {/* Keyboard focus lands here once the link exists (D2/M3): Enter copies it. */}- <button className="confirm__btn primary live-dialog__copy" data-autofocus="" onClick={() => p.onCopy?.(s.url)}>- {p.copied ? 'Copied!' : 'Copy link'}- </button>- </div>- {control && (- <>- <div className="live-dialog__url live-dialog__password">- <PasswordField value={s.password ?? ''} readOnly />- <button className="confirm__btn live-dialog__copy" onClick={() => p.onCopyPassword?.(s.password ?? '')}>- {p.passwordCopied ? 'Copied!' : 'Copy password'}- </button>- </div>- <p className="live-dialog__note">- {PASSWORD_SHOWN_ONCE} {PASSWORD_SEPARATE_NOTE}- </p>- </>- )}- {s.error && (- <p className="live-dialog__error" role="alert">- {s.error}- </p>- )}- <div className="confirm__actions live-dialog__actions">- <button className="confirm__btn live-dialog__stop" disabled={!!s.stopping} onClick={() => p.onStop(s.linkId)}>- Stop sharing- </button>- <button className="confirm__btn" onClick={p.onClose}>- Done- </button>- </div>- </div>- )- }- const control = s.role === 'controller'- const problem = control ? passwordProblemText(s.password) : null- // Nothing nags an empty field: Create is disabled, which says enough until something is typed.- const showProblem = s.password !== '' && problem !== null- const roleOptions = ROLE_ORDER.map((r) => {- const off = r === 'controller' && !!p.controlUnsupported- return { value: r, label: ROLE_CHOICE[r].label, hint: off ? CONTROL_UNSUPPORTED_REASON : ROLE_CHOICE[r].hint, disabled: off }- })- // Picking Control fills a generated password when there is none yet, so the fast path is two- // clicks; a password already there (typed, or kept from switching away and back) is left alone.- const setRole = (role: WatchLinkRole): void =>- p.onChange({ ...s, role, password: role === 'controller' && s.password === '' ? newControlPassword() : s.password })- return (- <div className="confirm live-dialog" onClick={(e) => e.stopPropagation()}>- <DialogHead title={title} onClose={p.onClose} disabled={s.busy} />- <div className="live-dialog__rows">- <div className="live-dialog__row">- <span className="live-dialog__icon" aria-hidden="true">- <IconWeb />- </span>- <span className="live-dialog__row-label">Anyone with the link</span>- {/* Keyboard focus lands here when the dialog opens (D2/M3): keys stay inside the dialog- instead of reaching the canvas behind it. */}- <MenuSelect- label="Anyone with the link"- value={s.role}- options={roleOptions}- onChange={setRole}- disabled={s.busy}- autoFocus- />- </div>- {control && (- <div className="live-dialog__row live-dialog__password">- <span className="live-dialog__icon" aria-hidden="true">- <IconLock />- </span>- <span className="live-dialog__row-label">Password</span>- <PasswordField- value={s.password}- disabled={s.busy}- describedBy={showProblem ? invalidId : undefined}- onChange={(v) => p.onChange({ ...s, password: v })}- />- <button- type="button"- className="live-dialog__icon-btn"- aria-label="New password"- title="Generate a new password"- disabled={s.busy}- onClick={() => p.onChange({ ...s, password: newControlPassword() })}- >- <IconReload />- </button>- </div>- )}- {showProblem && (- <p className="live-dialog__invalid" id={invalidId}>- {problem}- </p>- )}- <div className="live-dialog__row">- <span className="live-dialog__icon" aria-hidden="true">- <IconClock />- </span>- <span className="live-dialog__row-label">Expires</span>- <MenuSelect- label="Expires"- value={s.ttl}- options={TTL_OPTIONS}- onChange={(ttl: WatchLinkTtl) => p.onChange({ ...s, ttl })}- disabled={s.busy}- />- </div>- <label className="live-dialog__row live-dialog__label">- <span className="live-dialog__icon" aria-hidden="true">- <IconUser />- </span>- <span className="live-dialog__row-label">Viewers see you as</span>- <input- className="confirm__input"- maxLength={LABEL_MAX}- value={s.label}- disabled={s.busy}- onChange={(e) => p.onChange({ ...s, label: e.target.value })}- />- </label>- </div>- {/* Typing first (the stronger claim), then what WATCHING exposes, which holds for every role:- a Control link is watched by anyone with the link alone. */}- {control && <ControlWarning machine={p.controlMachine ?? controlWarningMachine(null)} />}- <p className="live-dialog__exposure">{LIVE_LINK_EXPOSURE}</p>- {p.whileOpenNote && <p className="live-dialog__note">{p.whileOpenNote}</p>}- {s.error && (- <p className="live-dialog__error" role="alert">- {s.error}- </p>- )}- <div className="confirm__actions">- {s.error && s.offerUpgrade && p.onUpgrade && (- <button className="confirm__btn" onClick={p.onUpgrade}>- Upgrade to Pro- </button>- )}- <button className="confirm__btn" disabled={s.busy} onClick={p.onClose}>- Cancel- </button>- <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>- </div>- )-}--export function LiveLinkDialog({- nodeId,- title,- surface,- remoteNode = false,- sshTarget,- readPersistence,- prepare,- onUpgrade,- onClose-}: {- nodeId: string- title: string- /** Where it was opened — decides how `unsupported` reads (H1). */- surface: LiveLinkSurface- /** The node runs on an SSH project's host, whose own tmux gives a viewer a client of its own (R63). */- remoteNode?: boolean- /** That SSH project's server, so the Control warning names the machine a controller's commands- * run on (`user@host`). Absent: a local node — this machine. */- sshTarget?: { user: string; host: string } | null- /** R63: the LOCAL core's session-protection status (`localSession.api.pty.tmuxStatus` — the core that- * creates the link, never a relay peer's). Absent, rejected or unreadable: no note (unknown claims- * nothing). */- readPersistence?: () => Promise<{ persistence?: { enabled: boolean; backend: string | null } | null } | null>- /** R47: publish pending canvas edits before core looks the node up. A sentence = do NOT create. */- prepare: () => Promise<string | null>- /** Absent on the Server Edition (R43): no Upgrade button there. */- onUpgrade?: () => void- onClose: () => void-}): React.JSX.Element {- // Opens on the role and expiry of the last link this person created (lib/liveLinkDefaults). A- // remembered Control opens with a fresh generated password, as picking it does.- const [state, setState] = useState<DialogState>(() => {- const d = loadLiveLinkDefaults()- return {- phase: 'form',- role: d.role,- ttl: d.ttl,- label: capUnits(loadIdentity()?.name ?? '', LABEL_MAX),- password: d.role === 'controller' ? newControlPassword() : '',- busy: false,- error: null- }- })- // The latest state for the async steps (a closure would see the render that started them).- const stateRef = useRef(state)- stateRef.current = state- const isTop = useDialogStack()- const [copied, copy] = useCopied()- const [passwordCopied, copyPassword] = useCopied()- // R63: does THIS machine have a watcher client for this node? Read once from the local core (the- // core that creates the link). Unknown — not read yet, or unreadable — says nothing.- const [whileOpenOnly, setWhileOpenOnly] = useState(false)- useEffect(() => {- if (!readPersistence) return- let live = true- Promise.resolve()- .then(() => readPersistence())- .then(- (st) => {- if (live) setWhileOpenOnly(watchableOnlyWhileOpen({ persistence: st?.persistence, remoteNode }))- },- () => {}- )- return () => {- 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 role menu on open, Copy link once created — so keys stay inside- // it (a bare-key canvas command could otherwise fire behind the overlay).- const panelRef = useRef<HTMLDivElement>(null)- useEffect(() => {- panelRef.current?.querySelector<HTMLElement>('[data-autofocus]')?.focus({ preventScroll: true })- }, [state.phase])-- const busy = state.phase === 'form' && state.busy- // 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.current- if (s.phase === 'form' && s.busy) return- const dropped: DialogState = s.phase === 'form' ? { ...s, password: '' } : { ...s, password: undefined }- stateRef.current = dropped- setState(dropped)- onClose()- }, [onClose])-- // A Control link's done step holds the ONLY copy of its password (core keeps a hash): a stray click- // beside the dialog must not throw it away. The scrim does nothing there until Copy password was- // pressed; Escape and Done still close — those are deliberate.- const passwordCopiedRef = useRef(false)- const scrimClick = useCallback(() => {- const s = stateRef.current- if (s.phase === 'done' && s.role === 'controller' && !passwordCopiedRef.current) return- dismiss()- }, [dismiss])- const onCopyPassword = useCallback(- (pw: string) => {- passwordCopiedRef.current = true- copyPassword(pw)- },- [copyPassword]- )-- useEffect(() => {- const onKey = (e: KeyboardEvent): void => {- if (e.key === 'Escape' && isTop()) dismiss()- }- window.addEventListener('keydown', onKey)- return () => window.removeEventListener('keydown', onKey)- }, [isTop, dismiss])-- const submit = async (): Promise<void> => {- const s = stateRef.current- if (s.phase !== 'form' || s.busy) return- const form = { ...s, busy: true, error: null, offerUpgrade: false }- setState(form)- const fail = (error: string, offerUpgrade = false): void =>- setState({ ...form, busy: false, error, offerUpgrade })- let refused: string | null- try {- refused = await prepare()- } catch {- // `liveLinkPrepare` answers instead of throwing; a throw is still "the save did not land".- 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(req)- if (r.ok) {- saveLiveLinkDefaults({ role: form.role, ttl: form.ttl })- setState({- phase: 'done',- role: form.role,- 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))- }- }-- const stop = async (linkId: string): Promise<void> => {- const s = stateRef.current- if (s.phase !== 'done' || s.stopping) return- setState({ ...s, stopping: true, error: null })- const ok = await stopLiveLinks(- () => window.nodeTerminal.watchLink.revoke(linkId),- (error) => setState({ ...s, stopping: false, error })- )- if (ok) onClose()- }-- return createPortal(- <div className="confirm-overlay" ref={panelRef} onClick={scrimClick}>- <LiveLinkDialogBody- title={title}- whileOpenNote={whileOpenOnly ? watchWhileOpenNote() : null}- state={state}- onChange={(next) => {- if (!busy) setState(next)- }}- onSubmit={() => void submit()}- onClose={dismiss}- onStop={(id) => void stop(id)}- onCopy={copy}- onCopyPassword={onCopyPassword}- copied={copied}- passwordCopied={passwordCopied}- onUpgrade={onUpgrade}- controlUnsupported={controlUnsupported}- controlMachine={controlWarningMachine(sshTarget)}- />- </div>,- document.body- )-}diff --git a/src/renderer/components/LiveLinkPassword.tsx b/src/renderer/components/LiveLinkPassword.tsxdeleted file mode 100644index 78773f8c7..000000000--- a/src/renderer/components/LiveLinkPassword.tsx+++ /dev/null@@ -1,62 +0,0 @@-// A Control link's password field and its generator — shared by the create dialog, the chip's popover-// and the Live chat drawer. The plaintext only ever lives in the state of the component that shows-// it; nothing here stores, logs or announces it. Core keeps only a hash.-import { useCallback, useEffect, useRef, useState, type Ref } from 'react'-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)))-}--/** A password field: plain text (the owner must be able to read what they send), no autocomplete or- * spell check, capped at the unlock cast's limit. Read-only selects its text on focus. */-export function PasswordField(p: {- value: string- readOnly?: boolean- disabled?: boolean- onChange?: (v: string) => void- label?: string- /** The id of the line that explains what is wrong with it (aria-describedby); absent when nothing is. */- describedBy?: string- inputRef?: Ref<HTMLInputElement>-}): React.JSX.Element {- return (- <input- ref={p.inputRef}- className="confirm__input"- type="text"- autoComplete="off"- spellCheck={false}- maxLength={PASSWORD_MAX}- aria-label={p.label ?? 'Password'}- aria-describedby={p.describedBy}- 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}- />- )-}--/** How long a copy button reads "Copied!". */-export const COPIED_FLASH_MS = 1500--/**- * A copy button's "Copied!" flash: `copy(text)` puts the text on the clipboard and flips `copied`- * for `COPIED_FLASH_MS`; a second copy restarts the flash. The timer dies with the component.- */-export function useCopied(): [boolean, (text: string) => void] {- const [copied, setCopied] = useState(false)- const timer = useRef<ReturnType<typeof setTimeout>>()- useEffect(() => () => clearTimeout(timer.current), [])- const copy = useCallback((text: string) => {- window.nodeTerminal.clipboard.writeText(text)- setCopied(true)- clearTimeout(timer.current)- timer.current = setTimeout(() => setCopied(false), COPIED_FLASH_MS)- }, [])- return [copied, copy]-}diff --git a/src/renderer/components/LiveLinkPopover.tsx b/src/renderer/components/LiveLinkPopover.tsxdeleted file mode 100644index 19db7137e..000000000--- a/src/renderer/components/LiveLinkPopover.tsx+++ /dev/null@@ -1,408 +0,0 @@-import { memo, useCallback, 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 { stripBidiControls } from '@shared/watch-link-types'-import { CHAT_TEXT_MAX, type WatchChatMessage } from '@shared/watch-link/protocol'-import { useDialogStack } from './dialog-stack'-import { useCopied } from './LiveLinkPassword'-import { ControlHold, ControlSection, hasChat, kickViewer, type ControlHoldKind } from './LiveLinkControls'-import { useMenuFlip } from '../ui/useMenuFlip'-import {- CHAT_NOT_SENT_MESSAGE,- commentFromChat,- formatClock,- formatRemaining,- kickNote,- ROLE_LABEL,- ROLE_NAME,- statusLine,- STOP_FAILED_MESSAGE,- viewerName,- waitingViewers-} from '../lib/liveLink'-import { thisMachine } from '../lib/machineName'-import { EMPTY_LINKS, useLinkThread, useWatchLinks } from '../state/watchLinks'-import { useBoardLog } from '../state/boardLog'-import { useProjects } from '../state/projects'-import { sessionForProject } from '../session/session'--/** Where the chip was when it was clicked (screen coordinates). */-export interface PopoverAnchor {- top: number- bottom: number- left: number-}--const EMPTY_CHAT: WatchChatMessage[] = []--const stop = (e: React.SyntheticEvent): void => e.stopPropagation()-/**- * The popover is a body portal, but its React events still bubble through the REACT tree — into the- * chip's surface: a card that opens on click and drags, a node header, a sessions row that ends the- * session on a middle click, the canvas's own window listeners (React stops a synthetic event at the- * portal's container, before the window). So every event is stopped at the portal's two roots, the- * scrim and the panel — and only there: the chip itself lets keys and drags through (LiveLinkChip).- */-const ISOLATE = {- onClick: stop,- onDoubleClick: stop,- onMouseDown: stop,- onMouseUp: stop,- onPointerDown: stop,- onPointerUp: stop,- onContextMenu: stop,- onKeyDown: stop,- onKeyUp: stop,- onDragStart: stop,- onDragOver: stop,- onDrop: stop,- onWheel: stop,- onFocus: stop,- onBlur: stop,- onChange: stop,- onInput: stop,- onSubmit: stop-} as const--function useNow(ms: number): number {- const [now, setNow] = useState(() => Date.now())- useEffect(() => {- const t = setInterval(() => setNow(Date.now()), ms)- return () => clearInterval(t)- }, [ms])- return now-}--/**- * The board a copied chat line goes to: the first project on THIS machine that holds the node. A- * relay tab's project can carry the same node id (a git-shared canvas opened here and over the- * relay), and its board belongs to the other machine, so it is skipped.- */-function commentTarget(nodeId: string): { projectId: string; api: NodeTerminalApi } | null {- for (const p of useProjects.getState().projects) {- if (!p.nodes.some((n) => n.id === nodeId)) continue- const session = sessionForProject(p.id)- if (session.source === 'relay') continue- return { projectId: p.id, api: session.api }- }- return null-}--/**- * 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`).- */-export function LiveLinkPopover({- nodeId,- anchor,- onClose-}: {- nodeId: string- anchor: PopoverAnchor- onClose: () => void-}): React.JSX.Element {- const links = useWatchLinks((s) => s.byNode[nodeId] ?? EMPTY_LINKS)- const isTop = useDialogStack()- const now = useNow(30_000)- // Below the chip; above it when there is no room below (the dropdown case of useMenuFlip).- const flip = useMenuFlip(anchor.bottom + 6, anchor.left, anchor.top - 6)- // Holds (see `ControlHold`): a counter, not state — nothing renders from it.- const holds = useRef(0)- // Only a save holds the popover: it has no link to switch away from, and a password on screen does- // not keep the owner from closing it (`ControlHoldKind`).- const hold = useCallback((kind: ControlHoldKind = 'save'): (() => void) => {- if (kind !== 'save') return () => {}- holds.current++- let released = false- return () => {- if (released) return- released = true- holds.current--- }- }, [])- /** Close unless something is held; says whether it closed. Every owner gesture comes here. */- const requestClose = useCallback((): boolean => {- if (holds.current > 0) return false- onClose()- return true- }, [onClose])- useEffect(() => {- const onKey = (e: KeyboardEvent): void => {- if (e.key !== 'Escape' || !isTop()) return- // Swallowed even while held: the Escape was meant for the popover, not what is behind it.- e.preventDefault()- e.stopPropagation()- requestClose()- }- // Capture phase: beat the canvas/global keydown listeners (and xterm) to the Escape.- window.addEventListener('keydown', onKey, true)- return () => window.removeEventListener('keydown', onKey, true)- }, [isTop, requestClose])- useEffect(() => {- if (links.length === 0) onClose()- }, [links.length, onClose])- // Keyboard users land IN the popover (a body portal, so Tab from the chip would never reach it),- // and go back to the chip when it closes.- const popRef = flip.ref- useEffect(() => {- const before = document.activeElement instanceof HTMLElement ? document.activeElement : null- popRef.current?.focus({ preventScroll: true })- return () => {- if (before?.isConnected) before.focus({ preventScroll: true })- }- }, [popRef])- return createPortal(- <>- <div- {...ISOLATE}- className="live-pop__scrim"- onClick={(e) => {- e.stopPropagation()- requestClose()- }}- onContextMenu={(e) => {- e.preventDefault()- e.stopPropagation()- requestClose()- }}- />- <div- {...ISOLATE}- ref={flip.ref}- className="live-pop nodrag nowheel"- style={{ top: flip.top, left: flip.left }}- role="dialog"- aria-label="Live links"- tabIndex={-1}- >- <ControlHold.Provider value={hold}>- {links.map((l) => (- <LinkBlock key={l.linkId} link={l} now={now} nodeId={nodeId} requestClose={requestClose} />- ))}- </ControlHold.Provider>- </div>- </>,- document.body- )-}--const LinkBlock = memo(function LinkBlock({- link,- now,- nodeId,- requestClose-}: {- link: WatchLinkView- now: number- nodeId: string- /** Close the popover unless something in it is held; true when it closed. */- requestClose: () => boolean-}): React.JSX.Element {- const api = window.nodeTerminal.watchLink- const [copied, copy] = useCopied()- const [error, setError] = useState<string | null>(null)- const status = statusLine(link)- const waiting = waitingViewers([link]) > 0- return (- <section className="live-pop__link" data-link-id={link.linkId}>- <header className="live-pop__head">- <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">- Shown to viewers as {stripBidiControls(link.label)}- </p>- {status && (- <p className={`live-pop__status live-pop__status--${link.status === 'live' && waiting ? 'waiting' : link.status}`} role="status">- {status}- </p>- )}- <div className="live-pop__actions">- <button- type="button"- className="confirm__btn live-pop__btn"- onClick={() => copy(link.url)}- >- {copied ? 'Copied!' : 'Copy link'}- </button>- {hasChat(link.role) && (- <button- type="button"- className="confirm__btn live-pop__btn"- onClick={() => {- // The Live chat drawer (Canvas) listens; the popover gives way to it — unless a new- // password is still on its way to being shown here.- if (!requestClose()) return- window.dispatchEvent(new CustomEvent('nodeterm:live-chat', { detail: { linkId: link.linkId } }))- }}- >- Open chat- </button>- )}- <button- type="button"- className="confirm__btn danger live-pop__btn"- onClick={() => {- setError(null)- // Desktop: the local stop is immediate and the state push removes this block. The- // Server Edition rejects when its socket is down — say so instead of looking stopped.- api.revoke(link.linkId).catch(() => setError(STOP_FAILED_MESSAGE))- }}- >- Stop sharing- </button>- </div>- {error && (- <p className="live-pop__error" role="alert">- {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>- ) : (- <>- <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- type="button"- className="confirm__btn live-pop__btn live-pop__kick"- title={kickNote(v)}- onClick={() => kickViewer(api, link.linkId, v.viewerId, setError)}- >- Kick- </button>- </li>- ))}- </ul>- {/* While anyone controls, the note also says a kicked controller can unlock again. */}- <p className="live-pop__muted live-pop__note">{kickNote({ controlling: link.viewers.some((v) => v.controlling) })}</p>- </>- )}- </div>- {hasChat(link.role) && <ChatThread linkId={link.linkId} nodeId={nodeId} />}- </section>- )-})--/** A Commenter or Control link's thread with the owner's reply box (the drawer has its own look). */-function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string }): React.JSX.Element {- const api = window.nodeTerminal.watchLink- const chat = useWatchLinks((s) => s.chats[linkId] ?? EMPTY_CHAT)- const onBoard = useProjects((s) => s.projects.some((p) => p.nodes.some((n) => n.id === nodeId)))- const [draft, setDraft] = useState('')- const [copiedIds, setCopiedIds] = useState<ReadonlySet<string>>(() => new Set())- const [copyError, setCopyError] = useState(false)- const [sendError, setSendError] = useState(false)- const threadRef = useRef<HTMLOListElement>(null)- // On screen = read, and core's history asked once (the thread rule, shared with the drawer).- useLinkThread(linkId, api)- // Follow the newest message. Keyed on the LAST message's id, not the length — at the 200-message- // cap the length stops changing.- const lastId = chat.length > 0 ? chat[chat.length - 1].id : ''- useEffect(() => {- const el = threadRef.current- if (el) el.scrollTop = el.scrollHeight- }, [lastId])- return (- <div className="live-pop__chat">- {chat.length === 0 ? (- <p className="live-pop__muted">No messages yet. Viewers of this link can chat with you here.</p>- ) : (- <ol className="live-pop__thread" ref={threadRef}>- {chat.map((m) => (- <li key={m.id} className={`live-pop__msg${m.from === 'sharer' ? ' live-pop__mine' : ''}`}>- <span className="live-pop__who">{stripBidiControls(m.name)}</span>{' '}- <span className="live-pop__muted">({m.from === 'sharer' ? 'sharer' : 'link viewer'})</span>- <span className="live-pop__text">{stripBidiControls(m.text)}</span>- {onBoard && m.from === 'viewer' && (- <button- type="button"- className="live-pop__copy"- disabled={copiedIds.has(m.id)}- onClick={() => {- const target = commentTarget(nodeId)- if (!target) {- setCopyError(true)- return- }- setCopyError(false)- useBoardLog.getState().append(target.api, target.projectId, {- kind: 'comment',- nodeId,- text: commentFromChat(m)- })- setCopiedIds((s) => new Set(s).add(m.id))- }}- >- {copiedIds.has(m.id) ? 'Copied to card comments' : 'Copy to card comments'}- </button>- )}- </li>- ))}- </ol>- )}- {copyError && (- <p className="live-pop__error" role="alert">- No project on {thisMachine()} holds this terminal, so there is no card to comment on.- </p>- )}- {sendError && (- <p className="live-pop__error" role="alert">- {CHAT_NOT_SENT_MESSAGE}- </p>- )}- <form- className="live-pop__reply"- onSubmit={(e) => {- e.preventDefault()- const text = draft.trim()- if (!text) return- setSendError(false)- // The reply comes back through the chat push (core echoes the owner's own message), so- // nothing is added here. The box is cleared only once core took it (unless the owner has- // typed on since); a null answer (no host for the link, or nothing left after cleaning) or- // a rejection keeps the draft and says so.- api.sendChat(linkId, text).then(- (sent) => {- if (sent) setDraft((d) => (d.trim() === text ? '' : d))- else setSendError(true)- },- () => setSendError(true)- )- }}- >- <input- className="confirm__input live-pop__input"- value={draft}- maxLength={CHAT_TEXT_MAX}- placeholder="Reply to viewers…"- aria-label="Reply to viewers"- onChange={(e) => setDraft(e.target.value)}- />- <button type="submit" className="confirm__btn live-pop__btn" disabled={!draft.trim()}>- Send- </button>- </form>- </div>- )-}diff --git a/src/renderer/components/ProjectLimitDialog.tsx b/src/renderer/components/ProjectLimitDialog.tsxindex 1d7bb7941..b26094738 100644--- a/src/renderer/components/ProjectLimitDialog.tsx+++ b/src/renderer/components/ProjectLimitDialog.tsx@@ -11,8 +11,8 @@ import { useDialogStack } from './dialog-stack'/*** The free-tier limit moment (docs/project-limit.md): the dialog the open gate* (lib/projectLimitGate.ts) shows when a new open would go past the allowance, plus the brief- * "Checking…" panel while a person's claim is in flight. Mounted once, in Canvas, beside- * `UpgradeDialog`; it renders only what `useProjectLimit` asks for.+ * "Checking…" panel while a person's claim is in flight. Mounted once, in Canvas; it renders only+ * what `useProjectLimit` asks for.** THE RULE: every way out of a dialog goes through `resolveDialog` — Cancel, an overlay click,* Escape, the automatic `proceed`, Pro arriving, and this component unmounting while one is up. Thediff --git a/src/renderer/components/SessionRow.test.tsx b/src/renderer/components/SessionRow.test.tsxindex a1abe7b3d..f63be0d3d 100644--- a/src/renderer/components/SessionRow.test.tsx+++ b/src/renderer/components/SessionRow.test.tsx@@ -23,7 +23,6 @@ describe('SessionRow status age', () => {const html = renderToStaticMarkup(<SessionRowrow={row}- liveLinkSource="local"stateAgeLabel="5m ago"onClick={vi.fn()}onClose={vi.fn()}@@ -47,7 +46,6 @@ describe('SessionRow icon', () => {renderToStaticMarkup(<SessionRowrow={{ ...row, icon }}- liveLinkSource="local"onClick={vi.fn()}onClose={vi.fn()}onRename={vi.fn()}diff --git a/src/renderer/components/SessionRow.tsx b/src/renderer/components/SessionRow.tsxindex 146c7d303..99363c687 100644--- a/src/renderer/components/SessionRow.tsx+++ b/src/renderer/components/SessionRow.tsx@@ -1,7 +1,5 @@import { useState } from 'react'import { AccountChip, useAccountChip } from './AccountChip'-import { LiveLinkChip } from './LiveLinkChip'-import type { SessionSource } from '../session/session'import { IconBellFilled, IconCircleCheck, IconClose } from './icons'import { NodeIconView } from './NodeIcon'import { ProjectGlyph } from './ProjectGlyph'@@ -23,9 +21,6 @@ export interface SessionRowProps {onDragEnd(): void/** Status-group mode only: elapsed time since the current state began. */stateAgeLabel?: string- /** The session this row's PROJECT belongs to (`projectSessionSource`): only a local one shows- * this machine's LIVE chip — a relay tab's node with the same id is not ours (R57). */- liveLinkSource: SessionSource | null}function dirName(p?: string): string {@@ -43,8 +38,7 @@ export function SessionRow({onContextMenu,onDragStart,onDragEnd,- stateAgeLabel,- liveLinkSource+ stateAgeLabel}: SessionRowProps): JSX.Element {const [editing, setEditing] = useState(false)const [draft, setDraft] = useState(row.title)@@ -163,7 +157,6 @@ export function SessionRow({</span>)}<AccountChip chip={accountChip} className="ss-account" />- <LiveLinkChip nodeId={row.id} source={liveLinkSource} className="ss-live" />{row.loop && (<span className="ss-loop">{row.loop.kind} · {row.loop.count}diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsxindex 200db978b..7dd16b0a5 100644--- a/src/renderer/components/SessionsSidebar.tsx+++ b/src/renderer/components/SessionsSidebar.tsx@@ -21,7 +21,6 @@ import {} from '../lib/sessionList'import { sidebarEmptyState, sidebarFilterKeyAction } from '../lib/sidebarFilter'import { SessionRow } from './SessionRow'-import { projectSessionSource } from '../lib/projectSessionSource'import { ProjectGlyph } from './ProjectGlyph'import { ClosedHistorySection } from './ClosedHistorySection'import { IconBellFilled, IconCircleCheck, IconClose, IconPin } from './icons'@@ -314,7 +313,6 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null><SessionRowrow={row}- liveLinkSource={projectSessionSource(projectId)}onClick={() => props.onFocusNode(row.id)}onClose={() => props.onCloseSession(projectId, row.id)}onRename={(title) => props.onRenameSession(projectId, row.id, title)}@@ -510,7 +508,6 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null<div key={row.id} className="ss-rowdrop"><SessionRowrow={row}- liveLinkSource={projectSessionSource(row.projectId!)}onClick={() => props.onFocusNode(row.id)}onClose={() => props.onCloseSession(row.projectId!, row.id)}onRename={(title) => props.onRenameSession(row.projectId!, row.id, title)}diff --git a/src/renderer/components/UpgradeDialog.test.tsx b/src/renderer/components/UpgradeDialog.test.tsxdeleted file mode 100644index 9976224a5..000000000--- a/src/renderer/components/UpgradeDialog.test.tsx+++ /dev/null@@ -1,86 +0,0 @@-// @vitest-environment jsdom-//-// The Pro upgrade prompt. Only live links open it today, yet its body never mentioned them, and it-// still promised "unlimited remote access from your phone" months after the relay quota was removed.-// The body is pinned verbatim, and it names unlimited open projects only while the free-tier limit-// is on (docs/project-limit.md: no "unlimited" claim the limit would contradict — and, inactive, no-// claim about a limit that does not exist).-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { act } from 'react'-import { createRoot, type Root } from 'react-dom/client'-import { pinNeutralMachineNoun } from '@renderer/lib/testMachineNoun'-import { INACTIVE_PROJECT_LIMIT, type ProjectLimitState } from '@shared/project-limit'--// The project-limit store subscribes to `window.nodeTerminal.projectLimit.onChange` when it is-// created, so the bridge must exist before any import runs.-vi.hoisted(() => {- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {- projectLimit: { state: vi.fn(), claim: vi.fn(), onChange: () => () => {} }- }-})-// The real entitlement store pulls in the license bridge; the dialog only reads `isPremium` and-// calls `upgrade`.-vi.mock('../state/entitlement', async () => {- const { create } = await import('zustand')- return { useEntitlement: create(() => ({ isPremium: false, upgrade: async () => {} })) }-})--import { UpgradeDialog } from './UpgradeDialog'-import { useUpgradeGate } from '../state/upgradeGate'-import { useProjectLimit } from '../state/projectLimit'--;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true--pinNeutralMachineNoun()--const ACTIVE: ProjectLimitState = { active: true, pro: false, free: 5, allowance: null, dnt: false }--const INACTIVE_BODY =- 'Pro adds live links to a terminal (watch, chat, or let people type), 3 team seats to share this computer, the larger on-device dictation models, and nodeterm mobile Pro. Complete your purchase in the browser — Pro unlocks here automatically.'-const ACTIVE_BODY =- 'Pro adds unlimited open projects, live links to a terminal (watch, chat, or let people type), 3 team seats to share this computer, the larger on-device dictation models, and nodeterm mobile Pro. Complete your purchase in the browser — Pro unlocks here automatically.'--let root: Root-let host: HTMLElement--beforeEach(() => {- host = document.createElement('div')- document.body.appendChild(host)- root = createRoot(host)-})--afterEach(() => {- act(() => root.unmount())- host.remove()- useUpgradeGate.setState({ open: false, feature: '' })- useProjectLimit.setState({ state: INACTIVE_PROJECT_LIMIT })-})--/** Open the dialog for a live link (the one feature that opens it) and return its two lines. */-function render(state: ProjectLimitState): string[] {- useProjectLimit.setState({ state })- useUpgradeGate.setState({ open: true, feature: 'Live links' })- act(() => root.render(<UpgradeDialog />))- // The dialog portals into document.body, not into `host`.- return [...document.body.querySelectorAll('.confirm__msg')].map((p) => p.textContent ?? '')-}--describe('UpgradeDialog', () => {- it('names the gated feature', () => {- expect(render(INACTIVE_PROJECT_LIMIT)[0]).toBe('Live links is a Pro feature')- })-- it('limit inactive: lists live links and dictation, and says nothing about projects', () => {- const [, body] = render(INACTIVE_PROJECT_LIMIT)- expect(body).toBe(INACTIVE_BODY)- expect(body).toContain('live links')- expect(body).not.toContain('unlimited open projects')- expect(body).not.toContain('remote access')- })-- it('limit active: leads with unlimited open projects, then the same list', () => {- const [, body] = render(ACTIVE)- expect(body).toBe(ACTIVE_BODY)- expect(body).toContain('live links')- })-})diff --git a/src/renderer/components/UpgradeDialog.tsx b/src/renderer/components/UpgradeDialog.tsxdeleted file mode 100644index da09b20a7..000000000--- a/src/renderer/components/UpgradeDialog.tsx+++ /dev/null@@ -1,42 +0,0 @@-import { createPortal } from 'react-dom'-import { useEntitlement } from '../state/entitlement'-import { useUpgradeGate } from '../state/upgradeGate'-import { thisMachine } from '../lib/machineName'-import { useProjectLimit } from '../state/projectLimit'--/**- * Pro upgrade prompt shown when a free user triggers a gated feature. Closes automatically- * once an active entitlement arrives (entitlement onChange flips isPremium).- */-export function UpgradeDialog() {- const { open, feature, hide } = useUpgradeGate()- const isPremium = useEntitlement((s) => s.isPremium)- const upgrade = useEntitlement((s) => s.upgrade)- // While the free-tier project limit is on, unlimited open projects is part of what Pro adds- // (docs/project-limit.md); while it is off there is no limit to lift, so the sentence does not- // mention one.- const limitActive = useProjectLimit((s) => s.state.active)- if (!open || isPremium) return null- return createPortal(- <div className="confirm-overlay" onClick={hide}>- <div className="confirm" onClick={(e) => e.stopPropagation()}>- <p className="confirm__msg">{feature} is a Pro feature</p>- <p className="confirm__msg">- Pro adds {limitActive ? 'unlimited open projects, ' : ''}live links to a terminal (watch,- chat, or let people type), 3 team seats to share {thisMachine()}, the larger on-device- dictation models, and nodeterm mobile Pro. Complete your purchase in the browser — Pro- unlocks here automatically.- </p>- <div className="confirm__actions">- <button className="confirm__btn" onClick={hide}>- Maybe later- </button>- <button className="confirm__btn primary" autoFocus onClick={() => void upgrade()}>- Upgrade to Pro — $10/mo- </button>- </div>- </div>- </div>,- document.body- )-}diff --git a/src/renderer/components/icons.tsx b/src/renderer/components/icons.tsxindex fea76379f..17f8687ed 100644--- a/src/renderer/components/icons.tsx+++ b/src/renderer/components/icons.tsx@@ -176,7 +176,7 @@ export const IconRemote = () => ()/** Remote access (phone relay) on/off — an antenna with signal arcs. Not `IconRemote` (the globe- * already means "web view") and not `IconBroadcast` ("share live link"). */+ * already means "web view"). */export const IconRemoteAccess = () => (<svg {...S}><circle cx="12" cy="9" r="1.8" />@@ -246,16 +246,6 @@ export const IconEye = () => (</svg>)-/** "Share live link" — a dot inside two pairs of arcs (the Settings → Live links glyph, at this- * set's 24-unit scale). Deliberately NOT `IconEye`: that already means "Hide cards & connections"- * in the same node header, and one glyph must not mean two things. */-export const IconBroadcast = () => (- <svg {...S}>- <circle cx="12" cy="12" r="2.4" />- <path d="M7.8 7.8a6 6 0 0 0 0 8.4M16.2 7.8a6 6 0 0 1 0 8.4M4.95 4.95a9.9 9.9 0 0 0 0 14.1M19.05 4.95a9.9 9.9 0 0 1 0 14.1" />- </svg>-)-export const IconEyeOff = () => (<svg {...S}><path d="M9.9 4.24A9.12 9.12 0 0 1 12 4c7 0 11 7 11 7a13.16 13.16 0 0 1-1.67 2.68M6.61 6.61A13.53 13.53 0 0 0 1 11s4 7 11 7a9.26 9.26 0 0 0 5.39-1.61M14.12 14.12a3 3 0 1 1-4.24-4.24" />@@ -367,22 +357,6 @@ export const IconCircleCheck = () => (/* Stroked padlocks: the canvas lock moved out of the React Flow controls (whose filled 12pxglyph set is why these used to be filled) into the dock, where every icon is an outline. */-/** A clock face — when something ends (the live-link dialog's "Expires" row). */-export const IconClock = () => (- <svg {...S}>- <circle cx="12" cy="12" r="9" />- <path d="M12 7v5l3 2" />- </svg>-)--/** One person — who someone is shown as (the live-link dialog's name row). */-export const IconUser = () => (- <svg {...S}>- <circle cx="12" cy="8" r="4" />- <path d="M4.5 20a7.5 7.5 0 0 1 15 0" />- </svg>-)-export const IconLock = () => (<svg {...S}><rect x="4.5" y="10.5" width="15" height="10.5" rx="2.5" />diff --git a/src/renderer/components/kanban/CardModal.liveChatEscape.test.tsx b/src/renderer/components/kanban/CardModal.liveChatEscape.test.tsxdeleted file mode 100644index 05afbdccd..000000000--- a/src/renderer/components/kanban/CardModal.liveChatEscape.test.tsx+++ /dev/null@@ -1,123 +0,0 @@-// @vitest-environment jsdom-/**- * Escape typed inside the Live chat drawer never closes the kanban card modal under it (ruling on- * Task 8 concern 4). The drawer is opened from the card's LIVE chip and sits RAISED above the modal.- * Pinned, it is not a dialog, so the card modal is the top dialog — and its capture-phase Escape used- * to close the modal while the owner was typing a reply. Escape in the drawer follows the drawer's- * own rule: unpinned, close the drawer (it is the top dialog); pinned, nothing.- */-import { act } from 'react'-import { createRoot, type Root } from 'react-dom/client'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ProjectKanban } from '@shared/types'-import type { WatchLinkView } from '@shared/watch-link-types'-import { resetDialogStack } from '../dialog-stack'-import { LiveChatDrawer } from '../LiveChatDrawer'-import { useWatchLinks } from '../../state/watchLinks'-import { CardModal } from './CardModal'-import type { KanbanSession } from './KanbanView'--vi.mock('../../session/session', async () => {- // The agent-status reads now resolve a store per project / per session (bug D, covered in- // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.- const { defaultAgentStatus } = await import('../../state/agentStatus')- return {- useSession: () => ({ api: { pty: {}, shell: {} } }),- agentStatusForProject: () => defaultAgentStatus,- useSessionRegistryVersion: () => 0,- useSessionStores: () => ({ agentStatus: defaultAgentStatus })- }-})-vi.mock('./BoardLogPanel', () => ({ BoardLogPanel: () => <textarea className="board-log__composer" /> }))-vi.mock('./CardMetaBar', () => ({ CardMetaBar: () => null }))-vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))--;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true--const board: ProjectKanban = { columns: [{ id: 'c', title: 'To Do', color: '#3b82f6' }], assignments: [] }-const session: KanbanSession = { id: 'n1', title: 'Note', color: '#ffd60a', kind: 'sticky', text: 'x', spawn: {} }-const link: WatchLinkView = {- linkId: 'L',- nodeId: 'n1',- role: 'commenter',- label: 'Ada',- title: 'build',- createdAt: 0,- expiresAt: null,- url: 'u',- status: 'live',- viewers: [],- control: null-}--let host: HTMLDivElement-let root: Root-beforeEach(() => {- resetDialogStack()- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })- useWatchLinks.getState().setLinks([link])- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {- onMarkdownToggle: () => () => {},- watchLink: { chatHistory: vi.fn(async () => []), sendChat: vi.fn(), kick: vi.fn() },- clipboard: { writeText: vi.fn() }- }- host = document.createElement('div')- document.body.append(host)- root = createRoot(host)-})-afterEach(() => {- act(() => root.unmount())- resetDialogStack()- document.body.innerHTML = ''-})--const escapeOn = (el: HTMLElement): void => {- el.focus()- act(() => void el.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))-}--async function open(pinned: boolean): Promise<{ closeModal: ReturnType<typeof vi.fn>; closeDrawer: ReturnType<typeof vi.fn> }> {- const closeModal = vi.fn()- const closeDrawer = vi.fn()- const modal = (- <CardModal projectId="p1" session={session} columnTitle={null} board={board} onChangeBoard={vi.fn()} onClose={closeModal}- onOpenCanvas={vi.fn()} onRename={vi.fn()} onEditSticky={vi.fn()} onBrowserNav={vi.fn()} onSetIcon={vi.fn()} />- )- // The card modal first; then Open chat on its LIVE chip raises the drawer over it.- await act(async () => root.render(<>{modal}</>))- await act(async () =>- root.render(- <>- {modal}- <LiveChatDrawer linkId="L" pinned={pinned} raised onPickLink={vi.fn()} onClose={closeDrawer} onTogglePin={vi.fn()} onGoToNode={vi.fn()} />- </>- )- )- expect(document.querySelector('.drawer-overlay--raised')).not.toBeNull()- return { closeModal, closeDrawer }-}--const composer = (): HTMLInputElement => document.querySelector<HTMLInputElement>('.live-chat__reply input')!--describe('Escape in the Live chat drawer over a card modal', () => {- it('pinned: Escape in the drawer closes neither the drawer nor the card modal', async () => {- const { closeModal, closeDrawer } = await open(true)- escapeOn(composer())- expect(closeModal).not.toHaveBeenCalled()- expect(closeDrawer).not.toHaveBeenCalled()- })-- it('unpinned (the top dialog): Escape in the drawer closes the drawer only', async () => {- const { closeModal, closeDrawer } = await open(false)- escapeOn(composer())- expect(closeDrawer).toHaveBeenCalledTimes(1)- expect(closeModal).not.toHaveBeenCalled()- })-- it('Escape outside the drawer still closes the card modal when the docked drawer is up (unchanged)', async () => {- const { closeModal, closeDrawer } = await open(true)- escapeOn(document.querySelector<HTMLTextAreaElement>('.board-log__composer')!)- expect(closeModal).toHaveBeenCalledTimes(1)- expect(closeDrawer).not.toHaveBeenCalled()- })-})diff --git a/src/renderer/components/kanban/CardModal.liveLink.test.tsx b/src/renderer/components/kanban/CardModal.liveLink.test.tsxdeleted file mode 100644index 79953e30f..000000000--- a/src/renderer/components/kanban/CardModal.liveLink.test.tsx+++ /dev/null@@ -1,153 +0,0 @@-// @vitest-environment jsdom-//-// The card modal's "Share live link" action (Task 17, H4) and its LIVE chip gate (R57). The modal-// sits over the board at z 55, ABOVE the canvas's notice strip, so an unavailable share must say-// why ON the button — a notice raised behind the scrim would be a silent dead click.-import { act } from 'react'-import { createRoot } from 'react-dom/client'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import type { ProjectKanban } from '@shared/types'-import type { WatchLinkView } from '@shared/watch-link-types'-import { resetDialogStack } from '../dialog-stack'-import { useWatchLinks } from '../../state/watchLinks'-import { CardModal } from './CardModal'-import type { KanbanSession } from './KanbanView'--const flags = vi.hoisted(() => ({ browser: false, relayProjects: new Set<string>() }))-vi.mock('../../session/session', async () => {- // The agent-status reads now resolve a store per project / per session (bug D, covered in- // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.- const { defaultAgentStatus } = await import('../../state/agentStatus')- return {- useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } }),- sessionForProject: (id: string) => ({ source: flags.relayProjects.has(id) ? 'relay' : 'local', api: {} }),- agentStatusForProject: () => defaultAgentStatus,- useSessionRegistryVersion: () => 0,- useSessionStores: () => ({ agentStatus: defaultAgentStatus })- }-})-vi.mock('@renderer/bridge/runtime', () => ({ isBrowserRuntime: () => flags.browser }))-vi.mock('./BoardLogPanel', () => ({ BoardLogPanel: () => null }))-vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))-vi.mock('./ModalTerminal', () => ({ ModalTerminal: () => <div className="kanban-modal__term" /> }))-vi.mock('../../nodes/BrowserSurface', () => ({ BrowserSurface: () => null }))--;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true--const R43 = 'Live links need a Pro license on this server — not available in the Server Edition yet'-const RELAY = 'Live links are created on the machine that runs this terminal.'-const LIMIT = 'Stop a live link first — 5 can be active at once.'--const terminal: KanbanSession = { id: 'n1', title: 'build', color: '#fff', kind: 'terminal', spawn: {} } as KanbanSession-const sticky: KanbanSession = { id: 's1', title: 'note', color: '#fff', kind: 'sticky', text: 'note', spawn: {} } as KanbanSession-const board = { columns: [], assignments: [] } as unknown as ProjectKanban-const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({- linkId: 'L',- nodeId: 'n1',- role: 'viewer',- label: 'Ada',- title: 'build',- createdAt: 0,- expiresAt: Date.now() + 3_600_000,- url: 'https://nodeterm.dev/s/L#1.secret',- status: 'live',- viewers: [],- control: null,- ...over-})--let host: HTMLDivElement-let events: CustomEvent[]-const onLive = (e: Event): void => void events.push(e as CustomEvent)-beforeEach(() => {- resetDialogStack()- flags.browser = false- flags.relayProjects.clear()- events = []- window.addEventListener('nodeterm:live-link', onLive)- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })- vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {- onMarkdownToggle: () => () => {},- boardLog: { list: async () => [], onChanged: () => () => {} }- }- host = document.createElement('div')- document.body.append(host)-})-afterEach(() => {- window.removeEventListener('nodeterm:live-link', onLive)- resetDialogStack()- document.body.innerHTML = ''- vi.unstubAllGlobals()-})--function mount(session: KanbanSession, projectId = 'p1'): () => void {- const root = createRoot(host)- act(() =>- root.render(- <CardModal session={session} projectId={projectId} columnTitle={null} board={board} onChangeBoard={vi.fn()}- onClose={vi.fn()} onOpenCanvas={vi.fn()} onRename={vi.fn()} onEditSticky={vi.fn()} onSetIcon={vi.fn()}- onBrowserNav={vi.fn()} />- )- )- return () => act(() => root.unmount())-}-const shareButton = (): HTMLButtonElement | null =>- document.querySelector<HTMLButtonElement>('.kanban-modal__action[data-action="live-link"]')--describe('CardModal — Share live link', () => {- it('a terminal card asks the canvas to share THIS node, naming its project', () => {- const unmount = mount(terminal, 'p-omni')- const b = shareButton()!- expect(b.disabled).toBe(false)- expect(b.title).toBe('Share live link')- act(() => b.dispatchEvent(new MouseEvent('click', { bubbles: true })))- expect(events).toHaveLength(1)- expect(events[0].detail).toEqual({ nodeId: 'n1', title: 'build', projectId: 'p-omni' })- unmount()- })-- it('is disabled WITH the reason where it cannot work, and a click sends nothing', () => {- for (const [setup, why] of [- [() => (flags.browser = true), R43],- [() => flags.relayProjects.add('p1'), RELAY],- [- () =>- useWatchLinks- .getState()- .setLinks(['a', 'b', 'c', 'd', 'e'].map((id) => link({ linkId: id, nodeId: `x-${id}` }))),- LIMIT- ]- ] as const) {- flags.browser = false- flags.relayProjects.clear()- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })- events = []- act(() => void setup())- const unmount = mount(terminal)- const b = shareButton()!- expect(b.disabled).toBe(true)- expect(b.title).toBe(why)- act(() => b.dispatchEvent(new MouseEvent('click', { bubbles: true })))- expect(events).toHaveLength(0)- unmount()- }- })-- it('a sticky card has no share action', () => {- const unmount = mount(sticky)- expect(shareButton()).toBeNull()- unmount()- })-- it('R57: the LIVE chip shows for a local project and not for a relay project with the same node id', () => {- act(() => useWatchLinks.getState().setLinks([link()]))- let unmount = mount(terminal, 'p1')- expect(document.querySelector('.kanban-modal__header .live-chip')).not.toBeNull()- unmount()- flags.relayProjects.add('p-relay')- unmount = mount(terminal, 'p-relay')- expect(document.querySelector('.kanban-modal__header .live-chip')).toBeNull()- unmount()- })-})diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsxindex e0ca269b6..5f05f3320 100644--- a/src/renderer/components/kanban/CardModal.tsx+++ b/src/renderer/components/kanban/CardModal.tsx@@ -3,7 +3,6 @@ import { sshHostKey } from '@shared/ssh'import { createPortal } from 'react-dom'import { isTopDialog, nextDialogId, popDialog, pushDialog } from '../dialog-stack'import {- IconBroadcast,IconChat,IconClose,IconColor,@@ -26,10 +25,6 @@ import { normalizeNodeIcon, type NodeIcon } from '@shared/node-icon'import { ContextMeter } from '../ContextMeter'import { isRemoteSessionNode } from '@shared/worktree'import { AccountChip, useAccountChip } from '../AccountChip'-import { LiveLinkChip } from '../LiveLinkChip'-import { projectSessionSource } from '../../lib/projectSessionSource'-import { useWatchLinks } from '../../state/watchLinks'-import { liveLinkUnavailable } from '../../lib/liveLinkEntry'import { isBrowserRuntime } from '@renderer/bridge/runtime'import { IssueRefChip } from '../IssueRefChip'import { TeamProgressChip } from '../TeamProgressChip'@@ -70,7 +65,6 @@ import { ModalTerminal } from './ModalTerminal'import { BrowserSurface } from '../../nodes/BrowserSurface'import { BrowserDrivingIndicator } from '../../nodes/BrowserDrivingChip'import { NoteMarkdown } from '../NoteMarkdown'-import { inLiveChatDrawer } from '../../lib/liveChatPin'import { relativeTime } from '../../lib/relativeTime'import { TerminalMarkdownView } from '../../nodes/TerminalMarkdownView'import { canChat } from '@shared/agents/config'@@ -95,8 +89,7 @@ interface CardModalProps {* on the Omni board. Both boards mount the modal under THAT project's session* (`ProjectSessionScope`: `sessionForProject(projectId)` + `OwningProjectContext`), so* `useSession()` here and in the terminal, chat and file views below is the core the node runs- * on — a team tab's relay session, never this desktop's local one. The LIVE chip (R57) and the- * "Share live link" action (H4) still resolve through this id. */+ * on — a team tab's relay session, never this desktop's local one. */projectId: string/** Owning project, supplied by the board (not necessarily the active project in Omni). */projectName?: string@@ -160,17 +153,6 @@ export function CardModal({ session, projectId, projectName, projectColor, colum// The header slot decides "icon or smiley" on the NORMALIZED value, the answer NodeIconView// itself gives — on the raw one, an invalid stored icon drew an empty, un-muted slot.const sessionIcon = normalizeNodeIcon(session.icon)- // Which machine this node runs on, for the live-link chip and action (R57, H4).- const liveLinkSource = projectSessionSource(projectId)- const activeLiveLinks = useWatchLinks((s) => s.links.length)- // The ONE availability rule every opener checks before the Pro gate. The modal paints ABOVE the- // canvas's notice strip, so the reason goes on the button (disabled + title) rather than into a- // notice nobody could see.- const liveLinkWhy = liveLinkUnavailable({- serverEdition: isBrowserRuntime(),- source: liveLinkSource,- activeLinks: activeLiveLinks- })const idRef = useRef<string>()if (!idRef.current) idRef.current = nextDialogId()const id = idRef.current@@ -426,10 +408,6 @@ export function CardModal({ session, projectId, projectName, projectColor, columuseEffect(() => {const onKey = (e: KeyboardEvent) => {if (e.key !== 'Escape' || !isTopDialog(id)) return- // An Escape typed in the Live chat drawer is the drawer's, never this modal's: docked over the- // modal (raised), the drawer is not a dialog, so this modal is still the top one. Not consumed —- // the drawer's own rule decides (unpinned: close the drawer; pinned: nothing).- if (inLiveChatDrawer(e.target) || inLiveChatDrawer(document.activeElement)) return// The header Color swatches own Esc first: close the menu, not the whole modal. (The menu is// not a dialog-stack entry, so this modal still reads as the top dialog while it is open.)if (colorMenuOpenRef.current) {@@ -584,7 +562,6 @@ export function CardModal({ session, projectId, projectName, projectColor, colum</span>)}{isTerminal && <AccountChip chip={accountChip} />}- {isTerminal && <LiveLinkChip nodeId={session.id} source={liveLinkSource} className="kanban-modal__live" />}{/* The driving chip, so a user watching a browser card THROUGH the modal is notdriving-blind. The lease is keyed by node id (not by webview object), so this showswhen the node is being driven even though the drive lands on the CANVAS webview, not@@ -681,26 +658,6 @@ export function CardModal({ session, projectId, projectName, projectColor, colum>{naming || funnelNaming ? '…' : '✦'}</button>- {/* Share a live link to this terminal — the canvas node menu's row, as a header action.- The canvas opens the dialog (`nodeterm:live-link`) after re-checking availability- and the Pro gate; the event names the card's PROJECT so a node of an Omni lane is- judged by its own session, not the active tab's. */}- <button- className="kanban-modal__action"- data-action="live-link"- title={liveLinkWhy ?? 'Share live link'}- aria-label="Share live link"- disabled={!!liveLinkWhy}- onClick={() =>- window.dispatchEvent(- new CustomEvent('nodeterm:live-link', {- detail: { nodeId: session.id, title: session.title, projectId }- })- )- }- >- <IconBroadcast />- </button>{hasSessionRows && (<buttonclassName="kanban-modal__action"diff --git a/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx b/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsxdeleted file mode 100644index 6513f0189..000000000--- a/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx+++ /dev/null@@ -1,126 +0,0 @@-// @vitest-environment jsdom-//-// Live links on the Omni (all-projects) board — R49 and R57:-// - every lane's card menu offers "Share live link…" from Canvas's ONE builder, asked for THAT-// lane's project (a link needs no node on screen, so another tab's card can share too);-// - a lane of a relay project never shows this machine's LIVE chip for a node id that collides-// with a local one (the same git-shared canvas opened both ways).-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { act } from 'react'-import { createRoot, type Root } from 'react-dom/client'-import type { CanvasNodeState, Project } from '@shared/types'-import type { WatchLinkView } from '@shared/watch-link-types'-import { GlobalKanbanView } from './GlobalKanbanView'-import { useProjects } from '../../state/projects'-import { useViewMode } from '../../state/viewMode'-import { useWatchLinks } from '../../state/watchLinks'-import type { MenuItem } from '../ContextMenu'--vi.mock('../../session/session', async () => {- // The agent-status reads now resolve a store per project / per session (bug D, covered in- // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.- const { defaultAgentStatus } = await import('../../state/agentStatus')- return {- useSession: () => ({ id: 'local', source: 'local', api: {} }),- sessionForProject: (projectId: string) =>- projectId === 'relay' ? { id: 'relay-session', source: 'relay', api: {} } : { id: 'local', source: 'local', api: {} },- agentStatusForProject: () => defaultAgentStatus,- useSessionRegistryVersion: () => 0,- useSessionStores: () => ({ agentStatus: defaultAgentStatus })- }-})-vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))-vi.mock('./CardModal', () => ({ CardModal: () => null }))--const terminal = (id: string, title: string): CanvasNodeState =>- ({ id, kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 200, height: 200 }, title, color: '#fff', group: null }) as CanvasNodeState-const project = (id: string, nodes: CanvasNodeState[]): Project =>- ({ id, name: id, color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 }, nodes }) as unknown as Project-const link = (nodeId: string): WatchLinkView => ({- linkId: `L-${nodeId}`,- nodeId,- role: 'viewer',- label: 'Ada',- title: 'build',- createdAt: 0,- expiresAt: Date.now() + 3_600_000,- url: 'u',- status: 'live',- viewers: [],- control: null-})--let root: Root | null = null-let host: HTMLElement-beforeEach(() => {- vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)- vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {- boardLog: { list: async () => [], onChanged: () => () => {} },- settings: { save: async () => {} }- }- useViewMode.setState({ requestedCardNodeId: null } as never)- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })-})-afterEach(() => {- if (root) act(() => root!.unmount())- root = null- host?.remove()- document.body.innerHTML = ''- vi.unstubAllGlobals()-})--function mount(- projects: Project[],- nodeActionItems?: (nodeId: string, projectId: string) => MenuItem[],- onAiName?: (projectId: string, nodeId: string) => void-): void {- useProjects.setState({ projects, activeProjectId: projects[0].id } as never)- host = document.createElement('div')- document.body.appendChild(host)- root = createRoot(host)- act(() => root!.render(<GlobalKanbanView nodeActionItems={nodeActionItems} onAiName={onAiName} />))-}-const cardIn = (lane: string): HTMLElement =>- document.querySelector<HTMLElement>(`#swimlane-${lane} [title="Open card"]`)!--describe('Omni board — live links', () => {- it('a card of a NON-active project offers the row, built for that node and that project', () => {- const rows = vi.fn((nodeId: string, projectId: string): MenuItem[] => [- { label: `Share live link… (${nodeId} in ${projectId})`, onClick: () => {} }- ])- mount([project('a', [terminal('n-a', 'alpha')]), project('b', [terminal('n-b', 'beta')])], rows)- act(() => {- cardIn('b').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 10, clientY: 10 }))- })- expect(rows).toHaveBeenCalledWith('n-b', 'b')- expect(document.body.textContent).toContain('Share live link… (n-b in b)')- })-- it('a board with no canvas behind it offers none', () => {- mount([project('a', [terminal('n-a', 'alpha')])])- act(() => {- cardIn('a').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 10, clientY: 10 }))- })- expect(document.body.textContent).toContain('Open card')- expect(document.body.textContent).not.toContain('Share live link')- })-- it('"Name with AI" on a background lane names the node of that lane', () => {- const ai = vi.fn()- mount([project('a', [terminal('n-a', 'alpha')]), project('b', [terminal('n-b', 'beta')])], undefined, ai)- act(() => {- cardIn('b').dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, clientX: 10, clientY: 10 }))- })- const row = [...document.querySelectorAll<HTMLElement>('.ctx-item')].find((el) => el.textContent?.includes('Name with AI'))- act(() => row!.click())- expect(ai).toHaveBeenCalledWith('b', 'n-b')- })-- it('R57: the local lane shows the chip; a relay lane with the SAME node id does not', () => {- mount([project('a', [terminal('same', 'alpha')]), project('relay', [terminal('same', 'theirs')])])- act(() => useWatchLinks.getState().setLinks([link('same')]))- expect(document.querySelector('#swimlane-a .live-chip')).not.toBeNull()- expect(document.querySelector('#swimlane-relay .live-chip')).toBeNull()- })-})diff --git a/src/renderer/components/kanban/GlobalKanbanView.tsx b/src/renderer/components/kanban/GlobalKanbanView.tsxindex 261311913..682a599c7 100644--- a/src/renderer/components/kanban/GlobalKanbanView.tsx+++ b/src/renderer/components/kanban/GlobalKanbanView.tsx@@ -12,7 +12,6 @@ import {} from '../../lib/kanban'import { KanbanColumn, type KanbanLane } from './KanbanColumn'import { SessionCard } from './SessionCard'-import { projectSessionSource } from '../../lib/projectSessionSource'import { toKanbanSessionState } from '../../canvas/toKanbanSessionState'import { createAgentNode, createBrowserNode, createStickyNode, createTerminalNode, flowToNodeStates, resolveNewNodeAccount } from '../../state/workspace'import { markCanvasCovered } from '../../lib/canvasCovered'@@ -163,8 +162,6 @@ const Swimlane = memo(function Swimlane({return teamsRef.current}, [liveTeams, ropes, nodes])const travel = useCallback((nodeId: string) => onOpenNode(nodeId, projectId), [onOpenNode, projectId])- // Which machine this lane's nodes run on: only a local lane shows this machine's LIVE chips (R57).- const liveLinkSource = projectSessionSource(projectId)// The agent-status store of the session this LANE's project belongs to — a lane is not the// active project, and a team lane's cards read its relay session's store (they share node ids// with the handed-off SSH project, whose entries are the default store's).@@ -304,7 +301,6 @@ const Swimlane = memo(function Swimlane({team={teams.get(s.id) ?? NO_STATIONS}onTravel={travel}columnCategory={category}- liveLinkSource={liveLinkSource}ports={cardPorts}onOpenPort={openPort}onRunQueued={runQueued}diff --git a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsxindex 46e200d33..a020c07d3 100644--- a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx+++ b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx@@ -2,7 +2,7 @@//// The card right-click menu carries the node's own rows — the SAME builder the canvas node menu// uses (lib/nodeActionItems, narrowed by Canvas to BOARD_NODE_ACTION_IDS), passed in as-// `nodeActionItems`. A card is a second view of its node, so color, icon, live link and the+// `nodeActionItems`. A card is a second view of its node, so color, icon, refresh and the// account switch must be reachable from the board without going back to the canvas.import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { act } from 'react'@@ -115,13 +115,13 @@ describe('KanbanView — card menu node rows', () => {it('shows the node’s rows from the shared builder, built for that card’s node', () => {const rows = vi.fn((id: string): MenuItem[] => [{ label: `Switch Claude account (${id})`, onClick: () => {} },- { label: `Share live link… (${id})`, onClick: () => {} }+ { label: `Refresh terminal (${id})`, onClick: () => {} }])render(rows)openCardMenu()expect(rows).toHaveBeenCalledWith('n1')expect(document.body.textContent).toContain('Switch Claude account (n1)')- expect(document.body.textContent).toContain('Share live link… (n1)')+ expect(document.body.textContent).toContain('Refresh terminal (n1)')})it('shows none without a builder (no canvas behind the board)', () => {@@ -129,7 +129,7 @@ describe('KanbanView — card menu node rows', () => {openCardMenu()expect(document.body.textContent).toContain('Open card')expect(document.body.textContent).not.toContain('Switch Claude account')- expect(document.body.textContent).not.toContain('Share live link')+ expect(document.body.textContent).not.toContain('Refresh terminal')})it('"Open card in chat / markdown view" opens the card modal on that view', () => {diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsxindex ab178dbe6..e8106d110 100644--- a/src/renderer/components/kanban/KanbanView.tsx+++ b/src/renderer/components/kanban/KanbanView.tsx@@ -31,7 +31,6 @@ import { labelSwatch } from '../../lib/kanbanLabelColors'import { CardModal } from './CardModal'import { KanbanColumn, type KanbanLane } from './KanbanColumn'import { SessionCard } from './SessionCard'-import { projectSessionSource } from '../../lib/projectSessionSource'import { GitHubIssueCard } from './GitHubIssueCard'import { GitHubPullCard } from './GitHubPullCard'import { kanbanSource, sourceVisible } from '../../lib/kanbanSources'@@ -148,7 +147,7 @@ export interface KanbanViewProps {/*** The node's own rows for its card menu — the SAME builder the canvas node menu and the sessions* sidebar use (lib/nodeActionItems), narrowed by Canvas to `BOARD_NODE_ACTION_IDS`: stop agent- * control, color, icon, refresh terminal, Share live link…, restart, switch model, Switch+ * control, color, icon, refresh terminal, restart, switch model, Switch* Claude/Codex account, pause. Optional: a board with no canvas behind it (a test, a future* read-only view) shows none.*/@@ -317,9 +316,6 @@ export const KanbanView = memo(function KanbanView({const projectId = useProjects((s) => s.activeProjectId)const projectName = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.name)const projectColor = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.color)- // Which machine this board's nodes run on — only a local board shows this machine's LIVE chips- // (R57). A primitive, so the memoized cards are not re-rendered by it.- const liveLinkSource = projectSessionSource(projectId)// The agent-status store of the session this board's PROJECT belongs to: a team tab's cards read// its relay session's store (they share node ids with the handed-off SSH project, whose entries// are the default store's). Every card, the chips' signature and the open card's read mark use it.@@ -999,7 +995,6 @@ export const KanbanView = memo(function KanbanView({team={teams?.get(s.id) ?? NO_STATIONS}onTravel={onOpenNode}columnCategory={category}- liveLinkSource={liveLinkSource}ports={cardPorts}onOpenPort={openPort}onRunQueued={onRunQueued}diff --git a/src/renderer/components/kanban/SessionCard.ports.test.tsx b/src/renderer/components/kanban/SessionCard.ports.test.tsxindex 1a8942259..9fe309449 100644--- a/src/renderer/components/kanban/SessionCard.ports.test.tsx+++ b/src/renderer/components/kanban/SessionCard.ports.test.tsx@@ -52,7 +52,6 @@ function render(session: KanbanSession, extra: { ports?: typeof ports; onOpenPoronDragEnd={noop}onDropAt={noop}onContext={noop}- liveLinkSource="local"ports={extra.ports}onOpenPort={extra.onOpenPort}/>diff --git a/src/renderer/components/kanban/SessionCard.queued.test.tsx b/src/renderer/components/kanban/SessionCard.queued.test.tsxindex f6cc60111..9a73d071f 100644--- a/src/renderer/components/kanban/SessionCard.queued.test.tsx+++ b/src/renderer/components/kanban/SessionCard.queued.test.tsx@@ -47,7 +47,6 @@ function render(session: KanbanSession, extra: { onRunQueued?: (id: string) => vonDragEnd={noop}onDropAt={noop}onContext={noop}- liveLinkSource="local"onRunQueued={extra.onRunQueued}/>)diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsxindex 033c637d5..f6c70932d 100644--- a/src/renderer/components/kanban/SessionCard.tsx+++ b/src/renderer/components/kanban/SessionCard.tsx@@ -3,9 +3,6 @@ import { sshHostKey } from '@shared/ssh'import type { KanbanCardMeta, KanbanColumnCategory, KanbanLabel, KanbanPriority } from '@shared/types'import { useAgentStatus, type AgentStatusSession } from '../../state/agentStatus'import { AccountChip, useAccountChip } from '../AccountChip'-import { LiveLinkChip, showsLiveLinks } from '../LiveLinkChip'-import type { SessionSource } from '../../session/session'-import { useWatchLinks } from '../../state/watchLinks'import { ContextMeter } from '../ContextMeter'import { transcriptSessionFor } from '../../lib/transcriptSession'import { isRemoteSessionNode } from '@shared/worktree'@@ -54,10 +51,6 @@ interface SessionCardProps {onTravel?: (nodeId: string) => void/** The lifecycle category of the column the card sits in (lib/cardRedundancy reads it). */columnCategory?: KanbanColumnCategory- /** The session the board's PROJECT belongs to (`projectSessionSource`). Only a local one shows- * this machine's LIVE chip, or counts a link as card detail — a relay tab's node with the same- * id is another machine's terminal (R57). */- liveLinkSource: SessionSource | null/** The card's project, when the dev-port scanner covers it (the project on the canvas). Absent =* no Ports chip: the scanner scans the active project only, so an Omni lane of a background* project would only ever show a stale or empty list. A stable object per board (memo). */@@ -83,7 +76,7 @@ interface SessionCardProps {export const SessionCard = memo(function SessionCard({session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext, pulls,- pullFreshness = 'fresh', onOpenIssue, team, onTravel, columnCategory, liveLinkSource, ports, onOpenPort, onRunQueued,+ pullFreshness = 'fresh', onOpenIssue, team, onTravel, columnCategory, ports, onOpenPort, onRunQueued,statusStore, selected = false, onSelectClick}: SessionCardProps) {// THIS card's agent status, subscribed per card rather than threaded down from the board.@@ -128,16 +121,10 @@ export const SessionCard = memo(function SessionCard({? status.session: undefinedconst priority = meta?.priority- // A live link counts as detail: "this terminal is being broadcast" must show on the card whatever- // else it has to say (a primitive selector — see LiveLinkChip).- const showLive = showsLiveLinks(liveLinkSource)- const hasLiveLink = useWatchLinks(- (s) => showLive && session.kind === 'terminal' && (s.byNode[session.id]?.length ?? 0) > 0- )// The account chip counts as detail in its own right: a card whose only thing to say is "this// one is on the other Claude login" is exactly the card that must say it.const hasDetail =- !!status?.sessionId || !!sessionName || !!accountChip || hasLiveLink || stickyPreview.includes('\n')+ !!status?.sessionId || !!sessionName || !!accountChip || stickyPreview.includes('\n')return (<divclassName={`kanban-card kanban-card--session${dragging ? ' kanban-card--dragging' : ''}${@@ -293,7 +280,6 @@ export const SessionCard = memo(function SessionCard({<><ContextMeter sessionId={cardTranscript.sessionId ?? null} fromLaunchId={cardTranscript.fallback} nodeId={session.id} remote={isRemoteSessionNode(session.spawn)} agentId={session.agentId ?? session.spawn.agentId ?? status?.agentId} /><AccountChip chip={accountChip} />- <LiveLinkChip nodeId={session.id} source={liveLinkSource} className="kanban-card__live" />{sessionName && (<span className="kanban-card__session" title={sessionName}>{sessionName}diff --git a/src/renderer/components/kanban/cardMenu.test.tsx b/src/renderer/components/kanban/cardMenu.test.tsxindex a321daba5..32d9c4fff 100644--- a/src/renderer/components/kanban/cardMenu.test.tsx+++ b/src/renderer/components/kanban/cardMenu.test.tsx@@ -19,7 +19,7 @@ function args(over: Partial<CardMenuArgs> = {}): CardMenuArgs {openOnCanvas: vi.fn(),rename: vi.fn(),aiName: vi.fn(),- nodeActions: () => [{ label: 'Share live link…', onClick: () => {} }],+ nodeActions: () => [{ label: 'Refresh terminal', onClick: () => {} }],remove: vi.fn(),...over}@@ -43,7 +43,7 @@ describe('buildCardMenuItems', () => {'Rename…','Name with AI','—',- 'Share live link…',+ 'Refresh terminal','—','Delete'])diff --git a/src/renderer/components/lazyPanels.tsx b/src/renderer/components/lazyPanels.tsxindex 7bfdd9165..dd8ad2805 100644--- a/src/renderer/components/lazyPanels.tsx+++ b/src/renderer/components/lazyPanels.tsx@@ -48,9 +48,6 @@ export const SourceControlPanel = withSuspense(export const ExplorerPanel = withSuspense(lazy(() => import('./ExplorerPanel').then((m) => ({ default: m.ExplorerPanel }))))-export const LiveChatDrawer = withSuspense(- lazy(() => import('./LiveChatDrawer').then((m) => ({ default: m.LiveChatDrawer })))-)export const ShortcutsPanel = withSuspense(lazy(() => import('./ShortcutsPanel').then((m) => ({ default: m.ShortcutsPanel }))))diff --git a/src/renderer/components/settings/SettingsIcons.tsx b/src/renderer/components/settings/SettingsIcons.tsxindex 25f150d02..409d3b545 100644--- a/src/renderer/components/settings/SettingsIcons.tsx+++ b/src/renderer/components/settings/SettingsIcons.tsx@@ -132,14 +132,6 @@ const PATHS: Record<StaticSettingsSectionId, React.JSX.Element> = {<path d="M10.6 3.6a2.2 2.2 0 0 1 0 4.2M11.4 9.3c1.5.4 2.4 1.6 2.4 3.2" /></>),- // A dot inside two pairs of arcs: this terminal is being broadcast (the same glyph as the- // node menu's "Share live link…" row, `IconBroadcast`).- 'live-links': (- <>- <circle cx="8" cy="8" r="1.6" />- <path d="M5.2 5.2a4 4 0 0 0 0 5.6M10.8 5.2a4 4 0 0 1 0 5.6M3.3 3.3a6.6 6.6 0 0 0 0 9.4M12.7 3.3a6.6 6.6 0 0 1 0 9.4" />- </>- ),ssh: (<><rect x="2" y="3" width="12" height="10" rx="2" />diff --git a/src/renderer/components/settings/SettingsPage.tsx b/src/renderer/components/settings/SettingsPage.tsxindex 623813106..51bfc639f 100644--- a/src/renderer/components/settings/SettingsPage.tsx+++ b/src/renderer/components/settings/SettingsPage.tsx@@ -28,7 +28,6 @@ import { LicenseSection } from './sections/LicenseSection'import { PresenceIdentitySection } from './sections/PresenceIdentitySection'import { RemoteSection } from './sections/RemoteSection'import { TeamAccessSection } from './sections/TeamAccessSection'-import { LiveLinksSection } from './sections/LiveLinksSection'import { SshSection } from './sections/SshSection'import { UpdatesSection } from './sections/UpdatesSection'import { PrivacySection } from './sections/PrivacySection'@@ -174,9 +173,6 @@ export function SettingsPage({<SettingsSectionBoundary title="Team seats" visible={active === 'team-access'}><TeamAccessSection isActive={active === 'team-access'} onClose={onClose} /></SettingsSectionBoundary>- <SettingsSectionBoundary title="Live links" visible={active === 'live-links'}>- <LiveLinksSection isActive={active === 'live-links'} />- </SettingsSectionBoundary><SettingsSectionBoundary title="Remote (SSH)" visible={active === 'ssh'}><SshSection isActive={active === 'ssh'} /></SettingsSectionBoundary>diff --git a/src/renderer/components/settings/nav.test.ts b/src/renderer/components/settings/nav.test.tsindex a6b0ae728..f99c22e38 100644--- a/src/renderer/components/settings/nav.test.ts+++ b/src/renderer/components/settings/nav.test.ts@@ -2,10 +2,10 @@ import { describe, it, expect } from 'vitest'import { SETTINGS_GROUPS, allSectionIds, FIRST_SECTION_ID, visibleSettingsGroups, projectsSettingsGroup } from './nav'describe('SETTINGS_GROUPS', () => {- it('lists exactly 27 sections with no duplicates', () => {+ it('lists exactly 26 sections with no duplicates', () => {const ids = allSectionIds()- expect(ids).toHaveLength(27)- expect(new Set(ids).size).toBe(27)+ expect(ids).toHaveLength(26)+ expect(new Set(ids).size).toBe(26)})it('starts at a section that exists in the groups', () => {expect(allSectionIds()).toContain(FIRST_SECTION_ID)@@ -13,7 +13,7 @@ describe('SETTINGS_GROUPS', () => {it('hides mac-only sections off macOS, keeps them on', () => {const off = visibleSettingsGroups(false).flatMap((g) => g.sections.map((s) => s.id))expect(off).not.toContain('notch')- expect(off).toHaveLength(25) // notch and the browser-only sign-in are both out+ expect(off).toHaveLength(24) // notch and the browser-only sign-in are both outexpect(visibleSettingsGroups(true, true)).toEqual(SETTINGS_GROUPS)// No group is left empty by the filter.expect(visibleSettingsGroups(false).every((g) => g.sections.length > 0)).toBe(true)@@ -28,12 +28,10 @@ describe('SETTINGS_GROUPS', () => {})})-describe('Live links section', () => {- it('sits in Remote & team right after Team seats', () => {+describe('Remote & team', () => {+ it('has no Live links section (live links are retired)', () => {const g = SETTINGS_GROUPS.find((x) => x.id === 'connectivity')!- const ids = g.sections.map((s) => s.id)- expect(ids.indexOf('live-links')).toBe(ids.indexOf('team-access') + 1)- expect(g.sections.find((s) => s.id === 'live-links')?.title).toBe('Live links')+ expect(g.sections.map((s) => s.id)).toEqual(['presence', 'phone', 'remote', 'team-access', 'ssh'])})})diff --git a/src/renderer/components/settings/nav.ts b/src/renderer/components/settings/nav.tsindex 5eb6ac2f9..17bf5e193 100644--- a/src/renderer/components/settings/nav.ts+++ b/src/renderer/components/settings/nav.ts@@ -23,7 +23,6 @@ export type SettingsSectionId =| 'presence'| 'remote'| 'team-access'- | 'live-links'| 'ssh'| 'updates'| 'privacy'@@ -103,7 +102,6 @@ export const SETTINGS_GROUPS: SettingsGroup[] = [{ id: 'phone', title: 'Phone' },{ id: 'remote', title: 'Remote access' },{ id: 'team-access', title: 'Team seats' },- { id: 'live-links', title: 'Live links' },{ id: 'ssh', title: 'Remote (SSH)' }]},diff --git a/src/renderer/components/settings/sections/LiveLinksSection.test.tsx b/src/renderer/components/settings/sections/LiveLinksSection.test.tsxdeleted file mode 100644index 82fc03fea..000000000--- a/src/renderer/components/settings/sections/LiveLinksSection.test.tsx+++ /dev/null@@ -1,276 +0,0 @@-// @vitest-environment jsdom-//-// Settings → Live links: every active link, Copy / Stop, and a CONFIRMED Stop all (R48). The pitch-// shows only with no links and no Pro (H10); the Server Edition says why there are none instead of-// offering an Upgrade (H1, R43).-import { act } from 'react'-import { createRoot, type Root } from 'react-dom/client'-import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'-import type { WatchLinkView } from '@shared/watch-link-types'-import { resetDialogStack } from '../../dialog-stack'-import { pinNeutralMachineNoun } from '../../../lib/testMachineNoun'--const flags = vi.hoisted(() => ({ browser: false, relay: new Set<string>() }))-vi.mock('@renderer/bridge/runtime', () => ({ isBrowserRuntime: () => flags.browser }))-vi.mock('../../../session/session', () => ({- sessionForProject: (id: string) => ({ source: flags.relay.has(id) ? 'relay' : 'local', api: {} })-}))--;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true-pinNeutralMachineNoun()--const api = {- revoke: vi.fn(async (_id: string) => {}),- revokeAll: vi.fn(async (): Promise<string> => 'stopped')-}-const writeText = vi.fn()-const upgrade = vi.fn(async () => ({ tier: null, active: false, expiresAt: null, termEndsAt: null, seats: 0, error: null }))--let LiveLinksSection: typeof import('./LiveLinksSection').LiveLinksSection-let useEntitlement: typeof import('../../../state/entitlement').useEntitlement-let useWatchLinks: typeof import('../../../state/watchLinks').useWatchLinks-let useProjects: typeof import('../../../state/projects').useProjects--beforeAll(async () => {- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {- license: { onChange: () => () => {}, upgrade },- watchLink: api,- clipboard: { writeText }- }- ;({ LiveLinksSection } = await import('./LiveLinksSection'))- ;({ useEntitlement } = await import('../../../state/entitlement'))- ;({ useWatchLinks } = await import('../../../state/watchLinks'))- ;({ useProjects } = await import('../../../state/projects'))-})--const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({- linkId: 'L1',- nodeId: 'n1',- role: 'commenter',- label: 'Ada',- title: 'build',- createdAt: 0,- expiresAt: Date.now() + 42 * 60_000 + 30_000,- url: 'https://nodeterm.dev/s/L1#1.SECRET',- status: 'live',- viewers: [- { viewerId: 'a', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false },- { viewerId: 'b', name: null, joinedAt: 0, waiting: false, controlling: false, typing: false }- ],- control: null,- ...over-})--let host: HTMLDivElement-let root: Root-beforeEach(() => {- resetDialogStack()- flags.browser = false- flags.relay.clear()- api.revoke.mockReset().mockImplementation(async () => {})- api.revokeAll.mockReset().mockImplementation(async () => 'stopped')- writeText.mockClear()- upgrade.mockClear()- useEntitlement.setState({ isPremium: true })- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })- useProjects.setState({- projects: [- { id: 'p1', name: 'Alpha', nodes: [{ id: 'n1', kind: 'terminal', title: 'build' }] },- { id: 'p2', name: 'Parked', closed: true, nodes: [{ id: 'n2', kind: 'terminal', title: 'old' }] },- { id: 'p-relay', name: 'Peer', nodes: [{ id: 'n3', kind: 'terminal', title: 'theirs' }] }- ]- } as never)- host = document.createElement('div')- document.body.append(host)- root = createRoot(host)-})-afterEach(() => {- act(() => root.unmount())- document.body.innerHTML = ''- resetDialogStack()-})--const render = (): void => act(() => root.render(<LiveLinksSection isActive />))-const setLinks = (links: WatchLinkView[]): void => act(() => useWatchLinks.getState().setLinks(links))-const buttons = (label: string): HTMLButtonElement[] =>- [...document.querySelectorAll<HTMLButtonElement>('button')].filter((b) => b.textContent === label)-const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))-const flush = (): Promise<void> => act(async () => {})--describe('LiveLinksSection', () => {- it('no links, no Pro: the pitch and Upgrade', () => {- useEntitlement.setState({ isPremium: false })- render()- expect(host.textContent).toContain('Share a terminal live with anyone')- click(buttons('Upgrade to Pro')[0])- expect(upgrade).toHaveBeenCalledWith('pro')- })-- it('Server Edition: the R43 sentence and NO Upgrade button, Pro or not (H1)', () => {- flags.browser = true- useEntitlement.setState({ isPremium: false })- render()- expect(host.textContent).toContain(- 'Live links need a Pro license on this server — not available in the Server Edition yet'- )- expect(buttons('Upgrade to Pro')).toEqual([])- })-- it('no links, Pro: says how to share one', () => {- render()- expect(host.textContent).toContain('No active live links. Right-click a terminal and choose "Share live link…".')- })-- it('H10: links outlive a Pro lapse, so the list — and Stop — show without Pro', () => {- useEntitlement.setState({ isPremium: false })- render()- setLinks([link()])- expect(host.textContent).not.toContain('Share a terminal live with anyone')- expect(buttons('Stop')).toHaveLength(1)- expect(buttons('Stop all')).toHaveLength(1)- })-- it('a row names node, project (H11), role, viewers and time left — and never prints the URL', () => {- flags.relay.add('p-relay')- render()- setLinks([- link(),- link({ linkId: 'L2', nodeId: 'n2', role: 'viewer', viewers: [] }),- link({ linkId: 'L3', nodeId: 'gone', viewers: [] }),- link({ linkId: 'L4', nodeId: 'n3', viewers: [] })- ])- const rows = [...host.querySelectorAll<HTMLElement>('.live-settings__row')]- expect(rows).toHaveLength(4)- expect(rows[0].textContent).toContain('build')- expect(rows[0].textContent).toContain('Alpha')- // The role by its name (ruling 4), as the create dialog and the popover name it.- expect(rows[0].textContent).toContain('Commenter · 2 watching')- expect(rows[0].textContent).not.toContain('Can watch')- expect(rows[0].textContent).toContain('2 watching')- expect(rows[0].textContent).toContain('ends in 42 min')- expect(rows[1].textContent).toContain('Parked (closed)')- expect(rows[1].textContent).toContain('Viewer · 0 watching')- expect(rows[2].textContent).toContain('not in an open project')- // A relay tab's project with the same node id is another machine's: never named for our link.- expect(rows[3].textContent).toContain('not in an open project')- expect(host.textContent).not.toContain('nodeterm.dev/s/')- expect(host.innerHTML).not.toContain('SECRET')- })-- it('a Control link reads "Control", and an Unlimited one has no end time', () => {- render()- setLinks([link({ role: 'controller', control: { enabled: true, locked: false }, expiresAt: null, viewers: [] })])- const row = host.querySelector<HTMLElement>('.live-settings__row')!- expect(row.textContent).toContain('Control · 0 watching · No end time')- })-- // D2/M2: closing a relay tab unbinds its session, so its source reads LOCAL — but it is still the- // other machine's canvas, and its copy of a git-shared node id is not this machine's node.- it("never names a CLOSED relay tab's project for this machine's link", () => {- act(() =>- useProjects.setState({- projects: [- { id: 'p-peer', name: 'PeerProject', closed: true, remote: true, nodes: [{ id: 'n1', kind: 'terminal', title: 'theirs' }] },- { id: 'p-mine', name: 'Mine', closed: true, nodes: [{ id: 'n1', kind: 'terminal', title: 'build' }] }- ]- } as never)- )- render()- setLinks([link()])- const row = host.querySelector<HTMLElement>('.live-settings__row')!- expect(row.textContent).toContain('Mine (closed)')- expect(row.textContent).not.toContain('PeerProject')- })-- it('Copy copies the URL', () => {- render()- setLinks([link()])- click(buttons('Copy')[0])- expect(writeText).toHaveBeenCalledWith('https://nodeterm.dev/s/L1#1.SECRET')- })-- it('Stop revokes that link; a rejected stop says so (H23)', async () => {- render()- setLinks([link()])- api.revoke.mockRejectedValueOnce(new Error('socket'))- click(buttons('Stop')[0])- await flush()- expect(api.revoke).toHaveBeenCalledWith('L1')- expect(host.textContent).toContain("The stop didn't reach nodeterm — try again.")- })-- it('R48: Stop all asks first, names other machines, and stops nothing on Cancel', async () => {- render()- setLinks([link()])- click(buttons('Stop all')[0])- const dialog = document.querySelector<HTMLElement>('.confirm')!- expect(dialog.textContent).toContain(- 'Stop every live link on your license? This also ends links shared from other computers. Viewers on this computer are disconnected at once; links on other computers stop within a few minutes.'- )- expect(api.revokeAll).not.toHaveBeenCalled()- click([...dialog.querySelectorAll('button')].find((b) => b.textContent === 'Cancel')!)- expect(document.querySelector('.confirm')).toBeNull()- expect(api.revokeAll).not.toHaveBeenCalled()- click(buttons('Stop all')[0])- const confirm = [...document.querySelectorAll<HTMLButtonElement>('.confirm button')].find(- (b) => b.textContent === 'Stop all'- )!- expect(confirm.className).toContain('danger')- click(confirm)- await flush()- expect(api.revokeAll).toHaveBeenCalledTimes(1)- expect(document.querySelector('.confirm')).toBeNull()- })-- // R62: Stop all is the one control that reaches links shared from OTHER machines — so it is there- // whenever the owner could have one, not only when THIS machine lists a link.- it('R62: Pro with no link listed here still offers Stop all, says why, and reports the success', async () => {- render()- expect(host.textContent).toContain('No live links are shared from this computer. Stop all also ends the ones shared from other computers on your license.')- click(buttons('Stop all')[0])- click([...document.querySelectorAll<HTMLButtonElement>('.confirm button')].find((b) => b.textContent === 'Stop all')!)- await flush()- expect(api.revokeAll).toHaveBeenCalledTimes(1)- const said = host.querySelector('[role="status"]')- expect(said?.textContent).toBe('Stopped every live link on your license. Links on other computers end within a few minutes.')- })-- it('R62: no Stop all without a link or Pro, and never in the Server Edition', () => {- useEntitlement.setState({ isPremium: false })- render()- expect(buttons('Stop all')).toEqual([])- act(() => root.unmount())- root = createRoot(host)- flags.browser = true- useEntitlement.setState({ isPremium: true })- render()- expect(buttons('Stop all')).toEqual([])- })-- it('R62: a server call that failed, or no entitlement, is NOT reported as stopped', async () => {- render()- setLinks([link()])- api.revokeAll.mockResolvedValueOnce('failed')- click(buttons('Stop all')[0])- click([...document.querySelectorAll<HTMLButtonElement>('.confirm button')].find((b) => b.textContent === 'Stop all')!)- await flush()- expect(host.querySelector('[role="alert"]')?.textContent).toBe(- "The stop didn't reach nodeterm — try again. Links on this computer are stopped; links shared from other computers may still be running."- )- api.revokeAll.mockResolvedValueOnce('no-entitlement')- click(buttons('Stop all')[0])- click([...document.querySelectorAll<HTMLButtonElement>('.confirm button')].find((b) => b.textContent === 'Stop all')!)- await flush()- expect(host.querySelector('[role="alert"]')?.textContent).toContain("can't be stopped from here: this computer has no Pro license")- })-- it('a rejected Stop all says so (H23)', async () => {- render()- setLinks([link()])- api.revokeAll.mockRejectedValueOnce(new Error('socket'))- click(buttons('Stop all')[0])- click([...document.querySelectorAll<HTMLButtonElement>('.confirm button')].find((b) => b.textContent === 'Stop all')!)- await flush()- expect(host.textContent).toContain("The stop didn't reach nodeterm — try again.")- })-})diff --git a/src/renderer/components/settings/sections/LiveLinksSection.tsx b/src/renderer/components/settings/sections/LiveLinksSection.tsxdeleted file mode 100644index 5e5321922..000000000--- a/src/renderer/components/settings/sections/LiveLinksSection.tsx+++ /dev/null@@ -1,199 +0,0 @@-import { useEffect, useState } from 'react'-import { SettingsSection } from '../SettingsSection'-import { SearchableRow } from '../SearchableRow'-import { Button } from '@renderer/ui/Button'-import { CopyButton } from '@renderer/ui/CopyButton'-import { isBrowserRuntime } from '@renderer/bridge/runtime'-import { ConfirmDialog } from '../../ConfirmDialog'-import { showsLiveLinks } from '../../LiveLinkChip'-import { projectSessionSource } from '../../../lib/projectSessionSource'-import { useEntitlement } from '../../../state/entitlement'-import { useProjects } from '../../../state/projects'-import { useWatchLinks } from '../../../state/watchLinks'-import {- formatRemaining,- NOT_IN_OPEN_PROJECT,- ROLE_NAME,- SERVER_EDITION_UNSUPPORTED,- showsStopAll,- statusLine,- STOP_ALL_BUTTON,- stopAllElsewhereNote-} from '../../../lib/liveLink'-import { stopAllConfirm, stopAllLiveLinks, stopLiveLinks } from '../../../lib/liveLinkEntry'-import { stripBidiControls, type WatchLinkView } from '@shared/watch-link-types'-import type { Project } from '@shared/types'--const ROWS = {- links: {- title: 'Active live links',- keywords: ['live', 'link', 'share', 'watch', 'broadcast', 'viewer', 'stop']- }-}-const ENTRIES = Object.values(ROWS)--/**- * Which project a link's node is in, as the row names it (H11): an open project on THIS machine- * first, else a closed one (a closed project keeps its sessions running, so its links run too),- * else "not in an open project". A project bound to a relay session is another machine's canvas —- * a node there with the same id is not the node this machine's link broadcasts (R57). A CLOSED relay- * tab no longer has a session (closing it unbinds the project, so its source reads as the local one),- * which is why `remote` — the relay tab's own mark — is checked too (D2/M2).- */-export function liveLinkProjectLabel(projects: readonly Project[], nodeId: string): string {- const holders = projects.filter(- (p) =>- !p.remote &&- Array.isArray(p.nodes) &&- p.nodes.some((n) => n?.id === nodeId) &&- showsLiveLinks(projectSessionSource(p.id))- )- const open = holders.find((p) => !p.closed)- if (open) return open.name- const closed = holders[0]- return closed ? `${closed.name} (closed)` : NOT_IN_OPEN_PROJECT-}--function LinkRow({ link, now, projects }: { link: WatchLinkView; now: number; projects: readonly Project[] }): React.JSX.Element {- const [error, setError] = useState<string | null>(null)- const [stopping, setStopping] = useState(false)- const status = statusLine(link)- return (- <div className="live-settings__row flex items-center justify-between gap-3">- <div className="min-w-0">- {/* Titles and names are other people's text: rendered as TEXT, bidi controls stripped. The- URL is NOT shown here — it carries the link's secret; Copy is how it leaves. */}- <div className="truncate text-sm text-text">- <strong>{stripBidiControls(link.title)}</strong>- <span className="text-muted"> · {liveLinkProjectLabel(projects, link.nodeId)}</span>- </div>- <div className="text-xs text-muted">- {ROLE_NAME[link.role]} · {link.viewers.length} watching · {formatRemaining(link.expiresAt, now)}- </div>- {status && <div className="text-xs text-muted">{status}</div>}- {error && (- <div className="text-xs" role="alert" style={{ color: 'var(--danger)' }}>- {error}- </div>- )}- </div>- <div className="flex shrink-0 gap-2">- <CopyButton text={link.url} variant="default" />- <Button- disabled={stopping}- onClick={() => {- setError(null)- setStopping(true)- void stopLiveLinks(() => window.nodeTerminal.watchLink.revoke(link.linkId), setError).then(() =>- setStopping(false)- )- }}- >- Stop- </Button>- </div>- </div>- )-}--export function LiveLinksSection({ isActive }: { isActive: boolean }): React.JSX.Element {- const premium = useEntitlement((s) => s.isPremium)- const links = useWatchLinks((s) => s.links)- const projects = useProjects((s) => s.projects)- const serverEdition = isBrowserRuntime()- const [now, setNow] = useState(() => Date.now())- const [confirmStopAll, setConfirmStopAll] = useState(false)- /** What the last Stop all reached (R62) — said for a success too: with no link listed on this- * machine, nothing else on this page changes. */- const [stopAllResult, setStopAllResult] = useState<{ ok: boolean; text: string } | null>(null)- const [stoppingAll, setStoppingAll] = useState(false)- const stopAllShown = showsStopAll({ serverEdition, entitled: premium, activeLinks: links.length })- useEffect(() => {- if (!isActive) return- setNow(Date.now())- const t = setInterval(() => setNow(Date.now()), 30_000)- return () => clearInterval(t)- }, [isActive])- const confirm = stopAllConfirm({- close: () => setConfirmStopAll(false),- stop: () => {- setStopAllResult(null)- setStoppingAll(true)- void stopAllLiveLinks(() => window.nodeTerminal.watchLink.revokeAll()).then((r) => {- setStoppingAll(false)- setStopAllResult(r)- })- }- })- return (- <SettingsSection- id="live-links"- title="Live links"- description="A read-only browser link to one terminal. Viewers need nothing installed; links end on their own."- isActive={isActive}- searchEntries={ENTRIES}- >- <SearchableRow {...ROWS.links}>- {links.length > 0 ? (- // Shown whether or not Pro is active right now: a link keeps running out its term after- // a lapse, and Stop must stay reachable (H10).- <div className="space-y-3">- <h4 className="text-[13px] font-medium text-text">Active live links</h4>- <div className="live-settings space-y-3">- {links.map((l) => (- <LinkRow key={l.linkId} link={l} now={now} projects={projects} />- ))}- </div>- </div>- ) : serverEdition ? (- // R43: no license layer in the Server Edition yet — say so, never offer an Upgrade.- <p className="text-sm text-muted">{SERVER_EDITION_UNSUPPORTED}</p>- ) : premium ? (- <div className="space-y-1">- <p className="text-sm text-muted">- No active live links. Right-click a terminal and choose "Share live link…".- </p>- {/* Links shared from OTHER machines are invisible here, and Stop all is the one control- that reaches them (R62): say so, beside the button. */}- <p className="text-xs text-muted">{stopAllElsewhereNote()}</p>- </div>- ) : (- <div className="space-y-3">- <p className="text-sm text-muted">- Share a terminal live with anyone — a teammate, a customer, a reviewer — as a link that ends- by itself.- </p>- <Button variant="primary" onClick={() => void useEntitlement.getState().upgrade('pro')}>- Upgrade to Pro- </Button>- </div>- )}- {stopAllShown && (- <div className="mt-3 flex items-center gap-3">- <Button disabled={stoppingAll} onClick={() => setConfirmStopAll(true)}>- {STOP_ALL_BUTTON}- </Button>- {stopAllResult && (- <span- className="text-xs"- role={stopAllResult.ok ? 'status' : 'alert'}- style={stopAllResult.ok ? undefined : { color: 'var(--danger)' }}- >- {stopAllResult.text}- </span>- )}- </div>- )}- </SearchableRow>- {confirmStopAll && (- <ConfirmDialog- message={confirm.message}- confirmLabel={confirm.confirmLabel}- danger={confirm.danger}- onConfirm={confirm.onConfirm}- onCancel={() => setConfirmStopAll(false)}- />- )}- </SettingsSection>- )-}diff --git a/src/renderer/components/settings/sections/ProCompare.test.tsx b/src/renderer/components/settings/sections/ProCompare.test.tsxindex 4e54d3ddd..864340af0 100644--- a/src/renderer/components/settings/sections/ProCompare.test.tsx+++ b/src/renderer/components/settings/sections/ProCompare.test.tsx@@ -35,7 +35,6 @@ const column = (html: string, heading: string): string[] => {}const AGENT_NODES = `Agent nodes (${BUILTIN_AGENT_IDS.map((id) => AGENT_CONFIG[id].label).join(' / ')})`-const LIVE_LINKS = 'Live links to a terminal: watch, chat, or let people type — viewers need nothing installed'const DICTATION = 'Larger on-device dictation models (base, small, large-v3-turbo)'let root: Root@@ -60,8 +59,9 @@ function render(state: ProjectLimitState): string {}describe('ProCompare — limit inactive', () => {- it('lists live links under Pro', () => {- expect(column(render(INACTIVE_PROJECT_LIMIT), 'Pro<')).toContain(LIVE_LINKS)+ it('lists no live links anywhere (the feature is retired)', () => {+ expect(render(INACTIVE_PROJECT_LIMIT).toLowerCase()).not.toContain('live link')+ expect(render(ACTIVE).toLowerCase()).not.toContain('live link')})it('leaves the free Core list exactly as it was', () => {@@ -76,12 +76,11 @@ describe('ProCompare — limit inactive', () => {])})- it('lists the larger dictation models right after live links, and nothing about projects', () => {+ it('lists the larger dictation models right after the team seats, and nothing about projects', () => {expect(column(render(INACTIVE_PROJECT_LIMIT), 'Pro<')).toEqual(['Everything in Core','nodeterm mobile Pro included','3 team seats included (extra seats $5/seat/mo)',- LIVE_LINKS,DICTATION])})@@ -115,7 +114,6 @@ describe('ProCompare — limit active', () => {'Unlimited open projects','nodeterm mobile Pro included','3 team seats included (extra seats $5/seat/mo)',- LIVE_LINKS,DICTATION])})diff --git a/src/renderer/components/settings/sections/ProCompare.tsx b/src/renderer/components/settings/sections/ProCompare.tsxindex c9aca6da2..547f734e5 100644--- a/src/renderer/components/settings/sections/ProCompare.tsx+++ b/src/renderer/components/settings/sections/ProCompare.tsx@@ -15,7 +15,6 @@ const CORE = ['Unlimited local terminals & canvas', 'Unlimited SSH projects', ..const PRO = ['nodeterm mobile Pro included','3 team seats included (extra seats $5/seat/mo)',- 'Live links to a terminal: watch, chat, or let people type — viewers need nothing installed','Larger on-device dictation models (base, small, large-v3-turbo)']diff --git a/src/renderer/lib/live-link.guard.test.ts b/src/renderer/lib/live-link.guard.test.tsdeleted file mode 100644index dbc7fa818..000000000--- a/src/renderer/lib/live-link.guard.test.ts+++ /dev/null@@ -1,105 +0,0 @@-// Live links: rules no single unit can see. Each is a way a live link turns into a leak, or into a-// broadcast the owner cannot see.-//-// Renderer-side on purpose: importing `ui-visibility` from here does not reach across the core-// boundary. Source-level where the rule is about WHERE something is written.-import { describe, it, expect } from 'vitest'-import { readFileSync } from 'node:fs'-import { join } from 'node:path'-import { HIDEABLE_HEADER_BUTTONS, HIDEABLE_MENU_ITEMS } from './ui-visibility'--const root = join(__dirname, '..', '..', '..')-const read = (p: string): string => readFileSync(join(root, p), 'utf8').replace(/\r\n/g, '\n')-/** From a top-level `export interface X {` to its closing `}` at column 0. */-function block(src: string, header: RegExp): string {- const m = header.exec(src)- if (!m) throw new Error(`not found: ${header}`)- const end = src.indexOf('\n}\n', m.index)- if (end === -1) throw new Error(`no end for: ${header}`)- return src.slice(m.index, end)-}--const LINK_STATE = /watchLink|liveLink|live[ -]link|watch[-_]link/i--/** The four surfaces that show a node, and so the chip (CONTRIBUTING: one session, one voice). */-const SURFACES = [- 'src/renderer/nodes/TerminalNode.tsx',- 'src/renderer/components/kanban/SessionCard.tsx',- 'src/renderer/components/kanban/CardModal.tsx',- 'src/renderer/components/SessionRow.tsx'-]--describe('live-link guards', () => {- it('no canvas content type carries link state (canvas sync and the canvas authority would publish it)', () => {- const types = read('src/shared/types.ts')- for (const h of [/export interface CanvasNodeState\b/, /export interface ProjectKanban\b/, /export interface Project\b/]) {- expect(block(types, h)).not.toMatch(LINK_STATE)- }- for (const f of ['src/shared/canvas-mutations.ts', 'src/shared/canvas-content.ts']) {- expect(read(f)).not.toMatch(LINK_STATE)- }- })-- it('the renderer serializers and the projects store never read the live-link store', () => {- for (const f of ['src/renderer/state/workspace.ts', 'src/renderer/state/projects.ts']) {- expect(read(f)).not.toMatch(LINK_STATE)- }- })-- it('the LIVE chip is not user-hideable', () => {- // Neither inventory can carry the chip. (The menu ROW "Share live link…" may be hideable; the- // chip that says a terminal IS being broadcast may not.)- expect(HIDEABLE_HEADER_BUTTONS.map((r) => r.id).filter((id) => /live/i.test(id))).toEqual([])- expect([...HIDEABLE_MENU_ITEMS, ...HIDEABLE_HEADER_BUTTONS].map((r) => r.id).filter((id) => /chip|indicator/i.test(id))).toEqual([])- for (const f of SURFACES) {- const src = read(f)- expect(src, f).toMatch(/import \{ LiveLinkChip(, [\w, ]+)? \} from '(\.\.\/|\.\/)(components\/)?LiveLinkChip'/)- const lines = src.split('\n')- const at = lines.findIndex((l) => l.includes('<LiveLinkChip'))- expect(at, `${f} renders <LiveLinkChip`).toBeGreaterThanOrEqual(0)- // Not behind a visibility check: nothing between the previous element that CLOSED (its `/>` or- // `</`) and the chip — the span where a wrapping `{!isHidden(…) && (` would open — nor on the- // three lines above it, however they are laid out…- let from = at - 1- while (from > 0 && !/\/>|<\//.test(lines[from])) from--- expect(lines.slice(Math.max(0, Math.min(from, at - 3)), at + 1).join('\n'), f).not.toMatch(/isHidden|hidden/i)- // …nor anywhere in the file under an id that names the chip.- expect(src, f).not.toMatch(/isHidden\(\s*['"][^'"]*(chip|indicator)/i)- // R57: every chip says which session it is viewed through (a relay copy of a git-shared node- // carries the same id, and must not show this machine's chip). The prop is required, so this- // pins that no surface satisfies it with a constant.- for (const line of lines.filter((l) => l.includes('<LiveLinkChip'))) {- expect(line, f).toMatch(/source=\{/)- expect(line, f).not.toMatch(/source=["']local["']|source=\{['"]local['"]\}/)- }- }- })-- it('R57: the surfaces outside a project\'s SessionProvider resolve the session from the project', () => {- // The boards and the sessions sidebar are not inside the node's SessionProvider (useSession()- // there is the app's local session), so each resolves its project's session and hands it on.- const sidebar = read('src/renderer/components/SessionsSidebar.tsx')- expect((sidebar.match(/<SessionRow\b/g) ?? []).length).toBeGreaterThan(0)- expect((sidebar.match(/liveLinkSource=\{projectSessionSource\(/g) ?? []).length).toBe(- (sidebar.match(/<SessionRow\b/g) ?? []).length- )- for (const f of ['src/renderer/components/kanban/KanbanView.tsx', 'src/renderer/components/kanban/GlobalKanbanView.tsx']) {- const src = read(f)- expect(src, f).toContain('const liveLinkSource = projectSessionSource(projectId)')- const cards = src.split('<SessionCard').slice(1)- expect(cards.length, f).toBeGreaterThan(0)- for (const c of cards) expect(c.slice(0, c.indexOf('/>')), f).toContain('liveLinkSource={liveLinkSource}')- const modals = src.split('<CardModal').slice(1)- expect(modals.length, f).toBeGreaterThan(0)- for (const m of modals) expect(m.slice(0, m.indexOf('/>')), f).toContain('projectId={projectId}')- }- })-- it('no canvas-control verb can publish a terminal', () => {- // The verbs moved: core/canvas-control-core.ts (handlers, agent-facing docs) and- // shared/control-verbs.ts (the verb registry). Neither may name a live link.- for (const f of ['src/core/canvas-control-core.ts', 'src/shared/control-verbs.ts']) {- expect(read(f), f).not.toMatch(LINK_STATE)- }- })-})diff --git a/src/renderer/lib/liveChatLook.test.ts b/src/renderer/lib/liveChatLook.test.tsdeleted file mode 100644index a6338d8e0..000000000--- a/src/renderer/lib/liveChatLook.test.ts+++ /dev/null@@ -1,29 +0,0 @@-import { describe, expect, it } from 'vitest'-import { chatClock, chatNameColor, nearBottom, NEAR_BOTTOM_PX, VIEWER_NAME_COLORS } from './liveChatLook'--describe('the viewer page\'s chat look, copied (nodeterm-web src/lib/watch-viewer/chat-panel.ts)', () => {- it('the same name gets the same colour as on the viewer page (FNV-1a over UTF-16 units)', () => {- // Values computed with the web page's own function: a drift here means the owner sees a viewer- // in a different colour than everyone watching does.- expect(chatNameColor('Mert')).toBe('#ffa657')- expect(chatNameColor('Ayşe')).toBe('#c9b6ff')- expect(chatNameColor('Bob')).toBe('#58a6ff')- expect(chatNameColor('<b>x</b>')).toBe('#58a6ff')- expect(chatNameColor('')).toBe('#ffa657')- expect(VIEWER_NAME_COLORS).toHaveLength(12)- expect(VIEWER_NAME_COLORS).toContain(chatNameColor('\u{1F642}\u{1F642}'))- })-- it('nearBottom: within 32 px of the end counts as reading the newest message', () => {- expect(NEAR_BOTTOM_PX).toBe(32)- expect(nearBottom({ scrollTop: 600, clientHeight: 400, scrollHeight: 1000 })).toBe(true)- expect(nearBottom({ scrollTop: 568, clientHeight: 400, scrollHeight: 1000 })).toBe(true)- expect(nearBottom({ scrollTop: 567, clientHeight: 400, scrollHeight: 1000 })).toBe(false)- })-- it('chatClock: a time the page cannot read is nothing', () => {- expect(chatClock(Number.NaN)).toBe('')- expect(chatClock('1' as unknown as number)).toBe('')- expect(chatClock(Date.UTC(2026, 9, 3, 14, 2))).not.toBe('')- })-})diff --git a/src/renderer/lib/liveChatLook.ts b/src/renderer/lib/liveChatLook.tsdeleted file mode 100644index d51d860bc..000000000--- a/src/renderer/lib/liveChatLook.ts+++ /dev/null@@ -1,46 +0,0 @@-// The live-link viewer page's chat look, for the owner's Live chat drawer. COPIED from nodeterm-web-// `src/lib/watch-viewer/chat-panel.ts` (chatNameColor, VIEWER_NAME_COLORS, nearBottom,-// NEAR_BOTTOM_PX, newMessagesLabel, chatClock) — never imported across repositories.-//-// WHY the drawer and the web page must match: the same viewer gets the same colour on both. The owner-// reads a viewer as "the orange one" in the drawer while everyone watching sees that viewer's lines in-// orange on the page; a drift splits one person into two colours. `liveChatLook.test.ts` pins the-// hash against values computed with the web page's own function — change either side and re-run it.-//-// The hex table is a deliberate exception to "semantic tokens only" (CLAUDE.md, Semantic colours), the-// same class as the agent brand colours: it is ANOTHER surface's palette, and copying it verbatim is-// the point. The drawer hands a colour to CSS as `--live-name`, where the light theme darkens it toward-// the ink (styles.css). The sharer's colour is NOT copied: the drawer marks the owner's lines with a-// token and the "Sharer" badge, and — as on the page — no viewer name is ever drawn in it (the badge is-// the host's word, never a name's).--/** Viewer name colours, readable on the page's near-black. No green near the sharer's. */-export const VIEWER_NAME_COLORS = [- '#ff7b72', '#ffa657', '#f2cc60', '#79c0ff', '#58a6ff', '#a5a0ff',- '#d2a8ff', '#ff9bce', '#f778ba', '#56d4dd', '#ffb4a1', '#c9b6ff'-] as const--/** One colour per name, the same on every viewer's page (FNV-1a over the UTF-16 units). Hash the- * name as the viewer sent it, before any display cleaning, so it matches the page. */-export function chatNameColor(name: string): string {- let h = 0x811c9dc5- for (let i = 0; i < name.length; i++) {- h ^= name.charCodeAt(i)- h = Math.imul(h, 0x01000193)- }- return VIEWER_NAME_COLORS[(h >>> 0) % VIEWER_NAME_COLORS.length]-}--/** How close to the end counts as "reading the newest message" (a fractional scroll position, a line- * still settling). */-export const NEAR_BOTTOM_PX = 32--export function nearBottom(m: { scrollTop: number; clientHeight: number; scrollHeight: number }): boolean {- return m.scrollHeight - m.scrollTop - m.clientHeight <= NEAR_BOTTOM_PX-}--/** "14:02" in the owner's own clock and locale; nothing for a time that cannot be read. */-export function chatClock(at: unknown, locale?: string): string {- if (typeof at !== 'number' || !Number.isFinite(at)) return ''- return new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit' }).format(at)-}diff --git a/src/renderer/lib/liveChatPin.test.ts b/src/renderer/lib/liveChatPin.test.tsdeleted file mode 100644index 602b92cce..000000000--- a/src/renderer/lib/liveChatPin.test.ts+++ /dev/null@@ -1,236 +0,0 @@-import { afterEach, describe, expect, it, vi } from 'vitest'-import type { WatchLinkView } from '@shared/watch-link-types'-import { formatClock } from './liveLink'-import {- chatLinkOptionLabels,- inLiveChatDrawer,- LIVE_CHAT_LINK_KEY,- LIVE_CHAT_PINNED_KEY,- liveChatIsOpen,- liveChatShown,- nextLiveChat,- pickChatLink,- readLiveChatLink,- readLiveChatPinned,- writeLiveChatLink,- writeLiveChatPinned,- type LiveChatState-} from './liveChatPin'--const hidden: LiveChatState = { pinned: false, dismissed: false, open: false, linkId: null }-const modal: LiveChatState = { pinned: false, dismissed: false, open: true, linkId: 'A' }-const docked: LiveChatState = { pinned: true, dismissed: false, open: true, linkId: 'A' }-const dockedHidden: LiveChatState = { pinned: true, dismissed: true, open: false, linkId: 'A' }-/** Launch after a previous pin: shown, but `open` was never set this run. */-const launchPinned: LiveChatState = { pinned: true, dismissed: false, open: false, linkId: null }--const link = (linkId: string, createdAt: number): WatchLinkView => ({- linkId,- nodeId: 'n',- role: 'commenter',- label: 'A',- title: 't',- createdAt,- expiresAt: null,- url: 'u',- status: 'live',- viewers: [],- control: null-})--afterEach(() => vi.unstubAllGlobals())--describe('liveChatIsOpen', () => {- it('follows `open` unpinned and `!dismissed` pinned', () => {- expect(liveChatIsOpen(hidden)).toBe(false)- expect(liveChatIsOpen(modal)).toBe(true)- expect(liveChatIsOpen(docked)).toBe(true)- expect(liveChatIsOpen(dockedHidden)).toBe(false)- expect(liveChatIsOpen(launchPinned)).toBe(true)- })-})--describe('liveChatShown (ruling on concern 3)', () => {- it('pinned: rendered only while at least one link is live — the pin is kept, the drawer comes back', () => {- expect(liveChatShown(docked, 0)).toBe(false)- expect(liveChatShown(launchPinned, 0)).toBe(false)- expect(liveChatShown(docked, 1)).toBe(true)- expect(liveChatShown(launchPinned, 3)).toBe(true)- // Dismissed stays hidden whatever the links.- expect(liveChatShown(dockedHidden, 2)).toBe(false)- })- it('unpinned: an explicit open shows even with no live link ("No live links.")', () => {- expect(liveChatShown(modal, 0)).toBe(true)- expect(liveChatShown(hidden, 0)).toBe(false)- expect(liveChatShown(hidden, 2)).toBe(false)- })-})--describe('nextLiveChat', () => {- it('open shows the drawer, on the named link when there is one, and keeps the pin', () => {- expect(nextLiveChat(hidden, { kind: 'open', linkId: 'B' })).toEqual({ pinned: false, dismissed: false, open: true, linkId: 'B' })- // No link named (the palette): the last link stays.- expect(nextLiveChat({ ...hidden, linkId: 'A' }, { kind: 'open' })).toEqual({ ...modal, linkId: 'A' })- expect(nextLiveChat(dockedHidden, { kind: 'open', linkId: 'C' })).toEqual({ pinned: true, dismissed: false, open: true, linkId: 'C' })- })-- it('close hides without touching the pin or the link', () => {- expect(nextLiveChat(modal, { kind: 'close' })).toEqual({ pinned: false, dismissed: true, open: false, linkId: 'A' })- expect(nextLiveChat(docked, { kind: 'close' })).toEqual({ pinned: true, dismissed: true, open: false, linkId: 'A' })- })-- it('toggle flips what is on screen, the launch-pinned case included', () => {- expect(liveChatIsOpen(nextLiveChat(hidden, { kind: 'toggle' }))).toBe(true)- expect(liveChatIsOpen(nextLiveChat(modal, { kind: 'toggle' }))).toBe(false)- expect(liveChatIsOpen(nextLiveChat(docked, { kind: 'toggle' }))).toBe(false)- expect(liveChatIsOpen(nextLiveChat(dockedHidden, { kind: 'toggle' }))).toBe(true)- expect(liveChatIsOpen(nextLiveChat(launchPinned, { kind: 'toggle' }))).toBe(false)- })-- it('pin docks and shows; unpinning a visible drawer keeps it on screen as the modal', () => {- expect(nextLiveChat(modal, { kind: 'pin' })).toEqual({ pinned: true, dismissed: false, open: true, linkId: 'A' })- expect(nextLiveChat(hidden, { kind: 'pin' })).toEqual({ pinned: true, dismissed: false, open: true, linkId: null })- // If unpinning only flipped `pinned`, the launch-pinned drawer (open never set) would vanish.- expect(nextLiveChat(launchPinned, { kind: 'pin' })).toEqual({ pinned: false, dismissed: false, open: true, linkId: null })- expect(nextLiveChat(docked, { kind: 'pin' })).toEqual({ pinned: false, dismissed: false, open: true, linkId: 'A' })- expect(nextLiveChat(dockedHidden, { kind: 'pin' })).toEqual({ pinned: false, dismissed: false, open: false, linkId: 'A' })- })-})--describe('pickChatLink', () => {- it('the wanted link while it is live', () => {- expect(pickChatLink([link('A', 1), link('B', 2)], 'A')).toBe('A')- })- it('else the most recent link (by creation), ties going to the later one in the list', () => {- expect(pickChatLink([link('A', 1), link('B', 3), link('C', 2)], 'gone')).toBe('B')- expect(pickChatLink([link('A', 1), link('B', 3), link('C', 2)], null)).toBe('B')- expect(pickChatLink([link('A', 5), link('B', 5)], null)).toBe('B')- })- it('nothing when no link is live', () => {- expect(pickChatLink([], 'A')).toBeNull()- expect(pickChatLink([], null)).toBeNull()- })-})--describe('chatLinkOptionLabels (ruling on concern 6: every option reads differently)', () => {- const l = (linkId: string, over: Partial<WatchLinkView> = {}): WatchLinkView => ({ ...link(linkId, 0), ...over })-- it('a unique title and role reads "{title} · {role}"', () => {- expect(- chatLinkOptionLabels([- l('A', { title: 'build', role: 'commenter' }),- l('B', { title: 'build', role: 'controller' }),- l('C', { title: 'api-\u202Eserver', role: 'viewer' }),- l('D', { title: ' ', role: 'viewer' })- ])- ).toEqual(['build · Commenter', 'build · Control', 'api-server · Viewer', 'Terminal · Viewer'])- })-- it('two that read the same are told apart by their own label, when that differs', () => {- expect(- chatLinkOptionLabels([- l('A', { title: 'build', label: 'Ada' }),- l('B', { title: 'build', label: 'Team \u202Edemo' })- ])- ).toEqual(['build · Commenter · shown as Ada', 'build · Commenter · shown as Team demo'])- })-- it('still the same: the start time is appended ("· since 14:05")', () => {- const t1 = Date.UTC(2026, 9, 3, 12, 5)- const t2 = Date.UTC(2026, 9, 3, 13, 40)- expect(- chatLinkOptionLabels([- l('A', { title: 'build', label: 'Ada', createdAt: t1 }),- l('B', { title: 'build', label: 'Ada', createdAt: t2 }),- l('C', { title: 'logs', label: 'Ada', createdAt: t2 })- ])- ).toEqual([- // The same label tells nothing apart, so it is not added.- `build · Commenter · since ${formatClock(t1)}`,- `build · Commenter · since ${formatClock(t2)}`,- 'logs · Commenter'- ])- // A label that differs AND a start time, where only the time separates two of three.- expect(- chatLinkOptionLabels([- l('A', { title: 'build', label: 'Ada', createdAt: t1 }),- l('B', { title: 'build', label: 'Ada', createdAt: t2 }),- l('C', { title: 'build', label: 'Team', createdAt: t2 })- ])- ).toEqual([- `build · Commenter · shown as Ada · since ${formatClock(t1)}`,- `build · Commenter · shown as Ada · since ${formatClock(t2)}`,- 'build · Commenter · shown as Team'- ])- })-- it('even started the same minute, every label is unique', () => {- const t = Date.UTC(2026, 9, 3, 12, 5)- const labels = chatLinkOptionLabels([l('A', { createdAt: t }), l('B', { createdAt: t }), l('C', { createdAt: t })])- expect(new Set(labels).size).toBe(3)- expect(labels).toEqual(['t · Commenter', 't · Commenter (2)', 't · Commenter (3)'])- })-})--describe('inLiveChatDrawer', () => {- it('anything inside the drawer, nothing outside; non-elements are outside', () => {- expect(inLiveChatDrawer(null)).toBe(false)- expect(inLiveChatDrawer({} as EventTarget)).toBe(false)- const inside = { closest: (sel: string) => (sel === '[data-live-chat-drawer]' ? {} : null) }- const outside = { closest: () => null }- expect(inLiveChatDrawer(inside as unknown as EventTarget)).toBe(true)- expect(inLiveChatDrawer(outside as unknown as EventTarget)).toBe(false)- })-})--describe('storage', () => {- it('pin: reads and writes its own key as 1/0, off by default', () => {- const store: Record<string, string> = {}- const get = (k: string): string | null => store[k] ?? null- const set = (k: string, v: string): void => void (store[k] = v)- expect(readLiveChatPinned(get)).toBe(false)- writeLiveChatPinned(true, set)- expect(store[LIVE_CHAT_PINNED_KEY]).toBe('1')- expect(readLiveChatPinned(get)).toBe(true)- writeLiveChatPinned(false, set)- expect(store[LIVE_CHAT_PINNED_KEY]).toBe('0')- expect(readLiveChatPinned(get)).toBe(false)- expect(LIVE_CHAT_PINNED_KEY).toBe('nodeterm.liveChatPinned')- })-- it('the last link: remembered under its own key; an empty or non-string value is no link', () => {- const store: Record<string, string> = {}- const get = (k: string): string | null => store[k] ?? null- const set = (k: string, v: string): void => void (store[k] = v)- expect(readLiveChatLink(get)).toBeNull()- writeLiveChatLink('L1', set)- expect(store[LIVE_CHAT_LINK_KEY]).toBe('L1')- expect(readLiveChatLink(get)).toBe('L1')- store[LIVE_CHAT_LINK_KEY] = ''- expect(readLiveChatLink(get)).toBeNull()- expect(LIVE_CHAT_LINK_KEY).toBe('nodeterm.liveChatLink')- })-- it('a throwing localStorage (private window, blocked site data) reads as nothing and never throws', () => {- const throwing = {- getItem: () => {- throw new Error('blocked')- },- setItem: () => {- throw new Error('quota')- }- }- vi.stubGlobal('localStorage', throwing)- expect(readLiveChatPinned()).toBe(false)- expect(readLiveChatLink()).toBeNull()- expect(() => writeLiveChatPinned(true)).not.toThrow()- expect(() => writeLiveChatLink('L')).not.toThrow()- })-- it('a missing localStorage (no DOM) reads as nothing too', () => {- vi.stubGlobal('localStorage', undefined)- expect(readLiveChatPinned()).toBe(false)- expect(readLiveChatLink()).toBeNull()- expect(() => writeLiveChatPinned(true)).not.toThrow()- })-})diff --git a/src/renderer/lib/liveChatPin.ts b/src/renderer/lib/liveChatPin.tsdeleted file mode 100644index 47a4757d7..000000000--- a/src/renderer/lib/liveChatPin.ts+++ /dev/null@@ -1,149 +0,0 @@-// The Live chat drawer's visibility: the Explorer drawer's pin pattern (lib/explorerPin.ts), with its-// own keys. This machine only, in localStorage — never settings.json or project.json: which link the-// owner follows is one person's view state, and a live link is not canvas content.-//-// pinned — persisted preference: docked, does not block the canvas (default off)-// dismissed — transient "hide for now" (the ×). Does NOT clear the pin.-// open — unpinned (modal) visibility-// linkId — the link the owner picked last (Open chat on a chip, the drawer's picker). The drawer-// shows it while it is live, else the most recent link (`pickChatLink`).-import type { WatchLinkView } from '@shared/watch-link-types'-import { stripBidiControls } from '@shared/watch-link-types'-import { formatClock, ROLE_NAME } from './liveLink'--export const LIVE_CHAT_PINNED_KEY = 'nodeterm.liveChatPinned'-export const LIVE_CHAT_LINK_KEY = 'nodeterm.liveChatLink'--export interface LiveChatState {- pinned: boolean- dismissed: boolean- open: boolean- linkId: string | null-}--export type LiveChatAction = { kind: 'open'; linkId?: string } | { kind: 'toggle' } | { kind: 'close' } | { kind: 'pin' }--/** Pinned: shown unless dismissed. Unpinned: `open` is the modal flag. */-export function liveChatIsOpen(s: LiveChatState): boolean {- return s.pinned ? !s.dismissed : s.open-}--/**- * Whether the drawer is RENDERED. A pinned drawer is docked chrome: with no live link it would be an- * empty card taking canvas width (and inset every maximize for nothing), so it shows only while at- * least one link is live — the pin is kept and it comes back with the next link. An unpinned drawer- * the owner explicitly opened shows even with none ("No live links.").- */-export function liveChatShown(s: LiveChatState, liveLinks: number): boolean {- return liveChatIsOpen(s) && (!s.pinned || liveLinks > 0)-}--export function nextLiveChat(s: LiveChatState, a: LiveChatAction): LiveChatState {- switch (a.kind) {- case 'open':- return { ...s, dismissed: false, open: true, linkId: a.linkId ?? s.linkId }- case 'close':- return { ...s, dismissed: true, open: false }- case 'toggle':- return liveChatIsOpen(s) ? { ...s, dismissed: true, open: false } : { ...s, dismissed: false, open: true }- case 'pin':- // (Re)pinning shows the docked drawer. Unpinning a visible drawer keeps it on screen as the- // modal even when `open` was never set — the launch-pinned case (`pinned && !dismissed`).- return s.pinned- ? { ...s, pinned: false, dismissed: false, open: liveChatIsOpen(s) }- : { ...s, pinned: true, dismissed: false, open: true }- }-}--/** The link to show: `wanted` while it is live, else the most recently created one (a tie goes to the- * later one in the list), else none. */-export function pickChatLink(links: readonly WatchLinkView[], wanted: string | null): string | null {- if (wanted !== null && links.some((l) => l.linkId === wanted)) return wanted- let best: WatchLinkView | null = null- for (const l of links) if (!best || l.createdAt >= best.createdAt) best = l- return best ? best.linkId : null-}--/**- * The picker's option per link, in list order — every one reads differently. "{title} · {role}"; two- * that read the same add the link's own label ("· shown as Ada" — the name viewers see for the- * owner, so only where it differs between them); still the same, the start time ("· since 14:05");- * still the same (started the same minute), a counter. Titles and labels are bidi-stripped.- */-export function chatLinkOptionLabels(links: readonly WatchLinkView[]): string[] {- /** Within each group of identical labels, append `extra` — unless it is the same for the whole- * group, where it would tell nothing apart. */- const disambiguate = (labels: string[], extra: (l: WatchLinkView) => string): string[] => {- const groups = new Map<string, Set<string>>()- labels.forEach((t, i) => groups.set(t, (groups.get(t) ?? new Set()).add(extra(links[i]))))- return labels.map((t, i) => {- const extras = groups.get(t)!- if (labels.filter((x) => x === t).length < 2 || extras.size < 2) return t- const more = extra(links[i])- return more ? `${t} · ${more}` : t- })- }- let labels = links.map((l) => `${stripBidiControls(l.title).trim() || 'Terminal'} · ${ROLE_NAME[l.role]}`)- labels = disambiguate(labels, (l) => {- const label = stripBidiControls(l.label).trim()- return label ? `shown as ${label}` : ''- })- labels = disambiguate(labels, (l) => `since ${formatClock(l.createdAt)}`)- const seen = new Map<string, number>()- return labels.map((t) => {- const n = (seen.get(t) ?? 0) + 1- seen.set(t, n)- return n === 1 ? t : `${t} (${n})`- })-}--/** The attribute that marks the drawer's root, so other surfaces can leave its keys alone. */-export const LIVE_CHAT_DRAWER_ATTR = 'data-live-chat-drawer'--/**- * Is this event target inside the Live chat drawer? The kanban card modal's capture-phase Escape asks:- * a raised, pinned drawer is not a dialog, so the card modal under it is the top dialog — and closed- * itself on an Escape the owner typed in the drawer's reply box.- */-export function inLiveChatDrawer(target: EventTarget | null): boolean {- const el = target as { closest?: unknown } | null- return !!el && typeof el.closest === 'function' && (el as Element).closest(`[${LIVE_CHAT_DRAWER_ATTR}]`) !== null-}--const getStored = (key: string): string | null => localStorage.getItem(key)-const setStored = (key: string, value: string): void => localStorage.setItem(key, value)--/** `'1'` is pinned; missing, `'0'`, unreadable storage or anything else is not. */-export function readLiveChatPinned(getItem: (key: string) => string | null = getStored): boolean {- try {- return getItem(LIVE_CHAT_PINNED_KEY) === '1'- } catch {- return false- }-}--export function writeLiveChatPinned(v: boolean, setItem: (key: string, value: string) => void = setStored): void {- try {- setItem(LIVE_CHAT_PINNED_KEY, v ? '1' : '0')- } catch {- /* private window / blocked storage: the pin is a nicety, never fail the UI */- }-}--/** The last picked link id, or null (none, empty, unreadable storage). */-export function readLiveChatLink(getItem: (key: string) => string | null = getStored): string | null {- try {- const v = getItem(LIVE_CHAT_LINK_KEY)- return typeof v === 'string' && v !== '' ? v : null- } catch {- return null- }-}--export function writeLiveChatLink(linkId: string, setItem: (key: string, value: string) => void = setStored): void {- try {- setItem(LIVE_CHAT_LINK_KEY, linkId)- } catch {- /* not remembered: the drawer falls back to the most recent link */- }-}diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.tsdeleted file mode 100644index f664b323f..000000000--- a/src/renderer/lib/liveLink.test.ts+++ /dev/null@@ -1,634 +0,0 @@-// @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 {- capUnits,- CHAT_NOT_SENT_MESSAGE,- chipView,- formatUntil,- controlLockedText,- controlLockedNoticeText,- watchableOnlyWhileOpen,- commentFromChat,- createErrorMessage,- DEFAULT_TTL,- formatClock,- formatRemaining,- KICK_FAILED_MESSAGE,- KICK_NOT_DONE_MESSAGE,- 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,- CONTROL_LOCKED_TEXT,- CONTROL_UNSUPPORTED_REASON,- controlWarning,- controlWarningMachine,- controlWarningText,- controlTakenText,- LIVE_LINK_EXPOSURE,- liveLinkNoticeEffect,- PASSWORD_SEPARATE_NOTE,- PASSWORD_SHOWN_ONCE,- passwordProblemText,- ROLE_CHOICE,- ROLE_NAME,- ROLE_ORDER,- typingNames,- UNLIMITED_NOTE,- CONTROL_CHANGE_UNSAVED_MESSAGE,- KICK_CONTROLLER_NOTE,- KICK_NOTE,- kickNote-} from './liveLink'-import type { CreateWatchLinkError, WatchLinkView } from '@shared/watch-link-types'-import { DEFAULT_WATCH_LINK_TTL, WATCH_LINK_TTLS } from '@shared/watch-link-types'-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: [],- control: null,- ...over-})-const viewer = (id: string) => ({ viewerId: id, name: null, joinedAt: 0, waiting: false, controlling: false, typing: false })--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',- 'ttl-unsupported',- 'control-unsupported',- 'bad-password'-]--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(link())).toBeNull()- expect(statusLine(link({ status: 'reconnecting' }))).toBe(- "Reconnecting to nodeterm's relay — viewers see no updates until it's back."- )- expect(statusLine(link({ status: '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."- )- })- // R63: a viewer with no session to join is the owner's to fix — never a silent LIVE.- it('a live link with viewers waiting for the terminal says how to let them watch', () => {- const waiting = { ...viewer('w'), waiting: true }- expect(statusLine(link({ viewers: [viewer('a'), waiting] }))).toBe(- 'Viewers are waiting — open this terminal in nodeterm to let them watch.'- )- expect(statusLine(link({ viewers: [viewer('a')] }))).toBeNull()- // A worse state still wins: refused or reconnecting say THAT.- expect(statusLine(link({ status: 'refused', viewers: [waiting] }))).toMatch(/won't host this link/)- })-})--describe('chipView: viewers waiting (R63)', () => {- it('a waiting viewer turns LIVE into an amber "waiting" chip whose title says what to do', () => {- const waiting = { ...viewer('w'), waiting: true }- expect(chipView([link({ viewers: [viewer('a'), waiting] })])).toEqual({- label: 'LIVE · 1 waiting',- tone: 'waiting',- title: 'Viewers are waiting — open this terminal in nodeterm to let them watch.'- })- // refused and reconnecting still win (they need the relay or the service, not an open terminal).- expect(chipView([link({ status: 'reconnecting', viewers: [waiting] })]).tone).toBe('offline')- expect(chipView([link({ viewers: [viewer('a')] })]).tone).toBe('live')- })-})--describe('time', () => {- it('remaining time, hours AND minutes past the hour (M4)', () => {- const MIN = 60_000- expect(formatRemaining(0, 5)).toBe('ended')- expect(formatRemaining(5, 5)).toBe('ended')- expect(formatRemaining(30_000, 0)).toBe('ends in under a minute')- expect(formatRemaining(MIN - 1, 0)).toBe('ends in under a minute')- expect(formatRemaining(MIN, 0)).toBe('ends in 1 min')- expect(formatRemaining(42 * MIN, 0)).toBe('ends in 42 min')- expect(formatRemaining(60 * MIN - 1, 0)).toBe('ends in 59 min')- expect(formatRemaining(60 * MIN, 0)).toBe('ends in 1 h')- expect(formatRemaining(60 * MIN + 1, 0)).toBe('ends in 1 h')- expect(formatRemaining(61 * MIN, 0)).toBe('ends in 1 h 1 min')- expect(formatRemaining(120 * MIN - 1, 0)).toBe('ends in 1 h 59 min')- expect(formatRemaining(120 * MIN, 0)).toBe('ends in 2 h')- expect(formatRemaining(24 * 60 * MIN - 1, 0)).toBe('ends in 23 h 59 min')- expect(formatRemaining(24 * 60 * MIN, 0)).toBe('ends in 24 h')- })- 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()- 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.')- })-- 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(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.')- })-})--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 is neutral: it claims nothing about earlier links and names no cause (H7, H26, R59)', () => {- // R59: the renderer cannot tell "the keychain refused to seal" from "the links file was- // unreadable at boot", and in the second case earlier links are NOT saved — so the copy says- // only what is true in both.- expect(noticeText({ kind: 'not-persistent' })).toBe(- "This link wasn't saved on this computer — it keeps working until you quit."- )- expect(noticeText({ kind: 'not-persistent' })).not.toMatch(/before it|still saved|keychain|secure storage/i)- })-- 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: 'a\u202eb', 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])- // Unlimited is offered, last.- expect(TTL_OPTIONS.map((o) => o.value)).toEqual([900, 3600, 28800, 86400, 0])- // Lowercase: the dialog's row reads "Expires in 1 hour" / "Expires never".- expect(TTL_OPTIONS.map((o) => o.label)).toEqual(['in 15 minutes', 'in 1 hour', 'in 8 hours', 'in 24 hours', 'never'])- // Only "never" carries a hint, and it is the Unlimited note.- expect(TTL_OPTIONS.map((o) => o.hint)).toEqual([undefined, undefined, undefined, undefined, UNLIMITED_NOTE])- 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' })- // The create dialog's menu: the verb the link grants, in the spec's order; Control names its password.- expect(ROLE_ORDER).toEqual(['viewer', 'commenter', 'controller'])- expect(ROLE_CHOICE).toEqual({- viewer: { label: 'can watch', hint: 'Sees the terminal' },- commenter: { label: 'can chat', hint: 'Watches and chats with you' },- controller: { label: 'can type', hint: 'Also types, with a password' }- })- })-})--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 on this computer are disconnected at once; links on other computers stop within a few minutes.'- )- expect(STOP_FAILED_MESSAGE).toBe("The stop didn't reach nodeterm — try again.")- expect(KICK_FAILED_MESSAGE).toBe("The kick didn't reach nodeterm — try again.")- expect(KICK_NOT_DONE_MESSAGE).toBe('That viewer was not disconnected — they may already have left.')- expect(CHAT_NOT_SENT_MESSAGE).toBe("Your reply wasn't sent — viewers didn't see it.")- 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, waiting: false, controlling: false, typing: false }, 0)).toBe('Viewer 1')- expect(viewerName({ viewerId: 'a', name: ' ', joinedAt: 0, waiting: false, controlling: false, typing: false }, 2)).toBe('Viewer 3')- expect(viewerName({ viewerId: 'a', name: 'Bob\u2066', joinedAt: 0, waiting: false, controlling: false, typing: false }, 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')- })-})--// R64/M1: the "until" of a link that ends on another day names the day.-describe('formatUntil', () => {- const at = (d: number, h: number, m: number): number => new Date(2026, 9, d, h, m, 0).getTime()- it('the same day reads as the time alone; the next day as "tomorrow"; later days by date', () => {- expect(formatUntil(at(1, 16, 43), at(1, 15, 43))).toBe(formatClock(at(1, 16, 43)))- expect(formatUntil(at(2, 15, 43), at(1, 15, 43))).toBe(`tomorrow ${formatClock(at(2, 15, 43))}`)- // An 8 h link made at 20:00 ends after midnight: not today.- expect(formatUntil(at(2, 4, 0), at(1, 20, 0))).toBe(`tomorrow ${formatClock(at(2, 4, 0))}`)- const far = formatUntil(at(4, 9, 0), at(1, 9, 0))- expect(far).not.toBe(formatClock(at(4, 9, 0)))- expect(far.endsWith(formatClock(at(4, 9, 0)))).toBe(true)- expect(far.startsWith('tomorrow')).toBe(false)- })-})--describe('capUnits (D2/M3)', () => {- it('caps by UTF-16 units without splitting a surrogate pair', () => {- expect(capUnits('abc', 5)).toBe('abc')- expect(capUnits('x'.repeat(39) + '\u{1F600}', 40)).toBe('x'.repeat(39))- expect(capUnits('x'.repeat(38) + '\u{1F600}', 40)).toBe('x'.repeat(38) + '\u{1F600}')- })-})--// R63: the dialog's "only while open" note — on for a machine with no watcher client of its own.-describe('watchableOnlyWhileOpen', () => {- it('only a local node on a machine whose local terminals are tmux has a watcher client', () => {- const p = (enabled: boolean, backend: string | null) => ({ enabled, backend })- expect(watchableOnlyWhileOpen({ persistence: p(true, 'tmux'), remoteNode: false })).toBe(false)- expect(watchableOnlyWhileOpen({ persistence: p(true, 'session-host'), remoteNode: false })).toBe(true)- expect(watchableOnlyWhileOpen({ persistence: p(true, 'zellij'), remoteNode: false })).toBe(true)- expect(watchableOnlyWhileOpen({ persistence: p(false, 'tmux'), remoteNode: false })).toBe(true)- expect(watchableOnlyWhileOpen({ persistence: p(true, null), remoteNode: false })).toBe(true)- // An SSH node: the host's tmux. Unknown: say nothing.- expect(watchableOnlyWhileOpen({ persistence: p(true, 'session-host'), remoteNode: true })).toBe(false)- expect(watchableOnlyWhileOpen({ persistence: undefined, remoteNode: false })).toBe(false)- expect(watchableOnlyWhileOpen({ persistence: null, remoteNode: false })).toBe(false)- })-- it('a session host that speaks watch-attach can be watched with the node closed', () => {- const p = (backend: string | null, watchJoin?: boolean, enabled = true) => ({ enabled, backend, watchJoin })- expect(watchableOnlyWhileOpen({ persistence: p('session-host', true), remoteNode: false })).toBe(false)- // An older running host, or one not connected yet: the conservative note stays.- expect(watchableOnlyWhileOpen({ persistence: p('session-host', false), remoteNode: false })).toBe(true)- expect(watchableOnlyWhileOpen({ persistence: p('session-host'), remoteNode: false })).toBe(true)- // The flag is the session host's alone, and persistence switched off still wins.- expect(watchableOnlyWhileOpen({ persistence: p('zellij', true), remoteNode: false })).toBe(true)- expect(watchableOnlyWhileOpen({ persistence: p('session-host', true, false), remoteNode: false })).toBe(true)- })-})--// R64/M3: the stream follows the terminal CLIENT, so tmux's chooser and a session switch reach viewers.-describe('the create warning', () => {- it("names tmux's session chooser and a session switch", () => {- expect(LIVE_LINK_EXPOSURE).toMatch(/session chooser/)- expect(LIVE_LINK_EXPOSURE).toMatch(/switch sessions/)- // What every viewer gets, said in the one sentence the dialog keeps for it.- expect(LIVE_LINK_EXPOSURE).toMatch(/scrollback/)- expect(LIVE_LINK_EXPOSURE).toMatch(/anything printed later/)- })-})--// ---- Control and Unlimited (spec 2026-10-03) -------------------------------------------------------describe('Control and Unlimited copy', () => {- it('is the exact ruled text', () => {- // Spec §2.7, with the machine named truthfully (ruling 2): this machine's noun for a local node…- expect(controlWarningText(controlWarningMachine(null))).toBe(- 'With this link and the password, anyone can type here as you: run any command on this computer, or instruct the agent in this terminal.'- )- // …and the host for an SSH project's node, whose shell runs there.- expect(controlWarningText(controlWarningMachine({ user: 'ada', host: 'build.example' }))).toBe(- 'With this link and the password, anyone can type here as you: run any command on [email protected], or instruct the agent in this terminal.'- )- // "and" is the emphasised word: the parts say where it is.- expect(controlWarning('x')[1]).toBe('and')- expect(controlWarning('x').join('')).toBe(controlWarningText('x'))- // The exposure sentence is shown for every role, Control included, so it must not claim nobody types.- expect(LIVE_LINK_EXPOSURE).not.toMatch(/type/)- 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('controlWarningMachine', () => {- it("names the SSH host as user@host, bidi stripped; a host alone without a user; else this machine's noun", () => {- expect(controlWarningMachine(undefined)).toBe('this computer')- expect(controlWarningMachine({ user: 'ada', host: 'build.example' })).toBe('[email protected]')- expect(controlWarningMachine({ user: '', host: 'build.example' })).toBe('build.example')- expect(controlWarningMachine({ user: 'a\u202eda', host: 'bu\u2066ild' })).toBe('ada@build')- })-})--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('only a name the viewer gave itself is quoted: the "Viewer N" placeholder is ours, not a claim', () => {- const nameless = (id: string, name: string | null) => ({ ...viewer(id), name, controlling: true, typing: true })- expect(chipView([link({ viewers: [nameless('a', null)] })]).title).toBe(- 'Viewer 1 is typing. This terminal is shared by a live link — 1 watching.'- )- expect(chipView([link({ viewers: [typing('a', 'Mert'), nameless('b', ' ')] })]).title).toBe(- '\u201cMert\u201d and Viewer 2 are typing. This terminal is shared by a live link — 2 watching.'- )- // A viewer who CALLS itself "Viewer 1" made a claim like any other: quoted.- expect(chipView([link({ viewers: [typing('a', 'Viewer 1')] })]).title).toBe(- '\u201cViewer 1\u201d is typing. This terminal is shared by a live link — 1 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.'- )- })-- // Finding L2: the lock lifts by itself, and the owner is told until when and who tipped it.- it('control-locked from a timed lock says until when and who tipped it — a name as a claim, else "a viewer"', () => {- const now = new Date(2026, 9, 23, 14, 0).getTime()- const until = new Date(2026, 9, 23, 14, 15).getTime()- const at = formatUntil(until, now)- expect(controlLockedNoticeText({ title: 'api-server', by: 'Mert', until }, now)).toBe(- `Control of api-server is locked until ${at} after 10 wrong passwords; the last came from a viewer using the name “Mert”. Allow it again from the LIVE chip.`- )- expect(controlLockedNoticeText({ title: 'api-server', by: null, until }, now)).toBe(- `Control of api-server is locked until ${at} after 10 wrong passwords; the last came from a viewer. Allow it again from the LIVE chip.`- )- // A lock that waits for the owner (no lift time) but names who tipped it.- expect(controlLockedNoticeText({ title: 'api-server', by: ' ', until: null }, now)).toBe(- 'Control of api-server is locked after 10 wrong passwords; the last came from a viewer. Allow it again from the LIVE chip.'- )- // Tomorrow is named as such (a 24 h lock).- expect(controlLockedNoticeText({ title: 'a', by: null, until: until + 24 * 3600_000 }, now)).toContain(`until tomorrow`)- })-- it('the locked line says until when a timed lock lasts, and nothing more for one that waits for the owner', () => {- const now = new Date(2026, 9, 23, 14, 0).getTime()- const until = new Date(2026, 9, 23, 14, 15).getTime()- expect(controlLockedText(until, now)).toBe(`Control locked after 10 wrong passwords, until ${formatUntil(until, now)}.`)- expect(controlLockedText(null, now)).toBe(CONTROL_LOCKED_TEXT)- expect(controlLockedText(undefined, now)).toBe(CONTROL_LOCKED_TEXT)- })-})--describe('final review copy', () => {- it("an owner's narrowing change that could not be saved: applied, undone by a restart, Stop ends it", () => {- expect(CONTROL_CHANGE_UNSAVED_MESSAGE).toBe(- "Applied, but couldn't be saved — it will undo when nodeterm restarts. Stop the link to end it for good."- )- })-- it('the Kick note of a viewer who is controlling says they can unlock again, and how to keep them out', () => {- expect(KICK_CONTROLLER_NOTE).toBe('They can unlock again — change the password or turn typing off to keep them out.')- expect(kickNote({ controlling: false })).toBe(KICK_NOTE)- expect(kickNote({ controlling: true })).toBe(`${KICK_NOTE} ${KICK_CONTROLLER_NOTE}`)- })-})--describe('liveLinkNoticeEffect', () => {- const CONSENT = { notifyOnClaudeDone: true, notifyConsentAsked: true }- const taken = (linkId = 'L') =>- ({ 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 })- })-- // Final review, Minor 7: someone taking control of a terminal is a SECURITY event, not an agent- // finishing: it notifies once the one-time notification question was answered, whatever the- // agent-done preference says.- it('control-taken also raises an OS notification, gated on the notification consent only', () => {- const text = 'Someone using the name “Mert” can now type in api-server.'- expect(liveLinkNoticeEffect(taken(), CONSENT, 0, new Map())).toEqual({- strip: { text, sticky: false },- os: { title: 'Live link', body: text, nodeId: 'n' }- })- // The agent-done preference off: still notified (the caller hands over the whole settings).- const agentDoneOff = { notifyOnClaudeDone: false, notifyConsentAsked: true }- expect(liveLinkNoticeEffect(taken(), agentDoneOff, 0, new Map()).os).toEqual({- title: 'Live link',- body: text,- nodeId: 'n'- })- // The consent question not answered yet: no OS notification (it would raise the OS prompt out of- // nowhere), whatever the preference says.- for (const prefs of [{ notifyOnClaudeDone: true, notifyConsentAsked: false }, {}]) {- const fx = liveLinkNoticeEffect(taken(), prefs, 0, new Map())- expect(fx.os, JSON.stringify(prefs)).toBeNull()- expect(fx.strip?.text).toBe(text)- }- })-- 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.tsdeleted file mode 100644index 4f7a36832..000000000--- a/src/renderer/lib/liveLink.ts+++ /dev/null@@ -1,579 +0,0 @@-// 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,- RevokeAllOutcome,- 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 { controlPasswordProblem, type ControlPasswordProblem } from '@shared/watch-link-password'-import { otherMachines, thisMachine } from './machineName'--export const ROLE_LABEL: Record<WatchLinkRole, string> = {- viewer: 'Can watch',- commenter: 'Can watch and chat',- controller: 'Can watch, chat and type'-}-/** The role's name, as the popover's role line and the chat drawer say it (spec §2.1). */-export const ROLE_NAME: Record<WatchLinkRole, string> = {- viewer: 'Viewer',- commenter: 'Commenter',- controller: 'Control'-}--/** The create dialog's role menu, Figma's "can view ▾" shape: the row reads as a sentence ("Anyone- * with the link can watch"), and the hint says what the choice grants. Control's hint names the- * password, because picking it adds the password row. */-export const ROLE_CHOICE: Record<WatchLinkRole, { label: string; hint: string }> = {- viewer: { label: 'can watch', hint: 'Sees the terminal' },- commenter: { label: 'can chat', hint: 'Watches and chats with you' },- controller: { label: 'can type', hint: 'Also types, with a password' }-}-/** The roles in the menu's order (spec §2.1: viewer, commenter, controller). */-export const ROLE_ORDER: readonly WatchLinkRole[] = ['viewer', 'commenter', 'controller']--/** A `Record` over the shared TTL list, so a TTL added there fails to compile here until it is named.- * Lowercase: the row reads "Expires in 1 hour". */-const TTL_LABEL: Record<WatchLinkTtl, string> = {- 900: 'in 15 minutes',- 3600: 'in 1 hour',- 28800: 'in 8 hours',- 86400: 'in 24 hours',- 0: 'never'-}-/** Unlimited's hint in the expiry menu. */-export const UNLIMITED_NOTE = 'This link works until you stop it.'-/** The create dialog's expiry choices — derived from the list core validates against (H19), so- * Unlimited (`0`, "never") comes last, as the shared list orders it. */-export const TTL_OPTIONS: { value: WatchLinkTtl; label: string; hint?: string }[] = WATCH_LINK_TTLS.map((value) => ({- value,- label: TTL_LABEL[value],- ...(value === 0 ? { hint: UNLIMITED_NOTE } : {})-}))-export const DEFAULT_TTL: WatchLinkTtl = DEFAULT_WATCH_LINK_TTL--/** Always on the create dialog, whatever the role. "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 preview of every session — other projects' agents included) or a- * session switch inside it reaches viewers as well. Short on purpose: the dialog is a row of- * choices, and a paragraph here buried the choices; the facts it must carry are all still in it. */-export const LIVE_LINK_EXPOSURE =- 'Viewers see everything this terminal shows: scrollback, anything printed later (tokens too), and other tmux sessions if you open the session chooser or switch sessions.'-export const KICK_NOTE =- 'Kick ends this connection; anyone with the link can rejoin. Stop sharing to end it for everyone.'-/** After `KICK_NOTE` for a viewer who is controlling: a kicked controller who has the password unlocks- * again as soon as it rejoins. */-export const KICK_CONTROLLER_NOTE = 'They can unlock again — change the password or turn typing off to keep them out.'-/** What Kick does to THIS viewer (the button's title, and the list's note while anyone controls). */-export function kickNote(v: { controlling: boolean }): string {- return v.controlling ? `${KICK_NOTE} ${KICK_CONTROLLER_NOTE}` : KICK_NOTE-}--/**- * The create dialog's typing warning while Control is picked — spec §2.7, with the machine named- * truthfully. It is shown ABOVE `LIVE_LINK_EXPOSURE`, never instead of it: a Control link is a- * Commenter link plus typing, so anyone with the link alone still watches. Three parts so the- * dialog can stress the middle one ("and"); `controlWarningText` is the same words as one string.- */-export function controlWarning(machine: string): [string, string, string] {- return [- 'With this link ',- 'and',- ` the password, anyone can type here as you: run any command on ${machine}, or instruct the agent in this terminal.`- ]-}-export function controlWarningText(machine: string): string {- return controlWarning(machine).join('')-}-/**- * Where a controller's commands run, for the typing warning: an SSH project's node runs its shell on- * the HOST (`user@host`, bidi-stripped — a project's SSH config is the user's own, but it is still- * shown as text); any other node on this machine, named through lib/machineName.- */-export function controlWarningMachine(ssh: { user: string; host: string } | null | undefined): string {- if (!ssh) return thisMachine()- const host = stripBidiControls(ssh.host)- const user = stripBidiControls(ssh.user)- return user ? `${user}@${host}` : host-}-/** 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": the lock of a- * core from before timed locks, which waits for the owner. */-export const CONTROL_LOCKED_TEXT = 'Control locked after 10 wrong passwords.'-/** The locked line, with when it lifts by itself (finding L2) when it does. */-export function controlLockedText(lockedUntil: number | null | undefined, now: number = Date.now()): string {- if (typeof lockedUntil !== 'number' || !Number.isFinite(lockedUntil)) return CONTROL_LOCKED_TEXT- return `Control locked after 10 wrong passwords, until ${formatUntil(lockedUntil, now)}.`-}-/** 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."-/** A NARROWING change (typing off, a new password) answered 'unsaved': it is in force, but the next- * launch would not have it — beside Stop sharing, which ends the link for good. */-export const CONTROL_CHANGE_UNSAVED_MESSAGE =- "Applied, but couldn't be saved — it will undo when nodeterm restarts. Stop the link to end it for good."-/** `setPassword` answered false, or did not answer: the old password still works. */-export const PASSWORD_CHANGE_FAILED_MESSAGE = "The password wasn't changed — try again. The old one still works."-/** How long a password save may hold the popover open before it lets go (`PASSWORD_UNCONFIRMED_MESSAGE`). */-export const PASSWORD_SAVE_TIMEOUT_MS = 30_000-/** A password save with no answer after `PASSWORD_SAVE_TIMEOUT_MS`: whether the old or the new one- * is in force is unknown, so the owner is told to check before handing either out. */-export const PASSWORD_UNCONFIRMED_MESSAGE = "Couldn't confirm the new password. Check the link before sharing it."--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'-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."-/** Kick rejected (the same dropped socket). */-export const KICK_FAILED_MESSAGE = "The kick didn't reach nodeterm — try again."-/** Kick answered false: core found no connected viewer by that id (or its host could not end it). */-export const KICK_NOT_DONE_MESSAGE = 'That viewer was not disconnected — they may already have left.'-/** `sendChat` answered null or rejected: nothing reached the viewers; the draft is kept. */-export const CHAT_NOT_SENT_MESSAGE = "Your reply wasn't sent — viewers didn't see it."-/** 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'-/** The timing is part of the promise (R62): this machine cuts its own viewers itself, while another- * machine learns of the revoke at its next mint (≤ ~90 s) or, for a full link, its status poll. */-export function stopAllConfirmMessage(): string {- return `Stop every live link on your license? This also ends links shared from ${otherMachines()}. Viewers on ${thisMachine()} are disconnected at once; links on ${otherMachines()} stop within a few minutes.`-}-/** Settings, beside Stop all when THIS machine lists no link: the button still reaches the others. */-export function stopAllElsewhereNote(): string {- return `No live links are shared from ${thisMachine()}. Stop all also ends the ones shared from ${otherMachines()} on your license.`-}--/**- * Where "Stop all" is offered (R62): wherever the owner could have links to stop — this machine lists- * one, or holds a Pro license (its links on OTHER machines are invisible here, and Stop all is the one- * control that reaches them: an office desktop left sharing, a lost laptop whose links resume at- * launch). Never in the Server Edition (R43: no license layer, nothing to stop).- */-export function showsStopAll(o: { serverEdition: boolean; entitled: boolean; activeLinks: number }): boolean {- return !o.serverEdition && (o.activeLinks > 0 || o.entitled)-}--/**- * What Stop all says once core answered (R62). This machine's links are always stopped by then; the- * outcome is about the server revoke, the only thing that reaches other machines' links, and a- * success is reported too — with nothing listed here, the sentence is the only sign anything happened.- */-export function stopAllOutcomeText(o: RevokeAllOutcome | unknown): { ok: boolean; text: string } {- switch (o) {- case 'stopped':- return {- ok: true,- text: `Stopped every live link on your license. Links on ${otherMachines()} end within a few minutes.`- }- case 'no-entitlement':- return {- ok: false,- text: `Stopped the live links on ${thisMachine()}. Links shared from ${otherMachines()} can't be stopped from here: ${thisMachine()} has no Pro license. Activate Pro here, or stop them on the machine that shared them.`- }- case 'unsupported':- return { ok: false, text: "Live links can't be stopped from here." }- // `failed`, and anything an older core might answer: the server was not reached.- default:- return {- ok: false,- text: `${STOP_FAILED_MESSAGE} Links on ${thisMachine()} are stopped; links shared from ${otherMachines()} may still be running.`- }- }-}-/** 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' | 'waiting'--/** R63: a connected viewer with no session it may join. On a machine with no watcher client of its- * own (Windows' session host, no local tmux, Zellij) only a terminal open in this app can be- * watched, so the owner is the one who can fix it — and is told how. */-export const VIEWERS_WAITING_MESSAGE = 'Viewers are waiting — open this terminal in nodeterm to let them watch.'--/** How many of a link's (or node's) connected viewers are waiting for a session (R63). */-export function waitingViewers(links: readonly Pick<WatchLinkView, 'viewers'>[]): number {- 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[] {- return typingViewers(links).map((t) => t.name)-}-/** The typing viewers with whether the name is one the viewer GAVE itself (a claim, quoted in a- * sentence) or our "Viewer N" placeholder (ours, never quoted). */-function typingViewers(links: readonly Pick<WatchLinkView, 'viewers'>[]): { name: string; claimed: boolean }[] {- const out: { name: string; claimed: boolean }[] = []- for (const l of links) {- l.viewers.forEach((v, i) => {- if (!v.typing) return- const name = viewerName(v, i)- out.push({ name, claimed: v.name !== null && stripBidiControls(v.name).trim() !== '' })- })- }- 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." — a name the- * viewer gave itself quoted, our "Viewer N" placeholder not. */-function typingSentence(names: readonly { name: string; claimed: boolean }[]): string {- const q = names.map((n) => (n.claimed ? quoted(n.name) : n.name))- 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. 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)- const waiting = waitingViewers(links)- 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."- }- }- 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 = typingViewers(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: watching- }-}--/** One line per link in the popover (and Settings) explaining a state that needs explaining (H9):- * not `live`, or live with viewers waiting for a session (R63). null when there is nothing to say. */-export function statusLine(link: Pick<WatchLinkView, 'status' | 'viewers'>): string | null {- if (link.status === 'reconnecting') return "Reconnecting to nodeterm's relay — viewers see no updates until it's back."- if (link.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."- }- if (waitingViewers([link]) > 0) return VIEWERS_WAITING_MESSAGE- return null-}--/** 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 = Date.now()): string {- if (expiresAt === null) return 'No end time'- 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)- if (min < 60) return `ends in ${min} min`- const h = Math.floor(min / 60)- const m = min % 60- return m === 0 ? `ends in ${h} h` : `ends in ${h} h ${m} 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' })-}--/**- * When a link ends, for "Anyone with this link can watch until …" (R64/M1). The time alone is the- * time TODAY: a 24 h link made at 15:43 read "until 15:43", which looks like it ends now, and an 8 h- * 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 = Date.now()): string {- if (expiresAt === null) return 'you stop it'- const end = new Date(expiresAt)- const today = new Date(now)- const dayStart = (d: Date): number => new Date(d.getFullYear(), d.getMonth(), d.getDate()).getTime()- const days = Math.round((dayStart(end) - dayStart(today)) / 86_400_000)- const time = formatClock(expiresAt)- if (days === 0) return time- if (days === 1) return `tomorrow ${time}`- return `${end.toLocaleDateString([], { weekday: 'short', month: 'short', day: 'numeric' })} ${time}`-}--/**- * At most `max` UTF-16 units — the unit `LABEL_MAX` and the input's `maxLength` count — cut BETWEEN- * code points (D2/M3): a plain `slice` of a prefilled name can split an emoji's surrogate pair.- */-export function capUnits(s: string, max: number): string {- if (s.length <= max) return s- let out = ''- for (const ch of s) {- if (out.length + ch.length > max) break- out += ch- }- return out-}--/**- * R63: whether a link to a node can be watched ONLY while the node is open in this app. A viewer joins- * a session this process holds (the canvas node, a parked view) or — with nothing held — spawns its- * own read-only tmux client; a machine whose LOCAL terminals are not tmux (tmux switched off or- * missing, Zellij) has no such client. The session host has its read-only equivalent (`watch-attach`)- * when the running host speaks it (`watchJoin`); one from an older build does not. An SSH project's- * node runs in the HOST's tmux, which does. Unknown (the status not read yet, or unreadable) claims- * nothing: the popover's waiting line still tells the truth at runtime.- */-export function watchableOnlyWhileOpen(o: {- persistence:- | { enabled: boolean; backend: string | null; watchJoin?: boolean }- | null- | undefined- remoteNode: boolean-}): boolean {- if (o.remoteNode || !o.persistence) return false- if (!o.persistence.enabled) return true- if (o.persistence.backend === 'tmux') return false- return !(o.persistence.backend === 'session-host' && o.persistence.watchJoin === true)-}-export function watchWhileOpenNote(): string {- return `On ${thisMachine()}, viewers can watch this terminal only while it is open in nodeterm; otherwise they wait until you open it.`-}-/** 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."- case 'ttl-unsupported':- return 'Unlimited links need a newer server. Pick an end time.'- case 'control-unsupported':- return CONTROL_UNSUPPORTED_REASON- case 'bad-password':- return 'The password must be 8 to 128 characters, with no line breaks.'- }-}--/**- * 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-}--/**- * "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 lock notice (finding L2): until when, and who tipped it — the name the attempt gave itself, as a- * claim ("a viewer using the name “Mert”"), else "a viewer" — so a kick and a new password are obvious.- * A core from before timed locks sends neither field, and gets the old sentence.- */-export function controlLockedNoticeText(- n: { title: string; by?: string | null; until?: number | null },- now: number = Date.now()-): string {- const title = stripBidiControls(n.title)- if (n.by === undefined && n.until === undefined) {- return `Control of ${title} was locked after 10 wrong passwords. Allow it again from the LIVE chip.`- }- const name = typeof n.by === 'string' ? stripBidiControls(n.by).trim() : ''- const who = name ? `a viewer using the name ${quoted(name)}` : 'a viewer'- const when = typeof n.until === 'number' && Number.isFinite(n.until) ? ` until ${formatUntil(n.until, now)}` : ''- return `Control of ${title} is locked${when} after 10 wrong passwords; the last came from ${who}. Allow it again from the LIVE chip.`-}--/**- * 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':- return `Someone started watching ${stripBidiControls(n.title)} (${n.viewers} watching).`- // Two causes, no reason carried (H7, R59): the keychain refused to seal — only the link just- // created is lost at a restart — or the links file could not be read at boot, in which case the- // earlier links are not being saved either. The renderer cannot tell them apart, so the copy- // says only what is true in both: THIS link is not saved, and it works until the app quits.- case 'not-persistent':- return `This link wasn't saved on ${thisMachine()} — it keeps 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}.`- }- case 'control-taken':- return controlTakenText(n)- case 'control-locked':- return controlLockedNoticeText(n)- default: {- // Compile-time: every known kind is handled above. Runtime: a newer core's kind is no notice.- const unknown: never = n- void unknown- return 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. It is a SECURITY event, not an agent finishing, so it is gated on the notification- * consent alone (`notifyConsentAsked`: the one-time question was answered, so no OS prompt comes out of- * nowhere), never on the agent-done preference (`notifyOnClaudeDone`); main shows it only while the- * window is unfocused, and at most once per link per 5 s. `lastOsAt` is the caller's per-link cooldown- * record; it is written only when a notification is raised.- */-export function liveLinkNoticeEffect(- n: WatchLinkNotice,- prefs: { 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.notifyConsentAsked !== true) return { strip, os: null }- for (const [id, at] of lastOsAt) if (now - at >= NOTIFY_COOLDOWN_MS) lastOsAt.delete(id)- if (lastOsAt.has(n.linkId)) return { strip, os: null }- lastOsAt.set(n.linkId, now)- 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()- 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/lib/liveLinkDefaults.test.ts b/src/renderer/lib/liveLinkDefaults.test.tsdeleted file mode 100644index ac214e4d3..000000000--- a/src/renderer/lib/liveLinkDefaults.test.ts+++ /dev/null@@ -1,43 +0,0 @@-import { describe, expect, it } from 'vitest'-import {- FIRST_LIVE_LINK_DEFAULTS,- LIVE_LINK_DEFAULTS_KEY,- loadLiveLinkDefaults,- parseLiveLinkDefaults,- saveLiveLinkDefaults-} from './liveLinkDefaults'--describe('liveLinkDefaults', () => {- it('a first dialog opens on "can watch" for an hour', () => {- expect(FIRST_LIVE_LINK_DEFAULTS).toEqual({ role: 'viewer', ttl: 3600 })- expect(parseLiveLinkDefaults(null)).toEqual(FIRST_LIVE_LINK_DEFAULTS)- })-- it('round-trips what was saved, under its own key, and nothing else', () => {- const store = new Map<string, string>()- saveLiveLinkDefaults({ role: 'controller', ttl: 0 }, (k, v) => store.set(k, v))- expect([...store.keys()]).toEqual([LIVE_LINK_DEFAULTS_KEY])- expect(JSON.parse(store.get(LIVE_LINK_DEFAULTS_KEY)!)).toEqual({ role: 'controller', ttl: 0 })- expect(loadLiveLinkDefaults((k) => store.get(k) ?? null)).toEqual({ role: 'controller', ttl: 0 })- })-- it('reads each field on its own: an unknown value falls back without costing the other', () => {- expect(parseLiveLinkDefaults('{"role":"admin","ttl":28800}')).toEqual({ role: 'viewer', ttl: 28800 })- expect(parseLiveLinkDefaults('{"role":"commenter","ttl":7200}')).toEqual({ role: 'commenter', ttl: 3600 })- expect(parseLiveLinkDefaults('{"role":"controller","ttl":"0"}')).toEqual({ role: 'controller', ttl: 3600 })- for (const raw of ['not json', '[]', 'null', '42', '"controller"']) expect(parseLiveLinkDefaults(raw)).toEqual(FIRST_LIVE_LINK_DEFAULTS)- })-- it('storage that throws (private mode, blocked site data) never breaks the dialog', () => {- expect(- loadLiveLinkDefaults(() => {- throw new Error('SecurityError')- })- ).toEqual(FIRST_LIVE_LINK_DEFAULTS)- expect(() =>- saveLiveLinkDefaults({ role: 'viewer', ttl: 3600 }, () => {- throw new Error('QuotaExceededError')- })- ).not.toThrow()- })-})diff --git a/src/renderer/lib/liveLinkDefaults.ts b/src/renderer/lib/liveLinkDefaults.tsdeleted file mode 100644index bc048aa43..000000000--- a/src/renderer/lib/liveLinkDefaults.ts+++ /dev/null@@ -1,59 +0,0 @@-// The live-link dialog's remembered choices: the role and the expiry of the last link this person-// CREATED, so a person who shares the same way every time (a Control link for pairing, say) is one-// click from it. Same storage family as the explorer pin (`nodeterm.explorerPinned`): this machine-// only, never settings.json or project.json.-//-// Only the two choices are kept. Never the password (a Control link's plaintext lives in the-// dialog's state alone) and never the label (it comes from the presence name). A first-ever dialog,-// and every value that does not parse, falls back to `can watch` for an hour: remembering may bring-// back a Control link, never invent one.-import type { WatchLinkRole } from '@shared/watch-link/protocol'-import { DEFAULT_WATCH_LINK_TTL, WATCH_LINK_TTLS, type WatchLinkTtl } from '@shared/watch-link-types'--export const LIVE_LINK_DEFAULTS_KEY = 'nodeterm.liveLinkDefaults'--export interface LiveLinkDefaults {- role: WatchLinkRole- ttl: WatchLinkTtl-}--export const FIRST_LIVE_LINK_DEFAULTS: LiveLinkDefaults = { role: 'viewer', ttl: DEFAULT_WATCH_LINK_TTL }--const ROLES: readonly WatchLinkRole[] = ['viewer', 'commenter', 'controller']--/** Each field on its own: a role this build does not know keeps a good expiry, and the reverse. */-export function parseLiveLinkDefaults(raw: string | null): LiveLinkDefaults {- if (!raw) return FIRST_LIVE_LINK_DEFAULTS- let v: unknown- try {- v = JSON.parse(raw)- } catch {- return FIRST_LIVE_LINK_DEFAULTS- }- const o = v && typeof v === 'object' ? (v as { role?: unknown; ttl?: unknown }) : {}- const role = ROLES.find((r) => r === o.role) ?? FIRST_LIVE_LINK_DEFAULTS.role- const ttl = WATCH_LINK_TTLS.find((t) => t === o.ttl) ?? FIRST_LIVE_LINK_DEFAULTS.ttl- return { role, ttl }-}--export function loadLiveLinkDefaults(- getItem: (key: string) => string | null = (key) => localStorage.getItem(key)-): LiveLinkDefaults {- try {- return parseLiveLinkDefaults(getItem(LIVE_LINK_DEFAULTS_KEY))- } catch {- // Private mode, blocked site data: the first-ever defaults, never a broken dialog.- return FIRST_LIVE_LINK_DEFAULTS- }-}--export function saveLiveLinkDefaults(- d: LiveLinkDefaults,- setItem: (key: string, value: string) => void = (key, value) => localStorage.setItem(key, value)-): void {- try {- setItem(LIVE_LINK_DEFAULTS_KEY, JSON.stringify({ role: d.role, ttl: d.ttl }))- } catch {- /* a convenience: a failed write only means the next dialog opens on the first-ever defaults */- }-}diff --git a/src/renderer/lib/liveLinkEntry.gate.test.ts b/src/renderer/lib/liveLinkEntry.gate.test.tsdeleted file mode 100644index 6fd1a07b6..000000000--- a/src/renderer/lib/liveLinkEntry.gate.test.ts+++ /dev/null@@ -1,71 +0,0 @@-// @vitest-environment jsdom-//-// The opener against the REAL Pro gate (state/upgradeGate + state/entitlement): a Server Edition-// tab and a relay tab never open the Upgrade dialog — not for a license layer the server does not-// have (R43), not for a peer's terminal (H4). The pure test (liveLinkEntry.test.tsx) pins the order-// with a fake gate; this one pins what the user actually sees.-import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'-import type { LiveLinkAvailabilityFacts } from './liveLinkEntry'--type Gate = typeof import('../state/upgradeGate')-type Ent = typeof import('../state/entitlement')-let gate: Gate-let ent: Ent-let entry: typeof import('./liveLinkEntry')--beforeAll(async () => {- // The entitlement store subscribes to `license.onChange` when it is created.- ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { license: { onChange: () => () => {} } }- gate = await import('../state/upgradeGate')- ent = await import('../state/entitlement')- entry = await import('./liveLinkEntry')-})--beforeEach(() => {- gate.useUpgradeGate.setState({ open: false, feature: '' })- ent.useEntitlement.setState({ isPremium: false })-})--const facts = (over: Partial<LiveLinkAvailabilityFacts>): LiveLinkAvailabilityFacts => ({- serverEdition: false,- source: 'local',- activeLinks: 0,- ...over-})--function open(f: LiveLinkAvailabilityFacts): { show: ReturnType<typeof vi.fn>; notice: ReturnType<typeof vi.fn> } {- const show = vi.fn()- const notice = vi.fn()- entry.openLiveLink({ facts: () => f, requirePro: gate.requireProOr, show, notice }, { nodeId: 'n', title: 't', projectId: 'p' })- return { show, notice }-}--describe('live-link entry points vs the real Pro gate', () => {- it('Server Edition, not Pro: no Upgrade dialog, the R43 sentence instead', () => {- const r = open(facts({ serverEdition: true }))- expect(gate.useUpgradeGate.getState().open).toBe(false)- expect(r.show).not.toHaveBeenCalled()- expect(r.notice).toHaveBeenCalledWith(- 'Live links need a Pro license on this server — not available in the Server Edition yet'- )- })-- it('relay tab, not Pro: no Upgrade dialog, the relay sentence instead', () => {- const r = open(facts({ source: 'relay' }))- expect(gate.useUpgradeGate.getState().open).toBe(false)- expect(r.notice).toHaveBeenCalledWith('Live links are created on the machine that runs this terminal.')- })-- it('desktop, not Pro: the Upgrade dialog, naming the feature as ruled (R56)', () => {- const r = open(facts({}))- expect(gate.useUpgradeGate.getState()).toMatchObject({ open: true, feature: 'Sharing a live link' })- expect(r.show).not.toHaveBeenCalled()- })-- it('desktop, Pro: straight to the dialog', () => {- ent.useEntitlement.setState({ isPremium: true })- const r = open(facts({}))- expect(gate.useUpgradeGate.getState().open).toBe(false)- expect(r.show).toHaveBeenCalledTimes(1)- })-})diff --git a/src/renderer/lib/liveLinkEntry.test.tsx b/src/renderer/lib/liveLinkEntry.test.tsxdeleted file mode 100644index ca9966912..000000000--- a/src/renderer/lib/liveLinkEntry.test.tsx+++ /dev/null@@ -1,433 +0,0 @@-// @vitest-environment jsdom-// jsdom so `pinNeutralMachineNoun` can pin the machine noun the Stop-all copy names.-import { describe, it, expect, vi } from 'vitest'-import {- liveLinkCommands,- liveLinkMenuItemsFor,- liveLinkMenuRow,- liveLinkNodeFor,- liveLinkPrepare,- liveLinkRemoteFacts,- liveLinkUnavailable,- openLiveLink,- stopAllConfirm,- stopAllLiveLinks,- stopLiveLinks,- type LiveLinkAvailabilityFacts-} from './liveLinkEntry'-import { PRO_GATE_FEATURE, SAVE_FIRST_MESSAGE, STOP_FAILED_MESSAGE } from './liveLink'-import { pinNeutralMachineNoun } from './testMachineNoun'--pinNeutralMachineNoun()--const R43 = 'Live links need a Pro license on this server — not available in the Server Edition yet'-const RELAY = 'Live links are created on the machine that runs this terminal.'-const LIMIT = 'Stop a live link first — 5 can be active at once.'--const facts = (over: Partial<LiveLinkAvailabilityFacts> = {}): LiveLinkAvailabilityFacts => ({- serverEdition: false,- source: 'local',- activeLinks: 0,- ...over-})-const target = { nodeId: 'n1', title: 'build', projectId: 'p1' }--describe('liveLinkUnavailable', () => {- it('reads the surface facts in the H1 order', () => {- expect(liveLinkUnavailable(facts({ serverEdition: true, source: 'relay', activeLinks: 9 }))).toBe(R43)- expect(liveLinkUnavailable(facts({ source: 'relay', activeLinks: 9 }))).toBe(RELAY)- expect(liveLinkUnavailable(facts({ activeLinks: 5 }))).toBe(LIMIT)- expect(liveLinkUnavailable(facts({ activeLinks: 4 }))).toBeNull()- })-})--describe('openLiveLink: the availability rule runs BEFORE the Pro gate (H1, H4)', () => {- const run = (f: LiveLinkAvailabilityFacts) => {- const requirePro = vi.fn((_feature: string, go: () => void) => go())- const show = vi.fn()- const notice = vi.fn()- openLiveLink({ facts: () => f, requirePro, show, notice }, target)- return { requirePro, show, notice }- }-- it('a Server Edition tab never reaches the Pro gate — it is told why instead', () => {- const r = run(facts({ serverEdition: true }))- expect(r.requirePro).not.toHaveBeenCalled()- expect(r.show).not.toHaveBeenCalled()- expect(r.notice).toHaveBeenCalledWith(R43)- })-- it('a relay tab never reaches the Pro gate', () => {- const r = run(facts({ source: 'relay' }))- expect(r.requirePro).not.toHaveBeenCalled()- expect(r.notice).toHaveBeenCalledWith(RELAY)- })-- it('five active links: the limit sentence, no gate', () => {- const r = run(facts({ activeLinks: 5 }))- expect(r.requirePro).not.toHaveBeenCalled()- expect(r.notice).toHaveBeenCalledWith(LIMIT)- })-- it('available: the Pro gate decides, with the ruled feature string, and opens the dialog for the target', () => {- const r = run(facts())- expect(r.requirePro).toHaveBeenCalledTimes(1)- expect(r.requirePro.mock.calls[0][0]).toBe(PRO_GATE_FEATURE)- expect(r.show).toHaveBeenCalledWith(target)- expect(r.notice).not.toHaveBeenCalled()- })-- it('asks the facts for the TARGET project (a relay project is not judged by the active one)', () => {- const f = vi.fn(() => facts())- openLiveLink({ facts: f, requirePro: vi.fn(), show: vi.fn(), notice: vi.fn() }, { ...target, projectId: 'relayed' })- expect(f).toHaveBeenCalledWith('relayed')- })-})--describe('liveLinkMenuRow', () => {- const base = {- node: { id: 'n1', kind: 'terminal', title: 'build' },- projectId: 'p1',- hidden: [] as string[],- facts: facts(),- icon: null,- open: vi.fn()- }-- it('a terminal node gets one enabled row that opens for this node and project', () => {- const open = vi.fn()- const rows = liveLinkMenuRow({ ...base, open })- expect(rows).toHaveLength(1)- const row = rows[0] as { label: string; disabled?: boolean; onClick: () => void }- expect(row.label).toBe('Share live link…')- expect(row.disabled).toBeFalsy()- row.onClick()- expect(open).toHaveBeenCalledWith({ nodeId: 'n1', title: 'build', projectId: 'p1' })- })-- it('is disabled WITH its reason, never hidden, where it cannot work', () => {- for (const [f, why] of [- [facts({ serverEdition: true }), R43],- [facts({ source: 'relay' }), RELAY],- [facts({ activeLinks: 5 }), LIMIT]- ] as const) {- const rows = liveLinkMenuRow({ ...base, facts: f })- expect(rows).toHaveLength(1)- expect(rows[0]).toMatchObject({ disabled: true, hint: why })- }- })-- it('no row for a hidden id, a missing node or a non-terminal node', () => {- expect(liveLinkMenuRow({ ...base, hidden: ['live-link'] })).toEqual([])- expect(liveLinkMenuRow({ ...base, node: null })).toEqual([])- expect(liveLinkMenuRow({ ...base, node: { id: 'n1', kind: 'sticky', title: 'x' } })).toEqual([])- })-- it('an untitled node is offered as "Terminal"', () => {- const open = vi.fn()- const row = liveLinkMenuRow({ ...base, node: { id: 'n1', kind: 'terminal', title: ' ' }, open })[0] as { onClick: () => void }- row.onClick()- expect(open).toHaveBeenCalledWith({ nodeId: 'n1', title: 'Terminal', projectId: 'p1' })- })-})--describe('liveLinkNodeFor (R49)', () => {- const live = [{ id: 'n1', type: 'terminal', data: { title: 'live title' } }]- const stored = [- { id: 'n1', kind: 'terminal', title: 'stored title' },- { id: 's1', kind: 'sticky', title: 'note' }- ]-- it('the active project is read from the live canvas', () => {- expect(liveLinkNodeFor({ nodeId: 'n1', projectId: 'a', activeProjectId: 'a', live, stored })).toEqual({- id: 'n1',- kind: 'terminal',- title: 'live title'- })- })-- it('any other project (a non-active sidebar row, an Omni lane) from its stored copy', () => {- expect(liveLinkNodeFor({ nodeId: 'n1', projectId: 'b', activeProjectId: 'a', live: [], stored })).toEqual({- id: 'n1',- kind: 'terminal',- title: 'stored title'- })- // …so the row it feeds is offered there, for THAT project.- const open = vi.fn()- const row = liveLinkMenuRow({- node: liveLinkNodeFor({ nodeId: 'n1', projectId: 'b', activeProjectId: 'a', live: [], stored }),- projectId: 'b',- hidden: [],- facts: facts(),- icon: null,- open- })[0] as { onClick: () => void }- row.onClick()- expect(open).toHaveBeenCalledWith({ nodeId: 'n1', title: 'stored title', projectId: 'b' })- })-- it('a node that is not there, or a hand-mangled stored list, is no node', () => {- expect(liveLinkNodeFor({ nodeId: 'zz', projectId: 'b', activeProjectId: 'a', live, stored })).toBeNull()- expect(liveLinkNodeFor({ nodeId: 'n1', projectId: 'b', activeProjectId: 'a', live, stored: undefined })).toBeNull()- expect(- liveLinkNodeFor({ nodeId: 'n1', projectId: 'b', activeProjectId: 'a', live, stored: 5 as never })- ).toBeNull()- })-})--// D2/M1: the composition Canvas calls for every surface. With a LOCAL tab on screen, a non-active-// RELAY project's sidebar row (or Omni lane card) must be judged by THAT project's session.-describe('liveLinkMenuItemsFor (D2/M1)', () => {- const stored: Record<string, { id: string; kind: string; title: string }[]> = {- 'p-relay': [{ id: 'n9', kind: 'terminal', title: 'theirs' }],- 'p-local': [{ id: 'n1', kind: 'terminal', title: 'ours' }]- }- const factsOf = (projectId: string): LiveLinkAvailabilityFacts =>- facts({ source: projectId === 'p-relay' ? 'relay' : 'local' })- const compose = (over: Partial<Parameters<typeof liveLinkMenuItemsFor>[0]>) =>- liveLinkMenuItemsFor({- nodeId: 'n9',- projectId: 'p-relay',- activeProjectId: 'p-local',- live: [{ id: 'n1', type: 'terminal', data: { title: 'ours' } }],- stored: (pid) => stored[pid],- hidden: [],- facts: factsOf,- icon: null,- open: vi.fn(),- ...over- })-- it("a non-active relay project's node is judged by ITS session, not the active local tab's", () => {- const open = vi.fn()- const rows = compose({ open })- expect(rows).toHaveLength(1)- expect(rows[0]).toMatchObject({ disabled: true, hint: RELAY })- ;(rows[0] as { onClick: () => void }).onClick()- expect(open).toHaveBeenCalledWith({ nodeId: 'n9', title: 'theirs', projectId: 'p-relay' })- })-- it('no project given: the active one, read from the live canvas', () => {- const open = vi.fn()- const rows = compose({ nodeId: 'n1', projectId: undefined, open })- expect(rows[0]).toMatchObject({ disabled: false })- ;(rows[0] as { onClick: () => void }).onClick()- expect(open).toHaveBeenCalledWith({ nodeId: 'n1', title: 'ours', projectId: 'p-local' })- expect(compose({ projectId: undefined, activeProjectId: null })).toEqual([])- })-})--describe('liveLinkPrepare (R47)', () => {- it('nothing to save: no save, no refusal', async () => {- const save = vi.fn(async () => true)- expect(await liveLinkPrepare({ needed: false, conflict: true, save })).toBeNull()- expect(save).not.toHaveBeenCalled()- })-- it('a dirty canvas is saved first', async () => {- const save = vi.fn(async () => true)- expect(await liveLinkPrepare({ needed: true, conflict: false, save })).toBeNull()- expect(save).toHaveBeenCalledTimes(1)- })-- it('never saves over an unresolved conflict', async () => {- const save = vi.fn(async () => true)- expect(await liveLinkPrepare({ needed: true, conflict: true, save })).toBe(SAVE_FIRST_MESSAGE)- expect(save).not.toHaveBeenCalled()- })-- it('a failed or throwing save refuses with the ruled sentence', async () => {- expect(await liveLinkPrepare({ needed: true, conflict: false, save: async () => false })).toBe(SAVE_FIRST_MESSAGE)- expect(- await liveLinkPrepare({- needed: true,- conflict: false,- save: async () => {- throw new Error('disk')- }- })- ).toBe(SAVE_FIRST_MESSAGE)- })-})--describe('Stop all (R48)', () => {- it('the confirm names other machines, is danger-styled, and stops only on confirm', () => {- const close = vi.fn()- const stop = vi.fn()- const spec = stopAllConfirm({ close, stop })- // R62: the timing is part of the promise — at once HERE, within minutes elsewhere.- expect(spec.message).toBe(- 'Stop every live link on your license? This also ends links shared from other computers. Viewers on this computer are disconnected at once; links on other computers stop within a few minutes.'- )- expect(spec.confirmLabel).toBe('Stop all')- expect(spec.danger).toBe(true)- expect(stop).not.toHaveBeenCalled()- spec.onConfirm()- expect(close).toHaveBeenCalled()- expect(stop).toHaveBeenCalledTimes(1)- })-- it('a rejected stop is reported, never swallowed (H23)', async () => {- const onError = vi.fn()- expect(await stopLiveLinks(() => Promise.reject(new Error('socket down')), onError)).toBe(false)- expect(onError).toHaveBeenCalledWith(STOP_FAILED_MESSAGE)- const ok = vi.fn()- expect(await stopLiveLinks(() => Promise.resolve(), ok)).toBe(true)- expect(ok).not.toHaveBeenCalled()- })-})--// R62: what Stop all reached is always said. This machine's links are stopped whatever the answer;-// the outcome is about the server revoke, the only thing that reaches the OTHER machines' links.-describe('stopAllLiveLinks (R62)', () => {- it('a success is reported too (with nothing listed here, nothing else on screen changes)', async () => {- expect(await stopAllLiveLinks(async () => 'stopped')).toEqual({- ok: true,- text: 'Stopped every live link on your license. Links on other computers end within a few minutes.'- })- })- it('no entitlement: this machine stopped, the others could not be — and why', async () => {- const r = await stopAllLiveLinks(async () => 'no-entitlement')- expect(r.ok).toBe(false)- expect(r.text).toBe(- "Stopped the live links on this computer. Links shared from other computers can't be stopped from here: this computer has no Pro license. Activate Pro here, or stop them on the machine that shared them."- )- })- it('a failed server call is NOT a success: the others may still be running', async () => {- const r = await stopAllLiveLinks(async () => 'failed')- expect(r).toEqual({- ok: false,- text: `${STOP_FAILED_MESSAGE} Links on this computer are stopped; links shared from other computers may still be running.`- })- // An answer this build does not know (an older core) reads the same way, never as a success.- expect((await stopAllLiveLinks(async () => undefined as never)).ok).toBe(false)- })- it('a rejection (the Server Edition socket was down) says nothing reached nodeterm', async () => {- expect(await stopAllLiveLinks(() => Promise.reject(new Error('socket')))).toEqual({ ok: false, text: STOP_FAILED_MESSAGE })- })- it('unsupported says so', async () => {- expect((await stopAllLiveLinks(async () => 'unsupported')).ok).toBe(false)- })-})--describe('liveLinkCommands (palette)', () => {- const base = { entitled: false, serverEdition: false, icon: null, chatIcon: null, openChat: () => {} }- it('Manage always; Stop all with links OR a Pro license (R62), labelled for every machine, and it CONFIRMS', () => {- const manage = vi.fn()- const confirmStopAll = vi.fn()- const none = liveLinkCommands({ ...base, activeLinks: 0, manage, confirmStopAll })- expect(none.map((c) => c.id)).toEqual(['live-links-manage'])- // Pro, and nothing listed HERE: links shared from another machine are invisible on this one,- // and Stop all is the only control that reaches them.- const entitled = liveLinkCommands({ ...base, entitled: true, activeLinks: 0, manage, confirmStopAll })- expect(entitled.map((c) => c.id)).toEqual(['live-links-manage', 'live-links-stop-all'])- // Never in the Server Edition (R43): no license layer, nothing to stop.- // The Server Edition lists no link of its own (no license layer): Manage alone. Were one listed,- // its chat would show — and still no Stop all.- const server = liveLinkCommands({ ...base, serverEdition: true, entitled: true, activeLinks: 0, manage, confirmStopAll })- expect(server.map((c) => c.id)).toEqual(['live-links-manage'])- const serverWithLinks = liveLinkCommands({ ...base, serverEdition: true, entitled: true, activeLinks: 3, manage, confirmStopAll })- expect(serverWithLinks.map((c) => c.id)).toEqual(['live-links-manage', 'live-chat'])- const some = liveLinkCommands({ ...base, activeLinks: 2, manage, confirmStopAll })- expect(some.map((c) => c.id)).toEqual(['live-links-manage', 'live-chat', 'live-links-stop-all'])- expect(some[0].label).toBe('Manage live links')- expect(some[2].label).toBe('Stop all live links (every machine on this license)')- some[0].run()- expect(manage).toHaveBeenCalledTimes(1)- some[2].run()- expect(confirmStopAll).toHaveBeenCalledTimes(1)- })-- it('"Live chat" (section View) while any link is live, and it opens the drawer', () => {- const openChat = vi.fn()- const args = { ...base, openChat, manage: () => {}, confirmStopAll: () => {} }- expect(liveLinkCommands({ ...args, activeLinks: 0 }).some((c) => c.id === 'live-chat')).toBe(false)- const chat = liveLinkCommands({ ...args, activeLinks: 1 }).find((c) => c.id === 'live-chat')!- expect(chat.label).toBe('Live chat')- expect(chat.section).toBe('View')- chat.run()- expect(openChat).toHaveBeenCalledTimes(1)- })-})--// Where a node runs, for the create dialog: R63 (does the HOST's tmux give a viewer a client of its-// own?) and the Control warning (on which machine would a controller's commands run?).-describe('liveLinkRemoteFacts', () => {- const box = { user: 'ada', host: 'box.example', port: 22 }- const facts = (o: {- live?: { id: string; data?: Record<string, unknown> }[]- stored?: { id: string; [k: string]: unknown }[]- projectSsh?: unknown- active?: boolean- }) =>- liveLinkRemoteFacts({- nodeId: 'n1',- projectId: 'p',- activeProjectId: o.active === false ? 'other' : 'p',- live: o.live ?? [],- stored: o.stored,- projectSsh: o.projectSsh- })-- it('a node on an SSH host attached to a LOCAL project: its own host, served by the host tmux', () => {- expect(facts({ live: [{ id: 'n1', data: { ssh: box, sshRemoteTmux: true } }] })).toEqual({- remoteNode: true,- sshTarget: { user: 'ada', host: 'box.example' }- })- })-- it('a standalone ssh terminal node: its own host, but R63 stays local (ssh is a LOCAL pty program)', () => {- expect(facts({ live: [{ id: 'n1', data: { ssh: box } }] })).toEqual({- remoteNode: false,- sshTarget: { user: 'ada', host: 'box.example' }- })- })-- it("an SSH project's node: the project's binding on its own host (how THIS user reaches it)", () => {- const server = { user: 'bob', host: 'box.example' }- // The node's `ssh` is a snapshot of whoever created it (sshConnectionIdForProject's rule).- expect(- facts({ live: [{ id: 'n1', data: { ssh: { user: 'alice', host: 'box.example' }, sshRemoteTmux: true } }], projectSsh: server })- ).toEqual({ remoteNode: true, sshTarget: { user: 'bob', host: 'box.example' } })- // No binding on the node: the project's.- expect(facts({ live: [{ id: 'n1', data: {} }], projectSsh: server })).toEqual({- remoteNode: true,- sshTarget: { user: 'bob', host: 'box.example' }- })- // A node attached to ANOTHER host inside the SSH project: that host.- expect(- facts({ live: [{ id: 'n1', data: { ssh: { user: 'cy', host: 'gpu.example' }, sshRemoteTmux: true } }], projectSsh: server })- ).toEqual({ remoteNode: true, sshTarget: { user: 'cy', host: 'gpu.example' } })- })-- it('a local node in a local project: this machine', () => {- expect(facts({ live: [{ id: 'n1', data: {} }] })).toEqual({ remoteNode: false, sshTarget: null })- expect(facts({ live: [] })).toEqual({ remoteNode: false, sshTarget: null })- })-- it("a non-active project's node is read from its stored copy", () => {- expect(facts({ active: false, stored: [{ id: 'n1', ssh: box, sshRemoteTmux: true }] })).toEqual({- remoteNode: true,- sshTarget: { user: 'ada', host: 'box.example' }- })- // The live canvas belongs to another project: never read for this one.- expect(facts({ active: false, live: [{ id: 'n1', data: { ssh: box } }], stored: [{ id: 'n1' }] })).toEqual({- remoteNode: false,- sshTarget: null- })- })-- it('a malformed binding (hand-editable, git-shared input) claims nothing', () => {- for (const ssh of ['box', 5, null, { host: 5, user: 'a' }, { host: '', user: 'a' }, { user: 'a' }]) {- expect(facts({ live: [{ id: 'n1', data: { ssh, sshRemoteTmux: 'yes' } }] }), JSON.stringify(ssh)).toEqual({- remoteNode: false,- sshTarget: null- })- }- // A host with no usable user still names the host.- expect(facts({ live: [{ id: 'n1', data: { ssh: { host: 'box.example', user: 7 } } }] }).sshTarget).toEqual({- user: '',- host: 'box.example'- })- })-})diff --git a/src/renderer/lib/liveLinkEntry.tsx b/src/renderer/lib/liveLinkEntry.tsxdeleted file mode 100644index 557f873a3..000000000--- a/src/renderer/lib/liveLinkEntry.tsx+++ /dev/null@@ -1,335 +0,0 @@-// Live links: the ENTRY POINTS' decisions — one rule for every place that can start or stop a live-// link (the canvas node menu, the sessions-sidebar row, the kanban card menus of both boards, the-// card modal's action, the command palette, Settings). Pure: every surface fact (Server Edition,-// the node's session, the link count, the Pro gate, the save) is handed in by the caller, so the-// ORDER of the checks is testable here rather than buried in an 18k-line component.-//-// The order is the point (task-14-17 reconcile H1/H4, spec §Entry points): the availability rule-// runs BEFORE the Pro gate, so a Server Edition tab or a relay tab is told why it cannot share —-// it never sees an Upgrade dialog for a license layer it does not have, or for a peer's terminal.-import type { ReactNode } from 'react'-import type { Command } from '../components/CommandPalette'-import type { MenuItem } from '../components/ContextMenu'-import type { SessionSource } from '../session/session'-import type { RevokeAllOutcome } from '@shared/watch-link-types'-import {- PRO_GATE_FEATURE,- SAVE_FIRST_MESSAGE,- shareDisabledReason,- showsStopAll,- STOP_ALL_BUTTON,- STOP_ALL_PALETTE_LABEL,- STOP_FAILED_MESSAGE,- stopAllConfirmMessage,- stopAllOutcomeText-} from './liveLink'-import { syncMessageScope } from './messageScopeSync'-import { isHidden } from './ui-visibility'--/** What a "Share live link…" opens a dialog FOR. `projectId` is the node's own project — which- * may be another tab (the Omni board, a non-active sidebar project) — never "the active one". */-export interface LiveLinkTarget {- nodeId: string- title: string- projectId: string-}--/** The facts the availability rule reads, per target project. */-export interface LiveLinkAvailabilityFacts {- /** `isBrowserRuntime()` — the Server Edition has no license layer yet (R43). */- serverEdition: boolean- /** The session the node's PROJECT belongs to. A relay tab's node is another machine's terminal. */- source: SessionSource | null- /** This machine's active links (the store's list length). */- activeLinks: number-}--/** Why a live link cannot be created for a node seen through these facts, or null. */-export function liveLinkUnavailable(f: LiveLinkAvailabilityFacts): string | null {- return shareDisabledReason({ serverEdition: f.serverEdition, relayTab: f.source === 'relay', activeLinks: f.activeLinks })-}--export interface LiveLinkOpenDeps {- facts: (projectId: string) => LiveLinkAvailabilityFacts- /** `requireProOr` (state/upgradeGate). The only caller that may pass the live-link feature. */- requirePro: (feature: string, run: () => void) => void- show: (target: LiveLinkTarget) => void- /** Where an unavailable surface says why (Canvas's info strip). */- notice: (text: string) => void-}--/**- * THE opener. Every entry point ends here (a menu row's click, the card modal's action through- * `nodeterm:live-link`): availability first — its reason is shown and nothing else happens — and- * only then the Pro gate, whose `run` opens the dialog.- */-export function openLiveLink(deps: LiveLinkOpenDeps, target: LiveLinkTarget): void {- const why = liveLinkUnavailable(deps.facts(target.projectId))- if (why) {- deps.notice(why)- return- }- deps.requirePro(PRO_GATE_FEATURE, () => deps.show(target))-}--export const SHARE_LIVE_LINK_LABEL = 'Share live link…'--/** A node as the menu row needs it — resolved by the caller from the live canvas (active project)- * or the stored project (any other), so the row works for a node that is not on screen. */-export interface LiveLinkMenuNode {- id: string- /** React Flow `type` for a live node, `kind` for a stored one — both say 'terminal'. */- kind: string | undefined- title: unknown-}--/**- * Which node a menu row is about, and where to read it (R49): the ACTIVE project's node from the- * live canvas (React Flow is its source of truth — a node opened seconds ago is not in the store- * yet), any other project's from its stored copy. A live link needs no node on screen: core- * attaches join-only, so an Omni-board card or a non-active sidebar row can share too.- */-export function liveLinkNodeFor(o: {- nodeId: string- projectId: string- activeProjectId: string | null- live: readonly { id: string; type?: string; data?: { title?: unknown } }[]- stored: readonly { id: string; kind?: string; title?: unknown }[] | undefined-}): LiveLinkMenuNode | null {- if (o.projectId === o.activeProjectId) {- const n = o.live.find((x) => x.id === o.nodeId)- return n ? { id: n.id, kind: n.type, title: n.data?.title } : null- }- const n = Array.isArray(o.stored) ? o.stored.find((x) => x?.id === o.nodeId) : undefined- return n ? { id: n.id, kind: n.kind, title: n.title } : null-}--/** An SSH binding read off a node or a project: only the two fields the dialog names. */-export interface LiveLinkSshTarget {- user: string- host: string-}-/** A binding read from hand-editable, git-shared data: a non-empty string host, else nothing. */-function sshTargetOf(v: unknown): LiveLinkSshTarget | null {- if (typeof v !== 'object' || v === null) return null- const { host, user } = v as { host?: unknown; user?: unknown }- if (typeof host !== 'string' || !host) return null- return { user: typeof user === 'string' ? user : '', host }-}--/**- * Where a node runs, for the create dialog — the NODE's own SSH binding first, then its project's:- * - `remoteNode` (R63): the node runs in a HOST's tmux, which gives a viewer a client of its own.- * An SSH project's node, and a node attached to an SSH host in a local project (`sshRemoteTmux`).- * NOT a standalone ssh terminal node: `ssh` is a LOCAL pty program there, in this machine's tmux.- * - `sshTarget`: the machine a controller's commands would run on (the Control warning) — the- * remote shell of every one of those, the standalone ssh node included. On its project's own host- * a remote-tmux node runs as the PROJECT's user: its `ssh` is a snapshot of whoever created it,- * and the project's binding is how THIS user reaches that host (`sshConnectionIdForProject`).- * Null: this machine.- * The node comes from the live canvas for the active project, else from the stored copy (R49).- */-export function liveLinkRemoteFacts(o: {- nodeId: string- projectId: string- activeProjectId: string | null- live: readonly { id: string; data?: unknown }[]- stored: readonly { id: string; ssh?: unknown; sshRemoteTmux?: unknown }[] | undefined- projectSsh: unknown-}): { remoteNode: boolean; sshTarget: LiveLinkSshTarget | null } {- let node: { ssh?: unknown; sshRemoteTmux?: unknown } | undefined- if (o.projectId === o.activeProjectId) {- const data = o.live.find((x) => x.id === o.nodeId)?.data- node = typeof data === 'object' && data !== null ? (data as { ssh?: unknown; sshRemoteTmux?: unknown }) : undefined- } else {- node = Array.isArray(o.stored) ? o.stored.find((x) => x?.id === o.nodeId) : undefined- }- const project = sshTargetOf(o.projectSsh)- const own = sshTargetOf(node?.ssh)- const remoteTmux = !!own && node?.sshRemoteTmux === true- const sshTarget = own ? (remoteTmux && project?.host === own.host ? project : own) : project- return { remoteNode: !!project || remoteTmux, sshTarget }-}--/**- * The "Share live link…" row for one node — the ONE builder behind the canvas node menu, the- * sessions-sidebar row (active and non-active projects) and both boards' card menus. Terminal nodes- * only (agents are terminal nodes). Where it cannot work it is DISABLED with the reason (spec: never- * hidden); only the user's own "hide this row" setting removes it.- */-export function liveLinkMenuRow(o: {- node: LiveLinkMenuNode | null- projectId: string- hidden: readonly string[]- facts: LiveLinkAvailabilityFacts- icon: ReactNode- open: (target: LiveLinkTarget) => void-}): MenuItem[] {- if (isHidden('live-link', o.hidden)) return []- if (!o.node || o.node.kind !== 'terminal') return []- const why = liveLinkUnavailable(o.facts)- const title = typeof o.node.title === 'string' && o.node.title.trim() ? o.node.title : 'Terminal'- const target: LiveLinkTarget = { nodeId: o.node.id, title, projectId: o.projectId }- return [- {- label: SHARE_LIVE_LINK_LABEL,- icon: o.icon,- disabled: !!why,- hint: why ?? 'A read-only browser link to this terminal that ends by itself.',- onClick: () => o.open(target)- }- ]-}--/**- * The menu row for one node, composed (D2/M1): which project the node is in (the caller's, else the- * active one), where to read the node (live canvas or stored copy), and the availability facts — of- * THAT project, never the active one. A non-active relay project's sidebar row or Omni lane card was- * judged by the active LOCAL tab's facts, and showed an enabled row the opener then refused.- */-export function liveLinkMenuItemsFor(o: {- nodeId: string- /** The node's own project; absent = the active one (the canvas node menu). */- projectId?: string- activeProjectId: string | null- live: readonly { id: string; type?: string; data?: { title?: unknown } }[]- stored: (projectId: string) => readonly { id: string; kind?: string; title?: unknown }[] | undefined- hidden: readonly string[]- facts: (projectId: string) => LiveLinkAvailabilityFacts- icon: ReactNode- open: (target: LiveLinkTarget) => void-}): MenuItem[] {- const pid = o.projectId ?? o.activeProjectId- if (!pid) return []- return liveLinkMenuRow({- node: liveLinkNodeFor({- nodeId: o.nodeId,- projectId: pid,- activeProjectId: o.activeProjectId,- live: o.live,- stored: o.stored(pid)- }),- projectId: pid,- hidden: o.hidden,- facts: o.facts(pid),- icon: o.icon,- open: o.open- })-}--/**- * R47: before a create, publish pending canvas edits — a node opened seconds ago is not in the- * saved project core checks, and would answer `node-missing`. The existing rule for "publish before- * core reads the store" (`syncMessageScope`): never saves over an unresolved external-edit conflict.- * Null = go ahead; a sentence = nothing was shared, show it and do not call create.- */-export async function liveLinkPrepare(o: {- needed: boolean- conflict: boolean- save: () => Promise<boolean>-}): Promise<string | null> {- const r = await syncMessageScope(o)- return r.ok ? null : SAVE_FIRST_MESSAGE-}--/**- * R48: "Stop all" revokes every link of the LICENSE, other machines included, and cannot be- * undone — so BOTH entry points (palette, Settings) ask first, with the same sentence and a- * danger button. `close` dismisses the dialog; `stop` runs only on confirm.- */-export function stopAllConfirm(o: { close: () => void; stop: () => void }): {- message: string- confirmLabel: string- danger: true- onConfirm: () => void-} {- return {- message: stopAllConfirmMessage(),- confirmLabel: STOP_ALL_BUTTON,- danger: true,- onConfirm: () => {- o.close()- o.stop()- }- }-}--/** Run one link's stop and report a rejection (H23 — the Server Edition's socket can be down).- * Desktop IPC never rejects; this is the belt, not the common path. Resolves true when the stop- * went through. Stop all is `stopAllLiveLinks`: it has an answer to report, not just a rejection. */-export async function stopLiveLinks(stop: () => Promise<void>, onError: (text: string) => void): Promise<boolean> {- try {- await stop()- return true- } catch {- onError(STOP_FAILED_MESSAGE)- return false- }-}--/**- * R62: run Stop all and say what it reached — a success too (with no link listed here, that sentence- * is the only sign anything happened). This machine's links are stopped whatever the answer; the- * outcome is about the server revoke that reaches the others. A rejection (the Server Edition's socket- * was down) means nothing reached nodeterm. Never rejects.- */-export async function stopAllLiveLinks(- revokeAll: () => Promise<RevokeAllOutcome>-): Promise<{ ok: boolean; text: string }> {- try {- return stopAllOutcomeText(await revokeAll())- } catch {- return { ok: false, text: STOP_FAILED_MESSAGE }- }-}--/** The palette's live-link entries. "Live chat" (the drawer) while any link is live here. "Stop all"- * appears wherever the owner could have links to stop (`showsStopAll`: a link listed here, OR a Pro- * license — its links on other machines are invisible here), and its `run` opens the confirm — it- * never stops anything itself. */-export function liveLinkCommands(o: {- activeLinks: number- /** Pro is active on this machine (`useEntitlement` `isPremium`). */- entitled: boolean- /** `isBrowserRuntime()`: no license layer there (R43), so nothing to stop. */- serverEdition: boolean- icon: ReactNode- chatIcon: ReactNode- manage: () => void- /** Open the Live chat drawer (on the link picked last). */- openChat: () => void- confirmStopAll: () => void-}): Command[] {- return [- {- id: 'live-links-manage',- label: 'Manage live links',- hint: 'share watch broadcast stream link public viewers',- icon: o.icon,- run: o.manage- },- ...(o.activeLinks > 0- ? [- {- id: 'live-chat',- label: 'Live chat',- hint: 'live link viewers messages reply people kick control',- section: 'View',- icon: o.chatIcon,- run: o.openChat- }- ]- : []),- ...(showsStopAll({ serverEdition: o.serverEdition, entitled: o.entitled, activeLinks: o.activeLinks })- ? [- {- id: 'live-links-stop-all',- label: STOP_ALL_PALETTE_LABEL,- hint: 'share revoke broadcast',- icon: o.icon,- run: o.confirmStopAll- }- ]- : [])- ]-}diff --git a/src/renderer/lib/localStore.test.ts b/src/renderer/lib/localStore.test.tsindex fca93f75c..e38981bc6 100644--- a/src/renderer/lib/localStore.test.ts+++ b/src/renderer/lib/localStore.test.ts@@ -7,7 +7,7 @@// handled and must stay handled.import { afterEach, describe, expect, it, vi } from 'vitest'-import { readLocal, writeLocal } from './localStore'+import { readLocal, removeLocal, writeLocal } from './localStore'const KEY = 'nodeterm.test.key'@@ -90,6 +90,34 @@ describe('writeLocal', () => {})})+describe('removeLocal', () => {+ it('removes through when storage works', () => {+ const removeItem = vi.fn()+ install({ removeItem })+ removeLocal(KEY)+ expect(removeItem).toHaveBeenCalledWith(KEY)+ })++ it('is silent on a method-less global', () => {+ install({})+ expect(() => removeLocal(KEY)).not.toThrow()+ })++ it('is silent when the removal throws (a blocked origin)', () => {+ install({+ removeItem: () => {+ throw new Error('SecurityError')+ }+ })+ expect(() => removeLocal(KEY)).not.toThrow()+ })++ it('is silent when the global is absent entirely', () => {+ Reflect.deleteProperty(globalThis as object, 'localStorage')+ expect(() => removeLocal(KEY)).not.toThrow()+ })+})+describe('readLocal fallback — the distinction the copy hint depends on', () => {// These four cases ARE `hintSeen()`. It reads `readLocal(KEY, '1') === '1'`, so the fallback is// the whole behaviour: unreadable storage must count as seen (or the hint returns on every copy),diff --git a/src/renderer/lib/localStore.ts b/src/renderer/lib/localStore.tsindex bf640c975..46816b6dc 100644--- a/src/renderer/lib/localStore.ts+++ b/src/renderer/lib/localStore.ts@@ -53,3 +53,13 @@ export function writeLocal(key: string, value: string): void {/* quota, private mode, disabled storage — never fail the UI over a remembered nicety */}}++/** Remove a key, or do nothing when storage is absent, method-less, or throws. */+export function removeLocal(key: string): void {+ try {+ if (typeof localStorage?.removeItem !== 'function') return+ localStorage.removeItem(key)+ } catch {+ /* a blocked origin or a locked-down embedder — removing a nicety may fail quietly */+ }+}diff --git a/src/renderer/lib/nodeActionItems.offCanvas.test.tsx b/src/renderer/lib/nodeActionItems.offCanvas.test.tsxindex d80fa3e90..6f2885864 100644--- a/src/renderer/lib/nodeActionItems.offCanvas.test.tsx+++ b/src/renderer/lib/nodeActionItems.offCanvas.test.tsx@@ -38,7 +38,6 @@ function input(nodes: CanvasNodeState[], over: Partial<OffCanvasCtxInput> = {}):grokModels: () => [],cursorModels: () => [],writes: { setColor: vi.fn(), pickIcon: vi.fn() },- liveLinkMenuItems: () => [],connectedProjectIdForHost: () => undefined,refuse: vi.fn(),...overdiff --git a/src/renderer/lib/nodeActionItems.test.tsx b/src/renderer/lib/nodeActionItems.test.tsxindex e8e5d0eb7..9ffc5178d 100644--- a/src/renderer/lib/nodeActionItems.test.tsx+++ b/src/renderer/lib/nodeActionItems.test.tsx@@ -41,7 +41,6 @@ function fakeCtx(nodes: CanvasNode[], over: Partial<NodeActionCtx> = {}): NodeActoggleCollapseNodes: noop,toggleMarkdown: noop,reloadTerminals: noop,- liveLinkMenuItems: () => [],branchClaude: async () => ({ ok: true }),transferConversation: noop,restartAgentNode: async () => {},@@ -216,32 +215,13 @@ describe('buildNodeActionItems — filters', () => {})it('allow keeps only the listed sections', () => {- const live = vi.fn((): MenuItem[] => [{ label: 'Share live link…', onClick: () => {} }])expect(top(- buildNodeActionItems(['t1'], undefined, fakeCtx([term('t1')], { liveLinkMenuItems: live }), {+ buildNodeActionItems(['t1'], undefined, fakeCtx([term('t1')]), {allow: BOARD_NODE_ACTION_IDS}))- ).toEqual(['[colors]', 'Set icon…', '—', 'Refresh terminal', 'Share live link…'])- })-- it('on the board list the live-link row comes before the account switch', () => {- useSettings.setState({- settings: { ...DEFAULT_SETTINGS, claudeAccounts: [{ id: 'acc1', label: 'Work', createdAt: 0 }] as never }- })- useAgentStatus.setState({ byId: { a1: { state: 'done', sessionId: 's1' } } } as never)- const live = (): MenuItem[] => [{ label: 'Share live link…', onClick: () => {} }]- const rows = top(- buildNodeActionItems(['a1'], undefined, fakeCtx([term('a1', { agentId: 'claude' })], { liveLinkMenuItems: live }), {- allow: BOARD_NODE_ACTION_IDS- })- )- const liveAt = rows.indexOf('Share live link…')- const switchAt = rows.findIndex((r) => r.startsWith('Switch Claude account'))- expect(liveAt).toBeGreaterThan(-1)- expect(switchAt).toBeGreaterThan(-1)- expect(liveAt).toBeLessThan(switchAt)+ ).toEqual(['[colors]', 'Set icon…', '—', 'Refresh terminal'])})it('no spatial row is ever on the board list, nor a row the board owns itself', () => {diff --git a/src/renderer/lib/nodeActionItems.tsx b/src/renderer/lib/nodeActionItems.tsxindex 31746273e..c9f53be19 100644--- a/src/renderer/lib/nodeActionItems.tsx+++ b/src/renderer/lib/nodeActionItems.tsx@@ -85,7 +85,6 @@ export type NodeActionId =| 'collapse'| 'markdown-view'| 'refresh-terminal'- | 'live-link'| 'branch'| 'transfer'| 'restart'@@ -142,7 +141,6 @@ export const BOARD_NODE_ACTION_IDS = ['colors','icon','refresh-terminal',- 'live-link','restart','switch-model','switch-account',@@ -150,8 +148,8 @@ export const BOARD_NODE_ACTION_IDS = [] as const satisfies readonly NodeActionId[]/**- * The card MODAL's actions menu. The modal header already has search, dictate, AI name, color,- * icon and live link, and its terminal has its own refresh (it re-attaches only the modal's own+ * The card MODAL's actions menu. The modal header already has search, dictate, AI name, color+ * and icon, and its terminal has its own refresh (it re-attaches only the modal's own* pty, which is a different action from the canvas node's `respawnNonce` bump), so only the* session-management sections are offered here.*/@@ -209,7 +207,6 @@ export interface NodeActionCtx {toggleCollapseNodes: (ids: string[]) => voidtoggleMarkdown: (ids: string[]) => voidreloadTerminals: (ids: string[]) => void- liveLinkMenuItems: (nodeId: string) => MenuItem[]branchClaude: (nodeId: string, opts?: { at?: { x: number; y: number } }) => Promise<unknown>transferConversation: TransferConversationHandlerrestartAgentNode: (@@ -461,9 +458,6 @@ export function buildNodeActionSections(]: []},- // Share live link… — single terminal only; disabled with its reason where it cannot- // work, hideable as `live-link` (the shared builder applies both).- { id: 'live-link', items: anyTerminal && ids.length === 1 ? ctx.liveLinkMenuItems(ids[0]) : [] },// Conversation actions — Branch, Transfer ▸ (targets, then models), Restart ▸, Pause — sit// together below the view actions, each ONE row: the per-target Transfer list and the six-odd// restart variants used to be spliced in flat, which made an agent node's menu run off screen.@@ -935,7 +929,6 @@ export interface OffCanvasCtxInput {cursorModels: () => GatewayModel[]/** The project's write router (Canvas `nodeWritesFor(projectId)`). */writes: Pick<NodeWrites, 'setColor' | 'pickIcon'>- liveLinkMenuItems: (nodeId: string) => MenuItem[]connectedProjectIdForHost: (host?: string) => string | undefined/** Raised by every row that needs the live canvas. None of them is on a board today* (`BOARD_NODE_ACTION_IDS`); this keeps the day one is added from failing in silence. */@@ -984,7 +977,6 @@ export function offCanvasNodeActionCtx(o: OffCanvasCtxInput): NodeActionCtx {toggleCollapseNodes: refuse,toggleMarkdown: refuse,reloadTerminals: refuse,- liveLinkMenuItems: o.liveLinkMenuItems,branchClaude: refuseLater,transferConversation: refuse,restartAgentNode: refuseLater,diff --git a/src/renderer/lib/nodeterm-events.test.ts b/src/renderer/lib/nodeterm-events.test.tsindex cdd49083f..26cfa5a4a 100644--- a/src/renderer/lib/nodeterm-events.test.ts+++ b/src/renderer/lib/nodeterm-events.test.ts@@ -59,22 +59,3 @@ describe('every nodeterm CustomEvent the renderer dispatches has a listener', ()expect(orphans).toEqual([])})})--// The LIVE chip's "Open chat" (LiveLinkPopover) asks for the Live chat drawer. Task 7 wired a stub-// listener that opened nothing; the drawer's listener REPLACES it — two listeners would open the-// drawer twice, a stub alone opens nothing.-describe('nodeterm:live-chat', () => {- const listened = names(/addEventListener\(\s*['"](nodeterm:live-chat)['"]/g)-- it('has exactly one listener, in Canvas', () => {- expect((listened.get('nodeterm:live-chat') ?? []).map((f) => f.split(path.sep).join('/'))).toEqual(['canvas/Canvas.tsx'])- })-- it('that listener opens the drawer on the link it names', () => {- const src = fs.readFileSync(path.join(RENDERER, 'canvas/Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')- const at = src.indexOf("window.addEventListener('nodeterm:live-chat'")- const effect = src.slice(src.lastIndexOf('useEffect(', at), at)- expect(effect).toContain("nextLiveChat(s, { kind: 'open', linkId })")- expect(effect).toContain('writeLiveChatLink(linkId)')- })-})diff --git a/src/renderer/lib/retiredStorage.test.ts b/src/renderer/lib/retiredStorage.test.tsindex 1a474e89e..28be44d66 100644--- a/src/renderer/lib/retiredStorage.test.ts+++ b/src/renderer/lib/retiredStorage.test.ts@@ -1,3 +1,5 @@+import fs from 'fs'+import path from 'path'import { describe, expect, it } from 'vitest'import { RETIRED_STORAGE_KEYS, removeRetiredStorageKeys } from './retiredStorage'@@ -26,3 +28,13 @@ describe('removeRetiredStorageKeys', () => {expect(() => removeRetiredStorageKeys(undefined)).not.toThrow()})})++// A dropped call compiles; this is the only thing that notices one.+describe('renderer boot', () => {+ it('removes the retired keys before the React root renders, through lib/localStore', () => {+ const boot = fs.readFileSync(path.join(__dirname, '..', 'boot.tsx'), 'utf8').replace(/\r\n/g, '\n')+ const call = boot.indexOf('removeRetiredStorageKeys({ removeItem: removeLocal })')+ expect(call).toBeGreaterThan(-1)+ expect(call).toBeLessThan(boot.indexOf('ReactDOM.createRoot('))+ })+})diff --git a/src/renderer/lib/ui-visibility.test.ts b/src/renderer/lib/ui-visibility.test.tsindex 4906a34ba..fb4350222 100644--- a/src/renderer/lib/ui-visibility.test.ts+++ b/src/renderer/lib/ui-visibility.test.ts@@ -6,6 +6,10 @@ describe('isHidden', () => {expect(isHidden('duplicate', ['duplicate'])).toBe(true)expect(isHidden('mic', ['mic', 'comments'])).toBe(true)})+ it('ignores the retired live-link ids a settings.json from an older build still carries', () => {+ expect(isHidden('live-link', ['live-link', 'share-link'])).toBe(false)+ expect(isHidden('share-link', ['live-link', 'share-link'])).toBe(false)+ })it('shows everything when nothing is listed', () => {for (const { id } of [...HIDEABLE_MENU_ITEMS, ...HIDEABLE_HEADER_BUTTONS])expect(isHidden(id, [])).toBe(false)@@ -28,10 +32,10 @@ describe('hideable inventories', () => {it('list the agreed ids and nothing destructive', () => {expect(HIDEABLE_MENU_ITEMS.map((r) => r.id)).toEqual(['group', 'remove-from-group', 'colors', 'icon', 'duplicate', 'snap-zone', 'collapse',- 'markdown-view', 'refresh-terminal', 'live-link', 'vanilla-restart'+ 'markdown-view', 'refresh-terminal', 'vanilla-restart'])expect(HIDEABLE_HEADER_BUTTONS.map((r) => r.id)).toEqual([- 'context-meter', 'maximize', 'refresh', 'mic', 'ai-name', 'comments', 'share-link', 'hide-fanout', 'tidy-fanout', 'md-hint'+ 'context-meter', 'maximize', 'refresh', 'mic', 'ai-name', 'comments', 'hide-fanout', 'tidy-fanout', 'md-hint'])})it('gives every entry a user-facing label', () => {diff --git a/src/renderer/lib/ui-visibility.ts b/src/renderer/lib/ui-visibility.tsindex 290d865f5..71c4e7a3d 100644--- a/src/renderer/lib/ui-visibility.ts+++ b/src/renderer/lib/ui-visibility.ts@@ -28,9 +28,6 @@ export const HIDEABLE_MENU_ITEMS: readonly HideableRow[] = [{ id: 'collapse', label: 'Collapse / Expand' },{ id: 'markdown-view', label: 'Markdown view' },{ id: 'refresh-terminal', label: 'Refresh terminal' },- // The ROW that opens the create dialog. The LIVE chip that says a terminal IS being broadcast is- // deliberately in neither inventory (lib/live-link.guard.test.ts).- { id: 'live-link', label: 'Share live link' },{ id: 'vanilla-restart', label: 'Restart on subscription' }]@@ -45,9 +42,6 @@ export const HIDEABLE_HEADER_BUTTONS: readonly HideableRow[] = [{ id: 'mic', label: 'Dictate' },{ id: 'ai-name', label: 'Name with AI' },{ id: 'comments', label: 'Comments' },- // The header twin of the node menu's "Share live link…" row. The button may be hidden; the LIVE- // chip it leads to never can (renderer/lib/live-link.guard.test.ts).- { id: 'share-link', label: 'Share live link' },{ id: 'hide-fanout', label: 'Hide cards & connections' },{ id: 'tidy-fanout', label: 'Tidy subagent cards' },// Not in the header proper but the label row right under it (`lib/mdViewHint.ts`); it is thediff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex abb40f057..c596e72eb 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -1422,8 +1422,8 @@ export function ChatPanel({)}</div>{!following && messages.length > 0 && (- // The Live chat drawer's "N new messages ↓" pill (LiveChatDrawer.tsx), plus a bare "↓" while- // nothing new has come in: here the thread is also read back from deep in its history.+ // An "N new messages ↓" pill, plus a bare "↓" while nothing new has come in: the thread is+ // also read back from deep in its history.<buttontype="button"className="confirm__btn primary term-chat__to-latest"diff --git a/src/renderer/nodes/TerminalNode.share-link.test.ts b/src/renderer/nodes/TerminalNode.share-link.test.tsdeleted file mode 100644index 4e8f35298..000000000--- a/src/renderer/nodes/TerminalNode.share-link.test.ts+++ /dev/null@@ -1,48 +0,0 @@-// Source-level: TerminalNode cannot be mounted in a unit test (xterm, the pty transport and React-// Flow's store all live behind it), so the header's "Share live link" button is pinned here. What it-// does after the click — availability, the Pro gate, the dialog — is Canvas's `nodeterm:live-link`-// listener, behaviour-tested through `openLiveLink` in lib/liveLinkEntry.test.tsx.-import { describe, it, expect } from 'vitest'-import { readFileSync } from 'node:fs'-import { join } from 'node:path'--const src = readFileSync(join(__dirname, 'TerminalNode.tsx'), 'utf8').replace(/\r\n/g, '\n')--/** The header button's JSX block, from its hideable guard to the guard that follows it. */-function shareBlock(): string {- const start = src.indexOf("{!isHidden('share-link', hiddenHeaderButtons) && (")- expect(start).toBeGreaterThan(-1)- const end = src.indexOf("{!isHidden('hide-fanout', hiddenHeaderButtons) && (", start)- expect(end).toBeGreaterThan(start)- return src.slice(start, end)-}--describe('TerminalNode header: Share live link', () => {- it('is a hideable header button that opens the live-link flow for THIS node', () => {- const b = shareBlock()- expect(b).toContain("new CustomEvent('nodeterm:live-link'")- expect(b).toContain('nodeId: id')- // A canvas node only ever lives in the active project's canvas.- expect(b).toContain('projectId: owningProjectId()')- expect(b).toContain('<IconBroadcast />')- })-- it('is disabled, with the reason as its tooltip, wherever sharing is unavailable', () => {- const b = shareBlock()- expect(b).toContain('disabled={!!shareLinkWhy}')- expect(b).toContain("label={shareLinkWhy ?? 'Share live link'}")- // The ONE availability rule, judged by this node's session (a relay tab is refused), with a- // primitive store selector so the header does not re-render on every watch-link push.- expect(src).toMatch(/const shareLinkWhy = liveLinkUnavailable\(\{\s*serverEdition: isBrowserRuntime\(\),\s*source: session\.source,/)- expect(src).toContain('const activeLiveLinks = useWatchLinks((s) => s.links.length)')- })-- it('sits between Comments and the cards & connections eye', () => {- const comments = src.indexOf("{!isHidden('comments', hiddenHeaderButtons) && (")- const share = src.indexOf("{!isHidden('share-link', hiddenHeaderButtons) && (")- const eye = src.indexOf("{!isHidden('hide-fanout', hiddenHeaderButtons) && (")- expect(comments).toBeGreaterThan(-1)- expect(comments).toBeLessThan(share)- expect(share).toBeLessThan(eye)- })-})diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex f4e7d79dc..061d15dd0 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -243,7 +243,7 @@ import {} from '../terminal/useMdModeFocus'import { canvasOwnsMarkdownChord } from '../lib/markdownChord'import { carryDraftToChat, carryDraftToTerminal } from '../lib/chatDraftCarry'-import { IconBroadcast, IconChat, IconChevronDown, IconChevronRight, IconClose, IconEye, IconEyeOff, IconGrid, IconMic, IconMoveTo, IconPlay, IconReload, IconSearch, IconSparkle } from '../components/icons'+import { IconChat, IconChevronDown, IconChevronRight, IconClose, IconEye, IconEyeOff, IconGrid, IconMic, IconMoveTo, IconPlay, IconReload, IconSearch, IconSparkle } from '../components/icons'import { NodeLabels } from '../components/kanban/NodeLabels'import { MdViewHintButton } from '../components/MdViewHintButton'import { mdViewHint } from '../lib/mdViewHint'@@ -288,7 +288,6 @@ import { pullBoardFor, useGitHubIssues } from '../state/githubIssues'import type { AgentState } from '@shared/agents/normalize'import type { ClientId } from '@shared/presence'import { PresenceChips } from '../components/PresenceChips'-import { LiveLinkChip } from '../components/LiveLinkChip'import { useAgentNodes } from '../state/agentNodes'import { useTerminalFocus } from '../state/terminalFocus'import { useProjects } from '../state/projects'@@ -302,8 +301,6 @@ import { isRemoteProjectId, useSession, useSessionStores, useActiveSessionPresenimport { relayStatusGates } from '../terminal/relay-status-gates'import { isHostedReadOnly, useHostedReadOnly } from '../state/hostedTeams'import { isBrowserRuntime } from '../bridge/runtime'-import { liveLinkUnavailable } from '../lib/liveLinkEntry'-import { useWatchLinks } from '../state/watchLinks'import { agentLaunchOverride, toggleCollapsed, type CanvasNode } from '../state/workspace'import { NodeColorSwatches } from '../components/NodeColorSwatches'import { AccountChip, useAccountChip } from '../components/AccountChip'@@ -1462,15 +1459,6 @@ export function TerminalNode({// mounted node right away instead of waiting for a remount. Search, Close and the worktree-move// button are absent from `isHidden`'s inventory and stay put whatever the list says.const hiddenHeaderButtons = useSettings((s) => s.settings.hiddenHeaderButtons)- // The header's "Share live link" button: the same availability rule every opener checks before the- // Pro gate (lib/liveLinkEntry). A primitive selector — the header must not re-render on every- // watch-link state push.- const activeLiveLinks = useWatchLinks((s) => s.links.length)- const shareLinkWhy = liveLinkUnavailable({- serverEdition: isBrowserRuntime(),- source: session.source,- activeLinks: activeLiveLinks- })const bodyRef = useRef<HTMLDivElement>(null)const middleClickPaste = useSettings((st) => st.settings.terminalMiddleClickPaste)// Chromium pastes the X PRIMARY selection into xterm's hidden textarea on middle click — a path@@ -6408,9 +6396,6 @@ export function TerminalNode({{showUsage && <ContextMeter sessionId={transcript.sessionId ?? null} fromLaunchId={transcript.fallback} nodeId={id} remote={!!remoteSession} agentId={agentId} />}{/* Who else is in this node. Subscribes to presence itself — see PresenceChips. */}<PresenceChips nodeId={id} />- {/* This terminal is broadcast by a live link — never hideable (live-link.guard.test.ts).- Only through the LOCAL session: a relay tab's node with the same id is not ours (R57). */}- <LiveLinkChip nodeId={id} source={session.source} />{status?.state === 'working' && (<span className="term-node__status term-node__status--busy" title={`${agentLabel} is working`}><AgentMascot agentId={agentId} />@@ -6701,28 +6686,6 @@ export function TerminalNode({</button></Tooltip>)}- {!isHidden('share-link', hiddenHeaderButtons) && (- <Tooltip label={shareLinkWhy ?? 'Share live link'}>- {/* The node menu's "Share live link…" row as a header button. Canvas opens the dialog- (`nodeterm:live-link`) after re-checking availability and the Pro gate; a node only- ever lives in the active project's canvas, so that is the project it names. */}- <button- className="term-node__share nodrag"- aria-label="Share live link"- disabled={!!shareLinkWhy}- onClick={(e) => {- e.stopPropagation()- window.dispatchEvent(- new CustomEvent('nodeterm:live-link', {- detail: { nodeId: id, title: data.title, projectId: owningProjectId() }- })- )- }}- >- <IconBroadcast />- </button>- </Tooltip>- )}{!isHidden('hide-fanout', hiddenHeaderButtons) && (<Tooltip label={hideFanout ? 'Show cards & connections' : 'Hide cards & connections'}><buttondiff --git a/src/renderer/session/agent-status-lookup.test.tsx b/src/renderer/session/agent-status-lookup.test.tsxindex 31f33d290..c88aee38f 100644--- a/src/renderer/session/agent-status-lookup.test.tsx+++ b/src/renderer/session/agent-status-lookup.test.tsx@@ -214,7 +214,6 @@ describe('SessionCard', () => {onDragEnd={noop}onDropAt={noop}onContext={noop}- liveLinkSource="relay"statusStore={statusStore}/>)diff --git a/src/renderer/state/upgradeGate.ts b/src/renderer/state/upgradeGate.tsdeleted file mode 100644index fe31da7cc..000000000--- a/src/renderer/state/upgradeGate.ts+++ /dev/null@@ -1,26 +0,0 @@-import { create } from 'zustand'-import { useEntitlement } from './entitlement'--interface UpgradeGateState {- open: boolean- feature: string- show(feature: string): void- hide(): void-}--export const useUpgradeGate = create<UpgradeGateState>((set) => ({- open: false,- feature: '',- show(feature) {- set({ open: true, feature })- },- hide() {- set({ open: false })- }-}))--/** Run `run` when the user is Pro; otherwise open the upgrade dialog for `feature`. */-export function requireProOr(feature: string, run: () => void): void {- if (useEntitlement.getState().isPremium) run()- else useUpgradeGate.getState().show(feature)-}diff --git a/src/renderer/state/watchLinks.test.ts b/src/renderer/state/watchLinks.test.tsdeleted file mode 100644index f3e89aa1a..000000000--- a/src/renderer/state/watchLinks.test.ts+++ /dev/null@@ -1,300 +0,0 @@-import { describe, it, expect, beforeEach } from 'vitest'-import { EMPTY_LINKS, liveChipSig, startWatchLinkSync, useWatchLinks, viewLinkThread } 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: [],- control: null,- ...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: {}, hydrated: false }))--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, waiting: false, controlling: false, typing: false }] })])- 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, waiting: false, controlling: false, typing: false }] })])- expect(useWatchLinks.getState()).toBe(after)- })-- it('compares EVERY field: a change to any one of them is a new object (M2)', () => {- // A fixture with every field of the type, iterated by key: a field added to WatchLinkView (and- // to this fixture, which the type forces) is covered without editing the comparison.- const base: WatchLinkView = link('a', 'n1', {- viewers: [{ viewerId: 'v', name: 'Eve', joinedAt: 5, waiting: false, controlling: false, typing: false }]- })- const bump = (v: unknown): unknown =>- typeof v === 'number'- ? v + 1- : typeof v === 'string'- ? `${v}x`- : typeof v === 'boolean'- ? !v- : Array.isArray(v)- ? []- : v === null- ? { changed: true }- : v- for (const key of Object.keys(base) as (keyof WatchLinkView)[]) {- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })- useWatchLinks.getState().setLinks([base])- const before = useWatchLinks.getState().links[0]- const changed = { ...base, [key]: bump(base[key]) } as WatchLinkView- expect(changed[key], key).not.toEqual(base[key])- useWatchLinks.getState().setLinks([changed])- expect(useWatchLinks.getState().links[0], key).not.toBe(before)- }- // Every field of a viewer, the name included (a viewer who starts chatting gains a name).- const viewer = base.viewers[0]- for (const key of Object.keys(viewer) as (keyof typeof viewer)[]) {- useWatchLinks.getState().setLinks([base])- const before = useWatchLinks.getState().links[0]- useWatchLinks.getState().setLinks([{ ...base, viewers: [{ ...viewer, [key]: bump(viewer[key]) }] }])- expect(useWatchLinks.getState().links[0], `viewer.${key}`).not.toBe(before)- }- useWatchLinks.getState().setLinks([{ ...base, viewers: [{ ...viewer, name: null }] }])- const unnamed = useWatchLinks.getState().links[0]- useWatchLinks.getState().setLinks([base])- expect(useWatchLinks.getState().links[0]).not.toBe(unnamed)- // A field this build has never heard of is compared too.- const known = useWatchLinks.getState().links[0]- useWatchLinks.getState().setLinks([{ ...base, fromANewerCore: 1 } as WatchLinkView])- expect(useWatchLinks.getState().links[0]).not.toBe(known)- })-- 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 chat for a link the list no longer holds is dropped once a list has landed (N1)', () => {- const s = useWatchLinks.getState()- // Before any list: kept — it can only be for a link not listed yet.- s.addChat('early', msg('0'))- expect(useWatchLinks.getState().chats.early).toHaveLength(1)- s.setLinks([link('a', 'n1')])- expect(useWatchLinks.getState().chats.early).toBeUndefined()- s.addChat('gone', msg('1'))- s.setChat('gone', [msg('2')])- expect(useWatchLinks.getState().chats.gone).toBeUndefined()- expect(useWatchLinks.getState().unread.gone).toBeUndefined()- s.addChat('a', msg('3'))- expect(useWatchLinks.getState().chats.a).toHaveLength(1)- })-- it('a message that lands while its thread is on screen never counts as unread (N2)', () => {- const s = useWatchLinks.getState()- s.setLinks([link('a', 'n1')])- const seen: number[] = []- const off = useWatchLinks.subscribe((st) => seen.push(st.unread.a ?? 0))- const release = viewLinkThread('a')- const release2 = viewLinkThread('a')- s.addChat('a', msg('1'))- release()- s.addChat('a', msg('2')) // still on screen in the other mount- expect(seen.every((n) => n === 0)).toBe(true)- release2()- release2() // idempotent- s.addChat('a', msg('3'))- expect(useWatchLinks.getState().unread.a).toBe(1)- off()- })-- 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.chat!('a', msg('1'))- expect(useWatchLinks.getState().chats.a).toHaveLength(1)- h.state!([])- expect(useWatchLinks.getState().links).toHaveLength(0)- expect(useWatchLinks.getState().chats.a).toBeUndefined()- 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()- })-})--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/state/watchLinks.ts b/src/renderer/state/watchLinks.tsdeleted file mode 100644index 1c9063b30..000000000--- a/src/renderer/state/watchLinks.ts+++ /dev/null@@ -1,244 +0,0 @@-// 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 { useEffect, useState } from 'react'-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>- /** A list has landed (a `list()` answer or a state push). Until then a chat for an unknown link- * is kept — it can only be for a link the list has not told us about yet. */- hydrated: boolean- setLinks(links: WatchLinkView[]): void- addChat(linkId: string, msg: WatchChatMessage): void- setChat(linkId: string, msgs: WatchChatMessage[]): void- markRead(linkId: string): void-}--/**- * Structural equality for the JSON core pushes (primitives, arrays, plain objects). Structural on- * purpose: a hand-written field list silently keeps a stale object when `WatchLinkView` gains a field- * nobody added to it — the `setCo` trap CLAUDE.md records for the cold-resume banner.- */-function sameJson(a: unknown, b: unknown): boolean {- if (Object.is(a, b)) return true- if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false- if (Array.isArray(a) || Array.isArray(b)) {- if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false- return a.every((x, i) => sameJson(x, b[i]))- }- const ra = a as Record<string, unknown>- const rb = b as Record<string, unknown>- const keys = Object.keys(ra)- if (keys.length !== Object.keys(rb).length) return false- return keys.every((k) => Object.prototype.hasOwnProperty.call(rb, k) && sameJson(ra[k], rb[k]))-}--/** Links whose thread someone can see right now (`useLinkThread`: a popover's or the Live chat- * drawer's thread, in a visible, focused window), counted per mount. A message that lands while its- * thread is seen is read the moment it arrives: it never counts as unread, so the chip's count does- * not flash for one render (N2). Not store state: nothing renders from it. */-const viewing = new Map<string, number>()--/** Mark a link's thread as on screen; the returned function takes the mark back. */-export function viewLinkThread(linkId: string): () => void {- viewing.set(linkId, (viewing.get(linkId) ?? 0) + 1)- let done = false- return () => {- if (done) return- done = true- const n = (viewing.get(linkId) ?? 1) - 1- if (n > 0) viewing.set(linkId, n)- else viewing.delete(linkId)- }-}--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)))-}--/** A chat for a link the (hydrated) list no longer holds is dropped (N1): a history answer or a- * push that lands after the link ended would otherwise bring its thread back until the next push. */-function unknownLink(s: WatchLinksState, linkId: string): boolean {- return s.hydrated && !s.links.some((l) => l.linkId === linkId)-}--export const useWatchLinks = create<WatchLinksState>((set) => ({- links: [],- byNode: {},- chats: {},- unread: {},- hydrated: false,-- // 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 && sameJson(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 && s.hydrated) return s- return { links, byNode, chats, unread, hydrated: true }- }),-- addChat: (linkId, msg) =>- set((s) => {- if (unknownLink(s, linkId)) return 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- const unseen = msg.from === 'viewer' && !viewing.has(linkId)- return {- chats: { ...s.chats, [linkId]: [...chat, msg].slice(-CHAT_KEEP) },- unread: unseen ? { ...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) => {- if (unknownLink(s, linkId)) return 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))-}))--/** Someone can see this window: it is visible and has the focus. */-function documentSeen(): boolean {- return typeof document !== 'undefined' && document.visibilityState === 'visible' && document.hasFocus()-}--/** `documentSeen`, re-evaluated when the window gains or loses focus or is hidden or shown. */-function useDocumentSeen(): boolean {- const [seen, setSeen] = useState(documentSeen)- useEffect(() => {- const update = (): void => setSeen(documentSeen())- // `blur` is the window losing focus: answer false outright — `hasFocus()` during the event is not- // something to lean on.- const blur = (): void => setSeen(false)- update()- window.addEventListener('focus', update)- window.addEventListener('blur', blur)- document.addEventListener('visibilitychange', update)- return () => {- window.removeEventListener('focus', update)- window.removeEventListener('blur', blur)- document.removeEventListener('visibilitychange', update)- }- }, [])- return seen-}--/**- * The thread rule for a link's chat on screen — the chip's popover and the Live chat drawer, ONE- * definition. A message counts as read only while someone can SEE it: the thread is mounted AND the- * window is visible and focused (a pinned drawer stays mounted behind another app, and the chip's- * count is how the owner learns something arrived). While seen, what lands is read as it arrives- * (`viewLinkThread`, N2) and what arrived before is read (`markRead`, H21) — on open, and again each- * time the window comes back. Core's history is asked once (a reload, or messages pushed before this- * renderer subscribed — the store merges the two).- */-export function useLinkThread(linkId: string, api: Pick<NodeTerminalApi['watchLink'], 'chatHistory'>): void {- const seen = useDocumentSeen()- useEffect(() => {- if (!seen) return- useWatchLinks.getState().markRead(linkId)- return viewLinkThread(linkId)- }, [linkId, seen])- useEffect(() => {- void api.chatHistory(linkId).then(- (m) => useWatchLinks.getState().setChat(linkId, m),- () => {}- )- }, [api, linkId])-}--/**- * 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()- }-}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex f1c6c6623..d2a1bf9a5 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -2514,7 +2514,6 @@ body,.term-node__close,.term-node__move-worktree,.term-node__hide-fanout,-.term-node__share,.term-node__tidy-fanout {display: inline-flex;align-items: center;@@ -2544,7 +2543,6 @@ body,.term-node__maximize:hover,.term-node__move-worktree:hover,.term-node__hide-fanout:hover,-.term-node__share:hover:not(:disabled),.term-node__tidy-fanout:hover {background: rgba(var(--tint-rgb), 0.1);color: var(--text);@@ -2556,8 +2554,7 @@ body,color: var(--danger);}-.term-node__ai:disabled,-.term-node__share:disabled {+.term-node__ai:disabled {opacity: 0.6;cursor: default;}@@ -3384,7 +3381,7 @@ body,display: flex;flex-direction: column;}-/* The Live chat drawer's "N new messages ↓" pill (.live-chat__more): same position and shape. */+/* The "N new messages ↓" pill. */.term-chat__thread .confirm__btn.term-chat__to-latest {position: absolute;bottom: 8px;@@ -12785,670 +12782,6 @@ button.pull-checks__name {background: var(--state-warning);border-color: transparent;}-/* Live link chip — "this terminal is being broadcast" (components/LiveLinkChip.tsx), one component on- the node header, the kanban card, the card modal and the sessions sidebar row. The dot reads the- ERROR role on purpose (task-14-17 H28): the spec asks for a red broadcast dot, and a role of its own- would have to pass styles.palette.test's one-colour-per-meaning pins. The label stays ink (muted- when refused, as the spec asks). Never animated: a chip that pulsed for as long as a link lives- would hold the compositor's frame loop open (CLAUDE.md, Idle energy). */-.live-chip {- --live-tone: var(--state-error);- display: inline-flex;- flex: 0 0 auto;- align-items: center;- gap: 5px;- height: 18px;- margin-left: 6px;- padding: 0 7px;- border: 1px solid color-mix(in srgb, var(--live-tone) 45%, transparent);- border-radius: 9px;- background: color-mix(in srgb, var(--live-tone) 12%, transparent);- color: var(--text);- font: inherit;- font-size: 10.5px;- font-weight: 600;- letter-spacing: 0.02em;- line-height: 1;- white-space: nowrap;- cursor: pointer;-}-.live-chip:hover {- background: color-mix(in srgb, var(--live-tone) 20%, transparent);-}-.live-chip__dot {- flex: 0 0 auto;- width: 6px;- height: 6px;- border-radius: 50%;- background: var(--live-tone);-}-/* Reconnecting: the relay leg is down; it comes back on its own. */-.live-chip--offline {- --live-tone: var(--state-warning);-}-/* Viewers are waiting for a session they may join (R63): the owner has to open the terminal. */-.live-chip--waiting {- --live-tone: var(--state-warning);-}-/* Refused: nodeterm's service will not host the link — muted, the owner opens it to see why. */-.live-chip--refused {- --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 {- 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 {- margin-left: 0;-}-.ss-live {- flex: 0 0 auto;- height: 16px;- margin-left: 0;- padding: 0 5px;- font-size: 10px;-}-/* Its popover: a body portal above the card modal's scrim (55) and the dictation overlay (60). A- solid --panel: under Liquid Glass it is not in either glass list, so it stays opaque. */-.live-pop__scrim {- position: fixed;- inset: 0;- z-index: 61;-}-.live-pop {- position: fixed;- z-index: 62;- box-sizing: border-box;- width: 340px;- max-width: calc(100vw - 12px);- max-height: 70vh;- overflow: auto;- padding: 10px 12px;- border: 1px solid var(--border);- border-radius: 10px;- background: var(--panel);- box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);- color: var(--text);- font-size: 12px;- line-height: 1.4;- text-align: left;- cursor: default;-}-.live-pop:focus {- outline: none;-}-:is(.live-pop, .live-chat__body) p {- margin: 0;-}-.live-pop__link + .live-pop__link {- margin-top: 10px;- padding-top: 10px;- border-top: 1px solid var(--border);-}-.live-pop__head {- display: flex;- justify-content: space-between;- align-items: baseline;- gap: 8px;-}-.live-pop__role,-.live-pop__who {- font-weight: 600;- overflow-wrap: anywhere;-}-.live-pop__time,-.live-pop__muted {- color: var(--muted);-}-.live-pop p.live-pop__label {- margin-top: 2px;- overflow-wrap: anywhere;-}-:is(.live-pop, .live-chat__body) p.live-pop__status {- margin-top: 6px;- padding: 6px 8px;- border-radius: 6px;- background: color-mix(in srgb, var(--state-warning) 12%, transparent);-}-:is(.live-pop, .live-chat__body) p.live-pop__status--refused {- background: rgba(var(--tint-rgb), 0.06);-}-.live-pop__actions {- display: flex;- gap: 6px;- margin: 8px 0;-}-:is(.live-pop, .live-chat__body) .confirm__btn.live-pop__btn {- padding: 3px 10px;- border-radius: 6px;- font-size: 12px;-}-:is(.live-pop, .live-chat__body) p.live-pop__error {- margin: 4px 0;- color: var(--danger);-}-.live-pop__viewers ul,-.live-pop__thread {- margin: 4px 0;- padding: 0;- list-style: none;-}-.live-pop__viewers li {- display: flex;- align-items: center;- gap: 6px;- padding: 2px 0;-}-:is(.live-pop, .live-chat__body) .live-pop__kick {- margin-left: auto;-}-:is(.live-pop, .live-chat__body) p.live-pop__note {- margin-top: 4px;- font-size: 11px;-}-.live-pop__chat {- margin-top: 8px;- padding-top: 8px;- border-top: 1px solid var(--border);-}-.live-pop__thread {- max-height: 220px;- overflow-y: auto;-}-.live-pop__msg {- display: flex;- flex-wrap: wrap;- align-items: baseline;- gap: 4px;- margin: 4px 0;-}-.live-pop__text {- flex-basis: 100%;- white-space: pre-wrap;- overflow-wrap: anywhere;-}-.live-pop__copy {- padding: 0;- border: 0;- background: none;- color: var(--accent);- font: inherit;- font-size: 11px;- cursor: pointer;-}-.live-pop__copy:disabled {- color: var(--muted);- cursor: default;-}-.live-pop__reply {- display: flex;- gap: 6px;- margin-top: 6px;-}-.live-pop .confirm__input.live-pop__input {- flex: 1 1 auto;- min-width: 0;- margin: 0;- 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-size: 12px;-}-/* A Control link's password, wherever it is typed or shown (create dialog, popover, drawer):- monospace, so a 0 and an o, or a 1 and an l, never read alike. One rule for every field. */-.live-dialog__password .confirm__input,-.live-pop__password .confirm__input {- font-family: ui-monospace, SFMono-Regular, Menlo, monospace;-}-:is(.live-pop, .live-chat__body) 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 Live chat drawer (LiveChatDrawer): the Explorer drawer's shell and pin, with the popover's- owner controls inside it (the `:is(.live-pop, .live-chat__body)` rules above are shared). Raised- over the kanban card modal (scrim 55) while one is open — the card's LIVE chip opens it — whatever- the pin; pinned beside a pinned Explorer, docked one Explorer width (320px) and a gap to its left.- The `.drawer` shell is already a Liquid Glass text surface with its blur, and nothing inside paints- a surface token. Tokens only: the viewer-name hues come from the web page's table- (lib/liveChatLook) as `--live-name`, darkened toward the ink on the light theme, where the- page's near-black-tuned yellows and cyans would not read. */-.drawer-overlay.drawer-overlay--raised {- z-index: 57;-}-.drawer-overlay--beside .drawer--pinned {- right: calc(var(--float-gap) + 320px + 8px);-}-.live-chat:focus {- outline: none;-}-.live-chat__body {- flex: 1 1 auto;- min-height: 0;- display: flex;- flex-direction: column;- padding: 8px 14px 12px;- font-size: 12.5px;- line-height: 1.4;-}-.live-chat__link {- flex: none;- padding-bottom: 8px;- border-bottom: 1px solid var(--border);-}-.live-chat__body .confirm__input.live-chat__select {- margin: 0 0 8px;- padding: 5px 8px;- font-size: 12.5px;-}-.live-chat__linkhead {- display: flex;- align-items: baseline;- justify-content: space-between;- gap: 8px;-}-.live-chat__goto {- flex: none;- padding: 0;- border: 0;- background: none;- color: var(--accent-text);- font: inherit;- font-size: 12px;- white-space: nowrap;- cursor: pointer;-}-.live-chat__goto:hover {- text-decoration: underline;-}-.live-chat__people {- flex: none;- max-height: 40%;- overflow-y: auto;- padding: 8px 0;- border-bottom: 1px solid var(--border);-}-/* A Viewer link has no chat: People takes the drawer. */-.live-chat__people.live-chat__people--only {- flex: 1 1 auto;- max-height: none;- border-bottom: 0;-}-.live-chat__heading {- margin: 0 0 6px;- font-size: 11px;- font-weight: 600;- letter-spacing: 0.4px;- text-transform: uppercase;- color: var(--muted);-}-.live-chat__viewers {- margin: 4px 0;- padding: 0;- list-style: none;-}-.live-chat__viewers li {- display: flex;- align-items: center;- gap: 6px;- padding: 2px 0;-}-.live-chat__chat {- flex: 1 1 auto;- min-height: 0;- display: flex;- flex-direction: column;- padding-top: 8px;-}-/* The list scrolls; the "N new messages" pill floats over its foot. */-.live-chat__listwrap {- position: relative;- flex: 1 1 auto;- min-height: 0;- display: flex;- flex-direction: column;-}-.live-chat__body p.live-chat__empty {- margin: 0 0 6px;-}-.live-chat__list {- flex: 1 1 auto;- min-height: 0;- margin: 0;- padding: 0;- overflow-y: auto;- list-style: none;-}-/* One dense line per message, like the viewer page: time, badge, name, text. */-.live-chat__msg {- padding: 2px 0;- overflow-wrap: anywhere;-}-.live-chat__time {- margin-right: 6px;- color: var(--muted);- font-size: 11px;- font-variant-numeric: tabular-nums;-}-/* The owner's own line, marked by the HOST's word: ink on a success wash, the status-chip recipe. */-.live-chat__badge {- display: inline-block;- margin-right: 5px;- padding: 0 5px;- border: 1px solid color-mix(in srgb, var(--state-success) 45%, transparent);- border-radius: 4px;- background: color-mix(in srgb, var(--state-success) 16%, transparent);- color: var(--text);- font-size: 10px;- font-weight: 700;- line-height: 15px;- vertical-align: 1px;-}-.live-chat__name {- color: var(--live-name, var(--text));- font-weight: 700;-}-.live-chat__msg--sharer .live-chat__name {- --live-name: var(--success);-}-:root[data-theme='light'] .live-chat__name {- color: color-mix(in srgb, var(--live-name, var(--text)) 55%, var(--text-strong));-}-.live-chat__colon {- color: var(--muted);-}-.live-chat__text {- color: var(--text);- white-space: pre-wrap;-}-.live-chat__body .confirm__btn.live-chat__more {- position: absolute;- bottom: 8px;- left: 50%;- transform: translateX(-50%);- padding: 3px 12px;- border-radius: 999px;- font-size: 12px;- white-space: nowrap;-}-.live-chat__reply {- flex: none;- display: flex;- gap: 6px;- margin-top: 8px;-}-.live-chat__body .confirm__input.live-chat__input {- flex: 1 1 auto;- min-width: 0;- margin: 0;- padding: 5px 8px;- font-size: 12.5px;-}-/* The create dialog (LiveLinkDialog), Figma's share-dialog shape on the `.confirm` shell: a head with- the node's title and ✕, then one grouped list of rows that each read as a sentence ("Anyone with- the link · can watch ▾"), the warnings, and the actions. */-.confirm.live-dialog {- width: 440px;- padding: 14px 16px 16px;-}-.live-dialog__head {- display: flex;- align-items: center;- gap: 8px;- margin: 0 0 12px;-}-.live-dialog__title {- flex: 1 1 auto;- min-width: 0;- margin: 0;- overflow: hidden;- color: var(--text);- font-size: 14px;- font-weight: 600;- text-overflow: ellipsis;- white-space: nowrap;-}-/* The head's ✕ and the password row's "new password": quiet icon buttons. */-.live-dialog__close,-.live-dialog__icon-btn {- flex: none;- display: grid;- place-items: center;- width: 26px;- height: 26px;- padding: 0;- border: 0;- border-radius: 6px;- background: transparent;- color: var(--muted);- cursor: pointer;-}-.live-dialog__close svg,-.live-dialog__icon-btn svg {- width: 14px;- height: 14px;-}-.live-dialog__close:hover:not(:disabled),-.live-dialog__icon-btn:hover:not(:disabled) {- background: rgba(var(--tint-rgb), 0.08);- color: var(--text);-}-.live-dialog__close:disabled,-.live-dialog__icon-btn:disabled {- opacity: 0.45;- cursor: not-allowed;-}-/* The grouped list: a hairline box, hairlines between rows. */-.live-dialog__rows {- display: flex;- flex-direction: column;- margin: 0 0 12px;- border: 1px solid var(--border);- border-radius: 10px;-}-.live-dialog__rows > * + .live-dialog__row {- border-top: 1px solid var(--border);-}-.live-dialog__row {- display: flex;- align-items: center;- gap: 10px;- min-height: 40px;- padding: 4px 6px 4px 12px;- color: var(--text);- font-size: 13px;-}-.live-dialog__icon {- flex: none;- display: grid;- place-items: center;- width: 16px;- color: var(--muted);-}-.live-dialog__icon svg {- width: 15px;- height: 15px;-}-.live-dialog__row-label {- flex: 1 1 auto;- min-width: 0;- overflow: hidden;- text-overflow: ellipsis;- white-space: nowrap;-}-.live-dialog__row .confirm__input {- min-width: 0;- margin: 0;- padding: 5px 8px;- font-size: 12.5px;-}-/* The password takes the row's width; its label only what it needs. */-.live-dialog__row.live-dialog__password .live-dialog__row-label {- flex: none;-}-.live-dialog__row.live-dialog__password .confirm__input {- flex: 1 1 auto;-}-/* The name: an inline value like the menus' (right-aligned, no box) that shows its field on hover- and focus, so the row reads "Viewers see you as Enes" and still says it can be edited. */-.live-dialog__label .confirm__input {- flex: 0 0 160px;- padding: 5px 10px;- border-color: transparent;- background: transparent;- text-align: right;-}-.live-dialog__label .confirm__input:hover:not(:disabled) {- border-color: var(--border);-}-.live-dialog__label .confirm__input:focus {- border-color: var(--accent);- background: rgba(var(--tint-rgb), 0.06);- text-align: left;-}-/* The password's validation line, inside the list under its row, aligned with the row's text. */-.live-dialog__invalid {- margin: 0;- padding: 0 12px 8px 38px;- color: var(--danger);- font-size: 11.5px;-}-/* The typing warning (Control only): what typing can do is the one sentence on this dialog that must- stop the eye, so it keeps a wash. Ink text on it, so it reads the same under Liquid Glass. */-.live-dialog__warning {- margin: 0 0 8px;- padding: 8px 10px;- border-radius: 8px;- background: color-mix(in srgb, var(--state-error) 12%, transparent);- color: var(--text);- font-size: 12px;- line-height: 1.45;- /* It can name a long user@host, which has no break points. */- overflow-wrap: anywhere;-}-/* What watching exposes: always shown, for every role, as one quiet sentence. */-.live-dialog__exposure {- margin: 0 0 12px;- color: var(--muted);- font-size: 12px;- line-height: 1.45;-}-.live-dialog__error {- margin: 0 0 10px;- color: var(--danger);- font-size: 12px;- overflow-wrap: anywhere;-}-.live-dialog__note {- margin: 0 0 12px;- color: var(--muted);- font-size: 12px;- line-height: 1.45;-}-/* The done step: "● Anyone with this link can watch until 15:42", the dot in the LIVE chip's tone. */-.live-dialog__status {- display: flex;- align-items: baseline;- gap: 8px;- margin: 0 0 12px;- color: var(--text);- font-size: 12.5px;-}-.live-dialog__dot {- flex: none;- width: 7px;- height: 7px;- border-radius: 50%;- background: var(--state-error);- transform: translateY(-1px);-}-.live-dialog__url {- display: flex;- gap: 6px;- align-items: center;- margin: 0 0 8px;-}-.live-dialog__url .confirm__input {- flex: 1 1 auto;- min-width: 0;- margin: 0;-}-/* Copy link and Copy password line up, and "Copied!" does not shift the field. */-.live-dialog__copy {- flex: none;- min-width: 124px;-}-.live-dialog__actions {- justify-content: space-between;-}-/* Stop sharing: a red text button on the left, away from Done. */-.confirm__btn.live-dialog__stop {- /* The text lines up with the content edge above it; the hover wash still has room. */- margin-left: -10px;- padding-inline: 10px;- border-color: transparent;- background: transparent;- color: var(--danger);-}-.confirm__btn.live-dialog__stop:hover:not(:disabled) {- background: color-mix(in srgb, var(--state-error) 12%, transparent);-}-/* MenuSelect (components/MenuSelect.tsx): a row's value with a chevron, and its small menu. The menuis absolutely positioned INSIDE the row and opaque: inside a dialog that is a backdrop root underLiquid Glass, a translucent or blurred menu would show the dialog's own content through it. */@@ -13657,7 +12990,7 @@ button.pull-checks__name {padding-left: 18px;overflow-wrap: anywhere;}-/* The security sentence: always visible, the status-chip recipe like the live link warning. */+/* The security sentence: always visible, in the status-chip recipe. */.share-team__warning {padding: 8px 10px;border-radius: 6px;@@ -18087,10 +17420,8 @@ body.focus-mode .dock:hover {(#323232 with no shadow, #242424, #1e1e1e, #1a1a1a, a near-black 0.98 slab) beside the glassmenus. Under glass each is the menu surface's own colour made solid (`--panel`, the colour theglass fill is `--panel` at an alpha of), with the glass hairline and one shadow. Every modal- dialog is glass (the text list above); these five are the only opaque floating surfaces — the- fifth, the live-link popover (LiveLinkPopover), opens over the card modal as well as a glass node- header, and stays solid for the same reason. */-:root[data-nt-glass='on'] :is(.ctx-popover, .color-popover, .label-picker, .kanban-meta__picker, .live-pop) {+ dialog is glass (the text list above); these four are the only opaque floating surfaces. */+:root[data-nt-glass='on'] :is(.ctx-popover, .color-popover, .label-picker, .kanban-meta__picker) {background: var(--panel);border: 1px solid var(--glass-edge);box-shadow: 0 12px 36px rgba(0, 0, 0, calc(0.45 * var(--shadow-k)));@@ -18386,7 +17717,7 @@ body.focus-mode .dock:hover {floating surfaces (the popovers inside glass nodes, below): the glass placeholder is sized for thetranslucent fill, and on a solid popover it read brighter than the popover's own body text, as ifthe field were already filled (visual QA round 4, N4-M2). */-:root[data-nt-glass='on'] :not(.sticky-node__body, :is(.ctx-popover, .color-popover, .label-picker, .kanban-meta__picker, .live-pop) *)::placeholder {+:root[data-nt-glass='on'] :not(.sticky-node__body, :is(.ctx-popover, .color-popover, .label-picker, .kanban-meta__picker) *)::placeholder {color: var(--glass-placeholder);}/* An empty field must look empty (visual QA round 3, NM1): the placeholder's 4.5:1 floor sits atdiff --git a/src/renderer/styles.liquid-glass.test.ts b/src/renderer/styles.liquid-glass.test.tsindex 264b933fa..12bd93c4c 100644--- a/src/renderer/styles.liquid-glass.test.ts+++ b/src/renderer/styles.liquid-glass.test.ts@@ -139,7 +139,7 @@ describe('Liquid Glass stylesheet', () => {expect(rules.find((r) => r.selector === `${ctxHost}::before`)?.body).toMatch(/var\(--glass-chrome-bg\)[\s\S]*var\(--glass-text-blur\)/)// Popovers inside a glass node or the card modal (their backdrop root) cannot blur: glass is// opt-in, so nothing hands them a translucent glass fill and they keep their opaque colour.- for (const nested of ['.dock-menu', '.dock-menu__sub', '.ctx-popover', '.color-popover', '.label-picker', '.kanban-meta__picker', '.live-pop']) {+ for (const nested of ['.dock-menu', '.dock-menu__sub', '.ctx-popover', '.color-popover', '.label-picker', '.kanban-meta__picker']) {const fills = gated(nested).filter((r) => !r.selector.includes('::before') && /background:[^;]*var\(--glass-(chrome|control)-bg\)/.test(r.body))@@ -148,8 +148,7 @@ describe('Liquid Glass stylesheet', () => {})it('the opaque floating surfaces share one look and keep their own placeholder (N4-M1/M2)', () => {- // The live-link popover is one of them: opaque over a glass node header or the card modal.- const OPAQUE = ['.ctx-popover', '.color-popover', '.label-picker', '.kanban-meta__picker', '.live-pop']+ const OPAQUE = ['.ctx-popover', '.color-popover', '.label-picker', '.kanban-meta__picker']const look = rules.find((r) => r.selector === `${GATE} :is(${OPAQUE.join(', ')})`)expect(look?.body).toMatch(/background:\s*var\(--panel\)[\s\S]*border:\s*1px solid var\(--glass-edge\)/)const placeholder = rules.find((r) => r.selector.startsWith(`${GATE} :not(`) && r.selector.endsWith('::placeholder'))diff --git a/src/renderer/styles.live-chat.test.ts b/src/renderer/styles.live-chat.test.tsdeleted file mode 100644index d676e7e43..000000000--- a/src/renderer/styles.live-chat.test.ts+++ /dev/null@@ -1,58 +0,0 @@-import { describe, expect, it } from 'vitest'-import { readFileSync } from 'node:fs'-import { join } from 'node:path'--/**- * The Live chat drawer's stacking and its colours (components/LiveChatDrawer.tsx). jsdom has no- * layout, so where the drawer SITS is pinned here: a z-index typo puts it under the board or under- * the card modal it was opened from, and nothing rendered in CI would notice.- */-const CSS = readFileSync(join(__dirname, 'styles.css'), 'utf8').replace(/\r\n/g, '\n')-const NO_COMMENTS = CSS.replace(/\/\*[\s\S]*?\*\//g, '')--/** Every rule body whose selector list contains `selector` exactly, in source order. */-function bodies(selector: string): { at: number; body: string }[] {- const out: { at: number; body: string }[] = []- const re = /([^{}]+)\{([^{}]*)\}/g- let m: RegExpExecArray | null- while ((m = re.exec(NO_COMMENTS))) {- const sels = m[1].split(',').map((s) => s.replace(/\s+/g, ' ').trim())- if (sels.includes(selector)) out.push({ at: m.index, body: m[2] })- }- return out-}-const zOf = (body: string): number | null => {- const m = /z-index:\s*(\d+)/.exec(body)- return m ? Number(m[1]) : null-}--describe('Live chat drawer CSS', () => {- it('raised (a card modal is open, z 55) sits at 57, and wins over the pinned 26 wherever it is written', () => {- const raised = bodies('.drawer-overlay.drawer-overlay--raised')- expect(raised).toHaveLength(1)- expect(zOf(raised[0].body)).toBe(57)- // Higher specificity than `.drawer-overlay--pinned`, so source order cannot undo it.- const pinned = bodies('.drawer-overlay--pinned').find((r) => zOf(r.body) !== null)!- expect(zOf(pinned.body)).toBe(26)- })-- it('beside the pinned Explorer: one Explorer width plus a gap further from the right edge', () => {- const beside = bodies('.drawer-overlay--beside .drawer--pinned')- expect(beside).toHaveLength(1)- expect(beside[0].body).toContain('right: calc(var(--float-gap) + 320px + 8px)')- })-- it('no colour literal in the drawer\'s own rules — tokens only (the name hues come from the copied web table)', () => {- const own = [...NO_COMMENTS.matchAll(/([^{}]*\.live-chat[^{}]*)\{([^{}]*)\}/g)]- expect(own.length).toBeGreaterThan(5)- for (const [, head, body] of own) {- expect(body, head.trim()).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgba?\(\s*\d/)- }- })-- it('viewer names keep their hue but are darkened toward the ink on the light theme', () => {- const light = bodies(":root[data-theme='light'] .live-chat__name")- expect(light).toHaveLength(1)- expect(light[0].body).toContain('color-mix(in srgb, var(--live-name, var(--text)) 55%, var(--text-strong))')- })-})