Skip to content

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

TypeScript

chore: sync EvenDrive fixes with dev

M9a3958d6a8e7
diff --cc control-ui/package-lock.json
index bf3293b71,c8e6c55d0..609d6da58
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-control-ui",
- "version": "0.1.755",
- "version": "0.1.736",
++ "version": "0.1.737",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.755",
- "version": "0.1.736",
++ "version": "0.1.737",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/frontend-components": "file:../packages/frontend-components",
diff --cc control-ui/package.json
index 8af4ea507,e0dec5632..6c036e6f1
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-control-ui",
- "version": "0.1.755",
- "version": "0.1.736",
++ "version": "0.1.737",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
@@@ -58,9 -58,8 +58,9 @@@
"qa:recorder:team-access-shared-label": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-team-access-shared-label.spec.ts",
"qa:recorder:convert-mp4": "bash ../scripts/qa-recorder/convert-videos-mp4.sh",
"qa:recorder:all": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts",
++ "e2e:gfs-drag-and-drop": "node e2e/run-gfs-drag-and-drop.mjs",
"test": "vitest run",
- "test:watch": "vitest",
- "e2e:gfs-drag-and-drop": "node e2e/run-gfs-drag-and-drop.mjs"
+ "test:watch": "vitest"
},
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
diff --cc desktop-app/src/preload.ts
index 18ddd5017,bdd7b5ccb..d429a40b8
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@@ -215,13 -216,8 +216,20 @@@ const clerum = Object.freeze(
getPathForFile: (file: File) => webUtils.getPathForFile(file),
renameResource: (resourceId: string, newName: string, drive?: string, ifMatch?: number) =>
ipcRenderer.invoke('gfs:renameResource', { resourceId, newName, drive, ifMatch }),
- moveResource: (resourceId: string, destinationId: string, drive?: string, ifMatch?: number) =>
- ipcRenderer.invoke('gfs:moveResource', { resourceId, destinationId, drive, ifMatch }),
+ moveResource: (
+ resourceId: string,
+ destinationId: string,
+ drive?: string,
+ ifMatch?: number,
+ newName?: string
- ) => ipcRenderer.invoke('gfs:moveResource', { resourceId, destinationId, drive, ifMatch, newName }),
++ ) =>
++ ipcRenderer.invoke('gfs:moveResource', {
++ resourceId,
++ destinationId,
++ drive,
++ ifMatch,
++ newName,
++ }),
deleteResource: (resourceId: string, drive?: string, ifMatch?: number) =>
ipcRenderer.invoke('gfs:deleteResource', { resourceId, drive, ifMatch }),
grant: (
diff --cc desktop-app/ui/src/App.tsx
index 11a9cf3df,f874248b6..c8d6a6488
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@@ -106,7 -105,11 +105,12 @@@ import type { SandboxUiConversationOrig
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 { GfsDragSessionProvider } from '@/gfs/dragSession'
import type { ActiveSandboxUiApp, NavItem, ThemeMode } from '@/uiTypes'
import {
type DesktopCommandId,
@@@ -2881,199 -2896,195 +2897,203 @@@ export function App()
>
<McpRuntimeProvider value={mcpRuntimeValue}>
<DesktopStateProvider value={desktopStateValue}>
- <main className="app-shell">
- <SidebarNav
- navItem={vm.navItem}
- activeSandboxUiApp={activeSandboxUiApp}
- availableSandboxUiApps={availableSandboxUiApps}
- collapsed={sidebarCollapsed}
- onCollapsedChange={handleSidebarCollapsedChange}
- onNewChat={handleNewWorkspaceChatTab}
- onOpenSandboxUiApp={handleOpenSandboxUiApp}
- onSettingsMenuOpenChange={setSidebarSettingsMenuOpen}
- onSelect={handleSidebarNavSelect}
- onOpenFilesSection={vm.openFilesSection}
- onOpenPreviewSection={vm.openPreviewSection}
- pushToast={vm.pushToast}
- toggleRequestId={sidebarToggleRequestId}
- />
- <section className="workspace-layout">
- <section
- ref={contentPanelRef}
- className={`content-panel glass-card${
- isAgentChatView ? ' content-panel--agent-chat' : ''
- }${vm.navItem === DESKTOP_ROUTES.settings ? ' content-panel--settings' : ''} content-panel--titlebar-actions${
- appNotificationDrawerOpen
- ? ' content-panel--app-notification-drawer-open'
- : ''
- }${chatDrawerVisible ? ' content-panel--chat-drawer-open' : ''}`}
- style={
- chatDrawerVisible
- ? // Only `--chat-drawer-width` lives here now: it feeds the
- // universal tab-area gutter (`--app-header-utilities-width`).
- // The rail's top/width are published by the RightRailShell
- // itself (`--rail-*`), not inherited from the panel.
- { '--chat-drawer-width': `${chatDrawerResize.width}px` }
- : undefined
- }
- >
- {/* Every route mounts the command-center header in the
+ <GfsDragSessionProvider>
- <main className="app-shell">
- <SidebarNav
- navItem={vm.navItem}
- activeSandboxUiApp={activeSandboxUiApp}
- availableSandboxUiApps={availableSandboxUiApps}
- collapsed={sidebarCollapsed}
- onCollapsedChange={handleSidebarCollapsedChange}
- onNewChat={handleNewWorkspaceChatTab}
- onOpenSandboxUiApp={handleOpenSandboxUiApp}
- onSettingsMenuOpenChange={setSidebarSettingsMenuOpen}
- onSelect={handleSidebarNavSelect}
- onOpenFilesSection={vm.openFilesSection}
- onOpenPreviewSection={vm.openPreviewSection}
- pushToast={vm.pushToast}
- toggleRequestId={sidebarToggleRequestId}
- />
- <section className="workspace-layout">
- <section
- ref={contentPanelRef}
- className={`content-panel glass-card${
- isAgentChatView ? ' content-panel--agent-chat' : ''
- }${vm.navItem === DESKTOP_ROUTES.settings ? ' content-panel--settings' : ''} content-panel--titlebar-actions${
- appNotificationDrawerOpen
- ? ' content-panel--app-notification-drawer-open'
- : ''
- }${chatDrawerVisible ? ' content-panel--chat-drawer-open' : ''}`}
- style={
- chatDrawerVisible
- ? // Only `--chat-drawer-width` lives here now: it feeds the
- // universal tab-area gutter (`--app-header-utilities-width`).
- // The rail's top/width are published by the RightRailShell
- // itself (`--rail-*`), not inherited from the panel.
- { '--chat-drawer-width': `${chatDrawerResize.width}px` }
- : undefined
- }
- >
- {/* Every route mounts the command-center header in the
++ <main className="app-shell">
++ <SidebarNav
++ navItem={vm.navItem}
++ activeSandboxUiApp={activeSandboxUiApp}
++ availableSandboxUiApps={availableSandboxUiApps}
++ collapsed={sidebarCollapsed}
++ onCollapsedChange={handleSidebarCollapsedChange}
++ onNewChat={handleNewWorkspaceChatTab}
++ onOpenSandboxUiApp={handleOpenSandboxUiApp}
++ onSettingsMenuOpenChange={setSidebarSettingsMenuOpen}
++ onSelect={handleSidebarNavSelect}
++ onOpenFilesSection={vm.openFilesSection}
++ onOpenPreviewSection={vm.openPreviewSection}
++ pushToast={vm.pushToast}
++ toggleRequestId={sidebarToggleRequestId}
++ />
++ <section className="workspace-layout">
++ <section
++ ref={contentPanelRef}
++ className={`content-panel glass-card${
++ isAgentChatView ? ' content-panel--agent-chat' : ''
++ }${vm.navItem === DESKTOP_ROUTES.settings ? ' content-panel--settings' : ''} content-panel--titlebar-actions${
++ appNotificationDrawerOpen
++ ? ' content-panel--app-notification-drawer-open'
++ : ''
++ }${chatDrawerVisible ? ' content-panel--chat-drawer-open' : ''}`}
++ style={
++ chatDrawerVisible
++ ? // Only `--chat-drawer-width` lives here now: it feeds the
++ // universal tab-area gutter (`--app-header-utilities-width`).
++ // The rail's top/width are published by the RightRailShell
++ // itself (`--rail-*`), not inherited from the panel.
++ { '--chat-drawer-width': `${chatDrawerResize.width}px` }
++ : undefined
++ }
++ >
++ {/* Every route mounts the command-center header in the
window title bar via the same portal — the search
pill and notification bell live in the title bar on
all routes, never floating inline over the panel. */}
-- <TitlebarActionsPortal container={titlebarActionsRoot}>
-- <AppHeader
-- placement="titlebar"
-- searchFocusRequestId={globalSearchFocusRequestId}
-- notificationOpenRequestId={notificationOpenRequestId}
-- notificationTrayMode={
-- notificationTrayUsesDrawer ? 'drawer' : 'overlay'
-- }
-- notificationTrayReady={notificationDrawerReady}
-- notificationTrayLeft={
-- notificationTrayUsesDrawer ? notificationTrayLeft : null
-- }
-- onNotificationTrayOpenChange={setHeaderNotificationTrayOpen}
-- onShellOverlayOpenChange={setHeaderShellOverlayOpen}
-- drawerAvailable={drawerAvailable}
-- chatDrawerOpen={chatDrawerVisible}
-- onToggleChatDrawer={toggleChatDrawer}
-- />
-- </TitlebarActionsPortal>
-- <ToastStack items={vm.toasts} />
-- {/* Single global strip: driven by the universal
++ <TitlebarActionsPortal container={titlebarActionsRoot}>
++ <AppHeader
++ placement="titlebar"
++ searchFocusRequestId={globalSearchFocusRequestId}
++ notificationOpenRequestId={notificationOpenRequestId}
++ notificationTrayMode={
++ notificationTrayUsesDrawer ? 'drawer' : 'overlay'
++ }
++ notificationTrayReady={notificationDrawerReady}
++ notificationTrayLeft={
++ notificationTrayUsesDrawer ? notificationTrayLeft : null
++ }
++ onNotificationTrayOpenChange={setHeaderNotificationTrayOpen}
++ onShellOverlayOpenChange={setHeaderShellOverlayOpen}
++ drawerAvailable={drawerAvailable}
++ chatDrawerOpen={chatDrawerVisible}
++ onToggleChatDrawer={toggleChatDrawer}
++ />
++ </TitlebarActionsPortal>
++ <ToastStack items={vm.toasts} />
++ {/* Single global strip: driven by the universal
store, visible on every route above the
per-kind seam so any tab is reachable from any
tab. Hidden only when the workspace is empty. */}
-- {workspaceTabs.tabs.length > 0 && (
-- <WorkspaceTabStrip
-- tabs={visibleWorkspaceTabs}
-- activeTabId={
-- vm.appsPickerActive ? null : workspaceTabs.activeTabId
-- }
-- onClose={handleCloseWorkspaceTab}
-- onReorder={handleReorderWorkspaceTab}
-- onSelect={handleSelectWorkspaceTab}
-- panelId={
-- vm.navItem === DESKTOP_ROUTES.chat
-- ? 'chat-view-panel'
-- : undefined
-- }
-- />
-- )}
-- {vm.navItem === DESKTOP_ROUTES.chat &&
-- (workspaceTabs.tabs.length === 0 ? (
-- <section className="chat-view-workspace" aria-label="Home">
-- <div className="chat-view-surface">
-- <div className="workspace-home-empty">
-- <h2>Nothing open</h2>
-- <Button onClick={handleNewWorkspaceChatTab}>
-- New chat
-- </Button>
-- <p className="muted">
-- or open something from the sidebar
-- </p>
++ {workspaceTabs.tabs.length > 0 && (
++ <WorkspaceTabStrip
++ tabs={visibleWorkspaceTabs}
++ activeTabId={
++ vm.appsPickerActive ? null : workspaceTabs.activeTabId
++ }
++ onClose={handleCloseWorkspaceTab}
++ onReorder={handleReorderWorkspaceTab}
++ onSelect={handleSelectWorkspaceTab}
++ panelId={
++ vm.navItem === DESKTOP_ROUTES.chat
++ ? 'chat-view-panel'
++ : undefined
++ }
++ />
++ )}
++ {vm.navItem === DESKTOP_ROUTES.chat &&
++ (workspaceTabs.tabs.length === 0 ? (
++ <section className="chat-view-workspace" aria-label="Home">
++ <div className="chat-view-surface">
++ <div className="workspace-home-empty">
++ <h2>Nothing open</h2>
++ <Button onClick={handleNewWorkspaceChatTab}>
++ New chat
++ </Button>
++ <p className="muted">
++ or open something from the sidebar
++ </p>
++ </div>
</div>
-- </div>
-- </section>
-- ) : (
-- <ChatViewWorkspace
-- localSearch={
-- chatLocalSearchOpen ? (
-- <ChatLocalSearch
-- models={chatSemanticModels}
-- onClose={closeChatLocalSearch}
-- onSearchStateChange={handleChatLocalSearchStateChange}
-- />
-- ) : null
++ </section>
++ ) : (
++ <ChatViewWorkspace
++ localSearch={
++ chatLocalSearchOpen ? (
++ <ChatLocalSearch
++ models={chatSemanticModels}
++ onClose={closeChatLocalSearch}
++ onSearchStateChange={handleChatLocalSearchStateChange}
++ />
++ ) : null
++ }
++ surfaceId="chat-view-panel"
++ >
++ <ChatPage scrollContainerRef={contentPanelRef} />
++ </ChatViewWorkspace>
++ ))}
++ {vm.navItem === DESKTOP_ROUTES.agents && (
++ <AgentsPage scrollContainerRef={contentPanelRef} />
++ )}
++ {vm.navItem === DESKTOP_ROUTES.files && (
++ <FilesPage
++ key={activeFilesTabId ?? 'files'}
++ pushToast={vm.pushToast}
++ pendingGfsUri={filesSeedPath}
++ remoteGfsChangeEpoch={remoteGfsChangeEpoch}
++ onLocationChange={handleFilesLocationChange}
++ onOpenPreview={vm.openPreviewSection}
++ />
++ )}
++ {vm.navItem === DESKTOP_ROUTES.preview &&
++ activePreviewPayload && (
++ <FilePreviewPage
++ key={activePreviewTabId ?? 'preview'}
++ gfsUri={activePreviewPayload.gfsUri}
++ fileName={activePreviewTab?.title ?? 'Preview'}
++ fileKind={activePreviewPayload.fileKind}
++ mimeType={activePreviewPayload.mimeType}
++ byteLength={activePreviewPayload.byteLength}
++ reloadVersion={activePreviewPayload.reloadVersion}
++ unavailable={activePreviewPayload.unavailable}
++ />
++ )}
++ {vm.navItem === DESKTOP_ROUTES.connectors && <McpServersPage />}
++ {vm.navItem === DESKTOP_ROUTES.plugins && <WorkflowsPage />}
++ {vm.navItem === DESKTOP_ROUTES.apps && (
++ <SandboxUiPage
++ embed={embed}
++ activeAppRef={activeTabAppRef}
++ refreshError={embedRefreshError}
++ boundsRefreshKey={sandboxUiBoundsRefreshKey}
++ currentTeamId={vm.currentTeamId}
++ headerShellOverlayOpen={
++ headerShellOverlayOpen || commandPaletteOpen
}
-- surfaceId="chat-view-panel"
-- >
-- <ChatPage scrollContainerRef={contentPanelRef} />
-- </ChatViewWorkspace>
-- ))}
-- {vm.navItem === DESKTOP_ROUTES.agents && (
-- <AgentsPage scrollContainerRef={contentPanelRef} />
-- )}
-- {vm.navItem === DESKTOP_ROUTES.files && (
-- <FilesPage
-- key={activeFilesTabId ?? 'files'}
-- pushToast={vm.pushToast}
-- pendingGfsUri={filesSeedPath}
-- remoteGfsChangeEpoch={remoteGfsChangeEpoch}
-- onLocationChange={handleFilesLocationChange}
-- onOpenPreview={vm.openPreviewSection}
-- />
-- )}
-- {vm.navItem === DESKTOP_ROUTES.preview && activePreviewPayload && (
-- <FilePreviewPage
-- key={activePreviewTabId ?? 'preview'}
-- gfsUri={activePreviewPayload.gfsUri}
-- fileName={activePreviewTab?.title ?? 'Preview'}
-- fileKind={activePreviewPayload.fileKind}
-- mimeType={activePreviewPayload.mimeType}
-- byteLength={activePreviewPayload.byteLength}
-- reloadVersion={activePreviewPayload.reloadVersion}
-- unavailable={activePreviewPayload.unavailable}
-- />
-- )}
-- {vm.navItem === DESKTOP_ROUTES.connectors && <McpServersPage />}
-- {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
-- }
-- 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}
- onRefresh={refreshActiveApp}
- onRelaunch={relaunchActiveApp}
-- onEmbedBoundsApplied={handleSandboxUiBoundsApplied}
-- onEmbedSlotTopChange={setChatDrawerEmbedTop}
-- onEmbedSlotRightChange={setNotificationTrayLeft}
-- onNotify={vm.pushToast}
- onShortcutOpenResult={handleSandboxUiShortcutOpenResult}
-- />
-- )}
-- {vm.navItem === DESKTOP_ROUTES.settings && (
-- <SettingsPage
-- shortcutsFocusRequestId={settingsShortcutsRequestId}
-- notificationSettings={vm.notificationSettings}
-- desktopNotificationPermission={vm.desktopNotificationPermission}
-- themeMode={themeMode}
-- onNotify={vm.pushToast}
-- onThemeModeChange={setThemeMode}
-- onNotificationSoundVolumeChange={vm.setNotificationSoundVolume}
-- onPlayNotificationSoundPreview={vm.playNotificationSoundPreview}
-- onSaveNotificationSettings={vm.saveNotificationSettings}
-- channelNotificationPreferences={
-- vm.channelNotificationPreferences
-- }
-- channelNotificationPreferencesLoading={
-- vm.channelNotificationPreferencesLoading
-- }
-- channelNotificationPreferencesSaving={
-- vm.channelNotificationPreferencesSaving
-- }
-- onSaveChannelNotificationPreferences={
-- vm.saveChannelNotificationPreferences
-- }
-- />
-- )}
-- </section>
-- {/* Universal chat drawer (mini-spec 04a §B/§D):
++ sidebarShellOverlayOpen={sidebarSettingsMenuOpen}
++ toastShellOverlayOpen={vm.toasts.length > 0}
++ deepLinkShellOverlayOpen={sandboxUiDeepLinkDialog !== null}
++ localSearchRequestId={sandboxLocalSearchRequestId}
++ titlebarLeadingContainer={titlebarLeadingRoot}
++ onLaunchApp={handleOpenSandboxUiApp}
++ onRefresh={refreshActiveApp}
++ onRelaunch={relaunchActiveApp}
++ onEmbedBoundsApplied={handleSandboxUiBoundsApplied}
++ onEmbedSlotTopChange={setChatDrawerEmbedTop}
++ onEmbedSlotRightChange={setNotificationTrayLeft}
++ onNotify={vm.pushToast}
++ />
++ )}
++ {vm.navItem === DESKTOP_ROUTES.settings && (
++ <SettingsPage
++ shortcutsFocusRequestId={settingsShortcutsRequestId}
++ notificationSettings={vm.notificationSettings}
++ desktopNotificationPermission={
++ vm.desktopNotificationPermission
++ }
++ themeMode={themeMode}
++ onNotify={vm.pushToast}
++ onThemeModeChange={setThemeMode}
++ onNotificationSoundVolumeChange={
++ vm.setNotificationSoundVolume
++ }
++ onPlayNotificationSoundPreview={
++ vm.playNotificationSoundPreview
++ }
++ onSaveNotificationSettings={vm.saveNotificationSettings}
++ channelNotificationPreferences={
++ vm.channelNotificationPreferences
++ }
++ channelNotificationPreferencesLoading={
++ vm.channelNotificationPreferencesLoading
++ }
++ channelNotificationPreferencesSaving={
++ vm.channelNotificationPreferencesSaving
++ }
++ onSaveChannelNotificationPreferences={
++ vm.saveChannelNotificationPreferences
++ }
++ />
++ )}
++ </section>
++ {/* Universal chat drawer (mini-spec 04a §B/§D):
mounted at the workspace-layout level (a sibling
of the content panel), not inside the apps block,
so it persists across ANY non-chat tab (R5). It
@@@ -3082,72 -3093,71 +3102,72 @@@
universal gutter. Single global <ChatPage>/
ChatSwitcher — no duplicated tab state or
streams. */}
-- {chatDrawerVisible && (
-- <RightRailShell
-- occupant="chat-drawer"
-- width={chatDrawerResize.width}
-- top={drawerRailTop}
-- >
-- <ChatDrawer
-- header={
-- <ChatSwitcher
-- tabs={chatWorkspaceTabs}
-- activeTabId={drawerActiveChatTabId}
-- onSelect={handleSelectDrawerChatTab}
-- onNewChat={handleNewWorkspaceChatTab}
-- focusRequestId={chatSwitcherFocusRequestId}
-- />
-- }
-- onNewChat={handleNewWorkspaceChatTab}
-- onExpandFullScreen={expandChatDrawerToFullScreen}
-- onToggle={toggleChatDrawer}
-- containerRef={chatDrawerRef}
-- ready={drawerReady}
-- onResizeHandleMouseDown={
-- chatDrawerResize.onResizeHandleMouseDown
-- }
-- onResizeHandleKeyDown={chatDrawerResize.onResizeHandleKeyDown}
++ {chatDrawerVisible && (
++ <RightRailShell
++ occupant="chat-drawer"
width={chatDrawerResize.width}
-- resizing={chatDrawerResize.isResizing}
++ top={drawerRailTop}
>
-- <ChatPage scrollContainerRef={chatDrawerRef} />
-- </ChatDrawer>
-- </RightRailShell>
-- )}
-- </section>
-- </main>
-- {commandPaletteOpen ? (
-- <CommandPalette
-- platform={platformFromNavigator(navigator.platform)}
-- isEligible={isCommandEligible}
-- onClose={closeCommandPalette}
-- onExecute={commandId => executeDesktopCommand(commandId, 'palette')}
-- restorePreviousFocus={!commandPaletteReturnToSandbox}
-- />
-- ) : null}
-- {desktopUpdateRequiredDialog}
-- {environmentSetupConfirmationDialog}
-- {environmentSwitchConfirmationDialog}
-- {environmentSetupSuccessDialog}
-- {sandboxUiDeepLinkDialog}
-- {pluginConsentPrompt ? (
-- <PluginConsentModal
-- request={pluginConsentPrompt}
-- onResolve={resolvePluginConsent}
-- />
-- ) : null}
-- {pluginGfsPreview ? (
-- <GfsImagePreview
-- key={`${pluginGfsPreview.gfsUri}:${pluginGfsPreview.reloadVersion}`}
-- byteLength={pluginGfsPreview.bytes}
-- fileName={pluginGfsPreview.name}
-- gfsUri={pluginGfsPreview.gfsUri}
-- mimeType={pluginGfsPreview.mimeType}
-- unavailable={pluginGfsPreview.unavailable}
-- onClose={closePluginGfsPreview}
-- />
-- ) : null}
++ <ChatDrawer
++ header={
++ <ChatSwitcher
++ tabs={chatWorkspaceTabs}
++ activeTabId={drawerActiveChatTabId}
++ onSelect={handleSelectDrawerChatTab}
++ onNewChat={handleNewWorkspaceChatTab}
++ focusRequestId={chatSwitcherFocusRequestId}
++ />
++ }
++ onNewChat={handleNewWorkspaceChatTab}
++ onExpandFullScreen={expandChatDrawerToFullScreen}
++ onToggle={toggleChatDrawer}
++ containerRef={chatDrawerRef}
++ ready={drawerReady}
++ onResizeHandleMouseDown={
++ chatDrawerResize.onResizeHandleMouseDown
++ }
++ onResizeHandleKeyDown={chatDrawerResize.onResizeHandleKeyDown}
++ width={chatDrawerResize.width}
++ resizing={chatDrawerResize.isResizing}
++ >
++ <ChatPage scrollContainerRef={chatDrawerRef} />
++ </ChatDrawer>
++ </RightRailShell>
++ )}
++ </section>
++ </main>
++ {commandPaletteOpen ? (
++ <CommandPalette
++ platform={platformFromNavigator(navigator.platform)}
++ isEligible={isCommandEligible}
++ onClose={closeCommandPalette}
++ onExecute={commandId => executeDesktopCommand(commandId, 'palette')}
++ restorePreviousFocus={!commandPaletteReturnToSandbox}
++ />
++ ) : null}
++ {desktopUpdateRequiredDialog}
++ {environmentSetupConfirmationDialog}
++ {environmentSwitchConfirmationDialog}
++ {environmentSetupSuccessDialog}
++ {sandboxUiDeepLinkDialog}
++ {pluginConsentPrompt ? (
++ <PluginConsentModal
++ request={pluginConsentPrompt}
++ onResolve={resolvePluginConsent}
++ />
++ ) : null}
++ {pluginGfsPreview ? (
++ <GfsImagePreview
++ key={`${pluginGfsPreview.gfsUri}:${pluginGfsPreview.reloadVersion}`}
++ byteLength={pluginGfsPreview.bytes}
++ fileName={pluginGfsPreview.name}
++ gfsUri={pluginGfsPreview.gfsUri}
++ mimeType={pluginGfsPreview.mimeType}
++ unavailable={pluginGfsPreview.unavailable}
++ onClose={closePluginGfsPreview}
++ />
++ ) : null}
+ </GfsDragSessionProvider>
</DesktopStateProvider>
</McpRuntimeProvider>
</AgentChatProviders>
diff --cc desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
index 2ed050667,40d357c75..065277fdc
--- a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
@@@ -1,20 -1,15 +1,21 @@@
// @vitest-environment jsdom
- import { type ReactElement, type ReactNode, useReducer } from 'react'
-import { useLayoutEffect, useReducer } from 'react'
++import { type ReactElement, type ReactNode, 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'
+import {
+ QueryClient,
+ QueryClientProvider,
+ useInfiniteQuery,
+ useQueries,
+ useQuery,
+} from '@tanstack/react-query'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
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 { desktopQueryClient, desktopQueryDefaults } from '@lib/queryClient'
import {
activeWorkspaceTab,
createWorkspaceTabsState,
diff --cc desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
index 81fc9c7f4,350074394..dde0772db
--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@@ -1,12 -1,11 +1,13 @@@
// @vitest-environment jsdom
- import { type ReactElement, type ReactNode, useEffect, useReducer } from 'react'
-import { type ReactNode, useEffect, useLayoutEffect, useReducer } from 'react'
++import { type ReactElement, type ReactNode, useEffect, useLayoutEffect, useReducer } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
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 { desktopQueryDefaults } from '@lib/queryClient'
import {
activeWorkspaceTab,
createWorkspaceTabsState,
@@@ -369,15 -388,6 +390,18 @@@ function makeController(overrides: Part
return controller
}
++// App mounts GfsDragSessionProvider, which reads Query state: every bare
++// App render needs a real QueryClient (fresh per render, production cache
++// defaults) instead of the app-level singleton provider it gets in prod.
+function renderApp(ui: ReactElement) {
+ const queryClient = new QueryClient({ defaultOptions: desktopQueryDefaults })
+ return render(ui, {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ ),
+ })
+}
+
describe('App deep-link orchestration', () => {
let currentController: AppController
let emitDeepLink: ((link: SandboxUiDeepLinkEnvelope) => void) | null
@@@ -510,19 -544,11 +558,11 @@@
initialExperienceLoading: false,
navItem: DESKTOP_ROUTES.apps,
} as Partial<AppController>)
- render(<App />)
+ renderApp(<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)
@@@ -538,15 -565,10 +579,10 @@@
initialExperienceLoading: false,
navItem: DESKTOP_ROUTES.apps,
} as Partial<AppController>)
- render(<App />)
+ renderApp(<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
@@@ -572,22 -595,30 +609,30 @@@
initialExperienceLoading: false,
navItem: DESKTOP_ROUTES.apps,
} as Partial<AppController>)
- render(<App />)
+ renderApp(<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 />)
++ renderApp(<App />)
+ await launchLiveApp()
+ await waitForMounted()
+ act(() => appHeaderHarness.props?.onShellOverlayOpenChange?.(true))
+ expect(sandboxUiPageHarness.props?.headerShellOverlayOpen).toBe(true)
+
+ await 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', () => {
@@@ -661,18 -692,16 +706,16 @@@
navItem: DESKTOP_ROUTES.apps,
selectedAgent: 'alpha',
} as Partial<AppController>)
- render(<App />)
+ renderApp(<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)
@@@ -695,15 -719,9 +733,9 @@@
navItem: DESKTOP_ROUTES.apps,
selectedAgent: 'alpha',
} as Partial<AppController>)
- render(<App />)
+ renderApp(<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)
@@@ -757,9 -775,9 +789,9 @@@
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 />)
+ renderApp(<App />)
act(() => emitCommand?.('commands.open'))
for (const [commandId, route] of [
@@@ -1265,16 -1275,11 +1289,11 @@@
navItem: DESKTOP_ROUTES.apps,
handleEnsureTeamContext: ensureTeamContext,
})
- render(<App />)
+ renderApp(<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(() => {
@@@ -1540,6 -1550,54 +1564,54 @@@
expect(ensureTeamContext).toHaveBeenCalledTimes(1)
})
+ it('defers a cross-team link whose open mounts and then fails, with its error', async () => {
+ vi.useFakeTimers({ shouldAdvanceTime: true })
+ let liveTeamId = 'team-a'
+ const ensureTeamContext = vi.fn(async ({ teamId }: { teamId?: string }) => {
+ if (!teamId || teamId === liveTeamId) return false
+ liveTeamId = teamId
+ return true
+ })
+ currentController = makeController({
+ initialExperienceLoading: false,
+ handleEnsureTeamContext: ensureTeamContext,
+ getCurrentTeamId: () => liveTeamId,
+ })
+ listApps.mockResolvedValue({
+ apps: [
+ {
+ appRef: 'ns/app',
+ title: 'Linked App',
+ defaultPath: '/',
+ ready: true,
+ phase: 'active',
+ },
+ ],
+ })
- render(<App />)
++ renderApp(<App />)
+ await waitFor(() => expect(emitDeepLink).not.toBeNull())
+
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-b' })
+ })
+ main.failNextOpenAfterMount(new Error('attach failed'))
+ await confirmPendingAppLink()
+ await waitForAppOpen()
+
+ await waitFor(() => {
+ expect(currentController.pushToast).toHaveBeenCalledWith('attach failed', 'error')
+ })
+ await act(async () => {
+ await main.settle()
+ })
+ expect(main.reported('sandboxUi:released')).toEqual([
+ expect.objectContaining({ reason: 'open_failed' }),
+ ])
+ expect(acknowledgeDeepLink).not.toHaveBeenCalled()
+ expect(liveTeamId).toBe('team-b')
+ expect(ensureTeamContext).toHaveBeenCalledTimes(1)
+ })
+
it('retries a failed cross-team native mount without treating its own restore as a user switch', async () => {
vi.useFakeTimers({ shouldAdvanceTime: true })
let liveTeamId = 'team-a'
@@@ -1878,34 -1927,28 +1941,28 @@@
})
}
- 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 />)
+ renderApp(<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 />)
+ renderApp(<App />)
// Two tabs of the same app: [chat, A, B].
await launchAppFromSidebar()
@@@ -1914,108 -1957,44 +1971,44 @@@
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')
- )
+ await waitFor(() => expect(openSandboxUi()).toHaveBeenCalledTimes(4))
+ expect(main.openCall(3).routePath).toBe('/tickets/B')
})
- it('closes the embed exactly once on deactivation — the store is the single emitter (§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 />)
+ renderApp(<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] })
- renderApp(<App />)
- await launchAppFromSidebar()
+ await act(() => main.crash())
+ await waitFor(() => expect(embedState().failure?.kind).toBe('crashed'))
- // 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()
+ 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] })
- renderApp(<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,
handleEnsureTeamContext: ensureTeamContext,
})
listApps.mockResolvedValue({ apps: [READY_APP] })
- render(<App />)
+ renderApp(<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(() => {
@@@ -2118,195 -2020,97 +2034,97 @@@
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 />)
+ renderApp(<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 waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
+ expect(ensureTeamContext).toHaveBeenCalledTimes(1)
+ expect(liveTeamId).toBe('team-b')
+ 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 () => {
- pendingLocation.resolve({ appRef: 'ns/app', routePath: '/stale/handoff' })
- await Promise.resolve()
- await Promise.resolve()
+ await new Promise(resolve => window.setTimeout(resolve, 50))
})
-
- // 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)
+ expect(openSandboxUi()).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] })
+ it('keeps the user where they navigated when a cross-team link is abandoned', async () => {
+ let liveTeamId = 'team-a'
+ const ensureTeamContext = vi.fn(async ({ teamId }: { teamId?: string }) => {
+ if (!teamId || teamId === liveTeamId) return false
+ liveTeamId = teamId
+ return true
+ })
+ currentController = makeController({
+ initialExperienceLoading: false,
+ navItem: DESKTOP_ROUTES.chat,
+ selectedAgent: 'alpha',
+ activeChatId: 'chat-1',
+ handleEnsureTeamContext: ensureTeamContext,
+ getCurrentTeamId: () => liveTeamId,
+ } as Partial<AppController>)
+ listApps.mockResolvedValue({ apps: [READY_APP] })
- render(<App />)
+ renderApp(<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 waitFor(() => expect(emitDeepLink).not.toBeNull())
- 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 act(async () => {
- await Promise.resolve()
- await Promise.resolve()
+ main.holdNextOpen()
+ act(() => {
+ emitDeepLink?.({ id: 1, appRef: 'ns/app', teamId: 'team-b' })
})
+ await confirmPendingAppLink()
+ await waitForAppOpen()
+ expect(liveTeamId).toBe('team-b')
- // 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()
- })
-
- // 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 () => {
- currentController = makeController({ initialExperienceLoading: false })
- listApps.mockResolvedValue({ apps: [READY_APP, READY_APP_B] })
- renderApp(<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.
+ // The user goes to Files while the linked app is still opening.
act(() => {
- currentController.setWorkspaceTabs(state =>
- setAppTabSavedRoutePath(state, outgoingId, '/a/own')
- )
+ currentController.handleNavSelect(DESKTOP_ROUTES.files)
})
- 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 waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
await act(async () => {
- pendingLocation.resolve({ appRef: 'ns/app-b', routePath: '/b/route' })
- await Promise.resolve()
- await Promise.resolve()
+ await new Promise(resolve => window.setTimeout(resolve, 50))
})
-
- // 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')
+ expect(liveTeamId).toBe('team-b')
+ expect(activeWorkspaceTab(currentController.workspaceTabs)?.kind).toBe('files')
+ expect(openSandboxUi()).toHaveBeenCalledTimes(1)
})
- 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,
- })
+ 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] })
- renderApp(<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 />)
++ const view = renderApp(<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 --cc desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
index b3da5fc99,f60f0d08a..f4701e8b6
--- a/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.sandboxUiOwnership.test.tsx
@@@ -1,12 -1,13 +1,15 @@@
// @vitest-environment jsdom
- import { type ReactElement, type ReactNode, useReducer } from 'react'
+ import { StrictMode, useEffect, useReducer } from 'react'
+ import { flushSync } from 'react-dom'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
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 { desktopQueryDefaults } from '@lib/queryClient'
import { toActiveSandboxUiApps } from '@lib/sandboxUiAppSelection'
import type { SandboxUiAppListing } from '@lib/sandboxUiAppSelection.types'
import {
@@@ -344,321 -429,459 +431,467 @@@ describe('App wires gestures and main e
delete (window as { clerum?: unknown }).clerum
})
- async function renderWithLiveApp(app: typeof ALPHA) {
- renderApp(<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()
+ 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 />)
++ // App mounts GfsDragSessionProvider, which reads Query state: the render
++ // needs a real QueryClient (fresh per render, production cache defaults)
++ // instead of the app-level singleton provider it gets in production.
++ const queryClient = new QueryClient({ defaultOptions: desktopQueryDefaults })
++ render(<App />, {
++ wrapper: ({ children }) => (
++ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
++ ),
+ })
+ await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
+ 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)
+ 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(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)
+ expect(screen.getByText('Loading app')).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Refresh app content' })).toBeNull()
- slotRect.mockReturnValue(MEASURED_SLOT)
- await handOffMarkdownFromPlugin()
+ await act(async () => held().resolve())
+ expect(await screen.findByRole('button', { name: 'Refresh app content' })).toBeTruthy()
+ expect(screen.queryByText('Loading app')).toBeNull()
+ })
+
+ 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('closes the embed when leaving an app tab whose open failed after an app-to-app switch', async () => {
- await renderWithLiveApp(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')
- 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()
+ 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)
})
- 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' }]
- renderApp(<App />)
- await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
- act(() => sidebarHarness.props?.onSelect?.(DESKTOP_ROUTES.apps))
- expect(currentController.appsPickerActive).toBe(true)
+ it('leaves a live view alone when its active tab is clicked again (Q4)', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
- fireEvent.click(await screen.findByRole('button', { name: 'Open Alpha' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Alpha', pressed: true }))
+ await flushMacrotask()
- 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(lastLaunch().type).toBe('intent')
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
expect(sandboxUi.close).not.toHaveBeenCalled()
-
- await handOffMarkdownFromPlugin()
-
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ expect(owner()?.launchId).toBe(main.openCall(0).launchId)
})
- // 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('shows a crash with Reopen, which relaunches the tab through the seam', 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)
- })
+ await act(() => main.crash())
+ expect(await screen.findByText('The app closed unexpectedly.')).toBeTruthy()
+ expect(sidebarHarness.props?.activeSandboxUiApp ?? null).toBeNull()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Reopen' }))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ 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()
+ })
- function emitSandboxUiClosed(event: ViewEventTag) {
- emitToSubscribed(sandboxUi.onClosed, event)
- }
+ it('shows a crash while the app is still opening with Reopen (DEC-10)', async () => {
+ await renderApp()
+ const held = main.holdNextOpen()
+ main.crashNextMount()
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(ALPHA!))
+ await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(1))
+ expect(screen.getByText('Loading app')).toBeTruthy()
- function emitRefreshError(event: ViewEventTag & { message: string }) {
- emitToSubscribed(sandboxUi.onRefreshError, event)
- }
+ // The view mounts and its renderer dies before the open settles.
+ held().resolve()
+ 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')
+ })
- // 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')
- }
+ it('relaunches a dead view when its tab is clicked again', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ await act(() => main.crash())
+ await screen.findByText('The app closed unexpectedly.')
- 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: 'Alpha', pressed: true }))
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().type).toBe('intent')
+ })
- 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('reloads a healthy view in place from Refresh: same view, same route, no relaunch', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
+ main.navigate('/tickets/7')
- // The view of open #1 dies (crash / teardown) before open #2 resolves.
- emitSandboxUiClosed(closedEventFor(0))
- await finishRelaunch()
+ fireEvent.click(screen.getByRole('button', { name: 'Refresh app content' }))
+ await act(() => main.settle())
- await handOffMarkdownFromPlugin()
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ expect(main.liveReloads()).toBe(1)
+ expect(main.live()).toEqual({ launchId: first, appRef: ALPHA!.appRef, routePath: '/tickets/7' })
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+ expect(sandboxUi.close).not.toHaveBeenCalled()
+ expect(main.reported('sandboxUi:released')).toEqual([])
+ expect(owner()?.launchId).toBe(first)
+ expect(screen.getByRole('button', { name: 'Refresh app content' })).toBeTruthy()
})
- 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('reloads a healthy view in place from the app.refresh command', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
- emitRefreshError({ ...closedEventFor(0), message: 'stale failure' })
- await finishRelaunch()
- expect(screen.queryByText(text => text.startsWith('Session refresh failed'))).toBeNull()
+ await shortcut('app.refresh')
+ await act(() => main.settle())
- emitRefreshError({ ...closedEventFor(1), message: 'live failure' })
- expect(
- await screen.findByText(text => text.startsWith('Session refresh failed: live failure'))
- ).toBeTruthy()
+ expect(main.liveReloads()).toBe(1)
+ expect(main.live()?.launchId).toBe(first)
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+ expect(sandboxUi.close).not.toHaveBeenCalled()
+ expect(flushSyncErrors).toEqual([])
})
- 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!))
- await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
+ // Refresh is offered while the last render showed a mounted view, but the
+ // machine can move on before React renders again. Refresh then reopens the
+ // tab: it never reloads a view that is not mounted, gone or still opening.
+ it('relaunches from app.refresh when the view ended before React rendered it', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
+
await act(async () => {
- await new Promise(resolve => window.setTimeout(resolve, 0))
+ void main.crash()
+ const release = main.reported('sandboxUi:released').at(-1) as Parameters<
+ EmbedOwnershipMachine['onReleased']
+ >[0]
+ expect(release).toMatchObject({ launchId: first, reason: 'crashed' })
+ machineHarness.machine!.onReleased(release)
+ shortcutCommandCb?.('app.refresh', 'host')
})
+ await act(() => main.settle())
- emitSandboxUiClosed(closedEventFor(0))
-
- await handOffMarkdownFromPlugin()
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ expect(sandboxUi.reload).not.toHaveBeenCalled()
+ expect(lastLaunch().type).toBe('relaunch')
+ expect(main.live()?.launchId).toBe(main.openCall(1).launchId)
})
- it('keeps the newer launch owned when a superseded open resolves late and its view then dies', async () => {
- renderApp(<App />)
- await waitFor(() => expect(sandboxUi.listApps).toHaveBeenCalled())
- await act(async () => {
- await Promise.resolve()
+ it('relaunches from app.refresh while the relaunch before it is still opening', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ await act(() => main.refreshFailed(new Error('mint failed')))
+ const retry = await screen.findByRole('button', { name: 'Retry' })
+
+ act(() => {
+ fireEvent.click(retry)
+ shortcutCommandCb?.('app.refresh', 'host')
})
- 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 act(() => main.settle())
+
+ expect(sandboxUi.reload).not.toHaveBeenCalled()
+ expect(machineHarness.launches.slice(-2).map(entry => entry.type)).toEqual([
+ 'relaunch',
+ 'relaunch',
+ ])
+ expect(main.live()?.launchId).toBe(machineHarness.launches.at(-1)!.launch.launchId)
+ expect(main.liveReloads()).toBe(0)
+ })
+
+ 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
+
+ await act(() => main.refreshFailed(new Error('mint failed')))
+ expect(await screen.findByText('Session refresh failed: mint failed.')).toBeTruthy()
+
+ 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())
+ })
- // 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))
+ it('clears the session failure and its Retry once a resumed refresh of the same view succeeds', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
+ main.navigate('/tickets/7')
+
+ await act(() => main.refreshFailed(new Error('mint failed')))
+ expect(await screen.findByText('Session refresh failed: mint failed.')).toBeTruthy()
+ const liveBefore = main.live()
- await handOffMarkdownFromPlugin()
- await waitFor(() => expect(sandboxUi.close).toHaveBeenCalledTimes(1))
+ await act(() => main.hostReturned())
+ await act(() => main.settle())
+
+ expect(main.reported('sandboxUi:refreshRecovered')).toEqual([
+ { appRef: ALPHA!.appRef, launchId: first },
+ ])
+ await waitFor(() => expect(screen.queryByText(/Session refresh failed/)).toBeNull())
+ expect(screen.queryByRole('button', { name: 'Retry' })).toBeNull()
+ expect(sandboxUi.open).toHaveBeenCalledTimes(1)
+ expect(sandboxUi.close).not.toHaveBeenCalled()
+ expect(main.live()).toEqual(liveBefore)
+ expect(main.live()).toEqual({ launchId: first, appRef: ALPHA!.appRef, routePath: '/tickets/7' })
})
- it('drops the owner when the closed event belongs to the live embed', async () => {
- await renderWithLiveApp(ALPHA)
- act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
+ // The machine drops a recovery of a launch that no longer owns the embed, so a
+ // late one cannot take down the failure of the view that replaced it.
+ it("keeps a relaunched view's session failure when a recovery of the view it replaced arrives late", async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
+ await act(() => main.refreshFailed(new Error('mint failed')))
+ await act(() => main.hostReturned())
+ await act(() => main.settle())
+ const staleRecovery = main.reported('sandboxUi:refreshRecovered').at(-1) as {
+ appRef: string
+ launchId: string
+ }
+ expect(staleRecovery).toEqual({ appRef: ALPHA!.appRef, launchId: first })
+
+ await act(() => main.refreshFailed(new Error('mint failed')))
+ fireEvent.click(await screen.findByRole('button', { name: 'Retry' }))
await waitFor(() => expect(sandboxUi.open).toHaveBeenCalledTimes(2))
- await act(async () => {
- await new Promise(resolve => window.setTimeout(resolve, 0))
- })
+ await act(() => main.settle())
+ const second = main.openCall(1).launchId
+ expect(main.live()?.launchId).toBe(second)
+ await act(() => main.refreshFailed(new Error('second view failed')))
+ expect(await screen.findByText('Session refresh failed: second view failed.')).toBeTruthy()
- emitSandboxUiClosed(closedEventFor(1))
+ act(() => latestListener<typeof staleRecovery>(sandboxUi.onRefreshRecovered)(staleRecovery))
+ await flushMacrotask()
- 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(screen.getByText('Session refresh failed: second view failed.')).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Retry' })).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('ignores the session failure of a view it already replaced', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
+ const first = main.openCall(0).launchId
- // 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)
+ // The replaced view's loop gives up before the open replacing it reaches main.
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
+ await act(() => main.refreshFailed(new Error('stale failure')))
+ await act(() => main.settle())
+
+ expect(main.reported('sandboxUi:refreshError')).toEqual([
+ expect.objectContaining({ launchId: first, message: 'stale failure' }),
+ ])
+ expect(screen.queryByText(/Session refresh failed/)).toBeNull()
+ expect(main.live()?.launchId).toBe(main.openCall(1).launchId)
+ })
- fireEvent.click(await screen.findByRole('button', { name: 'Open Beta' }))
+ 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
- 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 shortcut('app.backToApps')
+
+ 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()
})
- // App resolves app tabs against its own listing, refreshed on window focus and
- // every 30 s. Firing the real focus listener drives that refresh.
- async function refreshAppListingOnFocus() {
- 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 tab after its title and ignores titles of other views', async () => {
+ await renderApp()
+ await openFromSidebar(ALPHA, 1)
- 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: ' ' })
+ await act(() => main.retitle('Alpha Inbox'))
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()
+ // The view an open replaces retitles itself before that open reaches main.
+ const first = main.openCall(0).launchId
+ act(() => sidebarHarness.props?.onOpenSandboxUiApp?.(BETA!))
+ await act(() => main.retitle('Stale'))
+ await act(() => main.settle())
- await finishRelaunch()
- emitTitleChanged({ ...closedEventFor(1), title: 'Alpha Fresh' })
- expect(screen.getByRole('button', { name: 'Alpha Fresh', pressed: true })).toBeTruthy()
+ expect(main.reported('sandboxUi:titleChanged')).toContainEqual(
+ expect.objectContaining({ launchId: first, title: 'Stale' })
+ )
+ expect(main.live()?.launchId).toBe(main.openCall(1).launchId)
+ expect(screen.getByRole('button', { name: 'Alpha Inbox', pressed: false })).toBeTruthy()
+ expect(screen.queryByRole('button', { name: 'Stale' })).toBeNull()
})
- function tabByAppRef(appRef: string) {
- return currentController.workspaceTabs.tabs.find(tab => tab.app?.appRef === appRef)
- }
+ 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())
- function openedAppRef(openCall: number): string {
- return closedEventFor(openCall).appRef
+ 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 catalog, refreshed on window focus and
+ // every 30 s. Firing the real focus listener drives that refresh.
+ 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 flushMacrotask()
}
const BETA_RESTARTING: SandboxUiAppListing[] = APP_LISTING.map(app =>
@@@ -734,61 -953,216 +963,222 @@@
// 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('drops a failed relaunch banner when the user moves to an app tab that cannot be resolved', async () => {
- await renderWithLiveApp(BETA)
+ 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('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 () => {
++ const queryClient = new QueryClient({ defaultOptions: desktopQueryDefaults })
+ render(
+ <StrictMode>
+ <App />
- </StrictMode>
++ </StrictMode>,
++ {
++ wrapper: ({ children }) => (
++ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
++ ),
++ }
+ )
+ 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 = []
})
})