Skip to content

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

TypeScript

feat(desktop): drive rendering from the universal tab store

Diego Zacarias2ca6a9a5de00
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 93039a7ed..5c7c01749 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -23,6 +23,7 @@ import { PluginConsentModal } from '@components/PluginConsentModal'
import type { PluginConsentRequest } from '@components/PluginConsentModal/types'
import { SidebarNav } from '@components/SidebarNav'
import { TitlebarActionsPortal, WindowTitleBar } from '@components/WindowTitleBar'
+import { WorkspaceTabStrip } from '@components/WorkspaceTabStrip'
import { DESKTOP_ROUTES, SIDEBAR_COLLAPSED_KEY } from '@constants/navigation'
import { THEME_STORAGE_KEY } from '@constants/theme'
import { useAgentChatActionsValue } from '@hooks/useAgentChatActionsValue'
@@ -31,20 +32,6 @@ import { useChatDrawerResize } from '@hooks/useChatDrawerResize'
import { useWindowFocusBridge } from '@hooks/useWindowFocusBridge'
import type { ChatLocalMatch } from '@lib/chatLocalSearch'
import { buildLoadedChatSemanticModels } from '@lib/chatMessageSemantics'
-import {
- activeChatViewTab,
- addBlankChatViewTab,
- closeChatViewTab,
- createChatViewTabsState,
- cycleChatViewTab,
- focusBlankChatViewTab,
- openPersistedChatViewTab,
- reconcileChatViewTabs,
- selectChatViewTab,
- selectChatViewTabAt,
- selectLastChatViewTab,
-} from '@lib/chatViewTabs'
-import type { ChatViewTab } from '@lib/chatViewTabs.types'
import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
import {
canProcessSandboxUiDeepLinks,
@@ -68,6 +55,19 @@ import {
resetPendingSandboxUiDeepLinkFailure,
shouldPurgeSandboxUiDeepLinks,
} from '@lib/sandboxUiDeepLinkState'
+import {
+ activeWorkspaceTab,
+ closeWorkspaceTab,
+ createWorkspaceTabsState,
+ cycleWorkspaceTab,
+ newChatTab,
+ openAppTab,
+ reconcileWorkspaceChatTab,
+ selectLastWorkspaceTab,
+ selectWorkspaceTab,
+ selectWorkspaceTabAt,
+} from '@lib/workspaceTabs'
+import type { WorkspaceTab } from '@lib/workspaceTabs.types'
import { AgentsPage } from '@pages/AgentsPage'
import { AuthPage } from '@pages/AuthPage'
import { ChatPage } from '@pages/ChatPage'
@@ -284,11 +284,12 @@ export function App() {
PendingSandboxUiDeepLink[]
>([])
const [sandboxUiDeepLinkRetryTick, setSandboxUiDeepLinkRetryTick] = React.useState(0)
- const nextChatTabSequenceRef = React.useRef(2)
- const [chatViewTabs, setChatViewTabs] = React.useState(() =>
- createChatViewTabsState('chat-tab-1')
- )
- const chatViewTabsRef = React.useRef(chatViewTabs)
+ // The universal tab store lives in the controller (single writer; `vm.navItem`
+ // is its projection). App composes the strip/reveal/reconcile over it.
+ const workspaceTabs = vm.workspaceTabs
+ const setWorkspaceTabs = vm.setWorkspaceTabs
+ const nextChatTabId = vm.nextWorkspaceTabId
+ const workspaceTabsRef = React.useRef(workspaceTabs)
const chatDrawerRef = React.useRef<HTMLElement | null>(null)
// Mirrors `chatDrawerVisible` so the chat-tab handlers (which run from stable
// callbacks) can tell whether a reveal should target the in-app drawer or the
@@ -338,9 +339,13 @@ export function App() {
const sandboxUiDeepLinkIdentityRef = React.useRef<string | null | undefined>(undefined)
const sandboxUiDeepLinkGenerationRef = React.useRef(0)
const sandboxUiShortcutOpenRequestIdRef = React.useRef(0)
- chatViewTabsRef.current = chatViewTabs
-
- const nextChatTabId = React.useCallback(() => `chat-tab-${nextChatTabSequenceRef.current++}`, [])
+ // Relaunches a backgrounded app tab through the live-app machinery. A ref so
+ // `revealWorkspaceTab` (defined above `launchSandboxUiApp`) can call it without
+ // a TDZ on the launch callback.
+ const relaunchSandboxUiAppRef = React.useRef<
+ ((app: ActiveSandboxUiApp, tabId: string) => void) | null
+ >(null)
+ workspaceTabsRef.current = workspaceTabs
const leaveSandboxForChat = React.useCallback(() => {
setActiveSandboxUiApp(null)
@@ -350,103 +355,154 @@ export function App() {
setSidebarSettingsMenuOpen(false)
}, [])
- const revealChatViewTab = React.useCallback(
- (tab: ChatViewTab, inDrawer = chatDrawerVisibleRef.current) => {
+ // Load the CONTENT of a workspace tab once it is (about to be) active — the
+ // universal reveal seam. It never selects the tab itself (the store already
+ // owns identity/active). Chat tabs delegate to `handleSelectChatAgent` (the
+ // pending-selection machine, §4 — never reimplemented); app tabs relaunch
+ // through the existing embed machinery (store→embed, closes as today on the
+ // next deactivation via the SandboxUiPage unmount cleanup — the single close
+ // path, §9); DOM tabs (files/settings) render from the derived `navItem`, so
+ // this only tears down any lingering app embed.
+ const revealWorkspaceTab = React.useCallback(
+ (tab: WorkspaceTab | undefined, inDrawer = chatDrawerVisibleRef.current) => {
+ if (!tab || tab.kind === 'files' || tab.kind === 'settings') {
+ if (!inDrawer) leaveSandboxForChat()
+ return
+ }
+ if (tab.kind === 'app') {
+ const app = availableSandboxUiApps.find(candidate => candidate.appRef === tab.app?.appRef)
+ if (app) relaunchSandboxUiAppRef.current?.(app, tab.id)
+ return
+ }
+ const agentRef = tab.chat?.agentRef ?? null
+ const chatId = tab.chat?.chatId ?? null
if (inDrawer) {
// Swap the shared <ChatPage>'s conversation in place, keeping the live
// app mounted and the `apps` route active. A blank tab with no agent
// simply shows the empty composer — there is nothing to navigate to.
- if (tab.agentRef) {
+ if (agentRef) {
vm.handleSelectChatAgent(
- tab.agentRef,
- tab.chatId
- ? { chatId: tab.chatId, title: tab.title, selectLatest: false, keepNavItem: true }
+ agentRef,
+ chatId
+ ? { chatId, title: tab.title, selectLatest: false, keepNavItem: true }
: { selectLatest: false, keepNavItem: true }
)
}
return
}
leaveSandboxForChat()
- if (tab.agentRef) {
+ if (agentRef) {
vm.handleSelectChatAgent(
- tab.agentRef,
- tab.chatId
- ? { chatId: tab.chatId, title: tab.title, selectLatest: false }
- : { selectLatest: false }
+ agentRef,
+ chatId ? { chatId, title: tab.title, selectLatest: false } : { selectLatest: false }
)
} else {
vm.handleNavSelect(DESKTOP_ROUTES.chat)
}
},
- [leaveSandboxForChat, vm.handleNavSelect, vm.handleSelectChatAgent]
+ [availableSandboxUiApps, leaveSandboxForChat, vm.handleNavSelect, vm.handleSelectChatAgent]
+ )
+
+ // Global strip selection: activate the tab (so `navItem` derives this commit),
+ // then reveal its content.
+ const handleSelectWorkspaceTab = React.useCallback(
+ (id: string) => {
+ const tab = workspaceTabsRef.current.tabs.find(candidate => candidate.id === id)
+ if (!tab) return
+ vm.clearAppsPicker()
+ setWorkspaceTabs(state => selectWorkspaceTab(state, id))
+ revealWorkspaceTab(tab, false)
+ },
+ [revealWorkspaceTab, setWorkspaceTabs, vm.clearAppsPicker]
)
- const handleSelectChatViewTab = React.useCallback(
+ // Drawer switcher selection: reveal the chat IN the drawer (keepNavItem), never
+ // stealing focus from the active app tab.
+ const handleSelectDrawerChatTab = React.useCallback(
(id: string) => {
- const state = selectChatViewTab(chatViewTabsRef.current, id)
- if (state === chatViewTabsRef.current) return
- setChatViewTabs(state)
- revealChatViewTab(activeChatViewTab(state))
+ const tab = workspaceTabsRef.current.tabs.find(
+ candidate => candidate.id === id && candidate.kind === 'chat'
+ )
+ if (tab) revealWorkspaceTab(tab, true)
},
- [revealChatViewTab]
+ [revealWorkspaceTab]
)
- const handleCloseChatViewTab = React.useCallback(
+ const handleCloseWorkspaceTab = React.useCallback(
(id: string) => {
- const current = chatViewTabsRef.current
+ const current = workspaceTabsRef.current
const wasActive = current.activeTabId === id
- const next = closeChatViewTab(current, id, nextChatTabId())
+ const next = closeWorkspaceTab(current, id)
if (next === current) return
- setChatViewTabs(next)
- if (wasActive) revealChatViewTab(activeChatViewTab(next))
+ vm.clearAppsPicker()
+ setWorkspaceTabs(next)
+ // Closing the active tab activates a neighbor (or empties the workspace,
+ // §5). Reveal it so its content follows the strip.
+ if (wasActive) revealWorkspaceTab(activeWorkspaceTab(next), false)
},
- [nextChatTabId, revealChatViewTab]
+ [revealWorkspaceTab, setWorkspaceTabs, vm.clearAppsPicker]
)
- const handleNewChatViewTab = React.useCallback(() => {
- const next = addBlankChatViewTab(chatViewTabsRef.current, nextChatTabId(), vm.selectedAgent)
- setChatViewTabs(next)
+ const handleNewWorkspaceChatTab = React.useCallback(() => {
+ vm.clearAppsPicker()
+ const agentRef = vm.selectedAgent
if (chatDrawerDivertableRef.current) {
// Drawer is a valid surface (app live, panel wide enough): open the blank
- // chat in the drawer without tearing the live embed down. Opens the drawer
- // if it was closed.
+ // chat in the drawer without tearing the live embed down.
setChatDrawerOpen(true)
- revealChatViewTab(activeChatViewTab(next), true)
+ if (agentRef) {
+ vm.handleSelectChatAgent(agentRef, { selectLatest: false, keepNavItem: true })
+ }
+ // With no agent yet there is nothing to seed, so this INTENTIONALLY writes
+ // nothing to the store — opening/focusing the drawer is the whole action
+ // (equivalent to the old blank-seed). Do not "fix" this to always append.
} else {
- // No divertable drawer (no app live, or the panel is too narrow to render
- // one): fall back to the full-screen chat route so the new chat is reachable
- // instead of landing in a suppressed drawer.
- revealChatViewTab(activeChatViewTab(next))
+ // No divertable drawer: full-screen chat route so the new chat is reachable.
+ leaveSandboxForChat()
+ if (agentRef) {
+ vm.handleSelectChatAgent(agentRef, { selectLatest: false })
+ } else {
+ setWorkspaceTabs(state => newChatTab(state, nextChatTabId(), null))
+ }
}
setComposerFocusRequestId(value => value + 1)
- }, [nextChatTabId, revealChatViewTab, vm.selectedAgent])
+ }, [
+ leaveSandboxForChat,
+ nextChatTabId,
+ setWorkspaceTabs,
+ vm.clearAppsPicker,
+ vm.handleSelectChatAgent,
+ vm.selectedAgent,
+ ])
const openChatDrawer = React.useCallback(() => {
setChatDrawerOpen(true)
// Seed the drawer from the conversation the app was opened from ONLY when
- // there is no real chat to return to yet (blank active tab). Once a real
- // conversation is active in the drawer — because the user launched from a
- // chat, or switched to one via the switcher — reopening must preserve that
- // last-viewed chat, not jump back to the origin. (The launch path seeds the
- // origin on first open; this callback only handles subsequent reopens.)
- const current = chatViewTabsRef.current
- const active = activeChatViewTab(current)
+ // there is no real chat to return to yet. Once a real conversation is active
+ // in the drawer — the user launched from a chat, or switched to one via the
+ // switcher — reopening must preserve that last-viewed chat, not jump back to
+ // the origin. The drawer's current chat is the controller's
+ // (selectedAgent, activeChatId), not the store's active tab (which is the app
+ // tab). The reconcile effect adds the chat tab to the switcher.
const origin = sandboxUiConversationOriginRef.current
- let next = current
- if (origin && active.chatId === null) {
- next = openPersistedChatViewTab(current, {
- id: nextChatTabId(),
- agentRef: origin.agentName,
+ const hasActiveChat = Boolean(vm.selectedAgent && vm.activeChatId)
+ if (origin && !hasActiveChat) {
+ vm.handleSelectChatAgent(origin.agentName, {
chatId: origin.chatId,
title: origin.title,
+ selectLatest: false,
+ keepNavItem: true,
+ })
+ } else if (vm.selectedAgent) {
+ // Re-reveal the current drawer chat in place.
+ vm.handleSelectChatAgent(vm.selectedAgent, {
+ ...(vm.activeChatId ? { chatId: vm.activeChatId } : {}),
+ selectLatest: false,
+ keepNavItem: true,
})
- setChatViewTabs(next)
}
- // The ref still reads `false` until the next render commits the open state,
- // so reveal explicitly in-drawer to swap the shared <ChatPage> in place.
- revealChatViewTab(activeChatViewTab(next), true)
setComposerFocusRequestId(value => value + 1)
- }, [nextChatTabId, revealChatViewTab])
+ }, [vm.activeChatId, vm.handleSelectChatAgent, vm.selectedAgent])
const closeChatDrawer = React.useCallback(() => {
setChatDrawerOpen(false)
@@ -461,15 +517,29 @@ export function App() {
}, [closeChatDrawer, openChatDrawer])
const expandChatDrawerToFullScreen = React.useCallback(() => {
- // Ejects the drawer's active conversation into the full-screen chat route.
- // `revealChatViewTab(_, false)` forces the non-drawer branch: it tears the
- // live embed down and navigates to the chat route. Reset the open intent so a
+ // Ejects the drawer's active conversation into the full-screen chat route:
+ // tear the live embed down and navigate to chat. The drawer's chat is the
+ // controller's (selectedAgent, activeChatId). Reset the open intent so a
// stale `chatDrawerOpen` doesn't linger now that the drawer is gone (a later
// app launch from a chat re-sets it explicitly).
- revealChatViewTab(activeChatViewTab(chatViewTabsRef.current), false)
+ leaveSandboxForChat()
+ if (vm.selectedAgent) {
+ vm.handleSelectChatAgent(vm.selectedAgent, {
+ ...(vm.activeChatId ? { chatId: vm.activeChatId } : {}),
+ selectLatest: false,
+ })
+ } else {
+ vm.handleNavSelect(DESKTOP_ROUTES.chat)
+ }
setChatDrawerOpen(false)
setComposerFocusRequestId(value => value + 1)
- }, [revealChatViewTab])
+ }, [
+ leaveSandboxForChat,
+ vm.activeChatId,
+ vm.handleNavSelect,
+ vm.handleSelectChatAgent,
+ vm.selectedAgent,
+ ])
// minispec 04 approach C: while the app embed is live, an "open conversation"
// gesture (notification / approval) must surface the chat IN the drawer — open
@@ -529,33 +599,26 @@ export function App() {
agentName: string,
options: { selectLatest?: boolean; chatId?: string; isRemote?: boolean; title?: string } = {}
) => {
- const chatId = String(options.chatId || '').trim()
- const next = chatId
- ? openPersistedChatViewTab(chatViewTabsRef.current, {
- id: nextChatTabId(),
- agentRef: agentName,
- chatId,
- title: options.title,
- })
- : focusBlankChatViewTab(chatViewTabsRef.current, nextChatTabId(), agentName)
- setChatViewTabs(next)
- // While the drawer is visible, agent selection (sidebar picker, ChatPage's
- // auto-select) must swap the drawer's chat in place instead of navigating
- // to the full-screen chat route and tearing the live app down.
+ // The controller's handleSelectChatAgent owns the tab store now (it
+ // activates the matching chat tab so `navItem` derives to `chat` in the
+ // same commit). This wrapper only adds drawer-awareness: while the drawer
+ // is visible, selection swaps the drawer's chat in place (`keepNavItem`)
+ // instead of navigating to full-screen and tearing the live app down.
+ vm.clearAppsPicker()
vm.handleSelectChatAgent(
agentName,
chatDrawerVisibleRef.current ? { ...options, keepNavItem: true } : options
)
},
- [nextChatTabId, vm.handleSelectChatAgent]
+ [vm.clearAppsPicker, vm.handleSelectChatAgent]
)
const bootSplashLoading = vm.booting || vm.initialExperienceLoading
const isAgentChatView =
(vm.navItem === DESKTOP_ROUTES.agents && Boolean(vm.selectedAgent)) ||
(vm.navItem === DESKTOP_ROUTES.chat && Boolean(vm.selectedAgent))
// The chat drawer coexists with the live app only on the `apps` route. It is
- // an orthogonal boolean axis over the shared `chatViewTabs`/<ChatPage> — never
- // a second tab store, never a foreground/background precedence module.
+ // an orthogonal boolean axis over the universal store's chat sub-slice /
+ // <ChatPage> — never a second tab store, never a foreground/background module.
const chatDrawerAvailable = vm.navItem === DESKTOP_ROUTES.apps && Boolean(activeSandboxUiApp)
// Intention (what the user asked for) is kept separate from effective
// visibility. `chatDrawerDesired` is the user's open intent on an app-live
@@ -840,33 +903,47 @@ export function App() {
}, [appNotificationDrawerOpen, chatDrawerVisible])
const launchSandboxUiApp = React.useCallback(
- (app: ActiveSandboxUiApp, conversationOrigin: SandboxUiConversationOrigin | null) => {
+ (
+ app: ActiveSandboxUiApp,
+ conversationOrigin: SandboxUiConversationOrigin | null,
+ existingTabId?: string
+ ) => {
const requestId = sandboxUiShortcutOpenRequestIdRef.current + 1
sandboxUiShortcutOpenRequestIdRef.current = requestId
setSandboxUiMounted(false)
setSandboxUiConversationOrigin(conversationOrigin)
setActiveSandboxUiApp(app)
- vm.handleNavSelect(DESKTOP_ROUTES.apps)
+ // Store→embed: activate the app tab (a new one, or the backgrounded one on
+ // relaunch). Its `kind:'app'` derives `navItem` to the Apps route this
+ // commit and clears the instance-less picker residual.
+ vm.clearAppsPicker()
+ setWorkspaceTabs(state =>
+ existingTabId
+ ? selectWorkspaceTab(state, existingTabId)
+ : openAppTab(state, { id: nextChatTabId(), appRef: app.appRef, title: app.label })
+ )
setSandboxUiShortcutOpenRequestId(requestId)
if (conversationOrigin) {
// Opened from a chat: bring that conversation straight into the drawer
// instead of the destroy-and-reconstitute round-trip. The embed stays
- // live; `keepNavItem` (via revealChatViewTab in-drawer) records a pending
- // selection that survives the `apps` route change and loads the chat.
+ // live; `keepNavItem` records a pending selection that survives the
+ // `apps` route change and loads the chat. The reconcile effect adds the
+ // chat tab to the switcher.
setChatDrawerOpen(true)
- const next = openPersistedChatViewTab(chatViewTabsRef.current, {
- id: nextChatTabId(),
- agentRef: conversationOrigin.agentName,
+ vm.handleSelectChatAgent(conversationOrigin.agentName, {
chatId: conversationOrigin.chatId,
title: conversationOrigin.title,
+ selectLatest: false,
+ keepNavItem: true,
})
- setChatViewTabs(next)
- revealChatViewTab(activeChatViewTab(next), true)
}
return requestId
},
- [nextChatTabId, revealChatViewTab, vm.handleNavSelect]
+ [nextChatTabId, setWorkspaceTabs, vm.clearAppsPicker, vm.handleSelectChatAgent]
)
+ relaunchSandboxUiAppRef.current = (app, tabId) => {
+ launchSandboxUiApp(app, null, tabId)
+ }
const handleSidebarNavSelect = React.useCallback(
(item: NavItem) => {
@@ -1256,13 +1333,13 @@ export function App() {
]
)
- // Reconcile `chatViewTabs` (the switcher's source of truth) from the vm's
- // displayed chat. Runs for the full-screen chat route AND whenever the drawer
- // is visible (minispec 04, approach A), so any path that moves `vm.activeChatId`
- // — the ChatThread session list, an opened notification, auto-select, resume —
- // keeps the drawer's select in sync. `reconcileChatViewTabs` is idempotent, so
- // this never ping-pongs with the drawer reveal paths and never drives a chat
- // switch itself.
+ // Reconcile the chat sub-slice of the universal store from the vm's displayed
+ // chat. Runs for the full-screen chat route AND whenever the drawer is visible,
+ // so any path that moves `vm.activeChatId` — the ChatThread session list, an
+ // opened notification, auto-select, resume — keeps the strip / drawer switcher
+ // in sync. `reconcileWorkspaceChatTab` is idempotent (returns the same
+ // reference when already aligned), so this never ping-pongs with the reveal
+ // paths and never drives a chat switch itself.
React.useEffect(() => {
if ((vm.navItem !== DESKTOP_ROUTES.chat && !chatDrawerVisible) || !vm.selectedAgent) return
const conversation = vm.activeChatId
@@ -1276,10 +1353,29 @@ export function App() {
chatId: vm.activeChatId ?? null,
title: conversation?.title,
}
- setChatViewTabs(state => reconcileChatViewTabs(state, active, nextChatTabId()))
+ setWorkspaceTabs(state => {
+ const reconciled = reconcileWorkspaceChatTab(state, active, nextChatTabId())
+ if (reconciled === state) return state
+ // Drawer mode: the active tab is the app tab. Keep the chat tab reconcile
+ // created/aligned (so the switcher lists it) but DON'T let it steal the
+ // active slot — activating a chat tab would flip navItem to chat and tear
+ // the embed down.
+ const current = activeWorkspaceTab(state)
+ if (current && current.kind !== 'chat') {
+ // Drawer mode: keep the app tab active. When reconcile only moved
+ // `activeTabId` (the tab list is unchanged), return `state` unchanged so
+ // the idempotent same-reference bail this effect relies on still holds —
+ // rebuilding an equal object would force one extra render per change.
+ return reconciled.tabs === state.tabs
+ ? state
+ : { tabs: reconciled.tabs, activeTabId: state.activeTabId }
+ }
+ return reconciled
+ })
}, [
chatDrawerVisible,
nextChatTabId,
+ setWorkspaceTabs,
vm.activeChatId,
vm.chatList,
vm.latestChatSessions,
@@ -1287,9 +1383,17 @@ export function App() {
vm.selectedAgent,
])
+ // Reset ephemeral UI + the workspace store when the authenticated principal
+ // CHANGES (team switch / re-login), not on the initial mount — the controller
+ // already seeds a fresh store there, and resetting on mount would clobber the
+ // derived route before the first paint.
+ const previousPrincipalIdentityRef = React.useRef<string | null | undefined>(undefined)
React.useEffect(() => {
- nextChatTabSequenceRef.current = 2
- setChatViewTabs(createChatViewTabsState('chat-tab-1'))
+ const previousIdentity = previousPrincipalIdentityRef.current
+ previousPrincipalIdentityRef.current = vm.authenticatedPrincipalIdentity
+ if (previousIdentity === undefined) return
+ setWorkspaceTabs(createWorkspaceTabsState('chat-tab-1'))
+ vm.clearAppsPicker()
setComposerFocusRequestId(0)
setGlobalSearchFocusRequestId(0)
setNotificationOpenRequestId(0)
@@ -1307,17 +1411,22 @@ export function App() {
const desktopCommandContext = React.useMemo(
() => ({
- tabCount: chatViewTabs.tabs.length,
+ tabCount: workspaceTabs.tabs.length,
searchableContent:
(vm.navItem === DESKTOP_ROUTES.apps && Boolean(activeSandboxUiApp)) ||
(vm.navItem === DESKTOP_ROUTES.chat && Boolean(vm.activeChatId)),
composerAvailable:
// The drawer surfaces the same live composer as the full-screen chat
// route, so `composer.focus` must be eligible there too — not only when
- // `navItem === chat`. The command handler's reveal is already
- // drawer-aware; the gate was the only thing pinning it to the route.
+ // `navItem === chat`. On the chat route the active chat tab's agent gates
+ // it; in the drawer it is the controller's selected agent (the app tab is
+ // active, so the store's active tab is not a chat).
(vm.navItem === DESKTOP_ROUTES.chat || chatDrawerVisible) &&
- Boolean(activeChatViewTab(chatViewTabs).agentRef) &&
+ Boolean(
+ chatDrawerVisible
+ ? vm.selectedAgent
+ : (activeWorkspaceTab(workspaceTabs)?.chat?.agentRef ?? null)
+ ) &&
vm.hostRuntimeStatus?.degraded?.reason !== 'llm_key_missing',
appMounted:
vm.navItem === DESKTOP_ROUTES.apps && Boolean(activeSandboxUiApp) && sandboxUiMounted,
@@ -1326,12 +1435,13 @@ export function App() {
[
activeSandboxUiApp,
chatDrawerVisible,
- chatViewTabs,
sandboxUiMounted,
vm.activeChatId,
vm.busy,
vm.hostRuntimeStatus,
vm.navItem,
+ vm.selectedAgent,
+ workspaceTabs,
]
)
@@ -1364,8 +1474,17 @@ export function App() {
}
const command = getDesktopCommand(commandId)
if (origin !== 'palette' && hasBlockingDesktopDialog()) return
- const state = chatViewTabsRef.current
+ const state = workspaceTabsRef.current
if (!isDesktopCommandEligible(command, desktopCommandContext)) return
+ // Universal tab commands: activate a tab then reveal its content (chat load
+ // / app relaunch / DOM route). `tabs.*` cycle over ALL tabs; `chat.*` are
+ // chat-specific.
+ const selectAndReveal = (next: typeof state) => {
+ if (next === state) return
+ vm.clearAppsPicker()
+ setWorkspaceTabs(next)
+ revealWorkspaceTab(activeWorkspaceTab(next), false)
+ }
if (commandId === 'commands.open') {
closeChatLocalSearch(false)
if (origin === 'palette') {
@@ -1439,7 +1558,7 @@ export function App() {
}
if (commandId === 'chat.newTab') {
closeChatLocalSearch(false)
- handleNewChatViewTab()
+ handleNewWorkspaceChatTab()
return
}
if (commandId === 'chat.switcher') {
@@ -1456,33 +1575,38 @@ export function App() {
}
if (commandId === 'chat.closeTab') {
closeChatLocalSearch(false)
- handleCloseChatViewTab(state.activeTabId)
+ if (state.activeTabId) handleCloseWorkspaceTab(state.activeTabId)
return
}
if (command.eligibility === 'tab-index' && command.tabIndex !== undefined) {
- const next = selectChatViewTabAt(state, command.tabIndex)
- if (next !== state) {
- setChatViewTabs(next)
- revealChatViewTab(activeChatViewTab(next))
- }
+ selectAndReveal(selectWorkspaceTabAt(state, command.tabIndex))
return
}
if (commandId === 'tabs.selectLast') {
- const next = selectLastChatViewTab(state)
- setChatViewTabs(next)
- revealChatViewTab(activeChatViewTab(next))
+ selectAndReveal(selectLastWorkspaceTab(state))
return
}
if (commandId === 'tabs.next' || commandId === 'tabs.previous') {
if (state.tabs.length < 2) return
- const next = cycleChatViewTab(state, commandId === 'tabs.next' ? 'next' : 'previous')
- setChatViewTabs(next)
- revealChatViewTab(activeChatViewTab(next))
+ selectAndReveal(cycleWorkspaceTab(state, commandId === 'tabs.next' ? 'next' : 'previous'))
return
}
if (commandId === 'composer.focus') {
closeChatLocalSearch(false)
- revealChatViewTab(activeChatViewTab(state))
+ if (chatDrawerVisibleRef.current) {
+ // In the drawer the active workspace tab is the app tab; the composer
+ // belongs to the drawer's chat (selectedAgent, activeChatId). Reveal it
+ // in place so focus lands on the drawer's live composer.
+ if (vm.selectedAgent) {
+ vm.handleSelectChatAgent(vm.selectedAgent, {
+ ...(vm.activeChatId ? { chatId: vm.activeChatId } : {}),
+ selectLatest: false,
+ keepNavItem: true,
+ })
+ }
+ } else {
+ revealWorkspaceTab(activeWorkspaceTab(state), false)
+ }
setComposerFocusRequestId(value => value + 1)
return
}
@@ -1507,17 +1631,21 @@ export function App() {
closeCommandPalette,
commandPaletteOpen,
desktopCommandContext,
- handleCloseChatViewTab,
- handleNewChatViewTab,
+ handleCloseWorkspaceTab,
+ handleNewWorkspaceChatTab,
handleSidebarNavSelect,
openChatDrawer,
- revealChatViewTab,
+ revealWorkspaceTab,
sandboxUiMounted,
+ setWorkspaceTabs,
vm.activeChatId,
+ vm.clearAppsPicker,
vm.handleNavSelect,
vm.handleLogout,
+ vm.handleSelectChatAgent,
vm.isAuthenticated,
vm.navItem,
+ vm.selectedAgent,
]
)
@@ -1961,6 +2089,20 @@ export function App() {
tone="primary"
/>
) : null
+ // The drawer switcher is chat-only: the chat sub-slice of the universal store.
+ // Its "current" chat is the controller's (selectedAgent, activeChatId) — NOT
+ // the store's active tab, which is the app tab while the drawer is open.
+ const chatWorkspaceTabs = React.useMemo(
+ () => workspaceTabs.tabs.filter((tab): tab is WorkspaceTab => tab.kind === 'chat'),
+ [workspaceTabs.tabs]
+ )
+ const drawerActiveChatTabId =
+ chatWorkspaceTabs.find(
+ tab =>
+ (tab.chat?.agentRef ?? null) === vm.selectedAgent &&
+ (tab.chat?.chatId ?? null) === (vm.activeChatId ?? null)
+ )?.id ?? null
+
const desktopUpdateRequiredDialog =
vm.isAuthenticated && vm.desktopReleaseStatus?.updateRequired ? (
<DesktopUpdateRequiredDialog
@@ -1995,7 +2137,7 @@ export function App() {
availableSandboxUiApps={availableSandboxUiApps}
collapsed={sidebarCollapsed}
onCollapsedChange={handleSidebarCollapsedChange}
- onNewChat={handleNewChatViewTab}
+ onNewChat={handleNewWorkspaceChatTab}
onOpenSandboxUiApp={handleOpenSandboxUiApp}
onSettingsMenuOpenChange={setSidebarSettingsMenuOpen}
onSelect={handleSidebarNavSelect}
@@ -2047,26 +2189,56 @@ export function App() {
/>
</TitlebarActionsPortal>
<ToastStack items={vm.toasts} />
- {vm.navItem === DESKTOP_ROUTES.chat && (
- <ChatViewWorkspace
- activeTabId={chatViewTabs.activeTabId}
- localSearch={
- chatLocalSearchOpen ? (
- <ChatLocalSearch
- models={chatSemanticModels}
- onClose={closeChatLocalSearch}
- onSearchStateChange={handleChatLocalSearchStateChange}
- />
- ) : null
+ {/* 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={workspaceTabs.tabs}
+ activeTabId={
+ vm.appsPickerActive ? null : workspaceTabs.activeTabId
+ }
+ onClose={handleCloseWorkspaceTab}
+ onSelect={handleSelectWorkspaceTab}
+ panelId={
+ vm.navItem === DESKTOP_ROUTES.chat
+ ? 'chat-view-panel'
+ : undefined
}
- onClose={handleCloseChatViewTab}
- onSelect={handleSelectChatViewTab}
- surfaceId="chat-view-panel"
- tabs={chatViewTabs.tabs}
- >
- <ChatPage scrollContainerRef={contentPanelRef} />
- </ChatViewWorkspace>
+ />
)}
+ {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>
+ </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} />
)}
@@ -2112,14 +2284,14 @@ export function App() {
<ChatDrawer
header={
<ChatSwitcher
- tabs={chatViewTabs.tabs}
- activeTabId={chatViewTabs.activeTabId}
- onSelect={handleSelectChatViewTab}
- onNewChat={handleNewChatViewTab}
+ tabs={chatWorkspaceTabs}
+ activeTabId={drawerActiveChatTabId}
+ onSelect={handleSelectDrawerChatTab}
+ onNewChat={handleNewWorkspaceChatTab}
focusRequestId={chatSwitcherFocusRequestId}
/>
}
- onNewChat={handleNewChatViewTab}
+ onNewChat={handleNewWorkspaceChatTab}
onExpandFullScreen={expandChatDrawerToFullScreen}
onToggle={toggleChatDrawer}
containerRef={chatDrawerRef}
diff --git a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
index 333436b06..c24072010 100644
--- a/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.chatDrawer.test.tsx
@@ -1,12 +1,63 @@
// @vitest-environment jsdom
+import { useReducer } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { useNotificationsContext } from '@contexts/NotificationsContext'
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { DESKTOP_ROUTES } from '@constants/navigation'
import { useAppController } from '@hooks/useAppController'
+import {
+ activeWorkspaceTab,
+ createWorkspaceTabsState,
+ newChatTab,
+ openChatTab,
+ openFilesTab,
+ openSettingsTab,
+} from '@lib/workspaceTabs'
+import { mapKindToRoute, settingsSectionForRoute } from '@lib/workspaceTabsRoute'
import { App } from '@/App'
import type { AppNotification } from '@/uiTypes'
+// The universal tab store now lives inside the controller (single writer;
+// `navItem` derives from the active tab). These tests mock the controller, so
+// the mock reproduces that contract faithfully: `navItem` is DERIVED from the
+// store in `useReactiveController` (never a hand-set field), `setWorkspaceTabs`
+// bails out on an unchanged reference like React's setState, and the nav /
+// selection handlers drive the store through the real producers so the real
+// reconcile effect and real ChatSwitcher stay store-driven (T1).
+let forceControllerRender: () => void = () => {}
+
+function useReactiveController(controller: AppController): AppController {
+ const [, force] = useReducer((count: number) => count + 1, 0)
+ forceControllerRender = force
+ const activeTab = activeWorkspaceTab(controller.workspaceTabs)
+ ;(controller as { activeWorkspaceTab: unknown }).activeWorkspaceTab = activeTab
+ ;(controller as { navItem: unknown }).navItem = controller.appsPickerActive
+ ? DESKTOP_ROUTES.apps
+ : mapKindToRoute(activeTab)
+ return controller
+}
+
+type WorkspaceState = ReturnType<typeof useAppController>['workspaceTabs']
+
+// Store-driving helpers that mirror the real controller (focus a chat tab /
+// activate a specific chat), reused by the mock's nav + selection handlers.
+function focusChatState(state: WorkspaceState, nextId: string): WorkspaceState {
+ const active = activeWorkspaceTab(state)
+ if (active?.kind === 'chat') return state
+ const lastChat = [...state.tabs].reverse().find(tab => tab.kind === 'chat')
+ return lastChat ? { ...state, activeTabId: lastChat.id } : newChatTab(state, nextId, null)
+}
+function activateChatState(
+ state: WorkspaceState,
+ agentRef: string | null,
+ chatId: string | null,
+ nextId: string
+): WorkspaceState {
+ return chatId
+ ? openChatTab(state, { id: nextId, agentRef, chatId })
+ : newChatTab(state, nextId, agentRef)
+}
+
// Keep @components/Common, ChatDrawer and ChatSwitcher REAL so the drawer's
// open-chats switcher renders and can be driven. Everything else that App mounts
// is stubbed to null / prop-capture.
@@ -99,16 +150,72 @@ type AppController = ReturnType<typeof useAppController>
function makeController(overrides: Partial<AppController> = {}): AppController {
const noop = vi.fn()
let controller: AppController
+ let tabSequence = 2
+ const nextWorkspaceTabId = vi.fn(() => `ws-tab-${tabSequence++}`)
+ // React-setState-faithful: bail out on an unchanged reference (so the
+ // idempotent reconcile effect can't spin), otherwise commit + re-render.
+ const setWorkspaceTabs = vi.fn((updater: unknown) => {
+ const next =
+ typeof updater === 'function'
+ ? (updater as (state: AppController['workspaceTabs']) => AppController['workspaceTabs'])(
+ controller.workspaceTabs
+ )
+ : (updater as AppController['workspaceTabs'])
+ if (next === controller.workspaceTabs) return
+ controller.workspaceTabs = next
+ forceControllerRender()
+ })
+ const clearAppsPicker = vi.fn(() => {
+ if (!controller.appsPickerActive) return
+ controller.appsPickerActive = false
+ forceControllerRender()
+ })
+ const showAppsPicker = vi.fn(() => {
+ // The picker residual is redundant when an app tab is already active.
+ if (controller.appsPickerActive) return
+ if (activeWorkspaceTab(controller.workspaceTabs)?.kind === 'app') return
+ controller.appsPickerActive = true
+ forceControllerRender()
+ })
+ // Faithful to the real controller: nav is a store action. `navItem` is derived
+ // (useReactiveController), so these drive the store — never set navItem.
const handleNavSelect = vi.fn((item: AppController['navItem']) => {
- controller.navItem = item
+ if (item === DESKTOP_ROUTES.chat) {
+ controller.selectedAgent = null
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) => focusChatState(state, nextWorkspaceTabId()))
+ } else if (item === DESKTOP_ROUTES.apps) {
+ showAppsPicker()
+ } else if (item === DESKTOP_ROUTES.files) {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) => openFilesTab(state, { id: nextWorkspaceTabId() }))
+ } else {
+ const section = settingsSectionForRoute(item)
+ if (section) {
+ if (section === 'agents') controller.selectedAgent = null
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ openSettingsTab(state, { id: nextWorkspaceTabId(), section })
+ )
+ }
+ }
+ forceControllerRender()
})
// Faithful to the real vm: selecting an agent/chat moves the primary
- // `vm.activeChatId`/`selectedAgent` (the reconciler derives the tab from them).
+ // `vm.activeChatId`/`selectedAgent`, and (non-keepNavItem) activates the chat
+ // tab so `navItem` derives to `chat`. `keepNavItem` leaves the active tab (the
+ // app tab) untouched so the route stays on `apps`.
const handleSelectChatAgent = vi.fn(
(agentName: string, options: { chatId?: string; keepNavItem?: boolean } = {}) => {
controller.selectedAgent = agentName
controller.activeChatId = options.chatId ?? null
- if (!options.keepNavItem) controller.navItem = DESKTOP_ROUTES.chat
+ if (!options.keepNavItem) {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ activateChatState(state, agentName, options.chatId ?? null, nextWorkspaceTabId())
+ )
+ }
+ forceControllerRender()
}
)
// Faithful to the real openAgentConversationTarget: `keepNavItem` (passed by
@@ -119,16 +226,31 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
notification: { kind?: string; agentName?: string; chatId?: string },
options: { keepNavItem?: boolean } = {}
) => {
- // Faithful routing: workflow/sdk notifications navigate away (not to the
- // chat/apps surface) — model them as leaving the agent chat state untouched.
+ // Faithful routing: workflow notifications navigate to the plugins section;
+ // sdk notifications navigate away without touching the agent chat state.
if (notification.kind === 'workflow_completed') {
- controller.navItem = DESKTOP_ROUTES.plugins
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ openSettingsTab(state, { id: nextWorkspaceTabId(), section: 'plugins' })
+ )
+ forceControllerRender()
return Promise.resolve()
}
if (notification.kind === 'sdk_notification') return Promise.resolve()
controller.selectedAgent = notification.agentName ?? controller.selectedAgent
controller.activeChatId = notification.chatId ?? null
- if (!options.keepNavItem) controller.navItem = DESKTOP_ROUTES.chat
+ if (!options.keepNavItem) {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ activateChatState(
+ state,
+ controller.selectedAgent,
+ notification.chatId ?? null,
+ nextWorkspaceTabId()
+ )
+ )
+ }
+ forceControllerRender()
return Promise.resolve()
}
)
@@ -147,6 +269,14 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
selectedAgentRoute: null,
selectedContext: null,
selectedTeam: null,
+ workspaceTabs: createWorkspaceTabsState('chat-tab-1'),
+ setWorkspaceTabs,
+ activeWorkspaceTab: undefined,
+ nextWorkspaceTabId,
+ appsPickerActive: false,
+ showAppsPicker,
+ clearAppsPicker,
+ activateWorkspaceChatTab: noop,
activeChatId: null,
chatList: [],
latestChatSessions: [],
@@ -182,6 +312,25 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
setBooting: noop,
...overrides,
} as unknown as AppController
+ // `navItem` is derived from the store (useReactiveController), so an override
+ // that names a starting route is translated into the store state that derives
+ // to it — never a hand-set `navItem` field.
+ if (overrides.navItem) {
+ const route = overrides.navItem
+ if (route === DESKTOP_ROUTES.apps) {
+ controller.appsPickerActive = true
+ } else if (route === DESKTOP_ROUTES.files) {
+ controller.workspaceTabs = openFilesTab(controller.workspaceTabs, { id: 'seed-files' })
+ } else if (route !== DESKTOP_ROUTES.chat) {
+ const section = settingsSectionForRoute(route)
+ if (section) {
+ controller.workspaceTabs = openSettingsTab(controller.workspaceTabs, {
+ id: `seed-${section}`,
+ section,
+ })
+ }
+ }
+ }
return controller
}
@@ -219,7 +368,7 @@ describe('App chat drawer — reopen preserves the last-viewed chat', () => {
appHeaderHarness.props = null
appHeaderHarness.openNotification = null
currentController = makeController()
- vi.mocked(useAppController).mockImplementation(() => currentController)
+ vi.mocked(useAppController).mockImplementation(() => useReactiveController(currentController))
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
@@ -843,7 +992,7 @@ describe('App chat drawer — narrow-width suppression (mini-spec 05)', () => {
navItem: DESKTOP_ROUTES.chat,
chatList: CHAT_LIST,
} as Partial<AppController>)
- vi.mocked(useAppController).mockImplementation(() => currentController)
+ vi.mocked(useAppController).mockImplementation(() => useReactiveController(currentController))
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
index 53ccf47a5..28c509e6e 100644
--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@ -1,13 +1,40 @@
// @vitest-environment jsdom
-import { useEffect } from 'react'
+import { useEffect, useReducer } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, render, waitFor } from '@testing-library/react'
import { DESKTOP_ROUTES, SIDEBAR_COLLAPSED_KEY } from '@constants/navigation'
import { useAppController } from '@hooks/useAppController'
+import {
+ activeWorkspaceTab,
+ createWorkspaceTabsState,
+ newChatTab,
+ openChatTab,
+ openFilesTab,
+ openSettingsTab,
+} from '@lib/workspaceTabs'
+import { mapKindToRoute, settingsSectionForRoute } from '@lib/workspaceTabsRoute'
import { App } from '@/App'
import type { SandboxUiDeepLinkEnvelope } from '@/App.types'
import type { DesktopCommandId } from '../../../src/desktopCommands'
+// The universal tab store lives inside the controller; the mock reproduces that
+// contract — `navItem` is DERIVED from the store, the store is reactive, and nav
+// drives it through the real producers (T1). See App.chatDrawer.test for the
+// rationale.
+let forceControllerRender: () => void = () => {}
+type WorkspaceState = ReturnType<typeof useAppController>['workspaceTabs']
+
+function useReactiveController(controller: AppController): AppController {
+ const [, force] = useReducer((count: number) => count + 1, 0)
+ forceControllerRender = force
+ const activeTab = activeWorkspaceTab(controller.workspaceTabs)
+ ;(controller as { activeWorkspaceTab: unknown }).activeWorkspaceTab = activeTab
+ ;(controller as { navItem: unknown }).navItem = controller.appsPickerActive
+ ? DESKTOP_ROUTES.apps
+ : mapKindToRoute(activeTab)
+ return controller
+}
+
const confirmDialogHarness = vi.hoisted(() => ({
rendered: vi.fn(),
// Counts how many ConfirmDialogs are actually on screen right now,
@@ -152,15 +179,80 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
const noop = vi.fn()
let liveTeamId = String(overrides.currentTeamId || 'team-a')
let controller: AppController
+ let tabSequence = 2
+ const nextWorkspaceTabId = vi.fn(() => `ws-tab-${tabSequence++}`)
+ const setWorkspaceTabs = vi.fn((updater: unknown) => {
+ const next =
+ typeof updater === 'function'
+ ? (updater as (state: WorkspaceState) => WorkspaceState)(controller.workspaceTabs)
+ : (updater as WorkspaceState)
+ if (next === controller.workspaceTabs) return
+ controller.workspaceTabs = next
+ forceControllerRender()
+ })
+ const clearAppsPicker = vi.fn(() => {
+ if (!controller.appsPickerActive) return
+ controller.appsPickerActive = false
+ forceControllerRender()
+ })
+ const showAppsPicker = vi.fn(() => {
+ if (controller.appsPickerActive) return
+ if (activeWorkspaceTab(controller.workspaceTabs)?.kind === 'app') return
+ controller.appsPickerActive = true
+ forceControllerRender()
+ })
const ensureTeamContext = vi.fn(async (target: { teamId?: string }): Promise<boolean> => {
const targetTeamId = String(target.teamId || '').trim()
if (!targetTeamId || targetTeamId === liveTeamId) return false
liveTeamId = targetTeamId
return true
})
+ // Faithful nav: a store action; `navItem` is derived (useReactiveController).
const handleNavSelect = vi.fn((item: AppController['navItem']) => {
- controller.navItem = item
+ if (item === DESKTOP_ROUTES.chat) {
+ controller.selectedAgent = null
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) => {
+ const active = activeWorkspaceTab(state)
+ if (active?.kind === 'chat') return state
+ const lastChat = [...state.tabs].reverse().find(tab => tab.kind === 'chat')
+ return lastChat
+ ? { ...state, activeTabId: lastChat.id }
+ : newChatTab(state, nextWorkspaceTabId(), null)
+ })
+ } else if (item === DESKTOP_ROUTES.apps) {
+ showAppsPicker()
+ } else if (item === DESKTOP_ROUTES.files) {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) => openFilesTab(state, { id: nextWorkspaceTabId() }))
+ } else {
+ const section = settingsSectionForRoute(item)
+ if (section) {
+ if (section === 'agents') controller.selectedAgent = null
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) =>
+ openSettingsTab(state, { id: nextWorkspaceTabId(), section })
+ )
+ }
+ }
+ forceControllerRender()
})
+ const handleSelectChatAgent = vi.fn(
+ (agentName: string, options: { chatId?: string; keepNavItem?: boolean } = {}) => {
+ controller.selectedAgent = agentName
+ controller.activeChatId = options.chatId ?? null
+ if (!options.keepNavItem) {
+ clearAppsPicker()
+ setWorkspaceTabs((state: WorkspaceState) => {
+ const chatId = options.chatId ?? null
+ return chatId
+ ? openChatTab(state, { id: nextWorkspaceTabId(), agentRef: agentName, chatId })
+ : newChatTab(state, nextWorkspaceTabId(), agentName)
+ })
+ }
+ forceControllerRender()
+ }
+ )
controller = {
booting: false,
initialExperienceLoading: true,
@@ -184,6 +276,14 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
navItem: DESKTOP_ROUTES.chat,
selectedAgent: null,
selectedAgentRoute: null,
+ workspaceTabs: createWorkspaceTabsState('chat-tab-1'),
+ setWorkspaceTabs,
+ activeWorkspaceTab: undefined,
+ nextWorkspaceTabId,
+ appsPickerActive: false,
+ showAppsPicker,
+ clearAppsPicker,
+ activateWorkspaceChatTab: noop,
activeChatId: null,
chatList: [],
latestChatSessions: [],
@@ -210,7 +310,7 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
authTransitioning: false,
handleEnsureTeamContext: ensureTeamContext,
getCurrentTeamId: vi.fn(() => liveTeamId),
- handleSelectChatAgent: vi.fn(),
+ handleSelectChatAgent,
handleNavSelect,
handleLogout: vi.fn(),
pushToast: vi.fn(),
@@ -226,6 +326,24 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
setDesktopEnvironmentSetupComplete: noop,
...overrides,
} as unknown as AppController
+ // `navItem` is derived from the store; translate a starting-route override into
+ // the store state that derives to it.
+ if (overrides.navItem) {
+ const route = overrides.navItem
+ if (route === DESKTOP_ROUTES.apps) {
+ controller.appsPickerActive = true
+ } else if (route === DESKTOP_ROUTES.files) {
+ controller.workspaceTabs = openFilesTab(controller.workspaceTabs, { id: 'seed-files' })
+ } else if (route !== DESKTOP_ROUTES.chat) {
+ const section = settingsSectionForRoute(route)
+ if (section) {
+ controller.workspaceTabs = openSettingsTab(controller.workspaceTabs, {
+ id: `seed-${section}`,
+ section,
+ })
+ }
+ }
+ }
return controller
}
@@ -256,7 +374,7 @@ describe('App deep-link orchestration', () => {
emitDeepLink = null
emitCommand = null
currentController = makeController()
- vi.mocked(useAppController).mockImplementation(() => currentController)
+ vi.mocked(useAppController).mockImplementation(() => useReactiveController(currentController))
Object.defineProperty(window, 'clerum', {
configurable: true,
@@ -583,7 +701,12 @@ describe('App deep-link orchestration', () => {
act(() => commandPaletteHarness.props?.onExecute('sidebar.toggle'))
expect(sidebarHarness.props?.toggleRequestId).toBe(1)
- currentController.navItem = DESKTOP_ROUTES.apps
+ // `navItem` is derived from the store; the instance-less Apps picker residual
+ // puts the shell on the Apps route so the contextual app commands apply.
+ act(() => {
+ currentController.appsPickerActive = true
+ forceControllerRender()
+ })
act(() => emitCommand?.('commands.open'))
act(() => {
sandboxUiPageHarness.props?.onEmbeddedAppOpening?.({
@@ -732,7 +855,9 @@ describe('App deep-link orchestration', () => {
await reportShortcutOpenResult()
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
- expect(currentController.handleNavSelect).toHaveBeenCalledWith(DESKTOP_ROUTES.apps)
+ // The launch drives the store (an app tab), so `navItem` derives to the Apps
+ // route — the observable, not the retired `handleNavSelect(apps)` call.
+ expect(currentController.navItem).toBe(DESKTOP_ROUTES.apps)
})
it('acknowledges an authenticated app link when confirmation is cancelled', async () => {
@@ -919,7 +1044,9 @@ describe('App deep-link orchestration', () => {
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(acknowledgeDeepLink).toHaveBeenCalledTimes(1)
- expect(currentController.handleNavSelect).toHaveBeenCalledTimes(1)
+ // Launched exactly once — the store put the shell on the Apps route (the
+ // observable that replaced the retired single `handleNavSelect(apps)` call).
+ expect(currentController.navItem).toBe(DESKTOP_ROUTES.apps)
})
it('never presents a user A link after user B becomes authenticated', async () => {
@@ -1449,7 +1576,9 @@ describe('App deep-link orchestration', () => {
expect(confirmDialogHarness.props?.title).toBe('App link could not be opened')
expect(liveTeamId).toBe('team-c')
expect(ensureTeamContext).toHaveBeenCalledTimes(1)
- expect(currentController.handleNavSelect).toHaveBeenCalledTimes(1)
+ // The launch put the shell on the Apps route via the store (observable that
+ // replaced the retired single `handleNavSelect(apps)` call).
+ expect(currentController.navItem).toBe(DESKTOP_ROUTES.apps)
expect(sandboxUiPageHarness.props?.shortcutOpenRequestId).toBe(1)
expect(acknowledgeDeepLink).not.toHaveBeenCalled()
@@ -1514,7 +1643,9 @@ describe('App deep-link orchestration', () => {
await waitFor(() => expect(acknowledgeDeepLink).toHaveBeenCalledWith(1))
expect(acknowledgeDeepLink).toHaveBeenCalledTimes(1)
- expect(currentController.handleNavSelect).toHaveBeenCalledTimes(1)
+ // Launched exactly once onto the Apps route via the store (observable that
+ // replaced the retired single `handleNavSelect(apps)` call).
+ expect(currentController.navItem).toBe(DESKTOP_ROUTES.apps)
expect(liveTeamId).toBe('team-b')
})
diff --git a/desktop-app/ui/src/components/ChatSwitcher/ChatSwitcher.test.tsx b/desktop-app/ui/src/components/ChatSwitcher/ChatSwitcher.test.tsx
index 1ef3b4a4e..54f5a61d3 100644
--- a/desktop-app/ui/src/components/ChatSwitcher/ChatSwitcher.test.tsx
+++ b/desktop-app/ui/src/components/ChatSwitcher/ChatSwitcher.test.tsx
@@ -4,23 +4,20 @@ import { makeTaskKey } from '@contexts/AgentTaskTrackerContext/types'
import { ChatListProvider } from '@contexts/ChatListContext'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { createSessionFsmStore, projectSessionState } from '@hooks/domain/sessionFsm'
-import {
- addBlankChatViewTab,
- createChatViewTabsState,
- openPersistedChatViewTab,
-} from '@lib/chatViewTabs'
+import { createWorkspaceTabsState, newChatTab, openChatTab } from '@lib/workspaceTabs'
import { ChatSwitcher } from '.'
afterEach(cleanup)
-// Derive the tab list from the real chatViewTabs producers instead of hand-writing
-// ChatViewTab objects — if the tab shape changes, this fixture stops compiling
-// against the real form (T1). Two persisted chats (chat-1/chat-2, agent 'alpha')
-// plus a trailing blank tab. Ids resolve to 'one' (the seed blank reused for the
-// first persisted view), 'two' (view id), and 'blank', matching the assertions.
-const tabs = addBlankChatViewTab(
- openPersistedChatViewTab(
- openPersistedChatViewTab(createChatViewTabsState('one', 'alpha'), {
+// Derive the tab list from the real universal-store producers instead of
+// hand-writing WorkspaceTab objects — if the tab shape changes, this fixture
+// stops compiling against the real form (T1). Two persisted chats
+// (chat-1/chat-2, agent 'alpha') plus a trailing blank tab. Ids resolve to 'one'
+// (the seed blank reused for the first persisted view), 'two' (view id), and
+// 'blank', matching the assertions.
+const tabs = newChatTab(
+ openChatTab(
+ openChatTab(createWorkspaceTabsState('one', 'alpha'), {
id: 'chat-1-tab',
agentRef: 'alpha',
chatId: 'chat-1',
diff --git a/desktop-app/ui/src/components/ChatSwitcher/index.tsx b/desktop-app/ui/src/components/ChatSwitcher/index.tsx
index 37d8daf67..25d72a78d 100644
--- a/desktop-app/ui/src/components/ChatSwitcher/index.tsx
+++ b/desktop-app/ui/src/components/ChatSwitcher/index.tsx
@@ -5,15 +5,14 @@ import { ChatListContext } from '@contexts/ChatListContext'
import { Button } from '@components/Common'
import { ChatStateBadge } from '@components/agents/ChatStateBadge'
import { useClickOutside } from '@hooks/useClickOutside'
-import { activeChatViewTab } from '@lib/chatViewTabs'
import type { ChatSwitcherProps } from './types'
/**
* Open-chats selector for the chat drawer header. It is a thin, read-only view
- * over the shared global `chatViewTabs`: `tabs` is the list, `activeTabId` the
- * selection, and `onSelect`/`onNewChat` mutate that same state — no second tab
- * store. Per-chat status badges reuse `sessionStateByChatKey` exactly as the
- * full-screen `ChatTabs` strip does.
+ * over the chat sub-slice of the universal store: `tabs` are the chat tabs,
+ * `activeTabId` the drawer's current chat, and `onSelect`/`onNewChat` drive that
+ * same store — no second tab store. Per-chat status badges reuse
+ * `sessionStateByChatKey` exactly as the global `WorkspaceTabStrip` does.
*/
export function ChatSwitcher({
tabs,
@@ -29,16 +28,16 @@ export function ChatSwitcher({
const optionRefs = useRef<Array<HTMLButtonElement | null>>([])
const lastFocusRequestIdRef = useRef(focusRequestId)
- const active = activeChatViewTab({ tabs, activeTabId })
+ const active = tabs.find(tab => tab.id === activeTabId) ?? tabs[0]
const activeIndex = Math.max(
0,
- tabs.findIndex(tab => tab.id === active.id)
+ tabs.findIndex(tab => tab.id === active?.id)
)
const close = useCallback(() => setOpen(false), [])
useClickOutside(rootRef, open, close)
- const badgeFor = (agentRef: string | null, chatId: string | null) =>
+ const badgeFor = (agentRef: string | null | undefined, chatId: string | null | undefined) =>
agentRef && chatId ? chatList?.sessionStateByChatKey[makeTaskKey(agentRef, chatId)] : undefined
useEffect(() => {
@@ -99,10 +98,10 @@ export function ChatSwitcher({
>
<span className="chat-switcher__trigger-main">
<ChatStateBadge
- sessionState={badgeFor(active.agentRef, active.chatId)}
+ sessionState={badgeFor(active?.chat?.agentRef, active?.chat?.chatId)}
unreadTerminal={false}
/>
- <span className="chat-switcher__label">{active.title}</span>
+ <span className="chat-switcher__label">{active?.title ?? 'New chat'}</span>
</span>
<span aria-hidden="true" className="chat-switcher__chevron">
▾
@@ -129,7 +128,7 @@ export function ChatSwitcher({
variant="ghost"
>
<ChatStateBadge
- sessionState={badgeFor(tab.agentRef, tab.chatId)}
+ sessionState={badgeFor(tab.chat?.agentRef, tab.chat?.chatId)}
unreadTerminal={false}
/>
<span className="chat-switcher__label">{tab.title}</span>
diff --git a/desktop-app/ui/src/components/ChatSwitcher/types.ts b/desktop-app/ui/src/components/ChatSwitcher/types.ts
index 8d913586b..510be63e3 100644
--- a/desktop-app/ui/src/components/ChatSwitcher/types.ts
+++ b/desktop-app/ui/src/components/ChatSwitcher/types.ts
@@ -1,13 +1,19 @@
-import type { ChatViewTab } from '@lib/chatViewTabs.types'
+import type { WorkspaceTab } from '@lib/workspaceTabs.types'
export type ChatSwitcherProps = {
- tabs: ChatViewTab[]
- activeTabId: string
+ /** Chat sub-slice of the universal store (only `kind: 'chat'` tabs). */
+ tabs: WorkspaceTab[]
+ /**
+ * The chat tab shown in the drawer — the controller's (selectedAgent,
+ * activeChatId), not the store's active tab (which is the app tab while the
+ * drawer is open). `null` when the drawer has no chat yet.
+ */
+ activeTabId: string | null
onSelect: (id: string) => void
onNewChat: () => void
/**
* Incremented by the `chat.switcher` shortcut to open and focus the dropdown.
- * A thin view over the shared `chatViewTabs` — it owns no tab state of its own.
+ * A thin view over the shared universal store — it owns no tab state of its own.
*/
focusRequestId?: number
}
diff --git a/desktop-app/ui/src/components/ChatTabs/ChatTabs.surfaceAssociation.test.tsx b/desktop-app/ui/src/components/ChatTabs/ChatTabs.surfaceAssociation.test.tsx
deleted file mode 100644
index 33b2ccd0c..000000000
--- a/desktop-app/ui/src/components/ChatTabs/ChatTabs.surfaceAssociation.test.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-// @vitest-environment jsdom
-import { afterEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, render, screen } from '@testing-library/react'
-import { ChatTabs } from '.'
-
-afterEach(cleanup)
-
-describe('ChatTabs selected surface association', () => {
- it('associates the active tab control with its owned chat surface', () => {
- render(
- <ChatTabs
- activeTabId="one"
- onClose={vi.fn()}
- onSelect={vi.fn()}
- {...({ panelId: 'current-chat-surface' } as Record<string, string>)}
- tabs={[
- { id: 'one', agentRef: 'alpha', chatId: 'chat-1', title: 'First chat' },
- {
- id: 'two',
- agentRef: 'alpha',
- chatId: 'chat-2',
- title: 'A second conversation with a long title that must remain usable',
- },
- ]}
- />
- )
-
- expect(screen.getByRole('button', { name: 'First chat' }).getAttribute('aria-controls')).toBe(
- 'current-chat-surface'
- )
- expect(
- screen
- .getByRole('button', {
- name: 'A second conversation with a long title that must remain usable',
- })
- .getAttribute('aria-controls')
- ).toBeNull()
- })
-})
diff --git a/desktop-app/ui/src/components/ChatTabs/types.ts b/desktop-app/ui/src/components/ChatTabs/types.ts
deleted file mode 100644
index 39acf8ea7..000000000
--- a/desktop-app/ui/src/components/ChatTabs/types.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import type { ChatViewTab } from '@lib/chatViewTabs.types'
-
-export type ChatTabsProps = {
- tabs: ChatViewTab[]
- activeTabId: string
- onSelect: (id: string) => void
- onClose: (id: string) => void
- panelId?: string
-}
diff --git a/desktop-app/ui/src/components/ChatViewWorkspace/ChatViewWorkspace.test.tsx b/desktop-app/ui/src/components/ChatViewWorkspace/ChatViewWorkspace.test.tsx
index 06effbaa3..6f488bac3 100644
--- a/desktop-app/ui/src/components/ChatViewWorkspace/ChatViewWorkspace.test.tsx
+++ b/desktop-app/ui/src/components/ChatViewWorkspace/ChatViewWorkspace.test.tsx
@@ -1,20 +1,14 @@
// @vitest-environment jsdom
import type { ReactNode } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { ChatViewWorkspace } from '.'
-const tabs = [
- { id: 'one', agentRef: 'alpha', chatId: 'chat-1', title: 'First chat' },
- {
- id: 'two',
- agentRef: 'alpha',
- chatId: 'chat-2',
- title: 'A second conversation with a long title that must remain usable in narrow windows',
- },
-]
+// The workspace tab strip is now global (`WorkspaceTabStrip`, tested in its own
+// suite); `ChatViewWorkspace` owns only the selected chat surface — the
+// local-search slot and the active conversation.
beforeEach(() => {
const style = document.createElement('style')
@@ -34,37 +28,27 @@ afterEach(() => {
function renderWorkspace(contentLabel: string, localSearch: ReactNode = null) {
return render(
- <ChatViewWorkspace
- activeTabId="one"
- localSearch={localSearch}
- onClose={vi.fn()}
- onSelect={vi.fn()}
- tabs={tabs}
- >
+ <ChatViewWorkspace localSearch={localSearch} surfaceId="chat-view-panel">
<div data-testid="chat-state">{contentLabel}</div>
</ChatViewWorkspace>
)
}
describe('ChatViewWorkspace', () => {
- it('owns the active tab, local search, and current chat as one selected surface', () => {
- const { container } = renderWorkspace('active chat', <div role="search">Current chat find</div>)
+ it('owns local search and the current chat as one selected surface', () => {
+ renderWorkspace('active chat', <div role="search">Current chat find</div>)
const surface = screen.getByRole('region', { name: 'Current chat' })
- const active = screen.getByRole('button', { name: 'First chat' })
- const scroller = container.querySelector('.chat-view-tabs__scroller') as HTMLElement
- expect(active.getAttribute('aria-controls')).toBe(surface.id)
+ expect(surface.id).toBe('chat-view-panel')
expect(surface.getAttribute('data-selected-surface')).toBe('chat')
expect(surface.contains(screen.getByRole('search'))).toBe(true)
expect(surface.contains(screen.getByTestId('chat-state'))).toBe(true)
- expect(getComputedStyle(scroller).overflowX).toBe('auto')
expect(getComputedStyle(surface).borderTopStyle).toBe('solid')
expect(getComputedStyle(surface).borderTopWidth).toBe('0px')
expect(getComputedStyle(surface).borderLeftStyle).toBe('solid')
expect(getComputedStyle(surface).borderRightStyle).toBe('solid')
expect(getComputedStyle(surface).borderBottomStyle).toBe('solid')
expect(getComputedStyle(surface).paddingLeft).toBe('var(--space-3)')
- expect(container.querySelector('.chat-view-tab.is-active')).toBeTruthy()
})
it.each(['loading chat', 'blank chat', 'active chat'])(
@@ -76,17 +60,14 @@ describe('ChatViewWorkspace', () => {
}
)
- it('keeps tab overflow separate from a full-width surface at narrow widths', () => {
+ it('keeps a full-width surface at narrow widths', () => {
const { container } = renderWorkspace('narrow chat')
const workspace = container.querySelector('.chat-view-workspace') as HTMLElement
- const scroller = container.querySelector('.chat-view-tabs__scroller') as HTMLElement
const surface = screen.getByRole('region', { name: 'Current chat' })
workspace.style.width = '320px'
expect(getComputedStyle(workspace).display).toBe('flex')
- expect(getComputedStyle(scroller).overflowX).toBe('auto')
expect(getComputedStyle(surface).width).toBe('100%')
- expect(screen.getByText(/A second conversation/)).toBeTruthy()
- expect(screen.getByRole('button', { name: /Close A second conversation/ })).toBeTruthy()
+ expect(screen.getByText('narrow chat')).toBeTruthy()
})
})
diff --git a/desktop-app/ui/src/components/ChatViewWorkspace/index.tsx b/desktop-app/ui/src/components/ChatViewWorkspace/index.tsx
index 59d787f9c..e5d14180c 100644
--- a/desktop-app/ui/src/components/ChatViewWorkspace/index.tsx
+++ b/desktop-app/ui/src/components/ChatViewWorkspace/index.tsx
@@ -1,24 +1,18 @@
-import { ChatTabs } from '../ChatTabs'
import type { ChatViewWorkspaceProps } from './types'
+/**
+ * Chat surface wrapper for the full-screen chat route. The workspace tab strip
+ * is now global (mini-spec 03 §3, `WorkspaceTabStrip` rendered above the seam in
+ * `App.tsx`), so this owns only the selected chat surface — the local-search
+ * slot and the active conversation.
+ */
export function ChatViewWorkspace({
- activeTabId,
children,
localSearch,
- onClose,
- onSelect,
surfaceId = 'current-chat-surface',
- tabs,
}: ChatViewWorkspaceProps) {
return (
- <section className="chat-view-workspace" data-active-chat-tab={activeTabId}>
- <ChatTabs
- activeTabId={activeTabId}
- onClose={onClose}
- onSelect={onSelect}
- panelId={surfaceId}
- tabs={tabs}
- />
+ <section className="chat-view-workspace">
<section
aria-label="Current chat"
className="chat-view-surface"
diff --git a/desktop-app/ui/src/components/ChatViewWorkspace/types.ts b/desktop-app/ui/src/components/ChatViewWorkspace/types.ts
index de2ad1e66..4e974f7c9 100644
--- a/desktop-app/ui/src/components/ChatViewWorkspace/types.ts
+++ b/desktop-app/ui/src/components/ChatViewWorkspace/types.ts
@@ -1,7 +1,6 @@
import type { ReactNode } from 'react'
-import type { ChatTabsProps } from '../ChatTabs/types'
-export type ChatViewWorkspaceProps = ChatTabsProps & {
+export type ChatViewWorkspaceProps = {
children: ReactNode
localSearch?: ReactNode
surfaceId?: string
diff --git a/desktop-app/ui/src/components/ChatTabs/ChatTabs.test.tsx b/desktop-app/ui/src/components/WorkspaceTabStrip/WorkspaceTabStrip.test.tsx
similarity index 50%
rename from desktop-app/ui/src/components/ChatTabs/ChatTabs.test.tsx
rename to desktop-app/ui/src/components/WorkspaceTabStrip/WorkspaceTabStrip.test.tsx
index 1cda8a8c6..095fcad12 100644
--- a/desktop-app/ui/src/components/ChatTabs/ChatTabs.test.tsx
+++ b/desktop-app/ui/src/components/WorkspaceTabStrip/WorkspaceTabStrip.test.tsx
@@ -6,27 +6,46 @@ import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { createSessionFsmStore, projectSessionState } from '@hooks/domain/sessionFsm'
-import { ChatTabs } from '.'
+import {
+ createWorkspaceTabsState,
+ newChatTab,
+ openAppTab,
+ openChatTab,
+ openSettingsTab,
+} from '@lib/workspaceTabs'
+import { WorkspaceTabStrip } from '.'
afterEach(cleanup)
-describe('ChatTabs', () => {
- it('renders the in-memory tab order and exposes non-destructive view actions', () => {
+// Fixtures are derived from the real universal-store producers, never hand-built
+// WorkspaceTab objects — if the store's tab shape changes, these stop compiling
+// against the real form (T1). `openChatTab` collapses the first persisted chat
+// into the seed blank tab, so the ids resolve deterministically.
+const twoChatTabs = newChatTab(
+ openChatTab(createWorkspaceTabsState('one', 'alpha'), {
+ id: 'one-persisted',
+ agentRef: 'alpha',
+ chatId: 'chat-1',
+ title: 'First chat',
+ }),
+ 'two',
+ 'alpha'
+).tabs
+
+describe('WorkspaceTabStrip', () => {
+ it('renders the tab order and exposes non-destructive view actions', () => {
const onSelect = vi.fn()
const onClose = vi.fn()
render(
- <ChatTabs
- tabs={[
- { id: 'one', agentRef: 'alpha', chatId: 'chat-1', title: 'First chat' },
- { id: 'two', agentRef: 'alpha', chatId: null, title: 'New chat' },
- ]}
+ <WorkspaceTabStrip
+ tabs={twoChatTabs}
activeTabId="one"
onSelect={onSelect}
onClose={onClose}
/>
)
- expect(screen.getByRole('toolbar', { name: 'Chat tabs' })).toBeTruthy()
+ expect(screen.getByRole('toolbar', { name: 'Workspace tabs' })).toBeTruthy()
expect(screen.getByRole('button', { name: 'First chat' }).getAttribute('aria-pressed')).toBe(
'true'
)
@@ -38,13 +57,14 @@ describe('ChatTabs', () => {
it('keeps long tab labels left-aligned, truncatable, and separate from close controls', () => {
const longTitle = 'A very long conversation title that must not overlap its close control'
+ const longTabs = openChatTab(createWorkspaceTabsState('one', 'alpha'), {
+ id: 'one-persisted',
+ agentRef: 'alpha',
+ chatId: 'chat-1',
+ title: longTitle,
+ }).tabs
const { container } = render(
- <ChatTabs
- tabs={[{ id: 'one', agentRef: 'alpha', chatId: 'chat-1', title: longTitle }]}
- activeTabId="one"
- onSelect={vi.fn()}
- onClose={vi.fn()}
- />
+ <WorkspaceTabStrip tabs={longTabs} activeTabId="one" onSelect={vi.fn()} onClose={vi.fn()} />
)
const select = screen.getByRole('button', { name: longTitle })
@@ -64,10 +84,7 @@ describe('ChatTabs', () => {
expect(styles).toMatch(/\.chat-view-tab\s*\{[^}]*flex:\s*1 1 var\(--chat-tab-max\);/s)
expect(styles).toMatch(/\.chat-view-tab\s*\{[^}]*max-width:\s*var\(--chat-tab-max\);/s)
expect(styles).toMatch(/\.chat-view-tab\s*\{[^}]*min-width:\s*var\(--chat-tab-min\);/s)
- // The active tab shrinks slower than the others so it stays legible when crowded.
expect(styles).toMatch(/\.chat-view-tab\.is-active\s*\{[^}]*flex-shrink:\s*0\.4;/s)
- // The bottom shelf lives on the non-scrolling container so it survives horizontal
- // scroll of the overflowing tabs (a shelf on the list would slide away).
expect(styles).toMatch(/\.chat-view-tabs::after\s*\{[^}]*z-index:\s*-1;/s)
expect(styles).toMatch(
/\.chat-view-tab:not\(\.is-active\)\s*\{[^}]*border-bottom:\s*1px solid var\(--chat-view-selected-border\);/s
@@ -76,7 +93,44 @@ describe('ChatTabs', () => {
expect(styles).toMatch(/\.chat-view-tab__label\s*\{[^}]*text-overflow:\s*ellipsis;/s)
})
- it('shows existing running and approval indicators before their tab names', () => {
+ it('associates the active tab control with its owned surface, and only that one', () => {
+ const tabs = openChatTab(
+ openChatTab(createWorkspaceTabsState('one', 'alpha'), {
+ id: 'one-persisted',
+ agentRef: 'alpha',
+ chatId: 'chat-1',
+ title: 'First chat',
+ }),
+ {
+ id: 'two',
+ agentRef: 'alpha',
+ chatId: 'chat-2',
+ title: 'A second conversation with a long title that must remain usable',
+ }
+ ).tabs
+ render(
+ <WorkspaceTabStrip
+ activeTabId="one"
+ onClose={vi.fn()}
+ onSelect={vi.fn()}
+ panelId="chat-view-panel"
+ tabs={tabs}
+ />
+ )
+
+ expect(screen.getByRole('button', { name: 'First chat' }).getAttribute('aria-controls')).toBe(
+ 'chat-view-panel'
+ )
+ expect(
+ screen
+ .getByRole('button', {
+ name: 'A second conversation with a long title that must remain usable',
+ })
+ .getAttribute('aria-controls')
+ ).toBeNull()
+ })
+
+ it('shows running and approval indicators before their chat tab names', () => {
const runningKey = makeTaskKey('alpha', 'chat-running')
const approvalKey = makeTaskKey('beta', 'chat-approval')
const fsm = createSessionFsmStore()
@@ -93,6 +147,20 @@ describe('ChatTabs', () => {
Object.entries(fsm.getSnapshot()).map(([key, state]) => [key, projectSessionState(state)])
)
+ const tabs = newChatTab(
+ openChatTab(
+ openChatTab(createWorkspaceTabsState('seed', 'alpha'), {
+ id: 'running',
+ agentRef: 'alpha',
+ chatId: 'chat-running',
+ title: 'Running chat',
+ }),
+ { id: 'approval', agentRef: 'beta', chatId: 'chat-approval', title: 'Approval chat' }
+ ),
+ 'blank',
+ 'alpha'
+ ).tabs
+
render(
<ChatListProvider
value={{
@@ -105,26 +173,7 @@ describe('ChatTabs', () => {
sessionStateByChatKey,
}}
>
- <ChatTabs
- tabs={[
- {
- id: 'running',
- agentRef: 'alpha',
- chatId: 'chat-running',
- title: 'Running chat',
- },
- {
- id: 'approval',
- agentRef: 'beta',
- chatId: 'chat-approval',
- title: 'Approval chat',
- },
- { id: 'blank', agentRef: 'alpha', chatId: null, title: 'New chat' },
- ]}
- activeTabId="running"
- onSelect={vi.fn()}
- onClose={vi.fn()}
- />
+ <WorkspaceTabStrip tabs={tabs} activeTabId="seed" onSelect={vi.fn()} onClose={vi.fn()} />
</ChatListProvider>
)
@@ -139,6 +188,54 @@ describe('ChatTabs', () => {
)
expect(running.nextElementSibling).toBe(runningLabel)
expect(awaitingApproval.nextElementSibling).toBe(approvalLabel)
+ // The blank chat tab carries no live badge — only the two running/approval do.
expect(screen.getAllByRole('status')).toHaveLength(2)
})
+
+ it('renders app and settings tabs alongside chats, with badges only on chat tabs', () => {
+ const runningKey = makeTaskKey('alpha', 'chat-1')
+ const fsm = createSessionFsmStore()
+ fsm.dispatch(runningKey, { type: 'SEND_STARTED', taskId: 'task-running' })
+ fsm.dispatch(runningKey, { type: 'TASK_CREATED', taskId: 'task-running' })
+ const sessionStateByChatKey = Object.fromEntries(
+ Object.entries(fsm.getSnapshot()).map(([key, state]) => [key, projectSessionState(state)])
+ )
+
+ // A universal workspace: one running chat, one app, one settings section.
+ const tabs = openSettingsTab(
+ openAppTab(
+ openChatTab(createWorkspaceTabsState('chat', 'alpha'), {
+ id: 'chat',
+ agentRef: 'alpha',
+ chatId: 'chat-1',
+ title: 'Running chat',
+ }),
+ { id: 'app-1', appRef: 'ns/app', title: 'My App' }
+ ),
+ { id: 'settings-1', section: 'settings', title: 'Settings' }
+ ).tabs
+
+ render(
+ <ChatListProvider
+ value={{
+ activeChatId: 'chat-1',
+ chatList: [],
+ chatListLoading: false,
+ latestChatSessions: [],
+ latestChatSessionsLoading: false,
+ sessionStateByChatId: {},
+ sessionStateByChatKey,
+ }}
+ >
+ <WorkspaceTabStrip tabs={tabs} activeTabId="app-1" onSelect={vi.fn()} onClose={vi.fn()} />
+ </ChatListProvider>
+ )
+
+ expect(screen.getByRole('button', { name: 'Running chat' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'My App' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Settings' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'My App' }).getAttribute('aria-pressed')).toBe('true')
+ // Only the chat tab carries a live session badge — app/settings do not.
+ expect(screen.getAllByRole('status')).toHaveLength(1)
+ })
})
diff --git a/desktop-app/ui/src/components/ChatTabs/index.tsx b/desktop-app/ui/src/components/WorkspaceTabStrip/index.tsx
similarity index 62%
rename from desktop-app/ui/src/components/ChatTabs/index.tsx
rename to desktop-app/ui/src/components/WorkspaceTabStrip/index.tsx
index 0ce507c78..847e2c968 100644
--- a/desktop-app/ui/src/components/ChatTabs/index.tsx
+++ b/desktop-app/ui/src/components/WorkspaceTabStrip/index.tsx
@@ -3,20 +3,34 @@ import { makeTaskKey } from '@contexts/AgentTaskTrackerContext/types'
import { ChatListContext } from '@contexts/ChatListContext'
import { Button } from '@components/Common'
import { ChatStateBadge } from '@components/agents/ChatStateBadge'
-import type { ChatTabsProps } from './types'
+import type { WorkspaceTabStripProps } from './types'
-export function ChatTabs({ tabs, activeTabId, onSelect, onClose, panelId }: ChatTabsProps) {
+/**
+ * The single global workspace strip (spec 01 §4.2, mini-spec 03 §3). It renders
+ * every tab in the universal store — chat, app, files, settings — and is the
+ * only tab strip in the app (it absorbs the old chat-only `ChatTabs`). Chat tabs
+ * show their live session badge via `sessionStateByChatKey`, exactly as the
+ * former strip did; non-chat tabs carry no badge. Selecting a tab activates it
+ * (the seam derives the route from the active tab); the close control removes it.
+ */
+export function WorkspaceTabStrip({
+ tabs,
+ activeTabId,
+ onSelect,
+ onClose,
+ panelId,
+}: WorkspaceTabStripProps) {
const chatList = useContext(ChatListContext)
return (
- <div className="chat-view-tabs" role="toolbar" aria-label="Chat tabs">
+ <div className="chat-view-tabs" role="toolbar" aria-label="Workspace tabs">
<div className="chat-view-tabs__scroller">
<div className="chat-view-tabs__list">
{tabs.map(tab => {
const active = tab.id === activeTabId
const sessionState =
- tab.agentRef && tab.chatId
- ? chatList?.sessionStateByChatKey[makeTaskKey(tab.agentRef, tab.chatId)]
+ tab.kind === 'chat' && tab.chat?.agentRef && tab.chat?.chatId
+ ? chatList?.sessionStateByChatKey[makeTaskKey(tab.chat.agentRef, tab.chat.chatId)]
: undefined
return (
<div className={`chat-view-tab${active ? ' is-active' : ''}`} key={tab.id}>
@@ -31,7 +45,9 @@ export function ChatTabs({ tabs, activeTabId, onSelect, onClose, panelId }: Chat
size="sm"
variant="ghost"
>
- <ChatStateBadge sessionState={sessionState} unreadTerminal={false} />
+ {tab.kind === 'chat' && (
+ <ChatStateBadge sessionState={sessionState} unreadTerminal={false} />
+ )}
<span className="chat-view-tab__label">{tab.title}</span>
</Button>
<Button
diff --git a/desktop-app/ui/src/components/WorkspaceTabStrip/types.ts b/desktop-app/ui/src/components/WorkspaceTabStrip/types.ts
new file mode 100644
index 000000000..d59653d70
--- /dev/null
+++ b/desktop-app/ui/src/components/WorkspaceTabStrip/types.ts
@@ -0,0 +1,9 @@
+import type { WorkspaceTab } from '@lib/workspaceTabs.types'
+
+export type WorkspaceTabStripProps = {
+ tabs: WorkspaceTab[]
+ activeTabId: string | null
+ onSelect: (id: string) => void
+ onClose: (id: string) => void
+ panelId?: string
+}
diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.workspaceTabs.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.workspaceTabs.test.tsx
new file mode 100644
index 000000000..898e77220
--- /dev/null
+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.workspaceTabs.test.tsx
@@ -0,0 +1,100 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act, waitFor } from '@testing-library/react'
+import { DESKTOP_ROUTES } from '@constants/navigation'
+import { activeWorkspaceTab } from '@lib/workspaceTabs'
+import {
+ installAppControllerClerum,
+ renderAppController,
+} from '../domain/__tests__/__fixtures__/appControllerHarness'
+import { uninstallMockClerum } from '../domain/__tests__/__fixtures__/mockClerum'
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+/**
+ * Ported-behavior regression pins for the universal-tab-store integration
+ * (mini-spec 03 §2/§4). Both assert the store observable that the port now
+ * carries — the active tab and its agent/chat identity — so they exercise the
+ * seam, not just the pre-existing selectedAgent field.
+ */
+describe('useAppController — universal tab store ports', () => {
+ let unmount: (() => void) | null = null
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ afterEach(() => {
+ unmount?.()
+ unmount = null
+ vi.restoreAllMocks()
+ uninstallMockClerum()
+ })
+
+ // (a) Going to chat auto-selects the last agent, and the active workspace tab
+ // becomes that agent's chat tab (navItem derives to chat in the same commit).
+ it('auto-selects the last agent and activates its chat tab when navigating to chat', async () => {
+ installAppControllerClerum({ agentNames: ['agent-x'] })
+ const app = renderAppController()
+ unmount = app.unmount
+
+ await waitFor(() => expect(app.result.current.isAuthenticated).toBe(true))
+ await waitFor(() => expect(app.result.current.initialExperienceLoading).toBe(false))
+
+ // Leave the chat route so navigating back must auto-select.
+ act(() => {
+ app.result.current.handleNavSelect(DESKTOP_ROUTES.connectors)
+ })
+ expect(app.result.current.navItem).toBe(DESKTOP_ROUTES.connectors)
+ expect(app.result.current.selectedAgent).toBe(null)
+
+ act(() => {
+ app.result.current.handleNavSelect(DESKTOP_ROUTES.chat)
+ })
+
+ // Ported behavior: the last agent is auto-selected...
+ expect(app.result.current.selectedAgent).toBe('agent-x')
+ // ...and the derived route + the active tab reflect it in the same commit.
+ expect(app.result.current.navItem).toBe(DESKTOP_ROUTES.chat)
+ const active = activeWorkspaceTab(app.result.current.workspaceTabs)
+ expect(active?.kind).toBe('chat')
+ expect(active?.chat?.agentRef).toBe('agent-x')
+ })
+
+ // (b) A pending chat selection survives a tab/route change: selecting a chat
+ // with keepNavItem while on the apps route records the pending selection, and
+ // the agent-selection effect replays it (the chat actually loads) without
+ // flipping the active tab away from apps.
+ it('preserves the pending chat selection across a tab change (keepNavItem)', async () => {
+ installAppControllerClerum({ agentNames: ['agent-x'] })
+ const app = renderAppController()
+ unmount = app.unmount
+
+ await waitFor(() => expect(app.result.current.isAuthenticated).toBe(true))
+ await waitFor(() => expect(app.result.current.initialExperienceLoading).toBe(false))
+
+ // Move onto the apps route (its store tab is active; navItem derives to apps).
+ act(() => {
+ app.result.current.handleNavSelect(DESKTOP_ROUTES.apps)
+ })
+ expect(app.result.current.navItem).toBe(DESKTOP_ROUTES.apps)
+
+ // Select a chat in the drawer (keepNavItem): the active tab must NOT change
+ // to a chat tab, but the pending selection must survive and load the chat.
+ act(() => {
+ app.result.current.handleSelectChatAgent('agent-x', {
+ chatId: 'chat-1',
+ title: 'Kept chat',
+ selectLatest: false,
+ keepNavItem: true,
+ })
+ })
+
+ expect(app.result.current.navItem).toBe(DESKTOP_ROUTES.apps)
+ expect(app.result.current.selectedAgent).toBe('agent-x')
+ // The pending selection replayed and the chat loaded — the observable, not a
+ // spinner stuck forever.
+ await waitFor(() => expect(app.result.current.chatMessagesLoading).toBe(false))
+ expect(app.result.current.activeChatId).toBe('chat-1')
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/useNavigationController.ts b/desktop-app/ui/src/hooks/domain/useNavigationController.ts
index 143a73f31..d769adefe 100644
--- a/desktop-app/ui/src/hooks/domain/useNavigationController.ts
+++ b/desktop-app/ui/src/hooks/domain/useNavigationController.ts
@@ -1,33 +1,163 @@
-import { useCallback, useState } from 'react'
+import { useCallback, useMemo, useRef, useState } from 'react'
import { AGENT_WORKSPACE_ROUTES, DESKTOP_ROUTES } from '../../constants/navigation'
+import {
+ activeWorkspaceTab,
+ createWorkspaceTabsState,
+ newChatTab,
+ openChatTab,
+ openFilesTab,
+ openSettingsTab,
+} from '../../lib/workspaceTabs'
+import type { WorkspaceTabsState } from '../../lib/workspaceTabs.types'
+import { mapKindToRoute, settingsSectionForRoute } from '../../lib/workspaceTabsRoute'
import type { AgentWorkspaceRoute, NavItem } from '../../uiTypes'
+/**
+ * Owner of the universal tab store (mini-spec 03 §3/§4/§6). The store lives here
+ * — upstream of `useAgentChatController`, which reads `navItem` in its effect
+ * deps — so `navItem` is a SAME-COMMIT derived projection of the active tab
+ * (`mapKindToRoute`), never a second writer. Activating a tab flips `navItem` in
+ * the same render as the `activeTabId` change, which preserves the
+ * `handleSelectChatAgent` fast-path (`nav.navItem === chat`) with no
+ * session-blank frame (§4/§9).
+ *
+ * The instance-less Apps picker (Apps route, no app launched) is the one
+ * residual (§ decision B, directive 3): a bounded `navItem === 'sandbox-ui'`
+ * flag with NO store tab and NO fabricated placeholder `appRef`. It is
+ * single-sourced and cleared the instant any tab is (re)activated, so a derived
+ * `navItem` and the residual can never both be live in one commit.
+ */
export function useNavigationController() {
- const [navItem, setNavItem] = useState<NavItem>(DESKTOP_ROUTES.chat)
+ const [workspaceTabs, setWorkspaceTabs] = useState<WorkspaceTabsState>(() =>
+ createWorkspaceTabsState('chat-tab-1')
+ )
+ // Residual: the Apps route shown with no launched app (the picker). Launching
+ // an app creates a store app tab and clears this.
+ const [appsPickerActive, setAppsPickerActive] = useState(false)
const [selectedAgent, setSelectedAgent] = useState<string | null>(null)
const [selectedAgentRoute, setSelectedAgentRoute] = useState<AgentWorkspaceRoute>(
AGENT_WORKSPACE_ROUTES.connectors
)
- // Basic nav select — does NOT call cross-domain handlers (no workflow refresh here)
- const handleNavSelect = useCallback((item: NavItem) => {
- setNavItem(item)
- if (item === DESKTOP_ROUTES.agents || item === DESKTOP_ROUTES.chat) {
- setSelectedAgent(null)
- setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)
- }
+ const workspaceTabsRef = useRef(workspaceTabs)
+ workspaceTabsRef.current = workspaceTabs
+ const tabSequenceRef = useRef(2)
+ const nextWorkspaceTabId = useCallback(() => `ws-tab-${tabSequenceRef.current++}`, [])
+
+ const activeTab = useMemo(() => activeWorkspaceTab(workspaceTabs), [workspaceTabs])
+ const navItem: NavItem = appsPickerActive ? DESKTOP_ROUTES.apps : mapKindToRoute(activeTab)
+
+ const clearAppsPicker = useCallback(() => setAppsPickerActive(false), [])
+
+ // Apps route with no launched app → the picker residual. Redundant (and thus
+ // skipped) when an app tab is already active, since that already derives to
+ // the Apps route.
+ const showAppsPicker = useCallback(() => {
+ setAppsPickerActive(activeWorkspaceTab(workspaceTabsRef.current)?.kind !== 'app')
}, [])
+ // Ensure a chat tab is active (navItem → chat this commit) without agent
+ // logic: keep the active chat tab, else focus the last chat tab, else seed a
+ // blank one. Agent selection is layered on by `handleSelectChatAgent`.
+ const focusChatSection = useCallback(() => {
+ setAppsPickerActive(false)
+ setWorkspaceTabs(current => {
+ const active = activeWorkspaceTab(current)
+ if (active?.kind === 'chat') return current
+ const lastChat = [...current.tabs].reverse().find(tab => tab.kind === 'chat')
+ if (lastChat) return { ...current, activeTabId: lastChat.id }
+ return newChatTab(current, nextWorkspaceTabId(), null)
+ })
+ }, [nextWorkspaceTabId])
+
+ /**
+ * Activate a chat tab so `navItem` derives to `chat` in the same commit as the
+ * selection (the replacement for the old `nav.setNavItem(chat)`). Persisted
+ * chats dedupe/focus by `chatId`; a blank selection reuses the active blank
+ * chat or appends one. Used by `handleSelectChatAgent` on its non-`keepNavItem`
+ * paths; the `keepNavItem` (drawer) paths never call it, so the app tab stays
+ * active and the route stays on `apps`.
+ */
+ const activateChatTab = useCallback(
+ (agentRef: string | null, chatId: string | null, title?: string) => {
+ setAppsPickerActive(false)
+ setWorkspaceTabs(current =>
+ chatId
+ ? openChatTab(current, {
+ id: nextWorkspaceTabId(),
+ agentRef,
+ chatId,
+ ...(title ? { title } : {}),
+ })
+ : newChatTab(current, nextWorkspaceTabId(), agentRef)
+ )
+ },
+ [nextWorkspaceTabId]
+ )
+
+ const openSettingsSection = useCallback(
+ (section: Parameters<typeof openSettingsTab>[1]['section']) => {
+ setAppsPickerActive(false)
+ setWorkspaceTabs(current => openSettingsTab(current, { id: nextWorkspaceTabId(), section }))
+ },
+ [nextWorkspaceTabId]
+ )
+
+ const openFilesSection = useCallback(() => {
+ setAppsPickerActive(false)
+ setWorkspaceTabs(current => openFilesTab(current, { id: nextWorkspaceTabId() }))
+ }, [nextWorkspaceTabId])
+
+ // Base section navigation: every legacy `handleNavSelect(route)` call-site
+ // routes here and becomes an open/focus tab action (the single writer). For
+ // `chat`/`agents` it also clears `selectedAgent` exactly as before.
+ const handleNavSelect = useCallback(
+ (item: NavItem) => {
+ if (item === DESKTOP_ROUTES.chat) {
+ setSelectedAgent(null)
+ setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)
+ focusChatSection()
+ return
+ }
+ if (item === DESKTOP_ROUTES.apps) {
+ showAppsPicker()
+ return
+ }
+ if (item === DESKTOP_ROUTES.files) {
+ openFilesSection()
+ return
+ }
+ const section = settingsSectionForRoute(item)
+ if (!section) return
+ if (section === 'agents') {
+ setSelectedAgent(null)
+ setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)
+ }
+ openSettingsSection(section)
+ },
+ [focusChatSection, openFilesSection, openSettingsSection, showAppsPicker]
+ )
+
const handleBackToAgents = useCallback(() => {
setSelectedAgent(null)
setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)
}, [])
return {
+ // Derived route (single-writer projection of the active tab).
navItem,
+ // Universal tab store.
+ workspaceTabs,
+ setWorkspaceTabs,
+ activeTab,
+ nextWorkspaceTabId,
+ appsPickerActive,
+ showAppsPicker,
+ clearAppsPicker,
+ activateChatTab,
+ // Agent/chat selection state (stays here through this slice; §4).
selectedAgent,
selectedAgentRoute,
- setNavItem,
setSelectedAgent,
setSelectedAgentRoute,
handleNavSelect,
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index 4c666e375..20c9b5e7a 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -864,14 +864,16 @@ export function useAppController() {
if (!agentName) return
chat.setPendingChatSelection(agentName, null)
chat.clearActiveChat()
+ // Open/focus the agents tab (single writer). It clears selectedAgent/route,
+ // which the two setters below immediately override in the same batch.
+ nav.handleNavSelect(DESKTOP_ROUTES.agents)
nav.setSelectedAgentRoute(route)
nav.setSelectedAgent(agentName)
- nav.setNavItem(DESKTOP_ROUTES.agents)
},
[
chat.clearActiveChat,
chat.setPendingChatSelection,
- nav.setNavItem,
+ nav.handleNavSelect,
nav.setSelectedAgent,
nav.setSelectedAgentRoute,
]
@@ -926,7 +928,10 @@ export function useAppController() {
// server is the source of truth and hydrates server-only chats itself.
void chat.switchToChat(agentName, targetChatId)
nav.setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)
- nav.setNavItem(DESKTOP_ROUTES.chat)
+ // Activate the chat tab (dedupes/focuses by chatId). We are already on
+ // the chat route, so `navItem` stays `chat` — same-commit derivation, no
+ // blank frame.
+ nav.activateChatTab(agentName, targetChatId, options.title)
return
}
const shouldSelectLatest = targetChatId ? false : options.selectLatest !== false
@@ -947,7 +952,13 @@ export function useAppController() {
}
nav.setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)
nav.setSelectedAgent(agentName)
- if (!options.keepNavItem) nav.setNavItem(DESKTOP_ROUTES.chat)
+ // Non-drawer: activate the chat tab so `navItem` derives to `chat` in the
+ // SAME commit as `setSelectedAgent` — the agent-selection effect replays
+ // into its pending branch. `keepNavItem` (drawer) never touches the active
+ // tab, so the app tab stays active and the route stays on `apps`.
+ if (!options.keepNavItem) {
+ nav.activateChatTab(agentName, targetChatId || null, options.title)
+ }
// Drawer same-agent selection: `setSelectedAgent` above is a no-op (same
// value) and `navItem` is not flipped, so the agent-selection effect will
// not replay to consume the pending selection — load the chat imperatively.
@@ -963,9 +974,9 @@ export function useAppController() {
chat.clearActiveChat,
chat.setPendingChatSelection,
chat.switchToChat,
+ nav.activateChatTab,
nav.navItem,
nav.selectedAgent,
- nav.setNavItem,
nav.setSelectedAgent,
nav.setSelectedAgentRoute,
]
@@ -1041,7 +1052,7 @@ export function useAppController() {
) {
try {
await chat.switchToChat(targetAgent, targetChatId)
- nav.setNavItem(DESKTOP_ROUTES.chat)
+ nav.activateChatTab(targetAgent, targetChatId)
return
} catch {
// Fall through to pending selection so the normal agent load path can retry.
@@ -1050,7 +1061,7 @@ export function useAppController() {
chat.setPendingChatSelection(targetAgent, targetChatId || null)
nav.setSelectedAgent(targetAgent)
- nav.setNavItem(DESKTOP_ROUTES.chat)
+ nav.activateChatTab(targetAgent, targetChatId || null)
} catch (error) {
fullSetStatus(
`Could not open notification: ${error instanceof Error ? error.message : String(error)}`,
@@ -1064,9 +1075,9 @@ export function useAppController() {
ensureTeamContext,
fullSetStatus,
handleSelectChatAgent,
+ nav.activateChatTab,
nav.navItem,
nav.selectedAgent,
- nav.setNavItem,
nav.setSelectedAgent,
]
)
@@ -1079,7 +1090,7 @@ export function useAppController() {
if (!target) return
try {
await ensureTeamContext({ teamId: notification.teamId })
- nav.setNavItem(DESKTOP_ROUTES.plugins)
+ nav.handleNavSelect(DESKTOP_ROUTES.plugins)
const fallbackWorkflow = {
namespace: target.namespace,
@@ -1140,7 +1151,7 @@ export function useAppController() {
)
}
},
- [ensureTeamContext, fullSetStatus, nav.setNavItem, queryClient]
+ [ensureTeamContext, fullSetStatus, nav.handleNavSelect, queryClient]
)
const openSdkNotificationTarget = useCallback(
@@ -1151,7 +1162,7 @@ export function useAppController() {
// SDK notifications are user-addressed and do not carry one canonical
// team. Recipe reads use the current user session and its effective
// direct access instead of inventing a team switch.
- nav.setNavItem(DESKTOP_ROUTES.plugins)
+ nav.handleNavSelect(DESKTOP_ROUTES.plugins)
const fallbackWorkflow = {
namespace: target.recipeNamespace,
@@ -1201,7 +1212,7 @@ export function useAppController() {
)
}
},
- [fullSetStatus, nav.setNavItem, queryClient]
+ [fullSetStatus, nav.handleNavSelect, queryClient]
)
// ─── Cross-domain: handleOpenNotification ───
@@ -1313,6 +1324,16 @@ export function useAppController() {
selectedAgentRoute: nav.selectedAgentRoute,
setSelectedAgent: nav.setSelectedAgent,
handleNavSelect,
+ // Universal tab store (single writer; App composes the strip/reveal/reconcile
+ // over these — `navItem` above is its read-only projection).
+ workspaceTabs: nav.workspaceTabs,
+ setWorkspaceTabs: nav.setWorkspaceTabs,
+ activeWorkspaceTab: nav.activeTab,
+ nextWorkspaceTabId: nav.nextWorkspaceTabId,
+ appsPickerActive: nav.appsPickerActive,
+ showAppsPicker: nav.showAppsPicker,
+ clearAppsPicker: nav.clearAppsPicker,
+ activateWorkspaceChatTab: nav.activateChatTab,
handleOpenAgentWorkspace,
handleSelectChatAgent,
handleEnsureTeamContext: ensureTeamContext,
diff --git a/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts b/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts
deleted file mode 100644
index 6b1b36bf5..000000000
--- a/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts
+++ /dev/null
@@ -1,200 +0,0 @@
-import { describe, expect, it } from 'vitest'
-import fc from 'fast-check'
-import {
- activeChatViewTab,
- addBlankChatViewTab,
- closeChatViewTab,
- createChatViewTabsState,
- cycleChatViewTab,
- focusBlankChatViewTab,
- openPersistedChatViewTab,
- reconcileChatViewTabs,
- selectChatViewTabAt,
- selectLastChatViewTab,
-} from '../chatViewTabs'
-
-function tabs(count: number) {
- let state = createChatViewTabsState('tab-0', 'agent')
- for (let index = 1; index < count; index += 1) {
- state = addBlankChatViewTab(state, `tab-${index}`, 'agent')
- }
- return state
-}
-
-describe('chat view tabs', () => {
- it('creates blank tabs and deduplicates persisted agent/chat pairs', () => {
- let state = createChatViewTabsState('blank', 'alpha')
- state = openPersistedChatViewTab(state, {
- id: 'persisted',
- agentRef: 'alpha',
- chatId: 'chat-1',
- title: 'First',
- })
- expect(state.tabs).toEqual([
- { id: 'blank', agentRef: 'alpha', chatId: 'chat-1', title: 'First' },
- ])
- state = addBlankChatViewTab(state, 'blank-2', 'alpha')
- state = openPersistedChatViewTab(state, {
- id: 'duplicate',
- agentRef: 'alpha',
- chatId: 'chat-1',
- title: 'Renamed',
- })
- expect(state.tabs).toHaveLength(2)
- expect(state.activeTabId).toBe('blank')
- expect(state.tabs[0]?.title).toBe('Renamed')
- })
-
- it('reuses an active blank for agent selection and appends after a persisted chat', () => {
- let state = createChatViewTabsState('blank')
- state = focusBlankChatViewTab(state, 'unused', 'alpha')
- expect(state.tabs).toEqual([
- { id: 'blank', agentRef: 'alpha', chatId: null, title: 'New chat' },
- ])
- state = openPersistedChatViewTab(state, {
- id: 'unused-persisted',
- agentRef: 'alpha',
- chatId: 'chat-1',
- })
- state = focusBlankChatViewTab(state, 'next-blank', 'beta')
- expect(state.tabs.at(-1)).toEqual({
- id: 'next-blank',
- agentRef: 'beta',
- chatId: null,
- title: 'New chat',
- })
- })
-
- it('selects 1..8, maps 9 to last, and leaves missing indexes unchanged', () => {
- const state = tabs(10)
- expect(selectChatViewTabAt(state, 7).activeTabId).toBe('tab-7')
- expect(selectLastChatViewTab(state).activeTabId).toBe('tab-9')
- expect(selectChatViewTabAt(state, 10)).toBe(state)
- })
-
- it('cycles in both directions with wrapping', () => {
- let state = tabs(3)
- expect(cycleChatViewTab(state, 'next').activeTabId).toBe('tab-0')
- state = { ...state, activeTabId: 'tab-0' }
- expect(cycleChatViewTab(state, 'previous').activeTabId).toBe('tab-2')
- })
-
- it('selects the right close neighbor, then left, and keeps one blank fallback', () => {
- let state = { ...tabs(3), activeTabId: 'tab-1' }
- state = closeChatViewTab(state, 'tab-1', 'fallback')
- expect(state.activeTabId).toBe('tab-2')
- state = closeChatViewTab(state, 'tab-2', 'fallback')
- expect(state.activeTabId).toBe('tab-0')
- state = closeChatViewTab(state, 'tab-0', 'fallback')
- expect(state).toEqual(createChatViewTabsState('fallback', 'agent'))
- })
-
- it('preserves ordering, uniqueness, active membership, and idempotent persisted sync', () => {
- fc.assert(
- fc.property(
- fc.integer({ min: 1, max: 30 }),
- fc.integer({ min: 0, max: 29 }),
- (count, raw) => {
- const state = tabs(count)
- const index = raw % count
- const selected = selectChatViewTabAt(state, index)
- const cycled = cycleChatViewTab(cycleChatViewTab(selected, 'next'), 'previous')
- expect(cycled.tabs.map(tab => tab.id)).toEqual(state.tabs.map(tab => tab.id))
- expect(new Set(cycled.tabs.map(tab => tab.id)).size).toBe(cycled.tabs.length)
- expect(cycled.tabs.some(tab => tab.id === cycled.activeTabId)).toBe(true)
-
- const view = { id: 'persisted', agentRef: 'agent', chatId: `chat-${raw}` }
- const once = openPersistedChatViewTab(selected, view)
- const twice = openPersistedChatViewTab(once, view)
- expect(twice).toEqual(once)
- expect(
- twice.tabs.filter(tab => tab.agentRef === view.agentRef && tab.chatId === view.chatId)
- ).toHaveLength(1)
- }
- )
- )
- })
-})
-
-describe('reconcileChatViewTabs (minispec 04 §4 invariant — property-based)', () => {
- // An event is "the vm now displays this chat" (chatId null = a blank new chat).
- const agentArb = fc.constantFrom('alpha', 'beta', 'gamma')
- const chatArb = fc.option(fc.constantFrom('c1', 'c2', 'c3', 'c4'), { nil: null })
- const titleArb = fc.option(fc.constantFrom('T1', 'T2'), { nil: undefined })
- const eventArb = fc.record({ agentRef: agentArb, chatId: chatArb, title: titleArb })
-
- it('the active tab always reflects the displayed chat; no duplicate persisted tabs', () => {
- fc.assert(
- fc.property(fc.array(eventArb, { maxLength: 40 }), events => {
- let state = createChatViewTabsState('seed', 'alpha')
- let counter = 0
- for (const event of events) {
- state = reconcileChatViewTabs(state, event, `gen-${counter++}`)
- const active = activeChatViewTab(state)
- // (1) total order / correct selection: the active tab is the displayed chat.
- expect(active.agentRef).toBe(event.agentRef)
- expect(active.chatId).toBe(event.chatId)
- // (2) no duplicate identifiers among persisted (non-blank) tabs.
- const seen = new Set<string>()
- for (const tab of state.tabs) {
- if (tab.chatId === null) continue
- const key = `${tab.agentRef}::${tab.chatId}`
- expect(seen.has(key)).toBe(false)
- seen.add(key)
- }
- }
- })
- )
- })
-
- it('is idempotent: applying the same event twice equals applying it once (same ref)', () => {
- fc.assert(
- fc.property(fc.array(eventArb, { maxLength: 20 }), eventArb, (prefix, event) => {
- let state = createChatViewTabsState('seed', 'alpha')
- let counter = 0
- for (const e of prefix) state = reconcileChatViewTabs(state, e, `p-${counter++}`)
- const once = reconcileChatViewTabs(state, event, `once`)
- const twice = reconcileChatViewTabs(once, event, `twice`)
- // Second application must be a no-op — same reference (setState bails out).
- expect(twice).toBe(once)
- })
- )
- })
-
- it('never drops a non-displayed persisted tab that was already open', () => {
- fc.assert(
- fc.property(fc.array(eventArb, { maxLength: 30 }), events => {
- let state = createChatViewTabsState('seed', 'alpha')
- let counter = 0
- const everOpened = new Set<string>()
- for (const event of events) {
- state = reconcileChatViewTabs(state, event, `g-${counter++}`)
- if (event.chatId !== null) everOpened.add(`${event.agentRef}::${event.chatId}`)
- // Every persisted chat ever displayed still has exactly one live tab.
- for (const key of everOpened) {
- const [agentRef, chatId] = key.split('::')
- expect(
- state.tabs.filter(t => t.agentRef === agentRef && t.chatId === chatId)
- ).toHaveLength(1)
- }
- }
- })
- )
- })
-
- // R2-L3: the non-empty-tabs invariant is enforced across the module, but the
- // accessors that leaned on it used non-null assertions — a silent `undefined`
- // (activeChatViewTab) or a cryptic `.id of undefined` (selectLastChatViewTab)
- // if a future refactor ever produced an empty list. The named guard makes that
- // a diagnosable failure. (The empty state is unreachable by construction, so
- // it is built directly here to exercise the guard.)
- describe('empty-tabs invariant guard', () => {
- it('activeChatViewTab throws a named invariant error instead of returning undefined', () => {
- expect(() => activeChatViewTab({ tabs: [], activeTabId: 'x' })).toThrow(/invariant/)
- })
-
- it('selectLastChatViewTab throws a named invariant error instead of a cryptic TypeError', () => {
- expect(() => selectLastChatViewTab({ tabs: [], activeTabId: 'x' })).toThrow(/invariant/)
- })
- })
-})
diff --git a/desktop-app/ui/src/lib/chatViewTabs.ts b/desktop-app/ui/src/lib/chatViewTabs.ts
deleted file mode 100644
index 7d4d565c4..000000000
--- a/desktop-app/ui/src/lib/chatViewTabs.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-import type { ChatViewTab, ChatViewTabsState, PersistedChatView } from './chatViewTabs.types'
-
-/**
- * Module invariant: the tab list is never empty — `createChatViewTabsState`
- * seeds one tab and `closeChatViewTab` re-seeds when closing the last one. These
- * accessors turn a would-be silent `undefined` (or a cryptic `.id of undefined`)
- * into a named error if a future refactor ever breaks that invariant, instead of
- * the non-null assertions they replace.
- */
-function firstTab(tabs: ChatViewTab[]): ChatViewTab {
- const tab = tabs[0]
- if (!tab) throw new Error('chatViewTabs invariant violated: tab list must never be empty')
- return tab
-}
-
-function lastTab(tabs: ChatViewTab[]): ChatViewTab {
- const tab = tabs.at(-1)
- if (!tab) throw new Error('chatViewTabs invariant violated: tab list must never be empty')
- return tab
-}
-
-export function createChatViewTabsState(
- id: string,
- agentRef: string | null = null
-): ChatViewTabsState {
- return {
- tabs: [{ id, agentRef, chatId: null, title: 'New chat' }],
- activeTabId: id,
- }
-}
-
-export function activeChatViewTab(state: ChatViewTabsState): ChatViewTab {
- return state.tabs.find(tab => tab.id === state.activeTabId) ?? firstTab(state.tabs)
-}
-
-export function addBlankChatViewTab(
- state: ChatViewTabsState,
- id: string,
- agentRef: string | null
-): ChatViewTabsState {
- return {
- tabs: [...state.tabs, { id, agentRef, chatId: null, title: 'New chat' }],
- activeTabId: id,
- }
-}
-
-export function focusBlankChatViewTab(
- state: ChatViewTabsState,
- id: string,
- agentRef: string
-): ChatViewTabsState {
- const active = activeChatViewTab(state)
- if (active.chatId === null) {
- return {
- tabs: state.tabs.map(tab =>
- tab.id === active.id ? { ...tab, agentRef, title: 'New chat' } : tab
- ),
- activeTabId: active.id,
- }
- }
- return addBlankChatViewTab(state, id, agentRef)
-}
-
-export function openPersistedChatViewTab(
- state: ChatViewTabsState,
- view: PersistedChatView
-): ChatViewTabsState {
- const existing = state.tabs.find(
- tab => tab.agentRef === view.agentRef && tab.chatId === view.chatId
- )
- if (existing) {
- const title = view.title?.trim()
- return {
- tabs: title
- ? state.tabs.map(tab => (tab.id === existing.id ? { ...tab, title } : tab))
- : state.tabs,
- activeTabId: existing.id,
- }
- }
-
- const active = activeChatViewTab(state)
- const next: ChatViewTab = {
- id: active.chatId === null ? active.id : view.id,
- agentRef: view.agentRef,
- chatId: view.chatId,
- title: view.title?.trim() || 'Conversation',
- }
- if (active.chatId === null) {
- return {
- tabs: state.tabs.map(tab => (tab.id === active.id ? next : tab)),
- activeTabId: next.id,
- }
- }
- return { tabs: [...state.tabs, next], activeTabId: next.id }
-}
-
-/**
- * Single reconciler for the invariant `chatViewTabs.activeTabId ≡ the displayed
- * chat` (minispec 04, approach A). `vm.activeChatId` is PRIMARY; the tab state is
- * DERIVED from it. Used by both the full-screen chat route and the app drawer.
- *
- * Hard rules (anti-loop):
- * - Idempotent: when the active tab already reflects `active` (same agent+chat,
- * and the title already matches when one is supplied), it returns the SAME
- * `state` reference so `setChatViewTabs` bails out — no re-render, no ping-pong
- * with the drawer reveal paths (which dedupe by `(agentRef, chatId)` too).
- * - Never spawns a duplicate persisted tab (dedupes by `(agentRef, chatId)`).
- * - Blank branch (`active.chatId === null`): never cascades new blank tabs; it
- * keeps the already-active blank tab, only aligning its agent.
- * - Never drives `switchToChat` — it only derives tab state.
- */
-export function reconcileChatViewTabs(
- state: ChatViewTabsState,
- active: { agentRef: string; chatId: string | null; title?: string } | null,
- newTabId: string
-): ChatViewTabsState {
- if (!active || !active.agentRef) return state
- if (active.chatId === null) {
- const current = activeChatViewTab(state)
- if (current.chatId === null) {
- // Already showing a blank tab — align its agent, never spawn a new one.
- return current.agentRef === active.agentRef
- ? state
- : {
- tabs: state.tabs.map(tab =>
- tab.id === current.id ? { ...tab, agentRef: active.agentRef } : tab
- ),
- activeTabId: current.id,
- }
- }
- return focusBlankChatViewTab(state, newTabId, active.agentRef)
- }
- const existing = state.tabs.find(
- tab => tab.agentRef === active.agentRef && tab.chatId === active.chatId
- )
- const title = active.title?.trim()
- if (existing) {
- const isActive = state.activeTabId === existing.id
- const titleMatches = !title || existing.title === title
- if (isActive && titleMatches) return state
- return {
- tabs:
- title && existing.title !== title
- ? state.tabs.map(tab => (tab.id === existing.id ? { ...tab, title } : tab))
- : state.tabs,
- activeTabId: existing.id,
- }
- }
- return openPersistedChatViewTab(state, {
- id: newTabId,
- agentRef: active.agentRef,
- chatId: active.chatId,
- title: active.title,
- })
-}
-
-export function selectChatViewTab(state: ChatViewTabsState, id: string): ChatViewTabsState {
- return state.tabs.some(tab => tab.id === id) ? { ...state, activeTabId: id } : state
-}
-
-export function selectChatViewTabAt(state: ChatViewTabsState, index: number): ChatViewTabsState {
- const target = state.tabs[index]
- return target ? { ...state, activeTabId: target.id } : state
-}
-
-export function selectLastChatViewTab(state: ChatViewTabsState): ChatViewTabsState {
- return { ...state, activeTabId: lastTab(state.tabs).id }
-}
-
-export function cycleChatViewTab(
- state: ChatViewTabsState,
- direction: 'next' | 'previous'
-): ChatViewTabsState {
- if (state.tabs.length < 2) return state
- const activeIndex = Math.max(
- 0,
- state.tabs.findIndex(tab => tab.id === state.activeTabId)
- )
- const offset = direction === 'next' ? 1 : -1
- const targetIndex = (activeIndex + offset + state.tabs.length) % state.tabs.length
- return { ...state, activeTabId: state.tabs[targetIndex]!.id }
-}
-
-export function closeChatViewTab(
- state: ChatViewTabsState,
- id: string,
- fallbackId: string
-): ChatViewTabsState {
- const closingIndex = state.tabs.findIndex(tab => tab.id === id)
- if (closingIndex < 0) return state
- if (state.tabs.length === 1) {
- return createChatViewTabsState(fallbackId, state.tabs[0]?.agentRef ?? null)
- }
- const tabs = state.tabs.filter(tab => tab.id !== id)
- if (state.activeTabId !== id) return { tabs, activeTabId: state.activeTabId }
- const neighbor = tabs[Math.min(closingIndex, tabs.length - 1)]!
- return { tabs, activeTabId: neighbor.id }
-}
diff --git a/desktop-app/ui/src/lib/chatViewTabs.types.ts b/desktop-app/ui/src/lib/chatViewTabs.types.ts
deleted file mode 100644
index c767c36f8..000000000
--- a/desktop-app/ui/src/lib/chatViewTabs.types.ts
+++ /dev/null
@@ -1,18 +0,0 @@
-export type ChatViewTab = {
- id: string
- agentRef: string | null
- chatId: string | null
- title: string
-}
-
-export type ChatViewTabsState = {
- tabs: ChatViewTab[]
- activeTabId: string
-}
-
-export type PersistedChatView = {
- id: string
- agentRef: string
- chatId: string
- title?: string
-}
diff --git a/desktop-app/ui/src/lib/workspaceTabsRoute.ts b/desktop-app/ui/src/lib/workspaceTabsRoute.ts
new file mode 100644
index 000000000..319cd4274
--- /dev/null
+++ b/desktop-app/ui/src/lib/workspaceTabsRoute.ts
@@ -0,0 +1,53 @@
+import { DESKTOP_ROUTES } from '@constants/navigation'
+import type { NavItem } from '../uiTypes'
+import type { SettingsSection, WorkspaceTab } from './workspaceTabs.types'
+
+/**
+ * Read-only projection of the universal tab store onto the legacy `navItem`
+ * route (spec 01 §4.0/§4.2, mini-spec 03 §6). The store is the single writer;
+ * `navItem` is DERIVED from the active tab so `NavigationContext` consumers
+ * (`HeaderActions`, desktop commands, the render seam) keep reading a route.
+ *
+ * Total: an empty workspace (no active tab) maps to `chat`, the neutral default
+ * for `desktopCommandContext` (§5). The instance-less Apps picker is represented
+ * OUTSIDE this map (a bounded `navItem==='sandbox-ui'` residual owned by the
+ * controller), not as a fabricated placeholder app tab.
+ */
+
+const SETTINGS_SECTION_TO_ROUTE: Record<SettingsSection, NavItem> = {
+ connectors: DESKTOP_ROUTES.connectors,
+ agents: DESKTOP_ROUTES.agents,
+ plugins: DESKTOP_ROUTES.plugins,
+ settings: DESKTOP_ROUTES.settings,
+}
+
+const ROUTE_TO_SETTINGS_SECTION: Partial<Record<NavItem, SettingsSection>> = {
+ [DESKTOP_ROUTES.connectors]: 'connectors',
+ [DESKTOP_ROUTES.agents]: 'agents',
+ [DESKTOP_ROUTES.plugins]: 'plugins',
+ [DESKTOP_ROUTES.settings]: 'settings',
+}
+
+export function mapKindToRoute(tab: WorkspaceTab | undefined): NavItem {
+ if (!tab) return DESKTOP_ROUTES.chat
+ switch (tab.kind) {
+ case 'chat':
+ return DESKTOP_ROUTES.chat
+ case 'app':
+ return DESKTOP_ROUTES.apps
+ case 'files':
+ return DESKTOP_ROUTES.files
+ case 'settings':
+ return SETTINGS_SECTION_TO_ROUTE[tab.settings?.section ?? 'settings']
+ }
+}
+
+/**
+ * Reverse of `mapKindToRoute` for the `settings`-kind routes only. Returns the
+ * `SettingsSection` a sidebar/command navigation to `item` opens, or `null` for
+ * routes that are not settings-kind tabs (`chat`, `files`, `apps`) — those are
+ * handled by their own store actions.
+ */
+export function settingsSectionForRoute(item: NavItem): SettingsSection | null {
+ return ROUTE_TO_SETTINGS_SECTION[item] ?? null
+}
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index ed1f05cd2..3ec74088e 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -16595,6 +16595,18 @@ pre {
width: 100%;
}
+/* Empty-workspace home state (mini-spec 03 §5): shown when the last tab closes. */
+.workspace-home-empty {
+ align-items: center;
+ display: flex;
+ flex: 1 1 0;
+ flex-direction: column;
+ gap: var(--space-3);
+ justify-content: center;
+ padding: var(--space-5);
+ text-align: center;
+}
+
.chat-view-surface {
background: var(--surface-strong);
border-color: var(--chat-view-selected-border);