diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index 3b5fe53d5b..4923294afa 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -17,7 +17,7 @@ const i18n: Writable = getContext('i18n'); const appLayout = getContext('appLayout'); - import { goto, beforeNavigate, afterNavigate, onNavigate } from '$app/navigation'; + import { goto, beforeNavigate, afterNavigate } from '$app/navigation'; import { page } from '$app/stores'; import { get, writable, type Unsubscriber, type Writable } from 'svelte/store'; @@ -264,7 +264,7 @@ return; } window.history.replaceState(window.history.state, '', `${location.pathname}${search}`); - if ($chatId) await initNewChat(false, false, value); + if ($chatId) await initNewChat({ temporary: value }); else temporaryChat.set(value); }; @@ -1015,6 +1015,7 @@ onDestroy(() => chatLoadController.abort()); const navigateHandler = async () => { loading = true; + selectedFolder.set(null); tabs?.resetForChatSwitch(); const signal = startChatLoad(); modelDefaults = null; @@ -2168,16 +2169,6 @@ ); audioQueue.set(audioQueueInstance); - if ( - !embedded && - (initialPage || $page.url.pathname === '/' || $page.url.pathname.startsWith('/folders/')) - ) { - tick().then(async () => { - await initNewChat(); - if (initialPage) tabs?.openPageTab({ href: initialPage, label: '' }); - }); - } - const selectedFolderSubscribe = selectedFolder.subscribe(async (folder) => { await tick(); // Navigation applies defaults in initNewChat; only explicit settings edits reach here. @@ -2228,7 +2219,11 @@ messageInput?.focus({ preventScroll: true }); }; - init(); + if (embedded) init(); + else + void tick().then(() => { + if (!routeInitialized) void followRoute(); + }); return () => { try { @@ -2240,6 +2235,7 @@ } if (appLayout?.initNewChat === initNewChat) delete appLayout.initNewChat; selectedFolderSubscribe(); + if (!embedded) selectedFolder.set(null); // Clear the selected chat when leaving the chat surface (e.g. navigating // to the admin panel), otherwise the previously-viewed chat stays selected @@ -2724,26 +2720,32 @@ }); return () => bridge?.end(); }); - // Only real navigation resets the chat; shallow sidebar state changes must preserve it. - afterNavigate(async ({ from, to }) => { - // A navigation that mounts this page starts its new chat in onMount. - if ( - !embedded && - from?.route.id === to?.route.id && - (to?.url.pathname === '/' || to?.url.pathname.startsWith('/folders/')) - ) { - await tick(); - initNewChat(); + // The layout keeps this component mounted; route changes update only the main pane. + let routeInitialized = false; + const followRoute = async () => { + const preserveTabs = routeInitialized; + routeInitialized = true; + await tick(); + if ($page.route.id === '/(app)/c/[id]') { + chatIdProp = $page.params.id ?? ''; + } else if ($page.params.folderId || $page.url.pathname === '/') { + selectedFolder.set($page.data.folder ?? null); + await initNewChat({ preserveTabs, url: $page.url }); + } else if (initialPage) { + if (!preserveTabs) await initNewChat(); + loading = false; + tabs?.openPageTab({ href: initialPage, label: '' }); } + }; + afterNavigate(() => { + if (!embedded) void followRoute(); stopAudio(); }); beforeNavigate(() => { + if (!loading && !$temporaryChat) void saveDraft(getChatInputDraft(), getDraftChatId(), false); bridge?.end(); pendingUrlActions = null; }); - onNavigate(({ from, to }) => { - if (!embedded && to && from?.url.pathname !== to.url.pathname) loading = true; - }); $: if (!$user && (bridge?.connected || bridge?.connecting)) bridge.end(); $: if (selectedModelIds && $models && $config) bridge?.syncModel(); @@ -2877,24 +2879,22 @@ showTabs.set(true); }; - const initNewChat = async (preserveTabs = false, keepDraft = false, temporary?: boolean) => { + const initNewChat: NonNullable = async ({ + preserveTabs = false, + temporary, + url = initialPage || preserveTabs ? undefined : $page.url + } = {}) => { + if (!loading && !$temporaryChat) void saveDraft(getChatInputDraft(), getDraftChatId(), 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; + const searchParams = url?.searchParams ?? new URLSearchParams(); mainChatHref = '/'; - if (!initialPage && !preserveTabs && $page.url.pathname === '/') { - mainChatHref += $page.url.search + $page.url.hash; + if (url?.pathname === '/') { + mainChatHref += url.search + url.hash; } if (destinationFolder?.id) mainChatHref = `/folders/${destinationFolder.id}`; - if (keepDraft && !$chatId && !history.currentId && previousHref === mainChatHref) { - tabs?.focusMainChat(); - return; - } + if (preserveTabs) tabs?.carryPagesToNewChat(); else tabs?.resetForChatSwitch(); loading = true; @@ -3035,9 +3035,9 @@ autoScroll = true; // resetInput() must stay last: the selected model's defaults override the draft's selection. - const chatInputPrompt = (await restoreChatInput( - retainedDraft ?? sessionStorage.getItem(getChatInputKey()) - )) + prompt = ''; + files = []; + const chatInputPrompt = (await restoreChatInput(sessionStorage.getItem(getChatInputKey()))) ? prompt : null; const previousChatId = $chatId; @@ -5434,8 +5434,12 @@ let saveDraftTimeout: ReturnType | null = null; // chatIdProp is empty for chats started from the home page (URL set via replaceState) const getDraftChatId = () => chatIdProp || $chatId || embeddedDraftKey || null; - const getChatInputKey = (chatId: string | null = null) => - `chat-input${chatId ? `-${chatId}` : ''}`; + const getChatInputKey = (chatId: string | null = null) => { + if (chatId) return `chat-input-${chatId}`; + // Use the displayed pane: selectedFolder may already point to the destination. + const folderId = !embedded && mainChatHref.match(/^\/folders\/([^/?#]+)/)?.[1]; + return folderId ? `chat-input-folder-${folderId}` : 'chat-input'; + }; const getChatInputDraft = () => ({ prompt, @@ -6097,7 +6101,7 @@ onQueueEdit={editQueuedMessage} onQueueDelete={deleteQueuedMessage} onChange={(data: any) => { - if (!$temporaryChat) { + if (!loading && !$temporaryChat) { saveDraft(data, getDraftChatId()); } }} @@ -6216,7 +6220,7 @@ onQueueEdit={editQueuedMessage} onQueueDelete={deleteQueuedMessage} onChange={(data: any) => { - if (!$temporaryChat) { + if (!loading && !$temporaryChat) { saveDraft(data, getDraftChatId()); } }} @@ -6287,7 +6291,7 @@ showChatVariablesModal = true; }} onChange={(data: any) => { - if (!$temporaryChat) { + if (!loading && !$temporaryChat) { saveDraft(data, getDraftChatId()); } }} diff --git a/src/lib/components/chat/Messages/Markdown/MarkdownInlineTokens.svelte b/src/lib/components/chat/Messages/Markdown/MarkdownInlineTokens.svelte index 2f6825960c..fb21f819d7 100644 --- a/src/lib/components/chat/Messages/Markdown/MarkdownInlineTokens.svelte +++ b/src/lib/components/chat/Messages/Markdown/MarkdownInlineTokens.svelte @@ -6,6 +6,7 @@ import type { AppLayoutContext } from '$lib/types'; import { getContext } from 'svelte'; import { goto } from '$app/navigation'; + import { pageTabKey } from '$lib/components/chat/Tabs/tabs'; const i18n = getContext('i18n'); const appLayout = getContext('appLayout'); @@ -78,17 +79,14 @@ * Handle link clicks - intercept same-origin app URLs for in-app navigation */ const handleLinkClick = (e: MouseEvent, href: string) => { + if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return; try { const url = new URL(href, window.location.origin); + const folderId = url.pathname.match(/^\/folders\/([^/]+)\/?$/)?.[1]; // Check if same origin and an in-app route - if ( - url.origin === window.location.origin && - (url.pathname.startsWith('/notes/') || - url.pathname.startsWith('/c/') || - url.pathname.startsWith('/channels/')) - ) { + if (url.origin === window.location.origin && (folderId || pageTabKey(url))) { e.preventDefault(); - if (appLayout?.openPageTab && !url.pathname.startsWith('/c/')) + if (!folderId && appLayout?.openPageTab && !url.pathname.startsWith('/c/')) appLayout.openPageTab({ href: url.pathname + url.search + url.hash, label: '' }); else goto(url.pathname + url.search + url.hash); } diff --git a/src/lib/components/chat/Tabs.svelte b/src/lib/components/chat/Tabs.svelte index c18c2cce57..018d9d90cf 100644 --- a/src/lib/components/chat/Tabs.svelte +++ b/src/lib/components/chat/Tabs.svelte @@ -1990,7 +1990,7 @@ > {/each} - {#each (viewReady ? tabs.tabs : []).filter((tab) => tab.id !== mainChatTabId) as tab (`${viewEntry?.instanceId}:${tab.id}`)} + {#each (viewReady ? tabs.tabs : []).filter((tab) => tab.id !== mainChatTabId) as tab (tab.kind === 'page' ? tab.id : `${viewEntry?.instanceId}:${tab.id}`)} {@const chatView = viewEntry!} {@const target = isMounted && $config && $user && $settings && $terminalServers !== null diff --git a/src/lib/components/layout/Sidebar.svelte b/src/lib/components/layout/Sidebar.svelte index 92c299d09c..73a203205c 100644 --- a/src/lib/components/layout/Sidebar.svelte +++ b/src/lib/components/layout/Sidebar.svelte @@ -1057,7 +1057,7 @@ selectedFolder.set(null); closeMobileSidebar(); - if (appLayout?.initNewChat) await appLayout.initNewChat(true); + if (appLayout?.initNewChat) await appLayout.initNewChat({ preserveTabs: true }); else await goto('/'); }; diff --git a/src/lib/components/layout/Sidebar/RecursiveFolder.svelte b/src/lib/components/layout/Sidebar/RecursiveFolder.svelte index a7771786c6..a69bea6ff2 100644 --- a/src/lib/components/layout/Sidebar/RecursiveFolder.svelte +++ b/src/lib/components/layout/Sidebar/RecursiveFolder.svelte @@ -6,8 +6,6 @@ import { getContext, createEventDispatcher, onMount, onDestroy, tick } from 'svelte'; const i18n = getContext('i18n'); - /** @type {import('$lib/types').AppLayoutContext | undefined} */ - const appLayout = getContext('appLayout'); const dispatch = createEventDispatcher(); import DOMPurify from 'dompurify'; @@ -20,9 +18,9 @@ import { chatId, mobile, selectedFolder, showSidebar, user } from '$lib/stores'; import { - folderStates, getFolderState, folderChatPageKey, loadFolderChatPage, + folderStates, folderChatPageKey, loadFolderChatPage, loadFolderDetails, setFolderSidebarPage, updateFolderChatLists, markFolderRead, - updateFolderDetails, removeFolderState, beginFolderOpening, isCurrentFolderOpening, + updateFolderDetails, removeFolderState, isCancelledFolderRequest } from '$lib/stores/folderStates'; import { refreshFolderChatLists } from '$lib/stores/chatList'; @@ -555,25 +553,8 @@ } const openFolderHandler = async () => { - 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); - if (isCurrentFolderOpening(generation) && $mobile) showSidebar.set(false); - } else { - await goto(`/folders/${folderId}`); - if ($mobile) showSidebar.set(false); - } - } catch (error) { - if (isCurrentFolderOpening(generation) && !isCancelledFolderRequest(error)) toast.error(`${error}`); - } + await goto(`/folders/${folderId}`); + if ($mobile) showSidebar.set(false); }; const renameHandler = async () => { diff --git a/src/lib/stores/folderStates.ts b/src/lib/stores/folderStates.ts index 15e702ee9a..0fc1118bd5 100644 --- a/src/lib/stores/folderStates.ts +++ b/src/lib/stores/folderStates.ts @@ -58,7 +58,6 @@ const state = writable(entries); export const folderStates = readonly(state); const notify = () => state.set(entries); let session = 0; -let opening = 0; const revisions = new Map(); const pending = new Map }>(); const resourceKey = (id: string, resource: string) => JSON.stringify([id, resource]); @@ -87,8 +86,6 @@ 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'; @@ -388,7 +385,6 @@ export async function loadFolderAgentModels( export function clearFolderStates() { session++; - opening++; entries = {}; pending.clear(); agentRequests.clear(); diff --git a/src/lib/types/index.ts b/src/lib/types/index.ts index d3fa9727e6..11ac652e9f 100644 --- a/src/lib/types/index.ts +++ b/src/lib/types/index.ts @@ -23,7 +23,11 @@ export type TerminalContext = { export type AppLayoutContext = { openPageTab?: (tab: { href: string; label: string }) => void; - initNewChat?: (preserveTabs?: boolean, keepDraft?: boolean, temporary?: boolean) => Promise; + initNewChat?: (options?: { + preserveTabs?: boolean; + temporary?: boolean; + url?: URL; + }) => Promise; }; /** State of the chat a component is rendered in, so a side chat doesn't read the main chat's. */ diff --git a/src/routes/(app)/+layout.svelte b/src/routes/(app)/+layout.svelte index 0037b6a47d..7709a9db7c 100644 --- a/src/routes/(app)/+layout.svelte +++ b/src/routes/(app)/+layout.svelte @@ -61,7 +61,9 @@ const appLayout = setContext('appLayout', {}); let loaded = false; - $: routeHasTabs = ['/(app)', '/(app)/c/[id]'].includes($page.route.id ?? ''); + $: routeHasTabs = ['/(app)', '/(app)/c/[id]', '/(app)/folders/[folderId]'].includes( + $page.route.id ?? '' + ); $: usePageTabs = !routeHasTabs && !!pageTabKey($page.url); let version; @@ -341,7 +343,7 @@ } const temporary = !$temporaryChat; await goto('/'); - setTimeout(() => appLayout.initNewChat?.(false, false, temporary), 0); + setTimeout(() => appLayout.initNewChat?.({ temporary }), 0); } else if (shortcut === Shortcut.GENERATE_MESSAGE_PAIR) { console.log('Shortcut triggered: GENERATE_MESSAGE_PAIR'); event.preventDefault(); @@ -478,9 +480,12 @@ {#if loaded}
- {#if usePageTabs} - - {:else}{/if} + {#if routeHasTabs || usePageTabs} + + {/if} + {#if !usePageTabs}{/if}
{:else}
- import { onMount } from 'svelte'; import { toast } from 'svelte-sonner'; - import Chat from '$lib/components/chat/Chat.svelte'; import { page } from '$app/stores'; - onMount(() => { - if ($page.url.searchParams.get('error')) { - toast.error($page.url.searchParams.get('error') || 'An unknown error occurred.'); - } - }); + $: error = $page.url.searchParams.get('error'); + $: if (error) toast.error(error); - - diff --git a/src/routes/(app)/c/[id]/+page.svelte b/src/routes/(app)/c/[id]/+page.svelte index 7b22876ab7..8d97cc3ffd 100644 --- a/src/routes/(app)/c/[id]/+page.svelte +++ b/src/routes/(app)/c/[id]/+page.svelte @@ -1,11 +1 @@ - - - + diff --git a/src/routes/(app)/folders/[folderId]/+page.svelte b/src/routes/(app)/folders/[folderId]/+page.svelte index d5b21399fe..8d97cc3ffd 100644 --- a/src/routes/(app)/folders/[folderId]/+page.svelte +++ b/src/routes/(app)/folders/[folderId]/+page.svelte @@ -1,63 +1 @@ - - -{#if ready} - -{:else} -
- -
-{/if} + diff --git a/src/routes/(app)/folders/[folderId]/+page.ts b/src/routes/(app)/folders/[folderId]/+page.ts new file mode 100644 index 0000000000..363197ed16 --- /dev/null +++ b/src/routes/(app)/folders/[folderId]/+page.ts @@ -0,0 +1,13 @@ +import { redirect } from '@sveltejs/kit'; +import { loadFolderDetails } from '$lib/stores/folderStates'; +import type { PageLoad } from './$types'; + +export const load: PageLoad = async ({ params, url }) => { + if (!localStorage.token) + redirect(303, `/auth?redirect=${encodeURIComponent(url.pathname + url.search)}`); + try { + return { folder: await loadFolderDetails(localStorage.token, params.folderId, true) }; + } catch (error) { + redirect(303, `/?error=${encodeURIComponent(String(error))}`); + } +}; diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index 29fdf008dd..254f34454d 100644 --- a/src/routes/+layout.svelte +++ b/src/routes/+layout.svelte @@ -42,13 +42,12 @@ desktopEvent } from '$lib/stores'; import { refreshChatList, setChatTitle } from '$lib/stores/chatList'; - import { clearFolderStates, beginFolderOpening } from '$lib/stores/folderStates'; + import { clearFolderStates } from '$lib/stores/folderStates'; import { 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';