Send notes to working agents (#5748)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-19 20:30:51 -07:00
committed by GitHub
co-authored by Orca
parent 13427a7de0
commit 8264cd2416
25 changed files with 3346 additions and 293 deletions
+849
View File
@@ -5349,6 +5349,821 @@ describe('OrcaRuntimeService', () => {
expect(writes).toEqual(['continue', '\r'])
})
it('reports permission from blocked terminal wait text', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
const leafId = '11111111-1111-4111-8111-111111111111'
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'repo terminal',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
runtime.onPtyData('pty-1', 'Hooks need review. Press enter to confirm\n', 123)
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'permission'
})
})
it('reports permission from blocked wait text over title-only working state', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
const leafId = '11111111-1111-4111-8111-111111111111'
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'Codex working',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
runtime.onPtyData('pty-1', 'Hooks need review. Press enter to confirm\n', 123)
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'permission'
})
})
it('lets a live non-permission title supersede stale blocked wait text', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
const leafId = '11111111-1111-4111-8111-111111111111'
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'repo terminal',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
runtime.onPtyData('pty-1', 'Hooks need review. Press enter to confirm\n', 123)
runtime.onPtyData('pty-1', '\x1b]0;Codex working\x07', 124)
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'working'
})
})
it('maps fresh explicit waiting hook state to permission over a working title', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'waiting',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: Date.now(),
stateStartedAt: Date.now(),
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'Codex working',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'permission'
})
})
it('does not let stale wait text override a fresh explicit working state', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'working',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: Date.now(),
stateStartedAt: Date.now(),
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'Codex working',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
runtime.onPtyData('pty-1', 'Hooks need review. Press enter to confirm\n', 123)
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'working'
})
})
it('reports permission when blocked wait text is newer than explicit working state', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const now = Date.now()
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'working',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: now - 1000,
stateStartedAt: now - 1000,
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'Codex working',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
runtime.onPtyData('pty-1', 'Hooks need review. Press enter to confirm\n', now)
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'permission'
})
})
it('timestamps blocked wait text when the prompt arrives across PTY chunks', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const now = Date.now()
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'working',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: now,
stateStartedAt: now,
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'Codex working',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
runtime.onPtyData('pty-1', 'Hooks need review. ', now + 1000)
runtime.onPtyData('pty-1', 'Press enter to confirm\n', now + 1001)
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'permission'
})
})
it('prefers newer explicit working state over older explicit permission state', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const now = Date.now()
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'waiting',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: now - 1000,
stateStartedAt: now - 1000,
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
},
{
paneKey,
state: 'working',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: now,
stateStartedAt: now,
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'repo terminal',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'working'
})
})
it('prefers fresh explicit working state over a stale permission title', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'working',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: Date.now(),
stateStartedAt: Date.now(),
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'Codex - action required',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'working'
})
})
it('reports permission from a live title over fresh explicit working state', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'working',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: Date.now(),
stateStartedAt: Date.now(),
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'repo terminal',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1',
paneTitle: 'Codex - action required'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'permission'
})
})
it('does not let fresh explicit hook state authorize a current shell terminal', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'working',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: Date.now(),
stateStartedAt: Date.now(),
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'zsh',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: false,
status: null
})
})
it('does not let fresh explicit hook state authorize a shell foreground process', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'working',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: Date.now(),
stateStartedAt: Date.now(),
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => 'zsh'
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'repo terminal',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: false,
status: null
})
})
it('reports permission from a title-derived action-required agent state', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
const leafId = '11111111-1111-4111-8111-111111111111'
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'Codex waiting for permission',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'permission'
})
})
it('maps fresh explicit done hook state to idle for send readiness', async () => {
const leafId = '11111111-1111-4111-8111-111111111111'
const paneKey = makePaneKey('tab-1', leafId)
const runtime = new OrcaRuntimeService(store, undefined, {
getAgentStatusSnapshot: () => [
{
paneKey,
state: 'done',
prompt: '',
agentType: 'codex',
connectionId: null,
receivedAt: Date.now(),
stateStartedAt: Date.now(),
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID
}
]
})
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'repo terminal',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: 'idle'
})
})
it('reports recognized foreground agents with unknown status as running with null status', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => 'codex'
})
const leafId = '11111111-1111-4111-8111-111111111111'
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'repo terminal',
activeLeafId: leafId,
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId,
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(runtime.getTerminalAgentStatus(terminal.handle)).resolves.toEqual({
handle: terminal.handle,
isRunningAgent: true,
status: null
})
})
it('keeps ordinary terminal send suffix failures on the existing not-writable contract', async () => {
const writes: string[] = []
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-1' }),
write: (_ptyId: string, data: string) => {
writes.push(data)
return data !== '\r'
},
kill: () => true,
getForegroundProcess: async () => null
})
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
title: 'Codex ready',
activeLeafId: 'pane:1',
layout: null
}
],
leaves: [
{
tabId: 'tab-1',
worktreeId: TEST_WORKTREE_ID,
leafId: 'pane:1',
paneRuntimeId: 1,
ptyId: 'pty-1'
}
]
})
const [terminal] = (await runtime.listTerminals()).terminals
await expect(
runtime.sendTerminal(terminal.handle, { text: 'notes', enter: true })
).rejects.toThrow('terminal_not_writable')
expect(writes).toEqual(['notes', '\r'])
})
it('creates visible terminal sessions without asking the renderer to focus a tab', async () => {
const spawn = vi.fn().mockResolvedValue({ id: 'pty-bg' })
const createTerminal = vi.fn()
@@ -6426,6 +7241,40 @@ describe('OrcaRuntimeService', () => {
})
})
it('blocks tui-idle when a newer prompt follows a stale prompt and ready header', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
spawn: vi.fn().mockResolvedValue({ id: 'pty-bg' }),
write: () => true,
kill: () => true,
getForegroundProcess: async () => 'codex'
})
const { handle } = await runtime.createTerminal(`path:${TEST_WORKTREE_PATH}`)
runtime.onPtyData(
'pty-bg',
[
'Update available! 0.131.0 -> 0.132.0\n',
'Press enter to continue\n',
' >_ OpenAI Codex (v0.132.0)\n',
' model: gpt-5.5 high /model to change\n',
' directory: ~/orca/workspaces/orca/cli-debug\n',
'Hooks need review\n',
'Press enter to confirm\n'
].join(''),
Date.now()
)
await expect(
runtime.waitForTerminal(handle, { condition: 'tui-idle', timeoutMs: 1_000 })
).resolves.toMatchObject({
handle,
condition: 'tui-idle',
satisfied: false,
status: 'running',
blockedReason: 'codex-hooks-review-prompt'
})
})
it('returns a blocked wait result for Codex update prompts', async () => {
const runtime = new OrcaRuntimeService(store)
runtime.setPtyController({
+310 -30
View File
@@ -224,6 +224,7 @@ import type {
RuntimeRepoSearchRefs,
RuntimeTerminalRead,
RuntimeTerminalRename,
RuntimeTerminalAgentStatus,
RuntimeTerminalSend,
RuntimeTerminalCreate,
RuntimeTerminalSplit,
@@ -828,6 +829,7 @@ type RuntimeLeafRecord = RuntimeSyncedLeaf & {
tailTruncated: boolean
tailLinesTotal: number
preview: string
waitBlockedAt: number | null
lastAgentStatus: AgentStatus | null
// Why: the most recent OSC title observed on this leaf's PTY data. Used by
// worktree.ps so daemon-hosted terminals (no renderer pushing pane titles)
@@ -890,6 +892,7 @@ type RuntimePtyWorktreeRecord = {
tailTruncated: boolean
tailLinesTotal: number
preview: string
waitBlockedAt: number | null
}
export type RuntimeTerminalAgentStatusEvent = {
@@ -2562,6 +2565,7 @@ export class OrcaRuntimeService {
tailTruncated: tailSource?.tailTruncated ?? false,
tailLinesTotal: tailSource?.tailLinesTotal ?? 0,
preview: tailSource?.preview ?? '',
waitBlockedAt: tailSource?.waitBlockedAt ?? null,
lastAgentStatus: tailSource?.lastAgentStatus ?? null,
lastOscTitle: tailSource?.lastOscTitle ?? null,
lastOscTitleAt: tailSource?.lastOscTitleAt ?? null,
@@ -4752,12 +4756,26 @@ export class OrcaRuntimeService {
pty.lastOutputAt = at
const normalized = normalizeTerminalChunk(data, pty.tailPendingAnsi)
pty.tailPendingAnsi = normalized.pendingAnsi
const previousWaitText = buildTerminalWaitText(
pty.tailBuffer,
pty.tailPartialLine,
pty.preview
)
const nextTail = appendNormalizedToTailBuffer(
pty.tailBuffer,
pty.tailPartialLine,
normalized.text,
pty.tailRedrawCursor
)
if (
nextTailHasNewerBlockedReason(
previousWaitText,
buildTerminalWaitText(nextTail.lines, nextTail.partialLine, pty.preview),
normalized.text
)
) {
pty.waitBlockedAt = at
}
ptyTailAfter = nextTail
pty.tailBuffer = nextTail.lines
pty.tailPartialLine = nextTail.partialLine
@@ -4815,15 +4833,30 @@ export class OrcaRuntimeService {
leaf.tailTruncated = pty.tailTruncated
leaf.tailLinesTotal = pty.tailLinesTotal
leaf.preview = pty.preview
leaf.waitBlockedAt = pty.waitBlockedAt
} else {
const normalized = normalizeTerminalChunk(data, leaf.tailPendingAnsi)
leaf.tailPendingAnsi = normalized.pendingAnsi
const previousWaitText = buildTerminalWaitText(
leaf.tailBuffer,
leaf.tailPartialLine,
leaf.preview
)
const nextTail = appendNormalizedToTailBuffer(
leaf.tailBuffer,
leaf.tailPartialLine,
normalized.text,
leaf.tailRedrawCursor
)
if (
nextTailHasNewerBlockedReason(
previousWaitText,
buildTerminalWaitText(nextTail.lines, nextTail.partialLine, leaf.preview),
normalized.text
)
) {
leaf.waitBlockedAt = at
}
leaf.tailBuffer = nextTail.lines
leaf.tailPartialLine = nextTail.partialLine
leaf.tailRedrawCursor = nextTail.redrawCursor
@@ -7892,7 +7925,11 @@ export class OrcaRuntimeService {
text?: string
enter?: boolean
interrupt?: boolean
}
},
options: {
beforeWrite?: (ptyId: string) => void | Promise<void>
suffixFailureError?: string
} = {}
): Promise<RuntimeTerminalSend> {
const pty = this.getLivePtyForHandle(handle)
if (pty) {
@@ -7904,7 +7941,7 @@ export class OrcaRuntimeService {
throw new Error('invalid_terminal_send')
}
await assertTerminalInputWithinLimitWithYield(action.text)
await this.writeTerminalAction(pty.pty.ptyId, action, payload)
await this.writeTerminalAction(pty.pty.ptyId, action, payload, options)
return {
handle,
accepted: true,
@@ -7922,7 +7959,7 @@ export class OrcaRuntimeService {
}
await assertTerminalInputWithinLimitWithYield(action.text)
await this.writeTerminalAction(leaf.ptyId, action, payload)
await this.writeTerminalAction(leaf.ptyId, action, payload, options)
return {
handle,
@@ -7931,26 +7968,203 @@ export class OrcaRuntimeService {
}
}
async getTerminalAgentStatus(handle: string): Promise<RuntimeTerminalAgentStatus> {
const terminal = this.getTerminalAgentStatusSnapshot(handle)
const explicitStatus = this.getFreshExplicitAgentStatusForHandle(handle)
const blockedByWaitText = detectTerminalWaitBlockedReason(terminal.waitText)
const liveTitleClearsBlockedText =
terminal.titleStatusIsLive &&
terminal.titleStatus !== null &&
terminal.titleStatus !== 'permission'
if (terminal.titleStatus === 'permission' && terminal.titleStatusIsLive) {
return { handle, isRunningAgent: true, status: 'permission' }
}
if (
blockedByWaitText &&
!liveTitleClearsBlockedText &&
(!explicitStatus ||
explicitStatus.status === 'permission' ||
(terminal.waitBlockedAt !== null && terminal.waitBlockedAt >= explicitStatus.updatedAt))
) {
return { handle, isRunningAgent: true, status: 'permission' }
}
if (explicitStatus) {
// Why: permission titles can linger after hooks report the agent resumed.
// Fresh hook state is tighter, but current shell/management evidence wins.
const isRunningAgent =
!terminalTitleBlocksExplicitAgentStatus(terminal.title) &&
!(await this.terminalHasShellForegroundProcess(handle))
return {
handle,
isRunningAgent,
status: isRunningAgent ? explicitStatus.status : null
}
}
if (terminal.titleStatus) {
return { handle, isRunningAgent: true, status: terminal.titleStatus }
}
return {
handle,
isRunningAgent: await this.isTerminalRunningAgent(handle),
status: null
}
}
private getTerminalAgentStatusSnapshot(handle: string): {
waitText: string
waitBlockedAt: number | null
title: string | null
titleStatus: AgentStatus | null
titleStatusIsLive: boolean
} {
const pty = this.getLivePtyForHandle(handle)
if (pty) {
if (!pty.pty.connected) {
throw new Error('terminal_gone')
}
const leaf = this.getPrimaryLeafForPty(pty.pty.ptyId)
const leafTitle = leaf
? getLatestAgentCandidateTitleInfo(
{ title: leaf.paneTitle, updatedAt: leaf.paneTitleUpdatedAt },
{ title: leaf.lastOscTitle, updatedAt: leaf.lastOscTitleAt }
)
: null
const ptyTitle =
leafTitle ??
getLatestAgentCandidateTitleInfo(
{ title: pty.pty.title, updatedAt: pty.pty.titleUpdatedAt },
{ title: pty.pty.lastOscTitle, updatedAt: pty.pty.lastOscTitleAt }
)
const waitText = buildTerminalWaitText(
pty.pty.tailBuffer,
pty.pty.tailPartialLine,
pty.pty.preview
)
return {
waitText,
waitBlockedAt: pty.pty.waitBlockedAt,
title: ptyTitle?.title ?? null,
titleStatus: ptyTitle
? detectAgentStatusFromTitle(ptyTitle.title)
: pty.pty.lastAgentStatus,
titleStatusIsLive: ptyTitle !== null
}
}
const { leaf } = this.getLiveLeafForHandle(handle)
if (getTerminalState(leaf) !== 'running') {
throw new Error('terminal_exited')
}
if (!leaf.ptyId) {
throw new Error('terminal_gone')
}
const title = getLatestAgentCandidateTitleInfo(
{ title: leaf.paneTitle, updatedAt: leaf.paneTitleUpdatedAt },
{ title: leaf.lastOscTitle, updatedAt: leaf.lastOscTitleAt },
{ title: this.tabs.get(leaf.tabId)?.title, updatedAt: 0 }
)
return {
waitText: buildTerminalWaitText(leaf.tailBuffer, leaf.tailPartialLine, leaf.preview),
waitBlockedAt: leaf.waitBlockedAt,
title: title?.title ?? null,
titleStatus: title ? detectAgentStatusFromTitle(title.title) : leaf.lastAgentStatus,
titleStatusIsLive: (title?.updatedAt ?? 0) > 0
}
}
private async terminalHasShellForegroundProcess(handle: string): Promise<boolean> {
if (!this.ptyController) {
return false
}
try {
const pty = this.getLivePtyForHandle(handle)
const ptyId = pty?.pty.ptyId ?? this.getLiveLeafForHandle(handle).leaf.ptyId
if (!ptyId) {
return false
}
const foregroundProcess = await this.ptyController.getForegroundProcess(ptyId)
return foregroundProcess !== null && isShellProcess(foregroundProcess)
} catch {
return false
}
}
private getFreshExplicitAgentStatusForHandle(handle: string): {
status: NonNullable<RuntimeTerminalAgentStatus['status']>
updatedAt: number
} | null {
const paneKey = this.getPaneKeyForTerminalHandle(handle)
const now = Date.now()
let bestStatus: NonNullable<RuntimeTerminalAgentStatus['status']> | null = null
let bestUpdatedAt = -1
const consider = (
state: AgentStatusEntry['state'] | undefined,
updatedAt: number | null | undefined
): void => {
if (!state) {
return
}
if (typeof updatedAt !== 'number' || now - updatedAt > AGENT_STATUS_STALE_AFTER_MS) {
return
}
const status = mapExplicitAgentStateToRuntimeTerminalStatus(state)
// Why: older retained permission rows can remain visible after the agent
// resumes. Prefer the newest explicit state; only let permission win ties.
if (updatedAt > bestUpdatedAt || (updatedAt === bestUpdatedAt && status === 'permission')) {
bestStatus = status
bestUpdatedAt = updatedAt
}
}
if (paneKey) {
const retained = this.latestAgentStatusByPaneKey.get(paneKey)
consider(retained?.payload.state, retained?.updatedAt)
}
for (const entry of this.getAgentStatusSnapshotFn?.() ?? []) {
if (entry.terminalHandle !== handle && (!paneKey || entry.paneKey !== paneKey)) {
continue
}
consider(entry.state, entry.receivedAt)
}
return bestStatus ? { status: bestStatus, updatedAt: bestUpdatedAt } : null
}
private async writeTerminalAction(
ptyId: string,
action: { text?: string; enter?: boolean; interrupt?: boolean },
payload: string
payload: string,
options: {
beforeWrite?: (ptyId: string) => void | Promise<void>
suffixFailureError?: string
} = {}
): Promise<void> {
// Why: direct terminal.send can carry paste-sized text from RPC/mobile
// clients; chunk text before PTY/ConPTY while preserving suffix separation.
const hasText = typeof action.text === 'string' && action.text.length > 0
const hasSuffix = action.enter || action.interrupt
if (hasText) {
await this.writeTerminalInputChunks(ptyId, action.text!)
await this.writeTerminalInputChunks(ptyId, action.text!, options)
}
if (hasSuffix) {
const suffix = (action.enter ? '\r' : '') + (action.interrupt ? '\x03' : '')
if (hasText) {
await new Promise((resolve) => setTimeout(resolve, 500))
}
try {
await options.beforeWrite?.(ptyId)
} catch (error) {
if (options.suffixFailureError) {
throw new Error(options.suffixFailureError)
}
throw error
}
const suffixWrote = this.ptyController?.write(ptyId, suffix) ?? false
if (!suffixWrote) {
throw new Error('terminal_not_writable')
throw new Error(options.suffixFailureError ?? 'terminal_not_writable')
}
return
}
@@ -7958,16 +8172,24 @@ export class OrcaRuntimeService {
return
}
await options.beforeWrite?.(ptyId)
const wrote = this.ptyController?.write(ptyId, payload) ?? false
if (!wrote) {
throw new Error('terminal_not_writable')
}
}
private async writeTerminalInputChunks(ptyId: string, text: string): Promise<void> {
private async writeTerminalInputChunks(
ptyId: string,
text: string,
options: {
beforeWrite?: (ptyId: string) => void | Promise<void>
} = {}
): Promise<void> {
const chunks = iterateTerminalInputChunks(text)
let chunk = chunks.next()
while (!chunk.done) {
await options.beforeWrite?.(ptyId)
const wrote = this.ptyController?.write(ptyId, chunk.value) ?? false
if (!wrote) {
throw new Error('terminal_not_writable')
@@ -16125,7 +16347,8 @@ export class OrcaRuntimeService {
tailRedrawCursor: null,
tailTruncated: false,
tailLinesTotal: 0,
preview: state.preview ?? ''
preview: state.preview ?? '',
waitBlockedAt: null
}
if (state.title) {
this.setPtyManagementTitleFromObservedTitle(pty, state.title, titleObservedAt ?? 0)
@@ -16245,6 +16468,7 @@ export class OrcaRuntimeService {
pty.tailRedrawCursor = null
pty.tailTruncated = false
pty.tailLinesTotal = 0
pty.waitBlockedAt = null
}
private pruneDisconnectedPtyRecords(): void {
@@ -16927,16 +17151,7 @@ export class OrcaRuntimeService {
// status without throwing on stale handles, so this returns null on any error.
getAgentStatusForHandle(handle: string): string | null {
try {
const { leaf } = this.getLiveLeafForHandle(handle)
const title = getLatestAgentCandidateTitle(
{ title: leaf.paneTitle, updatedAt: leaf.paneTitleUpdatedAt },
{ title: leaf.lastOscTitle, updatedAt: leaf.lastOscTitleAt },
{ title: this.tabs.get(leaf.tabId)?.title, updatedAt: 0 }
)
if (title) {
return detectAgentStatusFromTitle(title)
}
return leaf.lastAgentStatus
return this.getTerminalAgentStatusSnapshot(handle).titleStatus
} catch {
return null
}
@@ -21500,6 +21715,36 @@ function isKnownReadyPromptPreview(preview: string): boolean {
function detectTerminalWaitBlockedReason(preview: string): RuntimeTerminalWaitBlockedReason | null {
const normalized = preview.toLowerCase()
return findActionableTerminalWaitBlockedSignal(normalized)?.reason ?? null
}
function nextTailHasNewerBlockedReason(
previousWaitText: string,
nextWaitText: string,
appendedText: string
): boolean {
const nextBlockedSignal = findActionableTerminalWaitBlockedSignal(nextWaitText.toLowerCase())
if (!nextBlockedSignal) {
return false
}
// Why: permission prompts can arrive split across PTY chunks. Stamp the
// blocked signal when the accumulated tail first becomes blocked, or when
// a later prompt appears after stale blocked text already in the tail.
const previousBlockedSignal = findActionableTerminalWaitBlockedSignal(
previousWaitText.toLowerCase()
)
if (previousBlockedSignal === null) {
return true
}
const appendCandidateSignal = findActionableTerminalWaitBlockedSignal(
`${previousWaitText}${appendedText}`.toLowerCase()
)
return appendCandidateSignal !== null && appendCandidateSignal.index > previousBlockedSignal.index
}
function findActionableTerminalWaitBlockedSignal(
normalized: string
): { reason: RuntimeTerminalWaitBlockedReason; index: number } | null {
const blockedSignal = findTerminalWaitBlockedSignal(normalized)
if (blockedSignal === null) {
return null
@@ -21507,10 +21752,7 @@ function detectTerminalWaitBlockedReason(preview: string): RuntimeTerminalWaitBl
const readyIndex = findKnownReadyPromptIndex(normalized)
// Why: retained terminal tails can include stale startup modals. If a known
// ready prompt appears after that modal, the latest signal is ready.
if (readyIndex !== null && readyIndex > blockedSignal.index) {
return null
}
return blockedSignal.reason
return readyIndex !== null && readyIndex > blockedSignal.index ? null : blockedSignal
}
function findKnownReadyPromptIndex(normalized: string): number | null {
@@ -21581,24 +21823,25 @@ function isTerminalWaitWhitespace(value: string, index: number): boolean {
function findTerminalWaitBlockedSignal(
normalized: string
): { reason: RuntimeTerminalWaitBlockedReason; index: number } | null {
const candidates: { reason: RuntimeTerminalWaitBlockedReason; index: number }[] = []
const updateIndex = normalized.lastIndexOf('update available')
if (updateIndex !== -1 && normalized.includes('press enter to continue', updateIndex)) {
return { reason: 'codex-update-prompt', index: updateIndex }
candidates.push({ reason: 'codex-update-prompt', index: updateIndex })
}
const cwdIndex = normalized.lastIndexOf('choose working directory to')
if (cwdIndex !== -1 && normalized.includes('press enter to continue', cwdIndex)) {
return { reason: 'codex-cwd-prompt', index: cwdIndex }
candidates.push({ reason: 'codex-cwd-prompt', index: cwdIndex })
}
const modelMigrationIndex = normalized.lastIndexOf('codex just got an upgrade')
if (
modelMigrationIndex !== -1 &&
normalized.includes('press enter to continue', modelMigrationIndex)
) {
return { reason: 'codex-model-migration-prompt', index: modelMigrationIndex }
candidates.push({ reason: 'codex-model-migration-prompt', index: modelMigrationIndex })
}
const hooksIndex = normalized.lastIndexOf('hooks need review')
if (hooksIndex !== -1 && normalized.includes('press enter to confirm', hooksIndex)) {
return { reason: 'codex-hooks-review-prompt', index: hooksIndex }
candidates.push({ reason: 'codex-hooks-review-prompt', index: hooksIndex })
}
const trustIndex = Math.max(
normalized.lastIndexOf('do you trust'),
@@ -21613,7 +21856,7 @@ function findTerminalWaitBlockedSignal(
trustSegment.includes('directory') ||
trustSegment.includes('repo'))
) {
return { reason: 'codex-trust-workspace', index: trustIndex }
candidates.push({ reason: 'codex-trust-workspace', index: trustIndex })
}
const interactivePromptIndex = Math.max(
normalized.lastIndexOf('press enter to confirm'),
@@ -21633,9 +21876,19 @@ function findTerminalWaitBlockedSignal(
interactivePromptContext.includes('trust') ||
interactivePromptContext.includes('hook')
if (interactivePromptIndex !== -1 && hasCodexInteractiveContext) {
return { reason: 'codex-interactive-prompt', index: interactivePromptIndex }
const contextStart = Math.max(0, interactivePromptIndex - 600)
const hasSpecificPromptInContext = candidates.some(
(candidate) => candidate.index >= contextStart && candidate.index <= interactivePromptIndex
)
if (!hasSpecificPromptInContext) {
candidates.push({ reason: 'codex-interactive-prompt', index: interactivePromptIndex })
}
}
return null
return candidates.length > 0
? candidates.reduce((latest, candidate) =>
candidate.index > latest.index ? candidate : latest
)
: null
}
function buildTerminalWaitResult(
@@ -21819,9 +22072,22 @@ function classifyAgentTitle(title: string | null): 'agent' | 'management' | 'neu
return detectAgentStatusFromTitle(title) !== null ? 'agent' : 'neutral'
}
function terminalTitleBlocksExplicitAgentStatus(title: string | null): boolean {
if (!title) {
return false
}
return isClaudeManagementTitle(title) || isShellProcess(title)
}
function getLatestAgentCandidateTitle(
...titles: { title: string | null | undefined; updatedAt: number | null | undefined }[]
): string | null {
return getLatestAgentCandidateTitleInfo(...titles)?.title ?? null
}
function getLatestAgentCandidateTitleInfo(
...titles: { title: string | null | undefined; updatedAt: number | null | undefined }[]
): { title: string; updatedAt: number } | null {
let latest: { title: string; updatedAt: number } | null = null
for (const candidate of titles) {
const title = candidate.title?.trim()
@@ -21833,7 +22099,7 @@ function getLatestAgentCandidateTitle(
latest = { title, updatedAt }
}
}
return latest?.title ?? null
return latest
}
function getSavedTabWorktreeStatus(title: string, hasPty: boolean): RuntimeWorktreeStatus {
@@ -21853,6 +22119,20 @@ function getDetectedWorktreeStatus(
return hasPty ? 'active' : 'inactive'
}
function mapExplicitAgentStateToRuntimeTerminalStatus(
state: AgentStatusEntry['state']
): NonNullable<RuntimeTerminalAgentStatus['status']> {
switch (state) {
case 'blocked':
case 'waiting':
return 'permission'
case 'working':
return 'working'
case 'done':
return 'idle'
}
}
function mergeWorktreeStatus(
current: RuntimeWorktreeStatus,
next: RuntimeWorktreeStatus
+115 -5
View File
@@ -287,6 +287,22 @@ function resolveMobileFloorClientId(
return null
}
function getTerminalSendGuardRefusedReason(error: unknown): 'no-agent' | 'permission' | undefined {
const message = error instanceof Error ? error.message : String(error)
if (message.includes('terminal_guard_permission')) {
return 'permission'
}
if (message.includes('terminal_guard_no_agent')) {
return 'no-agent'
}
return undefined
}
function isTerminalSendGuardNotWritable(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error)
return message.includes('terminal_guard_not_writable')
}
function appendPendingMultiplexOutput(
stream: TerminalMultiplexStream,
data: string,
@@ -567,6 +583,7 @@ const TerminalSend = TerminalHandle.extend({
text: OptionalString,
enter: z.unknown().optional(),
interrupt: z.unknown().optional(),
requireAgentStatus: z.enum(['sendable']).optional(),
// Why: identifies the caller for the driver state machine. Optional for
// backward compatibility with older mobile clients (server falls back to
// the most recent mobile actor when absent). New mobile builds populate
@@ -808,6 +825,13 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
isRunningAgent: await runtime.isTerminalRunningAgent(params.terminal)
})
}),
defineMethod({
name: 'terminal.agentStatus',
params: TerminalHandle,
handler: async (params, { runtime }) => ({
agentStatus: await runtime.getTerminalAgentStatus(params.terminal)
})
}),
defineMethod({
name: 'terminal.rename',
params: TerminalRename,
@@ -838,11 +862,97 @@ export const TERMINAL_METHODS: RpcAnyMethod[] = [
}
}
}
const result = await runtime.sendTerminal(params.terminal, {
text: params.text,
enter: params.enter === true,
interrupt: params.interrupt === true
})
const hasText = typeof params.text === 'string' && params.text.length > 0
const hasSuffix = params.enter === true || params.interrupt === true
if (params.requireAgentStatus === 'sendable' && hasText && hasSuffix) {
// Why: guarded sends are two-phase writes. Reject combined payload +
// submit so guard flips cannot create ambiguous partial delivery.
return {
send: {
handle: params.terminal,
accepted: false,
bytesWritten: 0
}
}
}
// Why: selected note sends submit with Enter. The runtime must recheck
// permission/no-agent state immediately before accepting the PTY write.
const assertSendPreconditions =
params.requireAgentStatus === 'sendable'
? async (ptyId?: string): Promise<void> => {
if (ptyId && isTerminalInputLockedForClient(runtime, ptyId, params.client)) {
throw new Error('terminal_guard_not_writable')
}
const agentStatus = await runtime.getTerminalAgentStatus(params.terminal)
if (!agentStatus.isRunningAgent) {
throw new Error('terminal_guard_no_agent')
}
if (agentStatus.status === 'permission') {
throw new Error('terminal_guard_permission')
}
}
: undefined
if (params.requireAgentStatus === 'sendable') {
try {
await assertSendPreconditions?.(leaf?.ptyId ?? undefined)
} catch (error) {
if (isTerminalSendGuardNotWritable(error)) {
return {
send: {
handle: params.terminal,
accepted: false,
bytesWritten: 0
}
}
}
const refusedReason = getTerminalSendGuardRefusedReason(error)
if (!refusedReason) {
throw error
}
return {
send: {
handle: params.terminal,
accepted: false,
bytesWritten: 0,
refusedReason
}
}
}
}
let result
try {
result = await runtime.sendTerminal(
params.terminal,
{
text: params.text,
enter: params.enter === true,
interrupt: params.interrupt === true
},
{ beforeWrite: assertSendPreconditions }
)
} catch (error) {
const refusedReason = getTerminalSendGuardRefusedReason(error)
if (refusedReason) {
return {
send: {
handle: params.terminal,
accepted: false,
bytesWritten: 0,
refusedReason
}
}
}
if (isTerminalSendGuardNotWritable(error)) {
return {
send: {
handle: params.terminal,
accepted: false,
bytesWritten: 0
}
}
}
throw error
}
// Why: deliberate mobile input is a take-floor action. Drives the
// `* → mobile{clientId}` driver transition so the desktop banner
// remounts (if previously reclaimed) and active phone-fit dims follow
+203 -9
View File
@@ -45,6 +45,36 @@ describe('terminal send RPC', () => {
expect(runtime.isTerminalRunningAgent).toHaveBeenCalledWith('terminal-1')
})
it('reports runtime-owned terminal agent status', async () => {
const runtime = stubRuntime({
getTerminalAgentStatus: vi.fn().mockResolvedValue({
handle: 'terminal-1',
isRunningAgent: true,
status: 'permission'
})
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const response = await dispatcher.dispatch(
makeRequest('terminal.agentStatus', {
terminal: 'terminal-1'
})
)
expect(response.ok).toBe(true)
if (!response.ok) {
throw new Error(response.error.message)
}
expect(response.result).toEqual({
agentStatus: {
handle: 'terminal-1',
isRunningAgent: true,
status: 'permission'
}
})
expect(runtime.getTerminalAgentStatus).toHaveBeenCalledWith('terminal-1')
})
it('drops desktop input while a mobile client owns the terminal floor', async () => {
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
@@ -102,11 +132,15 @@ describe('terminal send RPC', () => {
throw new Error(response.error.message)
}
expect(response.result).toMatchObject({ send: { accepted: true, bytesWritten: 1 } })
expect(runtime.sendTerminal).toHaveBeenCalledWith('terminal-1', {
text: 'x',
enter: false,
interrupt: false
})
expect(runtime.sendTerminal).toHaveBeenCalledWith(
'terminal-1',
{
text: 'x',
enter: false,
interrupt: false
},
{ beforeWrite: undefined }
)
expect(runtime.mobileTookFloor).toHaveBeenCalledWith('pty-1', 'mobile-1')
})
@@ -189,10 +223,170 @@ describe('terminal send RPC', () => {
ok: true,
result: { send: { accepted: true } }
})
expect(runtime.sendTerminal).toHaveBeenCalledWith('terminal-1', {
text,
enter: false,
interrupt: false
expect(runtime.sendTerminal).toHaveBeenCalledWith(
'terminal-1',
{
text,
enter: false,
interrupt: false
},
{ beforeWrite: undefined }
)
})
it('refuses guarded terminal sends when the agent needs permission', async () => {
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }),
getTerminalAgentStatus: vi.fn().mockResolvedValue({
handle: 'terminal-1',
isRunningAgent: true,
status: 'permission'
}),
sendTerminal: vi.fn()
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const response = await dispatcher.dispatch(
makeRequest('terminal.send', {
terminal: 'terminal-1',
enter: true,
requireAgentStatus: 'sendable',
client: { id: 'desktop-1', type: 'desktop' }
})
)
expect(response.ok).toBe(true)
if (!response.ok) {
throw new Error(response.error.message)
}
expect(response.result).toEqual({
send: {
handle: 'terminal-1',
accepted: false,
bytesWritten: 0,
refusedReason: 'permission'
}
})
expect(runtime.getTerminalAgentStatus).toHaveBeenCalledWith('terminal-1')
expect(runtime.sendTerminal).not.toHaveBeenCalled()
})
it('allows guarded terminal sends when the agent is sendable', async () => {
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }),
getTerminalAgentStatus: vi.fn().mockResolvedValue({
handle: 'terminal-1',
isRunningAgent: true,
status: 'working'
}),
sendTerminal: vi.fn().mockResolvedValue({
handle: 'terminal-1',
accepted: true,
bytesWritten: 1
})
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const response = await dispatcher.dispatch(
makeRequest('terminal.send', {
terminal: 'terminal-1',
enter: true,
requireAgentStatus: 'sendable',
client: { id: 'desktop-1', type: 'desktop' }
})
)
expect(response.ok).toBe(true)
if (!response.ok) {
throw new Error(response.error.message)
}
expect(response.result).toMatchObject({ send: { accepted: true, bytesWritten: 1 } })
expect(runtime.sendTerminal).toHaveBeenCalledWith(
'terminal-1',
{
text: undefined,
enter: true,
interrupt: false
},
{ beforeWrite: expect.any(Function) }
)
})
it('refuses guarded combined text and submit sends before any PTY write', async () => {
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
getDriver: vi.fn().mockReturnValue({ kind: 'desktop' }),
getTerminalAgentStatus: vi.fn(),
sendTerminal: vi.fn()
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const response = await dispatcher.dispatch(
makeRequest('terminal.send', {
terminal: 'terminal-1',
text: 'notes',
enter: true,
requireAgentStatus: 'sendable',
client: { id: 'desktop-1', type: 'desktop' }
})
)
expect(response.ok).toBe(true)
if (!response.ok) {
throw new Error(response.error.message)
}
expect(response.result).toEqual({
send: {
handle: 'terminal-1',
accepted: false,
bytesWritten: 0
}
})
expect(runtime.getTerminalAgentStatus).not.toHaveBeenCalled()
expect(runtime.sendTerminal).not.toHaveBeenCalled()
})
it('rechecks the mobile floor lock immediately before guarded PTY writes', async () => {
const runtime = stubRuntime({
resolveLeafForHandle: vi.fn().mockReturnValue({ ptyId: 'pty-1' }),
getDriver: vi
.fn()
.mockReturnValueOnce({ kind: 'desktop' })
.mockReturnValueOnce({ kind: 'desktop' })
.mockReturnValue({ kind: 'mobile', clientId: 'mobile-1' }),
getTerminalAgentStatus: vi.fn().mockResolvedValue({
handle: 'terminal-1',
isRunningAgent: true,
status: 'working'
}),
sendTerminal: vi.fn().mockImplementation(async (_handle, _action, options) => {
await options.beforeWrite('pty-1')
return { handle: 'terminal-1', accepted: true, bytesWritten: 1 }
})
})
const dispatcher = new RpcDispatcher({ runtime, methods: TERMINAL_METHODS })
const response = await dispatcher.dispatch(
makeRequest('terminal.send', {
terminal: 'terminal-1',
enter: true,
requireAgentStatus: 'sendable',
client: { id: 'desktop-1', type: 'desktop' }
})
)
expect(response.ok).toBe(true)
if (!response.ok) {
throw new Error(response.error.message)
}
expect(response.result).toEqual({
send: {
handle: 'terminal-1',
accepted: false,
bytesWritten: 0
}
})
})
+1
View File
@@ -316,6 +316,7 @@ const MOBILE_RPC_METHOD_ALLOWLIST = new Set([
'terminal.close',
'terminal.create',
'terminal.focus',
'terminal.agentStatus',
'terminal.getAutoRestoreFit',
'terminal.isRunningAgent',
'terminal.list',
@@ -83,7 +83,8 @@ describe('formatBrowserAnnotationsAsMarkdown', () => {
expect(markdown).toContain('## Design Feedback: /pricing')
expect(markdown).toContain('**Browser tab id:** page-1')
expect(markdown).toContain('**Orca CLI:** Use `--page page-1` to target this browser tab.')
expect(markdown).not.toContain('Orca CLI')
expect(markdown).not.toContain('--page page-1')
expect(markdown).not.toContain('Page Feedback')
expect(markdown).toContain('**Selector:** `main.pricing > button.primary`')
expect(markdown).toContain('**Source:** src/components/PricingCta.tsx:42:8')
@@ -164,7 +164,6 @@ export function formatBrowserAnnotationsAsMarkdown(annotations: BrowserPageAnnot
'',
`**URL:** ${first.page.sanitizedUrl}`,
`**Browser tab id:** ${firstAnnotation.browserPageId}`,
`**Orca CLI:** Use ${inlineCode(`--page ${firstAnnotation.browserPageId}`)} to target this browser tab.`,
`**Viewport:** ${first.page.viewportWidth}x${first.page.viewportHeight}`,
''
]
@@ -26,6 +26,7 @@ const harness = vi.hoisted(() => ({
storeState: {} as Record<string, unknown>,
sendNotesToActiveAgentSession: vi.fn(),
track: vi.fn(),
toastMessage: vi.fn(),
worktreeAgentRows: [] as DashboardAgentRowData[],
noteTargets: [] as {
paneKey: string
@@ -73,8 +74,12 @@ vi.mock('react', async () => {
})
vi.mock('@/store', () => ({
useAppStore: (selector: (state: Record<string, unknown>) => unknown) =>
selector(harness.storeState)
useAppStore: Object.assign(
(selector: (state: Record<string, unknown>) => unknown) => selector(harness.storeState),
{
getState: () => harness.storeState
}
)
}))
vi.mock('zustand/react/shallow', () => ({
@@ -82,7 +87,10 @@ vi.mock('zustand/react/shallow', () => ({
}))
vi.mock('@/lib/active-agent-note-send', () => ({
activeAgentNotesSendFailureMessage: (status: string) => status,
activeAgentNotesSendFailureMessage: (
status: string,
options: { explicitTarget?: boolean } = {}
) => (options.explicitTarget ? `selected:${status}` : status),
sendNotesToActiveAgentSession: harness.sendNotesToActiveAgentSession,
useCanSendNotesToActiveTerminal: () => true
}))
@@ -158,7 +166,7 @@ vi.mock('sonner', () => ({
dismiss: vi.fn(),
error: vi.fn(),
loading: vi.fn(() => 'toast-id'),
message: vi.fn(),
message: harness.toastMessage,
success: vi.fn()
}
}))
@@ -336,6 +344,7 @@ describe('ReviewNotesSendMenuContent', () => {
harness.sendNotesToActiveAgentSession.mockReset()
harness.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' })
harness.track.mockReset()
harness.toastMessage.mockReset()
harness.worktreeAgentRows = []
harness.noteTargets = []
harness.now = 600_000
@@ -442,7 +451,7 @@ describe('ReviewNotesSendMenuContent', () => {
expect(collectText(items[1])).toContain('Claude')
})
it('can target a title-detected agent row that has not reported hook status yet', async () => {
it('does not target title-detected rows skipped by target derivation', async () => {
const paneKey = makePaneKey(TAB_B, LEAF_B)
harness.worktreeAgentRows = [
agentRow({
@@ -461,17 +470,48 @@ describe('ReviewNotesSendMenuContent', () => {
})
const tree = render()
const item = findByType(tree, 'DropdownMenuItem')
;(item.props.onSelect as () => void)()
await flushMicrotasks()
const items = findAllByType(tree, 'DropdownMenuItem')
expect(collectText(item)).toContain('Codex')
expect(collectText(item)).toContain('Idle')
expect(harness.sendNotesToActiveAgentSession).toHaveBeenCalledWith({
worktreeId: 'wt-1',
prompt: 'my notes',
noteTarget: { tabId: TAB_B, leafId: LEAF_B }
expect(items).toHaveLength(0)
expect(harness.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
})
it('disables title-detected dashboard rows when target derivation reports permission', () => {
const paneKey = makePaneKey(TAB_B, LEAF_B)
harness.worktreeAgentRows = [
agentRow({
paneKey,
tabId: TAB_B,
title: 'Codex',
agentType: 'codex',
state: 'blocked',
startedAt: harness.now
})
]
setStore({
tabsByWorktree: { 'wt-1': [tab(TAB_B, { title: 'Codex' })] },
terminalLayoutsByTabId: { [TAB_B]: leafLayout(LEAF_B, 'pty-b') },
ptyIdsByTabId: { [TAB_B]: ['pty-b'] }
})
harness.noteTargets = [
{
paneKey,
tabId: TAB_B,
leafId: LEAF_B,
agentType: 'codex',
tabTitle: 'Codex',
status: 'disabled',
disabledReason: 'Agent needs permission'
}
]
const tree = render()
const item = findByType(tree, 'DropdownMenuItem')
expect(item.props.disabled).toBe(true)
expect(item.props.title).toBe('Agent needs permission')
;(item.props.onSelect as () => void)()
expect(harness.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
})
it('does not offer a title-detected agent row after its live PTY has exited', () => {
@@ -589,8 +629,10 @@ describe('ReviewNotesSendMenuContent', () => {
})
})
it('disables a working agent and never sends to it', () => {
it('keeps selected-target note failures undelivered and uses selected wording', async () => {
const statusPaneKey = makePaneKey(TAB_A, LEAF_A)
const onPromptDelivered = vi.fn()
harness.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'not-ready' })
setStore({
tabsByWorktree: { 'wt-1': [tab(TAB_A, { title: 'Terminal 1' })] },
terminalLayoutsByTabId: { [TAB_A]: leafLayout(LEAF_A, 'pty-a') }
@@ -602,18 +644,147 @@ describe('ReviewNotesSendMenuContent', () => {
leafId: LEAF_A,
agentType: 'claude',
tabTitle: 'Terminal 1',
status: 'disabled',
disabledReason: 'Agent is working'
status: 'eligible'
}
]
const tree = render({ onPromptDelivered })
;(findByType(tree, 'DropdownMenuItem').props.onSelect as () => void)()
await flushMicrotasks()
expect(onPromptDelivered).not.toHaveBeenCalled()
expect(harness.track).not.toHaveBeenCalled()
expect(harness.toastMessage).toHaveBeenCalledWith('selected:not-ready')
})
it('keeps selected-target thrown send errors undelivered', async () => {
const statusPaneKey = makePaneKey(TAB_A, LEAF_A)
const onPromptDelivered = vi.fn()
harness.sendNotesToActiveAgentSession.mockRejectedValue(new Error('runtime unavailable'))
setStore({
tabsByWorktree: { 'wt-1': [tab(TAB_A, { title: 'Terminal 1' })] },
terminalLayoutsByTabId: { [TAB_A]: leafLayout(LEAF_A, 'pty-a') }
})
harness.noteTargets = [
{
paneKey: statusPaneKey,
tabId: TAB_A,
leafId: LEAF_A,
agentType: 'claude',
tabTitle: 'Terminal 1',
status: 'eligible'
}
]
const tree = render({ onPromptDelivered })
;(findByType(tree, 'DropdownMenuItem').props.onSelect as () => void)()
await flushMicrotasks()
expect(onPromptDelivered).not.toHaveBeenCalled()
expect(harness.track).not.toHaveBeenCalled()
})
it('revalidates the chosen target at click time and refuses stale rows', async () => {
const statusPaneKey = makePaneKey(TAB_A, LEAF_A)
setStore({
tabsByWorktree: { 'wt-1': [tab(TAB_A, { title: 'Terminal 1' })] },
terminalLayoutsByTabId: { [TAB_A]: leafLayout(LEAF_A, 'pty-a') },
ptyIdsByTabId: { [TAB_A]: ['pty-a'] }
})
harness.noteTargets = [
{
paneKey: statusPaneKey,
tabId: TAB_A,
leafId: LEAF_A,
agentType: 'claude',
tabTitle: 'Terminal 1',
status: 'eligible'
}
]
const tree = render()
harness.noteTargets = [
{
paneKey: statusPaneKey,
tabId: TAB_A,
leafId: LEAF_A,
agentType: 'claude',
tabTitle: 'Terminal 1',
status: 'disabled',
disabledReason: 'Agent status is stale'
}
]
;(findByType(tree, 'DropdownMenuItem').props.onSelect as () => void)()
expect(harness.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
expect(harness.toastMessage).toHaveBeenCalledWith('Agent status is stale')
})
it('refuses stale menu targets that disappear from target derivation before click', () => {
const statusPaneKey = makePaneKey(TAB_A, LEAF_A)
setStore({
tabsByWorktree: { 'wt-1': [tab(TAB_A, { title: 'Terminal 1' })] },
terminalLayoutsByTabId: { [TAB_A]: leafLayout(LEAF_A, 'pty-a') },
ptyIdsByTabId: { [TAB_A]: ['pty-a'] }
})
harness.noteTargets = [
{
paneKey: statusPaneKey,
tabId: TAB_A,
leafId: LEAF_A,
agentType: 'claude',
tabTitle: 'Terminal 1',
status: 'eligible'
}
]
const tree = render()
harness.noteTargets = []
;(findByType(tree, 'DropdownMenuItem').props.onSelect as () => void)()
expect(harness.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
expect(harness.toastMessage).toHaveBeenCalledWith('Terminal is no longer available')
})
it('keeps a working agent selectable and preserves the Working state text', async () => {
const statusPaneKey = makePaneKey(TAB_A, LEAF_A)
setStore({
tabsByWorktree: { 'wt-1': [tab(TAB_A, { title: 'Terminal 1' })] },
terminalLayoutsByTabId: { [TAB_A]: leafLayout(LEAF_A, 'pty-a') },
ptyIdsByTabId: { [TAB_A]: ['pty-a'] }
})
harness.noteTargets = [
{
paneKey: statusPaneKey,
tabId: TAB_A,
leafId: LEAF_A,
agentType: 'claude',
tabTitle: 'Terminal 1',
status: 'eligible'
}
]
harness.worktreeAgentRows = [
agentRow({
paneKey: statusPaneKey,
tabId: TAB_A,
title: 'Terminal 1',
agentType: 'claude',
state: 'working'
})
]
const tree = render()
const item = findByType(tree, 'DropdownMenuItem')
expect(item.props.disabled).toBe(true)
expect(item.props.title).toBe('Agent is working')
expect(item.props.disabled).toBe(false)
expect(collectText(item)).toContain('Working')
;(item.props.onSelect as () => void)()
expect(harness.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
await flushMicrotasks()
expect(harness.sendNotesToActiveAgentSession).toHaveBeenCalledWith({
worktreeId: 'wt-1',
prompt: 'my notes',
noteTarget: { tabId: TAB_A, leafId: LEAF_A }
})
})
it('does not render an active agent fallback when no agents are derived', () => {
@@ -27,7 +27,6 @@ import { useNow } from '@/components/dashboard/useNow'
import type { DashboardAgentRow as DashboardAgentRowData } from '@/components/dashboard/useDashboardData'
import { selectLivePtyIdsForWorktree } from '@/components/sidebar/worktree-card-status-inputs'
import { useWorktreeAgentRows } from '@/components/sidebar/useWorktreeAgentRows'
import { parsePaneKey } from '../../../../shared/stable-pane-id'
import type { LaunchSource } from '../../../../shared/telemetry-events'
import type { AgentStatusState } from '../../../../shared/agent-status-types'
import { translate } from '@/i18n/i18n'
@@ -89,18 +88,16 @@ export function ReviewNotesSendMenuContent({
worktreeId
])
const orderedSendTargets = useMemo(
() =>
orderSendTargetsByWorktreeAgentRows(
sendTargets,
agentRows,
terminalLayoutsByTabId,
ptyIdsByTabId
),
[agentRows, sendTargets, terminalLayoutsByTabId, ptyIdsByTabId]
() => orderSendTargetsByWorktreeAgentRows(sendTargets, agentRows),
[agentRows, sendTargets]
)
const runNotesSend = useCallback(
(send: () => Promise<ActiveAgentNotesSendResult>, onSent: () => void) => {
(
send: () => Promise<ActiveAgentNotesSendResult>,
onSent: () => void,
options: { explicitTarget?: boolean } = {}
) => {
const pending = toast.loading(
translate(
'auto.components.editor.ReviewNotesSendMenuContent.50f7e753ea',
@@ -121,7 +118,11 @@ export function ReviewNotesSendMenuContent({
return
}
toast.message(activeAgentNotesSendFailureMessage(result.status))
toast.message(
activeAgentNotesSendFailureMessage(result.status, {
explicitTarget: options.explicitTarget
})
)
})
.catch((error) => {
console.error('Failed to send notes:', error)
@@ -145,6 +146,12 @@ export function ReviewNotesSendMenuContent({
return
}
const currentEligibility = resolveCurrentSendTargetEligibility(target, worktreeId)
if (currentEligibility.status !== 'eligible') {
toast.message(currentEligibility.disabledReason)
return
}
runNotesSend(
() =>
sendNotesToActiveAgentSession({
@@ -161,7 +168,8 @@ export function ReviewNotesSendMenuContent({
launch_source: launchSource,
request_kind: 'followup'
})
}
},
{ explicitTarget: true }
)
},
[hasPrompt, runNotesSend, worktreeId, prompt, onPromptDelivered, launchSource]
@@ -199,6 +207,26 @@ export function ReviewNotesSendMenuContent({
)
}
function resolveCurrentSendTargetEligibility(
target: NotesSendAgentTarget,
worktreeId: string
): { status: 'eligible' } | { status: 'disabled'; disabledReason: string } {
const state = useAppStore.getState()
const currentTarget = deriveNotesSendAgentTargets(state, worktreeId).find(
(candidate) => candidate.paneKey === target.paneKey
)
if (currentTarget) {
return currentTarget.status === 'eligible'
? { status: 'eligible' }
: {
status: 'disabled',
disabledReason: currentTarget.disabledReason ?? 'Terminal is no longer available'
}
}
return { status: 'disabled', disabledReason: 'Terminal is no longer available' }
}
function AgentTargetMenuItem({
target,
agent,
@@ -224,7 +252,7 @@ function AgentTargetMenuItem({
<DropdownMenuItem
disabled={disabled}
onSelect={() => onSend(target)}
// Why: surface the ineligibility reason (working/stale/no-terminal) as a
// Why: surface the ineligibility reason (permission/stale/no-terminal) as a
// hover tooltip rather than inline text, matching DashboardAgentRow's
// title-attribute treatment of the same disabledReason.
title={target.status === 'disabled' ? target.disabledReason : undefined}
@@ -246,18 +274,14 @@ function AgentTargetMenuItem({
function orderSendTargetsByWorktreeAgentRows(
sendTargets: NotesSendAgentTarget[],
agentRows: DashboardAgentRowData[],
terminalLayoutsByTabId: Record<string, { ptyIdsByLeafId?: Record<string, string> } | undefined>,
ptyIdsByTabId: Record<string, string[]>
agentRows: DashboardAgentRowData[]
): OrderedSendTarget[] {
const targetsByPaneKey = new Map(sendTargets.map((target) => [target.paneKey, target]))
const usedPaneKeys = new Set<string>()
const ordered: OrderedSendTarget[] = []
for (const agent of agentRows) {
const target =
targetsByPaneKey.get(agent.paneKey) ??
deriveTitleOnlySendTarget(agent, terminalLayoutsByTabId, ptyIdsByTabId)
const target = targetsByPaneKey.get(agent.paneKey)
if (!target) {
continue
}
@@ -274,31 +298,6 @@ function orderSendTargetsByWorktreeAgentRows(
return ordered
}
function deriveTitleOnlySendTarget(
agent: DashboardAgentRowData,
terminalLayoutsByTabId: Record<string, { ptyIdsByLeafId?: Record<string, string> } | undefined>,
ptyIdsByTabId: Record<string, string[]>
): NotesSendAgentTarget | null {
const parsed = parsePaneKey(agent.paneKey)
if (!parsed) {
return null
}
const ptyId = terminalLayoutsByTabId[parsed.tabId]?.ptyIdsByLeafId?.[parsed.leafId] ?? null
if (!ptyId || !ptyIdsByTabId[parsed.tabId]?.includes(ptyId)) {
return null
}
const disabledReason = agent.state === 'working' ? 'Agent is working' : undefined
return {
paneKey: agent.paneKey,
tabId: parsed.tabId,
leafId: parsed.leafId,
agentType: agent.agentType,
tabTitle: agent.tab.title,
status: disabledReason ? 'disabled' : 'eligible',
...(disabledReason ? { disabledReason } : {})
}
}
function asDotState(state: AgentStatusState | 'idle'): AgentDotState {
switch (state) {
case 'working':
@@ -65,6 +65,14 @@ function targetStoreState(now: number): Record<string, unknown> {
},
terminalLayoutsByTabId: {
'tab-1': {
root: {
type: 'split',
direction: 'horizontal',
first: { type: 'leaf', leafId: '11111111-1111-4111-8111-111111111111' },
second: { type: 'leaf', leafId: '22222222-2222-4222-8222-222222222222' }
},
activeLeafId: '11111111-1111-4111-8111-111111111111',
expandedLeafId: null,
ptyIdsByLeafId: {
'11111111-1111-4111-8111-111111111111': 'pty-1',
'22222222-2222-4222-8222-222222222222': 'pty-2'
@@ -73,7 +81,8 @@ function targetStoreState(now: number): Record<string, unknown> {
},
ptyIdsByTabId: {
'tab-1': ['pty-1', 'pty-2']
}
},
runtimePaneTitlesByTabId: {}
}
}
@@ -91,6 +100,7 @@ vi.mock('@/store', () => ({
tabsByWorktree: {},
terminalLayoutsByTabId: {},
ptyIdsByTabId: {},
runtimePaneTitlesByTabId: {},
sendPromptToSidebarAgentTarget: mockSendPromptToSidebarAgentTarget,
...mockStoreState
})
@@ -146,19 +156,38 @@ describe('WorktreeCardAgents send targets', () => {
}
})
it('marks eligible active-worktree rows and disables working send targets', async () => {
it('marks eligible active-worktree rows including working send targets', async () => {
const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents')
const markup = renderToStaticMarkup(<WorktreeCardAgents worktreeId="wt-1" />)
expect(markup).toContain('data-agent-send-target="eligible"')
expect(markup).toContain(`data-pane-key="${READY_PANE_KEY}"`)
expect(markup).toContain('data-agent-send-target="disabled"')
expect(markup).toContain('data-disabled-reason="Agent is working"')
expect(markup).toContain(`data-pane-key="${WORKING_PANE_KEY}"`)
expect(markup).toContain('data-has-send-handler="true"')
}, 30_000)
it('disables rows whose live pane title needs permission', async () => {
const now = Date.now()
mockAgents = [agentRow(WORKING_PANE_KEY, 'working', now)]
mockStoreState = {
...targetStoreState(now),
runtimePaneTitlesByTabId: {
'tab-1': {
2: 'Codex - action required'
}
},
agentSendPopoverTargetMode: activeTargetMode()
}
const { default: WorktreeCardAgents } = await import('./WorktreeCardAgents')
const markup = renderToStaticMarkup(<WorktreeCardAgents worktreeId="wt-1" />)
expect(markup).toContain('data-agent-send-target="disabled"')
expect(markup).toContain('data-disabled-reason="Agent needs permission"')
expect(markup).toContain(`data-pane-key="${WORKING_PANE_KEY}"`)
})
it('leaves other worktree rows in ordinary mode during target selection', async () => {
mockStoreState = {
agentSendPopoverTargetMode: activeTargetMode({ worktreeId: 'wt-other' })
@@ -203,7 +232,7 @@ describe('WorktreeCardAgents send targets', () => {
const markup = renderToStaticMarkup(<WorktreeCardAgents worktreeId="wt-1" />)
expect(markup).toContain('data-agent-send-target="eligible"')
expect(markup).toContain('data-agent-send-target="disabled"')
expect(markup).toContain('title="Agent is working"')
expect(markup).not.toContain('data-agent-send-target="disabled"')
expect(markup).not.toContain('title="Agent is working"')
})
})
@@ -91,6 +91,7 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({
const tabsByWorktree = useAppStore((s) => s.tabsByWorktree)
const terminalLayoutsByTabId = useAppStore((s) => s.terminalLayoutsByTabId)
const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId)
const runtimePaneTitlesByTabId = useAppStore((s) => s.runtimePaneTitlesByTabId)
const sendPromptToSidebarAgentTarget = useAppStore((s) => s.sendPromptToSidebarAgentTarget)
const focusedAgentPaneKey = useFocusedAgentPaneKey(worktreeId)
const compactAgentListRootRef = useRef<HTMLDivElement | null>(null)
@@ -131,7 +132,13 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({
return new Map(
deriveRunningAgentSendTargets(
{ agentStatusByPaneKey, tabsByWorktree, terminalLayoutsByTabId, ptyIdsByTabId },
{
agentStatusByPaneKey,
tabsByWorktree,
terminalLayoutsByTabId,
ptyIdsByTabId,
runtimePaneTitlesByTabId
},
worktreeId
).map((target) => [
target.paneKey,
@@ -152,6 +159,7 @@ const WorktreeCardAgentsBody = React.memo(function WorktreeCardAgentsBody({
agentStatusByPaneKey,
isAgentSendTargetModeActive,
ptyIdsByTabId,
runtimePaneTitlesByTabId,
tabsByWorktree,
terminalLayoutsByTabId,
worktreeId
@@ -276,6 +276,7 @@ const EMPTY_AGENT_STATUS_BY_PANE_KEY: AppState['agentStatusByPaneKey'] = {}
const EMPTY_TABS_BY_WORKTREE: AppState['tabsByWorktree'] = {}
const EMPTY_TERMINAL_LAYOUTS_BY_TAB_ID: AppState['terminalLayoutsByTabId'] = {}
const EMPTY_PTY_IDS_BY_TAB_ID: AppState['ptyIdsByTabId'] = {}
const EMPTY_RUNTIME_PANE_TITLES_BY_TAB_ID: AppState['runtimePaneTitlesByTabId'] = {}
const EXPANDING_CARD_MEASUREMENT_ADJUSTMENT_SUPPRESS_MS = 300
const NOOP_WORKSPACE_BOARD_DRAG_PREVIEW_CALLBACK = (): void => {}
const WORKTREE_SIDEBAR_SCROLL_STYLE: React.CSSProperties = {
@@ -4643,6 +4644,9 @@ const WorktreeList = React.memo(function WorktreeList({
const agentTargetPtyIdsByTabId = useAppStore((s) =>
agentSendPopoverTargetMode ? s.ptyIdsByTabId : EMPTY_PTY_IDS_BY_TAB_ID
)
const agentTargetRuntimePaneTitlesByTabId = useAppStore((s) =>
agentSendPopoverTargetMode ? s.runtimePaneTitlesByTabId : EMPTY_RUNTIME_PANE_TITLES_BY_TAB_ID
)
const agentSendTargetWorktreeId = useMemo(() => {
void agentTargetStatusEpoch
if (!agentSendPopoverTargetMode) {
@@ -4653,7 +4657,8 @@ const WorktreeList = React.memo(function WorktreeList({
agentStatusByPaneKey: agentTargetStatusByPaneKey,
tabsByWorktree: agentTargetTabsByWorktree,
terminalLayoutsByTabId: agentTargetTerminalLayoutsByTabId,
ptyIdsByTabId: agentTargetPtyIdsByTabId
ptyIdsByTabId: agentTargetPtyIdsByTabId,
runtimePaneTitlesByTabId: agentTargetRuntimePaneTitlesByTabId
},
agentSendPopoverTargetMode.worktreeId
)
@@ -4668,7 +4673,8 @@ const WorktreeList = React.memo(function WorktreeList({
agentTargetStatusByPaneKey,
agentTargetTabsByWorktree,
agentTargetTerminalLayoutsByTabId,
agentTargetPtyIdsByTabId
agentTargetPtyIdsByTabId,
agentTargetRuntimePaneTitlesByTabId
])
// Read tabsByWorktree when needed for filtering or sorting
@@ -0,0 +1,47 @@
export type ActiveAgentNotesSendStatus =
| 'sent'
| 'empty'
| 'no-active-terminal'
| 'no-agent'
| 'permission'
| 'status-unavailable'
| 'not-ready'
| 'not-writable'
| 'partial-submit-failed'
export type ActiveAgentNotesSendResult = {
status: ActiveAgentNotesSendStatus
}
export function activeAgentNotesSendFailureMessage(
status: ActiveAgentNotesSendStatus,
options: { explicitTarget?: boolean } = {}
): string {
const target = options.explicitTarget ? 'selected' : 'active'
switch (status) {
case 'empty':
return 'No notes to send.'
case 'no-active-terminal':
return options.explicitTarget
? 'The selected terminal is no longer available.'
: 'Open the agent terminal in this worktree, then send the notes again.'
case 'no-agent':
return `The ${target} terminal is not a recognized agent session.`
case 'permission':
return options.explicitTarget
? 'The selected agent needs permission.'
: 'The active agent needs permission.'
case 'status-unavailable':
return `The ${target} agent status could not be verified.`
case 'not-ready':
return `The ${target} agent was not ready for input yet.`
case 'not-writable':
return `The ${target} terminal did not accept the notes.`
case 'partial-submit-failed':
return options.explicitTarget
? 'The notes may already be pasted in the selected terminal, but Orca could not submit them.'
: 'The notes may already be pasted in the active terminal, but Orca could not submit them.'
case 'sent':
return ''
}
}
@@ -1,6 +1,7 @@
/* eslint-disable max-lines -- Why: these note-send routing cases share one mocked app store and RPC harness. */
import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
activeAgentNotesSendFailureMessage,
getActiveAgentNoteTarget,
getActiveAgentRuntimeProbeDescriptor,
getActiveTerminalNoteTarget,
@@ -14,6 +15,8 @@ import type { TerminalLayoutSnapshot } from '../../../shared/types'
const LEAF_ID = '11111111-1111-4111-8111-111111111111'
const OTHER_LEAF_ID = '22222222-2222-4222-8222-222222222222'
const NOW = 1_700_000_000_000
const PASTE_BEGIN = '\x1b[200~'
const PASTE_END = '\x1b[201~'
const testState = vi.hoisted(() => ({
appState: {
@@ -56,7 +59,18 @@ const testState = vi.hoisted(() => ({
settings: Record<string, unknown>
},
callRuntimeRpc: vi.fn(),
getActiveRuntimeTarget: vi.fn(() => ({ kind: 'local' }))
getActiveRuntimeTarget: vi.fn(() => ({ kind: 'local' })),
RuntimeRpcCallError: class RuntimeRpcCallError extends Error {
readonly code: string
readonly response: unknown
constructor(response: { error: { code: string; message: string } }) {
super(response.error.message)
this.name = 'RuntimeRpcCallError'
this.code = response.error.code
this.response = response
}
}
}))
vi.mock('@/store', () => ({
@@ -70,7 +84,8 @@ vi.mock('@/store', () => ({
vi.mock('@/runtime/runtime-rpc-client', () => ({
callRuntimeRpc: testState.callRuntimeRpc,
getActiveRuntimeTarget: testState.getActiveRuntimeTarget
getActiveRuntimeTarget: testState.getActiveRuntimeTarget,
RuntimeRpcCallError: testState.RuntimeRpcCallError
}))
describe('active agent note send', () => {
@@ -299,6 +314,155 @@ describe('active agent note send', () => {
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-1', isRunningAgent: true, status: 'idle' } }
}
if (method === 'terminal.wait') {
return {
wait: {
handle: 'term-1',
condition: 'tui-idle',
satisfied: true,
status: 'running',
exitCode: null
}
}
}
if (method === 'terminal.send') {
return {
send: {
handle: 'term-1',
accepted: true,
bytesWritten: typeof params.text === 'string' ? params.text.length : 1
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({ worktreeId: 'wt-1', prompt: 'File: src/app.ts' })
).resolves.toEqual({ status: 'sent' })
expect(testState.callRuntimeRpc).toHaveBeenCalledWith(
{ kind: 'local' },
'terminal.list',
{ worktree: 'id:wt-1', limit: 200 },
{ timeoutMs: 15000 }
)
expect(testState.callRuntimeRpc).toHaveBeenCalledWith(
{ kind: 'local' },
'terminal.send',
{
terminal: 'term-1',
text: `${PASTE_BEGIN}File: src/app.ts${PASTE_END}`,
requireAgentStatus: 'sendable',
client: { id: 'orca-desktop', type: 'desktop' }
},
{ timeoutMs: 15000 }
)
expect(testState.callRuntimeRpc).toHaveBeenLastCalledWith(
{ kind: 'local' },
'terminal.send',
{
terminal: 'term-1',
enter: true,
requireAgentStatus: 'sendable',
client: { id: 'orca-desktop', type: 'desktop' }
},
{ timeoutMs: 15000 }
)
})
it('maps active-focused guarded paste permission refusal to permission', async () => {
testState.callRuntimeRpc.mockImplementation(async (_target, method, params) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-1',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-1',
leafId: LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-1', isRunningAgent: true, status: 'idle' } }
}
if (method === 'terminal.wait') {
return {
wait: {
handle: 'term-1',
condition: 'tui-idle',
satisfied: true,
status: 'running',
exitCode: null
}
}
}
if (method === 'terminal.send') {
expect(params).toMatchObject({
terminal: 'term-1',
requireAgentStatus: 'sendable'
})
return {
send: {
handle: 'term-1',
accepted: false,
bytesWritten: 0,
refusedReason: 'permission'
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({ worktreeId: 'wt-1', prompt: 'notes' })
).resolves.toEqual({ status: 'permission' })
})
it('keeps active-focused sends compatible when an older runtime lacks agentStatus', async () => {
const methods: string[] = []
testState.callRuntimeRpc.mockImplementation(async (_target, method, params) => {
methods.push(method)
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-1',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-1',
leafId: LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
throw new testState.RuntimeRpcCallError({
error: { code: 'method_not_found', message: 'Unknown method: terminal.agentStatus' }
})
}
if (method === 'terminal.isRunningAgent') {
return { isRunningAgent: true }
}
@@ -323,23 +487,15 @@ describe('active agent note send', () => {
sendNotesToActiveAgentSession({ worktreeId: 'wt-1', prompt: 'File: src/app.ts' })
).resolves.toEqual({ status: 'sent' })
expect(testState.callRuntimeRpc).toHaveBeenCalledWith(
{ kind: 'local' },
expect(methods).toEqual([
'terminal.list',
{ worktree: 'id:wt-1', limit: 200 },
{ timeoutMs: 15000 }
)
expect(testState.callRuntimeRpc).toHaveBeenCalledWith(
{ kind: 'local' },
'terminal.send',
{
terminal: 'term-1',
text: 'File: src/app.ts',
enter: true,
client: { id: 'orca-desktop', type: 'desktop' }
},
{ timeoutMs: 15000 }
)
'terminal.agentStatus',
'terminal.isRunningAgent',
'terminal.wait',
'terminal.agentStatus',
'terminal.isRunningAgent',
'terminal.send'
])
})
it('does not write notes when the active terminal is not an agent', async () => {
@@ -365,8 +521,8 @@ describe('active agent note send', () => {
truncated: false
}
}
if (method === 'terminal.isRunningAgent') {
return { isRunningAgent: false }
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-1', isRunningAgent: false, status: null } }
}
throw new Error(`unexpected method ${method}`)
})
@@ -406,8 +562,8 @@ describe('active agent note send', () => {
truncated: false
}
}
if (method === 'terminal.isRunningAgent') {
return { isRunningAgent: true }
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-1', isRunningAgent: true, status: 'working' } }
}
if (method === 'terminal.wait') {
throw new Error('timeout')
@@ -427,6 +583,172 @@ describe('active agent note send', () => {
)
})
it('maps non-running active-focused waits to no active terminal', async () => {
testState.callRuntimeRpc.mockImplementation(async (_target, method) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-1',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-1',
leafId: LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-1', isRunningAgent: true, status: 'working' } }
}
if (method === 'terminal.wait') {
return {
wait: {
handle: 'term-1',
condition: 'tui-idle',
satisfied: false,
status: 'exited',
exitCode: 0
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({ worktreeId: 'wt-1', prompt: 'notes' })
).resolves.toEqual({ status: 'no-active-terminal' })
expect(testState.callRuntimeRpc).not.toHaveBeenCalledWith(
expect.anything(),
'terminal.send',
expect.anything(),
expect.anything()
)
})
it('maps active-focused blocked waits to permission without writing', async () => {
testState.callRuntimeRpc.mockImplementation(async (_target, method) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-1',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-1',
leafId: LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-1', isRunningAgent: true, status: 'working' } }
}
if (method === 'terminal.wait') {
return {
wait: {
handle: 'term-1',
condition: 'tui-idle',
satisfied: false,
status: 'running',
exitCode: null,
blockedReason: 'codex-interactive-prompt'
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({ worktreeId: 'wt-1', prompt: 'notes' })
).resolves.toEqual({ status: 'permission' })
expect(testState.callRuntimeRpc).not.toHaveBeenCalledWith(
expect.anything(),
'terminal.send',
expect.anything(),
expect.anything()
)
})
it('rechecks active-focused permission after idle wait succeeds before writing', async () => {
let statusChecks = 0
testState.callRuntimeRpc.mockImplementation(async (_target, method) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-1',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-1',
leafId: LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
statusChecks += 1
return {
agentStatus: {
handle: 'term-1',
isRunningAgent: true,
status: statusChecks === 1 ? 'idle' : 'permission'
}
}
}
if (method === 'terminal.wait') {
return {
wait: {
handle: 'term-1',
condition: 'tui-idle',
satisfied: true,
status: 'running',
exitCode: null
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({ worktreeId: 'wt-1', prompt: 'notes' })
).resolves.toEqual({ status: 'permission' })
expect(statusChecks).toBe(2)
expect(testState.callRuntimeRpc).not.toHaveBeenCalledWith(
expect.anything(),
'terminal.send',
expect.anything(),
expect.anything()
)
})
it('does not call runtime when no terminal pane is known for the worktree', async () => {
testState.appState.activeTabType = 'editor'
testState.appState.activeTabIdByWorktree = {}
@@ -438,9 +760,138 @@ describe('active agent note send', () => {
expect(testState.callRuntimeRpc).not.toHaveBeenCalled()
})
it('sends notes to an explicit note target even when no terminal pane is focused', async () => {
it('sends notes immediately to an explicit note target using bracketed paste and Enter', async () => {
testState.appState.activeTabType = 'editor'
testState.appState.activeTabIdByWorktree = {}
const methods: string[] = []
testState.callRuntimeRpc.mockImplementation(async (_target, method, params) => {
methods.push(method)
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-2', isRunningAgent: true, status: 'working' } }
}
if (method === 'terminal.send') {
return {
send: {
handle: 'term-2',
accepted: true,
bytesWritten: typeof params.text === 'string' ? params.text.length : 1
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'sent' })
expect(methods).toEqual([
'terminal.list',
'terminal.agentStatus',
'terminal.send',
'terminal.agentStatus',
'terminal.send'
])
expect(testState.callRuntimeRpc).toHaveBeenCalledWith(
{ kind: 'local' },
'terminal.send',
{
terminal: 'term-2',
text: `${PASTE_BEGIN}notes${PASTE_END}`,
requireAgentStatus: 'sendable',
client: { id: 'orca-desktop', type: 'desktop' }
},
{ timeoutMs: 15000 }
)
expect(testState.callRuntimeRpc).toHaveBeenLastCalledWith(
{ kind: 'local' },
'terminal.send',
{
terminal: 'term-2',
enter: true,
requireAgentStatus: 'sendable',
client: { id: 'orca-desktop', type: 'desktop' }
},
{ timeoutMs: 15000 }
)
})
it('refuses explicit targets when an older runtime cannot verify agent status', async () => {
const methods: string[] = []
testState.callRuntimeRpc.mockImplementation(async (_target, method) => {
methods.push(method)
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
throw new testState.RuntimeRpcCallError({
error: { code: 'method_not_found', message: 'Unknown method: terminal.agentStatus' }
})
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'status-unavailable' })
expect(methods).toEqual(['terminal.list', 'terminal.agentStatus'])
expect(testState.callRuntimeRpc).not.toHaveBeenCalledWith(
expect.anything(),
'terminal.send',
expect.anything(),
expect.anything()
)
})
it('sanitizes embedded escape bytes before wrapping explicit target notes', async () => {
testState.callRuntimeRpc.mockImplementation(async (_target, method, params) => {
if (method === 'terminal.list') {
return {
@@ -463,17 +914,260 @@ describe('active agent note send', () => {
truncated: false
}
}
if (method === 'terminal.isRunningAgent') {
return { isRunningAgent: true }
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-2', isRunningAgent: true, status: null } }
}
if (method === 'terminal.wait') {
if (method === 'terminal.send') {
return {
wait: {
send: {
handle: 'term-2',
condition: 'tui-idle',
satisfied: true,
status: 'running',
exitCode: null
accepted: true,
bytesWritten: typeof params.text === 'string' ? params.text.length : 1
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes \x1b[201~ tail',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'sent' })
expect(testState.callRuntimeRpc).toHaveBeenCalledWith(
{ kind: 'local' },
'terminal.send',
expect.objectContaining({
text: `${PASTE_BEGIN}notes \u241b[201~ tail${PASTE_END}`,
requireAgentStatus: 'sendable'
}),
{ timeoutMs: 15000 }
)
})
it('refuses explicit targets that are permission-blocked before writing', async () => {
testState.callRuntimeRpc.mockImplementation(async (_target, method) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-2', isRunningAgent: true, status: 'permission' } }
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'permission' })
expect(testState.callRuntimeRpc).not.toHaveBeenCalledWith(
expect.anything(),
'terminal.send',
expect.anything(),
expect.anything()
)
})
it('refuses explicit targets that are not recognized agents before writing', async () => {
testState.callRuntimeRpc.mockImplementation(async (_target, method) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'zsh',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-2', isRunningAgent: false, status: null } }
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'no-agent' })
expect(testState.callRuntimeRpc).not.toHaveBeenCalledWith(
expect.anything(),
'terminal.send',
expect.anything(),
expect.anything()
)
})
it('maps explicit target first-write refusal to not-writable', async () => {
testState.callRuntimeRpc.mockImplementation(async (_target, method, params) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-2', isRunningAgent: true, status: 'working' } }
}
if (method === 'terminal.send') {
return { send: { handle: 'term-2', accepted: false, bytesWritten: 0 } }
}
throw new Error(`unexpected method ${method} ${String(params)}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'not-writable' })
const sendCalls = testState.callRuntimeRpc.mock.calls.filter(
(call) => call[1] === 'terminal.send'
)
expect(sendCalls).toHaveLength(1)
})
it('maps explicit target guarded paste permission refusal to permission', async () => {
testState.callRuntimeRpc.mockImplementation(async (_target, method) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-2', isRunningAgent: true, status: 'working' } }
}
if (method === 'terminal.send') {
return {
send: {
handle: 'term-2',
accepted: false,
bytesWritten: 0,
refusedReason: 'permission'
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'permission' })
const sendCalls = testState.callRuntimeRpc.mock.calls.filter(
(call) => call[1] === 'terminal.send'
)
expect(sendCalls).toHaveLength(1)
})
it('maps explicit target permission or unavailable state before Enter to partial-submit-failed', async () => {
let statusChecks = 0
testState.callRuntimeRpc.mockImplementation(async (_target, method, params) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
statusChecks += 1
return {
agentStatus: {
handle: 'term-2',
isRunningAgent: true,
status: statusChecks === 1 ? 'working' : 'permission'
}
}
}
@@ -489,18 +1183,144 @@ describe('active agent note send', () => {
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'sent' })
).resolves.toEqual({ status: 'partial-submit-failed' })
expect(testState.callRuntimeRpc).toHaveBeenCalledWith(
{ kind: 'local' },
'terminal.send',
{
terminal: 'term-2',
text: 'notes',
enter: true,
client: { id: 'orca-desktop', type: 'desktop' }
},
{ timeoutMs: 15000 }
const sendCalls = testState.callRuntimeRpc.mock.calls.filter(
(call) => call[1] === 'terminal.send'
)
expect(sendCalls).toHaveLength(1)
})
it('maps explicit target Enter write failure to partial-submit-failed', async () => {
let sendCount = 0
testState.callRuntimeRpc.mockImplementation(async (_target, method, params) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-2', isRunningAgent: true, status: 'idle' } }
}
if (method === 'terminal.send') {
sendCount += 1
return {
send: {
handle: 'term-2',
accepted: sendCount === 1,
bytesWritten: typeof params.text === 'string' ? params.text.length : 0
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'partial-submit-failed' })
})
it('maps explicit target guarded Enter permission refusal to partial-submit-failed', async () => {
let sendCount = 0
testState.callRuntimeRpc.mockImplementation(async (_target, method, params) => {
if (method === 'terminal.list') {
return {
terminals: [
{
handle: 'term-2',
worktreeId: 'wt-1',
worktreePath: '/repo',
branch: 'main',
tabId: 'tab-9',
leafId: OTHER_LEAF_ID,
title: 'Codex',
connected: true,
writable: true,
lastOutputAt: 1,
preview: ''
}
],
totalCount: 1,
truncated: false
}
}
if (method === 'terminal.agentStatus') {
return { agentStatus: { handle: 'term-2', isRunningAgent: true, status: 'idle' } }
}
if (method === 'terminal.send') {
sendCount += 1
return sendCount === 1
? {
send: {
handle: 'term-2',
accepted: true,
bytesWritten: typeof params.text === 'string' ? params.text.length : 0
}
}
: {
send: {
handle: 'term-2',
accepted: false,
bytesWritten: 0,
refusedReason: 'permission'
}
}
}
throw new Error(`unexpected method ${method}`)
})
await expect(
sendNotesToActiveAgentSession({
worktreeId: 'wt-1',
prompt: 'notes',
noteTarget: { tabId: 'tab-9', leafId: OTHER_LEAF_ID }
})
).resolves.toEqual({ status: 'partial-submit-failed' })
})
it('uses selected-target failure wording for explicit note targets', () => {
expect(activeAgentNotesSendFailureMessage('not-ready', { explicitTarget: true })).toBe(
'The selected agent was not ready for input yet.'
)
expect(activeAgentNotesSendFailureMessage('not-ready')).toBe(
'The active agent was not ready for input yet.'
)
expect(activeAgentNotesSendFailureMessage('permission', { explicitTarget: true })).toBe(
'The selected agent needs permission.'
)
expect(activeAgentNotesSendFailureMessage('permission')).toBe(
'The active agent needs permission.'
)
expect(activeAgentNotesSendFailureMessage('status-unavailable', { explicitTarget: true })).toBe(
'The selected agent status could not be verified.'
)
expect(
activeAgentNotesSendFailureMessage('partial-submit-failed', { explicitTarget: true })
).toBe(
'The notes may already be pasted in the selected terminal, but Orca could not submit them.'
)
expect(activeAgentNotesSendFailureMessage('partial-submit-failed')).toBe(
'The notes may already be pasted in the active terminal, but Orca could not submit them.'
)
})
+170 -64
View File
@@ -7,6 +7,20 @@ import {
getActiveTerminalNoteTarget,
type ActiveTerminalNoteTarget
} from './active-agent-note-target'
import {
BRACKETED_PASTE_BEGIN,
BRACKETED_PASTE_END,
POST_PASTE_SUBMIT_DELAY_MS,
sanitizeBracketedPasteContent
} from './agent-paste-draft'
import type { ActiveAgentNotesSendResult } from './active-agent-note-send-result'
import {
ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS,
getTerminalAgentSendReadiness,
isRuntimeTerminalNotWritable,
isRuntimeTerminalUnavailable,
isRuntimeTimeout
} from './active-agent-terminal-send-readiness'
export {
getActiveAgentNoteTarget,
@@ -16,27 +30,20 @@ export {
useCanSendNotesToActiveTerminal,
type ActiveTerminalNoteTarget
} from './active-agent-note-target'
export {
activeAgentNotesSendFailureMessage,
type ActiveAgentNotesSendResult,
type ActiveAgentNotesSendStatus
} from './active-agent-note-send-result'
const ACTIVE_AGENT_SEND_TIMEOUT_MS = 8000
const ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS = 15000
export type ActiveAgentNotesSendStatus =
| 'sent'
| 'empty'
| 'no-active-terminal'
| 'no-agent'
| 'not-ready'
| 'not-writable'
export type ActiveAgentNotesSendResult = {
status: ActiveAgentNotesSendStatus
}
const ORCA_DESKTOP_TERMINAL_CLIENT = { id: 'orca-desktop', type: 'desktop' as const }
export async function sendNotesToActiveAgentSession({
worktreeId,
prompt,
noteTarget: explicitNoteTarget,
timeoutMs = ACTIVE_AGENT_SEND_TIMEOUT_MS
timeoutMs
}: {
worktreeId: string
prompt: string
@@ -57,7 +64,6 @@ export async function sendNotesToActiveAgentSession({
if (!noteTarget) {
return { status: 'no-active-terminal' }
}
// Route by the worktree's owner host so the agent terminal is found and driven
// on the host that actually runs it, not on the focused runtime.
const runtimeTarget = getActiveRuntimeTarget(
@@ -73,25 +79,31 @@ export async function sendNotesToActiveAgentSession({
return { status: 'no-active-terminal' }
}
// Why: sending notes submits with Enter, so only the runtime's agent/idle
// checks can authorize it; tab labels and renderer state are not enough.
const agentCheck = await callRuntimeRpc<{ isRunningAgent: boolean }>(
runtimeTarget,
'terminal.isRunningAgent',
{ terminal: terminal.handle },
{ timeoutMs: ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS }
)
if (!agentCheck.isRunningAgent) {
return { status: 'no-agent' }
if (explicitNoteTarget) {
return await sendPromptToExplicitAgentTarget(runtimeTarget, terminal.handle, trimmedPrompt)
}
const effectiveTimeoutMs = timeoutMs ?? ACTIVE_AGENT_SEND_TIMEOUT_MS
const initialAgentStatus = await getTerminalAgentSendReadiness(runtimeTarget, terminal.handle, {
allowLegacyFallback: true
})
if (initialAgentStatus.status !== 'sendable') {
return { status: initialAgentStatus.status }
}
try {
const { wait } = await callRuntimeRpc<{ wait: RuntimeTerminalWait }>(
runtimeTarget,
'terminal.wait',
{ terminal: terminal.handle, for: 'tui-idle', timeoutMs },
{ timeoutMs: timeoutMs + 5000 }
{ terminal: terminal.handle, for: 'tui-idle', timeoutMs: effectiveTimeoutMs },
{ timeoutMs: effectiveTimeoutMs + 5000 }
)
if (wait.status !== 'running') {
return { status: 'no-active-terminal' }
}
if (wait.blockedReason) {
return { status: 'permission' }
}
if (!wait.satisfied) {
return { status: 'not-ready' }
}
@@ -105,48 +117,142 @@ export async function sendNotesToActiveAgentSession({
throw error
}
const { send } = await callRuntimeRpc<{ send: RuntimeTerminalSend }>(
runtimeTarget,
'terminal.send',
{
terminal: terminal.handle,
text: trimmedPrompt,
enter: true,
client: { id: 'orca-desktop', type: 'desktop' }
},
{ timeoutMs: ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS }
)
return send.accepted ? { status: 'sent' } : { status: 'not-writable' }
const finalAgentStatus = await getTerminalAgentSendReadiness(runtimeTarget, terminal.handle, {
allowLegacyFallback: true
})
if (finalAgentStatus.status !== 'sendable') {
return { status: finalAgentStatus.status }
}
if (finalAgentStatus.supportsGuardedSend) {
return await sendPromptWithGuardedPasteAndEnter(runtimeTarget, terminal.handle, trimmedPrompt, {
allowLegacyFallback: false
})
}
// Why: protocol-compatible older SSH runtimes do not know the guarded send
// option. They already passed terminal.wait + legacy isRunningAgent checks,
// so preserve the old active-focused send path for remote compatibility.
return await sendPromptWithLegacyCombinedSend(runtimeTarget, terminal.handle, trimmedPrompt)
}
export function activeAgentNotesSendFailureMessage(status: ActiveAgentNotesSendStatus): string {
switch (status) {
case 'empty':
return 'No notes to send.'
case 'no-active-terminal':
return 'Open the agent terminal in this worktree, then send the notes again.'
case 'no-agent':
return 'The active terminal is not a recognized agent session.'
case 'not-ready':
return 'The active agent was not ready for input yet.'
case 'not-writable':
return 'The active terminal did not accept the notes.'
case 'sent':
return ''
async function sendPromptWithLegacyCombinedSend(
runtimeTarget: ReturnType<typeof getActiveRuntimeTarget>,
terminalHandle: string,
prompt: string
): Promise<ActiveAgentNotesSendResult> {
try {
const { send } = await callRuntimeRpc<{ send: RuntimeTerminalSend }>(
runtimeTarget,
'terminal.send',
{
terminal: terminalHandle,
text: prompt,
enter: true,
client: ORCA_DESKTOP_TERMINAL_CLIENT
},
{ timeoutMs: ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS }
)
return send.accepted ? { status: 'sent' } : { status: 'not-writable' }
} catch (error) {
if (isRuntimeTerminalUnavailable(error)) {
return { status: 'no-active-terminal' }
}
if (isRuntimeTerminalNotWritable(error)) {
return { status: 'not-writable' }
}
throw error
}
}
function isRuntimeTimeout(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error)
return message.includes('timeout')
async function sendPromptWithGuardedPasteAndEnter(
runtimeTarget: ReturnType<typeof getActiveRuntimeTarget>,
terminalHandle: string,
prompt: string,
options: { allowLegacyFallback: boolean }
): Promise<ActiveAgentNotesSendResult> {
const initialAgentStatus = await getTerminalAgentSendReadiness(runtimeTarget, terminalHandle, {
allowLegacyFallback: options.allowLegacyFallback
})
if (initialAgentStatus.status !== 'sendable') {
return { status: initialAgentStatus.status }
}
const pastePayload = `${BRACKETED_PASTE_BEGIN}${sanitizeBracketedPasteContent(prompt)}${BRACKETED_PASTE_END}`
try {
const { send } = await callRuntimeRpc<{ send: RuntimeTerminalSend }>(
runtimeTarget,
'terminal.send',
{
terminal: terminalHandle,
text: pastePayload,
requireAgentStatus: 'sendable',
client: ORCA_DESKTOP_TERMINAL_CLIENT
},
{ timeoutMs: ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS }
)
if (!send.accepted) {
if (send.refusedReason === 'permission') {
return { status: 'permission' }
}
if (send.refusedReason === 'no-agent') {
return { status: 'no-agent' }
}
return { status: 'not-writable' }
}
} catch (error) {
if (isRuntimeTerminalUnavailable(error)) {
return { status: 'no-active-terminal' }
}
if (isRuntimeTerminalNotWritable(error)) {
return { status: 'not-writable' }
}
throw error
}
await new Promise<void>((resolve) => setTimeout(resolve, POST_PASTE_SUBMIT_DELAY_MS))
try {
const submitAgentStatus = await getTerminalAgentSendReadiness(runtimeTarget, terminalHandle, {
allowLegacyFallback: options.allowLegacyFallback
})
if (submitAgentStatus.status !== 'sendable') {
return { status: 'partial-submit-failed' }
}
} catch (error) {
if (isRuntimeTerminalUnavailable(error)) {
return { status: 'partial-submit-failed' }
}
throw error
}
try {
const { send } = await callRuntimeRpc<{ send: RuntimeTerminalSend }>(
runtimeTarget,
'terminal.send',
{
terminal: terminalHandle,
enter: true,
requireAgentStatus: 'sendable',
client: ORCA_DESKTOP_TERMINAL_CLIENT
},
{ timeoutMs: ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS }
)
return send.accepted ? { status: 'sent' } : { status: 'partial-submit-failed' }
} catch (error) {
if (isRuntimeTerminalUnavailable(error) || isRuntimeTerminalNotWritable(error)) {
return { status: 'partial-submit-failed' }
}
throw error
}
}
function isRuntimeTerminalUnavailable(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error)
return (
message.includes('terminal_handle_stale') ||
message.includes('terminal_exited') ||
message.includes('terminal_gone') ||
message.includes('no_active_terminal')
)
async function sendPromptToExplicitAgentTarget(
runtimeTarget: ReturnType<typeof getActiveRuntimeTarget>,
terminalHandle: string,
prompt: string
): Promise<ActiveAgentNotesSendResult> {
return await sendPromptWithGuardedPasteAndEnter(runtimeTarget, terminalHandle, prompt, {
allowLegacyFallback: false
})
}
@@ -0,0 +1,97 @@
import type { RuntimeTerminalAgentStatus } from '../../../shared/runtime-types'
import { callRuntimeRpc, RuntimeRpcCallError } from '@/runtime/runtime-rpc-client'
import type { getActiveRuntimeTarget } from '@/runtime/runtime-rpc-client'
export const ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS = 15000
export type TerminalAgentSendReadiness =
| 'sendable'
| 'no-active-terminal'
| 'no-agent'
| 'permission'
| 'status-unavailable'
export type TerminalAgentSendReadinessResult = {
status: TerminalAgentSendReadiness
supportsGuardedSend: boolean
}
export async function getTerminalAgentSendReadiness(
runtimeTarget: ReturnType<typeof getActiveRuntimeTarget>,
terminalHandle: string,
options: { allowLegacyFallback: boolean }
): Promise<TerminalAgentSendReadinessResult> {
try {
const { agentStatus } = await callRuntimeRpc<{ agentStatus: RuntimeTerminalAgentStatus }>(
runtimeTarget,
'terminal.agentStatus',
{ terminal: terminalHandle },
{ timeoutMs: ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS }
)
if (!agentStatus.isRunningAgent) {
return { status: 'no-agent', supportsGuardedSend: true }
}
if (agentStatus.status === 'permission') {
return { status: 'permission', supportsGuardedSend: true }
}
return { status: 'sendable', supportsGuardedSend: true }
} catch (error) {
if (error instanceof RuntimeRpcCallError && error.code === 'method_not_found') {
if (!options.allowLegacyFallback) {
// Why: selected-target sends are immediate; without terminal.agentStatus
// an older remote runtime cannot rule out permission/action prompts.
return { status: 'status-unavailable', supportsGuardedSend: false }
}
// Why: active-focused sends still wait for tui-idle, preserving old
// runtime compatibility without immediate selected-target risk.
return {
status: await getLegacyTerminalAgentSendStatus(runtimeTarget, terminalHandle),
supportsGuardedSend: false
}
}
if (isRuntimeTerminalUnavailable(error)) {
return { status: 'no-active-terminal', supportsGuardedSend: false }
}
throw error
}
}
async function getLegacyTerminalAgentSendStatus(
runtimeTarget: ReturnType<typeof getActiveRuntimeTarget>,
terminalHandle: string
): Promise<TerminalAgentSendReadiness> {
try {
const { isRunningAgent } = await callRuntimeRpc<{ isRunningAgent: boolean }>(
runtimeTarget,
'terminal.isRunningAgent',
{ terminal: terminalHandle },
{ timeoutMs: ACTIVE_AGENT_SEND_RPC_TIMEOUT_MS }
)
return isRunningAgent ? 'sendable' : 'no-agent'
} catch (error) {
if (isRuntimeTerminalUnavailable(error)) {
return 'no-active-terminal'
}
throw error
}
}
export function isRuntimeTimeout(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error)
return message.includes('timeout')
}
export function isRuntimeTerminalUnavailable(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error)
return (
message.includes('terminal_handle_stale') ||
message.includes('terminal_exited') ||
message.includes('terminal_gone') ||
message.includes('no_active_terminal')
)
}
export function isRuntimeTerminalNotWritable(error: unknown): boolean {
const message = error instanceof Error ? error.message : String(error)
return message.includes('terminal_not_writable')
}
+16 -1
View File
@@ -2,6 +2,11 @@ import type { TuiAgent } from '../../../shared/types'
import { TUI_AGENT_CONFIG } from '../../../shared/tui-agent-config'
import { useAppStore } from '@/store'
import { sendRuntimePtyInputVerified } from '@/runtime/runtime-terminal-inspection'
import {
BRACKETED_PASTE_END,
BRACKETED_PASTE_START,
sanitizeTerminalPasteText
} from '@/components/terminal-pane/terminal-bracketed-paste'
import { waitForAgentReady } from './agent-ready-wait'
import { getSettingsForWorktreeRuntimeOwner } from './worktree-runtime-owner'
import type { GlobalSettings } from '../../../shared/types'
@@ -16,7 +21,17 @@ export {
sendAgentDraftPasteContent
} from './agent-draft-paste-content'
const POST_PASTE_SUBMIT_DELAY_MS = 50
// Why: bracketed paste markers let modern TUIs (Claude Code / Codex / Pi /
// OpenCode / Gemini / cursor-agent / copilot) treat the inserted text as a
// single atomic paste instead of echoing character-by-character or triggering
// line-edit shortcuts. Callers choose whether to append Enter after the paste.
export const BRACKETED_PASTE_BEGIN = BRACKETED_PASTE_START
export { BRACKETED_PASTE_END }
export const POST_PASTE_SUBMIT_DELAY_MS = 50
export function sanitizeBracketedPasteContent(content: string): string {
return sanitizeTerminalPasteText(content)
}
// Why: deterministic signal can fail in two ways: (1) the agent never
// emits DECSET 2004 (no shipped agent does this — guarded as a fallback),
@@ -122,6 +122,49 @@ describe('notes send agent targets', () => {
])
})
it('keeps permission status-backed targets visible but disabled', () => {
const paneKey = makePaneKey(STATUS_TAB_ID, LEAF_A)
const targets = deriveNotesSendAgentTargets(
state({
agentStatusByPaneKey: { [paneKey]: entry(paneKey, 'waiting') },
tabsByWorktree: { [WORKTREE_ID]: [tab(STATUS_TAB_ID, { title: 'Terminal 1' })] },
terminalLayoutsByTabId: { [STATUS_TAB_ID]: leafLayout(LEAF_A, 'pty-a') }
}),
WORKTREE_ID,
NOW
)
expect(targets).toEqual([
expect.objectContaining({
paneKey,
status: 'disabled',
disabledReason: 'Agent needs permission'
})
])
})
it('keeps status-backed working targets disabled when a live pane title needs permission', () => {
const paneKey = makePaneKey(STATUS_TAB_ID, LEAF_A)
const targets = deriveNotesSendAgentTargets(
state({
agentStatusByPaneKey: { [paneKey]: entry(paneKey, 'working') },
tabsByWorktree: { [WORKTREE_ID]: [tab(STATUS_TAB_ID, { title: 'Codex working' })] },
terminalLayoutsByTabId: { [STATUS_TAB_ID]: leafLayout(LEAF_A, 'pty-a') },
runtimePaneTitlesByTabId: { [STATUS_TAB_ID]: { 1: 'Codex - action required' } }
}),
WORKTREE_ID,
NOW
)
expect(targets).toEqual([
expect.objectContaining({
paneKey,
status: 'disabled',
disabledReason: 'Agent needs permission'
})
])
})
it('lists a launch-agent tab with a recognized pane title before any hook status', () => {
const targets = deriveNotesSendAgentTargets(
state({
@@ -129,7 +172,7 @@ describe('notes send agent targets', () => {
[WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Terminal 2', launchAgent: 'codex' })]
},
terminalLayoutsByTabId: { [LAUNCH_TAB_ID]: leafLayout(LEAF_B, 'pty-b') },
runtimePaneTitlesByTabId: { [LAUNCH_TAB_ID]: { 1: 'Codex' } }
runtimePaneTitlesByTabId: { [LAUNCH_TAB_ID]: { 1: 'Codex ready' } }
}),
WORKTREE_ID,
NOW
@@ -147,11 +190,11 @@ describe('notes send agent targets', () => {
])
})
it('recognizes a launch-agent tab by its OSC tab title when no pane title is set', () => {
it('recognizes a launch-agent tab by its explicit ready tab title when no pane title is set', () => {
const targets = deriveNotesSendAgentTargets(
state({
tabsByWorktree: {
[WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Codex', launchAgent: 'codex' })]
[WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Codex ready', launchAgent: 'codex' })]
},
terminalLayoutsByTabId: { [LAUNCH_TAB_ID]: leafLayout(LEAF_B, 'pty-b') }
}),
@@ -162,6 +205,67 @@ describe('notes send agent targets', () => {
expect(targets.map((target) => target.paneKey)).toEqual([makePaneKey(LAUNCH_TAB_ID, LEAF_B)])
})
it('skips a launch-agent tab with only a bare agent-name title', () => {
const targets = deriveNotesSendAgentTargets(
state({
tabsByWorktree: {
[WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Codex', launchAgent: 'codex' })]
},
terminalLayoutsByTabId: { [LAUNCH_TAB_ID]: leafLayout(LEAF_B, 'pty-b') },
runtimePaneTitlesByTabId: { [LAUNCH_TAB_ID]: { 1: 'Codex' } }
}),
WORKTREE_ID,
NOW
)
expect(targets).toEqual([])
})
it('disables a launch-agent tab with a permission pane title', () => {
const targets = deriveNotesSendAgentTargets(
state({
tabsByWorktree: {
[WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Terminal 2', launchAgent: 'codex' })]
},
terminalLayoutsByTabId: { [LAUNCH_TAB_ID]: leafLayout(LEAF_B, 'pty-b') },
runtimePaneTitlesByTabId: { [LAUNCH_TAB_ID]: { 1: 'Codex - action required' } }
}),
WORKTREE_ID,
NOW
)
expect(targets).toEqual([
expect.objectContaining({
paneKey: makePaneKey(LAUNCH_TAB_ID, LEAF_B),
status: 'disabled',
disabledReason: 'Agent needs permission'
})
])
})
it('disables a launch-agent tab with a permission tab title when no pane title is set', () => {
const targets = deriveNotesSendAgentTargets(
state({
tabsByWorktree: {
[WORKTREE_ID]: [
tab(LAUNCH_TAB_ID, { title: 'Codex - action required', launchAgent: 'codex' })
]
},
terminalLayoutsByTabId: { [LAUNCH_TAB_ID]: leafLayout(LEAF_B, 'pty-b') }
}),
WORKTREE_ID,
NOW
)
expect(targets).toEqual([
expect.objectContaining({
paneKey: makePaneKey(LAUNCH_TAB_ID, LEAF_B),
status: 'disabled',
disabledReason: 'Agent needs permission'
})
])
})
it('skips a still-booting launch-agent tab whose title is not yet an agent', () => {
const targets = deriveNotesSendAgentTargets(
state({
@@ -198,11 +302,11 @@ describe('notes send agent targets', () => {
const targets = deriveNotesSendAgentTargets(
state({
tabsByWorktree: {
[WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Codex', launchAgent: 'codex' })]
[WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Codex ready', launchAgent: 'codex' })]
},
terminalLayoutsByTabId: { [LAUNCH_TAB_ID]: leafLayout(LEAF_B, 'pty-b') },
ptyIdsByTabId: { [LAUNCH_TAB_ID]: [] },
runtimePaneTitlesByTabId: { [LAUNCH_TAB_ID]: { 1: 'Codex' } }
runtimePaneTitlesByTabId: { [LAUNCH_TAB_ID]: { 1: 'Codex ready' } }
}),
WORKTREE_ID,
NOW
@@ -232,8 +336,7 @@ describe('notes send agent targets', () => {
expect(targets[0]).toMatchObject({
tabId: LAUNCH_TAB_ID,
leafId: LEAF_A,
status: 'disabled',
disabledReason: 'Agent is working'
status: 'eligible'
})
})
@@ -263,9 +366,9 @@ describe('notes send agent targets', () => {
it('does not list a plain terminal tab without a launch agent or status', () => {
const targets = deriveNotesSendAgentTargets(
state({
tabsByWorktree: { [WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Codex' })] },
tabsByWorktree: { [WORKTREE_ID]: [tab(LAUNCH_TAB_ID, { title: 'Codex ready' })] },
terminalLayoutsByTabId: { [LAUNCH_TAB_ID]: leafLayout(LEAF_B, 'pty-b') },
runtimePaneTitlesByTabId: { [LAUNCH_TAB_ID]: { 1: 'Codex' } }
runtimePaneTitlesByTabId: { [LAUNCH_TAB_ID]: { 1: 'Codex ready' } }
}),
WORKTREE_ID,
NOW
@@ -8,6 +8,11 @@ import {
type RunningAgentTargetState
} from './running-agent-targets'
const EXPLICIT_IDLE_TITLE_RE = /(^|\s)(ready|idle|done)(\s|$|[.!?])/i
const CLAUDE_IDLE_PREFIX = '\u2733'
const GEMINI_IDLE_PREFIX = '\u25c7'
const PI_IDLE_PREFIX = '\u03c0 - '
export type NotesSendAgentTargetState = RunningAgentTargetState &
Pick<AppState, 'runtimePaneTitlesByTabId'>
@@ -27,13 +32,35 @@ function isRecognizedAgentTitle(title: string | null): boolean {
)
}
function launchAgentPaneLooksRecognized(paneTitle: string | null, tabTitle: string): boolean {
if (isRecognizedAgentTitle(paneTitle)) {
return true
function detectLaunchAgentPaneStatus(paneTitle: string | null, tabTitle: string) {
if (paneTitle !== null && isRecognizedAgentTitle(paneTitle)) {
return detectLaunchAgentStatusFromTitle(paneTitle)
}
// Why: mirror isTerminalRunningAgent — the OSC-enriched tab title only counts
// when the leaf has no runtime pane title of its own yet.
return paneTitle === null && isRecognizedAgentTitle(tabTitle)
? detectLaunchAgentStatusFromTitle(tabTitle)
: null
}
function detectLaunchAgentStatusFromTitle(title: string) {
const status = detectAgentStatusFromTitle(title)
if (status !== 'idle') {
return status
}
// Why: selected-target sends are immediate. A bare launch title like
// "Codex" proves agent identity, but not that the CLI is ready for input.
return isExplicitIdleLaunchTitle(title) ? status : null
}
function isExplicitIdleLaunchTitle(title: string): boolean {
return (
EXPLICIT_IDLE_TITLE_RE.test(title) ||
title.startsWith(CLAUDE_IDLE_PREFIX) ||
title.startsWith('* ') ||
title.includes(GEMINI_IDLE_PREFIX) ||
title.startsWith(PI_IDLE_PREFIX)
)
}
/**
@@ -94,13 +121,15 @@ export function deriveNotesSendAgentTargets(
state.runtimePaneTitlesByTabId[tab.id],
leafId
)
if (!launchAgentPaneLooksRecognized(paneTitle, tab.title)) {
const launchStatus = detectLaunchAgentPaneStatus(paneTitle, tab.title)
if (!launchStatus) {
// Why: launchAgent is set the instant Orca spawns the tab, but the runtime
// only accepts a send once the pane reads as an agent. Skipping until the
// title is recognized keeps "listed ⇒ sendable" and avoids the boot-window
// "not a recognized agent session" error.
continue
}
const disabledReason = launchStatus === 'permission' ? 'Agent needs permission' : undefined
targets.push({
paneKey: makePaneKey(tab.id, leafId),
@@ -108,7 +137,8 @@ export function deriveNotesSendAgentTargets(
leafId,
agentType: tab.launchAgent,
tabTitle: tab.title,
status: 'eligible'
status: disabledReason ? 'disabled' : 'eligible',
...(disabledReason ? { disabledReason } : {})
})
}
@@ -54,7 +54,11 @@ function state(
overrides: Partial<
Pick<
AppState,
'agentStatusByPaneKey' | 'tabsByWorktree' | 'terminalLayoutsByTabId' | 'ptyIdsByTabId'
| 'agentStatusByPaneKey'
| 'tabsByWorktree'
| 'terminalLayoutsByTabId'
| 'ptyIdsByTabId'
| 'runtimePaneTitlesByTabId'
>
> = {}
) {
@@ -67,10 +71,15 @@ function state(
},
terminalLayoutsByTabId,
ptyIdsByTabId: deriveLivePtyIdsByTabId(terminalLayoutsByTabId),
runtimePaneTitlesByTabId: {},
...overrides
} as Pick<
AppState,
'agentStatusByPaneKey' | 'tabsByWorktree' | 'terminalLayoutsByTabId' | 'ptyIdsByTabId'
| 'agentStatusByPaneKey'
| 'tabsByWorktree'
| 'terminalLayoutsByTabId'
| 'ptyIdsByTabId'
| 'runtimePaneTitlesByTabId'
>
}
@@ -108,7 +117,7 @@ describe('running agent send targets', () => {
expect(targets[0]).not.toHaveProperty('disabledReason')
})
it('allows fresh waiting and blocked agent states when the pane has a leaf PTY', () => {
it('allows working agents and disables permission states when the pane has a leaf PTY', () => {
const workingPaneKey = makePaneKey(TAB_ID, LEFT_LEAF_ID)
const waitingPaneKey = makePaneKey(TAB_ID, RIGHT_LEAF_ID)
const blockedPaneKey = makePaneKey(OTHER_TAB_ID, OTHER_LEAF_ID)
@@ -151,20 +160,51 @@ describe('running agent send targets', () => {
expect(resolveRunningAgentSendTarget(state(), WORKTREE_ID, 'missing')).toBeNull()
expect(targets.find((target) => target.paneKey === workingPaneKey)).toMatchObject({
status: 'disabled',
disabledReason: 'Agent is working',
status: 'eligible',
ptyId: 'pty-left'
})
expect(targets.find((target) => target.paneKey === waitingPaneKey)).toMatchObject({
status: 'eligible',
status: 'disabled',
disabledReason: 'Agent needs permission',
ptyId: 'pty-right'
})
expect(targets.find((target) => target.paneKey === blockedPaneKey)).toMatchObject({
status: 'eligible',
status: 'disabled',
disabledReason: 'Agent needs permission',
ptyId: 'pty-other'
})
})
it('disables a status-backed working row when the live pane title needs permission', () => {
const paneKey = makePaneKey(TAB_ID, LEFT_LEAF_ID)
const targets = deriveRunningAgentSendTargets(
state({
agentStatusByPaneKey: { [paneKey]: entry(paneKey, 'working') },
tabsByWorktree: { [WORKTREE_ID]: [tab(TAB_ID, WORKTREE_ID, 'pty-left')] },
terminalLayoutsByTabId: {
[TAB_ID]: {
root: { type: 'leaf', leafId: LEFT_LEAF_ID },
activeLeafId: LEFT_LEAF_ID,
expandedLeafId: null,
ptyIdsByLeafId: { [LEFT_LEAF_ID]: 'pty-left' }
}
},
runtimePaneTitlesByTabId: { [TAB_ID]: { 1: 'Codex - action required' } }
}),
WORKTREE_ID,
NOW
)
expect(targets).toMatchObject([
{
paneKey,
status: 'disabled',
disabledReason: 'Agent needs permission',
ptyId: 'pty-left'
}
])
})
it('disables stale agent status rows even when the pane still has a leaf PTY', () => {
const stalePaneKey = makePaneKey(TAB_ID, RIGHT_LEAF_ID)
const target = resolveRunningAgentSendTarget(
@@ -179,7 +219,8 @@ describe('running agent send targets', () => {
expandedLeafId: null,
ptyIdsByLeafId: { [RIGHT_LEAF_ID]: 'pty-right' }
}
}
},
runtimePaneTitlesByTabId: { [TAB_ID]: { 1: 'Codex - action required' } }
}),
WORKTREE_ID,
stalePaneKey,
@@ -211,7 +252,8 @@ describe('running agent send targets', () => {
expandedLeafId: null,
ptyIdsByLeafId: { [LEFT_LEAF_ID]: 'pty-left' }
}
}
},
runtimePaneTitlesByTabId: { [TAB_ID]: { 2: 'Codex - action required' } }
}),
WORKTREE_ID,
paneKey,
@@ -282,7 +324,8 @@ describe('running agent send targets', () => {
expect(
resolveRunningAgentSendTarget(base, OTHER_WORKTREE_ID, remotePaneKey, NOW)
).toMatchObject({
status: 'eligible',
status: 'disabled',
disabledReason: 'Agent needs permission',
ptyId: 'remote:env@@terminal-1'
})
})
+30 -4
View File
@@ -5,12 +5,18 @@ import {
} from '../../../shared/agent-status-types'
import type { TerminalTab } from '../../../shared/types'
import { parsePaneKey } from '../../../shared/stable-pane-id'
import { isExplicitAgentStatusFresh } from './agent-status'
import {
detectAgentStatusFromTitle,
getAgentLabel,
isExplicitAgentStatusFresh
} from './agent-status'
import { resolveRuntimePaneTitleForLeaf } from './runtime-pane-title-leaf-id'
export type RunningAgentTargetState = Pick<
AppState,
'agentStatusByPaneKey' | 'tabsByWorktree' | 'terminalLayoutsByTabId' | 'ptyIdsByTabId'
>
> &
Partial<Pick<AppState, 'runtimePaneTitlesByTabId'>>
export type RunningAgentSendTarget = {
paneKey: string
@@ -59,8 +65,10 @@ export function deriveRunningAgentSendTargets(
disabledReason = 'Agent status is stale'
} else if (!ptyId) {
disabledReason = 'Terminal is no longer available'
} else if (entry.state === 'working') {
disabledReason = 'Agent is working'
} else if (entry.state === 'blocked' || entry.state === 'waiting') {
disabledReason = 'Agent needs permission'
} else if (hasPermissionPaneTitle(state, parsed.tabId, parsed.leafId, tab.title)) {
disabledReason = 'Agent needs permission'
}
targets.push({
@@ -78,6 +86,24 @@ export function deriveRunningAgentSendTargets(
return targets
}
function hasPermissionPaneTitle(
state: RunningAgentTargetState,
tabId: string,
leafId: string,
tabTitle: string
): boolean {
const layout = state.terminalLayoutsByTabId[tabId]
const paneTitle = resolveRuntimePaneTitleForLeaf(
layout,
state.runtimePaneTitlesByTabId?.[tabId],
leafId
)
// Why: runtime pane titles are the freshest title signal for split panes; use
// the tab title only before the runtime has reported a pane title for the leaf.
const title = paneTitle ?? tabTitle
return detectAgentStatusFromTitle(title) === 'permission' && getAgentLabel(title) !== null
}
export function resolveRunningAgentSendTarget(
state: RunningAgentTargetState,
worktreeId: string,
+120 -31
View File
@@ -23,15 +23,19 @@ import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
import type { TaskSourceContext } from '../../../../shared/task-source-context'
const mocks = vi.hoisted(() => ({
sendBracketedPasteToRunningAgent: vi.fn(),
sendNotesToActiveAgentSession: vi.fn(),
track: vi.fn(),
toastMessage: vi.fn(),
toastSuccess: vi.fn(),
toastError: vi.fn()
}))
vi.mock('@/lib/agent-paste-draft', () => ({
sendBracketedPasteToRunningAgent: mocks.sendBracketedPasteToRunningAgent
vi.mock('@/lib/active-agent-note-send', () => ({
activeAgentNotesSendFailureMessage: (
status: string,
options: { explicitTarget?: boolean } = {}
) => (options.explicitTarget ? `selected:${status}` : status),
sendNotesToActiveAgentSession: mocks.sendNotesToActiveAgentSession
}))
vi.mock('@/lib/telemetry', () => ({
@@ -52,7 +56,8 @@ afterEach(() => {
})
beforeEach(() => {
mocks.sendBracketedPasteToRunningAgent.mockReset()
mocks.sendNotesToActiveAgentSession.mockReset()
mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'sent' })
mocks.track.mockReset()
mocks.toastMessage.mockReset()
mocks.toastSuccess.mockReset()
@@ -274,10 +279,8 @@ describe('createUISlice agent send target mode', () => {
expect(store.getState().agentSendPopoverTargetMode).toMatchObject({
id: 'send-1',
eligiblePaneKeys: [readyPaneKey],
disabledPaneKeys: {
[workingPaneKey]: 'Agent is working'
},
eligiblePaneKeys: [readyPaneKey, workingPaneKey],
disabledPaneKeys: {},
status: 'open'
})
expect(store.getState().pendingRevealWorktree).toMatchObject({
@@ -287,6 +290,43 @@ describe('createUISlice agent send target mode', () => {
})
})
it('disables sidebar target rows that need permission', async () => {
const store = createUIStore()
seedAgentSendState(store)
const agentStatusByPaneKey = store.getState().agentStatusByPaneKey
store.setState({
agentStatusByPaneKey: {
...agentStatusByPaneKey,
[workingPaneKey]: {
...agentStatusByPaneKey[workingPaneKey]!,
state: 'blocked'
}
}
} as Partial<AppState>)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: 'Review this',
label: 'All unsent notes',
launchSource: 'notes_send'
})
expect(store.getState().agentSendPopoverTargetMode).toMatchObject({
id: 'send-1',
eligiblePaneKeys: [readyPaneKey],
disabledPaneKeys: {
[workingPaneKey]: 'Agent needs permission'
},
status: 'open'
})
await expect(store.getState().sendPromptToSidebarAgentTarget(workingPaneKey)).resolves.toBe(
false
)
expect(mocks.sendNotesToActiveAgentSession).not.toHaveBeenCalled()
})
it('does not reveal the sidebar when the current workspace has no eligible targets', () => {
const store = createUIStore()
seedAgentSendState(store)
@@ -336,7 +376,6 @@ describe('createUISlice agent send target mode', () => {
const store = createUIStore()
const onPromptDelivered = vi.fn()
seedAgentSendState(store)
mocks.sendBracketedPasteToRunningAgent.mockResolvedValue(true)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
@@ -349,9 +388,10 @@ describe('createUISlice agent send target mode', () => {
await expect(store.getState().sendPromptToSidebarAgentTarget(readyPaneKey)).resolves.toBe(true)
expect(mocks.sendBracketedPasteToRunningAgent).toHaveBeenCalledWith({
ptyId: 'pty-ready',
content: 'Review this'
expect(mocks.sendNotesToActiveAgentSession).toHaveBeenCalledWith({
worktreeId,
prompt: 'Review this',
noteTarget: { tabId, leafId: readyLeafId }
})
expect(onPromptDelivered).toHaveBeenCalledTimes(1)
expect(mocks.track).toHaveBeenCalledWith('agent_prompt_sent', {
@@ -367,7 +407,7 @@ describe('createUISlice agent send target mode', () => {
const store = createUIStore()
const onPromptDelivered = vi.fn()
seedAgentSendState(store)
mocks.sendBracketedPasteToRunningAgent.mockResolvedValue(false)
mocks.sendNotesToActiveAgentSession.mockResolvedValue({ status: 'not-ready' })
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
@@ -383,19 +423,18 @@ describe('createUISlice agent send target mode', () => {
expect(onPromptDelivered).not.toHaveBeenCalled()
expect(mocks.track).not.toHaveBeenCalled()
expect(mocks.toastError).toHaveBeenCalledWith("Couldn't send to Codex", {
description: 'Terminal is no longer available'
description: 'selected:not-ready'
})
expect(store.getState().agentSendPopoverTargetMode).toMatchObject({
id: 'send-1',
status: 'error',
error: 'Terminal is no longer available'
error: 'selected:not-ready'
})
})
it('does not send to a working agent row', async () => {
it('sends to a working agent row through the selected-target note helper', async () => {
const store = createUIStore()
seedAgentSendState(store)
mocks.sendBracketedPasteToRunningAgent.mockResolvedValue(true)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
@@ -406,29 +445,32 @@ describe('createUISlice agent send target mode', () => {
})
await expect(store.getState().sendPromptToSidebarAgentTarget(workingPaneKey)).resolves.toBe(
false
true
)
expect(mocks.sendBracketedPasteToRunningAgent).not.toHaveBeenCalled()
expect(mocks.toastSuccess).not.toHaveBeenCalled()
expect(store.getState().agentSendPopoverTargetMode).toMatchObject({
id: 'send-1',
status: 'open'
expect(mocks.sendNotesToActiveAgentSession).toHaveBeenCalledWith({
worktreeId,
prompt: 'Review this',
noteTarget: { tabId, leafId: workingLeafId }
})
expect(mocks.toastSuccess).toHaveBeenCalledWith('Sent to Codex')
expect(store.getState().agentSendPopoverTargetMode).toBeNull()
})
it('does not let an older send close a reopened popover with the same id', async () => {
const store = createUIStore()
const write = deferred<boolean>()
const onPromptDelivered = vi.fn()
const write = deferred<{ status: 'sent' }>()
seedAgentSendState(store)
mocks.sendBracketedPasteToRunningAgent.mockReturnValue(write.promise)
mocks.sendNotesToActiveAgentSession.mockReturnValue(write.promise)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: 'Review this',
label: 'All unsent notes',
launchSource: 'notes_send'
launchSource: 'notes_send',
onPromptDelivered
})
const send = store.getState().sendPromptToSidebarAgentTarget(readyPaneKey)
@@ -443,8 +485,8 @@ describe('createUISlice agent send target mode', () => {
})
const reopenedMode = store.getState().agentSendPopoverTargetMode
write.resolve(true)
await expect(send).resolves.toBe(true)
write.resolve({ status: 'sent' })
await expect(send).resolves.toBe(false)
expect(store.getState().agentSendPopoverTargetMode).toBe(reopenedMode)
expect(store.getState().agentSendPopoverTargetMode).toMatchObject({
@@ -452,13 +494,60 @@ describe('createUISlice agent send target mode', () => {
prompt: 'Review this again',
status: 'open'
})
expect(onPromptDelivered).not.toHaveBeenCalled()
expect(mocks.track).not.toHaveBeenCalled()
expect(mocks.toastSuccess).not.toHaveBeenCalled()
expect(mocks.toastError).not.toHaveBeenCalled()
})
it('does not let an older send failure mutate a reopened popover with the same id', async () => {
const store = createUIStore()
const onPromptDelivered = vi.fn()
const write = deferred<{ status: 'not-ready' }>()
seedAgentSendState(store)
mocks.sendNotesToActiveAgentSession.mockReturnValue(write.promise)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: 'Review this',
label: 'All unsent notes',
launchSource: 'notes_send',
onPromptDelivered
})
const send = store.getState().sendPromptToSidebarAgentTarget(readyPaneKey)
store.getState().closeAgentSendPopoverTargetMode('send-1')
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
source: 'diff-notes',
prompt: 'Review this again',
label: 'All unsent notes',
launchSource: 'notes_send'
})
const reopenedMode = store.getState().agentSendPopoverTargetMode
write.resolve({ status: 'not-ready' })
await expect(send).resolves.toBe(false)
expect(store.getState().agentSendPopoverTargetMode).toBe(reopenedMode)
expect(store.getState().agentSendPopoverTargetMode).toMatchObject({
id: 'send-1',
prompt: 'Review this again',
status: 'open'
})
expect(onPromptDelivered).not.toHaveBeenCalled()
expect(mocks.track).not.toHaveBeenCalled()
expect(mocks.toastSuccess).not.toHaveBeenCalled()
expect(mocks.toastError).not.toHaveBeenCalled()
})
it('does not retarget the same popover while a send is in progress', async () => {
const store = createUIStore()
const write = deferred<boolean>()
const write = deferred<{ status: 'sent' }>()
seedAgentSendState(store)
mocks.sendBracketedPasteToRunningAgent.mockReturnValue(write.promise)
mocks.sendNotesToActiveAgentSession.mockReturnValue(write.promise)
store.getState().openAgentSendPopoverTargetMode({
id: 'send-1',
worktreeId,
@@ -487,7 +576,7 @@ describe('createUISlice agent send target mode', () => {
sendingPaneKey: readyPaneKey
})
write.resolve(true)
write.resolve({ status: 'sent' })
await expect(send).resolves.toBe(true)
})
})
+28 -8
View File
@@ -979,14 +979,28 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
)
const label = formatAgentTypeLabel(target.entry.agentType)
const { sendBracketedPasteToRunningAgent } = await import('@/lib/agent-paste-draft')
const delivered = await sendBracketedPasteToRunningAgent({
ptyId: target.ptyId,
content: mode.prompt
}).catch(() => false)
const { activeAgentNotesSendFailureMessage, sendNotesToActiveAgentSession } =
await import('@/lib/active-agent-note-send')
const result = await sendNotesToActiveAgentSession({
worktreeId: mode.worktreeId,
prompt: mode.prompt,
noteTarget: { tabId: target.tabId, leafId: target.leafId }
}).catch((error) => {
console.error('Failed to send notes to sidebar agent target:', error)
return { status: 'no-active-terminal' as const }
})
if (!delivered) {
const message = 'Terminal is no longer available'
const stillCurrent = (): boolean => {
const current = get().agentSendPopoverTargetMode
return current?.id === mode.id && current.instanceId === mode.instanceId
}
if (!stillCurrent()) {
return false
}
if (result.status !== 'sent') {
const message = activeAgentNotesSendFailureMessage(result.status, { explicitTarget: true })
set((s) =>
s.agentSendPopoverTargetMode?.id === mode.id &&
s.agentSendPopoverTargetMode.instanceId === mode.instanceId
@@ -1001,6 +1015,9 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
: s
)
const { toast } = await import('sonner')
if (!stillCurrent()) {
return false
}
toast.error(
translate('auto.store.slices.ui.53883b7bc3', "Couldn't send to {{value0}}", {
value0: label
@@ -1010,8 +1027,11 @@ export const createUISlice: StateCreator<AppState, [], [], UISlice> = (set, get)
return false
}
mode.onPromptDelivered?.()
const [{ toast }, { track }] = await Promise.all([import('sonner'), import('@/lib/telemetry')])
if (!stillCurrent()) {
return false
}
mode.onPromptDelivered?.()
track('agent_prompt_sent', {
agent_kind: agentKindForAgentType(target.entry.agentType),
launch_source: mode.launchSource,
@@ -7,6 +7,7 @@ describe('runtime RPC call queue', () => {
expect(isBackgroundRuntimeMethod('hostedReview.forBranch')).toBe(true)
expect(isBackgroundRuntimeMethod('worktree.prefetchCreateBase')).toBe(true)
expect(isBackgroundRuntimeMethod('terminal.send')).toBe(false)
expect(isBackgroundRuntimeMethod('terminal.agentStatus')).toBe(false)
expect(isBackgroundRuntimeMethod('worktree.create')).toBe(false)
})
+9
View File
@@ -427,6 +427,15 @@ export type RuntimeTerminalSend = {
handle: string
accepted: boolean
bytesWritten: number
refusedReason?: 'no-agent' | 'permission'
}
export type RuntimeTerminalAgentStatusState = 'working' | 'permission' | 'idle' | null
export type RuntimeTerminalAgentStatus = {
handle: string
isRunningAgent: boolean
status: RuntimeTerminalAgentStatusState
}
export type RuntimeTerminalCreate = {