This commit is contained in:
Timothy Jaeryang Baek committed 2026-11-24 19:01:44 +04:00
1 parent 00cb737759
commit e1855444ae
15 files changed
+432 -157

No files matched your search

+6 -3
View File
@@ -2762,9 +2762,6 @@ async def process_chat_payload(request, form_data, user, metadata, model):
tool_function = await make_tool_function(client, tool_spec['name'])
tool_name = re.sub(r'[^a-zA-Z0-9_-]', '_', f'{server_id}_{tool_spec["name"]}')
# Providers reject tool names over 64 characters
if len(tool_name) > 64:
tool_name = f'{tool_name[:55]}_{hashlib.sha256(tool_name.encode()).hexdigest()[:8]}'
mcp_tools_dict[tool_name] = {
'spec': {
@@ -2893,6 +2890,12 @@ async def process_chat_payload(request, form_data, user, metadata, model):
await filter_user_terminal_tools(request, user, tools_dict, metadata, extra_params)
# Providers reject tool names over 64 characters
for name in [name for name in tools_dict if len(name) > 64]:
tool = tools_dict.pop(name)
name = f'{name[:55]}_{hashlib.sha256(name.encode()).hexdigest()[:8]}'
tools_dict[name] = {**tool, 'spec': {**tool['spec'], 'name': name}}
if tools_dict:
# Always store resolved tools in metadata so downstream consumers
# (e.g. pipe functions) can access all tools including MCP and builtins.
@@ -349,7 +349,9 @@
<slot name="toolbar" slot="toolbar" />
</DocxPreview>
{:else if excelWorkbook !== null}
<ExcelPreview workbook={excelWorkbook} bind:selectedSheet={selectedExcelSheet} />
<ExcelPreview workbook={excelWorkbook} bind:selectedSheet={selectedExcelSheet}>
<slot name="toolbar" slot="toolbar" />
</ExcelPreview>
{:else if fileOfficeSlides !== null && fileOfficeSlides.length > 0}
<PptxPreview
bind:this={pptxPreviewRef}
@@ -357,7 +359,9 @@
bind:currentSlide
{targetPage}
className="w-full h-full"
/>
>
<slot name="toolbar" slot="toolbar" />
</PptxPreview>
{:else if fileContent !== null}
{#if searchTarget || showRaw}
<div class="absolute inset-0">
@@ -544,6 +548,7 @@
/>
</svg>
</button>
<slot name="toolbar" />
</div>
{/if}
</div>
+18 -2
View File
@@ -22,7 +22,8 @@
dayjs.extend(duration);
dayjs.extend(relativeTime);
import { onMount, tick, getContext, createEventDispatcher } from 'svelte';
import { onDestroy, onMount, tick, getContext, createEventDispatcher } from 'svelte';
import { writable } from 'svelte/store';
import type { Writable } from 'svelte/store';
import { createPicker, getAuthToken } from '$lib/utils/google-drive-picker';
@@ -41,6 +42,7 @@
skills,
machines,
user as _user,
embed,
showTabs,
showSettings,
showFileNavDir,
@@ -1165,6 +1167,14 @@
}
};
// A file's tab offers its context only while the file is still here to be sent
const attachedFiles = writable<any[]>([]);
$: attachedFiles.set(files);
onDestroy(() => {
attachedFiles.set([]);
if ($embed?.file?.attachedFiles === attachedFiles) embed.set(null);
});
const uploadFileHandler = async (file, process = true, itemData = {}) => {
if ($_user?.role !== 'admin' && !($_user?.permissions?.chat?.file_upload ?? true)) {
toast.error($i18n.t('You do not have permission to upload files.'));
@@ -1191,7 +1201,7 @@
error: '',
itemId: tempItemId,
// Stamp the user's default upload mode so the sent payload carries it;
// the per-file toggle in FileItemModal can still override it afterwards.
// the per-file toggle in FileContextSwitch can still override it afterwards.
...($settings?.defaultUploadContext === 'full' ? { context: 'full' } : {}),
...itemData
};
@@ -2410,6 +2420,7 @@
</div>
</div>
{:else}
<!-- A chat tab that has not started has no tab of its own to open beside -->
<FileItem
item={file}
name={file.name}
@@ -2420,6 +2431,11 @@
edit={true}
small={true}
modal={['file', 'collection'].includes(file?.type)}
chatId={embedded && !chatId ? null : chatId}
tabOptions={{
attachedFiles,
onAttachmentChange: () => (files = files)
}}
on:dismiss={async () => {
// Remove from UI state
files.splice(fileIdx, 1);
@@ -7,11 +7,10 @@
import { toast } from 'svelte-sonner';
import { tick, getContext, onMount } from 'svelte';
import { embed, settings, showEmbeds, showTabs } from '$lib/stores';
import { settings } from '$lib/stores';
import { user as _user } from '$lib/stores';
import {
copyToClipboard as _copyToClipboard,
decodeString,
formatMessageTimestamp,
formatMessageTimestampFull,
isRasterImageContentType
@@ -101,29 +100,6 @@
}
};
const getFileContent = (file) => file.file?.data?.content ?? file.content ?? '';
// A saved view of a chat has no tabs to open a file in
const canOpenInTab = (file) =>
!readOnly &&
!compactPreview &&
((file.type === 'file' && !!file.id) || (!!file.url && !!getFileContent(file)));
// An attached file opens beside the chat, as a cited one does
const openFileInTab = (file) => {
showTabs.set(true);
showEmbeds.set(true);
embed.set({
file: {
id: file.type === 'file' ? file.id : undefined,
page: null,
passages: [],
content: getFileContent(file)
},
url: file.url,
title: decodeString(file.name ?? ''),
chatId
});
};
const editMessageHandler = async () => {
edit = true;
editedContent = message?.content ?? '';
@@ -244,6 +220,7 @@
{#if file.type === 'image' || isRasterImageContentType(file?.content_type)}
<Image src={fileUrl} imageClassName=" max-h-96 rounded-lg" />
{:else}
<!-- A saved view of a chat has no tabs to open a file in -->
<FileItem
item={file}
url={file.url}
@@ -251,7 +228,7 @@
type={file.type}
size={file?.size}
small={true}
onOpen={canOpenInTab(file) ? () => openFileInTab(file) : null}
chatId={readOnly || compactPreview ? null : chatId}
/>
{/if}
</div>
@@ -1,17 +1,26 @@
<script lang="ts">
import { getContext } from 'svelte';
import { getContext, onDestroy } from 'svelte';
import { writable } from 'svelte/store';
import { goto } from '$app/navigation';
import { toast } from 'svelte-sonner';
import { v4 as uuidv4 } from 'uuid';
import type { AppLayoutContext } from '$lib/types';
import { config, selectedFolder, settings, user } from '$lib/stores';
import {
chatId,
config,
embed,
selectedFolder,
settings,
showEmbeds,
showTabs,
user
} from '$lib/stores';
import { updateFolderDetails, type FolderDetails } from '$lib/stores/folderStates';
import { getFolderById, updateFolderById } from '$lib/apis/folders';
import { uploadFile } from '$lib/apis/files';
import { decodeString, formatFileSize } from '$lib/utils';
import FileItemModal from '$lib/components/common/FileItemModal.svelte';
import FilesOverlay from '$lib/components/chat/MessageInput/FilesOverlay.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import ChatBubble from '$lib/components/icons/ChatBubble.svelte';
@@ -48,11 +57,6 @@
let dragging = false;
let inputElement: HTMLInputElement;
let showItemModal = false;
let editing: Item | null = null;
let editingKey = '';
let editingContext: string | undefined;
$: files = (folder?.data?.files ?? []) as Item[];
/** Everything shown, saved first, so the count in the toolbar matches the list. */
export let items: Item[] = [];
@@ -205,20 +209,18 @@
for (const file of Array.from(list ?? [])) void uploadOne(file);
}
// The preview can switch a file between focused retrieval and its full text; that choice is saved on close.
// Notes, knowledge bases and chats open as their own page, in a tab beside the folder like chats do.
// Notes and chats open as their own page, in a tab beside the folder like chats do.
const pageOf = (item: Item) =>
!item.id
? null
: item.type === 'collection'
? `/workspace/knowledge/${item.id}`
: item.type === 'note'
? `/notes/${item.id}`
: item.type === 'chat'
? `/c/${item.id}`
: null;
: item.type === 'note'
? `/notes/${item.id}`
: item.type === 'chat'
? `/c/${item.id}`
: null;
const canOpen = (item: Item) =>
item.status !== 'uploading' && (!!pageOf(item) || (item.type ?? 'file') === 'file');
item.status !== 'uploading' &&
(!!pageOf(item) || ['file', 'collection'].includes(item.type ?? 'file'));
function open(item: Item) {
if (!canOpen(item)) return;
@@ -228,26 +230,62 @@
else void goto(href);
return;
}
editing = { ...item };
editingKey = keyOf(item);
editingContext = item.context;
showItemModal = true;
if (item.id) openFile(item);
}
$: if (!showItemModal && editing) {
const item = editing;
editing = null;
if (!readOnly && item.context !== editingContext && editingKey === keyOf(item)) {
void save((current) =>
current.map((entry) =>
sameEntry(entry, item)
? item.context
? { ...entry, context: item.context }
: (({ context, ...rest }) => rest)(entry)
: entry
)
);
}
// A file's tab can switch it between focused retrieval and its full text while the folder is shown.
let openedFiles: { folderId?: string; item: Item }[] = [];
const attachedFiles = writable<Item[]>([]);
$: attachedFiles.set(
readOnly
? []
: openedFiles
.filter(
(file) =>
file.folderId === folder?.id && files.some((entry) => sameEntry(entry, file.item))
)
.map((file) => file.item)
);
onDestroy(() => {
attachedFiles.set([]);
if ($embed?.file?.attachedFiles === attachedFiles) embed.set(null);
});
function openFile(item: Item) {
const attachment = { ...item, type: item.type ?? 'file' };
openedFiles = [
...openedFiles.filter((file) => !sameEntry(file.item, item)),
{ folderId: folder?.id, item: attachment }
];
showTabs.set(true);
showEmbeds.set(true);
embed.set({
file: {
id: item.type === 'collection' ? undefined : item.id,
knowledgeId: item.type === 'collection' ? item.id : null,
page: null,
passages: [],
content: item.file?.data?.content ?? '',
attachment,
attachedFiles,
onAttachmentChange: () => {
const { context } = attachment as Item;
void save((current) =>
current.map((entry) =>
sameEntry(entry, attachment)
? context
? { ...entry, context }
: (({ context, ...rest }) => rest)(entry)
: entry
)
);
}
},
key: item.id,
url: item.url,
title: decodeString(item.name ?? ''),
chatId: $chatId
});
}
const typeLabel = (item: Item) =>
@@ -264,10 +302,6 @@
const isFiles = (event: DragEvent) => event.dataTransfer?.types.includes('Files') ?? false;
</script>
{#if showItemModal && editing}
<FileItemModal bind:show={showItemModal} bind:item={editing} edit={!readOnly} />
{/if}
<input
bind:this={inputElement}
type="file"
+14 -9
View File
@@ -113,6 +113,8 @@
import GitBar from './Tabs/GitBar.svelte';
import Artifacts from './Artifacts.svelte';
import Embeds from './Tabs/Embeds.svelte';
import Database from '$lib/components/icons/Database.svelte';
import Knowledge from './Tabs/Knowledge.svelte';
import ChatTab from './Tabs/ChatTab.svelte';
import PyodideFileNav from './PyodideFileNav.svelte';
import ConfirmDialog from '../common/ConfirmDialog.svelte';
@@ -932,16 +934,13 @@
const sourceTabId = embedSourceTab?.id;
const sourceGroup = tabs.groups.find((group) => group.tabIds.some((id) => id === sourceTabId));
// Each cited source has its own tab; citing it again shows the new passages there.
const id = `preview:${$embed.file?.id ?? $embed.url}`;
const id = `preview:${$embed.file?.id ?? $embed.key ?? $embed.url}`;
tabs = {
...tabs,
tabs: tabs.tabs.map((tab) => (tab.id === id ? { ...tab, embed: $embed } : tab))
};
// A file cited in the main chat opens beside it, so the answer stays readable.
openPanel(
{ id, kind: 'preview', label: $i18n.t('Preview'), embed: $embed },
!sourceGroup && !!$embed.file
);
// A source cited in the main chat opens beside it, so the answer stays readable.
openPanel({ id, kind: 'preview', label: $i18n.t('Preview'), embed: $embed }, !sourceGroup);
// A source cited in a chat tab opens in that tab's group, so the main chat stays in view.
if (sourceGroup) tabs = moveTabToGroup(tabs, id, sourceGroup.id);
};
@@ -1488,8 +1487,8 @@
// A chat's artifacts or Overview tab names the chat it belongs to.
$: tabLabel = (tab: Tab) => {
if (tab.kind === 'terminal') return terminalTitles[tab.sessionId ?? ''] || tab.label;
// A cited file is named like any other file tab.
if (tab.kind === 'preview' && tab.embed?.file) return tab.embed.title || tab.label;
// A cited file or web page names its own tab.
if (tab.kind === 'preview') return tab.embed?.title || tab.label;
const source =
(tab.kind === 'artifacts' || tab.kind === 'overview') &&
tab.sourceTabId &&
@@ -2143,7 +2142,11 @@
on:close={() => closeTab(tab.id)}
/>
{:else if tab.kind === 'preview'}
<Embeds embed={tab.embed} overlay={isDragging} />
{#if tab.embed?.file?.knowledgeId}
<Knowledge embed={tab.embed} chatId={chatId ?? ''} />
{:else}
<Embeds embed={tab.embed} overlay={isDragging} />
{/if}
{:else if tab.kind === 'artifacts'}
{@const source = tabs.tabs.find((item) => item.id === tab.sourceTabId)}
<Artifacts
@@ -2504,6 +2507,8 @@
{:else}
<Icon name="folder" size={14} />
{/if}
{:else if tab.kind === 'preview' && tab.embed?.file?.knowledgeId}
<Database className="size-3.5 shrink-0" />
{:else if tab.kind === 'file' || (tab.kind === 'preview' && tab.embed?.file)}
<Icon name={fileIconName(tabLabel(tab))} size={14} strokeWidth={1.4} />
{:else if tab.kind === 'terminal'}
+55 -11
View File
@@ -1,7 +1,9 @@
<script lang="ts">
import { getContext, onDestroy } from 'svelte';
import { readable, type Readable } from 'svelte/store';
import { WEBUI_API_BASE_URL } from '$lib/constants';
import { getFileById, getFileContentById } from '$lib/apis/files';
import { safeLinkUrl } from '$lib/utils';
import { quoteLines, quoteMarks } from '$lib/utils/comments/highlights';
import FullHeightIframe from '$lib/components/common/FullHeightIframe.svelte';
@@ -10,6 +12,8 @@
import FilePreview from '$lib/components/chat/FileNav/FilePreview.svelte';
import Markdown from '$lib/components/chat/Messages/Markdown.svelte';
import Tooltip from '$lib/components/common/Tooltip.svelte';
import FileContextSwitch from '$lib/components/common/FileContextSwitch.svelte';
import OpenFileLink from './OpenFileLink.svelte';
import RelevanceBadge from '$lib/components/chat/Messages/Citations/RelevanceBadge.svelte';
// A cited or attached upload, shown at its cited page. PDFs also mark the cited text.
@@ -38,6 +42,8 @@
const MODEL_EXTS = new Set(['glb', 'gltf', 'stl', 'obj', 'ply']);
const EXCEL_EXTS = new Set(['xlsx', 'xls']);
const LAID_OUT_EXTS = new Set(['pdf', 'docx', 'pptx', ...EXCEL_EXTS]);
// Documents whose text is only what was extracted; code and plain text are their text
const EXTRACTED_EXTS = new Set('doc ppt odt ods odp rtf epub msg'.split(' '));
// Text the preview draws as something other than its lines
const DRAWN_TEXT_EXTS = new Set(
'md markdown mdx csv tsv html htm json jsonc jsonl json5 svg ipynb'.split(' ')
@@ -89,6 +95,8 @@
if (fileId === id) fileLoading = false;
}
};
// Images and media are set at once, so this runs before what is drawn is decided
$: if ((embed?.file?.id ?? '') !== fileId) loadFile(embed?.file?.id ?? '', fileExt);
$: hasPreview =
fileDocxData ||
fileSqliteData ||
@@ -99,7 +107,6 @@
fileContent !== null ||
fileOfficeSlides ||
excelWorkbook;
$: if ((embed?.file?.id ?? '') !== fileId) loadFile(embed?.file?.id ?? '', fileExt);
$: isPlainText = !DRAWN_TEXT_EXTS.has(fileExt) && !LAID_OUT_EXTS.has(fileExt);
// Code and plain text are drawn as they are, so the lines are matched as they are
const textLines = (passage: string) => [
@@ -178,6 +185,24 @@
const NO_QUOTES: string[] = [];
$: shownQuotes = showQuotes ? fileQuotes : NO_QUOTES;
$: if (!showQuotes) hoveredText = null;
// A web page has no file of its own, so its address is opened
$: openUrl = fileId
? `${WEBUI_API_BASE_URL}/files/${fileId}/content`
: safeLinkUrl(embed?.url ?? '');
// A file still in the composer can have how it is sent changed
const NO_FILES: Readable<any[]> = readable([]);
let attachedFiles = NO_FILES;
$: attachedFiles = embed?.file?.attachedFiles ?? NO_FILES;
$: attachment = $attachedFiles.includes(embed?.file?.attachment) ? embed.file.attachment : null;
$: openLabel = fileId ? $i18n.t('Open file') : $i18n.t('Open link');
// These previews have a bar of their own, which the actions join
$: hasBar =
fileData ||
fileDocxData ||
fileImageUrl ||
excelWorkbook ||
fileOfficeSlides?.length ||
(fileContent && fileExt === 'svg');
let fileSource: any = null;
$: if (embed?.file !== fileSource) {
fileSource = embed?.file ?? null;
@@ -307,6 +332,12 @@
</button>
</Tooltip>
{/if}
{#if attachment}
<div class="px-1.5">
<FileContextSwitch item={attachment} onChange={embed.file.onAttachmentChange} />
</div>
{/if}
{#if openUrl}<OpenFileLink href={openUrl} label={openLabel} />{/if}
</svelte:fragment>
</PdfPagesPreview>
{/key}
@@ -372,6 +403,12 @@
</button>
</Tooltip>
{/if}
{#if attachment}
<div class="px-1.5">
<FileContextSwitch item={attachment} onChange={embed.file.onAttachmentChange} />
</div>
{/if}
{#if openUrl}<OpenFileLink href={openUrl} label={openLabel} />{/if}
</svelte:fragment>
</FilePreview>
</div>
@@ -385,30 +422,37 @@
/>
{:else if !fileLoading && (fileText || fileSource?.content)}
<FilePreview
selectedFile={`${fileName}.md`}
selectedFile={isPlainText && !EXTRACTED_EXTS.has(fileExt) && !/^https?:/.test(fileName)
? fileName
: `${fileName}.md`}
fileContent={fileText || fileSource.content}
wrapLines={true}
readOnly={true}
/>
{:else}
<div
class="flex h-full flex-col items-center justify-center gap-1 text-xs text-base-500 dark:text-base-400"
class="flex h-full items-center justify-center text-xs text-base-500 dark:text-base-400"
>
{#if fileLoading}
<Spinner className="size-3.5 text-base-400 dark:text-base-500" />
{:else}
{$i18n.t('Preview failed')}
{#if fileId}
<a
class="underline"
href={`${WEBUI_API_BASE_URL}/files/${fileId}/content`}
target="_blank"
rel="noopener noreferrer">{$i18n.t('Open file')}</a
>
{/if}
{/if}
</div>
{/if}
{#if (openUrl || attachment) && !hasBar && !fileLoading}
<!-- Styled as the bars of the other previews are -->
<div
class="absolute bottom-3 left-1/2 z-10 flex -translate-x-1/2 items-center rounded-lg border border-base-200/60 bg-base-0/90 px-1 py-0.5 text-base-500 shadow-lg backdrop-blur-sm dark:border-base-700/60 dark:bg-base-850/90 dark:text-base-400"
>
{#if attachment}
<div class="px-1.5">
<FileContextSwitch item={attachment} onChange={embed.file.onAttachmentChange} />
</div>
{/if}
{#if openUrl}<OpenFileLink href={openUrl} label={openLabel} />{/if}
</div>
{/if}
{#if hoveredText}
{@const hasRelevance = typeof hoveredText.distance === 'number'}
{@const hasLabel = hoveredText.page || hasRelevance}
@@ -0,0 +1,104 @@
<script lang="ts">
import { getContext, onDestroy, onMount } from 'svelte';
import { readable, type Readable } from 'svelte/store';
import { getKnowledgeById } from '$lib/apis/knowledge';
import { embed as openedEmbed, showEmbeds, showTabs } from '$lib/stores';
import FileContextSwitch from '$lib/components/common/FileContextSwitch.svelte';
import Spinner from '$lib/components/common/Spinner.svelte';
import Search from '$lib/components/icons/Search.svelte';
import Files from '$lib/components/workspace/Knowledge/KnowledgeBase/Files.svelte';
import {
fileName,
type KnowledgeFile
} from '$lib/components/workspace/Knowledge/KnowledgeBase/types';
const i18n: any = getContext('i18n');
/** The knowledge base this tab browses. */
export let embed: any;
/** The chat the tab is in now; one opened before its chat was saved has none of its own. */
export let chatId = '';
let knowledge: any = null;
let loading = true;
let selectedFileId: string | null = null;
let query = '';
let inputQuery = '';
let debounce: ReturnType<typeof setTimeout>;
$: external = knowledge?.meta?.source === 'external';
// Still attached, so how it is sent can be changed
const NO_FILES: Readable<any[]> = readable([]);
let attachedFiles = NO_FILES;
$: attachedFiles = embed.file.attachedFiles ?? NO_FILES;
$: attachment = $attachedFiles.includes(embed.file.attachment) ? embed.file.attachment : null;
// A file opens in its own tab, as cited and attached files do
const open = (file: KnowledgeFile) => {
selectedFileId = file.id ?? null;
showTabs.set(true);
showEmbeds.set(true);
openedEmbed.set({
file: { id: file.id, page: null, passages: [], content: '' },
title: fileName(file),
chatId: embed.chatId || chatId
});
};
onMount(async () => {
knowledge = await getKnowledgeById(localStorage.token, embed.file.knowledgeId).catch(
() => null
);
loading = false;
});
onDestroy(() => clearTimeout(debounce));
</script>
<div class="flex h-full w-full flex-col">
<div class="flex h-7 shrink-0 items-center gap-1 px-2 text-xs text-base-500 dark:text-base-400">
{#if knowledge && !external}
<Search className="mx-1 size-3.5 shrink-0" />
<input
aria-label={$i18n.t('Search Files')}
placeholder={$i18n.t('Search Files')}
bind:value={inputQuery}
class="h-7 min-w-0 flex-1 bg-transparent px-1 outline-none"
on:input={() => {
clearTimeout(debounce);
debounce = setTimeout(() => (query = inputQuery.trim()), 300);
}}
/>
{:else}
<span class="flex-1"></span>
{/if}
{#if attachment && !loading}
<div class="shrink-0 px-1.5">
<FileContextSwitch
item={attachment}
externalKnowledge={external}
onChange={embed.file.onAttachmentChange}
/>
</div>
{/if}
</div>
{#if loading || !knowledge || external}
<div class="flex flex-1 items-center justify-center text-xs text-base-500 dark:text-base-400">
{#if loading}
<Spinner className="size-3.5" />
{:else}
{$i18n.t(knowledge ? 'No files found' : 'Preview failed')}
{/if}
</div>
{:else}
<Files
knowledge={{ ...knowledge, write_access: false }}
{selectedFileId}
bind:query
sortKey="name"
direction="asc"
onSelect={open}
/>
{/if}
</div>
@@ -0,0 +1,19 @@
<script lang="ts">
import Tooltip from '$lib/components/common/Tooltip.svelte';
import Icon from '$lib/components/chat/FileNav/Icon.svelte';
export let href: string;
export let label: string;
</script>
<Tooltip content={label}>
<a
class="inline-flex h-7 min-w-7 shrink-0 items-center justify-center rounded-md p-1.5 text-base-500 transition hover:bg-base-100 dark:text-base-400 dark:hover:bg-base-800"
{href}
target="_blank"
rel="noopener noreferrer"
aria-label={label}
>
<Icon name="external-link" size={14} />
</a>
</Tooltip>
@@ -867,6 +867,7 @@
disabled={!focus}
on:click={copySelection}><Icon name="copy" size={13} /></button
>
<slot name="toolbar" />
</div>
</div>
</div>
@@ -0,0 +1,87 @@
<script lang="ts">
import { getContext, onMount } from 'svelte';
import { getBackendConfig } from '$lib/apis';
import { getFileById } from '$lib/apis/files';
import { config } from '$lib/stores';
import Switch from './Switch.svelte';
import Tooltip from './Tooltip.svelte';
const i18n: any = getContext('i18n');
/** The attached file whose context this sets. */
export let item: any;
export let externalKnowledge = false;
export let onChange: () => void = () => {};
let loading = true;
// Files are measured by the backend, which can count tokens.
let fullText = false;
const getCharacterCount = (text: string) => Array.from(text).length;
onMount(async () => {
if ($config?.file?.full_text_threshold === undefined) {
await getBackendConfig()
.then((value) => config.set(value))
.catch((error) => console.error('Error fetching file context settings:', error));
}
if (item?.type === 'file') {
const file =
item.file?.full_text === undefined
? await getFileById(localStorage.token, item.id).catch(() => null)
: item.file;
fullText = Boolean(file?.full_text);
}
loading = false;
});
$: fullTextThreshold = $config?.file?.full_text_threshold ?? 0;
$: contentLength = getCharacterCount(item?.file?.data?.content ?? '');
$: automaticFullContent =
!externalKnowledge &&
(Boolean($config?.file?.full_context) ||
fullText ||
(item?.type === 'text' &&
$config?.file?.full_text_threshold_type !== 'token' &&
contentLength > 0 &&
contentLength <= fullTextThreshold));
$: enableFullContent = automaticFullContent || item?.context === 'full';
</script>
{#if !loading && $config?.file?.full_text_threshold !== undefined}
<Tooltip
content={automaticFullContent
? $config?.file?.full_context
? $i18n.t('Full text is always enabled by your administrator.')
: $i18n.t(
'This attachment fits within the full text threshold, so its entire text is included automatically.'
)
: enableFullContent
? $i18n.t(
'Inject the entire content as context for comprehensive processing, this is recommended for complex queries.'
)
: $i18n.t(
'Default to segmented retrieval for focused and relevant content extraction, this is recommended for most cases.'
)}
>
<div class="flex items-center gap-1.5 text-xs">
{#if enableFullContent}
{$i18n.t('Using Entire Document')}
{:else}
{$i18n.t('Using Focused Retrieval')}
{/if}
{#if !automaticFullContent}
<Switch
bind:state={enableFullContent}
ariaLabel={$i18n.t('Using Entire Document')}
on:change={(e) => {
item.context = e.detail ? 'full' : undefined;
onChange();
}}
/>
{/if}
</div>
</Tooltip>
{/if}
+37 -5
View File
@@ -4,7 +4,7 @@
import { formatFileSize, safeLinkUrl } from '$lib/utils';
import type { AppLayoutContext } from '$lib/types';
import { settings, showFileNavPath, user } from '$lib/stores';
import { embed, settings, showEmbeds, showFileNavPath, showTabs, user } from '$lib/stores';
import FileItemModal from './FileItemModal.svelte';
import GarbageBin from '../icons/GarbageBin.svelte';
@@ -23,8 +23,10 @@
export let dismissible = false;
export let modal = false;
/** Opens the file somewhere other than the modal. */
export let onOpen: (() => void) | null = null;
/** The chat the file opens in a tab beside, instead of in the modal. */
export let chatId: string | null = null;
/** Anything more the file's tab needs. */
export let tabOptions: Record<string, any> = {};
export let loading = false;
export let item: any = null;
@@ -42,7 +44,9 @@
import Folder from '../icons/Folder.svelte';
let showModal = false;
// Where there are no chat tabs to browse it in
const canOpenKnowledge = () =>
!modal &&
item?.type === 'collection' &&
!!item.id &&
!!appLayout?.openPageTab &&
@@ -55,6 +59,33 @@
return str;
}
};
const openInTab = () => {
const id = item?.type === 'file' ? item.id : null;
const knowledgeId = item?.type === 'collection' ? item.id : null;
const content = item?.file?.data?.content ?? item?.content ?? '';
const key = item?.id || item?.itemId || item?.url;
if (chatId === null || !(id || knowledgeId || (key && content))) return false;
showTabs.set(true);
showEmbeds.set(true);
embed.set({
key,
file: {
id: id ?? undefined,
knowledgeId,
page: null,
passages: [],
content,
attachment: item,
...tabOptions
},
url: item.url,
title: decodeString(name ?? ''),
chatId
});
return true;
};
</script>
{#if item}
@@ -73,6 +104,8 @@
if (filesystemPath) {
showFileNavPath.set(filesystemPath);
} else if (item?.type === 'collection' && openInTab()) {
// Browsed beside the chat
} else if (canOpenKnowledge()) {
// Opens beside the chat, so the conversation stays readable
appLayout?.openPageTab?.({
@@ -81,8 +114,7 @@
inSplit: true
});
} else if (item?.file?.data?.content || item?.type === 'file' || item?.content || modal) {
if (onOpen) onOpen();
else showModal = !showModal;
if (!openInTab()) showModal = !showModal;
} else {
if (url) {
if (type === 'file') {
+5 -58
View File
@@ -6,8 +6,7 @@
import { formatFileSize, getLineCount, safeLinkUrl } from '$lib/utils';
import { WEBUI_API_BASE_URL } from '$lib/constants';
import { config, settings } from '$lib/stores';
import { getBackendConfig } from '$lib/apis';
import { settings } from '$lib/stores';
import { getKnowledgeById } from '$lib/apis/knowledge';
import { getFileById, getFileContentById } from '$lib/apis/files';
@@ -21,7 +20,7 @@
import Modal from './Modal.svelte';
import XMark from '../icons/XMark.svelte';
import Switch from './Switch.svelte';
import FileContextSwitch from './FileContextSwitch.svelte';
import Tooltip from './Tooltip.svelte';
import dayjs from 'dayjs';
import Spinner from './Spinner.svelte';
@@ -31,16 +30,13 @@
import PptxPreview from './PptxPreview.svelte';
import Reset from '../icons/Reset.svelte';
export let item;
export let item: any;
export let show = false;
export let edit = false;
let enableFullContent = false;
let loading = false;
let externalKnowledge = false;
const getCharacterCount = (text: string) => Array.from(text).length;
let isPDF = false;
let isAudio = false;
let isImage = false;
@@ -187,11 +183,6 @@
expandedContent = false;
docxData = null;
externalKnowledge = false;
if ($config?.file?.full_text_threshold === undefined) {
await getBackendConfig()
.then((value) => config.set(value))
.catch((error) => console.error('Error fetching file context settings:', error));
}
if (item?.type === 'collection') {
loading = true;
@@ -238,19 +229,6 @@
loadContent();
}
$: fullTextThreshold = $config?.file?.full_text_threshold ?? 0;
$: contentLength = getCharacterCount(item?.file?.data?.content ?? '');
$: automaticFullContent =
!externalKnowledge &&
(Boolean($config?.file?.full_context) ||
// Files are measured by the backend, which can count tokens.
(item?.type === 'file' && Boolean(item?.file?.full_text)) ||
(item?.type === 'text' &&
$config?.file?.full_text_threshold_type !== 'token' &&
contentLength > 0 &&
contentLength <= fullTextThreshold));
$: enableFullContent = automaticFullContent || item?.context === 'full';
onMount(() => {
console.log(item);
});
@@ -344,40 +322,9 @@
{/if}
</div>
{#if edit && !loading && $config?.file?.full_text_threshold !== undefined}
{#if edit && !loading}
<div class=" self-end">
<Tooltip
content={automaticFullContent
? $config?.file?.full_context
? $i18n.t('Full text is always enabled by your administrator.')
: $i18n.t(
'This attachment fits within the full text threshold, so its entire text is included automatically.'
)
: enableFullContent
? $i18n.t(
'Inject the entire content as context for comprehensive processing, this is recommended for complex queries.'
)
: $i18n.t(
'Default to segmented retrieval for focused and relevant content extraction, this is recommended for most cases.'
)}
>
<div class="flex items-center gap-1.5 text-xs">
{#if enableFullContent}
{$i18n.t('Using Entire Document')}
{:else}
{$i18n.t('Using Focused Retrieval')}
{/if}
{#if !automaticFullContent}
<Switch
bind:state={enableFullContent}
ariaLabel={$i18n.t('Using Entire Document')}
on:change={(e) => {
item.context = e.detail ? 'full' : undefined;
}}
/>
{/if}
</div>
</Tooltip>
<FileContextSwitch bind:item {externalKnowledge} />
</div>
{/if}
</div>
@@ -431,6 +431,7 @@
/>
</svg>
</button>
<slot name="toolbar" />
</div>
{/if}
</div>
+1 -1
View File
@@ -212,7 +212,7 @@ export const showFileNavPath: Writable<FileNavOpenRequest | null> = writable(nul
export const showFileNavDir: Writable<string | null> = writable(null);
export const selectedMachineId: Writable<string | null> = writable(null);
export const embed = writable(null);
export const embed = writable<any>(null);
/** Whether the main chat is temporary, or for a new chat, whether it starts as one. */
export const temporaryChat = writable(false);