From 8d1d51f75d097d9819d19ecf7c45fbe4aed3afdc Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Sat, 31 Oct 2026 13:54:01 +0100 Subject: [PATCH 01/11] ui : add a prompt library store in IndexedDB Prompts are reusable system messages kept in a new prompts table, with CRUD in DatabaseService and a promptsStore that searches by name, description and content. A system message can link to the prompt it came from through a PROMPT message extra. MCP prompt ids use an mcp: prefix so they are never read as library prompts. Assisted-by: Claude (Opus 5.5 Medium) --- .../src/lib/constants/database.constants.ts | 17 +- .../chat/src/lib/constants/mcp.constants.ts | 3 + .../chat/src/lib/enums/attachment.enums.ts | 1 + .../chat/src/lib/services/database.service.ts | 63 ++++++- ui/apps/chat/src/lib/stores/index.ts | 3 + ui/apps/chat/src/lib/stores/init.ts | 2 + ui/apps/chat/src/lib/stores/prompts.svelte.ts | 164 ++++++++++++++++++ ui/apps/chat/src/lib/types/database.d.ts | 22 +++ .../chat/src/lib/utils/attachment-display.ts | 3 + ui/apps/chat/src/lib/utils/mcp.ts | 11 ++ ui/apps/chat/tests/unit/prompts-store.test.ts | 134 ++++++++++++++ 11 files changed, 414 insertions(+), 9 deletions(-) create mode 100644 ui/apps/chat/src/lib/stores/prompts.svelte.ts create mode 100644 ui/apps/chat/tests/unit/prompts-store.test.ts diff --git a/ui/apps/chat/src/lib/constants/database.constants.ts b/ui/apps/chat/src/lib/constants/database.constants.ts index bfa3fd63b14b..85126b3005a8 100644 --- a/ui/apps/chat/src/lib/constants/database.constants.ts +++ b/ui/apps/chat/src/lib/constants/database.constants.ts @@ -15,7 +15,8 @@ export const IDXDB_TABLES = { conversations: 'conversations', groups: 'groups', messages: 'messages', - projects: 'projects' + projects: 'projects', + prompts: 'prompts' } as const; /** IndexedDB store schemas */ @@ -23,7 +24,8 @@ export const IDXDB_STORE_SCHEMAS = { conversations: 'id, lastModified, currNode, name', groups: 'id, updatedAt, name', messages: 'id, convId, type, role, timestamp, parent, children', - projects: 'id, updatedAt, name' + projects: 'id, updatedAt, name', + prompts: 'id, lastModified, name' } as const; /** Combined Dexie stores definition — keys are table names, values are schemas */ @@ -31,7 +33,8 @@ export const IDXDB_STORES = { [IDXDB_TABLES.conversations]: IDXDB_STORE_SCHEMAS.conversations, [IDXDB_TABLES.groups]: IDXDB_STORE_SCHEMAS.groups, [IDXDB_TABLES.messages]: IDXDB_STORE_SCHEMAS.messages, - [IDXDB_TABLES.projects]: IDXDB_STORE_SCHEMAS.projects + [IDXDB_TABLES.projects]: IDXDB_STORE_SCHEMAS.projects, + [IDXDB_TABLES.prompts]: IDXDB_STORE_SCHEMAS.prompts } as const; /** Stores of schema version 1, before the groups table existed. */ @@ -43,5 +46,11 @@ export const IDXDB_STORES_V1 = { /** Schema version that added the groups table. */ export const IDXDB_VERSION_GROUPS = 2; +/** Schema version that added the projects table. */ +export const IDXDB_VERSION_PROJECTS = 3; + +/** Schema version that added the prompts table. */ +export const IDXDB_VERSION_PROMPTS = 4; + /** Schema version new Dexie instances open the database at; bump with a new version block. */ -export const IDXDB_VERSION = 3; +export const IDXDB_VERSION = 4; diff --git a/ui/apps/chat/src/lib/constants/mcp.constants.ts b/ui/apps/chat/src/lib/constants/mcp.constants.ts index 9a681178111b..daf6772209df 100644 --- a/ui/apps/chat/src/lib/constants/mcp.constants.ts +++ b/ui/apps/chat/src/lib/constants/mcp.constants.ts @@ -28,6 +28,9 @@ export const DEFAULT_MCP_CONFIG = { export const MCP_SERVER_ID_PREFIX = 'LlamaUI-MCP-Server'; +/** Prefix of MCP prompt ids, so they never match a library prompt id. */ +export const MCP_PROMPT_ID_PREFIX = 'mcp:'; + /** Backoff policy for reconnecting to a dropped MCP server. */ export const MCP_RECONNECT = { /** Per-attempt timeout for a single reconnection attempt before giving up and backing off. */ diff --git a/ui/apps/chat/src/lib/enums/attachment.enums.ts b/ui/apps/chat/src/lib/enums/attachment.enums.ts index 035fdac9cdd0..af08a197dd77 100644 --- a/ui/apps/chat/src/lib/enums/attachment.enums.ts +++ b/ui/apps/chat/src/lib/enums/attachment.enums.ts @@ -8,6 +8,7 @@ export enum AttachmentType { MCP_PROMPT = 'MCP_PROMPT', MCP_RESOURCE = 'MCP_RESOURCE', PDF = 'PDF', + PROMPT = 'PROMPT', TEXT = 'TEXT', VIDEO = 'VIDEO' } diff --git a/ui/apps/chat/src/lib/services/database.service.ts b/ui/apps/chat/src/lib/services/database.service.ts index 8a4e45310fc7..9bb972a636c5 100644 --- a/ui/apps/chat/src/lib/services/database.service.ts +++ b/ui/apps/chat/src/lib/services/database.service.ts @@ -12,13 +12,18 @@ import { IDXDB_STORE_SCHEMAS, IDXDB_STORES_V1, IDXDB_TABLES, - IDXDB_VERSION, IDXDB_VERSION_GROUPS, + IDXDB_VERSION_PROJECTS, + IDXDB_VERSION_PROMPTS, STORAGE_APP_NAME } from '#lib/constants/index.ts'; import { MessageRole } from '#lib/enums/index.ts'; -import type { McpServerOverride } from '#lib/types/database.js'; -import type { ExportedConversation } from '#lib/types/database.js'; +import type { + DatabaseMessageExtra, + DatabasePrompt, + ExportedConversation, + McpServerOverride +} from '#lib/types/database.js'; import type { Group } from '#lib/types/groups.js'; import type { Project } from '#lib/types/projects.js'; import { filterByLeafNodeId, findDescendantMessages, uuid } from '#lib/utils/index.ts'; @@ -29,6 +34,7 @@ class LlamaUiDatabase extends Dexie { [IDXDB_TABLES.groups]!: EntityTable; [IDXDB_TABLES.messages]!: EntityTable; [IDXDB_TABLES.projects]!: EntityTable; + [IDXDB_TABLES.prompts]!: EntityTable; constructor() { super(STORAGE_APP_NAME); @@ -37,9 +43,12 @@ class LlamaUiDatabase extends Dexie { this.version(IDXDB_VERSION_GROUPS).stores({ [IDXDB_TABLES.groups]: IDXDB_STORE_SCHEMAS.groups }); - this.version(IDXDB_VERSION).stores({ + this.version(IDXDB_VERSION_PROJECTS).stores({ [IDXDB_TABLES.projects]: IDXDB_STORE_SCHEMAS.projects }); + this.version(IDXDB_VERSION_PROMPTS).stores({ + [IDXDB_TABLES.prompts]: IDXDB_STORE_SCHEMAS.prompts + }); } } @@ -236,6 +245,17 @@ export class DatabaseService { return project; } + /** + * Creates a prompt in the library. + * + * @returns The created prompt + */ + static async createPrompt(prompt: DatabasePrompt): Promise { + await db[IDXDB_TABLES.prompts].add(prompt); + + return prompt; + } + /** * Creates a root message for a new conversation. * Root messages are not displayed but serve as the tree root for branching. @@ -273,7 +293,8 @@ export class DatabaseService { static async createSystemMessage( convId: string, systemPrompt: string, - parentId: string + parentId: string, + extra?: DatabaseMessageExtra[] ): Promise { const trimmedPrompt = systemPrompt.trim(); @@ -292,6 +313,7 @@ export class DatabaseService { children: [], content: trimmedPrompt, convId, + extra, id: uuid(), parent: parentId, role: MessageRole.SYSTEM, @@ -431,6 +453,15 @@ export class DatabaseService { await db[IDXDB_TABLES.projects].delete(id); } + /** + * Deletes a prompt from the library. Messages linked to it keep their content. + * + * @param id - Prompt ID + */ + static async deletePrompt(id: string): Promise { + await db[IDXDB_TABLES.prompts].delete(id); + } + /** * Forks a conversation at a specific message, creating a new conversation * containing all messages from the root up to (and including) the target message. @@ -551,6 +582,15 @@ export class DatabaseService { return await db[IDXDB_TABLES.projects].orderBy('updatedAt').reverse().toArray(); } + /** + * Gets all prompts in the library, most recently edited first. + * + * @returns Array of prompts + */ + static async getAllPrompts(): Promise { + return await db[IDXDB_TABLES.prompts].orderBy('lastModified').reverse().toArray(); + } + /** * Gets a conversation by ID. * @@ -785,6 +825,19 @@ export class DatabaseService { await db[IDXDB_TABLES.projects].update(id, updates); } + /** + * Updates a prompt in the library. + * + * @param id - Prompt ID + * @param updates - Partial updates to apply + */ + static async updatePrompt( + id: string, + updates: Partial> + ): Promise { + await db[IDXDB_TABLES.prompts].update(id, updates); + } + /** * Appends a child id to a parent message's children array. */ diff --git a/ui/apps/chat/src/lib/stores/index.ts b/ui/apps/chat/src/lib/stores/index.ts index 7cf7f0a5ce51..de3ffafe34ac 100644 --- a/ui/apps/chat/src/lib/stores/index.ts +++ b/ui/apps/chat/src/lib/stores/index.ts @@ -54,6 +54,9 @@ export { modelsDiscoverStore } from './models-discover/index.svelte'; // PROJECTS (shared instructions and context for chats) export { projectsStore } from './projects.svelte'; +// PROMPTS (reusable system messages kept in the library) +export { promptsStore } from './prompts.svelte'; + // SERVER export { serverStore } from './llama-server.svelte'; diff --git a/ui/apps/chat/src/lib/stores/init.ts b/ui/apps/chat/src/lib/stores/init.ts index c98b95f880df..8b59c1084929 100644 --- a/ui/apps/chat/src/lib/stores/init.ts +++ b/ui/apps/chat/src/lib/stores/init.ts @@ -5,6 +5,7 @@ import { serverStore } from './llama-server.svelte'; import { modelsStore } from './models/index.svelte'; import { permissionsStore } from './permissions.svelte'; import { projectsStore } from './projects.svelte'; +import { promptsStore } from './prompts.svelte'; import { remoteAccessStore } from './remote-access.svelte'; import { serversStore } from './servers.svelte'; import { serversModelsStore } from './serversModels.svelte'; @@ -159,6 +160,7 @@ export function initStores(): Promise { void versionStore.initialize(); void groupsStore.initialize(); void projectsStore.initialize(); + void promptsStore.initialize(); // the full conversation list loads in the background; once it is back, // prune persisted tabs against the conversations that still exist diff --git a/ui/apps/chat/src/lib/stores/prompts.svelte.ts b/ui/apps/chat/src/lib/stores/prompts.svelte.ts new file mode 100644 index 000000000000..4c5cbc96f9d8 --- /dev/null +++ b/ui/apps/chat/src/lib/stores/prompts.svelte.ts @@ -0,0 +1,164 @@ +/** + * promptsStore - Reusable system messages kept in the prompt library + * + * Mirrors the prompts table through DatabaseService, like projectsStore: every + * mutation awaits the row write, then applies the change to the loaded list. + */ + +import { DatabaseService } from '#lib/services/database.service.ts'; +import type { DatabasePrompt } from '#lib/types/database.js'; +import { uuid } from '#lib/utils/index.ts'; +import { browser } from '$app/env'; + +/** Fields a prompt is built from; the name is required, the description optional. */ +export interface PromptDraft { + name: string; + content: string; + description?: string; +} + +/** Trims the text fields, dropping an empty description. */ +function normalize(draft: PromptDraft): PromptDraft { + const description = draft.description?.trim(); + + return { + content: draft.content.trim(), + description: description || undefined, + name: draft.name.trim() + }; +} + +class PromptsStore { + /** Whether the library was read from the database at least once. */ + isInitialized = $state(false); + + /** All prompts, most recently edited first. */ + prompts = $state([]); + + private initPromise: Promise | null = null; + + /** + * Adds a prompt to the library and puts it at the top of the list. + * + * @param draft - Name, content and optional description + * @returns The created prompt, or undefined when the name or content is empty + */ + async add(draft: PromptDraft): Promise { + const next = normalize(draft); + + if (!next.name || !next.content) return undefined; + + const prompt: DatabasePrompt = { ...next, id: uuid(), lastModified: Date.now() }; + + try { + await DatabaseService.createPrompt(prompt); + } catch (error) { + console.error('Failed to create prompt:', error); + + return undefined; + } + + this.prompts = [prompt, ...this.prompts]; + + return prompt; + } + + get(id: string): DatabasePrompt | undefined { + return this.prompts.find((prompt) => prompt.id === id); + } + + /** + * Reads every prompt from the database. + * Safe to call multiple times: concurrent callers share a single run, + * and a failed run can be retried by calling again. + */ + initialize(): Promise { + if (!browser) return Promise.resolve(); + + if (this.initPromise) return this.initPromise; + + this.initPromise = (async () => { + try { + this.prompts = await DatabaseService.getAllPrompts(); + this.isInitialized = true; + } catch (error) { + console.error('Failed to load prompts:', error); + this.initPromise = null; + } + })(); + + return this.initPromise; + } + + /** + * Deletes a prompt. System messages linked to it keep their content. + * + * @param id - Prompt ID + */ + async remove(id: string): Promise { + try { + await DatabaseService.deletePrompt(id); + } catch (error) { + console.error('Failed to delete prompt:', error); + + return; + } + + this.prompts = this.prompts.filter((prompt) => prompt.id !== id); + } + + /** + * Matches prompts by name, description or content, ignoring case. + * An empty query returns every prompt. + * + * @param query - Text to look for + */ + search(query: string): DatabasePrompt[] { + const q = query.trim().toLowerCase(); + + if (!q) return this.prompts; + + return this.prompts.filter( + (prompt) => + prompt.name.toLowerCase().includes(q) || + (prompt.description?.toLowerCase().includes(q) ?? false) || + prompt.content.toLowerCase().includes(q) + ); + } + + /** + * Edits a prompt and bumps its `lastModified`. An empty name keeps the current one. + * + * @param id - Prompt ID + * @param changes - The fields to change + */ + async update(id: string, changes: Partial): Promise { + const prompt = this.get(id); + + if (!prompt) return; + + const next = normalize({ ...prompt, ...changes }); + + if (!next.content) return; + + const updated: DatabasePrompt = { + ...prompt, + content: next.content, + description: next.description, + lastModified: Date.now(), + name: next.name || prompt.name + }; + + try { + await DatabaseService.updatePrompt(id, updated); + } catch (error) { + console.error('Failed to update prompt:', error); + + return; + } + + this.prompts = this.prompts.map((p) => (p.id === id ? updated : p)); + } +} + +export const promptsStore = new PromptsStore(); diff --git a/ui/apps/chat/src/lib/types/database.d.ts b/ui/apps/chat/src/lib/types/database.d.ts index 7c0ecd90cc13..8579f7b3129f 100644 --- a/ui/apps/chat/src/lib/types/database.d.ts +++ b/ui/apps/chat/src/lib/types/database.d.ts @@ -12,6 +12,16 @@ export interface McpServerOverride { enabled: boolean; } +/** A reusable system message stored in the prompt library. */ +export interface DatabasePrompt { + id: string; + name: string; + content: string; + /** Epoch ms of the last edit to the name, description or content. */ + lastModified: number; + description?: string; +} + export interface DatabaseConversation { currNode: string | null; id: string; @@ -112,6 +122,17 @@ export interface DatabaseMessageExtraMcpResource { mimeType?: string; } +/** + * Links a system message to the prompt it was created from. `promptId` is a + * library prompt id, or an MCP prompt id (`mcp::`) for prompts + * that come from an MCP server. + */ +export interface DatabaseMessageExtraPrompt { + type: AttachmentType.PROMPT; + promptId: string; + title: string; +} + export type DatabaseMessageExtra = | DatabaseMessageExtraImageFile | DatabaseMessageExtraTextFile @@ -120,6 +141,7 @@ export type DatabaseMessageExtra = | DatabaseMessageExtraPdfFile | DatabaseMessageExtraMcpPrompt | DatabaseMessageExtraMcpResource + | DatabaseMessageExtraPrompt | DatabaseMessageExtraLegacyContext; export interface DatabaseMessage { diff --git a/ui/apps/chat/src/lib/utils/attachment-display.ts b/ui/apps/chat/src/lib/utils/attachment-display.ts index 0bbfa4c033f9..aef3144a8e3b 100644 --- a/ui/apps/chat/src/lib/utils/attachment-display.ts +++ b/ui/apps/chat/src/lib/utils/attachment-display.ts @@ -73,6 +73,9 @@ export function getAttachmentDisplayItems( // Add stored attachments (ChatMessage) for (const [index, attachment] of attachments.entries()) { + // a prompt link marks where a system message came from, it is not a file + if (attachment.type === AttachmentType.PROMPT) continue; + const isImage = isImageFile(attachment); let preview: string | undefined; diff --git a/ui/apps/chat/src/lib/utils/mcp.ts b/ui/apps/chat/src/lib/utils/mcp.ts index 75ec000c2aa3..f73921b65aa7 100644 --- a/ui/apps/chat/src/lib/utils/mcp.ts +++ b/ui/apps/chat/src/lib/utils/mcp.ts @@ -17,6 +17,7 @@ import { FILE_EXTENSION_REGEX, IMAGE_FILE_EXTENSION_REGEX, MCP_ALLOWED_ICON_MIME_TYPES, + MCP_PROMPT_ID_PREFIX, MCP_SERVER_ID_PREFIX, MCP_SSE, MIME_TYPE_PREFIXES, @@ -462,3 +463,13 @@ export function getMcpServerLabel( return position < 0 ? label : `${label} (${position + 1})`; } + +/** Id stored on a system message created from an MCP prompt. */ +export function buildMcpPromptId(serverName: string, promptName: string): string { + return `${MCP_PROMPT_ID_PREFIX}${serverName}:${promptName}`; +} + +/** Whether a prompt id names an MCP prompt rather than a library prompt. */ +export function isMcpPromptId(promptId: string): boolean { + return promptId.startsWith(MCP_PROMPT_ID_PREFIX); +} diff --git a/ui/apps/chat/tests/unit/prompts-store.test.ts b/ui/apps/chat/tests/unit/prompts-store.test.ts new file mode 100644 index 000000000000..bfbb5e81f786 --- /dev/null +++ b/ui/apps/chat/tests/unit/prompts-store.test.ts @@ -0,0 +1,134 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('#lib/services/database.service.ts', () => ({ + DatabaseService: { + createPrompt: vi.fn(), + deletePrompt: vi.fn(), + getAllPrompts: vi.fn(), + updatePrompt: vi.fn() + } +})); + +import { DatabaseService } from '#lib/services/database.service.ts'; +import { promptsStore } from '#lib/stores/prompts.svelte.ts'; +import type { DatabasePrompt } from '#lib/types/database.js'; + +const createMock = vi.mocked(DatabaseService.createPrompt); +const deleteMock = vi.mocked(DatabaseService.deletePrompt); +const updateMock = vi.mocked(DatabaseService.updatePrompt); + +function makePrompt(overrides: Partial = {}): DatabasePrompt { + return { + content: 'You are terse.', + id: 'p1', + lastModified: 1000, + name: 'Terse', + ...overrides + }; +} + +describe('promptsStore', () => { + beforeEach(() => { + vi.clearAllMocks(); + promptsStore.prompts = []; + }); + + describe('add', () => { + it('trims the fields, stores the row and puts it first', async () => { + promptsStore.prompts = [makePrompt({ id: 'old' })]; + createMock.mockResolvedValue(undefined as never); + + const created = await promptsStore.add({ + content: ' Answer in French. ', + description: ' ', + name: ' French ' + }); + + expect(created).toBeDefined(); + expect(created?.name).toBe('French'); + expect(created?.content).toBe('Answer in French.'); + expect(created?.description).toBeUndefined(); + expect(createMock).toHaveBeenCalledWith(created); + expect(promptsStore.prompts[0]).toBe(created); + expect(promptsStore.prompts).toHaveLength(2); + }); + + it('refuses a prompt with an empty name or content', async () => { + expect(await promptsStore.add({ content: 'x', name: ' ' })).toBeUndefined(); + expect(await promptsStore.add({ content: ' ', name: 'Name' })).toBeUndefined(); + expect(createMock).not.toHaveBeenCalled(); + }); + + it('leaves the list alone when the database write fails', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}); + createMock.mockRejectedValue(new Error('quota')); + + expect(await promptsStore.add({ content: 'x', name: 'Name' })).toBeUndefined(); + expect(promptsStore.prompts).toHaveLength(0); + }); + }); + + describe('update', () => { + it('writes the new content, bumps lastModified and keeps the name when empty', async () => { + promptsStore.prompts = [makePrompt()]; + updateMock.mockResolvedValue(undefined); + + const before = Date.now(); + + await promptsStore.update('p1', { content: 'Be brief.', name: ' ' }); + + const stored = promptsStore.get('p1'); + + expect(stored?.content).toBe('Be brief.'); + expect(stored?.name).toBe('Terse'); + expect(stored?.lastModified).toBeGreaterThanOrEqual(before); + expect(updateMock).toHaveBeenCalledWith('p1', stored); + }); + + it('ignores an unknown id and an empty content', async () => { + promptsStore.prompts = [makePrompt()]; + + await promptsStore.update('missing', { content: 'x' }); + await promptsStore.update('p1', { content: ' ' }); + + expect(updateMock).not.toHaveBeenCalled(); + expect(promptsStore.get('p1')?.content).toBe('You are terse.'); + }); + }); + + describe('remove', () => { + it('drops the prompt from the list after the row is deleted', async () => { + promptsStore.prompts = [makePrompt(), makePrompt({ id: 'p2' })]; + deleteMock.mockResolvedValue(undefined); + + await promptsStore.remove('p1'); + + expect(deleteMock).toHaveBeenCalledWith('p1'); + expect(promptsStore.prompts.map((p) => p.id)).toEqual(['p2']); + }); + }); + + describe('search', () => { + beforeEach(() => { + promptsStore.prompts = [ + makePrompt({ content: 'Reply like a pirate.', id: 'a', name: 'Pirate' }), + makePrompt({ description: 'For code review', id: 'b', name: 'Reviewer' }), + makePrompt({ content: 'Use metric units.', id: 'c', name: 'Units' }) + ]; + }); + + it('returns everything for an empty query', () => { + expect(promptsStore.search(' ')).toHaveLength(3); + }); + + it('matches name, description and content, ignoring case', () => { + expect(promptsStore.search('PIRATE').map((p) => p.id)).toEqual(['a']); + expect(promptsStore.search('code review').map((p) => p.id)).toEqual(['b']); + expect(promptsStore.search('metric').map((p) => p.id)).toEqual(['c']); + }); + + it('returns nothing when no field matches', () => { + expect(promptsStore.search('zebra')).toEqual([]); + }); + }); +}); From 390ccce2ba29887bb442b740a3673723f0fa6ce0 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Sat, 31 Oct 2026 13:59:24 +0100 Subject: [PATCH 02/11] ui : add a System message submenu to the chat add menu The add dropdown's plain System message item becomes a submenu that lists the prompt library, MCP prompts and a Write new entry, with search. The mobile drawer shows the same list. Picking a library prompt, or an MCP prompt without arguments, sets the conversation's system message to its text and links the message to the prompt. An MCP prompt with arguments opens the existing argument form in the prompt picker. MCP prompts reach the list through a new extension point, systemPromptSources: the MCP extension lists its prompts, gives their text and opens its argument form in the prompt picker. With MCP switched off the list holds the prompt library only. Assisted-by: Claude (Opus 5.5 Medium) --- ui/apps/chat/README.md | 2 +- .../app/chat/ChatForm/ChatForm.svelte | 16 +- .../ChatFormActionAddDrawer.svelte | 130 +++++++++++++++- .../ChatFormActionAddDropdown.svelte | 19 ++- ...atFormActionAddSystemMessageSubmenu.svelte | 136 +++++++++++++++++ .../ChatFormActions/ChatFormActions.svelte | 11 ++ .../app/chat/ChatScreen/ChatScreen.svelte | 5 + .../app/chat/ChatScreen/ChatScreenForm.svelte | 3 + .../chat/src/lib/components/app/chat/index.ts | 5 + ui/apps/chat/src/lib/extensions/index.ts | 1 + .../ChatFormPickerMcpPrompts.svelte | 5 + .../contributions/ComposerMcpPrompts.svelte | 12 ++ ui/apps/chat/src/lib/extensions/mcp/index.ts | 2 + .../extensions/mcp/prompt-arguments.svelte.ts | 21 +++ .../src/lib/extensions/mcp/system-prompts.ts | 81 ++++++++++ .../lib/extensions/points/system-prompts.ts | 31 ++++ ui/apps/chat/src/lib/extensions/types.ts | 3 + .../use-system-message-prompts.svelte.ts | 125 +++++++++++++++ .../chat/src/lib/stores/chat/index.svelte.ts | 142 ++++++++++++++---- ui/apps/chat/src/lib/types/chat.d.ts | 7 + ui/apps/chat/src/lib/utils/index.ts | 4 +- 21 files changed, 710 insertions(+), 51 deletions(-) create mode 100644 ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddSystemMessageSubmenu.svelte create mode 100644 ui/apps/chat/src/lib/extensions/mcp/prompt-arguments.svelte.ts create mode 100644 ui/apps/chat/src/lib/extensions/mcp/system-prompts.ts create mode 100644 ui/apps/chat/src/lib/extensions/points/system-prompts.ts create mode 100644 ui/apps/chat/src/lib/hooks/use-system-message-prompts.svelte.ts diff --git a/ui/apps/chat/README.md b/ui/apps/chat/README.md index 49c6fcb4f3c5..5f537803b0b9 100644 --- a/ui/apps/chat/README.md +++ b/ui/apps/chat/README.md @@ -148,7 +148,7 @@ sequenceDiagram ### Extensions (`src/lib/extensions/`) -An extension is a feature the app is composed with and that can be switched off. The registry (`registry.svelte.ts`) knows the built-in extensions (`builtin.ts`), activates the ones that are on at startup, and holds what they add to each extension point (`points/`): tools, flow hooks, sidebar entries, pages, slash commands, pickers, pending attachments, and message and attachment renderers. +An extension is a feature the app is composed with and that can be switched off. The registry (`registry.svelte.ts`) knows the built-in extensions (`builtin.ts`), activates the ones that are on at startup, and holds what they add to each extension point (`points/`): tools, flow hooks, sidebar entries, pages, slash commands, pickers, pending attachments, message and attachment renderers, and prompts offered as system messages. The core never imports an extension's own code; an extension may import the core. ESLint enforces this: a file outside `src/lib/extensions//` cannot import from that folder. diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte index fd1e302ee585..075d2b02e3b6 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatForm.svelte @@ -24,7 +24,12 @@ MimeTypeText, SpecialFileType } from '#lib/enums/index.ts'; - import { type ComposerHandle, extensions } from '#lib/extensions/index.ts'; + import { + type ComposerHandle, + extensions, + type SystemPromptEntry, + type SystemPromptSource + } from '#lib/extensions/index.ts'; import { useChatFormExpansion } from '#lib/hooks/use-chat-form-expansion.svelte.ts'; import { useChatFormPickers } from '#lib/hooks/use-chat-form-pickers.svelte.ts'; import { @@ -83,6 +88,7 @@ onStop?: () => void; onSubmit?: () => void; onSystemPromptClick?: (draft: { message: string; files: ChatUploadedFile[] }) => void; + onSystemPromptWithContent?: (content: string, promptId: string, title: string) => void; onUploadedFileRemove?: (fileId: string) => void; onUploadedFilesChange?: (files: ChatUploadedFile[]) => void; onValueChange?: (value: string) => void; @@ -104,6 +110,7 @@ onStop, onSubmit, onSystemPromptClick, + onSystemPromptWithContent, onUploadedFileRemove, onUploadedFilesChange, onValueChange, @@ -518,6 +525,11 @@ } } + /** A prompt of the System message list that needs arguments: its source asks for them in the form. */ + function handlePromptArguments(source: SystemPromptSource, entry: SystemPromptEntry) { + source.openArguments(entry, composer); + } + // Deferred so the closing popover's focus scope tears down first - // bits-ui yanks a synchronous focus() back into the still-mounted popover. function refocusInput() { @@ -799,9 +811,11 @@ micWarning={micUnavailableReason ?? micError} onFileUpload={handleFileUpload} onMicClick={handleMicClick} + onPromptArguments={handlePromptArguments} {onStop} onSystemPromptClick={() => onSystemPromptClick?.({ files: uploadedFiles, message: value })} + {onSystemPromptWithContent} onVoiceModeClick={voiceModeAvailable ? handleVoiceModeClick : undefined} onWorkingDirectoryClick={isWorkingDirectoryInAddMenu ? pickers.handleWorkingDirectoryOpen diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte index 36cdf4169168..53a5f51bf097 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddDrawer.svelte @@ -1,4 +1,5 @@ + + + + + + System message + + + + {#if prompts.hasPrompts} +
+ +
+ {/if} + + onWriteNew?.()} + > + + + Write new + + + {#if prompts.libraryPrompts.length > 0} + + + Your prompts + + {#each prompts.libraryPrompts as prompt (prompt.id)} + prompts.selectLibraryPrompt(prompt.id)} + > + {prompt.name} + + {#if prompt.description} + + {prompt.description} + + {/if} + + + {prompt.content} + + + {/each} + {/if} + + {#each prompts.sourceGroups as group (group.source.id)} + + + {group.source.label} + + {#each group.entries as entry (entry.id)} + prompts.selectSourcePrompt(group.source, entry)} + > +
+ {#if entry.iconUrl} + { + (e.currentTarget as HTMLImageElement).style.display = 'none'; + }} + src={entry.iconUrl} + /> + {:else} + + {/if} + + {entry.origin} + + {#if entry.argumentCount > 0} + + {entry.argumentCount} arg{entry.argumentCount > 1 ? 's' : ''} + + {/if} +
+ + + {entry.title} + + + {#if entry.description} + + {entry.description} + + {/if} +
+ {/each} + {/each} + + {#if prompts.hasNoMatches} +
No matches
+ {/if} +
+
diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte index 44368c396ca2..004703fe2f39 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatForm/ChatFormActions/ChatFormActions.svelte @@ -16,6 +16,7 @@ } from '#lib/constants/index.ts'; import { setChatFormActionsContext } from '#lib/contexts/index.ts'; import { FileTypeCategory } from '#lib/enums/index.ts'; + import type { SystemPromptEntry, SystemPromptSource } from '#lib/extensions/index.ts'; import { useChatFormModel } from '#lib/hooks/use-chat-form-model.svelte.ts'; import { useShowContextGauge } from '#lib/hooks/use-context-gauge.svelte.ts'; import { ChatService } from '#lib/services/index.ts'; @@ -55,7 +56,9 @@ /** Why voice mode cannot listen. */ voiceModeUnavailableReason?: string | null; onStop?: () => void; + onPromptArguments?: (source: SystemPromptSource, entry: SystemPromptEntry) => void; onSystemPromptClick?: () => void; + onSystemPromptWithContent?: (content: string, promptId: string, title: string) => void; onWorkingDirectoryClick?: () => void; } @@ -71,8 +74,10 @@ micWarning = null, onFileUpload, onMicClick, + onPromptArguments, onStop, onSystemPromptClick, + onSystemPromptWithContent, onVoiceModeClick, onWorkingDirectoryClick, showAddButton = true, @@ -142,9 +147,15 @@ get onFileUpload() { return onFileUpload; }, + get onPromptArguments() { + return onPromptArguments; + }, get onSystemPromptClick() { return onSystemPromptClick; }, + get onSystemPromptWithContent() { + return onSystemPromptWithContent; + }, get onWorkingDirectoryClick() { return onWorkingDirectoryClick; }, diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte index 4b97863c4229..735ad85ee707 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreen.svelte @@ -277,6 +277,10 @@ await chatStore.addSystemPrompt(draft); } + async function handleSystemPromptWithContent(content: string, promptId: string, title: string) { + await chatStore.addSystemPromptFromPrompt(content, { promptId, title }); + } + $effect(() => { stick.setEnabled(!settingsStore.config.disableAutoScroll); }); @@ -428,6 +432,7 @@ onSend={handleSendMessage} onStop={() => chatStore.stopGeneration()} onSystemPromptAdd={handleSystemPromptAdd} + onSystemPromptWithContent={handleSystemPromptWithContent} /> diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte index ee71a96eb820..ffdb39c47865 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatScreen/ChatScreenForm.svelte @@ -17,6 +17,7 @@ onSend?: (message: string, files?: ChatUploadedFile[]) => Promise; onStop?: () => void; onSystemPromptAdd?: (draft: { message: string; files: ChatUploadedFile[] }) => void; + onSystemPromptWithContent?: (content: string, promptId: string, title: string) => void; uploadedFiles?: ChatUploadedFile[]; } @@ -29,6 +30,7 @@ onSend, onStop, onSystemPromptAdd, + onSystemPromptWithContent, uploadedFiles = $bindable([]) }: Props = $props(); @@ -161,6 +163,7 @@ {onStop} onSubmit={handleSubmit} onSystemPromptClick={handleSystemPromptClick} + {onSystemPromptWithContent} onUploadedFileRemove={handleUploadedFileRemove} singleRow={settingsStore.config[SETTINGS_KEYS.SINGLE_ROW_CHAT_FORM] !== false} voiceMode diff --git a/ui/apps/chat/src/lib/components/app/chat/index.ts b/ui/apps/chat/src/lib/components/app/chat/index.ts index 63f1491ffdd1..98e43db86b55 100644 --- a/ui/apps/chat/src/lib/components/app/chat/index.ts +++ b/ui/apps/chat/src/lib/components/app/chat/index.ts @@ -231,6 +231,11 @@ export { default as ChatFormActionReasoning } from './ChatForm/ChatFormActions/C */ export { default as ChatFormActionAddToolsSubmenu } from './ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddToolsSubmenu.svelte'; +/** + * System message submenu of the add dropdown: prompts from the library, MCP prompts and a write-new entry. + */ +export { default as ChatFormActionAddSystemMessageSubmenu } from './ChatForm/ChatFormActions/ChatFormActionAdd/ChatFormActionAddSystemMessageSubmenu.svelte'; + /** * Compact context-usage gauge with per-turn and cumulative breakdown in the tooltip. */ diff --git a/ui/apps/chat/src/lib/extensions/index.ts b/ui/apps/chat/src/lib/extensions/index.ts index 985044de14ee..3ff92793366d 100644 --- a/ui/apps/chat/src/lib/extensions/index.ts +++ b/ui/apps/chat/src/lib/extensions/index.ts @@ -25,6 +25,7 @@ export type { ToolProviderEmptyHint, ToolProviderEntry } from './points/tools'; +export type { SystemPromptEntry, SystemPromptSource } from './points/system-prompts'; export { ExtensionRegistry, extensions } from './registry.svelte'; export type { Extension, diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/chat/ChatFormPickerMcpPrompts/ChatFormPickerMcpPrompts.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/chat/ChatFormPickerMcpPrompts/ChatFormPickerMcpPrompts.svelte index 9ffad776b68c..4d67f70787a1 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/components/chat/ChatFormPickerMcpPrompts/ChatFormPickerMcpPrompts.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/chat/ChatFormPickerMcpPrompts/ChatFormPickerMcpPrompts.svelte @@ -106,6 +106,11 @@ } } + /** Opens the argument form of a prompt, as if the user had picked it from the list. */ + export function openArguments(prompt: MCPPromptInfo) { + handlePromptClick(prompt); + } + function handlePromptClick(prompt: MCPPromptInfo) { const args = prompt.arguments ?? []; diff --git a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpPrompts.svelte b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpPrompts.svelte index 337721f75754..a29a9e2ab745 100644 --- a/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpPrompts.svelte +++ b/ui/apps/chat/src/lib/extensions/mcp/components/contributions/ComposerMcpPrompts.svelte @@ -1,12 +1,24 @@ + + + + + + + Update prompt + + + + {#if drift === PromptDrift.LIBRARY} + The prompt changed after this system message was written. Update the prompt with this + message's text, or sync this message from the prompt. + {:else} + Save this system message's text back to the prompt in your library. + {/if} + + + +
+ + + + +
+ {content} +
+
+ + + Cancel + + {#if drift === PromptDrift.LIBRARY} + + {/if} + + + +
+
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 c7c5db37a183..b82f2b81af1a 100644 --- a/ui/apps/chat/src/lib/components/app/dialogs/index.ts +++ b/ui/apps/chat/src/lib/components/app/dialogs/index.ts @@ -161,6 +161,15 @@ export { default as DialogConversationDelete } from './DialogConversationDelete. */ export { default as DialogConversationRename } from './DialogConversationRename.svelte'; +/** + * **DialogPromptUpdate** - Save a system message back to its library prompt + * + * Opened from the "Modified" link under a system message made from a prompt. + * Writes the message text to the prompt (with an optional rename), or syncs the + * message from the prompt when the library is the newer side. + */ +export { default as DialogPromptUpdate } from './DialogPromptUpdate.svelte'; + /** * **DialogGroup** - Name a new sidebar group, or rename one * diff --git a/ui/apps/chat/src/lib/enums/index.ts b/ui/apps/chat/src/lib/enums/index.ts index be3d4270a015..c8bbc91c79ec 100644 --- a/ui/apps/chat/src/lib/enums/index.ts +++ b/ui/apps/chat/src/lib/enums/index.ts @@ -129,4 +129,5 @@ export { export { SplashOrientation } from './splash.enums'; +export { PromptDrift } from './prompt.enums'; export { VoiceInputMode, VoiceMode } from './voice.enums'; diff --git a/ui/apps/chat/src/lib/enums/prompt.enums.ts b/ui/apps/chat/src/lib/enums/prompt.enums.ts new file mode 100644 index 000000000000..22a494824653 --- /dev/null +++ b/ui/apps/chat/src/lib/enums/prompt.enums.ts @@ -0,0 +1,13 @@ +/** + * How a system message linked to a library prompt differs from that prompt. + */ +export enum PromptDrift { + /** The prompt changed after the message, so the library is the newer side. */ + LIBRARY = 'library', + /** The message changed after the prompt, so the message is the newer side. */ + MESSAGE = 'message', + /** The prompt was deleted, or never existed. */ + MISSING = 'missing', + /** The message and the prompt have the same text. */ + NONE = 'none' +} diff --git a/ui/apps/chat/src/lib/types/index.ts b/ui/apps/chat/src/lib/types/index.ts index bddea98d76da..97a02281add5 100644 --- a/ui/apps/chat/src/lib/types/index.ts +++ b/ui/apps/chat/src/lib/types/index.ts @@ -94,11 +94,13 @@ export type { export type { McpServerOverride, DatabaseConversation, + DatabasePrompt, DatabaseMessageExtraAudioFile, DatabaseMessageExtraVideoFile, DatabaseMessageExtraImageFile, DatabaseMessageExtraLegacyContext, DatabaseMessageExtraMcpPrompt, + DatabaseMessageExtraPrompt, DatabaseMessageExtraMcpResource, DatabaseMessageExtraPdfFile, DatabaseMessageExtraTextFile, diff --git a/ui/apps/chat/src/lib/utils/index.ts b/ui/apps/chat/src/lib/utils/index.ts index 7ec0b075eb23..0d5f4b29b08d 100644 --- a/ui/apps/chat/src/lib/utils/index.ts +++ b/ui/apps/chat/src/lib/utils/index.ts @@ -280,6 +280,7 @@ export { // Project system prompt section (instructions + referenced documents) export { buildProjectSystemPrompt, estimateProjectContext } from './project-prompt'; +export { getPromptDrift } from './prompt-drift'; export { projectNewChatTabId, projectOfNewChatTab, diff --git a/ui/apps/chat/src/lib/utils/prompt-drift.ts b/ui/apps/chat/src/lib/utils/prompt-drift.ts new file mode 100644 index 000000000000..ef777c7d357b --- /dev/null +++ b/ui/apps/chat/src/lib/utils/prompt-drift.ts @@ -0,0 +1,18 @@ +import { PromptDrift } from '#lib/enums/index.ts'; +import type { DatabaseMessage, DatabasePrompt } from '#lib/types/index.ts'; + +/** + * Tells how a system message differs from the library prompt it was made from. + * The side edited last is the newer one: a prompt saved after the message + * means the library changed, otherwise the message did. + */ +export function getPromptDrift( + message: Pick, + prompt: DatabasePrompt | undefined +): PromptDrift { + if (!prompt) return PromptDrift.MISSING; + + if (message.content.trim() === prompt.content.trim()) return PromptDrift.NONE; + + return prompt.lastModified > message.timestamp ? PromptDrift.LIBRARY : PromptDrift.MESSAGE; +} diff --git a/ui/apps/chat/tests/unit/prompt-drift.test.ts b/ui/apps/chat/tests/unit/prompt-drift.test.ts new file mode 100644 index 000000000000..cdfa7e60cbfa --- /dev/null +++ b/ui/apps/chat/tests/unit/prompt-drift.test.ts @@ -0,0 +1,44 @@ +import { PromptDrift } from '#lib/enums/index.ts'; +import type { DatabasePrompt } from '#lib/types/database.js'; +import { getPromptDrift } from '#lib/utils/prompt-drift.ts'; +import { describe, expect, it } from 'vitest'; + +function makePrompt(overrides: Partial = {}): DatabasePrompt { + return { + content: 'Answer briefly.', + id: 'p1', + lastModified: 2000, + name: 'Brief', + ...overrides + }; +} + +describe('getPromptDrift', () => { + it('reports missing when there is no prompt', () => { + expect(getPromptDrift({ content: 'x', timestamp: 1000 }, undefined)).toBe(PromptDrift.MISSING); + }); + + it('reports none when the texts match, ignoring surrounding whitespace', () => { + const message = { content: ' Answer briefly.\n', timestamp: 1000 }; + + expect(getPromptDrift(message, makePrompt())).toBe(PromptDrift.NONE); + }); + + it('reports the library side when the prompt was saved after the message', () => { + const message = { content: 'Answer at length.', timestamp: 1000 }; + + expect(getPromptDrift(message, makePrompt({ lastModified: 2000 }))).toBe(PromptDrift.LIBRARY); + }); + + it('reports the message side when the prompt was saved before the message', () => { + const message = { content: 'Answer at length.', timestamp: 3000 }; + + expect(getPromptDrift(message, makePrompt({ lastModified: 2000 }))).toBe(PromptDrift.MESSAGE); + }); + + it('treats a prompt saved in the same millisecond as the message as the message side', () => { + const message = { content: 'Answer at length.', timestamp: 2000 }; + + expect(getPromptDrift(message, makePrompt({ lastModified: 2000 }))).toBe(PromptDrift.MESSAGE); + }); +}); From 421295e75f60a91116883ebb4d5a2dd50fb929c7 Mon Sep 17 00:00:00 2001 From: Aleksander Grygier Date: Sat, 31 Oct 2026 18:03:25 +0100 Subject: [PATCH 04/11] ui : add a system message to the prompt library A system message written in the chat, not linked to a prompt yet, shows an "Add to library" link under it. It opens a dialog to name and describe the prompt, with the message text shown as is, and saving adds the prompt and links the message to it, so the System message submenu lists it from then on. The same dialog adds and edits prompts with editable text elsewhere. Assisted-by: Claude (Opus 5.5 Medium) --- .../ChatMessageSystem.svelte | 36 ++++- .../app/dialogs/DialogPrompt.svelte | 139 ++++++++++++++++++ .../src/lib/components/app/dialogs/index.ts | 8 + 3 files changed, 182 insertions(+), 1 deletion(-) create mode 100644 ui/apps/chat/src/lib/components/app/dialogs/DialogPrompt.svelte diff --git a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte index bf25c00024fb..6ab961993f37 100644 --- a/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte +++ b/ui/apps/chat/src/lib/components/app/chat/ChatMessages/ChatMessage/ChatMessageSystem/ChatMessageSystem.svelte @@ -4,14 +4,16 @@ import { Check, ScanText, X } from '@lucide/svelte'; import { ChatMessageActionIcons, + DialogPrompt, DialogPromptUpdate, MarkdownContent } from '#lib/components/app/index.ts'; - import { INPUT_CLASSES } from '#lib/constants/index.ts'; + import { INPUT_CLASSES, SYSTEM_MESSAGE_PLACEHOLDER } from '#lib/constants/index.ts'; import { getChatMessageEditContext } from '#lib/contexts/index.ts'; import { AttachmentType, KeyboardKey, PromptDrift } from '#lib/enums/index.ts'; import { DatabaseService } from '#lib/services/database.service.ts'; import { conversationsStore, promptsStore, settingsStore } from '#lib/stores/index.ts'; + import type { PromptDraft } from '#lib/stores/prompts.svelte.ts'; import type { DatabaseMessageExtra, DatabaseMessageExtraPrompt } from '#lib/types/index.ts'; import { autoResizeTextarea, @@ -66,6 +68,12 @@ let linkedPrompt = $derived(libraryPromptId ? promptsStore.get(libraryPromptId) : undefined); let drift = $derived(libraryPromptId ? getPromptDrift(message, linkedPrompt) : PromptDrift.NONE); let showUpdateDialog = $state(false); + let showAddDialog = $state(false); + + // a system message written in the chat, not yet a prompt, can be saved as one + let canAddToLibrary = $derived( + !promptLink && !!message.content.trim() && message.content !== SYSTEM_MESSAGE_PLACEHOLDER + ); /** Sets the message text and links it to a prompt, keeping its other extras. */ async function linkMessageToPrompt(content: string, link: { promptId: string; title: string }) { @@ -119,6 +127,14 @@ await linkMessageToPrompt(message.content, { promptId: created.id, title: created.name }); } + async function handleAddToLibrary(draft: PromptDraft) { + const created = await promptsStore.add({ ...draft, content: message.content }); + + if (!created) return; + + await linkMessageToPrompt(created.content, { promptId: created.id, title: created.name }); + } + $effect(() => { if (!messageElement || !message.content.trim()) return; @@ -293,6 +309,17 @@ {/if} + {:else if canAddToLibrary} + {/if} {#if message.timestamp} @@ -302,6 +329,13 @@ {/if} {/if} + + {#if linkedPrompt} + import { Button } from '@ggml-org/llama-ui/ui/button'; + import * as Dialog from '@ggml-org/llama-ui/ui/dialog'; + import { Input } from '@ggml-org/llama-ui/ui/input'; + import { Label } from '@ggml-org/llama-ui/ui/label'; + import { Textarea } from '@ggml-org/llama-ui/ui/textarea'; + import type { PromptDraft } from '#lib/stores/prompts.svelte.ts'; + import type { DatabasePrompt } from '#lib/types/index.ts'; + import { untrack } from 'svelte'; + + interface Props { + open?: boolean; + /** The prompt to edit; a new one is made without it. */ + prompt?: DatabasePrompt; + /** Text a new prompt starts with, e.g. the system message it is saved from. */ + initialContent?: string; + /** Whether the text can be edited here; a system message saved as is shows it read-only. */ + contentEditable?: boolean; + onSave: (draft: PromptDraft) => void | Promise; + } + + let { + contentEditable = true, + initialContent = '', + onSave, + open = $bindable(false), + prompt + }: Props = $props(); + + let name = $state(''); + let description = $state(''); + let content = $state(''); + let nameInput = $state(null); + + // fresh fields every time the dialog opens, the prompt's own when editing + $effect.pre(() => { + if (!open) return; + + untrack(() => { + name = prompt?.name ?? ''; + description = prompt?.description ?? ''; + content = prompt?.content ?? initialContent; + }); + }); + + const canSave = $derived(name.trim().length > 0 && content.trim().length > 0); + + async function handleSubmit(event: SubmitEvent) { + event.preventDefault(); + + if (!canSave) return; + + open = false; + + await onSave({ content, description, name }); + } + + + + { + event.preventDefault(); + nameInput?.focus(); + nameInput?.select(); + }} + > + + + {prompt ? 'Edit prompt' : contentEditable ? 'New prompt' : 'Add to library'} + + + {#if !prompt && !contentEditable} + + Save this system message as a prompt, to start other chats from it. + + {/if} + + +
+
+
+ + + +
+ +
+ + + +
+ +
+ + + {#if contentEditable} +