mirror of
https://github.com/open-webui/computer.git
synced 2026-11-23 06:00:43 -05:00
921 lines
28 KiB
TypeScript
921 lines
28 KiB
TypeScript
/**
|
|
* 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';
|
|
|
|
// ── Types ───────────────────────────────────────────────────────
|
|
|
|
export interface Tab {
|
|
id: string;
|
|
type: 'files' | 'terminal' | 'file' | 'git' | 'chat' | 'preview';
|
|
label: string;
|
|
filePath?: string;
|
|
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;
|
|
sidebarOpen: boolean;
|
|
sidebarWidth: number;
|
|
toolApprovalMode: ToolApprovalMode;
|
|
locale: string;
|
|
workspaceOrder?: string[]; // ordered paths for sidebar drag-reorder
|
|
}
|
|
|
|
export type Theme = 'dark' | 'light' | 'system';
|
|
|
|
// ── 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 = path.split('/').filter(Boolean).pop() || 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<WorkspaceState | null>(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 >= 768 : false);
|
|
export const sidebarWidth = writable(220);
|
|
export const theme = writable<Theme>('dark');
|
|
export const toolApprovalMode = writable<ToolApprovalMode>('auto');
|
|
/** @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<StreamingBehavior>('queue');
|
|
|
|
/** Saved workspace path order for sidebar drag-reorder. */
|
|
export const workspaceOrder = writable<string[]>([]);
|
|
|
|
// ── 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 splitCurrentTab or openInGroup */
|
|
export function openTabInSplit(tabId: string, direction?: SplitDirection): void {
|
|
const ws = get(currentWorkspace);
|
|
if (!ws) return;
|
|
|
|
// If already split, move tab to the other group
|
|
if (ws.groups.length > 1) {
|
|
const otherGroup = ws.groups.find((g) => g.id !== ws.activeGroupId);
|
|
if (otherGroup) {
|
|
moveTabToGroup(tabId, ws.activeGroupId, otherGroup.id);
|
|
return;
|
|
}
|
|
}
|
|
|
|
// Otherwise, create a new group with this tab
|
|
const dir = direction ?? ws.splitDirection ?? 'horizontal';
|
|
|
|
// Find the tab in any group
|
|
let sourceTab: Tab | undefined;
|
|
for (const g of ws.groups) {
|
|
sourceTab = g.tabs.find((t) => t.id === tabId);
|
|
if (sourceTab) break;
|
|
}
|
|
if (!sourceTab) return;
|
|
|
|
const newTab: Tab = { ...sourceTab, 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,
|
|
};
|
|
});
|
|
}
|
|
|
|
/** @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<typeof setTimeout> | null = null;
|
|
let _savePrefTimer: ReturnType<typeof setTimeout> | 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<string, unknown>).catch(() => {});
|
|
}, 300);
|
|
}
|
|
|
|
function persistPreferences(): void {
|
|
if (_savePrefTimer) clearTimeout(_savePrefTimer);
|
|
_savePrefTimer = setTimeout(() => {
|
|
const prefs: UserPreferences = {
|
|
theme: get(theme),
|
|
sidebarOpen: get(sidebarOpen),
|
|
sidebarWidth: get(sidebarWidth),
|
|
toolApprovalMode: get(toolApprovalMode),
|
|
locale: i18next.language,
|
|
workspaceOrder: get(workspaceOrder),
|
|
};
|
|
savePreferences(prefs as unknown as Record<string, unknown>).catch(() => {});
|
|
}, 300);
|
|
}
|
|
|
|
let _subscribed = false;
|
|
function subscribeForPersistence() {
|
|
if (_subscribed) return;
|
|
_subscribed = true;
|
|
currentWorkspace.subscribe(() => { if (get(stateLoaded)) persistWorkspace(); });
|
|
theme.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
|
|
sidebarOpen.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
|
|
sidebarWidth.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
|
|
toolApprovalMode.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
|
|
workspaceOrder.subscribe(() => { if (get(stateLoaded)) persistPreferences(); });
|
|
i18next.on('languageChanged', () => { if (get(stateLoaded)) persistPreferences(); });
|
|
}
|
|
|
|
// ── Load preferences (called once at app startup) ───────────────
|
|
|
|
export async function loadPreferences(): Promise<void> {
|
|
try {
|
|
const prefs = await getPreferences();
|
|
if (prefs.theme) theme.set(prefs.theme as Theme);
|
|
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.locale) changeLocale(prefs.locale as string);
|
|
if (Array.isArray(prefs.workspaceOrder)) workspaceOrder.set(prefs.workspaceOrder as string[]);
|
|
} catch {
|
|
// First run, no preferences yet
|
|
}
|
|
}
|
|
|
|
// ── Load workspace list (called once at app startup) ────────────
|
|
|
|
export async function loadWorkspaceList(): Promise<void> {
|
|
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<void> {
|
|
try {
|
|
const wsData = await getWorkspaceState(path);
|
|
|
|
if (wsData && wsData.groups && (wsData.groups as EditorGroup[]).length > 0) {
|
|
// Validate terminal sessions are still alive
|
|
let aliveSessions: Set<string> = 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,
|
|
groups,
|
|
activeGroupId,
|
|
splitDirection: ws.splitDirection ?? 'horizontal',
|
|
splitRatio: ws.splitRatio ?? 0.5,
|
|
fileBrowserCwd: ws.fileBrowserCwd ?? path,
|
|
});
|
|
} else {
|
|
// First time opening this workspace, create defaults
|
|
currentWorkspace.set(createDefaultWorkspace(path));
|
|
}
|
|
} catch {
|
|
// Error loading, create fresh workspace
|
|
currentWorkspace.set(createDefaultWorkspace(path));
|
|
}
|
|
}
|
|
|
|
// ── Initialize everything (called once at app startup) ──────────
|
|
|
|
export async function initState(): Promise<void> {
|
|
await loadPreferences();
|
|
await loadWorkspaceList();
|
|
stateLoaded.set(true);
|
|
subscribeForPersistence();
|
|
}
|
|
|
|
/** @deprecated Use initState */
|
|
export const loadStateFromServer = initState;
|
|
|
|
// ── Theme application ───────────────────────────────────────────
|
|
|
|
function applyTheme(t: Theme) {
|
|
if (typeof window === 'undefined') return;
|
|
let resolved = t;
|
|
if (t === 'system') {
|
|
resolved = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
|
|
}
|
|
document.documentElement.classList.toggle('dark', resolved === 'dark');
|
|
document.documentElement.style.colorScheme = resolved;
|
|
const meta = document.querySelector('meta[name="theme-color"]');
|
|
if (meta) meta.setAttribute('content', resolved === 'dark' ? '#0d0d0d' : '#ffffff');
|
|
}
|
|
|
|
theme.subscribe(applyTheme);
|
|
|
|
if (typeof window !== 'undefined') {
|
|
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
|
|
if (get(theme) === 'system') applyTheme('system');
|
|
});
|
|
}
|
|
|
|
// ── 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 = path.split('/').filter(Boolean).pop() || 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<void> {
|
|
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<WorkspaceState>): 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): 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) {
|
|
setActiveTab(existing.id, gid);
|
|
return;
|
|
}
|
|
|
|
const name = filePath.split('/').pop() || filePath;
|
|
const newTab: Tab = {
|
|
id: nextId(),
|
|
type: 'file',
|
|
label: name,
|
|
filePath,
|
|
};
|
|
|
|
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<void> {
|
|
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;
|
|
}
|
|
}
|
|
|
|
const newTab: Tab = {
|
|
id: nextId(),
|
|
type: 'chat',
|
|
label: '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 = newPath.split('/').pop() || 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
|
|
),
|
|
})),
|
|
};
|
|
});
|
|
}
|
|
|
|
// ── 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 = filePath.split('/').pop() || 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;
|
|
|
|
// Clean up terminal sessions in this group
|
|
const group = ws.groups.find((g) => g.id === groupId);
|
|
if (group) {
|
|
group.tabs.forEach((t) => {
|
|
if (t.type === 'terminal' && t.sessionId) deleteSession(t.sessionId);
|
|
});
|
|
}
|
|
|
|
let newGroups = ws.groups.filter((g) => g.id !== groupId);
|
|
if (newGroups.length === 0) {
|
|
newGroups = [createDefaultGroup()];
|
|
}
|
|
const activeGroupStillExists = newGroups.some((g) => g.id === ws.activeGroupId);
|
|
return {
|
|
...ws,
|
|
groups: newGroups,
|
|
activeGroupId: activeGroupStillExists ? ws.activeGroupId : newGroups[0].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 activeGroupStillExists = newGroups.some((g) => g.id === ws.activeGroupId);
|
|
return {
|
|
...ws,
|
|
groups: newGroups,
|
|
activeGroupId: activeGroupStillExists ? ws.activeGroupId : newGroups[0].id,
|
|
};
|
|
});
|
|
}
|
|
|
|
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
|
|
);
|
|
}
|