Repository navigation
fix(native-chat): a failed cleanup when reopening a chat never refuses the send - #26554
brennanb2025 wants to merge 2 commits into
Conversation
…s the send Reopening a chat corrected leftover "working" rows from a previous run by appending revisions, and awaited them without a catch, so a failed cleanup append became "this chat's history couldn't be loaded" and the user's send was refused. The open now shows the safe lost-contact reading derived from existing rows, attempts each correction individually and logs failures, and retries on later opens or activity; a newer revision or history supersedes the correction. Genuinely unreadable history still refuses. Co-Authored-By: OpenAI Codex gpt-6.1-sol <[email protected]> Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review round 1 follow-ups for the open-cleanup fix: - A client resuming from a cursor while the reopen verdict is still unwritten gets a fresh snapshot, which rebuilds its subagent roster. The equal-revision reconnect refresh could not reach that roster, so it is reverted and the stop-note refresh is back to main. - Drop the read-side projection of raw rows; no reader takes item bodies from them. - Project only the items the cleanup write can address, so nothing is shown settled that is never written. - Log a failing cleanup once per item, not on every retry. - Tests: background-task case, cursor resubscribe before and after the write, and a send through the host that reopens the chat while the write fails.
Review summaryThe problem. When Orca reopened a chat whose saved history still listed subagents or background tasks as running (the app had restarted mid-run), it first saved a "status unavailable" correction for them. That save had no error handling, so if it failed (for example the database stayed locked past its 5-second wait, a disk error, or a full disk), the chat refused to open. The user saw "Orca couldn't open this chat's history right now." and could neither read the chat nor send in it. User-facing change. The chat now always opens when its history is readable. Old subagents and background tasks show "status unavailable" (not running) straight away, and messages send. The correction is saved later. Nothing new appears on screen. What review changed (head
Deferred (minor):
No failure was found in normal use that hits only this correction save and keeps hitting it. Verified:
Not verified: Windows, Linux, a real SSH host, a phone or older client reconnecting during the failure window, and a real (not injected) database failure. |
Walkthrough
Merge Risk:
|
There was a problem hiding this comment.
Actionable comments posted: 2
ℹ️ Review info
⚙️ Run configuration
- Configuration used: Repository UI
- Review profile: CHILL
- Plan: Advanced
- Run ID:
4e048a0b-77ee-4dda-908c-600b902fb495
📒 Files selected for processing (8)
src/main/native-chat/agent-session-journal/journal-open-cleanup.test.tssrc/main/native-chat/agent-session-journal/journal-reopened-live-work.tssrc/main/native-chat/agent-session-journal/journal-store-collaborators.tssrc/main/native-chat/agent-session-journal/journal-store-open.tssrc/main/native-chat/agent-session-journal/journal-store-restore.tssrc/main/native-chat/agent-session-journal/journal-store.tssrc/main/native-chat/agent-session-wire/structured-agent-session-send-preparation.test.tssrc/main/native-chat/agent-session-wire/structured-agent-session-subscribers.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.
| afterCommit(): void { | ||
| for (const [itemId, entry] of this.reopened) { | ||
| if (!this.matchesReopenedItem(itemId, entry)) { | ||
| this.reopened.delete(itemId) | ||
| } | ||
| } | ||
| if (this.reopened.size > 0) { | ||
| void (this.pending ?? Promise.resolve()).then(() => this.settle()) | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
sed -n '1,150p' src/main/native-chat/agent-session-journal/journal-reopened-live-work.ts
rg -n 'async close|close\(\)|markClosed|stale live-work cleanup skipped' src/main/native-chat/agent-session-journalRepository: stablyai/orca
Length of output: 14917
🏁 Script executed:
set -e
printf '%s\n' '--- journal-store close and surrounding lifecycle ---'
nl -ba src/main/native-chat/agent-session-journal/journal-store.ts | sed -n '130,205p'
printf '%s\n' '--- journal-write-queue implementation ---'
nl -ba src/main/native-chat/agent-session-journal/journal-write-queue.ts | sed -n '1,150p'
printf '%s\n' '--- journal-item-appender implementation ---'
nl -ba src/main/native-chat/agent-session-journal/journal-item-appender.ts | sed -n '1,110p'
printf '%s\n' '--- close and cleanup tests ---'
nl -ba src/main/native-chat/agent-session-journal/journal-open-cleanup.test.ts | sed -n '70,240p'
printf '%s\n' '--- close/error identifiers in the journal subtree ---'
rg -n -F --glob '*.ts' -- 'journal_closed' src/main/native-chat/agent-session-journal || test "$?" -eq 1
rg -n -F --glob '*.ts' -- 'stale live-work cleanup skipped' src/main/native-chat/agent-session-journal || test "$?" -eq 1Repository: stablyai/orca
Length of output: 18934
🏁 Script executed:
nl -ba src/main/native-chat/agent-session-journal/journal-write-guards.ts | sed -n '1,100p'
rg -n -F --glob '*.ts' -- 'instanceof AgentSessionJournalError' src/main/native-chat/agent-session-journalRepository: stablyai/orca
Length of output: 2483
Treat journal_closed as expected cleanup cancellation.
afterCommit() can run its deferred retry after close() marks the queue closed. The queue rejects with journal_closed, and persist() logs stale live-work cleanup skipped for an expected lifecycle event. Handle this error as cancellation and remove the entry. A separate close check is not required.
Suggested fix
import { AGENT_JOURNAL_THREAD_SCOPE } from '../../../shared/agent-session-journal-types'
+import { AgentSessionJournalError } from './journal-write-guards'
import type { JournalLoad } from './journal-open'
@@
} catch (error) {
+ if (error instanceof AgentSessionJournalError && error.code === 'journal_closed') {
+ this.reopened.delete(itemId)
+ continue
+ }
// Retries ride every later commit; only the first failure is worth a log line.| it('accepts a send whose reopen cannot write the cleanup of a stale subagent roster', async () => { | ||
| await loseOwner() | ||
| expect(host.hasSession(SESSION)).toBe(false) | ||
| const database = openTestJournalHostDatabase(root) | ||
| const previous = await openAgentSessionJournal({ | ||
| identity: { | ||
| sessionId: SESSION, | ||
| workspaceId: LOCATION.workspaceId, | ||
| hostId: LOCATION.executionHostId, | ||
| agent: 'codex', | ||
| providerHandle: codexProviderHandle(THREAD) | ||
| }, | ||
| database | ||
| }) | ||
| await previous.appendItem( | ||
| codexSubagentGroupIdentity('group-1'), | ||
| codexSubagentGroupBody('group-1', [{ id: 'child-1', label: 'Read', state: 'working' }]), | ||
| { fence: 0, turnScope: AGENT_JOURNAL_THREAD_SCOPE } | ||
| ) | ||
| await previous.close() | ||
| database.db.exec(` | ||
| CREATE TRIGGER fail_roster_cleanup BEFORE INSERT ON journal_rows | ||
| WHEN NEW.row_json LIKE '%unverifiable%' | ||
| BEGIN SELECT RAISE(ABORT, 'roster cleanup unavailable'); END; | ||
| `) | ||
| const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) | ||
|
|
||
| await accept(sendParams('after the cleanup failed')) | ||
|
|
||
| const roster = (await host.journalSnapshot(SESSION)).items.find( | ||
| (item) => item.body.kind === 'message' && item.body.blocks.some(isSubagentGroupBlock) | ||
| ) | ||
| expect(JSON.stringify(roster?.body)).toContain('"state":"unverifiable"') | ||
| database.db.exec('DROP TRIGGER fail_roster_cleanup') | ||
| warn.mockRestore() | ||
| }) | ||
|
|
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
🔎 Supported by static analysis
🏁 Script executed:
rg -n 'restoreMocks|mockReset|clearMocks|vi\.restoreAllMocks|setupFiles' vitest.config.* vite.config.* package.json src/main/native-chat/agent-session-wire/structured-agent-session-send-preparation.test.tsRepository: stablyai/orca
Length of output: 269
🏁 Script executed:
set -u
printf '%s\n' '--- candidate configuration/setup files ---'
rg --files -g '*vitest*' -g '*vite*' -g '*setup*' -g 'package.json' -g '*.config.*' | sort
printf '%s\n' '--- relevant references ---'
rg -n -F --glob '*.ts' --glob '*.tsx' --glob '*.js' --glob '*.mjs' --glob '*.cjs' --glob '*.json' \
-e 'restoreMocks' -e 'mockReset' -e 'clearMocks' -e 'vi.restoreAllMocks' -e 'setupFiles' \
-e 'afterEach' -e 'beforeEach' \
. || test "$?" -eq 1
printf '%s\n' '--- target test teardown and imports ---'
target='src/main/native-chat/agent-session-wire/structured-agent-session-send-preparation.test.ts'
if test -f "$target"; then
nl -ba "$target" | sed -n '1,125p;200,270p'
else
printf 'missing target: %s\n' "$target"
fiRepository: stablyai/orca
Length of output: 45668
🏁 Script executed:
printf '%s\n' '--- root package test scripts ---'
python3 - <<'PY'
import json
from pathlib import Path
p = Path('package.json')
data = json.loads(p.read_text())
for k, v in data.get('scripts', {}).items():
if 'vitest' in str(v) or 'test' in k.lower():
print(f'{k}: {v}')
PY
printf '%s\n' '--- config/vitest.config.ts ---'
nl -ba config/vitest.config.ts | sed -n '1,260p'
printf '%s\n' '--- config/scripts/run-vitest.mjs ---'
nl -ba config/scripts/run-vitest.mjs | sed -n '1,300p'
printf '%s\n' '--- root config references ---'
rg -n -F --glob 'config/**' --glob 'package.json' \
-e 'restoreMocks' -e 'mockReset' -e 'clearMocks' -e 'vi.restoreAllMocks' -e 'setupFiles' -e 'vitest.setup' \
. || test "$?" -eq 1Repository: stablyai/orca
Length of output: 13351
Restore the console spy in afterEach.
If the assertion before warn.mockRestore() throws, the console.warn spy remains active because the Vitest configuration does not enable automatic mock restoration. The trigger uses this test's unique database directory, so it does not affect later tests.
🐛 Suggested fix
afterEach(async () => {
await host.flushAllStreamedEvents()
+ vi.restoreAllMocks()
await rm(root, { recursive: true, force: true })
})
ELI5
When Orca restarts while an agent in a chat still has subagents or background tasks running, the chat's saved history keeps saying that work is "running". The next time the chat is opened, Orca first saves a correction ("status unavailable": Orca lost contact, it can't tell whether the work finished). If saving that correction failed, Orca treated the whole chat as unopenable: the chat showed "Orca couldn't open this chat's history right now." and every message was refused with "Your message was not sent. Try again." The user was locked out of a chat whose history was perfectly readable, because of a bookkeeping write.
Now a failed correction never blocks the chat. The chat opens, the old subagents show "status unavailable" (not running), and new messages send. Orca saves the correction later.
What Changed
Before (user): a stale "running" subagent + a failed correction write = the chat can't be read, and nothing can be sent until the write happens to succeed on a later attempt.
After (user): the chat opens and sends normally. Old subagents and background tasks show "status unavailable" right away, whether or not the correction is saved yet. Nothing new appears on screen: no notices, labels or settings.
Mechanism:
awaitthe correction writes with no error handling, so a failed write failed the open (journal-store-open.ts). That code now hands off to a small per-chat helper,JournalReopenedLiveWork(journal-reopened-live-work.ts), which never throws.staleSubagentRosterRevisions). It shows the corrected state in the chat's in-memory view straight away, so screens, history pages and anything that continues a subagent list all see "status unavailable".Why
When the failure happens: no failure in normal use was found that hits only this correction and keeps hitting it. The real causes are temporary: the database stays locked past its 5-second wait, a disk error, or a full disk. On main any of these made the chat unreadable, even just to read history, until a later open happened to succeed.
Design (the correction for interrupted work is stored as an ordinary new event, so incremental readers receive it in their normal stream). Differences:
No temporary differences.
Linked Issue
Maintainer work from the chat-write audit (a send was refused by internal bookkeeping); no pre-existing issue.
Visual Proof
A hidden test copy of Orca with a fake model. The chat's saved history holds a subagent still marked "working", and the correction save is forced to fail with a temporary SQLite trigger in that test profile.
Before (base

5252884a9c7): the chat can't be read and the send is refused.After (this PR), same setup: the chat opens, the subagent shows "status unavailable", and the message sends and gets a reply.


After, once the failure is removed: the next send also saves the correction (the database gains revision 2 of that row with the child "unverifiable"); the screen is unchanged and the subagent list still shows one entry.

Testing
I manually tested these changes locally (hidden macOS test app driven over CDP; before/after above)
Automated tests added/updated
journal-open-cleanup.test.ts: chat opens and accepts a message while the correction save fails; one log line across retries; the save lands after a later write; background-task case; a reconnecting client gets a fresh copy only while the correction is unsaved; the correction is worked out again on the next open; a newer row cancels it. All fail on the base code.structured-agent-session-send-preparation.test.ts: a real send through the host succeeds when reopening the chat can't save the correction. On the base code it gets the "couldn't open history" refusal.Related journal, history, subscriber and stop-note suites pass. The Node typecheck passes. The repo's static checks pass (22/22). CI is green.
Platforms: macOS only. The change is shared main-process TypeScript with no paths, processes or platform APIs. Remote hosts over SSH run the same code; this was not exercised on Windows, Linux or a real SSH host.
Review
Reviewed in rounds by independent reviewers (journal correctness, delivery to clients, architecture challenge), then a readiness checklist. See the review comment for what was fixed, deferred and verified.
Agent skill upstream boundary
Notes
No wire or schema change. A full refresh sent to a reconnecting client is an existing message every client version already handles. Folder workspaces are unaffected (the code is keyed by chat, not by git). Out of scope: other places where start-up bookkeeping can still refuse starting or resuming an agent are being fixed separately.
Checklist
N/Awith reasonpnpm lint,pnpm typecheck,pnpm test, andpnpm buildpass (or CI will cover; local preferred)Author: @BrennanKB5