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(live-links): a pinnable Live chat drawer to follow and answer link chat

review16d667ce26f7
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 6d65caf41..a41de0599 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -116,6 +116,7 @@ import { Tooltip } from '../components/Tooltip'
import {
IconBranch,
IconBroadcast,
+ IconChat,
IconCanvasView,
IconClose,
IconCollapse,
@@ -158,6 +159,7 @@ import {
SettingsPage,
SourceControlPanel,
ExplorerPanel,
+ LiveChatDrawer,
ShortcutsPanel,
OnboardingFlow,
DictationOverlay,
@@ -436,6 +438,15 @@ const sshDisconnect = (scopeId: string): Promise<unknown> =>
import { opensInEditor } from '../lib/openTarget'
import { displacedFilesPatch } from '../lib/filesNode'
import { newEntryPath, parentDir } from '../lib/explorerCreate'
+import {
+ liveChatIsOpen,
+ nextLiveChat,
+ readLiveChatLink,
+ readLiveChatPinned,
+ writeLiveChatLink,
+ writeLiveChatPinned,
+ type LiveChatState
+} from '../lib/liveChatPin'
import {
explorerIsOpen,
nextExplorerPin,
@@ -3653,14 +3664,44 @@ export function Canvas() {
}),
[]
)
- // The popover's "Open chat" (`nodeterm:live-chat`, `{ linkId }`). A STUB that opens nothing yet:
- // Task 8 replaces it with the Live chat drawer. It exists so the event is heard
- // (lib/nodeterm-events.test.ts pairs every dispatch with a listener).
+ // The Live chat drawer (lib/liveChatPin — the Explorer's pin pattern, its own keys): which link it
+ // follows and whether it is docked are this machine's view state, in localStorage only. Opened by
+ // the popover's "Open chat" (`nodeterm:live-chat`, `{ linkId }` — this is its ONE listener, pinned
+ // in lib/nodeterm-events.test.ts) and by the palette's "Live chat".
+ const [liveChat, setLiveChat] = useState<LiveChatState>(() => ({
+ pinned: readLiveChatPinned(),
+ dismissed: false,
+ open: false,
+ linkId: readLiveChatLink()
+ }))
+ const liveChatOpen = liveChatIsOpen(liveChat)
+ const liveChatRef = useRef(liveChat)
+ liveChatRef.current = liveChat
useEffect(() => {
- const on = (): void => {}
+ const on = (e: Event): void => {
+ const linkId = (e as CustomEvent<{ linkId?: unknown }>).detail?.linkId
+ if (typeof linkId !== 'string' || !linkId) return
+ // Open chat on a chip IS a pick: the drawer comes back to this link next time.
+ writeLiveChatLink(linkId)
+ setLiveChat((s) => nextLiveChat(s, { kind: 'open', linkId }))
+ }
window.addEventListener('nodeterm:live-chat', on)
return () => window.removeEventListener('nodeterm:live-chat', on)
}, [])
+ const pickLiveChatLink = useCallback((linkId: string) => {
+ writeLiveChatLink(linkId)
+ setLiveChat((s) => nextLiveChat(s, { kind: 'open', linkId }))
+ }, [])
+ const closeLiveChat = useCallback(() => setLiveChat((s) => nextLiveChat(s, { kind: 'close' })), [])
+ const toggleLiveChatPin = useCallback(() => {
+ setLiveChat((s) => {
+ const next = nextLiveChat(s, { kind: 'pin' })
+ writeLiveChatPinned(next.pinned)
+ return next
+ })
+ }, [])
+ /** True while a kanban card modal is open (either board): the drawer then sits above its scrim. */
+ const [cardModalOpen, setCardModalOpen] = useState(false)
const [liveLinkDialog, setLiveLinkDialog] = useState<LiveLinkTarget | null>(null)
const closeLiveLinkDialog = useCallback(() => setLiveLinkDialog(null), [])
/** The facts the ONE availability rule reads, for the node's OWN project (H4): a node of a relay
@@ -12262,6 +12303,8 @@ export function Canvas() {
// whole board on every Canvas render.
const setKanbanModalNode = useCallback((id: string | null) => {
kanbanModalNodeRef.current = id
+ // The Live chat drawer opened from the card's LIVE chip must sit above the modal (`raised`).
+ setCardModalOpen(id !== null)
// The one place the "is anyone looking at this session" predicate learns about the modal —
// every asker (the sweep's plan, the node's fire-time re-ask, the nudge) reads it through
// `isNodeWatched`, so the modal clause cannot go missing from one of them.
@@ -17403,6 +17446,17 @@ export function Canvas() {
travelToNodeRef.current = travelToNode
})
+ /** The Live chat drawer's "Go to terminal": a modal drawer gives way to the canvas first (its scrim
+ * would cover the node); a docked one stays. The project switch, a closed project's reopen and the
+ * board's "open the card" are `travelToNode`'s. */
+ const goToLiveChatNode = useCallback(
+ (nodeId: string) => {
+ if (!liveChatRef.current.pinned) setLiveChat((s) => nextLiveChat(s, { kind: 'close' }))
+ travelToNode(nodeId)
+ },
+ [travelToNode]
+ )
+
// Prepare-for-update (Windows session host, issue #829). Opened from the update card or ⌘K via
// `nodeterm:prepare-update`. `prepareUpdateAvailable` gates the ⌘K entry: the main process answers
// `unsupported` off Windows, when the session host is not the backend, and in the Server Edition.
@@ -18150,11 +18204,13 @@ export function Canvas() {
entitled: useEntitlement.getState().isPremium,
serverEdition: isBrowserRuntime(),
icon: <IconBroadcast />,
+ chatIcon: <IconChat />,
manage: () => {
setSettingsSection('live-links')
setSettingsNonce((n) => n + 1)
setSettingsOpen(true)
},
+ openChat: () => setLiveChat((s) => nextLiveChat(s, { kind: 'open' })),
confirmStopAll: confirmStopAllLiveLinks
}),
// Hidden when the canvas has no restartable agent node — the row would have nothing to act
@@ -19072,6 +19128,21 @@ export function Canvas() {
/>
)}
+ {liveChatOpen && (
+ <LiveChatDrawer
+ linkId={liveChat.linkId}
+ pinned={liveChat.pinned}
+ // `kanbanOpen` too: the per-project board reports a closed modal on change, not on unmount,
+ // so a board closed with its card open would leave the flag behind.
+ raised={cardModalOpen && kanbanOpen}
+ beside={liveChat.pinned && explorerOpen && explorer.pinned}
+ onPickLink={pickLiveChatLink}
+ onClose={closeLiveChat}
+ onTogglePin={toggleLiveChatPin}
+ onGoToNode={goToLiveChatNode}
+ />
+ )}
+
<SessionsSidebar
open={sessionsOpen}
pinned={sessionsPinned}
diff --git a/src/renderer/canvas/live-link-wiring.test.ts b/src/renderer/canvas/live-link-wiring.test.ts
index 80f188032..d172f2505 100644
--- a/src/renderer/canvas/live-link-wiring.test.ts
+++ b/src/renderer/canvas/live-link-wiring.test.ts
@@ -125,4 +125,38 @@ describe('Canvas live-link wiring', () => {
expect(src).toContain("window.addEventListener('nodeterm:live-link', on)")
expect(src).toMatch(/openLiveLinkFor\(\{ nodeId: d\.nodeId, title, projectId: d\.projectId \}\)/)
})
+
+ // ── The Live chat drawer (Task 8) ──
+ it('the drawer is lazy-loaded like the Explorer and mounted only while open', () => {
+ const lazyImport = src.slice(0, src.indexOf("} from '../components/lazyPanels'"))
+ expect(lazyImport.slice(lazyImport.lastIndexOf('import {'))).toContain('LiveChatDrawer')
+ expect(src).toMatch(/\{liveChatOpen && \(\s*<LiveChatDrawer/)
+ })
+
+ it('raised while a card modal is open, beside only when BOTH drawers are pinned', () => {
+ const mount = src.slice(src.indexOf('<LiveChatDrawer'))
+ const props = mount.slice(0, mount.indexOf('/>'))
+ expect(props).toContain('linkId={liveChat.linkId}')
+ expect(props).toContain('pinned={liveChat.pinned}')
+ expect(props).toContain('raised={cardModalOpen && kanbanOpen}')
+ expect(props).toContain('beside={liveChat.pinned && explorerOpen && explorer.pinned}')
+ expect(props).toContain('onGoToNode={goToLiveChatNode}')
+ // The card modal's open state is published where every board reports it.
+ expect(callback('setKanbanModalNode')).toContain('setCardModalOpen(id !== null)')
+ })
+
+ it('the pin is persisted by the toggle; Go to terminal travels (closing a modal drawer first)', () => {
+ expect(callback('toggleLiveChatPin')).toContain('writeLiveChatPinned(next.pinned)')
+ const go = callback('goToLiveChatNode')
+ expect(go).toContain("if (!liveChatRef.current.pinned) setLiveChat((s) => nextLiveChat(s, { kind: 'close' }))")
+ expect(go).toContain('travelToNode(nodeId)')
+ expect(callback('pickLiveChatLink')).toContain('writeLiveChatLink(linkId)')
+ })
+
+ it('the palette opens it; nothing about chat raises an OS notification', () => {
+ const cmds = src.slice(src.indexOf('...liveLinkCommands({'))
+ expect(cmds.slice(0, 600)).toContain("openChat: () => setLiveChat((s) => nextLiveChat(s, { kind: 'open' })),")
+ const drawerSrc = readFileSync(join(__dirname, '../components/LiveChatDrawer.tsx'), 'utf8').replace(/\r\n/g, '\n')
+ expect(drawerSrc).not.toMatch(/notify\(/)
+ })
})
diff --git a/src/renderer/components/LiveChatDrawer.test.tsx b/src/renderer/components/LiveChatDrawer.test.tsx
new file mode 100644
index 000000000..ede80e5d4
--- /dev/null
+++ b/src/renderer/components/LiveChatDrawer.test.tsx
@@ -0,0 +1,393 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { WatchChatMessage, WatchLinkView } from '@shared/watch-link-types'
+import { CHAT_TEXT_MAX } from '@shared/watch-link/protocol'
+import { LiveChatDrawer } from './LiveChatDrawer'
+import { liveChipSig, useWatchLinks } from '../state/watchLinks'
+import { openDialogCount, popDialog, pushDialog, resetDialogStack } from './dialog-stack'
+import { CHAT_NOT_SENT_MESSAGE, CONTROL_LOCKED_TEXT, KICK_NOT_DONE_MESSAGE } from '../lib/liveLink'
+import { chatNameColor } from '../lib/liveChatLook'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({
+ linkId: 'L',
+ nodeId: 'n1',
+ role: 'commenter',
+ label: 'Ada',
+ title: 'build',
+ createdAt: 0,
+ expiresAt: null,
+ url: 'https://nodeterm.dev/s/L#1.secret',
+ status: 'live',
+ viewers: [],
+ control: null,
+ ...over
+})
+const msg = (id: string, over: Partial<WatchChatMessage> = {}): WatchChatMessage => ({
+ id,
+ name: 'Bob',
+ text: 'hello',
+ at: Number(id),
+ from: 'viewer',
+ ...over
+})
+
+const api = {
+ revoke: vi.fn(async (_id: string) => {}),
+ kick: vi.fn(async (_l: string, _v: string) => true),
+ sendChat: vi.fn(async (_l: string, t: string): Promise<WatchChatMessage | null> => ({
+ id: 's',
+ name: 'Ada',
+ text: t,
+ at: 0,
+ from: 'sharer'
+ })),
+ chatHistory: vi.fn(async (_l: string): Promise<WatchChatMessage[]> => []),
+ setControl: vi.fn(async (_l: string, _on: boolean) => true),
+ setPassword: vi.fn(async (_l: string, _pw: string) => true),
+ allowControl: vi.fn(async (_l: string) => true)
+}
+
+let host: HTMLDivElement
+let root: Root
+beforeEach(() => {
+ resetDialogStack()
+ useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })
+ for (const f of Object.values(api)) f.mockClear()
+ api.kick.mockImplementation(async () => true)
+ api.sendChat.mockImplementation(async (_l: string, t: string) => ({ id: 's', name: 'Ada', text: t, at: 0, from: 'sharer' }))
+ api.setPassword.mockImplementation(async () => true)
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { watchLink: api, clipboard: { writeText: vi.fn() } }
+ host = document.createElement('div')
+ document.body.append(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ document.body.innerHTML = ''
+ resetDialogStack()
+})
+
+const noop = (): void => {}
+const props = (over: Partial<Parameters<typeof LiveChatDrawer>[0]> = {}): Parameters<typeof LiveChatDrawer>[0] => ({
+ linkId: 'L',
+ pinned: false,
+ raised: false,
+ onPickLink: noop,
+ onClose: noop,
+ onTogglePin: noop,
+ onGoToNode: noop,
+ ...over
+})
+const render = (p: Parameters<typeof LiveChatDrawer>[0]): void => act(() => root.render(<LiveChatDrawer {...p} />))
+const setLinks = (links: WatchLinkView[]): void => act(() => useWatchLinks.getState().setLinks(links))
+const addChat = (linkId: string, m: WatchChatMessage): void => act(() => useWatchLinks.getState().addChat(linkId, m))
+const drawer = (): HTMLElement => document.querySelector<HTMLElement>('.live-chat')!
+const overlay = (): HTMLElement => document.querySelector<HTMLElement>('.drawer-overlay')!
+const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))
+const button = (label: string): HTMLButtonElement =>
+ [...drawer().querySelectorAll<HTMLButtonElement>('button')].find((b) => b.textContent === label)!
+const flush = (): Promise<void> => act(async () => {})
+const type = (input: HTMLInputElement, value: string): void =>
+ act(() => {
+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!
+ set.call(input, value)
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+const keydown = (key: string): void => act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })))
+
+describe('LiveChatDrawer', () => {
+ it('is the Explorer drawer: titled Live chat, a pin button with aria-pressed, and a close', () => {
+ setLinks([link()])
+ const onClose = vi.fn()
+ const onTogglePin = vi.fn()
+ render(props({ onClose, onTogglePin }))
+ expect(drawer().classList.contains('drawer')).toBe(true)
+ expect(drawer().querySelector('.drawer__head h2')?.textContent).toBe('Live chat')
+ const pin = drawer().querySelector<HTMLButtonElement>('button[aria-label="Pin"]')!
+ expect(pin.getAttribute('aria-pressed')).toBe('false')
+ click(pin)
+ expect(onTogglePin).toHaveBeenCalledTimes(1)
+ click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('unpinned: a modal with a scrim that closes it; a click inside does not', () => {
+ setLinks([link()])
+ const onClose = vi.fn()
+ render(props({ onClose }))
+ expect(overlay().className).toBe('drawer-overlay live-chat-overlay')
+ expect(drawer().classList.contains('drawer--pinned')).toBe(false)
+ click(drawer())
+ expect(onClose).not.toHaveBeenCalled()
+ click(overlay())
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('pinned: docked (drawer--pinned, overlay --pinned), no scrim close, the pin pressed', () => {
+ setLinks([link()])
+ const onClose = vi.fn()
+ render(props({ onClose, pinned: true }))
+ expect(overlay().classList.contains('drawer-overlay--pinned')).toBe(true)
+ expect(drawer().classList.contains('drawer--pinned')).toBe(true)
+ expect(drawer().querySelector('button[aria-label="Unpin"]')?.getAttribute('aria-pressed')).toBe('true')
+ click(overlay())
+ expect(onClose).not.toHaveBeenCalled()
+ })
+
+ it('raised (a card modal is open) and beside (the pinned Explorer is open) are class names on the overlay', () => {
+ setLinks([link()])
+ render(props({ raised: true }))
+ expect(overlay().classList.contains('drawer-overlay--raised')).toBe(true)
+ expect(overlay().classList.contains('drawer-overlay--beside')).toBe(false)
+ render(props({ raised: true, pinned: true, beside: true }))
+ expect(overlay().classList.contains('drawer-overlay--raised')).toBe(true)
+ expect(overlay().classList.contains('drawer-overlay--pinned')).toBe(true)
+ expect(overlay().classList.contains('drawer-overlay--beside')).toBe(true)
+ // `beside` is a docked arrangement: an unpinned modal is never moved for the Explorer.
+ render(props({ pinned: false, beside: true }))
+ expect(overlay().classList.contains('drawer-overlay--beside')).toBe(false)
+ })
+
+ it('shows "No live links." when none is live, and still closes', () => {
+ const onClose = vi.fn()
+ render(props({ onClose, linkId: null }))
+ expect(drawer().textContent).toContain('No live links.')
+ click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('messages: time, name, text, a Sharer badge on the owner\'s lines; names are TEXT, coloured like the viewer page', () => {
+ setLinks([link()])
+ useWatchLinks.getState().setChat('L', [
+ msg('1', { name: '<b>Mallory</b>', text: '<i>hi</i>' }),
+ msg('2', { name: 'Ada', text: 'welcome', from: 'sharer' }),
+ msg('3', { name: 'Ev‮e', text: 'x' })
+ ])
+ render(props())
+ const lines = [...drawer().querySelectorAll<HTMLElement>('.live-chat__msg')]
+ expect(lines).toHaveLength(3)
+ // A name is a claim, shown as written — never parsed as markup.
+ expect(lines[0].querySelector('b')).toBeNull()
+ expect(lines[0].querySelector('i')).toBeNull()
+ expect(lines[0].querySelector('.live-chat__name')?.textContent).toBe('<b>Mallory</b>')
+ expect(lines[0].querySelector('.live-chat__text')?.textContent).toBe('<i>hi</i>')
+ expect(lines[0].querySelector('.live-chat__badge')).toBeNull()
+ expect(lines[0].querySelector<HTMLElement>('.live-chat__name')!.style.getPropertyValue('--live-name')).toBe(chatNameColor('<b>Mallory</b>'))
+ expect(lines[0].querySelector('time')).not.toBeNull()
+ // The owner's own line: the badge, and no viewer colour (the sharer's look is the HOST's word).
+ expect(lines[1].classList.contains('live-chat__msg--sharer')).toBe(true)
+ expect(lines[1].querySelector('.live-chat__badge')?.textContent).toBe('Sharer')
+ expect(lines[1].querySelector<HTMLElement>('.live-chat__name')!.style.getPropertyValue('--live-name')).toBe('')
+ // Bidi controls never reach the screen.
+ expect(lines[2].querySelector('.live-chat__name')?.textContent).toBe('Eve')
+ })
+
+ it('stays at the newest message; scrolled up, a "N new messages ↓" pill appears and takes you down', () => {
+ setLinks([link()])
+ useWatchLinks.getState().setChat('L', [msg('1')])
+ render(props())
+ const list = drawer().querySelector<HTMLElement>('.live-chat__list')!
+ // jsdom has no layout: give the list one, scrolled up.
+ Object.defineProperty(list, 'scrollHeight', { configurable: true, value: 1000 })
+ Object.defineProperty(list, 'clientHeight', { configurable: true, value: 200 })
+ list.scrollTop = 100
+ act(() => void list.dispatchEvent(new Event('scroll')))
+ expect(drawer().querySelector('.live-chat__more')).toBeNull()
+ addChat('L', msg('2'))
+ addChat('L', msg('3'))
+ const pill = drawer().querySelector<HTMLButtonElement>('.live-chat__more')!
+ expect(pill.textContent).toBe('2 new messages ↓')
+ expect(list.scrollTop).toBe(100)
+ click(pill)
+ expect(list.scrollTop).toBe(1000)
+ expect(drawer().querySelector('.live-chat__more')).toBeNull()
+ })
+
+ it('at the bottom, a new message keeps it at the bottom and raises no pill', () => {
+ setLinks([link()])
+ render(props())
+ const list = drawer().querySelector<HTMLElement>('.live-chat__list')!
+ Object.defineProperty(list, 'scrollHeight', { configurable: true, value: 1000 })
+ Object.defineProperty(list, 'clientHeight', { configurable: true, value: 200 })
+ list.scrollTop = 800
+ act(() => void list.dispatchEvent(new Event('scroll')))
+ addChat('L', msg('5'))
+ expect(drawer().querySelector('.live-chat__more')).toBeNull()
+ expect(list.scrollTop).toBe(1000)
+ })
+
+ it('the composer posts as the sharer with api.sendChat, capped at CHAT_TEXT_MAX; a refused send says so', async () => {
+ setLinks([link()])
+ render(props())
+ const input = drawer().querySelector<HTMLInputElement>('.live-chat__reply input')!
+ expect(input.maxLength).toBe(CHAT_TEXT_MAX)
+ type(input, ' hello there ')
+ act(() => void drawer().querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })))
+ await flush()
+ expect(api.sendChat).toHaveBeenCalledWith('L', 'hello there')
+ expect(input.value).toBe('')
+ api.sendChat.mockImplementation(async () => null)
+ type(input, 'again')
+ act(() => void drawer().querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })))
+ await flush()
+ expect(drawer().querySelector('[role="alert"]')?.textContent).toBe(CHAT_NOT_SENT_MESSAGE)
+ expect(input.value).toBe('again')
+ })
+
+ it('a link picker only when more than one link is live: "{title} · {role}", and a pick is reported', () => {
+ setLinks([link()])
+ const onPickLink = vi.fn()
+ render(props({ onPickLink }))
+ expect(drawer().querySelector('select')).toBeNull()
+ setLinks([
+ link(),
+ link({ linkId: 'M', nodeId: 'n2', title: 'api-‮server', role: 'controller', control: { enabled: true, locked: false }, createdAt: 5 }),
+ link({ linkId: 'V', nodeId: 'n3', title: 'logs', role: 'viewer', createdAt: 1 })
+ ])
+ const select = drawer().querySelector<HTMLSelectElement>('select')!
+ expect([...select.options].map((o) => o.textContent)).toEqual(['build · Commenter', 'api-server · Control', 'logs · Viewer'])
+ expect(select.value).toBe('L')
+ act(() => {
+ select.value = 'M'
+ select.dispatchEvent(new Event('change', { bubbles: true }))
+ })
+ expect(onPickLink).toHaveBeenCalledWith('M')
+ })
+
+ it('a link that is not live any more falls back to the most recent one', () => {
+ setLinks([link({ linkId: 'A', createdAt: 1, title: 'old' }), link({ linkId: 'B', createdAt: 9, title: 'new' })])
+ render(props({ linkId: 'gone' }))
+ expect(drawer().querySelector<HTMLSelectElement>('select')!.value).toBe('B')
+ })
+
+ it('a Viewer link shows People only — no thread, no composer', () => {
+ setLinks([link({ role: 'viewer', viewers: [{ viewerId: 'v1', name: null, joinedAt: 1, waiting: false, controlling: false, typing: false }] })])
+ render(props())
+ expect(drawer().querySelector('.live-chat__list')).toBeNull()
+ expect(drawer().querySelector('.live-chat__reply')).toBeNull()
+ expect(drawer().querySelector('.live-chat__people')?.textContent).toContain('Viewer 1')
+ expect(api.chatHistory).not.toHaveBeenCalled()
+ })
+
+ it('People: each viewer watching or able to type, a typing dot, and Kick', async () => {
+ setLinks([
+ link({
+ role: 'controller',
+ control: { enabled: true, locked: false },
+ viewers: [
+ { viewerId: 'v1', name: 'Mert', joinedAt: 1, waiting: false, controlling: true, typing: true },
+ { viewerId: 'v2', name: null, joinedAt: 2, waiting: false, controlling: false, typing: false }
+ ]
+ })
+ ])
+ render(props())
+ const rows = [...drawer().querySelectorAll<HTMLElement>('.live-chat__people li')]
+ expect(rows).toHaveLength(2)
+ expect(rows[0].textContent).toContain('Mert')
+ expect(rows[0].textContent).toContain('can type')
+ expect(rows[0].querySelector('.live-pop__typing')).not.toBeNull()
+ expect(rows[1].textContent).toContain('Viewer 2')
+ expect(rows[1].textContent).toContain('watching')
+ expect(rows[1].querySelector('.live-pop__typing')).toBeNull()
+ click(rows[1].querySelector('button')!)
+ await flush()
+ expect(api.kick).toHaveBeenCalledWith('L', 'v2')
+ api.kick.mockImplementation(async () => false)
+ click(rows[0].querySelector('button')!)
+ await flush()
+ expect(drawer().textContent).toContain(KICK_NOT_DONE_MESSAGE)
+ })
+
+ it("a Control link: the popover's owner controls — Typing calls setControl, Allow again only while locked", async () => {
+ setLinks([link({ role: 'controller', control: { enabled: true, locked: true } })])
+ render(props())
+ const sw = drawer().querySelector<HTMLButtonElement>('[role="switch"]')!
+ click(sw)
+ await flush()
+ expect(api.setControl).toHaveBeenCalledWith('L', false)
+ expect(drawer().textContent).toContain(CONTROL_LOCKED_TEXT)
+ click(button('Allow control again'))
+ await flush()
+ expect(api.allowControl).toHaveBeenCalledWith('L')
+ expect(button('Change password…')).toBeTruthy()
+ })
+
+ it('mounting on a link reads it: markRead, so the chip\'s unread count clears; what lands while shown is read too', async () => {
+ setLinks([link()])
+ addChat('L', msg('1'))
+ addChat('L', msg('2'))
+ expect(useWatchLinks.getState().unread.L).toBe(2)
+ expect(liveChipSig(useWatchLinks.getState(), 'n1').endsWith('\u00012')).toBe(true)
+ render(props())
+ expect(useWatchLinks.getState().unread.L).toBe(0)
+ expect(liveChipSig(useWatchLinks.getState(), 'n1').endsWith('\u00010')).toBe(true)
+ addChat('L', msg('3'))
+ expect(useWatchLinks.getState().unread.L).toBe(0)
+ // Core's history is asked once for the thread on screen.
+ await flush()
+ expect(api.chatHistory).toHaveBeenCalledWith('L')
+ // Closed: a new message counts again.
+ act(() => root.render(<></>))
+ addChat('L', msg('4'))
+ expect(useWatchLinks.getState().unread.L).toBe(1)
+ })
+
+ it('Go to terminal hands the link\'s node to the caller', () => {
+ setLinks([link({ nodeId: 'node-7' })])
+ const onGoToNode = vi.fn()
+ render(props({ onGoToNode }))
+ click(button('Go to terminal'))
+ expect(onGoToNode).toHaveBeenCalledWith('node-7')
+ })
+
+ it('Escape closes the unpinned drawer only while it is the top dialog; pinned, Escape does nothing', () => {
+ setLinks([link()])
+ const onClose = vi.fn()
+ render(props({ onClose }))
+ pushDialog('other')
+ keydown('Escape')
+ expect(onClose).not.toHaveBeenCalled()
+ popDialog('other')
+ keydown('Escape')
+ expect(onClose).toHaveBeenCalledTimes(1)
+ onClose.mockClear()
+ render(props({ onClose, pinned: true }))
+ keydown('Escape')
+ expect(onClose).not.toHaveBeenCalled()
+ })
+
+ it('pinned, it is not a modal: it takes no place in the dialog stack (the board keeps its keys)', () => {
+ setLinks([link()])
+ render(props({ pinned: true }))
+ expect(openDialogCount()).toBe(0)
+ render(props({ pinned: false }))
+ expect(openDialogCount()).toBe(1)
+ render(props({ pinned: true }))
+ expect(openDialogCount()).toBe(0)
+ })
+
+ it('a new password on its way is not lost: × and Escape wait while the save is in flight', async () => {
+ setLinks([link({ role: 'controller', control: { enabled: true, locked: false } })])
+ let answer: (ok: boolean) => void = () => {}
+ api.setPassword.mockImplementation(() => new Promise<boolean>((r) => (answer = r)))
+ const onClose = vi.fn()
+ render(props({ onClose }))
+ click(button('Change password…'))
+ click(button('Generate'))
+ click(button('Save'))
+ await flush()
+ expect(button('Saving…')).toBeTruthy()
+ click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)
+ keydown('Escape')
+ click(overlay())
+ expect(onClose).not.toHaveBeenCalled()
+ await act(async () => answer(true))
+ expect(button('Copy password')).toBeTruthy()
+ click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/renderer/components/LiveChatDrawer.tsx b/src/renderer/components/LiveChatDrawer.tsx
new file mode 100644
index 000000000..1251957a4
--- /dev/null
+++ b/src/renderer/components/LiveChatDrawer.tsx
@@ -0,0 +1,391 @@
+import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from 'react'
+import { createPortal } from 'react-dom'
+import type { WatchChatMessage, WatchLinkView } from '@shared/watch-link-types'
+import { stripBidiControls } from '@shared/watch-link-types'
+import { CHAT_TEXT_MAX } from '@shared/watch-link/protocol'
+import { isTopDialog, nextDialogId, popDialog, pushDialog } from './dialog-stack'
+import { ControlHold, ControlSection, hasChat, kickViewer } from './LiveLinkControls'
+import { IconClose, IconPin } from './icons'
+import { CHAT_NOT_SENT_MESSAGE, KICK_NOTE, ROLE_NAME, statusLine, viewerName, waitingViewers } from '../lib/liveLink'
+import { chatClock, chatNameColor, nearBottom, newMessagesLabel } from '../lib/liveChatLook'
+import { pickChatLink } from '../lib/liveChatPin'
+import { useLinkThread, useWatchLinks } from '../state/watchLinks'
+
+const EMPTY_CHAT: WatchChatMessage[] = []
+
+export interface LiveChatDrawerProps {
+ /** The link the owner picked last; the drawer shows it while it is live, else the most recent. */
+ linkId: string | null
+ /** Docked (no scrim, the canvas stays usable) — the Explorer's pin. */
+ pinned: boolean
+ /** A kanban card modal is open (z 55): sit above it, whatever the pin. */
+ raised: boolean
+ /** The pinned Explorer is open too: dock to its left. Only meaningful while this drawer is pinned. */
+ beside?: boolean
+ onPickLink(id: string): void
+ onClose(): void
+ onTogglePin(): void
+ onGoToNode(nodeId: string): void
+}
+
+/** "build" for the picker and the head: the node title as viewers see it, never empty. */
+function linkTitle(l: Pick<WatchLinkView, 'title'>): string {
+ return stripBidiControls(l.title).trim() || 'Terminal'
+}
+
+/**
+ * The Live chat drawer (spec §4): follow and answer a live link's chat, and manage who can type —
+ * the Explorer drawer's shape and pin, on the right. A Commenter or Control link shows its thread in
+ * the viewer page's live-chat look (lib/liveChatLook) with a composer that posts as the sharer, plus
+ * People; a Viewer link has no chat, so People only.
+ *
+ * Every string someone else wrote — a name, a message, a title — is React TEXT, bidi-stripped. A
+ * name is a claim; the People list shows it as a label, the way the popover does. Nothing here ever
+ * raises an OS notification: chat raises the chip's unread count, and only `control-taken` notifies.
+ *
+ * Unpinned it is a modal in the dialog stack (Escape and the scrim close it while it is the top
+ * dialog); pinned it is docked chrome and takes no place in the stack, so the board and the card
+ * modal keep their keys.
+ */
+export function LiveChatDrawer(p: LiveChatDrawerProps): React.JSX.Element {
+ const { pinned, raised, onClose } = p
+ const links = useWatchLinks((s) => s.links)
+ const shownId = pickChatLink(links, p.linkId)
+ const link = shownId === null ? null : (links.find((l) => l.linkId === shownId) ?? null)
+
+ // A new Control password on its way to being shown holds the drawer open (`ControlHold`): its
+ // plaintext exists nowhere else once core takes it. A counter, not state — nothing renders from it.
+ const holds = useRef(0)
+ const hold = useCallback((): (() => void) => {
+ holds.current++
+ let released = false
+ return () => {
+ if (released) return
+ released = true
+ holds.current--
+ }
+ }, [])
+ /** Close unless something is held. Every close gesture of the owner comes here. */
+ const requestClose = useCallback((): void => {
+ if (holds.current > 0) return
+ onClose()
+ }, [onClose])
+
+ // A modal only while unpinned: docked, it must not take the keyboard from the board or a dialog.
+ const dialogIdRef = useRef<string>()
+ if (!dialogIdRef.current) dialogIdRef.current = nextDialogId()
+ const dialogId = dialogIdRef.current
+ useEffect(() => {
+ if (pinned) return
+ pushDialog(dialogId)
+ return () => popDialog(dialogId)
+ }, [pinned, dialogId])
+ useEffect(() => {
+ if (pinned) return
+ const onKey = (e: KeyboardEvent): void => {
+ if (e.key !== 'Escape' || !isTopDialog(dialogId)) return
+ e.preventDefault()
+ e.stopPropagation()
+ requestClose()
+ }
+ // Capture phase: beat the canvas's own keydown listeners (and xterm) to the Escape.
+ window.addEventListener('keydown', onKey, true)
+ return () => window.removeEventListener('keydown', onKey, true)
+ }, [pinned, dialogId, requestClose])
+
+ // Opened as a modal, keyboard users land in it (a body portal: Tab from the chip would never reach
+ // it) and go back where they were when it closes. Docked, it takes nothing.
+ const asideRef = useRef<HTMLElement>(null)
+ const pinnedAtMount = useRef(pinned)
+ useEffect(() => {
+ if (pinnedAtMount.current) return
+ const before = document.activeElement instanceof HTMLElement ? document.activeElement : null
+ asideRef.current?.focus({ preventScroll: true })
+ return () => {
+ if (before?.isConnected) before.focus({ preventScroll: true })
+ }
+ }, [])
+
+ const overlayClass = [
+ 'drawer-overlay',
+ 'live-chat-overlay',
+ pinned && 'drawer-overlay--pinned',
+ pinned && p.beside && 'drawer-overlay--beside',
+ raised && 'drawer-overlay--raised'
+ ]
+ .filter(Boolean)
+ .join(' ')
+
+ return createPortal(
+ <div
+ className={overlayClass}
+ // Pinned: no handler, and the overlay is pointer-events:none (styles.css) — both halves are
+ // what keep a docked drawer from stealing or dismissing on canvas clicks (the Explorer's rule).
+ onClick={pinned ? undefined : requestClose}
+ >
+ <aside
+ ref={asideRef}
+ className={pinned ? 'drawer drawer--pinned live-chat' : 'drawer live-chat'}
+ role={pinned ? undefined : 'dialog'}
+ aria-label="Live chat"
+ tabIndex={-1}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <div className="drawer__head">
+ <h2>Live chat</h2>
+ <div className="ex-head-actions">
+ <button
+ type="button"
+ className={pinned ? 'is-on' : ''}
+ title={pinned ? 'Unpin' : 'Pin'}
+ aria-label={pinned ? 'Unpin' : 'Pin'}
+ aria-pressed={pinned}
+ onClick={p.onTogglePin}
+ >
+ <IconPin />
+ </button>
+ <button type="button" className="drawer__close" title="Close" aria-label="Close" onClick={requestClose}>
+ <IconClose />
+ </button>
+ </div>
+ </div>
+ {link === null ? (
+ <div className="drawer__body">
+ <p className="set-note">No live links.</p>
+ </div>
+ ) : (
+ <ControlHold.Provider value={hold}>
+ <div className="live-chat__body">
+ <div className="live-chat__link">
+ {links.length > 1 && (
+ <select
+ className="confirm__input live-chat__select"
+ aria-label="Live link"
+ value={link.linkId}
+ onChange={(e) => {
+ // Switching links unmounts the controls: not while a new password is on its way.
+ if (holds.current > 0) return
+ p.onPickLink(e.target.value)
+ }}
+ >
+ {links.map((l) => (
+ <option key={l.linkId} value={l.linkId}>
+ {`${linkTitle(l)} · ${ROLE_NAME[l.role]}`}
+ </option>
+ ))}
+ </select>
+ )}
+ <div className="live-chat__linkhead">
+ <span>
+ <span className="live-pop__who">{linkTitle(link)}</span>{' '}
+ <span className="live-pop__muted">{ROLE_NAME[link.role]}</span>
+ </span>
+ <button
+ type="button"
+ className="live-chat__goto"
+ onClick={() => {
+ // A modal drawer gives way to the canvas — unless a new password is still on
+ // its way to being shown here.
+ if (!pinned && holds.current > 0) return
+ p.onGoToNode(link.nodeId)
+ }}
+ >
+ Go to terminal
+ </button>
+ </div>
+ <LinkStatus link={link} />
+ </div>
+ <People key={`people-${link.linkId}`} link={link} only={!hasChat(link.role)} />
+ {hasChat(link.role) && <Thread key={link.linkId} linkId={link.linkId} />}
+ </div>
+ </ControlHold.Provider>
+ )}
+ </aside>
+ </div>,
+ document.body
+ )
+}
+
+function LinkStatus({ link }: { link: WatchLinkView }): React.JSX.Element | null {
+ const status = statusLine(link)
+ if (!status) return null
+ const tone = link.status === 'live' && waitingViewers([link]) > 0 ? 'waiting' : link.status
+ return (
+ <p className={`live-pop__status live-pop__status--${tone}`} role="status">
+ {status}
+ </p>
+ )
+}
+
+/** Who is connected: each viewer watching or able to type, a typing dot, Kick — and, for a Control
+ * link, the owner controls the popover has (one `ControlSection`). */
+function People({ link, only }: { link: WatchLinkView; only: boolean }): React.JSX.Element {
+ const api = window.nodeTerminal.watchLink
+ const [error, setError] = useState<string | null>(null)
+ return (
+ <section className={only ? 'live-chat__people live-chat__people--only' : 'live-chat__people'} aria-label="People">
+ <h3 className="live-chat__heading">People</h3>
+ {link.control && <ControlSection linkId={link.linkId} control={link.control} />}
+ {link.viewers.length === 0 ? (
+ <p className="live-pop__muted">Nobody is watching right now.</p>
+ ) : (
+ <ul className="live-chat__viewers">
+ {link.viewers.map((v, i) => (
+ <li key={v.viewerId}>
+ {v.typing && <span className="live-pop__typing" role="img" aria-label="Typing now" title="Typing now" />}
+ <span className="live-pop__who">{viewerName(v, i)}</span>
+ <span className="live-pop__muted">
+ {v.controlling ? 'can type' : 'watching'}
+ {v.waiting ? ' · waiting for the terminal' : ''}
+ </span>
+ <button
+ type="button"
+ className="confirm__btn live-pop__btn live-pop__kick"
+ title={KICK_NOTE}
+ onClick={() => kickViewer(api, link.linkId, v.viewerId, setError)}
+ >
+ Kick
+ </button>
+ </li>
+ ))}
+ </ul>
+ )}
+ {error && (
+ <p className="live-pop__error" role="alert">
+ {error}
+ </p>
+ )}
+ </section>
+ )
+}
+
+/** "14:02" with the full date in the tooltip; nothing for a time no Date can hold. */
+function MessageTime({ at }: { at: number }): React.JSX.Element | null {
+ const date = new Date(at)
+ if (!Number.isFinite(date.getTime())) return null
+ const clock = chatClock(at)
+ if (!clock) return null
+ return (
+ <time className="live-chat__time" dateTime={date.toISOString()} title={date.toLocaleString()}>
+ {clock}
+ </time>
+ )
+}
+
+/**
+ * The thread, the viewer page's live chat: one dense line per message, a Sharer badge on the owner's
+ * own lines (the HOST's word, `from === 'sharer'` — never a name), and a list that stays at the newest
+ * message unless the owner scrolled up, then says how many arrived ("N new messages ↓").
+ */
+function Thread({ linkId }: { linkId: string }): React.JSX.Element {
+ const api = window.nodeTerminal.watchLink
+ const chat = useWatchLinks((s) => s.chats[linkId] ?? EMPTY_CHAT)
+ const [draft, setDraft] = useState('')
+ const [sendError, setSendError] = useState(false)
+ const [unseen, setUnseen] = useState(0)
+ const listRef = useRef<HTMLOListElement>(null)
+ /** Reading the newest message (within NEAR_BOTTOM_PX of the end), as of the last scroll. */
+ const stick = useRef(true)
+ // On screen = read (the chip's count clears), and core's history asked once — the popover's rule.
+ useLinkThread(linkId, api)
+
+ const toBottom = (): void => {
+ const el = listRef.current
+ if (el) el.scrollTop = el.scrollHeight
+ stick.current = true
+ setUnseen(0)
+ }
+ // Keyed on the LAST message's id, not the length: at the store's cap the length stops changing.
+ const lastId = chat.length > 0 ? chat[chat.length - 1].id : ''
+ const prevLast = useRef('')
+ useLayoutEffect(() => {
+ const before = prevLast.current
+ prevLast.current = lastId
+ if (lastId === '') return
+ if (stick.current || before === '') {
+ toBottom()
+ return
+ }
+ const at = chat.findIndex((m) => m.id === before)
+ const added = at === -1 ? 1 : chat.length - 1 - at
+ if (added > 0) setUnseen((n) => n + added)
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- runs per new last message, reads the list then
+ }, [lastId])
+
+ return (
+ <div className="live-chat__chat">
+ <div className="live-chat__listwrap">
+ {chat.length === 0 && <p className="live-pop__muted live-chat__empty">No messages yet. Viewers of this link can chat with you here.</p>}
+ <ol
+ className="live-chat__list"
+ ref={listRef}
+ onScroll={(e) => {
+ stick.current = nearBottom(e.currentTarget)
+ if (stick.current && unseen > 0) toBottom()
+ }}
+ >
+ {chat.map((m) => {
+ const sharer = m.from === 'sharer'
+ return (
+ <li key={m.id} className={sharer ? 'live-chat__msg live-chat__msg--sharer' : 'live-chat__msg'}>
+ <MessageTime at={m.at} />
+ {sharer && <span className="live-chat__badge">Sharer</span>}
+ <span
+ className="live-chat__name"
+ // The page's colour for this name, hashed from the name as the viewer sent it.
+ style={sharer ? undefined : ({ '--live-name': chatNameColor(m.name) } as CSSProperties)}
+ >
+ {stripBidiControls(m.name)}
+ </span>
+ <span className="live-chat__colon">: </span>
+ <span className="live-chat__text">{stripBidiControls(m.text)}</span>
+ </li>
+ )
+ })}
+ </ol>
+ {unseen > 0 && (
+ <button type="button" className="confirm__btn primary live-chat__more" onClick={toBottom}>
+ {`${newMessagesLabel(unseen)} ↓`}
+ </button>
+ )}
+ </div>
+ {sendError && (
+ <p className="live-pop__error" role="alert">
+ {CHAT_NOT_SENT_MESSAGE}
+ </p>
+ )}
+ <form
+ className="live-chat__reply"
+ onSubmit={(e) => {
+ e.preventDefault()
+ const text = draft.trim()
+ if (!text) return
+ setSendError(false)
+ // The reply comes back through the chat push (core echoes the owner's own message): be at
+ // the end for it. The box is cleared only once core took it (unless the owner typed on);
+ // a null answer or a rejection keeps the draft and says so — the popover's rule.
+ toBottom()
+ api.sendChat(linkId, text).then(
+ (sent) => {
+ if (sent) setDraft((d) => (d.trim() === text ? '' : d))
+ else setSendError(true)
+ },
+ () => setSendError(true)
+ )
+ }}
+ >
+ <input
+ className="confirm__input live-chat__input"
+ value={draft}
+ maxLength={CHAT_TEXT_MAX}
+ placeholder="Reply to viewers…"
+ aria-label="Reply to viewers"
+ onChange={(e) => setDraft(e.target.value)}
+ />
+ <button type="submit" className="confirm__btn live-pop__btn" disabled={!draft.trim()}>
+ Send
+ </button>
+ </form>
+ </div>
+ )
+}
diff --git a/src/renderer/components/LiveLinkControls.tsx b/src/renderer/components/LiveLinkControls.tsx
new file mode 100644
index 000000000..2da1864e2
--- /dev/null
+++ b/src/renderer/components/LiveLinkControls.tsx
@@ -0,0 +1,289 @@
+// A live link's owner controls, shared by the LIVE chip's popover (LiveLinkPopover) and the Live chat
+// drawer (LiveChatDrawer): one implementation, so the two surfaces cannot disagree about what a
+// Control link's switch, password change or unlock does. Every string someone else wrote is rendered
+// as React TEXT; a new password lives only in `ControlSection`'s state and goes with it.
+import { createContext, useContext, useEffect, useId, useRef, useState } from 'react'
+import type { NodeTerminalApi } from '@shared/types'
+import type { WatchLinkControlView, WatchLinkRole } from '@shared/watch-link-types'
+import { newControlPassword, PasswordField, useCopied } from './LiveLinkPassword'
+import { Switch } from '../ui/Switch'
+import {
+ CONTROL_CHANGE_FAILED_MESSAGE,
+ CONTROL_LOCKED_TEXT,
+ KICK_FAILED_MESSAGE,
+ KICK_NOT_DONE_MESSAGE,
+ PASSWORD_CHANGE_FAILED_MESSAGE,
+ PASSWORD_CHANGE_NOTE,
+ PASSWORD_SAVE_TIMEOUT_MS,
+ PASSWORD_SEPARATE_NOTE,
+ PASSWORD_SHOWN_ONCE,
+ PASSWORD_UNCONFIRMED_MESSAGE,
+ passwordProblemText
+} from '../lib/liveLink'
+
+/**
+ * Something inside a surface the owner must still be shown — a new Control password whose save is in
+ * flight: once core takes it, its plaintext exists nowhere else, so a popover or drawer closed under
+ * it would lose a password that was changed. `hold()` keeps the surface from closing on the owner's
+ * close gestures until the returned release runs. The link going away still closes the popover
+ * (nothing is owed for a link that no longer exists). Absent: nothing to hold.
+ */
+export const ControlHold = createContext<(() => () => void) | null>(null)
+
+/** The roles whose viewers can chat: a Control link is a Commenter link plus typing (spec §2.1). */
+export function hasChat(role: WatchLinkRole): boolean {
+ return role === 'commenter' || role === 'controller'
+}
+
+/**
+ * Kick one viewer, reporting what did not happen: `false` from core (they may already have left) and
+ * a rejection (the Server Edition's socket was down) say different things. `onError(null)` first
+ * clears an earlier message.
+ */
+export function kickViewer(
+ api: Pick<NodeTerminalApi['watchLink'], 'kick'>,
+ linkId: string,
+ viewerId: string,
+ onError: (text: string | null) => void
+): void {
+ onError(null)
+ api.kick(linkId, viewerId).then(
+ (ok) => {
+ if (!ok) onError(KICK_NOT_DONE_MESSAGE)
+ },
+ () => onError(KICK_FAILED_MESSAGE)
+ )
+}
+
+/**
+ * A Control link's owner controls (spec §2.6): the Typing switch, Change password (a new one is shown
+ * ONCE, then only its hash exists — core keeps no plaintext), and Allow control again while the link
+ * is locked by wrong passwords. Shared by the chip's popover and the Live chat drawer.
+ *
+ * The switch shows core's state (the next push), never an optimistic one: a change core refused must
+ * not look applied. A typed or new password lives only in this component's state and goes with it.
+ */
+export function ControlSection({ linkId, control }: { linkId: string; control: WatchLinkControlView }): React.JSX.Element {
+ const api = window.nodeTerminal.watchLink
+ const hold = useContext(ControlHold)
+ const invalidId = useId()
+ const [busy, setBusy] = useState(false)
+ /** A password save is in flight: the surface holds open, Save reads "Saving…". */
+ const [saving, setSaving] = useState(false)
+ const [error, setError] = useState<string | null>(null)
+ const [editing, setEditing] = useState(false)
+ const [draft, setDraft] = useState('')
+ const [shown, setShown] = useState<string | null>(null)
+ const [copied, copy] = useCopied()
+ // Keyboard focus follows the flow: the new field on entering it, Copy password once a new one is
+ // shown, "Change password…" again on Cancel or Done (whose button would otherwise take the focus
+ // with it as it unmounts). Applied after the render that mounts the target.
+ const [focusTo, setFocusTo] = useState<'field' | 'copy' | 'change' | null>(null)
+ const fieldRef = useRef<HTMLInputElement>(null)
+ const copyRef = useRef<HTMLButtonElement>(null)
+ const changeRef = useRef<HTMLButtonElement>(null)
+ useEffect(() => {
+ if (!focusTo) return
+ const el = focusTo === 'field' ? fieldRef.current : focusTo === 'copy' ? copyRef.current : changeRef.current
+ el?.focus({ preventScroll: true })
+ setFocusTo(null)
+ }, [focusTo])
+ // A hold and a deadline this section took and has not given back — both go on unmount too (the
+ // link went away: nothing is owed for it).
+ const releaseRef = useRef<(() => void) | null>(null)
+ const deadlineRef = useRef<ReturnType<typeof setTimeout>>()
+ useEffect(
+ () => () => {
+ releaseRef.current?.()
+ clearTimeout(deadlineRef.current)
+ },
+ []
+ )
+ /** Which save is current: a late answer to an older one is not shown. */
+ const saveGen = useRef(0)
+ const run = (call: () => Promise<boolean>, failed: string): void => {
+ setBusy(true)
+ setError(null)
+ void Promise.resolve()
+ .then(call)
+ .then(
+ (ok) => !ok && setError(failed),
+ () => setError(failed)
+ )
+ .finally(() => setBusy(false))
+ }
+ /**
+ * Save a new password, holding the surface (popover or drawer) open until the answer is in and, on
+ * success, shown —
+ * its plaintext exists nowhere else. Bounded: with no answer after `PASSWORD_SAVE_TIMEOUT_MS` the
+ * hold is released and the owner is told the outcome is unknown. An answer that lands later still
+ * counts: a new password that did take is shown, one refused says so.
+ */
+ const save = (): void => {
+ const next = draft
+ const gen = ++saveGen.current
+ const release = hold?.() ?? null
+ releaseRef.current = release
+ let open = true
+ const settle = (): void => {
+ if (!open) return
+ open = false
+ clearTimeout(deadlineRef.current)
+ setSaving(false)
+ setBusy(false)
+ release?.()
+ if (releaseRef.current === release) releaseRef.current = null
+ }
+ setSaving(true)
+ setBusy(true)
+ setError(null)
+ deadlineRef.current = setTimeout(() => {
+ if (!open) return
+ settle()
+ setError(PASSWORD_UNCONFIRMED_MESSAGE)
+ }, PASSWORD_SAVE_TIMEOUT_MS)
+ void Promise.resolve()
+ .then(() => api.setPassword(linkId, next))
+ .then(
+ (ok) => {
+ settle()
+ if (gen !== saveGen.current) return
+ if (ok) {
+ setError(null)
+ setShown(next)
+ setDraft('')
+ setEditing(false)
+ setFocusTo('copy')
+ } else setError(PASSWORD_CHANGE_FAILED_MESSAGE)
+ },
+ () => {
+ settle()
+ if (gen === saveGen.current) setError(PASSWORD_CHANGE_FAILED_MESSAGE)
+ }
+ )
+ }
+ const problem = passwordProblemText(draft)
+ const showProblem = draft !== '' && problem !== null
+ return (
+ <div className="live-pop__control">
+ {control.locked && (
+ <div className="live-pop__locked">
+ <p className="live-pop__status" role="status">
+ {CONTROL_LOCKED_TEXT}
+ </p>
+ <button
+ type="button"
+ className="confirm__btn live-pop__btn"
+ disabled={busy}
+ onClick={() => run(() => api.allowControl(linkId), CONTROL_CHANGE_FAILED_MESSAGE)}
+ >
+ Allow control again
+ </button>
+ </div>
+ )}
+ <div className="live-pop__toggle">
+ <span>
+ <span className="live-pop__who">Typing</span>{' '}
+ <span className="live-pop__muted">
+ {control.enabled ? 'Anyone with the password can type.' : 'Off: viewers can watch and chat.'}
+ </span>
+ </span>
+ {/* `pending`, not `disabled`: a switch the owner just toggled from the keyboard keeps the focus. */}
+ <Switch
+ checked={control.enabled}
+ ariaLabel="Typing"
+ pending={busy}
+ onChange={(on) => run(() => api.setControl(linkId, on), CONTROL_CHANGE_FAILED_MESSAGE)}
+ />
+ </div>
+ {shown !== null ? (
+ <>
+ <div className="live-pop__password">
+ <PasswordField value={shown} readOnly label="New password" />
+ <button type="button" ref={copyRef} className="confirm__btn live-pop__btn" onClick={() => copy(shown)}>
+ {copied ? 'Copied!' : 'Copy password'}
+ </button>
+ </div>
+ <p className="live-pop__muted live-pop__note">{PASSWORD_SHOWN_ONCE}</p>
+ <p className="live-pop__muted live-pop__note">{PASSWORD_SEPARATE_NOTE}</p>
+ <div className="live-pop__actions">
+ <button
+ type="button"
+ className="confirm__btn live-pop__btn"
+ onClick={() => {
+ setShown(null)
+ setFocusTo('change')
+ }}
+ >
+ Done
+ </button>
+ </div>
+ </>
+ ) : editing ? (
+ <>
+ <div className="live-pop__password">
+ <PasswordField
+ inputRef={fieldRef}
+ value={draft}
+ disabled={busy}
+ onChange={setDraft}
+ label="New password"
+ describedBy={showProblem ? invalidId : undefined}
+ />
+ <button type="button" className="confirm__btn live-pop__btn" disabled={busy} onClick={() => setDraft(newControlPassword())}>
+ Generate
+ </button>
+ </div>
+ {showProblem && (
+ <p className="live-pop__invalid" id={invalidId}>
+ {problem}
+ </p>
+ )}
+ <p className="live-pop__muted live-pop__note">{PASSWORD_CHANGE_NOTE}</p>
+ <div className="live-pop__actions">
+ <button
+ type="button"
+ className="confirm__btn live-pop__btn"
+ disabled={busy}
+ onClick={() => {
+ setEditing(false)
+ setDraft('')
+ setError(null)
+ setFocusTo('change')
+ }}
+ >
+ Cancel
+ </button>
+ <button
+ type="button"
+ className="confirm__btn primary live-pop__btn"
+ disabled={busy || problem !== null}
+ onClick={save}
+ >
+ {saving ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+ </>
+ ) : (
+ <div className="live-pop__actions">
+ <button
+ type="button"
+ ref={changeRef}
+ className="confirm__btn live-pop__btn"
+ onClick={() => {
+ setEditing(true)
+ setFocusTo('field')
+ }}
+ >
+ Change password…
+ </button>
+ </div>
+ )}
+ {error && (
+ <p className="live-pop__error" role="alert">
+ {error}
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/src/renderer/components/LiveLinkPopover.tsx b/src/renderer/components/LiveLinkPopover.tsx
index 0bad82203..30b53fd1f 100644
--- a/src/renderer/components/LiveLinkPopover.tsx
+++ b/src/renderer/components/LiveLinkPopover.tsx
@@ -1,30 +1,19 @@
-import { createContext, memo, useCallback, useContext, useEffect, useId, useRef, useState } from 'react'
+import { memo, useCallback, useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import type { NodeTerminalApi } from '@shared/types'
-import type { WatchLinkControlView, WatchLinkRole, WatchLinkView } from '@shared/watch-link-types'
+import type { WatchLinkView } from '@shared/watch-link-types'
import { stripBidiControls } from '@shared/watch-link-types'
import { CHAT_TEXT_MAX, type WatchChatMessage } from '@shared/watch-link/protocol'
import { useDialogStack } from './dialog-stack'
-import { newControlPassword, PasswordField, useCopied } from './LiveLinkPassword'
+import { useCopied } from './LiveLinkPassword'
+import { ControlHold, ControlSection, hasChat, kickViewer } from './LiveLinkControls'
import { useMenuFlip } from '../ui/useMenuFlip'
-import { Switch } from '../ui/Switch'
import {
CHAT_NOT_SENT_MESSAGE,
commentFromChat,
- CONTROL_CHANGE_FAILED_MESSAGE,
- CONTROL_LOCKED_TEXT,
formatClock,
formatRemaining,
- KICK_FAILED_MESSAGE,
- KICK_NOT_DONE_MESSAGE,
KICK_NOTE,
- PASSWORD_CHANGE_FAILED_MESSAGE,
- PASSWORD_CHANGE_NOTE,
- PASSWORD_SAVE_TIMEOUT_MS,
- PASSWORD_UNCONFIRMED_MESSAGE,
- PASSWORD_SEPARATE_NOTE,
- PASSWORD_SHOWN_ONCE,
- passwordProblemText,
ROLE_LABEL,
ROLE_NAME,
statusLine,
@@ -33,7 +22,7 @@ import {
waitingViewers
} from '../lib/liveLink'
import { thisMachine } from '../lib/machineName'
-import { EMPTY_LINKS, useWatchLinks, viewLinkThread } from '../state/watchLinks'
+import { EMPTY_LINKS, useLinkThread, useWatchLinks } from '../state/watchLinks'
import { useBoardLog } from '../state/boardLog'
import { useProjects } from '../state/projects'
import { sessionForProject } from '../session/session'
@@ -100,20 +89,6 @@ function commentTarget(nodeId: string): { projectId: string; api: NodeTerminalAp
return null
}
-/**
- * Something inside the popover the owner must still be shown — a new Control password whose save is
- * in flight: once core takes it, its plaintext exists nowhere else, so a popover closed under it
- * would lose a password that was changed. `hold()` keeps the popover from closing on an outside
- * click, Escape or Open chat until the returned release runs. The link going away still closes it
- * (nothing is owed for a link that no longer exists). Absent (the drawer): nothing to hold.
- */
-const PopoverHold = createContext<(() => () => void) | null>(null)
-
-/** The roles whose viewers can chat: a Control link is a Commenter link plus typing (spec §2.1). */
-export function hasChat(role: WatchLinkRole): boolean {
- return role === 'commenter' || role === 'controller'
-}
-
/**
* Per-link controls for one node: copy, stop, the viewer list with Kick, and — for a Commenter or
* Control link — the thread with a reply box and "Copy to card comments" (the owner's explicit act;
@@ -138,7 +113,7 @@ export function LiveLinkPopover({
const now = useNow(30_000)
// Below the chip; above it when there is no room below (the dropdown case of useMenuFlip).
const flip = useMenuFlip(anchor.bottom + 6, anchor.left, anchor.top - 6)
- // Holds (see `PopoverHold`): a counter, not state — nothing renders from it.
+ // Holds (see `ControlHold`): a counter, not state — nothing renders from it.
const holds = useRef(0)
const hold = useCallback((): (() => void) => {
holds.current++
@@ -204,11 +179,11 @@ export function LiveLinkPopover({
aria-label="Live links"
tabIndex={-1}
>
- <PopoverHold.Provider value={hold}>
+ <ControlHold.Provider value={hold}>
{links.map((l) => (
<LinkBlock key={l.linkId} link={l} now={now} nodeId={nodeId} requestClose={requestClose} />
))}
- </PopoverHold.Provider>
+ </ControlHold.Provider>
</div>
</>,
document.body
@@ -262,7 +237,7 @@ const LinkBlock = memo(function LinkBlock({
type="button"
className="confirm__btn live-pop__btn"
onClick={() => {
- // The Live chat drawer (Task 8) listens; the popover gives way to it — unless a new
+ // The Live chat drawer (Canvas) listens; the popover gives way to it — unless a new
// password is still on its way to being shown here.
if (!requestClose()) return
window.dispatchEvent(new CustomEvent('nodeterm:live-chat', { detail: { linkId: link.linkId } }))
@@ -309,15 +284,7 @@ const LinkBlock = memo(function LinkBlock({
type="button"
className="confirm__btn live-pop__btn live-pop__kick"
title={KICK_NOTE}
- onClick={() => {
- setError(null)
- api.kick(link.linkId, v.viewerId).then(
- (ok) => {
- if (!ok) setError(KICK_NOT_DONE_MESSAGE)
- },
- () => setError(KICK_FAILED_MESSAGE)
- )
- }}
+ onClick={() => kickViewer(api, link.linkId, v.viewerId, setError)}
>
Kick
</button>
@@ -333,240 +300,8 @@ const LinkBlock = memo(function LinkBlock({
)
})
-/**
- * A Control link's owner controls (spec §2.6): the Typing switch, Change password (a new one is shown
- * ONCE, then only its hash exists — core keeps no plaintext), and Allow control again while the link
- * is locked by wrong passwords. Exported for the Live chat drawer.
- *
- * The switch shows core's state (the next push), never an optimistic one: a change core refused must
- * not look applied. A typed or new password lives only in this component's state and goes with it.
- */
-export function ControlSection({ linkId, control }: { linkId: string; control: WatchLinkControlView }): React.JSX.Element {
- const api = window.nodeTerminal.watchLink
- const hold = useContext(PopoverHold)
- const invalidId = useId()
- const [busy, setBusy] = useState(false)
- /** A password save is in flight: the popover holds open, Save reads "Saving…". */
- const [saving, setSaving] = useState(false)
- const [error, setError] = useState<string | null>(null)
- const [editing, setEditing] = useState(false)
- const [draft, setDraft] = useState('')
- const [shown, setShown] = useState<string | null>(null)
- const [copied, copy] = useCopied()
- // Keyboard focus follows the flow: the new field on entering it, Copy password once a new one is
- // shown, "Change password…" again on Cancel or Done (whose button would otherwise take the focus
- // with it as it unmounts). Applied after the render that mounts the target.
- const [focusTo, setFocusTo] = useState<'field' | 'copy' | 'change' | null>(null)
- const fieldRef = useRef<HTMLInputElement>(null)
- const copyRef = useRef<HTMLButtonElement>(null)
- const changeRef = useRef<HTMLButtonElement>(null)
- useEffect(() => {
- if (!focusTo) return
- const el = focusTo === 'field' ? fieldRef.current : focusTo === 'copy' ? copyRef.current : changeRef.current
- el?.focus({ preventScroll: true })
- setFocusTo(null)
- }, [focusTo])
- // A hold and a deadline this section took and has not given back — both go on unmount too (the
- // link went away: nothing is owed for it).
- const releaseRef = useRef<(() => void) | null>(null)
- const deadlineRef = useRef<ReturnType<typeof setTimeout>>()
- useEffect(
- () => () => {
- releaseRef.current?.()
- clearTimeout(deadlineRef.current)
- },
- []
- )
- /** Which save is current: a late answer to an older one is not shown. */
- const saveGen = useRef(0)
- const run = (call: () => Promise<boolean>, failed: string): void => {
- setBusy(true)
- setError(null)
- void Promise.resolve()
- .then(call)
- .then(
- (ok) => !ok && setError(failed),
- () => setError(failed)
- )
- .finally(() => setBusy(false))
- }
- /**
- * Save a new password, holding the popover open until the answer is in and, on success, shown —
- * its plaintext exists nowhere else. Bounded: with no answer after `PASSWORD_SAVE_TIMEOUT_MS` the
- * hold is released and the owner is told the outcome is unknown. An answer that lands later still
- * counts: a new password that did take is shown, one refused says so.
- */
- const save = (): void => {
- const next = draft
- const gen = ++saveGen.current
- const release = hold?.() ?? null
- releaseRef.current = release
- let open = true
- const settle = (): void => {
- if (!open) return
- open = false
- clearTimeout(deadlineRef.current)
- setSaving(false)
- setBusy(false)
- release?.()
- if (releaseRef.current === release) releaseRef.current = null
- }
- setSaving(true)
- setBusy(true)
- setError(null)
- deadlineRef.current = setTimeout(() => {
- if (!open) return
- settle()
- setError(PASSWORD_UNCONFIRMED_MESSAGE)
- }, PASSWORD_SAVE_TIMEOUT_MS)
- void Promise.resolve()
- .then(() => api.setPassword(linkId, next))
- .then(
- (ok) => {
- settle()
- if (gen !== saveGen.current) return
- if (ok) {
- setError(null)
- setShown(next)
- setDraft('')
- setEditing(false)
- setFocusTo('copy')
- } else setError(PASSWORD_CHANGE_FAILED_MESSAGE)
- },
- () => {
- settle()
- if (gen === saveGen.current) setError(PASSWORD_CHANGE_FAILED_MESSAGE)
- }
- )
- }
- const problem = passwordProblemText(draft)
- const showProblem = draft !== '' && problem !== null
- return (
- <div className="live-pop__control">
- {control.locked && (
- <div className="live-pop__locked">
- <p className="live-pop__status" role="status">
- {CONTROL_LOCKED_TEXT}
- </p>
- <button
- type="button"
- className="confirm__btn live-pop__btn"
- disabled={busy}
- onClick={() => run(() => api.allowControl(linkId), CONTROL_CHANGE_FAILED_MESSAGE)}
- >
- Allow control again
- </button>
- </div>
- )}
- <div className="live-pop__toggle">
- <span>
- <span className="live-pop__who">Typing</span>{' '}
- <span className="live-pop__muted">
- {control.enabled ? 'Anyone with the password can type.' : 'Off: viewers can watch and chat.'}
- </span>
- </span>
- {/* `pending`, not `disabled`: a switch the owner just toggled from the keyboard keeps the focus. */}
- <Switch
- checked={control.enabled}
- ariaLabel="Typing"
- pending={busy}
- onChange={(on) => run(() => api.setControl(linkId, on), CONTROL_CHANGE_FAILED_MESSAGE)}
- />
- </div>
- {shown !== null ? (
- <>
- <div className="live-pop__password">
- <PasswordField value={shown} readOnly label="New password" />
- <button type="button" ref={copyRef} className="confirm__btn live-pop__btn" onClick={() => copy(shown)}>
- {copied ? 'Copied!' : 'Copy password'}
- </button>
- </div>
- <p className="live-pop__muted live-pop__note">{PASSWORD_SHOWN_ONCE}</p>
- <p className="live-pop__muted live-pop__note">{PASSWORD_SEPARATE_NOTE}</p>
- <div className="live-pop__actions">
- <button
- type="button"
- className="confirm__btn live-pop__btn"
- onClick={() => {
- setShown(null)
- setFocusTo('change')
- }}
- >
- Done
- </button>
- </div>
- </>
- ) : editing ? (
- <>
- <div className="live-pop__password">
- <PasswordField
- inputRef={fieldRef}
- value={draft}
- disabled={busy}
- onChange={setDraft}
- label="New password"
- describedBy={showProblem ? invalidId : undefined}
- />
- <button type="button" className="confirm__btn live-pop__btn" disabled={busy} onClick={() => setDraft(newControlPassword())}>
- Generate
- </button>
- </div>
- {showProblem && (
- <p className="live-pop__invalid" id={invalidId}>
- {problem}
- </p>
- )}
- <p className="live-pop__muted live-pop__note">{PASSWORD_CHANGE_NOTE}</p>
- <div className="live-pop__actions">
- <button
- type="button"
- className="confirm__btn live-pop__btn"
- disabled={busy}
- onClick={() => {
- setEditing(false)
- setDraft('')
- setError(null)
- setFocusTo('change')
- }}
- >
- Cancel
- </button>
- <button
- type="button"
- className="confirm__btn primary live-pop__btn"
- disabled={busy || problem !== null}
- onClick={save}
- >
- {saving ? 'Saving…' : 'Save'}
- </button>
- </div>
- </>
- ) : (
- <div className="live-pop__actions">
- <button
- type="button"
- ref={changeRef}
- className="confirm__btn live-pop__btn"
- onClick={() => {
- setEditing(true)
- setFocusTo('field')
- }}
- >
- Change password…
- </button>
- </div>
- )}
- {error && (
- <p className="live-pop__error" role="alert">
- {error}
- </p>
- )}
- </div>
- )
-}
-
-/** A Commenter or Control link's thread with the owner's reply box. Exported for the Live chat drawer. */
-export function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string }): React.JSX.Element {
+/** A Commenter or Control link's thread with the owner's reply box (the drawer has its own look). */
+function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string }): React.JSX.Element {
const api = window.nodeTerminal.watchLink
const chat = useWatchLinks((s) => s.chats[linkId] ?? EMPTY_CHAT)
const onBoard = useProjects((s) => s.projects.some((p) => p.nodes.some((n) => n.id === nodeId)))
@@ -575,21 +310,8 @@ export function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string
const [copyError, setCopyError] = useState(false)
const [sendError, setSendError] = useState(false)
const threadRef = useRef<HTMLOListElement>(null)
- // While this thread is on screen, what lands in it is read as it arrives (N2).
- useEffect(() => viewLinkThread(linkId), [linkId])
- // Core keeps the thread in memory; ask for it once when the thread opens (a reload, or messages
- // that arrived before this renderer subscribed). The store merges it with what was pushed.
- useEffect(() => {
- void api.chatHistory(linkId).then(
- (m) => useWatchLinks.getState().setChat(linkId, m),
- () => {}
- )
- }, [api, linkId])
- // Open = read (H21): what arrived before the thread opened is read on open; what lands while it
- // is open never counts (`viewLinkThread` above).
- useEffect(() => {
- useWatchLinks.getState().markRead(linkId)
- }, [linkId])
+ // On screen = read, and core's history asked once (the thread rule, shared with the drawer).
+ useLinkThread(linkId, api)
// Follow the newest message. Keyed on the LAST message's id, not the length — at the 200-message
// cap the length stops changing.
const lastId = chat.length > 0 ? chat[chat.length - 1].id : ''
diff --git a/src/renderer/components/lazyPanels.tsx b/src/renderer/components/lazyPanels.tsx
index dd8ad2805..7bfdd9165 100644
--- a/src/renderer/components/lazyPanels.tsx
+++ b/src/renderer/components/lazyPanels.tsx
@@ -48,6 +48,9 @@ export const SourceControlPanel = withSuspense(
export const ExplorerPanel = withSuspense(
lazy(() => import('./ExplorerPanel').then((m) => ({ default: m.ExplorerPanel })))
)
+export const LiveChatDrawer = withSuspense(
+ lazy(() => import('./LiveChatDrawer').then((m) => ({ default: m.LiveChatDrawer })))
+)
export const ShortcutsPanel = withSuspense(
lazy(() => import('./ShortcutsPanel').then((m) => ({ default: m.ShortcutsPanel })))
)
diff --git a/src/renderer/lib/liveChatLook.test.ts b/src/renderer/lib/liveChatLook.test.ts
new file mode 100644
index 000000000..fd980bcd6
--- /dev/null
+++ b/src/renderer/lib/liveChatLook.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest'
+import { chatClock, chatNameColor, nearBottom, NEAR_BOTTOM_PX, newMessagesLabel, VIEWER_NAME_COLORS } from './liveChatLook'
+
+describe('the viewer page\'s chat look, copied (nodeterm-web src/lib/watch-viewer/chat-panel.ts)', () => {
+ it('the same name gets the same colour as on the viewer page (FNV-1a over UTF-16 units)', () => {
+ // Values computed with the web page's own function: a drift here means the owner sees a viewer
+ // in a different colour than everyone watching does.
+ expect(chatNameColor('Mert')).toBe('#ffa657')
+ expect(chatNameColor('Ayşe')).toBe('#c9b6ff')
+ expect(chatNameColor('Bob')).toBe('#58a6ff')
+ expect(chatNameColor('<b>x</b>')).toBe('#58a6ff')
+ expect(chatNameColor('')).toBe('#ffa657')
+ expect(VIEWER_NAME_COLORS).toHaveLength(12)
+ expect(VIEWER_NAME_COLORS).toContain(chatNameColor('\u{1F642}\u{1F642}'))
+ })
+
+ it('nearBottom: within 32 px of the end counts as reading the newest message', () => {
+ expect(NEAR_BOTTOM_PX).toBe(32)
+ expect(nearBottom({ scrollTop: 600, clientHeight: 400, scrollHeight: 1000 })).toBe(true)
+ expect(nearBottom({ scrollTop: 568, clientHeight: 400, scrollHeight: 1000 })).toBe(true)
+ expect(nearBottom({ scrollTop: 567, clientHeight: 400, scrollHeight: 1000 })).toBe(false)
+ })
+
+ it('the pill label', () => {
+ expect(newMessagesLabel(1)).toBe('1 new message')
+ expect(newMessagesLabel(4)).toBe('4 new messages')
+ expect(newMessagesLabel(140)).toBe('99+ new messages')
+ })
+
+ it('chatClock: a time the page cannot read is nothing', () => {
+ expect(chatClock(Number.NaN)).toBe('')
+ expect(chatClock('1' as unknown as number)).toBe('')
+ expect(chatClock(Date.UTC(2026, 9, 3, 14, 2))).not.toBe('')
+ })
+})
diff --git a/src/renderer/lib/liveChatLook.ts b/src/renderer/lib/liveChatLook.ts
new file mode 100644
index 000000000..b699edd34
--- /dev/null
+++ b/src/renderer/lib/liveChatLook.ts
@@ -0,0 +1,45 @@
+// The live-link viewer page's chat look, for the owner's Live chat drawer. COPIED from nodeterm-web
+// `src/lib/watch-viewer/chat-panel.ts` (chatNameColor, VIEWER_NAME_COLORS, nearBottom,
+// NEAR_BOTTOM_PX, newMessagesLabel, chatClock) — never imported across repositories. Keep the two in
+// step: a viewer must be drawn in the same colour on the owner's drawer as on every viewer's page
+// (`liveChatLook.test.ts` pins the hash against values computed with the web page's function).
+//
+// The hex table is the web page's, kept verbatim so the colours match; the drawer hands a colour to
+// CSS as `--live-name`, where the light theme darkens it toward the ink (styles.css). The sharer's
+// colour is NOT copied: the drawer marks the owner's lines with a token and the "Sharer" badge, and —
+// as on the page — no viewer name is ever drawn in it (the badge is the host's word, never a name's).
+
+/** Viewer name colours, readable on the page's near-black. No green near the sharer's. */
+export const VIEWER_NAME_COLORS = [
+ '#ff7b72', '#ffa657', '#f2cc60', '#79c0ff', '#58a6ff', '#a5a0ff',
+ '#d2a8ff', '#ff9bce', '#f778ba', '#56d4dd', '#ffb4a1', '#c9b6ff'
+] as const
+
+/** One colour per name, the same on every viewer's page (FNV-1a over the UTF-16 units). Hash the
+ * name as the viewer sent it, before any display cleaning, so it matches the page. */
+export function chatNameColor(name: string): string {
+ let h = 0x811c9dc5
+ for (let i = 0; i < name.length; i++) {
+ h ^= name.charCodeAt(i)
+ h = Math.imul(h, 0x01000193)
+ }
+ return VIEWER_NAME_COLORS[(h >>> 0) % VIEWER_NAME_COLORS.length]
+}
+
+/** How close to the end counts as "reading the newest message" (a fractional scroll position, a line
+ * still settling). */
+export const NEAR_BOTTOM_PX = 32
+
+export function nearBottom(m: { scrollTop: number; clientHeight: number; scrollHeight: number }): boolean {
+ return m.scrollHeight - m.scrollTop - m.clientHeight <= NEAR_BOTTOM_PX
+}
+
+/** "14:02" in the owner's own clock and locale; nothing for a time that cannot be read. */
+export function chatClock(at: unknown, locale?: string): string {
+ if (typeof at !== 'number' || !Number.isFinite(at)) return ''
+ return new Intl.DateTimeFormat(locale, { hour: 'numeric', minute: '2-digit' }).format(at)
+}
+
+export function newMessagesLabel(n: number): string {
+ return n === 1 ? '1 new message' : `${n > 99 ? '99+' : n} new messages`
+}
diff --git a/src/renderer/lib/liveChatPin.test.ts b/src/renderer/lib/liveChatPin.test.ts
new file mode 100644
index 000000000..e7dd365cf
--- /dev/null
+++ b/src/renderer/lib/liveChatPin.test.ts
@@ -0,0 +1,145 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import type { WatchLinkView } from '@shared/watch-link-types'
+import {
+ LIVE_CHAT_LINK_KEY,
+ LIVE_CHAT_PINNED_KEY,
+ liveChatIsOpen,
+ nextLiveChat,
+ pickChatLink,
+ readLiveChatLink,
+ readLiveChatPinned,
+ writeLiveChatLink,
+ writeLiveChatPinned,
+ type LiveChatState
+} from './liveChatPin'
+
+const hidden: LiveChatState = { pinned: false, dismissed: false, open: false, linkId: null }
+const modal: LiveChatState = { pinned: false, dismissed: false, open: true, linkId: 'A' }
+const docked: LiveChatState = { pinned: true, dismissed: false, open: true, linkId: 'A' }
+const dockedHidden: LiveChatState = { pinned: true, dismissed: true, open: false, linkId: 'A' }
+/** Launch after a previous pin: shown, but `open` was never set this run. */
+const launchPinned: LiveChatState = { pinned: true, dismissed: false, open: false, linkId: null }
+
+const link = (linkId: string, createdAt: number): WatchLinkView => ({
+ linkId,
+ nodeId: 'n',
+ role: 'commenter',
+ label: 'A',
+ title: 't',
+ createdAt,
+ expiresAt: null,
+ url: 'u',
+ status: 'live',
+ viewers: [],
+ control: null
+})
+
+afterEach(() => vi.unstubAllGlobals())
+
+describe('liveChatIsOpen', () => {
+ it('follows `open` unpinned and `!dismissed` pinned', () => {
+ expect(liveChatIsOpen(hidden)).toBe(false)
+ expect(liveChatIsOpen(modal)).toBe(true)
+ expect(liveChatIsOpen(docked)).toBe(true)
+ expect(liveChatIsOpen(dockedHidden)).toBe(false)
+ expect(liveChatIsOpen(launchPinned)).toBe(true)
+ })
+})
+
+describe('nextLiveChat', () => {
+ it('open shows the drawer, on the named link when there is one, and keeps the pin', () => {
+ expect(nextLiveChat(hidden, { kind: 'open', linkId: 'B' })).toEqual({ pinned: false, dismissed: false, open: true, linkId: 'B' })
+ // No link named (the palette): the last link stays.
+ expect(nextLiveChat({ ...hidden, linkId: 'A' }, { kind: 'open' })).toEqual({ ...modal, linkId: 'A' })
+ expect(nextLiveChat(dockedHidden, { kind: 'open', linkId: 'C' })).toEqual({ pinned: true, dismissed: false, open: true, linkId: 'C' })
+ })
+
+ it('close hides without touching the pin or the link', () => {
+ expect(nextLiveChat(modal, { kind: 'close' })).toEqual({ pinned: false, dismissed: true, open: false, linkId: 'A' })
+ expect(nextLiveChat(docked, { kind: 'close' })).toEqual({ pinned: true, dismissed: true, open: false, linkId: 'A' })
+ })
+
+ it('toggle flips what is on screen, the launch-pinned case included', () => {
+ expect(liveChatIsOpen(nextLiveChat(hidden, { kind: 'toggle' }))).toBe(true)
+ expect(liveChatIsOpen(nextLiveChat(modal, { kind: 'toggle' }))).toBe(false)
+ expect(liveChatIsOpen(nextLiveChat(docked, { kind: 'toggle' }))).toBe(false)
+ expect(liveChatIsOpen(nextLiveChat(dockedHidden, { kind: 'toggle' }))).toBe(true)
+ expect(liveChatIsOpen(nextLiveChat(launchPinned, { kind: 'toggle' }))).toBe(false)
+ })
+
+ it('pin docks and shows; unpinning a visible drawer keeps it on screen as the modal', () => {
+ expect(nextLiveChat(modal, { kind: 'pin' })).toEqual({ pinned: true, dismissed: false, open: true, linkId: 'A' })
+ expect(nextLiveChat(hidden, { kind: 'pin' })).toEqual({ pinned: true, dismissed: false, open: true, linkId: null })
+ // If unpinning only flipped `pinned`, the launch-pinned drawer (open never set) would vanish.
+ expect(nextLiveChat(launchPinned, { kind: 'pin' })).toEqual({ pinned: false, dismissed: false, open: true, linkId: null })
+ expect(nextLiveChat(docked, { kind: 'pin' })).toEqual({ pinned: false, dismissed: false, open: true, linkId: 'A' })
+ expect(nextLiveChat(dockedHidden, { kind: 'pin' })).toEqual({ pinned: false, dismissed: false, open: false, linkId: 'A' })
+ })
+})
+
+describe('pickChatLink', () => {
+ it('the wanted link while it is live', () => {
+ expect(pickChatLink([link('A', 1), link('B', 2)], 'A')).toBe('A')
+ })
+ it('else the most recent link (by creation), ties going to the later one in the list', () => {
+ expect(pickChatLink([link('A', 1), link('B', 3), link('C', 2)], 'gone')).toBe('B')
+ expect(pickChatLink([link('A', 1), link('B', 3), link('C', 2)], null)).toBe('B')
+ expect(pickChatLink([link('A', 5), link('B', 5)], null)).toBe('B')
+ })
+ it('nothing when no link is live', () => {
+ expect(pickChatLink([], 'A')).toBeNull()
+ expect(pickChatLink([], null)).toBeNull()
+ })
+})
+
+describe('storage', () => {
+ it('pin: reads and writes its own key as 1/0, off by default', () => {
+ const store: Record<string, string> = {}
+ const get = (k: string): string | null => store[k] ?? null
+ const set = (k: string, v: string): void => void (store[k] = v)
+ expect(readLiveChatPinned(get)).toBe(false)
+ writeLiveChatPinned(true, set)
+ expect(store[LIVE_CHAT_PINNED_KEY]).toBe('1')
+ expect(readLiveChatPinned(get)).toBe(true)
+ writeLiveChatPinned(false, set)
+ expect(store[LIVE_CHAT_PINNED_KEY]).toBe('0')
+ expect(readLiveChatPinned(get)).toBe(false)
+ expect(LIVE_CHAT_PINNED_KEY).toBe('nodeterm.liveChatPinned')
+ })
+
+ it('the last link: remembered under its own key; an empty or non-string value is no link', () => {
+ const store: Record<string, string> = {}
+ const get = (k: string): string | null => store[k] ?? null
+ const set = (k: string, v: string): void => void (store[k] = v)
+ expect(readLiveChatLink(get)).toBeNull()
+ writeLiveChatLink('L1', set)
+ expect(store[LIVE_CHAT_LINK_KEY]).toBe('L1')
+ expect(readLiveChatLink(get)).toBe('L1')
+ store[LIVE_CHAT_LINK_KEY] = ''
+ expect(readLiveChatLink(get)).toBeNull()
+ expect(LIVE_CHAT_LINK_KEY).toBe('nodeterm.liveChatLink')
+ })
+
+ it('a throwing localStorage (private window, blocked site data) reads as nothing and never throws', () => {
+ const throwing = {
+ getItem: () => {
+ throw new Error('blocked')
+ },
+ setItem: () => {
+ throw new Error('quota')
+ }
+ }
+ vi.stubGlobal('localStorage', throwing)
+ expect(readLiveChatPinned()).toBe(false)
+ expect(readLiveChatLink()).toBeNull()
+ expect(() => writeLiveChatPinned(true)).not.toThrow()
+ expect(() => writeLiveChatLink('L')).not.toThrow()
+ })
+
+ it('a missing localStorage (no DOM) reads as nothing too', () => {
+ vi.stubGlobal('localStorage', undefined)
+ expect(readLiveChatPinned()).toBe(false)
+ expect(readLiveChatLink()).toBeNull()
+ expect(() => writeLiveChatPinned(true)).not.toThrow()
+ })
+})
diff --git a/src/renderer/lib/liveChatPin.ts b/src/renderer/lib/liveChatPin.ts
new file mode 100644
index 000000000..4e27b1962
--- /dev/null
+++ b/src/renderer/lib/liveChatPin.ts
@@ -0,0 +1,91 @@
+// The Live chat drawer's visibility: the Explorer drawer's pin pattern (lib/explorerPin.ts), with its
+// own keys. This machine only, in localStorage — never settings.json or project.json: which link the
+// owner follows is one person's view state, and a live link is not canvas content.
+//
+// pinned — persisted preference: docked, does not block the canvas (default off)
+// dismissed — transient "hide for now" (the ×). Does NOT clear the pin.
+// open — unpinned (modal) visibility
+// linkId — the link the owner picked last (Open chat on a chip, the drawer's picker). The drawer
+// shows it while it is live, else the most recent link (`pickChatLink`).
+import type { WatchLinkView } from '@shared/watch-link-types'
+
+export const LIVE_CHAT_PINNED_KEY = 'nodeterm.liveChatPinned'
+export const LIVE_CHAT_LINK_KEY = 'nodeterm.liveChatLink'
+
+export interface LiveChatState {
+ pinned: boolean
+ dismissed: boolean
+ open: boolean
+ linkId: string | null
+}
+
+export type LiveChatAction = { kind: 'open'; linkId?: string } | { kind: 'toggle' } | { kind: 'close' } | { kind: 'pin' }
+
+/** Pinned: shown unless dismissed. Unpinned: `open` is the modal flag. */
+export function liveChatIsOpen(s: LiveChatState): boolean {
+ return s.pinned ? !s.dismissed : s.open
+}
+
+export function nextLiveChat(s: LiveChatState, a: LiveChatAction): LiveChatState {
+ switch (a.kind) {
+ case 'open':
+ return { ...s, dismissed: false, open: true, linkId: a.linkId ?? s.linkId }
+ case 'close':
+ return { ...s, dismissed: true, open: false }
+ case 'toggle':
+ return liveChatIsOpen(s) ? { ...s, dismissed: true, open: false } : { ...s, dismissed: false, open: true }
+ case 'pin':
+ // (Re)pinning shows the docked drawer. Unpinning a visible drawer keeps it on screen as the
+ // modal even when `open` was never set — the launch-pinned case (`pinned && !dismissed`).
+ return s.pinned
+ ? { ...s, pinned: false, dismissed: false, open: liveChatIsOpen(s) }
+ : { ...s, pinned: true, dismissed: false, open: true }
+ }
+}
+
+/** The link to show: `wanted` while it is live, else the most recently created one (a tie goes to the
+ * later one in the list), else none. */
+export function pickChatLink(links: readonly WatchLinkView[], wanted: string | null): string | null {
+ if (wanted !== null && links.some((l) => l.linkId === wanted)) return wanted
+ let best: WatchLinkView | null = null
+ for (const l of links) if (!best || l.createdAt >= best.createdAt) best = l
+ return best ? best.linkId : null
+}
+
+const getStored = (key: string): string | null => localStorage.getItem(key)
+const setStored = (key: string, value: string): void => localStorage.setItem(key, value)
+
+/** `'1'` is pinned; missing, `'0'`, unreadable storage or anything else is not. */
+export function readLiveChatPinned(getItem: (key: string) => string | null = getStored): boolean {
+ try {
+ return getItem(LIVE_CHAT_PINNED_KEY) === '1'
+ } catch {
+ return false
+ }
+}
+
+export function writeLiveChatPinned(v: boolean, setItem: (key: string, value: string) => void = setStored): void {
+ try {
+ setItem(LIVE_CHAT_PINNED_KEY, v ? '1' : '0')
+ } catch {
+ /* private window / blocked storage: the pin is a nicety, never fail the UI */
+ }
+}
+
+/** The last picked link id, or null (none, empty, unreadable storage). */
+export function readLiveChatLink(getItem: (key: string) => string | null = getStored): string | null {
+ try {
+ const v = getItem(LIVE_CHAT_LINK_KEY)
+ return typeof v === 'string' && v !== '' ? v : null
+ } catch {
+ return null
+ }
+}
+
+export function writeLiveChatLink(linkId: string, setItem: (key: string, value: string) => void = setStored): void {
+ try {
+ setItem(LIVE_CHAT_LINK_KEY, linkId)
+ } catch {
+ /* not remembered: the drawer falls back to the most recent link */
+ }
+}
diff --git a/src/renderer/lib/liveLinkEntry.test.tsx b/src/renderer/lib/liveLinkEntry.test.tsx
index 1727bec72..abbd49eaa 100644
--- a/src/renderer/lib/liveLinkEntry.test.tsx
+++ b/src/renderer/lib/liveLinkEntry.test.tsx
@@ -311,7 +311,7 @@ describe('stopAllLiveLinks (R62)', () => {
})
describe('liveLinkCommands (palette)', () => {
- const base = { entitled: false, serverEdition: false, icon: null }
+ const base = { entitled: false, serverEdition: false, icon: null, chatIcon: null, openChat: () => {} }
it('Manage always; Stop all with links OR a Pro license (R62), labelled for every machine, and it CONFIRMS', () => {
const manage = vi.fn()
const confirmStopAll = vi.fn()
@@ -323,16 +323,27 @@ describe('liveLinkCommands (palette)', () => {
expect(entitled.map((c) => c.id)).toEqual(['live-links-manage', 'live-links-stop-all'])
// Never in the Server Edition (R43): no license layer, nothing to stop.
const server = liveLinkCommands({ ...base, serverEdition: true, entitled: true, activeLinks: 3, manage, confirmStopAll })
- expect(server.map((c) => c.id)).toEqual(['live-links-manage'])
+ expect(server.map((c) => c.id)).not.toContain('live-links-stop-all')
const some = liveLinkCommands({ ...base, activeLinks: 2, manage, confirmStopAll })
- expect(some.map((c) => c.id)).toEqual(['live-links-manage', 'live-links-stop-all'])
+ expect(some.map((c) => c.id)).toEqual(['live-links-manage', 'live-chat', 'live-links-stop-all'])
expect(some[0].label).toBe('Manage live links')
- expect(some[1].label).toBe('Stop all live links (every machine on this license)')
+ expect(some[2].label).toBe('Stop all live links (every machine on this license)')
some[0].run()
expect(manage).toHaveBeenCalledTimes(1)
- some[1].run()
+ some[2].run()
expect(confirmStopAll).toHaveBeenCalledTimes(1)
})
+
+ it('"Live chat" (section View) while any link is live, and it opens the drawer', () => {
+ const openChat = vi.fn()
+ const args = { ...base, openChat, manage: () => {}, confirmStopAll: () => {} }
+ expect(liveLinkCommands({ ...args, activeLinks: 0 }).some((c) => c.id === 'live-chat')).toBe(false)
+ const chat = liveLinkCommands({ ...args, activeLinks: 1 }).find((c) => c.id === 'live-chat')!
+ expect(chat.label).toBe('Live chat')
+ expect(chat.section).toBe('View')
+ chat.run()
+ expect(openChat).toHaveBeenCalledTimes(1)
+ })
})
// Where a node runs, for the create dialog: R63 (does the HOST's tmux give a viewer a client of its
diff --git a/src/renderer/lib/liveLinkEntry.tsx b/src/renderer/lib/liveLinkEntry.tsx
index b20b9ad0f..557f873a3 100644
--- a/src/renderer/lib/liveLinkEntry.tsx
+++ b/src/renderer/lib/liveLinkEntry.tsx
@@ -283,9 +283,10 @@ export async function stopAllLiveLinks(
}
}
-/** The palette's live-link entries. "Stop all" appears wherever the owner could have links to stop
- * (`showsStopAll`: a link listed here, OR a Pro license — its links on other machines are invisible
- * here), and its `run` opens the confirm — it never stops anything itself. */
+/** The palette's live-link entries. "Live chat" (the drawer) while any link is live here. "Stop all"
+ * appears wherever the owner could have links to stop (`showsStopAll`: a link listed here, OR a Pro
+ * license — its links on other machines are invisible here), and its `run` opens the confirm — it
+ * never stops anything itself. */
export function liveLinkCommands(o: {
activeLinks: number
/** Pro is active on this machine (`useEntitlement` `isPremium`). */
@@ -293,7 +294,10 @@ export function liveLinkCommands(o: {
/** `isBrowserRuntime()`: no license layer there (R43), so nothing to stop. */
serverEdition: boolean
icon: ReactNode
+ chatIcon: ReactNode
manage: () => void
+ /** Open the Live chat drawer (on the link picked last). */
+ openChat: () => void
confirmStopAll: () => void
}): Command[] {
return [
@@ -304,6 +308,18 @@ export function liveLinkCommands(o: {
icon: o.icon,
run: o.manage
},
+ ...(o.activeLinks > 0
+ ? [
+ {
+ id: 'live-chat',
+ label: 'Live chat',
+ hint: 'live link viewers messages reply people kick control',
+ section: 'View',
+ icon: o.chatIcon,
+ run: o.openChat
+ }
+ ]
+ : []),
...(showsStopAll({ serverEdition: o.serverEdition, entitled: o.entitled, activeLinks: o.activeLinks })
? [
{
diff --git a/src/renderer/lib/nodeterm-events.test.ts b/src/renderer/lib/nodeterm-events.test.ts
index 26cfa5a4a..cdd49083f 100644
--- a/src/renderer/lib/nodeterm-events.test.ts
+++ b/src/renderer/lib/nodeterm-events.test.ts
@@ -59,3 +59,22 @@ describe('every nodeterm CustomEvent the renderer dispatches has a listener', ()
expect(orphans).toEqual([])
})
})
+
+// The LIVE chip's "Open chat" (LiveLinkPopover) asks for the Live chat drawer. Task 7 wired a stub
+// listener that opened nothing; the drawer's listener REPLACES it — two listeners would open the
+// drawer twice, a stub alone opens nothing.
+describe('nodeterm:live-chat', () => {
+ const listened = names(/addEventListener\(\s*['"](nodeterm:live-chat)['"]/g)
+
+ it('has exactly one listener, in Canvas', () => {
+ expect((listened.get('nodeterm:live-chat') ?? []).map((f) => f.split(path.sep).join('/'))).toEqual(['canvas/Canvas.tsx'])
+ })
+
+ it('that listener opens the drawer on the link it names', () => {
+ const src = fs.readFileSync(path.join(RENDERER, 'canvas/Canvas.tsx'), 'utf8').replace(/\r\n/g, '\n')
+ const at = src.indexOf("window.addEventListener('nodeterm:live-chat'")
+ const effect = src.slice(src.lastIndexOf('useEffect(', at), at)
+ expect(effect).toContain("nextLiveChat(s, { kind: 'open', linkId })")
+ expect(effect).toContain('writeLiveChatLink(linkId)')
+ })
+})
diff --git a/src/renderer/lib/pinnedInsets.test.ts b/src/renderer/lib/pinnedInsets.test.ts
index 4e46f307f..295f64fb4 100644
--- a/src/renderer/lib/pinnedInsets.test.ts
+++ b/src/renderer/lib/pinnedInsets.test.ts
@@ -33,6 +33,11 @@ describe('insetsForPanels', () => {
})
})
+ it('two right-hugging pinned drawers side by side (Explorer, Live chat docked to its left) inset up to the far one', () => {
+ // Explorer: 320px at right gap 22 → x 858–1178; Live chat beside it, 8px further left → 530–850.
+ expect(insetsForPanels(WRAP, [rect(858, 1178), rect(530, 850)])).toEqual({ left: 0, right: 670 })
+ })
+
it('keeps the widest panel per edge rather than summing them', () => {
expect(insetsForPanels(WRAP, [rect(14, 314), rect(14, 474)])).toEqual({ left: 474, right: 0 })
})
diff --git a/src/renderer/state/watchLinks.ts b/src/renderer/state/watchLinks.ts
index 893e88eed..93660dd29 100644
--- a/src/renderer/state/watchLinks.ts
+++ b/src/renderer/state/watchLinks.ts
@@ -5,6 +5,7 @@
// serialized into a project, a canvas op or the board — link state is not canvas content, and a
// guard test (lib/live-link.guard.test.ts) keeps it out of every shared type. A reload rebuilds it
// from `list()`; chat history comes back from `chatHistory()` (core keeps it in memory only).
+import { useEffect } from 'react'
import { create } from 'zustand'
import type { NodeTerminalApi } from '@shared/types'
import type { WatchChatMessage, WatchLinkNotice, WatchLinkView } from '@shared/watch-link-types'
@@ -148,6 +149,25 @@ export const useWatchLinks = create<WatchLinksState>((set) => ({
markRead: (linkId) => set((s) => (s.unread[linkId] ? { unread: { ...s.unread, [linkId]: 0 } } : s))
}))
+/**
+ * The thread rule for a link's chat on screen — the chip's popover and the Live chat drawer, ONE
+ * definition: what lands while it is shown is read as it arrives (`viewLinkThread`, N2); what arrived
+ * before is read on open (`markRead`, H21), which clears the chip's count; and core's history is asked
+ * once (a reload, or messages pushed before this renderer subscribed — the store merges the two).
+ */
+export function useLinkThread(linkId: string, api: Pick<NodeTerminalApi['watchLink'], 'chatHistory'>): void {
+ useEffect(() => viewLinkThread(linkId), [linkId])
+ useEffect(() => {
+ void api.chatHistory(linkId).then(
+ (m) => useWatchLinks.getState().setChat(linkId, m),
+ () => {}
+ )
+ }, [api, linkId])
+ useEffect(() => {
+ useWatchLinks.getState().markRead(linkId)
+ }, [linkId])
+}
+
/**
* A PRIMITIVE signature of everything one node's chip shows (tone, label, title, unread count) —
* '' when the node has no link. The chip subscribes to this, never to a map: a string compares by
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 102327b7c..f831f7b66 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -11733,7 +11733,7 @@ button.pull-checks__name {
.live-pop:focus {
outline: none;
}
-.live-pop p {
+:is(.live-pop, .live-chat__body) p {
margin: 0;
}
.live-pop__link + .live-pop__link {
@@ -11760,13 +11760,13 @@ button.pull-checks__name {
margin-top: 2px;
overflow-wrap: anywhere;
}
-.live-pop p.live-pop__status {
+:is(.live-pop, .live-chat__body) p.live-pop__status {
margin-top: 6px;
padding: 6px 8px;
border-radius: 6px;
background: color-mix(in srgb, var(--state-warning) 12%, transparent);
}
-.live-pop p.live-pop__status--refused {
+:is(.live-pop, .live-chat__body) p.live-pop__status--refused {
background: rgba(var(--tint-rgb), 0.06);
}
.live-pop__actions {
@@ -11774,12 +11774,12 @@ button.pull-checks__name {
gap: 6px;
margin: 8px 0;
}
-.live-pop .confirm__btn.live-pop__btn {
+:is(.live-pop, .live-chat__body) .confirm__btn.live-pop__btn {
padding: 3px 10px;
border-radius: 6px;
font-size: 12px;
}
-.live-pop p.live-pop__error {
+:is(.live-pop, .live-chat__body) p.live-pop__error {
margin: 4px 0;
color: var(--danger);
}
@@ -11795,10 +11795,10 @@ button.pull-checks__name {
gap: 6px;
padding: 2px 0;
}
-.live-pop .live-pop__kick {
+:is(.live-pop, .live-chat__body) .live-pop__kick {
margin-left: auto;
}
-.live-pop p.live-pop__note {
+:is(.live-pop, .live-chat__body) p.live-pop__note {
margin-top: 4px;
font-size: 11px;
}
@@ -11887,7 +11887,7 @@ button.pull-checks__name {
.live-pop__password .confirm__input {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
}
-.live-pop p.live-pop__invalid {
+:is(.live-pop, .live-chat__body) p.live-pop__invalid {
margin: 4px 0 0;
color: var(--danger);
font-size: 11px;
@@ -11900,6 +11900,185 @@ button.pull-checks__name {
border-radius: 50%;
background: var(--state-working);
}
+/* The Live chat drawer (LiveChatDrawer): the Explorer drawer's shell and pin, with the popover's
+ owner controls inside it (the `:is(.live-pop, .live-chat__body)` rules above are shared). Raised
+ over the kanban card modal (scrim 55) while one is open — the card's LIVE chip opens it — whatever
+ the pin; pinned beside a pinned Explorer, docked one Explorer width (320px) and a gap to its left.
+ The `.drawer` shell is already a Liquid Glass text surface with its blur, and nothing inside paints
+ a surface token. Tokens only: the viewer-name hues come from the web page's table
+ (lib/liveChatLook) as `--live-name`, darkened toward the ink on the light theme, where the
+ page's near-black-tuned yellows and cyans would not read. */
+.drawer-overlay.drawer-overlay--raised {
+ z-index: 57;
+}
+.drawer-overlay--beside .drawer--pinned {
+ right: calc(var(--float-gap) + 320px + 8px);
+}
+.live-chat:focus {
+ outline: none;
+}
+.live-chat__body {
+ flex: 1 1 auto;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ padding: 8px 14px 12px;
+ font-size: 12.5px;
+ line-height: 1.4;
+}
+.live-chat__link {
+ flex: none;
+ padding-bottom: 8px;
+ border-bottom: 1px solid var(--border);
+}
+.live-chat__body .confirm__input.live-chat__select {
+ margin: 0 0 8px;
+ padding: 5px 8px;
+ font-size: 12.5px;
+}
+.live-chat__linkhead {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 8px;
+}
+.live-chat__goto {
+ flex: none;
+ padding: 0;
+ border: 0;
+ background: none;
+ color: var(--accent-text);
+ font: inherit;
+ font-size: 12px;
+ white-space: nowrap;
+ cursor: pointer;
+}
+.live-chat__goto:hover {
+ text-decoration: underline;
+}
+.live-chat__people {
+ flex: none;
+ max-height: 40%;
+ overflow-y: auto;
+ padding: 8px 0;
+ border-bottom: 1px solid var(--border);
+}
+/* A Viewer link has no chat: People takes the drawer. */
+.live-chat__people.live-chat__people--only {
+ flex: 1 1 auto;
+ max-height: none;
+ border-bottom: 0;
+}
+.live-chat__heading {
+ margin: 0 0 6px;
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.4px;
+ text-transform: uppercase;
+ color: var(--muted);
+}
+.live-chat__viewers {
+ margin: 4px 0;
+ padding: 0;
+ list-style: none;
+}
+.live-chat__viewers li {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 2px 0;
+}
+.live-chat__chat {
+ flex: 1 1 auto;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ padding-top: 8px;
+}
+/* The list scrolls; the "N new messages" pill floats over its foot. */
+.live-chat__listwrap {
+ position: relative;
+ flex: 1 1 auto;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+}
+.live-chat__body p.live-chat__empty {
+ margin: 0 0 6px;
+}
+.live-chat__list {
+ flex: 1 1 auto;
+ min-height: 0;
+ margin: 0;
+ padding: 0;
+ overflow-y: auto;
+ list-style: none;
+}
+/* One dense line per message, like the viewer page: time, badge, name, text. */
+.live-chat__msg {
+ padding: 2px 0;
+ overflow-wrap: anywhere;
+}
+.live-chat__time {
+ margin-right: 6px;
+ color: var(--muted);
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+}
+/* The owner's own line, marked by the HOST's word: ink on a success wash, the status-chip recipe. */
+.live-chat__badge {
+ display: inline-block;
+ margin-right: 5px;
+ padding: 0 5px;
+ border: 1px solid color-mix(in srgb, var(--state-success) 45%, transparent);
+ border-radius: 4px;
+ background: color-mix(in srgb, var(--state-success) 16%, transparent);
+ color: var(--text);
+ font-size: 10px;
+ font-weight: 700;
+ line-height: 15px;
+ vertical-align: 1px;
+}
+.live-chat__name {
+ color: var(--live-name, var(--text));
+ font-weight: 700;
+}
+.live-chat__msg--sharer .live-chat__name {
+ --live-name: var(--success);
+}
+:root[data-theme='light'] .live-chat__name {
+ color: color-mix(in srgb, var(--live-name, var(--text)) 55%, var(--text-strong));
+}
+.live-chat__colon {
+ color: var(--muted);
+}
+.live-chat__text {
+ color: var(--text);
+ white-space: pre-wrap;
+}
+.live-chat__body .confirm__btn.live-chat__more {
+ position: absolute;
+ bottom: 8px;
+ left: 50%;
+ transform: translateX(-50%);
+ padding: 3px 12px;
+ border-radius: 999px;
+ font-size: 12px;
+ white-space: nowrap;
+}
+.live-chat__reply {
+ flex: none;
+ display: flex;
+ gap: 6px;
+ margin-top: 8px;
+}
+.live-chat__body .confirm__input.live-chat__input {
+ flex: 1 1 auto;
+ min-width: 0;
+ margin: 0;
+ padding: 5px 8px;
+ font-size: 12.5px;
+}
/* The create dialog (LiveLinkDialog): the `.confirm` shell, a little wider for the URL. */
.confirm.live-dialog {
width: 460px;
diff --git a/src/renderer/styles.live-chat.test.ts b/src/renderer/styles.live-chat.test.ts
new file mode 100644
index 000000000..d676e7e43
--- /dev/null
+++ b/src/renderer/styles.live-chat.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it } from 'vitest'
+import { readFileSync } from 'node:fs'
+import { join } from 'node:path'
+
+/**
+ * The Live chat drawer's stacking and its colours (components/LiveChatDrawer.tsx). jsdom has no
+ * layout, so where the drawer SITS is pinned here: a z-index typo puts it under the board or under
+ * the card modal it was opened from, and nothing rendered in CI would notice.
+ */
+const CSS = readFileSync(join(__dirname, 'styles.css'), 'utf8').replace(/\r\n/g, '\n')
+const NO_COMMENTS = CSS.replace(/\/\*[\s\S]*?\*\//g, '')
+
+/** Every rule body whose selector list contains `selector` exactly, in source order. */
+function bodies(selector: string): { at: number; body: string }[] {
+ const out: { at: number; body: string }[] = []
+ const re = /([^{}]+)\{([^{}]*)\}/g
+ let m: RegExpExecArray | null
+ while ((m = re.exec(NO_COMMENTS))) {
+ const sels = m[1].split(',').map((s) => s.replace(/\s+/g, ' ').trim())
+ if (sels.includes(selector)) out.push({ at: m.index, body: m[2] })
+ }
+ return out
+}
+const zOf = (body: string): number | null => {
+ const m = /z-index:\s*(\d+)/.exec(body)
+ return m ? Number(m[1]) : null
+}
+
+describe('Live chat drawer CSS', () => {
+ it('raised (a card modal is open, z 55) sits at 57, and wins over the pinned 26 wherever it is written', () => {
+ const raised = bodies('.drawer-overlay.drawer-overlay--raised')
+ expect(raised).toHaveLength(1)
+ expect(zOf(raised[0].body)).toBe(57)
+ // Higher specificity than `.drawer-overlay--pinned`, so source order cannot undo it.
+ const pinned = bodies('.drawer-overlay--pinned').find((r) => zOf(r.body) !== null)!
+ expect(zOf(pinned.body)).toBe(26)
+ })
+
+ it('beside the pinned Explorer: one Explorer width plus a gap further from the right edge', () => {
+ const beside = bodies('.drawer-overlay--beside .drawer--pinned')
+ expect(beside).toHaveLength(1)
+ expect(beside[0].body).toContain('right: calc(var(--float-gap) + 320px + 8px)')
+ })
+
+ it('no colour literal in the drawer\'s own rules — tokens only (the name hues come from the copied web table)', () => {
+ const own = [...NO_COMMENTS.matchAll(/([^{}]*\.live-chat[^{}]*)\{([^{}]*)\}/g)]
+ expect(own.length).toBeGreaterThan(5)
+ for (const [, head, body] of own) {
+ expect(body, head.trim()).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgba?\(\s*\d/)
+ }
+ })
+
+ it('viewer names keep their hue but are darkened toward the ink on the light theme', () => {
+ const light = bodies(":root[data-theme='light'] .live-chat__name")
+ expect(light).toHaveLength(1)
+ expect(light[0].body).toContain('color-mix(in srgb, var(--live-name, var(--text)) 55%, var(--text-strong))')
+ })
+})