Skip to content

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

TypeScript

refactor(desktop-app): route every tab activation gesture through one seam

Diego Zacariasccc4665b0928
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 26210533d..0e75ae8d8 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -1,4 +1,5 @@
import React from 'react'
+import { flushSync } from 'react-dom'
import {
AgentActivityProvider,
AgentChatProviders,
@@ -88,7 +89,7 @@ import {
setAppTabTitle,
setFilesTabPath,
} from '@lib/workspaceTabs'
-import type { WorkspaceTab } from '@lib/workspaceTabs.types'
+import type { WorkspaceTab, WorkspaceTabsState } from '@lib/workspaceTabs.types'
import { AgentsPage } from '@pages/AgentsPage'
import { AuthPage } from '@pages/AuthPage'
import { ChatPage } from '@pages/ChatPage'
@@ -396,8 +397,8 @@ export function App() {
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 `launchSandboxUiApp`) can call it without
- // a TDZ on the launch callback.
+ // `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)
@@ -422,10 +423,10 @@ export function App() {
// 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 `launchSandboxUiApp` targeted. 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.
+ // 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
@@ -437,6 +438,30 @@ export function App() {
setSidebarSettingsMenuOpen(false)
}, [])
+ // 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.
+ const activateAndLaunch = React.useCallback(
+ (update: (state: WorkspaceTabsState) => WorkspaceTabsState, launch?: () => void) => {
+ flushSync(() => {
+ vm.clearAppsPicker()
+ setWorkspaceTabs(update)
+ launch?.()
+ })
+ },
+ [setWorkspaceTabs, vm.clearAppsPicker]
+ )
+
// 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
@@ -511,11 +536,12 @@ export function App() {
(id: string) => {
const tab = workspaceTabsRef.current.tabs.find(candidate => candidate.id === id)
if (!tab) return
- vm.clearAppsPicker()
- setWorkspaceTabs(state => selectWorkspaceTab(state, id))
- revealWorkspaceTab(tab, false)
+ activateAndLaunch(
+ state => selectWorkspaceTab(state, id),
+ () => revealWorkspaceTab(tab, false)
+ )
},
- [revealWorkspaceTab, setWorkspaceTabs, vm.clearAppsPicker]
+ [activateAndLaunch, revealWorkspaceTab]
)
// Drawer switcher selection: reveal the chat IN the drawer (keepNavItem), never
@@ -534,15 +560,16 @@ export function App() {
(id: string) => {
const current = workspaceTabsRef.current
const wasActive = current.activeTabId === id
- const next = closeWorkspaceTab(current, id)
- if (next === current) return
- vm.clearAppsPicker()
- setWorkspaceTabs(next)
+ 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.
- if (wasActive) revealWorkspaceTab(activeWorkspaceTab(next), false)
+ activateAndLaunch(
+ state => closeWorkspaceTab(state, id),
+ wasActive ? () => revealWorkspaceTab(activeWorkspaceTab(projected), false) : undefined
+ )
},
- [revealWorkspaceTab, setWorkspaceTabs, vm.clearAppsPicker]
+ [activateAndLaunch, revealWorkspaceTab]
)
// Session-only strip reorder (drag & drop / keyboard). It never changes the
@@ -1406,30 +1433,20 @@ export function App() {
if (chatDrawerVisible) setChatDrawerReady(true)
}, [appNotificationDrawerOpen, chatDrawerVisible])
- const launchSandboxUiApp = React.useCallback(
+ // 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,
- existingTabId?: string
+ targetTabId: string
) => {
const requestId = sandboxUiShortcutOpenRequestIdRef.current + 1
sandboxUiShortcutOpenRequestIdRef.current = requestId
setSandboxUiMounted(false)
setSandboxUiConversationOrigin(conversationOrigin)
setActiveSandboxUiApp(app)
- // Store→embed: activate the app tab (a new one, or the backgrounded one on
- // relaunch). Its `kind:'app'` derives `navItem` to the Apps route this
- // commit and clears the instance-less picker residual.
- vm.clearAppsPicker()
- // Compute the id only on the open-new branch so the sequence counter
- // advances exactly as before: relaunch of an existing tab must not burn one.
- const newAppTabId = existingTabId ? null : nextChatTabId()
- launchTargetTabIdRef.current = existingTabId ?? newAppTabId
- setWorkspaceTabs(state =>
- existingTabId
- ? selectWorkspaceTab(state, existingTabId)
- : openAppTab(state, { id: newAppTabId!, appRef: app.appRef, title: app.label })
- )
+ launchTargetTabIdRef.current = targetTabId
setSandboxUiShortcutOpenRequestId(requestId)
if (conversationOrigin) {
// Opened from a chat: bring that conversation straight into the drawer
@@ -1447,10 +1464,31 @@ export function App() {
}
return requestId
},
- [nextChatTabId, setWorkspaceTabs, vm.clearAppsPicker, vm.handleSelectChatAgent]
+ [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) => {
+ const tabId = nextChatTabId()
+ let requestId = 0
+ activateAndLaunch(
+ state => openAppTab(state, { id: tabId, appRef: app.appRef, title: app.label }),
+ () => {
+ requestId = beginSandboxUiLaunch(app, conversationOrigin, tabId)
+ }
+ )
+ return requestId
+ },
+ [activateAndLaunch, beginSandboxUiLaunch, nextChatTabId]
)
+ // 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) => {
- launchSandboxUiApp(app, null, tabId)
+ setWorkspaceTabs(state => selectWorkspaceTab(state, tabId))
+ beginSandboxUiLaunch(app, null, tabId)
}
// Store-governed embed lifecycle (mini-spec 05 §3, replaces the old
@@ -1736,11 +1774,11 @@ export function App() {
// 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 `launchSandboxUiApp`, 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.
+ // 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
@@ -2137,11 +2175,10 @@ export function App() {
// Universal tab commands: activate a tab then reveal its content (chat load
// / app relaunch / DOM route). `tabs.*` cycle over ALL tabs; `chat.*` are
// chat-specific.
- const selectAndReveal = (next: typeof state) => {
- if (next === state) return
- vm.clearAppsPicker()
- setWorkspaceTabs(next)
- revealWorkspaceTab(activeWorkspaceTab(next), false)
+ const selectAndReveal = (update: (current: WorkspaceTabsState) => WorkspaceTabsState) => {
+ const projected = update(state)
+ if (projected === state) return
+ activateAndLaunch(update, () => revealWorkspaceTab(activeWorkspaceTab(projected), false))
}
if (commandId === 'commands.open') {
closeChatLocalSearch(false)
@@ -2237,16 +2274,18 @@ export function App() {
return
}
if (command.eligibility === 'tab-index' && command.tabIndex !== undefined) {
- selectAndReveal(selectWorkspaceTabAt(state, command.tabIndex))
+ const tabIndex = command.tabIndex
+ selectAndReveal(current => selectWorkspaceTabAt(current, tabIndex))
return
}
if (commandId === 'tabs.selectLast') {
- selectAndReveal(selectLastWorkspaceTab(state))
+ selectAndReveal(selectLastWorkspaceTab)
return
}
if (commandId === 'tabs.next' || commandId === 'tabs.previous') {
if (state.tabs.length < 2) return
- selectAndReveal(cycleWorkspaceTab(state, commandId === 'tabs.next' ? 'next' : 'previous'))
+ const direction = commandId === 'tabs.next' ? 'next' : 'previous'
+ selectAndReveal(current => cycleWorkspaceTab(current, direction))
return
}
if (commandId === 'composer.focus') {
@@ -2263,7 +2302,10 @@ export function App() {
})
}
} else {
- revealWorkspaceTab(activeWorkspaceTab(state), false)
+ activateAndLaunch(
+ current => current,
+ () => revealWorkspaceTab(activeWorkspaceTab(state), false)
+ )
}
setComposerFocusRequestId(value => value + 1)
return
@@ -2284,6 +2326,7 @@ export function App() {
}
},
[
+ activateAndLaunch,
activeSandboxUiApp,
closeChatLocalSearch,
closeCommandPalette,
@@ -2295,9 +2338,7 @@ export function App() {
openChatDrawer,
revealWorkspaceTab,
sandboxUiMounted,
- setWorkspaceTabs,
vm.activeChatId,
- vm.clearAppsPicker,
vm.handleNavSelect,
vm.handleLogout,
vm.handleSelectChatAgent,
diff --git a/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx b/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx
new file mode 100644
index 000000000..d817bf692
--- /dev/null
+++ b/desktop-app/ui/src/__tests__/App.activationSeam.test.tsx
@@ -0,0 +1,598 @@
+// @vitest-environment jsdom
+import { useReducer } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { readFileSync, readdirSync, statSync } from 'node:fs'
+import { join, relative } from 'node:path'
+import { DESKTOP_ROUTES } from '@constants/navigation'
+import { useAppController } from '@hooks/useAppController'
+import type { GfsPreviewResource } from '@lib/gfsPreview'
+import { toActiveSandboxUiApps } from '@lib/sandboxUiAppSelection'
+import type { SandboxUiAppListing } from '@lib/sandboxUiAppSelection.types'
+import {
+ activeWorkspaceTab,
+ createWorkspaceTabsState,
+ openChatTab,
+ openFilesTab,
+ openPreviewTab,
+} 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'
+
+// 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
+// `flushSync`. A store write that activates an app tab from anywhere else (an
+// effect, a late async continuation, a new handler) lands in a later commit than
+// the launch it belongs to. These tests record, for every store write, whether
+// it ran inside a `flushSync` callback, and fail on any app-tab activation that
+// did not. The callback body — not the commit that follows it — is what counts:
+// effects flushed by that sync commit are NOT inside the seam.
+// The probe only catches activations in the scenarios driven here; the static
+// guarantee is the `flushSync` call-site check at the end of this file.
+
+const seamProbe = vi.hoisted(() => ({ depth: 0 }))
+
+vi.mock('react-dom', async importOriginal => {
+ const actual = await importOriginal<typeof import('react-dom')>()
+ return {
+ ...actual,
+ flushSync: <R,>(fn: () => R): R =>
+ actual.flushSync(() => {
+ seamProbe.depth += 1
+ try {
+ return fn()
+ } finally {
+ seamProbe.depth -= 1
+ }
+ }),
+ }
+})
+
+let forceControllerRender: () => void = () => {}
+
+function useReactiveController(controller: AppController): AppController {
+ const [, force] = useReducer((count: number) => count + 1, 0)
+ forceControllerRender = force
+ const activeTab = activeWorkspaceTab(controller.workspaceTabs)
+ ;(controller as { activeWorkspaceTab: unknown }).activeWorkspaceTab = activeTab
+ ;(controller as { navItem: unknown }).navItem = controller.appsPickerActive
+ ? DESKTOP_ROUTES.apps
+ : mapKindToRoute(activeTab)
+ return controller
+}
+
+type WorkspaceState = ReturnType<typeof useAppController>['workspaceTabs']
+type AppController = ReturnType<typeof useAppController>
+
+const sidebarHarness = vi.hoisted(() => ({
+ props: null as null | {
+ onSelect?: (item: string) => void
+ onOpenSandboxUiApp?: (app: {
+ appRef: string
+ label: string
+ defaultPath: string
+ icon?: string
+ }) => 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: () => ({}) }))
+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: (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', () => ({
+ SidebarNav: (props: NonNullable<typeof sidebarHarness.props>) => {
+ sidebarHarness.props = props
+ return null
+ },
+}))
+vi.mock('@pages/AgentsPage', () => ({ AgentsPage: () => null }))
+vi.mock('@pages/AuthPage', () => ({ AuthPage: () => null }))
+vi.mock('@pages/ChatPage', () => ({ ChatPage: () => null }))
+vi.mock('@pages/ContextDetailsPage', () => ({ ContextDetailsPage: () => null }))
+vi.mock('@pages/ContextsPage', () => ({ ContextsPage: () => null }))
+vi.mock('@pages/FilesPage', () => ({ FilesPage: () => null }))
+vi.mock('@pages/FilePreviewPage', () => ({ FilePreviewPage: () => null }))
+vi.mock('@pages/McpServersPage', () => ({ McpServersPage: () => null }))
+vi.mock('@pages/SettingsPage', () => ({ SettingsPage: () => null }))
+vi.mock('@pages/TeamDetailsPage', () => ({ TeamDetailsPage: () => null }))
+vi.mock('@pages/TeamsPage', () => ({ TeamsPage: () => null }))
+vi.mock('@pages/UnavailablePage', () => ({ UnavailablePage: () => null }))
+vi.mock('@pages/WorkflowsPage', () => ({ WorkflowsPage: () => null }))
+
+type StoreWrite = { activatedAppTabId: string | null; insideSeam: boolean }
+
+// Store-faithful controller: `navItem` derives from the active tab and every
+// navigation drives the real store producers. Each write is recorded with
+// whether it was issued from inside a `flushSync` callback.
+function makeController(writes: StoreWrite[]): AppController {
+ const noop = vi.fn()
+ let controller: AppController
+ let tabSequence = 2
+ const nextWorkspaceTabId = vi.fn(() => `ws-tab-${tabSequence++}`)
+ const setWorkspaceTabs = vi.fn((updater: unknown) => {
+ const previous = controller.workspaceTabs
+ const next =
+ typeof updater === 'function'
+ ? (updater as (state: WorkspaceState) => WorkspaceState)(previous)
+ : (updater as WorkspaceState)
+ const activated =
+ next.activeTabId !== previous.activeTabId ? activeWorkspaceTab(next) : undefined
+ writes.push({
+ activatedAppTabId: activated?.kind === 'app' ? activated.id : null,
+ insideSeam: seamProbe.depth > 0,
+ })
+ if (next === previous) return
+ controller.workspaceTabs = next
+ forceControllerRender()
+ })
+ const clearAppsPicker = vi.fn(() => {
+ if (!controller.appsPickerActive) return
+ controller.appsPickerActive = false
+ forceControllerRender()
+ })
+ const openPreviewSection = vi.fn((preview: GfsPreviewResource) => {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ openPreviewTab(state, {
+ id: nextWorkspaceTabId(),
+ title: preview.name,
+ gfsUri: preview.gfsUri,
+ fileKind: preview.kind,
+ byteLength: preview.bytes,
+ ...(preview.version !== undefined ? { resourceVersion: preview.version } : {}),
+ ...('mimeType' in preview ? { mimeType: preview.mimeType } : {}),
+ })
+ )
+ })
+ 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
+ if (activeWorkspaceTab(controller.workspaceTabs)?.kind === 'app') return
+ controller.appsPickerActive = true
+ forceControllerRender()
+ })
+ controller = {
+ booting: false,
+ initialExperienceLoading: false,
+ busy: false,
+ statusText: '',
+ statusTone: 'info',
+ isAuthenticated: true,
+ authenticatedPrincipalIdentity: 'user-a:[email protected]',
+ me: { id: 'user-a', email: '[email protected]', name: 'User A', teamId: 'team-a' },
+ currentTeamId: 'team-a',
+ navItem: DESKTOP_ROUTES.chat,
+ selectedAgent: null,
+ selectedAgentRoute: null,
+ selectedContext: null,
+ selectedTeam: null,
+ workspaceTabs: createWorkspaceTabsState('chat-tab-1'),
+ setWorkspaceTabs,
+ activeWorkspaceTab: undefined,
+ nextWorkspaceTabId,
+ appsPickerActive: false,
+ showAppsPicker,
+ clearAppsPicker,
+ activateWorkspaceChatTab: noop,
+ openFilesSection,
+ openPreviewSection,
+ lastActiveChatTabId: null,
+ activeChatId: null,
+ chatList: [],
+ latestChatSessions: [],
+ notifications: [],
+ toasts: [],
+ pendingApprovals: [],
+ composerImageAttachments: [],
+ composerReferenceAttachments: [],
+ groupedMessages: [],
+ activeMessages: [],
+ notificationActionById: {},
+ sessionStateByChatId: {},
+ sessionStateByChatKey: {},
+ activityByMessageId: {},
+ progressByMessageId: {},
+ agentLastActiveByAgent: {},
+ dependencyHealth: null,
+ hasDependencyOutage: false,
+ desktopEnvironmentSetupComplete: false,
+ pendingDesktopEnvironmentSetup: null,
+ desktopReleaseStatus: null,
+ showRuntimeConfigSelector: false,
+ runtimeConfigMissing: false,
+ authTransitioning: false,
+ handleEnsureTeamContext: vi.fn(async () => false),
+ getCurrentTeamId: vi.fn(() => 'team-a'),
+ isHostAccessBlocked: vi.fn(() => false),
+ handleSelectChatAgent: vi.fn(() => forceControllerRender()),
+ handleOpenNotification: vi.fn(async () => undefined),
+ handleNavSelect: vi.fn((item: string) => {
+ if (item === DESKTOP_ROUTES.apps) showAppsPicker()
+ }),
+ handleLogout: vi.fn(),
+ pushToast: vi.fn(),
+ setStatus: noop,
+ setBooting: noop,
+ } as unknown as AppController
+ return controller
+}
+
+const APP_LISTING: SandboxUiAppListing[] = [
+ {
+ appRef: 'sandbox-recipes/alpha',
+ title: 'Alpha',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ updatedAt: null,
+ },
+ {
+ appRef: 'sandbox-recipes/beta',
+ title: 'Beta',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ updatedAt: null,
+ },
+]
+const [ALPHA, BETA] = toActiveSandboxUiApps(APP_LISTING)
+
+const MEASURED_SLOT = {
+ x: 0,
+ y: 0,
+ top: 12,
+ left: 16,
+ right: 416,
+ bottom: 312,
+ width: 400,
+ height: 300,
+ toJSON: () => ({}),
+} as DOMRect
+
+function makeSandboxUiBridge() {
+ return {
+ 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>>
+type ShortcutListener = (commandId: string, source: string) => void
+
+// The latest subscriber of a bridge `on*` registration, i.e. the listener App
+// currently has wired.
+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 activates app tabs only through its activation seam', () => {
+ let controller: AppController
+ let writes: StoreWrite[]
+ let flushSyncErrors: string[]
+ let openGfsResourceCb: ((resource: OpenGfsPayload) => void) | null
+ let shortcutCommandCb: ShortcutListener | null
+ let sandboxUi: ReturnType<typeof makeSandboxUiBridge>
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ seamProbe.depth = 0
+ sidebarHarness.props = null
+ confirmDialogHarness.props = null
+ openGfsResourceCb = null
+ shortcutCommandCb = null
+ writes = []
+ 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(writes)
+ vi.mocked(useAppController).mockImplementation(() => useReactiveController(controller))
+ vi.stubGlobal('requestAnimationFrame', (cb: FrameRequestCallback) => {
+ cb(0)
+ return 1
+ })
+ vi.stubGlobal(
+ 'ResizeObserver',
+ class {
+ observe = vi.fn()
+ unobserve = vi.fn()
+ disconnect = vi.fn()
+ }
+ )
+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockReturnValue(MEASURED_SLOT)
+ sandboxUi = makeSandboxUiBridge()
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ shortcuts: {
+ onCommand: vi.fn((cb: ShortcutListener) => {
+ shortcutCommandCb = cb
+ return vi.fn()
+ }),
+ },
+ app: { rendererReady: vi.fn().mockResolvedValue(undefined) },
+ sandboxUi,
+ pluginSdk: {
+ onOpenGfsResource: vi.fn((cb: (resource: OpenGfsPayload) => void) => {
+ openGfsResourceCb = cb
+ return vi.fn()
+ }),
+ },
+ } as unknown as Window['clerum'],
+ })
+ })
+
+ afterEach(async () => {
+ cleanup()
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+ vi.restoreAllMocks()
+ vi.unstubAllGlobals()
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ // The invariant, checked at the end of every scenario. `minActivations` keeps
+ // a scenario from passing vacuously when it never activated an app tab.
+ function expectActivationsOnlyThroughSeam(minActivations: number) {
+ const appActivations = writes.filter(write => write.activatedAppTabId !== null)
+ expect(appActivations.filter(write => !write.insideSeam)).toEqual([])
+ expect(appActivations.length).toBeGreaterThanOrEqual(minActivations)
+ expect(flushSyncErrors).toEqual([])
+ }
+
+ async function renderApp() {
+ render(<App />)
+ await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
+ await act(async () => {
+ await Promise.resolve()
+ })
+ }
+
+ async function openFromSidebar(app: typeof ALPHA, openCount: number) {
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(app!))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(openCount))
+ await flushMacrotask()
+ }
+
+ async function shortcut(commandId: string) {
+ await act(async () => {
+ shortcutCommandCb?.(commandId, 'host')
+ await new Promise(resolve => window.setTimeout(resolve, 0))
+ })
+ }
+
+ function activeTab() {
+ return activeWorkspaceTab(controller.workspaceTabs)
+ }
+
+ it('opens apps from the sidebar and the picker grid through the seam', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ expect(activeTab()?.app?.appRef).toBe(ALPHA!.appRef)
+
+ await shortcut('app.backToApps')
+ fireEvent.click(await screen.findByRole('button', { name: 'Open Beta' }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ expect(activeTab()?.app?.appRef).toBe(BETA!.appRef)
+
+ expectActivationsOnlyThroughSeam(2)
+ })
+
+ it('activates app tabs from the strip (select and close-to-neighbor) through the seam', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+
+ fireEvent.click(screen.getByRole('button', { name: 'New chat', pressed: false }))
+ await flushMacrotask()
+ fireEvent.click(screen.getByRole('button', { name: 'Alpha', pressed: false }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ await flushMacrotask()
+
+ // Closing the active chat tab activates its right neighbor, the Alpha tab.
+ fireEvent.click(screen.getByRole('button', { name: 'New chat', pressed: false }))
+ await flushMacrotask()
+ fireEvent.click(screen.getByRole('button', { name: 'Close New chat' }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(3))
+ expect(activeTab()?.app?.appRef).toBe(ALPHA!.appRef)
+
+ // open #1 (sidebar) + strip select + close-to-neighbor.
+ expectActivationsOnlyThroughSeam(3)
+ })
+
+ it('activates app tabs from tab shortcuts through the seam', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ await openFromSidebar(BETA, 2)
+ // Tabs: [New chat, Alpha, Beta].
+
+ await shortcut('tabs.select1')
+ await shortcut('tabs.select2')
+ expect(activeTab()?.app?.appRef).toBe(ALPHA!.appRef)
+ await shortcut('tabs.next')
+ expect(activeTab()?.app?.appRef).toBe(BETA!.appRef)
+ await shortcut('tabs.previous')
+ expect(activeTab()?.app?.appRef).toBe(ALPHA!.appRef)
+ await shortcut('tabs.select1')
+ await shortcut('tabs.selectLast')
+ expect(activeTab()?.app?.appRef).toBe(BETA!.appRef)
+ await shortcut('tabs.select1')
+ await shortcut('chat.closeTab')
+ expect(activeTab()?.app?.appRef).toBe(ALPHA!.appRef)
+
+ // 2 sidebar opens + select2, next, previous, selectLast, closeTab.
+ expectActivationsOnlyThroughSeam(7)
+ })
+
+ it('activates the app tab of a confirmed deep link through the seam', async () => {
+ await renderApp()
+ 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 Promise.resolve()
+ })
+
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
+ expect(activeTab()?.app?.appRef).toBe(ALPHA!.appRef)
+ expectActivationsOnlyThroughSeam(1)
+ })
+
+ it('keeps every other store writer from activating an app tab', async () => {
+ controller.selectedAgent = 'agent-a'
+ controller.activeChatId = 'chat-1'
+ ;(controller as { chatList: unknown }).chatList = [{ id: 'chat-1', title: 'Planning' }]
+ controller.workspaceTabs = openChatTab(createWorkspaceTabsState('chat-tab-1'), {
+ id: 'ws-tab-90',
+ agentRef: 'agent-a',
+ chatId: 'chat-1',
+ title: 'Planning',
+ })
+ await renderApp()
+ // composer.focus on the chat route reveals the active chat through the seam.
+ await shortcut('composer.focus')
+
+ 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' }
+ )
+ )
+ // Leaving the app persists its route, and a plugin handoff opens a preview.
+ sandboxUi.getLocation.mockResolvedValue({ appRef: ALPHA!.appRef, routePath: '/inbox' })
+ const payload = await openGfsResourcePayload(
+ resolvedFile('md1', 'README.md', { gfsUri: 'gfs://main/md1' })
+ )
+ act(() => openGfsResourceCb?.(payload))
+ await waitFor(() =>
+ expect(
+ controller.workspaceTabs.tabs.find(tab => tab.app?.appRef === ALPHA!.appRef)?.app
+ ?.savedRoutePath
+ ).toBe('/inbox')
+ )
+ expect(activeTab()?.kind).toBe('preview')
+
+ // A new chat tab, then a principal change resets the store.
+ await shortcut('chat.newTab')
+ ;(controller as { authenticatedPrincipalIdentity: string }).authenticatedPrincipalIdentity =
+ act(() => forceControllerRender())
+ await flushMacrotask()
+ expect(controller.workspaceTabs.activeTabId).toBe('chat-tab-1')
+
+ // Only the sidebar open activated an app tab.
+ expectActivationsOnlyThroughSeam(1)
+ expect(writes.filter(write => write.activatedAppTabId !== null)).toHaveLength(1)
+ })
+
+ // A store write that lands between App's last render and a gesture (here a
+ // title from the live embed) must survive the gesture's own store write.
+ 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' })
+ gesture()
+ })
+ await flushMacrotask()
+ }
+
+ it('keeps a pending store update when a tab shortcut activates another tab', async () => {
+ await renderWithRetitledLiveAlpha(() => shortcutCommandCb?.('tabs.select1', 'host'))
+
+ expect(screen.getByRole('button', { name: 'New chat', pressed: true })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: false })).toBeTruthy()
+ expectActivationsOnlyThroughSeam(1)
+ })
+
+ it('keeps a pending store update when the strip closes another tab', async () => {
+ await renderWithRetitledLiveAlpha(() =>
+ fireEvent.click(screen.getByRole('button', { name: 'Close New chat' }))
+ )
+
+ expect(screen.queryByRole('button', { name: 'New chat' })).toBeNull()
+ expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: true })).toBeTruthy()
+ expectActivationsOnlyThroughSeam(1)
+ })
+})
+
+// `flushSync` is what makes the seam a seam: a second call site would be a
+// second, unaudited activation path, and one inside an effect would not flush.
+describe('flushSync call sites in the renderer', () => {
+ function sourceFiles(dir: string): string[] {
+ return readdirSync(dir).flatMap(name => {
+ const path = join(dir, name)
+ if (statSync(path).isDirectory()) {
+ return name === '__tests__' || name === 'node_modules' ? [] : sourceFiles(path)
+ }
+ return /\.tsx?$/.test(name) && !/\.test\.tsx?$/.test(name) ? [path] : []
+ })
+ }
+
+ it('calls flushSync only from the activation seam in App', () => {
+ const root = join(__dirname, '..')
+ const sites = sourceFiles(root).flatMap(path =>
+ readFileSync(path, 'utf8')
+ .split('\n')
+ .filter(line => /\bflushSync\(/.test(line))
+ .map(line => `${relative(root, path)}: ${line.trim()}`)
+ )
+ expect(sites).toEqual(['App.tsx: flushSync(() => {'])
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useNavigationController.activation.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/useNavigationController.activation.test.ts
new file mode 100644
index 000000000..12deb5f57
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useNavigationController.activation.test.ts
@@ -0,0 +1,207 @@
+// @vitest-environment jsdom
+import { describe, expect, it } from 'vitest'
+import { act, renderHook } from '@testing-library/react'
+import fc from 'fast-check'
+import { DESKTOP_ROUTES } from '../../../constants/navigation'
+import { resolveGfsPreview } from '../../../lib/gfsPreview'
+import {
+ activeWorkspaceTab,
+ closeWorkspaceTab,
+ createEmptyWorkspaceTabsState,
+ createWorkspaceTabsState,
+ openAppTab,
+ openChatTab,
+ openFilesTab,
+ openPreviewTab,
+ openSettingsTab,
+ selectWorkspaceTabAt,
+} from '../../../lib/workspaceTabs'
+import type { SettingsSection, WorkspaceTabsState } from '../../../lib/workspaceTabs.types'
+import { useNavigationController } from '../useNavigationController'
+
+// App activates app tabs only through its activation seam, which commits the
+// tab and its launch together. The navigation controller writes the same store
+// from sidebar navigation and chat selection, outside that seam, so none of its
+// writers may ever move the active tab onto an app tab — whatever the store
+// holds when they run.
+
+type Seed =
+ | { op: 'app'; appRef: string }
+ | { op: 'chat'; agentRef: string; chatId: string | null }
+ | { op: 'files'; path: string | null }
+ | { op: 'settings'; section: SettingsSection }
+ | { op: 'preview'; name: string }
+ | { op: 'select'; index: number }
+ | { op: 'close'; index: number }
+
+type NavOp =
+ | { op: 'nav'; route: (typeof DESKTOP_ROUTES)[keyof typeof DESKTOP_ROUTES] }
+ | { op: 'activateChat'; agentRef: string | null; chatId: string | null }
+ | { op: 'files'; path: string | null }
+ | { op: 'preview'; name: string }
+
+const agentRef = fc.constantFrom('agent-a', 'agent-b')
+const chatId = fc.option(fc.constantFrom('chat-1', 'chat-2'), { nil: null })
+const filesPath = fc.option(fc.constantFrom('gfs://main/a', 'gfs://main/b'), { nil: null })
+const previewName = fc.constantFrom('README.md', 'notes.md')
+
+const appSeed = fc.record({
+ op: fc.constant('app' as const),
+ appRef: fc.constantFrom('ns/alpha', 'ns/beta'),
+})
+const selectSeed = fc.record({ op: fc.constant('select' as const), index: fc.nat({ max: 8 }) })
+
+// Chat seeds are rare on purpose: a chat ever made active becomes the chat the
+// controller resumes, which hides any fallback that could pick another tab.
+const seedArb: fc.Arbitrary<Seed> = fc.oneof(
+ { weight: 3, arbitrary: appSeed },
+ { weight: 1, arbitrary: fc.record({ op: fc.constant('chat' as const), agentRef, chatId }) },
+ { weight: 2, arbitrary: fc.record({ op: fc.constant('files' as const), path: filesPath }) },
+ {
+ weight: 2,
+ arbitrary: fc.record({
+ op: fc.constant('settings' as const),
+ section: fc.constantFrom<SettingsSection>('connectors', 'agents', 'plugins', 'settings'),
+ }),
+ },
+ { weight: 2, arbitrary: fc.record({ op: fc.constant('preview' as const), name: previewName }) },
+ { weight: 2, arbitrary: selectSeed },
+ {
+ weight: 1,
+ arbitrary: fc.record({ op: fc.constant('close' as const), index: fc.nat({ max: 8 }) }),
+ }
+)
+
+// The dangerous shape: an app tab last in the strip but not active, reached by
+// re-selecting an earlier tab after it was opened.
+const seedsArb: fc.Arbitrary<Seed[]> = fc.oneof(
+ { weight: 1, arbitrary: fc.array(seedArb, { maxLength: 8 }) },
+ {
+ weight: 2,
+ arbitrary: fc
+ .tuple(fc.array(seedArb, { maxLength: 6 }), appSeed, selectSeed)
+ .map(([prefix, app, select]) => [...prefix, app, select]),
+ }
+)
+
+const navOpArb: fc.Arbitrary<NavOp> = fc.oneof(
+ { weight: 4, arbitrary: fc.constant({ op: 'nav' as const, route: DESKTOP_ROUTES.chat }) },
+ {
+ weight: 2,
+ arbitrary: fc.record({
+ op: fc.constant('nav' as const),
+ route: fc.constantFrom(...Object.values(DESKTOP_ROUTES)),
+ }),
+ },
+ {
+ weight: 1,
+ arbitrary: fc.record({
+ op: fc.constant('activateChat' as const),
+ agentRef: fc.option(agentRef, { nil: null }),
+ chatId,
+ }),
+ },
+ {
+ weight: 1,
+ arbitrary: fc.record({ op: fc.constant('files' as const), path: filesPath }),
+ },
+ {
+ weight: 1,
+ arbitrary: fc.record({ op: fc.constant('preview' as const), name: previewName }),
+ }
+)
+
+function preview(name: string) {
+ return resolveGfsPreview({ gfsUri: `gfs://main/${name}`, name, bytes: 10 })!
+}
+
+// Seeds use their own id prefix so they never collide with the controller's
+// `ws-tab-N` sequence. Starting empty (or closing the boot chat) matters: while
+// the boot chat survives it is always the chat the controller resumes.
+function buildSeed(fromEmpty: boolean, seeds: Seed[]): WorkspaceTabsState {
+ return seeds.reduce<WorkspaceTabsState>(
+ (state, seed, index) => {
+ const id = `seed-${index}`
+ switch (seed.op) {
+ case 'app':
+ return openAppTab(state, { id, appRef: seed.appRef, title: seed.appRef })
+ case 'chat':
+ return openChatTab(state, { id, agentRef: seed.agentRef, chatId: seed.chatId })
+ case 'files':
+ return openFilesTab(state, { id, path: seed.path })
+ case 'settings':
+ return openSettingsTab(state, { id, section: seed.section })
+ case 'preview': {
+ const resource = preview(seed.name)
+ return openPreviewTab(state, {
+ id,
+ title: resource.name,
+ gfsUri: resource.gfsUri,
+ fileKind: resource.kind,
+ byteLength: resource.bytes,
+ })
+ }
+ case 'select':
+ return selectWorkspaceTabAt(state, seed.index)
+ case 'close': {
+ const target = state.tabs[seed.index]
+ return target ? closeWorkspaceTab(state, target.id) : state
+ }
+ }
+ },
+ fromEmpty ? createEmptyWorkspaceTabsState() : createWorkspaceTabsState('chat-tab-1')
+ )
+}
+
+describe('useNavigationController never activates an app tab', () => {
+ it('keeps every navigation writer off app tabs, from any store state', () => {
+ fc.assert(
+ fc.property(
+ fc.oneof(
+ { weight: 3, arbitrary: fc.constant(true) },
+ { weight: 1, arbitrary: fc.constant(false) }
+ ),
+ seedsArb,
+ fc.array(navOpArb, { minLength: 1, maxLength: 8 }),
+ (fromEmpty, seeds, ops) => {
+ const { result, unmount } = renderHook(() => useNavigationController())
+ try {
+ act(() => result.current.setWorkspaceTabs(buildSeed(fromEmpty, seeds)))
+ for (const op of ops) {
+ const before = result.current.workspaceTabs.activeTabId
+ act(() => {
+ if (op.op === 'nav') result.current.handleNavSelect(op.route)
+ else if (op.op === 'activateChat')
+ result.current.activateChatTab(op.agentRef, op.chatId)
+ else if (op.op === 'files') result.current.openFilesSection(op.path)
+ else result.current.openPreviewSection(preview(op.name))
+ })
+ const after = result.current.workspaceTabs
+ if (after.activeTabId !== before) {
+ expect(activeWorkspaceTab(after)?.kind).not.toBe('app')
+ }
+ }
+ } finally {
+ unmount()
+ }
+ }
+ ),
+ {
+ numRuns: 300,
+ // No chat ever active, a non-chat tab active and an app tab last:
+ // navigating to chat has no chat to resume or fall back to.
+ examples: [
+ [
+ true,
+ [
+ { op: 'files', path: null },
+ { op: 'app', appRef: 'ns/alpha' },
+ { op: 'select', index: 0 },
+ ],
+ [{ op: 'nav', route: DESKTOP_ROUTES.chat }],
+ ],
+ ],
+ }
+ )
+ })
+})