/** * Workspace + Tab state management for cptr. * * State is split into three layers: * 1. Browser-tab state: which workspace is active, determined by URL (?workspace=...) * 2. Workspace state: tabs, groups, split layout, persisted server-side per workspace path * 3. User preferences: theme, locale, sidebar, persisted server-side globally * * Architecture: * Workspace → EditorGroup[] (1 or more groups, each with independent tabs) * Each group has its own tab list and active tab, like VS Code editor groups. * When there are 2+ groups, a split view is rendered. * * Multiple browser tabs can independently view different workspaces without * interfering; each tab reads its workspace path from the URL and loads/saves * only that workspace's state. */ import { writable, derived, get } from 'svelte/store'; import { getPreferences, savePreferences, getWorkspaceList, getWorkspaceState, saveWorkspaceState } from '$lib/apis/state'; import { listSessions, createSession, deleteSession } from '$lib/apis/terminal'; import { changeLocale, i18next } from '$lib/i18n'; import { streamingChatTabs } from '$lib/stores/chat'; import { keybindings, loadKeybindings } from '$lib/stores/keybindings'; import { defaultPwaPreferences, type PwaPreferences } from '$lib/intents/types'; import { getPathDisplayName, isSupportedWorkspacePath } from '$lib/utils/paths'; import { applyAppearance, sanitizeThemeConfig, type AppearancePreferences, type Theme, type ThemeConfig } from '$lib/utils/appearance'; export type { AppearancePreferences, Theme, ThemeConfig }; // ── Types ─────────────────────────────────────────────────────── export interface Tab { id: string; type: 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview'; label: string; filePath?: string; edit?: boolean; path?: string; // generic path (e.g. for chat) sessionId?: string; port?: number; unsaved?: boolean; permanent?: boolean; badge?: number; } export type SplitDirection = 'horizontal' | 'vertical'; export interface EditorGroup { id: string; tabs: Tab[]; activeTabId: string; tabHistory?: string[]; // MRU stack of tab IDs (most recent last) } export interface WorkspaceState { name: string; path: string; groups: EditorGroup[]; activeGroupId: string; splitDirection: SplitDirection; splitRatio: number; // 0-1, fraction for the first group fileBrowserCwd: string; } export type ToolApprovalMode = 'ask' | 'auto' | 'full'; export interface UserPreferences { theme?: Theme; appearance?: AppearancePreferences; sidebarOpen: boolean; sidebarWidth: number; toolApprovalMode: ToolApprovalMode; planMode: boolean; locale: string; workspaceOrder?: string[]; // ordered paths for sidebar drag-reorder keybindings?: Record; // user-customised keyboard shortcuts version?: string; // last seen app version for changelog selectedModelId?: string; // last selected chat model, synced across browsers requestParams?: Record; // arbitrary params merged into API request body showUpdateToast?: boolean; // show version update notifications (default true) pwa?: PwaPreferences; textScale?: number | null; } // ── ID generation ─────────────────────────────────────────────── let _idCounter = Date.now(); function nextId(): string { return (++_idCounter).toString(36); } // ── Default group for a workspace ─────────────────────────────── function createDefaultGroup(): EditorGroup { return { id: 'default', tabs: [{ id: 'files', type: 'files', label: 'Files', permanent: true }], activeTabId: 'files' }; } function createDefaultWorkspace(path: string): WorkspaceState { const name = getPathDisplayName(path); return { name, path, groups: [createDefaultGroup()], activeGroupId: 'default', splitDirection: 'horizontal', splitRatio: 0.5, fileBrowserCwd: path }; } // ── Stores ────────────────────────────────────────────────────── /** The workspace currently displayed in THIS browser tab. Null = welcome page. */ export const currentWorkspace = writable(null); /** List of all workspace summaries for the sidebar. */ export const workspaceList = writable<{ path: string; name: string }[]>([]); /** Global user preferences. */ export const sidebarOpen = writable( typeof window !== 'undefined' ? window.innerWidth >= 1024 : false ); // Auto-close sidebar when window is resized below mobile breakpoint if (typeof window !== 'undefined') { window.addEventListener('resize', () => { if (window.innerWidth < 768) { sidebarOpen.set(false); } }); } export const sidebarWidth = writable(220); export const theme = writable('dark'); export const toolApprovalMode = writable('auto'); export const planMode = writable(false); export const requestParams = writable>({}); export const appVersion = writable(''); export const lastSeenVersion = writable(''); export const latestVersion = writable(''); export const updateAvailable = derived([appVersion, latestVersion], ([$app, $latest]) => { if (!$app || !$latest || $app === 'dev' || $app === '0.0.0') return false; return ( $app.localeCompare($latest, undefined, { numeric: true, sensitivity: 'case', caseFirst: 'upper' }) < 0 ); }); export const showChangelog = writable(false); export const showUpdateToastPref = writable(true); export const showSearch = writable(false); /** @deprecated Use toolApprovalMode */ export const autoApproveTools = { subscribe: toolApprovalMode.subscribe, set: (v: boolean) => toolApprovalMode.set(v ? 'full' : 'ask'), update: (fn: (v: boolean) => boolean) => toolApprovalMode.update((m) => (fn(m === 'full') ? 'full' : 'ask')) }; export const stateLoaded = writable(false); export const gitReviewOpen = writable(false); export const isGitRepo = writable(false); export type StreamingBehavior = 'queue' | 'interrupt'; export const streamingBehavior = writable('queue'); export const selectedModelId = writable(''); export const pwaPreferences = writable(defaultPwaPreferences); export const themeConfig = writable(null); export const textScale = writable(null); /** Saved workspace path order for sidebar drag-reorder. */ export const workspaceOrder = writable([]); // ── Derived stores ────────────────────────────────────────────── /** @deprecated Alias for currentWorkspace. Helps migration of existing imports */ export const activeWorkspace = currentWorkspace; export const activeGroup = derived(currentWorkspace, ($ws) => $ws ? ($ws.groups.find((g) => g.id === $ws.activeGroupId) ?? $ws.groups[0] ?? null) : null ); export const activeTab = derived(activeGroup, ($g) => $g ? ($g.tabs.find((t) => t.id === $g.activeTabId) ?? null) : null ); export const splitActive = derived(currentWorkspace, ($ws) => ($ws?.groups.length ?? 0) > 1); // ── Compat aliases for old split-pane API ────────────────────── /** @deprecated Use splitActive */ export const splitPaneOpen = splitActive; /** @deprecated The "split tab" is now the active tab of the second group */ export const splitTab = derived(currentWorkspace, ($ws) => { if (!$ws || $ws.groups.length < 2) return null; const secondGroup = $ws.groups.find((g) => g.id !== $ws.activeGroupId) ?? $ws.groups[1]; return secondGroup?.tabs.find((t) => t.id === secondGroup.activeTabId) ?? null; }); /** @deprecated Use closeGroup */ export function closeSplitPane(): void { const ws = get(currentWorkspace); if (!ws || ws.groups.length < 2) return; for (const g of ws.groups.slice(1)) { closeGroup(g.id); } } /** @deprecated No direct equivalent. Swaps active group focus */ export function swapSplitPanes(): void { const ws = get(currentWorkspace); if (!ws || ws.groups.length < 2) return; const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId); if (otherGroup) setActiveGroup(otherGroup.id); } /** @deprecated Use activeGroup */ export const focusedPane = derived(currentWorkspace, ($ws) => $ws?.activeGroupId === $ws?.groups[0]?.id ? 'main' : 'split' ); // ── MRU tab history helpers ───────────────────────────────────── function pushTabHistory(group: EditorGroup, tabId: string): string[] { const history = (group.tabHistory ?? []).filter((id) => id !== tabId); history.push(tabId); if (history.length > 50) history.splice(0, history.length - 50); return history; } // ── Server-side persistence ───────────────────────────────────── let _saveWsTimer: ReturnType | null = null; let _savePrefTimer: ReturnType | null = null; function persistWorkspace(): void { if (_saveWsTimer) clearTimeout(_saveWsTimer); _saveWsTimer = setTimeout(() => { const ws = get(currentWorkspace); if (!ws) return; saveWorkspaceState(ws.path, ws as unknown as Record).catch(() => {}); }, 300); } function persistPreferences(): void { if (_savePrefTimer) clearTimeout(_savePrefTimer); _savePrefTimer = setTimeout(() => { const prefs: UserPreferences = { theme: get(theme), appearance: { theme: get(theme), themeConfig: sanitizeThemeConfig(get(themeConfig)), textScale: get(textScale) ?? undefined }, sidebarOpen: get(sidebarOpen), sidebarWidth: get(sidebarWidth), toolApprovalMode: get(toolApprovalMode), planMode: get(planMode), locale: i18next.language, workspaceOrder: get(workspaceOrder), keybindings: get(keybindings), version: get(lastSeenVersion), selectedModelId: get(selectedModelId) || undefined, requestParams: Object.keys(get(requestParams)).length ? get(requestParams) : undefined, showUpdateToast: get(showUpdateToastPref), pwa: get(pwaPreferences), textScale: get(textScale) ?? undefined }; savePreferences(prefs as unknown as Record).catch(() => {}); }, 300); } let _subscribed = false; function subscribeForPersistence() { if (_subscribed) return; _subscribed = true; currentWorkspace.subscribe(() => { if (get(stateLoaded)) persistWorkspace(); }); theme.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); themeConfig.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); sidebarOpen.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); sidebarWidth.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); toolApprovalMode.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); planMode.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); requestParams.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); workspaceOrder.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); keybindings.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); lastSeenVersion.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); selectedModelId.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); showUpdateToastPref.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); pwaPreferences.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); textScale.subscribe(() => { if (get(stateLoaded)) persistPreferences(); }); i18next.on('languageChanged', () => { if (get(stateLoaded)) persistPreferences(); }); } // ── Load preferences (called once at app startup) ─────────────── export async function loadPreferences(): Promise { try { const prefs = await getPreferences(); const appearance = ( prefs.appearance && typeof prefs.appearance === 'object' ? prefs.appearance : {} ) as AppearancePreferences; if (appearance.theme || prefs.theme) theme.set((appearance.theme ?? prefs.theme) as Theme); themeConfig.set(sanitizeThemeConfig(appearance.themeConfig)); if (prefs.sidebarOpen !== undefined) sidebarOpen.set(prefs.sidebarOpen as boolean); if (prefs.sidebarWidth !== undefined) sidebarWidth.set(prefs.sidebarWidth as number); // Support new toolApprovalMode and legacy boolean autoApproveTools if (prefs.toolApprovalMode) { toolApprovalMode.set(prefs.toolApprovalMode as ToolApprovalMode); } else if (prefs.autoApproveTools !== undefined) { // Legacy boolean migration toolApprovalMode.set((prefs.autoApproveTools as unknown as boolean) ? 'full' : 'ask'); } if (prefs.planMode !== undefined) planMode.set(prefs.planMode as boolean); if (prefs.locale) changeLocale(prefs.locale as string); if (Array.isArray(prefs.workspaceOrder)) workspaceOrder.set(prefs.workspaceOrder as string[]); if (prefs.keybindings) loadKeybindings(prefs.keybindings as Record); if (prefs.version) lastSeenVersion.set(prefs.version as string); if (prefs.selectedModelId) selectedModelId.set(prefs.selectedModelId as string); if (prefs.requestParams) requestParams.set(prefs.requestParams as Record); if (prefs.showUpdateToast !== undefined) showUpdateToastPref.set(prefs.showUpdateToast as boolean); textScale.set( typeof appearance.textScale === 'number' ? appearance.textScale : typeof prefs.textScale === 'number' ? (prefs.textScale as number) : null ); const pwaPrefs = prefs.pwa; if (pwaPrefs) pwaPreferences.set({ ...defaultPwaPreferences, ...(pwaPrefs as PwaPreferences) }); } catch { // First run, no preferences yet } } // ── Load workspace list (called once at app startup) ──────────── export async function loadWorkspaceList(): Promise { try { const list = await getWorkspaceList(); const order = get(workspaceOrder); if (order.length > 0 && list) { // Sort by saved order; unknown paths go to end const orderMap = new Map(order.map((p, i) => [p, i])); list.sort((a, b) => (orderMap.get(a.path) ?? Infinity) - (orderMap.get(b.path) ?? Infinity)); } workspaceList.set(list || []); } catch { workspaceList.set([]); } } // ── Load a specific workspace (called when URL changes) ───────── export async function loadWorkspace(path: string): Promise { if (!isSupportedWorkspacePath(path)) { currentWorkspace.set(null); return; } try { const wsData = await getWorkspaceState(path); const canonicalWorkspacePath = typeof wsData.path === 'string' ? wsData.path : path; if (wsData && wsData.groups && (wsData.groups as EditorGroup[]).length > 0) { // Validate terminal sessions are still alive let aliveSessions: Set = new Set(); try { const sessions = await listSessions(); aliveSessions = new Set(sessions.map((s) => s.session_id)); } catch {} const ws = wsData as unknown as WorkspaceState; // Remove dead terminal tabs from all groups const cleanedGroups = ws.groups .map((g) => { const filteredTabs = g.tabs.filter((t: Tab) => { if (t.type === 'terminal' && t.sessionId && !aliveSessions.has(t.sessionId)) { return false; } return true; }); const activeStillExists = filteredTabs.some((t: Tab) => t.id === g.activeTabId); return { ...g, tabs: filteredTabs, activeTabId: activeStillExists ? g.activeTabId : (filteredTabs[0]?.id ?? 'files') }; }) .filter((g) => g.tabs.length > 0); const groups = cleanedGroups.length > 0 ? cleanedGroups : [createDefaultGroup()]; const activeGroupId = groups.some((g) => g.id === ws.activeGroupId) ? ws.activeGroupId : (groups[0]?.id ?? 'default'); currentWorkspace.set({ ...ws, path: canonicalWorkspacePath, groups, activeGroupId, splitDirection: ws.splitDirection ?? 'horizontal', splitRatio: ws.splitRatio ?? 0.5, fileBrowserCwd: ws.fileBrowserCwd ?? canonicalWorkspacePath }); } else { // First time opening this workspace, create defaults currentWorkspace.set(createDefaultWorkspace(canonicalWorkspacePath)); } } catch { currentWorkspace.set(null); } } // ── Initialize everything (called once at app startup) ────────── export async function initState(): Promise { await loadPreferences(); await loadWorkspaceList(); stateLoaded.set(true); subscribeForPersistence(); } /** @deprecated Use initState */ export const loadStateFromServer = initState; // ── Appearance application ────────────────────────────────────── function applyCurrentAppearance() { applyAppearance(get(theme), get(themeConfig), get(textScale)); } theme.subscribe(applyCurrentAppearance); themeConfig.subscribe(applyCurrentAppearance); textScale.subscribe(applyCurrentAppearance); if (typeof window !== 'undefined') { window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { if (get(theme) === 'system') applyCurrentAppearance(); }); } // ── Cross-tab state sync (BroadcastChannel) ───────────────────── // Syncs theme and locale changes between browser tabs / PWA windows // so the user doesn't see divergent state. if (typeof BroadcastChannel !== 'undefined') { const channel = new BroadcastChannel('cptr-sync'); let _syncingFromBroadcast = false; channel.onmessage = (e: MessageEvent) => { const { type, value } = e.data || {}; _syncingFromBroadcast = true; try { if (type === 'theme' && value) { theme.set(value); } else if (type === 'appearance' && value) { if (value.theme) theme.set(value.theme); themeConfig.set(sanitizeThemeConfig(value.themeConfig)); textScale.set(typeof value.textScale === 'number' ? value.textScale : null); } else if (type === 'locale' && value) { changeLocale(value); } } finally { _syncingFromBroadcast = false; } }; theme.subscribe((t) => { if (!_syncingFromBroadcast) { channel.postMessage({ type: 'theme', value: t }); channel.postMessage({ type: 'appearance', value: { theme: t, themeConfig: get(themeConfig), textScale: get(textScale) } }); } }); themeConfig.subscribe((config) => { if (!_syncingFromBroadcast) { channel.postMessage({ type: 'appearance', value: { theme: get(theme), themeConfig: config, textScale: get(textScale) } }); } }); textScale.subscribe((scale) => { if (!_syncingFromBroadcast) { channel.postMessage({ type: 'appearance', value: { theme: get(theme), themeConfig: get(themeConfig), textScale: scale } }); } }); // Locale changes are broadcast from changeLocale() calls; // subscribe to i18next language changes. if (i18next) { i18next.on('languageChanged', (lng: string) => { if (!_syncingFromBroadcast) { channel.postMessage({ type: 'locale', value: lng }); } }); } } // ── Workspace actions ─────────────────────────────────────────── /** * Register a workspace path in the sidebar list. * Does NOT set currentWorkspace. That happens when the URL changes * (via goto() in the calling component), which triggers loadWorkspace(). * The URL is the single source of truth for which workspace is active. */ export function addWorkspace(path: string): void { const name = getPathDisplayName(path, path); // Update workspace list for sidebar workspaceList.update((list) => { if (list.some((w) => w.path === path)) return list; return [...list, { path, name }]; }); // Append to order workspaceOrder.update((order) => { if (order.includes(path)) return order; return [...order, path]; }); } export async function removeWorkspace(path: string): Promise { const { deleteWorkspace: deleteWs } = await import('$lib/apis/state'); await deleteWs(path); workspaceList.update((list) => list.filter((w) => w.path !== path)); workspaceOrder.update((order) => order.filter((p) => p !== path)); // If this was the current workspace, clear it const ws = get(currentWorkspace); if (ws?.path === path) { currentWorkspace.set(null); } } /** Reorder workspaces in the sidebar (from drag-and-drop). */ export function reorderWorkspaces(oldIndex: number, newIndex: number): void { workspaceList.update((list) => { const reordered = [...list]; const [moved] = reordered.splice(oldIndex, 1); reordered.splice(newIndex, 0, moved); // Sync order preference workspaceOrder.set(reordered.map((w) => w.path)); return reordered; }); } export function updateWorkspace(partial: Partial): void { currentWorkspace.update((ws) => { if (!ws) return ws; return { ...ws, ...partial }; }); } // ── Internal: update a group's tabs ───────────────────────────── function updateGroupTabs( groupId: string | undefined, fn: ( tabs: Tab[], group: EditorGroup ) => { tabs: Tab[]; activeTabId?: string; tabHistory?: string[] } ): void { currentWorkspace.update((ws) => { if (!ws) return ws; const gid = groupId ?? ws.activeGroupId; return { ...ws, groups: ws.groups.map((g) => { if (g.id !== gid) return g; const result = fn(g.tabs, g); const newActiveId = result.activeTabId ?? g.activeTabId; const tabHistory = result.tabHistory ?? (newActiveId !== g.activeTabId ? pushTabHistory(g, g.activeTabId) : g.tabHistory); return { ...g, tabs: result.tabs, activeTabId: newActiveId, tabHistory }; }) }; }); } // ── Tab actions (operate on the active group by default) ──────── export function reorderTabs(oldIndex: number, newIndex: number, groupId?: string): void { updateGroupTabs(groupId, (tabs) => { const reordered = [...tabs]; const [moved] = reordered.splice(oldIndex, 1); reordered.splice(newIndex, 0, moved); return { tabs: reordered }; }); } export function openFileTab( filePath: string, targetGroupId?: string, options: { edit?: boolean } = {} ): void { const ws = get(currentWorkspace); if (!ws) return; const gid = targetGroupId ?? ws.activeGroupId; const group = ws.groups.find((g) => g.id === gid); if (!group) return; // Reuse existing tab within this group const existing = group.tabs.find((t) => t.type === 'file' && t.filePath === filePath); if (existing) { if (options.edit) { updateGroupTabs(gid, (tabs) => ({ tabs: tabs.map((t) => (t.id === existing.id ? { ...t, edit: true } : t)), activeTabId: existing.id })); return; } setActiveTab(existing.id, gid); return; } const name = getPathDisplayName(filePath, filePath); const newTab: Tab = { id: nextId(), type: 'file', label: name, filePath, edit: options.edit }; updateGroupTabs(gid, (tabs) => ({ tabs: [...tabs, newTab], activeTabId: newTab.id })); } export function openUntitledFileTab(targetGroupId?: string): void { // Find the lowest unused number across ALL groups const ws = get(currentWorkspace); const allTabs = ws ? ws.groups.flatMap((g) => g.tabs) : []; const usedNumbers = new Set( allTabs .filter((t) => t.filePath?.startsWith('untitled:Untitled-')) .map((t) => parseInt(t.filePath!.replace('untitled:Untitled-', ''), 10)) .filter((n) => !isNaN(n)) ); let n = 1; while (usedNumbers.has(n)) n++; const label = `Untitled-${n}`; const newTab: Tab = { id: nextId(), type: 'file', label, filePath: `untitled:${label}`, unsaved: true }; updateGroupTabs(targetGroupId, (tabs) => ({ tabs: [...tabs, newTab], activeTabId: newTab.id })); } export async function openTerminalTab(targetGroupId?: string): Promise { const ws = get(currentWorkspace); if (!ws) return; try { const data = await createSession(ws.path); const newTab: Tab = { id: nextId(), type: 'terminal', label: 'Terminal', sessionId: data.session_id }; updateGroupTabs(targetGroupId, (tabs) => ({ tabs: [...tabs, newTab], activeTabId: newTab.id })); } catch (e) { console.error('Failed to create terminal:', e); } } export function openPreviewTab(port: number, targetGroupId?: string): void { const ws = get(currentWorkspace); if (!ws) return; const gid = targetGroupId ?? ws.activeGroupId; const group = ws.groups.find((g) => g.id === gid); if (!group) return; // Reuse existing tab within this group const existing = group.tabs.find((t) => t.type === 'preview' && t.port === port); if (existing) { setActiveTab(existing.id, gid); return; } const newTab: Tab = { id: nextId(), type: 'preview', label: `localhost:${port}`, port }; updateGroupTabs(gid, (tabs) => ({ tabs: [...tabs, newTab], activeTabId: newTab.id })); } export function openChatTab(chatId?: string, targetGroupId?: string): void { const ws = get(currentWorkspace); if (!ws) return; const gid = targetGroupId ?? ws.activeGroupId; const group = ws.groups.find((g) => g.id === gid); if (!group) return; // If chatId provided, reuse existing tab if (chatId) { const existing = group.tabs.find((t) => t.type === 'chat' && t.path === chatId); if (existing) { setActiveTab(existing.id, gid); return; } } else { // No chatId — reuse an existing new/pending chat tab if one is open const existing = group.tabs.find( (t) => t.type === 'chat' && (t.path?.startsWith('new-') || t.path?.startsWith('pending-')) ); if (existing) { setActiveTab(existing.id, gid); return; } } const newTab: Tab = { id: nextId(), type: 'chat', label: chatId ? 'Chat' : 'New Chat', path: chatId || `new-${Date.now()}` }; updateGroupTabs(gid, (tabs) => ({ tabs: [...tabs, newTab], activeTabId: newTab.id })); } export function closeTab(tabId: string, groupId?: string): void { const ws = get(currentWorkspace); if (!ws) return; // Find the group containing this tab const gid = groupId ?? ws.groups.find((g) => g.tabs.some((t) => t.id === tabId))?.id ?? ws.activeGroupId; const group = ws.groups.find((g) => g.id === gid); if (!group) return; const tab = group.tabs.find((t) => t.id === tabId); if (!tab || tab.permanent) return; if (tab.type === 'terminal' && tab.sessionId) { deleteSession(tab.sessionId); } // Clean up streaming indicator for closed chat tabs if (tab.type === 'chat') { streamingChatTabs.update((s) => { const n = new Set(s); n.delete(tabId); return n; }); } currentWorkspace.update((ws) => { if (!ws) return ws; let newGroups = ws.groups.map((g) => { if (g.id !== gid) return g; const newTabs = g.tabs.filter((t) => t.id !== tabId); const tabIdSet = new Set(newTabs.map((t) => t.id)); let newActiveId = g.activeTabId; if (newActiveId === tabId) { // Walk back through MRU history const history = g.tabHistory ?? []; let found = false; for (let i = history.length - 1; i >= 0; i--) { if (tabIdSet.has(history[i])) { newActiveId = history[i]; found = true; break; } } if (!found) { const idx = g.tabs.findIndex((t) => t.id === tabId); newActiveId = newTabs[Math.max(0, idx - 1)]?.id ?? newTabs[0]?.id ?? ''; } } const tabHistory = (g.tabHistory ?? []).filter((id) => id !== tabId); return { ...g, tabs: newTabs, activeTabId: newActiveId, tabHistory }; }); // Remove empty non-primary groups (groups with no tabs collapse) newGroups = newGroups.filter((g) => g.tabs.length > 0); if (newGroups.length === 0) { newGroups = [createDefaultGroup()]; } // If active group was removed, switch to first remaining const activeGroupStillExists = newGroups.some((g) => g.id === ws.activeGroupId); return { ...ws, groups: newGroups, activeGroupId: activeGroupStillExists ? ws.activeGroupId : newGroups[0].id }; }); } export function setActiveTab(tabId: string, groupId?: string): void { currentWorkspace.update((ws) => { if (!ws) return ws; const gid = groupId ?? ws.activeGroupId; return { ...ws, activeGroupId: gid, // Clicking a tab in a group focuses that group groups: ws.groups.map((g) => { if (g.id !== gid) return g; if (g.activeTabId === tabId) return g; return { ...g, activeTabId: tabId, tabHistory: pushTabHistory(g, g.activeTabId) }; }) }; }); } export function setActiveGroup(groupId: string): void { currentWorkspace.update((ws) => (ws ? { ...ws, activeGroupId: groupId } : ws)); } export function setFileBrowserCwd(cwd: string): void { currentWorkspace.update((ws) => (ws ? { ...ws, fileBrowserCwd: cwd } : ws)); } export function markTabUnsaved(tabId: string, unsaved: boolean): void { currentWorkspace.update((ws) => { if (!ws) return ws; return { ...ws, groups: ws.groups.map((g) => ({ ...g, tabs: g.tabs.map((t) => (t.id === tabId ? { ...t, unsaved } : t)) })) }; }); } export function updateTabFilePath(tabId: string, newPath: string): void { const name = getPathDisplayName(newPath, newPath); currentWorkspace.update((ws) => { if (!ws) return ws; return { ...ws, groups: ws.groups.map((g) => ({ ...g, tabs: g.tabs.map((t) => t.id === tabId ? { ...t, filePath: newPath, label: name, unsaved: false } : t ) })) }; }); } export function clearTabEdit(tabId: string): void { currentWorkspace.update((ws) => { if (!ws) return ws; return { ...ws, groups: ws.groups.map((g) => ({ ...g, tabs: g.tabs.map((t) => { if (t.id !== tabId || !t.edit) return t; const next = { ...t }; delete next.edit; return next; }) })) }; }); } // ── Split / Editor Group actions ──────────────────────────────── /** Open a file in a new split group (creates the group if needed) */ export function openInSplit(filePath: string, direction?: SplitDirection): void { const ws = get(currentWorkspace); if (!ws) return; const dir = direction ?? ws.splitDirection ?? 'horizontal'; // If there's already a second group, open in it if (ws.groups.length > 1) { const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId); if (otherGroup) { openFileTab(filePath, otherGroup.id); return; } } // Create a new group with this file const name = getPathDisplayName(filePath, filePath); const newTab: Tab = { id: nextId(), type: 'file', label: name, filePath }; const newGroup: EditorGroup = { id: nextId(), tabs: [newTab], activeTabId: newTab.id }; currentWorkspace.update((ws) => { if (!ws) return ws; return { ...ws, groups: [...ws.groups, newGroup], activeGroupId: newGroup.id, splitDirection: dir, splitRatio: ws.splitRatio ?? 0.5 }; }); } /** Split the current active tab into a new group */ export function splitCurrentTab(direction?: SplitDirection): void { const ws = get(currentWorkspace); if (!ws) return; const group = ws.groups.find((g) => g.id === ws.activeGroupId); if (!group) return; const tab = group.tabs.find((t) => t.id === group.activeTabId); if (!tab) return; const dir = direction ?? ws.splitDirection ?? 'horizontal'; // If already split, focus the other group if (ws.groups.length > 1) { const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId); if (otherGroup) { setActiveGroup(otherGroup.id); return; } } // Copy the tab into a new group const newTab: Tab = { ...tab, id: nextId(), permanent: false }; const newGroup: EditorGroup = { id: nextId(), tabs: [newTab], activeTabId: newTab.id }; currentWorkspace.update((ws) => { if (!ws) return ws; return { ...ws, groups: [...ws.groups, newGroup], activeGroupId: newGroup.id, splitDirection: dir, splitRatio: ws.splitRatio ?? 0.5 }; }); } /** Close an entire editor group */ export function closeGroup(groupId: string): void { currentWorkspace.update((ws) => { if (!ws) return ws; const closingGroup = ws.groups.find((g) => g.id === groupId); const remainingGroups = ws.groups.filter((g) => g.id !== groupId); const targetGroup = remainingGroups.find((g) => g.id === ws.activeGroupId) ?? remainingGroups[0]; if (!closingGroup || !targetGroup) return ws; const existingTabIds = new Set(targetGroup.tabs.map((t) => t.id)); const movedTabs = closingGroup.tabs.filter((t) => !existingTabIds.has(t.id)); const tabs = [...targetGroup.tabs, ...movedTabs]; const activeTabId = ws.activeGroupId === closingGroup.id && tabs.some((t) => t.id === closingGroup.activeTabId) ? closingGroup.activeTabId : targetGroup.activeTabId; const newGroups = remainingGroups.map((g) => g.id === targetGroup.id ? { ...g, tabs, activeTabId: tabs.some((t) => t.id === activeTabId) ? activeTabId : (tabs[0]?.id ?? '') } : g ); return { ...ws, groups: newGroups, activeGroupId: targetGroup.id }; }); } /** Move a tab from one group to another */ export function moveTabToGroup(tabId: string, fromGroupId: string, toGroupId: string): void { currentWorkspace.update((ws) => { if (!ws) return ws; const fromGroup = ws.groups.find((g) => g.id === fromGroupId); if (!fromGroup) return ws; const tab = fromGroup.tabs.find((t) => t.id === tabId); if (!tab) return ws; let newGroups = ws.groups.map((g) => { if (g.id === fromGroupId) { const newTabs = g.tabs.filter((t) => t.id !== tabId); const newActiveId = g.activeTabId === tabId ? (newTabs[0]?.id ?? 'files') : g.activeTabId; return { ...g, tabs: newTabs, activeTabId: newActiveId }; } if (g.id === toGroupId) { return { ...g, tabs: [...g.tabs, tab], activeTabId: tab.id }; } return g; }); // Remove empty non-primary groups newGroups = newGroups.filter((g) => g.tabs.length > 0); if (newGroups.length === 0) newGroups = [createDefaultGroup()]; const targetGroupStillExists = newGroups.some((g) => g.id === toGroupId); return { ...ws, groups: newGroups, activeGroupId: targetGroupStillExists ? toGroupId : newGroups[0].id }; }); } export function moveTabToNewSplit( tabId: string, fromGroupId: string, direction: SplitDirection, placement: 'before' | 'after' = 'after' ): void { currentWorkspace.update((ws) => { if (!ws || ws.groups.length > 1) return ws; const fromGroup = ws.groups.find((g) => g.id === fromGroupId); if (!fromGroup) return ws; const tab = fromGroup.tabs.find((t) => t.id === tabId); if (!tab || tab.permanent) return ws; const newGroup: EditorGroup = { id: nextId(), tabs: [tab], activeTabId: tab.id }; let groups = ws.groups.map((g) => { if (g.id !== fromGroupId) return g; const tabs = g.tabs.filter((t) => t.id !== tabId); return { ...g, tabs, activeTabId: tabs[0]?.id ?? '' }; }); groups = groups.filter((g) => g.tabs.length > 0); return { ...ws, groups: placement === 'before' ? [newGroup, ...groups] : [...groups, newGroup], activeGroupId: newGroup.id, splitDirection: direction, splitRatio: ws.splitRatio ?? 0.5 }; }); } export function setSplitDirection(direction: SplitDirection): void { currentWorkspace.update((ws) => (ws ? { ...ws, splitDirection: direction } : ws)); } export function setSplitRatio(ratio: number): void { currentWorkspace.update((ws) => ws ? { ...ws, splitRatio: Math.max(0.2, Math.min(0.8, ratio)) } : ws ); }