Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
refactor(session): terminal/chat leaf consumers read pty/chat/fs from the session
enes8bfb796a1690
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex a163f9ff5..891611c6b 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -131,6 +131,7 @@ import {import { relativeTime } from '../lib/relativeTime'import { AgentIcon } from '../lib/agentIcons'import { branchClaudeSession } from '../lib/claudeBranch'+import { useSession } from '../session/session'import { buildContextLinkNote, buildLinkMap, buildNotePushMessage, classifyLink, type LinkEndpoint } from '../lib/noteLink'import { useSettings } from '../state/settings'import { activePermissionMode } from '../state/permissionMode'@@ -304,6 +305,9 @@ function StatusAwareMiniMap({ onNodeDoubleClick }: { onNodeDoubleClick: (node: N}export function Canvas() {+ // This canvas's core api (a context read — stable for the session, no store subscription).+ // For the local session it IS window.nodeTerminal, so every call resolves identically.+ const { api } = useSession()const [nodes, setNodes, onNodesChange] = useNodesState<CanvasNode>([])// Persistent context links between Claude nodes (separate from ephemeral subagent/loop edges).const [linkEdges, setLinkEdges, onLinkEdgesChange] = useEdgesState<Edge>([])@@ -2927,7 +2931,7 @@ export function Canvas() {if (known) {await window.nodeTerminal.pty.sendText(nodeId, '/branch')} else {- const res = await branchClaudeSession(nodeId)+ const res = await branchClaudeSession(api, nodeId)if (!res.ok || !res.originalId) {const error = res.error ?? 'Branch failed.'// The error dialog is for humans; agent-CLI calls get the error in the reply instead.@@ -2958,7 +2962,7 @@ export function Canvas() {markDirty()return { ok: true, newNodeId: copy.id }},- [setNodes, markDirty]+ [api, setNodes, markDirty])// Transfer this agent's full conversation to a different agent. We render the sourcediff --git a/src/renderer/lib/claudeBranch.test.ts b/src/renderer/lib/claudeBranch.test.tsnew file mode 100644index 000000000..7eb959680--- /dev/null+++ b/src/renderer/lib/claudeBranch.test.ts@@ -0,0 +1,24 @@+import { describe, it, expect, vi } from 'vitest'+import type { NodeTerminalApi } from '@shared/types'+import { branchClaudeSession } from './claudeBranch'++const fakeApi = (over: { sendText?: unknown; capture?: unknown }): NodeTerminalApi =>+ ({ pty: { sendText: over.sendText, capture: over.capture } }) as unknown as NodeTerminalApi++describe('branchClaudeSession', () => {+ it('sends /branch through the passed api, not the global', async () => {+ const sendText = vi.fn(async () => true)+ const capture = vi.fn(async () => 'run claude -r abcdef12-3456 in a new terminal')+ const res = await branchClaudeSession(fakeApi({ sendText, capture }), 'node-1')+ expect(sendText).toHaveBeenCalledWith('node-1', '/branch')+ expect(capture).toHaveBeenCalledWith('node-1')+ expect(res).toEqual({ ok: true, originalId: 'abcdef12-3456' })+ })++ it('fails without polling when the session is not persistent (sendText false)', async () => {+ const capture = vi.fn()+ const res = await branchClaudeSession(fakeApi({ sendText: vi.fn(async () => false), capture }), 'node-1')+ expect(res.ok).toBe(false)+ expect(capture).not.toHaveBeenCalled()+ })+})diff --git a/src/renderer/lib/claudeBranch.ts b/src/renderer/lib/claudeBranch.tsindex 445515fd5..accf1da9e 100644--- a/src/renderer/lib/claudeBranch.ts+++ b/src/renderer/lib/claudeBranch.ts@@ -6,6 +6,11 @@// new terminal.// We parse <ORIGINAL_ID> so the caller can open a second node that resumes the parked// original conversation (`claude -r <ORIGINAL_ID>`).+//+// Pure lib: the caller passes the session's api (a component reads useSession().api) —+// this file never touches the window.nodeTerminal global.++import type { NodeTerminalApi } from '@shared/types'const ORIGINAL = /claude -r\s+([0-9a-fA-F-]{8,})/const RESUME = /\/resume\s+([0-9a-fA-F-]{8,})/@@ -18,14 +23,14 @@ export interface BranchResult {error?: string}-export async function branchClaudeSession(nodeId: string): Promise<BranchResult> {- const sent = await window.nodeTerminal.pty.sendText(nodeId, '/branch')+export async function branchClaudeSession(api: NodeTerminalApi, nodeId: string): Promise<BranchResult> {+ const sent = await api.pty.sendText(nodeId, '/branch')if (!sent) return { ok: false, error: 'Branch requires a persistent (tmux) session.' }// Poll the visible buffer until the branch output (with the original session id) appears.for (let i = 0; i < 20; i++) {await delay(300)- const buf = await window.nodeTerminal.pty.capture(nodeId)+ const buf = await api.pty.capture(nodeId)const m = buf.match(ORIGINAL) ?? buf.match(RESUME)if (m) return { ok: true, originalId: m[1] }}diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex ad049dd57..b7a83a512 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -1,6 +1,7 @@import { memo, useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'import { renderMarkdown } from '../lib/markdown'import { useAgentStatus } from '../state/agentStatus'+import { useSession } from '../session/session'import type { ChatMessage } from '@shared/types'// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each@@ -25,6 +26,9 @@ interface ChatPanelProps {* (working -> idle); live streaming is a later phase. Replaces the markdown-of-output overlay.*/export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps) {+ // This node's core api (stable for the session — the chat transcript and the tmux session+ // both live on the core this panel's project belongs to).+ const { api } = useSession()const [messages, setMessages] = useState<ChatMessage[]>([])const [input, setInput] = useState('')const [readonly, setReadonly] = useState(false)@@ -33,8 +37,8 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps)const prevState = useRef(state)const load = useCallback(() => {- void window.nodeTerminal.chat.readTranscript(sessionId, cwd, accountId).then(setMessages)- }, [sessionId, cwd, accountId])+ void api.chat.readTranscript(sessionId, cwd, accountId).then(setMessages)+ }, [api, sessionId, cwd, accountId])// Initial load.useEffect(() => {@@ -58,7 +62,7 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps)const send = useCallback(async () => {const text = input.trim()if (!text || working) return- const ok = await window.nodeTerminal.pty.sendText(nodeId, text)+ const ok = await api.pty.sendText(nodeId, text)if (!ok) {setReadonly(true)return@@ -66,7 +70,7 @@ export function ChatPanel({ nodeId, sessionId, cwd, accountId }: ChatPanelProps)// Optimistic: show the prompt immediately; the next load() reconciles from the transcript.setMessages((m) => [...m, { role: 'user', parts: [{ kind: 'text', text }] }])setInput('')- }, [input, working, nodeId])+ }, [api, input, working, nodeId])const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {if (e.key === 'Enter') {diff --git a/src/renderer/nodes/LoopNode.tsx b/src/renderer/nodes/LoopNode.tsxindex a024c3aff..db30dff4b 100644--- a/src/renderer/nodes/LoopNode.tsx+++ b/src/renderer/nodes/LoopNode.tsx@@ -3,6 +3,7 @@ import { Handle, NodeResizer, Position, type NodeProps } from '@xyflow/react'import type { CanvasNode } from '../state/workspace'import { useAgentNodes } from '../state/agentNodes'import { useAgentStatus } from '../state/agentStatus'+import { useSession } from '../session/session'/*** Loop/schedule/cron node — first-class (select/drag/resize). Shows the kind, schedule, full@@ -10,6 +11,8 @@ import { useAgentStatus } from '../state/agentStatus'* parent terminal (manual trigger).*/export function LoopNode({ id, data, selected }: NodeProps<CanvasNode>) {+ // The parent terminal's core api — the manual trigger sends into ITS tmux session.+ const { api } = useSession()const count = (data.loopCount as number) ?? 0const items = (data.loopItems as string[]) ?? []const active = !!data.loopActive@@ -27,7 +30,7 @@ export function LoopNode({ id, data, selected }: NodeProps<CanvasNode>) {const trigger = (e: React.MouseEvent) => {e.stopPropagation()- if (task) void window.nodeTerminal.pty.sendText(id.replace(/^loop-/, ''), task)+ if (task) void api.pty.sendText(id.replace(/^loop-/, ''), task)}// Manual dismiss: cron/schedule cards persist across turns/sessions/restarts, so a jobdiff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 105910f61..09ddefdba 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -61,6 +61,7 @@ import { useProjects } from '../state/projects'import { useSshConn } from '../state/sshConn'import { useWorktrees } from '../state/worktrees'import { isRemoteSessionNode } from '@shared/worktree'+import { useSession } from '../session/session'import { accountChipLabel, COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, canRename, resumeCommand, withPermissionMode, agentConfig, type AgentId } from '@shared/agents/config'import { ensureActivePermissionMode } from '../state/permissionMode'@@ -299,6 +300,10 @@ function setCo(id: string, patch: Partial<CoState>): void {*/export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNode>) {const { updateNodeData, deleteElements, getZoom, setNodes, getNode } = useReactFlow()+ // This node's core api (a context read — stable for the session's lifetime, so using it+ // inside the once-mounted lifecycle effect is safe and never re-runs that effect). Core-bound+ // namespaces (pty, fs) go through it; app-global ones (clipboard, shell) stay on the global.+ const { api } = useSession()// Pick the session layer: a remote-bound node (data.remote) talks to a host over the relay// via RemoteTransport; otherwise the local PTY (LocalTransport). The connectionId is stable// for a node's lifetime, so the instance is created once and held in a ref.@@ -641,7 +646,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNconst projectFs = (): { fs: FsApi; ssh: boolean } => {const st = useProjects.getState()const project = st.projects.find((p) => p.id === st.activeProjectId)- return project?.ssh ? { fs: sshFs(project.id), ssh: true } : { fs: window.nodeTerminal.fs, ssh: false }+ return project?.ssh ? { fs: sshFs(project.id), ssh: true } : { fs: api.fs, ssh: false }}const lookup = makeDirListingLookup(async (dir) => projectFs().fs.list(dir))term.registerLinkProvider(@@ -745,7 +750,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNconst scrollbackPromise =parked || noSpawn? Promise.resolve('')- : window.nodeTerminal.pty.readScrollback(id).catch(() => '')+ : api.pty.readScrollback(id).catch(() => '')// Consume the recycle-restart flag HERE, at the start of the spawn it belongs to — not in the// create() continuation, which returns early when the node unmounted mid-spawn and would leave// the flag set for some unrelated mount hours later ("session restarted by another user" out of@@ -1240,7 +1245,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN// A rename-capable agent's session name follows the node title: push `/rename <name>` into// the live session (tmux send-keys, like Branch's /branch). No-op for other agents/shells.const pushSessionRename = (name: string) => {- if (canRenameNode && name) void window.nodeTerminal.pty.sendText(id, `/rename ${name}`)+ if (canRenameNode && name) void api.pty.sendText(id, `/rename ${name}`)}// The user took over the name (manual rename or ✦ AI-name): stop auto-tracking the session@@ -1260,7 +1265,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNconst nameWithAi = async () => {setNaming(true)- const r = await window.nodeTerminal.pty.generateName(id, (data.cwd as string) ?? '')+ const r = await api.pty.generateName(id, (data.cwd as string) ?? '')setNaming(false)if (r.ok) applyManualTitle(r.message)}@@ -1289,7 +1294,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNlet timer: ReturnType<typeof setTimeout> | undefinedconst sync = async () => {if (!titleAutoRef.current || editingTitleRef.current) return- const name = await window.nodeTerminal.pty.readSessionName(sid, data.accountId)+ const name = await api.pty.readSessionName(sid, data.accountId)if (cancelled) returnif (name) delayMs = 15000if (@@ -1349,7 +1354,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNuseEffect(() => {if (data.mdMode && !useChat) {// Full scrollback (not just the visible viewport) so the whole session renders.- void window.nodeTerminal.pty.capture(id, true).then((t) => setMdHtml(renderMarkdown(t)))+ void api.pty.capture(id, true).then((t) => setMdHtml(renderMarkdown(t)))}}, [data.mdMode, id, useChat])diff --git a/src/renderer/terminal/useTerminalSearch.ts b/src/renderer/terminal/useTerminalSearch.tsindex ca879927f..b21646ce8 100644--- a/src/renderer/terminal/useTerminalSearch.ts+++ b/src/renderer/terminal/useTerminalSearch.ts@@ -1,5 +1,6 @@import { useEffect, useMemo, useState } from 'react'import type { TranscriptLine } from '@shared/types'+import { useSession } from '../session/session'export interface SearchSnippet {source: 'terminal' | 'claude'@@ -40,6 +41,9 @@ export function useTerminalSearch({open,readBuffer}: Args): TerminalSearch {+ // The node's core api — the tmux capture must run on the core that owns the session.+ // (Hook, so this runs in the calling component's context; the value is session-stable.)+ const { api } = useSession()const [query, setQuery] = useState('')const [cursor, setCursor] = useState(0) // 0-based index into `matches`const [source, setSource] = useState<SearchSnippet[]>([])@@ -57,7 +61,7 @@ export function useTerminalSearch({const lines: SearchSnippet[] = []let captured = ''try {- captured = await window.nodeTerminal.pty.capture(nodeId, true)+ captured = await api.pty.capture(nodeId, true)} catch {captured = ''}@@ -85,7 +89,7 @@ export function useTerminalSearch({cancelled = true}// readBuffer must be stable (useCallback in the caller) to avoid rebuilds.- }, [open, nodeId, sessionId, cwd, accountId, searchTranscript, readBuffer])+ }, [api, open, nodeId, sessionId, cwd, accountId, searchTranscript, readBuffer])// Lowercase once per snapshot, not per keystroke — the snapshot can be tens of thousands of// lines (full scrollback + transcript), and re-lowercasing all of it on every typed character