Commit de3069728 for llama.cpp
commit de306972853640223d20ce57a3d9e44f6719d3db
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date: Wed Nov 25 09:56:31 2026 +0100
ui: import conversations or settings by dropping them anywhere in the app (#32958)
* ui : add global drag-and-drop import for conversations and settings
Dropping an exported conversation (.zip, .jsonl) or settings (.json)
anywhere in the app now routes to a global importer instead of attaching
the file to a message. A state machine in use-drop-import classifies the
file, shows a review dialog (settings diff, single-conversation preview,
or bulk picker), and applies it on confirmation. The chat screen defers
import files so they are not treated as attachments.
* ui : preview settings diff before importing from Import/Export tab
The Import/Export settings tab now opens the same settings diff dialog
used by drag-and-drop (showing which values would change) before applying
an imported settings file. It reuses computeSettingsDiff from the global
drop-import hook instead of importing immediately.
* ui : fix formatting in drag-and-drop import
* ui : use SvelteMap/SvelteSet and fix eslint in drag-and-drop import
* ui : adapt drag-and-drop import to current lint rules
Assisted-by: Claude (Opus 5.5 Medium)
* ui : fix importing dropped conversations
Store a plain snapshot of the previewed conversation, since IndexedDB
cannot clone the reactive proxy, and collapse drops that carry the same
conversation more than once to its newest copy, so the selection list
no longer crashes on duplicate keys.
Assisted-by: Claude (Opus 5.5 Medium)
* ui : simplify the dropped conversation preview dialog
Drop the icon and the description from the header, and give the
preview padding and a subtler border.
Assisted-by: Claude (Opus 5.5 Medium)
* ui : set the dropped conversation preview on a recessed surface
Assisted-by: Claude (Opus 5.5 Medium)
* ui : ask to open a dropped conversation after importing it
Assisted-by: Claude (Opus 5.5 Medium)
* ui : diff dropped settings against what importing applies
Importing applies the file over the defaults, so a key the file leaves
out goes back to its default instead of showing as unset.
Assisted-by: Claude (Opus 5.5 Medium)
* ui : match the settings import preview to the conversation preview
Assisted-by: Claude (Opus 5.5 Medium)
* ui : set the drop import text through type roles
Assisted-by: Claude (Opus 5.5 Medium)
* ui : attach dropped files on the chat unless they are exports
The chat now reads each dropped .json, .jsonl or .zip and hands only real
Llama Chat exports to the importer, through a drop-import context set by the
layout; everything else is attached as on master, mixed drops included. Its
drag events no longer bubble to the document, so the import overlay no
longer shows over the chat or stays up after an attachment drop.
Assisted-by: Claude (Opus 5.5 Medium)
* ui : one drop area to import and a choice of what to export
The Import/Export tab now has a single drop area (or file picker) that takes
conversations, settings or a full backup and goes through the same previews
as dropping anywhere in the app. Export asks for conversations, settings or
everything; everything is one ZIP with the conversations and settings.json,
which importing reads back, showing the settings first and the conversations
after. Sensitive data is an inline checkbox instead of its own dialog.
Bulk import now reports conversations already in the library instead of
counting them as imported, and reloads groups like the tab used to.
Assisted-by: Claude (Opus 5.5 Medium)
* ui : import demo traces through the Import/Export drop area
Assisted-by: Claude (Opus 5.5 Medium)
diff --git a/ui/apps/chat/demo/helpers.ts b/ui/apps/chat/demo/helpers.ts
index 97e7bdb11..6712d5c7b 100644
--- a/ui/apps/chat/demo/helpers.ts
+++ b/ui/apps/chat/demo/helpers.ts
@@ -519,10 +519,21 @@ async function importTraces(page: Page, file: string): Promise<void> {
const chooser = page.waitForEvent('filechooser');
- await scope.getByRole('button', { name: 'Import conversations' }).click();
+ await scope.getByRole('button', { name: /^Drop files here/ }).click();
await (await chooser).setFiles(file);
- await page.getByRole('button', { name: /^Import \(\d+\)$/ }).click();
- await page.getByRole('heading', { name: /^Imported \d+ conversation/ }).waitFor();
+
+ // one conversation gets a preview, then a prompt to open it; several get a picker, then a list
+ const notNow = page.getByRole('button', { exact: true, name: 'Not now' });
+ const importedList = page.getByRole('heading', { name: 'Imported Conversations' });
+
+ await page
+ .getByRole('button', { name: /^Import \(\d+\)$/ })
+ .or(page.getByRole('alertdialog').getByRole('button', { exact: true, name: 'Import' }))
+ .click();
+ await notNow.or(importedList).waitFor();
+
+ if (await notNow.isVisible()) await notNow.click();
+ else await page.keyboard.press('Escape');
// the app remembers the sidebar the import expanded; a demo starts with it collapsed, as on a
// first visit
diff --git a/ui/apps/chat/src/lib/components/app/DropImportOverlay.svelte b/ui/apps/chat/src/lib/components/app/DropImportOverlay.svelte
new file mode 100644
index 000000000..efc39431a
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/DropImportOverlay.svelte
@@ -0,0 +1,17 @@
+<script lang="ts">
+ import { FileDown } from '@lucide/svelte';
+</script>
+
+<div
+ class="pointer-events-none fixed inset-0 z-1000000 flex items-center justify-center bg-black/50 backdrop-blur-sm"
+>
+ <div
+ class="flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-border bg-background p-12 shadow-(--elevation-raised)"
+ >
+ <FileDown class="mb-4 h-12 w-12 text-muted-foreground" />
+
+ <p class="text-title text-foreground">Import conversations or settings</p>
+
+ <p class="text-body-sm text-muted-foreground">Drop your files here to import</p>
+ </div>
+</div>
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogExportSettings.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogExportSettings.svelte
deleted file mode 100644
index 51a9486ac..000000000
--- a/ui/apps/chat/src/lib/components/app/dialogs/DialogExportSettings.svelte
+++ /dev/null
@@ -1,81 +0,0 @@
-<script lang="ts">
- import * as AlertDialog from '@ggml-org/llama-ui/ui/alert-dialog';
- import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox';
- import { Label } from '@ggml-org/llama-ui/ui/label';
- import { Shield, ShieldOff } from '@lucide/svelte';
-
- let {
- includeSensitiveData = $bindable(false),
- onCancel,
- onConfirm,
- open = $bindable()
- }: {
- open: boolean;
- includeSensitiveData: boolean;
- onCancel: () => void;
- onConfirm: () => void;
- } = $props();
-
- function handleOpenChange(newOpen: boolean) {
- if (!newOpen) {
- onCancel();
- }
- }
-</script>
-
-<AlertDialog.Root onOpenChange={handleOpenChange} {open}>
- <AlertDialog.Content>
- <AlertDialog.Header>
- <AlertDialog.Title class="flex items-center gap-2">
- {#if includeSensitiveData}
- <ShieldOff class="size-icon-lg text-destructive" />
- {:else}
- <Shield class="size-icon-lg text-destructive" />
- {/if}
- Export Settings
- </AlertDialog.Title>
-
- <AlertDialog.Description>
- {#if includeSensitiveData}
- <p class="text-amber-500">
- Warning: This export will include sensitive data such as API keys and MCP server custom
- headers (e.g., authorization tokens). Do not share this file with anyone you don't
- trust.
- </p>
- {:else}
- <p>
- Sensitive data (API keys, MCP server custom headers) will not be included in the export
- to protect your credentials.
- </p>
- {/if}
- </AlertDialog.Description>
- </AlertDialog.Header>
-
- <div class="flex items-center gap-2 py-2">
- <Checkbox bind:checked={includeSensitiveData} id="include-sensitive" />
-
- <Label
- class="text-body-sm leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
- for="include-sensitive"
- >
- {#if includeSensitiveData}
- <span class="text-destructive">Include sensitive data (not recommended)</span>
- {:else}
- <span>Include sensitive data</span>
- {/if}
- </Label>
- </div>
-
- <AlertDialog.Footer>
- <AlertDialog.Cancel onclick={onCancel}>Cancel</AlertDialog.Cancel>
-
- <AlertDialog.Action onclick={onConfirm} variant="destructive">
- {#if includeSensitiveData}
- Export Anyway
- {:else}
- Export Without Sensitive Data
- {/if}
- </AlertDialog.Action>
- </AlertDialog.Footer>
- </AlertDialog.Content>
-</AlertDialog.Root>
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogImportConversationPreview.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogImportConversationPreview.svelte
new file mode 100644
index 000000000..9945a190e
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogImportConversationPreview.svelte
@@ -0,0 +1,39 @@
+<script lang="ts">
+ import * as AlertDialog from '@ggml-org/llama-ui/ui/alert-dialog';
+ import ChatMessages from '#lib/components/app/chat/ChatMessages/ChatMessages.svelte';
+
+ interface Props {
+ open: boolean;
+ messages?: DatabaseMessage[];
+ onConfirm: () => void;
+ onCancel: () => void;
+ }
+
+ let { messages = [], onCancel, onConfirm, open = $bindable() }: Props = $props();
+
+ function handleOpenChange(newOpen: boolean) {
+ if (!newOpen) {
+ onCancel();
+ }
+ }
+</script>
+
+<AlertDialog.Root onOpenChange={handleOpenChange} {open}>
+ <AlertDialog.Content class="sm:max-w-3xl">
+ <AlertDialog.Header>
+ <AlertDialog.Title>Import conversation?</AlertDialog.Title>
+ </AlertDialog.Header>
+
+ <div
+ class="max-h-[60vh] overflow-y-auto rounded-md border border-border/30 bg-muted/50 p-4 matte-well dark:border-border/20 dark:bg-muted/80"
+ >
+ <ChatMessages {messages} />
+ </div>
+
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel onclick={onCancel}>Cancel</AlertDialog.Cancel>
+
+ <AlertDialog.Action onclick={onConfirm}>Import</AlertDialog.Action>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+</AlertDialog.Root>
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogImportConversationsResult.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogImportConversationsResult.svelte
new file mode 100644
index 000000000..7947d297b
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogImportConversationsResult.svelte
@@ -0,0 +1,106 @@
+<script lang="ts">
+ import { SearchInput } from '@ggml-org/llama-ui/app/forms';
+ import * as Dialog from '@ggml-org/llama-ui/ui/dialog';
+ import { ScrollArea } from '@ggml-org/llama-ui/ui/scroll-area';
+ import { MessageSquarePlus } from '@lucide/svelte';
+ import { UI_DATA_ATTRS } from '#lib/constants/index.ts';
+
+ interface Props {
+ conversations: DatabaseConversation[];
+ messageCountMap?: Map<string, number>;
+ onOpen: (conversation: DatabaseConversation) => void;
+ onClose: () => void;
+ open?: boolean;
+ }
+
+ let {
+ conversations,
+ messageCountMap = new Map(),
+ onClose,
+ onOpen,
+ open = $bindable()
+ }: Props = $props();
+
+ let searchQuery = $state('');
+
+ function handleOpenChange(newOpen: boolean) {
+ if (!newOpen) {
+ onClose();
+ }
+ }
+
+ let filteredConversations = $derived(
+ conversations.filter((conv) => {
+ const name = conv.name || 'Untitled conversation';
+
+ return name.toLowerCase().includes(searchQuery.toLowerCase());
+ })
+ );
+</script>
+
+<Dialog.Root bind:open onOpenChange={handleOpenChange}>
+ <Dialog.Portal>
+ <Dialog.Overlay class="z-1000000" />
+
+ <Dialog.Content class="z-1000001 max-w-2xl">
+ <Dialog.Header>
+ <Dialog.Title class="flex items-center gap-2">
+ <MessageSquarePlus class="h-5 w-5" />
+
+ Imported Conversations
+ </Dialog.Title>
+
+ <Dialog.Description>
+ {conversations.length} conversation{conversations.length === 1 ? '' : 's'} imported. Select
+ one to open it.
+ </Dialog.Description>
+ </Dialog.Header>
+
+ <div class="space-y-4">
+ <SearchInput bind:value={searchQuery} placeholder="Search conversations..." />
+
+ <div class="overflow-hidden rounded-md border">
+ <ScrollArea class="h-100">
+ <table class="w-full">
+ <thead class="sticky top-0 z-10 bg-muted">
+ <tr class="border-b">
+ <th class="p-3 text-left text-label">Conversation Name</th>
+
+ <th class="w-32 p-3 text-left text-label">Messages</th>
+ </tr>
+ </thead>
+
+ <tbody>
+ {#if filteredConversations.length === 0}
+ <tr>
+ <td class="p-8 text-center text-body-sm text-muted-foreground" colspan="2">
+ No conversations found matching "{searchQuery}"
+ </td>
+ </tr>
+ {:else}
+ {#each filteredConversations as conv (conv.id)}
+ <tr
+ class="cursor-pointer border-b transition-colors hover:bg-muted/50"
+ {...{ [UI_DATA_ATTRS.CONVERSATION_ROW]: conv.id }}
+ onclick={() => onOpen(conv)}
+ >
+ <td class="p-3 text-body-sm">
+ <div class="max-w-68 truncate" title={conv.name || 'Untitled conversation'}>
+ {conv.name || 'Untitled conversation'}
+ </div>
+ </td>
+
+ <td class="p-3 text-body-sm text-muted-foreground">
+ {messageCountMap.get(conv.id) ?? 0}
+ </td>
+ </tr>
+ {/each}
+ {/if}
+ </tbody>
+ </table>
+ </ScrollArea>
+ </div>
+ </div>
+ </Dialog.Content>
+ </Dialog.Portal>
+</Dialog.Root>
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/DialogSettingsImportPreview.svelte b/ui/apps/chat/src/lib/components/app/dialogs/DialogSettingsImportPreview.svelte
new file mode 100644
index 000000000..9daa8997c
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/dialogs/DialogSettingsImportPreview.svelte
@@ -0,0 +1,78 @@
+<script lang="ts">
+ import * as AlertDialog from '@ggml-org/llama-ui/ui/alert-dialog';
+ import { ArrowRight } from '@lucide/svelte';
+
+ export interface SettingsDiffEntry {
+ key: string;
+ label: string;
+ from: SettingsConfigValue;
+ to: SettingsConfigValue;
+ }
+
+ interface Props {
+ open: boolean;
+ diff?: SettingsDiffEntry[];
+ onConfirm: () => void;
+ onCancel: () => void;
+ }
+
+ let { diff = [], onCancel, onConfirm, open = $bindable() }: Props = $props();
+
+ function formatValue(value: SettingsConfigValue): string {
+ if (value === undefined) return 'default';
+
+ if (typeof value === 'string') {
+ return value || '(empty)';
+ }
+
+ return String(value);
+ }
+
+ function handleOpenChange(newOpen: boolean) {
+ if (!newOpen) {
+ onCancel();
+ }
+ }
+</script>
+
+<AlertDialog.Root onOpenChange={handleOpenChange} {open}>
+ <AlertDialog.Content class="sm:max-w-2xl">
+ <AlertDialog.Header>
+ <AlertDialog.Title>Import settings?</AlertDialog.Title>
+ </AlertDialog.Header>
+
+ <div
+ class="max-h-[60vh] overflow-y-auto rounded-md border border-border/30 bg-muted/50 matte-well dark:border-border/20 dark:bg-muted/80"
+ >
+ {#if diff.length === 0}
+ <p class="p-4 text-body-sm text-muted-foreground">No settings would change.</p>
+ {:else}
+ <div class="divide-y divide-border/30 dark:divide-border/20">
+ {#each diff as entry (entry.key)}
+ <div class="flex items-center gap-3 p-3">
+ <div class="min-w-0 flex-1">
+ <p class="truncate text-label">{entry.label}</p>
+
+ <p class="truncate text-caption text-muted-foreground">{entry.key}</p>
+ </div>
+
+ <div class="flex shrink-0 items-center gap-2 text-body-sm">
+ <span class="line-through text-muted-foreground">{formatValue(entry.from)}</span>
+
+ <ArrowRight class="h-4 w-4 text-muted-foreground" />
+
+ <span class="font-medium">{formatValue(entry.to)}</span>
+ </div>
+ </div>
+ {/each}
+ </div>
+ {/if}
+ </div>
+
+ <AlertDialog.Footer>
+ <AlertDialog.Cancel onclick={onCancel}>Cancel</AlertDialog.Cancel>
+
+ <AlertDialog.Action onclick={onConfirm}>Import</AlertDialog.Action>
+ </AlertDialog.Footer>
+ </AlertDialog.Content>
+</AlertDialog.Root>
diff --git a/ui/apps/chat/src/lib/components/app/dialogs/index.ts b/ui/apps/chat/src/lib/components/app/dialogs/index.ts
index af0204ca8..342a6a6f8 100644
--- a/ui/apps/chat/src/lib/components/app/dialogs/index.ts
+++ b/ui/apps/chat/src/lib/components/app/dialogs/index.ts
@@ -35,37 +35,6 @@ export { default as DialogMcpServers } from './DialogMcpServers.svelte';
*/
export { default as DialogSettingsChat } from './DialogSettingsChat.svelte';
-/**
- * **DialogExportSettings** - Settings export dialog with sensitive data warning
- *
- * Dialog for exporting settings with an option to include or exclude
- * sensitive data (API keys, MCP server custom headers). Defaults to excluding
- * sensitive data for security. User must explicitly opt-in to include them.
- *
- * **Architecture:**
- * - Uses ShadCN AlertDialog
- * - Checkbox to toggle sensitive data inclusion (defaults to false)
- * - Warning icon and message when sensitive data is included
- * - Destructive variant for the action button when exporting with sensitive data
- *
- * **Features:**
- * - Secure default: sensitive data excluded by default
- * - User must explicitly opt-in to include sensitive data
- * - Visual warning (ShieldOff icon) when sensitive data is included
- * - Different action text based on sensitive data state
- *
- * @example
- * ```svelte
- * <DialogExportSettings
- * bind:open={showExportSettings}
- * bind:includeSensitiveData
- * onConfirm={handleSettingsExport}
- * onCancel={() => showExportSettings = false}
- * />
- * ```
- */
-export { default as DialogExportSettings } from './DialogExportSettings.svelte';
-
/**
*
* CONFIRMATION DIALOGS
@@ -447,6 +416,64 @@ export { default as DialogModelNotAvailable } from './DialogModelNotAvailable.sv
*/
export { default as DialogConversationSelection } from './DialogConversationSelection.svelte';
+/**
+ * **DialogSettingsImportPreview** - Review the settings diff before importing
+ *
+ * Alert dialog shown when a settings file is imported via drag-and-drop.
+ * Lists each setting that would change (old value -> new value) so the user
+ * can review before confirming the import.
+ *
+ * @example
+ * ```svelte
+ * <DialogSettingsImportPreview
+ * bind:open={showSettingsPreview}
+ * diff={settingsDiff}
+ * onConfirm={handleConfirm}
+ * onCancel={() => (showSettingsPreview = false)}
+ * />
+ * ```
+ */
+export { default as DialogSettingsImportPreview } from './DialogSettingsImportPreview.svelte';
+
+/**
+ * **DialogImportConversationPreview** - Preview a single conversation before importing
+ *
+ * Alert dialog shown when a single conversation is imported via drag-and-drop.
+ * Renders the conversation's messages (via ChatMessages) so the user can review
+ * it before confirming the import.
+ *
+ * @example
+ * ```svelte
+ * <DialogImportConversationPreview
+ * bind:open={showPreview}
+ * messages={conv?.messages}
+ * onConfirm={handleConfirm}
+ * onCancel={() => (showPreview = false)}
+ * />
+ * ```
+ */
+export { default as DialogImportConversationPreview } from './DialogImportConversationPreview.svelte';
+
+/**
+ * **DialogImportConversationsResult** - Pick one imported conversation to open
+ *
+ * Dialog shown after multiple conversations are imported via drag-and-drop.
+ * Lists the imported conversations in a table (with search) and lets the user
+ * click one to open it.
+ *
+ * @example
+ * ```svelte
+ * <DialogImportConversationsResult
+ * bind:open={showOpenBulk}
+ * conversations={imported}
+ * messageCountMap={countMap}
+ * onOpen={handleOpen}
+ * onClose={() => (showOpenBulk = false)}
+ * />
+ * ```
+ */
+export { default as DialogImportConversationsResult } from './DialogImportConversationsResult.svelte';
+
/**
* **DialogMcpResourcesBrowser** - MCP resources browser dialog
*
diff --git a/ui/apps/chat/src/lib/components/app/index.ts b/ui/apps/chat/src/lib/components/app/index.ts
index a0a14c617..a916f4b14 100644
--- a/ui/apps/chat/src/lib/components/app/index.ts
+++ b/ui/apps/chat/src/lib/components/app/index.ts
@@ -1,5 +1,6 @@
export * from './actions';
export * from './badges';
+export { default as DropImportOverlay } from './DropImportOverlay.svelte';
export * from './chat';
export * from './content';
export * from './dialogs';
diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportDropZone.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportDropZone.svelte
new file mode 100644
index 000000000..e770e9f1a
--- /dev/null
+++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportDropZone.svelte
@@ -0,0 +1,81 @@
+<script lang="ts">
+ import { FileDown } from '@lucide/svelte';
+ import { getDropImportContext } from '#lib/contexts/index.ts';
+ import { HtmlInputType } from '#lib/enums/index.ts';
+ import { toast } from 'svelte-sonner';
+
+ const dropImport = getDropImportContext();
+
+ let dragCounter = $state(0);
+ let input = $state<HTMLInputElement>();
+ let isDragOver = $derived(dragCounter > 0);
+
+ async function importFiles(files: File[]) {
+ if (!dropImport || files.length === 0) return;
+
+ for (const file of await dropImport.importExports(files)) {
+ toast.error(`${file.name} is not a Llama Chat export`);
+ }
+ }
+
+ // every drag event stops here, so the app-wide import overlay stays off this area
+ function handleDragEnter(event: DragEvent) {
+ event.preventDefault();
+ event.stopPropagation();
+ dragCounter++;
+ }
+
+ function handleDragLeave(event: DragEvent) {
+ event.preventDefault();
+ event.stopPropagation();
+ dragCounter = Math.max(0, dragCounter - 1);
+ }
+
+ function handleDragOver(event: DragEvent) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+
+ function handleDrop(event: DragEvent) {
+ event.preventDefault();
+ event.stopPropagation();
+ dragCounter = 0;
+ importFiles(Array.from(event.dataTransfer?.files ?? []));
+ }
+
+ function handleChange() {
+ importFiles(Array.from(input?.files ?? []));
+
+ if (input) input.value = '';
+ }
+</script>
+
+<!-- No `accept` filter: iOS resolves each entry to a UTI and has none for `.jsonl`,
+ which greys out exported conversations in the file picker. -->
+<input
+ bind:this={input}
+ class="hidden"
+ multiple
+ onchange={handleChange}
+ type={HtmlInputType.FILE}
+/>
+
+<button
+ class="flex w-full flex-col items-center justify-center gap-1 rounded-lg border-2 border-dashed px-6 py-10 text-center transition-colors focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none {isDragOver
+ ? 'border-primary bg-accent'
+ : 'border-border hover:border-muted-foreground/50 hover:bg-muted/50'}"
+ onclick={() => input?.click()}
+ ondragenter={handleDragEnter}
+ ondragleave={handleDragLeave}
+ ondragover={handleDragOver}
+ ondrop={handleDrop}
+ type="button"
+>
+ <FileDown class="mb-2 size-8 text-muted-foreground" />
+
+ <span class="text-label">Drop files here or click to browse</span>
+
+ <span class="text-caption text-muted-foreground">
+ A conversation (.jsonl), several in a .zip, settings (.json) or a full backup
+ </span>
+</button>
diff --git a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportExportTab.svelte b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportExportTab.svelte
index 9f95d5e44..02affed6b 100644
--- a/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportExportTab.svelte
+++ b/ui/apps/chat/src/lib/components/app/settings/SettingsChat/SettingsChatImportExportTab.svelte
@@ -1,140 +1,96 @@
<script lang="ts">
+ import SettingsChatImportDropZone from './SettingsChatImportDropZone.svelte';
import SettingsChatImportExportSection from './SettingsChatImportExportSection.svelte';
- import { Download, Trash2, Upload } from '@lucide/svelte';
- import {
- DialogConfirmation,
- DialogConversationSelection,
- DialogExportSettings
- } from '#lib/components/app/index.ts';
+ import { Button } from '@ggml-org/llama-ui/ui/button';
+ import { Checkbox } from '@ggml-org/llama-ui/ui/checkbox';
+ import { Label } from '@ggml-org/llama-ui/ui/label';
+ import * as RadioGroup from '@ggml-org/llama-ui/ui/radio-group';
+ import { Download, Trash2 } from '@lucide/svelte';
+ import { DialogConfirmation, DialogConversationSelection } from '#lib/components/app/index.ts';
import SettingsGroup from '#lib/components/app/settings/SettingsGroup.svelte';
- import { ConversationSelectionMode, FileExtensionText, HtmlInputType } from '#lib/enums/index.ts';
+ import { ICON_CLASS_DEFAULT } from '#lib/constants/index.ts';
+ import { ConversationSelectionMode, DataExportScope } from '#lib/enums/index.ts';
import { ConversationTransferService } from '#lib/services/index.ts';
- import { conversationsStore, groupsStore, settingsStore } from '#lib/stores/index.ts';
+ import { conversationsStore, settingsStore } from '#lib/stores/index.ts';
import { createMessageCountMap } from '#lib/utils/index.ts';
import { fade } from 'svelte/transition';
import { toast } from 'svelte-sonner';
- let exportedConversations = $state<DatabaseConversation[]>([]);
- let importedConversations = $state<DatabaseConversation[]>([]);
- let showExportSummary = $state(false);
- let showImportSummary = $state(false);
+ const EXPORT_OPTIONS = [
+ {
+ description: 'Pick which ones: one is saved as a JSONL file, several as a ZIP.',
+ label: 'Conversations',
+ value: DataExportScope.CONVERSATIONS
+ },
+ {
+ description: 'Your chat settings and preferences as a JSON file.',
+ label: 'Settings',
+ value: DataExportScope.SETTINGS
+ },
+ {
+ description: 'All conversations and settings in one ZIP, to restore in one drop.',
+ label: 'Everything',
+ value: DataExportScope.ALL
+ }
+ ];
+
+ let exportScope = $state(DataExportScope.CONVERSATIONS);
+ let includeSensitiveData = $state(false);
+ let exportsSettings = $derived(exportScope !== DataExportScope.CONVERSATIONS);
let showExportDialog = $state(false);
- let showImportDialog = $state(false);
let availableConversations = $state<DatabaseConversation[]>([]);
let messageCountMap = $state<Map<string, number>>(new Map());
- let fullImportData = $state<Array<{ conv: DatabaseConversation; messages: DatabaseMessage[] }>>(
- []
- );
- // Delete functionality state
let showDeleteDialog = $state(false);
- // Settings import/export state
- let showSettingsExportSummary = $state(false);
- let showSettingsImportSummary = $state(false);
- let showSettingsExportDialog = $state(false);
- let includeSensitiveData = $state(false);
-
- function handleSettingsExport() {
- showSettingsExportDialog = true;
- includeSensitiveData = false;
- }
-
- function handleSettingsExportConfirm() {
- showSettingsExportDialog = false;
-
+ async function handleExport() {
try {
- const data = settingsStore.exportSettings(includeSensitiveData);
- const blob = new Blob([JSON.stringify(data, null, 2)], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
-
- a.href = url;
- a.download = `llama_settings_${new Date().toISOString().split('T')[0]}.json`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
-
- showSettingsExportSummary = true;
- showSettingsImportSummary = false;
- toast.success('Settings exported');
- } catch (err) {
- console.error('Failed to export settings:', err);
- toast.error('Failed to export settings');
- }
- }
-
- function handleSettingsExportCancel() {
- showSettingsExportDialog = false;
- }
-
- function handleSettingsImport() {
- try {
- const input = document.createElement('input');
-
- input.type = HtmlInputType.FILE;
- input.accept = FileExtensionText.JSON;
-
- input.onchange = async (e) => {
- const file = (e.target as HTMLInputElement)?.files?.[0];
-
- if (!file) return;
-
- try {
- const text = await file.text();
- const data = JSON.parse(text);
-
- if (!data || typeof data !== 'object' || !data.config) {
- toast.error('Invalid settings file: missing config');
-
- return;
- }
-
- settingsStore.importSettings(data);
-
- showSettingsImportSummary = true;
- showSettingsExportSummary = false;
- toast.success('Settings imported successfully');
- } catch (err) {
- console.error('Failed to import settings:', err);
- toast.error('Failed to import settings');
- }
- };
+ if (exportScope === DataExportScope.SETTINGS) {
+ ConversationTransferService.downloadSettingsFile(
+ settingsStore.exportSettings(includeSensitiveData)
+ );
+ toast.success('Settings exported');
+ } else if (exportScope === DataExportScope.ALL) {
+ const data = await conversationsStore.getConversationsForExport(
+ conversationsStore.conversations.map((conv) => conv.id)
+ );
- input.click();
+ ConversationTransferService.downloadConversationsArchive(
+ data,
+ settingsStore.exportSettings(includeSensitiveData)
+ );
+ toast.success(
+ `Exported ${data.length} conversation${data.length === 1 ? '' : 's'} and settings`
+ );
+ } else {
+ await openConversationPicker();
+ }
} catch (err) {
- console.error('Failed to open file picker:', err);
- toast.error('Failed to open file picker');
+ console.error('Export failed:', err);
+ toast.error('Export failed');
}
}
- async function handleExportClick() {
- try {
- const allConversations = conversationsStore.conversations;
+ async function openConversationPicker() {
+ const allConversations = conversationsStore.conversations;
- if (allConversations.length === 0) {
- toast.info('No conversations to export');
+ if (allConversations.length === 0) {
+ toast.info('No conversations to export');
- return;
- }
-
- const conversationsWithMessages = await Promise.all(
- allConversations.map(async (conv: DatabaseConversation) => {
- const messages = await conversationsStore.getConversationMessages(conv.id);
+ return;
+ }
- return { conv, messages };
- })
- );
+ const conversationsWithMessages = await Promise.all(
+ allConversations.map(async (conv: DatabaseConversation) => ({
+ conv,
+ messages: await conversationsStore.getConversationMessages(conv.id)
+ }))
+ );
- messageCountMap = createMessageCountMap(conversationsWithMessages);
- availableConversations = allConversations;
- showExportDialog = true;
- } catch (err) {
- console.error('Failed to load conversations:', err);
- alert('Failed to load conversations');
- }
+ messageCountMap = createMessageCountMap(conversationsWithMessages);
+ availableConversations = allConversations;
+ showExportDialog = true;
}
async function handleExportConfirm(selectedConversations: DatabaseConversation[]) {
@@ -149,100 +105,22 @@
ConversationTransferService.downloadConversationsArchive(allData);
}
- exportedConversations = selectedConversations;
- showExportSummary = true;
- showImportSummary = false;
showExportDialog = false;
+ toast.success(`Exported ${allData.length} conversation${allData.length === 1 ? '' : 's'}`);
} catch (err) {
console.error('Export failed:', err);
- alert('Failed to export conversations');
+ toast.error('Failed to export conversations');
}
}
- async function handleImportClick() {
- try {
- const input = document.createElement('input');
-
- // No `accept` filter: iOS resolves each entry to a UTI and has none for
- // `.jsonl`, which greys out exported conversations in the file picker.
- // `parseImportFile` detects the format from the file contents instead.
- input.type = HtmlInputType.FILE;
-
- input.onchange = async (e) => {
- const file = (e.target as HTMLInputElement)?.files?.[0];
-
- if (!file) return;
-
- try {
- const importedData = await ConversationTransferService.parseImportFile(file);
+ function handleDeleteAllClick() {
+ if (conversationsStore.conversations.length === 0) {
+ toast.info('No conversations to delete');
- if (importedData.length === 0) {
- throw new Error('No conversations found in file');
- }
-
- fullImportData = importedData;
- availableConversations = importedData.map((item) => item.conv);
- messageCountMap = createMessageCountMap(importedData);
- showImportDialog = true;
- } catch (err: unknown) {
- const message = err instanceof Error ? err.message : 'Unknown error';
-
- console.error('Failed to parse file:', err);
- alert(`Failed to parse file: ${message}`);
- }
- };
-
- input.click();
- } catch (err) {
- console.error('Import failed:', err);
- alert('Failed to import conversations');
+ return;
}
- }
- async function handleImportConfirm(selectedConversations: DatabaseConversation[]) {
- try {
- const selectedIds = new Set(selectedConversations.map((c) => c.id));
- const selectedData = $state
- .snapshot(fullImportData)
- .filter((item) => selectedIds.has(item.conv.id));
- const { imported, skipped } = await conversationsStore.importConversationsData(selectedData);
-
- // an import can add the groups its chats were in
- await groupsStore.reload();
-
- // A conversation already in the database is left untouched, so the summary
- // lists what was written and the toast accounts for the rest.
- if (skipped.length > 0) {
- toast.info(
- `Skipped ${skipped.length} conversation${skipped.length === 1 ? '' : 's'} already in your library`
- );
- }
-
- importedConversations = imported;
- showImportSummary = true;
- showExportSummary = false;
- showImportDialog = false;
- } catch (err) {
- console.error('Import failed:', err);
- alert('Failed to import conversations. Please check the file format.');
- }
- }
-
- async function handleDeleteAllClick() {
- try {
- const allConversations = conversationsStore.conversations;
-
- if (allConversations.length === 0) {
- toast.info('No conversations to delete');
-
- return;
- }
-
- showDeleteDialog = true;
- } catch (err) {
- console.error('Failed to load conversations for deletion:', err);
- toast.error('Failed to load conversations');
- }
+ showDeleteDialog = true;
}
async function handleDeleteAllConfirm() {
@@ -261,25 +139,64 @@
</script>
<div in:fade={{ duration: 150 }} class="space-y-12">
- <SettingsGroup title="Conversations">
- <SettingsChatImportExportSection
- IconComponent={Download}
- buttonText="Export conversations"
- description="Download your conversations as a ZIP of JSONL files. This includes all messages, attachments, and conversation history."
- onclick={handleExportClick}
- summary={{ items: exportedConversations, show: showExportSummary, verb: 'Exported' }}
- title="Export"
- />
+ <SettingsGroup title="Import">
+ <p class="text-body-sm text-muted-foreground">
+ Bring in one or more conversations, your settings, or both at once. You see what each file
+ holds before anything changes; conversations already in your library are left as they are.
+ </p>
- <SettingsChatImportExportSection
- IconComponent={Upload}
- buttonText="Import conversations"
- description="Import one or more conversations from a previously exported ZIP or JSONL file. This will merge with your existing conversations."
- onclick={handleImportClick}
- summary={{ items: importedConversations, show: showImportSummary, verb: 'Imported' }}
- title="Import"
- />
+ <SettingsChatImportDropZone />
+ </SettingsGroup>
+
+ <SettingsGroup title="Export">
+ <RadioGroup.Root
+ class="gap-3"
+ onValueChange={(value) => (exportScope = value as DataExportScope)}
+ value={exportScope}
+ >
+ {#each EXPORT_OPTIONS as option (option.value)}
+ {@const id = `export-${option.value}`}
+
+ <div class="flex items-start gap-3">
+ <RadioGroup.Item class="mt-0.5" {id} value={option.value} />
+
+ <Label class="grid cursor-pointer gap-0.5" for={id}>
+ <span class="text-label">{option.label}</span>
+
+ <span class="text-caption font-normal text-muted-foreground">{option.description}</span>
+ </Label>
+ </div>
+ {/each}
+ </RadioGroup.Root>
+
+ {#if exportsSettings}
+ <div transition:fade={{ duration: 150 }} class="grid gap-1">
+ <div class="flex items-center gap-2">
+ <Checkbox bind:checked={includeSensitiveData} id="export-sensitive" />
+
+ <Label class="text-body-sm font-normal" for="export-sensitive">
+ Include API keys and MCP server headers
+ </Label>
+ </div>
+
+ <p
+ class="text-caption {includeSensitiveData ? 'text-destructive' : 'text-muted-foreground'}"
+ >
+ {includeSensitiveData
+ ? 'The file will hold your credentials: share it with no one you do not trust.'
+ : 'Left out by default to keep your credentials safe.'}
+ </p>
+ </div>
+ {/if}
+
+ <Button class="justify-self-start" onclick={handleExport} variant="outline">
+ <Download class="mr-2 {ICON_CLASS_DEFAULT}" />
+
+ Export
+ </Button>
+ </SettingsGroup>
+ <SettingsGroup title="Delete">
<SettingsChatImportExportSection
IconComponent={Trash2}
buttonClass="justify-start justify-self-start md:w-auto"
@@ -291,35 +208,8 @@
titleClass="text-destructive"
/>
</SettingsGroup>
-
- <SettingsGroup title="Settings">
- <SettingsChatImportExportSection
- IconComponent={Download}
- buttonText="Export settings"
- description="Export your chat settings and preferences as a JSON file."
- onclick={handleSettingsExport}
- summary={{ items: [], show: showSettingsExportSummary, verb: 'Exported' }}
- title="Export"
- />
-
- <SettingsChatImportExportSection
- IconComponent={Upload}
- buttonText="Import settings"
- description="Import chat settings from a previously exported JSON file. This will merge with your existing settings."
- onclick={handleSettingsImport}
- summary={{ items: [], show: showSettingsImportSummary, verb: 'Imported' }}
- title="Import"
- />
- </SettingsGroup>
</div>
-<DialogExportSettings
- bind:includeSensitiveData
- bind:open={showSettingsExportDialog}
- onCancel={handleSettingsExportCancel}
- onConfirm={handleSettingsExportConfirm}
-/>
-
<DialogConversationSelection
bind:open={showExportDialog}
conversations={availableConversations}
@@ -329,15 +219,6 @@
onConfirm={handleExportConfirm}
/>
-<DialogConversationSelection
- bind:open={showImportDialog}
- conversations={availableConversations}
- {messageCountMap}
- mode={ConversationSelectionMode.IMPORT}
- onCancel={() => (showImportDialog = false)}
- onConfirm={handleImportConfirm}
-/>
-
<DialogConfirmation
bind:open={showDeleteDialog}
cancelText="Cancel"
diff --git a/ui/apps/chat/src/lib/constants/conversation-import.constants.ts b/ui/apps/chat/src/lib/constants/conversation-import.constants.ts
index ed500440a..c9ea089f6 100644
--- a/ui/apps/chat/src/lib/constants/conversation-import.constants.ts
+++ b/ui/apps/chat/src/lib/constants/conversation-import.constants.ts
@@ -1,3 +1,9 @@
// First bytes of every ZIP local file header ("PK"). Import detects an archive
// from these bytes rather than from the filename, which the OS may not preserve.
export const ZIP_MAGIC = [0x50, 0x4b];
+
+// The settings file inside a full backup ZIP, next to one JSONL file per conversation.
+export const SETTINGS_ARCHIVE_ENTRY = 'settings.json';
+
+// Filename of a full backup ZIP (conversations and settings), after its date.
+export const BACKUP_ARCHIVE_NAME = 'llama_chat_backup';
diff --git a/ui/apps/chat/src/lib/contexts/drop-import.context.ts b/ui/apps/chat/src/lib/contexts/drop-import.context.ts
new file mode 100644
index 000000000..9b1e0c459
--- /dev/null
+++ b/ui/apps/chat/src/lib/contexts/drop-import.context.ts
@@ -0,0 +1,18 @@
+import { getContext, setContext } from 'svelte';
+
+export interface DropImportContext {
+ /** Imports the dropped files that are Llama Chat exports and returns the ones that are not. */
+ importExports: (files: File[]) => Promise<File[]>;
+}
+
+const DROP_IMPORT_CONTEXT = Symbol('drop-import');
+
+/** Set by the root layout, which owns the import dialogs. */
+export function setDropImportContext(context: DropImportContext): void {
+ setContext(DROP_IMPORT_CONTEXT, context);
+}
+
+/** Undefined outside the app layout (e.g. in a story), where drops are only attached. */
+export function getDropImportContext(): DropImportContext | undefined {
+ return getContext<DropImportContext | undefined>(DROP_IMPORT_CONTEXT);
+}
diff --git a/ui/apps/chat/src/lib/contexts/index.ts b/ui/apps/chat/src/lib/contexts/index.ts
index 4aaec8148..8bf4ec08f 100644
--- a/ui/apps/chat/src/lib/contexts/index.ts
+++ b/ui/apps/chat/src/lib/contexts/index.ts
@@ -6,3 +6,5 @@ export {
} from './chat-message-actions.context';
export { getChatFormActionsContext, setChatFormActionsContext } from './chat-form-actions.context';
+
+export { getDropImportContext, setDropImportContext } from './drop-import.context';
diff --git a/ui/apps/chat/src/lib/enums/conversation-import.enums.ts b/ui/apps/chat/src/lib/enums/conversation-import.enums.ts
index c2cf99deb..4abf5018b 100644
--- a/ui/apps/chat/src/lib/enums/conversation-import.enums.ts
+++ b/ui/apps/chat/src/lib/enums/conversation-import.enums.ts
@@ -7,3 +7,10 @@ export enum SessionRecordType {
MESSAGE = 'message',
SESSION = 'session'
}
+
+/** What the Import/Export settings tab exports. */
+export enum DataExportScope {
+ ALL = 'all',
+ CONVERSATIONS = 'conversations',
+ SETTINGS = 'settings'
+}
diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts
index 510e3d18f..66d7b9496 100644
--- a/ui/apps/chat/src/lib/enums/index.ts
+++ b/ui/apps/chat/src/lib/enums/index.ts
@@ -31,7 +31,7 @@ export {
FileMentionEntryType
} from './chat.enums';
-export { SessionRecordType } from './conversation-import.enums';
+export { DataExportScope, SessionRecordType } from './conversation-import.enums';
export { BooleanString } from './boolean-string.enums';
diff --git a/ui/apps/chat/src/lib/hooks/use-chat-screen-drag-and-drop.svelte.ts b/ui/apps/chat/src/lib/hooks/use-chat-screen-drag-and-drop.svelte.ts
index a4dd5ef72..898754c01 100644
--- a/ui/apps/chat/src/lib/hooks/use-chat-screen-drag-and-drop.svelte.ts
+++ b/ui/apps/chat/src/lib/hooks/use-chat-screen-drag-and-drop.svelte.ts
@@ -2,11 +2,13 @@
* Drag-and-drop state machine for the ChatScreen.
*
* Tracks pointer enter/leave nesting so the overlay stays visible while the
- * cursor traverses child elements, then routes the dropped files either to
- * the active message-edit handler (if a message is being edited) or to the
- * caller's onDrop callback.
+ * cursor traverses child elements. Dropped Llama Chat exports go to the
+ * importer; the other files go either to the active message-edit handler (if
+ * a message is being edited) or to the caller's onDrop callback. Every drag
+ * event stops here, so the app-wide import overlay stays out of the chat.
*/
+import { getDropImportContext } from '#lib/contexts/index.ts';
import { chatStore } from '#lib/stores/index.ts';
interface UseChatScreenDragAndDropOptions {
@@ -18,8 +20,11 @@ export function useChatScreenDragAndDrop(options: UseChatScreenDragAndDropOption
let dragCounter = $state(0);
let isDragOver = $state(false);
+ const dropImport = getDropImportContext();
+
function handleDragEnter(event: DragEvent) {
event.preventDefault();
+ event.stopPropagation();
dragCounter++;
if (event.dataTransfer?.types.includes('Files')) {
@@ -29,6 +34,7 @@ export function useChatScreenDragAndDrop(options: UseChatScreenDragAndDropOption
function handleDragLeave(event: DragEvent) {
event.preventDefault();
+ event.stopPropagation();
dragCounter--;
if (dragCounter === 0) {
@@ -38,16 +44,21 @@ export function useChatScreenDragAndDrop(options: UseChatScreenDragAndDropOption
function handleDragOver(event: DragEvent) {
event.preventDefault();
+ event.stopPropagation();
}
async function handleDrop(event: DragEvent) {
event.preventDefault();
+ event.stopPropagation();
isDragOver = false;
dragCounter = 0;
if (!event.dataTransfer?.files) return;
- const files = Array.from(event.dataTransfer.files);
+ const dropped = Array.from(event.dataTransfer.files);
+ const files = dropImport ? await dropImport.importExports(dropped) : dropped;
+
+ if (files.length === 0) return;
if (chatStore.isEditing()) {
const handler = chatStore.getAddFilesHandler();
diff --git a/ui/apps/chat/src/lib/hooks/use-drop-import.svelte.ts b/ui/apps/chat/src/lib/hooks/use-drop-import.svelte.ts
new file mode 100644
index 000000000..1f037c55e
--- /dev/null
+++ b/ui/apps/chat/src/lib/hooks/use-drop-import.svelte.ts
@@ -0,0 +1,378 @@
+/**
+ * Global drag-and-drop import state machine.
+ *
+ * Tracks pointer enter/leave nesting so the overlay stays visible while the
+ * cursor traverses child elements, then routes dropped files to the right
+ * importer: settings files (JSON with a `config` key) get a diff preview,
+ * while conversation files (JSONL/ZIP/JSON) get a preview or the selection
+ * dialog before asking whether to open the result. The chat screen hands its
+ * drops over through the drop-import context and attaches what is left.
+ */
+
+import type { SettingsDiffEntry } from '#lib/components/app/dialogs/DialogSettingsImportPreview.svelte';
+import { SETTING_CONFIG_DEFAULT, SETTINGS_REGISTRY, ZIP_MAGIC } from '#lib/constants/index.ts';
+import { setDropImportContext } from '#lib/contexts/index.ts';
+import { FileExtensionText } from '#lib/enums/index.ts';
+import { ConversationTransferService } from '#lib/services/conversation-transfer.service.ts';
+import { RouterService } from '#lib/services/router.service.ts';
+import { conversationsStore } from '#lib/stores/conversations/index.svelte.ts';
+import { groupsStore } from '#lib/stores/groups.svelte.ts';
+import { settingsStore } from '#lib/stores/settings/index.svelte.ts';
+import type { SettingsConfigType, SettingsExportType } from '#lib/types/index.ts';
+import { createMessageCountMap } from '#lib/utils/index.ts';
+import { goto } from '$app/navigation';
+import { strFromU8 } from 'fflate';
+import { SvelteMap, SvelteSet } from 'svelte/reactivity';
+import { toast } from 'svelte-sonner';
+
+// only these can hold an export; anything else is never read
+const IMPORT_FILE_EXTENSIONS: string[] = [
+ FileExtensionText.JSON,
+ FileExtensionText.JSONL,
+ FileExtensionText.ZIP
+];
+
+type DroppedExport =
+ | { data: ExportedConversation[]; kind: 'conversations' }
+ | { data: SettingsExportType; kind: 'settings' };
+
+function isExportedConversation(item: unknown): item is ExportedConversation {
+ const candidate = item as Partial<ExportedConversation> | null;
+
+ return Boolean(candidate?.conv?.id) && Array.isArray(candidate?.messages);
+}
+
+/**
+ * Reads a dropped file as Llama Chat exports: a settings file (a JSON object
+ * with a `config` key), conversations (JSONL sessions or legacy JSON) or a ZIP
+ * of conversations, which a full backup adds the settings to. Returns nothing
+ * for any other file, which stays a plain file.
+ */
+async function readExports(file: File): Promise<DroppedExport[]> {
+ const name = file.name.toLowerCase();
+
+ if (!IMPORT_FILE_EXTENSIONS.some((extension) => name.endsWith(extension))) return [];
+
+ const exports: DroppedExport[] = [];
+ const bytes = new Uint8Array(await file.arrayBuffer());
+
+ try {
+ const settings = ZIP_MAGIC.every((byte, index) => bytes[index] === byte)
+ ? await ConversationTransferService.parseArchiveSettings(file)
+ : JSON.parse(strFromU8(bytes));
+
+ if (settings && typeof settings === 'object' && settings.config) {
+ exports.push({ data: settings as SettingsExportType, kind: 'settings' });
+ }
+ } catch {
+ // Not a single JSON value: JSONL sessions are checked below.
+ }
+
+ try {
+ const data = await ConversationTransferService.parseImportFile(file);
+
+ if (data.length > 0 && data.every(isExportedConversation)) {
+ exports.push({ data, kind: 'conversations' });
+ }
+ } catch {
+ // Not a conversation export.
+ }
+
+ return exports;
+}
+
+/**
+ * Collapses several exports of the same conversation (e.g. the same chat
+ * exported twice) to the most recently modified one, keeping the drop order.
+ */
+function keepNewestPerConversation(items: ExportedConversation[]): ExportedConversation[] {
+ const newest: Record<string, ExportedConversation> = {};
+
+ for (const item of items) {
+ const current = newest[item.conv.id];
+
+ if (!current || item.conv.lastModified > current.conv.lastModified) {
+ newest[item.conv.id] = item;
+ }
+ }
+
+ return items.filter((item) => newest[item.conv.id] === item);
+}
+
+function computeSettingsDiff(
+ current: SettingsConfigType,
+ imported: SettingsConfigType
+): SettingsDiffEntry[] {
+ const labels = new SvelteMap<string, string>();
+
+ for (const section of SETTINGS_REGISTRY) {
+ for (const setting of section.settings) {
+ labels.set(setting.key, setting.label);
+ }
+ }
+
+ // importing applies the file over the defaults, so a key the file leaves out goes back to its default
+ const next: SettingsConfigType = { ...SETTING_CONFIG_DEFAULT, ...imported };
+ const keys = new SvelteSet([...Object.keys(current), ...Object.keys(next)]);
+ const diff: SettingsDiffEntry[] = [];
+
+ for (const key of keys) {
+ const from = current[key];
+ const to = next[key];
+
+ if (from !== to) {
+ diff.push({ from, key, label: labels.get(key) ?? key, to });
+ }
+ }
+
+ return diff;
+}
+
+export function useDropImport() {
+ let dragCounter = $state(0);
+ let isDragOver = $state(false);
+
+ // All dialog state lives in one reactive object so it stays reactive when
+ // exposed through the hook and bound from the layout.
+ const ui = $state({
+ availableConversations: [] as DatabaseConversation[],
+ bulkMessageCountMap: new SvelteMap() as SvelteMap<string, number>,
+ fullImportData: [] as ExportedConversation[],
+ importedConversations: [] as DatabaseConversation[],
+ // The single conversation just imported, offered to open right away.
+ openImported: null as { alreadyInLibrary: boolean; conv: DatabaseConversation } | null,
+ previewData: null as ExportedConversation | null,
+ selectionMessageCountMap: new SvelteMap() as SvelteMap<string, number>,
+ settingsData: null as SettingsExportType | null,
+ settingsDiff: [] as SettingsDiffEntry[],
+ // Bulk result dialog: pick one of the imported conversations to open.
+ showOpenBulk: false,
+ // Asks whether to open the single conversation that was just imported.
+ showOpenImported: false,
+ // Single conversation preview dialog (confirm before importing).
+ showPreview: false,
+ // Selection dialog (the existing import flow) for multiple conversations.
+ showSelection: false,
+ // Settings import preview dialog (review diff before applying).
+ showSettingsPreview: false
+ });
+
+ // conversations of a full backup, shown once its settings preview closes
+ let pendingConversations: ExportedConversation[] | null = null;
+
+ setDropImportContext({ importExports });
+
+ function handleDragEnter(event: DragEvent) {
+ event.preventDefault();
+ dragCounter++;
+
+ if (event.dataTransfer?.types.includes('Files')) {
+ isDragOver = true;
+ }
+ }
+
+ function handleDragLeave(event: DragEvent) {
+ event.preventDefault();
+ dragCounter--;
+
+ if (dragCounter === 0) {
+ isDragOver = false;
+ }
+ }
+
+ function handleDragOver(event: DragEvent) {
+ event.preventDefault();
+ }
+
+ async function handleDrop(event: DragEvent) {
+ event.preventDefault();
+ isDragOver = false;
+ dragCounter = 0;
+
+ if (!event.dataTransfer?.files) return;
+
+ const rest = await importExports(Array.from(event.dataTransfer.files));
+
+ for (const file of rest) {
+ toast.error(`${file.name} is not a Llama Chat export`);
+ }
+ }
+
+ async function importExports(files: File[]): Promise<File[]> {
+ const exports = await Promise.all(files.map(readExports));
+ const allConversations: ExportedConversation[] = [];
+
+ for (const dropped of exports.flat()) {
+ if (dropped.kind === 'settings') {
+ ui.settingsData = dropped.data;
+ ui.settingsDiff = computeSettingsDiff(
+ $state.snapshot(settingsStore.config) as SettingsConfigType,
+ dropped.data.config
+ );
+ ui.showSettingsPreview = true;
+ } else {
+ allConversations.push(...dropped.data);
+ }
+ }
+
+ // a full backup holds both: its conversations wait until the settings preview is closed
+ if (allConversations.length > 0 && ui.showSettingsPreview) {
+ pendingConversations = allConversations;
+ } else if (allConversations.length > 0) {
+ showConversations(allConversations);
+ }
+
+ return files.filter((_, index) => exports[index].length === 0);
+ }
+
+ function showConversations(allConversations: ExportedConversation[]) {
+ const conversations = keepNewestPerConversation(allConversations);
+ const duplicates = allConversations.length - conversations.length;
+
+ if (duplicates > 0) {
+ toast.info(
+ duplicates === 1
+ ? 'The same conversation was dropped twice, keeping the newest copy'
+ : `${duplicates} conversations were dropped more than once, keeping the newest copies`
+ );
+ }
+
+ if (conversations.length === 1) {
+ ui.previewData = conversations[0];
+ ui.showPreview = true;
+ } else {
+ ui.fullImportData = conversations;
+ ui.availableConversations = conversations.map((item) => item.conv);
+ ui.selectionMessageCountMap = new SvelteMap(createMessageCountMap(conversations));
+ ui.showSelection = true;
+ }
+ }
+
+ async function confirmSettingsImport() {
+ if (!ui.settingsData) return;
+
+ const data = $state.snapshot(ui.settingsData) as SettingsExportType;
+
+ try {
+ settingsStore.importSettings(data);
+ closeSettingsPreview();
+ toast.success('Settings imported successfully');
+ } catch (err) {
+ console.error('Failed to import settings:', err);
+ toast.error('Failed to import settings');
+ }
+ }
+
+ function cancelSettingsImport() {
+ closeSettingsPreview();
+ }
+
+ function closeSettingsPreview() {
+ ui.showSettingsPreview = false;
+
+ if (pendingConversations) {
+ showConversations(pendingConversations);
+ pendingConversations = null;
+ }
+ }
+
+ async function confirmImportSingle() {
+ if (!ui.previewData) return;
+
+ // IndexedDB cannot clone the reactive proxy, so store a plain copy.
+ const data = $state.snapshot(ui.previewData) as ExportedConversation;
+
+ try {
+ const { skipped } = await conversationsStore.importConversationsData([data]);
+
+ // an import can add the groups its chats were in
+ await groupsStore.reload();
+
+ ui.showPreview = false;
+ ui.openImported = { alreadyInLibrary: skipped.length > 0, conv: data.conv };
+ ui.showOpenImported = true;
+ } catch (err) {
+ console.error('Failed to import conversation:', err);
+ toast.error('Failed to import conversation');
+ }
+ }
+
+ async function handleSelectionConfirm(selectedConversations: DatabaseConversation[]) {
+ try {
+ const selectedIds = new SvelteSet(selectedConversations.map((c) => c.id));
+ const selectedData = ($state.snapshot(ui.fullImportData) as ExportedConversation[]).filter(
+ (item) => selectedIds.has(item.conv.id)
+ );
+ const { imported, skipped } = await conversationsStore.importConversationsData(selectedData);
+
+ await groupsStore.reload();
+
+ // a conversation already in the library is left untouched, so the list shows what was written
+ if (skipped.length > 0) {
+ toast.info(
+ `Skipped ${skipped.length} conversation${skipped.length === 1 ? '' : 's'} already in your library`
+ );
+ }
+
+ ui.importedConversations = imported;
+ ui.bulkMessageCountMap = new SvelteMap(createMessageCountMap(selectedData));
+ ui.showSelection = false;
+ ui.showOpenBulk = imported.length > 0;
+ } catch (err) {
+ console.error('Import failed:', err);
+ toast.error('Failed to import conversations');
+ }
+ }
+
+ function openConversation(conversation: DatabaseConversation) {
+ ui.showOpenBulk = false;
+ goto(RouterService.chat(conversation.id));
+ }
+
+ function confirmOpenImported() {
+ const imported = ui.openImported;
+
+ ui.showOpenImported = false;
+
+ if (imported) goto(RouterService.chat(imported.conv.id));
+ }
+
+ function cancelOpenImported() {
+ ui.showOpenImported = false;
+ }
+
+ function cancelPreview() {
+ ui.showPreview = false;
+ }
+
+ function cancelBulk() {
+ ui.showOpenBulk = false;
+ }
+
+ function cancelSelection() {
+ ui.showSelection = false;
+ }
+
+ return {
+ cancelBulk,
+ cancelOpenImported,
+ cancelPreview,
+ cancelSelection,
+ cancelSettingsImport,
+ confirmImportSingle,
+ confirmOpenImported,
+ confirmSettingsImport,
+ dragHandlers: {
+ dragenter: handleDragEnter,
+ dragleave: handleDragLeave,
+ dragover: handleDragOver,
+ drop: handleDrop
+ },
+ handleSelectionConfirm,
+ get isDragOver() {
+ return isDragOver;
+ },
+ openConversation,
+ ui
+ };
+}
diff --git a/ui/apps/chat/src/lib/services/conversation-transfer.service.ts b/ui/apps/chat/src/lib/services/conversation-transfer.service.ts
index 065e40a63..b48d291d9 100644
--- a/ui/apps/chat/src/lib/services/conversation-transfer.service.ts
+++ b/ui/apps/chat/src/lib/services/conversation-transfer.service.ts
@@ -6,13 +6,20 @@
* DB access and store refreshes stay in conversationsStore.
*/
-import { EXPORT_CONV, NEWLINE, ZIP_MAGIC } from '#lib/constants/index.ts';
+import {
+ BACKUP_ARCHIVE_NAME,
+ EXPORT_CONV,
+ NEWLINE,
+ SETTINGS_ARCHIVE_ENTRY,
+ ZIP_MAGIC
+} from '#lib/constants/index.ts';
import {
FileExtensionText,
MimeTypeApplication,
MimeTypeText,
SessionRecordType
} from '#lib/enums/index.ts';
+import type { SettingsExportType } from '#lib/types/index.ts';
import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate';
export class ConversationTransferService {
@@ -40,11 +47,15 @@ export class ConversationTransferService {
/**
* Triggers a browser download of multiple conversations as a `.zip`, one
- * `.jsonl` file per conversation.
+ * `.jsonl` file per conversation, plus the settings when given (a full backup).
* @param data - The conversations to export
+ * @param settings - Settings to add as {@link SETTINGS_ARCHIVE_ENTRY}
*/
- static downloadConversationsArchive(data: ExportedConversation[]): void {
- if (data.length === 0) {
+ static downloadConversationsArchive(
+ data: ExportedConversation[],
+ settings?: SettingsExportType
+ ): void {
+ if (data.length === 0 && !settings) {
console.error('Invalid data: no conversations to export');
return;
@@ -74,13 +85,32 @@ export class ConversationTransferService {
files[entryName] = strToU8(ConversationTransferService.serializeSessionToJsonl(session));
}
- const archiveName = `${new Date().toISOString().split(EXPORT_CONV.ISO_DATE_TIME_SEPARATOR)[0]}_conversations${FileExtensionText.ZIP}`;
+ if (settings) {
+ files[SETTINGS_ARCHIVE_ENTRY] = strToU8(JSON.stringify(settings, null, 2));
+ }
+
+ const date = new Date().toISOString().split(EXPORT_CONV.ISO_DATE_TIME_SEPARATOR)[0];
+ const archiveName = `${date}_${settings ? BACKUP_ARCHIVE_NAME : 'conversations'}${FileExtensionText.ZIP}`;
const zipped = zipSync(files);
const blob = new Blob([zipped], { type: MimeTypeApplication.ZIP });
ConversationTransferService.triggerDownload(blob, archiveName);
}
+ /**
+ * Triggers a browser download of the settings as a `.json` file.
+ * @param settings - The settings export
+ */
+ static downloadSettingsFile(settings: SettingsExportType): void {
+ const date = new Date().toISOString().split(EXPORT_CONV.ISO_DATE_TIME_SEPARATOR)[0];
+ const blob = new Blob([JSON.stringify(settings, null, 2)], { type: MimeTypeApplication.JSON });
+
+ ConversationTransferService.triggerDownload(
+ blob,
+ `llama_settings_${date}${FileExtensionText.JSON}`
+ );
+ }
+
/**
* Generates a sanitized filename for a conversation export
* @param conversation - The conversation metadata
@@ -109,6 +139,27 @@ export class ConversationTransferService {
return `${formattedDate}_conv_${trimmedConvId}_${sanitizedName}${FileExtensionText.JSONL}`;
}
+ /**
+ * Reads the settings of a full backup ZIP, if the file is one.
+ * @param file - A dropped or picked file
+ * @returns The settings export, or null when the file is no ZIP or has none
+ */
+ static async parseArchiveSettings(file: File): Promise<SettingsExportType | null> {
+ const bytes = new Uint8Array(await file.arrayBuffer());
+
+ if (!ZIP_MAGIC.every((byte, index) => bytes[index] === byte)) return null;
+
+ const entry = unzipSync(bytes, { filter: ({ name }) => name === SETTINGS_ARCHIVE_ENTRY })[
+ SETTINGS_ARCHIVE_ENTRY
+ ];
+
+ if (!entry) return null;
+
+ const parsed = JSON.parse(strFromU8(entry));
+
+ return parsed?.config ? (parsed as SettingsExportType) : null;
+ }
+
/**
* Parses an import file into conversations, accepting the current JSONL and
* ZIP formats as well as the legacy JSON format. The format comes from the
diff --git a/ui/apps/chat/src/routes/+layout.svelte b/ui/apps/chat/src/routes/+layout.svelte
index b66a3ecfc..31f05f5c1 100644
--- a/ui/apps/chat/src/routes/+layout.svelte
+++ b/ui/apps/chat/src/routes/+layout.svelte
@@ -1,7 +1,17 @@
<script lang="ts">
import '../app.css';
import * as Tooltip from '@ggml-org/llama-ui/ui/tooltip';
- import { GlassKey, MenuIcon, SidebarNavigation } from '#lib/components/app/index.ts';
+ import {
+ DialogConfirmation,
+ DialogConversationSelection,
+ DialogImportConversationPreview,
+ DialogImportConversationsResult,
+ DialogSettingsImportPreview,
+ DropImportOverlay,
+ GlassKey,
+ MenuIcon,
+ SidebarNavigation
+ } from '#lib/components/app/index.ts';
import { PwaMetaTags, PwaRefreshAlert } from '#lib/components/pwa/index.ts';
import {
BOX_BORDER,
@@ -15,6 +25,7 @@
SETTINGS_KEYS,
TOOLTIP_DELAY_DURATION
} from '#lib/constants/index.ts';
+ import { useDropImport } from '#lib/hooks/use-drop-import.svelte.ts';
import { useKeyboardShortcuts } from '#lib/hooks/use-keyboard-shortcuts.svelte.ts';
import { usePwa } from '#lib/hooks/use-pwa.svelte.ts';
import { useSidebarReveal } from '#lib/hooks/use-sidebar-reveal.svelte.ts';
@@ -152,6 +163,9 @@
uiStore.rememberModelsReturnRoute();
});
+ // Global drag-and-drop import (works on any route)
+ const dropImport = useDropImport();
+
// Global keyboard shortcuts
const { handleKeydown } = useKeyboardShortcuts({
editActiveConversation: () => chatSidebar?.editActiveConversation?.(),
@@ -318,7 +332,13 @@
</svelte:head>
<svelte:window bind:innerHeight bind:innerWidth onkeydown={handleKeydown} />
-<svelte:document onvisibilitychange={handleVisibilityChange} />
+<svelte:document
+ ondragenter={dropImport.dragHandlers.dragenter}
+ ondragleave={dropImport.dragHandlers.dragleave}
+ ondragover={dropImport.dragHandlers.dragover}
+ ondrop={dropImport.dragHandlers.drop}
+ onvisibilitychange={handleVisibilityChange}
+/>
<Tooltip.Provider delayDuration={TOOLTIP_DELAY_DURATION}>
<!-- clip, not hide: the page slid aside for the phone sidebar must not widen the document,
@@ -442,6 +462,55 @@
<Toaster closeButton richColors />
+ {#if dropImport.isDragOver}
+ <DropImportOverlay />
+ {/if}
+
+ <DialogConversationSelection
+ bind:open={dropImport.ui.showSelection}
+ conversations={dropImport.ui.availableConversations}
+ messageCountMap={dropImport.ui.selectionMessageCountMap}
+ mode="import"
+ onCancel={dropImport.cancelSelection}
+ onConfirm={dropImport.handleSelectionConfirm}
+ />
+
+ <DialogSettingsImportPreview
+ bind:open={dropImport.ui.showSettingsPreview}
+ diff={dropImport.ui.settingsDiff}
+ onCancel={dropImport.cancelSettingsImport}
+ onConfirm={dropImport.confirmSettingsImport}
+ />
+
+ <DialogImportConversationPreview
+ bind:open={dropImport.ui.showPreview}
+ messages={dropImport.ui.previewData?.messages}
+ onCancel={dropImport.cancelPreview}
+ onConfirm={dropImport.confirmImportSingle}
+ />
+
+ <DialogConfirmation
+ bind:open={dropImport.ui.showOpenImported}
+ cancelText="Not now"
+ confirmText="Open"
+ description={dropImport.ui.openImported?.alreadyInLibrary
+ ? `"${dropImport.ui.openImported.conv.name}" was already in your library. Open it now?`
+ : `"${dropImport.ui.openImported?.conv.name ?? ''}" is now in your library. Open it now?`}
+ onCancel={dropImport.cancelOpenImported}
+ onConfirm={dropImport.confirmOpenImported}
+ title={dropImport.ui.openImported?.alreadyInLibrary
+ ? 'Already in your library'
+ : 'Conversation imported'}
+ />
+
+ <DialogImportConversationsResult
+ bind:open={dropImport.ui.showOpenBulk}
+ conversations={dropImport.ui.importedConversations}
+ messageCountMap={dropImport.ui.bulkMessageCountMap}
+ onClose={dropImport.cancelBulk}
+ onOpen={dropImport.openConversation}
+ />
+
<!-- a debug tool, kept with the tests and loaded on demand, so it stays out of the production bundle -->
{#if import.meta.env.DEV && import.meta.env.VITE_DEBUG}
{#await import('../../tests/debug/ViewportProbe.svelte') then { default: ViewportProbe }}