+
+
diff --git a/ui/apps/chat/src/lib/components/app/library/index.ts b/ui/apps/chat/src/lib/components/app/library/index.ts
index 73936c399ed7..b47bc2298111 100644
--- a/ui/apps/chat/src/lib/components/app/library/index.ts
+++ b/ui/apps/chat/src/lib/components/app/library/index.ts
@@ -1,9 +1,12 @@
/**
* LIBRARY
*
- * The Library page: the prompts kept in the app, as cards that are sent in a
- * chat or used as its system message.
+ * The Library page, in tabs: the prompts kept in the app, as cards that are sent
+ * in a chat or used as its system message, and the files of every conversation
+ * in a grid, each leading back to the message it was sent in.
*/
+export { default as LibraryAttachments } from './LibraryAttachments.svelte';
+export { default as LibraryAttachmentTile } from './LibraryAttachmentTile.svelte';
export { default as LibraryPromptCard } from './LibraryPromptCard.svelte';
export { default as LibraryPrompts } from './LibraryPrompts.svelte';
diff --git a/ui/apps/chat/src/lib/constants/library.constants.ts b/ui/apps/chat/src/lib/constants/library.constants.ts
index b931867010b4..6704e29a44cd 100644
--- a/ui/apps/chat/src/lib/constants/library.constants.ts
+++ b/ui/apps/chat/src/lib/constants/library.constants.ts
@@ -1,3 +1,27 @@
+import FileIcon from '@lucide/svelte/icons/file';
+import AudioIcon from '@lucide/svelte/icons/file-headphone';
+import FileTextIcon from '@lucide/svelte/icons/file-text';
+import ImageIcon from '@lucide/svelte/icons/image';
+import VideoIcon from '@lucide/svelte/icons/video';
+import { AttachmentType, LibraryTab } from '#lib/enums/index.ts';
+import type { Component } from 'svelte';
+
+/** The Library's tabs, in order. */
+export const LIBRARY_TABS: { label: string; search: string; value: LibraryTab }[] = [
+ { label: 'Prompts', search: 'Search prompts', value: LibraryTab.PROMPTS },
+ { label: 'Attachments', search: 'Search attachments', value: LibraryTab.ATTACHMENTS }
+];
+
+/** The mark of a file in the Library's attachments, by its kind. */
+export const LIBRARY_ATTACHMENT_ICONS: Partial> = {
+ [AttachmentType.AUDIO]: AudioIcon,
+ [AttachmentType.IMAGE]: ImageIcon,
+ [AttachmentType.LEGACY_CONTEXT]: FileTextIcon,
+ [AttachmentType.PDF]: FileIcon,
+ [AttachmentType.TEXT]: FileTextIcon,
+ [AttachmentType.VIDEO]: VideoIcon
+};
+
/** Id of the library as a source of prompts. */
export const PROMPT_LIBRARY_SOURCE_ID = 'library';
@@ -12,3 +36,21 @@ export const PROMPT_SEARCH_MIN_ITEMS = 4;
export const PROMPT_NAME_MAX_LENGTH = 200;
export const PROMPT_DESCRIPTION_MAX_LENGTH = 300;
+
+/** Messages read per page of the Library's attachments: enough to fill a screen. */
+export const LIBRARY_ATTACHMENTS_PAGE_SIZE = 24;
+
+/** The narrowest a column of the attachments grid gets, which sets how many fit. */
+export const LIBRARY_ATTACHMENTS_COLUMN_MIN_WIDTH_PX = 220;
+
+/** A phone still shows the files side by side. */
+export const LIBRARY_ATTACHMENTS_MIN_COLUMNS = 2;
+
+/** How long typing rests before the attachments are searched. */
+export const LIBRARY_ATTACHMENTS_SEARCH_DEBOUNCE_MS = 200;
+
+/** How much of a text attachment its tile shows. */
+export const LIBRARY_TEXT_PREVIEW_CHARS = 600;
+
+/** How far before the end of the grid the next page starts loading. */
+export const LIBRARY_LOAD_MORE_MARGIN = '600px';
diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts
index d2c26393e459..83f14498f53e 100644
--- a/ui/apps/chat/src/lib/enums/index.ts
+++ b/ui/apps/chat/src/lib/enums/index.ts
@@ -137,3 +137,5 @@ export { ChatFormVoiceState, VoiceInputMode, VoiceMode, VoiceModelRole } from '.
export { AddSheetPage, ModelsSheetPage, SettingsSheetPage } from './sheet.enums';
export { PromptDrift } from './prompt.enums';
+
+export { LibraryTab } from './library.enums';
diff --git a/ui/apps/chat/src/lib/enums/library.enums.ts b/ui/apps/chat/src/lib/enums/library.enums.ts
new file mode 100644
index 000000000000..205ccbb04368
--- /dev/null
+++ b/ui/apps/chat/src/lib/enums/library.enums.ts
@@ -0,0 +1,5 @@
+/** The part of the Library a tab shows. */
+export enum LibraryTab {
+ ATTACHMENTS = 'attachments',
+ PROMPTS = 'prompts'
+}
diff --git a/ui/apps/chat/src/lib/hooks/use-stick-to-bottom.svelte.ts b/ui/apps/chat/src/lib/hooks/use-stick-to-bottom.svelte.ts
index 1ae4f6920f62..474cd2719191 100644
--- a/ui/apps/chat/src/lib/hooks/use-stick-to-bottom.svelte.ts
+++ b/ui/apps/chat/src/lib/hooks/use-stick-to-bottom.svelte.ts
@@ -211,6 +211,14 @@ export class StickToBottom {
this.measure();
}
+ /** Stops following, for a landing somewhere else than the bottom: a jump to a message. */
+ release(): void {
+ this.stopGlide();
+ this.glideSettleUntil = 0;
+ this.stick = false;
+ this.syncAnchor();
+ }
+
scrollToBottom(behavior: ScrollBehavior = 'auto'): void {
const el = this.container;
diff --git a/ui/apps/chat/src/lib/services/database.service.ts b/ui/apps/chat/src/lib/services/database.service.ts
index c5f13ac1f348..8c122cae8e9a 100644
--- a/ui/apps/chat/src/lib/services/database.service.ts
+++ b/ui/apps/chat/src/lib/services/database.service.ts
@@ -613,6 +613,28 @@ export class DatabaseService {
return result;
}
+ /**
+ * Reads the messages `holds` accepts, newest first, a page at a time, so a long history
+ * is never read as a whole.
+ *
+ * @param holds - Whether a message belongs in the result
+ * @param limit - How many messages to return at most
+ * @param upTo - Only messages this old or older, to go on from the last one of a page
+ */
+ static async getMessagesHolding(
+ holds: (message: DatabaseMessage) => boolean,
+ limit: number,
+ upTo?: number
+ ): Promise {
+ const messages = db[IDXDB_TABLES.messages];
+ const range =
+ upTo === undefined
+ ? messages.orderBy('timestamp')
+ : messages.where('timestamp').belowOrEqual(upTo);
+
+ return await range.reverse().filter(holds).limit(limit).toArray();
+ }
+
/**
* Gets the messages written at or after `timestamp`, in any conversation.
*
diff --git a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts
index 85dfab8ea3f4..8353a929386b 100644
--- a/ui/apps/chat/src/lib/stores/chat/index.svelte.ts
+++ b/ui/apps/chat/src/lib/stores/chat/index.svelte.ts
@@ -82,6 +82,8 @@ class ChatStore implements ChatStreamHost, ChatFlowsHost {
pendingSystemMessage = $state(null);
/** The prompt the pending system message is made from, if any. */
pendingSystemPrompt = $state(null);
+ /** A message its conversation opens at, in place of the bottom, the next time it is opened. */
+ scrollTarget = $state<{ convId: string; messageId: string } | null>(null);
// resumable stream connection state for the active conversation
// streaming -> bytes flowing normally, resuming -> waiting on /v1/stream reconnect, lost -> unrecoverable
streamConnectionState = $state(StreamConnectionState.STREAMING);
diff --git a/ui/apps/chat/src/lib/stores/index.ts b/ui/apps/chat/src/lib/stores/index.ts
index 1fd9f9a520b4..be73c1f63a32 100644
--- a/ui/apps/chat/src/lib/stores/index.ts
+++ b/ui/apps/chat/src/lib/stores/index.ts
@@ -47,6 +47,9 @@ export { modelsStore } from './models/index.svelte';
// MODELS DISCOVER (HuggingFace browse state for the discover dialog)
export { modelsDiscoverStore } from './models-discover/index.svelte';
+// LIBRARY ATTACHMENTS (the files of every conversation, read a page at a time)
+export { libraryAttachmentsStore } from './library-attachments.svelte';
+
// PROMPTS (the library's prompts, and every source of prompts)
export { promptsStore } from './prompts.svelte';
diff --git a/ui/apps/chat/src/lib/stores/library-attachments.svelte.ts b/ui/apps/chat/src/lib/stores/library-attachments.svelte.ts
new file mode 100644
index 000000000000..fb1a1be3c14d
--- /dev/null
+++ b/ui/apps/chat/src/lib/stores/library-attachments.svelte.ts
@@ -0,0 +1,85 @@
+/**
+ * libraryAttachmentsStore - The files of every conversation, for the Library
+ *
+ * Reads the messages that hold files a page at a time, newest first, so the
+ * Library never loads a whole history at once. What it read is dropped when
+ * the Library is left: the files stay in the database.
+ */
+
+import { LIBRARY_ATTACHMENTS_PAGE_SIZE } from '#lib/constants/index.ts';
+import { DatabaseService } from '#lib/services/database.service.ts';
+import { type LibraryAttachment, libraryAttachmentsOf } from '#lib/utils/index.ts';
+
+class LibraryAttachmentsStore {
+ /** Whether older messages may still hold files that match. */
+ hasMore = $state(true);
+ isLoading = $state(false);
+ /** The files read so far, newest first. */
+ items = $state.raw([]);
+
+ private messageIds = new Set();
+ private oldest: number | undefined;
+ private query = '';
+ // a search or a reset that starts while a page loads makes that page stale
+ private run = 0;
+
+ /** Drops what was read, to free the files' data once the Library is left. */
+ clear(): void {
+ this.run++;
+ this.messageIds = new Set();
+ this.oldest = undefined;
+ this.items = [];
+ this.hasMore = true;
+ this.isLoading = false;
+ }
+
+ /** Reads the next page of files. Does nothing while a page loads, or when none are left. */
+ async loadMore(): Promise {
+ if (this.isLoading || !this.hasMore) return;
+
+ const run = this.run;
+ const query = this.query;
+
+ this.isLoading = true;
+
+ try {
+ const messages = await DatabaseService.getMessagesHolding(
+ (message) => libraryAttachmentsOf(message, query).length > 0,
+ LIBRARY_ATTACHMENTS_PAGE_SIZE,
+ this.oldest
+ );
+
+ if (run !== this.run) return;
+
+ // the page starts at the last timestamp of the one before, so that messages
+ // sent in the same millisecond are not skipped: the ones already read come again
+ const fresh = messages.filter((message) => !this.messageIds.has(message.id));
+
+ for (const message of fresh) this.messageIds.add(message.id);
+
+ this.oldest = messages.at(-1)?.timestamp ?? this.oldest;
+ this.items = [
+ ...this.items,
+ ...fresh.flatMap((message) => libraryAttachmentsOf(message, query))
+ ];
+ this.hasMore = messages.length === LIBRARY_ATTACHMENTS_PAGE_SIZE && fresh.length > 0;
+ } catch (error) {
+ if (run !== this.run) return;
+
+ console.error('Failed to read the attachments of conversations:', error);
+ this.hasMore = false;
+ } finally {
+ if (run === this.run) this.isLoading = false;
+ }
+ }
+
+ /** Starts over with the files whose name holds `query`, from the newest message. */
+ async search(query: string): Promise {
+ this.clear();
+ this.query = query;
+
+ await this.loadMore();
+ }
+}
+
+export const libraryAttachmentsStore = new LibraryAttachmentsStore();
diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts
index 9febda6eb9d0..312502d0f7c8 100644
--- a/ui/apps/chat/src/lib/utils/index.ts
+++ b/ui/apps/chat/src/lib/utils/index.ts
@@ -250,6 +250,25 @@ export {
export { resolveTabTarget, resolveTabView, type TabView } from './chat-tabs';
+// The files of conversations as the Library lists them
+export {
+ attachmentBlob,
+ attachmentImage,
+ attachmentText,
+ downloadAttachment,
+ isFileAttachment,
+ libraryAttachmentsOf,
+ type LibraryAttachment
+} from './library-attachments';
+
+// A jump to a message of the open conversation
+export {
+ findMessageRowId,
+ MESSAGE_ROW_ATTRIBUTE,
+ messageRow,
+ scrollToMessageRow
+} from './message-jump';
+
// Library prompts: as attachments of the chat form, and against the system messages made from them
export { isPromptAttachment, promptLinkExtra, promptToUploadedFile } from './prompt-attachment';
export { getPromptDrift } from './prompt-drift';
diff --git a/ui/apps/chat/src/lib/utils/library-attachments.ts b/ui/apps/chat/src/lib/utils/library-attachments.ts
new file mode 100644
index 000000000000..aae2879a63bf
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/library-attachments.ts
@@ -0,0 +1,123 @@
+import { createBase64DataUrl } from './data-url';
+import { base64ToBytes } from '@ggml-org/llama-voice';
+import { AttachmentType, MimeTypeApplication, MimeTypeText } from '#lib/enums/index.ts';
+import type { DatabaseMessage, DatabaseMessageExtra } from '#lib/types/database.js';
+
+/** A file of a conversation as the Library lists it, with the message it was sent in. */
+export interface LibraryAttachment {
+ attachment: DatabaseMessageExtra;
+ convId: string;
+ /** Stable across pages: the message's id and the file's place in it. */
+ id: string;
+ messageId: string;
+ /** When its message was sent. */
+ timestamp: number;
+}
+
+const FILE_ATTACHMENT_TYPES: readonly AttachmentType[] = [
+ AttachmentType.AUDIO,
+ AttachmentType.IMAGE,
+ AttachmentType.LEGACY_CONTEXT,
+ AttachmentType.PDF,
+ AttachmentType.TEXT,
+ AttachmentType.VIDEO
+];
+
+/** Whether an extra is a file: an image, audio clip, video, PDF or text. Prompts and MCP resources are not. */
+export function isFileAttachment(extra: DatabaseMessageExtra): boolean {
+ return FILE_ATTACHMENT_TYPES.includes(extra.type);
+}
+
+/**
+ * The files of a message, in the order they were attached. With a query, only
+ * the ones whose name holds it, ignoring case.
+ */
+export function libraryAttachmentsOf(message: DatabaseMessage, query = ''): LibraryAttachment[] {
+ const search = query.trim().toLowerCase();
+
+ return (message.extra ?? []).flatMap((attachment, index) =>
+ isFileAttachment(attachment) && attachment.name.toLowerCase().includes(search)
+ ? [
+ {
+ attachment,
+ convId: message.convId,
+ id: `${message.id}:${index}`,
+ messageId: message.id,
+ timestamp: message.timestamp
+ }
+ ]
+ : []
+ );
+}
+
+/** An image to draw for a file: the image itself, or the first page of a PDF sent as images. */
+export function attachmentImage(attachment: DatabaseMessageExtra): string | undefined {
+ if (attachment.type === AttachmentType.IMAGE) return attachment.base64Url;
+
+ if (attachment.type === AttachmentType.PDF && attachment.processedAsImages) {
+ return attachment.images?.[0];
+ }
+
+ return undefined;
+}
+
+/** The text of a file that has some to show or copy: a text file, or a PDF read as text. */
+export function attachmentText(attachment: DatabaseMessageExtra): string | undefined {
+ if (
+ attachment.type === AttachmentType.TEXT ||
+ attachment.type === AttachmentType.LEGACY_CONTEXT
+ ) {
+ return attachment.content;
+ }
+
+ return undefined;
+}
+
+/** A file's content as a blob to save, or null for an extra that is not a file. */
+export function attachmentBlob(attachment: DatabaseMessageExtra): Blob | null {
+ switch (attachment.type) {
+ case AttachmentType.AUDIO:
+ case AttachmentType.VIDEO:
+ return new Blob([base64ToBytes(attachment.base64Data)], { type: attachment.mimeType });
+ case AttachmentType.IMAGE:
+ // stored as a data URL, whose header names the type
+ return dataUrlBlob(attachment.base64Url);
+ case AttachmentType.LEGACY_CONTEXT:
+ case AttachmentType.TEXT:
+ return new Blob([attachment.content], { type: MimeTypeText.PLAIN });
+ case AttachmentType.PDF:
+ return dataUrlBlob(createBase64DataUrl(MimeTypeApplication.PDF, attachment.base64Data));
+ default:
+ return null;
+ }
+}
+
+/** Saves a file to the device under its own name. */
+export function downloadAttachment(attachment: DatabaseMessageExtra): void {
+ const blob = attachmentBlob(attachment);
+
+ if (!blob) return;
+
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement('a');
+
+ link.href = url;
+ link.download = attachment.name;
+ document.body.appendChild(link);
+ link.click();
+ document.body.removeChild(link);
+ URL.revokeObjectURL(url);
+}
+
+const DATA_URL_BASE64_MARKER = ';base64,';
+const DATA_URL_PREFIX = 'data:';
+
+function dataUrlBlob(dataUrl: string): Blob | null {
+ const marker = dataUrl.indexOf(DATA_URL_BASE64_MARKER);
+
+ if (!dataUrl.startsWith(DATA_URL_PREFIX) || marker < 0) return null;
+
+ return new Blob([base64ToBytes(dataUrl.slice(marker + DATA_URL_BASE64_MARKER.length))], {
+ type: dataUrl.slice(DATA_URL_PREFIX.length, marker)
+ });
+}
diff --git a/ui/apps/chat/src/lib/utils/message-jump.ts b/ui/apps/chat/src/lib/utils/message-jump.ts
new file mode 100644
index 000000000000..ba04660d8790
--- /dev/null
+++ b/ui/apps/chat/src/lib/utils/message-jump.ts
@@ -0,0 +1,76 @@
+import type { DatabaseMessage } from '#lib/types/database.js';
+
+/** Marks a message's row in the conversation, so a jump can find it. */
+export const MESSAGE_ROW_ATTRIBUTE = 'data-message-id';
+
+/** How long the rows' heights must rest before a jump lets go of its row. */
+const JUMP_QUIET_MS = 1000;
+/** What the reader does to take the scroll back from a jump. */
+const JUMP_CANCEL_EVENTS = ['wheel', 'touchstart', 'pointerdown', 'keydown'] as const;
+
+/**
+ * The id of the row that shows a message: its own, or for a message drawn inside
+ * another's row (a tool result in the turn that called it) the nearest message
+ * before it that has a row. Null when no row shows it.
+ */
+export function findMessageRowId(
+ messages: DatabaseMessage[],
+ messageId: string,
+ hasRow: (id: string) => boolean
+): string | null {
+ const byId = new Map(messages.map((message) => [message.id, message]));
+
+ let current = byId.get(messageId);
+
+ while (current) {
+ if (hasRow(current.id)) return current.id;
+
+ current = current.parent ? byId.get(current.parent) : undefined;
+ }
+
+ return null;
+}
+
+/** The row of a message in the open conversation, if it has one. */
+export function messageRow(messageId: string): HTMLElement | null {
+ return document.querySelector(
+ `[${MESSAGE_ROW_ATTRIBUTE}="${CSS.escape(messageId)}"]`
+ );
+}
+
+/**
+ * Brings a row to the top of the view and holds it there while the list settles:
+ * the rows around it are placeholders until they come near, and each one that
+ * mounts takes its real height and moves the rest. The row is put back whenever
+ * the list changes size, before the frame is painted, until the sizes rest or
+ * the reader scrolls, presses or types. Returns a function that ends the hold.
+ */
+export function scrollToMessageRow(row: HTMLElement): () => void {
+ let quietTimer: ReturnType | undefined;
+
+ const stop = () => {
+ observer.disconnect();
+ clearTimeout(quietTimer);
+
+ for (const type of JUMP_CANCEL_EVENTS) {
+ window.removeEventListener(type, stop, { capture: true });
+ }
+ };
+ const land = () => {
+ row.scrollIntoView({ block: 'start' });
+ clearTimeout(quietTimer);
+ quietTimer = setTimeout(stop, JUMP_QUIET_MS);
+ };
+ // the rows' container grows and shrinks with every row in it
+ const observer = new ResizeObserver(land);
+
+ for (const type of JUMP_CANCEL_EVENTS) {
+ window.addEventListener(type, stop, { capture: true, passive: true });
+ }
+
+ if (row.parentElement) observer.observe(row.parentElement);
+
+ land();
+
+ return stop;
+}
diff --git a/ui/apps/chat/src/routes/library/+page.svelte b/ui/apps/chat/src/routes/library/+page.svelte
index c3181a518c28..d1e9fdb3913f 100644
--- a/ui/apps/chat/src/routes/library/+page.svelte
+++ b/ui/apps/chat/src/routes/library/+page.svelte
@@ -1,11 +1,16 @@
@@ -20,18 +25,45 @@
Library
- The prompts you reuse: send one in a chat, or use it as a chat's system message.
+ The prompts you reuse and the files of your chats, in one place.
-
+ {/if}
-
+ (tab = value as LibraryTab)} value={tab}>
+