From 5bf793284a2eab9c5e895237eacc7dafa038c644 Mon Sep 17 00:00:00 2001 From: Neil Date: Tue, 20 Oct 2026 23:43:52 -0700 Subject: [PATCH 1/7] fix(native-chat): send OMP question answers through its selector Adapt the community navigation-key answer plan for desktop and mobile, including OMP multi-select parsing and paced mobile delivery coverage. Refs: https://github.com/stablyai/orca/pull/26688 Refs: https://github.com/stablyai/orca/pull/29184 Fixes: #26692 Co-authored-by: jairuspace Co-authored-by: Daniel Lopez --- ...mobile-native-chat-answer-send-omp.test.ts | 109 ++++++++++++++++ .../use-mobile-native-chat-answer-send.ts | 20 +-- .../native-chat-interactive-prompt.test.ts | 122 ++++++++++++++++++ .../native-chat-interactive-prompt.ts | 4 + .../use-native-chat-interactive-send.ts | 10 +- src/shared/native-chat-agent-support.test.ts | 4 +- src/shared/native-chat-agent-support.ts | 5 +- src/shared/native-chat-ask.test.ts | 15 +++ src/shared/native-chat-ask.ts | 74 ++++++++++- 9 files changed, 338 insertions(+), 25 deletions(-) create mode 100644 mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts diff --git a/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts b/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts new file mode 100644 index 000000000000..9fa32d6ce410 --- /dev/null +++ b/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts @@ -0,0 +1,109 @@ +// Takeover RPCs have their own send-site integration tests; these fixtures script PTY acknowledgements. +vi.mock('../terminal/worker-terminal-takeover-report', () => ({ + reportWorkerTerminalUserInput: vi.fn() +})) + +import { createElement } from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + formatAskAnswer, + type AskAnswerSelection, + type AskPrompt +} from '../../../src/shared/native-chat-ask' +import { AGENT_TUI_CLEAR_INPUT_MAX } from '../../../src/shared/agent-tui-input-clear' +import type { AgentType } from '../../../src/shared/native-chat-types' +import type { RpcClient } from '../transport/rpc-client' +import { MOBILE_NATIVE_CHAT_QUESTION_STEP_MS } from './mobile-native-chat-answer-stepping' +import { resetMobileNativeChatStaleInputForTests } from './mobile-native-chat-stale-input' +import { resetMobileNativeChatTerminalWritesForTests } from './mobile-native-chat-terminal-write-lock' +import { + useMobileNativeChatAnswerSend, + type MobileNativeChatAnswerSend +} from './use-mobile-native-chat-answer-send' + +function acceptedResponse() { + return { + id: 'send', + ok: true as const, + result: { send: { accepted: true } }, + _meta: { runtimeId: 'runtime' } + } +} + +describe('useMobileNativeChatAnswerSend for OMP asks', () => { + let renderer: ReactTestRenderer | null = null + let answerSend: MobileNativeChatAnswerSend | null = null + + beforeEach(() => { + vi.useFakeTimers() + resetMobileNativeChatStaleInputForTests() + resetMobileNativeChatTerminalWritesForTests() + }) + + afterEach(() => { + act(() => renderer?.unmount()) + renderer = null + answerSend = null + vi.useRealTimers() + }) + + async function mount(client: RpcClient, agent: AgentType): Promise { + function Harness(): null { + answerSend = useMobileNativeChatAnswerSend({ + client, + enabled: true, + handleRef: { current: 'terminal' }, + deviceTokenRef: { current: 'device' }, + agentRef: { current: agent }, + sessionId: 'session', + streamIdentity: 'host\0worktree\0tab\0session', + onSendError: vi.fn() + }) + return null + } + await act(async () => { + renderer = create(createElement(Harness)) + }) + } + + it('writes OMP groups from the shared key plan, paced, never as pasted labels', async () => { + const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture exercises only the scripted sendRequest port. + await mount({ sendRequest } as unknown as RpcClient, 'omp') + const prompt: AskPrompt = { + questions: [ + { question: 'q1', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] }, + { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } + ] + } + const selections: AskAnswerSelection[] = [{ indices: [1] }, { indices: [0] }] + const expected = [ + AGENT_TUI_CLEAR_INPUT_MAX, + '\x1b[A\x1b[A\x1b[B', + '\r', + '\x1b[A\x1b[A', + '\r', + '\r' + ] + + let result: Promise | undefined + await act(async () => { + result = answerSend?.answerAsk(prompt, selections) + }) + expect(sendRequest).toHaveBeenCalledTimes(1) + for (let index = 1; index < expected.length; index += 1) { + await act(async () => { + await vi.advanceTimersByTimeAsync(MOBILE_NATIVE_CHAT_QUESTION_STEP_MS) + }) + expect(sendRequest).toHaveBeenCalledTimes(index + 1) + } + await expect(result).resolves.toBe(true) + expect(sendRequest.mock.calls.map((call) => call[1])).toEqual( + expected.map((text) => expect.objectContaining({ text, enter: false })) + ) + expect(sendRequest.mock.calls.map((call) => call[1])).not.toContainEqual( + expect.objectContaining({ text: formatAskAnswer(prompt, selections), enter: true }) + ) + }) +}) diff --git a/mobile/src/session/use-mobile-native-chat-answer-send.ts b/mobile/src/session/use-mobile-native-chat-answer-send.ts index b9b2ecdf0ecb..1ea3c7330503 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send.ts @@ -1,7 +1,6 @@ import { useCallback, useEffect, useRef, type MutableRefObject } from 'react' import { - buildAskAnswerKeys, - buildCodexAskAnswerKeys, + buildNativeChatAskAnswerKeys, formatAskAnswer, hasAskAnswer, type AskAnswerSelection, @@ -18,13 +17,10 @@ import { acquireMobileNativeChatTerminalWrite, releaseMobileNativeChatTerminalWrite } from './mobile-native-chat-terminal-write-lock' -import { - resolveNativeChatTranscriptAgent, - shouldStepNativeChatAskAnswer -} from '../../../src/shared/native-chat-agent-support' +import { shouldStepNativeChatAskAnswer } from '../../../src/shared/native-chat-agent-support' -/** Sends an ask-user answer to the active chat pane. Claude and Codex selectors - * use their agent-specific keystrokes; other agents get pasted label text. +/** Sends an ask-user answer to the active chat pane. Selector agents use their + * own keystrokes; other agents get pasted label text. * Extracted from the session route to keep that file under its line cap and to * own the pending-timer lifecycle in one place. */ export type MobileNativeChatAnswerSend = { @@ -224,8 +220,7 @@ export function useMobileNativeChatAnswerSend(args: { } return false } - // Grok commits pasted labels; Claude and Codex need their selector-specific - // keystrokes paced so each step renders before the next lands. + // Selector keystrokes are paced so each step renders before the next lands. if (!shouldStepNativeChatAskAnswer(agentRef.current)) { // This shape pastes the label into the composer and commits it, so an // orphaned image paste would be submitted along with the answer (#10228). @@ -259,10 +254,7 @@ export function useMobileNativeChatAnswerSend(args: { const sent = (await sendTerminal(formatAskAnswer(prompt, selections), true)) || fail() return sent && writeTurnsRef.current.get(handle) === turn } - const groups = - resolveNativeChatTranscriptAgent(agentRef.current) === 'codex' - ? buildCodexAskAnswerKeys(prompt, selections) - : buildAskAnswerKeys(prompt, selections) + const groups = buildNativeChatAskAnswerKeys(agentRef.current, prompt, selections) for (let index = 0; index < groups.length; index += 1) { if (generationRef.current !== generation) { return false diff --git a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts index 4cbc4c692eae..f827a7870cc1 100644 --- a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts @@ -2,6 +2,8 @@ import { describe, expect, it } from 'vitest' import { buildAskAnswerKeys, buildCodexAskAnswerKeys, + buildNativeChatAskAnswerKeys, + buildOmpAskAnswerKeys, formatAskAnswer, hasAskAnswer, parseApprovalFromStatus, @@ -9,6 +11,7 @@ import { parseInteractivePrompt, type AskPrompt } from './native-chat-interactive-prompt' +import { AGENT_TUI_CLEAR_INPUT_MAX } from '../../../../shared/agent-tui-input-clear' const ESC = String.fromCharCode(27) @@ -302,3 +305,122 @@ for (const agent of ['opencode', 'opencode2']) { expect(card?.options[0].send).toBe('\r') }) } + +describe('buildOmpAskAnswerKeys', () => { + const UP = '\x1b[A' + const DOWN = '\x1b[B' + const ENTER = '\r' + const RIGHT = '\x1b[C' + const SPACE = ' ' + const CLEAR = { raw: AGENT_TUI_CLEAR_INPUT_MAX } + + it('homes to row 0 then moves down to the picked option before Enter', () => { + expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [1] }])).toEqual([ + CLEAR, + { raw: `${UP}${UP}${UP}${DOWN}` }, + { raw: ENTER } + ]) + }) + + it('homes only when the first option is picked', () => { + expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [0] }])).toEqual([ + CLEAR, + { raw: `${UP}${UP}${UP}` }, + { raw: ENTER } + ]) + }) + + it('routes free text through the Other row and submits the editor', () => { + expect( + buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [], other: 'Custom' }]) + ).toEqual([ + CLEAR, + { raw: `${UP}${UP}${UP}${DOWN}${DOWN}${DOWN}` }, + { raw: ENTER }, + { text: 'Custom' }, + { raw: ENTER } + ]) + }) + + it('toggles multi-select picks with Space, then Right to Review and Enter to submit', () => { + // OMP >= 18.2: Enter on a multi-select row confirms and advances; only Space toggles. + expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C'], true), [{ indices: [0, 2] }])).toEqual([ + CLEAR, + { raw: `${UP}${UP}${UP}` }, + { raw: SPACE }, + { raw: `${UP}${UP}${UP}${DOWN}${DOWN}` }, + { raw: SPACE }, + { raw: RIGHT }, + { raw: ENTER } + ]) + }) + + it('does not step again after multi-select free text, which advances on its own', () => { + expect( + buildOmpAskAnswerKeys(single(['A', 'B', 'C'], true), [{ indices: [1], other: 'D' }]) + ).toEqual([ + CLEAR, + { raw: `${UP}${UP}${UP}${DOWN}` }, + { raw: SPACE }, + { raw: `${UP}${UP}${UP}${DOWN}${DOWN}${DOWN}` }, + { raw: ENTER }, + { text: 'D' }, + { raw: ENTER }, + { raw: ENTER } + ]) + const prompt: AskPrompt = { + questions: [ + { question: 'q1', multiSelect: true, options: [{ label: 'A' }, { label: 'B' }] }, + { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } + ] + } + expect(buildOmpAskAnswerKeys(prompt, [{ indices: [], other: 'x' }, { indices: [1] }])).toEqual([ + CLEAR, + { raw: `${UP}${UP}${DOWN}${DOWN}` }, + { raw: ENTER }, + { text: 'x' }, + { raw: ENTER }, + { raw: `${UP}${UP}${DOWN}` }, + { raw: ENTER }, + { raw: ENTER } + ]) + }) + + it('steps past an unanswered question in a multi-question prompt', () => { + const prompt: AskPrompt = { + questions: [ + { question: 'q1', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] }, + { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } + ] + } + + expect(buildOmpAskAnswerKeys(prompt, [{ indices: [1] }, { indices: [] }])).toEqual([ + CLEAR, + { raw: `${UP}${UP}${DOWN}` }, + { raw: ENTER }, + { raw: RIGHT }, + { raw: ENTER } + ]) + }) + + it('returns no keys when nothing is answered', () => { + expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [] }])).toEqual([]) + expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [])).toEqual([]) + }) +}) + +describe('buildNativeChatAskAnswerKeys', () => { + it('dispatches by agent to the matching builder', () => { + const prompt = single(['A', 'B', 'C']) + const selections = [{ indices: [1] }] + expect(buildNativeChatAskAnswerKeys('omp', prompt, selections)).toEqual( + buildOmpAskAnswerKeys(prompt, selections) + ) + expect(buildNativeChatAskAnswerKeys('codex', prompt, selections)).toEqual( + buildCodexAskAnswerKeys(prompt, selections) + ) + expect(buildNativeChatAskAnswerKeys('claude', prompt, selections)).toEqual( + buildAskAnswerKeys(prompt, selections) + ) + }) +}) diff --git a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.ts b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.ts index baaf6803a234..0601a82af993 100644 --- a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.ts +++ b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.ts @@ -7,6 +7,8 @@ import type { import { buildAskAnswerKeys, buildCodexAskAnswerKeys, + buildNativeChatAskAnswerKeys, + buildOmpAskAnswerKeys, formatAskAnswer, hasAskAnswer, parseAskFromStatus, @@ -22,6 +24,8 @@ import { export { buildAskAnswerKeys, buildCodexAskAnswerKeys, + buildNativeChatAskAnswerKeys, + buildOmpAskAnswerKeys, formatAskAnswer, hasAskAnswer, parseAskFromStatus, diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts index 9ad2d4f53bb6..9fcedbe75e47 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts @@ -8,8 +8,7 @@ import { shouldStepNativeChatAskAnswer } from '../../../../shared/native-chat-agent-support' import { - buildAskAnswerKeys, - buildCodexAskAnswerKeys, + buildNativeChatAskAnswerKeys, formatAskAnswer, hasAskAnswer, type AskAnswerSelection, @@ -103,9 +102,8 @@ export function useNativeChatInteractiveSend( } // Cancel any prior in-flight answer before starting a new one. cancelInFlight() - // Selector TUIs ignore pasted labels; Codex uses a different key sequence. + // Selector TUIs ignore pasted labels; each agent's selector takes its own key sequence. const stepsAnswer = shouldStepNativeChatAskAnswer(agent) - const buildsCodexAnswer = resolveNativeChatTranscriptAgent(agent) === 'codex' // Why: pin the answered question's baseline BEFORE delivery. A late settle // callback (paced writes + remote acceptance can span seconds on SSH) must // not read the live status and mint a fresh baseline for a replacement @@ -138,9 +136,7 @@ export function useNativeChatInteractiveSend( const handle: NativeChatSendHandle = stepsAnswer ? sendNativeChatAskAnswer( targetPtyId, - buildsCodexAnswer - ? buildCodexAskAnswerKeys(prompt, selections) - : buildAskAnswerKeys(prompt, selections), + buildNativeChatAskAnswerKeys(agent, prompt, selections), onSettled ) : sendNativeChatMessage(targetPtyId, formatAskAnswer(prompt, selections), { diff --git a/src/shared/native-chat-agent-support.test.ts b/src/shared/native-chat-agent-support.test.ts index 3da69dd80a0d..20e185df47a4 100644 --- a/src/shared/native-chat-agent-support.test.ts +++ b/src/shared/native-chat-agent-support.test.ts @@ -60,7 +60,7 @@ describe('nativeChatRequiresLocalTranscript', () => { }) describe('shouldStepNativeChatAskAnswer', () => { - it('steps the digit-commit selector agents (Claude, OpenClaude, Codex)', () => { + it('steps the selector agents (Claude, OpenClaude, Codex, OpenCode, OMP)', () => { expect(shouldStepNativeChatAskAnswer('claude')).toBe(true) expect(shouldStepNativeChatAskAnswer('openclaude')).toBe(true) // Codex 0.145's request_user_input card ignores typed labels and commits on @@ -68,11 +68,11 @@ describe('shouldStepNativeChatAskAnswer', () => { expect(shouldStepNativeChatAskAnswer('codex')).toBe(true) expect(shouldStepNativeChatAskAnswer('opencode')).toBe(true) expect(shouldStepNativeChatAskAnswer('opencode2')).toBe(true) + expect(shouldStepNativeChatAskAnswer('omp')).toBe(true) }) it('does not step other or unknown agents', () => { expect(shouldStepNativeChatAskAnswer('grok')).toBe(false) - expect(shouldStepNativeChatAskAnswer('omp')).toBe(false) expect(shouldStepNativeChatAskAnswer('cursor')).toBe(false) expect(shouldStepNativeChatAskAnswer(null)).toBe(false) expect(shouldStepNativeChatAskAnswer(undefined)).toBe(false) diff --git a/src/shared/native-chat-agent-support.ts b/src/shared/native-chat-agent-support.ts index b0956a97a81d..f4909b5f5498 100644 --- a/src/shared/native-chat-agent-support.ts +++ b/src/shared/native-chat-agent-support.ts @@ -33,7 +33,10 @@ export function nativeChatRequiresLocalTranscript(agent: string | null | undefin export function shouldStepNativeChatAskAnswer(agent: string | null | undefined): boolean { const transcriptAgent = resolveNativeChatTranscriptAgent(agent) return ( - transcriptAgent === 'claude' || transcriptAgent === 'codex' || transcriptAgent === 'opencode' + transcriptAgent === 'claude' || + transcriptAgent === 'codex' || + transcriptAgent === 'opencode' || + transcriptAgent === 'omp' ) } diff --git a/src/shared/native-chat-ask.test.ts b/src/shared/native-chat-ask.test.ts index 0c9ff11753ee..979fb0cbca53 100644 --- a/src/shared/native-chat-ask.test.ts +++ b/src/shared/native-chat-ask.test.ts @@ -8,6 +8,7 @@ import { extractPendingAsk, nativeChatAskDismissKey, parseAskFromStatus, + parseAskFromToolInput, resolveNativeChatAsk } from './native-chat-ask' @@ -223,3 +224,17 @@ describe('resolveNativeChatAsk', () => { ) }) }) + +describe('parseAskFromToolInput OMP multi flag', () => { + it('treats OMP multi: true as a multi-select question', () => { + expect( + parseAskFromToolInput('ask', { + questions: [{ id: 'checks', question: 'Q', options: [{ label: 'A' }], multi: true }] + }) + ).toEqual({ + questions: [ + { question: 'Q', header: undefined, multiSelect: true, options: [{ label: 'A' }] } + ] + }) + }) +}) diff --git a/src/shared/native-chat-ask.ts b/src/shared/native-chat-ask.ts index 44ee53c6c7de..e538a9295b5c 100644 --- a/src/shared/native-chat-ask.ts +++ b/src/shared/native-chat-ask.ts @@ -5,6 +5,8 @@ import type { InteractiveQuestionParser } from './native-chat-ask-types' import { isInterruptedStatusMessage, type NativeChatMessage } from './native-chat-types' +import { resolveNativeChatTranscriptAgent } from './native-chat-agent-support' +import { AGENT_TUI_CLEAR_INPUT_MAX } from './agent-tui-input-clear' export type { AskOption, AskPrompt, AskQuestion, InteractiveQuestionParser } @@ -38,10 +40,12 @@ function parseCanonicalQuestionsInput(input: unknown): AskPrompt | null { questions.push({ question: text, header: 'header' in raw && typeof raw.header === 'string' ? raw.header : undefined, + // Why: OpenCode names the flag `multiple`, OMP's ask tool `multi`. multiSelect: 'multiSelect' in raw ? raw.multiSelect === true - : 'multiple' in raw && raw.multiple === true, + : ('multiple' in raw && raw.multiple === true) || + ('multi' in raw && raw.multi === true), options }) } @@ -328,6 +332,74 @@ export function buildCodexAskAnswerKeys( return groups } +// OMP >= 18.2 uses arrows, Space to toggle, and Enter to select. +export function buildOmpAskAnswerKeys( + prompt: AskPrompt, + selections: AskAnswerSelection[] +): AskAnswerKeyGroup[] { + if (!hasAskAnswer(prompt, selections)) { + return [] + } + const hasSubmitTab = prompt.questions.length > 1 || prompt.questions.some((q) => q.multiSelect) + // Clear any draft that would otherwise consume the dialog keys. + const groups: AskAnswerKeyGroup[] = [{ raw: AGENT_TUI_CLEAR_INPUT_MAX }] + const moveTo = (optionCount: number, row: number): void => { + // The recommended option can start highlighted; Up clamps at the first row. + const nav = ASK_PREVIOUS_ROW.repeat(optionCount) + ASK_NEXT_ROW.repeat(row) + if (nav) { + groups.push({ raw: nav }) + } + } + + prompt.questions.forEach((q, qi) => { + const sel = selections[qi] + const other = (sel?.other ?? '').trim() + if (q.multiSelect) { + for (const i of sel?.indices ?? []) { + moveTo(q.options.length, i) + groups.push({ raw: ' ' }) + } + if (other) { + // Submitting Other advances to the next question. + moveTo(q.options.length, q.options.length) + groups.push({ raw: ASK_ENTER }, { text: other }, { raw: ASK_ENTER }) + } else { + // Right advances even when Other is highlighted. + groups.push({ raw: ASK_NEXT_TAB }) + } + } else if (other) { + moveTo(q.options.length, q.options.length) + groups.push({ raw: ASK_ENTER }, { text: answerLabels(q, sel).join(', ') }, { raw: ASK_ENTER }) + } else if ((sel?.indices.length ?? 0) > 0) { + moveTo(q.options.length, sel!.indices[0]!) + groups.push({ raw: ASK_ENTER }) + } else { + groups.push({ raw: ASK_NEXT_TAB }) + } + }) + + if (hasSubmitTab) { + groups.push({ raw: ASK_ENTER }) + } + return groups +} + +/** Build the answer keystrokes for the agent that owns this question card. */ +export function buildNativeChatAskAnswerKeys( + agent: string | null | undefined, + prompt: AskPrompt, + selections: AskAnswerSelection[] +): AskAnswerKeyGroup[] { + const transcriptAgent = resolveNativeChatTranscriptAgent(agent) + if (transcriptAgent === 'codex') { + return buildCodexAskAnswerKeys(prompt, selections) + } + if (transcriptAgent === 'omp') { + return buildOmpAskAnswerKeys(prompt, selections) + } + return buildAskAnswerKeys(prompt, selections) +} + /** Whether any question in `selections` carries an answer worth submitting. */ export function hasAskAnswer(prompt: AskPrompt, selections: AskAnswerSelection[]): boolean { return prompt.questions.some((_, i) => isAnswered(selections[i])) From 719e9732d2d9bc4127de055030aed5d21aebf91c Mon Sep 17 00:00:00 2001 From: Neil Date: Wed, 21 Oct 2026 00:45:45 -0700 Subject: [PATCH 2/7] fix(native-chat): fence OMP answer retries and stale steps --- .../use-mobile-bridge-chat-prompt-writes.ts | 3 + ...mobile-native-chat-answer-send-omp.test.ts | 85 ++++++++++++++++++- .../use-mobile-native-chat-answer-send.ts | 33 ++++++- .../use-mobile-native-chat-controller.ts | 1 + .../native-chat/native-chat-input-clear.ts | 2 + .../native-chat-interactive-prompt.test.ts | 7 ++ .../native-chat/native-chat-observed-send.ts | 5 ++ .../native-chat-runtime-send.test.ts | 16 +++- .../native-chat/native-chat-runtime-send.ts | 5 +- .../use-native-chat-interactive-send.test.tsx | 37 ++++++++ .../use-native-chat-interactive-send.ts | 41 ++++++++- src/shared/native-chat-ask.ts | 6 +- src/shared/native-chat-omp-selection.ts | 17 ++++ 13 files changed, 248 insertions(+), 10 deletions(-) create mode 100644 src/shared/native-chat-omp-selection.ts diff --git a/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts b/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts index 2dddad48e16b..23e2099d2ee9 100644 --- a/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts +++ b/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts @@ -1,4 +1,5 @@ import type { MutableRefObject } from 'react' +import type { AskPrompt } from '../../../src/shared/native-chat-ask' import type { RpcClient } from '../transport/rpc-client' import { useMobileNativeChatPermissionSend } from './mobile-native-chat-permission-send' import { useMobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' @@ -20,6 +21,7 @@ export function useMobileBridgeChatPromptWrites(args: { sessionId: string | null streamIdentity: string onSendError: (message: string) => void + currentAsk?: AskPrompt | null }): { answerAsk: MobileNativeChatAnswerSend['answerAsk'] cancelAsk: () => Promise @@ -33,6 +35,7 @@ export function useMobileBridgeChatPromptWrites(args: { handleRef, deviceTokenRef, agentRef: args.agentRef, + currentAsk: args.currentAsk, sessionId: args.sessionId, streamIdentity, onSendError diff --git a/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts b/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts index 9fa32d6ce410..46fc1614f8a6 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts @@ -48,7 +48,11 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { vi.useRealTimers() }) - async function mount(client: RpcClient, agent: AgentType): Promise { + async function mount( + client: RpcClient, + agent: AgentType, + options: { currentAsk?: AskPrompt | null; onSendError?: (message: string) => void } = {} + ): Promise<() => Promise> { function Harness(): null { answerSend = useMobileNativeChatAnswerSend({ client, @@ -58,13 +62,17 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { agentRef: { current: agent }, sessionId: 'session', streamIdentity: 'host\0worktree\0tab\0session', - onSendError: vi.fn() + onSendError: options.onSendError ?? vi.fn(), + currentAsk: options.currentAsk }) return null } await act(async () => { renderer = create(createElement(Harness)) }) + return async () => { + await act(async () => renderer?.update(createElement(Harness))) + } } it('writes OMP groups from the shared key plan, paced, never as pasted labels', async () => { @@ -106,4 +114,77 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { expect.objectContaining({ text: formatAskAnswer(prompt, selections), enter: true }) ) }) + + it.each(['accepted', 'unknown'] as const)( + 'fences a later retry after an %s group even after the chain has unwound', + async (outcome) => { + const sendRequest = vi + .fn() + .mockResolvedValue( + outcome === 'accepted' ? acceptedResponse() : { ...acceptedResponse(), result: {} } + ) + const prompt: AskPrompt = { + questions: [ + { question: 'Pick', multiSelect: true, options: [{ label: 'A' }, { label: 'B' }] } + ] + } + const onSendError = vi.fn() + const options: { currentAsk: AskPrompt | null; onSendError: typeof onSendError } = { + currentAsk: prompt, + onSendError + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the scripted sendRequest port is exercised. + const rerender = await mount({ sendRequest } as unknown as RpcClient, 'omp', options) + let first: Promise | undefined + await act(async () => { + first = answerSend?.answerAsk(prompt, [{ indices: [1] }]) + }) + act(() => answerSend?.cancelPending()) + await expect(first).resolves.toBe(false) + await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(1) + expect(onSendError).toHaveBeenLastCalledWith( + 'Answer already attempted — check terminal before retrying' + ) + options.currentAsk = null + await rerender() + options.currentAsk = prompt + await rerender() + sendRequest.mockResolvedValue(acceptedResponse()) + let next: Promise | undefined + await act(async () => { + next = answerSend?.answerAsk(prompt, [{ indices: [1] }]) + }) + await act(async () => { + await vi.runAllTimersAsync() + }) + await expect(next).resolves.toBe(true) + } + ) + + it('stops before the next group when the observed card is replaced', async () => { + const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) + const prompt: AskPrompt = { + questions: [ + { question: 'Pick', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] } + ] + } + const options = { currentAsk: prompt, onSendError: vi.fn() } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the scripted sendRequest port is exercised. + const rerender = await mount({ sendRequest } as unknown as RpcClient, 'omp', options) + let result: Promise | undefined + await act(async () => { + result = answerSend?.answerAsk(prompt, [{ indices: [1] }]) + }) + options.currentAsk = { questions: [{ ...prompt.questions[0]!, question: 'Replacement' }] } + await rerender() + await act(async () => { + await vi.runAllTimersAsync() + }) + await expect(result).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(1) + expect(options.onSendError).toHaveBeenCalledWith( + 'Answer partly sent — check chat before retrying' + ) + }) }) diff --git a/mobile/src/session/use-mobile-native-chat-answer-send.ts b/mobile/src/session/use-mobile-native-chat-answer-send.ts index 1ea3c7330503..b35a4a9ae745 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send.ts @@ -3,6 +3,7 @@ import { buildNativeChatAskAnswerKeys, formatAskAnswer, hasAskAnswer, + nativeChatAskDismissKey, type AskAnswerSelection, type AskPrompt } from '../../../src/shared/native-chat-ask' @@ -17,7 +18,10 @@ import { acquireMobileNativeChatTerminalWrite, releaseMobileNativeChatTerminalWrite } from './mobile-native-chat-terminal-write-lock' -import { shouldStepNativeChatAskAnswer } from '../../../src/shared/native-chat-agent-support' +import { + resolveNativeChatTranscriptAgent, + shouldStepNativeChatAskAnswer +} from '../../../src/shared/native-chat-agent-support' /** Sends an ask-user answer to the active chat pane. Selector agents use their * own keystrokes; other agents get pasted label text. @@ -58,6 +62,7 @@ export function useMobileNativeChatAnswerSend(args: { sessionId: string | null streamIdentity: string onSendError: (message: string) => void + currentAsk?: AskPrompt | null }): MobileNativeChatAnswerSend { const { client, @@ -69,6 +74,12 @@ export function useMobileNativeChatAnswerSend(args: { streamIdentity, onSendError } = args + const currentAskRef = useRef(args.currentAsk) + currentAskRef.current = args.currentAsk + const attemptedOmpAskRef = useRef(null) + useEffect(() => { + attemptedOmpAskRef.current = null + }, [nativeChatAskDismissKey(args.currentAsk ?? null), sessionId, streamIdentity]) const generationRef = useRef(0) const activeRouteRef = useRef({ client, enabled, sessionId, streamIdentity }) activeRouteRef.current = { client, enabled, sessionId, streamIdentity } @@ -109,6 +120,14 @@ export function useMobileNativeChatAnswerSend(args: { if (!hasAskAnswer(prompt, selections)) { return false } + const agent = agentRef.current + const omp = resolveNativeChatTranscriptAgent(agent) === 'omp' + const askKey = nativeChatAskDismissKey(prompt) + const ompAttemptKey = JSON.stringify([streamIdentity, sessionId, handle, askKey]) + if (omp && attemptedOmpAskRef.current === ompAttemptKey) { + onSendError('Answer already attempted — check terminal before retrying') + return false + } // One composed write sequence per terminal: an answer landing mid-flight // in an image paste (or vice versa) would interleave bytes into the PTY. // A superseding answer shares the cancelled chain's hold on this terminal @@ -162,7 +181,11 @@ export function useMobileNativeChatAnswerSend(args: { activeRoute.client !== client || activeRoute.sessionId !== sessionId || activeRoute.streamIdentity !== streamIdentity || - handleRef.current !== handle + handleRef.current !== handle || + agentRef.current !== agent || + (omp && + currentAskRef.current !== undefined && + nativeChatAskDismissKey(currentAskRef.current) !== askKey) ) { return false } @@ -178,9 +201,15 @@ export function useMobileNativeChatAnswerSend(args: { : {}) }) if (outcome === 'unknown') { + if (omp) { + attemptedOmpAskRef.current = ompAttemptKey + } sawUnknownOutcome = true } if (outcome === 'accepted') { + if (omp) { + attemptedOmpAskRef.current = ompAttemptKey + } sawAcceptedGroup = true } return outcome === 'accepted' diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index 7d1b238bf791..15038b5fe6eb 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -184,6 +184,7 @@ export function useMobileNativeChatController(args: { handleRef: activeHandleRef, deviceTokenRef, agentRef: activeChatAgentRef, + currentAsk: nativeChatAskPrompt, sessionId: activeChatSessionId, streamIdentity, onSendError diff --git a/src/renderer/src/components/native-chat/native-chat-input-clear.ts b/src/renderer/src/components/native-chat/native-chat-input-clear.ts index 3d8cbabe6e13..0e6a0bb5e805 100644 --- a/src/renderer/src/components/native-chat/native-chat-input-clear.ts +++ b/src/renderer/src/components/native-chat/native-chat-input-clear.ts @@ -17,6 +17,8 @@ export const NATIVE_CHAT_CLEAR_UNSUBMITTED_INPUT = '\x15' export const NATIVE_CHAT_CLEAR_CONFIRM_MS = 140 export type NativeChatSendOptions = { + /** Stop a paced selector when its observed question is no longer current. */ + beforeWrite?: () => boolean /** The host refused a write; nothing after it was sent. */ onWriteRejected?: () => void /** A write's acknowledgment was lost; it may or may not have landed. */ diff --git a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts index f827a7870cc1..82b81a8921af 100644 --- a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts @@ -403,6 +403,13 @@ describe('buildOmpAskAnswerKeys', () => { ]) }) + it.each([[3], [-1], [0.5], [0, 0]])( + 'rejects invalid OMP indices %j before clearing the terminal', + (...indices) => { + expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C'], true), [{ indices }])).toEqual([]) + } + ) + it('returns no keys when nothing is answered', () => { expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [] }])).toEqual([]) expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [])).toEqual([]) diff --git a/src/renderer/src/components/native-chat/native-chat-observed-send.ts b/src/renderer/src/components/native-chat/native-chat-observed-send.ts index 1b96acd49cec..4b5e81e4ee45 100644 --- a/src/renderer/src/components/native-chat/native-chat-observed-send.ts +++ b/src/renderer/src/components/native-chat/native-chat-observed-send.ts @@ -46,6 +46,11 @@ export function sendNativeChatObservedWrites( if (isCancelled()) { return } + if (options.beforeWrite && !options.beforeWrite()) { + options.onDeliverySettled?.(false) + markSubmitted() + return + } void sendRuntimePtyInputVerified(ptyId, write.data, 'driving', writeOptions) .then((accepted) => { if (isCancelled()) { diff --git a/src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts b/src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts index 6bddf8b4e888..7b766cd48c00 100644 --- a/src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts @@ -463,7 +463,9 @@ describe('sendNativeChatAskAnswer', () => { }) it('returns a no-op handle for an empty key group list', () => { - const handle = sendNativeChatAskAnswer(PTY, []) + const settled = vi.fn() + const handle = sendNativeChatAskAnswer(PTY, [], settled) + expect(settled).toHaveBeenCalledExactlyOnceWith(false) expect(handle.settleAfterMs).toBe(0) handle.cancel() expect(sendRuntimePtyInput).not.toHaveBeenCalled() @@ -494,6 +496,18 @@ describe('sendNativeChatAskAnswer', () => { ) }) + it('stops a paced selector before writing when its question guard changes', async () => { + let current = true + const settled = vi.fn() + sendNativeChatAskAnswer(PTY, [{ raw: ' ' }, { raw: '\r' }], settled, () => current) + await vi.advanceTimersByTimeAsync(0) + expect(sendRuntimePtyInputVerified).toHaveBeenCalledTimes(1) + current = false + await vi.runAllTimersAsync() + expect(sendRuntimePtyInputVerified).toHaveBeenCalledTimes(1) + expect(settled).toHaveBeenCalledExactlyOnceWith(false) + }) + it('cancels remaining key group timers', async () => { const handle = sendNativeChatAskAnswer(PTY, [{ raw: '1' }, { raw: '2' }]) await vi.advanceTimersByTimeAsync(0) diff --git a/src/renderer/src/components/native-chat/native-chat-runtime-send.ts b/src/renderer/src/components/native-chat/native-chat-runtime-send.ts index 2e4696cf2e95..26c216bbfcf8 100644 --- a/src/renderer/src/components/native-chat/native-chat-runtime-send.ts +++ b/src/renderer/src/components/native-chat/native-chat-runtime-send.ts @@ -212,9 +212,11 @@ export function submitNativeChatPrompt(ptyId: string): void { export function sendNativeChatAskAnswer( ptyId: string, groups: AskAnswerKeyGroup[], - onSettled?: (delivered: boolean) => void + onSettled?: (delivered: boolean) => void, + beforeWrite?: () => boolean ): NativeChatSendHandle { if (groups.length === 0) { + onSettled?.(false) return { cancel: () => {}, settleAfterMs: 0 } } return sendNativeChatObservedWrites( @@ -225,6 +227,7 @@ export function sendNativeChatAskAnswer( })), { clearInput: '', + beforeWrite, stopOnUnconfirmed: !!onSettled, settleDelayMs: NATIVE_CHAT_SUBMIT_DELAY_MS, onDeliverySettled: onSettled diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx index 6266eeea5002..4117875666a1 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx @@ -118,6 +118,43 @@ describe('useNativeChatInteractiveSend', () => { expect(mocks.inferQuestionAnswered).toHaveBeenCalledOnce() }) + it('guards OMP groups against a changed question and fences blind retries', () => { + const original = { + ...waitingQuestion, + agentType: 'omp', + interactivePrompt: JSON.stringify(PROMPT) + } + mocks.storeState.agentStatusByPaneKey[PANE_KEY] = original + const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'omp')) + const settled = vi.fn() + act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }], settled)) + const canWrite = mocks.sendNativeChatAskAnswer.mock.calls[0]?.[3] + expect(canWrite()).toBe(true) + mocks.storeState.agentStatusByPaneKey[PANE_KEY] = { ...original, state: 'working' } + expect(canWrite()).toBe(false) + act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }], settled)) + expect(mocks.sendNativeChatAskAnswer).toHaveBeenCalledTimes(1) + expect(settled).toHaveBeenCalledWith(false) + mocks.storeState.agentStatusByPaneKey[PANE_KEY] = { + ...original, + stateStartedAt: original.stateStartedAt + 1 + } + act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }], settled)) + expect(mocks.sendNativeChatAskAnswer).toHaveBeenCalledTimes(2) + }) + + it('refuses an OMP status prompt that is already working before delivery starts', () => { + mocks.storeState.agentStatusByPaneKey[PANE_KEY] = { + ...waitingQuestion, + agentType: 'omp', + state: 'working', + interactivePrompt: JSON.stringify(PROMPT) + } + const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'omp')) + act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }])) + expect(mocks.sendNativeChatAskAnswer.mock.calls[0]?.[3]()).toBe(false) + }) + it('does nothing when no option is answered', () => { const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'claude')) diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts index 9fcedbe75e47..4b69efada5d1 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts @@ -19,6 +19,7 @@ import { sendNativeChatMessage, type NativeChatSendHandle } from './native-chat-runtime-send' +import { nativeChatAskDismissKey, parseAskFromStatus } from '../../../../shared/native-chat-ask' import { inferQuestionAnsweredFromCurrentStatus } from '../terminal-pane/agent-question-answered-inference' // ESC is the agent-TUI interrupt/cancel key over the PTY (matches how the @@ -63,6 +64,7 @@ export function useNativeChatInteractiveSend( // unmount so a detached setTimeout chain can't keep writing PTY bytes after // the view is gone / the user switched away. const inFlightRef = useRef(null) + const attemptedOmpAskRef = useRef(null) const cancelInFlight = useCallback(() => { inFlightRef.current?.cancel() inFlightRef.current = null @@ -113,6 +115,42 @@ export function useNativeChatInteractiveSend( const questionStatusBaseline = stepsAnswer ? useAppStore.getState().agentStatusByPaneKey[paneKey] : undefined + const omp = resolveNativeChatTranscriptAgent(agent) === 'omp' + const askKey = nativeChatAskDismissKey(prompt) + const baselineKey = JSON.stringify([ + targetPtyId, + askKey, + questionStatusBaseline?.stateStartedAt, + questionStatusBaseline?.turnStartedAt + ]) + if (omp && attemptedOmpAskRef.current === baselineKey) { + onDeliverySettled?.(false) + return { settleAfterMs: 0 } + } + const baselineAskKey = nativeChatAskDismissKey( + parseAskFromStatus( + questionStatusBaseline?.interactivePrompt, + questionStatusBaseline?.toolName + ) + ) + const beforeWrite = (): boolean => { + const current = useAppStore.getState().agentStatusByPaneKey[paneKey] + if ( + (baselineAskKey !== null && + (baselineAskKey !== askKey || + (current?.state !== 'waiting' && current?.state !== 'blocked'))) || + current?.state !== questionStatusBaseline?.state || + current?.stateStartedAt !== questionStatusBaseline?.stateStartedAt || + current?.turnStartedAt !== questionStatusBaseline?.turnStartedAt || + nativeChatAskDismissKey( + parseAskFromStatus(current?.interactivePrompt, current?.toolName) + ) !== baselineAskKey + ) { + return false + } + attemptedOmpAskRef.current = baselineKey + return true + } let settledHandle: NativeChatSendHandle | null = null const onSettled = (delivered: boolean): void => { if (settledHandle && inFlightRef.current === settledHandle) { @@ -137,7 +175,8 @@ export function useNativeChatInteractiveSend( ? sendNativeChatAskAnswer( targetPtyId, buildNativeChatAskAnswerKeys(agent, prompt, selections), - onSettled + onSettled, + ...(omp ? [beforeWrite] : []) ) : sendNativeChatMessage(targetPtyId, formatAskAnswer(prompt, selections), { onDeliverySettled: onSettled diff --git a/src/shared/native-chat-ask.ts b/src/shared/native-chat-ask.ts index e538a9295b5c..24142089d43f 100644 --- a/src/shared/native-chat-ask.ts +++ b/src/shared/native-chat-ask.ts @@ -7,6 +7,7 @@ import type { import { isInterruptedStatusMessage, type NativeChatMessage } from './native-chat-types' import { resolveNativeChatTranscriptAgent } from './native-chat-agent-support' import { AGENT_TUI_CLEAR_INPUT_MAX } from './agent-tui-input-clear' +import { isOmpAskSelectionValid } from './native-chat-omp-selection' export type { AskOption, AskPrompt, AskQuestion, InteractiveQuestionParser } @@ -337,10 +338,9 @@ export function buildOmpAskAnswerKeys( prompt: AskPrompt, selections: AskAnswerSelection[] ): AskAnswerKeyGroup[] { - if (!hasAskAnswer(prompt, selections)) { + if (!hasAskAnswer(prompt, selections) || !isOmpAskSelectionValid(prompt, selections)) { return [] } - const hasSubmitTab = prompt.questions.length > 1 || prompt.questions.some((q) => q.multiSelect) // Clear any draft that would otherwise consume the dialog keys. const groups: AskAnswerKeyGroup[] = [{ raw: AGENT_TUI_CLEAR_INPUT_MAX }] const moveTo = (optionCount: number, row: number): void => { @@ -378,7 +378,7 @@ export function buildOmpAskAnswerKeys( } }) - if (hasSubmitTab) { + if (prompt.questions.length > 1 || prompt.questions.some((q) => q.multiSelect)) { groups.push({ raw: ASK_ENTER }) } return groups diff --git a/src/shared/native-chat-omp-selection.ts b/src/shared/native-chat-omp-selection.ts new file mode 100644 index 000000000000..b4ae7ab7bb37 --- /dev/null +++ b/src/shared/native-chat-omp-selection.ts @@ -0,0 +1,17 @@ +import type { AskAnswerSelection, AskPrompt } from './native-chat-ask' + +export function isOmpAskSelectionValid( + prompt: AskPrompt, + selections: AskAnswerSelection[] +): boolean { + return prompt.questions.every((question, i) => { + const indices = selections[i]?.indices ?? [] + return ( + indices.every( + (index) => Number.isInteger(index) && index >= 0 && index < question.options.length + ) && + new Set(indices).size === indices.length && + (question.multiSelect || indices.length <= 1) + ) + }) +} From 54e88a8b4305f4aa86367b2de1eeffa3d1c5f1de Mon Sep 17 00:00:00 2001 From: Neil Date: Wed, 21 Oct 2026 00:50:07 -0700 Subject: [PATCH 3/7] fix(mobile): commit OMP question guard refs after render --- .../session/use-mobile-native-chat-answer-send.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/mobile/src/session/use-mobile-native-chat-answer-send.ts b/mobile/src/session/use-mobile-native-chat-answer-send.ts index b35a4a9ae745..e68679fb98f9 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send.ts @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, type MutableRefObject } from 'react' +import { useCallback, useEffect, useLayoutEffect, useRef, type MutableRefObject } from 'react' import { buildNativeChatAskAnswerKeys, formatAskAnswer, @@ -72,14 +72,18 @@ export function useMobileNativeChatAnswerSend(args: { agentRef, sessionId, streamIdentity, - onSendError + onSendError, + currentAsk } = args - const currentAskRef = useRef(args.currentAsk) - currentAskRef.current = args.currentAsk + const currentAskRef = useRef(currentAsk) + useLayoutEffect(() => { + currentAskRef.current = currentAsk + }, [currentAsk]) + const currentAskKey = nativeChatAskDismissKey(currentAsk ?? null) const attemptedOmpAskRef = useRef(null) useEffect(() => { attemptedOmpAskRef.current = null - }, [nativeChatAskDismissKey(args.currentAsk ?? null), sessionId, streamIdentity]) + }, [currentAskKey, sessionId, streamIdentity]) const generationRef = useRef(0) const activeRouteRef = useRef({ client, enabled, sessionId, streamIdentity }) activeRouteRef.current = { client, enabled, sessionId, streamIdentity } From 58794aca7f811d2773b178812a9c8c2ed17edb9f Mon Sep 17 00:00:00 2001 From: Neil Date: Wed, 21 Oct 2026 01:40:26 -0700 Subject: [PATCH 4/7] fix(native-chat): require live OMP prompt identity before answers --- .../use-mobile-bridge-chat-prompt-writes.ts | 3 + ...mobile-native-chat-answer-send-omp.test.ts | 98 +++++++++++++++++-- .../use-mobile-native-chat-answer-send.ts | 52 ++++++---- .../use-mobile-native-chat-controller.ts | 1 + .../use-native-chat-interactive-send.test.tsx | 14 +++ .../use-native-chat-interactive-send.ts | 35 +++---- ...native-chat-omp-answer-retry-fence.test.ts | 17 ++++ .../native-chat-omp-answer-retry-fence.ts | 17 ++++ src/shared/native-chat-omp-prompt-identity.ts | 19 ++++ 9 files changed, 210 insertions(+), 46 deletions(-) create mode 100644 src/shared/native-chat-omp-answer-retry-fence.test.ts create mode 100644 src/shared/native-chat-omp-answer-retry-fence.ts create mode 100644 src/shared/native-chat-omp-prompt-identity.ts diff --git a/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts b/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts index 23e2099d2ee9..8664eb42f5c4 100644 --- a/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts +++ b/mobile/src/session/use-mobile-bridge-chat-prompt-writes.ts @@ -1,4 +1,5 @@ import type { MutableRefObject } from 'react' +import type { AgentStatusEntry } from '../../../src/shared/agent-status-types' import type { AskPrompt } from '../../../src/shared/native-chat-ask' import type { RpcClient } from '../transport/rpc-client' import { useMobileNativeChatPermissionSend } from './mobile-native-chat-permission-send' @@ -22,6 +23,7 @@ export function useMobileBridgeChatPromptWrites(args: { streamIdentity: string onSendError: (message: string) => void currentAsk?: AskPrompt | null + currentAskStatus?: AgentStatusEntry | null }): { answerAsk: MobileNativeChatAnswerSend['answerAsk'] cancelAsk: () => Promise @@ -36,6 +38,7 @@ export function useMobileBridgeChatPromptWrites(args: { deviceTokenRef, agentRef: args.agentRef, currentAsk: args.currentAsk, + currentAskStatus: args.currentAskStatus, sessionId: args.sessionId, streamIdentity, onSendError diff --git a/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts b/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts index 46fc1614f8a6..d60e53eb4393 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts @@ -12,6 +12,7 @@ import { type AskPrompt } from '../../../src/shared/native-chat-ask' import { AGENT_TUI_CLEAR_INPUT_MAX } from '../../../src/shared/agent-tui-input-clear' +import type { AgentStatusEntry } from '../../../src/shared/agent-status-types' import type { AgentType } from '../../../src/shared/native-chat-types' import type { RpcClient } from '../transport/rpc-client' import { MOBILE_NATIVE_CHAT_QUESTION_STEP_MS } from './mobile-native-chat-answer-stepping' @@ -31,6 +32,21 @@ function acceptedResponse() { } } +function waitingStatus(prompt: AskPrompt): AgentStatusEntry { + return { + agentType: 'omp', + state: 'waiting', + stateStartedAt: 10, + turnStartedAt: 5, + updatedAt: 10, + prompt: '', + paneKey: 'pane', + stateHistory: [], + toolName: 'ask', + interactivePrompt: JSON.stringify(prompt) + } +} + describe('useMobileNativeChatAnswerSend for OMP asks', () => { let renderer: ReactTestRenderer | null = null let answerSend: MobileNativeChatAnswerSend | null = null @@ -51,7 +67,11 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { async function mount( client: RpcClient, agent: AgentType, - options: { currentAsk?: AskPrompt | null; onSendError?: (message: string) => void } = {} + options: { + currentAsk?: AskPrompt | null + currentAskStatus?: AgentStatusEntry | null + onSendError?: (message: string) => void + } = {} ): Promise<() => Promise> { function Harness(): null { answerSend = useMobileNativeChatAnswerSend({ @@ -63,7 +83,11 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { sessionId: 'session', streamIdentity: 'host\0worktree\0tab\0session', onSendError: options.onSendError ?? vi.fn(), - currentAsk: options.currentAsk + currentAsk: options.currentAsk, + currentAskStatus: + options.currentAskStatus === undefined && options.currentAsk + ? waitingStatus(options.currentAsk) + : options.currentAskStatus }) return null } @@ -77,14 +101,14 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { it('writes OMP groups from the shared key plan, paced, never as pasted labels', async () => { const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture exercises only the scripted sendRequest port. - await mount({ sendRequest } as unknown as RpcClient, 'omp') const prompt: AskPrompt = { questions: [ { question: 'q1', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] }, { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } ] } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture exercises only the scripted sendRequest port. + await mount({ sendRequest } as unknown as RpcClient, 'omp', { currentAsk: prompt }) const selections: AskAnswerSelection[] = [{ indices: [1] }, { indices: [0] }] const expected = [ AGENT_TUI_CLEAR_INPUT_MAX, @@ -129,7 +153,11 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { ] } const onSendError = vi.fn() - const options: { currentAsk: AskPrompt | null; onSendError: typeof onSendError } = { + const options: { + currentAsk: AskPrompt | null + currentAskStatus?: AgentStatusEntry + onSendError: typeof onSendError + } = { currentAsk: prompt, onSendError } @@ -144,12 +172,20 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) expect(sendRequest).toHaveBeenCalledTimes(1) expect(onSendError).toHaveBeenLastCalledWith( - 'Answer already attempted — check terminal before retrying' + 'Answer not sent — check terminal before retrying' ) options.currentAsk = null await rerender() options.currentAsk = prompt await rerender() + await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(1) + options.currentAskStatus = { ...waitingStatus(prompt), stateStartedAt: 15, state: 'blocked' } + await rerender() + await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(1) + options.currentAskStatus = { ...waitingStatus(prompt), turnStartedAt: 20, stateStartedAt: 25 } + await rerender() sendRequest.mockResolvedValue(acceptedResponse()) let next: Promise | undefined await act(async () => { @@ -187,4 +223,54 @@ describe('useMobileNativeChatAnswerSend for OMP asks', () => { 'Answer partly sent — check chat before retrying' ) }) + it.each(['missing status', 'working', 'different turn'] as const)( + 'stops writes when the prompt has %s', + async (change) => { + const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) + const prompt: AskPrompt = { + questions: [ + { question: 'Pick', multiSelect: true, options: [{ label: 'A' }, { label: 'B' }] } + ] + } + const options: { currentAsk: AskPrompt; currentAskStatus: AgentStatusEntry | null } = { + currentAsk: prompt, + currentAskStatus: waitingStatus(prompt) + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the scripted sendRequest port is exercised. + const rerender = await mount({ sendRequest } as unknown as RpcClient, 'omp', options) + let result: Promise | undefined + await act(async () => { + result = answerSend?.answerAsk(prompt, [{ indices: [1] }]) + }) + options.currentAskStatus = + change === 'missing status' + ? null + : { + ...waitingStatus(prompt), + ...(change === 'working' ? { state: 'working' } : { turnStartedAt: 20 }) + } + await rerender() + await act(async () => { + await vi.runAllTimersAsync() + }) + await expect(result).resolves.toBe(false) + expect(sendRequest).toHaveBeenCalledTimes(1) + } + ) + + it('refuses a transcript-only OMP question before any terminal write', async () => { + const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) + const prompt: AskPrompt = { + questions: [ + { question: 'Pick', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] } + ] + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the scripted sendRequest port is exercised. + await mount({ sendRequest } as unknown as RpcClient, 'omp', { + currentAsk: prompt, + currentAskStatus: null + }) + await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) + expect(sendRequest).not.toHaveBeenCalled() + }) }) diff --git a/mobile/src/session/use-mobile-native-chat-answer-send.ts b/mobile/src/session/use-mobile-native-chat-answer-send.ts index e68679fb98f9..47b6ea332298 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send.ts @@ -1,4 +1,11 @@ -import { useCallback, useEffect, useLayoutEffect, useRef, type MutableRefObject } from 'react' +import { + useCallback, + useEffect, + useLayoutEffect, + useRef, + useState, + type MutableRefObject +} from 'react' import { buildNativeChatAskAnswerKeys, formatAskAnswer, @@ -7,6 +14,9 @@ import { type AskAnswerSelection, type AskPrompt } from '../../../src/shared/native-chat-ask' +import type { AgentStatusEntry } from '../../../src/shared/agent-status-types' +import { nativeChatOmpPromptIdentity } from '../../../src/shared/native-chat-omp-prompt-identity' +import { createOmpAnswerRetryFence } from '../../../src/shared/native-chat-omp-answer-retry-fence' import type { RpcClient } from '../transport/rpc-client' import { MOBILE_NATIVE_CHAT_QUESTION_STEP_MS } from './mobile-native-chat-answer-stepping' import { @@ -63,6 +73,7 @@ export function useMobileNativeChatAnswerSend(args: { streamIdentity: string onSendError: (message: string) => void currentAsk?: AskPrompt | null + currentAskStatus?: AgentStatusEntry | null }): MobileNativeChatAnswerSend { const { client, @@ -73,17 +84,14 @@ export function useMobileNativeChatAnswerSend(args: { sessionId, streamIdentity, onSendError, - currentAsk + currentAsk, + currentAskStatus } = args - const currentAskRef = useRef(currentAsk) + const currentAskRef = useRef({ prompt: currentAsk, status: currentAskStatus }) useLayoutEffect(() => { - currentAskRef.current = currentAsk - }, [currentAsk]) - const currentAskKey = nativeChatAskDismissKey(currentAsk ?? null) - const attemptedOmpAskRef = useRef(null) - useEffect(() => { - attemptedOmpAskRef.current = null - }, [currentAskKey, sessionId, streamIdentity]) + currentAskRef.current = { prompt: currentAsk, status: currentAskStatus } + }, [currentAsk, currentAskStatus]) + const [attemptedOmpAsks] = useState(createOmpAnswerRetryFence) const generationRef = useRef(0) const activeRouteRef = useRef({ client, enabled, sessionId, streamIdentity }) activeRouteRef.current = { client, enabled, sessionId, streamIdentity } @@ -127,9 +135,16 @@ export function useMobileNativeChatAnswerSend(args: { const agent = agentRef.current const omp = resolveNativeChatTranscriptAgent(agent) === 'omp' const askKey = nativeChatAskDismissKey(prompt) - const ompAttemptKey = JSON.stringify([streamIdentity, sessionId, handle, askKey]) - if (omp && attemptedOmpAskRef.current === ompAttemptKey) { - onSendError('Answer already attempted — check terminal before retrying') + const ompPromptIdentity = nativeChatOmpPromptIdentity(currentAskRef.current.status, prompt) + const ompAttemptKey = JSON.stringify([ + streamIdentity, + sessionId, + handle, + askKey, + currentAskRef.current.status?.turnStartedAt ?? currentAskRef.current.status?.stateStartedAt + ]) + if (omp && attemptedOmpAsks.blocks(ompAttemptKey)) { + onSendError('Answer not sent — check terminal before retrying') return false } // One composed write sequence per terminal: an answer landing mid-flight @@ -188,8 +203,10 @@ export function useMobileNativeChatAnswerSend(args: { handleRef.current !== handle || agentRef.current !== agent || (omp && - currentAskRef.current !== undefined && - nativeChatAskDismissKey(currentAskRef.current) !== askKey) + (ompPromptIdentity === null || + nativeChatOmpPromptIdentity(currentAskRef.current.status, prompt) !== + ompPromptIdentity || + nativeChatAskDismissKey(currentAskRef.current.prompt ?? null) !== askKey)) ) { return false } @@ -206,13 +223,13 @@ export function useMobileNativeChatAnswerSend(args: { }) if (outcome === 'unknown') { if (omp) { - attemptedOmpAskRef.current = ompAttemptKey + attemptedOmpAsks.record(ompAttemptKey) } sawUnknownOutcome = true } if (outcome === 'accepted') { if (omp) { - attemptedOmpAskRef.current = ompAttemptKey + attemptedOmpAsks.record(ompAttemptKey) } sawAcceptedGroup = true } @@ -327,6 +344,7 @@ export function useMobileNativeChatAnswerSend(args: { }, [ agentRef, + attemptedOmpAsks, enabled, cancelPending, client, diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index 15038b5fe6eb..c87ad7e44696 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -185,6 +185,7 @@ export function useMobileNativeChatController(args: { deviceTokenRef, agentRef: activeChatAgentRef, currentAsk: nativeChatAskPrompt, + currentAskStatus: nativeChatStatus, sessionId: activeChatSessionId, streamIdentity, onSendError diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx index 4117875666a1..cd0764ef2bef 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx @@ -155,6 +155,20 @@ describe('useNativeChatInteractiveSend', () => { expect(mocks.sendNativeChatAskAnswer.mock.calls[0]?.[3]()).toBe(false) }) + it.each([undefined, 'not json', JSON.stringify({ questions: [] })])( + 'refuses OMP writes without canonical live prompt: %s', + (interactivePrompt) => { + mocks.storeState.agentStatusByPaneKey[PANE_KEY] = { + ...waitingQuestion, + agentType: 'omp', + interactivePrompt + } + const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'omp')) + act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }])) + expect(mocks.sendNativeChatAskAnswer.mock.calls[0]?.[3]()).toBe(false) + } + ) + it('does nothing when no option is answered', () => { const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'claude')) diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts index 4b69efada5d1..226c4e78e0a4 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts @@ -1,4 +1,4 @@ -import { useCallback, useLayoutEffect, useRef } from 'react' +import { useCallback, useLayoutEffect, useRef, useState } from 'react' import { useAppStore } from '../../store' import { sendRuntimePtyInput } from '@/runtime/runtime-terminal-inspection' import { sendRuntimePtyInputVerified } from '@/runtime/runtime-terminal-verified-input' @@ -19,7 +19,9 @@ import { sendNativeChatMessage, type NativeChatSendHandle } from './native-chat-runtime-send' -import { nativeChatAskDismissKey, parseAskFromStatus } from '../../../../shared/native-chat-ask' +import { nativeChatAskDismissKey } from '../../../../shared/native-chat-ask' +import { nativeChatOmpPromptIdentity } from '../../../../shared/native-chat-omp-prompt-identity' +import { createOmpAnswerRetryFence } from '../../../../shared/native-chat-omp-answer-retry-fence' import { inferQuestionAnsweredFromCurrentStatus } from '../terminal-pane/agent-question-answered-inference' // ESC is the agent-TUI interrupt/cancel key over the PTY (matches how the @@ -64,7 +66,7 @@ export function useNativeChatInteractiveSend( // unmount so a detached setTimeout chain can't keep writing PTY bytes after // the view is gone / the user switched away. const inFlightRef = useRef(null) - const attemptedOmpAskRef = useRef(null) + const [attemptedOmpAsks] = useState(createOmpAnswerRetryFence) const cancelInFlight = useCallback(() => { inFlightRef.current?.cancel() inFlightRef.current = null @@ -120,35 +122,22 @@ export function useNativeChatInteractiveSend( const baselineKey = JSON.stringify([ targetPtyId, askKey, - questionStatusBaseline?.stateStartedAt, - questionStatusBaseline?.turnStartedAt + questionStatusBaseline?.turnStartedAt ?? questionStatusBaseline?.stateStartedAt ]) - if (omp && attemptedOmpAskRef.current === baselineKey) { + if (omp && attemptedOmpAsks.blocks(baselineKey)) { onDeliverySettled?.(false) return { settleAfterMs: 0 } } - const baselineAskKey = nativeChatAskDismissKey( - parseAskFromStatus( - questionStatusBaseline?.interactivePrompt, - questionStatusBaseline?.toolName - ) - ) + const baselineIdentity = nativeChatOmpPromptIdentity(questionStatusBaseline, prompt) const beforeWrite = (): boolean => { const current = useAppStore.getState().agentStatusByPaneKey[paneKey] if ( - (baselineAskKey !== null && - (baselineAskKey !== askKey || - (current?.state !== 'waiting' && current?.state !== 'blocked'))) || - current?.state !== questionStatusBaseline?.state || - current?.stateStartedAt !== questionStatusBaseline?.stateStartedAt || - current?.turnStartedAt !== questionStatusBaseline?.turnStartedAt || - nativeChatAskDismissKey( - parseAskFromStatus(current?.interactivePrompt, current?.toolName) - ) !== baselineAskKey + baselineIdentity === null || + nativeChatOmpPromptIdentity(current, prompt) !== baselineIdentity ) { return false } - attemptedOmpAskRef.current = baselineKey + attemptedOmpAsks.record(baselineKey) return true } let settledHandle: NativeChatSendHandle | null = null @@ -190,7 +179,7 @@ export function useNativeChatInteractiveSend( settleAfterMs: handle.settleAfterMs } }, - [paneKey, targetPtyId, agent, cancelInFlight] + [paneKey, targetPtyId, agent, attemptedOmpAsks, cancelInFlight] ) const cancelAsk = useCallback(() => { diff --git a/src/shared/native-chat-omp-answer-retry-fence.test.ts b/src/shared/native-chat-omp-answer-retry-fence.test.ts new file mode 100644 index 000000000000..7d513d8bd80a --- /dev/null +++ b/src/shared/native-chat-omp-answer-retry-fence.test.ts @@ -0,0 +1,17 @@ +import { describe, expect, it } from 'vitest' +import { createOmpAnswerRetryFence } from './native-chat-omp-answer-retry-fence' + +describe('OMP answer retry fence', () => { + it('retains attempted keys and fails closed when capacity is exhausted', () => { + const fence = createOmpAnswerRetryFence() + expect(fence.blocks('first')).toBe(false) + fence.record('first') + expect(fence.blocks('first')).toBe(true) + expect(fence.blocks('next')).toBe(false) + for (let i = 0; i < 200; i += 1) { + fence.record(`attempt-${i}`) + } + expect(fence.blocks('first')).toBe(true) + expect(fence.blocks('unseen')).toBe(true) + }) +}) diff --git a/src/shared/native-chat-omp-answer-retry-fence.ts b/src/shared/native-chat-omp-answer-retry-fence.ts new file mode 100644 index 000000000000..8168417f8869 --- /dev/null +++ b/src/shared/native-chat-omp-answer-retry-fence.ts @@ -0,0 +1,17 @@ +const OMP_ANSWER_RETRY_FENCE_CAPACITY = 128 + +export function createOmpAnswerRetryFence(): { + blocks: (key: string) => boolean + record: (key: string) => void +} { + const attempts = new Set() + return { + blocks: (key) => attempts.has(key) || attempts.size >= OMP_ANSWER_RETRY_FENCE_CAPACITY, + record: (key) => { + // Retain earlier attempts; reaching capacity must never reopen stale retries. + if (attempts.size < OMP_ANSWER_RETRY_FENCE_CAPACITY) { + attempts.add(key) + } + } + } +} diff --git a/src/shared/native-chat-omp-prompt-identity.ts b/src/shared/native-chat-omp-prompt-identity.ts new file mode 100644 index 000000000000..26c28a51320d --- /dev/null +++ b/src/shared/native-chat-omp-prompt-identity.ts @@ -0,0 +1,19 @@ +import type { AgentStatusEntry } from './agent-status-types' +import { resolveNativeChatTranscriptAgent } from './native-chat-agent-support' +import { nativeChatAskDismissKey, parseAskFromStatus, type AskPrompt } from './native-chat-ask' + +export function nativeChatOmpPromptIdentity( + status: AgentStatusEntry | null | undefined, + prompt: AskPrompt +): string | null { + if ( + !status || + resolveNativeChatTranscriptAgent(status.agentType) !== 'omp' || + (status.state !== 'waiting' && status.state !== 'blocked') || + nativeChatAskDismissKey(parseAskFromStatus(status.interactivePrompt, status.toolName)) !== + nativeChatAskDismissKey(prompt) + ) { + return null + } + return JSON.stringify([status.state, status.stateStartedAt, status.turnStartedAt]) +} From e5e6c1f17d0e568aa815fd6130375b4fcdbb58f9 Mon Sep 17 00:00:00 2001 From: Neil Date: Wed, 21 Oct 2026 01:46:06 -0700 Subject: [PATCH 5/7] refactor(mobile): keep native chat controller within line limit --- mobile/src/session/use-mobile-native-chat-controller.ts | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index c87ad7e44696..187b433eacf0 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -219,7 +219,7 @@ export function useMobileNativeChatController(args: { onSendError }) - const structuredNativeChatSend = useMobileStructuredNativeChatSendBridge({ + const structuredSend = useMobileStructuredNativeChatSendBridge({ agent: activeChatResolution?.agent, sendStructured: structuredNativeChat.sendWithOutcome, captureSendOrigin, @@ -328,11 +328,9 @@ export function useMobileNativeChatController(args: { nativeChatQueued: structuredNativeChat.queued, nativeChatBackgroundTasks: activeChatStructured ? structuredNativeChat.backgroundTasks : null, ...nativeChatFiles, - handleNativeChatSend: activeChatStructured - ? structuredNativeChatSend.send - : handleNativeChatSend, + handleNativeChatSend: activeChatStructured ? structuredSend.send : handleNativeChatSend, handleNativeChatSendWithOutcome: activeChatStructured - ? structuredNativeChatSend.sendWithOutcome + ? structuredSend.sendWithOutcome : handleNativeChatSendWithOutcome, readSeededLaunchDraft, nativeChatSessionOptions, From d922b3f3240c330b4e9ddfe1f588b51379dd688f Mon Sep 17 00:00:00 2001 From: Neil Date: Wed, 21 Oct 2026 12:37:48 -0700 Subject: [PATCH 6/7] fix(chat): route OMP questions to terminal safely Use a visible terminal action for OMP ask dialogs and refuse automated card answer/cancel writes. Preserve structured-session responses and OMP multi-select parsing. Co-authored-by: jairuspace Co-authored-by: Daniel Lopez --- .../session/MobileNativeChatOverlay.test.ts | 40 +- .../src/session/MobileNativeChatOverlay.tsx | 11 + .../MobileNativeChatPromptCard.test.tsx | 36 ++ .../session/MobileNativeChatPromptCard.tsx | 121 ++++-- ...NativeChatView.prompt-presentation.test.ts | 19 + mobile/src/session/MobileNativeChatView.tsx | 6 + .../session/MobileSessionActiveContent.tsx | 1 + .../use-mobile-bridge-chat-prompt-writes.ts | 7 +- ...mobile-native-chat-answer-send-omp.test.ts | 347 +++++------------- .../use-mobile-native-chat-answer-send.ts | 74 +--- .../use-mobile-native-chat-cancel-ask.test.ts | 12 +- .../use-mobile-native-chat-cancel-ask.ts | 11 +- .../use-mobile-native-chat-controller.ts | 10 +- .../NativeChatInteractiveCard.test.tsx | 36 ++ .../native-chat/NativeChatInteractiveCard.tsx | 30 ++ ...iveChatResolvedView.reveal-latest.test.tsx | 51 ++- .../native-chat/NativeChatResolvedView.tsx | 15 +- .../native-chat/native-chat-input-clear.ts | 2 - .../native-chat-interactive-prompt.test.ts | 129 ------- .../native-chat-interactive-prompt.ts | 4 - .../native-chat/native-chat-observed-send.ts | 5 - .../native-chat-runtime-send.test.ts | 16 +- .../native-chat/native-chat-runtime-send.ts | 5 +- .../use-native-chat-interactive-send.test.tsx | 68 +--- .../use-native-chat-interactive-send.ts | 55 +-- src/renderer/src/i18n/locales/en.json | 4 +- src/shared/native-chat-agent-support.test.ts | 4 +- src/shared/native-chat-agent-support.ts | 10 +- src/shared/native-chat-ask.test.ts | 26 +- src/shared/native-chat-ask.ts | 71 ---- ...native-chat-omp-answer-retry-fence.test.ts | 17 - .../native-chat-omp-answer-retry-fence.ts | 17 - src/shared/native-chat-omp-prompt-identity.ts | 19 - src/shared/native-chat-omp-selection.ts | 17 - 34 files changed, 514 insertions(+), 782 deletions(-) delete mode 100644 src/shared/native-chat-omp-answer-retry-fence.test.ts delete mode 100644 src/shared/native-chat-omp-answer-retry-fence.ts delete mode 100644 src/shared/native-chat-omp-prompt-identity.ts delete mode 100644 src/shared/native-chat-omp-selection.ts diff --git a/mobile/src/session/MobileNativeChatOverlay.test.ts b/mobile/src/session/MobileNativeChatOverlay.test.ts index 2ec406f59909..990e39d606b8 100644 --- a/mobile/src/session/MobileNativeChatOverlay.test.ts +++ b/mobile/src/session/MobileNativeChatOverlay.test.ts @@ -36,6 +36,10 @@ type Tick = { /** The host says a person's Stop is ending the turn. */ stopping?: boolean acceptsImages?: boolean + agent?: string + structured?: boolean + activeTabId?: string | null + setTabView?: (tabId: string, view: 'terminal') => void } function overlayElement(tick: Tick): ReturnType { @@ -43,7 +47,9 @@ function overlayElement(tick: Tick): ReturnType { const controller = { showNativeChat: tick.show ?? true, nativeChatSession: { messages: tick.messages ?? [], status: 'ready' }, - nativeChatAgent: 'claude', + nativeChatAgent: tick.agent ?? 'claude', + nativeChatStructured: tick.structured ?? false, + setTabView: tick.setTabView ?? vi.fn(), nativeChatAcceptsImages: tick.acceptsImages ?? true, nativeChatAgentWorking: tick.streamLive ?? false, nativeChatTurnIndicator: { @@ -70,6 +76,7 @@ function overlayElement(tick: Tick): ReturnType { } as unknown as MobileNativeChatController return createElement(MobileNativeChatOverlay, { controller, + activeSessionTabId: tick.activeTabId, images: {} as never, onMicPress: vi.fn(), micActive: false, @@ -238,6 +245,37 @@ describe('MobileNativeChatOverlay attach button', () => { renderer = null }) + it('opens the exact active terminal tab for an OMP bridge question', async () => { + const setTabView = vi.fn() + await act(async () => { + renderer = create(overlayElement({ agent: 'omp', activeTabId: 'tab-omp', setTabView })) + }) + const view = renderer!.root.find((node) => node.type === 'ChatView') + expect(view.props.askRequiresTerminal).toBe(true) + act(() => view.props.onAnswerInTerminal()) + expect(setTabView).toHaveBeenCalledExactlyOnceWith('tab-omp', 'terminal') + }) + + it.each(['structured', 'claude', 'missing tab'])( + 'keeps the terminal-only gate scoped correctly: %s', + async (scenario) => { + await act(async () => { + renderer = create( + overlayElement({ + agent: scenario === 'claude' ? 'claude' : 'omp', + structured: scenario === 'structured', + activeTabId: scenario === 'missing tab' ? null : 'tab-omp' + }) + ) + }) + const view = renderer!.root.find((node) => node.type === 'ChatView') + expect(view.props.askRequiresTerminal).toBe(scenario === 'missing tab') + if (scenario === 'missing tab') { + expect(view.props.onAnswerInTerminal).toBeUndefined() + } + } + ) + it.each([true, false])('offers attach only when the agent takes images (%s)', async (accepts) => { await act(async () => { renderer = create(overlayElement({ acceptsImages: accepts })) diff --git a/mobile/src/session/MobileNativeChatOverlay.tsx b/mobile/src/session/MobileNativeChatOverlay.tsx index 1ec05faa6686..e860ea45fd84 100644 --- a/mobile/src/session/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/MobileNativeChatOverlay.tsx @@ -17,9 +17,11 @@ import { useMobileNativeChatReplyReveals } from './mobile-native-chat-reply-reveals' import { MobileNativeChatRowOverlaysHost } from './MobileNativeChatRowOverlaysHost' +import { nativeChatAskRequiresTerminal } from '../../../src/shared/native-chat-agent-support' type Props = { controller: MobileNativeChatController + activeSessionTabId?: string | null /** Opens a tapped file reference (worktree-relative or absolute, optional * :line(:col) suffix) through the shared tap-to-open flow. */ onOpenFile: (pathText: string) => void @@ -53,6 +55,7 @@ type Props = { * the chat list below it does not. */ export function MobileNativeChatOverlay({ controller, + activeSessionTabId, onOpenFile, images, structuredComposer = null, @@ -146,6 +149,14 @@ export function MobileNativeChatOverlay({ promptKey={controller.nativeChatPromptKey} onDismissAsk={controller.dismissNativeChatAsk} onAnswerAsk={controller.handleNativeChatAnswerAsk} + askRequiresTerminal={ + !controller.nativeChatStructured && nativeChatAskRequiresTerminal(agent) + } + onAnswerInTerminal={ + activeSessionTabId + ? () => controller.setTabView(activeSessionTabId, 'terminal') + : undefined + } onCancelAsk={controller.handleNativeChatCancelAsk} onCancelPrompt={controller.handleNativeChatCancelPrompt} onCollapseAsk={controller.collapseNativeChatAsk} diff --git a/mobile/src/session/MobileNativeChatPromptCard.test.tsx b/mobile/src/session/MobileNativeChatPromptCard.test.tsx index 48ddd6571413..6b547ab4fc3f 100644 --- a/mobile/src/session/MobileNativeChatPromptCard.test.tsx +++ b/mobile/src/session/MobileNativeChatPromptCard.test.tsx @@ -27,6 +27,42 @@ const textInput = (root: ReactTestInstance) => const ask = { questions: [{ question: 'Pick?', options: [{ label: 'East' }], multiSelect: false }] } describe('MobileNativeChatPromptCard collapse', () => { + it.each([true, false])( + 'shows only terminal navigation when answering requires it (%s)', + async (available) => { + const onAnswerInTerminal = vi.fn() + const onAnswerAsk = vi.fn(async () => true) + const onCancelAsk = vi.fn(async () => true) + const onDismissAsk = vi.fn() + let tree: ReactTestRenderer | null = null + await act(async () => { + tree = create( + createElement(MobileNativeChatPromptCard, { + ask, + requiresTerminal: true, + onAnswerAsk, + onCancelAsk, + onDismissAsk, + onAnswerInTerminal: available ? onAnswerInTerminal : undefined + }) + ) + }) + const buttons = tree!.root.findAllByType('Pressable') + expect(buttons).toHaveLength(1) + expect(buttons[0]!.props.accessibilityLabel).toBe('Answer in terminal') + expect(buttons[0]!.props.disabled).toBe(!available) + expect(tree!.root.findAllByType('TextInput')).toHaveLength(0) + if (available) { + act(() => buttons[0]!.props.onPress()) + } + expect(onAnswerInTerminal).toHaveBeenCalledTimes(available ? 1 : 0) + expect(onAnswerAsk).not.toHaveBeenCalled() + expect(onCancelAsk).not.toHaveBeenCalled() + expect(onDismissAsk).not.toHaveBeenCalled() + act(() => tree!.unmount()) + } + ) + it('keeps a partly answered Ask mounted but hidden while collapsed', async () => { let tree: ReactTestRenderer | null = null const render = (collapsed: boolean) => diff --git a/mobile/src/session/MobileNativeChatPromptCard.tsx b/mobile/src/session/MobileNativeChatPromptCard.tsx index 210c91839622..cbb1ce6d7ca0 100644 --- a/mobile/src/session/MobileNativeChatPromptCard.tsx +++ b/mobile/src/session/MobileNativeChatPromptCard.tsx @@ -1,4 +1,5 @@ -import { StyleSheet, View } from 'react-native' +import { Pressable, StyleSheet, Text, View } from 'react-native' +import { colors, radii, spacing, typography } from '../theme/mobile-theme' import type { AskAnswerSelection, AskPrompt } from '../../../src/shared/native-chat-ask' import { MobileNativeChatAsk } from './MobileNativeChatAsk' import { MobileNativeChatPermission } from './MobileNativeChatPermission' @@ -16,6 +17,8 @@ export function MobileNativeChatPromptCard({ askKey, onDismissAsk, onAnswerAsk, + requiresTerminal = false, + onAnswerInTerminal, onCancelAsk, onCancelPrompt, onCollapseAsk, @@ -30,6 +33,8 @@ export function MobileNativeChatPromptCard({ askKey?: string | null onDismissAsk?: () => void onAnswerAsk?: (prompt: AskPrompt, selections: AskAnswerSelection[]) => Promise + requiresTerminal?: boolean + onAnswerInTerminal?: () => void onCancelAsk?: () => Promise onCancelPrompt?: (prompt?: NonNullable) => Promise onCollapseAsk?: () => void @@ -42,43 +47,58 @@ export function MobileNativeChatPromptCard({ question?: MobileChatQuestion | null onAnswerQuestion?: (text: string) => Promise }): React.JSX.Element | null { - const card = ask ? ( - { - const accepted = (await onAnswerAsk?.(ask, selections)) ?? false - if (accepted) { - onDismissAsk?.() - } - return accepted - }} - onCancel={async () => { - const accepted = (await onCancelAsk?.()) ?? false - if (accepted) { - onDismissAsk?.() - } - return accepted - }} - onCollapse={onCollapseAsk} - /> - ) : permission ? ( - (await onRespondPermission?.(send)) ?? false} - onCancel={onCancelPrompt} - onCollapse={onCollapsePrompt} - /> - ) : question ? ( - (await onAnswerQuestion?.(text)) ?? false} - onCancel={onCancelPrompt} - onCollapse={onCollapsePrompt} - /> - ) : null + const card = + ask && requiresTerminal ? ( + + Answer this OMP question in the terminal. + + Answer in terminal + + + ) : ask ? ( + { + const accepted = (await onAnswerAsk?.(ask, selections)) ?? false + if (accepted) { + onDismissAsk?.() + } + return accepted + }} + onCancel={async () => { + const accepted = (await onCancelAsk?.()) ?? false + if (accepted) { + onDismissAsk?.() + } + return accepted + }} + onCollapse={onCollapseAsk} + /> + ) : permission ? ( + (await onRespondPermission?.(send)) ?? false} + onCancel={onCancelPrompt} + onCollapse={onCollapsePrompt} + /> + ) : question ? ( + (await onAnswerQuestion?.(text)) ?? false} + onCancel={onCancelPrompt} + onCollapse={onCollapsePrompt} + /> + ) : null // Why one stable wrapper: collapsing hides the card without remounting it, so a partly answered // card keeps its selections. return ( @@ -94,4 +114,27 @@ export function MobileNativeChatPromptCard({ ) } -const styles = StyleSheet.create({ collapsed: { display: 'none' } }) +const styles = StyleSheet.create({ + collapsed: { display: 'none' }, + terminalCard: { + backgroundColor: colors.bgPanel, + borderTopWidth: StyleSheet.hairlineWidth, + borderTopColor: colors.borderSubtle, + padding: spacing.md, + gap: spacing.sm + }, + explanation: { color: colors.textPrimary, fontSize: typography.bodySize }, + terminalButton: { + alignSelf: 'flex-start', + minHeight: 44, + justifyContent: 'center', + backgroundColor: colors.surfaceBright, + borderRadius: radii.button, + paddingHorizontal: spacing.md + }, + terminalButtonText: { + color: colors.bgBase, + fontSize: typography.bodySize, + fontWeight: '600' + } +}) diff --git a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts index e320c78a53c7..2bf9dd3b6227 100644 --- a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts +++ b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts @@ -134,6 +134,25 @@ afterEach(() => { vi.unstubAllGlobals() }) describe('terminal prompt presentation with the production view, card and composer', () => { + it('forwards terminal navigation without answering or cancelling the question', async () => { + const onAnswerInTerminal = vi.fn() + const onAnswerAsk = vi.fn(async () => true) + const onCancelAsk = vi.fn(async () => true) + await render({ + ask: { questions: [{ question: 'Pick', options: [{ label: 'A' }], multiSelect: false }] }, + askRequiresTerminal: true, + onAnswerInTerminal, + onAnswerAsk, + onCancelAsk + }) + const button = tree!.root.findByProps({ accessibilityLabel: 'Answer in terminal' }) + act(() => button.props.onPress()) + expect(onAnswerInTerminal).toHaveBeenCalledOnce() + expect(onAnswerAsk).not.toHaveBeenCalled() + expect(onCancelAsk).not.toHaveBeenCalled() + expect(tree!.root.findAll((node) => node.type === 'ChatAsk')).toHaveLength(0) + }) + it('accepted Deny hides exactly that occurrence and restores Send across reconnect', async () => { vi.stubGlobal('requestAnimationFrame', (callback: () => void) => setTimeout(callback, 0)) const onRespondPermission = vi.fn(async () => true) diff --git a/mobile/src/session/MobileNativeChatView.tsx b/mobile/src/session/MobileNativeChatView.tsx index c5d94eb62d9a..06973107762d 100644 --- a/mobile/src/session/MobileNativeChatView.tsx +++ b/mobile/src/session/MobileNativeChatView.tsx @@ -146,6 +146,8 @@ type Props = ComposerTrayProps & { /** Deliver the ask answer as per-question selections; the send hook turns them * into selector keystrokes (Claude) or pasted label text (other agents). */ onAnswerAsk?: (prompt: AskPrompt, selections: AskAnswerSelection[]) => Promise + askRequiresTerminal?: boolean + onAnswerInTerminal?: () => void onCancelAsk?: () => Promise /** Cancel a structured approval/question with exact item identity when supported. */ onCancelPrompt?: (prompt?: { itemId: string; expectedRevision: number }) => Promise @@ -213,6 +215,8 @@ export function MobileNativeChatView({ askKey, onDismissAsk, onAnswerAsk, + askRequiresTerminal = false, + onAnswerInTerminal, onCancelAsk, onCancelPrompt, onCollapseAsk, @@ -389,6 +393,8 @@ export function MobileNativeChatView({ diff --git a/mobile/src/session/MobileSessionActiveContent.tsx b/mobile/src/session/MobileSessionActiveContent.tsx index 44e97da19d79..731aebd74d77 100644 --- a/mobile/src/session/MobileSessionActiveContent.tsx +++ b/mobile/src/session/MobileSessionActiveContent.tsx @@ -229,6 +229,7 @@ export function MobileSessionActiveContent({ ))} void - currentAsk?: AskPrompt | null - currentAskStatus?: AgentStatusEntry | null }): { answerAsk: MobileNativeChatAnswerSend['answerAsk'] cancelAsk: () => Promise @@ -37,8 +33,6 @@ export function useMobileBridgeChatPromptWrites(args: { handleRef, deviceTokenRef, agentRef: args.agentRef, - currentAsk: args.currentAsk, - currentAskStatus: args.currentAskStatus, sessionId: args.sessionId, streamIdentity, onSendError @@ -48,6 +42,7 @@ export function useMobileBridgeChatPromptWrites(args: { enabled, handleRef, deviceTokenRef, + agentRef: args.agentRef, cancelPending, onSendError }) diff --git a/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts b/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts index d60e53eb4393..fe197ba2d27d 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send-omp.test.ts @@ -1,276 +1,119 @@ -// Takeover RPCs have their own send-site integration tests; these fixtures script PTY acknowledgements. -vi.mock('../terminal/worker-terminal-takeover-report', () => ({ - reportWorkerTerminalUserInput: vi.fn() -})) - import { createElement } from 'react' import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { - formatAskAnswer, - type AskAnswerSelection, - type AskPrompt -} from '../../../src/shared/native-chat-ask' -import { AGENT_TUI_CLEAR_INPUT_MAX } from '../../../src/shared/agent-tui-input-clear' -import type { AgentStatusEntry } from '../../../src/shared/agent-status-types' -import type { AgentType } from '../../../src/shared/native-chat-types' +import type { AskPrompt } from '../../../src/shared/native-chat-ask' import type { RpcClient } from '../transport/rpc-client' -import { MOBILE_NATIVE_CHAT_QUESTION_STEP_MS } from './mobile-native-chat-answer-stepping' -import { resetMobileNativeChatStaleInputForTests } from './mobile-native-chat-stale-input' -import { resetMobileNativeChatTerminalWritesForTests } from './mobile-native-chat-terminal-write-lock' +import { useMobileNativeChatAnswerSend } from './use-mobile-native-chat-answer-send' +import { useNativeChatAcceptedAction } from './use-native-chat-action-outcomes' import { - useMobileNativeChatAnswerSend, - type MobileNativeChatAnswerSend -} from './use-mobile-native-chat-answer-send' + isMobileNativeChatInputStale, + markMobileNativeChatInputStale, + resetMobileNativeChatStaleInputForTests +} from './mobile-native-chat-stale-input' +import { resetMobileNativeChatTerminalWritesForTests } from './mobile-native-chat-terminal-write-lock' -function acceptedResponse() { - return { - id: 'send', - ok: true as const, - result: { send: { accepted: true } }, - _meta: { runtimeId: 'runtime' } - } -} +vi.mock('../terminal/worker-terminal-takeover-report', () => ({ + reportWorkerTerminalUserInput: vi.fn() +})) -function waitingStatus(prompt: AskPrompt): AgentStatusEntry { - return { - agentType: 'omp', - state: 'waiting', - stateStartedAt: 10, - turnStartedAt: 5, - updatedAt: 10, - prompt: '', - paneKey: 'pane', - stateHistory: [], - toolName: 'ask', - interactivePrompt: JSON.stringify(prompt) - } +const prompt: AskPrompt = { + questions: [{ question: 'Pick', multiSelect: true, options: [{ label: 'A' }, { label: 'B' }] }] } +let renderer: ReactTestRenderer | undefined +beforeEach(() => { + vi.useFakeTimers() + resetMobileNativeChatStaleInputForTests() + resetMobileNativeChatTerminalWritesForTests() +}) +afterEach(() => { + act(() => renderer?.unmount()) + vi.useRealTimers() +}) -describe('useMobileNativeChatAnswerSend for OMP asks', () => { - let renderer: ReactTestRenderer | null = null - let answerSend: MobileNativeChatAnswerSend | null = null - - beforeEach(() => { - vi.useFakeTimers() - resetMobileNativeChatStaleInputForTests() - resetMobileNativeChatTerminalWritesForTests() - }) - - afterEach(() => { - act(() => renderer?.unmount()) - renderer = null - answerSend = null - vi.useRealTimers() +function mount(agent = 'omp') { + const sendRequest = vi.fn().mockResolvedValue({ + id: 'send', + ok: true, + result: { send: { accepted: true } } }) - - async function mount( - client: RpcClient, - agent: AgentType, - options: { - currentAsk?: AskPrompt | null - currentAskStatus?: AgentStatusEntry | null - onSendError?: (message: string) => void - } = {} - ): Promise<() => Promise> { - function Harness(): null { - answerSend = useMobileNativeChatAnswerSend({ - client, - enabled: true, - handleRef: { current: 'terminal' }, - deviceTokenRef: { current: 'device' }, - agentRef: { current: agent }, - sessionId: 'session', - streamIdentity: 'host\0worktree\0tab\0session', - onSendError: options.onSendError ?? vi.fn(), - currentAsk: options.currentAsk, - currentAskStatus: - options.currentAskStatus === undefined && options.currentAsk - ? waitingStatus(options.currentAsk) - : options.currentAskStatus - }) - return null - } - await act(async () => { - renderer = create(createElement(Harness)) + const client: RpcClient = { + sendRequest, + subscribe: () => () => {}, + updateTerminalSubscriptionViewport: () => {}, + getState: () => 'connected', + getReconnectAttempt: () => 0, + getLastConnectedAt: () => 1, + onStateChange: () => () => {}, + notifyForeground: () => {}, + close: () => {} + } + const agentRef = { current: agent } + const onSendError = vi.fn() + const onAccepted = vi.fn() + let answer: ReturnType['answerAsk'] | undefined + function Probe(): null { + const sender = useMobileNativeChatAnswerSend({ + client, + enabled: true, + handleRef: { current: 'terminal' }, + deviceTokenRef: { current: 'device' }, + agentRef, + sessionId: 'session', + streamIdentity: 'host\0folder\0tab\0session', + onSendError }) - return async () => { - await act(async () => renderer?.update(createElement(Harness))) - } + answer = useNativeChatAcceptedAction(sender.answerAsk, onAccepted) + return null } - - it('writes OMP groups from the shared key plan, paced, never as pasted labels', async () => { - const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) - const prompt: AskPrompt = { - questions: [ - { question: 'q1', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] }, - { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } - ] + act(() => { + renderer = create(createElement(Probe)) + }) + return { + sendRequest, + agentRef, + onSendError, + onAccepted, + answer: () => { + if (!answer) { + throw new Error('Answer hook did not mount') + } + return answer(prompt, [{ indices: [0, 1] }]) } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: This fixture exercises only the scripted sendRequest port. - await mount({ sendRequest } as unknown as RpcClient, 'omp', { currentAsk: prompt }) - const selections: AskAnswerSelection[] = [{ indices: [1] }, { indices: [0] }] - const expected = [ - AGENT_TUI_CLEAR_INPUT_MAX, - '\x1b[A\x1b[A\x1b[B', - '\r', - '\x1b[A\x1b[A', - '\r', - '\r' - ] + } +} - let result: Promise | undefined - await act(async () => { - result = answerSend?.answerAsk(prompt, selections) - }) - expect(sendRequest).toHaveBeenCalledTimes(1) - for (let index = 1; index < expected.length; index += 1) { - await act(async () => { - await vi.advanceTimersByTimeAsync(MOBILE_NATIVE_CHAT_QUESTION_STEP_MS) - }) - expect(sendRequest).toHaveBeenCalledTimes(index + 1) - } - await expect(result).resolves.toBe(true) - expect(sendRequest.mock.calls.map((call) => call[1])).toEqual( - expected.map((text) => expect.objectContaining({ text, enter: false })) - ) - expect(sendRequest.mock.calls.map((call) => call[1])).not.toContainEqual( - expect.objectContaining({ text: formatAskAnswer(prompt, selections), enter: true }) - ) +describe('OMP terminal-only question answers', () => { + it('refuses without healing drafts, writing input or dismissing the card', async () => { + const f = mount() + markMobileNativeChatInputStale('terminal') + await expect(f.answer()).resolves.toBe(false) + expect(f.sendRequest).not.toHaveBeenCalled() + expect(isMobileNativeChatInputStale('terminal')).toBe(true) + expect(f.onAccepted).not.toHaveBeenCalled() + expect(f.onSendError).toHaveBeenCalledWith('Answer this question in terminal view') }) - it.each(['accepted', 'unknown'] as const)( - 'fences a later retry after an %s group even after the chain has unwound', - async (outcome) => { - const sendRequest = vi - .fn() - .mockResolvedValue( - outcome === 'accepted' ? acceptedResponse() : { ...acceptedResponse(), result: {} } - ) - const prompt: AskPrompt = { - questions: [ - { question: 'Pick', multiSelect: true, options: [{ label: 'A' }, { label: 'B' }] } - ] - } - const onSendError = vi.fn() - const options: { - currentAsk: AskPrompt | null - currentAskStatus?: AgentStatusEntry - onSendError: typeof onSendError - } = { - currentAsk: prompt, - onSendError - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the scripted sendRequest port is exercised. - const rerender = await mount({ sendRequest } as unknown as RpcClient, 'omp', options) - let first: Promise | undefined - await act(async () => { - first = answerSend?.answerAsk(prompt, [{ indices: [1] }]) - }) - act(() => answerSend?.cancelPending()) - await expect(first).resolves.toBe(false) - await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) - expect(sendRequest).toHaveBeenCalledTimes(1) - expect(onSendError).toHaveBeenLastCalledWith( - 'Answer not sent — check terminal before retrying' - ) - options.currentAsk = null - await rerender() - options.currentAsk = prompt - await rerender() - await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) - expect(sendRequest).toHaveBeenCalledTimes(1) - options.currentAskStatus = { ...waitingStatus(prompt), stateStartedAt: 15, state: 'blocked' } - await rerender() - await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) - expect(sendRequest).toHaveBeenCalledTimes(1) - options.currentAskStatus = { ...waitingStatus(prompt), turnStartedAt: 20, stateStartedAt: 25 } - await rerender() - sendRequest.mockResolvedValue(acceptedResponse()) - let next: Promise | undefined - await act(async () => { - next = answerSend?.answerAsk(prompt, [{ indices: [1] }]) - }) - await act(async () => { - await vi.runAllTimersAsync() - }) - await expect(next).resolves.toBe(true) - } - ) + it('refuses a retained answer callback after the live agent becomes OMP', async () => { + const f = mount('claude') + f.agentRef.current = 'omp' + await expect(f.answer()).resolves.toBe(false) + expect(f.sendRequest).not.toHaveBeenCalled() + expect(f.onAccepted).not.toHaveBeenCalled() + }) - it('stops before the next group when the observed card is replaced', async () => { - const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) - const prompt: AskPrompt = { - questions: [ - { question: 'Pick', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] } - ] - } - const options = { currentAsk: prompt, onSendError: vi.fn() } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the scripted sendRequest port is exercised. - const rerender = await mount({ sendRequest } as unknown as RpcClient, 'omp', options) - let result: Promise | undefined + it('stops paced writes before another group reaches a replacement OMP agent', async () => { + const f = mount('claude') + let sent: Promise | undefined await act(async () => { - result = answerSend?.answerAsk(prompt, [{ indices: [1] }]) + sent = f.answer() }) - options.currentAsk = { questions: [{ ...prompt.questions[0]!, question: 'Replacement' }] } - await rerender() + expect(f.sendRequest).toHaveBeenCalledTimes(1) + f.agentRef.current = 'omp' await act(async () => { await vi.runAllTimersAsync() }) - await expect(result).resolves.toBe(false) - expect(sendRequest).toHaveBeenCalledTimes(1) - expect(options.onSendError).toHaveBeenCalledWith( - 'Answer partly sent — check chat before retrying' - ) - }) - it.each(['missing status', 'working', 'different turn'] as const)( - 'stops writes when the prompt has %s', - async (change) => { - const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) - const prompt: AskPrompt = { - questions: [ - { question: 'Pick', multiSelect: true, options: [{ label: 'A' }, { label: 'B' }] } - ] - } - const options: { currentAsk: AskPrompt; currentAskStatus: AgentStatusEntry | null } = { - currentAsk: prompt, - currentAskStatus: waitingStatus(prompt) - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the scripted sendRequest port is exercised. - const rerender = await mount({ sendRequest } as unknown as RpcClient, 'omp', options) - let result: Promise | undefined - await act(async () => { - result = answerSend?.answerAsk(prompt, [{ indices: [1] }]) - }) - options.currentAskStatus = - change === 'missing status' - ? null - : { - ...waitingStatus(prompt), - ...(change === 'working' ? { state: 'working' } : { turnStartedAt: 20 }) - } - await rerender() - await act(async () => { - await vi.runAllTimersAsync() - }) - await expect(result).resolves.toBe(false) - expect(sendRequest).toHaveBeenCalledTimes(1) - } - ) - - it('refuses a transcript-only OMP question before any terminal write', async () => { - const sendRequest = vi.fn().mockResolvedValue(acceptedResponse()) - const prompt: AskPrompt = { - questions: [ - { question: 'Pick', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] } - ] - } - // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Only the scripted sendRequest port is exercised. - await mount({ sendRequest } as unknown as RpcClient, 'omp', { - currentAsk: prompt, - currentAskStatus: null - }) - await expect(answerSend?.answerAsk(prompt, [{ indices: [1] }])).resolves.toBe(false) - expect(sendRequest).not.toHaveBeenCalled() + await expect(sent).resolves.toBe(false) + expect(f.sendRequest).toHaveBeenCalledTimes(1) + expect(f.onAccepted).not.toHaveBeenCalled() }) }) diff --git a/mobile/src/session/use-mobile-native-chat-answer-send.ts b/mobile/src/session/use-mobile-native-chat-answer-send.ts index 47b6ea332298..79e43109d14a 100644 --- a/mobile/src/session/use-mobile-native-chat-answer-send.ts +++ b/mobile/src/session/use-mobile-native-chat-answer-send.ts @@ -1,22 +1,12 @@ +import { useCallback, useEffect, useRef, type MutableRefObject } from 'react' import { - useCallback, - useEffect, - useLayoutEffect, - useRef, - useState, - type MutableRefObject -} from 'react' -import { - buildNativeChatAskAnswerKeys, + buildAskAnswerKeys, + buildCodexAskAnswerKeys, formatAskAnswer, hasAskAnswer, - nativeChatAskDismissKey, type AskAnswerSelection, type AskPrompt } from '../../../src/shared/native-chat-ask' -import type { AgentStatusEntry } from '../../../src/shared/agent-status-types' -import { nativeChatOmpPromptIdentity } from '../../../src/shared/native-chat-omp-prompt-identity' -import { createOmpAnswerRetryFence } from '../../../src/shared/native-chat-omp-answer-retry-fence' import type { RpcClient } from '../transport/rpc-client' import { MOBILE_NATIVE_CHAT_QUESTION_STEP_MS } from './mobile-native-chat-answer-stepping' import { @@ -29,12 +19,13 @@ import { releaseMobileNativeChatTerminalWrite } from './mobile-native-chat-terminal-write-lock' import { + nativeChatAskRequiresTerminal, resolveNativeChatTranscriptAgent, shouldStepNativeChatAskAnswer } from '../../../src/shared/native-chat-agent-support' -/** Sends an ask-user answer to the active chat pane. Selector agents use their - * own keystrokes; other agents get pasted label text. +/** Sends an ask-user answer to the active chat pane. Claude and Codex selectors + * use their agent-specific keystrokes; other agents get pasted label text. * Extracted from the session route to keep that file under its line cap and to * own the pending-timer lifecycle in one place. */ export type MobileNativeChatAnswerSend = { @@ -72,8 +63,6 @@ export function useMobileNativeChatAnswerSend(args: { sessionId: string | null streamIdentity: string onSendError: (message: string) => void - currentAsk?: AskPrompt | null - currentAskStatus?: AgentStatusEntry | null }): MobileNativeChatAnswerSend { const { client, @@ -83,15 +72,8 @@ export function useMobileNativeChatAnswerSend(args: { agentRef, sessionId, streamIdentity, - onSendError, - currentAsk, - currentAskStatus + onSendError } = args - const currentAskRef = useRef({ prompt: currentAsk, status: currentAskStatus }) - useLayoutEffect(() => { - currentAskRef.current = { prompt: currentAsk, status: currentAskStatus } - }, [currentAsk, currentAskStatus]) - const [attemptedOmpAsks] = useState(createOmpAnswerRetryFence) const generationRef = useRef(0) const activeRouteRef = useRef({ client, enabled, sessionId, streamIdentity }) activeRouteRef.current = { client, enabled, sessionId, streamIdentity } @@ -124,6 +106,11 @@ export function useMobileNativeChatAnswerSend(args: { const answerAsk = useCallback( async (prompt: AskPrompt, selections: AskAnswerSelection[]): Promise => { + if (nativeChatAskRequiresTerminal(agentRef.current)) { + cancelPending() + onSendError('Answer this question in terminal view') + return false + } const handle = handleRef.current if (!client || !handle || !enabled) { onSendError('Answer not sent (disconnected)') @@ -132,21 +119,6 @@ export function useMobileNativeChatAnswerSend(args: { if (!hasAskAnswer(prompt, selections)) { return false } - const agent = agentRef.current - const omp = resolveNativeChatTranscriptAgent(agent) === 'omp' - const askKey = nativeChatAskDismissKey(prompt) - const ompPromptIdentity = nativeChatOmpPromptIdentity(currentAskRef.current.status, prompt) - const ompAttemptKey = JSON.stringify([ - streamIdentity, - sessionId, - handle, - askKey, - currentAskRef.current.status?.turnStartedAt ?? currentAskRef.current.status?.stateStartedAt - ]) - if (omp && attemptedOmpAsks.blocks(ompAttemptKey)) { - onSendError('Answer not sent — check terminal before retrying') - return false - } // One composed write sequence per terminal: an answer landing mid-flight // in an image paste (or vice versa) would interleave bytes into the PTY. // A superseding answer shares the cancelled chain's hold on this terminal @@ -201,12 +173,7 @@ export function useMobileNativeChatAnswerSend(args: { activeRoute.sessionId !== sessionId || activeRoute.streamIdentity !== streamIdentity || handleRef.current !== handle || - agentRef.current !== agent || - (omp && - (ompPromptIdentity === null || - nativeChatOmpPromptIdentity(currentAskRef.current.status, prompt) !== - ompPromptIdentity || - nativeChatAskDismissKey(currentAskRef.current.prompt ?? null) !== askKey)) + nativeChatAskRequiresTerminal(agentRef.current) ) { return false } @@ -222,15 +189,9 @@ export function useMobileNativeChatAnswerSend(args: { : {}) }) if (outcome === 'unknown') { - if (omp) { - attemptedOmpAsks.record(ompAttemptKey) - } sawUnknownOutcome = true } if (outcome === 'accepted') { - if (omp) { - attemptedOmpAsks.record(ompAttemptKey) - } sawAcceptedGroup = true } return outcome === 'accepted' @@ -270,7 +231,8 @@ export function useMobileNativeChatAnswerSend(args: { } return false } - // Selector keystrokes are paced so each step renders before the next lands. + // Grok commits pasted labels; Claude and Codex need their selector-specific + // keystrokes paced so each step renders before the next lands. if (!shouldStepNativeChatAskAnswer(agentRef.current)) { // This shape pastes the label into the composer and commits it, so an // orphaned image paste would be submitted along with the answer (#10228). @@ -304,7 +266,10 @@ export function useMobileNativeChatAnswerSend(args: { const sent = (await sendTerminal(formatAskAnswer(prompt, selections), true)) || fail() return sent && writeTurnsRef.current.get(handle) === turn } - const groups = buildNativeChatAskAnswerKeys(agentRef.current, prompt, selections) + const groups = + resolveNativeChatTranscriptAgent(agentRef.current) === 'codex' + ? buildCodexAskAnswerKeys(prompt, selections) + : buildAskAnswerKeys(prompt, selections) for (let index = 0; index < groups.length; index += 1) { if (generationRef.current !== generation) { return false @@ -344,7 +309,6 @@ export function useMobileNativeChatAnswerSend(args: { }, [ agentRef, - attemptedOmpAsks, enabled, cancelPending, client, diff --git a/mobile/src/session/use-mobile-native-chat-cancel-ask.test.ts b/mobile/src/session/use-mobile-native-chat-cancel-ask.test.ts index 0220e09c6655..ecd2761b7a1f 100644 --- a/mobile/src/session/use-mobile-native-chat-cancel-ask.test.ts +++ b/mobile/src/session/use-mobile-native-chat-cancel-ask.test.ts @@ -8,7 +8,7 @@ import { useMobileNativeChatCancelAsk } from './use-mobile-native-chat-cancel-as let renderer: ReactTestRenderer | undefined afterEach(() => act(() => renderer?.unmount())) -function fixture() { +function fixture(agent = 'claude') { const sendRequest = vi.fn().mockResolvedValue({ id: 'send', ok: true, @@ -27,6 +27,7 @@ function fixture() { } const cancelPending = vi.fn() const onSendError = vi.fn() + const agentRef = { current: agent } let cancelAsk: (() => Promise) | undefined function Probe(): null { cancelAsk = useMobileNativeChatCancelAsk({ @@ -34,6 +35,7 @@ function fixture() { enabled: true, handleRef: { current: 'terminal' }, deviceTokenRef: { current: 'device' }, + agentRef, cancelPending, onSendError }) @@ -46,6 +48,7 @@ function fixture() { sendRequest, cancelPending, onSendError, + agentRef, cancel: () => { if (!cancelAsk) { throw new Error('Cancel hook did not mount') @@ -56,6 +59,13 @@ function fixture() { } describe('mobile question rejection', () => { + it('refuses a retained cancel callback when the live agent becomes OMP', async () => { + const f = fixture() + f.agentRef.current = 'omp' + await expect(f.cancel()).resolves.toBe(false) + expect(f.sendRequest).not.toHaveBeenCalled() + expect(f.onSendError).toHaveBeenCalledWith('Answer this question in terminal view') + }) it('cancels pending answer writes then sends exactly one Escape without submitting', async () => { const f = fixture() await expect(f.cancel()).resolves.toBe(true) diff --git a/mobile/src/session/use-mobile-native-chat-cancel-ask.ts b/mobile/src/session/use-mobile-native-chat-cancel-ask.ts index fa949db146bd..8b59f91a8722 100644 --- a/mobile/src/session/use-mobile-native-chat-cancel-ask.ts +++ b/mobile/src/session/use-mobile-native-chat-cancel-ask.ts @@ -1,4 +1,5 @@ import { useCallback, type MutableRefObject } from 'react' +import { nativeChatAskRequiresTerminal } from '../../../src/shared/native-chat-agent-support' import type { RpcClient } from '../transport/rpc-client' import { sendMobileNativeChatMessageWithOutcome } from './mobile-native-chat-send' @@ -10,12 +11,18 @@ export function useMobileNativeChatCancelAsk(args: { enabled: boolean handleRef: MutableRefObject deviceTokenRef: MutableRefObject + agentRef: MutableRefObject /** Cancels unsent answer groups before issuing Escape. */ cancelPending: () => void onSendError: (message: string) => void }): () => Promise { - const { client, enabled, handleRef, deviceTokenRef, cancelPending, onSendError } = args + const { client, enabled, handleRef, deviceTokenRef, agentRef, cancelPending, onSendError } = args return useCallback(async (): Promise => { + if (nativeChatAskRequiresTerminal(agentRef.current)) { + cancelPending() + onSendError('Answer this question in terminal view') + return false + } const handle = handleRef.current if (!client || !handle || !enabled) { onSendError('Cancel not sent (disconnected)') @@ -42,5 +49,5 @@ export function useMobileNativeChatCancelAsk(args: { onSendError('Cancel not sent') } return outcome === 'accepted' - }, [cancelPending, client, deviceTokenRef, enabled, handleRef, onSendError]) + }, [agentRef, cancelPending, client, deviceTokenRef, enabled, handleRef, onSendError]) } diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index 187b433eacf0..7d1b238bf791 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -184,8 +184,6 @@ export function useMobileNativeChatController(args: { handleRef: activeHandleRef, deviceTokenRef, agentRef: activeChatAgentRef, - currentAsk: nativeChatAskPrompt, - currentAskStatus: nativeChatStatus, sessionId: activeChatSessionId, streamIdentity, onSendError @@ -219,7 +217,7 @@ export function useMobileNativeChatController(args: { onSendError }) - const structuredSend = useMobileStructuredNativeChatSendBridge({ + const structuredNativeChatSend = useMobileStructuredNativeChatSendBridge({ agent: activeChatResolution?.agent, sendStructured: structuredNativeChat.sendWithOutcome, captureSendOrigin, @@ -328,9 +326,11 @@ export function useMobileNativeChatController(args: { nativeChatQueued: structuredNativeChat.queued, nativeChatBackgroundTasks: activeChatStructured ? structuredNativeChat.backgroundTasks : null, ...nativeChatFiles, - handleNativeChatSend: activeChatStructured ? structuredSend.send : handleNativeChatSend, + handleNativeChatSend: activeChatStructured + ? structuredNativeChatSend.send + : handleNativeChatSend, handleNativeChatSendWithOutcome: activeChatStructured - ? structuredSend.sendWithOutcome + ? structuredNativeChatSend.sendWithOutcome : handleNativeChatSendWithOutcome, readSeededLaunchDraft, nativeChatSessionOptions, diff --git a/src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx b/src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx index 6d374f1278b2..be39835cd3aa 100644 --- a/src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInteractiveCard.test.tsx @@ -76,6 +76,42 @@ const SEND: NativeChatInteractiveSend = { cancelAsk: mocks.cancelAsk } +describe('terminal-only question presentation', () => { + beforeEach(() => vi.clearAllMocks()) + afterEach(cleanup) + it.each([true, false])( + 'replaces answer and cancel controls with terminal navigation (%s)', + (available) => { + const onAnswerInTerminal = vi.fn() + const onDismiss = vi.fn() + render( + + ) + const button = screen.getByRole('button', { name: 'Answer in terminal' }) + expect(screen.getAllByRole('button')).toHaveLength(1) + expect(screen.queryByRole('textbox')).not.toBeInTheDocument() + expect(button).toHaveProperty('disabled', !available) + fireEvent.click(button) + expect(onAnswerInTerminal).toHaveBeenCalledTimes(available ? 1 : 0) + expect(mocks.sendAnswer).not.toHaveBeenCalled() + expect(mocks.cancelAsk).not.toHaveBeenCalled() + expect(mocks.sendRawVerified).not.toHaveBeenCalled() + expect(onDismiss).not.toHaveBeenCalled() + } + ) +}) + // Stands in for the view: it derives the shown card and renders it XOR the composer. function CardHarness({ canSend, diff --git a/src/renderer/src/components/native-chat/NativeChatInteractiveCard.tsx b/src/renderer/src/components/native-chat/NativeChatInteractiveCard.tsx index c448ff6eb6d0..940cb0b0e6ad 100644 --- a/src/renderer/src/components/native-chat/NativeChatInteractiveCard.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInteractiveCard.tsx @@ -3,6 +3,8 @@ import type { InteractivePromptCard } from './native-chat-interactive-prompt' import { NativeChatQuestionCard } from './NativeChatQuestionCard' import { NativeChatApprovalCard } from './NativeChatApprovalCard' import type { NativeChatInteractiveSend } from './use-native-chat-interactive-send' +import { Button } from '@/components/ui/button' +import { translate } from '@/i18n/i18n' /** * Render one prompt occurrence the view chose (see useNativeChatPromptCardPresentation): a @@ -19,6 +21,8 @@ export function NativeChatInteractiveCard({ send, onDismiss, onCollapse, + requiresTerminal = false, + onAnswerInTerminal, shouldFocus = false, answerInputRef }: { @@ -28,6 +32,8 @@ export function NativeChatInteractiveCard({ onDismiss: () => void /** Fold this occurrence to a strip above the composer, writing nothing. */ onCollapse?: () => void + requiresTerminal?: boolean + onAnswerInTerminal?: () => void /** Take focus when the card takes the input region from the composer. */ shouldFocus?: boolean /** Forwarded to the question card's free-text row so pane-level Paste keeps @@ -61,6 +67,30 @@ export function NativeChatInteractiveCard({ }, [cancelPending]) if (card.kind === 'question') { + if (requiresTerminal) { + return ( +
+
+
+

+ {translate( + 'components.native-chat.question.terminalRequired', + 'Answer this OMP question in the terminal.' + )} +

+ +
+
+
+ ) + } return ( ({ vi.mock('./use-native-chat-interactive-prompt-card', () => ({ useNativeChatInteractivePromptCard: () => ({ kind: 'question', prompt }) })) -vi.mock('./NativeChatInteractiveCard', () => ({ - NativeChatInteractiveCard: (props: { send: NativeChatInteractiveSend }) => { - stubs.cardSend = props.send - return null +vi.mock('./NativeChatInteractiveCard', async (importOriginal) => { + const original = await importOriginal() + return { + NativeChatInteractiveCard: ( + props: React.ComponentProps + ) => { + stubs.cardSend = props.send + return props.requiresTerminal ? : null + } } -})) +}) vi.mock('./NativeChatComposer', () => ({ NativeChatComposer: (props: ComposerStubProps) => { stubs.composer = props @@ -73,6 +79,39 @@ afterEach(() => { }) describe('NativeChatResolvedView sends', () => { + it('opens the terminal for an OMP question instead of showing answer controls', () => { + stubs.session = { + messages: [], + status: 'ready', + sessionId: 'session-omp', + agent: 'omp', + hasMore: false, + loadingEarlier: false, + olderHistoryGeneration: 0, + loadEarlier: vi.fn(), + readPhase: 'ready' + } + const onSwitchToTerminal = vi.fn() + render( + + ) + fireEvent.click(screen.getByRole('button', { name: 'Answer in terminal' })) + expect(onSwitchToTerminal).toHaveBeenCalledOnce() + expect(stubs.revealLatest).not.toHaveBeenCalled() + expect(screen.queryByRole('textbox')).toBeNull() + }) + it('brings the latest into view for a composer send and a prompt answer, not a Stop', () => { stubs.session = { messages: [ diff --git a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx index 8d1c7a20a83e..55fb7574c54b 100644 --- a/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx +++ b/src/renderer/src/components/native-chat/NativeChatResolvedView.tsx @@ -19,6 +19,7 @@ import { useNativeChatFind } from './use-native-chat-find' import { NativeChatFindBar } from './NativeChatFindBar' import { useNativeChatCanSend } from './use-native-chat-can-send' import { NativeChatInteractiveCard } from './NativeChatInteractiveCard' +import { nativeChatAskRequiresTerminal } from '../../../../shared/native-chat-agent-support' import { useNativeChatInteractivePromptCard } from './use-native-chat-interactive-prompt-card' import { useNativeChatPromptCardPresentation } from './use-native-chat-prompt-card-presentation' import { NativeChatPromptStrip } from './NativeChatPromptCollapse' @@ -114,9 +115,7 @@ export function NativeChatResolvedView({ ) // Why: Stop suppression must clear on a newer working epoch even when status // never leaves 'working' (interrupt + immediate next turn coalesced). - const hookWorkingEpoch = useAppStore( - (s) => s.agentStatusByPaneKey[paneKey]?.stateStartedAt ?? null - ) + const workingEpoch = useAppStore((s) => s.agentStatusByPaneKey[paneKey]?.stateStartedAt ?? null) const canSend = useNativeChatCanSend(targetPtyId) // Reuse the verified composer send path for interactive cards and composer // stop (Stop sends ESC, the agent-TUI interrupt key). @@ -279,19 +278,19 @@ export function NativeChatResolvedView({ shouldClearNativeChatWorkingSuppression({ working: liveWorking, interrupted: workingInterrupted, - workingEpoch: hookWorkingEpoch, + workingEpoch, previousWorkingEpoch: previousWorkingEpochRef.current }) ) { setWorkingInterrupted(false) } - if (liveWorking && hookWorkingEpoch != null) { - previousWorkingEpochRef.current = hookWorkingEpoch + if (liveWorking && workingEpoch != null) { + previousWorkingEpochRef.current = workingEpoch } if (!liveWorking) { previousWorkingEpochRef.current = null } - }, [liveWorking, workingInterrupted, hookWorkingEpoch]) + }, [liveWorking, workingInterrupted, workingEpoch]) const { isWorking, turnActive, awaitingInput } = resolveNativeChatTerminalTurn({ isConversation, working: liveWorking, @@ -404,6 +403,8 @@ export function NativeChatResolvedView({ key={promptCardPresentation.occurrenceKey ?? 'prompt'} card={mountedPromptCard} send={interactiveSend} + requiresTerminal={nativeChatAskRequiresTerminal(agent)} + onAnswerInTerminal={onSwitchToTerminal} onDismiss={promptCardPresentation.dismiss} onCollapse={promptCardPresentation.collapse} shouldFocus={shownPromptCard !== null && isVisible && isFocusedGroup} diff --git a/src/renderer/src/components/native-chat/native-chat-input-clear.ts b/src/renderer/src/components/native-chat/native-chat-input-clear.ts index 0e6a0bb5e805..3d8cbabe6e13 100644 --- a/src/renderer/src/components/native-chat/native-chat-input-clear.ts +++ b/src/renderer/src/components/native-chat/native-chat-input-clear.ts @@ -17,8 +17,6 @@ export const NATIVE_CHAT_CLEAR_UNSUBMITTED_INPUT = '\x15' export const NATIVE_CHAT_CLEAR_CONFIRM_MS = 140 export type NativeChatSendOptions = { - /** Stop a paced selector when its observed question is no longer current. */ - beforeWrite?: () => boolean /** The host refused a write; nothing after it was sent. */ onWriteRejected?: () => void /** A write's acknowledgment was lost; it may or may not have landed. */ diff --git a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts index 82b81a8921af..4cbc4c692eae 100644 --- a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.test.ts @@ -2,8 +2,6 @@ import { describe, expect, it } from 'vitest' import { buildAskAnswerKeys, buildCodexAskAnswerKeys, - buildNativeChatAskAnswerKeys, - buildOmpAskAnswerKeys, formatAskAnswer, hasAskAnswer, parseApprovalFromStatus, @@ -11,7 +9,6 @@ import { parseInteractivePrompt, type AskPrompt } from './native-chat-interactive-prompt' -import { AGENT_TUI_CLEAR_INPUT_MAX } from '../../../../shared/agent-tui-input-clear' const ESC = String.fromCharCode(27) @@ -305,129 +302,3 @@ for (const agent of ['opencode', 'opencode2']) { expect(card?.options[0].send).toBe('\r') }) } - -describe('buildOmpAskAnswerKeys', () => { - const UP = '\x1b[A' - const DOWN = '\x1b[B' - const ENTER = '\r' - const RIGHT = '\x1b[C' - const SPACE = ' ' - const CLEAR = { raw: AGENT_TUI_CLEAR_INPUT_MAX } - - it('homes to row 0 then moves down to the picked option before Enter', () => { - expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [1] }])).toEqual([ - CLEAR, - { raw: `${UP}${UP}${UP}${DOWN}` }, - { raw: ENTER } - ]) - }) - - it('homes only when the first option is picked', () => { - expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [0] }])).toEqual([ - CLEAR, - { raw: `${UP}${UP}${UP}` }, - { raw: ENTER } - ]) - }) - - it('routes free text through the Other row and submits the editor', () => { - expect( - buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [], other: 'Custom' }]) - ).toEqual([ - CLEAR, - { raw: `${UP}${UP}${UP}${DOWN}${DOWN}${DOWN}` }, - { raw: ENTER }, - { text: 'Custom' }, - { raw: ENTER } - ]) - }) - - it('toggles multi-select picks with Space, then Right to Review and Enter to submit', () => { - // OMP >= 18.2: Enter on a multi-select row confirms and advances; only Space toggles. - expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C'], true), [{ indices: [0, 2] }])).toEqual([ - CLEAR, - { raw: `${UP}${UP}${UP}` }, - { raw: SPACE }, - { raw: `${UP}${UP}${UP}${DOWN}${DOWN}` }, - { raw: SPACE }, - { raw: RIGHT }, - { raw: ENTER } - ]) - }) - - it('does not step again after multi-select free text, which advances on its own', () => { - expect( - buildOmpAskAnswerKeys(single(['A', 'B', 'C'], true), [{ indices: [1], other: 'D' }]) - ).toEqual([ - CLEAR, - { raw: `${UP}${UP}${UP}${DOWN}` }, - { raw: SPACE }, - { raw: `${UP}${UP}${UP}${DOWN}${DOWN}${DOWN}` }, - { raw: ENTER }, - { text: 'D' }, - { raw: ENTER }, - { raw: ENTER } - ]) - const prompt: AskPrompt = { - questions: [ - { question: 'q1', multiSelect: true, options: [{ label: 'A' }, { label: 'B' }] }, - { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } - ] - } - expect(buildOmpAskAnswerKeys(prompt, [{ indices: [], other: 'x' }, { indices: [1] }])).toEqual([ - CLEAR, - { raw: `${UP}${UP}${DOWN}${DOWN}` }, - { raw: ENTER }, - { text: 'x' }, - { raw: ENTER }, - { raw: `${UP}${UP}${DOWN}` }, - { raw: ENTER }, - { raw: ENTER } - ]) - }) - - it('steps past an unanswered question in a multi-question prompt', () => { - const prompt: AskPrompt = { - questions: [ - { question: 'q1', multiSelect: false, options: [{ label: 'A' }, { label: 'B' }] }, - { question: 'q2', multiSelect: false, options: [{ label: 'C' }, { label: 'D' }] } - ] - } - - expect(buildOmpAskAnswerKeys(prompt, [{ indices: [1] }, { indices: [] }])).toEqual([ - CLEAR, - { raw: `${UP}${UP}${DOWN}` }, - { raw: ENTER }, - { raw: RIGHT }, - { raw: ENTER } - ]) - }) - - it.each([[3], [-1], [0.5], [0, 0]])( - 'rejects invalid OMP indices %j before clearing the terminal', - (...indices) => { - expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C'], true), [{ indices }])).toEqual([]) - } - ) - - it('returns no keys when nothing is answered', () => { - expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [{ indices: [] }])).toEqual([]) - expect(buildOmpAskAnswerKeys(single(['A', 'B', 'C']), [])).toEqual([]) - }) -}) - -describe('buildNativeChatAskAnswerKeys', () => { - it('dispatches by agent to the matching builder', () => { - const prompt = single(['A', 'B', 'C']) - const selections = [{ indices: [1] }] - expect(buildNativeChatAskAnswerKeys('omp', prompt, selections)).toEqual( - buildOmpAskAnswerKeys(prompt, selections) - ) - expect(buildNativeChatAskAnswerKeys('codex', prompt, selections)).toEqual( - buildCodexAskAnswerKeys(prompt, selections) - ) - expect(buildNativeChatAskAnswerKeys('claude', prompt, selections)).toEqual( - buildAskAnswerKeys(prompt, selections) - ) - }) -}) diff --git a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.ts b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.ts index 0601a82af993..baaf6803a234 100644 --- a/src/renderer/src/components/native-chat/native-chat-interactive-prompt.ts +++ b/src/renderer/src/components/native-chat/native-chat-interactive-prompt.ts @@ -7,8 +7,6 @@ import type { import { buildAskAnswerKeys, buildCodexAskAnswerKeys, - buildNativeChatAskAnswerKeys, - buildOmpAskAnswerKeys, formatAskAnswer, hasAskAnswer, parseAskFromStatus, @@ -24,8 +22,6 @@ import { export { buildAskAnswerKeys, buildCodexAskAnswerKeys, - buildNativeChatAskAnswerKeys, - buildOmpAskAnswerKeys, formatAskAnswer, hasAskAnswer, parseAskFromStatus, diff --git a/src/renderer/src/components/native-chat/native-chat-observed-send.ts b/src/renderer/src/components/native-chat/native-chat-observed-send.ts index 4b5e81e4ee45..1b96acd49cec 100644 --- a/src/renderer/src/components/native-chat/native-chat-observed-send.ts +++ b/src/renderer/src/components/native-chat/native-chat-observed-send.ts @@ -46,11 +46,6 @@ export function sendNativeChatObservedWrites( if (isCancelled()) { return } - if (options.beforeWrite && !options.beforeWrite()) { - options.onDeliverySettled?.(false) - markSubmitted() - return - } void sendRuntimePtyInputVerified(ptyId, write.data, 'driving', writeOptions) .then((accepted) => { if (isCancelled()) { diff --git a/src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts b/src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts index 7b766cd48c00..6bddf8b4e888 100644 --- a/src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts +++ b/src/renderer/src/components/native-chat/native-chat-runtime-send.test.ts @@ -463,9 +463,7 @@ describe('sendNativeChatAskAnswer', () => { }) it('returns a no-op handle for an empty key group list', () => { - const settled = vi.fn() - const handle = sendNativeChatAskAnswer(PTY, [], settled) - expect(settled).toHaveBeenCalledExactlyOnceWith(false) + const handle = sendNativeChatAskAnswer(PTY, []) expect(handle.settleAfterMs).toBe(0) handle.cancel() expect(sendRuntimePtyInput).not.toHaveBeenCalled() @@ -496,18 +494,6 @@ describe('sendNativeChatAskAnswer', () => { ) }) - it('stops a paced selector before writing when its question guard changes', async () => { - let current = true - const settled = vi.fn() - sendNativeChatAskAnswer(PTY, [{ raw: ' ' }, { raw: '\r' }], settled, () => current) - await vi.advanceTimersByTimeAsync(0) - expect(sendRuntimePtyInputVerified).toHaveBeenCalledTimes(1) - current = false - await vi.runAllTimersAsync() - expect(sendRuntimePtyInputVerified).toHaveBeenCalledTimes(1) - expect(settled).toHaveBeenCalledExactlyOnceWith(false) - }) - it('cancels remaining key group timers', async () => { const handle = sendNativeChatAskAnswer(PTY, [{ raw: '1' }, { raw: '2' }]) await vi.advanceTimersByTimeAsync(0) diff --git a/src/renderer/src/components/native-chat/native-chat-runtime-send.ts b/src/renderer/src/components/native-chat/native-chat-runtime-send.ts index 26c216bbfcf8..2e4696cf2e95 100644 --- a/src/renderer/src/components/native-chat/native-chat-runtime-send.ts +++ b/src/renderer/src/components/native-chat/native-chat-runtime-send.ts @@ -212,11 +212,9 @@ export function submitNativeChatPrompt(ptyId: string): void { export function sendNativeChatAskAnswer( ptyId: string, groups: AskAnswerKeyGroup[], - onSettled?: (delivered: boolean) => void, - beforeWrite?: () => boolean + onSettled?: (delivered: boolean) => void ): NativeChatSendHandle { if (groups.length === 0) { - onSettled?.(false) return { cancel: () => {}, settleAfterMs: 0 } } return sendNativeChatObservedWrites( @@ -227,7 +225,6 @@ export function sendNativeChatAskAnswer( })), { clearInput: '', - beforeWrite, stopOnUnconfirmed: !!onSettled, settleDelayMs: NATIVE_CHAT_SUBMIT_DELAY_MS, onDeliverySettled: onSettled diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx index cd0764ef2bef..753a3124184f 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.test.tsx @@ -64,6 +64,23 @@ describe('useNativeChatInteractiveSend', () => { mocks.sendNativeChatMessage.mockReturnValue(handle) }) + it('refuses OMP question answers and cancellation without writing or clearing the wait', async () => { + const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'omp')) + const settled = vi.fn() + act(() => { + expect(result.current.sendAnswer(PROMPT, [{ indices: [1] }], settled)).toEqual({ + settleAfterMs: 0 + }) + }) + expect(settled).toHaveBeenCalledWith(false) + await expect(result.current.cancelAsk()).resolves.toBe(false) + expect(mocks.sendNativeChatAskAnswer).not.toHaveBeenCalled() + expect(mocks.sendNativeChatMessage).not.toHaveBeenCalled() + expect(mocks.sendRuntimePtyInput).not.toHaveBeenCalled() + expect(mocks.sendRuntimePtyInputVerified).not.toHaveBeenCalled() + expect(mocks.inferQuestionAnswered).not.toHaveBeenCalled() + }) + it('routes a non-selector answer through the pasted-text send path', () => { const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'grok')) @@ -118,57 +135,6 @@ describe('useNativeChatInteractiveSend', () => { expect(mocks.inferQuestionAnswered).toHaveBeenCalledOnce() }) - it('guards OMP groups against a changed question and fences blind retries', () => { - const original = { - ...waitingQuestion, - agentType: 'omp', - interactivePrompt: JSON.stringify(PROMPT) - } - mocks.storeState.agentStatusByPaneKey[PANE_KEY] = original - const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'omp')) - const settled = vi.fn() - act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }], settled)) - const canWrite = mocks.sendNativeChatAskAnswer.mock.calls[0]?.[3] - expect(canWrite()).toBe(true) - mocks.storeState.agentStatusByPaneKey[PANE_KEY] = { ...original, state: 'working' } - expect(canWrite()).toBe(false) - act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }], settled)) - expect(mocks.sendNativeChatAskAnswer).toHaveBeenCalledTimes(1) - expect(settled).toHaveBeenCalledWith(false) - mocks.storeState.agentStatusByPaneKey[PANE_KEY] = { - ...original, - stateStartedAt: original.stateStartedAt + 1 - } - act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }], settled)) - expect(mocks.sendNativeChatAskAnswer).toHaveBeenCalledTimes(2) - }) - - it('refuses an OMP status prompt that is already working before delivery starts', () => { - mocks.storeState.agentStatusByPaneKey[PANE_KEY] = { - ...waitingQuestion, - agentType: 'omp', - state: 'working', - interactivePrompt: JSON.stringify(PROMPT) - } - const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'omp')) - act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }])) - expect(mocks.sendNativeChatAskAnswer.mock.calls[0]?.[3]()).toBe(false) - }) - - it.each([undefined, 'not json', JSON.stringify({ questions: [] })])( - 'refuses OMP writes without canonical live prompt: %s', - (interactivePrompt) => { - mocks.storeState.agentStatusByPaneKey[PANE_KEY] = { - ...waitingQuestion, - agentType: 'omp', - interactivePrompt - } - const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'omp')) - act(() => result.current.sendAnswer(PROMPT, [{ indices: [1] }])) - expect(mocks.sendNativeChatAskAnswer.mock.calls[0]?.[3]()).toBe(false) - } - ) - it('does nothing when no option is answered', () => { const { result } = renderHook(() => useNativeChatInteractiveSend(PANE_KEY, 'pty-1', 'claude')) diff --git a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts index 226c4e78e0a4..deba72b75a7f 100644 --- a/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts +++ b/src/renderer/src/components/native-chat/use-native-chat-interactive-send.ts @@ -1,14 +1,16 @@ -import { useCallback, useLayoutEffect, useRef, useState } from 'react' +import { useCallback, useLayoutEffect, useRef } from 'react' import { useAppStore } from '../../store' import { sendRuntimePtyInput } from '@/runtime/runtime-terminal-inspection' import { sendRuntimePtyInputVerified } from '@/runtime/runtime-terminal-verified-input' import type { AgentType } from '../../../../shared/native-chat-types' import { + nativeChatAskRequiresTerminal, resolveNativeChatTranscriptAgent, shouldStepNativeChatAskAnswer } from '../../../../shared/native-chat-agent-support' import { - buildNativeChatAskAnswerKeys, + buildAskAnswerKeys, + buildCodexAskAnswerKeys, formatAskAnswer, hasAskAnswer, type AskAnswerSelection, @@ -19,9 +21,6 @@ import { sendNativeChatMessage, type NativeChatSendHandle } from './native-chat-runtime-send' -import { nativeChatAskDismissKey } from '../../../../shared/native-chat-ask' -import { nativeChatOmpPromptIdentity } from '../../../../shared/native-chat-omp-prompt-identity' -import { createOmpAnswerRetryFence } from '../../../../shared/native-chat-omp-answer-retry-fence' import { inferQuestionAnsweredFromCurrentStatus } from '../terminal-pane/agent-question-answered-inference' // ESC is the agent-TUI interrupt/cancel key over the PTY (matches how the @@ -66,7 +65,6 @@ export function useNativeChatInteractiveSend( // unmount so a detached setTimeout chain can't keep writing PTY bytes after // the view is gone / the user switched away. const inFlightRef = useRef(null) - const [attemptedOmpAsks] = useState(createOmpAnswerRetryFence) const cancelInFlight = useCallback(() => { inFlightRef.current?.cancel() inFlightRef.current = null @@ -101,13 +99,19 @@ export function useNativeChatInteractiveSend( selections: AskAnswerSelection[], onDeliverySettled?: (delivered: boolean) => void ): { settleAfterMs: number } => { + if (nativeChatAskRequiresTerminal(agent)) { + cancelInFlight() + onDeliverySettled?.(false) + return { settleAfterMs: 0 } + } if (!targetPtyId || !hasAskAnswer(prompt, selections)) { return { settleAfterMs: 0 } } // Cancel any prior in-flight answer before starting a new one. cancelInFlight() - // Selector TUIs ignore pasted labels; each agent's selector takes its own key sequence. + // Selector TUIs ignore pasted labels; Codex uses a different key sequence. const stepsAnswer = shouldStepNativeChatAskAnswer(agent) + const buildsCodexAnswer = resolveNativeChatTranscriptAgent(agent) === 'codex' // Why: pin the answered question's baseline BEFORE delivery. A late settle // callback (paced writes + remote acceptance can span seconds on SSH) must // not read the live status and mint a fresh baseline for a replacement @@ -117,29 +121,6 @@ export function useNativeChatInteractiveSend( const questionStatusBaseline = stepsAnswer ? useAppStore.getState().agentStatusByPaneKey[paneKey] : undefined - const omp = resolveNativeChatTranscriptAgent(agent) === 'omp' - const askKey = nativeChatAskDismissKey(prompt) - const baselineKey = JSON.stringify([ - targetPtyId, - askKey, - questionStatusBaseline?.turnStartedAt ?? questionStatusBaseline?.stateStartedAt - ]) - if (omp && attemptedOmpAsks.blocks(baselineKey)) { - onDeliverySettled?.(false) - return { settleAfterMs: 0 } - } - const baselineIdentity = nativeChatOmpPromptIdentity(questionStatusBaseline, prompt) - const beforeWrite = (): boolean => { - const current = useAppStore.getState().agentStatusByPaneKey[paneKey] - if ( - baselineIdentity === null || - nativeChatOmpPromptIdentity(current, prompt) !== baselineIdentity - ) { - return false - } - attemptedOmpAsks.record(baselineKey) - return true - } let settledHandle: NativeChatSendHandle | null = null const onSettled = (delivered: boolean): void => { if (settledHandle && inFlightRef.current === settledHandle) { @@ -163,9 +144,10 @@ export function useNativeChatInteractiveSend( const handle: NativeChatSendHandle = stepsAnswer ? sendNativeChatAskAnswer( targetPtyId, - buildNativeChatAskAnswerKeys(agent, prompt, selections), - onSettled, - ...(omp ? [beforeWrite] : []) + buildsCodexAnswer + ? buildCodexAskAnswerKeys(prompt, selections) + : buildAskAnswerKeys(prompt, selections), + onSettled ) : sendNativeChatMessage(targetPtyId, formatAskAnswer(prompt, selections), { onDeliverySettled: onSettled @@ -179,13 +161,16 @@ export function useNativeChatInteractiveSend( settleAfterMs: handle.settleAfterMs } }, - [paneKey, targetPtyId, agent, attemptedOmpAsks, cancelInFlight] + [paneKey, targetPtyId, agent, cancelInFlight] ) const cancelAsk = useCallback(() => { cancelInFlight() + if (nativeChatAskRequiresTerminal(agent)) { + return Promise.resolve(false) + } return sendRawVerified(ESC) - }, [cancelInFlight, sendRawVerified]) + }, [agent, cancelInFlight, sendRawVerified]) const cancel = useCallback(() => { cancelInFlight() diff --git a/src/renderer/src/i18n/locales/en.json b/src/renderer/src/i18n/locales/en.json index cdffc8fa91a2..45813e747e7f 100644 --- a/src/renderer/src/i18n/locales/en.json +++ b/src/renderer/src/i18n/locales/en.json @@ -19184,7 +19184,9 @@ "send": "Submit", "next": "Next", "skip": "Skip", - "sending": "Sending…" + "sending": "Sending…", + "terminalRequired": "Answer this OMP question in the terminal.", + "openTerminal": "Answer in terminal" }, "ask": { "awaiting": "Awaiting user input:", diff --git a/src/shared/native-chat-agent-support.test.ts b/src/shared/native-chat-agent-support.test.ts index 20e185df47a4..3da69dd80a0d 100644 --- a/src/shared/native-chat-agent-support.test.ts +++ b/src/shared/native-chat-agent-support.test.ts @@ -60,7 +60,7 @@ describe('nativeChatRequiresLocalTranscript', () => { }) describe('shouldStepNativeChatAskAnswer', () => { - it('steps the selector agents (Claude, OpenClaude, Codex, OpenCode, OMP)', () => { + it('steps the digit-commit selector agents (Claude, OpenClaude, Codex)', () => { expect(shouldStepNativeChatAskAnswer('claude')).toBe(true) expect(shouldStepNativeChatAskAnswer('openclaude')).toBe(true) // Codex 0.145's request_user_input card ignores typed labels and commits on @@ -68,11 +68,11 @@ describe('shouldStepNativeChatAskAnswer', () => { expect(shouldStepNativeChatAskAnswer('codex')).toBe(true) expect(shouldStepNativeChatAskAnswer('opencode')).toBe(true) expect(shouldStepNativeChatAskAnswer('opencode2')).toBe(true) - expect(shouldStepNativeChatAskAnswer('omp')).toBe(true) }) it('does not step other or unknown agents', () => { expect(shouldStepNativeChatAskAnswer('grok')).toBe(false) + expect(shouldStepNativeChatAskAnswer('omp')).toBe(false) expect(shouldStepNativeChatAskAnswer('cursor')).toBe(false) expect(shouldStepNativeChatAskAnswer(null)).toBe(false) expect(shouldStepNativeChatAskAnswer(undefined)).toBe(false) diff --git a/src/shared/native-chat-agent-support.ts b/src/shared/native-chat-agent-support.ts index f4909b5f5498..a3f461786742 100644 --- a/src/shared/native-chat-agent-support.ts +++ b/src/shared/native-chat-agent-support.ts @@ -33,13 +33,15 @@ export function nativeChatRequiresLocalTranscript(agent: string | null | undefin export function shouldStepNativeChatAskAnswer(agent: string | null | undefined): boolean { const transcriptAgent = resolveNativeChatTranscriptAgent(agent) return ( - transcriptAgent === 'claude' || - transcriptAgent === 'codex' || - transcriptAgent === 'opencode' || - transcriptAgent === 'omp' + transcriptAgent === 'claude' || transcriptAgent === 'codex' || transcriptAgent === 'opencode' ) } +/** OMP's configurable keys and existing checkbox state cannot be replaced through PTY input. */ +export function nativeChatAskRequiresTerminal(agent: string | null | undefined): boolean { + return resolveNativeChatTranscriptAgent(agent) === 'omp' +} + export function resolveNativeChatTranscriptAgent( agent: string | null | undefined ): NativeChatTranscriptAgent | null { diff --git a/src/shared/native-chat-ask.test.ts b/src/shared/native-chat-ask.test.ts index 979fb0cbca53..d08d63796f52 100644 --- a/src/shared/native-chat-ask.test.ts +++ b/src/shared/native-chat-ask.test.ts @@ -8,7 +8,6 @@ import { extractPendingAsk, nativeChatAskDismissKey, parseAskFromStatus, - parseAskFromToolInput, resolveNativeChatAsk } from './native-chat-ask' @@ -169,6 +168,17 @@ describe('extractPendingAsk', () => { }) describe('parseAskFromStatus', () => { + it('preserves OMP checkbox questions from live status and transcript history', () => { + const input = { + questions: [ + { id: 'q1', question: 'Pick', multi: true, options: [{ label: 'A' }, { label: 'B' }] } + ] + } + const prompt = parseAskFromStatus(JSON.stringify(input), 'ask') + expect(prompt?.questions[0]?.multiSelect).toBe(true) + expect(extractPendingAsk([message('m1', [call('ask', input)])])).toEqual(prompt) + }) + it('preserves OpenCode question envelope multiple selection on live status and replay', () => { const input = { id: 'question', @@ -224,17 +234,3 @@ describe('resolveNativeChatAsk', () => { ) }) }) - -describe('parseAskFromToolInput OMP multi flag', () => { - it('treats OMP multi: true as a multi-select question', () => { - expect( - parseAskFromToolInput('ask', { - questions: [{ id: 'checks', question: 'Q', options: [{ label: 'A' }], multi: true }] - }) - ).toEqual({ - questions: [ - { question: 'Q', header: undefined, multiSelect: true, options: [{ label: 'A' }] } - ] - }) - }) -}) diff --git a/src/shared/native-chat-ask.ts b/src/shared/native-chat-ask.ts index 24142089d43f..450ad38ecf7d 100644 --- a/src/shared/native-chat-ask.ts +++ b/src/shared/native-chat-ask.ts @@ -5,9 +5,6 @@ import type { InteractiveQuestionParser } from './native-chat-ask-types' import { isInterruptedStatusMessage, type NativeChatMessage } from './native-chat-types' -import { resolveNativeChatTranscriptAgent } from './native-chat-agent-support' -import { AGENT_TUI_CLEAR_INPUT_MAX } from './agent-tui-input-clear' -import { isOmpAskSelectionValid } from './native-chat-omp-selection' export type { AskOption, AskPrompt, AskQuestion, InteractiveQuestionParser } @@ -41,7 +38,6 @@ function parseCanonicalQuestionsInput(input: unknown): AskPrompt | null { questions.push({ question: text, header: 'header' in raw && typeof raw.header === 'string' ? raw.header : undefined, - // Why: OpenCode names the flag `multiple`, OMP's ask tool `multi`. multiSelect: 'multiSelect' in raw ? raw.multiSelect === true @@ -333,73 +329,6 @@ export function buildCodexAskAnswerKeys( return groups } -// OMP >= 18.2 uses arrows, Space to toggle, and Enter to select. -export function buildOmpAskAnswerKeys( - prompt: AskPrompt, - selections: AskAnswerSelection[] -): AskAnswerKeyGroup[] { - if (!hasAskAnswer(prompt, selections) || !isOmpAskSelectionValid(prompt, selections)) { - return [] - } - // Clear any draft that would otherwise consume the dialog keys. - const groups: AskAnswerKeyGroup[] = [{ raw: AGENT_TUI_CLEAR_INPUT_MAX }] - const moveTo = (optionCount: number, row: number): void => { - // The recommended option can start highlighted; Up clamps at the first row. - const nav = ASK_PREVIOUS_ROW.repeat(optionCount) + ASK_NEXT_ROW.repeat(row) - if (nav) { - groups.push({ raw: nav }) - } - } - - prompt.questions.forEach((q, qi) => { - const sel = selections[qi] - const other = (sel?.other ?? '').trim() - if (q.multiSelect) { - for (const i of sel?.indices ?? []) { - moveTo(q.options.length, i) - groups.push({ raw: ' ' }) - } - if (other) { - // Submitting Other advances to the next question. - moveTo(q.options.length, q.options.length) - groups.push({ raw: ASK_ENTER }, { text: other }, { raw: ASK_ENTER }) - } else { - // Right advances even when Other is highlighted. - groups.push({ raw: ASK_NEXT_TAB }) - } - } else if (other) { - moveTo(q.options.length, q.options.length) - groups.push({ raw: ASK_ENTER }, { text: answerLabels(q, sel).join(', ') }, { raw: ASK_ENTER }) - } else if ((sel?.indices.length ?? 0) > 0) { - moveTo(q.options.length, sel!.indices[0]!) - groups.push({ raw: ASK_ENTER }) - } else { - groups.push({ raw: ASK_NEXT_TAB }) - } - }) - - if (prompt.questions.length > 1 || prompt.questions.some((q) => q.multiSelect)) { - groups.push({ raw: ASK_ENTER }) - } - return groups -} - -/** Build the answer keystrokes for the agent that owns this question card. */ -export function buildNativeChatAskAnswerKeys( - agent: string | null | undefined, - prompt: AskPrompt, - selections: AskAnswerSelection[] -): AskAnswerKeyGroup[] { - const transcriptAgent = resolveNativeChatTranscriptAgent(agent) - if (transcriptAgent === 'codex') { - return buildCodexAskAnswerKeys(prompt, selections) - } - if (transcriptAgent === 'omp') { - return buildOmpAskAnswerKeys(prompt, selections) - } - return buildAskAnswerKeys(prompt, selections) -} - /** Whether any question in `selections` carries an answer worth submitting. */ export function hasAskAnswer(prompt: AskPrompt, selections: AskAnswerSelection[]): boolean { return prompt.questions.some((_, i) => isAnswered(selections[i])) diff --git a/src/shared/native-chat-omp-answer-retry-fence.test.ts b/src/shared/native-chat-omp-answer-retry-fence.test.ts deleted file mode 100644 index 7d513d8bd80a..000000000000 --- a/src/shared/native-chat-omp-answer-retry-fence.test.ts +++ /dev/null @@ -1,17 +0,0 @@ -import { describe, expect, it } from 'vitest' -import { createOmpAnswerRetryFence } from './native-chat-omp-answer-retry-fence' - -describe('OMP answer retry fence', () => { - it('retains attempted keys and fails closed when capacity is exhausted', () => { - const fence = createOmpAnswerRetryFence() - expect(fence.blocks('first')).toBe(false) - fence.record('first') - expect(fence.blocks('first')).toBe(true) - expect(fence.blocks('next')).toBe(false) - for (let i = 0; i < 200; i += 1) { - fence.record(`attempt-${i}`) - } - expect(fence.blocks('first')).toBe(true) - expect(fence.blocks('unseen')).toBe(true) - }) -}) diff --git a/src/shared/native-chat-omp-answer-retry-fence.ts b/src/shared/native-chat-omp-answer-retry-fence.ts deleted file mode 100644 index 8168417f8869..000000000000 --- a/src/shared/native-chat-omp-answer-retry-fence.ts +++ /dev/null @@ -1,17 +0,0 @@ -const OMP_ANSWER_RETRY_FENCE_CAPACITY = 128 - -export function createOmpAnswerRetryFence(): { - blocks: (key: string) => boolean - record: (key: string) => void -} { - const attempts = new Set() - return { - blocks: (key) => attempts.has(key) || attempts.size >= OMP_ANSWER_RETRY_FENCE_CAPACITY, - record: (key) => { - // Retain earlier attempts; reaching capacity must never reopen stale retries. - if (attempts.size < OMP_ANSWER_RETRY_FENCE_CAPACITY) { - attempts.add(key) - } - } - } -} diff --git a/src/shared/native-chat-omp-prompt-identity.ts b/src/shared/native-chat-omp-prompt-identity.ts deleted file mode 100644 index 26c28a51320d..000000000000 --- a/src/shared/native-chat-omp-prompt-identity.ts +++ /dev/null @@ -1,19 +0,0 @@ -import type { AgentStatusEntry } from './agent-status-types' -import { resolveNativeChatTranscriptAgent } from './native-chat-agent-support' -import { nativeChatAskDismissKey, parseAskFromStatus, type AskPrompt } from './native-chat-ask' - -export function nativeChatOmpPromptIdentity( - status: AgentStatusEntry | null | undefined, - prompt: AskPrompt -): string | null { - if ( - !status || - resolveNativeChatTranscriptAgent(status.agentType) !== 'omp' || - (status.state !== 'waiting' && status.state !== 'blocked') || - nativeChatAskDismissKey(parseAskFromStatus(status.interactivePrompt, status.toolName)) !== - nativeChatAskDismissKey(prompt) - ) { - return null - } - return JSON.stringify([status.state, status.stateStartedAt, status.turnStartedAt]) -} diff --git a/src/shared/native-chat-omp-selection.ts b/src/shared/native-chat-omp-selection.ts deleted file mode 100644 index b4ae7ab7bb37..000000000000 --- a/src/shared/native-chat-omp-selection.ts +++ /dev/null @@ -1,17 +0,0 @@ -import type { AskAnswerSelection, AskPrompt } from './native-chat-ask' - -export function isOmpAskSelectionValid( - prompt: AskPrompt, - selections: AskAnswerSelection[] -): boolean { - return prompt.questions.every((question, i) => { - const indices = selections[i]?.indices ?? [] - return ( - indices.every( - (index) => Number.isInteger(index) && index >= 0 && index < question.options.length - ) && - new Set(indices).size === indices.length && - (question.multiSelect || indices.length <= 1) - ) - }) -} From 7bbfc88e0e487e127d3c4209fbf829b5ca1ef13b Mon Sep 17 00:00:00 2001 From: Neil Date: Wed, 21 Oct 2026 12:46:09 -0700 Subject: [PATCH 7/7] test(mobile): use typed components in OMP fallback fixtures --- mobile/src/session/MobileNativeChatPromptCard.test.tsx | 5 +++-- .../session/MobileNativeChatView.prompt-presentation.test.ts | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/mobile/src/session/MobileNativeChatPromptCard.test.tsx b/mobile/src/session/MobileNativeChatPromptCard.test.tsx index 6b547ab4fc3f..2bd9bb145b66 100644 --- a/mobile/src/session/MobileNativeChatPromptCard.test.tsx +++ b/mobile/src/session/MobileNativeChatPromptCard.test.tsx @@ -1,5 +1,6 @@ import { createElement } from 'react' import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' +import { Pressable, TextInput } from 'react-native' import { describe, expect, it, vi } from 'vitest' import { MobileNativeChatPromptCard } from './MobileNativeChatPromptCard' @@ -47,11 +48,11 @@ describe('MobileNativeChatPromptCard collapse', () => { }) ) }) - const buttons = tree!.root.findAllByType('Pressable') + const buttons = tree!.root.findAllByType(Pressable) expect(buttons).toHaveLength(1) expect(buttons[0]!.props.accessibilityLabel).toBe('Answer in terminal') expect(buttons[0]!.props.disabled).toBe(!available) - expect(tree!.root.findAllByType('TextInput')).toHaveLength(0) + expect(tree!.root.findAllByType(TextInput)).toHaveLength(0) if (available) { act(() => buttons[0]!.props.onPress()) } diff --git a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts index 2bf9dd3b6227..5b8dd0425452 100644 --- a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts +++ b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts @@ -3,6 +3,7 @@ import { act, create, type ReactTestRenderer } from 'react-test-renderer' import { Pressable } from 'react-native' import { afterEach, describe, expect, it, vi } from 'vitest' import { MobileNativeChatView } from './MobileNativeChatView' +import { MobileNativeChatAsk } from './MobileNativeChatAsk' import { useMobileNativeChatPromptPresentation } from './use-mobile-native-chat-prompt-presentation' import type { MobileChatPermission } from './mobile-native-chat-permission' vi.mock('react-native', async () => { @@ -150,7 +151,7 @@ describe('terminal prompt presentation with the production view, card and compos expect(onAnswerInTerminal).toHaveBeenCalledOnce() expect(onAnswerAsk).not.toHaveBeenCalled() expect(onCancelAsk).not.toHaveBeenCalled() - expect(tree!.root.findAll((node) => node.type === 'ChatAsk')).toHaveLength(0) + expect(tree!.root.findAllByType(MobileNativeChatAsk)).toHaveLength(0) }) it('accepted Deny hides exactly that occurrence and restores Send across reconnect', async () => {