From 834c47ee02b7ed10ead608ddcda7024d203282ca Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 8 Nov 2026 01:28:41 +0900 Subject: [PATCH] refac --- backend/open_webui/main.py | 2 +- backend/open_webui/models/users.py | 1 + src/lib/apis/terminal/recentFolders.ts | 81 ++ src/lib/components/chat/Chat.svelte | 6 +- src/lib/components/chat/ChatTabs.svelte | 27 +- src/lib/components/chat/MessageInput.svelte | 116 ++- .../chat/MessageInput/InputMenu.svelte | 94 +- .../chat/MessageInput/IntegrationsMenu.svelte | 876 +++++++++--------- .../chat/MessageInput/TerminalMenu.svelte | 22 + .../MessageInput/WorkingDirectoryMenu.svelte | 258 ++++++ src/lib/components/chat/Placeholder.svelte | 2 +- .../common/InterfaceSettings.svelte | 29 + src/lib/i18n/locales/en-US/translation.json | 3 + src/lib/stores/index.ts | 1 + 14 files changed, 947 insertions(+), 571 deletions(-) create mode 100644 src/lib/apis/terminal/recentFolders.ts create mode 100644 src/lib/components/chat/MessageInput/WorkingDirectoryMenu.svelte diff --git a/backend/open_webui/main.py b/backend/open_webui/main.py index 2cbc0d7558..ce59cbc4bb 100644 --- a/backend/open_webui/main.py +++ b/backend/open_webui/main.py @@ -1120,7 +1120,7 @@ async def chat_completion( folder_defaults = await get_folder_terminal_defaults(user, form_data.get('folder_id')) if 'terminal_id' not in form_data and folder_defaults.get('terminal_id'): form_data['terminal_id'] = folder_defaults['terminal_id'] - if not requested_directory and form_data.get('terminal_id') == folder_defaults.get('terminal_id'): + if requested_directory is None and form_data.get('terminal_id') == folder_defaults.get('terminal_id'): requested_directory = folder_defaults.get('working_directory') else: requested_directory = None diff --git a/backend/open_webui/models/users.py b/backend/open_webui/models/users.py index b541f8424b..557e9d84f7 100644 --- a/backend/open_webui/models/users.py +++ b/backend/open_webui/models/users.py @@ -81,6 +81,7 @@ class InterfaceSettings(BaseModel): chatFadeStreamingText: bool | None = None richTextInput: bool | None = None showFormattingToolbar: bool | None = None + showInputSelections: bool | None = None insertPromptAsRichText: bool | None = None promptAutocomplete: bool | None = None insertSuggestionPrompt: bool | None = None diff --git a/src/lib/apis/terminal/recentFolders.ts b/src/lib/apis/terminal/recentFolders.ts new file mode 100644 index 0000000000..c41ce8250a --- /dev/null +++ b/src/lib/apis/terminal/recentFolders.ts @@ -0,0 +1,81 @@ +import { + joinTerminalPath, + terminalRequest, + TerminalRequestError, + type TerminalConnection, + type TerminalFileList +} from './index'; +import { computeFileHash } from '$lib/utils/hash'; + +const historyDirectory = (home: string, userId: string) => { + if (!home || !userId || userId === '.' || userId === '..') + throw new Error('Terminal home and a valid user are required'); + return joinTerminalPath(home, `.open-webui/users/${encodeURIComponent(userId)}/folders`); +}; + +export async function loadRecentFolders( + connection: TerminalConnection, + chatId: string | null, + home: string, + userId: string +): Promise { + const directory = historyDirectory(home, userId); + let listing: TerminalFileList; + try { + listing = await terminalRequest( + connection, + chatId, + `/files/list?directory=${encodeURIComponent(directory)}` + ); + } catch (error) { + if (error instanceof TerminalRequestError && error.status === 404) return []; + throw error; + } + const entries = listing.entries + .filter((entry) => entry.type === 'file' && /^[a-f0-9]{64}\.json$/.test(entry.name)) + .sort((a, b) => (b.modified ?? 0) - (a.modified ?? 0)) + .slice(0, 8); + const paths = await Promise.all( + entries.map(async (entry) => { + try { + const result = await terminalRequest<{ content: string }>( + connection, + chatId, + `/files/read?path=${encodeURIComponent(joinTerminalPath(directory, entry.name))}` + ); + const record = JSON.parse(result.content); + return typeof record?.path === 'string' && record.path ? record.path : null; + } catch (error) { + // A missing or partially written record must not hide the rest of the history. + if ( + error instanceof SyntaxError || + (error instanceof TerminalRequestError && error.status === 404) + ) + return null; + throw error; + } + }) + ); + return [...new Set(paths.filter((path): path is string => path !== null))]; +} + +export async function rememberRecentFolder( + connection: TerminalConnection, + chatId: string | null, + home: string, + userId: string, + path: string +): Promise { + if (!path) return; + const normalized = path.replace(/\/+$/, '') || '/'; + const hash = await computeFileHash(new File([normalized], 'folder')); + // Separate records preserve simultaneous selections in different browsers. + await terminalRequest(connection, chatId, '/files/write', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + path: joinTerminalPath(historyDirectory(home, userId), `${hash}.json`), + content: JSON.stringify({ path: normalized }) + }) + }); +} diff --git a/src/lib/components/chat/Chat.svelte b/src/lib/components/chat/Chat.svelte index 9b51350e4b..744a3a7f26 100644 --- a/src/lib/components/chat/Chat.svelte +++ b/src/lib/components/chat/Chat.svelte @@ -5584,7 +5584,7 @@ class=" pb-2 {dragged ? 'z-0' : 'z-10'}" > emitTyping(event.detail)} callActive={!!(bridge?.connected || bridge?.connecting)} @@ -5685,7 +5685,7 @@ {/if}
emitTyping(event.detail)} callActive={!!(bridge?.connected || bridge?.connecting)} @@ -5756,7 +5756,7 @@
`position:absolute;left:${rect.left * 100}%;top:calc(100% * ${rect.top} + ${header}px * var(--app-text-scale, 1));width:${rect.width * 100}%;height:calc(100% * ${rect.height} - ${header}px * var(--app-text-scale, 1));`; - const focusGroup = (id: string) => { + const focusGroup = (id: string, event?: Event) => { + // Tab activation reads the composer's directory before changing the active context. + if (event?.target instanceof Element && event.target.closest('[data-panel-tab]')) return; const group = tabs.groups.find((group) => group.id === id); - if (group?.activeId) tabs = activateTab(tabs, group.activeId); + if (group?.activeId && tabs.activeGroupId !== id) tabs = activateTab(tabs, group.activeId); }; let terminalViews: Record = {}; export const hasTerminals = () => tabs.tabs.some((tab) => tab.kind === 'terminal'); @@ -422,6 +424,11 @@ tabs = activateTab(tabs, mainChatTabId); }; const selectTab = (id: string) => { + const tab = tabs.tabs.find((tab) => tab.id === id); + if (tab?.kind === 'files') { + openFiles(tab.terminalId ?? null); + return; + } tabs = activateTab(tabs, id); showTabs.set(true); }; @@ -434,6 +441,10 @@ }; const openFiles = (selector = $selectedTerminalId, directory?: string) => { if (selector ? !terminalAccessible(selector) : !showFilesTab) return; + directory ??= + terminalContext?.terminalId === selector + ? terminalContext.currentDirectory || undefined + : undefined; const id = selector ? `files:${selector}` : 'files'; openPanel({ id, @@ -442,7 +453,13 @@ terminalId: selector ?? undefined, path: directory }); - if (directory) void fileViews[id]?.browseDirectory?.(directory); + const view = fileViews[id]; + if ( + directory && + view && + view.captureView()?.directory?.replace(/\/+$/, '') !== directory.replace(/\/+$/, '') + ) + void view.browseDirectory(directory); }; const openFile = (path: string, selector: string, page?: number | null) => { if (!terminalAccessible(selector)) return; @@ -1476,8 +1493,8 @@ role="presentation" class="absolute min-h-0 min-w-0 pointer-events-none flex flex-col overflow-hidden" style={paneStyle(positions.groups[group.id])} - on:focusin={() => focusGroup(group.id)} - on:pointerdown={() => focusGroup(group.id)} + on:focusin={(event) => focusGroup(group.id, event)} + on:pointerdown={(event) => focusGroup(group.id, event)} > {@render tabBar(group)}
diff --git a/src/lib/components/chat/MessageInput.svelte b/src/lib/components/chat/MessageInput.svelte index 1b439c350d..1bfafc81fc 100644 --- a/src/lib/components/chat/MessageInput.svelte +++ b/src/lib/components/chat/MessageInput.svelte @@ -116,7 +116,6 @@ import Terminal from '../icons/Terminal.svelte'; import IntegrationsMenu from './MessageInput/IntegrationsMenu.svelte'; import TerminalMenu from './MessageInput/TerminalMenu.svelte'; - import Component from '../icons/Component.svelte'; import PlusAlt from '../icons/PlusAlt.svelte'; import Dropdown from '../common/Dropdown.svelte'; @@ -317,10 +316,12 @@ let copiedStatusChatId = false; let selectedValvesType = 'tool'; // 'tool' or 'function' let selectedValvesItemId = null; - let integrationsMenuCloseOnOutsideClick = true; + let showInputMenu = false; + let inputMenuTab = ''; + let inputMenuCloseOnOutsideClick = true; $: if (!showValvesModal) { - integrationsMenuCloseOnOutsideClick = true; + inputMenuCloseOnOutsideClick = true; } let chatInputDraft: any; @@ -936,6 +937,8 @@ .map((id) => ($models.find((model) => model.id === id) || {})?.filters ?? []) .reduce((acc, filters) => acc.filter((f1) => filters.some((f2) => f2.id === f1.id))); + $: showInputSelections = $settings?.showInputSelections ?? false; + let showToolsButton = false; $: showToolsButton = ($tools ?? []).length > 0 || ($toolServers ?? []).length > 0; @@ -1945,7 +1948,7 @@ await tick(); }} on:close={() => { - integrationsMenuCloseOnOutsideClick = true; + inputMenuCloseOnOutsideClick = true; }} /> @@ -2557,7 +2560,9 @@
+ + + {#if showWebSearchButton || showImageGenerationButton || showCodeInterpreterButton || showToolsButton || showSkillsButton || (toggleFilters && toggleFilters.length > 0)} + oauthRedirectHandler(tool, chatInputDraft)} + {onWebSearchToggle} + onShowValves={(e) => { + const { type, id } = e; + selectedValvesType = type; + selectedValvesItemId = id; + showValvesModal = true; + inputMenuCloseOnOutsideClick = false; + }} + /> + {/if} + - {#if showWebSearchButton || showImageGenerationButton || showCodeInterpreterButton || showToolsButton || showSkillsButton || (toggleFilters && toggleFilters.length > 0)} -
- - oauthRedirectHandler(tool, chatInputDraft)} - {onWebSearchToggle} - closeOnOutsideClick={integrationsMenuCloseOnOutsideClick} - onShowValves={(e) => { - const { type, id } = e; - selectedValvesType = type; - selectedValvesItemId = id; - showValvesModal = true; - integrationsMenuCloseOnOutsideClick = false; - }} - onClose={async () => { - await tick(); - - if (!$mobile) { - const chatInput = document.getElementById(inputId); - chatInput?.focus(); - } - }} - > - - - {/if} + {#if hasChatVariables} @@ -2721,7 +2713,7 @@ {/if}
- {#if (selectedToolIds ?? []).length > 0 && $visibleControls['chat.selected_tools']} + {#if showInputSelections && (selectedToolIds ?? []).length > 0 && $visibleControls['chat.selected_tools']} {/if} - {#if (selectedSkillIds ?? []).length > 0 && $visibleControls['chat.selected_skills']} + {#if showInputSelections && (selectedSkillIds ?? []).length > 0 && $visibleControls['chat.selected_skills']} f.id === filterId)} - {#if filter && $visibleControls['chat.selected_filters']} + {#if showInputSelections && filter && $visibleControls['chat.selected_filters']} - {/if} + +
+ {:else if tab === 'attachments'} +
+ +
{#if $visibleControls['chat.attach_webpage']} { - tab = ''; + tab = 'attachments'; }} > @@ -685,7 +692,7 @@ role="menuitem" class="flex w-full shrink-0 justify-between gap-2 items-center h-[1.6875rem] px-2 text-[0.8125rem] font-normal select-none cursor-pointer rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40" on:click={() => { - tab = ''; + tab = 'attachments'; }} > @@ -705,7 +712,7 @@ role="menuitem" class="flex w-full shrink-0 justify-between gap-2 items-center h-[1.6875rem] px-2 text-[0.8125rem] font-normal select-none cursor-pointer rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40" on:click={() => { - tab = ''; + tab = 'attachments'; }} > @@ -725,7 +732,7 @@ role="menuitem" class="flex w-full shrink-0 justify-between gap-2 items-center h-[1.6875rem] px-2 text-[0.8125rem] font-normal select-none cursor-pointer rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40" on:click={() => { - tab = ''; + tab = 'attachments'; }} > @@ -745,7 +752,7 @@ role="menuitem" class="flex w-full justify-between gap-2 items-center h-[1.6875rem] px-2 text-[0.8125rem] font-normal select-none cursor-pointer rounded-xl hover:bg-gray-50/40 dark:hover:bg-gray-800/40" on:click={() => { - tab = ''; + tab = 'attachments'; }} > @@ -790,6 +797,7 @@ {/if}
{/if} +
diff --git a/src/lib/components/chat/MessageInput/IntegrationsMenu.svelte b/src/lib/components/chat/MessageInput/IntegrationsMenu.svelte index 34d017c694..3bdf43e904 100644 --- a/src/lib/components/chat/MessageInput/IntegrationsMenu.svelte +++ b/src/lib/components/chat/MessageInput/IntegrationsMenu.svelte @@ -1,7 +1,7 @@ - { - if (state === false) { - toolQuery = ''; - skillQuery = ''; - onClose(); - } - }} -> - - - -
- - {#if tab === ''} -
+
+ {#if tools} + {#if Object.keys(tools).length > 0} + - {/if} - - {#if skills && Object.keys(skills).length > 0} - - {/if} - {:else} -
- +
+
+ {$i18n.t('Tools')} + {Object.keys(tools).length}
- {/if} - {#if toggleFilters && toggleFilters.length > 0} - {#each toggleFilters.sort( (a, b) => a.name.localeCompare( b.name, undefined, { sensitivity: 'base' } ) ) as filter, filterIdx (filter.id)} - - - + {#if skills && Object.keys(skills).length > 0} + - +
+
+ {$i18n.t('Skills')} + {Object.keys(skills).length} +
+ +
+ +
+
+ + {/if} + {:else} +
+ +
+ {/if} + + {#if toggleFilters && toggleFilters.length > 0} + {#each toggleFilters.sort( (a, b) => a.name.localeCompare( b.name, undefined, { sensitivity: 'base' } ) ) as filter, filterIdx (filter.id)} + + - {:else if tab === 'tools' && tools} -
- + - - -
- {#if toolIds.length === 0} -
{$i18n.t('No tools found')}
- {:else} -
- {#each toolIds as toolId} - - {/each} -
- {/if} -
-
- {:else if tab === 'skills' && skills} -
- - - - -
- {#if skillIds.length === 0} -
{$i18n.t('No skills found')}
- {:else} -
- {#each skillIds as skillId} + {#if filter?.has_user_valves && ($user?.role === 'admin' || ($user?.permissions?.chat?.valves ?? true))} +
+ - {/each} +
{/if} + +
+ +
+ + {/each} + {/if} + + {#if showWebSearchButton} + + + + {/if} + + {#if showImageGenerationButton} + + + + {/if} + + {#if showCodeInterpreterButton} + + + + {/if} +
+{:else if tab === 'tools' && tools} +
+ + + + +
+ {#if toolIds.length === 0} +
{$i18n.t('No tools found')}
+ {:else} +
+ {#each toolIds as toolId} + + {/each}
{/if} - +
- +{:else if tab === 'skills' && skills} +
+ + + + +
+ {#if skillIds.length === 0} +
{$i18n.t('No skills found')}
+ {:else} +
+ {#each skillIds as skillId} + + {/each} +
+ {/if} +
+
+{/if} diff --git a/src/lib/components/chat/MessageInput/TerminalMenu.svelte b/src/lib/components/chat/MessageInput/TerminalMenu.svelte index 887f03f543..d82d6de0bc 100644 --- a/src/lib/components/chat/MessageInput/TerminalMenu.svelte +++ b/src/lib/components/chat/MessageInput/TerminalMenu.svelte @@ -3,6 +3,8 @@ import { resolveTerminalConnection, type TerminalConnection } from '$lib/apis/terminal'; import TerminalSystemInfoModal from '../TerminalSystemInfoModal.svelte'; import Activity from '$lib/components/icons/Activity.svelte'; + import WorkingDirectoryMenu from './WorkingDirectoryMenu.svelte'; + import type { TerminalContext } from '$lib/types'; import { chatId as activeChatId, @@ -27,6 +29,8 @@ export let show = false; export let disabled = false; + export let chatId: string | null = null; + export let terminalContext: TerminalContext | null = null; const chatContext = (terminal: any) => terminal?.contexts?.chat ?? {}; @@ -124,6 +128,12 @@ $: selectedSystemTerminal = systemTerminals.find((t) => t.id === $selectedTerminalId); $: selectedDirectTerminal = directTerminals.find((t) => t.url === $selectedTerminalId); + $: folderConnection = resolveTerminalConnection( + $selectedTerminalId, + systemTerminals, + directTerminals, + '' + ); $: selectedDevice = !!selectedSystemTerminal && isDevice(selectedSystemTerminal); $: selectedLabel = @@ -428,3 +438,15 @@ /> {/key} {/if} + +{#if folderConnection && (chatContext(selectedSystemTerminal)?.context_id !== 'chat_id' || isSavedChatId(chatId))} + {#key `${$user?.id}:${folderConnection.selector}:${chatId ?? ''}`} + + {/key} +{/if} diff --git a/src/lib/components/chat/MessageInput/WorkingDirectoryMenu.svelte b/src/lib/components/chat/MessageInput/WorkingDirectoryMenu.svelte new file mode 100644 index 0000000000..b08e195d4a --- /dev/null +++ b/src/lib/components/chat/MessageInput/WorkingDirectoryMenu.svelte @@ -0,0 +1,258 @@ + + +
+ { + search = ''; + if (open) void refreshRecentFolders(); + }} + > + + + +
+ + +
+ + {#if options.length > 0} +
+ {$i18n.t('Recently Used')} +
+ {#if historyError} +
+ {historyError} +
+ {/if} +
+ {#each options as path} + {@const selected = !!directory && normalize(directory) === path} + + {/each} +
+ {/if} +
+ +
+
+
+
+ +{#if showPicker} + +
+
+ {$i18n.t('Choose working directory')} + +
+
+ +
+
+
+{/if} diff --git a/src/lib/components/chat/Placeholder.svelte b/src/lib/components/chat/Placeholder.svelte index b2a3f4c8d7..db8c2d99e7 100644 --- a/src/lib/components/chat/Placeholder.svelte +++ b/src/lib/components/chat/Placeholder.svelte @@ -260,7 +260,7 @@ {#if !($selectedFolder && folderReadOnly)}
+
+
+ + +
+ { + saveSettings({ showInputSelections }); + }} + /> +
+
+

+ {$i18n.t('settings.personal.interface.showInputSelections.description')} +

+
+ {#if $visibleControls['settings.rich_text_input']}
diff --git a/src/lib/i18n/locales/en-US/translation.json b/src/lib/i18n/locales/en-US/translation.json index b4ad5683fa..4b8706d382 100644 --- a/src/lib/i18n/locales/en-US/translation.json +++ b/src/lib/i18n/locales/en-US/translation.json @@ -129,6 +129,7 @@ "Active Users": "", "Activity": "", "Add": "", + "Add Context": "Add Context", "Add a comment…": "", "Add a model ID": "", "Add a preference, fact, or instruction about you": "", @@ -3800,6 +3801,8 @@ "settings.personal.interface.showFilesOnTerminalSelect.label": "Show Files on Terminal Select", "settings.personal.interface.showFormattingToolbar.description": "Show formatting controls in the rich text composer.", "settings.personal.interface.showFormattingToolbar.label": "Show Formatting Toolbar", + "settings.personal.interface.showInputSelections.description": "Show selected tools, skills, filters, and capabilities beside the + menu. Hiding them preserves your selections.", + "settings.personal.interface.showInputSelections.label": "Show Input Selections", "settings.personal.interface.stylizedPdfExport.description": "Use styled formatting when exporting chats to PDF.", "settings.personal.interface.stylizedPdfExport.label": "Stylized PDF Export", "settings.personal.interface.temporaryChatByDefault.description": "Start new chats as temporary unless changed.", diff --git a/src/lib/stores/index.ts b/src/lib/stores/index.ts index cbbe562002..822dd811a3 100644 --- a/src/lib/stores/index.ts +++ b/src/lib/stores/index.ts @@ -296,6 +296,7 @@ type Settings = { responseAutoCopy?: any; richTextInput?: boolean; showFormattingToolbar?: boolean; + showInputSelections?: boolean; params?: any; userLocation?: any; webSearch?: any;