Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(board-comments): per-comment flow budget, trusted row status, picker and Escape fixes
review832348372761
diff --git a/CLAUDE.md b/CLAUDE.mdindex 60fae2922..f246fea35 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1726,9 +1726,14 @@ name); on send, each mentioned session gets its own delivery through the SAME `ragent `send` takes — scope, runtime pane ownership, the per-project `agentMessaging` switch, flowcontrol, the pane probes, the nonce envelope, the receipt, the deliver-on-idle queue with its TTL.What differs is only who it is from: the scope is "the target is on the comment's board"-(`resolveBoardCommentScope`), the flow budget belongs to the board (`board:<projectId>`, and each-new comment is a new turn, capped at `BOARD_COMMENT_MENTION_MAX` = `FANOUT_PER_TURN` mentions,-refused whole above it), and the envelope reads `from: board comment by <author>` with no node id+(`resolveBoardCommentScope`); the PAIR window belongs to the board (`board:<projectId>` — one comment+per session per 10 s, whichever comment) while the FAN-OUT budget belongs to the comment itself+(`reserveFlow`'s `fanOutKey`, `board:<projectId>:<commentId>`), because a person's turn is one comment+and an earlier comment's in-flight holds or queued flush must never spend a newer one's (review+finding; both scenarios are tests); a comment mentions at most `BOARD_COMMENT_MENTION_MAX` =+`FANOUT_PER_TURN` sessions and is refused whole above it; a pair-limited board comment is QUEUED+rather than refused (`BOARD_QUEUE_ON` — an agent retries, a person could only post again; the+flush re-runs the limiter); and the envelope reads `from: board comment by <author>` with no node idand `reply-to: none (…)` (`BOARD_COMMENT_REPLY_TO`; both agent-facing bodies render it from theconstants). An agent node TITLED like that is labelled `node titled "…"` in its own `from:` line, soit cannot pass as a person. The body is the comment with tokens turned into `@<current title>`,@@ -1743,9 +1748,17 @@ Canvas takes the same two steps as `send`: the target's `guardConcurrentRestart``syncMessageScope`. **No silent success**: every outcome is on the comment row — `sending…`, thenthe reply's typed outcome (with the `notPermitted` reason) from this app run, else the latest`agent-message` trace line in the log whose `from` is `board-comment:<commentId>` (the trace now-carries `reason` too, and the queue's trace leg falls back to the target's listing project for a-board comment, so an expiry reaches its row even after pane ownership is gone). Those trace lines-render on their comment's row, not as rows of their own. Desktop: full. Server Edition and relay+carries `reason` too, and the queue hands its trace leg the queued request, so a board comment's+`queued`/`expired` lines land on ITS board whoever owns the pane by then). Log lines are trusted+ONLY for comments this machine sent (`nodeterm.boardCommentsSent`, localStorage, bounded): the log+is shared, so a teammate's comment arrives with THEIR machine's trace lines and a forged line is one+append away — such a comment shows no status, and its lines stay ordinary feed rows. For our own:+a line dated in the future is ignored, a `queued` older than `BOARD_COMMENT_QUEUE_STALE_MS` (the+queue TTL + 1 min — the queue is process memory, so a quit never writes its end) says no outcome+was recorded, and a mention with no record at all says so too. A trace line is hidden as a row only+on the card whose comment row shows it; the mentioned session's own card keeps "routed a board+comment here: …". Text tables are read with `Object.hasOwn` (values come from the shared file).+The card modal's capture-phase Escape defers to the composer while its @ picker is open. Desktop: full. Server Edition and relaytabs: display-only by design (the bridge answers `notPermitted: unsupported-edition`; the picker isnot offered) — a browser or a relay guest typing into this machine's panes is exactly thecross-user injection this refuses. Mobile: N/A (the phone posts no board comments).diff --git a/src/core/agents/agent-message-flow.ts b/src/core/agents/agent-message-flow.tsindex 48c5663c2..6ca39178b 100644--- a/src/core/agents/agent-message-flow.ts+++ b/src/core/agents/agent-message-flow.ts@@ -291,10 +291,16 @@ export interface FlowReservation {*/export type FlowReserve = { ok: false; limit: FlowLimit; outcome: RateLimited } | FlowReservation-export function reserveFlow(src: string, dst: string, now: number): FlowReserve {+/**+ * `fanOutKey` names whose PER-TURN budget this delivery spends; it defaults to the sender, which is+ * every agent. A board comment passes its own key (`board:<project>:<comment>`), because a person's+ * turn is one comment: its pair window stays the board's (`src`), but one comment's in-flight holds+ * and later sends must not spend the next comment's budget.+ */+export function reserveFlow(src: string, dst: string, now: number, fanOutKey: string = src): FlowReserve {sweep(now)- const sent = senderTurns.get(src)?.sent ?? 0- const pending = pendingBySender.get(src) ?? 0+ const sent = senderTurns.get(fanOutKey)?.sent ?? 0+ const pending = pendingBySender.get(fanOutKey) ?? 0if (sent + pending >= FANOUT_PER_TURN) {return {ok: false,@@ -319,7 +325,7 @@ export function reserveFlow(src: string, dst: string, now: number): FlowReserve}}pendingPairs.add(key)- pendingBySender.set(src, pending + 1)+ pendingBySender.set(fanOutKey, pending + 1)let released = falsereturn {ok: true,@@ -327,9 +333,9 @@ export function reserveFlow(src: string, dst: string, now: number): FlowReserveif (released) returnreleased = truependingPairs.delete(key)- const n = (pendingBySender.get(src) ?? 1) - 1- if (n <= 0) pendingBySender.delete(src)- else pendingBySender.set(src, n)+ const n = (pendingBySender.get(fanOutKey) ?? 1) - 1+ if (n <= 0) pendingBySender.delete(fanOutKey)+ else pendingBySender.set(fanOutKey, n)}}}@@ -344,15 +350,15 @@ export function reserveFlow(src: string, dst: string, now: number): FlowReserve* come back from — would find itself silent for the rest of its turn, blocked by the retries the* feature asked it to make.*/-export function noteSent(src: string, dst: string, now: number): void {+export function noteSent(src: string, dst: string, now: number, fanOutKey: string = src): void {sweep(now)pairLastSentAt.set(pairKey(src, dst), now)- const budget = senderTurns.get(src)+ const budget = senderTurns.get(fanOutKey)if (budget) {budget.sent += 1budget.lastSentAt = now} else {- senderTurns.set(src, { sent: 1, lastSentAt: now })+ senderTurns.set(fanOutKey, { sent: 1, lastSentAt: now })}}diff --git a/src/core/agents/agent-messaging.ts b/src/core/agents/agent-messaging.tsindex 91f013f9c..b769e3f63 100644--- a/src/core/agents/agent-messaging.ts+++ b/src/core/agents/agent-messaging.ts@@ -46,7 +46,6 @@ import {boardCommentBody,boardCommentFrom,boardCommentSourceId,- commentIdOfSource,commentTextForAgent,isBoardCommentDeliverRequest,type BoardCommentDeliverRequest@@ -294,17 +293,18 @@ export function createDeliveryQueue(},deps),- // The trace leg: ring always, board log when the TARGET's owning project is resolvable. For a- // board comment that falls back to the project that LISTS the target — the board the comment- // is on, which is where its row reads the outcome. A trace is not an authorization, and the- // expiry is exactly the moment runtime ownership may be gone (the target restarted), so an- // expired comment must not vanish from its row for want of it.- trace: (input) =>+ // The trace leg: ring always, board log when the TARGET's owning project is resolvable. A board+ // comment's lines go to ITS board instead — where its row reads them — whoever owns the pane+ // by then: a trace is not an authorization, and the expiry is exactly the moment runtime+ // ownership may be gone or moved (the target restarted), so an expired comment must neither+ // vanish from its row nor land on another project's board.+ trace: (input, qreq) =>recordDelivery(input, {appendBoardLog: (entry) => {const projectId =- deps.paneOwnerProject(input.targetNodeId) ??- (commentIdOfSource(input.sourceNodeId) ? projectFor(input.targetNodeId) : undefined)+ qreq?.verb === 'board-comment' && typeof qreq.projectId === 'string'+ ? qreq.projectId+ : deps.paneOwnerProject(input.targetNodeId)return projectId ? deps.appendBoardLog(projectId, entry) : Promise.resolve(false)},now@@ -598,13 +598,16 @@ export async function runDelivery(// polite enough to send sequentially. `reserveFlow` checks and holds in one synchronous step;// the hold is released in the `finally` below, so a delivery that never reaches the pane still// costs nothing (noteSent's own contract). The parallel-sends test in agent-messaging.test.ts- // is the one that fails if this goes back to a bare check. A board comment's budget belongs to- // its board (`boardFlowSource`), not to the per-comment trace id.+ // is the one that fails if this goes back to a bare check. A board comment's PAIR window belongs+ // to its board (`boardFlowSource`: one comment per session per window, whichever comment), and+ // its FAN-OUT budget to the comment itself — a person's turn is one comment, so an earlier+ // comment's in-flight holds and later sends (a queued flush) never spend a newer one's.const flowSource = board ? boardFlowSource(board.projectId) : ident.sourceNodeId+ const fanOutKey = board ? `${flowSource}:${board.commentId}` : flowSourcelet retryAfterMs: number | undefinedlet reservation: { release(): void } | null = nullif (!notPermitted) {- const flow = reserveFlow(flowSource, req.targetNodeId, now())+ const flow = reserveFlow(flowSource, req.targetNodeId, now(), fanOutKey)if (!flow.ok) retryAfterMs = flow.outcome.retryAfterMselse reservation = flow}@@ -687,13 +690,18 @@ export async function runDelivery(// No await between the record and the release: the recorded send replaces the hold in the// same tick, so no concurrent reservation can slip through the seam between them.- if (WROTE.has(outcome.kind)) noteSent(flowSource, req.targetNodeId, now())+ if (WROTE.has(outcome.kind)) noteSent(flowSource, req.targetNodeId, now(), fanOutKey)return outcome} finally {reservation?.release()}}+/** What a board comment additionally waits out instead of being refused: the pair window. An agent+ * told `rateLimited` retries on its own; a person could only post the comment again. The flush+ * re-runs the limiter, so a queued comment still never lands inside the window. */+const BOARD_QUEUE_ON: ReadonlySet<AgentMessageOutcome['kind']> = new Set(['rateLimited'])+/** The `AgentMessageOutcome` kinds a permitted-but-not-ready target produces — a busy agent, or a* node between sessions. Only these are enqueued (and only with a queue wired): the target passed* scope/ownership/grant, and its non-readiness is a turn it happens to be in, not a boundary. */@@ -752,6 +760,8 @@ async function deliverWithQueue({ hibernated })if (QUEUE_ON_BUSY.has(outcome.kind)) return answer(await queued(false))+ if (req.verb === 'board-comment' && BOARD_QUEUE_ON.has(outcome.kind))+ return answer(await queued(false))// A hibernated target reads as `targetNotAgentPane` (its pane is a shell) — enqueue+wake ONLY// then, never for a real non-agent pane.if (outcome.kind === 'targetNotAgentPane' && deps.isHibernated?.(req.targetNodeId))@@ -760,11 +770,6 @@ async function deliverWithQueue(return answer(outcome)}-/** The comment currently spending each board's flow budget. A NEW comment starts a new turn for- * its author — the board's fan-out budget resets, exactly as an agent's does on its own `newTurn`.- * Bounded by the number of boards; a lost entry (restart) only means a fresh budget. */-const boardTurnComment = new Map<string, string>()-/*** Deliver ONE mentioned session's copy of a board comment the local user just posted.*@@ -782,11 +787,6 @@ export async function deliverBoardCommentFromUi(): Promise<AgentMessageReply> {if (!isBoardCommentDeliverRequest(raw))return { ok: false, error: 'malformed board-comment delivery request. Do not retry.' }- const source = boardFlowSource(raw.projectId)- if (boardTurnComment.get(source) !== raw.commentId) {- noteNewTurn(source)- boardTurnComment.set(source, raw.commentId)- }const { reply } = await deliverWithQueue({verb: 'board-comment',diff --git a/src/core/agents/board-comment-messaging.test.ts b/src/core/agents/board-comment-messaging.test.tsindex 635364585..99bdd9b5b 100644--- a/src/core/agents/board-comment-messaging.test.ts+++ b/src/core/agents/board-comment-messaging.test.ts@@ -30,6 +30,8 @@ import {mentionToken} from '../../shared/board-comment'import { FANOUT_PER_TURN } from './agent-message-flow'+import { DELIVERY_QUEUE_TTL_MS } from './delivery-queue'+import { BOARD_COMMENT_QUEUE_STALE_MS } from '../../shared/board-comment'const idle: MirrorEntry = {state: 'done',@@ -224,6 +226,64 @@ describe('flow control for a person', () => {expect(deps.rec.sent).toHaveLength(1)})+ it('with a queue wired, the pair-limited second comment WAITS instead — a person cannot retry', async () => {+ // An agent told `rateLimited` retries; a person would have to post the comment again. So a board+ // comment that hits the pair limit is held like a busy target's and flushed on the next idle —+ // still never inside the window (the flush re-runs the limiter).+ let t = 1_000_000+ const deps = fakeDeps({ now: () => t })+ deps.queue = createDeliveryQueue(deps, { schedule: () => () => {} })+ expect((await deliverBoardCommentFromUi(comment('b1'), deps)).ok).toBe(true)+ const second = await deliverBoardCommentFromUi(comment('b1'), deps)+ expect((second.result as { kind: string }).kind).toBe('queued')+ t += 11_000+ onMessagingAgentEvent({ nodeId: 'b1', state: 'done', verified: true, newTurn: false }, deps.queue)+ await vi.waitFor(() => expect(deps.rec.sent).toHaveLength(2))+ })++ it('a comment\'s budget is its own: another comment still in flight does not spend it', async () => {+ // Comment 1 mentions four sessions and its deliveries are still waiting on their receipts when+ // comment 2 mentions a fifth, never-messaged session. Before: comment 1's in-flight holds+ // counted against comment 2 and it came back `rateLimited` ("moments ago") — false.+ let release!: () => void+ const gate = new Promise<void>((r) => (release = r))+ const deps = fakeDeps({+ sendEnvelope: async (nodeId, payload) => {+ if (nodeId !== 'b5') await gate+ deps.rec.sent.push({ nodeId, payload })+ return true+ }+ })+ const first = ['b1', 'b2', 'b3', 'b4']+ const c1 = comment('b1', first.map((t) => mentionToken(t, t)).join(' '))+ const inflight = first.map((t) => deliverBoardCommentFromUi({ ...c1, targetNodeId: t }, deps))+ await new Promise((r) => setTimeout(r, 1))+ let kind: string+ try {+ kind = ((await deliverBoardCommentFromUi(comment('b5'), deps)).result as { kind: string }).kind+ } finally {+ release() // never leave comment 1's node locks held for the next test+ await Promise.all(inflight)+ }+ expect(kind).toBe('delivered')+ })++ it('a queued comment is charged to ITSELF when it flushes, not to whatever was posted since', async () => {+ let entry: MirrorEntry = busy+ const deps = fakeDeps({ mirrorEntry: (id) => (id === 'b1' ? entry : idle) })+ deps.queue = createDeliveryQueue(deps, { schedule: () => () => {} })+ const c1 = comment('b1')+ expect(((await deliverBoardCommentFromUi(c1, deps)).result as { kind: string }).kind).toBe('queued')+ // A later comment spends four deliveries on other sessions.+ const others = ['b2', 'b3', 'b4', 'b5']+ const c2 = comment('b2', others.map((t) => mentionToken(t, t)).join(' '))+ for (const t of others)+ expect(((await deliverBoardCommentFromUi({ ...c2, targetNodeId: t }, deps)).result as { kind: string }).kind).toBe('delivered')+ entry = idle+ onMessagingAgentEvent({ nodeId: 'b1', state: 'done', verified: true, newTurn: false }, deps.queue)+ await vi.waitFor(() => expect(deps.rec.sent.map((s) => s.nodeId)).toContain('b1'))+ })+it('each comment is its own turn: a new comment has a fresh fan-out budget', async () => {expect(BOARD_COMMENT_MENTION_MAX).toBe(FANOUT_PER_TURN)const deps = fakeDeps()@@ -293,6 +353,31 @@ describe('deliver-on-idle for a board comment', () => {)})+ it('an expiry lands on the comment\'s OWN board even if the pane is now owned by another project', async () => {+ let fire: (() => void) | null = null+ let owner: string | undefined = 'p1'+ const deps = fakeDeps({ mirrorEntry: () => busy, paneOwnerProject: () => owner })+ deps.queue = createDeliveryQueue(deps, {+ schedule: (_ms, fn) => {+ fire = fn+ return () => {+ fire = null+ }+ }+ })+ const c = comment('b1')+ expect(((await deliverBoardCommentFromUi(c, deps)).result as { kind: string }).kind).toBe('queued')+ owner = 'p2' // the session was respawned from another project while the comment waited+ fire!()+ await vi.waitFor(() =>+ expect(+ deps.rec.log.some((l) => l.entry.event?.from === boardCommentSourceId(c.commentId) && l.entry.event.title === 'expired')+ ).toBe(true)+ )+ const expired = deps.rec.log.filter((l) => l.entry.event?.title === 'expired')+ expect(expired.map((l) => l.projectId)).toEqual(['p1'])+ })+it('an expiry is recorded in the comment\'s board even when the pane owner is no longer proven', async () => {let fire: (() => void) | null = nulllet owner: string | undefined = 'p1'@@ -321,6 +406,10 @@ describe('deliver-on-idle for a board comment', () => {})describe('the row text', () => {+ it('a row stops calling a comment "queued" only after the queue itself would have dropped it', () => {+ expect(BOARD_COMMENT_QUEUE_STALE_MS).toBeGreaterThan(DELIVERY_QUEUE_TTL_MS)+ })+it('names every outcome the core can produce — no kind falls through to silence', () => {for (const kind of Object.keys(RETRYABLE)) {const t = boardCommentOutcomeText(kind)diff --git a/src/core/agents/delivery-queue.ts b/src/core/agents/delivery-queue.tsindex 3da55afff..0b8ee8c62 100644--- a/src/core/agents/delivery-queue.ts+++ b/src/core/agents/delivery-queue.ts@@ -86,8 +86,9 @@ export interface DeliveryQueueDeps {*/deliver(req: QueuedDeliveryRequest): Promise<AgentMessageOutcome>/** Record an outcome (`recordDelivery`). The queue traces `queued` on enqueue and `expired` on a- * TTL lapse; the flush's own outcomes are traced inside `deliver`. */- trace(input: DeliveryTraceInput): Promise<{ traceId: string; traced: string }>+ * TTL lapse; the flush's own outcomes are traced inside `deliver`. `req` is the queued request+ * itself, so a shell can route the line by what the request carries (a board comment's board). */+ trace(input: DeliveryTraceInput, req?: QueuedDeliveryRequest): Promise<{ traceId: string; traced: string }>/*** Wake a hibernated target through the existing registry (`agent-restart.ts` hibernate/wake* pair). Optional: a target that is merely busy (not hibernated) needs no wake, and a shell with@@ -182,7 +183,7 @@ export class DeliveryQueue {targetNodeId: req.targetNodeId,outcome: 'queued',bodyChars: req.body.length- })+ }, req)const entry: QueueEntry = {req,enqueuedAt: now,@@ -260,7 +261,7 @@ export class DeliveryQueue {targetNodeId: entry.req.targetNodeId,outcome: 'expired',bodyChars: entry.req.body.length- })+ }, entry.req)this.deps.onExpired?.(entry.req, { traceId: t.traceId, queuedForMs })}diff --git a/src/renderer/components/kanban/BoardLogPanel.tsx b/src/renderer/components/kanban/BoardLogPanel.tsxindex 1cce664a4..ff675844f 100644--- a/src/renderer/components/kanban/BoardLogPanel.tsx+++ b/src/renderer/components/kanban/BoardLogPanel.tsx@@ -133,6 +133,7 @@ export function BoardLogPanel({ card, title, readOnly, emptyText, mentionables }const unsupported = useBoardLog((s) => !!s.unsupportedByProject[projectId])const error = useBoardLog((s) => !!s.errorByProject[projectId])const deliveries = useBoardCommentDelivery((s) => s.byComment)+ const sent = useBoardCommentDelivery((s) => s.sent)const [draft, setDraft] = useState('')const [composeError, setComposeError] = useState<string | null>(null)const [picker, setPicker] = useState<{ start: number; caret: number; query: string } | null>(null)@@ -183,25 +184,38 @@ export function BoardLogPanel({ card, title, readOnly, emptyText, mentionables }})}+ /** Re-read the @query at the caret — on every edit, and whenever the caret moves (a click, an+ * arrow key), so the picker never inserts at a place the user has left. */+ const syncPicker = (value: string, caret: number): void => {+ const q = candidates.length ? mentionQueryAt(value, caret) : null+ setPicker((cur) => {+ if (!q) return null+ if (cur && cur.start === q.start && cur.query === q.query && cur.caret === caret) return cur+ return { ...q, caret }+ })+ }+const onDraftChange = (value: string, caret: number): void => {setDraft(value)setComposeError(null)- const q = candidates.length ? mentionQueryAt(value, caret) : null- setPicker(q ? { ...q, caret } : null)+ syncPicker(value, caret)setPick(0)}// Card-scoped: this card's comments + its own events. Column events (no nodeId) never match. A- // board comment's delivery line is shown on its comment's row, so it is not a row of its own when- // that comment is in the log; `traces` reads the WHOLE log, because the line is filed under the- // session it was delivered to, which is not necessarily this card.+ // board comment's delivery line is shown ON its comment's row — so it is not also a row of its own+ // when that comment is on THIS card and is one this machine sent (the only comments whose row+ // shows a status). Everywhere else — the mentioned session's own card, a teammate's comment — it+ // stays a line. `traces` reads the WHOLE log: a line is filed under the session it went to.const all = entries ?? []- const commentIds = useMemo(() => new Set(all.filter((e) => e.kind === 'comment').map((e) => e.id)), [all])+ const ownHere = new Set(+ all.filter((e) => e.kind === 'comment' && e.nodeId === card.id && sent[e.id] !== undefined).map((e) => e.id)+ )const traces = useMemo(() => boardCommentTraces(all), [all])const feed = all.filter((e) =>e.nodeId === card.id &&- !(isBoardCommentTrace(e) && commentIds.has(commentIdOfSource(e.event?.from) ?? ''))+ !(isBoardCommentTrace(e) && ownHere.has(commentIdOfSource(e.event?.from) ?? '')))const titles = useMemo(() => new Map((mentionables ?? []).map((m) => [m.id, m.title])), [mentionables])const pending = canDeliver ? parseMentions(draft) : []@@ -221,6 +235,17 @@ export function BoardLogPanel({ card, title, readOnly, emptyText, mentionables }aria-autocomplete={candidates.length ? 'list' : undefined}aria-expanded={options.length > 0 ? true : undefined}onChange={(e) => onDraftChange(e.target.value, e.target.selectionStart ?? e.target.value.length)}+ onKeyUp={(e) => {+ // A caret move (arrows, Home/End) — the keys that edit already went through onChange.+ if (!picker || e.nativeEvent.isComposing) return+ const el = e.currentTarget+ syncPicker(el.value, el.selectionStart ?? el.value.length)+ }}+ onClick={(e) => {+ const el = e.currentTarget+ syncPicker(el.value, el.selectionStart ?? el.value.length)+ }}+ onBlur={() => setPicker(null)}onKeyDown={(e) => {// Never act mid-IME-composition (e.g. selecting a kanji candidate with Enter).if (e.nativeEvent.isComposing) return@@ -286,7 +311,12 @@ export function BoardLogPanel({ card, title, readOnly, emptyText, mentionables }<BoardLogFeedfeed={feed}titles={titles}- statusesFor={(entry) => mentionStatuses(entry, traces, deliveries[entry.id])}+ statusesFor={(entry) =>+ mentionStatuses(entry, traces, deliveries[entry.id], {+ own: sent[entry.id] !== undefined,+ now: Date.now()+ })+ }/></div>)diff --git a/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx b/src/renderer/components/kanban/CardModal.mentionEscape.test.tsxnew file mode 100644index 000000000..a08734e3e--- /dev/null+++ b/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx@@ -0,0 +1,73 @@+// @vitest-environment jsdom+/**+ * Escape while the comment composer's @ picker is open closes the PICKER, not the card modal — the+ * modal's own Escape runs in the capture phase, ahead of the composer, and used to close the whole+ * modal (and throw the draft away) instead.+ */+import { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import type { ProjectKanban } from '@shared/types'+import { resetDialogStack } from '../dialog-stack'+import { CardModal } from './CardModal'+import type { KanbanSession } from './KanbanView'++const picker = vi.hoisted(() => ({ open: true }))++vi.mock('../../session/session', () => ({+ useSession: () => ({ api: { pty: {}, shell: {} } })+}))+vi.mock('./BoardLogPanel', () => ({+ BoardLogPanel: () => (+ <textarea className="board-log__composer" aria-expanded={picker.open ? true : undefined} />+ )+}))+vi.mock('./CardMetaBar', () => ({ CardMetaBar: () => null }))+vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const board: ProjectKanban = { columns: [{ id: 'c', title: 'To Do', color: '#3b82f6' }], assignments: [] }+const session: KanbanSession = { id: 'n1', title: 'Note', color: '#ffd60a', kind: 'sticky', text: 'x', spawn: {} }++describe('CardModal Escape vs the comment @ picker', () => {+ let host: HTMLDivElement+ beforeEach(() => {+ resetDialogStack()+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { onMarkdownToggle: () => () => {} }+ host = document.createElement('div')+ document.body.append(host)+ })+ afterEach(() => {+ resetDialogStack()+ document.body.innerHTML = ''+ })++ async function escapeInComposer(): Promise<ReturnType<typeof vi.fn>> {+ const onClose = vi.fn()+ const root = createRoot(host)+ await act(async () => {+ root.render(+ <CardModal session={session} columnTitle={null} board={board} onChangeBoard={vi.fn()} onClose={onClose}+ onOpenCanvas={vi.fn()} onRename={vi.fn()} onEditSticky={vi.fn()} onBrowserNav={vi.fn()} onSetIcon={vi.fn()} />+ )+ })+ const ta = document.querySelector('.board-log__composer') as HTMLTextAreaElement+ ta.focus()+ await act(async () => {+ ta.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true, cancelable: true }))+ })+ act(() => root.unmount())+ return onClose+ }++ it('an open picker keeps Escape', async () => {+ picker.open = true+ expect(await escapeInComposer()).not.toHaveBeenCalled()+ })++ it('with no picker open, Escape in the composer still closes the modal (unchanged)', async () => {+ picker.open = false+ expect(await escapeInComposer()).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsxindex 1863e371c..377cd0bdc 100644--- a/src/renderer/components/kanban/CardModal.tsx+++ b/src/renderer/components/kanban/CardModal.tsx@@ -276,6 +276,9 @@ export function CardModal({ session, columnTitle, board, onChangeBoard, onClose,// Esc, and closing the whole modal from inside it (or from the composer) threw the typed text// away. This listener runs in the CAPTURE phase, before any field's own handler could stop it.if (ae && ae.closest('.term-chat__answer, .term-chat__compose')) return+ // The board-comment composer's @ picker owns Esc while it is open (it closes the picker; the+ // draft stays). `aria-expanded` is set on the textarea exactly while the picker shows options.+ if (ae && ae.closest('.board-log__composer[aria-expanded="true"]')) returne.preventDefault()e.stopPropagation()onClose()diff --git a/src/renderer/components/kanban/NodeCommentsPanel.test.tsx b/src/renderer/components/kanban/NodeCommentsPanel.test.tsxnew file mode 100644index 000000000..1944650cd--- /dev/null+++ b/src/renderer/components/kanban/NodeCommentsPanel.test.tsx@@ -0,0 +1,59 @@+// @vitest-environment jsdom+/**+ * The canvas node's comments flyout offers the same @mention candidates the card modal does — the+ * agent sessions on the canvas — and follows the canvas when one is added or renamed.+ */+import { act, useEffect } from 'react'+import { createRoot } from 'react-dom/client'+import { describe, expect, it, vi } from 'vitest'+import { ReactFlowProvider, useStoreApi, type Node } from '@xyflow/react'+import { NodeCommentsPanel } from './NodeCommentsPanel'++const seen = vi.hoisted(() => ({ calls: [] as unknown[] }))+vi.mock('./BoardLogPanel', () => ({+ BoardLogPanel: (p: { mentionables?: unknown }) => {+ seen.calls.push(p.mentionables)+ return null+ }+}))++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++const node = (id: string, type: string, data: Record<string, unknown>): Node => ({ id, type, position: { x: 0, y: 0 }, data })++function Seed({ nodes }: { nodes: Node[] }) {+ const store = useStoreApi()+ useEffect(() => store.setState({ nodes }), [store, nodes])+ return null+}++describe('NodeCommentsPanel', () => {+ it('hands the panel the canvas\'s agent sessions, and follows a rename', async () => {+ const host = document.createElement('div')+ const root = createRoot(host)+ const first = [+ node('a', 'terminal', { title: 'Alpha', agentId: 'claude' }),+ node('s', 'sticky', { text: 'note' }),+ node('t', 'terminal', { title: 'Shell' })+ ]+ await act(async () => {+ root.render(+ <ReactFlowProvider>+ <Seed nodes={first} />+ <NodeCommentsPanel id="a" />+ </ReactFlowProvider>+ )+ })+ expect(seen.calls.at(-1)).toEqual([{ id: 'a', title: 'Alpha' }])+ await act(async () => {+ root.render(+ <ReactFlowProvider>+ <Seed nodes={[node('a', 'terminal', { title: 'Renamed', agentId: 'claude' }), ...first.slice(1)]} />+ <NodeCommentsPanel id="a" />+ </ReactFlowProvider>+ )+ })+ expect(seen.calls.at(-1)).toEqual([{ id: 'a', title: 'Renamed' }])+ act(() => root.unmount())+ })+})diff --git a/src/renderer/components/kanban/NodeCommentsPanel.tsx b/src/renderer/components/kanban/NodeCommentsPanel.tsxindex e99049c53..dbd773efa 100644--- a/src/renderer/components/kanban/NodeCommentsPanel.tsx+++ b/src/renderer/components/kanban/NodeCommentsPanel.tsx@@ -1,5 +1,5 @@-import { useMemo } from 'react'-import { useStore } from '@xyflow/react'+import { useCallback, useMemo, useRef } from 'react'+import { useStore, type ReactFlowState } from '@xyflow/react'import { mentionCandidatesFromNodes } from '../../lib/boardMentions'import type { CanvasNode } from '../../state/workspace'import { BoardLogPanel } from './BoardLogPanel'@@ -7,13 +7,19 @@ import { BoardLogPanel } from './BoardLogPanel'/*** The canvas node's comments flyout: the same `BoardLogPanel` the card modal shows, with the same* @mention candidates — the agent sessions on this canvas, built through the board's own mapping.- * Mounted only while the flyout is open, and it re-renders only when that candidate list changes- * (the selector returns a string), not on every drag frame's new node array.+ * Mounted only while the flyout is open. The selector recomputes only when the node ARRAY changes+ * (a pan or zoom leaves it alone), and it returns a string, so the panel re-renders only when the+ * candidate list itself changes — not on every drag frame.*/export function NodeCommentsPanel({ id }: { id: string }) {- const signature = useStore((s) =>- JSON.stringify(mentionCandidatesFromNodes(s.nodes as unknown as CanvasNode[]))- )+ const cache = useRef<{ nodes: unknown; signature: string } | null>(null)+ const select = useCallback((s: ReactFlowState) => {+ if (cache.current?.nodes === s.nodes) return cache.current.signature+ const signature = JSON.stringify(mentionCandidatesFromNodes(s.nodes as unknown as CanvasNode[]))+ cache.current = { nodes: s.nodes, signature }+ return signature+ }, [])+ const signature = useStore(select)const mentionables = useMemo(() => JSON.parse(signature) as ReturnType<typeof mentionCandidatesFromNodes>,[signature]diff --git a/src/renderer/components/kanban/board-comment-panel.test.tsx b/src/renderer/components/kanban/board-comment-panel.test.tsxindex c2da628ee..b46afb5f5 100644--- a/src/renderer/components/kanban/board-comment-panel.test.tsx+++ b/src/renderer/components/kanban/board-comment-panel.test.tsx@@ -205,6 +205,7 @@ describe('a comment that ARRIVES is display-only', () => {describe('durable outcomes', () => {it('a reloaded comment row reads its outcome from the log; the trace line is not a row of its own', async () => {+ useBoardCommentDelivery.getState().markSent('c-7') // sent by this machine in an earlier runconst c: BoardLogEntry = {id: 'c-7',ts: 10,@@ -227,4 +228,75 @@ describe('durable outcomes', () => {expect(host.querySelector('.board-log__comment')?.textContent).toMatch(/expired/)expect(delivered).toEqual([])})++ it('a teammate\'s comment shows no status on its row; its delivery lines stay visible as lines', async () => {+ const c: BoardLogEntry = {+ id: 'c-8',+ ts: 10,+ author: { name: 'Teammate', color: '#0ff' },+ kind: 'comment',+ nodeId: 'card-a',+ text: `${mentionToken('card-a', 'Self')} go`+ }+ const trace: BoardLogEntry = {+ id: 't-8',+ ts: 20,+ author: { name: 'nodeterm', color: '#8b8b8b' },+ kind: 'event',+ nodeId: 'card-a',+ event: { type: 'agent-message', from: boardCommentSourceId('c-8'), to: 'card-a', title: 'delivered' }+ }+ h.loaded = [trace, c]+ await mount()+ expect(host.querySelector('.board-log__deliveries')).toBeNull()+ expect(host.querySelector('.board-log__event')?.textContent).toMatch(/routed a board comment here: delivered/)+ })++ it('the MENTIONED session\'s own card shows the routed line when the comment was written elsewhere', async () => {+ useBoardCommentDelivery.getState().markSent('c-9')+ const c: BoardLogEntry = {+ id: 'c-9',+ ts: 10,+ author: { name: 'Enes', color: '#fff' },+ kind: 'comment',+ nodeId: 'card-x',+ text: `${mentionToken('card-a', 'A')} go`+ }+ const trace: BoardLogEntry = {+ id: 't-9',+ ts: 20,+ author: { name: 'nodeterm', color: '#8b8b8b' },+ kind: 'event',+ nodeId: 'card-a',+ event: { type: 'agent-message', from: boardCommentSourceId('c-9'), to: 'card-a', title: 'queued' }+ }+ h.loaded = [trace, c]+ await mount() // card-a's panel+ expect(host.querySelector('.board-log__event')?.textContent).toMatch(/routed a board comment here: queued/)+ })+})++describe('the picker follows the caret', () => {+ it('moving the caret away from the @query closes it — Enter then sends instead of inserting', async () => {+ await mount()+ await type('hi @be')+ expect(host.querySelectorAll('[role="option"]')).toHaveLength(1)+ await act(async () => {+ textarea().setSelectionRange(0, 0)+ textarea().dispatchEvent(new KeyboardEvent('keyup', { key: 'Home', bubbles: true }))+ })+ expect(host.querySelectorAll('[role="option"]')).toHaveLength(0)+ await key('Enter')+ expect(api.boardLog.append).toHaveBeenCalledTimes(1)+ })++ it('leaving the composer closes it', async () => {+ await mount()+ await type('@be')+ expect(host.querySelectorAll('[role="option"]')).toHaveLength(1)+ await act(async () => {+ textarea().dispatchEvent(new FocusEvent('focusout', { bubbles: true }))+ })+ expect(host.querySelectorAll('[role="option"]')).toHaveLength(0)+ })})diff --git a/src/renderer/lib/boardCommentDelivery.test.ts b/src/renderer/lib/boardCommentDelivery.test.tsindex e612c334c..9e8cff4ca 100644--- a/src/renderer/lib/boardCommentDelivery.test.ts+++ b/src/renderer/lib/boardCommentDelivery.test.ts@@ -78,6 +78,8 @@ describe('deliverCommentMentions', () => {['b1'])expect(useBoardCommentDelivery.getState().byComment.c1.b1.state).toBe('sending')+ // Marked as THIS machine's comment before anything else: its log outcomes are trusted after a reload.+ expect(useBoardCommentDelivery.getState().sent.c1).toBeTypeOf('number')finish({ ok: false, result: { kind: 'notPermitted', reason: 'switch-off' } })await runexpect(useBoardCommentDelivery.getState().byComment.c1.b1).toMatchObject({diff --git a/src/renderer/lib/boardCommentDelivery.ts b/src/renderer/lib/boardCommentDelivery.tsindex b333256be..2a058c085 100644--- a/src/renderer/lib/boardCommentDelivery.ts+++ b/src/renderer/lib/boardCommentDelivery.ts@@ -84,6 +84,9 @@ export async function deliverCommentMentions(targets: readonly string[]): Promise<void> {const store = useBoardCommentDelivery.getState()+ // Remembered as THIS machine's comment before anything is sent: its row may then trust the log's+ // delivery lines for it after a reload (and no one else's).+ store.markSent(comment.commentId)for (const t of targets) store.set(comment.commentId, t, { at: Date.now(), state: 'sending' })await Promise.all(targets.map(async (targetNodeId) => {diff --git a/src/renderer/lib/boardCommentStatus.test.ts b/src/renderer/lib/boardCommentStatus.test.tsindex 69e96841c..d87da3fce 100644--- a/src/renderer/lib/boardCommentStatus.test.ts+++ b/src/renderer/lib/boardCommentStatus.test.ts@@ -1,6 +1,6 @@import { describe, it, expect } from 'vitest'import type { BoardLogEntry } from '@shared/types'-import { boardCommentSourceId, mentionToken } from '@shared/board-comment'+import { BOARD_COMMENT_QUEUE_STALE_MS, boardCommentSourceId, mentionToken } from '@shared/board-comment'import { boardCommentTraces, isBoardCommentTrace, mentionStatuses } from './boardCommentStatus'const comment = (id: string, text: string, ts = 100): BoardLogEntry => ({@@ -22,6 +22,8 @@ const trace = (commentId: string, to: string, title: string, ts: number, reason?})const text = `${mentionToken('b1', 'Beta')} and ${mentionToken('b2', 'Two')} go`+/** A comment THIS machine sent, looked at shortly after. */+const own = { own: true, now: 1_000 }describe('mentionStatuses', () => {it('reads each mention\'s LATEST recorded outcome from the log, in mention order', () => {@@ -31,7 +33,7 @@ describe('mentionStatuses', () => {trace('c1', 'b1', 'queued', 200),comment('c1', text)]- const s = mentionStatuses(comment('c1', text), boardCommentTraces(entries))+ const s = mentionStatuses(comment('c1', text), boardCommentTraces(entries), undefined, own)expect(s.map((m) => m.nodeId)).toEqual(['b1', 'b2'])expect(s[0].view).toEqual({ tone: 'ok', text: 'delivered' })expect(s[1].view.text).toMatch(/agent messaging is off for this project/)@@ -42,22 +44,46 @@ describe('mentionStatuses', () => {const s = mentionStatuses(comment('c1', text), traces, {b1: { at: 250, state: 'done', kind: 'rateLimited' },b2: { at: 150, state: 'sending' }- })+ }, own)expect(s[0].view.text).toMatch(/moments ago/)expect(s[1].view).toEqual({ tone: 'pending', text: 'sending…' })})it('a failure with no typed outcome still says it was not delivered', () => {- const s = mentionStatuses(comment('c1', text), new Map(), {+ const s = mentionStatuses(comment('c1', `${mentionToken('b1', 'Beta')} go`), new Map(), {b1: { at: 1, state: 'done', kind: 'error', error: 'Message not sent: resolve the conflict.' }- })+ }, own)expect(s).toEqual([{ nodeId: 'b1', view: { tone: 'error', text: 'not delivered — Message not sent: resolve the conflict.' } }])})- it('a mention with no record at all shows nothing — a pulled comment is not claimed delivered', () => {- expect(mentionStatuses(comment('c9', text), new Map())).toEqual([])+ it('a comment this machine did NOT send shows no status — even when the log holds outcomes for it', () => {+ // A teammate's comment arrives by git pull WITH their machine's trace lines. Those describe a+ // delivery on their machine; on this row they would read as "delivered here".+ const entries = [trace('c9', 'b1', 'delivered', 300)]+ expect(mentionStatuses(comment('c9', text), boardCommentTraces(entries), undefined, { own: false, now: 1_000 })).toEqual([])+ })++ it('one of OUR comments with no outcome recorded says so, rather than showing nothing', () => {+ const s = mentionStatuses(comment('c1', `${mentionToken('b1', 'Beta')} go`), new Map(), undefined, own)+ expect(s).toEqual([{ nodeId: 'b1', view: { tone: 'warn', text: 'no delivery outcome was recorded' } }])+ })++ it('"queued" older than the queue can hold a message is not left looking live', () => {+ const entries = [trace('c1', 'b1', 'queued', 100)]+ const later = { own: true, now: 100 + BOARD_COMMENT_QUEUE_STALE_MS + 1 }+ const s = mentionStatuses(comment('c1', `${mentionToken('b1', 'Beta')} go`), boardCommentTraces(entries), undefined, later)+ expect(s[0].view.tone).toBe('warn')+ expect(s[0].view.text).toMatch(/no outcome was recorded/)+ })++ it('a future-dated log line cannot override what this app run saw', () => {+ const entries = [trace('c1', 'b1', 'delivered', 9_999_999)]+ const s = mentionStatuses(comment('c1', `${mentionToken('b1', 'Beta')} go`), boardCommentTraces(entries), {+ b1: { at: 900, state: 'done', kind: 'notPermitted', reason: 'switch-off' }+ }, own)+ expect(s[0].view.text).toMatch(/off for this project/)})it('another comment\'s lines never attach, and a forged `from` that is not a comment id is ignored', () => {@@ -65,7 +91,10 @@ describe('mentionStatuses', () => {trace('c2', 'b1', 'delivered', 300),{ ...trace('c1', 'b1', 'delivered', 300), event: { type: 'agent-message' as const, from: 'a1', to: 'b1', title: 'delivered' } }]- expect(mentionStatuses(comment('c1', text), boardCommentTraces(entries))).toEqual([])+ expect(mentionStatuses(comment('c1', text), boardCommentTraces(entries), undefined, own)).toEqual([+ { nodeId: 'b1', view: { tone: 'warn', text: 'no delivery outcome was recorded' } },+ { nodeId: 'b2', view: { tone: 'warn', text: 'no delivery outcome was recorded' } }+ ])})})diff --git a/src/renderer/lib/boardCommentStatus.ts b/src/renderer/lib/boardCommentStatus.tsindex f28bcaf0f..c5a51d734 100644--- a/src/renderer/lib/boardCommentStatus.ts+++ b/src/renderer/lib/boardCommentStatus.ts@@ -1,5 +1,6 @@import type { BoardLogEntry } from '@shared/types'import {+ BOARD_COMMENT_QUEUE_STALE_MS,boardCommentOutcomeText,commentIdOfSource,parseMentions,@@ -49,31 +50,56 @@ export function boardCommentTraces(return out}-function viewOf(d: MentionDelivery): BoardCommentOutcomeView {+/** A log line dated after "now" is not an outcome this machine recorded (the core stamps its own+ * clock), so it is ignored rather than allowed to outrank what this app run saw. */+const FUTURE_SLACK_MS = 60_000++const STALE_QUEUED: BoardCommentOutcomeView = {+ tone: 'warn',+ text: 'queued, but no outcome was recorded — the app may have closed before it was delivered'+}+const NOTHING_RECORDED: BoardCommentOutcomeView = { tone: 'warn', text: 'no delivery outcome was recorded' }++function viewOf(d: MentionDelivery, now: number): BoardCommentOutcomeView {if (d.state === 'sending') return { tone: 'pending', text: 'sending…' }if (d.kind === 'error') return { tone: 'error', text: `not delivered — ${d.error ?? 'unknown error'}` }+ if (d.kind === 'queued' && now - d.at > BOARD_COMMENT_QUEUE_STALE_MS) return STALE_QUEUEDreturn boardCommentOutcomeText(d.kind, d.reason)}/**- * The delivery status of each session a comment mentions, in the order the text mentions them: the- * newer of this app run's own record (`transient`) and the latest outcome the log holds. A mention- * with neither shows nothing — a comment that arrived by git pull, from a relay peer or from before- * this feature was never delivered by this app, and the row must not suggest otherwise.+ * The delivery status of each session a comment mentions, in the order the text mentions them.+ *+ * Only for a comment THIS machine sent (`own`). The log is shared: a teammate's comment arrives with+ * their machine's trace lines, and a forged line is one append away — on this row either would read+ * as a delivery that happened here. A comment that is not ours shows no status at all; its lines stay+ * visible in the feed as what they are (`eventBody`).+ *+ * For our own: the newer of this app run's record (`transient`) and the latest outcome the log holds.+ * A `queued` older than the queue can hold a message says it never finished. A mention with neither+ * record says nothing was recorded — a silence here could be read as success.*/export function mentionStatuses(comment: BoardLogEntry,traces: Map<string, Map<string, TraceOutcome>>,- transient?: Record<string, MentionDelivery>+ transient: Record<string, MentionDelivery> | undefined,+ opts: { own: boolean; now: number }): MentionStatus[] {if (comment.kind !== 'comment' || typeof comment.text !== 'string') return []- const logged = traces.get(comment.id)+ if (!opts.own && !transient) return []+ const logged = opts.own ? traces.get(comment.id) : undefinedconst out: MentionStatus[] = []for (const nodeId of parseMentions(comment.text)) {- const t = logged?.get(nodeId)+ const raw = logged?.get(nodeId)+ const t = raw && raw.ts <= opts.now + FUTURE_SLACK_MS ? raw : undefinedconst live = transient?.[nodeId]- if (live && (!t || live.at >= t.ts)) out.push({ nodeId, view: viewOf(live) })- else if (t) out.push({ nodeId, view: boardCommentOutcomeText(t.kind, t.reason) })+ if (live && (!t || live.at >= t.ts)) out.push({ nodeId, view: viewOf(live, opts.now) })+ else if (t)+ out.push({+ nodeId,+ view: viewOf({ at: t.ts, state: 'done', kind: t.kind, reason: t.reason }, opts.now)+ })+ else if (opts.own) out.push({ nodeId, view: NOTHING_RECORDED })}return out}diff --git a/src/renderer/state/boardCommentDelivery.test.ts b/src/renderer/state/boardCommentDelivery.test.tsnew file mode 100644index 000000000..112d20986--- /dev/null+++ b/src/renderer/state/boardCommentDelivery.test.ts@@ -0,0 +1,35 @@+// @vitest-environment jsdom+import { describe, it, expect, beforeEach } from 'vitest'+import { readSentComments, useBoardCommentDelivery, SENT_COMMENTS_KEY } from './boardCommentDelivery'++describe('which comments THIS machine sent', () => {+ beforeEach(() => {+ localStorage.clear()+ useBoardCommentDelivery.getState().reset()+ })++ it('survives a reload (localStorage) — it is what lets a reloaded row trust its log outcomes', () => {+ useBoardCommentDelivery.getState().markSent('c-1')+ expect(useBoardCommentDelivery.getState().sent['c-1']).toBeTypeOf('number')+ expect(Object.keys(readSentComments())).toEqual(['c-1'])+ })++ it('is bounded, oldest forgotten first', () => {+ for (let i = 0; i < 520; i++) useBoardCommentDelivery.getState().markSent(`c-${i}`)+ const kept = Object.keys(readSentComments())+ expect(kept.length).toBe(500)+ expect(kept).not.toContain('c-0')+ expect(kept).toContain('c-519')+ })++ it('a malformed or hostile stored value reads as nothing, never a crash', () => {+ for (const raw of ['{', '5', '{"a":"x","__proto__":1}', JSON.stringify({ 'bad id': 1, ok: 2 })]) {+ localStorage.setItem(SENT_COMMENTS_KEY, raw)+ const r = readSentComments()+ for (const [k, v] of Object.entries(r)) {+ expect(/^[A-Za-z0-9-]{1,64}$/.test(k), raw).toBe(true)+ expect(typeof v).toBe('number')+ }+ }+ })+})diff --git a/src/renderer/state/boardCommentDelivery.ts b/src/renderer/state/boardCommentDelivery.tsindex 476cbe80b..82ac86f1b 100644--- a/src/renderer/state/boardCommentDelivery.ts+++ b/src/renderer/state/boardCommentDelivery.ts@@ -1,4 +1,35 @@import { create } from 'zustand'+import { readLocal, writeLocal } from '../lib/localStore'++/** localStorage key for the comments THIS machine delivered (id → when). */+export const SENT_COMMENTS_KEY = 'nodeterm.boardCommentsSent'+const SENT_MAX = 500+const COMMENT_ID_RE = /^[A-Za-z0-9-]{1,64}$/++/**+ * The comments this machine delivered, as stored. A comment row trusts the board log's delivery+ * lines ONLY for these: the log is shared, and a teammate's comment arrives with THEIR machine's+ * trace lines, which on this row would read as "delivered here". Per viewer and best-effort by+ * design (a cleared store only means an old row shows no status). Every entry is re-checked.+ */+export function readSentComments(): Record<string, number> {+ const out: Record<string, number> = {}+ try {+ const raw = readLocal(SENT_COMMENTS_KEY)+ const parsed: unknown = raw ? JSON.parse(raw) : null+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return out+ for (const [k, v] of Object.entries(parsed as Record<string, unknown>))+ if (COMMENT_ID_RE.test(k) && typeof v === 'number' && Number.isFinite(v)) out[k] = v+ } catch {+ // unreadable ⇒ nothing remembered+ }+ return out+}++/** Best-effort (`writeLocal` never throws); the in-memory copy still answers for this app run. */+function writeSent(sent: Record<string, number>): void {+ writeLocal(SENT_COMMENTS_KEY, JSON.stringify(sent))+}/*** What THIS app run knows about the deliveries of the board comments the local user posted:@@ -18,12 +49,24 @@ const MAX_COMMENTS = 200interface BoardCommentDeliveryState {byComment: Record<string, Record<string, MentionDelivery>>+ /** Comments this machine delivered (persisted — see `readSentComments`). */+ sent: Record<string, number>+ markSent(commentId: string): voidset(commentId: string, targetNodeId: string, d: MentionDelivery): voidreset(): void}export const useBoardCommentDelivery = create<BoardCommentDeliveryState>((set) => ({byComment: {},+ sent: readSentComments(),+ markSent: (commentId) =>+ set((s) => {+ const next = { ...s.sent, [commentId]: Date.now() }+ const ids = Object.keys(next).sort((a, b) => next[a] - next[b])+ for (const id of ids.slice(0, Math.max(0, ids.length - SENT_MAX))) delete next[id]+ writeSent(next)+ return { sent: next }+ }),set: (commentId, targetNodeId, d) =>set((s) => {const next = { ...s.byComment, [commentId]: { ...s.byComment[commentId], [targetNodeId]: d } }@@ -31,5 +74,5 @@ export const useBoardCommentDelivery = create<BoardCommentDeliveryState>((set) =for (const id of ids.slice(0, Math.max(0, ids.length - MAX_COMMENTS))) delete next[id]return { byComment: next }}),- reset: () => set({ byComment: {} })+ reset: () => set({ byComment: {}, sent: {} })}))diff --git a/src/shared/board-comment.test.ts b/src/shared/board-comment.test.tsindex 54a293e69..d19adbac4 100644--- a/src/shared/board-comment.test.ts+++ b/src/shared/board-comment.test.ts@@ -11,7 +11,8 @@ import {isBoardCommentDeliverRequest,mentionLabel,mentionToken,- parseMentions+ parseMentions,+ boardCommentOutcomeText} from './board-comment'describe('mention tokens', () => {@@ -125,3 +126,16 @@ describe('isBoardCommentDeliverRequest', () => {expect(isBoardCommentDeliverRequest(bad), JSON.stringify(bad)).toBe(false)})})++describe('boardCommentOutcomeText reads values from a SHARED log', () => {+ it('an inherited key is not an outcome — never an empty or code-shaped sentence', () => {+ for (const kind of ['constructor', '__proto__', 'toString', 'hasOwnProperty']) {+ const v = boardCommentOutcomeText(kind)+ expect(v, kind).toEqual({ tone: 'error', text: 'not delivered' })+ }+ expect(boardCommentOutcomeText('notPermitted', 'toString')).toEqual({+ tone: 'error',+ text: 'not delivered — not permitted'+ })+ })+})diff --git a/src/shared/board-comment.ts b/src/shared/board-comment.tsindex 694f56ca0..11606afed 100644--- a/src/shared/board-comment.ts+++ b/src/shared/board-comment.ts@@ -35,6 +35,12 @@ export const BOARD_COMMENT_MENTION_MAX = 4* (`BOARD_LOG_TEXT_MAX`), so what the agent reads is what the board shows. */export const BOARD_COMMENT_BODY_MAX = 16_384+/** How long after a `queued` outcome a comment row stops presenting it as live: the core's+ * deliver-on-idle TTL (`DELIVERY_QUEUE_TTL_MS`, 5 min — pinned by a core test) plus a minute. The+ * queue is process memory; an app that quit while a comment waited never writes its end, and a+ * row reading "queued" forever would be a silent lie. */+export const BOARD_COMMENT_QUEUE_STALE_MS = 6 * 60_000+/** The trace/queue identity of a delivery started by a board comment: `board-comment:<commentId>`.* A node id is `[A-Za-z0-9._-]`, so the ':' guarantees this never names, or collides with, a* node. The comment id is what lets the comment row find its own delivery outcomes in the log. */@@ -241,7 +247,9 @@ const NOT_PERMITTED_TEXT: Record<string, string> = {* reason when there is one. Both come from the shared log for a reloaded row, so an unknown value* still yields a sentence — never an empty one. */export function boardCommentOutcomeText(kind: string, reason?: unknown): BoardCommentOutcomeView {- if (kind === 'notPermitted' && typeof reason === 'string' && NOT_PERMITTED_TEXT[reason])+ // Own keys only: `kind`/`reason` come from a shared file, and a bare `table[key]` answers+ // `constructor` or `toString` with an inherited function instead of "unknown".+ if (kind === 'notPermitted' && typeof reason === 'string' && Object.hasOwn(NOT_PERMITTED_TEXT, reason))return { tone: 'error', text: NOT_PERMITTED_TEXT[reason] }- return OUTCOME_TEXT[kind] ?? { tone: 'error', text: 'not delivered' }+ return Object.hasOwn(OUTCOME_TEXT, kind) ? OUTCOME_TEXT[kind] : { tone: 'error', text: 'not delivered' }}