mirror of
https://github.com/stablyai/orca.git
synced 2026-11-15 18:37:24 +00:00
Apply remote page observations without preempting pending outcomes
This commit is contained in:
+2
-2
@@ -94,7 +94,7 @@ export async function runRemoteBrowserNavigationCommand(
|
||||
setPaneBusy(true)
|
||||
setPaneNotice(null)
|
||||
// A standing failure stays visible until the native outcome is observed.
|
||||
onUpdatePageState(browserTab.id, { loading: true })
|
||||
lifecycle.session.setPageLoading(operationToken, true, onUpdatePageState)
|
||||
try {
|
||||
pageId = await lifecycle.session.resolveNavigationPage(operationToken)
|
||||
if (!pageId || !ownsAction()) {
|
||||
@@ -159,7 +159,7 @@ export async function runRemoteBrowserNavigationCommand(
|
||||
reportFailure(error)
|
||||
} finally {
|
||||
if (ownsAction()) {
|
||||
onUpdatePageState(browserTab.id, { loading: false })
|
||||
lifecycle.session.setPageLoading(operationToken, false, onUpdatePageState)
|
||||
setPaneBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
+58
-8
@@ -38,6 +38,10 @@ export type RemoteBrowserPageSessionDeps = {
|
||||
export class RemoteBrowserPageSession {
|
||||
private tabRefreshTimer: ReturnType<typeof setTimeout> | null = null
|
||||
private observationGeneration = 0
|
||||
private nextObservationId = 0
|
||||
private appliedObservationId = 0
|
||||
private observationAnchor: readonly unknown[] | null = null
|
||||
private loadingGeneration: number | null = null
|
||||
|
||||
constructor(private readonly deps: RemoteBrowserPageSessionDeps) {}
|
||||
|
||||
@@ -46,22 +50,64 @@ export class RemoteBrowserPageSession {
|
||||
this.cancelTabInfoRefresh()
|
||||
}
|
||||
|
||||
private observeExternalChanges(): void {
|
||||
const current = this.deps.readCurrentObservation()
|
||||
if (
|
||||
this.observationAnchor &&
|
||||
(this.observationAnchor.length !== current.length ||
|
||||
this.observationAnchor.some((value, index) => value !== current[index]))
|
||||
) {
|
||||
this.observationGeneration += 1
|
||||
this.loadingGeneration = null
|
||||
}
|
||||
this.observationAnchor = current
|
||||
}
|
||||
|
||||
private applyObservedWrite(write: () => void): void {
|
||||
try {
|
||||
write()
|
||||
} finally {
|
||||
this.observationAnchor = this.deps.readCurrentObservation()
|
||||
}
|
||||
}
|
||||
|
||||
setPageLoading(
|
||||
token: RemoteBrowserOperationToken,
|
||||
loading: boolean,
|
||||
update: (pageId: string, state: { loading: boolean }) => void
|
||||
): void {
|
||||
if (!this.deps.tokens.isCurrent(token)) {
|
||||
return
|
||||
}
|
||||
this.observeExternalChanges()
|
||||
if (!loading && this.loadingGeneration !== this.observationGeneration) {
|
||||
return
|
||||
}
|
||||
this.applyObservedWrite(() => update(token.tabId, { loading }))
|
||||
this.loadingGeneration = loading ? this.observationGeneration : null
|
||||
}
|
||||
|
||||
captureTabInfoAdmission(token: RemoteBrowserOperationToken): {
|
||||
isCurrent: () => boolean
|
||||
apply: (tab: BrowserTabInfo, onApplied?: (tab: BrowserTabInfo) => void) => boolean
|
||||
} {
|
||||
const generation = ++this.observationGeneration
|
||||
const observed = this.deps.tokens.isCurrent(token) ? this.deps.readCurrentObservation() : null
|
||||
const id = ++this.nextObservationId
|
||||
const active = this.deps.tokens.isCurrent(token)
|
||||
if (active) {
|
||||
this.observeExternalChanges()
|
||||
}
|
||||
const generation = this.observationGeneration
|
||||
const isCurrent = (): boolean => {
|
||||
if (
|
||||
generation !== this.observationGeneration ||
|
||||
!observed ||
|
||||
!active ||
|
||||
id < this.appliedObservationId ||
|
||||
!this.deps.tokens.isCurrent(token)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
const current = this.deps.readCurrentObservation()
|
||||
return observed.every((value, index) => value === current[index])
|
||||
this.observeExternalChanges()
|
||||
return generation === this.observationGeneration
|
||||
}
|
||||
return {
|
||||
isCurrent,
|
||||
@@ -69,8 +115,12 @@ export class RemoteBrowserPageSession {
|
||||
if (!isCurrent()) {
|
||||
return false
|
||||
}
|
||||
this.deps.applyTabInfo(tab)
|
||||
onApplied?.(tab)
|
||||
this.applyObservedWrite(() => {
|
||||
this.deps.applyTabInfo(tab)
|
||||
this.appliedObservationId = id
|
||||
this.loadingGeneration = null
|
||||
onApplied?.(tab)
|
||||
})
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -92,7 +142,7 @@ export class RemoteBrowserPageSession {
|
||||
return null
|
||||
}
|
||||
if (callbacks.onError) {
|
||||
callbacks.onError(error)
|
||||
this.applyObservedWrite(() => callbacks.onError?.(error))
|
||||
return null
|
||||
}
|
||||
throw error
|
||||
|
||||
+175
-12
@@ -12,9 +12,8 @@ import {
|
||||
readRemoteBrowserPage,
|
||||
readRemoteBrowserPageObservation
|
||||
} from './remote-browser-page-observation'
|
||||
import { RemoteBrowserPageSession } from './remote-browser-page-session'
|
||||
import { RemoteBrowserOperationTokens } from './remote-browser-stream-tokens'
|
||||
import type { RemoteBrowserStreamLifecycle } from './remote-browser-stream-lifecycle'
|
||||
import { RemoteBrowserStreamLifecycle } from './remote-browser-stream-lifecycle'
|
||||
import type { RemoteBrowserScreencastSubscribe } from './remote-browser-screencast-subscription'
|
||||
|
||||
vi.mock('@/runtime/rpc/calls/runtime-rpc-call', () => ({ callRuntimeRpc: vi.fn() }))
|
||||
|
||||
@@ -94,18 +93,26 @@ function renderNavigation(count = 1) {
|
||||
}
|
||||
})
|
||||
const identity = { mounted: true, active: true, environmentId: 'environment-a' }
|
||||
const tokens = new RemoteBrowserOperationTokens({
|
||||
const paneIdentity = {
|
||||
isMounted: () => identity.mounted,
|
||||
isActive: () => identity.active,
|
||||
getTabId: () => 'page-a',
|
||||
getEnvironmentId: () => identity.environmentId,
|
||||
browserPageExists: (pageId) =>
|
||||
Boolean(readRemoteBrowserPage(useAppStore.getState(), 'workspace-a', pageId))
|
||||
})
|
||||
tokens.setRemotePage('remote-page-a')
|
||||
}
|
||||
let project: (tab: BrowserTabInfo) => void = () => {}
|
||||
const session = new RemoteBrowserPageSession({
|
||||
tokens,
|
||||
const subscribe = vi.fn<RemoteBrowserScreencastSubscribe>(async () => ({ unsubscribe: vi.fn() }))
|
||||
const lifecycle = new RemoteBrowserStreamLifecycle({
|
||||
identity: paneIdentity,
|
||||
subscribeScreencast: subscribe,
|
||||
waitForViewportSize: async () => ({ width: 800, height: 600 }),
|
||||
readViewportSize: () => ({ width: 800, height: 600 }),
|
||||
syncViewport: async () => {},
|
||||
getDeviceScaleFactor: () => 1,
|
||||
setStatus: vi.fn(),
|
||||
clearFrame: vi.fn(),
|
||||
handleFrameBytes: vi.fn(),
|
||||
callRpc: callRuntimeRpc,
|
||||
getWorktreeSelector: () => 'worktree-a',
|
||||
getCurrentUrl: () => currentPage().url,
|
||||
@@ -117,6 +124,8 @@ function renderNavigation(count = 1) {
|
||||
applyTabInfo: (tab) => project(tab),
|
||||
closeMissingRemotePage: vi.fn()
|
||||
})
|
||||
const { session, tokens } = lifecycle
|
||||
tokens.setRemotePage('remote-page-a')
|
||||
const closeMissing = vi.fn()
|
||||
const busy = vi.fn()
|
||||
const notice = vi.fn()
|
||||
@@ -126,8 +135,7 @@ function renderNavigation(count = 1) {
|
||||
stagedPage: false,
|
||||
addressBarValue: 'about:blank',
|
||||
setAddressBarValueFromPage: vi.fn(),
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: this hook reads only the real session; stream transport is outside this fixture.
|
||||
lifecycle: { session } as unknown as RemoteBrowserStreamLifecycle,
|
||||
lifecycle,
|
||||
runtimeWorktree: 'worktree-a',
|
||||
runtimeTarget: () => ({ kind: 'environment', environmentId: identity.environmentId }),
|
||||
createRemoteOperationToken: () => tokens.createOperationToken(),
|
||||
@@ -140,7 +148,7 @@ function renderNavigation(count = 1) {
|
||||
})
|
||||
)
|
||||
project = (tab) => hook.result.current.applyRemoteTabInfo(tab)
|
||||
return { ...hook, session, tokens, identity, busy, notice, closeMissing }
|
||||
return { ...hook, lifecycle, subscribe, session, tokens, identity, busy, notice, closeMissing }
|
||||
}
|
||||
|
||||
function currentPage(): BrowserPage {
|
||||
@@ -162,7 +170,10 @@ function expectPending(challengeId = 'challenge-x') {
|
||||
}
|
||||
|
||||
beforeEach(() => vi.mocked(callRuntimeRpc).mockReset())
|
||||
afterEach(cleanup)
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
describe('remote browser authoritative page state', () => {
|
||||
it('projects a pending host challenge through local actions and clears an old full snapshot without fields', () => {
|
||||
@@ -268,6 +279,158 @@ describe('remote browser authoritative page state', () => {
|
||||
expect(notice).not.toHaveBeenCalledWith(expect.objectContaining({ kind: 'consequence' }))
|
||||
})
|
||||
|
||||
it.each(['older-first', 'newer-first', 'newer-fails'] as const)(
|
||||
'retains current outcomes across command cleanup with %s settlement',
|
||||
async (order) => {
|
||||
const { result, session, tokens } = renderNavigation()
|
||||
act(() => result.current.applyRemoteTabInfo(failedTab()))
|
||||
const older = deferred<{ tab: BrowserTabInfo }>()
|
||||
const newer = deferred<{ tab: BrowserTabInfo }>()
|
||||
vi.mocked(callRuntimeRpc)
|
||||
.mockResolvedValueOnce({ url: 'https://selfsigned.test/', title: 'Reload' })
|
||||
.mockReturnValueOnce(older.promise)
|
||||
.mockReturnValueOnce(newer.promise)
|
||||
let command!: Promise<void>
|
||||
await act(async () => {
|
||||
command = result.current.runRemoteNavigation('browser.reload')
|
||||
})
|
||||
const refresh = session.refreshTabInfo(tokens.createOperationToken('remote-page-a')!)
|
||||
if (order === 'newer-fails') {
|
||||
await act(async () => {
|
||||
newer.reject(new Error('input read unavailable'))
|
||||
await expect(refresh).rejects.toThrow('input read unavailable')
|
||||
})
|
||||
} else if (order === 'newer-first') {
|
||||
await act(async () => {
|
||||
newer.resolve({ tab: { ...failedTab('challenge-z'), title: 'Current input' } })
|
||||
await refresh
|
||||
})
|
||||
}
|
||||
await act(async () => {
|
||||
older.resolve({ tab: { ...failedTab('challenge-y'), title: 'Reload outcome' } })
|
||||
await command
|
||||
})
|
||||
if (order === 'older-first') {
|
||||
await act(async () => {
|
||||
newer.resolve({ tab: { ...failedTab('challenge-z'), title: 'Current input' } })
|
||||
await refresh
|
||||
})
|
||||
}
|
||||
expectPending(order === 'newer-fails' ? 'challenge-y' : 'challenge-z')
|
||||
expect(currentPage().title).toBe(order === 'newer-fails' ? 'Reload outcome' : 'Current input')
|
||||
expect(currentPage().loading).toBe(false)
|
||||
}
|
||||
)
|
||||
|
||||
it('releases retired Reload loading before failed Proceed without a native wake', async () => {
|
||||
const { result } = renderNavigation()
|
||||
act(() => result.current.applyRemoteTabInfo(failedTab()))
|
||||
const reload = deferred<unknown>()
|
||||
vi.mocked(callRuntimeRpc).mockReturnValue(reload.promise)
|
||||
let pending!: Promise<void>
|
||||
await act(async () => {
|
||||
pending = result.current.runRemoteNavigation('browser.reload')
|
||||
})
|
||||
expect(currentPage().loading).toBe(true)
|
||||
act(() => result.current.prepareCertificateProceed())
|
||||
expect(currentPage().loading).toBe(false)
|
||||
await act(async () => {
|
||||
reload.reject(new Error('connection lost before reaching host'))
|
||||
await pending
|
||||
})
|
||||
expectPending()
|
||||
expect(currentPage().loading).toBe(false)
|
||||
})
|
||||
|
||||
it('does not bless external ABA or clear native-owned loading during local cleanup', async () => {
|
||||
const { session, tokens, result } = renderNavigation()
|
||||
act(() => result.current.applyRemoteTabInfo(failedTab()))
|
||||
const token = tokens.createOperationToken('remote-page-a')!
|
||||
act(() => session.setPageLoading(token, true, useAppStore.getState().updateBrowserPageState))
|
||||
const response = deferred<{ tab: BrowserTabInfo }>()
|
||||
vi.mocked(callRuntimeRpc).mockReturnValue(response.promise)
|
||||
const pending = session.refreshTabInfo(token)
|
||||
act(() => {
|
||||
useAppStore.getState().updateBrowserPageState('page-a', { loadError: null })
|
||||
result.current.applyRemoteTabInfo(failedTab())
|
||||
useAppStore.getState().updateBrowserPageState('page-a', { loading: true })
|
||||
session.setPageLoading(token, false, useAppStore.getState().updateBrowserPageState)
|
||||
})
|
||||
await act(async () => {
|
||||
response.resolve({ tab: failedTab('stale') })
|
||||
await pending
|
||||
})
|
||||
expectPending()
|
||||
expect(currentPage().loading).toBe(true)
|
||||
})
|
||||
|
||||
it.each(['initial-open', 'restart'] as const)(
|
||||
'preserves command failure when %s fails before ready',
|
||||
async (phase) => {
|
||||
vi.useFakeTimers()
|
||||
const { lifecycle, subscribe, result } = renderNavigation()
|
||||
const status = deferred<{ capabilities: string[] }>()
|
||||
const read = deferred<{ tab: BrowserTabInfo }>()
|
||||
let held = phase === 'initial-open'
|
||||
let commandStarted = false
|
||||
vi.mocked(callRuntimeRpc).mockImplementation(async (_target, method) => {
|
||||
if (method === 'status.get') {
|
||||
return held ? status.promise : { capabilities: ['browser.screencast.v1'] }
|
||||
}
|
||||
if (method === 'browser.goto') {
|
||||
commandStarted = true
|
||||
throw new Error('ERR_NAME_NOT_RESOLVED (-105)')
|
||||
}
|
||||
return commandStarted ? read.promise : { tab: failedTab() }
|
||||
})
|
||||
try {
|
||||
lifecycle.open()
|
||||
await act(() => vi.advanceTimersByTimeAsync(0))
|
||||
if (phase === 'restart') {
|
||||
const callbacks = subscribe.mock.calls[0][1]
|
||||
callbacks.onResponse({
|
||||
id: 'stream-1',
|
||||
ok: true,
|
||||
result: {
|
||||
type: 'ready',
|
||||
subscriptionId: 'stream-1',
|
||||
browserPageId: 'remote-page-a',
|
||||
format: 'jpeg',
|
||||
tab: failedTab()
|
||||
},
|
||||
_meta: { runtimeId: 'host-a' }
|
||||
})
|
||||
held = true
|
||||
callbacks.onClose?.()
|
||||
await act(() => vi.runOnlyPendingTimersAsync())
|
||||
}
|
||||
let command!: Promise<void>
|
||||
await act(async () => {
|
||||
command = result.current.runRemoteNavigation('browser.goto', 'https://missing.test/')
|
||||
})
|
||||
subscribe.mockRejectedValueOnce(
|
||||
Object.assign(new Error('stream unavailable'), { code: 'browser_screencast_unsupported' })
|
||||
)
|
||||
await act(async () => {
|
||||
status.resolve({ capabilities: ['browser.screencast.v1'] })
|
||||
await vi.advanceTimersByTimeAsync(0)
|
||||
})
|
||||
await act(async () => {
|
||||
read.reject(new Error('outcome read unavailable'))
|
||||
await command
|
||||
})
|
||||
expect(currentPage().loadError).toEqual({
|
||||
code: -105,
|
||||
description: 'ERR_NAME_NOT_RESOLVED',
|
||||
validatedUrl: 'https://missing.test/'
|
||||
})
|
||||
expect(currentPage().loading).toBe(false)
|
||||
} finally {
|
||||
lifecycle.dispose()
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
it('rejects a late read after native replacement/clear, another action, host switch, or unmount, then accepts a current read', async () => {
|
||||
const { result, session, tokens, identity } = renderNavigation()
|
||||
act(() => result.current.applyRemoteTabInfo(failedTab()))
|
||||
|
||||
+5
-1
@@ -111,10 +111,14 @@ export function useRemoteBrowserPageNavigation({
|
||||
|
||||
const prepareCertificateProceed = useCallback((): void => {
|
||||
navigationSequence.current += 1
|
||||
const token = createRemoteOperationToken()
|
||||
if (token) {
|
||||
lifecycle.session.setPageLoading(token, false, onUpdatePageState)
|
||||
}
|
||||
lifecycle.session.invalidateTabInfoReads()
|
||||
setPaneBusy(false)
|
||||
setPaneNotice(null)
|
||||
}, [lifecycle, setPaneBusy, setPaneNotice])
|
||||
}, [createRemoteOperationToken, lifecycle, onUpdatePageState, setPaneBusy, setPaneNotice])
|
||||
|
||||
const scheduleRemoteTabInfoRefresh = useCallback(
|
||||
(token: RemoteBrowserOperationToken, delayMs = 250): void => {
|
||||
|
||||
Reference in New Issue
Block a user