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(context-link): retain verified paths and coalesce rebuilds

review467f23f2dd7c
diff --git a/CLAUDE.md b/CLAUDE.md
index 368bce779..48e6d2048 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2767,6 +2767,11 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
retired — its embedded-JS parser now lives as tested TS in `core/context-link-render.ts`:
parsers for **all four** formats — claude JSONL / codex rollout / gemini event-sourced chat /
opencode export — plus `renderContextLink` over injected fetchers). `src/core/context-link.ts`
+ coalesces renderer updates before workspace-map construction with a non-resetting task.
+ Intermediate ACL publications retain previously resolved paths keyed by node, agent, session,
+ account, cwd, remote/local placement and hook path. Ingest prunes changed/removed identities,
+ so changing back during queued discovery cannot revive an invalidated path. Reinitialization
+ clears the cache, and only current-revision discovery may refill it. The service
holds the link docs in memory (per-node files under `<userData>/context-links/` remain as a
debug aid), carries per-entry `agentId`/`sessionId`/`accountId`, and answers the route;
**authorization** = the doc is selected by the REQUESTER's node id, so a token-holding caller
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 788de8c93..1d28afd8e 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -61,6 +61,9 @@ projects independently of canvas geometry updates; a debounce reset by every nod
starve publication indefinitely. Only merge projects owned by the same core, and use the rendered
canvas's project epoch during tab switches. Core must revoke removed links before asynchronous
transcript discovery or debug-file writes finish; an older write must never restore that access.
+Coalesce renderer updates before building the workspace map, without resetting the scheduled task.
+Intermediate publications retain resolved transcript paths only for unchanged identities; changing
+a session/account/location/hook path or removing the target invalidates that cache immediately.
## Three surfaces
diff --git a/src/core/context-link.handler.test.ts b/src/core/context-link.handler.test.ts
index 14dc87fb6..65f1cb86a 100644
--- a/src/core/context-link.handler.test.ts
+++ b/src/core/context-link.handler.test.ts
@@ -237,3 +237,72 @@ it('recovers the write queue after enrichment fails', async () => {
expect(await handleContextLinkRequest({ verb: 'list', nodeId: 'a', args: {} })).toContain('Recovered')
expect(JSON.parse(readFileSync(join(dir, 'context-links', 'a.json'), 'utf8')).links[0].note).toBe('safe fixture')
})
+
+it('keeps verified local and remote transcripts readable during edits and delayed discovery', async () => {
+ const { locateCodex } = await import('./handoff/locate')
+ const local = join(dir, 'retained.jsonl')
+ writeFileSync(local, JSON.stringify({ type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'ship it' }] } }))
+ const readRemoteFile = vi.fn(async () => CLAUDE_LINE)
+ start({ isRemoteNode: id => id === 'retained-remote', readRemoteFile })
+ setNodeTranscript('retained-remote', 'remote-session', '/home/u/.claude/projects/x/retained.jsonl')
+ vi.mocked(locateCodex).mockResolvedValueOnce(local)
+ const links = [
+ { id: 'retained-local', title: 'Local', agentId: 'codex', sessionId: 'local-session' },
+ { id: 'retained-remote', title: 'Remote', agentId: 'claude', sessionId: 'remote-session' },
+ { id: 'retained-note', title: 'Brief', note: 'old' }
+ ]
+ await setContextLinks({ reader: links })
+ let release!: (value: string) => void
+ let entered!: () => void
+ const started = new Promise<void>(resolve => { entered = resolve })
+ vi.mocked(locateCodex).mockImplementationOnce(async () => {
+ entered()
+ return new Promise<string>(resolve => { release = resolve })
+ })
+ const pending = setContextLinks({ reader: links.map(n => ({ ...n, title: `${n.title} edited`, ...(n.note ? { note: 'new' } : {}) })) })
+ await started
+ try {
+ expect(await handleContextLinkRequest({ verb: 'list', nodeId: 'reader', args: {} })).toContain('Local edited')
+ for (const node of ['retained-local', 'retained-remote']) {
+ expect(await handleContextLinkRequest({ verb: 'transcript', nodeId: 'reader', args: { node } })).toContain('ship it')
+ }
+ expect(await handleContextLinkRequest({ verb: 'transcript', nodeId: 'reader', args: { node: 'retained-note' } })).toContain('new')
+ expect(readRemoteFile).toHaveBeenCalledWith('retained-remote', '/home/u/.claude/projects/x/retained.jsonl', expect.any(Number))
+ } finally { release(local); await pending }
+})
+
+it.each(['sessionId', 'accountId', 'cwd', 'agentId', 'hook', 'remote', 'removed'])(
+ 'invalidates retained paths when %s changes, including change-back before discovery finishes', async field => {
+ const { locateCodex } = await import('./handoff/locate')
+ const local = join(dir, 'identity.jsonl')
+ writeFileSync(local, JSON.stringify({ type: 'response_item', payload: { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'ship it' }] } }))
+ let remote = false
+ start({ isRemoteNode: () => remote })
+ const link = { id: `identity-${field}`, title: 'Identity', agentId: 'codex', sessionId: 'original', accountId: 'original', cwd: '/original' }
+ vi.mocked(locateCodex).mockResolvedValueOnce(local)
+ await setContextLinks({ reader: [link] })
+ expect(await handleContextLinkRequest({ verb: 'transcript', nodeId: 'reader', args: {} })).toContain('ship it')
+ let release!: (value: undefined) => void
+ let entered!: () => void
+ const started = new Promise<void>(resolve => { entered = resolve })
+ vi.mocked(locateCodex).mockImplementationOnce(async () => {
+ entered()
+ return new Promise<undefined>(resolve => { release = resolve })
+ })
+ // Block the write queue so all assertions observe the intermediate publication.
+ const blocker = setContextLinks({ reader: [link], slow: [{ id: 'slow-identity', title: 'Slow', agentId: 'codex', sessionId: 'slow' }] })
+ await started
+ if (field === 'remote') remote = true
+ if (field === 'hook') setNodeTranscript(link.id, 'original', '/changed-hook.jsonl')
+ const changed: ContextLinkMap = field === 'removed' ? {} : { reader: [{ ...link, ...(['sessionId', 'accountId', 'cwd', 'agentId'].includes(field) ? { [field]: 'changed' } : {}) }] }
+ const pending = setContextLinks(changed)
+ try {
+ expect(await handleContextLinkRequest({ verb: 'transcript', nodeId: 'reader', args: {} })).not.toContain('ship it')
+ remote = false
+ const back = setContextLinks({ reader: [link] })
+ expect(await handleContextLinkRequest({ verb: 'transcript', nodeId: 'reader', args: {} })).not.toContain('ship it')
+ release(undefined)
+ await Promise.all([blocker, pending, back])
+ } finally { release(undefined); await blocker }
+ }
+)
diff --git a/src/core/context-link.ts b/src/core/context-link.ts
index b02d98f63..20564d1e7 100644
--- a/src/core/context-link.ts
+++ b/src/core/context-link.ts
@@ -19,7 +19,7 @@ import os from 'os'
import path from 'path'
import { platform } from './platform'
import { IPC } from '../shared/ipc'
-import type { ContextLinkMap } from '../shared/types'
+import type { ContextLinkInfo, ContextLinkMap } from '../shared/types'
import { type PtyManager } from './pty-manager'
import { directExecutableInvocation, findInLoginPath } from './exec-path'
import { TMUX_SOCKET } from './tmux-naming'
@@ -140,6 +140,13 @@ const LINK_LOCATORS = { claude: locateClaude, codex: locateCodex, gemini: locate
// are what authorizes a read (a node may only ever name a link inside ITS OWN document).
let linkDocs = new Map<string, LinkDoc>()
let linkRevision = 0
+// Only paths resolved for this exact identity may survive an intermediate publication.
+// Include the hook path so a replaced/invalidated hook cannot reuse an older resolution.
+let verifiedPaths = new Map<string, string>()
+function transcriptIdentity(n: ContextLinkInfo): string {
+ return JSON.stringify([n.id, n.agentId, n.sessionId, n.accountId, n.cwd,
+ !!deps.isRemoteNode?.(n.id), transcriptPathOf(n.id)])
+}
// Write one enriched link file per node id present in the map. Removed links should not
// linger, so we clear stale per-node files first. Async fs throughout — this runs on edge
@@ -151,9 +158,11 @@ async function writeLinkFiles(map: ContextLinkMap, revision: number): Promise<vo
// Resolve each linked node's transcript once (hook-fed for claude, locator-by-sessionId
// for codex/gemini), so buildLinkDoc stays pure and sync.
const resolved = new Map<string, string>()
+ const verified = new Map<string, string>()
for (const links of Object.values(map)) {
for (const n of links) {
if (n.note != null || resolved.has(n.id)) continue
+ const identity = transcriptIdentity(n)
resolved.set(
n.id,
await resolveLinkTranscript(n, {
@@ -162,6 +171,8 @@ async function writeLinkFiles(map: ContextLinkMap, revision: number): Promise<vo
isRemote: deps.isRemoteNode
})
)
+ if (identity === transcriptIdentity(n)) verified.set(identity, resolved.get(n.id)!)
+ else resolved.set(n.id, '')
}
}
if (revision !== linkRevision) return
@@ -175,6 +186,7 @@ async function writeLinkFiles(map: ContextLinkMap, revision: number): Promise<vo
docs.set(nodeId, doc)
}
// Publish all enriched documents together; never expose a partially rebuilt map.
+ verifiedPaths = verified
linkDocs = docs
try {
for (const f of await fs.promises.readdir(d)) {
@@ -297,8 +309,22 @@ export function setContextLinks(map: ContextLinkMap): Promise<void> {
const revision = ++linkRevision
// Authorization changes immediately, before transcript discovery or debug-file I/O. A slow
// locator must neither hide a new edge from list nor retain a removed read permission.
+ const retained = new Map<string, string>()
+ const paths = new Map<string, string>()
+ for (const links of Object.values(snapshot)) {
+ for (const n of links) {
+ if (n.note != null) continue
+ // Dependency lookup can fail; leave discovery to report the failure asynchronously.
+ try {
+ const identity = transcriptIdentity(n)
+ const prior = verifiedPaths.get(identity)
+ if (prior) { retained.set(identity, prior); paths.set(n.id, prior) }
+ } catch { /* no verified path */ }
+ }
+ }
+ verifiedPaths = retained
linkDocs = new Map(Object.entries(snapshot).map(([nodeId, links]) => [nodeId, buildLinkDoc(
- nodeId, links, { transcriptOf: () => '', tmuxBin: pty?.getTmuxBin() ?? null, tmuxSocket: TMUX_SOCKET }
+ nodeId, links, { transcriptOf: (id) => paths.get(id) ?? '', tmuxBin: pty?.getTmuxBin() ?? null, tmuxSocket: TMUX_SOCKET }
)]))
const write = () => writeLinkFiles(snapshot, revision)
writeChain = writeChain.then(write, write)
@@ -331,6 +357,7 @@ export function initContextLink(
deps = platformDeps
linkRevision++
linkDocs.clear()
+ verifiedPaths.clear()
hookServer.setContextLinkHandler(handleContextLinkRequest)
try {
const d = contextLinkDir()
diff --git a/src/renderer/canvas/useContextLinkSync.test.tsx b/src/renderer/canvas/useContextLinkSync.test.tsx
index 72f65f400..fd03cbf75 100644
--- a/src/renderer/canvas/useContextLinkSync.test.tsx
+++ b/src/renderer/canvas/useContextLinkSync.test.tsx
@@ -2,6 +2,7 @@
import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
+import * as linkMaps from '@shared/context-link-map'
import { useProjects } from '../state/projects'
import { useAgentStatus } from '../state/agentStatus'
import { useContextLinkSync, type LiveContextLinks } from './useContextLinkSync'
@@ -18,10 +19,12 @@ const project = (id: string, ids: string[], bridges = ids.length > 1 ? [edge(ids
} as Project)
let root: Root
function Harness(props: LiveContextLinks) { useContextLinkSync(props); return null }
-function render(props: LiveContextLinks) { act(() => root.render(<Harness {...props} />)) }
-function lastMap() { return setLinks.mock.calls.at(-1)?.[0] as unknown as Record<string, Array<Record<string, unknown>>> }
+function render(props: LiveContextLinks) { act(() => root.render(<Harness {...props} />)); flush() }
+function flush() { act(() => vi.runOnlyPendingTimers()) }
+function lastMap() { flush(); return setLinks.mock.calls.at(-1)?.[0] as unknown as Record<string, Array<Record<string, unknown>>> }
beforeEach(() => {
+ vi.useFakeTimers()
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true })
Object.assign(window, { nodeTerminal: { contextLink: { setLinks } } })
useProjects.setState({ projects: [project('p', ['a', 'b'])], activeProjectId: 'p' })
@@ -29,7 +32,7 @@ beforeEach(() => {
setLinks.mockClear()
root = createRoot(document.createElement('div'))
})
-afterEach(() => act(() => root.unmount()))
+afterEach(() => { act(() => root.unmount()); vi.useRealTimers(); vi.restoreAllMocks() })
it('publishes a newly drawn/auto-created link during continuous node renders, then removes it', () => {
const live = { projectId: 'p', nodes: [node('a'), node('b')], edges: [] as LiveContextLinks['edges'] }
@@ -85,3 +88,22 @@ it('refreshes linked notes and titles, and stops subscribing after unmount', ()
act(() => useProjects.setState({ projects: [] }))
expect(setLinks).toHaveBeenCalledTimes(count)
})
+
+it('coalesces workspace rebuilds before serialization and cancels pending work on unmount', () => {
+ const build = vi.spyOn(linkMaps, 'buildBackgroundLinkMaps')
+ const live = { projectId: 'p', nodes: [node('a'), node('b')], edges: [edge('a', 'b')] }
+ render(live)
+ build.mockClear()
+ for (let i = 0; i < 30; i++) {
+ act(() => root.render(<Harness {...live} nodes={live.nodes.map(n => ({ ...n }))} />))
+ act(() => useAgentStatus.setState({ byId: { b: { agentId: 'codex', sessionId: `s-${i}`, unread: false } } }))
+ }
+ expect(build).not.toHaveBeenCalled()
+ flush()
+ expect(build).toHaveBeenCalledTimes(1)
+ expect(lastMap().a[0].sessionId).toBe('s-29')
+ act(() => useProjects.setState({ projects: [] }))
+ act(() => root.unmount())
+ flush()
+ expect(build).toHaveBeenCalledTimes(1)
+})
diff --git a/src/renderer/canvas/useContextLinkSync.ts b/src/renderer/canvas/useContextLinkSync.ts
index 2ebc0a3f1..44bdd8d05 100644
--- a/src/renderer/canvas/useContextLinkSync.ts
+++ b/src/renderer/canvas/useContextLinkSync.ts
@@ -23,6 +23,7 @@ export function useContextLinkSync(live: LiveContextLinks): void {
useEffect(() => {
let last = ''
+ let pending: ReturnType<typeof setTimeout> | undefined
const update = () => {
const { projects, activeProjectId } = useProjects.getState()
const local = projects.filter((p) => sessionForProject(p.id).api === window.nodeTerminal)
@@ -61,11 +62,18 @@ export function useContextLinkSync(live: LiveContextLinks): void {
console.warn('[context-link] publish failed', error)
})
}
- publish.current = update
- const offProjects = useProjects.subscribe(update)
- const offStatus = useAgentStatus.subscribe(update)
- update()
+ // A fixed task boundary coalesces renders and hook bursts BEFORE rebuilding the workspace.
+ // Never reset the timer: continuous drag/status traffic must not starve publication.
+ const schedule = () => {
+ if (pending !== undefined) return
+ pending = setTimeout(() => { pending = undefined; update() }, 0)
+ }
+ publish.current = schedule
+ const offProjects = useProjects.subscribe(schedule)
+ const offStatus = useAgentStatus.subscribe(schedule)
+ schedule()
return () => {
+ clearTimeout(pending)
offProjects()
offStatus()
publish.current = () => {}