Skip to content

fix(resource-manager): protect live unbound terminal sessions - #8467

Closed
bbingz wants to merge 13 commits into
stablyai:mainfrom
bbingz:fix/resource-manager-orphan-safety
Closed

bbingz wants to merge 13 commits into
stablyai:mainfrom
bbingz:fix/resource-manager-orphan-safety

Conversation

@bbingz

@bbingz bbingz commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • replace Resource Manager direct bulk termination of renderer-unbound PTYs with an explicit review and confirmation flow
  • classify candidates at the owning provider boundary and only close sessions freshly verified as a known idle shell with no child processes
  • protect active, unknown, disconnected, newly bound, later-created, and already-gone sessions; an SSH provider disappearing after inspection now fails closed
  • route individual unbound-row cleanup through confirmation, replace misleading orphan/kill copy in all locales, and translate error states through typed codes
  • add deterministic shared/main/renderer coverage plus a real daemon Electron smoke test whose split marker cannot pass on typed echo alone

Screenshots

Not captured. The change reuses the existing Resource Manager surface and design-system primitives; the visible behavior changes from direct Kill orphan actions to Review unbound terminal confirmation and verified outcome copy.

Testing

  • pnpm lint
  • pnpm typecheck
  • pnpm test — the local machine is on unsupported Node 26; the exact focused safety gate is run below and full-suite CI is requested on Node 24
  • pnpm run build:desktop
  • Added or updated high-quality regression tests
  • 11 focused files: 477 tests passed after syncing current main
  • built-Electron real-daemon E2E passed twice after the anti-echo assertion was added
  • git diff --check and reliability-gate validation passed
  • pnpm run verify:localization-catalog and pnpm run verify:localization-coverage passed after the close-terminology review fix

Focused gate:

pnpm exec vitest run --config config/vitest.config.ts src/shared/pty-inactive-cleanup.test.ts src/main/ipc/pty-inactive-cleanup.test.ts src/main/ipc/pty.test.ts src/renderer/src/components/status-bar/resource-session-cleanup-review.test.ts src/renderer/src/components/status-bar/use-resource-session-cleanup-review.test.tsx src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.test.tsx src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx src/renderer/src/components/status-bar/ResourceUsageStatusSegment.session-polling.test.ts src/renderer/src/components/status-bar/resource-session-bindings.test.ts src/renderer/src/components/status-bar/resource-session-count-selector.test.ts src/renderer/src/components/status-bar/mergeSnapshotAndSessions.test.ts

AI Review Report

The review checked the destructive IPC boundary, renderer-to-main race windows, provider ownership, SSH disconnect behavior, late binding, already-gone sessions, partial failures, dialog lifecycle, translation routing, test false positives, and direct-kill bypasses. It also checked macOS/Linux/Windows shell names and Electron preload/IPC behavior; no shortcut or path behavior changed.

Review findings fixed:

  • guarded SSH cleanup previously could tombstone a session if its provider disconnected after inspection and then report it as killed; guarded cleanup now fails closed while explicit user kill preserves the existing tombstone behavior
  • renderer errors were raw English strings; state now carries typed error codes translated in the dialog
  • empty reviews no longer perform an inspection IPC round-trip
  • execution hydration and transport failures, locked cleanup settlement, and always-visible unbound row actions now have explicit regression coverage
  • phase-driven nested ternaries were replaced by exhaustive switch-based presentation helpers
  • stale locale catalog entries still said orphan and kill; all supported locales now say unbound and review
  • E2E command-output proof could match tty input echo; the complete marker is now assembled only by executed shell output

Cross-platform review found no new platform-specific shortcut or path assumptions. Shell fixtures cover POSIX shells, PowerShell, CMD, and Git Bash. Live Linux, Windows, WSL, and SSH process evidence remains a CI/follow-up gap documented in the reliability gate.

Security Audit

  • destructive input is normalized, deduplicated, capped at 500 IDs, and intersected with the reviewed/live/unbound set before main-process reinspection
  • cleanup never treats renderer absence as idle evidence and never falls back a disconnected SSH-owned PTY to the local provider
  • no new arbitrary command construction, filesystem path handling, authentication, secrets, network endpoints, dependencies, or persisted sensitive data were added
  • IPC returns bounded safety/outcome discriminants and the UI exposes aggregate results rather than process IDs

Notes

ELI5

Resource Manager used to bulk-kill unbound terminals, which could close live sessions by mistake. Cleanup now needs review and confirmation, and only freshly verified idle shells with no child processes are closed, so active work is protected.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review 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
📝 Walkthrough

Walkthrough

Adds provider-aware PTY inactivity classification and guarded cleanup IPC with normalized inputs, ownership routing, revalidation, and fail-closed behavior. Adds preload and web API surfaces, renderer review and confirmation workflows, lifecycle state handling, status-bar integration, localized dialog copy, reliability-gate metadata, and unit/component tests. Adds an Electron smoke test verifying idle unbound sessions are removed while active sessions remain usable.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed The PR matches the issue's safety goals by adding review, revalidation, fail-closed handling, and regression coverage before cleanup.
Out of Scope Changes check ✅ Passed The change set stays focused on unbound-session cleanup, UI copy, localization, IPC, and tests, with no clear unrelated additions.
Title check ✅ Passed The title is concise and accurately summarizes the main change: protecting unbound terminal sessions with review and confirmation.
Description check ✅ Passed The description follows the template with Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes, and includes the required cross-platform review.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/main/ipc/pty.ts (1)

4962-4977: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not treat a newly disconnected SSH session as killed.

Line 4967 tombstones a missing SSH provider and returns successfully. If the provider disconnects after killInactiveSessions classifies an ID as inactive, Line 5035 reaches this force-kill behavior without invoking remote shutdown, and reports killed for a potentially live remote PTY. Keep this tombstone behavior exclusive to explicit pty:kill; guarded cleanup should return protected/failed when its provider disappears. Add a regression covering disconnect after inspection.

Proposed direction
 const shutdownPty = async (args: {
   id: string
   keepHistory?: boolean
+  allowDisconnectedSshTombstone?: boolean
 }): Promise<void> => {
   // ...
   if (!provider && connectionId) {
+    if (args.allowDisconnectedSshTombstone === false) {
+      throw new Error('PTY provider disconnected before guarded shutdown')
+    }
     finishPtyShutdown(args.id, connectionId, store)
     // existing explicit-force-kill lifecycle
     return
   }
 }
 
 ipcMain.handle('pty:kill', async (_event, args) =>
-  shutdownPty(args)
+  shutdownPty({ ...args, allowDisconnectedSshTombstone: true })
 )
 
 // guarded path: re-resolve immediately before shutdown and protect if absent
-await shutdownPty({ id, keepHistory: false })
+await shutdownPty({ id, keepHistory: false, allowDisconnectedSshTombstone: false })

As per PR objectives, disconnected sessions must be protected, and the plan requires guarded cleanup not to fall back from unavailable SSH ownership.

🧹 Nitpick comments (6)
src/renderer/src/components/status-bar/resource-session-cleanup-review.ts (2)

11-14: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Error messages bypass i18n and are shown raw to users.

RESOURCE_SESSION_CLEANUP_SESSION_NOT_READY_ERROR, RESOURCE_SESSION_CLEANUP_REVIEW_ERROR, and RESOURCE_SESSION_CLEANUP_EXECUTION_ERROR are plain English strings thrown as Error.message. Per the ResourceSessionCleanupDialog component (referenced context), the error phase renders state.message directly instead of a translated string, and the newly added en.json ResourceSessionCleanupDialog block (this PR) has no corresponding error key. Non-English users will see untranslated English error copy when review/cleanup fails or the workspace isn't ready.

Consider exposing a discriminant (e.g. an error code enum) instead of relying on message-string equality, and have the dialog map that code to a translated string.


69-103: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Skip the inspection round-trip when nothing is unbound.

executeResourceSessionCleanup already short-circuits when eligibleIds.length === 0 (line 155), avoiding an unnecessary killInactiveSessions call. reviewResourceSessionCleanup doesn't have the analogous guard: it always calls dependencies.inspectInactiveCleanup(reviewedIds) even when reviewedIds is empty (e.g., every PTY is currently bound to a renderer tab). Since this runs every time the cleanup review dialog opens, adding an early return for the empty case avoids a wasted IPC round trip on the common "nothing unbound" path.

♻️ Proposed guard
     const reviewedIds = sessions.map((session) => session.id).filter((id) => !boundPtyIds.has(id))
+    if (reviewedIds.length === 0) {
+      return { reviewedIds, inspections: [], inactiveIds: [], activeCount: 0, unknownCount: 0, goneCount: 0 }
+    }
     const returned = await dependencies.inspectInactiveCleanup(reviewedIds)
src/renderer/src/components/status-bar/resource-session-cleanup-review.test.ts (1)

45-148: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Missing coverage for executeResourceSessionCleanup's guard/error-mapping paths.

Tests exist for reviewResourceSessionCleanup's "not ready" guard (line 83) and transport-error mapping (line 93), but executeResourceSessionCleanup shares the exact same requireReadyBindingIndex guard and try/catch error-mapping shape and has no equivalent tests (e.g. workspace not ready during execute, or killInactiveSessions/listSessions throwing and being mapped to RESOURCE_SESSION_CLEANUP_EXECUTION_ERROR). Since this is a safety-critical cleanup path, it's worth covering both branches for parity with the review-side tests.

src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.tsx (1)

61-83: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract phase-driven description/footer into helper functions.

Both the description (Lines 61-83) and footer (Lines 139-201) are 4-5 level nested ternaries keyed off state.phase. As more phases/edge cases are added this will get harder to follow safely. A switch-based helper (or per-phase sub-components) would make each branch easier to review and extend.

♻️ Example extraction for the description block
+function getDialogDescription(state: ResourceSessionCleanupReviewState): string {
+  switch (state.phase) {
+    case 'reviewing':
+      return translate(
+        'auto.components.status.bar.ResourceSessionCleanupDialog.reviewing',
+        'Checking current process activity…'
+      )
+    case 'running':
+      return translate(
+        'auto.components.status.bar.ResourceSessionCleanupDialog.running',
+        'Closing confirmed inactive terminals…'
+      )
+    case 'completed':
+      return translate(
+        'auto.components.status.bar.ResourceSessionCleanupDialog.completed',
+        'Cleanup finished. Review the verified result below.'
+      )
+    case 'error':
+      return state.message
+    default:
+      return translate(
+        'auto.components.status.bar.ResourceSessionCleanupDialog.description',
+        'Only terminals freshly verified as idle shells can be closed. Active and unverified terminals are protected.'
+      )
+  }
+}
+
 <DialogDescription className="text-xs">
-  {state.phase === 'reviewing' ? ... : ...}
+  {getDialogDescription(state)}
 </DialogDescription>

The footer buttons block can follow the same pattern (a renderFooterActions(state, { onClose, onRetry, onConfirm }) helper returning the JSX for each phase).

Also applies to: 139-201

src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx (1)

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

Assertion only checks button presence, not the unbound "always visible" behavior.

The kill button is unconditionally rendered for both bound and unbound rows (ResourceUsageStatusSegment.tsx Lines 426-430); the distinguishing behavior is the absence of the can-hover:opacity-0 class for unbound rows. Checking only for DOM presence doesn't verify that differentiator.

♻️ Proposed stronger assertion
     expect(container.querySelector('button[aria-label="Kill session unbound-a"]')).not.toBeNull()
+    expect(
+      container
+        .querySelector('button[aria-label="Kill session unbound-a"]')
+        ?.className.includes('can-hover:opacity-0')
+    ).toBe(false)
src/renderer/src/components/status-bar/use-resource-session-cleanup-review.test.tsx (1)

115-139: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add a final assertion after the locked cleanup settles.

The test confirms close() is a no-op while phase === 'running', but never verifies the hook actually reaches completed once the guarded cleanup resolves. Adding that assertion would fully validate the documented guarantee that "confirmed cleanup stays non-cancellable and continues to settlement."

✅ Suggested addition
     await act(async () => {
       cleanup.resolve([{ id: 'idle', outcome: 'killed' }])
       await completion
     })
+    expect(result.current.state.phase).toBe('completed')
   })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 21122048-7941-469b-9e76-d12a92464858

📥 Commits

Reviewing files that changed from the base of the PR and between 8abe093 and 3c352da.

📒 Files selected for processing (27)
  • config/reliability-gates.jsonc
  • docs/superpowers/plans/2026-07-13-resource-manager-unbound-session-safety.md
  • docs/superpowers/specs/2026-07-13-resource-manager-unbound-session-safety-design.md
  • src/main/ipc/pty-inactive-cleanup.test.ts
  • src/main/ipc/pty-inactive-cleanup.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.test.tsx
  • src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.tsx
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.session-polling.test.ts
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.tsx
  • src/renderer/src/components/status-bar/resource-session-cleanup-review.test.ts
  • src/renderer/src/components/status-bar/resource-session-cleanup-review.ts
  • src/renderer/src/components/status-bar/use-resource-session-cleanup-review.test.tsx
  • src/renderer/src/components/status-bar/use-resource-session-cleanup-review.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/web/web-preload-api.ts
  • src/shared/pty-inactive-cleanup.test.ts
  • src/shared/pty-inactive-cleanup.ts
  • tests/e2e/resource-session-unbound-cleanup-safety.spec.ts

@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

Fork-local CI validation completed against the exact upstream base/head commits while the upstream fork workflows await maintainer approval:

The temporary fork PR was closed after the checks settled. The upstream PR Checks and Wayland runs remain action_required until a stablyai/orca maintainer approves external-contributor workflows.

@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

All actionable review findings, including the SSH disconnect-after-inspection race and both inline comments, are addressed in exact head 8ed55cde7492fe5c23d5a64f0aa521e2e56f5591.

Local verification on that change set: 353 focused tests passed, typecheck passed, lint passed, desktop/web build passed, and the strengthened real-daemon Electron E2E passed twice. Upstream fork workflows require maintainer approval; please approve the pending Actions runs for this head.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

@bbingz Thanks for the update. I'll re-review the PR at head 8ed55cde7492fe5c23d5a64f0aa521e2e56f5591 to verify the SSH disconnect-after-inspection race fix and the two inline comment resolutions.

Note that approving pending Actions runs for external-contributor workflows is a repository/GitHub Actions permission matter that a stablyai/orca maintainer will need to handle directly — that's outside what I can action here.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

Merged current upstream main (0b65d725c98d6552f08fb512f4026b350b7fbf0b) without conflicts. New exact head: 3d52c606dd1cf56b0dffc698663295ec77de40dd.

Post-merge verification passed: 353 focused tests, lint, typecheck, desktop/web build, diff check, and the strengthened real-daemon Electron E2E. Exact-head fork CI is running at bbingz#4.

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
src/renderer/src/i18n/locales/ja.json (1)

3247-3249: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Replace “kill” terminology in the cleanup dialog actions.

These fallbacks still say “kill,” while this flow is explicitly intended to use review/unbound terminology and the dialog closes only verified inactive terminals. Update the source strings to “close,” then resync locale catalogs.

Proposed wording
-            "none": "No inactive terminals to kill",
-            "killOne": "Kill 1 inactive terminal",
-            "killMany": "Kill {{value0}} inactive terminals",
+            "none": "No inactive terminals to close",
+            "killOne": "Close 1 inactive terminal",
+            "killMany": "Close {{value0}} inactive terminals",
src/renderer/src/i18n/locales/zh.json (1)

3247-3249: 📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Remove “kill” from the review dialog CTA.

The new flow still exposes “Kill … inactive terminals”, contradicting the PR’s review terminology and making the confirmation action sound like an unreviewed force-kill. Update the source fallback/key names in ResourceSessionCleanupDialog.tsx, then resync locale catalogs.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: ae28d8f0-3845-440a-8a36-baf0d2379eac

📥 Commits

Reviewing files that changed from the base of the PR and between 3c352da and 3d52c60.

📒 Files selected for processing (21)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/preload/api-types.ts
  • src/preload/index.ts
  • src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.test.tsx
  • src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.tsx
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.session-polling.test.ts
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.tsx
  • src/renderer/src/components/status-bar/resource-session-cleanup-review.test.ts
  • src/renderer/src/components/status-bar/resource-session-cleanup-review.ts
  • src/renderer/src/components/status-bar/use-resource-session-cleanup-review.test.tsx
  • src/renderer/src/components/status-bar/use-resource-session-cleanup-review.ts
  • src/renderer/src/i18n/locales/en.json
  • src/renderer/src/i18n/locales/es.json
  • src/renderer/src/i18n/locales/ja.json
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/zh.json
  • src/renderer/src/web/web-preload-api.ts
  • tests/e2e/resource-session-unbound-cleanup-safety.spec.ts
🚧 Files skipped from review as they are similar to previous changes (19)
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.session-polling.test.ts
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.rows.test.tsx
  • src/preload/index.ts
  • src/preload/api-types.ts
  • src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.tsx
  • tests/e2e/resource-session-unbound-cleanup-safety.spec.ts
  • src/renderer/src/i18n/locales/ko.json
  • src/renderer/src/i18n/locales/en.json
  • config/reliability-gates.jsonc
  • src/renderer/src/web/web-preload-api.ts
  • src/main/ipc/pty.test.ts
  • src/renderer/src/components/status-bar/resource-session-cleanup-review.ts
  • src/renderer/src/components/status-bar/use-resource-session-cleanup-review.test.tsx
  • src/renderer/src/i18n/locales/es.json
  • src/main/ipc/pty.ts
  • src/renderer/src/components/status-bar/resource-session-cleanup-review.test.ts
  • src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.test.tsx
  • src/renderer/src/components/status-bar/use-resource-session-cleanup-review.ts
  • src/renderer/src/components/status-bar/ResourceUsageStatusSegment.tsx

@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

Exact-head fork CI is green for current head 3d52c606dd1cf56b0dffc698663295ec77de40dd against base 0b65d725c98d6552f08fb512f4026b350b7fbf0b:

The fork-only track-community-pr metadata job is not a product/code gate and cannot map the temporary fork PR to an upstream community PR. The temporary validation PR is closed and its base branch deleted. Upstream external-contributor runs still require maintainer approval.

@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

The two outside-diff close/kill terminology findings are addressed in exact head 834902f3a9b670d2cf204ff6b0290e18d18e9b5c.

The dialog now uses close terminology in source fallbacks and all five locale catalogs, with the translation keys renamed from killOne/killMany to closeOne/closeMany. The dialog regression was changed first and failed on the old CTA, then passed after the implementation update.

Local verification: 8 focused files / 332 tests passed; lint, typecheck, localization catalog parity, localization coverage, and diff check passed. Exact-head fork CI is running at bbingz#7.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

@bbingz Thanks for the update. I'll re-review the PR at head 834902f3a9b670d2cf204ff6b0290e18d18e9b5c to verify the close/kill terminology fixes across the dialog source and all five locale catalogs.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

Exact-head CI is green for current head 834902f3a9b670d2cf204ff6b0290e18d18e9b5c against base 0b65d725c98d6552f08fb512f4026b350b7fbf0b after the final close-terminology review fix:

The verify job includes lint, typecheck, full tests, unpacked app build, and packaged CLI smoke. The fork-only track-community-pr metadata job cannot map a temporary fork validation PR to an upstream PR and is not a code/product gate. The temporary PR is closed and its base branch removed.

@bbingz

bbingz commented Jul 13, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (1)
src/main/ipc/pty-inactive-cleanup.ts (1)

106-112: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Simplify inactiveTargets filtering and unref the timer.

Since firstInspection strictly maps 1:1 with targets and maintains the exact same order, you can use an index-based lookup to avoid an O(N^2) .find() operation. Additionally, consider calling unref() on the timer to prevent it from unnecessarily keeping the Node event loop alive if cleanup happens during app shutdown.

♻️ Proposed refactor
-  delay: (milliseconds: number) => Promise<void> = (milliseconds) =>
-    new Promise((resolve) => setTimeout(resolve, milliseconds))
+  delay: (milliseconds: number) => Promise<void> = (milliseconds) =>
+    new Promise((resolve) => {
+      const timer = setTimeout(resolve, milliseconds)
+      if (typeof timer.unref === 'function') timer.unref()
+    })
 ): Promise<PtyCleanupInspection[]> {
   const firstInspection = await inspectPtyInactiveCleanupTargets(targets)
   const inactiveTargets = targets.filter(
-    ({ id }) => firstInspection.find((inspection) => inspection.id === id)?.safety === 'inactive'
+    (_, index) => firstInspection[index].safety === 'inactive'
   )

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: f39bdfa1-4d0a-4734-947f-022bbd80ee55

📥 Commits

Reviewing files that changed from the base of the PR and between c707d2b and 06d5fdf0f0d97f7c8a17226c13e951ac62503a24.

📒 Files selected for processing (5)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty-inactive-cleanup.test.ts
  • src/main/ipc/pty-inactive-cleanup.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • config/reliability-gates.jsonc

@bbingz

bbingz commented Jul 16, 2026

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Synced current upstream main at 1ba71d2cee59d12687a32e1d595247b0c2677a85 and resolved the reliability-manifest conflict by preserving the upstream gate updates plus this PR's single terminal-session.unbound-cleanup-safety entry. Exact head: f55beb19f2bb29eae97058f04a2179cdbd2e2b46.

Post-merge verification passed: 11 focused files / 369 tests, typecheck, full lint (including reliability, max-lines, skill-guide, and localization gates), desktop/web build, and the real-daemon Electron E2E that kills the idle unbound shell while preserving later input on the active session. The PR is now mergeable; upstream check runs have not yet been attached to this external-contributor head.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

@bbingz Thanks for the update. I'll re-review the PR at head f55beb19f2bb29eae97058f04a2179cdbd2e2b46 to verify the merge resolution against upstream main and confirm the terminal-session.unbound-cleanup-safety reliability gate entry was preserved correctly.

✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@bbingz

bbingz commented Jul 22, 2026

Copy link
Copy Markdown
Contributor Author

Rebased onto latest origin/main (force-with-lease).

Conflict resolution notes:

  • Kept main's remote: PTY id rejection on kill/shutdown
  • Ported inactive-session inspect/kill IPC boundary + SSH disconnect fail-closed policy for guarded cleanup (explicit kill still tombstones)
  • Resource Manager: orphan→unbound terminology, review/confirm cleanup flow instead of bulk kill
  • Reliability gate + locale updates for unbound cleanup safety

@bbingz
bbingz force-pushed the fix/resource-manager-orphan-safety branch from 1229177 to 96430cb Compare July 23, 2026 02:41
@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack note

Rebased onto latest main (force-with-lease). Resolved i18n keep-both conflicts in en/es/ja/ko/zh.json:

  • Kept main’s UsageRosterPanel + RemoteServerUpdateStatusSegment
  • Kept this PR’s ResourceSessionCleanupDialog strings

No intentional behavior change beyond main drift + i18n union.

@bbingz

bbingz commented Jul 23, 2026

Copy link
Copy Markdown
Contributor Author

Restack note

Rebased onto latest main (force-with-lease). All 12 commits applied cleanly (i18n keep-both already resolved in prior restack).

Scope (unique vs main):

  • Classify unbound candidates as idle shells (fail closed on active/unknown/SSH disconnect)
  • Resource Manager review dialog before bulk cleanup — not a one-click kill

Coordinates with (avoid three confirm UIs):

PR Role
#10013 Attribution + orphan-sweep confirm gate (who/why + rebind re-filter)
#8467 (this) Idle-shell classification review UI in Resource Manager
#8888 Protocol soft-deny / rate-limit for unattributed destructive closes — no third modal
#9752 Windows Job Object reaping after an authorized kill

Landing order preference: instrument/confirm (#10013) → how kill completes on Windows (#9752) → idle classification (#8467). #8888 stays orthogonal at the RPC policy layer.

@bbingz
bbingz force-pushed the fix/resource-manager-orphan-safety branch from 96430cb to cd36af3 Compare July 23, 2026 03:26
@bbingz
bbingz force-pushed the fix/resource-manager-orphan-safety branch from cd36af3 to a7c3652 Compare July 24, 2026 08:17
@nwparker nwparker added the bug Something isn't working label Jul 27, 2026
@bbingz
bbingz force-pushed the fix/resource-manager-orphan-safety branch 2 times, most recently from 07cffd9 to 91c5058 Compare July 28, 2026 04:37
@bbingz
bbingz force-pushed the fix/resource-manager-orphan-safety branch from 91c5058 to 2b1a9a9 Compare July 31, 2026 09:56
@bbingz
bbingz requested a review from brennanb2025 as a code owner July 31, 2026 09:56
@greptile-apps

greptile-apps Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR replaces the Resource Manager's direct bulk-kill of renderer-unbound PTY sessions with an explicit review-and-confirm flow. Sessions are now classified at the owning provider boundary, and only freshly verified idle shells with no child processes are eligible for closure; active, unknown, disconnected, SSH-owned, newly bound, and already-gone sessions are protected or skipped.

  • IPC boundary hardening: Two new handlers (inspectInactiveCleanup, killInactiveSessions) gate destructive action behind a fresh double-inspection; the resolveInactiveCleanupProvider helper fails-closed for disconnected SSH PTYs instead of falling through to the local provider.
  • Renderer coordinator + dialog: reviewResourceSessionCleanup and executeResourceSessionCleanup enforce a renderer-side binding re-check between review and confirmation; the ResourceSessionCleanupDialog presents typed error codes translated through the catalog rather than raw English strings.
  • Locale update gap: New ResourceSessionCleanupDialog catalog entries are correctly added to all five locale files, but the existing hash-keyed entries in ResourceUsageStatusSegment that the new code reuses for the "unbound" count badge and footer button still carry the old "orphan"/"Kill" English values in every locale file.

Confidence Score: 4/5

The destructive IPC path is solid — double-classification, fail-closed SSH provider resolution, binding re-checks, and the 500-ID cap all work correctly. The one concrete defect is that the locale catalog values for four ResourceUsageStatusSegment translation keys were never updated, so every user sees 'Kill N orphan terminal(s)' and 'N orphan(s)' in the badge/footer rather than the intended 'Review N unbound terminal(s)'.

The core safety logic (inspection, guarded shutdown, coordinator, hook, dialog) is well-structured and the test coverage is thorough. The locale bug is a real, present UI defect: i18next returns the catalog value when the key exists, so the new fallback text is never shown in any of the five supported languages. Everything else in the changed files reads correctly.

Files Needing Attention: All five locale files — en.json, es.json, ja.json, ko.json, zh.json — need the four stale ResourceUsageStatusSegment entries updated to match the new unbound/Review terminology.

Important Files Changed

Filename Overview
src/renderer/src/i18n/locales/en.json ResourceSessionCleanupDialog entries correctly added; however, four ResourceUsageStatusSegment keys reused by the new unbound/Review UI still carry old orphan/Kill values in all five locale files, so the catalog overrides the new fallback text for every user.
src/main/ipc/pty.ts Adds inspectInactiveCleanup and killInactiveSessions IPC handlers; resolveInactiveCleanupProvider correctly fails-closed for disconnected SSH sessions; killInactiveSessions re-classifies before destruction so sessions active at confirm time are protected.
src/main/ipc/pty-inactive-cleanup.ts New inspector that groups IDs by owning provider, calls listProcesses once per provider, and classifies each PTY as inactive/active/unknown/gone. Fail-closed on every error path; agent-owner listings guard against legacy providers that lack the claim API.
src/renderer/src/components/status-bar/resource-session-cleanup-review.ts Coordinator reads bindings after the async session inventory (not at click time), freezes the reviewed ID set, re-checks bindings at execution time, and accounts for newly-bound/gone sessions before calling killInactiveSessions.
src/renderer/src/components/status-bar/ResourceUsageStatusSegment.tsx Single-row kill now routes through the force-kill confirmation dialog (no longer bypassing for unbound rows); unboundCount drives the footer review button; sessionCleanupReview dialog is hoisted outside PopoverContent to survive popover close mid-interaction.
src/renderer/src/components/status-bar/ResourceSessionCleanupDialog.tsx Dialog correctly blocks dismissal during running phase, shows typed error codes translated through the catalog, and exposes only aggregate counts with no process IDs.
src/renderer/src/components/status-bar/use-resource-session-cleanup-review.ts Hook correctly guards mount-check on all state updates and increments operationGenerationRef to cancel stale review callbacks. Running cleanup is non-cancellable; post-kill session refresh is wrapped in a silent catch.
tests/e2e/resource-session-unbound-cleanup-safety.spec.ts E2E test spawns idle and sleep-running sessions via preload, polls until classified correctly, calls killInactiveSessions, then proves the active session accepts shell commands via a split marker that cannot be satisfied by TTY echo alone.

Comments Outside Diff (1)

  1. src/renderer/src/i18n/locales/en.json, line 3115-3157 (link)

    P1 Stale locale values override new default text for all users

    The translate() function calls i18n.t(key, { defaultValue: fallback }). i18next returns the catalog value whenever the key is present, so the defaultValue is never reached. Four keys still carry the old "orphan"/"Kill" strings in every locale file, meaning all users see the outdated text regardless of language:

    • 30ff2c3c31 → "{{value0}} orphan" (code default: "{{value0}} unbound terminal")
    • b8f4a2c1d0e3 → "{{value0}} orphans" (code default: "{{value0}} unbound terminals")
    • c7e3b1a0d9f2 → "Kill {{value0}} orphan terminal" (code default: "Review {{value0}} unbound terminal")
    • d8f4c2b1e0a3 → "Kill {{value0}} orphan terminals" (code default: "Review {{value0}} unbound terminals")

    The same stale values are present in es.json, ja.json, ko.json, and zh.json. The ResourceSessionCleanupDialog keys were correctly added, but the ResourceUsageStatusSegment entries that were repurposed to carry the new "unbound/Review" meaning were not updated in any catalog file.

Reviews (1): Last reviewed commit: "fix(resource-manager): wire cleanup revi..." | Re-trigger Greptile

@nwparker

nwparker commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Closing as superseded — the linked issue(s) for this PR were fixed by another change that has already been merged.

Superseding merge: #10893

Thank you for the contribution! If anything remains unaddressed, please open a new issue or PR against current main.

@nwparker nwparker closed this Aug 3, 2026
@bbingz

bbingz commented Aug 6, 2026

Copy link
Copy Markdown
Contributor Author

Agreed that #10893 covers the core rule — selectUnboundDaemonSessions now gates on mayDestroyWithoutOwnerEvidence (agentOwnership === 'absent'), and single-row kills route through requiresKillConfirmation.

One piece from this PR is still open on 2ff2a1b26: the bulk path skips confirmation entirely. ResourceUsageStatusSegment.tsx:1497-1498 calls handleKillOrphans directly, and handleKillOrphans (lines 1068-1083) kills every selected session immediately — the same asymmetry resource-session-kill-confirmation.ts was introduced to close for the single-row path.

The surviving evidence is agent ownership only, so a plain shell running a long build reports agentOwnership: 'absent' and gets swept with no prompt, still under "Kill {N} orphan terminals" copy.

Happy to open a small follow-up against current main: route the bulk button through the existing confirm dialog with the affected session list, and drop the "orphan"/"kill" wording. No change to the #10893 evidence gate.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Resource Manager misclassifies live daemon sessions as orphan and force-kills them without confirmation

5 participants