Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(desktop): add universal workspace tab store (pure)
Diego Zacariasb3e133c7a60a
diff --git a/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts b/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.tsnew file mode 100644index 000000000..41d4d5d88--- /dev/null+++ b/desktop-app/ui/src/lib/__tests__/workspaceTabs.test.ts@@ -0,0 +1,470 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import {+ activeWorkspaceTab,+ closeWorkspaceTab,+ createEmptyWorkspaceTabsState,+ createWorkspaceTabsState,+ cycleWorkspaceTab,+ firstWorkspaceTab,+ lastWorkspaceTab,+ newChatTab,+ openAppTab,+ openChatTab,+ openFilesTab,+ openSettingsTab,+ reconcileWorkspaceChatTab,+ selectLastWorkspaceTab,+ selectWorkspaceTab,+ selectWorkspaceTabAt,+} from '../workspaceTabs'+import type { ActiveChat, SettingsSection, WorkspaceTabsState } from '../workspaceTabs.types'++const SECTIONS: SettingsSection[] = ['connectors', 'agents', 'plugins', 'settings']++// A persisted chatId is unique to its agent, so tie the agent to the chat: the+// store dedupes chat tabs by (agentRef, chatId), and this makes that equivalent+// to dedupe-by-chatId, the identity the spec (§4.1 / §7-3) states.+const agentForChat = (chatId: string) => `agent:${chatId}`++// ---- example-based specifications -------------------------------------------++describe('workspaceTabs — construction and empty state', () => {+ it('boots with a single active blank chat tab (§5 boot seed)', () => {+ const state = createWorkspaceTabsState('boot', 'alpha')+ expect(state).toEqual({+ tabs: [+ { id: 'boot', kind: 'chat', title: 'New chat', chat: { agentRef: 'alpha', chatId: null } },+ ],+ activeTabId: 'boot',+ })+ })++ it('represents an empty workspace with a null active id', () => {+ expect(createEmptyWorkspaceTabsState()).toEqual({ tabs: [], activeTabId: null })+ })++ it('total accessors never throw on an empty list (lifted invariant)', () => {+ const empty = createEmptyWorkspaceTabsState()+ expect(firstWorkspaceTab(empty.tabs)).toBeUndefined()+ expect(lastWorkspaceTab(empty.tabs)).toBeUndefined()+ expect(activeWorkspaceTab(empty)).toBeUndefined()+ expect(selectLastWorkspaceTab(empty)).toBe(empty)+ expect(cycleWorkspaceTab(empty, 'next')).toBe(empty)+ expect(selectWorkspaceTabAt(empty, 0)).toBe(empty)+ })+})++describe('workspaceTabs — identity rules R6–R9', () => {+ it('R7 — dedupes a chat by chatId and focuses the existing tab', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openChatTab(state, { id: 'c1', agentRef: 'a', chatId: 'chat-1', title: 'First' })+ state = openAppTab(state, { id: 'app-1', appRef: 'app' })+ const before = state.tabs.length+ state = openChatTab(state, { id: 'dup', agentRef: 'a', chatId: 'chat-1', title: 'Renamed' })+ expect(state.tabs.length).toBe(before) // no new tab+ expect(state.activeTabId).toBe('c1') // focused existing+ expect(state.tabs.find(t => t.id === 'c1')?.title).toBe('Renamed')++ // A re-open with the same (or no) title is a no-op on the tab array — the+ // dedupe branch preserves referential equality so downstream skips a render.+ const sameTabs = state.tabs+ const reopened = openChatTab(state, {+ id: 'dup2',+ agentRef: 'a',+ chatId: 'chat-1',+ title: 'Renamed',+ })+ expect(reopened.tabs).toBe(sameTabs)+ expect(openChatTab(state, { id: 'dup3', agentRef: 'a', chatId: 'chat-1' }).tabs).toBe(sameTabs)+ })++ it('R9 — apps always open a new tab, keyed by tab-id (no appRef dedupe)', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openAppTab(state, { id: 'app-1', appRef: 'eventasks' })+ state = openAppTab(state, { id: 'app-2', appRef: 'eventasks' })+ expect(state.tabs.filter(t => t.kind === 'app')).toHaveLength(2)+ expect(state.activeTabId).toBe('app-2')+ })++ it('R8 — files is a single instance; re-open focuses the existing tab', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openFilesTab(state, { id: 'files-1' })+ state = openAppTab(state, { id: 'app-1', appRef: 'x' })+ state = openFilesTab(state, { id: 'files-2' })+ expect(state.tabs.filter(t => t.kind === 'files')).toHaveLength(1)+ expect(state.activeTabId).toBe('files-1')+ })++ it('R6 — settings is unique per section; re-open focuses the existing section', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openSettingsTab(state, { id: 's-connectors', section: 'connectors' })+ state = openSettingsTab(state, { id: 's-agents', section: 'agents' })+ state = openSettingsTab(state, { id: 's-connectors-2', section: 'connectors' })+ expect(state.tabs.filter(t => t.kind === 'settings')).toHaveLength(2)+ expect(state.activeTabId).toBe('s-connectors')+ })+})++describe('workspaceTabs — new chat (blank) with kind guard', () => {+ it('reuses the active blank chat tab (aligns the agent)', () => {+ let state = createWorkspaceTabsState('boot', null)+ state = newChatTab(state, 'unused', 'alpha')+ expect(state.tabs).toHaveLength(1)+ expect(state.tabs[0]).toEqual({+ id: 'boot',+ kind: 'chat',+ title: 'New chat',+ chat: { agentRef: 'alpha', chatId: null },+ })+ })++ it('ADDS a chat tab when the active tab is not a chat (§5 / focusBlank guard)', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openFilesTab(state, { id: 'files-1' })+ state = newChatTab(state, 'chat-new', 'beta')+ expect(state.tabs).toHaveLength(2)+ expect(state.activeTabId).toBe('chat-new')+ expect(activeWorkspaceTab(state)?.kind).toBe('chat')+ })++ it('ADDS a chat tab when the active chat already holds a persisted chat', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openChatTab(state, { id: 'c1', agentRef: 'a', chatId: 'chat-1' })+ state = newChatTab(state, 'blank', 'a')+ expect(state.tabs).toHaveLength(2)+ expect(state.activeTabId).toBe('blank')+ })+})++describe('workspaceTabs — selection and cycling over all kinds', () => {+ function mixed(): WorkspaceTabsState {+ let state = createEmptyWorkspaceTabsState()+ state = openChatTab(state, { id: 't0', agentRef: 'a', chatId: 'c0' })+ state = openAppTab(state, { id: 't1', appRef: 'app' })+ state = openFilesTab(state, { id: 't2' })+ state = openSettingsTab(state, { id: 't3', section: 'agents' })+ return state+ }++ it('selects by id, by index, and last — across kinds', () => {+ const state = mixed()+ expect(selectWorkspaceTab(state, 't1').activeTabId).toBe('t1')+ expect(selectWorkspaceTabAt(state, 2).activeTabId).toBe('t2')+ expect(selectLastWorkspaceTab(state).activeTabId).toBe('t3')+ expect(selectWorkspaceTab(state, 'missing')).toBe(state)+ })++ it('cycles in both directions with wrapping', () => {+ let state = { ...mixed(), activeTabId: 't3' }+ expect(cycleWorkspaceTab(state, 'next').activeTabId).toBe('t0')+ state = { ...state, activeTabId: 't0' }+ expect(cycleWorkspaceTab(state, 'previous').activeTabId).toBe('t3')+ })+})++describe('workspaceTabs — close (no re-seed; empty allowed §5)', () => {+ it('activates the right neighbor, then clamps left, then leaves EMPTY', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openChatTab(state, { id: 't0', agentRef: 'a', chatId: 'c0' })+ state = openAppTab(state, { id: 't1', appRef: 'app' })+ state = openFilesTab(state, { id: 't2' })+ state = { ...state, activeTabId: 't1' }++ state = closeWorkspaceTab(state, 't1')+ expect(state.activeTabId).toBe('t2') // right neighbor++ state = closeWorkspaceTab(state, 't2')+ expect(state.activeTabId).toBe('t0') // clamped to left++ state = closeWorkspaceTab(state, 't0')+ // Closing the last tab does NOT re-seed a blank chat — it goes empty.+ expect(state).toEqual({ tabs: [], activeTabId: null })+ })++ it('closing a non-active tab keeps the active id', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openChatTab(state, { id: 't0', agentRef: 'a', chatId: 'c0' })+ state = openAppTab(state, { id: 't1', appRef: 'app' })+ state = { ...state, activeTabId: 't1' }+ state = closeWorkspaceTab(state, 't0')+ expect(state.activeTabId).toBe('t1')+ expect(state.tabs.map(t => t.id)).toEqual(['t1'])+ })++ it('is a no-op for an unknown id', () => {+ const state = openChatTab(createEmptyWorkspaceTabsState(), {+ id: 't0',+ agentRef: 'a',+ chatId: 'c0',+ })+ expect(closeWorkspaceTab(state, 'nope')).toBe(state)+ })+})++// ---- T2 property-based (§7) --------------------------------------------------++type OpenOp =+ | { t: 'chat'; chatId: string }+ | { t: 'app'; appRef: string }+ | { t: 'files' }+ | { t: 'settings'; section: SettingsSection }++const openOpArb: fc.Arbitrary<OpenOp> = fc.oneof(+ fc.record({ t: fc.constant('chat' as const), chatId: fc.constantFrom('c1', 'c2', 'c3', 'c4') }),+ fc.record({ t: fc.constant('app' as const), appRef: fc.constantFrom('app-a', 'app-b') }),+ fc.record({ t: fc.constant('files' as const) }),+ fc.record({ t: fc.constant('settings' as const), section: fc.constantFrom(...SECTIONS) })+)++function applyOpens(ops: OpenOp[]): WorkspaceTabsState {+ let state = createEmptyWorkspaceTabsState()+ ops.forEach((op, i) => {+ const id = `id-${i}`+ if (op.t === 'chat') {+ state = openChatTab(state, { id, agentRef: agentForChat(op.chatId), chatId: op.chatId })+ } else if (op.t === 'app') {+ state = openAppTab(state, { id, appRef: op.appRef })+ } else if (op.t === 'files') {+ state = openFilesTab(state, { id })+ } else {+ state = openSettingsTab(state, { id, section: op.section })+ }+ })+ return state+}++describe('workspaceTabs — T2 properties (§7)', () => {+ it('(2)+(3) no duplicate ids; chat/files/settings unique, apps multiple', () => {+ fc.assert(+ fc.property(fc.array(openOpArb, { maxLength: 40 }), ops => {+ const state = applyOpens(ops)++ // (2) no duplicate tab ids.+ const ids = state.tabs.map(t => t.id)+ expect(new Set(ids).size).toBe(ids.length)++ // (3) chat unique by chatId.+ const chatIds = state.tabs.filter(t => t.kind === 'chat').map(t => t.chat?.chatId)+ expect(new Set(chatIds).size).toBe(chatIds.length)++ // (3) files unique.+ expect(state.tabs.filter(t => t.kind === 'files').length).toBeLessThanOrEqual(1)++ // (3) settings unique per section.+ const sections = state.tabs.filter(t => t.kind === 'settings').map(t => t.settings?.section)+ expect(new Set(sections).size).toBe(sections.length)++ // (3) apps: one tab per app open (no dedupe).+ const appOpens = ops.filter(op => op.t === 'app').length+ expect(state.tabs.filter(t => t.kind === 'app').length).toBe(appOpens)++ // active id (when tabs exist) always references a real tab.+ if (state.tabs.length > 0) {+ expect(state.tabs.some(t => t.id === state.activeTabId)).toBe(true)+ } else {+ expect(state.activeTabId).toBeNull()+ }+ })+ )+ })++ it('(1) opens append in insertion order; selection and cycling preserve it', () => {+ fc.assert(+ fc.property(+ fc.array(openOpArb, { minLength: 1, maxLength: 30 }),+ fc.integer({ min: 0, max: 29 }),+ (ops, raw) => {+ // Expected strip order: the id of each op that CREATES a new tab+ // (dedupe focuses in place, it does not reorder), in open order.+ const expectedOrder: string[] = []+ const seenChats = new Set<string>()+ const seenSections = new Set<string>()+ let hasFiles = false+ ops.forEach((op, i) => {+ const id = `id-${i}`+ if (op.t === 'chat') {+ if (!seenChats.has(op.chatId)) {+ seenChats.add(op.chatId)+ expectedOrder.push(id)+ }+ } else if (op.t === 'app') {+ expectedOrder.push(id)+ } else if (op.t === 'files') {+ if (!hasFiles) {+ hasFiles = true+ expectedOrder.push(id)+ }+ } else if (!seenSections.has(op.section)) {+ seenSections.add(op.section)+ expectedOrder.push(id)+ }+ })++ const state = applyOpens(ops)+ const order = state.tabs.map(t => t.id)+ // Insertion order is preserved in the strip.+ expect(order).toEqual(expectedOrder)++ const index = raw % state.tabs.length+ const selected = selectWorkspaceTabAt(state, index)+ const cycled = cycleWorkspaceTab(cycleWorkspaceTab(selected, 'next'), 'previous')+ // Order is untouched by selection/cycling; only activeTabId moves.+ expect(selected.tabs.map(t => t.id)).toEqual(order)+ expect(cycled.tabs.map(t => t.id)).toEqual(order)+ }+ )+ )+ })++ it('(5) closing every tab in any order never re-seeds — ends EMPTY', () => {+ fc.assert(+ fc.property(+ fc.array(openOpArb, { minLength: 1, maxLength: 25 }),+ fc.array(fc.integer({ min: 0, max: 24 }), { maxLength: 25 }),+ (ops, order) => {+ let state = applyOpens(ops)+ const opened = state.tabs.length+ // Close each tab exactly once, in a shuffled-ish order.+ const ids = [...state.tabs.map(t => t.id)]+ const closeOrder = order+ .map(n => ids[n % ids.length]!)+ .concat(ids)+ .filter((id, i, arr) => arr.indexOf(id) === i)+ let closes = 0+ for (const id of closeOrder) {+ const before = state.tabs.length+ state = closeWorkspaceTab(state, id)+ if (state.tabs.length < before) closes += 1+ // The list only ever shrinks — no phantom tab appears.+ expect(state.tabs.length).toBeLessThanOrEqual(before)+ }+ expect(closes).toBe(opened)+ expect(state).toEqual({ tabs: [], activeTabId: null })+ }+ )+ )+ })+})++describe('workspaceTabs — reconcile (chat sub-slice, §3)', () => {+ 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 activeArb: fc.Arbitrary<ActiveChat> = 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(activeArb, { maxLength: 40 }), events => {+ let state = createWorkspaceTabsState('seed', 'alpha')+ let counter = 0+ for (const event of events) {+ state = reconcileWorkspaceChatTab(state, event, `gen-${counter++}`)+ const active = activeWorkspaceTab(state)+ expect(active?.kind).toBe('chat')+ expect(active?.chat?.agentRef).toBe(event.agentRef)+ expect(active?.chat?.chatId).toBe(event.chatId)+ const seen = new Set<string>()+ for (const tab of state.tabs) {+ if (tab.kind !== 'chat' || tab.chat?.chatId == null) continue+ const key = `${tab.chat.agentRef}::${tab.chat.chatId}`+ expect(seen.has(key)).toBe(false)+ seen.add(key)+ }+ }+ })+ )+ })++ it('(4) is idempotent: applying the same event twice equals applying it once (same ref)', () => {+ fc.assert(+ fc.property(fc.array(activeArb, { maxLength: 20 }), activeArb, (prefix, event) => {+ let state = createWorkspaceTabsState('seed', 'alpha')+ let counter = 0+ for (const e of prefix) state = reconcileWorkspaceChatTab(state, e, `p-${counter++}`)+ const once = reconcileWorkspaceChatTab(state, event, 'once')+ const twice = reconcileWorkspaceChatTab(once, event, 'twice')+ expect(twice).toBe(once)+ })+ )+ })++ it('never drops a persisted chat tab that was already open', () => {+ fc.assert(+ fc.property(fc.array(activeArb, { maxLength: 30 }), events => {+ let state = createWorkspaceTabsState('seed', 'alpha')+ let counter = 0+ const everOpened = new Set<string>()+ for (const event of events) {+ state = reconcileWorkspaceChatTab(state, event, `g-${counter++}`)+ if (event.chatId !== null) everOpened.add(`${event.agentRef}::${event.chatId}`)+ for (const key of everOpened) {+ const [agentRef, chatId] = key.split('::')+ expect(+ state.tabs.filter(+ t => t.kind === 'chat' && t.chat?.agentRef === agentRef && t.chat?.chatId === chatId+ )+ ).toHaveLength(1)+ }+ }+ })+ )+ })++ // Coverage gap: the other reconcile properties all seed a chat tab. This one+ // seeds a NON-chat active tab (app/files/settings) so the append+activate path+ // is exercised and its contract is pinned.+ it('reconciles from a non-chat active tab: re-homes focus to the chat, keeps the seed, stays idempotent', () => {+ const seedKindArb = fc.constantFrom<'app' | 'files' | 'settings'>('app', 'files', 'settings')+ fc.assert(+ fc.property(+ seedKindArb,+ fc.array(activeArb, { minLength: 1, maxLength: 20 }),+ (seedKind, events) => {+ let state = createEmptyWorkspaceTabsState()+ if (seedKind === 'app') state = openAppTab(state, { id: 'seed', appRef: 'x' })+ else if (seedKind === 'files') state = openFilesTab(state, { id: 'seed' })+ else state = openSettingsTab(state, { id: 'seed', section: 'agents' })+ const seedTab = state.tabs[0]!++ let counter = 0+ for (const event of events) {+ state = reconcileWorkspaceChatTab(state, event, `n-${counter++}`)+ const active = activeWorkspaceTab(state)+ // Documented contract: focus re-homes onto the chat tab.+ expect(active?.kind).toBe('chat')+ expect(active?.chat?.agentRef).toBe(event.agentRef)+ expect(active?.chat?.chatId).toBe(event.chatId)+ // The non-chat seed is never dropped by chat reconciliation.+ expect(state.tabs.some(t => t.id === seedTab.id && t.kind === seedTab.kind)).toBe(true)+ }++ // Idempotence still holds from a non-chat-seeded history.+ const lastEvent = events[events.length - 1]!+ const again = reconcileWorkspaceChatTab(state, lastEvent, 'again')+ expect(again).toBe(state)+ }+ )+ )+ })++ it('reconcile leaves non-chat tabs untouched and re-homes focus to the chat tab', () => {+ let state = createEmptyWorkspaceTabsState()+ state = openAppTab(state, { id: 'app-1', appRef: 'x' })+ state = openFilesTab(state, { id: 'files-1' }) // files-1 is the active tab+ const nonChatBefore = state.tabs.filter(t => t.kind !== 'chat')+ state = reconcileWorkspaceChatTab(state, { agentRef: 'a', chatId: 'c1', title: 'Hi' }, 'gen')+ const nonChatAfter = state.tabs.filter(t => t.kind !== 'chat')+ expect(nonChatAfter).toEqual(nonChatBefore)+ // NOTE: reconcile/openChat currently re-home focus to the chat tab even from+ // a non-chat active tab (ported from chatViewTabs). Slice 04 (drawer) will+ // revisit whether the drawer needs its own chat pointer distinct from+ // activeTabId.+ expect(state.activeTabId).toBe('gen')+ expect(activeWorkspaceTab(state)?.kind).toBe('chat')+ })+})diff --git a/desktop-app/ui/src/lib/workspaceTabs.ts b/desktop-app/ui/src/lib/workspaceTabs.tsnew file mode 100644index 000000000..5a20af12e--- /dev/null+++ b/desktop-app/ui/src/lib/workspaceTabs.ts@@ -0,0 +1,322 @@+import type {+ ActiveChat,+ OpenAppTabInput,+ OpenChatTabInput,+ OpenFilesTabInput,+ OpenSettingsTabInput,+ WorkspaceTab,+ WorkspaceTabsState,+} from './workspaceTabs.types'++/**+ * Universal tab store — the pure algebra of the single global strip (spec 01+ * §4.1). It reuses the order/dedupe/select/cycle/reconcile logic of+ * `chatViewTabs` for the `kind:'chat'` sub-slice, but LIFTS OUT the+ * "list is never empty + re-seed a blank chat" invariant that does not survive+ * universalization (§5, option B):+ * - the workspace may be empty; `activeTabId` is nullable;+ * - `firstWorkspaceTab`/`lastWorkspaceTab` are TOTAL (never throw);+ * - closing the last tab leaves an empty workspace — it does NOT re-seed.+ * This store is the sole owner of tab identity and which tab is active;+ * chat loading (`selectedAgent`, pending-selection) stays in its controllers.+ *+ * Contract: callers MUST supply a unique `id` for every opened tab. Ids are the+ * identity used for select/cycle/close; a reused id yields two tabs sharing an+ * id, and `closeWorkspaceTab` would then filter BOTH out at once.+ */++const isBlankChatTab = (tab: WorkspaceTab | undefined): boolean =>+ tab?.kind === 'chat' && (tab.chat?.chatId ?? null) === null++// ---- accessors (total: never throw on an empty list) ------------------------++export function firstWorkspaceTab(tabs: WorkspaceTab[]): WorkspaceTab | undefined {+ return tabs[0]+}++export function lastWorkspaceTab(tabs: WorkspaceTab[]): WorkspaceTab | undefined {+ return tabs.at(-1)+}++export function activeWorkspaceTab(state: WorkspaceTabsState): WorkspaceTab | undefined {+ return state.tabs.find(tab => tab.id === state.activeTabId)+}++// ---- constructors -----------------------------------------------------------++/** Boot seed: one active blank chat tab (preserves "boot to chat", §5). */+export function createWorkspaceTabsState(+ id: string,+ agentRef: string | null = null+): WorkspaceTabsState {+ return {+ tabs: [{ id, kind: 'chat', title: 'New chat', chat: { agentRef, chatId: null } }],+ activeTabId: id,+ }+}++/** Empty workspace — the state left after closing the last tab (§5). */+export function createEmptyWorkspaceTabsState(): WorkspaceTabsState {+ return { tabs: [], activeTabId: null }+}++function appendBlankChatTab(+ state: WorkspaceTabsState,+ id: string,+ agentRef: string | null+): WorkspaceTabsState {+ const tab: WorkspaceTab = {+ id,+ kind: 'chat',+ title: 'New chat',+ chat: { agentRef, chatId: null },+ }+ return { tabs: [...state.tabs, tab], activeTabId: id }+}++// ---- open / focus (identity rules R6–R9, spec 01 §4.1) ----------------------++/**+ * Open or focus a chat tab (R7). Persisted chats (`chatId !== null`) dedupe by+ * `agentRef + chatId` (a chatId is unique to its agent, so this is dedupe by+ * chatId). A port of `openPersistedChatViewTab` with the kind guard from §1:+ * it only collapses into the active tab when that tab is a BLANK CHAT tab.+ */+export function openChatTab(+ state: WorkspaceTabsState,+ input: OpenChatTabInput+): WorkspaceTabsState {+ const { id, agentRef, chatId } = input+ const title = input.title?.trim()++ if (chatId !== null) {+ const existing = state.tabs.find(+ tab => tab.kind === 'chat' && tab.chat?.agentRef === agentRef && tab.chat?.chatId === chatId+ )+ if (existing) {+ return {+ tabs:+ title && existing.title !== title+ ? state.tabs.map(tab => (tab.id === existing.id ? { ...tab, title } : tab))+ : state.tabs,+ activeTabId: existing.id,+ }+ }+ }++ const current = activeWorkspaceTab(state)+ const collapseIntoBlank = current !== undefined && isBlankChatTab(current)+ const next: WorkspaceTab = {+ id: collapseIntoBlank ? current!.id : id,+ kind: 'chat',+ title: title || (chatId === null ? 'New chat' : 'Conversation'),+ chat: { agentRef, chatId },+ }+ if (collapseIntoBlank) {+ return {+ tabs: state.tabs.map(tab => (tab.id === current!.id ? next : tab)),+ activeTabId: next.id,+ }+ }+ return { tabs: [...state.tabs, next], activeTabId: next.id }+}++/**+ * "New chat" (`focusBlankChatViewTab` port with the §1 kind guard): if the+ * active tab is already a blank chat, reuse it (align the agent); otherwise —+ * including when the active tab is app/files/settings or there is none — ADD a+ * new blank chat tab. Never collapses into a non-chat active tab.+ */+export function newChatTab(+ state: WorkspaceTabsState,+ id: string,+ agentRef: string | null = null+): WorkspaceTabsState {+ const current = activeWorkspaceTab(state)+ if (current && isBlankChatTab(current)) {+ return {+ tabs: state.tabs.map(tab =>+ tab.id === current.id+ ? { ...tab, title: 'New chat', chat: { agentRef, chatId: null } }+ : tab+ ),+ activeTabId: current.id,+ }+ }+ return appendBlankChatTab(state, id, agentRef)+}++/** Apps ALWAYS open a new tab, keyed by tab-id — no dedupe by appRef (R9). */+export function openAppTab(state: WorkspaceTabsState, input: OpenAppTabInput): WorkspaceTabsState {+ const tab: WorkspaceTab = {+ id: input.id,+ kind: 'app',+ title: input.title?.trim() || 'App',+ app: {+ appRef: input.appRef,+ ...(input.savedRoutePath !== undefined ? { savedRoutePath: input.savedRoutePath } : {}),+ },+ }+ return { tabs: [...state.tabs, tab], activeTabId: input.id }+}++/** Files: single instance — focus the existing tab if present (R8). */+export function openFilesTab(+ state: WorkspaceTabsState,+ input: OpenFilesTabInput+): WorkspaceTabsState {+ const existing = state.tabs.find(tab => tab.kind === 'files')+ const title = input.title?.trim()+ if (existing) {+ return {+ tabs:+ title && existing.title !== title+ ? state.tabs.map(tab => (tab.id === existing.id ? { ...tab, title } : tab))+ : state.tabs,+ activeTabId: existing.id,+ }+ }+ const tab: WorkspaceTab = { id: input.id, kind: 'files', title: title || 'Files' }+ return { tabs: [...state.tabs, tab], activeTabId: input.id }+}++/** Settings: unique per `section` — focus the existing section tab (R6). */+export function openSettingsTab(+ state: WorkspaceTabsState,+ input: OpenSettingsTabInput+): WorkspaceTabsState {+ const existing = state.tabs.find(+ tab => tab.kind === 'settings' && tab.settings?.section === input.section+ )+ const title = input.title?.trim()+ if (existing) {+ return {+ tabs:+ title && existing.title !== title+ ? state.tabs.map(tab => (tab.id === existing.id ? { ...tab, title } : tab))+ : state.tabs,+ activeTabId: existing.id,+ }+ }+ const tab: WorkspaceTab = {+ id: input.id,+ kind: 'settings',+ title: title || input.section,+ settings: { section: input.section },+ }+ return { tabs: [...state.tabs, tab], activeTabId: input.id }+}++// ---- selection / cycling (universal: over ALL tabs, any kind) ---------------++export function selectWorkspaceTab(state: WorkspaceTabsState, id: string): WorkspaceTabsState {+ return state.tabs.some(tab => tab.id === id) ? { ...state, activeTabId: id } : state+}++export function selectWorkspaceTabAt(state: WorkspaceTabsState, index: number): WorkspaceTabsState {+ const target = state.tabs[index]+ return target ? { ...state, activeTabId: target.id } : state+}++export function selectLastWorkspaceTab(state: WorkspaceTabsState): WorkspaceTabsState {+ const last = lastWorkspaceTab(state.tabs)+ return last ? { ...state, activeTabId: last.id } : state+}++export function cycleWorkspaceTab(+ state: WorkspaceTabsState,+ direction: 'next' | 'previous'+): WorkspaceTabsState {+ 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 }+}++// ---- close (no re-seed; empty workspace allowed, §5) ------------------------++/**+ * Close a tab. Unlike `closeChatViewTab`, it never re-seeds a blank chat: when+ * the last tab closes, the workspace becomes empty (`activeTabId === null`).+ * When the active tab closes, the right neighbor (any kind) is activated.+ */+export function closeWorkspaceTab(state: WorkspaceTabsState, id: string): WorkspaceTabsState {+ const closingIndex = state.tabs.findIndex(tab => tab.id === id)+ if (closingIndex < 0) return state+ const tabs = state.tabs.filter(tab => tab.id !== id)+ if (tabs.length === 0) return { tabs, activeTabId: null }+ if (state.activeTabId !== id) return { tabs, activeTabId: state.activeTabId }+ const neighbor = tabs[Math.min(closingIndex, tabs.length - 1)]!+ return { tabs, activeTabId: neighbor.id }+}++// ---- reconcile (chat sub-slice; idempotent) ---------------------------------++/**+ * Aligns the chat-tab state to the chat the controller currently displays+ * (a port of `reconcileChatViewTabs`, §3: same logic, universal trigger). The+ * displayed `active` chat is PRIMARY; tab state is DERIVED from it.+ *+ * Anti-loop rules preserved from the origin:+ * - Idempotent: when the active tab already reflects `active` (same agent+chat,+ * title already matching when supplied), it returns the SAME `state`+ * reference so a `setState` bails out.+ * - Never spawns a duplicate persisted chat tab (dedupe by `agentRef + chatId`).+ * - Blank branch: keeps the already-active blank chat tab, only aligning its+ * agent; from any other active tab it appends one blank chat tab.+ * - It only touches chat tabs; app/files/settings tabs are left untouched.+ */+export function reconcileWorkspaceChatTab(+ state: WorkspaceTabsState,+ active: ActiveChat | null,+ newTabId: string+): WorkspaceTabsState {+ if (!active || !active.agentRef) return state+ const current = activeWorkspaceTab(state)++ if (active.chatId === null) {+ if (current && isBlankChatTab(current)) {+ return current.chat?.agentRef === active.agentRef+ ? state+ : {+ tabs: state.tabs.map(tab =>+ tab.id === current.id+ ? { ...tab, chat: { agentRef: active.agentRef, chatId: null } }+ : tab+ ),+ activeTabId: current.id,+ }+ }+ return appendBlankChatTab(state, newTabId, active.agentRef)+ }++ const existing = state.tabs.find(+ tab =>+ tab.kind === 'chat' &&+ tab.chat?.agentRef === active.agentRef &&+ tab.chat?.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 openChatTab(state, {+ id: newTabId,+ agentRef: active.agentRef,+ chatId: active.chatId,+ title: active.title,+ })+}diff --git a/desktop-app/ui/src/lib/workspaceTabs.types.ts b/desktop-app/ui/src/lib/workspaceTabs.types.tsnew file mode 100644index 000000000..a6073f9b8--- /dev/null+++ b/desktop-app/ui/src/lib/workspaceTabs.types.ts@@ -0,0 +1,77 @@+export type WorkspaceTabKind = 'chat' | 'app' | 'files' | 'settings'++export type SettingsSection = 'connectors' | 'agents' | 'plugins' | 'settings'++export type ChatTabPayload = {+ agentRef: string | null+ chatId: string | null+}++export type AppTabPayload = {+ appRef: string+ savedRoutePath?: string+}++export type SettingsTabPayload = {+ section: SettingsSection+}++/**+ * A single tab in the universal strip. `kind` discriminates the payload:+ * `chat` carries `chat`, `app` carries `app`, `settings` carries `settings`,+ * and `files` carries no payload (single instance, R8).+ */+export type WorkspaceTab = {+ id: string+ kind: WorkspaceTabKind+ title: string+ chat?: ChatTabPayload+ app?: AppTabPayload+ settings?: SettingsTabPayload+}++/**+ * `activeTabId` is nullable: the universal workspace may be empty (§5, option+ * B). The never-empty + blank-seed invariant of `chatViewTabs` does NOT survive+ * universalization — closing the last tab leaves `activeTabId === null`.+ */+export type WorkspaceTabsState = {+ tabs: WorkspaceTab[]+ activeTabId: string | null+}++export type OpenChatTabInput = {+ id: string+ agentRef: string | null+ chatId: string | null+ title?: string+}++export type OpenAppTabInput = {+ id: string+ appRef: string+ title?: string+ savedRoutePath?: string+}++export type OpenFilesTabInput = {+ id: string+ title?: string+}++export type OpenSettingsTabInput = {+ id: string+ section: SettingsSection+ title?: string+}++/**+ * The chat currently displayed by the chat controller — the primary that+ * `reconcileWorkspaceChatTab` aligns tab state to (`chatId === null` = a blank+ * new chat).+ */+export type ActiveChat = {+ agentRef: string+ chatId: string | null+ title?: string+}