Deliver client browser reconciliation completion to observed workspaces

This commit is contained in:
Brennan Benson
2026-11-12 00:35:04 -08:00
parent ed5fce8f7d
commit ea18664bc3
18 changed files with 1038 additions and 79 deletions
@@ -0,0 +1,94 @@
import type { WorkspaceSessionState } from '../../../../shared/workspace-session/workspace-session-state-types'
import { orderTerminalRowsByTabGroups } from '../../../../shared/workspace-layout/terminal-row-order'
const WT = 'repo-1::/tmp/worktree-a'
const storeBase = {
getRepo: () => ({
id: 'repo-1',
path: '/tmp/repo',
displayName: 'repo',
badgeColor: 'blue',
addedAt: 1
}),
getRepos: () => [storeBase.getRepo()],
addRepo: () => {},
updateRepo: () => {
throw new Error('unused fixture write')
},
getAllWorktreeMeta: () => ({}),
getWorktreeMeta: () => undefined,
getGitHubCache: () => ({ pr: {}, issue: {} }),
setWorktreeMeta: () => {
throw new Error('unused fixture write')
},
removeWorktreeMeta: () => {},
getRetiredWorktreeNameRegistry: () => ({ exhaustedTiers: 0, names: [] }),
addRetiredWorktreeName: () => {},
mergeRetiredWorktreeNames: () => false,
getSettings: () => ({
workspaceDir: '/tmp/workspaces',
nestWorkspaces: false,
refreshLocalBaseRefOnWorktreeCreate: false,
branchPrefix: 'none',
branchPrefixCustom: ''
})
}
export function createProfile(worktreeCount = 0) {
const work = { writes: 0, normalizedWorktrees: 0 }
let measuringWrite = false
const tabsByWorktree: WorkspaceSessionState['tabsByWorktree'] = {}
for (let index = 0; index < worktreeCount; index += 1) {
const id = index === 0 ? WT : `repo-1::/tmp/worktree-${index}`
const rows = [
{
id: `terminal-${index}`,
ptyId: null,
worktreeId: id,
title: 'Terminal',
customTitle: null,
color: null,
sortOrder: 0,
createdAt: 1
}
]
Object.defineProperty(tabsByWorktree, id, {
enumerable: true,
configurable: true,
get: () => {
if (measuringWrite) {
work.normalizedWorktrees += 1
}
return rows
}
})
}
const state: { session: WorkspaceSessionState } = {
session: {
activeRepoId: 'repo-1',
activeWorktreeId: WT,
activeTabId: null,
tabsByWorktree,
terminalLayoutsByTabId: {}
} satisfies WorkspaceSessionState
}
return {
work,
get session() {
return state.session
},
store: {
...storeBase,
getWorkspaceSession: () => state.session,
setWorkspaceSession: (next: WorkspaceSessionState) => {
work.writes += 1
measuringWrite = true
try {
state.session = orderTerminalRowsByTabGroups(next)
} finally {
measuringWrite = false
}
}
}
}
}
@@ -2,19 +2,85 @@ export const DEFAULT_CLIENT_HOSTED_RECONCILIATION_WINDOW_MS = 45_000
/** A client with no paired-device identity, which no host attach can ever speak for. */
const ANONYMOUS_CLIENT = '\0anonymous'
const READ_REPLY = Symbol('read-reply')
type Observation = object | symbol
/** Restart snapshots precede host inventories; hold browser-row culling until each client's host reconciles.
* One client's attach proves nothing about another; bound never-attached clients by the deadline. */
export class ClientHostedPageReconciliationWindow {
private readonly reconciledClients = new Set<string>()
private readonly observations = new Map<string, Map<Observation, Set<string>>>()
constructor(
private readonly openedAt: number,
private readonly windowMs: number = DEFAULT_CLIENT_HOSTED_RECONCILIATION_WINDOW_MS
) {}
markReconciled(pairedDeviceId: string): void {
this.reconciledClients.add(clientKey(pairedDeviceId))
markReconciled(pairedDeviceId: string): ReadonlySet<string> | undefined {
const key = clientKey(pairedDeviceId)
this.reconciledClients.add(key)
const observations = this.observations.get(key)
this.observations.delete(key)
return observations && new Set([...observations.values()].flatMap((held) => [...held]))
}
forgetClient(pairedDeviceId: string): void {
this.observations.delete(clientKey(pairedDeviceId))
}
observe(
frames: readonly { worktree: string; clientHostedPagesUnreconciled?: true; removed?: true }[],
pairedDeviceId?: string,
observer: Observation = READ_REPLY
): void {
const key = clientKey(pairedDeviceId)
const observations = this.observations.get(key) ?? new Map<Observation, Set<string>>()
const held = observations.get(observer) ?? new Set<string>()
for (const frame of frames) {
if (frame.clientHostedPagesUnreconciled && !frame.removed) {
held.add(frame.worktree)
} else {
held.delete(frame.worktree)
}
}
if (held.size) {
observations.set(observer, held)
} else {
observations.delete(observer)
}
if (observations.size) {
this.observations.set(key, observations)
} else {
this.observations.delete(key)
}
}
forgetObservation(pairedDeviceId: string | undefined, observer: Observation): void {
const key = clientKey(pairedDeviceId)
const observations = this.observations.get(key)
observations?.delete(observer)
if (observations?.size === 0) {
this.observations.delete(key)
}
}
forgetWorktree(worktree: string): void {
for (const [key, observations] of this.observations) {
for (const [observer, held] of observations) {
held.delete(worktree)
if (!held.size) {
observations.delete(observer)
}
}
if (!observations.size) {
this.observations.delete(key)
}
}
}
dispose(): void {
this.observations.clear()
this.reconciledClients.clear()
}
isUnreconciled(pairedDeviceId: string | undefined, now: number): boolean {
@@ -24,7 +90,7 @@ export class ClientHostedPageReconciliationWindow {
}
/** Set and clear per recipient: shared fan-out frames must not inherit another client's hold. */
holdFor<T extends { clientHostedPagesUnreconciled?: true }>(
holdFor<T extends { worktree: string; clientHostedPagesUnreconciled?: true }>(
result: T,
pairedDeviceId: string | undefined,
now: number
@@ -0,0 +1,80 @@
import { OrcaRuntimeService } from '../../orca-runtime'
import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts'
import { createProfile } from './client-hosted-browser-persistence-test-harness'
import { RpcDispatcher } from '../../rpc/dispatcher'
import { BROWSER_CLIENT_HOST_METHODS } from '../../rpc/methods/browser/browser-client-host'
import { BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY } from '../../../../shared/browser/runtime/browser-runtime-capabilities'
class ReconciliationDeliveryRuntime extends OrcaRuntimeService {
projectedFrames = 0
sessionTabsSequence() {
return this.mobileSessionTabsChangeSequence
}
protected override projectMobileSessionTabsForClient(
result: RuntimeMobileSessionTabsResult,
clientId?: string
) {
this.projectedFrames += 1
return super.projectMobileSessionTabsForClient(result, clientId)
}
peekSnapshotForClient(worktree: string, clientId: string) {
return this.getMobileSessionTabsForWorktree(worktree, clientId, {
includeAgentSenders: false
})
}
snapshotForClient(worktree: string, clientId: string) {
const result = this.peekSnapshotForClient(worktree, clientId)
this.observeClientHostedPageSnapshots([result], clientId)
return result
}
override getRuntimeId(): string {
return 'runtime-a'
}
}
export function createReconciliationDeliveryRuntime() {
const profile = createProfile()
const hostRuntime = new ReconciliationDeliveryRuntime(profile.store, undefined, {})
const rpc = new RpcDispatcher({ runtime: hostRuntime, methods: BROWSER_CLIENT_HOST_METHODS })
const streams: { stopped: AbortController; completion: Promise<void> }[] = []
function attach() {
const stopped = new AbortController()
const completion = rpc.dispatchStreaming(
{
id: 'empty-adoption',
authToken: 'test',
method: 'browser.clientHost.attach',
params: {
authorityRuntimeId: 'runtime-a',
browserHostClientId: 'client-a',
hostCapabilities: ['webview'],
pageCommandProtocolVersion: 1,
pageReconciliationProtocolVersion: 1,
pageInventoryProtocolVersion: 1,
pageInventory: [],
leaseReconnectProtocolVersion: 1
}
},
() => {},
{
connectionId: 'empty-adoption',
pairedDeviceId: 'device-a',
clientKind: 'runtime',
clientCapabilities: [BROWSER_CLIENT_HOST_RUNTIME_CAPABILITY],
signal: stopped.signal
}
)
streams.push({ stopped, completion })
return { abort: () => stopped.abort(), completion }
}
return {
hostRuntime,
attach,
async close() {
for (const stream of streams) {
stream.stopped.abort()
}
await Promise.all(streams.map((stream) => stream.completion))
}
}
}
@@ -0,0 +1,113 @@
import { expect, it, vi } from 'vitest'
import { createReconciliationDeliveryRuntime } from './client-page-reconciliation-delivery-test-harness'
import { RpcDispatcher } from '../../rpc/dispatcher'
import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs'
import { openRecoveryTabsStream } from './client-page-recovery-stream-test-harness'
const WORKSPACE = 'repo-1::/tmp/worktree-a'
it.each(['session.tabs.subscribe', 'session.tabs.subscribeAll'])(
'forgets %s initial hold after the same stream receives an unheld frame',
async (method) => {
vi.useFakeTimers({ toFake: ['Date'] })
const h = createReconciliationDeliveryRuntime()
const runtime = h.hostRuntime
const stopped = new AbortController()
const replies: string[] = []
try {
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree: WORKSPACE,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
}
]
})
const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS })
const stream = rpc.dispatchStreaming(
{
id: 'held-stream',
authToken: 'test',
method,
params: method === 'session.tabs.subscribe' ? { worktree: `id:${WORKSPACE}` } : {}
},
(reply) => replies.push(reply),
{
connectionId: 'held-connection',
pairedDeviceId: 'device-a',
clientKind: 'mobile',
signal: stopped.signal
}
)
await vi.waitFor(() =>
expect(
replies.some((reply) =>
['snapshots', 'snapshot'].includes(JSON.parse(reply).result?.type)
)
).toBe(true)
)
expect(
replies.some((reply) =>
(JSON.parse(reply).result?.snapshots ?? [JSON.parse(reply).result]).some(
(frame: { worktree: string; clientHostedPagesUnreconciled?: true }) =>
frame.worktree === WORKSPACE && frame.clientHostedPagesUnreconciled
)
)
).toBe(true)
vi.setSystemTime(Date.now() + 46_000)
runtime.notifyMobileSessionTabsChanged(WORKSPACE)
expect(
replies.some(
(reply) =>
JSON.parse(reply).result?.type === 'updated' &&
JSON.parse(reply).result?.clientHostedPagesUnreconciled === undefined
)
).toBe(true)
runtime.projectedFrames = 0
const delivered = replies.length
runtime.markClientHostedPagesReconciled('device-a')
expect(runtime.projectedFrames).toBe(0)
expect(replies).toHaveLength(delivered)
stopped.abort()
await stream
} finally {
stopped.abort()
await h.close()
vi.useRealTimers()
}
}
)
it('delivers a cleared snapshot when authenticated empty adoption completes without another workspace change', async () => {
const h = createReconciliationDeliveryRuntime()
const stream = openRecoveryTabsStream(h.hostRuntime, 'empty-adoption-consumer')
try {
await stream.initial
expect(
stream.frames.findLast((frame) => frame.worktree === WORKSPACE)?.clientHostedPagesUnreconciled
).toBe(true)
const attached = h.attach()
await vi.waitFor(() =>
expect(
stream.frames.findLast((frame) => frame.worktree === WORKSPACE)
?.clientHostedPagesUnreconciled
).toBeUndefined()
)
expect(stream.errors).toEqual([])
attached.abort()
await attached.completion
} finally {
stream.stop()
await stream.completion
await h.close()
}
})
@@ -0,0 +1,177 @@
import { expect, it, vi } from 'vitest'
import { createReconciliationDeliveryRuntime } from './client-page-reconciliation-delivery-test-harness'
import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts'
vi.mock('../../../../shared/sidebar-inputs-switch', () => ({ ORCA_SIDEBAR_INPUTS_IS_MAIN: true }))
it.each([750, 7500])(
'only clears previously held frames in a %i-workspace runtime',
async (count) => {
const h = createReconciliationDeliveryRuntime()
const runtime = h.hostRuntime
const snapshots = Array.from({ length: count }, (_, index) => ({
worktree: `repo-1::/tmp/worktree-${index}`,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
}))
runtime.attachWindow(1)
runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: snapshots })
runtime.markClientHostedPagesReconciled('device-a')
const frames: RuntimeMobileSessionTabsResult[] = []
const otherFrames: RuntimeMobileSessionTabsResult[] = []
const unsubscribe = runtime.onMobileSessionTabsChanged(
(frame) => frames.push(frame),
'device-a',
'mobile'
)
const unsubscribeHeld = runtime.onMobileSessionTabsChanged(
(frame) => otherFrames.push(frame),
'device-b',
'mobile'
)
const facts = runtime.sidebarFacts
if (!facts) {
throw new Error('sidebar facts fixture is required')
}
const refresh = vi.spyOn(facts.workspaceActivityFacts, 'refreshWorkspace')
try {
runtime.projectedFrames = 0
const attached = h.attach()
expect(runtime.projectedFrames).toBe(0)
expect(frames).toEqual([])
expect(otherFrames).toEqual([])
expect(refresh).not.toHaveBeenCalled()
attached.abort()
await attached.completion
const heldWorktrees = [snapshots[0]!.worktree, snapshots[count - 1]!.worktree]
for (const worktree of heldWorktrees) {
expect(runtime.snapshotForClient(worktree, 'device-b').clientHostedPagesUnreconciled).toBe(
true
)
}
runtime.projectedFrames = 0
runtime.markClientHostedPagesReconciled('device-b')
expect(runtime.projectedFrames).toBe(2)
expect(otherFrames.map((frame) => frame.worktree)).toEqual(heldWorktrees)
expect(otherFrames.every((frame) => frame.clientHostedPagesUnreconciled === undefined)).toBe(
true
)
expect(frames).toEqual([])
expect(refresh).not.toHaveBeenCalled()
otherFrames.length = 0
runtime.projectedFrames = 0
runtime.markClientHostedPagesReconciled('device-b')
expect(runtime.projectedFrames).toBe(0)
expect(otherFrames).toEqual([])
expect(refresh).not.toHaveBeenCalled()
} finally {
refresh.mockRestore()
unsubscribe()
unsubscribeHeld()
await h.close()
}
}
)
it('does not owe delivery for speculative projections and forgets removed workspaces', async () => {
const h = createReconciliationDeliveryRuntime()
const runtime = h.hostRuntime
const worktree = 'repo-1::/tmp/worktree-observed'
const frames: RuntimeMobileSessionTabsResult[] = []
const unsubscribe = runtime.onMobileSessionTabsChanged(
(frame) => frames.push(frame),
'device-a',
'mobile'
)
const unsubscribeOther = runtime.onMobileSessionTabsChanged(
(frame) => frames.push(frame),
'device-b',
'mobile'
)
try {
expect(runtime.peekSnapshotForClient(worktree, 'device-a').clientHostedPagesUnreconciled).toBe(
true
)
runtime.markClientHostedPagesReconciled('device-a')
expect(frames).toEqual([])
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
}
]
})
expect(runtime.snapshotForClient(worktree, 'device-b').clientHostedPagesUnreconciled).toBe(true)
runtime.syncWindowGraph(1, { tabs: [], leaves: [], mobileSessionTabs: [] })
frames.length = 0
runtime.markClientHostedPagesReconciled('device-b')
expect(frames).toEqual([])
} finally {
unsubscribe()
unsubscribeOther()
await h.close()
}
})
it('keeps each subscription last held frame independently of later read replies', async () => {
const h = createReconciliationDeliveryRuntime()
const runtime = h.hostRuntime
const worktree = 'repo-1::/tmp/worktree-observed'
const frames: RuntimeMobileSessionTabsResult[] = []
const unsubscribe = runtime.onMobileSessionTabsChanged(
(frame) => frames.push(frame),
'device-a',
'mobile'
)
try {
runtime.attachWindow(1)
runtime.syncWindowGraph(1, {
tabs: [],
leaves: [],
mobileSessionTabs: [
{
worktree,
publicationEpoch: 'renderer',
snapshotVersion: 1,
activeGroupId: null,
activeTabId: null,
activeTabType: null,
tabs: []
}
]
})
// A subscription flush is a production delivery boundary.
runtime.onMobileSessionTabsChanged(() => {}, 'other-device', 'mobile')()
expect(frames.some((frame) => frame.clientHostedPagesUnreconciled === true)).toBe(true)
frames.length = 0
const now = Date.now()
vi.spyOn(Date, 'now').mockReturnValue(now + 45_001)
expect(
runtime.snapshotForClient(worktree, 'device-a').clientHostedPagesUnreconciled
).toBeUndefined()
runtime.markClientHostedPagesReconciled('device-a')
expect(frames.map((frame) => [frame.worktree, frame.clientHostedPagesUnreconciled])).toEqual([
[worktree, undefined]
])
frames.length = 0
runtime.markClientHostedPagesReconciled('device-a')
expect(frames).toEqual([])
} finally {
vi.restoreAllMocks()
unsubscribe()
await h.close()
}
})
@@ -0,0 +1,198 @@
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('keeps an independent held read after stream progression, then forgets disposed streams and removed workspaces', async () => {
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', `id:${WORKSPACE}`)
const independent = openRecoveryTabsStream(runtime, 'independent-stream')
try {
await Promise.all([stream.initial, independent.initial])
expect(runtime.snapshotForClient(WORKSPACE, 'device-a').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()
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()
}
}
)
@@ -0,0 +1,48 @@
import type { RuntimeMobileSessionTabsResult } from '../../../../shared/runtime-session-contracts'
import type { OrcaRuntimeService } from '../../orca-runtime'
import { RpcDispatcher } from '../../rpc/dispatcher'
import { SESSION_TAB_METHODS } from '../../rpc/methods/session-tabs/session-tabs'
export function openRecoveryTabsStream(
runtime: OrcaRuntimeService,
id: string,
worktree?: string,
deviceId = 'device-a'
) {
const stopped = new AbortController()
const frames: RuntimeMobileSessionTabsResult[] = []
const errors: unknown[] = []
const initial = Promise.withResolvers<void>()
const rpc = new RpcDispatcher({ runtime, methods: SESSION_TAB_METHODS })
const completion = rpc.dispatchStreaming(
{
id,
authToken: 'test',
method: worktree ? 'session.tabs.subscribe' : 'session.tabs.subscribeAll',
params: worktree ? { worktree } : {}
},
(reply) => {
const message: {
ok?: boolean
error?: unknown
result?:
| { type: 'snapshots'; snapshots: RuntimeMobileSessionTabsResult[] }
| ({ type: 'snapshot' | 'updated' } & RuntimeMobileSessionTabsResult)
} = JSON.parse(reply)
if (message.ok === false) {
errors.push(message.error)
initial.reject(new Error('session-stream-failed'))
}
const result = message.result
if (result?.type === 'snapshots') {
frames.push(...result.snapshots)
initial.resolve()
} else if (result?.type === 'snapshot' || result?.type === 'updated') {
frames.push(result)
initial.resolve()
}
},
{ connectionId: id, pairedDeviceId: deviceId, clientKind: 'mobile', signal: stopped.signal }
)
return { frames, errors, initial: initial.promise, completion, stop: () => stopped.abort() }
}
@@ -221,6 +221,7 @@ export abstract class OrcaRuntimeWithRuntimeId extends RuntimeConstructionServic
listener: (snapshot: RuntimeMobileSessionTabsResult, changeSequence: number) => void
clientNavigationId?: string
clientKind?: 'mobile' | 'runtime'
observation?: 'caller'
}>()
protected pendingMobileSessionTabsChangeSequenceByWorktree = new Map<string, number>()
@@ -0,0 +1,24 @@
import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/runtime-session-contracts'
import { projectSessionTabAgentStatus } from './session-tab-agent-status-projection'
import { projectSessionTabBrowserPlacements } from './session-tab-browser-placement-projection'
import { projectSessionTabFileHosts } from './session-tab-file-host-projection'
export function projectSessionTabsForClient(
snapshot: RuntimeMobileSessionTabsResult,
clientKind: 'mobile' | 'runtime' | undefined,
clientCapabilities: Parameters<typeof projectSessionTabAgentStatus>[2]
): RuntimeMobileSessionTabsResult {
// Phones draw no agent message cards, so they never pay for sender identity.
const { agentSenderAssociations: _desktopOnly, ...phone } = snapshot
return projectSessionTabBrowserPlacements(
projectSessionTabFileHosts(
projectSessionTabAgentStatus(
clientKind === 'mobile' ? phone : snapshot,
clientKind,
clientCapabilities
),
clientKind
),
clientCapabilities
)
}
@@ -118,8 +118,19 @@ function deferredPtyInventory(): {
}
}
class CensusRuntime extends OrcaRuntimeService {
projectedFrames = 0
protected override projectMobileSessionTabsForClient(
snapshot: RuntimeMobileSessionTabsResult,
clientId?: string
) {
this.projectedFrames += 1
return super.projectMobileSessionTabsForClient(snapshot, clientId)
}
}
function createRuntimeHarness(initialSnapshots: RuntimeMobileSessionTabsSnapshot[] = []) {
const runtime = new OrcaRuntimeService()
const runtime = new CensusRuntime()
runtime.syncWindowGraph(0, { tabs: [], leaves: [], mobileSessionTabs: initialSnapshots })
const census = deferredPtyInventory()
const internals = runtime as unknown as RuntimeInventoryInternals
@@ -648,3 +659,45 @@ describe('session tabs inventory census boundary', () => {
expect(emit).not.toHaveBeenCalled()
})
})
it.each(['subsumed', 'invalidated', 'aborted'] as const)(
'does not owe completion for %s held census candidates never emitted',
async (caseName) => {
vi.useFakeTimers({ toFake: ['Date'] })
const h = createRuntimeHarness()
try {
const created = runtimeSnapshot('wt-census-race', 1)
h.publish([created])
if (caseName === 'invalidated') {
for (let index = 0; index < 300; index += 1) {
h.publish(index % 2 ? [created] : [])
}
}
if (caseName === 'aborted') {
h.runtime.cleanupSubscription(
'session.tabs:conn-runtime-census-race:*:req-runtime-census-race'
)
}
vi.setSystemTime(Date.now() + 46_000)
h.census.resolve(completePtyInventory())
if (caseName === 'aborted') {
await expect(h.pending).rejects.toThrow('client_disconnected')
expect(h.emit).not.toHaveBeenCalled()
} else {
await h.pending
expect(h.emit.mock.calls).toHaveLength(1)
expect(h.emit.mock.calls[0]?.[0]).toMatchObject({ type: 'snapshots' })
}
h.runtime.projectedFrames = 0
const outputs = h.emit.mock.calls.length
h.runtime.markClientHostedPagesReconciled('paired-runtime-census-race')
expect(h.runtime.projectedFrames).toBe(0)
expect(h.emit.mock.calls).toHaveLength(outputs)
} finally {
h.runtime.cleanupSubscription(
'session.tabs:conn-runtime-census-race:*:req-runtime-census-race'
)
vi.useRealTimers()
}
}
)
@@ -1,3 +1,5 @@
import { SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY } from '../../../../../shared/session-tabs-runtime-capabilities'
import { projectSessionTabsForClient } from './session-tabs-client-projection'
import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/runtime-session-contracts'
import type { RpcContext } from '../../core'
@@ -34,3 +36,34 @@ export async function collectSessionTabsInventory(
changeSequence: collected.changeSequence
}
}
export function clientUnderstandsAuthoritativeInventory(context: RpcContext): boolean {
return (
context.clientCapabilities?.includes(
SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY
) === true
)
}
function projectInventory(
inventory: SessionTabsInventory,
context: RpcContext
): SessionTabsInventory {
return {
snapshots: inventory.snapshots.map((snapshot) =>
projectSessionTabsForClient(snapshot, context.clientKind, context.clientCapabilities)
),
...(inventory.authoritative && clientUnderstandsAuthoritativeInventory(context)
? { authoritative: true as const }
: {})
}
}
export async function listSessionTabsInventory(context: RpcContext): Promise<SessionTabsInventory> {
const result = projectInventory((await collectSessionTabsInventory(context)).inventory, context)
if (context.signal?.aborted) {
throw new Error('client_disconnected')
}
context.runtime.observeClientHostedPageSnapshots?.(result.snapshots, context.pairedDeviceId)
return result
}
@@ -1,15 +1,14 @@
import { projectSessionTabsForClient } from './session-tabs-client-projection'
export { projectSessionTabsForClient } from './session-tabs-client-projection'
import {
collectSessionTabsInventory,
type SessionTabsInventory
clientUnderstandsAuthoritativeInventory
} from './session-tabs-inventory-collection'
export { listSessionTabsInventory } from './session-tabs-inventory-collection'
import { isDeepStrictEqual } from 'node:util'
import '../../../../../shared/protocol-version'
import { SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY } from '../../../../../shared/session-tabs-runtime-capabilities'
import type { RuntimeMobileSessionTabsResult } from '../../../../../shared/runtime-session-contracts'
import type { RpcContext } from '../../core'
import { projectSessionTabAgentStatus } from './session-tab-agent-status-projection'
import { projectSessionTabBrowserPlacements } from './session-tab-browser-placement-projection'
import { projectSessionTabFileHosts } from './session-tab-file-host-projection'
import { createSessionTabsStreamDelta } from './session-tabs-sender-delta'
import { prepareStructuredTabsIfSupported } from './structured-session-tab-restore'
import { createSessionTabsTabDeltaEncoder } from '../../../../../shared/session-tabs-tab-delta'
@@ -19,52 +18,6 @@ type SessionTabsChange = RuntimeMobileSessionTabsResult & { removed?: true }
const MAX_BUFFERED_CENSUS_CHANGES = 256
const MAX_CENSUS_COLLECTION_ATTEMPTS = 3
function clientUnderstandsAuthoritativeInventory(context: RpcContext): boolean {
return (
context.clientCapabilities?.includes(
SESSION_TABS_AUTHORITATIVE_INVENTORY_RUNTIME_CAPABILITY
) === true
)
}
export function projectSessionTabsForClient(
snapshot: RuntimeMobileSessionTabsResult,
clientKind: 'mobile' | 'runtime' | undefined,
clientCapabilities: Parameters<typeof projectSessionTabAgentStatus>[2]
): RuntimeMobileSessionTabsResult {
// Phones draw no agent message cards, so they never pay for sender identity.
const { agentSenderAssociations: _desktopOnly, ...phone } = snapshot
return projectSessionTabBrowserPlacements(
projectSessionTabFileHosts(
projectSessionTabAgentStatus(
clientKind === 'mobile' ? phone : snapshot,
clientKind,
clientCapabilities
),
clientKind
),
clientCapabilities
)
}
function projectInventory(
inventory: SessionTabsInventory,
context: RpcContext
): SessionTabsInventory {
return {
snapshots: inventory.snapshots.map((snapshot) =>
projectSessionTabsForClient(snapshot, context.clientKind, context.clientCapabilities)
),
...(inventory.authoritative && clientUnderstandsAuthoritativeInventory(context)
? { authoritative: true as const }
: {})
}
}
export async function listSessionTabsInventory(context: RpcContext): Promise<SessionTabsInventory> {
return projectInventory((await collectSessionTabsInventory(context)).inventory, context)
}
export async function subscribeSessionTabsInventory(
context: RpcContext,
emit: (result: unknown) => void
@@ -75,6 +28,7 @@ export async function subscribeSessionTabsInventory(
}
const cleanupPrefix = `session.tabs:${connectionId ?? 'local'}:*`
const subscriptionId = requestId ? `${cleanupPrefix}:${requestId}` : cleanupPrefix
const observation = {}
const inventoryController = new AbortController()
// For the stream's whole life, not just the census: a desktop unsubscribe arrives as this abort.
const onTransportAbort = (): void => runtime.cleanupSubscription(subscriptionId)
@@ -163,6 +117,21 @@ export async function subscribeSessionTabsInventory(
changeSequence
})
}
const emitChange = (projected: SessionTabsChange): void => {
if (closed) {
return
}
emit({ type: 'updated', ...tabDelta.update(withProofDelta(projected)) })
if (!closed) {
runtime.observeClientHostedPageSnapshots?.(
[
projected.removed ? { ...projected, clientHostedPagesUnreconciled: undefined } : projected
],
pairedDeviceId,
observation
)
}
}
const publishChange = (snapshot: SessionTabsChange, changeSequence: number): void => {
const { navigationIntent: _intent, ...canonical } = snapshot
if (snapshot.removed) {
@@ -177,10 +146,10 @@ export async function subscribeSessionTabsInventory(
deliveredChangeSequenceByWorktree.set(snapshot.worktree, changeSequence)
return
}
emit({
type: 'updated',
...tabDelta.update(withProofDelta(projected))
})
emitChange(projected)
if (closed) {
return
}
if (projected.removed === true) {
publishedSnapshotsByWorktree.delete(snapshot.worktree)
deliveredChangeSequenceByWorktree.delete(snapshot.worktree)
@@ -191,6 +160,9 @@ export async function subscribeSessionTabsInventory(
}
const unsubscribe = runtime.onMobileSessionTabsChanged(
(runtimeSnapshot, changeSequence) => {
if (closed) {
return
}
const snapshot = runtimeSnapshot as SessionTabsChange
if (!initialized) {
bufferChange(snapshot, changeSequence)
@@ -205,7 +177,8 @@ export async function subscribeSessionTabsInventory(
publishChange(snapshot, changeSequence)
},
pairedDeviceId,
context.clientKind
context.clientKind,
{ observation: 'caller' }
)
const stopCapabilities = context.capabilitySource?.observe(() => {
if (!initialized || closed) {
@@ -216,17 +189,24 @@ export async function subscribeSessionTabsInventory(
if (isDeepStrictEqual(publishedSnapshotsByWorktree.get(snapshot.worktree), projected)) {
continue
}
emit({ type: 'updated', ...tabDelta.update(withProofDelta(projected)) })
emitChange(projected)
if (closed) {
return
}
publishedSnapshotsByWorktree.set(snapshot.worktree, projected)
}
})
runtime.registerSubscriptionCleanup(
subscriptionId,
() => {
if (closed) {
return
}
closed = true
context.signal?.removeEventListener('abort', onTransportAbort)
inventoryController.abort()
unsubscribe()
runtime.forgetClientHostedPageObservation?.(pairedDeviceId, observation)
stopCapabilities?.()
canonicalSnapshotsByWorktree.clear()
clearBufferedChanges()
@@ -278,15 +258,18 @@ export async function subscribeSessionTabsInventory(
}
const { inventory, changeSequence } = collected
censusChangeSequence = changeSequence
const projectedSnapshots = inventory.snapshots.map(projectChange)
emit({
type: 'snapshots',
...(inventory.authoritative && clientUnderstandsAuthoritativeInventory(context)
? { authoritative: true as const }
: {}),
snapshots: inventory.snapshots.map((snapshot) =>
tabDelta.full(withProofDelta(projectChange(snapshot)))
)
snapshots: projectedSnapshots.map((snapshot) => tabDelta.full(withProofDelta(snapshot)))
})
if (closed) {
return
}
runtime.observeClientHostedPageSnapshots?.(projectedSnapshots, pairedDeviceId, observation)
for (const snapshot of inventory.snapshots) {
const canonical = withoutNavigationIntent(snapshot)
canonicalSnapshotsByWorktree.set(snapshot.worktree, canonical)
@@ -61,8 +61,11 @@ describe.each(['session.tabs.subscribe', 'session.tabs.subscribeAll'] as const)(
}
]
}
const observedFrames: RuntimeMobileSessionTabsResult[][] = []
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: these real RPC handlers reach only the runtime members stubbed here.
const runtime = {
observeClientHostedPageSnapshots: (frames: RuntimeMobileSessionTabsResult[]) =>
observedFrames.push(frames),
getRuntimeId: () => 'runtime',
getClientSettings: () => ({}),
listMobileSessionTabs: async () => initial,
@@ -145,9 +148,15 @@ describe.each(['session.tabs.subscribe', 'session.tabs.subscribeAll'] as const)(
// A capability the projection ignores sends no frame; the next real change still decodes.
await update([...source.current, 'unrelated.test.v1'])
expect(messages).toHaveLength(1)
expect(observedFrames).toHaveLength(2)
await update(structured)
expect(siblingMessages).toHaveLength(1)
expect(messages).toHaveLength(2)
expect(observedFrames).toHaveLength(3)
expect(observedFrames.at(-1)?.[0]?.tabs[0]).toMatchObject({
type: 'agent-session',
title: 'Claude chat'
})
const recovered = decode(messages[1]!)
expect(JSON.stringify(recovered)).toContain('Claude chat')
const proofState = { retiredTerminalSurfaces: delta ? [] : initial.retiredTerminalSurfaces }
@@ -36,7 +36,7 @@ export const SESSION_TAB_METHODS = [
params: WorktreeTabSelector,
handler: async (params, { runtime, pairedDeviceId, clientKind, clientCapabilities }) => {
await prepareStructuredTabsIfSupported({ runtime, clientKind, clientCapabilities })
return projectSessionTabsForClient(
const result = projectSessionTabsForClient(
await runtime.listMobileSessionTabs(params.worktree, pairedDeviceId, {
includeInitialSurfaceLaunch: true,
includeAgentSenders: clientKind !== 'mobile'
@@ -44,6 +44,8 @@ export const SESSION_TAB_METHODS = [
clientKind,
clientCapabilities
)
runtime.observeClientHostedPageSnapshots?.([result], pairedDeviceId)
return result
}
}),
defineMethod({
@@ -129,6 +131,7 @@ export const SESSION_TAB_METHODS = [
},
emit
) => {
const observation = {}
let subscriptionId: string | null = null
let released = false
let endOnRelease = true
@@ -164,6 +167,7 @@ export const SESSION_TAB_METHODS = [
closePhoneSession?.()
signal?.removeEventListener('abort', release)
stopListening()
runtime.forgetClientHostedPageObservation?.(pairedDeviceId, observation)
stopCapabilities()
if (endOnRelease) {
emit({ type: 'end' })
@@ -184,13 +188,30 @@ export const SESSION_TAB_METHODS = [
snapshot: NonNullable<typeof currentSnapshot>,
capabilities = capabilitySource?.current ?? clientCapabilities
) => projectSessionTabsForClient(snapshot, clientKind, capabilities)
const emitSnapshot = (
projected: NonNullable<typeof currentSnapshot>,
type: 'snapshot' | 'updated'
): void => {
if (released) {
return
}
emit({
type,
...(type === 'snapshot'
? tabDelta.full(withProofDelta(projected))
: tabDelta.update(withProofDelta(projected)))
})
if (!released) {
runtime.observeClientHostedPageSnapshots?.([projected], pairedDeviceId, observation)
}
}
stopCapabilities =
capabilitySource?.observe((previous) => {
if (!released && currentSnapshot) {
const projected = project(currentSnapshot)
// The last frame was projected with the previous set; a change it ignores sends nothing.
if (!isDeepStrictEqual(projected, project(currentSnapshot, previous))) {
emit({ type: 'updated', ...tabDelta.update(withProofDelta(projected)) })
emitSnapshot(projected, 'updated')
}
}
}) ?? (() => {})
@@ -223,15 +244,15 @@ export const SESSION_TAB_METHODS = [
}
let subscribedWorktree = initial.worktree
currentSnapshot = initial
emit({
type: 'snapshot',
...tabDelta.full(withProofDelta(project(initial)))
})
emitSnapshot(project(initial), 'snapshot')
if (released) {
return
}
stopListening = runtime.onMobileSessionTabsChanged(
(snapshot) => {
if (released) {
return
}
if (
snapshot.worktree !== subscribedWorktree &&
worktreeIdsEqual(snapshot.worktree, subscribedWorktree)
@@ -254,14 +275,12 @@ export const SESSION_TAB_METHODS = [
: { ...snapshot, worktree: initial.worktree }
const { navigationIntent: _intent, ...retained } = streamSnapshot
currentSnapshot = retained
emit({
type: 'updated',
...tabDelta.update(withProofDelta(project(streamSnapshot)))
})
emitSnapshot(project(streamSnapshot), 'updated')
}
},
pairedDeviceId,
clientKind
clientKind,
{ observation: 'caller' }
)
} catch (error) {
// A stream already ended by its release must not also report an error.
@@ -238,6 +238,19 @@ export abstract class OrcaRuntimeWithTransitionGraphReloadToTerminalState extend
/** Reconcile client-hosted pages per paired device; one attached client cannot account for another's pages. */
markClientHostedPagesReconciled(pairedDeviceId: string): void {
this.clientHostedPageReconciliation.markReconciled(pairedDeviceId)
const held = this.clientHostedPageReconciliation.markReconciled(pairedDeviceId)
if (!held?.size || this.mobileSessionTabListeners.size === 0) {
return
}
const deliver = this.createMobileSessionTabsDelivery()
for (const worktree of held) {
deliver(
this.getMobileSessionTabsForWorktree(worktree, pairedDeviceId, {
includeAgentSenders: false
}),
++this.mobileSessionTabsChangeSequence,
pairedDeviceId
)
}
}
}
@@ -214,6 +214,7 @@ export abstract class OrcaRuntimeWithStoredMobileSnapshotHasStalePreservedTab ex
changeSequence
)
}
this.clientHostedPageReconciliation.forgetWorktree(worktreeId)
this.clientSessionTabSelections.forgetWorktree(worktreeId)
}
@@ -4,16 +4,23 @@ export abstract class RuntimeMobileSessionTabSubscriptions extends RuntimeWorksp
onMobileSessionTabsChanged(
listener: (snapshot: RuntimeMobileSessionTabsResult, changeSequence: number) => void,
clientNavigationId?: string,
clientKind?: 'mobile' | 'runtime'
clientKind?: 'mobile' | 'runtime',
options?: { observation: 'caller' }
): () => void {
// Drain coalesced notifications before subscribing: the initial snapshot already includes them.
this.mobileSessionTabsNotifyCoalescer.flushAll()
const subscription = { listener, clientNavigationId, clientKind }
const subscription = {
listener,
clientNavigationId,
clientKind,
observation: options?.observation
}
this.mobileSessionTabListeners.add(subscription)
return () => {
// Flush before removal so this listener receives the latest settled state.
this.mobileSessionTabsNotifyCoalescer.flushAll()
const removed = this.mobileSessionTabListeners.delete(subscription)
this.clientHostedPageReconciliation.forgetObservation(clientNavigationId, subscription)
if (removed && clientKind !== 'mobile') {
this.releaseAgentSenderHistoryIfUnobserved()
}
@@ -23,6 +30,44 @@ export abstract class RuntimeMobileSessionTabSubscriptions extends RuntimeWorksp
}
}
protected deliverMobileSessionTabsFrame(
subscription: {
listener(frame: RuntimeMobileSessionTabsResult, sequence: number): void
clientNavigationId?: string
observation?: 'caller'
},
frame: RuntimeMobileSessionTabsResult,
sequence: number
): void {
subscription.listener(frame, sequence)
if (
subscription.observation === 'caller' ||
!this.mobileSessionTabListeners.has(subscription)
) {
return
}
this.clientHostedPageReconciliation.observe(
[frame],
subscription.clientNavigationId,
subscription
)
}
observeClientHostedPageSnapshots(
frames: readonly RuntimeMobileSessionTabsResult[],
clientNavigationId?: string,
observer?: object
): void {
this.clientHostedPageReconciliation.observe(frames, clientNavigationId, observer)
}
forgetClientHostedPageObservation(
clientNavigationId: string | undefined,
observer: object
): void {
this.clientHostedPageReconciliation.forgetObservation(clientNavigationId, observer)
}
protected hasAgentSenderListeners(): boolean {
for (const { clientKind } of this.mobileSessionTabListeners) {
if (clientKind !== 'mobile') {
@@ -40,5 +85,6 @@ export abstract class RuntimeMobileSessionTabSubscriptions extends RuntimeWorksp
forgetClientNavigationState(clientNavigationId: string): void {
this.clientSessionTabSelections.forgetClient(clientNavigationId)
this.clientHostedPageReconciliation.forgetClient(clientNavigationId)
}
}
@@ -94,7 +94,8 @@ export abstract class OrcaRuntimeWithScheduleMobileSessionTabsChanged extends Or
}
frame = desktopFrame
}
subscription.listener(project(frame, subscription.clientNavigationId), changeSequence)
const supplied = project(frame, subscription.clientNavigationId)
this.deliverMobileSessionTabsFrame(subscription, supplied, changeSequence)
}
if (clientNavigationId === undefined && desktopFrame?.agentSenderAssociations) {
this.agentProjections.senders.acknowledgeFrame(