This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-16 21:56:34 +09:00
1 parent c82884453c
commit 7be99d1e97
13 files changed
+94 -173

No files matched your search

+50 -46
View File
@@ -17,7 +17,7 @@
const i18n: Writable<i18nType> = getContext('i18n');
const appLayout = getContext<AppLayoutContext | undefined>('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<AppLayoutContext['initNewChat']> = 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<typeof setTimeout> | 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());
}
}}
@@ -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<AppLayoutContext | undefined>('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);
}
+1 -1
View File
@@ -1990,7 +1990,7 @@
></div>
</div>
{/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
+1 -1
View File
@@ -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('/');
};
@@ -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 () => {
-4
View File
@@ -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<string, number>();
const pending = new Map<string, { revision: number; promise: Promise<any> }>();
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();
+5 -1
View File
@@ -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<void>;
initNewChat?: (options?: {
preserveTabs?: boolean;
temporary?: boolean;
url?: URL;
}) => Promise<void>;
};
/** State of the chat a component is rendered in, so a side chat doesn't read the main chat's. */
+10 -5
View File
@@ -61,7 +61,9 @@
const appLayout = setContext<AppLayoutContext>('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}
<main class="contents">
<div id="main-content" tabindex="-1" class="sr-only left-0 top-0"></div>
{#if usePageTabs}
<Chat initialPage={$page.url.pathname + $page.url.search + $page.url.hash} />
{:else}<slot />{/if}
{#if routeHasTabs || usePageTabs}
<Chat
initialPage={usePageTabs ? $page.url.pathname + $page.url.search + $page.url.hash : ''}
/>
{/if}
{#if !usePageTabs}<slot />{/if}
</main>
{:else}
<div
+2 -9
View File
@@ -1,15 +1,8 @@
<script lang="ts">
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);
</script>
<Chat />
+1 -11
View File
@@ -1,11 +1 @@
<script lang="ts">
import { navigating, page } from '$app/state';
import Chat from '$lib/components/chat/Chat.svelte';
const params = $derived(
(navigating.to?.route.id === page.route.id && navigating.to.params) || page.params
);
</script>
<Chat chatIdProp={params.id} />
<!-- The shared app layout owns the chat and its tabs. -->
@@ -1,63 +1 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/stores';
import { onDestroy } from 'svelte';
import { toast } from 'svelte-sonner';
import Chat from '$lib/components/chat/Chat.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import {
getFolderState,
loadFolderDetails,
beginFolderOpening,
isCurrentFolderOpening,
isCancelledFolderRequest,
} from '$lib/stores/folderStates';
import { selectedFolder, showSidebar } from '$lib/stores';
let ready = false;
let loadedFolderId = '';
const init = async (folderId: string) => {
if (!folderId) {
await goto('/');
return;
}
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);
});
} 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 ?? '';
init(loadedFolderId);
}
onDestroy(() => {
if ($selectedFolder?.id === loadedFolderId) selectedFolder.set(null);
});
</script>
{#if ready}
<Chat />
{:else}
<div class="w-full h-screen max-h-[100dvh] flex items-center justify-center {$showSidebar ? 'md:max-w-[calc(100%-var(--sidebar-width))]' : ''}">
<Spinner className="size-5" />
</div>
{/if}
<!-- The shared app layout owns the chat and its tabs. -->
@@ -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))}`);
}
};
+1 -2
View File
@@ -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';