Skip to content

fix(worktrees): close an idle structured chat on delete instead of refusing - #19762

Merged
brennanb2025 merged 9 commits into
mainfrom
brennanb2025/idle-chat-blocks-worktree-delete
Sep 11, 2026
Merged

brennanb2025 merged 9 commits into
mainfrom
brennanb2025/idle-chat-blocks-worktree-delete

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​936 $\color{#cf222e}{\Huge{\mathbf{−}}}$​29 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​907
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​511 $\color{#cf222e}{\Huge{\mathbf{−}}}$​94 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​417

Status: ready to merge. Reviewed over eight adversarial passes with live Electron validation at the final head. CI green. Follow-up in #19970.

The bug

You open a Codex or Claude chat in a workspace, it answers, you're done with it. You try to delete the workspace and Orca refuses: "This workspace still has running agent sessions."

Meanwhile, a workspace whose terminal is actively running the same agent deletes without a word — because that path kills the terminal for you.

That's backwards. The thing you were done with blocked you; the thing still working didn't.

How deleting a workspace used to work

Deleting a workspace sweeps every process Orca can attribute to it. There are three places a terminal can be registered — the renderer's view of the app, the terminal provider's own session list, and a local registry — and the delete sweeps all three, killing what it finds. If it kills something and then can't confirm it actually died, it stops and refuses, because deleting the files out from under a live process is how you get a program running against a directory that no longer exists.

Native chat sessions (Codex Chat, Claude Chat) appear on none of those three lists. They have no terminal. So all three sweeps found nothing, reported success, and the delete proceeded — leaving a chat's underlying process running with its working directory deleted.

A guard was added for that: a fourth check that looked for chats in the workspace and refused the delete if it found any attached. It never tried to close them. Closing only happened under --force.

Why that guard was wrong

It refused based on whether a chat was attached, not whether it was busy.

"Attached" just means a process is currently backing the chat. An idle chat that answered a greeting an hour ago is attached in exactly the same way as one mid-answer. So the guard couldn't tell "you're about to lose work" from "this panel is open" — and it chose to block on both.

The other three sweeps never worked that way. Each one issues a real stop, then checks what actually stopped, and refuses only for what it couldn't confirm. Refusing there means we tried and couldn't prove it worked — never something is attached.

How it works now

The fourth sweep behaves like the other three: it closes the chats, then checks each one actually closed.

  • Chats in the workspace get closed as part of the normal delete, the same way terminals get killed.
  • Each close is verified. A chat proven gone is done.
  • The delete refuses only for a chat whose close couldn't be confirmed — the same bargain the terminal sweeps already strike.
  • Force delete still overrides everything, as before.

No new capability was needed. The code to close a chat and verify it stopped already existed; it was just locked behind --force.

The practical result: an idle chat is no harder to delete than a terminal running the same agent. Which was the point.

What else the review found

Reworking the sweep surfaced several problems, fixed in the same PR:

  • It could close a chat on the wrong machine. A workspace ID is a repo and a path with no machine attached, so the same ID can exist on your laptop and on a remote host. Deleting the local one could have closed a live chat on the remote. Now the sweep only touches chats on the machine whose workspace is being deleted — matching how the terminal sweeps already fence themselves.
  • Force Delete could get stuck. If a chat's close hung, the resulting error was worded as a terminal failure, and clicking Force Delete hit the identical error again. The button meant to break the deadlock was itself deadlocked. Now a stuck chat is reported as a chat, and Force Delete clears it.
  • A chat that was already gone could still block the delete. If a close killed the chat but then failed a later step, Orca treated "proven dead" the same as "unknown" and refused. It now takes the proof.
  • Chats could starve the terminal sweeps of time. The chat close ran first and alone against a shared time budget, so a slow one left no time for the terminals, which then reported a timeout for a stop they were never asked to make. The sweeps now run alongside each other.
  • The refusal message didn't say which problem it was. "We watched this stay running" and "we couldn't confirm this closed" are different things to ask someone to override. They're now worded differently, and the delete dialog says the right one.
  • A failed delete left the chat tab gone. The tab was hidden before the close was attempted and never restored when the close failed — so a delete that didn't happen still took your tab away, permanently, from the next launch onward. It's now put back.
  • A red error flashed during deletion. Closing a chat while its panel was still open made the panel briefly render "Could not load conversation" before the tab disappeared. The panel now treats a chat that has gone away as a normal closing state rather than a loading failure. A genuine failure to load still shows an error.

Behaviour changes worth knowing

  • orca worktree rm and desktop Delete now close an attached chat instead of refusing. This is the point of the PR, but it is a new outcome on a destructive command.
  • If the delete does refuse over a stuck chat, that workspace's terminals have already been killed. Running the sweeps together is what fixed the starvation above, and the terminal sweeps kill as they go. The terminal path already behaved this way. Pinned by a test so it can't change silently.
  • This partially reverses a guard added a few days earlier. That guard was the "refuse if attached" check described above.

Existing "you might lose work" protection is unchanged: the uncommitted-changes confirmation still runs before any of this.

Testing

  • Eight adversarial review passes; the last found nothing.
  • Live validation in the real app at the final commit: a real Codex chat exchanged a message, the workspace deleted with no refusal and no error toast, and the chat stayed gone after restart. Screenshots in the comments.
  • The error flash was checked by sampling 14 distinct UI states across the delete rather than a single screenshot — neither error string appeared anywhere, with zero toasts.
  • Full suites, both typecheck projects, and the changed-code quality gates all green.

Known, not fixed here

A chat with no process backing it — because you'd switched away from it, or restarted the app — isn't seen by this sweep, so its tab can reappear after deletion pointing at a workspace that's gone. This behaves identically on main and is not caused by this PR. Fixed separately in #19970.

…fusing

`worktree rm` refused whenever any structured chat session was attached to the
workspace, so an idle Codex/Claude chat that had already answered was harder to
delete than a terminal actively running the same agent.

The PTY sweep stops every terminal it owns and refuses only for the ones whose
exit it could not verify. The structured sweep refused on `live` alone and never
attempted the close, which ran only under force. `live` is lease state — a
provider child is attached — not work in flight, so it was never the right proxy
for "you would lose something".

Close first, refuse only on what did not settle. The refusal now means the same
thing the unverified-PTY one does, so the toast takes that wording.
@coderabbitai

coderabbitai Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 23af7ae9-c719-4090-86c9-7d99a84720df

📥 Commits

Reviewing files that changed from the base of the PR and between 52b4cd7 and 3a3fb93.

📒 Files selected for processing (2)
  • src/main/runtime/structured-session-worktree-teardown.test.ts
  • src/main/runtime/worktree-teardown.ts

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


📝 Walkthrough

Walkthrough

Worktree teardown now fences structured sessions to the resolved execution host. It starts structured-session closure before PTY sweeps and joins it afterward. Failed or timed-out closes are classified as live or unverifiable. Removal messages and force-delete behavior now distinguish these states. Tests cover host isolation, timeout handling, provider aggregation, and concurrent sweeps.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to 3a3fb

Worktree deletion now attempts to close matching structured chat sessions before removal and accurately distinguishes sessions still running from closures that cannot be confirmed. Current coverage supports the changed deletion and warning behavior with no remaining merge-blocking risk.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 68.75% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 16 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the bug, cause, implementation, behavior changes, testing, and known limitations. However, it omits the required template sections and information, including a Fixes # linke… Restructure the description using the repository template. Add the required Fixes # issue reference, provide before-and-after visual proof or state N/A with a reason, complete the Testing checkboxes, and address the Review, Agent skill …
✅ 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: closing an idle structured chat during worktree deletion instead of refusing the deletion.
Full details: Description check

Explanation

The description explains the bug, cause, implementation, behavior changes, testing, and known limitations. However, it omits the required template sections and information, including a Fixes # linked issue, an explicit Visual Proof section or N/A justification, checklist confirmations, and several review metadata sections.

Resolution

Restructure the description using the repository template. Add the required Fixes # issue reference, provide before-and-after visual proof or state N/A with a reason, complete the Testing checkboxes, and address the Review, Agent skill upstream boundary, Notes, and Checklist sections.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • 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: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 37308494-89d5-44d6-a3a3-947d65ac792d

📥 Commits

Reviewing files that changed from the base of the PR and between 7dd183d and 5dc2df9.

📒 Files selected for processing (5)
  • src/main/runtime/structured-session-worktree-teardown.test.ts
  • src/main/runtime/structured-session-worktree-teardown.ts
  • src/main/runtime/worktree-teardown.ts
  • src/renderer/src/components/sidebar/delete-worktree-toast.ts
  • src/renderer/src/i18n/locales/en.json

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

Comment thread src/main/runtime/worktree-teardown.ts Resolved

@pullfrog pullfrog 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.

ℹ️ No critical issues — one minor suggestion inline, plus a nitpick.

Reviewed changes

  • Close-before-refuse structured sweep — sweepStructuredSessions now closes live sessions on the ordinary destructive path and refuses only when a close does not settle, matching the PTY sweeps' stop-first-then-verify bargain.
  • Toast copy — the running-agent-session toast now uses the "could not confirm … has closed" wording, mirroring unstoppedPty under the same i18n key.
  • Tests — the four refuse-on-existence cases now seed a stuck close, and an ordinary-removal-closes case is added; force, folder-workspace and reconciliation paths stay covered.

ℹ️ Nitpicks

  • The CLI refusal still reads "Refusing to remove worktree with running agent sessions … 1 running agent session (claude)" (RUNNING_AGENT_SESSION_REMOVAL_PREFIX plus describeLiveStructuredSessions), while the toast was changed to "could not confirm … has closed". "Running" sits oddly against the PR's own "live is lease state, not work in flight" argument once the refusal is fired by an un-settled close rather than a proven-running session.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

Comment thread src/main/runtime/worktree-teardown.ts Resolved
Review follow-ups on the close-first structured sweep. The close-first
direction is unchanged; four things it got wrong are not.

Host fence. `listLiveStructuredSessionsForWorktree` matched on
`location.workspaceId` alone, and a `repoId::path` id names a DIFFERENT
workspace on every host (STA-4343). Once the sweep started closing rather
than refusing, deleting a local workspace could close a live chat on an SSH
or paired-runtime copy of the same id. It now takes the same two host fields
the PTY sweeps already fence on, compared against the session's own
`location.executionHostId`; neither field set means this machine.

Shared budget. The close ran to completion before the first PTY sweep was
constructed, and it is serial with a provider round trip per session — so a
slow one spent the whole budget and the sweeps then rejected with a timeout
for a stop they never attempted. It is now issued first but joined before the
verdict, so the agent plane is still asked ahead of the terminal plane while
the two share the clock.

Timeout wording. The close raced the deadline fail-closed, and that sentinel
carries the PTY timeout prefix, which the classifier reads first — so a
wedged session close refused in terminal wording and refused identically
again under the Force Delete meant to clear it (#11960). A close that ran out
of time is now a session the removal could not confirm closed, which is what
the refusal already words. Tracked, so a forced removal still waits out the
abandoned-sweep grace before deleting files.

Verdict fidelity. `closeStructuredAgentSessionChild` re-observes after the
close, and that verdict was being discarded — so a session Orca watched stay
attached and one it merely could not reach produced the same message, while
the toast asserted "could not confirm" for both. `removal.ts` documents
flattening those two as the thing not to do. The unclosed sessions now carry
their post-close status, the detail uses the shared `still live:` marker, and
the toast branches on it like the PTY pair above it.

Also: the close takes the enumerated list instead of re-deriving it, so it no
longer runs every liveness observation twice or names a session it never
touched; and both teardown log lines count structured closes, since closing a
chat is now an ordinary outcome of this verb.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Host-fenced the structured sweep — listLiveStructuredSessionsForWorktree now filters on location.executionHostId, resolved from resolvedRuntimeEnvironmentId / resolvedConnectionId with the same precedence as the PTY fence (worktree-pty-host-fence.ts), so a repoId::path id no longer closes a like-named chat on another machine.
  • Bounded the close without the PTY-timeout sentinel — sweepStructuredSessions races closeStructuredSessionsForWorktree against settleBeforeDeadline with a fallback (unverifiable) instead of deadlineError, so a wedged close refuses in running-agent-session wording rather than classifying as unstopped-pty; the prior review's timeout-misclassification finding is resolved.
  • Worded the refusal by post-close verdict — describeUnclosedStructuredSessions distinguishes "still live:" from "could not confirm these closed:", the shared STILL_LIVE_DETAIL_PREFIX backs a new isProvenLiveStructuredSessionRemovalError, and the delete toast splits into runningAgentSessionLive / runningAgentSession.
  • Counted structured stops in the teardown log — both the IPC and pty-foreground kill paths now include structured= in their summary.

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

The structured sweep re-observes after a close that reported `stopped: false`,
but folded a proven `exited` into `unverifiable` — so a close that threw past
its own observation, or one whose death evidence landed a beat later, refused a
delete over a child that is demonstrably gone. That is the defect this sweep
exists to remove, and the PTY gate it mirrors never refuses on a proven exit.

Take the proof, and run the tab retirement the close skipped when it gave up:
a chat tab left behind re-attaches a released session pointing at a workspace
that is about to be deleted.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Took a proven exited over a failed close's verdict — closeStructuredSessionsForWorktree now re-reads the post-close observation and, when it is exited, retires the session's chat tab and counts it closed, rather than folding a demonstrably-gone child into unverifiable and refusing the delete.
  • Added a discriminating regression test — a settledThenThrows fixture arm models a close that records death evidence and then fails, and the new takes the proof when a failed close is re-observed as exited case pins the refusal-vs-close ordering; reverting this one lever fails the case with the field refusal.

The change is the direct analogue of the guarantee closeStructuredAgentSessionChild already makes on its own success path: past the proof of exit, it retires the tab. The re-read pulled that retirement into the sweep so a close that gave up before its own retirement step no longer refuses over a provably-gone session.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Validated 6d05fb8 (6d05fb8a52) from qa-19762-electron: deletion succeeded without the running-agent-session refusal. Rebuilt this worktree, launched with ORCA_BACKGROUND_LAUNCH=1 and an isolated profile, verified the app identity, and captured the hidden Electron renderer through Playwright CDP. This covers a completed local Codex structured-chat turn; Claude, active turns, SSH, and folder workspaces were not exercised.

The disposable idle-chat-delete-proof workspace has a real Codex structured native chat open. I sent “Say hi in one short sentence. Do not use tools or change any files.” and Codex answered “Hi, Brennan!”; the chat shows Done before deletion.

01-idle-structured-chat.png

The workspace’s sidebar Delete action opened this confirmation dialog. The completed Codex chat remains open behind it, and the dialog identifies the workspace folder that will be removed.

02-delete-confirmation.png

Immediately after clicking Delete Workspace, the target workspace is gone from the sidebar and its chat tab is closed. No running-agent-session refusal or other toast appeared; a toast observer installed before confirmation recorded no notifications.

03-immediately-after-delete.png

The settled view shows only the fixture’s primary main workspace, with its normal terminal opened automatically. The deleted workspace remains absent; Git also lists only the primary workspace, and the app teardown log reports structured=1.

04-after-delete.png

…live ones

The refusal named only the proven-live subset when any session was live, so a
sweep that left one attached and two unconfirmed told the user "1 agent session
(claude)" while three were about to be discarded — and dropped the providers of
the ones it hid. The PTY sibling may drop everything outside its live list
because a fresh inventory PROVED those exited; nothing proves that here, so both
groups are counted. The `still live:` marker still leads, so the delete toast
keeps showing the stronger warning.

Also carries the structured close count through the forced-removal early return:
that path skips the per-PTY verdict, not the sweep that already ended a user's
chats, so the removal log claimed `structured=0` for chats it had just closed.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Named both unclosed-session verdicts — describeUnclosedStructuredSessions now reports the unverifiable sessions alongside the live ones, so a mixed refusal names both groups instead of silently dropping the unconfirmed subset when a proven-live session leads the message.
  • Propagated the structured close count — the forced.incomplete early return in killAllProcessesForWorktree now carries structuredStopped, so a forced removal whose PTY sweep failed still logs the chats it closed instead of reporting structured=0.

The split message keeps isProvenLiveStructuredSessionRemovalError leading with the stronger warning (so the delete toast stays correct in the mixed case), and the new tests are discriminating — names the unconfirmed sessions too fails against the previous drop-only-live wording, and still reports what it closed fails against the bare forced.stopped return. Both changed test files pass locally.

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

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: d851c05e-9010-4d78-a474-2f58af0407d7

📥 Commits

Reviewing files that changed from the base of the PR and between 6d05fb8 and 52b4cd7.

📒 Files selected for processing (3)
  • src/main/runtime/structured-session-worktree-teardown.test.ts
  • src/main/runtime/structured-session-worktree-teardown.ts
  • src/main/runtime/worktree-teardown.ts

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

Comment on lines +142 to +147
return `could not confirm these closed: ${countStructuredSessions(unconfirmed)}`
}
const live = `${STILL_LIVE_DETAIL_PREFIX} ${countStructuredSessions(stillLive)}`
return unconfirmed.length === 0
? live
: `${live}; could not confirm these closed: ${countStructuredSessions(unconfirmed)}`

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 | 🟠 Major | 🏗️ Heavy lift

Use a localization payload for the new closure detail.

could not confirm these closed reaches the desktop toast and CLI output. A raw string prevents the renderer from localizing the new message or using named placeholders for the count and providers. Keep the classifier marker stable, but return an intent and named values that each surface formats through its localization path. Update src/main/runtime/structured-session-worktree-teardown.test.ts to assert the intent and values instead of the English sentence.

Based on learnings: For newly added user-facing strings in TypeScript and TSX files, use intent-named localization IDs with named interpolation placeholders.

Source: Learnings

…oes not have

The structured sweep splits its post-close verdict in two on purpose: "we watched
it stay attached" and "we could not confirm it closed" are different things to
waive, and `removal.ts` keeps a marker and a matcher together so the delete toast
can tell them apart. The force-path warn then appended "still attached" to
whichever verdict it got, so a removal forced over a close that merely ran out of
time logged that Orca had seen the session running.

That line is the only record a forced removal leaves of a child left pointing at
a deleted `cwd`, so it is the one place the two must not be flattened. Carry the
verdict verbatim, the way the unstopped-PTY warn above already does.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Stopped the forced-removal warn from asserting a live verdict — sweepStructuredSessions's console.warn now emits …${UNSTOPPED_PTY_DETAIL_SEPARATOR}${describeUnclosedStructuredSessions(unstopped)} instead of appending still attached, so an unproven could not confirm these closed verdict is no longer worded as a session Orca watched stay attached.
  • Pinned both post-close verdicts in the warning — the test file's new structuredSessionWarning helper isolates the structured sweep's warn from the PTY-sweep warn, and the forced-removal cases now assert still live: 1 agent session (claude) for the live arm and could not confirm these closed: … with no still attached for the timeout arm.

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

…xpires

The structured close loop is serial, so the shared sweep budget can expire
part-way through it. The timeout fallback was assembled by the caller and could
only name the whole list: sessions this removal had already closed were reported
as unclosed, named in the refusal the user reads, and logged as `structured=0`.
The loop now records progress into a structure the timeout path reads, so both
the refusal and the count say only what was observed. A session with no recorded
outcome reports `unverifiable` — the same verdict as an attempted close that
stayed unproven, because "never asked" and "asked, unconfirmed" are both exactly
"not observed exited", and neither may claim `live`.

The loop also checks the deadline before each close, so one slow provider round
trip no longer starves every session behind it. It stops ISSUING closes; an
in-flight one is left to finish, since nothing here can cancel a round trip.

The structured host fence now reuses the PTY fence's own type instead of a
look-alike that read `undefined` as local while the other read it as match-all,
with both claiming the same precedence. `null` means this machine on both sides;
ABSENT stays narrowed to local here, documented and pinned, because a
single-host-id comparison cannot express match-all.

Also pins a tradeoff that was accepted rather than wanted: the PTY sweeps run
concurrently with the structured close, so a removal that refuses over a stuck
session has already killed that workspace's terminals.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Progress-accounted structured sweep — closeStructuredSessionsForWorktree now writes its outcome into a mutable StructuredSweepProgress as the serial loop runs (and takes the absolute deadline), so sweepStructuredSessions reads the actual closed/unstopped counts off progress instead of a whole-list fallback that reported structured=0 and named every session unverifiable when the budget expired mid-loop.
  • Bounded the close loop — the loop stops issuing new closes once the budget is spent, leaving only the in-flight close to finish, so one slow provider round trip no longer starves every session queued behind it.
  • Shared the PTY fence type — StructuredSessionHostFence is now WorktreePtyHostFence (resolvedConnectionId?: string | null), with null/undefined collapsing to local in structuredSessionTeardownHostId and the absent-fence divergence documented and pinned by test.

ℹ️ Force delete stops closing sessions queued behind a slow close

The new if (Date.now() >= deadline) return is a deliberate reversal of the loop's old run-to-completion behavior, and on the ordinary path it is strictly better (the removal refuses, so nothing should keep closing). On the force path it has one narrow cost: settleSweepsForForcedRemoval's awaitAbandonedSweeps grace used to let a mid-loop close finish closing the sessions queued behind a slow-but-eventually-completing one, and now those queued sessions are left un-closed, orphaning their provider children against a deleted cwd. This only bites when a single close outlives the 10s budget while more sessions wait behind it, and force is the explicit escape hatch, so I don't think it blocks — flagging so the tradeoff reads as a confirmed decision rather than an accident.

Technical details
# Force-path orphan window from the close-loop deadline check

## Affected sites
- src/main/runtime/structured-session-worktree-teardown.ts:231 — `if (Date.now() >= deadline) return` stops issuing closes at the budget, leaving `progress.sessions.slice(settled)` un-closed.
- src/main/runtime/worktree-teardown.ts:341 — the tracked close is no longer run-to-completion, so `awaitAbandonedSweeps` (forced-sweep-settlement.ts) has nothing left to wait out on the structured sweep.

## Required outcome
- Confirm the force-delete tradeoff is intended: sessions queued behind a close that outlives the budget are now orphaned instead of closed during the abandoned-sweep grace.

## Open questions for the human
- Should the force path keep the serial loop running (bounded by the grace) while the ordinary path stops at the deadline?

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review status — ready to merge

Reviewed at 3028b85df3 across six adversarial passes plus live Electron validation. CI green (28 checks: 17 pass, 11 skipping), mergeStateStatus: CLEAN, headRefOid confirmed to match the run that went green.

The PR's direction was assessed independently and kept: live is lease state, not work in flight, and the three PTY sweeps stop-then-refuse while the structured sweep refused-then-stopped. The fix removes that asymmetry rather than guarding it. Everything below is what the review found around that correct core.

Defects found and fixed during review

# Defect Why it mattered
1 Structured sweep was not host-fenced repoId::path carries no host component, so deleting a local workspace could close a live chat on an SSH host or paired runtime sharing the id. The three PTY sweeps are fenced; the fourth was not.
2 A structured wedge Force Delete could not clear The shared timeout sentinel carried the PTY prefix, which the classifier reads first — so a stuck session refused in terminal wording and refused identically again under the Force Delete meant to clear it. Newly reachable on the ordinary path.
3 A proven-dead child still refused removal exited was collapsed into unverifiable, so a close that killed the child and then failed a later step refused worktree rm over a session demonstrably gone — this PR's own bug class, through a different door.
4 Head-first budget starvation The serial close could spend the whole 10s budget before a single PTY was asked, making the sweeps report a timeout for a stop they never attempted.
5 Unverifiable sessions hidden from a destructive warning The refusal named only the still-live subset, dropping other unclosed sessions and their providers from the message.
6 Verdict flattening CLI said "running agent sessions" while the toast said "could not confirm". Now split, reusing the existing marker-plus-matcher pattern.
7 Forced-removal warn asserted a verdict it did not have It appended "still attached" to sessions the sweep had just said it could not confirm either way — in the one line that is the only forensic record a forced removal leaves.
8 Timeout path reported fabricated results Sessions already closed were named as unclosed in the refusal the user reads, and structured=0 was logged for closes that landed. The loop now records progress the timeout path reads.
9 Serial close had no per-session deadline check; two host-fence helpers silently disagreed on what undefined meant; no observability on a newly destructive outcome

Items 2, 3, 7 and 8 were introduced by earlier review passes, not by the original commit — which is the argument for running the loops to convergence rather than stopping at the first clean-looking result. The final pass found nothing.

Live validation

Electron QA at 6d05fb8a52 on a real build: a genuine Codex structured chat was opened in a workspace, exchanged a real message, and the workspace deleted with no refusal and no toast — a DOM observer installed before confirming recorded an empty toast list. Screenshots are in the comment above. The app log showed:

[worktree-teardown] <id> killed runtime=1 provider=0 registry=0 structured=1

That structured=1 is the useful part: it proves the host fence found the session rather than silently skipping it, which was the main risk in fixing defect #1.

Commits after that QA touch only refusal wording, a console.warn, and the timeout-path accounting — none on the validated happy path.

Not covered by QA: Claude (only Codex was exercised), mid-turn active sessions, SSH, and folder workspaces.

Behaviour changes worth explicit sign-off

  1. A refusal over a stuck session now lands after the workspace's terminals were killed. Making the sweeps concurrent fixed the budget starvation, but the previous head-first-serial ordering spared those terminals. Accepted because the alternative is a force-delete removing files while PTY handles are open, and the PTY gate already kills-then-refuses. Now pinned by a test so it cannot flip silently.
  2. A refused ordinary delete clears the session's durable tab-restore entry (setSessionTabVisibility(false) runs before the close fails). Costs tab restore, not data — the journal is rooted at userData, never inside the working tree, so transcripts survive.
  3. This partially reverses a guard added days earlier, as the description says. That is the point of the change, but it is a new outcome on a destructive verb.

Correction to the description

the dirty/untracked confirmation still runs ahead of the sweep

True on the desktop path, not on the CLI SSH route: runtime-registered-remote-worktree-removal.ts:38-42 calls stopPtys() with no assertWorktreeCleanForRemoval. Pre-existing and unchanged here — stopPtys() already kills terminals ahead of that same refusal today — but the claim as written is broader than the code.

Known, non-blocking, not fixed here

  • observeStructuredWorker reports live on hasSession && claimStatus === 'live' and never consults hasProviderChild; the recovering lease disposition preserves claimStatus, so a session with no provider child can report live. Pre-existing; this PR makes it strictly less harmful (such a phantom previously refused outright).
  • worktrees:forgetLocal sets neither flag, leaving structured chats attached to a forgotten workspace while both sibling paths opt in. Identical on main; looks unintentional but is product scope past this fix.
  • Nothing upstream warns the user that agent sessions are about to close. A pre-flight count in the confirm dialog is the right follow-up; it applies equally to terminals and predates this PR.

Validation performed

tsc both projects clean (run sequentially) · check:code-quality:changed 0/0/0 across 10 files including React Doctor · oxlint + oxfmt --check clean · localization catalog and translation policy both exit 0 · every new test ablated with the both-files-at-baseline arm and re-proven at the final head · no max-lines disable or cap bump anywhere · pnpm-lock.yaml confirmed absent from all six commits.

…t land

`closeStructuredAgentSessionChild` hides the session's chat tab before it issues
the close, so every failure past that point left a refused delete having still
taken the tab out of the durable restore index. The conversation survived under
`userData`, but nothing brought the tab back at the next launch.

Both failure shapes now roll the hide back: `host.close` throwing, and the
post-close observation coming back not-`exited`. The restore is gated on the
visibility read taken BEFORE the hide, so it never publishes a tab for a session
that was already hidden, and on a fresh observation, so it never resurrects one
for a child a throwing close still took with it — which is what the worktree
sweep reads when it counts such a session closed. It cannot throw out of the
function, so the caller's original reason is still what the user is asked to act
on.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Restored the chat tab after an unsettled structured close — closeStructuredAgentSessionChild now reads the session's persisted tab visibility before the hide and, when the close throws past it or the post-close observation is not exited, restores the tab via restorePersistedTabVisibility, which re-observes first so a close that threw past its own proof (session demonstrably gone) stays retired.
  • Added a discriminating regression test — the new structured-agent-session-close.test.ts covers the success path and every failure shape (close throws, stuck close, throws-past-proven-exit, already-hidden tab, failed visibility write, failed restore, unreadable index, no host), pinning the exact setSessionTabVisibility call sequence for each.

The rollback reads visibility before the hide and only restores what was actually visible, so it cannot resurrect a user-closed tab, and its re-observe guard keeps it from republishing a tab for a session the sweep already proved gone.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Re-validation at 5e62f61 (5e62f61), rebuilt from qa-19762-electron and launched with ORCA_BACKGROUND_LAUNCH=1, an isolated profile, and hidden-renderer Playwright CDP. Deleting a workspace with a genuinely attached, completed Codex structured chat SUCCEEDED without a running-agent-session refusal or any toast. That attached chat stayed gone after restarting the app against the same profile. There is an additional persistence finding: a second Codex tab opened during setup but never sent a message was republished in persisted tab state for the deleted workspace after restart; it is not visible in the default post-restart UI. This is therefore not a blanket all-tabs persistence pass.

The actual teardown line was:

[worktree-teardown] ca5b31c2-7219-4d5d-b0da-dd20cd9b267c::/Users/brennanbenson/orca/workspaces/qa-19762-fixture/final-head-chat-delete killed runtime=1 provider=0 registry=0 structured=1

Before deletion: final-head-chat-delete has a real Codex structured chat that answered “Hi, Brennan!” and shows Done. Two chats were opened through New tab during setup; after reloading the renderer to apply the fresh profile settings, the selected one exchanged this message, while the other remained unstarted. The ordinary terminal tab was not used as an agent substitute.

01-completed-codex-chat.png

The real Delete Workspace confirmation names the disposable workspace and its folder. Deletion was confirmed through this UI button.

02-delete-confirmation.png

The first screenshot immediately after confirming catches the “Deleting…” transition, with the completed chat still painted. The DOM read immediately after this screenshot briefly contained “Could not load conversation / RuntimeRpcCallError: agent_session_ownership_unknown”; that transient inline message was not captured in the image. A toast observer recorded no toast, including no running-agent-session refusal.

03-immediately-after-delete.png

Deletion completed successfully: the workspace is gone from the sidebar and both chat tabs are gone from the rendered tab bar, leaving the fixture primary workspace. No toast appeared; Git also lists only the fixture primary worktree.

04-delete-complete.png

After stopping and relaunching the app against the SAME isolated profile, the rendered UI still shows only main and no chat tab. The message-bearing chat codex_6b05bb41_e88d_43cf_8a58_9eaadd353381 stayed absent, but a repeated window.api.session.get() read found the unstarted chat codex_5a0d812b_1ca3_40e8_b3f4_c73aad750a71 in unifiedTabs under the deleted workspace, with contentType: agent-session, label Codex Chat, and a headless-terminals:<deleted-workspace-id> group. That orphaned backing state needs follow-up even though it does not appear in this default view.

05-after-app-restart.png

Coverage: local macOS, Codex, completed turn, successful workspace deletion, and same-profile app restart. Claude, active turns, SSH, and folder workspaces were not exercised. No source changes or code push.

…e the workspace

The rollback added for a refused close ran on every unproven close, including the two
shapes of removal that cannot refuse. Force Delete warns and deletes the checkout; a
folder-workspace removal never refuses at all. Putting the tab back on those paths leaves
a durable restore-index entry for a workspace that is then gone, and the chat republishes
at the next launch pointing at it — the outcome this sweep exists to remove.

The close now takes `restoreTabOnUnprovenClose`, on by default so `worker-stop` and
`worker-release` keep the rollback, and the teardown sweep passes it only when the removal
can still refuse.

Second hole, same chain: `host.close` can return before the child's exit is recorded, so
the close's own observation reads unverifiable and restores the tab, while the sweep's
re-read one store write later proves the exit and counts the session closed. The two
observations straddle that write and disagree. The sweep now re-drops the tab reference
when it takes that proof, and the comment claiming the re-observation alone covers this
is corrected.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Gated the chat-tab rollback on a removable refusal — closeStructuredAgentSessionChild takes restoreTabOnUnprovenClose (default on, so the orchestration stop path is unchanged), and the sweep passes mayRefuse === true — the same condition as the refusal at worktree-teardown.ts:360 — so a force or folder-workspace removal no longer re-publishes a tab for a workspace it is about to delete.
  • Dropped the restored tab when the sweep proves the exit — the re-read-exited branch now also calls dropDurableChatTabReference, clearing the durable reference the rollback had re-added for a session the sweep counts closed (the two observations straddle the restore's store write).
  • Added four discriminating tests — ordinary-refusal restore, force no-restore, folder-workspace no-restore, and the restore-then-drop disagreement, backed by new visible / exitsDuringTabRestore fixture arms.

The mayRefuse mapping exactly mirrors the sweep's refusal condition, so the tab is only ever restored when the workspace (and its tabs) actually survives. The regression this fixes — a durable tab reference to a workspace that was just deleted — is the precise outcome the sweep exists to remove, and the rollback's own re-observe guard is preserved intact.

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

…would not load

Deleting a workspace now closes the structured chats inside it, and the chat pane
outlives that close by a few frames. Every read it makes in that window —
`agentSession.history` on refresh, `agentSession.subscribe` on reconnect — resolves
through the host's `requireSession`, which refuses with
`agent_session_ownership_unknown` for a session it no longer holds. The pane turned
that into its terminal error surface, so an ordinary delete flashed
`Could not load conversation` over the transcript before the tab retired.

That code, raised by a READ, never means the transcript could not be read. It means
this host has no session object by that id: one it has just closed, or one it has not
attached yet, since the surface's hold is what attaches a session at all. Both windows
end on their own. The genuinely latched lease — Orca cannot prove the previous owner
exited — reaches the client through the acquisition path instead, so narrowing on the
code costs a read no real diagnosis.

So the read transport classifies before it reports: an unattached refusal stays on the
reconnect loop it is already the subject of, and the pane keeps the transcript it has.
It is a window, not a mute. A read still refusing that way past the grace is no longer
transitional, and the pane is owed the failure rather than a spinner that never
resolves. Every other failure still surfaces immediately, unchanged.

The refusal code now has one definition, shared by the host that raises it and the
client that narrows on it, so the two cannot drift into a red error nobody meant.

Deliberately NOT changed: the order of teardown. The tab is retired after the close
proves, not before it, because a close that does not settle has to put the user's chat
tab back — the rollback this PR already establishes. Retiring the pane first would
unmount it ahead of a close that may be refused, so the pane instead treats a session
that has gone as a neutral terminal state.

Mobile's structured chat reaches the same reducer but has no reconnect loop, and its
hold refusal is what carries the diagnosis there, so the grace does not transfer; it
keeps reporting as before.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes (since prior review at 5292373909)

  • Shared the unattached-read refusal code — AGENT_SESSION_UNATTACHED_REFUSAL_CODE now has one definition in src/shared/structured-agent-session-read-refusal.ts, and the host's AGENT_SESSION_NOT_ATTACHED uses it, so the host that raises agent_session_ownership_unknown and the client that narrows on it can no longer drift apart.
  • Gated the pane's error on a grace window — reportReadFailure in the read transport now classifies before it reports: an unattached refusal stays off the pane and on the reconnect loop it is already the subject of, surfacing as an error only once it outlives AGENT_SESSION_UNATTACHED_READ_GRACE_MS. A closing chat no longer flashes Could not load conversation in the frames before its tab retires.
  • Suppressed the same refusal at the page level — loadOlder's catch no longer errors the pane on an unattached older-page read, matching the transport's transitional treatment so a page that lost the close race doesn't repaint the pane red.
  • Added discriminating tests — the surface-lifetime test pins the host contract (history/subscribe throw the code after a close); the transport tests cover grace expiry, grace restart once a read lands, immediate surfacing of unrelated failures, and raw-stream-payload classification; the hook test distinguishes an unattached page refusal from a genuine failure.

The grace is a window, not a mute — a read still refusing past 5s is owed the failure — and the genuinely latched lease reaches the client through the acquisition path rather than the read, so narrowing on the code costs a read no real diagnosis. The design reads as sound and well-bounded.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Re-validation at 0e041d4. The purpose of this run was to confirm that the red structured-chat load error no longer flashes while deleting a workspace.

Result: PASS for the targeted flash. A MutationObserver plus a 50 ms polling sampler recorded 14 distinct document.body.innerText states and every notification-region child across the transition; it recorded 0 toast events. Literal search result: Could not load conversation = false; agent_session_ownership_unknown = false.

The normal read path also passed: a new host-owned Codex Chat rendered the prompt and the real reply “Hi!”. The workspace disappeared from the sidebar and store, its folder and git worktree were removed, and the teardown log was:

[worktree-teardown] 1878464d-23ed-4f9c-8759-cb564a095ae7::/Users/brennanbenson/orca/workspaces/qa-19762-electron/qa-19762-flash-0e041d4 killed runtime=1 provider=0 registry=2 structured=1

After restarting Orca against the same isolated profile, neither the deleted workspace nor its Codex Chat tab reappeared.

1 — Read-path check: the answered Codex Chat is visibly rendered before deletion.

qa-19762-chat-answer.png

2 — Delete confirmation: the answered Codex Chat remains the visible pane behind the confirmation dialog.

qa-19762-delete-confirmation.png

3 — Initial delete frame: immediately after confirmation, the workspace is marked Deleting while the healthy chat transcript remains visible; no red load error or toast is present.

qa-19762-delete-t0000.png

4 — One-second delete frame: the transition remains clean one second later.

qa-19762-delete-t1000.png

5 — Later delete frame: the structured chat pane has closed and the workspace is still marked Deleting, with no load error or toast.

qa-19762-delete-t4000.png

6 — Delete complete: the disposable workspace is gone from the sidebar and Orca has returned to the original worktree.

qa-19762-delete-loop-00.png

7 — Same-profile restart: the deleted workspace and its Codex Chat tab remain absent after relaunch.

qa-19762-after-restart.png

@brennanb2025
brennanb2025 merged commit b6e4457 into main Sep 11, 2026
28 checks passed
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