Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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 @@ -2,8 +2,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as TrackingDecisions from './web-session-tabs-sync/tracking-decisions'
import {
activateWebRuntimeSessionTab,
closeWebRuntimeSessionTab
closeWebRuntimeSessionTab,
replayWebSessionTabCloses
} from './web-runtime-session-tab-lifecycle'
import {
queueWebSessionCloseReplay,
resetWebSessionCloseReplaysForTests,
takeDueWebSessionCloseReplays
} from './web-session-close-replay'
import {
peekWebSessionFocusIntent,
resetWebSessionFocusIntentForTests
Expand Down Expand Up @@ -87,7 +93,10 @@ vi.mock('./web-runtime-browser-materialization', () => ({
hasMaterializedWebRuntimeBrowserPage: mocks.hasMaterializedWebRuntimeBrowserPage
}))

afterEach(() => resetWebSessionCloseIntentForTests())
afterEach(() => {
resetWebSessionCloseIntentForTests()
resetWebSessionCloseReplaysForTests()
})

describe('web runtime session tab actions', () => {
beforeEach(() => {
Expand Down Expand Up @@ -595,6 +604,148 @@ describe('web runtime session tab actions', () => {
expect(mocks.acceptReplayedWebSessionTabsSnapshot).not.toHaveBeenCalled()
})

// STA-6224: clearing on a dropped connection let the host's next snapshot re-add the tab.
it('holds a user close the host never received and sends it again once reachable', async () => {
const runtimeCall = vi
.fn()
.mockRejectedValueOnce(new Error('socket hang up'))
.mockResolvedValueOnce({ id: 'close', ok: true, result: { closed: true } })
.mockResolvedValue({ id: 'list', ok: true, result: makeSnapshot() })
stubRuntimeEnvironmentBridge({ call: runtimeCall })
const owner = { environmentId: ENVIRONMENT_ID }

await expect(
closeWebRuntimeSessionTab({
worktreeId: WORKTREE_ID,
tabId: 'local-browser-unified',
reason: 'user'
})
).resolves.toBe('failed')

// Durable: a reconnect long after the RPC timeout must still not re-show it.
expect(
isWebSessionCloseIntentPending(
owner,
WORKTREE_ID,
'host-browser-unified',
Date.now() + 60_000
)
).toBe(true)
const due = takeDueWebSessionCloseReplays(owner, WORKTREE_ID, new Set(['host-browser-unified']))
expect(due.map((replay) => replay.hostTabIds[0])).toEqual(['host-browser-unified'])

await replayWebSessionTabCloses(ENVIRONMENT_ID, due)

const closeCalls = runtimeCall.mock.calls.filter(
([request]: unknown[]) =>
typeof request === 'object' &&
request !== null &&
'method' in request &&
request.method === 'session.tabs.close'
)
expect(closeCalls).toHaveLength(2)
expect(closeCalls[1]?.[0]).toMatchObject({
params: { tabId: 'host-browser-unified', reason: 'user' }
})
expect(
takeDueWebSessionCloseReplays(owner, WORKTREE_ID, new Set(['host-browser-unified']))
).toEqual([])
})

it('re-lists the worktree after holding a close so an idle host still gets the first replay', async () => {
vi.useFakeTimers()
try {
const runtimeCall = vi.fn().mockRejectedValue(new Error('socket hang up'))
stubRuntimeEnvironmentBridge({ call: runtimeCall })

await closeWebRuntimeSessionTab({
worktreeId: WORKTREE_ID,
tabId: 'local-browser-unified',
reason: 'user'
})
const callsAfterClose = runtimeCall.mock.calls.length
await vi.advanceTimersByTimeAsync(5_000)

expect(
runtimeCall.mock.calls
.slice(callsAfterClose)
.some(
([request]: unknown[]) =>
typeof request === 'object' &&
request !== null &&
'method' in request &&
request.method === 'session.tabs.list'
)
).toBe(true)
} finally {
vi.useRealTimers()
}
})

it('re-lists the worktree after a failed replay so an idle host still gets the next attempt', async () => {
vi.useFakeTimers()
try {
const runtimeCall = vi.fn().mockRejectedValue(new Error('socket hang up'))
stubRuntimeEnvironmentBridge({ call: runtimeCall })
const owner = { environmentId: ENVIRONMENT_ID }
queueWebSessionCloseReplay(owner, WORKTREE_ID, ['host-browser-unified'])

await replayWebSessionTabCloses(
ENVIRONMENT_ID,
takeDueWebSessionCloseReplays(owner, WORKTREE_ID, new Set(['host-browser-unified']))
)
const callsAfterReplay = runtimeCall.mock.calls.length
await vi.advanceTimersByTimeAsync(5_000)

const relisted = runtimeCall.mock.calls
.slice(callsAfterReplay)
.some(
([request]: unknown[]) =>
typeof request === 'object' &&
request !== null &&
'method' in request &&
request.method === 'session.tabs.list'
)
expect(relisted).toBe(true)
} finally {
vi.useRealTimers()
}
})

it('never replays a held close to an environment re-paired since', async () => {
const runtimeCall = vi.fn()
stubRuntimeEnvironmentBridge({ call: runtimeCall })
const staleOwner = { environmentId: ENVIRONMENT_ID, pairingRevision: 99 }
queueWebSessionCloseReplay(staleOwner, WORKTREE_ID, ['host-browser-unified'])

await replayWebSessionTabCloses(
ENVIRONMENT_ID,
takeDueWebSessionCloseReplays(staleOwner, WORKTREE_ID, new Set(['host-browser-unified']))
)

expect(runtimeCall).not.toHaveBeenCalled()
})

it('does not hold a lifecycle close the host never received', async () => {
stubRuntimeEnvironmentBridge({ call: vi.fn().mockRejectedValue(new Error('socket hang up')) })

await closeWebRuntimeSessionTab({
worktreeId: WORKTREE_ID,
tabId: 'local-browser-unified',
reason: 'cleanup',
publicationEpoch: 'epoch-1',
terminalHandle: 'term-1'
})

expect(
takeDueWebSessionCloseReplays(
{ environmentId: ENVIRONMENT_ID },
WORKTREE_ID,
new Set(['host-browser-unified'])
)
).toEqual([])
})

it('clears an optimistic close intent when pairing CAS rejects the host call', async () => {
const runtimeCall = vi.fn().mockResolvedValue({
id: 'close-rejected',
Expand Down
124 changes: 116 additions & 8 deletions src/renderer/src/runtime/web-runtime-session-tab-lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,22 @@ import type {
RuntimeSessionTabCloseReason
} from '../../../shared/runtime-types'
import { useAppStore } from '../store'
import { hasRuntimeRpcErrorCode, unwrapRuntimeRpcResult } from './runtime-rpc-result'
import {
hasRuntimeRpcErrorCode,
RuntimeRpcCallError,
unwrapRuntimeRpcResult
} from './runtime-rpc-result'
import { toRuntimeWorktreeSelector } from './runtime-worktree-selector'
import {
clearWebSessionCloseIntent,
makeWebSessionCloseIntentDurable,
recordWebSessionCloseIntent
} from './web-session-close-intent'
import {
queueWebSessionCloseReplay,
settleWebSessionCloseReplay,
type WebSessionCloseReplay
} from './web-session-close-replay'
import {
clearWebSessionFocusIntent,
clearWebSessionFocusIntentIfMatches,
Expand All @@ -21,7 +30,8 @@ import { toHostSessionTabId } from '../../../shared/terminal-surface-id'
import {
captureRuntimeEnvironmentCall,
captureWebSessionIntentOwner,
isWebRuntimeSessionActive
isWebRuntimeSessionActive,
matchesWebSessionIntentOwner
} from './web-runtime-session-environment'
import { refreshWebRuntimeSessionTabsSnapshot } from './web-runtime-session-snapshot'

Expand Down Expand Up @@ -74,10 +84,88 @@ export async function closeWebRuntimeSessionTab(args: {
reason: RuntimeSessionTabCloseReason
publicationEpoch?: string | null
terminalHandle?: string | null
/** A replay's pairing; the call is refused if the environment was re-paired since. */
expectedPairingRevision?: number
}): Promise<WebRuntimeSessionTabCloseOutcome> {
return callWebRuntimeSessionTabMethod('session.tabs.close', args)
}

// Why these and a bare rejection only: they mean the close never reached the host, so sending it
// again is the user's own close. A structured refusal (e.g. a re-paired host) is an answer.
const UNDELIVERED_CLOSE_CODES = new Set([
'runtime_unavailable',
'remote_runtime_unavailable',
'runtime_timeout',
'remote_runtime_timeout'
])

function isUndeliveredCloseFailure(error: unknown): boolean {
return !(error instanceof RuntimeRpcCallError) || UNDELIVERED_CLOSE_CODES.has(error.code)
}

/** Keeps a user close the host never received, hiding the tab until a replay reaches the host. */
function holdUndeliveredUserClose(
intentOwner: ReturnType<typeof captureWebSessionIntentOwner>,
worktreeId: string,
hostTabIds: readonly string[]
): void {
for (const hostTabId of hostTabIds) {
recordWebSessionCloseIntent(intentOwner, worktreeId, hostTabId, Date.now())
makeWebSessionCloseIntentDurable(intentOwner, worktreeId, hostTabId)
}
queueWebSessionCloseReplay(intentOwner, worktreeId, hostTabIds)
scheduleWebSessionCloseReplayRelist(intentOwner.environmentId, worktreeId)
}

const WEB_SESSION_CLOSE_REPLAY_RETRY_DELAY_MS = 5_000

// Why a re-list: subscriptions are change-driven, so an idle worktree may never publish the
// snapshot that makes the next attempt due. The re-list's receipt does.
function scheduleWebSessionCloseReplayRelist(environmentId: string, worktreeId: string): void {
setTimeout(() => {
void refreshWebRuntimeSessionTabsSnapshot(environmentId, worktreeId)
}, WEB_SESSION_CLOSE_REPLAY_RETRY_DELAY_MS)
}

/** Sends again the user closes a host snapshot proved reachable; see `takeDueWebSessionCloseReplays`. */
export async function replayWebSessionTabCloses(
environmentId: string,
replays: readonly WebSessionCloseReplay[]
): Promise<void> {
for (const replay of replays) {
// Why: the close was the old pairing's; a replacement host must never receive it.
if (!matchesWebSessionIntentOwner(replay.owner)) {
settleWebSessionCloseReplay(replay, true)
continue
}
const outcome = await closeWebRuntimeSessionTab({
worktreeId: replay.worktreeId,
tabId: replay.hostTabIds[0],
environmentId,
reason: 'user',
...(replay.owner.pairingRevision !== undefined
? { expectedPairingRevision: replay.owner.pairingRevision }
: {})
})
const settled = settleWebSessionCloseReplay(replay, outcome !== 'failed')

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 | 🟡 Minor | ⚡ Quick win

Treat a definitive refusal of a replayed close as settled, not as a retry.

closeWebRuntimeSessionTab returns 'failed' for two different cases:

  • The close did not reach the host (undelivered).
  • The host refused the close with a structured RuntimeRpcCallError code that is not in UNDELIVERED_CLOSE_CODES.

On a refusal, the inner catch takes the else branch at Line 324-331 and clears the close intents. The tab becomes visible again. Line 150 still passes delivered = false, so the replay stays in pendingReplays as 'retry'. The next snapshot that lists the tab then runs replayWebSessionClosesDueForSnapshot. That call hides the tab again and sends the close again. The tab flickers and the close is resent until the attempt limit is reached.

The comment at Line 93-94 says a structured refusal "is an answer." The replay path does not follow that contract.

The fix: return a distinct outcome for undelivered failures, or have the replay classify the error. Settle as delivered when the failure is a definitive refusal.

Proposed direction
-export type WebRuntimeSessionTabCloseOutcome = 'applied' | 'unknown-tab' | 'failed'
+export type WebRuntimeSessionTabCloseOutcome = 'applied' | 'unknown-tab' | 'failed' | 'undelivered'
...
-    return hostHasNoSuchTab ? 'unknown-tab' : 'failed'
+    if (hostHasNoSuchTab) return 'unknown-tab'
+    return isUndeliveredCloseFailure(error) ? 'undelivered' : 'failed'
...
-    const settled = settleWebSessionCloseReplay(replay, outcome !== 'failed')
+    const settled = settleWebSessionCloseReplay(replay, outcome !== 'undelivered')

If you add a new outcome value, check the existing callers that compare against 'failed'.

if (settled === 'retry') {
scheduleWebSessionCloseReplayRelist(environmentId, replay.worktreeId)
continue
}
if (settled === 'done') {
continue
}
// The host kept failing the close; show the tab again rather than hide a live one forever.
for (const hostTabId of replay.hostTabIds) {
clearWebSessionCloseIntent(replay.owner, replay.worktreeId, hostTabId)
}
// The unchanged snapshot that made this replay due would otherwise be refused as stale.
await refreshWebRuntimeSessionTabsSnapshot(environmentId, replay.worktreeId, {
acceptCurrentSnapshot: true
})
}
}

function resolveTabEnvironmentId(environmentId: string | null | undefined): string | null {
return (
environmentId?.trim() ??
Expand All @@ -97,13 +185,22 @@ async function callWebRuntimeSessionTabMethod(
terminalHandle?: string | null
leafId?: string | null
expectedCurrentLocalTabId?: string | null
expectedPairingRevision?: number
}
): Promise<WebRuntimeSessionTabCloseOutcome> {
const environmentId = resolveTabEnvironmentId(args.environmentId)
if (!environmentId || !isWebRuntimeSessionActive(environmentId)) {
if (environmentId && method === 'session.tabs.close' && args.reason === 'user') {
holdUndeliveredUserClose(captureWebSessionIntentOwner(environmentId), args.worktreeId, [
toHostSessionTabId(args.tabId)
])
}
return 'failed'
}
const intentOwner = captureWebSessionIntentOwner(environmentId)
const intentOwner =
args.expectedPairingRevision !== undefined
? { environmentId, pairingRevision: args.expectedPairingRevision }
: captureWebSessionIntentOwner(environmentId)
const callEnvironment = captureRuntimeEnvironmentCall(environmentId, intentOwner.pairingRevision)
const closeIntentTabIds = new Set<string>()
let activationHostTabId: string | null = null
Expand Down Expand Up @@ -215,11 +312,22 @@ async function callWebRuntimeSessionTabMethod(
const hostHasNoSuchTab =
hasRuntimeRpcErrorCode(error, 'tab_not_found') ||
hasRuntimeRpcErrorCode(error, 'terminal_tab_not_found')
for (const hostTabId of closeIntentTabIds) {
if (hostHasNoSuchTab) {
makeWebSessionCloseIntentDurable(intentOwner, args.worktreeId, hostTabId)
} else {
clearWebSessionCloseIntent(intentOwner, args.worktreeId, hostTabId)
if (
isClose &&
args.reason === 'user' &&
!hostHasNoSuchTab &&
isUndeliveredCloseFailure(error)
) {
// Why: clearing here let the host's next snapshot bring back a tab the user closed (STA-6224).
// The resolved host id was added last and is the one the host knows.
holdUndeliveredUserClose(intentOwner, args.worktreeId, [...closeIntentTabIds].toReversed())
} else {
for (const hostTabId of closeIntentTabIds) {
if (hostHasNoSuchTab) {
makeWebSessionCloseIntentDurable(intentOwner, args.worktreeId, hostTabId)
} else {
clearWebSessionCloseIntent(intentOwner, args.worktreeId, hostTabId)
}
}
}
if (isLifecycleClose) {
Expand Down
Loading
Loading