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): ⌘M chat panel UX — Shift+Enter, scroll-follow, thinking, stale guard, reload, agent label

review037120ee2503
diff --git a/CLAUDE.md b/CLAUDE.md
index 28415b6ed..f695e98eb 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2337,8 +2337,11 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
`renderer/lib/chatSendGate.ts`) — never in `waiting`/`blocked`, not just never in `working`:
PermissionRequest and AskUserQuestion both normalize to `waiting`, the pane then holds a TUI
select dialog this view does not show, and `sendText`'s Enter would ANSWER it ("Yes" is the
- default highlight). The state is re-read from the store at send time, not only at render. Same
- trap as the in-place restart's `/exit`.
+ default highlight). It also refuses a **hibernated / paused / dropped** node, whose `state` still
+ reads `done` while a SHELL owns the pane — the message would run as a shell command; those flags
+ rank above the state (`chatSendRefusal`). Everything is re-read from the store at send time, not
+ only at render. Same trap as the in-place restart's `/exit`. The ↻ in the panel bar is the only
+ reload for a session whose hooks never report `working`.
- **Subagent visualization** (agents in `SUBAGENT_CAPABLE`) — `subagent-start`/`subagent-end`
normalized events (from Claude's `PreToolUse`/`PostToolUse` on tool `Agent`/`Task`, correlated
by `tool_use_id`) drive a transient `state/agentNodes.ts` store. Claude launches subagents
diff --git a/src/renderer/lib/chatPanel.test.ts b/src/renderer/lib/chatPanel.test.ts
new file mode 100644
index 000000000..3e9d1e83a
--- /dev/null
+++ b/src/renderer/lib/chatPanel.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest'
+import { CHAT_FOLLOW_THRESHOLD_PX, chatAgentLabel, chatKeyAction, isNearBottom, shouldFollowOnLoad } from './chatPanel'
+
+describe('chatKeyAction', () => {
+ it('Enter sends', () => {
+ expect(chatKeyAction({ key: 'Enter', shiftKey: false, isComposing: false })).toBe('send')
+ })
+ it('Shift+Enter inserts a newline (the textarea default), never sends', () => {
+ expect(chatKeyAction({ key: 'Enter', shiftKey: true, isComposing: false })).toBe('newline')
+ })
+ it('an Enter that commits an IME composition is not a send', () => {
+ expect(chatKeyAction({ key: 'Enter', shiftKey: false, isComposing: true })).toBe('none')
+ expect(chatKeyAction({ key: 'Enter', shiftKey: true, isComposing: true })).toBe('none')
+ })
+ it('any other key is left alone', () => {
+ expect(chatKeyAction({ key: 'a', shiftKey: false, isComposing: false })).toBe('none')
+ })
+})
+
+describe('isNearBottom', () => {
+ it('is true at the bottom and within the threshold', () => {
+ expect(isNearBottom({ scrollTop: 600, scrollHeight: 1000, clientHeight: 400 })).toBe(true)
+ expect(
+ isNearBottom({ scrollTop: 600 - CHAT_FOLLOW_THRESHOLD_PX, scrollHeight: 1000, clientHeight: 400 })
+ ).toBe(true)
+ })
+ it('is false once the user scrolled further up than the threshold', () => {
+ expect(
+ isNearBottom({ scrollTop: 600 - CHAT_FOLLOW_THRESHOLD_PX - 1, scrollHeight: 1000, clientHeight: 400 })
+ ).toBe(false)
+ })
+ it('content shorter than the viewport counts as at the bottom', () => {
+ expect(isNearBottom({ scrollTop: 0, scrollHeight: 200, clientHeight: 400 })).toBe(true)
+ })
+})
+
+describe('shouldFollowOnLoad', () => {
+ it('follows when the user was at the bottom or just sent', () => {
+ expect(shouldFollowOnLoad({ wasNearBottom: true, justSent: false })).toBe(true)
+ expect(shouldFollowOnLoad({ wasNearBottom: false, justSent: true })).toBe(true)
+ })
+ it('keeps the position of a user reading history', () => {
+ expect(shouldFollowOnLoad({ wasNearBottom: false, justSent: false })).toBe(false)
+ })
+})
+
+describe('chatAgentLabel', () => {
+ it('uses the builtin label', () => {
+ expect(chatAgentLabel('claude', [])).toBe('Claude Code')
+ expect(chatAgentLabel('grok', [])).toBe('Grok')
+ })
+ it('uses a custom agent label', () => {
+ expect(chatAgentLabel('custom:1', [{ id: 'custom:1', label: 'My Proxy' }])).toBe('My Proxy')
+ })
+ it('falls back to a neutral word, never to Claude', () => {
+ expect(chatAgentLabel('custom:gone', [])).toBe('Agent')
+ expect(chatAgentLabel('custom:blank', [{ id: 'custom:blank', label: ' ' }])).toBe('Agent')
+ })
+})
diff --git a/src/renderer/lib/chatPanel.ts b/src/renderer/lib/chatPanel.ts
new file mode 100644
index 000000000..acc312b4c
--- /dev/null
+++ b/src/renderer/lib/chatPanel.ts
@@ -0,0 +1,55 @@
+import { agentConfig, type AgentId } from '@shared/agents/config'
+import type { CustomAgent } from '@shared/types'
+
+/**
+ * Pure decisions behind the ⌘M chat panel (`nodes/ChatPanel.tsx`), kept out of the component so
+ * each is unit-tested without a DOM.
+ */
+
+export type ChatKeyAction = 'send' | 'newline' | 'none'
+
+/**
+ * What a keydown in the composer means. Enter sends; Shift+Enter is left to the textarea's own
+ * default (a newline) — it used to SEND, because every Enter was swallowed. An Enter that commits
+ * an IME composition (Japanese, Chinese, Korean input) is the user picking a candidate, not
+ * submitting: sending there would ship a half-typed message. The glue passes
+ * `nativeEvent.isComposing || keyCode === 229` (Safari reports the commit keydown only by 229).
+ */
+export function chatKeyAction(e: { key: string; shiftKey: boolean; isComposing: boolean }): ChatKeyAction {
+ if (e.key !== 'Enter' || e.isComposing) return 'none'
+ return e.shiftKey ? 'newline' : 'send'
+}
+
+/** How close to the bottom (px) still counts as "following" the conversation. */
+export const CHAT_FOLLOW_THRESHOLD_PX = 48
+
+export function isNearBottom(
+ el: { scrollTop: number; scrollHeight: number; clientHeight: number },
+ threshold = CHAT_FOLLOW_THRESHOLD_PX
+): boolean {
+ return el.scrollHeight - el.scrollTop - el.clientHeight <= threshold
+}
+
+/**
+ * Pin to the newest message after a load only when the user was already following it, or has
+ * just sent one (they expect to see it land). A user scrolled up reading an earlier answer keeps
+ * their place — every turn-finish reload used to yank them to the bottom.
+ */
+export function shouldFollowOnLoad(s: { wasNearBottom: boolean; justSent: boolean }): boolean {
+ return s.wasNearBottom || s.justSent
+}
+
+/**
+ * The word the composer uses for this node's agent: the builtin label, else the custom agent's
+ * own label (a custom agent with `baseAgent: 'claude'` reaches this panel too), else a neutral
+ * 'Agent' — never "Claude" by default, which is how a grok node came to say "Message Claude…".
+ */
+export function chatAgentLabel(
+ agentId: AgentId,
+ customAgents: readonly Pick<CustomAgent, 'id' | 'label'>[]
+): string {
+ const builtin = agentConfig(agentId)?.label
+ if (builtin) return builtin
+ const custom = customAgents.find((c) => c.id === agentId)?.label?.trim()
+ return custom || 'Agent'
+}
diff --git a/src/renderer/lib/chatSendGate.test.ts b/src/renderer/lib/chatSendGate.test.ts
index 806db1096..5b73726dd 100644
--- a/src/renderer/lib/chatSendGate.test.ts
+++ b/src/renderer/lib/chatSendGate.test.ts
@@ -1,54 +1,85 @@
import { describe, expect, it } from 'vitest'
-import { canSendFromChat, chatComposerPlaceholder } from './chatSendGate'
+import { canSendFromChat, chatComposerPlaceholder, chatSendRefusal } from './chatSendGate'
-describe('canSendFromChat', () => {
+describe('chatSendRefusal / canSendFromChat', () => {
it('allows a finished turn and an unknown state (no hook knowledge keeps the historical behavior)', () => {
- expect(canSendFromChat('done')).toBe(true)
- expect(canSendFromChat(undefined)).toBe(true)
+ expect(chatSendRefusal({ state: 'done' })).toBeNull()
+ expect(chatSendRefusal({ state: undefined })).toBeNull()
+ expect(chatSendRefusal({})).toBeNull()
+ expect(canSendFromChat({ state: 'done' })).toBe(true)
+ expect(canSendFromChat({})).toBe(true)
})
it('refuses while the agent is working', () => {
- expect(canSendFromChat('working')).toBe(false)
+ expect(chatSendRefusal({ state: 'working' })).toBe('working')
+ expect(canSendFromChat({ state: 'working' })).toBe(false)
})
it('refuses while a TUI dialog is up: Enter would answer it', () => {
// PermissionRequest / AskUserQuestion normalize to `waiting`, a permission Notification to
// `blocked` — both are select dialogs where sendText's trailing Enter confirms the highlight.
- expect(canSendFromChat('waiting')).toBe(false)
- expect(canSendFromChat('blocked')).toBe(false)
+ expect(chatSendRefusal({ state: 'waiting' })).toBe('dialog')
+ expect(chatSendRefusal({ state: 'blocked' })).toBe('dialog')
+ })
+
+ it('refuses a hibernated node even though its state still reads done: a SHELL owns the pane', () => {
+ expect(chatSendRefusal({ state: 'done', hibernated: true })).toBe('asleep')
+ expect(canSendFromChat({ state: 'done', hibernated: true })).toBe(false)
+ expect(chatSendRefusal({ hibernated: true })).toBe('asleep')
+ })
+
+ it('refuses a paused or dropped node for the same reason', () => {
+ expect(chatSendRefusal({ state: 'done', paused: true })).toBe('paused')
+ expect(chatSendRefusal({ state: 'done', dropped: true })).toBe('dropped')
+ })
+
+ it('a shell-owned pane outranks a stale live state', () => {
+ expect(chatSendRefusal({ state: 'working', hibernated: true })).toBe('asleep')
})
})
describe('chatComposerPlaceholder', () => {
- it('keeps the historical copy for a sendable state', () => {
- expect(chatComposerPlaceholder({ readonly: false, state: 'done', chip: '⌘M' })).toBe(
- 'Message Claude… (Enter to send)'
+ const base = { readonly: false, agentLabel: 'Grok', chip: '⌘M' }
+
+ it('names the node agent in the sendable copy', () => {
+ expect(chatComposerPlaceholder({ ...base, refusal: null })).toBe(
+ 'Message Grok… (Enter to send, Shift+Enter for a new line)'
)
- expect(chatComposerPlaceholder({ readonly: false, state: undefined, chip: '' })).toBe(
- 'Message Claude… (Enter to send)'
+ expect(chatComposerPlaceholder({ ...base, agentLabel: 'Claude Code', refusal: null })).toBe(
+ 'Message Claude Code… (Enter to send, Shift+Enter for a new line)'
)
})
- it('keeps the working copy', () => {
- expect(chatComposerPlaceholder({ readonly: false, state: 'working', chip: '⌘M' })).toBe('Claude is working…')
+ it('names the agent while working', () => {
+ expect(chatComposerPlaceholder({ ...base, refusal: 'working' })).toBe('Grok is working…')
})
it('points a dialog back at the terminal through the bound chord', () => {
- for (const state of ['waiting', 'blocked'] as const) {
- expect(chatComposerPlaceholder({ readonly: false, state, chip: '⌘M' })).toBe(
- 'Claude is waiting for an answer in the terminal — press ⌘M to answer there'
- )
- }
+ expect(chatComposerPlaceholder({ ...base, refusal: 'dialog' })).toBe(
+ 'Grok is waiting for an answer in the terminal — press ⌘M to answer there'
+ )
})
it('never promises a chord that is unbound', () => {
- const text = chatComposerPlaceholder({ readonly: false, state: 'waiting', chip: '' })
- expect(text).toBe('Claude is waiting for an answer in the terminal — switch back to the terminal to answer')
+ const text = chatComposerPlaceholder({ ...base, chip: '', refusal: 'dialog' })
+ expect(text).toBe('Grok is waiting for an answer in the terminal — switch back to the terminal to answer')
expect(text).not.toMatch(/press/)
})
- it('a write failure wins over every state', () => {
- expect(chatComposerPlaceholder({ readonly: true, state: 'waiting', chip: '⌘M' })).toBe(
+ it('tells an asleep, paused or dropped node how to come back, by the chip it shows', () => {
+ expect(chatComposerPlaceholder({ ...base, refusal: 'asleep' })).toBe(
+ 'Grok is asleep to save memory — click SLEEPING in the node header to resume it'
+ )
+ expect(chatComposerPlaceholder({ ...base, refusal: 'paused' })).toBe(
+ 'Grok is paused — click PAUSED in the node header to resume it'
+ )
+ expect(chatComposerPlaceholder({ ...base, refusal: 'dropped' })).toBe(
+ 'Grok is no longer running in this terminal — click DROPPED in the node header to resume it'
+ )
+ })
+
+ it('a write failure wins over every refusal', () => {
+ expect(chatComposerPlaceholder({ ...base, readonly: true, refusal: 'dialog' })).toBe(
"Can't write to this session"
)
})
diff --git a/src/renderer/lib/chatSendGate.ts b/src/renderer/lib/chatSendGate.ts
index 5c0a5ffec..47d6aac8b 100644
--- a/src/renderer/lib/chatSendGate.ts
+++ b/src/renderer/lib/chatSendGate.ts
@@ -1,46 +1,87 @@
import type { AgentState } from '@shared/agents/normalize'
+/** The slice of a node's agent status the composer gate reads (`AgentNodeStatus` fits it). */
+export interface ChatGateStatus {
+ state?: AgentState
+ hibernated?: boolean
+ paused?: boolean
+ dropped?: boolean
+}
+
+/** Why the composer refuses to send; `null` = it may send. */
+export type ChatSendRefusal = 'working' | 'dialog' | 'asleep' | 'paused' | 'dropped' | null
+
/**
- * May the ⌘M chat composer type into the agent's pane right now?
+ * May the ⌘M chat composer type into the agent's pane right now — and if not, why?
*
* `pty.sendText` pastes the text and then presses Enter. That is a prompt only while the agent's
- * input box owns the pane. In `waiting` (Claude's PermissionRequest AND AskUserQuestion both
- * normalize to it, `shared/agents/normalize.ts`) and `blocked` (a permission Notification) the
- * pane holds a TUI select dialog the transcript view does not show — and Enter CONFIRMS the
- * highlighted option, which is "Yes" by default. A message typed into the chat would silently
- * grant a permission or pick an answer. Same trap CLAUDE.md documents for the in-place restart's
- * `/exit`, and the same refusal.
+ * input box owns the pane. Two ways it does not:
+ *
+ * - **A TUI dialog** (`waiting`/`blocked`). Claude's PermissionRequest AND AskUserQuestion both
+ * normalize to `waiting` (`shared/agents/normalize.ts`), a permission Notification to `blocked`.
+ * The pane then holds a select dialog the transcript view does not show, and Enter CONFIRMS the
+ * highlighted option — "Yes" by default. A chat message would silently grant a permission or
+ * pick an answer. Same trap CLAUDE.md documents for the in-place restart's `/exit`.
+ * - **A SHELL** (hibernated / paused / dropped). Eco's hibernation exits the CLI and leaves the
+ * node's `state` at `done`, so the state alone reads "sendable" — but the pane now belongs to
+ * the login shell, and the message would be EXECUTED as a shell command. Pause and an
+ * unaccounted CLI exit (DROPPED) leave the pane in the same shell. These flags therefore rank
+ * ABOVE the state: a stale live state cannot vouch for a CLI that is known to be gone.
*
- * `undefined` is ALLOWED: no hook knowledge (a custom agent, a session with no event yet in this
- * app run) is "unknown", not "unsafe", and refusing it would take the composer away from every
- * such node — the historical behavior is kept there. Only `done` is a positive "input box is up".
+ * No hook knowledge (`state` undefined, no flags — a custom agent, a session with no event yet in
+ * this app run) is ALLOWED: unknown is not unsafe, and refusing it would take the composer away
+ * from every such node. Only `done` is a positive "input box is up".
*/
-export function canSendFromChat(state: AgentState | undefined): boolean {
- return state === undefined || state === 'done'
+export function chatSendRefusal(s: ChatGateStatus): ChatSendRefusal {
+ if (s.dropped) return 'dropped'
+ if (s.paused) return 'paused'
+ if (s.hibernated) return 'asleep'
+ if (s.state === 'working') return 'working'
+ if (s.state === 'waiting' || s.state === 'blocked') return 'dialog'
+ return null
+}
+
+export function canSendFromChat(s: ChatGateStatus): boolean {
+ return chatSendRefusal(s) === null
}
/**
- * The composer's placeholder — the one place the user learns WHY it is disabled. A dialog points
- * back at the terminal through the chord actually bound to the markdown/chat toggle (`chip`, from
- * `chipFor('node.toggleMarkdown')`); `''` = unbound, and then the text names the action instead
- * of promising a chord that never fires. A write failure (`readonly`) outranks every state: no
- * state change will make that session writable.
+ * The composer's placeholder — the one place the user learns WHY it is disabled, naming the
+ * node's own agent (the panel serves grok and base-claude custom agents too, not only Claude).
+ *
+ * A dialog points back at the terminal through the chord actually bound to the markdown/chat
+ * toggle (`chip`, from `chipFor('node.toggleMarkdown')`); `''` = unbound, and then the text names
+ * the action instead of promising a chord that never fires. A shell-owned pane names the header
+ * chip that resumes it — the same SLEEPING / PAUSED / DROPPED chip whose click runs the wake,
+ * visible above this panel. A write failure (`readonly`) outranks everything: no state change will
+ * make that session writable.
*/
export function chatComposerPlaceholder({
readonly,
- state,
+ refusal,
+ agentLabel,
chip
}: {
readonly: boolean
- state: AgentState | undefined
+ refusal: ChatSendRefusal
+ agentLabel: string
chip: string
}): string {
if (readonly) return "Can't write to this session"
- if (state === 'working') return 'Claude is working…'
- if (!canSendFromChat(state)) {
- return chip
- ? `Claude is waiting for an answer in the terminal — press ${chip} to answer there`
- : 'Claude is waiting for an answer in the terminal — switch back to the terminal to answer'
+ switch (refusal) {
+ case 'working':
+ return `${agentLabel} is working…`
+ case 'dialog':
+ return chip
+ ? `${agentLabel} is waiting for an answer in the terminal — press ${chip} to answer there`
+ : `${agentLabel} is waiting for an answer in the terminal — switch back to the terminal to answer`
+ case 'asleep':
+ return `${agentLabel} is asleep to save memory — click SLEEPING in the node header to resume it`
+ case 'paused':
+ return `${agentLabel} is paused — click PAUSED in the node header to resume it`
+ case 'dropped':
+ return `${agentLabel} is no longer running in this terminal — click DROPPED in the node header to resume it`
+ case null:
+ return `Message ${agentLabel}… (Enter to send, Shift+Enter for a new line)`
}
- return 'Message Claude… (Enter to send)'
}
diff --git a/src/renderer/nodes/ChatPanel.sendGate.test.tsx b/src/renderer/nodes/ChatPanel.sendGate.test.tsx
index 11888348e..7328f9dff 100644
--- a/src/renderer/nodes/ChatPanel.sendGate.test.tsx
+++ b/src/renderer/nodes/ChatPanel.sendGate.test.tsx
@@ -34,9 +34,12 @@ const NODE = 'n-chat-gate'
let host: HTMLDivElement
let root: Root
-function setAgentState(state: 'working' | 'waiting' | 'blocked' | 'done' | undefined): void {
+function setAgentState(
+ state: 'working' | 'waiting' | 'blocked' | 'done' | undefined,
+ extra: { hibernated?: boolean } = {}
+): void {
useAgentStatus.setState((s) => ({
- byId: { ...s.byId, [NODE]: { ...(s.byId[NODE] ?? {}), state } as (typeof s.byId)[string] }
+ byId: { ...s.byId, [NODE]: { ...(s.byId[NODE] ?? {}), state, ...extra } as (typeof s.byId)[string] }
}))
}
@@ -64,8 +67,8 @@ beforeEach(() => {
root = createRoot(host)
})
-afterEach(() => {
- act(() => root.unmount())
+afterEach(async () => {
+ await act(async () => root.unmount())
host.remove()
useAgentStatus.setState((s) => {
const byId = { ...s.byId }
@@ -103,4 +106,22 @@ describe('ChatPanel send gate', () => {
})
expect(sendText).not.toHaveBeenCalled()
})
+
+ it('disables the composer on a hibernated node: its state still reads done, but a SHELL owns the pane', async () => {
+ setAgentState('done', { hibernated: true })
+ const ta = await mount()
+ expect(ta.disabled).toBe(true)
+ expect(ta.placeholder).toMatch(/asleep to save memory/)
+ })
+
+ it('re-reads hibernation at send time too', async () => {
+ setAgentState('done')
+ const ta = await mount()
+ await act(async () => type(ta, 'ls -la'))
+ await act(async () => {
+ setAgentState('done', { hibernated: true })
+ enter(ta)
+ })
+ expect(sendText).not.toHaveBeenCalled()
+ })
})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 398eab3da..5ecc78800 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -1,11 +1,13 @@
import { TEXT_NOT_SUBMITTED } from '@shared/text-delivery'
-import { memo, useCallback, useEffect, useMemo, useRef, useState, type KeyboardEvent } from 'react'
+import { memo, useCallback, useEffect, useLayoutEffect, 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'
import { chipFor } from '../lib/keybindingOverrides'
-import { canSendFromChat, chatComposerPlaceholder } from '../lib/chatSendGate'
+import { chatComposerPlaceholder, chatSendRefusal } from '../lib/chatSendGate'
+import { chatAgentLabel, chatKeyAction, isNearBottom, shouldFollowOnLoad } from '../lib/chatPanel'
+import { useSettings } from '../state/settings'
import { E_UNSUPPORTED } from '@shared/rpc'
// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each
@@ -94,20 +96,40 @@ export function ChatPanel({
const [input, setInput] = useState('')
const [readonly, setReadonly] = useState(false)
const state = useAgentStatus((s) => s.byId[nodeId]?.state)
+ // The shell-owned-pane flags, each as its own primitive selector (an object selector would
+ // re-render on every hook event for every node). See lib/chatSendGate.ts for why they gate.
+ const hibernated = useAgentStatus((s) => s.byId[nodeId]?.hibernated)
+ const paused = useAgentStatus((s) => s.byId[nodeId]?.paused)
+ const dropped = useAgentStatus((s) => s.byId[nodeId]?.dropped)
+ const customAgents = useSettings((s) => s.settings.customAgents)
const msgsRef = useRef<HTMLDivElement>(null)
const prevState = useRef(state)
+ // Request token: only the NEWEST readTranscript may land. An older read resolving late (the
+ // sessionId changed underneath it, or a ↻ raced the turn-finish reload) would otherwise paint
+ // another session's thread over the current one. Bumped on unmount too, so a read that resolves
+ // after the panel closed is dropped rather than applied to a dead component.
+ const reqRef = useRef(0)
+ // Scroll-follow inputs, captured BEFORE a load changes the content: was the user following the
+ // bottom (updated on every scroll), and did they just send (they expect to see it land).
+ const nearBottomRef = useRef(true)
+ const justSentRef = useRef(false)
const load = useCallback(() => {
+ const token = ++reqRef.current
setLoadState((s) => (s === 'ok' ? s : 'loading')) // a reload never blanks a rendered thread
// `nodeId` is what lets an SSH-project node resolve on its host; the rejection branch is what
// keeps a surface that cannot read transcripts (Server Edition, relay tab) from silently
// presenting itself as an empty conversation.
void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId).then(
(res) => {
+ if (token !== reqRef.current) return
setMessages(res.messages)
setLoadState(res.found ? 'ok' : 'missing')
},
- (e: unknown) => setLoadState(isUnsupported(e) ? 'unsupported' : 'error')
+ (e: unknown) => {
+ if (token !== reqRef.current) return
+ setLoadState(isUnsupported(e) ? 'unsupported' : 'error')
+ }
)
}, [api, sessionId, cwd, accountId, nodeId, agentId])
@@ -116,27 +138,49 @@ export function ChatPanel({
load()
}, [load])
- // Reload when a turn completes (working -> not working).
+ // Invalidate any in-flight read when the panel goes away.
+ useEffect(
+ () => () => {
+ reqRef.current++
+ },
+ []
+ )
+
+ // Reload when a turn completes (working -> not working). Sessions whose hooks never report
+ // `working` never take this path — the bar's ↻ is their reload.
useEffect(() => {
if (prevState.current === 'working' && state !== 'working') load()
prevState.current = state
}, [state, load])
- // Keep pinned to the latest message.
- useEffect(() => {
+ // Follow the newest message only when the user was already at the bottom or just sent; a user
+ // scrolled up reading an earlier answer keeps their place. Layout effect: the jump lands before
+ // paint, so a followed thread never flashes one frame short.
+ useLayoutEffect(() => {
const el = msgsRef.current
- if (el) el.scrollTop = el.scrollHeight
+ if (!el) return
+ if (shouldFollowOnLoad({ wasNearBottom: nearBottomRef.current, justSent: justSentRef.current })) {
+ el.scrollTop = el.scrollHeight
+ nearBottomRef.current = true
+ }
+ justSentRef.current = false
}, [messages])
- // Not just `working`: in `waiting`/`blocked` the pane holds a TUI dialog this view does not show,
- // and sendText's Enter would ANSWER it (see lib/chatSendGate.ts).
- const sendRefused = !canSendFromChat(state)
+ const onScroll = () => {
+ const el = msgsRef.current
+ if (el) nearBottomRef.current = isNearBottom(el)
+ }
+
+ // Not just `working`: a TUI dialog (`waiting`/`blocked`) would be ANSWERED by sendText's Enter,
+ // and a hibernated/paused/dropped node's pane is a SHELL that would execute the text.
+ const refusal = chatSendRefusal({ state, hibernated, paused, dropped })
+ const agentLabel = chatAgentLabel(agentId, customAgents)
const send = useCallback(async () => {
const text = input.trim()
- // Read the store at SEND time, not the render-time `state`: a PermissionRequest that landed
- // between the last render and this keypress must still block, or the Enter answers the dialog.
- if (!text || !canSendFromChat(useAgentStatus.getState().byId[nodeId]?.state)) return
+ // Read the store at SEND time, not the render-time values: a PermissionRequest (or an Eco
+ // hibernation) that landed between the last render and this keypress must still block.
+ if (!text || chatSendRefusal(useAgentStatus.getState().byId[nodeId] ?? {}) !== null) return
const ok = await api.pty.sendText(nodeId, text)
if (ok === 'pasted-not-submitted') {
window.dispatchEvent(new CustomEvent('nodeterm:toast', { detail: { kind: 'error', message: TEXT_NOT_SUBMITTED } }))
@@ -148,15 +192,21 @@ export function ChatPanel({
return
}
// Optimistic: show the prompt immediately; the next load() reconciles from the transcript.
+ justSentRef.current = true
setMessages((m) => [...m, { role: 'user', parts: [{ kind: 'text', text }] }])
setInput('')
}, [api, input, nodeId])
const onKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
- if (e.key === 'Enter') {
- e.preventDefault()
- void send()
- }
+ // Shift+Enter falls through to the textarea's own newline; an IME commit is not a send.
+ const action = chatKeyAction({
+ key: e.key,
+ shiftKey: e.shiftKey,
+ isComposing: e.nativeEvent.isComposing || e.keyCode === 229
+ })
+ if (action !== 'send') return
+ e.preventDefault()
+ void send()
}
// Whatever the markdown/chat toggle is bound to; '' when unbound, in which case the bar names
@@ -167,9 +217,19 @@ export function ChatPanel({
<div className="term-chat nodrag nowheel">
<div className="term-chat__bar">
<span>{title ?? 'Chat'}</span>
- <span className="term-chat__hint">{hint ?? (mdChip ? `${mdChip} to exit` : 'Exit')}</span>
+ <span className="term-chat__bar-end">
+ <button
+ className="term-chat__refresh"
+ onClick={load}
+ title="Reload conversation"
+ aria-label="Reload conversation"
+ >
+ ↻
+ </button>
+ <span className="term-chat__hint">{hint ?? (mdChip ? `${mdChip} to exit` : 'Exit')}</span>
+ </span>
</div>
- <div className="term-chat__msgs" ref={msgsRef}>
+ <div className="term-chat__msgs" ref={msgsRef} onScroll={onScroll}>
{messages.length === 0 && loadState !== 'loading' && (
<div className="term-chat__empty">
<div>{EMPTY_TEXT[loadState].title}</div>
@@ -186,8 +246,14 @@ export function ChatPanel({
{messages.map((m, i) => (
<div key={i} className={`term-chat__msg term-chat__msg--${m.role}`}>
{m.parts.map((p, j) =>
- p.kind === 'text' || p.kind === 'thinking' ? (
+ p.kind === 'text' ? (
<MarkdownText key={j} text={p.text} />
+ ) : p.kind === 'thinking' ? (
+ // Reasoning, not the answer: collapsed by default so it cannot be mistaken for it.
+ <details key={j} className="term-chat__thinking">
+ <summary>Thinking</summary>
+ <MarkdownText text={p.text} />
+ </details>
) : (
<details key={j} className="term-chat__tool">
<summary>
@@ -208,8 +274,8 @@ export function ChatPanel({
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={onKeyDown}
- placeholder={chatComposerPlaceholder({ readonly, state, chip: mdChip })}
- disabled={readonly || sendRefused}
+ placeholder={chatComposerPlaceholder({ readonly, refusal, agentLabel, chip: mdChip })}
+ disabled={readonly || refusal !== null}
rows={2}
/>
</div>
diff --git a/src/renderer/nodes/ChatPanel.ux.test.tsx b/src/renderer/nodes/ChatPanel.ux.test.tsx
new file mode 100644
index 000000000..7ed8a7157
--- /dev/null
+++ b/src/renderer/nodes/ChatPanel.ux.test.tsx
@@ -0,0 +1,214 @@
+// @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 type { ChatMessage, ChatTranscriptResult } from '@shared/types'
+import { useAgentStatus } from '../state/agentStatus'
+
+/**
+ * The ⌘M chat panel's UX glue (the pure decisions live in `lib/chatPanel.ts`): Shift+Enter / IME,
+ * the thinking disclosure, the stale-response guard, the ↻ reload, the agent-named composer copy
+ * and scroll-follow. `readTranscript` is a controllable deferred per call so ordering is explicit.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+interface Pending {
+ sessionId: string | undefined
+ resolve: (r: ChatTranscriptResult) => void
+}
+
+// ONE stable api object: `load` depends on `api`, so a fresh object per `useSession()` call would
+// re-run the load effect on every render and never settle.
+const { sendText, readTranscript, pending, session } = vi.hoisted(() => {
+ const pending: Pending[] = []
+ const sendText = vi.fn(async (_id: string, _text: string) => true as const)
+ const readTranscript = vi.fn(
+ (sessionId: string | undefined) =>
+ new Promise<ChatTranscriptResult>((resolve) => pending.push({ sessionId, resolve }))
+ )
+ const session = { api: { chat: { readTranscript }, pty: { sendText } } }
+ return { sendText, readTranscript, pending, session }
+})
+vi.mock('../session/session', () => ({ useSession: () => session }))
+
+import { ChatPanel } from './ChatPanel'
+
+const NODE = 'n-chat-ux'
+let host: HTMLDivElement
+let root: Root
+
+const text = (role: 'user' | 'assistant', t: string): ChatMessage => ({ role, parts: [{ kind: 'text', text: t }] })
+
+async function render(props: { sessionId?: string; agentId?: string } = {}): Promise<void> {
+ await act(async () => {
+ root.render(<ChatPanel nodeId={NODE} sessionId={props.sessionId ?? 's1'} agentId={props.agentId ?? 'claude'} />)
+ })
+}
+
+async function resolveAt(i: number, messages: ChatMessage[]): Promise<void> {
+ await act(async () => {
+ pending[i].resolve({ messages, found: true })
+ })
+}
+
+const textarea = (): HTMLTextAreaElement => host.querySelector('textarea') as HTMLTextAreaElement
+const msgs = (): HTMLDivElement => host.querySelector('.term-chat__msgs') as HTMLDivElement
+
+function type(ta: HTMLTextAreaElement, value: string): void {
+ const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!
+ setter.call(ta, value)
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+}
+
+function key(ta: HTMLTextAreaElement, init: KeyboardEventInit & { isComposing?: boolean }): KeyboardEvent {
+ const ev = new KeyboardEvent('keydown', { bubbles: true, cancelable: true, ...init })
+ ta.dispatchEvent(ev)
+ return ev
+}
+
+/** jsdom has no layout: give the scroller explicit geometry the component reads. */
+function geometry(el: HTMLElement, g: { scrollHeight: number; clientHeight: number }): void {
+ Object.defineProperty(el, 'scrollHeight', { configurable: true, get: () => g.scrollHeight })
+ Object.defineProperty(el, 'clientHeight', { configurable: true, get: () => g.clientHeight })
+}
+
+beforeEach(() => {
+ sendText.mockClear()
+ readTranscript.mockClear()
+ pending.length = 0
+ 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 composer keys', () => {
+ it('Shift+Enter does not send and keeps the textarea default (a newline)', async () => {
+ await render()
+ await resolveAt(0, [])
+ await act(async () => type(textarea(), 'line one'))
+ let ev!: KeyboardEvent
+ await act(async () => {
+ ev = key(textarea(), { key: 'Enter', shiftKey: true })
+ })
+ expect(sendText).not.toHaveBeenCalled()
+ expect(ev.defaultPrevented).toBe(false)
+ })
+
+ it('an Enter committing an IME composition does not send', async () => {
+ await render()
+ await resolveAt(0, [])
+ await act(async () => type(textarea(), 'こんにちは'))
+ await act(async () => {
+ key(textarea(), { key: 'Enter', isComposing: true })
+ })
+ expect(sendText).not.toHaveBeenCalled()
+ })
+
+ it('plain Enter still sends', async () => {
+ await render()
+ await resolveAt(0, [])
+ await act(async () => type(textarea(), 'hi'))
+ await act(async () => {
+ key(textarea(), { key: 'Enter' })
+ })
+ expect(sendText).toHaveBeenCalledWith(NODE, 'hi')
+ })
+})
+
+describe('ChatPanel rendering', () => {
+ it('renders a thinking part as a collapsed "Thinking" disclosure, not as answer text', async () => {
+ await render()
+ await resolveAt(0, [{ role: 'assistant', parts: [{ kind: 'thinking', text: 'pondering' }, { kind: 'text', text: 'answer' }] }])
+ const d = host.querySelector('details.term-chat__thinking') as HTMLDetailsElement
+ expect(d).not.toBeNull()
+ expect(d.open).toBe(false)
+ expect(d.querySelector('summary')?.textContent).toBe('Thinking')
+ expect(d.textContent).toContain('pondering')
+ // The answer stays ordinary text, outside the disclosure.
+ const answers = [...host.querySelectorAll('.term-chat__msg > .term-chat__text')].map((e) => e.textContent?.trim())
+ expect(answers).toEqual(['answer'])
+ })
+
+ it('names the node agent in the composer, not Claude', async () => {
+ await render({ agentId: 'grok' })
+ await resolveAt(0, [])
+ expect(textarea().placeholder).toMatch(/^Message Grok…/)
+ })
+})
+
+describe('ChatPanel loading', () => {
+ it('ignores an older transcript read that resolves after a newer one', async () => {
+ await render({ sessionId: 's-old' })
+ await render({ sessionId: 's-new' })
+ expect(pending.map((p) => p.sessionId)).toEqual(['s-old', 's-new'])
+ await resolveAt(1, [text('assistant', 'NEW')])
+ await resolveAt(0, [text('assistant', 'OLD')])
+ expect(msgs().textContent).toContain('NEW')
+ expect(msgs().textContent).not.toContain('OLD')
+ })
+
+ it('the ↻ button in the bar reloads the transcript', async () => {
+ await render()
+ await resolveAt(0, [text('assistant', 'one')])
+ const btn = host.querySelector('.term-chat__bar .term-chat__refresh') as HTMLButtonElement
+ expect(btn).not.toBeNull()
+ await act(async () => btn.click())
+ expect(readTranscript).toHaveBeenCalledTimes(2)
+ await resolveAt(1, [text('assistant', 'one'), text('assistant', 'two')])
+ expect(msgs().textContent).toContain('two')
+ })
+})
+
+describe('ChatPanel scroll-follow', () => {
+ it('pins to the bottom on a load when the user was already at the bottom', async () => {
+ await render()
+ const el = msgs()
+ geometry(el, { scrollHeight: 1000, clientHeight: 400 })
+ await resolveAt(0, [text('assistant', 'a')])
+ expect(el.scrollTop).toBe(1000)
+ })
+
+ it('keeps the position of a user who scrolled up to read history', async () => {
+ await render()
+ const el = msgs()
+ geometry(el, { scrollHeight: 1000, clientHeight: 400 })
+ await resolveAt(0, [text('assistant', 'a')])
+ // User scrolls up, far past the threshold.
+ await act(async () => {
+ el.scrollTop = 100
+ el.dispatchEvent(new Event('scroll'))
+ })
+ geometry(el, { scrollHeight: 1600, clientHeight: 400 })
+ await act(async () => host.querySelector<HTMLButtonElement>('.term-chat__refresh')!.click())
+ await resolveAt(1, [text('assistant', 'a'), text('assistant', 'b')])
+ expect(el.scrollTop).toBe(100)
+ })
+
+ it('follows after the user sends, even when scrolled up', async () => {
+ await render()
+ const el = msgs()
+ geometry(el, { scrollHeight: 1000, clientHeight: 400 })
+ await resolveAt(0, [text('assistant', 'a')])
+ await act(async () => {
+ el.scrollTop = 100
+ el.dispatchEvent(new Event('scroll'))
+ })
+ geometry(el, { scrollHeight: 1200, clientHeight: 400 })
+ await act(async () => type(textarea(), 'go'))
+ await act(async () => {
+ key(textarea(), { key: 'Enter' })
+ })
+ expect(el.scrollTop).toBe(1200)
+ })
+})
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index e30fe13a7..e05cc379f 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3183,6 +3183,39 @@ body,
.term-chat__input:disabled {
opacity: 0.5;
}
+.term-chat__bar-end {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.term-chat__refresh {
+ padding: 0 4px;
+ font-size: 12px;
+ line-height: 1;
+ color: inherit;
+ background: none;
+ border: none;
+ border-radius: 4px;
+ cursor: pointer;
+}
+.term-chat__refresh:hover {
+ background: rgba(var(--tint-rgb), 0.1);
+}
+/* Reasoning, collapsed by default and dimmed so it never reads as the answer. */
+.term-chat__thinking {
+ margin: 4px 0;
+ font-size: 12px;
+ color: rgba(var(--tint-rgb), 0.6);
+}
+.term-chat__thinking summary {
+ cursor: pointer;
+ font-style: italic;
+}
+.term-chat__thinking .term-chat__text {
+ margin-top: 4px;
+ padding-left: 8px;
+ border-left: 2px solid rgba(var(--tint-rgb), 0.15);
+}
/* Transparent overlay that lets you pan across a terminal until you dwell/click. */
.term-hover-guard {