diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/LazyChatMessage.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/LazyChatMessage.svelte index 4c1c77e33117..d41b185d55e6 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/LazyChatMessage.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/LazyChatMessage.svelte @@ -3,6 +3,7 @@ import { MessageType } from '#lib/enums/index.ts'; import { chatStore } from '#lib/stores/index.ts'; import type { ChatMessageActions } from '#lib/types/index.ts'; + import { MESSAGE_ROW_ATTRIBUTE } from '#lib/utils/index.ts'; interface Props { chatActions: ChatMessageActions; @@ -78,6 +79,7 @@
message.id === messageId)) { + const all = await conversationsStore.getConversationMessages(convId); + + // only a message the conversation still holds names a branch to switch to + if (all.some((message) => message.id === messageId)) { + await conversationsStore.navigateToSibling(messageId); + } + } + + await tick(); + + const rowId = findMessageRowId( + conversationsStore.activeMessages, + messageId, + (id) => messageRow(id) !== null + ); + const row = rowId ? messageRow(rowId) : null; + + if (!row) { + stick.scrollToBottom(); + + return; + } + + stick.release(); + scrollToMessageRow(row); + } + /** * Moves the form between its centered and bottom positions: it fades out * where it is, drifting toward where it goes, and fades diff --git a/ui/apps/chat/src/lib/components/app/library/LibraryAttachmentTile.svelte b/ui/apps/chat/src/lib/components/app/library/LibraryAttachmentTile.svelte new file mode 100644 index 000000000000..c77118df1d7b --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/library/LibraryAttachmentTile.svelte @@ -0,0 +1,100 @@ + + + +
+ + +
+ +
+ +
+ {item.attachment.name} + + {#if conversationName} + {conversationName} + {/if} +
+
+
diff --git a/ui/apps/chat/src/lib/components/app/library/LibraryAttachments.svelte b/ui/apps/chat/src/lib/components/app/library/LibraryAttachments.svelte new file mode 100644 index 000000000000..43ec9df73b4e --- /dev/null +++ b/ui/apps/chat/src/lib/components/app/library/LibraryAttachments.svelte @@ -0,0 +1,169 @@ + + +
+ {#if items.length === 0 && libraryAttachmentsStore.isLoading} +
+ {#each { length: columnCount } as _, column (column)} +
+ {#each SKELETON_HEIGHT_CLASSES as _, row (row)} + + {/each} +
+ {/each} +
+ {:else if items.length === 0} + + + + {#if query.trim()} + + {:else} + + {/if} + + + {query.trim() ? 'No attachments match' : 'No attachments yet'} + + + {query.trim() + ? 'Try another search.' + : 'The files you send in your chats show here: images, audio, video, PDFs and text.'} + + + + {:else} +
+ {#each columns as column, index (index)} +
    + {#each column as item (item.id)} +
  • + void goToConversation(target)} + onOpen={open} + /> +
  • + {/each} +
+ {/each} +
+ {/if} + + {#if libraryAttachmentsStore.hasMore} + + {/if} +
+ + 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.

- + New prompt + + {/if} - + (tab = value as LibraryTab)} value={tab}> +
+ + {#each LIBRARY_TABS as entry (entry.value)} + {entry.label} + {/each} + + + +
+ + + + - + + + {#if tab === LibraryTab.ATTACHMENTS} + + {/if} + +
diff --git a/ui/apps/chat/tests/unit/library-attachments-store.test.ts b/ui/apps/chat/tests/unit/library-attachments-store.test.ts new file mode 100644 index 000000000000..9aca74eedd97 --- /dev/null +++ b/ui/apps/chat/tests/unit/library-attachments-store.test.ts @@ -0,0 +1,166 @@ +// The Library reads the files of conversations a page at a time: it goes on from the +// oldest message of the page before, never lists a message twice, starts over for a +// search, and drops a page that arrives after it was cleared. + +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: { getMessagesHolding: vi.fn() } +})); + +import { LIBRARY_ATTACHMENTS_PAGE_SIZE } from '#lib/constants/index.ts'; +import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts'; +import { DatabaseService } from '#lib/services/database.service.ts'; +import { libraryAttachmentsStore } from '#lib/stores/library-attachments.svelte.ts'; +import type { DatabaseMessage } from '#lib/types/database.js'; + +const getMessagesHolding = vi.mocked(DatabaseService.getMessagesHolding); + +function message(id: string, timestamp: number, names: string[] = [`${id}.png`]): DatabaseMessage { + return { + children: [], + content: '', + convId: 'c1', + extra: names.map((name) => ({ base64Url: '', name, type: AttachmentType.IMAGE })), + id, + parent: null, + role: MessageRole.USER, + timestamp, + type: MessageType.TEXT + } as DatabaseMessage; +} + +/** A full page of messages, newest first, ending at `oldest`. */ +function page(prefix: string, oldest: number): DatabaseMessage[] { + return Array.from({ length: LIBRARY_ATTACHMENTS_PAGE_SIZE }, (_, index) => + message(`${prefix}${index}`, oldest + LIBRARY_ATTACHMENTS_PAGE_SIZE - 1 - index) + ); +} + +describe('libraryAttachmentsStore', () => { + beforeEach(() => { + vi.clearAllMocks(); + libraryAttachmentsStore.clear(); + }); + + it('reads the newest files first and knows there are no more after a short page', async () => { + getMessagesHolding.mockResolvedValue([ + message('b', 2000, ['b1.png', 'b2.png']), + message('a', 1000) + ]); + + await libraryAttachmentsStore.search(''); + + expect(getMessagesHolding).toHaveBeenCalledWith( + expect.any(Function), + LIBRARY_ATTACHMENTS_PAGE_SIZE, + undefined + ); + expect(libraryAttachmentsStore.items.map((item) => item.id)).toEqual(['b:0', 'b:1', 'a:0']); + expect(libraryAttachmentsStore.hasMore).toBe(false); + expect(libraryAttachmentsStore.isLoading).toBe(false); + }); + + it('goes on from the oldest message of the page before, without listing one twice', async () => { + const first = page('new', 5000); + // sent in the same millisecond as the last message of the first page + const sameMoment = message('twin', 5000); + + getMessagesHolding.mockResolvedValueOnce(first); + await libraryAttachmentsStore.search(''); + + expect(libraryAttachmentsStore.hasMore).toBe(true); + + getMessagesHolding.mockResolvedValueOnce([first.at(-1)!, sameMoment, message('old', 4000)]); + await libraryAttachmentsStore.loadMore(); + + expect(getMessagesHolding).toHaveBeenLastCalledWith( + expect.any(Function), + LIBRARY_ATTACHMENTS_PAGE_SIZE, + 5000 + ); + expect(libraryAttachmentsStore.items).toHaveLength(LIBRARY_ATTACHMENTS_PAGE_SIZE + 2); + expect(libraryAttachmentsStore.items.slice(-2).map((item) => item.messageId)).toEqual([ + 'twin', + 'old' + ]); + expect(libraryAttachmentsStore.hasMore).toBe(false); + }); + + it('stops when a full page brings nothing new', async () => { + const first = page('same', 5000); + + getMessagesHolding.mockResolvedValue(first); + await libraryAttachmentsStore.search(''); + await libraryAttachmentsStore.loadMore(); + + expect(libraryAttachmentsStore.items).toHaveLength(LIBRARY_ATTACHMENTS_PAGE_SIZE); + expect(libraryAttachmentsStore.hasMore).toBe(false); + }); + + it('asks the database only for messages with a file that matches the search', async () => { + getMessagesHolding.mockResolvedValue([message('m', 1000, ['Map.png', 'notes.png'])]); + + await libraryAttachmentsStore.search('map'); + + const holds = getMessagesHolding.mock.calls[0][0]; + + expect(holds(message('x', 1, ['city-map.png']))).toBe(true); + expect(holds(message('y', 1, ['notes.png']))).toBe(false); + expect(libraryAttachmentsStore.items.map((item) => item.attachment.name)).toEqual(['Map.png']); + }); + + it('starts over for a new search', async () => { + getMessagesHolding.mockResolvedValueOnce(page('first', 5000)); + await libraryAttachmentsStore.search(''); + + getMessagesHolding.mockResolvedValueOnce([message('hit', 9000)]); + await libraryAttachmentsStore.search('hit'); + + expect(getMessagesHolding).toHaveBeenLastCalledWith( + expect.any(Function), + LIBRARY_ATTACHMENTS_PAGE_SIZE, + undefined + ); + expect(libraryAttachmentsStore.items.map((item) => item.messageId)).toEqual(['hit']); + }); + + it('drops a page that arrives after the Library was left', async () => { + let deliver!: (messages: DatabaseMessage[]) => void; + + getMessagesHolding.mockReturnValueOnce( + new Promise((resolve) => { + deliver = resolve; + }) + ); + + const loading = libraryAttachmentsStore.search(''); + + libraryAttachmentsStore.clear(); + deliver([message('late', 1000)]); + await loading; + + expect(libraryAttachmentsStore.items).toEqual([]); + expect(libraryAttachmentsStore.isLoading).toBe(false); + }); + + it('does not read two pages at once, or any once none are left', async () => { + getMessagesHolding.mockResolvedValue([message('a', 1000)]); + + await Promise.all([libraryAttachmentsStore.search(''), libraryAttachmentsStore.loadMore()]); + await libraryAttachmentsStore.loadMore(); + + expect(getMessagesHolding).toHaveBeenCalledOnce(); + }); + + it('lists nothing more after a read fails', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + getMessagesHolding.mockRejectedValue(new Error('database is closed')); + + await libraryAttachmentsStore.search(''); + + expect(libraryAttachmentsStore.items).toEqual([]); + expect(libraryAttachmentsStore.hasMore).toBe(false); + expect(libraryAttachmentsStore.isLoading).toBe(false); + }); +}); diff --git a/ui/apps/chat/tests/unit/library-attachments.test.ts b/ui/apps/chat/tests/unit/library-attachments.test.ts new file mode 100644 index 000000000000..9463651b5c6c --- /dev/null +++ b/ui/apps/chat/tests/unit/library-attachments.test.ts @@ -0,0 +1,126 @@ +// The Library lists the files of conversations: which extras count as files, how a +// message's files are listed and searched, and what a file gives to draw, copy and save. + +import { AttachmentType, MessageRole, MessageType } from '#lib/enums/index.ts'; +import type { DatabaseMessage, DatabaseMessageExtra } from '#lib/types/database.js'; +import { + attachmentBlob, + attachmentImage, + attachmentText, + isFileAttachment, + libraryAttachmentsOf +} from '#lib/utils/library-attachments.ts'; +import { describe, expect, it } from 'vitest'; + +// "hello" in base64 +const HELLO = 'aGVsbG8='; +const IMAGE: DatabaseMessageExtra = { + base64Url: `data:image/png;base64,${HELLO}`, + name: 'Map.png', + type: AttachmentType.IMAGE +}; +const TEXT: DatabaseMessageExtra = { + content: 'first line\nsecond line', + name: 'notes.txt', + type: AttachmentType.TEXT +}; +const AUDIO: DatabaseMessageExtra = { + base64Data: HELLO, + mimeType: 'audio/wav', + name: 'voice-1.wav', + type: AttachmentType.AUDIO +}; +const PDF_AS_IMAGES: DatabaseMessageExtra = { + base64Data: HELLO, + content: '', + images: ['data:image/png;base64,cGFnZTE=', 'data:image/png;base64,cGFnZTI='], + name: 'paper.pdf', + processedAsImages: true, + type: AttachmentType.PDF +}; +const PROMPT: DatabaseMessageExtra = { + content: 'Review this change.', + name: 'Review', + promptId: 'p1', + type: AttachmentType.PROMPT +}; +const MCP_RESOURCE: DatabaseMessageExtra = { + content: '# Readme', + name: 'README.md', + serverName: 'github', + type: AttachmentType.MCP_RESOURCE, + uri: 'repo://readme' +}; + +function message(extra: DatabaseMessageExtra[] | undefined): DatabaseMessage { + return { + children: [], + content: '', + convId: 'c1', + extra, + id: 'm1', + parent: null, + role: MessageRole.USER, + timestamp: 1000, + type: MessageType.TEXT + } as DatabaseMessage; +} + +describe('the files of a message', () => { + it('counts images, audio, video, PDFs and text as files, not prompts or MCP resources', () => { + expect([IMAGE, TEXT, AUDIO, PDF_AS_IMAGES].every(isFileAttachment)).toBe(true); + expect([PROMPT, MCP_RESOURCE].some(isFileAttachment)).toBe(false); + }); + + it('lists them in the order they were attached, each with its message', () => { + expect(libraryAttachmentsOf(message([IMAGE, PROMPT, TEXT]))).toEqual([ + { attachment: IMAGE, convId: 'c1', id: 'm1:0', messageId: 'm1', timestamp: 1000 }, + { attachment: TEXT, convId: 'c1', id: 'm1:2', messageId: 'm1', timestamp: 1000 } + ]); + }); + + it('lists nothing for a message without files', () => { + expect(libraryAttachmentsOf(message(undefined))).toEqual([]); + expect(libraryAttachmentsOf(message([PROMPT]))).toEqual([]); + }); + + it('keeps only the files whose name holds the query, ignoring case', () => { + const files = libraryAttachmentsOf(message([IMAGE, TEXT, AUDIO]), ' MAP '); + + expect(files.map((file) => file.attachment.name)).toEqual(['Map.png']); + }); +}); + +describe('what a file gives', () => { + it('draws an image as itself, and a PDF sent as images as its first page', () => { + expect(attachmentImage(IMAGE)).toBe(`data:image/png;base64,${HELLO}`); + expect(attachmentImage(PDF_AS_IMAGES)).toBe('data:image/png;base64,cGFnZTE='); + expect(attachmentImage(TEXT)).toBeUndefined(); + expect(attachmentImage(AUDIO)).toBeUndefined(); + }); + + it('has text to show and copy only when it is a text file', () => { + expect(attachmentText(TEXT)).toBe('first line\nsecond line'); + expect(attachmentText(IMAGE)).toBeUndefined(); + }); + + it('saves as a blob of its own type', async () => { + const image = attachmentBlob(IMAGE); + const audio = attachmentBlob(AUDIO); + const text = attachmentBlob(TEXT); + const pdf = attachmentBlob(PDF_AS_IMAGES); + + expect(image?.type).toBe('image/png'); + expect(await image?.text()).toBe('hello'); + expect(audio?.type).toBe('audio/wav'); + expect(await audio?.text()).toBe('hello'); + expect(text?.type).toBe('text/plain'); + expect(await text?.text()).toBe('first line\nsecond line'); + expect(pdf?.type).toBe('application/pdf'); + }); + + it('has nothing to save for an extra that is not a file, or an image that is not a data URL', () => { + expect(attachmentBlob(PROMPT)).toBeNull(); + expect(attachmentBlob({ ...IMAGE, base64Url: 'https://example.com/a.png' })).toBeNull(); + }); +}); diff --git a/ui/apps/chat/tests/unit/message-jump.test.ts b/ui/apps/chat/tests/unit/message-jump.test.ts new file mode 100644 index 000000000000..ffe7a10301aa --- /dev/null +++ b/ui/apps/chat/tests/unit/message-jump.test.ts @@ -0,0 +1,51 @@ +// A jump to a message (from a file in the Library to where it was sent) lands on the +// row that shows the message: its own, or the row of the turn it is drawn in. + +import { MessageRole, MessageType } from '#lib/enums/index.ts'; +import type { DatabaseMessage } from '#lib/types/database.js'; +import { findMessageRowId } from '#lib/utils/message-jump.ts'; +import { describe, expect, it } from 'vitest'; + +function message(id: string, role: MessageRole, parent: string | null): DatabaseMessage { + return { + children: [], + content: '', + convId: 'c1', + id, + parent, + role, + timestamp: 0, + type: MessageType.TEXT + } as DatabaseMessage; +} + +// a user message with a file, then an agentic turn: the assistant calls a tool, whose +// result carries an image, and answers +const MESSAGES = [ + message('user', MessageRole.USER, 'root'), + message('assistant', MessageRole.ASSISTANT, 'user'), + message('tool', MessageRole.TOOL, 'assistant'), + message('answer', MessageRole.ASSISTANT, 'tool') +]; +// the turn is one row, under its first message +const ROWS = new Set(['user', 'assistant']); +const hasRow = (id: string) => ROWS.has(id); + +describe('the row a jump to a message lands on', () => { + it('is the message own row when it has one', () => { + expect(findMessageRowId(MESSAGES, 'user', hasRow)).toBe('user'); + }); + + it('is the row of the turn for a message drawn inside it', () => { + expect(findMessageRowId(MESSAGES, 'tool', hasRow)).toBe('assistant'); + expect(findMessageRowId(MESSAGES, 'answer', hasRow)).toBe('assistant'); + }); + + it('is none for a message that is not in the open branch', () => { + expect(findMessageRowId(MESSAGES, 'gone', hasRow)).toBeNull(); + }); + + it('is none when no message up to the root has a row', () => { + expect(findMessageRowId(MESSAGES, 'tool', () => false)).toBeNull(); + }); +});