Skip to content

fix(native-chat): reland large structured command results - #17720

Merged
brennanb2025 merged 4 commits into
mainfrom
brennanb2025/reland-native-chat-large-results
Aug 31, 2026
Merged

brennanb2025 merged 4 commits into
mainfrom
brennanb2025/reland-native-chat-large-results

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 46 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​6939 $\color{#cf222e}{\Huge{\mathbf{−}}}$​943 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​5996
Prod 101 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​7378 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1508 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​5870

Summary

Reland the native-chat large structured command result fix from #17707 after revert #17719.

  • Preserves large structured command results through bounded framing, streaming, journal persistence, and restore.
  • Includes the lifecycle append-slot rebuild regression fix and coverage.
  • Does not include unrelated package configuration cleanup.

Verification

  • Native-chat/journal/codex/runtime test suites: 7,967 passed, 19 skipped.
  • pnpm tc:node passed.
  • Changed-code quality: 0 new findings across 140 changed files.
  • Electron/CDP verification and screenshots are being attached separately.

brennanb2025 and others added 2 commits August 31, 2026 12:37
* 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>
@pullfrog

pullfrog Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor
  • Checkout PR fix(native-chat): reland large structured command results #17720 and read complete diff
  • Triage: understand domain, seams, contracts touched
  • Read PR summary snapshot and investigate surrounding code
  • Dispatch reviewfrog specialists for unresolved questions
  • Aggregate findings and draft review
  • Update PR summary snapshot file
  • Submit review

Pullfrog  | View workflow run | via Pullfrog | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@greptile-apps

greptile-apps Bot commented Aug 31, 2026 •

Copy link
Copy Markdown

Too many files changed for review (147 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Reland verification status

The reland is pushed from the reverted main and intentionally excludes:

  • docs/native-chat-large-result-plan.md
  • docs/native-chat-large-result-electron-evidence.md
  • unrelated .npmrc cleanup

Review/readiness loop is clean. The CI dependency-cycle finding was fixed in 35814cb29e by moving openAgentSessionJournal into journal-store.ts and retaining the factory module as a re-export.

Local verification:

  • Focused native-chat/journal/wire/runtime tests: 204 passed.
  • pnpm tc:node passed.
  • pnpm run check:code-quality:changed: 0 new findings.
  • Final readiness/performance pass: no proven in-scope issues.

Electron/CDP proof:

  • The supervised Grok CDP run attached to the intended worktree and captured the rendered UI. The isolated profile could not start the Codex app-server because credentials were unavailable, so the live 2 MiB interaction is recorded as environment-blocked in this run.
  • Prior codex-lb Electron verification of this same implementation measured a 2 MiB structured result (2,097,152 bytes), confirmed the raw payload was not dumped into chat, and confirmed a same-chat follow-up completed normally.

00-empty-app-before.png

01-codex-launch-error.png

Prior successful rendered proof from codex-lb:

native-chat-large-result

@coderabbitai

coderabbitai Bot commented Aug 31, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Team

Run ID: 39ef6071-8e14-4553-92d2-c48105626fd4

📥 Commits

Reviewing files that changed from the base of the PR and between 3ff618a and c041bee.

📒 Files selected for processing (22)
  • src/main/native-chat/agent-session-journal/journal-crash-boundary.test.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.test.ts
  • src/main/native-chat/agent-session-journal/journal-legacy-import.test.ts
  • src/main/native-chat/agent-session-journal/journal-log-file.test.ts
  • src/main/native-chat/agent-session-journal/journal-physical-quota.test.ts
  • src/main/native-chat/agent-session-journal/journal-store-schema.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-recovery.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-handoff.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-read-restore.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-send-idempotency.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-subscribers.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-turns.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-wire-admission.test.ts
  • src/main/native-chat/agent-session-wire/structured-tui-transcript-catchup.test.ts
  • src/main/runtime/structured-agent-session-integration-replay.test.ts
  • src/main/runtime/structured-agent-session-integration.test.ts
💤 Files with no reviewable changes (1)
  • src/main/native-chat/agent-session-journal/journal-store.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • src/main/native-chat/agent-session-wire/structured-agent-session-handoff.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.ts
  • src/main/runtime/structured-agent-session-integration-replay.test.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.test.ts
  • src/main/native-chat/agent-session-journal/journal-physical-quota.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.test.ts
  • src/main/native-chat/agent-session-journal/journal-legacy-import.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The 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 c041b

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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.89% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 143 functions across 72 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning 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… Complete the required template sections. Add an explicit issue reference such as Fixes #17707``, provide visual proof or write N/A with a reason, document testing and platforms, complete the AI Disclosure and Agent skill upstream boundary…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the main change: relanding the native-chat fix for large structured command results.
Full details: Description check

Explanation

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 Fixes #17707``, provide visual proof or write N/A with a reason, document testing and platforms, complete the AI Disclosure and Agent skill upstream boundary sections, address the Notes items, and complete the Checklist.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 20

🧹 Nitpick comments (7)
src/main/codex/codex-app-server-connection.test.ts (1)

502-503: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the trailing notification so the test matches its name.

The test name says "keeps processing", and line 502 writes a turn/completed notification for that purpose. The vi.waitFor at line 503 only waits for the item/completed push, 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[] = [] alongside completed.

src/main/codex/codex-structured-session-adapter-lifecycle.test.ts (1)

38-125: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the shared Codex test fixtures into one helper module.

Route, FakeConnection, fakeCodex, and adapterFor are duplicated verbatim in src/main/codex/codex-structured-session-adapter.test.ts, and codex-structured-session-close.ts tests build a third near-identical connection double. Three copies must now track the same CodexAppServerConnection shape, including pauseReading and resumeReading.

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 win

Extract the duplicated translator test fixtures into one shared module.

deferredTarget and hardWatermarkDeferred here duplicate the same helpers in src/main/codex/codex-structured-journal-translation.test.ts lines 90-130, and recorder, manualWindow, notification, TURN_STARTED, and translatorWith are duplicated as well. Both suites assert exact queuedOperations counts, 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 win

Extract the row-to-digest traversal into one helper.

This loop duplicates the traversal added in journal-compaction.ts lines 128-138. Both walk item rows and lifecycle-batch mutations 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 blobDigestsInBody in journal-reducer.ts and 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 win

Import the shared contract types instead of re-declaring them.

journal-store-contracts.ts already defines JournalItemAppendOptions and JournalBlobInput. journal-store.ts uses those types in the public appendItem and appendItemWithBlobs signatures. This module declares structurally similar local copies.

The copies are assignable today, so the code compiles. If JournalItemAppendOptions gains a field, AgentSessionJournal.appendItem accepts it and this boundary narrows it away without a type error. The field would then never reach journalItemRowBuilder.

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 JournalItemAppendOptions and JournalBlobInput in 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 win

Remove the factory re-export and update its importers.

journal-store.ts imports journal-store-factory.ts through the re-export, while journal-store-factory.ts imports AgentSessionJournal from journal-store.ts. This creates a direct module cycle. Import openAgentSessionJournal from ./journal-store-factory at 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 win

Tolerate a disappearing entry during the size walk.

readdir handles ENOENT for the directory, but the per-entry lstat does not. Journal operations rename durable-write temp files. If an entry disappears between the listing and the lstat, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 894ed75 and 3ff618a.

📒 Files selected for processing (140)
  • src/main/codex/codex-app-server-connection-types.ts
  • src/main/codex/codex-app-server-connection.test.ts
  • src/main/codex/codex-app-server-connection.ts
  • src/main/codex/codex-app-server-frame-size-error.ts
  • src/main/codex/codex-app-server-record-dispatch.ts
  • src/main/codex/codex-app-server-record-prefix.ts
  • src/main/codex/codex-app-server-record-reader.ts
  • src/main/codex/codex-prompt-registry-bounds.ts
  • src/main/codex/codex-server-request-disposition.test.ts
  • src/main/codex/codex-server-request-disposition.ts
  • src/main/codex/codex-structured-acquisition-window.ts
  • src/main/codex/codex-structured-item-stream-bounds.ts
  • src/main/codex/codex-structured-item-stream-contracts.ts
  • src/main/codex/codex-structured-item-stream-events.ts
  • src/main/codex/codex-structured-item-streams.ts
  • src/main/codex/codex-structured-item-translation.test.ts
  • src/main/codex/codex-structured-item-translation.ts
  • src/main/codex/codex-structured-journal-contracts.ts
  • src/main/codex/codex-structured-journal-generic-frames.ts
  • src/main/codex/codex-structured-journal-items.ts
  • src/main/codex/codex-structured-journal-limits.ts
  • src/main/codex/codex-structured-journal-prompts.ts
  • src/main/codex/codex-structured-journal-settlement.ts
  • src/main/codex/codex-structured-journal-sink.ts
  • src/main/codex/codex-structured-journal-translation-restore.ts
  • src/main/codex/codex-structured-journal-translation-settlement.test.ts
  • src/main/codex/codex-structured-journal-translation-streams.test.ts
  • src/main/codex/codex-structured-journal-translation-turn-state.test.ts
  • src/main/codex/codex-structured-journal-translation-turn-state.ts
  • src/main/codex/codex-structured-journal-translation-turns.ts
  • src/main/codex/codex-structured-journal-translation-values.ts
  • src/main/codex/codex-structured-journal-translation.test.ts
  • src/main/codex/codex-structured-journal-translation.ts
  • src/main/codex/codex-structured-notification-retry.ts
  • src/main/codex/codex-structured-prompt-items.test.ts
  • src/main/codex/codex-structured-prompt-items.ts
  • src/main/codex/codex-structured-prompt-replies.test.ts
  • src/main/codex/codex-structured-prompt-replies.ts
  • src/main/codex/codex-structured-provider-events.ts
  • src/main/codex/codex-structured-session-acquire.ts
  • src/main/codex/codex-structured-session-adapter-lifecycle.test.ts
  • src/main/codex/codex-structured-session-adapter.test.ts
  • src/main/codex/codex-structured-session-adapter.ts
  • src/main/codex/codex-structured-session-close.test.ts
  • src/main/codex/codex-structured-session-close.ts
  • src/main/codex/codex-structured-session-options.test.ts
  • src/main/codex/codex-structured-session-state.ts
  • src/main/codex/codex-structured-thread-open.test.ts
  • src/main/codex/codex-structured-thread-open.ts
  • src/main/codex/codex-turn-ordinals.ts
  • src/main/daemon/ndjson.test.ts
  • src/main/daemon/ndjson.ts
  • src/main/native-chat/agent-session-journal/journal-blob-store.ts
  • src/main/native-chat/agent-session-journal/journal-compaction.ts
  • src/main/native-chat/agent-session-journal/journal-corruption-quarantine.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-controller.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.test.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-replacement.ts
  • src/main/native-chat/agent-session-journal/journal-epoch-rollover.ts
  • src/main/native-chat/agent-session-journal/journal-item-appender.ts
  • src/main/native-chat/agent-session-journal/journal-legacy-import.test.ts
  • src/main/native-chat/agent-session-journal/journal-legacy-import.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-admission.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-batch-appender.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-batch-partition.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-capacity.test.ts
  • src/main/native-chat/agent-session-journal/journal-lifecycle-capacity.ts
  • src/main/native-chat/agent-session-journal/journal-log-file.ts
  • src/main/native-chat/agent-session-journal/journal-open.ts
  • src/main/native-chat/agent-session-journal/journal-payload-bounds.ts
  • src/main/native-chat/agent-session-journal/journal-physical-quota.test.ts
  • src/main/native-chat/agent-session-journal/journal-physical-quota.ts
  • src/main/native-chat/agent-session-journal/journal-prompt-body-bounds.ts
  • src/main/native-chat/agent-session-journal/journal-reducer.test.ts
  • src/main/native-chat/agent-session-journal/journal-reducer.ts
  • src/main/native-chat/agent-session-journal/journal-row-builders.ts
  • src/main/native-chat/agent-session-journal/journal-row-schema.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-schema.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer-read-only-latch.test.ts
  • src/main/native-chat/agent-session-journal/journal-row-writer.ts
  • src/main/native-chat/agent-session-journal/journal-store-contracts.ts
  • src/main/native-chat/agent-session-journal/journal-store-factory.ts
  • src/main/native-chat/agent-session-journal/journal-store-open.ts
  • src/main/native-chat/agent-session-journal/journal-store-schema.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.test.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-journal/journal-tool-output-fallback.ts
  • src/main/native-chat/agent-session-journal/journal-write-guards.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-delta-coalescer.ts
  • src/main/native-chat/agent-session-wire/agent-session-history-page-bounds.ts
  • src/main/native-chat/agent-session-wire/agent-session-history-page.test.ts
  • src/main/native-chat/agent-session-wire/agent-session-history-page.ts
  • src/main/native-chat/agent-session-wire/agent-session-journal-batch.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-adapter.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-context.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-flow.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-attach-orchestration.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-recovery.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-estimate.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink-queue.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-event-sink.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-eviction.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-eviction.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-handoff.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-holders.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-holds.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-holds.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-handoff.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-runtime-state.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-runtime-state.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host-types.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-host.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-lease-release.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-read-restore.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-recovery-resolution.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-refusal-message.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-settlement-retry.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-surface-lifetime.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-turns-options.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-turns-prompt.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-turns.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-turns.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.test.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-unexpected-exit.ts
  • src/main/native-chat/agent-session-wire/structured-tui-transcript-catchup.test.ts
  • src/main/native-chat/agent-session-wire/unhandled-provider-frame.ts
  • src/main/runtime/agent-session-lease-transitions.ts
  • src/main/runtime/agent-session-surface-release-transition.ts
  • src/main/runtime/structured-agent-session-integration-replay.test.ts
  • src/main/runtime/structured-agent-session-integration.test.ts
  • src/main/runtime/structured-agent-session-runtime-exit.test.ts
  • src/main/runtime/structured-agent-session-runtime.ts
  • src/shared/agent-session-journal-types.ts
  • src/shared/agent-session-lease-adjudication.ts
  • src/shared/agent-session-record.ts
  • src/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')) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.

Suggested change
if (typeof method === 'string' && properties.some((property) => property.key === 'params')) {
if (typeof method === 'string') {

Comment on lines +43 to +54
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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 handleItem rejects at lines 50-51, the function returns while the restored turn stays in byThread. activeTurns.current(threadId) then reports that stale turn, so later items are keyed to the restored turn id. A later forget for that turn also decrements activeCount below the true count, which weakens the MAX_CODEX_ACTIVE_TURNS bound 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 byThread while 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.

Suggested change
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)

Comment on lines +64 to +69
state.events.shift()
state.bytes = Math.max(0, state.bytes - pending.bytes)
}
if (state.events.length === 0) {
states.delete(sessionId)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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: call state.connection.resumeReading?.() before deleting the state on the successful-drain path, and pause only on the empty-to-non-empty transition in enqueue so pause and resume stay balanced.
  • src/main/codex/codex-structured-session-adapter.test.ts#L262-L296: give the fake connection pauseReading and resumeReading counters, 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

Comment on lines +163 to +168
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.'
)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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"
  done

Repository: 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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🗄️ 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

Comment on lines +20 to +22
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.'
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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

Comment on lines +99 to +108
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 }
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
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.
}

Comment on lines +173 to +175
} catch {
await ctx.journal.releaseLifecycleCapacity(dispatchReservationId(input.clientMessageId))
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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.

Suggested change
} catch {
await ctx.journal.releaseLifecycleCapacity(dispatchReservationId(input.clientMessageId))
}
} catch {
await ctx.journal.releaseLifecycleCapacity(dispatchReservationId(input.clientMessageId))
await ctx.journal.releaseLifecycleCapacity(
tentativeTurnReservationId(input.clientMessageId)
)
}

Comment on lines +166 to +172
recoveryChain = recoveryChain.then(async () => {
try {
await host?.handleAdapterEvent(event)
} catch (error) {
deps.onError?.({ scope: `structured-agent-session-exit:${event.sessionId}`, error })
}
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 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=ts

Repository: 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 -300

Repository: 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 -300

Repository: 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 -300

Repository: 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Follow-up: after the factory/import-cycle fix, local pnpm run audit:code-quality:native is clean and the repository-wide CI lint phase reports no errors. The required static-analysis job still exits nonzero on an existing warning in src/main/providers/agent-foreground-process-batch.test.ts (no-duplicate-imports), which is outside this PR’s diff; I am leaving that unrelated baseline untouched. All completed platform smoke, packaging, cross-version, typecheck, and test-shard checks are passing; the latest matrix is still finishing.

@brennanb2025
brennanb2025 merged commit 872bd51 into main Aug 31, 2026
30 of 32 checks passed
brennanb2025 added a commit that referenced this pull request Sep 1, 2026
…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>
nwparker added a commit that referenced this pull request Sep 2, 2026
…#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]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant