mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Preserve browser navigation and loading across asynchronous metadata reads
This commit is contained in:
@@ -2,11 +2,16 @@ import { EventEmitter } from 'node:events'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import type { BrowserGuestMetadata } from '../../../../shared/browser/guest-lifecycle/browser-guest-metadata'
|
||||
import type { BrowserLoadError } from '../../../../shared/browser-workspace-types'
|
||||
import { installBrowserGuestMetadata, publishBrowserGuestMetadata } from './browser-guest-metadata'
|
||||
import {
|
||||
installBrowserGuestMetadata,
|
||||
publishBrowserGuestMetadata,
|
||||
readBrowserGuestMetadata
|
||||
} from './browser-guest-metadata'
|
||||
|
||||
function fixture() {
|
||||
let url = 'https://example.test/start'
|
||||
let title = 'Start'
|
||||
let loading = false
|
||||
let back = false
|
||||
let loadError: BrowserLoadError | null = null
|
||||
const emitter = new EventEmitter()
|
||||
@@ -15,7 +20,7 @@ function fixture() {
|
||||
isDestroyed: () => false,
|
||||
getURL: () => url,
|
||||
getTitle: () => title,
|
||||
isLoadingMainFrame: () => false,
|
||||
isLoadingMainFrame: () => loading,
|
||||
navigationHistory: { canGoBack: () => back, canGoForward: () => false }
|
||||
})
|
||||
const reports: BrowserGuestMetadata[] = []
|
||||
@@ -44,6 +49,9 @@ function fixture() {
|
||||
url = nextUrl
|
||||
title = nextTitle
|
||||
},
|
||||
setLoading: (value: boolean) => {
|
||||
loading = value
|
||||
},
|
||||
setBack: () => {
|
||||
back = true
|
||||
}
|
||||
@@ -51,6 +59,24 @@ function fixture() {
|
||||
}
|
||||
|
||||
describe('native guest metadata', () => {
|
||||
it('samples native loading before navigation-start and keeps subsequent title reports current', () => {
|
||||
const f = fixture()
|
||||
f.setLoading(true)
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies the native metadata methods.
|
||||
const state = readBrowserGuestMetadata(f.guest as unknown as Electron.WebContents)
|
||||
expect(state).toMatchObject({
|
||||
url: 'https://example.test/start',
|
||||
loading: true,
|
||||
navigationRevision: 0
|
||||
})
|
||||
f.guest.emit('page-title-updated', {}, 'Current title')
|
||||
expect(f.reports.at(-1)).toMatchObject({ title: 'Current title', loading: true })
|
||||
f.setLoading(false)
|
||||
f.guest.emit('did-stop-loading')
|
||||
expect(f.reports.at(-1)).toMatchObject({ url: 'https://example.test/start', loading: false })
|
||||
f.dispose()
|
||||
})
|
||||
|
||||
it('projects same-URL native history and retains it through a failed destination without publishing Chromium internals', () => {
|
||||
const f = fixture()
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: fixture supplies the production publisher native methods.
|
||||
|
||||
@@ -61,10 +61,12 @@ export function installBrowserGuestMetadata({
|
||||
...readGuestNavigationState(guest)
|
||||
}
|
||||
}
|
||||
const publish = (kind: BrowserGuestMetadata['kind'] = 'snapshot'): void => {
|
||||
const publish = (
|
||||
kind: BrowserGuestMetadata['kind'] = 'snapshot'
|
||||
): BrowserGuestMetadata | null => {
|
||||
const next = read(kind)
|
||||
if (!next) {
|
||||
return
|
||||
return null
|
||||
}
|
||||
if (
|
||||
previous &&
|
||||
@@ -82,11 +84,12 @@ export function installBrowserGuestMetadata({
|
||||
next.canGoForward === previous.canGoForward &&
|
||||
next.navigationRevision === previous.navigationRevision
|
||||
) {
|
||||
return
|
||||
return previous
|
||||
}
|
||||
next.revision = ++revision
|
||||
previous = next
|
||||
send(next)
|
||||
return next
|
||||
}
|
||||
const onNavigate = (_event: Electron.Event, url: string): void => {
|
||||
if (isChromiumInternalErrorUrl(url)) {
|
||||
@@ -125,6 +128,12 @@ export function installBrowserGuestMetadata({
|
||||
loading = true
|
||||
publish('start')
|
||||
}
|
||||
const onStartLoading = (): void => {
|
||||
if (guest.isLoadingMainFrame() && !isChromiumInternalErrorUrl(guest.getURL())) {
|
||||
loading = true
|
||||
publish('start')
|
||||
}
|
||||
}
|
||||
const onStop = (): void => {
|
||||
if (
|
||||
isChromiumInternalErrorUrl(guest.getURL()) &&
|
||||
@@ -149,11 +158,23 @@ export function installBrowserGuestMetadata({
|
||||
loading = false
|
||||
publish('failure')
|
||||
}
|
||||
projections.set(guest, { read: () => read(), publish: () => publish() })
|
||||
projections.set(guest, {
|
||||
read: () => {
|
||||
if (guest.isDestroyed()) {
|
||||
return null
|
||||
}
|
||||
loading = guest.isLoadingMainFrame()
|
||||
return publish()
|
||||
},
|
||||
publish: () => {
|
||||
publish()
|
||||
}
|
||||
})
|
||||
guest.on('did-navigate', onNavigate)
|
||||
guest.on('did-navigate-in-page', onInPage)
|
||||
guest.on('page-title-updated', onTitle)
|
||||
guest.on('did-start-navigation', onStart)
|
||||
guest.on('did-start-loading', onStartLoading)
|
||||
guest.on('did-stop-loading', onStop)
|
||||
guest.on('did-fail-load', onFail)
|
||||
return () => {
|
||||
@@ -165,6 +186,7 @@ export function installBrowserGuestMetadata({
|
||||
guest.off('did-navigate-in-page', onInPage)
|
||||
guest.off('page-title-updated', onTitle)
|
||||
guest.off('did-start-navigation', onStart)
|
||||
guest.off('did-start-loading', onStartLoading)
|
||||
guest.off('did-stop-loading', onStop)
|
||||
guest.off('did-fail-load', onFail)
|
||||
}
|
||||
|
||||
+246
-2
@@ -1,5 +1,10 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { act, cleanup, render, screen } from '@testing-library/react'
|
||||
import type { BrowserGuestMetadata } from '../../../../shared/browser/guest-lifecycle/browser-guest-metadata'
|
||||
import {
|
||||
cachedBrowserGuestMetadata,
|
||||
clearBrowserGuestMetadata
|
||||
} from './host-guest/browser-guest-metadata-cache'
|
||||
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import type {
|
||||
BrowserCertificateFailure,
|
||||
@@ -27,6 +32,7 @@ import {
|
||||
reportClientHostedGuestMetadata
|
||||
} from './client-hosted-browser-pane-test-rig'
|
||||
import { ClientHostedBrowserPagePane } from './ClientHostedBrowserPagePane'
|
||||
import { clearBrowserPageDeferredNavigation } from './navigate/browser-page-deferred-navigation'
|
||||
|
||||
const PLACEMENT = {
|
||||
kind: 'client' as const,
|
||||
@@ -52,21 +58,249 @@ beforeEach(() => {
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
clearBrowserPageDeferredNavigation('page-a')
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
/** Worktree switches unmount chrome while retaining the guest; use the real store because clearing loadError also deletes its certificate record. */
|
||||
describe('ClientHostedBrowserPagePane failure records across a remount', () => {
|
||||
it('issues a staged request before native replay or an unanswered initial publication', async () => {
|
||||
const idleA = reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
url: FAILED_URL,
|
||||
title: 'Selfsigned',
|
||||
loading: false
|
||||
})
|
||||
mocks.attach.mockReturnValueOnce(null)
|
||||
const staged = render(<StoreDrivenPane />)
|
||||
submitUrl('https://requested.internal/b')
|
||||
act(() => staged.unmount())
|
||||
vi.mocked(window.api.browser.publishClientPageMetadata).mockImplementation(
|
||||
() => new Promise(() => {})
|
||||
)
|
||||
vi.mocked(window.api.browser.getGuestMetadata).mockResolvedValueOnce({
|
||||
...idleA,
|
||||
revision: idleA.revision + 1,
|
||||
kind: 'snapshot',
|
||||
loading: true
|
||||
})
|
||||
await act(async () => {
|
||||
render(<StoreDrivenPane />)
|
||||
})
|
||||
expect(webview.loadURL).toHaveBeenCalledWith('https://requested.internal/b')
|
||||
expect(storedPage()).toMatchObject({
|
||||
url: 'https://requested.internal/b',
|
||||
title: 'https://requested.internal/b',
|
||||
loading: true
|
||||
})
|
||||
expect(
|
||||
vi.mocked(window.api.browser.publishClientPageMetadata).mock.calls[0]?.[0].params
|
||||
).toMatchObject({
|
||||
url: 'https://requested.internal/b',
|
||||
title: 'https://requested.internal/b',
|
||||
loading: true
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps a requested page through old readback and a successor, then settles Stop at the native document', async () => {
|
||||
const staleA = reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
url: FAILED_URL,
|
||||
title: 'Selfsigned',
|
||||
loading: false
|
||||
})
|
||||
clearBrowserGuestMetadata()
|
||||
let q1!: (state: BrowserGuestMetadata) => void
|
||||
let q2!: (state: BrowserGuestMetadata) => void
|
||||
vi.mocked(window.api.browser.getGuestMetadata)
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
q1 = resolve
|
||||
})
|
||||
)
|
||||
.mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((resolve) => {
|
||||
q2 = resolve
|
||||
})
|
||||
)
|
||||
let view!: ReturnType<typeof render>
|
||||
await act(async () => {
|
||||
view = render(<StoreDrivenPane />)
|
||||
})
|
||||
submitUrl('https://requested.internal/b')
|
||||
await act(async () => {})
|
||||
act(() => view.unmount())
|
||||
await act(async () => {
|
||||
render(<StoreDrivenPane />)
|
||||
})
|
||||
await act(async () => {
|
||||
q1(staleA)
|
||||
})
|
||||
expect(storedPage()).toMatchObject({
|
||||
url: 'https://requested.internal/b',
|
||||
title: 'https://requested.internal/b',
|
||||
loading: true
|
||||
})
|
||||
const sample = reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
kind: 'snapshot',
|
||||
url: FAILED_URL,
|
||||
title: 'Outgoing A',
|
||||
loading: true
|
||||
})
|
||||
await act(async () => {
|
||||
q2(sample)
|
||||
})
|
||||
act(() =>
|
||||
reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
kind: 'title',
|
||||
title: 'Outgoing A tick',
|
||||
loading: true
|
||||
})
|
||||
)
|
||||
expect(storedPage()).toMatchObject({
|
||||
url: 'https://requested.internal/b',
|
||||
title: 'https://requested.internal/b',
|
||||
loading: true
|
||||
})
|
||||
expect(
|
||||
vi.mocked(window.api.browser.publishClientPageMetadata).mock.lastCall?.[0].params
|
||||
).toMatchObject({
|
||||
url: 'https://requested.internal/b',
|
||||
title: 'https://requested.internal/b',
|
||||
loading: true
|
||||
})
|
||||
expect(cachedBrowserGuestMetadata(webview)?.url).toBe('https://selfsigned.internal/')
|
||||
await act(async () =>
|
||||
reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
kind: 'stop',
|
||||
title: 'Selfsigned',
|
||||
loading: false
|
||||
})
|
||||
)
|
||||
expect(storedPage()).toMatchObject({
|
||||
url: 'https://selfsigned.internal/',
|
||||
title: 'Selfsigned',
|
||||
loading: false
|
||||
})
|
||||
})
|
||||
|
||||
it('revalidates a healthy Stop after a command read failed', async () => {
|
||||
render(<StoreDrivenPane />)
|
||||
vi.mocked(window.api.browser.getGuestMetadata).mockRejectedValueOnce(
|
||||
new Error('metadata read failed')
|
||||
)
|
||||
submitUrl('https://requested.internal/b')
|
||||
await act(async () => {})
|
||||
expect(storedPage()).toMatchObject({ url: 'https://requested.internal/b', loading: true })
|
||||
await act(async () =>
|
||||
reportClientHostedGuestMetadata({ webContentsId: 42, kind: 'stop', loading: false })
|
||||
)
|
||||
expect(storedPage()).toMatchObject({
|
||||
url: 'https://selfsigned.internal/',
|
||||
title: 'Selfsigned',
|
||||
loading: false
|
||||
})
|
||||
})
|
||||
|
||||
it('adopts an already committed page on same-guest readiness after its read failed', async () => {
|
||||
render(<StoreDrivenPane />)
|
||||
let reject!: (error: Error) => void
|
||||
vi.mocked(window.api.browser.getGuestMetadata).mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((_resolve, fail) => {
|
||||
reject = fail
|
||||
})
|
||||
)
|
||||
submitUrl('https://requested.internal/b')
|
||||
await act(async () => {})
|
||||
act(() =>
|
||||
reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
kind: 'navigation',
|
||||
url: 'https://requested.internal/b',
|
||||
title: 'Committed B',
|
||||
loading: true
|
||||
})
|
||||
)
|
||||
await act(async () => {
|
||||
reject(new Error('metadata read failed'))
|
||||
})
|
||||
await act(async () => {
|
||||
webview.dispatchEvent(new Event('dom-ready'))
|
||||
})
|
||||
expect(storedPage()).toMatchObject({
|
||||
url: 'https://requested.internal/b',
|
||||
title: 'Committed B',
|
||||
loading: true
|
||||
})
|
||||
})
|
||||
|
||||
it('shows a hidden committed document and its live title while another load is pending', async () => {
|
||||
let resolve!: (state: BrowserGuestMetadata) => void
|
||||
const view = render(<StoreDrivenPane />)
|
||||
vi.mocked(window.api.browser.getGuestMetadata).mockImplementationOnce(
|
||||
() =>
|
||||
new Promise((done) => {
|
||||
resolve = done
|
||||
})
|
||||
)
|
||||
submitUrl('https://requested.internal/b')
|
||||
await act(async () => {})
|
||||
act(() => view.unmount())
|
||||
reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
kind: 'navigation',
|
||||
url: 'https://current.internal/c',
|
||||
title: 'Current C',
|
||||
loading: true
|
||||
})
|
||||
const sample = reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
kind: 'snapshot',
|
||||
loading: true
|
||||
})
|
||||
await act(async () => {
|
||||
resolve(sample)
|
||||
})
|
||||
expect(storedPage().loading).toBe(true)
|
||||
render(<StoreDrivenPane />)
|
||||
expect(storedPage()).toMatchObject({
|
||||
url: 'https://current.internal/c',
|
||||
title: 'Current C',
|
||||
loading: true
|
||||
})
|
||||
act(() =>
|
||||
reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
kind: 'title',
|
||||
title: 'Current C live',
|
||||
loading: true
|
||||
})
|
||||
)
|
||||
expect(storedPage()).toMatchObject({
|
||||
url: 'https://current.internal/c',
|
||||
title: 'Current C live',
|
||||
loading: true
|
||||
})
|
||||
})
|
||||
|
||||
it('retains the saved title until a first committed document exists, including a failed first load', () => {
|
||||
reportClientHostedGuestMetadata({
|
||||
webContentsId: 42,
|
||||
navigationRevision: 0,
|
||||
url: '',
|
||||
title: '',
|
||||
kind: 'snapshot'
|
||||
kind: 'snapshot',
|
||||
loading: true
|
||||
})
|
||||
render(<StoreDrivenPane />)
|
||||
expect(storedPage().title).toBe('Selfsigned')
|
||||
expect(storedPage().loading).toBe(true)
|
||||
act(() => reportClientHostedGuestMetadata({ webContentsId: 42, kind: 'start', loading: true }))
|
||||
expect(storedPage().title).toBe('Selfsigned')
|
||||
act(() => reportClientHostedGuestMetadata({ webContentsId: 42, kind: 'stop', loading: false }))
|
||||
@@ -307,3 +541,13 @@ function createWebview(): Electron.WebviewTag & { getURL: ReturnType<typeof vi.f
|
||||
})
|
||||
return element
|
||||
}
|
||||
|
||||
function submitUrl(url: string): void {
|
||||
const input = screen.getByRole('combobox')
|
||||
fireEvent.change(input, { target: { value: url } })
|
||||
const form = input.closest('form')
|
||||
if (!form) {
|
||||
throw new Error('Address input has no submission form')
|
||||
}
|
||||
fireEvent.submit(form)
|
||||
}
|
||||
|
||||
@@ -57,7 +57,9 @@ import {
|
||||
} from './client-hosted-browser-pane-test-rig'
|
||||
import { ClientHostedBrowserPagePane } from './ClientHostedBrowserPagePane'
|
||||
|
||||
function render(ui: React.ReactElement) {
|
||||
function render(ui: React.ReactElement<{ browserTab: BrowserPage }>) {
|
||||
const current = ui.props.browserTab
|
||||
useAppStore.setState({ browserPagesByWorkspace: { [current.workspaceId]: [current] } })
|
||||
return renderWithProviders(ui, { wrapper: TooltipProvider })
|
||||
}
|
||||
|
||||
@@ -211,17 +213,11 @@ describe('ClientHostedBrowserPagePane', () => {
|
||||
expect(screen.getByPlaceholderText('Find in page...')).not.toBeNull()
|
||||
act(() => reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'stop' }))
|
||||
expect(screen.getByPlaceholderText('Find in page...')).not.toBeNull()
|
||||
act(() =>
|
||||
reportClientHostedGuestMetadata({
|
||||
webContentsId: 7,
|
||||
kind: 'navigation',
|
||||
navigationRevision: 2
|
||||
})
|
||||
)
|
||||
act(() => webview.dispatchEvent(new Event('did-navigate')))
|
||||
expect(screen.queryByPlaceholderText('Find in page...')).toBeNull()
|
||||
})
|
||||
|
||||
it('restores the committed address after an attempted navigation is stopped', () => {
|
||||
it('restores the committed address after an attempted navigation is stopped', async () => {
|
||||
const { webview } = createWebview()
|
||||
reportClientHostedGuestMetadata({
|
||||
webContentsId: 7,
|
||||
@@ -251,7 +247,9 @@ describe('ClientHostedBrowserPagePane', () => {
|
||||
)
|
||||
act(() => screen.getByLabelText<HTMLInputElement>('Address').blur())
|
||||
onSetUrl.mockClear()
|
||||
act(() => reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'stop', loading: false }))
|
||||
await act(async () =>
|
||||
reportClientHostedGuestMetadata({ webContentsId: 7, kind: 'stop', loading: false })
|
||||
)
|
||||
expect(screen.getByLabelText<HTMLInputElement>('Address').value).toBe(
|
||||
'https://example.internal/a'
|
||||
)
|
||||
|
||||
@@ -6,7 +6,11 @@ import { BrowserLinkStatusBubble } from './assemble-chrome/browser-link-status-b
|
||||
import { useAppStore } from '@/store'
|
||||
import type { BrowserLoadError } from '../../../../shared/browser-workspace-types'
|
||||
import { createBrowserClientPageLoadFailureHandler } from './browser-client-page-guest-metadata'
|
||||
import { subscribeBrowserGuestMetadata } from './host-guest/browser-guest-metadata-cache'
|
||||
import {
|
||||
issueBrowserGuestNavigation,
|
||||
browserGuestPreservesRequestedDocument,
|
||||
subscribeBrowserGuestMetadata
|
||||
} from './host-guest/browser-guest-metadata-cache'
|
||||
import { redactKagiSessionToken } from '../../../../shared/browser-url'
|
||||
import {
|
||||
forgetBrowserClientPageMetadataReports,
|
||||
@@ -130,14 +134,15 @@ export function ClientHostedBrowserPagePane({
|
||||
webviewRef,
|
||||
activeLoadFailureRef,
|
||||
onUpdatePageState,
|
||||
onSetUrl,
|
||||
setAddressBarValue
|
||||
})
|
||||
const runDeferredNavigation = useEffectEvent(navigateToUrl)
|
||||
const readPendingPageMetadata = useEffectEvent(() => ({
|
||||
url: browserTab.url,
|
||||
title: browserTab.title,
|
||||
loading: browserTab.loading
|
||||
}))
|
||||
const readCurrentPage = useEffectEvent(() =>
|
||||
useAppStore
|
||||
.getState()
|
||||
.browserPagesByWorkspace[workspaceId]?.find((page) => page.id === browserTab.id)
|
||||
)
|
||||
// The guest lives in a body-level host that paints above the pane, so the cursor joins it there.
|
||||
const getAgentCursorHost = useCallback(
|
||||
() => webviewRef.current?.parentElement ?? null,
|
||||
@@ -197,75 +202,72 @@ export function ClientHostedBrowserPagePane({
|
||||
})
|
||||
webviewRef.current = webview
|
||||
setAttachmentError(null)
|
||||
let appliedUrl: string | null = null
|
||||
const receiveMetadata = (state: BrowserGuestMetadata | null): void => {
|
||||
if (!state || state.kind === 'retired') {
|
||||
guestLoss.lose('unreadable')
|
||||
return
|
||||
}
|
||||
const pending = readCurrentPage()
|
||||
if (!pending) {
|
||||
guestAvailable = false
|
||||
releaseGuest()
|
||||
return
|
||||
}
|
||||
const metadata = {
|
||||
url: redactKagiSessionToken(state.url || 'about:blank'),
|
||||
url: redactKagiSessionToken(state.url),
|
||||
title: state.title,
|
||||
loading: state.loading,
|
||||
canGoBack: state.canGoBack,
|
||||
canGoForward: state.canGoForward
|
||||
}
|
||||
const validDocument =
|
||||
Boolean(state.url) && !state.errorPage && !state.loadError && !state.hasCertificateFailure
|
||||
const presentDocument =
|
||||
validDocument && !browserGuestPreservesRequestedDocument(webview, state.url, pending.url)
|
||||
if (
|
||||
state.kind === 'navigation' ||
|
||||
((state.kind === 'stop' || (state.kind === 'snapshot' && !state.loading)) &&
|
||||
state.navigationRevision > 0 &&
|
||||
!state.loadError &&
|
||||
!state.hasCertificateFailure &&
|
||||
!state.errorPage)
|
||||
((state.kind === 'stop' || (state.kind === 'snapshot' && !state.loading)) && validDocument)
|
||||
) {
|
||||
activeLoadFailureRef.current = null
|
||||
}
|
||||
if (state.kind === 'navigation') {
|
||||
setFindOpen(false)
|
||||
}
|
||||
if (state.loadError) {
|
||||
activeLoadFailureRef.current = state.loadError
|
||||
}
|
||||
const activeLoadFailure = activeLoadFailureRef.current
|
||||
const observeUrl =
|
||||
state.navigationRevision > 0 &&
|
||||
!state.errorPage &&
|
||||
!state.loadError &&
|
||||
!state.hasCertificateFailure &&
|
||||
presentDocument &&
|
||||
!activeLoadFailure &&
|
||||
(state.kind === 'navigation' ||
|
||||
state.kind === 'in-page' ||
|
||||
state.kind === 'stop' ||
|
||||
(state.kind === 'snapshot' && state.navigationRevision > 0 && !state.loading))
|
||||
if (observeUrl && !activeLoadFailure) {
|
||||
if (appliedUrl !== metadata.url) {
|
||||
appliedUrl = metadata.url
|
||||
state.kind === 'snapshot')
|
||||
if (observeUrl) {
|
||||
if (pending.url !== metadata.url) {
|
||||
setUrlFromGuest(browserTab.id, metadata.url, { preserveLoadError: true })
|
||||
}
|
||||
setAddressBarValueFromPage(toDisplayUrl(metadata.url))
|
||||
}
|
||||
updatePageStateFromGuest(browserTab.id, {
|
||||
...(state.navigationRevision > 0 ? { title: metadata.title } : {}),
|
||||
...(state.kind === 'snapshot' && state.navigationRevision === 0
|
||||
? {}
|
||||
: { loading: metadata.loading }),
|
||||
...(presentDocument && !activeLoadFailure ? { title: metadata.title } : {}),
|
||||
loading: metadata.loading,
|
||||
canGoBack: metadata.canGoBack,
|
||||
canGoForward: metadata.canGoForward,
|
||||
loadError: activeLoadFailure
|
||||
})
|
||||
if (state.navigationRevision > 0) {
|
||||
publisher.publish(metadata)
|
||||
} else if (state.kind !== 'title') {
|
||||
const pending = readPendingPageMetadata()
|
||||
publisher.publish({
|
||||
...metadata,
|
||||
...pending,
|
||||
loading: state.kind === 'snapshot' ? pending.loading : state.loading
|
||||
})
|
||||
const current = readCurrentPage()
|
||||
if (!current) {
|
||||
return
|
||||
}
|
||||
if (observeUrl || state.kind === 'title') {
|
||||
publisher.publish({
|
||||
...metadata,
|
||||
...(presentDocument && !activeLoadFailure ? {} : { url: current.url, title: current.title })
|
||||
})
|
||||
if (observeUrl || (state.kind === 'title' && presentDocument && !activeLoadFailure)) {
|
||||
recordHistoryFromGuest(metadata.url, getBrowserDisplayTitle(metadata.title, metadata.url))
|
||||
}
|
||||
}
|
||||
const onNavigate = (): void => setFindOpen(false)
|
||||
webview.addEventListener('did-navigate', onNavigate)
|
||||
const onFailLoad = createBrowserClientPageLoadFailureHandler(webview, (loadError) => {
|
||||
activeLoadFailureRef.current = loadError
|
||||
updatePageStateFromGuest(browserTab.id, { loading: false, loadError })
|
||||
@@ -275,21 +277,22 @@ export function ClientHostedBrowserPagePane({
|
||||
const cleanupGuest = (): void => {
|
||||
unsubscribeMetadata()
|
||||
webview.removeEventListener('did-fail-load', onFailLoad)
|
||||
webview.removeEventListener('did-navigate', onNavigate)
|
||||
guestLoss.dispose()
|
||||
publisher.dispose()
|
||||
forgetBrowserClientPageMetadataReports(browserTab.id)
|
||||
attachment.detach()
|
||||
}
|
||||
releaseGuest = cleanupGuest
|
||||
const deferredUrl = consumeBrowserPageDeferredNavigation(browserTab.id)
|
||||
if (deferredUrl) {
|
||||
runDeferredNavigation(deferredUrl)
|
||||
}
|
||||
unsubscribeMetadata = subscribeBrowserGuestMetadata(browserTab.id, webview, receiveMetadata)
|
||||
if (!guestAvailable) {
|
||||
cleanupGuest()
|
||||
return cleanupGuest
|
||||
}
|
||||
const deferredUrl = consumeBrowserPageDeferredNavigation(browserTab.id)
|
||||
if (deferredUrl) {
|
||||
runDeferredNavigation(deferredUrl)
|
||||
}
|
||||
return cleanupGuest
|
||||
}, [
|
||||
browserTab.id,
|
||||
@@ -334,8 +337,10 @@ export function ClientHostedBrowserPagePane({
|
||||
controls={{
|
||||
canGoBack: browserTab.canGoBack,
|
||||
canGoForward: browserTab.canGoForward,
|
||||
goBack: () => webviewRef.current?.goBack(),
|
||||
goForward: () => webviewRef.current?.goForward(),
|
||||
goBack: () =>
|
||||
issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goBack()),
|
||||
goForward: () =>
|
||||
issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goForward()),
|
||||
reload: () => reload.runReloadTrigger('button'),
|
||||
navigate: navigateToUrl
|
||||
}}
|
||||
@@ -394,7 +399,7 @@ export function ClientHostedBrowserPagePane({
|
||||
<ClientHostedBrowserUnavailableNotice
|
||||
runtimeEnvironmentId={runtimeEnvironmentId}
|
||||
worktreeId={worktreeId}
|
||||
lastCommittedUrl={browserTab.url}
|
||||
reopenUrl={browserTab.url}
|
||||
placementHostClientId={browserHostClientId}
|
||||
/>
|
||||
) : isBlankBrowserUrl(browserTab.url) ? (
|
||||
|
||||
@@ -25,12 +25,12 @@ export function reopenOnServerCaveat(t: Translate = translate): string {
|
||||
export function ReopenBrowserPageOnServerButton({
|
||||
environmentId,
|
||||
worktreeId,
|
||||
lastCommittedUrl,
|
||||
reopenUrl,
|
||||
className
|
||||
}: {
|
||||
environmentId: string
|
||||
worktreeId: string
|
||||
lastCommittedUrl: string | null | undefined
|
||||
reopenUrl: string | null | undefined
|
||||
className?: string
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
@@ -54,7 +54,7 @@ export function ReopenBrowserPageOnServerButton({
|
||||
pendingTimerRef.current = null
|
||||
setShowPending(true)
|
||||
}, REOPEN_PENDING_FEEDBACK_DELAY_MS)
|
||||
void reopenBrowserPageOnServer({ environmentId, worktreeId, lastCommittedUrl })
|
||||
void reopenBrowserPageOnServer({ environmentId, worktreeId, reopenUrl })
|
||||
.then((created) => {
|
||||
if (!created) {
|
||||
toast.error(
|
||||
@@ -73,7 +73,7 @@ export function ReopenBrowserPageOnServerButton({
|
||||
setShowPending(false)
|
||||
setPending(false)
|
||||
})
|
||||
}, [clearPendingTimer, environmentId, lastCommittedUrl, worktreeId])
|
||||
}, [clearPendingTimer, environmentId, reopenUrl, worktreeId])
|
||||
|
||||
return (
|
||||
<Button
|
||||
|
||||
+3
-2
@@ -1,3 +1,4 @@
|
||||
import { issueBrowserGuestNavigation } from '../host-guest/browser-guest-metadata-cache'
|
||||
import { Fragment, type MutableRefObject } from 'react'
|
||||
import { useAppStore } from '@/store'
|
||||
import { isMac } from '@/app-shell/app-window-chrome'
|
||||
@@ -221,12 +222,12 @@ function buildMenuSections(
|
||||
sections.push([
|
||||
item(
|
||||
t('auto.components.browser.pane.BrowserPane.40edfa75cb', 'Back'),
|
||||
() => webviewRef.current?.goBack(),
|
||||
() => issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goBack()),
|
||||
!canGoBack
|
||||
),
|
||||
item(
|
||||
t('auto.components.browser.pane.BrowserPane.250a9b3e42', 'Forward'),
|
||||
() => webviewRef.current?.goForward(),
|
||||
() => issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goForward()),
|
||||
!canGoForward
|
||||
),
|
||||
item(t('auto.components.browser.pane.BrowserPane.0e080d820e', 'Reload'), onReload)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { issueBrowserGuestNavigation } from '../host-guest/browser-guest-metadata-cache'
|
||||
import type { Dispatch, RefObject, SetStateAction } from 'react'
|
||||
import { ArtifactPublishButton } from '@/components/artifacts/ArtifactPublishButton'
|
||||
import { useShortcutLabel } from '@/hooks/useShortcutLabel'
|
||||
@@ -151,7 +152,7 @@ export function BrowserPageToolbar({
|
||||
// Guest replacement loses history; Back/Forward cross the conversion once guest history runs out.
|
||||
goBack: () => {
|
||||
if (canGoBack) {
|
||||
webviewRef.current?.goBack()
|
||||
issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goBack())
|
||||
return
|
||||
}
|
||||
if (convertedFrom) {
|
||||
@@ -160,7 +161,7 @@ export function BrowserPageToolbar({
|
||||
},
|
||||
goForward: () => {
|
||||
if (canGoForward) {
|
||||
webviewRef.current?.goForward()
|
||||
issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goForward())
|
||||
return
|
||||
}
|
||||
if (convertedTo) {
|
||||
|
||||
@@ -3,7 +3,7 @@ import '../../../../shared/constants'
|
||||
import { ORCA_BROWSER_BLANK_URL } from '../../../../shared/browser/browser-blank-page'
|
||||
import { createWebRuntimeSessionBrowserTab } from '@/runtime/browser/creation/web-runtime-browser-creation'
|
||||
|
||||
/** Restore only committed web URLs across engines; other destinations reopen blank and request bodies are never reconstructed. */
|
||||
/** Reopen the requested/current web URL across engines; other destinations reopen blank and request bodies are never reconstructed. */
|
||||
export function resolveBrowserReopenOnServerUrl(
|
||||
url: string | null | undefined
|
||||
): string | undefined {
|
||||
@@ -26,12 +26,12 @@ export function resolveBrowserReopenOnServerUrl(
|
||||
export async function reopenBrowserPageOnServer(args: {
|
||||
environmentId: string
|
||||
worktreeId: string
|
||||
lastCommittedUrl: string | null | undefined
|
||||
reopenUrl: string | null | undefined
|
||||
}): Promise<boolean> {
|
||||
return createWebRuntimeSessionBrowserTab({
|
||||
worktreeId: args.worktreeId,
|
||||
environmentId: args.environmentId,
|
||||
url: resolveBrowserReopenOnServerUrl(args.lastCommittedUrl),
|
||||
url: resolveBrowserReopenOnServerUrl(args.reopenUrl),
|
||||
placementPreference: 'server',
|
||||
focusOnCreate: true
|
||||
})
|
||||
|
||||
@@ -45,7 +45,9 @@ export function installClientHostedPaneApi(overrides?: {
|
||||
configurable: true,
|
||||
value: {
|
||||
browser: {
|
||||
getGuestMetadata: vi.fn(async () => undefined),
|
||||
getGuestMetadata: vi.fn(async ({ webContentsId }: { webContentsId: number }) =>
|
||||
guestStates.get(webContentsId)
|
||||
),
|
||||
onGuestMetadata: inert,
|
||||
onGuestEscape: inert,
|
||||
onPopup: inert,
|
||||
|
||||
+3
-3
@@ -20,12 +20,12 @@ import { BROWSER_SCREENCAST_RUNTIME_CAPABILITY } from '../../../../shared/browse
|
||||
export function ClientHostedBrowserUnavailableNotice({
|
||||
runtimeEnvironmentId,
|
||||
worktreeId,
|
||||
lastCommittedUrl,
|
||||
reopenUrl,
|
||||
placementHostClientId
|
||||
}: {
|
||||
runtimeEnvironmentId: string
|
||||
worktreeId: string
|
||||
lastCommittedUrl: string
|
||||
reopenUrl: string
|
||||
placementHostClientId: string | null
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
@@ -87,7 +87,7 @@ export function ClientHostedBrowserUnavailableNotice({
|
||||
<ReopenBrowserPageOnServerButton
|
||||
environmentId={runtimeEnvironmentId}
|
||||
worktreeId={worktreeId}
|
||||
lastCommittedUrl={lastCommittedUrl}
|
||||
reopenUrl={reopenUrl}
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { issueBrowserGuestNavigation } from '../host-guest/browser-guest-metadata-cache'
|
||||
import type { BrowserPage as BrowserPageState } from '../../../../../shared/browser-workspace-types'
|
||||
import '../../../../../shared/constants'
|
||||
import { ORCA_BROWSER_BLANK_URL } from '../../../../../shared/browser/browser-blank-page'
|
||||
@@ -72,5 +73,7 @@ export function retryBrowserTabLoad(
|
||||
loading: true,
|
||||
title: retryUrl
|
||||
})
|
||||
webview.src = retryUrl
|
||||
issueBrowserGuestNavigation(webview, () => {
|
||||
webview.src = retryUrl
|
||||
})
|
||||
}
|
||||
|
||||
+30
-10
@@ -1,4 +1,9 @@
|
||||
import { subscribeBrowserGuestMetadata } from './browser-guest-metadata-cache'
|
||||
import { useAppStore } from '@/store'
|
||||
import {
|
||||
issueBrowserGuestNavigation,
|
||||
browserGuestPreservesRequestedDocument,
|
||||
subscribeBrowserGuestMetadata
|
||||
} from './browser-guest-metadata-cache'
|
||||
import { getBrowserDisplayTitle } from '../describe-page/browser-page-url-display'
|
||||
import { publishNativeChatVisualGuestTheme } from '@/components/native-chat/media/visuals/NativeChatVisualGuestThemePublisher'
|
||||
import { normalizeBrowserGuestSrc } from '../../../../../shared/browser/extensions/browser-extension-url'
|
||||
@@ -160,26 +165,39 @@ export function bindBrowserPageWebviewListeners({
|
||||
if (!metadata || metadata.kind === 'retired') {
|
||||
return
|
||||
}
|
||||
const page = useAppStore
|
||||
.getState()
|
||||
.browserPagesByWorkspace[workspaceId]?.find((page) => page.id === browserTabId)
|
||||
if (!page) {
|
||||
return
|
||||
}
|
||||
const { kind, url, title, loading, canGoBack, canGoForward } = metadata
|
||||
if (metadata.loadError) {
|
||||
activeLoadFailureRef.current = metadata.loadError
|
||||
}
|
||||
const presentDocument =
|
||||
Boolean(url) &&
|
||||
!metadata.errorPage &&
|
||||
!metadata.loadError &&
|
||||
!metadata.hasCertificateFailure &&
|
||||
!browserGuestPreservesRequestedDocument(webview, url, page.url)
|
||||
if (kind === 'navigation') {
|
||||
handleFullDidNavigate({ url })
|
||||
} else if (kind === 'in-page') {
|
||||
} else if (
|
||||
kind === 'in-page' ||
|
||||
(kind === 'snapshot' && loading && presentDocument && !activeLoadFailureRef.current)
|
||||
) {
|
||||
handleDidNavigateInPage({ url })
|
||||
}
|
||||
if (kind === 'title' && metadata.navigationRevision > 0) {
|
||||
if (kind === 'title' && presentDocument && !activeLoadFailureRef.current) {
|
||||
handleTitleUpdate({ title })
|
||||
}
|
||||
const settlement =
|
||||
kind === 'stop' || (kind === 'snapshot' && !loading && metadata.navigationRevision > 0)
|
||||
? handleDidStopLoading()
|
||||
: null
|
||||
kind === 'stop' || (kind === 'snapshot' && !loading) ? handleDidStopLoading() : null
|
||||
onUpdatePageStateRef.current(browserTabId, {
|
||||
...settlement,
|
||||
...(metadata.navigationRevision > 0
|
||||
? { title: getBrowserDisplayTitle(title, url || browserTabUrlRef.current) }
|
||||
...(presentDocument && !activeLoadFailureRef.current
|
||||
? { title: getBrowserDisplayTitle(title, url) }
|
||||
: {}),
|
||||
canGoBack,
|
||||
canGoForward,
|
||||
@@ -188,7 +206,7 @@ export function bindBrowserPageWebviewListeners({
|
||||
: kind === 'navigation'
|
||||
? { loadError: activeLoadFailureRef.current }
|
||||
: {}),
|
||||
...(kind === 'snapshot' && metadata.navigationRevision === 0 ? {} : { loading })
|
||||
loading
|
||||
})
|
||||
})
|
||||
|
||||
@@ -198,7 +216,9 @@ export function bindBrowserPageWebviewListeners({
|
||||
const initialUrl =
|
||||
normalizeBrowserGuestSrc(initialBrowserUrlRef.current) ?? ORCA_BROWSER_BLANK_URL
|
||||
lastKnownWebviewUrlRef.current = initialUrl
|
||||
webview.src = initialUrl
|
||||
issueBrowserGuestNavigation(webview, () => {
|
||||
webview.src = initialUrl
|
||||
})
|
||||
} else if (isPaintableRef.current) {
|
||||
if (isBrowserPageRendererRecoveryPending(browserTabId)) {
|
||||
guestRecovery.recoverRenderer()
|
||||
|
||||
+21
@@ -4,6 +4,7 @@ import type { BrowserGuestMetadata } from '../../../../../shared/browser/guest-l
|
||||
import {
|
||||
acceptBrowserGuestMetadata,
|
||||
clearBrowserGuestMetadata,
|
||||
issueBrowserGuestNavigation,
|
||||
subscribeBrowserGuestMetadata
|
||||
} from './browser-guest-metadata-cache'
|
||||
|
||||
@@ -37,6 +38,25 @@ function tag(id: number): Electron.WebviewTag {
|
||||
afterEach(clearBrowserGuestMetadata)
|
||||
|
||||
describe('guest metadata lifetime cache', () => {
|
||||
it('initializes a successor after an eventless command returns unchanged native state', async () => {
|
||||
const state = snapshot(1, 1, 'Idle A')
|
||||
Object.defineProperty(window, 'api', {
|
||||
configurable: true,
|
||||
value: { browser: { getGuestMetadata: vi.fn(async () => state) } }
|
||||
})
|
||||
acceptBrowserGuestMetadata(state)
|
||||
const webview = tag(1)
|
||||
const first = subscribeBrowserGuestMetadata('page', webview, () => {})
|
||||
issueBrowserGuestNavigation(webview, () => {})
|
||||
first()
|
||||
const observed: (BrowserGuestMetadata | null)[] = []
|
||||
const dispose = subscribeBrowserGuestMetadata('page', webview, (state) => observed.push(state))
|
||||
await vi.waitFor(() =>
|
||||
expect(observed.at(-1)).toMatchObject({ title: 'Idle A', loading: false })
|
||||
)
|
||||
dispose()
|
||||
})
|
||||
|
||||
it('discards a late initial read after a newer event and fences a replacement guest', async () => {
|
||||
let resolve!: (state: BrowserGuestMetadata) => void
|
||||
const getGuestMetadata = vi.fn(
|
||||
@@ -52,6 +72,7 @@ describe('guest metadata lifetime cache', () => {
|
||||
const webview = tag(1)
|
||||
const observed: (BrowserGuestMetadata | null)[] = []
|
||||
const dispose = subscribeBrowserGuestMetadata('page', webview, (state) => observed.push(state))
|
||||
await Promise.resolve()
|
||||
acceptBrowserGuestMetadata(snapshot(1, 2, 'Newer'))
|
||||
resolve(snapshot(1, 1, 'Stale'))
|
||||
await Promise.resolve()
|
||||
|
||||
+191
-37
@@ -1,26 +1,188 @@
|
||||
import type { BrowserGuestMetadata } from '../../../../../shared/browser/guest-lifecycle/browser-guest-metadata'
|
||||
import {
|
||||
normalizeBrowserNavigationUrl,
|
||||
redactKagiSessionToken
|
||||
} from '../../../../../shared/browser-url'
|
||||
|
||||
type Listener = (state: BrowserGuestMetadata | null) => void
|
||||
const snapshots = new Map<number, BrowserGuestMetadata>()
|
||||
type GuestMetadataEntry = {
|
||||
browserPageId?: string
|
||||
state?: BrowserGuestMetadata
|
||||
applicable: boolean
|
||||
presentationRequest?: object
|
||||
stopObserving?: () => void
|
||||
}
|
||||
const guests = new Map<number, GuestMetadataEntry>()
|
||||
const listeners = new Map<number, Set<Listener>>()
|
||||
const initialReads = new Map<number, Promise<void>>()
|
||||
|
||||
function notifyGuest(id: number, entry: GuestMetadataEntry, state: BrowserGuestMetadata): void {
|
||||
listeners.get(id)?.forEach((listener) => {
|
||||
if (guests.get(id) === entry && entry.applicable && entry.state?.revision === state.revision) {
|
||||
listener(state)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function retireGuest(id: number): void {
|
||||
const entry = guests.get(id)
|
||||
guests.delete(id)
|
||||
initialReads.delete(id)
|
||||
entry?.stopObserving?.()
|
||||
listeners.get(id)?.forEach((listener) => listener(null))
|
||||
}
|
||||
|
||||
function observeGuestDeath(
|
||||
id: number,
|
||||
webview: Electron.WebviewTag,
|
||||
entry: GuestMetadataEntry
|
||||
): void {
|
||||
if (entry.stopObserving) {
|
||||
return
|
||||
}
|
||||
const onDestroyed = (): void => retireGuest(id)
|
||||
webview.addEventListener('destroyed', onDestroyed)
|
||||
entry.stopObserving = () => webview.removeEventListener('destroyed', onDestroyed)
|
||||
}
|
||||
|
||||
function refreshGuest(id: number, browserPageId: string): void {
|
||||
if (initialReads.has(id)) {
|
||||
return
|
||||
}
|
||||
const request = Promise.resolve()
|
||||
.then(() => window.api.browser.getGuestMetadata({ browserPageId, webContentsId: id }))
|
||||
.then((state) => {
|
||||
if (initialReads.get(id) !== request) {
|
||||
return
|
||||
}
|
||||
initialReads.delete(id)
|
||||
if (state === null || state?.kind === 'retired') {
|
||||
retireGuest(id)
|
||||
return
|
||||
}
|
||||
if (!state) {
|
||||
return
|
||||
}
|
||||
const entry = guests.get(id) ?? { browserPageId, applicable: true }
|
||||
const wasApplicable = entry.applicable
|
||||
const previous = entry.state
|
||||
if (!previous || previous.revision < state.revision) {
|
||||
entry.state = state
|
||||
}
|
||||
const selected = entry.state ?? state
|
||||
entry.browserPageId = browserPageId
|
||||
entry.applicable = true
|
||||
if (
|
||||
!selected.loading ||
|
||||
selected.loadError ||
|
||||
selected.hasCertificateFailure ||
|
||||
selected.errorPage
|
||||
) {
|
||||
delete entry.presentationRequest
|
||||
}
|
||||
guests.set(id, entry)
|
||||
if (!wasApplicable || !previous || previous.revision < state.revision) {
|
||||
notifyGuest(id, entry, { ...selected, kind: 'snapshot' })
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
if (initialReads.get(id) === request) {
|
||||
initialReads.delete(id)
|
||||
}
|
||||
})
|
||||
initialReads.set(id, request)
|
||||
}
|
||||
|
||||
export function acceptBrowserGuestMetadata(state: BrowserGuestMetadata): void {
|
||||
const previous = snapshots.get(state.webContentsId)
|
||||
if (previous && previous.revision >= state.revision) {
|
||||
const id = state.webContentsId
|
||||
const entry = guests.get(id) ?? { browserPageId: state.browserPageId, applicable: true }
|
||||
if (entry.state && entry.state.revision >= state.revision) {
|
||||
return
|
||||
}
|
||||
if (state.kind === 'retired') {
|
||||
snapshots.delete(state.webContentsId)
|
||||
initialReads.delete(state.webContentsId)
|
||||
} else {
|
||||
snapshots.set(state.webContentsId, state)
|
||||
retireGuest(id)
|
||||
return
|
||||
}
|
||||
listeners.get(state.webContentsId)?.forEach((listener) => listener(state))
|
||||
entry.state = state
|
||||
entry.browserPageId = state.browserPageId
|
||||
if (
|
||||
state.kind === 'navigation' ||
|
||||
state.kind === 'in-page' ||
|
||||
(entry.applicable && (state.kind === 'stop' || state.kind === 'failure'))
|
||||
) {
|
||||
delete entry.presentationRequest
|
||||
}
|
||||
guests.set(id, entry)
|
||||
if (entry.applicable) {
|
||||
notifyGuest(id, entry, state)
|
||||
} else if (state.kind !== 'title') {
|
||||
refreshGuest(id, state.browserPageId)
|
||||
}
|
||||
}
|
||||
|
||||
export function issueBrowserGuestNavigation<T>(
|
||||
webview: Electron.WebviewTag,
|
||||
issue: (guest: Electron.WebviewTag) => T
|
||||
): T
|
||||
export function issueBrowserGuestNavigation<T>(
|
||||
webview: Electron.WebviewTag | null | undefined,
|
||||
issue: (guest: Electron.WebviewTag) => T
|
||||
): T | undefined
|
||||
export function issueBrowserGuestNavigation<T>(
|
||||
webview: Electron.WebviewTag | null | undefined,
|
||||
issue: (guest: Electron.WebviewTag) => T
|
||||
): T | undefined {
|
||||
if (!webview) {
|
||||
return undefined
|
||||
}
|
||||
const id = readBrowserGuestId(webview)
|
||||
const result = issue(webview)
|
||||
if (id === null) {
|
||||
return result
|
||||
}
|
||||
const previous = guests.get(id)
|
||||
const receipt = {}
|
||||
const entry: GuestMetadataEntry = { ...previous, applicable: false, presentationRequest: receipt }
|
||||
guests.set(id, entry)
|
||||
observeGuestDeath(id, webview, entry)
|
||||
initialReads.delete(id)
|
||||
if (entry.browserPageId) {
|
||||
refreshGuest(id, entry.browserPageId)
|
||||
}
|
||||
// A rejected command ends its presentation claim, never the native observation or a successor's claim.
|
||||
if (result instanceof Promise) {
|
||||
void result.catch(() => {
|
||||
const current = guests.get(id)
|
||||
if (current?.presentationRequest === receipt) {
|
||||
delete current.presentationRequest
|
||||
}
|
||||
})
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
export function browserGuestPreservesRequestedDocument(
|
||||
webview: Electron.WebviewTag,
|
||||
observedUrl: string,
|
||||
requestedUrl: string
|
||||
): boolean {
|
||||
const id = readBrowserGuestId(webview)
|
||||
if (id === null || !guests.get(id)?.presentationRequest) {
|
||||
return false
|
||||
}
|
||||
const normalized = (url: string): string => {
|
||||
const redacted = redactKagiSessionToken(url)
|
||||
return normalizeBrowserNavigationUrl(redacted) ?? redacted
|
||||
}
|
||||
return normalized(observedUrl) !== normalized(requestedUrl)
|
||||
}
|
||||
|
||||
export function clearBrowserGuestMetadata(): void {
|
||||
snapshots.clear()
|
||||
for (const entry of guests.values()) {
|
||||
entry.stopObserving?.()
|
||||
}
|
||||
guests.clear()
|
||||
initialReads.clear()
|
||||
}
|
||||
|
||||
@@ -36,7 +198,7 @@ export function cachedBrowserGuestMetadata(
|
||||
webview: Electron.WebviewTag
|
||||
): BrowserGuestMetadata | undefined {
|
||||
const id = readBrowserGuestId(webview)
|
||||
return id === null ? undefined : snapshots.get(id)
|
||||
return id === null ? undefined : guests.get(id)?.state
|
||||
}
|
||||
|
||||
export function subscribeBrowserGuestMetadata(
|
||||
@@ -52,10 +214,20 @@ export function subscribeBrowserGuestMetadata(
|
||||
return
|
||||
}
|
||||
const id = readBrowserGuestId(webview)
|
||||
if (id === null || id === guestId) {
|
||||
if (id === null) {
|
||||
return
|
||||
}
|
||||
if (id === guestId) {
|
||||
const entry = guests.get(id)
|
||||
if (!entry?.applicable || !entry.state) {
|
||||
refreshGuest(id, browserPageId)
|
||||
}
|
||||
return
|
||||
}
|
||||
unsubscribe()
|
||||
if (guestId !== null) {
|
||||
retireGuest(guestId)
|
||||
}
|
||||
guestId = id
|
||||
const onState: Listener = (state) => {
|
||||
if (readBrowserGuestId(webview) === id && (!state || state.browserPageId === browserPageId)) {
|
||||
@@ -74,33 +246,15 @@ export function subscribeBrowserGuestMetadata(
|
||||
listeners.delete(id)
|
||||
}
|
||||
}
|
||||
const cached = snapshots.get(id)
|
||||
if (cached) {
|
||||
onState({ ...cached, kind: 'snapshot' })
|
||||
return
|
||||
const entry = guests.get(id) ?? { applicable: true }
|
||||
entry.browserPageId = browserPageId
|
||||
guests.set(id, entry)
|
||||
observeGuestDeath(id, webview, entry)
|
||||
if (entry.applicable && entry.state) {
|
||||
onState({ ...entry.state, kind: 'snapshot' })
|
||||
} else {
|
||||
refreshGuest(id, browserPageId)
|
||||
}
|
||||
if (initialReads.has(id)) {
|
||||
return
|
||||
}
|
||||
const request = window.api.browser
|
||||
.getGuestMetadata({ browserPageId, webContentsId: id })
|
||||
.then((state) => {
|
||||
if (initialReads.get(id) !== request) {
|
||||
return
|
||||
}
|
||||
if (state) {
|
||||
acceptBrowserGuestMetadata(state)
|
||||
} else if (state === null && !snapshots.has(id)) {
|
||||
listeners.get(id)?.forEach((notify) => notify(null))
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
if (initialReads.get(id) === request) {
|
||||
initialReads.delete(id)
|
||||
}
|
||||
})
|
||||
initialReads.set(id, request)
|
||||
}
|
||||
webview.addEventListener('did-attach', bind)
|
||||
webview.addEventListener('dom-ready', bind)
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { issueBrowserGuestNavigation } from './browser-guest-metadata-cache'
|
||||
export const BROWSER_GUEST_RECOVERY_ERROR_CODE = -10_000
|
||||
export const BROWSER_GUEST_RECOVERY_TIMEOUT_MS = 8_000
|
||||
export const BROWSER_GUEST_VALIDATION_RETRY_DELAY_MS = 1_000
|
||||
@@ -142,7 +143,7 @@ export function createBrowserPageGuestRecovery(
|
||||
watchRecovery()
|
||||
try {
|
||||
// Why: reload keeps Chromium history and guest identity while starting a fresh renderer.
|
||||
options.webview.reload()
|
||||
issueBrowserGuestNavigation(options.webview, () => options.webview.reload())
|
||||
} catch {
|
||||
replaceGuest()
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ function nativeState(patch: Partial<BrowserGuestMetadata> = {}): BrowserGuestMet
|
||||
}
|
||||
}
|
||||
|
||||
function mount(state: BrowserGuestMetadata) {
|
||||
function mount(state: BrowserGuestMetadata, initiallyLoading = false) {
|
||||
const ref = <T>(current: T) => ({ current })
|
||||
const first: BrowserPage = {
|
||||
id: 'page-a',
|
||||
@@ -68,7 +68,7 @@ function mount(state: BrowserGuestMetadata) {
|
||||
worktreeId: 'worktree-a',
|
||||
url: 'https://example.test/attempted',
|
||||
title: 'Saved title',
|
||||
loading: false,
|
||||
loading: initiallyLoading,
|
||||
faviconUrl: null,
|
||||
canGoBack: true,
|
||||
canGoForward: false,
|
||||
@@ -160,8 +160,9 @@ function mount(state: BrowserGuestMetadata) {
|
||||
|
||||
describe('mounted browser metadata application', () => {
|
||||
it('keeps the saved title before the first document commits', () => {
|
||||
const view = mount(nativeState({ navigationRevision: 0, url: '', title: '' }))
|
||||
const view = mount(nativeState({ navigationRevision: 0, url: '', title: '', loading: true }))
|
||||
expect(view.page().title).toBe('Saved title')
|
||||
expect(view.page().loading).toBe(true)
|
||||
acceptBrowserGuestMetadata(
|
||||
nativeState({
|
||||
revision: 2,
|
||||
@@ -185,6 +186,24 @@ describe('mounted browser metadata application', () => {
|
||||
)
|
||||
expect(view.page().title).toBe('Saved title')
|
||||
expect(view.page().url).toBe('https://example.test/attempted')
|
||||
expect(view.page().loading).toBe(false)
|
||||
})
|
||||
|
||||
it('adopts a document that predates observation while native loading and saved loading are true', () => {
|
||||
const view = mount(
|
||||
nativeState({
|
||||
navigationRevision: 0,
|
||||
url: 'https://current.test/c',
|
||||
title: 'Current C',
|
||||
loading: true
|
||||
}),
|
||||
true
|
||||
)
|
||||
expect(view.page()).toMatchObject({
|
||||
url: 'https://current.test/c',
|
||||
title: 'Current C',
|
||||
loading: true
|
||||
})
|
||||
})
|
||||
|
||||
it('reattaches a failed destination without replacing its address or clearing its certificate challenge', () => {
|
||||
|
||||
+2
-2
@@ -69,7 +69,7 @@ export function createBrowserPageWebviewLoadingHandlers({
|
||||
if (!metadata) {
|
||||
return null
|
||||
}
|
||||
const currentUrl = metadata.url || 'about:blank'
|
||||
const currentUrl = metadata.url
|
||||
const browserModelUrl = redactKagiSessionToken(currentUrl)
|
||||
const activeLoadFailure = metadata.loadError ?? activeLoadFailureRef.current
|
||||
if (metadata.loadError) {
|
||||
@@ -97,7 +97,7 @@ export function createBrowserPageWebviewLoadingHandlers({
|
||||
activeLoadFailureRef.current = failure
|
||||
return { loading: false, loadError: failure }
|
||||
}
|
||||
if (metadata.navigationRevision === 0) {
|
||||
if (!metadata.url) {
|
||||
return { loading: false }
|
||||
}
|
||||
if (activeLoadFailure?.code === BROWSER_GUEST_RECOVERY_ERROR_CODE) {
|
||||
|
||||
+5
-4
@@ -1,3 +1,4 @@
|
||||
import { issueBrowserGuestNavigation } from './browser-guest-metadata-cache'
|
||||
import { useEffect, type MutableRefObject } from 'react'
|
||||
import { getShortcutPlatform } from '@/hooks/useShortcutLabel'
|
||||
import { useAppStore } from '@/store'
|
||||
@@ -56,9 +57,9 @@ export function useBrowserPageWebviewShortcuts({
|
||||
// Why: stop other window capture listeners (workspace, embedded editors) from also acting.
|
||||
e.stopImmediatePropagation()
|
||||
if (direction === 'back') {
|
||||
webviewRef.current?.goBack()
|
||||
issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goBack())
|
||||
} else {
|
||||
webviewRef.current?.goForward()
|
||||
issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goForward())
|
||||
}
|
||||
}
|
||||
addAppKeyListener('keydown', handleKeyDown)
|
||||
@@ -74,9 +75,9 @@ export function useBrowserPageWebviewShortcuts({
|
||||
return
|
||||
}
|
||||
if (direction === 'back') {
|
||||
webviewRef.current?.goBack()
|
||||
issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goBack())
|
||||
} else {
|
||||
webviewRef.current?.goForward()
|
||||
issueBrowserGuestNavigation(webviewRef.current, (webview) => webview.goForward())
|
||||
}
|
||||
})
|
||||
}, [browserTabId, isActive, webviewRef])
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { issueBrowserGuestNavigation } from '../host-guest/browser-guest-metadata-cache'
|
||||
import { BROWSER_GUEST_RECOVERY_ERROR_CODE } from '../host-guest/browser-page-guest-recovery'
|
||||
|
||||
export type BrowserReloadTrigger = 'button' | 'reload' | 'hard-reload'
|
||||
@@ -44,9 +45,9 @@ export function reloadBrowserPageWebview(
|
||||
}
|
||||
try {
|
||||
if (ignoreCache) {
|
||||
webview.reloadIgnoringCache()
|
||||
issueBrowserGuestNavigation(webview, () => webview.reloadIgnoringCache())
|
||||
} else {
|
||||
webview.reload()
|
||||
issueBrowserGuestNavigation(webview, () => webview.reload())
|
||||
}
|
||||
} catch {
|
||||
try {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { issueBrowserGuestNavigation } from '../host-guest/browser-guest-metadata-cache'
|
||||
import { detectLanguage } from '../../../../../shared/editor-language/editor-language-detect'
|
||||
import { getConnectionId } from '@/lib/workspace/ownership/connection-context'
|
||||
import {
|
||||
@@ -82,7 +83,9 @@ export function navigateBrowserPageToUrl({
|
||||
recoveryNavigationValidationRef.current = recoveryLoadError
|
||||
? { committed: false, started: false, targetUrl: normalizedBrowserModelUrl }
|
||||
: null
|
||||
webview.src = targetUrl
|
||||
issueBrowserGuestNavigation(webview, () => {
|
||||
webview.src = targetUrl
|
||||
})
|
||||
if (targetUrl !== ORCA_BROWSER_BLANK_URL) {
|
||||
focusWebviewNow()
|
||||
}
|
||||
|
||||
+7
-2
@@ -1,4 +1,7 @@
|
||||
import { cachedBrowserGuestMetadata } from '../host-guest/browser-guest-metadata-cache'
|
||||
import {
|
||||
issueBrowserGuestNavigation,
|
||||
cachedBrowserGuestMetadata
|
||||
} from '../host-guest/browser-guest-metadata-cache'
|
||||
import { useEffect, useLayoutEffect, type MutableRefObject, type RefObject } from 'react'
|
||||
import { normalizeBrowserNavigationUrl } from '../../../../../shared/browser-url'
|
||||
import '../../../../../shared/constants'
|
||||
@@ -78,7 +81,9 @@ export function useBrowserPageWebviewUrlSync({
|
||||
declaredSrc !== normalizedUrl
|
||||
) {
|
||||
lastKnownWebviewUrlRef.current = normalizedUrl
|
||||
webview.src = normalizedUrl
|
||||
issueBrowserGuestNavigation(webview, () => {
|
||||
webview.src = normalizedUrl
|
||||
})
|
||||
if (normalizedUrl !== ORCA_BROWSER_BLANK_URL) {
|
||||
keepAddressBarFocusRef.current = false
|
||||
if (document.activeElement === addressBarInputRef.current) {
|
||||
|
||||
+14
-10
@@ -1,3 +1,4 @@
|
||||
import { issueBrowserGuestNavigation } from '../host-guest/browser-guest-metadata-cache'
|
||||
import { useCallback } from 'react'
|
||||
import type { MutableRefObject, RefObject } from 'react'
|
||||
import { redactKagiSessionToken } from '../../../../../shared/browser-url'
|
||||
@@ -6,7 +7,7 @@ import { resolveBrowserAddressBarSubmission } from './browser-address-bar-naviga
|
||||
import { routeWorkspaceDocAddressSubmission } from './workspace-doc-address-submission'
|
||||
import { deferBrowserPageNavigation } from './browser-page-deferred-navigation'
|
||||
import { getBrowserDisplayTitle, toDisplayUrl } from '../describe-page/browser-page-url-display'
|
||||
import type { BrowserTabPageState } from '../describe-page/browser-page-types'
|
||||
import type { BrowserPageUrlSetter, BrowserTabPageState } from '../describe-page/browser-page-types'
|
||||
|
||||
/** Resolve workspace documents before URLs; refuse local file: access and defer navigation until a staged guest attaches. */
|
||||
export function useClientHostedPageUrlSubmission(params: {
|
||||
@@ -14,6 +15,7 @@ export function useClientHostedPageUrlSubmission(params: {
|
||||
worktreeId: string
|
||||
webviewRef: RefObject<Electron.WebviewTag | null>
|
||||
activeLoadFailureRef: MutableRefObject<BrowserLoadError | null>
|
||||
onSetUrl: BrowserPageUrlSetter
|
||||
onUpdatePageState: (pageId: string, updates: Partial<BrowserTabPageState>) => void
|
||||
setAddressBarValue: (value: string) => void
|
||||
}): (value: string) => void {
|
||||
@@ -22,6 +24,7 @@ export function useClientHostedPageUrlSubmission(params: {
|
||||
worktreeId,
|
||||
webviewRef,
|
||||
activeLoadFailureRef,
|
||||
onSetUrl,
|
||||
onUpdatePageState,
|
||||
setAddressBarValue
|
||||
} = params
|
||||
@@ -41,29 +44,30 @@ export function useClientHostedPageUrlSubmission(params: {
|
||||
onUpdatePageState(browserTabId, { loadError: submission.loadError })
|
||||
return
|
||||
}
|
||||
const webview = webviewRef.current
|
||||
if (!webview) {
|
||||
// Park staged navigation for attachment rather than dropping typed input.
|
||||
deferBrowserPageNavigation(browserTabId, submission.url)
|
||||
setAddressBarValue(toDisplayUrl(redactKagiSessionToken(submission.url)))
|
||||
return
|
||||
}
|
||||
// Never persist Kagi session tokens; match local panes’ optimistic title until the guest reports one.
|
||||
const browserModelUrl = redactKagiSessionToken(submission.url)
|
||||
activeLoadFailureRef.current = null
|
||||
setAddressBarValue(toDisplayUrl(browserModelUrl))
|
||||
onSetUrl(browserTabId, browserModelUrl)
|
||||
onUpdatePageState(browserTabId, {
|
||||
loading: true,
|
||||
loadError: null,
|
||||
title: getBrowserDisplayTitle(browserModelUrl, browserModelUrl)
|
||||
})
|
||||
const webview = webviewRef.current
|
||||
if (!webview) {
|
||||
deferBrowserPageNavigation(browserTabId, submission.url)
|
||||
return
|
||||
}
|
||||
// Why: loadURL rejects on any failed navigation; did-fail-load owns error reporting.
|
||||
void webview.loadURL(submission.url).catch(() => {})
|
||||
void issueBrowserGuestNavigation(webview, () => webview.loadURL(submission.url)).catch(
|
||||
() => {}
|
||||
)
|
||||
},
|
||||
[
|
||||
activeLoadFailureRef,
|
||||
browserTabId,
|
||||
onUpdatePageState,
|
||||
onSetUrl,
|
||||
setAddressBarValue,
|
||||
webviewRef,
|
||||
worktreeId
|
||||
|
||||
+1
-1
@@ -208,7 +208,7 @@ export function RemoteBrowserPageViewport({
|
||||
<ReopenBrowserPageOnServerButton
|
||||
environmentId={remotePageHandle.environmentId}
|
||||
worktreeId={worktreeId}
|
||||
lastCommittedUrl={browserTab.url}
|
||||
reopenUrl={browserTab.url}
|
||||
className="h-6 shrink-0 px-2 text-xs"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
Reference in New Issue
Block a user