diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml index d8ecbf4619d3..56ee54e13de0 100644 --- a/.github/workflows/mobile.yml +++ b/.github/workflows/mobile.yml @@ -39,6 +39,30 @@ on: - 'config/tsconfig.node.json' - 'src/types/build-constants.d.ts' - 'src/main/native-chat/agent-session-wire/**' + # Recorded phone transcripts exercise these host decoders and their runtime dependencies. + - 'src/main/native-chat/*transcript*.ts' + - 'src/main/native-chat/subagent-entry-id-bounds.ts' + - 'src/main/native-chat/agent-session-journal/journal-payload-bounds.ts' + - 'src/main/native-chat/agent-session-journal/journal-reasoning-row.ts' + - 'src/main/claude/claude-internal-message-content.ts' + - 'src/main/claude/claude-stop-hook-feedback.ts' + - 'src/main/claude/structured/journal/**' + - 'src/main/claude/__fixtures__/claude-adapter-capture-fold.jsonl' + - 'src/main/codex/app-server/codex-item-field-readers.ts' + - 'src/main/codex/structured/items/**' + - 'src/main/codex/structured/background-work/codex-subagent-activity.ts' + - 'src/main/codex/structured/journal/codex-goal-journal-rows.ts' + - 'src/main/codex/__fixtures__/codex-hook-outcomes.jsonl' + - 'src/main/ai-vault/session-scanner-*.ts' + - 'src/main/ai-vault/ai-vault-scan-cancellation.ts' + - 'src/main/ai-vault/scan-service/session-scanner-service-env.ts' + - 'src/main/ai-vault/scanners/grok/session-scanner-grok-user-text.ts' + - 'src/main/provider-process/provider-json-record.ts' + - 'src/main/providers/ssh-host-not-served-error.ts' + - 'src/main/wsl/discovery/**' + - 'src/main/wsl/execution/wsl-exe-process.ts' + - 'src/main/wsl/execution/wsl-interop-spawn-directory.ts' + - 'src/main/wsl/filesystem/wsl-unc-access-gate.ts' - 'src/main/runtime/structured-attention-original-delivery.test-fixture.ts' # Rerun the only Fastfile-loading checks for release-workflow/Fastfile edits. - '.github/workflows/mobile.yml' @@ -103,6 +127,30 @@ on: - 'config/tsconfig.node.json' - 'src/types/build-constants.d.ts' - 'src/main/native-chat/agent-session-wire/**' + # Recorded phone transcripts exercise these host decoders and their runtime dependencies. + - 'src/main/native-chat/*transcript*.ts' + - 'src/main/native-chat/subagent-entry-id-bounds.ts' + - 'src/main/native-chat/agent-session-journal/journal-payload-bounds.ts' + - 'src/main/native-chat/agent-session-journal/journal-reasoning-row.ts' + - 'src/main/claude/claude-internal-message-content.ts' + - 'src/main/claude/claude-stop-hook-feedback.ts' + - 'src/main/claude/structured/journal/**' + - 'src/main/claude/__fixtures__/claude-adapter-capture-fold.jsonl' + - 'src/main/codex/app-server/codex-item-field-readers.ts' + - 'src/main/codex/structured/items/**' + - 'src/main/codex/structured/background-work/codex-subagent-activity.ts' + - 'src/main/codex/structured/journal/codex-goal-journal-rows.ts' + - 'src/main/codex/__fixtures__/codex-hook-outcomes.jsonl' + - 'src/main/ai-vault/session-scanner-*.ts' + - 'src/main/ai-vault/ai-vault-scan-cancellation.ts' + - 'src/main/ai-vault/scan-service/session-scanner-service-env.ts' + - 'src/main/ai-vault/scanners/grok/session-scanner-grok-user-text.ts' + - 'src/main/provider-process/provider-json-record.ts' + - 'src/main/providers/ssh-host-not-served-error.ts' + - 'src/main/wsl/discovery/**' + - 'src/main/wsl/execution/wsl-exe-process.ts' + - 'src/main/wsl/execution/wsl-interop-spawn-directory.ts' + - 'src/main/wsl/filesystem/wsl-unc-access-gate.ts' - 'src/main/runtime/structured-attention-original-delivery.test-fixture.ts' - '.github/workflows/mobile.yml' - 'config/mobile-ci.vitest.config.mjs' diff --git a/config/tsconfig.test.mobile-host-declarations.json b/config/tsconfig.test.mobile-host-declarations.json index 156cd732e3b1..0b6e169678d2 100644 --- a/config/tsconfig.test.mobile-host-declarations.json +++ b/config/tsconfig.test.mobile-host-declarations.json @@ -19,7 +19,10 @@ "../src/main/runtime/rpc/dispatcher-request-parsing.ts", "../src/main/github/issue-field-options.ts", "../src/main/runtime/workspaces/process-listing/runtime-worktree-ps-summaries.ts", - "../src/types/build-constants.d.ts" + "../src/types/build-constants.d.ts", + "../src/main/native-chat/transcript-line-decoders-claude.ts", + "../src/main/codex/structured/items/codex-thread-item-identity.ts", + "../src/main/codex/structured/items/codex-structured-item-translation.ts" ], "include": ["../src/shared/**/*.ts", "../src/shared/**/*.tsx"], "exclude": [ diff --git a/mobile/scripts/check-tests-typecheck-ratchet.mjs b/mobile/scripts/check-tests-typecheck-ratchet.mjs index 7a082032547c..1aaee09eee52 100644 --- a/mobile/scripts/check-tests-typecheck-ratchet.mjs +++ b/mobile/scripts/check-tests-typecheck-ratchet.mjs @@ -15,6 +15,10 @@ const ERROR_LINE = /^(\S.*?)\(\d+,\d+\): error TS\d+:/ // Tests outside the RN program. Checked transfers are the roots of tsconfig.test.node.json and must pass // that strict program; the rest are legacy runtime-only allowances whose bodies nothing typechecks. export const TESTS_OUTSIDE_PROGRAM = new Map([ + [ + 'src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts', + 'Checked transfer: strict Node program over emitted phone/host declarations (tsconfig.test.node.json)' + ], [ 'src/components/WorktreeAgentList.runtime-lineage.test.tsx', 'Legacy runtime-only: the test body is not typechecked anywhere; it imports the desktop SQLite assignment projection, which does not check against RN libs, and its implementation sources keep their normal checks' diff --git a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx index 1178cd7a4e73..566759d9ff9d 100644 --- a/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatOverlay.tsx @@ -2,7 +2,7 @@ import { MobileQueuedMessageComposerContext } from '../mobile-queued-message-com import { useCallback, useLayoutEffect, useMemo, useRef } from 'react' import { StyleSheet, View } from 'react-native' import { MobileNativeChatView, type MobileNativeChatInputLockReason } from './MobileNativeChatView' -import { foldMobileNativeChatMessages } from './mobile-native-chat-render-data' +import { useMobileNativeChatProjection } from './transcript/use-mobile-native-chat-projection' import { nativeChatDockedTaskList } from '../../../../src/shared/native-chat/input/native-chat-task-list-state' import type { MobileNativeChatImageAttachments } from './composer/use-mobile-native-chat-image-attachments' import type { MobileNativeChatController } from './mobile-native-chat-controller-contract' @@ -99,10 +99,12 @@ export function MobileNativeChatOverlay({ session.messages, controller.nativeChatItemSource ) - const folded = useMemo( - () => foldMobileNativeChatMessages(fullContent.messages, agent), - [fullContent.messages, agent] - ) + const folded = useMobileNativeChatProjection(fullContent.messages, agent, [ + sendSurfaceId, + sessionId, + controller.nativeChatItemSource?.client, + controller.nativeChatItemSource?.sessionId + ]) const taskList = useMemo(() => nativeChatDockedTaskList(folded), [folded]) const streaming = controller.nativeChatStreamingText ?? null const queued = controller.nativeChatQueued diff --git a/mobile/src/session/native-chat/MobileNativeChatView.tsx b/mobile/src/session/native-chat/MobileNativeChatView.tsx index 4e0fc6c7f1fa..12a3c1d2f336 100644 --- a/mobile/src/session/native-chat/MobileNativeChatView.tsx +++ b/mobile/src/session/native-chat/MobileNativeChatView.tsx @@ -26,10 +26,10 @@ import { MobileNativeChatEmptyStateView } from '../MobileNativeChatEmptyStateVie import { mobileNativeChatListFooter } from './mobile-native-chat-list-footer' import { mobileNativeChatListHeader } from './mobile-native-chat-list-header' import { - buildMobileNativeChatTransientData, mobileNativeChatEmptyState, type MobileNativeChatPendingItem } from './mobile-native-chat-render-data' +import { useMobileNativeChatTransientData } from './transcript/use-mobile-native-chat-transient-data' import { useMobileNativeChatRowKeys } from './transcript/mobile-native-chat-row-keys' import { useMobileNativeChatPinchGesture } from './transcript/use-mobile-native-chat-pinch-gesture' import { useMobileNativeChatTailFollow } from './transcript/use-mobile-native-chat-tail-follow' @@ -217,15 +217,9 @@ export function MobileNativeChatView({ const bottomPad = keyboardInset > 0 ? keyboardInset + insets.bottom : insets.bottom const { fontScale, pinchGesture } = useMobileNativeChatPinchGesture() - const { data } = useMemo( - () => - buildMobileNativeChatTransientData({ - folded, - streaming, - pending, - imagePreviewsByMessageId - }), - [folded, streaming, pending, imagePreviewsByMessageId] + const data = useMobileNativeChatTransientData( + { folded, streaming, pending, imagePreviewsByMessageId }, + sendSurfaceId ) const tail = useMobileNativeChatTailFollow({ hasItems: data.length > 0, scopeKey: sendSurfaceId }) const { jumpToTail, recordScrollMetrics, scrollMayLoadEarlier } = tail diff --git a/mobile/src/session/native-chat/mobile-native-chat-render-data.ts b/mobile/src/session/native-chat/mobile-native-chat-render-data.ts index 06c526f59c58..d8f5893538be 100644 --- a/mobile/src/session/native-chat/mobile-native-chat-render-data.ts +++ b/mobile/src/session/native-chat/mobile-native-chat-render-data.ts @@ -17,7 +17,7 @@ import { type NativeChatMessage } from '../../../../src/shared/native-chat/native-chat-types' import type { AgentType } from '../../../../src/shared/agent-status/contracts/agent-status-types' -import type { MobileNativeChatStatus } from './use-mobile-native-chat-session' +import type { MobileNativeChatStatus } from './mobile-native-chat-session-status' import { orderNativeChatDisplayMessages } from '../../../../src/shared/native-chat/transcript/native-chat-message-order' import { translate } from '../../i18n/mobile-i18n' @@ -99,22 +99,37 @@ export function foldMobileNativeChatMessages( messages: readonly NativeChatMessage[], agent: AgentType ): NativeChatMessage[] { - // Filter child/noise rows before folding so they cannot split tool runs; project plan updates afterward so they cannot consume another call’s result. - return projectNativeChatTaskListFrames( - stripNoiseMessages( - foldToolMessages( - foldSubagentItems( - prepareNativeChatMessages( - messages.filter( - (message) => - isRootAgentJournalItem(message) && !isUndrawnProviderFrameMessage(message) - ), - agent - ) - ) - ) - ) - ).filter((message) => !isWordlessProviderFrameMessage(message)) + return finishMobileNativeChatMessages( + foldToolMessages(foldSubagentItems(prepareMobileNativeChatMessages(messages, agent))) + ) +} + +export function isMobileNativeChatSource(message: NativeChatMessage): boolean { + return isRootAgentJournalItem(message) && !isUndrawnProviderFrameMessage(message) +} + +export function prepareMobileNativeChatMessages( + messages: readonly NativeChatMessage[], + agent: AgentType, + recordSource?: (message: NativeChatMessage, visible: boolean) => void +): NativeChatMessage[] { + return prepareNativeChatMessages( + messages.filter((message) => { + const visible = isMobileNativeChatSource(message) + recordSource?.(message, visible) + return visible + }), + agent + ) +} + +export function finishMobileNativeChatMessages( + messages: readonly NativeChatMessage[] +): NativeChatMessage[] { + // Plan frames must not consume another call's result. + return projectNativeChatTaskListFrames(stripNoiseMessages(messages)).filter( + (message) => !isWordlessProviderFrameMessage(message) + ) } export function buildMobileNativeChatTransientData({ diff --git a/mobile/src/session/native-chat/mobile-native-chat-session-status.ts b/mobile/src/session/native-chat/mobile-native-chat-session-status.ts new file mode 100644 index 000000000000..cbd5642aa805 --- /dev/null +++ b/mobile/src/session/native-chat/mobile-native-chat-session-status.ts @@ -0,0 +1,8 @@ +export type MobileNativeChatStatus = + | 'idle' + | 'loading' + | 'waiting-session' + // No transcript file yet: render the empty chat while keeping its read unsettled. + | 'awaiting-transcript' + | 'ready' + | 'error' diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts new file mode 100644 index 000000000000..eb4c330a6717 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection-units.ts @@ -0,0 +1,120 @@ +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import { + foldToolMessages, + type NativeChatToolFoldKind +} from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold' +import { + orphanRowId, + type NativeChatOrphanOrigin +} from '../../../../../src/shared/native-chat/tools/native-chat-folded-tool-results' +import { finishMobileNativeChatMessages } from '../mobile-native-chat-render-data' + +export type Unit = { + sources: readonly NativeChatMessage[] + rows: NativeChatMessage[] + orphans: readonly NativeChatOrphanOrigin[] +} + +export function buildMobileNativeChatUnits( + grouped: readonly NativeChatMessage[], + kinds: ReadonlyMap, + previous?: { units: readonly Unit[] } +): Unit[] { + const members: NativeChatMessage[][] = [] + let active = false + for (const source of grouped) { + const kind = kinds.get(source)! + if (active && (kind === 'tool' || kind === 'sidecar' || kind === 'pass')) { + members.at(-1)!.push(source) + } else { + members.push([source]) + active = source.role === 'assistant' && kind !== 'orphan' + } + } + const ids = new Set(grouped.map((row) => row.id)) + const oldUnits = new Map(previous?.units.map((unit) => [unit.sources[0]!.id, unit])) + const units = members.map((sources): Unit => { + const before = oldUnits.get(sources[0]!.id) + if ( + before && + before.sources.length === sources.length && + before.sources.every((source, index) => source === sources[index]) + ) { + return before + } + const substituted = before && substituteProse(before, sources, kinds) + const orphans: NativeChatOrphanOrigin[] = [] + const rows = + substituted ?? + finishMobileNativeChatMessages( + foldToolMessages(sources, ids, kinds, (origin) => orphans.push(origin)) + ) + return { sources, rows, orphans: substituted ? before!.orphans : orphans } + }) + const allocated = new Set(ids) + const occurrences = new Map() + return units.map((unit) => { + const renamed = new Map() + const orphans = unit.orphans.map((origin) => { + const id = orphanRowId(origin.sourceId, allocated, occurrences) + allocated.add(id) + if (id === origin.row.id) { + return origin + } + const row = { ...origin.row, id } + renamed.set(origin.row, row) + return { ...origin, row } + }) + return renamed.size === 0 + ? unit + : { + ...unit, + orphans, + rows: unit.rows.map((row) => renamed.get(row) ?? row) + } + }) +} + +function substituteProse( + before: Unit, + sources: readonly NativeChatMessage[], + kinds: ReadonlyMap +): NativeChatMessage[] | null { + if (before.sources.length !== sources.length) { + return null + } + const changed = sources.flatMap((source, index) => + source === before.sources[index] ? [] : [index] + ) + if (changed.length !== 1 || changed[0] !== 0) { + return null + } + const old = before.sources[0]!, + next = sources[0]! + if ( + old.role !== next.role || + (next.role !== 'assistant' && next.role !== 'reasoning') || + old.unpairedToolResults || + next.unpairedToolResults || + !old.blocks.every((block) => block.type === 'text' && !block.providerFrame) || + !next.blocks.every((block) => block.type === 'text' && !block.providerFrame) + ) { + return null + } + const target = before.rows.find((row) => row.id === old.id && row.role === old.role) + if (!target || !old.blocks.every((block, index) => block === target.blocks[index])) { + return null + } + const contribution = sources + .slice(1) + .findLast( + (source) => + source.journalPosition && (kinds.get(source) === 'tool' || kinds.get(source) === 'sidecar') + ) + const replacement: NativeChatMessage = { + ...next, + blocks: [...next.blocks, ...target.blocks.slice(old.blocks.length)], + ...(contribution ? { foldedJournalPosition: contribution.journalPosition } : {}) + } + return before.rows.map((row) => (row === target ? replacement : row)) +} diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.test.tsx b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.test.tsx new file mode 100644 index 000000000000..2818ccd9ab31 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.test.tsx @@ -0,0 +1,409 @@ +import { projectStructuredAgentSessionMessages } from '../../../../../src/shared/agent-session/view/structured-agent-session-message-projection' +import type { + AgentJournalRenderItem, + AgentJournalSubmission +} from '../../../../../src/shared/agent-session/journal/agent-session-journal-types' +import { withStopRowsAfterStoppedSends } from '../../../../../src/shared/native-chat/native-chat-stopped-before-start' +import { createElement } from 'react' +import { act, create } from 'react-test-renderer' +import { expect, it } from 'vitest' +import type { + NativeChatBlock, + NativeChatMessage +} from '../../../../../src/shared/native-chat/native-chat-types' +import { nativeChatTaskListPredecessors } from '../../../../../src/shared/native-chat/input/native-chat-task-list-history' +import { nativeChatDockedTaskList } from '../../../../../src/shared/native-chat/input/native-chat-task-list-state' +import { projectMobileNativeChatMessages } from './mobile-native-chat-projection' +import { useMobileNativeChatProjection } from './use-mobile-native-chat-projection' +import { useMobileNativeChatTransientData } from './use-mobile-native-chat-transient-data' +import { useMobileNativeChatTurnDisclosure } from './use-mobile-native-chat-turn-disclosure' + +Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }) +function row( + id: string, + role: NativeChatMessage['role'], + blocks: NativeChatBlock[] +): NativeChatMessage { + return { id, role, blocks, source: 'transcript', timestamp: 0 } +} +const prose = (id: string, text: string, role: NativeChatMessage['role'] = 'assistant') => + row(id, role, [{ type: 'text', text }]) +const call = (id: string, state: 'running' | 'completed' = 'running'): NativeChatBlock => ({ + type: 'tool-call', + callId: id, + name: 'Read', + input: { file_path: '/tmp/a.ts' }, + state +}) +const result = (id: string): NativeChatBlock => ({ + type: 'tool-result', + callId: id, + output: 'contents' +}) +const spawn = (id: string, state: 'working' | 'completed' = 'working') => + row(id, 'system', [{ type: 'subagent', id, groupId: 'live-group', label: id, state }]) + +it('preserves source positions, tools and orphan ids across successive local replacements', () => { + const lead = prose('a', 'Checking') + const roster = spawn('s1') + const tools = row('t', 'assistant', [call('read'), result('read'), result('missing')]) + tools.journalPosition = { sequence: 3, index: 0 } + const collision = prose('unpaired-tool-results:["t",0]', 'reserved', 'user') + let input = [lead, roster, tools, collision] + let state = projectMobileNativeChatMessages(input, 'claude') + expect(state.rows.map((message) => message.id)).toEqual([ + 'a', + 's1', + 't', + 'unpaired-tool-results:["t",0]' + ]) + const original = state.rows + for (const blocks of [ + [ + { type: 'text' as const, text: 'Checking now' }, + { type: 'text' as const, text: '.' } + ], + [{ type: 'text' as const, text: 'Done' }] + ]) { + input = [{ ...lead, blocks }, roster, tools, collision] + state = projectMobileNativeChatMessages(input, 'claude', state) + expect(state.rows[0]!.blocks.slice(blocks.length)).toEqual([call('read'), result('read')]) + expect(state.rows[0]!.foldedJournalPosition).toEqual({ sequence: 3, index: 0 }) + expect(state.rows[2]!.blocks).toEqual([result('missing')]) + } + expect(original[0]!.blocks[0]).toEqual({ type: 'text', text: 'Checking' }) + input = [ + input[0]!, + spawn('s1', 'completed'), + { ...tools, blocks: [call('read', 'completed'), result('read')] }, + collision + ] + state = projectMobileNativeChatMessages(input, 'claude', state) + expect(state.rows.map((message) => message.id)).toEqual(['a', 's1', collision.id]) + // A real source occupying a generated orphan id forces only the affected namespace reconciliation. + const orphan = row('orphan', 'assistant', [call('yes'), result('yes'), result('no')]) + let namespace = projectMobileNativeChatMessages([orphan], 'codex') + expect(namespace.rows.map((message) => message.id)).toEqual([ + 'orphan', + 'unpaired-tool-results:["orphan",0]' + ]) + namespace = projectMobileNativeChatMessages( + [orphan, prose('unpaired-tool-results:["orphan",0]', 'reserved', 'user')], + 'codex', + namespace + ) + expect(namespace.rows.map((message) => message.id)).toEqual([ + 'orphan', + 'unpaired-tool-results:["orphan",1]', + 'unpaired-tool-results:["orphan",0]' + ]) +}) + +it('preserves image preparation through prompt edits and source resets', () => { + const source = prose('image', '[Image: source: /tmp/a.png]', 'user') + let state = projectMobileNativeChatMessages( + [source, prose('prompt', '[Image #1] inspect', 'user')], + 'claude' + ) + expect(state.rows.map((message) => message.id)).toEqual(['prompt']) + expect(state.rows[0]?.blocks).toEqual([ + { type: 'image-ref', path: '/tmp/a.png' }, + { type: 'text', text: 'inspect' } + ]) + state = projectMobileNativeChatMessages( + [source, prose('prompt', '[Image #1] explain', 'user')], + 'claude', + state + ) + expect(state.rows[0]?.blocks).toEqual([ + { type: 'image-ref', path: '/tmp/a.png' }, + { type: 'text', text: 'explain' } + ]) + const prompt = prose('prompt', '[Image #1] explain', 'user') + state = projectMobileNativeChatMessages( + [source, prose('separator', 'Answer'), prompt], + 'claude', + state + ) + expect(state.rows.map((message) => [message.id, message.blocks])).toEqual([ + ['image', [{ type: 'image-ref', path: '/tmp/a.png' }]], + ['separator', [{ type: 'text', text: 'Answer' }]], + ['prompt', [{ type: 'text', text: 'explain' }]] + ]) + state = projectMobileNativeChatMessages([source, prompt], 'claude', state) + expect(state.rows[0]?.blocks).toEqual([ + { type: 'image-ref', path: '/tmp/a.png' }, + { type: 'text', text: 'explain' } + ]) + state = projectMobileNativeChatMessages([prompt], 'claude', state) + expect(state.rows.map((message) => [message.id, message.blocks])).toEqual([ + ['prompt', [{ type: 'text', text: 'explain' }]] + ]) + state = projectMobileNativeChatMessages([prose('other', 'Another chat')], 'codex', state) + expect(state.rows.map((message) => message.id)).toEqual(['other']) + expect(state.rows[0]?.blocks).toEqual([{ type: 'text', text: 'Another chat' }]) +}) + +it('reveals a retained command reply when paging loads its parent', () => { + const reply = { + ...prose('output', 'context report', 'user'), + parentId: 'command' + } + let state = projectMobileNativeChatMessages([reply], 'openclaude') + expect(state.rows).toEqual([]) + const parent = prose('command', '/context', 'user') + state = projectMobileNativeChatMessages([parent, reply], 'openclaude', state) + expect(state.rows.map((message) => message.id)).toEqual(['output']) + expect(state.rows[0]).toMatchObject({ + role: 'system', + blocks: [{ type: 'text', text: 'context report', presentation: 'command-output' }] + }) + state = projectMobileNativeChatMessages([reply], 'openclaude', state) + expect(state.rows).toEqual([]) + state = projectMobileNativeChatMessages([reply, parent], 'openclaude', state) + expect(state.rows.map((message) => message.id)).toEqual(['output']) + state = projectMobileNativeChatMessages( + [reply, prose('command', '/model', 'user')], + 'openclaude', + state + ) + expect(state.rows.map((message) => [message.id, message.blocks])).toEqual([ + ['command', [{ type: 'text', text: '/model' }]] + ]) +}) + +it('forgets evicted tool contributions and releases generated orphan names', () => { + const reserved = prose('unpaired-tool-results:["a",0]', 'Reserved', 'user') + const a = row('a', 'assistant', [{ type: 'text', text: 'Checking' }, result('missing')]) + const boundary = prose('boundary', 'Next', 'user') + const b = row('b', 'assistant', [call('read')]) + const t = row('t', 'tool', [result('read')]) + let state = projectMobileNativeChatMessages([reserved, a, boundary, b, t], 'claude') + expect(state.rows.map((message) => message.id)).toEqual([ + reserved.id, + 'a', + 'unpaired-tool-results:["a",1]', + 'boundary', + 'b' + ]) + state = projectMobileNativeChatMessages( + [a, boundary, b, t, prose('tail', 'End', 'user')], + 'claude', + state + ) + expect(state.rows.map((message) => message.id)).toEqual([ + 'a', + 'unpaired-tool-results:["a",0]', + 'boundary', + 'b', + 'tail' + ]) + state = projectMobileNativeChatMessages( + [t, prose('tail', 'End', 'user'), prose('new', 'New')], + 'claude', + state + ) + expect(state.rows.map((message) => [message.id, message.blocks])).toEqual([ + ['t', [result('read')]], + ['tail', [{ type: 'text', text: 'End' }]], + ['new', [{ type: 'text', text: 'New' }]] + ]) + const sidecar = row('sidecar', 'user', [ + result('unknown'), + { type: 'text', text: 'Reminder' } + ]) + const lead = prose('lead', 'First') + state = projectMobileNativeChatMessages([lead, sidecar], 'claude') + state = projectMobileNativeChatMessages( + [ + prose('lead', 'Second'), + sidecar, + prose('unpaired-tool-results:["sidecar",0]', 'Reserved', 'user') + ], + 'claude', + state + ) + expect(state.rows.map((message) => message.id)).toEqual([ + 'lead', + 'unpaired-tool-results:["sidecar",1]', + 'unpaired-tool-results:["sidecar",0]' + ]) + expect(state.rows[1]?.blocks).toEqual([result('unknown')]) +}) + +it('places a surviving roster at its new first sibling and recomputes labels', () => { + const sibling = (id: string) => + row(id, 'system', [ + { + type: 'subagent', + id, + groupId: 'group', + label: 'Audit', + state: 'completed' + } + ]) + const first = sibling('one'), + second = sibling('two'), + third = sibling('three') + const middle = prose('middle', 'Between', 'user') + let state = projectMobileNativeChatMessages([first, middle, second, third], 'claude') + state = projectMobileNativeChatMessages([middle, second, third], 'claude', state) + expect(state.rows.map((message) => message.id)).toEqual(['middle', 'two']) + expect(state.rows[1]?.blocks).toEqual([ + { + type: 'subagent-group', + groupId: 'group', + agents: [ + { id: 'two', label: 'Audit', state: 'completed' }, + { id: 'three', label: 'Audit 2', state: 'completed' } + ] + } + ]) +}) + +it('updates live tools, reasoning, sibling outcomes and waiting rows through the phone hooks', () => { + let live = [ + prose('user', 'Inspect', 'user'), + prose('a', 'Checking'), + spawn('s1'), + spawn('s2'), + row('tool', 'assistant', [call('live')]), + { ...prose('child', 'Child'), agentId: 'child' } + ] + const held = { ...prose('held', 'Follow-up', 'user'), queued: true as const } + let current = [...live, held] + let output: readonly NativeChatMessage[] = [] + let scope = 'chat' + const pending = [{ id: 'pending', text: 'Pending', images: ['preview'] }] + function Transcript() { + const folded = useMobileNativeChatProjection(current, 'claude', [scope]) + output = useMobileNativeChatTransientData( + { + folded, + streaming: null, + pending + }, + scope + ) + useMobileNativeChatTurnDisclosure({ + messages: output, + enabled: true, + isWorking: false, + scopeKey: scope + }) + nativeChatTaskListPredecessors(output) + nativeChatDockedTaskList(folded) + return null + } + let renderer: ReturnType + act(() => { + renderer = create(createElement(Transcript)) + }) + live = [ + prose('user', 'Inspect', 'user'), + prose('a', 'Checking now'), + spawn('s1'), + spawn('s2', 'completed'), + row('tool', 'assistant', [call('live', 'completed'), result('live')]), + { ...prose('child', 'Child revised'), agentId: 'child' }, + { ...prose('thought', 'Consider', 'reasoning'), state: 'completed', completedAt: 10 } + ] + current = [...live, { ...held }] + act(() => renderer.update(createElement(Transcript))) + expect(output.map((message) => message.id)).toEqual([ + 'user', + 'a', + 's1', + 'thought', + 'held', + 'pending' + ]) + expect(output[1]?.blocks).toEqual([ + { type: 'text', text: 'Checking now' }, + call('live', 'completed'), + result('live') + ]) + expect(output[2]?.blocks).toEqual([ + { + type: 'subagent-group', + groupId: 'live-group', + agents: [ + { id: 's1', label: 's1', state: 'working' }, + { id: 's2', label: 's2', state: 'completed' } + ] + } + ]) + expect(output[3]).toMatchObject({ + role: 'reasoning', + state: 'completed', + completedAt: 10, + blocks: [{ type: 'text', text: 'Consider' }] + }) + expect(output[4]?.queued).toBe(true) + expect(output[5]?.blocks).toEqual([ + { type: 'text', text: 'Pending' }, + { type: 'image-ref', url: 'preview' } + ]) + scope = 'another-chat' + current = [prose('new', 'New chat')] + act(() => renderer.update(createElement(Transcript))) + expect(output.map((message) => message.id)).toEqual(['new', 'pending']) + act(() => renderer.unmount()) +}) + +it('preserves current delivery facts and synthetic notices when upstream wrappers refresh', () => { + const items: AgentJournalRenderItem[] = [ + { + itemId: 'orca:send', + revision: 1, + sequence: 0, + observedAt: 0, + body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'Prompt' }] } + }, + { + itemId: 'answer', + revision: 1, + sequence: 1, + observedAt: 1, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Checking' }] } + } + ] + const submission: AgentJournalSubmission = { + clientMessageId: 'send', + fence: 1, + payloadFingerprint: 'fingerprint', + dispatchState: 'unknown', + providerItemId: null, + reason: null, + submittedAt: 0, + resolvedAt: null + } + const stopped = new Set(['orca:send']) + const project = (input: AgentJournalRenderItem[], current: AgentJournalSubmission) => + withStopRowsAfterStoppedSends( + projectStructuredAgentSessionMessages(input, [], [current]), + stopped + ) + let state = projectMobileNativeChatMessages(project(items, submission), 'claude') + const next: AgentJournalRenderItem[] = [ + items[0]!, + { + ...items[1]!, + revision: 2, + body: { kind: 'message', role: 'assistant', blocks: [{ type: 'text', text: 'Done' }] } + } + ] + state = projectMobileNativeChatMessages( + project(next, { ...submission, dispatchState: 'pending' }), + 'claude', + state + ) + expect(state.rows.map((message) => message.id)).toEqual([ + 'orca:send', + 'stopped-before-start:orca:send', + 'answer' + ]) + expect(state.rows[0]?.deliveryState).toBe('pending') + expect(state.rows[1]?.role).toBe('system') + expect(state.rows[2]?.blocks).toEqual([{ type: 'text', text: 'Done' }]) +}) diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts new file mode 100644 index 000000000000..0b55a8d777cf --- /dev/null +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-projection.ts @@ -0,0 +1,181 @@ +import type { AgentType } from '../../../../../src/shared/agent-status/contracts/agent-status-types' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import { getVerifiedNativeChatCommands } from '../../../../../src/shared/native-chat/native-chat-agent-profiles' +import { surfaceSkillInvocationUserTurns } from '../../../../../src/shared/native-chat/native-chat-command-envelope' +import { + nativeChatToolFoldKind, + type NativeChatToolFoldKind +} from '../../../../../src/shared/native-chat/tools/native-chat-tool-fold' +import { foldSubagentItems } from '../../../../../src/shared/native-chat/transcript/native-chat-subagent-items' +import { + nativeChatImageTranscriptUnits, + normalizeImageTranscriptUnit +} from '../../../../../src/shared/native-chat/transcript/native-chat-image-transcript-markers' +import { + nativeChatCommandName, + nativeChatCommandOutputParentId, + surfaceNativeChatCommandOutputs +} from '../../../../../src/shared/native-chat/tools/native-chat-command-output' +import { + foldMobileNativeChatMessages, + isMobileNativeChatSource +} from '../mobile-native-chat-render-data' +import { buildMobileNativeChatUnits, type Unit } from './mobile-native-chat-projection-units' + +type Source = { + raw: NativeChatMessage + skill?: NativeChatMessage + parentId?: string | null + parentCommand?: string | null + harness?: NativeChatMessage +} +type ImageUnit = { sources: readonly NativeChatMessage[]; rows: NativeChatMessage[] } +export type MobileNativeChatProjection = { + input: readonly NativeChatMessage[] + agent: AgentType + sources: ReadonlyMap + images: readonly ImageUnit[] + kinds: ReadonlyMap + units: readonly Unit[] + rows: NativeChatMessage[] +} + +type JournalPosition = NonNullable + +function samePosition(left: JournalPosition, right: JournalPosition): boolean { + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Own enumerable keys are used only to compare the same fields on both positions. + const keys = Object.keys(left) as (keyof JournalPosition)[] + return ( + keys.length === Object.keys(right).length && + keys.every((key) => Object.hasOwn(right, key) && Object.is(left[key], right[key])) + ) +} + +function sameSource(left: NativeChatMessage, right: NativeChatMessage): boolean { + if (left === right) { + return true + } + // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: Own enumerable keys are used only to compare the same fields on both messages. + const keys = Object.keys(left) as (keyof NativeChatMessage)[] + return ( + keys.length === Object.keys(right).length && + keys.every((key) => { + if (!Object.hasOwn(right, key)) { + return false + } + if (key === 'journalPosition' || key === 'foldedJournalPosition') { + const a = left[key], + b = right[key] + return Object.is(a, b) || (a != null && b != null && samePosition(a, b)) + } + return Object.is(left[key], right[key]) + }) + ) +} + +function prepareSources( + input: readonly NativeChatMessage[], + agent: AgentType, + previous?: MobileNativeChatProjection +): Map { + const commands = new Set(getVerifiedNativeChatCommands(agent).map((command) => command.name)) + const sources = new Map() + for (const candidate of input) { + const before = previous?.sources.get(candidate.id) + if (before && sameSource(before.raw, candidate)) { + sources.set(candidate.id, before) + continue + } + if (!isMobileNativeChatSource(candidate)) { + sources.set(candidate.id, { raw: candidate }) + continue + } + const skill = surfaceSkillInvocationUserTurns([candidate], commands)[0]! + sources.set(candidate.id, { + raw: candidate, + skill, + parentId: nativeChatCommandOutputParentId(skill) + }) + } + for (const [id, source] of sources) { + if (!source.skill) { + continue + } + const parent = + source.parentId !== null && source.parentId !== undefined + ? sources.get(source.parentId) + : undefined + const parentCommand = parent?.skill ? nativeChatCommandName(parent.skill) : null + const before = previous?.sources.get(id) + if (before?.skill === source.skill && before.parentCommand === parentCommand) { + continue + } + const context = + parent?.skill && parent.skill !== source.skill ? [source.skill, parent.skill] : [source.skill] + sources.set(id, { + ...source, + parentCommand, + harness: surfaceNativeChatCommandOutputs(context, agent)[0]! + }) + } + return sources +} + +/** One disposable generation; unchanged history contributes references, never semantic replay. */ +export function projectMobileNativeChatMessages( + input: readonly NativeChatMessage[], + agent: AgentType, + previous?: MobileNativeChatProjection +): MobileNativeChatProjection { + const ids = new Set(input.map((row) => row.id)) + if (ids.size !== input.length) { + return { + input, + agent, + sources: new Map(), + images: [], + kinds: new Map(), + units: [], + rows: foldMobileNativeChatMessages(input, agent) + } + } + if (previous && (previous.agent !== agent || previous.sources.size !== previous.input.length)) { + previous = undefined + } + if (previous) { + const survivors = [...previous.sources.keys()].filter((id) => ids.has(id)) + let cursor = 0 + if (input.some((row) => previous!.sources.has(row.id) && survivors[cursor++] !== row.id)) { + previous = undefined + } + } + const sources = prepareSources(input, agent, previous) + const harness = [...sources.values()].flatMap((source) => source.harness ?? []) + const oldImages = new Map(previous?.images.map((unit) => [unit.sources[0]!, unit])) + const images = nativeChatImageTranscriptUnits(harness).map((members) => { + const held = oldImages.get(members[0]!) + return held && + held.sources.length === members.length && + held.sources.every((source, index) => source === members[index]) + ? held + : { sources: members, rows: normalizeImageTranscriptUnit(members) } + }) + const grouped = foldSubagentItems(images.flatMap((unit) => unit.rows)) + const kinds = new Map( + grouped.map((source) => [source, previous?.kinds.get(source) ?? nativeChatToolFoldKind(source)]) + ) + const units = buildMobileNativeChatUnits(grouped, kinds, previous) + const unchanged = + previous && + units.length === previous.units.length && + units.every((unit, index) => unit === previous!.units[index]) + return { + input, + agent, + sources, + images, + kinds, + units, + rows: previous && unchanged ? previous.rows : units.flatMap((unit) => unit.rows) + } +} diff --git a/mobile/src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts b/mobile/src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts new file mode 100644 index 000000000000..02e7b20ff2f4 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts @@ -0,0 +1,76 @@ +import { readFileSync } from 'node:fs' +import { expect, it } from 'vitest' +import { projectStructuredItemToNativeChat } from '@orca/test-host/shared/agent-session/view/structured-agent-session-projection' +import { + createNativeChatMerger, + applyAppend +} from '@orca/test-host/shared/native-chat/native-chat-merge' +import { decodeClaudeTranscriptLine } from '@orca/test-host/main/native-chat/transcript-line-decoders-claude' +import { readCodexThreadItem } from '@orca/test-host/main/codex/structured/items/codex-thread-item-identity' +import { codexJournalItem } from '@orca/test-host/main/codex/structured/items/codex-structured-item-translation' +import { projectMobileNativeChatMessages } from '@orca/test-mobile/session/native-chat/transcript/mobile-native-chat-projection' + +it('preserves captured agent output through legacy appends', () => { + const claude = readFileSync( + new URL( + '../../../../../src/main/claude/__fixtures__/claude-adapter-capture-fold.jsonl', + import.meta.url + ), + 'utf8' + ) + .trim() + .split('\n') + .flatMap((line, index) => { + const record = JSON.parse(line) + const message = record.frame + ? decodeClaudeTranscriptLine(JSON.stringify(record.frame), `capture-${index}`) + : null + return message ? [message] : [] + }) + const codex = readFileSync( + new URL( + '../../../../../src/main/codex/__fixtures__/codex-hook-outcomes.jsonl', + import.meta.url + ), + 'utf8' + ) + .trim() + .split('\n') + .flatMap((line, index) => { + const parsed = JSON.parse(line) + const frame = parsed.frame ?? parsed + const item = + frame?.method === 'item/completed' ? readCodexThreadItem(frame.params?.item) : null + const body = item ? codexJournalItem(item).body : null + const message = body + ? projectStructuredItemToNativeChat({ + itemId: `capture-${index}`, + sequence: index, + revision: 1, + observedAt: index, + body + }) + : null + return message ? [message] : [] + }) + for (const [agent, records] of [ + ['claude', claude], + ['codex', codex] + ] as const) { + const merger = createNativeChatMerger() + let state = projectMobileNativeChatMessages([], agent) + for (const message of records) { + const input = applyAppend(merger, [message]) + state = projectMobileNativeChatMessages(input, agent, state) + } + expect(state.rows.at(-1)?.blocks).toEqual([ + { + type: 'text', + text: + agent === 'claude' + ? 'FIRST DONE banana' + : 'The command was blocked by an automatic hook stating “Deploys are frozen,” so it printed nothing.' + } + ]) + } +}) diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-projection.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-projection.ts new file mode 100644 index 000000000000..4fcc2a6ca189 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-projection.ts @@ -0,0 +1,28 @@ +import { useState } from 'react' +import type { AgentType } from '../../../../../src/shared/agent-status/contracts/agent-status-types' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import { projectMobileNativeChatMessages } from './mobile-native-chat-projection' + +export function useMobileNativeChatProjection( + messages: readonly NativeChatMessage[], + agent: AgentType, + scope: readonly unknown[] +): NativeChatMessage[] { + const [state, setState] = useState(() => ({ + scope, + projection: projectMobileNativeChatMessages(messages, agent) + })) + const sameScope = + scope.length === state.scope.length && + scope.every((part, index) => Object.is(part, state.scope[index])) + if (sameScope && state.projection.input === messages && state.projection.agent === agent) { + return state.projection.rows + } + const projection = projectMobileNativeChatMessages( + messages, + agent, + sameScope ? state.projection : undefined + ) + setState({ scope, projection }) + return projection.rows +} diff --git a/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transient-data.ts b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transient-data.ts new file mode 100644 index 000000000000..a99c895969f9 --- /dev/null +++ b/mobile/src/session/native-chat/transcript/use-mobile-native-chat-transient-data.ts @@ -0,0 +1,127 @@ +import { useState } from 'react' +import { + buildMobileNativeChatTransientData, + type MobileNativeChatPendingItem +} from '../mobile-native-chat-render-data' +import type { NativeChatMessage } from '../../../../../src/shared/native-chat/native-chat-types' +import { orderNativeChatDisplayMessages } from '../../../../../src/shared/native-chat/transcript/native-chat-message-order' + +type Input = Parameters[0] +type Preview = { urls: readonly string[]; row: NativeChatMessage } +type Pending = { input: MobileNativeChatPendingItem; row: NativeChatMessage } +export type MobileNativeChatTransientProjection = { + input: Input + previews: ReadonlyMap + pending: ReadonlyMap + stream: NativeChatMessage | undefined + data: NativeChatMessage[] +} + +function sameUrls( + left: readonly string[] | undefined, + right: readonly string[] | undefined +): boolean { + return ( + left === right || + (!!left && + !!right && + left.length === right.length && + left.every((url, index) => url === right[index])) + ) +} + +export function projectMobileNativeChatTransientData( + input: Input, + before?: MobileNativeChatTransientProjection +): MobileNativeChatTransientProjection { + const previews = new Map() + const folded = input.folded.map((source) => { + const urls = input.imagePreviewsByMessageId?.[source.id] + if (source.role !== 'user' || !urls?.length) { + return source + } + const held = before?.previews.get(source) + const preview = + held && sameUrls(held.urls, urls) + ? held + : { + urls, + row: buildMobileNativeChatTransientData({ + ...input, + folded: [source], + streaming: null, + pending: [] + }).folded[0]! + } + previews.set(source, preview) + return preview.row + }) + const pending = new Map() + const transient = input.pending.map((item) => { + const held = before?.pending.get(item.id) + const old = held?.input + const entry = + held && + old && + old.text === item.text && + old.sentAt === item.sentAt && + old.pendingSend === item.pendingSend && + sameUrls(old.images, item.images) + ? held + : { + input: item, + row: buildMobileNativeChatTransientData({ + folded: [], + streaming: null, + pending: [item] + }).data[0]! + } + pending.set(item.id, entry) + return entry.row + }) + const stream = input.streaming + ? before?.input.streaming === input.streaming + ? before.stream + : buildMobileNativeChatTransientData({ folded: [], streaming: input.streaming, pending: [] }) + .data[0] + : undefined + const data = [ + ...folded, + ...orderNativeChatDisplayMessages([...(stream ? [stream] : []), ...transient]) + ] + return { + input, + previews, + pending, + stream, + data: + before && + data.length === before.data.length && + data.every((row, index) => row === before.data[index]) + ? before.data + : data + } +} + +export function useMobileNativeChatTransientData(input: Input, scope: string): NativeChatMessage[] { + const [state, setState] = useState(() => ({ + scope, + projection: projectMobileNativeChatTransientData(input) + })) + const previous = state.projection.input + if ( + state.scope === scope && + input.folded === previous.folded && + input.streaming === previous.streaming && + input.pending === previous.pending && + input.imagePreviewsByMessageId === previous.imagePreviewsByMessageId + ) { + return state.projection.data + } + const projection = projectMobileNativeChatTransientData( + input, + state.scope === scope ? state.projection : undefined + ) + setState({ scope, projection }) + return projection.data +} diff --git a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts index f892c8d9950b..5afe5ef1a453 100644 --- a/mobile/src/session/native-chat/use-mobile-native-chat-session.ts +++ b/mobile/src/session/native-chat/use-mobile-native-chat-session.ts @@ -27,14 +27,8 @@ import { mobileNativeChatTranscriptCache } from './mobile-native-chat-transcript-cache' -export type MobileNativeChatStatus = - | 'idle' - | 'loading' - | 'waiting-session' - // No transcript file yet: render the empty chat while keeping its read unsettled. - | 'awaiting-transcript' - | 'ready' - | 'error' +import type { MobileNativeChatStatus } from './mobile-native-chat-session-status' +export type { MobileNativeChatStatus } from './mobile-native-chat-session-status' export type MobileNativeChatSession = { messages: NativeChatMessage[] diff --git a/mobile/tsconfig.test.json b/mobile/tsconfig.test.json index c051bfdf1d56..e7b4495b25ec 100644 --- a/mobile/tsconfig.test.json +++ b/mobile/tsconfig.test.json @@ -8,6 +8,7 @@ // Outside this RN program: RN's numeric timers and Expo's process.env break the desktop graphs these // tests import. The two roots of tsconfig.test.node.json are checked there against emitted // declarations; the others are legacy runtime-only coverage whose test bodies nothing typechecks. + "src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts", "src/components/WorktreeAgentList.runtime-lineage.test.tsx", "src/components/pr-sidebar/reviewer-picker.target-contract.test.tsx", "src/session/mobile-native-command-discovery.test.tsx", diff --git a/mobile/tsconfig.test.mobile-declarations.json b/mobile/tsconfig.test.mobile-declarations.json index 495873daa63c..24174edca524 100644 --- a/mobile/tsconfig.test.mobile-declarations.json +++ b/mobile/tsconfig.test.mobile-declarations.json @@ -34,7 +34,8 @@ "src/worktree/workspace-list-sections.ts", "src/worktree/worktree-catalog-snapshot-client.ts", "src/worktree/worktree-host-context-labels.ts", - "src/worktree/workspace-view-settings.ts" + "src/worktree/workspace-view-settings.ts", + "src/session/native-chat/transcript/mobile-native-chat-projection.ts" ], "include": ["**/*.d.ts"], "exclude": ["node_modules"] diff --git a/mobile/tsconfig.test.node.json b/mobile/tsconfig.test.node.json index 9b61a72ce7ec..dfc0ed134994 100644 --- a/mobile/tsconfig.test.node.json +++ b/mobile/tsconfig.test.node.json @@ -30,6 +30,7 @@ }, "files": [ "src/components/pr-sidebar/reviewer-picker.target-contract.test.tsx", + "src/session/native-chat/transcript/mobile-native-chat-recorded-projection.test.ts", "../src/types/build-constants.d.ts" ], "include": [], diff --git a/src/shared/native-chat/input/native-chat-task-list-history.ts b/src/shared/native-chat/input/native-chat-task-list-history.ts index 7406247a2ecd..8c447191904d 100644 --- a/src/shared/native-chat/input/native-chat-task-list-history.ts +++ b/src/shared/native-chat/input/native-chat-task-list-history.ts @@ -20,6 +20,22 @@ function taskListFromCall(call: NativeChatToolCallBlock): NativeChatTaskList | n return call.state === 'failed' ? null : normalizeNativeChatTaskList(call.name, call.input) } +type AcceptedTaskCall = { tool: NativeChatTaskListTool; call: NativeChatToolCallBlock } +const acceptedTaskCalls = new WeakMap() + +function taskCalls(message: NativeChatMessage): readonly AcceptedTaskCall[] { + const cached = acceptedTaskCalls.get(message) + if (cached) { + return cached + } + const calls = pairToolBlocks(message.blocks).flatMap(({ call, result }) => { + const tool = call && nativeChatTaskListTool(call.name) + return call && tool && !result?.isError && taskListFromCall(call) ? [{ tool, call }] : [] + }) + acceptedTaskCalls.set(message, calls) + return calls +} + /** Store call identities so unchanged rows stay memoized, while prepends replace their context. */ export function nativeChatTaskListPredecessors( messages: readonly NativeChatMessage[] @@ -31,14 +47,8 @@ export function nativeChatTaskListPredecessors( if (message.role === 'user') { continue } - for (const { call, result } of pairToolBlocks(message.blocks)) { - if (!call || result?.isError) { - continue - } - const tool = nativeChatTaskListTool(call.name) - if (tool && taskListFromCall(call)) { - previous[tool] = call - } + for (const { tool, call } of taskCalls(message)) { + previous[tool] = call } } return history diff --git a/src/shared/native-chat/native-chat-stopped-before-start.ts b/src/shared/native-chat/native-chat-stopped-before-start.ts index 594be08cf11c..d22faca1f0d4 100644 --- a/src/shared/native-chat/native-chat-stopped-before-start.ts +++ b/src/shared/native-chat/native-chat-stopped-before-start.ts @@ -248,6 +248,14 @@ export function keepStoppedSendsInSendOrder( return moved } +const stoppedSendNoticeBlocks: NativeChatMessage['blocks'] = [ + { + type: 'text', + text: NATIVE_CHAT_STOPPED_BEFORE_START_TEXT, + presentation: NATIVE_CHAT_STOPPED_BEFORE_START_PRESENTATION + } +] + /** One row after each run of sends a Stop took back (`stopped`, by id), placed with the last. */ export function withStopRowsAfterStoppedSends( messages: readonly NativeChatMessage[], @@ -262,13 +270,7 @@ export function withStopRowsAfterStoppedSends( role: 'system' as const, source: 'transcript' as const, timestamp: message.timestamp, - blocks: [ - { - type: 'text' as const, - text: NATIVE_CHAT_STOPPED_BEFORE_START_TEXT, - presentation: NATIVE_CHAT_STOPPED_BEFORE_START_PRESENTATION - } - ], + blocks: stoppedSendNoticeBlocks, ...(message.journalPosition ? { journalPosition: message.journalPosition } : {}) } ] diff --git a/src/shared/native-chat/native-chat-work-run.ts b/src/shared/native-chat/native-chat-work-run.ts index b15249903c1b..a377fcf6374c 100644 --- a/src/shared/native-chat/native-chat-work-run.ts +++ b/src/shared/native-chat/native-chat-work-run.ts @@ -10,6 +10,8 @@ import type { NativeChatBlock, NativeChatMessage } from './native-chat-types' * never join one. */ export type NativeChatWorkRunMember = 'lead' | 'tool' | 'thought' +const memberFacts = new WeakMap() + /** Only prose/plain tool activity joins runs; rosters, tasks, questions and approval receipts keep separate rows. scopeIsWorking names the owning turn/subagent’s liveness. */ export function nativeChatWorkRunMember( message: NativeChatMessage, @@ -23,6 +25,15 @@ export function nativeChatWorkRunMember( // Live thinking stays separate; ended thoughts join runs, including textless thoughts that render nothing. return scopeIsWorking && message.state === 'running' ? null : 'thought' } + if (memberFacts.has(message)) { + return memberFacts.get(message)! + } + const member = deriveWorkRunMember(message) + memberFacts.set(message, member) + return member +} + +function deriveWorkRunMember(message: NativeChatMessage): NativeChatWorkRunMember | null { const content = deriveNativeChatRowContent(message.blocks) if ( message.role !== 'assistant' || diff --git a/src/shared/native-chat/tools/native-chat-command-output.ts b/src/shared/native-chat/tools/native-chat-command-output.ts index 25ee39afdd04..ee59a738e617 100644 --- a/src/shared/native-chat/tools/native-chat-command-output.ts +++ b/src/shared/native-chat/tools/native-chat-command-output.ts @@ -9,17 +9,40 @@ import { isTextBlock, type NativeChatMessage } from '../native-chat-types' const LOCAL_COMMAND_STDOUT = /^\s*([\s\S]*?)<\/local-command-stdout>\s*$/ +const commandNames = new WeakMap() + +const userTexts = new WeakMap() + function userText(message: NativeChatMessage): string | null { - return message.role === 'user' && message.blocks.every(isTextBlock) + if (message.role !== 'user') { + return null + } + if (userTexts.has(message.blocks)) { + return userTexts.get(message.blocks)! + } + const text = message.blocks.every(isTextBlock) ? message.blocks.map((block) => block.text).join('\n') : null + userTexts.set(message.blocks, text) + return text } /** The command a user turn's envelope names, without its slash; null for other turns. */ -function envelopeCommand(message: NativeChatMessage): string | null { +export function nativeChatCommandName(message: NativeChatMessage): string | null { + if (commandNames.has(message)) { + return commandNames.get(message)! + } const text = userText(message) const envelope = text === null ? null : parseNativeChatCommandEnvelope(text) - return envelope ? envelope.name.replace(/^\//, '') : null + const name = envelope ? envelope.name.replace(/^\//, '') : null + commandNames.set(message, name) + return name +} + +export function nativeChatCommandOutputParentId(message: NativeChatMessage): string | null { + return message.parentId !== undefined && LOCAL_COMMAND_STDOUT.test(userText(message) ?? '') + ? message.parentId + : null } /** Surface catalog-declared transcript replies as command output, matched by explicit row link. Older unlinked replies or unloaded command rows stay hidden. */ @@ -48,7 +71,7 @@ export function surfaceNativeChatCommandOutputs( } rowsById ??= new Map(messages.map((row) => [row.id, row])) const parent = rowsById.get(message.parentId) - const command = parent ? envelopeCommand(parent) : null + const command = parent ? nativeChatCommandName(parent) : null if (command === null || !transcriptReplies.has(command)) { return message } diff --git a/src/shared/native-chat/tools/native-chat-edit-cards.ts b/src/shared/native-chat/tools/native-chat-edit-cards.ts index bf66bbc426f9..64d0b2d8b9f9 100644 --- a/src/shared/native-chat/tools/native-chat-edit-cards.ts +++ b/src/shared/native-chat/tools/native-chat-edit-cards.ts @@ -95,8 +95,24 @@ const diffSummaries = new WeakMap< } >() +const rowEditSummaries = new WeakMap>() + +export function buildEditSummaries( + blocks: NativeChatBlock[] +): ReadonlyMap< + NativeChatToolCallBlock, + { files: NativeChatEditFileSummary[]; key: string; result: NativeChatToolResultBlock | undefined } +> { + let summaries = rowEditSummaries.get(blocks) + if (!summaries) { + summaries = deriveEditSummaries(blocks) + rowEditSummaries.set(blocks, summaries) + } + return summaries +} + // Only the journal's path-only Diff envelope has counts that can be read without tool normalization. -export function buildEditSummaries(blocks: NativeChatBlock[]): Map< +function deriveEditSummaries(blocks: NativeChatBlock[]): Map< NativeChatToolCallBlock, { files: NativeChatEditFileSummary[] diff --git a/src/shared/native-chat/tools/native-chat-folded-tool-results.ts b/src/shared/native-chat/tools/native-chat-folded-tool-results.ts index c1b8f490210d..93f5f77bcfa2 100644 --- a/src/shared/native-chat/tools/native-chat-folded-tool-results.ts +++ b/src/shared/native-chat/tools/native-chat-folded-tool-results.ts @@ -1,6 +1,8 @@ import { unpairedToolResultIndices } from './native-chat-tool-pairs' import type { NativeChatBlock, NativeChatMessage } from '../native-chat-types' +export type NativeChatOrphanOrigin = { row: NativeChatMessage; sourceId: string } + type ToolContribution = { source: NativeChatMessage blocks: readonly NativeChatBlock[] @@ -13,7 +15,11 @@ type ToolContribution = { export class FoldedToolResultSources { private readonly contributions = new Map() - constructor(private readonly sourceMessages: readonly NativeChatMessage[]) {} + constructor( + private readonly sourceMessages: readonly NativeChatMessage[], + private readonly allocatedIds?: ReadonlySet, + private readonly recordOrphan?: (origin: NativeChatOrphanOrigin) => void + ) {} append( row: number, @@ -82,7 +88,7 @@ export class FoldedToolResultSources { const sourceStillDraws = contribution.sourceRow !== undefined && retained[contribution.sourceRow] !== null const id = sourceStillDraws - ? orphanRowId(contribution.source.id, allocatedIds, occurrences) + ? orphanRowId(contribution.source.id, allocatedIds, occurrences, this.allocatedIds) : contribution.source.id allocatedIds.add(id) const orphan: NativeChatMessage = { @@ -92,6 +98,9 @@ export class FoldedToolResultSources { blocks: orphanBlocks, unpairedToolResults: true } + if (sourceStillDraws) { + this.recordOrphan?.({ row: orphan, sourceId: contribution.source.id }) + } const at = orphans.get(contribution.insertAt) if (at) { at.push(orphan) @@ -112,14 +121,15 @@ export class FoldedToolResultSources { } } -function orphanRowId( +export function orphanRowId( sourceId: string, allocated: ReadonlySet, - occurrences: Map + occurrences: Map, + reserved?: ReadonlySet ): string { let occurrence = occurrences.get(sourceId) ?? 0 let id = `unpaired-tool-results:${JSON.stringify([sourceId, occurrence])}` - while (allocated.has(id)) { + while (allocated.has(id) || reserved?.has(id)) { occurrence += 1 id = `unpaired-tool-results:${JSON.stringify([sourceId, occurrence])}` } diff --git a/src/shared/native-chat/tools/native-chat-tool-fold.ts b/src/shared/native-chat/tools/native-chat-tool-fold.ts index 18ddf011c63b..9975e5868406 100644 --- a/src/shared/native-chat/tools/native-chat-tool-fold.ts +++ b/src/shared/native-chat/tools/native-chat-tool-fold.ts @@ -12,7 +12,10 @@ import { CODEX_PLAN_UPDATED_FRAME_KIND, isWordlessProviderFrameMessage } from '../native-chat-provider-frame-summary' -import { FoldedToolResultSources } from './native-chat-folded-tool-results' +import { + FoldedToolResultSources, + type NativeChatOrphanOrigin +} from './native-chat-folded-tool-results' function isToolOnlyMessage(message: NativeChatMessage): boolean { return ( @@ -76,20 +79,55 @@ function recordFoldedPosition(target: NativeChatMessage, folded: NativeChatMessa } } +export type NativeChatToolFoldKind = + | 'orphan' + | 'sidecar' + | 'tool' + | 'assistant' + | 'pass' + | 'boundary' + +export function nativeChatToolFoldKind(message: NativeChatMessage): NativeChatToolFoldKind { + if (message.unpairedToolResults) { + return 'orphan' + } + if (isHarnessSidecarToolMessage(message)) { + return 'sidecar' + } + if (isToolOnlyMessage(message)) { + return 'tool' + } + if (message.role === 'assistant') { + return 'assistant' + } + return isSubagentRosterMessage(message) || + isBackgroundTaskMessage(message) || + isUndrawnProviderFrameMessage(message) || + (isNoiseMessage(message) && !isInterruptionBoundary(message)) + ? 'pass' + : 'boundary' +} + /** Fold consecutive tool-only messages into their preceding assistant turn. */ -export function foldToolMessages(messages: readonly NativeChatMessage[]): NativeChatMessage[] { +export function foldToolMessages( + messages: readonly NativeChatMessage[], + allocatedIds?: ReadonlySet, + kinds?: ReadonlyMap, + recordOrphan?: (origin: NativeChatOrphanOrigin) => void +): NativeChatMessage[] { const output: NativeChatMessage[] = [] - const sources = new FoldedToolResultSources(messages) + const sources = new FoldedToolResultSources(messages, allocatedIds, recordOrphan) let mutableAssistantIndex = -1 let clonedAssistantIndex = -1 for (const message of messages) { - if (message.unpairedToolResults) { + const kind = kinds?.get(message) ?? nativeChatToolFoldKind(message) + if (kind === 'orphan') { output.push(message) mutableAssistantIndex = -1 clonedAssistantIndex = -1 continue } - if (isHarnessSidecarToolMessage(message) && mutableAssistantIndex >= 0) { + if (kind === 'sidecar' && mutableAssistantIndex >= 0) { const index = mutableAssistantIndex const assistant = output[index] if (assistant?.role === 'assistant') { @@ -108,7 +146,7 @@ export function foldToolMessages(messages: readonly NativeChatMessage[]): Native continue } } - if (isToolOnlyMessage(message) && mutableAssistantIndex >= 0) { + if (kind === 'tool' && mutableAssistantIndex >= 0) { const index = mutableAssistantIndex const assistant = output[index] if (assistant?.role !== 'assistant') { @@ -129,12 +167,7 @@ export function foldToolMessages(messages: readonly NativeChatMessage[]): Native if (message.role === 'assistant') { mutableAssistantIndex = output.length - 1 clonedAssistantIndex = -1 - } else if ( - !isSubagentRosterMessage(message) && - !isBackgroundTaskMessage(message) && - !isUndrawnProviderFrameMessage(message) && - (!isNoiseMessage(message) || isInterruptionBoundary(message)) - ) { + } else if (kind !== 'pass') { mutableAssistantIndex = -1 clonedAssistantIndex = -1 } diff --git a/src/shared/native-chat/transcript/native-chat-image-transcript-markers.ts b/src/shared/native-chat/transcript/native-chat-image-transcript-markers.ts index da994b9f5ccf..e3428fa23473 100644 --- a/src/shared/native-chat/transcript/native-chat-image-transcript-markers.ts +++ b/src/shared/native-chat/transcript/native-chat-image-transcript-markers.ts @@ -25,12 +25,25 @@ export function imageSourcePathFromText(text: string): string | null { return text.match(IMAGE_SOURCE_MARKER)?.[1]?.trim() ?? null } +const imageSourcePaths = new WeakMap() +const imagePromptMarkers = new WeakMap() + /** Source paths only from all-text turns whose every block is an image-source marker. Claude groups multi-image pastes into one turn; * requiring one block misses them, while accepting mixed blocks would hide real prompts. */ export function imageSourcePathsFromMessage(message: NativeChatMessage): string[] { - if (message.role !== 'user' || message.blocks.length === 0) { + if (message.role !== 'user') { return [] } + const cached = imageSourcePaths.get(message.blocks) + if (cached) { + return cached + } + const paths = deriveImageSourcePaths(message) + imageSourcePaths.set(message.blocks, paths) + return paths +} + +function deriveImageSourcePaths(message: NativeChatMessage): string[] { const paths: string[] = [] for (const block of message.blocks) { if (!isTextBlock(block)) { @@ -161,73 +174,85 @@ function stripImagePromptMarkersFromTextBlocks( } export function hasImagePromptMarker(message: NativeChatMessage): boolean { - return message.blocks.some((block) => isTextBlock(block) && IMAGE_PROMPT_MARKER.test(block.text)) + const cached = imagePromptMarkers.get(message.blocks) + if (cached !== undefined) { + return cached + } + const hasMarker = message.blocks.some( + (block) => isTextBlock(block) && IMAGE_PROMPT_MARKER.test(block.text) + ) + imagePromptMarkers.set(message.blocks, hasMarker) + return hasMarker } -/** Claude records image paths as source turns followed by a prompt carrying - * image markers. Merge the whole run back into one native user turn. */ -export function normalizeImageTranscriptMessages( +/** Consecutive source turns and their optional prompt form one preparation dependency. */ +export function nativeChatImageTranscriptUnits( messages: readonly NativeChatMessage[] -): NativeChatMessage[] { - let normalized: NativeChatMessage[] | null = null +): NativeChatMessage[][] { + const units: NativeChatMessage[][] = [] for (let index = 0; index < messages.length; index += 1) { - const message = messages[index]! - if (message.role !== 'user') { - normalized?.push(message) - continue - } - const messageImagePaths = imageSourcePathsFromMessage(message) - if (messageImagePaths.length > 0) { - normalized ??= messages.slice(0, index) - const sourceTurns = [{ message, paths: messageImagePaths }] - let nextIndex = index + 1 - while (nextIndex < messages.length) { - const candidate = messages[nextIndex]! - const candidatePaths = imageSourcePathsFromMessage(candidate) - if ( - candidate.role !== 'user' || - candidate.source !== message.source || - candidatePaths.length === 0 - ) { + const first = messages[index]! + const members = [first] + if (imageSourcePathsFromMessage(first).length > 0) { + while (index + 1 < messages.length) { + const next = messages[index + 1]! + if (next.source !== first.source || imageSourcePathsFromMessage(next).length === 0) { break } - sourceTurns.push({ message: candidate, paths: candidatePaths }) - nextIndex += 1 + members.push(next) + index += 1 } - const prompt = messages[nextIndex] + const prompt = messages[index + 1] if ( prompt?.role === 'user' && - prompt.source === message.source && + prompt.source === first.source && hasImagePromptMarker(prompt) ) { - normalized.push({ - ...prompt, - blocks: [ - ...sourceTurns.flatMap(({ paths }) => - paths.map((path) => ({ type: 'image-ref' as const, path })) - ), - ...stripImagePromptMarkersFromTextBlocks(prompt.blocks) - ] - }) - index = nextIndex - continue - } - for (const sourceTurn of sourceTurns) { - normalized.push({ - ...sourceTurn.message, - blocks: sourceTurn.paths.map((path) => ({ type: 'image-ref' as const, path })) - }) + members.push(prompt) + index += 1 } - index = nextIndex - 1 - continue - } - const blocks = stripImagePromptMarkersFromTextBlocks(message.blocks) - if (blocks === message.blocks) { - normalized?.push(message) - } else { - normalized ??= messages.slice(0, index) - normalized.push({ ...message, blocks }) } + units.push(members) + } + return units +} + +/** Claude records image paths as source turns followed by a prompt carrying + * image markers. Merge the whole run back into one native user turn. */ +export function normalizeImageTranscriptMessages( + messages: readonly NativeChatMessage[] +): NativeChatMessage[] { + const rows = nativeChatImageTranscriptUnits(messages).flatMap(normalizeImageTranscriptUnit) + return rows.length === messages.length && rows.every((row, index) => row === messages[index]) + ? (messages as NativeChatMessage[]) + : rows +} + +export function normalizeImageTranscriptUnit( + messages: readonly NativeChatMessage[] +): NativeChatMessage[] { + const first = messages[0]! + if (imageSourcePathsFromMessage(first).length > 0) { + const last = messages.at(-1)! + const hasPrompt = imageSourcePathsFromMessage(last).length === 0 + const sources = hasPrompt ? messages.slice(0, -1) : messages + const images = (source: NativeChatMessage) => + imageSourcePathsFromMessage(source).map((path) => ({ type: 'image-ref' as const, path })) + return hasPrompt + ? [ + { + ...last, + blocks: [ + ...sources.flatMap(images), + ...stripImagePromptMarkersFromTextBlocks(last.blocks) + ] + } + ] + : sources.map((source) => ({ ...source, blocks: images(source) })) + } + if (first.role !== 'user') { + return messages as NativeChatMessage[] } - return normalized ?? (messages as NativeChatMessage[]) + const blocks = stripImagePromptMarkersFromTextBlocks(first.blocks) + return blocks === first.blocks ? (messages as NativeChatMessage[]) : [{ ...first, blocks }] } diff --git a/src/shared/native-chat/transcript/native-chat-subagent-items.ts b/src/shared/native-chat/transcript/native-chat-subagent-items.ts index 74f32e1775aa..dd5f357fb2ba 100644 --- a/src/shared/native-chat/transcript/native-chat-subagent-items.ts +++ b/src/shared/native-chat/transcript/native-chat-subagent-items.ts @@ -50,18 +50,25 @@ export function subagentFoldKey(block: NativeChatSubagentBlock): string { : JSON.stringify([block.groupId, block.parentId]) } +const subagentBlocks = new WeakMap() + /** The subagent a row is, when it is one: its block, beside nothing but its twin sentence. */ export function subagentItemBlock( message: Pick ): NativeChatSubagentBlock | null { + if (subagentBlocks.has(message.blocks)) { + return subagentBlocks.get(message.blocks)! + } let found: NativeChatSubagentBlock | null = null for (const block of message.blocks) { if (isSubagentBlock(block) && found === null) { found = block } else if (block.type !== 'text') { + subagentBlocks.set(message.blocks, null) return null } } + subagentBlocks.set(message.blocks, found) return found } @@ -72,17 +79,15 @@ const foldedGroups = new WeakMap() const foldedEntries = new WeakMap() /** Fold sibling rows at the first sibling’s position; preserve every unrelated row. */ -export function foldSubagentItems( +export function nativeChatSubagentGroups( messages: readonly NativeChatMessage[] -): readonly NativeChatMessage[] { +): Map { const groups = new Map() - let any = false for (const message of messages) { const block = subagentItemBlock(message) if (block === null) { continue } - any = true const key = subagentFoldKey(block) const siblings = groups.get(key) if (siblings) { @@ -91,7 +96,14 @@ export function foldSubagentItems( groups.set(key, [message]) } } - if (!any) { + return groups +} + +export function foldSubagentItems( + messages: readonly NativeChatMessage[], + groups: ReadonlyMap = nativeChatSubagentGroups(messages) +): readonly NativeChatMessage[] { + if (groups.size === 0) { return messages } const rows = new Map() diff --git a/src/shared/native-chat/transcript/native-chat-turn-fold.ts b/src/shared/native-chat/transcript/native-chat-turn-fold.ts index 24e3b7daafdb..63bc9d352fd5 100644 --- a/src/shared/native-chat/transcript/native-chat-turn-fold.ts +++ b/src/shared/native-chat/transcript/native-chat-turn-fold.ts @@ -34,11 +34,26 @@ export type NativeChatTurnFoldRow = { sendsBack: boolean } +const rowFacts = new WeakMap() + /** How the fold reads a transcript row, with the same derivation the row renders from. */ export function nativeChatTurnFoldRow( message: NativeChatMessage, turnKey: string | undefined, hasReceipt: boolean +): NativeChatTurnFoldRow { + let facts = rowFacts.get(message) + if (!facts) { + facts = deriveTurnFoldRow(message, undefined, false) + rowFacts.set(message, facts) + } + return { ...facts, turnKey, draws: hasReceipt || facts.draws } +} + +function deriveTurnFoldRow( + message: NativeChatMessage, + turnKey: string | undefined, + hasReceipt: boolean ): NativeChatTurnFoldRow { return { turnKey,