Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(desktop): persist app tab route across deactivation (phase 1)
Diego Zacarias75913381223c
diff --git a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts b/desktop-app/src/__tests__/appService.sandboxUiApps.test.tsindex 5b2a98dc9..588c7ec46 100644--- a/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts+++ b/desktop-app/src/__tests__/appService.sandboxUiApps.test.ts@@ -586,3 +586,58 @@ describe('AppService profile UI link authority', () => {expect(service.memberRegistrationServiceClient.getInvitationProfile).not.toHaveBeenCalled()})})++// Round-trip of the renderer's route-persistence read (mini-spec 05 §1/§2). The+// driver output shapes fed to the mock are the ones the REAL producer emits:+// `{ recipeNs, recipeName, path }` where `path` is what `resolveSandboxUiSharePath`+// returns (see sandboxUiDriver.test.ts — a non-default route yields '/tickets/42',+// a default route yields undefined, an out-of-prefix URL throws).+describe('AppService.getSandboxUiLocation', () => {+ it('reshapes a non-default route into { appRef, routePath }', async () => {+ const service = makeService() as unknown as {+ getSandboxUiLocation: () => Promise<{ appRef: string; routePath?: string } | null>+ }+ mockGetActiveSandboxUiLocation.mockReturnValue({+ recipeNs: 'ns',+ recipeName: 'app',+ path: '/tickets/42',+ })++ await expect(service.getSandboxUiLocation()).resolves.toEqual({+ appRef: 'ns/app',+ routePath: '/tickets/42',+ })+ })++ it('omits routePath when the active app is on its default route', async () => {+ const service = makeService() as unknown as {+ getSandboxUiLocation: () => Promise<{ appRef: string; routePath?: string } | null>+ }+ // Default route → the driver omits `path`.+ mockGetActiveSandboxUiLocation.mockReturnValue({ recipeNs: 'ns', recipeName: 'app' })++ await expect(service.getSandboxUiLocation()).resolves.toEqual({ appRef: 'ns/app' })+ })++ it('returns null when no embed is mounted or its webContents is destroyed', async () => {+ const service = makeService() as unknown as {+ getSandboxUiLocation: () => Promise<{ appRef: string; routePath?: string } | null>+ }+ mockGetActiveSandboxUiLocation.mockReturnValue(null)++ await expect(service.getSandboxUiLocation()).resolves.toBeNull()+ })++ it('propagates the out-of-prefix throw so the renderer falls back to default', async () => {+ const service = makeService() as unknown as {+ getSandboxUiLocation: () => Promise<{ appRef: string; routePath?: string } | null>+ }+ mockGetActiveSandboxUiLocation.mockImplementation(() => {+ throw new Error('Cannot read the current app route')+ })++ await expect(service.getSandboxUiLocation()).rejects.toThrow(+ 'Cannot read the current app route'+ )+ })+})diff --git a/desktop-app/src/__tests__/sandboxUiDriver.test.ts b/desktop-app/src/__tests__/sandboxUiDriver.test.tsindex 75953ffc6..e9955c9f3 100644--- a/desktop-app/src/__tests__/sandboxUiDriver.test.ts+++ b/desktop-app/src/__tests__/sandboxUiDriver.test.ts@@ -197,6 +197,21 @@ describe('sandbox UI route normalization', () => {).toThrow('Cannot read the current app route')})+ it('returns the in-prefix pathname for a non-default route (mini-spec 05 §2)', () => {+ // The real producer of the route the renderer persists on deactivation:+ // a nested view URL yields its pathname (leading-slash share form). This is+ // the value `appService.getSandboxUiLocation` reshapes into `routePath`.+ expect(+ resolveSandboxUiSharePath({+ currentUrl: 'https://rpc.example/api/v1/sandbox-ui/ns/app/view/tickets/42',+ rpcProxyOrigin: 'https://rpc.example',+ recipeNs: 'ns',+ recipeName: 'app',+ defaultPath: '/tasks',+ })+ ).toBe('/tickets/42')+ })+it('falls back to the default route when the app view has not committed a URL yet', () => {expect(resolveSandboxUiSharePath({diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 86865d45a..25d25fe82 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -4926,6 +4926,23 @@ export class AppService {})}+ // Read the active embed's current in-app route for the renderer's tab store+ // (mini-spec 05 §1). Mirrors `createSandboxUiDeepLink`'s read: it wraps+ // `driver.getActiveSandboxUiLocation()` and reshapes to the renderer contract.+ // Returns null when no embed is mounted or its webContents is destroyed.+ // An out-of-prefix current URL makes `getActiveSandboxUiLocation` THROW+ // ('Cannot read the current app route'); that propagates so the renderer can+ // fall back to the default route instead of persisting a stale one.+ async getSandboxUiLocation(): Promise<{ appRef: string; routePath?: string } | null> {+ const driver = await import('./sandboxUiDriver.js')+ const location = driver.getActiveSandboxUiLocation()+ if (!location) return null+ return {+ appRef: `${location.recipeNs}/${location.recipeName}`,+ ...(location.path ? { routePath: location.path } : {}),+ }+ }+async createSandboxUiDeepLink(teamId?: string): Promise<{ url: string }> {const driver = await import('./sandboxUiDriver.js')const { buildSandboxUiWebLink } = await import('./sandboxUiDeepLinks.js')diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex cf07a5768..c066cc0ea 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -1758,6 +1758,15 @@ export function registerIpcHandlers(service: AppService): void {await service.reloadSandboxUi()})+ // Read the active embed's current in-app route so the renderer can persist it+ // on the app tab before deactivation (mini-spec 05 §1). Returns null when no+ // embed is mounted; rejects when the current URL is outside the recipe prefix+ // (the renderer treats a rejection as "fall back to the default route").+ ipcMain.handle('sandboxUi:getLocation', async event => {+ assertTrustedSender(event)+ return service.getSandboxUiLocation()+ })+ipcMain.handle('sandboxUi:copyDeepLink', async (event, payload: { teamId?: unknown }) => {assertTrustedSender(event)const teamId = sanitizeString(payload?.teamId)diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex fffd6f1b1..59b2d2db7 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -609,6 +609,7 @@ const clerum = Object.freeze({}) => ipcRenderer.invoke('sandboxUi:open', args),close: () => ipcRenderer.invoke('sandboxUi:close'),reload: () => ipcRenderer.invoke('sandboxUi:reload'),+ getLocation: () => ipcRenderer.invoke('sandboxUi:getLocation'),copyDeepLink: (teamId?: string) => ipcRenderer.invoke('sandboxUi:copyDeepLink', { teamId }),listPendingDeepLinks: () => ipcRenderer.invoke('sandboxUi:listPendingDeepLinks'),clearPendingDeepLinks: () => ipcRenderer.invoke('sandboxUi:clearPendingDeepLinks'),diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex af75ee4d0..8a3b6f05f 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -713,6 +713,7 @@ declare global {}) => Promise<void>close: () => Promise<void>reload: () => Promise<void>+ getLocation: () => Promise<{ appRef: string; routePath?: string } | null>copyDeepLink: (teamId?: string) => Promise<{ url: string }>listPendingDeepLinks: () => Promise<{ links: SandboxUiDeepLinkEnvelope[] }>clearPendingDeepLinks: () => Promise<void>diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsxindex 700ffb9a3..739340f51 100644--- a/desktop-app/ui/src/App.tsx+++ b/desktop-app/ui/src/App.tsx@@ -71,6 +71,7 @@ import {selectLastWorkspaceTab,selectWorkspaceTab,selectWorkspaceTabAt,+ setAppTabSavedRoutePath,} from '@lib/workspaceTabs'import type { WorkspaceTab } from '@lib/workspaceTabs.types'import { AgentsPage } from '@pages/AgentsPage'@@ -350,6 +351,13 @@ export function App() {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).+ const liveSandboxUiTabIdRef = React.useRef<string | null>(null)workspaceTabsRef.current = workspaceTabsconst leaveSandboxForChat = React.useCallback(() => {@@ -376,7 +384,20 @@ export function App() {}if (tab.kind === 'app') {const app = availableSandboxUiApps.find(candidate => candidate.appRef === tab.app?.appRef)- if (app) relaunchSandboxUiAppRef.current?.(app, tab.id)+ // 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}const agentRef = tab.chat?.agentRef ?? null@@ -892,6 +913,19 @@ export function App() {const handleSandboxUiOpening = React.useCallback((app: ActiveSandboxUiApp) => {setSandboxUiMounted(false)setActiveSandboxUiApp(app)+ // Arm the store's embed-liveness ref on EVERY open, however it was launched+ // (store launch, deep link, relaunch, or the in-page picker grid opening the+ // embed directly without changing the active tab). The deactivation effect+ // otherwise only arms it on an active-tab CHANGE, so an embed re-mounted+ // WITHIN the still-active app tab — 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(() => {@@ -899,6 +933,12 @@ export function App() {}, [])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 = nullsetActiveSandboxUiApp(null)setSandboxUiMounted(false)setSandboxUiConversationOrigin(null)@@ -907,6 +947,7 @@ export function App() {}, [])const handleSandboxUiRemoved = React.useCallback(() => {+ liveSandboxUiTabIdRef.current = nullsetActiveSandboxUiApp(null)setSandboxUiMounted(false)setSandboxUiConversationOrigin(null)@@ -985,6 +1026,64 @@ export function App() {launchSandboxUiApp(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 outgoingTabId = liveSandboxUiTabIdRef.current+ if (outgoingTabId === activeSandboxUiTabId) return+ liveSandboxUiTabIdRef.current = activeSandboxUiTabId+ if (outgoingTabId === null) return+ const replacedByAnotherApp = activeSandboxUiTabId !== null+ 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 (sidebar auto-collapse, 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".+ void (async () => {+ let routePath: string | undefined+ try {+ const location = await window.clerum.sandboxUi.getLocation()+ routePath = location?.routePath+ } catch {+ routePath = undefined+ }+ // No-op when the outgoing tab was closed (§3: closing a tab does not save).+ setWorkspaceTabs(state => setAppTabSavedRoutePath(state, outgoingTabId, routePath))+ if (replacedByAnotherApp) return+ try {+ await window.clerum.sandboxUi.close()+ } catch {+ // Idempotent: an unsolicited close may have torn it down already.+ }+ })()+ }, [activeSandboxUiTabId, setWorkspaceTabs])+const handleSidebarNavSelect = React.useCallback((item: NavItem) => {setSandboxUiConversationOrigin(@@ -1115,9 +1214,26 @@ export function App() {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+ if (outgoingTabId !== null) {+ let routePath: string | undefined+ try {+ const location = await window.clerum.sandboxUi.getLocation()+ routePath = location?.routePath+ } catch {+ routePath = undefined+ }+ setWorkspaceTabs(state => setAppTabSavedRoutePath(state, outgoingTabId, routePath))+ }await window.clerum.sandboxUi.close()handleSandboxUiClosed()- }, [activeSandboxUiApp, handleSandboxUiClosed])+ }, [activeSandboxUiApp, handleSandboxUiClosed, setWorkspaceTabs])React.useEffect(() => {const enqueue = (link: SandboxUiDeepLinkEnvelope) => {diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsxindex 28c509e6e..94b20358c 100644--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx@@ -68,11 +68,14 @@ const commandPaletteHarness = vi.hoisted(() => ({},}))+type SidebarLaunchApp = { appRef: string; label: string; defaultPath: string; routePath?: string }const sidebarHarness = vi.hoisted(() => ({props: null as null | {toggleRequestId?: numbercollapsed?: booleanonCollapsedChange?: (next: boolean) => void+ availableSandboxUiApps?: SidebarLaunchApp[]+ onOpenSandboxUiApp?: (app: SidebarLaunchApp) => void},}))@@ -80,6 +83,12 @@ const sandboxUiPageHarness = vi.hoisted(() => ({props: null as null | {headerShellOverlayOpen?: booleandeepLinkShellOverlayOpen?: boolean+ shortcutApp?: {+ appRef: string+ label?: string+ defaultPath?: string+ routePath?: string+ } | nullshortcutOpenRequestId?: numberlocalSearchRequestId?: numberactionRequest?: {@@ -356,6 +365,10 @@ describe('App deep-link orchestration', () => {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)beforeEach(() => {vi.clearAllMocks()@@ -371,6 +384,7 @@ describe('App deep-link orchestration', () => {listApps.mockResolvedValue({ apps: [] })listPendingDeepLinks.mockResolvedValue({ links: [] })closeSandboxUi.mockResolvedValue(undefined)+ getSandboxUiLocation.mockResolvedValue(null)emitDeepLink = nullemitCommand = nullcurrentController = makeController()@@ -396,6 +410,7 @@ describe('App deep-link orchestration', () => {clearPendingDeepLinks,acknowledgeDeepLink,close: closeSandboxUi,+ getLocation: getSandboxUiLocation,focusActive: vi.fn().mockResolvedValue(true),onDeepLink: vi.fn((callback: (link: SandboxUiDeepLinkEnvelope) => void) => {emitDeepLink = callback@@ -1753,4 +1768,195 @@ describe('App deep-link orchestration', () => {await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(2))expect(acknowledgeDeepLink).not.toHaveBeenCalledWith(1)})++ // ── mini-spec 05: Phase-1 app persistence by URL restoration ────────────────++ const READY_APP = {+ appRef: 'ns/app',+ title: 'Linked App',+ 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.+ async function launchAppFromSidebar(): Promise<void> {+ await waitFor(() =>+ expect(sidebarHarness.props?.availableSandboxUiApps?.some(a => a.appRef === 'ns/app')).toBe(+ true+ )+ )+ const app = sidebarHarness.props?.availableSandboxUiApps?.find(a => a.appRef === 'ns/app')+ if (!app) throw new Error('ns/app was not available to the sidebar')+ await act(async () => {+ sidebarHarness.props?.onOpenSandboxUiApp?.(app)+ await Promise.resolve()+ })+ await waitFor(() => expect(sandboxUiPageHarness.props?.shortcutApp?.appRef).toBe('ns/app'))+ }++ 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()+ })+ }++ it('restores the saved route when an app tab is reactivated (mini-spec 05 §3, T3)', 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' })++ // Deactivate → the store reads the route and persists it on the app tab.+ await selectTab(0)+ await waitFor(() => expect(appTabs()[0]?.app?.savedRoutePath).toBe('/tickets/42'))++ // 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')+ )+ })++ it('keeps two tabs of the same app on their own routes when alternating (§5)', 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+ 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' })+ 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')+ )++ // Back to B restores B's own route.+ 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)+ })++ it('does not re-close after an UNsolicited close reconciles the tab as not mounted (§3)', 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()++ // 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()+ })++ 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 () => {+ const ensureTeamContext = vi.fn(async (): Promise<boolean> => true)+ currentController = makeController({+ initialExperienceLoading: false,+ handleEnsureTeamContext: ensureTeamContext,+ })+ listApps.mockResolvedValue({ apps: [READY_APP] })+ 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' })++ await waitFor(() => expect(emitDeepLink).not.toBeNull())+ act(() => {+ emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-b' })+ })+ await confirmPendingAppLink()++ await waitFor(() =>+ expect(+ currentController.workspaceTabs.tabs.find(tab => tab.id === outgoingId)?.app?.savedRoutePath+ ).toBe('/handoff/route')+ )+ expect(getSandboxUiLocation).toHaveBeenCalled()+ expect(closeSandboxUi).toHaveBeenCalled()+ })})diff --git a/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts b/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.tsindex 41d4d5d88..998ed030c 100644--- a/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts+++ b/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts@@ -17,6 +17,7 @@ import {selectLastWorkspaceTab,selectWorkspaceTab,selectWorkspaceTabAt,+ setAppTabSavedRoutePath,} from '../workspaceTabs'import type { ActiveChat, SettingsSection, WorkspaceTabsState } from '../workspaceTabs.types'@@ -106,6 +107,65 @@ describe('workspaceTabs — identity rules R6–R9', () => {})})+describe('workspaceTabs — setAppTabSavedRoutePath (mini-spec 05 §3)', () => {+ it('persists a route on the matching app tab and leaves siblings untouched', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openAppTab(state, { id: 'app-1', appRef: 'eventasks' })+ state = openAppTab(state, { id: 'app-2', appRef: 'eventasks' })++ state = setAppTabSavedRoutePath(state, 'app-1', '/tickets/42')++ expect(state.tabs.find(t => t.id === 'app-1')?.app?.savedRoutePath).toBe('/tickets/42')+ expect(state.tabs.find(t => t.id === 'app-2')?.app?.savedRoutePath).toBeUndefined()+ expect(state.activeTabId).toBe('app-2') // selection is not disturbed+ })++ it('clears the saved route (drops the key) when routePath is undefined', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openAppTab(state, { id: 'app-1', appRef: 'eventasks', savedRoutePath: '/tickets/42' })++ state = setAppTabSavedRoutePath(state, 'app-1', undefined)++ const app = state.tabs.find(t => t.id === 'app-1')?.app+ expect(app?.savedRoutePath).toBeUndefined()+ expect(Object.prototype.hasOwnProperty.call(app, 'savedRoutePath')).toBe(false)+ })++ it('is a no-op (same reference) when the route is unchanged', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openAppTab(state, { id: 'app-1', appRef: 'eventasks', savedRoutePath: '/tickets/42' })++ expect(setAppTabSavedRoutePath(state, 'app-1', '/tickets/42')).toBe(state)+ // Clearing an already-absent route is likewise a no-op.+ state = openAppTab(state, { id: 'app-2', appRef: 'eventasks' })+ expect(setAppTabSavedRoutePath(state, 'app-2', undefined)).toBe(state)+ })++ it('is a no-op when the tab is missing (e.g. a persist racing a close) or not an app', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openAppTab(state, { id: 'app-1', appRef: 'eventasks' })+ state = openChatTab(state, { id: 'chat-1', agentRef: 'a', chatId: 'c1' })++ // Closed / unknown tab id → the route write silently no-ops (§3: closing a+ // tab does not save).+ expect(setAppTabSavedRoutePath(state, 'gone', '/tickets/42')).toBe(state)+ // A chat tab is not an app tab → no route is written.+ expect(setAppTabSavedRoutePath(state, 'chat-1', '/tickets/42')).toBe(state)+ })++ it('keeps each of two tabs of the same app on its own route (R9, §5)', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openAppTab(state, { id: 'app-a', appRef: 'eventasks' })+ state = openAppTab(state, { id: 'app-b', appRef: 'eventasks' })++ state = setAppTabSavedRoutePath(state, 'app-a', '/tickets/A')+ state = setAppTabSavedRoutePath(state, 'app-b', '/tickets/B')++ expect(state.tabs.find(t => t.id === 'app-a')?.app?.savedRoutePath).toBe('/tickets/A')+ expect(state.tabs.find(t => t.id === 'app-b')?.app?.savedRoutePath).toBe('/tickets/B')+ })+})+describe('workspaceTabs — new chat (blank) with kind guard', () => {it('reuses the active blank chat tab (aligns the agent)', () => {let state = createWorkspaceTabsState('boot', null)diff --git a/desktop-app/ui/src/lib/workspaceTabs.ts b/desktop-app/ui/src/lib/workspaceTabs.tsindex 5a20af12e..19b800383 100644--- a/desktop-app/ui/src/lib/workspaceTabs.ts+++ b/desktop-app/ui/src/lib/workspaceTabs.ts@@ -1,5 +1,6 @@import type {ActiveChat,+ AppTabPayload,OpenAppTabInput,OpenChatTabInput,OpenFilesTabInput,@@ -160,6 +161,34 @@ export function openAppTab(state: WorkspaceTabsState, input: OpenAppTabInput): Wreturn { tabs: [...state.tabs, tab], activeTabId: input.id }}+/**+ * Persist the current in-app route on an app tab (mini-spec 05 §3). The store+ * governs the embed lifecycle: on deactivation the route is read from the live+ * embed and written here so reactivation can re-mount at it. `routePath ===+ * undefined` CLEARS any saved route (the tab reopens at its default path) — the+ * key is dropped rather than stored as `undefined`. A no-op (same reference)+ * when the tab is missing, is not an app tab, or already holds this route, so a+ * `setState` bails out. Closing a tab removes it, so a persist racing a close+ * simply no-ops.+ */+export function setAppTabSavedRoutePath(+ state: WorkspaceTabsState,+ tabId: string,+ routePath: string | undefined+): WorkspaceTabsState {+ const target = state.tabs.find(tab => tab.id === tabId && tab.kind === 'app')+ if (!target?.app) return state+ if (target.app.savedRoutePath === routePath) return state+ const nextApp: AppTabPayload = {+ appRef: target.app.appRef,+ ...(routePath !== undefined ? { savedRoutePath: routePath } : {}),+ }+ return {+ ...state,+ tabs: state.tabs.map(tab => (tab.id === tabId ? { ...tab, app: nextApp } : tab)),+ }+}+/** Files: single instance — focus the existing tab if present (R8). */export function openFilesTab(state: WorkspaceTabsState,diff --git a/desktop-app/ui/src/pages/SandboxUiPage.tsx b/desktop-app/ui/src/pages/SandboxUiPage.tsxindex 8e4a80335..847606dae 100644--- a/desktop-app/ui/src/pages/SandboxUiPage.tsx+++ b/desktop-app/ui/src/pages/SandboxUiPage.tsx@@ -162,7 +162,6 @@ function useEmbedBounds(}const APP_PAGE_SIZE = 6-let pendingSandboxUiUnmountCleanup: number | null = nulllet nextSandboxFindClientRequestId = 0// Icon-only app action rendered into the native title bar's leading slot. The@@ -383,20 +382,14 @@ export function SandboxUiPage({stopLocalSearch()}, [launch.kind, localSearchOpen, stopLocalSearch])- // Tear down the embed when this page unmounts (user navigates away).- useLayoutEffect(() => {- if (pendingSandboxUiUnmountCleanup !== null) {- window.clearTimeout(pendingSandboxUiUnmountCleanup)- pendingSandboxUiUnmountCleanup = null- }- return () => {- pendingSandboxUiUnmountCleanup = window.setTimeout(() => {- pendingSandboxUiUnmountCleanup = null- void window.clerum.sandboxUi.close()- onEmbeddedAppBack?.()- }, 0)- }- }, [onEmbeddedAppBack])+ // 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: SandboxUiLaunchApp): Promise<SandboxUiShortcutOpenResult> => {