Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
d285a67
fix(terminal): every explicit terminal close commits through one main…
brennanb2025 Sep 25, 2026
7012c3e
fix(terminal): tell the desktop renderer to drop a split pane main cl…
brennanb2025 Sep 25, 2026
fc5cac5
fix(terminal): a pane close never widens into a whole-tab close
brennanb2025 Sep 25, 2026
95abe04
test(terminal): cover the PTY-handle branch of a CLI split-pane close
brennanb2025 Sep 25, 2026
bc8bbd7
fix(terminal): a CLI pane close with an unconfirmed stop closes only …
brennanb2025 Sep 25, 2026
f860b7d
refactor(terminal): one resolver decides whether a pane close becomes…
brennanb2025 Sep 26, 2026
25e31cb
fix(cli): an unverifiable stop says the close happened
brennanb2025 Sep 26, 2026
07496c1
fix(terminal): a phone pane close commits even when its kill fails
brennanb2025 Sep 26, 2026
a201c79
fix(terminal): a pane close widens only when a copy shows it is the l…
brennanb2025 Sep 26, 2026
0a808ae
fix(cli): promise a kill retry only when the host recorded the kill
brennanb2025 Sep 26, 2026
28613ff
test(pty): justify the controller cast the recorded-stop tests extend
brennanb2025 Sep 26, 2026
e17f7a6
fix(terminal): parse the close target with typed narrowing
brennanb2025 Sep 26, 2026
6734584
Merge origin/main into terminal-close-intents: close transaction over…
brennanb2025 Sep 26, 2026
3e78690
fix(terminal): a desktop tab close is not refused by a split that bou…
brennanb2025 Sep 26, 2026
b6db605
chore(terminal): note that closedByLayoutOwner goes away once main ow…
brennanb2025 Sep 26, 2026
a0782a7
Merge origin/main into terminal-close-intents (brings #22810, #22919)
brennanb2025 Sep 27, 2026
1c2c599
test(terminal): reload the close-intent fixture through the SQLite pr…
brennanb2025 Sep 27, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -552,7 +552,7 @@ describe('registerCoreHandlers', () => {
expect(registerLocalhostWorktreeLabelHandlersMock).toHaveBeenCalledWith(store)
expect(registerTelemetryHandlersMock).toHaveBeenCalledWith(store)
expect(registerOrcaProfileHandlersMock).toHaveBeenCalledWith(store, { onBeforeRelaunch })
expect(registerSessionHandlersMock).toHaveBeenCalledWith(store)
expect(registerSessionHandlersMock).toHaveBeenCalledWith(store, runtime)
expect(registerUIHandlersMock).toHaveBeenCalledWith(store, {
isDashboardPopoutRenderer: isDashboardPopoutRendererMock
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ export function registerCoreHandlers(
registerBrowserHandlers()
registerShellHandlers(store)
registerPetHandlers()
registerSessionHandlers(store)
registerSessionHandlers(store, runtime)
registerUIHandlers(store, { isDashboardPopoutRenderer })
registerEmulatorFrameStreamHandlers()
registerEmulatorVideoStreamHandlers()
Expand Down
18 changes: 17 additions & 1 deletion src/main/ipc/session.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import { ipcMain } from 'electron'
import type { Store } from '../persistence'
import type { OrcaRuntimeService } from '../runtime/orca-runtime'
import type {
WorkspaceSessionPatch,
WorkspaceSessionState
} from '../../shared/workspace-session-state-types'

export function registerSessionHandlers(store: Store): void {
export function registerSessionHandlers(store: Store, runtime: OrcaRuntimeService): void {
// Why: hostId is an optional second arg so an older renderer that invokes
// these channels without it keeps reading/writing the 'local' partition
// exactly as before. Channel names stay stable.
Expand All @@ -28,6 +29,21 @@ export function registerSessionHandlers(store: Store): void {
store.patchWorkspaceSession(args, hostId)
})

// Why: a renderer save cannot shrink membership main owns, so each close commits it explicitly.
ipcMain.handle(
'session:close-terminal-surface',
(_event, args: { worktreeId: string; tabId: string; leafId?: string }) => {
if (typeof args?.worktreeId !== 'string' || typeof args.tabId !== 'string') {
throw new Error('invalid_terminal_surface')
}
runtime.closeTerminalSurfaceFromRenderer({
worktreeId: args.worktreeId,
tabId: args.tabId,
...(typeof args.leafId === 'string' ? { leafId: args.leafId } : {})
})
}
)

ipcMain.handle('session:flush', () => {
// Why: durable lifecycle RPCs must propagate disk failures instead of
// returning success through Store.flush(), which intentionally only logs.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,10 @@ import type {
} from '../../shared/runtime-types'
import { getRuntimeBrowserPageRegistry } from './runtime-browser-page-registry'
import type { Tab } from '../../shared/tab-types'
import { closeTerminalTabInWorkspaceSession } from '../../shared/workspace-session-terminal-tab-close'
import { advanceTerminalTopologyRevision } from './workspace-session-terminal-membership-authority'
import { closeTerminalSurfaceInWorkspaceSession } from './terminal-surface-close'
import { retireTerminalSurfacesFromSnapshot } from './mobile-session-terminal-retirement'
import type { PtyControllerInventory } from './runtime-pty-controller-contract'
import { FLOATING_TERMINAL_WORKTREE_ID } from '../../shared/constants'
import { rollbackWorkspaceSessionAfterFailedAsyncWrite } from './workspace-session-failed-write-rollback'

export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRuntimeWithPersistTerminalSurfaceRetirements {
// Why: headless serve backs browser panes with offscreen WebContents that live
Expand Down Expand Up @@ -78,46 +77,102 @@ export class OrcaRuntimeWithBuildHeadlessMobileSessionBrowserTabs extends OrcaRu
return tab ? { color: tab.color, isPinned: tab.isPinned } : null
}

protected commitHeadlessTerminalTabRetirement(
/**
* The one close transaction every explicit terminal close reaches: commit the membership
* removal in the owning host's partition, then flush. Callers publish and kill afterwards.
*/
protected closeTerminalSurface(
worktreeId: string,
parentTabId: string,
options: { allowMissing?: boolean; force?: boolean } = {}
tabId: string,
options: { leafId?: string; allowMissing?: boolean; force?: boolean } = {}
): string[] {
const session = this.getWorkspaceSessionForWorktree(worktreeId)
if (!session || !this.store?.setWorkspaceSession || !this.store.flushOrThrow) {
throw new Error('workspace_session_unavailable')
}
const result = closeTerminalTabInWorkspaceSession(session, worktreeId, parentTabId, {
force: options.force
})
const result = closeTerminalSurfaceInWorkspaceSession(session, worktreeId, tabId, options)
if (result.pinned) {
throw new Error('terminal_tab_pinned')
}
if (!result.closed) {
if (!options.allowMissing) {
throw new Error('tab_not_found')
}
return []
}
const persisted = result.closed
? advanceTerminalTopologyRevision(result.session, worktreeId)
: session
this.setWorkspaceSessionForWorktree(worktreeId, persisted)
const staged = this.getWorkspaceSessionForWorktree(worktreeId)
this.setWorkspaceSessionForWorktree(worktreeId, result.session)
try {
this.store.flushOrThrow()
} catch (error) {
const current = this.getWorkspaceSessionForWorktree(worktreeId)
if (staged && current) {
const rolledBack = rollbackWorkspaceSessionAfterFailedAsyncWrite(session, staged, current)
if (rolledBack !== current) {
this.setWorkspaceSessionForWorktree(worktreeId, rolledBack)
}
}
throw error
// Why no rollback: bookkeeping must not undo a user's close or skip its kill; the removal
// stays in memory and the next flush writes it. Only host-started retirements roll back.
console.error('[runtime] failed to flush terminal close:', error)
}
return result.ptyIdsToKill
}

/** The desktop renderer's close intent: the renderer already ran its pin guard and owns the kill. */
closeTerminalSurfaceFromRenderer(args: {
worktreeId: string
tabId: string
leafId?: string
}): void {
this.closeTerminalSurface(args.worktreeId, args.tabId, {
leafId: args.leafId,
allowMissing: true,
force: true
})
}

/**
* Commits a split pane's close that main started once its process was stopped, then tells the
* desktop renderer to drop that leaf. No session means nothing persisted to remove.
*/
protected closeTerminalLeaf(worktreeId: string, tabId: string, leafId: string): void {
try {
// Why force: the process is already stopped, so a pin must not fail the close after the fact.
this.closeTerminalSurface(worktreeId, tabId, { leafId, allowMissing: true, force: true })
} catch (error) {
if (!(error instanceof Error) || error.message !== 'workspace_session_unavailable') {
throw error
}
}
// Why: no exit may ever arrive to remove the pane. The notice is leaf-addressed, so it and the
// renderer's exit handling are each a no-op after the other.
this.retireClosedTerminalLeafFromMobileSnapshot(worktreeId, tabId, leafId)
this.notifier?.closeTerminal(tabId, leafId)
}

private retireClosedTerminalLeafFromMobileSnapshot(
worktreeId: string,
tabId: string,
leafId: string
): void {
const snapshot = this.mobileSessionTabsByWorktree.get(worktreeId)
const tab = snapshot?.tabs.find(
(candidate) =>
candidate.type === 'terminal' &&
candidate.parentTabId === tabId &&
candidate.leafId === leafId
)
// Why: a renderer that lists the tab republishes its own snapshot once it drops the pane.
if (!snapshot || !tab || this.tabs.has(tabId)) {
return
}
const proof = this.getMobileSessionTerminalRetirementProof(worktreeId, tab)
const retired = retireTerminalSurfacesFromSnapshot({
snapshot,
ptyId: tab.ptyId ?? tab.parentLayout?.ptyIdsByLeafId?.[leafId] ?? '',
exactSurfaces: [{ parentTabId: tabId, leafId }],
exactOnly: true,
...(proof ? { retirementProofs: [proof] } : {})
})
if (retired) {
this.storeMobileSessionSnapshot(worktreeId, retired.snapshot)
this.notifyMobileSessionTabsChanged(worktreeId)
}
}

protected persistHeadlessTerminalTabOrder(worktreeId: string, tabOrder: readonly string[]): void {
const session = this.getWorkspaceSessionForWorktree(worktreeId)
if (!session || !this.store?.setWorkspaceSession) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,10 @@ export class OrcaRuntimeWithCloseHeadlessMobileTerminalTab extends OrcaRuntimeWi
)
return proof ? [proof] : []
})
const projectedPtyIds = this.commitHeadlessTerminalTabRetirement(
worktreeId,
closedParentTabId,
{ allowMissing: options.allowMissingPersistedTab, force: options.force }
)
const projectedPtyIds = this.closeTerminalSurface(worktreeId, closedParentTabId, {
allowMissing: options.allowMissingPersistedTab,
force: options.force
})
this.clearRuntimeSessionOwnershipForMobileTab(worktreeId, snapshot, closedParentTabId)
if (options.authorizedPty) {
options.authorizedPty.runtimeSessionOwned = false
Expand Down
8 changes: 5 additions & 3 deletions src/main/runtime/orca-runtime-close-mobile-session-tab.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,9 +238,9 @@ export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseU
})
this.notifyRendererOfHeadlessTerminalClose(tab.parentTabId)
} else if (retirement.hasPersistedTab) {
this.commitHeadlessTerminalTabRetirement(worktreeId, tab.parentTabId, {
force: options.force
})
// Why: the renderer's close normally commits this through its own intent; this covers
// a renderer that acknowledged a tab it no longer listed.
this.closeTerminalSurface(worktreeId, tab.parentTabId, { force: options.force })
}
this.clearRuntimeSessionOwnershipForMobileTab(worktreeId, snapshot, tab.parentTabId)
return finishCommittedClose()
Expand Down Expand Up @@ -268,6 +268,8 @@ export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseU
if (this.ptyController?.kill(pty.ptyId) !== true) {
throw new Error('terminal_close_failed')
}
// Why: the pane's removal is this close's own commit, not a side effect of its exit.
this.closeTerminalLeaf(worktreeId, tab.parentTabId, tab.leafId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

set -eu
printf '%s\n' '--- changed file outline ---'
ast-grep outline src/main/runtime/orca-runtime-close-mobile-session-tab.ts
printf '%s\n' '--- target file around branch ---'
sed -n '220,300p' src/main/runtime/orca-runtime-close-mobile-session-tab.ts
printf '%s\n' '--- direct bindings and call sites ---'
rg -n -C 4 'closeTerminalLeaf|listMobileSessionTabs|mobileSessionTabsByWorktree|setMobileSession|publish.*Mobile|MobileSessionTabs' src/main
printf '%s\n' '--- diff for target file against supplied base ---'
git diff --unified=35 8fb13edd9ff98f3670bc09a1270cd69fb07ccc58 d285a67c0a3ce1007b87764b81c8a4356a99f34b -- src/main/runtime/orca-runtime-close-mobile-session-tab.ts

Repository: stablyai/orca

Length of output: 45665


🏁 Script executed:

set -eu
printf '%s\n' '--- closeTerminalLeaf declarations and calls ---'
rg -n -C 12 'closeTerminalLeaf\s*\(' src/main/runtime --glob '*.ts' --glob '!*.test.ts'
printf '%s\n' '--- finishCommittedClose declaration and calls ---'
rg -n -C 16 'finishCommittedClose\s*=|function finishCommittedClose|finishCommittedClose\s*\(' src/main/runtime/orca-runtime-close-mobile-session-tab.ts
printf '%s\n' '--- snapshot mutation and emission helpers in runtime sources ---'
rg -n -C 10 'storeMobileSessionSnapshot|emitMobileSessionTabsSnapshot|notifyMobileSessionTabsChanged' src/main/runtime/orca-runtime-close-mobile-session-tab.ts src/main/runtime/orca-runtime-close-structured-agent-session-tab.ts src/main/runtime/orca-runtime-sync-mobile-session-tabs.ts

Repository: stablyai/orca

Length of output: 34912


🏁 Script executed:

set -eu
printf '%s\n' '--- closeTerminalSurface declarations ---'
rg -n -C 18 'closeTerminalSurface\s*\(' src/main/runtime --glob '*.ts' --glob '!*.test.ts'
printf '%s\n' '--- closeTerminalLeaf file context ---'
sed -n '90,145p' src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts
printf '%s\n' '--- relevant snapshot/listing definitions ---'
rg -n -C 14 'getMobileSessionTabsForWorktree|listMobileSessionTabs|mobileSessionTabsByWorktree' src/main/runtime/orca-runtime-service.ts src/main/runtime --glob '*.ts' --glob '!*.test.ts' | head -n 500

Repository: stablyai/orca

Length of output: 41450


🏁 Script executed:

set -eu
printf '%s\n' '--- listMobileSessionTabs implementation ---'
rg -n -C 24 '(?:async\s+)?listMobileSessionTabs\s*\(' src/main/runtime --glob '*.ts' --glob '!*.test.ts'
printf '%s\n' '--- headless close implementation ---'
sed -n '1,125p' src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts
printf '%s\n' '--- snapshot emission and leaf-removal candidates ---'
rg -n -C 12 'leafId|parentLayout|emitMobileSessionTabsSnapshot|storeMobileSessionSnapshot' src/main/runtime/orca-runtime-close-headless-mobile-terminal-tab.ts src/main/runtime/orca-runtime-sync-mobile-session-tabs.ts src/main/runtime/orca-runtime-build-headless-mobile-session-browser-tabs.ts --glob '*.ts'

Repository: stablyai/orca

Length of output: 45659


🏁 Script executed:

set -eu
printf '%s\n' '--- exact non-test listing declarations ---'
rg -n 'listMobileSessionTabs' src/main/runtime --glob '*.ts' --glob '!*.test.ts' --glob '!*.spec.ts'
printf '%s\n' '--- candidate method contexts ---'
while IFS=: read -r file line rest; do
  [ -n "$file" ] || continue
  start=$((line-20)); [ "$start" -lt 1 ] && start=1
  end=$((line+45))
  printf '\n--- %s:%s ---\n' "$file" "$line"
  sed -n "${start},${end}p" "$file"
done < <(rg -n 'listMobileSessionTabs' src/main/runtime --glob '*.ts' --glob '!*.test.ts' --glob '!*.spec.ts' | cut -d: -f1-2)

Repository: stablyai/orca

Length of output: 1824


🏁 Script executed:

set -eu
sed -n '1,125p' src/main/runtime/orca-runtime-collect-mobile-visible-graph-changed-worktrees.ts

Repository: stablyai/orca

Length of output: 5598


🏁 Script executed:

set -eu
rg -n -C 25 'hydrateHeadlessMobileSessionTabsFromWorkspaceSession\s*\(' src/main/runtime --glob '*.ts' --glob '!*.test.ts' --glob '!*.spec.ts'

Repository: stablyai/orca

Length of output: 42310


🏁 Script executed:

set -eu
sed -n '31,240p' src/main/runtime/orca-runtime-hydrate-headless-mobile-session-tabs-from-workspace-session.ts

Repository: stablyai/orca

Length of output: 10097


🏁 Script executed:

set -eu
printf '%s\n' '--- hydration tail ---'
sed -n '180,270p' src/main/runtime/orca-runtime-hydrate-headless-mobile-session-tabs-from-workspace-session.ts
printf '%s\n' '--- storeMobileSessionSnapshot definition ---'
rg -n -C 18 'storeMobileSessionSnapshot\s*\(' src/main/runtime/orca-runtime-stored-mobile-snapshot-has-stale-preserved-tab.ts src/main/runtime --glob '*.ts' --glob '!*.test.ts' --glob '!*.spec.ts' | head -n 220

Repository: stablyai/orca

Length of output: 28146


🏁 Script executed:

set -eu
printf '%s\n' '--- exact snapshot store helper ---'
rg -n -C 10 '((protected|private|public)\s+)?storeMobileSessionSnapshot\s*\(' src/main/runtime --glob '*.ts' --glob '!*.test.ts' --glob '!*.spec.ts' | grep -E '^[^:]+:[0-9]+:' | head -n 120
printf '%s\n' '--- terminal snapshot retirement helpers ---'
rg -n -C 12 'retireTerminalSurfacesFromSnapshot|retire.*Terminal.*Snapshot|exactSurfaces' src/main/runtime --glob '*.ts' --glob '!*.test.ts' --glob '!*.spec.ts'

Repository: stablyai/orca

Length of output: 37166


🏁 Script executed:

set -eu
printf '%s\n' '--- store helper ---'
sed -n '80,125p' src/main/runtime/orca-runtime-runtime-id.ts
printf '%s\n' '--- touch helper ---'
sed -n '1,155p' src/main/runtime/orca-runtime-touch-mobile-session-tabs-for-worktree.ts
printf '%s\n' '--- retirement helper output shape ---'
sed -n '193,285p' src/main/runtime/mobile-session-terminal-retirement.ts

Repository: stablyai/orca

Length of output: 10569


🏁 Script executed:

set -eu
sed -n '1,35p' src/main/runtime/orca-runtime-close-mobile-session-tab.ts
sed -n '255,278p' src/main/runtime/orca-runtime-close-mobile-session-tab.ts

Repository: stablyai/orca

Length of output: 3026


Publish the leaf removal after a successful PTY kill.

This branch persists the workspace session removal but does not update or notify the mobile snapshot. A later listing is not sufficient in all cases. Without a PTY exit event, subscribed mobile clients can retain the closed leaf.

Suggested fix
 import { rendererPublicationThrottle } from '../window/renderer-publication-throttle'
+import { retireTerminalSurfacesFromSnapshot } from './mobile-session-terminal-retirement'
 
 export class OrcaRuntimeWithCloseMobileSessionTab extends OrcaRuntimeWithRefuseUnattributedMobileSessionTabClose {
...
           // Why: the pane's removal is this close's own commit, not a side effect of its exit.
           this.closeTerminalLeaf(worktreeId, tab.parentTabId, tab.leafId)
+          const retired = retireTerminalSurfacesFromSnapshot({
+            snapshot,
+            ptyId: pty.ptyId,
+            exactSurfaces: [{ parentTabId: tab.parentTabId, leafId: tab.leafId }],
+            exactOnly: true
+          })
+          if (retired) {
+            this.storeMobileSessionSnapshot(worktreeId, retired.snapshot)
+            this.notifyMobileSessionTabsChanged(worktreeId)
+          }
           return finishCommittedClose()

return finishCommittedClose()
}
this.notifier.closeTerminal(tab.parentTabId)
Expand Down
39 changes: 23 additions & 16 deletions src/main/runtime/orca-runtime-stop-explicitly-closed-tab-ptys.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { SSH_PROVIDER_UNREGISTERED_REASON } from '../../shared/pty-liveness-verd
import type { RuntimeTerminalClose } from '../../shared/runtime-types'
import { countTerminalLayoutLeaves } from './headless-terminal-split-layout'
import type { RuntimePtyTabCloseAuthority } from './runtime-terminal-state-records'
import { parsePaneKey } from '../../shared/stable-pane-id'

export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithFocusTerminal {
protected async stopExplicitlyClosedTabPtys(
Expand Down Expand Up @@ -155,28 +156,32 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF
return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled)
}
const ptyKilled = await this.stopExplicitlyClosedTabPtys([pty.pty.ptyId], pty.pty.ptyId)
if (!ptyKilled || siblingCount <= 1) {
if (surface) {
// Why: paired viewers keep ended streams mounted until the HUB publishes removal, so explicit close uses the durable host-tab transaction instead of viewer-local exit handling.
try {
await this.closeMobileSessionTab(`id:${pty.pty.worktreeId}`, tabId, {
localPtyTeardownOwnedExternally: true
})
} catch (error) {
if (!(error instanceof Error) || error.message !== 'workspace_session_unavailable') {
throw error
}
this.notifier?.closeTerminal(tabId)
if (siblingCount > 1) {
const leafId = surface?.tab.leafId ?? parsePaneKey(pty.pty.paneKey ?? '')?.leafId
// Why: the pane's removal is this close's own commit, not a side effect of its exit. An
// unconfirmed stop is unverifiable, never a reason to close the live siblings with it.
if (leafId) {
this.closeTerminalLeaf(pty.pty.worktreeId, tabId, leafId)
}
} else if (surface) {
// Why: paired viewers keep ended streams mounted until the HUB publishes removal, so explicit close uses the durable host-tab transaction instead of viewer-local exit handling.
try {
await this.closeMobileSessionTab(`id:${pty.pty.worktreeId}`, tabId, {
localPtyTeardownOwnedExternally: true
})
} catch (error) {
if (!(error instanceof Error) || error.message !== 'workspace_session_unavailable') {
throw error
}
} else {
this.notifier?.closeTerminal(tabId)
}
} else {
this.notifier?.closeTerminal(tabId)
}
return this.describeTerminalClose(handle, tabId, pty.pty.ptyId, ptyKilled)
}
this.assertGraphReady()
const { leaf } = this.getLiveLeafForHandle(handle)
// Why: in a multi-pane tab, killing the PTY is enough (renderer's exit handler closes the pane); an extra IPC close would race it and close the whole tab.
const siblingCount = this.countLeavesInTab(leaf.tabId)
const ptyIdsToKill =
siblingCount <= 1
Expand All @@ -190,8 +195,10 @@ export class OrcaRuntimeWithStopExplicitlyClosedTabPtys extends OrcaRuntimeWithF
const ptyKilled = leaf.ptyId
? await this.stopExplicitlyClosedTabPtys(ptyIdsToKill, leaf.ptyId)
: false
if (siblingCount > 1 ? !ptyKilled : !this.notifier?.closeTerminalTab) {
this.notifier?.closeTerminal(leaf.tabId, leaf.paneRuntimeId)
if (siblingCount > 1) {
this.closeTerminalLeaf(leaf.worktreeId, leaf.tabId, leaf.leafId)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Do not retire a split pane while its PTY stop is unverified.

If stopAndWait fails or times out, stopExplicitlyClosedTabPtys can return false after a follow-up kill attempt. This branch still removes the graph-backed pane and notifies the renderer. The PTY may remain running without a visible pane. Keep the surface until termination is verified, or define and enforce a separate recovery path for an unverified stop.

} else if (!this.notifier?.closeTerminalTab) {
this.notifier?.closeTerminal(leaf.tabId)
}
return this.describeTerminalClose(handle, leaf.tabId, leaf.ptyId ?? null, ptyKilled)
}
Expand Down
30 changes: 16 additions & 14 deletions src/main/runtime/orca-runtime-terminal-close-continuity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,25 +72,27 @@ describe('terminal close and handle incarnation continuity', () => {
unsubscribe()
})

it('publishes no retirement or absence when the durable headless close fails', async () => {
it('still kills and keeps the removal when the durable headless close fails to flush', async () => {
const harness = await createStaleTabCloseHarness({ headless: true })
const published = vi.fn()
const unsubscribe = harness.runtime.onMobileSessionTabsChanged(published)
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => undefined)
harness.rejectPersistenceFlush(new Error('disk-full'))

await expect(harness.runtime.closeTerminalTab(harness.terminal.handle)).rejects.toThrow(
'disk-full'
)
await expect(harness.runtime.closeTerminalTab(harness.terminal.handle)).resolves.toMatchObject({
tabId: TAB_ID,
closeMode: 'tab'
})

expect(harness.kill).not.toHaveBeenCalled()
expect(published).not.toHaveBeenCalled()
expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toHaveLength(1)
// Why: a failed flush is bookkeeping; the user's close still stops its process and the
// in-memory removal stays for the next flush to write.
expect(harness.kill).toHaveBeenCalledWith(RUNTIME_OWNED_PTY_ID)
expect(harness.getSession().tabsByWorktree[WORKTREE_ID]).toEqual([])
const snapshot = await harness.runtime.listMobileSessionTabs(`id:${WORKTREE_ID}`)
expect(snapshot).toMatchObject({
tabs: [expect.objectContaining({ parentTabId: TAB_ID, leafId: LEAF_ID })]
})
expect(snapshot.retiredTerminalSurfaces).toBeUndefined()
unsubscribe()
expect(snapshot.tabs).toEqual([])
expect(errorSpy).toHaveBeenCalledWith(
'[runtime] failed to flush terminal close:',
expect.any(Error)
)
errorSpy.mockRestore()
})

it('publishes each split leaf retirement with its own terminal handle', async () => {
Expand Down
Loading
Loading