Skip to content

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.

feat(renderer): share a live link from every surface, gated by availability before the Pro gate

reviewde1253552ae8
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index c2b55f95c..1ca67b242 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -110,6 +110,7 @@ import { CommandPalette, type Command } from '../components/CommandPalette'
import { Tooltip } from '../components/Tooltip'
import {
IconBranch,
+ IconBroadcast,
IconCanvasView,
IconClose,
IconCollapse,
@@ -237,6 +238,21 @@ import { approvePhoneWithFeedback } from '../lib/phone-approval'
import { peerApprovalView } from '@shared/remote/approval'
import { promptDialog } from '../components/promptDialog'
import { UpgradeDialog } from '../components/UpgradeDialog'
+import { LiveLinkDialog } from '../components/LiveLinkDialog'
+import { requireProOr } from '../state/upgradeGate'
+import { startWatchLinkSync, useWatchLinks } from '../state/watchLinks'
+import { noticeText } from '../lib/liveLink'
+import {
+ liveLinkCommands,
+ liveLinkMenuRow,
+ liveLinkNodeFor,
+ liveLinkPrepare,
+ openLiveLink,
+ stopAllConfirm,
+ stopLiveLinks,
+ type LiveLinkAvailabilityFacts,
+ type LiveLinkTarget
+} from '../lib/liveLinkEntry'
import { RemotePicker } from '../components/RemotePicker'
import { WorktreeDialog } from '../components/WorktreeDialog'
import { SpawnTeamDialog } from '../components/SpawnTeamDialog'
@@ -3471,6 +3487,126 @@ export function Canvas() {
// eslint-disable-next-line react-hooks/exhaustive-deps -- refs are read at call time
}, [api, persist])
+ // ── Live links (Task 17) ────────────────────────────────────────────────────────────────────
+ // A read-only, expiring browser view of ONE terminal. The store (state/watchLinks) mirrors this
+ // machine's core registry — `window.nodeTerminal`, never a relay session's api: links are made on
+ // the machine that runs the terminal. Started ONCE per Canvas mount; without it the store stays
+ // empty and no LIVE chip ever appears. `not-persistent` stays on screen (it is shown after every
+ // create while links cannot be saved); the rest fade like any info strip.
+ useEffect(
+ () =>
+ startWatchLinkSync(window.nodeTerminal, (n) => {
+ const text = noticeText(n)
+ if (text) setNotice({ kind: 'info', text, sticky: n.kind === 'not-persistent' })
+ }),
+ []
+ )
+ 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()
+ const pid = projectId ?? store.activeProjectId
+ if (!pid) return []
+ return liveLinkMenuRow({
+ node: liveLinkNodeFor({
+ nodeId,
+ projectId: pid,
+ activeProjectId: store.activeProjectId,
+ live: nodesRef.current,
+ stored: store.getProject(pid)?.nodes
+ }),
+ projectId: pid,
+ hidden: useSettings.getState().settings.hiddenNodeMenuItems,
+ facts: liveLinkFacts(pid),
+ 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]
+ )
+
+ /** 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. */
+ const confirmStopAllLiveLinks = useCallback(
+ () =>
+ setConfirm(
+ stopAllConfirm({
+ close: () => setConfirm(null),
+ stop: () =>
+ void stopLiveLinks(
+ () => window.nodeTerminal.watchLink.revokeAll(),
+ (text) => setNotice({ kind: 'error', text })
+ )
+ })
+ ),
+ [setConfirm]
+ )
+
/** Re-runs the active-project load effect by bumping the store's `reloadNonce`.
*
* This used to flip the active id to '' and back on a microtask. React coalesces both writes
@@ -9711,7 +9847,10 @@ export function Canvas() {
hint: 'Rebuilds the view and re-attaches to the same session. Nothing running is interrupted.',
onClick: () => reloadTerminals(ids)
}
- ])
+ ]),
+ // Share live link… — single terminal only; disabled with its reason where it cannot
+ // work, hideable as `live-link` (the shared builder applies both).
+ ...(ids.length === 1 ? liveLinkMenuItems(ids[0]) : [])
] as MenuItem[])
: []),
// Conversation actions — Branch, Transfer ▸ (targets, then models), Restart ▸, Pause — sit
@@ -10012,7 +10151,8 @@ export function Canvas() {
gatewayModels,
gatewayStatus,
gatewayError,
- session.source
+ session.source,
+ liveLinkMenuItems
])
/** "New <agent>" creation entries shared by the pane, sidebar and group context menus.
@@ -15551,6 +15691,8 @@ 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) }
]
@@ -15562,7 +15704,8 @@ export function Canvas() {
renameSession,
closeSession,
writeDisk,
- selectionItems
+ selectionItems,
+ liveLinkMenuItems
]
)
@@ -17061,6 +17204,17 @@ 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,
+ icon: <IconBroadcast />,
+ manage: () => {
+ setSettingsSection('live-links')
+ setSettingsNonce((n) => n + 1)
+ setSettingsOpen(true)
+ },
+ 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()
@@ -17172,7 +17326,8 @@ export function Canvas() {
toggleFocusMode,
hostedBookmarks,
copyHostedInviteCode,
- forgetHostedTeam
+ forgetHostedTeam,
+ confirmStopAllLiveLinks
])
// Build the palette's command list only when its inputs change — the inline `buildCommands()`
@@ -17413,7 +17568,11 @@ export function Canvas() {
})()}
</div>
{globalKanbanOpen ? (
- <GlobalKanbanView live={globalKanbanLive} onModalNodeChange={setKanbanModalNode} />
+ <GlobalKanbanView
+ live={globalKanbanLive}
+ onModalNodeChange={setKanbanModalNode}
+ liveLinkMenuItems={liveLinkMenuItems}
+ />
) : perProjectKanbanOpen && (
<KanbanView
board={projectKanban ?? seedBoard}
@@ -17428,6 +17587,7 @@ export function Canvas() {
onBrowserNav={browserNavFromKanban}
onSetIcon={setNodeIcon}
accountMenuItems={accountSwitchRows}
+ liveLinkMenuItems={liveLinkMenuItems}
onAutoMoveFromPulls={autoMoveCardFromPulls}
issueAgentMenu={issueAgentMenu}
issueWorktreeMenu={issueWorktreeMenu}
@@ -18140,6 +18300,24 @@ export function Canvas() {
)}
<UpgradeDialog />
+ {liveLinkDialog && (
+ <LiveLinkDialog
+ key={`${liveLinkDialog.projectId}:${liveLinkDialog.nodeId}`}
+ nodeId={liveLinkDialog.nodeId}
+ title={liveLinkDialog.title}
+ surface={
+ isBrowserRuntime()
+ ? 'server'
+ : sessionForProject(liveLinkDialog.projectId).source === 'relay'
+ ? 'relay'
+ : 'desktop'
+ }
+ 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 && (
<RemotePicker
diff --git a/src/renderer/canvas/live-link-wiring.test.ts b/src/renderer/canvas/live-link-wiring.test.ts
new file mode 100644
index 000000000..ff2069d6e
--- /dev/null
+++ b/src/renderer/canvas/live-link-wiring.test.ts
@@ -0,0 +1,88 @@
+// 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('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('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('one row builder, declared before selectionItems and listed in its deps (H15)', () => {
+ const builder = src.indexOf('const liveLinkMenuItems = useCallback(')
+ const selection = src.indexOf('const selectionItems = useCallback(')
+ expect(builder).toBeGreaterThan(-1)
+ expect(builder).toBeLessThan(selection)
+ const sel = src.slice(selection, src.indexOf('/** "New <agent>" creation entries', selection))
+ // After "Refresh terminal", single selection only.
+ expect(sel.indexOf("...(ids.length === 1 ? liveLinkMenuItems(ids[0]) : [])")).toBeGreaterThan(sel.indexOf("label: 'Refresh terminal'"))
+ expect(sel).toMatch(/session\.source,\s*liveLinkMenuItems\s*\]\)/)
+ })
+
+ 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),')
+ expect(src).toContain('liveLinkMenuItems={liveLinkMenuItems}\n onAutoMoveFromPulls')
+ expect(src).toMatch(/<GlobalKanbanView[\s\S]{0,200}liveLinkMenuItems=\{liveLinkMenuItems\}/)
+ })
+
+ 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 \}\)/)
+ })
+})
diff --git a/src/renderer/components/LiveLinkChip.surfaces.test.tsx b/src/renderer/components/LiveLinkChip.surfaces.test.tsx
index e6798c49b..92d503ade 100644
--- a/src/renderer/components/LiveLinkChip.surfaces.test.tsx
+++ b/src/renderer/components/LiveLinkChip.surfaces.test.tsx
@@ -87,10 +87,11 @@ const setLinks = (links: WatchLinkView[]): void => act(() => useWatchLinks.getSt
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()) {
+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()}
@@ -112,6 +113,16 @@ describe('LIVE chip — kanban card', () => {
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))
@@ -142,7 +153,7 @@ 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
+ <CardModal projectId="p1"
session={session}
columnTitle="Doing"
board={board}
@@ -177,6 +188,7 @@ describe('LIVE chip — sessions sidebar row', () => {
render(
<SessionRow
row={row}
+ liveLinkSource="local"
onClick={onClick}
onClose={onClose}
onRename={vi.fn()}
@@ -196,4 +208,22 @@ describe('LIVE chip — sessions sidebar row', () => {
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.tsx
index b80be2dff..429417348 100644
--- a/src/renderer/components/LiveLinkChip.test.tsx
+++ b/src/renderer/components/LiveLinkChip.test.tsx
@@ -4,7 +4,7 @@ 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 } from './LiveLinkChip'
+import { LiveLinkChip, projectSessionSource, showsLiveLinks } from './LiveLinkChip'
import { useWatchLinks } from '../state/watchLinks'
import { useBoardLog } from '../state/boardLog'
import { useProjects } from '../state/projects'
@@ -93,16 +93,41 @@ const flush = (): Promise<void> => act(async () => {})
describe('LiveLinkChip', () => {
it('renders nothing for a node with no link', () => {
- expect(renderToStaticMarkup(<LiveLinkChip nodeId="n1" />)).toBe('')
- render(<LiveLinkChip nodeId="n1" />)
+ 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" className="extra" />)
+ render(<LiveLinkChip nodeId="n1" source="local" className="extra" />)
setLinks([link({ viewers: [{ viewerId: 'v', name: null, joinedAt: 0 }] })])
const c = chip()!
expect(c.tagName).toBe('BUTTON')
@@ -114,7 +139,7 @@ describe('LiveLinkChip', () => {
})
it('follows the store: offline, refused, the unread dot, and gone again', () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link()])
expect(host.querySelector('.live-chip__dot')).not.toBeNull()
setLinks([link({ status: 'reconnecting' })])
@@ -136,7 +161,7 @@ describe('LiveLinkChip', () => {
describe('LiveLinkPopover', () => {
it('opens on click with role, time, the controls and the kick note', () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0 }, { viewerId: 'v2', name: 'Cy', joinedAt: 0 }] })])
click(chip()!)
const p = pop()!
@@ -155,7 +180,7 @@ describe('LiveLinkPopover', () => {
})
it('takes the keyboard focus while open and gives it back to the chip', () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link()])
act(() => chip()!.focus())
click(chip()!)
@@ -165,14 +190,14 @@ describe('LiveLinkPopover', () => {
})
it('explains a link that is not live (H9)', () => {
- render(<LiveLinkChip nodeId="n1" />)
+ 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")
})
it('Stop sharing revokes; a stop that did not reach nodeterm says so (H23)', async () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link()])
click(chip()!)
api.revoke.mockImplementationOnce(async () => {
@@ -191,7 +216,7 @@ describe('LiveLinkPopover', () => {
})
it('Escape closes it, and only when it is the top dialog', () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link()])
click(chip()!)
// A dialog raised above it owns the key.
@@ -207,7 +232,7 @@ describe('LiveLinkPopover', () => {
const globalKeys = vi.fn()
window.addEventListener('keydown', globalKeys)
try {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link()])
click(chip()!)
act(() => void document.body.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })))
@@ -222,7 +247,7 @@ describe('LiveLinkPopover', () => {
const globalKeys = vi.fn()
window.addEventListener('keydown', globalKeys)
try {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link()])
act(() => chip()!.focus())
click(chip()!)
@@ -242,7 +267,7 @@ describe('LiveLinkPopover', () => {
const onDrop = vi.fn()
render(
<div onDragOver={onDragOver} onDrop={onDrop}>
- <LiveLinkChip nodeId="n1" />
+ <LiveLinkChip nodeId="n1" source="local" />
</div>
)
setLinks([link()])
@@ -259,7 +284,7 @@ describe('LiveLinkPopover', () => {
try {
render(
<div onKeyDown={onKeyDown}>
- <LiveLinkChip nodeId="n1" />
+ <LiveLinkChip nodeId="n1" source="local" />
</div>
)
setLinks([link({ role: 'commenter' })])
@@ -276,7 +301,7 @@ describe('LiveLinkPopover', () => {
})
it('a failed Kick says so: not reached, or nobody to kick (M3)', async () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0 }] })])
click(chip()!)
api.kick.mockImplementationOnce(async () => {
@@ -299,7 +324,7 @@ describe('LiveLinkPopover', () => {
const onMouseDown = vi.fn()
render(
<div onClick={onClick} onMouseDown={onMouseDown}>
- <LiveLinkChip nodeId="n1" />
+ <LiveLinkChip nodeId="n1" source="local" />
</div>
)
setLinks([link()])
@@ -317,7 +342,7 @@ describe('LiveLinkPopover', () => {
describe('LiveLinkPopover — Commenter chat', () => {
it('renders every viewer string as text, never as markup', () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ role: 'commenter', label: '<b>Ada</b>', viewers: [{ viewerId: 'v', name: '<i>Eve</i>', joinedAt: 0 }] })])
act(() => useWatchLinks.getState().addChat('L', msg('1', { name: '<u>Eve</u>', text: '<img src=x onerror=alert(1)>' })))
click(chip()!)
@@ -331,7 +356,7 @@ describe('LiveLinkPopover — Commenter chat', () => {
})
it('strips bidi controls from what viewers wrote', () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ role: 'commenter' })])
act(() => useWatchLinks.getState().addChat('L', msg('1', { name: 'Ev‮e', text: 'a⁧b' })))
click(chip()!)
@@ -340,7 +365,7 @@ describe('LiveLinkPopover — Commenter chat', () => {
})
it('opening marks the link read, and so does every message that lands while it is open (H21)', async () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ role: 'commenter' })])
act(() => useWatchLinks.getState().addChat('L', msg('1')))
expect(useWatchLinks.getState().unread.L).toBe(1)
@@ -354,7 +379,7 @@ describe('LiveLinkPopover — Commenter chat', () => {
})
it('stays read at the 200-message cap, where the thread length stops changing', async () => {
- render(<LiveLinkChip nodeId="n1" />)
+ 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)))
@@ -367,7 +392,7 @@ describe('LiveLinkPopover — Commenter chat', () => {
})
it('sends a reply and clears the box; the echo comes back through the push', async () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ role: 'commenter' })])
click(chip()!)
const input = pop()!.querySelector<HTMLInputElement>('.live-pop__input')!
@@ -386,7 +411,7 @@ describe('LiveLinkPopover — Commenter chat', () => {
})
it('a reply core did not take keeps the draft and says so (M3)', async () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ role: 'commenter' })])
click(chip()!)
const input = pop()!.querySelector<HTMLInputElement>('.live-pop__input')!
@@ -417,7 +442,7 @@ describe('LiveLinkPopover — Commenter chat', () => {
})
it('while the thread is open a new message never shows as unread, not even for one render (N2)', async () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ role: 'commenter' })])
click(chip()!)
await flush()
@@ -444,7 +469,7 @@ describe('LiveLinkPopover — Commenter chat', () => {
{ id: 'p-local', nodes: [{ id: 'n1' }] }
]
} as never)
- render(<LiveLinkChip nodeId="n1" />)
+ 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' })))
@@ -464,7 +489,7 @@ describe('LiveLinkPopover — Commenter chat', () => {
})
it('offers no copy when no project holds the node', () => {
- render(<LiveLinkChip nodeId="n1" />)
+ render(<LiveLinkChip nodeId="n1" source="local" />)
setLinks([link({ role: 'commenter' })])
act(() => useWatchLinks.getState().addChat('L', msg('1')))
click(chip()!)
diff --git a/src/renderer/components/LiveLinkChip.tsx b/src/renderer/components/LiveLinkChip.tsx
index 537471593..2ecfcd43e 100644
--- a/src/renderer/components/LiveLinkChip.tsx
+++ b/src/renderer/components/LiveLinkChip.tsx
@@ -1,8 +1,34 @@
import { memo, useCallback, useEffect, useState } from 'react'
import { chipView } from '../lib/liveLink'
+import { sessionForProject, 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'
+}
+
+/**
+ * The source of the session a project's surfaces are viewed through — for the surfaces that know a
+ * project id but sit outside that project's `SessionProvider` (the boards, the sessions sidebar).
+ * Null when no session resolves (a registry with no session at all, e.g. a unit test), which
+ * `showsLiveLinks` reads as "do not show".
+ */
+export function projectSessionSource(projectId: string): SessionSource | null {
+ try {
+ return sessionForProject(projectId).source
+ } catch {
+ return null
+ }
+}
+
/**
* "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
@@ -15,12 +41,17 @@ import { LiveLinkPopover, type PopoverAnchor } from './LiveLinkPopover'
*/
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 sig = useWatchLinks((s) => liveChipSig(s, nodeId))
+ 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
diff --git a/src/renderer/components/LiveLinkDialog.test.tsx b/src/renderer/components/LiveLinkDialog.test.tsx
new file mode 100644
index 000000000..4d3fab046
--- /dev/null
+++ b/src/renderer/components/LiveLinkDialog.test.tsx
@@ -0,0 +1,254 @@
+// @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 { CreateWatchLinkRequest, CreateWatchLinkResult } from '@shared/watch-link-types'
+import { LiveLinkDialog, LiveLinkDialogBody } from './LiveLinkDialog'
+import { formatClock, LIVE_LINK_WARNING, SAVE_FIRST_MESSAGE, STOP_FAILED_MESSAGE } from '../lib/liveLink'
+import { resetDialogStack } from './dialog-stack'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+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', busy: false, error: null } as const
+
+describe('LiveLinkDialogBody', () => {
+ it('shows the role and expiry choices with the defaults, and the warning always', () => {
+ const html = body(FORM)
+ expect(html).toContain('Share a live link to build')
+ expect(html).toContain('Can watch')
+ expect(html).toContain('Can watch and chat')
+ for (const t of ['15 min', '1 hour', '8 hours', '24 hours']) expect(html).toContain(t)
+ expect(html).toContain(LIVE_LINK_WARNING.replace(/'/g, '&#x27;'))
+ 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 html = body({ phase: 'done', url: 'https://nodeterm.dev/s/x#1.y', linkId: 'x', expiresAt })
+ expect(html).toContain('https://nodeterm.dev/s/x#1.y')
+ expect(html).toContain('Copy')
+ expect(html).toContain('Stop sharing')
+ expect(html).toContain(`Anyone with this link can watch until ${formatClock(expiresAt)}.`)
+ })
+
+ it('the header title loses its bidi controls (H26)', () => {
+ const html = renderToStaticMarkup(
+ <LiveLinkDialogBody title={'bu‮ild'} state={FORM} onChange={noop} onSubmit={noop} onClose={noop} onStop={noop} />
+ )
+ expect(html).toContain('Share a live link to 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: []
+ }
+})
+
+let api: {
+ create: ReturnType<typeof vi.fn<(r: CreateWatchLinkRequest) => Promise<CreateWatchLinkResult>>>
+ revoke: ReturnType<typeof vi.fn<(id: string) => Promise<void>>>
+}
+let host: HTMLDivElement
+let root: Root
+beforeEach(() => {
+ resetDialogStack()
+ api = { create: vi.fn(async () => created()), revoke: vi.fn(async () => {}) }
+ ;(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 }))
+ })
+}
+
+function mount(o: {
+ prepare?: () => Promise<string | null>
+ onUpgrade?: () => void
+ onClose?: () => void
+ surface?: 'desktop' | 'server' | 'relay'
+} = {}): { onClose: ReturnType<typeof vi.fn> } {
+ const onClose = vi.fn(o.onClose ?? (() => {}))
+ act(() =>
+ root.render(
+ <LiveLinkDialog
+ nodeId="n1"
+ title="build"
+ surface={o.surface ?? 'desktop'}
+ 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('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'))
+ expect(window.nodeTerminal.clipboard.writeText).toHaveBeenCalledWith('https://nodeterm.dev/s/abc#1.k')
+ })
+})
diff --git a/src/renderer/components/LiveLinkDialog.tsx b/src/renderer/components/LiveLinkDialog.tsx
new file mode 100644
index 000000000..8efbce373
--- /dev/null
+++ b/src/renderer/components/LiveLinkDialog.tsx
@@ -0,0 +1,265 @@
+// 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.
+//
+// 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).
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { createPortal } from 'react-dom'
+import { useDialogStack } from './dialog-stack'
+import {
+ createErrorMessage,
+ DEFAULT_TTL,
+ formatClock,
+ LIVE_LINK_WARNING,
+ ROLE_LABEL,
+ SAVE_FIRST_MESSAGE,
+ TTL_OPTIONS,
+ type LiveLinkSurface
+} from '../lib/liveLink'
+import { stopLiveLinks } from '../lib/liveLinkEntry'
+import { loadIdentity } from '../state/presence'
+import { LABEL_MAX, stripBidiControls, type WatchLinkRole, type WatchLinkTtl } from '@shared/watch-link-types'
+
+export type DialogState =
+ | {
+ phase: 'form'
+ role: WatchLinkRole
+ ttl: WatchLinkTtl
+ label: 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'
+ url: string
+ linkId: string
+ expiresAt: number
+ copied?: boolean
+ 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
+ onUpgrade?: () => void
+}): React.JSX.Element {
+ const s = p.state
+ // 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') {
+ return (
+ <div className="confirm live-dialog" onClick={(e) => e.stopPropagation()}>
+ <p className="confirm__msg live-dialog__title">Live link to {title}</p>
+ <div className="live-dialog__url">
+ <input
+ className="confirm__input"
+ readOnly
+ aria-label="Live link"
+ value={s.url}
+ onFocus={(e) => e.currentTarget.select()}
+ />
+ <button className="confirm__btn primary" onClick={() => p.onCopy?.(s.url)}>
+ {s.copied ? 'Copied!' : 'Copy'}
+ </button>
+ </div>
+ <p className="live-dialog__note">Anyone with this link can watch until {formatClock(s.expiresAt)}.</p>
+ {s.error && (
+ <p className="live-dialog__error" role="alert">
+ {s.error}
+ </p>
+ )}
+ <div className="confirm__actions">
+ <button className="confirm__btn danger" disabled={!!s.stopping} onClick={() => p.onStop(s.linkId)}>
+ Stop sharing
+ </button>
+ <button className="confirm__btn" onClick={p.onClose}>
+ Done
+ </button>
+ </div>
+ </div>
+ )
+ }
+ return (
+ <div className="confirm live-dialog" onClick={(e) => e.stopPropagation()}>
+ <p className="confirm__msg live-dialog__title">Share a live link to {title}</p>
+ <fieldset className="live-dialog__group" disabled={s.busy}>
+ <legend>Viewers</legend>
+ {(['viewer', 'commenter'] as const).map((r) => (
+ <label key={r}>
+ <input type="radio" name="live-role" checked={s.role === r} onChange={() => p.onChange({ ...s, role: r })} />{' '}
+ {ROLE_LABEL[r]}
+ </label>
+ ))}
+ </fieldset>
+ <fieldset className="live-dialog__group" disabled={s.busy}>
+ <legend>Ends after</legend>
+ {TTL_OPTIONS.map((o) => (
+ <label key={o.value}>
+ <input type="radio" name="live-ttl" checked={s.ttl === o.value} onChange={() => p.onChange({ ...s, ttl: o.value })} />{' '}
+ {o.label}
+ </label>
+ ))}
+ </fieldset>
+ <label className="live-dialog__label">
+ Shown to viewers as
+ <input
+ className="confirm__input"
+ maxLength={LABEL_MAX}
+ value={s.label}
+ disabled={s.busy}
+ onChange={(e) => p.onChange({ ...s, label: e.target.value })}
+ />
+ </label>
+ <p className="live-dialog__warning">{LIVE_LINK_WARNING}</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()} onClick={p.onSubmit}>
+ {s.busy ? 'Creating…' : 'Create live link'}
+ </button>
+ </div>
+ </div>
+ )
+}
+
+export function LiveLinkDialog({
+ nodeId,
+ title,
+ surface,
+ prepare,
+ onUpgrade,
+ onClose
+}: {
+ nodeId: string
+ title: string
+ /** Where it was opened — decides how `unsupported` reads (H1). */
+ surface: LiveLinkSurface
+ /** 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 {
+ const [state, setState] = useState<DialogState>(() => ({
+ phase: 'form',
+ role: 'viewer',
+ ttl: DEFAULT_TTL,
+ label: (loadIdentity()?.name ?? '').slice(0, LABEL_MAX),
+ 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 copiedTimer = useRef<ReturnType<typeof setTimeout>>()
+ useEffect(() => () => clearTimeout(copiedTimer.current), [])
+
+ const busy = state.phase === 'form' && state.busy
+ // Every dismissal goes through here: a create in flight cannot be walked away from (H24).
+ const dismiss = useCallback(() => {
+ const s = stateRef.current
+ if (s.phase === 'form' && s.busy) return
+ onClose()
+ }, [onClose])
+
+ 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)
+ try {
+ const r = await window.nodeTerminal.watchLink.create({
+ nodeId,
+ role: form.role,
+ ttlSeconds: form.ttl,
+ label: form.label.trim(),
+ title
+ })
+ if (r.ok) setState({ phase: 'done', url: r.link.url, linkId: r.link.linkId, expiresAt: r.link.expiresAt })
+ else fail(createErrorMessage(r.error, surface), r.error === 'not-entitled')
+ } 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()
+ }
+
+ const copy = (url: string): void => {
+ window.nodeTerminal.clipboard.writeText(url)
+ setState((s) => (s.phase === 'done' ? { ...s, copied: true } : s))
+ clearTimeout(copiedTimer.current)
+ copiedTimer.current = setTimeout(() => setState((s) => (s.phase === 'done' ? { ...s, copied: false } : s)), 1500)
+ }
+
+ return createPortal(
+ <div className="confirm-overlay" onClick={dismiss}>
+ <LiveLinkDialogBody
+ title={title}
+ state={state}
+ onChange={(next) => {
+ if (!busy) setState(next)
+ }}
+ onSubmit={() => void submit()}
+ onClose={dismiss}
+ onStop={(id) => void stop(id)}
+ onCopy={copy}
+ onUpgrade={onUpgrade}
+ />
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/SessionRow.test.tsx b/src/renderer/components/SessionRow.test.tsx
index 649d3e13e..c661f2c9f 100644
--- a/src/renderer/components/SessionRow.test.tsx
+++ b/src/renderer/components/SessionRow.test.tsx
@@ -23,6 +23,7 @@ describe('SessionRow status age', () => {
const html = renderToStaticMarkup(
<SessionRow
row={row}
+ liveLinkSource="local"
stateAgeLabel="5m ago"
onClick={vi.fn()}
onClose={vi.fn()}
diff --git a/src/renderer/components/SessionRow.tsx b/src/renderer/components/SessionRow.tsx
index 84ddf9f28..7aae76786 100644
--- a/src/renderer/components/SessionRow.tsx
+++ b/src/renderer/components/SessionRow.tsx
@@ -1,6 +1,7 @@
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'
@@ -21,6 +22,9 @@ 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 {
@@ -38,7 +42,8 @@ export function SessionRow({
onContextMenu,
onDragStart,
onDragEnd,
- stateAgeLabel
+ stateAgeLabel,
+ liveLinkSource
}: SessionRowProps): JSX.Element {
const [editing, setEditing] = useState(false)
const [draft, setDraft] = useState(row.title)
@@ -157,7 +162,7 @@ export function SessionRow({
</span>
)}
<AccountChip chip={accountChip} className="ss-account" />
- <LiveLinkChip nodeId={row.id} className="ss-live" />
+ <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.tsx
index e15806781..1d5d6e80c 100644
--- a/src/renderer/components/SessionsSidebar.tsx
+++ b/src/renderer/components/SessionsSidebar.tsx
@@ -19,6 +19,7 @@ import {
} from '../lib/sessionList'
import { sidebarEmptyState, sidebarFilterKeyAction } from '../lib/sidebarFilter'
import { SessionRow } from './SessionRow'
+import { projectSessionSource } from './LiveLinkChip'
import { ProjectGlyph } from './ProjectGlyph'
import { ClosedHistorySection } from './ClosedHistorySection'
import { IconBellFilled, IconCircleCheck, IconClose, IconPin } from './icons'
@@ -245,6 +246,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
>
<SessionRow
row={row}
+ liveLinkSource={projectSessionSource(projectId)}
onClick={() => props.onFocusNode(row.id)}
onClose={() => props.onCloseSession(projectId, row.id)}
onRename={(title) => props.onRenameSession(projectId, row.id, title)}
@@ -435,6 +437,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
<div key={row.id} className="ss-rowdrop">
<SessionRow
row={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/icons.tsx b/src/renderer/components/icons.tsx
index d65b5bfed..09b3528f9 100644
--- a/src/renderer/components/icons.tsx
+++ b/src/renderer/components/icons.tsx
@@ -219,6 +219,16 @@ 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" />
diff --git a/src/renderer/components/kanban/CardModal.liveLink.test.tsx b/src/renderer/components/kanban/CardModal.liveLink.test.tsx
new file mode 100644
index 000000000..a9974223c
--- /dev/null
+++ b/src/renderer/components/kanban/CardModal.liveLink.test.tsx
@@ -0,0 +1,144 @@
+// @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', () => ({
+ useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } }),
+ sessionForProject: (id: string) => ({ source: flags.relayProjects.has(id) ? 'relay' : 'local', api: {} })
+}))
+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: [],
+ ...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.mentionEscape.test.tsx b/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx
index a08734e3e..d6dd82017 100644
--- a/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx
+++ b/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx
@@ -48,7 +48,7 @@ describe('CardModal Escape vs the comment @ picker', () => {
const root = createRoot(host)
await act(async () => {
root.render(
- <CardModal session={session} columnTitle={null} board={board} onChangeBoard={vi.fn()} onClose={onClose}
+ <CardModal projectId="p1" session={session} columnTitle={null} board={board} onChangeBoard={vi.fn()} onClose={onClose}
onOpenCanvas={vi.fn()} onRename={vi.fn()} onEditSticky={vi.fn()} onBrowserNav={vi.fn()} onSetIcon={vi.fn()} />
)
})
diff --git a/src/renderer/components/kanban/CardModal.teamProgress.test.tsx b/src/renderer/components/kanban/CardModal.teamProgress.test.tsx
index a2b7e25dc..0bec7dc00 100644
--- a/src/renderer/components/kanban/CardModal.teamProgress.test.tsx
+++ b/src/renderer/components/kanban/CardModal.teamProgress.test.tsx
@@ -59,7 +59,7 @@ function mount(onTravel = vi.fn()): () => void {
const root = createRoot(host)
act(() =>
root.render(
- <CardModal session={session} columnTitle="Done" board={board} onChangeBoard={vi.fn()} onClose={vi.fn()}
+ <CardModal projectId="p1" session={session} columnTitle="Done" board={board} onChangeBoard={vi.fn()} onClose={vi.fn()}
onOpenCanvas={vi.fn()} onRename={vi.fn()} onEditSticky={vi.fn()} onSetIcon={vi.fn()}
onBrowserNav={vi.fn()} team={team} onTravel={onTravel} />
)
diff --git a/src/renderer/components/kanban/CardModal.test.tsx b/src/renderer/components/kanban/CardModal.test.tsx
index 12a3f4029..e5499d168 100644
--- a/src/renderer/components/kanban/CardModal.test.tsx
+++ b/src/renderer/components/kanban/CardModal.test.tsx
@@ -136,7 +136,7 @@ describe('CardModal', () => {
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
@@ -217,7 +217,7 @@ describe('CardModal', () => {
const root = createRoot(host)
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
@@ -259,7 +259,7 @@ describe('CardModal', () => {
const onClose = vi.fn()
act(() =>
root.render(
- <CardModal session={session} columnTitle="To Do" board={board} onChangeBoard={vi.fn()}
+ <CardModal projectId="p1" session={session} columnTitle="To Do" board={board} onChangeBoard={vi.fn()}
onClose={onClose} onOpenCanvas={vi.fn()} onRename={vi.fn()} onEditSticky={vi.fn()}
onSetIcon={vi.fn()} onBrowserNav={vi.fn()} onOpenIssue={onOpenIssue} />
)
@@ -279,7 +279,7 @@ describe('CardModal', () => {
const root = createRoot(host)
act(() =>
root.render(
- <CardModal session={{ id: 'n', title: 'T', color: '#fff', kind: 'terminal', issueRef, spawn: {} } as KanbanSession}
+ <CardModal projectId="p1" session={{ id: 'n', title: 'T', color: '#fff', kind: 'terminal', issueRef, spawn: {} } as KanbanSession}
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()} onOpenIssue={vi.fn()} />
@@ -305,7 +305,7 @@ describe('CardModal', () => {
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
@@ -381,7 +381,7 @@ describe('CardModal', () => {
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
@@ -435,7 +435,7 @@ describe('CardModal', () => {
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
@@ -475,7 +475,7 @@ describe('CardModal', () => {
const onClose = vi.fn()
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
@@ -526,7 +526,7 @@ describe('CardModal', () => {
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
@@ -580,7 +580,7 @@ describe('CardModal', () => {
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
@@ -629,7 +629,7 @@ describe('CardModal', () => {
const render = (root: ReturnType<typeof createRoot>, session: KanbanSession) =>
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle="To Do"
board={board}
diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsx
index 13f9952c0..faf9ed233 100644
--- a/src/renderer/components/kanban/CardModal.tsx
+++ b/src/renderer/components/kanban/CardModal.tsx
@@ -2,6 +2,7 @@ import { Suspense, lazy, useCallback, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { isTopDialog, nextDialogId, popDialog, pushDialog } from '../dialog-stack'
import {
+ IconBroadcast,
IconChat,
IconClose,
IconExternal,
@@ -19,7 +20,10 @@ import 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 { LiveLinkChip, projectSessionSource } from '../LiveLinkChip'
+import { useWatchLinks } from '../../state/watchLinks'
+import { liveLinkUnavailable } from '../../lib/liveLinkEntry'
+import { isBrowserRuntime } from '@renderer/bridge/runtime'
import { IssueRefChip } from '../IssueRefChip'
import { TeamProgressChip } from '../TeamProgressChip'
import type { TeamStation } from '../../lib/teamProgress'
@@ -68,6 +72,11 @@ const ChatPanel = lazy(() => import('../../nodes/ChatPanel').then((m) => ({ defa
interface CardModalProps {
session: KanbanSession
+ /** The project whose board this card is on — the active one on the per-project board, the lane's
+ * on the Omni board. The modal sits OUTSIDE that project's `SessionProvider` (`useSession()`
+ * here is the app's local session), so anything that depends on which machine the node runs
+ * on resolves through this id: the LIVE chip (R57) and the "Share live link" action (H4). */
+ projectId: string
/** Column title shown as a chip; null = Ungrouped. */
columnTitle: string | null
/** The live board + its pruned commit — the Members/Due strip edits through them. */
@@ -101,8 +110,19 @@ interface CardModalProps {
* canvas under it) stay mounted. Terminal cards carry the node header's actions too:
* search / dictate / AI-name / the ⌘M view — ChatPanel or the output markdown, the same face the
* canvas node shows (the node itself is hidden under the board). */
-export function CardModal({ session, columnTitle, board, onChangeBoard, onClose, onOpenCanvas, onRename, onEditSticky, onBrowserNav, onSetIcon, onOpenIssue, mentionables, team, onTravel }: CardModalProps) {
+export function CardModal({ session, projectId, columnTitle, board, onChangeBoard, onClose, onOpenCanvas, onRename, onEditSticky, onBrowserNav, onSetIcon, onOpenIssue, mentionables, team, onTravel }: CardModalProps) {
const { api } = useSession()
+ // 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
@@ -380,7 +400,7 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
</span>
)}
{isTerminal && <AccountChip chip={accountChip} />}
- {isTerminal && <LiveLinkChip nodeId={session.id} className="kanban-modal__live" />}
+ {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 not
driving-blind. The lease is keyed by node id (not by webview object), so this shows
when the node is being driven even though the drive lands on the CANVAS webview, not
@@ -477,6 +497,26 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,
>
{naming ? '…' : '✦'}
</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>
</>
)}
<button
diff --git a/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx b/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx
new file mode 100644
index 000000000..e8e8fea24
--- /dev/null
+++ b/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx
@@ -0,0 +1,102 @@
+// @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', () => ({
+ useSession: () => ({ id: 'local', source: 'local', api: {} }),
+ sessionForProject: (projectId: string) =>
+ projectId === 'relay' ? { id: 'relay-session', source: 'relay', api: {} } : { id: 'local', source: 'local', api: {} }
+}))
+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: []
+})
+
+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[], liveLinkMenuItems?: (nodeId: string, projectId: string) => MenuItem[]): 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 liveLinkMenuItems={liveLinkMenuItems} />))
+}
+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('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.tsx
index b6a383fb3..57ada800f 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.tsx
@@ -11,6 +11,7 @@ import {
} from '../../lib/kanban'
import { KanbanColumn, type KanbanLane } from './KanbanColumn'
import { SessionCard } from './SessionCard'
+import { projectSessionSource } from '../LiveLinkChip'
import { toKanbanSessionState } from '../../canvas/toKanbanSessionState'
import { createAgentNode, createBrowserNode, createStickyNode, createTerminalNode, flowToNodeStates, resolveNewNodeAccount } from '../../state/workspace'
import { markCanvasCovered } from '../../lib/canvasCovered'
@@ -78,10 +79,13 @@ interface SwimlaneProps {
* lane only; other lanes derive it from their persisted ropes. */
liveTeams?: ReadonlyMap<string, readonly TeamStation[]>
highlight?: boolean
+ /** Canvas's "Share live link…" row builder, asked for THIS lane's project (R49): creating a link
+ * does not need the node on screen, so a card of another project can share too. */
+ liveLinkMenuItems?: (nodeId: string, projectId: string) => MenuItem[]
}
const Swimlane = memo(function Swimlane({
- projectId, projectName, projectColor, board, sessions, ropes, nodes, onChangeBoard, onOpenNode, onCreateNode, onDeleteNode, onRenameNode, onEditSticky, onBrowserNav, onSetIcon, modalNodeId, onModalChange, liveTeams, highlight
+ projectId, projectName, projectColor, board, sessions, ropes, nodes, onChangeBoard, onOpenNode, onCreateNode, onDeleteNode, onRenameNode, onEditSticky, onBrowserNav, onSetIcon, modalNodeId, onModalChange, liveTeams, highlight, liveLinkMenuItems
}: SwimlaneProps) {
const dragRef = useRef<{ kind: 'column'; id: string } | { kind: 'card'; id: string } | null>(null)
const setModalNodeId = useCallback((nodeId: string | null) => onModalChange(projectId, nodeId), [onModalChange, projectId])
@@ -110,6 +114,8 @@ 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)
const sessionIds = useMemo(() => sessions.map(s => s.id), [sessions])
const paletteLabels = useMemo(() => boardLabels(board), [board])
@@ -215,6 +221,7 @@ const Swimlane = memo(function Swimlane({
team={teams.get(s.id) ?? NO_STATIONS}
onTravel={travel}
columnCategory={category}
+ liveLinkSource={liveLinkSource}
/>
))
}]
@@ -230,6 +237,7 @@ const Swimlane = memo(function Swimlane({
{ label: 'Open card', icon: <IconExternal />, onClick: () => setModalNodeId(nodeId) },
{ label: 'Open on canvas', icon: <IconExternal />, onClick: () => onOpenNode(nodeId, projectId) },
...(moveTargets.length ? [{ type: 'submenu', label: 'Move to', icon: <IconSwitch />, children: moveTargets } as MenuItem] : []),
+ ...(liveLinkMenuItems?.(nodeId, projectId) ?? []),
{ type: 'separator' },
{ label: 'Delete', icon: <IconTrash />, danger: true, onClick: () => onDeleteNode(projectId, nodeId) }
]
@@ -300,6 +308,7 @@ const Swimlane = memo(function Swimlane({
{modalNodeId && byId.has(modalNodeId) && (
<CardModal
session={byId.get(modalNodeId)!}
+ projectId={projectId}
columnTitle={columnForNode(board, modalNodeId)?.title ?? null}
board={board}
onChangeBoard={commit}
@@ -332,13 +341,16 @@ export interface GlobalKanbanLive {
export interface GlobalKanbanViewProps {
live?: GlobalKanbanLive | null
+ /** Canvas's "Share live link…" row builder (the node menu's), for every lane's card menu.
+ * Optional: an overview with no canvas behind it offers none. */
+ liveLinkMenuItems?: (nodeId: string, projectId: string) => MenuItem[]
/** Canvas's `setKanbanModalNode` — the same hook the per-project board reports to. It is what
* makes an open card "watched" (Eco must not hibernate it), wakes a hibernated agent on open,
* and points the dictation shortcut at the card instead of the selected canvas node. */
onModalNodeChange?: (nodeId: string | null) => void
}
-export const GlobalKanbanView = memo(function GlobalKanbanView({ live = null, onModalNodeChange }: GlobalKanbanViewProps) {
+export const GlobalKanbanView = memo(function GlobalKanbanView({ live = null, onModalNodeChange, liveLinkMenuItems }: GlobalKanbanViewProps) {
// Same rule as the per-project board: the canvas is covered but mounted underneath.
useEffect(() => markCanvasCovered(document.documentElement), [])
const boardStyle = useBoardWallpaperStyle()
@@ -487,6 +499,7 @@ export const GlobalKanbanView = memo(function GlobalKanbanView({ live = null, on
onModalChange={onModalChange}
liveTeams={isLive ? live.teams : undefined}
highlight={highlightId === p.id}
+ liveLinkMenuItems={liveLinkMenuItems}
/>
)
})}
diff --git a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
index 67c5ebab9..9cac9cba0 100644
--- a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
@@ -48,7 +48,7 @@ afterEach(() => {
vi.unstubAllGlobals()
})
-function render(accountMenuItems?: (id: string) => MenuItem[]): void {
+function render(accountMenuItems?: (id: string) => MenuItem[], liveLinkMenuItems?: (id: string) => MenuItem[]): void {
host = document.createElement('div')
document.body.appendChild(host)
root = createRoot(host)
@@ -68,6 +68,7 @@ function render(accountMenuItems?: (id: string) => MenuItem[]): void {
onBrowserNav={noop}
onSetIcon={noop}
accountMenuItems={accountMenuItems}
+ liveLinkMenuItems={liveLinkMenuItems}
/>
)
)
@@ -98,3 +99,21 @@ describe('KanbanView — card menu account switch', () => {
expect(document.body.textContent).not.toContain('Switch Claude account')
})
})
+
+describe('KanbanView — card menu Share live link (Task 17)', () => {
+ it('shows the node’s "Share live link…" row from the canvas builder, after the account rows', () => {
+ const live = vi.fn((id: string): MenuItem[] => [{ label: `Share live link… (${id})`, onClick: () => {} }])
+ render(() => [{ label: 'Switch Claude account', onClick: () => {} }], live)
+ openCardMenu()
+ expect(live).toHaveBeenCalledWith('n1')
+ const text = document.body.textContent ?? ''
+ expect(text).toContain('Share live link… (n1)')
+ expect(text.indexOf('Share live link… (n1)')).toBeGreaterThan(text.indexOf('Switch Claude account'))
+ })
+
+ it('shows none without a builder', () => {
+ render()
+ openCardMenu()
+ expect(document.body.textContent).not.toContain('Share live link')
+ })
+})
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index 69d9b4a46..ebdac4277 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -30,6 +30,7 @@ import { labelSwatch } from '../../lib/kanbanLabelColors'
import { CardModal } from './CardModal'
import { KanbanColumn, type KanbanLane } from './KanbanColumn'
import { SessionCard } from './SessionCard'
+import { projectSessionSource } from '../LiveLinkChip'
import { GitHubIssueCard } from './GitHubIssueCard'
import { GitHubPullCard } from './GitHubPullCard'
import { kanbanSource, sourceVisible } from '../../lib/kanbanSources'
@@ -135,6 +136,13 @@ export interface KanbanViewProps {
* with no canvas behind it (a test, a future read-only view) simply shows no rows.
*/
accountMenuItems?: (nodeId: string) => MenuItem[]
+ /**
+ * The node's "Share live link…" row — the SAME builder the canvas node menu and the sessions
+ * sidebar use (`liveLinkMenuItems` in Canvas), so a card offers what its node does, disabled with
+ * the same reason. Optional for the same reason as `accountMenuItems`: a board with no canvas
+ * behind it offers none.
+ */
+ liveLinkMenuItems?: (nodeId: string) => MenuItem[]
/** The board moving a session card itself because its linked pull requests merged (Canvas owns
* the compare-and-set + board-log line). Optional: without it nothing ever auto-moves. */
onAutoMoveFromPulls?: (
@@ -235,7 +243,7 @@ function useCanvasCovered(): void {
export const KanbanView = memo(function KanbanView({
board, sessions, onChange, onOpenNode, onCreateNode, onRenameNode, onEditSticky, onDeleteNode,
onModalNodeChange, onBrowserNav, onSetIcon, accountMenuItems, onAutoMoveFromPulls, issueAgentMenu,
- issueWorktreeMenu, teams, onIssueMoved
+ issueWorktreeMenu, teams, onIssueMoved, liveLinkMenuItems
}: KanbanViewProps) {
useCanvasCovered()
const { api } = useSession()
@@ -277,6 +285,9 @@ 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)
// Per-user display: whether `closed` columns are on screen (localStorage, never the board).
const showClosed = useKanbanDisplay((s) => s.byProject[projectId]?.showClosed === true)
const setShowClosed = useKanbanDisplay((s) => s.setShowClosed)
@@ -911,6 +922,7 @@ export const KanbanView = memo(function KanbanView({
team={teams?.get(s.id) ?? NO_STATIONS}
onTravel={onOpenNode}
columnCategory={category}
+ liveLinkSource={liveLinkSource}
/>
))
})
@@ -1003,6 +1015,7 @@ export const KanbanView = memo(function KanbanView({
? ([{ type: 'submenu', label: 'Move to', icon: <IconSwitch />, children: moveTargets }] as MenuItem[])
: []),
...(accountMenuItems?.(nodeId) ?? []),
+ ...(liveLinkMenuItems?.(nodeId) ?? []),
{ type: 'separator' },
{ label: 'Delete', icon: <IconTrash />, danger: true, onClick: () => onDeleteNode(nodeId) }
]
@@ -1240,6 +1253,7 @@ export const KanbanView = memo(function KanbanView({
{modalNodeId && byId.has(modalNodeId) && (
<CardModal
session={byId.get(modalNodeId)!}
+ projectId={projectId}
mentionables={mentionables}
columnTitle={columnForNode(board, modalNodeId)?.title ?? null}
board={board}
diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsx
index b853a1ca5..08f4fb360 100644
--- a/src/renderer/components/kanban/SessionCard.tsx
+++ b/src/renderer/components/kanban/SessionCard.tsx
@@ -2,7 +2,8 @@ import { memo, useState } from 'react'
import type { KanbanCardMeta, KanbanColumnCategory, KanbanLabel, KanbanPriority } from '@shared/types'
import { useAgentStatus } from '../../state/agentStatus'
import { AccountChip, useAccountChip } from '../AccountChip'
-import { LiveLinkChip } from '../LiveLinkChip'
+import { LiveLinkChip, showsLiveLinks } from '../LiveLinkChip'
+import type { SessionSource } from '../../session/session'
import { useWatchLinks } from '../../state/watchLinks'
import { ContextMeter } from '../ContextMeter'
import { isRemoteSessionNode } from '@shared/worktree'
@@ -48,11 +49,15 @@ 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
}
export const SessionCard = memo(function SessionCard({
session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext, pulls,
- pullFreshness = 'fresh', onOpenIssue, team, onTravel, columnCategory
+ pullFreshness = 'fresh', onOpenIssue, team, onTravel, columnCategory, liveLinkSource
}: SessionCardProps) {
// THIS card's agent status, subscribed per card rather than threaded down from the board.
// KanbanView used to hold `useAgentStatus((s) => s.byId)` and pass the map through the column:
@@ -91,7 +96,10 @@ export const SessionCard = memo(function SessionCard({
const 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 hasLiveLink = useWatchLinks((s) => session.kind === 'terminal' && (s.byNode[session.id]?.length ?? 0) > 0)
+ 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 =
@@ -224,7 +232,7 @@ export const SessionCard = memo(function SessionCard({
<>
<ContextMeter sessionId={status?.sessionId ?? null} nodeId={session.id} remote={isRemoteSessionNode(session.spawn)} agentId={session.agentId ?? session.spawn.agentId ?? status?.agentId} />
<AccountChip chip={accountChip} />
- <LiveLinkChip nodeId={session.id} className="kanban-card__live" />
+ <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/settings/SettingsIcons.tsx b/src/renderer/components/settings/SettingsIcons.tsx
index ddc40b375..0bef94828 100644
--- a/src/renderer/components/settings/SettingsIcons.tsx
+++ b/src/renderer/components/settings/SettingsIcons.tsx
@@ -132,6 +132,14 @@ 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.tsx
index 871a20478..733a0d39d 100644
--- a/src/renderer/components/settings/SettingsPage.tsx
+++ b/src/renderer/components/settings/SettingsPage.tsx
@@ -27,6 +27,7 @@ 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'
@@ -126,6 +127,7 @@ export function SettingsPage({
<PresenceIdentitySection isActive={active === 'presence'} />
<RemoteSection isActive={active === 'remote'} onClose={onClose} />
<TeamAccessSection isActive={active === 'team-access'} onClose={onClose} />
+ <LiveLinksSection isActive={active === 'live-links'} />
<SshSection isActive={active === 'ssh'} />
<UpdatesSection isActive={active === 'updates'} />
<PrivacySection isActive={active === 'privacy'} />
diff --git a/src/renderer/components/settings/nav.test.ts b/src/renderer/components/settings/nav.test.ts
index a3edd98ae..fa58bcfc1 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 25 sections with no duplicates', () => {
+ it('lists exactly 26 sections with no duplicates', () => {
const ids = allSectionIds()
- expect(ids).toHaveLength(25)
- expect(new Set(ids).size).toBe(25)
+ 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,13 +13,22 @@ 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(24)
+ expect(off).toHaveLength(25)
expect(visibleSettingsGroups(true)).toEqual(SETTINGS_GROUPS)
// No group is left empty by the filter.
expect(visibleSettingsGroups(false).every((g) => g.sections.length > 0)).toBe(true)
})
})
+describe('Live links section', () => {
+ it('sits in Remote & team right after Team seats', () => {
+ 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')
+ })
+})
+
describe('projectsSettingsGroup', () => {
// NOTE (project-icons Task 2): this assertion used to read
// `expect(g?.sections).toEqual([{ id: 'project-p1', title: 'Alpha' }])` — the exact bug this
diff --git a/src/renderer/components/settings/nav.ts b/src/renderer/components/settings/nav.ts
index 251711908..b6db6b458 100644
--- a/src/renderer/components/settings/nav.ts
+++ b/src/renderer/components/settings/nav.ts
@@ -23,6 +23,7 @@ export type SettingsSectionId =
| 'presence'
| 'remote'
| 'team-access'
+ | 'live-links'
| 'ssh'
| 'updates'
| 'privacy'
@@ -99,6 +100,7 @@ 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.tsx
new file mode 100644
index 000000000..5ed7fe54b
--- /dev/null
+++ b/src/renderer/components/settings/sections/LiveLinksSection.test.tsx
@@ -0,0 +1,206 @@
+// @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 () => {})
+}
+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 },
+ { viewerId: 'b', name: null, joinedAt: 0 }
+ ],
+ ...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 () => {})
+ 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')
+ expect(rows[0].textContent).toContain('Can watch and chat')
+ 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('Can watch')
+ 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('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 are disconnected at once.'
+ )
+ 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()
+ })
+
+ 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.tsx
new file mode 100644
index 000000000..d8b4f2853
--- /dev/null
+++ b/src/renderer/components/settings/sections/LiveLinksSection.tsx
@@ -0,0 +1,169 @@
+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 { projectSessionSource, showsLiveLinks } from '../../LiveLinkChip'
+import { useEntitlement } from '../../../state/entitlement'
+import { useProjects } from '../../../state/projects'
+import { useWatchLinks } from '../../../state/watchLinks'
+import {
+ formatRemaining,
+ NOT_IN_OPEN_PROJECT,
+ ROLE_LABEL,
+ SERVER_EDITION_UNSUPPORTED,
+ statusLine,
+ STOP_ALL_BUTTON
+} from '../../../lib/liveLink'
+import { stopAllConfirm, 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).
+ */
+export function liveLinkProjectLabel(projects: readonly Project[], nodeId: string): string {
+ const holders = projects.filter(
+ (p) => 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.status)
+ 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_LABEL[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)
+ const [stopAllError, setStopAllError] = useState<string | null>(null)
+ 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: () => {
+ setStopAllError(null)
+ void stopLiveLinks(() => window.nodeTerminal.watchLink.revokeAll(), setStopAllError)
+ }
+ })
+ 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 className="flex items-center gap-3">
+ <Button onClick={() => setConfirmStopAll(true)}>{STOP_ALL_BUTTON}</Button>
+ {stopAllError && (
+ <span className="text-xs" role="alert" style={{ color: 'var(--danger)' }}>
+ {stopAllError}
+ </span>
+ )}
+ </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 ? (
+ <p className="text-sm text-muted">
+ No active live links. Right-click a terminal and choose "Share live link…".
+ </p>
+ ) : (
+ <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>
+ )}
+ </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.tsx
new file mode 100644
index 000000000..0d1d366af
--- /dev/null
+++ b/src/renderer/components/settings/sections/ProCompare.test.tsx
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { ProCompare } from './ProCompare'
+import { AGENT_CONFIG, BUILTIN_AGENT_IDS } from '@shared/agents/config'
+
+const column = (html: string, heading: string): string[] => {
+ const at = html.indexOf(heading)
+ const rest = html.slice(at)
+ const end = rest.indexOf('</div>')
+ return [...rest.slice(0, end).matchAll(/<p class="text-text">✓ ([^<]*)<\/p>/g)].map((m) => m[1].replace(/&amp;/g, '&'))
+}
+
+describe('ProCompare', () => {
+ const html = renderToStaticMarkup(<ProCompare />)
+
+ it('lists live links under Pro', () => {
+ expect(column(html, 'Pro<')).toContain('Live read-only links to a terminal — viewers need nothing installed')
+ })
+
+ it('leaves the free Core list exactly as it was', () => {
+ expect(column(html, 'Core — free forever')).toEqual([
+ 'Unlimited local terminals & canvas',
+ 'Unlimited SSH projects',
+ 'Groups, worktrees, git & diff',
+ `Agent nodes (${BUILTIN_AGENT_IDS.map((id) => AGENT_CONFIG[id].label).join(' / ')})`,
+ 'QR phone pairing on your LAN',
+ 'Remote access from your phone (relay, E2E encrypted)'
+ ])
+ })
+})
diff --git a/src/renderer/components/settings/sections/ProCompare.tsx b/src/renderer/components/settings/sections/ProCompare.tsx
index 09bf80d87..7f637f970 100644
--- a/src/renderer/components/settings/sections/ProCompare.tsx
+++ b/src/renderer/components/settings/sections/ProCompare.tsx
@@ -10,7 +10,8 @@ const CORE = [
]
const PRO = [
'nodeterm mobile Pro included',
- '3 team seats included (extra seats $5/seat/mo)'
+ '3 team seats included (extra seats $5/seat/mo)',
+ 'Live read-only links to a terminal — viewers need nothing installed'
]
/** Core vs Pro comparison. */
diff --git a/src/renderer/lib/live-link.guard.test.ts b/src/renderer/lib/live-link.guard.test.ts
index 04ea8c9ed..dbc7fa818 100644
--- a/src/renderer/lib/live-link.guard.test.ts
+++ b/src/renderer/lib/live-link.guard.test.ts
@@ -53,7 +53,7 @@ describe('live-link guards', () => {
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 \} from '(\.\.\/|\.\/)(components\/)?LiveLinkChip'/)
+ 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)
@@ -65,6 +65,33 @@ describe('live-link guards', () => {
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}')
}
})
diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.ts
index a0696fe64..759e96642 100644
--- a/src/renderer/lib/liveLink.test.ts
+++ b/src/renderer/lib/liveLink.test.ts
@@ -198,10 +198,14 @@ describe('noticeText', () => {
)
})
- it('not-persistent says only the new link is unsaved, and names no cause (H7, H26, R55)', () => {
+ 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(
- "The live link you just created isn't saved on this computer: it works until you quit. Links created before it are still saved."
+ "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', () => {
diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.ts
index 884b79731..a1d2e4c59 100644
--- a/src/renderer/lib/liveLink.ts
+++ b/src/renderer/lib/liveLink.ts
@@ -186,12 +186,12 @@ 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, R55): the keychain refused to seal — only the link just
- // created is lost at a restart, links read at boot or sealed earlier stay saved — or the links
- // file could not be read. The renderer cannot tell them apart, so it says what the shared type
- // documents as the default: only the new link.
+ // 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 `The live link you just created isn't saved on ${thisMachine()}: it works until you quit. Links created before it are still saved.`
+ 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.`
diff --git a/src/renderer/lib/liveLinkEntry.gate.test.ts b/src/renderer/lib/liveLinkEntry.gate.test.ts
new file mode 100644
index 000000000..6fd1a07b6
--- /dev/null
+++ b/src/renderer/lib/liveLinkEntry.gate.test.ts
@@ -0,0 +1,71 @@
+// @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.tsx
new file mode 100644
index 000000000..c1e3bd7be
--- /dev/null
+++ b/src/renderer/lib/liveLinkEntry.test.tsx
@@ -0,0 +1,249 @@
+// @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,
+ liveLinkMenuRow,
+ liveLinkNodeFor,
+ liveLinkPrepare,
+ liveLinkUnavailable,
+ openLiveLink,
+ stopAllConfirm,
+ 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()
+ })
+})
+
+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 })
+ expect(spec.message).toBe(
+ 'Stop every live link on your license? This also ends links shared from other computers. Viewers are disconnected at once.'
+ )
+ 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()
+ })
+})
+
+describe('liveLinkCommands (palette)', () => {
+ it('Manage always; Stop all only with links, labelled for every machine, and it CONFIRMS', () => {
+ const manage = vi.fn()
+ const confirmStopAll = vi.fn()
+ const none = liveLinkCommands({ activeLinks: 0, icon: null, manage, confirmStopAll })
+ expect(none.map((c) => c.id)).toEqual(['live-links-manage'])
+ const some = liveLinkCommands({ activeLinks: 2, icon: null, manage, confirmStopAll })
+ expect(some.map((c) => c.id)).toEqual(['live-links-manage', 'live-links-stop-all'])
+ expect(some[0].label).toBe('Manage live links')
+ expect(some[1].label).toBe('Stop all live links (every machine on this license)')
+ some[0].run()
+ expect(manage).toHaveBeenCalledTimes(1)
+ some[1].run()
+ expect(confirmStopAll).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/renderer/lib/liveLinkEntry.tsx b/src/renderer/lib/liveLinkEntry.tsx
new file mode 100644
index 000000000..f9d7c1c97
--- /dev/null
+++ b/src/renderer/lib/liveLinkEntry.tsx
@@ -0,0 +1,212 @@
+// 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 {
+ PRO_GATE_FEATURE,
+ SAVE_FIRST_MESSAGE,
+ shareDisabledReason,
+ STOP_ALL_BUTTON,
+ STOP_ALL_PALETTE_LABEL,
+ STOP_FAILED_MESSAGE,
+ stopAllConfirmMessage
+} 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
+}
+
+/**
+ * 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)
+ }
+ ]
+}
+
+/**
+ * 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 a stop (one revoke, or revoke-all) 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. */
+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
+ }
+}
+
+/** The palette's live-link entries. "Stop all" appears only while this machine lists a link, and
+ * its `run` opens the confirm — it never stops anything itself. */
+export function liveLinkCommands(o: {
+ activeLinks: number
+ icon: ReactNode
+ manage: () => 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-links-stop-all',
+ label: STOP_ALL_PALETTE_LABEL,
+ hint: 'share revoke broadcast',
+ icon: o.icon,
+ run: o.confirmStopAll
+ }
+ ]
+ : [])
+ ]
+}
diff --git a/src/renderer/lib/ui-visibility.test.ts b/src/renderer/lib/ui-visibility.test.ts
index f6adfd17a..a7d945011 100644
--- a/src/renderer/lib/ui-visibility.test.ts
+++ b/src/renderer/lib/ui-visibility.test.ts
@@ -24,7 +24,7 @@ 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', 'vanilla-restart'
+ 'markdown-view', 'refresh-terminal', 'live-link', 'vanilla-restart'
])
expect(HIDEABLE_HEADER_BUTTONS.map((r) => r.id)).toEqual([
'maximize', 'refresh', 'mic', 'ai-name', 'comments', 'hide-fanout', 'tidy-fanout', 'md-hint'
diff --git a/src/renderer/lib/ui-visibility.ts b/src/renderer/lib/ui-visibility.ts
index d54e8a3f0..b53d17793 100644
--- a/src/renderer/lib/ui-visibility.ts
+++ b/src/renderer/lib/ui-visibility.ts
@@ -28,6 +28,9 @@ 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' }
]
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index a53ca5c57..ed3981cd9 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -5959,8 +5959,9 @@ export function TerminalNode({
{showUsage && <ContextMeter sessionId={status?.sessionId ?? null} 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). */}
- <LiveLinkChip 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} />
diff --git a/src/renderer/nodes/browser-partition-parity.test.tsx b/src/renderer/nodes/browser-partition-parity.test.tsx
index 12513eaef..e0c79ec1e 100644
--- a/src/renderer/nodes/browser-partition-parity.test.tsx
+++ b/src/renderer/nodes/browser-partition-parity.test.tsx
@@ -70,7 +70,7 @@ function partitionFromModal(sessionPartition: string | undefined): string | null
}
act(() =>
root.render(
- <CardModal
+ <CardModal projectId="p1"
session={session}
columnTitle={null}
board={{ columns: [], assignments: {} } as never}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 193f67071..72158316f 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -11498,6 +11498,78 @@ button.pull-checks__name {
padding: 4px 8px;
font-size: 12px;
}
+/* The create dialog (LiveLinkDialog): the `.confirm` shell, a little wider for the URL. */
+.confirm.live-dialog {
+ width: 460px;
+}
+.live-dialog .live-dialog__title {
+ flex: 0 0 auto;
+ margin-bottom: 10px;
+ font-weight: 600;
+ overflow-wrap: anywhere;
+}
+.live-dialog__group {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px 14px;
+ margin: 0 0 10px;
+ padding: 0;
+ border: 0;
+ font-size: 12px;
+}
+.live-dialog__group legend {
+ width: 100%;
+ margin-bottom: 4px;
+ padding: 0;
+ color: var(--muted);
+ font-size: 11px;
+}
+.live-dialog__group label {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ cursor: pointer;
+}
+.live-dialog__label {
+ display: block;
+ color: var(--muted);
+ font-size: 11px;
+}
+.live-dialog__label .confirm__input {
+ margin: 4px 0 10px;
+}
+/* The exposure warning: always visible, never a checkbox. A hue wash with ink text (the status-chip
+ recipe), so it reads the same on the default look and under Liquid Glass. */
+.live-dialog__warning {
+ margin: 0 0 10px;
+ padding: 8px 10px;
+ border-radius: 6px;
+ background: color-mix(in srgb, var(--state-warning) 12%, transparent);
+ color: var(--text);
+ 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__url {
+ display: flex;
+ gap: 6px;
+ align-items: center;
+}
+.live-dialog__url .confirm__input {
+ flex: 1 1 auto;
+ min-width: 0;
+ margin: 0;
+}
+.live-dialog__note {
+ margin: 8px 0 12px;
+ color: var(--muted);
+ font-size: 12px;
+}
/* The session name in the card modal header: sized to its text, not a flex-filling detail line. */
.kanban-modal__session {
flex: 0 1 auto;