Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(server): make Context Link work in the Server Edition (#93)

dowlle222e35cf8471
diff --git a/docs/SERVER.md b/docs/SERVER.md
index 11236978f..e43f3caae 100644
--- a/docs/SERVER.md
+++ b/docs/SERVER.md
@@ -416,6 +416,38 @@ Because the hook POST carries a `transcript_path`, a forged POST is defended by
that path to the system-default `~/.claude/projects` or a managed account dir
(`isSafeLocalTranscriptPath`) before any tail reads it.
+### Context Link
+
+Context Link works in the Server Edition. The feature itself lives entirely in core
+(`src/core/context-link.ts`) and writes everything under `dataDir`; what it needs from a
+shell is the **link map** — who is linked to whom.
+
+The desktop gets that from its renderer, because React Flow holds the live canvas. That
+does not fit here: agents and their tmux sessions keep running with the browser closed,
+and a headless deployment may never have one attached. So the server derives the same map
+from the **persisted** `bridges[]` of every canvas (`workspaceStore.persistedCanvases()` →
+`buildBackgroundLinkMaps`, in `src/server/context-link.ts`). A workspace save re-derives
+immediately; a 15 s sweep also catches transcript paths, which arrive from the hooks
+rather than from any canvas change, and skips the write when nothing moved.
+
+Consequences worth knowing:
+
+- **Boot reads the workspace once** (`load({ sideline: false })`) so links are live before
+ the first browser connects. Read-only on purpose — sidelining a conflicted
+ `project.json` stays a renderer/probe decision.
+- **Boot also writes into agent configuration directories** when managed hook installation
+ is on: the `get-linked-context` Claude skill, plus marker-delimited instruction blocks in
+ `~/.codex/AGENTS.md`, `~/.gemini/GEMINI.md` and opencode's `AGENTS.md`. The blocks are
+ idempotent and preserve surrounding content. Set **`installHooks: false`** to skip every
+ one of those writes — the Context Link read handler still works, agents simply have to be
+ told about the shim some other way.
+- **Local-only, deliberately.** No remote deps are injected (`initContextLink(pty, {})`):
+ the server runs ON the host whose transcripts and tmux it reads, and SSH projects are a
+ desktop-only concept.
+- `contextLink.info()` is still unsupported in the browser bridge, so the canvas note that
+ announces a new link cannot quote the shim path. The boot-installed instructions cover
+ discovery independently.
+
**Deliberate scope skips (Phase 3b):**
- The SDK **chat node** is still **deferred** — it is not wired into the server bridge.
diff --git a/src/core/context-link.ts b/src/core/context-link.ts
index 1b91793c4..1b51240c0 100644
--- a/src/core/context-link.ts
+++ b/src/core/context-link.ts
@@ -259,7 +259,28 @@ export async function handleContextLinkRequest(req: {
}
}
-export function initContextLink(ptyManager: PtyManager, platformDeps: ContextLinkDeps = {}): void {
+// Serialize writes: writeLinkFiles is a multi-step async clear-then-write; two overlapping
+// calls could interleave (B's clear runs before A's writes land) and leave a just-removed
+// link file behind — which is a read-authorization leak, not just a perf nit.
+let writeChain: Promise<void> = Promise.resolve()
+
+/**
+ * Replace the WHOLE link map (every project) and rewrite the per-node link files.
+ *
+ * The desktop reaches this over IPC, from the renderer that owns the canvas. The Server Edition
+ * has no such renderer — it derives the map from persisted project files and calls this directly
+ * (src/server/context-link.ts), which is why the map setter is a function and not only a handler.
+ */
+export function setContextLinks(map: ContextLinkMap): Promise<void> {
+ writeChain = writeChain.then(() => writeLinkFiles(map && typeof map === 'object' ? map : {}))
+ return writeChain
+}
+
+export function initContextLink(
+ ptyManager: PtyManager,
+ platformDeps: ContextLinkDeps = {},
+ options: { installAgentIntegrations?: boolean } = {}
+): void {
pty = ptyManager
deps = platformDeps
linkDocs.clear()
@@ -271,19 +292,14 @@ export function initContextLink(ptyManager: PtyManager, platformDeps: ContextLin
if (f.endsWith('.json')) fs.rmSync(path.join(d, f), { force: true })
}
writeCliFiles()
- installSkill()
- installAgentInstructions()
+ if (options.installAgentIntegrations !== false) {
+ installSkill()
+ installAgentInstructions()
+ }
} catch (e) {
console.error('[context-link] setup failed', e)
return
}
- // Serialize writes: writeLinkFiles is a multi-step async clear-then-write; two overlapping
- // calls could interleave (B's clear runs before A's writes land) and leave a just-removed
- // link file behind — which is a read-authorization leak, not just a perf nit.
- let writeChain: Promise<void> = Promise.resolve()
- platform().handle(IPC.contextLinkSetLinks, (map: ContextLinkMap) => {
- writeChain = writeChain.then(() => writeLinkFiles(map && typeof map === 'object' ? map : {}))
- return writeChain
- })
+ platform().handle(IPC.contextLinkSetLinks, (map: ContextLinkMap) => setContextLinks(map))
platform().handle(IPC.contextLinkInfo, () => ({ shimPath: cliShimPath() }))
}
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 67ee93079..a4df87a71 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -5,10 +5,10 @@ import { IPC } from '../shared/ipc'
import { platform } from './platform'
import {
DEFAULT_PROJECT_ID, EMPTY_WORKSPACE,
- type CanvasNodeState, type Project, type Workspace, type WorkspaceV1
+ type BridgeLink, type CanvasNodeState, type Project, type Workspace, type WorkspaceV1
} from '../shared/types'
import {
- PROJECT_DIR, PROJECT_FILE, fileToProject, projectToFile, sameProjectContent,
+ PROJECT_DIR, PROJECT_FILE, fileToProject, projectToFile, resolveNodes, sameProjectContent,
serializeProjectFile, splitWorkspace, validKanban,
type IndexEntryV3, type ProjectFileV1, type WorkspaceIndexV3
} from './workspace-files'
@@ -470,6 +470,39 @@ export class WorkspaceStore {
return undefined
}
+ /**
+ * Every persisted canvas as {id, nodes, bridges} — the raw material the Server Edition derives
+ * its context-link map from (src/server/context-link.ts). Same three-entry-kind scan as
+ * `getNode`, but whole projects rather than one node, because a link edge only means anything
+ * alongside the nodes it joins.
+ *
+ * Sync + in-memory: it reads the loaded index and the last content written to each local ref's
+ * project.json, so a project whose file has never been read this run is simply absent (it
+ * appears after the next load/save, which is also what re-derives the map).
+ */
+ persistedCanvases(): Array<{ id: string; nodes: CanvasNodeState[]; bridges?: BridgeLink[] }> {
+ const out: Array<{ id: string; nodes: CanvasNodeState[]; bridges?: BridgeLink[] }> = []
+ for (const e of this.index?.entries ?? []) {
+ if (e.project) {
+ out.push({ id: e.project.id, nodes: e.project.nodes, bridges: e.project.bridges })
+ } else if (e.cache) {
+ out.push({ id: e.cache.id, nodes: e.cache.nodes, bridges: e.cache.bridges })
+ } else if (e.cwd) {
+ const raw = this.lastWritten.get(projectFilePath(e.cwd))
+ if (!raw) continue
+ try {
+ const f = JSON.parse(raw) as ProjectFileV1
+ // Node cwds are stored portable ("./sub"); resolve them the way `fileToProject` does, so
+ // a caller sees the same absolute paths the desktop's renderer would have handed it.
+ out.push({ id: f.id, nodes: resolveNodes(f.nodes, e.cwd), bridges: f.bridges })
+ } catch {
+ // Corrupt cached content: skip this entry, keep scanning the others.
+ }
+ }
+ }
+ return out
+ }
+
getNodeTitle(nodeId: string): string | undefined {
for (const e of this.index?.entries ?? []) {
let nodes: CanvasNodeState[] | undefined
diff --git a/src/renderer/lib/noteLink.ts b/src/renderer/lib/noteLink.ts
index f46b89565..32ed0cecc 100644
Binary files a/src/renderer/lib/noteLink.ts and b/src/renderer/lib/noteLink.ts differ
diff --git a/src/server/context-link.test.ts b/src/server/context-link.test.ts
new file mode 100644
index 000000000..c83c4e4bc
--- /dev/null
+++ b/src/server/context-link.test.ts
@@ -0,0 +1,254 @@
+// The Server Edition's half of context-link: deriving the link map from persisted canvases, and
+// registering the read handler core answers with. The reads themselves (authorization, transcript
+// parsing, the local/remote split) are core's and are covered by src/core/context-link.handler.test.ts —
+// what is tested here is the wiring that was missing server-side.
+import { describe, it, expect, beforeEach, afterEach, afterAll, vi } from 'vitest'
+import { existsSync, mkdtempSync, promises as fsPromises, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { deriveLinkMap, initServerContextLink } from './context-link'
+import { setNodeTranscript } from '../core/context-link-core'
+import { hookServer } from '../core/agents/hook-server'
+import { initPlatform, resetPlatformForTests } from '../core/platform'
+import { fakePlatform } from '../core/platform-fake'
+import type { CanvasNodeState } from '../shared/types'
+import type { PtyManager } from '../core/pty-manager'
+
+const dir = mkdtempSync(join(tmpdir(), 'srv-ctxlink-'))
+// initContextLink installs the skill + instruction blocks under the user's HOME. Point HOME at a
+// scratch dir for the duration so a test run never edits the real ~/.claude / ~/.codex / ~/.gemini.
+const realHome = process.env.HOME
+let home = ''
+
+/** Enough PtyManager for context-link: the tmux binary it stamps into each link document, and
+ * the terminal capture the `terminal` verb goes through. */
+function fakePty(): PtyManager {
+ return {
+ getTmuxBin: () => '/usr/bin/tmux',
+ captureSession: async (key: string) => `pane of ${key}`
+ } as unknown as PtyManager
+}
+
+/** A serialized agent node, the shape `.nodeterm/project.json` stores in `nodes[]`. */
+function node(id: string, over: Partial<CanvasNodeState> = {}): CanvasNodeState {
+ return {
+ id,
+ kind: 'terminal',
+ position: { x: 0, y: 0 },
+ size: { width: 400, height: 300 },
+ title: id,
+ color: '#fff',
+ group: null,
+ ...over
+ } as CanvasNodeState
+}
+
+const bridge = (source: string, target: string) => ({ id: `bridge-${source}-${target}`, source, target })
+
+beforeEach(() => {
+ home = mkdtempSync(join(tmpdir(), 'srv-ctxlink-home-'))
+ process.env.HOME = home
+ resetPlatformForTests()
+ initPlatform(fakePlatform({ userDataDir: dir }))
+})
+
+afterEach(() => {
+ if (realHome === undefined) delete process.env.HOME
+ else process.env.HOME = realHome
+ rmSync(home, { recursive: true, force: true })
+})
+
+afterAll(() => rmSync(dir, { recursive: true, force: true }))
+
+describe('deriveLinkMap', () => {
+ it('maps a bridge between two agent nodes in BOTH directions', () => {
+ const map = deriveLinkMap({
+ canvases: () => [
+ {
+ id: 'p1',
+ nodes: [node('term-a', { title: 'Alpha' }), node('term-b', { title: 'Beta' })],
+ bridges: [bridge('term-a', 'term-b')]
+ }
+ ]
+ })
+ expect(map['term-a']).toEqual([{ id: 'term-b', title: 'Beta', cwd: '' }])
+ expect(map['term-b']).toEqual([{ id: 'term-a', title: 'Alpha', cwd: '' }])
+ })
+
+ it('covers EVERY canvas — headless, no project is the active one', () => {
+ const map = deriveLinkMap({
+ canvases: () => [
+ { id: 'p1', nodes: [node('a'), node('b')], bridges: [bridge('a', 'b')] },
+ { id: 'p2', nodes: [node('c'), node('d')], bridges: [bridge('c', 'd')] }
+ ]
+ })
+ // The desktop skips the active project (its renderer supplies that one live). There is no
+ // renderer here, so skipping any project would silently sever a running agent's links.
+ expect(Object.keys(map).sort()).toEqual(['a', 'b', 'c', 'd'])
+ })
+
+ it('drops bridges whose endpoints are no longer on the canvas', () => {
+ const map = deriveLinkMap({
+ canvases: () => [
+ { id: 'p1', nodes: [node('a')], bridges: [bridge('a', 'deleted')] }
+ ]
+ })
+ expect(map).toEqual({})
+ })
+
+ it('ignores a canvas with no bridges at all', () => {
+ expect(deriveLinkMap({ canvases: () => [{ id: 'p1', nodes: [node('a'), node('b')] }] })).toEqual({})
+ })
+
+ it('links a sticky note one way only — a note cannot read', () => {
+ const map = deriveLinkMap({
+ canvases: () => [
+ {
+ id: 'p1',
+ nodes: [node('sticky-1', { kind: 'sticky', title: 'Spec', text: 'ship it' }), node('term-a')],
+ bridges: [bridge('sticky-1', 'term-a')]
+ }
+ ]
+ })
+ expect(map['term-a']).toEqual([{ id: 'sticky-1', title: 'Spec', note: 'ship it' }])
+ expect(map['sticky-1']).toBeUndefined()
+ })
+
+ it('takes agent + session from the hooks when the serialized node predates the launch', () => {
+ // A plain terminal the user started an agent CLI in by hand: project.json carries no agentId,
+ // but the status mirror learned both from the hook events.
+ const map = deriveLinkMap({
+ canvases: () => [{ id: 'p1', nodes: [node('a'), node('b')], bridges: [bridge('a', 'b')] }],
+ agentSessions: () => [{ nodeId: 'b', agentId: 'codex', sessionId: 'sess-b' }]
+ })
+ expect(map['a']).toEqual([{ id: 'b', title: 'b', cwd: '', agentId: 'codex', sessionId: 'sess-b' }])
+ })
+})
+
+describe('initServerContextLink', () => {
+ /** Start the wiring and hand back the handler it registered on the hook server — the exact
+ * function the /context-link/ route calls. */
+ function start(deps: Parameters<typeof initServerContextLink>[0]) {
+ const spy = vi.spyOn(hookServer, 'setContextLinkHandler')
+ const link = initServerContextLink(deps)
+ const handler = spy.mock.calls.at(-1)?.[0]
+ spy.mockRestore()
+ return { link, handler: handler!, registered: !!handler }
+ }
+
+ it('registers the read handler the route would otherwise refuse for', async () => {
+ const { link, handler, registered } = start({
+ ptyManager: fakePty(),
+ canvases: () => [
+ {
+ id: 'p1',
+ nodes: [node('term-a', { title: 'Alpha' }), node('term-b', { title: 'Beta' })],
+ bridges: [bridge('term-a', 'term-b')]
+ }
+ ]
+ })
+ // Without this registration the hook server answers every read with
+ // "Context link is unavailable in this session." — the whole desktop-only symptom.
+ expect(registered).toBe(true)
+ await link.refresh()
+ const out = await handler({ verb: 'list', nodeId: 'term-a', args: {} })
+ expect(out).toContain('Beta')
+ expect(out).toContain('term-b')
+ await link.stop()
+ })
+
+ it('answers a node with no links, rather than pretending the feature is missing', async () => {
+ const { link, handler } = start({ ptyManager: fakePty(), canvases: () => [] })
+ await link.refresh()
+ const out = await handler({ verb: 'list', nodeId: 'term-a', args: {} })
+ expect(out).toContain('No linked nodes')
+ await link.stop()
+ })
+
+ it('respects installHooks false while keeping the read handler available', async () => {
+ const { link, registered } = start({
+ ptyManager: fakePty(),
+ canvases: () => [],
+ installAgentIntegrations: false
+ })
+ expect(registered).toBe(true)
+ expect(existsSync(join(home, '.claude', 'skills', 'get-linked-context', 'SKILL.md'))).toBe(false)
+ expect(existsSync(join(home, '.codex', 'AGENTS.md'))).toBe(false)
+ await link.stop()
+ })
+
+ it('picks up a bridge drawn after boot', async () => {
+ let bridges = [] as ReturnType<typeof bridge>[]
+ const { link, handler } = start({
+ ptyManager: fakePty(),
+ canvases: () => [{ id: 'p1', nodes: [node('term-a'), node('term-b', { title: 'Beta' })], bridges }]
+ })
+ await link.refresh()
+ expect(await handler({ verb: 'list', nodeId: 'term-a', args: {} })).toContain('No linked nodes')
+ // What a browser drawing the edge produces: a workspace save, and the onPersist refresh.
+ bridges = [bridge('term-a', 'term-b')]
+ await link.refresh()
+ expect(await handler({ verb: 'list', nodeId: 'term-a', args: {} })).toContain('Beta')
+ await link.stop()
+ })
+
+ it('rewrites when a linked node\'s transcript arrives, though the canvas never changed', async () => {
+ const transcript = join(dir, 'late.jsonl')
+ writeFileSync(transcript, JSON.stringify({ type: 'user', message: { content: 'ship it' } }))
+ const canvases = () => [
+ {
+ id: 'p1',
+ nodes: [node('term-a'), node('term-b', { title: 'Beta', agentId: 'claude' as const })],
+ bridges: [bridge('term-a', 'term-b')]
+ }
+ ]
+ const { link, handler } = start({ ptyManager: fakePty(), canvases })
+ await link.refresh()
+ expect(await handler({ verb: 'summary', nodeId: 'term-a', args: {} })).toContain(
+ 'no conversation transcript yet'
+ )
+ // The transcript path is hook-fed, so it lands with no canvas change behind it — the sweep's
+ // change signature has to include it or the link document stays permanently empty.
+ setNodeTranscript('term-b', 'sess-b', transcript)
+ await link.refresh()
+ expect(await handler({ verb: 'summary', nodeId: 'term-a', args: {} })).toContain('user: ship it')
+ await link.stop()
+ })
+
+ it('settles owed writes on stop, and writes nothing afterwards', async () => {
+ const { link } = start({
+ ptyManager: fakePty(),
+ canvases: () => [
+ { id: 'p1', nodes: [node('term-a'), node('term-b')], bridges: [bridge('term-a', 'term-b')] }
+ ]
+ })
+ // Neither the sweep nor onPersist awaits a refresh, so at close there is normally one in
+ // flight. A stop that does not drain it lets link files land in a dataDir the caller is
+ // already tearing down (a server test caught exactly that, as ENOTEMPTY).
+ const owed = link.refresh()
+ await link.stop()
+ await expect(owed).resolves.toBeUndefined()
+ const writes = vi.spyOn(fsPromises, 'writeFile')
+ await link.refresh()
+ expect(writes).not.toHaveBeenCalled()
+ writes.mockRestore()
+ })
+
+ it('skips the rewrite when nothing moved', async () => {
+ const { link } = start({
+ ptyManager: fakePty(),
+ canvases: () => [
+ { id: 'p1', nodes: [node('term-a'), node('term-b')], bridges: [bridge('term-a', 'term-b')] }
+ ]
+ })
+ await link.refresh()
+ // The sweep runs every 15s for the life of the server: an unconditional rewrite would be a
+ // clear-and-rewrite of every link file, forever, on a canvas nobody is touching.
+ const writes = vi.spyOn(fsPromises, 'writeFile')
+ await link.refresh()
+ await link.refresh()
+ expect(writes).not.toHaveBeenCalled()
+ writes.mockRestore()
+ await link.stop()
+ })
+})
diff --git a/src/server/context-link.ts b/src/server/context-link.ts
new file mode 100644
index 000000000..2dad8e4e8
--- /dev/null
+++ b/src/server/context-link.ts
@@ -0,0 +1,129 @@
+// Context Link for the Server Edition — the piece the desktop gets from its renderer.
+//
+// The feature itself is entirely in core (src/core/context-link.ts): it builds the per-node link
+// documents, installs the shim + skill + instruction blocks, and answers reads on the hook
+// server's /context-link/ route. All of it is shell-agnostic, and every path it writes is derived
+// from `platform().userDataDir` — which here IS the server's dataDir. What was missing server-side
+// is the one thing that came from the desktop renderer: somebody to say WHICH nodes are linked.
+// Without that push the map stays empty, no contextLinkHandler is ever registered, and the route
+// answers "Context link is unavailable in this session."
+//
+// On the desktop the canvas is the authority: React Flow holds the live edges. Headless there is
+// no focused canvas — there may be no browser attached at all while the agents keep working — so
+// the authority is the persisted project file instead. `bridges[]` in `.nodeterm/project.json` is
+// the same edge set the renderer would have pushed, so we derive the map from every persisted
+// canvas and get a link map that is correct with zero tabs open.
+import type { ContextLinkMap } from '../shared/types'
+import { buildBackgroundLinkMaps } from '../shared/context-link-map'
+import { initContextLink, setContextLinks } from '../core/context-link'
+import { transcriptPathOf } from '../core/context-link-core'
+import { sessionNameSweepEntries } from '../core/agent-status-mirror'
+import type { PtyManager } from '../core/pty-manager'
+import type { WorkspaceStore } from '../core/workspace-store'
+
+/**
+ * How often to re-derive the map from live agent state. A save re-derives immediately (onPersist),
+ * but a link's transcript is not knowable from the canvas at all: it arrives later, from the hooks,
+ * when the agent actually starts talking. The desktop rewrites on a renderer-side signature of
+ * every linked node's agent/session; headless we sweep instead, and skip the write when nothing
+ * moved — so the steady-state cost is one in-memory scan.
+ */
+export const CONTEXT_LINK_SWEEP_MS = 15_000
+
+/** The narrow slice of each collaborator this module needs — injectable so tests need no real
+ * workspace on disk, no tmux, and no mirror. */
+export interface ServerContextLinkDeps {
+ ptyManager: PtyManager
+ /** Every persisted canvas (`workspaceStore.persistedCanvases`). */
+ canvases: () => Array<Parameters<typeof buildBackgroundLinkMaps>[0][number]>
+ /** nodeId → its live agent/session, as the hooks last reported it. */
+ agentSessions?: () => Array<{ nodeId: string; agentId?: string; sessionId?: string }>
+ /** nodeId → hook-fed transcript path; part of the change signature, not of the map. */
+ transcriptOf?: (nodeId: string) => string
+ sweepMs?: number
+ /** Respect the server's installHooks gate for writes into agent configuration directories. */
+ installAgentIntegrations?: boolean
+}
+
+/**
+ * Derive the whole link map from persisted canvases plus what the hooks know about who is running
+ * where.
+ *
+ * `activeProjectId: null` is not a placeholder — headless, no project IS active. Every canvas is
+ * exactly the "background" case buildBackgroundLinkMaps was written for: serialized nodes, a
+ * `bridges[]` array, and agent identity that has to come from the status mirror rather than from a
+ * mounted node.
+ */
+export function deriveLinkMap(deps: {
+ canvases: ServerContextLinkDeps['canvases']
+ agentSessions?: ServerContextLinkDeps['agentSessions']
+}): ContextLinkMap {
+ const live = new Map((deps.agentSessions?.() ?? []).map((e) => [e.nodeId, e]))
+ return buildBackgroundLinkMaps(
+ deps.canvases(),
+ null,
+ (id) => live.get(id)?.sessionId,
+ (id) => live.get(id)?.agentId
+ )
+}
+
+/**
+ * Boot context-link server-side: register the read handler + write the shim/skill/instructions
+ * (core), then keep the link map in step with the canvases on disk.
+ *
+ * Returns `refresh` (also the onPersist hook the caller wires to the workspace store) and a
+ * `stop` that settles the sweep — awaitable, because a refresh is a write into `dataDir` and a
+ * close that does not wait for it lets link files reappear behind a shutting-down server.
+ */
+export function initServerContextLink(deps: ServerContextLinkDeps): {
+ refresh: () => Promise<void>
+ stop: () => Promise<void>
+} {
+ const agentSessions = deps.agentSessions ?? sessionNameSweepEntries
+ const transcriptOf = deps.transcriptOf ?? transcriptPathOf
+
+ // No remote deps: the Server Edition runs ON the host whose transcripts and tmux it reads, so
+ // the local-only behavior is the complete answer (SSH projects are a desktop-only concept here).
+ initContextLink(deps.ptyManager, {}, {
+ installAgentIntegrations: deps.installAgentIntegrations
+ })
+
+ // Skip a rewrite when nothing a link document depends on has changed. The map alone is not the
+ // whole input — a link's transcript path is resolved at write time from the hook-fed table, and
+ // that is precisely the thing that changes without the canvas changing.
+ let lastSig = ''
+ const derive = async (): Promise<void> => {
+ if (stopped) return
+ const map = deriveLinkMap({ canvases: deps.canvases, agentSessions })
+ const transcripts = Object.values(map)
+ .flat()
+ .map((n) => `${n.id}=${transcriptOf(n.id)}`)
+ .sort()
+ const sig = `${JSON.stringify(map)}|${transcripts.join(',')}`
+ if (sig === lastSig) return
+ lastSig = sig
+ await setContextLinks(map)
+ }
+
+ // Serialized, and tracked: the sweep and onPersist both fire this without awaiting it, so `chain`
+ // is the only handle a caller has on writes that are still owed when the server closes.
+ let stopped = false
+ let chain: Promise<void> = Promise.resolve()
+ const refresh = (): Promise<void> => {
+ chain = chain.then(derive, derive)
+ return chain
+ }
+
+ const timer = setInterval(() => void refresh(), deps.sweepMs ?? CONTEXT_LINK_SWEEP_MS)
+ // Never hold the process open for a sweep — the server's lifetime is the listener's, not ours.
+ timer.unref?.()
+
+ return {
+ refresh,
+ stop: async () => {
+ stopped = true
+ clearInterval(timer)
+ await chain.catch(() => {})
+ }
+ }
+}
diff --git a/src/server/index.ts b/src/server/index.ts
index 51d23543a..6952b9684 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -56,6 +56,7 @@ import { claudeConfigDirFor } from '../core/claude-config-dir'
import { presenceHub } from '../core/presence/hub'
import { initCanvasSync } from '../core/canvas-sync'
import { wireAgentStatus } from './agent-status'
+import { initServerContextLink } from './context-link'
import { registerTranscriptIpc } from '../core/transcript-ipc'
import { IPC } from '@shared/ipc'
import { WhisperModelStore } from '../core/speech/whisper-models'
@@ -406,6 +407,27 @@ export async function startServer(
}
await hookServer.start()
+ // Context Link: core owns the whole feature (read handler, shim, skill, instruction blocks) and
+ // writes everything under `dataDir`; what it needs from a shell is the link map. The desktop's
+ // renderer pushes it from the live canvas — headless there may be no browser attached at all, so
+ // we derive the same map from the persisted `bridges[]` of every canvas instead. See
+ // src/server/context-link.ts.
+ const contextLink = initServerContextLink({
+ ptyManager,
+ canvases: () => workspaceStore.persistedCanvases(),
+ installAgentIntegrations: config.installHooks !== false
+ })
+ // Every load()/save() is a canvas change as far as links are concerned: a browser drawing a
+ // bridge edge reaches us as the workspace save it triggers.
+ workspaceStore.onPersist = () => void contextLink.refresh()
+ // Nothing has read the workspace index yet — the desktop gets its first load from the renderer,
+ // and this shell may never have one. Read it once so links are live before any browser connects.
+ // Read-only: boot must not sideline a conflict-marked project.json (that stays a renderer/probe
+ // decision). The onPersist above turns this load into the initial refresh.
+ await workspaceStore.load({ sideline: false }).catch((e) => {
+ console.warn('[nodeterm-server] context-link initial workspace load failed', e)
+ })
+
// Session budget (docs/SERVER.md): reap long-idle DETACHED nt- tmux sessions under memory
// pressure (10%-of-RAM watermark) or past a count cap, on BOTH the local socket and the
// SSH-remote socket (`nodeterm-rmt`) — a host serving SSH projects accumulates sessions there,
@@ -426,6 +448,7 @@ export async function startServer(
async close() {
// Detach PTY clients — tmux sessions keep running (Phase 1 contract).
sessionReaper.stop()
+ await contextLink.stop()
await ptyManager.killAll()
hookServer.stop()
}
@@ -468,6 +491,7 @@ export async function startServer(
async close() {
// Detach PTY clients — tmux sessions keep running (Phase 1 contract; never kill the server).
sessionReaper.stop()
+ await contextLink.stop()
await ptyManager.killAll()
// Close the loopback hook-server listener (it would otherwise die with the process anyway).
hookServer.stop()
diff --git a/src/shared/context-link-map.ts b/src/shared/context-link-map.ts
new file mode 100644
index 000000000..b0d88b696
--- /dev/null
+++ b/src/shared/context-link-map.ts
@@ -0,0 +1,101 @@
+// How a canvas becomes a context-link map: node id → the nodes it may READ.
+//
+// Lives in shared because both shells need it and neither owns it. The desktop renderer builds
+// the ACTIVE project's map from live React Flow edges and the rest from the projects store
+// (Canvas.tsx). The Server Edition has no renderer holding a canvas — it derives the whole map
+// from persisted project files instead (src/server/context-link.ts). Same rules either way, so
+// they belong in one place rather than two that drift.
+import type { BridgeLink, CanvasNodeState, ContextLinkInfo, ContextLinkMap } from './types'
+
+export interface LinkNodeInfo {
+ id: string
+ title: string
+ cwd?: string
+ note?: string
+ sticky: boolean
+ agentId?: string
+ sessionId?: string
+ accountId?: string
+}
+
+/**
+ * Build the node → linked-nodes map pushed to main (which writes the per-node link files).
+ * Context edges map both directions; note edges map one direction only — the terminal side
+ * gets a { id, title, note } entry, the sticky side gets nothing (a sticky cannot read).
+ */
+export function buildLinkMap(
+ edges: Array<{ source: string; target: string }>,
+ infoOf: (id: string) => LinkNodeInfo
+): ContextLinkMap {
+ const map: ContextLinkMap = {}
+ const entryOf = (n: LinkNodeInfo): ContextLinkInfo => {
+ if (n.sticky) return { id: n.id, title: n.title, note: n.note ?? '' }
+ const e: ContextLinkInfo = { id: n.id, title: n.title, cwd: n.cwd ?? '' }
+ if (n.agentId) e.agentId = n.agentId
+ if (n.sessionId) e.sessionId = n.sessionId
+ if (n.accountId) e.accountId = n.accountId
+ return e
+ }
+ for (const e of edges) {
+ const s = infoOf(e.source)
+ const t = infoOf(e.target)
+ if (s.sticky && t.sticky) continue
+ if (s.sticky) {
+ ;(map[t.id] ??= []).push(entryOf(s))
+ } else if (t.sticky) {
+ ;(map[s.id] ??= []).push(entryOf(t))
+ } else {
+ ;(map[s.id] ??= []).push(entryOf(t))
+ ;(map[t.id] ??= []).push(entryOf(s))
+ }
+ }
+ return map
+}
+
+/**
+ * Link maps built from serialized nodes + bridges, for every project EXCEPT `activeProjectId`.
+ *
+ * On the desktop the active project's map is built live from React Flow and this covers the rest,
+ * because writeLinkFiles clears ALL link files before writing the pushed map — pushing only the
+ * active project's map deleted the link files of background projects whose tmux sessions (and
+ * agents mid-task) were still running. Node ids are globally unique across projects, so the maps
+ * merge without collisions.
+ *
+ * A shell with no focused canvas (the Server Edition) passes `activeProjectId: null` and gets
+ * every project, which is the whole map.
+ *
+ * `agentIdOf` is the hook-status fallback for plain terminals where the user launched an
+ * agent CLI by hand: the serialized node carries no agentId, but the status store (fed by
+ * the managed hooks, node ids are per-core so background projects share it) knows who's
+ * running inside.
+ */
+export function buildBackgroundLinkMaps(
+ projects: Array<{ id: string; nodes: CanvasNodeState[]; bridges?: BridgeLink[] }>,
+ activeProjectId: string | null,
+ sessionIdOf: (nodeId: string) => string | undefined,
+ agentIdOf?: (nodeId: string) => string | undefined
+): ContextLinkMap {
+ const map: ContextLinkMap = {}
+ for (const p of projects) {
+ if (p.id === activeProjectId || !p.bridges?.length) continue
+ const byId = new Map(p.nodes.map((n) => [n.id, n]))
+ const edges = p.bridges.filter((e) => byId.has(e.source) && byId.has(e.target))
+ const infoOf = (id: string): LinkNodeInfo => {
+ const n = byId.get(id)!
+ const sticky = n.kind === 'sticky'
+ const agentId = sticky ? undefined : (n.agentId ?? agentIdOf?.(id))
+ return {
+ id,
+ title: n.title || id,
+ cwd: n.cwd ?? '',
+ note: sticky ? (n.text ?? '') : undefined,
+ sticky,
+ agentId,
+ sessionId: agentId ? sessionIdOf(id) : undefined,
+ accountId: sticky ? undefined : n.accountId
+ }
+ }
+ Object.assign(map, buildLinkMap(edges, infoOf))
+ }
+ return map
+}
diff --git a/test/server/hook-install-guard.test.ts b/test/server/hook-install-guard.test.ts
index d55547bec..a36e3f486 100644
--- a/test/server/hook-install-guard.test.ts
+++ b/test/server/hook-install-guard.test.ts
@@ -17,17 +17,24 @@ import { installManagedAgentHooks } from '../../src/core/agents/hooks'
describe('startServer: managed hook install is opt-out-able', () => {
let dataDir: string
+ let testHome: string
let close: (() => Promise<void>) | undefined
+ const realHome = process.env.HOME
beforeEach(() => {
dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-e2e-hookguard-'))
+ testHome = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-e2e-hookguard-home-'))
+ process.env.HOME = testHome
vi.mocked(installManagedAgentHooks).mockClear()
})
afterEach(async () => {
await close?.()
close = undefined
+ if (realHome === undefined) delete process.env.HOME
+ else process.env.HOME = realHome
fs.rmSync(dataDir, { recursive: true, force: true })
+ fs.rmSync(testHome, { recursive: true, force: true })
})
const boot = (installHooks?: boolean) =>
@@ -45,11 +52,15 @@ describe('startServer: managed hook install is opt-out-able', () => {
const srv = await boot(false)
close = srv.close
expect(installManagedAgentHooks).not.toHaveBeenCalled()
+ expect(fs.existsSync(path.join(testHome, '.claude', 'skills', 'get-linked-context', 'SKILL.md'))).toBe(false)
+ expect(fs.existsSync(path.join(testHome, '.codex', 'AGENTS.md'))).toBe(false)
}, 30_000)
it('installs the hooks by default (real deployments need them)', async () => {
const srv = await boot(undefined)
close = srv.close
expect(installManagedAgentHooks).toHaveBeenCalledOnce()
+ expect(fs.existsSync(path.join(testHome, '.claude', 'skills', 'get-linked-context', 'SKILL.md'))).toBe(true)
+ expect(fs.existsSync(path.join(testHome, '.codex', 'AGENTS.md'))).toBe(true)
}, 30_000)
})