From 10e695004c6f0eed3cd00f70e6a1497ae7e5d6ec Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 15 Nov 2026 17:20:16 +0900 Subject: [PATCH] refac --- src/lib/components/chat/Chat.svelte | 57 +- src/lib/components/chat/MessageInput.svelte | 6 +- src/lib/components/chat/Tabs.svelte | 823 ++++++++++---------- src/lib/components/chat/Tabs/tabs.ts | 82 +- src/lib/stores/chatViewStates.ts | 8 +- src/lib/stores/index.ts | 4 +- src/routes/(app)/+layout.svelte | 2 +- 7 files changed, 507 insertions(+), 475 deletions(-) diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index d8652ffbd6..2349f84f95 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -39,7 +39,7 @@ socket, audioQueue as _audioQueue, showTabs as _showTabs, - sideChatRequest, + chatTabRequest, openEmbeddedChatIds, showCallOverlay as _showCallOverlay, temporaryChatEnabled as _temporaryChatEnabled, @@ -491,7 +491,7 @@ // the list is rebuilt after a debounce, so it can lag behind the block being opened getContents(); if (embedded) onOpenArtifacts?.(code); - else terminalTabs?.openArtifacts(code); + else tabs?.openArtifacts(code); }; // a notes chat has nowhere to show them $: canOpenArtifacts = !embedded || !!onOpenArtifacts; @@ -508,7 +508,7 @@ $: isShared = chat != null && chat.user_id !== $user?.id; $: if (isShared && $showCallOverlay) showCallOverlay.set(false); $: canClone = isShared && ($user?.role === 'admin' || ($user?.permissions?.chat?.import ?? true)); - $: sideChatAllowed = + $: canOpenChatTab = $user?.role === 'admin' || ($user?.role === 'user' && ($user.permissions?.chat?.side_chat ?? false)); let cloning = false; @@ -600,7 +600,7 @@ if (selectedModels.includes('')) throw new Error($i18n.t('Model not selected')); const attachments = [structuredClone(file)]; if (fullWidthTabs) { - terminalTabs?.focusMainChat(); + tabs?.focusMainChat(); await tick(); if (!$showCallOverlay) messageInput?.focus({ preventScroll: true }); } @@ -621,7 +621,7 @@ // Adds text to the composer for the user to review, keeping any draft already there. const draftPrompt = async (text: string) => { if (fullWidthTabs) { - terminalTabs?.focusMainChat(); + tabs?.focusMainChat(); await tick(); } messageInput?.setText(prompt.trim() ? `${prompt.trimEnd()}\n\n${text}` : text); @@ -993,7 +993,7 @@ onDestroy(() => chatLoadController.abort()); const navigateHandler = async () => { loading = true; - terminalTabs?.prepareChatSwitch(); + tabs?.resetForChatSwitch(); const signal = startChatLoad(); modelDefaults = null; cancelBrowserInteractions(); @@ -2178,7 +2178,7 @@ ) { tick().then(async () => { await initNewChat(); - if (initialPage) terminalTabs?.openPageTab({ href: initialPage, label: '' }); + if (initialPage) tabs?.openPageTab({ href: initialPage, label: '' }); }); } @@ -2898,14 +2898,15 @@ } if (destinationFolder?.id) mainChatHref = `/folders/${destinationFolder.id}`; if (keepDraft && !$chatId && !history.currentId && previousHref === mainChatHref) { - terminalTabs?.focusMainChat(); + tabs?.focusMainChat(); return; } - terminalTabs?.prepareChatSwitch(preserveTabs); + if (preserveTabs) tabs?.carryPagesToNewChat(); + else tabs?.resetForChatSwitch(); loading = true; if ( !embedded && - ($showTabs === 'comments' || $showTabs === 'side' || typeof $showTabs === 'object') + ($showTabs === 'comments' || $showTabs === 'chat' || typeof $showTabs === 'object') ) showTabs.set(false); const signal = startChatLoad(); @@ -3189,12 +3190,12 @@ ); await tick(); - if (preserveTabs) terminalTabs?.focusMainChat(); + if (preserveTabs) tabs?.focusMainChat(); messageInput?.focus({ preventScroll: true }); }; const loadChat = async (signal = startChatLoad()) => { - if (chatIdProp && chatIdProp !== $chatId) terminalTabs?.prepareChatSwitch(); + if (chatIdProp && chatIdProp !== $chatId) tabs?.resetForChatSwitch(); if (chatIdProp && chatIdProp !== $chatId) { terminalContext = null; history = { messages: {}, currentId: null }; @@ -4214,7 +4215,7 @@ prompt = ''; }; - let terminalTabs: Tabs; + let tabs: Tabs; let fullWidthTabs = false; let mainChatActive = false; let mainChatStyle = ''; @@ -4376,13 +4377,13 @@ _chatId = createTemporaryChatId($socket?.id); await chatId.set(_chatId); } - if (!_chatId && (tabbed || context?.currentDirectory || terminalTabs?.hasTerminals())) { + if (!_chatId && (tabbed || context?.currentDirectory || tabs?.hasTerminalTabs())) { _chatId = await initChatHandler(_history); } await tick(); } if (history !== _history) return null; - if (_chatId) await terminalTabs?.bindTerminalChat(_chatId); + if (_chatId) await tabs?.attachChatViewTo(_chatId); if (history !== _history || $chatId !== _chatId) return null; // Also covers temporary/embedded chats and retries after a failed initialization. if (_chatId) await initializeTerminalDirectory(_chatId, context); @@ -4433,21 +4434,21 @@ messageInput?.openComments(); return { status: 'rejected' }; } - const sideCommand = String(userPrompt) + const chatTabCommand = String(userPrompt) .trim() .match(/^\/(?:side|btw)(?:\s+([\s\S]*))?$/i); - if (sideCommand && !sideChatAllowed) { + if (chatTabCommand && !canOpenChatTab) { toast.error($i18n.t('You do not have permission to use side chat.')); return { status: 'rejected' }; } - if (sideCommand && !embedded && $chatId && history.currentId) { + if (chatTabCommand && !embedded && $chatId && history.currentId) { if (selectedModels.length !== 1 || !selectedModelIds[0]) { toast.error($i18n.t('Select only one model to open a side chat.')); return { status: 'rejected' }; } clearCommandInput(); - sideChatRequest.set({ parentId: $chatId, prompt: sideCommand[1] ?? '' }); - showTabs.set('side'); + chatTabRequest.set({ parentChatId: $chatId, prompt: chatTabCommand[1] ?? '' }); + showTabs.set('chat'); return { status: 'rejected' }; } if (String(userPrompt).trim() === '/fork') { @@ -5789,9 +5790,9 @@ id={chatContainerId} data-chat={embedded ? instanceId : 'main'} role="presentation" - on:dragover|capture={(event) => terminalTabs?.dragOverChat(event)} - on:drop|capture={(event) => terminalTabs?.dropChat(event)} - on:dragleave={(event) => terminalTabs?.leaveChatDrop(event)} + on:dragover|capture={(event) => tabs?.handleChatDragOver(event)} + on:drop|capture={(event) => tabs?.handleChatDrop(event)} + on:dragleave={(event) => tabs?.handleChatDragLeave(event)} >
{#if backgroundImage} @@ -5811,8 +5812,8 @@ style={fullWidthTabs ? mainChatStyle : undefined} data-main-chat-pane data-panel-group={fullWidthTabs ? mainChatGroupId : undefined} - on:focusin={() => fullWidthTabs && terminalTabs?.focusMainChat()} - on:pointerdown={() => fullWidthTabs && terminalTabs?.focusMainChat()} + on:focusin={() => fullWidthTabs && tabs?.focusMainChat()} + on:pointerdown={() => fullWidthTabs && tabs?.focusMainChat()} id={fullWidthTabs ? 'chat-panel-main-chat-view' : undefined} role={fullWidthTabs ? 'tabpanel' : undefined} aria-labelledby={fullWidthTabs ? 'chat-panel-main-chat' : undefined} @@ -6281,15 +6282,15 @@ tabActions={loading ? undefined : !$chatId && $selectedFolder ? folderTabActions : tabActions} tabBarActions={loading ? undefined : tabBarActions} {terminalContext} - bind:history + bind:chatHistory={history} bind:files chatId={$chatId} mainArtifacts={artifacts} - bind:this={terminalTabs} + bind:this={tabs} folderId={chat ? (chat.folder_id ?? null) : ($selectedFolder?.id ?? null)} chatUser={chatOwner} modelId={selectedModelIds?.at(0) ?? null} - canBranchChat={sideChatAllowed} + {canOpenChatTab} systemPrompt={params?.system || $settings.system || ''} submitPrompt={submitHandler} onAskFile={askFile} diff --git a/src/lib/components/chat/MessageInput.svelte b/src/lib/components/chat/MessageInput.svelte index f766b35f12..bcd7e84a96 100644 --- a/src/lib/components/chat/MessageInput.svelte +++ b/src/lib/components/chat/MessageInput.svelte @@ -47,7 +47,7 @@ showFileNavDir, TTSWorker, temporaryChatEnabled, - sideChatRequest, + chatTabRequest, visibleControls } from '$lib/stores'; @@ -1753,8 +1753,8 @@ onComments: openComments, onSide: () => { if (!canSide) return; - sideChatRequest.set({ parentId: chatId, prompt: '' }); - showTabs.set('side'); + chatTabRequest.set({ parentChatId: chatId, prompt: '' }); + showTabs.set('chat'); }, onFork: forkHandler, onModel: () => modelSelector?.open(), diff --git a/src/lib/components/chat/Tabs.svelte b/src/lib/components/chat/Tabs.svelte index 388b7e73ca..bcca11d9f9 100644 --- a/src/lib/components/chat/Tabs.svelte +++ b/src/lib/components/chat/Tabs.svelte @@ -34,7 +34,7 @@ temporaryChatEnabled, terminalServers, showTabs, - sideChatRequest, + chatTabRequest, showOverview, showSidebar, mobile, @@ -55,25 +55,25 @@ import { page } from '$app/stores'; import { - emptyTabs, + createTabsState, openTab, - openTabInSidePanel, + openTabInSplit, activateTab, removeTab, moveTab, moveTabToGroup, splitTab, resizeSplit, - panelPositions, - type PanelGroup, - type PanelRect, - type PanelDivider, + getLayoutRects, + type TabGroup, + type GroupRect, + type SplitDivider, type SplitEdge, mainChatTabId, setMainChatTab, setSplitTabs, fileTabId, - type PanelTab + type Tab } from './Tabs/tabs'; import { resolveTerminalTarget, @@ -126,7 +126,7 @@ const i18n = getContext('i18n'); const appLayout = getContext('appLayout'); - export let history: any = { messages: {}, currentId: null }; + export let chatHistory: any = { messages: {}, currentId: null }; export let chatId: string | null = null; export let chatLoading = false; @@ -149,7 +149,7 @@ export let files: any[] = []; export let modelId: string | null = null; export let systemPrompt = ''; - export let canBranchChat = false; + export let canOpenChatTab = false; $: canOpenChat = $user?.role === 'admin' || $user?.role === 'user'; export let codeInterpreterEnabled = false; @@ -166,24 +166,24 @@ null; /** Double-clicking the folder tab renames the folder inline. */ export let onRenameFolder: ((folderId: string, name: string) => Promise) | null = null; - let renamingFolder = false; + let isRenamingFolder = false; let folderNameDraft = ''; const startFolderRename = async () => { if (!mainTabFolder?.canEdit || !onRenameFolder) return; folderNameDraft = mainTabFolder.name; - renamingFolder = true; + isRenamingFolder = true; await tick(); const input = document.querySelector('[data-folder-tab-rename]'); input?.focus(); input?.select(); }; const saveFolderRename = async () => { - if (!renamingFolder || !mainTabFolder) return; - renamingFolder = false; + if (!isRenamingFolder || !mainTabFolder) return; + isRenamingFolder = false; const name = folderNameDraft.trim(); if (name && name !== mainTabFolder.name) await onRenameFolder?.(mainTabFolder.id, name); }; - $: if (!mainTabFolder) renamingFolder = false; + $: if (!mainTabFolder) isRenamingFolder = false; $: mainTabTitle = mainTabFolder?.name ?? title; export let mainChatHref = '/'; export let tabTitleEditor: import('svelte').Snippet | undefined = undefined; @@ -191,16 +191,16 @@ export let onRenameMainTab: (() => void) | null = null; export let tabActions: import('svelte').Snippet | undefined = undefined; export let tabBarActions: import('svelte').Snippet | undefined = undefined; - $: fullWidth = largeScreen; - $: panelVisible = largeScreen || !!$showTabs; + $: fullWidth = isLargeScreen; + $: panelVisible = isLargeScreen || !!$showTabs; - let largeScreen = false; - let dragged = false; - let mounted = false; + let isLargeScreen = false; + let isDragging = false; + let isMounted = false; let viewportWidth = 0; - let tabs = emptyTabs(); - const paneStyle = (rect: PanelRect, header = 0) => + let tabs = createTabsState(); + const toPaneStyle = (rect: GroupRect, header = 0) => `position:absolute;left:${rect.left * 100}%;top:calc(100% * ${rect.top} + ${header}px * var(--app-text-scale, 1));width:${rect.width * 100}%;height:calc(100% * ${rect.height} - ${header}px * var(--app-text-scale, 1));`; const focusGroup = (id: string, event?: Event) => { // Tab clicks activate their own group. @@ -211,7 +211,7 @@ let terminalViews: Record = {}; let terminalTitles: Record = {}; let terminalProcesses: Record = {}; - export const hasTerminals = () => tabs.tabs.some((tab) => tab.kind === 'terminal'); + export const hasTerminalTabs = () => tabs.tabs.some((tab) => tab.kind === 'terminal'); let browserViews: Record = {}; let gitViews: Record = {}; let chatViews: Record = {}; @@ -219,69 +219,98 @@ let chatStreamingStates: Record = {}; // Each chat writes its artifacts here; its artifacts tab reads them. const chatArtifacts: Record> = {}; - const chatArtifactsFor = (id: string) => (chatArtifacts[id] ??= writable([])); - const artifactsOf = (sourceTabId = mainChatTabId) => - sourceTabId === mainChatTabId ? mainArtifacts : chatArtifactsFor(sourceTabId); + const getChatArtifacts = (id: string) => (chatArtifacts[id] ??= writable([])); + const getArtifactsStore = (sourceTabId = mainChatTabId) => + sourceTabId === mainChatTabId ? mainArtifacts : getChatArtifacts(sourceTabId); // The code block each artifacts tab was last asked to show. let artifactSelections: Record = {}; - let pendingArtifacts: { code?: string } | null = null; + let queuedArtifactCode: { code?: string } | null = null; let viewEntry: ReturnType | null = null; let viewReady = false; let viewError = ''; - let switchVersion = 0; - let promotion: Promise | null = null; + let restoreRequestId = 0; + let attachInFlight: Promise | null = null; let sessionFailures: Record = {}; let sessionAttempts: Record = {}; export function captureView() { if (!viewEntry || !viewReady) return; - const owner = viewEntry; + const chatView = viewEntry; for (const tab of tabs.tabs) { const draft = fileViews[tab.id]?.captureView?.(); - if (draft) owner.drafts.set(tab.id, draft); - if (gitViews[tab.id]) owner.transient[`git:${tab.id}`] = gitViews[tab.id].captureView(); - if (chatViews[tab.id]) owner.transient[`chat:${tab.id}`] = chatViews[tab.id].captureView(); + if (draft) chatView.drafts.set(tab.id, draft); + if (gitViews[tab.id]) chatView.transient[`git:${tab.id}`] = gitViews[tab.id].captureView(); + if (chatViews[tab.id]) chatView.transient[`chat:${tab.id}`] = chatViews[tab.id].captureView(); } - owner.transient.gitDiffModes = fileGitDiffModes; - owner.transient.gitHideWhitespace = fileGitHideWhitespace; - const panels = { + chatView.transient.gitDiffModes = fileGitDiffModes; + chatView.transient.gitHideWhitespace = fileGitHideWhitespace; + const snapshot = { ...tabs, tabs: tabs.tabs.map((tab) => ({ ...tab, - ...(tab.kind === 'files' && owner.drafts.get(tab.id)?.directory - ? { directory: owner.drafts.get(tab.id).directory } + ...(tab.kind === 'files' && chatView.drafts.get(tab.id)?.directory + ? { directory: chatView.drafts.get(tab.id).directory } : {}) })) }; - changeChatView(owner, { ...owner.state, panels, selectedTerminalId: $selectedTerminalId }); + changeChatView(chatView, { + ...chatView.state, + panels: snapshot, + selectedTerminalId: $selectedTerminalId + }); } let preserveChatView = false; - export function prepareChatSwitch(preserve = false) { + const leaveChatView = () => { stopTerminalChoice?.(false); stopTerminalChoice = null; captureView(); if (viewEntry) void flushChatView(viewEntry); - preserveChatView = preserve && viewReady; - if (preserveChatView) return; + }; + export function resetForChatSwitch() { + leaveChatView(); + preserveChatView = false; viewReady = false; - tabs = emptyTabs(); + tabs = createTabsState(); chatStreamingStates = {}; chatTitleEditors = {}; - pendingArtifacts = null; - ++switchVersion; + queuedArtifactCode = null; + ++restoreRequestId; tabsChatId = undefined; } - export async function bindTerminalChat(id: string) { + /** Starts a new chat that keeps the open pages; everything else stays with the chat being left. */ + export function carryPagesToNewChat() { + if (!viewReady || !$user?.id) return resetForChatSwitch(); + leaveChatView(); + preserveChatView = true; + let carried = tabs; + for (const tab of tabs.tabs) { + if (tab.id !== mainChatTabId && tab.kind !== 'page') carried = removeTab(carried, tab.id); + } + const kept = new Set(carried.tabs.map((tab) => tab.id)); + const keep = (record: Record) => + Object.fromEntries(Object.entries(record).filter(([id]) => kept.has(id))); + dirtyFiles = keep(dirtyFiles); + fileContexts = keep(fileContexts); + chatStreamingStates = {}; + chatTitleEditors = {}; + queuedArtifactCode = null; + const chatView = chatViewEntry($user.id, null, $temporaryChatEnabled); + chatView.state = { ...chatView.state, panels: carried, selectedTerminalId: $selectedTerminalId }; + viewEntry = chatView; + tabs = carried; + hasExtraTabs = carried.tabs.some((tab) => tab.id !== mainChatTabId); + } + export async function attachChatViewTo(id: string) { if (!viewEntry || viewEntry.chatId === id) return; - if (promotion) return promotion; - const owner = viewEntry; + if (attachInFlight) return attachInFlight; + const chatView = viewEntry; captureView(); - promotion = promoteChatView( - owner, + attachInFlight = promoteChatView( + chatView, id, async () => { await tick(); - for (const tab of owner.state.panels.tabs) { + for (const tab of chatView.state.panels.tabs) { if (!tab.sessionId) continue; if (tab.kind === 'terminal') { if (!terminalViews[tab.id]) throw new Error('Terminal is not connected'); @@ -296,71 +325,75 @@ ) .then(() => { tabsChatId = id; - viewEntry = owner; + viewEntry = chatView; preserveChatView = false; viewError = ''; }) .finally(() => { - promotion = null; + attachInFlight = null; }); - return promotion; + return attachInFlight; } async function restoreChatView(id: string | null) { if (!$user?.id) return; - const version = ++switchVersion; + const version = ++restoreRequestId; captureView(); if (viewEntry) void flushChatView(viewEntry); viewReady = false; - tabs = emptyTabs(); + tabs = createTabsState(); viewError = ''; terminalTitles = {}; terminalProcesses = {}; chatStreamingStates = {}; chatTitleEditors = {}; tabsChatId = id; - const owner = chatViewEntry($user.id, id, $temporaryChatEnabled); - viewEntry = owner; + const chatView = chatViewEntry($user.id, id, $temporaryChatEnabled); + viewEntry = chatView; try { - await loadChatView(owner); - if (version !== switchVersion) return; + await loadChatView(chatView); + if (version !== restoreRequestId) return; // The chat restores its terminal and directory together; layouts must not override them. - owner.state.selectedTerminalId = $selectedTerminalId; - owner.state.panels = setMainChatTab(owner.state.panels, true, mainTabTitle); - tabs = owner.state.panels; + chatView.state.selectedTerminalId = $selectedTerminalId; + chatView.state.panels = setMainChatTab(chatView.state.panels, true, mainTabTitle); + tabs = chatView.state.panels; dirtyFiles = {}; fileContexts = {}; fileGitStatuses = {}; - fileGitDiffModes = owner.transient.gitDiffModes ?? {}; - fileGitHideWhitespace = owner.transient.gitHideWhitespace ?? {}; - commentTarget = {}; + fileGitDiffModes = chatView.transient.gitDiffModes ?? {}; + fileGitHideWhitespace = chatView.transient.gitHideWhitespace ?? {}; + commentAnchor = {}; sessionFailures = {}; sessionAttempts = {}; viewReady = true; - hasOpenedTabs = tabs.tabs.some((tab) => tab.id !== mainChatTabId); + hasExtraTabs = tabs.tabs.some((tab) => tab.id !== mainChatTabId); } catch (error) { - if (version === switchVersion) viewError = String(error); + if (version === restoreRequestId) viewError = String(error); } } - const persistPanels = (panels: typeof tabs, selector: string | null, ready: boolean) => { + const persistPanels = ( + nextTabs: typeof tabs, + terminalId: string | null, + ready: boolean + ) => { if (!ready || !viewEntry || chatLoading || viewEntry.promoting) return; // The Files tab follows the terminal picked for the chat and starts over there. - if (selector && selector !== viewEntry.state.selectedTerminalId) { - const moved = panels.tabs.filter( - (tab) => tab.kind === 'files' && tab.terminalId !== selector + if (terminalId && terminalId !== viewEntry.state.selectedTerminalId) { + const moved = nextTabs.tabs.filter( + (tab) => tab.kind === 'files' && tab.terminalId !== terminalId ); for (const tab of moved) { viewEntry.drafts.delete(tab.id); delete fileContexts[tab.id]; } - panels = { - ...panels, - tabs: panels.tabs.map((tab) => + nextTabs = { + ...nextTabs, + tabs: nextTabs.tabs.map((tab) => moved.includes(tab) ? { ...tab, label: $i18n.t('Files'), - terminalId: selector, + terminalId: terminalId, target: undefined, path: undefined, directory: undefined @@ -369,30 +402,34 @@ ) }; } - if (viewEntry.state.panels !== panels || viewEntry.state.selectedTerminalId !== selector) - changeChatView(viewEntry, { ...viewEntry.state, panels, selectedTerminalId: selector }); + if (viewEntry.state.panels !== nextTabs || viewEntry.state.selectedTerminalId !== terminalId) + changeChatView(viewEntry, { + ...viewEntry.state, + panels: nextTabs, + selectedTerminalId: terminalId + }); }; $: persistPanels(tabs, $selectedTerminalId, viewReady); $: if (viewEntry && viewEntry.userId !== $user?.id) { viewReady = false; viewEntry = null; - tabs = emptyTabs(); + tabs = createTabsState(); chatStreamingStates = {}; chatTitleEditors = {}; tabsChatId = undefined; clearChatViews(); } - const captureTargets = (..._connections: unknown[]) => { + const forgetDraftsForUnreachableTerminals = (..._connections: unknown[]) => { captureView(); // A returning component must read disk before restoring its cached draft. for (const tab of tabs.tabs) { - if (tab.terminalId && !terminalAccessible(tab.terminalId)) delete dirtyFiles[tab.id]; + if (tab.terminalId && !isTerminalReachable(tab.terminalId)) delete dirtyFiles[tab.id]; } dirtyFiles = { ...dirtyFiles }; }; - $: if (mounted && viewReady) captureTargets($terminalServers, $settings, $config, $user); - const tabTarget = (tab: PanelTab) => { - if (!tab.terminalId || !terminalAccessible(tab.terminalId)) return null; + $: if (isMounted && viewReady) forgetDraftsForUnreachableTerminals($terminalServers, $settings, $config, $user); + const resolveTabConnection = (tab: Tab) => { + if (!tab.terminalId || !isTerminalReachable(tab.terminalId)) return null; const target = resolveTerminalTarget( tab.terminalId, $terminalServers ?? [], @@ -402,11 +439,11 @@ if (target) tab.target = target; return target; }; - const startSession = (owner: NonNullable, tab: PanelTab) => { - const target = tabTarget(tab); + const startSession = (chatView: NonNullable, tab: Tab) => { + const target = resolveTabConnection(tab); if (target) { delete sessionFailures[tab.id]; - void createViewSession(owner, tab.id, target); + void createViewSession(chatView, tab.id, target); } }; @@ -425,40 +462,40 @@ let fileContexts: Record = {}; let panelTarget: HTMLElement | null = null; let tabsChatId: string | null | undefined = undefined; - let hasOpenedTabs = false; - let commentTarget: { comment_id?: string } = {}; - let closing = new Set(); - let selectedTarget: TerminalTarget | null = null; + let hasExtraTabs = false; + let commentAnchor: { comment_id?: string } = {}; + let closingTabIds = new Set(); + let selectedConnection: TerminalTarget | null = null; let showQuickOpen = false; let voiceNote: VoiceNote; - let voiceNoteTarget: { + let voiceNoteDestination: { target: TerminalTarget; chatId: string | null; directory?: string; } | null = null; - $: canVoiceNote = terminalFilesAvailable && !!$user; + $: canVoiceNote = supportsTerminalFiles && !!$user; $: canTranscribeVoiceNote = $user?.role === 'admin' || ($user?.permissions?.chat?.stt ?? true); const openVoiceNote = () => { - if (voiceNoteTarget) { + if (voiceNoteDestination) { voiceNote?.finishRecording(); return; } - if (!selectedTarget) return askForTerminal(openVoiceNote); + if (!selectedConnection) return askForTerminal(openVoiceNote); if (!canVoiceNote || !$user) return; - voiceNoteTarget = { - target: selectedTarget, + voiceNoteDestination = { + target: selectedConnection, chatId, directory: - activeFileContext?.terminalId === selectedTarget.selector + activeFileContext?.terminalId === selectedConnection.selector ? activeFileContext.currentDirectory : undefined }; }; - $: if (!terminalFilesAvailable) showQuickOpen = false; - let terminalEnabled = false; - let desktopEnabled = false; - let browserEnabled = false; - let featureVersion = 0; + $: if (!supportsTerminalFiles) showQuickOpen = false; + let supportsTerminal = false; + let supportsDesktop = false; + let supportsBrowser = false; + let featureCheckRequestId = 0; let releasePanel: (target: HTMLElement) => void = () => {}; const preservePanel = (target: HTMLElement) => ({ destroy: () => releasePanel(target) }); @@ -500,7 +537,7 @@ home: HomeIcon, channels: HashtagIcon }; - const tabIcon = (kind: PanelTab['kind']) => + const getTabIcon = (kind: Tab['kind']) => ({ chat: 'chat-lines', page: 'page', @@ -514,7 +551,7 @@ voice: 'microphone', comments: 'chat-bubble' })[kind]; - const domId = (id: string) => `chat-panel-${encodeURIComponent(id)}`; + const toTabDomId = (id: string) => `chat-panel-${encodeURIComponent(id)}`; $: activeTabId = tabs.activeId; $: activeTab = tabs.tabs.find((tab) => tab.id === tabs.activeId); $: contextTab = @@ -526,7 +563,7 @@ const id = activeTabId; void tick().then(() => document - .getElementById(domId(id)) + .getElementById(toTabDomId(id)) ?.parentElement?.scrollIntoView({ block: 'nearest', inline: 'nearest' }) ); } @@ -538,7 +575,7 @@ tabs = activateTab(tabs, id); showTabs.set(true); }; - const activateFilesOnDrag = (node: HTMLElement, tab: PanelTab) => { + const activateFilesOnDrag = (node: HTMLElement, tab: Tab) => { if (tab.kind !== 'files') return; let timer: ReturnType | undefined; const clear = () => { @@ -570,9 +607,9 @@ } }; }; - const openPanel = (tab: PanelTab, inSidePanel = false, besideId?: string) => { + const openPanel = (tab: Tab, inSplit = false, besideId?: string) => { if (!viewReady || !viewEntry) return; - hasOpenedTabs = true; + hasExtraTabs = true; if (tab.terminalId) { const target = tab.target ?? @@ -582,11 +619,11 @@ }); tab = { ...tab, target: target ?? undefined }; } - tabs = inSidePanel ? openTabInSidePanel(tabs, tab, besideId) : openTab(tabs, tab); + tabs = inSplit ? openTabInSplit(tabs, tab, besideId) : openTab(tabs, tab); changeChatView(viewEntry, { ...viewEntry.state, panels: tabs }); showTabs.set(true); }; - const createPageTab = (request: { href: string; label: string }): PanelTab => { + const createPageTab = (request: { href: string; label: string }): Tab => { const url = new URL(request.href, location.origin); const chat = url.pathname === '/' || url.pathname.startsWith('/c/'); return { @@ -641,15 +678,15 @@ } const openFiles = ( - selector = $selectedTerminalId, + terminalId = $selectedTerminalId, directory?: string, newTab = false, sourceModelId = modelId ) => { - if (!selector && !showFilesTab) + if (!terminalId && !showFilesTab) return askForTerminal(() => openFiles($selectedTerminalId, directory, newTab, sourceModelId)); - if (selector ? !terminalAccessible(selector) : !showFilesTab) return; - const target = resolveTerminalTarget(selector, $terminalServers ?? [], localStorage.token, { + if (terminalId ? !isTerminalReachable(terminalId) : !showFilesTab) return; + const target = resolveTerminalTarget(terminalId, $terminalServers ?? [], localStorage.token, { chatId: chatId, modelId: sourceModelId ?? null }); @@ -660,23 +697,23 @@ (tab) => tab.id === tabs.activeId && tab.kind === 'files' && - (tab.terminalId ?? null) === selector && + (tab.terminalId ?? null) === terminalId && (tab.target?.context.modelId ?? null) === pinnedModel ) ?? tabs.tabs.find( (tab) => tab.kind === 'files' && - (tab.terminalId ?? null) === selector && + (tab.terminalId ?? null) === terminalId && (tab.target?.context.modelId ?? null) === pinnedModel )); - if (!existing && terminalContext?.terminalId === selector) + if (!existing && terminalContext?.terminalId === terminalId) directory ??= terminalContext.currentDirectory || undefined; const id = existing?.id ?? uuidv4(); openPanel({ id, kind: 'files', label: $i18n.t('Files'), - terminalId: selector ?? undefined, + terminalId: terminalId ?? undefined, target: target ?? undefined, path: directory }); @@ -690,12 +727,12 @@ }; const openFile = ( path: string, - selector: string, + terminalId: string, page?: number | null, sourceModelId = modelId ) => { - if (!terminalAccessible(selector)) return; - const target = resolveTerminalTarget(selector, $terminalServers ?? [], localStorage.token, { + if (!isTerminalReachable(terminalId)) return; + const target = resolveTerminalTarget(terminalId, $terminalServers ?? [], localStorage.token, { chatId: chatId, modelId: sourceModelId ?? null }); @@ -706,89 +743,89 @@ (tab) => tab.kind === 'file' && !tab.untitled && - tab.terminalId === selector && + tab.terminalId === terminalId && (tab.target?.context.modelId ?? null) === pinnedModel && tab.path === path - )?.id ?? fileTabId(JSON.stringify([selector, pinnedModel]), path); + )?.id ?? fileTabId(JSON.stringify([terminalId, pinnedModel]), path); openPanel({ id, kind: 'file', label: path.split('/').pop() || path, - terminalId: selector, + terminalId: terminalId, target: target ?? undefined, path, page }); if (page != null) fileViews[id]?.revealPage?.(page); }; - const newFile = () => { - if (!selectedTarget) return askForTerminal(newFile); + const openNewFileTab = () => { + if (!selectedConnection) return askForTerminal(openNewFileTab); let number = 1; while (tabs.tabs.some((tab) => tab.untitled && tab.label === `Untitled-${number}`)) number++; openPanel({ id: uuidv4(), kind: 'file', label: `Untitled-${number}`, - terminalId: selectedTarget.selector, - target: { ...selectedTarget }, + terminalId: selectedConnection.selector, + target: { ...selectedConnection }, untitled: true, context: - activeFileContext?.terminalId === selectedTarget.selector ? activeFileContext : undefined + activeFileContext?.terminalId === selectedConnection.selector ? activeFileContext : undefined }); }; /** Opens the artifacts tab of the chat in `sourceTabId` beside that chat. */ - export const openArtifacts = (code?: string, sourceTabId = mainChatTabId, inSidePanel = true) => { + export const openArtifacts = (code?: string, sourceTabId = mainChatTabId, inSplit = true) => { if (!$visibleControls['chat.artifacts']) return; if (sourceTabId === mainChatTabId && !viewReady) { // the chat's messages can render before its tabs are restored - pendingArtifacts = { code }; + queuedArtifactCode = { code }; return; } - if (!get(artifactsOf(sourceTabId)).length) return; + if (!get(getArtifactsStore(sourceTabId)).length) return; const id = `artifacts:${sourceTabId}`; if (code) artifactSelections = { ...artifactSelections, [id]: { code } }; openPanel( { id, kind: 'artifacts', label: $i18n.t('Artifacts'), sourceTabId }, - inSidePanel, + inSplit, sourceTabId ); }; - $: if (viewReady && pendingArtifacts) { - const { code } = pendingArtifacts; - pendingArtifacts = null; + $: if (viewReady && queuedArtifactCode) { + const { code } = queuedArtifactCode; + queuedArtifactCode = null; openArtifacts(code); } - const openFeature = ( + const openFeatureTab = ( kind: 'artifacts' | 'preview' | 'voice' | 'comments' | 'chat', - inSidePanel = false + inSplit = false ) => { if (!availableViews.some((view) => view.kind === kind && view.available)) return; - if (kind === 'artifacts') return openArtifacts(undefined, mainChatTabId, inSidePanel); + if (kind === 'artifacts') return openArtifacts(undefined, mainChatTabId, inSplit); const view = availableViews.find((view) => view.kind === kind)!; if (kind === 'chat') { let chatNumber = 1; while (tabs.tabs.some((tab) => tab.kind === 'chat' && tab.chatNumber === chatNumber)) chatNumber++; - const pending = $sideChatRequest; - const initialPrompt = pending?.parentId === chatId ? pending.prompt : ''; - if (pending?.parentId === chatId) sideChatRequest.set(null); + const pending = $chatTabRequest; + const initialPrompt = pending?.parentChatId === chatId ? pending.prompt : ''; + if (pending?.parentChatId === chatId) chatTabRequest.set(null); openPanel( { id: uuidv4(), kind, label: `${view.label} ${chatNumber}`, chatNumber, - parentChatId: pending?.parentId === chatId ? (chatId ?? undefined) : undefined, + parentChatId: pending?.parentChatId === chatId ? (chatId ?? undefined) : undefined, initialPrompt }, - inSidePanel + inSplit ); return; } - openPanel({ id: kind, kind, label: view.label }, inSidePanel); + openPanel({ id: kind, kind, label: view.label }, inSplit); }; - type SplitDrop = PanelRect & { groupId: string; edge: SplitEdge | null }; + type SplitDrop = GroupRect & { groupId: string; edge: SplitEdge | null }; let chatDropPreview: SplitDrop | null = null; let draggedTabId = ''; let pendingTabDrop: (() => void) | null = null; @@ -801,7 +838,7 @@ ($user?.permissions?.chat?.temporary_enforced ?? false) )) && event.dataTransfer?.types.includes('application/x-open-webui-chat'); - const chatDropBounds = ( + const getChatDropZone = ( event: Pick ): SplitDrop | null => { const internal = @@ -839,7 +876,7 @@ } const edge = edges.sort((a, b) => a.distance - b.distance)[0]?.edge ?? null; if (main && !edge) { - if (!$showTabs && largeScreen) return null; + if (!$showTabs && isLargeScreen) return null; if (internal || event.clientX < rect.right - rect.width * 0.3) return null; return { groupId: tabs.activeGroupId, @@ -863,8 +900,8 @@ top: rect.top + (edge === 'bottom' ? height : 0) }; }; - export const dragOverChat = (event: DragEvent) => { - chatDropPreview = chatDropBounds(event); + export const handleChatDragOver = (event: DragEvent) => { + chatDropPreview = getChatDropZone(event); if (chatDropPreview || event.dataTransfer?.types.includes('Files')) event.preventDefault(); if (chatDropPreview) event.dataTransfer!.dropEffect = @@ -873,12 +910,12 @@ ? 'move' : 'copy'; }; - export const leaveChatDrop = (event: DragEvent) => { + export const handleChatDragLeave = (event: DragEvent) => { if (!(event.currentTarget as HTMLElement).contains(event.relatedTarget as Node)) clearChatDropPreview(); }; - export const dropChat = (event: DragEvent) => { - const bounds = chatDropBounds(event); + export const handleChatDrop = (event: DragEvent) => { + const bounds = getChatDropZone(event); clearChatDropPreview(); if ( event.dataTransfer?.types.includes('Files') && @@ -891,7 +928,7 @@ if (!bounds || pendingTabDrop) return; const internalId = event.dataTransfer?.getData('application/x-chat-panel-tab'); let savedId = ''; - let droppedPage: PanelTab | null = null; + let droppedPage: Tab | null = null; if (internalId) { if (!tabs.tabs.some((tab) => tab.id === internalId)) return; } else if (event.dataTransfer?.types.includes('application/x-open-webui-page')) { @@ -944,7 +981,7 @@ }; if (internalId) { // Let Sortable restore its source DOM before changing the keyed tab groups. - tabDropHandled = true; + isTabDropHandled = true; pendingTabDrop = applyDrop; } else { event.stopPropagation(); @@ -952,11 +989,11 @@ } }; - let resizingSplit: PanelDivider | null = null; - const startSplitResize = (event: PointerEvent, divider: PanelDivider) => { + let resizingSplit: SplitDivider | null = null; + const startSplitResize = (event: PointerEvent, divider: SplitDivider) => { event.preventDefault(); resizingSplit = divider; - dragged = true; + isDragging = true; (event.currentTarget as HTMLElement).setPointerCapture(event.pointerId); }; const moveSplitResize = (event: PointerEvent) => { @@ -971,10 +1008,10 @@ }; const endSplitResize = () => { resizingSplit = null; - dragged = false; + isDragging = false; }; - const newTerminal = () => { - if (!selectedTarget) return askForTerminal(newTerminal); + const openNewTerminalTab = () => { + if (!selectedConnection) return askForTerminal(openNewTerminalTab); let terminalNumber = 1; while ( tabs.tabs.some((tab) => tab.kind === 'terminal' && tab.terminalNumber === terminalNumber) @@ -987,22 +1024,22 @@ kind: 'terminal', label: `${$i18n.t('Terminal')} ${terminalNumber}`, terminalNumber, - terminalId: selectedTarget.selector, - target: { ...selectedTarget } + terminalId: selectedConnection.selector, + target: { ...selectedConnection } }); if (viewEntry && viewReady) startSession(viewEntry, tabs.tabs.find((tab) => tab.id === id)!); }; const openDesktop = () => { - if (!selectedTarget) return askForTerminal(openDesktop); + if (!selectedConnection) return askForTerminal(openDesktop); openPanel({ - id: JSON.stringify(['desktop', selectedTarget.baseUrl, selectedTarget.context.modelId]), + id: JSON.stringify(['desktop', selectedConnection.baseUrl, selectedConnection.context.modelId]), kind: 'desktop', label: $i18n.t('Desktop'), - terminalId: selectedTarget.selector, - target: { ...selectedTarget } + terminalId: selectedConnection.selector, + target: { ...selectedConnection } }); }; - const browserBaseUrl = (target: TerminalTarget) => { + const getBrowserBaseUrl = (target: TerminalTarget) => { const terminal = ($terminalServers ?? []).find((item) => item.id === target.selector); return chatContextNeedsSavedChat(terminal) && target.context.chatId ? `${target.baseUrl}/chats/${encodeURIComponent(target.context.chatId)}` @@ -1010,35 +1047,35 @@ }; const openBrowser = ( port?: number, - selector = $selectedTerminalId, + terminalId = $selectedTerminalId, baseUrl?: string, initialUrl?: string ) => { - if (!selector) + if (!terminalId) return askForTerminal(() => openBrowser(port, $selectedTerminalId, baseUrl, initialUrl)); - if (!terminalAccessible(selector)) return; + if (!isTerminalReachable(terminalId)) return; const url = initialUrl ?? (port ? `http://localhost:${port}/` : undefined); const existing = url && tabs.tabs.find( (tab) => tab.kind === 'browser' && - tab.terminalId === selector && + tab.terminalId === terminalId && tab.path === url && - (tab.target?.context.modelId ?? null) === (selectedTarget?.context.modelId ?? null) + (tab.target?.context.modelId ?? null) === (selectedConnection?.context.modelId ?? null) ); if (existing) { selectTab(existing.id); return; } - const target = selector - ? resolveTerminalTarget(selector, $terminalServers ?? [], localStorage.token ?? '', { + const target = terminalId + ? resolveTerminalTarget(terminalId, $terminalServers ?? [], localStorage.token ?? '', { chatId: chatId, modelId: modelId ?? null }) : null; if (!target) return; - const terminal = ($terminalServers ?? []).find((item) => item.id === selector); + const terminal = ($terminalServers ?? []).find((item) => item.id === terminalId); const proxyBase = baseUrl ?? (target && chatContextNeedsSavedChat(terminal) && chatId @@ -1050,7 +1087,7 @@ kind: 'browser', label: port ? `localhost:${port}` : $i18n.t('Browser'), path: url, - terminalId: selector ?? undefined, + terminalId: terminalId ?? undefined, browserBaseUrl: proxyBase, target: target ?? undefined }); @@ -1058,18 +1095,18 @@ }; const closeTab = async (id: string) => { if (id === mainChatTabId) return; - if (closing.has(id)) return; - const owner = viewEntry; - if (!owner) return; - closing.add(id); + if (closingTabIds.has(id)) return; + const chatView = viewEntry; + if (!chatView) return; + closingTabIds.add(id); try { - await owner.pending.get(id); - const tab = owner.state.panels.tabs.find((item) => item.id === id); + await chatView.pending.get(id); + const tab = chatView.state.panels.tabs.find((item) => item.id === id); if (!tab) return; if (tab.kind === 'page' && !((await pageViews[id]?.requestClose()) ?? true)) return; const target = tab.sessionId && (tab.kind === 'terminal' || tab.kind === 'browser') - ? tabTarget(tab) + ? resolveTabConnection(tab) : null; if ( target && @@ -1079,7 +1116,7 @@ })) ) return; - if (owner === viewEntry && fileViews[id]?.hasUnsavedChanges()) { + if (chatView === viewEntry && fileViews[id]?.hasUnsavedChanges()) { selectTab(id); if (!(await fileViews[id].requestClose())) return; } @@ -1088,14 +1125,14 @@ showCallOverlay.set(false); } if (tab.kind === 'preview') showEmbeds.set(false); - owner.drafts.delete(id); - const previousPanels = owner.state.panels; + chatView.drafts.delete(id); + const previousPanels = chatView.state.panels; let closedPanels = removeTab(previousPanels, id); // a chat's artifacts have nothing to show once the chat is gone if (tab.kind === 'chat') closedPanels = removeTab(closedPanels, `artifacts:${id}`); - changeChatView(owner, { ...owner.state, panels: closedPanels }); - if (owner === viewEntry) { - tabs = owner.state.panels; + changeChatView(chatView, { ...chatView.state, panels: closedPanels }); + if (chatView === viewEntry) { + tabs = chatView.state.panels; delete dirtyFiles[id]; delete fileContexts[id]; delete chatStreamingStates[id]; @@ -1105,10 +1142,10 @@ delete chatArtifacts[id]; delete artifactSelections[`artifacts:${id}`]; } - if (!tabs.tabs.length || (!largeScreen && tabs.tabs.every((tab) => tab.id === mainChatTabId))) + if (!tabs.tabs.length || (!isLargeScreen && tabs.tabs.every((tab) => tab.id === mainChatTabId))) showTabs.set(false); await tick(); - if (owner === viewEntry) document.getElementById(domId(tabs.activeId))?.focus(); + if (chatView === viewEntry) document.getElementById(toTabDomId(tabs.activeId))?.focus(); } if (target && tab.sessionId) { try { @@ -1119,15 +1156,15 @@ ); } catch (error) { if (!(error instanceof TerminalRequestError) || error.status !== 404) { - changeChatView(owner, { - ...owner.state, + changeChatView(chatView, { + ...chatView.state, panels: - owner.state.panels === closedPanels + chatView.state.panels === closedPanels ? previousPanels - : openTab(owner.state.panels, tab) + : openTab(chatView.state.panels, tab) }); - if (owner === viewEntry) { - tabs = owner.state.panels; + if (chatView === viewEntry) { + tabs = chatView.state.panels; showTabs.set(true); } throw error; @@ -1137,18 +1174,18 @@ } catch (error) { toast.error(String(error)); } finally { - closing.delete(id); + closingTabIds.delete(id); } }; - let tabDropHandled = false; - const sortableTabs = (node: HTMLElement) => { + let isTabDropHandled = false; + const makeTabsSortable = (node: HTMLElement) => { let nextSibling: ChildNode | null = null; - let touchDrag = false; + let isTouchDrag = false; const trackTouch = (event: TouchEvent) => { - if (!touchDrag) return; + if (!isTouchDrag) return; const point = event.touches[0] ?? event.changedTouches[0]; chatDropPreview = point - ? chatDropBounds({ + ? getChatDropZone({ target: document.elementFromPoint(point.clientX, point.clientY), clientX: point.clientX, clientY: point.clientY, @@ -1177,11 +1214,11 @@ transfer.setData('application/x-chat-panel-tab', item.dataset.panelTab ?? ''), onStart: ({ item, originalEvent }: { item: HTMLElement; originalEvent?: Event }) => { nextSibling = item.nextSibling; - touchDrag = !!originalEvent && 'touches' in originalEvent; + isTouchDrag = !!originalEvent && 'touches' in originalEvent; clearChatDropPreview(); - tabDropHandled = false; + isTabDropHandled = false; draggedTabId = item.dataset.panelTab ?? ''; - dragged = true; + isDragging = true; }, onEnd: ({ item, @@ -1193,11 +1230,11 @@ originalEvent?: Event; }) => { const cancelled = originalEvent?.type === 'touchcancel'; - if (touchDrag && originalEvent && 'touches' in originalEvent) + if (isTouchDrag && originalEvent && 'touches' in originalEvent) trackTouch(originalEvent as TouchEvent); - const touchTarget = touchDrag && !cancelled ? chatDropPreview : null; + const touchTarget = isTouchDrag && !cancelled ? chatDropPreview : null; const id = item.dataset.panelTab!; - const group = tabGroups[id]; + const group = groupByTabId[id]; const order = Array.from(from.querySelectorAll('[data-panel-tab]')) .map((tab) => tab.dataset.panelTab!) .filter((tabId) => group?.tabIds.includes(tabId)); @@ -1207,15 +1244,15 @@ tabs = touchTarget.edge ? splitTab(tabs, id, touchTarget.groupId, touchTarget.edge) : moveTabToGroup(tabs, id, touchTarget.groupId); - } else if (!tabDropHandled && !cancelled) tabs = moveTab(tabs, id, order.indexOf(id)); + } else if (!isTabDropHandled && !cancelled) tabs = moveTab(tabs, id, order.indexOf(id)); const drop = pendingTabDrop; pendingTabDrop = null; drop?.(); // Consume Sortable's fallback click suppression so it cannot swallow the next tap. - if (touchDrag) document.documentElement.dispatchEvent(new MouseEvent('click')); + if (isTouchDrag) document.documentElement.dispatchEvent(new MouseEvent('click')); draggedTabId = ''; - dragged = false; - touchDrag = false; + isDragging = false; + isTouchDrag = false; clearChatDropPreview(); } }); @@ -1234,10 +1271,10 @@ const index = group.tabIds.indexOf(tabs.activeId); if (event.altKey && event.shiftKey && ['ArrowLeft', 'ArrowRight'].includes(event.key)) { event.preventDefault(); - const tabIndex = tabGroups[tabs.activeId].tabIds.indexOf(tabs.activeId); + const tabIndex = groupByTabId[tabs.activeId].tabIds.indexOf(tabs.activeId); tabs = moveTab(tabs, tabs.activeId, tabIndex + (event.key === 'ArrowLeft' ? -1 : 1)); await tick(); - document.getElementById(domId(tabs.activeId))?.focus(); + document.getElementById(toTabDomId(tabs.activeId))?.focus(); return; } let next = index; @@ -1249,10 +1286,10 @@ else return; event.preventDefault(); selectTab(group.tabIds[next]); - document.getElementById(domId(group.tabIds[next]))?.focus(); + document.getElementById(toTabDomId(group.tabIds[next]))?.focus(); }; - $: hasMessages = history?.messages && Object.keys(history.messages).length > 0; + $: hasMessages = chatHistory?.messages && Object.keys(chatHistory.messages).length > 0; const chatContextNeedsSavedChat = (terminal: any) => terminal?.scope === 'chat'; $: selectedSystemTerminal = ($terminalServers ?? []).find( @@ -1261,13 +1298,13 @@ $: selectedSystemTerminalAvailable = selectedSystemTerminal && !(chatContextNeedsSavedChat(selectedSystemTerminal) && !isSavedChatId(chatId)); - $: terminalFilesAvailable = !!( + $: supportsTerminalFiles = !!( $config?.features?.enable_tool_servers && $selectedTerminalId && selectedSystemTerminalAvailable ); $: showFilesTab = - terminalFilesAvailable || + supportsTerminalFiles || (codeInterpreterEnabled && $config?.code?.interpreter_engine !== 'jupyter'); $: if (!hasMessages) showOverview.set(false); $: showCommentsTab = !!( @@ -1277,27 +1314,27 @@ !$temporaryChatEnabled ); let commentCount: number | null = null; - let countVersion = 0; + let commentCountRequestId = 0; const setCommentCount = (total: number) => { - ++countVersion; + ++commentCountRequestId; commentCount = total; }; const loadCommentCount = async (id: string) => { - const version = ++countVersion; + const version = ++commentCountRequestId; commentCount = null; try { const result = await commentsRequest<{ total: number }>( `/?${resourceQuery({ resource_type: 'chat', resource_id: id })}&limit=1` ); - if (version === countVersion) commentCount = result.total; + if (version === commentCountRequestId) commentCount = result.total; } catch { /* The comments panel handles access errors when opened. */ } }; $: if (showCommentsTab && $showTabs && chatId) loadCommentCount(chatId); - let linkedComment = ''; - $: if (showCommentsTab && chatId === $page.params.id && $page.url.href !== linkedComment) { - linkedComment = $page.url.href; + let lastCommentLinkHref = ''; + $: if (showCommentsTab && chatId === $page.params.id && $page.url.href !== lastCommentLinkHref) { + lastCommentLinkHref = $page.url.href; const comment_id = $page.url.searchParams.get('comment'); if (comment_id) showTabs.set({ tab: 'comments', comment_id }); } @@ -1307,11 +1344,11 @@ ? { resource_type: 'chat', resource_id: chatId, - ...commentTarget + ...commentAnchor } : null; // A chat's artifacts tab names the chat it belongs to. - $: tabLabel = (tab: PanelTab) => { + $: tabLabel = (tab: Tab) => { if (tab.kind === 'terminal') return terminalTitles[tab.sessionId ?? ''] || tab.label; const source = tab.kind === 'artifacts' && tab.sourceTabId !== mainChatTabId @@ -1338,21 +1375,21 @@ (view) => view.kind !== 'files' && view.kind !== 'voice' && view.available ); $: canOpenNewTab = - showFilesTab || terminalFilesAvailable || canSelectTerminal || newTabViews.length > 0 || hasMessages; + showFilesTab || supportsTerminalFiles || canSelectTerminal || newTabViews.length > 0 || hasMessages; - const quickSplit = () => { + const splitWithSuggestedTab = () => { if (tabs.tabs.length < 2) { const view = availableViews.find((view) => view.available); if (!view) return; if (view.kind === 'files') openFiles(); - else openFeature(view.kind as 'artifacts' | 'preview' | 'voice' | 'comments' | 'chat'); + else openFeatureTab(view.kind as 'artifacts' | 'preview' | 'voice' | 'comments' | 'chat'); } tabs = setSplitTabs(tabs, true); }; const toggleSplit = () => { if (tabs.groups.length > 1) tabs = setSplitTabs(tabs, false); - else quickSplit(); + else splitWithSuggestedTab(); }; const handleWorkspaceShortcut = (event: KeyboardEvent) => { @@ -1370,10 +1407,10 @@ let action: (() => void) | undefined; switch (shortcut) { case Shortcut.VOICE_NOTE: - if (voiceNoteTarget || canVoiceNote || canSelectTerminal) action = openVoiceNote; + if (voiceNoteDestination || canVoiceNote || canSelectTerminal) action = openVoiceNote; break; case Shortcut.QUICK_OPEN: - if (terminalFilesAvailable && selectedTarget) + if (supportsTerminalFiles && selectedConnection) action = () => { showQuickOpen = true; }; @@ -1382,22 +1419,22 @@ if (showFilesTab || canSelectTerminal) action = () => openFiles(); break; case Shortcut.OPEN_DESKTOP: - if ((desktopEnabled && selectedTarget) || canSelectTerminal) action = openDesktop; + if ((supportsDesktop && selectedConnection) || canSelectTerminal) action = openDesktop; break; case Shortcut.NEW_CHAT_TAB: - if (canOpenChat) action = () => openFeature('chat'); + if (canOpenChat) action = () => openFeatureTab('chat'); break; case Shortcut.OPEN_COMMENTS: - if (showCommentsTab) action = () => openFeature('comments'); + if (showCommentsTab) action = () => openFeatureTab('comments'); break; case Shortcut.NEW_FILE: - if ((terminalFilesAvailable && selectedTarget) || canSelectTerminal) action = newFile; + if ((supportsTerminalFiles && selectedConnection) || canSelectTerminal) action = openNewFileTab; break; case Shortcut.NEW_TERMINAL: - if ((terminalEnabled && selectedTarget) || canSelectTerminal) action = newTerminal; + if ((supportsTerminal && selectedConnection) || canSelectTerminal) action = openNewTerminalTab; break; case Shortcut.NEW_BROWSER: - if ((browserEnabled && selectedTarget) || canSelectTerminal) action = () => openBrowser(); + if ((supportsBrowser && selectedConnection) || canSelectTerminal) action = () => openBrowser(); break; case Shortcut.CLOSE_TAB: if (panelVisible && tabs.activeId) @@ -1414,7 +1451,7 @@ const id = group.tabIds[(index + direction + group.tabIds.length) % group.tabIds.length]; action = () => { selectTab(id); - document.getElementById(domId(id))?.focus(); + document.getElementById(toTabDomId(id))?.focus(); }; break; } @@ -1429,15 +1466,15 @@ action(); }; - const terminalAccessible = (selector: string) => { + const isTerminalReachable = (terminalId: string) => { if (!$config?.features?.enable_tool_servers) return false; const system = ($terminalServers ?? []).find( - (terminal) => !!selector && terminal.id === selector + (terminal) => !!terminalId && terminal.id === terminalId ); return !!system && !(chatContextNeedsSavedChat(system) && !isSavedChatId(chatId)); }; - $: selectedTarget = - terminalFilesAvailable && mounted + $: selectedConnection = + supportsTerminalFiles && isMounted ? resolveTerminalTarget( $selectedTerminalId, $terminalServers ?? [], @@ -1461,7 +1498,7 @@ })) ] : []; - $: canSelectTerminal = !selectedTarget && availableTerminals.length > 0; + $: canSelectTerminal = !selectedConnection && availableTerminals.length > 0; let pendingTerminalAction: (() => void) | null = null; const askForTerminal = (action: () => void) => { if (availableTerminals.length) pendingTerminalAction = action; @@ -1471,47 +1508,47 @@ pendingTerminalAction = null; selectTerminal(selectedTerminalId, id, chatId); await tick(); - if (selectedTarget) action?.(); + if (selectedConnection) action?.(); }; - const checkTerminal = async () => { - const version = ++featureVersion; - terminalEnabled = false; - desktopEnabled = false; - browserEnabled = false; - if (!selectedTarget) return; + const loadTerminalFeatures = async () => { + const version = ++featureCheckRequestId; + supportsTerminal = false; + supportsDesktop = false; + supportsBrowser = false; + if (!selectedConnection) return; try { const result = await terminalRequest<{ features?: { terminal?: boolean; desktop?: boolean; browser?: boolean }; - }>(selectedTarget, '/api/config'); - if (version === featureVersion) { - terminalEnabled = result.features?.terminal !== false; - desktopEnabled = result.features?.desktop === true; - browserEnabled = result.features?.browser === true; + }>(selectedConnection, '/api/config'); + if (version === featureCheckRequestId) { + supportsTerminal = result.features?.terminal !== false; + supportsDesktop = result.features?.desktop === true; + supportsBrowser = result.features?.browser === true; } } catch { /* Files remain available when interactive terminals are disabled. */ } }; $: { - selectedTarget; + selectedConnection; chatId; - void checkTerminal(); + void loadTerminalFeatures(); } - $: if (mounted && !chatLoading && $user?.id && chatId !== tabsChatId) { + $: if (isMounted && !chatLoading && $user?.id && chatId !== tabsChatId) { if (viewEntry && viewReady && (preserveChatView || (!viewEntry.chatId && chatId))) { tabsChatId = chatId; if (chatId) - void bindTerminalChat(chatId).catch((error) => { + void attachChatViewTo(chatId).catch((error) => { viewError = String(error); }); } else void restoreChatView(chatId); } $: if ( - mounted && + isMounted && viewReady && !chatLoading && - !largeScreen && + !isLargeScreen && $showTabs === true && tabs.tabs.every((tab) => tab.id === mainChatTabId) ) { @@ -1520,29 +1557,23 @@ .filter((view) => view.available && view.kind !== 'chat') .map((view) => () => { if (view.kind === 'files') openFiles(); - else openFeature(view.kind as 'artifacts' | 'preview' | 'voice' | 'comments' | 'chat'); + else openFeatureTab(view.kind as 'artifacts' | 'preview' | 'voice' | 'comments' | 'chat'); }), - ...(terminalFilesAvailable ? [newFile] : []), - ...(terminalEnabled ? [newTerminal] : []), - ...(browserEnabled ? [openBrowser] : []), - ...(desktopEnabled ? [openDesktop] : []) + ...(supportsTerminalFiles ? [openNewFileTab] : []), + ...(supportsTerminal ? [openNewTerminalTab] : []), + ...(supportsBrowser ? [openBrowser] : []), + ...(supportsDesktop ? [openDesktop] : []) ]; - if (terminalFilesAvailable || (!hasOpenedTabs && showFilesTab)) openFiles(); + if (supportsTerminalFiles || (!hasExtraTabs && showFilesTab)) openFiles(); else if (options.length === 1) options[0](); else if (!options.length && !canOpenChat) showTabs.set(false); - hasOpenedTabs = true; + hasExtraTabs = true; } - $: if ( - !( - $user?.role === 'admin' || - ($user?.role === 'user' && ($user.permissions?.chat?.side_chat ?? false)) - ) && - $sideChatRequest?.parentId === chatId - ) - sideChatRequest.set(null); - $: if (viewReady && $showTabs === 'side') { - if (canBranchChat) openFeature('chat', true); - else sideChatRequest.set(null); + $: if (!canOpenChatTab && $chatTabRequest?.parentChatId === chatId) + chatTabRequest.set(null); + $: if (viewReady && $showTabs === 'chat') { + if (canOpenChatTab) openFeatureTab('chat', true); + else chatTabRequest.set(null); showTabs.set(tabs.tabs.length > 0); } $: if ( @@ -1550,23 +1581,23 @@ ($showTabs === 'comments' || (typeof $showTabs === 'object' && $showTabs)) && showCommentsTab ) { - commentTarget = typeof $showTabs === 'object' ? $showTabs : {}; - openFeature('comments'); + commentAnchor = typeof $showTabs === 'object' ? $showTabs : {}; + openFeatureTab('comments'); } $: if (viewReady && $showEmbeds && showPreviewTab) { - openFeature('preview'); + openFeatureTab('preview'); showEmbeds.set(false); } - $: if (viewReady && $showCallOverlay) openFeature('voice'); + $: if (viewReady && $showCallOverlay) openFeatureTab('voice'); $: if (viewReady && !$showCallOverlay && tabs.tabs.some((tab) => tab.kind === 'voice')) closeTab('voice'); - $: if (viewReady && $showTabs === 'voice') openFeature('voice'); + $: if (viewReady && $showTabs === 'voice') openFeatureTab('voice'); $: if (viewReady && $showFileNav) { const request = $showFileNav; showFileNav.set(null); if (request.chatId === chatId) openFiles(request.terminalId, request.directory, true); } - $: if (viewReady && $showFileNavPath && terminalFilesAvailable && $selectedTerminalId) { + $: if (viewReady && $showFileNavPath && supportsTerminalFiles && $selectedTerminalId) { const request = $showFileNavPath; showFileNavPath.set(null); openFile( @@ -1586,15 +1617,15 @@ stopTerminalChoice?.(false); captureView(); if (viewEntry) void flushChatView(viewEntry); - ++switchVersion; - ++countVersion; - ++featureVersion; + ++restoreRequestId; + ++commentCountRequestId; + ++featureCheckRequestId; showOverview.set(false); }); const handleMediaQuery = (event: MediaQueryList | MediaQueryListEvent) => { - if (panelTarget && largeScreen !== event.matches) releasePanel(panelTarget); - largeScreen = event.matches; + if (panelTarget && isLargeScreen !== event.matches) releasePanel(panelTarget); + isLargeScreen = event.matches; }; onMount(() => { @@ -1608,7 +1639,7 @@ }); document.addEventListener('keydown', handleWorkspaceShortcut, true); const unsubscribeVisibility = showTabs.subscribe((visible) => { - if (!largeScreen && !visible && panelTarget) releasePanel(panelTarget); + if (!isLargeScreen && !visible && panelTarget) releasePanel(panelTarget); }); const mediaQuery = window.matchMedia('(min-width: 768px)'); mediaQuery.addEventListener('change', handleMediaQuery); @@ -1622,7 +1653,7 @@ if (isDestroyed) return; setTimeout(() => { - mounted = true; + isMounted = true; }, 0); }; init(); @@ -1634,31 +1665,31 @@ document.removeEventListener('keydown', handleWorkspaceShortcut, true); unsubscribeVisibility(); isDestroyed = true; - mounted = false; - if (!largeScreen) { + isMounted = false; + if (!isLargeScreen) { showTabs.set(false); } mediaQuery.removeEventListener('change', handleMediaQuery); }; }); // Tab-opening handlers mutate tabs indirectly, so derive visibility and placement after them. - $: displayTabs = fullWidth ? tabs : setMainChatTab(tabs, false); - $: positions = fullWidth - ? panelPositions(displayTabs.layout) + $: renderedTabs = fullWidth ? tabs : setMainChatTab(tabs, false); + $: layoutRects = fullWidth + ? getLayoutRects(renderedTabs.layout) : { - groups: { [displayTabs.activeGroupId]: { left: 0, top: 0, width: 1, height: 1 } }, + groups: { [renderedTabs.activeGroupId]: { left: 0, top: 0, width: 1, height: 1 } }, dividers: [] }; - $: tabGroups = Object.fromEntries( - displayTabs.groups.flatMap((group) => group.tabIds.map((id) => [id, group])) + $: groupByTabId = Object.fromEntries( + renderedTabs.groups.flatMap((group) => group.tabIds.map((id) => [id, group])) ); $: visibleTabIds = new Set( - displayTabs.groups - .filter((group) => fullWidth || group.id === displayTabs.activeGroupId) + renderedTabs.groups + .filter((group) => fullWidth || group.id === renderedTabs.activeGroupId) .map((group) => group.activeId) ); $: mainChatActive = fullWidth && visibleTabIds.has(mainChatTabId); - $: if (mounted && viewReady && !chatLoading) { + $: if (isMounted && viewReady && !chatLoading) { const active = tabs.tabs.find((tab) => tab.id === tabs.activeId); const href = active?.kind === 'page' @@ -1684,10 +1715,10 @@ } } $: mainChatGroupId = - displayTabs.groups.find((group) => group.tabIds.includes(mainChatTabId))?.id ?? ''; + renderedTabs.groups.find((group) => group.tabIds.includes(mainChatTabId))?.id ?? ''; $: mainChatStyle = - fullWidth && positions.groups[mainChatGroupId] - ? paneStyle(positions.groups[mainChatGroupId], 36) + fullWidth && layoutRects.groups[mainChatGroupId] + ? toPaneStyle(layoutRects.groups[mainChatGroupId], 36) : ''; @@ -1722,10 +1753,10 @@ { - if (event.target instanceof Element && event.target.closest('#sidebar')) dragged = true; + if (event.target instanceof Element && event.target.closest('#sidebar')) isDragging = true; }} on:dragend|capture={() => { - dragged = false; + isDragging = false; clearChatDropPreview(); }} on:drop|capture={clearChatDropPreview} @@ -1750,28 +1781,28 @@
{/if} -{#if voiceNoteTarget} - {@const target = voiceNoteTarget} +{#if voiceNoteDestination} + {@const target = voiceNoteDestination} { - voiceNoteTarget = null; + voiceNoteDestination = null; }} onsaved={(path) => openFile(path, target.target.selector)} /> {/if} -{#if showQuickOpen && terminalFilesAvailable && selectedTarget} - {#key JSON.stringify([selectedTarget.baseUrl, selectedTarget.context.modelId, chatId])} +{#if showQuickOpen && supportsTerminalFiles && selectedConnection} + {#key JSON.stringify([selectedConnection.baseUrl, selectedConnection.context.modelId, chatId])} { showQuickOpen = false; }} - onselect={(path) => openFile(path, selectedTarget!.selector)} + onselect={(path) => openFile(path, selectedConnection!.selector)} /> {/key} {/if} @@ -1806,11 +1837,11 @@
{ const { node } = e; - history.messages[node.data.message.id].favorite = node.data.message.favorite + chatHistory.messages[node.data.message.id].favorite = node.data.message.favorite ? true : null; showOverview.set(false); @@ -1823,9 +1854,9 @@