Show changed files directly in chat turns (#38256)

* Show changed files directly in chat turns

* Use the fixture frame for the diff interaction

* Keep changed filenames readable and preserve file actions

* Keep unconfirmed file changes in tool activity

* Capture changed files in completed transcript fixtures

* Preserve patch data with authoritative history status

* Keep mobile diff interaction coverage beside its card

* Assert the decoded patch line contract

* Exercise full returned history in catch-up coverage

* test(chat): target file summary when reopening patches
This commit is contained in:
Brennan Benson
2026-11-04 17:53:16 -08:00
committed by GitHub
parent 9661361266
commit e5a960cbf9
56 changed files with 1295 additions and 470 deletions
@@ -0,0 +1,177 @@
import { afterEach, expect, it } from 'vitest'
import { agentJournalItemKey } from '../../../../shared/agent-session/journal/agent-session-journal-item-key'
import { isAdmissibleAgentJournalRenderItem } from '../../../../shared/agent-session/journal/agent-session-journal-schemas'
import type { AgentJournalRenderItem } from '../../../../shared/agent-session/journal/agent-session-journal-types'
import {
EMPTY_STRUCTURED_AGENT_SESSION,
reduceStructuredAgentSession,
type StructuredAgentSessionState
} from '../../../../shared/agent-session/structured-agent-session-reducer'
import { projectStructuredItemsToNativeChat } from '../../../../shared/agent-session/view/structured-agent-session-projection'
import {
nativeChatTurnDiffEditFile,
nativeChatTurnDiffs
} from '../../../../shared/native-chat/tools/native-chat-turn-diffs'
import type { StructuredAgentSessionEventSink } from '../../../native-chat/agent-session-wire/structured-agent-session-event-sink'
import { agentJournalItemForWire } from '../../../native-chat/agent-session-wire/agent-session-item-wire-form'
import {
createCodexHistoryTranslator,
createCodexJournalTranslator
} from '../journal/codex-structured-journal-translation'
import type { CodexStructuredSessionEvent } from '../session-lifecycle/codex-structured-session-state'
const disposers: (() => void)[] = []
afterEach(() => disposers.splice(0).forEach((dispose) => dispose()))
const patch = '@@ -1 +1 @@\n-old\n+new'
// Protocol shape also exercised by codex-structured-reasoning-lifecycle.test.ts; no real CLI run is claimed.
const change = (status?: string) => ({
type: 'fileChange',
id: 'patch',
...(status ? { status } : {}),
changes: [{ path: 'src/app.ts', kind: { type: 'update' }, diff: patch }]
})
function fixture() {
let sequence = 0
let state: StructuredAgentSessionState = { ...EMPTY_STRUCTURED_AGENT_SESSION, epoch: 'epoch' }
const apply = (items: AgentJournalRenderItem[]) => {
state = reduceStructuredAgentSession(state, {
type: 'event',
event: {
type: 'batch',
sessionId: 'session',
batch: {
cursor: { epoch: 'epoch', sequence: ++sequence },
items,
removedItemIds: [],
submissions: []
}
}
})
}
const sink: StructuredAgentSessionEventSink = {
appendItem: (identity, body, options) => {
const itemId = agentJournalItemKey(identity)
const previous = state.items.find((item) => item.itemId === itemId)
apply([
agentJournalItemForWire({
itemId,
body,
revision: (previous?.revision ?? 0) + 1,
sequence: previous?.sequence ?? sequence + 1,
observedAt: options.observedAt ?? 1
}).item
])
},
appendTombstone: () => {},
publish: () => {}
}
const live = createCodexJournalTranslator({ sink, schedule: () => () => {} })
const history = createCodexHistoryTranslator({ sink })
disposers.push(live.dispose, history.dispose)
const send = (method: string, params: unknown) =>
live.handle({
type: 'notification',
sessionId: 'session',
threadId: 'thread',
method,
params
} satisfies CodexStructuredSessionEvent)
const outcome = () => {
const messages = projectStructuredItemsToNativeChat(state.items)
return nativeChatTurnDiffs(
messages,
messages.map(() => 'turn')
).get('turn')
}
return {
live,
history,
send,
outcome,
replay: () => {
const items = state.items.map((item) => {
const restored: unknown = JSON.parse(JSON.stringify(item))
if (!isAdmissibleAgentJournalRenderItem(restored)) {
throw new Error('Journal item failed replay validation')
}
return restored
})
state = reduceStructuredAgentSession(EMPTY_STRUCTURED_AGENT_SESSION, {
type: 'history-page',
page: {
sessionId: 'session',
epoch: 'epoch',
direction: 'tail',
items,
submissions: [],
removedItemIds: [],
hasOlder: false,
hasNewer: false,
liveCursor: { epoch: 'epoch', sequence },
window: {
oldest: null,
newest: null,
nextCursor: { epoch: 'epoch', sequence: 0 }
}
}
})
}
}
}
it('shows one landed patch only after completion, including stream updates and replay revisions', () => {
const f = fixture()
f.send('item/started', { item: change('inProgress') })
expect(f.outcome()).toBeUndefined()
f.send('item/fileChange/outputDelta', {
itemId: 'patch',
delta: '@@ -1 +1 @@\n-stdout\n+not-a-patch'
})
f.send('item/fileChange/patchUpdated', { itemId: 'patch', changes: change().changes })
f.live.flush()
expect(f.outcome()).toBeUndefined()
f.send('item/completed', { item: change('completed') })
f.live.flush()
expect(f.outcome()?.files.map((file) => file.path)).toEqual(['src/app.ts'])
expect(f.outcome()).toMatchObject({ added: 1, removed: 1 })
expect(f.outcome()?.files[0]?.edits).toHaveLength(1)
expect(nativeChatTurnDiffEditFile(f.outcome()!.files[0]!.edits[0]!)).toMatchObject({
path: 'src/app.ts',
added: 1,
removed: 1
})
f.replay()
f.send('item/completed', { item: change('completed') })
expect(f.outcome()?.files[0]?.edits).toHaveLength(1)
expect(f.outcome()).toMatchObject({ added: 1, removed: 1 })
})
it.each(['failed', 'declined', 'inProgress', undefined])(
'never promotes %s changes via a completion wrapper or history import',
(status) => {
const f = fixture()
f.send('item/started', { item: change('inProgress') })
f.send('item/completed', { item: change(status) })
expect(f.outcome()).toBeUndefined()
f.history.restoreThread('thread', {
turns: [{ id: 'turn', status: 'completed', items: [change(status)] }]
})
expect(f.outcome()).toBeUndefined()
f.replay()
expect(f.outcome()).toBeUndefined()
}
)
it('keeps an orphan patch update unconfirmed and settles buffered stdout without a landed file', () => {
const f = fixture()
f.send('item/fileChange/patchUpdated', { itemId: 'patch', changes: change().changes })
f.live.flush()
expect(f.outcome()).toBeUndefined()
f.send('item/started', { item: change('inProgress') })
f.send('item/fileChange/outputDelta', { itemId: 'patch', delta: patch })
f.live.handle({ type: 'ended', sessionId: 'session', reason: 'app-server exited' })
expect(f.outcome()).toBeUndefined()
f.replay()
expect(f.outcome()).toBeUndefined()
})
@@ -92,6 +92,20 @@ function commandItem(item: CodexThreadItem): CodexJournalItem {
}
}
function fileChangeToolCall(item: CodexThreadItem, output?: string): CodexJournalItem {
return {
body: {
kind: 'tool-call',
name: 'apply_patch',
callId: item.id,
input: { changes: item.changes ?? null },
state: codexItemRunState(item),
...(output === undefined ? {} : { output: journalPayload(output) })
},
handled: true
}
}
function fileChangeItem(item: CodexThreadItem): CodexJournalItem {
const changes = Array.isArray(item.changes)
? item.changes.flatMap((change) => {
@@ -101,17 +115,8 @@ function fileChangeItem(item: CodexThreadItem): CodexJournalItem {
return path && diff ? [{ path, diff }] : []
})
: []
if (changes.length === 0) {
return {
body: {
kind: 'tool-call',
name: 'apply_patch',
callId: item.id,
input: { changes: item.changes ?? null },
state: codexItemRunState(item)
},
handled: true
}
if (changes.length === 0 || codexItemRunState(item) !== 'completed') {
return fileChangeToolCall(item)
}
const patch = changes.map((change) => change.diff).join('\n')
return {
@@ -267,13 +272,7 @@ export function codexStreamingJournalItem(item: CodexThreadItem, text: string):
return commandItem({ ...item, aggregatedOutput: text })
}
if (item.type === 'fileChange') {
const path = Array.isArray(item.changes)
? readString(readRecord(item.changes[0]), 'path')
: null
return {
body: { kind: 'diff', path: path ?? 'pending patch', patch: journalPayload(text) },
handled: true
}
return fileChangeToolCall(item, text)
}
if (item.type === 'plan') {
return {
@@ -0,0 +1,89 @@
import { expect, it } from 'vitest'
import { projectStructuredItemsToNativeChat } from '../../../../shared/agent-session/view/structured-agent-session-projection'
import {
nativeChatTurnDiffEditFile,
nativeChatTurnDiffs
} from '../../../../shared/native-chat/tools/native-chat-turn-diffs'
import { chat, turn } from './codex-thread-catch-up-contract-test-fixture'
const patch = '@@ -1 +1 @@\n-old\n+new'
async function savedChange() {
const c = await chat({ now: 1_000 })
const source = (status?: string, changes?: unknown[]) => ({
...turn(1),
items: [
{
type: 'fileChange',
id: 'patch',
...(status === undefined ? {} : { status }),
...(changes === undefined ? {} : { changes })
}
]
})
await c.open([
source('completed', [{ path: 'src/app.ts', kind: { type: 'update' }, diff: patch }])
])
const original = c.journal.snapshot().items.find((item) => item.body.kind === 'diff')!
expect(original.body.kind).toBe('diff')
const current = () => c.journal.snapshot().items.find((item) => item.itemId === original.itemId)!
const outcome = () => {
const messages = projectStructuredItemsToNativeChat(c.journal.snapshot().items)
return nativeChatTurnDiffs(
messages,
messages.map(() => 'turn')
).get('turn')
}
return { c, source, original, current, outcome }
}
it('uses declined history status without losing the patch or resurrecting it on sparse enrichment', async () => {
const f = await savedChange()
await f.c.open([], { returnedTurns: [f.source('declined')], paginate: false })
expect(f.current().body).toMatchObject({
kind: 'tool-call',
name: 'Diff',
input: { path: 'src/app.ts' },
state: 'failed'
})
expect(f.outcome()).toBeUndefined()
const failed = f.current().body
expect(failed.kind === 'tool-call' && failed.output).toEqual(
f.original.body.kind === 'diff' && f.original.body.patch
)
await f.c.open([], { returnedTurns: [f.source()], paginate: false })
expect(f.current().body).toEqual(failed)
expect(f.outcome()).toBeUndefined()
})
it.each(['completed', undefined])(
'retains the saved successful patch for sparse %s history',
async (status) => {
const f = await savedChange()
await f.c.open([], { returnedTurns: [f.source(status)], paginate: false })
expect(f.current().body).toEqual(f.original.body)
expect(f.outcome()).toMatchObject({ added: 1, removed: 1 })
expect(f.outcome()?.files.map((file) => file.path)).toEqual(['src/app.ts'])
expect(f.outcome()?.files[0]?.edits).toHaveLength(1)
}
)
it('retains a sparse pending patch until a new import confirms its application', async () => {
const f = await savedChange()
await f.c.open([], { returnedTurns: [f.source('inProgress')], paginate: false })
expect(f.current().body).toMatchObject({ kind: 'tool-call', name: 'Diff', state: 'running' })
expect(f.outcome()).toBeUndefined()
await f.c.open([], { returnedTurns: [f.source('completed')], paginate: false })
expect(f.current().body).toEqual(f.original.body)
const outcome = f.outcome()!
expect(outcome).toMatchObject({ added: 1, removed: 1 })
expect(outcome.files.map((file) => file.path)).toEqual(['src/app.ts'])
expect(outcome.files[0]?.edits).toHaveLength(1)
expect(nativeChatTurnDiffEditFile(outcome.files[0]!.edits[0]!)).toMatchObject({
path: 'src/app.ts',
lines: [
{ kind: 'del', text: 'old' },
{ kind: 'add', text: 'new' }
]
})
})
@@ -246,9 +246,10 @@ describe('a Codex reasoning row', () => {
for (let index = 2; index <= MAX_CODEX_ACTIVE_ITEMS + 1; index += 1) {
items.handle({ threadId: THREAD_ID, method: 'item/started', params: reasoning(`r-${index}`) })
}
expect(rows.get('orca:codex-item%3Athread-abc%3Apatch-1')).toEqual({
kind: 'status',
text: 'File changes were interrupted before completion.'
expect(rows.get('orca:codex-item%3Athread-abc%3Apatch-1')).toMatchObject({
kind: 'tool-call',
name: 'apply_patch',
state: 'failed'
})
})