From b428dbaf2d93ed2836575112b471f34b5f8290dd Mon Sep 17 00:00:00 2001 From: Classic298 <27028174+Classic298@users.noreply.github.com> Date: Wed, 11 Nov 2026 02:10:53 +0100 Subject: [PATCH] refac: side chat uses the same chat as the main view (#34064) * refac: chat input reads its terminal from the chat it belongs to The message input with its menus, skills dialog and command lists read the selected terminal and the terminal's skills from one page-wide place. They now get both from the chat they are part of. Every chat still hands over the same page-wide selection, so nothing changes for users. This prepares for chats that run next to the main chat and keep their own terminal; the text editor inside the input, the message list, the model list and the current side chat's own request still look the terminal up page-wide. * refac: the chat builds the key for its unsent input in one place The chat spelled out the storage key for its unsent input in six places. One function builds it now, with the same keys as before, so nothing changes for users. This prepares for chats that run next to the main chat and keep their unsent input apart. * fix: two chats on one page take each other's unsent text, input requests and regenerate shortcut With a chat open next to a note, three things reached the wrong chat. Text typed into a new chat next to a note replaced the unsent text of a new main chat. An input request from a tool was answered as cancelled by the other chat on the page before its dialog could show. The regenerate shortcut, pressed in the main chat's input, regenerated the note chat's answer. Each chat now keeps its own unsent text and leaves the other chat's input requests alone, and the shortcut takes the main chat's last answer. * refac: let the chat run inside a side chat tab A second copy of the chat can already run on the same page, next to a note. This prepares it to run in a side chat tab too: it can be opened with a given conversation, unsent input and first message, and it sends the parent chat's messages to the model as context while showing only what was written in the side chat. A chat in a side tab keeps away from what belongs to the main chat: it uses the main chat's terminal without changing it, and it leaves the last used model, sign-in redirects and prompts sent by embeds to the main chat. Nothing opens a chat in a side tab yet, so the main chat and the chat next to a note behave as before. * refac: side chat uses the same chat as the main view The side chat was a separate, reduced version of the chat with its own code for sending, streaming and loading, so many chat features were missing or behaved differently there. A side chat tab now runs the same chat as the main view and the separate version is removed. Message buttons, sources, token usage, follow-ups, slash commands, queued messages, chat variables and tool events such as code execution and input requests now work in a side chat. Chats saved by the old side chat still open, and in most places where the old side chat had its own rules it now follows the main chat, for example it can answer with several models at once and shows errors as notifications. A new chat opened in a tab on its own, for example from a pinned model, no longer gets the neighbouring chat's system prompt and the side conversation instruction saved as its own. Fixes #34029 --- src/lib/components/chat/Chat.svelte | 143 +++- src/lib/components/chat/MessageInput.svelte | 10 +- .../MessageInput/CommandSuggestionList.svelte | 12 + .../MessageInput/Commands/AtCommands.svelte | 3 +- .../chat/MessageInput/Commands/Skills.svelte | 11 +- .../Commands/SlashCommands.svelte | 13 +- .../chat/MessageInput/IntegrationsMenu.svelte | 5 +- .../chat/MessageInput/TerminalMenu.svelte | 3 +- src/lib/components/chat/Messages.svelte | 6 +- .../chat/Messages/ResponseMessage.svelte | 3 +- src/lib/components/chat/SkillsModal.svelte | 5 +- src/lib/components/chat/Tabs/SideChat.svelte | 779 ++---------------- src/routes/(app)/+layout.svelte | 4 +- 13 files changed, 248 insertions(+), 749 deletions(-) diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index fce6af6ec6..3f8aeaf81d 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -40,6 +40,7 @@ audioQueue as _audioQueue, showTabs as _showTabs, sideChatRequest, + openSideChatIds, showCallOverlay as _showCallOverlay, temporaryChatEnabled as _temporaryChatEnabled, mobile, @@ -54,7 +55,7 @@ functions, selectedFolder as _selectedFolder, showEmbeds as _showEmbeds, - selectedTerminalId, + selectedTerminalId as _selectedTerminalId, showFileNavPath, showFileNavDir, chatRequestQueues, @@ -167,6 +168,7 @@ let mainChatHref = '/'; $: if ($chatId) mainChatHref = `/c/${$chatId}`; export let embedded = false; + export let side = false; const chatId = embedded ? writable('') : _chatId; const chatTitle = embedded ? writable('') : _chatTitle; const audioQueue = embedded ? writable(null) : _audioQueue; @@ -177,9 +179,24 @@ const showArtifacts = embedded ? writable(false) : _showArtifacts; const showEmbeds = embedded ? writable(false) : _showEmbeds; const artifactContents = embedded ? writable(null) : _artifactContents; + // A side chat uses the main chat's terminal and never changes it. + const selectedTerminalId = side + ? { subscribe: _selectedTerminalId.subscribe, set: () => {} } + : _selectedTerminalId; export let embeddedTitle = ''; export let embeddedChats = []; export let embeddedDraftKey = ''; + export let embeddedDraft: { + selectedModels: string[]; + params: Record; + history: typeof history; + chatFiles: any[]; + temporary: boolean; + prompt: string; + files: any[]; + } | null = null; + export let initialPrompt = ''; + export let parentChatId = ''; export let suggestedPrompts = []; export let selectedText = ''; export let notePageId = ''; @@ -188,7 +205,13 @@ export let onInsertToNote: ((content: string) => void) | null = null; export let onCloseEmbedded: (() => void) | null = null; export let onNewEmbeddedChat: (() => void | Promise) | null = null; - export let onCreateEmbeddedChat: (() => any | Promise) | null = null; + export let onCreateEmbeddedChat: + | ((chat: { + models: string[]; + params: Record; + variables: Record; + }) => any | Promise) + | null = null; export let onSelectEmbeddedChat: ((chatId: string) => void | Promise) | null = null; export let onDeleteEmbeddedChat: ((chatId: string) => void | Promise) | null = null; export let onEmbeddedChatTitle: ((chatId: string, title: string) => void | Promise) | null = @@ -201,6 +224,12 @@ let audioElement: HTMLAudioElement; $: chatContainerId = embedded ? `note-chat-container-${instanceId}` : 'chat-container'; $: messageInputDropzoneId = embedded ? `note-chat-input-dropzone-${instanceId}` : 'chat-pane'; + $: dropzoneId = side ? chatContainerId : messageInputDropzoneId; + const onTemporaryChange = side + ? (value: boolean) => { + if (!processing) temporaryChatEnabled.set(value); + } + : null; const eventTarget = new EventTarget(); @@ -450,6 +479,8 @@ let generating = false; let dragged = false; let generationController = null; + setContext('selectedTerminalId', selectedTerminalId); + setContext('terminalSkills', terminalSkills); const contextCompactions = writable>({}); setContext('contextCompactions', contextCompactions); let compactionChatId = ''; @@ -485,7 +516,7 @@ } ]); if (copy) { - await goto(`/c/${copy.id}`); + if (!embedded) await goto(`/c/${copy.id}`); await refreshChatList(localStorage.token); } } catch (error) { @@ -520,6 +551,10 @@ messages: {}, currentId: null }; + // A side chat hides its parent's context up to here. + let branchPointMessageId: string | null = null; + $: contextOnly = !!branchPointMessageId && history.currentId === branchPointMessageId; + $: inputHistory = contextOnly ? { messages: {}, currentId: null } : history; let taskIds = null; let liveStatus = ''; @@ -537,9 +572,9 @@ } // Chat Input - let prompt = ''; + export let prompt = ''; let chatFiles = []; - let files: any[] = []; + export let files: any[] = []; let terminalContext: TerminalContext | null = null; const askFile = async (instruction: string, file: FilesystemFile) => { if (selectedModels.includes('')) throw new Error($i18n.t('Model not selected')); @@ -610,6 +645,7 @@ } const messages = [...Object.values(history?.messages ?? {})].reverse() as any[]; for (const message of messages) { + if (message.id === branchPointMessageId) break; if ((message.user_id ?? chat?.user_id ?? $user?.id) !== $user?.id) continue; const output = (Array.isArray(message?.output) ? message.output : []) as any[]; const resultCallIds = new Set( @@ -657,6 +693,7 @@ ? createMessagesList(chatHistory, chatHistory.currentId) : Object.values(chatHistory.messages); for (const message of [...messages].reverse()) { + if (message.id === branchPointMessageId) break; if ((message.user_id ?? chat?.user_id ?? $user?.id) !== $user?.id) continue; const pending = getPendingAskUserFromMessage(message); if (pending) return pending; @@ -906,6 +943,7 @@ $: if (embedded && embeddedDraftKey && embeddedDraftKey !== currentDraftKey) { noteChatDebug('embedded draft requested', { embeddedDraftKey }); + if (currentDraftKey) sessionStorage.removeItem(getChatInputKey(currentDraftKey)); currentDraftKey = embeddedDraftKey; initEmbeddedDraft(); } @@ -947,6 +985,7 @@ messageInput?.setText(''); files = []; + if (embeddedDraft) ({ prompt, files } = embeddedDraft); selectedToolIds = []; selectedSkillIds = []; selectedFilterIds = []; @@ -999,11 +1038,24 @@ messageInput?.setText(''); await chatId.set(''); await chatTitle.set(''); + if (embeddedDraft) { + ({ selectedModels, params, history, chatFiles, prompt, files } = embeddedDraft); + branchPointMessageId = history.currentId; + await temporaryChatEnabled.set(embeddedDraft.temporary); + } await setDefaults(); loading = false; await tick(); + if (embeddedDraft) { + ({ prompt, files } = embeddedDraft); + messageInput?.setText(prompt); + } messageInput?.focus({ preventScroll: true }); + if (initialPrompt) { + await tick(); + submitHandler(initialPrompt); + } }; const onSelect = async (e) => { @@ -1027,6 +1079,7 @@ const saveSessionSelectedModels = () => { const selectedModelsString = JSON.stringify(selectedModels); if ( + side || selectedModels.length === 0 || (selectedModels.length === 1 && selectedModels[0] === '') || sessionStorage.selectedModels === selectedModelsString @@ -1038,6 +1091,10 @@ }; const continueOAuthRedirect = async () => { + if (side) { + pendingOAuthTools = []; + return; + } if (pendingOAuthTools.length === 0) { sessionStorage.removeItem('oauthRedirectInProgressToolId'); return; @@ -1119,6 +1176,7 @@ folder: FolderDetails | null = null, signal = chatLoadController.signal ) => { + if (side) return; const terminalId = $selectedTerminalId; const environment = folder ? null : getAgentEnvironment(); loadedAgentEnvironment = null; @@ -1169,7 +1227,7 @@ $: if ($selectedTerminalId !== lastTerminalSkillSelector) { if (terminalContext?.terminalId !== $selectedTerminalId) terminalContext = null; selectedSkillIds = selectedSkillIds.filter((id) => !id.startsWith('terminal:')); - terminalSkills.set([]); + if (!side) terminalSkills.set([]); lastTerminalSkillSelector = $selectedTerminalId; // Folder initialization already requests this exact environment. if (!((loading || !history.currentId) && $selectedFolder?.data?.terminal_id === $selectedTerminalId)) { @@ -1572,6 +1630,7 @@ }); }; $: syncChatRoom($socket, $chatId, $temporaryChatEnabled); + $: if (side && $chatId) openSideChatIds.update((ids) => new Set([...ids, $chatId])); const chatEventHandler = async (event, cb) => { if (isTemporaryChatId(event.chat_id) && event.chat_id !== $chatId) return; @@ -1598,7 +1657,7 @@ } if (event.shared && event.user_id === $user?.id && event.data?.type !== 'chat:messages') return; // The first event can identify a new chat before the HTTP response arrives. - if (!$chatId && event.chat_id && history.messages[event.message_id]) { + if (!side && !$chatId && event.chat_id && history.messages[event.message_id]) { chatId.set(event.chat_id); } const interactionType = event?.data?.type; @@ -1620,7 +1679,8 @@ ) { if (!cb) return; if (event.chat_id !== $chatId) { - cb({ status: 'cancelled', answers: {} }); + if (!embedded && !$openSideChatIds.has(event.chat_id)) + cb({ status: 'cancelled', answers: {} }); return; } if ( @@ -2052,7 +2112,7 @@ loading = true; console.log('mounted'); if (!embedded && appLayout) appLayout.initNewChat = initNewChat; - window.addEventListener('message', onMessageHandler); + if (!side) window.addEventListener('message', onMessageHandler); $socket?.on('events', chatEventHandler); $socket?.on('connect', handleSocketConnect); $socket?.on('disconnect', clearTyping); @@ -2106,7 +2166,7 @@ }); const storageChatInput = sessionStorage.getItem( - `chat-input${chatIdProp ? `-${chatIdProp}` : ''}` + getChatInputKey(chatIdProp || embeddedDraftKey) ); const init = async () => { @@ -2154,6 +2214,15 @@ if (joinedChatId && $socket?.connected) $socket.emit('events:chat', { chat_id: joinedChatId, data: { type: 'leave' } }); joinedChatId = ''; + if (side && $chatId) { + if ($temporaryChatEnabled) + stopTasksByChatId(localStorage.token, $chatId).catch(console.error); + openSideChatIds.update((ids) => { + const next = new Set(ids); + next.delete($chatId); + return next; + }); + } chatId.set(''); chatTitle.set(''); @@ -2945,7 +3014,7 @@ autoScroll = true; // resetInput() must stay last: the selected model's defaults override the draft's selection. - const chatInputPrompt = (await restoreChatInput(retainedDraft ?? sessionStorage.getItem('chat-input'))) + const chatInputPrompt = (await restoreChatInput(retainedDraft ?? sessionStorage.getItem(getChatInputKey()))) ? prompt : null; const previousChatId = $chatId; @@ -3103,6 +3172,7 @@ const id = $chatId; const loadedChat = await getChatById(localStorage.token, id, signal).catch(async (error) => { + if (side && !signal.aborted) toast.error(`${error}`); console.error('[note-chat] getChatById failed', { chatIdProp, activeChatId: $chatId, @@ -3153,7 +3223,7 @@ } const terminalId = chatContent.terminal_id; selectedTerminalId.set(terminalId && isTerminalAvailable(terminalId) ? terminalId : null); - terminalContext = $selectedTerminalId && typeof chatContent.working_directory === 'string' + terminalContext = $selectedTerminalId && $selectedTerminalId === terminalId && typeof chatContent.working_directory === 'string' ? { terminalId: $selectedTerminalId, currentDirectory: chatContent.working_directory } : null; if (selectedModels[0]?.startsWith('agent:')) { @@ -3204,6 +3274,8 @@ sanitizeHistory(history); chatTitle.set(chatContent.title); + branchPointMessageId = parentChatId ? (chatContent.branchPointMessageId ?? null) : null; + if (side) await onEmbeddedChatTitle?.(id, chatContent.title); params = structuredClone(chatContent?.params ?? {}); delete params.note_id; @@ -3287,7 +3359,7 @@ } if (signal.aborted) return; const restored = await restoreChatInput( - sessionStorage.getItem(`chat-input${chatIdProp ? `-${chatIdProp}` : ''}`) + sessionStorage.getItem(getChatInputKey(chatIdProp)) ); if (signal.aborted) return; await setDefaults(restored); @@ -3295,6 +3367,10 @@ loading = false; await tick(); if (signal.aborted) return; + if (embeddedDraft) { + ({ prompt, files } = embeddedDraft); + messageInput?.setText(prompt); + } messageInput?.focus({ preventScroll: true }); } return true; @@ -4111,8 +4187,12 @@ : null; // Empty embedded drafts create their backing chat only when the first message is sent. if (!_chatId) { - if (embedded && onCreateEmbeddedChat) { - const createdChat = await onCreateEmbeddedChat(); + if (embedded && onCreateEmbeddedChat && !$temporaryChatEnabled) { + const createdChat = await onCreateEmbeddedChat({ + models: selectedModels, + params, + variables: chatVariables + }); if (!createdChat?.id) { toast.error($i18n.t('Failed to create chat')); return null; @@ -4792,7 +4872,8 @@ ...(!$temporaryChatEnabled && (!_chatId || ((userMessage?.parentId ?? null) === null && - createMessagesList(_history, responseMessageId).length === 2)) + createMessagesList(_history, responseMessageId).length === 2) || + (branchPointMessageId && userMessage?.parentId === branchPointMessageId)) ? { title_generation: $settings?.title?.auto ?? true, tags_generation: $settings?.autoTags ?? true @@ -5224,7 +5305,9 @@ const MAX_DRAFT_LENGTH = 5000; let saveDraftTimeout: ReturnType | null = null; // chatIdProp is empty for chats started from the home page (URL set via replaceState) - const getDraftChatId = () => chatIdProp || $chatId || null; + const getDraftChatId = () => chatIdProp || $chatId || embeddedDraftKey || null; + const getChatInputKey = (chatId: string | null = null) => + `chat-input${chatId ? `-${chatId}` : ''}`; const getChatInputDraft = () => ({ prompt, @@ -5249,7 +5332,7 @@ } if (draft.prompt !== null && draft.prompt.length < MAX_DRAFT_LENGTH) { - const key = `chat-input${chatId ? `-${chatId}` : ''}`; + const key = getChatInputKey(chatId); const write = () => sessionStorage.setItem(key, JSON.stringify(draft)); if (debounce) { saveDraftTimeout = setTimeout(write, 500); @@ -5257,7 +5340,7 @@ write(); } } else { - sessionStorage.removeItem(`chat-input${chatId ? `-${chatId}` : ''}`); + sessionStorage.removeItem(getChatInputKey(chatId)); } }; @@ -5269,6 +5352,7 @@ }, draft = getChatInputDraft() ) => { + if (side) return; await tick(); saveSessionSelectedModels(); await saveDraft(draft, null, false); @@ -5279,7 +5363,7 @@ if (saveDraftTimeout) { clearTimeout(saveDraftTimeout); } - await sessionStorage.removeItem(`chat-input${chatId ? `-${chatId}` : ''}`); + await sessionStorage.removeItem(getChatInputKey(chatId)); }; const moveChatHandler = async (chatId, folderId) => { @@ -5559,7 +5643,7 @@ {:else} - {#if embedded} + {#if embedded && !side}
@@ -5586,7 +5670,7 @@ {/if}
- {:else} + {:else if !embedded}
{liveStatus}
- {#if ($settings?.landingPageMode === 'chat' && !$selectedFolder) || createMessagesList(history, history.currentId).length > 0} + {#if ($settings?.landingPageMode === 'chat' && !$selectedFolder) || (!contextOnly && createMessagesList(history, history.currentId).length > 0)}