diff --git a/mobile/src/components/ActionSheetModal.tsx b/mobile/src/components/ActionSheetModal.tsx index 2c4d1d011a0c..85ecccb766f0 100644 --- a/mobile/src/components/ActionSheetModal.tsx +++ b/mobile/src/components/ActionSheetModal.tsx @@ -1,6 +1,6 @@ import { useRef, type ReactNode } from 'react' import { ActivityIndicator, View, Text, Pressable, StyleSheet } from 'react-native' -import { Edit3, Trash2, type LucideIcon } from 'lucide-react-native' +import { Check, Edit3, Trash2, type LucideIcon } from 'lucide-react-native' import { colors, radii, spacing, typography } from '../theme/mobile-theme' import { themedStyleSheet } from '../theme/themed-styles' import { useMobileColorScheme } from '../theme/use-mobile-color-scheme' @@ -14,6 +14,8 @@ export type ActionSheetAction = { destructive?: boolean disabled?: boolean hint?: string + /** Marks the choice that is current, as a trailing check. */ + checked?: boolean loading?: boolean skipAutoClose?: boolean closeBeforePress?: boolean @@ -78,6 +80,7 @@ export function ActionSheetContent({ title, message, children, actions, onClose pressed && !action.disabled && !action.loading && styles.actionPressed ]} disabled={action.disabled || action.loading} + accessibilityState={action.checked ? { checked: true } : undefined} onPress={() => { action.onPress() if (!action.skipAutoClose && onClose) { @@ -105,6 +108,8 @@ export function ActionSheetContent({ title, message, children, actions, onClose {action.loading ? ( + ) : action.checked ? ( + ) : null} diff --git a/mobile/src/components/composer-input/ComposerSendButton.tsx b/mobile/src/components/composer-input/ComposerSendButton.tsx index 81563f76854a..0732e515ec1b 100644 --- a/mobile/src/components/composer-input/ComposerSendButton.tsx +++ b/mobile/src/components/composer-input/ComposerSendButton.tsx @@ -1,19 +1,25 @@ import { ActivityIndicator, Pressable } from 'react-native' -import { ArrowUp } from 'lucide-react-native' +import { ArrowUp, type LucideIcon } from 'lucide-react-native' import { colors } from '../../theme/mobile-theme' import { useMobileColorScheme } from '../../theme/use-mobile-color-scheme' import { composerInputStyles as styles } from './composer-input-styles' export function ComposerSendButton({ onPress, + onLongPress, canSend, sending = false, - label = 'Send' + label = 'Send', + icon: Icon = ArrowUp }: { onPress: () => void + /** A hold offers more ways to send; absent, a hold is a plain press. */ + onLongPress?: () => void canSend: boolean sending?: boolean label?: string + /** What a tap does when it isn't a plain send. */ + icon?: LucideIcon }): React.JSX.Element { useMobileColorScheme() const enabled = canSend && !sending @@ -30,12 +36,13 @@ export function ComposerSendButton({ pressed && enabled && styles.pressed ]} onPress={onPress} + onLongPress={onLongPress} disabled={!enabled} > {sending ? ( ) : ( - + )} ) diff --git a/mobile/src/i18n/locales/de.json b/mobile/src/i18n/locales/de.json index 0f7b0993e1ce..e966da44e0b8 100644 --- a/mobile/src/i18n/locales/de.json +++ b/mobile/src/i18n/locales/de.json @@ -186,7 +186,11 @@ "cancelEditing": "Bearbeitung abbrechen", "placeholder": "Frage stellen, @ für Dateiverweise, / für Befehle", "saveEditedMessage": "Bearbeitete Nachricht speichern", - "sendMessage": "Nachricht senden" + "sendMessage": "Nachricht senden", + "sendQueue": "Einreihen", + "sendSteer": "Steuern", + "sendQueueHint": "Läuft nach dem aktuellen Durchgang", + "sendSteerHint": "Fließt in das ein, was der Agent gerade tut" }, "composerAttachments": { "attachedImage": "Angehängtes Bild", diff --git a/mobile/src/i18n/locales/en.json b/mobile/src/i18n/locales/en.json index b929e1987061..d7a9b6cc939d 100644 --- a/mobile/src/i18n/locales/en.json +++ b/mobile/src/i18n/locales/en.json @@ -2550,7 +2550,11 @@ "placeholder": "Ask anything, @ to mention files, / for commands", "cancelEditing": "Cancel editing", "saveEditedMessage": "Save edited message", - "sendMessage": "Send message" + "sendMessage": "Send message", + "sendQueue": "Queue", + "sendSteer": "Steer", + "sendQueueHint": "Runs after the current turn", + "sendSteerHint": "Goes into what the agent is doing now" }, "composerAttachments": { "file": "File", diff --git a/mobile/src/i18n/locales/es.json b/mobile/src/i18n/locales/es.json index d64b67288634..d8a9dac93a34 100644 --- a/mobile/src/i18n/locales/es.json +++ b/mobile/src/i18n/locales/es.json @@ -190,7 +190,11 @@ "cancelEditing": "Cancelar edición", "placeholder": "Pregunta lo que quieras, @ para referenciar archivos, / para comandos", "saveEditedMessage": "Guardar mensaje editado", - "sendMessage": "Enviar mensaje" + "sendMessage": "Enviar mensaje", + "sendQueue": "Poner en cola", + "sendSteer": "Enviar ahora", + "sendQueueHint": "Se ejecuta después del turno actual", + "sendSteerHint": "Entra en lo que el agente está haciendo ahora" }, "composerAttachments": { "attachedImage": "Imagen adjunta", diff --git a/mobile/src/i18n/locales/fr.json b/mobile/src/i18n/locales/fr.json index cf5eb032b01e..909ee0a6dd28 100644 --- a/mobile/src/i18n/locales/fr.json +++ b/mobile/src/i18n/locales/fr.json @@ -190,7 +190,11 @@ "cancelEditing": "Annuler la modification", "placeholder": "Posez votre question, @ pour référencer des fichiers, / pour les commandes", "saveEditedMessage": "Enregistrer le message modifié", - "sendMessage": "Envoyer le message" + "sendMessage": "Envoyer le message", + "sendQueue": "Mettre en file d’attente", + "sendSteer": "Envoyer maintenant", + "sendQueueHint": "S’exécute après le tour en cours", + "sendSteerHint": "S’ajoute à ce que l’agent fait en ce moment" }, "composerAttachments": { "attachedImage": "Image jointe", diff --git a/mobile/src/i18n/locales/ja.json b/mobile/src/i18n/locales/ja.json index cd1e8e96125e..e2d349f21af7 100644 --- a/mobile/src/i18n/locales/ja.json +++ b/mobile/src/i18n/locales/ja.json @@ -186,7 +186,11 @@ "cancelEditing": "編集をキャンセル", "placeholder": "何でも聞いてください。@ でファイルを参照、/ でコマンドを実行", "saveEditedMessage": "編集したメッセージを保存", - "sendMessage": "メッセージを送信" + "sendMessage": "メッセージを送信", + "sendQueue": "キューに入れる", + "sendSteer": "今すぐ送信", + "sendQueueHint": "現在のターンの後に実行します", + "sendSteerHint": "Agent が今行っている作業に加えます" }, "composerAttachments": { "attachedImage": "添付画像", diff --git a/mobile/src/i18n/locales/ko.json b/mobile/src/i18n/locales/ko.json index ec4f8c2f98a7..b6dbd60b9567 100644 --- a/mobile/src/i18n/locales/ko.json +++ b/mobile/src/i18n/locales/ko.json @@ -186,7 +186,11 @@ "cancelEditing": "편집 취소", "placeholder": "무엇이든 물어보세요. @로 파일 참조, /로 명령어 실행", "saveEditedMessage": "수정한 메시지 저장", - "sendMessage": "메시지 보내기" + "sendMessage": "메시지 보내기", + "sendQueue": "대기열에 추가", + "sendSteer": "지금 보내기", + "sendQueueHint": "현재 턴이 끝난 뒤 실행됩니다", + "sendSteerHint": "Agent가 지금 하고 있는 작업에 들어갑니다" }, "composerAttachments": { "attachedImage": "첨부된 이미지", diff --git a/mobile/src/i18n/locales/pt.json b/mobile/src/i18n/locales/pt.json index 198f5ce616db..59280b34be9e 100644 --- a/mobile/src/i18n/locales/pt.json +++ b/mobile/src/i18n/locales/pt.json @@ -190,7 +190,11 @@ "cancelEditing": "Cancelar edição", "placeholder": "Pergunte o que quiser, @ para mencionar arquivos, / para comandos", "saveEditedMessage": "Salvar mensagem editada", - "sendMessage": "Enviar mensagem" + "sendMessage": "Enviar mensagem", + "sendQueue": "Colocar na fila", + "sendSteer": "Orientar", + "sendQueueHint": "Executa depois do turno atual", + "sendSteerHint": "Entra no que o agente está fazendo agora" }, "composerAttachments": { "attachedImage": "Imagem anexada", diff --git a/mobile/src/i18n/locales/ru.json b/mobile/src/i18n/locales/ru.json index 1eaeda11b344..f8c28ee149c6 100644 --- a/mobile/src/i18n/locales/ru.json +++ b/mobile/src/i18n/locales/ru.json @@ -194,7 +194,11 @@ "cancelEditing": "Отменить редактирование", "placeholder": "Задайте вопрос; @ — файлы, / — команды", "saveEditedMessage": "Сохранить изменённое сообщение", - "sendMessage": "Отправить сообщение" + "sendMessage": "Отправить сообщение", + "sendQueue": "В очередь", + "sendSteer": "Направить", + "sendQueueHint": "Выполнится после текущего хода", + "sendSteerHint": "Попадёт в то, что агент делает сейчас" }, "composerAttachments": { "attachedImage": "Прикреплённое изображение", diff --git a/mobile/src/i18n/locales/tr.json b/mobile/src/i18n/locales/tr.json index 3816f32a5eff..a8d1f77b7ccb 100644 --- a/mobile/src/i18n/locales/tr.json +++ b/mobile/src/i18n/locales/tr.json @@ -186,7 +186,11 @@ "cancelEditing": "Düzenlemeyi iptal et", "placeholder": "Bir şey sorun; dosyalara başvurmak için @, komutlar için / kullanın", "saveEditedMessage": "Düzenlenen mesajı kaydet", - "sendMessage": "Mesaj gönder" + "sendMessage": "Mesaj gönder", + "sendQueue": "Sıraya al", + "sendSteer": "Yönlendir", + "sendQueueHint": "Geçerli tur bittikten sonra çalışır", + "sendSteerHint": "Ajanın şu anda yaptığı işe katılır" }, "composerAttachments": { "attachedImage": "Ekli görsel", diff --git a/mobile/src/i18n/locales/zh-Hant.json b/mobile/src/i18n/locales/zh-Hant.json index 6e63ce2f1518..3f81fd0932a7 100644 --- a/mobile/src/i18n/locales/zh-Hant.json +++ b/mobile/src/i18n/locales/zh-Hant.json @@ -186,7 +186,11 @@ "cancelEditing": "取消編輯", "placeholder": "隨心輸入,@ 引用檔案,/ 使用命令", "saveEditedMessage": "儲存編輯後的訊息", - "sendMessage": "傳送訊息" + "sendMessage": "傳送訊息", + "sendQueue": "加入佇列", + "sendSteer": "引導", + "sendQueueHint": "在目前回合結束後執行", + "sendSteerHint": "加入代理程式目前正在進行的工作" }, "composerAttachments": { "attachedImage": "已附加的圖片", diff --git a/mobile/src/i18n/locales/zh.json b/mobile/src/i18n/locales/zh.json index b428ee972f22..831f878fe8fd 100644 --- a/mobile/src/i18n/locales/zh.json +++ b/mobile/src/i18n/locales/zh.json @@ -186,7 +186,11 @@ "cancelEditing": "取消编辑", "placeholder": "随心输入,@ 引用文件,/ 使用命令", "saveEditedMessage": "保存编辑后的消息", - "sendMessage": "发送消息" + "sendMessage": "发送消息", + "sendQueue": "加入队列", + "sendSteer": "立即发送", + "sendQueueHint": "在当前回合结束后运行", + "sendSteerHint": "加入智能体当前正在进行的工作" }, "composerAttachments": { "attachedImage": "已添加的图片", diff --git a/mobile/src/session/MobileNativeChatOverlay.tsx b/mobile/src/session/MobileNativeChatOverlay.tsx index d4bd544bed0b..6557a78902e7 100644 --- a/mobile/src/session/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/MobileNativeChatOverlay.tsx @@ -96,7 +96,8 @@ export function MobileNativeChatOverlay({ onResume: queued.resume, sessionKey: queued.sessionKey, // Hold steering while Stop ends the turn; use the session’s single display-status decision. - steerHeld: controller.nativeChatTurnIndicator?.stopping === true + steerHeld: controller.nativeChatTurnIndicator?.stopping === true, + agentWorking: controller.nativeChatTurnActive }, backgroundTasks: controller.nativeChatBackgroundTasks }) @@ -192,6 +193,7 @@ export function MobileNativeChatOverlay({ agentWorking={controller.nativeChatTurnActive} awaitingInput={controller.nativeChatAwaitingInput} canStop={controller.nativeChatCanStop} + sendFollowUp={controller.nativeChatSendFollowUp} structuredActivityUi={controller.nativeChatStructured} turnIndicator={controller.nativeChatTurnIndicator} workingStartedAt={controller.nativeChatWorkingStartedAt} diff --git a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts index 83c009efc9ad..ce3ce1c75afa 100644 --- a/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts +++ b/mobile/src/session/MobileNativeChatView.prompt-presentation.test.ts @@ -48,6 +48,8 @@ vi.mock('lucide-react-native', () => [ 'ArrowDown', 'ArrowUp', + 'ListEnd', + 'CornerDownRight', 'ChevronDown', 'ChevronUp', 'ChevronsDownUp', diff --git a/mobile/src/session/MobileNativeChatView.tsx b/mobile/src/session/MobileNativeChatView.tsx index c233344cdd3c..1ae147fc4581 100644 --- a/mobile/src/session/MobileNativeChatView.tsx +++ b/mobile/src/session/MobileNativeChatView.tsx @@ -49,6 +49,7 @@ import { MobileNativeChatFloatingControls } from './MobileNativeChatFloatingCont import type { PendingNativeChatImage } from './native-chat/composer/mobile-native-chat-image-attachment' import { MobileNativeChatDraftComposer, + type MobileNativeChatSendProps, type MobileNativeChatStructuredComposer } from './native-chat/composer/MobileNativeChatComposer' import { MobileNativeChatPromptCard } from './native-chat/input/MobileNativeChatPromptCard' @@ -71,7 +72,7 @@ export type MobileNativeChatInputLockReason = 'disconnected' | 'waiting' type Props = ComposerTrayProps & MobileNativeChatMicProps & ChatViewProps -type ChatViewProps = { +type ChatViewProps = MobileNativeChatSendProps & { // Keep raw messages to distinguish loading from a loaded transcript filtered to empty. messages: NativeChatMessage[] folded: NativeChatMessage[] @@ -98,7 +99,6 @@ type ChatViewProps = { hasMore?: boolean olderPages?: OlderPagePhase onLoadEarlier?: () => void - onSend: (text: string) => Promise // Fence send completion by route identity after tab/view switches. sendSurfaceId: string getSendCompletionGeneration: () => number @@ -154,6 +154,7 @@ export function MobileNativeChatView({ sessionLive, agentWorking, canStop = agentWorking, + sendFollowUp, awaitingInput = null, structuredActivityUi = false, turnIndicator = null, @@ -236,8 +237,8 @@ export function MobileNativeChatView({ const { jumpToTail, recordScrollMetrics, scrollMayLoadEarlier } = tail const handleSend = useCallback( - async (text: string): Promise => { - const accepted = await onSend(text) + async (...send: Parameters): Promise => { + const accepted = await onSend(...send) if (!accepted) { return false } @@ -400,7 +401,7 @@ export function MobileNativeChatView({ onChangeText={onComposerTextChange} onSend={handleSend} sendSurfaceId={sendSurfaceId} - {...{ getSendCompletionGeneration, getComposerEditGeneration, inputRef }} + {...{ getSendCompletionGeneration, getComposerEditGeneration, inputRef, sendFollowUp }} agent={agent} sessionOptions={sessionOptions} onAttachImage={onAttachImage} diff --git a/mobile/src/session/MobileQueuedMessageCardRow.tsx b/mobile/src/session/MobileQueuedMessageCardRow.tsx index ecb16450c497..4d63e0f37ee0 100644 --- a/mobile/src/session/MobileQueuedMessageCardRow.tsx +++ b/mobile/src/session/MobileQueuedMessageCardRow.tsx @@ -27,6 +27,8 @@ type QueuedMessageCardRowProps = { busy: boolean editBlocked: boolean steerHeld: boolean + /** Steer only into a running turn; an idle agent's card reads Send. */ + agentWorking: boolean onSend: () => void onDelete: () => void onMore: () => void @@ -59,6 +61,7 @@ function QueuedMessageCardContents({ busy, editBlocked, steerHeld, + agentWorking, onSend, onDelete, onMore, @@ -68,7 +71,7 @@ function QueuedMessageCardContents({ const t = useMobileTranslation() const [expanded, setExpanded] = useState(false) const returned = card.state === 'returned' - const steers = queuedMessageCardSteers(card) + const steers = agentWorking && queuedMessageCardSteers(card) const count = card.images?.length ?? 0 return ( diff --git a/mobile/src/session/__mocks__/mobile-prompt-controller.ts b/mobile/src/session/__mocks__/mobile-prompt-controller.ts index 7e6e2b29d746..fa8411b112fb 100644 --- a/mobile/src/session/__mocks__/mobile-prompt-controller.ts +++ b/mobile/src/session/__mocks__/mobile-prompt-controller.ts @@ -156,7 +156,7 @@ function Harness(props: HarnessProps) { controller: current, onOpenFile: vi.fn(), images: { - sendNativeChat: controller.handleNativeChatSend, + sendNativeChat: (text: string) => controller.handleNativeChatSend(text), attachments: [], isAttaching: false, attachImage: async () => {}, diff --git a/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts b/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts index 97da83855b9e..58adb4bd7ddc 100644 --- a/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts +++ b/mobile/src/session/__mocks__/mobile-prompt-render-mocks.ts @@ -40,6 +40,8 @@ vi.mock('lucide-react-native', () => [ 'ArrowDown', 'ArrowUp', + 'ListEnd', + 'CornerDownRight', 'ChevronDown', 'ChevronUp', 'ChevronsDownUp', diff --git a/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx b/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx index 4c48c57f399d..bdae618c931f 100644 --- a/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx +++ b/mobile/src/session/mobile-closed-tab-dictation-lifetime.test.tsx @@ -31,6 +31,8 @@ vi.mock('react-native', async () => { }) vi.mock('lucide-react-native', () => ({ ArrowUp: 'ArrowUp', + ListEnd: 'ListEnd', + CornerDownRight: 'CornerDownRight', Check: 'Check', ChevronDown: 'ChevronDown', ChevronLeft: 'ChevronLeft', diff --git a/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx b/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx index 04ad621a2a52..375670c10c75 100644 --- a/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx +++ b/mobile/src/session/mobile-file-search-owner-cleanup.test.tsx @@ -24,6 +24,8 @@ vi.mock('react-native', async () => { }) vi.mock('lucide-react-native', () => ({ ArrowUp: 'ArrowUp', + ListEnd: 'ListEnd', + CornerDownRight: 'CornerDownRight', Check: 'Check', ChevronDown: 'ChevronDown', ChevronLeft: 'ChevronLeft', diff --git a/mobile/src/session/mobile-follow-up-preference.test.tsx b/mobile/src/session/mobile-follow-up-preference.test.tsx new file mode 100644 index 000000000000..11c8ffaa48cd --- /dev/null +++ b/mobile/src/session/mobile-follow-up-preference.test.tsx @@ -0,0 +1,295 @@ +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { afterEach, expect, it, vi } from 'vitest' +import { mobileNativeChatFollowUpPreference } from './mobile-native-chat-follow-up-preference' +import { useMobileNativeChatQueueFollowUps } from './use-mobile-native-chat-queue-follow-ups' +import { createStableLogicalRpcClient } from '../transport/stable-logical-rpc-client' +import { scopeRpcClientToExecutionHost } from '../transport/execution-host-scoped-rpc-client' +import type { RpcClient } from '../transport/rpc-client' +import type { ConnectionState, RpcResponse } from '../transport/types' + +function connection() { + let state: ConnectionState = 'connected' + let generation = 0 + const callbacks: ((event: unknown) => void)[] = [] + const states = new Set<(state: ConnectionState) => void>() + const stops = vi.fn() + const replies: ((reply: RpcResponse) => void)[] = [] + const failures: ((reason: Error) => void)[] = [] + const sendRequest = vi.fn( + () => + new Promise((resolve, reject) => { + replies.push(resolve) + failures.push(reject) + }) + ) + const client: RpcClient = { + sendRequest, + subscribe: vi.fn((_method, _params, callback) => { + callbacks.push(callback) + return stops + }), + onStateChange: (callback) => { + states.add(callback) + return () => { + states.delete(callback) + } + }, + getState: () => state, + getGeneration: () => generation, + getReconnectAttempt: () => 0, + getLastConnectedAt: () => null, + notifyForeground: () => {}, + close: () => {}, + updateTerminalSubscriptionViewport: () => {} + } + return { + client, + stops, + replies, + failures, + callbacks, + states, + emit: (event: unknown) => callbacks.at(-1)?.(event), + change: (next: ConnectionState, migrate = false) => { + state = next + if (migrate) { + generation++ + } + for (const callback of states) { + callback(state) + } + } + } +} +const reply = (queueFollowUps: boolean): RpcResponse => ({ + id: 'r', + ok: true, + result: { settings: { nativeChatQueueFollowUps: queueFollowUps } }, + _meta: { runtimeId: 'r' } +}) + +const renderers = new Set() +afterEach(() => { + act(() => { + for (const renderer of renderers) { + renderer.unmount() + } + }) + renderers.clear() +}) + +it('shares one live scalar per connection, fences late reads/events, and isolates real hook renders', async () => { + const a = connection(), + b = connection() + const renders = new Map() + const values = new Map() + function Chat({ id, client }: { id: string; client: RpcClient }) { + values.set(id, useMobileNativeChatQueueFollowUps(client, true, id)) + renders.set(id, (renders.get(id) ?? 0) + 1) + return null + } + let mounted: ReactTestRenderer | undefined + await act(async () => { + mounted = create( + <> + + + + + ) + renderers.add(mounted) + }) + await act(async () => {}) + expect(a.client.subscribe).toHaveBeenCalledTimes(1) + expect(b.client.subscribe).toHaveBeenCalledTimes(1) + const before = new Map(renders) + for (const count of [10, 100]) { + for (let index = 0; index < count; index++) { + await act(async () => a.emit({ type: 'workspaceViewChanged' })) + } + expect(renders).toEqual(before) + expect(a.client.sendRequest).toHaveBeenCalledTimes(1) + expect(a.client.subscribe).toHaveBeenCalledTimes(1) + } + await act(async () => + a.emit({ + type: 'ready', + subscriptionId: 'a', + snapshot: { nativeChatQueueFollowUps: true } + }) + ) + expect(values.get('a1')).toBe(true) + expect(values.get('a2')).toBe(true) + expect(values.get('b')).toBe(true) + expect(renders.get('b')).toBe(before.get('b')) + const after = new Map(renders) + await act(async () => a.emit({ type: 'ready', subscriptionId: 'old-no-projection' })) + await act(async () => a.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true })) + expect(renders).toEqual(after) + await act(async () => a.replies[1]!(reply(false))) + expect(values.get('a1')).toBe(true) + await act(async () => a.replies[0]!(reply(false))) + expect(values.get('a1')).toBe(true) + const beforeOff = new Map(renders) + await act(async () => a.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false })) + expect(values.get('a1')).toBe(false) + expect(values.get('a2')).toBe(false) + expect(renders.get('a1')).toBe(beforeOff.get('a1')! + 1) + expect(renders.get('a2')).toBe(beforeOff.get('a2')! + 1) + expect(renders.get('b')).toBe(before.get('b')) + const oldEvent = a.callbacks[0]! + await act(async () => a.change('disconnected')) + await act(async () => a.change('connected')) + const beforeOn = new Map(renders) + await act(async () => + a.emit({ + type: 'ready', + subscriptionId: 'a2', + snapshot: { nativeChatQueueFollowUps: true } + }) + ) + expect(values.get('a1')).toBe(true) + expect(values.get('a2')).toBe(true) + expect(renders.get('a1')).toBe(beforeOn.get('a1')! + 1) + expect(renders.get('a2')).toBe(beforeOn.get('a2')! + 1) + expect(renders.get('b')).toBe(beforeOn.get('b')) + await act(async () => + oldEvent({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + expect(values.get('a1')).toBe(true) + const previousTransportEvent = a.callbacks.at(-1)! + await act(async () => a.change('connected', true)) + expect(values.get('a1')).toBe(true) + await act(async () => + previousTransportEvent({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + expect(values.get('a1')).toBe(true) + // Old host ready uses the existing read fallback; latest read wins. + await act(async () => a.emit({ type: 'ready', subscriptionId: 'old' })) + await act(async () => a.replies.at(-1)!(reply(true))) + expect(values.get('a1')).toBe(true) + await act(async () => a.replies[2]!(reply(false))) + expect(values.get('a1')).toBe(true) + await act(async () => mounted?.unmount()) + expect(a.states.size).toBe(0) + expect(b.states.size).toBe(0) + expect(a.stops).toHaveBeenCalledTimes(3) + expect(b.stops).toHaveBeenCalledTimes(1) +}) + +it('existing phone workspace event reader ignores additive preference snapshot and events', async () => { + const { startHostWorktreeRefresh } = await import('../worktree/host-worktree-refresh') + const host = connection() + const fetchWorktrees = vi.fn(async () => {}), + fetchRepoMetadata = vi.fn(async () => {}), + syncViewSettings = vi.fn(async () => {}) + const stop = startHostWorktreeRefresh({ + client: host.client, + fetchWorktrees, + fetchRepoMetadata, + syncViewSettings, + appState: { currentState: 'active', addEventListener: () => ({ remove: () => {} }) } + }) + const counts = [ + fetchWorktrees.mock.calls.length, + fetchRepoMetadata.mock.calls.length, + syncViewSettings.mock.calls.length + ] + host.emit({ + type: 'ready', + subscriptionId: 'old', + snapshot: { nativeChatQueueFollowUps: true } + }) + host.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + expect([ + fetchWorktrees.mock.calls.length, + fetchRepoMetadata.mock.calls.length, + syncViewSettings.mock.calls.length + ]).toEqual(counts) + stop() +}) + +it('keeps known OFF across real direct/relay migrations and failed reads, while scoped hosts start Queue', async () => { + const direct = connection(), + relay = connection(), + directAgain = connection() + const logical = createStableLogicalRpcClient(direct.client, 'lan') + const values = new Map() + function Chat({ id, client }: { id: string; client: RpcClient | null }) { + values.set(id, useMobileNativeChatQueueFollowUps(client, true, id)) + return null + } + let mounted!: ReactTestRenderer + await act(async () => { + mounted = create( + <> + + + + ) + renderers.add(mounted) + }) + expect(values.get('same')).toBe(true) + expect(values.get('unknown')).toBe(true) + await act(async () => + direct.emit({ + type: 'ready', + subscriptionId: 'd', + snapshot: { nativeChatQueueFollowUps: false } + }) + ) + await act(async () => direct.replies[0]!(reply(true))) + expect(values.get('same')).toBe(false) + await act(async () => logical.migrateTo(relay.client, 'relay')) + expect(values.get('same')).toBe(false) + await act(async () => relay.failures[0]!(new Error('read failed'))) + expect(values.get('same')).toBe(false) + await act(async () => + direct.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + ) + expect(values.get('same')).toBe(false) + // Ready ON also fences an older OFF read. + await act(async () => relay.emit({ type: 'ready', subscriptionId: 'legacy' })) + await act(async () => + relay.emit({ type: 'ready', subscriptionId: 'r', snapshot: { nativeChatQueueFollowUps: true } }) + ) + await act(async () => relay.replies.at(-1)!(reply(false))) + expect(values.get('same')).toBe(true) + await act(async () => + relay.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + await act(async () => logical.migrateTo(directAgain.client, 'lan')) + expect(values.get('same')).toBe(false) + await act(async () => directAgain.failures[0]!(new Error('read failed'))) + expect(values.get('same')).toBe(false) + const sameHostEvent = directAgain.callbacks.at(-1)! + const other = scopeRpcClientToExecutionHost(logical, 'runtime:other') + await act(async () => + mounted.update( + <> + + + + ) + ) + expect(values.get('other')).toBe(true) + expect(values.get('same')).toBe(false) + await act(async () => + directAgain.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + await act(async () => + sameHostEvent({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + ) + expect(values.get('same')).toBe(true) + expect(values.get('other')).toBe(false) + await act(async () => + sameHostEvent({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + await act(async () => mounted.unmount()) + // Late callbacks after last unsubscribe cannot replace the retained same-host value. + directAgain.emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: true }) + expect(mobileNativeChatFollowUpPreference(logical).getSnapshot()).toBe(false) + expect(directAgain.states.size).toBe(1) // Only the logical transport's own state listener remains. + logical.close() + expect(directAgain.states.size).toBe(0) +}) diff --git a/mobile/src/session/mobile-native-chat-controller-contract.ts b/mobile/src/session/mobile-native-chat-controller-contract.ts index 55d0bf227c19..23af8c7c5341 100644 --- a/mobile/src/session/mobile-native-chat-controller-contract.ts +++ b/mobile/src/session/mobile-native-chat-controller-contract.ts @@ -1,4 +1,5 @@ import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items' +import type { NativeChatSendFollowUp } from '../../../src/shared/native-chat-follow-up-behavior' import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' import type { MobileSessionView } from '../storage/session-view-preferences' import type { Dispatch, MutableRefObject, SetStateAction } from 'react' @@ -13,7 +14,10 @@ import type { import type { NativeChatTurnJournal } from '../../../src/shared/native-chat-turn-membership' import type { NativeChatAwaitingInput } from '../../../src/shared/native-chat/native-chat-terminal-turn' import type { NativeChatResolvedPrompt } from '../../../src/shared/native-chat-resolution-receipt' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import type { MobileNativeChatCommandRefusalCauses } from './native-chat/use-mobile-native-chat-send-error' import type { MobileStructuredQueuedMessageControls } from './use-mobile-structured-queued-message-controls' import type { MobileStructuredBackgroundTasks } from './use-mobile-structured-background-tasks' @@ -54,6 +58,8 @@ export type MobileNativeChatController = { nativeChatActionablePromptIds: readonly string[] | undefined nativeChatCommandRefusalCauses: MobileNativeChatCommandRefusalCauses nativeChatCanStop: boolean + /** While the agent works on a host that queues: what a tap on Send does and whether holding it offers the other way; null otherwise. */ + nativeChatSendFollowUp: NativeChatSendFollowUp | null nativeChatStreamingText?: string nativeChatPermission: MobileChatPermission | null // A new prompt occurrence resets local card submission state only. @@ -97,7 +103,8 @@ export type MobileNativeChatController = { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - sentAt?: number + sentAt?: number, + intent?: MobileNativeChatSendIntent ) => Promise // Read parked TUI launch text to clear one line per Ctrl+U before pasting images. readSeededLaunchDraft: () => string | null diff --git a/mobile/src/session/mobile-native-chat-follow-up-preference.ts b/mobile/src/session/mobile-native-chat-follow-up-preference.ts new file mode 100644 index 000000000000..af701c73b3de --- /dev/null +++ b/mobile/src/session/mobile-native-chat-follow-up-preference.ts @@ -0,0 +1,111 @@ +import { nativeChatQueueFollowUpsRead } from '../transport/settings-read-operations' +import type { RpcClient } from '../transport/rpc-client' +import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat-follow-up-behavior' + +const projections = new WeakMap() + +/** The connection owns one live host preference shared by every mounted chat. */ +export function mobileNativeChatFollowUpPreference( + client: RpcClient +): MobileNativeChatFollowUpPreference { + let projection = projections.get(client) + if (!projection) { + projection = new MobileNativeChatFollowUpPreference(client) + projections.set(client, projection) + } + return projection +} + +class MobileNativeChatFollowUpPreference { + private value = nativeChatQueueFollowUps(null) + private readonly listeners = new Set<() => void>() + private stopState?: () => void + private stopStream?: () => void + private readVersion = 0 + private connectionVersion = 0 + + constructor(private readonly client: RpcClient) {} + + getSnapshot = (): boolean => this.value + + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener) + if (this.listeners.size === 1) { + this.stopState = this.client.onStateChange(() => this.connect()) + this.connect() + } + return () => { + this.listeners.delete(listener) + if (this.listeners.size === 0) { + this.connectionVersion += 1 + this.readVersion += 1 + this.stopStream?.() + this.stopStream = undefined + this.stopState?.() + this.stopState = undefined + } + } + } + + private publish(value: boolean): void { + if (value !== this.value) { + this.value = value + for (const listener of this.listeners) { + listener() + } + } + } + + private connect(): void { + const connectionVersion = ++this.connectionVersion + this.readVersion += 1 + this.stopStream?.() + this.stopStream = undefined + const generation = this.client.getGeneration?.() ?? 0 + if (this.client.getState() !== 'connected') { + return + } + const current = (): boolean => + connectionVersion === this.connectionVersion && + generation === (this.client.getGeneration?.() ?? 0) + const read = (): void => { + const version = ++this.readVersion + void nativeChatQueueFollowUpsRead + .request(this.client) + .then((response) => { + const preference = nativeChatQueueFollowUpsRead.interpret(response) + if (current() && version === this.readVersion && preference.accepted) { + this.publish(preference.value) + } + }) + .catch(() => { + // Keep this host's last answer until a ready snapshot repairs the gap. + }) + } + read() + this.stopStream = this.client.subscribe('runtime.clientEvents.subscribe', null, (payload) => { + if (!current() || !payload || typeof payload !== 'object') { + return + } + const event: { type?: unknown; queueFollowUps?: unknown; snapshot?: unknown } = payload + let queueFollowUps: unknown + if (event.type === 'nativeChatQueueFollowUpsChanged') { + queueFollowUps = event.queueFollowUps + } else if (event.type === 'ready') { + const snapshot = event.snapshot + if (snapshot && typeof snapshot === 'object' && 'nativeChatQueueFollowUps' in snapshot) { + queueFollowUps = snapshot.nativeChatQueueFollowUps + } else { + read() + return + } + } else { + return + } + if (typeof queueFollowUps === 'boolean') { + this.readVersion += 1 + this.publish(queueFollowUps) + } + }) + } +} diff --git a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx index 6b60d180a6d7..0443f893fa46 100644 --- a/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx +++ b/mobile/src/session/mobile-queued-edit-hook.test-fixture.tsx @@ -110,7 +110,9 @@ export function mobileQueuedEditHarness() { const client: RpcClient = { sendRequest, subscribe: (_method, _params, onData) => { - state.listener = onData + if (_method === 'agentSession.subscribe') { + state.listener = onData + } return () => {} }, updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/mobile-structured-agent-session-contract.ts b/mobile/src/session/mobile-structured-agent-session-contract.ts index 8be99e1f8abf..679f92f46d78 100644 --- a/mobile/src/session/mobile-structured-agent-session-contract.ts +++ b/mobile/src/session/mobile-structured-agent-session-contract.ts @@ -1,7 +1,11 @@ import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session-wire' +import type { NativeChatSendFollowUp } from '../../../src/shared/native-chat-follow-up-behavior' import type { RpcClient } from '../transport/rpc-client' import type { StructuredAgentSessionHostSupport } from './mobile-structured-agent-session-host-support' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import type { MobileNativeChatVisualSource } from './native-chat/visual/mobile-native-chat-visual-read' import type { MobileChatPermission } from './native-chat/input/mobile-native-chat-permission' import type { MobileChatQuestion } from './native-chat/input/mobile-native-chat-question' @@ -26,6 +30,8 @@ export type StructuredMobileSession = ReturnType Promise cancel: () => void receipts: ReadonlyMap diff --git a/mobile/src/session/mobile-structured-agent-session-send.ts b/mobile/src/session/mobile-structured-agent-session-send.ts index 7e67badf8121..11d886b7c93a 100644 --- a/mobile/src/session/mobile-structured-agent-session-send.ts +++ b/mobile/src/session/mobile-structured-agent-session-send.ts @@ -27,7 +27,7 @@ export async function sendMobileStructuredAgentSessionMessage(input: { attachments: readonly StructuredAgentSessionAttachment[] /** Sent only when the host advertises `agent-session.send-skills.v1`. */ skills?: readonly AgentJournalSkillRef[] - /** Sent only when the host advertises `agent-session.queued-messages.v1`. */ + /** Sent only when the host advertises `agent-session.queued-messages.v2`. */ delivery?: 'queue-if-active' /** Sent only when the host advertises `agent-session.send-selection.v1`. */ selection?: Readonly> diff --git a/mobile/src/session/mobile-structured-agent-session-working.ts b/mobile/src/session/mobile-structured-agent-session-working.ts new file mode 100644 index 000000000000..9134f849ac59 --- /dev/null +++ b/mobile/src/session/mobile-structured-agent-session-working.ts @@ -0,0 +1,16 @@ +import type { StructuredAgentSessionState } from '../../../src/shared/structured-agent-session-reducer' +import { + runningStructuredAgentSessionTurnId, + structuredAgentSessionHostSaysWorking +} from '../../../src/shared/structured-agent-session-live-turn' +import { isStructuredAgentSessionMainAgentWorking } from '../../../src/shared/structured-agent-session-main-agent-working' + +export function mobileStructuredAgentSessionWorking(state: StructuredAgentSessionState): boolean { + return structuredAgentSessionHostSaysWorking(state.working, () => + isStructuredAgentSessionMainAgentWorking( + runningStructuredAgentSessionTurnId(state), + state.submissions, + state.fence + ) + ) +} diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts index 3c0b8ef25221..86ac24156430 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.structured.test.ts @@ -1,3 +1,4 @@ +import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments' import { setMobileNativeChatDraftText, @@ -15,6 +16,8 @@ import { useMobileStructuredAgentSession } from '../../use-mobile-structured-age import { CAPABLE, SESSION_ID, + batchEvent, + queuedDraft, snapshotEvent, mutationOk, ok @@ -22,6 +25,8 @@ import { import { structuredSendResultFixture } from '../../structured-agent-send-result.test-fixture' import { findByHostType } from '../../../test-support/react-test-renderer-host-nodes' import type { RpcClient } from '../../../transport/rpc-client' +import { structuredAgentSessionHostSupport } from '../../mobile-structured-agent-session-host-support' +import { AGENT_SESSION_RUNTIME_CAPABILITIES } from '../../../../../src/shared/agent-session-runtime-capabilities' vi.mock('../../../components/MobileSwitch', () => ({ MobileSwitch: 'Switch' })) vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => ({ pickImages: async () => [] }) @@ -30,7 +35,7 @@ vi.mock('@react-native-async-storage/async-storage', () => ({ default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} } })) import { createElement, type ComponentProps } from 'react' -import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer' import { afterEach, describe, expect, it, vi } from 'vitest' import { MobileNativeChatComposer as NativeChatComposer, @@ -76,7 +81,9 @@ vi.mock('lucide-react-native', () => ({ ChevronDown: 'ChevronDown', ChevronLeft: 'ChevronLeft', ChevronRight: 'ChevronRight', + CornerDownRight: 'CornerDownRight', FileText: 'FileText', + ListEnd: 'ListEnd', Mic: 'Mic', Package: 'Package', Plus: 'Plus', @@ -111,9 +118,10 @@ const structured = ( describe('MobileNativeChatComposer on a structured chat', () => { let renderer: ReactTestRenderer | null = null - afterEach(() => { + afterEach(async () => { act(() => renderer?.unmount()) renderer = null + await activateMobileUiLocale('en') }) const draw = (props: Partial>) => @@ -292,7 +300,7 @@ describe('MobileNativeChatComposer on a structured chat', () => { agent, draftScopeKey: scope, onChangeText: drafts.setComposerText, - onSend: bridge.send, + onSend: (text: string) => bridge.send(text), sendSurfaceId: scope, getSendCompletionGeneration: () => 0, getComposerEditGeneration: () => readMobileNativeChatDraftEditGeneration(scope), @@ -388,6 +396,194 @@ describe('MobileNativeChatComposer on a structured chat', () => { expect(onAttachImage).toHaveBeenCalledTimes(1) }) + it.each([ + { + locale: 'en', + send: 'Send message', + queue: 'Queue', + steer: 'Steer', + queueHint: 'Runs after the current turn', + steerHint: 'Goes into what the agent is doing now' + }, + { + locale: 'de', + send: 'Nachricht senden', + queue: 'Einreihen', + steer: 'Steuern', + queueHint: 'Läuft nach dem aktuellen Durchgang', + steerHint: 'Fließt in das ein, was der Agent gerade tut' + } + ] as const)( + 'mid-turn Send shows what a tap does, and holding it offers the other way first-marked in $locale', + async (labels) => { + await activateMobileUiLocale(labels.locale) + const onSend = vi.fn().mockResolvedValue(true) + const choices = () => + drawers()[0]!.findAll( + (node) => String(node.type) === 'Pressable' && node.props.onPress !== undefined + ) + const text = (node: ReactTestInstance) => + node + .findAll((child) => typeof child.props.children === 'string') + .map((child) => child.props.children) + await act(async () => { + renderer = create( + draw({ value: 'hi', onSend, sendFollowUp: { action: 'steer', offersChoice: true } }) + ) + }) + const send = () => labelled(labels.steer)[0]! + expect(send().findAll((node) => String(node.type) === 'CornerDownRight')).toHaveLength(1) + await act(async () => send().props.onLongPress()) + await act(async () => drawers()[0]!.props.onClose()) + expect(onSend).not.toHaveBeenCalled() + + await act(async () => send().props.onLongPress()) + expect(choices().map(text)).toEqual([ + [labels.steer, labels.steerHint], + [labels.queue, labels.queueHint] + ]) + expect(choices().map((choice) => choice.props.accessibilityState?.checked)).toEqual([ + true, + undefined + ]) + await act(async () => choices()[1]!.props.onPress()) + expect(onSend).toHaveBeenCalledExactlyOnceWith('hi', { alternate: true }) + await act(async () => send().props.onLongPress()) + await act(async () => choices()[0]!.props.onPress()) + expect(onSend).toHaveBeenCalledTimes(2) + expect(onSend).toHaveBeenLastCalledWith('hi') + + // A waiting command queues either way: the button says so, and a hold is a tap. + await act(async () => + renderer!.update( + draw({ value: 'hi', onSend, sendFollowUp: { action: 'queue', offersChoice: false } }) + ) + ) + expect(labelled(labels.queue)[0]!.props.onLongPress).toBeUndefined() + await act(async () => renderer!.update(draw({ value: 'hi', onSend, sendFollowUp: null }))) + expect(labelled(labels.send)[0]!.props.onLongPress).toBeUndefined() + } + ) + + it('the hold choice and a tap reach the outgoing request through the real send path', async () => { + const scope = mobileNativeChatScopeKey('host', 'worktree', 'hold-choice')! + resetMobileNativeChatDraftInputsForTests() + setMobileNativeChatDraftText(scope, 'hi') + // The phone's own mapping of what this build's host advertises. + const advertised = structuredAgentSessionHostSupport(AGENT_SESSION_RUNTIME_CAPABILITIES) + expect(advertised.queuedMessages).toBe(true) + let publish: ((data: unknown) => void) | undefined + const sendRequest = vi.fn(async (method) => + method === 'agentSession.send' + ? mutationOk(structuredSendResultFixture('accepted')) + : method === 'settings.get' + ? ok({ settings: {} }) + : ok({ models: [], current: {} }) + ) + const client: RpcClient = { + sendRequest, + subscribe: (method, _p, listener) => { + if (method === 'agentSession.subscribe') { + publish = listener + } + return () => {} + }, + updateTerminalSubscriptionViewport: () => {}, + getState: () => 'connected', + getReconnectAttempt: () => 0, + getLastConnectedAt: () => null, + onStateChange: () => () => {}, + notifyForeground: () => {}, + close: () => {} + } + function Conversation() { + const session = useMobileStructuredAgentSession({ + client, + sessionId: SESSION_ID, + sourceIdentity: 'host', + enabled: true, + connected: true, + agent: 'claude', + hostSupport: { ...CAPABLE, queuedMessages: advertised.queuedMessages }, + composerScopeKey: scope, + onSendError: vi.fn() + }) + const drafts = useMobileNativeChatDrafts({ + hostId: 'host', + worktreeId: 'worktree', + tabId: 'hold-choice', + sessionId: SESSION_ID, + messages: [], + transcriptSettled: true + }) + const bridge = useMobileStructuredNativeChatSendBridge({ + ...drafts, + agent: 'claude', + sendStructured: session.sendWithOutcome, + onSendError: vi.fn() + }) + const image = useMobileNativeChatImageAttachments({ + client, + agent: 'claude', + activeHandleRef: { current: null }, + deviceTokenRef: { current: null }, + getActiveWorktreeConnectionId: async () => null, + connState: 'connected', + scopeKey: scope, + enabled: true, + structuredNativeChat: true, + showToast: vi.fn(), + onSendError: vi.fn(), + baseSend: bridge.sendWithOutcome, + readSeededLaunchDraft: () => null + }) + return draw({ + value: 'hi', + onSend: image.sendNativeChat, + sendFollowUp: session.sendFollowUp, + structured: structured() + }) + } + await act(async () => { + renderer = create(createElement(Conversation)) + }) + await act(async () => + publish?.({ + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: true, + latestTurn: null, + nextQueuedMessageId: null + } + }) + ) + const sends = () => + sendRequest.mock.calls.filter(([method]) => method === 'agentSession.send').map(([, p]) => p) + const send = () => labelled('Queue')[0]! + await act(async () => send().props.onLongPress()) + const steer = drawers()[0]!.findAll( + (node) => + String(node.type) === 'Pressable' && + node.findAll((child) => child.props.children === 'Steer').length > 0 + )[0]! + await act(async () => steer.props.onPress()) + expect(sends()).toHaveLength(1) + expect(sends()[0]).not.toHaveProperty('delivery') + + await act(async () => send().props.onPress()) + expect(sends()).toHaveLength(2) + expect(sends()[1]).toHaveProperty('delivery', 'queue-if-active') + + // A waiting command queues either way, so a hold is a tap. + const compact = queuedDraft({ + messageId: 'compact', + body: { kind: 'message', role: 'user', blocks: [], command: { name: 'compact' } } + }) + await act(async () => publish?.(batchEvent([compact]))) + expect(send().props.onLongPress).toBeUndefined() + }) + it('holds Send while a file is still uploading, and sends a stored file alone', async () => { const onSend = vi.fn().mockResolvedValue(true) const file = { id: 'f1', name: 'spec.pdf', mime: 'application/pdf', byteLength: 10 } diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts index 24dc7f816347..fb91f863a61f 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.test.ts @@ -47,6 +47,8 @@ vi.mock('react-native', async () => { vi.mock('lucide-react-native', () => ({ ArrowUp: 'ArrowUp', + ListEnd: 'ListEnd', + CornerDownRight: 'CornerDownRight', Check: 'Check', ChevronDown: 'ChevronDown', ChevronLeft: 'ChevronLeft', @@ -293,17 +295,6 @@ describe('MobileNativeChatComposer', () => { expect(onSend).not.toHaveBeenCalled() }) - it('keeps the draft when the send is rejected', async () => { - const onChangeText = vi.fn() - const onSend = vi.fn().mockResolvedValue(false) - await render(onSend, onChangeText) - - await act(async () => sendButton().props.onPress()) - - expect(onSend).toHaveBeenCalledWith(' hello ') - expect(onChangeText).not.toHaveBeenCalled() - }) - it('disables send while an attachment path is still being injected', async () => { const onSend = vi.fn().mockResolvedValue(true) await render(onSend, vi.fn(), true) @@ -682,14 +673,18 @@ describe('MobileNativeChatComposer', () => { expect(Keyboard.dismiss).toHaveBeenCalledTimes(1) }) - it('keeps the keyboard up when the send is rejected', async () => { + it('keeps the draft and keyboard when the send is rejected', async () => { // Keep the keyboard after rejection so the draft can be corrected and retried. vi.mocked(Keyboard.dismiss).mockClear() - await render(vi.fn().mockResolvedValue(false), vi.fn()) + const onSend = vi.fn().mockResolvedValue(false) + const onChangeText = vi.fn() + await render(onSend, onChangeText) await act(async () => sendButton().props.onPress()) expect(Keyboard.dismiss).not.toHaveBeenCalled() + expect(onSend).toHaveBeenCalledWith(' hello ') + expect(onChangeText).not.toHaveBeenCalled() }) it('does not dismiss a newly focused composer when an old accepted send settles', async () => { diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx index e8563787f84c..47fa0a43d22e 100644 --- a/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx +++ b/mobile/src/session/native-chat/composer/MobileNativeChatComposer.tsx @@ -1,4 +1,5 @@ import { getNativeChatAgentProfile } from '../../../../../src/shared/native-chat-agent-profiles' +import type { NativeChatSendFollowUp } from '../../../../../src/shared/native-chat-follow-up-behavior' import { recordMobileNativeChatSkillPick, useMobileNativeChatDraft @@ -33,7 +34,8 @@ import { mobileNativeChatComposerShowsStop } from './mobile-native-chat-composer import { MobileNativeChatStopButton } from '../input/MobileNativeChatStopButton' import { mobileNativeChatComposerStyles as styles } from './mobile-native-chat-composer-styles' import { composerInputStyles as inputStyles } from '../../../components/composer-input/composer-input-styles' -import { ComposerSendButton } from '../../../components/composer-input/ComposerSendButton' +import { MobileNativeChatSendButton } from './MobileNativeChatSendButton' +import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' import { MobileNativeChatComposerMic, type MobileNativeChatMicProps @@ -64,7 +66,9 @@ type Props = MobileNativeChatMicProps & { structured?: MobileNativeChatStructuredComposer | null value: string onChangeText: (text: string) => void - onSend: (text: string) => Promise + onSend: (text: string, intent?: MobileNativeChatSendIntent) => Promise + /** While the agent works on a host that queues: what a tap on Send does and whether holding it offers the other way; null otherwise. */ + sendFollowUp?: NativeChatSendFollowUp | null /** Changes whenever the route focuses a different chat composer surface. */ sendSurfaceId: string /** Reads the retained route's focus generation without forcing a screen render. */ @@ -89,6 +93,9 @@ type Props = MobileNativeChatMicProps & { stop?: { onStop?: () => void; held: boolean } | null } +/** What a chat's composer sends through, which the chat view hands down from its route. */ +export type MobileNativeChatSendProps = Pick + export function MobileNativeChatComposer({ inputRef, draftScopeKey, @@ -122,7 +129,8 @@ export function MobileNativeChatComposer({ onNeedFiles, skillDiscovery, onNeedSkills, - stop = null + stop = null, + sendFollowUp = null }: Props): React.JSX.Element { useMobileColorScheme() const t = useMobileTranslation() @@ -216,7 +224,7 @@ export function MobileNativeChatComposer({ } }, []) - const handleSend = async (): Promise => { + const handleSend = async (intent?: MobileNativeChatSendIntent): Promise => { if (!canSend || sendingRef.current) { return } @@ -228,7 +236,7 @@ export function MobileNativeChatComposer({ try { // Raw, not trimmed: the send seam owns the wire trim, and a rejection has // to hand the user back exactly what they typed (#14819). - const accepted = await onSend(value) + const accepted = await (intent ? onSend(value, intent) : onSend(value)) if ( accepted && mountedRef.current && @@ -368,7 +376,7 @@ export function MobileNativeChatComposer({ !canSend && inputStyles.sendButtonDisabled, pressed && canSend && inputStyles.pressed ]} - onPress={handleSend} + onPress={() => void handleSend()} disabled={!canSend} > @@ -376,10 +384,10 @@ export function MobileNativeChatComposer({ ) : ( - void handleSend(intent)} /> )} diff --git a/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx b/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx new file mode 100644 index 000000000000..00f102017ce0 --- /dev/null +++ b/mobile/src/session/native-chat/composer/MobileNativeChatSendButton.tsx @@ -0,0 +1,61 @@ +import { useState } from 'react' +import { CornerDownRight, ListEnd } from 'lucide-react-native' +import type { + NativeChatFollowUpBehavior, + NativeChatSendFollowUp +} from '../../../../../src/shared/native-chat-follow-up-behavior' +import { ActionSheetModal } from '../../../components/ActionSheetModal' +import { ComposerSendButton } from '../../../components/composer-input/ComposerSendButton' +import { useMobileTranslation } from '../../../i18n/use-mobile-translation' +import type { MobileNativeChatSendIntent } from '../mobile-native-chat-send' + +const FOLLOW_UP_ICON = { queue: ListEnd, steer: CornerDownRight } as const + +/** Send; while the agent works on a host that queues, it shows what a tap does, and holding it offers the other way when that would differ. */ +export function MobileNativeChatSendButton({ + canSend, + sendFollowUp, + onSend +}: { + canSend: boolean + sendFollowUp: NativeChatSendFollowUp | null + onSend: (intent?: MobileNativeChatSendIntent) => void +}): React.JSX.Element { + const t = useMobileTranslation() + const [open, setOpen] = useState(false) + const label = { + queue: t('chat.composer.sendQueue', 'Queue'), + steer: t('chat.composer.sendSteer', 'Steer') + } + const hint = { + queue: t('chat.composer.sendQueueHint', 'Runs after the current turn'), + steer: t('chat.composer.sendSteerHint', 'Goes into what the agent is doing now') + } + const action = sendFollowUp?.action + const choices: NativeChatFollowUpBehavior[] = + action === 'queue' ? ['queue', 'steer'] : ['steer', 'queue'] + return ( + <> + onSend()} + onLongPress={sendFollowUp?.offersChoice && canSend ? () => setOpen(true) : undefined} + canSend={canSend} + label={action ? label[action] : t('chat.composer.sendMessage', 'Send message')} + icon={action ? FOLLOW_UP_ICON[action] : undefined} + /> + setOpen(false)} + actions={choices.map((choice) => ({ + id: choice, + label: label[choice], + hint: hint[choice], + icon: FOLLOW_UP_ICON[choice], + checked: choice === action, + // Only the choice other than a tap's is the alternate; the send resolves it against the state then. + onPress: () => (choice === action ? onSend() : onSend({ alternate: true })) + }))} + /> + + ) +} diff --git a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts index 4dc637211c1d..488bec0fce3a 100644 --- a/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts +++ b/mobile/src/session/native-chat/composer/mobile-native-chat-draft-inputs.ts @@ -1,4 +1,5 @@ import { useCallback, useSyncExternalStore } from 'react' +import { createUuidV4 } from '../../../../../src/shared/uuid-v4' import { pickedSkillsInText } from '../../../../../src/shared/structured-agent-session-send-mutation' import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session-journal-types' import type { PendingNativeChatImage } from './mobile-native-chat-image-attachment' @@ -63,6 +64,19 @@ export function updateMobileNativeChatDraftInputs( drafts.set(destination.scope, update(readMobileNativeChatDraftInputs(destination.scope))) listeners.get(destination.scope)?.forEach((listener) => listener()) } +/** Adds uploaded images to the draft they were picked for, each under a fresh chip id. */ +export function addMobileNativeChatDraftImages( + scope: MobileNativeChatDraftDestination, + uploadedImages: Omit[] +): void { + updateMobileNativeChatDraftInputs(scope, (current) => ({ + ...current, + images: [ + ...current.images, + ...uploadedImages.map((image) => ({ ...image, id: createUuidV4() })) + ] + })) +} export function subscribeMobileNativeChatDraftInputs( scope: string | null, listener: () => void diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts index b19d162041ca..4e31d209676f 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-composer-tray.ts @@ -41,7 +41,8 @@ export function useMobileNativeChatComposerTray({ pause, onResume, sessionKey, - steerHeld + steerHeld, + agentWorking } = queued return useMemo( () => ({ @@ -66,7 +67,8 @@ export function useMobileNativeChatComposerTray({ onMove, pause, onResume, - steerHeld + steerHeld, + agentWorking }) ), composerInputRef @@ -84,7 +86,8 @@ export function useMobileNativeChatComposerTray({ onSend, pause, sessionKey, - steerHeld + steerHeld, + agentWorking ] ) } diff --git a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts index d342fdb7481c..04cb9bd932c8 100644 --- a/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts +++ b/mobile/src/session/native-chat/composer/use-mobile-native-chat-image-attachments.ts @@ -1,5 +1,5 @@ -import { createUuidV4 } from '../../../../../src/shared/uuid-v4' import { + addMobileNativeChatDraftImages, readMobileNativeChatDraftInputs, useMobileNativeChatDraftInputs, updateMobileNativeChatDraftInputs, @@ -18,6 +18,7 @@ import { } from './mobile-native-chat-image-send' import { openMobileNativeChatSendBudget, + type MobileNativeChatSendIntent, type MobileNativeChatSendOutcome } from '../mobile-native-chat-send' import { @@ -65,7 +66,8 @@ type Args = { imagePreviewUris?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - sentAt?: number + sentAt?: number, + intent?: MobileNativeChatSendIntent ) => Promise /** Structured sessions send attachments without the terminal paste path. */ readonly structuredNativeChat: boolean @@ -91,7 +93,7 @@ export type MobileNativeChatImageAttachments = { readonly removeAttachment: (id: string) => void /** Ride any pending images along with `text`, then submit; clears the sent * chips (and only those) once the send is accepted. */ - readonly sendNativeChat: (text: string) => Promise + readonly sendNativeChat: (text: string, intent?: MobileNativeChatSendIntent) => Promise } const NO_FILES: readonly PendingNativeChatFile[] = [] @@ -123,22 +125,6 @@ export function useMobileNativeChatImageAttachments({ const images = inputs.images const attachments = useMemo(() => [...images], [images]) - const addUploadedImages = useCallback( - ( - scope: MobileNativeChatDraftDestination, - uploadedImages: Omit[] - ) => { - updateMobileNativeChatDraftInputs(scope, (current) => ({ - ...current, - images: [ - ...current.images, - ...uploadedImages.map((image) => ({ ...image, id: createUuidV4() })) - ] - })) - }, - [] - ) - const { attachImage, isAttaching } = useMobileNativeChatImageUpload({ client, activeHandleRef, @@ -147,7 +133,7 @@ export function useMobileNativeChatImageAttachments({ scopeKey, structuredNativeChat, showToast, - onImagesUploaded: addUploadedImages, + onImagesUploaded: addMobileNativeChatDraftImages, onAttachSuccess, onError }) @@ -167,7 +153,7 @@ export function useMobileNativeChatImageAttachments({ ) const sendNativeChat = useCallback( - async (text: string): Promise => { + async (text: string, intent?: MobileNativeChatSendIntent): Promise => { // Serialize clear/paste/submit ownership per terminal while allowing other // tabs to send. Shared with the prompt-card writes (answer/permission), so // a card tap can't interleave into a mid-flight paste sequence either. @@ -202,12 +188,11 @@ export function useMobileNativeChatImageAttachments({ onSendError('Message not sent (disconnected)') return false } - const outcome = await baseSend( - text, - pendingImages.map((attachment) => attachment.previewUri), - deadline, - [...pendingImages, ...storedFiles] - ) + const previews = pendingImages.map((attachment) => attachment.previewUri) + const sendAttachments = [...pendingImages, ...storedFiles] + const outcome = await (intent + ? baseSend(text, previews, deadline, sendAttachments, undefined, intent) + : baseSend(text, previews, deadline, sendAttachments)) if (outcome !== 'rejected' && destination.active) { const sentIds = new Set(pendingImages.map((attachment) => attachment.id)) updateMobileNativeChatDraftInputs(destination, (current) => ({ @@ -244,7 +229,10 @@ export function useMobileNativeChatImageAttachments({ return false } } - return (await baseSend(text, undefined, deadline, undefined, sentAt)) !== 'rejected' + const outcome = await (intent + ? baseSend(text, undefined, deadline, undefined, sentAt, intent) + : baseSend(text, undefined, deadline, undefined, sentAt)) + return outcome !== 'rejected' } const handle = activeHandleRef.current if (!client || !handle || !enabled || connState !== 'connected') { diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx index aa8c5ee12aa4..f9bd6f9ee10c 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.test.tsx @@ -1,3 +1,4 @@ +import { activateMobileUiLocale } from '../../../i18n/mobile-i18n' import { mobileQueuedMessageCards, type MobileQueuedMessageCard @@ -104,10 +105,11 @@ function card( describe('MobileNativeChatQueuedMessages', () => { let renderer: ReactTestRenderer | null = null - afterEach(() => { + afterEach(async () => { vi.restoreAllMocks() act(() => renderer?.unmount()) renderer = null + await activateMobileUiLocale('en') }) async function mount( @@ -183,19 +185,13 @@ describe('MobileNativeChatQueuedMessages', () => { expect(texts(mounted)).toContain('See this') }) - it('draws a plain waiting card as one compact row with no caption', async () => { + it('draws a translated idle card as one compact row with Send and no caption', async () => { + await activateMobileUiLocale('de') const mounted = await mount({ cards: [card({ messageId: 'w', text: 'next' })] }) const rows = mounted.root.findAllByProps({ testID: 'queued-card-row' }) expect(rows).toHaveLength(1) - expect(texts(mounted)).toEqual(['Queued', 1, 'next', 'Steer']) - expect( - mounted.root.find( - (node) => - String(node.type) === 'Text' && - node.props.children === 'next' && - !node.props.accessibilityElementsHidden - ).props.numberOfLines - ).toBe(2) + expect(texts(mounted)).toEqual(['In der Warteschlange', 1, 'next', 'Senden']) + expect(mounted.root.findByProps({ children: 'next', numberOfLines: 2 })).toBeTruthy() expect(nodeTypes(rows[0]!)).toContain('ListEnd') expect(nodeTypes(rows[0]!)).not.toContain('AlertCircle') }) @@ -318,7 +314,7 @@ describe('MobileNativeChatQueuedMessages', () => { expect(texts(mounted).filter((text) => text === reason)).toHaveLength(1) }) - it('reads Steer on a waiting card and plain Send on a returned one or one whose own send failed', async () => { + it('reads Steer during work and plain Send on a returned one or one whose own send failed', async () => { const mounted = await mount({ cards: [ card({ @@ -330,6 +326,7 @@ describe('MobileNativeChatQueuedMessages', () => { card({ messageId: 'waiting' }), card({ messageId: 'returned', state: 'returned', needsAttention: true }) ], + agentWorking: true, onSend: vi.fn(async () => true) }) expect(control(mounted, 'Send this message')).toBeTruthy() @@ -392,7 +389,8 @@ describe('MobileNativeChatQueuedMessages', () => { cards: [card({ messageId: 'w' })], onSend, onDelete, - steerHeld: true + steerHeld: true, + agentWorking: true }) const steer = control(mounted, 'Submit without interrupting the model') expect(steer.props.disabled).toBe(true) @@ -478,15 +476,15 @@ describe('MobileNativeChatQueuedMessages', () => { const mounted = await mount({ cards: [card({ messageId: 'w' })], onSend, onDelete }) // Tap all actions before disabled state renders to expose same-frame duplication. await act(async () => { - control(mounted, 'Submit without interrupting the model').props.onPress() - control(mounted, 'Submit without interrupting the model').props.onPress() + control(mounted, 'Send this message').props.onPress() + control(mounted, 'Send this message').props.onPress() control(mounted, 'Delete this queued message').props.onPress() }) expect(onSend).toHaveBeenCalledTimes(1) expect(onDelete).not.toHaveBeenCalled() expect(control(mounted, 'More actions').props.disabled).toBe(true) await act(async () => answer(true)) - expect(control(mounted, 'Submit without interrupting the model').props.disabled).toBe(false) + expect(control(mounted, 'Send this message').props.disabled).toBe(false) }) describe('a paused queue', () => { @@ -557,7 +555,7 @@ describe('MobileNativeChatQueuedMessages', () => { onSend }) const labels = ['Delete every queued message', 'Resume sending the queued messages'] - const steer = 'Submit without interrupting the model' + const steer = 'Send this message' const trigger = async (action: () => void) => { counting = true await act(async () => action()) @@ -665,7 +663,11 @@ describe('MobileNativeChatQueuedMessages', () => { it('keeps Steer on its cards: one card can still go beside the paused rest', async () => { const onSend = vi.fn(async () => true) - const mounted = await mountPaused({ pause: { reason: 'stopped' }, onSend }) + const mounted = await mountPaused({ + pause: { reason: 'stopped' }, + onSend, + agentWorking: true + }) const steer = control(mounted, 'Submit without interrupting the model') expect(texts(mounted)).toContain('Steer') expect(texts(mounted)).not.toContain('Send') @@ -695,7 +697,7 @@ describe('MobileNativeChatQueuedMessages', () => { 'Queued messages', 'Delete every queued message', 'Resume sending the queued messages', - 'Submit without interrupting the model', + 'Send this message', 'Delete this queued message', 'More actions' ]) diff --git a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx index 95acd0d9f8c8..9c75a2d397cb 100644 --- a/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx +++ b/mobile/src/session/native-chat/input/MobileNativeChatQueuedMessages.tsx @@ -33,6 +33,8 @@ export type MobileNativeChatQueuedMessagesProps = { pause?: AgentSessionQueuePause | null onResume?: () => Promise steerHeld?: boolean + /** The agent is working: a steerable card's action reads Steer, otherwise Send. */ + agentWorking?: boolean } export function MobileNativeChatQueuedMessages({ @@ -45,7 +47,8 @@ export function MobileNativeChatQueuedMessages({ onMove, pause, onResume, - steerHeld = false + steerHeld = false, + agentWorking = false }: MobileNativeChatQueuedMessagesProps): React.JSX.Element | null { useMobileColorScheme() const t = useMobileTranslation() @@ -199,6 +202,7 @@ export function MobileNativeChatQueuedMessages({ busy={busyIds.has(card.messageId)} editBlocked={busyIds.has(card.messageId) || editor !== undefined || !onEdit} steerHeld={steerHeld} + agentWorking={agentWorking} onSend={() => void run(card.messageId, onSend)} onDelete={() => void run(card.messageId, onDelete)} onMore={() => setMenuFor(card.messageId)} diff --git a/mobile/src/session/native-chat/mobile-native-chat-send.ts b/mobile/src/session/native-chat/mobile-native-chat-send.ts index 3b11086de646..6044bf4b2644 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-send.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-send.ts @@ -27,6 +27,9 @@ type MobileNativeChatSendArgs = { // Unknown delivery must not be called definite failure; structured queued drafts render as cards, not transcript echoes. export type MobileNativeChatSendOutcome = 'accepted' | 'rejected' | 'unknown' | 'queued' +/** How one send goes: `alternate` does the other thing than the host's follow-up setting. */ +export type MobileNativeChatSendIntent = { alternate?: true } + export type MobileNativeChatWriteOutcome = Exclude // Bound reconnect wait so an interactive send cannot keep the composer locked indefinitely. diff --git a/mobile/src/session/use-mobile-native-chat-controller.ts b/mobile/src/session/use-mobile-native-chat-controller.ts index 1fae8abe0ffe..507e6c013cb2 100644 --- a/mobile/src/session/use-mobile-native-chat-controller.ts +++ b/mobile/src/session/use-mobile-native-chat-controller.ts @@ -261,6 +261,7 @@ export function useMobileNativeChatController(args: { nativeChatActionablePromptIds: structuredNativeChat.actionablePromptIds, nativeChatCommandRefusalCauses: structuredNativeChat.commandRefusalCauses, nativeChatCanStop: activeChatStructured ? structuredNativeChat.canStop : nativeChatAgentWorking, + nativeChatSendFollowUp: activeChatStructured ? structuredNativeChat.sendFollowUp : null, nativeChatStreamingText: terminalTurn.streamingText, ...prompts, handleNativeChatStop: activeChatStructured ? structuredNativeChat.cancel : terminalTurn.stop, diff --git a/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts b/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts index 1f0509c08271..64f302075527 100644 --- a/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts +++ b/mobile/src/session/use-mobile-native-chat-queue-follow-ups.ts @@ -1,33 +1,24 @@ -import { useEffect, useState } from 'react' -import { nativeChatQueueFollowUpsRead } from '../transport/settings-read-operations' +import { useCallback, useSyncExternalStore } from 'react' +import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat-follow-up-behavior' import type { RpcClient } from '../transport/rpc-client' +import { mobileNativeChatFollowUpPreference } from './mobile-native-chat-follow-up-preference' + +const defaultSnapshot = (): boolean => nativeChatQueueFollowUps(null) -// Read per connection and chat: the phone has no settings stream, and on is today's default. export function useMobileNativeChatQueueFollowUps( client: RpcClient | null, connected: boolean, sessionId: string | null ): boolean { - const [queueFollowUps, setQueueFollowUps] = useState(true) - useEffect(() => { - if (!client || !connected || !sessionId) { - return - } - let stale = false - void nativeChatQueueFollowUpsRead - .request(client) - .then((response) => { - const preference = nativeChatQueueFollowUpsRead.interpret(response) - if (!stale && preference.accepted) { - setQueueFollowUps(preference.value) - } - }) - .catch(() => { - // Keep the last answer when the host is unreachable. - }) - return () => { - stale = true - } - }, [client, connected, sessionId]) - return queueFollowUps + const preference = client ? mobileNativeChatFollowUpPreference(client) : null + const subscribe = useCallback( + (listener: () => void) => + preference && connected && sessionId ? preference.subscribe(listener) : () => {}, + [preference, connected, sessionId] + ) + return useSyncExternalStore( + subscribe, + preference?.getSnapshot ?? defaultSnapshot, + defaultSnapshot + ) } diff --git a/mobile/src/session/use-mobile-session-image-attachments.ts b/mobile/src/session/use-mobile-session-image-attachments.ts index f3b2ec4509d2..b71e12489447 100644 --- a/mobile/src/session/use-mobile-session-image-attachments.ts +++ b/mobile/src/session/use-mobile-session-image-attachments.ts @@ -1,7 +1,10 @@ import type { RpcClient } from '../transport/rpc-client' import type { ConnectionState } from '../transport/types' import type { MobileImageSource } from './mobile-image-source-picker' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' import { useMobileImageAttachment } from './use-mobile-image-attachment' import { @@ -35,7 +38,8 @@ type Args = { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - sentAt?: number + sentAt?: number, + intent?: MobileNativeChatSendIntent ) => Promise readonly structuredNativeChat: boolean readonly nativeChatSessionId: string | null diff --git a/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx index 6407b0d17051..e7a5dbdd03a4 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-background-tasks.test.tsx @@ -61,7 +61,9 @@ describe('mobile structured session background tasks', () => { const client: RpcClient = { sendRequest, subscribe: (_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }, updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx index 90c6b52e426c..0d7bf1023183 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-newer-approval-send.test.tsx @@ -30,7 +30,9 @@ const sendRequest = vi.fn() const client: RpcClient = { sendRequest, subscribe: vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }), updateTerminalSubscriptionViewport: () => {}, @@ -82,7 +84,7 @@ async function sentDelivery(items: AgentJournalRenderItem[]): Promise { }) await vi.waitFor(() => expect(listener).toEqual(expect.any(Function))) const event = snapshotEvent({ items }) - act(() => listener?.(event)) + await act(async () => listener?.(event)) await act(async () => { await hook!.sendWithOutcome('carry on') }) @@ -98,7 +100,9 @@ beforeEach(() => { ? mutationOk({ clientMessageId: 'client-1' }) : method === 'agentSession.options' ? ok({ models: [], current: {} }) - : ok({}) + : method === 'settings.get' + ? ok({ settings: { nativeChatQueueFollowUps: true } }) + : ok({}) ) }) @@ -136,14 +140,16 @@ async function afterStop(items: AgentJournalRenderItem[]): Promise { ? new Promise(() => undefined) : method === 'agentSession.options' ? ok({ models: [], current: {} }) - : ok({}) + : method === 'settings.get' + ? ok({ settings: { nativeChatQueueFollowUps: true } }) + : ok({}) ) act(() => { renderer = create(createElement(Harness)) }) await vi.waitFor(() => expect(listener).toEqual(expect.any(Function))) const event = snapshotEvent({ items: [...items, RUNNING_TURN] }) - act(() => listener?.(event)) + await act(async () => listener?.(event)) act(() => hook?.cancel()) expect(hook?.turnIndicator.stopping).toBe(true) return hook?.turnIndicator.afterStop diff --git a/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx index a7a5bad603cc..38d890594e5b 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-queued.test.tsx @@ -43,6 +43,10 @@ const asyncStorage = vi.hoisted(() => ({ vi.mock('@react-native-async-storage/async-storage', () => ({ default: asyncStorage })) function normalReply(method: string): RpcResponse { + // Queue is the default; explicit OFF is covered below. + if (method === 'settings.get') { + return ok({ settings: { nativeChatQueueFollowUps: true } }) + } if (method === 'agentSession.options') { return ok({ models: [], current: {} }) } @@ -61,12 +65,18 @@ describe('mobile structured queued messages', () => { let renderer: ReactTestRenderer | null = null let hook: ReturnType | null = null let listener: ((value: unknown) => void) | null = null + let preferenceListener: ((value: unknown) => void) | null = null let stored: Map const onSendError = vi.fn() const appendText = vi.fn((_text: string) => true) const sendRequest = vi.fn() const subscribe = vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } + if (_method === 'runtime.clientEvents.subscribe') { + preferenceListener = onData + } return vi.fn() }) const client: RpcClient = { @@ -121,6 +131,7 @@ describe('mobile structured queued messages', () => { renderer = null hook = null listener = null + preferenceListener = null } function calls(method: string) { @@ -249,7 +260,7 @@ describe('mobile structured queued messages', () => { expect(asyncStorage.setItem).not.toHaveBeenCalled() }) - it("sends straight into the turn when the host's Queue follow-ups is off, as the desktop does", async () => { + it("sends straight into the turn when the host's setting is Steer, as the desktop does", async () => { sendRequest.mockImplementation(async (method) => { if (method === 'settings.get') { return ok({ settings: { nativeChatQueueFollowUps: false } }) @@ -273,6 +284,105 @@ describe('mobile structured queued messages', () => { expect('delivery' in requestOf('agentSession.send').params).toBe(false) }) + it.each(['steer', 'queue'] as const)( + 'pre-turn host Working honors default and explicit choice (%s)', + async (behavior) => { + sendRequest.mockImplementation(async (method) => { + if (method === 'settings.get') { + return ok({ settings: { nativeChatQueueFollowUps: behavior === 'queue' } }) + } + if (method === 'agentSession.send') { + return mutationOk({ + clientMessageId: 'client-1', + submission: acceptedSubmission('client-1') + }) + } + return normalReply(method) + }) + await mountSession(CAPABLE, { + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: true, + latestTurn: null, + nextQueuedMessageId: null + } + }) + await act(async () => {}) + expect(hook!.isWorking).toBe(true) + expect(hook!.sendFollowUp).toEqual({ action: behavior, offersChoice: true }) + for (const alternate of [false, true]) { + await act(async () => { + await hook!.sendWithOutcome( + 'pre-turn', + undefined, + undefined, + undefined, + [], + alternate ? { alternate: true } : undefined + ) + }) + expect(requestOf('agentSession.send', alternate ? 1 : 0).params.delivery).toBe( + (behavior === 'queue') !== alternate ? 'queue-if-active' : undefined + ) + } + // A sheet opened during work sends against the current idle state. + await act(async () => + listener?.({ + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: false, + latestTurn: null, + nextQueuedMessageId: null + } + }) + ) + await act(async () => { + await hook!.sendWithOutcome('now idle', undefined, undefined, undefined, [], { + alternate: true + }) + }) + expect(requestOf('agentSession.send', 2).params.delivery).toBe( + behavior === 'queue' ? 'queue-if-active' : undefined + ) + } + ) + + it('sends using a changed host preference in the same connected chat', async () => { + sendRequest.mockImplementation(async (method) => + method === 'agentSession.send' + ? mutationOk({ clientMessageId: 'client-1', submission: acceptedSubmission('client-1') }) + : normalReply(method) + ) + await mountSession(CAPABLE, { + ...snapshotEvent(), + page: { + ...snapshotEvent().page, + working: true, + latestTurn: null, + nextQueuedMessageId: null + } + }) + expect(hook!.sendFollowUp).toEqual({ action: 'queue', offersChoice: true }) + await act(async () => { + await hook!.sendWithOutcome('queue by default') + }) + expect(requestOf('agentSession.send').params.delivery).toBe('queue-if-active') + await act(async () => + preferenceListener?.({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }) + ) + expect(hook!.sendFollowUp).toEqual({ action: 'steer', offersChoice: true }) + await act(async () => { + await hook!.sendWithOutcome('now steer') + }) + expect(requestOf('agentSession.send', 1).params.delivery).toBeUndefined() + expect( + subscribe.mock.calls.filter(([method]) => method === 'agentSession.subscribe') + ).toHaveLength(1) + expect(calls('settings.get')).toHaveLength(1) + }) + it('keeps today’s request exactly against an incapable host', async () => { sendRequest.mockImplementation(async (method) => { if (method === 'agentSession.send') { diff --git a/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx index b7e53dfd5884..e81bd5fb7909 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-read-failure.test.tsx @@ -22,7 +22,9 @@ const sendRequest = vi.fn() const client: RpcClient = { sendRequest, subscribe: vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }), updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx index 892aed434d64..fcae4a545470 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-retry-rows.test.tsx @@ -57,7 +57,9 @@ it('draws one row for a run of provider retries, with what failed on its second _meta: { runtimeId: 'runtime-1' } }), subscribe: (_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return () => {} }, updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx b/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx index a80642c23db6..a2001f9113b9 100644 --- a/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session-send.test.tsx @@ -74,7 +74,9 @@ describe('mobile structured send actions', () => { const onSendError = vi.fn() const sendRequest = vi.fn() const subscribe = vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }) const client: RpcClient = { diff --git a/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx b/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx index fe2dc61a6a0b..380295ac1ae0 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session.cut-turn-notice.test.tsx @@ -71,7 +71,9 @@ describe('useMobileStructuredAgentSession transcript', () => { _meta: { runtimeId: 'runtime-1' } })), subscribe: vi.fn((_method: string, _params: unknown, onData: (value: unknown) => void) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return () => {} }) } diff --git a/mobile/src/session/use-mobile-structured-agent-session.test.tsx b/mobile/src/session/use-mobile-structured-agent-session.test.tsx index d69a78ed2dfd..ffac946981d9 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.test.tsx +++ b/mobile/src/session/use-mobile-structured-agent-session.test.tsx @@ -195,10 +195,14 @@ describe('useMobileStructuredAgentSession', () => { let listener: ((value: unknown) => void) | null = null const onSendError = vi.fn() const unsubscribe = vi.fn() + const unsubscribePreference = vi.fn() const sendRequest = vi.fn(defaultSendRequest) const subscribe = vi.fn((_method: string, _params: unknown, onData: (value: unknown) => void) => { - listener = onData - return unsubscribe + if (_method === 'agentSession.subscribe') { + listener = onData + return unsubscribe + } + return unsubscribePreference }) const client: RpcClient = { sendRequest, @@ -337,13 +341,17 @@ describe('useMobileStructuredAgentSession', () => { sendRequest.mock.calls.filter(([method]) => method === 'agentSession.hold') ).toHaveLength(1) ) - await vi.waitFor(() => expect(subscribe).toHaveBeenCalledTimes(1)) + await vi.waitFor(() => + expect( + subscribe.mock.calls.filter(([method]) => method === 'agentSession.subscribe') + ).toHaveLength(1) + ) // Reconnect must acquire the connection-scoped hold before replaying the stream. await act(async () => { renderer?.update(createElement(Harness, { connected: false })) }) - expect(unsubscribe).toHaveBeenCalledTimes(1) + expect([unsubscribe.mock.calls.length, unsubscribePreference.mock.calls.length]).toEqual([1, 1]) await act(async () => { renderer?.update(createElement(Harness, { connected: true })) }) @@ -353,19 +361,28 @@ describe('useMobileStructuredAgentSession', () => { sendRequest.mock.calls.filter(([method]) => method === 'agentSession.hold') ).toHaveLength(2) ) - await vi.waitFor(() => expect(subscribe).toHaveBeenCalledTimes(2)) + await vi.waitFor(() => + expect( + subscribe.mock.calls.filter(([method]) => method === 'agentSession.subscribe') + ).toHaveLength(2) + ) const holdOrders = sendRequest.mock.calls .map((call, index) => call[0] === 'agentSession.hold' ? sendRequest.mock.invocationCallOrder[index] : null ) .filter((order): order is number => order !== null) - const subscribeOrders = subscribe.mock.invocationCallOrder + const subscribeOrders = subscribe.mock.calls.flatMap(([method], index) => + method === 'agentSession.subscribe' ? [subscribe.mock.invocationCallOrder[index]] : [] + ) const secondHoldOrder = holdOrders[1] const secondSubscribeOrder = subscribeOrders[1] if (secondHoldOrder === undefined || secondSubscribeOrder === undefined) { throw new Error('reconnect calls were not recorded') } expect(secondHoldOrder).toBeLessThan(secondSubscribeOrder) + await act(async () => renderer?.unmount()) + renderer = null + expect([unsubscribe.mock.calls.length, unsubscribePreference.mock.calls.length]).toEqual([2, 2]) }) it('sends with the shared structured mutation envelope after the stream fence lands', async () => { diff --git a/mobile/src/session/use-mobile-structured-agent-session.ts b/mobile/src/session/use-mobile-structured-agent-session.ts index ba86e0a6a91d..c3e58b25dd6a 100644 --- a/mobile/src/session/use-mobile-structured-agent-session.ts +++ b/mobile/src/session/use-mobile-structured-agent-session.ts @@ -9,11 +9,10 @@ import { import { withNativeChatCutTurnNotices } from '../../../src/shared/native-chat/transcript/native-chat-cut-turn-notice' import { agentSessionTranscriptRows } from '../../../src/shared/agent-session-context-clear' import { tuiAgentDisplayName } from '../../../src/shared/tui-agent-display-names' -import { isStructuredAgentSessionMainAgentWorking } from '../../../src/shared/structured-agent-session-main-agent-working' +import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' import { isFinalAgentSessionReadRefusal } from '../../../src/shared/structured-agent-session-read-refusal' import { runningStructuredAgentSessionTurnId, - structuredAgentSessionHostSaysWorking, structuredAgentSessionQueueSendsNext } from '../../../src/shared/structured-agent-session-live-turn' import { @@ -152,9 +151,7 @@ export function useMobileStructuredAgentSession( { ...state, items: transcriptItems }, turnId ) - const isWorking = structuredAgentSessionHostSaysWorking(state.working, () => - isStructuredAgentSessionMainAgentWorking(turnId, state.submissions, state.fence) - ) + const isWorking = mobileStructuredAgentSessionWorking(state) const queueSendsNext = structuredAgentSessionQueueSendsNext(state.nextQueuedMessageId, isWorking) const backgroundTasks = useMobileStructuredBackgroundTasks({ sessionKey, @@ -183,7 +180,8 @@ export function useMobileStructuredAgentSession( hostStopping, stopPressed: stopPress.pressed, queueCapable, - queueFollowUps + queueFollowUps, + queueSendsNext }) const { stopping } = turnIndicator const sendWithOutcome = useMobileStructuredSendWithOutcome({ @@ -289,6 +287,7 @@ export function useMobileStructuredAgentSession( }, isWorking: isWorking || queueSendsNext, canStop, + sendFollowUp: turnIndicator.sendFollowUp ?? null, turnId, turnIndicator, ...turnTiming, diff --git a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts b/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts index e4ed7a921273..b9764d890355 100644 --- a/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts +++ b/mobile/src/session/use-mobile-structured-native-chat-send-bridge.ts @@ -2,7 +2,10 @@ import { useCallback } from 'react' import type { StructuredAgentId } from '../../../src/shared/agent-session-provider-handle' import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session-wire' import { isStructuredAgentSessionComposerCommand } from '../../../src/shared/structured-agent-session-composer' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import type { MobileNativeChatSendOrigin } from './native-chat/mobile-native-chat-pending-echo' import type { StructuredMobileSendAttachment } from './use-mobile-structured-send-with-outcome' import type { AgentJournalSkillRef } from '../../../src/shared/agent-session-journal-types' @@ -19,7 +22,8 @@ export function useMobileStructuredNativeChatSendBridge(args: { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - skills?: readonly AgentJournalSkillRef[] + skills?: readonly AgentJournalSkillRef[], + intent?: MobileNativeChatSendIntent ) => Promise captureSendOrigin: (text: string) => MobileNativeChatSendOrigin | null clearDraftForSend: (origin: MobileNativeChatSendOrigin, text: string) => void @@ -31,7 +35,9 @@ export function useMobileStructuredNativeChatSendBridge(args: { text: string, images?: string[], deadline?: number, - attachments?: readonly StructuredMobileSendAttachment[] + attachments?: readonly StructuredMobileSendAttachment[], + sentAt?: number, + intent?: MobileNativeChatSendIntent ) => Promise } { const { @@ -48,7 +54,9 @@ export function useMobileStructuredNativeChatSendBridge(args: { text: string, images?: string[], deadline?: number, - attachments?: readonly StructuredMobileSendAttachment[] + attachments?: readonly StructuredMobileSendAttachment[], + _sentAt?: number, + intent?: MobileNativeChatSendIntent ): Promise => { const origin = captureSendOrigin(text.trimEnd()) if (!origin) { @@ -58,7 +66,9 @@ export function useMobileStructuredNativeChatSendBridge(args: { const isHostCommand = isStructuredAgentSessionComposerCommand(text, agent, sessionCommands) const skills = readMobileNativeChatPickedSkills(origin.draftKey) clearDraftForSend(origin, text) - const outcome = await sendStructured(text, images, deadline, attachments, skills) + const outcome = await (intent + ? sendStructured(text, images, deadline, attachments, skills, intent) + : sendStructured(text, images, deadline, attachments, skills)) // Accepted messages remain host-owned; restore commands whose reply was lost. if (outcome === 'rejected' || (outcome === 'unknown' && isHostCommand)) { restoreRejectedDraft(origin, text) diff --git a/mobile/src/session/use-mobile-structured-send-with-outcome.ts b/mobile/src/session/use-mobile-structured-send-with-outcome.ts index 0de5ab7453fe..6f4ce056d0a4 100644 --- a/mobile/src/session/use-mobile-structured-send-with-outcome.ts +++ b/mobile/src/session/use-mobile-structured-send-with-outcome.ts @@ -2,6 +2,7 @@ import { selectAgentSessionCurrentRequests } from '../../../src/shared/agent-ses import { useCallback } from 'react' import { runningStructuredAgentSessionTurnId } from '../../../src/shared/structured-agent-session-live-turn' +import { mobileStructuredAgentSessionWorking } from './mobile-structured-agent-session-working' import { structuredSessionBackgroundTasksView } from '../../../src/shared/structured-session-background-tasks-view' import { agentSessionVisibleFailureFacts } from '../../../src/shared/agent-session-visible-failures' import { tuiAgentDisplayName } from '../../../src/shared/tui-agent-display-names' @@ -17,9 +18,15 @@ import { MAX_SKILL_REFS } from '../../../src/shared/rpc-contract/structured-agen import type { StructuredAgentSessionComposerOptions } from '../../../src/shared/structured-agent-session-composer' import type { AgentSessionSlashCommand } from '../../../src/shared/agent-session-wire' import type { StructuredAgentSessionState } from '../../../src/shared/structured-agent-session-reducer' -import { structuredAgentSessionQueueEnabled } from '../../../src/shared/structured-agent-session-queued-cards' +import { + structuredAgentSessionFollowUpsQueue, + structuredAgentSessionQueueEnabled +} from '../../../src/shared/structured-agent-session-queued-cards' import type { RpcClient } from '../transport/rpc-client' -import type { MobileNativeChatSendOutcome } from './native-chat/mobile-native-chat-send' +import type { + MobileNativeChatSendIntent, + MobileNativeChatSendOutcome +} from './native-chat/mobile-native-chat-send' import { dispatchMobileStructuredCommand } from './mobile-structured-composer-command' import type { MobileNativeChatSendErrorReporter } from './native-chat/use-mobile-native-chat-send-error' import { sendMobileStructuredAgentSessionMessage } from './mobile-structured-agent-session-send' @@ -33,15 +40,20 @@ import { actionableStructuredQuestion } from './mobile-structured-actionable-prompt' +/** The desktop's rule: the alternate flips the setting first, then the queue's own rules decide. */ export function mobileStructuredSendQueues( queueCapable: boolean, queueFollowUps: boolean, - state: Pick + state: Pick, + send: { alternate?: boolean; isWorking: boolean; stopping: boolean } = { + isWorking: false, + stopping: false + } ): boolean { return ( queueCapable && structuredAgentSessionQueueEnabled( - queueFollowUps, + structuredAgentSessionFollowUpsQueue(queueFollowUps, send), state, selectAgentSessionCurrentRequests(state) ) @@ -86,7 +98,8 @@ export function useMobileStructuredSendWithOutcome(args: { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - skills?: readonly AgentJournalSkillRef[] + skills?: readonly AgentJournalSkillRef[], + intent?: MobileNativeChatSendIntent ) => Promise { const { accept, @@ -116,7 +129,8 @@ export function useMobileStructuredSendWithOutcome(args: { images?: string[], deadline?: number, attachments?: readonly StructuredMobileSendAttachment[], - pickedSkills?: readonly AgentJournalSkillRef[] + pickedSkills?: readonly AgentJournalSkillRef[], + intent?: MobileNativeChatSendIntent ): Promise => { const currentFence = stateRef.current.fence if (!client || !sessionId || !enabled || currentFence === null) { @@ -148,7 +162,7 @@ export function useMobileStructuredSendWithOutcome(args: { const turnId = runningStructuredAgentSessionTurnId(state) const tasks = structuredSessionBackgroundTasksView(state.backgroundTasks, turnId) return { - working: turnId !== null || queueSendsNext, + working: mobileStructuredAgentSessionWorking(state) || queueSendsNext, prompt: Boolean( actionableStructuredApproval(state) || actionableStructuredQuestion(state) ), @@ -207,7 +221,12 @@ export function useMobileStructuredSendWithOutcome(args: { text: wireText, attachments: imageAttachments, skills, - ...(mobileStructuredSendQueues(queueCapable, queueFollowUps, stateRef.current) + // Resolved from the chat as it is now: a hold-menu choice made mid-turn may land after it. + ...(mobileStructuredSendQueues(queueCapable, queueFollowUps, stateRef.current, { + alternate: intent?.alternate, + isWorking: mobileStructuredAgentSessionWorking(stateRef.current) || queueSendsNext, + stopping + }) ? { delivery: 'queue-if-active' as const } : {}), ...captured, diff --git a/mobile/src/session/use-mobile-structured-sends.test.tsx b/mobile/src/session/use-mobile-structured-sends.test.tsx index 781ed76c7a7f..dde7e107eaa4 100644 --- a/mobile/src/session/use-mobile-structured-sends.test.tsx +++ b/mobile/src/session/use-mobile-structured-sends.test.tsx @@ -64,7 +64,9 @@ describe('a structured send in the open chat', () => { const client: RpcClient = { sendRequest, subscribe: vi.fn((_method, _params, onData) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }), updateTerminalSubscriptionViewport: () => {}, diff --git a/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx b/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx index b0822655eb07..c17a6c405958 100644 --- a/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx +++ b/mobile/src/session/use-mobile-structured-turn-indicator.test.tsx @@ -44,7 +44,9 @@ describe('useMobileStructuredAgentSession turn indicator', () => { _meta: { runtimeId: 'r1' } })) const subscribe = vi.fn((_method: string, _params: unknown, onData: (value: unknown) => void) => { - listener = onData + if (_method === 'agentSession.subscribe') { + listener = onData + } return vi.fn() }) const client: RpcClient = { diff --git a/mobile/src/session/use-mobile-structured-turn-indicator.ts b/mobile/src/session/use-mobile-structured-turn-indicator.ts index 272209db5e89..f1c9d7f808ba 100644 --- a/mobile/src/session/use-mobile-structured-turn-indicator.ts +++ b/mobile/src/session/use-mobile-structured-turn-indicator.ts @@ -5,6 +5,10 @@ import { isStructuredAgentSessionThinking } from '../../../src/shared/structured import { selectStructuredAgentTurnActivity } from '../../../src/shared/native-chat/transcript/native-chat-turn-activity' import { agentStopDisplayStatus } from '../../../src/shared/agent-stop-display-status' import { mobileStructuredSendQueues } from './use-mobile-structured-send-with-outcome' +import { + nativeChatSendFollowUp, + type NativeChatSendFollowUp +} from '../../../src/shared/native-chat-follow-up-behavior' export function useMobileStructuredTurnIndicator(input: { state: StructuredAgentSessionState @@ -16,7 +20,12 @@ export function useMobileStructuredTurnIndicator(input: { stopPressed: boolean queueCapable: boolean queueFollowUps: boolean -}): NativeChatLiveTurnIndicator & { stopping: boolean } { + /** The send's own working test counts a queued card about to send. */ + queueSendsNext: boolean +}): NativeChatLiveTurnIndicator & { + stopping: boolean + sendFollowUp?: NativeChatSendFollowUp +} { const { state, turnId, hostStopping, stopPressed, queueCapable, queueFollowUps } = input const activityText = useMemo( () => selectStructuredAgentTurnActivity(state.items, turnId, state.activity)?.text ?? null, @@ -31,14 +40,38 @@ export function useMobileStructuredTurnIndicator(input: { ? ('queue' as const) : ('send' as const) : undefined + const isWorking = input.isWorking || input.queueSendsNext + const sendFollowUp = + queueCapable && working && !stopping + ? nativeChatSendFollowUp((alternate) => + mobileStructuredSendQueues(queueCapable, queueFollowUps, state, { + alternate, + isWorking, + stopping + }) + ) + : null + const followUpAction = sendFollowUp?.action + const followUpOffersChoice = sendFollowUp?.offersChoice === true return useMemo( () => ({ thinking, activityText, stopping, stopRequestInFlight, + ...(followUpAction + ? { sendFollowUp: { action: followUpAction, offersChoice: followUpOffersChoice } } + : {}), ...(afterStop ? { afterStop } : {}) }), - [thinking, activityText, stopping, stopRequestInFlight, afterStop] + [ + thinking, + activityText, + stopping, + stopRequestInFlight, + followUpAction, + followUpOffersChoice, + afterStop + ] ) } diff --git a/mobile/src/transport/settings-read-operations.test.ts b/mobile/src/transport/settings-read-operations.test.ts index b0731eefb0de..b0e8a9ec02f4 100644 --- a/mobile/src/transport/settings-read-operations.test.ts +++ b/mobile/src/transport/settings-read-operations.test.ts @@ -6,6 +6,7 @@ import { markRpcDeliveryUnknown, isRpcDeliveryUnknown } from './rpc-delivery-amb import { LogicalClientCutoverError, isLogicalClientCutoverError } from './stable-logical-rpc-client' import { settingsRead, + nativeChatQueueFollowUpsRead, optionalSettingsRead, botOverridesRead, newTabSettingsRead, @@ -50,6 +51,29 @@ async function drain() { } describe('settings historical acceptance', () => { + it.each([ + undefined, + null, + {}, + { nativeChatQueueFollowUps: true }, + { nativeChatQueueFollowUps: false }, + { nativeChatQueueFollowUps: 'false' } + ])( + 'reads the existing queue boolean without treating false as missing (%j)', + async (settings) => { + const response = await nativeChatQueueFollowUpsRead.request(replyWith(success({ settings }))) + expect(nativeChatQueueFollowUpsRead.interpret(response)).toEqual({ + accepted: true, + value: settings?.nativeChatQueueFollowUps !== false + }) + expect( + nativeChatQueueFollowUpsRead.interpret( + await nativeChatQueueFollowUpsRead.request(replyWith(refusal())) + ) + ).toEqual({ accepted: false }) + } + ) + it('distinguishes a skipped refusal from an accepted absent settings member', async () => { const skipped = await settingsRead.request(replyWith(refusal())) const missing = await settingsRead.request(replyWith(success({}))) diff --git a/mobile/src/transport/settings-read-operations.ts b/mobile/src/transport/settings-read-operations.ts index 6f43c2263423..c51c91470c7e 100644 --- a/mobile/src/transport/settings-read-operations.ts +++ b/mobile/src/transport/settings-read-operations.ts @@ -2,6 +2,7 @@ import { bindDeferredRpcOperation, defineRpcOperation } from './rpc-operation' import type { RpcCompatibleReader } from './rpc-operation-contract' import { normalizeSourceControlGroupOrder } from '../../../src/shared/source-control-group-order' import type { SourceControlGroupOrder } from '../../../src/shared/ui-chrome-types' +import { nativeChatQueueFollowUps } from '../../../src/shared/native-chat-follow-up-behavior' function settingsMember(raw: unknown): unknown { const boxed: { readonly settings?: unknown } | null | undefined = raw == null ? raw : Object(raw) @@ -117,13 +118,29 @@ export const terminalCopyTrimsGutterRead = bindDeferredRpcOperation( }) ) +// Absent settings default ON; delivery still depends on host capability. +const followUpBehaviorReader: RpcCompatibleReader = ( + raw +) => { + const settings = raw == null ? undefined : settingsMember(raw) + return { + compatible: true, + variant: 'follow-up-behavior', + value: nativeChatQueueFollowUps({ + nativeChatQueueFollowUps: + settings == null ? undefined : settingsField(settings, 'nativeChatQueueFollowUps') + }), + salvage: { droppedPaths: [], droppedCount: 0 } + } +} + export const nativeChatQueueFollowUpsRead = bindDeferredRpcOperation( defineRpcOperation({ - name: 'settings.native-chat-queue-follow-ups-or-skip', + name: 'settings.native-chat-follow-up-behavior-or-skip', method: 'settings.get', acceptance: 'success-result-or-skip', barrier: 'after-caller-barrier', - read: onByDefaultSettingReader('nativeChatQueueFollowUps', 'queue-follow-ups') + read: followUpBehaviorReader }) ) diff --git a/src/main/persistence/applying-settings/persistence-settings-ui-defaults.test.ts b/src/main/persistence/applying-settings/persistence-settings-ui-defaults.test.ts index 7d7ed9f042ae..9daeda90e39b 100644 --- a/src/main/persistence/applying-settings/persistence-settings-ui-defaults.test.ts +++ b/src/main/persistence/applying-settings/persistence-settings-ui-defaults.test.ts @@ -13,6 +13,7 @@ import { tmpdir } from 'node:os' import type { GlobalSettings } from '../../../shared/global-settings-types' import type { PersistedState } from '../../../shared/persisted-state-types' import { getDefaultPersistedState } from '../../../shared/constants' +import { nativeChatQueueFollowUps } from '../../../shared/native-chat-follow-up-behavior' import { ONBOARDING_FINAL_STEP, ONBOARDING_FLOW_VERSION } from '../../../shared/onboarding-defaults' const { loadUserSshConfigMock, sshConfigHostsToTargetsMock } = vi.hoisted(() => ({ @@ -137,6 +138,32 @@ describe('Store', () => { expect(readDataFile()).not.toHaveProperty('settings.orchestrationHeartbeatIntervalMinutes') }) + it.each([true, false, undefined])( + 'preserves the queue preference %s through load, update, save and reload', + async (saved) => { + const persisted = getDefaultPersistedState(testState.dir) + const { nativeChatQueueFollowUps: _absent, ...settings } = persisted.settings + void _absent + writeDataFile({ + ...persisted, + settings: { + ...settings, + ...(saved === undefined ? {} : { nativeChatQueueFollowUps: saved }) + } + }) + const store = await createStore() + expect(nativeChatQueueFollowUps(store.getSettings())).toBe(saved !== false) + store.updateSettings({ nativeChatQueueFollowUps: false }) + store.flush() + expect(readDataFile()).toHaveProperty('settings.nativeChatQueueFollowUps', false) + const reloaded = await createStore() + expect(nativeChatQueueFollowUps(reloaded.getSettings())).toBe(false) + reloaded.updateSettings({ nativeChatQueueFollowUps: true }) + reloaded.flush() + expect(readDataFile()).toHaveProperty('settings.nativeChatQueueFollowUps', true) + } + ) + it('returns default UI state when no data file exists', async () => { const store = await createStore() const ui = store.getUI() diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 0364ce3eb3c8..65363e690463 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -1,6 +1,7 @@ import { conversationRecordReader } from './orchestration/structured-session-lineage' import type { RuntimeLinearCommandSurface } from './runtime-linear-command-surface' import { installRuntimeLinearCommandSurface } from './runtime-linear-command-surface' +import { publishNativeChatFollowUpChanges } from './runtime-native-chat-follow-up-events' import { publishWorkspaceViewChanges } from './runtime-workspace-view-change-events' import { OrcaRuntimeWithSidebarTemporal, @@ -169,6 +170,7 @@ class OrcaRuntimeService extends OrcaRuntimeSidebarBase { registerDetectedWorktreeScanInvalidation() registerWorktreeChangeInvalidator((repoId) => this.invalidateWorktreeCatalog(repoId)) publishWorkspaceViewChanges(this.store, (event) => this.emitClientEvent(event)) + publishNativeChatFollowUpChanges(this.store, (event) => this.emitClientEvent(event)) } private structuredAgentAvailability?: ReturnType diff --git a/src/main/runtime/remote-runtime-request-connection.integration.test.ts b/src/main/runtime/remote-runtime-request-connection.integration.test.ts index 4c11d06a20f7..8bfa43c9c180 100644 --- a/src/main/runtime/remote-runtime-request-connection.integration.test.ts +++ b/src/main/runtime/remote-runtime-request-connection.integration.test.ts @@ -117,6 +117,7 @@ describe('remote runtime request connection integration', () => { ] const clientEventListeners = new Set<(event: RuntimeClientEvent) => void>() const subscriptionCleanups = new Map void>() + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this socket fixture implements every runtime method used by client-events subscribe and repo.list. const runtime = { configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'events-runtime-test', @@ -143,6 +144,7 @@ describe('remote runtime request connection integration', () => { } return repo }, + getClientSettings: () => ({ nativeChatQueueFollowUps: false }), onClientEvent: (listener: (event: RuntimeClientEvent) => void) => { clientEventListeners.add(listener) return () => clientEventListeners.delete(listener) @@ -284,6 +286,7 @@ describe('remote runtime request connection integration', () => { listener(event) } } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this sleep socket fixture implements every runtime method reached by its subscriptions and list requests. const runtime = { configureNotificationDismissalStore: () => {}, getRuntimeId: () => 'remote-sleep-runtime-test', @@ -304,6 +307,7 @@ describe('remote runtime request connection integration', () => { subscriptionCleanups.delete(id) }, onClientDisconnected: () => {}, + getClientSettings: () => ({ nativeChatQueueFollowUps: false }), onClientEvent: (listener: (event: RuntimeClientEvent) => void) => { clientEventListeners.add(listener) return () => clientEventListeners.delete(listener) @@ -551,6 +555,7 @@ describe('remote runtime request connection integration', () => { } }, onClientDisconnected: () => {}, + getClientSettings: () => ({ nativeChatQueueFollowUps: false }), onClientEvent: (listener: (event: RuntimeClientEvent) => void) => { clientEventListeners.add(listener) return () => clientEventListeners.delete(listener) diff --git a/src/main/runtime/rpc/methods/client-events.ts b/src/main/runtime/rpc/methods/client-events.ts index dca46e043347..3e683ebb9365 100644 --- a/src/main/runtime/rpc/methods/client-events.ts +++ b/src/main/runtime/rpc/methods/client-events.ts @@ -48,7 +48,14 @@ export const CLIENT_EVENT_METHODS = [ return state ? [{ targetId: target.id, state }] : [] }) // Listen before snapshotting to close reload gaps without exposing HUB-private target configuration. - emit({ type: 'ready', subscriptionId, snapshot: { sshStates } }) + emit({ + type: 'ready', + subscriptionId, + snapshot: { + sshStates, + nativeChatQueueFollowUps: runtime.getClientSettings().nativeChatQueueFollowUps + } + }) }) } }), diff --git a/src/main/runtime/rpc/methods/structured-agent-session-legacy-command-wait.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-legacy-command-wait.test.ts new file mode 100644 index 000000000000..4cee22e028b1 --- /dev/null +++ b/src/main/runtime/rpc/methods/structured-agent-session-legacy-command-wait.test.ts @@ -0,0 +1,117 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { + createQueuedMessageTestRig, + eventually, + QUEUED_RIG_CALLER +} from '../../../native-chat/agent-session-wire/structured-agent-session-queued-message-rig.test-fixture' +import { + HOST_TEST_NOW, + HOST_TEST_SESSION as SESSION, + hostTestOperationId, + hostTestMessage +} from '../../../native-chat/agent-session-wire/structured-agent-session-host-test-data' +import { setStructuredAgentSessionHost } from '../../../native-chat/agent-session-wire/structured-agent-session-registry' +import { sendStructuredAgentSessionForClient } from './structured-agent-session-send-compatibility' +import { + AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY, + AGENT_SESSION_PENDING_SEND_RESULT_RUNTIME_CAPABILITY, + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY +} from '../../../../shared/protocol-version' +import type { RpcContext } from '../core' +import { agentSessionMessagePayload } from '../../../../shared/structured-agent-session-send-mutation' + +afterEach(() => { + setStructuredAgentSessionHost(null) + vi.restoreAllMocks() + vi.useRealTimers() +}) + +it.each(['accepted', 'pending', 'oldest'] as const)( + 'real %s reader wait tier behind an active command uses its actual budget and eventual wake', + async (tier) => { + vi.useFakeTimers() + vi.setSystemTime(HOST_TEST_NOW) + vi.spyOn(Date, 'now').mockReturnValue(HOST_TEST_NOW) + const rig = await createQueuedMessageTestRig({ now: () => Date.now() }) + setStructuredAgentSessionHost(rig.host) + try { + const working = await rig.workingSend() + await rig.settleAccepted(working, 'warmup') + const commandId = hostTestOperationId() + const commandFields = { command: 'compact' as const } + const command = rig.host.conversationCommand(QUEUED_RIG_CALLER, { + ...commandFields, + envelope: rig.envelope(commandFields, 'agentSession.conversationCommand', commandId), + userSend: true + }) + await eventually(() => expect(rig.compact).toHaveBeenCalledTimes(1)) + await command + const body = hostTestMessage('M behind compact') + const messageId = hostTestOperationId() + let replied = false + const wait = vi.spyOn(rig.host, 'waitForSendSettlement') + const reply = sendStructuredAgentSessionForClient( + { + body, + envelope: rig.envelope( + { body: agentSessionMessagePayload(body) }, + 'agentSession.send', + messageId + ) + }, + { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the installed-host registry path never reads runtime methods. + runtime: {} as RpcContext['runtime'], + clientId: QUEUED_RIG_CALLER.callerKey, + clientKind: 'runtime', + clientCapabilities: [ + STRUCTURED_AGENT_SESSION_RUNTIME_CAPABILITY, + ...(tier === 'accepted' ? [AGENT_SESSION_ACCEPTED_SEND_RUNTIME_CAPABILITY] : []), + ...(tier === 'pending' ? [AGENT_SESSION_PENDING_SEND_RESULT_RUNTIME_CAPABILITY] : []) + ] + } + ).then((result) => { + replied = true + return result + }) + await eventually(async () => + expect(await rig.submission(messageId)).toMatchObject({ dispatchState: 'pending' }) + ) + if (tier !== 'accepted') { + expect(wait).toHaveBeenCalledWith(SESSION, messageId, { + until: tier === 'oldest' ? 'answered' : 'handed-over-or-behind-command', + budgetMs: 120_000 + }) + } + if (tier !== 'oldest') { + expect(await reply).toMatchObject({ + ok: true, + value: { submission: { dispatchState: 'pending' } } + }) + } + await vi.advanceTimersByTimeAsync(15_001) + expect(replied).toBe(tier !== 'oldest') + if (tier === 'oldest') { + await vi.advanceTimersByTimeAsync(100_000) + expect(replied).toBe(false) + await vi.advanceTimersByTimeAsync(5_000) + expect(await reply).toMatchObject({ + ok: true, + value: { submission: { dispatchState: 'pending' } } + }) + } + expect((await rig.submission(messageId))?.handedOverAt).toBeUndefined() + rig.finishCompact() + await eventually(async () => + expect((await rig.submission(messageId))?.handedOverAt).toBeDefined() + ) + await rig.settleAccepted(messageId, `M-${tier}`) + expect((await rig.submission(messageId))?.dispatchState).toBe('accepted') + expect( + rig.dispatch.mock.calls.filter(([input]) => input.clientMessageId === messageId) + ).toHaveLength(1) + } finally { + await rig.dispose() + } + } +) diff --git a/src/main/runtime/rpc/methods/structured-agent-session-queued-edit.test.ts b/src/main/runtime/rpc/methods/structured-agent-session-queued-edit.test.ts index b3ee7ecc3bfe..23401ec6bde9 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-queued-edit.test.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-queued-edit.test.ts @@ -43,9 +43,10 @@ beforeEach(() => { afterEach(clearStructuredHostStub) describe('queued edit methods', () => { - it('the host advertises editing on its own, with mid-turn queueing still dark', () => { + it('the host advertises editing and mid-turn queueing, never the v1 name released clients read', () => { expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_QUEUED_MESSAGE_EDIT_RUNTIME_CAPABILITY) - expect(RUNTIME_CAPABILITIES).not.toContain(AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY) + expect(RUNTIME_CAPABILITIES).toContain(AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY) + expect(RUNTIME_CAPABILITIES).not.toContain('agent-session.queued-messages.v1') }) it.each([ diff --git a/src/main/runtime/rpc/methods/structured-agent-session-queued-methods.ts b/src/main/runtime/rpc/methods/structured-agent-session-queued-methods.ts index 94d4897f9303..06bb8dcb4692 100644 --- a/src/main/runtime/rpc/methods/structured-agent-session-queued-methods.ts +++ b/src/main/runtime/rpc/methods/structured-agent-session-queued-methods.ts @@ -1,4 +1,4 @@ -// Do not gate queued-card actions on queued-messages.v1: hosts without it still publish unsent cards. Older pre-queue/edit hosts lack the methods. +// Do not gate queued-card actions on queued-messages.v2: hosts without it still publish unsent cards. Older pre-queue/edit hosts lack the methods. import { defineMethod } from '../core' import { diff --git a/src/main/runtime/runtime-client-settings.ts b/src/main/runtime/runtime-client-settings.ts index 5e200cf4e154..87648b4b0c3f 100644 --- a/src/main/runtime/runtime-client-settings.ts +++ b/src/main/runtime/runtime-client-settings.ts @@ -17,6 +17,7 @@ import type { GlobalSettings } from '../../shared/global-settings-types' import { applyNativeChatSessionOptionSettingsMutation } from '../../shared/native-chat/input/native-chat-session-option-defaults' import type { NativeChatSessionOptionSettingsMutation } from '../../shared/native-chat/input/native-chat-session-options' import { getHostDisplayLabelOverrides } from '../../shared/host-setting-overrides' +import { nativeChatQueueFollowUps } from '../../shared/native-chat-follow-up-behavior' import type { TerminalQuickCommand } from '../../shared/terminal-quick-command-types' import { recordManagedHookInstallFailure } from '../agent-hooks/install-telemetry' import { applyAgentStatusHooksEnabled } from '../agent-hooks/managed-agent-hook-controls' @@ -108,8 +109,8 @@ export class RuntimeClientSettingsController { : { agentSkillSharingEnabled: isAgentSkillSharingEnabled(settings) }), machineName: settings.machineName ?? '', nativeChatPermissionMode: publishedLegacyChatPermissionMode(settings), - // Phone sends queue mid-turn only while this is on; absence from older hosts means on. - nativeChatQueueFollowUps: settings.nativeChatQueueFollowUps !== false, + // Mirror the host preference; delivery still depends on queue capability. + nativeChatQueueFollowUps: nativeChatQueueFollowUps(settings), // Why projected: a paired client's AI buttons start these actions' agents, and must honour // the agent saved for each one as the desktop does. Absent on older hosts. sourceControlAi: projectSourceControlLaunchRecipes(settings), diff --git a/src/main/runtime/runtime-native-chat-follow-up-events.test.ts b/src/main/runtime/runtime-native-chat-follow-up-events.test.ts new file mode 100644 index 000000000000..407bf7300501 --- /dev/null +++ b/src/main/runtime/runtime-native-chat-follow-up-events.test.ts @@ -0,0 +1,71 @@ +import { expect, it, vi } from 'vitest' +import { getDefaultSettings } from '../../shared/constants' +import type { RuntimeStore } from './runtime-store-contract' +import { publishNativeChatFollowUpChanges } from './runtime-native-chat-follow-up-events' + +it('publishes only a change in the normalized host preference, including on a headless store', () => { + let settings = getDefaultSettings('/tmp') + let changed: Parameters>[0] | undefined + const emit = vi.fn() + publishNativeChatFollowUpChanges( + { + getSettings: () => settings, + onSettingsChanged: (listener) => { + changed = listener + return () => {} + } + }, + emit + ) + for (const count of [10, 100]) { + for (let index = 0; index < count; index++) { + changed?.({}, settings) + } + expect(emit).not.toHaveBeenCalled() + } + settings = { ...settings, nativeChatQueueFollowUps: false } + changed?.({ nativeChatQueueFollowUps: false }, settings) + expect(emit.mock.calls).toEqual([ + [{ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps: false }] + ]) + changed?.({}, settings) + settings = { ...settings, nativeChatQueueFollowUps: true } + changed?.({}, settings) + expect(emit).toHaveBeenLastCalledWith({ + type: 'nativeChatQueueFollowUpsChanged', + queueFollowUps: true + }) + expect(emit).toHaveBeenCalledTimes(2) +}) + +it('client-events ready snapshots the same normalized setting after installing its event listener', async () => { + const { OrcaRuntimeService } = await import('./orca-runtime') + const { RuntimeClientSettingsController } = await import('./runtime-client-settings') + const { CLIENT_EVENT_METHODS } = await import('./rpc/methods/client-events') + const runtime = new OrcaRuntimeService() + const settings = getDefaultSettings('/tmp') + const controller = new RuntimeClientSettingsController({ + getSettings: () => ({ ...settings, nativeChatQueueFollowUps: false }), + updateSettings: () => {} + }) + const onEvent = vi.spyOn(runtime, 'onClientEvent') + vi.spyOn(runtime, 'getClientSettings').mockImplementation(() => { + expect(onEvent).toHaveBeenCalledTimes(1) + return controller.get() + }) + const ready = vi.fn() + const handler = CLIENT_EVENT_METHODS.find( + (method) => method.name === 'runtime.clientEvents.subscribe' + ) + if (!handler || !('stream' in handler)) { + throw new Error('missing client events method') + } + const pending = handler.handler(undefined, { runtime, connectionId: 'preference' }, ready) + const message = ready.mock.calls.find(([value]) => value.type === 'ready')?.[0] + expect(message).toMatchObject({ + type: 'ready', + snapshot: { nativeChatQueueFollowUps: false } + }) + runtime.cleanupSubscription(message.subscriptionId) + await pending +}) diff --git a/src/main/runtime/runtime-native-chat-follow-up-events.ts b/src/main/runtime/runtime-native-chat-follow-up-events.ts new file mode 100644 index 000000000000..878f5704a285 --- /dev/null +++ b/src/main/runtime/runtime-native-chat-follow-up-events.ts @@ -0,0 +1,20 @@ +import { nativeChatQueueFollowUps } from '../../shared/native-chat-follow-up-behavior' +import type { RuntimeClientEvent } from '../../shared/runtime-client-events' +import type { RuntimeStore } from './runtime-store-contract' + +export function publishNativeChatFollowUpChanges( + store: Pick | null, + emit: (event: RuntimeClientEvent) => void +): void { + if (!store?.getSettings || !store.onSettingsChanged) { + return + } + let previous = nativeChatQueueFollowUps(store.getSettings()) + store.onSettingsChanged((_updates, settings) => { + const queueFollowUps = nativeChatQueueFollowUps(settings) + if (queueFollowUps !== previous) { + previous = queueFollowUps + emit({ type: 'nativeChatQueueFollowUpsChanged', queueFollowUps }) + } + }) +} diff --git a/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts b/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts index 48fc0a08b196..c7f19271fa67 100644 --- a/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts +++ b/src/main/runtime/structured-agent-session-codex-turn-end-settlement.test.ts @@ -518,6 +518,8 @@ describe("a queued card's Send-now while a Codex turn runs", () => { expect(verdictOf((await settled()).submissions, sent)).toBe('accepted') ) expect((await settled()).owesWork).toBe(false) + // Delivered once: the turn's end neither steers it again nor starts a turn with it. + expect([steers, answers]).toEqual([1, 1]) }) it('is settled when a Stop ends that turn, on a Codex that names a steered start falsely', async () => { diff --git a/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx b/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx index bbf9729a7296..cb6ddad060b7 100644 --- a/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatAgentMessageRow.test.tsx @@ -143,7 +143,7 @@ describe("another agent's queued card", () => { onSteer={vi.fn()} onDelete={vi.fn()} onEdit={vi.fn()} - onTurnOffQueueing={vi.fn()} + agentWorking /> ) } diff --git a/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx b/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx index 9dd7963526cb..1c93a3fd8608 100644 --- a/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx +++ b/src/renderer/src/components/native-chat/NativeChatComposerPane.tsx @@ -56,7 +56,7 @@ export const NativeChatComposerPane = forwardRef 0, - ...(!editSession && steerQueued ? { steerQueued } : {}), + ...(!editSession && steerHead ? { steerHead } : {}), setActiveSuggestion, setDraft, setCaret diff --git a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx index 2747bf8e1a25..d35306de1236 100644 --- a/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx +++ b/src/renderer/src/components/native-chat/NativeChatInterruptedContinue.test.tsx @@ -376,7 +376,14 @@ it('keeps the draft through Continue admission, refusal, uncertainty and recorde fence: 1, submissions: [], queuedMessageIds: [], - queue: { capability: 'unsupported', enabled: false }, + queue: { + capability: 'unsupported', + followUpsQueue: false, + isWorking: false, + stopping: false, + session: {}, + prompts: [] + }, historyLoaded: false, sendOptions: () => options }) diff --git a/src/renderer/src/components/native-chat/NativeChatQueuedMessageCard.tsx b/src/renderer/src/components/native-chat/NativeChatQueuedMessageCard.tsx index e1bdb19a3e3c..a85161b31461 100644 --- a/src/renderer/src/components/native-chat/NativeChatQueuedMessageCard.tsx +++ b/src/renderer/src/components/native-chat/NativeChatQueuedMessageCard.tsx @@ -88,14 +88,17 @@ export function queuedMessageCardCaption( } } -/** Steer's or Send's label and tooltip (`queuedMessageCardSteers`). */ -export function queuedMessageCardSendNow(card: QueuedMessageCard): { +/** Steer's or Send's label and tooltip: Steer only into a turn that is running (`queuedMessageCardSteers`). */ +export function queuedMessageCardSendNow( + card: QueuedMessageCard, + agentWorking: boolean +): { /** Steer's ↳, or Send's paper plane. */ steers: boolean label: string hint: string } { - if (!queuedMessageCardSteers(card)) { + if (!agentWorking || !queuedMessageCardSteers(card)) { return { steers: false, label: translate('components.native-chat.queuedMessages.send', 'Send'), @@ -118,6 +121,7 @@ export function NativeChatQueuedMessageCard({ agentName, statedFailures, showsSteerShortcut, + agentWorking, steerHeld = false, pending = null, onSteer, @@ -126,16 +130,17 @@ export function NativeChatQueuedMessageCard({ editor, editAttachTo, editDisabled = false, - drag, - onTurnOffQueueing + drag }: { card: QueuedMessageCard /** The chat's worktree, whose host its sender is found on; null shows the sender unlinked. */ chatWorktreeId: string | null agentName?: string statedFailures?: readonly AgentSessionFailureFact[] - /** Only the newest card answers Cmd/Ctrl+Enter; only it may show the chord. */ + /** Only the head card answers Cmd/Ctrl+Shift+Enter; only it may show the chord. */ showsSteerShortcut: boolean + /** The agent is working: a steerable card's action reads Steer, otherwise Send. */ + agentWorking: boolean /** The chat reads Stopping: the card waits for the stop (`NativeChatQueuedMessageList`). */ steerHeld?: boolean /** Disable the card during its own action or Clear all; spin only the pressed action. */ @@ -151,14 +156,12 @@ export function NativeChatQueuedMessageCard({ /** Another card in this pane is being edited. */ editDisabled?: boolean drag?: QueuedMessageDragPresentation - /** Absent when the host does not queue sends, so there is nothing to turn off. */ - onTurnOffQueueing?: () => void }): React.JSX.Element { const caption = queuedMessageCardCaption(card, agentName, statedFailures) const line = queuedMessageCardLine(card, nativeChatImageLabelCopy()) const returned = card.state === 'returned' const attention = queuedMessageCardNeedsAttention(card) - const sendNow = queuedMessageCardSendNow(card) + const sendNow = queuedMessageCardSendNow(card, agentWorking) const busy = pending !== null const isMac = isMacPlatform() // Allow inspecting clipped text before acting; another agent may have authored the card. @@ -275,7 +278,9 @@ export function NativeChatQueuedMessageCard({ {sendNow.hint} {showsSteerShortcut ? ( - + ) : null} @@ -300,7 +305,8 @@ export function NativeChatQueuedMessageCard({ {translate('components.native-chat.queuedMessages.delete', 'Delete')} - {(!card.command && onEdit) || onTurnOffQueueing ? ( + {/* A command's text is not a draft: edited, it would become a message. */} + {!card.command && onEdit ? (