This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-01 20:50:42 +09:00
1 parent 950da84bdb
commit 5b58b1ebc0
9 files changed
+1042 -282

No files matched your search

+46 -90
View File
@@ -9,17 +9,15 @@
config,
settings,
showArtifacts,
showTabs,
artifactContents
} from '$lib/stores';
import { copyToClipboard, createMessagesList } from '$lib/utils';
import { injectCsp } from '$lib/utils/csp';
import ArrowsPointingOut from '../icons/ArrowsPointingOut.svelte';
import Icon from './FileNav/Icon.svelte';
import Tooltip from '../common/Tooltip.svelte';
import SvgPanZoom from '../common/SVGPanZoom.svelte';
import ArrowLeft from '../icons/ArrowLeft.svelte';
import Download from '../icons/Download.svelte';
export let overlay = false;
@@ -95,7 +93,6 @@
console.log('Artifact contents updated:', newContents);
if (newContents.length === 0) {
showTabs.set(false);
showArtifacts.set(false);
selectedContentIdx = 0;
} else if (newContents.length > contents.length) {
@@ -122,106 +119,65 @@
});
</script>
<div
class=" w-full h-full relative flex flex-col bg-white dark:bg-gray-850"
id="artifacts-container"
>
<div class="w-full h-full relative flex flex-col" id="artifacts-container">
<div class="w-full min-h-0 flex flex-col flex-1 relative">
{#if contents.length > 0}
<div
class="pointer-events-auto z-20 shrink-0 flex justify-between items-center px-2.5 pb-2.5 font-primar text-gray-900 dark:text-white"
class="pointer-events-auto z-20 shrink-0 flex items-center justify-between gap-2 px-2 pb-1.5"
>
<div class="flex-1 flex items-center justify-between pr-1">
<div class="flex items-center space-x-2">
<div class="flex items-center gap-0.5 self-center min-w-fit" dir="ltr">
<button
aria-label={$i18n.t('Previous version')}
class="self-center p-1 hover:bg-black/5 dark:hover:bg-white/5 dark:hover:text-white hover:text-black rounded-md transition disabled:cursor-not-allowed"
on:click={() => navigateContent('prev')}
disabled={contents.length <= 1}
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2.5"
class="size-3.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="M15.75 19.5 8.25 12l7.5-7.5"
/>
</svg>
</button>
<div class="text-xs self-center dark:text-gray-100 min-w-fit">
{$i18n.t('Version {{selectedVersion}} of {{totalVersions}}', {
selectedVersion: selectedContentIdx + 1,
totalVersions: contents.length
})}
</div>
<button
aria-label={$i18n.t('Next version')}
class="self-center p-1 hover:bg-black/5 dark:hover:bg-white/5 dark:hover:text-white hover:text-black rounded-md transition disabled:cursor-not-allowed"
on:click={() => navigateContent('next')}
disabled={contents.length <= 1}
>
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
stroke-width="2.5"
class="size-3.5"
>
<path
stroke-linecap="round"
stroke-linejoin="round"
d="m8.25 4.5 7.5 7.5-7.5 7.5"
/>
</svg>
</button>
</div>
</div>
<div class="flex items-center gap-1.5">
<div class="flex min-w-0 items-center gap-0.5" dir="ltr">
<button
aria-label={$i18n.t('Previous version')}
class="flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-100 hover:text-gray-600 disabled:text-gray-200 dark:text-gray-500 dark:hover:text-gray-300 dark:disabled:text-gray-700"
on:click={() => navigateContent('prev')}
disabled={selectedContentIdx === 0}
><Icon name="chevron-left" size={11} strokeWidth={1.5} /></button
>
<span class="truncate text-xs text-gray-500 dark:text-gray-400">
{$i18n.t('Version {{selectedVersion}} of {{totalVersions}}', {
selectedVersion: selectedContentIdx + 1,
totalVersions: contents.length
})}
</span>
<button
aria-label={$i18n.t('Next version')}
class="flex h-5 w-5 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-100 hover:text-gray-600 disabled:text-gray-200 dark:text-gray-500 dark:hover:text-gray-300 dark:disabled:text-gray-700"
on:click={() => navigateContent('next')}
disabled={selectedContentIdx === contents.length - 1}
><Icon name="chevron-right" size={11} strokeWidth={1.5} /></button
>
</div>
<div class="flex shrink-0 items-center gap-0.5">
<Tooltip content={copied ? $i18n.t('Copied') : $i18n.t('Copy')}>
<button
class="bg-none border-none text-xs bg-gray-50 hover:bg-gray-100 dark:bg-gray-850 dark:hover:bg-gray-800 transition rounded-md px-1.5 py-0.5"
aria-label={copied ? $i18n.t('Copied') : $i18n.t('Copy')}
class="flex h-5 w-5 items-center justify-center rounded text-gray-400 transition-colors duration-100 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
on:click={() => {
copyToClipboard(contents[selectedContentIdx].content);
copied = true;
setTimeout(() => {
copied = false;
}, 2000);
}}>{copied ? $i18n.t('Copied') : $i18n.t('Copy')}</button
}}><Icon name={copied ? 'check' : 'copy'} size={11} strokeWidth={1.4} /></button
>
<Tooltip content={$i18n.t('Download')}>
</Tooltip>
<Tooltip content={$i18n.t('Download')}>
<button
aria-label={$i18n.t('Download')}
class="flex h-5 w-5 items-center justify-center rounded text-gray-400 transition-colors duration-100 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
on:click={downloadArtifact}
><Icon name="download" size={11} strokeWidth={1.4} /></button
>
</Tooltip>
{#if contents[selectedContentIdx].type === 'iframe'}
<Tooltip content={$i18n.t('Open in full screen')}>
<button
aria-label={$i18n.t('Download')}
class=" bg-none border-none text-xs bg-gray-50 hover:bg-gray-100 dark:bg-gray-850 dark:hover:bg-gray-800 transition rounded-md p-0.5"
on:click={downloadArtifact}
aria-label={$i18n.t('Open in full screen')}
class="flex h-5 w-5 items-center justify-center rounded text-gray-400 transition-colors duration-100 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
on:click={showFullScreen}><Icon name="expand" size={11} strokeWidth={1.4} /></button
>
<Download className="size-3.5" />
</button>
</Tooltip>
{#if contents[selectedContentIdx].type === 'iframe'}
<Tooltip content={$i18n.t('Open in full screen')}>
<button
aria-label={$i18n.t('Open in full screen')}
class=" bg-none border-none text-xs bg-gray-50 hover:bg-gray-100 dark:bg-gray-850 dark:hover:bg-gray-800 transition rounded-md p-0.5"
on:click={showFullScreen}
>
<ArrowsPointingOut className="size-3.5" />
</button>
</Tooltip>
{/if}
</div>
{/if}
</div>
</div>
{/if}
@@ -230,7 +186,7 @@
<div class=" absolute top-0 left-0 right-0 bottom-0 z-10"></div>
{/if}
<div class="flex-1 w-full min-h-0">
<div class="flex-1 w-full min-h-0 bg-white dark:bg-gray-850">
<div class=" h-full flex flex-col">
{#if contents.length > 0}
<div class="max-w-full w-full h-full">
+503 -133
View File
@@ -1,12 +1,7 @@
<script context="module" lang="ts">
type PanelTab = 'files' | 'artifacts' | 'preview' | 'voice' | 'comments';
let savedTab: 'files' | 'comments' = 'files';
</script>
<script lang="ts">
import type { TerminalContext } from '$lib/types';
import { onMount, onDestroy, tick, getContext } from 'svelte';
import { beforeNavigate } from '$app/navigation';
import { beforeNavigate, goto } from '$app/navigation';
import {
artifactContents,
config,
@@ -33,6 +28,25 @@
} from '$lib/components/comments/CommentsPanel.svelte';
import { page } from '$app/stores';
import {
emptyTabs,
openTab,
activateTab,
removeTab,
fileTabId,
type PanelTab
} from './ChatControls/tabs';
import {
resolveTerminalConnection,
terminalRequest,
type TerminalConnection
} from '$lib/apis/terminal';
import Dropdown from '../common/Dropdown.svelte';
import DropdownMenu from '../common/DropdownMenu.svelte';
import Icon from './FileNav/Icon.svelte';
import FileTypeIcon from './FileNav/FileTypeIcon.svelte';
import UntitledFile from './ChatControls/UntitledFile.svelte';
import XTerminal from './XTerminal.svelte';
import CallPanel from './MessageInput/CallPanel.svelte';
import Drawer from '../common/Drawer.svelte';
import MobileSwipePanel from '../common/MobileSwipePanel.svelte';
@@ -46,10 +60,9 @@
import XMark from '../icons/XMark.svelte';
import { isSavedChatId } from '$lib/utils/chatId';
const i18n = getContext('i18n');
const i18n = getContext<any>('i18n');
export let history;
let sidePanelAvailable = false;
export let chatId: string | null = null;
export let terminalContext: TerminalContext | null = null;
@@ -64,7 +77,7 @@
| null = null;
export let stopResponse: Function;
export let showMessage: Function;
export let files;
export let files: any[];
export let modelId;
export let codeInterpreterEnabled = false;
@@ -75,15 +88,168 @@
let controlsWidth = 300;
let viewportWidth = 0;
// Tab state for the side panel
let activeTab: PanelTab = savedTab;
$: if ($showTabs === 'files' || $showTabs === 'comments') activeTab = $showTabs;
else if (typeof $showTabs === 'object') activeTab = $showTabs.tab;
// svelte-ignore reactive_declaration_module_script_dependency
$: {
if (activeTab === 'files') savedTab = activeTab;
let tabs = emptyTabs();
let fileViews: Record<
string,
{
hasUnsavedChanges: () => boolean;
requestClose: () => Promise<boolean>;
browseDirectory?: (path: string) => unknown;
revealPage?: (page: number | null) => void;
}
> = {};
let dirtyFiles: Record<string, boolean> = {};
let fileContexts: Record<string, TerminalContext | null> = {};
let panelTarget: HTMLElement | null = null;
let initialized = false;
let tabsChatId = chatId;
let terminalSequence = 0;
let commentTarget: { comment_id?: string } = {};
let closing = new Set<string>();
let navigationApproved = false;
let selectedConnection: TerminalConnection | null = null;
let terminalEnabled = false;
let featureVersion = 0;
// Move a single mounted panel between desktop, mobile, and its hidden parking spot.
const placePanel = (node: HTMLElement, target: HTMLElement | null) => {
const home = node.parentElement!;
const move = (destination: HTMLElement | null) => {
const parent = destination ?? home;
if (node.parentElement !== parent) parent.appendChild(node);
};
move(target);
return { update: move, destroy: () => node.remove() };
};
const tabIcon = (kind: PanelTab['kind']) =>
({
files: 'folder',
file: 'page',
terminal: 'terminal',
artifacts: 'code',
preview: 'browser',
voice: 'microphone',
comments: 'chat-bubble'
})[kind];
const domId = (id: string) => `chat-panel-${encodeURIComponent(id)}`;
$: activeTabId = tabs.activeId;
$: activeTab = tabs.tabs.find((tab) => tab.id === tabs.activeId);
$: terminalContext = fileContexts[tabs.activeId] ?? activeTab?.context ?? null;
$: if (activeTabId && panelTarget) {
const id = activeTabId;
void tick().then(() =>
document.getElementById(domId(id))?.scrollIntoView({ block: 'nearest', inline: 'nearest' })
);
}
const selectTab = (id: string) => {
tabs = activateTab(tabs, id);
showTabs.set(true);
};
const openPanel = (tab: PanelTab) => {
initialized = true;
tabs = openTab(tabs, tab);
showTabs.set(true);
};
const openFiles = (selector = $selectedTerminalId, directory?: string) => {
if (selector ? !terminalAccessible(selector) : !showFilesTab) return;
const id = selector ? `files:${selector}` : 'files';
openPanel({
id,
kind: 'files',
label: $i18n.t('Files'),
terminalId: selector ?? undefined,
path: directory
});
if (directory) void fileViews[id]?.browseDirectory?.(directory);
};
const openFile = (path: string, selector: string, page?: number | null) => {
if (!terminalAccessible(selector)) return;
path = path.replace(/\\/g, '/').replace(/\/{2,}/g, '/');
const id =
tabs.tabs.find(
(tab) =>
tab.kind === 'file' && !tab.untitled && tab.terminalId === selector && tab.path === path
)?.id ?? fileTabId(selector, path);
openPanel({
id,
kind: 'file',
label: path.split('/').pop() || path,
terminalId: selector,
path,
page
});
if (page != null) fileViews[id]?.revealPage?.(page);
};
const newFile = () => {
if (!terminalFilesAvailable || !selectedConnection) return;
let number = 1;
while (tabs.tabs.some((tab) => tab.untitled && tab.label === `Untitled-${number}`)) number++;
openPanel({
id: crypto.randomUUID(),
kind: 'file',
label: `Untitled-${number}`,
terminalId: selectedConnection.selector,
connection: { ...selectedConnection },
untitled: true,
context: activeTab?.terminalId === selectedConnection.selector ? terminalContext : undefined
});
};
const openFeature = (kind: 'artifacts' | 'preview' | 'voice' | 'comments') => {
if (!availableViews.some((view) => view.kind === kind && view.available)) return;
const view = availableViews.find((view) => view.kind === kind)!;
openPanel({ id: kind, kind, label: view.label });
};
const newTerminal = () => {
if (!terminalEnabled || !selectedConnection) return;
openPanel({
id: crypto.randomUUID(),
kind: 'terminal',
label: `${$i18n.t('Terminal')} ${++terminalSequence}`,
terminalId: selectedConnection.selector,
connection: { ...selectedConnection }
});
};
const closeTab = async (id: string) => {
if (closing.has(id)) return;
closing.add(id);
try {
const tab = tabs.tabs.find((item) => item.id === id);
if (!tab) return;
if (fileViews[id]?.hasUnsavedChanges()) {
selectTab(id);
if (!(await fileViews[id].requestClose())) return;
}
if (tab.kind === 'voice') {
bridge?.end();
showCallOverlay.set(false);
}
if (tab.kind === 'artifacts') showArtifacts.set(false);
if (tab.kind === 'preview') showEmbeds.set(false);
tabs = removeTab(tabs, id);
delete dirtyFiles[id];
delete fileContexts[id];
await tick();
document.getElementById(domId(tabs.activeId))?.focus();
} finally {
closing.delete(id);
}
};
const navigateTabs = (event: KeyboardEvent) => {
if (!(event.target instanceof HTMLElement) || event.target.getAttribute('role') !== 'tab')
return;
const index = tabs.tabs.findIndex((tab) => tab.id === tabs.activeId);
let next = index;
if (event.key === 'ArrowRight') next = (index + 1) % tabs.tabs.length;
else if (event.key === 'ArrowLeft') next = (index - 1 + tabs.tabs.length) % tabs.tabs.length;
else if (event.key === 'Home') next = 0;
else if (event.key === 'End') next = tabs.tabs.length - 1;
else return;
event.preventDefault();
selectTab(tabs.tabs[next].id);
document.getElementById(domId(tabs.tabs[next].id))?.focus();
};
$: hasMessages = history?.messages && Object.keys(history.messages).length > 0;
const chatContext = (terminal: any) => terminal?.contexts?.chat ?? {};
@@ -133,7 +299,7 @@
/* The comments panel handles access errors when opened. */
}
};
$: if (showCommentsTab && $showTabs) loadCommentCount(chatId);
$: if (showCommentsTab && $showTabs && chatId) loadCommentCount(chatId);
let linkedComment = '';
$: if (showCommentsTab && chatId === $page.params.id && $page.url.href !== linkedComment) {
linkedComment = $page.url.href;
@@ -146,57 +312,153 @@
? {
resource_type: 'chat',
resource_id: chatId,
...(typeof $showTabs === 'object' ? $showTabs : {})
...commentTarget
}
: null;
$: if ($showTabs === 'files' || $showTabs === 'comments' || typeof $showTabs === 'object') {
$: showArtifactsTab = ($artifactContents ?? []).length > 0 && $visibleControls['chat.artifacts'];
$: showPreviewTab = !!$embed && $embed.chatId === chatId;
$: availableViews = [
{ kind: 'files', label: $i18n.t('Files'), available: showFilesTab },
{ kind: 'artifacts', label: $i18n.t('Artifacts'), available: showArtifactsTab },
{ kind: 'preview', label: $i18n.t('Preview'), available: showPreviewTab },
{ kind: 'voice', label: $i18n.t('Voice'), available: $showCallOverlay },
{ kind: 'comments', label: $i18n.t('Comments'), available: showCommentsTab }
];
$: directTerminals =
($settings as { terminalServers?: { url: string; key?: string }[] })?.terminalServers ?? [];
const terminalAccessible = (selector: string) => {
if (!$config?.features?.enable_tool_servers) return false;
const system = ($terminalServers ?? []).find((terminal) => terminal.id === selector);
if (system)
return (
chatContextAvailable(system) &&
!(chatContextNeedsSavedChat(system) && !isSavedChatId(chatId))
);
return !!(
$config?.features?.enable_direct_integrations &&
($user?.role === 'admin' || ($user?.permissions?.features?.direct_tool_servers ?? true)) &&
directTerminals.some((terminal) => terminal.url === selector)
);
};
const pruneTabs = () => {
for (const tab of tabs.tabs) {
const available = tab.terminalId
? terminalAccessible(tab.terminalId)
: availableViews.some((view) => view.kind === tab.kind && view.available);
if (!available) tabs = removeTab(tabs, tab.id);
}
};
$: {
availableViews;
$terminalServers;
$settings;
$config;
$user;
chatId;
pruneTabs();
}
const checkTerminal = async () => {
const version = ++featureVersion;
terminalEnabled = false;
selectedConnection =
terminalFilesAvailable && mounted
? resolveTerminalConnection(
$selectedTerminalId,
$terminalServers ?? [],
directTerminals,
localStorage.token ?? ''
)
: null;
if (!selectedConnection) return;
try {
const result = await terminalRequest<{ features?: { terminal?: boolean } }>(
selectedConnection,
chatId,
'/api/config'
);
if (version === featureVersion) terminalEnabled = result.features?.terminal !== false;
} catch {
/* Files remain available when interactive terminals are disabled. */
}
};
$: {
terminalFilesAvailable;
$selectedTerminalId;
$terminalServers;
$settings;
mounted;
chatId;
void checkTerminal();
}
$: if (chatId !== tabsChatId) {
if (tabsChatId !== null || !chatId) {
tabs = emptyTabs();
dirtyFiles = {};
fileContexts = {};
initialized = false;
commentTarget = {};
}
tabsChatId = chatId;
}
$: if ($showTabs === true && !initialized && showFilesTab) {
initialized = true;
openFiles();
}
$: if ($showTabs === 'files' && showFilesTab) openFiles();
$: if (
($showTabs === 'comments' || (typeof $showTabs === 'object' && $showTabs)) &&
showCommentsTab
) {
commentTarget = typeof $showTabs === 'object' ? $showTabs : {};
openFeature('comments');
}
$: if ($showArtifacts && showArtifactsTab) {
openFeature('artifacts');
showArtifacts.set(false);
}
$: if ($showEmbeds && showPreviewTab) {
openFeature('preview');
showEmbeds.set(false);
}
$: if ($showArtifacts) activeTab = 'artifacts';
$: if ($showEmbeds) activeTab = 'preview';
$: if ($showCallOverlay) activeTab = 'voice';
$: if ($showCallOverlay) openFeature('voice');
$: if ($showFileNavPath && terminalFilesAvailable && $selectedTerminalId) {
const request = $showFileNavPath;
showFileNavPath.set(null);
openFile(
typeof request === 'string' ? request : request.path,
$selectedTerminalId,
typeof request === 'string' ? null : request.page
);
}
const selectTab = (tab: PanelTab) => {
showTabs.set(tab === 'files' || tab === 'comments' ? tab : true);
showArtifacts.set(tab === 'artifacts');
showEmbeds.set(tab === 'preview');
activeTab = tab;
};
beforeNavigate(({ from, to }) => {
if (from?.url.pathname === to?.url.pathname) return;
beforeNavigate(({ from, to, cancel, willUnload }) => {
if (navigationApproved || from?.url.pathname === to?.url.pathname) return;
showOverview.set(false);
if (activeTab === 'comments' && $showTabs)
showTabs.set(to?.route.id === '/(app)/c/[id]' ? 'comments' : false);
const dirtyTabs = tabs.tabs.filter((tab) => fileViews[tab.id]?.hasUnsavedChanges());
if (!dirtyTabs.length) return;
cancel();
if (willUnload || !to) return;
void (async () => {
for (const tab of dirtyTabs) {
selectTab(tab.id);
if (!(await fileViews[tab.id].requestClose())) return;
}
navigationApproved = true;
try {
await goto(to.url);
} finally {
navigationApproved = false;
}
})();
});
onDestroy(() => {
++countVersion;
++featureVersion;
showOverview.set(false);
});
$: showArtifactsTab = ($artifactContents ?? []).length > 0 && $visibleControls['chat.artifacts'];
$: showPreviewTab = !!$embed && $embed.chatId === chatId;
$: panelTabs = [
{ id: 'files', label: $i18n.t('Files'), available: showFilesTab },
{ id: 'artifacts', label: $i18n.t('Artifacts'), available: showArtifactsTab },
{ id: 'preview', label: $i18n.t('Preview'), available: showPreviewTab },
{ id: 'voice', label: $i18n.t('Voice'), available: $showCallOverlay },
{ id: 'comments', label: $i18n.t('Comments'), available: showCommentsTab }
].filter((tab) => tab.available) as { id: PanelTab; label: string; available: boolean }[];
$: sidePanelAvailable = panelTabs.length > 0;
$: if (sidePanelAvailable && !panelTabs.some((tab) => tab.id === activeTab)) {
activeTab = panelTabs[0].id;
if ($showTabs) selectTab(activeTab);
}
$: if (!sidePanelAvailable) showTabs.set(false);
// Auto-switch to Files tab when display_file is triggered
$: if ($showFileNavPath && terminalFilesAvailable) {
activeTab = 'files';
showTabs.set('files');
}
// Clear selected direct terminal if user lost permission
$: if (
$selectedTerminalId &&
@@ -210,22 +472,8 @@
selectedTerminalId.set(null);
}
const handleMediaQuery = async (e) => {
if (e.matches) {
largeScreen = true;
if ($showCallOverlay) {
showCallOverlay.set(false);
await tick();
showCallOverlay.set(true);
}
} else {
largeScreen = false;
if ($showCallOverlay) {
showCallOverlay.set(false);
await tick();
showCallOverlay.set(true);
}
}
const handleMediaQuery = (event: MediaQueryList | MediaQueryListEvent) => {
largeScreen = event.matches;
};
const onMouseDown = () => {
@@ -267,17 +515,6 @@
document.removeEventListener('mouseup', onMouseUp);
};
});
const closeHandler = () => {
if (!largeScreen) {
showTabs.set(false);
}
showArtifacts.set(false);
showEmbeds.set(false);
if ($showCallOverlay) showCallOverlay.set(false);
};
$: if (mounted && !chatId) closeHandler();
</script>
<svelte:window bind:innerWidth={viewportWidth} />
@@ -317,38 +554,108 @@
</div>
</Modal>
{#snippet panelContent()}
<div class="flex flex-col h-full min-h-0">
<div class="flex items-center justify-between px-2 pt-2 pb-2 shrink-0">
<div class="flex gap-1 min-w-0 overflow-x-auto scrollbar-hidden">
{#each panelTabs as tab (tab.id)}
<button
class="inline-flex items-center justify-center gap-1 px-2.5 py-0.5 text-sm rounded-lg transition whitespace-nowrap {activeTab ===
<div
class:hidden={!panelTarget}
use:placePanel={panelTarget}
class="h-full w-full min-h-0 flex flex-col"
id="controls-container"
>
<div class="flex items-center px-2 pt-1 pb-1 gap-1 shrink-0 select-none">
<div class="flex items-center gap-0.5 flex-1 min-w-0 py-0.5">
<div
role="tablist"
tabindex="-1"
aria-label={$i18n.t('Tabs')}
on:keydown={navigateTabs}
class="panel-tab-strip flex items-center gap-0.5 min-w-0 overflow-x-auto"
>
{#each tabs.tabs as tab (tab.id)}
<div
class="flex items-center gap-1.5 px-2.5 h-7 rounded-lg text-sm font-normal whitespace-nowrap shrink-0 transition {tabs.activeId ===
tab.id
? 'bg-gray-100/40 dark:bg-gray-800/25 font-normal text-gray-700 dark:text-gray-200'
? 'bg-gray-100/40 dark:bg-gray-800/25 text-gray-700 dark:text-gray-200'
: 'text-gray-500 dark:text-gray-400 hover:bg-gray-100/30 dark:hover:bg-gray-800/20 hover:text-gray-600 dark:hover:text-gray-300'}"
on:click={() => selectTab(tab.id)}
>
{tab.label}{#if tab.id === 'comments' && commentCount !== null && commentCount > 0}<span
class="text-[0.8125rem] leading-none text-gray-400/70 dark:text-gray-500/70"
>{commentCount}</span
>{/if}
</button>
<button
role="tab"
id={domId(tab.id)}
aria-controls={`${domId(tab.id)}-view`}
aria-selected={tabs.activeId === tab.id}
tabindex={tabs.activeId === tab.id ? 0 : -1}
title={tab.path ?? tab.label}
class="flex h-full items-center gap-1.5 min-w-0"
on:click={() => selectTab(tab.id)}
>
{#if tab.kind === 'file'}
<FileTypeIcon name={tab.label} />
{:else}
<Icon name={tabIcon(tab.kind)} size={14} />
{/if}
<span class="max-w-30 overflow-hidden text-ellipsis">{tab.label}</span>
{#if tab.kind === 'comments' && commentCount}<span class="text-gray-400"
>{commentCount}</span
>{/if}
</button>
{#if tab.untitled || dirtyFiles[tab.id]}<span
class="size-1.5 shrink-0 rounded-full bg-gray-400"
aria-label={$i18n.t('Unsaved changes')}
></span>{/if}
<button
type="button"
class="flex items-center justify-center w-4 h-4 rounded text-gray-400 hover:bg-gray-200 hover:text-gray-700 dark:hover:bg-white/10 dark:hover:text-white"
aria-label={tab.kind === 'voice'
? $i18n.t('End call')
: `${$i18n.t('Close')} ${tab.label}`}
on:click={() => closeTab(tab.id)}><Icon name="xmark" size={12} /></button
>
</div>
{/each}
</div>
<button
class="py-1 rounded-lg text-gray-500 hover:text-gray-900 dark:text-gray-400 dark:hover:text-gray-100 px-0 shrink-0"
on:click={() => showTabs.set(false)}
aria-label={$i18n.t('Close')}
>
<XMark className="size-4" />
</button>
<Dropdown align="end" closeOnSelect>
<button
type="button"
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
aria-label={$i18n.t('New tab')}><Icon name="plus" size={14} /></button
>
<div slot="content">
<DropdownMenu className="w-48">
{#if terminalFilesAvailable}<button on:click={newFile}
><Icon name="page" size={14} />{$i18n.t('New File')}</button
>{/if}
{#if terminalEnabled}<button on:click={newTerminal}
><Icon name="terminal" size={14} />{$i18n.t('New Terminal')}</button
>{/if}
{#each availableViews.filter((view) => view.kind !== 'files' && view.kind !== 'voice' && view.available) as view}
<button
on:click={() =>
openFeature(view.kind as 'artifacts' | 'preview' | 'voice' | 'comments')}
><Icon
name={tabIcon(view.kind as PanelTab['kind'])}
size={14}
/>{view.label}</button
>
{/each}
</DropdownMenu>
</div>
</Dropdown>
</div>
<div class="flex-1 min-h-0">
{#if $showCallOverlay}
<!-- Keep the call mounted while viewing another tab. -->
<div class="w-full h-full flex justify-center" class:hidden={activeTab !== 'voice'}>
<button
type="button"
class="flex items-center justify-center w-7 h-7 rounded-lg text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 transition-colors duration-100 shrink-0"
on:click={() => showTabs.set(false)}
aria-label={$i18n.t('Hide tabs')}><Icon name="xmark" size={12} /></button
>
</div>
<div class="relative flex-1 min-h-0">
{#each tabs.tabs as tab (tab.id)}
<div
id={`${domId(tab.id)}-view`}
role="tabpanel"
aria-labelledby={domId(tab.id)}
class="h-full w-full min-h-0"
class:hidden={tabs.activeId !== tab.id}
>
{#if tab.kind === 'voice'}
<CallPanel
{bridge}
bind:callMode
@@ -356,41 +663,99 @@
{submitPrompt}
{stopResponse}
{modelId}
{chatId}
chatId={chatId ?? ''}
{eventTarget}
on:close={() => showTabs.set(false)}
on:close={() => closeTab(tab.id)}
/>
</div>
{/if}
{#if activeTab === 'preview'}
<Embeds overlay={dragged} />
{:else if activeTab === 'artifacts'}
<Artifacts {history} overlay={dragged} />
{:else if activeTab === 'comments'}
{#if currentComments}
{#key `${$user.id}:${chatId}:${currentComments.comment_id ?? ''}`}
{:else if tab.kind === 'preview'}
<Embeds overlay={dragged} />
{:else if tab.kind === 'artifacts'}
<Artifacts overlay={dragged} />
{:else if tab.kind === 'comments' && currentComments}
{#key `${$user?.id}:${chatId}:${currentComments.comment_id ?? ''}`}
<CommentsPanel
embedded={true}
bind:view={currentComments}
onCountChange={setCommentCount}
/>
{/key}
{:else if tab.kind === 'terminal' && tab.connection}
<XTerminal
connection={tab.connection}
{chatId}
active={!!$showTabs && tabs.activeId === tab.id}
overlay={dragged}
/>
{:else if tab.untitled && tab.connection}
<UntitledFile
bind:this={fileViews[tab.id]}
bind:dirty={dirtyFiles[tab.id]}
label={tab.label}
connection={tab.connection}
{chatId}
initialDirectory={tab.context?.currentDirectory}
isOpen={(path) =>
tabs.tabs.some(
(item) =>
item.id !== tab.id &&
item.kind === 'file' &&
!item.untitled &&
item.terminalId === tab.terminalId &&
item.path === path
)}
onSaved={(path) => {
tabs = {
...tabs,
tabs: tabs.tabs.map((item) =>
item.id === tab.id
? {
...item,
untitled: false,
dirty: false,
path,
label: path.split('/').pop() || path
}
: item
)
};
}}
/>
{:else if (tab.kind === 'files' || tab.kind === 'file') && tab.terminalId}
<FileNav
bind:this={fileViews[tab.id]}
bind:dirty={dirtyFiles[tab.id]}
terminalId={tab.terminalId}
initialFile={tab.kind === 'file' ? { path: tab.path!, page: tab.page } : null}
initialDirectory={tab.kind === 'files' ? (tab.path ?? null) : null}
active={!!$showTabs && tabs.activeId === tab.id}
manageFileRequests={false}
showTerminalDock={false}
onOpenFile={(path, page) => openFile(path, tab.terminalId!, page)}
onBrowseDirectory={(path) => openFiles(tab.terminalId, path)}
{onAskFile}
overlay={dragged}
{chatId}
bind:terminalContext={fileContexts[tab.id]}
/>
{:else if tab.kind === 'files' && codeInterpreterEnabled}
<PyodideFileNav overlay={dragged} />
{/if}
{:else if activeTab === 'files' && terminalFilesAvailable && $selectedTerminalId}
<FileNav {onAskFile} overlay={dragged} {chatId} bind:terminalContext />
{:else if activeTab === 'files' && codeInterpreterEnabled}
<PyodideFileNav overlay={dragged} />
{/if}
</div>
</div>
{/each}
{#if !tabs.tabs.length}<div
class="flex h-full items-center justify-center p-4 text-center text-xs text-gray-400"
>
{$i18n.t('Open a tab using the + menu.')}
</div>{/if}
</div>
{/snippet}
</div>
{#if !largeScreen}
<MobileSwipePanel
open={!!$showTabs}
enabled={$mobile}
side="right"
blocked={$showSidebar || !sidePanelAvailable}
blocked={$showSidebar}
startTarget="#chat-container"
width={viewportWidth}
onOpenChange={(open) => showTabs.set(open)}
@@ -409,9 +774,7 @@
swipeSide={$mobile ? 'right' : undefined}
className="min-h-[100dvh] !bg-white dark:!bg-gray-850"
>
<div class="h-[100dvh] flex flex-col">
{@render panelContent()}
</div>
<div bind:this={panelTarget} class="h-[100dvh] flex flex-col"></div>
</Drawer>
{/if}
</MobileSwipePanel>
@@ -424,8 +787,15 @@
storageKey="chatControlsSize"
className="h-full z-10 bg-white dark:bg-gray-900"
>
<div class="h-full w-full z-40 pointer-events-auto" id="controls-container">
{@render panelContent()}
</div>
<div bind:this={panelTarget} class="h-full w-full z-40 pointer-events-auto"></div>
</ResizableSidePanel>
{/if}
<style>
.panel-tab-strip {
scrollbar-width: none;
}
.panel-tab-strip::-webkit-scrollbar {
display: none;
}
</style>
@@ -0,0 +1,258 @@
<script lang="ts">
import { getContext, onDestroy, onMount, tick } from 'svelte';
import { toast } from 'svelte-sonner';
import { formatFileSize } from '$lib/utils';
import {
getCwd,
listFiles,
uploadToTerminal,
joinTerminalPath,
type FileEntry,
type TerminalConnection
} from '$lib/apis/terminal';
import FileCodeEditor from '../FileNav/FileCodeEditor.svelte';
import Icon from '../FileNav/Icon.svelte';
import FileTypeIcon from '../FileNav/FileTypeIcon.svelte';
import Modal from '../../common/Modal.svelte';
import ConfirmDialog from '../../common/ConfirmDialog.svelte';
const i18n = getContext<any>('i18n');
export let label: string;
export let connection: TerminalConnection;
export let chatId: string | null = null;
export let initialDirectory: string | undefined = undefined;
export let dirty = false;
export let onSaved: (path: string) => void;
export let isOpen: (path: string) => boolean;
let value = '';
let editor: FileCodeEditor;
let saving = false;
let showSave = false;
let fileName = label;
let directory = initialDirectory ?? '/';
let root = '/';
let entries: FileEntry[] = [];
let loading = false;
let writable = false;
let showHidden = false;
let error = '';
let replacePath = '';
let disposed = false;
let fileNameInput: HTMLInputElement;
let saveResult: ((saved: boolean) => void) | null = null;
let closeChoice: ((choice: 'save' | 'discard' | 'cancel') => void) | null = null;
$: dirty = value.length > 0;
$: byteCount = new TextEncoder().encode(value).length;
$: fullPath = joinTerminalPath(directory, fileName.trim());
$: if (fullPath !== replacePath) replacePath = '';
const browse = async (path: string) => {
loading = true;
error = '';
const listing = await listFiles(connection.baseUrl, connection.key, path, chatId ?? undefined);
if (disposed) return;
loading = false;
writable = listing?.writable !== false && !!listing;
if (!listing) {
error = $i18n.t('Failed to load directory');
return;
}
directory = path;
entries = listing.entries;
};
const finishSave = (saved: boolean) => {
showSave = false;
saveResult?.(saved);
saveResult = null;
};
const save = async () => {
if (saving || showSave) return false;
const result = new Promise<boolean>((resolve) => {
saveResult = resolve;
});
showSave = true;
loading = true;
fileName = label;
replacePath = '';
const cwd = await getCwd(connection.baseUrl, connection.key, chatId ?? undefined);
if (disposed || !showSave) return false;
root = (cwd?.root?.path ?? '/').replace(/\/$/, '') || '/';
await browse(initialDirectory ?? cwd?.cwd ?? cwd?.home ?? root);
await tick();
fileNameInput?.focus();
fileNameInput?.select();
return result;
};
const write = async () => {
if (saving || loading || !writable) return;
const name = fileName.trim();
if (!name || name === '.' || name === '..' || /[\\/\0]/.test(name)) {
error = $i18n.t('Enter a file name without slashes.');
return;
}
if (isOpen(fullPath)) {
error = $i18n.t('This file is already open. Close its tab or choose another name.');
return;
}
saving = true;
error = '';
try {
const listing = await listFiles(
connection.baseUrl,
connection.key,
directory,
chatId ?? undefined
);
if (!listing || listing.writable === false) throw new Error($i18n.t('File is not writable.'));
const existing = listing.entries.find((entry) => entry.name === name);
if (existing?.type === 'directory' || existing?.writable === false)
throw new Error($i18n.t('File is not writable.'));
if (existing && replacePath !== fullPath) {
replacePath = fullPath;
error = $i18n.t('A file with this name already exists. Replace it?');
return;
}
const result = await uploadToTerminal(
connection.baseUrl,
connection.key,
directory,
new File([value], name, { type: 'text/plain' }),
chatId ?? undefined
);
if (!result)
throw new Error($i18n.t('Failed to save file. Your changes are still in the editor.'));
dirty = false;
finishSave(true);
onSaved(result.path || fullPath);
} catch (reason) {
error = reason instanceof Error ? reason.message : String(reason);
} finally {
saving = false;
}
};
export const hasUnsavedChanges = () => dirty || saving;
export const requestClose = async () => {
if (saving || showSave || closeChoice) return false;
if (!dirty) return true;
const choice = await new Promise<'save' | 'discard' | 'cancel'>((resolve) => {
closeChoice = resolve;
});
closeChoice = null;
await tick();
return choice === 'discard' || (choice === 'save' && (await save()));
};
onMount(() => {
editor?.focus();
});
onDestroy(() => {
disposed = true;
saveResult?.(false);
closeChoice?.('cancel');
});
</script>
<div class="flex h-full min-h-0 flex-col">
<div class="m-0 flex shrink-0 items-center gap-1 px-2 pt-0 pb-1.5">
<span class="min-w-0 flex-1 truncate text-xs text-gray-700 dark:text-gray-300" title={label}
>{label}</span
>
<span class="shrink-0 text-[0.6875rem] text-gray-400">{formatFileSize(byteCount)}</span>
<button
class="flex size-5 shrink-0 items-center justify-center rounded text-gray-400 dark:text-gray-500 hover:text-gray-600 dark:hover:text-gray-300"
aria-label={$i18n.t('Save')}
title={$i18n.t('Save')}
on:click={() => void save().catch((e) => toast.error(String(e)))}
><Icon name="save" size={11} strokeWidth={1.4} /></button
>
</div>
<div class="relative flex-1 min-h-0">
<FileCodeEditor
bind:this={editor}
bind:value
ariaLabel={$i18n.t('File content')}
onSave={async () => {
await save();
}}
/>
</div>
</div>
<Modal
show={showSave}
size="sm"
ariaLabel={$i18n.t('Save As')}
onRequestClose={() => {
if (!saving) finishSave(false);
}}
className="bg-white dark:bg-gray-900 rounded-2xl"
>
<form class="flex max-h-[26rem] flex-col p-3 text-sm" on:submit|preventDefault={write}>
<label class="flex items-center gap-2 pb-3">
<FileTypeIcon name={fileName} />
<input
bind:this={fileNameInput}
bind:value={fileName}
disabled={saving}
aria-label={$i18n.t('File name')}
class="min-w-0 flex-1 bg-transparent outline-none"
/>
</label>
<div class="flex h-8 items-center gap-2 text-xs text-gray-500">
<button
type="button"
class="size-6 shrink-0"
disabled={loading || saving || directory.replace(/\/$/, '') === root.replace(/\/$/, '')}
aria-label={$i18n.t('Parent directory')}
on:click={() =>
browse(directory.replace(/\/$/, '').split('/').slice(0, -1).join('/') || '/')}
><Icon name="chevron-left" size={14} /></button
>
<span class="min-w-0 flex-1 truncate" title={directory}>{directory}</span>
<label class="flex items-center gap-1"
><input type="checkbox" bind:checked={showHidden} />{$i18n.t('Hidden')}</label
>
</div>
<div class="min-h-24 overflow-y-auto py-1">
{#if loading}<p class="p-3 text-xs text-gray-400">{$i18n.t('Loading...')}</p>
{:else}{#each entries.filter((entry) => entry.type === 'directory' && (showHidden || !entry.name.startsWith('.'))) as entry}
<button
type="button"
disabled={saving}
class="flex h-7 w-full items-center gap-2 rounded-lg px-2 text-left text-xs hover:bg-gray-100/40 dark:hover:bg-gray-800/25"
on:click={() => browse(joinTerminalPath(directory, entry.name))}
><FileTypeIcon name={entry.name} type="directory" /><span class="truncate"
>{entry.name}</span
></button
>
{/each}{/if}
</div>
{#if error}<p role="alert" class="py-2 text-xs text-red-500">{error}</p>{/if}
<div class="flex items-center gap-2 pt-2">
<span class="min-w-0 flex-1 truncate text-xs text-gray-400" title={fullPath}>{fullPath}</span>
<button
type="button"
disabled={saving}
class="rounded-lg px-2 py-1 text-xs"
on:click={() => finishSave(false)}>{$i18n.t('Cancel')}</button
>
<button
type="submit"
disabled={saving || loading || !writable || !fileName.trim()}
class="rounded-lg bg-gray-100 px-3 py-1 text-xs disabled:opacity-40 dark:bg-gray-800"
>{$i18n.t(replacePath ? 'Replace' : 'Save')}</button
>
</div>
</form>
</Modal>
<ConfirmDialog
show={closeChoice !== null}
title={$i18n.t('Unsaved changes')}
confirmLabel={$i18n.t('Save')}
on:confirm={() => closeChoice?.('save')}
on:cancel={() => closeChoice?.('cancel')}
>
<button class="rounded-lg px-3 py-2 text-sm" on:click={() => closeChoice?.('discard')}
>{$i18n.t('Discard changes')}</button
>
</ConfirmDialog>
@@ -0,0 +1,38 @@
import { describe, expect, it } from 'vitest';
import { activateTab, emptyTabs, fileTabId, openTab, removeTab, type PanelTab } from './tabs';
const tab = (id: string, kind: PanelTab['kind'] = 'file'): PanelTab => ({ id, kind, label: id });
describe('chat panel tabs', () => {
it('reuses an open file and keeps files from different terminals separate', () => {
const a = tab(fileTabId('server-a', '/readme.md'));
const b = tab(fileTabId('server-b', '/readme.md'));
let state = openTab(openTab(emptyTabs(), a), b);
state = openTab(state, a);
expect(state.tabs).toHaveLength(2);
expect(state.activeId).toBe(a.id);
});
it('keeps independent shells and returns to the most recently used tab on close', () => {
let state = openTab(
openTab(openTab(emptyTabs(), tab('files', 'files')), tab('shell-1', 'terminal')),
tab('shell-2', 'terminal')
);
state = activateTab(state, 'files');
state = activateTab(state, 'shell-2');
state = removeTab(state, 'shell-2');
expect(state.activeId).toBe('files');
expect(state.tabs.map((item) => item.id)).toEqual(['files', 'shell-1']);
});
it('closes a feature view without automatically reopening it and can reopen it explicitly', () => {
let state = openTab(emptyTabs(), tab('artifacts', 'artifacts'));
state = removeTab(state, 'artifacts');
expect(state).toEqual(emptyTabs());
state = openTab(state, tab('artifacts', 'artifacts'));
expect(state.activeId).toBe('artifacts');
});
it('closing an inactive tab leaves the active tab selected', () => {
const state = removeTab(openTab(openTab(emptyTabs(), tab('a')), tab('b')), 'a');
expect(state.activeId).toBe('b');
expect(state.history).toEqual([]);
});
});
@@ -0,0 +1,66 @@
import type { TerminalContext } from '$lib/types';
import type { TerminalConnection } from '$lib/apis/terminal';
export type PanelTabKind =
| 'files'
| 'file'
| 'terminal'
| 'artifacts'
| 'preview'
| 'voice'
| 'comments';
export type PanelTab = {
id: string;
kind: PanelTabKind;
label: string;
terminalId?: string;
path?: string;
page?: number | null;
dirty?: boolean;
untitled?: boolean;
connection?: TerminalConnection;
context?: TerminalContext | null;
};
export type PanelTabs = { tabs: PanelTab[]; activeId: string; history: string[] };
export const emptyTabs = (): PanelTabs => ({ tabs: [], activeId: '', history: [] });
export function activateTab(state: PanelTabs, id: string): PanelTabs {
if (!state.tabs.some((tab) => tab.id === id) || state.activeId === id) return state;
return {
...state,
activeId: id,
history: [
...state.history.filter((entry) => entry !== id && entry !== state.activeId),
state.activeId
].filter(Boolean)
};
}
export function openTab(state: PanelTabs, tab: PanelTab): PanelTabs {
return activateTab(
state.tabs.some((item) => item.id === tab.id)
? state
: { ...state, tabs: [...state.tabs, tab] },
tab.id
);
}
export function removeTab(state: PanelTabs, id: string): PanelTabs {
const tabs = state.tabs.filter((tab) => tab.id !== id);
const history = state.history.filter(
(entry) => entry !== id && tabs.some((tab) => tab.id === entry)
);
const index = state.tabs.findIndex((tab) => tab.id === id);
return {
tabs,
activeId:
state.activeId === id
? (history.at(-1) ?? tabs[Math.max(0, index - 1)]?.id ?? '')
: state.activeId,
history
};
}
export const fileTabId = (terminalId: string, path: string) =>
JSON.stringify(['file', terminalId, path]);
+84 -44
View File
@@ -1,16 +1,3 @@
<script context="module">
// Keep keys in nested template expressions visible to i18next-parser.
// $i18n.t("Unknown error");
// Persists across mount/unmount cycles (module-level, not per-instance)
let savedPath = '/';
let savedFileRoot = null;
/** @type {Map<string, string[]>} */
const treeExpandedCache = new Map();
/** @type {Map<string, [string, any[]][]>} */
const treeContentsCache = new Map();
</script>
<script lang="ts">
import type { TerminalContext } from '$lib/types';
import { filesystemFile, type FilesystemFile } from '$lib/apis/terminal';
@@ -70,9 +57,25 @@
import PortPreview from './FileNav/PortPreview.svelte';
import TerminalDock from './TerminalDock.svelte';
// Directory and preview state belong to this tab, including its terminal connection.
let savedPath = '/';
let savedFileRoot: TerminalFileRoot | null = null;
const treeExpandedCache = new Map<string, string[]>();
const treeContentsCache = new Map<string, [string, FileEntry[]][]>();
const i18n = getContext<Readable<I18n>>('i18n');
export let overlay = false;
export let active = true;
export let terminalId: string | null = null;
export let initialFile: { path: string; page?: number | null } | null = null;
export let initialDirectory: string | null = null;
export let manageFileRequests = true;
export let showTerminalDock = true;
export let onOpenFile: ((path: string, page?: number | null) => void) | null = null;
export let onBrowseDirectory: ((path: string) => void) | null = null;
$: effectiveTerminalId = terminalId ?? $selectedTerminalId;
export let chatId: string | null = null;
export let terminalContext: TerminalContext | null = null;
export let onAskFile: ((instruction: string, file: FilesystemFile) => Promise<void>) | null =
@@ -138,7 +141,7 @@
let pendingFile: FilesystemFile | null = null;
let viewerLabel = '';
let loadGeneration = 0;
let dirty = false;
export let dirty = false;
let diskChanged = false;
let saveConnection: { url: string; key: string; chatId: string | null; path: string } | null =
null;
@@ -169,6 +172,13 @@
}
return true;
};
export const requestClose = () => protectBuffer();
export const hasUnsavedChanges = () => dirty || saving;
export const browseDirectory = (path: string) => loadDir(path);
export const revealPage = (page: number | null) => {
documentTargetPage = normalizeDocumentTargetPage(page);
};
const publishFile = () => {
if (!openedFile) return;
terminalContext = {
@@ -214,7 +224,7 @@
if (
!openedFile ||
openedFile.path !== target.path ||
openedFile.terminal_id !== $selectedTerminalId ||
openedFile.terminal_id !== effectiveTerminalId ||
openedFile.session_id !== chatId
)
throw new Error('The file or terminal changed. Open it again before sending.');
@@ -228,7 +238,7 @@
if (terminalContext) terminalContext = { ...terminalContext, file: null };
}
$: {
(selectedFile, $selectedTerminalId, chatId);
(selectedFile, effectiveTerminalId, chatId);
fileAsk = null;
}
$: viewerLabel = selectedExcelSheet
@@ -610,8 +620,8 @@
const chatContext = (terminal: any) => terminal?.contexts?.chat ?? {};
const getTerminal = (): { url: string; key: string } | null => {
const systemTerminal = $selectedTerminalId
? (($terminalServers ?? []).find((t) => t.id === $selectedTerminalId) ?? null)
const systemTerminal = effectiveTerminalId
? (($terminalServers ?? []).find((t) => t.id === effectiveTerminalId) ?? null)
: ($terminalServers?.[0] ?? null);
const chatConfig = chatContext(systemTerminal);
isPerChatTerminal = !!systemTerminal && chatConfig?.context_id === 'chat_id';
@@ -624,7 +634,7 @@
const settingsValue: any = $settings;
const userTerminal = (settingsValue?.terminalServers ?? []).find(
(s: any) => s.url === $selectedTerminalId
(s: any) => s.url === effectiveTerminalId
);
const isSystem = !!systemTerminal;
@@ -638,11 +648,12 @@
// Svelte re-runs this block when any of them update.
// The `mounted` flag prevents the initial run from racing with onMount.
let prevTerminalUrl = '';
let prevTerminalId = $selectedTerminalId;
let prevTerminalId = effectiveTerminalId;
let prevChatId = chatId;
let mounted = false;
let disposed = false;
$: {
($selectedTerminalId, $terminalServers, $settings);
(effectiveTerminalId, $terminalServers, $settings);
const terminal = getTerminal();
selectedTerminal = terminal;
@@ -651,10 +662,10 @@
if (chatChanged) prevChatId = chatId;
const terminalChanged =
terminal && (terminal.url !== prevTerminalUrl || $selectedTerminalId !== prevTerminalId);
terminal && (terminal.url !== prevTerminalUrl || effectiveTerminalId !== prevTerminalId);
if (terminalChanged) {
prevTerminalUrl = terminal.url;
prevTerminalId = $selectedTerminalId;
prevTerminalId = effectiveTerminalId;
}
if (chatChanged || terminalChanged || !terminal) {
@@ -685,6 +696,7 @@
(async () => {
if (terminalChanged) {
const config = await getTerminalConfig(terminal.url, terminal.key);
if (disposed) return;
terminalEnabled = config?.features?.terminal !== false;
}
@@ -982,9 +994,10 @@
path: string,
options: { preserveTree?: boolean; restoreTree?: boolean } = {}
) => {
if (disposed) return;
if (!(await protectBuffer())) return;
const generation = ++loadGeneration;
const selector = $selectedTerminalId,
const selector = effectiveTerminalId,
session = chatId;
const terminal = selectedTerminal;
if (!terminal) return;
@@ -1006,17 +1019,17 @@
clearFilePreview();
clearSelection();
currentPath = directory;
terminalContext = { terminalId: $selectedTerminalId, currentDirectory: directory };
terminalContext = { terminalId: effectiveTerminalId, currentDirectory: directory };
savedPath = directory;
pushNavHistory(directory);
const result = await listFiles(terminal.url, terminal.key, directory, chatId ?? undefined);
if (generation !== loadGeneration || selector !== $selectedTerminalId || session !== chatId)
if (generation !== loadGeneration || selector !== effectiveTerminalId || session !== chatId)
return;
loading = false;
// Set working directory on the terminal server (fire-and-forget)
setCwd(terminal.url, terminal.key, directory, chatId ?? undefined);
if (!initialFile) setCwd(terminal.url, terminal.key, directory, chatId ?? undefined);
if (result === null) {
error =
@@ -1087,6 +1100,7 @@
entry: FileEntry,
options: { page?: unknown; refresh?: boolean } = {}
) => {
if (disposed) return;
const fullPath =
'fullPath' in entry ? (entry as BrowserRow).fullPath : entryPath(currentPath, entry);
const parentPath = 'parentPath' in entry ? (entry as BrowserRow).parentPath : currentPath;
@@ -1095,6 +1109,11 @@
return;
}
if (onOpenFile && !options.refresh && fullPath !== initialFile?.path) {
onOpenFile(fullPath, normalizeDocumentTargetPage(options.page));
return;
}
if (options.refresh && (dirty || saving)) {
diskChanged = true;
return;
@@ -1111,14 +1130,14 @@
if (!terminal) return;
const generation = ++loadGeneration;
const selector = $selectedTerminalId!,
const selector = effectiveTerminalId!,
session = chatId;
const previousView =
openedFile?.path === filePath
? { showRaw, currentSlide, selectedExcelSheet, scroll: viewerRoot?.scrollTop ?? 0 }
: null;
const current = () =>
generation === loadGeneration && selector === $selectedTerminalId && session === chatId;
generation === loadGeneration && selector === effectiveTerminalId && session === chatId;
openedFile = null;
if (terminalContext) terminalContext = { ...terminalContext, file: null };
dirty = false;
@@ -1565,7 +1584,7 @@
if (!name) return;
const terminal = selectedTerminal;
if (!terminal) return;
if (!terminal || !currentWritable) return;
const emptyFile = new File([''], name, { type: 'application/octet-stream' });
const result = await uploadToTerminal(
@@ -1809,6 +1828,7 @@
// Click outside panel to clear selection
const handleWindowClick = (e: MouseEvent) => {
if (!active) return;
// A close click may reach the window after its modal has already been destroyed.
if (
e.composedPath().some((node) => node instanceof Element && node.classList.contains('modal'))
@@ -1834,7 +1854,7 @@
let handledDisplayFile = false;
const unsubFileNav = showFileNavPath.subscribe(async (request) => {
if (!request || !selectedTerminal || comparison) return;
if (!manageFileRequests || !active || !request || !selectedTerminal || comparison) return;
handledDisplayFile = true;
showFileNavPath.set(null);
let filePath = typeof request === 'string' ? request : request.path;
@@ -1851,10 +1871,10 @@
// Always reload directory to ensure entries are fresh
if (!(await protectBuffer())) return;
const selector = $selectedTerminalId,
const selector = effectiveTerminalId,
session = chatId;
await loadDir(dir);
if (selector !== $selectedTerminalId || session !== chatId || currentPath !== dir || dirty)
if (selector !== effectiveTerminalId || session !== chatId || currentPath !== dir || dirty)
return;
await tick();
@@ -1868,7 +1888,7 @@
});
const unsubFileNavDir = showFileNavDir.subscribe(async (filePath) => {
if (!filePath || !selectedTerminal) return;
if (!filePath || !selectedTerminal || effectiveTerminalId !== $selectedTerminalId) return;
showFileNavDir.set(null);
filePath = normalizePath(filePath);
if (!isInsideFileRoot(filePath)) {
@@ -1901,13 +1921,28 @@
terminalEnabled = config?.features?.terminal !== false;
const serverCwd = await getCwd(terminal.url, terminal.key, chatId ?? undefined);
if (disposed) return;
const serverPath = applyCwd(serverCwd);
savedPath =
terminalContext && terminalContext.terminalId === $selectedTerminalId
terminalContext && terminalContext.terminalId === effectiveTerminalId
? terminalContext.currentDirectory
: serverPath;
savedPath = clampToFileRoot(savedPath);
loadDir(savedPath, { restoreTree: true });
if (initialFile) {
const path = normalizePath(initialFile.path);
const slash = path.lastIndexOf('/');
await loadDir(slash > 0 ? path.slice(0, slash + 1) : '/');
await openEntry(
entries.find((entry) => entry.name === path.slice(slash + 1)) ?? {
name: path.slice(slash + 1),
type: 'file',
writable: currentWritable
},
{ page: initialFile.page }
);
} else {
await loadDir(initialDirectory ?? savedPath, { restoreTree: true });
}
})();
}
@@ -1923,6 +1958,7 @@
const onVisibilityChange = () => {
if (
active &&
document.visibilityState === 'visible' &&
!comparison &&
!selectedFile &&
@@ -1950,6 +1986,7 @@
});
onDestroy(() => {
disposed = true;
++loadGeneration;
dirtyChoice?.resolve('cancel');
clearMatchRequest();
@@ -1975,6 +2012,7 @@
<svelte:window
on:keydown={(event) => {
if (!active) return;
if (event.key === 'Escape' && fileAsk) {
fileAsk = null;
event.preventDefault();
@@ -2063,8 +2101,8 @@
{selectedFile}
{loading}
writable={currentWritable}
{canGoBack}
{canGoForward}
canGoBack={!initialFile && canGoBack}
canGoForward={!initialFile && canGoForward}
{sortBy}
{sortAsc}
showDateAdded
@@ -2073,7 +2111,7 @@
onViewModeChange={changeViewMode}
onGoBack={goBack}
onGoForward={goForward}
onNavigate={loadDir}
onNavigate={initialFile && onBrowseDirectory ? onBrowseDirectory : loadDir}
onRefresh={() => {
if (selectedFile) {
const fileName = selectedFile.split('/').pop() ?? '';
@@ -2361,7 +2399,7 @@
bind:dirty
{chatId}
resourceVersion={commentGeneration}
onLocalLink={(path) => showFileNavPath.set({ path })}
onLocalLink={(path) => (onOpenFile ? onOpenFile(path) : showFileNavPath.set({ path }))}
bind:currentSlide
{selectedFile}
readOnly={!selectedFileWritable}
@@ -2518,7 +2556,7 @@
<Spinner className="size-4" />
{$i18n.t('Uploading...')}
</div>
{:else if loading || ($selectedTerminalId && $terminalServers === null)}
{:else if loading || (effectiveTerminalId && $terminalServers === null)}
<div class="flex justify-center pt-8"><Spinner className="size-4" /></div>
{:else if error}
<div class="p-4 text-xs">{error}</div>
@@ -2530,7 +2568,7 @@
</div>
{/if}
{#if !isSearching && !loading && !error && !uploading && !($selectedTerminalId && $terminalServers === null)}
{#if !isSearching && !loading && !error && !uploading && !(effectiveTerminalId && $terminalServers === null)}
{#if visibleEntries.length > 0 || creatingFolder || creatingFile}
<ul
class={viewMode === 'grid'
@@ -2686,7 +2724,7 @@
{/if}
<!-- Terminal bottom panel -->
{#if terminalEnabled}
{#if terminalEnabled && showTerminalDock}
<div class="shrink-0 border-t border-gray-50 dark:border-gray-850/30">
{#if terminalExpanded}
<!-- Drag handle (at top of panel) -->
@@ -2699,8 +2737,10 @@
</div>
{/if}
{#key JSON.stringify([chatId, $selectedTerminalId])}
{#key JSON.stringify([chatId, effectiveTerminalId])}
<TerminalDock
terminalId={effectiveTerminalId}
{active}
overlay={overlay || isDraggingHandle}
bind:expanded={terminalExpanded}
height={terminalHeight}
@@ -1,6 +1,6 @@
<script lang="ts">
import { getContext, onMount } from 'svelte';
import { config, showCallOverlay, showTabs } from '$lib/stores';
import { createEventDispatcher, getContext, onMount } from 'svelte';
import { config, showCallOverlay } from '$lib/stores';
import type { RealtimeCall } from '$lib/utils/realtime';
import CallOverlay from './CallOverlay.svelte';
import BridgeCallOverlay from './CallOverlay/BridgeCallOverlay.svelte';
@@ -16,10 +16,11 @@
export let chatId: string;
export let eventTarget: EventTarget;
let started = false;
const dispatch = createEventDispatcher();
const close = () => {
showCallOverlay.set(false);
showTabs.set(false);
dispatch('close');
};
onMount(() => {
+14 -5
View File
@@ -13,6 +13,8 @@
import Icon from './FileNav/Icon.svelte';
export let chatId: string | null = null;
export let terminalId: string | null = null;
export let active = true;
export let expanded = false;
export let height = 200;
export let overlay = false;
@@ -144,7 +146,7 @@
onMount(() => {
connection = resolveTerminalConnection(
$selectedTerminalId,
terminalId ?? $selectedTerminalId,
$terminalServers ?? [],
($settings as { terminalServers?: { url: string; key?: string }[] })?.terminalServers ?? [],
localStorage.getItem('token') ?? ''
@@ -257,8 +259,15 @@
<Icon name={expanded ? 'chevron-down' : 'chevron-up'} size={12} />
</button>
</div>
<div style:height={`${height}px`} class="flex min-h-0 flex-col bg-black" class:hidden={!expanded}>
{#if error}<div class="shrink-0 truncate px-2 text-xs text-red-400" title={error}>
<div
style:height={`${height}px`}
class="flex min-h-0 flex-col bg-white dark:bg-black"
class:hidden={!expanded}
>
{#if error}<div
class="shrink-0 truncate px-2 text-xs text-red-600 dark:text-red-400"
title={error}
>
{error}
</div>{/if}
<div class="relative min-h-0 flex-1">
@@ -268,7 +277,7 @@
{connection}
{chatId}
{overlay}
active={expanded && activeId === 'shell'}
active={active && expanded && activeId === 'shell'}
bind:connected
bind:connecting
/>
@@ -284,7 +293,7 @@
{chatId}
{overlay}
readOnly
active={expanded && activeId === tab.id}
active={active && expanded && activeId === tab.id}
/>
</div>
{/if}
+29 -7
View File
@@ -20,6 +20,7 @@
let fitAddon: FitAddon;
let ws: WebSocket | null = null;
let resizeObserver: ResizeObserver;
let themeObserver: MutationObserver;
let pingInterval: ReturnType<typeof setInterval>;
let destroyed = false;
let sessionId = '';
@@ -47,6 +48,25 @@
if (active && terminalEl?.clientWidth && terminalEl?.clientHeight) fitAddon?.fit();
}
function updateTheme() {
if (!term) return;
term.options.theme = document.documentElement.classList.contains('dark')
? {
background: '#000000',
foreground: '#c0c0c0',
cursor: '#ffffff',
cursorAccent: '#000000',
selectionBackground: '#444444'
}
: {
background: '#ffffff',
foreground: '#171717',
cursor: '#171717',
cursorAccent: '#ffffff',
selectionBackground: '#bfdbfe'
};
}
async function connect() {
connecting = true;
try {
@@ -119,14 +139,15 @@
fontSize: 13,
fontFamily:
"'JetBrains Mono', 'Fira Code', 'Cascadia Code', Menlo, Monaco, 'Courier New', monospace",
theme: {
background: '#000000',
foreground: '#c0c0c0',
cursor: '#ffffff',
selectionBackground: '#444444'
},
minimumContrastRatio: 4.5,
scrollback: 5000
});
updateTheme();
themeObserver = new MutationObserver(updateTheme);
themeObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class']
});
fitAddon = new FitAddon();
term.loadAddon(fitAddon);
term.loadAddon(new WebLinksAddon());
@@ -155,12 +176,13 @@
disconnect();
ws?.close();
resizeObserver?.disconnect();
themeObserver?.disconnect();
term?.dispose();
term = null;
});
</script>
<div class="h-full min-h-0 relative">
<div class="h-full min-h-0 relative bg-white dark:bg-black">
<div
bind:this={terminalEl}
class="absolute inset-0 px-0.5"