Skip to content

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

TypeScript

refactor(desktop-app): let the embed ownership machine own the native app view

Diego Zacarias3676630fc9dd
diff --git a/desktop-app/src/__tests__/embedOwnership.property.test.ts b/desktop-app/src/__tests__/embedOwnership.property.test.ts
index 9b265089d..988d42801 100644
--- a/desktop-app/src/__tests__/embedOwnership.property.test.ts
+++ b/desktop-app/src/__tests__/embedOwnership.property.test.ts
@@ -1042,7 +1042,8 @@ class World {
event.type === 'released' &&
event.reason === 'crashed' &&
previous.owner === event.launchId &&
- previous.views.get(event.launchId)?.phase === 'mounted'
+ (previous.views.get(event.launchId)?.phase === 'mounted' ||
+ previous.views.get(event.launchId)?.phase === 'opening')
) {
if (next.failure?.launchId !== event.launchId || next.failure.kind !== 'crashed') {
this.violation('P17', `${where}: the owner's crash left no crash failure`)
@@ -1615,7 +1616,7 @@ describe('embed ownership named cases (real main process)', () => {
assertClean(world)
})
- it('K20: a view whose renderer dies before its open resolves settles abandoned, not crashed', async () => {
+ it('K20/K25: a view whose renderer dies before its open resolves fails with a crash failure', async () => {
const { sink, world } = await manualWorld()
world.crashNextLoad = true
@@ -1624,8 +1625,12 @@ describe('embed ownership named cases (real main process)', () => {
// main reports the release first, then rejects the open.
expect(world.releases).toEqual([{ launchId, reason: 'crashed', location: null }])
- expect(world.outcomes.get(launchId)).toBe('abandoned')
- expect(world.machine.getSnapshot().failure).toBeNull()
+ expect(world.outcomes.get(launchId)).toBe('failed')
+ expect(world.machine.getSnapshot().failure).toEqual({
+ tabId: TAB_ALPHA,
+ launchId,
+ kind: 'crashed',
+ })
expect(world.machine.getSnapshot().owner).toBeNull()
expectNoView(world)
})
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 0e75ae8d8..d23ab7f4b 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -37,9 +37,14 @@ import {
CHAT_DRAWER_EMBED_FLOOR,
useChatDrawerResize,
} from '@hooks/useChatDrawerResize'
+import { useEmbedOwnership } from '@hooks/useEmbedOwnership'
import { useWindowFocusBridge } from '@hooks/useWindowFocusBridge'
import type { ChatLocalMatch } from '@lib/chatLocalSearch'
import { buildLoadedChatSemanticModels } from '@lib/chatMessageSemantics'
+import type { Launch, LaunchId, LaunchOutcome } from '@lib/embedOwnership.types'
+import { createEmbedOwnershipMachine } from '@lib/embedOwnershipMachine'
+import type { EmbedRefreshErrorEvent } from '@lib/embedOwnershipMachine.types'
+import { embedFailureMessage, embedViewState } from '@lib/embedOwnershipView'
import { EntityChangeRegistry } from '@lib/entityChangeRegistry'
import {
authoritativeGfsStatus,
@@ -85,8 +90,6 @@ import {
selectLastWorkspaceTab,
selectWorkspaceTab,
selectWorkspaceTabAt,
- setAppTabSavedRoutePath,
- setAppTabTitle,
setFilesTabPath,
} from '@lib/workspaceTabs'
import type { WorkspaceTab, WorkspaceTabsState } from '@lib/workspaceTabs.types'
@@ -98,15 +101,15 @@ import { FilesPage } from '@pages/FilesPage'
import { McpServersPage } from '@pages/McpServersPage'
import { OnboardingPage } from '@pages/OnboardingPage'
import { SandboxUiPage } from '@pages/SandboxUiPage'
-import type {
- SandboxUiConversationOrigin,
- SandboxUiPageAction,
- SandboxUiShortcutOpenResult,
-} from '@pages/SandboxUiPage.types'
+import type { SandboxUiConversationOrigin } from '@pages/SandboxUiPage.types'
import { SettingsPage } from '@pages/SettingsPage'
import { UnavailablePage } from '@pages/UnavailablePage'
import { WorkflowsPage } from '@pages/WorkflowsPage'
-import type { PendingSandboxUiDeepLink, SandboxUiDeepLinkEnvelope } from '@/App.types'
+import type {
+ EmbedLaunchPlan,
+ PendingSandboxUiDeepLink,
+ SandboxUiDeepLinkEnvelope,
+} from '@/App.types'
import type { ActiveSandboxUiApp, NavItem, ThemeMode } from '@/uiTypes'
import {
type DesktopCommandId,
@@ -117,7 +120,6 @@ import {
type PendingSandboxUiDeepLinkLaunch = {
linkId: number
- requestId: number
generation: number
originalTeamId: string
linkTeamId?: string
@@ -139,29 +141,11 @@ const TRANSIENT_TEAM_CONTEXT_ERROR_CODES = new Set([
const SANDBOX_UI_DEEP_LINK_MANUAL_TEAM_CHANGE_MESSAGE =
'App link paused because you switched teams. Retry to open it from the current team, or dismiss it.'
-// §3 (mini-spec 08): what a `getLocation()` read means for the OUTGOING app
-// tab's saved route. `set`/`clear` come only from the tab's OWN app; `preserve`
-// (foreign read within one activation generation, or a failed read) leaves the
-// stored route untouched — the caller must NOT invoke the setter, because
-// passing `undefined` to it would erase A's previously-saved route.
-type OutgoingRouteDecision =
- | { action: 'set'; routePath: string }
- | { action: 'clear' }
- | { action: 'preserve' }
-
-async function readOutgoingRouteDecision(
- outgoingAppRef: string | undefined
-): Promise<OutgoingRouteDecision> {
- try {
- const location = await window.clerum.sandboxUi.getLocation()
- if (!location || location.appRef !== outgoingAppRef) return { action: 'preserve' }
- return location.routePath
- ? { action: 'set', routePath: location.routePath }
- : { action: 'clear' }
- } catch {
- return { action: 'preserve' }
- }
-}
+// Every reveal gesture launches whatever app tab its commit leaves active.
+const ACTIVE_TAB_LAUNCH: EmbedLaunchPlan = { kind: 'activeTab' }
+// Closing a tab launches the app tab its commit activated, never one that was
+// already active (a failed one must wait for an explicit gesture).
+const ACTIVATED_TAB_LAUNCH: EmbedLaunchPlan = { kind: 'activeTab', onlyIfActivated: true }
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error || 'Unknown error')
@@ -302,10 +286,6 @@ export function App() {
const [sidebarCollapsed, setSidebarCollapsed] = React.useState<boolean>(
getInitialSidebarCollapsed
)
- const [activeSandboxUiApp, setActiveSandboxUiApp] = React.useState<ActiveSandboxUiApp | null>(
- null
- )
- const [sandboxUiMounted, setSandboxUiMounted] = React.useState(false)
const [sandboxUiConversationOrigin, setSandboxUiConversationOrigin] =
React.useState<SandboxUiConversationOrigin | null>(null)
const [sidebarSettingsMenuOpen, setSidebarSettingsMenuOpen] = React.useState(false)
@@ -327,7 +307,6 @@ export function App() {
const [availableSandboxUiApps, setAvailableSandboxUiApps] = React.useState<ActiveSandboxUiApp[]>(
[]
)
- const [sandboxUiShortcutOpenRequestId, setSandboxUiShortcutOpenRequestId] = React.useState(0)
const [pendingSandboxUiDeepLinks, setPendingSandboxUiDeepLinks] = React.useState<
PendingSandboxUiDeepLink[]
>([])
@@ -379,10 +358,6 @@ export function App() {
currentMatch: ChatLocalMatch | null
}>({ query: '', currentMatch: null })
const [sandboxLocalSearchRequestId, setSandboxLocalSearchRequestId] = React.useState(0)
- const [sandboxActionRequest, setSandboxActionRequest] = React.useState<{
- id: number
- action: SandboxUiPageAction
- } | null>(null)
const [commandPaletteOpen, setCommandPaletteOpen] = React.useState(false)
const [commandPaletteReturnToSandbox, setCommandPaletteReturnToSandbox] = React.useState(false)
const [settingsShortcutsRequestId, setSettingsShortcutsRequestId] = React.useState(0)
@@ -390,110 +365,254 @@ export function App() {
const contentPanelRef = React.useRef<HTMLElement | null>(null)
const activeConversationOriginRef = React.useRef<SandboxUiConversationOrigin | null>(null)
const processingSandboxUiDeepLinkIdRef = React.useRef<number | null>(null)
- const launchingSandboxUiDeepLinkRef = React.useRef<PendingSandboxUiDeepLinkLaunch | null>(null)
const pendingSandboxUiDeepLinksRef = React.useRef<PendingSandboxUiDeepLink[]>([])
const sandboxUiDeepLinkRestoreTeamByIdRef = React.useRef(new Map<number, string>())
const sandboxUiDeepLinkIdentityRef = React.useRef<string | null | undefined>(undefined)
const sandboxUiDeepLinkGenerationRef = React.useRef(0)
- const sandboxUiShortcutOpenRequestIdRef = React.useRef(0)
- // Relaunches a backgrounded app tab through the live-app machinery. A ref so
- // `revealWorkspaceTab` (defined above `beginSandboxUiLaunch`) can call it
- // without a TDZ on the launch callback.
- const relaunchSandboxUiAppRef = React.useRef<
- ((app: ActiveSandboxUiApp, tabId: string) => void) | null
- >(null)
- // Id of the app tab whose native embed is currently live in the main process
- // (mini-spec 05 §3). The store governs the embed lifecycle: when the active
- // app tab changes, this ref tells the deactivation effect which OUTGOING tab
- // to persist the route onto. `null` = no embed is live (also the reconciled
- // state after an UNsolicited close — crash/quit/GC — so a later tab switch
- // does not persist or re-close a dead embed). A FAILED open does not reset it:
- // the tab keeps owning whatever main may still hold (see
- // `handleSandboxUiOpenFailed`).
- const liveSandboxUiTabIdRef = React.useRef<string | null>(null)
- // Id of the most recent open request (minted by SandboxUiPage, echoed by main
- // on per-view events). A relaunch of the same app keeps the appRef, so title
- // events are matched on this id, not on the appRef.
- const currentSandboxUiLaunchIdRef = React.useRef<string | null>(null)
- // Monotonic generation bumped on EVERY transition of the active embed (the
- // deactivation effect and the deep-link handoff are the only emitters). Each
- // read-then-close continuation captures this at dispatch; anything reopened or
- // switched-to while its `getLocation()` IPC is in flight bumps the generation,
- // so the stale continuation can tell it no longer owns the active view and
- // must abort — it must neither close the newer embed nor persist the newer
- // tab's route with a value read from a view that is already gone.
- const sandboxUiActivationGenRef = React.useRef(0)
- // Tab the latest `beginSandboxUiLaunch` targeted (new tab or relaunch).
- // Activating an app tab hands the embed over (app→app) only when a launch is
- // about to `open()` into it: a tab whose app App cannot resolve gets no
- // launch, and leaving the outgoing view up would paint it inside that tab.
- const launchTargetTabIdRef = React.useRef<string | null>(null)
workspaceTabsRef.current = workspaceTabs
-
- const leaveSandboxForChat = React.useCallback(() => {
- setActiveSandboxUiApp(null)
- setSandboxUiMounted(false)
+ const availableSandboxUiAppsRef = React.useRef(availableSandboxUiApps)
+ availableSandboxUiAppsRef.current = availableSandboxUiApps
+ const setWorkspaceTabsRef = React.useRef(setWorkspaceTabs)
+ setWorkspaceTabsRef.current = setWorkspaceTabs
+
+ // The app chrome tied to a live embed: what it was opened from and the shell
+ // overlays raised over it.
+ const resetEmbedChrome = React.useCallback(() => {
setSandboxUiConversationOrigin(null)
setHeaderShellOverlayOpen(false)
setSidebarSettingsMenuOpen(false)
}, [])
+ const leaveSandboxForChat = resetEmbedChrome
+
+ // Which launch owns the native embed (one machine per App). The machine is
+ // not recreated when the tab store is reset for a new principal: views the
+ // previous store owned must still be closed by it, and the routes it
+ // remembers are keyed by tab ids that are never reused.
+ const [embedRefreshError, setEmbedRefreshError] = React.useState<EmbedRefreshErrorEvent | null>(
+ null
+ )
+ const handoffWaitersRef = React.useRef(new Map<number, () => void>())
+ const [embed] = React.useState(() =>
+ createEmbedOwnershipMachine({
+ bridge: {
+ open: request => window.clerum.sandboxUi.open(request),
+ close: request => window.clerum.sandboxUi.close(request),
+ },
+ updateTabs: updater => setWorkspaceTabsRef.current(updater),
+ onHandoffReady: requestId => {
+ const resolve = handoffWaitersRef.current.get(requestId)
+ handoffWaitersRef.current.delete(requestId)
+ resolve?.()
+ },
+ onOwnerRefreshError: event =>
+ setEmbedRefreshError({ launchId: event.launchId, message: event.message }),
+ onTransition: ({ previous, next }) => {
+ // The tab stays but its embed is gone (back to apps, team handoff, a
+ // failed open, a crash, a session end): drop the chrome that belonged
+ // to it, as the picker it falls back to has none. Leaving the tab is
+ // handled by whatever gesture left it.
+ if (
+ previous.owner !== null &&
+ next.owner === null &&
+ previous.activeAppTabId === next.activeAppTabId
+ ) {
+ resetEmbedChrome()
+ }
+ },
+ })
+ )
+ const embedState = useEmbedOwnership(embed)
+ const embedView = embedViewState(embedState)
+ const embedOwner =
+ embedView.kind === 'minting' || embedView.kind === 'mounted' ? embedView.launch : null
+ const sandboxUiMounted = embedView.kind === 'mounted'
+ // The app the embed is showing, named from the trusted catalog when it has it.
+ const activeSandboxUiApp = React.useMemo<ActiveSandboxUiApp | null>(() => {
+ if (!embedOwner) return null
+ return (
+ availableSandboxUiApps.find(app => app.appRef === embedOwner.appRef) ?? {
+ appRef: embedOwner.appRef,
+ label: embedOwner.app.label ?? embedOwner.appRef,
+ defaultPath: embedOwner.app.defaultPath ?? '/',
+ }
+ )
+ }, [availableSandboxUiApps, embedOwner])
+
+ const activeTabAppRef =
+ vm.activeWorkspaceTab?.kind === 'app' ? (vm.activeWorkspaceTab.app?.appRef ?? null) : null
+
+ // StrictMode replays effects (cleanup, then setup) on the same instance, so
+ // only a cleanup that no setup follows is the real unmount that disposes the
+ // machine. Continuations awaiting a launch or a handoff race this, so none is
+ // left hanging, and none acts after it.
+ const embedLifetimeRef = React.useRef<{
+ mounts: number
+ disposed: boolean
+ unmounted: Promise<void>
+ resolveUnmounted: () => void
+ } | null>(null)
+ if (embedLifetimeRef.current === null) {
+ let resolveUnmounted: () => void = () => {}
+ const unmounted = new Promise<void>(resolve => (resolveUnmounted = resolve))
+ embedLifetimeRef.current = { mounts: 0, disposed: false, unmounted, resolveUnmounted }
+ }
+ React.useEffect(() => {
+ const lifetime = embedLifetimeRef.current!
+ lifetime.mounts += 1
+ const sandboxUi = window.clerum.sandboxUi
+ const offReleased = sandboxUi.onReleased?.(event => embed.onReleased(event))
+ const offTitle = sandboxUi.onTitleChanged?.(event => embed.onTitleChanged(event))
+ const offRefreshError = sandboxUi.onRefreshError?.(event => embed.onRefreshError(event))
+ return () => {
+ offReleased?.()
+ offTitle?.()
+ offRefreshError?.()
+ lifetime.mounts -= 1
+ queueMicrotask(() => {
+ if (lifetime.mounts > 0 || lifetime.disposed) return
+ lifetime.disposed = true
+ embed.dispose()
+ lifetime.resolveUnmounted()
+ })
+ }
+ }, [embed])
+
+ // Resolves with the launch's single outcome, or `null` once App is gone.
+ const awaitLaunchOutcome = React.useCallback(
+ async (launchId: LaunchId): Promise<LaunchOutcome | null> => {
+ const lifetime = embedLifetimeRef.current!
+ const settled = embed.whenSettled(launchId)
+ if (!settled || lifetime.disposed) return null
+ const outcome = await Promise.race([settled, lifetime.unmounted.then(() => null)])
+ return lifetime.disposed ? null : outcome
+ },
+ [embed]
+ )
- // The single seam through which a gesture activates a tab and launches what it
- // reveals. Everything commits together under `flushSync`, so the deactivation
- // effect (flushed at the end of that sync commit) already sees the launch's
- // `launchTargetTabIdRef` and launch state; a launch committed in a later render
- // would make an app→app switch look like a departure and close the incoming
- // embed. `update` must be an updater, never a value derived from
- // `workspaceTabsRef`: `flushSync` also commits any pending store update, and a
- // stale value applied after it would silently undo it. The updater keeps the
- // store right, but callers still pick the tab to reveal from the last committed
- // state: if a pending update shifts the base a relative updater (cycle, close)
- // works on, the store and the reveal can disagree for that gesture. Must only
- // run from an event or async continuation — inside a render or effect
- // `flushSync` does not flush.
+ // Main is the only one that knows when a view is gone; the tab store is the
+ // only one that knows which tab is active. The machine learns the latter
+ // here, in the commit that changes it, before any gesture launches into it.
+ const activeSandboxUiTabId =
+ !vm.appsPickerActive && vm.activeWorkspaceTab?.kind === 'app' ? vm.activeWorkspaceTab.id : null
+ React.useLayoutEffect(() => {
+ embed.dispatch({ type: 'projected', activeAppTabId: activeSandboxUiTabId })
+ }, [activeSandboxUiTabId, embed])
+
+ // The launch of the app tab the last commit left active, or none when that
+ // tab is not an app or its app cannot be resolved right now (registry
+ // reconciling, list refreshing): the tab is left intact and relaunches once
+ // the list has it again.
+ const launchForActiveAppTab = React.useCallback((): Launch | null => {
+ const state = embed.getSnapshot()
+ const tabId = state.activeAppTabId
+ if (tabId === null) return null
+ const tab = workspaceTabsRef.current.tabs.find(candidate => candidate.id === tabId)
+ const appRef = tab?.kind === 'app' ? tab.app?.appRef : undefined
+ if (!tab || !appRef) return null
+ // The label names the app in consent prompts: always the catalog's, never
+ // the tab title, which the embedded app itself controls. A view still live
+ // on the tab already carries the catalog's, so relaunching it does not
+ // depend on the list being loaded right now.
+ const catalogApp = availableSandboxUiAppsRef.current.find(
+ candidate => candidate.appRef === appRef
+ )
+ const liveOwner = state.owner === null ? undefined : state.views.get(state.owner)
+ const app = catalogApp
+ ? { label: catalogApp.label, defaultPath: catalogApp.defaultPath }
+ : liveOwner?.tabId === tabId
+ ? liveOwner.app
+ : null
+ if (!app) return null
+ const savedRoutePath = tab.app?.savedRoutePath
+ return {
+ launchId: crypto.randomUUID(),
+ tabId,
+ appRef,
+ route: {
+ kind: 'tab',
+ ...(savedRoutePath !== undefined ? { routePath: savedRoutePath } : {}),
+ },
+ app,
+ }
+ }, [embed])
+
+ // The single seam through which a gesture activates a tab and launches an app
+ // into it. The store commits under `flushSync`, which also delivers the
+ // commit's projection to the machine, and only then is the launch built and
+ // dispatched: the machine judges it against the tab that is really active
+ // (a launch whose tab the commit did not leave active is dropped). `update`
+ // must be an updater, never a value derived from `workspaceTabsRef`:
+ // `flushSync` also commits any pending store update, and a stale value applied
+ // after it would silently undo it. `reveal` loads the content of the tab the
+ // gesture targets (a chat, the drawer of an app launch) in the same commit.
+ // Must only run from an event or async continuation — inside a render or
+ // effect `flushSync` does not flush.
const activateAndLaunch = React.useCallback(
- (update: (state: WorkspaceTabsState) => WorkspaceTabsState, launch?: () => void) => {
+ (
+ update: (state: WorkspaceTabsState) => WorkspaceTabsState,
+ reveal?: () => void,
+ plan?: EmbedLaunchPlan
+ ): LaunchId | null => {
+ const activeAppTabBefore = embed.getSnapshot().activeAppTabId
flushSync(() => {
vm.clearAppsPicker()
setWorkspaceTabs(update)
- launch?.()
+ reveal?.()
})
+ if (!plan) return null
+ if (
+ plan.kind === 'activeTab' &&
+ plan.onlyIfActivated &&
+ embed.getSnapshot().activeAppTabId === activeAppTabBefore
+ ) {
+ return null
+ }
+ const launch: Launch | null =
+ plan.kind === 'activeTab'
+ ? launchForActiveAppTab()
+ : {
+ launchId: crypto.randomUUID(),
+ tabId: plan.tabId,
+ appRef: plan.app.appRef,
+ route:
+ plan.app.routePath !== undefined
+ ? { kind: 'explicit', routePath: plan.app.routePath }
+ : { kind: 'tab' },
+ app: { label: plan.app.label, defaultPath: plan.app.defaultPath },
+ }
+ if (!launch) return null
+ embed.registerWhenSettled(launch.launchId)
+ embed.dispatch(
+ plan.kind === 'activeTab' && plan.replace
+ ? { type: 'relaunch', launch }
+ : { type: 'intent', launch }
+ )
+ return launch.launchId
},
- [setWorkspaceTabs, vm.clearAppsPicker]
+ [embed, launchForActiveAppTab, setWorkspaceTabs, vm.clearAppsPicker]
)
+ // Refresh, Reopen after a crash and Retry after a session failure: tear the
+ // active tab's view down, healthy or not, and open a fresh one (new view, new
+ // session) where the old one stood. It never comes from a re-click, which
+ // leaves a live view alone.
+ const relaunchActiveApp = React.useCallback(() => {
+ activateAndLaunch(state => state, undefined, { kind: 'activeTab', replace: true })
+ }, [activateAndLaunch])
+
// Load the CONTENT of a workspace tab once it is (about to be) active — the
// universal reveal seam. It never selects the tab itself (the store already
// owns identity/active). Chat tabs delegate to `handleSelectChatAgent` (the
- // pending-selection machine, §4 — never reimplemented); app tabs relaunch
- // through the existing embed machinery (store→embed, closes as today on the
- // next deactivation via the SandboxUiPage unmount cleanup — the single close
- // path, §9); DOM tabs (files/settings) render from the derived `navItem`, so
- // this only tears down any lingering app embed.
+ // pending-selection machine, §4 — never reimplemented); app tabs are launched
+ // by the seam from the committed store, not here; DOM tabs (files/settings)
+ // render from the derived `navItem`, so this only drops the app chrome.
const revealWorkspaceTab = React.useCallback(
(tab: WorkspaceTab | undefined, inDrawer = chatDrawerVisibleRef.current) => {
if (!tab || tab.kind === 'files' || tab.kind === 'settings' || tab.kind === 'preview') {
if (!inDrawer) leaveSandboxForChat()
return
}
- if (tab.kind === 'app') {
- const app = availableSandboxUiApps.find(candidate => candidate.appRef === tab.app?.appRef)
- // Transient-empty survivability (mini-spec 05): when the app can't be
- // resolved (registry reconciling / periodic refresh emptied the list),
- // leave the tab intact and do nothing destructive — it recovers when the
- // list repopulates (the picker / no-embed state, never a tab destroy).
- if (app) {
- // Restore the route persisted on deactivation (§3). `savedRoutePath`
- // lives on the tab, not the app; thread it onto the launch so the
- // embed re-mounts where the user left off (undefined → default path).
- const savedRoutePath = tab.app?.savedRoutePath
- relaunchSandboxUiAppRef.current?.(
- savedRoutePath !== undefined ? { ...app, routePath: savedRoutePath } : app,
- tab.id
- )
- }
- return
- }
+ if (tab.kind === 'app') return
const agentRef = tab.chat?.agentRef ?? null
const chatId = tab.chat?.chatId ?? null
if (inDrawer) {
@@ -527,7 +646,7 @@ export function App() {
vm.handleNavSelect(DESKTOP_ROUTES.chat)
}
},
- [availableSandboxUiApps, leaveSandboxForChat, vm.handleNavSelect, vm.handleSelectChatAgent]
+ [leaveSandboxForChat, vm.handleNavSelect, vm.handleSelectChatAgent]
)
// Global strip selection: activate the tab (so `navItem` derives this commit),
@@ -536,9 +655,12 @@ export function App() {
(id: string) => {
const tab = workspaceTabsRef.current.tabs.find(candidate => candidate.id === id)
if (!tab) return
+ // Re-clicking the active app tab relaunches it only when its view is gone;
+ // a live view is left as it is (Refresh is the explicit reload).
activateAndLaunch(
state => selectWorkspaceTab(state, id),
- () => revealWorkspaceTab(tab, false)
+ () => revealWorkspaceTab(tab, false),
+ ACTIVE_TAB_LAUNCH
)
},
[activateAndLaunch, revealWorkspaceTab]
@@ -563,10 +685,13 @@ export function App() {
const projected = closeWorkspaceTab(current, id)
if (projected === current) return
// Closing the active tab activates a neighbor (or empties the workspace,
- // §5). Reveal it so its content follows the strip.
+ // §5). Reveal it so its content follows the strip. Whether an app is
+ // launched is decided on the commit, not on App's last render: a pending
+ // update may have made the closed tab the active one.
activateAndLaunch(
state => closeWorkspaceTab(state, id),
- wasActive ? () => revealWorkspaceTab(activeWorkspaceTab(projected), false) : undefined
+ wasActive ? () => revealWorkspaceTab(activeWorkspaceTab(projected), false) : undefined,
+ ACTIVATED_TAB_LAUNCH
)
},
[activateAndLaunch, revealWorkspaceTab]
@@ -1285,7 +1410,6 @@ export function App() {
React.useEffect(() => {
if (!vm.isAuthenticated) {
setAvailableSandboxUiApps([])
- setActiveSandboxUiApp(null)
setSandboxUiConversationOrigin(null)
return
}
@@ -1322,7 +1446,6 @@ export function App() {
pendingSandboxUiDeepLinksRef.current = []
setPendingSandboxUiDeepLinks([])
processingSandboxUiDeepLinkIdRef.current = null
- launchingSandboxUiDeepLinkRef.current = null
sandboxUiDeepLinkRestoreTeamByIdRef.current.clear()
sandboxUiDeepLinkGenerationRef.current += 1
void window.clerum.sandboxUi.clearPendingDeepLinks().catch(error => {
@@ -1330,56 +1453,6 @@ export function App() {
})
}, [vm.authenticatedPrincipalIdentity])
- const handleSandboxUiOpening = React.useCallback((app: ActiveSandboxUiApp, launchId: string) => {
- currentSandboxUiLaunchIdRef.current = launchId
- setSandboxUiMounted(false)
- setActiveSandboxUiApp(app)
- // Arm the store's embed-liveness ref on EVERY open, however it was launched
- // (store launch from the sidebar or the picker grid, deep link, or relaunch).
- // The deactivation effect otherwise only arms it on an active-tab CHANGE, so
- // an embed re-mounted WITHIN the still-active app tab — a strip relaunch
- // after a back-to-apps / unsolicited onClosed cleared the ref — would never
- // be tracked and would leak (the native view paints over the next tab).
- // Guard on `null` so this never clobbers the OUTGOING id the effect still
- // needs on an app→app switch (ref stays the old tab; the effect reads it,
- // then re-points to the new one).
- if (liveSandboxUiTabIdRef.current === null) {
- const active = activeWorkspaceTab(workspaceTabsRef.current)
- if (active?.kind === 'app') liveSandboxUiTabIdRef.current = active.id
- }
- }, [])
-
- const handleSandboxUiMounted = React.useCallback(() => {
- setSandboxUiMounted(true)
- }, [])
-
- const handleSandboxUiClosed = React.useCallback(() => {
- // Unsolicited close (crash / quit / partition GC) or an explicit back-to-apps
- // teardown from SandboxUiPage: the embed is already gone, so reconcile the
- // store's view of the live embed to "not mounted" (§3). The app TAB stays in
- // the store and recovers on reactivation; only the liveness bookkeeping is
- // cleared so the deactivation effect won't re-close a dead embed.
- liveSandboxUiTabIdRef.current = null
- setActiveSandboxUiApp(null)
- setSandboxUiMounted(false)
- setSandboxUiConversationOrigin(null)
- setHeaderShellOverlayOpen(false)
- setSidebarSettingsMenuOpen(false)
- }, [])
-
- // A failed open (rejected by main, or failed before reaching it) clears only
- // the React state. The active tab stays the embed's owner: a failure before
- // the open IPC leaves the previous view live in main, and only an owner makes
- // the deactivation effect `close()` it when the user leaves the tab. When main
- // already tore the view down, that `close()` is a harmless no-op.
- const handleSandboxUiOpenFailed = React.useCallback(() => {
- setActiveSandboxUiApp(null)
- setSandboxUiMounted(false)
- setSandboxUiConversationOrigin(null)
- setHeaderShellOverlayOpen(false)
- setSidebarSettingsMenuOpen(false)
- }, [])
-
React.useEffect(() => {
setNotificationDrawerReady(false)
}, [activeSandboxUiApp?.appRef, headerNotificationTrayOpen])
@@ -1433,153 +1506,46 @@ export function App() {
if (chatDrawerVisible) setChatDrawerReady(true)
}, [appNotificationDrawerOpen, chatDrawerVisible])
- // The launch half of an activation. It writes no activation of its own, so it
- // must run inside `activateAndLaunch`, in the same commit as the tab it targets.
- const beginSandboxUiLaunch = React.useCallback(
- (
- app: ActiveSandboxUiApp,
- conversationOrigin: SandboxUiConversationOrigin | null,
- targetTabId: string
- ) => {
- const requestId = sandboxUiShortcutOpenRequestIdRef.current + 1
- sandboxUiShortcutOpenRequestIdRef.current = requestId
- setSandboxUiMounted(false)
+ // The conversation an app launch was opened from comes along into the drawer,
+ // committed with the launch's own tab so the drawer opens over it.
+ const seedLaunchConversation = React.useCallback(
+ (conversationOrigin: SandboxUiConversationOrigin | null) => {
setSandboxUiConversationOrigin(conversationOrigin)
- setActiveSandboxUiApp(app)
- launchTargetTabIdRef.current = targetTabId
- setSandboxUiShortcutOpenRequestId(requestId)
- if (conversationOrigin) {
- // Opened from a chat: bring that conversation straight into the drawer
- // instead of the destroy-and-reconstitute round-trip. The embed stays
- // live; `keepNavItem` records a pending selection that survives the
- // `apps` route change and loads the chat. The reconcile effect adds the
- // chat tab to the switcher.
- setChatDrawerOpen(true)
- vm.handleSelectChatAgent(conversationOrigin.agentName, {
- chatId: conversationOrigin.chatId,
- title: conversationOrigin.title,
- selectLatest: false,
- keepNavItem: true,
- })
- }
- return requestId
+ if (!conversationOrigin) return
+ // Opened from a chat: bring that conversation straight into the drawer
+ // instead of the destroy-and-reconstitute round-trip. `keepNavItem`
+ // records a pending selection that survives the `apps` route change and
+ // loads the chat. The reconcile effect adds the chat tab to the switcher.
+ setChatDrawerOpen(true)
+ vm.handleSelectChatAgent(conversationOrigin.agentName, {
+ chatId: conversationOrigin.chatId,
+ title: conversationOrigin.title,
+ selectLatest: false,
+ keepNavItem: true,
+ })
},
[vm.handleSelectChatAgent]
)
// Grid and deep-link launches: always a new app tab (apps never dedupe by
// appRef). Its `kind:'app'` derives `navItem` to the Apps route this commit.
const launchSandboxUiApp = React.useCallback(
- (app: ActiveSandboxUiApp, conversationOrigin: SandboxUiConversationOrigin | null) => {
+ (
+ app: ActiveSandboxUiApp,
+ conversationOrigin: SandboxUiConversationOrigin | null
+ ): LaunchId | null => {
const tabId = nextChatTabId()
- let requestId = 0
- activateAndLaunch(
+ return activateAndLaunch(
state => openAppTab(state, { id: tabId, appRef: app.appRef, title: app.label }),
- () => {
- requestId = beginSandboxUiLaunch(app, conversationOrigin, tabId)
- }
+ () => seedLaunchConversation(conversationOrigin),
+ { kind: 'newTab', tabId, app }
)
- return requestId
},
- [activateAndLaunch, beginSandboxUiLaunch, nextChatTabId]
+ [activateAndLaunch, nextChatTabId, seedLaunchConversation]
)
- // Relaunch of a backgrounded app tab, reached only from `revealWorkspaceTab`
- // inside the activating gesture's seam. The re-select keeps the store on the
- // tab being launched when a pending store update moved the active tab, as long
- // as that tab still exists; a tab the pending update removed is not restored.
- relaunchSandboxUiAppRef.current = (app, tabId) => {
- setWorkspaceTabs(state => selectWorkspaceTab(state, tabId))
- beginSandboxUiLaunch(app, null, tabId)
- }
- // Store-governed embed lifecycle (mini-spec 05 §3, replaces the old
- // SandboxUiPage unmount-cleanup close). The live embed belongs to whichever
- // app tab is active; when that changes, the OUTGOING app's route is persisted
- // and the embed is closed — UNLESS another app tab is taking over, in which
- // case the incoming `open()` replaces the embed in the driver (one-at-a-time,
- // guarded by `mountGeneration`), so a redundant `close()` here would risk
- // closing the freshly-opened view. This effect is the single SOLICITED
- // `close()` emitter for deactivation.
- const activeSandboxUiTabId =
- !vm.appsPickerActive && vm.activeWorkspaceTab?.kind === 'app' ? vm.activeWorkspaceTab.id : null
- React.useEffect(() => {
- const launchTargetTabId = launchTargetTabIdRef.current
- launchTargetTabIdRef.current = null
- const outgoingTabId = liveSandboxUiTabIdRef.current
- if (outgoingTabId === activeSandboxUiTabId) return
- const replacedByAnotherApp =
- activeSandboxUiTabId !== null && launchTargetTabId === activeSandboxUiTabId
- // An app tab activated without a launch hosts no embed: it stays unowned
- // until a relaunch arms it (`handleSandboxUiOpening`).
- liveSandboxUiTabIdRef.current = replacedByAnotherApp ? activeSandboxUiTabId : null
- // This is the single point where the active embed transitions; bump the
- // generation so any older in-flight continuation knows it no longer owns
- // the active view.
- sandboxUiActivationGenRef.current += 1
- if (outgoingTabId === null) return
- // The Apps route stays mounted when the incoming app tab gets no launch:
- // drop the page's launch state too, or it keeps the outgoing app's chrome
- // over an empty slot. The close below stays the only solicited one.
- if (activeSandboxUiTabId !== null && !replacedByAnotherApp) {
- setSandboxActionRequest(previous => ({ id: (previous?.id ?? 0) + 1, action: 'release' }))
- }
- if (!replacedByAnotherApp) {
- // Deactivating to a non-app surface (chat/files/settings via strip, sidebar
- // nav, or closing the tab): drop the embed's React state now so anything
- // gated on a live app (drawer-with-embed) reacts in this commit. On an
- // app→app switch the incoming launch already owns this
- // state, so leave it. This restores the reset the removed unmount cleanup
- // used to do for paths that never call `leaveSandboxForChat` (sidebar nav).
- setActiveSandboxUiApp(null)
- setSandboxUiMounted(false)
- }
- // Read optimistically, persist, then close in a microtask — the visual tab
- // switch (already committed above) must not block on the IPC (§4). A read
- // failure (out-of-prefix throw, destroyed webContents → null) falls back to
- // the default route rather than blocking the switch.
- //
- // app→app ordering: the incoming `open()` is dispatched by SandboxUiPage's
- // child effect (the shortcut-open effect), which runs BEFORE this parent
- // effect AND gates its `open()` IPC behind `waitForEmbedSlotRect` (an rAF
- // loop). This parent effect's `getLocation()` invoke below is dispatched
- // synchronously here — after `open()` STARTED but before its rAF resolves —
- // so `getLocation` reaches main (and reads the still-live outgoing view)
- // strictly before `open()` tears it down. i.e. the read is captured before
- // the incoming open, not merely "usually first".
- const gen = sandboxUiActivationGenRef.current
- // The app the outgoing tab hosts. Its appRef is immutable for the tab's
- // lifetime, so capturing it now (before the read) is safe.
- const outgoingAppRef = workspaceTabsRef.current.tabs.find(
- tab => tab.id === outgoingTabId && tab.kind === 'app'
- )?.app?.appRef
- void (async () => {
- // §3 (mini-spec 08): only the outgoing tab's OWN app decides its saved
- // route. On an app→app switch the incoming `open()` can reach main before
- // this `getLocation()` resolves, so the read may surface the INCOMING app's
- // location; a foreign or failed read must PRESERVE tab A's route (leave the
- // store untouched), NOT clear it — passing `undefined` to the setter would
- // erase A's previously-saved route. Persist only when the read is A's own:
- // its routePath (set), or clear when A is back on its default path.
- const decision = await readOutgoingRouteDecision(outgoingAppRef)
- // A newer activation took over while the read was in flight (the same app
- // reopened, or another app/surface became active): the read value belongs
- // to a view that is no longer the active one, so abort BOTH the persist
- // (it would clobber the live tab's route with a stale one) and the close
- // (it would tear down the embed the user is now looking at).
- if (gen !== sandboxUiActivationGenRef.current) return
- // A foreign/unknown read owns no route on this tab — leave it as it was.
- if (decision.action !== 'preserve') {
- const nextRoutePath = decision.action === 'set' ? decision.routePath : undefined
- // No-op when the outgoing tab was closed (§3: closing a tab does not save).
- setWorkspaceTabs(state => setAppTabSavedRoutePath(state, outgoingTabId, nextRoutePath))
- }
- if (replacedByAnotherApp) return
- try {
- await window.clerum.sandboxUi.close()
- } catch {
- // Idempotent: an unsolicited close may have torn it down already.
- }
- })()
- }, [activeSandboxUiTabId, setWorkspaceTabs])
+ const handleBackToApps = React.useCallback(() => {
+ embed.dispatch({ type: 'backToApps' })
+ }, [embed])
const handleSidebarNavSelect = React.useCallback(
(item: NavItem) => {
@@ -1616,9 +1582,6 @@ export function App() {
if (linkId === undefined || processingSandboxUiDeepLinkIdRef.current === linkId) {
processingSandboxUiDeepLinkIdRef.current = null
}
- if (linkId === undefined || launchingSandboxUiDeepLinkRef.current?.linkId === linkId) {
- launchingSandboxUiDeepLinkRef.current = null
- }
}, [])
const acknowledgeSandboxUiDeepLink = React.useCallback(
@@ -1709,42 +1672,66 @@ export function App() {
[deferSandboxUiDeepLink, restoreSandboxUiDeepLinkTeam]
)
- const closeActiveSandboxUiEmbedForHandoff = React.useCallback(async () => {
- if (!activeSandboxUiApp) return
- // §3 consistency: persist the outgoing app tab's route before tearing the
- // embed down for a deep-link handoff, so returning to that tab restores
- // where the user was rather than the default/stale route. Same read-then-
- // close as the deactivation effect (try/catch → undefined on failure); read
- // BEFORE `close()` destroys the webContents. `handleSandboxUiClosed` clears
- // the ref, so snapshot the outgoing tab id first.
- const outgoingTabId = liveSandboxUiTabIdRef.current
- // The handoff itself transitions the active embed; bump the generation (so an
- // older in-flight deactivation continuation aborts) and own the new one by
- // capturing AFTER the bump. If a newer activation supersedes this handoff
- // while the read below is in flight, gen no longer matches and both the
- // persist and the close are aborted.
- sandboxUiActivationGenRef.current += 1
- const gen = sandboxUiActivationGenRef.current
- if (outgoingTabId !== null) {
- // §3 (mini-spec 08), identical to the deactivation effect: only the
- // outgoing tab's OWN app may set/clear its saved route. A foreign or failed
- // read PRESERVES it (the setter is not called) rather than clobbering it
- // with another app's route or erasing it with `undefined`. appRef is
- // immutable for the tab, so capturing it before the read is safe.
- const outgoingAppRef = workspaceTabsRef.current.tabs.find(
- tab => tab.id === outgoingTabId && tab.kind === 'app'
- )?.app?.appRef
- const decision = await readOutgoingRouteDecision(outgoingAppRef)
- if (gen !== sandboxUiActivationGenRef.current) return
- if (decision.action !== 'preserve') {
- const nextRoutePath = decision.action === 'set' ? decision.routePath : undefined
- setWorkspaceTabs(state => setAppTabSavedRoutePath(state, outgoingTabId, nextRoutePath))
+ // A cross-team link switches teams, which does not end the embed session, so
+ // the live view is handed off first: ownership drops and the switch waits
+ // until main has released every view this renderer still had, each leaving
+ // its route on its tab. Resolves `false` when App went away meanwhile.
+ const handoffSeqRef = React.useRef(0)
+ const handOffEmbedBeforeTeamSwitch = React.useCallback(async (): Promise<boolean> => {
+ const lifetime = embedLifetimeRef.current!
+ if (lifetime.disposed) return false
+ const requestId = ++handoffSeqRef.current
+ const ready = new Promise<void>(resolve => handoffWaitersRef.current.set(requestId, resolve))
+ embed.dispatch({ type: 'handoff', requestId })
+ await Promise.race([ready, lifetime.unmounted])
+ handoffWaitersRef.current.delete(requestId)
+ return !lifetime.disposed
+ }, [embed])
+
+ // What a deep link does once its launch settled. Mounted: done. Failed: retried
+ // with the failure's message until the retry budget runs out. Abandoned (the
+ // user left its tab before it mounted): dropped without a retry, which would
+ // reopen an app the user walked away from, and the team it switched to is
+ // given back.
+ const finishSandboxUiDeepLinkLaunch = React.useCallback(
+ async (context: PendingSandboxUiDeepLinkLaunch, launchId: LaunchId, outcome: LaunchOutcome) => {
+ if (context.generation !== sandboxUiDeepLinkGenerationRef.current) {
+ clearSandboxUiDeepLinkProcessing(context.linkId)
+ return
}
- }
- if (gen !== sandboxUiActivationGenRef.current) return
- await window.clerum.sandboxUi.close()
- handleSandboxUiClosed()
- }, [activeSandboxUiApp, handleSandboxUiClosed, setWorkspaceTabs])
+ const pending = pendingSandboxUiDeepLinksRef.current.find(
+ item => item.link.id === context.linkId
+ )
+ if (!pending) {
+ clearSandboxUiDeepLinkProcessing(context.linkId)
+ return
+ }
+ if (outcome === 'mounted') {
+ await acknowledgeSandboxUiDeepLink(context.linkId)
+ return
+ }
+ if (outcome === 'abandoned') {
+ await restoreSandboxUiDeepLinkTeam(context)
+ await acknowledgeSandboxUiDeepLink(context.linkId)
+ return
+ }
+ const failure = embed.getSnapshot().failure
+ await deferSandboxUiDeepLinkUntilTerminal(
+ pending,
+ failure?.launchId === launchId
+ ? embedFailureMessage(failure)
+ : 'The native app view did not mount',
+ context
+ )
+ },
+ [
+ acknowledgeSandboxUiDeepLink,
+ clearSandboxUiDeepLinkProcessing,
+ deferSandboxUiDeepLinkUntilTerminal,
+ embed,
+ restoreSandboxUiDeepLinkTeam,
+ ]
+ )
React.useEffect(() => {
const enqueue = (link: SandboxUiDeepLinkEnvelope) => {
@@ -1768,27 +1755,6 @@ export function App() {
return unsubscribe
}, [setPendingSandboxUiDeepLinkState])
- // Name the live app tab after the embed's `document.title` (mini-spec 06 §2).
- // Only the tab whose embed is live (`liveSandboxUiTabIdRef`) is renamed, and
- // only when the event comes from the current launch, so a late title event
- // from a torn-down embed (even one of the same app being relaunched) can't
- // relabel whichever view is live now. The launchId alone is enough: main tags
- // each event with the appRef/launchId pair of the open that created the view,
- // and every open goes through `beginSandboxUiLaunch` inside `activateAndLaunch`,
- // which activates a tab of that same app in the commit that publishes the
- // launchId — so whenever the launchId is current, the live tab (if any) holds
- // the event's app. The store ignores empty titles, so the tab keeps its
- // `app.label` until a real title arrives.
- React.useEffect(() => {
- const off = window.clerum.sandboxUi.onTitleChanged?.(({ launchId, title }) => {
- if (launchId !== currentSandboxUiLaunchIdRef.current) return
- const tabId = liveSandboxUiTabIdRef.current
- if (!tabId) return
- setWorkspaceTabs(state => setAppTabTitle(state, tabId, title))
- })
- return () => off?.()
- }, [setWorkspaceTabs])
-
React.useEffect(() => {
if (
!canProcessSandboxUiDeepLinks(
@@ -1858,7 +1824,7 @@ export function App() {
return
}
if (pending.link.teamId && pending.link.teamId !== currentTeamId) {
- await closeActiveSandboxUiEmbedForHandoff()
+ if (!(await handOffEmbedBeforeTeamSwitch())) return
try {
const didSwitchTeam = await vm.handleEnsureTeamContext({
teamId: pending.link.teamId,
@@ -1879,7 +1845,6 @@ export function App() {
if (isTransientSandboxUiTeamContextError(error)) {
const launchContext: PendingSandboxUiDeepLinkLaunch = {
linkId: pending.link.id,
- requestId: 0,
generation: processingGeneration,
originalTeamId,
linkTeamId: pending.link.teamId,
@@ -1911,7 +1876,6 @@ export function App() {
if (resolution.status === 'starting') {
const launchContext: PendingSandboxUiDeepLinkLaunch = {
linkId: pending.link.id,
- requestId: 0,
generation: processingGeneration,
originalTeamId,
linkTeamId: pending.link.teamId,
@@ -1926,22 +1890,33 @@ export function App() {
)
return
}
- const requestId = launchSandboxUiApp(
+ const launchId = launchSandboxUiApp(
{
...resolution.app,
...(pending.link.path ? { routePath: pending.link.path } : {}),
},
pending.conversationOrigin ?? sandboxUiConversationOrigin
)
- launchingSandboxUiDeepLinkRef.current = {
- linkId: pending.link.id,
- requestId,
- generation: processingGeneration,
- originalTeamId,
- linkTeamId: pending.link.teamId,
- switchedTeam,
- conversationOrigin: pending.conversationOrigin,
+ if (launchId === null) {
+ clearSandboxUiDeepLinkProcessing(pending.link.id)
+ return
}
+ // The link stays the one being processed until its launch settles, so
+ // the queue moves on only after it mounted, failed or was left.
+ const outcome = await awaitLaunchOutcome(launchId)
+ if (outcome === null) return
+ await finishSandboxUiDeepLinkLaunch(
+ {
+ linkId: pending.link.id,
+ generation: processingGeneration,
+ originalTeamId,
+ linkTeamId: pending.link.teamId,
+ switchedTeam,
+ conversationOrigin: pending.conversationOrigin,
+ },
+ launchId,
+ outcome
+ )
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
vm.pushToast(`Could not open app link: ${message}`, 'error')
@@ -1953,7 +1928,6 @@ export function App() {
}
await restoreSandboxUiDeepLinkTeam({
linkId: pending.link.id,
- requestId: 0,
generation: processingGeneration,
originalTeamId,
linkTeamId: pending.link.teamId,
@@ -1965,11 +1939,12 @@ export function App() {
})()
}, [
acknowledgeSandboxUiDeepLink,
- activeSandboxUiApp,
+ awaitLaunchOutcome,
bootSplashLoading,
- closeActiveSandboxUiEmbedForHandoff,
clearSandboxUiDeepLinkProcessing,
deferSandboxUiDeepLinkUntilTerminal,
+ finishSandboxUiDeepLinkLaunch,
+ handOffEmbedBeforeTeamSwitch,
launchSandboxUiApp,
pendingSandboxUiDeepLinks,
restoreSandboxUiDeepLinkTeam,
@@ -1996,38 +1971,6 @@ export function App() {
return () => window.clearTimeout(timeoutId)
}, [pendingSandboxUiDeepLinks, sandboxUiDeepLinkRetryTick])
- const handleSandboxUiShortcutOpenResult = React.useCallback(
- async (requestId: number, result: SandboxUiShortcutOpenResult) => {
- const launch = launchingSandboxUiDeepLinkRef.current
- if (!launch || launch.requestId !== requestId) return
- if (launch.generation !== sandboxUiDeepLinkGenerationRef.current) {
- clearSandboxUiDeepLinkProcessing(launch.linkId)
- return
- }
- const pending = pendingSandboxUiDeepLinksRef.current.find(
- item => item.link.id === launch.linkId
- )
- if (!pending) {
- clearSandboxUiDeepLinkProcessing(launch.linkId)
- return
- }
- if (result.status === 'mounted') {
- await acknowledgeSandboxUiDeepLink(launch.linkId)
- return
- }
- await deferSandboxUiDeepLinkUntilTerminal(
- pending,
- result.message || 'The native app view did not mount',
- launch
- )
- },
- [
- acknowledgeSandboxUiDeepLink,
- clearSandboxUiDeepLinkProcessing,
- deferSandboxUiDeepLinkUntilTerminal,
- ]
- )
-
// Reconcile the chat sub-slice of the universal store from the vm's displayed
// chat. Runs for the full-screen chat route AND whenever the drawer is visible,
// so any path that moves `vm.activeChatId` — the ChatThread session list, an
@@ -2096,8 +2039,6 @@ export function App() {
setSidebarToggleRequestId(0)
setChatLocalSearchOpen(false)
setSandboxLocalSearchRequestId(0)
- setSandboxActionRequest(null)
- setSandboxUiMounted(false)
setCommandPaletteOpen(false)
setCommandPaletteReturnToSandbox(false)
setSettingsShortcutsRequestId(0)
@@ -2178,7 +2119,11 @@ export function App() {
const selectAndReveal = (update: (current: WorkspaceTabsState) => WorkspaceTabsState) => {
const projected = update(state)
if (projected === state) return
- activateAndLaunch(update, () => revealWorkspaceTab(activeWorkspaceTab(projected), false))
+ activateAndLaunch(
+ update,
+ () => revealWorkspaceTab(activeWorkspaceTab(projected), false),
+ ACTIVE_TAB_LAUNCH
+ )
}
if (commandId === 'commands.open') {
closeChatLocalSearch(false)
@@ -2246,9 +2191,12 @@ export function App() {
setSidebarToggleRequestId(value => value + 1)
return
}
- if (commandId === 'app.refresh' || commandId === 'app.backToApps') {
- const action = commandId === 'app.refresh' ? 'refresh' : 'back-to-apps'
- setSandboxActionRequest(previous => ({ id: (previous?.id ?? 0) + 1, action }))
+ if (commandId === 'app.refresh') {
+ relaunchActiveApp()
+ return
+ }
+ if (commandId === 'app.backToApps') {
+ handleBackToApps()
return
}
if (commandId === 'chat.newTab') {
@@ -2304,7 +2252,8 @@ export function App() {
} else {
activateAndLaunch(
current => current,
- () => revealWorkspaceTab(activeWorkspaceTab(state), false)
+ () => revealWorkspaceTab(activeWorkspaceTab(state), false),
+ ACTIVE_TAB_LAUNCH
)
}
setComposerFocusRequestId(value => value + 1)
@@ -2332,10 +2281,12 @@ export function App() {
closeCommandPalette,
commandPaletteOpen,
desktopCommandContext,
+ handleBackToApps,
handleCloseWorkspaceTab,
handleNewWorkspaceChatTab,
handleSidebarNavSelect,
openChatDrawer,
+ relaunchActiveApp,
revealWorkspaceTab,
sandboxUiMounted,
vm.activeChatId,
@@ -2993,8 +2944,10 @@ export function App() {
{vm.navItem === DESKTOP_ROUTES.plugins && <WorkflowsPage />}
{vm.navItem === DESKTOP_ROUTES.apps && (
<SandboxUiPage
+ embed={embed}
+ activeAppRef={activeTabAppRef}
+ refreshError={embedRefreshError}
boundsRefreshKey={sandboxUiBoundsRefreshKey}
- actionRequest={sandboxActionRequest}
currentTeamId={vm.currentTeamId}
headerShellOverlayOpen={
headerShellOverlayOpen || commandPaletteOpen
@@ -3002,20 +2955,14 @@ export function App() {
sidebarShellOverlayOpen={sidebarSettingsMenuOpen}
toastShellOverlayOpen={vm.toasts.length > 0}
deepLinkShellOverlayOpen={sandboxUiDeepLinkDialog !== null}
- shortcutApp={activeSandboxUiApp}
- shortcutOpenRequestId={sandboxUiShortcutOpenRequestId}
localSearchRequestId={sandboxLocalSearchRequestId}
titlebarLeadingContainer={titlebarLeadingRoot}
onLaunchApp={handleOpenSandboxUiApp}
- onEmbeddedAppOpening={handleSandboxUiOpening}
- onEmbeddedAppMounted={handleSandboxUiMounted}
- onEmbeddedAppBack={handleSandboxUiClosed}
- onEmbeddedAppOpenFailed={handleSandboxUiOpenFailed}
+ onRelaunch={relaunchActiveApp}
onEmbedBoundsApplied={handleSandboxUiBoundsApplied}
onEmbedSlotTopChange={setChatDrawerEmbedTop}
onEmbedSlotRightChange={setNotificationTrayLeft}
onNotify={vm.pushToast}
- onShortcutOpenResult={handleSandboxUiShortcutOpenResult}
/>
)}
{vm.navItem === DESKTOP_ROUTES.settings && (
diff --git a/desktop-app/ui/src/App.types.ts b/desktop-app/ui/src/App.types.ts
index fbf286be4..b4e1e086e 100644
--- a/desktop-app/ui/src/App.types.ts
+++ b/desktop-app/ui/src/App.types.ts
@@ -1,5 +1,6 @@
import type { SandboxUiDeepLinkEnvelope } from '@clerum/desktop-app-links'
import type { SandboxUiConversationOrigin } from '@pages/SandboxUiPage.types'
+import type { ActiveSandboxUiApp } from '@/uiTypes'
export type { SandboxUiDeepLinkEnvelope } from '@clerum/desktop-app-links'
@@ -12,3 +13,18 @@ export type PendingSandboxUiDeepLink = {
nextRetryAt?: number
failedMessage?: string
}
+
+/**
+ * Which launch a gesture asks for once its commit landed. `activeTab` (reveal
+ * gestures, and Refresh/Reopen/Retry with `replace`) launches the app tab the
+ * commit left active, so the launch always names the tab that is actually
+ * shown. `newTab` (grid pick, deep link) launches the tab the gesture opened.
+ */
+export type EmbedLaunchPlan =
+ /**
+ * `onlyIfActivated`: launch only when the commit changed which app tab is
+ * active, so a gesture that leaves the active tab alone (closing another tab)
+ * does not relaunch it.
+ */
+ | { kind: 'activeTab'; replace?: boolean; onlyIfActivated?: boolean }
+ | { kind: 'newTab'; tabId: string; app: ActiveSandboxUiApp }
diff --git a/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx b/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx
index d817bf692..09cda3538 100644
--- a/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx
@@ -20,6 +20,7 @@ import { mapKindToRoute } from '@lib/workspaceTabsRoute'
import { App } from '@/App'
import type { SandboxUiDeepLinkEnvelope } from '@/App.types'
import { openGfsResourcePayload, resolvedFile } from '@/gfs/__fixtures__/gfsProducerFixtures'
+import { type SandboxUiMainFake, createSandboxUiMainFake } from './__fixtures__/sandboxUiMainFake'
// Every gesture that activates an app tab must do it through App's single
// activation seam, which commits the store and the launch together under
@@ -270,26 +271,20 @@ const MEASURED_SLOT = {
toJSON: () => ({}),
} as DOMRect
-function makeSandboxUiBridge() {
+function makeSandboxUiBridge(main: SandboxUiMainFake) {
return {
+ ...main.bridge,
listApps: vi.fn().mockResolvedValue({ apps: APP_LISTING }),
listPendingDeepLinks: vi.fn().mockResolvedValue({ links: [] }),
clearPendingDeepLinks: vi.fn().mockResolvedValue(undefined),
acknowledgeDeepLink: vi.fn().mockResolvedValue(undefined),
onDeepLink: vi.fn(() => vi.fn()),
- onTitleChanged: vi.fn(() => vi.fn()),
- onClosed: vi.fn(() => vi.fn()),
- onRefreshError: vi.fn(() => vi.fn()),
onFindResult: vi.fn(() => vi.fn()),
- open: vi.fn().mockResolvedValue(undefined),
- close: vi.fn().mockResolvedValue(undefined),
- getLocation: vi.fn().mockResolvedValue(null),
setVisible: vi.fn().mockResolvedValue(undefined),
setBounds: vi.fn().mockResolvedValue(undefined),
capturePreview: vi.fn().mockResolvedValue(null),
stopFindInPage: vi.fn().mockResolvedValue(undefined),
focusActive: vi.fn().mockResolvedValue(true),
- reload: vi.fn().mockResolvedValue(undefined),
}
}
@@ -316,6 +311,7 @@ describe('App activates app tabs only through its activation seam', () => {
let openGfsResourceCb: ((resource: OpenGfsPayload) => void) | null
let shortcutCommandCb: ShortcutListener | null
let sandboxUi: ReturnType<typeof makeSandboxUiBridge>
+ let main: SandboxUiMainFake
beforeEach(() => {
vi.clearAllMocks()
@@ -347,7 +343,8 @@ describe('App activates app tabs only through its activation seam', () => {
}
)
vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(MEASURED_SLOT)
- sandboxUi = makeSandboxUiBridge()
+ main = createSandboxUiMainFake()
+ sandboxUi = makeSandboxUiBridge(main)
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
@@ -504,14 +501,9 @@ describe('App activates app tabs only through its activation seam', () => {
await openFromSidebar(ALPHA, 1)
// A title from the live embed renames its tab.
- const openRequest = sandboxUi.open.mock.calls[0]![0] as { launchId: string }
- act(() =>
- latestListener<{ appRef: string; launchId: string; title: string }>(sandboxUi.onTitleChanged)(
- { appRef: ALPHA!.appRef, launchId: openRequest.launchId, title: 'Alpha Inbox' }
- )
- )
+ act(() => main.retitle('Alpha Inbox'))
// Leaving the app persists its route, and a plugin handoff opens a preview.
- sandboxUi.getLocation.mockResolvedValue({ appRef: ALPHA!.appRef, routePath: '/inbox' })
+ main.navigate('/inbox')
const payload = await openGfsResourcePayload(
resolvedFile('md1', 'README.md', { gfsUri: 'gfs://main/md1' })
)
@@ -542,12 +534,8 @@ describe('App activates app tabs only through its activation seam', () => {
async function renderWithRetitledLiveAlpha(gesture: () => void) {
await renderApp()
await openFromSidebar(ALPHA, 1)
- const openRequest = sandboxUi.open.mock.calls[0]![0] as { launchId: string }
- const titleListener = latestListener<{ appRef: string; launchId: string; title: string }>(
- sandboxUi.onTitleChanged
- )
act(() => {
- titleListener({ appRef: ALPHA!.appRef, launchId: openRequest.launchId, title: 'Alpha Inbox' })
+ main.retitle('Alpha Inbox')
gesture()
})
await flushMacrotask()
diff --git a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
index 2a9fad2a8..40d357c75 100644
--- a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { useReducer } from 'react'
+import { useLayoutEffect, useReducer } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useNotificationsContext } from '@contexts/NotificationsContext'
import { QueryClientProvider, useInfiniteQuery, useQueries, useQuery } from '@tanstack/react-query'
@@ -7,6 +7,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libra
import { DESKTOP_ROUTES } from '@constants/navigation'
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import { useAppController } from '@hooks/useAppController'
+import type { EmbedOwnershipMachine } from '@lib/embedOwnershipMachine.types'
import type { GfsPreviewResource } from '@lib/gfsPreview'
import { desktopQueryClient } from '@lib/queryClient'
import {
@@ -79,8 +80,7 @@ const sidebarHarness = vi.hoisted(() => ({
}))
const sandboxUiPageHarness = vi.hoisted(() => ({
props: null as null | {
- onEmbeddedAppMounted?: () => void
- onEmbeddedAppBack?: () => void
+ embed: EmbedOwnershipMachine
onEmbedBoundsApplied?: () => void
onEmbedSlotTopChange?: (topPx: number) => void
onEmbedSlotRightChange?: (rightPx: number) => void
@@ -156,9 +156,15 @@ vi.mock('@pages/ContextsPage', () => ({ ContextsPage: () => null }))
vi.mock('@pages/FilesPage', () => ({ FilesPage: () => null }))
vi.mock('@pages/FilePreviewPage', () => ({ FilePreviewPage: () => null }))
vi.mock('@pages/McpServersPage', () => ({ McpServersPage: () => null }))
+// Like the real page, the stub measures the slot for each launch while mounted.
vi.mock('@pages/SandboxUiPage', () => ({
SandboxUiPage: (props: NonNullable<typeof sandboxUiPageHarness.props>) => {
sandboxUiPageHarness.props = props
+ const { embed } = props
+ useLayoutEffect(
+ () => embed.registerMeasurer(async () => ({ x: 0, y: 0, width: 400, height: 300 })),
+ [embed]
+ )
return null
},
}))
@@ -614,7 +620,7 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {
// embed acks its bounds and the drawer is READY — bumping on visibility alone
// would open the option list while still inert, leaving it unfocused. This pins
// that ordering at the observable level: options appear only after ready.
- it('defers the chat.switcher open until the drawer is ready, not merely visible', () => {
+ it('defers the chat.switcher open until the drawer is ready, not merely visible', async () => {
currentController = makeController({
selectedAgent: 'alpha',
activeChatId: 'chat-1',
@@ -640,6 +646,7 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {
setVisible: vi.fn().mockResolvedValue(undefined),
setBounds: vi.fn().mockResolvedValue(undefined),
focusActive: vi.fn().mockResolvedValue(true),
+ open: vi.fn().mockResolvedValue(undefined),
close: vi.fn().mockResolvedValue(undefined),
},
} as unknown as Window['clerum'],
@@ -657,7 +664,11 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {
defaultPath: '/',
})
})
- act(() => sandboxUiPageHarness.props?.onEmbeddedAppMounted?.())
+ // main mounts the launch.
+ await waitFor(() => {
+ const state = sandboxUiPageHarness.props!.embed.getSnapshot()
+ expect(state.owner && state.views.get(state.owner)?.phase).toBe('mounted')
+ })
act(() => appHeaderHarness.props?.onToggleChatDrawer?.())
expect(appHeaderHarness.props?.chatDrawerOpen).toBe(false)
@@ -797,7 +808,8 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {
})
expect(appHeaderHarness.props?.notificationTrayLeft).toBe(716)
- act(() => sandboxUiPageHarness.props?.onEmbeddedAppBack?.())
+ // Back to apps: the embed is gone while the tab stays.
+ act(() => sandboxUiPageHarness.props?.embed.dispatch({ type: 'backToApps' }))
expect(appHeaderHarness.props?.notificationTrayMode).toBe('overlay')
expect(appHeaderHarness.props?.notificationTrayLeft).toBeNull()
diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
index ca15a4c46..4d8fc1e53 100644
--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@ -1,10 +1,11 @@
// @vitest-environment jsdom
-import { type ReactNode, useEffect, useReducer } from 'react'
+import { type ReactNode, useEffect, useLayoutEffect, useReducer } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render, waitFor } from '@testing-library/react'
import { renderToStaticMarkup } from 'react-dom/server'
import { DESKTOP_ROUTES, SIDEBAR_COLLAPSED_KEY } from '@constants/navigation'
import { useAppController } from '@hooks/useAppController'
+import type { EmbedOwnershipMachine } from '@lib/embedOwnershipMachine.types'
import {
activeWorkspaceTab,
createWorkspaceTabsState,
@@ -12,12 +13,12 @@ import {
openChatTab,
openFilesTab,
openSettingsTab,
- setAppTabSavedRoutePath,
} from '@lib/workspaceTabs'
import { mapKindToRoute, settingsSectionForRoute } from '@lib/workspaceTabsRoute'
import { App } from '@/App'
import type { SandboxUiDeepLinkEnvelope } from '@/App.types'
import type { DesktopCommandId } from '../../../src/desktopCommands'
+import { type SandboxUiMainFake, createSandboxUiMainFake } from './__fixtures__/sandboxUiMainFake'
// The universal tab store lives inside the controller; the mock reproduces that
// contract — `navItem` is DERIVED from the store, the store is reactive, and nav
@@ -58,6 +59,7 @@ const appHeaderHarness = vi.hoisted(() => ({
placement?: 'default' | 'titlebar'
searchFocusRequestId?: number
notificationOpenRequestId?: number
+ onShellOverlayOpenChange?: (open: boolean) => void
},
}))
@@ -84,36 +86,13 @@ const sidebarHarness = vi.hoisted(() => ({
const sandboxUiPageHarness = vi.hoisted(() => ({
props: null as null | {
+ embed: EmbedOwnershipMachine
headerShellOverlayOpen?: boolean
deepLinkShellOverlayOpen?: boolean
- shortcutApp?: {
- appRef: string
- label?: string
- defaultPath?: string
- routePath?: string
- } | null
- shortcutOpenRequestId?: number
localSearchRequestId?: number
- actionRequest?: {
- id: number
- action: 'refresh' | 'back-to-apps'
- } | null
- onEmbeddedAppOpening?: (app: {
- appRef: string
- label: string
- icon?: string | null
- defaultPath: string
- routePath?: string
- }) => void
- onEmbeddedAppMounted?: () => void
- onEmbeddedAppBack?: () => void
- onEmbeddedAppOpenFailed?: () => void
- onShortcutOpenResult?: (
- requestId: number,
- result: { status: 'mounted' } | { status: 'failed'; message: string }
- ) => void | Promise<void>
},
}))
+const SLOT_BOUNDS = { x: 16, y: 12, width: 400, height: 300, dpr: 1 }
vi.mock('@hooks/useAppController', () => ({
useAppController: vi.fn(),
@@ -172,9 +151,13 @@ vi.mock('@pages/AuthPage', () => ({ AuthPage: () => null }))
vi.mock('@pages/ChatPage', () => ({ ChatPage: () => null }))
vi.mock('@pages/FilesPage', () => ({ FilesPage: () => null }))
vi.mock('@pages/McpServersPage', () => ({ McpServersPage: () => null }))
+// The page is stubbed, but like the real one it measures the slot for every
+// launch while it is mounted, so launches reach main.
vi.mock('@pages/SandboxUiPage', () => ({
SandboxUiPage: (props: NonNullable<typeof sandboxUiPageHarness.props>) => {
sandboxUiPageHarness.props = props
+ const { embed } = props
+ useLayoutEffect(() => embed.registerMeasurer(async () => SLOT_BOUNDS), [embed])
return null
},
}))
@@ -373,11 +356,9 @@ describe('App deep-link orchestration', () => {
const acknowledgeDeepLink = vi.fn().mockResolvedValue(undefined)
const listApps = vi.fn().mockResolvedValue({ apps: [] })
const listPendingDeepLinks = vi.fn().mockResolvedValue({ links: [] })
- const closeSandboxUi = vi.fn().mockResolvedValue(undefined)
- // Route-persistence read (mini-spec 05). Defaults to "on the default route"
- // (null) so unrelated launch/deactivation tests behave exactly as before;
- // the persistence tests override the resolved value per case.
- const getSandboxUiLocation = vi.fn().mockResolvedValue(null)
+ let main: SandboxUiMainFake
+ const closeSandboxUi = () => main.bridge.close
+ const openSandboxUi = () => main.bridge.open
it('prompts to add an environment when a Profile Portal handoff has no saved match', () => {
currentController = makeController({
@@ -412,8 +393,7 @@ describe('App deep-link orchestration', () => {
acknowledgeDeepLink.mockResolvedValue(undefined)
listApps.mockResolvedValue({ apps: [] })
listPendingDeepLinks.mockResolvedValue({ links: [] })
- closeSandboxUi.mockResolvedValue(undefined)
- getSandboxUiLocation.mockResolvedValue(null)
+ main = createSandboxUiMainFake()
emitDeepLink = null
emitCommand = null
currentController = makeController()
@@ -434,12 +414,11 @@ describe('App deep-link orchestration', () => {
rendererReady: vi.fn().mockResolvedValue(undefined),
},
sandboxUi: {
+ ...main.bridge,
listApps,
listPendingDeepLinks,
clearPendingDeepLinks,
acknowledgeDeepLink,
- close: closeSandboxUi,
- getLocation: getSandboxUiLocation,
focusActive: vi.fn().mockResolvedValue(true),
onDeepLink: vi.fn((callback: (link: SandboxUiDeepLinkEnvelope) => void) => {
emitDeepLink = callback
@@ -450,10 +429,38 @@ describe('App deep-link orchestration', () => {
})
})
+ // An app launched the way the sidebar does, into a new app tab. The stubbed
+ // page measures for it, and main mounts it unless told otherwise.
+ const LIVE_APP = { appRef: 'ns/app', label: 'App', defaultPath: '/' }
+
+ function embedState() {
+ const embed = sandboxUiPageHarness.props?.embed
+ if (!embed) throw new Error('the Apps page is not mounted')
+ return embed.getSnapshot()
+ }
+
+ function embedPhase(): string | undefined {
+ const state = embedState()
+ return state.owner === null ? undefined : state.views.get(state.owner)?.phase
+ }
+
+ async function launchLiveApp(
+ app: { appRef: string; label: string; defaultPath: string } = LIVE_APP
+ ) {
+ await act(async () => {
+ sidebarHarness.props?.onOpenSandboxUiApp?.(app)
+ await Promise.resolve()
+ })
+ }
+
+ async function waitForMounted() {
+ await waitFor(() => expect(embedPhase()).toBe('mounted'))
+ }
+
// With universal-tabs an open app is a `kind:'app'` tab in the global strip, so
// opening/closing an app no longer auto-collapses or restores the sidebar. The
// manual toggle and its persistence are the only things that move the sidebar.
- it('does not collapse or restore the sidebar when an app opens and closes', () => {
+ it('does not collapse or restore the sidebar when an app opens and closes', async () => {
window.localStorage.clear()
currentController = makeController({
initialExperienceLoading: false,
@@ -462,26 +469,19 @@ describe('App deep-link orchestration', () => {
render(<App />)
expect(sidebarHarness.props?.collapsed).toBe(false)
- act(() => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/app',
- label: 'App',
- defaultPath: '/',
- })
- })
- // Guard against a vacuous assertion: the app must actually be active for
- // "the sidebar didn't move" to mean anything.
- expect(sandboxUiPageHarness.props?.shortcutApp?.appRef).toBe('ns/app')
+ await launchLiveApp()
+ await waitForMounted()
// Opening an app leaves the sidebar exactly as it was, and touches nothing in
// the saved preference.
expect(sidebarHarness.props?.collapsed).toBe(false)
expect(window.localStorage.getItem(SIDEBAR_COLLAPSED_KEY)).toBeNull()
- act(() => sandboxUiPageHarness.props?.onEmbeddedAppBack?.())
+ await act(async () => emitCommand?.('app.backToApps'))
+ await waitFor(() => expect(embedState().owner).toBeNull())
expect(sidebarHarness.props?.collapsed).toBe(false)
})
- it('keeps the manual sidebar toggle and its persistence intact while an app is open', () => {
+ it('keeps the manual sidebar toggle and its persistence intact while an app is open', async () => {
window.localStorage.clear()
currentController = makeController({
initialExperienceLoading: false,
@@ -489,13 +489,8 @@ describe('App deep-link orchestration', () => {
} as Partial<AppController>)
render(<App />)
- act(() => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/app',
- label: 'App',
- defaultPath: '/',
- })
- })
+ await launchLiveApp()
+ await waitForMounted()
expect(sidebarHarness.props?.collapsed).toBe(false)
// The user collapses the sidebar manually while the app is open: it collapses
@@ -510,11 +505,12 @@ describe('App deep-link orchestration', () => {
expect(window.localStorage.getItem(SIDEBAR_COLLAPSED_KEY)).toBe('0')
// Closing the app leaves the user's manual state untouched.
- act(() => sandboxUiPageHarness.props?.onEmbeddedAppBack?.())
+ await act(async () => emitCommand?.('app.backToApps'))
+ await waitFor(() => expect(embedState().owner).toBeNull())
expect(sidebarHarness.props?.collapsed).toBe(false)
})
- it('respects a saved collapsed preference regardless of app open/close', () => {
+ it('respects a saved collapsed preference regardless of app open/close', async () => {
window.localStorage.clear()
window.localStorage.setItem(SIDEBAR_COLLAPSED_KEY, '1')
currentController = makeController({
@@ -524,19 +520,27 @@ describe('App deep-link orchestration', () => {
render(<App />)
expect(sidebarHarness.props?.collapsed).toBe(true)
- act(() => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/app',
- label: 'App',
- defaultPath: '/',
- })
- })
- // Guard against a vacuous assertion: the app must actually be active here.
- expect(sandboxUiPageHarness.props?.shortcutApp?.appRef).toBe('ns/app')
+ main.failNextOpen(new Error('open rejected'))
+ await launchLiveApp()
+ await waitFor(() => expect(embedState().failure?.kind).toBe('open'))
expect(sidebarHarness.props?.collapsed).toBe(true)
+ })
- act(() => sandboxUiPageHarness.props?.onEmbeddedAppOpenFailed?.())
- expect(sidebarHarness.props?.collapsed).toBe(true)
+ it('drops the shell overlays raised over an app whose view is gone while its tab stays', async () => {
+ currentController = makeController({
+ initialExperienceLoading: false,
+ navItem: DESKTOP_ROUTES.apps,
+ } as Partial<AppController>)
+ render(<App />)
+ await launchLiveApp()
+ await waitForMounted()
+ act(() => appHeaderHarness.props?.onShellOverlayOpenChange?.(true))
+ expect(sandboxUiPageHarness.props?.headerShellOverlayOpen).toBe(true)
+
+ act(() => main.crash())
+
+ await waitFor(() => expect(embedState().failure?.kind).toBe('crashed'))
+ expect(sandboxUiPageHarness.props?.headerShellOverlayOpen).toBe(false)
})
it('uses the shared titlebar header on every authenticated route', () => {
@@ -604,55 +608,42 @@ describe('App deep-link orchestration', () => {
consent.remove()
})
- it('routes contextual search to the current sandbox app without opening global search', () => {
+ it('routes contextual search to the current sandbox app without opening global search', async () => {
currentController = makeController({
initialExperienceLoading: false,
navItem: DESKTOP_ROUTES.apps,
selectedAgent: 'alpha',
} as Partial<AppController>)
render(<App />)
- act(() => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/app',
- label: 'App',
- defaultPath: '/',
- })
- })
+ const held = main.holdNextOpen()
+ await launchLiveApp()
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(1))
+ // Still opening: nothing to search yet.
act(() => emitCommand?.('search.current'))
expect(sandboxUiPageHarness.props?.localSearchRequestId).toBe(0)
- act(() => sandboxUiPageHarness.props?.onEmbeddedAppMounted?.())
+ await act(async () => held().resolve())
+ await waitForMounted()
act(() => emitCommand?.('search.current'))
expect(sandboxUiPageHarness.props?.localSearchRequestId).toBe(1)
expect(appHeaderHarness.props?.searchFocusRequestId).toBe(0)
- act(() => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/replacement',
- label: 'Replacement app',
- defaultPath: '/',
- })
- sandboxUiPageHarness.props?.onEmbeddedAppMounted?.()
- })
+ await launchLiveApp({ appRef: 'ns/replacement', label: 'Replacement app', defaultPath: '/' })
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(2))
+ await waitForMounted()
act(() => emitCommand?.('search.current'))
expect(sandboxUiPageHarness.props?.localSearchRequestId).toBe(2)
})
- it('opens the palette, executes eligible registry actions, and captures the sandbox view', () => {
+ it('opens the palette, executes eligible registry actions, and captures the sandbox view', async () => {
currentController = makeController({
initialExperienceLoading: false,
navItem: DESKTOP_ROUTES.apps,
selectedAgent: 'alpha',
} as Partial<AppController>)
render(<App />)
- act(() => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/app',
- label: 'App',
- defaultPath: '/',
- })
- emitCommand?.('commands.open', 'sandbox')
- })
+ await launchLiveApp()
+ act(() => emitCommand?.('commands.open', 'sandbox'))
expect(commandPaletteHarness.props).not.toBeNull()
expect(sandboxUiPageHarness.props?.headerShellOverlayOpen).toBe(true)
@@ -706,7 +697,7 @@ describe('App deep-link orchestration', () => {
expect(currentController.handleLogout).toHaveBeenCalledOnce()
})
- it('routes approved contextual palette actions through shell and app owners', () => {
+ it('routes approved contextual palette actions through shell and app owners', async () => {
currentController = makeController({ initialExperienceLoading: false })
render(<App />)
act(() => emitCommand?.('commands.open'))
@@ -723,27 +714,26 @@ describe('App deep-link orchestration', () => {
act(() => commandPaletteHarness.props?.onExecute('sidebar.toggle'))
expect(sidebarHarness.props?.toggleRequestId).toBe(1)
- // `navItem` is derived from the store; the instance-less Apps picker residual
- // puts the shell on the Apps route so the contextual app commands apply.
- act(() => {
- currentController.appsPickerActive = true
- forceControllerRender()
- })
+ const held = main.holdNextOpen()
+ await launchLiveApp()
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(1))
act(() => emitCommand?.('commands.open'))
- act(() => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/app',
- label: 'App',
- defaultPath: '/',
- })
- })
expect(commandPaletteHarness.props?.isEligible('app.refresh')).toBe(false)
- act(() => sandboxUiPageHarness.props?.onEmbeddedAppMounted?.())
+ await act(async () => held().resolve())
+ await waitForMounted()
expect(commandPaletteHarness.props?.isEligible('app.refresh')).toBe(true)
- act(() => commandPaletteHarness.props?.onExecute('app.refresh'))
- expect(sandboxUiPageHarness.props?.actionRequest).toEqual({ id: 1, action: 'refresh' })
- act(() => commandPaletteHarness.props?.onExecute('app.backToApps'))
- expect(sandboxUiPageHarness.props?.actionRequest).toEqual({ id: 2, action: 'back-to-apps' })
+
+ // Refresh relaunches the app: the live view closes and a new one opens.
+ const first = main.openCall(0).launchId
+ await act(async () => commandPaletteHarness.props?.onExecute('app.refresh'))
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(2))
+ expect(closeSandboxUi()).toHaveBeenCalledWith({ launchId: first })
+ await waitForMounted()
+
+ act(() => emitCommand?.('commands.open'))
+ await act(async () => commandPaletteHarness.props?.onExecute('app.backToApps'))
+ await waitFor(() => expect(embedState().owner).toBeNull())
+ expect(closeSandboxUi()).toHaveBeenLastCalledWith({ launchId: main.openCall(1).launchId })
})
it('resets controlled command requests with the authenticated shell lifetime', async () => {
@@ -767,7 +757,6 @@ describe('App deep-link orchestration', () => {
await waitFor(() => {
expect(appHeaderHarness.props?.notificationOpenRequestId).toBe(0)
expect(sidebarHarness.props?.toggleRequestId).toBe(0)
- expect(sandboxUiPageHarness.props?.actionRequest).toBeNull()
expect(commandPaletteHarness.props?.isEligible('app.refresh')).toBe(false)
})
})
@@ -776,23 +765,10 @@ describe('App deep-link orchestration', () => {
vi.useRealTimers()
})
- async function reportShortcutOpenResult(
- result: { status: 'mounted' } | { status: 'failed'; message: string } = {
- status: 'mounted',
- }
- ): Promise<void> {
- await waitFor(() => {
- expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBeGreaterThan(0)
- })
- const props = sandboxUiPageHarness.props
- // Bound to its own const: TypeScript discards the narrowing of a property
- // inside a callback, because the object could be mutated in between.
- const requestId = props?.shortcutOpenRequestId
- if (!props || !requestId) throw new Error('Sandbox UI shortcut was not requested')
- await act(async () => {
- await props.onShortcutOpenResult?.(requestId, result)
- await Promise.resolve()
- })
+ // The deep link's launch reached main (`times` opens so far). Main mounts it
+ // unless the test told the fake to hold or fail that open.
+ async function waitForAppOpen(times = 1): Promise<void> {
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(times))
}
async function confirmPendingAppLink(): Promise<void> {
@@ -847,7 +823,7 @@ describe('App deep-link orchestration', () => {
confirmDialogHarness.props?.onConfirm()
await Promise.resolve()
})
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
})
@@ -877,7 +853,7 @@ describe('App deep-link orchestration', () => {
expect(acknowledgeDeepLink).not.toHaveBeenCalled()
await confirmPendingAppLink()
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
// The launch drives the store (an app tab), so `navItem` derives to the Apps
@@ -902,7 +878,7 @@ describe('App deep-link orchestration', () => {
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(currentController.handleNavSelect).not.toHaveBeenCalledWith(DESKTOP_ROUTES.apps)
- expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBeUndefined()
+ expect(openSandboxUi()).not.toHaveBeenCalled()
})
it('signals a deep-link overlay to the sandbox page while the confirm dialog is open', async () => {
@@ -936,7 +912,7 @@ describe('App deep-link orchestration', () => {
expect(sandboxUiPageHarness.props?.deepLinkShellOverlayOpen).toBe(true)
await confirmPendingAppLink()
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
await waitFor(() => expect(sandboxUiPageHarness.props?.deepLinkShellOverlayOpen).toBe(false))
})
@@ -1065,7 +1041,7 @@ describe('App deep-link orchestration', () => {
})
await confirmPendingAppLink()
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(acknowledgeDeepLink).toHaveBeenCalledTimes(1)
@@ -1208,7 +1184,11 @@ describe('App deep-link orchestration', () => {
})
it('closes the active embed before switching teams for a failed cross-team handoff', async () => {
- const ensureTeamContext = vi.fn(async (): Promise<boolean> => true)
+ let viewLiveAtSwitch: unknown = 'not switched'
+ const ensureTeamContext = vi.fn(async (): Promise<boolean> => {
+ if (viewLiveAtSwitch === 'not switched') viewLiveAtSwitch = main.live()
+ return true
+ })
currentController = makeController({
initialExperienceLoading: false,
navItem: DESKTOP_ROUTES.apps,
@@ -1217,13 +1197,8 @@ describe('App deep-link orchestration', () => {
render(<App />)
await waitFor(() => expect(sandboxUiPageHarness.props).not.toBeNull())
- act(() => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/current',
- label: 'Current App',
- defaultPath: '/',
- })
- })
+ await launchLiveApp({ appRef: 'ns/current', label: 'Current App', defaultPath: '/' })
+ await waitForMounted()
await waitFor(() => expect(emitDeepLink).not.toBeNull())
act(() => {
@@ -1232,8 +1207,11 @@ describe('App deep-link orchestration', () => {
await confirmPendingAppLink()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
- expect(closeSandboxUi).toHaveBeenCalledOnce()
- expect(closeSandboxUi.mock.invocationCallOrder[0]).toBeLessThan(
+ expect(closeSandboxUi()).toHaveBeenCalledOnce()
+ expect(closeSandboxUi()).toHaveBeenCalledWith({ launchId: main.openCall(0).launchId })
+ // The team switch waited for main to release the view, not just for the close.
+ expect(viewLiveAtSwitch).toBeNull()
+ expect(closeSandboxUi().mock.invocationCallOrder[0]).toBeLessThan(
ensureTeamContext.mock.invocationCallOrder[0] ?? Number.POSITIVE_INFINITY
)
})
@@ -1264,7 +1242,7 @@ describe('App deep-link orchestration', () => {
})
await confirmPendingAppLink()
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(currentController.handleEnsureTeamContext).toHaveBeenCalledWith({
teamId: 'team-b',
@@ -1338,7 +1316,7 @@ describe('App deep-link orchestration', () => {
})
await confirmPendingAppLink()
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(currentController.pushToast).not.toHaveBeenCalledWith(
expect.stringContaining('bridge unavailable'),
@@ -1370,14 +1348,16 @@ describe('App deep-link orchestration', () => {
act(() => {
emitDeepLink?.({ id: 1, appRef: 'ns/app' })
})
+ const held = main.holdNextOpen()
await confirmPendingAppLink()
- await waitFor(() => {
- expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBeGreaterThan(0)
+ await waitForAppOpen()
+ await act(async () => {
+ await new Promise(resolve => window.setTimeout(resolve, 0))
})
expect(acknowledgeDeepLink).not.toHaveBeenCalled()
- await reportShortcutOpenResult()
+ await act(async () => held().resolve())
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
})
@@ -1418,7 +1398,7 @@ describe('App deep-link orchestration', () => {
vi.advanceTimersByTime(1_000)
await Promise.resolve()
})
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
})
@@ -1482,7 +1462,7 @@ describe('App deep-link orchestration', () => {
vi.advanceTimersByTime(2_000)
await Promise.resolve()
})
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(liveTeamId).toBe('team-b')
@@ -1519,8 +1499,9 @@ describe('App deep-link orchestration', () => {
act(() => {
emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-b' })
})
+ main.failNextOpen(new Error('native mount failed'))
await confirmPendingAppLink()
- await reportShortcutOpenResult({ status: 'failed', message: 'native mount failed' })
+ await waitForAppOpen()
await waitFor(() => {
expect(currentController.pushToast).toHaveBeenCalledWith('native mount failed', 'error')
@@ -1532,7 +1513,7 @@ describe('App deep-link orchestration', () => {
vi.advanceTimersByTime(1_000)
await Promise.resolve()
})
- await reportShortcutOpenResult()
+ await waitForAppOpen(2)
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(acknowledgeDeepLink).toHaveBeenCalledTimes(1)
@@ -1574,8 +1555,9 @@ describe('App deep-link orchestration', () => {
act(() => {
emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-b' })
})
+ main.failNextOpen(new Error('native mount failed'))
await confirmPendingAppLink()
- await reportShortcutOpenResult({ status: 'failed', message: 'native mount failed' })
+ await waitForAppOpen()
await waitFor(() => {
expect(currentController.pushToast).toHaveBeenCalledWith('native mount failed', 'error')
@@ -1604,7 +1586,7 @@ describe('App deep-link orchestration', () => {
// The launch put the shell on the Apps route via the store (observable that
// replaced the retired single `handleNavSelect(apps)` call).
expect(currentController.navItem).toBe(DESKTOP_ROUTES.apps)
- expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBe(1)
+ expect(openSandboxUi()).toHaveBeenCalledTimes(1)
expect(acknowledgeDeepLink).not.toHaveBeenCalled()
await act(async () => {
@@ -1664,7 +1646,7 @@ describe('App deep-link orchestration', () => {
vi.advanceTimersByTime(1_000)
await Promise.resolve()
})
- await reportShortcutOpenResult()
+ await waitForAppOpen()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(acknowledgeDeepLink).toHaveBeenCalledTimes(1)
@@ -1761,8 +1743,9 @@ describe('App deep-link orchestration', () => {
act(() => {
emitDeepLink?.({ id: 1, appRef: 'ns/app' })
})
+ main.failNextOpen(new Error('native mount failed'))
await confirmPendingAppLink()
- await reportShortcutOpenResult({ status: 'failed', message: 'native mount failed' })
+ await waitForAppOpen()
expect(acknowledgeDeepLink).not.toHaveBeenCalledWith(1)
@@ -1770,16 +1753,13 @@ describe('App deep-link orchestration', () => {
emitDeepLink?.({ id: 2, appRef: 'ns/next' })
})
await confirmPendingAppLink()
- await waitFor(() => {
- expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBeGreaterThan(1)
- })
- await reportShortcutOpenResult()
+ await waitForAppOpen(2)
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(2))
expect(acknowledgeDeepLink).not.toHaveBeenCalledWith(1)
})
- // ── mini-spec 05: Phase-1 app persistence by URL restoration ────────────────
+ // ── the route an app tab is left on, and deep links left before mounting ──
const READY_APP = {
appRef: 'ns/app',
@@ -1789,167 +1769,91 @@ describe('App deep-link orchestration', () => {
phase: 'active',
}
- // A genuinely distinct app: a different appRef, so cross-app lifecycle
- // isolation tests exercise App A → App B rather than a second tab of App A.
- const READY_APP_B = {
- appRef: 'ns/app-b',
- title: 'Linked App B',
- defaultPath: '/',
- ready: true,
- phase: 'active',
- }
-
const appTabs = () => currentController.workspaceTabs.tabs.filter(tab => tab.kind === 'app')
// Launch an app straight through the sidebar (`onOpenSandboxUiApp`), the same
- // path the real app-picker uses — no deep-link confirm ceremony. Defaults to
- // `ns/app`; pass a distinct appRef to launch another app the sidebar offers.
+ // path the real app-picker uses — no deep-link confirm ceremony.
async function launchAppFromSidebar(appRef = 'ns/app'): Promise<void> {
const app = await waitFor(() => {
const available = sidebarHarness.props?.availableSandboxUiApps?.find(a => a.appRef === appRef)
if (!available) throw new Error(`${appRef} was not available to the sidebar`)
return available
})
+ const opens = openSandboxUi().mock.calls.length
await act(async () => {
sidebarHarness.props?.onOpenSandboxUiApp?.(app)
await Promise.resolve()
})
- await waitFor(() => expect(sandboxUiPageHarness.props?.shortcutApp?.appRef).toBe(appRef))
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(opens + 1))
+ await waitForMounted()
}
async function selectTab(index: 0 | 1 | 2): Promise<void> {
await waitFor(() => expect(emitCommand).not.toBeNull())
await act(async () => {
emitCommand?.(`tabs.select${index + 1}` as DesktopCommandId)
- await Promise.resolve()
+ await new Promise(resolve => window.setTimeout(resolve, 0))
})
}
- it('restores the saved route when an app tab is reactivated (mini-spec 05 §3, T3)', async () => {
+ it('restores the route an app tab was left on when it is reactivated', async () => {
currentController = makeController({ initialExperienceLoading: false })
listApps.mockResolvedValue({ apps: [READY_APP] })
render(<App />)
await launchAppFromSidebar()
- // Launched at the default route — nothing persisted yet.
- expect(sandboxUiPageHarness.props?.shortcutApp?.routePath).toBeUndefined()
-
- // The embed navigated to a non-default route. This is the shape the real
- // producer emits (sandboxUiDriver.test.ts proves '/tickets/42' for a nested
- // view URL; appService.getSandboxUiLocation reshapes it to { appRef, routePath }).
- getSandboxUiLocation.mockResolvedValue({ appRef: 'ns/app', routePath: '/tickets/42' })
+ // Launched at the default route.
+ expect(main.openCall(0).routePath).toBeUndefined()
- // Deactivate → the store reads the route and persists it on the app tab.
+ main.navigate('/tickets/42')
await selectTab(0)
await waitFor(() => expect(appTabs()[0]?.app?.savedRoutePath).toBe('/tickets/42'))
+ expect(closeSandboxUi()).toHaveBeenCalledTimes(1)
- // Reactivate → the embed re-mounts at the saved route, not the default path.
await selectTab(1)
- await waitFor(() =>
- expect(sandboxUiPageHarness.props?.shortcutApp?.routePath).toBe('/tickets/42')
- )
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(2))
+ expect(main.openCall(1).routePath).toBe('/tickets/42')
})
- it('keeps two tabs of the same app on their own routes when alternating (§5)', async () => {
+ it('keeps two tabs of the same app on their own routes when alternating', async () => {
currentController = makeController({ initialExperienceLoading: false })
listApps.mockResolvedValue({ apps: [READY_APP] })
render(<App />)
// Two tabs of the same app: [chat, A, B].
await launchAppFromSidebar()
- getSandboxUiLocation.mockResolvedValue({ appRef: 'ns/app', routePath: '/tickets/A' })
- await launchAppFromSidebar() // deactivates A (persists /tickets/A), activates B
+ main.navigate('/tickets/A')
+ await launchAppFromSidebar() // leaves A (its view reports /tickets/A), opens B
await waitFor(() => expect(appTabs()).toHaveLength(2))
await waitFor(() => expect(appTabs()[0]?.app?.savedRoutePath).toBe('/tickets/A'))
- // B navigates to its own route, then we switch back to A.
- getSandboxUiLocation.mockResolvedValue({ appRef: 'ns/app', routePath: '/tickets/B' })
+ main.navigate('/tickets/B')
await selectTab(1) // index 1 = A
- await waitFor(() => expect(appTabs()[1]?.app?.savedRoutePath).toBe('/tickets/B'))
- await waitFor(() =>
- expect(sandboxUiPageHarness.props?.shortcutApp?.routePath).toBe('/tickets/A')
- )
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(3))
+ expect(appTabs()[1]?.app?.savedRoutePath).toBe('/tickets/B')
+ expect(main.openCall(2).routePath).toBe('/tickets/A')
- // Back to B restores B's own route.
+ await waitForMounted()
await selectTab(2) // index 2 = B
- await waitFor(() =>
- expect(sandboxUiPageHarness.props?.shortcutApp?.routePath).toBe('/tickets/B')
- )
- })
-
- it('closes the embed exactly once on deactivation — the store is the single emitter (§3)', async () => {
- currentController = makeController({ initialExperienceLoading: false })
- listApps.mockResolvedValue({ apps: [READY_APP] })
- render(<App />)
- await launchAppFromSidebar()
-
- closeSandboxUi.mockClear()
- getSandboxUiLocation.mockClear()
-
- await selectTab(0) // deactivate to the seeded chat tab
- await waitFor(() => expect(closeSandboxUi).toHaveBeenCalledTimes(1))
- expect(getSandboxUiLocation).toHaveBeenCalledTimes(1)
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(4))
+ expect(main.openCall(3).routePath).toBe('/tickets/B')
})
- it('does not re-close after an UNsolicited close reconciles the tab as not mounted (§3)', async () => {
+ it('does not close a view main already tore down when its tab is left', async () => {
currentController = makeController({ initialExperienceLoading: false })
listApps.mockResolvedValue({ apps: [READY_APP] })
render(<App />)
await launchAppFromSidebar()
- // Unsolicited teardown (crash / quit / partition GC) arrives while the app
- // tab is still active: the store reconciles its liveness to "not mounted".
- await act(async () => {
- sandboxUiPageHarness.props?.onEmbeddedAppBack?.()
- await Promise.resolve()
- })
-
- closeSandboxUi.mockClear()
- getSandboxUiLocation.mockClear()
+ act(() => main.crash())
+ await waitFor(() => expect(embedState().failure?.kind).toBe('crashed'))
- // A later deactivation must not persist/close a dead embed.
await selectTab(0)
- await act(async () => {
- await Promise.resolve()
- })
- expect(closeSandboxUi).not.toHaveBeenCalled()
- expect(getSandboxUiLocation).not.toHaveBeenCalled()
+ expect(closeSandboxUi()).not.toHaveBeenCalled()
+ // A crash leaves no route behind: reopening must not land on a crashing page.
+ expect(appTabs()[0]?.app?.savedRoutePath).toBeUndefined()
})
- it('closes an embed re-mounted within the still-active app tab (Blocker — arm-on-open)', async () => {
- currentController = makeController({ initialExperienceLoading: false })
- listApps.mockResolvedValue({ apps: [READY_APP] })
- render(<App />)
- await launchAppFromSidebar()
-
- // Back-to-apps / unsolicited onClosed clears the liveness ref but leaves the
- // app tab active (the in-page Apps grid is shown, no tab change).
- await act(async () => {
- sandboxUiPageHarness.props?.onEmbeddedAppBack?.()
- await Promise.resolve()
- })
-
- // Re-mount the embed DIRECTLY from the in-page grid: this only fires
- // onEmbeddedAppOpening — it does NOT create or select a store tab. Before the
- // arm-on-open fix the liveness ref stays null here, so the deactivation
- // effect early-returns on the next switch and the native view leaks; with the
- // fix, onEmbeddedAppOpening arms the ref to the active app tab.
- await act(async () => {
- sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
- appRef: 'ns/app',
- label: 'Linked App',
- defaultPath: '/',
- })
- await Promise.resolve()
- })
-
- closeSandboxUi.mockClear()
-
- // Switching to a chat tab must close the re-mounted embed exactly once.
- await selectTab(0)
- await waitFor(() => expect(closeSandboxUi).toHaveBeenCalledTimes(1))
- })
-
- it('persists the outgoing app route on a deep-link handoff (§3, Should-fix)', async () => {
+ it('persists the outgoing app route on a deep-link team handoff', async () => {
const ensureTeamContext = vi.fn(async (): Promise<boolean> => true)
currentController = makeController({
initialExperienceLoading: false,
@@ -1959,10 +1863,7 @@ describe('App deep-link orchestration', () => {
render(<App />)
await launchAppFromSidebar()
const outgoingId = appTabs()[0]?.id
-
- // The outgoing embed is on a non-default route when a cross-team deep link
- // hands off — the handoff must persist it, same as the deactivation effect.
- getSandboxUiLocation.mockResolvedValue({ appRef: 'ns/app', routePath: '/handoff/route' })
+ main.navigate('/handoff/route')
await waitFor(() => expect(emitDeepLink).not.toBeNull())
act(() => {
@@ -1975,285 +1876,69 @@ describe('App deep-link orchestration', () => {
currentController.workspaceTabs.tabs.find(tab => tab.id === outgoingId)?.app?.savedRoutePath
).toBe('/handoff/route')
)
- expect(getSandboxUiLocation).toHaveBeenCalled()
- expect(closeSandboxUi).toHaveBeenCalled()
+ expect(closeSandboxUi()).toHaveBeenCalledWith({ launchId: main.openCall(0).launchId })
})
- // R1-H1 (mini-spec 07): the deactivation continuation reads the outgoing
- // route over IPC and then closes the singleton embed. If the user reactivates
- // the SAME app tab before that read resolves, the stale continuation must not
- // tear down the just-reopened embed nor overwrite the live tab's route with
- // the value it read from the view that is already gone. The read is deferred
- // here so the reactivation lands while it is in flight. The resolved value uses
- // the same `{ appRef, routePath }` contract shape the rest of the suite uses
- // (pinned by sandboxUiDriver.test.ts); the gate aborts before routePath is read
- // on the raced path, so its exact value does not matter to this test.
- function createDeferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
- let resolve!: (value: T) => void
- const promise = new Promise<T>(res => {
- resolve = res
- })
- return { promise, resolve }
- }
-
- it('does not close or overwrite an app tab reactivated before the stale getLocation resolves (R1-H1, T3)', async () => {
- currentController = makeController({ initialExperienceLoading: false })
- listApps.mockResolvedValue({ apps: [READY_APP] })
- render(<App />)
- await launchAppFromSidebar() // tabs: [chat, A]; A is live
-
- closeSandboxUi.mockClear()
- getSandboxUiLocation.mockClear()
-
- // Defer the deactivation read so App A can be reactivated while it is still
- // in flight. Only the deactivation continuation calls getLocation here
- // (reactivation early-returns before any read), so one deferred call is exact.
- const pendingLocation = createDeferred<{ appRef: string; routePath?: string }>()
- getSandboxUiLocation.mockReturnValueOnce(pendingLocation.promise)
-
- // Deactivate A → seeded chat tab: dispatches the read-then-close continuation.
- await selectTab(0)
- // Reactivate A before the old read resolves: a newer activation now owns the
- // active view and the embed is re-mounted for A.
- await selectTab(1)
-
- // The stale read finally resolves with A's earlier route.
- await act(async () => {
- pendingLocation.resolve({ appRef: 'ns/app', routePath: '/stale/route' })
- await Promise.resolve()
- await Promise.resolve()
- })
-
- // Liveness witnesses (M4): the negative assertions below pass vacuously if the
- // deactivation never reads/closes at all, so pin that the read-then-close DID
- // run (exactly the deferred call) and that A is genuinely re-mounted and live.
- expect(getSandboxUiLocation).toHaveBeenCalledTimes(1)
- expect(sandboxUiPageHarness.props?.shortcutApp?.appRef).toBe('ns/app')
-
- // Observable result: the reopened embed was NOT torn down, and the live tab's
- // route was NOT clobbered by the stale value. (At the pre-fix head the stale
- // continuation closes the reopened embed and persists '/stale/route' onto A.)
- expect(closeSandboxUi).not.toHaveBeenCalled()
- expect(appTabs()[0]?.app?.savedRoutePath).not.toBe('/stale/route')
- })
-
- it('does not close a different app opened before the stale getLocation resolves (R1-H1, T3)', async () => {
- currentController = makeController({ initialExperienceLoading: false })
- // Two genuinely distinct apps: A's stale continuation must not tear down B.
- listApps.mockResolvedValue({ apps: [READY_APP, READY_APP_B] })
- render(<App />)
- await launchAppFromSidebar('ns/app') // tabs: [chat, A]; A is live
-
- closeSandboxUi.mockClear()
- getSandboxUiLocation.mockClear()
-
- const pendingLocation = createDeferred<{ appRef: string; routePath?: string }>()
- getSandboxUiLocation.mockReturnValueOnce(pendingLocation.promise)
-
- // Deactivate A → seeded chat tab (A's read in flight).
- await selectTab(0)
- // Open a DIFFERENT app (B, distinct appRef) before A's read resolves; B is live.
- await launchAppFromSidebar('ns/app-b')
- await waitFor(() => expect(appTabs()).toHaveLength(2))
-
- // The stale read resolves with A's route, while B owns the active view.
- await act(async () => {
- pendingLocation.resolve({ appRef: 'ns/app', routePath: '/stale/route' })
- await Promise.resolve()
- await Promise.resolve()
+ it('acks a cross-team link left before it mounted without retrying it, and gives the team back', async () => {
+ let liveTeamId = 'team-a'
+ const ensureTeamContext = vi.fn(async ({ teamId }: { teamId?: string }) => {
+ if (!teamId || teamId === liveTeamId) return false
+ liveTeamId = teamId
+ return true
})
-
- // Liveness witness (M4): A's deactivation read-then-close DID run (exactly the
- // deferred call — launching B early-returns before any read), so the negative
- // assertions below are not vacuously green.
- expect(getSandboxUiLocation).toHaveBeenCalledTimes(1)
- // Observable result: B stays the live view and its embed survives (no close).
- // (At the pre-fix head the stale continuation closes the newly-opened B embed.)
- expect(sandboxUiPageHarness.props?.shortcutApp?.appRef).toBe('ns/app-b')
- expect(closeSandboxUi).not.toHaveBeenCalled()
- expect(appTabs()[1]?.app?.appRef).toBe('ns/app-b')
- // Cross-app persist isolation: the stale read carried A's appRef, so the pre-fix
- // continuation would clobber A's own route with '/stale/route'. The gate aborts
- // that persist once B owns the active view, so A's route stays untouched.
- expect(appTabs()[0]?.app?.appRef).toBe('ns/app')
- expect(appTabs()[0]?.app?.savedRoutePath).not.toBe('/stale/route')
- expect(appTabs()[1]?.app?.savedRoutePath).toBeUndefined()
- })
-
- // R3-H1: closeActiveSandboxUiEmbedForHandoff re-checks the activation generation
- // after its `getLocation()` read, so a handoff superseded mid-read never clobbers
- // the live tab's route nor tears down the embed that now owns the active view. That
- // post-read check is the reachable guard: it aborts before both the persist AND the
- // close, since no `await` separates them (the second gen check right before close is
- // a defensive re-check for a future edit that would add one — it cannot fire on its
- // own with today's control flow). No test exercised the reachable guard: removing it
- // left the suite green. This defers the handoff's read, supersedes it with a plain
- // deactivation (which bumps the generation and closes the embed itself), then
- // resolves the stale read and asserts the handoff added neither a stale persist
- // nor a second close.
- it('does not persist or close for a superseded deep-link handoff (R3-H1, T3)', async () => {
- const ensureTeamContext = vi.fn(async (): Promise<boolean> => true)
currentController = makeController({
initialExperienceLoading: false,
handleEnsureTeamContext: ensureTeamContext,
+ getCurrentTeamId: () => liveTeamId,
})
- // The deep link targets an UNAVAILABLE app (ns/missing) so the post-handoff
- // open fails cleanly instead of relaunching an app and muddying the assertions.
listApps.mockResolvedValue({ apps: [READY_APP] })
render(<App />)
- await launchAppFromSidebar('ns/app') // tabs: [chat, A]; A live, liveRef = A
- const outgoingId = appTabs()[0]?.id
-
- closeSandboxUi.mockClear()
- getSandboxUiLocation.mockClear()
-
- // Defer the HANDOFF's read so a newer activation can bump the generation while
- // it is in flight (only the handoff reads before the supersede below).
- const pendingLocation = createDeferred<{ appRef: string; routePath?: string }>()
- getSandboxUiLocation.mockReturnValueOnce(pendingLocation.promise)
-
- // A cross-team deep link drives closeActiveSandboxUiEmbedForHandoff, which reads
- // the outgoing route (deferred here) before it would persist + close.
await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ main.holdNextOpen()
act(() => {
- emitDeepLink?.({ id: 1, appRef: 'ns/missing', teamId: 'team-b' })
+ emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-b' })
})
await confirmPendingAppLink()
- await waitFor(() => expect(getSandboxUiLocation).toHaveBeenCalledTimes(1), { timeout: 5000 })
+ await waitForAppOpen()
+ expect(liveTeamId).toBe('team-b')
- // Supersede the handoff: switch to the seeded chat tab. The deactivation effect
- // bumps the activation generation AND closes A's embed itself, all while the
- // handoff's read is still pending.
+ // The user leaves the link's tab while its view is still opening.
await selectTab(0)
- await waitFor(() => expect(closeSandboxUi).toHaveBeenCalledTimes(1))
- // The superseded handoff read finally resolves with A's earlier route.
- await act(async () => {
- pendingLocation.resolve({ appRef: 'ns/app', routePath: '/stale/handoff' })
- await Promise.resolve()
- await Promise.resolve()
- })
-
- // The post-read gen check aborts the superseded continuation: A is NOT persisted
- // with the stale route, and the handoff emits NO second close on top of the
- // deactivation's. With that guard removed the handoff clobbers A with
- // '/stale/handoff' AND closes a second time.
- const appA = currentController.workspaceTabs.tabs.find(tab => tab.id === outgoingId)
- expect(appA?.app?.savedRoutePath).not.toBe('/stale/handoff')
- expect(closeSandboxUi).toHaveBeenCalledTimes(1)
- })
-
- // R3-M1 (the missing half of R1-H1): the deactivation continuation must validate
- // that the route it read belongs to the OUTGOING tab's app before persisting it.
- // On an app→app switch the incoming `open()` can reach main before this read
- // resolves, so `getLocation` can surface the INCOMING app's location within a
- // single activation generation — the generation gate does not catch that. Without
- // the appRef guard, App B's route lands on App A's tab.
- it('does not persist the incoming app route onto the outgoing tab (R3-M1, T3)', async () => {
- currentController = makeController({ initialExperienceLoading: false })
- // Two genuinely distinct apps so the read can carry the WRONG app's location.
- listApps.mockResolvedValue({ apps: [READY_APP, READY_APP_B] })
- render(<App />)
- await launchAppFromSidebar('ns/app') // tabs: [chat, A]; A live
- const outgoingId = appTabs()[0]?.id
-
- // The deactivation read returns the INCOMING app's location (B), not A's.
- getSandboxUiLocation.mockResolvedValue({ appRef: 'ns/app-b', routePath: '/b/route' })
-
- await launchAppFromSidebar('ns/app-b') // deactivates A (reads B's location), activates B
- await waitFor(() => expect(appTabs()).toHaveLength(2))
- // Let A's deactivation continuation run to completion.
+ await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ expect(ensureTeamContext).toHaveBeenLastCalledWith({ teamId: 'team-a', announce: true })
+ expect(liveTeamId).toBe('team-a')
+ expect(confirmDialogHarness.props?.title).not.toBe('App link could not be opened')
+ expect(currentController.pushToast).not.toHaveBeenCalledWith(
+ expect.stringContaining('Could not open app link'),
+ 'error'
+ )
+ // No retry: the link is gone and nothing reopens the app later.
await act(async () => {
- await Promise.resolve()
- await Promise.resolve()
+ await new Promise(resolve => window.setTimeout(resolve, 50))
})
-
- // Observable result: A keeps its own identity and is NOT saved with B's route.
- // The read's appRef ('ns/app-b') did not match A's ('ns/app'), so the persist
- // fell back to undefined. (At the pre-guard head A.savedRoutePath === '/b/route'.)
- const appA = currentController.workspaceTabs.tabs.find(tab => tab.id === outgoingId)
- expect(appA?.app?.appRef).toBe('ns/app')
- expect(appA?.app?.savedRoutePath).not.toBe('/b/route')
- expect(appA?.app?.savedRoutePath).toBeUndefined()
+ expect(openSandboxUi()).toHaveBeenCalledTimes(1)
})
- // R4-M1 (regression of R3-M1's fix 8a9c45f5d): the appRef guard fell back to
- // `undefined` on a foreign read, and setAppTabSavedRoutePath treats `undefined`
- // as an authoritative CLEAR — so a foreign/stale read did not merely "skip
- // saving B", it ERASED A's own previously-saved route. §3 Option A: a foreign
- // or failed read must PRESERVE (never call the setter). Both seam sites.
- it('preserves the outgoing tab route when the deactivation read surfaces a foreign app (R4-M1, §3, T3)', async () => {
+ it('stops a deep link waiting on its launch when App unmounts, without acting on it', async () => {
currentController = makeController({ initialExperienceLoading: false })
- listApps.mockResolvedValue({ apps: [READY_APP, READY_APP_B] })
- render(<App />)
- await launchAppFromSidebar('ns/app') // tabs: [chat, A]; A live & active
- const outgoingId = appTabs()[0]!.id
-
- // Seed A's OWN saved route through the real store producer.
- act(() => {
- currentController.setWorkspaceTabs(state =>
- setAppTabSavedRoutePath(state, outgoingId, '/a/own')
- )
- })
- expect(appTabs()[0]?.app?.savedRoutePath).toBe('/a/own')
-
- // app→app switch whose deactivation read resolves the INCOMING app's location
- // within one activation generation (deferred so it lands after B is active).
- getSandboxUiLocation.mockClear()
- const pendingLocation = createDeferred<{ appRef: string; routePath?: string }>()
- getSandboxUiLocation.mockReturnValueOnce(pendingLocation.promise)
- await launchAppFromSidebar('ns/app-b') // deactivates A, reads (deferred)
- await waitFor(() => expect(getSandboxUiLocation).toHaveBeenCalled())
- await act(async () => {
- pendingLocation.resolve({ appRef: 'ns/app-b', routePath: '/b/route' })
- await Promise.resolve()
- await Promise.resolve()
- })
-
- // Liveness witness (M4): A's deactivation read genuinely ran. A later
- // read may also occur while the incoming app activates.
- expect(getSandboxUiLocation).toHaveBeenCalled()
- // Observable: A keeps its OWN route — the foreign read must not clear it.
- // (Pre-fix, the mismatch fell back to undefined → setter CLEARED '/a/own'.)
- const appA = currentController.workspaceTabs.tabs.find(tab => tab.id === outgoingId)
- expect(appA?.app?.savedRoutePath).toBe('/a/own')
- })
-
- it('preserves the outgoing tab route when the handoff read surfaces a foreign app (R4-M1, §3, T3)', async () => {
- const ensureTeamContext = vi.fn(async (): Promise<boolean> => true)
- currentController = makeController({
- initialExperienceLoading: false,
- handleEnsureTeamContext: ensureTeamContext,
- })
listApps.mockResolvedValue({ apps: [READY_APP] })
- render(<App />)
- await launchAppFromSidebar('ns/app') // A live & active
- const outgoingId = appTabs()[0]!.id
-
- act(() => {
- currentController.setWorkspaceTabs(state =>
- setAppTabSavedRoutePath(state, outgoingId, '/a/own')
- )
- })
- expect(appTabs()[0]?.app?.savedRoutePath).toBe('/a/own')
-
- // A cross-team deep link drives closeActiveSandboxUiEmbedForHandoff; its read
- // of the outgoing embed surfaces a FOREIGN app's location.
- getSandboxUiLocation.mockResolvedValue({ appRef: 'ns/app-b', routePath: '/b/route' })
+ const view = render(<App />)
await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ main.holdNextOpen()
act(() => {
- emitDeepLink?.({ id: 1, appRef: 'ns/missing', teamId: 'team-b' })
+ emitDeepLink?.({ id: 1, appRef: 'ns/app' })
})
await confirmPendingAppLink()
- await waitFor(() => expect(getSandboxUiLocation).toHaveBeenCalled())
+ await waitForAppOpen()
+
+ view.unmount()
await act(async () => {
- await Promise.resolve()
- await Promise.resolve()
+ await new Promise(resolve => window.setTimeout(resolve, 0))
})
-
- // Observable: the handoff must not erase A's own route on a foreign read.
- // (Pre-fix, the mismatch fell back to undefined → setter CLEARED '/a/own'.)
- const appA = currentController.workspaceTabs.tabs.find(tab => tab.id === outgoingId)
- expect(appA?.app?.savedRoutePath).toBe('/a/own')
+ // The pending link stays with main for the next renderer to pick up.
+ expect(acknowledgeDeepLink).not.toHaveBeenCalled()
})
})
diff --git a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
index 4525d0f4c..75c34fd0e 100644
--- a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
@@ -1,30 +1,78 @@
// @vitest-environment jsdom
-import { useReducer } from 'react'
+import { StrictMode, useEffect, useReducer } from 'react'
+import { flushSync } from 'react-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { DESKTOP_ROUTES } from '@constants/navigation'
import { useAppController } from '@hooks/useAppController'
+import type { EmbedEvent, Launch } from '@lib/embedOwnership.types'
+import type { EmbedOwnershipMachine } from '@lib/embedOwnershipMachine.types'
import type { GfsPreviewResource } from '@lib/gfsPreview'
import { toActiveSandboxUiApps } from '@lib/sandboxUiAppSelection'
import type { SandboxUiAppListing } from '@lib/sandboxUiAppSelection.types'
import {
activeWorkspaceTab,
createWorkspaceTabsState,
+ newChatTab,
+ openAppTab,
openFilesTab,
openPreviewTab,
+ selectWorkspaceTab,
+ setAppTabSavedRoutePath,
} from '@lib/workspaceTabs'
import { mapKindToRoute } from '@lib/workspaceTabsRoute'
import { App } from '@/App'
+import type { SandboxUiDeepLinkEnvelope } from '@/App.types'
import { openGfsResourcePayload, resolvedFile } from '@/gfs/__fixtures__/gfsProducerFixtures'
+import { type SandboxUiMainFake, createSandboxUiMainFake } from './__fixtures__/sandboxUiMainFake'
+
+// Wiring of App to the embed ownership machine: which event each gesture
+// dispatches, in which commit, and that the real SandboxUiPage paints what the
+// machine holds. Who owns the embed under every interleaving is not decided
+// here: the reducer's table and the property suite against the real main
+// process cover that.
+
+const machineHarness = vi.hoisted(() => ({
+ machine: null as null | EmbedOwnershipMachine,
+ // Every intent/relaunch App dispatched, with what the machine and the store
+ // held at that moment.
+ launches: [] as Array<{
+ type: 'intent' | 'relaunch'
+ launch: Launch
+ projectedTab: string | null
+ storeActiveTab: string | null
+ }>,
+ events: [] as EmbedEvent[],
+ afterDispatch: null as null | ((event: EmbedEvent) => void),
+ storeActiveTab: () => null as string | null,
+}))
-// Ownership of the native sandbox-ui embed. The WebContentsView paints above the
-// renderer DOM, so whichever app tab owns it must emit `sandboxUi.close()` when
-// the user leaves it — even after an open on that tab failed, because main may
-// still hold a view (a failure before the open IPC never reaches main at all),
-// and also when the app was opened from the in-page picker grid, which must
-// create that owning tab. These cases drive the REAL SandboxUiPage
-// (its open/catch path is the producer under test) and the REAL tab strip; the
-// App harness in App.chatDrawer.test.tsx stubs SandboxUiPage and so cannot.
+vi.mock('@lib/embedOwnershipMachine', async importOriginal => {
+ const actual = await importOriginal<typeof import('@lib/embedOwnershipMachine')>()
+ return {
+ createEmbedOwnershipMachine: (
+ deps: Parameters<typeof actual.createEmbedOwnershipMachine>[0]
+ ) => {
+ const machine = actual.createEmbedOwnershipMachine(deps)
+ const dispatch = machine.dispatch
+ machine.dispatch = (event: EmbedEvent) => {
+ machineHarness.events.push(event)
+ if (event.type === 'intent' || event.type === 'relaunch') {
+ machineHarness.launches.push({
+ type: event.type,
+ launch: event.launch,
+ projectedTab: machine.getSnapshot().activeAppTabId,
+ storeActiveTab: machineHarness.storeActiveTab(),
+ })
+ }
+ dispatch(event)
+ machineHarness.afterDispatch?.(event)
+ }
+ machineHarness.machine = machine
+ return machine
+ },
+ }
+})
let forceControllerRender: () => void = () => {}
@@ -40,9 +88,11 @@ function useReactiveController(controller: AppController): AppController {
}
type WorkspaceState = ReturnType<typeof useAppController>['workspaceTabs']
+type AppController = ReturnType<typeof useAppController>
const sidebarHarness = vi.hoisted(() => ({
props: null as null | {
+ activeSandboxUiApp?: { appRef: string } | null
onSelect?: (item: string) => void
onOpenSandboxUiApp?: (app: {
appRef: string
@@ -52,6 +102,9 @@ const sidebarHarness = vi.hoisted(() => ({
}) => void
},
}))
+const confirmDialogHarness = vi.hoisted(() => ({
+ props: null as null | { title?: string; onConfirm: () => void },
+}))
vi.mock('@hooks/useAppController', () => ({ useAppController: vi.fn() }))
vi.mock('@hooks/useAgentChatActionsValue', () => ({ useAgentChatActionsValue: () => ({}) }))
@@ -59,7 +112,12 @@ vi.mock('@components/AppHeader', () => ({ AppHeader: () => null }))
vi.mock('@components/ChatLocalSearch', () => ({ ChatLocalSearch: () => null }))
vi.mock('@components/CommandPalette', () => ({ CommandPalette: () => null }))
vi.mock('@components/BootSplash', () => ({ BootSplash: () => null }))
-vi.mock('@components/ConfirmDialog', () => ({ ConfirmDialog: () => null }))
+vi.mock('@components/ConfirmDialog', () => ({
+ ConfirmDialog: (props: NonNullable<typeof confirmDialogHarness.props>) => {
+ confirmDialogHarness.props = props
+ return null
+ },
+}))
vi.mock('@components/GfsImagePreview', () => ({ GfsImagePreview: () => null }))
vi.mock('@components/PluginConsentModal', () => ({ PluginConsentModal: () => null }))
vi.mock('@components/SidebarNav', () => ({
@@ -82,11 +140,10 @@ vi.mock('@pages/TeamsPage', () => ({ TeamsPage: () => null }))
vi.mock('@pages/UnavailablePage', () => ({ UnavailablePage: () => null }))
vi.mock('@pages/WorkflowsPage', () => ({ WorkflowsPage: () => null }))
-type AppController = ReturnType<typeof useAppController>
-
// Store-faithful controller (same contract as App.chatDrawer.test.tsx): `navItem`
// derives from the active tab, and every navigation drives the real store
-// producers.
+// producers. A write lands in the store at once and reaches App on its next
+// render, which is how a store update can be pending when a gesture runs.
function makeController(): AppController {
const noop = vi.fn()
let controller: AppController
@@ -106,13 +163,6 @@ function makeController(): AppController {
controller.appsPickerActive = false
forceControllerRender()
})
- const openFilesSection = vi.fn((path: string | null = null) => {
- clearAppsPicker()
- setWorkspaceTabs((state: WorkspaceState) =>
- openFilesTab(state, { id: nextWorkspaceTabId(), path })
- )
- forceControllerRender()
- })
const openPreviewSection = vi.fn((preview: GfsPreviewResource) => {
clearAppsPicker()
setWorkspaceTabs((state: WorkspaceState) =>
@@ -126,7 +176,12 @@ function makeController(): AppController {
...('mimeType' in preview ? { mimeType: preview.mimeType } : {}),
})
)
- forceControllerRender()
+ })
+ const openFilesSection = vi.fn((path: string | null = null) => {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ openFilesTab(state, { id: nextWorkspaceTabId(), path })
+ )
})
const showAppsPicker = vi.fn(() => {
if (controller.appsPickerActive) return
@@ -134,7 +189,6 @@ function makeController(): AppController {
controller.appsPickerActive = true
forceControllerRender()
})
- const handleSelectChatAgent = vi.fn(() => forceControllerRender())
controller = {
booting: false,
initialExperienceLoading: false,
@@ -188,10 +242,8 @@ function makeController(): AppController {
handleEnsureTeamContext: vi.fn(async () => false),
getCurrentTeamId: vi.fn(() => 'team-a'),
isHostAccessBlocked: vi.fn(() => false),
- handleSelectChatAgent,
+ handleSelectChatAgent: vi.fn(() => forceControllerRender()),
handleOpenNotification: vi.fn(async () => undefined),
- // Only the Apps entry matters here: like the real navigation controller it
- // shows the instance-less picker instead of opening a tab.
handleNavSelect: vi.fn((item: string) => {
if (item === DESKTOP_ROUTES.apps) showAppsPicker()
}),
@@ -225,18 +277,6 @@ const APP_LISTING: SandboxUiAppListing[] = [
// listing it loaded.
const [ALPHA, BETA] = toActiveSandboxUiApps(APP_LISTING)
-// Any rejection of the open IPC takes the same failure path; its text only
-// picks the banner copy, which these tests deliberately do not assert.
-const OPEN_REJECTED = new Error('open rejected')
-
-// The failure banner is prefixed with the appRef of the failed launch. Waiting
-// on that prefix (not on the copy) pins the moment the page has handled the
-// failure, before the test leaves the tab.
-async function waitForLaunchFailure(appRef: string) {
- const prefix = `${appRef}: `
- expect(await screen.findByText(text => text.startsWith(prefix))).toBeTruthy()
-}
-
const MEASURED_SLOT = {
x: 0,
y: 0,
@@ -248,46 +288,67 @@ const MEASURED_SLOT = {
height: 300,
toJSON: () => ({}),
} as DOMRect
-const UNMEASURED_SLOT = { ...MEASURED_SLOT, width: 0, height: 0, right: 16, bottom: 12 } as DOMRect
-function makeSandboxUiBridge() {
+function makeSandboxUiBridge(main: SandboxUiMainFake) {
return {
+ ...main.bridge,
listApps: vi.fn().mockResolvedValue({ apps: APP_LISTING }),
listPendingDeepLinks: vi.fn().mockResolvedValue({ links: [] }),
clearPendingDeepLinks: vi.fn().mockResolvedValue(undefined),
+ acknowledgeDeepLink: vi.fn().mockResolvedValue(undefined),
onDeepLink: vi.fn(() => vi.fn()),
- onTitleChanged: vi.fn(() => vi.fn()),
- onClosed: vi.fn(() => vi.fn()),
- onRefreshError: vi.fn(() => vi.fn()),
onFindResult: vi.fn(() => vi.fn()),
- open: vi.fn().mockResolvedValue(undefined),
- close: vi.fn().mockResolvedValue(undefined),
- getLocation: vi.fn().mockResolvedValue(null),
setVisible: vi.fn().mockResolvedValue(undefined),
setBounds: vi.fn().mockResolvedValue(undefined),
capturePreview: vi.fn().mockResolvedValue(null),
stopFindInPage: vi.fn().mockResolvedValue(undefined),
focusActive: vi.fn().mockResolvedValue(true),
- reload: vi.fn().mockResolvedValue(undefined),
}
}
type OpenGfsPayload = Awaited<ReturnType<typeof openGfsResourcePayload>>
-describe('App sandbox-ui embed always has an owning app tab', () => {
- let currentController: AppController
+function latestListener<T>(subscribe: ReturnType<typeof vi.fn>): (event: T) => void {
+ const calls = subscribe.mock.calls as unknown as Array<[(event: T) => void]>
+ return calls[calls.length - 1]![0]
+}
+
+function flushMacrotask() {
+ return act(async () => {
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+ })
+}
+
+describe('App wires gestures and main events to the embed ownership machine', () => {
+ let controller: AppController
let openGfsResourceCb: ((resource: OpenGfsPayload) => void) | null
let shortcutCommandCb: ((commandId: string, source: string) => void) | null
let sandboxUi: ReturnType<typeof makeSandboxUiBridge>
- let slotRect: ReturnType<typeof vi.spyOn>
+ let main: SandboxUiMainFake
+ // A `flushSync` from inside a render or effect does not flush: React only
+ // warns about it. The seam depends on flushing, so the warning fails the test.
+ let flushSyncErrors: string[]
beforeEach(() => {
vi.clearAllMocks()
sidebarHarness.props = null
+ confirmDialogHarness.props = null
+ machineHarness.machine = null
+ machineHarness.launches = []
+ machineHarness.events = []
+ machineHarness.afterDispatch = null
openGfsResourceCb = null
shortcutCommandCb = null
- currentController = makeController()
- vi.mocked(useAppController).mockImplementation(() => useReactiveController(currentController))
+ flushSyncErrors = []
+ const consoleError = console.error.bind(console)
+ vi.spyOn(console, 'error').mockImplementation((...args: unknown[]) => {
+ const text = args.map(String).join(' ')
+ if (text.includes('flushSync')) flushSyncErrors.push(text)
+ else consoleError(...args)
+ })
+ controller = makeController()
+ machineHarness.storeActiveTab = () => controller.workspaceTabs.activeTabId
+ vi.mocked(useAppController).mockImplementation(() => useReactiveController(controller))
vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
cb(0)
return 1
@@ -300,10 +361,9 @@ describe('App sandbox-ui embed always has an owning app tab', () => {
disconnect = vi.fn()
}
)
- slotRect = vi
- .spyOn(HTMLElement.prototype, 'getBoundingClientRect')
- .mockReturnValue(MEASURED_SLOT)
- sandboxUi = makeSandboxUiBridge()
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(MEASURED_SLOT)
+ main = createSandboxUiMainFake()
+ sandboxUi = makeSandboxUiBridge(main)
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
@@ -328,456 +388,612 @@ describe('App sandbox-ui embed always has an owning app tab', () => {
afterEach(async () => {
cleanup()
await new Promise(resolve => window.setTimeout(resolve, 0))
+ expect(flushSyncErrors).toEqual([])
vi.restoreAllMocks()
vi.unstubAllGlobals()
delete (window as { clerum?: unknown }).clerum
})
- async function renderWithLiveApp(app: typeof ALPHA) {
+ function machine(): EmbedOwnershipMachine {
+ const current = machineHarness.machine
+ if (!current) throw new Error('App did not create its embed machine')
+ return current
+ }
+
+ function owner() {
+ const state = machine().getSnapshot()
+ return state.owner === null ? undefined : state.views.get(state.owner)
+ }
+
+ // I-commit: every launch reaches the machine after the commit that activates
+ // its tab was projected, or names a tab the store did not leave active.
+ function expectLaunchesAfterTheirCommit(minLaunches: number) {
+ expect(machineHarness.launches.length).toBeGreaterThanOrEqual(minLaunches)
+ for (const entry of machineHarness.launches) {
+ if (entry.storeActiveTab === entry.launch.tabId) {
+ expect(entry.projectedTab).toBe(entry.launch.tabId)
+ }
+ }
+ }
+
+ async function renderApp() {
render(<App />)
- // The strip relaunch resolves the tab's app against the loaded listing.
await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
- await act(async () => {
- await Promise.resolve()
- })
+ await flushMacrotask()
+ }
+
+ async function openFromSidebar(app: typeof ALPHA, openCount: number) {
act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(app!))
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
- await waitFor(() => expect(currentController.navItem).toBe(DESKTOP_ROUTES.apps))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(openCount))
+ await flushMacrotask()
}
- function clickActiveStripTab(label: string) {
- const activeTab = currentController.workspaceTabs.tabs.find(
- tab => tab.id === currentController.workspaceTabs.activeTabId
- )
- expect(activeTab?.kind).toBe('app')
- // The strip marks the active tab with aria-pressed.
- fireEvent.click(screen.getByRole('button', { name: label, pressed: true }))
+ async function shortcut(commandId: string) {
+ await act(async () => {
+ shortcutCommandCb?.(commandId, 'host')
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+ })
}
- async function handOffMarkdownFromPlugin() {
- const payload = await openGfsResourcePayload(
- resolvedFile('md1', 'README.md', { gfsUri: 'gfs://main/md1' })
- )
- act(() => openGfsResourceCb?.(payload))
- expect(currentController.navItem).toBe(DESKTOP_ROUTES.preview)
+ function tabOf(appRef: string) {
+ return controller.workspaceTabs.tabs.find(tab => tab.app?.appRef === appRef)
}
- it('closes the embed when a plugin handoff leaves the app tab after a relaunch rejected by main', async () => {
- await renderWithLiveApp(ALPHA)
- expect(sandboxUi.close).not.toHaveBeenCalled()
+ function lastLaunch() {
+ return machineHarness.launches.at(-1)!
+ }
- sandboxUi.open.mockRejectedValueOnce(OPEN_REJECTED)
- clickActiveStripTab('Alpha')
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- await waitForLaunchFailure(ALPHA!.appRef)
+ it('launches a sidebar pick into its own new tab, named from the catalog', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+
+ const tab = tabOf(ALPHA!.appRef)!
+ expect(lastLaunch()).toMatchObject({
+ type: 'intent',
+ launch: {
+ tabId: tab.id,
+ appRef: ALPHA!.appRef,
+ route: { kind: 'tab' },
+ app: { label: 'Alpha', defaultPath: '/' },
+ },
+ })
+ expect(main.openCall(0)).toMatchObject({
+ launchId: lastLaunch().launch.launchId,
+ title: 'Alpha',
+ })
+ expect(owner()?.phase).toBe('mounted')
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ expect(sidebarHarness.props?.activeSandboxUiApp?.appRef).toBe(ALPHA!.appRef)
+ })
- await handOffMarkdownFromPlugin()
+ it('launches a picker-grid pick into its own new tab', async () => {
+ await renderApp()
+ act(() => sidebarHarness.props?.onSelect?.(DESKTOP_ROUTES.apps))
+ fireEvent.click(await screen.findByRole('button', { name: 'Open Beta' }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ expect(activeWorkspaceTab(controller.workspaceTabs)?.app?.appRef).toBe(BETA!.appRef)
+ expect(lastLaunch().launch.tabId).toBe(controller.workspaceTabs.activeTabId)
+ expectLaunchesAfterTheirCommit(1)
})
- it('closes the embed when a relaunch fails before reaching main (slot never measured)', async () => {
- await renderWithLiveApp(ALPHA)
-
- slotRect.mockReturnValue(UNMEASURED_SLOT)
- clickActiveStripTab('Alpha')
- await waitForLaunchFailure(ALPHA!.appRef)
- // The failure happened before the open IPC: main still holds the old view.
- expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+ it('paints the launch as loading until main confirms the mount', async () => {
+ await renderApp()
+ const held = main.holdNextOpen()
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
- slotRect.mockReturnValue(MEASURED_SLOT)
- await handOffMarkdownFromPlugin()
+ expect(screen.getByText('Loading app')).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Refresh app content' })).toBeNull()
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ await act(async () => held().resolve())
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ expect(screen.queryByText('Loading app')).toBeNull()
})
- it('closes the embed when leaving an app tab whose open failed after an app-to-app switch', async () => {
- await renderWithLiveApp(ALPHA)
-
- sandboxUi.open.mockRejectedValueOnce(OPEN_REJECTED)
- act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- await waitForLaunchFailure(BETA!.appRef)
- // app→app hands the embed over; it is never closed on the way in.
- expect(sandboxUi.close).not.toHaveBeenCalled()
-
- await handOffMarkdownFromPlugin()
+ it('paints a rejected open as the failure banner of its tab', async () => {
+ await renderApp()
+ main.failNextOpen(new Error('open rejected'))
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ expect(await screen.findByText(`${ALPHA!.appRef}: open rejected`)).toBeTruthy()
+ expect(screen.queryByTestId('sandbox-ui-mounted')).toBeNull()
+ expect(sidebarHarness.props?.activeSandboxUiApp ?? null).toBeNull()
})
- it('opens an app from the in-page picker grid as its own active tab that closes the embed on leave', async () => {
- // Reach the picker from a conversation through the sidebar, as a user does.
- currentController.selectedAgent = 'agent-a'
- currentController.activeChatId = 'chat-1'
- ;(currentController as { chatList: unknown }).chatList = [{ id: 'chat-1', title: 'Planning' }]
- render(<App />)
- await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
- act(() => sidebarHarness.props?.onSelect?.(DESKTOP_ROUTES.apps))
- expect(currentController.appsPickerActive).toBe(true)
-
- fireEvent.click(await screen.findByRole('button', { name: 'Open Alpha' }))
+ it('closes the view when the user leaves its tab and reopens it at the route it was left on', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
+ main.navigate('/inbox')
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
- const activeTab = activeWorkspaceTab(currentController.workspaceTabs)
- expect(activeTab?.kind).toBe('app')
- expect(activeTab?.app?.appRef).toBe(ALPHA!.appRef)
- expect(currentController.appsPickerActive).toBe(false)
- // The drawer comes up with the conversation the picker was reached from.
- expect(currentController.handleSelectChatAgent).toHaveBeenCalledWith(
- 'agent-a',
- expect.objectContaining({ chatId: 'chat-1', keepNavItem: true })
- )
- expect(sandboxUi.close).not.toHaveBeenCalled()
+ fireEvent.click(screen.getByRole('button', { name: 'New chat', pressed: false }))
+ await flushMacrotask()
- await handOffMarkdownFromPlugin()
+ expect(sandboxUi.close).toHaveBeenCalledWith({ launchId: first })
+ expect(tabOf(ALPHA!.appRef)?.app?.savedRoutePath).toBe('/inbox')
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ fireEvent.click(screen.getByRole('button', { name: 'Alpha', pressed: false }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ expect(lastLaunch()).toMatchObject({
+ type: 'intent',
+ launch: { route: { kind: 'tab', routePath: '/inbox' } },
+ })
+ expect(main.openCall(1).routePath).toBe('/inbox')
+ expectLaunchesAfterTheirCommit(2)
})
- // main tags every per-view event with the appRef it composed from the open
- // request (`${recipeNs}/${recipeName}` in the `sandboxUi:open` handler) and
- // echoes that request's `launchId` (pinned main-side by
- // ipc.sandboxUiLaunchId.test.ts). Derive both from the open() call the real
- // page sent instead of restating them.
- type ViewEventTag = { appRef: string; launchId: string }
- function closedEventFor(openCall: number): ViewEventTag {
- const request = sandboxUi.open.mock.calls[openCall]![0] as {
- recipeNs: string
- recipeName: string
- launchId: string
- }
- return { appRef: `${request.recipeNs}/${request.recipeName}`, launchId: request.launchId }
- }
+ it('leaves a live view alone when its active tab is clicked again (Q4)', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
- function emitToSubscribed<T>(subscribe: ReturnType<typeof vi.fn>, event: T) {
- const listeners = subscribe.mock.calls as unknown as Array<[(args: T) => void]>
- const unsubscribed = new Set(
- subscribe.mock.results
- .map((result, index) =>
- (result.value as ReturnType<typeof vi.fn>).mock.calls.length > 0 ? index : -1
- )
- .filter(index => index >= 0)
- )
- act(() => {
- listeners.forEach(([listener], index) => {
- if (!unsubscribed.has(index)) listener(event)
- })
- })
- }
+ fireEvent.click(screen.getByRole('button', { name: 'Alpha', pressed: true }))
+ await flushMacrotask()
- function emitSandboxUiClosed(event: ViewEventTag) {
- emitToSubscribed(sandboxUi.onClosed, event)
- }
+ expect(lastLaunch().type).toBe('intent')
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+ expect(sandboxUi.close).not.toHaveBeenCalled()
+ expect(owner()?.launchId).toBe(main.openCall(0).launchId)
+ })
- function emitRefreshError(event: ViewEventTag & { message: string }) {
- emitToSubscribed(sandboxUi.onRefreshError, event)
- }
+ it('shows a crash with Reopen, which relaunches the tab through the seam', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
- // Relaunches the live Alpha tab (open #2) and holds that open in flight, the
- // window in which main is still tearing down the view of open #1.
- function relaunchAlphaHeldOpen(): Promise<() => Promise<void>> {
- return relaunchAlphaHeldOpenFrom('Alpha')
- }
+ act(() => main.crash())
+ expect(await screen.findByText('The app closed unexpectedly.')).toBeTruthy()
+ expect(sidebarHarness.props?.activeSandboxUiApp ?? null).toBeNull()
- async function relaunchAlphaHeldOpenFrom(tabLabel: string): Promise<() => Promise<void>> {
- let resolveOpen: () => void = () => {}
- sandboxUi.open.mockImplementationOnce(
- () => new Promise<undefined>(resolve => (resolveOpen = () => resolve(undefined)))
- )
- clickActiveStripTab(tabLabel)
+ fireEvent.click(screen.getByRole('button', { name: 'Reopen' }))
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- expect(closedEventFor(1).appRef).toBe(ALPHA!.appRef)
- return async () => {
- await act(async () => {
- resolveOpen()
- await new Promise(resolve => window.setTimeout(resolve, 0))
- })
- expect(await screen.findByTestId('sandbox-ui-mounted')).toBeTruthy()
- }
- }
+ expect(lastLaunch()).toMatchObject({
+ type: 'relaunch',
+ launch: { tabId: tabOf(ALPHA!.appRef)!.id, route: { kind: 'tab' } },
+ })
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ expect(screen.queryByText('The app closed unexpectedly.')).toBeNull()
+ })
- it('keeps a same-app relaunch owned when the replaced view reports closed while the relaunch is opening', async () => {
- await renderWithLiveApp(ALPHA)
- const finishRelaunch = await relaunchAlphaHeldOpen()
+ it('shows a crash while the app is still opening with Reopen (DEC-10)', async () => {
+ await renderApp()
+ main.holdNextOpen()
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
+ expect(screen.getByText('Loading app')).toBeTruthy()
- // The view of open #1 dies (crash / teardown) before open #2 resolves.
- emitSandboxUiClosed(closedEventFor(0))
- await finishRelaunch()
+ act(() => main.crash())
- await handOffMarkdownFromPlugin()
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ expect(await screen.findByText('The app closed unexpectedly.')).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'Reopen' }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ expect(lastLaunch().type).toBe('relaunch')
})
- it("ignores a same-app relaunch's predecessor refresh failure but shows the live view's", async () => {
- await renderWithLiveApp(ALPHA)
- const finishRelaunch = await relaunchAlphaHeldOpen()
+ it('relaunches a dead view when its tab is clicked again', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ act(() => main.crash())
+ await screen.findByText('The app closed unexpectedly.')
- emitRefreshError({ ...closedEventFor(0), message: 'stale failure' })
- await finishRelaunch()
- expect(screen.queryByText(text => text.startsWith('Session refresh failed'))).toBeNull()
-
- emitRefreshError({ ...closedEventFor(1), message: 'live failure' })
- expect(
- await screen.findByText(text => text.startsWith('Session refresh failed: live failure'))
- ).toBeTruthy()
+ fireEvent.click(screen.getByRole('button', { name: 'Alpha', pressed: true }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ expect(lastLaunch().type).toBe('intent')
})
- it('keeps the live embed owned when a late closed event belongs to the app it replaced', async () => {
- await renderWithLiveApp(ALPHA)
- act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
+ it('relaunches from Refresh: the live view closes first and the new one opens where it stood', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
+ main.navigate('/tickets/7')
+
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh app content' }))
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- await act(async () => {
- await new Promise(resolve => window.setTimeout(resolve, 0))
+
+ expect(lastLaunch()).toMatchObject({
+ type: 'relaunch',
+ launch: { tabId: tabOf(ALPHA!.appRef)!.id },
})
+ expect(sandboxUi.close).toHaveBeenCalledWith({ launchId: first })
+ expect(sandboxUi.close.mock.invocationCallOrder[0]!).toBeLessThan(
+ sandboxUi.open.mock.invocationCallOrder[1]!
+ )
+ expect(main.openCall(1).routePath).toBe('/tickets/7')
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ })
- emitSandboxUiClosed(closedEventFor(0))
+ it('relaunches from the app.refresh command without flushing inside an effect', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
- await handOffMarkdownFromPlugin()
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ await shortcut('app.refresh')
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ expect(lastLaunch().type).toBe('relaunch')
})
- it('keeps the newer launch owned when a superseded open resolves late and its view then dies', async () => {
- render(<App />)
- await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
- await act(async () => {
- await Promise.resolve()
- })
- let resolveAlphaOpen: () => void = () => {}
- sandboxUi.open.mockImplementationOnce(
- () => new Promise<undefined>(resolve => (resolveAlphaOpen = () => resolve(undefined)))
- )
- act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
- act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ it("shows the live view's session failure with Retry, which relaunches it", async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
- // main serves the opens in order: Alpha mounts first, and its renderer dies
- // before Beta's open replaces it.
- await act(async () => {
- resolveAlphaOpen()
- await new Promise(resolve => window.setTimeout(resolve, 0))
- })
- emitSandboxUiClosed(closedEventFor(0))
+ act(() => main.refreshFailed('stale failure', crypto.randomUUID()))
+ expect(screen.queryByText(/Session refresh failed/)).toBeNull()
+ act(() => main.refreshFailed('mint failed'))
+ expect(await screen.findByText('Session refresh failed: mint failed.')).toBeTruthy()
- await handOffMarkdownFromPlugin()
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ expect(lastLaunch().type).toBe('relaunch')
+ expect(sandboxUi.close).toHaveBeenCalledWith({ launchId: first })
+ // The banner belonged to the view that was replaced.
+ await waitFor(() => expect(screen.queryByText(/Session refresh failed/)).toBeNull())
})
- it('drops the owner when the closed event belongs to the live embed', async () => {
- await renderWithLiveApp(ALPHA)
- act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- await act(async () => {
- await new Promise(resolve => window.setTimeout(resolve, 0))
- })
+ it('goes back to apps on the app.backToApps command, keeping the tab', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const alphaTab = controller.workspaceTabs.activeTabId
- emitSandboxUiClosed(closedEventFor(1))
+ await shortcut('app.backToApps')
- await handOffMarkdownFromPlugin()
- await act(async () => {
- await new Promise(resolve => window.setTimeout(resolve, 0))
- })
- // main already tore the view down: nothing is left to close.
- expect(sandboxUi.close).not.toHaveBeenCalled()
+ expect(machineHarness.events.at(-1)).toEqual({ type: 'backToApps' })
+ expect(sandboxUi.close).toHaveBeenCalledWith({ launchId: main.openCall(0).launchId })
+ expect(controller.workspaceTabs.activeTabId).toBe(alphaTab)
+ expect(await screen.findByRole('button', { name: 'Open Beta' })).toBeTruthy()
})
- it('opens a grid pick shown inside an app tab after back-to-apps as its own tab, leaving that tab intact', async () => {
- await renderWithLiveApp(ALPHA)
- const alphaTab = activeWorkspaceTab(currentController.workspaceTabs)
- expect(alphaTab?.kind).toBe('app')
+ it('renames the live tab after its title and ignores titles of other views', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
- // The in-view "Back to apps" button is gone by design; the host shortcut
- // command is the remaining real entry point.
- act(() => shortcutCommandCb?.('app.backToApps', 'host'))
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
- // Still inside the Alpha tab, now showing the picker grid.
- expect(currentController.workspaceTabs.activeTabId).toBe(alphaTab!.id)
+ act(() => main.retitle('Alpha Inbox'))
+ expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()
+ act(() => main.retitle('Stale', crypto.randomUUID()))
+ expect(screen.queryByRole('button', { name: 'Stale' })).toBeNull()
+ })
- fireEvent.click(await screen.findByRole('button', { name: 'Open Beta' }))
+ it('launches the app tab of a confirmed deep link at its explicit route and acks it once mounted', async () => {
+ await renderApp()
+ act(() =>
+ latestListener<SandboxUiDeepLinkEnvelope>(sandboxUi.onDeepLink)({
+ id: 1,
+ appRef: ALPHA!.appRef,
+ path: '/tasks/42',
+ })
+ )
+ await waitFor(() => expect(confirmDialogHarness.props?.title).toBe('Open app link?'))
+ await act(async () => confirmDialogHarness.props?.onConfirm())
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- const activeTab = activeWorkspaceTab(currentController.workspaceTabs)
- expect(activeTab?.id).not.toBe(alphaTab!.id)
- expect(activeTab?.kind).toBe('app')
- expect(activeTab?.app?.appRef).toBe(BETA!.appRef)
- const alphaAfter = currentController.workspaceTabs.tabs.find(tab => tab.id === alphaTab!.id)
- expect(alphaAfter?.app?.appRef).toBe(ALPHA!.appRef)
- expect(alphaAfter?.title).toBe(alphaTab!.title)
+ await waitFor(() => expect(sandboxUi.acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ expect(lastLaunch()).toMatchObject({
+ type: 'intent',
+ launch: { route: { kind: 'explicit', routePath: '/tasks/42' } },
+ })
+ expect(main.openCall(0).routePath).toBe('/tasks/42')
+ expectLaunchesAfterTheirCommit(1)
+ })
+
+ it('acks a deep link left before it mounted without retrying it, and keeps the queue moving (K23)', async () => {
+ await renderApp()
+ // The user leaves the deep link's tab through a shortcut in the very turn
+ // its launch reaches the machine, before anything else gets to render.
+ machineHarness.afterDispatch = event => {
+ if (event.type !== 'intent') return
+ machineHarness.afterDispatch = null
+ shortcutCommandCb?.('tabs.select1', 'host')
+ }
+ act(() =>
+ latestListener<SandboxUiDeepLinkEnvelope>(sandboxUi.onDeepLink)({
+ id: 1,
+ appRef: ALPHA!.appRef,
+ })
+ )
+ await waitFor(() => expect(confirmDialogHarness.props?.title).toBe('Open app link?'))
+ await act(async () => confirmDialogHarness.props?.onConfirm())
+
+ await waitFor(() => expect(sandboxUi.acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ expect(sandboxUi.open).not.toHaveBeenCalled()
+ expect(controller.workspaceTabs.activeTabId).toBe('chat-tab-1')
+ expect(machine().getSnapshot().views.size).toBe(0)
+
+ act(() =>
+ latestListener<SandboxUiDeepLinkEnvelope>(sandboxUi.onDeepLink)({
+ id: 2,
+ appRef: BETA!.appRef,
+ })
+ )
+ await waitFor(() => expect(confirmDialogHarness.props?.title).toBe('Open app link?'))
+ await act(async () => confirmDialogHarness.props?.onConfirm())
+ await waitFor(() => expect(sandboxUi.acknowledgeDeepLink).toHaveBeenCalledWith(2))
+ expect(main.openCall(0).recipeName).toBe('beta')
+ expect(sandboxUi.acknowledgeDeepLink).toHaveBeenCalledTimes(2)
})
- // App resolves app tabs against its own listing, refreshed on window focus and
+
+ // App resolves app tabs against its own catalog, refreshed on window focus and
// every 30 s. Firing the real focus listener drives that refresh.
- async function refreshAppListingOnFocus() {
+ async function refreshCatalogOnFocus() {
const calls = sandboxUi.listApps.mock.calls.length
act(() => {
window.dispatchEvent(new Event('focus'))
})
await waitFor(() => expect(sandboxUi.listApps.mock.calls.length).toBeGreaterThan(calls))
- await act(async () => {
- await new Promise(resolve => window.setTimeout(resolve, 0))
- })
- }
-
- function emitTitleChanged(event: ViewEventTag & { title: string }) {
- emitToSubscribed(sandboxUi.onTitleChanged, event)
- }
-
- it('renames the live app tab after its document.title, ignoring empty titles and titles from the view a relaunch replaces', async () => {
- await renderWithLiveApp(ALPHA)
- emitTitleChanged({ ...closedEventFor(0), title: 'Alpha Inbox' })
- expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()
- // A mid-navigation blank title keeps the last real one.
- emitTitleChanged({ ...closedEventFor(0), title: ' ' })
- expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()
-
- const finishRelaunch = await relaunchAlphaHeldOpenFrom('Alpha Inbox')
- // main only forwards titles of its active view; until the relaunch replaces
- // it, that is still the view of open #1.
- emitTitleChanged({ ...closedEventFor(0), title: 'Alpha Stale' })
- expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()
- expect(screen.queryByRole('button', { name: 'Alpha Stale' })).toBeNull()
-
- await finishRelaunch()
- emitTitleChanged({ ...closedEventFor(1), title: 'Alpha Fresh' })
- expect(screen.getByRole('button', { name: 'Alpha Fresh', pressed: true })).toBeTruthy()
- })
-
- function tabByAppRef(appRef: string) {
- return currentController.workspaceTabs.tabs.find(tab => tab.app?.appRef === appRef)
- }
-
- function openedAppRef(openCall: number): string {
- return closedEventFor(openCall).appRef
+ await flushMacrotask()
}
const BETA_RESTARTING: SandboxUiAppListing[] = APP_LISTING.map(app =>
app.appRef === BETA!.appRef ? { ...app, ready: false, phase: 'pending' } : app
)
- it('closes the live embed and shows the picker when the incoming app tab cannot be resolved, then relaunches it once the app is back', async () => {
- await renderWithLiveApp(BETA)
- act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- expect(openedAppRef(1)).toBe(ALPHA!.appRef)
- const betaTab = tabByAppRef(BETA!.appRef)!
+ it('closes the live view and shows the picker for an app tab the catalog cannot resolve, then relaunches it named from the catalog', async () => {
+ await renderApp()
+ await openFromSidebar(BETA, 1)
+ // The app renames its own tab; that title must never name it to main.
+ act(() => main.retitle('Beta Inbox'))
+ await openFromSidebar(ALPHA, 2)
+ const alpha = main.openCall(1).launchId
+ const betaTab = tabOf(BETA!.appRef)!
// Beta's pod restarts: App's next refresh drops it from the resolvable list.
sandboxUi.listApps.mockResolvedValue({ apps: BETA_RESTARTING })
- await refreshAppListingOnFocus()
+ await refreshCatalogOnFocus()
+ main.navigate('/inbox')
+ fireEvent.click(screen.getByRole('button', { name: 'Beta Inbox', pressed: false }))
+ await flushMacrotask()
- sandboxUi.getLocation.mockResolvedValue({ appRef: ALPHA!.appRef, routePath: '/inbox' })
- fireEvent.click(screen.getByRole('button', { name: 'Beta', pressed: false }))
-
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ expect(sandboxUi.close).toHaveBeenCalledWith({ launchId: alpha })
expect(sandboxUi.open).toHaveBeenCalledTimes(2)
- expect(currentController.workspaceTabs.activeTabId).toBe(betaTab.id)
- // Tab B shows the picker instead of Alpha's chrome over an empty slot.
+ expect(controller.workspaceTabs.activeTabId).toBe(betaTab.id)
+ expect(owner()).toBeUndefined()
expect(screen.queryByTestId('sandbox-ui-mounted')).toBeNull()
expect(await screen.findByRole('button', { name: 'Open Alpha' })).toBeTruthy()
- // A late title from Alpha must not relabel B.
- emitTitleChanged({ ...closedEventFor(1), title: 'Alpha Inbox' })
- const betaAfter = currentController.workspaceTabs.tabs.find(tab => tab.id === betaTab.id)
- expect(betaAfter?.title).toBe('Beta')
- expect(betaAfter?.app?.appRef).toBe(BETA!.appRef)
- expect(betaAfter?.app?.savedRoutePath).toBeUndefined()
- // Alpha's own route is still persisted on its tab.
- await waitFor(() => expect(tabByAppRef(ALPHA!.appRef)?.app?.savedRoutePath).toBe('/inbox'))
-
- // Beta is ready again: reactivating its (still existing) tab relaunches it.
+ // A late title from Alpha does not relabel Beta, and Alpha keeps its route.
+ act(() => main.retitle('Alpha Late', alpha))
+ expect(controller.workspaceTabs.tabs.find(tab => tab.id === betaTab.id)?.title).toBe(
+ 'Beta Inbox'
+ )
+ expect(tabOf(ALPHA!.appRef)?.app?.savedRoutePath).toBe('/inbox')
+
+ // Beta is ready again: clicking its tab relaunches it.
sandboxUi.listApps.mockResolvedValue({ apps: APP_LISTING })
- await refreshAppListingOnFocus()
- clickActiveStripTab('Beta')
+ await refreshCatalogOnFocus()
+ fireEvent.click(screen.getByRole('button', { name: 'Beta Inbox', pressed: true }))
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(3))
- expect(openedAppRef(2)).toBe(BETA!.appRef)
- expect(currentController.workspaceTabs.activeTabId).toBe(betaTab.id)
- expect(await screen.findByTestId('sandbox-ui-mounted')).toBeTruthy()
-
- // The relaunched Beta owns the embed again: leaving closes it.
- await handOffMarkdownFromPlugin()
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(2))
+ expect(main.openCall(2)).toMatchObject({ recipeName: 'beta', title: 'Beta' })
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
})
- it('does not hand the embed to a grid-opened app tab that App has not resolved yet when the user returns to it', async () => {
- // App's listing predates Beta becoming ready.
+ it('does not relaunch a grid-opened app tab App has not resolved yet when the user returns to it', async () => {
+ // App's catalog predates Beta becoming ready.
sandboxUi.listApps.mockResolvedValue({ apps: BETA_RESTARTING })
- await renderWithLiveApp(ALPHA)
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
// Beta turns ready between App refreshes; the picker grid loads its own list.
sandboxUi.listApps.mockResolvedValue({ apps: APP_LISTING })
fireEvent.click(screen.getByRole('button', { name: 'New chat', pressed: false }))
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ await flushMacrotask()
act(() => sidebarHarness.props?.onSelect?.(DESKTOP_ROUTES.apps))
fireEvent.click(await screen.findByRole('button', { name: 'Open Beta' }))
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- expect(openedAppRef(1)).toBe(BETA!.appRef)
- const betaTab = activeWorkspaceTab(currentController.workspaceTabs)!
- expect(betaTab.app?.appRef).toBe(BETA!.appRef)
- // The grid launch itself is a real app tab, not torn down on the way in.
- expect(sandboxUi.close).toHaveBeenCalledTimes(1)
+ expect(main.openCall(1)).toMatchObject({ recipeName: 'beta', title: 'Beta' })
+ const betaTab = activeWorkspaceTab(controller.workspaceTabs)!
+ await flushMacrotask()
- // Alpha (resolvable) takes the embed over from Beta.
fireEvent.click(screen.getByRole('button', { name: 'Alpha', pressed: false }))
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(3))
- expect(openedAppRef(2)).toBe(ALPHA!.appRef)
- expect(sandboxUi.close).toHaveBeenCalledTimes(1)
+ await flushMacrotask()
// Back to Beta before App's next refresh: it cannot be relaunched yet.
fireEvent.click(screen.getByRole('button', { name: 'Beta', pressed: false }))
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(2))
+ await flushMacrotask()
expect(sandboxUi.open).toHaveBeenCalledTimes(3)
- expect(currentController.workspaceTabs.activeTabId).toBe(betaTab.id)
+ expect(sandboxUi.close).toHaveBeenLastCalledWith({ launchId: main.openCall(2).launchId })
+ expect(controller.workspaceTabs.activeTabId).toBe(betaTab.id)
expect(screen.queryByTestId('sandbox-ui-mounted')).toBeNull()
- await refreshAppListingOnFocus()
- clickActiveStripTab('Beta')
+ await refreshCatalogOnFocus()
+ fireEvent.click(screen.getByRole('button', { name: 'Beta', pressed: true }))
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(4))
- expect(openedAppRef(3)).toBe(BETA!.appRef)
+ expect(main.openCall(3).recipeName).toBe('beta')
})
- it('hands the embed to a grid pick that App has not resolved yet while the app tab it replaces still owns the embed', async () => {
- // App's own listing predates Beta becoming ready; the page's grid sees it ready.
+
+ it('opens a grid pick App has not resolved yet as its own tab, leaving the tab it was picked from intact', async () => {
+ // App's catalog predates Beta becoming ready; the page's grid sees it ready.
sandboxUi.listApps.mockResolvedValueOnce({ apps: BETA_RESTARTING })
- await renderWithLiveApp(ALPHA)
- const alphaTab = activeWorkspaceTab(currentController.workspaceTabs)!
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const alphaTab = activeWorkspaceTab(controller.workspaceTabs)!
+
+ await shortcut('app.backToApps')
+ fireEvent.click(await screen.findByRole('button', { name: 'Open Beta' }))
- // A failed relaunch leaves the Alpha tab owning the embed and shows the grid.
- sandboxUi.open.mockRejectedValueOnce(OPEN_REJECTED)
- clickActiveStripTab('Alpha')
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- await waitForLaunchFailure(ALPHA!.appRef)
+ expect(main.openCall(1)).toMatchObject({ recipeName: 'beta', title: 'Beta' })
+ const active = activeWorkspaceTab(controller.workspaceTabs)!
+ expect(active.id).not.toBe(alphaTab.id)
+ expect(owner()?.tabId).toBe(active.id)
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ const alphaAfter = controller.workspaceTabs.tabs.find(tab => tab.id === alphaTab.id)
+ expect(alphaAfter?.app?.appRef).toBe(ALPHA!.appRef)
+ })
- fireEvent.click(await screen.findByRole('button', { name: 'Open Beta' }))
+ // A store update can be pending when a gesture runs (here, one written while
+ // App had not rendered yet). The reveal is picked from App's last render, but
+ // the updater lands on the pending store: the launch must follow the store.
+ function seedTabs(): void {
+ let state = createWorkspaceTabsState('chat-tab-1')
+ state = openAppTab(state, { id: 'ws-tab-90', appRef: ALPHA!.appRef, title: 'Alpha' })
+ state = newChatTab(state, 'ws-tab-91', null)
+ controller.workspaceTabs = state
+ }
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(3))
- expect(openedAppRef(2)).toBe(BETA!.appRef)
- const activeTab = activeWorkspaceTab(currentController.workspaceTabs)
- expect(activeTab?.id).not.toBe(alphaTab.id)
- expect(activeTab?.app?.appRef).toBe(BETA!.appRef)
- expect(await screen.findByTestId('sandbox-ui-mounted')).toBeTruthy()
- // app→app: the incoming open replaces the view; nothing closes it.
- await act(async () => {
- await new Promise(resolve => window.setTimeout(resolve, 0))
+ it('launches the app tab a relative shortcut lands on over a pending store update (DEC-9 a)', async () => {
+ seedTabs()
+ await renderApp()
+ // Tabs: [New chat, Alpha, New chat (active)]. From App's render, "next"
+ // wraps to the first chat; from the pending store it reaches Alpha.
+ act(() => {
+ controller.setWorkspaceTabs(state => selectWorkspaceTab(state, 'chat-tab-1'))
+ shortcutCommandCb?.('tabs.next', 'host')
})
- expect(sandboxUi.close).not.toHaveBeenCalled()
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
+
+ expect(controller.workspaceTabs.activeTabId).toBe('ws-tab-90')
+ expect(owner()?.tabId).toBe('ws-tab-90')
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ expectLaunchesAfterTheirCommit(1)
+ })
+
+ it('launches the app neighbour of a tab closed right after a pending update activated it', async () => {
+ seedTabs()
+ await renderApp()
+ // Tabs: [New chat (chat-tab-1), Alpha, New chat (active)]. The pending update
+ // activates chat-tab-1; the user closes it from the strip App last rendered.
+ act(() => {
+ controller.setWorkspaceTabs(state => selectWorkspaceTab(state, 'chat-tab-1'))
+ fireEvent.click(screen.getAllByRole('button', { name: 'Close New chat' })[0]!)
+ })
+ await flushMacrotask()
+
+ expect(controller.workspaceTabs.activeTabId).toBe('ws-tab-90')
+ expect(owner()?.tabId).toBe('ws-tab-90')
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+ })
+
+ it('launches an app tab a pending update activated when the user closes another tab', async () => {
+ seedTabs()
+ await renderApp()
+ // Tabs: [New chat (chat-tab-1), Alpha, New chat (active)]. The pending update
+ // activates Alpha; the user closes chat-tab-1, which is active in neither.
+ act(() => {
+ controller.setWorkspaceTabs(state => selectWorkspaceTab(state, 'ws-tab-90'))
+ fireEvent.click(screen.getAllByRole('button', { name: 'Close New chat' })[0]!)
+ })
+ await flushMacrotask()
+
+ expect(controller.workspaceTabs.tabs.map(tab => tab.id)).toEqual(['ws-tab-90', 'ws-tab-91'])
+ expect(controller.workspaceTabs.activeTabId).toBe('ws-tab-90')
+ expect(owner()?.tabId).toBe('ws-tab-90')
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+ expect(main.openCall(0).recipeName).toBe('alpha')
})
- it('drops a failed relaunch banner when the user moves to an app tab that cannot be resolved', async () => {
- await renderWithLiveApp(BETA)
+ it('does not relaunch a failed app tab when another tab is closed', async () => {
+ await renderApp()
+ main.failNextOpen(new Error('open rejected'))
act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- sandboxUi.listApps.mockResolvedValue({ apps: BETA_RESTARTING })
- await refreshAppListingOnFocus()
+ expect(await screen.findByText(`${ALPHA!.appRef}: open rejected`)).toBeTruthy()
- sandboxUi.open.mockRejectedValueOnce(OPEN_REJECTED)
- clickActiveStripTab('Alpha')
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(3))
- await waitForLaunchFailure(ALPHA!.appRef)
+ fireEvent.click(screen.getByRole('button', { name: 'Close New chat' }))
+ await flushMacrotask()
+
+ expect(controller.workspaceTabs.tabs.map(tab => tab.id)).toEqual([tabOf(ALPHA!.appRef)!.id])
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+ expect(machineHarness.launches).toHaveLength(1)
+ expect(screen.getByText(`${ALPHA!.appRef}: open rejected`)).toBeTruthy()
+ })
+
+ it('launches nothing when a pending reset removed the tab a shortcut picked (DEC-9 b)', async () => {
+ seedTabs()
+ await renderApp()
+ act(() => {
+ controller.setWorkspaceTabs(createWorkspaceTabsState('chat-tab-1'))
+ shortcutCommandCb?.('tabs.select2', 'host')
+ })
+ await flushMacrotask()
+
+ expect(controller.workspaceTabs.activeTabId).toBe('chat-tab-1')
+ expect(machineHarness.launches).toEqual([])
+ expect(sandboxUi.open).not.toHaveBeenCalled()
+ expect(sidebarHarness.props?.activeSandboxUiApp ?? null).toBeNull()
+ })
+ it('launches every tab shortcut and strip gesture after its commit (I-commit)', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ await openFromSidebar(BETA, 2)
+ // Tabs: [New chat, Alpha, Beta].
+ // After every gesture an active app tab has a launch that owns it (T4).
+ const expectActiveAppTabOwned = () => {
+ const active = activeWorkspaceTab(controller.workspaceTabs)
+ if (active?.kind !== 'app') return
+ expect(owner()?.tabId).toBe(active.id)
+ expect(owner()?.appRef).toBe(active.app?.appRef)
+ }
+ for (const commandId of [
+ 'tabs.select1',
+ 'tabs.select2',
+ 'tabs.next',
+ 'tabs.previous',
+ 'tabs.selectLast',
+ 'tabs.select1',
+ 'chat.closeTab',
+ ]) {
+ await shortcut(commandId)
+ expectActiveAppTabOwned()
+ }
fireEvent.click(screen.getByRole('button', { name: 'Beta', pressed: false }))
+ await flushMacrotask()
- // The Alpha tab still owned the embed after its failed relaunch.
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
- const alphaPrefix = `${ALPHA!.appRef}: `
- await waitFor(() => expect(screen.queryByText(text => text.startsWith(alphaPrefix))).toBeNull())
- expect(await screen.findByRole('button', { name: 'Open Alpha' })).toBeTruthy()
+ expect(owner()?.appRef).toBe(BETA!.appRef)
+ expectActiveAppTabOwned()
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ expectLaunchesAfterTheirCommit(7)
+ })
+
+ it('closes the view when a plugin hands off to a preview tab', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const payload = await openGfsResourcePayload(
+ resolvedFile('md1', 'README.md', { gfsUri: 'gfs://main/md1' })
+ )
+ act(() => openGfsResourceCb?.(payload))
+ await flushMacrotask()
+
+ expect(controller.navItem).toBe(DESKTOP_ROUTES.preview)
+ expect(sandboxUi.close).toHaveBeenCalledWith({ launchId: main.openCall(0).launchId })
+ expect(machine().getSnapshot().views.size).toBe(0)
+ })
+
+ it('opens a tab at the route the store kept for it when the machine has none', async () => {
+ // A route the store holds that no view of this renderer reported (the store
+ // outlived the views that left it).
+ let state = createWorkspaceTabsState('chat-tab-1')
+ state = openAppTab(state, { id: 'ws-tab-90', appRef: ALPHA!.appRef, title: 'Alpha' })
+ state = setAppTabSavedRoutePath(state, 'ws-tab-90', '/kept')
+ state = selectWorkspaceTab(state, 'chat-tab-1')
+ controller.workspaceTabs = state
+ await renderApp()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Alpha', pressed: false }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
+
+ expect(lastLaunch().launch.route).toEqual({ kind: 'tab', routePath: '/kept' })
+ expect(main.openCall(0).routePath).toBe('/kept')
+ })
+
+ it('keeps its machine alive through StrictMode effect replay', async () => {
+ render(
+ <StrictMode>
+ <App />
+ </StrictMode>
+ )
+ await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
+ await flushMacrotask()
+
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ })
+
+ it('fails the suite on a flushSync issued from inside an effect', () => {
+ function FlushesInAnEffect() {
+ useEffect(() => {
+ flushSync(() => {})
+ }, [])
+ return null
+ }
+ render(<FlushesInAnEffect />)
+ expect(flushSyncErrors.length).toBeGreaterThan(0)
+ flushSyncErrors = []
})
})
diff --git a/desktop-app/ui/src/__tests__/__fixtures__/sandboxUiMainFake.ts b/desktop-app/ui/src/__tests__/__fixtures__/sandboxUiMainFake.ts
new file mode 100644
index 000000000..b1374f5e7
--- /dev/null
+++ b/desktop-app/ui/src/__tests__/__fixtures__/sandboxUiMainFake.ts
@@ -0,0 +1,142 @@
+import { vi } from 'vitest'
+import type { SandboxUiReleaseReason, SandboxUiReleasedEvent } from '../../../../src/types'
+
+/**
+ * The lifecycle half of main's sandbox-ui contract, reduced to what App's
+ * wiring tests need: one live view at a time, `open` resolves once it mounted,
+ * `close({ launchId })` only closes that launch's view, and every view that
+ * dies reports `released` once, with the route it stood for (the requested one
+ * until the test navigates it, none for a crash) before the call that killed it
+ * resolves.
+ *
+ * The ownership properties themselves are checked against the real main process
+ * (`src/__tests__/embedOwnership.property.test.ts`); this only has to deliver
+ * the events, so App-level suites can run in jsdom.
+ */
+export type SandboxUiOpenCall = {
+ launchId: string
+ recipeNs: string
+ recipeName: string
+ title?: string
+ defaultPath?: string
+ routePath?: string
+}
+
+type HeldOpen = { resolve: () => void; reject: (error: Error) => void }
+
+export function createSandboxUiMainFake() {
+ const releasedListeners = new Set<(event: SandboxUiReleasedEvent) => void>()
+ const titleListeners = new Set<
+ (event: { appRef: string; launchId: string; title: string }) => void
+ >()
+ const refreshErrorListeners = new Set<
+ (event: { appRef: string; launchId: string; message: string }) => void
+ >()
+ let live: { launchId: string; appRef: string; routePath?: string } | null = null
+ const held: HeldOpen[] = []
+ let holdNext = 0
+ const failures: Error[] = []
+
+ function release(reason: SandboxUiReleaseReason, crashed = false): void {
+ if (!live) return
+ const view = live
+ live = null
+ const event: SandboxUiReleasedEvent = {
+ launchId: view.launchId,
+ reason,
+ location: crashed ? null : view.routePath ? { routePath: view.routePath } : {},
+ }
+ for (const listener of [...releasedListeners]) listener(event)
+ }
+
+ const open = vi.fn(async (request: SandboxUiOpenCall) => {
+ const appRef = `${request.recipeNs}/${request.recipeName}`
+ if (live) release('replaced')
+ const failure = failures.shift()
+ if (failure) throw failure
+ live = {
+ launchId: request.launchId,
+ appRef,
+ ...(request.routePath ? { routePath: request.routePath } : {}),
+ }
+ if (holdNext > 0) {
+ holdNext -= 1
+ await new Promise<void>((resolve, reject) => held.push({ resolve, reject }))
+ }
+ })
+
+ // Main's events reach the renderer in a later task than the call that
+ // caused them.
+ const close = vi.fn(async (request?: { launchId: string }) => {
+ await new Promise(resolve => setTimeout(resolve, 0))
+ if (!live || (request && request.launchId !== live.launchId)) return
+ release('closed')
+ })
+
+ return {
+ bridge: {
+ open,
+ close,
+ onReleased: vi.fn((listener: (event: SandboxUiReleasedEvent) => void) => {
+ releasedListeners.add(listener)
+ return () => releasedListeners.delete(listener)
+ }),
+ onTitleChanged: vi.fn(
+ (listener: (event: { appRef: string; launchId: string; title: string }) => void) => {
+ titleListeners.add(listener)
+ return () => titleListeners.delete(listener)
+ }
+ ),
+ onRefreshError: vi.fn(
+ (listener: (event: { appRef: string; launchId: string; message: string }) => void) => {
+ refreshErrorListeners.add(listener)
+ return () => refreshErrorListeners.delete(listener)
+ }
+ ),
+ },
+ /** The open request of the `index`-th open call. */
+ openCall(index: number): SandboxUiOpenCall {
+ const call = open.mock.calls[index]
+ if (!call) throw new Error(`no open call #${index}`)
+ return call[0]
+ },
+ live: () => live,
+ /** The next open stays in flight until the returned handle settles it. */
+ holdNextOpen(): () => HeldOpen {
+ holdNext += 1
+ const index = held.length
+ return () => {
+ const handle = held[index]
+ if (!handle) throw new Error('the held open has not been sent yet')
+ return handle
+ }
+ },
+ failNextOpen(error: Error): void {
+ failures.push(error)
+ },
+ /** The user navigated the live view. */
+ navigate(routePath: string): void {
+ if (live) live = { ...live, routePath }
+ },
+ crash(): void {
+ release('crashed', true)
+ },
+ endSession(): void {
+ release('session')
+ },
+ retitle(title: string, launchId = live?.launchId): void {
+ if (!launchId) return
+ for (const listener of [...titleListeners]) {
+ listener({ appRef: live?.appRef ?? '', launchId, title })
+ }
+ },
+ refreshFailed(message: string, launchId = live?.launchId): void {
+ if (!launchId) return
+ for (const listener of [...refreshErrorListeners]) {
+ listener({ appRef: live?.appRef ?? '', launchId, message })
+ }
+ },
+ }
+}
+
+export type SandboxUiMainFake = ReturnType<typeof createSandboxUiMainFake>
diff --git a/desktop-app/ui/src/hooks/useEmbedOwnership.ts b/desktop-app/ui/src/hooks/useEmbedOwnership.ts
new file mode 100644
index 000000000..b6c8cc4cf
--- /dev/null
+++ b/desktop-app/ui/src/hooks/useEmbedOwnership.ts
@@ -0,0 +1,7 @@
+import { useSyncExternalStore } from 'react'
+import type { EmbedOwnershipState } from '../lib/embedOwnership.types'
+import type { EmbedOwnershipMachine } from '../lib/embedOwnershipMachine.types'
+
+export function useEmbedOwnership(machine: EmbedOwnershipMachine): EmbedOwnershipState {
+ return useSyncExternalStore(machine.subscribe, machine.getSnapshot, machine.getSnapshot)
+}
diff --git a/desktop-app/ui/src/lib/__tests__/embedOwnership.table.test.ts b/desktop-app/ui/src/lib/__tests__/embedOwnership.table.test.ts
index 732654871..a7f9c6e1b 100644
--- a/desktop-app/ui/src/lib/__tests__/embedOwnership.table.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/embedOwnership.table.test.ts
@@ -458,10 +458,15 @@ describe('decision table rows', () => {
expect(out.state.views.size).toBe(0)
})
- it('R1b: a crash of an opening owner is abandoned, not a crash failure', () => {
+ it('R1a: a crash of the owner while it opens is a crash failure and a failed launch', () => {
const out = reduceEmbedOwnership(stateOf(openingSeq), ev.released(A, 'crashed', null))
- expect(out.state.failure).toBeNull()
- expect(out.effects).toEqual([{ type: 'launchSettled', launchId: A, outcome: 'abandoned' }])
+ expect(out.state.owner).toBeNull()
+ expect(out.state.views.size).toBe(0)
+ expect(out.state.failure).toEqual({ tabId: T1, launchId: A, kind: 'crashed' })
+ expect(out.state.lastRoute.size).toBe(0)
+ expect(out.effects).toEqual([{ type: 'launchSettled', launchId: A, outcome: 'failed' }])
+ // The late rejection of that open is then a duplicate.
+ expectNoop(out.state, ev.openFailed(A))
})
it('R2: released for an unknown launch is ignored', () => {
@@ -916,6 +921,7 @@ describe('R-settle walks every row', () => {
O3: [...openingSeq, ev.openFailed(A)],
O4: [...mountedSeq, ev.mounted(C)],
R1a: [...mountedSeq, ev.released(A, 'crashed', null)],
+ 'R1a (opening)': [...openingSeq, ev.released(A, 'crashed', null)],
R1b: [...openingSeq, ev.released(A, 'session', null)],
R2: [...closeRequestedSeq, ev.released(A), ev.released(A)],
X1: [...closeRequestedSeq, ev.closeFailed(A)],
diff --git a/desktop-app/ui/src/lib/embedOwnership.ts b/desktop-app/ui/src/lib/embedOwnership.ts
index 5a56723c9..8b4d67f4f 100644
--- a/desktop-app/ui/src/lib/embedOwnership.ts
+++ b/desktop-app/ui/src/lib/embedOwnership.ts
@@ -220,17 +220,23 @@ function applyRow(state: EmbedOwnershipState, event: EmbedEvent): RowResult {
next = { ...next, lastRoute }
effects.push({ type: 'persistRoute', tabId: record.tabId, route })
}
- // Only a view the user was looking at counts as a crash; one still opening
- // settles as abandoned instead of showing "closed unexpectedly".
- const crashed = event.reason === 'crashed' && wasOwner && record.phase === 'mounted'
+ // A crash of the view the user is waiting on or looking at must leave the tab
+ // something to show and a way back. Any other release (session end, a view
+ // being closed) is not the app's fault and leaves the tab simply unowned.
+ const crashed =
+ event.reason === 'crashed' &&
+ wasOwner &&
+ (record.phase === 'mounted' || record.phase === 'opening')
+ if (!crashed) return { state: next, effects }
+ // A crash before the mount is a failed launch, not an abandoned one: a deep
+ // link waiting on it must retry instead of being dropped.
+ if (record.phase === 'opening') {
+ effects.push({ type: 'launchSettled', launchId: record.launchId, outcome: 'failed' })
+ }
return {
state: next,
effects,
- ...(crashed
- ? {
- failure: { tabId: record.tabId, launchId: record.launchId, kind: 'crashed' as const },
- }
- : {}),
+ failure: { tabId: record.tabId, launchId: record.launchId, kind: 'crashed' },
}
}
diff --git a/desktop-app/ui/src/lib/embedOwnershipMachine.types.ts b/desktop-app/ui/src/lib/embedOwnershipMachine.types.ts
index 07e9f40d4..1b1ce5129 100644
--- a/desktop-app/ui/src/lib/embedOwnershipMachine.types.ts
+++ b/desktop-app/ui/src/lib/embedOwnershipMachine.types.ts
@@ -47,7 +47,10 @@ export type EmbedOwnershipMachineDeps = {
onHandoffReady?: (requestId: number) => void
/** Only refresh failures of the launch that owns the embed when they arrive. */
onOwnerRefreshError?: (event: EmbedRefreshErrorEvent) => void
- /** Observability for tests: every reduced event with the state around it and its effects. */
+ /**
+ * Every reduced event with the state around it and its effects, before the
+ * effects run. It must not dispatch: it observes, it does not decide.
+ */
onTransition?: (transition: {
event: EmbedEvent
previous: EmbedOwnershipState
diff --git a/desktop-app/ui/src/lib/embedOwnershipView.ts b/desktop-app/ui/src/lib/embedOwnershipView.ts
new file mode 100644
index 000000000..bac2b0222
--- /dev/null
+++ b/desktop-app/ui/src/lib/embedOwnershipView.ts
@@ -0,0 +1,44 @@
+import type { EmbedFailure, EmbedOwnershipState } from './embedOwnership.types'
+import type { EmbedViewState } from './embedOwnershipView.types'
+
+/** Projects the ownership state onto what the active app tab shows. */
+export function embedViewState(state: EmbedOwnershipState): EmbedViewState {
+ const owner = state.owner === null ? undefined : state.views.get(state.owner)
+ if (owner) {
+ return owner.phase === 'mounted'
+ ? { kind: 'mounted', launch: owner }
+ : { kind: 'minting', launch: owner }
+ }
+ if (state.failure !== null && state.failure.tabId === state.activeAppTabId) {
+ return { kind: 'failed', failure: state.failure }
+ }
+ return { kind: 'idle' }
+}
+
+export const EMBED_SLOT_UNMEASURED_MESSAGE = 'Embed slot is not laid out — cannot determine bounds'
+export const EMBED_CRASHED_MESSAGE = 'The app closed unexpectedly.'
+
+/**
+ * Session errors carry the upstream status as "(404):" and bridge failures as
+ * "403 Forbidden"; either form picks the user-facing copy.
+ */
+export function httpStatusOf(message: string): number | null {
+ const match = /\((\d{3})\)|\b(\d{3})\s+[A-Za-z]/.exec(message)
+ return match ? Number(match[1] ?? match[2]) : null
+}
+
+export function embedFailureMessage(failure: EmbedFailure): string {
+ if (failure.kind === 'slot') return EMBED_SLOT_UNMEASURED_MESSAGE
+ if (failure.kind === 'crashed') return EMBED_CRASHED_MESSAGE
+ const message = failure.message ?? ''
+ switch (httpStatusOf(message)) {
+ case 404:
+ return 'This app was removed.'
+ case 403:
+ return "You don't have access to this app."
+ case 409:
+ return 'This app is starting up — try again in a moment.'
+ default:
+ return message
+ }
+}
diff --git a/desktop-app/ui/src/lib/embedOwnershipView.types.ts b/desktop-app/ui/src/lib/embedOwnershipView.types.ts
new file mode 100644
index 000000000..9e377b4a3
--- /dev/null
+++ b/desktop-app/ui/src/lib/embedOwnershipView.types.ts
@@ -0,0 +1,11 @@
+import type { EmbedFailure, ViewRecord } from './embedOwnership.types'
+
+/** What the embed slot of the active app tab shows. */
+export type EmbedViewState =
+ /** No launch owns the tab and nothing failed: the app picker. */
+ | { kind: 'idle' }
+ /** The owner is on its way to main (waiting, measuring or opening). */
+ | { kind: 'minting'; launch: ViewRecord }
+ | { kind: 'mounted'; launch: ViewRecord }
+ /** The tab's last launch failed or its view crashed. */
+ | { kind: 'failed'; failure: EmbedFailure }
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsx
index 115c0f002..c9ee25b0d 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx
@@ -1,15 +1,16 @@
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
-import { IconButton, StatusBanner } from '@components/Common'
+import { Button, IconButton, StatusBanner } from '@components/Common'
+import { useEmbedOwnership } from '@hooks/useEmbedOwnership'
import { joinClasses } from '@lib/classNames'
-import type { ActiveSandboxUiApp } from '@/uiTypes'
+import { embedFailureMessage, embedViewState, httpStatusOf } from '@lib/embedOwnershipView'
import SandboxCurrentContentSearch from '../components/SandboxCurrentContentSearch'
import type { AppFindState } from '../components/SandboxCurrentContentSearch/types'
import { IconCopy, IconRefresh, IconSandboxUi } from '../components/SidebarNav/icons'
import { clickableRowProps } from '../lib/clickableRowProps'
import { toActiveSandboxUiApp } from '../lib/sandboxUiAppSelection'
import type { SandboxUiAppListing } from '../lib/sandboxUiAppSelection.types'
-import type { SandboxUiPageProps, SandboxUiShortcutOpenResult } from './SandboxUiPage.types'
+import type { SandboxUiPageProps } from './SandboxUiPage.types'
type PhasePillTone = 'allowed' | 'warning' | 'denied' | 'info' | 'muted'
@@ -44,22 +45,24 @@ function phasePill(phase: string | null): { label: string; tone: PhasePillTone }
}
}
-// `launchId` names one open request end to end: main tags every per-view event
-// (`closed`, `refreshError`, `titleChanged`) with the id of the open that
-// mounted that view. Relaunching the SAME app keeps the appRef, so only the id
-// tells a late event from the replaced view apart from the live one.
-type LaunchState =
- | { kind: 'idle' }
- | { kind: 'minting'; appRef: string; launchId: string }
- | { kind: 'mounted'; appRef: string; launchId: string }
- | { kind: 'error'; appRef: string; launchId: string; message: string }
+// Past this, the overlay hides the native view without a preview: a brief flash
+// of the empty slot is better than a view that never gets out of the way.
+const CAPTURE_PREVIEW_TIMEOUT_MS = 500
function statusFromError(err: unknown): { status: number | null; message: string } {
const message = err instanceof Error ? err.message : String(err)
- // SandboxUiSessionError surfaces "(404):" / "(403):" etc., while bridge
- // failures can include "403 Forbidden". Pull out either form for UX copy.
- const m = /\((\d{3})\)|\b(\d{3})\s+[A-Za-z]/.exec(message)
- return { status: m ? Number(m[1] ?? m[2]) : null, message }
+ return { status: httpStatusOf(message), message }
+}
+
+function previewWithin(timeoutMs: number): Promise<string | null> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const timedOut = new Promise<null>(resolve => {
+ timer = setTimeout(() => resolve(null), timeoutMs)
+ })
+ const capture = Promise.resolve()
+ .then(() => window.clerum.sandboxUi.capturePreview())
+ .catch(() => null)
+ return Promise.race([capture, timedOut]).finally(() => clearTimeout(timer))
}
function appLabel(app: SandboxUiAppListing): string {
@@ -203,47 +206,27 @@ function TitlebarLeadingAction({
}
export function SandboxUiPage({
- actionRequest = null,
+ embed,
+ activeAppRef = null,
+ refreshError = null,
boundsRefreshKey = 0,
currentTeamId = '',
headerShellOverlayOpen = false,
sidebarShellOverlayOpen = false,
toastShellOverlayOpen = false,
deepLinkShellOverlayOpen = false,
- shortcutApp = null,
- shortcutOpenRequestId = 0,
localSearchRequestId = 0,
titlebarLeadingContainer = null,
onLaunchApp,
- onEmbeddedAppOpening,
- onEmbeddedAppMounted,
- onEmbeddedAppBack,
- onEmbeddedAppOpenFailed,
+ onRelaunch,
onEmbedBoundsApplied,
onEmbedSlotTopChange,
onEmbedSlotRightChange,
onNotify,
- onShortcutOpenResult,
}: SandboxUiPageProps) {
+ const view = embedViewState(useEmbedOwnership(embed))
const [apps, setApps] = useState<SandboxUiAppListing[] | null>(null)
const [error, setError] = useState<string | null>(null)
- const [launch, setLaunchState] = useState<LaunchState>({ kind: 'idle' })
- // Mirrors `launch` synchronously: the `sandboxUi:closed` listener must judge
- // the launch that is current when the event lands, not the last committed
- // render.
- const launchRef = useRef<LaunchState>({ kind: 'idle' })
- // Bumped by every launch and by back-to-apps. An open that resolves after a
- // newer one took over must not write its outcome: that would re-point
- // `launchRef` at the superseded app, so a later `closed` for it would release
- // the owner of the embed that is actually live.
- const launchSeqRef = useRef(0)
- const setLaunch = useCallback((next: LaunchState) => {
- launchRef.current = next
- setLaunchState(next)
- }, [])
- const [refreshError, setRefreshError] = useState<{ launchId: string; message: string } | null>(
- null
- )
const [appsPage, setAppsPage] = useState(0)
const [embedPreviewDataUrl, setEmbedPreviewDataUrl] = useState<string | null>(null)
const [localSearchOpen, setLocalSearchOpen] = useState(false)
@@ -252,10 +235,10 @@ export function SandboxUiPage({
const embedSlotRef = useRef<HTMLDivElement>(null)
const activeFindClientRequestIdRef = useRef<number | null>(null)
const localSearchStateRef = useRef<AppFindState>({ status: 'idle' })
- const lastLocalSearchRequestIdRef = useRef(shortcutApp ? localSearchRequestId : 0)
+ const lastLocalSearchRequestIdRef = useRef(
+ view.kind === 'mounted' || view.kind === 'minting' ? localSearchRequestId : 0
+ )
const localSearchPreviousFocusRef = useRef<HTMLElement | null>(null)
- const lastShortcutOpenRequestIdRef = useRef(0)
- const lastActionRequestIdRef = useRef(0)
// The deep-link confirm/error dialogs render as renderer DOM at the App
// shell level; like the other shell overlays they must hide the native
// WebContentsView, which always paints above the DOM, to be visible at all.
@@ -285,38 +268,18 @@ export function SandboxUiPage({
setAppsPage(0)
}, [apps?.length])
- // Re-render the picker if the main process tears the view down (e.g. on
- // app quit, parent window close, or the embed's renderer crashing).
- useEffect(() => {
- return window.clerum.sandboxUi.onClosed(({ launchId }) => {
- // A closed event can land after the renderer has already launched
- // another app, or relaunched the same one (it was in flight when the
- // switch happened). Reconciling it would drop the owner of the NEW embed,
- // which then stays painted over every later surface. Only the launch it
- // names may be released.
- const current = launchRef.current
- if (current.kind === 'idle' || current.launchId !== launchId) return
- if (current.kind === 'mounted' || current.kind === 'minting') {
- setLaunch({ kind: 'idle' })
- }
- setRefreshError(null)
- onEmbeddedAppBack?.()
- })
- }, [onEmbeddedAppBack, setLaunch])
-
- // Surface refresh failures (403 / 410 / network) as an in-chrome banner.
- // 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
- if (current.kind === 'idle' || current.launchId !== launchId) return
- setRefreshError({ launchId, message })
- })
- }, [])
+ // A launch waits for a registered measurer before anything is sent to main,
+ // so the slot it opens into is the one this page lays out. The slot only
+ // renders while a launch owns the tab; a measurement that never finds it laid
+ // out reports `null` and the launch fails before reaching main.
+ useLayoutEffect(
+ () =>
+ embed.registerMeasurer(async () => {
+ const rect = await waitForEmbedSlotRect(embedSlotRef)
+ return rect ? boundsFromRect(rect) : null
+ }),
+ [embed]
+ )
useEffect(() => {
return window.clerum.sandboxUi.onFindResult(result => {
@@ -400,138 +363,18 @@ export function SandboxUiPage({
)
useEffect(() => {
- if (localSearchRequestId <= lastLocalSearchRequestIdRef.current || launch.kind !== 'mounted') {
+ if (localSearchRequestId <= lastLocalSearchRequestIdRef.current || view.kind !== 'mounted') {
return
}
lastLocalSearchRequestIdRef.current = localSearchRequestId
localSearchPreviousFocusRef.current = document.activeElement as HTMLElement | null
setLocalSearchOpen(true)
- }, [launch.kind, localSearchRequestId])
+ }, [view.kind, localSearchRequestId])
useEffect(() => {
- if (launch.kind === 'mounted' || !localSearchOpen) return
+ if (view.kind === 'mounted' || !localSearchOpen) return
stopLocalSearch()
- }, [launch.kind, localSearchOpen, stopLocalSearch])
-
- // The embed lifecycle is governed by the universal tab store (mini-spec 05
- // §3), not by this page's mount/unmount: deactivating an app tab persists its
- // route and closes the embed from App.tsx, so the store is the single
- // solicited `close()` emitter. The old unmount-driven `close()` +
- // `setTimeout` cancel lived here; it could not capture the route on an
- // app→app switch (this page stays mounted) and risked a double close, so it
- // was removed. Unsolicited teardown still flows through `onClosed` (crash /
- // quit / partition GC) and the explicit back-to-apps `closeEmbed`.
-
- const openApp = useCallback(
- async (app: ActiveSandboxUiApp): Promise<SandboxUiShortcutOpenResult> => {
- const [recipeNs, recipeName] = app.appRef.split('/', 2)
- if (!recipeNs || !recipeName) {
- return { status: 'failed', message: 'Invalid app reference' }
- }
- // Transition to 'minting' so the slot div mounts. Wait for the next
- // layout commit so getBoundingClientRect() reflects the slot's real
- // position (otherwise we'd be reading before React has rendered the
- // slot, and the fallback would mount the WebContentsView full-window —
- // covering the close button until the next ResizeObserver tick).
- const seq = ++launchSeqRef.current
- // Unique across page remounts, unlike `seq`: main echoes it on events
- // that can outlive this component instance.
- const launchId = crypto.randomUUID()
- setLaunch({ kind: 'minting', appRef: app.appRef, launchId })
- onEmbeddedAppOpening?.(
- {
- appRef: app.appRef,
- label: app.label,
- icon: app.icon,
- defaultPath: app.defaultPath,
- ...(app.routePath ? { routePath: app.routePath } : {}),
- },
- launchId
- )
- try {
- const rect = await waitForEmbedSlotRect(embedSlotRef)
- if (!rect) {
- throw new Error('Embed slot is not laid out — cannot determine bounds')
- }
- const bounds = boundsFromRect(rect)
- await window.clerum.sandboxUi.open({
- recipeNs,
- recipeName,
- // Title travels from the trusted app list into consent prompts and
- // notification attribution. The plugin never gets to name itself.
- ...(app.label ? { title: app.label } : {}),
- defaultPath: app.defaultPath,
- ...(app.routePath ? { routePath: app.routePath } : {}),
- bounds,
- launchId,
- })
- if (seq === launchSeqRef.current) {
- setLaunch({ kind: 'mounted', appRef: app.appRef, launchId })
- onEmbeddedAppMounted?.()
- }
- return { status: 'mounted' }
- } catch (err) {
- const { status, message } = statusFromError(err)
- const userFacing =
- status === 404
- ? 'This app was removed.'
- : status === 403
- ? "You don't have access to this app."
- : status === 409
- ? 'This app is starting up — try again in a moment.'
- : message
- if (seq === launchSeqRef.current) {
- setLaunch({ kind: 'error', appRef: app.appRef, launchId, message: userFacing })
- onEmbeddedAppOpenFailed?.()
- }
- return { status: 'failed', message: userFacing }
- }
- },
- [onEmbeddedAppMounted, onEmbeddedAppOpening, onEmbeddedAppOpenFailed, setLaunch]
- )
-
- const closeEmbed = useCallback(async () => {
- launchSeqRef.current += 1
- try {
- await window.clerum.sandboxUi.close()
- } catch {
- // Always return the user to the app picker even if the main-process
- // close call races with an already-closed view.
- }
- setLaunch({ kind: 'idle' })
- setRefreshError(null)
- }, [setLaunch])
-
- const onBackToApps = useCallback(async () => {
- await closeEmbed()
- onEmbeddedAppBack?.()
- }, [closeEmbed, onEmbeddedAppBack])
-
- // In-place hard-reload of the embedded app — fetches freshly-arrived
- // server data (e.g. new inbox items) without tearing the view down, so the
- // user no longer has to navigate away and back to see updates.
- const onRefresh = useCallback(() => {
- void window.clerum.sandboxUi.reload()
- }, [])
-
- useEffect(() => {
- if (!actionRequest || actionRequest.id <= lastActionRequestIdRef.current) return
- lastActionRequestIdRef.current = actionRequest.id
- if (actionRequest.action === 'release') {
- // Any launch state counts: a minting open must not write its outcome, and
- // a failed one must not leave its banner on a tab it never belonged to.
- launchSeqRef.current += 1
- setLaunch({ kind: 'idle' })
- setRefreshError(null)
- return
- }
- if (launch.kind !== 'mounted') return
- if (actionRequest.action === 'refresh') {
- onRefresh()
- } else if (actionRequest.action === 'back-to-apps') {
- void onBackToApps()
- }
- }, [actionRequest, launch.kind, onBackToApps, onRefresh, setLaunch])
+ }, [view.kind, localSearchOpen, stopLocalSearch])
const onCopyDeepLink = useCallback(async () => {
try {
@@ -543,20 +386,13 @@ export function SandboxUiPage({
}
}, [currentTeamId, onNotify])
- useEffect(() => {
- if (shortcutOpenRequestId === lastShortcutOpenRequestIdRef.current) return
- lastShortcutOpenRequestIdRef.current = shortcutOpenRequestId
- if (shortcutOpenRequestId <= 0 || !shortcutApp) return
- void openApp(shortcutApp).then(result => {
- void onShortcutOpenResult?.(shortcutOpenRequestId, result)
- })
- }, [onShortcutOpenResult, openApp, shortcutApp, shortcutOpenRequestId])
+ const embedLive = view.kind === 'mounted' || view.kind === 'minting'
- // Track bounds while mounted; also during 'minting' so openApp can read
- // the slot's rect AFTER the layout pass that renders the slot div.
+ // Track bounds while mounted; also while minting so the slot is placed by
+ // the time the open reads it.
useEmbedBounds(
embedSlotRef,
- launch.kind === 'mounted' || launch.kind === 'minting',
+ embedLive,
shellOverlayOpen,
boundsRefreshKey,
onEmbedBoundsApplied,
@@ -571,12 +407,7 @@ export function SandboxUiPage({
let cancelled = false
const updateVisibility = async (): Promise<void> => {
if (shellOverlayOpen) {
- let dataUrl: string | null = null
- try {
- dataUrl = await window.clerum.sandboxUi.capturePreview()
- } catch {
- // A missing preview must not prevent the shell overlay from opening.
- }
+ const dataUrl = await previewWithin(CAPTURE_PREVIEW_TIMEOUT_MS)
if (cancelled) return
if (dataUrl) {
setEmbedPreviewDataUrl(dataUrl)
@@ -591,7 +422,7 @@ export function SandboxUiPage({
return
}
- if (launch.kind === 'mounted' || launch.kind === 'minting') {
+ if (embedLive) {
const rect = embedSlotRef.current?.getBoundingClientRect()
if (rect) {
try {
@@ -614,17 +445,21 @@ export function SandboxUiPage({
return () => {
cancelled = true
}
- }, [launch.kind, shellOverlayOpen])
+ }, [embedLive, shellOverlayOpen])
- if (launch.kind === 'mounted' || launch.kind === 'minting') {
+ if (view.kind === 'mounted' || view.kind === 'minting') {
+ // Only failures of the launch that owns the tab right now; one from a view
+ // the user already left must not surface on its replacement.
const showRefreshBanner =
- refreshError && launch.kind === 'mounted' && refreshError.launchId === launch.launchId
+ refreshError !== null &&
+ view.kind === 'mounted' &&
+ refreshError.launchId === view.launch.launchId
// The refresh/copy pair only exists while 'mounted'. The chat-drawer toggle
// moved to the app header (mini-spec 04a §C), so the leading slot carries no
// drawer control any more. In the 'minting' state both are absent, so
// portaling the wrapper unconditionally would inject an empty <div> into the
// shared title bar. Only portal when at least one control will render.
- const hasLeadingActions = launch.kind === 'mounted'
+ const hasLeadingActions = view.kind === 'mounted'
return (
<section className="page" data-testid="sandbox-ui-mounted">
{/* App actions live in the native title bar's leading slot (icon-only,
@@ -637,32 +472,35 @@ export function SandboxUiPage({
hasLeadingActions &&
createPortal(
<div className="window-titlebar__leading-actions">
- {launch.kind === 'mounted' && (
- <>
- <TitlebarLeadingAction
- className="sandbox-ui-refresh-btn"
- label="Refresh app content"
- onClick={onRefresh}
- >
- <IconRefresh />
- </TitlebarLeadingAction>
- <TitlebarLeadingAction
- className="sandbox-ui-copy-link-btn"
- label="Copy current app link"
- onClick={() => void onCopyDeepLink()}
- >
- <IconCopy />
- </TitlebarLeadingAction>
- </>
- )}
+ <TitlebarLeadingAction
+ className="sandbox-ui-refresh-btn"
+ label="Refresh app content"
+ onClick={() => onRelaunch?.()}
+ >
+ <IconRefresh />
+ </TitlebarLeadingAction>
+ <TitlebarLeadingAction
+ className="sandbox-ui-copy-link-btn"
+ label="Copy current app link"
+ onClick={() => void onCopyDeepLink()}
+ >
+ <IconCopy />
+ </TitlebarLeadingAction>
</div>,
titlebarLeadingContainer
)}
{showRefreshBanner && (
- <StatusBanner
- tone="error"
- text={`Session refresh failed: ${refreshError.message}. Close and re-open the app to continue.`}
- />
+ <StatusBanner tone="error">
+ <span>{`Session refresh failed: ${refreshError.message}.`}</span>
+ <Button
+ className="sandbox-ui-status-action"
+ size="xs"
+ variant="outline"
+ onClick={() => onRelaunch?.()}
+ >
+ Retry
+ </Button>
+ </StatusBanner>
)}
{localSearchOpen ? (
<SandboxCurrentContentSearch
@@ -688,7 +526,7 @@ export function SandboxUiPage({
data-testid="sandbox-ui-embed-preview"
/>
)}
- {launch.kind === 'minting' && (
+ {view.kind === 'minting' && (
<div className="sandbox-ui-loading" role="status" aria-live="polite">
<span className="sandbox-ui-loading__mark" aria-hidden="true">
<span />
@@ -703,6 +541,27 @@ export function SandboxUiPage({
)
}
+ const failure = view.kind === 'failed' ? view.failure : null
+ const failureBanner =
+ failure === null ? null : failure.kind === 'crashed' ? (
+ <StatusBanner tone="error">
+ <span>{embedFailureMessage(failure)}</span>
+ <Button
+ className="sandbox-ui-status-action"
+ size="xs"
+ variant="outline"
+ onClick={() => onRelaunch?.()}
+ >
+ Reopen
+ </Button>
+ </StatusBanner>
+ ) : (
+ <StatusBanner
+ tone="error"
+ text={`${activeAppRef ?? 'App'}: ${embedFailureMessage(failure)}`}
+ />
+ )
+
if (apps === null) {
return (
<section className="page apps-page" aria-busy="true">
@@ -740,6 +599,7 @@ export function SandboxUiPage({
return (
<section className="page apps-page">
{error && <StatusBanner tone="error" text={error} />}
+ {failureBanner}
<div className="apps-page-header">
<div className="apps-page-header-text">
@@ -784,9 +644,7 @@ export function SandboxUiPage({
return (
<section className="page apps-page">
{error && <StatusBanner tone="error" text={error} />}
- {launch.kind === 'error' && (
- <StatusBanner tone="error" text={`${launch.appRef}: ${launch.message}`} />
- )}
+ {failureBanner}
<div className="apps-page-header">
<div className="apps-page-header-text">
diff --git a/desktop-app/ui/src/pages/SandboxUiPage.types.ts b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
index e89d2711b..f03562599 100644
--- a/desktop-app/ui/src/pages/SandboxUiPage.types.ts
+++ b/desktop-app/ui/src/pages/SandboxUiPage.types.ts
@@ -1,3 +1,4 @@
+import type { EmbedOwnershipMachine } from '@lib/embedOwnershipMachine.types'
import type { ActiveSandboxUiApp, Tone } from '@/uiTypes'
export type SandboxUiConversationOrigin = {
@@ -7,43 +8,30 @@ export type SandboxUiConversationOrigin = {
teamId?: string
}
-export type SandboxUiShortcutOpenResult =
- | { status: 'mounted' }
- | { status: 'failed'; message: string }
-
-// `release` returns the page to its picker without closing the embed: the
-// caller already owns (and emits) the close.
-export type SandboxUiPageAction = 'refresh' | 'back-to-apps' | 'release'
+export type SandboxUiRefreshError = { launchId: string; message: string }
export type SandboxUiPageProps = {
- actionRequest?: {
- id: number
- action: SandboxUiPageAction
- } | null
+ /** Who owns the embed: the page paints its state and measures the slot for it. */
+ embed: EmbedOwnershipMachine
+ /** The app of the active app tab, naming a failed launch in its banner. */
+ activeAppRef?: string | null
+ /** The latest session refresh failure of the launch that owned the embed when it arrived. */
+ refreshError?: SandboxUiRefreshError | null
boundsRefreshKey?: string | number
currentTeamId?: string
headerShellOverlayOpen?: boolean
sidebarShellOverlayOpen?: boolean
toastShellOverlayOpen?: boolean
deepLinkShellOverlayOpen?: boolean
- shortcutApp?: ActiveSandboxUiApp | null
- shortcutOpenRequestId?: number
localSearchRequestId?: number
titlebarLeadingContainer?: HTMLElement | null
// The picker grid hands the chosen app to the owner instead of opening it
- // itself, so every embed is opened against a workspace tab that owns it. The
- // app comes back through `shortcutApp` / `shortcutOpenRequestId`.
+ // itself, so every embed is opened against a workspace tab that owns it.
onLaunchApp: (app: ActiveSandboxUiApp) => void
- onEmbeddedAppOpening?: (app: ActiveSandboxUiApp, launchId: string) => void
- onEmbeddedAppMounted?: () => void
- onEmbeddedAppBack?: () => void
- onEmbeddedAppOpenFailed?: () => void
+ /** Tears the active tab's view down and opens a fresh one (Refresh, Reopen, Retry). */
+ onRelaunch?: () => void
onEmbedBoundsApplied?: () => void
onEmbedSlotTopChange?: (topPx: number) => void
onEmbedSlotRightChange?: (rightPx: number) => void
onNotify?: (message: string, tone: Tone) => void
- onShortcutOpenResult?: (
- requestId: number,
- result: SandboxUiShortcutOpenResult
- ) => void | Promise<void>
}
diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.focus.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.focus.test.tsx
index deb1d9096..44ed4a795 100644
--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.focus.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.focus.test.tsx
@@ -1,13 +1,15 @@
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
-import { LaunchingSandboxUiPage as SandboxUiPage } from './__fixtures__/launchingSandboxUiPage'
+import {
+ LaunchingSandboxUiPage as SandboxUiPage,
+ createPageEmbed,
+} from './__fixtures__/launchingSandboxUiPage'
const sandboxUi = {
listApps: vi.fn(),
open: vi.fn(),
close: vi.fn(),
- reload: vi.fn(),
copyDeepLink: vi.fn(),
setBounds: vi.fn(),
setVisible: vi.fn(),
@@ -16,8 +18,6 @@ const sandboxUi = {
stopFindInPage: vi.fn(),
focusActive: vi.fn(),
onFindResult: vi.fn(() => vi.fn()),
- onClosed: vi.fn(() => vi.fn()),
- onRefreshError: vi.fn(() => vi.fn()),
}
const apps = [
@@ -117,19 +117,15 @@ describe('SandboxUiPage contextual-search focus ownership', () => {
})
it('does not replay a stale focus request after the page remounts', async () => {
- const first = render(<SandboxUiPage localSearchRequestId={0} />)
+ // App's machine outlives the page: a remount finds the app already mounted.
+ const embed = createPageEmbed()
+ const first = render(<SandboxUiPage embed={embed} localSearchRequestId={0} />)
await openApp()
- first.rerender(<SandboxUiPage localSearchRequestId={1} />)
+ first.rerender(<SandboxUiPage embed={embed} localSearchRequestId={1} />)
await screen.findByRole('textbox', { name: 'Find in current app' })
first.unmount()
- render(
- <SandboxUiPage
- localSearchRequestId={1}
- shortcutApp={{ appRef: apps[0]!.appRef, defaultPath: '/', label: 'Sales CRM' }}
- shortcutOpenRequestId={1}
- />
- )
+ render(<SandboxUiPage embed={embed} localSearchRequestId={1} />)
await screen.findByTestId('sandbox-ui-mounted')
await new Promise(resolve => window.setTimeout(resolve, 0))
diff --git a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
index 94055d234..c6a043482 100644
--- a/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/SandboxUiPage.test.tsx
@@ -1,15 +1,18 @@
// @vitest-environment jsdom
import React from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import type { EmbedOwnershipMachine } from '@lib/embedOwnershipMachine.types'
import { SandboxUiPage as SandboxUiPageBase } from '../SandboxUiPage'
-import { LaunchingSandboxUiPage as SandboxUiPage } from './__fixtures__/launchingSandboxUiPage'
+import {
+ LaunchingSandboxUiPage as SandboxUiPage,
+ createPageEmbed,
+} from './__fixtures__/launchingSandboxUiPage'
const sandboxUi = {
listApps: vi.fn(),
open: vi.fn(),
close: vi.fn(),
- reload: vi.fn(),
copyDeepLink: vi.fn(),
setBounds: vi.fn(),
setVisible: vi.fn(),
@@ -18,8 +21,6 @@ const sandboxUi = {
stopFindInPage: vi.fn(),
focusActive: vi.fn(),
onFindResult: vi.fn((_callback: (result: FindResultPayload) => void) => vi.fn()),
- onClosed: vi.fn(() => vi.fn()),
- onRefreshError: vi.fn(() => vi.fn()),
}
type FindResultPayload = {
requestId: number
@@ -125,11 +126,8 @@ describe('SandboxUiPage', () => {
],
})
const onLaunchApp = vi.fn()
- const onEmbeddedAppOpening = vi.fn()
- render(
- <SandboxUiPageBase onLaunchApp={onLaunchApp} onEmbeddedAppOpening={onEmbeddedAppOpening} />
- )
+ render(<SandboxUiPageBase embed={createPageEmbed()} onLaunchApp={onLaunchApp} />)
fireEvent.click(await screen.findByRole('button', { name: "Open Andy's Sales CRM" }))
expect(onLaunchApp).toHaveBeenCalledExactlyOnceWith({
@@ -141,7 +139,6 @@ describe('SandboxUiPage', () => {
await new Promise(resolve => window.setTimeout(resolve, 0))
// Without an owner feeding the app back, the page stays on the picker.
expect(sandboxUi.open).not.toHaveBeenCalled()
- expect(onEmbeddedAppOpening).not.toHaveBeenCalled()
expect(screen.queryByTestId('sandbox-ui-mounted')).toBeNull()
})
@@ -160,7 +157,7 @@ describe('SandboxUiPage', () => {
})
const onLaunchApp = vi.fn()
- render(<SandboxUiPageBase onLaunchApp={onLaunchApp} />)
+ render(<SandboxUiPageBase embed={createPageEmbed()} onLaunchApp={onLaunchApp} />)
fireEvent.click(await screen.findByText("Andy's Sales CRM"))
expect(screen.queryByRole('button', { name: "Open Andy's Sales CRM" })).toBeNull()
@@ -307,50 +304,7 @@ describe('SandboxUiPage', () => {
expect(screen.getByRole('button', { name: 'Copy current app link' })).toBeTruthy()
})
- it('routes controlled refresh and back requests through mounted-app owners', async () => {
- sandboxUi.listApps.mockResolvedValue({
- apps: [
- {
- appRef: 'sandbox-recipes/sales-crm',
- title: 'Sales CRM',
- defaultPath: '/',
- ready: true,
- phase: 'active',
- updatedAt: null,
- },
- ],
- })
- sandboxUi.open.mockResolvedValue(undefined)
- sandboxUi.close.mockResolvedValue(undefined)
- sandboxUi.reload.mockResolvedValue(undefined)
- const onEmbeddedAppBack = vi.fn()
- const { rerender } = render(
- <SandboxUiPage actionRequest={null} onEmbeddedAppBack={onEmbeddedAppBack} />
- )
- fireEvent.click(await screen.findByRole('button', { name: 'Open Sales CRM' }))
- await screen.findByRole('button', { name: 'Refresh app content' })
-
- rerender(
- <SandboxUiPage
- actionRequest={{ id: 1, action: 'refresh' }}
- onEmbeddedAppBack={onEmbeddedAppBack}
- />
- )
- await waitFor(() => expect(sandboxUi.reload).toHaveBeenCalledOnce())
-
- rerender(
- <SandboxUiPage
- actionRequest={{ id: 2, action: 'back-to-apps' }}
- onEmbeddedAppBack={onEmbeddedAppBack}
- />
- )
- await waitFor(() => {
- expect(sandboxUi.close).toHaveBeenCalledOnce()
- expect(onEmbeddedAppBack).toHaveBeenCalledOnce()
- })
- })
-
- it('does not replay an app action requested while the native view is mounting', async () => {
+ it('asks its owner to relaunch on Refresh, only once the app is mounted', async () => {
sandboxUi.listApps.mockResolvedValue({
apps: [
{
@@ -370,25 +324,19 @@ describe('SandboxUiPage', () => {
finishOpen = resolve
})
)
- sandboxUi.reload.mockResolvedValue(undefined)
- const onEmbeddedAppMounted = vi.fn()
- const { rerender } = render(
- <SandboxUiPage actionRequest={null} onEmbeddedAppMounted={onEmbeddedAppMounted} />
- )
+ const onRelaunch = vi.fn()
+ render(<SandboxUiPage onRelaunch={onRelaunch} />)
fireEvent.click(await screen.findByRole('button', { name: 'Open Sales CRM' }))
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledOnce())
+ // While the view is still opening there is nothing to refresh.
+ expect(screen.queryByRole('button', { name: 'Refresh app content' })).toBeNull()
- rerender(
- <SandboxUiPage
- actionRequest={{ id: 1, action: 'refresh' }}
- onEmbeddedAppMounted={onEmbeddedAppMounted}
- />
- )
- expect(sandboxUi.reload).not.toHaveBeenCalled()
+ await act(async () => finishOpen())
+ fireEvent.click(await screen.findByRole('button', { name: 'Refresh app content' }))
- finishOpen()
- await waitFor(() => expect(onEmbeddedAppMounted).toHaveBeenCalledOnce())
- expect(sandboxUi.reload).not.toHaveBeenCalled()
+ expect(onRelaunch).toHaveBeenCalledOnce()
+ // The relaunch is the owner's: the page itself neither reloads nor closes.
+ expect(sandboxUi.close).not.toHaveBeenCalled()
})
it('runs contextual find only against the mounted active WebContents contract', async () => {
@@ -539,20 +487,15 @@ describe('SandboxUiPage', () => {
it('opens a deep-linked app at its stable entry point before handing off the client route', async () => {
sandboxUi.listApps.mockResolvedValueOnce({ apps: [] })
sandboxUi.open.mockResolvedValueOnce(undefined)
- const onEmbeddedAppOpening = vi.fn()
- const onShortcutOpenResult = vi.fn()
render(
<SandboxUiPage
- shortcutApp={{
+ initialLaunch={{
appRef: 'sandbox-recipes/task-board',
label: 'Agentic Task Board',
defaultPath: '/',
routePath: '/tasks/task-42',
}}
- shortcutOpenRequestId={1}
- onEmbeddedAppOpening={onEmbeddedAppOpening}
- onShortcutOpenResult={onShortcutOpenResult}
/>
)
@@ -575,45 +518,128 @@ describe('SandboxUiPage', () => {
launchId: expect.any(String),
})
})
- // The owner learns the same launch id main will echo on this view's events.
- const { launchId } = sandboxUi.open.mock.calls[0]![0] as { launchId: string }
- expect(onEmbeddedAppOpening).toHaveBeenCalledWith(
- {
- appRef: 'sandbox-recipes/task-board',
- label: 'Agentic Task Board',
- defaultPath: '/',
- routePath: '/tasks/task-42',
- },
- launchId
- )
- await waitFor(() => {
- expect(onShortcutOpenResult).toHaveBeenCalledWith(1, { status: 'mounted' })
- })
+ expect(await screen.findByTestId('sandbox-ui-mounted')).toBeTruthy()
})
- it('reports a failed deep-linked shortcut open without acknowledging success', async () => {
- sandboxUi.listApps.mockResolvedValueOnce({ apps: [] })
+ it('shows a failed open as the failure banner of the active app', async () => {
+ sandboxUi.listApps.mockResolvedValue({ apps: [] })
sandboxUi.open.mockRejectedValueOnce(new Error('native mount failed'))
- const onShortcutOpenResult = vi.fn()
render(
<SandboxUiPage
- shortcutApp={{
+ activeAppRef="sandbox-recipes/task-board"
+ initialLaunch={{
appRef: 'sandbox-recipes/task-board',
label: 'Agentic Task Board',
defaultPath: '/',
}}
- shortcutOpenRequestId={1}
- onShortcutOpenResult={onShortcutOpenResult}
/>
)
- await waitFor(() => {
- expect(onShortcutOpenResult).toHaveBeenCalledWith(1, {
- status: 'failed',
- message: 'native mount failed',
- })
- })
+ expect(await screen.findByText('sandbox-recipes/task-board: native mount failed')).toBeTruthy()
+ expect(screen.queryByTestId('sandbox-ui-mounted')).toBeNull()
+ })
+
+ it('maps the session status of a failed open to its user-facing copy', async () => {
+ sandboxUi.listApps.mockResolvedValue({ apps: [] })
+ sandboxUi.open.mockRejectedValueOnce(new Error('Sandbox UI session failed (404): gone'))
+
+ render(
+ <SandboxUiPage
+ activeAppRef="sandbox-recipes/task-board"
+ initialLaunch={{ appRef: 'sandbox-recipes/task-board', label: 'Task', defaultPath: '/' }}
+ />
+ )
+
+ expect(
+ await screen.findByText('sandbox-recipes/task-board: This app was removed.')
+ ).toBeTruthy()
+ })
+
+ it('shows a slot that never laid out as the slot failure', async () => {
+ sandboxUi.listApps.mockResolvedValue({ apps: [] })
+ vi.mocked(HTMLElement.prototype.getBoundingClientRect).mockReturnValue({
+ x: 0,
+ y: 0,
+ top: 0,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ width: 0,
+ height: 0,
+ toJSON: () => ({}),
+ } as DOMRect)
+
+ render(
+ <SandboxUiPage
+ activeAppRef="sandbox-recipes/task-board"
+ initialLaunch={{ appRef: 'sandbox-recipes/task-board', label: 'Task', defaultPath: '/' }}
+ />
+ )
+
+ expect(
+ await screen.findByText(
+ 'sandbox-recipes/task-board: Embed slot is not laid out — cannot determine bounds'
+ )
+ ).toBeTruthy()
+ expect(sandboxUi.open).not.toHaveBeenCalled()
+ })
+
+ // What main reports when the mounted view's renderer dies.
+ function crashOf(embed: EmbedOwnershipMachine, openCall = 0) {
+ const { launchId } = sandboxUi.open.mock.calls[openCall]![0] as { launchId: string }
+ act(() => embed.onReleased({ launchId, reason: 'crashed', location: null }))
+ }
+
+ it('shows a crash of the mounted app with a Reopen that asks the owner to relaunch', async () => {
+ sandboxUi.listApps.mockResolvedValue({ apps: [] })
+ sandboxUi.open.mockResolvedValue(undefined)
+ const embed = createPageEmbed()
+ const onRelaunch = vi.fn()
+
+ render(
+ <SandboxUiPage
+ embed={embed}
+ onRelaunch={onRelaunch}
+ initialLaunch={{ appRef: 'sandbox-recipes/task-board', label: 'Task', defaultPath: '/' }}
+ />
+ )
+ await screen.findByRole('button', { name: 'Refresh app content' })
+
+ crashOf(embed)
+
+ expect(await screen.findByText('The app closed unexpectedly.')).toBeTruthy()
+ expect(screen.queryByTestId('sandbox-ui-mounted')).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'Reopen' }))
+ expect(onRelaunch).toHaveBeenCalledOnce()
+ })
+
+ it("shows the live view's session failure with a Retry that asks the owner to relaunch", async () => {
+ sandboxUi.listApps.mockResolvedValue({ apps: [] })
+ sandboxUi.open.mockResolvedValue(undefined)
+ const onRelaunch = vi.fn()
+ const app = { appRef: 'sandbox-recipes/task-board', label: 'Task', defaultPath: '/' }
+
+ const { rerender } = render(<SandboxUiPage onRelaunch={onRelaunch} initialLaunch={app} />)
+ await screen.findByRole('button', { name: 'Refresh app content' })
+ const { launchId } = sandboxUi.open.mock.calls[0]![0] as { launchId: string }
+
+ // A failure of a view that is not the live one is not shown.
+ rerender(
+ <SandboxUiPage
+ onRelaunch={onRelaunch}
+ refreshError={{ launchId: crypto.randomUUID(), message: 'stale' }}
+ />
+ )
+ expect(screen.queryByText(/Session refresh failed/)).toBeNull()
+
+ rerender(
+ <SandboxUiPage onRelaunch={onRelaunch} refreshError={{ launchId, message: 'mint failed' }} />
+ )
+ expect(await screen.findByText('Session refresh failed: mint failed.')).toBeTruthy()
+ expect(screen.queryByText(/Close and re-open/)).toBeNull()
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }))
+ expect(onRelaunch).toHaveBeenCalledOnce()
})
it('keeps the embed mounted during Strict Mode effect replay', async () => {
@@ -630,11 +656,10 @@ describe('SandboxUiPage', () => {
],
})
sandboxUi.open.mockResolvedValueOnce(undefined)
- const onEmbeddedAppBack = vi.fn()
render(
<React.StrictMode>
- <SandboxUiPage onEmbeddedAppBack={onEmbeddedAppBack} />
+ <SandboxUiPage />
</React.StrictMode>
)
@@ -643,7 +668,8 @@ describe('SandboxUiPage', () => {
// The mounted embed survives StrictMode's double-invoke without tearing down;
// its leading refresh control is the observable that it stayed mounted.
expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
- expect(onEmbeddedAppBack).not.toHaveBeenCalled()
+ expect(sandboxUi.open).toHaveBeenCalledOnce()
+ expect(sandboxUi.close).not.toHaveBeenCalled()
})
it('copies a deep link for the current app route and active team', async () => {
@@ -773,36 +799,6 @@ describe('SandboxUiPage', () => {
})
})
- it('reloads the embed in place when the Refresh button is clicked (no navigate-away needed)', async () => {
- sandboxUi.listApps.mockResolvedValueOnce({
- apps: [
- {
- appRef: 'sandbox-recipes/sales-crm',
- title: "Andy's Sales CRM",
- defaultPath: '/',
- ready: true,
- phase: 'active',
- updatedAt: null,
- },
- ],
- })
- sandboxUi.open.mockResolvedValueOnce(undefined)
- sandboxUi.reload.mockResolvedValueOnce(undefined)
-
- render(<SandboxUiPage />)
-
- fireEvent.click(await screen.findByRole('button', { name: "Open Andy's Sales CRM" }))
- await screen.findByTestId('sandbox-ui-mounted')
-
- fireEvent.click(screen.getByRole('button', { name: 'Refresh app content' }))
-
- await waitFor(() => {
- expect(sandboxUi.reload).toHaveBeenCalledTimes(1)
- })
- // Refresh must NOT tear the embed down (that's the old navigate-away workaround).
- expect(sandboxUi.close).not.toHaveBeenCalled()
- })
-
it('shows an embed preview and hides the native view while shell overlays are open', async () => {
sandboxUi.listApps.mockResolvedValueOnce({
apps: [
@@ -998,6 +994,35 @@ describe('SandboxUiPage', () => {
expect(sandboxUi.setVisible.mock.calls).toEqual([[true]])
})
+ it('hides the native view without a preview when the capture does not answer in time', async () => {
+ sandboxUi.listApps.mockResolvedValue({ apps: [] })
+ sandboxUi.open.mockResolvedValue(undefined)
+ sandboxUi.capturePreview.mockReturnValue(new Promise<string | null>(() => {}))
+ const app = { appRef: 'sandbox-recipes/task-board', label: 'Task', defaultPath: '/' }
+ const { rerender } = render(<SandboxUiPage initialLaunch={app} />)
+ await screen.findByRole('button', { name: 'Refresh app content' })
+ await waitFor(() => expect(sandboxUi.setVisible).toHaveBeenLastCalledWith(true))
+ sandboxUi.setVisible.mockClear()
+
+ vi.useFakeTimers()
+ try {
+ rerender(<SandboxUiPage headerShellOverlayOpen />)
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(499)
+ })
+ expect(sandboxUi.capturePreview).toHaveBeenCalled()
+ expect(sandboxUi.setVisible).not.toHaveBeenCalled()
+
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(1)
+ })
+ expect(sandboxUi.setVisible.mock.calls).toEqual([[false]])
+ expect(screen.queryByTestId('sandbox-ui-embed-preview')).toBeNull()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
it('hides an active native view even before local launch state is available', async () => {
sandboxUi.listApps.mockResolvedValueOnce({ apps: [] })
sandboxUi.capturePreview.mockResolvedValueOnce(null)
diff --git a/desktop-app/ui/src/pages/__tests__/__fixtures__/launchingSandboxUiPage.tsx b/desktop-app/ui/src/pages/__tests__/__fixtures__/launchingSandboxUiPage.tsx
index 06819a78e..eba144422 100644
--- a/desktop-app/ui/src/pages/__tests__/__fixtures__/launchingSandboxUiPage.tsx
+++ b/desktop-app/ui/src/pages/__tests__/__fixtures__/launchingSandboxUiPage.tsx
@@ -1,35 +1,86 @@
-import { type ComponentProps, useCallback, useState } from 'react'
+import { type ComponentProps, useCallback, useEffect, useRef, useState } from 'react'
+import type { Launch } from '@lib/embedOwnership.types'
+import { createEmbedOwnershipMachine } from '@lib/embedOwnershipMachine'
+import type { EmbedOwnershipMachine } from '@lib/embedOwnershipMachine.types'
import type { ActiveSandboxUiApp } from '@/uiTypes'
import { SandboxUiPage } from '../../SandboxUiPage'
-type LaunchingSandboxUiPageProps = Omit<ComponentProps<typeof SandboxUiPage>, 'onLaunchApp'> & {
+/** The real ownership machine, talking to whatever `window.clerum.sandboxUi` the test installed. */
+export function createPageEmbed(): EmbedOwnershipMachine {
+ return createEmbedOwnershipMachine({
+ bridge: {
+ open: request => window.clerum.sandboxUi.open(request),
+ close: request => window.clerum.sandboxUi.close(request),
+ },
+ updateTabs: () => {},
+ })
+}
+
+type LaunchingSandboxUiPageProps = Omit<
+ ComponentProps<typeof SandboxUiPage>,
+ 'onLaunchApp' | 'embed'
+> & {
+ embed?: EmbedOwnershipMachine
onLaunchApp?: (app: ActiveSandboxUiApp) => void
+ /** Launched once on mount, the way a deep link to `routePath` is. */
+ initialLaunch?: ActiveSandboxUiApp
+}
+
+function launchOf(app: ActiveSandboxUiApp, tabId: string): Launch {
+ return {
+ launchId: crypto.randomUUID(),
+ tabId,
+ appRef: app.appRef,
+ route:
+ app.routePath !== undefined
+ ? { kind: 'explicit', routePath: app.routePath }
+ : { kind: 'tab' },
+ app: { label: app.label, defaultPath: app.defaultPath },
+ }
}
// The picker grid never opens an app itself: it hands it to the owner, and App
-// (`launchSandboxUiApp`) feeds it back as `shortcutApp` with a fresh
-// `shortcutOpenRequestId`. Page-level tests that need a mounted app reproduce
-// exactly that round-trip here; the App-level ownership suite covers the real
-// owner end to end. The title-bar container is document.body so the portaled
-// mounted-app actions stay queryable via `screen`.
-export function LaunchingSandboxUiPage({ onLaunchApp, ...props }: LaunchingSandboxUiPageProps) {
- const [launched, setLaunched] = useState<{ app: ActiveSandboxUiApp; requestId: number } | null>(
- null
+// opens a new app tab for it and launches into it once that tab is committed.
+// Page-level tests that need a mounted app reproduce that here against the real
+// machine: project the new tab, then dispatch its launch. The App-level suites
+// cover App's own seam. The title-bar container is document.body so the
+// portaled mounted-app actions stay queryable via `screen`.
+export function LaunchingSandboxUiPage({
+ embed: providedEmbed,
+ onLaunchApp,
+ initialLaunch,
+ ...props
+}: LaunchingSandboxUiPageProps) {
+ const [embed] = useState(() => providedEmbed ?? createPageEmbed())
+ const tabSequenceRef = useRef(0)
+ const launch = useCallback(
+ (app: ActiveSandboxUiApp) => {
+ const tabId = `ws-tab-${++tabSequenceRef.current}`
+ embed.dispatch({ type: 'projected', activeAppTabId: tabId })
+ const next = launchOf(app, tabId)
+ embed.registerWhenSettled(next.launchId)
+ embed.dispatch({ type: 'intent', launch: next })
+ },
+ [embed]
)
const handleLaunchApp = useCallback(
(app: ActiveSandboxUiApp) => {
onLaunchApp?.(app)
- setLaunched(current => ({ app, requestId: (current?.requestId ?? 0) + 1 }))
+ launch(app)
},
- [onLaunchApp]
+ [launch, onLaunchApp]
)
+ const initialLaunchRef = useRef(initialLaunch)
+ useEffect(() => {
+ const app = initialLaunchRef.current
+ initialLaunchRef.current = undefined
+ if (app) launch(app)
+ }, [launch])
return (
<SandboxUiPage
titlebarLeadingContainer={document.body}
{...props}
- {...(launched
- ? { shortcutApp: launched.app, shortcutOpenRequestId: launched.requestId }
- : {})}
+ embed={embed}
onLaunchApp={handleLaunchApp}
/>
)
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index 8260bbcf6..42a73e8ad 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -13157,6 +13157,12 @@ pre {
pointer-events: none;
}
+/* Recovery action (Reopen / Retry) at the trailing end of an app status banner. */
+.sandbox-ui-status-action {
+ margin-left: auto;
+ flex-shrink: 0;
+}
+
.sandbox-ui-loading {
position: relative;
z-index: 1;