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(agent-naming): two-way sync between node title and session name

enesb4477f361390
diff --git a/src/main/index.ts b/src/main/index.ts
index f8abddaa2..8e021e56a 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -18,6 +18,7 @@ import { createContextTail } from './context-tail'
import {
readTranscriptLines,
readChatMessages,
+ readSessionName,
resolveTranscriptPath,
transcriptPathForCwd,
parseTranscriptLines,
@@ -188,6 +189,10 @@ app.whenReady().then(async () => {
ptyManager.captureSession(persistKey, full)
)
+ ipcMain.handle(IPC.ptyReadSessionName, (_e, sessionId: string, cwd: string) =>
+ readSessionName(sessionId ?? '', cwd ?? '')
+ )
+
ipcMain.on(IPC.appCloseWindow, () => BrowserWindow.getFocusedWindow()?.close())
// Dock badge: number of Claude nodes with unread output (macOS only). '' clears it.
diff --git a/src/main/transcript-reader.test.ts b/src/main/transcript-reader.test.ts
index 26aa861b3..41236c1eb 100644
--- a/src/main/transcript-reader.test.ts
+++ b/src/main/transcript-reader.test.ts
@@ -1,7 +1,30 @@
import { describe, expect, it } from 'vitest'
-import { parseTranscriptLines } from './transcript-reader'
+import { parseTranscriptLines, pickSessionName } from './transcript-reader'
import type { TranscriptLine } from '../shared/types'
+describe('pickSessionName', () => {
+ const ai = (t: string) => JSON.stringify({ type: 'ai-title', aiTitle: t, sessionId: 's' })
+ const custom = (t: string) => JSON.stringify({ type: 'custom-title', customTitle: t, sessionId: 's' })
+
+ it('returns the auto name when no /rename title is present', () => {
+ expect(pickSessionName([ai('First topic'), ai('Refined topic')].join('\n'))).toBe('Refined topic')
+ })
+
+ it('prefers the user /rename name over the auto name', () => {
+ const text = [ai('auto'), custom('My Work'), ai('auto changed')].join('\n')
+ expect(pickSessionName(text)).toBe('My Work')
+ })
+
+ it('uses the latest custom-title and trims it', () => {
+ const text = [custom('old'), custom(' new ')].join('\n')
+ expect(pickSessionName(text)).toBe('new')
+ })
+
+ it('returns null when there is no title record (and ignores junk lines)', () => {
+ expect(pickSessionName('not json\n{"type":"assistant"}\n')).toBeNull()
+ })
+})
+
describe('parseTranscriptLines', () => {
it('maps each JSONL line to TranscriptLine[] (role/text), mirroring the reader', () => {
const text = [
diff --git a/src/main/transcript-reader.ts b/src/main/transcript-reader.ts
index dac7e8223..e257b55b3 100644
--- a/src/main/transcript-reader.ts
+++ b/src/main/transcript-reader.ts
@@ -202,6 +202,63 @@ export async function resolveTranscriptPath(sessionId: string): Promise<string |
return undefined
}
+// Read only the last `cap` bytes of a file as UTF-8 (whole file if smaller). Drops the partial
+// leading line on a capped read. Cheaper than readCappedTail for tiny scans (session title).
+async function readSmallTail(filePath: string, cap: number): Promise<string | undefined> {
+ try {
+ const stat = await fs.promises.stat(filePath)
+ if (stat.size <= cap) return await fs.promises.readFile(filePath, 'utf8')
+ const fd = await fs.promises.open(filePath, 'r')
+ try {
+ const { buffer } = await fd.read({
+ position: stat.size - cap,
+ length: cap,
+ buffer: Buffer.alloc(cap)
+ })
+ const s = buffer.toString('utf8')
+ const nl = s.indexOf('\n')
+ return nl >= 0 ? s.slice(nl + 1) : s
+ } finally {
+ await fd.close()
+ }
+ } catch {
+ return undefined
+ }
+}
+
+// Pure: pick a session's display name from transcript text. Prefers the user's `/rename` name
+// (latest `custom-title` record's `customTitle`), else Claude's auto name (latest `ai-title`'s
+// `aiTitle`) — mirroring what `/resume` shows. Returns null if neither is present.
+export function pickSessionName(text: string): string | null {
+ let custom: string | null = null
+ let ai: string | null = null
+ for (const raw of text.split('\n')) {
+ if (!raw.includes('title')) continue
+ try {
+ const o = JSON.parse(raw) as { type?: string; customTitle?: unknown; aiTitle?: unknown }
+ if (o.type === 'custom-title' && typeof o.customTitle === 'string') custom = o.customTitle
+ else if (o.type === 'ai-title' && typeof o.aiTitle === 'string') ai = o.aiTitle
+ } catch {
+ /* skip non-JSON line */
+ }
+ }
+ const name = (custom ?? ai)?.trim()
+ return name ? name : null
+}
+
+// The current display name of a Claude session, read from its transcript. This is the name shown
+// in `/resume` — the authoritative source, since `/rename` does NOT push to the OSC terminal
+// title. Resolved by sessionId when known, else by cwd. Returns null if none found.
+const TITLE_TAIL_BYTES = 128 * 1024
+export async function readSessionName(sessionId: string, cwd: string): Promise<string | null> {
+ let p = sessionId ? await resolveTranscriptPath(sessionId) : undefined
+ if (!p && cwd) p = await transcriptPathForCwd(cwd)
+ if (!p) return null
+ const tail = await readSmallTail(p, TITLE_TAIL_BYTES)
+ if (!tail) return null
+ return pickSessionName(tail)
+}
+
// Durable resolver by working directory: Claude stores a project's transcripts under
// ~/.claude/projects/<cwd with every '/' and '.' replaced by '-'>/. We pick the most
// recently modified .jsonl there — the node's active session. Unlike the sessionId path
diff --git a/src/preload/index.ts b/src/preload/index.ts
index aba778025..4ea451e45 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -53,6 +53,8 @@ const api: NodeTerminalApi = {
capture: (persistKey, full) => ipcRenderer.invoke(IPC.ptyCapture, persistKey, full),
readScrollback: (persistKey) => ipcRenderer.invoke(IPC.ptyReadScrollback, persistKey),
sendText: (persistKey, text) => ipcRenderer.invoke(IPC.ptySendText, persistKey, text),
+ readSessionName: (sessionId, cwd) =>
+ ipcRenderer.invoke(IPC.ptyReadSessionName, sessionId, cwd),
onData: (sessionId, listener) => {
const channel = IPC.ptyData(sessionId)
const handler = (_e: unknown, data: string) => listener(data)
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 63adf7661..71477b264 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -81,6 +81,7 @@ import {
agentConfig,
hasHooks,
canBranch,
+ canRename,
canTransferFrom,
canContextLink,
AGENT_CONFIG,
@@ -1919,12 +1920,27 @@ export function Canvas() {
const renameSession = useCallback(
(projectId: string, id: string, title: string) => {
if (projectId === activeProjectId) {
- setNodes((ns) => ns.map((n) => (n.id === id ? { ...n, data: { ...n.data, title } } : n)))
+ // An explicit rename takes ownership of the name → stop auto-tracking the session.
+ setNodes((ns) =>
+ ns.map((n) => (n.id === id ? { ...n, data: { ...n.data, title, titleAuto: false } } : n))
+ )
markDirty()
} else {
useProjects.getState().renameNode(projectId, id, title)
void writeDisk()
}
+ // Mirror the new name into a rename-capable agent's live session (tmux send-keys works
+ // whether or not the node is currently mounted). Same one-way push as the node header's ✦.
+ const liveAgent = nodesRef.current.find((n) => n.id === id)?.data.agentId as AgentId | undefined
+ const storedAgent = useProjects
+ .getState()
+ .projects.find((p) => p.id === projectId)
+ ?.nodes.find((n) => n.id === id)?.agentId
+ const agentId = liveAgent ?? storedAgent
+ const name = title.trim()
+ if (agentId && canRename(agentId) && name) {
+ void window.nodeTerminal.pty.sendText(id, `/rename ${name}`)
+ }
},
[activeProjectId, setNodes, markDirty, writeDisk]
)
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 5a46674f0..145d94271 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -30,7 +30,7 @@ import { useAgentNodes } from '../state/agentNodes'
import { useProjects } from '../state/projects'
import { useSshConn } from '../state/sshConn'
import { COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'
-import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, resumeCommand, agentConfig, type AgentId } from '@shared/agents/config'
+import { hasHooks, canRecur, canContextLink, hasUsage, canChat, canResume, canRename, resumeCommand, agentConfig, type AgentId } from '@shared/agents/config'
import { buildSshArgs, type SshConnection } from '@shared/ssh'
/** Backslash-escape shell-special characters, like a native terminal does on file drop. */
@@ -134,6 +134,16 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
const [mdHtml, setMdHtml] = useState('')
const [editingTitle, setEditingTitle] = useState(false)
const hoveredRef = useRef(false)
+ // Live mirrors for the once-mounted onTitleChange listener (its `[]`-deps closure can't see
+ // fresh props/state): whether the title still auto-tracks the session, whether the rename box
+ // is open (don't clobber mid-edit), and the current title (skip no-op updates).
+ const titleAutoRef = useRef(data.titleAuto !== false)
+ const editingTitleRef = useRef(false)
+ const titleRef = useRef(data.title as string)
+ // Rename-box bookkeeping: the value when editing began (for Escape-revert) and a one-shot
+ // flag so the blur that follows Enter/Escape doesn't commit a second time.
+ const titleEditStartRef = useRef('')
+ const skipBlurRef = useRef(false)
const mdMode = !!data.mdMode
const collapsed = !!data.collapsed
const tags = (data.tags as string[]) ?? []
@@ -146,7 +156,13 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
const showLink = !!agentId && canContextLink(agentId) // context-link handles
const showUsage = !!agentId && hasUsage(agentId) // per-node context-window meter
const showChat = !!agentId && canChat(agentId) // Cmd+M opens a chat panel instead of markdown
+ const canRenameNode = !!agentId && canRename(agentId) // title ⇄ session-name two-way sync
const agentLabel = (agentId ? agentConfig(agentId) : undefined)?.label ?? 'Agent'
+
+ // Keep the listener's mirrors current every render.
+ titleAutoRef.current = data.titleAuto !== false
+ editingTitleRef.current = editingTitle
+ titleRef.current = data.title as string
// "Move into worktree" affordance: shown only when this terminal is a child of a group that
// is bound to a worktree AND its current cwd differs from that worktree path (i.e. it's still
// running in the old folder). Reads the parent group from React Flow state (single source of
@@ -293,6 +309,8 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
term.onTitleChange((t) => {
const title = t.trim()
// Ignore path/prompt-like titles (e.g. "user@host: ~/dir") which aren't session names.
+ // This feeds the `session` chip only; the node title is synced from the transcript's
+ // authoritative session name instead (see the readSessionName effect below).
if (title && !/[/:~]/.test(title)) useAgentStatus.getState().setSession(id, title)
}).dispose
)
@@ -536,11 +554,32 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
useAgentStatus.getState().setActive(id, true)
}
+ // 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}`)
+ }
+
+ // The user took over the name (manual rename or ✦ AI-name): stop auto-tracking the session
+ // and, for rename-capable agents, push the chosen name back to the session.
+ const applyManualTitle = (raw: string) => {
+ const name = raw.trim()
+ updateNodeData(id, { title: name, titleAuto: false })
+ pushSessionRename(name)
+ }
+
+ // Close the rename box, committing only if the value actually changed (so just clicking in
+ // and out doesn't take ownership or fire a spurious /rename).
+ const commitTitleEdit = (value: string) => {
+ setEditingTitle(false)
+ if (value.trim() !== titleEditStartRef.current.trim()) applyManualTitle(value)
+ }
+
const nameWithAi = async () => {
setNaming(true)
const r = await window.nodeTerminal.pty.generateName(id, (data.cwd as string) ?? '')
setNaming(false)
- if (r.ok) updateNodeData(id, { title: r.message })
+ if (r.ok) applyManualTitle(r.message)
}
// Selecting a node clears its unread badge.
@@ -548,6 +587,38 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
if (selected) useAgentStatus.getState().clearUnread(id)
}, [selected, id])
+ // Keep the node title in sync with the agent session's display name — the name shown in
+ // `/resume`, read from the transcript (`/rename` name, else auto name). This is the authoritative
+ // source: `/rename` doesn't update the OSC terminal title, so reading the transcript is the only
+ // way the name shows up after a resume. Polls only while the title still auto-tracks the session
+ // (titleAuto) and stops once the user renames by hand. Claude-only via canRenameNode.
+ useEffect(() => {
+ if (!canRenameNode || data.titleAuto === false) return
+ const sid = status?.sessionId ?? ''
+ const cwd = (data.cwd as string) ?? ''
+ if (!sid && !cwd) return
+ let cancelled = false
+ const sync = async () => {
+ if (!titleAutoRef.current || editingTitleRef.current) return
+ const name = await window.nodeTerminal.pty.readSessionName(sid, cwd)
+ if (
+ !cancelled &&
+ name &&
+ titleAutoRef.current &&
+ !editingTitleRef.current &&
+ name !== titleRef.current
+ ) {
+ updateNodeData(id, { title: name })
+ }
+ }
+ void sync()
+ const timer = setInterval(() => void sync(), 4000)
+ return () => {
+ cancelled = true
+ clearInterval(timer)
+ }
+ }, [id, canRenameNode, status?.sessionId, data.cwd, data.titleAuto, updateNodeData])
+
// Cmd/Ctrl+M toggles markdown view of this terminal's output (only when hovered).
useEffect(() => {
return window.nodeTerminal.onMarkdownToggle(() => {
@@ -667,16 +738,35 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN
spellCheck={false}
autoFocus
onChange={(e) => updateNodeData(id, { title: e.target.value })}
- onBlur={() => setEditingTitle(false)}
+ // Enter commits, Escape reverts to the value editing started with. The blur that
+ // follows either keypress is skipped (skipBlurRef) so we don't commit twice; a plain
+ // focus-loss blur still commits.
+ onBlur={(e) => {
+ if (skipBlurRef.current) {
+ skipBlurRef.current = false
+ return
+ }
+ commitTitleEdit(e.currentTarget.value)
+ }}
onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === 'Escape') setEditingTitle(false)
+ if (e.key === 'Enter') {
+ skipBlurRef.current = true
+ commitTitleEdit(e.currentTarget.value)
+ } else if (e.key === 'Escape') {
+ skipBlurRef.current = true
+ updateNodeData(id, { title: titleEditStartRef.current })
+ setEditingTitle(false)
+ }
}}
/>
) : (
<span
className="term-node__title-text nodrag"
title="Click to rename"
- onClick={() => setEditingTitle(true)}
+ onClick={() => {
+ titleEditStartRef.current = data.title as string
+ setEditingTitle(true)
+ }}
>
{data.title || 'Untitled'}
</span>
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 6686fd7fe..c8fe0f31b 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -118,7 +118,8 @@ export const useProjects = create<ProjectsState>((set, get) => ({
renameNode(projectId, nodeId, title) {
set((s) => ({
projects: mapProjectNodes(s.projects, projectId, (nodes) =>
- nodes.map((n) => (n.id === nodeId ? { ...n, title } : n))
+ // An explicit rename means the user owns the name now: stop auto-tracking the session.
+ nodes.map((n) => (n.id === nodeId ? { ...n, title, titleAuto: false } : n))
)
}))
},
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 7905d9e65..345b37acd 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -28,6 +28,12 @@ export const COLLAPSED_HEIGHT = 40
/** User data carried in the React Flow node's data field. */
export interface NodeData {
title: string
+ /**
+ * Agent nodes only: while true (the default for agent nodes), the title auto-tracks the
+ * agent's session name (see TerminalNode's onTitleChange). Flipped to false the moment the
+ * user renames the node by hand — then the user's name is pushed back via `/rename`.
+ */
+ titleAuto?: boolean
color: string
group: string | null
tags?: string[]
@@ -246,6 +252,8 @@ export function createAgentNode(
style: { width: TERMINAL_SIZE.width, height: TERMINAL_SIZE.height },
data: {
title: label,
+ // Adopt the agent's own session name into the title until the user renames it by hand.
+ titleAuto: true,
color,
group: null,
tags: [],
@@ -605,6 +613,9 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
...(n.parentId ? { parentId: n.parentId, extent: 'parent' as const } : {}),
data: {
title: n.title,
+ // Default true for older agent nodes saved before titleAuto existed, so they start
+ // tracking the session name; non-agent nodes ignore it.
+ titleAuto: n.titleAuto ?? true,
color: n.color,
group: n.group,
tags: n.tags,
@@ -660,6 +671,7 @@ export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {
: n.measured?.height ?? n.height ?? sizeFor(kind).height
},
title: n.data.title,
+ titleAuto: n.data.titleAuto,
color: n.data.color,
group: n.data.group,
tags: n.data.tags,
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index 2a6067a5c..1cf13446d 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -55,6 +55,9 @@ export const USAGE_CAPABLE = ['claude'] as const
export const CHAT_CAPABLE = ['claude'] as const
// Agents whose native transcript we can read + render for cross-agent transfer.
export const TRANSFER_SOURCE_CAPABLE = ['claude', 'codex', 'gemini'] as const
+// Agents that support naming the session in two directions: they emit a session title we adopt
+// into the node title, and accept `/rename <name>` to push a renamed node title back. Claude-only.
+export const RENAME_CAPABLE = ['claude'] as const
const includes = (list: readonly string[], id: AgentId): boolean => list.includes(id)
@@ -67,6 +70,7 @@ export const canContextLink = (id: AgentId): boolean => includes(CONTEXT_LINK_CA
export const hasUsage = (id: AgentId): boolean => includes(USAGE_CAPABLE, id)
export const canChat = (id: AgentId): boolean => includes(CHAT_CAPABLE, id)
export const canTransferFrom = (id: AgentId): boolean => includes(TRANSFER_SOURCE_CAPABLE, id)
+export const canRename = (id: AgentId): boolean => includes(RENAME_CAPABLE, id)
// Returns the builtin config for an id, or undefined for custom/unknown agents.
export const agentConfig = (id: AgentId): AgentConfig | undefined =>
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index c0655a4f3..4a85d830e 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -12,8 +12,10 @@ export const IPC = {
ptyCapture: 'pty:capture',
ptyReadScrollback: 'pty:read-scrollback',
ptySendText: 'pty:send-text',
+ ptyReadSessionName: 'pty:read-session-name',
claudeReadTranscript: 'claude:read-transcript',
chatReadTranscript: 'chat:read-transcript',
+ transcriptSearch: 'transcript:search',
appToggleMarkdown: 'app:toggle-markdown',
appCloseNode: 'app:close-node',
appCloseWindow: 'app:close-window',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index d8b6c5751..f750e1f77 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -47,6 +47,12 @@ export interface CanvasNodeState {
position: { x: number; y: number }
size: { width: number; height: number }
title: string
+ /**
+ * Agent nodes only: while true (the default), the node title auto-tracks the agent's own
+ * session name. Set false once the user renames the node by hand, so we stop overwriting it
+ * and instead push the user's name back to the agent via `/rename`. Persisted.
+ */
+ titleAuto?: boolean
color: string
group: string | null
/** Labels for organizing/filtering terminals. */
@@ -180,6 +186,9 @@ export interface PtyApi {
readScrollback(persistKey: string): Promise<string>
/** Send literal text + Enter into a session (e.g. a slash command). Returns false if unavailable. */
sendText(persistKey: string, text: string): Promise<boolean>
+ /** The agent session's display name (`/rename` name, else auto name) read from its transcript;
+ * null if none. Used to keep a node title in sync with the `/resume` name (e.g. after resume). */
+ readSessionName(sessionId: string, cwd: string): Promise<string | null>
/** Listens for PTY output. Returns an unsubscribe function. */
onData(sessionId: string, listener: (data: string) => void): () => void
/** Fires when the PTY process exits. Returns an unsubscribe function. */
@@ -645,6 +654,21 @@ export interface ChatApi {
): Promise<ChatMessage[]>
}
+/** One ranked search hit across all on-disk Claude session transcripts. */
+export interface TranscriptHit {
+ sessionId: string
+ title: string
+ snippet: string
+ cwd: string
+ projectLabel: string
+ mtime: number
+}
+
+export interface TranscriptsApi {
+ /** Search all on-disk Claude session transcripts by content. */
+ search(query: string): Promise<TranscriptHit[]>
+}
+
export interface ClaudeApi {
/**
* Reads a Claude session's full transcript as flat searchable lines ([] if unavailable).
@@ -801,6 +825,7 @@ export interface NodeTerminalApi {
context: ContextApi
claude: ClaudeApi
chat: ChatApi
+ transcripts: TranscriptsApi
remoteHost: RemoteHostApi
remoteClient: RemoteClientApi
handoff: HandoffApi