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: one-way context links (#852)

Erik Zwepef0c4afaf480
diff --git a/CLAUDE.md b/CLAUDE.md
index 7194d4c7a..f5815a2d5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4893,6 +4893,21 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`~/.gemini/GEMINI.md`. On connect an idle-gated one-line note is injected into each endpoint
(claude → skill pointer; codex/gemini → inline CLI command via `contextLink.info()`).
(Replaced the earlier MCP-based bridge.)
+ **One-way links (issue #852):** a context bridge may carry `reader` (`BridgeLink.reader`, the ONE
+ endpoint allowed to read the other); absent = both read, which is every pre-#852 link, so old
+ `project.json` files load unchanged. The rule is `linkReadPairs` (`shared/canvas-link.ts`), and
+ `buildLinkMap` is where it BITES: the non-reading side gets no map entry, so main serves it no
+ document and the resolver refuses it — enforcement is at the read, not in the discovery note. A
+ `reader` naming neither endpoint authorizes nobody (fail closed). Set it from the context-link
+ edge's right-click menu (both / A reads B / B reads A; arrowheads point at the reader) or with
+ `link --one-way` (`--from` reads). On the canvas it rides `edge.data.reader`; every bridge↔edge
+ conversion goes through `bridgeToEdge`/`edgeToBridge` (renderer/lib/noteLink.ts) and the server
+ merge keeps it (`serverChange.edgeRef`) — a field-by-field `{id, source, target}` copy silently
+ turns a one-way link two-way again. A flip that GRANTS read access sends the same one-shot
+ discovery note a new link sends; losing access sends nothing, like removing a link. Note: the
+ premise "every submit triggers a full read" does not hold — nothing reads on submit; the linked
+ agent reads only when it decides to run the skill/shim. What one-way removes is the other side's
+ PERMISSION and its discovery note.
**Note links:** a sticky note can be connected to ANY terminal node (one-way, sticky →
terminal). On connect, agent sessions get a one-shot idle-gated push of the note text
(`buildNotePushMessage`, single-line, truncated at 2000 chars); plain terminals get no
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index b0c0c484f..8432a89f3 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -963,6 +963,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' on demand (nodeterm linked-context CLI). `--from` defaults to you; nothing is pushed into the',
' linked sessions. Agent sessions you open, and the stations you name in `--after`, are already',
' linked — nothing to `link`. Use `link` only for nodes you did not open, or to link two OTHER nodes.',
+ ' `--one-way` makes each new link one-way: `--from` (you, by default) reads the `--to` nodes, and',
+ ' they cannot read it back. The human can flip or reset a link\'s direction from its right-click menu.',
` Both endpoints must be in your project. A missing endpoint reports: ${LINK_ENDPOINT_NOT_FOUND}.`,
' This does not reveal whether the id exists in another project.',
' On Server Edition the ownership rule is stricter: every endpoint must be a node you opened',
@@ -1559,7 +1561,9 @@ ${reportOutcomeDocLines().join('\n')}
pushed into the linked sessions — reading is on demand, so linking never interrupts anyone.
Agent sessions you open (\`open-claude\`/\`open-agent\`/\`spawn-team\`) and the stations you name in
\`--after\` are already linked — nothing to \`link\`. Use \`link\` only for nodes you did not open,
- or to link two OTHER nodes together.
+ or to link two OTHER nodes together. Add \`--one-way\` to make each new link one-way: \`--from\`
+ (you, by default) reads the \`--to\` nodes and they cannot read it back. The human can flip or
+ reset a link's direction from its right-click menu.
Both endpoints must be in your project. A missing endpoint reports: ${LINK_ENDPOINT_NOT_FOUND}.
This does not reveal whether the id exists in another project.
On Server Edition the ownership rule is stricter: every endpoint must be a node you opened
diff --git a/src/core/context-link.handler.test.ts b/src/core/context-link.handler.test.ts
index 94c63bd6f..ba6462b17 100644
--- a/src/core/context-link.handler.test.ts
+++ b/src/core/context-link.handler.test.ts
@@ -11,6 +11,7 @@ import { IPC } from '../shared/ipc'
import { initPlatform, resetPlatformForTests } from './platform'
import { fakePlatform, type FakePlatform } from './platform-fake'
import type { ContextLinkMap } from '../shared/types'
+import { buildLinkMap } from '../shared/context-link-map'
import type { PtyManager } from './pty-manager'
const dir = mkdtempSync(join(tmpdir(), 'ctxlink-h-'))
@@ -96,6 +97,37 @@ describe('handleContextLinkRequest — authorization', () => {
'No linked nodes'
)
})
+
+ // Issue #852 end to end: the canvas edge → buildLinkMap → the served documents. The one-way
+ // refusal must hold at the READ, not only in what the discovery note tells the agent.
+ const info = (id: string) => ({ id, title: id === 'node-A' ? 'Reader' : 'Source', sticky: false })
+
+ it('a one-way link lets the reader read and refuses the other side', async () => {
+ await setLinks(buildLinkMap([{ source: 'node-A', target: 'node-B', reader: 'node-A' }], info))
+ expect(await handleContextLinkRequest({ verb: 'list', nodeId: 'node-A', args: {} })).toContain('Source')
+ const back = await handleContextLinkRequest({
+ verb: 'transcript',
+ nodeId: 'node-B',
+ args: { node: 'node-A' }
+ })
+ expect(back).toContain('No linked nodes')
+ expect(back).not.toContain('Reader')
+ })
+
+ it('flipping the direction moves the permission with it', async () => {
+ await setLinks(buildLinkMap([{ source: 'node-A', target: 'node-B', reader: 'node-A' }], info))
+ await setLinks(buildLinkMap([{ source: 'node-A', target: 'node-B', reader: 'node-B' }], info))
+ expect(await handleContextLinkRequest({ verb: 'list', nodeId: 'node-A', args: {} })).toContain(
+ 'No linked nodes'
+ )
+ expect(await handleContextLinkRequest({ verb: 'list', nodeId: 'node-B', args: {} })).toContain('Reader')
+ })
+
+ it('a reader-less (pre-#852) link still serves both sides', async () => {
+ await setLinks(buildLinkMap([{ source: 'node-A', target: 'node-B' }], info))
+ expect(await handleContextLinkRequest({ verb: 'list', nodeId: 'node-A', args: {} })).toContain('Source')
+ expect(await handleContextLinkRequest({ verb: 'list', nodeId: 'node-B', args: {} })).toContain('Reader')
+ })
})
describe('handleContextLinkRequest — local reads', () => {
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index 0e6fc06b6..8324511ca 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -1618,3 +1618,10 @@ describe('open-project --name limit in the agent-facing text (issue #940)', () =
expect(squash(buildCanvasControlInstructions('/tmp/nodeterm.sh'))).toContain(sentence)
})
})
+
+describe('one-way context links (issue #852) — agent-facing docs', () => {
+ it('both canvas-control surfaces document link --one-way', () => {
+ expect(buildCanvasControlInstructions('/x/nodeterm.sh')).toContain('--one-way')
+ expect(buildCanvasSkillBody('/x/nodeterm.sh')).toContain('--one-way')
+ })
+})
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 098f9c60f..dac4d88ae 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -603,7 +603,7 @@ import { answerHostedRequest, type HostedAnswer } from '../lib/hostedOwner'
import { headRequest, type QueuedRequest } from '../lib/hostedPendingQueue'
import { useHostedPending } from '../state/hostedPending'
import { hostedInfoFor, isHostedReadOnly, useHostedTeams } from '../state/hostedTeams'
-import { buildContextLinkNote, buildNotePushMessage, classifyLink, hiddenLinkIds, linkIdsCoveredByRopes, pairKey, planBridges, type LinkEndpoint } from '../lib/noteLink'
+import { bridgeToEdge, buildContextLinkNote, buildNotePushMessage, classifyLink, edgeToBridge, gainedReaders, hiddenLinkIds, linkIdsCoveredByRopes, linkReadPairs, pairKey, planBridges, withLinkReader, type LinkEndpoint } from '../lib/noteLink'
import {
deliveriesToRetire,
launchesToFire,
@@ -2813,22 +2813,26 @@ export function Canvas() {
const sel = !!e.selected
const isNote = stickyIds.has(e.source)
const stroke = sel ? '#ffffff' : accent
- const baseLabel = isNote ? '🗒 note' : '⇄ context'
+ const arrow = { type: MarkerType.ArrowClosed, color: stroke, width: 14, height: 14 }
+ // Arrowheads point at the side that READS, as a note link's does (it ends at the terminal).
+ // A context link is two-way unless it names a one-way reader (issue #852).
+ const readers = isNote ? [e.target] : linkReadPairs(edgeToBridge(e)).map((p) => p.reader)
+ const oneWay = !isNote && readers.length < 2
+ const baseLabel = isNote ? '🗒 note' : oneWay ? '→ context (one-way)' : '⇄ context'
return {
...e,
type: 'floating',
// Context and note links meet the node at its bridge handles (left/right dots) — the point
// the user dragged from — never at the top or bottom.
data: { anchor: 'horizontal' },
- label: sel ? `${baseLabel} — ⌫ to remove` : baseLabel,
+ label: sel
+ ? `${baseLabel} — ⌫ to remove${isNote ? '' : ' · right-click for direction'}`
+ : baseLabel,
labelStyle: { fill: stroke, fontSize: 11, fontWeight: 600 },
...labelBg,
style: { stroke, strokeWidth: sel ? 3.5 : 2 },
- markerEnd: { type: MarkerType.ArrowClosed, color: stroke, width: 14, height: 14 },
- // Context links are bidirectional (arrowheads both ends); note links flow one way.
- ...(isNote
- ? {}
- : { markerStart: { type: MarkerType.ArrowClosed, color: stroke, width: 14, height: 14 } })
+ ...(readers.includes(e.target) ? { markerEnd: arrow } : {}),
+ ...(readers.includes(e.source) ? { markerStart: arrow } : {})
}
})
const ropeCoversLink = new Set(
@@ -3204,7 +3208,7 @@ export function Canvas() {
// installEpoch assigns nodesRef: the setters land on a later render, and a peer's edge op
// arriving in between would otherwise be built from the PREVIOUS project's edges and then
// overwrite this load's queued value (see the ref declarations for the render-time half).
- const loadedBridges: Edge[] = (project.bridges ?? []).map((b) => ({ id: b.id, source: b.source, target: b.target }))
+ const loadedBridges: Edge[] = (project.bridges ?? []).map(bridgeToEdge)
linkEdgesRef.current = loadedBridges
setLinkEdges(loadedBridges)
// A wait with no rope is a wait nothing on screen explains. Ropes for `--after` are written by
@@ -3481,7 +3485,7 @@ export function Canvas() {
id,
flowToNodeStates(nodesRef.current, sessionForProject(nodesProjectIdRef.current ?? '').source !== 'relay'),
viewportRef.current,
- linkEdgesRef.current.map(toBridgeLink),
+ linkEdgesRef.current.map(edgeToBridge),
controlEdgesRef.current.map(toBridgeLink)
)
}, [])
@@ -3865,11 +3869,7 @@ export function Canvas() {
source: e.source,
target: e.target
})),
- liveBridges: linkEdgesRef.current.map((e) => ({
- id: e.id,
- source: e.source,
- target: e.target
- }))
+ liveBridges: linkEdgesRef.current.map(edgeToBridge)
})
const adopted = adoptNodesSilently(plan.added)
// Only when the merge actually moved something: a fresh array of identical edges re-renders
@@ -3883,7 +3883,7 @@ export function Canvas() {
setControlEdges(ropes)
}
if (plan.bridgesChanged) {
- const bridges: Edge[] = plan.bridges.map((b) => ({ id: b.id, source: b.source, target: b.target }))
+ const bridges: Edge[] = plan.bridges.map(bridgeToEdge)
linkEdgesRef.current = bridges
setLinkEdges(bridges)
}
@@ -4623,6 +4623,21 @@ export function Canvas() {
[agentIdOf]
)
+ // One-shot discovery note into an idle agent endpoint that can now read `otherId` (skip a node
+ // mid-turn so we don't interrupt it). Claude gets the skill pointer; codex/gemini the CLI inline.
+ const announceContextLink = useCallback(
+ async (selfId: string, otherId: string) => {
+ if (useAgentStatus.getState().byId[selfId]?.state === 'working') return
+ const title = (nodesRef.current.find((n) => n.id === otherId)?.data.title as string) || 'a linked node'
+ const { shimPath } = await window.nodeTerminal.contextLink.info()
+ void api.pty.sendText(
+ selfId,
+ buildContextLinkNote(agentIdOf(selfId), title, shimPath)
+ ).then(reportTextDelivery)
+ },
+ [agentIdOf]
+ )
+
// Draw a link: context (two agent nodes read each other) or note (sticky text becomes
// the terminal's context).
const onConnect = useCallback(
@@ -4649,21 +4664,11 @@ export function Canvas() {
)
markDirty()
const status = useAgentStatus.getState().byId
- const titleOf = (id: string) =>
- (nodes.find((n) => n.id === id)?.data.title as string) || 'a linked node'
if (kind === 'context') {
// Discovery: tell each idle endpoint it is now linked (skip a node mid-turn so we
// don't interrupt it). Claude gets the skill pointer; codex/gemini get the CLI inline.
- const note = async (selfId: string, otherId: string) => {
- if (status[selfId]?.state === 'working') return
- const { shimPath } = await window.nodeTerminal.contextLink.info()
- void api.pty.sendText(
- selfId,
- buildContextLinkNote(agentIdOf(selfId), titleOf(otherId), shimPath)
- ).then(reportTextDelivery)
- }
- void note(source, target)
- void note(target, source)
+ void announceContextLink(source, target)
+ void announceContextLink(target, source)
return
}
// Note link: push the note text once into the terminal — agent sessions only.
@@ -4679,7 +4684,65 @@ export function Canvas() {
)
if (msg) void api.pty.sendText(target, msg).then(reportTextDelivery)
},
- [linkEndpointOf, agentIdOf, setLinkEdges, markDirty, nodes]
+ [linkEndpointOf, agentIdOf, setLinkEdges, markDirty, nodes, announceContextLink]
+ )
+
+ // Right-click a context link: pick its direction (issue #852) or remove it. Direction is a
+ // property of the persisted bridge (`reader`), and the link map main authorizes reads from is
+ // rebuilt from it by useContextLinkSync — so a flip changes who may read immediately, exactly as
+ // drawing or removing a link does. An endpoint that GAINS read access gets the same one-shot
+ // discovery note a freshly drawn link sends; one that loses it gets nothing, like a removal.
+ // Note links (sticky → terminal) are one-way by nature and get no menu.
+ const onEdgeContextMenu = useCallback(
+ (e: React.MouseEvent, edge: Edge) => {
+ const link = linkEdgesRef.current.find((b) => b.id === edge.id)
+ if (!link) return
+ const nodeOf = (id: string) => nodesRef.current.find((n) => n.id === id)
+ if (nodeOf(link.source)?.type === 'sticky' || nodeOf(link.target)?.type === 'sticky') return
+ e.preventDefault()
+ const titleOf = (id: string) => (nodeOf(id)?.data.title as string) || id
+ const current = edgeToBridge(link)
+ const setReader = (reader: string | null) => {
+ const next = withLinkReader(current, reader)
+ setLinkEdges((es) =>
+ es.map((x) => (x.id === link.id ? { ...bridgeToEdge(next), selected: x.selected } : x))
+ )
+ markDirty()
+ for (const id of gainedReaders(current, next)) {
+ void announceContextLink(id, id === next.source ? next.target : next.source)
+ }
+ }
+ const a = titleOf(link.source)
+ const b = titleOf(link.target)
+ const option = (label: string, reader: string | null) => {
+ const active = (current.reader ?? null) === reader
+ return {
+ label: `${active ? '✓ ' : ''}${label}`,
+ onClick: () => setReader(reader),
+ ...(active ? { disabled: true, hint: 'Current direction' } : {})
+ }
+ }
+ setMenu({
+ x: e.clientX,
+ y: e.clientY,
+ items: [
+ { type: 'label', label: 'Context link — who reads whom' },
+ option(`${a} ⇄ ${b} (both read)`, null),
+ option(`${a} reads ${b} only`, link.source),
+ option(`${b} reads ${a} only`, link.target),
+ { type: 'separator' },
+ {
+ label: 'Remove link',
+ danger: true,
+ onClick: () => {
+ setLinkEdges((es) => es.filter((x) => x.id !== link.id))
+ markDirty()
+ }
+ }
+ ]
+ })
+ },
+ [setLinkEdges, markDirty, announceContextLink]
)
// Of these ropes, the ones that are NOT live waits. A waiting rope's removal means "stop waiting
@@ -4768,8 +4831,10 @@ export function Canvas() {
// The RENDERED epoch, not the ref: in a project switch's window the ref already names the incoming
// project while `nodes` / `linkEdges` are still the outgoing one's (see useNodesEpoch), and this map
- // authorizes context reads.
- useContextLinkSync({ projectId: renderedProjectId, nodes, edges: linkEdges })
+ // authorizes context reads. Persisted-shape bridges: the one-way `reader` (issue #852) lives in
+ // edge.data on the canvas.
+ const linkBridges = useMemo(() => linkEdges.map(edgeToBridge), [linkEdges])
+ useContextLinkSync({ projectId: renderedProjectId, nodes, edges: linkBridges })
// Phone chat: tell the core's agent-status mirror which session each node was last running, for
// nodes it learned nothing about this run (see useMirrorIdentitySeed).
useMirrorIdentitySeed()
@@ -13781,13 +13846,14 @@ export function Canvas() {
const bridgeTo = (
fromId: string,
targetIds: string[],
- lookup: (id: string) => LinkEndpoint | null = ctlLinkEndpointOf
+ lookup: (id: string) => LinkEndpoint | null = ctlLinkEndpointOf,
+ options: { oneWay?: boolean } = {}
) => {
// Off canvas the existing edges are the OWNING project's persisted `bridges` — React
// Flow's array belongs to whatever the human is looking at, so deduping against it would
// let a link be drawn twice (or refuse one that does not exist yet).
const existing = offCanvas ? (offCanvas.project.bridges ?? []) : linkEdgesRef.current
- const plan = planBridges(fromId, targetIds, lookup, [...existing, ...drawn])
+ const plan = planBridges(fromId, targetIds, lookup, [...existing, ...drawn], options)
if (plan.edges.length) {
drawn.push(...plan.edges)
if (offCanvas) {
@@ -14481,7 +14547,10 @@ export function Canvas() {
reply({ ok: false, error: `link: --from ${from}: ${LINK_ENDPOINT_NOT_FOUND}` })
return
}
- const { linked, skipped } = bridgeTo(from, targets)
+ // `--one-way` (issue #852): only --from reads the targets. Valueless flag — the shim
+ // sends it as `arg.one-way=` (present, empty).
+ const oneWay = 'one-way' in args
+ const { linked, skipped } = bridgeTo(from, targets, undefined, { oneWay })
if (linked.length === 0) {
reply({
ok: false,
@@ -14494,7 +14563,9 @@ export function Canvas() {
: ''
reply({
ok: true,
- message: `linked ${from} ↔ ${linked.join(', ')}${note}`,
+ message: oneWay
+ ? `linked one-way: ${from} reads ${linked.join(', ')}${note}`
+ : `linked ${from} ↔ ${linked.join(', ')}${note}`,
result: { from, linked, skipped }
})
return
@@ -18529,6 +18600,7 @@ export function Canvas() {
onEdgesChange={handleEdgesChange}
onConnect={onConnect}
onEdgeDoubleClick={onEdgeDoubleClick}
+ onEdgeContextMenu={onEdgeContextMenu}
onMove={onMove}
onMoveStart={onCanvasMoveStart}
onMoveEnd={onCanvasMoveEnd}
diff --git a/src/renderer/canvas/context-link-direction.source.test.ts b/src/renderer/canvas/context-link-direction.source.test.ts
new file mode 100644
index 000000000..b7df4ed96
--- /dev/null
+++ b/src/renderer/canvas/context-link-direction.source.test.ts
@@ -0,0 +1,48 @@
+import { describe, it, expect } from 'vitest'
+import { readFileSync } from 'node:fs'
+
+/**
+ * STRUCTURAL pins for one-way context links (issue #852). The direction lives on the persisted
+ * bridge (`reader`) and rides React Flow's `edge.data`; every place Canvas converts between the
+ * two must go through `bridgeToEdge` / `edgeToBridge`, or a load, save or server merge silently
+ * turns a one-way link back into a two-way one. The behavioural halves are proven in
+ * `noteLink.test.ts` (conversion), `serverChange.test.ts` (merge), `context-link-map.test.ts`
+ * (map) and `context-link.handler.test.ts` (read refusal).
+ */
+const src = readFileSync(new URL('./Canvas.tsx', import.meta.url), 'utf8')
+
+describe('one-way context links — Canvas wiring (source pins)', () => {
+ it('never rebuilds a bridge edge field-by-field (that drops the reader)', () => {
+ expect(src).not.toMatch(/\(\{ id: b\.id, source: b\.source, target: b\.target \}\)/)
+ expect(src).not.toMatch(/linkEdgesRef\.current\.map\(\(e\) => \(\{ id: e\.id, source: e\.source, target: e\.target \}\)\)/)
+ expect(src).toContain('setLinkEdges((project.bridges ?? []).map(bridgeToEdge))')
+ expect(src).toContain('linkEdgesRef.current.map(edgeToBridge)')
+ expect(src).toContain('liveBridges: linkEdgesRef.current.map(edgeToBridge)')
+ expect(src).toContain('setLinkEdges(plan.bridges.map(bridgeToEdge))')
+ })
+
+ it('publishes the link map from reader-carrying bridges', () => {
+ expect(src).toMatch(/useContextLinkSync\(\{ projectId: nodesProjectIdRef\.current, nodes, edges: linkBridges \}\)/)
+ })
+
+ it('draws the arrowhead on the reading side only for a one-way link', () => {
+ const start = src.indexOf('const displayEdges = useMemo(')
+ const body = src.slice(start, src.indexOf('const ropeCoversLink', start))
+ expect(body).toContain('linkReadPairs(')
+ })
+
+ it('offers the direction on the context-link edge menu and routes it through withLinkReader', () => {
+ expect(src).toMatch(/onEdgeContextMenu=\{onEdgeContextMenu\}/)
+ const start = src.indexOf('const onEdgeContextMenu = useCallback(')
+ expect(start).toBeGreaterThan(-1)
+ const body = src.slice(start, start + 4000)
+ expect(body).toContain('withLinkReader(')
+ expect(body).toContain('gainedReaders(')
+ })
+
+ it('the link verb passes --one-way to the shared planner', () => {
+ const start = src.indexOf("case 'link': {")
+ const body = src.slice(start, start + 2000)
+ expect(body).toContain("'one-way' in args")
+ })
+})
diff --git a/src/renderer/canvas/useContextLinkSync.ts b/src/renderer/canvas/useContextLinkSync.ts
index 44bdd8d05..6fd1307cf 100644
--- a/src/renderer/canvas/useContextLinkSync.ts
+++ b/src/renderer/canvas/useContextLinkSync.ts
@@ -9,7 +9,8 @@ export interface LiveContextLinks {
// Capture the epoch DURING render, before the project-load effect changes its ref.
projectId: string | null
nodes: Array<{ id: string; type?: string; data: Record<string, unknown> }>
- edges: Array<{ source: string; target: string }>
+ /** Persisted-shape bridges (`edgeToBridge`), so a one-way link's `reader` reaches the map. */
+ edges: Array<{ source: string; target: string; reader?: string }>
}
/** Publish semantic changes, independent of drag/status render frequency. Subscriptions also
diff --git a/src/renderer/lib/noteLink.test.ts b/src/renderer/lib/noteLink.test.ts
index 99878240e..b8f31cbbc 100644
--- a/src/renderer/lib/noteLink.test.ts
+++ b/src/renderer/lib/noteLink.test.ts
@@ -8,7 +8,9 @@ import {
hiddenLinkIds,
linkIdsCoveredByRopes,
pairKey,
- planBridges
+ planBridges,
+ bridgeToEdge,
+ edgeToBridge
} from './noteLink'
import type { CanvasNodeState } from '@shared/types'
@@ -410,3 +412,25 @@ describe('the note builders cannot be made to submit a second line', () => {
expect(buildNotePushMessage('T', 'one\ntwo')).toContain('one ⏎ two')
})
})
+
+describe('bridge ⇄ React Flow edge (issue #852)', () => {
+ it('a reader-less bridge round-trips with no data field (old project.json unchanged)', () => {
+ const b = { id: 'bridge-a-b', source: 'a', target: 'b' }
+ const e = bridgeToEdge(b)
+ expect(e).toEqual(b)
+ expect(edgeToBridge(e)).toEqual(b)
+ })
+
+ it('a one-way bridge carries its reader in edge.data and back', () => {
+ const b = { id: 'bridge-a-b', source: 'a', target: 'b', reader: 'b' }
+ const e = bridgeToEdge(b)
+ expect(e).toEqual({ id: 'bridge-a-b', source: 'a', target: 'b', data: { reader: 'b' } })
+ expect(edgeToBridge(e)).toEqual(b)
+ })
+
+ it('drops display-only edge fields and a non-string reader', () => {
+ expect(
+ edgeToBridge({ id: 'x', source: 'a', target: 'b', selected: true, data: { reader: 7, anchor: 'h' } } as never)
+ ).toEqual({ id: 'x', source: 'a', target: 'b' })
+ })
+})
diff --git a/src/renderer/lib/noteLink.ts b/src/renderer/lib/noteLink.ts
index 2b4a4b697..a02b86da8 100644
--- a/src/renderer/lib/noteLink.ts
+++ b/src/renderer/lib/noteLink.ts
@@ -2,7 +2,9 @@
// agent nodes vs. note link between a sticky and a terminal), build the one-shot push
// message a note link injects into an agent session, and re-export the link-map builders.
// Kept free of React/store imports so the connection matrix is unit-testable.
+import type { Edge } from '@xyflow/react'
import { oneLine } from '@shared/one-line'
+import type { BridgeLink } from '@shared/types'
import {
classifyLink,
planBridges,
@@ -13,13 +15,34 @@ import {
// Server Edition consumes the same pure planner directly from shared.
export {
classifyLink,
+ gainedReaders,
+ linkReadPairs,
planBridges,
+ withLinkReader,
type BridgePlan,
type LinkEndpoint,
type LinkKind,
type SkippedBridge
} from '@shared/canvas-link'
+/**
+ * Persisted bridge → React Flow edge. A one-way link's reader (issue #852) rides `edge.data`,
+ * because React Flow owns the edge's top-level fields; a reader-less bridge gets no `data` at all,
+ * so every pre-#852 link loads exactly as before.
+ */
+export function bridgeToEdge(b: BridgeLink): Edge {
+ const e: Edge = { id: b.id, source: b.source, target: b.target }
+ return typeof b.reader === 'string' ? { ...e, data: { reader: b.reader } } : e
+}
+
+/** React Flow edge → persisted bridge: id, endpoints and the one-way reader only — selection and
+ * display-only data never reach project.json. The single inverse of `bridgeToEdge`. */
+export function edgeToBridge(e: Pick<Edge, 'id' | 'source' | 'target' | 'data'>): BridgeLink {
+ const b: BridgeLink = { id: e.id, source: e.source, target: e.target }
+ const reader = (e.data as { reader?: unknown } | undefined)?.reader
+ return typeof reader === 'string' ? { ...b, reader } : b
+}
+
/** Order-independent key for an edge's endpoints (a↔b and b↔a are the same connection). */
export function pairKey(a: string, b: string): string {
return a < b ? `${a}\0${b}` : `${b}\0${a}`
diff --git a/src/renderer/lib/serverChange.test.ts b/src/renderer/lib/serverChange.test.ts
index 9e0333997..619db9bfb 100644
--- a/src/renderer/lib/serverChange.test.ts
+++ b/src/renderer/lib/serverChange.test.ts
@@ -211,4 +211,23 @@ describe('planServerChange', () => {
expect(plan.bridges.map((b) => b.id)).toEqual(['bridge-local', 'bridge-new'])
expect(plan.bridgesChanged).toBe(true)
})
+
+ it('keeps a one-way link\'s reader through the merge (issue #852)', () => {
+ // The merge used to rebuild every edge as {id, source, target}: any server-side change would
+ // have silently turned the user's one-way link back into a two-way one.
+ const spawned = node('term-spawned')
+ const plan = planServerChange({
+ base: project([caller, first]),
+ incoming: project([caller, first, spawned], {
+ bridges: [{ id: 'bridge-new', source: caller.id, target: spawned.id, reader: spawned.id }]
+ }),
+ liveNodeIds: [caller.id, first.id],
+ liveRopes: [],
+ liveBridges: [{ id: 'bridge-local', source: caller.id, target: first.id, reader: caller.id }]
+ })
+ expect(plan.bridges).toEqual([
+ { id: 'bridge-local', source: caller.id, target: first.id, reader: caller.id },
+ { id: 'bridge-new', source: caller.id, target: spawned.id, reader: spawned.id }
+ ])
+ })
})
diff --git a/src/renderer/lib/serverChange.ts b/src/renderer/lib/serverChange.ts
index 443642cd5..bea3d94de 100644
--- a/src/renderer/lib/serverChange.ts
+++ b/src/renderer/lib/serverChange.ts
@@ -27,6 +27,8 @@ export interface EdgeRef {
id: string
source: string
target: string
+ /** Bridges only: the one-way reader of a context link (issue #852). Ropes never carry it. */
+ reader?: string
}
export interface ServerChangeInput {
@@ -56,7 +58,12 @@ export interface ServerChangePlan {
bridgesChanged: boolean
}
-const edgeRef = (e: EdgeRef): EdgeRef => ({ id: e.id, source: e.source, target: e.target })
+// A bridge's one-way `reader` (issue #852) is part of the link, not display state: dropping it
+// here would turn a one-way link back into a two-way one on any server-side change.
+const edgeRef = (e: EdgeRef): EdgeRef =>
+ typeof e.reader === 'string'
+ ? { id: e.id, source: e.source, target: e.target, reader: e.reader }
+ : { id: e.id, source: e.source, target: e.target }
/** One merge, applied to ropes and to bridges alike — they are the same problem with two names,
* and a second copy of these five rules is a second place for them to drift. */
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index 9447b8982..3bb0bd4fe 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -585,6 +585,20 @@ describe('HeadlessNodeFactory', () => {
expect(pty.sends).toEqual([])
})
+ it('link --one-way persists a reader so only --from reads (issue #852)', async () => {
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push(terminal('term-third', 'Third', 'gemini', 900))
+ await store.save(workspace)
+ ownership.record('term-third', { sourceNodeId: 'term-source', projectId: 'project-1' })
+
+ await expect(
+ factory.link('term-source', { from: 'term-upstream', to: 'term-third', 'one-way': '' }, true)
+ ).resolves.toMatchObject({ ok: true, result: { from: 'term-upstream', linked: ['term-third'] } })
+ expect((await store.load({ sideline: false })).projects[0].bridges).toEqual([
+ expect.objectContaining({ source: 'term-upstream', target: 'term-third', reader: 'term-upstream' })
+ ])
+ })
+
it('refuses unverified and cross-project link endpoints without a partial graph edit', async () => {
await expect(factory.link('term-source', { to: 'term-upstream' }, false)).resolves.toMatchObject({
ok: false,
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index 5ab9ec870..99f1eb222 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -1156,7 +1156,7 @@ export class HeadlessNodeFactory {
verified: boolean
): Promise<ServerControlReply> {
return this.runExclusive(async () => {
- const flagError = unsupportedFlags(args, new Set(['from', 'to']))
+ const flagError = unsupportedFlags(args, new Set(['from', 'to', 'one-way']))
if (flagError) return { ok: false, error: `link: ${flagError}` }
if (!verified) {
return {
@@ -1203,7 +1203,9 @@ export class HeadlessNodeFactory {
const node = byId.get(id)
return node ? headlessLinkEndpoint(node, this.deps.agentIdOf) : null
},
- existing
+ existing,
+ // Valueless flag: the shim sends `arg.one-way=` (present, empty).
+ { oneWay: 'one-way' in args }
)
if (!plan.edges.length) {
return {
@@ -1222,7 +1224,9 @@ export class HeadlessNodeFactory {
: ''
return {
ok: true,
- message: `linked ${from} ↔ ${plan.linked.join(', ')}${note}`,
+ message: 'one-way' in args
+ ? `linked one-way: ${from} reads ${plan.linked.join(', ')}${note}`
+ : `linked ${from} ↔ ${plan.linked.join(', ')}${note}`,
result: { from, linked: plan.linked, skipped: plan.skipped }
}
})
diff --git a/src/shared/canvas-link.test.ts b/src/shared/canvas-link.test.ts
new file mode 100644
index 000000000..afe9c6954
--- /dev/null
+++ b/src/shared/canvas-link.test.ts
@@ -0,0 +1,93 @@
+// Issue #852: a context link may be one-way. These pin the pure "who reads whom" rule that both
+// shells (desktop renderer, Server Edition) derive the read-authorization map from.
+import { describe, it, expect } from 'vitest'
+import { gainedReaders, linkReadPairs, planBridges, withLinkReader } from './canvas-link'
+
+describe('linkReadPairs', () => {
+ it('a link without a reader is bidirectional (every link persisted before #852)', () => {
+ expect(linkReadPairs({ source: 'a', target: 'b' })).toEqual([
+ { reader: 'a', read: 'b' },
+ { reader: 'b', read: 'a' }
+ ])
+ })
+
+ it('reader = source: only the source reads the target', () => {
+ expect(linkReadPairs({ source: 'a', target: 'b', reader: 'a' })).toEqual([
+ { reader: 'a', read: 'b' }
+ ])
+ })
+
+ it('reader = target: only the target reads the source', () => {
+ expect(linkReadPairs({ source: 'a', target: 'b', reader: 'b' })).toEqual([
+ { reader: 'b', read: 'a' }
+ ])
+ })
+
+ it('fails closed on a reader that is not an endpoint (hand-edited or corrupt project.json)', () => {
+ expect(linkReadPairs({ source: 'a', target: 'b', reader: 'c' })).toEqual([])
+ expect(linkReadPairs({ source: 'a', target: 'b', reader: '' })).toEqual([])
+ expect(
+ linkReadPairs({ source: 'a', target: 'b', reader: 42 as unknown as string })
+ ).toEqual([])
+ })
+})
+
+describe('withLinkReader', () => {
+ const edge = { id: 'bridge-a-b', source: 'a', target: 'b' }
+
+ it('sets a reader on a copy, never mutating the input', () => {
+ const next = withLinkReader(edge, 'b')
+ expect(next).toEqual({ id: 'bridge-a-b', source: 'a', target: 'b', reader: 'b' })
+ expect(edge).toEqual({ id: 'bridge-a-b', source: 'a', target: 'b' })
+ })
+
+ it('null returns the link to bidirectional by dropping the field entirely', () => {
+ const next = withLinkReader({ ...edge, reader: 'a' }, null)
+ expect(next).toEqual(edge)
+ expect('reader' in next).toBe(false)
+ })
+
+ it('ignores a reader that is not an endpoint', () => {
+ expect(withLinkReader(edge, 'z')).toBe(edge)
+ })
+})
+
+describe('gainedReaders', () => {
+ it('flipping one-way hands read access to the other side only', () => {
+ expect(
+ gainedReaders({ source: 'a', target: 'b', reader: 'a' }, { source: 'a', target: 'b', reader: 'b' })
+ ).toEqual(['b'])
+ })
+
+ it('both → one-way grants nobody anything new', () => {
+ expect(
+ gainedReaders({ source: 'a', target: 'b' }, { source: 'a', target: 'b', reader: 'a' })
+ ).toEqual([])
+ })
+
+ it('one-way → both grants the former non-reader', () => {
+ expect(
+ gainedReaders({ source: 'a', target: 'b', reader: 'a' }, { source: 'a', target: 'b' })
+ ).toEqual(['b'])
+ })
+})
+
+describe('planBridges oneWay', () => {
+ const lookup = (id: string) =>
+ id === 's1' ? { kind: 'sticky', contextCapable: false } : { kind: 'terminal', contextCapable: true }
+
+ it('a one-way context bridge makes --from the only reader', () => {
+ const plan = planBridges('n1', ['n2'], lookup, [], { oneWay: true })
+ expect(plan.edges).toEqual([{ id: 'bridge-n1-n2', source: 'n1', target: 'n2', reader: 'n1' }])
+ })
+
+ it('without the option the edge carries no reader (bidirectional, unchanged shape)', () => {
+ const plan = planBridges('n1', ['n2'], lookup, [])
+ expect(plan.edges).toEqual([{ id: 'bridge-n1-n2', source: 'n1', target: 'n2' }])
+ })
+
+ it('note links are one-way by nature and never carry a reader', () => {
+ const plan = planBridges('n1', ['s1'], lookup, [], { oneWay: true })
+ expect(plan.edges).toEqual([{ id: 'bridge-s1-n1', source: 's1', target: 'n1' }])
+ })
+})
diff --git a/src/shared/canvas-link.ts b/src/shared/canvas-link.ts
index cc4ab7d88..2ccc72110 100644
--- a/src/shared/canvas-link.ts
+++ b/src/shared/canvas-link.ts
@@ -20,6 +20,60 @@ export const LINK_ENDPOINT_NOT_FOUND = `node not found in this project; ${LINK_P
export type LinkKind = 'context' | 'note'
+/** The endpoints of a context link, plus its optional one-way reader (issue #852). */
+export interface LinkEdge {
+ source: string
+ target: string
+ reader?: string
+}
+
+/** One granted read: `reader` may read `read`'s context. */
+export interface LinkRead {
+ reader: string
+ read: string
+}
+
+/**
+ * Who may READ whom across one CONTEXT link. This is the rule the read authorization is built
+ * from (buildLinkMap → main's per-node link documents), so it is the enforcement point, not a
+ * display hint. No `reader` = both directions (every link persisted before issue #852); a reader
+ * that names neither endpoint grants nothing — a restriction that cannot be understood must not
+ * fall back to the wider permission.
+ */
+export function linkReadPairs(edge: LinkEdge): LinkRead[] {
+ const { source, target } = edge
+ if (!('reader' in edge) || edge.reader === undefined) {
+ return [
+ { reader: source, read: target },
+ { reader: target, read: source }
+ ]
+ }
+ if (edge.reader === source) return [{ reader: source, read: target }]
+ if (edge.reader === target) return [{ reader: target, read: source }]
+ return []
+}
+
+/** A copy of `edge` made one-way toward `reader`, or bidirectional again for `null`. A reader
+ * that is not an endpoint changes nothing (returns the same object). */
+export function withLinkReader<T extends LinkEdge>(edge: T, reader: string | null): T {
+ if (reader === null) {
+ const { reader: _dropped, ...rest } = edge
+ return rest as T
+ }
+ if (reader !== edge.source && reader !== edge.target) return edge
+ return { ...edge, reader }
+}
+
+/** Endpoints that may read after a direction change but could not before — the ones owed the
+ * same one-shot discovery note a freshly drawn link sends. Losing access sends nothing, exactly
+ * like removing a link. */
+export function gainedReaders(before: LinkEdge, after: LinkEdge): string[] {
+ const had = new Set(linkReadPairs(before).map((p) => p.reader))
+ return linkReadPairs(after)
+ .map((p) => p.reader)
+ .filter((r) => !had.has(r))
+}
+
/** Decide what kind of link (if any) a new edge between two nodes forms. */
export function classifyLink(a: LinkEndpoint, b: LinkEndpoint): LinkKind | null {
const stickies = (a.kind === 'sticky' ? 1 : 0) + (b.kind === 'sticky' ? 1 : 0)
@@ -48,12 +102,14 @@ export interface BridgePlan {
* The caller supplies node lookup and the already-persisted edges, so this stays independent of
* React/store/server state. Note edges normalize to sticky→terminal; every pair dedupes in either
* direction. Creating the edges has no delivery side effect: context is always read on demand.
+ * `options.oneWay` makes each new context edge readable by `fromId` only (issue #852).
*/
export function planBridges(
fromId: string,
targetIds: string[],
lookup: (id: string) => LinkEndpoint | null,
- existing: readonly { source: string; target: string }[]
+ existing: readonly { source: string; target: string }[],
+ options: { oneWay?: boolean } = {}
): BridgePlan {
const edges: BridgeLink[] = []
const linked: string[] = []
@@ -90,7 +146,13 @@ export function planBridges(
skipped.push({ id: targetId, why: 'already linked' })
continue
}
- edges.push({ id: `bridge-${source}-${target}`, source, target })
+ // `oneWay` (issue #852): `fromId` reads the targets, never the reverse. Note links are
+ // already one-way (the terminal reads the sticky) and never carry a reader.
+ edges.push(
+ kind === 'context' && options.oneWay
+ ? { id: `bridge-${source}-${target}`, source, target, reader: fromId }
+ : { id: `bridge-${source}-${target}`, source, target }
+ )
linked.push(targetId)
}
return { edges, linked, skipped }
diff --git a/src/shared/context-link-map.test.ts b/src/shared/context-link-map.test.ts
new file mode 100644
index 000000000..a0098395e
--- /dev/null
+++ b/src/shared/context-link-map.test.ts
@@ -0,0 +1,54 @@
+// Issue #852: the link map is the read AUTHORIZATION (main serves a node only the entries of its
+// own document). A one-way link must therefore put an entry on the reading side only.
+import { describe, it, expect } from 'vitest'
+import { buildBackgroundLinkMaps, buildLinkMap, type LinkNodeInfo } from './context-link-map'
+import type { CanvasNodeState } from './types'
+
+const info = (id: string): LinkNodeInfo => ({ id, title: id.toUpperCase(), cwd: `/w/${id}`, sticky: id.startsWith('s') })
+
+describe('buildLinkMap direction', () => {
+ it('a link without a reader maps both directions (backward compatible)', () => {
+ const map = buildLinkMap([{ source: 'a', target: 'b' }], info)
+ expect(Object.keys(map).sort()).toEqual(['a', 'b'])
+ expect(map.a!.map((e) => e.id)).toEqual(['b'])
+ expect(map.b!.map((e) => e.id)).toEqual(['a'])
+ })
+
+ it('reader = source: only the source gets an entry', () => {
+ const map = buildLinkMap([{ source: 'a', target: 'b', reader: 'a' }], info)
+ expect(map).toEqual({ a: [{ id: 'b', title: 'B', cwd: '/w/b' }] })
+ })
+
+ it('reader = target: only the target gets an entry', () => {
+ const map = buildLinkMap([{ source: 'a', target: 'b', reader: 'b' }], info)
+ expect(map).toEqual({ b: [{ id: 'a', title: 'A', cwd: '/w/a' }] })
+ })
+
+ it('a reader naming neither endpoint authorizes nobody', () => {
+ expect(buildLinkMap([{ source: 'a', target: 'b', reader: 'x' }], info)).toEqual({})
+ })
+
+ it('note links keep their fixed direction (terminal reads the sticky)', () => {
+ const map = buildLinkMap([{ source: 's1', target: 'a' }], info)
+ expect(Object.keys(map)).toEqual(['a'])
+ })
+})
+
+describe('buildBackgroundLinkMaps direction', () => {
+ const node = (id: string): CanvasNodeState => ({
+ id, kind: 'terminal', agentId: 'claude', position: { x: 0, y: 0 }, size: { width: 1, height: 1 },
+ title: id, color: '#fff', group: null, cwd: `/w/${id}`
+ })
+
+ it('honours a persisted reader and still reads old, reader-less bridges as bidirectional', () => {
+ const map = buildBackgroundLinkMaps(
+ [
+ { id: 'p1', nodes: [node('a'), node('b')], bridges: [{ id: 'l1', source: 'a', target: 'b', reader: 'a' }] },
+ { id: 'p2', nodes: [node('c'), node('d')], bridges: [{ id: 'l2', source: 'c', target: 'd' }] }
+ ],
+ null,
+ () => undefined
+ )
+ expect(Object.keys(map).sort()).toEqual(['a', 'c', 'd'])
+ })
+})
diff --git a/src/shared/context-link-map.ts b/src/shared/context-link-map.ts
index b0d88b696..f219c7196 100644
--- a/src/shared/context-link-map.ts
+++ b/src/shared/context-link-map.ts
@@ -6,6 +6,7 @@
// 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'
+import { linkReadPairs, type LinkEdge } from './canvas-link'
export interface LinkNodeInfo {
id: string
@@ -20,11 +21,13 @@ export interface LinkNodeInfo {
/**
* 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).
+ * Context edges map both directions unless the edge names a one-way `reader` (issue #852), in
+ * which case only the reader gets an entry — and since main serves a node nothing outside its own
+ * entry list, that is what stops the other side reading. 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 }>,
+ edges: LinkEdge[],
infoOf: (id: string) => LinkNodeInfo
): ContextLinkMap {
const map: ContextLinkMap = {}
@@ -45,8 +48,9 @@ export function buildLinkMap(
} else if (t.sticky) {
;(map[s.id] ??= []).push(entryOf(t))
} else {
- ;(map[s.id] ??= []).push(entryOf(t))
- ;(map[t.id] ??= []).push(entryOf(s))
+ for (const { reader } of linkReadPairs(e)) {
+ ;(map[reader] ??= []).push(entryOf(reader === s.id ? t : s))
+ }
}
}
return map
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 0b64b7d29..0f90c2846 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -777,6 +777,12 @@ export interface BridgeLink {
id: string
source: string
target: string
+ /**
+ * Context links only (issue #852): the ONE endpoint allowed to read the other. Absent = both
+ * read each other, which is every link persisted before the field existed. A value naming
+ * neither endpoint authorizes nobody (fail closed) — see `linkReadPairs` in canvas-link.ts.
+ */
+ reader?: string
}
/** Where a column sits in a card's lifecycle (see @shared/kanban-category). A closed set; an