This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-10 22:23:31 +09:00
1 parent cec9fdd127
commit 3d98e86e2d
22 files changed
+981 -550

No files matched your search

+2
View File
@@ -382,6 +382,8 @@ export const userSignUp = async (
export const userSignOut = async () => {
const { clearChatViews } = await import('$lib/stores/chatViewStates');
clearChatViews();
const { clearFolderStates } = await import('$lib/stores/folderStates');
clearFolderStates();
const token = localStorage.getItem('token');
// Stop local access even if the hosted server cannot be reached.
await window.tether?.signedOut();
+11 -5
View File
@@ -78,14 +78,17 @@ export const getFolderById = async (token: string, id: string) => {
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw Object.assign(new Error(body.detail ?? res.statusText), { status: res.status });
}
return res.json();
})
.then((json) => {
return json;
})
.catch((err) => {
error = err.detail;
error = err;
console.error(err);
return null;
});
@@ -333,7 +336,7 @@ export const getSharedFolderChats = async (
folderId: string,
params: {
page?: number | null;
sortBy?: 'title' | 'updated_at';
sortBy?: 'title' | 'updated_at' | 'unread_updated_at';
sortDir?: 'asc' | 'desc';
} = {}
) => {
@@ -363,11 +366,14 @@ export const getSharedFolderChats = async (
}
)
.then(async (res) => {
if (!res.ok) throw await res.json();
if (!res.ok) {
const body = await res.json().catch(() => ({}));
throw Object.assign(new Error(body.detail ?? res.statusText), { status: res.status });
}
return res.json();
})
.catch((err) => {
error = err.detail;
error = err;
return null;
});
+91 -49
View File
@@ -61,6 +61,11 @@
desktopEvent
} from '$lib/stores';
import { refreshChatList, refreshFolderChatLists } from '$lib/stores/chatList';
import {
getFolderAgentModels, loadFolderAgentModels, setFolderModelConnections,
isCancelledFolderRequest, updateFolderChatLists,
type FolderDetails
} from '$lib/stores/folderStates';
import { WEBUI_API_BASE_URL } from '$lib/constants';
@@ -166,7 +171,7 @@
const chatTitle = embedded ? writable('') : _chatTitle;
const audioQueue = embedded ? writable<AudioQueue | null>(null) : _audioQueue;
const temporaryChatEnabled = embedded ? writable(false) : _temporaryChatEnabled;
const selectedFolder = embedded ? writable(null) : _selectedFolder;
const selectedFolder = embedded ? writable<FolderDetails | null>(null) : _selectedFolder;
const showTabs = embedded ? writable(get(_showTabs)) : _showTabs;
const showCallOverlay = embedded ? writable(false) : _showCallOverlay;
const showArtifacts = embedded ? writable(false) : _showArtifacts;
@@ -1087,42 +1092,70 @@
}
let lastTerminalSkillSelector: string | null = null;
let agentDiscovery = 0;
const refreshAgentModels = async () => {
const generation = ++agentDiscovery;
models.update((available) =>
available.filter(
(model) => model.owned_by !== 'terminal' || model.agent.terminal_id === $selectedTerminalId
)
);
try {
const available = await getModels(
localStorage.token,
$config?.features?.enable_direct_connections ? ($settings?.directConnections ?? null) : null
);
if (generation === agentDiscovery) {
let appliedFolderDefaults: FolderDetails['data'] = null;
$: setFolderModelConnections([
$config?.features?.enable_direct_connections,
$settings?.directConnections,
(($settings as any)?.terminalServers ?? []).map(({ enabled, ...server }: Record<string, unknown>) => server),
$terminalServers
]);
const refreshAgentModels = async (
folder: FolderDetails | null = null,
signal = chatLoadController.signal
) => {
const terminalId = $selectedTerminalId;
const retained = folder ? getFolderAgentModels(folder) : null;
models.update((available) => [
...available.filter((model) => model.owned_by !== 'terminal' ||
(!folder && model.agent.terminal_id === $selectedTerminalId)),
...(retained ?? [])
]);
const refresh = async () => {
try {
const connections = $config?.features?.enable_direct_connections
? ($settings?.directConnections ?? null) : null;
const discovered = folder
? await loadFolderAgentModels(localStorage.token, folder, connections, !!retained)
: await getModels(localStorage.token, connections);
if (signal.aborted || terminalId !== $selectedTerminalId) return;
if (folder && ($selectedFolder?.id !== folder.id ||
$selectedTerminalId !== folder.data?.terminal_id ||
terminalContext?.currentDirectory !== (folder.data?.working_directory ?? '') ||
!getFolderAgentModels(folder))) return;
const available = folder
? [...$models.filter((model) => model.owned_by !== 'terminal'), ...discovered]
: discovered;
models.set(available);
// Folder refreshes update the catalog without overwriting a draft's model choice.
if (folder) return;
const remaining = selectedModels.filter(
(id) =>
!id.startsWith('agent:') ||
(id) => !id.startsWith('agent:') ||
(chat?.chat?.models?.includes(id) && decodeURIComponent(id.split(':')[1]) === $selectedTerminalId) ||
available.some((model: Model) => model.id === id)
);
selectedModels =
remaining.length || equal(remaining, selectedModels)
? remaining
: normalizeSelectedModels(remaining);
selectedModels = remaining.length || equal(remaining, selectedModels)
? remaining : normalizeSelectedModels(remaining);
} catch (error) {
if (!isCancelledFolderRequest(error)) console.error('Agent model discovery failed', error);
}
} catch (error) {
console.error('Agent model discovery failed', error);
}
};
if (retained) void refresh();
else await refresh();
};
$: if ($selectedTerminalId !== lastTerminalSkillSelector) {
if (terminalContext?.terminalId !== $selectedTerminalId) terminalContext = null;
selectedSkillIds = selectedSkillIds.filter((id) => !id.startsWith('terminal:'));
terminalSkills.set([]);
lastTerminalSkillSelector = $selectedTerminalId;
void refreshAgentModels();
// Folder initialization already requests this exact environment.
if (!((loading || !history.currentId) && $selectedFolder?.data?.terminal_id === $selectedTerminalId)) {
void refreshAgentModels();
}
}
const applyFolderTerminal = (folder: any) => {
@@ -1756,6 +1789,7 @@
// Update message favorite status
message.favorite = data.favorite;
} else if (type === 'chat:title') {
updateFolderChatLists({ id: event.chat_id, title: data });
chatTitle.set(data);
if (embedded && $chatId) {
await onEmbeddedChatTitle?.($chatId, data);
@@ -2038,18 +2072,14 @@
const selectedFolderSubscribe = selectedFolder.subscribe(async (folder) => {
await tick();
// Folder defaults apply to new chats only.
if (!history.currentId && folder) {
applyFolderTerminal(folder);
if (folder.data?.terminal_id) {
await refreshAgentModels();
if (history.currentId || $selectedFolder?.id !== folder.id) return;
}
const folderModels = normalizeSelectedModels(folder.data?.model_ids ?? []);
if (!equal(selectedModels, folderModels)) {
selectedModels = folderModels;
}
}
// Navigation applies defaults in initNewChat; only explicit settings edits reach here.
if (loading || history.currentId || !folder || mainChatHref !== `/folders/${folder.id}` ||
equal(appliedFolderDefaults, folder.data)) return;
appliedFolderDefaults = folder.data;
applyFolderTerminal(folder);
if (folder.data?.terminal_id) await refreshAgentModels(folder);
if (history.currentId || $selectedFolder?.id !== folder.id || appliedFolderDefaults !== folder.data) return;
selectedModels = normalizeSelectedModels(folder.data?.model_ids ?? []);
});
const storageChatInput = sessionStorage.getItem(
@@ -2084,7 +2114,6 @@
return () => {
try {
cancelBrowserInteractions();
agentDiscovery++;
clearTimeout(saveControlsTimer);
saveControls();
if (chatIdProp && !$temporaryChatEnabled) {
@@ -2722,13 +2751,16 @@
};
const initNewChat = async (preserveTabs = false, keepDraft = false) => {
const destinationFolder = $selectedFolder ? structuredClone($selectedFolder) as FolderDetails : null;
const retainedDraft = keepDraft && !$chatId && !history.currentId ? JSON.stringify(getChatInputDraft()) : null;
const searchParams = initialPage || preserveTabs ? new URLSearchParams() : $page.url.searchParams;
const previousHref = mainChatHref;
mainChatHref = '/';
if (!initialPage && !preserveTabs && $page.url.pathname === '/') {
mainChatHref += $page.url.search + $page.url.hash;
}
if ($selectedFolder?.id) mainChatHref = `/folders/${$selectedFolder.id}`;
if (keepDraft && !$chatId && !history.currentId) {
if (destinationFolder?.id) mainChatHref = `/folders/${destinationFolder.id}`;
if (keepDraft && !$chatId && !history.currentId && previousHref === mainChatHref) {
terminalTabs?.focusMainChat();
return;
}
@@ -2740,6 +2772,7 @@
)
showTabs.set(false);
const signal = startChatLoad();
appliedFolderDefaults = destinationFolder?.data;
modelDefaults = null;
clearTimeout(saveControlsTimer);
await saveControls();
@@ -2825,13 +2858,14 @@
(modelId) => modelId.startsWith('agent:') || $models.map((m) => m.id).includes(modelId)
);
} else {
if ($selectedFolder) {
if (destinationFolder) {
// A configured folder terminal overrides the previous selection.
applyFolderTerminal($selectedFolder);
if ($selectedFolder.data?.terminal_id) {
await refreshAgentModels();
applyFolderTerminal(destinationFolder);
if (destinationFolder.data?.terminal_id) {
await refreshAgentModels(destinationFolder, signal);
if (signal.aborted) return;
}
selectedModels = normalizeSelectedModels($selectedFolder.data?.model_ids ?? []);
selectedModels = normalizeSelectedModels(destinationFolder.data?.model_ids ?? []);
} else {
if (sessionStorage.selectedModels) {
// Set from session storage (temporary selection)
@@ -2888,7 +2922,7 @@
autoScroll = true;
// resetInput() must stay last: the selected model's defaults override the draft's selection.
const chatInputPrompt = (await restoreChatInput(sessionStorage.getItem('chat-input')))
const chatInputPrompt = (await restoreChatInput(retainedDraft ?? sessionStorage.getItem('chat-input')))
? prompt
: null;
const previousChatId = $chatId;
@@ -2916,7 +2950,7 @@
};
// Apply folder defaults after restoring the draft and model defaults.
applyFolderTerminal($selectedFolder);
applyFolderTerminal(destinationFolder);
chatFiles = [];
params = {};
@@ -2970,8 +3004,10 @@
}
}
if (signal.aborted) return;
loading = false;
await tick();
if (signal.aborted) return;
// Mounting the editor clears prompt, so apply the saved text afterward.
if (chatInputPrompt !== null) messageInput?.setText(chatInputPrompt);
if (modelSearch) await openModelSelectorWithSearch(modelSearch);
@@ -3098,10 +3134,12 @@
? { terminalId: $selectedTerminalId, currentDirectory: chatContent.working_directory }
: null;
if (selectedModels[0]?.startsWith('agent:')) {
if ($selectedTerminalId) await refreshAgentModels();
if ($selectedTerminalId) await refreshAgentModels(null, signal);
else selectedModels = selectedModels.filter((modelId) => !modelId.startsWith('agent:'));
}
if (signal.aborted) return;
// An empty model list is not evidence that the chat's models are gone.
if ($models.length > 0) {
selectedModels = selectedModels.filter(
@@ -5083,6 +5121,7 @@
if (!createdChat?.id) throw new Error($i18n.t('Failed to create chat'));
if (history !== _history || $chatId !== _chatId) return '';
chat = createdChat;
if (selectedFolderId) updateFolderChatLists(createdChat, selectedFolderId);
_chatId = chat.id;
await chatId.set(_chatId);
@@ -5101,7 +5140,7 @@
await refreshFolderChatLists(selectedFolderId, chat);
}
selectedFolder.set(null);
if ($chatId === _chatId && $selectedFolder?.id === selectedFolderId) selectedFolder.set(null);
} else {
_chatId = isTemporaryChatId(_chatId) ? _chatId : createTemporaryChatId($socket?.id);
await chatId.set(_chatId);
@@ -5224,6 +5263,7 @@
);
if (res) {
updateFolderChatLists(res, folderId);
await refreshChatList(localStorage.token, { refreshPinned: true });
await refreshFolderChatLists();
@@ -5237,6 +5277,7 @@
const archiveChatHandler = async (id: string) => {
try {
const res = await archiveChatById(localStorage.token, id);
updateFolderChatLists({ id }, undefined, true);
initNewChat();
await goto('/');
await refreshChatList(localStorage.token, { refreshPinned: true });
@@ -5273,6 +5314,7 @@
try {
const res = await deleteChatById(localStorage.token, id);
if (res) {
updateFolderChatLists({ id }, undefined, true);
initNewChat();
await goto('/');
await refreshChatList(localStorage.token, { refreshPinned: true });
@@ -1,7 +1,7 @@
<script lang="ts">
export let modelId: string | null = null;
import { getContext, tick } from 'svelte';
import { resolveTerminalTarget, type TerminalTarget } from '$lib/apis/terminal';
import { templatesApi, resolveTerminalTarget, type TerminalTarget } from '$lib/apis/terminal';
import UserTerminalsModal from '../UserTerminalsModal.svelte';
import { updateChatById } from '$lib/apis/chats';
import { toast } from 'svelte-sonner';
@@ -27,6 +27,8 @@
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
import Tooltip from '$lib/components/common/Tooltip.svelte';
import Cloud from '$lib/components/icons/Cloud.svelte';
import Plus from '$lib/components/icons/Plus.svelte';
import Cog6 from '$lib/components/icons/Cog6.svelte';
import Server from '$lib/components/icons/Server.svelte';
import ChevronRight from '$lib/components/icons/ChevronRight.svelte';
@@ -38,20 +40,18 @@
export let chatId: string | null = null;
export let terminalContext: TerminalContext | null = null;
let connections = Promise.resolve([]);
$: if (show) connections = templatesApi('/connections').catch(() => []);
$: systemTerminals = ($terminalServers ?? []).filter(
(t) =>
t.id &&
!(
($temporaryChatEnabled || isTemporaryChatId($activeChatId)) &&
t.scope === 'chat'
)
t.id && !(($temporaryChatEnabled || isTemporaryChatId($activeChatId)) && t.scope === 'chat')
);
// Tether presences are the user's own paired devices, listed apart from servers.
const isDevice = (terminal: any) => terminal.id.startsWith('tether:');
$: systemSections = [
{ devices: false, managed: true, terminals: systemTerminals.filter((t) => !isDevice(t)) },
{ devices: true, managed: false, terminals: systemTerminals.filter(isDevice) }
{ devices: false, terminals: systemTerminals.filter((t) => !isDevice(t)) },
{ devices: true, terminals: systemTerminals.filter(isDevice) }
].filter((section) => !section.devices || section.terminals.length > 0);
$: directTerminals = (
$config?.features?.enable_direct_integrations &&
@@ -132,13 +132,17 @@
show = false;
};
$: selectedSystemTerminal = systemTerminals.find((t) => (!!$selectedTerminalId && t.id === $selectedTerminalId));
$: selectedSystemTerminal = systemTerminals.find(
(t) => !!$selectedTerminalId && t.id === $selectedTerminalId
);
$: selectedDirectTerminal = directTerminals.find((t) => t.url === $selectedTerminalId);
$: folderTarget = resolveTerminalTarget(
$selectedTerminalId,
systemTerminals,
directTerminals,
'', { chatId: $activeChatId || null, modelId: modelId });
'',
{ chatId: $activeChatId || null, modelId: modelId }
);
$: selectedDevice = !!selectedSystemTerminal && isDevice(selectedSystemTerminal);
$: selectedLabel =
@@ -150,6 +154,7 @@
$: if (disabled && show) show = false;
let showTerminals = false;
let managedTerminalId: string | null = null;
async function saveSelection(id: string | null) {
if (isSavedChatId(chatId)) {
try {
@@ -170,7 +175,7 @@
let info: { target: TerminalTarget; label: string } | null = null;
const openInfo = async (selector: string, label: string) => {
if (
systemTerminals.find((t) => (!!selector && t.id === selector))?.scope === 'chat' &&
systemTerminals.find((t) => !!selector && t.id === selector)?.scope === 'chat' &&
!isSavedChatId($activeChatId)
)
return;
@@ -178,7 +183,9 @@
selector,
systemTerminals,
directTerminals,
localStorage.token ?? '', { chatId: $activeChatId || null, modelId: modelId });
localStorage.token ?? '',
{ chatId: $activeChatId || null, modelId: modelId }
);
if (!target) return;
show = false;
await tick();
@@ -356,56 +363,20 @@
<span
class="text-[0.625rem] font-normal text-gray-400 dark:text-gray-500 uppercase tracking-wider"
>
{section.devices
? $i18n.t('Your devices')
: section.managed
? $i18n.t('Terminals')
: $i18n.t('System')}
{section.devices ? $i18n.t('Your devices') : $i18n.t('Terminals')}
</span>
{#if section.managed}
<Tooltip content={$i18n.t('Manage terminals')} placement="top">
{#if !section.devices && $user?.role === 'admin'}
<Tooltip content={$i18n.t('Settings')} placement="top">
<button
type="button"
aria-label={$i18n.t('Manage terminals')}
class="p-0.5 rounded-md text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition"
on:click|stopPropagation={() => {
show = false;
showTerminals = true;
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="size-3.5"
>
<path
d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z"
/>
</svg>
</button>
</Tooltip>
{:else if !section.devices && $user?.role === 'admin'}
<Tooltip content={$i18n.t('Add Terminal')} placement="top">
<button
type="button"
aria-label={$i18n.t('Add Terminal')}
aria-label={$i18n.t('Settings')}
class="p-0.5 rounded-md text-gray-400 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300 transition"
on:click|stopPropagation={() => {
show = false;
showSettings.set('admin:integrations');
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="size-3.5"
>
<path
d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z"
/>
</svg>
<Cog6 className="size-3.5" />
</button>
</Tooltip>
{/if}
@@ -421,8 +392,12 @@
aria-checked={$selectedTerminalId === terminal.id}
class="flex w-full min-w-0 gap-2 items-center h-[1.6875rem] pl-2 {$selectedTerminalId ===
terminal.id
? 'pr-14'
: 'pr-8'} text-[0.8125rem] font-normal cursor-pointer rounded-xl {$selectedTerminalId ===
? terminal.template_id
? 'pr-20'
: 'pr-14'
: terminal.template_id
? 'pr-14'
: 'pr-8'} text-[0.8125rem] font-normal cursor-pointer rounded-xl {$selectedTerminalId ===
terminal.id
? 'bg-gray-50/40 dark:bg-gray-800/40'
: 'hover:bg-gray-50/40 dark:hover:bg-gray-800/40'}"
@@ -453,37 +428,61 @@
</div>
{/if}
</button>
{#if terminal.scope !== 'chat' || isSavedChatId($activeChatId)}
{#if terminal.template_id || terminal.scope !== 'chat' || isSavedChatId($activeChatId)}
<div
class="absolute inset-y-0 {$selectedTerminalId === terminal.id
? 'right-6'
: 'right-1'} flex items-center opacity-0 pointer-events-none transition-opacity group-hover/terminal:opacity-100 group-hover/terminal:pointer-events-auto group-focus-within/terminal:opacity-100 group-focus-within/terminal:pointer-events-auto"
>
<Tooltip content={$i18n.t('System info')} placement="top">
<button
type="button"
aria-label={$i18n.t('System info for {{name}}', {
name: terminal.name || terminal.id
})}
class="flex size-6 shrink-0 items-center justify-center rounded-lg text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 focus-visible:outline focus-visible:outline-2"
on:click|stopPropagation={() =>
openInfo(terminal.id, terminal.name || terminal.id)}
><Activity className="size-3.5" /></button
>
</Tooltip>
{#if terminal.template_id}
<Tooltip content={$i18n.t('Manage')} placement="top">
<button
type="button"
aria-label={$i18n.t('Manage {{name}}', {
name: terminal.name || terminal.id
})}
class="flex size-6 shrink-0 items-center justify-center rounded-lg text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 focus-visible:outline focus-visible:outline-2"
on:click|stopPropagation={() => {
managedTerminalId = terminal.id;
show = false;
showTerminals = true;
}}><Cog6 className="size-3.5" /></button
>
</Tooltip>
{/if}
{#if terminal.scope !== 'chat' || isSavedChatId($activeChatId)}
<Tooltip content={$i18n.t('System info')} placement="top">
<button
type="button"
aria-label={$i18n.t('System info for {{name}}', {
name: terminal.name || terminal.id
})}
class="flex size-6 shrink-0 items-center justify-center rounded-lg text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 focus-visible:outline focus-visible:outline-2"
on:click|stopPropagation={() =>
openInfo(terminal.id, terminal.name || terminal.id)}
><Activity className="size-3.5" /></button
>
</Tooltip>
{/if}
</div>
{/if}
</div>
{:else}
<button
type="button"
class="flex w-full items-center h-[1.6875rem] px-2 text-[0.8125rem] text-gray-500 rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40"
on:click={() => {
show = false;
showTerminals = true;
}}>{$i18n.t('New terminal')}</button
>
{/each}
{#if !section.devices}
{#await connections then allowed}
{#if allowed.length}
<button
type="button"
class="flex h-[1.6875rem] w-full items-center gap-2 rounded-xl px-2 text-[0.8125rem] text-gray-500 hover:bg-gray-50/40 dark:hover:bg-gray-800/40"
on:click={() => {
managedTerminalId = null;
show = false;
showTerminals = true;
}}><Plus className="size-3.5" />{$i18n.t('New Terminal')}</button
>
{/if}
{/await}
{/if}
{/each}
</DropdownMenu>
</div>
@@ -520,10 +519,11 @@
{/if}
{#if showTerminals}
<UserTerminalsModal {modelId}
<UserTerminalsModal
{modelId}
bind:show={showTerminals}
{chatId}
selected={$selectedTerminalId}
selected={managedTerminalId}
onSelect={selectTerminal}
/>
{/if}
+2
View File
@@ -1,4 +1,5 @@
<script lang="ts">
import { updateFolderChatLists } from '$lib/stores/folderStates';
import { getContext, tick, type Snippet } from 'svelte';
import { toast } from 'svelte-sonner';
@@ -119,6 +120,7 @@
}
);
if (!res) return;
updateFolderChatLists({ id: chat.id, title: newTitle });
if (chat.id === $chatId) {
_chatTitle.set(newTitle);
+2 -2
View File
@@ -145,10 +145,10 @@
onUpdate={async () => {
await Promise.all([refreshChatList(localStorage.token), refreshFolderChatLists(null)]);
}}
onDelete={async () => {
onDelete={async (deletedFolder: { id: string }) => {
await Promise.all([refreshChatList(localStorage.token), refreshFolderChatLists(null)]);
selectedFolder.set(null);
if ($selectedFolder?.id === deletedFolder.id) selectedFolder.set(null);
}}
/>
{:else}
@@ -6,7 +6,14 @@
import ChatList from './ChatList.svelte';
import FolderKnowledge from './FolderKnowledge.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import { getSharedFolderChats } from '$lib/apis/folders';
import {
folderStates,
folderChatPageKey,
loadFolderChatPage,
updateFolderChatLists,
isCancelledFolderRequest,
} from '$lib/stores/folderStates';
import { registerFolderRefreshHandler } from '$lib/stores/chatList';
type FolderPlaceholderFolder = {
id?: string;
@@ -63,18 +70,8 @@
};
const updateChatActive = (chatId: string, active: boolean) => {
if (!chats) {
return false;
}
let found = false;
chats = chats.map((chat) => {
if (chat.id !== chatId) {
return chat;
}
found = true;
return { ...chat, active };
});
const found = chats?.some((chat) => chat.id === chatId) ?? false;
updateFolderChatLists({ id: chatId, active });
return found;
};
@@ -95,37 +92,24 @@
});
};
const setChatList = async (clear = false) => {
let requestGeneration = 0;
let loadError = '';
$: retainedPage = folder?.id ? $folderStates[folder.id]?.chatPages[folderChatPageKey({ page, sortBy: orderBy, sortDir: direction })] : null;
$: chats = retainedPage?.chats ?? null;
$: totalChats = retainedPage?.total ?? 0;
const setChatList = async () => {
const folderId = folder?.id;
if (clear) {
chats = null;
}
if (folderId) {
// Always use the shared folder endpoint so owners also see
// chats created by users who have write access to this folder.
chatListLoading = true;
const res = await getSharedFolderChats(localStorage.token, folderId, {
page,
sortBy: orderBy,
sortDir: direction
}).catch((error) => {
console.error(error);
return null;
});
if (res && res.chats) {
chats = res.chats;
totalChats = res.total ?? res.chats.length;
} else {
chats = [];
totalChats = 0;
}
chatListLoading = false;
} else {
chats = [];
totalChats = 0;
chatListLoading = false;
const generation = ++requestGeneration;
if (!folderId) return;
chatListLoading = true;
loadError = '';
try {
await loadFolderChatPage(localStorage.token, folderId, { page, sortBy: orderBy, sortDir: direction }, true);
} catch (error) {
if (generation === requestGeneration && !isCancelledFolderRequest(error)) loadError = String(error);
} finally {
if (generation === requestGeneration) chatListLoading = false;
}
};
@@ -144,11 +128,16 @@
};
onMount(() => {
const unregister = registerFolderRefreshHandler((id) => {
if (id === undefined || id === folder?.id) return setChatList();
});
const socketInstance = $socket;
socketInstance?.on('events', chatEventHandler);
socketInstance?.on('connect', refreshChatListSoon);
return () => {
unregister();
requestGeneration++;
socketInstance?.off('events', chatEventHandler);
socketInstance?.off('connect', refreshChatListSoon);
};
@@ -157,13 +146,12 @@
$: if (folder?.id && folder.id !== currentFolderId) {
currentFolderId = folder.id;
page = 1;
setChatList(true);
setChatList();
}
$: if (!folder?.id && currentFolderId !== null) {
currentFolderId = null;
chats = [];
totalChats = 0;
requestGeneration++;
}
</script>
@@ -213,6 +201,8 @@
onPageChange={setPage}
onSort={setSortKey}
/>
{:else if loadError}
<div class="py-10" role="alert">{loadError}</div>
{:else}
<div class="py-10">
<Spinner />
@@ -10,10 +10,15 @@
import { toast } from 'svelte-sonner';
import { selectedFolder } from '$lib/stores';
import {
loadFolderDetails,
updateFolderDetails,
removeFolderState,
type FolderDetails,
} from '$lib/stores/folderStates';
import {
deleteFolderById,
getFolderById,
updateFolderById,
createNewFolder
} from '$lib/apis/folders';
@@ -29,7 +34,7 @@
import Emoji from '$lib/components/common/Emoji.svelte';
import EmojiPicker from '$lib/components/common/EmojiPicker.svelte';
export let folder = null;
export let folder: FolderDetails | null = null;
export let readOnly: boolean = false;
export let onUpdate: Function = (folderId) => {};
@@ -41,48 +46,53 @@
let deleteFolderContents = true;
const updateHandler = async ({ name, meta, data }) => {
const targetFolder = folder;
if (!targetFolder) return;
name = name?.trim();
if (!name) {
toast.error($i18n.t('Folder name cannot be empty.'));
return;
}
const currentName = folder.name;
const currentName = targetFolder.name;
folder.name = name;
targetFolder.name = name;
const res = await updateFolderById(localStorage.token, folder.id, {
const res = await updateFolderById(localStorage.token, targetFolder.id, {
name,
...(meta ? { meta } : {}),
...(data ? { data } : {})
}).catch((error) => {
toast.error(`${error}`);
folder.name = currentName;
targetFolder.name = currentName;
return null;
});
if (res) {
folder.name = name;
updateFolderDetails(targetFolder.id, res);
targetFolder.name = name;
if (data) {
folder.data = data;
targetFolder.data = data;
}
toast.success($i18n.t('Folder updated successfully'));
const _folder = await getFolderById(localStorage.token, folder.id).catch((error) => {
const _folder = await loadFolderDetails(localStorage.token, targetFolder.id, true).catch((error) => {
toast.error(`${error}`);
return null;
});
const updatedFolder = { ...folder, ..._folder };
await selectedFolder.set(updatedFolder);
const updatedFolder = { ...targetFolder, ..._folder };
if ($selectedFolder?.id === targetFolder.id) selectedFolder.set(updatedFolder);
onUpdate(updatedFolder);
}
};
const updateIconHandler = async (iconName) => {
const res = await updateFolderById(localStorage.token, folder.id, {
const targetFolder = folder;
if (!targetFolder) return;
const res = await updateFolderById(localStorage.token, targetFolder.id, {
meta: {
icon: iconName ?? ''
}
@@ -92,23 +102,26 @@
});
if (res) {
folder.meta = { ...folder.meta, icon: iconName ?? '' };
updateFolderDetails(targetFolder.id, res);
targetFolder.meta = { ...targetFolder.meta, icon: iconName ?? '' };
toast.success($i18n.t('Folder updated successfully'));
const _folder = await getFolderById(localStorage.token, folder.id).catch((error) => {
const _folder = await loadFolderDetails(localStorage.token, targetFolder.id, true).catch((error) => {
toast.error(`${error}`);
return null;
});
const updatedFolder = { ...folder, ..._folder };
await selectedFolder.set(updatedFolder);
const updatedFolder = { ...targetFolder, ..._folder };
if ($selectedFolder?.id === targetFolder.id) selectedFolder.set(updatedFolder);
onUpdate(updatedFolder);
}
};
const deleteHandler = async () => {
const res = await deleteFolderById(localStorage.token, folder.id, deleteFolderContents).catch(
const targetFolder = folder;
if (!targetFolder) return;
const res = await deleteFolderById(localStorage.token, targetFolder.id, deleteFolderContents).catch(
(error) => {
toast.error(`${error}`);
return null;
@@ -116,8 +129,9 @@
);
if (res) {
removeFolderState(targetFolder.id);
toast.success($i18n.t('Folder deleted successfully'));
onDelete(folder);
onDelete(targetFolder);
}
};
@@ -10,6 +10,7 @@
import type { Writable } from 'svelte/store';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import { updateFolderChatLists } from '$lib/stores/folderStates';
import {
archiveChatById,
@@ -134,9 +135,11 @@
const unarchiveHandler = async (id: string) => {
const index = chatList?.findIndex((chat) => chat.id === id) ?? -1;
await archiveChatById(localStorage.token, id).catch((error) => {
const restored = await archiveChatById(localStorage.token, id).catch((error) => {
toast.error(`${error}`);
});
if (!restored) return;
updateFolderChatLists(restored, restored.folder_id);
chatList = chatList?.filter((chat) => chat.id !== id) ?? null;
if (chatCount !== null) chatCount -= 1;
@@ -152,9 +155,11 @@
if (!selectedChatId) return;
const id = selectedChatId;
await deleteChatById(localStorage.token, id).catch((error) => {
const deleted = await deleteChatById(localStorage.token, id).catch((error) => {
toast.error(`${error}`);
});
if (!deleted) return;
updateFolderChatLists({ id }, undefined, true);
chatList = chatList?.filter((chat) => chat.id !== id) ?? null;
if (chatCount !== null) chatCount -= 1;
+183 -161
View File
@@ -4,20 +4,19 @@
import Modal from '$lib/components/common/Modal.svelte';
import ConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
import Collapsible from '$lib/components/common/Collapsible.svelte';
import SettingsSelect from '$lib/components/common/SettingsSelect.svelte';
import Dropdown from '$lib/components/common/Dropdown.svelte';
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import Cloud from '$lib/components/icons/Cloud.svelte';
import Check from '$lib/components/icons/Check.svelte';
import ChevronLeft from '$lib/components/icons/ChevronLeft.svelte';
import EllipsisHorizontal from '$lib/components/icons/EllipsisHorizontal.svelte';
import Plus from '$lib/components/icons/Plus.svelte';
import XMark from '$lib/components/icons/XMark.svelte';
import Pencil from '$lib/components/icons/Pencil.svelte';
import Users from '$lib/components/icons/Users.svelte';
import ArrowPath from '$lib/components/icons/ArrowPath.svelte';
import Trash from '$lib/components/icons/Trash.svelte';
import ArrowUturnLeft from '$lib/components/icons/ArrowUturnLeft.svelte';
import GarbageBin from '$lib/components/icons/GarbageBin.svelte';
import AccessControl from '$lib/components/workspace/common/AccessControl.svelte';
import { templatesApi, getTerminalServers } from '$lib/apis/terminal';
import { terminalServers } from '$lib/stores';
@@ -31,7 +30,7 @@
let rows: any[] = [];
let connections: any[] = [];
let current: any = null;
let editing: any = null;
let editing: any = selected ? null : { id: null };
let sharing: any = null;
let accessGrants: any[] = [];
let connectionId = '';
@@ -49,7 +48,9 @@
const button =
'flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg px-2.5 text-xs font-normal text-gray-600 transition hover:bg-gray-100 hover:text-gray-900 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-850 dark:hover:text-white';
const input =
'w-full min-w-0 bg-transparent py-1 text-sm outline-hidden placeholder:text-gray-400 dark:placeholder:text-gray-600';
'w-full min-w-0 bg-transparent py-0.5 text-sm text-gray-900 outline-hidden placeholder:text-gray-300 dark:text-gray-100 dark:placeholder:text-gray-700';
const select =
'min-w-0 bg-transparent pr-5 text-sm text-gray-900 outline-hidden dark:text-gray-100';
const path = (id: string) => `/${encodeURIComponent(id)}`;
const context = () => ({ chat_id: chatId, model_id: modelId });
@@ -198,159 +199,182 @@
)}
>
<div class="text-gray-900 dark:text-gray-100">
<div class="flex items-center justify-between gap-2 px-4 pt-3 pb-2">
<div class="flex min-w-0 items-center gap-1.5">
{#if editing || sharing}
<button
type="button"
class="-ml-1 flex size-6 shrink-0 items-center justify-center rounded-lg text-gray-400 transition hover:bg-gray-50 hover:text-gray-700 dark:hover:bg-gray-850 dark:hover:text-gray-200"
aria-label={$i18n.t('Back')}
disabled={busy}
on:click={() => {
editing = null;
sharing = null;
error = '';
}}><ChevronLeft className="size-3.5" strokeWidth="2" /></button
>
{/if}
<h2 class="truncate text-sm font-medium">
{editing
? $i18n.t(editing.id ? 'Configure terminal' : 'New terminal')
: sharing
? `${$i18n.t('Share')} ${sharing.name}`
: $i18n.t('Terminals')}
</h2>
</div>
<div class="flex items-center justify-between gap-2 px-4 pb-1 pt-3 dark:text-gray-300">
<h2 class="min-w-0 self-center truncate text-sm font-medium">
{editing
? $i18n.t(editing.id ? 'Configure terminal' : 'New terminal')
: sharing
? `${$i18n.t('Share')} ${sharing.name}`
: $i18n.t('Terminals')}
</h2>
<button
type="button"
class="shrink-0 rounded-lg py-1 text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
class="self-center shrink-0 rounded-lg px-0 py-1 text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
on:click={() => (show = false)}
aria-label={$i18n.t('Close')}><XMark className="size-4" /></button
>
</div>
<div class="max-h-[min(36rem,75dvh)] overflow-y-auto px-4 pb-4" aria-busy={busy}>
{#if error}<p role="alert" class="mb-3 text-xs text-gray-700 dark:text-gray-300">{error}</p>{/if}
<div
class="max-h-[min(36rem,75dvh)] overflow-y-auto pb-4 {editing || sharing ? 'px-5' : 'px-3'}"
aria-busy={busy}
>
{#if error}<p role="alert" class="mb-3 text-xs text-gray-700 dark:text-gray-300">
{error}
</p>{/if}
{#if editing}
<form class="space-y-4 pt-1" on:submit|preventDefault={save}>
<form class="space-y-2" on:submit|preventDefault={save}>
<div>
<label for="terminal-name" class="block text-xs text-gray-500 dark:text-gray-400"
<label for="terminal-name" class="mb-0.5 block text-xs text-gray-500"
>{$i18n.t('Name')}</label
>
<input
id="terminal-name"
list="terminal-name-suggestions"
class={input}
bind:value={name}
placeholder={$i18n.t('Terminal name')}
placeholder={$i18n.t('My Terminal')}
required
/>
<datalist id="terminal-name-suggestions">
{#each [$i18n.t('My Terminal'), $i18n.t('Development'), $i18n.t('Sandbox')] as value}
<option {value}></option>
{/each}
</datalist>
</div>
<div class="space-y-3 border-t border-gray-100/50 pt-3 dark:border-white/[0.04]">
{#if !editing.id}
<div class="flex items-center justify-between gap-3">
<label for="terminal-connection" class="text-xs">{$i18n.t('Connection')}</label>
<SettingsSelect
id="terminal-connection"
bind:value={connectionId}
className="max-w-[65%]"
required
disabled={busy}
>{#each connections as c}<option value={c.id}>{c.name}</option
>{/each}</SettingsSelect
>
</div>
{/if}
{#if !editing.id}
<div>
<div class="flex items-center justify-between gap-3">
<label for="terminal-scope" class="text-xs">{$i18n.t('Scope')}</label>
<SettingsSelect id="terminal-scope" bind:value={scope} disabled={busy}
><option value="none">{$i18n.t('None')}</option><option value="user"
>{$i18n.t('User')}</option
><option value="chat">{$i18n.t('Chat')}</option><option value="model"
>{$i18n.t('Model')}</option
></SettingsSelect
>
</div>
<p class="mt-1.5 text-xs leading-relaxed text-gray-500 dark:text-gray-400">
{$i18n.t(
scope === 'none'
? 'Everyone with access shares this terminal.'
: scope === 'user'
? 'Each user gets their own terminal.'
: scope === 'chat'
? 'Each chat gets a terminal shared by its participants.'
: 'Each model gets a terminal shared across authorized users and chats.'
)}
<label for="terminal-connection" class="mb-0.5 block text-xs text-gray-500"
>{$i18n.t('Connection')}</label
>
<select
id="terminal-connection"
class="{select} w-full"
bind:value={connectionId}
required
disabled={busy}
>
{#each connections as c}<option value={c.id}>{c.name}</option>{/each}
</select>
<p class="mt-1 text-xs text-gray-500">
{$i18n.t('Choose the connection that will run this terminal.')}
</p>
</div>
{/if}
<div>
<label for="terminal-scope" class="mb-0.5 block text-xs text-gray-500"
>{$i18n.t('Scope')}</label
>
<select id="terminal-scope" class="{select} w-full" bind:value={scope} disabled={busy}>
<option value="none">{$i18n.t('None')}</option>
<option value="user">{$i18n.t('User')}</option>
<option value="chat">{$i18n.t('Chat')}</option>
<option value="model">{$i18n.t('Model')}</option>
</select>
<p class="mt-1 text-xs text-gray-500">
{$i18n.t(
scope === 'none'
? 'Everyone with access shares this terminal.'
: scope === 'user'
? 'Each user gets their own terminal.'
: scope === 'chat'
? 'Each chat gets a terminal shared by its participants.'
: 'Each model gets a terminal shared across authorized users and chats.'
)}
</p>
</div>
<div class="space-y-3 border-t border-gray-100/50 pt-3 dark:border-white/[0.04]">
<div>
<label for="terminal-image" class="block text-xs text-gray-500 dark:text-gray-400"
>{$i18n.t('Image')}</label
><input
id="terminal-image"
<div>
<label for="terminal-image" class="mb-0.5 block text-xs text-gray-500"
>{$i18n.t('Image')}</label
>
<input
id="terminal-image"
list="terminal-image-suggestions"
class={input}
bind:value={image}
placeholder={$i18n.t('Server default')}
/>
<datalist id="terminal-image-suggestions">
{#each ['latest', 'agents', 'cuda', 'slim', 'alpine', 'openshift'] as tag}
<option value={`ghcr.io/open-webui/open-terminal:${tag}`}></option>
{/each}
</datalist>
<p class="mt-1 text-xs text-gray-500">
{$i18n.t('Container image used to run the terminal.')}
</p>
</div>
<div class="grid grid-cols-2 gap-2">
<div class="min-w-0">
<label for="terminal-cpu" class="mb-0.5 block text-xs text-gray-500">CPU</label>
<input
id="terminal-cpu"
list="terminal-cpu-suggestions"
class={input}
bind:value={image}
bind:value={cpu}
placeholder={$i18n.t('Server default')}
/>
<datalist id="terminal-cpu-suggestions">
{#each ['0.5', '1', '2', '4', '8'] as value}
<option {value}></option>
{/each}
</datalist>
<p class="mt-1 text-xs text-gray-500">
{$i18n.t('CPU limit, for example 1 or 0.5.')}
</p>
</div>
<div class="grid grid-cols-2 gap-4">
<div>
<label for="terminal-cpu" class="block text-xs text-gray-500 dark:text-gray-400"
>CPU</label
><input
id="terminal-cpu"
class={input}
bind:value={cpu}
placeholder={$i18n.t('Server default')}
/>
</div>
<div>
<label for="terminal-memory" class="block text-xs text-gray-500 dark:text-gray-400"
>{$i18n.t('Memory')}</label
><input
id="terminal-memory"
class={input}
bind:value={memory}
placeholder={$i18n.t('Server default')}
/>
</div>
<div class="min-w-0">
<label for="terminal-memory" class="mb-0.5 block text-xs text-gray-500"
>{$i18n.t('Memory')}</label
>
<input
id="terminal-memory"
list="terminal-memory-suggestions"
class={input}
bind:value={memory}
placeholder={$i18n.t('Server default')}
/>
<datalist id="terminal-memory-suggestions">
{#each ['512Mi', '1Gi', '2Gi', '4Gi', '8Gi', '16Gi'] as value}
<option {value}></option>
{/each}
</datalist>
<p class="mt-1 text-xs text-gray-500">{$i18n.t('Memory limit, for example 2Gi.')}</p>
</div>
</div>
<div class="border-t border-gray-100/50 pt-2 dark:border-white/[0.04]">
<Collapsible
title={$i18n.t('Advanced configuration')}
bind:open={showAdvanced}
buttonClassName="flex w-full py-1 text-xs text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
chevronClassName="size-3.5"
chevronStrokeWidth="2"
>
<div slot="content" class="pt-2">
<p class="mb-2 text-xs leading-relaxed text-gray-500 dark:text-gray-400">
{$i18n.t('Environment variables, storage, networking, and security settings.')}
</p>
<textarea
class="w-full resize-y rounded-lg bg-gray-50/60 p-2.5 font-mono text-xs leading-relaxed outline-hidden focus:ring-1 focus:ring-gray-200 dark:bg-gray-850/50 dark:focus:ring-gray-700"
rows="7"
bind:value={advanced}
aria-label={$i18n.t('Template configuration')}
spellcheck="false"
/>
</div>
</Collapsible>
</div>
<div class="flex justify-end gap-1.5 pt-1">
<button type="button" class={button} disabled={busy} on:click={() => (editing = null)}
>{$i18n.t('Cancel')}</button
<Collapsible
title={$i18n.t('Advanced')}
bind:open={showAdvanced}
buttonClassName="flex w-full py-1 text-xs text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
chevronClassName="size-3.5"
chevronStrokeWidth="2"
>
<div slot="content" class="mt-2">
<p class="mb-2 text-xs text-gray-500">
{$i18n.t('Environment variables, storage, networking, and security settings.')}
</p>
<textarea
class="w-full resize-y rounded-lg bg-gray-50/60 p-2.5 font-mono text-xs leading-relaxed outline-hidden focus:ring-1 focus:ring-gray-200 dark:bg-gray-850/50 dark:focus:ring-gray-700"
rows="7"
bind:value={advanced}
aria-label={$i18n.t('Template configuration')}
spellcheck="false"
/>
</div>
</Collapsible>
<div class="flex items-center justify-between pt-3">
<button
type="button"
class="px-1 py-1.5 text-sm font-medium text-gray-500 transition hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200"
disabled={busy}
on:click={() => (editing = null)}>{$i18n.t('Cancel')}</button
>
<button
type="submit"
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-gray-900 px-2.5 text-xs font-normal text-white transition hover:bg-black disabled:opacity-50 dark:bg-gray-100 dark:text-gray-900 dark:hover:bg-white"
disabled={busy || (!editing.id && !connectionId)}
>{#if busy}<Spinner className="size-3" />{/if}{$i18n.t(
editing.id ? 'Save' : 'Create'
)}</button
>
{$i18n.t(editing.id ? 'Save' : 'Create')}
{#if busy}<Spinner className="size-3" />{/if}
</button>
</div>
</form>
{:else if sharing}
@@ -380,16 +404,16 @@
>
</div>
{:else}
<div class="-mx-2 space-y-0.5">
<div class="space-y-0.5">
{#each rows as row (row.id)}
{@const connection = connections.find((c) => c.id === row.id.slice('template:'.length, row.id.lastIndexOf(':')))}
{@const connection = connections.find(
(c) => c.id === row.id.slice('template:'.length, row.id.lastIndexOf(':'))
)}
<div
class="flex items-center gap-1 rounded-xl pr-1 transition {row.id === selected
? 'bg-gray-50/60 dark:bg-gray-850/50'
: 'hover:bg-gray-50/40 dark:hover:bg-gray-850/30'}"
class="flex items-center gap-1 rounded-lg pr-1 hover:bg-gray-50/60 dark:hover:bg-gray-850/60"
>
<button
class="flex min-w-0 flex-1 items-center gap-2.5 rounded-xl px-2 py-2 text-left disabled:opacity-50"
class="flex min-w-0 flex-1 items-center gap-2 rounded-lg px-2 py-1.5 text-left disabled:opacity-50"
aria-pressed={row.id === selected}
disabled={busy}
on:click={() =>
@@ -400,13 +424,14 @@
})}
>
<Cloud
className="size-4 shrink-0 text-gray-400 dark:text-gray-500"
className="size-3.5 shrink-0 text-gray-500 dark:text-gray-400"
strokeWidth="1.5"
/>
<span class="min-w-0 flex-1"
><span class="block truncate text-[0.8125rem]">{row.name}</span><span
class="mt-0.5 flex items-center gap-1.5 text-[0.6875rem] text-gray-500 dark:text-gray-400"
>{$i18n.t(
><span class="block truncate text-sm font-normal text-gray-800 dark:text-gray-100"
>{row.name}</span
><span class="flex flex-wrap items-center gap-1.5 text-xs text-gray-500"
>{$i18n.t('Scope')}: {$i18n.t(
row.scope ? row.scope[0].toUpperCase() + row.scope.slice(1) : 'None'
)}{#if row.id === selected && current}<span aria-hidden="true">·</span><span
class="flex items-center gap-1"
@@ -421,43 +446,40 @@
></span
>
{#if row.id === selected}<Check
className="size-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"
className="size-3.5 shrink-0 text-gray-500 dark:text-gray-400"
/>{/if}
</button>
{#if connection}
<Dropdown align="end" closeOnSelect>
<button
class="flex size-7 items-center justify-center rounded-lg text-gray-400 transition hover:bg-gray-100/60 hover:text-gray-700 disabled:opacity-50 dark:hover:bg-gray-800/60 dark:hover:text-gray-200"
class="flex size-6 shrink-0 items-center justify-center rounded-lg text-gray-400 transition hover:text-gray-700 disabled:opacity-50 dark:text-gray-500 dark:hover:text-gray-200"
aria-label={$i18n.t('Actions for {{name}}', { name: row.name })}
disabled={busy}><EllipsisHorizontal className="size-4" /></button
>
<div slot="content">
<DropdownMenu className="w-48">
<DropdownMenu className="min-w-[10.625rem]">
<button disabled={busy} on:click={() => edit(row)}
><Pencil />{$i18n.t('Configure')}</button
><button disabled={busy} on:click={() => share(row)}
><Users />{$i18n.t('Share')}</button
>
>
<button disabled={busy} on:click={() => share(row)}
><Users />{$i18n.t('Share')}</button
>
{#if row.id === selected && current && !['not_created', 'unavailable'].includes(current.status)}
<hr class="border-gray-100/50 dark:border-white/[0.04]" />
<hr class="border-gray-50 dark:border-gray-850/30" />
<button disabled={busy} on:click={() => action('restart')}
><ArrowPath />{$i18n.t('Restart')}</button
><button disabled={busy} on:click={() => action('reset')}
><ArrowPath />{$i18n.t('Reset')}</button
><button
class="text-gray-700 dark:text-gray-300"
disabled={busy}
on:click={() => action('delete')}
><Trash />{$i18n.t('Delete instance')}</button
>
<button disabled={busy} on:click={() => action('reset')}
><ArrowUturnLeft />{$i18n.t('Reset')}</button
>
<button disabled={busy} on:click={() => action('delete')}
><XMark />{$i18n.t('Delete instance')}</button
>
{/if}
<hr class="border-gray-100/50 dark:border-white/[0.04]" />
<button
class="text-gray-700 dark:text-gray-300"
disabled={busy}
on:click={() => removeTemplate(row)}
><Trash />{$i18n.t('Delete terminal')}</button
>
<hr class="border-gray-50 dark:border-gray-850/30" />
<button disabled={busy} on:click={() => removeTemplate(row)}
><GarbageBin />{$i18n.t('Delete terminal')}</button
>
</DropdownMenu>
</div>
</Dropdown>
@@ -472,11 +494,11 @@
{#if current?.detail}<p class="mt-2 text-xs text-gray-500" role="status">
{current.detail}
</p>{/if}
{#if connections.length}<div
class="mt-2 border-t border-gray-100/50 pt-2 dark:border-white/[0.04]"
>
<button class={`${button} -ml-2`} disabled={busy} on:click={() => edit()}
><Plus className="size-3.5" />{$i18n.t('New terminal')}</button
{#if connections.length}<div class="mt-2 flex justify-end px-1">
<button
class="flex h-7 shrink-0 items-center justify-center gap-1.5 rounded-lg bg-gray-100 px-2.5 text-xs font-normal text-gray-800 transition hover:bg-gray-100/70 disabled:opacity-60 dark:bg-gray-850 dark:text-white dark:hover:bg-gray-850/60"
disabled={busy}
on:click={() => edit()}><Plus className="size-3.5" />{$i18n.t('New terminal')}</button
>
</div>{/if}
{/if}
@@ -10,6 +10,7 @@
dayjs.extend(calendar);
import { deleteChatById } from '$lib/apis/chats';
import { updateFolderChatLists } from '$lib/stores/folderStates';
import { WEBUI_API_BASE_URL } from '$lib/constants';
import { copyToClipboard, formatNumber } from '$lib/utils';
@@ -78,6 +79,7 @@
});
if (res) {
updateFolderChatLists({ id: chatId }, undefined, true);
chatList = chatList?.filter((c) => c.id !== chatId) ?? null;
onDelete(chatId);
}
+39 -8
View File
@@ -1,5 +1,6 @@
<script lang="ts">
import { toast } from 'svelte-sonner';
import equal from 'fast-deep-equal';
import { v4 as uuidv4 } from 'uuid';
import Sortable from 'sortablejs';
@@ -40,6 +41,13 @@
setChatActive,
setChatReadAt
} from '$lib/stores/chatList';
import {
folderStates,
markFolderChatsDirty,
updateFolderChatLists,
updateFolderDetails,
removeFolderState,
} from '$lib/stores/folderStates';
import { onMount, getContext, setContext, tick, onDestroy } from 'svelte';
import { writable } from 'svelte/store';
@@ -191,6 +199,7 @@
id
);
if (!result) throw new Error('Chat action failed');
updateFolderChatLists({ id }, undefined, true);
succeeded.add(id);
} catch (error) {
console.error(`Failed to ${action} chat:`, error);
@@ -256,13 +265,12 @@
let showSharedFolders = false;
let showChatsMenu = false;
let folders = {};
let folders: Record<string, any> = {};
type SelectedSidebarFolder = { id: string } | null;
let folderRegistry: Record<
string,
{
setFolderItems?: () => unknown;
upsertChat?: (chat: Record<string, unknown>) => unknown;
setFolderItems?: (append?: boolean, refresh?: boolean) => unknown;
setChatActive?: (chatId: string, active: boolean, pendingApproval: boolean) => boolean;
setChatReadAt?: (chatId: string, lastReadAt: number) => boolean;
setAllChatsRead?: () => unknown;
@@ -273,12 +281,28 @@
let sharedFolders: any[] = [];
let retainedFolderId: string | null = null;
$: if ($selectedFolder?.id) {
const id = $selectedFolder.id;
const details = $folderStates[id]?.details;
if (details) {
retainedFolderId = id;
const display = { name: details.name, meta: details.meta, write_access: details.write_access, access_grants: details.access_grants };
const current = { name: $selectedFolder.name, meta: $selectedFolder.meta, write_access: $selectedFolder.write_access, access_grants: $selectedFolder.access_grants };
if (!equal(display, current)) selectedFolder.set({ ...$selectedFolder, ...display });
} else if (!$folderStates[id] && retainedFolderId === id) {
selectedFolder.set(null);
if ($page.url.pathname.startsWith('/folders/')) void goto('/');
}
} else retainedFolderId = null;
const initSelectedFolderChats = (folder: SelectedSidebarFolder) => {
if (!folder?.id) {
return;
}
folderRegistry[folder.id]?.setFolderItems?.();
folderRegistry[folder.id]?.setFolderItems?.(false, false);
};
$: pinnedItems = $settings?.pinnedMenuItems ?? DEFAULT_PINNED_ITEMS;
@@ -540,6 +564,7 @@
};
const refreshChatRows = async () => {
markFolderChatsDirty();
const result = await refreshChatList(localStorage.token, { refreshPinned: true });
if (result.accepted) {
await initFolders();
@@ -873,10 +898,6 @@
}
if (folderId) {
if (chat) {
return folderRegistry[folderId]?.upsertChat?.(chat);
}
return folderRegistry[folderId]?.setFolderItems?.();
}
@@ -925,6 +946,7 @@
};
}) => {
if (event.data?.type === 'chat:active') {
updateFolderChatLists({ id: event.chat_id, active: event.data.data?.active ?? false, pending_approval: event.data.data?.pending_approval ?? false });
const eventData = event.data.data ?? {};
const active = eventData.active ?? false;
const pendingApproval = eventData.pending_approval ?? false;
@@ -941,6 +963,7 @@
await refreshChatRows();
}
} else if (event.data?.type === 'chat:list') {
if (typeof event.data.data?.last_read_at === 'number') updateFolderChatLists({ id: event.chat_id, last_read_at: event.data.data.last_read_at });
const eventData = event.data.data ?? {};
const folderUnreadCounts = eventData.folder_unread_counts;
if (folderUnreadCounts) {
@@ -1628,6 +1651,7 @@
);
if (res) {
updateFolderDetails(id, res);
await initFolders();
}
}
@@ -1639,6 +1663,11 @@
{shiftKey}
onFolderUnreadCounts={applyFolderUnreadCounts}
onDelete={(folderId) => {
for (const childId of Object.keys(folders)) {
let parentId = childId;
while (parentId && parentId !== folderId) parentId = folders[parentId]?.parent_id;
if (parentId) removeFolderState(childId);
}
let id = $selectedFolder?.id;
while (id && id !== folderId) id = folders[id]?.parent_id;
if (id) selectedFolder.set(null);
@@ -1711,6 +1740,7 @@
folderRegistry[chat.folder_id]?.setFolderItems();
if (res) {
updateFolderChatLists(res, null);
chat = res;
}
}
@@ -1812,6 +1842,7 @@
});
if (res) {
updateFolderChatLists(res, null);
chat = res;
}
}
@@ -49,6 +49,7 @@
user
} from '$lib/stores';
import { refreshChatList, refreshSidebar } from '$lib/stores/chatList';
import { updateFolderChatLists } from '$lib/stores/folderStates';
import ChatMenu from './ChatMenu.svelte';
import DeleteConfirmDialog from '$lib/components/common/ConfirmDialog.svelte';
@@ -263,6 +264,7 @@
return null;
});
if (!res) return;
updateFolderChatLists({ id, title });
if (id === $chatId) {
_chatTitle.set(title);
@@ -342,6 +344,7 @@
});
if (res) {
updateFolderChatLists({ id }, undefined, true);
if ($chatId === id) {
await goto('/');
@@ -363,6 +366,7 @@
try {
await archiveChatById(localStorage.token, id);
updateFolderChatLists({ id }, undefined, true);
if ($chatId === id) {
await goto('/');
@@ -389,6 +393,7 @@
);
if (res) {
updateFolderChatLists(res, folderId);
await refreshAfterChange(folderId);
toast.success($i18n.t('Chat moved successfully'));
@@ -1,7 +1,13 @@
<script lang="ts">
import { getContext, onMount } from 'svelte';
import { LinkPreview } from 'bits-ui';
import { getFolderById, getSharedFolderChats } from '$lib/apis/folders';
import {
folderStates,
folderChatPageKey,
loadFolderDetails,
loadFolderChatPage,
type FolderDetails,
} from '$lib/stores/folderStates';
import { models } from '$lib/stores';
import Emoji from '$lib/components/common/Emoji.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
@@ -17,9 +23,11 @@
export let isWritable = false;
export let onEdit = () => {};
let details: { data?: { model_ids?: string[]; files?: unknown[] } } | null = null;
let details: FolderDetails | null = null;
let total: number | null = null;
let loading = true;
$: details = $folderStates[folder.id]?.details ?? null;
$: total = $folderStates[folder.id]?.chatPages[folderChatPageKey()]?.total ?? null;
$: modelNames = (details?.data?.model_ids ?? []).map(
(id) => $models.find((model) => model.id === id)?.name ?? id
@@ -27,12 +35,10 @@
$: files = details?.data?.files ?? [];
onMount(async () => {
const [loadedFolder, chats] = await Promise.all([
getFolderById(localStorage.token, folder.id).catch(() => null),
getSharedFolderChats(localStorage.token, folder.id, { page: 1 }).catch(() => null)
await Promise.all([
loadFolderDetails(localStorage.token, folder.id).catch(() => null),
loadFolderChatPage(localStorage.token, folder.id).catch(() => null)
]);
details = loadedFolder;
total = chats?.total ?? null;
loading = false;
});
</script>
@@ -57,7 +63,7 @@
</div>
<div class="flex items-center gap-2 text-xs text-gray-500 dark:text-gray-400">
<ChatBubble className="size-3.5 shrink-0" />
{#if loading}
{#if loading && total === null}
<Spinner className="size-3" />
{:else if total !== null}
<span>{total.toLocaleString()} {$i18n.t(total === 1 ? 'Chat' : 'Chats')}</span>
@@ -8,8 +8,13 @@
import Modal from '$lib/components/common/Modal.svelte';
import AccessControl from '$lib/components/workspace/common/AccessControl.svelte';
import XMark from '../icons/XMark.svelte';
import { getFolderById, updateFolderAccessById } from '$lib/apis/folders';
import { updateFolderAccessById } from '$lib/apis/folders';
import { user } from '$lib/stores';
import {
loadFolderDetails,
updateFolderDetails,
markFolderChatsDirty,
} from '$lib/stores/folderStates';
type AccessGrant = {
id?: string;
@@ -33,7 +38,7 @@
const loadAccessGrants = async () => {
loading = true;
try {
const freshFolder = await getFolderById(localStorage.token, folder.id);
const freshFolder = await loadFolderDetails(localStorage.token, folder.id, true);
if (freshFolder) {
accessGrants = freshFolder.access_grants ?? [];
shareMode = freshFolder.data?.share_mode ?? null;
@@ -58,6 +63,9 @@
shareMode
);
if (res) {
updateFolderDetails(folder.id, res);
markFolderChatsDirty(folder.id);
await loadFolderDetails(localStorage.token, folder.id, true);
accessGrants = res.access_grants ?? accessGrants;
toast.success($i18n.t('Saved'));
}
@@ -19,21 +19,24 @@
import { toast } from 'svelte-sonner';
import { chatId, mobile, selectedFolder, showSidebar, user } from '$lib/stores';
import {
folderStates, getFolderState, folderChatPageKey, loadFolderChatPage,
loadFolderDetails, setFolderSidebarPage, updateFolderChatLists, markFolderRead,
updateFolderDetails, removeFolderState, beginFolderOpening, isCurrentFolderOpening,
isCancelledFolderRequest
} from '$lib/stores/folderStates';
import {
deleteFolderById,
updateFolderIsExpandedById,
updateFolderById,
updateFolderParentIdById,
getFolderById,
createNewFolder,
getSharedFolderChats,
markFolderChatsReadById
} from '$lib/apis/folders';
import {
getChatById,
getChatsByFolderId,
getChatListByFolderId,
updateChatFolderIdById,
importChats
} from '$lib/apis/chats';
@@ -148,7 +151,7 @@
}
if (typeof data?.last_read_at === 'number') {
folderRegistry[folderId]?.setChatReadAt?.(data.chat_id, data.last_read_at);
updateFolderChatLists({ id: data.chat_id, last_read_at: data.last_read_at });
}
};
@@ -169,15 +172,7 @@
}
}
if (chats) {
chats = sortFolderChats(
chats.map((chat) =>
!chat.user_id || chat.user_id === $user?.id
? { ...chat, last_read_at: chat.updated_at }
: chat
)
);
}
for (const id of res.folder_ids ?? [folderId]) markFolderRead(id, $user?.id);
};
$: isWritable = !folders[folderId]?.shared || folders[folderId]?.permission === 'write';
@@ -256,6 +251,7 @@
);
if (res) {
updateFolderDetails(id, res);
dispatch('update');
}
} else if (type === 'chat') {
@@ -296,6 +292,7 @@
return null;
});
if (res) updateFolderChatLists(res, folderId);
onItemMove({
originFolderId: chat.folder_id,
targetFolderId: folderId,
@@ -375,59 +372,15 @@
open = folders[folderId].is_expanded;
folderRegistry[folderId] = {
setFolderItems,
upsertChat: (chat) => {
if (chat.folder_id && chat.folder_id !== folderId) {
return;
}
pendingUpsertChats = mergeFolderChats(pendingUpsertChats, [chat]);
if (open || chats) {
chats = mergeFolderChats(chats ?? [], [chat]);
}
setChatActive: /** @param {string} id */ (id) => {
const found = chats?.some((chat) => chat.id === id) ?? false;
return found;
},
setChatActive: (chatId, active, pendingApproval = false) => {
if (chats) {
let found = false;
chats = sortFolderChats(
chats.map((chat) => {
if (chat.id !== chatId) {
return chat;
}
found = true;
return { ...chat, active, pending_approval: pendingApproval };
})
);
return found;
}
return false;
setChatReadAt: /** @param {string} id */ (id) => {
const found = chats?.some((chat) => chat.id === id) ?? false;
return found;
},
setChatReadAt: (chatId, lastReadAt) => {
if (chats) {
let found = false;
chats = sortFolderChats(
chats.map((chat) => {
if (chat.id !== chatId) {
return chat;
}
found = true;
return { ...chat, last_read_at: lastReadAt };
})
);
return found;
}
return false;
},
setAllChatsRead: () => {
if (chats) {
chats = sortFolderChats(
chats.map((chat) =>
!chat.user_id || chat.user_id === $user?.id
? { ...chat, last_read_at: chat.updated_at }
: chat
)
);
}
}
setAllChatsRead: () => markFolderRead(folderId, $user?.id)
};
if (folderElement) {
folderElement.addEventListener('dragover', onDragOver);
@@ -478,6 +431,7 @@
);
if (res) {
removeFolderState(folderId);
toast.success($i18n.t('Folder deleted successfully'));
onDelete(folderId);
}
@@ -506,6 +460,7 @@
});
if (res) {
updateFolderDetails(folderId, res);
folders[folderId].name = name;
if (data) {
folders[folderId].data = data;
@@ -515,7 +470,7 @@
toast.success($i18n.t('Folder updated successfully'));
if ($selectedFolder?.id === folderId) {
const folder = await getFolderById(localStorage.token, folderId).catch((error) => {
const folder = await loadFolderDetails(localStorage.token, folderId, true).catch((error) => {
toast.error(`${error}`);
return null;
});
@@ -546,104 +501,70 @@
}, 500);
};
const SIDEBAR_CHATS_PAGE_SIZE = 10;
/** @type {any[] | null} */
/** @type {import('$lib/stores/folderStates').FolderChat[] | null} */
let chats = null;
let chatsPage = 1;
let hasMoreChats = false;
let chatsLoading = false;
let queuedReload = false;
let pendingUpsertChats = [];
let wasOpen = false;
export const setFolderItems = async (append = false) => {
if (open && chatsLoading) {
if (!append) {
queuedReload = true;
}
$: {
const retained = $folderStates[folderId];
chatsPage = retained?.sidebarPage ?? 1;
const pages = Array.from({ length: chatsPage }, (_, index) =>
retained?.chatPages[folderChatPageKey({ page: index + 1 })]
);
chats = pages.some(Boolean) ? mergeFolderChats([], pages.flatMap((page) => page?.chats ?? [])) : null;
hasMoreChats = pages.at(-1)?.has_more ?? false;
}
export const setFolderItems = async (append = false, refresh = true) => {
if (!open) return;
if (chatsLoading) {
if (refresh) queuedReload = true;
return;
}
if (open) {
chatsLoading = true;
}
await tick();
if (open) {
if (!append) {
pendingUpsertChats = [];
chatsLoading = true;
try {
const nextPage = append ? chatsPage + 1 : chatsPage;
await Promise.all(Array.from({ length: append ? 1 : nextPage }, (_, index) =>
loadFolderChatPage(localStorage.token, folderId, { page: append ? nextPage : index + 1 }, !append && refresh)
));
if (append) setFolderSidebarPage(folderId, nextPage);
} catch (error) {
if (!isCancelledFolderRequest(error)) toast.error(`${error}`);
} finally {
chatsLoading = false;
if (queuedReload) {
queuedReload = false;
void setFolderItems();
}
// Always use getSharedFolderChats so owners also see chats
// created by users who have write access to this folder.
const nextPage = append ? chatsPage + 1 : 1;
try {
const res = await getSharedFolderChats(localStorage.token, folderId, {
page: nextPage
});
const nextChats = res?.chats ?? [];
const merged = append ? mergeFolderChats(chats ?? [], nextChats) : nextChats;
chats = mergeFolderChats(merged, pendingUpsertChats);
pendingUpsertChats = pendingUpsertChats.filter(
(pendingChat) => !nextChats.some((chat) => chat.id === pendingChat.id)
);
chatsPage = nextPage;
hasMoreChats = res?.has_more ?? nextChats.length === SIDEBAR_CHATS_PAGE_SIZE;
} catch (error) {
// Fallback to regular API
const fallback = await getChatListByFolderId(localStorage.token, folderId, nextPage).catch(
(error) => {
toast.error(`${error}`);
return [];
}
);
const fallbackChats = fallback ?? [];
const merged = append ? mergeFolderChats(chats ?? [], fallbackChats) : fallbackChats;
chats = mergeFolderChats(merged, pendingUpsertChats);
pendingUpsertChats = pendingUpsertChats.filter(
(pendingChat) => !fallbackChats.some((chat) => chat.id === pendingChat.id)
);
chatsPage = nextPage;
hasMoreChats = (fallback?.length ?? 0) === SIDEBAR_CHATS_PAGE_SIZE;
} finally {
chatsLoading = false;
if (queuedReload) {
queuedReload = false;
setFolderItems();
}
}
} else if (!open) {
chats = null;
chatsPage = 1;
hasMoreChats = false;
queuedReload = false;
}
};
$: if (open && chats === null && !chatsLoading) {
setFolderItems();
$: if (open !== wasOpen) {
wasOpen = open;
if (open) void setFolderItems(false, false);
}
const openFolderHandler = async () => {
const folder = await getFolderById(localStorage.token, folderId).catch((error) => {
toast.error(`${error}`);
return null;
});
if (folder) {
await selectedFolder.set({ ...folders[folderId], ...folder });
}
if (appLayout?.initNewChat) await appLayout.initNewChat(true, true);
else await goto(`/folders/${folderId}`);
if ($mobile) {
showSidebar.set(!$showSidebar);
const generation = beginFolderOpening();
const loaded = getFolderState(folderId).details;
try {
const folder = loaded ?? await loadFolderDetails(localStorage.token, folderId);
if (!isCurrentFolderOpening(generation)) return;
selectedFolder.set({ ...folders[folderId], ...folder });
if (loaded) void loadFolderDetails(localStorage.token, folderId, true).catch((error) => {
if (!isCancelledFolderRequest(error)) console.error(error);
});
if (appLayout?.initNewChat) await appLayout.initNewChat(true, true);
else await goto(`/folders/${folderId}`);
if (isCurrentFolderOpening(generation) && $mobile) showSidebar.set(false);
} catch (error) {
if (isCurrentFolderOpening(generation) && !isCancelledFolderRequest(error)) toast.error(`${error}`);
}
};
$: if (!open && chats !== null) {
chats = null;
chatsPage = 1;
hasMoreChats = false;
}
const renameHandler = async () => {
console.log('Edit');
@@ -1,4 +1,5 @@
<script lang="ts">
import { updateFolderChatLists } from '$lib/stores/folderStates';
import { getPageContext, onTabLeave } from '$lib/utils/page';
const { goto, url: pageUrl } = getPageContext();
@@ -901,6 +902,7 @@ ${content}
});
if (!deleted) return;
updateFolderChatLists({ id: chatId }, undefined, true);
let chats =
(await getNoteChatsById(localStorage.token, note.id).catch((error) => {
+6 -1
View File
@@ -1,5 +1,6 @@
import { get, readonly, writable } from 'svelte/store';
import { getChatList, getPinnedChatList } from '$lib/apis/chats';
import { markFolderChatsDirty, updateFolderChatLists } from './folderStates';
type ChatListItem = {
id: string;
@@ -62,7 +63,7 @@ export const refreshChatList = async (
return { accepted: true, allLoaded };
};
// The sidebar owns folder state. This bridge lets other components refresh it.
// Retained data is updated even when no folder component is mounted.
type FolderRefreshHandler = (folderId?: string | null, chat?: ChatListItem | null) => unknown;
const folderRefreshHandlers = new Set<FolderRefreshHandler>();
@@ -77,6 +78,10 @@ export const refreshFolderChatLists = async (
folderId?: string | null,
chat?: ChatListItem | null
) => {
if (folderId !== null) {
if (folderId && chat) updateFolderChatLists(chat, folderId);
else markFolderChatsDirty(folderId);
}
await Promise.all([...folderRefreshHandlers].map((handler) => handler(folderId, chat)));
};
+361
View File
@@ -0,0 +1,361 @@
import { readonly, writable } from 'svelte/store';
import { getFolderById, getSharedFolderChats } from '$lib/apis/folders';
import { getChatListByFolderId } from '$lib/apis/chats';
import { getModels } from '$lib/apis';
import type { Model } from '$lib/stores';
export type FolderDetails = {
id: string;
name: string;
parent_id?: string | null;
user_id?: string;
data?: {
terminal_id?: string;
working_directory?: string;
model_ids?: string[];
[key: string]: any;
} | null;
meta?: Record<string, any> | null;
write_access?: boolean;
access_grants?: any[];
[key: string]: any;
};
export type FolderChat = { id: string; [key: string]: any };
export type FolderChatQuery = {
page?: number;
sortBy?: 'title' | 'updated_at' | 'unread_updated_at';
sortDir?: 'asc' | 'desc';
};
export type FolderChatPage = {
chats: FolderChat[];
total: number;
has_more: boolean;
folder_permission?: string;
dirty: boolean;
};
export type FolderState = {
details: FolderDetails | null;
chatPages: Record<string, FolderChatPage>;
sidebarPage: number;
agentModels: {
terminalId: string;
directory: string;
connectionRevision: number;
models: Model[];
} | null;
};
let entries: Record<string, FolderState> = {};
const state = writable(entries);
export const folderStates = readonly(state);
const notify = () => state.set(entries);
let session = 0;
let opening = 0;
const revisions = new Map<string, number>();
const pending = new Map<string, { revision: number; promise: Promise<any> }>();
const resourceKey = (id: string, resource: string) => JSON.stringify([id, resource]);
const revision = (key: string) => revisions.get(key) ?? 0;
const changed = (key: string) => revisions.set(key, revision(key) + 1);
export const folderChatPageKey = (query: FolderChatQuery = {}) =>
JSON.stringify([query.page ?? 1, query.sortBy ?? 'unread_updated_at', query.sortDir ?? 'desc']);
export function getFolderState(id: string): FolderState {
return (entries[id] ??= { details: null, chatPages: {}, sidebarPage: 1, agentModels: null });
}
export const beginFolderOpening = () => ++opening;
export const isCurrentFolderOpening = (generation: number) => generation === opening;
export const isCancelledFolderRequest = (error: unknown) =>
error instanceof Error && error.name === 'AbortError';
// Navigation changes readers, not the lifetime of their successfully loaded data.
async function request<T>(
id: string,
resource: string,
fetch: () => Promise<T>,
accept: (data: T) => void
) {
const key = resourceKey(id, resource);
const version = revision(key);
const existing = pending.get(key);
if (existing?.revision === version) return existing.promise as Promise<T>;
const generation = session;
const task = { revision: version, promise: null as unknown as Promise<T> };
task.promise = (async () => {
try {
const data = await fetch();
if (generation !== session || version !== revision(key))
throw new DOMException('Folder request superseded', 'AbortError');
if (!data) throw new Error('Could not load folder');
accept(data);
notify();
return data;
} catch (error) {
if (generation === session && version === revision(key)) {
if (
!resource.startsWith('models:') &&
[403, 404].includes((error as { status?: number })?.status ?? 0)
)
removeFolderState(id);
if ((error as { status?: number })?.status === 401) clearFolderStates();
}
throw error;
} finally {
if (pending.get(key) === task) pending.delete(key);
}
})();
pending.set(key, task);
return task.promise;
}
export function loadFolderDetails(
token: string,
id: string,
refresh = false
): Promise<FolderDetails> {
const folder = getFolderState(id);
if (folder.details && !refresh) return Promise.resolve(folder.details);
return request(
id,
'details',
() => getFolderById(token, id),
(details) => {
folder.details = details;
}
);
}
export function updateFolderDetails(id: string, details: Partial<FolderDetails>) {
changed(resourceKey(id, 'details'));
const folder = getFolderState(id);
// Mutation responses omit access fields; never turn a partial response into full details.
if (folder.details) folder.details = { ...folder.details, ...details };
notify();
}
export function loadFolderChatPage(
token: string,
id: string,
query: FolderChatQuery = {},
refresh = false
): Promise<FolderChatPage> {
const folder = getFolderState(id);
const key = folderChatPageKey(query);
const page = folder.chatPages[key];
if (page && !page.dirty && !refresh) return Promise.resolve(page);
return request(
id,
key,
async () => {
let result;
try {
result = await getSharedFolderChats(token, id, { ...query, page: query.page ?? 1 });
} catch (error) {
// Keep the sidebar's legacy fallback, but never use it to bypass access failures.
if (
(query.sortBy && query.sortBy !== 'unread_updated_at') ||
[401, 403, 404].includes((error as any)?.status)
)
throw error;
const chats = await getChatListByFolderId(token, id, query.page ?? 1);
if (!chats) throw error;
result = { chats, total: chats.length, has_more: chats.length === 10 };
}
if (!result?.chats) throw new Error('Could not load folder chats');
return {
...result,
total: result.total ?? result.chats.length,
has_more: result.has_more ?? result.chats.length === 10,
dirty: false
};
},
(result) => {
folder.chatPages[key] = result;
}
);
}
export function setFolderSidebarPage(id: string, page: number) {
getFolderState(id).sidebarPage = page;
notify();
}
export function markFolderChatsDirty(id?: string) {
for (const folderId of id ? [id] : Object.keys(entries)) {
const folder = entries[folderId];
if (!folder) continue;
for (const [key, page] of Object.entries(folder.chatPages)) {
page.dirty = true;
changed(resourceKey(folderId, key));
}
for (const key of pending.keys()) {
const [pendingId, resource] = JSON.parse(key);
if (pendingId === folderId && resource.startsWith('[') && !folder.chatPages[resource])
changed(key);
}
}
notify();
}
const unread = (chat: FolderChat) =>
!chat.active && (chat.last_read_at == null || chat.updated_at > chat.last_read_at);
export function sortFolderChats(
chats: FolderChat[],
sortBy = 'unread_updated_at',
sortDir = 'desc'
) {
return [...chats].sort((a, b) => {
const order =
sortBy === 'title'
? String(a.title ?? '').localeCompare(String(b.title ?? ''))
: (sortBy === 'unread_updated_at' ? Number(unread(a)) - Number(unread(b)) : 0) ||
Number(a.updated_at ?? 0) - Number(b.updated_at ?? 0);
return sortDir === 'asc' ? order : -order;
});
}
export function updateFolderChatLists(chat: FolderChat, destination?: string | null, remove = false) {
const { chat: conversation, ...row } = chat;
chat = row;
for (const [id, folder] of Object.entries(entries)) {
const known = Object.values(folder.chatPages).some((page) =>
page.chats.some((item) => item.id === chat.id)
);
const removingFromFolder = remove || (destination !== undefined && destination !== id);
const countChange =
removingFromFolder && known
? -1
: !removingFromFolder && destination === id && !known
? 1
: 0;
for (const [key, page] of Object.entries(folder.chatPages)) {
const [number, sortBy, sortDir] = JSON.parse(key);
page.total = Math.max(0, page.total + countChange);
page.has_more = page.total > number * 10;
const existing = page.chats.find((item) => item.id === chat.id);
const removing = remove || (destination !== undefined && destination !== id);
if (!existing && (removing || destination !== id || number !== 1)) continue;
changed(resourceKey(id, key));
if (removing) {
page.chats = page.chats.filter((item) => item.id !== chat.id);
} else {
page.chats = sortFolderChats(
[...page.chats.filter((item) => item.id !== chat.id), { ...existing, ...chat }],
sortBy,
sortDir
);
}
}
}
// Membership and ordering can change page boundaries. Keep rows until reconciliation.
if (remove || destination !== undefined || chat.title !== undefined) markFolderChatsDirty();
else notify();
}
export function markFolderRead(id: string, userId: string | undefined) {
if (!userId) return;
for (const page of Object.values(entries[id]?.chatPages ?? {})) {
for (const chat of page.chats) {
if (!chat.user_id || chat.user_id === userId)
updateFolderChatLists({ id: chat.id, last_read_at: chat.updated_at });
}
}
}
export function removeFolderState(id: string) {
const descendants = Object.keys(entries).filter(
(child) => entries[child].details?.parent_id === id
);
for (const child of descendants) removeFolderState(child);
for (const key of new Set([...revisions.keys(), ...pending.keys()])) {
if (JSON.parse(key)[0] === id) changed(key);
}
delete entries[id];
notify();
}
let connectionRevision = 0;
let connectionsSignature = '';
const agentRequests = new Map<string, Promise<Model[]>>();
export function setFolderModelConnections(configuration: unknown) {
const signature = JSON.stringify(configuration);
if (signature !== connectionsSignature) {
connectionsSignature = signature;
connectionRevision++;
}
}
export function getFolderAgentModels(folder: FolderDetails): Model[] | null {
const loaded = entries[folder.id]?.agentModels;
return loaded &&
loaded.terminalId === folder.data?.terminal_id &&
loaded.directory === (folder.data?.working_directory ?? '') &&
loaded.connectionRevision === connectionRevision
? loaded.models
: null;
}
export async function loadFolderAgentModels(
token: string,
folder: FolderDetails,
connections: any,
refresh = false
): Promise<Model[]> {
const loaded = getFolderAgentModels(folder);
if (loaded && !refresh) return loaded;
const terminalId = folder.data?.terminal_id;
if (!terminalId) return [];
const directory = folder.data?.working_directory ?? '';
const version = connectionRevision;
const resource = `models:${JSON.stringify([terminalId, directory, version])}`;
return request(
folder.id,
resource,
async () => {
let discovery = agentRequests.get(resource);
if (!discovery) {
discovery = getModels(token, connections, false, false, {
terminalId,
chatId: null,
cwd: directory || null
}).then((models) => models.filter((model: Model) => model.owned_by === 'terminal'));
agentRequests.set(resource, discovery);
}
try {
return await discovery;
} finally {
if (agentRequests.get(resource) === discovery) agentRequests.delete(resource);
}
},
(models) => {
const current = getFolderState(folder.id);
const details = current.details;
if (
details &&
(details.data?.terminal_id !== terminalId ||
(details.data?.working_directory ?? '') !== directory)
)
return;
if (version === connectionRevision)
current.agentModels = {
terminalId,
directory,
connectionRevision: version,
models
};
}
);
}
export function clearFolderStates() {
session++;
opening++;
entries = {};
pending.clear();
agentRequests.clear();
revisions.clear();
connectionsSignature = '';
connectionRevision++;
notify();
}
+2 -1
View File
@@ -9,6 +9,7 @@ import { type Writable, derived, get, writable } from 'svelte/store';
import type { CommentTarget } from '$lib/apis/comments';
import type { ModelConfig } from '$lib/apis';
import type { Banner } from '$lib/types';
import type { FolderDetails } from './folderStates';
import type { Socket } from 'socket.io-client';
import type { AudioQueue, NotificationSoundStyle } from '$lib/utils/audio';
import type { I18nOverrides } from '$lib/utils/translationDictionary';
@@ -77,7 +78,7 @@ export const pinnedNotes = writable([]);
export const tags = writable([]);
export const folders = writable([]);
export const selectedFolder = writable(null);
export const selectedFolder = writable<FolderDetails | null>(null);
export const models: Writable<Model[]> = writable([]);
@@ -6,49 +6,51 @@
import Chat from '$lib/components/chat/Chat.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import { getFolderById } from '$lib/apis/folders';
import {
getFolderState,
loadFolderDetails,
beginFolderOpening,
isCurrentFolderOpening,
isCancelledFolderRequest,
} from '$lib/stores/folderStates';
import { selectedFolder } from '$lib/stores';
let ready = false;
let loadedFolderId = '';
const init = async (folderId) => {
const init = async (folderId: string) => {
if (!folderId) {
await goto('/');
return;
}
// The sidebar click handler already fetches the folder and sets
// `selectedFolder` before navigating here; refetching would duplicate
// the request and re-trigger the sidebar's folder refresh.
if ($selectedFolder?.id !== folderId) {
const folder = await getFolderById(localStorage.token, folderId).catch((error) => {
toast.error(`${error}`);
return null;
const generation = beginFolderOpening();
const loaded = getFolderState(folderId).details;
if (!loaded && $selectedFolder?.id !== folderId) ready = false;
try {
const folder = loaded ?? await loadFolderDetails(localStorage.token, folderId);
if (!isCurrentFolderOpening(generation) || folderId !== loadedFolderId) return;
if ($selectedFolder?.id !== folderId) selectedFolder.set(folder);
if (loaded) void loadFolderDetails(localStorage.token, folderId, true).catch((error) => {
if (!isCancelledFolderRequest(error)) console.error(error);
});
if (folderId !== loadedFolderId) {
return;
}
if (!folder) {
await goto('/');
return;
}
await selectedFolder.set(folder);
} catch (error) {
if (!isCurrentFolderOpening(generation) || isCancelledFolderRequest(error)) return;
toast.error(`${error}`);
await goto('/');
return;
}
ready = true;
};
$: if ($page.params.folderId !== loadedFolderId) {
loadedFolderId = $page.params.folderId;
loadedFolderId = $page.params.folderId ?? '';
init(loadedFolderId);
}
onDestroy(() => {
selectedFolder.set(null);
if ($selectedFolder?.id === loadedFolderId) selectedFolder.set(null);
});
</script>
+4
View File
@@ -47,11 +47,13 @@
desktopEvent
} from '$lib/stores';
import { refreshChatList } from '$lib/stores/chatList';
import { clearFolderStates, updateFolderChatLists, beginFolderOpening } from '$lib/stores/folderStates';
import { getFileBlobById, getFileContentById } from '$lib/apis/files';
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import { beforeNavigate } from '$app/navigation';
import { updated } from '$app/state';
beforeNavigate(() => beginFolderOpening());
import i18n, { initI18n, getLanguages, changeLanguage } from '$lib/i18n';
@@ -843,6 +845,7 @@
});
}
} else if (type === 'chat:title') {
updateFolderChatLists({ id: event.chat_id, title: data });
await refreshChatList(localStorage.token);
} else if (type === 'chat:tags') {
tags.set(await getAllTags(localStorage.token));
@@ -1310,6 +1313,7 @@
let queueUserId = $user?.id;
const unsubscribeQueueUser = user.subscribe(async (value) => {
if (queueUserId !== value?.id) {
clearFolderStates();
channelRequestQueues.set({});
queueUserId = value?.id;
}