test: remove weak recovery observation and repeated lifecycle cases

This commit is contained in:
OrcaWin
2026-11-13 15:27:49 -08:00
parent cb381e0ac4
commit 4e1be3b26a
5 changed files with 1 additions and 518 deletions
@@ -220,22 +220,6 @@ it('retires a preparation waiter on full authority death without late creation',
}
})
it('keeps a successful real RPC handoff alive after caller cancellation', async () => {
const h = createRecoveryLoop([])
try {
h.attach()
const cancelled = new AbortController()
expect(await ordinaryPageRpc(h)('browser.tabCreate', 'handed-off', cancelled.signal)).toEqual([
expect.objectContaining({ ok: true })
])
cancelled.abort()
expect(h.pages.getPage('handed-off')?.placement).toEqual(h.authority.getPlacement('handed-off'))
expect(h.executor.snapshotPageInventory().map((p) => p.browserPageId)).toEqual(['handed-off'])
} finally {
await h.close()
}
})
it('transfers a real logical-capacity publication failure to exact cleanup until its join', async () => {
const h = createRecoveryLoop([])
try {
@@ -1,6 +1,3 @@
import * as initializationSettlement from '../../browser-host/client-pages/browser-host-page-initialization-settlement'
import * as initializationCommands from '../../browser-host/client-pages/browser-host-page-initialization-commands'
import * as pageAdoption from './runtime-browser-client-page-adoption'
import { workspaceSessionStateSchema } from '../../../../shared/workspace-session/workspace-session-schema'
import { prepareBrowserClientPageInventoryForAttach } from '../../../browser/client-pages/lifecycle/browser-client-page-inventory'
import { BrowserClientPageMetadataTransport } from '../../../browser/client-pages/renderer/browser-client-page-metadata-transport'
@@ -37,62 +34,6 @@ async function action(h: Harness, type: 'stop' | 'navigate', url?: string) {
return responses[0]
}
it('accepts missing-guest Stop and Retry, supersedes a pending agent goto, and honors intentional blank', async () => {
const h = createRecoveryLoop(['slow', 'fast'])
const navigating = h.hold('slow')
try {
h.attach()
await navigating
const next = h.hold('next')
const goto = h.hostRuntime.routeClientHostedBrowserRpc(
'browser.goto',
{
page: 'slow',
url: 'https://example.internal/next',
expectUrl: 'https://example.internal/slow'
},
{ kind: 'local-cli' }
)
const cancelled = expect(goto).rejects.toThrow('initialization_cancelled')
await next
expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/slow')
const stopped = await action(h, 'stop')
expect(stopped).toMatchObject({ ok: true })
await cancelled
await vi.waitFor(() =>
expect(h.executor.snapshotPageInventory().map((p) => p.browserPageId)).toEqual(['fast'])
)
expect(
h.hostRuntime
.snapshotForClient(WORKSPACE, 'device-a')
.tabs.find((t) => t.type === 'browser' && t.browserPageId === 'slow')
).toMatchObject({
initializationState: 'stopped',
loading: false,
url: 'https://example.internal/slow'
})
const retried = h.hold('retry')
expect((await action(h, 'navigate', 'https://example.internal/retry')).ok).toBe(true)
await retried
expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/retry')
expect(
h.profile.session.clientHostedBrowserPagesByWorktree?.[WORKSPACE]?.find(
(p) => p.browserPageId === 'slow'
)
).not.toHaveProperty('initializationState')
const blank = await action(h, 'navigate', 'about:blank')
expect(blank.ok).toBe(true)
await h.published('slow')
expect(h.pages.getPage('slow')?.url).toBe('data:text/html,')
expect(
h.authority.clientPageInitializations.status('slow', h.pages.getPage('slow')!.placement)
).toBeUndefined()
expect(h.errors).toEqual([])
} finally {
await h.close()
}
})
it('follows the same row through commit while the workspace resolver is awaited and rejects a closed owner', async () => {
const h = createRecoveryLoop(['slow'])
const navigating = h.hold('slow')
@@ -408,88 +349,24 @@ it('keeps the UI successor through a truthful empty reconnect while the prior na
const initial = h.hold('slow')
const closeReply = Promise.withResolvers<void>()
const physicallyClosed = Promise.withResolvers<void>()
const trace: string[] = []
const initialization = h.authority.clientPageInitializations
const settle = initializationSettlement.settleInitialization
vi.spyOn(initializationSettlement, 'settleInitialization').mockImplementation(
(operation, outcome, owner) => {
const requested = operation.admission.input.url
trace.push(`terminal-enter:${requested}:${outcome}`)
const result = settle(operation, outcome, owner)
trace.push(`terminal-return:${requested}:${outcome}`)
return result
}
)
const forget = initializationCommands.forgetAbsentInitializationTarget
vi.spyOn(initializationCommands, 'forgetAbsentInitializationTarget').mockImplementation(
(...args) => {
trace.push('authoritative-absence-join')
return forget(...args)
}
)
const observe = initialization.observeAttach.bind(initialization)
vi.spyOn(initialization, 'observeAttach').mockImplementation((state, inventory, complete) => {
trace.push(`observe:${state.lease.connectionId}:${inventory?.length}`)
if (state.lease.connectionId === 'connection-2') {
trace.push('release-close-result-inside-observe')
closeReply.resolve()
}
return observe(state, inventory, complete)
})
const admit = initialization.admit.bind(initialization)
vi.spyOn(initialization, 'admit').mockImplementation((state, input) => {
const connectionId = state.lease.connectionId
trace.push(`admit:${connectionId}:${input.url}`)
const disposition = admit(state, {
...input,
settled: (outcome) => {
trace.push(`settle:${connectionId}:${outcome}`)
input.settled?.(outcome)
}
})
trace.push(`admit-return:${connectionId}:${disposition}`)
return disposition
})
const delivery = h.authority.attachCommandDelivery.bind(h.authority)
vi.spyOn(h.authority, 'attachCommandDelivery').mockImplementation((...args) => {
trace.push('delivery-attached')
return delivery(...args)
})
const adopt = pageAdoption.adoptRuntimeBrowserClientPagesFromInventory
vi.spyOn(pageAdoption, 'adoptRuntimeBrowserClientPagesFromInventory').mockImplementation(
(options) => {
const result = adopt(options)
trace.push(`adoption-return:${options.lease.connectionId}`)
return result
}
)
const seal = initialization.sealAttach.bind(initialization)
vi.spyOn(initialization, 'sealAttach').mockImplementation((...args) => {
trace.push(`seal:${args[0].lease.connectionId}`)
return seal(...args)
})
const acceptResult = h.authority.settleClientPageCommand.bind(h.authority)
vi.spyOn(h.authority, 'settleClientPageCommand').mockImplementation((...args) => {
const accepted = acceptResult(...args)
const oldClose = h.commands.find((event) => event.command.type === 'closePage')
trace.push(
`ledger-result:${args[1].commandId === oldClose?.commandId ? 'old-close' : 'other'}:${accepted}`
)
return accepted
})
try {
const first = h.attach()
await initial
const cleanup = h.holdRetirement('slow')
h.hooks.beforeResult = async (event) => {
if (event.command.type === 'closePage') {
trace.push('native-closed-result-held')
physicallyClosed.resolve()
await closeReply.promise
trace.push('close-result-sent')
}
}
h.hooks.onResult = (event) => trace.push(`result:${event.command.type}`)
const requested = h.hold('B')
expect(await action(h, 'navigate', 'https://example.internal/B')).toMatchObject({ ok: true })
await cleanup.started
@@ -497,10 +374,8 @@ it('keeps the UI successor through a truthful empty reconnect while the prior na
await physicallyClosed.promise
const inventory = h.executor.snapshotPageInventory()
expect(inventory).toEqual([])
trace.push('truthful-empty-attach')
const second = h.attach({ inventory })
await requested
trace.push('B-native-started')
h.release('B', 'https://example.internal/B-redirect')
await vi.waitFor(() =>
expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/B-redirect')
@@ -513,7 +388,6 @@ it('keeps the UI successor through a truthful empty reconnect while the prior na
'https://example.internal/B-redirect'
)
expect(h.errors).toEqual([])
console.info('R18-R1 native/result transport trace', trace)
first.abort()
second.abort()
await Promise.all([first.completion, second.completion])
@@ -1,275 +0,0 @@
import { RpcDispatcher } from '../../rpc/dispatcher'
import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs'
import { expect, it, vi } from 'vitest'
import { createReconciliationDeliveryRuntime } from './client-page-reconciliation-delivery-test-harness'
import { openRecoveryTabsStream } from './client-page-recovery-stream-test-harness'
const WORKSPACE = 'repo-1::/tmp/worktree-a'
vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true }))
it.each([750, 7500])(
'owes no completion for %i workspace updates filtered by a real RPC stream',
async (count) => {
vi.useFakeTimers({ toFake: ['Date'] })
const h = createReconciliationDeliveryRuntime()
const runtime = h.hostRuntime
const snapshots = [
WORKSPACE,
...Array.from({ length: count }, (_, index) => `repo-1::/tmp/filtered-${index}`)
].map((worktree) => ({
worktree,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
}))
runtime.attachWindow(1)
runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: snapshots })
const stream = openRecoveryTabsStream(runtime, 'filtered-stream', `id:${WORKSPACE}`)
const facts = runtime.sidebarFacts!
const refresh = vi.spyOn(facts.workspaceActivityFacts, 'refreshWorkspace')
try {
await stream.initial
for (const snapshot of snapshots.slice(1)) {
runtime.notifyMobileSessionTabsChanged(snapshot.worktree)
}
runtime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')()
expect(stream.frames.every((frame) => frame.worktree === WORKSPACE)).toBe(true)
vi.setSystemTime(Date.now() + 46_000)
runtime.notifyMobileSessionTabsChanged(WORKSPACE)
runtime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')()
expect(stream.frames.at(-1)?.clientHostedPagesUnreconciled).toBeUndefined()
runtime.projectedFrames = 0
refresh.mockClear()
const sequence = runtime.sessionTabsSequence()
const delivered = stream.frames.length
runtime.markClientHostedPagesReconciled('device-a')
expect(runtime.projectedFrames).toBe(0)
expect(runtime.sessionTabsSequence()).toBe(sequence)
expect(stream.frames).toHaveLength(delivered)
expect(refresh).not.toHaveBeenCalled()
} finally {
stream.stop()
await h.close()
refresh.mockRestore()
vi.useRealTimers()
}
}
)
it.each(['workspace', 'all'])(
'keeps an independent held read after %s stream progression, then forgets disposed streams and removed workspaces',
async (kind) => {
vi.useFakeTimers({ toFake: ['Date'] })
const h = createReconciliationDeliveryRuntime()
const runtime = h.hostRuntime
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree: WORKSPACE,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
}
]
})
const stream = openRecoveryTabsStream(
runtime,
'progressing-stream',
kind === 'workspace' ? `id:${WORKSPACE}` : undefined
)
const independent = openRecoveryTabsStream(runtime, 'independent-stream')
try {
await Promise.all([stream.initial, independent.initial])
const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS })
const reads: string[] = []
await rpc.dispatchStreaming(
{ id: 'independent-read', authToken: 'test', method: 'session.tabs.listAll', params: {} },
(reply) => reads.push(reply),
{ connectionId: 'independent-read', pairedDeviceId: 'device-a', clientKind: 'mobile' }
)
expect(JSON.parse(reads[0]!).result.snapshots[0].clientHostedPagesUnreconciled).toBe(true)
independent.stop()
await independent.completion
vi.setSystemTime(Date.now() + 46_000)
runtime.notifyMobileSessionTabsChanged(WORKSPACE)
runtime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')()
expect(stream.frames.at(-1)?.clientHostedPagesUnreconciled).toBeUndefined()
runtime.projectedFrames = 0
const delivered = stream.frames.length
runtime.markClientHostedPagesReconciled('device-a')
expect(runtime.projectedFrames).toBe(1)
expect(stream.frames).toHaveLength(delivered + 1)
expect(stream.frames.at(-1)?.clientHostedPagesUnreconciled).toBeUndefined()
runtime.markClientHostedPagesReconciled('device-a')
expect(runtime.projectedFrames).toBe(1)
expect(stream.frames).toHaveLength(delivered + 1)
stream.stop()
await stream.completion
vi.setSystemTime(Date.now() - 46_000)
const removed = openRecoveryTabsStream(runtime, 'removed-stream', undefined, 'device-b')
await removed.initial
expect(
removed.frames.findLast((frame) => frame.worktree === WORKSPACE)
?.clientHostedPagesUnreconciled
).toBe(true)
runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] })
runtime.projectedFrames = 0
runtime.markClientHostedPagesReconciled('device-b')
expect(runtime.projectedFrames).toBe(0)
removed.stop()
await removed.completion
} finally {
stream.stop()
independent.stop()
await h.close()
vi.useRealTimers()
}
}
)
it('cannot recreate a raw observation when its listener unsubscribes during delivery', async () => {
const h = createReconciliationDeliveryRuntime()
let unsubscribe = () => {}
try {
unsubscribe = h.hostRuntime.onMobileSessionTabsChanged(
() => unsubscribe(),
'device-a',
'mobile'
)
h.hostRuntime.notifyMobileSessionTabsChanged(WORKSPACE)
h.hostRuntime.onMobileSessionTabsChanged(() => {}, 'flush-device', 'mobile')()
h.hostRuntime.projectedFrames = 0
h.hostRuntime.markClientHostedPagesReconciled('device-a')
expect(h.hostRuntime.projectedFrames).toBe(0)
} finally {
unsubscribe()
await h.close()
}
})
it.each(['session.tabs.subscribe', 'session.tabs.subscribeAll'])(
'cannot recreate %s observations when initial output releases the stream',
async (method) => {
const h = createReconciliationDeliveryRuntime()
h.hostRuntime.attachWindow(1)
h.hostRuntime.syncWindowGraph(1, {
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree: WORKSPACE,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
}
]
})
const stopped = new AbortController()
const rpc = new RpcDispatcher({ runtime: h.hostRuntime, methods: SESSION_TAB_METHODS })
try {
let supplied = false
await rpc.dispatchStreaming(
{
id: 'release-during-output',
authToken: 'test',
method,
params: method === 'session.tabs.subscribe' ? { worktree: `id:${WORKSPACE}` } : {}
},
(reply) => {
if (['snapshot', 'snapshots'].includes(JSON.parse(reply).result?.type)) {
supplied = true
stopped.abort()
}
},
{
connectionId: 'release-during-output',
pairedDeviceId: 'device-a',
clientKind: 'mobile',
signal: stopped.signal
}
)
expect(supplied).toBe(true)
h.hostRuntime.projectedFrames = 0
h.hostRuntime.markClientHostedPagesReconciled('device-a')
expect(h.hostRuntime.projectedFrames).toBe(0)
} finally {
stopped.abort()
await h.close()
}
}
)
it.each([750, 7500])(
'does no completion projection for %i held read replies after that device unsubscribes',
async (count) => {
const h = createReconciliationDeliveryRuntime()
const runtime = h.hostRuntime
const snapshots = Array.from({ length: count }, (_, index) => ({
worktree: `repo-1::/tmp/unsubscribed-${index}`,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
}))
runtime.attachWindow(1)
runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: snapshots })
const departed = openRecoveryTabsStream(runtime, 'departing-device-stream')
const other = openRecoveryTabsStream(
runtime,
'remaining-device-stream',
`id:${snapshots[0]!.worktree}`,
'device-b'
)
const refresh = vi.spyOn(runtime.sidebarFacts!.workspaceActivityFacts, 'refreshWorkspace')
try {
await Promise.all([departed.initial, other.initial])
const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS })
const reads: string[] = []
await rpc.dispatchStreaming(
{ id: 'held-read', authToken: 'test', method: 'session.tabs.listAll', params: {} },
(reply) => reads.push(reply),
{ connectionId: 'held-read', pairedDeviceId: 'device-a', clientKind: 'runtime' }
)
const supplied = JSON.parse(reads[0]!).result.snapshots
expect(supplied).toHaveLength(count)
expect(
supplied.every(
(frame: { clientHostedPagesUnreconciled?: true }) =>
frame.clientHostedPagesUnreconciled === true
)
).toBe(true)
departed.stop()
await departed.completion
runtime.projectedFrames = 0
refresh.mockClear()
const sequence = runtime.sessionTabsSequence()
const delivered = other.frames.length
runtime.markClientHostedPagesReconciled('device-a')
expect(runtime.projectedFrames).toBe(0)
expect(runtime.sessionTabsSequence()).toBe(sequence)
expect(other.frames).toHaveLength(delivered)
expect(refresh).not.toHaveBeenCalled()
} finally {
departed.stop()
other.stop()
await Promise.all([departed.completion, other.completion])
await h.close()
refresh.mockRestore()
}
}
)
@@ -2,98 +2,7 @@ import { createRecoveryPeer } from './client-page-recovery-peer-test-harness'
import { expect, it, vi } from 'vitest'
import { createRecoveryLoop } from './client-page-recovery-loop-test-harness'
import { retireRuntimeBrowserClientPage } from './browser-client-page-close'
import {
buildPersistedClientHostedBrowserPages,
RESTORED_CLIENT_HOSTED_BROWSER_PLACEMENT
} from './client-hosted-browser-page-persistence'
it('a new attach owns the successor while exact prior cleanup is still joining', async () => {
const h = createRecoveryLoop(['slow', 'fast'])
const started = h.hold('slow')
const first = h.attach()
try {
await started
await h.published('fast')
const retirement = h.holdRetirement('slow')
first.disconnect()
const next = h.attach()
await retirement.started
first.abort()
await first.completion
expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/slow')
expect(h.pages.getPage('slow')?.placement.pageHostGeneration).toBe(0)
expect(h.pages.getPage('fast')?.placement.pageHostGeneration).toBeGreaterThan(0)
h.release('slow')
retirement.release()
await h.published('slow')
expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/slow')
expect(h.authority.getClientPageExecutionHostKey('slow')).toBe('execution-host-a')
expect(
h.results
.filter((result) => result.id === 'slow')
.map((result) => [result.type, result.status])
).toContainEqual(['closePage', 'completed'])
expect(h.errors).toEqual([])
next.abort()
await next.completion
} finally {
await h.close()
}
})
it.each(['client-a', 'replacement-client'])(
'a fully retired ledger recovers its saved continuation on %s',
async (hostId) => {
const h = createRecoveryLoop(['slow'])
try {
let current = h.attach()
await h.published('slow')
for (let round = 0; round < 3; round += 1) {
h.fence()
current.abort()
await current.completion
await h.restartClient()
const started = h.hold('slow')
current = h.attach({ inventory: [] })
await started
const saved = h.pages.getPage('slow')!
expect(saved.placement.pageHostGeneration).toBeGreaterThan(0)
h.fence()
current.abort()
await current.completion
await h.restartClient()
h.release('slow')
current = h.attach({ hostId, inventory: [] })
await vi.waitFor(() =>
expect(h.authority.getPlacement('slow')).toMatchObject({
kind: 'client',
browserHostClientId: hostId
})
)
expect(h.pages.getPage('slow')?.url).toBe('https://example.internal/slow')
expect(h.executor.snapshotPageInventory()).toHaveLength(1)
expect(h.authority.getClientPageExecutionHostKey('slow')).toBe('execution-host-a')
}
await retireRuntimeBrowserClientPage(
{
getBrowserHostLeaseRegistry: () => h.authority,
notifyHeadlessBrowserSessionTabsChanged: (id) =>
h.hostRuntime.notifyMobileSessionTabsChanged(id),
getRuntimeBrowserPageRegistry: () => h.pages,
resolveBrowserWorkspace: async () => ({ id: 'workspace' })
},
h.pages.getPage('slow')!
)
expect(h.executor.snapshotPageInventory()).toEqual([])
expect(buildPersistedClientHostedBrowserPages(h.pages.listPages(), 100)).toEqual([])
current.abort()
await current.completion
expect(h.errors).toEqual([])
} finally {
await h.close()
}
}
)
import { RESTORED_CLIENT_HOSTED_BROWSER_PLACEMENT } from './client-hosted-browser-page-persistence'
it('full retirement preserves another live scope successor and an unrelated host', async () => {
const h = createRecoveryLoop(['slow'])
@@ -1,9 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { TuiAgent } from './agent-launch/catalog/tui-agent'
import { requireTuiAgentConfig } from './require-tui-agent-config'
describe('requireTuiAgentConfig', () => {
it('rejects a prototype key that Object.hasOwn keeps off the config', () => {
expect(() => requireTuiAgentConfig('toString' as TuiAgent)).toThrow(/Unknown agent "toString"/)
})
})