Skip to content

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

fix(chat): keep the ⌘M draft across project switches, reloads and restarts

Paul Robertson50e5f3c23fbc
diff --git a/CLAUDE.md b/CLAUDE.md
index a2bfbe969..4c77023a5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -4594,6 +4594,13 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
terminal equivalent. Surfaces: Desktop + Server Edition identical (dictation and uploads already
bridge — `files.saveUpload`, `speech.*`); SSH nodes upload to the host; kanban card modal shares
ChatPanel and wires both props; relay tabs keep the panel's existing refusal; mobile N/A.
+ **The draft is not component state** (`state/chatDraft.ts`): ChatPanel unmounts on every project
+ switch, and a `useState` draft was lost with it. It is keyed by node id (the canvas node and the
+ card modal share one draft) and persisted to localStorage (`nodeterm.chatDrafts`, machine-local),
+ so it survives a reload and a restart as the TUI's own input box does in tmux. Writes are
+ debounced, flushed on pagehide, and merge only this window's changes into the stored map (two
+ Server Edition tabs); bounded by age (30 days), count (50) and size (32,000 chars stays in memory
+ only). Pruned by age, not node existence: a closed project still holds its nodes.
Fix-round rules (same day): the composer is its OWN component (`nodes/ChatComposer.tsx`) so the
thread and the composer restyle independently. A label click is an explicit "go to the
terminal", so the flip FOCUSES the xterm whatever its entry state was
diff --git a/src/renderer/nodes/ChatPanel.composer.test.tsx b/src/renderer/nodes/ChatPanel.composer.test.tsx
index 9432c11cd..2b3df1294 100644
--- a/src/renderer/nodes/ChatPanel.composer.test.tsx
+++ b/src/renderer/nodes/ChatPanel.composer.test.tsx
@@ -3,6 +3,7 @@ import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useAgentStatus } from '../state/agentStatus'
+import { useChatDraft } from '../state/chatDraft'
import { useContextWindow } from '../state/contextWindow'
import { deliverToComposer } from '../lib/chatComposerDictation'
import { COMPOSER_EFFORT_MIN_WIDTH, COMPOSER_MODEL_MIN_WIDTH } from '../lib/chatComposer'
@@ -90,6 +91,8 @@ const flush = () => act(async () => {
})
beforeEach(() => {
+ // Drafts outlive a panel (state/chatDraft.ts); one test's text must not reach the next.
+ useChatDraft.setState({ drafts: {} })
sendText.mockReset()
sendText.mockResolvedValue(true)
sendChatPrompt.mockClear()
diff --git a/src/renderer/nodes/ChatPanel.draft.test.tsx b/src/renderer/nodes/ChatPanel.draft.test.tsx
new file mode 100644
index 000000000..6eacf929f
--- /dev/null
+++ b/src/renderer/nodes/ChatPanel.draft.test.tsx
@@ -0,0 +1,107 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useAgentStatus } from '../state/agentStatus'
+import { useChatDraft } from '../state/chatDraft'
+
+/**
+ * The ⌘M draft outlives the panel. A project switch unmounts every node's panel; the draft used to
+ * be component state and went with it.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+const { sendChatPrompt, session } = vi.hoisted(() => {
+ const sendChatPrompt = vi.fn(async (_id: string, _text: string, _agent: string) => true as const)
+ const session = {
+ api: {
+ chat: { readTranscript: async () => ({ messages: [], found: true }) },
+ pty: { sendChatPrompt, paneOwner: async () => null }
+ }
+ }
+ return { sendChatPrompt, session }
+})
+vi.mock('../session/session', () => ({ useSession: () => session }))
+
+import { ChatPanel } from './ChatPanel'
+
+const NODE = 'n-draft'
+let host: HTMLDivElement
+let root: Root
+
+async function mount(nodeId = NODE): Promise<HTMLTextAreaElement> {
+ await act(async () => {
+ root.render(<ChatPanel nodeId={nodeId} sessionId="s1" agentId="claude" />)
+ })
+ return host.querySelector('textarea') as HTMLTextAreaElement
+}
+
+async function unmount(): Promise<void> {
+ await act(async () => root.unmount())
+ root = createRoot(host)
+}
+
+async function type(ta: HTMLTextAreaElement, text: string): Promise<void> {
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!
+ await act(async () => {
+ setter.call(ta, text)
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+}
+
+beforeEach(() => {
+ useChatDraft.setState({ drafts: {} })
+ sendChatPrompt.mockClear()
+ useAgentStatus.setState((s) => ({
+ byId: { ...s.byId, [NODE]: { ...(s.byId[NODE] ?? {}), state: 'done' } as (typeof s.byId)[string] }
+ }))
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+ useAgentStatus.setState((s) => {
+ const byId = { ...s.byId }
+ delete byId[NODE]
+ return { byId }
+ })
+})
+
+describe('ChatPanel draft', () => {
+ it('keeps a draft across an unmount, as on a project switch', async () => {
+ await type(await mount(), 'half a thought')
+ await unmount()
+
+ const ta = await mount()
+
+ expect(ta.value).toBe('half a thought')
+ })
+
+ it("keeps one node's draft out of another node's composer", async () => {
+ await type(await mount(), 'for n-draft only')
+ await unmount()
+
+ const ta = await mount('n-other')
+
+ expect(ta.value).toBe('')
+ })
+
+ it('clears the kept draft once it is sent', async () => {
+ const first = await mount()
+ await type(first, 'send me')
+ await act(async () => {
+ first.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }))
+ })
+ await unmount()
+
+ const ta = await mount()
+
+ expect(sendChatPrompt).toHaveBeenCalledWith(NODE, 'send me', 'claude')
+ expect(ta.value).toBe('')
+ expect(useChatDraft.getState().drafts).toEqual({})
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.escInterrupt.test.tsx b/src/renderer/nodes/ChatPanel.escInterrupt.test.tsx
index 17ce78a47..57b1b4e72 100644
--- a/src/renderer/nodes/ChatPanel.escInterrupt.test.tsx
+++ b/src/renderer/nodes/ChatPanel.escInterrupt.test.tsx
@@ -3,6 +3,7 @@ import { act } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useAgentStatus } from '../state/agentStatus'
+import { useChatDraft } from '../state/chatDraft'
import type { ChatInterruptResult } from '@shared/text-delivery'
/**
@@ -59,6 +60,8 @@ const press = (ta: HTMLTextAreaElement, key: string): void => {
}
beforeEach(() => {
+ // Drafts outlive a panel (state/chatDraft.ts); one test's text must not reach the next.
+ useChatDraft.setState({ drafts: {} })
interruptChat.mockClear()
sendChatPrompt.mockClear()
host = document.createElement('div')
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 699200704..99ab2bd8c 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -1,8 +1,9 @@
import { TEXT_NOT_SUBMITTED, isChatPromptBlocked } from '@shared/text-delivery'
import { claudeScreenBlocksInput, type ChatScreenRead } from '@shared/agents/claude-screen'
-import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'
+import { Fragment, memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type SetStateAction } from 'react'
import { renderMarkdown } from '../lib/markdown'
import { inferInterruptAfterSettle, useAgentStatus } from '../state/agentStatus'
+import { useChatDraft } from '../state/chatDraft'
import { useSession } from '../session/session'
import { chipFor } from '../lib/keybindingOverrides'
import {
@@ -266,7 +267,13 @@ export function ChatPanel({
// Mirror for `load`, which must not depend on it (its identity drives the initial-load effect).
const olderStateRef = useRef(olderState)
olderStateRef.current = olderState
- const [input, setInput] = useState('')
+ // The draft lives in a store keyed by node (state/chatDraft.ts): this panel unmounts on every
+ // project switch, and a draft in component state was lost with it.
+ const input = useChatDraft((s) => s.drafts[nodeId] ?? '')
+ const setInput = useCallback(
+ (next: SetStateAction<string>) => useChatDraft.getState().setDraft(nodeId, next),
+ [nodeId]
+ )
const [readonly, setReadonly] = useState(false)
// The last prompt this panel sent, for taking it back out of the agent's input box after an Esc.
const lastSentRef = useRef<string | null>(null)
diff --git a/src/renderer/state/chatDraft.test.ts b/src/renderer/state/chatDraft.test.ts
new file mode 100644
index 000000000..e9bd6b038
--- /dev/null
+++ b/src/renderer/state/chatDraft.test.ts
@@ -0,0 +1,162 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import {
+ CHAT_DRAFTS_KEY,
+ DRAFTS_MAX,
+ DRAFT_MAX_AGE_MS,
+ DRAFT_SAVE_DELAY_MS,
+ DRAFT_STORE_MAX_CHARS,
+ flushChatDrafts,
+ mergeStoredDrafts,
+ parseStoredDrafts,
+ useChatDraft
+} from './chatDraft'
+
+const NOW = 1_800_000_000_000
+const drafts = () => useChatDraft.getState().drafts
+const setDraft = (nodeId: string, next: string | ((cur: string) => string)) =>
+ useChatDraft.getState().setDraft(nodeId, next)
+const stored = () => JSON.parse(localStorage.getItem(CHAT_DRAFTS_KEY) ?? 'null')
+const storedFile = (drafts: Record<string, unknown>) => JSON.stringify({ v: 1, drafts })
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(NOW)
+ flushChatDrafts()
+ localStorage.removeItem(CHAT_DRAFTS_KEY)
+ useChatDraft.setState({ drafts: {} })
+})
+afterEach(() => {
+ flushChatDrafts()
+ vi.useRealTimers()
+})
+
+describe('useChatDraft in memory', () => {
+ it('keeps a draft per node', () => {
+ setDraft('a', 'one')
+ setDraft('b', 'two')
+
+ expect(drafts()).toEqual({ a: 'one', b: 'two' })
+ })
+
+ it('hands a function the current draft', () => {
+ setDraft('a', 'one')
+
+ setDraft('a', (cur) => `${cur} more`)
+
+ expect(drafts().a).toBe('one more')
+ })
+
+ it('drops the entry when the draft is emptied', () => {
+ setDraft('a', 'one')
+
+ setDraft('a', '')
+
+ expect(drafts()).toEqual({})
+ })
+
+ it('leaves the map alone when nothing changes', () => {
+ setDraft('a', 'one')
+ const before = drafts()
+
+ setDraft('a', 'one')
+
+ expect(drafts()).toBe(before)
+ })
+})
+
+describe('useChatDraft storage', () => {
+ it('writes half a second after the last change, not on every keystroke', () => {
+ setDraft('a', 'o')
+ setDraft('a', 'on')
+ vi.advanceTimersByTime(DRAFT_SAVE_DELAY_MS - 1)
+ const early = localStorage.getItem(CHAT_DRAFTS_KEY)
+
+ vi.advanceTimersByTime(1)
+
+ expect(early).toBeNull()
+ expect(stored()).toEqual({ v: 1, drafts: { a: { text: 'on', at: NOW } } })
+ })
+
+ it('removes a stored draft once it is emptied', () => {
+ setDraft('a', 'one')
+ flushChatDrafts()
+
+ setDraft('a', '')
+ flushChatDrafts()
+
+ expect(stored()).toEqual({ v: 1, drafts: {} })
+ })
+
+ it("keeps another window's drafts when it writes", () => {
+ localStorage.setItem(CHAT_DRAFTS_KEY, storedFile({ other: { text: 'from tab B', at: NOW } }))
+
+ setDraft('a', 'from tab A')
+ flushChatDrafts()
+
+ expect(stored().drafts).toEqual({
+ other: { text: 'from tab B', at: NOW },
+ a: { text: 'from tab A', at: NOW }
+ })
+ })
+
+ it('keeps a draft across a restart', async () => {
+ setDraft('a', 'half a thought')
+ flushChatDrafts()
+ vi.resetModules()
+
+ const fresh = await import('./chatDraft')
+
+ expect(fresh.useChatDraft.getState().drafts).toEqual({ a: 'half a thought' })
+ })
+})
+
+describe('parseStoredDrafts', () => {
+ it('reads well-formed entries', () => {
+ expect(parseStoredDrafts(storedFile({ a: { text: 'x', at: NOW } }), NOW)).toEqual({ a: { text: 'x', at: NOW } })
+ })
+
+ it('reads anything that is not a version-1 map as empty', () => {
+ for (const raw of [null, '', 'not json', '[]', '{"v":2,"drafts":{}}', '{"v":1,"drafts":[]}']) {
+ expect(parseStoredDrafts(raw, NOW)).toEqual({})
+ }
+ })
+
+ it('drops malformed, empty, oversized, expired and future entries', () => {
+ const raw = storedFile({
+ 'bad id with spaces': { text: 'x', at: NOW },
+ notAnObject: 'x',
+ noText: { at: NOW },
+ empty: { text: '', at: NOW },
+ huge: { text: 'x'.repeat(DRAFT_STORE_MAX_CHARS + 1), at: NOW },
+ old: { text: 'x', at: NOW - DRAFT_MAX_AGE_MS - 1 },
+ future: { text: 'x', at: NOW + 10 * 60_000 },
+ good: { text: 'x', at: NOW }
+ })
+
+ expect(Object.keys(parseStoredDrafts(raw, NOW))).toEqual(['good'])
+ })
+
+ it('keeps only the newest drafts', () => {
+ const many = Object.fromEntries(
+ Array.from({ length: DRAFTS_MAX + 5 }, (_, i) => [`n${i}`, { text: 'x', at: NOW - i }])
+ )
+
+ const kept = parseStoredDrafts(storedFile(many), NOW)
+
+ expect(Object.keys(kept)).toHaveLength(DRAFTS_MAX)
+ expect(kept[`n${DRAFTS_MAX}`]).toBeUndefined()
+ expect(kept.n0).toBeDefined()
+ })
+})
+
+describe('mergeStoredDrafts', () => {
+ it('does not store a draft over the size cap, and drops its older stored copy', () => {
+ const merged = mergeStoredDrafts(
+ { a: { text: 'short', at: NOW - 1 } },
+ new Map([['a', { text: 'x'.repeat(DRAFT_STORE_MAX_CHARS + 1), at: NOW }]])
+ )
+
+ expect(merged).toEqual({})
+ })
+})
diff --git a/src/renderer/state/chatDraft.ts b/src/renderer/state/chatDraft.ts
new file mode 100644
index 000000000..27c2ec8fc
--- /dev/null
+++ b/src/renderer/state/chatDraft.ts
@@ -0,0 +1,135 @@
+import { create } from 'zustand'
+import type { SetStateAction } from 'react'
+import { readLocal, writeLocal } from '../lib/localStore'
+
+/**
+ * The ⌘M composer's draft per node, kept OUTSIDE ChatPanel. The panel unmounts whenever its node
+ * does — a project switch, a park expiry, a project reopened — and a draft in component state went
+ * with it. Keyed by node id, so the canvas node's composer and the kanban card modal's composer for
+ * the same session show one draft. An empty draft removes its entry.
+ *
+ * PERSISTED in localStorage (`nodeterm.chatDrafts`), so a draft also survives a reload and an app
+ * restart, as the agent's own TUI input box does by living in tmux. Machine-local: never
+ * settings.json, never the git-shared project file. In the Server Edition it is per browser profile.
+ * - Written half a second after the last change, and flushed when the page hides or unloads.
+ * - Each write re-reads the stored map and changes only the drafts THIS window changed, so two
+ * browser tabs on one Server Edition do not erase each other's drafts.
+ * - Bounded: entries older than 30 days are dropped, at most 50 drafts are kept (newest first), and a
+ * draft longer than 32,000 characters stays in memory but is not stored. Pruned by age and count,
+ * not by "does the node still exist": a closed project keeps its nodes, so a node missing from the
+ * open canvases is not evidence that its draft is dead.
+ * - The stored file is hand-editable input: anything that is not a well-formed entry is dropped.
+ */
+
+export const CHAT_DRAFTS_KEY = 'nodeterm.chatDrafts'
+export const DRAFT_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000
+export const DRAFTS_MAX = 50
+export const DRAFT_STORE_MAX_CHARS = 32_000
+export const DRAFT_SAVE_DELAY_MS = 500
+
+interface StoredDraft {
+ text: string
+ at: number
+}
+type StoredDrafts = Record<string, StoredDraft>
+
+const NODE_ID = /^[A-Za-z0-9._:-]{1,128}$/
+
+/** The stored map, with every malformed, empty, oversized or expired entry dropped. */
+export function parseStoredDrafts(raw: string | null, now: number): StoredDrafts {
+ if (raw === null || raw === '') return {}
+ let parsed: unknown
+ try {
+ parsed = JSON.parse(raw)
+ } catch {
+ return {}
+ }
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return {}
+ const drafts = (parsed as { v?: unknown; drafts?: unknown }).drafts
+ if ((parsed as { v?: unknown }).v !== 1 || drafts === null || typeof drafts !== 'object' || Array.isArray(drafts)) {
+ return {}
+ }
+ const out: StoredDrafts = {}
+ for (const [nodeId, entry] of Object.entries(drafts as Record<string, unknown>)) {
+ if (!NODE_ID.test(nodeId) || entry === null || typeof entry !== 'object') continue
+ const { text, at } = entry as { text?: unknown; at?: unknown }
+ if (typeof text !== 'string' || text === '' || text.length > DRAFT_STORE_MAX_CHARS) continue
+ if (typeof at !== 'number' || !Number.isFinite(at) || at > now + 60_000 || now - at > DRAFT_MAX_AGE_MS) continue
+ out[nodeId] = { text, at }
+ }
+ return keepNewest(out)
+}
+
+/** At most DRAFTS_MAX entries, the most recently changed. */
+function keepNewest(drafts: StoredDrafts): StoredDrafts {
+ const entries = Object.entries(drafts)
+ if (entries.length <= DRAFTS_MAX) return drafts
+ return Object.fromEntries(entries.sort((a, b) => b[1].at - a[1].at).slice(0, DRAFTS_MAX))
+}
+
+/** Applies this window's changes (`null` = removed) to the stored map. */
+export function mergeStoredDrafts(
+ stored: StoredDrafts,
+ changes: ReadonlyMap<string, StoredDraft | null>
+): StoredDrafts {
+ const next = { ...stored }
+ for (const [nodeId, entry] of changes) {
+ if (entry === null || entry.text.length > DRAFT_STORE_MAX_CHARS) delete next[nodeId]
+ else next[nodeId] = entry
+ }
+ return keepNewest(next)
+}
+
+/** Drafts this window changed since its last write: node id → the new draft, or null if removed. */
+const pending = new Map<string, StoredDraft | null>()
+let saveTimer: ReturnType<typeof setTimeout> | null = null
+
+/** Writes this window's pending changes now. */
+export function flushChatDrafts(): void {
+ if (saveTimer !== null) {
+ clearTimeout(saveTimer)
+ saveTimer = null
+ }
+ if (pending.size === 0) return
+ const stored = parseStoredDrafts(readLocal(CHAT_DRAFTS_KEY), Date.now())
+ const drafts = mergeStoredDrafts(stored, pending)
+ pending.clear()
+ writeLocal(CHAT_DRAFTS_KEY, JSON.stringify({ v: 1, drafts }))
+}
+
+function scheduleSave(): void {
+ if (saveTimer !== null) clearTimeout(saveTimer)
+ saveTimer = setTimeout(flushChatDrafts, DRAFT_SAVE_DELAY_MS)
+}
+
+function loadDrafts(): Record<string, string> {
+ const stored = parseStoredDrafts(readLocal(CHAT_DRAFTS_KEY), Date.now())
+ return Object.fromEntries(Object.entries(stored).map(([nodeId, d]) => [nodeId, d.text]))
+}
+
+interface ChatDraftState {
+ drafts: Record<string, string>
+ /** Sets one node's draft; a function gets the current draft, as React's state setter does. */
+ setDraft(nodeId: string, next: SetStateAction<string>): void
+}
+
+export const useChatDraft = create<ChatDraftState>((set) => ({
+ drafts: loadDrafts(),
+ setDraft: (nodeId, next) =>
+ set((s) => {
+ const cur = s.drafts[nodeId] ?? ''
+ const value = typeof next === 'function' ? next(cur) : next
+ if (value === cur) return s
+ const drafts = { ...s.drafts }
+ if (value === '') delete drafts[nodeId]
+ else drafts[nodeId] = value
+ pending.set(nodeId, value === '' ? null : { text: value, at: Date.now() })
+ scheduleSave()
+ return { drafts }
+ })
+}))
+
+if (typeof window !== 'undefined') {
+ window.addEventListener('pagehide', flushChatDrafts)
+ window.addEventListener('beforeunload', flushChatDrafts)
+}