Files
open-webui/src/lib/components/chat/Messages/ToolOutputFile.svelte
T
2026-11-23 02:26:51 +04:00

311 lines
11 KiB
Svelte

<script lang="ts">
import { resolveMachineTarget } from '$lib/apis/machines';
// Keep keys in nested template expressions visible to i18next-parser.
// $i18n.t("Terminal unavailable");
// $i18n.t("No preview available");
import { getContext, onDestroy } from 'svelte';
import type { Writable } from 'svelte/store';
import type { i18n as i18nType } from 'i18next';
import { toast } from 'svelte-sonner';
import { settings, selectedMachineId, showTabs, showFileNavPath, machines } from '$lib/stores';
import { downloadFileBlob, downloadFilePreview, readFile } from '$lib/apis/machines';
import { getFileContentById } from '$lib/apis/files';
import FilePreview from '$lib/components/chat/FileNav/FilePreview.svelte';
import Icon from '$lib/components/chat/FileNav/Icon.svelte';
import { fileIconName } from '$lib/components/chat/FileNav/fileIcon';
import { normalizeDocumentTargetPage } from '$lib/utils/documentPreview';
export let item: any;
export let chatId = '';
export let modelId: string | null = null;
const i18n = getContext<Writable<i18nType>>('i18n');
let expanded = true;
let loading = false;
let loadedKey = '';
let error = '';
let objectUrls: string[] = [];
let fileImageUrl: string | null = null;
let fileVideoUrl: string | null = null;
let fileAudioUrl: string | null = null;
let filePdfData: ArrayBuffer | null = null;
let fileSqliteData: ArrayBuffer | null = null;
let fileModelData: ArrayBuffer | null = null;
let fileDocxData: ArrayBuffer | null = null;
let fileContent: string | null = null;
let fileOfficeSlides: string[] | null = null;
let currentSlide = 0;
let selectedExcelSheet = '';
let excelWorkbook: import('xlsx').WorkBook | null = null;
const IMAGE_EXTS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'ico', 'avif']);
const VIDEO_EXTS = new Set(['mp4', 'webm', 'mov', 'ogv', 'avi', 'mkv']);
const AUDIO_EXTS = new Set(['mp3', 'wav', 'ogg', 'oga', 'flac', 'm4a', 'aac', 'wma', 'opus']);
const SQLITE_EXTS = new Set(['db', 'sqlite', 'sqlite3', 'db3']);
const OFFICE_EXTS = new Set(['docx', 'xlsx', 'xls', 'pptx']);
$: fileId =
item?.source === 'open_webui'
? (String(item.path ?? '').match(/^\/api\/v1\/files\/([^/]+)\/content$/)?.[1] ?? '')
: '';
// Content URLs have no extension; use the filename to select the preview.
$: path = String(fileId ? item.name : item?.full_path || item?.path || '');
$: name = String(item?.name || path.split('/').filter(Boolean).at(-1) || 'file');
$: targetPage = normalizeDocumentTargetPage(item?.page);
$: selector = item?.machine_selector ?? item?.terminal_selector; // terminal_selector: saved before the rename
// Follows the machine menu: the card only reaches its file while that machine is selected.
$: machine =
selector && $selectedMachineId === selector
? resolveMachineTarget(selector, $machines ?? [], localStorage.token, {
chatId,
modelId: item?.model_id ?? modelId
})
: null;
$: unavailable = !machine && !fileId;
$: previewKey = fileId || (machine ? `${machine.baseUrl}|${machine.key}|${path}|${chatId}` : '');
$: previewClass = isImage(path)
? 'h-[22rem]'
: isPdf(path) ||
isOffice(path) ||
['glb', 'gltf', 'stl', 'obj', 'ply'].includes(getExt(path)) ||
getExt(path) === 'html' ||
getExt(path) === 'htm' ||
getExt(path) === 'svg'
? 'h-96'
: 'h-72';
$: if (expanded && !unavailable && path && previewKey !== loadedKey && !loading) {
void loadPreview(previewKey);
}
const getExt = (value: string) => value.split('.').pop()?.toLowerCase() ?? '';
const isImage = (value: string) => IMAGE_EXTS.has(getExt(value));
const isVideo = (value: string) => VIDEO_EXTS.has(getExt(value));
const isAudio = (value: string) => AUDIO_EXTS.has(getExt(value));
const isSqlite = (value: string) => SQLITE_EXTS.has(getExt(value));
const isPdf = (value: string) => getExt(value) === 'pdf';
const isOffice = (value: string) => OFFICE_EXTS.has(getExt(value));
const t = (key: string, vars?: Record<string, unknown>) => $i18n?.t?.(key, vars) ?? key;
function clearPreview() {
for (const url of objectUrls) URL.revokeObjectURL(url);
objectUrls = [];
fileImageUrl = null;
fileVideoUrl = null;
fileAudioUrl = null;
filePdfData = null;
fileSqliteData = null;
fileModelData = null;
fileDocxData = null;
fileContent = null;
fileOfficeSlides = null;
currentSlide = 0;
selectedExcelSheet = '';
excelWorkbook = null;
}
async function blobForPreview() {
if (fileId) {
const data = await getFileContentById(fileId).catch(() => null);
return data
? { blob: new Blob([data], { type: item?.content_type ?? '' }), filename: name }
: null;
}
if (!machine) return null;
return downloadFileBlob(machine, path);
}
async function loadPreview(key: string) {
loadedKey = key;
loading = true;
error = '';
clearPreview();
try {
if (isImage(path) || isVideo(path) || isAudio(path)) {
const result = await blobForPreview();
if (!result) throw new Error(t('Preview failed'));
const url = URL.createObjectURL(result.blob);
objectUrls = [...objectUrls, url];
if (isImage(path)) fileImageUrl = url;
else if (isVideo(path)) fileVideoUrl = url;
else fileAudioUrl = url;
} else if (['glb', 'gltf', 'stl', 'obj', 'ply'].includes(getExt(path))) {
const result = await blobForPreview();
if (!result) throw new Error(t('Preview failed'));
fileModelData = await result.blob.arrayBuffer();
} else if (isPdf(path) || isSqlite(path) || isOffice(path)) {
const ext = getExt(path);
if (isPdf(path)) {
const result = await blobForPreview();
if (!result) throw new Error(t('Preview failed'));
const arrayBuffer = await result.blob.arrayBuffer();
filePdfData = arrayBuffer;
} else if (isSqlite(path)) {
const result = await blobForPreview();
if (!result) throw new Error(t('Preview failed'));
const arrayBuffer = await result.blob.arrayBuffer();
fileSqliteData = arrayBuffer;
} else if (ext === 'docx') {
const preview = machine ? await downloadFilePreview(machine, path) : null;
if (preview) {
filePdfData = await preview.blob.arrayBuffer();
} else {
const result = await blobForPreview();
if (!result) throw new Error(t('Preview failed'));
fileDocxData = await result.blob.arrayBuffer();
}
} else if (ext === 'xlsx' || ext === 'xls') {
const result = await blobForPreview();
if (!result) throw new Error(t('Preview failed'));
const arrayBuffer = await result.blob.arrayBuffer();
const { readExcelWorkbook } = await import('$lib/utils/excelToTable');
const workbook = await readExcelWorkbook(arrayBuffer);
if (workbook.SheetNames.length > 0) {
selectedExcelSheet = workbook.SheetNames[0];
excelWorkbook = workbook;
}
} else if (ext === 'pptx') {
const preview = machine ? await downloadFilePreview(machine, path) : null;
if (preview) {
filePdfData = await preview.blob.arrayBuffer();
} else {
const result = await blobForPreview();
if (!result) throw new Error(t('Preview failed'));
const arrayBuffer = await result.blob.arrayBuffer();
const { pptxToImages } = await import('$lib/utils/pptxToHtml');
const resultImages = await pptxToImages(arrayBuffer);
fileOfficeSlides = resultImages.images;
}
}
} else if (fileId) {
const result = await blobForPreview();
if (!result) throw new Error(t('Preview failed'));
fileContent = await result.blob.text();
} else if (machine) {
fileContent = await readFile(machine, path);
}
} catch (e) {
error = e instanceof Error ? e.message : t('Preview failed');
} finally {
loading = false;
}
}
function openInFiles() {
if (unavailable || !path) return;
showTabs.set(true);
showFileNavPath.set(targetPage ? { path, page: targetPage } : path);
}
async function downloadFile() {
if (unavailable || !path) return;
const result = await blobForPreview();
if (!result) {
toast.error(t('Download failed'));
return;
}
const url = URL.createObjectURL(result.blob);
const a = document.createElement('a');
a.href = url;
a.download = result.filename;
a.click();
URL.revokeObjectURL(url);
}
onDestroy(clearPreview);
</script>
<div
class="my-2 w-full overflow-hidden rounded-xl border border-base-200 bg-base-0 dark:border-base-0/8 dark:bg-base-950/20"
>
<div
class="flex h-8 items-center {expanded ? 'border-b border-base-100 dark:border-base-0/8' : ''}"
>
<button
type="button"
class="flex h-full min-w-0 flex-1 items-center gap-2 px-2.5 text-left"
on:click={() => (expanded = !expanded)}
aria-expanded={expanded}
>
<div
class="flex size-5 shrink-0 items-center justify-center text-base-500 dark:text-base-400"
>
<Icon name={fileIconName(name || path || '', 'file')} size={14} />
</div>
<div class="min-w-0 flex-1 truncate text-xs font-medium text-base-800 dark:text-base-100">
{name}
</div>
</button>
<button
type="button"
class="mr-1 flex size-6 shrink-0 items-center justify-center rounded text-base-400 transition-colors hover:text-base-700 disabled:opacity-40 disabled:hover:text-base-400 dark:text-base-500 dark:hover:text-base-200 dark:disabled:hover:text-base-500"
disabled={unavailable}
on:click|stopPropagation={downloadFile}
aria-label={t('Download')}
>
<Icon name="download" size={13} />
</button>
{#if !fileId}
<button
type="button"
class="mr-1 flex size-6 shrink-0 items-center justify-center rounded text-base-400 transition-colors hover:text-base-700 disabled:opacity-40 disabled:hover:text-base-400 dark:text-base-500 dark:hover:text-base-200 dark:disabled:hover:text-base-500"
disabled={unavailable}
on:click|stopPropagation={openInFiles}
aria-label={t('Open')}
>
<Icon name="external-link" size={13} />
</button>
{/if}
</div>
{#if expanded}
{#if unavailable}
<div class="px-4 py-3 text-xs text-base-500 dark:text-base-400">
{t('Machine unavailable')}
</div>
{:else if error}
<div class="px-4 py-3 text-xs text-red-500 dark:text-red-400">{error}</div>
{:else}
<div
class="{previewClass} max-h-[75vh] min-h-24 resize-y overflow-hidden bg-base-50 dark:bg-base-950"
>
<FilePreview
selectedFile={path}
fileLoading={loading}
{fileImageUrl}
{fileVideoUrl}
{fileAudioUrl}
{filePdfData}
{fileSqliteData}
{fileModelData}
{fileDocxData}
{fileContent}
target={fileId ? null : machine}
{chatId}
{excelWorkbook}
{fileOfficeSlides}
{currentSlide}
{targetPage}
bind:selectedExcelSheet
readOnly={true}
/>
{#if !loading && fileImageUrl === null && fileVideoUrl === null && fileAudioUrl === null && filePdfData === null && fileSqliteData === null && fileModelData === null && fileDocxData === null && fileContent === null && excelWorkbook === null && fileOfficeSlides === null}
<div
class="flex h-full items-center justify-center px-3 text-xs text-base-500 dark:text-base-400"
>
{t('No preview available')}
</div>
{/if}
</div>
{/if}
{/if}
</div>