Skip to content

fix(native-chat): a failed cleanup when reopening a chat never refuses the send - #26554

Open
brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/chat-open-cleanup-never-blocks
Open

brennanb2025 wants to merge 2 commits into
mainfrom
brennanb2025/chat-open-cleanup-never-blocks

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​286 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​286
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​142 $\color{#cf222e}{\Huge{\mathbf{−}}}$​39 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​103

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:

  • Opening a chat used to await the 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.
  • The helper works out the correction from the saved rows when the chat opens, using the same rule as before (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".
  • It then tries to save each correction. On success the saved row is identical to what main writes.
  • On failure it logs once per item and tries again after the chat's next successful write. Before each attempt it checks that the row hasn't changed. A newer version of the row, a replaced history, or closing the chat cancels the pending correction.
  • Nothing is saved to remember the pending work. The next open works it out again from disk.
  • A client reconnecting while a correction is still unsaved (for example after the app reloads) gets a full fresh copy of the chat instead of only the rows it missed, because the correction has no new row to send it yet. A full refresh is something the app already sends today, so older clients handle it.

Why

  • Catch-and-log alone: if the error were only caught, the chat would open but go on showing the dead subagents as running. Anything that continues the subagent list would also inherit a "running" child that nothing can ever settle. Showing the corrected state from the moment the chat opens avoids both.
  • Never saving the correction (working it out on every read): this would make every way of reading history, now and later, re-apply the correction. A saved row reaches every reader through the normal update stream, so the saved row stays the single source of truth, and the in-memory correction only covers the window while the save keeps failing.
  • Same-version re-send to reconnecting clients (tried, then dropped): an earlier version of this PR sent reconnecting clients the corrected row at the same version number. Clients refuse to update their subagent list from a row at the same version, so a reconnecting client could keep showing a "working" dot. A full refresh rebuilds that list correctly on current and older clients.

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:

  • Intended: Orca records "status unavailable" (lost contact, no proof the work ended), not "stopped" or "cancelled".
  • Intended: the correction is made per chat when that chat opens, not in an app-wide sweep at startup, so a failure stays scoped to one chat.
  • Intended: when the save fails, Orca shows the corrected state from memory and retries after later writes. This is the "bookkeeping never blocks the user" requirement. It is safe because nothing durable is added, and every pending correction ends on success, when a newer version replaces the row, or when the chat closes.

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.
B2-send-refused.png

After (this PR), same setup: the chat opens, the subagent shows "status unavailable", and the message sends and gets a reply.
A1-reopened-unverifiable.png
A2-sent.png

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.
A3-correction-landed.png

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

  • Not applicable, or this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

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

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

Author: @BrennanKB5

brennanb2025 and others added 2 commits October 8, 2026 03:48
…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.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review summary

The 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 3a85f9b0004, on top of the original patch):

  • Reconnecting clients: reconnecting desktop clients now get a full fresh copy of the chat while a correction is unsaved. The original patch sent the corrected row at the same version number, which clients refuse to apply to their subagent list, so a reconnecting client could keep showing a "working" dot. A full refresh is a message every client version already handles.
  • Unused code removed: a rewrite of rows read back from disk that no client-facing path used.
  • One rule: the on-screen correction and the save now use the same rule, so nothing is shown as corrected that the save could never write.
  • Logging: a failing save is logged once per item instead of after every later write.
  • Tests: an end-to-end send test through the host, a background-task case, and the reconnect case before and after the save lands.

Deferred (minor):

  • Reconnects: while a correction keeps failing, each desktop reconnect reloads the chat from its latest page, which drops older pages the user had loaded (the same thing an existing full refresh does).
  • Retries: a failing correction is retried after every later successful write.
  • Open time: opening still waits for the first save attempt, as on main.
  • Tests: small test-hygiene nits.

No failure was found in normal use that hits only this correction save and keeps hitting it.

Verified:

  • Tests: new and related tests pass. The new ones fail on the base commit.
  • Static checks: the Node typecheck and the repo's static checks pass. CI is green on 3a85f9b0004.
  • Manual (macOS, hidden test app, fake model): the correction save was forced to fail with a temporary database trigger.
    • Before: "couldn't open this chat's history" and the message was refused.
    • After: the chat opens, the subagent shows "status unavailable", and the message sends.
    • Once the failure was removed, the next send saved the correction (revision 2 of the row in the database).
  • Readiness checklist: no P0/P1/P2 findings.

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.

@brennanb2025
brennanb2025 marked this pull request as ready for review October 8, 2026 12:41
@coderabbitai

coderabbitai Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Walkthrough

The journal now tracks stale live-work corrections found during restoration and attempts to persist them. Failed corrections remain eligible for retry after later commits. The journal exposes whether reopened live work remains unpersisted. Subscribers receive a hydration snapshot rather than cursor-based delivery while such work remains unpersisted. New tests cover persistence failures, retries, superseding provider evidence, and subscriber delivery.

Merge Risk: Low · up to 3a85f

Chat reopening and sending are not shown to be blocked. The remaining issues are a misleading warning on closure and a test-isolation problem; they are bounded follow-ups rather than merge blockers.

Pre-merge checks: Passed 4

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 names the fixed behavior: a failed cleanup when reopening a chat no longer refuses the send. The changeset matches this. It adds JournalReopenedLiveWork, which keeps a failed stale-subagent …
Description check Passed The description follows the repository template. It has ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Risk, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist s…
Full details: Title check

Explanation

The title names the fixed behavior: a failed cleanup when reopening a chat no longer refuses the send. The changeset matches this. It adds JournalReopenedLiveWork, which keeps a failed stale-subagent correction write from failing the chat open, and it shows the corrected state in memory. The title is specific and uses the conventional fix(scope) form. It omits the in-memory display and retry mechanics, which is expected for a title.

Full details: Description check

Explanation

The description follows the repository template. It has ELI5, What Changed, Why, Linked Issue, Visual Proof, Testing, Risk, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections. It gives a detailed before and after, the mechanism, the alternatives considered, and reports platform coverage. Gaps: the Risk section has no 'Level' value (it says 'Level: <!-- Low, Medium, or High -->' with no selection). The Testing checkbox 'Every added test fails without this change...' is not checked. The Linked Issue section has 'Fixes #' with no issue number and no pre-existing issue, which the template says outside contributors must provide, though the author is a maintainer. The Risk section does not say how to back out the change, which the template asks for. The Review section is brief. Overall the description is mostly complete.

Resolution

Fill in the Risk level (Low, Medium, or High). Add the back-out plan: a plain revert, or what a revert would not undo. Check whether the 'Every added test fails without this change' box applies, and confirm it. Replace the empty 'Fixes #' with the linked issue or state that none exists.

Finishing Touches

  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@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: 2


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4e048a0b-77ee-4dda-908c-600b902fb495
📥 Commits

Reviewing files that changed from the base of the PR and between e0a98a4 and 3a85f9b.

📒 Files selected for processing (8)
  • src/main/native-chat/agent-session-journal/journal-open-cleanup.test.ts
  • src/main/native-chat/agent-session-journal/journal-reopened-live-work.ts
  • src/main/native-chat/agent-session-journal/journal-store-collaborators.ts
  • src/main/native-chat/agent-session-journal/journal-store-open.ts
  • src/main/native-chat/agent-session-journal/journal-store-restore.ts
  • src/main/native-chat/agent-session-journal/journal-store.ts
  • src/main/native-chat/agent-session-wire/structured-agent-session-send-preparation.test.ts
  • src/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.

Comment on lines +65 to +74
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())
}
}

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:

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-journal

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

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

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

Comment on lines +210 to +246
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()
})

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:

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

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

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

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

This branch has not been deployed

No deployments
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