Skip to content

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

TypeScript

feat(desktop): add keyboard-driven chat tabs and composer focus

Josué993bf46d81d8
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 63752bce6..60f2ab802 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -11,6 +11,7 @@ import {
} from '@contexts/index'
import { AppHeader } from '@components/AppHeader'
import { BootSplash } from '@components/BootSplash'
+import { ChatTabs } from '@components/ChatTabs'
import { Button, ToastStack } from '@components/Common'
import { ConfirmDialog } from '@components/ConfirmDialog'
import { GfsImagePreview } from '@components/GfsImagePreview'
@@ -21,6 +22,19 @@ import { DESKTOP_ROUTES, SIDEBAR_COLLAPSED_KEY } from '@constants/navigation'
import { THEME_STORAGE_KEY } from '@constants/theme'
import { useAgentChatActionsValue } from '@hooks/useAgentChatActionsValue'
import { useAppController } from '@hooks/useAppController'
+import {
+ activeChatViewTab,
+ addBlankChatViewTab,
+ closeChatViewTab,
+ createChatViewTabsState,
+ cycleChatViewTab,
+ focusBlankChatViewTab,
+ openPersistedChatViewTab,
+ selectChatViewTab,
+ selectChatViewTabAt,
+ selectLastChatViewTab,
+} from '@lib/chatViewTabs'
+import type { ChatViewTab } from '@lib/chatViewTabs.types'
import { gfsImagePreviewMimeType } from '@lib/gfsImagePreview'
import {
canProcessSandboxUiDeepLinks,
@@ -63,6 +77,7 @@ import { UnavailablePage } from '@pages/UnavailablePage'
import { WorkflowsPage } from '@pages/WorkflowsPage'
import type { PendingSandboxUiDeepLink, SandboxUiDeepLinkEnvelope } from '@/App.types'
import type { ActiveSandboxUiApp, NavItem, ThemeMode } from '@/uiTypes'
+import { type DesktopCommandId, getDesktopCommand } from '../../src/desktopCommands'
type PendingSandboxUiDeepLinkLaunch = {
linkId: number
@@ -232,6 +247,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)
+ const [composerFocusRequestId, setComposerFocusRequestId] = React.useState(0)
const contentPanelRef = React.useRef<HTMLElement | null>(null)
const activeConversationOriginRef = React.useRef<SandboxUiConversationOrigin | null>(null)
const processingSandboxUiDeepLinkIdRef = React.useRef<number | null>(null)
@@ -241,6 +262,81 @@ 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++}`, [])
+
+ const leaveSandboxForChat = React.useCallback(() => {
+ setActiveSandboxUiApp(null)
+ setSandboxUiConversationOrigin(null)
+ setHeaderShellOverlayOpen(false)
+ setSidebarSettingsMenuOpen(false)
+ }, [])
+
+ const revealChatViewTab = React.useCallback(
+ (tab: ChatViewTab) => {
+ leaveSandboxForChat()
+ if (tab.agentRef) {
+ vm.handleSelectChatAgent(
+ tab.agentRef,
+ tab.chatId
+ ? { chatId: tab.chatId, title: tab.title, selectLatest: false }
+ : { selectLatest: false }
+ )
+ } else {
+ vm.handleNavSelect(DESKTOP_ROUTES.chat)
+ }
+ },
+ [leaveSandboxForChat, vm.handleNavSelect, vm.handleSelectChatAgent]
+ )
+
+ const handleSelectChatViewTab = React.useCallback(
+ (id: string) => {
+ const state = selectChatViewTab(chatViewTabsRef.current, id)
+ if (state === chatViewTabsRef.current) return
+ setChatViewTabs(state)
+ revealChatViewTab(activeChatViewTab(state))
+ },
+ [revealChatViewTab]
+ )
+
+ const handleCloseChatViewTab = React.useCallback(
+ (id: string) => {
+ const current = chatViewTabsRef.current
+ const wasActive = current.activeTabId === id
+ const next = closeChatViewTab(current, id, nextChatTabId())
+ if (next === current) return
+ setChatViewTabs(next)
+ if (wasActive) revealChatViewTab(activeChatViewTab(next))
+ },
+ [nextChatTabId, revealChatViewTab]
+ )
+
+ const handleNewChatViewTab = React.useCallback(() => {
+ const next = addBlankChatViewTab(chatViewTabsRef.current, nextChatTabId(), vm.selectedAgent)
+ setChatViewTabs(next)
+ revealChatViewTab(activeChatViewTab(next))
+ }, [nextChatTabId, revealChatViewTab, vm.selectedAgent])
+
+ const handleSelectChatAgentWithTabs = React.useCallback(
+ (
+ 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)
+ vm.handleSelectChatAgent(agentName, options)
+ },
+ [nextChatTabId, vm.handleSelectChatAgent]
+ )
const bootSplashLoading = vm.booting || vm.initialExperienceLoading
const isAgentChatView =
(vm.navItem === DESKTOP_ROUTES.agents && Boolean(vm.selectedAgent)) ||
@@ -889,34 +985,84 @@ export function App() {
)
React.useEffect(() => {
- const handleNewChatShortcut = (event: KeyboardEvent) => {
- const isNewChatShortcut =
- event.key.toLowerCase() === 'n' &&
- (event.metaKey || event.ctrlKey) &&
- !event.altKey &&
- !event.shiftKey
-
- if (!isNewChatShortcut || event.repeat || event.defaultPrevented) return
-
- event.preventDefault()
- if (activeSandboxUiApp) {
- setActiveSandboxUiApp(null)
- setSandboxUiConversationOrigin(null)
- }
- setHeaderShellOverlayOpen(false)
- setSidebarSettingsMenuOpen(false)
+ if (vm.navItem !== DESKTOP_ROUTES.chat || !vm.selectedAgent) return
+ if (!vm.activeChatId) {
+ setChatViewTabs(state =>
+ focusBlankChatViewTab(state, nextChatTabId(), vm.selectedAgent as string)
+ )
+ return
+ }
+ const conversation =
+ vm.chatList.find(chat => chat.id === vm.activeChatId) ??
+ vm.latestChatSessions.find(
+ chat => chat.agentRef === vm.selectedAgent && chat.id === vm.activeChatId
+ )
+ setChatViewTabs(state =>
+ openPersistedChatViewTab(state, {
+ id: nextChatTabId(),
+ agentRef: vm.selectedAgent as string,
+ chatId: vm.activeChatId as string,
+ title: conversation?.title,
+ })
+ )
+ }, [
+ nextChatTabId,
+ vm.activeChatId,
+ vm.chatList,
+ vm.latestChatSessions,
+ vm.navItem,
+ vm.selectedAgent,
+ ])
- if (vm.selectedAgent) {
- vm.handleSelectChatAgent(vm.selectedAgent, { selectLatest: false })
+ React.useEffect(() => {
+ nextChatTabSequenceRef.current = 2
+ setChatViewTabs(createChatViewTabsState('chat-tab-1'))
+ setComposerFocusRequestId(0)
+ }, [vm.authenticatedPrincipalIdentity])
+
+ React.useEffect(() => {
+ if (!window.clerum.shortcuts) return undefined
+ return window.clerum.shortcuts.onCommand((commandId: DesktopCommandId) => {
+ if (!vm.isAuthenticated || document.querySelector('[role="dialog"][aria-modal="true"]')) {
return
}
-
- vm.handleNavSelect(DESKTOP_ROUTES.chat)
- }
-
- window.addEventListener('keydown', handleNewChatShortcut)
- return () => window.removeEventListener('keydown', handleNewChatShortcut)
- }, [activeSandboxUiApp, vm.handleNavSelect, vm.handleSelectChatAgent, vm.selectedAgent])
+ const command = getDesktopCommand(commandId)
+ const state = chatViewTabsRef.current
+ if (commandId === 'chat.newTab') {
+ handleNewChatViewTab()
+ return
+ }
+ if (commandId === 'chat.closeTab') {
+ handleCloseChatViewTab(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))
+ }
+ return
+ }
+ if (commandId === 'tabs.selectLast') {
+ const next = selectLastChatViewTab(state)
+ setChatViewTabs(next)
+ revealChatViewTab(activeChatViewTab(next))
+ 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))
+ return
+ }
+ if (commandId === 'composer.focus') {
+ revealChatViewTab(activeChatViewTab(state))
+ setComposerFocusRequestId(value => value + 1)
+ }
+ })
+ }, [handleCloseChatViewTab, handleNewChatViewTab, revealChatViewTab, vm.isAuthenticated])
const sandboxUiBoundsRefreshKey = `${sidebarCollapsed ? 'collapsed' : 'expanded'}:${
appNotificationDrawerOpen ? 'notification-drawer-open' : 'notification-drawer-closed'
@@ -1104,7 +1250,7 @@ export function App() {
selectedTeam: vm.selectedTeam,
handleNavSelect: vm.handleNavSelect,
handleOpenAgentWorkspace: vm.handleOpenAgentWorkspace,
- handleSelectChatAgent: vm.handleSelectChatAgent,
+ handleSelectChatAgent: handleSelectChatAgentWithTabs,
handleBackToAgents: vm.handleBackToAgents,
handleOpenContextDetails: vm.handleOpenContextDetails,
handleBackToContexts: vm.handleBackToContexts,
@@ -1119,7 +1265,7 @@ export function App() {
vm.handleOpenAgentWorkspace,
vm.handleOpenContextDetails,
vm.handleOpenTeamDetails,
- vm.handleSelectChatAgent,
+ handleSelectChatAgentWithTabs,
vm.navItem,
vm.selectedAgent,
vm.selectedAgentRoute,
@@ -1221,6 +1367,7 @@ export function App() {
agentError: vm.agentError,
failedAgentSend: vm.failedAgentSend,
activeMessageCount: vm.activeMessages.length,
+ composerFocusRequestId,
}),
[
vm.activeChatId,
@@ -1230,6 +1377,7 @@ export function App() {
vm.agentError,
vm.failedAgentSend,
vm.activeMessages.length,
+ composerFocusRequestId,
]
)
@@ -1407,7 +1555,15 @@ export function App() {
/>
<ToastStack items={vm.toasts} />
{vm.navItem === DESKTOP_ROUTES.chat && (
- <ChatPage scrollContainerRef={contentPanelRef} />
+ <section className="chat-view-workspace" id="chat-view-panel">
+ <ChatTabs
+ tabs={chatViewTabs.tabs}
+ activeTabId={chatViewTabs.activeTabId}
+ onSelect={handleSelectChatViewTab}
+ onClose={handleCloseChatViewTab}
+ />
+ <ChatPage scrollContainerRef={contentPanelRef} />
+ </section>
)}
{vm.navItem === DESKTOP_ROUTES.agents && (
<AgentsPage scrollContainerRef={contentPanelRef} />
diff --git a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
index 64e5e7a61..ed213e933 100644
--- a/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
+++ b/desktop-app/ui/src/__tests__/App.deepLinks.test.tsx
@@ -5,6 +5,7 @@ import { DESKTOP_ROUTES } from '@constants/navigation'
import { useAppController } from '@hooks/useAppController'
import { App } from '@/App'
import type { SandboxUiDeepLinkEnvelope } from '@/App.types'
+import type { DesktopCommandId } from '../../../src/desktopCommands'
const confirmDialogHarness = vi.hoisted(() => ({
rendered: vi.fn(),
@@ -157,6 +158,7 @@ function makeController(overrides: Partial<AppController> = {}): AppController {
describe('App deep-link orchestration', () => {
let currentController: AppController
let emitDeepLink: ((link: SandboxUiDeepLinkEnvelope) => void) | null
+ let emitCommand: ((commandId: DesktopCommandId) => void) | null
const clearPendingDeepLinks = vi.fn().mockResolvedValue(undefined)
const acknowledgeDeepLink = vi.fn().mockResolvedValue(undefined)
const listApps = vi.fn().mockResolvedValue({ apps: [] })
@@ -172,12 +174,19 @@ describe('App deep-link orchestration', () => {
listPendingDeepLinks.mockResolvedValue({ links: [] })
closeSandboxUi.mockResolvedValue(undefined)
emitDeepLink = null
+ emitCommand = null
currentController = makeController()
vi.mocked(useAppController).mockImplementation(() => currentController)
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
+ shortcuts: {
+ onCommand: vi.fn((callback: (commandId: DesktopCommandId) => void) => {
+ emitCommand = callback
+ return vi.fn()
+ }),
+ },
app: {
rendererReady: vi.fn().mockResolvedValue(undefined),
},
@@ -196,6 +205,24 @@ describe('App deep-link orchestration', () => {
})
})
+ it('runs registered new-tab and composer-focus commands through existing chat selection', () => {
+ currentController = makeController({
+ initialExperienceLoading: false,
+ selectedAgent: 'alpha',
+ } as Partial<AppController>)
+ render(<App />)
+
+ act(() => emitCommand?.('chat.newTab'))
+ expect(currentController.handleSelectChatAgent).toHaveBeenCalledWith('alpha', {
+ selectLatest: false,
+ })
+
+ act(() => emitCommand?.('composer.focus'))
+ expect(currentController.handleSelectChatAgent).toHaveBeenLastCalledWith('alpha', {
+ selectLatest: false,
+ })
+ })
+
afterEach(() => {
vi.useRealTimers()
})
diff --git a/desktop-app/ui/src/components/ChatTabs/ChatTabs.test.tsx b/desktop-app/ui/src/components/ChatTabs/ChatTabs.test.tsx
new file mode 100644
index 000000000..69f49d837
--- /dev/null
+++ b/desktop-app/ui/src/components/ChatTabs/ChatTabs.test.tsx
@@ -0,0 +1,33 @@
+// @vitest-environment jsdom
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { ChatTabs } from '.'
+
+afterEach(cleanup)
+
+describe('ChatTabs', () => {
+ it('renders the in-memory 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' },
+ ]}
+ activeTabId="one"
+ onSelect={onSelect}
+ onClose={onClose}
+ />
+ )
+
+ expect(screen.getByRole('toolbar', { name: 'Chat tabs' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'First chat' }).getAttribute('aria-pressed')).toBe(
+ 'true'
+ )
+ fireEvent.click(screen.getByRole('button', { name: 'New chat' }))
+ fireEvent.click(screen.getByRole('button', { name: 'Close First chat' }))
+ expect(onSelect).toHaveBeenCalledWith('two')
+ expect(onClose).toHaveBeenCalledWith('one')
+ })
+})
diff --git a/desktop-app/ui/src/components/ChatTabs/index.tsx b/desktop-app/ui/src/components/ChatTabs/index.tsx
new file mode 100644
index 000000000..e42ca9018
--- /dev/null
+++ b/desktop-app/ui/src/components/ChatTabs/index.tsx
@@ -0,0 +1,38 @@
+import { Button } from '@components/Common'
+import type { ChatTabsProps } from './types'
+
+export function ChatTabs({ tabs, activeTabId, onSelect, onClose }: ChatTabsProps) {
+ return (
+ <div className="chat-view-tabs" role="toolbar" aria-label="Chat tabs">
+ <div className="chat-view-tabs__list">
+ {tabs.map(tab => {
+ const active = tab.id === activeTabId
+ return (
+ <div className={`chat-view-tab${active ? ' is-active' : ''}`} key={tab.id}>
+ <Button
+ aria-pressed={active}
+ className="chat-view-tab__select"
+ color="neutral"
+ onClick={() => onSelect(tab.id)}
+ size="sm"
+ variant="ghost"
+ >
+ {tab.title}
+ </Button>
+ <Button
+ aria-label={`Close ${tab.title}`}
+ className="chat-view-tab__close"
+ color="neutral"
+ onClick={() => onClose(tab.id)}
+ size="xs"
+ variant="ghost"
+ >
+ <span aria-hidden="true">×</span>
+ </Button>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )
+}
diff --git a/desktop-app/ui/src/components/ChatTabs/types.ts b/desktop-app/ui/src/components/ChatTabs/types.ts
new file mode 100644
index 000000000..bc05773e8
--- /dev/null
+++ b/desktop-app/ui/src/components/ChatTabs/types.ts
@@ -0,0 +1,8 @@
+import type { ChatViewTab } from '@lib/chatViewTabs.types'
+
+export type ChatTabsProps = {
+ tabs: ChatViewTab[]
+ activeTabId: string
+ onSelect: (id: string) => void
+ onClose: (id: string) => void
+}
diff --git a/desktop-app/ui/src/components/agents/ComposerPanel.tsx b/desktop-app/ui/src/components/agents/ComposerPanel.tsx
index c645c0812..428d50287 100644
--- a/desktop-app/ui/src/components/agents/ComposerPanel.tsx
+++ b/desktop-app/ui/src/components/agents/ComposerPanel.tsx
@@ -71,6 +71,7 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr
failedAgentSend,
activeChatId,
activeMessageCount,
+ composerFocusRequestId,
} = useChatComposerStateContext()
const {
clearComposerSendError,
@@ -257,6 +258,13 @@ export function ComposerPanel({ inline = false, agentSelector }: ComposerPanelPr
})
}, [activeChatId, activeMessageCount, agentSending])
+ useEffect(() => {
+ if (composerFocusRequestId === 0) return
+ const textarea = composerInputRef.current
+ if (!textarea || textarea.disabled || document.activeElement === textarea) return
+ textarea.focus()
+ }, [composerFocusRequestId])
+
const handleDraftChange = useCallback(
(value: string) => {
setDraft(value)
diff --git a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
index 2e96a508e..15baecd24 100644
--- a/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
+++ b/desktop-app/ui/src/components/agents/__tests__/ComposerPanel.test.tsx
@@ -19,6 +19,7 @@ const composerState = {
failedAgentSend: null,
activeChatId: null,
activeMessageCount: 0,
+ composerFocusRequestId: 0,
}
const draftState = { value: '', set: vi.fn() }
@@ -99,6 +100,7 @@ afterEach(() => {
cleanup()
draftState.value = ''
draftState.set.mockReset()
+ composerState.composerFocusRequestId = 0
delete (window as Partial<typeof window>).clerum
})
@@ -169,4 +171,25 @@ describe.each([
expect(cssRule('\\.composer-input-shell')).not.toMatch(/overflow\s*:/)
expect(cssRule('\\.composer-textarea-viewport')).toMatch(/overflow\s*:\s*hidden/)
})
+
+ it('focuses on a trusted request and preserves selection when already focused', () => {
+ const otherInput = document.createElement('input')
+ document.body.append(otherInput)
+ otherInput.focus()
+ const { rerender } = render(<ComposerPanel inline={inline} />)
+ const textarea = screen.getByTestId('chat-input') as HTMLTextAreaElement
+
+ composerState.composerFocusRequestId = 1
+ rerender(<ComposerPanel inline={inline} />)
+ expect(document.activeElement).toBe(textarea)
+
+ draftState.value = 'preserve this draft'
+ rerender(<ComposerPanel inline={inline} />)
+ textarea.setSelectionRange(4, 8)
+ composerState.composerFocusRequestId = 2
+ rerender(<ComposerPanel inline={inline} />)
+ expect(textarea.selectionStart).toBe(4)
+ expect(textarea.selectionEnd).toBe(8)
+ otherInput.remove()
+ })
})
diff --git a/desktop-app/ui/src/contexts/ChatComposerStateContext/types.ts b/desktop-app/ui/src/contexts/ChatComposerStateContext/types.ts
index 4281b1b80..b9188ee81 100644
--- a/desktop-app/ui/src/contexts/ChatComposerStateContext/types.ts
+++ b/desktop-app/ui/src/contexts/ChatComposerStateContext/types.ts
@@ -19,6 +19,7 @@ export interface ChatComposerStateContextValue {
agentError: string | null
failedAgentSend: FailedAgentSend | null
activeMessageCount: number
+ composerFocusRequestId: number
}
export interface ChatComposerStateProviderProps {
diff --git a/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts b/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts
new file mode 100644
index 000000000..c976a56e0
--- /dev/null
+++ b/desktop-app/ui/src/lib/__tests__/chatViewTabs.test.ts
@@ -0,0 +1,115 @@
+import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import {
+ addBlankChatViewTab,
+ closeChatViewTab,
+ createChatViewTabsState,
+ cycleChatViewTab,
+ focusBlankChatViewTab,
+ openPersistedChatViewTab,
+ 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)
+ }
+ )
+ )
+ })
+})
diff --git a/desktop-app/ui/src/lib/chatViewTabs.ts b/desktop-app/ui/src/lib/chatViewTabs.ts
new file mode 100644
index 000000000..1fc13f0ad
--- /dev/null
+++ b/desktop-app/ui/src/lib/chatViewTabs.ts
@@ -0,0 +1,119 @@
+import type { ChatViewTab, ChatViewTabsState, PersistedChatView } from './chatViewTabs.types'
+
+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) ?? state.tabs[0]!
+}
+
+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 }
+}
+
+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: state.tabs.at(-1)!.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
new file mode 100644
index 000000000..c767c36f8
--- /dev/null
+++ b/desktop-app/ui/src/lib/chatViewTabs.types.ts
@@ -0,0 +1,18 @@
+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/styles.css b/desktop-app/ui/src/styles.css
index 2938c7fa5..edbbd56ad 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -14779,3 +14779,46 @@ pre {
margin: 0 0 var(--space-2);
font-size: var(--font-size-sm);
}
+/* Keyboard-first chat view tabs */
+.chat-view-tabs {
+ display: flex;
+ min-width: 0;
+ padding: var(--space-2) var(--space-3) 0;
+}
+
+.chat-view-tabs__list {
+ display: flex;
+ gap: var(--space-1);
+ min-width: 0;
+ overflow-x: auto;
+}
+
+.chat-view-tab {
+ align-items: center;
+ background: var(--surface-soft);
+ border: 1px solid var(--border-soft);
+ border-radius: var(--radius-sm) var(--radius-sm) 0 0;
+ display: flex;
+ flex: 0 0 auto;
+ max-width: 220px;
+}
+
+.chat-view-tab.is-active {
+ background: var(--surface-strong);
+ border-color: var(--accent);
+}
+
+.chat-view-tab__select {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.chat-view-tab__close {
+ flex: 0 0 auto;
+}
+
+.chat-view-workspace {
+ display: contents;
+}