Repository navigation
fix(native-chat): reland large structured command results - #17720
Conversation
* fix(native-chat): preserve large structured command results * chore: place native chat validation artifacts under docs * chore: drop stale root package config * fix(native-chat): enforce rebuilt lifecycle append slots --------- Co-authored-by: Merge Sim <sim@local>
|
|
Too many files changed for review (147 files, 100 file limit). Bypass the limit by tagging |
Reland verification statusThe reland is pushed from the reverted
Review/readiness loop is clean. The CI dependency-cycle finding was fixed in Local verification:
Electron/CDP proof:
Prior successful rendered proof from codex-lb: |
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Team Run ID: 📒 Files selected for processing (22)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (8)
Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review. 📝 WalkthroughWalkthroughThe change adds bounded NDJSON framing and Codex record dispatch with oversized-frame recovery. It refactors Codex journal translation into admission-aware collaborators for streams, prompts, generic frames, settlement, and restoration. The journal gains lifecycle-batch rows, settlement deduplication, physical-quota enforcement, bounded payloads, lifecycle reservations, and delegated write components. Structured session handling adds sink backpressure, acquisition generations, provider-exit settlement retry, lease recovery state, and runtime recovery coordination. History pagination preserves complete journal sequence groups. Merge Risk: 🟠 High · up to This PR adds streaming, durable persistence, and restart recovery for large structured command results, but unresolved failure-path issues can drop provider output, leave sessions stuck or falsely settled, corrupt restored journal identities, and expose mixed durable state after an interrupted replacement. The current head is not merge-ready until these correctness and recovery risks are fixed or explicitly accepted. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
Full details: Description checkExplanation The description gives a relevant summary and verification results, but it does not follow the required template. It omits the ELI5, What Changed, Why, Linked Issue, Visual Proof, AI Disclosure, Review, boundary, Notes, and Checklist sections, and it does not provide the required issue link format. Resolution Complete the required template sections. Add an explicit issue reference such as
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 20
🧹 Nitpick comments (7)
src/main/codex/codex-app-server-connection.test.ts (1)
502-503: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the trailing notification so the test matches its name.
The test name says "keeps processing", and line 502 writes a
turn/completednotification for that purpose. Thevi.waitForat line 503 only waits for theitem/completedpush, so the test passes even if the reader stops after the large record. Collect the second method and assert it.♻️ Proposed assertion
- onNotification: (method, params) => { - if (method === 'item/completed') { - completed.push(params) - } - } + onNotification: (method, params) => { + methods.push(method) + if (method === 'item/completed') { + completed.push(params) + } + }child.stdout.write('{"method":"turn/completed","params":{"turn":{"id":"turn-large"}}}\n') - await vi.waitFor(() => expect(completed).toHaveLength(1)) + await vi.waitFor(() => + expect(methods).toEqual(['item/completed', 'turn/completed']) + )Declare
const methods: string[] = []alongsidecompleted.src/main/codex/codex-structured-session-adapter-lifecycle.test.ts (1)
38-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the shared Codex test fixtures into one helper module.
Route,FakeConnection,fakeCodex, andadapterForare duplicated verbatim insrc/main/codex/codex-structured-session-adapter.test.ts, andcodex-structured-session-close.tstests build a third near-identical connection double. Three copies must now track the sameCodexAppServerConnectionshape, includingpauseReadingandresumeReading.Move these fixtures into a shared test helper, for example
src/main/codex/codex-structured-session-test-fixtures.ts, and import them from each test file. A single fixture also makes it cheap to add reading-control doubles once.src/main/codex/codex-structured-journal-translation-settlement.test.ts (1)
101-141: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the duplicated translator test fixtures into one shared module.
deferredTargetandhardWatermarkDeferredhere duplicate the same helpers insrc/main/codex/codex-structured-journal-translation.test.tslines 90-130, andrecorder,manualWindow,notification,TURN_STARTED, andtranslatorWithare duplicated as well. Both suites assert exactqueuedOperationscounts, so the watermark values and the journal mock shape must stay identical. Move these fixtures into one shared test helper module and import them in both suites.src/main/native-chat/agent-session-journal/journal-row-writer.ts (1)
161-171: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the row-to-digest traversal into one helper.
This loop duplicates the traversal added in
journal-compaction.tslines 128-138. Both walkitemrows andlifecycle-batchmutations to collect blob digests.The two sites must stay identical. If they diverge when a new row kind carries bodies, one site leaks blobs and the other prunes a referenced payload. Move the traversal next to
blobDigestsInBodyinjournal-reducer.tsand call it from both places.♻️ Proposed shared helper
Add to
src/main/native-chat/agent-session-journal/journal-reducer.ts:export function journalRowBlobDigests(row: JournalRow, into: Set<string>): void { if (row.kind === 'item') { blobDigestsInBody(row.body, into) return } if (row.kind === 'lifecycle-batch') { for (const mutation of row.mutations) { if (mutation.kind === 'item') { blobDigestsInBody(mutation.body, into) } } } }Then in this file:
const retained = new Set(this.deps.referencedBlobDigests()) for (const row of this.deps.tailRows()) { - if (row.kind === 'item') { - blobDigestsInBody(row.body, retained) - } else if (row.kind === 'lifecycle-batch') { - for (const mutation of row.mutations) { - if (mutation.kind === 'item') { - blobDigestsInBody(mutation.body, retained) - } - } - } + journalRowBlobDigests(row, retained) }src/main/native-chat/agent-session-journal/journal-item-appender.ts (1)
13-14: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winImport the shared contract types instead of re-declaring them.
journal-store-contracts.tsalready definesJournalItemAppendOptionsandJournalBlobInput.journal-store.tsuses those types in the publicappendItemandappendItemWithBlobssignatures. This module declares structurally similar local copies.The copies are assignable today, so the code compiles. If
JournalItemAppendOptionsgains a field,AgentSessionJournal.appendItemaccepts it and this boundary narrows it away without a type error. The field would then never reachjournalItemRowBuilder.Import the contract types to keep the two sides from drifting.
♻️ Proposed change
-import type { JournalAppendResult } from './journal-store-contracts' +import type { + JournalAppendResult, + JournalBlobInput, + JournalItemAppendOptions +} from './journal-store-contracts' import type { JournalRow } from './journal-row-schema' import { appendToolOutputFallback } from './journal-tool-output-fallback' - -type ItemAppendOptions = { fence: number; observedAt?: number; recovered?: true } -type JournalBlob = { digest: string; payload: string }Then replace the local names with
JournalItemAppendOptionsandJournalBlobInputin the constructor dependency type and in both method signatures.src/main/native-chat/agent-session-journal/journal-store.ts (1)
61-61: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the factory re-export and update its importers.
journal-store.tsimportsjournal-store-factory.tsthrough the re-export, whilejournal-store-factory.tsimportsAgentSessionJournalfromjournal-store.ts. This creates a direct module cycle. ImportopenAgentSessionJournalfrom./journal-store-factoryat each call site instead.Source: Linters/SAST tools
src/main/native-chat/agent-session-journal/journal-physical-quota.ts (1)
20-23: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winTolerate a disappearing entry during the size walk.
readdirhandles ENOENT for the directory, but the per-entrylstatdoes not. Journal operations rename durable-write temp files. If an entry disappears between the listing and thelstat, this walk rejects and the caller reports a quota failure instead of a byte total.♻️ Proposed fix to skip vanished entries
let total = 0 for (const entry of entries) { const path = join(directory, entry.name) - total += entry.isDirectory() ? await journalDirectoryBytes(path) : (await lstat(path)).size + if (entry.isDirectory()) { + total += await journalDirectoryBytes(path) + continue + } + total += await lstat(path) + .then((info) => info.size) + .catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code === 'ENOENT') { + return 0 + } + throw error + }) } return total
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 7c93ebb4-b285-4095-91a9-add5c8ad278f
📒 Files selected for processing (140)
src/main/codex/codex-app-server-connection-types.tssrc/main/codex/codex-app-server-connection.test.tssrc/main/codex/codex-app-server-connection.tssrc/main/codex/codex-app-server-frame-size-error.tssrc/main/codex/codex-app-server-record-dispatch.tssrc/main/codex/codex-app-server-record-prefix.tssrc/main/codex/codex-app-server-record-reader.tssrc/main/codex/codex-prompt-registry-bounds.tssrc/main/codex/codex-server-request-disposition.test.tssrc/main/codex/codex-server-request-disposition.tssrc/main/codex/codex-structured-acquisition-window.tssrc/main/codex/codex-structured-item-stream-bounds.tssrc/main/codex/codex-structured-item-stream-contracts.tssrc/main/codex/codex-structured-item-stream-events.tssrc/main/codex/codex-structured-item-streams.tssrc/main/codex/codex-structured-item-translation.test.tssrc/main/codex/codex-structured-item-translation.tssrc/main/codex/codex-structured-journal-contracts.tssrc/main/codex/codex-structured-journal-generic-frames.tssrc/main/codex/codex-structured-journal-items.tssrc/main/codex/codex-structured-journal-limits.tssrc/main/codex/codex-structured-journal-prompts.tssrc/main/codex/codex-structured-journal-settlement.tssrc/main/codex/codex-structured-journal-sink.tssrc/main/codex/codex-structured-journal-translation-restore.tssrc/main/codex/codex-structured-journal-translation-settlement.test.tssrc/main/codex/codex-structured-journal-translation-streams.test.tssrc/main/codex/codex-structured-journal-translation-turn-state.test.tssrc/main/codex/codex-structured-journal-translation-turn-state.tssrc/main/codex/codex-structured-journal-translation-turns.tssrc/main/codex/codex-structured-journal-translation-values.tssrc/main/codex/codex-structured-journal-translation.test.tssrc/main/codex/codex-structured-journal-translation.tssrc/main/codex/codex-structured-notification-retry.tssrc/main/codex/codex-structured-prompt-items.test.tssrc/main/codex/codex-structured-prompt-items.tssrc/main/codex/codex-structured-prompt-replies.test.tssrc/main/codex/codex-structured-prompt-replies.tssrc/main/codex/codex-structured-provider-events.tssrc/main/codex/codex-structured-session-acquire.tssrc/main/codex/codex-structured-session-adapter-lifecycle.test.tssrc/main/codex/codex-structured-session-adapter.test.tssrc/main/codex/codex-structured-session-adapter.tssrc/main/codex/codex-structured-session-close.test.tssrc/main/codex/codex-structured-session-close.tssrc/main/codex/codex-structured-session-options.test.tssrc/main/codex/codex-structured-session-state.tssrc/main/codex/codex-structured-thread-open.test.tssrc/main/codex/codex-structured-thread-open.tssrc/main/codex/codex-turn-ordinals.tssrc/main/daemon/ndjson.test.tssrc/main/daemon/ndjson.tssrc/main/native-chat/agent-session-journal/journal-blob-store.tssrc/main/native-chat/agent-session-journal/journal-compaction.tssrc/main/native-chat/agent-session-journal/journal-corruption-quarantine.tssrc/main/native-chat/agent-session-journal/journal-epoch-controller.tssrc/main/native-chat/agent-session-journal/journal-epoch-replacement.test.tssrc/main/native-chat/agent-session-journal/journal-epoch-replacement.tssrc/main/native-chat/agent-session-journal/journal-epoch-rollover.tssrc/main/native-chat/agent-session-journal/journal-item-appender.tssrc/main/native-chat/agent-session-journal/journal-legacy-import.test.tssrc/main/native-chat/agent-session-journal/journal-legacy-import.tssrc/main/native-chat/agent-session-journal/journal-lifecycle-admission.tssrc/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.tssrc/main/native-chat/agent-session-journal/journal-lifecycle-batch-partition.tssrc/main/native-chat/agent-session-journal/journal-lifecycle-capacity.test.tssrc/main/native-chat/agent-session-journal/journal-lifecycle-capacity.tssrc/main/native-chat/agent-session-journal/journal-log-file.tssrc/main/native-chat/agent-session-journal/journal-open.tssrc/main/native-chat/agent-session-journal/journal-payload-bounds.tssrc/main/native-chat/agent-session-journal/journal-physical-quota.test.tssrc/main/native-chat/agent-session-journal/journal-physical-quota.tssrc/main/native-chat/agent-session-journal/journal-prompt-body-bounds.tssrc/main/native-chat/agent-session-journal/journal-reducer.test.tssrc/main/native-chat/agent-session-journal/journal-reducer.tssrc/main/native-chat/agent-session-journal/journal-row-builders.tssrc/main/native-chat/agent-session-journal/journal-row-schema.test.tssrc/main/native-chat/agent-session-journal/journal-row-schema.tssrc/main/native-chat/agent-session-journal/journal-row-writer-read-only-latch.test.tssrc/main/native-chat/agent-session-journal/journal-row-writer.tssrc/main/native-chat/agent-session-journal/journal-store-contracts.tssrc/main/native-chat/agent-session-journal/journal-store-factory.tssrc/main/native-chat/agent-session-journal/journal-store-open.tssrc/main/native-chat/agent-session-journal/journal-store-schema.test.tssrc/main/native-chat/agent-session-journal/journal-store.test.tssrc/main/native-chat/agent-session-journal/journal-store.tssrc/main/native-chat/agent-session-journal/journal-tool-output-fallback.tssrc/main/native-chat/agent-session-journal/journal-write-guards.tssrc/main/native-chat/agent-session-wire/agent-session-delta-coalescer.test.tssrc/main/native-chat/agent-session-wire/agent-session-delta-coalescer.tssrc/main/native-chat/agent-session-wire/agent-session-history-page-bounds.tssrc/main/native-chat/agent-session-wire/agent-session-history-page.test.tssrc/main/native-chat/agent-session-wire/agent-session-history-page.tssrc/main/native-chat/agent-session-wire/agent-session-journal-batch.tssrc/main/native-chat/agent-session-wire/structured-agent-session-adapter.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-context.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.tssrc/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-recovery.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink-estimate.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-event-sink.tssrc/main/native-chat/agent-session-wire/structured-agent-session-eviction.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-eviction.tssrc/main/native-chat/agent-session-wire/structured-agent-session-handoff.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-holders.tssrc/main/native-chat/agent-session-wire/structured-agent-session-holds.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-holds.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-runtime-state.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-runtime-state.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host-types.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-host.tssrc/main/native-chat/agent-session-wire/structured-agent-session-lease-release.tssrc/main/native-chat/agent-session-wire/structured-agent-session-read-restore.tssrc/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.tssrc/main/native-chat/agent-session-wire/structured-agent-session-refusal-message.tssrc/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.tssrc/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-turns-options.tssrc/main/native-chat/agent-session-wire/structured-agent-session-turns-prompt.tssrc/main/native-chat/agent-session-wire/structured-agent-session-turns.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-turns.tssrc/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.tssrc/main/native-chat/agent-session-wire/structured-tui-transcript-catchup.test.tssrc/main/native-chat/agent-session-wire/unhandled-provider-frame.tssrc/main/runtime/agent-session-lease-transitions.tssrc/main/runtime/agent-session-surface-release-transition.tssrc/main/runtime/structured-agent-session-integration-replay.test.tssrc/main/runtime/structured-agent-session-integration.test.tssrc/main/runtime/structured-agent-session-runtime-exit.test.tssrc/main/runtime/structured-agent-session-runtime.tssrc/shared/agent-session-journal-types.tssrc/shared/agent-session-lease-adjudication.tssrc/shared/agent-session-record.tssrc/shared/main-process-ndjson-framer.ts
Included review availability: Your plan provides up to 10 included reviews per hour; 4 remain after this review.
| if (typeof id === 'number') { | ||
| return { kind: 'response-unknown' } | ||
| } | ||
| if (typeof method === 'string' && properties.some((property) => property.key === 'params')) { |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Align the notification classification with dispatch.
Line 182 requires a top-level params key before it classifies a record as a notification. dispatch in src/main/codex/codex-app-server-record-dispatch.ts (lines 65-68) treats any record that carries only method as a notification and leaves params optional. notify in src/main/codex/codex-app-server-connection.ts also sends { method } with no params.
An oversized record whose only top-level key is a long method string therefore classifies as unknown. rejectOversized then reports frame:oversized-unclassified and calls onProtocolFailure, which terminates the provider process tree instead of dropping one frame. The trigger is narrow, because the method name must exceed the record limit on its own.
♻️ Proposed alignment
- if (typeof method === 'string' && properties.some((property) => property.key === 'params')) {
+ if (typeof method === 'string') {
return { kind: 'notification', method }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (typeof method === 'string' && properties.some((property) => property.key === 'params')) { | |
| if (typeof method === 'string') { |
| input.currentTurnIds.set(input.threadId, new Set([turnId])) | ||
| for (const item of Array.isArray(turn.items) ? turn.items : []) { | ||
| const admission = input.handleItem({ | ||
| threadId: input.threadId, | ||
| method: 'item/completed', | ||
| params: { turnId, item } | ||
| }) | ||
| if (!admission.accepted) { | ||
| return admission | ||
| } | ||
| } | ||
| input.currentTurnIds.delete(input.threadId) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Route restored turn state through CodexJournalActiveTurns instead of mutating its map.
src/main/codex/codex-structured-journal-translation.ts line 64 passes activeTurns.byThread as currentTurnIds. Lines 43 and 54 then write and delete entries directly, so activeCount and retainedBytes are never updated. Two concrete consequences follow:
- If
handleItemrejects at lines 50-51, the function returns while the restored turn stays inbyThread.activeTurns.current(threadId)then reports that stale turn, so later items are keyed to the restored turn id. A laterforgetfor that turn also decrementsactiveCountbelow the true count, which weakens theMAX_CODEX_ACTIVE_TURNSbound added by this change. - Line 43 replaces the thread's set instead of adding to it. A restore on a thread that already has open turns drops those turns from
byThreadwhile the counters still include them.
Pass the CodexJournalActiveTurns instance and use remember/forget, so the bookkeeping stays consistent on every exit path.
🐛 Proposed fix to keep active-turn accounting authoritative
export function restoreCodexJournalThread(input: {
threadId: string
thread: Record<string, unknown>
- currentTurnIds: Map<string, Set<string>>
+ activeTurns: {
+ remember: (threadId: string, turnId: string) => boolean
+ forget: (threadId: string, turnId: string) => void
+ }
ordinals: CodexTurnOrdinals
@@
- input.currentTurnIds.set(input.threadId, new Set([turnId]))
+ if (!input.activeTurns.remember(input.threadId, turnId)) {
+ return { accepted: false, reason: 'backpressure' }
+ }
for (const item of Array.isArray(turn.items) ? turn.items : []) {
const admission = input.handleItem({
threadId: input.threadId,
method: 'item/completed',
params: { turnId, item }
})
if (!admission.accepted) {
+ input.activeTurns.forget(input.threadId, turnId)
return admission
}
}
- input.currentTurnIds.delete(input.threadId)
+ input.activeTurns.forget(input.threadId, turnId)
input.ordinals.forgetTurn(input.threadId, turnId)Update the call site accordingly:
// src/main/codex/codex-structured-journal-translation.ts
restoreThread: (threadId, thread) =>
restoreCodexJournalThread({
threadId,
thread,
activeTurns,
ordinals: items.ordinals,
// ...
})📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| input.currentTurnIds.set(input.threadId, new Set([turnId])) | |
| for (const item of Array.isArray(turn.items) ? turn.items : []) { | |
| const admission = input.handleItem({ | |
| threadId: input.threadId, | |
| method: 'item/completed', | |
| params: { turnId, item } | |
| }) | |
| if (!admission.accepted) { | |
| return admission | |
| } | |
| } | |
| input.currentTurnIds.delete(input.threadId) | |
| if (!input.activeTurns.remember(input.threadId, turnId)) { | |
| return { accepted: false, reason: 'backpressure' } | |
| } | |
| for (const item of Array.isArray(turn.items) ? turn.items : []) { | |
| const admission = input.handleItem({ | |
| threadId: input.threadId, | |
| method: 'item/completed', | |
| params: { turnId, item } | |
| }) | |
| if (!admission.accepted) { | |
| input.activeTurns.forget(input.threadId, turnId) | |
| return admission | |
| } | |
| } | |
| input.activeTurns.forget(input.threadId, turnId) | |
| input.ordinals.forgetTurn(input.threadId, turnId) |
| state.events.shift() | ||
| state.bytes = Math.max(0, state.bytes - pending.bytes) | ||
| } | ||
| if (state.events.length === 0) { | ||
| states.delete(sessionId) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Unbalanced pauseReading/resumeReading accounting in the notification retry queue. enqueue pauses provider reading for every buffered notification, but only fail and clear resume it. The successful-drain path deletes the retry state and returns without resuming, and no test exercises a connection that implements reading control, so the imbalance is invisible to the suite.
src/main/codex/codex-structured-notification-retry.ts#L64-L69: callstate.connection.resumeReading?.()before deleting the state on the successful-drain path, and pause only on the empty-to-non-empty transition inenqueueso pause and resume stay balanced.src/main/codex/codex-structured-session-adapter.test.ts#L262-L296: give the fake connectionpauseReadingandresumeReadingcounters, and assert that reading is resumed after the rejected notification is finally admitted.
📍 Affects 2 files
src/main/codex/codex-structured-notification-retry.ts#L64-L69(this comment)src/main/codex/codex-structured-session-adapter.test.ts#L262-L296
| const restoreAdmission = translator?.restoreThread(opened.threadId, opened.thread ?? {}) | ||
| if (restoreAdmission && !restoreAdmission.accepted) { | ||
| throw new AgentSessionAcquisitionRefusal( | ||
| 'Codex thread history exceeds the bounded restore queue; history was not partially imported.' | ||
| ) | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Check whether restoreThread admits atomically before writing any journal rows.
set -euo pipefail
fd -t f 'codex-structured-journal-translation-restore.ts$' -x ast-grep outline --items all
echo '--- restoreThread implementations ---'
rg -nP --type=ts -C 20 '\brestoreThread\b\s*[:(=]' -g '!**/*.test.ts'
echo '--- restore admission tests ---'
rg -nP --type=ts -C 6 'restoreThread' -g '**/*.test.ts'Repository: stablyai/orca
Length of output: 502
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- scoped repository conventions and learnings ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 \
-type f \( -path '*/conventions/*' -o -path '*/learnings/*' -o -path '*/architecture/*' \) \
-print
echo '--- restore implementation ---'
cat -n src/main/codex/codex-structured-journal-translation-restore.ts
echo '--- translation contracts and callers ---'
rg -n -C 12 'restoreCodexJournalThread|restoreThread|CodexJournalTranslationAdmission' src/main/codex \
-g '*.ts' -g '!*.test.ts'Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- repository-wide convention ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md
echo '--- journal contracts ---'
cat -n src/main/codex/codex-structured-journal-contracts.ts
echo '--- item translator ---'
ast-grep outline src/main/codex/codex-structured-journal-items.ts --items all
cat -n src/main/codex/codex-structured-journal-items.ts
echo '--- sink operations used by item translator ---'
rg -n -C 12 'function (admit|append|publish)|export (function|const)|tryPublish|class' \
src/main/codex/codex-structured-journal-sink.ts \
src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
echo '--- restore tests and relevant test fixtures ---'
rg -n -C 14 'restoreCodexJournalThread|CODEX_RESTORE_MAX|restoreThread|accepted: false|backpressure' \
src/main/codex -g '*.test.ts' -g '*.spec.ts'Repository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo '--- item parser and translation contract ---'
rg -n -C 18 'function readCodexThreadItem|export function readCodexThreadItem|function codexJournalItem|export function codexJournalItem' \
src/main/codex/codex-structured-item-translation.ts
echo '--- sink interface and queue-backed append/publish implementation ---'
sed -n '1,75p' src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
sed -n '175,230p' src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
rg -n -C 18 'tryAppendItem|function publish|class StructuredAgentSessionSinkQueue|submit\(' \
src/main/native-chat/agent-session-wire \
src/main/codex/codex-structured-journal-sink.ts \
-g '*.ts' -g '!*.test.ts'
echo '--- exact restore-related tests, if any ---'
rg -l 'restoreCodexJournalThread|restoreThread|CODEX_RESTORE_MAX_OPERATIONS|CODEX_RESTORE_MAX_BYTES' src/main/codex -g '*.test.ts' -g '*.spec.ts' |
while read -r file; do
echo "### $file"
rg -n -C 10 'restoreCodexJournalThread|restoreThread|CODEX_RESTORE_MAX_OPERATIONS|CODEX_RESTORE_MAX_BYTES' "$file"
doneRepository: stablyai/orca
Length of output: 41519
Make restoreThread atomic before throwing the refusal.
restoreCodexJournalThread processes items sequentially. CodexJournalItems.handle can queue an earlier item before a later malformed item returns accepted: false. The caller then reports that no history was partially imported, although earlier rows can already be queued for journal persistence.
| if (typeof itemKey !== 'string') { | ||
| break | ||
| } | ||
| turn.assigned.delete(itemKey) |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
Do not evict ordinal mappings for active turns.
When the byte cap is exceeded, these branches remove mappings from a live turn. A later frame for the same codexItemId then gets a new ordinal instead of its original ordinal. This can make one active provider item appear as multiple journal items.
Retain active mappings until forgetTurn. If the active-turn budget is full, reject or terminalize new provider items through an admission path instead of changing an existing item identity. Add a regression test that repeats an early item ID after the byte cap is reached.
Also applies to: 95-95
| if (record.lease.settlementRetryRequired) { | ||
| return 'The provider exited, but Orca has not finished settling the terminal chat state. Reopen this chat to retry the settlement.' | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Localize the new settlement refusal message.
Line 21 adds a user-facing string directly. Use an intent-named localization ID with named placeholders. Otherwise, localized builds show this refusal only in English.
Based on learnings: newly added user-facing strings must use intent-named localization IDs with named interpolation placeholders.
Source: Learnings
| await ctx.journal.appendItem( | ||
| { provider: 'orca', clientMessageId: `${input.itemId}#delivery` }, | ||
| { | ||
| kind: 'status', | ||
| text: `Your answer was recorded but the agent did not confirm it: ${ | ||
| error instanceof Error ? error.message : String(error) | ||
| }` | ||
| }, | ||
| { fence: ctx.fence } | ||
| ) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Bound the delivery-failure status text and isolate this append.
The status text interpolates an unbounded provider error message. structured-agent-session-unexpected-exit.ts Line 213 bounds the same kind of row with boundJournalStatusText. If this append exceeds the journal payload bounds and rejects, performPrompt rejects even though the resolution at Line 81 is already durable, so the client sees a failure for an answer that was recorded.
Bound the text and treat this notice as best effort.
🛡️ Proposed fix
} catch (error) {
- await ctx.journal.appendItem(
- { provider: 'orca', clientMessageId: `${input.itemId}`#delivery`` },
- {
- kind: 'status',
- text: `Your answer was recorded but the agent did not confirm it: ${
- error instanceof Error ? error.message : String(error)
- }`
- },
- { fence: ctx.fence }
- )
- ctx.publish()
+ try {
+ await ctx.journal.appendItem(
+ { provider: 'orca', clientMessageId: `${input.itemId}`#delivery`` },
+ {
+ kind: 'status',
+ text: boundJournalStatusText(
+ `Your answer was recorded but the agent did not confirm it: ${
+ error instanceof Error ? error.message : String(error)
+ }`
+ )
+ },
+ { fence: ctx.fence }
+ )
+ ctx.publish()
+ } catch {
+ // The resolution is already durable; the advisory row is best effort.
+ }
}Add the import:
+import { boundJournalStatusText } from '../agent-session-journal/journal-prompt-body-bounds'📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| await ctx.journal.appendItem( | |
| { provider: 'orca', clientMessageId: `${input.itemId}#delivery` }, | |
| { | |
| kind: 'status', | |
| text: `Your answer was recorded but the agent did not confirm it: ${ | |
| error instanceof Error ? error.message : String(error) | |
| }` | |
| }, | |
| { fence: ctx.fence } | |
| ) | |
| try { | |
| await ctx.journal.appendItem( | |
| { provider: 'orca', clientMessageId: `${input.itemId}#delivery` }, | |
| { | |
| kind: 'status', | |
| text: boundJournalStatusText( | |
| `Your answer was recorded but the agent did not confirm it: ${ | |
| error instanceof Error ? error.message : String(error) | |
| }` | |
| ) | |
| }, | |
| { fence: ctx.fence } | |
| ) | |
| ctx.publish() | |
| } catch { | |
| // The resolution is already durable; the advisory row is best effort. | |
| } |
| } catch { | ||
| await ctx.journal.releaseLifecycleCapacity(dispatchReservationId(input.clientMessageId)) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Release the tentative turn reservation when both resolutions fail.
This branch runs when resolveDispatch fails twice. It releases only the dispatch reservation. The tentative turn reservation stays held.
No later code path can release it. The dispatch state was never persisted, so the submission stays pending. Lines 100-105 then return that pending submission for every subsequent performSend call with the same clientMessageId, and the retryUnknown branch is unreachable, because existing.dispatchState never becomes unknown. The session permanently loses JOURNAL_TURN_TERMINAL_RESERVATION_BYTES and one lifecycle append slot.
🛠️ Proposed fix to release both reservations
} catch {
await ctx.journal.releaseLifecycleCapacity(dispatchReservationId(input.clientMessageId))
+ await ctx.journal.releaseLifecycleCapacity(
+ tentativeTurnReservationId(input.clientMessageId)
+ )
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| } catch { | |
| await ctx.journal.releaseLifecycleCapacity(dispatchReservationId(input.clientMessageId)) | |
| } | |
| } catch { | |
| await ctx.journal.releaseLifecycleCapacity(dispatchReservationId(input.clientMessageId)) | |
| await ctx.journal.releaseLifecycleCapacity( | |
| tentativeTurnReservationId(input.clientMessageId) | |
| ) | |
| } |
| recoveryChain = recoveryChain.then(async () => { | ||
| try { | ||
| await host?.handleAdapterEvent(event) | ||
| } catch (error) { | ||
| deps.onError?.({ scope: `structured-agent-session-exit:${event.sessionId}`, error }) | ||
| } | ||
| }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
#!/bin/bash
# Description: Find callers that supply onError to the structured agent session runtime.
set -euo pipefail
rg -nP -C 8 'ensureStructuredAgentSessionHost\s*\(' --type=ts
rg -nP -C 4 'onError:\s*\(\s*\{\s*scope' --type=tsRepository: stablyai/orca
Length of output: 151
🏁 Script executed:
#!/bin/bash
set -euo pipefail
printf '%s\n' '--- repository conventions and learnings ---'
find /tmp/coderabbit-repo-knowledge/stablyai/orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print 2>/dev/null | sort | head -80
printf '%s\n' '--- runtime implementation ---'
sed -n '80,185p' src/main/runtime/structured-agent-session-runtime.ts
printf '%s\n' '--- directly bound symbols and callers ---'
rg -n -C 5 'ensureStructuredAgentSessionHost|stopStructuredAgentSessionRuntime|onError' src/main/runtime/structured-agent-session-runtime.ts src --glob '*.ts' --glob '!**/node_modules/**' | head -300Repository: stablyai/orca
Length of output: 196
🏁 Script executed:
#!/bin/bash
set -u
printf '%s\n' '--- repository conventions and learnings ---'
find /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4 -maxdepth 2 -type f -name '*.md' -print 2>/dev/null | sort | head -80
printf '%s\n' '--- runtime implementation ---'
sed -n '80,185p' src/main/runtime/structured-agent-session-runtime.ts
printf '%s\n' '--- directly bound symbols and callers ---'
rg -n -C 5 'ensureStructuredAgentSessionHost|stopStructuredAgentSessionRuntime|onError' src/main/runtime/structured-agent-session-runtime.ts src --glob '*.ts' --glob '!**/node_modules/**' | head -300Repository: stablyai/orca
Length of output: 33038
🏁 Script executed:
#!/bin/bash
set -u
printf '%s\n' '--- applicable repository conventions ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/repo-wide.md
printf '%s\n' '--- src/main convention ---'
cat /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/conventions/src-main-daemon.md
printf '%s\n' '--- runtime continuation ---'
sed -n '185,270p' src/main/runtime/structured-agent-session-runtime.ts
printf '%s\n' '--- exact runtime-related onError wiring ---'
rg -n -C 8 'ensureStructuredAgentSessionHost|StructuredAgentSessionRuntimeDeps|structured-agent-session.*onError|onError.*structured-agent' src --glob '*.ts' --glob '!**/*.test.ts' | head -300Repository: stablyai/orca
Length of output: 29875
Guard deps.onError in the exit-recovery callback.
StructuredAgentSessionRuntimeDeps.onError is caller-supplied and may throw. That throw rejects recoveryChain. stopStructuredAgentSessionRuntime awaits this chain before its try/finally, so it can skip flushAllStreamedEvents. Later exit callbacks chain onto the rejected promise and do not run recovery. Apply the same try/catch protection used by the orphan-reaper path.
| } | ||
| const completeBytes = Buffer.byteLength(complete, 'utf8') | ||
| if (pausedCompleteInputBytes + completeBytes > maxQueuedCompleteInputBytes) { | ||
| pausedCompleteInputOverflowed = true |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Clear the overflow latch when the consumer resumes.
Line 105 permanently sets pausedCompleteInputOverflowed. After one paused queue exceeds its limit, every later pause drops complete valid records because queuePausedCompleteInput returns at line 100. Reset this flag when resume() transitions out of the paused state.
Proposed fix
resume(): void {
if (options.shouldPause?.() || (pendingInput === null && pausedCompleteInputBytes === 0)) {
return
}
+ pausedCompleteInputOverflowed = false
const input = pendingInput|
Follow-up: after the factory/import-cycle fix, local |
…ession (#17813) A frame the classifier declines (status-chrome, suppressed-benign, stream-into-item) is deliberately not journaled. #17720 turned that null translation into `{accepted: false, reason: 'untranslated'}`, which is not `backpressure`, so the notification retry queue treated it as unreplayable and escalated through fail() -> forceCloseUnexpected -> connection.close(). The app-server latched `closing` and the create path's next model/list rejected with "codex app-server connection is closed (model/list)". The provider emits `remoteControl/status/changed` right after initialize, so every structured Codex session died on its first chrome frame. Admit the null translation instead, before any bookkeeping or publish. Also restore the error-frame exemption from the generic row cap, dropped by the same PR: the cap now runs after the classification check, so a noisy turn can no longer reduce provider errors to a suppression count. The test that pinned the capped behavior is inverted to assert the exemption. Co-authored-by: Merge Sim <sim@local>
…#17930) * fix(native-chat): keep the attachments on a Claude turn that pasted images (#17801) * fix(native-chat): keep the attachments on a Claude turn that pasted images A Claude turn carrying pasted images reached native chat with no images at all — no thumbnails on mobile, and not even an attachment chip on desktop. Nothing showed that the message had any. Both carriers were being dropped: - Claude records the paths in a companion turn marked `isMeta`, holding one `[Image: source: <path>]` text block per image. The decoder treats an `isMeta` user row as injected, filters it down to tool-result blocks, and returns null when none remain — so the whole row went away. - The prompt row's own `image` blocks are `{source: {type: 'base64'}}`, which carry no url or path, so `imageRefBlock` drops them too. With the companion gone, `isImageSourceUserTurn` could never fire and the fold in `normalizeImageTranscriptMessages` was unreachable on the Claude path. Surveying every transcript under `~/.claude/projects`: 238 of 241 image-source rows are `isMeta`, across every versioned release (2.1.220 through 2.1.237); the 3 that are not carry no version field at all. 38 of those rows hold more than one content block, which also defeated the single-block rule in `isImageSourceUserTurn`. Let image-source text survive the injected-turn filter, and recognize a turn whose blocks are *all* markers rather than only a lone one. An ordinary injected turn (a skill preamble, a compact summary) is still dropped, and a turn that mixes prose with a marker is still not an image-source turn. Carrying the paths keeps the payload small; decoding the base64 instead would put hundreds of KB per image on the wire to mobile. * fix(native-chat): preserve image companion ordering * fix(native-chat): keep image companions turn-local --------- Co-authored-by: Merge Sim <sim@local> * fix(native-chat): stop unjournaled provider frames from killing the session (#17813) A frame the classifier declines (status-chrome, suppressed-benign, stream-into-item) is deliberately not journaled. #17720 turned that null translation into `{accepted: false, reason: 'untranslated'}`, which is not `backpressure`, so the notification retry queue treated it as unreplayable and escalated through fail() -> forceCloseUnexpected -> connection.close(). The app-server latched `closing` and the create path's next model/list rejected with "codex app-server connection is closed (model/list)". The provider emits `remoteControl/status/changed` right after initialize, so every structured Codex session died on its first chrome frame. Admit the null translation instead, before any bookkeeping or publish. Also restore the error-frame exemption from the generic row cap, dropped by the same PR: the cap now runs after the classification check, so a noisy turn can no longer reduce provider errors to a suppression count. The test that pinned the capped behavior is inverted to assert the exemption. Co-authored-by: Merge Sim <sim@local> * refactor(mobile): split session and terminal surfaces (cherry picked from commit f129f29) * fix(mobile): restore session parity after extraction (cherry picked from commit 47706a5) * chore(mobile): prune stale max-lines overrides (cherry picked from commit be954c3663409116f34ba08658876262733b3f67) * fix(mobile): honor host-follow tab snapshots (cherry picked from commit a4a9c4da19d6967eceb8025dd01480a56261039f) * fix(mobile): keep split session hooks render-pure Documents the pre-existing render-time refs the split relocated onto changed lines, and drops a ref assignment the split added that the monolith never had. * fix(agent-send-target): acknowledge delivery even when picker closes bef (#17835) Delivery callbacks and telemetry belong to the completed send operation, not to the picker instance that launched it. Remove early returns that skipped delivery acknowledgment and success toast when the popover was already closed. * fix(mobile-native-chat): retire an image echo glued with the send beside it (#17783) * fix(mobile-native-chat): retire an image echo glued with the send beside it A message sent with images could render two or three times over, with the copy carrying the photos sorting below the reply that answered it — and it never cleared. A send issued while the agent is mid-turn is glued onto the agent's input line with any send adjacent to it, so the pair lands as one transcript row whose text is the concatenation. Every retirement path then declined the pair: - The image matcher wanted the whole row to equal the echo's text, so a glued row never bound. That also stranded the local preview: the phone's photo never reached the authoritative row. - The exact-count path skips image echoes by design. - The glue path excluded image echoes too, which made one a *barrier* — splitting the run so the text-only send beside it was left alone, and a lone match is rejected as an ordinary landing. So neither echo could ever retire, and the unmatched image echo fell through to the trailing bucket, which is what put it below the reply. Match a glued row in the image matcher, and let an image echo take part in the glue pass once its preview has been rebound. It stays a barrier while unbound, so the existing guarantee is kept: an image echo never retires before its local preview reaches the transcript row, or the photo would disappear. * fix(mobile-chat): require image provenance for glued prefix matches --------- Co-authored-by: Merge Sim <sim@local> * refactor(renderer): split oversized UI surfaces (cherry picked from commit da89be4) * fix(renderer): keep split imports lint-clean (cherry picked from commit c778ac7) * fix(renderer): preserve extracted lifecycle and retention behavior (cherry picked from commit 1731f2a) * chore(max-lines): prune refactored file suppressions (cherry picked from commit 787228e) * fix(status-bar): preserve Git refresh ordering after split (cherry picked from commit e65d298) * fix(lint): preserve TaskPage effect suppressions after split (cherry picked from commit 4a3bc23) * fix(status-bar): preserve workspace-space review and agent freshness (cherry picked from commit 9455e31) * fix(automations): preserve Escape drill-out behavior (cherry picked from commit 790680d) * fix(renderer): restore worktree palette behavior after split (cherry picked from commit 0b78c1c) * style(renderer): format palette project candidates (cherry picked from commit 1e93d66) * refactor(renderer): finish worktree palette extraction (cherry picked from commit ea8e6e5) * fix(renderer): document intentional render-time refs (cherry picked from commit 6fc78dd) * chore(max-lines): prune stale lifecycle baseline (cherry picked from commit 42bf3eb) * fix(renderer): preserve status localization parity (cherry picked from commit 0a802c7) * fix(renderer): preserve floating editor visibility (cherry picked from commit bcf715b) * fix(automations): preserve destination form save semantics (cherry picked from commit a793b07) * fix(renderer): preserve Codex sign-in behavior (cherry picked from commit 81f4803) * fix(renderer): preserve palette create telemetry (cherry picked from commit b13c2b1) * style(renderer): format extracted palette modules * refactor(automations): extract list toolbar and drop dead list projection * fix(lint): drop unused exhaustive-deps suppression after split The split's dependency list no longer trips the rule, so the directive is dead and the changed-code quality gate rejects it. * fix(renderer): document pre-split render-time refs in workspace search Both assignments are verbatim from the pre-split monolith; the split relocated them onto changed lines, which the React Doctor gate scans. * refactor(renderer): split runtime and store modules (cherry picked from commit 207bef0) * fix(renderer): merge split runtime imports (cherry picked from commit 90bf505) * chore(max-lines): prune runtime baseline entries (cherry picked from commit 08820a4) * fix(renderer): preserve accepted visibility snapshots (cherry picked from commit bc5f8a5ac5b8e8ad3fc59250795842e663bad0ee) * refactor(preload): split bridge API modules (cherry picked from commit b77e318) * test(preload): census split GitHub bridge owners (cherry picked from commit cd08e4e) * fix(preload): merge split plugin imports (cherry picked from commit 682ff4f) * chore(max-lines): prune preload baseline entry (cherry picked from commit aad2e1e) * fix(pty,remote): close the pty master fd leak and two remote-terminal defects #8362: node-pty leaves the forkpty()/posix_openpt() master without FD_CLOEXEC, so on Linux every later child of the process -- both later pty children and plain child_process spawns -- inherits it and keeps the /dev/pts device alive. Measured on Linux with stock node-pty 1.1.0: master fd flags 0404002 (cloexec=false), and 17 -> /dev/pts/ptmx present in both a later pty child's /proc/self/fd and a later child_process child's. Extend the existing node-pty patch with pty_cloexec() on both PtyFork spawn paths; after the patch the flags read 02404002 (cloexec=true) and neither child sees the master. This covers the app and terminal daemon only -- the SSH relay installs node-pty from npm on the remote host, so it stays exposed (see the report). #8414: the inspection queue's fire-and-forget `.finally()` chain re-raised a rejecting inspection as a renderer-global unhandledrejection, which an unreachable runtime produced on every cadence tick. #9194: `tab_not_found` is the host's definitive "no such tab", but the close path cleared the close intent for it exactly like a dropped connection, so a host that keeps republishing the dead surface re-materialized the pane the user just closed. Keep that intent and drop its TTL. Also route the banner's "Remote terminal was closed." line through translate() so it stops mixing English into a localized banner. * fix(pty): retire the node-pty master fd instead of probing around it node-pty hands the master to libuv, which closes it on EIO/EOF, but `_close()` never invalidated `_fd` and neither `resize()` nor the `process` getter consulted anything. A late ioctl therefore addressed whatever the kernel had since reissued that number to. On Linux the very next pty gets it: resizing an exited handle silently resized an unrelated live pane, with no error for #17832's probe-retry-classify to observe. Retire `_fd` in the same block that gives up the master and guard both fd-addressed syscalls on it, so a stale handle is unreachable by construction. The relay's resize keeps the isProcessAlive-proven retirement — still the only evidence of `exited` — and drops the re-probe-and-classify arm the ioctl no longer needs. Windows is unaffected: WindowsTerminal.resize goes through the conpty agent and reads no fd. * fix(pty): retire the write stream's fd copy too, and keep the resize re-probe Two gaps in the fd-retirement change. `CustomWriteStream` is the third fd-addressed surface and takes its own plain-number copy of the master at spawn, so `Terminal._fd = -1` never reaches it. Its `dispose()` only cleared a pending immediate, and it was called from `destroy()` alone — the EIO/EOF read-error path and the socket `'close'` path both reach `_close()` without it. A residual `_writeQueue` and an in-flight `fs.write` therefore kept addressing the number after libuv gave it up. Retire the copy and drop the queue in `dispose()`, and call it from `_close()`. Restore the relay's catch-block re-probe. It was never redundant with the patch: libuv closes the fd synchronously inside `uv_close`, before the JS `'close'` that runs `_close()`, so the reuse window opens ahead of any JS guard; and a relay host installs node-pty from npm, where the patch is not applied at all. The re-probe is a `process.kill(pid, 0)` on a path already inside an exception handler. Both existing resize tests pinned liveness with a constant mock, which is why the deletion passed CI invisibly; the new case is alive at the pre-probe and gone by the time the ioctl throws. Also adds the patch's first upstream reference: microsoft/node-pty#220 named this mechanism in 2018 and was closed 2025-12-19 as completed after only improving the error message; #827 is still open. Tracked as #18109. * test(pty): release the live pty before the next fd-reuse case The new Linux write case killed its live pty without awaiting the exit, so that master was still open when the next case spawned. Linux hands out the lowest free descriptor, so the retired pty got N+1 while the leaked N closed during the 400ms settle -- and `does not name a live pty foreground process off the retired descriptor` then saw its live pty take N, failing its own reuse premise by exactly one (`expected 22 to be 23` on CI, reproduced as 19/20 in a container). Test isolation, not a Linux behavior difference: with the descriptor released the case passes 8/8. Await the exit like the resize case above already does, and switch the payload command to `sleep 1` -- the line discipline echoes a leaked write back on its own, so nothing has to read it. Note the constraint on the block so the next case does not repeat it. The premise assertion stays as it is. It compares two observed descriptors, not a hardcoded number; relaxing it to "differs from the retired one" would let both reuse cases pass vacuously on a kernel that never reissues, which is the whole thing they exist to demonstrate. Verified with vitest under node:24-bookworm against a source-built patched node-pty: 7 passed, 8 runs, no flake. Negative check in the same container -- reverting the `_close()` -> `dispose()` hook fails the case with `expected 'leak\r\n' not to contain 'leak'`, so the rewritten assertion is still load-bearing. --------- Co-authored-by: Brennan Benson <[email protected]> Co-authored-by: Merge Sim <sim@local> Co-authored-by: Jinjing <[email protected]>
…7720) * fix(native-chat): preserve large structured command results (stablyai#17707) * fix(native-chat): preserve large structured command results * chore: place native chat validation artifacts under docs * chore: drop stale root package config * fix(native-chat): enforce rebuilt lifecycle append slots --------- Co-authored-by: Merge Sim <sim@local> * chore: omit native-chat reland planning docs * fix(native-chat): remove journal store import cycle * fix(native-chat): keep journal factory acyclic --------- Co-authored-by: Merge Sim <sim@local>
…ession (stablyai#17813) A frame the classifier declines (status-chrome, suppressed-benign, stream-into-item) is deliberately not journaled. stablyai#17720 turned that null translation into `{accepted: false, reason: 'untranslated'}`, which is not `backpressure`, so the notification retry queue treated it as unreplayable and escalated through fail() -> forceCloseUnexpected -> connection.close(). The app-server latched `closing` and the create path's next model/list rejected with "codex app-server connection is closed (model/list)". The provider emits `remoteControl/status/changed` right after initialize, so every structured Codex session died on its first chrome frame. Admit the null translation instead, before any bookkeeping or publish. Also restore the error-frame exemption from the generic row cap, dropped by the same PR: the cap now runs after the classification check, so a noisy turn can no longer reduce provider errors to a suppression count. The test that pinned the capped behavior is inverted to assert the exemption. Co-authored-by: Merge Sim <sim@local>




Summary
Reland the native-chat large structured command result fix from #17707 after revert #17719.
Verification
pnpm tc:nodepassed.