From 0ebf06417338cf9ca72b77fa09f205576d729ba9 Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:26:27 +0100 Subject: [PATCH] Add audio transcripts, monthly AI limits, PDF sources and AI chat on phones Follow-ups to Phase E (ADR-15): - Transcription (E2): OpenAI-compatible profiles can name a speech-to-text model; POST /files/{id}/transcribe turns an audio or video attachment (up to 25 MB) into text and a summary with key points and action items. The editor gets a Transcribe button on media files that inserts the summary and the transcript in a toggle. - Monthly token limits: ai_usage counts requests and tokens per workspace and month. Workspace admins can cap their workspace; superadmins can cap what each workspace uses through the server's providers, after which the workspace's own providers keep working. The admin panel lists usage. - PDF text for extra retrieval files (ledongthuc/pdf, pure Go). - Phone app: an AI chat screen for the workspace or a page, with streamed answers and sources that open the cited block. - OpenAPI, generated clients, migration, translations and docs. Co-Authored-By: Claude Opus 5.5 --- .../pb_migrations/1764200000_ai_limits.js | 46 ++ Docs-Site/guide/administration.md | 9 +- Docs-Site/guide/using-docwell.md | 6 + Packages/api-client/src/index.ts | 13 + Packages/api-client/src/schema.d.ts | 233 +++++++++ Packages/editor/src/editor.css | 26 + Packages/editor/src/files.ts | 69 ++- Packages/editor/src/index.ts | 2 +- Packages/editor/src/labels.ts | 9 + Phone-App/lib/api/docwell_api.dart | 95 ++++ Phone-App/lib/api/generated/models.dart | 134 +++++ Phone-App/lib/l10n.dart | 75 +++ Phone-App/lib/screens/ai_chat_screen.dart | 456 ++++++++++++++++++ Phone-App/lib/screens/home_screen.dart | 19 + Phone-App/lib/screens/page_screen.dart | 29 ++ Phone-App/test/ai_test.dart | 26 + Server/admin/src/locales/de.json | 13 +- Server/admin/src/locales/en.json | 13 +- Server/admin/src/locales/es.json | 13 +- Server/admin/src/locales/fr.json | 13 +- Server/admin/src/locales/pl.json | 13 +- Server/admin/src/views/AiView.vue | 89 +++- Server/go.mod | 5 +- Server/go.sum | 78 +++ Server/internal/ai/ai_test.go | 68 +++ Server/internal/ai/anthropic.go | 4 + Server/internal/ai/chat.go | 6 +- Server/internal/ai/files.go | 41 +- Server/internal/ai/index.go | 7 +- Server/internal/ai/limits.go | 246 ++++++++++ Server/internal/ai/profiles.go | 77 +-- Server/internal/ai/provider.go | 52 ++ Server/internal/ai/service.go | 8 +- Server/internal/ai/transcribe.go | 137 ++++++ Server/internal/ai/write.go | 2 +- Server/internal/api/api.gen.go | 66 ++- Server/internal/httpapi/ai.go | 40 ++ Server/internal/httpapi/security.go | 1 + Server/internal/pbschema/schema.json | 147 ++++++ .../frontend/src/components/ai/AiProfiles.vue | 11 + .../src/components/ai/WorkspaceAI.vue | 73 ++- .../frontend/src/composables/useAi.test.ts | 23 + Web-App/frontend/src/composables/useAi.ts | 55 ++- Web-App/frontend/src/locales/de.json | 24 +- Web-App/frontend/src/locales/en.json | 24 +- Web-App/frontend/src/locales/es.json | 24 +- Web-App/frontend/src/locales/fr.json | 24 +- Web-App/frontend/src/locales/pl.json | 24 +- Web-App/frontend/src/views/page/PageView.vue | 11 +- api/openapi.yaml | 124 ++++- 50 files changed, 2724 insertions(+), 79 deletions(-) create mode 100644 Database/pb_migrations/1764200000_ai_limits.js create mode 100644 Phone-App/lib/screens/ai_chat_screen.dart create mode 100644 Phone-App/test/ai_test.dart create mode 100644 Server/internal/ai/limits.go create mode 100644 Server/internal/ai/transcribe.go create mode 100644 Web-App/frontend/src/composables/useAi.test.ts diff --git a/Database/pb_migrations/1764200000_ai_limits.js b/Database/pb_migrations/1764200000_ai_limits.js new file mode 100644 index 0000000..9d2e560 --- /dev/null +++ b/Database/pb_migrations/1764200000_ai_limits.js @@ -0,0 +1,46 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +/// + +// AI follow-ups (ADR-15): +// +// - ai_usage: tokens a workspace used per calendar month (UTC), so workspace +// admins can cap their spending and superadmins can cap what each +// workspace spends through the server's providers (instance_tokens). +// The cap itself lives in workspaces.ai_settings and in the "ai" key of +// instance_settings. +// - ai_profiles.transcribe_model: the speech-to-text model of an +// OpenAI-compatible profile, for audio attachments (E2). + +migrate( + (app) => { + const workspaces = app.findCollectionByNameOrId("workspaces"); + app.save( + new Collection({ + type: "base", + name: "ai_usage", + fields: [ + { name: "workspace", type: "relation", collectionId: workspaces.id, maxSelect: 1, required: true, cascadeDelete: true }, + { name: "month", type: "text", required: true, max: 7 }, + { name: "requests", type: "number" }, + { name: "input_tokens", type: "number" }, + { name: "output_tokens", type: "number" }, + { name: "instance_tokens", type: "number" }, + { name: "created", type: "autodate", onCreate: true, onUpdate: false }, + { name: "updated", type: "autodate", onCreate: true, onUpdate: true }, + ], + indexes: ["CREATE UNIQUE INDEX idx_ai_usage_month ON ai_usage (workspace, month)"], + }), + ); + + const profiles = app.findCollectionByNameOrId("ai_profiles"); + profiles.fields.add(new TextField({ name: "transcribe_model", max: 200 })); + app.save(profiles); + }, + (app) => { + app.delete(app.findCollectionByNameOrId("ai_usage")); + const profiles = app.findCollectionByNameOrId("ai_profiles"); + profiles.fields.removeByName("transcribe_model"); + app.save(profiles); + }, +); diff --git a/Docs-Site/guide/administration.md b/Docs-Site/guide/administration.md index e06de71..99767ce 100644 --- a/Docs-Site/guide/administration.md +++ b/Docs-Site/guide/administration.md @@ -49,12 +49,17 @@ Docwell brings no AI of its own: you choose a provider, and nothing is sent anyw - **Providers.** *Admin panel → AI* holds the server's default providers; each workspace can add its own under *Workspace settings → AI* and use them before (or instead of) the server's. A provider is an OpenAI-compatible API (OpenAI, Azure, OpenRouter, LiteLLM, vLLM, LocalAI…), Anthropic, or Ollama, with a chat model and, except - for Anthropic, optionally an embedding model. Providers are tried from the top: when one fails, the next one + for Anthropic, optionally an embedding model; OpenAI-compatible providers can also have a speech-to-text model + (for example `whisper-1`) for transcribing recordings. Providers are tried from the top: when one fails, the next one answers. **Test** checks a provider; requests and tokens are counted per provider. - **Search by meaning.** *Index pages for AI* in a workspace's settings sends every page's text to the first provider with an embedding model and keeps the vectors in `DOCWELL_DATA_DIR`. Without it, the chat finds sources - with keyword search. Pages can be left out (with their subpages), and extra text, Markdown, HTML or Word files + with keyword search. Pages can be left out (with their subpages), and extra text, Markdown, HTML, Word or PDF files can be added as sources. Changing the embedding model indexes the workspace again. +- **Limits.** Usage is counted per workspace and month (UTC). A workspace admin can set a monthly token limit for + the workspace; a superadmin can cap what each workspace may use through the server's providers (*Admin panel → + AI*, which also lists every workspace's usage). When the server's cap is reached, a workspace's own providers + still answer. - **Keys** are encrypted with `DOCWELL_SECRET_KEY` (see *Configuration*) and never shown again. - **MCP.** AI agents and tools (Claude, IDEs, …) can use Docwell as an MCP server at `https:///mcp` with a personal API token: read-only tokens can list, search and read pages and ask the workspace's AI; write tokens can diff --git a/Docs-Site/guide/using-docwell.md b/Docs-Site/guide/using-docwell.md index 8ecb207..f0e110d 100644 --- a/Docs-Site/guide/using-docwell.md +++ b/Docs-Site/guide/using-docwell.md @@ -140,6 +140,12 @@ Select text in a page and choose **Ask AI** in the toolbar to improve, shorten, or continue it, or to give your own instruction. The result shows first; **Replace selection** or **Insert below** puts it in the page, where undo and page history work as for any edit. +Audio and video files in a page get a **Transcribe** button when the workspace has a speech-to-text model: it +adds a summary with key points and action items below the file, and the full transcript in a toggle. + +The phone app has the same chat: the ✦ button on the home screen asks about the workspace, on a page about that +page. + AI only ever reads what you can open yourself. ## Properties, tags and collections diff --git a/Packages/api-client/src/index.ts b/Packages/api-client/src/index.ts index 07fc3c4..b041102 100644 --- a/Packages/api-client/src/index.ts +++ b/Packages/api-client/src/index.ts @@ -112,6 +112,9 @@ export type AiCitation = Schemas["AiCitation"]; export type AiMessage = Schemas["AiMessage"]; export type AiWriteAction = Schemas["AiWriteAction"]; export type AiWriteInput = Schemas["AiWriteInput"]; +export type AiUsage = Schemas["AiUsage"]; +export type AiInstanceSettings = Schemas["AiInstanceSettings"]; +export type AiTranscript = Schemas["AiTranscript"]; /** One server-sent event of a streamed AI answer. */ export interface AiStreamEvent { @@ -349,6 +352,16 @@ export function createClient(opts: ClientOptions) { return upload(`/api/v1/workspaces/${enc(workspace)}/ai/files`, form); }, deleteFile: (id: string) => request("DELETE", `/api/v1/ai/files/${enc(id)}`), + /** This month's usage of a workspace, with its caps (workspace admin). */ + usage: (workspace: string) => request("GET", `/api/v1/workspaces/${enc(workspace)}/ai/usage`), + /** Every workspace's usage this month (superadmin). */ + allUsage: () => request("GET", "/api/v1/admin/ai/usage"), + instanceSettings: () => request("GET", "/api/v1/admin/ai/settings"), + saveInstanceSettings: (input: AiInstanceSettings) => + request("PUT", "/api/v1/admin/ai/settings", input), + /** Turns an audio or video attachment into text (and a summary). */ + transcribe: (fileId: string, summarize = true) => + post(`/api/v1/files/${enc(fileId)}/transcribe`, { summarize }), sessions: (workspace: string) => request("GET", `/api/v1/workspaces/${enc(workspace)}/ai/sessions`), createSession: (workspace: string, input: AiSessionInput) => diff --git a/Packages/api-client/src/schema.d.ts b/Packages/api-client/src/schema.d.ts index fe21f48..e7a87de 100644 --- a/Packages/api-client/src/schema.d.ts +++ b/Packages/api-client/src/schema.d.ts @@ -2805,6 +2805,82 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/workspaces/{id}/ai/usage": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + /** The workspace's AI usage this month, with its caps (workspace admin) */ + get: operations["getAiUsage"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/admin/ai/usage": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** Every workspace's AI usage this month, most first (superadmin) */ + get: operations["listAiUsage"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/admin/ai/settings": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** The server's AI rules (superadmin) */ + get: operations["getInstanceAiSettings"]; + /** Replace the server's AI rules (superadmin) */ + put: operations["saveInstanceAiSettings"]; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/v1/files/{id}/transcribe": { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Turn an audio or video attachment (up to 25 MB) into text, and optionally a summary (page reader) + * @description Uses the first profile of the page's workspace with a speech-to-text model (OpenAI-compatible /audio/transcriptions). The summary comes from the workspace's chat profiles. + */ + post: operations["transcribeFile"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; } export type webhooks = Record; export interface components { @@ -3722,6 +3798,8 @@ export interface components { chat: boolean; /** @description The workspace is indexed for retrieval */ embeddings: boolean; + /** @description A profile can turn audio attachments into text */ + transcribe: boolean; /** @description The caller may change the workspace's AI settings */ canManage: boolean; }; @@ -3733,6 +3811,8 @@ export interface components { index: boolean; /** @description Pages (with their subpages) that are neither indexed nor retrieved */ ignored: string[]; + /** @description Tokens the workspace may use per month; 0 is no cap */ + monthlyTokenLimit: number; }; /** * @description openai is any OpenAI-compatible API @@ -3752,6 +3832,8 @@ export interface components { chatModel: string; /** @description Empty when the profile is not used for embeddings */ embedModel: string; + /** @description Speech-to-text model (OpenAI-compatible); empty when unused */ + transcribeModel: string; /** @description Anthropic effort level */ effort: string; enabled: boolean; @@ -3774,6 +3856,7 @@ export interface components { apiKey?: string; chatModel?: string; embedModel?: string; + transcribeModel?: string; /** @enum {string} */ effort?: "" | "low" | "medium" | "high" | "xhigh" | "max"; enabled?: boolean; @@ -3868,6 +3951,33 @@ export interface components { /** @description What to do (custom) */ instruction?: string; }; + AiUsage: { + workspace: string; + /** @description The workspace's name (admin listing) */ + name?: string; + /** @description Calendar month in UTC, e.g. 2026-11 */ + month: string; + requests: number; + inputTokens: number; + outputTokens: number; + /** @description Tokens used through the server's own profiles */ + instanceTokens: number; + /** @description The workspace's monthly token cap; 0 is none */ + limit: number; + /** @description The server's cap on instanceTokens; 0 is none */ + instanceLimit: number; + }; + AiInstanceSettings: { + /** @description Tokens one workspace may use through the server's profiles per month; 0 is no cap */ + workspaceTokenLimit: number; + }; + AiTranscript: { + name: string; + text: string; + /** @description Markdown; empty when not asked for or when it failed */ + summary: string; + summaryError?: string; + }; }; responses: { /** @description Signed in */ @@ -8953,4 +9063,127 @@ export interface operations { 401: components["responses"]["Error"]; }; }; + getAiUsage: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiUsage"]; + }; + }; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; + listAiUsage: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiUsage"][]; + }; + }; + 403: components["responses"]["Error"]; + }; + }; + getInstanceAiSettings: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiInstanceSettings"]; + }; + }; + 403: components["responses"]["Error"]; + }; + }; + saveInstanceAiSettings: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": components["schemas"]["AiInstanceSettings"]; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiInstanceSettings"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + }; + }; + transcribeFile: { + parameters: { + query?: never; + header?: never; + path: { + id: string; + }; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + summarize?: boolean; + }; + }; + }; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["AiTranscript"]; + }; + }; + 400: components["responses"]["Error"]; + 403: components["responses"]["Error"]; + 404: components["responses"]["Error"]; + }; + }; } diff --git a/Packages/editor/src/editor.css b/Packages/editor/src/editor.css index e5cad4d..74de701 100644 --- a/Packages/editor/src/editor.css +++ b/Packages/editor/src/editor.css @@ -131,6 +131,32 @@ color: var(--color-ink-muted); font-size: var(--text-ui-sm); } +.dw-prose .dw-file__action { + border: 1px solid var(--color-line); + border-radius: var(--radius-sm); + padding: 2px 8px; + color: var(--color-ink); + font-size: var(--text-ui-sm); + font-weight: 600; + cursor: pointer; +} +.dw-prose .dw-file__action:hover { + background: var(--color-surface-hover); +} +.dw-prose .dw-file__action:disabled { + cursor: progress; + opacity: 0.7; +} +.dw-prose .dw-file__status { + display: block; + margin-top: 4px; + color: var(--color-danger); + font-family: var(--font-sans); + font-size: var(--text-ui-sm); +} +.dw-prose .dw-file__status:empty { + display: none; +} /* Other editors' carets (CollaborationCaret's default render). */ .dw-prose .collaboration-carets__caret { diff --git a/Packages/editor/src/files.ts b/Packages/editor/src/files.ts index 17db139..30f33f6 100644 --- a/Packages/editor/src/files.ts +++ b/Packages/editor/src/files.ts @@ -14,6 +14,17 @@ import { isPdf, showPdf, type PdfLoader } from "./pdf"; export interface FileHost { resolve(src: string): string; upload?(file: File): Promise; + /** + * Turns an audio or video attachment into text: resolves with HTML to put + * below the file (a summary and the transcript). Without it, media files + * have no Transcribe button. + */ + transcribe?(src: string, name: string): Promise; +} + +/** Whether a file is audio or video, by type or extension. */ +export function isMedia(mime: string, name: string): boolean { + return /^(audio|video)\//.test(mime) || /\.(mp3|mp4|mpeg|mpga|m4a|wav|webm|ogg|oga|flac|aac|opus|mov)$/i.test(name); } export interface UploadedFile { @@ -175,7 +186,7 @@ export const FileAttachment = Node.create({ }, addNodeView() { - return ({ node }) => { + return ({ node, editor, getPos }) => { const { host, loadPdf, labels } = this.options; const dom = document.createElement("div"); dom.className = "dw-file-block"; @@ -190,6 +201,34 @@ export const FileAttachment = Node.create({ size.className = "dw-file__size"; card.append(link, size); dom.append(card); + // Audio and video: Transcribe puts a summary and the transcript below. + let transcribe: HTMLButtonElement | null = null; + let status: HTMLSpanElement | null = null; + let current = node; + const transcribeFile = async () => { + const run = host?.transcribe; + if (!run || !transcribe || !labels) return; + transcribe.disabled = true; + transcribe.textContent = labels.blocks.transcribing; + if (status) status.textContent = ""; + try { + const html = await run(String(current.attrs.url ?? ""), String(current.attrs.name ?? "file")); + const pos = typeof getPos === "function" ? getPos() : undefined; + if (pos !== undefined && html) + editor + .chain() + .insertContentAt(pos + current.nodeSize, html) + .run(); + } catch (err) { + if (status) + status.textContent = err instanceof Error && err.message ? err.message : labels.blocks.transcribeFailed; + } finally { + if (transcribe) { + transcribe.disabled = false; + transcribe.textContent = labels.blocks.transcribe; + } + } + }; let pages: HTMLDivElement | null = null; let stop: (() => void) | null = null; let shown = ""; @@ -199,6 +238,30 @@ export const FileAttachment = Node.create({ link.href = href; link.textContent = String(n.attrs.name ?? "file"); size.textContent = formatSize(Number(n.attrs.size ?? 0)); + current = n; + const media = + !!host?.transcribe && + !!labels && + editor.isEditable && + isMedia(String(n.attrs.mime ?? ""), String(n.attrs.name ?? "")); + if (media && !transcribe && labels) { + transcribe = document.createElement("button"); + transcribe.type = "button"; + transcribe.className = "dw-file__action"; + transcribe.textContent = labels.blocks.transcribe; + transcribe.title = labels.blocks.transcribeHint; + transcribe.setAttribute("data-testid", "file-transcribe"); + transcribe.addEventListener("click", () => void transcribeFile()); + status = document.createElement("span"); + status.className = "dw-file__status"; + status.setAttribute("role", "status"); + card.append(transcribe); + dom.append(status); + } else if (!media && transcribe) { + transcribe.remove(); + status?.remove(); + transcribe = status = null; + } const preview = n.attrs.view === "preview" && isPdf(n.attrs.mime, n.attrs.name) && !!url; if (!preview || !loadPdf || !labels) { stop?.(); @@ -230,7 +293,9 @@ export const FileAttachment = Node.create({ return true; }, // Scrolling and clicking through the pages are not edits. - stopEvent: (e) => !!pages && pages.contains(e.target as globalThis.Node) && e.type !== "mousedown", + stopEvent: (e) => + (!!transcribe && transcribe.contains(e.target as globalThis.Node)) || + (!!pages && pages.contains(e.target as globalThis.Node) && e.type !== "mousedown"), ignoreMutation: () => true, destroy: () => stop?.(), }; diff --git a/Packages/editor/src/index.ts b/Packages/editor/src/index.ts index 7a5f8d8..30cc749 100644 --- a/Packages/editor/src/index.ts +++ b/Packages/editor/src/index.ts @@ -7,7 +7,7 @@ export { decodeAnchor, encodeAnchor, setCommentMarks, type CommentAnchor, type C export { englishLabels, type EditorLabels } from "./labels"; export type { MentionHost, Person } from "./mention"; export { filterCommands, slashCommands, type SlashCommand } from "./slash"; -export { insertFiles, type FileHost, type UploadedFile } from "./files"; +export { insertFiles, isMedia, type FileHost, type UploadedFile } from "./files"; export { insertSyncedPage, SyncedPage, type SyncedPageHost } from "./syncedpage"; export { CollabProvider, type CollabProviderOptions, type CollabStatus } from "./provider"; export { linkedPage, pagePath, type PageHost, type PageRef as LinkablePage } from "./pagelinks"; diff --git a/Packages/editor/src/labels.ts b/Packages/editor/src/labels.ts index 951e5ec..e86c565 100644 --- a/Packages/editor/src/labels.ts +++ b/Packages/editor/src/labels.ts @@ -114,6 +114,11 @@ export interface EditorLabels { pdfLoading: string; /** One page of a PDF shown inline; {n} is its number. */ pdfPage: string; + /** The button on audio and video files that adds a transcript. */ + transcribe: string; + transcribeHint: string; + transcribing: string; + transcribeFailed: string; syncedPage: string; syncedOpen: string; syncedFold: string; @@ -317,6 +322,10 @@ export const englishLabels: EditorLabels = { calloutColor: "Change colour", pdfLoading: "Loading PDF…", pdfPage: "Page {n}", + transcribe: "Transcribe", + transcribeHint: "Add a summary and the transcript below, with AI", + transcribing: "Transcribing…", + transcribeFailed: "The recording could not be transcribed.", }, find: { find: "Find in page", diff --git a/Phone-App/lib/api/docwell_api.dart b/Phone-App/lib/api/docwell_api.dart index 30eacd4..a85ac02 100644 --- a/Phone-App/lib/api/docwell_api.dart +++ b/Phone-App/lib/api/docwell_api.dart @@ -194,6 +194,67 @@ class DocwellApi { Future removeDevice(String id) => _send('DELETE', '/api/v1/me/devices/${_id(id)}'); + // ---- AI (ADR-15) ---------------------------------------------------------- + + /// What AI offers in a workspace. A server without AI answers 404. + Future aiAvailability(String workspace) async => + AiAvailability.fromJson( + await _send('GET', '/api/v1/workspaces/${_id(workspace)}/ai'), + ); + + Future> aiSessions(String workspace) async => + ((await _send( + 'GET', + '/api/v1/workspaces/${_id(workspace)}/ai/sessions', + ))['items'] + as List) + .map((e) => AiSessionSummary.fromJson(e as Map)) + .toList(); + + Future aiSession(String id) async => + AiSession.fromJson(await _send('GET', '/api/v1/ai/sessions/${_id(id)}')); + + Future createAiSession( + String workspace, + AiScope scope, { + String scopeId = '', + }) async => AiSession.fromJson( + await _send('POST', '/api/v1/workspaces/${_id(workspace)}/ai/sessions', { + 'scope': scope.value, + 'scopeId': scopeId, + }), + ); + + Future deleteAiSession(String id) => + _send('DELETE', '/api/v1/ai/sessions/${_id(id)}'); + + /// Asks a question; the answer streams as events: sources {citations}, + /// delta {text}, then done {user, message} or error {message}. + Stream ask(String session, String question) async* { + final req = http.Request( + 'POST', + Uri.parse('$baseUrl/api/v1/ai/sessions/${_id(session)}/messages'), + ); + req.headers['Accept'] = 'text/event-stream'; + req.headers['Content-Type'] = 'application/json'; + if (token != null) req.headers['Authorization'] = 'Bearer $token'; + req.body = jsonEncode({'content': question}); + final res = await _client.send(req).timeout(const Duration(seconds: 30)); + if (res.statusCode >= 300) { + final text = await res.stream.bytesToString(); + Map data = {}; + try { + data = jsonDecode(text) as Map; + } catch (_) {} + throw DocwellApiException( + res.statusCode, + code: data['error'] as String? ?? 'unknown', + message: data['message'] as String? ?? '', + ); + } + yield* parseEventStream(res.stream.transform(utf8.decoder)); + } + // ---- Transport ----------------------------------------------------------- static String _id(String id) => Uri.encodeComponent(id); @@ -278,6 +339,40 @@ extension SpaceRoles on SpaceRole { bool get canComment => canEdit || this == SpaceRole.commenter; } +/// One server-sent event of a streamed AI answer. +class AiEvent { + const AiEvent(this.name, this.data); + final String name; + final Map data; +} + +/// Splits a text/event-stream into events with JSON data. +Stream parseEventStream(Stream chunks) async* { + var buf = ''; + await for (final chunk in chunks) { + buf += chunk.replaceAll('\r\n', '\n'); + var cut = buf.indexOf('\n\n'); + while (cut >= 0) { + final block = buf.substring(0, cut); + buf = buf.substring(cut + 2); + var name = 'message'; + final data = StringBuffer(); + for (final line in block.split('\n')) { + if (line.startsWith('event:')) { + name = line.substring(6).trim(); + } else if (line.startsWith('data:')) { + data.write(line.substring(5).trimLeft()); + } + } + if (data.isNotEmpty) { + final decoded = jsonDecode(data.toString()); + yield AiEvent(name, decoded is Map ? decoded : {}); + } + cut = buf.indexOf('\n\n'); + } + } +} + class DocwellApiException implements Exception { DocwellApiException( this.status, { diff --git a/Phone-App/lib/api/generated/models.dart b/Phone-App/lib/api/generated/models.dart index 15714f4..6437ec5 100644 --- a/Phone-App/lib/api/generated/models.dart +++ b/Phone-App/lib/api/generated/models.dart @@ -4175,12 +4175,14 @@ class AiAvailability { const AiAvailability({ required this.chat, required this.embeddings, + required this.transcribe, required this.canManage, }); factory AiAvailability.fromJson(Map json) => AiAvailability( chat: json['chat'] as bool, embeddings: json['embeddings'] as bool, + transcribe: json['transcribe'] as bool, canManage: json['canManage'] as bool, ); @@ -4190,12 +4192,16 @@ class AiAvailability { /// The workspace is indexed for retrieval final bool embeddings; + /// A profile can turn audio attachments into text + final bool transcribe; + /// The caller may change the workspace's AI settings final bool canManage; Map toJson() => { 'chat': chat, 'embeddings': embeddings, + 'transcribe': transcribe, 'canManage': canManage, }; } @@ -4206,6 +4212,7 @@ class AiSettings { required this.useInstanceProfiles, required this.index, required this.ignored, + required this.monthlyTokenLimit, }); factory AiSettings.fromJson(Map json) => AiSettings( @@ -4213,6 +4220,7 @@ class AiSettings { useInstanceProfiles: json['useInstanceProfiles'] as bool, index: json['index'] as bool, ignored: (json['ignored'] as List).map((e) => e as String).toList(), + monthlyTokenLimit: (json['monthlyTokenLimit'] as num).toInt(), ); final bool enabled; @@ -4226,11 +4234,15 @@ class AiSettings { /// Pages (with their subpages) that are neither indexed nor retrieved final List ignored; + /// Tokens the workspace may use per month; 0 is no cap + final int monthlyTokenLimit; + Map toJson() => { 'enabled': enabled, 'useInstanceProfiles': useInstanceProfiles, 'index': index, 'ignored': ignored.map((e) => e).toList(), + 'monthlyTokenLimit': monthlyTokenLimit, }; } @@ -4287,6 +4299,7 @@ class AiProfile { required this.keySet, required this.chatModel, required this.embedModel, + required this.transcribeModel, required this.effort, required this.enabled, required this.position, @@ -4305,6 +4318,7 @@ class AiProfile { keySet: json['keySet'] as bool, chatModel: json['chatModel'] as String, embedModel: json['embedModel'] as String, + transcribeModel: json['transcribeModel'] as String, effort: json['effort'] as String, enabled: json['enabled'] as bool, position: (json['position'] as num).toInt(), @@ -4334,6 +4348,9 @@ class AiProfile { /// Empty when the profile is not used for embeddings final String embedModel; + /// Speech-to-text model (OpenAI-compatible); empty when unused + final String transcribeModel; + /// Anthropic effort level final String effort; @@ -4358,6 +4375,7 @@ class AiProfile { 'keySet': keySet, 'chatModel': chatModel, 'embedModel': embedModel, + 'transcribeModel': transcribeModel, 'effort': effort, 'enabled': enabled, 'position': position, @@ -4396,6 +4414,7 @@ class AiProfileInput { this.apiKey, this.chatModel, this.embedModel, + this.transcribeModel, this.effort, this.enabled, }); @@ -4411,6 +4430,9 @@ class AiProfileInput { embedModel: json['embedModel'] == null ? null : json['embedModel'] as String, + transcribeModel: json['transcribeModel'] == null + ? null + : json['transcribeModel'] as String, effort: json['effort'] == null ? null : AiProfileInputEffort.fromJson(json['effort'] as String), @@ -4430,6 +4452,8 @@ class AiProfileInput { final String? embedModel; + final String? transcribeModel; + final AiProfileInputEffort? effort; final bool? enabled; @@ -4441,6 +4465,7 @@ class AiProfileInput { 'apiKey': ?apiKey, 'chatModel': ?chatModel, 'embedModel': ?embedModel, + 'transcribeModel': ?transcribeModel, 'effort': ?effort?.toJson(), 'enabled': ?enabled, }; @@ -4910,3 +4935,112 @@ class AiWriteInput { 'instruction': ?instruction, }; } + +class AiUsage { + const AiUsage({ + required this.workspace, + this.name, + required this.month, + required this.requests, + required this.inputTokens, + required this.outputTokens, + required this.instanceTokens, + required this.limit, + required this.instanceLimit, + }); + + factory AiUsage.fromJson(Map json) => AiUsage( + workspace: json['workspace'] as String, + name: json['name'] == null ? null : json['name'] as String, + month: json['month'] as String, + requests: (json['requests'] as num).toInt(), + inputTokens: (json['inputTokens'] as num).toInt(), + outputTokens: (json['outputTokens'] as num).toInt(), + instanceTokens: (json['instanceTokens'] as num).toInt(), + limit: (json['limit'] as num).toInt(), + instanceLimit: (json['instanceLimit'] as num).toInt(), + ); + + final String workspace; + + /// The workspace's name (admin listing) + final String? name; + + /// Calendar month in UTC, e.g. 2026-11 + final String month; + + final int requests; + + final int inputTokens; + + final int outputTokens; + + /// Tokens used through the server's own profiles + final int instanceTokens; + + /// The workspace's monthly token cap; 0 is none + final int limit; + + /// The server's cap on instanceTokens; 0 is none + final int instanceLimit; + + Map toJson() => { + 'workspace': workspace, + 'name': ?name, + 'month': month, + 'requests': requests, + 'inputTokens': inputTokens, + 'outputTokens': outputTokens, + 'instanceTokens': instanceTokens, + 'limit': limit, + 'instanceLimit': instanceLimit, + }; +} + +class AiInstanceSettings { + const AiInstanceSettings({required this.workspaceTokenLimit}); + + factory AiInstanceSettings.fromJson(Map json) => + AiInstanceSettings( + workspaceTokenLimit: (json['workspaceTokenLimit'] as num).toInt(), + ); + + /// Tokens one workspace may use through the server's profiles per month; 0 is no cap + final int workspaceTokenLimit; + + Map toJson() => {'workspaceTokenLimit': workspaceTokenLimit}; +} + +class AiTranscript { + const AiTranscript({ + required this.name, + required this.text, + required this.summary, + this.summaryError, + }); + + factory AiTranscript.fromJson(Map json) => AiTranscript( + name: json['name'] as String, + text: json['text'] as String, + summary: json['summary'] as String, + summaryError: json['summaryError'] == null + ? null + : json['summaryError'] as String, + ); + + final String name; + + final String text; + + /// Markdown; empty when not asked for or when it failed + final String summary; + + final String? summaryError; + + Map toJson() => { + 'name': name, + 'text': text, + 'summary': summary, + 'summaryError': ?summaryError, + }; +} diff --git a/Phone-App/lib/l10n.dart b/Phone-App/lib/l10n.dart index 9533357..6b9634a 100644 --- a/Phone-App/lib/l10n.dart +++ b/Phone-App/lib/l10n.dart @@ -37,6 +37,21 @@ String tr(String key, [Map args = const {}]) { const appStrings = >{ 'en': { + 'aiChat': 'AI chat', + 'aiHistory': 'Earlier chats', + 'aiUntitled': 'Untitled chat', + 'aiNewChat': 'New chat', + 'aiDelete': 'Delete this chat', + 'aiIntroPage': + 'Ask about “{title}”: summaries, answers and to-dos from this page.', + 'aiIntroWorkspace': + 'Ask about anything in this workspace. Answers link to their sources.', + 'aiThinking': 'Looking through the pages…', + 'aiFailed': 'The AI could not answer.', + 'aiAskPage': 'Ask about this page…', + 'aiAskWorkspace': 'Ask about the workspace…', + 'aiStop': 'Stop', + 'aiSend': 'Send', 'untitled': 'Untitled', 'someone': 'Someone', 'retry': 'Retry', @@ -140,6 +155,21 @@ const appStrings = >{ 'redo': 'Redo', }, 'pl': { + 'aiChat': 'Czat AI', + 'aiHistory': 'Wcześniejsze czaty', + 'aiUntitled': 'Czat bez tytułu', + 'aiNewChat': 'Nowy czat', + 'aiDelete': 'Usuń ten czat', + 'aiIntroPage': + 'Pytaj o „{title}”: podsumowania, odpowiedzi i zadania z tej strony.', + 'aiIntroWorkspace': + 'Pytaj o wszystko w tym obszarze roboczym. Odpowiedzi linkują do źródeł.', + 'aiThinking': 'Przegląda strony…', + 'aiFailed': 'AI nie mogło odpowiedzieć.', + 'aiAskPage': 'Zapytaj o tę stronę…', + 'aiAskWorkspace': 'Zapytaj o obszar roboczy…', + 'aiStop': 'Zatrzymaj', + 'aiSend': 'Wyślij', 'untitled': 'Bez tytułu', 'someone': 'Ktoś', 'retry': 'Spróbuj ponownie', @@ -243,6 +273,21 @@ const appStrings = >{ 'redo': 'Ponów', }, 'de': { + 'aiChat': 'KI-Chat', + 'aiHistory': 'Frühere Chats', + 'aiUntitled': 'Chat ohne Titel', + 'aiNewChat': 'Neuer Chat', + 'aiDelete': 'Diesen Chat löschen', + 'aiIntroPage': + 'Fragen zu „{title}“: Zusammenfassungen, Antworten und Aufgaben aus dieser Seite.', + 'aiIntroWorkspace': + 'Fragen zu allem in diesem Arbeitsbereich. Antworten verlinken ihre Quellen.', + 'aiThinking': 'Durchsucht die Seiten …', + 'aiFailed': 'Die KI konnte nicht antworten.', + 'aiAskPage': 'Frage zu dieser Seite …', + 'aiAskWorkspace': 'Frage zum Arbeitsbereich …', + 'aiStop': 'Stopp', + 'aiSend': 'Senden', 'untitled': 'Ohne Titel', 'someone': 'Jemand', 'retry': 'Erneut versuchen', @@ -348,6 +393,21 @@ const appStrings = >{ 'redo': 'Wiederholen', }, 'fr': { + 'aiChat': 'Chat IA', + 'aiHistory': 'Chats précédents', + 'aiUntitled': 'Chat sans titre', + 'aiNewChat': 'Nouveau chat', + 'aiDelete': 'Supprimer ce chat', + 'aiIntroPage': + 'Posez vos questions sur « {title} » : résumés, réponses et tâches tirés de cette page.', + 'aiIntroWorkspace': + 'Posez vos questions sur tout cet espace de travail. Les réponses renvoient à leurs sources.', + 'aiThinking': 'Parcours des pages…', + 'aiFailed': 'L’IA n’a pas pu répondre.', + 'aiAskPage': 'Question sur cette page…', + 'aiAskWorkspace': 'Question sur l’espace de travail…', + 'aiStop': 'Arrêter', + 'aiSend': 'Envoyer', 'untitled': 'Sans titre', 'someone': 'Quelqu’un', 'retry': 'Réessayer', @@ -453,6 +513,21 @@ const appStrings = >{ 'redo': 'Rétablir', }, 'es': { + 'aiChat': 'Chat de IA', + 'aiHistory': 'Chats anteriores', + 'aiUntitled': 'Chat sin título', + 'aiNewChat': 'Chat nuevo', + 'aiDelete': 'Eliminar este chat', + 'aiIntroPage': + 'Pregunta sobre «{title}»: resúmenes, respuestas y tareas de esta página.', + 'aiIntroWorkspace': + 'Pregunta sobre cualquier cosa de este espacio de trabajo. Las respuestas enlazan sus fuentes.', + 'aiThinking': 'Buscando en las páginas…', + 'aiFailed': 'La IA no pudo responder.', + 'aiAskPage': 'Pregunta sobre esta página…', + 'aiAskWorkspace': 'Pregunta sobre el espacio de trabajo…', + 'aiStop': 'Detener', + 'aiSend': 'Enviar', 'untitled': 'Sin título', 'someone': 'Alguien', 'retry': 'Reintentar', diff --git a/Phone-App/lib/screens/ai_chat_screen.dart b/Phone-App/lib/screens/ai_chat_screen.dart new file mode 100644 index 0000000..9d1b716 --- /dev/null +++ b/Phone-App/lib/screens/ai_chat_screen.dart @@ -0,0 +1,456 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import 'dart:async'; + +import 'package:flutter/material.dart'; + +import '../api/docwell_api.dart'; +import '../app.dart'; +import '../l10n.dart'; +import 'page_screen.dart'; +import 'widgets.dart'; + +/// The AI chat (ADR-15): questions about the workspace or one page, with +/// answers that cite the pages they come from. Chats are the same as in the +/// web app's panel. +class AiChatScreen extends StatefulWidget { + const AiChatScreen({ + super.key, + required this.session, + required this.workspace, + this.page, + this.pageTitle = '', + }); + + final AppSession session; + final String workspace; + + /// Asks about this page instead of the whole workspace. + final String? page; + final String pageTitle; + + @override + State createState() => _AiChatScreenState(); +} + +class _AiChatScreenState extends State { + final _input = TextEditingController(); + final _scroll = ScrollController(); + List _sessions = []; + AiSession? _chat; + String? _error; + bool _busy = false; + // The answer being streamed. + String? _question; + String _answer = ''; + List _sources = []; + StreamSubscription? _stream; + + DocwellApi get _api => widget.session.api; + + AiScope get _scope => widget.page != null ? AiScope.page : AiScope.workspace; + + @override + void initState() { + super.initState(); + _loadSessions(); + } + + @override + void dispose() { + _stream?.cancel(); + _input.dispose(); + _scroll.dispose(); + super.dispose(); + } + + Future _loadSessions() async { + try { + final list = await _api.aiSessions(widget.workspace); + if (mounted) setState(() => _sessions = list); + } catch (_) { + // The list is a convenience; asking still works without it. + } + } + + Future _open(String id) async { + try { + final s = await _api.aiSession(id); + if (!mounted) return; + setState(() { + _chat = s; + _error = null; + }); + _toEnd(); + } catch (e) { + if (mounted) setState(() => _error = describeError(e)); + } + } + + void _toEnd() { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (_scroll.hasClients) { + _scroll.jumpTo(_scroll.position.maxScrollExtent); + } + }); + } + + Future _send() async { + final q = _input.text.trim(); + if (q.isEmpty || _busy) return; + setState(() { + _busy = true; + _error = null; + _question = q; + _answer = ''; + _sources = []; + }); + _input.clear(); + _toEnd(); + try { + final chat = + _chat ?? + await _api.createAiSession( + widget.workspace, + _scope, + scopeId: widget.page ?? '', + ); + _chat = chat; + final done = Completer(); + _stream = _api + .ask(chat.id, q) + .listen( + (e) { + if (!mounted) return; + setState(() { + switch (e.name) { + case 'sources': + _sources = ((e.data['citations'] as List?) ?? []) + .map( + (c) => AiCitation.fromJson(c as Map), + ) + .toList(); + case 'delta': + _answer += e.data['text'] as String? ?? ''; + case 'error': + _error = e.data['message'] as String? ?? tr('aiFailed'); + } + }); + _toEnd(); + }, + onError: (Object err) { + if (mounted) setState(() => _error = describeError(err)); + if (!done.isCompleted) done.complete(); + }, + onDone: () { + if (!done.isCompleted) done.complete(); + }, + ); + await done.future; + } catch (e) { + if (mounted) setState(() => _error = describeError(e)); + } finally { + _stream = null; + if (mounted) { + setState(() { + _busy = false; + _question = null; + }); + // Show the turn as the server stored it. + if (_chat != null) await _open(_chat!.id); + await _loadSessions(); + } + } + } + + void _stop() => _stream?.cancel().then((_) { + if (mounted) setState(() => _busy = false); + }); + + void _newChat() => setState(() { + _chat = null; + _error = null; + }); + + Future _delete() async { + final chat = _chat; + if (chat == null) return; + try { + await _api.deleteAiSession(chat.id); + _newChat(); + await _loadSessions(); + } catch (e) { + if (mounted) setState(() => _error = describeError(e)); + } + } + + void _openSource(AiCitation c) { + final page = c.page; + if (page == null || page.isEmpty) return; + Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => PageScreen( + session: widget.session, + pageId: page, + target: (c.block ?? '').isEmpty ? null : '#b-${c.block}', + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final messages = _chat?.messages ?? const []; + final empty = messages.isEmpty && _question == null; + return Scaffold( + appBar: AppBar( + title: Text( + _chat?.title.isNotEmpty == true ? _chat!.title : tr('aiChat'), + overflow: TextOverflow.ellipsis, + ), + actions: [ + if (_sessions.isNotEmpty) + PopupMenuButton( + tooltip: tr('aiHistory'), + icon: const Icon(Icons.history), + onSelected: _open, + itemBuilder: (_) => [ + for (final s in _sessions) + PopupMenuItem( + value: s.id, + child: Text( + s.title.isEmpty ? tr('aiUntitled') : s.title, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + IconButton( + key: const Key('ai-new'), + tooltip: tr('aiNewChat'), + icon: const Icon(Icons.add_comment_outlined), + onPressed: _busy ? null : _newChat, + ), + if (_chat != null) + IconButton( + tooltip: tr('aiDelete'), + icon: const Icon(Icons.delete_outline), + onPressed: _busy ? null : _delete, + ), + ], + ), + body: Column( + children: [ + Expanded( + child: ListView( + controller: _scroll, + padding: const EdgeInsets.all(12), + children: [ + if (empty) + Padding( + padding: const EdgeInsets.symmetric(vertical: 32), + child: Text( + widget.page != null + ? tr('aiIntroPage', { + 'title': widget.pageTitle.isEmpty + ? tr('untitled') + : widget.pageTitle, + }) + : tr('aiIntroWorkspace'), + textAlign: TextAlign.center, + style: TextStyle( + color: Theme.of(context).colorScheme.onSurfaceVariant, + ), + ), + ), + for (final m in messages) + m.role == AiMessageRole.user + ? _Question(m.content) + : _Answer( + text: m.content, + error: m.error, + sources: m.citations ?? const [], + onSource: _openSource, + ), + if (_question != null) ...[ + _Question(_question!), + _Answer( + text: _answer.isEmpty ? tr('aiThinking') : _answer, + sources: _sources, + onSource: _openSource, + pending: _answer.isEmpty, + ), + ], + if (_error != null) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text( + _error!, + style: TextStyle( + color: Theme.of(context).colorScheme.error, + ), + ), + ), + ], + ), + ), + SafeArea( + top: false, + child: Padding( + padding: const EdgeInsets.fromLTRB(12, 4, 8, 8), + child: Row( + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Expanded( + child: TextField( + key: const Key('ai-input'), + controller: _input, + minLines: 1, + maxLines: 5, + maxLength: 8000, + textInputAction: TextInputAction.send, + onSubmitted: (_) => _send(), + decoration: InputDecoration( + hintText: widget.page != null + ? tr('aiAskPage') + : tr('aiAskWorkspace'), + counterText: '', + border: const OutlineInputBorder(), + isDense: true, + ), + ), + ), + const SizedBox(width: 4), + _busy + ? IconButton( + tooltip: tr('aiStop'), + icon: const Icon(Icons.stop_circle_outlined), + onPressed: _stop, + ) + : IconButton( + key: const Key('ai-send'), + tooltip: tr('aiSend'), + icon: const Icon(Icons.send), + onPressed: _send, + ), + ], + ), + ), + ), + ], + ), + ); + } +} + +class _Question extends StatelessWidget { + const _Question(this.text); + final String text; + + @override + Widget build(BuildContext context) => Align( + alignment: Alignment.centerRight, + child: Container( + margin: const EdgeInsets.only(left: 48, bottom: 12), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Theme.of(context).colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: SelectableText(text), + ), + ); +} + +class _Answer extends StatelessWidget { + const _Answer({ + required this.text, + required this.sources, + required this.onSource, + this.error, + this.pending = false, + }); + + final String text; + final String? error; + final List sources; + final void Function(AiCitation) onSource; + final bool pending; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final used = citedNumbers(text); + final cited = sources.where((c) => used.contains(c.n)).toList(); + return Padding( + padding: const EdgeInsets.only(bottom: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SelectableText( + plainMarkdown(text), + style: pending + ? TextStyle(color: theme.colorScheme.onSurfaceVariant) + : null, + ), + if ((error ?? '').isNotEmpty) + Text(error!, style: TextStyle(color: theme.colorScheme.error)), + for (final c in cited) + ListTile( + dense: true, + contentPadding: EdgeInsets.zero, + leading: CircleAvatar(radius: 11, child: Text('${c.n}')), + title: Text( + c.title.isEmpty ? tr('untitled') : c.title, + overflow: TextOverflow.ellipsis, + ), + subtitle: Text( + c.snippet, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + trailing: (c.page ?? '').isEmpty + ? const Icon(Icons.attach_file, size: 18) + : const Icon(Icons.chevron_right), + onTap: (c.page ?? '').isEmpty ? null : () => onSource(c), + ), + ], + ), + ); + } +} + +/// The source numbers an answer cites as [n]. +Set citedNumbers(String text) => RegExp( + r'\[(\d{1,2})\]', +).allMatches(text).map((m) => int.parse(m.group(1)!)).toSet(); + +/// Answers are Markdown; the phone shows them as plain text with list +/// bullets, without the markup characters. +String plainMarkdown(String md) { + final out = []; + for (var line in md.split('\n')) { + line = line.replaceFirst(RegExp(r'^\s*#{1,6}\s+'), ''); + line = line.replaceFirstMapped( + RegExp(r'^(\s*)[-*+]\s+\[ \]\s+'), + (m) => '${m[1]}☐ ', + ); + line = line.replaceFirstMapped( + RegExp(r'^(\s*)[-*+]\s+\[[xX]\]\s+'), + (m) => '${m[1]}☑ ', + ); + line = line.replaceFirstMapped( + RegExp(r'^(\s*)[-*+]\s+'), + (m) => '${m[1]}• ', + ); + line = line + .replaceAll(RegExp(r'\*\*|__'), '') + .replaceAll('`', '') + .replaceAllMapped( + RegExp(r'\[([^\]]+)\]\((https?://[^)]+)\)'), + (m) => '${m[1]} (${m[2]})', + ); + out.add(line); + } + return out.join('\n').trim(); +} diff --git a/Phone-App/lib/screens/home_screen.dart b/Phone-App/lib/screens/home_screen.dart index 56e27e5..bd29b43 100644 --- a/Phone-App/lib/screens/home_screen.dart +++ b/Phone-App/lib/screens/home_screen.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import '../api/docwell_api.dart'; import '../app.dart'; +import 'ai_chat_screen.dart'; import 'notifications_screen.dart'; import 'page_screen.dart'; import 'search_screen.dart'; @@ -29,6 +30,8 @@ class _HomeScreenState extends State { List _spaces = []; List _recent = []; int _unread = 0; + // The workspace has an AI chat (ADR-15). + bool _ai = false; String? _error; bool _offline = false; @@ -52,6 +55,12 @@ class _HomeScreenState extends State { offline |= _api.offline; recent = await _api.recent(ws.id).catchError((_) => []); } + final ai = ws == null || offline + ? false + : await _api + .aiAvailability(ws.id) + .then((a) => a.chat) + .catchError((_) => false); final unread = offline ? _unread : await _api @@ -65,6 +74,7 @@ class _HomeScreenState extends State { _spaces = spaces; _recent = recent; _unread = unread; + _ai = ai; _offline = offline; _error = null; }); @@ -172,6 +182,15 @@ class _HomeScreenState extends State { onPressed: () => _open(SearchScreen(session: widget.session, workspace: ws)), ), + if (ws != null && _ai) + IconButton( + key: const Key('ai-chat'), + tooltip: tr('aiChat'), + icon: const Icon(Icons.auto_awesome_outlined), + onPressed: () => _open( + AiChatScreen(session: widget.session, workspace: ws.id), + ), + ), IconButton( tooltip: tr('inbox'), icon: Badge( diff --git a/Phone-App/lib/screens/page_screen.dart b/Phone-App/lib/screens/page_screen.dart index cc433eb..560a88b 100644 --- a/Phone-App/lib/screens/page_screen.dart +++ b/Phone-App/lib/screens/page_screen.dart @@ -15,6 +15,7 @@ import '../editor/editor_screen.dart' editorNavigation, editorView, loadEditorPage; +import 'ai_chat_screen.dart'; import 'comments_screen.dart'; import 'widgets.dart'; import '../l10n.dart'; @@ -53,6 +54,8 @@ class _PageScreenState extends State { StreamSubscription? _links; Page? _page; + // The page's workspace has an AI chat. + bool _ai = false; Map? _content; String? _error; bool _offline = false; @@ -110,6 +113,16 @@ class _PageScreenState extends State { final content = await _api.content(widget.pageId); offline |= _api.offline; if (!offline) unawaited(_api.visit(widget.pageId).catchError((_) {})); + if (!offline) { + unawaited( + _api + .aiAvailability(page.workspace) + .then((a) { + if (mounted) setState(() => _ai = a.chat); + }) + .catchError((_) {}), + ); + } if (!mounted) return; setState(() { _page = page; @@ -236,6 +249,22 @@ class _PageScreenState extends State { ), onPressed: _bridge.isReady ? _toggleCanvas : null, ), + if (page != null && !_offline && _ai) + IconButton( + key: const Key('ai-chat'), + tooltip: tr('aiChat'), + icon: const Icon(Icons.auto_awesome_outlined), + onPressed: () => Navigator.of(context).push( + MaterialPageRoute( + builder: (_) => AiChatScreen( + session: widget.session, + workspace: page.workspace, + page: page.id, + pageTitle: page.title, + ), + ), + ), + ), if (page != null && !_offline) IconButton( tooltip: tr('comments'), diff --git a/Phone-App/test/ai_test.dart b/Phone-App/test/ai_test.dart new file mode 100644 index 0000000..4887db0 --- /dev/null +++ b/Phone-App/test/ai_test.dart @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-or-later + +import 'package:docwell_mobile/api/docwell_api.dart'; +import 'package:docwell_mobile/screens/ai_chat_screen.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + test('parseEventStream splits events across chunks', () async { + final chunks = Stream.fromIterable([ + 'event: sources\ndata: {"citations":[]}\n\nevent: del', + 'ta\ndata: {"text":"Hi"}\r\n\r\n', + 'event: done\ndata: {}\n\n', + ]); + final events = await parseEventStream(chunks).toList(); + expect(events.map((e) => e.name), ['sources', 'delta', 'done']); + expect(events[1].data['text'], 'Hi'); + }); + + test('plainMarkdown drops markup and keeps lists readable', () { + expect( + plainMarkdown('## Plan\n\n- **one** [1]\n- [ ] call `Ana`\n'), + 'Plan\n\n• one [1]\n☐ call Ana', + ); + expect(citedNumbers('a [1] b [12][3]'), {1, 12, 3}); + }); +} diff --git a/Server/admin/src/locales/de.json b/Server/admin/src/locales/de.json index b342578..d6b8dc1 100644 --- a/Server/admin/src/locales/de.json +++ b/Server/admin/src/locales/de.json @@ -307,6 +307,17 @@ "effortDefault": "Standard des Modells", "add": "Anbieter hinzufügen", "mcpTitle": "MCP-Server", - "mcpHint": "KI-Agenten und Werkzeuge verbinden sich mit /mcp auf diesem Server über ein persönliches API-Token (lesen oder lesen und schreiben). Sie handeln als Besitzer des Tokens, mit dessen Rechten." + "mcpHint": "KI-Agenten und Werkzeuge verbinden sich mit /mcp auf diesem Server über ein persönliches API-Token (lesen oder lesen und schreiben). Sie handeln als Besitzer des Tokens, mit dessen Rechten.", + "speech": "Sprache", + "transcribeModel": "Sprache-zu-Text-Modell", + "usageTitle": "Verbrauch in diesem Monat", + "limitHint": "Begrenzt, wie viel jeder Arbeitsbereich pro Monat (UTC) über die Anbieter oben verbrauchen darf. Danach nutzen Arbeitsbereiche weiter ihre eigenen Anbieter.", + "limit": "Tokens pro Arbeitsbereich und Monat", + "noLimit": "Kein Limit", + "workspace": "Arbeitsbereich", + "requests": "Anfragen", + "tokens": "Tokens", + "serverTokens": "Über den Server", + "noUsage": "In diesem Monat noch keine KI-Nutzung." } } diff --git a/Server/admin/src/locales/en.json b/Server/admin/src/locales/en.json index 7c6840c..5c5e157 100644 --- a/Server/admin/src/locales/en.json +++ b/Server/admin/src/locales/en.json @@ -307,6 +307,17 @@ "effortDefault": "Model default", "add": "Add a provider", "mcpTitle": "MCP server", - "mcpHint": "AI agents and tools connect to /mcp on this server with a personal API token (read, or read and write). They act as the token's owner, with that person's rights." + "mcpHint": "AI agents and tools connect to /mcp on this server with a personal API token (read, or read and write). They act as the token's owner, with that person's rights.", + "speech": "speech", + "transcribeModel": "Speech-to-text model", + "usageTitle": "Usage this month", + "limitHint": "Cap what each workspace may use through the providers above per month (UTC). Workspaces keep using their own providers after that.", + "limit": "Tokens per workspace per month", + "noLimit": "No limit", + "workspace": "Workspace", + "requests": "Requests", + "tokens": "Tokens", + "serverTokens": "Through the server", + "noUsage": "No AI use this month yet." } } diff --git a/Server/admin/src/locales/es.json b/Server/admin/src/locales/es.json index 96df0d1..ad8c979 100644 --- a/Server/admin/src/locales/es.json +++ b/Server/admin/src/locales/es.json @@ -307,6 +307,17 @@ "effortDefault": "El del modelo", "add": "Añadir un proveedor", "mcpTitle": "Servidor MCP", - "mcpHint": "Los agentes y herramientas de IA se conectan a /mcp en este servidor con un token de API personal (lectura, o lectura y escritura). Actúan como el dueño del token, con sus permisos." + "mcpHint": "Los agentes y herramientas de IA se conectan a /mcp en este servidor con un token de API personal (lectura, o lectura y escritura). Actúan como el dueño del token, con sus permisos.", + "speech": "voz", + "transcribeModel": "Modelo de voz a texto", + "usageTitle": "Consumo este mes", + "limitHint": "Limita lo que cada espacio de trabajo puede consumir al mes (UTC) con los proveedores de arriba. Después, los espacios siguen con sus propios proveedores.", + "limit": "Tokens por espacio de trabajo y mes", + "noLimit": "Sin límite", + "workspace": "Espacio de trabajo", + "requests": "Solicitudes", + "tokens": "Tokens", + "serverTokens": "Con el servidor", + "noUsage": "Aún no hay uso de IA este mes." } } diff --git a/Server/admin/src/locales/fr.json b/Server/admin/src/locales/fr.json index 5d4b407..f4d2f9b 100644 --- a/Server/admin/src/locales/fr.json +++ b/Server/admin/src/locales/fr.json @@ -307,6 +307,17 @@ "effortDefault": "Valeur du modèle", "add": "Ajouter un fournisseur", "mcpTitle": "Serveur MCP", - "mcpHint": "Les agents et outils d’IA se connectent à /mcp sur ce serveur avec un jeton d’API personnel (lecture, ou lecture et écriture). Ils agissent comme le propriétaire du jeton, avec ses droits." + "mcpHint": "Les agents et outils d’IA se connectent à /mcp sur ce serveur avec un jeton d’API personnel (lecture, ou lecture et écriture). Ils agissent comme le propriétaire du jeton, avec ses droits.", + "speech": "parole", + "transcribeModel": "Modèle de transcription", + "usageTitle": "Consommation ce mois-ci", + "limitHint": "Plafonne ce que chaque espace de travail peut consommer par mois (UTC) via les fournisseurs ci-dessus. Ensuite, les espaces de travail continuent avec leurs propres fournisseurs.", + "limit": "Jetons par espace de travail et par mois", + "noLimit": "Aucune limite", + "workspace": "Espace de travail", + "requests": "Requêtes", + "tokens": "Jetons", + "serverTokens": "Via le serveur", + "noUsage": "Aucune utilisation de l’IA ce mois-ci." } } diff --git a/Server/admin/src/locales/pl.json b/Server/admin/src/locales/pl.json index 9f4dc64..dab1261 100644 --- a/Server/admin/src/locales/pl.json +++ b/Server/admin/src/locales/pl.json @@ -307,6 +307,17 @@ "effortDefault": "Domyślny modelu", "add": "Dodaj dostawcę", "mcpTitle": "Serwer MCP", - "mcpHint": "Agenci i narzędzia AI łączą się z /mcp na tym serwerze za pomocą osobistego tokenu API (odczyt albo odczyt i zapis). Działają jako właściciel tokenu, z jego uprawnieniami." + "mcpHint": "Agenci i narzędzia AI łączą się z /mcp na tym serwerze za pomocą osobistego tokenu API (odczyt albo odczyt i zapis). Działają jako właściciel tokenu, z jego uprawnieniami.", + "speech": "mowa", + "transcribeModel": "Model zamiany mowy na tekst", + "usageTitle": "Zużycie w tym miesiącu", + "limitHint": "Ogranicza, ile każdy obszar roboczy może zużyć miesięcznie (UTC) przez dostawców powyżej. Potem obszary nadal korzystają z własnych dostawców.", + "limit": "Tokeny na obszar roboczy miesięcznie", + "noLimit": "Bez limitu", + "workspace": "Obszar roboczy", + "requests": "Zapytania", + "tokens": "Tokeny", + "serverTokens": "Przez serwer", + "noUsage": "W tym miesiącu nie użyto jeszcze AI." } } diff --git a/Server/admin/src/views/AiView.vue b/Server/admin/src/views/AiView.vue index 0ae1089..4909d1f 100644 --- a/Server/admin/src/views/AiView.vue +++ b/Server/admin/src/views/AiView.vue @@ -1,6 +1,6 @@