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(live-links): chat drawer keyboard, hold and read-state edges

reviewd4c0c0f20dd3
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 584d67d19..59e354c4c 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -17448,6 +17448,12 @@ export function Canvas() {
travelToNodeRef.current = travelToNode
})
+ /** The Live chat drawer sits above a kanban card modal (z 57 over 55) — opened from the card's LIVE
+ * chip — but never above Settings, which stays on top. `kanbanOpen` too: the per-project board
+ * reports a closed modal on change, not on unmount, so a board closed with its card open would
+ * leave the flag behind. */
+ const liveChatRaised = cardModalOpen && kanbanOpen && !settingsOpen
+
/** The Live chat drawer's "Go to terminal": a modal drawer gives way to the canvas first (its scrim
* would cover the node); a docked one stays. The project switch, a closed project's reopen and the
* board's "open the card" are `travelToNode`'s. */
@@ -19134,10 +19140,8 @@ export function Canvas() {
<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}
+ raised={liveChatRaised}
+ beside={liveChat.pinned && explorerOpen && explorer.pinned && !liveChatRaised}
onPickLink={pickLiveChatLink}
onClose={closeLiveChat}
onTogglePin={toggleLiveChatPin}
diff --git a/src/renderer/canvas/live-link-wiring.test.ts b/src/renderer/canvas/live-link-wiring.test.ts
index ea7d22aed..2ace56dc0 100644
--- a/src/renderer/canvas/live-link-wiring.test.ts
+++ b/src/renderer/canvas/live-link-wiring.test.ts
@@ -138,7 +138,13 @@ describe('Canvas live-link wiring', () => {
expect(src).toContain('const liveLinkCount = useWatchLinks((s) => s.links.length)')
// `beside` follows the drawer actually on screen, not just the pin.
const mount = src.slice(src.indexOf('<LiveChatDrawer'))
- expect(mount.slice(0, mount.indexOf('/>'))).toContain('beside={liveChat.pinned && explorerOpen && explorer.pinned}')
+ expect(mount.slice(0, mount.indexOf('/>'))).toContain('beside={liveChat.pinned && explorerOpen && explorer.pinned && !liveChatRaised}')
+ })
+
+ it('raised only over a card modal on an open board, and never over Settings (hardening 3/4)', () => {
+ // Settings (z 55) stays on top: the drawer is not lifted to 57 while it is open. Raised, the
+ // drawer is not docked beside the Explorer either — the Explorer sits under the card modal.
+ expect(src).toContain('const liveChatRaised = cardModalOpen && kanbanOpen && !settingsOpen')
})
it('raised while a card modal is open, beside only when BOTH drawers are pinned', () => {
@@ -146,8 +152,8 @@ describe('Canvas live-link wiring', () => {
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('raised={liveChatRaised}')
+ expect(props).toContain('beside={liveChat.pinned && explorerOpen && explorer.pinned && !liveChatRaised}')
expect(props).toContain('onGoToNode={goToLiveChatNode}')
// The card modal's open state is published where every board reports it.
expect(callback('setKanbanModalNode')).toContain('setCardModalOpen(id !== null)')
diff --git a/src/renderer/components/LiveChatDrawer.test.tsx b/src/renderer/components/LiveChatDrawer.test.tsx
index 6873f2cdd..f6a36befe 100644
--- a/src/renderer/components/LiveChatDrawer.test.tsx
+++ b/src/renderer/components/LiveChatDrawer.test.tsx
@@ -10,6 +10,12 @@ import { openDialogCount, popDialog, pushDialog, resetDialogStack } from './dial
import { CHAT_NOT_SENT_MESSAGE, CONTROL_LOCKED_TEXT, KICK_NOT_DONE_MESSAGE } from '../lib/liveLink'
import { chatNameColor } from '../lib/liveChatLook'
+// Spied, with the real implementation: how often the message list was RENDERED (one call per line).
+vi.mock('../lib/liveChatLook', async (importOriginal) => {
+ const real = await importOriginal<typeof import('../lib/liveChatLook')>()
+ return { ...real, chatNameColor: vi.fn(real.chatNameColor) }
+})
+
;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
const link = (over: Partial<WatchLinkView> = {}): WatchLinkView => ({
@@ -60,6 +66,8 @@ beforeEach(() => {
api.kick.mockImplementation(async () => true)
api.sendChat.mockImplementation(async (_l: string, t: string) => ({ id: 's', name: 'Ada', text: t, at: 0, from: 'sharer' }))
api.setPassword.mockImplementation(async () => true)
+ // A focused, visible window: someone can see the drawer (the read-state rule, useLinkThread).
+ vi.spyOn(document, 'hasFocus').mockReturnValue(true)
;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { watchLink: api, clipboard: { writeText: vi.fn() } }
host = document.createElement('div')
document.body.append(host)
@@ -69,6 +77,8 @@ afterEach(() => {
act(() => root.unmount())
document.body.innerHTML = ''
resetDialogStack()
+ vi.restoreAllMocks()
+ delete (document as { visibilityState?: unknown }).visibilityState
})
const noop = (): void => {}
@@ -97,7 +107,9 @@ const type = (input: HTMLInputElement, value: string): void =>
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 })))
+/** A key with nothing focused: its target is the body. */
+const keydown = (key: string): void =>
+ act(() => void document.body.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })))
describe('LiveChatDrawer', () => {
it('is the Explorer drawer: titled Live chat, a pin button with aria-pressed, and a close', () => {
@@ -409,4 +421,127 @@ describe('LiveChatDrawer', () => {
click(drawer().querySelector<HTMLButtonElement>('button[aria-label="Close"]')!)
expect(onClose).toHaveBeenCalledTimes(1)
})
+
+ // ── Hardening round ──
+ it('Escape typed OUTSIDE the drawer (the palette, Settings — not on the dialog stack) is not the drawer\'s', () => {
+ setLinks([link()])
+ const onClose = vi.fn()
+ render(props({ onClose }))
+ const palette = document.createElement('input')
+ document.body.append(palette)
+ palette.focus()
+ act(() => void palette.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))
+ expect(onClose).not.toHaveBeenCalled()
+ // …and the palette keeps the keyboard (no focus restore pulled out from under it).
+ expect(document.activeElement).toBe(palette)
+ // On the body (nothing focused) with the drawer as the top dialog: it is the drawer's.
+ keydown('Escape')
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ it('Escape inside the drawer closes it when it is the top dialog', () => {
+ setLinks([link()])
+ const onClose = vi.fn()
+ render(props({ onClose }))
+ const input = drawer().querySelector<HTMLInputElement>('.live-chat__reply input')!
+ input.focus()
+ act(() => void input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true })))
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+
+ const controlLinks = (): WatchLinkView[] => [
+ link({ role: 'controller', control: { enabled: true, locked: false } }),
+ link({ linkId: 'M', nodeId: 'n2', title: 'other', createdAt: 5 })
+ ]
+ const startSave = async (): Promise<(ok: boolean) => void> => {
+ let answer: (ok: boolean) => void = () => {}
+ api.setPassword.mockImplementation(() => new Promise<boolean>((r) => (answer = r)))
+ click(button('Change password…'))
+ click(button('Generate'))
+ click(button('Save'))
+ await flush()
+ expect(button('Saving…')).toBeTruthy()
+ return (ok) => answer(ok)
+ }
+ const shown = (): string => drawer().querySelector<HTMLSelectElement>('select')!.value
+
+ it('a password save in flight keeps the drawer on its link: an open on another link waits (refused save → then it moves)', async () => {
+ setLinks(controlLinks())
+ const onPickLink = vi.fn()
+ render(props({ linkId: 'L', onPickLink }))
+ const answer = await startSave()
+ // Canvas's `nodeterm:live-chat` listener opens the drawer on M meanwhile.
+ render(props({ linkId: 'M', onPickLink }))
+ expect(shown()).toBe('L')
+ expect(button('Saving…')).toBeTruthy()
+ expect(drawer().querySelector('select')!.disabled).toBe(true)
+ await act(async () => answer(false))
+ expect(shown()).toBe('M')
+ // The drawer followed Canvas's link; it never asked Canvas to change it back.
+ expect(onPickLink).not.toHaveBeenCalled()
+ })
+
+ it('a password that took stays on screen (its plaintext exists nowhere else) until Done, then the drawer moves', async () => {
+ setLinks(controlLinks())
+ render(props({ linkId: 'L' }))
+ const answer = await startSave()
+ render(props({ linkId: 'M' }))
+ await act(async () => answer(true))
+ expect(shown()).toBe('L')
+ expect(button('Copy password')).toBeTruthy()
+ click(button('Done'))
+ expect(shown()).toBe('M')
+ })
+
+ it('when the remembered link is gone, the drawer adopts what it shows (Canvas state and the pick agree)', () => {
+ setLinks([link({ linkId: 'A', createdAt: 1 }), link({ linkId: 'B', createdAt: 9 })])
+ const onPickLink = vi.fn()
+ render(props({ linkId: 'gone', onPickLink }))
+ expect(onPickLink).toHaveBeenCalledWith('B')
+ onPickLink.mockClear()
+ render(props({ linkId: 'B', onPickLink }))
+ expect(onPickLink).not.toHaveBeenCalled()
+ })
+
+ it('a message counts as read only while someone can see it: hidden or unfocused, the chip\'s count grows', () => {
+ setLinks([link()])
+ addChat('L', msg('1'))
+ vi.mocked(document.hasFocus).mockReturnValue(false)
+ render(props({ pinned: true }))
+ expect(useWatchLinks.getState().unread.L).toBe(1)
+ addChat('L', msg('2'))
+ expect(useWatchLinks.getState().unread.L).toBe(2)
+ // The window gains focus: what is on screen is read.
+ vi.mocked(document.hasFocus).mockReturnValue(true)
+ act(() => void window.dispatchEvent(new Event('focus')))
+ expect(useWatchLinks.getState().unread.L).toBe(0)
+ addChat('L', msg('3'))
+ expect(useWatchLinks.getState().unread.L).toBe(0)
+ // Blurred: it counts again.
+ vi.mocked(document.hasFocus).mockReturnValue(false)
+ act(() => void window.dispatchEvent(new Event('blur')))
+ addChat('L', msg('4'))
+ expect(useWatchLinks.getState().unread.L).toBe(1)
+ // Focused but HIDDEN (minimized, another Space): still counts.
+ vi.mocked(document.hasFocus).mockReturnValue(true)
+ act(() => void window.dispatchEvent(new Event('focus')))
+ expect(useWatchLinks.getState().unread.L).toBe(0)
+ Object.defineProperty(document, 'visibilityState', { configurable: true, get: () => 'hidden' })
+ act(() => void document.dispatchEvent(new Event('visibilitychange')))
+ addChat('L', msg('5'))
+ expect(useWatchLinks.getState().unread.L).toBe(1)
+ })
+
+ it('a viewer typing push does not re-render the message list', () => {
+ setLinks([link({ viewers: [{ viewerId: 'v1', name: 'Mert', joinedAt: 1, waiting: false, controlling: false, typing: false }] })])
+ useWatchLinks.getState().setChat('L', [msg('1'), msg('2'), msg('3')])
+ render(props())
+ const color = vi.mocked(chatNameColor)
+ color.mockClear()
+ setLinks([link({ viewers: [{ viewerId: 'v1', name: 'Mert', joinedAt: 1, waiting: false, controlling: false, typing: true }] })])
+ expect(drawer().querySelector('.live-pop__typing')).not.toBeNull()
+ expect(color).not.toHaveBeenCalled()
+ addChat('L', msg('4'))
+ expect(color).toHaveBeenCalled()
+ })
})
diff --git a/src/renderer/components/LiveChatDrawer.tsx b/src/renderer/components/LiveChatDrawer.tsx
index caddc2dbf..d6d1d2dff 100644
--- a/src/renderer/components/LiveChatDrawer.tsx
+++ b/src/renderer/components/LiveChatDrawer.tsx
@@ -1,14 +1,14 @@
-import { useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from 'react'
+import { memo, useCallback, useEffect, useLayoutEffect, useRef, useState, type CSSProperties } from 'react'
import { createPortal } from 'react-dom'
import type { WatchChatMessage, WatchLinkView } from '@shared/watch-link-types'
import { stripBidiControls } from '@shared/watch-link-types'
import { CHAT_TEXT_MAX } from '@shared/watch-link/protocol'
import { isTopDialog, nextDialogId, popDialog, pushDialog } from './dialog-stack'
-import { ControlHold, ControlSection, hasChat, kickViewer } from './LiveLinkControls'
+import { ControlHold, ControlSection, hasChat, kickViewer, type ControlHoldKind } 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 { chatLinkOptionLabels, LIVE_CHAT_DRAWER_ATTR, pickChatLink } from '../lib/liveChatPin'
+import { chatLinkOptionLabels, inLiveChatDrawer, LIVE_CHAT_DRAWER_ATTR, pickChatLink } from '../lib/liveChatPin'
import { useLinkThread, useWatchLinks } from '../state/watchLinks'
const EMPTY_CHAT: WatchChatMessage[] = []
@@ -48,26 +48,43 @@ function linkTitle(l: Pick<WatchLinkView, 'title'>): string {
* modal keep their keys.
*/
export function LiveChatDrawer(p: LiveChatDrawerProps): React.JSX.Element {
- const { pinned, raised, onClose } = p
+ const { pinned, raised, onClose, onPickLink } = 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++
+ // A new Control password holds the drawer (`ControlHold`) — its plaintext exists nowhere else once
+ // core takes it. `saves` counts the saves in flight: they keep the drawer from closing AND on its
+ // link. `pins` counts every hold (a save, or a new password on screen until Done): they keep the
+ // drawer on its link, whatever an Open chat for another link or the fallback says meanwhile. The
+ // counters are refs (read in handlers); the held link is state, because it decides what renders.
+ const saves = useRef(0)
+ const pins = useRef(0)
+ const [heldLink, setHeldLink] = useState<string | null>(null)
+ const wanted = pickChatLink(links, p.linkId)
+ const shownId = heldLink !== null && links.some((l) => l.linkId === heldLink) ? heldLink : wanted
+ const link = shownId === null ? null : (links.find((l) => l.linkId === shownId) ?? null)
+ const shownRef = useRef(shownId)
+ shownRef.current = shownId
+ const hold = useCallback((kind: ControlHoldKind = 'save'): (() => void) => {
+ if (kind === 'save') saves.current++
+ if (++pins.current === 1) setHeldLink(shownRef.current)
let released = false
return () => {
if (released) return
released = true
- holds.current--
+ if (kind === 'save') saves.current--
+ if (--pins.current === 0) setHeldLink(null)
}
}, [])
+ // The remembered link is gone (or none was remembered): the drawer shows the most recent one, and
+ // ADOPTS it, so Canvas's state and the remembered pick say what is on screen. Never while held:
+ // there the difference is an open on another link waiting for the hold to end.
+ useEffect(() => {
+ if (heldLink !== null || shownId === null || shownId === p.linkId) return
+ onPickLink(shownId)
+ }, [heldLink, shownId, p.linkId, onPickLink])
/** Close unless something is held. Every close gesture of the owner comes here. */
const requestClose = useCallback((): void => {
- if (holds.current > 0) return
+ if (saves.current > 0) return
onClose()
}, [onClose])
@@ -84,6 +101,10 @@ export function LiveChatDrawer(p: LiveChatDrawerProps): React.JSX.Element {
if (pinned) return
const onKey = (e: KeyboardEvent): void => {
if (e.key !== 'Escape' || !isTopDialog(dialogId)) return
+ // Only an Escape that is the drawer's: typed inside it, or with nothing focused. The palette and
+ // Settings are not on the dialog stack — an Escape typed there is theirs, and closing the drawer
+ // underneath would also pull the keyboard out of them (the drawer gives focus back on close).
+ if (!inLiveChatDrawer(e.target) && e.target !== document.body) return
e.preventDefault()
e.stopPropagation()
requestClose()
@@ -165,10 +186,13 @@ export function LiveChatDrawer(p: LiveChatDrawerProps): React.JSX.Element {
className="confirm__input live-chat__select"
aria-label="Live link"
value={link.linkId}
+ // Switching links unmounts the controls: not while a new password is on its way or
+ // on screen.
+ disabled={heldLink !== null}
+ title={heldLink !== null ? 'Finish the password change first.' : undefined}
onChange={(e) => {
- // Switching links unmounts the controls: not while a new password is on its way.
- if (holds.current > 0) return
- p.onPickLink(e.target.value)
+ if (pins.current > 0) return
+ onPickLink(e.target.value)
}}
>
{chatLinkOptionLabels(links).map((text, i) => (
@@ -189,7 +213,7 @@ export function LiveChatDrawer(p: LiveChatDrawerProps): React.JSX.Element {
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
+ if (!pinned && saves.current > 0) return
p.onGoToNode(link.nodeId)
}}
>
@@ -279,8 +303,12 @@ function MessageTime({ at }: { at: number }): React.JSX.Element | null {
* The thread, the viewer page's live chat: one dense line per message, a Sharer badge on the owner's
* own lines (the HOST's word, `from === 'sharer'` — never a name), and a list that stays at the newest
* message unless the owner scrolled up, then says how many arrived ("N new messages ↓").
+ *
+ * `memo`: its only prop is the link id, and it reads the thread from the store itself — so a push
+ * about the link's viewers (a typing dot, every few seconds while someone types) does not re-render
+ * the whole message list.
*/
-function Thread({ linkId }: { linkId: string }): React.JSX.Element {
+const Thread = memo(function Thread({ linkId }: { linkId: string }): React.JSX.Element {
const api = window.nodeTerminal.watchLink
const chat = useWatchLinks((s) => s.chats[linkId] ?? EMPTY_CHAT)
const [draft, setDraft] = useState('')
@@ -391,4 +419,4 @@ function Thread({ linkId }: { linkId: string }): React.JSX.Element {
</form>
</div>
)
-}
+})
diff --git a/src/renderer/components/LiveLinkChip.test.tsx b/src/renderer/components/LiveLinkChip.test.tsx
index cd32a38cd..f10314b88 100644
--- a/src/renderer/components/LiveLinkChip.test.tsx
+++ b/src/renderer/components/LiveLinkChip.test.tsx
@@ -80,6 +80,10 @@ beforeEach(() => {
api.setPassword.mockImplementation(async () => true)
api.allowControl.mockImplementation(async () => true)
writeText.mockClear()
+ // A focused, visible window: the thread counts as read only while someone can see it
+ // (useLinkThread). jsdom answers `hasFocus()` from whatever an EARLIER test focused, which made the
+ // read tests pass in a full run and fail alone.
+ vi.spyOn(document, 'hasFocus').mockReturnValue(true)
;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { watchLink: api, clipboard: { writeText } }
host = document.createElement('div')
document.body.append(host)
@@ -90,6 +94,7 @@ afterEach(() => {
document.body.innerHTML = ''
resetDialogStack()
vi.unstubAllGlobals()
+ vi.restoreAllMocks()
})
const render = (ui: React.ReactElement): void => act(() => root.render(ui))
diff --git a/src/renderer/components/LiveLinkControls.tsx b/src/renderer/components/LiveLinkControls.tsx
index 2da1864e2..610591145 100644
--- a/src/renderer/components/LiveLinkControls.tsx
+++ b/src/renderer/components/LiveLinkControls.tsx
@@ -22,13 +22,22 @@ import {
} 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.
+ * What a section holds its surface for:
+ * - `save`: a new Control password's save is in flight. Once core takes it, its plaintext exists
+ * nowhere else, so a surface closed under it would lose a password that was changed: the surface
+ * must not close on the owner's close gestures, nor switch away from this link.
+ * - `shown`: the new password is on screen until Done. Closing is the owner's own gesture (they have
+ * it in front of them), but a surface that switches LINKS by itself (the drawer, on an Open chat
+ * for another link) must not take it away first.
*/
-export const ControlHold = createContext<(() => () => void) | null>(null)
+export type ControlHoldKind = 'save' | 'shown'
+
+/**
+ * `hold(kind)` holds the surface until the returned release runs (see `ControlHoldKind`). The link
+ * going away still closes the popover (nothing is owed for a link that no longer exists). Absent:
+ * nothing to hold.
+ */
+export const ControlHold = createContext<((kind?: ControlHoldKind) => () => void) | null>(null)
/** The roles whose viewers can chat: a Control link is a Commenter link plus typing (spec §2.1). */
export function hasChat(role: WatchLinkRole): boolean {
@@ -91,10 +100,13 @@ export function ControlSection({ linkId, control }: { linkId: string; control: W
// A hold and a deadline this section took and has not given back — both go on unmount too (the
// link went away: nothing is owed for it).
const releaseRef = useRef<(() => void) | null>(null)
+ /** The `shown` hold while a new password is on screen (released by Done, or on unmount). */
+ const shownReleaseRef = useRef<(() => void) | null>(null)
const deadlineRef = useRef<ReturnType<typeof setTimeout>>()
useEffect(
() => () => {
releaseRef.current?.()
+ shownReleaseRef.current?.()
clearTimeout(deadlineRef.current)
},
[]
@@ -114,10 +126,9 @@ export function ControlSection({ linkId, control }: { linkId: string; control: W
}
/**
* 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.
+ * 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
@@ -146,8 +157,15 @@ export function ControlSection({ linkId, control }: { linkId: string; control: W
.then(() => api.setPassword(linkId, next))
.then(
(ok) => {
+ const current = gen === saveGen.current
+ // A password that took is held on screen until Done — taken BEFORE the save's hold goes, so
+ // there is no moment in which the drawer may switch to another link and drop it.
+ if (ok && current) {
+ shownReleaseRef.current?.()
+ shownReleaseRef.current = hold?.('shown') ?? null
+ }
settle()
- if (gen !== saveGen.current) return
+ if (!current) return
if (ok) {
setError(null)
setShown(next)
@@ -211,6 +229,8 @@ export function ControlSection({ linkId, control }: { linkId: string; control: W
type="button"
className="confirm__btn live-pop__btn"
onClick={() => {
+ shownReleaseRef.current?.()
+ shownReleaseRef.current = null
setShown(null)
setFocusTo('change')
}}
diff --git a/src/renderer/components/LiveLinkPopover.tsx b/src/renderer/components/LiveLinkPopover.tsx
index 30b53fd1f..13317f72b 100644
--- a/src/renderer/components/LiveLinkPopover.tsx
+++ b/src/renderer/components/LiveLinkPopover.tsx
@@ -6,7 +6,7 @@ import { stripBidiControls } from '@shared/watch-link-types'
import { CHAT_TEXT_MAX, type WatchChatMessage } from '@shared/watch-link/protocol'
import { useDialogStack } from './dialog-stack'
import { useCopied } from './LiveLinkPassword'
-import { ControlHold, ControlSection, hasChat, kickViewer } from './LiveLinkControls'
+import { ControlHold, ControlSection, hasChat, kickViewer, type ControlHoldKind } from './LiveLinkControls'
import { useMenuFlip } from '../ui/useMenuFlip'
import {
CHAT_NOT_SENT_MESSAGE,
@@ -115,7 +115,10 @@ export function LiveLinkPopover({
const flip = useMenuFlip(anchor.bottom + 6, anchor.left, anchor.top - 6)
// Holds (see `ControlHold`): a counter, not state — nothing renders from it.
const holds = useRef(0)
- const hold = useCallback((): (() => void) => {
+ // Only a save holds the popover: it has no link to switch away from, and a password on screen does
+ // not keep the owner from closing it (`ControlHoldKind`).
+ const hold = useCallback((kind: ControlHoldKind = 'save'): (() => void) => {
+ if (kind !== 'save') return () => {}
holds.current++
let released = false
return () => {
diff --git a/src/renderer/lib/liveLinkEntry.test.tsx b/src/renderer/lib/liveLinkEntry.test.tsx
index abbd49eaa..ca9966912 100644
--- a/src/renderer/lib/liveLinkEntry.test.tsx
+++ b/src/renderer/lib/liveLinkEntry.test.tsx
@@ -322,8 +322,12 @@ describe('liveLinkCommands (palette)', () => {
const entitled = liveLinkCommands({ ...base, entitled: true, activeLinks: 0, manage, confirmStopAll })
expect(entitled.map((c) => c.id)).toEqual(['live-links-manage', 'live-links-stop-all'])
// Never in the Server Edition (R43): no license layer, nothing to stop.
- const server = liveLinkCommands({ ...base, serverEdition: true, entitled: true, activeLinks: 3, manage, confirmStopAll })
- expect(server.map((c) => c.id)).not.toContain('live-links-stop-all')
+ // The Server Edition lists no link of its own (no license layer): Manage alone. Were one listed,
+ // its chat would show — and still no Stop all.
+ const server = liveLinkCommands({ ...base, serverEdition: true, entitled: true, activeLinks: 0, manage, confirmStopAll })
+ expect(server.map((c) => c.id)).toEqual(['live-links-manage'])
+ const serverWithLinks = liveLinkCommands({ ...base, serverEdition: true, entitled: true, activeLinks: 3, manage, confirmStopAll })
+ expect(serverWithLinks.map((c) => c.id)).toEqual(['live-links-manage', 'live-chat'])
const some = liveLinkCommands({ ...base, activeLinks: 2, manage, confirmStopAll })
expect(some.map((c) => c.id)).toEqual(['live-links-manage', 'live-chat', 'live-links-stop-all'])
expect(some[0].label).toBe('Manage live links')
diff --git a/src/renderer/state/watchLinks.ts b/src/renderer/state/watchLinks.ts
index 93660dd29..1c9063b30 100644
--- a/src/renderer/state/watchLinks.ts
+++ b/src/renderer/state/watchLinks.ts
@@ -5,7 +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 { useEffect, useState } from 'react'
import { create } from 'zustand'
import type { NodeTerminalApi } from '@shared/types'
import type { WatchChatMessage, WatchLinkNotice, WatchLinkView } from '@shared/watch-link-types'
@@ -51,10 +51,10 @@ function sameJson(a: unknown, b: unknown): boolean {
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. */
+/** Links whose thread someone can see right now (`useLinkThread`: a popover's or the Live chat
+ * drawer's thread, in a visible, focused window), counted per mount. A message that lands while its
+ * thread is seen is read the moment it arrives: it never counts as unread, so the chip's count does
+ * not flash for one render (N2). Not store state: nothing renders from it. */
const viewing = new Map<string, number>()
/** Mark a link's thread as on screen; the returned function takes the mark back. */
@@ -149,23 +149,54 @@ export const useWatchLinks = create<WatchLinksState>((set) => ({
markRead: (linkId) => set((s) => (s.unread[linkId] ? { unread: { ...s.unread, [linkId]: 0 } } : s))
}))
+/** Someone can see this window: it is visible and has the focus. */
+function documentSeen(): boolean {
+ return typeof document !== 'undefined' && document.visibilityState === 'visible' && document.hasFocus()
+}
+
+/** `documentSeen`, re-evaluated when the window gains or loses focus or is hidden or shown. */
+function useDocumentSeen(): boolean {
+ const [seen, setSeen] = useState(documentSeen)
+ useEffect(() => {
+ const update = (): void => setSeen(documentSeen())
+ // `blur` is the window losing focus: answer false outright — `hasFocus()` during the event is not
+ // something to lean on.
+ const blur = (): void => setSeen(false)
+ update()
+ window.addEventListener('focus', update)
+ window.addEventListener('blur', blur)
+ document.addEventListener('visibilitychange', update)
+ return () => {
+ window.removeEventListener('focus', update)
+ window.removeEventListener('blur', blur)
+ document.removeEventListener('visibilitychange', update)
+ }
+ }, [])
+ return seen
+}
+
/**
* The thread rule for a link's chat on screen — the chip's popover and the Live chat drawer, ONE
- * definition: 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).
+ * definition. A message counts as read only while someone can SEE it: the thread is mounted AND the
+ * window is visible and focused (a pinned drawer stays mounted behind another app, and the chip's
+ * count is how the owner learns something arrived). While seen, what lands is read as it arrives
+ * (`viewLinkThread`, N2) and what arrived before is read (`markRead`, H21) — on open, and again each
+ * time the window comes back. Core's history is asked once (a reload, or messages pushed before this
+ * renderer subscribed — the store merges the two).
*/
export function useLinkThread(linkId: string, api: Pick<NodeTerminalApi['watchLink'], 'chatHistory'>): void {
- useEffect(() => viewLinkThread(linkId), [linkId])
+ const seen = useDocumentSeen()
+ useEffect(() => {
+ if (!seen) return
+ useWatchLinks.getState().markRead(linkId)
+ return viewLinkThread(linkId)
+ }, [linkId, seen])
useEffect(() => {
void api.chatHistory(linkId).then(
(m) => useWatchLinks.getState().setChat(linkId, m),
() => {}
)
}, [api, linkId])
- useEffect(() => {
- useWatchLinks.getState().markRead(linkId)
- }, [linkId])
}
/**