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.

fix(renderer): live-link chip lets keys and drags through; popover isolates itself, says what failed

reviewf1ef97a43bbd
diff --git a/src/renderer/components/LiveLinkChip.surfaces.test.tsx b/src/renderer/components/LiveLinkChip.surfaces.test.tsx
index 6df950214..e6798c49b 100644
--- a/src/renderer/components/LiveLinkChip.surfaces.test.tsx
+++ b/src/renderer/components/LiveLinkChip.surfaces.test.tsx
@@ -61,7 +61,7 @@ let host: HTMLDivElement
let root: Root
beforeEach(() => {
resetDialogStack()
- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {} })
+ useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })
useAgentStatus.setState({ byId: {} } as never)
useProjects.setState({ activeProjectId: 'p1', projects: [] } as never)
vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })
@@ -87,14 +87,14 @@ const setLinks = (links: WatchLinkView[]): void => act(() => useWatchLinks.getSt
const click = (el: Element): void => act(() => void el.dispatchEvent(new MouseEvent('click', { bubbles: true })))
const pop = (): HTMLElement | null => document.querySelector<HTMLElement>('.live-pop')
-function card(onOpen = vi.fn()) {
+function card(onOpen = vi.fn(), onDropAt = vi.fn()) {
return (
<SessionCard
session={session}
onOpen={onOpen}
onDragStart={vi.fn()}
onDragEnd={vi.fn()}
- onDropAt={vi.fn()}
+ onDropAt={onDropAt}
onContext={vi.fn()}
/>
)
@@ -122,6 +122,20 @@ describe('LIVE chip — kanban card', () => {
click(document.querySelector('.live-pop__scrim')!)
expect(onOpen).not.toHaveBeenCalled()
})
+
+ it('another card dragged over this card\'s chip can still be dropped on the card (I1)', () => {
+ const onDropAt = vi.fn()
+ render(card(vi.fn(), onDropAt))
+ setLinks([link()])
+ const chip = host.querySelector('.live-chip')!
+ const over = new Event('dragover', { bubbles: true, cancelable: true })
+ act(() => void chip.dispatchEvent(over))
+ // The card's handler ran: it accepted the drop and drew its drop line.
+ expect(over.defaultPrevented).toBe(true)
+ expect(host.querySelector('.kanban-card')!.className).toMatch(/kanban-card--drop-(before|after)/)
+ act(() => void chip.dispatchEvent(new Event('drop', { bubbles: true, cancelable: true })))
+ expect(onDropAt).toHaveBeenCalledWith('n1', expect.stringMatching(/before|after/))
+ })
})
describe('LIVE chip — card modal header', () => {
diff --git a/src/renderer/components/LiveLinkChip.test.tsx b/src/renderer/components/LiveLinkChip.test.tsx
index 0ea99fdce..b80be2dff 100644
--- a/src/renderer/components/LiveLinkChip.test.tsx
+++ b/src/renderer/components/LiveLinkChip.test.tsx
@@ -9,7 +9,13 @@ import { useWatchLinks } from '../state/watchLinks'
import { useBoardLog } from '../state/boardLog'
import { useProjects } from '../state/projects'
import { popDialog, pushDialog, resetDialogStack } from './dialog-stack'
-import { KICK_NOTE, STOP_FAILED_MESSAGE } from '../lib/liveLink'
+import {
+ CHAT_NOT_SENT_MESSAGE,
+ KICK_FAILED_MESSAGE,
+ KICK_NOT_DONE_MESSAGE,
+ KICK_NOTE,
+ STOP_FAILED_MESSAGE
+} from '../lib/liveLink'
const boardApi = { tag: 'local-api' }
vi.mock('../session/session', () => ({
@@ -43,7 +49,13 @@ const msg = (id: string, over: Partial<WatchChatMessage> = {}): WatchChatMessage
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) => null),
+ 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[]> => [])
}
const writeText = vi.fn()
@@ -52,7 +64,7 @@ let host: HTMLDivElement
let root: Root
beforeEach(() => {
resetDialogStack()
- useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {} })
+ useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })
useProjects.setState({ projects: [] } as never)
vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })
for (const f of Object.values(api)) f.mockClear()
@@ -103,11 +115,16 @@ describe('LiveLinkChip', () => {
it('follows the store: offline, refused, the unread dot, and gone again', () => {
render(<LiveLinkChip nodeId="n1" />)
+ setLinks([link()])
+ expect(host.querySelector('.live-chip__dot')).not.toBeNull()
setLinks([link({ status: 'reconnecting' })])
expect(chip()!.className).toContain('live-chip--offline')
expect(chip()!.textContent).toBe('LIVE · offline')
+ // The broadcast dot is LIVE's alone (N6).
+ expect(host.querySelector('.live-chip__dot')).toBeNull()
setLinks([link({ status: 'refused' })])
expect(chip()!.className).toContain('live-chip--refused')
+ expect(host.querySelector('.live-chip__dot')).toBeNull()
expect(host.querySelector('.live-chip__unread')).toBeNull()
act(() => useWatchLinks.getState().addChat('L', msg('1')))
expect(host.querySelector('.live-chip__unread')).not.toBeNull()
@@ -201,7 +218,83 @@ describe('LiveLinkPopover', () => {
}
})
- it('a click or middle press inside the popover never reaches the surface it sits in', () => {
+ it('keys pressed on the chip reach the window — also after the popover hands focus back (I1)', () => {
+ const globalKeys = vi.fn()
+ window.addEventListener('keydown', globalKeys)
+ try {
+ render(<LiveLinkChip nodeId="n1" />)
+ setLinks([link()])
+ act(() => chip()!.focus())
+ click(chip()!)
+ act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))
+ expect(pop()).toBeNull()
+ expect(document.activeElement).toBe(chip())
+ globalKeys.mockClear()
+ act(() => void chip()!.dispatchEvent(new KeyboardEvent('keydown', { key: 'k', metaKey: true, bubbles: true })))
+ expect(globalKeys).toHaveBeenCalledTimes(1)
+ } finally {
+ window.removeEventListener('keydown', globalKeys)
+ }
+ })
+
+ it('a drag over the chip reaches the surface under it (I1)', () => {
+ const onDragOver = vi.fn()
+ const onDrop = vi.fn()
+ render(
+ <div onDragOver={onDragOver} onDrop={onDrop}>
+ <LiveLinkChip nodeId="n1" />
+ </div>
+ )
+ setLinks([link()])
+ act(() => void chip()!.dispatchEvent(new Event('dragover', { bubbles: true, cancelable: true })))
+ act(() => void chip()!.dispatchEvent(new Event('drop', { bubbles: true, cancelable: true })))
+ expect(onDragOver).toHaveBeenCalledTimes(1)
+ expect(onDrop).toHaveBeenCalledTimes(1)
+ })
+
+ it('keys typed inside the popover reach neither the surface nor the window', () => {
+ const globalKeys = vi.fn()
+ const onKeyDown = vi.fn()
+ window.addEventListener('keydown', globalKeys)
+ try {
+ render(
+ <div onKeyDown={onKeyDown}>
+ <LiveLinkChip nodeId="n1" />
+ </div>
+ )
+ setLinks([link({ role: 'commenter' })])
+ click(chip()!)
+ const input = pop()!.querySelector<HTMLInputElement>('.live-pop__input')!
+ act(() => void input.dispatchEvent(new KeyboardEvent('keydown', { key: 'j', bubbles: true })))
+ act(() => void input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Delete', bubbles: true })))
+ expect(onKeyDown).not.toHaveBeenCalled()
+ expect(globalKeys).not.toHaveBeenCalled()
+ expect(pop()).not.toBeNull()
+ } finally {
+ window.removeEventListener('keydown', globalKeys)
+ }
+ })
+
+ it('a failed Kick says so: not reached, or nobody to kick (M3)', async () => {
+ render(<LiveLinkChip nodeId="n1" />)
+ setLinks([link({ viewers: [{ viewerId: 'v1', name: null, joinedAt: 0 }] })])
+ click(chip()!)
+ api.kick.mockImplementationOnce(async () => {
+ throw new Error('socket down')
+ })
+ click(pop()!.querySelector('.live-pop__kick')!)
+ await flush()
+ expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(KICK_FAILED_MESSAGE)
+ api.kick.mockImplementationOnce(async () => false)
+ click(pop()!.querySelector('.live-pop__kick')!)
+ await flush()
+ expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(KICK_NOT_DONE_MESSAGE)
+ click(pop()!.querySelector('.live-pop__kick')!)
+ await flush()
+ expect(pop()!.querySelector('[role="alert"]')).toBeNull()
+ })
+
+ it('a click or middle press on the chip or inside the popover never reaches the surface it sits in', () => {
const onClick = vi.fn()
const onMouseDown = vi.fn()
render(
@@ -210,6 +303,8 @@ describe('LiveLinkPopover', () => {
</div>
)
setLinks([link()])
+ // The chip's own press and click stop too (a sessions row ends the session on a middle press).
+ act(() => void chip()!.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 1 })))
click(chip()!)
act(() => void pop()!.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 1 })))
click(pop()!)
@@ -287,6 +382,56 @@ describe('LiveLinkPopover — Commenter chat', () => {
expect(api.sendChat).toHaveBeenCalledWith('L', 'on it')
expect(input.value).toBe('')
expect(useWatchLinks.getState().chats.L ?? []).toHaveLength(0)
+ expect(pop()!.querySelector('[role="alert"]')).toBeNull()
+ })
+
+ it('a reply core did not take keeps the draft and says so (M3)', async () => {
+ render(<LiveLinkChip nodeId="n1" />)
+ setLinks([link({ role: 'commenter' })])
+ click(chip()!)
+ const input = pop()!.querySelector<HTMLInputElement>('.live-pop__input')!
+ const type = (v: string): void =>
+ act(() => {
+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, v)
+ input.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ const submit = (): void =>
+ act(() => void pop()!.querySelector('form')!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })))
+ type('hello')
+ api.sendChat.mockImplementationOnce(async () => null)
+ submit()
+ await flush()
+ expect(input.value).toBe('hello')
+ expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(CHAT_NOT_SENT_MESSAGE)
+ api.sendChat.mockImplementationOnce(async () => {
+ throw new Error('socket down')
+ })
+ submit()
+ await flush()
+ expect(input.value).toBe('hello')
+ expect(pop()!.querySelector('[role="alert"]')!.textContent).toBe(CHAT_NOT_SENT_MESSAGE)
+ submit()
+ await flush()
+ expect(input.value).toBe('')
+ expect(pop()!.querySelector('[role="alert"]')).toBeNull()
+ })
+
+ it('while the thread is open a new message never shows as unread, not even for one render (N2)', async () => {
+ render(<LiveLinkChip nodeId="n1" />)
+ setLinks([link({ role: 'commenter' })])
+ click(chip()!)
+ await flush()
+ const counts: number[] = []
+ const off = useWatchLinks.subscribe((st) => counts.push(st.unread.L ?? 0))
+ act(() => useWatchLinks.getState().addChat('L', msg('1')))
+ act(() => useWatchLinks.getState().addChat('L', msg('2')))
+ off()
+ expect(counts.every((n) => n === 0)).toBe(true)
+ expect(host.querySelector('.live-chip__unread')).toBeNull()
+ // Closed: the next one counts again.
+ act(() => void window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' })))
+ act(() => useWatchLinks.getState().addChat('L', msg('3')))
+ expect(useWatchLinks.getState().unread.L).toBe(1)
})
it('"Copy to card comments" writes one comment as the owner, on this machine\'s project', () => {
diff --git a/src/renderer/components/LiveLinkChip.tsx b/src/renderer/components/LiveLinkChip.tsx
index 237939297..537471593 100644
--- a/src/renderer/components/LiveLinkChip.tsx
+++ b/src/renderer/components/LiveLinkChip.tsx
@@ -35,26 +35,12 @@ export const LiveLinkChip = memo(function LiveLinkChip({
const unread = links.reduce((n, l) => n + (s.unread[l.linkId] ?? 0), 0)
const stop = (e: React.SyntheticEvent): void => e.stopPropagation()
return (
- // The chip sits INSIDE a clickable card, a draggable node header and a sessions row that
- // closes on a middle click, and the popover is a body portal whose React events still bubble
- // through this tree. Every event is stopped here, or a click in the popover would also open the
- // card, a middle click would end the session, and a text drag would start a card drag.
- <span
- className="live-chip-wrap"
- onClick={stop}
- onDoubleClick={stop}
- onMouseDown={stop}
- onMouseUp={stop}
- onPointerDown={stop}
- onPointerUp={stop}
- onContextMenu={stop}
- onKeyDown={stop}
- onKeyUp={stop}
- onDragStart={stop}
- onDragOver={stop}
- onDrop={stop}
- onWheel={stop}
- >
+ <>
+ {/* The chip sits INSIDE a clickable card, a draggable node header and a sessions row that
+ closes on a middle click, so its own click-related events stop here. Only those: keys, drags
+ and the wheel pass, or with focus on the chip (where the popover hands it back) every global
+ shortcut went dead, and a card dragged over another card's chip could not be dropped. The
+ popover isolates ITS events at its own portal roots (LiveLinkPopover). */}
<button
type="button"
className={`live-chip live-chip--${view.tone} nodrag${className ? ` ${className}` : ''}`}
@@ -62,16 +48,22 @@ export const LiveLinkChip = memo(function LiveLinkChip({
aria-label={unread > 0 ? `${view.label}, ${unread} unread chat ${unread === 1 ? 'message' : 'messages'}` : view.label}
aria-haspopup="dialog"
aria-expanded={!!anchor}
+ onMouseDown={stop}
+ onPointerDown={stop}
+ onDoubleClick={stop}
+ onContextMenu={stop}
onClick={(e) => {
+ e.stopPropagation()
const r = e.currentTarget.getBoundingClientRect()
setAnchor((cur) => (cur ? null : { top: r.top, bottom: r.bottom, left: r.left }))
}}
>
- <span className="live-chip__dot" aria-hidden="true" />
+ {/* The broadcast dot is the LIVE state's (spec: `● LIVE`); offline and refused carry none. */}
+ {view.tone === 'live' && <span className="live-chip__dot" aria-hidden="true" />}
{view.label}
{unread > 0 && <span className="live-chip__unread" aria-hidden="true" />}
</button>
{anchor && <LiveLinkPopover nodeId={nodeId} anchor={anchor} onClose={close} />}
- </span>
+ </>
)
})
diff --git a/src/renderer/components/LiveLinkPopover.tsx b/src/renderer/components/LiveLinkPopover.tsx
index 3da70616e..12ebd50c1 100644
--- a/src/renderer/components/LiveLinkPopover.tsx
+++ b/src/renderer/components/LiveLinkPopover.tsx
@@ -7,9 +7,12 @@ import { CHAT_TEXT_MAX, type WatchChatMessage } from '@shared/watch-link/protoco
import { useDialogStack } from './dialog-stack'
import { useMenuFlip } from '../ui/useMenuFlip'
import {
+ CHAT_NOT_SENT_MESSAGE,
commentFromChat,
formatClock,
formatRemaining,
+ KICK_FAILED_MESSAGE,
+ KICK_NOT_DONE_MESSAGE,
KICK_NOTE,
ROLE_LABEL,
statusLine,
@@ -17,7 +20,7 @@ import {
viewerName
} from '../lib/liveLink'
import { thisMachine } from '../lib/machineName'
-import { EMPTY_LINKS, useWatchLinks } from '../state/watchLinks'
+import { EMPTY_LINKS, useWatchLinks, viewLinkThread } from '../state/watchLinks'
import { useBoardLog } from '../state/boardLog'
import { useProjects } from '../state/projects'
import { sessionForProject } from '../session/session'
@@ -31,6 +34,35 @@ export interface PopoverAnchor {
const EMPTY_CHAT: WatchChatMessage[] = []
+const stop = (e: React.SyntheticEvent): void => e.stopPropagation()
+/**
+ * The popover is a body portal, but its React events still bubble through the REACT tree — into the
+ * chip's surface: a card that opens on click and drags, a node header, a sessions row that ends the
+ * session on a middle click, the canvas's own window listeners (React stops a synthetic event at the
+ * portal's container, before the window). So every event is stopped at the portal's two roots, the
+ * scrim and the panel — and only there: the chip itself lets keys and drags through (LiveLinkChip).
+ */
+const ISOLATE = {
+ onClick: stop,
+ onDoubleClick: stop,
+ onMouseDown: stop,
+ onMouseUp: stop,
+ onPointerDown: stop,
+ onPointerUp: stop,
+ onContextMenu: stop,
+ onKeyDown: stop,
+ onKeyUp: stop,
+ onDragStart: stop,
+ onDragOver: stop,
+ onDrop: stop,
+ onWheel: stop,
+ onFocus: stop,
+ onBlur: stop,
+ onChange: stop,
+ onInput: stop,
+ onSubmit: stop
+} as const
+
function useNow(ms: number): number {
const [now, setNow] = useState(() => Date.now())
useEffect(() => {
@@ -105,14 +137,20 @@ export function LiveLinkPopover({
return createPortal(
<>
<div
+ {...ISOLATE}
className="live-pop__scrim"
- onClick={onClose}
+ onClick={(e) => {
+ e.stopPropagation()
+ onClose()
+ }}
onContextMenu={(e) => {
e.preventDefault()
+ e.stopPropagation()
onClose()
}}
/>
<div
+ {...ISOLATE}
ref={flip.ref}
className="live-pop nodrag nowheel"
style={{ top: flip.top, left: flip.left }}
@@ -204,7 +242,15 @@ const LinkBlock = memo(function LinkBlock({
type="button"
className="confirm__btn live-pop__btn live-pop__kick"
title={KICK_NOTE}
- onClick={() => void api.kick(link.linkId, v.viewerId).catch(() => {})}
+ onClick={() => {
+ setError(null)
+ api.kick(link.linkId, v.viewerId).then(
+ (ok) => {
+ if (!ok) setError(KICK_NOT_DONE_MESSAGE)
+ },
+ () => setError(KICK_FAILED_MESSAGE)
+ )
+ }}
>
Kick
</button>
@@ -227,7 +273,10 @@ function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string }): Rea
const [draft, setDraft] = useState('')
const [copiedIds, setCopiedIds] = useState<ReadonlySet<string>>(() => new Set())
const [copyError, setCopyError] = useState(false)
+ const [sendError, setSendError] = useState(false)
const threadRef = useRef<HTMLOListElement>(null)
+ // 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(() => {
@@ -236,14 +285,18 @@ function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string }): Rea
() => {}
)
}, [api, linkId])
- // Open = read: on open, and again for every message that lands while it is open (H21). 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 : ''
+ // 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])
+ // Follow the newest message. Keyed on the LAST message's id, not the length — at the 200-message
+ // cap the length stops changing.
+ const lastId = chat.length > 0 ? chat[chat.length - 1].id : ''
+ useEffect(() => {
const el = threadRef.current
if (el) el.scrollTop = el.scrollHeight
- }, [linkId, lastId])
+ }, [lastId])
return (
<div className="live-pop__chat">
{chat.length === 0 ? (
@@ -287,15 +340,29 @@ function ChatThread({ linkId, nodeId }: { linkId: string; nodeId: string }): Rea
No project on {thisMachine()} holds this terminal, so there is no card to comment on.
</p>
)}
+ {sendError && (
+ <p className="live-pop__error" role="alert">
+ {CHAT_NOT_SENT_MESSAGE}
+ </p>
+ )}
<form
className="live-pop__reply"
onSubmit={(e) => {
e.preventDefault()
const text = draft.trim()
if (!text) return
- setDraft('')
- // The reply comes back through the chat push (core echoes the owner's own message).
- api.sendChat(linkId, text).catch(() => setDraft((d) => d || text))
+ setSendError(false)
+ // The reply comes back through the chat push (core echoes the owner's own message), so
+ // nothing is added here. The box is cleared only once core took it (unless the owner has
+ // typed on since); a null answer (no host for the link, or nothing left after cleaning) or
+ // a rejection keeps the draft and says so.
+ api.sendChat(linkId, text).then(
+ (sent) => {
+ if (sent) setDraft((d) => (d.trim() === text ? '' : d))
+ else setSendError(true)
+ },
+ () => setSendError(true)
+ )
}}
>
<input
diff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.ts
index c10e91104..a0696fe64 100644
--- a/src/renderer/lib/liveLink.test.ts
+++ b/src/renderer/lib/liveLink.test.ts
@@ -3,12 +3,15 @@
// through lib/machineName, and a literal "this computer" must not depend on the OS running the suite.
import { describe, it, expect } from 'vitest'
import {
+ CHAT_NOT_SENT_MESSAGE,
chipView,
commentFromChat,
createErrorMessage,
DEFAULT_TTL,
formatClock,
formatRemaining,
+ KICK_FAILED_MESSAGE,
+ KICK_NOT_DONE_MESSAGE,
noticeText,
NOT_IN_OPEN_PROJECT,
PRO_GATE_FEATURE,
@@ -102,11 +105,22 @@ describe('statusLine (H9)', () => {
})
describe('time', () => {
- it('remaining time', () => {
- expect(formatRemaining(60 * 60_000 + 1, 0)).toBe('ends in 1 h')
- expect(formatRemaining(42 * 60_000, 0)).toBe('ends in 42 min')
- expect(formatRemaining(30_000, 0)).toBe('ends in under a minute')
+ it('remaining time, hours AND minutes past the hour (M4)', () => {
+ const MIN = 60_000
expect(formatRemaining(0, 5)).toBe('ended')
+ expect(formatRemaining(5, 5)).toBe('ended')
+ expect(formatRemaining(30_000, 0)).toBe('ends in under a minute')
+ expect(formatRemaining(MIN - 1, 0)).toBe('ends in under a minute')
+ expect(formatRemaining(MIN, 0)).toBe('ends in 1 min')
+ expect(formatRemaining(42 * MIN, 0)).toBe('ends in 42 min')
+ expect(formatRemaining(60 * MIN - 1, 0)).toBe('ends in 59 min')
+ expect(formatRemaining(60 * MIN, 0)).toBe('ends in 1 h')
+ expect(formatRemaining(60 * MIN + 1, 0)).toBe('ends in 1 h')
+ expect(formatRemaining(61 * MIN, 0)).toBe('ends in 1 h 1 min')
+ expect(formatRemaining(120 * MIN - 1, 0)).toBe('ends in 1 h 59 min')
+ expect(formatRemaining(120 * MIN, 0)).toBe('ends in 2 h')
+ expect(formatRemaining(24 * 60 * MIN - 1, 0)).toBe('ends in 23 h 59 min')
+ expect(formatRemaining(24 * 60 * MIN, 0)).toBe('ends in 24 h')
})
it('a clock time is hours and minutes, never seconds (H25)', () => {
const at = new Date(2026, 9, 1, 15, 42, 37).getTime()
@@ -184,9 +198,9 @@ describe('noticeText', () => {
)
})
- it('not-persistent names no cause it did not measure (H7, H26)', () => {
+ it('not-persistent says only the new link is unsaved, and names no cause (H7, H26, R55)', () => {
expect(noticeText({ kind: 'not-persistent' })).toBe(
- "Live links aren't being saved on this computer right now. They keep working until you quit."
+ "The live link you just created isn't saved on this computer: it works until you quit. Links created before it are still saved."
)
})
@@ -219,6 +233,9 @@ describe('copy Task 17 reads (R47, R48, R52, H11, H23, H26)', () => {
'Stop every live link on your license? This also ends links shared from other computers. Viewers are disconnected at once.'
)
expect(STOP_FAILED_MESSAGE).toBe("The stop didn't reach nodeterm — try again.")
+ expect(KICK_FAILED_MESSAGE).toBe("The kick didn't reach nodeterm — try again.")
+ expect(KICK_NOT_DONE_MESSAGE).toBe('That viewer was not disconnected — they may already have left.')
+ expect(CHAT_NOT_SENT_MESSAGE).toBe("Your reply wasn't sent — viewers didn't see it.")
expect(NOT_IN_OPEN_PROJECT).toBe('not in an open project')
// UpgradeDialog appends " is a Pro feature" (R52).
expect(`${PRO_GATE_FEATURE} is a Pro feature`).toBe('Sharing a live link is a Pro feature')
diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.ts
index 7bb823486..884b79731 100644
--- a/src/renderer/lib/liveLink.ts
+++ b/src/renderer/lib/liveLink.ts
@@ -56,6 +56,12 @@ export const PRO_GATE_FEATURE = 'Sharing a live link'
export const SAVE_FIRST_MESSAGE = "Save the canvas first — this terminal isn't saved yet. Nothing was shared."
/** H23: `revoke`/`revokeAll` rejected (the Server Edition's socket was down). */
export const STOP_FAILED_MESSAGE = "The stop didn't reach nodeterm — try again."
+/** Kick rejected (the same dropped socket). */
+export const KICK_FAILED_MESSAGE = "The kick didn't reach nodeterm — try again."
+/** Kick answered false: core found no connected viewer by that id (or its host could not end it). */
+export const KICK_NOT_DONE_MESSAGE = 'That viewer was not disconnected — they may already have left.'
+/** `sendChat` answered null or rejected: nothing reached the viewers; the draft is kept. */
+export const CHAT_NOT_SENT_MESSAGE = "Your reply wasn't sent — viewers didn't see it."
/** R48: Stop all revokes every link of the LICENSE, other machines included — both entry points confirm. */
export const STOP_ALL_PALETTE_LABEL = 'Stop all live links (every machine on this license)'
export const STOP_ALL_BUTTON = 'Stop all'
@@ -105,12 +111,17 @@ export function statusLine(status: WatchLinkView['status']): string | null {
return null
}
+/** How long a link still runs. Hours AND minutes past the hour: a floored "1 h" for 1 h 59 min
+ * understated by up to an hour the one figure that says how long a broadcast goes on. */
export function formatRemaining(expiresAt: number, now: number): string {
const ms = expiresAt - now
if (ms <= 0) return 'ended'
if (ms < 60_000) return 'ends in under a minute'
const min = Math.floor(ms / 60_000)
- return min >= 60 ? `ends in ${Math.floor(min / 60)} h` : `ends in ${min} min`
+ if (min < 60) return `ends in ${min} min`
+ const h = Math.floor(min / 60)
+ const m = min % 60
+ return m === 0 ? `ends in ${h} h` : `ends in ${h} h ${m} min`
}
/** A wall-clock time for "until 15:42" / "since 14:05" — hours and minutes, in the user's locale (H25). */
@@ -175,10 +186,12 @@ export function noticeText(n: WatchLinkNotice): string | null {
switch (n.kind) {
case 'joined':
return `Someone started watching ${stripBidiControls(n.title)} (${n.viewers} watching).`
- // It covers "the keychain refused to seal" AND "the links file could not be read", and carries
- // no reason — so it names neither (H7).
+ // Two causes, no reason carried (H7, R55): the keychain refused to seal — only the link just
+ // created is lost at a restart, links read at boot or sealed earlier stay saved — or the links
+ // file could not be read. The renderer cannot tell them apart, so it says what the shared type
+ // documents as the default: only the new link.
case 'not-persistent':
- return `Live links aren't being saved on ${thisMachine()} right now. They keep working until you quit.`
+ return `The live link you just created isn't saved on ${thisMachine()}: it works until you quit. Links created before it are still saved.`
case 'ended': {
const title = stripBidiControls(n.title)
if (n.reason === 'expired') return `The live link to ${title} expired.`
diff --git a/src/renderer/state/watchLinks.test.ts b/src/renderer/state/watchLinks.test.ts
index 500d09b39..627b04d19 100644
--- a/src/renderer/state/watchLinks.test.ts
+++ b/src/renderer/state/watchLinks.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach } from 'vitest'
-import { EMPTY_LINKS, liveChipSig, startWatchLinkSync, useWatchLinks } from './watchLinks'
+import { EMPTY_LINKS, liveChipSig, startWatchLinkSync, useWatchLinks, viewLinkThread } from './watchLinks'
import type { WatchChatMessage, WatchLinkNotice, WatchLinkView } from '@shared/watch-link-types'
const link = (id: string, nodeId: string, over: Partial<WatchLinkView> = {}): WatchLinkView => ({
@@ -23,7 +23,7 @@ const msg = (id: string, from: 'viewer' | 'sharer' = 'viewer', at = 0): WatchCha
from
})
-beforeEach(() => useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {} }))
+beforeEach(() => useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false }))
describe('watchLinks store', () => {
it('indexes by node, in list order', () => {
@@ -49,6 +49,41 @@ describe('watchLinks store', () => {
expect(useWatchLinks.getState()).toBe(after)
})
+ it('compares EVERY field: a change to any one of them is a new object (M2)', () => {
+ // A fixture with every field of the type, iterated by key: a field added to WatchLinkView (and
+ // to this fixture, which the type forces) is covered without editing the comparison.
+ const base: WatchLinkView = link('a', 'n1', {
+ viewers: [{ viewerId: 'v', name: 'Eve', joinedAt: 5 }]
+ })
+ const bump = (v: unknown): unknown =>
+ typeof v === 'number' ? v + 1 : typeof v === 'string' ? `${v}x` : Array.isArray(v) ? [] : v
+ for (const key of Object.keys(base) as (keyof WatchLinkView)[]) {
+ useWatchLinks.setState({ links: [], byNode: {}, chats: {}, unread: {}, hydrated: false })
+ useWatchLinks.getState().setLinks([base])
+ const before = useWatchLinks.getState().links[0]
+ const changed = { ...base, [key]: bump(base[key]) } as WatchLinkView
+ expect(changed[key], key).not.toEqual(base[key])
+ useWatchLinks.getState().setLinks([changed])
+ expect(useWatchLinks.getState().links[0], key).not.toBe(before)
+ }
+ // Every field of a viewer, the name included (a viewer who starts chatting gains a name).
+ const viewer = base.viewers[0]
+ for (const key of Object.keys(viewer) as (keyof typeof viewer)[]) {
+ useWatchLinks.getState().setLinks([base])
+ const before = useWatchLinks.getState().links[0]
+ useWatchLinks.getState().setLinks([{ ...base, viewers: [{ ...viewer, [key]: bump(viewer[key]) }] }])
+ expect(useWatchLinks.getState().links[0], `viewer.${key}`).not.toBe(before)
+ }
+ useWatchLinks.getState().setLinks([{ ...base, viewers: [{ ...viewer, name: null }] }])
+ const unnamed = useWatchLinks.getState().links[0]
+ useWatchLinks.getState().setLinks([base])
+ expect(useWatchLinks.getState().links[0]).not.toBe(unnamed)
+ // A field this build has never heard of is compared too.
+ const known = useWatchLinks.getState().links[0]
+ useWatchLinks.getState().setLinks([{ ...base, fromANewerCore: 1 } as WatchLinkView])
+ expect(useWatchLinks.getState().links[0]).not.toBe(known)
+ })
+
it('counts unread viewer messages, not the sharer\'s own', () => {
const s = useWatchLinks.getState()
s.addChat('a', msg('1'))
@@ -75,6 +110,39 @@ describe('watchLinks store', () => {
expect(st.unread.b).toBe(1)
})
+ it('a chat for a link the list no longer holds is dropped once a list has landed (N1)', () => {
+ const s = useWatchLinks.getState()
+ // Before any list: kept — it can only be for a link not listed yet.
+ s.addChat('early', msg('0'))
+ expect(useWatchLinks.getState().chats.early).toHaveLength(1)
+ s.setLinks([link('a', 'n1')])
+ expect(useWatchLinks.getState().chats.early).toBeUndefined()
+ s.addChat('gone', msg('1'))
+ s.setChat('gone', [msg('2')])
+ expect(useWatchLinks.getState().chats.gone).toBeUndefined()
+ expect(useWatchLinks.getState().unread.gone).toBeUndefined()
+ s.addChat('a', msg('3'))
+ expect(useWatchLinks.getState().chats.a).toHaveLength(1)
+ })
+
+ it('a message that lands while its thread is on screen never counts as unread (N2)', () => {
+ const s = useWatchLinks.getState()
+ s.setLinks([link('a', 'n1')])
+ const seen: number[] = []
+ const off = useWatchLinks.subscribe((st) => seen.push(st.unread.a ?? 0))
+ const release = viewLinkThread('a')
+ const release2 = viewLinkThread('a')
+ s.addChat('a', msg('1'))
+ release()
+ s.addChat('a', msg('2')) // still on screen in the other mount
+ expect(seen.every((n) => n === 0)).toBe(true)
+ release2()
+ release2() // idempotent
+ s.addChat('a', msg('3'))
+ expect(useWatchLinks.getState().unread.a).toBe(1)
+ off()
+ })
+
it('a history answer never drops a message that arrived while it was in flight', () => {
const s = useWatchLinks.getState()
s.addChat('a', msg('3', 'viewer', 30)) // pushed after the history snapshot was taken
@@ -153,10 +221,11 @@ describe('startWatchLinkSync', () => {
await Promise.resolve()
await Promise.resolve()
expect(useWatchLinks.getState().links).toHaveLength(1)
- h.state!([])
- expect(useWatchLinks.getState().links).toHaveLength(0)
h.chat!('a', msg('1'))
expect(useWatchLinks.getState().chats.a).toHaveLength(1)
+ h.state!([])
+ expect(useWatchLinks.getState().links).toHaveLength(0)
+ expect(useWatchLinks.getState().chats.a).toBeUndefined()
h.notice!({ kind: 'not-persistent' })
expect(notices).toEqual([{ kind: 'not-persistent' }])
stop()
diff --git a/src/renderer/state/watchLinks.ts b/src/renderer/state/watchLinks.ts
index a9aa4b443..893e88eed 100644
--- a/src/renderer/state/watchLinks.ts
+++ b/src/renderer/state/watchLinks.ts
@@ -22,31 +22,51 @@ interface WatchLinksState {
chats: Record<string, WatchChatMessage[]>
/** Viewer messages the owner has not seen in that link's popover yet. */
unread: Record<string, number>
+ /** A list has landed (a `list()` answer or a state push). Until then a chat for an unknown link
+ * is kept — it can only be for a link the list has not told us about yet. */
+ hydrated: boolean
setLinks(links: WatchLinkView[]): void
addChat(linkId: string, msg: WatchChatMessage): void
setChat(linkId: string, msgs: WatchChatMessage[]): void
markRead(linkId: string): void
}
-function sameLink(a: WatchLinkView, b: WatchLinkView): boolean {
- if (
- a.linkId !== b.linkId ||
- a.nodeId !== b.nodeId ||
- a.role !== b.role ||
- a.label !== b.label ||
- a.title !== b.title ||
- a.createdAt !== b.createdAt ||
- a.expiresAt !== b.expiresAt ||
- a.url !== b.url ||
- a.status !== b.status ||
- a.viewers.length !== b.viewers.length
- ) {
- return false
+/**
+ * Structural equality for the JSON core pushes (primitives, arrays, plain objects). Structural on
+ * purpose: a hand-written field list silently keeps a stale object when `WatchLinkView` gains a field
+ * nobody added to it — the `setCo` trap CLAUDE.md records for the cold-resume banner.
+ */
+function sameJson(a: unknown, b: unknown): boolean {
+ if (Object.is(a, b)) return true
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null) return false
+ if (Array.isArray(a) || Array.isArray(b)) {
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false
+ return a.every((x, i) => sameJson(x, b[i]))
+ }
+ const ra = a as Record<string, unknown>
+ const rb = b as Record<string, unknown>
+ const keys = Object.keys(ra)
+ if (keys.length !== Object.keys(rb).length) return false
+ return keys.every((k) => Object.prototype.hasOwnProperty.call(rb, k) && sameJson(ra[k], rb[k]))
+}
+
+/** Links whose thread is on screen right now (a popover's chat is mounted), counted per mount. A
+ * message that lands while its thread is shown is read the moment it arrives: it never counts as
+ * unread, so the chip's dot does not flash for one render (N2). Not store state: nothing renders
+ * from it. */
+const viewing = new Map<string, number>()
+
+/** Mark a link's thread as on screen; the returned function takes the mark back. */
+export function viewLinkThread(linkId: string): () => void {
+ viewing.set(linkId, (viewing.get(linkId) ?? 0) + 1)
+ let done = false
+ return () => {
+ if (done) return
+ done = true
+ const n = (viewing.get(linkId) ?? 1) - 1
+ if (n > 0) viewing.set(linkId, n)
+ else viewing.delete(linkId)
}
- return a.viewers.every((v, i) => {
- const w = b.viewers[i]
- return v.viewerId === w.viewerId && v.name === w.name && v.joinedAt === w.joinedAt
- })
}
function sameItems<T>(a: readonly T[] | undefined, b: readonly T[]): boolean {
@@ -59,11 +79,18 @@ function pruned<V>(rec: Record<string, V>, keep: (id: string) => boolean): Recor
return Object.fromEntries(Object.entries(rec).filter(([id]) => keep(id)))
}
+/** A chat for a link the (hydrated) list no longer holds is dropped (N1): a history answer or a
+ * push that lands after the link ended would otherwise bring its thread back until the next push. */
+function unknownLink(s: WatchLinksState, linkId: string): boolean {
+ return s.hydrated && !s.links.some((l) => l.linkId === linkId)
+}
+
export const useWatchLinks = create<WatchLinksState>((set) => ({
links: [],
byNode: {},
chats: {},
unread: {},
+ hydrated: false,
// Every push is the FULL list, freshly deserialized. Objects whose content did not change keep
// their identity (and so does each node's array), so a push about one link re-renders only the
@@ -73,7 +100,7 @@ export const useWatchLinks = create<WatchLinksState>((set) => ({
const prev = new Map(s.links.map((l) => [l.linkId, l]))
const next = incoming.map((l) => {
const p = prev.get(l.linkId)
- return p && sameLink(p, l) ? p : l
+ return p && sameJson(p, l) ? p : l
})
const links = sameItems(s.links, next) ? s.links : next
let byNode = s.byNode
@@ -89,18 +116,20 @@ export const useWatchLinks = create<WatchLinksState>((set) => ({
const live = new Set(links.map((l) => l.linkId))
const chats = pruned(s.chats, (id) => live.has(id))
const unread = pruned(s.unread, (id) => live.has(id))
- if (links === s.links && chats === s.chats && unread === s.unread) return s
- return { links, byNode, chats, unread }
+ if (links === s.links && chats === s.chats && unread === s.unread && s.hydrated) return s
+ return { links, byNode, chats, unread, hydrated: true }
}),
addChat: (linkId, msg) =>
set((s) => {
+ if (unknownLink(s, linkId)) return s
const chat = s.chats[linkId] ?? []
// The same message can reach us twice: pushed, and inside a history answer that raced it.
if (chat.some((m) => m.id === msg.id)) return s
+ const unseen = msg.from === 'viewer' && !viewing.has(linkId)
return {
chats: { ...s.chats, [linkId]: [...chat, msg].slice(-CHAT_KEEP) },
- unread: msg.from === 'viewer' ? { ...s.unread, [linkId]: (s.unread[linkId] ?? 0) + 1 } : s.unread
+ unread: unseen ? { ...s.unread, [linkId]: (s.unread[linkId] ?? 0) + 1 } : s.unread
}
}),
@@ -109,6 +138,7 @@ export const useWatchLinks = create<WatchLinksState>((set) => ({
// would drop it. Ordered by core's timestamp; the sort is stable, so equal times keep their order.
setChat: (linkId, msgs) =>
set((s) => {
+ if (unknownLink(s, linkId)) return s
const ids = new Set(msgs.map((m) => m.id))
const extra = (s.chats[linkId] ?? []).filter((m) => !ids.has(m.id))
const merged = [...msgs, ...extra].sort((a, b) => a.at - b.at).slice(-CHAT_KEEP)
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 2d1bfd1fd..193f67071 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -11299,13 +11299,10 @@ button.pull-checks__name {
would have to pass styles.palette.test's one-colour-per-meaning pins. The label stays ink (muted
when refused, as the spec asks). Never animated: a chip that pulsed for as long as a link lives
would hold the compositor's frame loop open (CLAUDE.md, Idle energy). */
-.live-chip-wrap {
- display: inline-flex;
- flex: 0 0 auto;
-}
.live-chip {
--live-tone: var(--state-error);
display: inline-flex;
+ flex: 0 0 auto;
align-items: center;
gap: 5px;
height: 18px;
@@ -15515,8 +15512,10 @@ body.focus-mode .dock:hover {
(#323232 with no shadow, #242424, #1e1e1e, #1a1a1a, a near-black 0.98 slab) beside the glass
menus. Under glass each is the menu surface's own colour made solid (`--panel`, the colour the
glass fill is `--panel` at an alpha of), with the glass hairline and one shadow. Every modal
- dialog is glass (the text list above); these four are the only opaque floating surfaces. */
-:root[data-nt-glass='on'] :is(.ctx-popover, .color-popover, .label-picker, .kanban-meta__picker) {
+ dialog is glass (the text list above); these five are the only opaque floating surfaces — the
+ fifth, the live-link popover (LiveLinkPopover), opens over the card modal as well as a glass node
+ header, and stays solid for the same reason. */
+:root[data-nt-glass='on'] :is(.ctx-popover, .color-popover, .label-picker, .kanban-meta__picker, .live-pop) {
background: var(--panel);
border: 1px solid var(--glass-edge);
box-shadow: 0 12px 36px rgba(0, 0, 0, calc(0.45 * var(--shadow-k)));
@@ -15812,7 +15811,7 @@ body.focus-mode .dock:hover {
floating surfaces (the popovers inside glass nodes, below): the glass placeholder is sized for the
translucent fill, and on a solid popover it read brighter than the popover's own body text, as if
the field were already filled (visual QA round 4, N4-M2). */
-:root[data-nt-glass='on'] :not(.sticky-node__body, :is(.ctx-popover, .color-popover, .label-picker, .kanban-meta__picker) *)::placeholder {
+:root[data-nt-glass='on'] :not(.sticky-node__body, :is(.ctx-popover, .color-popover, .label-picker, .kanban-meta__picker, .live-pop) *)::placeholder {
color: var(--glass-placeholder);
}
/* An empty field must look empty (visual QA round 3, NM1): the placeholder's 4.5:1 floor sits at
diff --git a/src/renderer/styles.liquid-glass.test.ts b/src/renderer/styles.liquid-glass.test.ts
index a506ed2fe..3d74c988e 100644
--- a/src/renderer/styles.liquid-glass.test.ts
+++ b/src/renderer/styles.liquid-glass.test.ts
@@ -107,7 +107,7 @@ describe('Liquid Glass stylesheet', () => {
expect(rules.find((r) => r.selector === `${ctxHost}::before`)?.body).toMatch(/var\(--glass-chrome-bg\)[\s\S]*var\(--glass-text-blur\)/)
// Popovers inside a glass node or the card modal (their backdrop root) cannot blur: glass is
// opt-in, so nothing hands them a translucent glass fill and they keep their opaque colour.
- for (const nested of ['.dock-menu', '.dock-menu__sub', '.ctx-popover', '.color-popover', '.label-picker', '.kanban-meta__picker']) {
+ for (const nested of ['.dock-menu', '.dock-menu__sub', '.ctx-popover', '.color-popover', '.label-picker', '.kanban-meta__picker', '.live-pop']) {
const fills = gated(nested).filter(
(r) => !r.selector.includes('::before') && /background:[^;]*var\(--glass-(chrome|control)-bg\)/.test(r.body)
)
@@ -115,6 +115,15 @@ describe('Liquid Glass stylesheet', () => {
}
})
+ it('the opaque floating surfaces share one look and keep their own placeholder (N4-M1/M2)', () => {
+ // The live-link popover is one of them: opaque over a glass node header or the card modal.
+ const OPAQUE = ['.ctx-popover', '.color-popover', '.label-picker', '.kanban-meta__picker', '.live-pop']
+ const look = rules.find((r) => r.selector === `${GATE} :is(${OPAQUE.join(', ')})`)
+ expect(look?.body).toMatch(/background:\s*var\(--panel\)[\s\S]*border:\s*1px solid var\(--glass-edge\)/)
+ const placeholder = rules.find((r) => r.selector.startsWith(`${GATE} :not(`) && r.selector.endsWith('::placeholder'))
+ expect(placeholder?.selector).toContain(`:is(${OPAQUE.join(', ')}) *`)
+ })
+
it('OK-range meters match the literal green the fills are drawn in (M1)', () => {
expect(SYSTEM_COLORS.dark.green.toLowerCase()).toBe('#30d158') // = rgb(48, 209, 88)
expect(gated('[style*=').some((r) => r.selector.includes("[style*='rgb(48, 209, 88)']"))).toBe(true)