Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(live-links): a Figma-style create dialog
review6ef48ae27984
diff --git a/docs/live-links.md b/docs/live-links.mdindex b8869a23c..b844a39d2 100644--- a/docs/live-links.md+++ b/docs/live-links.md@@ -618,23 +618,47 @@ everything.### The create dialog-- The role radios read "Viewer · Can watch", "Commenter · Can watch and chat" and "Control · Can watch,- chat and type". `controlSupport(nodeId)` is asked once; only `unsupported` disables Control.-- With Control picked, the dialog shows the password field with Generate and an inline validation line,- and **both warnings**, one box each: the watch warning first (anyone with the LINK alone still sees- everything the terminal shows; the sentence "They can't type or resize it." is left out), then the- typing warning, with "and" in bold: "Anyone with this link **and** the password can type in this- terminal as you. In a shell that means running any command on <machine>; in an agent session,- giving the agent any instruction. Send the password separately from the link."+Figma's share-dialog shape (`LiveLinkDialog.tsx`, `MenuSelect.tsx`): a head with the node's title+and ✕, then one grouped list whose rows read as sentences, the warnings, and the actions.++- **Rows.** "Anyone with the link · can watch ▾" (the role menu), "Password · <field> ↻" (Control+ only), "Expires · in 1 hour ▾" (the expiry menu) and "Viewers see you as · <name>" (the label, an+ inline field that shows its box on hover and focus). The role menu's options read "can watch —+ Sees the terminal", "can chat — Watches and chats with you" and "can type — Also types, with a+ password" (`ROLE_CHOICE`). The expiry menu reads "in 15 minutes" … "in 24 hours", then "never —+ This link works until you stop it." `controlSupport(nodeId)` is asked once; only `unsupported`+ disables "can type", and the disabled option's hint is the reason.+- **The menus render inside their row**, absolutely positioned and opaque, never in a portal: the+ dialog is a backdrop root under Liquid Glass. Keyboard: ArrowDown/ArrowUp open a menu; the arrows,+ Home and End move over the options that can be picked; Enter/Space pick; Escape and Tab close it+ and give focus back to the trigger. The menu's Escape never reaches the dialog's, so it does not+ close the dialog. The role menu's trigger takes the focus when the dialog opens (D2/M3).+- **Picking "can type" fills a generated password** (16 symbols, the same generator as before) when+ the field is empty, so a Control link is two clicks; ↻ ("New password") replaces it, and the owner+ can still type their own. A password already there (typed, or kept from switching away and back) is+ left alone. The validation line sits under the row once something invalid is typed.+- **Warnings.** Control shows the typing warning, with "and" in bold, in a red wash: "With this link+ **and** the password, anyone can type here as you: run any command on <machine>, or instruct the+ agent in this terminal." Under it, for every role, one muted sentence of what watching exposes:+ "Viewers see everything this terminal shows: scrollback, anything printed later (tokens too), and+ other tmux sessions if you open the session chooser or switch sessions." Neither is behind a+ toggle.- **The typing warning names the machine where the commands run**: `thisMachine()` ("this Mac", "thisPC", "this computer") for a local node; `user@host` for an SSH-project node or a node attached to anSSH host. A remote tmux node on its own SSH project's host names the PROJECT's user, the one theshell runs as.+- **The dialog remembers the role and the expiry of the last link this person created**+ (`lib/liveLinkDefaults.ts`, localStorage `nodeterm.liveLinkDefaults`, saved only after a create+ succeeds). The first dialog opens on "can watch" for an hour. A remembered Control opens with a+ fresh generated password and its warning on screen, and on a terminal that cannot take input it+ falls back to "can watch". Never the password, never the label.- Create stays disabled until the password passes the rule. The request carries `password` only forControl.-- The done step shows the password once, read-only, with Copy password, "This is the only time the- password is shown. Change it later from the LIVE chip." and "Send the password separately from the- link.", then "Anyone with this link and the password can type until …".+- **The done step**: a status line in the LIVE chip's red ("● Anyone with this link and the password+ can type until …"), the link with **Copy link**, then for Control the read-only password with+ **Copy password** and one note ("This is the only time the password is shown. Change it later+ from the LIVE chip. Send the password separately from the link."). **Stop sharing** is a red text+ button on the left, **Done** on the right.### The viewer page (nodeterm-web)@@ -658,8 +682,8 @@ control again to type.". While typing:## Unlimited links-The TTL choice has a fifth option, **Unlimited** (wire value `ttlSeconds: 0`), listed last. While it is-picked the dialog says "This link works until you stop it." The link has `expiresAt: null` and lives+The TTL choice has a fifth option, **Unlimited** (wire value `ttlSeconds: 0`), listed last; the+dialog's expiry menu calls it "never", with the hint "This link works until you stop it." The link has `expiresAt: null` and livesuntil Stop, Stop all, a server 410, node-gone, or (for new joins) a lapse of the owner's Pro.- **Backend** (nodeterm-server). `watch_links.expires_at` is nullable, and NULL means live everywhere:@@ -1128,8 +1152,9 @@ Visual checks (renderer, Mac and a Server Edition browser tab):from Settings → Appearance → Terminal header buttons.Card modal header: the broadcast action between ✦ and the comments button; disabled look + tooltip(Chromium shows `title` on disabled buttons — confirm on the packaged build).-29. The create dialog: 460 px `.confirm` shell, radios wrapping, the warning wash, the URL row with- Copy/Copied!, "until HH:MM" in 12/24 h locales; long node titles; dark + light; Liquid Glass.+29. The create dialog: 440 px `.confirm` shell, the grouped rows, the menus, the URL row with+ Copy link/Copied!, "until HH:MM" in 12/24 h locales; a long node title ellipsizes in the head (full+ title on hover); dark + light; Liquid Glass.30. The dialog opened from the card modal (z 70 over 55), and the UpgradeDialog opened from the cardmodal / board.31. Palette: "Manage live links" and "Stop all live links (every machine on this license)" with the@@ -1235,23 +1260,29 @@ From the build:Visual checks (Mac, default look and Liquid Glass, dark and light) — the create dialog:-58. Role radios read "Viewer · Can watch", "Commenter · Can watch and chat", "Control · Can watch, chat- and type" (name in ink, the rest muted) and wrap cleanly in the 460 px dialog.-59. On a Zellij node: the Control radio is dimmed (`.live-dialog__off`, not-allowed cursor, tooltip with- the reason) and the reason line sits under the radios.-60. The password block between the roles and "Ends after": a muted "Password" caption, a monospace text- field and **Generate**; the red validation line under it only once something is typed.-61. Control shows TWO stacked warning boxes: the watch exposure first, then the typing warning with a- bold "and", naming this machine ("this Mac") for a local node and `user@host` for an SSH-project- node, for a node attached to an SSH host in a local project, and for a standalone ssh terminal node.+58. The form is one grouped list of rows (globe, lock, clock, person icons): "Anyone with the link ·+ can watch ▾", "Expires · in 1 hour ▾", "Viewers see you as · Enes" (no box until hover/focus).+ The role and expiry menus open under their trigger, right-aligned, opaque, over the rows and the+ warnings; a check marks the current choice; hints are muted, one line each. Under Liquid Glass+ the menu stays opaque (no see-through, no blur inside the dialog). Keyboard: ArrowDown opens a+ menu, Enter picks, Escape closes only the menu (the dialog stays).+59. On a Zellij node: "can type" in the role menu is muted and cannot be picked, its hint is the+ reason. A remembered Control opens on "can watch" there.+60. Picking "can type" adds the Password row with a generated monospace password and ↻; ↻ changes it;+ clearing it disables Create; the red validation line sits under the row only once something+ invalid is typed.+61. Control shows the typing warning in a red wash with a bold "and", naming this machine ("this Mac")+ for a local node and `user@host` for an SSH-project node, for a node attached to an SSH host in a+ local project, and for a standalone ssh terminal node; the muted exposure sentence sits under it.A long host wraps inside its box. Check the dialog's height on a small window: Create stays- reachable.-62. "Ends after" has a fifth radio, **Unlimited**; picking it shows "This link works until you stop it."- under the row.-63. The done step for Control: under the URL row, a read-only monospace password row with **Copy- password** ("Copied!" for 1.5 s), the two notes, then "Anyone with this link and the password can- type until you stop it." (or a time).-+ reachable, and the expiry menu is not cut off.+62. The expiry menu's last option is "never" with "This link works until you stop it."; picking it+ makes the row read "Expires · never".+63. The done step for Control: the red status dot and "Anyone with this link and the password can+ type until …", the URL row with **Copy link**, the read-only monospace password with **Copy+ password** ("Copied!" for 1.5 s, the buttons the same width), the one note, then Stop sharing+ (red text, left) and Done. Create a second link: the dialog opens on the role and expiry of the+ first; the very first dialog after a fresh install opens on "can watch" for an hour.The chip and the popover:64. The unread count pill (13 px, a `--state-unread` wash, `99+` cap) on the 18 px node chip and thediff --git a/src/renderer/components/LiveLinkDialog.test.tsx b/src/renderer/components/LiveLinkDialog.test.tsxindex 63a678d9d..5aacb0889 100644--- a/src/renderer/components/LiveLinkDialog.test.tsx+++ b/src/renderer/components/LiveLinkDialog.test.tsx@@ -10,13 +10,13 @@ import {controlWarningText,formatClock,LIVE_LINK_EXPOSURE,- LIVE_LINK_WARNING,PASSWORD_SEPARATE_NOTE,PASSWORD_SHOWN_ONCE,SAVE_FIRST_MESSAGE,STOP_FAILED_MESSAGE,UNLIMITED_NOTE} from '../lib/liveLink'+import { LIVE_LINK_DEFAULTS_KEY } from '../lib/liveLinkDefaults'import { resetDialogStack } from './dialog-stack'import { pinNeutralMachineNoun } from '../lib/testMachineNoun'@@ -31,18 +31,20 @@ const body = (state: Parameters<typeof LiveLinkDialogBody>[0]['state'], extra: Pconst FORM = { phase: 'form', role: 'viewer', ttl: 3600, label: 'Ada', password: '', busy: false, error: null } as constdescribe('LiveLinkDialogBody', () => {- it('shows the role and expiry choices with the defaults, and the warning always', () => {+ it('reads as rows: who can use the link, when it expires, the name — and the exposure always', () => {const html = body(FORM)- expect(html).toContain('Share 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', 'Unlimited']) expect(html).toContain(t)- // Spec §2.7: Viewer / Commenter / Control.- for (const r of ['Viewer', 'Commenter', 'Control']) expect(html).toContain(r)- // Neither Control's password field nor its warning until Control is picked.+ expect(html).toContain('Share “build”')+ expect(html).toContain('Anyone with the link')+ expect(html).toContain('can watch')+ expect(html).toContain('Expires')+ expect(html).toContain('in 1 hour')+ expect(html).toContain('Viewers see you as')+ // The menus are closed: their choices are not on the page until one is opened.+ expect(html).not.toContain('menu-select__menu')+ // Neither Control's password row nor its warning until Control is picked.expect(html).not.toContain('live-dialog__password')- expect(html).not.toContain('can type in this terminal as you')- expect(html).toContain(LIVE_LINK_WARNING.replace(/'/g, '''))+ expect(html).not.toContain('live-dialog__warning')+ expect(html).toContain(LIVE_LINK_EXPOSURE)expect(html).toContain('Create live link')})@@ -51,7 +53,7 @@ describe('LiveLinkDialogBody', () => {const now = new Date(2026, 9, 1, 14, 42, 0).getTime()const html = body({ phase: 'done', role: 'viewer', url: 'https://nodeterm.dev/s/x#1.y', linkId: 'x', expiresAt }, { now })expect(html).toContain('https://nodeterm.dev/s/x#1.y')- expect(html).toContain('Copy')+ expect(html).toContain('Copy link')expect(html).toContain('Stop sharing')expect(html).toContain(`Anyone with this link can watch until ${formatClock(expiresAt)}.`)})@@ -67,7 +69,9 @@ describe('LiveLinkDialogBody', () => {it('Control: the "and" of the typing warning is bold, and the machine is the one the caller names', () => {const html = body({ ...FORM, role: 'controller' }, { controlMachine: '[email protected]' })expect(html).toContain('<strong>and</strong>')- expect(html).toContain('running any command on [email protected];')+ expect(html).toContain('run any command on [email protected],')+ // The exposure stays under it: anyone with the link alone still watches a Control link.+ expect(html).toContain(LIVE_LINK_EXPOSURE)})it('R63: the "only while open" note shows in the form when the caller has one', () => {@@ -79,7 +83,7 @@ describe('LiveLinkDialogBody', () => {const html = renderToStaticMarkup(<LiveLinkDialogBody title={'bu\u202eild'} state={FORM} onChange={noop} onSubmit={noop} onClose={noop} onStop={noop} />)- expect(html).toContain('Share a live link to build')+ expect(html).toContain('Share “build”')})it('offers Upgrade only for a not-entitled error AND only when the caller can upgrade (H12, R43)', () => {@@ -166,6 +170,22 @@ const setLabel = (v: string): void => {})}+/** A row's menu trigger, by the row's label ("Anyone with the link", "Expires"). */+const trigger = (row: string): HTMLButtonElement =>+ document.querySelector<HTMLButtonElement>(`.menu-select__trigger[aria-label^="${row}:"]`)!+/** An option of the OPEN menu, by its label. */+const option = (label: string): HTMLButtonElement | undefined =>+ [...document.querySelectorAll<HTMLButtonElement>('.menu-select__item')].find(+ (b) => b.querySelector('.menu-select__label')?.textContent === label+ )+/** Open a row's menu and pick an option, the way a person does. */+const choose = (row: string, label: string): void => {+ click(trigger(row))+ click(option(label)!)+}+const pickRole = (label: 'can watch' | 'can chat' | 'can type'): void => choose('Anyone with the link', label)+const roleValue = (): string => trigger('Anyone with the link').querySelector('.menu-select__value')!.textContent!+function mount(o: {prepare?: () => Promise<string | null>onUpgrade?: () => void@@ -213,13 +233,13 @@ describe('LiveLinkDialog', () => {expect(document.querySelector<HTMLInputElement>('.live-dialog__label input')!.value).toBe('x'.repeat(39))})- it('D2/M3: focus lands in the dialog — the label on open, Copy once created', async () => {+ it('D2/M3: focus lands in the dialog — the role menu on open, Copy link once created', async () => {mount()- expect(document.activeElement).toBe(document.querySelector('.live-dialog__label input'))+ expect(document.activeElement).toBe(trigger('Anyone with the link'))setLabel('Ada')click(btn('Create live link'))await flush()- expect(document.activeElement).toBe(btn('Copy'))+ expect(document.activeElement).toBe(btn('Copy link'))})// R63: on a machine with no watcher client for a local node (Windows' session host, tmux off or@@ -343,18 +363,13 @@ describe('LiveLinkDialog', () => {setLabel('Ada')click(btn('Create live link'))await flush()- click(btn('Copy'))+ click(btn('Copy link'))expect(window.nodeTerminal.clipboard.writeText).toHaveBeenCalledWith('https://nodeterm.dev/s/abc#1.k')})})// ---- Control and Unlimited (spec 2026-10-03 §2.7, §3) --------------------------------------------const radio = (text: string): HTMLInputElement =>- [...document.querySelectorAll<HTMLLabelElement>('.live-dialog__group label')]- .find((l) => l.textContent?.includes(text))!- .querySelector('input')!-const pick = (text: string): void => click(radio(text))const pwInput = (): HTMLInputElement | null => document.querySelector<HTMLInputElement>('.live-dialog__password input')const typeInto = (input: HTMLInputElement, v: string): void =>act(() => {@@ -362,7 +377,8 @@ const typeInto = (input: HTMLInputElement, v: string): void =>input.dispatchEvent(new Event('input', { bubbles: true }))})const warnings = (): string[] => [...document.querySelectorAll('.live-dialog__warning')].map((e) => e.textContent ?? '')-const warning = (): string | null => warnings()[0] ?? null+const exposure = (): string | null => document.querySelector('.live-dialog__exposure')?.textContent ?? null+const GENERATED = /^[0-9abcdefghjkmnpqrstvwxyz]{16}$/const createWith = (over: Partial<CreateWatchLinkRequest> = {}): CreateWatchLinkResult => ({ok: true,link: {@@ -373,83 +389,119 @@ const createWith = (over: Partial<CreateWatchLinkRequest> = {}): CreateWatchLink}})+describe('LiveLinkDialog — the menus', () => {+ it('the role menu lists the three roles, each with what it grants, the current one checked', async () => {+ mount()+ await flush()+ click(trigger('Anyone with the link'))+ const items = [...document.querySelectorAll<HTMLButtonElement>('.menu-select__item')]+ expect(items.map((b) => b.querySelector('.menu-select__label')!.textContent)).toEqual(['can watch', 'can chat', 'can type'])+ expect(items.map((b) => b.querySelector('.menu-select__hint')!.textContent)).toEqual([+ 'Sees the terminal',+ 'Watches and chats with you',+ 'Also types, with a password'+ ])+ expect(items.map((b) => b.getAttribute('aria-checked'))).toEqual(['true', 'false', 'false'])+ })++ it('the expiry menu ends on "never", whose hint says it works until stopped', async () => {+ mount()+ await flush()+ click(trigger('Expires'))+ const labels = [...document.querySelectorAll('.menu-select__item .menu-select__label')].map((e) => e.textContent)+ expect(labels).toEqual(['in 15 minutes', 'in 1 hour', 'in 8 hours', 'in 24 hours', 'never'])+ expect(option('never')!.querySelector('.menu-select__hint')!.textContent).toBe(UNLIMITED_NOTE)+ })++ it("Escape in an open menu closes the menu, not the dialog", async () => {+ const { onClose } = mount()+ await flush()+ click(trigger('Expires'))+ const focused = document.activeElement!+ expect(focused.className).toContain('menu-select__item')+ act(() => void focused.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true })))+ expect(document.querySelector('.menu-select__menu')).toBeNull()+ expect(onClose).not.toHaveBeenCalled()+ expect(document.activeElement).toBe(trigger('Expires'))+ })+})+describe('LiveLinkDialog — Control', () => {- it('Control shows the password field with Generate, and BOTH warnings: what watching exposes, then typing', async () => {+ it('picking "can type" fills a generated password and shows the typing warning above the exposure', async () => {mount()await flush()expect(pwInput()).toBeNull()- expect(warnings()).toEqual([LIVE_LINK_WARNING])- pick('Control')+ expect(warnings()).toEqual([])+ expect(exposure()).toBe(LIVE_LINK_EXPOSURE)+ pickRole('can type')+ expect(roleValue()).toBe('can type')const input = pwInput()!+ expect(input.value).toMatch(GENERATED)expect(input.type).toBe('text')expect(input.getAttribute('autocomplete')).toBe('off')expect(input.getAttribute('spellcheck')).toBe('false')expect(input.maxLength).toBe(128)- // Anyone with the link alone still WATCHES a Control link: that warning stays (minus the- // sentence a Control link makes false), and the typing warning comes under it.- expect(warnings()).toEqual([LIVE_LINK_EXPOSURE, controlWarningText('this computer')])- expect(document.querySelectorAll('.live-dialog__warning')[1].querySelector('strong')!.textContent).toBe('and')- expect(btn('Generate')).toBeTruthy()- // Back to Viewer: the watch warning alone again, no password field.- pick('Viewer')+ // Anyone with the link alone still WATCHES a Control link: the exposure stays, the typing+ // warning comes first.+ expect(warnings()).toEqual([controlWarningText('this computer')])+ expect(document.querySelector('.live-dialog__warning strong')!.textContent).toBe('and')+ expect(exposure()).toBe(LIVE_LINK_EXPOSURE)+ const order = [...document.querySelectorAll('.live-dialog__warning, .live-dialog__exposure')].map((e) => e.className)+ expect(order).toEqual(['live-dialog__warning', 'live-dialog__exposure'])+ // Ready to create at once: the generated password passes the rule.+ setLabel('Ada')+ expect(btn('Create live link').disabled).toBe(false)+ // Back to watching: no password row, no typing warning.+ pickRole('can watch')expect(pwInput()).toBeNull()- expect(warnings()).toEqual([LIVE_LINK_WARNING])+ expect(warnings()).toEqual([])})- it('the validation line is tied to the password field (aria-describedby)', async () => {+ it('a password already there is kept when "can type" is picked again', async () => {mount()await flush()- setLabel('Ada')- pick('Control')- expect(pwInput()!.hasAttribute('aria-describedby')).toBe(false)- typeInto(pwInput()!, 'short')- const id = pwInput()!.getAttribute('aria-describedby')!- expect(document.getElementById(id)!.textContent).toBe('Use at least 8 characters.')- expect(document.getElementById(id)!.className).toContain('live-dialog__invalid')+ pickRole('can type')typeInto(pwInput()!, 'longenough1')- expect(pwInput()!.hasAttribute('aria-describedby')).toBe(false)+ pickRole('can chat')+ pickRole('can type')+ expect(pwInput()!.value).toBe('longenough1')})- it('a disabled Control choice is described by its reason', async () => {- api.controlSupport.mockResolvedValue('unsupported')+ it('"New password" replaces it with 16 symbols from crypto.getRandomValues', async () => {mount()await flush()- const id = radio('Control').getAttribute('aria-describedby')!- expect(document.getElementById(id)!.textContent).toBe(CONTROL_UNSUPPORTED_REASON)- expect(radio('Viewer').hasAttribute('aria-describedby')).toBe(false)- })-- it("an SSH project's node: the typing warning names the host its shell runs on", async () => {- mount({ remoteNode: true, sshTarget: { user: 'ada', host: 'build.example' } })- await flush()- pick('Control')- expect(warnings()[1]).toBe(controlWarningText('[email protected]'))- expect(warnings()[1]).toContain('running any command on [email protected];')- expect(warnings()[1]).not.toContain('this computer')+ pickRole('can type')+ typeInto(pwInput()!, 'longenough1')+ const spy = vi.spyOn(crypto, 'getRandomValues')+ click(document.querySelector<HTMLButtonElement>('button[aria-label="New password"]')!)+ expect(spy).toHaveBeenCalled()+ expect(pwInput()!.value).toMatch(GENERATED)+ spy.mockRestore()})- it('Generate fills 16 symbols from crypto.getRandomValues', async () => {- const spy = vi.spyOn(crypto, 'getRandomValues')+ it('the validation line is tied to the password field (aria-describedby)', async () => {mount()await flush()setLabel('Ada')- pick('Control')- expect(btn('Create live link').disabled).toBe(true)- click(btn('Generate'))- expect(spy).toHaveBeenCalled()- expect(pwInput()!.value).toMatch(/^[0-9abcdefghjkmnpqrstvwxyz]{16}$/)- expect(btn('Create live link').disabled).toBe(false)- spy.mockRestore()+ pickRole('can type')+ expect(pwInput()!.hasAttribute('aria-describedby')).toBe(false)+ typeInto(pwInput()!, 'short')+ const id = pwInput()!.getAttribute('aria-describedby')!+ expect(document.getElementById(id)!.textContent).toBe('Use at least 8 characters.')+ expect(document.getElementById(id)!.className).toContain('live-dialog__invalid')+ typeInto(pwInput()!, 'longenough1')+ expect(pwInput()!.hasAttribute('aria-describedby')).toBe(false)})it('Create stays disabled until the password is acceptable, and says why', async () => {mount()await flush()setLabel('Ada')- pick('Control')+ pickRole('can type')const create = (): HTMLButtonElement => btn('Create live link')const problem = (): string | null => document.querySelector('.live-dialog__invalid')?.textContent ?? null- // Empty: disabled, nothing nagging yet.+ // Cleared: disabled, nothing nagging yet.+ typeInto(pwInput()!, '')expect(create().disabled).toBe(true)expect(problem()).toBeNull()typeInto(pwInput()!, 'short')@@ -463,15 +515,24 @@ describe('LiveLinkDialog — Control', () => {expect(problem()).toBeNull()})+ it("an SSH project's node: the typing warning names the host its shell runs on", async () => {+ mount({ remoteNode: true, sshTarget: { user: 'ada', host: 'build.example' } })+ await flush()+ pickRole('can type')+ expect(warnings()).toEqual([controlWarningText('[email protected]')])+ expect(warnings()[0]).toContain('run any command on [email protected],')+ expect(warnings()[0]).not.toContain('this computer')+ })+it('sends the password only for Control', async () => {api.create.mockImplementation(async (r) => createWith(r))mount()await flush()setLabel('Ada')- pick('Control')+ pickRole('can type')typeInto(pwInput()!, 'longenough1')- // A password typed, then the owner switched to Commenter: nothing of it leaves the dialog.- pick('Commenter')+ // A password typed, then the owner switched to "can chat": nothing of it leaves the dialog.+ pickRole('can chat')click(btn('Create live link'))await flush()expect(api.create).toHaveBeenCalledTimes(1)@@ -481,10 +542,11 @@ describe('LiveLinkDialog — Control', () => {act(() => root.unmount())root = createRoot(host)api.create.mockClear()+ localStorage.removeItem(LIVE_LINK_DEFAULTS_KEY)mount()await flush()setLabel('Ada')- pick('Control')+ pickRole('can type')typeInto(pwInput()!, 'longenough1')click(btn('Create live link'))await flush()@@ -498,15 +560,21 @@ describe('LiveLinkDialog — Control', () => {})})- it("Control is disabled, with the reason, when the terminal can't take input — asked once, for this node", async () => {+ it("\"can type\" is shown disabled, with the reason as its hint, when the terminal can't take input — asked once", async () => {api.controlSupport.mockResolvedValue('unsupported')mount()await flush()expect(api.controlSupport).toHaveBeenCalledTimes(1)expect(api.controlSupport).toHaveBeenCalledWith('n1')- expect(radio('Control').disabled).toBe(true)- expect(document.querySelector('.live-dialog__reason')!.textContent).toBe(CONTROL_UNSUPPORTED_REASON)- expect(radio('Viewer').disabled).toBe(false)+ click(trigger('Anyone with the link'))+ const off = option('can type')!+ expect(off.getAttribute('aria-disabled')).toBe('true')+ expect(off.querySelector('.menu-select__hint')!.textContent).toBe(CONTROL_UNSUPPORTED_REASON)+ expect(option('can watch')!.hasAttribute('aria-disabled')).toBe(false)+ // Clicking it changes nothing.+ click(off)+ expect(roleValue()).toBe('can watch')+ expect(pwInput()).toBeNull()})it("'unknown' (and a rejected or missing answer) keeps Control offered: the create decides", async () => {@@ -518,8 +586,9 @@ describe('LiveLinkDialog — Control', () => {else (api as { controlSupport?: unknown }).controlSupport = undefinedmount()await flush()- expect(radio('Control').disabled, answer).toBe(false)- expect(document.querySelector('.live-dialog__reason'), answer).toBeNull()+ click(trigger('Anyone with the link'))+ expect(option('can type')!.hasAttribute('aria-disabled'), answer).toBe(false)+ expect(option('can type')!.querySelector('.menu-select__hint')!.textContent, answer).not.toBe(CONTROL_UNSUPPORTED_REASON)}})@@ -528,12 +597,13 @@ describe('LiveLinkDialog — Control', () => {api.controlSupport.mockImplementation(() => new Promise((r) => (answer = r)))mount()await flush()- pick('Control')+ pickRole('can type')typeInto(pwInput()!, 'longenough1')await act(async () => answer('unsupported'))- expect(radio('Control').checked).toBe(false)- expect(radio('Control').disabled).toBe(true)+ expect(roleValue()).toBe('can watch')expect(pwInput()).toBeNull()+ click(trigger('Anyone with the link'))+ expect(option('can type')!.getAttribute('aria-disabled')).toBe('true')})it('the done step shows the password once, with Copy password and the separate-send note', async () => {@@ -541,9 +611,9 @@ describe('LiveLinkDialog — Control', () => {mount()await flush()setLabel('Ada')- pick('Control')+ pickRole('can type')typeInto(pwInput()!, 'longenough1')- pick('Unlimited')+ choose('Expires', 'never')click(btn('Create live link'))await flush()const field = document.querySelector<HTMLInputElement>('.live-dialog__password input')!@@ -561,14 +631,14 @@ describe('LiveLinkDialog — Control', () => {})// Final review, Minor 6: a stray click beside the done step must not throw away the only copy of a- // Control link's password. The scrim does nothing until Copy password was pressed; Escape and Done- // still close (deliberate gestures).+ // Control link's password. The scrim does nothing until Copy password was pressed; Escape, Done and+ // the head's close button still close (deliberate gestures).it('the done step of a Control link ignores the scrim until Copy password is pressed', async () => {api.create.mockImplementation(async (r) => createWith(r))const { onClose } = mount()await flush()setLabel('Ada')- pick('Control')+ pickRole('can type')typeInto(pwInput()!, 'longenough1')click(btn('Create live link'))await flush()@@ -580,19 +650,32 @@ describe('LiveLinkDialog — Control', () => {expect(onClose).toHaveBeenCalledTimes(1)})- it('the done step of a Control link: Escape still closes before the password was copied', async () => {+ it('the done step of a Control link: Escape and the close button still close before the password was copied', async () => {api.create.mockImplementation(async (r) => createWith(r))const { onClose } = mount()await flush()setLabel('Ada')- pick('Control')- typeInto(pwInput()!, 'longenough1')+ pickRole('can type')click(btn('Create live link'))await flush()escape()expect(onClose).toHaveBeenCalledTimes(1)})+ it('the head close button closes the form, and is disabled while a create is in flight', async () => {+ let release!: (v: string | null) => void+ const { onClose } = mount({ prepare: () => new Promise((r) => (release = r)) })+ await flush()+ setLabel('Ada')+ click(btn('Create live link'))+ const close = document.querySelector<HTMLButtonElement>('.live-dialog__close')!+ expect(close.disabled).toBe(true)+ await act(async () => release('refused'))+ await flush()+ click(document.querySelector<HTMLButtonElement>('.live-dialog__close')!)+ expect(onClose).toHaveBeenCalledTimes(1)+ })+it('the done step of a watch link closes on the scrim as before', async () => {const { onClose } = mount()await flush()@@ -608,7 +691,7 @@ describe('LiveLinkDialog — Control', () => {const { onClose } = mount()await flush()setLabel('Ada')- pick('Control')+ pickRole('can type')typeInto(pwInput()!, 'longenough1')click(btn('Create live link'))await flush()@@ -626,7 +709,7 @@ describe('LiveLinkDialog — Control', () => {it('a form closed before creating drops the typed password too', async () => {const { onClose } = mount()await flush()- pick('Control')+ pickRole('can type')typeInto(pwInput()!, 'longenough1')escape()expect(onClose).toHaveBeenCalledTimes(1)@@ -635,14 +718,12 @@ describe('LiveLinkDialog — Control', () => {})describe('LiveLinkDialog — Unlimited', () => {- it('sends ttlSeconds 0 and says the link works until it is stopped', async () => {+ it('"never" sends ttlSeconds 0', async () => {mount()await flush()setLabel('Ada')- const notes = (): string[] => [...document.querySelectorAll('.live-dialog__note')].map((e) => e.textContent ?? '')- expect(notes()).not.toContain(UNLIMITED_NOTE)- pick('Unlimited')- expect(notes()).toContain(UNLIMITED_NOTE)+ choose('Expires', 'never')+ expect(trigger('Expires').textContent).toBe('never')click(btn('Create live link'))await flush()expect(api.create).toHaveBeenCalledWith(expect.objectContaining({ ttlSeconds: 0 }))@@ -653,7 +734,7 @@ describe('LiveLinkDialog — Unlimited', () => {mount()await flush()setLabel('Ada')- pick('Unlimited')+ choose('Expires', 'never')click(btn('Create live link'))await flush()expect(document.querySelector('.live-dialog__error')!.textContent).toBe(@@ -678,3 +759,58 @@ describe('LiveLinkDialog — Unlimited', () => {expect(html).not.toContain('live-dialog__password')})})++// ---- the remembered role and expiry (lib/liveLinkDefaults) ---------------------------------------++describe('LiveLinkDialog — remembered choices', () => {+ it('the first dialog opens on "can watch" for an hour', async () => {+ mount()+ await flush()+ expect(roleValue()).toBe('can watch')+ expect(trigger('Expires').textContent).toBe('in 1 hour')+ })++ it('a created link remembers its role and expiry; the next dialog opens on them, Control with a fresh password', async () => {+ api.create.mockImplementation(async (r) => createWith(r))+ mount()+ await flush()+ setLabel('Ada')+ pickRole('can type')+ const first = pwInput()!.value+ choose('Expires', 'in 8 hours')+ click(btn('Create live link'))+ await flush()+ expect(JSON.parse(localStorage.getItem(LIVE_LINK_DEFAULTS_KEY)!)).toEqual({ role: 'controller', ttl: 28800 })++ act(() => root.unmount())+ root = createRoot(host)+ mount()+ await flush()+ expect(roleValue()).toBe('can type')+ expect(trigger('Expires').textContent).toBe('in 8 hours')+ // A fresh password, never the last one, and the typing warning is on screen from the start.+ expect(pwInput()!.value).toMatch(GENERATED)+ expect(pwInput()!.value).not.toBe(first)+ expect(warnings()).toEqual([controlWarningText('this computer')])+ })++ it('a refused create remembers nothing', async () => {+ api.create.mockResolvedValue({ ok: false, error: 'not-entitled' })+ mount()+ await flush()+ setLabel('Ada')+ pickRole('can chat')+ click(btn('Create live link'))+ await flush()+ expect(localStorage.getItem(LIVE_LINK_DEFAULTS_KEY)).toBeNull()+ })++ it('a remembered Control on a terminal that cannot take input opens on "can watch"', async () => {+ localStorage.setItem(LIVE_LINK_DEFAULTS_KEY, JSON.stringify({ role: 'controller', ttl: 3600 }))+ api.controlSupport.mockResolvedValue('unsupported')+ mount()+ await flush()+ expect(roleValue()).toBe('can watch')+ expect(pwInput()).toBeNull()+ })+})diff --git a/src/renderer/components/LiveLinkDialog.tsx b/src/renderer/components/LiveLinkDialog.tsxindex 73b17e489..dee1f8f14 100644--- a/src/renderer/components/LiveLinkDialog.tsx+++ b/src/renderer/components/LiveLinkDialog.tsx@@ -1,6 +1,9 @@// Create a live link to one terminal. Opened only through `openLiveLink` (lib/liveLinkEntry): the// availability rule and the Pro gate have already run by the time this mounts.//+// Figma's share-dialog shape: one row per choice, each reading as a sentence ("Anyone with the link+// can watch", "Expires in 1 hour"), the choices in small menus instead of radio lists.+//// The warning is always visible (not a checkbox): the owner must read what a link exposes every// time, because "the screen" includes whatever is printed next.//@@ -13,6 +16,8 @@import { useCallback, useEffect, useId, useRef, useState } from 'react'import { createPortal } from 'react-dom'import { useDialogStack } from './dialog-stack'+import { IconClock, IconClose, IconLock, IconReload, IconUser, IconWeb } from './icons'+import { MenuSelect } from './MenuSelect'import { newControlPassword, PasswordField, useCopied } from './LiveLinkPassword'import {capUnits,@@ -20,28 +25,25 @@ import {controlWarning,controlWarningMachine,createErrorMessage,- DEFAULT_TTL,formatUntil,LIVE_LINK_EXPOSURE,- LIVE_LINK_WARNING,PASSWORD_SEPARATE_NOTE,PASSWORD_SHOWN_ONCE,passwordProblemText,- ROLE_LABEL,- ROLE_NAME,+ ROLE_CHOICE,+ ROLE_ORDER,SAVE_FIRST_MESSAGE,TTL_OPTIONS,- UNLIMITED_NOTE,watchableOnlyWhileOpen,watchWhileOpenNote,type LiveLinkSurface} from '../lib/liveLink'+import { loadLiveLinkDefaults, saveLiveLinkDefaults } from '../lib/liveLinkDefaults'import { stopLiveLinks } from '../lib/liveLinkEntry'import { loadIdentity } from '../state/presence'import {LABEL_MAX,stripBidiControls,- UNLIMITED_TTL,type CreateWatchLinkRequest,type WatchLinkRole,type WatchLinkTtl@@ -59,6 +61,20 @@ function ControlWarning({ machine }: { machine: string }): React.JSX.Element {)}+/** The dialog's head: the node's title and a close button (which every dismissal rule still owns). */+function DialogHead(p: { title: string; onClose: () => void; disabled?: boolean }): React.JSX.Element {+ return (+ <div className="live-dialog__head">+ <p className="live-dialog__title" title={p.title}>+ Share “{p.title}”+ </p>+ <button type="button" className="live-dialog__close" aria-label="Close" disabled={p.disabled} onClick={p.onClose}>+ <IconClose />+ </button>+ </div>+ )+}+export type DialogState =| {phase: 'form'@@ -116,16 +132,22 @@ export function LiveLinkDialogBody(p: {now?: number}): React.JSX.Element {const s = p.state- // Ids for aria-describedby: the password's validation line, and why Control is disabled.+ // The id for aria-describedby: the password's validation line.const invalidId = useId()- const reasonId = useId()// The title is the node's own (git-shared, hand-editable): shown as TEXT, bidi controls stripped.const title = stripBidiControls(p.title)if (s.phase === 'done') {const control = s.role === 'controller'+ const until = formatUntil(s.expiresAt, p.now ?? Date.now())return (<div className="confirm live-dialog" onClick={(e) => e.stopPropagation()}>- <p className="confirm__msg live-dialog__title">Live link to {title}</p>+ <DialogHead title={title} onClose={p.onClose} disabled={!!s.stopping} />+ <p className="live-dialog__status">+ <span className="live-dialog__dot" aria-hidden="true" />+ {control+ ? `Anyone with this link and the password can type until ${until}.`+ : `Anyone with this link can watch until ${until}.`}+ </p><div className="live-dialog__url"><inputclassName="confirm__input"@@ -135,34 +157,30 @@ export function LiveLinkDialogBody(p: {onFocus={(e) => e.currentTarget.select()}/>{/* Keyboard focus lands here once the link exists (D2/M3): Enter copies it. */}- <button className="confirm__btn primary" data-autofocus="" onClick={() => p.onCopy?.(s.url)}>- {p.copied ? 'Copied!' : 'Copy'}+ <button className="confirm__btn primary live-dialog__copy" data-autofocus="" onClick={() => p.onCopy?.(s.url)}>+ {p.copied ? 'Copied!' : 'Copy link'}</button></div>{control && (<><div className="live-dialog__url live-dialog__password"><PasswordField value={s.password ?? ''} readOnly />- <button className="confirm__btn" onClick={() => p.onCopyPassword?.(s.password ?? '')}>+ <button className="confirm__btn live-dialog__copy" onClick={() => p.onCopyPassword?.(s.password ?? '')}>{p.passwordCopied ? 'Copied!' : 'Copy password'}</button></div>- <p className="live-dialog__note live-dialog__note--tight">{PASSWORD_SHOWN_ONCE}</p>- <p className="live-dialog__note live-dialog__note--tight">{PASSWORD_SEPARATE_NOTE}</p>+ <p className="live-dialog__note">+ {PASSWORD_SHOWN_ONCE} {PASSWORD_SEPARATE_NOTE}+ </p></>)}- <p className="live-dialog__note">- {control- ? `Anyone with this link and the password can type until ${formatUntil(s.expiresAt, p.now ?? Date.now())}.`- : `Anyone with this link can watch until ${formatUntil(s.expiresAt, p.now ?? Date.now())}.`}- </p>{s.error && (<p className="live-dialog__error" role="alert">{s.error}</p>)}- <div className="confirm__actions">- <button className="confirm__btn danger" disabled={!!s.stopping} onClick={() => p.onStop(s.linkId)}>+ <div className="confirm__actions live-dialog__actions">+ <button className="confirm__btn live-dialog__stop" disabled={!!s.stopping} onClick={() => p.onStop(s.linkId)}>Stop sharing</button><button className="confirm__btn" onClick={p.onClose}>@@ -176,81 +194,94 @@ export function LiveLinkDialogBody(p: {const problem = control ? passwordProblemText(s.password) : null// Nothing nags an empty field: Create is disabled, which says enough until something is typed.const showProblem = s.password !== '' && problem !== null+ const roleOptions = ROLE_ORDER.map((r) => {+ const off = r === 'controller' && !!p.controlUnsupported+ return { value: r, label: ROLE_CHOICE[r].label, hint: off ? CONTROL_UNSUPPORTED_REASON : ROLE_CHOICE[r].hint, disabled: off }+ })+ // Picking Control fills a generated password when there is none yet, so the fast path is two+ // clicks; a password already there (typed, or kept from switching away and back) is left alone.+ const setRole = (role: WatchLinkRole): void =>+ p.onChange({ ...s, role, password: role === 'controller' && s.password === '' ? newControlPassword() : s.password })return (<div className="confirm live-dialog" onClick={(e) => e.stopPropagation()}>- <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', 'controller'] as const).map((r) => {- const off = r === 'controller' && !!p.controlUnsupported- return (- <label key={r} className={off ? 'live-dialog__off' : undefined} title={off ? CONTROL_UNSUPPORTED_REASON : undefined}>- <input- type="radio"- name="live-role"- checked={s.role === r}- disabled={off}- aria-describedby={off ? reasonId : undefined}- onChange={() => p.onChange({ ...s, role: r })}- />{' '}- {ROLE_NAME[r]} <span className="live-dialog__hint">· {ROLE_LABEL[r]}</span>- </label>- )- })}- {p.controlUnsupported && (- <p className="live-dialog__reason" id={reasonId}>- {CONTROL_UNSUPPORTED_REASON}- </p>- )}- </fieldset>- {control && (- <div className="live-dialog__pw">- Password- <div className="live-dialog__url live-dialog__password">+ <DialogHead title={title} onClose={p.onClose} disabled={s.busy} />+ <div className="live-dialog__rows">+ <div className="live-dialog__row">+ <span className="live-dialog__icon" aria-hidden="true">+ <IconWeb />+ </span>+ <span className="live-dialog__row-label">Anyone with the link</span>+ {/* Keyboard focus lands here when the dialog opens (D2/M3): keys stay inside the dialog+ instead of reaching the canvas behind it. */}+ <MenuSelect+ label="Anyone with the link"+ value={s.role}+ options={roleOptions}+ onChange={setRole}+ disabled={s.busy}+ autoFocus+ />+ </div>+ {control && (+ <div className="live-dialog__row live-dialog__password">+ <span className="live-dialog__icon" aria-hidden="true">+ <IconLock />+ </span>+ <span className="live-dialog__row-label">Password</span><PasswordFieldvalue={s.password}disabled={s.busy}describedBy={showProblem ? invalidId : undefined}onChange={(v) => p.onChange({ ...s, password: v })}/>- <button className="confirm__btn" disabled={s.busy} onClick={() => p.onChange({ ...s, password: newControlPassword() })}>- Generate+ <button+ type="button"+ className="live-dialog__icon-btn"+ aria-label="New password"+ title="Generate a new password"+ disabled={s.busy}+ onClick={() => p.onChange({ ...s, password: newControlPassword() })}+ >+ <IconReload /></button></div>- {showProblem && (- <p className="live-dialog__invalid" id={invalidId}>- {problem}- </p>- )}+ )}+ {showProblem && (+ <p className="live-dialog__invalid" id={invalidId}>+ {problem}+ </p>+ )}+ <div className="live-dialog__row">+ <span className="live-dialog__icon" aria-hidden="true">+ <IconClock />+ </span>+ <span className="live-dialog__row-label">Expires</span>+ <MenuSelect+ label="Expires"+ value={s.ttl}+ options={TTL_OPTIONS}+ onChange={(ttl: WatchLinkTtl) => p.onChange({ ...s, ttl })}+ disabled={s.busy}+ /></div>- )}- <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>- {s.ttl === UNLIMITED_TTL && <p className="live-dialog__note live-dialog__note--tight">{UNLIMITED_NOTE}</p>}- <label className="live-dialog__label">- Shown to viewers as- {/* Keyboard focus lands here when the dialog opens (D2/M3): keys stay inside the dialog- instead of reaching the canvas behind it. */}- <input- className="confirm__input"- data-autofocus=""- maxLength={LABEL_MAX}- value={s.label}- disabled={s.busy}- onChange={(e) => p.onChange({ ...s, label: e.target.value })}- />- </label>- {/* Always what WATCHING exposes. A Control link is watched by anyone with the link alone, so- its warning keeps that (minus "They can't type", which it makes false) and adds typing. */}- <p className="live-dialog__warning">{control ? LIVE_LINK_EXPOSURE : LIVE_LINK_WARNING}</p>+ <label className="live-dialog__row live-dialog__label">+ <span className="live-dialog__icon" aria-hidden="true">+ <IconUser />+ </span>+ <span className="live-dialog__row-label">Viewers see you as</span>+ <input+ className="confirm__input"+ maxLength={LABEL_MAX}+ value={s.label}+ disabled={s.busy}+ onChange={(e) => p.onChange({ ...s, label: e.target.value })}+ />+ </label>+ </div>+ {/* Typing first (the stronger claim), then what WATCHING exposes, which holds for every role:+ a Control link is watched by anyone with the link alone. */}{control && <ControlWarning machine={p.controlMachine ?? controlWarningMachine(null)} />}+ <p className="live-dialog__exposure">{LIVE_LINK_EXPOSURE}</p>{p.whileOpenNote && <p className="live-dialog__note">{p.whileOpenNote}</p>}{s.error && (<p className="live-dialog__error" role="alert">@@ -308,15 +339,20 @@ export function LiveLinkDialog({onUpgrade?: () => voidonClose: () => void}): React.JSX.Element {- const [state, setState] = useState<DialogState>(() => ({- phase: 'form',- role: 'viewer',- ttl: DEFAULT_TTL,- label: capUnits(loadIdentity()?.name ?? '', LABEL_MAX),- password: '',- busy: false,- error: null- }))+ // Opens on the role and expiry of the last link this person created (lib/liveLinkDefaults). A+ // remembered Control opens with a fresh generated password, as picking it does.+ const [state, setState] = useState<DialogState>(() => {+ const d = loadLiveLinkDefaults()+ return {+ phase: 'form',+ role: d.role,+ ttl: d.ttl,+ label: capUnits(loadIdentity()?.name ?? '', LABEL_MAX),+ password: d.role === 'controller' ? newControlPassword() : '',+ busy: false,+ error: null+ }+ })// The latest state for the async steps (a closure would see the render that started them).const stateRef = useRef(state)stateRef.current = state@@ -362,7 +398,7 @@ export function LiveLinkDialog({live = false}}, [nodeId])- // D2/M3: focus lands in the dialog — the label on open, Copy once created — so keys stay inside+ // D2/M3: focus lands in the dialog — the role menu on open, Copy link once created — so keys stay inside// it (a bare-key canvas command could otherwise fire behind the overlay).const panelRef = useRef<HTMLDivElement>(null)useEffect(() => {@@ -434,6 +470,7 @@ export function LiveLinkDialog({try {const r = await window.nodeTerminal.watchLink.create(req)if (r.ok) {+ saveLiveLinkDefaults({ role: form.role, ttl: form.ttl })setState({phase: 'done',role: form.role,diff --git a/src/renderer/components/MenuSelect.test.tsx b/src/renderer/components/MenuSelect.test.tsxnew file mode 100644index 000000000..0d815c75d--- /dev/null+++ b/src/renderer/components/MenuSelect.test.tsx@@ -0,0 +1,151 @@+// @vitest-environment jsdom+import { act, useState } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { MenuSelect, nextEnabled, type MenuSelectOption } from './MenuSelect'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const OPTIONS: MenuSelectOption<string>[] = [+ { value: 'a', label: 'Alpha', hint: 'first' },+ { value: 'b', label: 'Beta', disabled: true, hint: 'not here' },+ { value: 'c', label: 'Gamma' }+]++let host: HTMLDivElement+let root: Root+let onChange: ReturnType<typeof vi.fn<(v: string) => void>>+beforeEach(() => {+ host = document.createElement('div')+ document.body.append(host)+ root = createRoot(host)+ onChange = vi.fn()+})+afterEach(() => {+ act(() => root.unmount())+ document.body.innerHTML = ''+})++function Harness(p: { disabled?: boolean }): React.JSX.Element {+ const [value, setValue] = useState('a')+ return (+ <MenuSelect+ label="Pick"+ value={value}+ options={OPTIONS}+ disabled={p.disabled}+ onChange={(v) => {+ onChange(v)+ setValue(v)+ }}+ />+ )+}+const mount = (disabled = false): void => act(() => root.render(<Harness disabled={disabled} />))+const triggerEl = (): HTMLButtonElement => document.querySelector<HTMLButtonElement>('.menu-select__trigger')!+const menu = (): HTMLElement | null => document.querySelector('.menu-select__menu')+const key = (el: Element, k: string): void =>+ act(() => void el.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true })))+const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))+const focusedLabel = (): string | null | undefined =>+ (document.activeElement as HTMLElement | null)?.querySelector('.menu-select__label')?.textContent++describe('nextEnabled', () => {+ it('skips disabled options and wraps both ways', () => {+ expect(nextEnabled(OPTIONS, 0, 1)).toBe(2)+ expect(nextEnabled(OPTIONS, 2, 1)).toBe(0)+ expect(nextEnabled(OPTIONS, 0, -1)).toBe(2)+ expect(nextEnabled(OPTIONS, -1, 1)).toBe(0)+ })+ it('stays put when nothing else can be picked', () => {+ expect(nextEnabled([{ value: 1, label: 'x' }], 0, 1)).toBe(0)+ })+})++describe('MenuSelect', () => {+ it('shows the current choice, and names the row and the choice to a screen reader', () => {+ mount()+ expect(triggerEl().textContent).toBe('Alpha')+ expect(triggerEl().getAttribute('aria-label')).toBe('Pick: Alpha')+ expect(triggerEl().getAttribute('aria-expanded')).toBe('false')+ expect(menu()).toBeNull()+ })++ it('a click opens it on the current choice; picking one closes it and gives focus back', () => {+ mount()+ click(triggerEl())+ expect(triggerEl().getAttribute('aria-expanded')).toBe('true')+ expect(focusedLabel()).toBe('Alpha')+ const gamma = [...document.querySelectorAll('.menu-select__item')][2]+ click(gamma)+ expect(onChange).toHaveBeenCalledWith('c')+ expect(menu()).toBeNull()+ expect(document.activeElement).toBe(triggerEl())+ expect(triggerEl().textContent).toBe('Gamma')+ })++ it('the arrows move over the options that can be picked; a disabled one is never focused or picked', () => {+ mount()+ key(triggerEl(), 'ArrowDown')+ expect(menu()).not.toBeNull()+ expect(focusedLabel()).toBe('Alpha')+ key(document.activeElement!, 'ArrowDown')+ expect(focusedLabel()).toBe('Gamma')+ key(document.activeElement!, 'ArrowDown')+ expect(focusedLabel()).toBe('Alpha')+ key(document.activeElement!, 'End')+ expect(focusedLabel()).toBe('Gamma')+ key(document.activeElement!, 'Home')+ expect(focusedLabel()).toBe('Alpha')+ click([...document.querySelectorAll('.menu-select__item')][1])+ expect(onChange).not.toHaveBeenCalled()+ expect(menu()).not.toBeNull()+ })++ it('Escape and Tab close it and give focus back; Escape does not reach the window', () => {+ const onWindowKey = vi.fn()+ window.addEventListener('keydown', onWindowKey)+ try {+ mount()+ click(triggerEl())+ key(document.activeElement!, 'Escape')+ expect(menu()).toBeNull()+ expect(document.activeElement).toBe(triggerEl())+ expect(onWindowKey).not.toHaveBeenCalled()+ click(triggerEl())+ key(document.activeElement!, 'Tab')+ expect(menu()).toBeNull()+ expect(document.activeElement).toBe(triggerEl())+ } finally {+ window.removeEventListener('keydown', onWindowKey)+ }+ })++ it('a press outside closes it without picking', () => {+ mount()+ click(triggerEl())+ act(() => void document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })))+ expect(menu()).toBeNull()+ expect(onChange).not.toHaveBeenCalled()+ })++ it('a disabled select does not open, and one disabled while open closes', () => {+ mount(true)+ expect(triggerEl().disabled).toBe(true)+ key(triggerEl(), 'ArrowDown')+ expect(menu()).toBeNull()+ mount(false)+ click(triggerEl())+ expect(menu()).not.toBeNull()+ mount(true)+ expect(menu()).toBeNull()+ })++ it('a disabled option keeps its hint readable (the reason it cannot be picked)', () => {+ mount()+ click(triggerEl())+ const beta = [...document.querySelectorAll('.menu-select__item')][1]+ expect(beta.getAttribute('aria-disabled')).toBe('true')+ expect(beta.querySelector('.menu-select__hint')!.textContent).toBe('not here')+ })+})diff --git a/src/renderer/components/MenuSelect.tsx b/src/renderer/components/MenuSelect.tsxnew file mode 100644index 000000000..c09e96746--- /dev/null+++ b/src/renderer/components/MenuSelect.tsx@@ -0,0 +1,171 @@+// A compact dropdown for a dialog row ("Anyone with the link · can watch ▾"): a button that shows the+// current choice and opens a small menu of options, each with an optional one-line hint. It renders+// INSIDE its row (absolutely positioned below the trigger), never in a portal: a dialog under Liquid+// Glass is a backdrop root, and a menu portaled out of it would sit on top of the scrim instead.+//+// Keyboard: ArrowDown / ArrowUp on the trigger open the menu; in the menu, the arrows, Home and End+// move between the options that can be picked, Enter / Space pick, Escape and Tab close it and give+// focus back to the trigger. Escape is stopped here so it closes the menu and not the dialog.+import { useEffect, useRef, useState, type KeyboardEvent } from 'react'+import { IconCheck, IconChevronDown } from './icons'++export interface MenuSelectOption<T> {+ value: T+ label: string+ /** One muted line under the label: what the choice means, or why it is disabled. */+ hint?: string+ /** Shown, readable, never pickable. */+ disabled?: boolean+}++/** The next option that can be picked from `from` in `dir`, wrapping; `from` itself when none. */+export function nextEnabled<T>(options: readonly MenuSelectOption<T>[], from: number, dir: 1 | -1): number {+ const n = options.length+ for (let step = 1; step <= n; step++) {+ const i = (((from + dir * step) % n) + n) % n+ if (!options[i].disabled) return i+ }+ return from+}++export function MenuSelect<T extends string | number>(p: {+ /** The accessible name: what is being chosen ("Who can use the link"). */+ label: string+ value: T+ options: readonly MenuSelectOption<T>[]+ onChange: (value: T) => void+ disabled?: boolean+ /** Marks the trigger as the dialog's first focus (`data-autofocus`). */+ autoFocus?: boolean+ className?: string+}): React.JSX.Element {+ const [open, setOpen] = useState(false)+ const [active, setActive] = useState(0)+ const rootRef = useRef<HTMLDivElement>(null)+ const triggerRef = useRef<HTMLButtonElement>(null)+ const itemRefs = useRef<(HTMLButtonElement | null)[]>([])+ const current = p.options.find((o) => o.value === p.value)++ const openMenu = (): void => {+ if (p.disabled) return+ const at = p.options.findIndex((o) => o.value === p.value && !o.disabled)+ setActive(at >= 0 ? at : nextEnabled(p.options, -1, 1))+ setOpen(true)+ }+ const close = (refocus: boolean): void => {+ setOpen(false)+ if (refocus) triggerRef.current?.focus()+ }+ const pick = (o: MenuSelectOption<T>): void => {+ if (o.disabled) return+ if (o.value !== p.value) p.onChange(o.value)+ close(true)+ }++ // The highlighted option holds focus, so a screen reader follows the arrows.+ useEffect(() => {+ if (open) itemRefs.current[active]?.focus()+ }, [open, active])+ // A press anywhere outside the menu and its trigger closes it.+ useEffect(() => {+ if (!open) return+ const onDown = (e: MouseEvent): void => {+ if (!rootRef.current?.contains(e.target as Node)) setOpen(false)+ }+ document.addEventListener('mousedown', onDown, true)+ return () => document.removeEventListener('mousedown', onDown, true)+ }, [open])+ // Disabled while open (the dialog went busy): nothing may be picked any more.+ useEffect(() => {+ if (p.disabled) setOpen(false)+ }, [p.disabled])++ const onTriggerKey = (e: KeyboardEvent<HTMLButtonElement>): void => {+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {+ e.preventDefault()+ openMenu()+ }+ }+ const onMenuKey = (e: KeyboardEvent<HTMLDivElement>): void => {+ const last = p.options.length - 1+ switch (e.key) {+ case 'ArrowDown':+ e.preventDefault()+ setActive((i) => nextEnabled(p.options, i, 1))+ break+ case 'ArrowUp':+ e.preventDefault()+ setActive((i) => nextEnabled(p.options, i, -1))+ break+ case 'Home':+ e.preventDefault()+ setActive(nextEnabled(p.options, last, 1))+ break+ case 'End':+ e.preventDefault()+ setActive(nextEnabled(p.options, 0, -1))+ break+ case 'Escape':+ // The menu's Escape, not the dialog's: the dialog listens on the window, which this never reaches.+ e.preventDefault()+ e.stopPropagation()+ close(true)+ break+ case 'Tab':+ e.preventDefault()+ close(true)+ break+ }+ }++ return (+ <div className={`menu-select${p.className ? ` ${p.className}` : ''}`} ref={rootRef}>+ <button+ type="button"+ ref={triggerRef}+ className="menu-select__trigger"+ aria-haspopup="menu"+ aria-expanded={open}+ aria-label={`${p.label}: ${current?.label ?? ''}`}+ disabled={p.disabled}+ data-autofocus={p.autoFocus ? '' : undefined}+ onClick={() => (open ? close(false) : openMenu())}+ onKeyDown={onTriggerKey}+ >+ <span className="menu-select__value">{current?.label ?? ''}</span>+ <IconChevronDown />+ </button>+ {open && (+ <div className="menu-select__menu" role="menu" aria-label={p.label} onKeyDown={onMenuKey}>+ {p.options.map((o, i) => {+ const selected = o.value === p.value+ return (+ <button+ key={String(o.value)}+ type="button"+ ref={(el) => {+ itemRefs.current[i] = el+ }}+ role="menuitemradio"+ aria-checked={selected}+ aria-disabled={o.disabled || undefined}+ tabIndex={i === active ? 0 : -1}+ className={`menu-select__item${i === active ? ' active' : ''}${o.disabled ? ' disabled' : ''}`}+ onMouseEnter={() => {+ if (!o.disabled) setActive(i)+ }}+ onClick={() => pick(o)}+ >+ <span className="menu-select__check">{selected && <IconCheck />}</span>+ <span className="menu-select__text">+ <span className="menu-select__label">{o.label}</span>+ {o.hint && <span className="menu-select__hint">{o.hint}</span>}+ </span>+ </button>+ )+ })}+ </div>+ )}+ </div>+ )+}diff --git a/src/renderer/components/icons.tsx b/src/renderer/components/icons.tsxindex 3a298a001..4cffd4456 100644--- a/src/renderer/components/icons.tsx+++ b/src/renderer/components/icons.tsx@@ -340,6 +340,22 @@ export const IconCircleCheck = () => (/* Stroked padlocks: the canvas lock moved out of the React Flow controls (whose filled 12pxglyph set is why these used to be filled) into the dock, where every icon is an outline. */+/** A clock face — when something ends (the live-link dialog's "Expires" row). */+export const IconClock = () => (+ <svg {...S}>+ <circle cx="12" cy="12" r="9" />+ <path d="M12 7v5l3 2" />+ </svg>+)++/** One person — who someone is shown as (the live-link dialog's name row). */+export const IconUser = () => (+ <svg {...S}>+ <circle cx="12" cy="8" r="4" />+ <path d="M4.5 20a7.5 7.5 0 0 1 15 0" />+ </svg>+)+export const IconLock = () => (<svg {...S}><rect x="4.5" y="10.5" width="15" height="10.5" rx="2.5" />diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.tsindex 149122c56..550043ee1 100644--- a/src/renderer/lib/liveLink.test.ts+++ b/src/renderer/lib/liveLink.test.ts@@ -7,7 +7,6 @@ import {CHAT_NOT_SENT_MESSAGE,chipView,formatUntil,- LIVE_LINK_WARNING,watchableOnlyWhileOpen,commentFromChat,createErrorMessage,@@ -41,7 +40,9 @@ import {PASSWORD_SEPARATE_NOTE,PASSWORD_SHOWN_ONCE,passwordProblemText,+ ROLE_CHOICE,ROLE_NAME,+ ROLE_ORDER,typingNames,UNLIMITED_NOTE,CONTROL_CHANGE_UNSAVED_MESSAGE,@@ -290,10 +291,20 @@ describe('fixed lists (H19)', () => {expect(TTL_OPTIONS.map((o) => o.value)).toEqual([...WATCH_LINK_TTLS])// Unlimited is offered, last.expect(TTL_OPTIONS.map((o) => o.value)).toEqual([900, 3600, 28800, 86400, 0])- expect(TTL_OPTIONS.map((o) => o.label)).toEqual(['15 min', '1 hour', '8 hours', '24 hours', 'Unlimited'])+ // Lowercase: the dialog's row reads "Expires in 1 hour" / "Expires never".+ expect(TTL_OPTIONS.map((o) => o.label)).toEqual(['in 15 minutes', 'in 1 hour', 'in 8 hours', 'in 24 hours', 'never'])+ // Only "never" carries a hint, and it is the Unlimited note.+ expect(TTL_OPTIONS.map((o) => o.hint)).toEqual([undefined, undefined, undefined, undefined, UNLIMITED_NOTE])expect(DEFAULT_TTL).toBe(DEFAULT_WATCH_LINK_TTL)expect(ROLE_LABEL).toEqual({ viewer: 'Can watch', commenter: 'Can watch and chat', controller: 'Can watch, chat and type' })expect(ROLE_NAME).toEqual({ viewer: 'Viewer', commenter: 'Commenter', controller: 'Control' })+ // The create dialog's menu: the verb the link grants, in the spec's order; Control names its password.+ expect(ROLE_ORDER).toEqual(['viewer', 'commenter', 'controller'])+ expect(ROLE_CHOICE).toEqual({+ viewer: { label: 'can watch', hint: 'Sees the terminal' },+ commenter: { label: 'can chat', hint: 'Watches and chats with you' },+ controller: { label: 'can type', hint: 'Also types, with a password' }+ })})})@@ -379,8 +390,11 @@ describe('watchableOnlyWhileOpen', () => {// R64/M3: the stream follows the terminal CLIENT, so tmux's chooser and a session switch reach viewers.describe('the create warning', () => {it("names tmux's session chooser and a session switch", () => {- expect(LIVE_LINK_WARNING).toMatch(/session chooser/)- expect(LIVE_LINK_WARNING).toMatch(/switch sessions/)+ expect(LIVE_LINK_EXPOSURE).toMatch(/session chooser/)+ expect(LIVE_LINK_EXPOSURE).toMatch(/switch sessions/)+ // What every viewer gets, said in the one sentence the dialog keeps for it.+ expect(LIVE_LINK_EXPOSURE).toMatch(/scrollback/)+ expect(LIVE_LINK_EXPOSURE).toMatch(/anything printed later/)})})@@ -390,18 +404,16 @@ describe('Control and Unlimited copy', () => {it('is the exact ruled text', () => {// Spec §2.7, with the machine named truthfully (ruling 2): this machine's noun for a local node…expect(controlWarningText(controlWarningMachine(null))).toBe(- 'Anyone with this link and the password can type in this terminal as you. In a shell that means running any command on this computer; in an agent session, giving the agent any instruction. Send the password separately from the link.'+ 'With this link and the password, anyone can type here as you: run any command on this computer, or instruct the agent in this terminal.')// …and the host for an SSH project's node, whose shell runs there.expect(controlWarningText(controlWarningMachine({ user: 'ada', host: 'build.example' }))).toBe(- 'Anyone with this link and the password can type in this terminal as you. In a shell that means running any command on [email protected]; in an agent session, giving the agent any instruction. Send the password separately from the link.'+ 'With this link and the password, anyone can type here as you: run any command on [email protected], or instruct the agent in this terminal.')// "and" is the emphasised word: the parts say where it is.expect(controlWarning('x')[1]).toBe('and')expect(controlWarning('x').join('')).toBe(controlWarningText('x'))- // A Control link still shows what WATCHING exposes — without the sentence a Control link makes false.- expect(LIVE_LINK_WARNING.startsWith(LIVE_LINK_EXPOSURE)).toBe(true)- expect(LIVE_LINK_WARNING).toBe(`${LIVE_LINK_EXPOSURE} They can't type or resize it.`)+ // The exposure sentence is shown for every role, Control included, so it must not claim nobody types.expect(LIVE_LINK_EXPOSURE).not.toMatch(/type/)expect(PASSWORD_SEPARATE_NOTE).toBe('Send the password separately from the link.')expect(PASSWORD_SHOWN_ONCE).toBe(diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.tsindex 1991d1455..bb66edb01 100644--- a/src/renderer/lib/liveLink.ts+++ b/src/renderer/lib/liveLink.ts@@ -30,38 +30,51 @@ export const ROLE_LABEL: Record<WatchLinkRole, string> = {commenter: 'Can watch and chat',controller: 'Can watch, chat and type'}-/** The role's name, as the create dialog's choice and the popover's role line say it (spec §2.1). */+/** The role's name, as the popover's role line and the chat drawer say it (spec §2.1). */export const ROLE_NAME: Record<WatchLinkRole, string> = {viewer: 'Viewer',commenter: 'Commenter',controller: 'Control'}-/** A `Record` over the shared TTL list, so a TTL added there fails to compile here until it is named. */+/** The create dialog's role menu, Figma's "can view ▾" shape: the row reads as a sentence ("Anyone+ * with the link can watch"), and the hint says what the choice grants. Control's hint names the+ * password, because picking it adds the password row. */+export const ROLE_CHOICE: Record<WatchLinkRole, { label: string; hint: string }> = {+ viewer: { label: 'can watch', hint: 'Sees the terminal' },+ commenter: { label: 'can chat', hint: 'Watches and chats with you' },+ controller: { label: 'can type', hint: 'Also types, with a password' }+}+/** The roles in the menu's order (spec §2.1: viewer, commenter, controller). */+export const ROLE_ORDER: readonly WatchLinkRole[] = ['viewer', 'commenter', 'controller']++/** A `Record` over the shared TTL list, so a TTL added there fails to compile here until it is named.+ * Lowercase: the row reads "Expires in 1 hour". */const TTL_LABEL: Record<WatchLinkTtl, string> = {- 900: '15 min',- 3600: '1 hour',- 28800: '8 hours',- 86400: '24 hours',- 0: 'Unlimited'+ 900: 'in 15 minutes',+ 3600: 'in 1 hour',+ 28800: 'in 8 hours',+ 86400: 'in 24 hours',+ 0: 'never'}+/** Unlimited's hint in the expiry menu. */+export const UNLIMITED_NOTE = 'This link works until you stop it.'/** The create dialog's expiry choices — derived from the list core validates against (H19), so- * Unlimited (`0`) comes last, as the shared list orders it. */-export const TTL_OPTIONS: { value: WatchLinkTtl; label: string }[] = WATCH_LINK_TTLS.map((value) => ({+ * Unlimited (`0`, "never") comes last, as the shared list orders it. */+export const TTL_OPTIONS: { value: WatchLinkTtl; label: string; hint?: string }[] = WATCH_LINK_TTLS.map((value) => ({value,- label: TTL_LABEL[value]+ label: TTL_LABEL[value],+ ...(value === 0 ? { hint: UNLIMITED_NOTE } : {})}))export const DEFAULT_TTL: WatchLinkTtl = DEFAULT_WATCH_LINK_TTL-/** Under the expiry choices while Unlimited is picked. */-export const UNLIMITED_NOTE = 'This link works until you stop it.'-/** Always on the create dialog. "Everything this terminal shows" is meant literally (R64/M3): the- * stream is the terminal CLIENT's output, so tmux's session chooser (`C-b s` / `C-b w`, a live- * preview of every session — other projects' agents included) or a session switch inside it reaches- * viewers as well. */+/** Always on the create dialog, whatever the role. "Everything this terminal shows" is meant+ * literally (R64/M3): the stream is the terminal CLIENT's output, so tmux's session chooser+ * (`C-b s` / `C-b w`, a live preview of every session — other projects' agents included) or a+ * session switch inside it reaches viewers as well. Short on purpose: the dialog is a row of+ * choices, and a paragraph here buried the choices; the facts it must carry are all still in it. */export const LIVE_LINK_EXPOSURE =- "Anyone with the link sees everything this terminal shows: what's on screen now, anything printed later (tokens, env dumps), anything you scroll back to — and, if you open tmux's session chooser or switch sessions in it, those other sessions too."-export const LIVE_LINK_WARNING = `${LIVE_LINK_EXPOSURE} They can't type or resize it.`+ 'Viewers see everything this terminal shows: scrollback, anything printed later (tokens too), and other tmux sessions if you open the session chooser or switch sessions.'export const KICK_NOTE ='Kick ends this connection; anyone with the link can rejoin. Stop sharing to end it for everyone.'/** After `KICK_NOTE` for a viewer who is controlling: a kicked controller who has the password unlocks@@ -74,15 +87,15 @@ export function kickNote(v: { controlling: boolean }): string {/*** The create dialog's typing warning while Control is picked — spec §2.7, with the machine named- * truthfully. It is shown UNDER `LIVE_LINK_EXPOSURE`, never instead of it: a Control link is a+ * truthfully. It is shown ABOVE `LIVE_LINK_EXPOSURE`, never instead of it: a Control link is a* Commenter link plus typing, so anyone with the link alone still watches. Three parts so the* dialog can stress the middle one ("and"); `controlWarningText` is the same words as one string.*/export function controlWarning(machine: string): [string, string, string] {return [- 'Anyone with this link ',+ 'With this link ','and',- ` the password can type in this terminal as you. In a shell that means running any command on ${machine}; in an agent session, giving the agent any instruction. Send the password separately from the link.`+ ` the password, anyone can type here as you: run any command on ${machine}, or instruct the agent in this terminal.`]}export function controlWarningText(machine: string): string {diff --git a/src/renderer/lib/liveLinkDefaults.test.ts b/src/renderer/lib/liveLinkDefaults.test.tsnew file mode 100644index 000000000..ac214e4d3--- /dev/null+++ b/src/renderer/lib/liveLinkDefaults.test.ts@@ -0,0 +1,43 @@+import { describe, expect, it } from 'vitest'+import {+ FIRST_LIVE_LINK_DEFAULTS,+ LIVE_LINK_DEFAULTS_KEY,+ loadLiveLinkDefaults,+ parseLiveLinkDefaults,+ saveLiveLinkDefaults+} from './liveLinkDefaults'++describe('liveLinkDefaults', () => {+ it('a first dialog opens on "can watch" for an hour', () => {+ expect(FIRST_LIVE_LINK_DEFAULTS).toEqual({ role: 'viewer', ttl: 3600 })+ expect(parseLiveLinkDefaults(null)).toEqual(FIRST_LIVE_LINK_DEFAULTS)+ })++ it('round-trips what was saved, under its own key, and nothing else', () => {+ const store = new Map<string, string>()+ saveLiveLinkDefaults({ role: 'controller', ttl: 0 }, (k, v) => store.set(k, v))+ expect([...store.keys()]).toEqual([LIVE_LINK_DEFAULTS_KEY])+ expect(JSON.parse(store.get(LIVE_LINK_DEFAULTS_KEY)!)).toEqual({ role: 'controller', ttl: 0 })+ expect(loadLiveLinkDefaults((k) => store.get(k) ?? null)).toEqual({ role: 'controller', ttl: 0 })+ })++ it('reads each field on its own: an unknown value falls back without costing the other', () => {+ expect(parseLiveLinkDefaults('{"role":"admin","ttl":28800}')).toEqual({ role: 'viewer', ttl: 28800 })+ expect(parseLiveLinkDefaults('{"role":"commenter","ttl":7200}')).toEqual({ role: 'commenter', ttl: 3600 })+ expect(parseLiveLinkDefaults('{"role":"controller","ttl":"0"}')).toEqual({ role: 'controller', ttl: 3600 })+ for (const raw of ['not json', '[]', 'null', '42', '"controller"']) expect(parseLiveLinkDefaults(raw)).toEqual(FIRST_LIVE_LINK_DEFAULTS)+ })++ it('storage that throws (private mode, blocked site data) never breaks the dialog', () => {+ expect(+ loadLiveLinkDefaults(() => {+ throw new Error('SecurityError')+ })+ ).toEqual(FIRST_LIVE_LINK_DEFAULTS)+ expect(() =>+ saveLiveLinkDefaults({ role: 'viewer', ttl: 3600 }, () => {+ throw new Error('QuotaExceededError')+ })+ ).not.toThrow()+ })+})diff --git a/src/renderer/lib/liveLinkDefaults.ts b/src/renderer/lib/liveLinkDefaults.tsnew file mode 100644index 000000000..bc048aa43--- /dev/null+++ b/src/renderer/lib/liveLinkDefaults.ts@@ -0,0 +1,59 @@+// The live-link dialog's remembered choices: the role and the expiry of the last link this person+// CREATED, so a person who shares the same way every time (a Control link for pairing, say) is one+// click from it. Same storage family as the explorer pin (`nodeterm.explorerPinned`): this machine+// only, never settings.json or project.json.+//+// Only the two choices are kept. Never the password (a Control link's plaintext lives in the+// dialog's state alone) and never the label (it comes from the presence name). A first-ever dialog,+// and every value that does not parse, falls back to `can watch` for an hour: remembering may bring+// back a Control link, never invent one.+import type { WatchLinkRole } from '@shared/watch-link/protocol'+import { DEFAULT_WATCH_LINK_TTL, WATCH_LINK_TTLS, type WatchLinkTtl } from '@shared/watch-link-types'++export const LIVE_LINK_DEFAULTS_KEY = 'nodeterm.liveLinkDefaults'++export interface LiveLinkDefaults {+ role: WatchLinkRole+ ttl: WatchLinkTtl+}++export const FIRST_LIVE_LINK_DEFAULTS: LiveLinkDefaults = { role: 'viewer', ttl: DEFAULT_WATCH_LINK_TTL }++const ROLES: readonly WatchLinkRole[] = ['viewer', 'commenter', 'controller']++/** Each field on its own: a role this build does not know keeps a good expiry, and the reverse. */+export function parseLiveLinkDefaults(raw: string | null): LiveLinkDefaults {+ if (!raw) return FIRST_LIVE_LINK_DEFAULTS+ let v: unknown+ try {+ v = JSON.parse(raw)+ } catch {+ return FIRST_LIVE_LINK_DEFAULTS+ }+ const o = v && typeof v === 'object' ? (v as { role?: unknown; ttl?: unknown }) : {}+ const role = ROLES.find((r) => r === o.role) ?? FIRST_LIVE_LINK_DEFAULTS.role+ const ttl = WATCH_LINK_TTLS.find((t) => t === o.ttl) ?? FIRST_LIVE_LINK_DEFAULTS.ttl+ return { role, ttl }+}++export function loadLiveLinkDefaults(+ getItem: (key: string) => string | null = (key) => localStorage.getItem(key)+): LiveLinkDefaults {+ try {+ return parseLiveLinkDefaults(getItem(LIVE_LINK_DEFAULTS_KEY))+ } catch {+ // Private mode, blocked site data: the first-ever defaults, never a broken dialog.+ return FIRST_LIVE_LINK_DEFAULTS+ }+}++export function saveLiveLinkDefaults(+ d: LiveLinkDefaults,+ setItem: (key: string, value: string) => void = (key, value) => localStorage.setItem(key, value)+): void {+ try {+ setItem(LIVE_LINK_DEFAULTS_KEY, JSON.stringify({ role: d.role, ttl: d.ttl }))+ } catch {+ /* a convenience: a failed write only means the next dialog opens on the first-ever defaults */+ }+}diff --git a/src/renderer/styles.css b/src/renderer/styles.cssindex 2f76a13d2..98027cb29 100644--- a/src/renderer/styles.css+++ b/src/renderer/styles.css@@ -12104,111 +12104,318 @@ button.pull-checks__name {padding: 5px 8px;font-size: 12.5px;}-/* The create dialog (LiveLinkDialog): the `.confirm` shell, a little wider for the URL. */+/* The create dialog (LiveLinkDialog), Figma's share-dialog shape on the `.confirm` shell: a head with+ the node's title and ✕, then one grouped list of rows that each read as a sentence ("Anyone with+ the link · can watch ▾"), the warnings, and the actions. */.confirm.live-dialog {- width: 460px;+ width: 440px;+ padding: 14px 16px 16px;}-.live-dialog .live-dialog__title {- flex: 0 0 auto;- margin-bottom: 10px;+.live-dialog__head {+ display: flex;+ align-items: center;+ gap: 8px;+ margin: 0 0 12px;+}+.live-dialog__title {+ flex: 1 1 auto;+ min-width: 0;+ margin: 0;+ overflow: hidden;+ color: var(--text);+ font-size: 14px;font-weight: 600;- overflow-wrap: anywhere;+ text-overflow: ellipsis;+ white-space: nowrap;}-.live-dialog__group {- display: flex;- flex-wrap: wrap;- gap: 4px 14px;- margin: 0 0 10px;+/* The head's ✕ and the password row's "new password": quiet icon buttons. */+.live-dialog__close,+.live-dialog__icon-btn {+ flex: none;+ display: grid;+ place-items: center;+ width: 26px;+ height: 26px;padding: 0;border: 0;- font-size: 12px;-}-.live-dialog__group legend {- width: 100%;- margin-bottom: 4px;- padding: 0;+ border-radius: 6px;+ background: transparent;color: var(--muted);- font-size: 11px;+ cursor: pointer;}-.live-dialog__group label {- display: inline-flex;+.live-dialog__close svg,+.live-dialog__icon-btn svg {+ width: 14px;+ height: 14px;+}+.live-dialog__close:hover:not(:disabled),+.live-dialog__icon-btn:hover:not(:disabled) {+ background: rgba(var(--tint-rgb), 0.08);+ color: var(--text);+}+.live-dialog__close:disabled,+.live-dialog__icon-btn:disabled {+ opacity: 0.45;+ cursor: not-allowed;+}+/* The grouped list: a hairline box, hairlines between rows. */+.live-dialog__rows {+ display: flex;+ flex-direction: column;+ margin: 0 0 12px;+ border: 1px solid var(--border);+ border-radius: 10px;+}+.live-dialog__rows > * + .live-dialog__row {+ border-top: 1px solid var(--border);+}+.live-dialog__row {+ display: flex;align-items: center;- gap: 4px;- cursor: pointer;+ gap: 10px;+ min-height: 40px;+ padding: 4px 6px 4px 12px;+ color: var(--text);+ font-size: 13px;}-.live-dialog__label {- display: block;+.live-dialog__icon {+ flex: none;+ display: grid;+ place-items: center;+ width: 16px;color: var(--muted);- font-size: 11px;}+.live-dialog__icon svg {+ width: 15px;+ height: 15px;+}+.live-dialog__row-label {+ flex: 1 1 auto;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.live-dialog__row .confirm__input {+ min-width: 0;+ margin: 0;+ padding: 5px 8px;+ font-size: 12.5px;+}+/* The password takes the row's width; its label only what it needs. */+.live-dialog__row.live-dialog__password .live-dialog__row-label {+ flex: none;+}+.live-dialog__row.live-dialog__password .confirm__input {+ flex: 1 1 auto;+}+/* The name: an inline value like the menus' (right-aligned, no box) that shows its field on hover+ and focus, so the row reads "Viewers see you as Enes" and still says it can be edited. */.live-dialog__label .confirm__input {- margin: 4px 0 10px;+ flex: 0 0 160px;+ padding: 5px 10px;+ border-color: transparent;+ background: transparent;+ text-align: right;+}+.live-dialog__label .confirm__input:hover:not(:disabled) {+ border-color: var(--border);+}+.live-dialog__label .confirm__input:focus {+ border-color: var(--accent);+ background: rgba(var(--tint-rgb), 0.06);+ text-align: left;}-/* The 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. */+/* The password's validation line, inside the list under its row, aligned with the row's text. */+.live-dialog__invalid {+ margin: 0;+ padding: 0 12px 8px 38px;+ color: var(--danger);+ font-size: 11.5px;+}+/* The typing warning (Control only): what typing can do is the one sentence on this dialog that must+ stop the eye, so it keeps a wash. Ink text on it, so it reads the same under Liquid Glass. */.live-dialog__warning {- margin: 0 0 10px;+ margin: 0 0 8px;padding: 8px 10px;- border-radius: 6px;- background: color-mix(in srgb, var(--state-warning) 12%, transparent);+ border-radius: 8px;+ background: color-mix(in srgb, var(--state-error) 12%, transparent);color: var(--text);font-size: 12px;line-height: 1.45;- /* The Control warning can name a long user@host, which has no break points. */+ /* It can name a long user@host, which has no break points. */overflow-wrap: anywhere;}+/* What watching exposes: always shown, for every role, as one quiet sentence. */+.live-dialog__exposure {+ margin: 0 0 12px;+ color: var(--muted);+ font-size: 12px;+ line-height: 1.45;+}.live-dialog__error {margin: 0 0 10px;color: var(--danger);font-size: 12px;overflow-wrap: anywhere;}+.live-dialog__note {+ margin: 0 0 12px;+ color: var(--muted);+ font-size: 12px;+ line-height: 1.45;+}+/* The done step: "● Anyone with this link can watch until 15:42", the dot in the LIVE chip's tone. */+.live-dialog__status {+ display: flex;+ align-items: baseline;+ gap: 8px;+ margin: 0 0 12px;+ color: var(--text);+ font-size: 12.5px;+}+.live-dialog__dot {+ flex: none;+ width: 7px;+ height: 7px;+ border-radius: 50%;+ background: var(--state-error);+ transform: translateY(-1px);+}.live-dialog__url {display: flex;gap: 6px;align-items: center;+ margin: 0 0 8px;}.live-dialog__url .confirm__input {flex: 1 1 auto;min-width: 0;margin: 0;}-.live-dialog__note {- margin: 8px 0 12px;- color: var(--muted);- font-size: 12px;+/* Copy link and Copy password line up, and "Copied!" does not shift the field. */+.live-dialog__copy {+ flex: none;+ min-width: 124px;}-/* A note that belongs to the control just above it (Unlimited's, a password shown once). */-.live-dialog__note.live-dialog__note--tight {- margin: -4px 0 10px;+.live-dialog__actions {+ justify-content: space-between;}-/* The role choice: "Viewer · Can watch". */-.live-dialog__hint {+/* Stop sharing: a red text button on the left, away from Done. */+.confirm__btn.live-dialog__stop {+ /* The text lines up with the content edge above it; the hover wash still has room. */+ margin-left: -10px;+ padding-inline: 10px;+ border-color: transparent;+ background: transparent;+ color: var(--danger);+}+.confirm__btn.live-dialog__stop:hover:not(:disabled) {+ background: color-mix(in srgb, var(--state-error) 12%, transparent);+}++/* MenuSelect (components/MenuSelect.tsx): a row's value with a chevron, and its small menu. The menu+ is absolutely positioned INSIDE the row and opaque: inside a dialog that is a backdrop root under+ Liquid Glass, a translucent or blurred menu would show the dialog's own content through it. */+.menu-select {+ position: relative;+ flex: none;+}+.menu-select__trigger {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 5px 6px 5px 10px;+ border: 0;+ border-radius: 7px;+ background: transparent;+ color: var(--text);+ font: inherit;+ font-size: 13px;+ white-space: nowrap;+ cursor: pointer;+}+.menu-select__trigger svg {+ width: 14px;+ height: 14px;color: var(--muted);}-/* Control on a terminal that cannot take typed input (a Zellij session): shown, disabled, with why. */-.live-dialog__group label.live-dialog__off {+.menu-select__trigger:hover:not(:disabled),+.menu-select__trigger[aria-expanded='true'] {+ background: rgba(var(--tint-rgb), 0.08);+}+.menu-select__trigger:disabled {+ opacity: 0.45;cursor: not-allowed;- opacity: 0.55;}-.live-dialog__reason {+.menu-select__menu {+ position: absolute;+ top: calc(100% + 4px);+ right: 0;+ z-index: 5;+ display: flex;+ flex-direction: column;+ gap: 1px;+ min-width: 280px;+ max-width: 320px;+ padding: 5px;+ border: 1px solid var(--border);+ border-radius: 10px;+ background: rgb(var(--menu-rgb));+ box-shadow: 0 12px 36px rgba(0, 0, 0, calc(0.55 * var(--shadow-k)));+}+.menu-select__item {+ display: flex;+ align-items: flex-start;+ gap: 6px;width: 100%;- margin: 2px 0 0;- color: var(--muted);- font-size: 11px;+ padding: 6px 10px 6px 4px;+ border: 0;+ border-radius: 7px;+ background: transparent;+ color: var(--text);+ font: inherit;+ text-align: left;+ cursor: pointer;+}+.menu-select__item:focus {+ outline: none;}-/* A Control link's password: the form's field with Generate, and the done step's copy of it. */-.live-dialog__pw {+.menu-select__item.active {+ background: var(--panel-header);+}+.menu-select__item.disabled {+ cursor: not-allowed;+}+.menu-select__item.disabled .menu-select__label {color: var(--muted);- font-size: 11px;}-.live-dialog__url.live-dialog__password {- margin: 4px 0 10px;+.menu-select__check {+ flex: none;+ display: grid;+ place-items: center;+ width: 16px;+ height: 18px;+ color: var(--accent);}-.live-dialog__invalid {- margin: -6px 0 10px;- color: var(--danger);- font-size: 11px;+.menu-select__check svg {+ width: 13px;+ height: 13px;+}+.menu-select__text {+ display: flex;+ flex-direction: column;+ gap: 1px;+ min-width: 0;+}+.menu-select__label {+ font-size: 13px;+ line-height: 18px;+}+.menu-select__hint {+ color: var(--muted);+ font-size: 11.5px;+ line-height: 1.35;}/* "Share with team" (ShareTeamDialog): the `.confirm` shell, wider for the lists, with the body asthe scrolling region so Share / Close stay on screen however long the lists are. */