Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(desktop-app): make the embedded app session survive idle, sleep and transient mint failures

Diego Zacariasb5d174055a3c
diff --git a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts
index 4db384b73..4e801c75a 100644
--- a/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts
+++ b/desktop-app/src/__tests__/appService.sandboxUiLifecycle.test.ts
@@ -11,6 +11,7 @@ import { _resetPluginSurfacesForTests, resolvePluginSurface } from '../pluginSur
import { SANDBOX_UI_MINT_TIMEOUT_MS } from '../rpcProxyClient.js'
import { getActiveSandboxUi, unmountSandboxUiView } from '../sandboxUiDriver.js'
import {
+ SANDBOX_UI_RATE_LIMIT_MS,
SANDBOX_UI_REFRESH_INTERVAL_MS,
_resetSandboxUiRefreshForTests,
} from '../sandboxUiSessionRefresh.js'
@@ -39,6 +40,7 @@ const electronMocks = vi.hoisted(() => {
findInPage = vi.fn(() => 41)
focus = vi.fn()
send = vi.fn()
+ reloadIgnoringCache = vi.fn()
on(event: string, handler: (...args: unknown[]) => void): this {
if (!this.listeners.has(event)) this.listeners.set(event, new Set())
@@ -202,6 +204,10 @@ class FakeParentWindow {
this.listeners.get(event)?.delete(handler)
return this
}
+
+ emit(event: string): void {
+ this.listeners.get(event)?.forEach(handler => handler())
+ }
}
// rpc-proxy's mint contract: 204 + a Path-scoped Set-Cookie on success, any
@@ -475,22 +481,90 @@ describe('AppService sandbox-ui mint against a hung rpc-proxy', () => {
expect(getActiveSandboxUi()).toBeNull()
})
- it('a refresh whose mint hangs stops and reports the error', async () => {
+ it('a refresh whose mint hangs is retried instead of abandoned', async () => {
const onRefreshError = vi.fn()
const service = makeService()
initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })
const parentWindow = new FakeParentWindow()
await service.openSandboxUi({ ...openArgs('first-app', parentWindow), onRefreshError })
- shrinkMintBound()
+ const embed = getActiveSandboxUi()!
+ // The mint bound fires when the test says so, not on the runtime's real
+ // clock, so the retry timing stays on the fake timers alone.
+ const mintBounds: AbortController[] = []
+ const realTimeout = AbortSignal.timeout.bind(AbortSignal)
+ vi.spyOn(AbortSignal, 'timeout').mockImplementation(ms => {
+ if (ms !== SANDBOX_UI_MINT_TIMEOUT_MS) return realTimeout(ms)
+ const bound = new AbortController()
+ mintBounds.push(bound)
+ return bound.signal
+ })
mintResponders.set('first-app', mintHangs)
await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)
+ expect(mintCallsFor('first-app')).toBe(2)
+ mintBounds.at(-1)!.abort(new DOMException('mint timed out', 'TimeoutError'))
+ await vi.advanceTimersByTimeAsync(2_000)
+ expect(mintCallsFor('first-app')).toBe(3)
+ expect(onRefreshError).not.toHaveBeenCalled()
+ expect(getActiveSandboxUi()?.webContentsId).toBe(embed.webContentsId)
+ expect(resolvePluginSurface(embed.webContentsId)?.pluginId).toBe('sandbox-recipes/first-app')
+ })
+})
- await vi.waitFor(() => expect(onRefreshError).toHaveBeenCalledOnce(), { timeout: 1_000 })
- // Stopped: a further interval issues no mint.
- const mintsBefore = mintCallsFor('first-app')
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1_000)
- expect(mintCallsFor('first-app')).toBe(mintsBefore)
+describe('AppService sandbox-ui session against a failing rpc-proxy', () => {
+ it('retries, reports only once the cookie is past its grace period, and resumes on an embed request', async () => {
+ // The retry deadline is wall-clock, so here the wall clock moves with the timers.
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
+ const onRefreshError = vi.fn()
+ const service = makeService()
+ initPluginSdkRuntime({ service, getMainWindow: () => null, userDataDir })
+ const parentWindow = new FakeParentWindow()
+ await service.openSandboxUi({ ...openArgs('first-app', parentWindow), onRefreshError })
+ const embed = getActiveSandboxUi()!
+ mintResponders.set('first-app', () => mintFails(503, 'upstream unavailable'))
+
+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ await vi.advanceTimersByTimeAsync(1_000)
+ expect(mintCallsFor('first-app')).toBe(3)
+ expect(onRefreshError).not.toHaveBeenCalled()
+
+ await vi.advanceTimersByTimeAsync(120_000)
+ expect(onRefreshError).toHaveBeenCalledOnce()
+ expect(onRefreshError.mock.calls[0]![0]).toContain('503')
+ const mintsWhenExhausted = mintCallsFor('first-app')
+ await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS)
+ expect(mintCallsFor('first-app')).toBe(mintsWhenExhausted)
+ // The view and its pins survive the error.
+ expect(getActiveSandboxUi()?.webContentsId).toBe(embed.webContentsId)
+ expect(resolvePluginSurface(embed.webContentsId)?.pluginId).toBe('sandbox-recipes/first-app')
+
+ mintResponders.delete('first-app')
+ electronMocks.sessionObject.cookies.set.mockClear()
+ await service.requestSandboxUiRefresh(embed.webContentsId)
+ expect(mintCallsFor('first-app')).toBe(mintsWhenExhausted + 1)
+ expect(electronMocks.sessionObject.cookies.set).toHaveBeenCalledWith(
+ expect.objectContaining({ value: 'tok-first-app' })
+ )
+ })
+})
+
+describe('AppService sandbox-ui embed whose document comes back 401', () => {
+ it('re-mints through rpc-proxy and reloads the embed once per mint', async () => {
+ const { firstView } = await setupWithLiveFirstApp()
+ const webContents = firstView!.webContents
+ const appUrl = 'https://rpc.example/api/v1/sandbox-ui/sandbox-recipes/first-app/view/'
+
+ webContents.emit('did-navigate', {}, appUrl, 401, 'Unauthorized')
+ await vi.waitFor(() => expect(webContents.reloadIgnoringCache).toHaveBeenCalledOnce(), {
+ timeout: 1_000,
+ })
+ expect(mintCallsFor('first-app')).toBe(2)
+
+ // The reload 401s again under the recovery cookie: no second round.
+ webContents.emit('did-navigate', {}, appUrl, 401, 'Unauthorized')
+ await vi.advanceTimersByTimeAsync(0)
+ expect(mintCallsFor('first-app')).toBe(2)
+ expect(webContents.reloadIgnoringCache).toHaveBeenCalledOnce()
})
})
diff --git a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
index 59932aea6..982ed9a24 100644
--- a/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiDriverLifecycle.test.ts
@@ -343,6 +343,33 @@ describe('mountSandboxUiView lifecycle cleanup', () => {
})
})
+ it('reports a 401 document navigation inside the app prefix, for as long as the view lives', async () => {
+ const parentWindow = new FakeParentWindow()
+ const onUnauthorizedNavigation = vi.fn()
+ await mountSandboxUiView(mountArgs({ parentWindow, onUnauthorizedNavigation }))
+ const webContents = electronMocks.views[0]!.webContents
+ const inPrefix = 'https://rpc.example/api/v1/sandbox-ui/sandbox-recipes/task-board/view/'
+
+ webContents.emit('did-navigate', {} as Electron.Event, inPrefix, 200, 'OK')
+ webContents.emit('did-navigate', {} as Electron.Event, 'https://elsewhere.example/', 401, '')
+ webContents.emit(
+ 'did-navigate',
+ {} as Electron.Event,
+ 'https://rpc.example/api/v1/sandbox-ui/sandbox-recipes/other-app/view/',
+ 401,
+ ''
+ )
+ expect(onUnauthorizedNavigation).not.toHaveBeenCalled()
+
+ webContents.emit('did-navigate', {} as Electron.Event, `${inPrefix}inbox`, 401, 'Unauthorized')
+ webContents.emit('did-navigate', {} as Electron.Event, `${inPrefix}inbox`, 401, 'Unauthorized')
+ expect(onUnauthorizedNavigation).toHaveBeenCalledTimes(2)
+ expect(onUnauthorizedNavigation).toHaveBeenCalledWith(webContents.id)
+
+ await unmountSandboxUiView()
+ expect(webContents.listenerCount('did-navigate')).toBe(0)
+ })
+
it('keeps the current document searchable after same-document navigation', async () => {
const parentWindow = new FakeParentWindow()
await mountSandboxUiView(mountArgs({ parentWindow }))
diff --git a/desktop-app/src/__tests__/sandboxUiSessionRefresh.test.ts b/desktop-app/src/__tests__/sandboxUiSessionRefresh.test.ts
index 8f662e90e..30ef86e3b 100644
--- a/desktop-app/src/__tests__/sandboxUiSessionRefresh.test.ts
+++ b/desktop-app/src/__tests__/sandboxUiSessionRefresh.test.ts
@@ -1,11 +1,14 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
+ SANDBOX_UI_COOKIE_TTL_MS,
SANDBOX_UI_RATE_LIMIT_MS,
SANDBOX_UI_REFRESH_INTERVAL_MS,
_isPinnedForTests,
_resetSandboxUiRefreshForTests,
cancelSandboxUiRefresh,
handleEmbedRefreshRequest,
+ handleSandboxUiUnauthorizedNavigation,
+ notifySandboxUiHostResumed,
startSandboxUiRefresh,
} from '../sandboxUiSessionRefresh.js'
import type {
@@ -47,8 +50,33 @@ class FakeBrowserWindow {
}
}
+// Two independent clocks: the wall clock the module reads through `now()`, and
+// the fake timers that drive `setTimeout`. Awake, the wall clock follows the
+// timer clock (`advance`, firing each timer at its own instant); asleep, only
+// the wall clock moves (`sleep`) — the case a timer-only design gets wrong.
+// `performance` is faked only so the test can read the timer clock; the module
+// never touches it, and Date stays real.
+let sleptMs = 0
+const wallNow = (): number => 1_800_000_000_000 + performance.now() + sleptMs
+
+async function advance(ms: number): Promise<void> {
+ await vi.advanceTimersByTimeAsync(ms)
+}
+
+function sleep(ms: number): void {
+ sleptMs += ms
+}
+
+/** Lets already-started promise chains (mint → install → reschedule) settle. */
+async function flush(): Promise<void> {
+ await vi.advanceTimersByTimeAsync(0)
+}
+
beforeEach(() => {
- vi.useFakeTimers()
+ // Date is deliberately left real: the module must take its wall clock from
+ // the injected `now()`, never from whatever the timer clock says.
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'performance'] })
+ sleptMs = 0
_resetSandboxUiRefreshForTests()
})
@@ -62,6 +90,7 @@ function makeArgs(
refresh?: SandboxUiRefreshFn
installCookie?: SandboxUiInstallCookieFn
onError?: (error: Error) => void
+ reload?: () => void
parentWindow?: FakeBrowserWindow
webContentsId?: number
} = {}
@@ -83,9 +112,15 @@ function makeArgs(
installCookie:
overrides.installCookie ?? vi.fn<SandboxUiInstallCookieFn>(async () => undefined),
onError: overrides.onError ?? vi.fn(),
+ reload: overrides.reload ?? vi.fn(),
+ now: wallNow,
}
}
+const mintOk = (): Promise<{ setCookie: string }> =>
+ Promise.resolve({ setCookie: 'clerum_sandbox_ui_session=X' })
+const mintDown = (): Promise<never> => Promise.reject(new Error('control-api 503'))
+
describe('startSandboxUiRefresh', () => {
it('pins the sender and arms the visibility-driven timer', () => {
const args = makeArgs()
@@ -110,7 +145,7 @@ describe('startSandboxUiRefresh', () => {
}))
const args = makeArgs({ parentWindow: window, refresh })
startSandboxUiRefresh(args)
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1000)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1000)
expect(refresh).not.toHaveBeenCalled()
})
})
@@ -124,57 +159,41 @@ describe('refresh timer', () => {
const args = makeArgs({ refresh, installCookie })
startSandboxUiRefresh(args)
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS - 1)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS - 1)
expect(refresh).not.toHaveBeenCalled()
- await vi.advanceTimersByTimeAsync(2)
+ await advance(2)
expect(refresh).toHaveBeenCalledTimes(1)
expect(installCookie).toHaveBeenCalledWith('clerum_sandbox_ui_session=X')
// After the first refresh, the next tick is 270 s later.
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS)
expect(refresh).toHaveBeenCalledTimes(2)
})
- it('cancels the timer and surfaces the error when refresh throws', async () => {
- const refresh = vi.fn<SandboxUiRefreshFn>(async () => {
- throw new Error('rpc-proxy 410: recipe deleted')
- })
- const onError = vi.fn()
- const args = makeArgs({ refresh, onError })
- startSandboxUiRefresh(args)
-
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
- expect(refresh).toHaveBeenCalledTimes(1)
- expect(onError).toHaveBeenCalledTimes(1)
- expect(onError.mock.calls[0]![0].message).toContain('410')
-
- // After error: no further refresh fires, even after another full interval.
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS * 2)
- expect(refresh).toHaveBeenCalledTimes(1)
- })
-
- it('cancels on hide and reschedules on show', async () => {
+ it('cancels on hide and refreshes at once on a restore after the cookie expired', async () => {
const window = new FakeBrowserWindow()
- const refresh = vi.fn<SandboxUiRefreshFn>(async () => ({
- setCookie: 'clerum_sandbox_ui_session=X',
- }))
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintOk)
const args = makeArgs({ parentWindow: window, refresh })
startSandboxUiRefresh(args)
// Halfway to the next refresh, the user minimizes — timer should be
// cleared and no refresh should fire even if we wait the full interval.
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS / 2)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS / 2)
window.minimized = true
window.emit('minimize')
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS * 2)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS * 2)
expect(refresh).not.toHaveBeenCalled()
- // Restoring re-arms the timer; full interval should produce one refresh.
+ // The cookie died while minimized: restoring re-mints immediately.
window.minimized = false
window.emit('restore')
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(1)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS - 1)
expect(refresh).toHaveBeenCalledTimes(1)
+ await advance(2)
+ expect(refresh).toHaveBeenCalledTimes(2)
})
})
@@ -195,6 +214,30 @@ describe('cancelSandboxUiRefresh', () => {
expect(window.listenerCount('show')).toBe(0)
expect(window.listenerCount('minimize')).toBe(0)
expect(window.listenerCount('restore')).toBe(0)
+ expect(window.listenerCount('focus')).toBe(0)
+ })
+
+ it('stays terminal: no retry, return, embed request or 401 revives a cancelled loop', async () => {
+ const window = new FakeBrowserWindow()
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
+ const reload = vi.fn()
+ const args = makeArgs({ parentWindow: window, refresh, reload })
+ startSandboxUiRefresh(args)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ expect(refresh).toHaveBeenCalledTimes(1)
+
+ // Cancelled mid-backoff, with a retry already scheduled.
+ cancelSandboxUiRefresh()
+ sleep(SANDBOX_UI_COOKIE_TTL_MS)
+ window.emit('show')
+ notifySandboxUiHostResumed()
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await expect(handleEmbedRefreshRequest(args.webContentsId)).rejects.toThrow(/unpinned sender/)
+ await advance(SANDBOX_UI_COOKIE_TTL_MS * 2)
+
+ expect(refresh).toHaveBeenCalledTimes(1)
+ expect(reload).not.toHaveBeenCalled()
+ expect(_isPinnedForTests(args.webContentsId)).toBe(false)
})
})
@@ -219,22 +262,398 @@ describe('handleEmbedRefreshRequest (Decision 11 — IPC pinning)', () => {
startSandboxUiRefresh(args)
// Advance past the rate limit but well before the scheduled timer.
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_RATE_LIMIT_MS + 100)
+ await advance(SANDBOX_UI_RATE_LIMIT_MS + 100)
await handleEmbedRefreshRequest(args.webContentsId)
expect(refresh).toHaveBeenCalledTimes(1)
expect(installCookie).toHaveBeenCalledWith('clerum_sandbox_ui_session=NEW')
})
- it('rejects IPC refresh after a fatal error has stopped the driver', async () => {
- const refresh = vi.fn<SandboxUiRefreshFn>(async () => {
- throw new Error('rpc-proxy 403: ACL revoked')
- })
+ it('counts an accepted request against the rate limit even when its mint fails', async () => {
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
const args = makeArgs({ refresh })
startSandboxUiRefresh(args)
+ await advance(SANDBOX_UI_RATE_LIMIT_MS + 100)
- await vi.advanceTimersByTimeAsync(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
- // Driver is now stopped; the sender is also unpinned.
- await expect(handleEmbedRefreshRequest(args.webContentsId)).rejects.toThrow(/unpinned sender/)
+ await handleEmbedRefreshRequest(args.webContentsId)
+ expect(refresh).toHaveBeenCalledTimes(1)
+ await expect(handleEmbedRefreshRequest(args.webContentsId)).rejects.toThrow(/rate-limited/)
+ // The first request's mint failed, yet the second is still rate-limited and mints nothing.
+ expect(refresh).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('session expiry by wall clock', () => {
+ it('a show after the cookie expired while the timers were frozen refreshes at once', async () => {
+ const window = new FakeBrowserWindow()
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintOk)
+ startSandboxUiRefresh(makeArgs({ parentWindow: window, refresh }))
+
+ // Machine asleep for 10 min: the wall clock moves, the timer does not.
+ sleep(10 * 60 * 1000)
+ window.emit('show')
+ await flush()
+
+ expect(refresh).toHaveBeenCalledTimes(1)
+ })
+
+ it('a host resume after the cookie expired while asleep refreshes at once', async () => {
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintOk)
+ startSandboxUiRefresh(makeArgs({ refresh }))
+
+ sleep(10 * 60 * 1000)
+ notifySandboxUiHostResumed()
+ await flush()
+
+ expect(refresh).toHaveBeenCalledTimes(1)
+ })
+
+ it('a restore before expiry re-arms the timer to the remaining time, not a full interval', async () => {
+ const window = new FakeBrowserWindow()
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintOk)
+ startSandboxUiRefresh(makeArgs({ parentWindow: window, refresh }))
+
+ await advance(100_000)
+ window.minimized = true
+ window.emit('minimize')
+ await advance(50_000)
+ window.minimized = false
+ window.emit('restore')
+ await flush()
+ expect(refresh).not.toHaveBeenCalled()
+
+ const remaining = SANDBOX_UI_REFRESH_INTERVAL_MS - 150_000
+ await advance(remaining - 1)
+ expect(refresh).not.toHaveBeenCalled()
+ await advance(2)
+ expect(refresh).toHaveBeenCalledTimes(1)
+ })
+
+ it('a focus after the timer clock lagged behind the wall clock re-arms to the wall-clock remainder', async () => {
+ const window = new FakeBrowserWindow()
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintOk)
+ startSandboxUiRefresh(makeArgs({ parentWindow: window, refresh }))
+
+ await advance(100_000)
+ sleep(100_000)
+ window.emit('focus')
+ await flush()
+ expect(refresh).not.toHaveBeenCalled()
+
+ // 70 s of wall time remain; the timer armed at mount still had 170 s.
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS - 200_000 + 1)
+ expect(refresh).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('mint failure backoff', () => {
+ it('retries a failed mint instead of stopping, keeping the sender pinned', async () => {
+ const refresh = vi
+ .fn<SandboxUiRefreshFn>()
+ .mockImplementationOnce(mintDown)
+ .mockImplementationOnce(mintDown)
+ .mockImplementation(mintOk)
+ const installCookie = vi.fn<SandboxUiInstallCookieFn>(async () => undefined)
+ const onError = vi.fn()
+ const args = makeArgs({ refresh, installCookie, onError })
+ startSandboxUiRefresh(args)
+
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ expect(refresh).toHaveBeenCalledTimes(1)
+ expect(_isPinnedForTests(args.webContentsId)).toBe(true)
+
+ await advance(1_000)
+ expect(refresh).toHaveBeenCalledTimes(2)
+ await advance(2_000)
+ expect(refresh).toHaveBeenCalledTimes(3)
+ expect(installCookie).toHaveBeenCalledWith('clerum_sandbox_ui_session=X')
+ expect(onError).not.toHaveBeenCalled()
+
+ // Back on the regular schedule, counted from the mint that succeeded
+ // (requested 1 ms before the clock now reads).
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS - 2)
+ expect(refresh).toHaveBeenCalledTimes(3)
+ await advance(2)
+ expect(refresh).toHaveBeenCalledTimes(4)
+ })
+
+ it('reports once the cookie has been dead for the grace period, and stays pinned', async () => {
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
+ const onError = vi.fn()
+ const args = makeArgs({ refresh, onError })
+ startSandboxUiRefresh(args)
+
+ // First failure at 270 s; the cookie expires at 300 s, retries continue
+ // to 360 s: attempts at 271, 273, 278, 293, 323, 353 — the next (383)
+ // would land past the deadline.
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ await advance(100_000)
+ expect(refresh).toHaveBeenCalledTimes(7)
+ expect(onError).toHaveBeenCalledTimes(1)
+ expect(onError.mock.calls[0]![0].message).toContain('503')
+ expect(_isPinnedForTests(args.webContentsId)).toBe(true)
+
+ await advance(SANDBOX_UI_COOKIE_TTL_MS * 2)
+ expect(refresh).toHaveBeenCalledTimes(7)
+ })
+
+ it('gives a mint that fails right after waking a full retry window', async () => {
+ const window = new FakeBrowserWindow()
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
+ const onError = vi.fn()
+ startSandboxUiRefresh(makeArgs({ parentWindow: window, refresh, onError }))
+
+ sleep(60 * 60 * 1000)
+ window.emit('show')
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(1)
+ expect(onError).not.toHaveBeenCalled()
+
+ await advance(1_000)
+ expect(refresh).toHaveBeenCalledTimes(2)
+ })
+
+ it('an embed request after the retries ran out resumes the loop', async () => {
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
+ const installCookie = vi.fn<SandboxUiInstallCookieFn>(async () => undefined)
+ const onError = vi.fn()
+ const args = makeArgs({ refresh, installCookie, onError })
+ startSandboxUiRefresh(args)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ await advance(100_000)
+ expect(onError).toHaveBeenCalledTimes(1)
+ const callsWhenExhausted = refresh.mock.calls.length
+
+ refresh.mockImplementation(mintOk)
+ await handleEmbedRefreshRequest(args.webContentsId)
+ expect(refresh).toHaveBeenCalledTimes(callsWhenExhausted + 1)
+ expect(installCookie).toHaveBeenCalledWith('clerum_sandbox_ui_session=X')
+ // The 30 s rate limit still applies to the resumed loop.
+ await expect(handleEmbedRefreshRequest(args.webContentsId)).rejects.toThrow(/rate-limited/)
+
+ // And the timer is back.
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ expect(refresh).toHaveBeenCalledTimes(callsWhenExhausted + 2)
+ })
+})
+
+describe('top-level 401 recovery', () => {
+ it('re-mints and reloads exactly once per mint', async () => {
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintOk)
+ const installCookie = vi.fn<SandboxUiInstallCookieFn>(async () => undefined)
+ const reload = vi.fn()
+ const args = makeArgs({ refresh, installCookie, reload })
+ startSandboxUiRefresh(args)
+
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(1)
+ expect(installCookie).toHaveBeenCalledTimes(1)
+ expect(reload).toHaveBeenCalledTimes(1)
+
+ // The reload under the recovery mint 401s again: no loop.
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(1)
+ expect(reload).toHaveBeenCalledTimes(1)
+
+ // A later scheduled mint earns a fresh recovery.
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ expect(refresh).toHaveBeenCalledTimes(2)
+ expect(reload).toHaveBeenCalledTimes(1)
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(3)
+ expect(reload).toHaveBeenCalledTimes(2)
+ })
+
+ it('reloads only once the recovery mint succeeds, after backoff', async () => {
+ const refresh = vi
+ .fn<SandboxUiRefreshFn>()
+ .mockImplementationOnce(mintDown)
+ .mockImplementation(mintOk)
+ const reload = vi.fn()
+ const args = makeArgs({ refresh, reload })
+ startSandboxUiRefresh(args)
+
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(1)
+ expect(reload).not.toHaveBeenCalled()
+ // Further 401s while the recovery is pending add no mints.
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(1)
+
+ await advance(1_000)
+ expect(refresh).toHaveBeenCalledTimes(2)
+ expect(reload).toHaveBeenCalledTimes(1)
+ })
+
+ it('ignores a 401 from a webContents that is not the pinned embed', async () => {
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintOk)
+ const reload = vi.fn()
+ startSandboxUiRefresh(makeArgs({ refresh, reload, webContentsId: 42 }))
+
+ handleSandboxUiUnauthorizedNavigation(7)
+ await flush()
+
+ expect(refresh).not.toHaveBeenCalled()
+ expect(reload).not.toHaveBeenCalled()
+ })
+})
+
+describe('recovery after retries ran out or went stale', () => {
+ it('a 401 after its recovery mint exhausted its retries reopens them and reloads on success', async () => {
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
+ const reload = vi.fn()
+ const onError = vi.fn()
+ const args = makeArgs({ refresh, reload, onError })
+ startSandboxUiRefresh(args)
+
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await advance(400_000)
+ expect(onError).toHaveBeenCalledTimes(1)
+ const callsWhenExhausted = refresh.mock.calls.length
+
+ // rpc-proxy is back; the user reloads and the page 401s again.
+ refresh.mockImplementation(mintOk)
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await flush()
+
+ expect(refresh).toHaveBeenCalledTimes(callsWhenExhausted + 1)
+ expect(reload).toHaveBeenCalledTimes(1)
+ })
+
+ it('a restore after sleeping through a failure gets a fresh retry window instead of reporting', async () => {
+ const window = new FakeBrowserWindow()
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
+ const onError = vi.fn()
+ startSandboxUiRefresh(makeArgs({ parentWindow: window, refresh, onError }))
+
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ expect(refresh).toHaveBeenCalledTimes(1)
+ window.minimized = true
+ window.emit('minimize')
+ sleep(10 * 60 * 1000)
+ window.minimized = false
+ window.emit('restore')
+ await flush()
+
+ expect(refresh).toHaveBeenCalledTimes(2)
+ expect(onError).not.toHaveBeenCalled()
+ await advance(1_000)
+ expect(refresh).toHaveBeenCalledTimes(3)
+ expect(onError).not.toHaveBeenCalled()
+ })
+
+ it('a host resume after the retries ran out re-mints the session', async () => {
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
+ const installCookie = vi.fn<SandboxUiInstallCookieFn>(async () => undefined)
+ const onError = vi.fn()
+ startSandboxUiRefresh(makeArgs({ refresh, installCookie, onError }))
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ await advance(100_000)
+ expect(onError).toHaveBeenCalledTimes(1)
+ const callsWhenExhausted = refresh.mock.calls.length
+
+ // The machine sleeps; it wakes with a healthy network.
+ sleep(10 * 60 * 1000)
+ refresh.mockImplementation(mintOk)
+ notifySandboxUiHostResumed()
+ await flush()
+
+ expect(refresh).toHaveBeenCalledTimes(callsWhenExhausted + 1)
+ expect(installCookie).toHaveBeenCalledWith('clerum_sandbox_ui_session=X')
+ })
+
+ it('a focus burst on an exhausted loop resumes it once per rate-limit window', async () => {
+ const window = new FakeBrowserWindow()
+ const refresh = vi.fn<SandboxUiRefreshFn>(mintDown)
+ startSandboxUiRefresh(makeArgs({ parentWindow: window, refresh }))
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ await advance(100_000)
+ const callsWhenExhausted = refresh.mock.calls.length
+
+ for (let i = 0; i < 5; i += 1) window.emit('focus')
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(callsWhenExhausted + 1)
+
+ // Once that resumed episode runs out too, the next burst (well past the
+ // window) resumes once more — and only once.
+ await advance(120_000)
+ const callsWhenExhaustedAgain = refresh.mock.calls.length
+ for (let i = 0; i < 5; i += 1) window.emit('focus')
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(callsWhenExhaustedAgain + 1)
+ })
+})
+
+describe('concurrent triggers share one mint', () => {
+ function heldMint(): { refresh: ReturnType<typeof vi.fn<SandboxUiRefreshFn>>; land: () => void } {
+ let land: () => void = () => undefined
+ const refresh = vi.fn<SandboxUiRefreshFn>(
+ () =>
+ new Promise(resolve => {
+ land = () => resolve({ setCookie: 'clerum_sandbox_ui_session=X' })
+ })
+ )
+ return { refresh, land: () => land() }
+ }
+
+ it('an embed request during a timer mint joins it instead of minting again', async () => {
+ const { refresh, land } = heldMint()
+ const installCookie = vi.fn<SandboxUiInstallCookieFn>(async () => undefined)
+ const args = makeArgs({ refresh, installCookie })
+ startSandboxUiRefresh(args)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+ expect(refresh).toHaveBeenCalledTimes(1)
+
+ const request = handleEmbedRefreshRequest(args.webContentsId)
+ land()
+ await request
+
+ expect(refresh).toHaveBeenCalledTimes(1)
+ expect(installCookie).toHaveBeenCalledTimes(1)
+ })
+
+ it('a 401 during a timer mint reloads once that mint lands, without minting again', async () => {
+ const { refresh, land } = heldMint()
+ const reload = vi.fn()
+ const args = makeArgs({ refresh, reload })
+ startSandboxUiRefresh(args)
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS + 1)
+
+ handleSandboxUiUnauthorizedNavigation(args.webContentsId)
+ await flush()
+ expect(reload).not.toHaveBeenCalled()
+
+ land()
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(1)
+ expect(reload).toHaveBeenCalledTimes(1)
+ })
+
+ it('a focus burst neither duplicates nor advances the mint', async () => {
+ const window = new FakeBrowserWindow()
+ const { refresh, land } = heldMint()
+ startSandboxUiRefresh(makeArgs({ parentWindow: window, refresh }))
+
+ await advance(100_000)
+ for (let i = 0; i < 10; i += 1) window.emit('focus')
+ await flush()
+ expect(refresh).not.toHaveBeenCalled()
+
+ await advance(SANDBOX_UI_REFRESH_INTERVAL_MS - 100_000 - 1)
+ expect(refresh).not.toHaveBeenCalled()
+ await advance(2)
+ expect(refresh).toHaveBeenCalledTimes(1)
+
+ // While that mint is in flight, more focus adds nothing.
+ for (let i = 0; i < 10; i += 1) window.emit('focus')
+ await flush()
+ land()
+ await flush()
+ expect(refresh).toHaveBeenCalledTimes(1)
})
})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index 795d72d6d..bee13e1c2 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -5335,6 +5335,7 @@ export class AppService {
// the open itself must refuse to install the cleared session's cookie or
// attach a view for it.
this.assertSandboxUiSessionEpoch(sessionEpoch)
+ const mintedAt = Date.now()
const { setCookie } = await this.mintSandboxUiSession(recipeNs, recipeName)
this.assertSandboxUiSessionEpoch(sessionEpoch)
const driver = await import('./sandboxUiDriver.js')
@@ -5366,6 +5367,9 @@ export class AppService {
void active.openGfsResourceFromNavigation(surface.webContentsId, uri)
},
onTitleChanged: args.onTitleChanged,
+ onUnauthorizedNavigation: webContentsId => {
+ refreshModule.handleSandboxUiUnauthorizedNavigation(webContentsId)
+ },
onOauthAuthorize: (oauthClientId, background) => {
void this.requestSandboxUiOauthAuthorize(
recipeNs,
@@ -5401,15 +5405,25 @@ export class AppService {
recipeName,
webContentsId: activeView.webContentsId,
parentWindow: args.parentWindow,
- refresh: (ns, name) => this.mintSandboxUiSession(ns, name),
+ mintedAt,
// A refresh minted before a session clear can land before the queued
- // close cancels this loop. Rejecting stops the loop without writing the
- // cleared session's cookie; the user has nothing to act on, so it is not
+ // close cancels this loop. Rejecting fails the attempt without writing
+ // the cleared session's cookie, and any retry before the close runs is
+ // refused before it reaches rpc-proxy, so the next session's token never
+ // mints for this view. The user has nothing to act on, so it is not
// reported.
+ refresh: async (ns, name) => {
+ this.assertSandboxUiSessionEpoch(sessionEpoch)
+ return this.mintSandboxUiSession(ns, name)
+ },
installCookie: async setCookieValue => {
this.assertSandboxUiSessionEpoch(sessionEpoch)
await driver.installSandboxUiCookie(setCookieValue)
},
+ reload: () => {
+ if (driver.getActiveSandboxUi()?.webContentsId !== activeView.webContentsId) return
+ driver.reloadActiveSandboxUiView()
+ },
onError: err => {
if (this.sandboxUiSessionEpoch !== sessionEpoch) return
args.onRefreshError?.(err instanceof Error ? err.message : String(err))
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index e07dc21a5..f0b52dc2d 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -33,6 +33,7 @@ import {
parseSandboxUiDeepLink,
} from './sandboxUiDeepLinks.js'
import { shouldAcceptSandboxUiProtocolLink } from './sandboxUiProtocolWindowPolicy.js'
+import { notifySandboxUiHostResumed } from './sandboxUiSessionRefresh.js'
import { wireHostDesktopShortcutRouting } from './shortcutRouter.js'
import { installAdaptiveSystemIcon, resolveSystemIconPath } from './systemIcon.js'
import { TokenStore } from './tokenStore.js'
@@ -146,6 +147,8 @@ function emitWindowControlsState(win: BrowserWindow): void {
* streams — the 30s watchdog stays as a slower safety net. No payload: the
* renderer decides which chats to reconcile from its own FSM. Registered once,
* app-wide (not per-window); `send` is a no-op when the webContents is gone.
+ * The sandbox UI session loop gets the same tick: a cookie that expired during
+ * sleep is re-minted now instead of whenever its timer catches up.
*/
function wirePowerMonitor(): void {
const emit = () => {
@@ -155,6 +158,8 @@ function wirePowerMonitor(): void {
}
powerMonitor.on('resume', emit)
powerMonitor.on('unlock-screen', emit)
+ powerMonitor.on('resume', notifySandboxUiHostResumed)
+ powerMonitor.on('unlock-screen', notifySandboxUiHostResumed)
}
/** Push native window state to the renderer on every visibility/focus change. */
diff --git a/desktop-app/src/sandboxUiDriver.ts b/desktop-app/src/sandboxUiDriver.ts
index 4194bf7d5..b878af8c8 100644
--- a/desktop-app/src/sandboxUiDriver.ts
+++ b/desktop-app/src/sandboxUiDriver.ts
@@ -125,6 +125,13 @@ export type MountSandboxUiArgs = {
* viewer, so a click reveals nothing to the plugin.
*/
onGfsOpen?: (uri: string) => void
+ /**
+ * Fired when a main-frame navigation inside the app's `view/` prefix
+ * commits with HTTP 401 — the session cookie was rejected and the page left
+ * behind has no script that could ask for a refresh. Lives as long as the
+ * view, unlike the one-shot client-route handoff listener.
+ */
+ onUnauthorizedNavigation?: (webContentsId: number) => void
/**
* Re-checked at every await before a session effect (cookie write, view
* creation). False means the caller's authenticated session ended while this
@@ -535,13 +542,25 @@ export async function mountSandboxUiView(args: MountSandboxUiArgs): Promise<void
const onPageTitleUpdated = (_event: Electron.Event, title: string): void => {
if (active?.view === view) onTitleChanged?.(title)
}
+ // `did-navigate` only fires for the main frame.
+ const onDocumentNavigated = (
+ _event: Electron.Event,
+ navigatedUrl: string,
+ httpResponseCode: number
+ ): void => {
+ if (active?.view !== view || httpResponseCode !== 401) return
+ if (!isSandboxUiNavigationWithinPrefix(navigatedUrl, allowedNavigationPrefix)) return
+ args.onUnauthorizedNavigation?.(view.webContents.id)
+ }
view.webContents.on('did-start-navigation', onDidStartNavigation)
view.webContents.on('did-finish-load', onDocumentReady)
view.webContents.on('page-title-updated', onPageTitleUpdated)
+ view.webContents.on('did-navigate', onDocumentNavigated)
active.cleanupDocumentLifecycle = () => {
view.webContents.removeListener('did-start-navigation', onDidStartNavigation)
view.webContents.removeListener('did-finish-load', onDocumentReady)
view.webContents.removeListener('page-title-updated', onPageTitleUpdated)
+ view.webContents.removeListener('did-navigate', onDocumentNavigated)
}
active.cleanupShortcutRouting = wireDesktopShortcutRouting({
diff --git a/desktop-app/src/sandboxUiSessionRefresh.ts b/desktop-app/src/sandboxUiSessionRefresh.ts
index 763c42a87..7e49c9394 100644
--- a/desktop-app/src/sandboxUiSessionRefresh.ts
+++ b/desktop-app/src/sandboxUiSessionRefresh.ts
@@ -18,13 +18,24 @@ import type { BrowserWindow } from 'electron'
* mount time and removed at teardown. An IPC from a sender not in the
* map is dropped — the trust check is identity, not URL, because the
* embed loads from rpc-proxy and would fail `assertTrustedSender`.
- * 2. **Per-view rate-limit:** ≤1 refresh / 30 s.
+ * 2. **Per-view rate-limit:** ≤1 accepted request / 30 s.
+ *
+ * Expiry model: every successful mint records a wall-clock `expiresAt`.
+ * Whether a refresh is due is decided against that wall clock, never against
+ * how long a timer has been waiting — timers may not advance while the
+ * machine sleeps, so a timer alone would wake up long after the cookie died.
*
* Visibility model:
- * - mounted + visible → 270 s timer scheduled.
+ * - mounted + visible → timer armed for `expiresAt - lead`.
* - parent hidden / minimized → cancel timer, cookie expires naturally.
- * - parent shown / restored → re-arm timer.
- * - unmount / refresh fail → stop timer, surface error to the chrome.
+ * - parent shown / restored / focused, or the host resumes / unlocks →
+ * refresh now if the attempt is already due, otherwise re-arm the timer
+ * for the remaining time.
+ * - mint fails → retry with backoff until the cookie has been dead for a
+ * grace period, then surface the error. The loop stays alive (and the
+ * sender pinned): an embed request, a top-level 401 or the window / host
+ * returning resumes it.
+ * - unmount → stop for good.
*/
export const SANDBOX_UI_REFRESH_IPC_CHANNEL = 'clerum:sandbox-ui:request-refresh'
@@ -37,6 +48,11 @@ export const SANDBOX_UI_REFRESH_INTERVAL_MS = SANDBOX_UI_COOKIE_TTL_MS - SANDBOX
export const SANDBOX_UI_RATE_LIMIT_MS = 30 * 1000
+/** Delay before each consecutive retry of a failed mint; the last repeats. */
+export const SANDBOX_UI_RETRY_DELAYS_MS: readonly number[] = [1_000, 2_000, 5_000, 15_000, 30_000]
+/** How long past the cookie's expiry (or the first failure, if later) retries continue. */
+export const SANDBOX_UI_RETRY_GRACE_MS = 60 * 1000
+
export type SandboxUiRefreshFn = (
recipeNs: string,
recipeName: string
@@ -51,20 +67,47 @@ export type StartSandboxUiRefreshArgs = {
parentWindow: BrowserWindow
refresh: SandboxUiRefreshFn
installCookie: SandboxUiInstallCookieFn
+ /** Hard-reloads the embed after a mint that recovers a top-level 401. */
+ reload: () => void
onError: (err: Error) => void
+ /**
+ * Wall-clock time the initial mint was requested. The cookie's lifetime is
+ * counted from the server's issue time, so the request start is the
+ * conservative anchor. Defaults to `now()` at start.
+ */
+ mintedAt?: number
+ /** Wall clock; injectable so tests can move it independently of timers. */
+ now?: () => number
}
+type RefreshTrigger = 'timer' | 'retry' | 'return' | 'ipc' | 'unauthorized'
+
type ParentVisibilityHandlers = {
hide: () => void
minimize: () => void
show: () => void
restore: () => void
+ focus: () => void
} | null
-type ActiveRefresh = StartSandboxUiRefreshArgs & {
+type ActiveRefresh = Omit<StartSandboxUiRefreshArgs, 'now' | 'mintedAt'> & {
+ now: () => number
timer: ReturnType<typeof setTimeout> | null
parentHandlers: ParentVisibilityHandlers
stopped: boolean
+ inflight: Promise<void> | null
+ expiresAt: number
+ /** Wall-clock time of the next scheduled attempt; null once retries are exhausted. */
+ nextAttemptAt: number | null
+ consecutiveFailures: number
+ retryDeadline: number | null
+ /** Incremented by every successful mint (the initial one is 0). */
+ mintSeq: number
+ reloadOnNextMint: boolean
+ /** The mint that recovered a top-level 401; a 401 under it is not retried again. */
+ unauthorizedRecoveryMintSeq: number | null
+ /** Last time a return event or a 401 reopened retries after they ran out. */
+ lastResumeAt: number | null
}
let activeRefresh: ActiveRefresh | null = null
@@ -85,49 +128,145 @@ function isParentVisible(ref: ActiveRefresh): boolean {
return ref.parentWindow.isVisible() && !ref.parentWindow.isMinimized()
}
-function scheduleNext(ref: ActiveRefresh): void {
+function armTimer(ref: ActiveRefresh): void {
clearTimer(ref)
- if (ref.stopped) return
+ if (ref.stopped || ref.nextAttemptAt === null) return
if (!isParentVisible(ref)) return
- ref.timer = setTimeout(() => {
- void runRefresh(ref, 'timer')
- }, SANDBOX_UI_REFRESH_INTERVAL_MS)
+ const trigger: RefreshTrigger = ref.consecutiveFailures > 0 ? 'retry' : 'timer'
+ ref.timer = setTimeout(
+ () => {
+ ref.timer = null
+ void runRefresh(ref, trigger)
+ },
+ Math.max(0, ref.nextAttemptAt - ref.now())
+ )
}
-async function runRefresh(ref: ActiveRefresh, trigger: 'timer' | 'ipc'): Promise<void> {
- if (ref.stopped) return
+function onHostReturn(ref: ActiveRefresh): void {
+ if (ref.stopped || ref.inflight) return
+ if (!isParentVisible(ref)) return
+ if (ref.nextAttemptAt === null) {
+ if (tryResumeExhausted(ref)) void runRefresh(ref, 'return')
+ return
+ }
+ if (ref.now() >= ref.nextAttemptAt) {
+ void runRefresh(ref, 'return')
+ return
+ }
+ armTimer(ref)
+}
+
+function startRetryEpisode(ref: ActiveRefresh): void {
+ ref.consecutiveFailures = 0
+ ref.retryDeadline = null
+}
+
+/**
+ * Reopens retries for a loop that gave up. Focus events and 401 navigations
+ * can arrive in bursts, so together they get one resume per rate-limit window.
+ */
+function tryResumeExhausted(ref: ActiveRefresh): boolean {
+ const now = ref.now()
+ if (ref.lastResumeAt !== null && now - ref.lastResumeAt < SANDBOX_UI_RATE_LIMIT_MS) return false
+ ref.lastResumeAt = now
+ startRetryEpisode(ref)
+ return true
+}
+
+/**
+ * Every scheduled retry lands before its episode's deadline, so an attempt
+ * starting well past it means the host was asleep or hidden in between: the
+ * old outage window says nothing about now, and this attempt gets a fresh one.
+ * The slack absorbs a timer that merely fires late.
+ */
+function isRetryEpisodeStale(ref: ActiveRefresh): boolean {
+ if (ref.retryDeadline === null) return false
+ const slack = SANDBOX_UI_RETRY_DELAYS_MS[SANDBOX_UI_RETRY_DELAYS_MS.length - 1]!
+ return ref.now() > ref.retryDeadline + slack
+}
+
+function runRefresh(ref: ActiveRefresh, trigger: RefreshTrigger): Promise<void> {
+ if (ref.stopped) return Promise.resolve()
+ if (ref.inflight) return ref.inflight
+ if (isRetryEpisodeStale(ref)) startRetryEpisode(ref)
// Suspend the timer until we know the outcome.
clearTimer(ref)
+ const attempt = attemptMint(ref, trigger).finally(() => {
+ if (ref.inflight === attempt) ref.inflight = null
+ })
+ ref.inflight = attempt
+ return attempt
+}
+
+async function attemptMint(ref: ActiveRefresh, trigger: RefreshTrigger): Promise<void> {
+ const requestedAt = ref.now()
try {
const { setCookie } = await ref.refresh(ref.recipeNs, ref.recipeName)
if (ref.stopped) return
await ref.installCookie(setCookie)
- lastRefreshAtBySender.set(ref.webContentsId, Date.now())
- // Reschedule — IPC-driven refresh resets the 270 s window so a
- // successful recovery push delays the next scheduled tick.
- scheduleNext(ref)
} catch (err) {
+ if (ref.stopped) return
console.error(`[SandboxUI] refresh failed (trigger=${trigger}):`, err)
- ref.stopped = true
- senderToRefreshContext.delete(ref.webContentsId)
- ref.onError(err instanceof Error ? err : new Error(String(err)))
+ scheduleRetry(ref, err instanceof Error ? err : new Error(String(err)))
+ return
+ }
+ if (ref.stopped) return
+ ref.expiresAt = requestedAt + SANDBOX_UI_COOKIE_TTL_MS
+ ref.nextAttemptAt = ref.expiresAt - SANDBOX_UI_REFRESH_LEAD_MS
+ ref.mintSeq += 1
+ startRetryEpisode(ref)
+ lastRefreshAtBySender.set(ref.webContentsId, ref.now())
+ if (ref.reloadOnNextMint) {
+ ref.reloadOnNextMint = false
+ ref.unauthorizedRecoveryMintSeq = ref.mintSeq
+ ref.reload()
+ }
+ armTimer(ref)
+}
+
+function scheduleRetry(ref: ActiveRefresh, err: Error): void {
+ const now = ref.now()
+ // A cookie that died while the machine slept would leave no retry window
+ // at all if the deadline were anchored on `expiresAt` alone.
+ ref.retryDeadline ??= Math.max(ref.expiresAt, now) + SANDBOX_UI_RETRY_GRACE_MS
+ const delays = SANDBOX_UI_RETRY_DELAYS_MS
+ const delay = delays[Math.min(ref.consecutiveFailures, delays.length - 1)]!
+ ref.consecutiveFailures += 1
+ if (now + delay > ref.retryDeadline) {
+ ref.nextAttemptAt = null
+ ref.onError(err)
+ return
}
+ ref.nextAttemptAt = now + delay
+ armTimer(ref)
}
export function startSandboxUiRefresh(args: StartSandboxUiRefreshArgs): void {
cancelSandboxUiRefresh()
+ const { now = Date.now, mintedAt, ...rest } = args
+ const expiresAt = (mintedAt ?? now()) + SANDBOX_UI_COOKIE_TTL_MS
const ref: ActiveRefresh = {
- ...args,
+ ...rest,
+ now,
timer: null,
parentHandlers: null,
stopped: false,
+ inflight: null,
+ expiresAt,
+ nextAttemptAt: expiresAt - SANDBOX_UI_REFRESH_LEAD_MS,
+ consecutiveFailures: 0,
+ retryDeadline: null,
+ mintSeq: 0,
+ reloadOnNextMint: false,
+ unauthorizedRecoveryMintSeq: null,
+ lastResumeAt: null,
}
senderToRefreshContext.set(args.webContentsId, ref)
// The just-completed mint counts as t=0 for rate-limit accounting so an
// immediate IPC retry from a flaky embed gets dropped.
- lastRefreshAtBySender.set(args.webContentsId, Date.now())
+ lastRefreshAtBySender.set(args.webContentsId, now())
activeRefresh = ref
if (!args.parentWindow.isDestroyed()) {
@@ -137,17 +276,19 @@ export function startSandboxUiRefresh(args: StartSandboxUiRefreshArgs): void {
const handlers = {
hide: (): void => clearTimer(ref),
minimize: (): void => clearTimer(ref),
- show: (): void => scheduleNext(ref),
- restore: (): void => scheduleNext(ref),
+ show: (): void => onHostReturn(ref),
+ restore: (): void => onHostReturn(ref),
+ focus: (): void => onHostReturn(ref),
}
args.parentWindow.on('hide', handlers.hide)
args.parentWindow.on('minimize', handlers.minimize)
args.parentWindow.on('show', handlers.show)
args.parentWindow.on('restore', handlers.restore)
+ args.parentWindow.on('focus', handlers.focus)
ref.parentHandlers = handlers
}
- scheduleNext(ref)
+ armTimer(ref)
}
export function cancelSandboxUiRefresh(): void {
@@ -163,15 +304,24 @@ export function cancelSandboxUiRefresh(): void {
ref.parentWindow.removeListener('minimize', ref.parentHandlers.minimize)
ref.parentWindow.removeListener('show', ref.parentHandlers.show)
ref.parentWindow.removeListener('restore', ref.parentHandlers.restore)
+ ref.parentWindow.removeListener('focus', ref.parentHandlers.focus)
}
ref.parentHandlers = null
}
+/**
+ * The host came back from sleep or a screen lock (`powerMonitor`). Same rule
+ * as the parent window returning: refresh now if due, else re-arm.
+ */
+export function notifySandboxUiHostResumed(): void {
+ if (activeRefresh) onHostReturn(activeRefresh)
+}
+
/**
* Embed-side IPC entry point. Resolves senderId via the pinning map and
- * per-view rate-limit (≤1 refresh / 30 s). Throws when the sender is
- * unpinned or rate-limited so the embed sees an error and doesn't retry
- * in a tight loop.
+ * per-view rate-limit (≤1 accepted request / 30 s). Throws when the sender
+ * is unpinned or rate-limited so the embed sees an error and doesn't retry
+ * in a tight loop. Resumes a loop whose retries were exhausted.
*/
export async function handleEmbedRefreshRequest(senderId: number): Promise<void> {
const ref = senderToRefreshContext.get(senderId)
@@ -183,13 +333,37 @@ export async function handleEmbedRefreshRequest(senderId: number): Promise<void>
throw new Error('sandbox-ui refresh: stopped')
}
const last = lastRefreshAtBySender.get(senderId) ?? 0
- if (Date.now() - last < SANDBOX_UI_RATE_LIMIT_MS) {
+ if (ref.now() - last < SANDBOX_UI_RATE_LIMIT_MS) {
console.warn('[SandboxUI] refresh rate-limited for sender', senderId)
throw new Error('sandbox-ui refresh: rate-limited')
}
+ // Counted on acceptance, not only on success: a failing mint no longer
+ // stops the loop, so the embed must not be able to drive it faster.
+ lastRefreshAtBySender.set(senderId, ref.now())
+ if (ref.nextAttemptAt === null) startRetryEpisode(ref)
await runRefresh(ref, 'ipc')
}
+/**
+ * The embed's top-level document came back 401 (an expired cookie leaves a
+ * dead error page with no script to ask for a refresh). Re-mints and reloads,
+ * at most once per mint: if the cookie minted for that recovery still yields
+ * a 401, the next one is left alone instead of looping.
+ */
+export function handleSandboxUiUnauthorizedNavigation(webContentsId: number): void {
+ const ref = senderToRefreshContext.get(webContentsId)
+ if (!ref || ref.stopped) return
+ if (ref.unauthorizedRecoveryMintSeq === ref.mintSeq) return
+ const exhausted = ref.nextAttemptAt === null
+ // A pending recovery is already being retried — unless its retries ran out,
+ // in which case this 401 is the only signal left that can reopen them.
+ if (ref.reloadOnNextMint && !exhausted) return
+ ref.reloadOnNextMint = true
+ if (ref.inflight) return
+ if (exhausted && !tryResumeExhausted(ref)) return
+ void runRefresh(ref, 'unauthorized')
+}
+
/** ONLY for tests — resets module-level singleton state between cases. */
export function _resetSandboxUiRefreshForTests(): void {
if (activeRefresh) {
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 14a34daaf..115c0f002 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -305,9 +305,11 @@ export function SandboxUiPage({
}, [onEmbeddedAppBack, setLaunch])
// Surface refresh failures (403 / 410 / network) as an in-chrome banner.
- // The main-process timer has already stopped firing by the time we get
- // here — this is informational, not actionable beyond the user closing
- // and re-opening.
+ // By the time this fires main has exhausted its retries, but the session
+ // loop is still alive: returning to the window, waking the machine, a
+ // 401-ed page load or the embed's own refresh request can still recover
+ // the session. No recovery signal reaches this page, so the banner stays
+ // until the view is closed.
useEffect(() => {
return window.clerum.sandboxUi.onRefreshError(({ launchId, message }) => {
const current = launchRef.current