Add audio transcripts, monthly AI limits, PDF sources and AI chat on phones
CI / go (Server) (push) Failing after 25m5s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m38s
CI / desktop (ubuntu-latest) (push) Successful in 1h41m20s
CI / mobile (push) Failing after 4m19s
CI / docker (push) Failing after 44m8s
Docs / build (push) Successful in 17m11s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Server) (push) Failing after 25m5s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 8m38s
CI / desktop (ubuntu-latest) (push) Successful in 1h41m20s
CI / mobile (push) Failing after 4m19s
CI / docker (push) Failing after 44m8s
Docs / build (push) Successful in 17m11s
Docs / deploy (push) Skipped
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
78b7710090
commit
0ebf064173
50 files changed
+2724
-79
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
/// <reference path="../pb_data/types.d.ts" />
|
||||
|
||||
// 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);
|
||||
},
|
||||
);
|
||||
@@ -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://<server>/mcp` with a
|
||||
personal API token: read-only tokens can list, search and read pages and ask the workspace's AI; write tokens can
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<AiFile>(`/api/v1/workspaces/${enc(workspace)}/ai/files`, form);
|
||||
},
|
||||
deleteFile: (id: string) => request<void>("DELETE", `/api/v1/ai/files/${enc(id)}`),
|
||||
/** This month's usage of a workspace, with its caps (workspace admin). */
|
||||
usage: (workspace: string) => request<AiUsage>("GET", `/api/v1/workspaces/${enc(workspace)}/ai/usage`),
|
||||
/** Every workspace's usage this month (superadmin). */
|
||||
allUsage: () => request<AiUsage[]>("GET", "/api/v1/admin/ai/usage"),
|
||||
instanceSettings: () => request<AiInstanceSettings>("GET", "/api/v1/admin/ai/settings"),
|
||||
saveInstanceSettings: (input: AiInstanceSettings) =>
|
||||
request<AiInstanceSettings>("PUT", "/api/v1/admin/ai/settings", input),
|
||||
/** Turns an audio or video attachment into text (and a summary). */
|
||||
transcribe: (fileId: string, summarize = true) =>
|
||||
post<AiTranscript>(`/api/v1/files/${enc(fileId)}/transcribe`, { summarize }),
|
||||
sessions: (workspace: string) =>
|
||||
request<AiSessionSummary[]>("GET", `/api/v1/workspaces/${enc(workspace)}/ai/sessions`),
|
||||
createSession: (workspace: string, input: AiSessionInput) =>
|
||||
|
||||
Vendored
+233
@@ -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<string, never>;
|
||||
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"];
|
||||
};
|
||||
};
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -14,6 +14,17 @@ import { isPdf, showPdf, type PdfLoader } from "./pdf";
|
||||
export interface FileHost {
|
||||
resolve(src: string): string;
|
||||
upload?(file: File): Promise<UploadedFile>;
|
||||
/**
|
||||
* 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<string>;
|
||||
}
|
||||
|
||||
/** 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<FileAttachmentOptions>({
|
||||
},
|
||||
|
||||
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<FileAttachmentOptions>({
|
||||
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<FileAttachmentOptions>({
|
||||
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<FileAttachmentOptions>({
|
||||
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?.(),
|
||||
};
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -194,6 +194,67 @@ class DocwellApi {
|
||||
Future<void> 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> aiAvailability(String workspace) async =>
|
||||
AiAvailability.fromJson(
|
||||
await _send('GET', '/api/v1/workspaces/${_id(workspace)}/ai'),
|
||||
);
|
||||
|
||||
Future<List<AiSessionSummary>> aiSessions(String workspace) async =>
|
||||
((await _send(
|
||||
'GET',
|
||||
'/api/v1/workspaces/${_id(workspace)}/ai/sessions',
|
||||
))['items']
|
||||
as List<dynamic>)
|
||||
.map((e) => AiSessionSummary.fromJson(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
Future<AiSession> aiSession(String id) async =>
|
||||
AiSession.fromJson(await _send('GET', '/api/v1/ai/sessions/${_id(id)}'));
|
||||
|
||||
Future<AiSession> 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<void> 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<AiEvent> 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<String, dynamic> data = {};
|
||||
try {
|
||||
data = jsonDecode(text) as Map<String, dynamic>;
|
||||
} 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<String, dynamic> data;
|
||||
}
|
||||
|
||||
/// Splits a text/event-stream into events with JSON data.
|
||||
Stream<AiEvent> parseEventStream(Stream<String> 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<String, dynamic> ? decoded : {});
|
||||
}
|
||||
cut = buf.indexOf('\n\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class DocwellApiException implements Exception {
|
||||
DocwellApiException(
|
||||
this.status, {
|
||||
|
||||
@@ -4175,12 +4175,14 @@ class AiAvailability {
|
||||
const AiAvailability({
|
||||
required this.chat,
|
||||
required this.embeddings,
|
||||
required this.transcribe,
|
||||
required this.canManage,
|
||||
});
|
||||
|
||||
factory AiAvailability.fromJson(Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String> ignored;
|
||||
|
||||
/// Tokens the workspace may use per month; 0 is no cap
|
||||
final int monthlyTokenLimit;
|
||||
|
||||
Map<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> 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<String, dynamic> toJson() => {'workspaceTokenLimit': workspaceTokenLimit};
|
||||
}
|
||||
|
||||
class AiTranscript {
|
||||
const AiTranscript({
|
||||
required this.name,
|
||||
required this.text,
|
||||
required this.summary,
|
||||
this.summaryError,
|
||||
});
|
||||
|
||||
factory AiTranscript.fromJson(Map<String, dynamic> 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<String, dynamic> toJson() => {
|
||||
'name': name,
|
||||
'text': text,
|
||||
'summary': summary,
|
||||
'summaryError': ?summaryError,
|
||||
};
|
||||
}
|
||||
@@ -37,6 +37,21 @@ String tr(String key, [Map<String, Object> args = const {}]) {
|
||||
|
||||
const appStrings = <String, Map<String, String>>{
|
||||
'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 = <String, Map<String, String>>{
|
||||
'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 = <String, Map<String, String>>{
|
||||
'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 = <String, Map<String, String>>{
|
||||
'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 = <String, Map<String, String>>{
|
||||
'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',
|
||||
|
||||
@@ -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<AiChatScreen> createState() => _AiChatScreenState();
|
||||
}
|
||||
|
||||
class _AiChatScreenState extends State<AiChatScreen> {
|
||||
final _input = TextEditingController();
|
||||
final _scroll = ScrollController();
|
||||
List<AiSessionSummary> _sessions = [];
|
||||
AiSession? _chat;
|
||||
String? _error;
|
||||
bool _busy = false;
|
||||
// The answer being streamed.
|
||||
String? _question;
|
||||
String _answer = '';
|
||||
List<AiCitation> _sources = [];
|
||||
StreamSubscription<AiEvent>? _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<void> _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<void> _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<void> _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<void>();
|
||||
_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<String, dynamic>),
|
||||
)
|
||||
.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<void> _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<void>(
|
||||
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 <AiMessage>[];
|
||||
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<String>(
|
||||
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<AiCitation> 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<int> 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 = <String>[];
|
||||
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();
|
||||
}
|
||||
@@ -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<HomeScreen> {
|
||||
List<Space> _spaces = [];
|
||||
List<PageItem> _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<HomeScreen> {
|
||||
offline |= _api.offline;
|
||||
recent = await _api.recent(ws.id).catchError((_) => <PageItem>[]);
|
||||
}
|
||||
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<HomeScreen> {
|
||||
_spaces = spaces;
|
||||
_recent = recent;
|
||||
_unread = unread;
|
||||
_ai = ai;
|
||||
_offline = offline;
|
||||
_error = null;
|
||||
});
|
||||
@@ -172,6 +182,15 @@ class _HomeScreenState extends State<HomeScreen> {
|
||||
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(
|
||||
|
||||
@@ -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<PageScreen> {
|
||||
StreamSubscription<String>? _links;
|
||||
|
||||
Page? _page;
|
||||
// The page's workspace has an AI chat.
|
||||
bool _ai = false;
|
||||
Map<String, dynamic>? _content;
|
||||
String? _error;
|
||||
bool _offline = false;
|
||||
@@ -110,6 +113,16 @@ class _PageScreenState extends State<PageScreen> {
|
||||
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<PageScreen> {
|
||||
),
|
||||
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<void>(
|
||||
builder: (_) => AiChatScreen(
|
||||
session: widget.session,
|
||||
workspace: page.workspace,
|
||||
page: page.id,
|
||||
pageTitle: page.title,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (page != null && !_offline)
|
||||
IconButton(
|
||||
tooltip: tr('comments'),
|
||||
|
||||
@@ -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});
|
||||
});
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { AiProfile, AiProfileInput, AiProviderKind, AiTestResult } from "@docwell/api-client";
|
||||
import type { AiProfile, AiProfileInput, AiProviderKind, AiTestResult, AiUsage } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onMounted, reactive, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
@@ -25,8 +25,12 @@ const form = reactive({
|
||||
apiKey: "",
|
||||
chatModel: "",
|
||||
embedModel: "",
|
||||
transcribeModel: "",
|
||||
effort: "",
|
||||
});
|
||||
const usage = ref<AiUsage[]>([]);
|
||||
const limitInput = ref("");
|
||||
const limitSaved = ref(false);
|
||||
|
||||
async function run(action: () => Promise<unknown>) {
|
||||
busy.value = true;
|
||||
@@ -43,11 +47,34 @@ async function run(action: () => Promise<unknown>) {
|
||||
const load = () =>
|
||||
run(async () => {
|
||||
profiles.value = await api.ai.profiles("");
|
||||
const inst = await api.ai.instanceSettings();
|
||||
limitInput.value = inst.workspaceTokenLimit ? String(inst.workspaceTokenLimit) : "";
|
||||
usage.value = await api.ai.allUsage();
|
||||
});
|
||||
onMounted(load);
|
||||
|
||||
const saveLimit = () =>
|
||||
run(async () => {
|
||||
const n = Math.max(0, Math.round(Number(limitInput.value) || 0));
|
||||
await api.ai.saveInstanceSettings({ workspaceTokenLimit: n });
|
||||
limitInput.value = n ? String(n) : "";
|
||||
usage.value = await api.ai.allUsage();
|
||||
limitSaved.value = true;
|
||||
setTimeout(() => (limitSaved.value = false), 2000);
|
||||
});
|
||||
const num = (n: number) => new Intl.NumberFormat(locale.value).format(n);
|
||||
|
||||
function startNew() {
|
||||
Object.assign(form, { name: "", kind: "openai", baseUrl: "", apiKey: "", chatModel: "", embedModel: "", effort: "" });
|
||||
Object.assign(form, {
|
||||
name: "",
|
||||
kind: "openai",
|
||||
baseUrl: "",
|
||||
apiKey: "",
|
||||
chatModel: "",
|
||||
embedModel: "",
|
||||
transcribeModel: "",
|
||||
effort: "",
|
||||
});
|
||||
keyTouched.value = false;
|
||||
editing.value = "new";
|
||||
}
|
||||
@@ -62,6 +89,7 @@ function setKind(kind: AiProviderKind) {
|
||||
if (form.chatModel === DEFAULT_CHAT[form.kind]) form.chatModel = DEFAULT_CHAT[kind];
|
||||
if (kind === "anthropic") form.embedModel = "";
|
||||
else form.effort = "";
|
||||
if (kind !== "openai") form.transcribeModel = "";
|
||||
form.kind = kind;
|
||||
}
|
||||
|
||||
@@ -73,6 +101,7 @@ const save = () =>
|
||||
baseUrl: form.baseUrl.trim(),
|
||||
chatModel: form.chatModel.trim(),
|
||||
embedModel: form.embedModel.trim(),
|
||||
transcribeModel: form.transcribeModel.trim(),
|
||||
effort: form.effort as AiProfileInput["effort"],
|
||||
};
|
||||
if (editing.value === "new" || keyTouched.value) input.apiKey = form.apiKey.trim();
|
||||
@@ -149,6 +178,7 @@ const total = computed(() =>
|
||||
{{ $t(`ai.kinds.${p.kind}`) }}
|
||||
<template v-if="p.chatModel"> · {{ p.chatModel }}</template>
|
||||
<template v-if="p.embedModel"> · {{ $t("ai.embeddings") }}: {{ p.embedModel }}</template>
|
||||
<template v-if="p.transcribeModel"> · {{ $t("ai.speech") }}: {{ p.transcribeModel }}</template>
|
||||
· {{ p.keySet ? $t("ai.keySet") : $t("ai.noKey") }}
|
||||
</p>
|
||||
<p class="text-ui-xs text-ink-faint">
|
||||
@@ -220,6 +250,10 @@ const total = computed(() =>
|
||||
<span class="text-ui-sm font-semibold">{{ $t("ai.embedModel") }}</span>
|
||||
<input v-model="form.embedModel" class="dw-input" :disabled="form.kind === 'anthropic'" />
|
||||
</label>
|
||||
<label v-if="form.kind === 'openai'" class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("ai.transcribeModel") }}</span>
|
||||
<input v-model="form.transcribeModel" class="dw-input" placeholder="whisper-1" />
|
||||
</label>
|
||||
<label v-if="form.kind === 'anthropic'" class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("ai.effort") }}</span>
|
||||
<select v-model="form.effort" class="dw-input">
|
||||
@@ -237,6 +271,57 @@ const total = computed(() =>
|
||||
<DwButton v-else class="mt-4" size="sm" icon="plus" @click="startNew">{{ $t("ai.add") }}</DwButton>
|
||||
</section>
|
||||
|
||||
<section class="mt-6 max-w-3xl dw-card" data-testid="admin-ai-usage">
|
||||
<h2 class="text-ui-lg">{{ $t("ai.usageTitle") }}</h2>
|
||||
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("ai.limitHint") }}</p>
|
||||
<form class="mt-3 flex flex-wrap items-end gap-2" @submit.prevent="saveLimit">
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("ai.limit") }}</span>
|
||||
<input
|
||||
v-model="limitInput"
|
||||
type="number"
|
||||
min="0"
|
||||
step="1000"
|
||||
class="dw-input w-56"
|
||||
:placeholder="$t('ai.noLimit')"
|
||||
/>
|
||||
</label>
|
||||
<DwButton type="submit" variant="secondary" :disabled="busy">{{ $t("common.save") }}</DwButton>
|
||||
<span v-if="limitSaved" class="text-ui-sm text-ink-muted">{{ $t("common.saved") }}</span>
|
||||
</form>
|
||||
<div class="mt-4 overflow-x-auto">
|
||||
<table class="w-full text-left text-ui-sm">
|
||||
<thead class="text-ink-muted">
|
||||
<tr>
|
||||
<th class="py-1 pr-3 font-medium">{{ $t("ai.workspace") }}</th>
|
||||
<th class="py-1 pr-3 text-right font-medium">{{ $t("ai.requests") }}</th>
|
||||
<th class="py-1 pr-3 text-right font-medium">{{ $t("ai.tokens") }}</th>
|
||||
<th class="py-1 text-right font-medium">{{ $t("ai.serverTokens") }}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody class="divide-y divide-line">
|
||||
<tr v-for="u in usage" :key="u.workspace">
|
||||
<td class="py-1.5 pr-3">{{ u.name || u.workspace }}</td>
|
||||
<td class="py-1.5 pr-3 text-right tabular-nums">{{ num(u.requests) }}</td>
|
||||
<td class="py-1.5 pr-3 text-right tabular-nums">
|
||||
{{ num(u.inputTokens + u.outputTokens) }}
|
||||
<span v-if="u.limit" class="text-ink-muted">/ {{ num(u.limit) }}</span>
|
||||
</td>
|
||||
<td
|
||||
class="py-1.5 text-right tabular-nums"
|
||||
:class="{ 'text-danger': u.instanceLimit && u.instanceTokens >= u.instanceLimit }"
|
||||
>
|
||||
{{ num(u.instanceTokens) }}
|
||||
</td>
|
||||
</tr>
|
||||
<tr v-if="!usage.length">
|
||||
<td colspan="4" class="py-2 text-ink-muted">{{ $t("ai.noUsage") }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="mt-6 max-w-3xl dw-card">
|
||||
<h2 class="text-ui-lg">{{ $t("ai.mcpTitle") }}</h2>
|
||||
<p class="mt-1 text-ui-sm text-ink-muted">{{ $t("ai.mcpHint") }}</p>
|
||||
|
||||
+3
-2
@@ -3,13 +3,16 @@ module docwell/server
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/anthropics/anthropic-sdk-go/v2 v2.9.0
|
||||
github.com/blevesearch/bleve/v2 v2.6.1
|
||||
github.com/coder/websocket v1.8.15
|
||||
github.com/go-pdf/fpdf v0.9.0
|
||||
github.com/ledongthuc/pdf v0.0.0-20261020125853-5e46805f718e
|
||||
github.com/oapi-codegen/runtime v1.8.0
|
||||
github.com/pquerna/otp v1.5.0
|
||||
github.com/tetratelabs/wazero v1.12.0
|
||||
github.com/yuin/goldmark v1.8.7
|
||||
go.etcd.io/bbolt v1.4.0
|
||||
golang.org/x/image v0.47.0
|
||||
golang.org/x/net v0.62.0
|
||||
gopkg.in/yaml.v3 v3.0.1
|
||||
@@ -17,7 +20,6 @@ require (
|
||||
|
||||
require (
|
||||
github.com/RoaringBitmap/roaring/v2 v2.14.5 // indirect
|
||||
github.com/anthropics/anthropic-sdk-go/v2 v2.9.0 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/bits-and-blooms/bitset v1.24.2 // indirect
|
||||
github.com/blevesearch/bleve_index_api v1.4.1 // indirect
|
||||
@@ -66,7 +68,6 @@ require (
|
||||
github.com/tidwall/pretty v1.2.1 // indirect
|
||||
github.com/tidwall/sjson v1.2.5 // indirect
|
||||
github.com/vmware-labs/yaml-jsonpath v0.3.2 // indirect
|
||||
go.etcd.io/bbolt v1.4.0 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 // indirect
|
||||
go.opentelemetry.io/otel v1.33.0 // indirect
|
||||
go.opentelemetry.io/otel/metric v1.33.0 // indirect
|
||||
|
||||
@@ -1,7 +1,41 @@
|
||||
cloud.google.com/go/auth v0.7.2 h1:uiha352VrCDMXg+yoBtaD0tUF4Kv9vrtrWPYXwutnDE=
|
||||
cloud.google.com/go/auth v0.7.2/go.mod h1:VEc4p5NNxycWQTMQEDQF0bd6aTMb6VgYDXEwiJJQAbs=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.3 h1:MlxF+Pd3OmSudg/b1yZ5lJwoXCEaeedAguodky1PcKI=
|
||||
cloud.google.com/go/auth/oauth2adapt v0.2.3/go.mod h1:tMQXOfZzFuNuUxOypHlQEXgdfX5cuhwU+ffUuXRJE8I=
|
||||
cloud.google.com/go/compute/metadata v0.5.0 h1:Zr0eK8JbFv6+Wi4ilXAR8FJ3wyNdpxHKJNPos6LTZOY=
|
||||
cloud.google.com/go/compute/metadata v0.5.0/go.mod h1:aHnloV2TPI38yx4s9+wAZhHykWvVCfu7hQbF+9CWoiY=
|
||||
github.com/RoaringBitmap/roaring/v2 v2.14.5 h1:ckd0o545JqDPeVJDgeFoaM21eBixUnlWfYgjE5VnyWw=
|
||||
github.com/RoaringBitmap/roaring/v2 v2.14.5/go.mod h1:eq4wdNXxtJIS/oikeCzdX1rBzek7ANzbth041hrU8Q4=
|
||||
github.com/anthropics/anthropic-sdk-go/v2 v2.9.0 h1:kn8rCJlgcOTd5/yjofmTuUdfMRP14OL9vDS4tsdJqZg=
|
||||
github.com/anthropics/anthropic-sdk-go/v2 v2.9.0/go.mod h1:LAOInMKgn6reTIrPvKXa5weyqzxsJkxSBuzhnxzukpQ=
|
||||
github.com/aws/aws-sdk-go-v2 v1.38.0 h1:UCRQ5mlqcFk9HJDIqENSLR3wiG1VTWlyUfLDEvY7RxU=
|
||||
github.com/aws/aws-sdk-go-v2 v1.38.0/go.mod h1:9Q0OoGQoboYIAJyslFyF1f5K1Ryddop8gqMhWx/n4Wg=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 h1:tW1/Rkad38LA15X4UQtjXZXNKsCgkshC3EbmcUmghTg=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3/go.mod h1:UbnqO+zjqk3uIt9yCACHJ9IVNhyhOCnYk8yA19SAWrM=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.27.27 h1:HdqgGt1OAP0HkEDDShEl0oSYa9ZZBSOmKpdpsDMdO90=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.27.27/go.mod h1:MVYamCg76dFNINkZFu4n4RjDixhVr51HLj4ErWzrVwg=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.17.27 h1:2raNba6gr2IfA0eqqiP2XiQ0UVOpGPgDSi0I9iAP+UI=
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.17.27/go.mod h1:gniiwbGahQByxan6YjQUMcW4Aov6bLC3m+evgcoN4r4=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 h1:KreluoV8FZDEtI6Co2xuNk/UqI9iwMrOx/87PBNIKqw=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11/go.mod h1:SeSUYBLsMYFoRvHE0Tjvn7kbxaUhl75CJi1sbfhMxkU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 h1:SoNJ4RlFEQEbtDcCEt+QG56MY4fm4W8rYirAmq+/DdU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15/go.mod h1:U9ke74k1n2bf+RIgoX1SXFed1HLs51OgUSs+Ph0KJP8=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 h1:C6WHdGnTDIYETAm5iErQUiVNsclNx9qbJVPIt03B6bI=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15/go.mod h1:ZQLZqhcu+JhSrA9/NXRm8SkDvsycE+JkV3WGY41e+IM=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 h1:hT8rVHwugYE2lEfdFE0QWVo81lF7jMrYJVDWI+f+VxU=
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0/go.mod h1:8tu/lYfQfFe6IGnaOdrpVgEL2IrrDOf6/m9RQum4NkY=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 h1:dT3MqvGhSoaIhRseqw2I0yH81l7wiR2vjs57O51EAm8=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3/go.mod h1:GlAeCkHwugxdHaueRr4nhPuY+WW+gR8UjlcqzPr1SPI=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 h1:HGErhhrxZlQ044RiM+WdoZxp0p+EGM62y3L6pwA4olE=
|
||||
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17/go.mod h1:RkZEx4l0EHYDJpWppMJ3nD9wZJAa8/0lq9aVC+r2UII=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 h1:BXx0ZIxvrJdSgSvKTZ+yRBeSqqgPM89VPlulEcl37tM=
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4/go.mod h1:ooyCOXjvJEsUw7x+ZDHeISPMhtwI3ZCB7ggFMcFfWLU=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 h1:yiwVzJW2ZxZTurVbYWA7QOrAaCYQR72t0wrSBfoesUE=
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4/go.mod h1:0oxfLkpz3rQ/CHlx5hB7H69YUpFiI1tql6Q6Ne+1bCw=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 h1:ZsDKRLXGWHk8WdtyYMoGNO7bTudrvuKpDKgMVRlepGE=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.30.3/go.mod h1:zwySh8fpFyXp9yOr/KVzxOl8SRqgf/IDw5aUt9UKFcQ=
|
||||
github.com/aws/smithy-go v1.22.5 h1:P9ATCXPMb2mPjYBgueqJNCA5S9UfktsW0tTxi+a7eqw=
|
||||
github.com/aws/smithy-go v1.22.5/go.mod h1:t1ufH5HMublsJYulve2RKmHDC15xu1f26kHCp/HgceI=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/bits-and-blooms/bitset v1.24.2 h1:M7/NzVbsytmtfHbumG+K2bremQPMJuqv1JD3vOaFxp0=
|
||||
@@ -60,9 +94,13 @@ github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo=
|
||||
github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
|
||||
github.com/dnaeon/go-vcr v1.2.0 h1:zHCHvJYTMh1N7xnV7zf1m1GPBF9Ad0Jk/whtQ1663qI=
|
||||
github.com/dnaeon/go-vcr v1.2.0/go.mod h1:R4UdLID7HZT3taECzJs4YgbbH6PIGXB6W/sc5OLb6RQ=
|
||||
github.com/dprotaso/go-yit v0.0.0-20191028211022-135eb7262960/go.mod h1:9HQzr9D/0PGwMEbC3d5AB7oi67+h4TsQqItC1GVYG58=
|
||||
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936 h1:PRxIJD8XjimM5aTknUK9w6DHLDox2r2M3DI4i2pnd3w=
|
||||
github.com/dprotaso/go-yit v0.0.0-20220510233725-9ba8df137936/go.mod h1:ttYvX5qlB+mlV1okblJqcSMtR4c52UKxDiX9GRBS8+Q=
|
||||
github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
|
||||
github.com/felixge/httpsnoop v1.0.4/go.mod h1:m8KPJKqk1gH5J9DgRY2ASl2lWCfGKXixSwevea8zH2U=
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
|
||||
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
|
||||
@@ -82,6 +120,8 @@ github.com/go-openapi/testify/v2 v2.4.2/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf4
|
||||
github.com/go-pdf/fpdf v0.9.0 h1:PPvSaUuo1iMi9KkaAn90NuKi+P4gwMedWPHhj8YlJQw=
|
||||
github.com/go-pdf/fpdf v0.9.0/go.mod h1:oO8N111TkmKb9D7VvWGLvLJlaZUQVPM+6V42pp3iV4Y=
|
||||
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da h1:oI5xCqsCo564l8iNU+DwB5epxmsaqB+rhGL0m5jtYqE=
|
||||
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc=
|
||||
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
|
||||
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
|
||||
@@ -91,6 +131,8 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq
|
||||
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
|
||||
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
|
||||
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
|
||||
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
|
||||
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
|
||||
github.com/golang/snappy v1.0.0 h1:Oy607GVXHs7RtbggtPBnr2RmDArIsAefDwvrdWvRhGs=
|
||||
github.com/golang/snappy v1.0.0/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q=
|
||||
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
|
||||
@@ -100,9 +142,15 @@ github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/google/jsonschema-go v0.4.2 h1:tmrUohrwoLZZS/P3x7ex0WAVknEkBZM46iALbcqoRA8=
|
||||
github.com/google/jsonschema-go v0.4.2/go.mod h1:r5quNTdLOYEz95Ru18zA0ydNbBuYoo9tgaYcxEYhJVE=
|
||||
github.com/google/pprof v0.0.0-20210407192527-94a9f03dee38/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
|
||||
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
|
||||
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.2 h1:Vie5ybvEvT75RniqhfFxPRy3Bf7vr3h0cechB90XaQs=
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.2/go.mod h1:VLSiSSBs/ksPL8kq3OBOQ6WRI2QnaFynd1DCjZ62+V0=
|
||||
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/invopop/jsonschema v0.14.0 h1:MHQqLhvpNUZfw+hM3AZDYK7jxO8FZoQeQM77g8iyZjg=
|
||||
@@ -116,6 +164,10 @@ github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/ledongthuc/pdf v0.0.0-20261020125853-5e46805f718e h1:U2Z+V2xqvjJg0azbxHnhOmz2DrpYq0WKpItMPKR6FhY=
|
||||
github.com/ledongthuc/pdf v0.0.0-20261020125853-5e46805f718e/go.mod h1:1fEHWurg7pvf5SG6XNE5Q8UZmOwex51Mkx3SLhrW5B4=
|
||||
github.com/modelcontextprotocol/go-sdk v1.3.1 h1:TfqtNKOIWN4Z1oqmPAiWDC2Jq7K9OdJaooe0teoXASI=
|
||||
github.com/modelcontextprotocol/go-sdk v1.3.1/go.mod h1:DgVX498dMD8UJlseK1S5i1T4tFz2fkBk4xogC3D15nw=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
@@ -157,6 +209,10 @@ github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0t
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2 h1:KRzFb2m7YtdldCEkzs6KqmJw4nqEVZGK7IN2kJkjTuQ=
|
||||
github.com/santhosh-tekuri/jsonschema/v6 v6.0.2/go.mod h1:JXeL+ps8p7/KNMjDQk3TCwPpBy0wYklyWTfbkIzdIFU=
|
||||
github.com/segmentio/asm v1.1.3 h1:WM03sfUOENvvKexOLp+pCqgb/WDjsi7EK8gIsICtzhc=
|
||||
github.com/segmentio/asm v1.1.3/go.mod h1:Ld3L4ZXGNcSLRg4JBsZ3//1+f/TjYl0Mzen/DQy1EJg=
|
||||
github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=
|
||||
github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=
|
||||
github.com/sergi/go-diff v1.1.0 h1:we8PVUC3FE2uYfodKH/nBHMSetSfHDR6scGdBi+erh0=
|
||||
github.com/sergi/go-diff v1.1.0/go.mod h1:STckp+ISIX8hZLjrqAeVduY0gWCT9IjLuqbuNXdaHfM=
|
||||
github.com/speakeasy-api/jsonpath v0.6.3 h1:c+QPwzAOdrWvzycuc9HFsIZcxKIaWcNpC+xhOW9rJxU=
|
||||
@@ -185,17 +241,27 @@ github.com/tidwall/sjson v1.2.5 h1:kLy8mja+1c9jlljvWTlSazM7cKDRfJuR/bOJhcY5NcY=
|
||||
github.com/tidwall/sjson v1.2.5/go.mod h1:Fvgq9kS/6ociJEDnK0Fk1cpYF4FIW6ZF7LAe+6jwd28=
|
||||
github.com/vmware-labs/yaml-jsonpath v0.3.2 h1:/5QKeCBGdsInyDCyVNLbXyilb61MXGi9NP674f9Hobk=
|
||||
github.com/vmware-labs/yaml-jsonpath v0.3.2/go.mod h1:U6whw1z03QyqgWdgXxvVnQ90zN1BWz5V+51Ewf8k+rQ=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2 h1:Ed3Oyj9yrmi9087+NczuL5BwkIc4wvTb5zIM+UJPGz4=
|
||||
github.com/yosida95/uritemplate/v3 v3.0.2/go.mod h1:ILOh0sOhIJR3+L/8afwt/kE++YT040gmv5BQTMR2HP4=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.8.7 h1:XT/tNqCIbabh0ln675w4x3dv04kQBKi8NwYqi9IJaxI=
|
||||
github.com/yuin/goldmark v1.8.7/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
go.etcd.io/bbolt v1.4.0 h1:TU77id3TnN/zKr7CO/uk+fBCwF2jGcMuw2B/FMAzYIk=
|
||||
go.etcd.io/bbolt v1.4.0/go.mod h1:AsD+OCi/qPN1giOX1aiLAha3o1U8rAz65bvN4j0sRuk=
|
||||
go.opencensus.io v0.24.0 h1:y73uSU6J157QMP2kn2r30vwW1A2W2WFwSCGnAVxeaD0=
|
||||
go.opencensus.io v0.24.0/go.mod h1:vNK8G9p7aAivkbmorf4v+7Hgx+Zs0yY+0fOtgBfjQKo=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0 h1:cH53jehLUN6UFLY71z+NDOiNJqDdPRaXzTel0sJySYA=
|
||||
go.opentelemetry.io/auto/sdk v1.1.0/go.mod h1:3wSPjt5PWp2RhlCcmmOial7AvC4DQqZb7a7wCow3W8A=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0 h1:4Pp6oUg3+e/6M4C0A/3kJ2VYa++dsWVTtGgLVj5xtHg=
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.49.0/go.mod h1:Mjt1i1INqiaoZOMGR1RIUJN+i3ChKoFRqzrRQhlkbs0=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0 h1:jq9TW8u3so/bN+JPT166wjOI6/vQPF6Xe7nMNIltagk=
|
||||
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.49.0/go.mod h1:p8pYQP+m5XfbZm9fxtSKAbM6oIllS7s2AfxrChvc7iw=
|
||||
go.opentelemetry.io/otel v1.33.0 h1:/FerN9bax5LoK51X/sI0SVYrjSE0/yUL7DpxW4K3FWw=
|
||||
go.opentelemetry.io/otel v1.33.0/go.mod h1:SUUkR6csvUQl+yjReHu5uM3EtVV7MBm5FHKRlNx4I8I=
|
||||
go.opentelemetry.io/otel/metric v1.33.0 h1:r+JOocAyeRVXD8lZpjdQjzMadVZp2M4WmQ+5WtEnklQ=
|
||||
go.opentelemetry.io/otel/metric v1.33.0/go.mod h1:L9+Fyctbp6HFTddIxClbQkjtubW6O9QS3Ann/M82u6M=
|
||||
go.opentelemetry.io/otel/sdk v1.33.0 h1:iax7M131HuAm9QkZotNHEfstof92xM+N8sr3uHXc2IM=
|
||||
go.opentelemetry.io/otel/sdk v1.33.0/go.mod h1:A1Q5oi7/9XaMlIWzPSxLRWOI8nG3FnzHJNbiENQuihM=
|
||||
go.opentelemetry.io/otel/trace v1.33.0 h1:cCJuF7LRjUFso9LPnEAHJDB2pqzp+hbO8eu1qqW2d/s=
|
||||
go.opentelemetry.io/otel/trace v1.33.0/go.mod h1:uIcdVUZMpTAmz0tI1z04GoVSezK37CbGV4fr1f2nBck=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
@@ -205,6 +271,8 @@ go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfP
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
|
||||
golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||
golang.org/x/image v0.47.0 h1:za/8gVz++PPZqmZJBNSISICN5Rrj5zixP/8K++fgmqo=
|
||||
golang.org/x/image v0.47.0/go.mod h1:IkN5o4A7vq55vXN8FWjjnhg9Rs2GOtffqsSi9mWAKYE=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
@@ -219,6 +287,8 @@ golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT
|
||||
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
|
||||
golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY=
|
||||
golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI=
|
||||
golang.org/x/oauth2 v0.30.0 h1:dnDm7JmhM45NNpd8FDDeLhK6FwqbOf4MLCM9zb1BOHI=
|
||||
golang.org/x/oauth2 v0.30.0/go.mod h1:B++QgG3ZKulg6sRPGD/mqlHQs5rB3Ml9erfeDY7xKlU=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
@@ -248,6 +318,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||
golang.org/x/time v0.14.0 h1:MRx4UaLrDotUKUdCIqzPC48t1Y9hANFKIRpNx+Te8PI=
|
||||
golang.org/x/time v0.14.0/go.mod h1:eL/Oa2bBBK0TkX57Fyni+NgnyQQN4LitPmob2Hjnqw4=
|
||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
@@ -257,6 +329,12 @@ golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8T
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/api v0.189.0 h1:equMo30LypAkdkLMBqfeIqtyAnlyig1JSZArl4XPwdI=
|
||||
google.golang.org/api v0.189.0/go.mod h1:FLWGJKb0hb+pU2j+rJqwbnsF+ym+fQs73rbJ+KAUgy8=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240722135656-d784300faade h1:oCRSWfwGXQsqlVdErcyTt4A93Y8fo0/9D4b1gnI++qo=
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20240722135656-d784300faade/go.mod h1:Ue6ibwXGpU+dqIcODieyLOcgj7z8+IcskoNIgZxtrFY=
|
||||
google.golang.org/grpc v1.64.1 h1:LKtvyfbX3UGVPFcGqJ9ItpVWW6oN/2XqTxfAnwRRXiA=
|
||||
google.golang.org/grpc v1.64.1/go.mod h1:hiQF4LFZelK2WKaP6W0L92zGHtiQdZxk8CrSdvyjeP0=
|
||||
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
|
||||
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
|
||||
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -14,6 +15,8 @@ import (
|
||||
"testing"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
|
||||
"github.com/go-pdf/fpdf"
|
||||
)
|
||||
|
||||
func TestSealerRoundTrip(t *testing.T) {
|
||||
@@ -247,3 +250,68 @@ func TestMCPProtocol(t *testing.T) {
|
||||
t.Error("unknown method answered")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPDFText(t *testing.T) {
|
||||
doc := fpdf.New("P", "mm", "A4", "")
|
||||
doc.AddPage()
|
||||
doc.SetFont("Helvetica", "", 12)
|
||||
doc.Cell(40, 10, "Expense policy page one")
|
||||
doc.AddPage()
|
||||
doc.Cell(40, 10, "Receipts are due within 30 days")
|
||||
var buf bytes.Buffer
|
||||
if err := doc.Output(&buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
text, err := extractText("policy.pdf", buf.Bytes())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(text, "Expense policy page one") || !strings.Contains(text, "Receipts are due") {
|
||||
t.Fatalf("text = %q", text)
|
||||
}
|
||||
if _, err := extractText("broken.pdf", []byte("%PDF-1.4 not really")); err == nil {
|
||||
t.Fatal("a broken PDF was read")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTranscribeDriver(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/audio/transcriptions" {
|
||||
w.WriteHeader(404)
|
||||
return
|
||||
}
|
||||
if err := r.ParseMultipartForm(1 << 20); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
f, h, err := r.FormFile("file")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, _ := io.ReadAll(f)
|
||||
fmt.Fprintf(w, `{"text":"model %s heard %d bytes of %s"}`, r.FormValue("model"), len(data), h.Filename)
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(KindOpenAI, srv.URL+"/v1", "", srv.Client())
|
||||
text, err := p.Transcribe(context.Background(), "whisper-1", "call.m4a", []byte("abcd"))
|
||||
if err != nil || text != "model whisper-1 heard 4 bytes of call.m4a" {
|
||||
t.Fatalf("text = %q, %v", text, err)
|
||||
}
|
||||
o, _ := NewProvider(KindOllama, srv.URL, "", srv.Client())
|
||||
if _, err := o.Transcribe(context.Background(), "m", "a.mp3", nil); err != ErrNoTranscription {
|
||||
t.Fatalf("ollama = %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsMedia(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
mime, name string
|
||||
want bool
|
||||
}{
|
||||
{"audio/mpeg", "a", true}, {"video/mp4", "v", true}, {"", "Meeting.M4A", true},
|
||||
{"application/octet-stream", "rec.webm", true}, {"application/pdf", "x.pdf", false},
|
||||
} {
|
||||
if IsMedia(c.mime, c.name) != c.want {
|
||||
t.Errorf("IsMedia(%q, %q) != %v", c.mime, c.name, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,10 @@ func anthropicMessage(e *anthropic.Error) string {
|
||||
return http.StatusText(e.StatusCode)
|
||||
}
|
||||
|
||||
func (p *anthropicProvider) Transcribe(context.Context, string, string, []byte) (string, error) {
|
||||
return "", ErrNoTranscription
|
||||
}
|
||||
|
||||
func (p *anthropicProvider) Embed(context.Context, string, []string) ([][]float32, Usage, error) {
|
||||
return nil, Usage{}, ErrNoEmbeddings
|
||||
}
|
||||
@@ -340,7 +340,7 @@ func (s *Service) retrieve(ctx context.Context, c access.Caller, wsID, scope, sc
|
||||
p, err := s.provider(prof)
|
||||
if err == nil {
|
||||
vecs, usage, err := p.Embed(ctx, prof.EmbedModel, []string{question})
|
||||
s.record(prof, usage, err)
|
||||
s.record(wsID, prof, usage, err)
|
||||
if err == nil && len(vecs) == 1 {
|
||||
hits, err := s.store.Search(wsID, normalize(vecs[0]), maxSources, func(ch Chunk) bool {
|
||||
if ch.File != "" {
|
||||
@@ -491,7 +491,7 @@ func (s *Service) Ask(ctx context.Context, c access.Caller, id, question string,
|
||||
msgs = append(msgs, Message{Role: "user", Content: sourcesBlock(sources) + "Question: " + question})
|
||||
|
||||
var answer strings.Builder
|
||||
_, chatErr := s.chat(ctx, chain, ChatRequest{System: chatSystem, Messages: msgs, MaxTokens: 8000}, func(d string) {
|
||||
_, chatErr := s.chat(ctx, rec.Workspace, chain, ChatRequest{System: chatSystem, Messages: msgs, MaxTokens: 8000}, func(d string) {
|
||||
answer.WriteString(d)
|
||||
emit(Event{Name: "delta", Data: map[string]string{"text": d}})
|
||||
})
|
||||
@@ -557,7 +557,7 @@ func (s *Service) Answer(ctx context.Context, c access.Caller, wsID, scope, scop
|
||||
return "", nil, err
|
||||
}
|
||||
var answer strings.Builder
|
||||
_, err = s.chat(ctx, chain, ChatRequest{
|
||||
_, err = s.chat(ctx, wsID, chain, ChatRequest{
|
||||
System: chatSystem, MaxTokens: 8000,
|
||||
Messages: []Message{{Role: "user", Content: sourcesBlock(sources) + "Question: " + question}},
|
||||
}, func(d string) { answer.WriteString(d) })
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
package ai
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
@@ -13,6 +14,8 @@ import (
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/convert"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
|
||||
"github.com/ledongthuc/pdf"
|
||||
)
|
||||
|
||||
// ---- Extra files for retrieval ----------------------------------------------------
|
||||
@@ -59,6 +62,8 @@ func extractText(name string, data []byte) (string, error) {
|
||||
return "", apperr.Invalid("The HTML file could not be read.")
|
||||
}
|
||||
return convert.Markdown(doc, convert.Options{}), nil
|
||||
case ".pdf":
|
||||
return pdfText(data)
|
||||
case ".docx":
|
||||
doc, _, err := convert.FromDOCX(data)
|
||||
if err != nil {
|
||||
@@ -66,7 +71,41 @@ func extractText(name string, data []byte) (string, error) {
|
||||
}
|
||||
return convert.Markdown(doc, convert.Options{}), nil
|
||||
}
|
||||
return "", apperr.Invalid("Add text, Markdown, HTML or Word (.docx) files.")
|
||||
return "", apperr.Invalid("Add text, Markdown, HTML, Word (.docx) or PDF files.")
|
||||
}
|
||||
|
||||
// pdfText reads a PDF's text page by page. Scanned PDFs have none (no OCR).
|
||||
// The reader panics on some malformed files, so that becomes an error.
|
||||
func pdfText(data []byte) (text string, err error) {
|
||||
bad := apperr.Invalid("The PDF could not be read.")
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
text, err = "", bad
|
||||
}
|
||||
}()
|
||||
r, err := pdf.NewReader(bytes.NewReader(data), int64(len(data)))
|
||||
if err != nil {
|
||||
return "", bad
|
||||
}
|
||||
var b strings.Builder
|
||||
for i := 1; i <= r.NumPage(); i++ {
|
||||
p := r.Page(i)
|
||||
if p.V.IsNull() {
|
||||
continue
|
||||
}
|
||||
t, err := p.GetPlainText(nil)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if t = strings.TrimSpace(t); t != "" {
|
||||
b.WriteString(t)
|
||||
b.WriteString("\n\n")
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(b.String()) == "" {
|
||||
return "", apperr.Invalid("The PDF has no text to read (a scanned PDF needs text recognition first).")
|
||||
}
|
||||
return b.String(), nil
|
||||
}
|
||||
|
||||
func (s *Service) fileView(ws string, r fileRecord) File {
|
||||
|
||||
@@ -189,6 +189,11 @@ func (s *Service) indexWorkspace(ctx context.Context, ws string, st Settings, sw
|
||||
return err
|
||||
}
|
||||
}
|
||||
// Over a monthly cap: keep the vectors, embed nothing new until next month.
|
||||
if _, err := s.limit(ctx, ws, st, []profileRecord{prof}); err != nil {
|
||||
s.setState(ws, func(x *indexState) { x.LastError = userError(err) })
|
||||
return nil
|
||||
}
|
||||
provider, err := s.provider(prof)
|
||||
if err != nil {
|
||||
s.setState(ws, func(x *indexState) { x.LastError = err.Error() })
|
||||
@@ -206,7 +211,7 @@ func (s *Service) indexWorkspace(ctx context.Context, ws string, st Settings, sw
|
||||
for i := 0; i < len(texts); i += embedBatch {
|
||||
end := min(i+embedBatch, len(texts))
|
||||
vecs, usage, err := provider.Embed(ctx, prof.EmbedModel, texts[i:end])
|
||||
s.record(prof, usage, err)
|
||||
s.record(ws, prof, usage, err)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
// ---- Monthly token limits --------------------------------------------------------
|
||||
//
|
||||
// Every call's tokens count against its workspace in ai_usage, per calendar
|
||||
// month (UTC). Two caps apply: a workspace admin's cap on everything the
|
||||
// workspace uses, and a superadmin's cap on what each workspace may use
|
||||
// through the server's own profiles (the server pays for those). When the
|
||||
// server's cap is reached, the workspace's own profiles still work.
|
||||
|
||||
type usageRecord struct {
|
||||
ID string `json:"id"`
|
||||
Workspace string `json:"workspace"`
|
||||
Month string `json:"month"`
|
||||
Requests float64 `json:"requests"`
|
||||
InputTokens float64 `json:"input_tokens"`
|
||||
OutputTokens float64 `json:"output_tokens"`
|
||||
InstanceTokens float64 `json:"instance_tokens"`
|
||||
}
|
||||
|
||||
func (u usageRecord) tokens() int { return int(u.InputTokens + u.OutputTokens) }
|
||||
|
||||
func thisMonth() string { return time.Now().UTC().Format("2006-01") }
|
||||
|
||||
// usage is a workspace's usage this month (zero when it has none).
|
||||
func (s *Service) usage(ctx context.Context, ws string) (usageRecord, error) {
|
||||
res, err := pocketbase.List[usageRecord](ctx, s.pb, "ai_usage", pocketbase.ListOptions{
|
||||
PerPage: 1, Filter: fmt.Sprintf("workspace = '%s' && month = '%s'", ws, thisMonth()),
|
||||
})
|
||||
if err != nil || len(res.Items) == 0 {
|
||||
return usageRecord{Workspace: ws, Month: thisMonth()}, err
|
||||
}
|
||||
return res.Items[0], nil
|
||||
}
|
||||
|
||||
// addUsage counts a call against its workspace. Callers hold usageMu.
|
||||
func (s *Service) addUsage(ctx context.Context, ws string, instance bool, u Usage) error {
|
||||
cur, err := s.usage(ctx, ws)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tokens := u.InputTokens + u.OutputTokens
|
||||
inc := map[string]any{"requests+": 1, "input_tokens+": u.InputTokens, "output_tokens+": u.OutputTokens}
|
||||
if instance {
|
||||
inc["instance_tokens+"] = tokens
|
||||
}
|
||||
if cur.ID != "" {
|
||||
_, err = pocketbase.Update[usageRecord](ctx, s.pb, "ai_usage", cur.ID, inc)
|
||||
return err
|
||||
}
|
||||
body := map[string]any{"workspace": ws, "month": cur.Month, "requests": 1, "input_tokens": u.InputTokens, "output_tokens": u.OutputTokens}
|
||||
if instance {
|
||||
body["instance_tokens"] = tokens
|
||||
}
|
||||
if _, err = pocketbase.Create[usageRecord](ctx, s.pb, "ai_usage", body); err != nil {
|
||||
// Another server made the month's record first: add to it.
|
||||
if cur, err2 := s.usage(ctx, ws); err2 == nil && cur.ID != "" {
|
||||
_, err = pocketbase.Update[usageRecord](ctx, s.pb, "ai_usage", cur.ID, inc)
|
||||
}
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// InstanceSettings are the superadmin's AI rules for every workspace.
|
||||
type InstanceSettings struct {
|
||||
// WorkspaceTokenLimit caps the tokens one workspace may use through the
|
||||
// server's profiles per month; 0 is no cap.
|
||||
WorkspaceTokenLimit int `json:"workspaceTokenLimit"`
|
||||
}
|
||||
|
||||
type kvRecord struct {
|
||||
ID string `json:"id"`
|
||||
Key string `json:"key"`
|
||||
Value json.RawMessage `json:"value"`
|
||||
}
|
||||
|
||||
const instanceKey = "ai"
|
||||
|
||||
func (s *Service) instanceSettings(ctx context.Context) (InstanceSettings, string, error) {
|
||||
var out InstanceSettings
|
||||
res, err := pocketbase.List[kvRecord](ctx, s.pb, "instance_settings", pocketbase.ListOptions{
|
||||
PerPage: 1, Filter: fmt.Sprintf("key = '%s'", instanceKey),
|
||||
})
|
||||
if err != nil || len(res.Items) == 0 {
|
||||
return out, "", err
|
||||
}
|
||||
_ = json.Unmarshal(res.Items[0].Value, &out)
|
||||
return out, res.Items[0].ID, nil
|
||||
}
|
||||
|
||||
// GetInstanceSettings returns the server's AI rules (superadmin).
|
||||
func (s *Service) GetInstanceSettings(ctx context.Context, c access.Caller) (InstanceSettings, error) {
|
||||
if !c.IsSuperadmin() {
|
||||
return InstanceSettings{}, apperr.Forbidden("superadmin role required")
|
||||
}
|
||||
out, _, err := s.instanceSettings(ctx)
|
||||
return out, err
|
||||
}
|
||||
|
||||
// SaveInstanceSettings replaces the server's AI rules (superadmin).
|
||||
func (s *Service) SaveInstanceSettings(ctx context.Context, c access.Caller, in InstanceSettings) (InstanceSettings, error) {
|
||||
if !c.IsSuperadmin() {
|
||||
return InstanceSettings{}, apperr.Forbidden("superadmin role required")
|
||||
}
|
||||
if in.WorkspaceTokenLimit < 0 {
|
||||
return InstanceSettings{}, apperr.InvalidFields(map[string]string{"workspaceTokenLimit": "Use 0 for no limit, or a positive number."})
|
||||
}
|
||||
_, id, err := s.instanceSettings(ctx)
|
||||
if err != nil {
|
||||
return InstanceSettings{}, err
|
||||
}
|
||||
body := map[string]any{"key": instanceKey, "value": in}
|
||||
if id != "" {
|
||||
_, err = pocketbase.Update[kvRecord](ctx, s.pb, "instance_settings", id, body)
|
||||
} else {
|
||||
_, err = pocketbase.Create[kvRecord](ctx, s.pb, "instance_settings", body)
|
||||
}
|
||||
return in, err
|
||||
}
|
||||
|
||||
// UsageView is a workspace's usage this month, with its caps.
|
||||
type UsageView struct {
|
||||
Workspace string `json:"workspace"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Month string `json:"month"`
|
||||
Requests int `json:"requests"`
|
||||
InputTokens int `json:"inputTokens"`
|
||||
OutputTokens int `json:"outputTokens"`
|
||||
InstanceTokens int `json:"instanceTokens"`
|
||||
// Limit is the workspace's own cap, InstanceLimit the server's cap on
|
||||
// instanceTokens; 0 means none.
|
||||
Limit int `json:"limit"`
|
||||
InstanceLimit int `json:"instanceLimit"`
|
||||
}
|
||||
|
||||
func (u usageRecord) view(limit, instanceLimit int) UsageView {
|
||||
return UsageView{
|
||||
Workspace: u.Workspace, Month: u.Month, Requests: int(u.Requests),
|
||||
InputTokens: int(u.InputTokens), OutputTokens: int(u.OutputTokens), InstanceTokens: int(u.InstanceTokens),
|
||||
Limit: limit, InstanceLimit: instanceLimit,
|
||||
}
|
||||
}
|
||||
|
||||
// Usage reports a workspace's usage this month (workspace admin).
|
||||
func (s *Service) Usage(ctx context.Context, c access.Caller, wsID string) (UsageView, error) {
|
||||
if err := s.canManage(ctx, c, wsID); err != nil {
|
||||
return UsageView{}, err
|
||||
}
|
||||
st, err := s.settings(ctx, wsID)
|
||||
if err != nil {
|
||||
return UsageView{}, err
|
||||
}
|
||||
inst, _, err := s.instanceSettings(ctx)
|
||||
if err != nil {
|
||||
return UsageView{}, err
|
||||
}
|
||||
u, err := s.usage(ctx, wsID)
|
||||
return u.view(st.MonthlyTokenLimit, inst.WorkspaceTokenLimit), err
|
||||
}
|
||||
|
||||
// AllUsage lists every workspace's usage this month, most first (superadmin).
|
||||
func (s *Service) AllUsage(ctx context.Context, c access.Caller) ([]UsageView, error) {
|
||||
if !c.IsSuperadmin() {
|
||||
return nil, apperr.Forbidden("superadmin role required")
|
||||
}
|
||||
inst, _, err := s.instanceSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := pocketbase.List[struct {
|
||||
usageRecord
|
||||
Expand struct {
|
||||
Workspace *struct {
|
||||
Name string `json:"name"`
|
||||
AISettings json.RawMessage `json:"ai_settings"`
|
||||
} `json:"workspace"`
|
||||
} `json:"expand"`
|
||||
}](ctx, s.pb, "ai_usage", pocketbase.ListOptions{
|
||||
PerPage: 500, Filter: fmt.Sprintf("month = '%s'", thisMonth()), Sort: "-output_tokens", Expand: "workspace",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out := make([]UsageView, 0, len(res.Items))
|
||||
for _, r := range res.Items {
|
||||
st := defaultSettings()
|
||||
name := ""
|
||||
if w := r.Expand.Workspace; w != nil {
|
||||
name = w.Name
|
||||
if len(w.AISettings) > 0 {
|
||||
_ = json.Unmarshal(w.AISettings, &st)
|
||||
}
|
||||
}
|
||||
v := r.view(st.MonthlyTokenLimit, inst.WorkspaceTokenLimit)
|
||||
v.Name = name
|
||||
out = append(out, v)
|
||||
}
|
||||
slices.SortStableFunc(out, func(a, b UsageView) int {
|
||||
return (b.InputTokens + b.OutputTokens) - (a.InputTokens + a.OutputTokens)
|
||||
})
|
||||
return out, nil
|
||||
}
|
||||
|
||||
var (
|
||||
errWorkspaceLimit = apperr.Forbidden("This workspace has used its AI tokens for this month; a workspace admin can raise the limit.")
|
||||
errInstanceLimit = apperr.Forbidden("This workspace has used its share of the server's AI for this month; add a provider of its own, or ask the server's admin.")
|
||||
)
|
||||
|
||||
// limit applies the monthly caps to a workspace's chain: it fails when the
|
||||
// workspace's own cap is reached, and drops the server's profiles when the
|
||||
// server's cap is.
|
||||
func (s *Service) limit(ctx context.Context, ws string, st Settings, chain []profileRecord) ([]profileRecord, error) {
|
||||
u, err := s.usage(ctx, ws)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if st.MonthlyTokenLimit > 0 && u.tokens() >= st.MonthlyTokenLimit {
|
||||
return nil, errWorkspaceLimit
|
||||
}
|
||||
inst, _, err := s.instanceSettings(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if inst.WorkspaceTokenLimit > 0 && int(u.InstanceTokens) >= inst.WorkspaceTokenLimit {
|
||||
hadInstance := slices.ContainsFunc(chain, func(r profileRecord) bool { return r.Workspace == "" })
|
||||
chain = slices.DeleteFunc(slices.Clone(chain), func(r profileRecord) bool { return r.Workspace == "" })
|
||||
if hadInstance && len(chain) == 0 {
|
||||
return nil, errInstanceLimit
|
||||
}
|
||||
}
|
||||
return chain, nil
|
||||
}
|
||||
@@ -64,23 +64,25 @@ func (s *sealer) open(sealed string) (string, error) {
|
||||
// ---- Profiles --------------------------------------------------------------------
|
||||
|
||||
type profileRecord struct {
|
||||
ID string `json:"id"`
|
||||
Workspace string `json:"workspace"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
BaseURL string `json:"base_url"`
|
||||
APIKey string `json:"api_key"`
|
||||
ChatModel string `json:"chat_model"`
|
||||
EmbedModel string `json:"embed_model"`
|
||||
Effort string `json:"effort"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Position float64 `json:"position"`
|
||||
Requests float64 `json:"requests"`
|
||||
InputTokens float64 `json:"input_tokens"`
|
||||
OutputTokens float64 `json:"output_tokens"`
|
||||
LastUsed string `json:"last_used"`
|
||||
LastError string `json:"last_error"`
|
||||
Created string `json:"created"`
|
||||
ID string `json:"id"`
|
||||
Workspace string `json:"workspace"`
|
||||
Name string `json:"name"`
|
||||
Kind string `json:"kind"`
|
||||
BaseURL string `json:"base_url"`
|
||||
APIKey string `json:"api_key"`
|
||||
ChatModel string `json:"chat_model"`
|
||||
EmbedModel string `json:"embed_model"`
|
||||
// TranscribeModel is the speech-to-text model (OpenAI-compatible only).
|
||||
TranscribeModel string `json:"transcribe_model"`
|
||||
Effort string `json:"effort"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Position float64 `json:"position"`
|
||||
Requests float64 `json:"requests"`
|
||||
InputTokens float64 `json:"input_tokens"`
|
||||
OutputTokens float64 `json:"output_tokens"`
|
||||
LastUsed string `json:"last_used"`
|
||||
LastError string `json:"last_error"`
|
||||
Created string `json:"created"`
|
||||
}
|
||||
|
||||
// Profile is a provider configuration as admins see it, without the key.
|
||||
@@ -94,10 +96,12 @@ type Profile struct {
|
||||
KeySet bool `json:"keySet"`
|
||||
ChatModel string `json:"chatModel"`
|
||||
EmbedModel string `json:"embedModel"`
|
||||
Effort string `json:"effort"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Position int `json:"position"`
|
||||
Usage struct {
|
||||
// TranscribeModel turns audio attachments into text ("" when unused).
|
||||
TranscribeModel string `json:"transcribeModel"`
|
||||
Effort string `json:"effort"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Position int `json:"position"`
|
||||
Usage struct {
|
||||
Requests int `json:"requests"`
|
||||
InputTokens int `json:"inputTokens"`
|
||||
OutputTokens int `json:"outputTokens"`
|
||||
@@ -110,7 +114,7 @@ type Profile struct {
|
||||
func (r profileRecord) view() Profile {
|
||||
p := Profile{
|
||||
ID: r.ID, Workspace: r.Workspace, Name: r.Name, Kind: r.Kind, BaseURL: r.BaseURL, KeySet: r.APIKey != "",
|
||||
ChatModel: r.ChatModel, EmbedModel: r.EmbedModel, Effort: r.Effort, Enabled: r.Enabled,
|
||||
ChatModel: r.ChatModel, EmbedModel: r.EmbedModel, TranscribeModel: r.TranscribeModel, Effort: r.Effort, Enabled: r.Enabled,
|
||||
Position: int(r.Position), LastUsed: r.LastUsed, LastError: r.LastError, Created: r.Created,
|
||||
}
|
||||
p.Usage.Requests, p.Usage.InputTokens, p.Usage.OutputTokens = int(r.Requests), int(r.InputTokens), int(r.OutputTokens)
|
||||
@@ -126,8 +130,10 @@ type ProfileInput struct {
|
||||
APIKey *string `json:"apiKey"`
|
||||
ChatModel *string `json:"chatModel"`
|
||||
EmbedModel *string `json:"embedModel"`
|
||||
Effort *string `json:"effort"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
// TranscribeModel is the speech-to-text model.
|
||||
TranscribeModel *string `json:"transcribeModel"`
|
||||
Effort *string `json:"effort"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
var efforts = []string{"", "low", "medium", "high", "xhigh", "max"}
|
||||
@@ -150,6 +156,7 @@ func (in ProfileInput) body(s *sealer, create bool) (map[string]any, error) {
|
||||
str(in.Name, "name", "name", 80)
|
||||
str(in.ChatModel, "chat_model", "chatModel", 200)
|
||||
str(in.EmbedModel, "embed_model", "embedModel", 200)
|
||||
str(in.TranscribeModel, "transcribe_model", "transcribeModel", 200)
|
||||
if in.Name != nil && strings.TrimSpace(*in.Name) == "" {
|
||||
fields["name"] = "Give the profile a name."
|
||||
}
|
||||
@@ -385,7 +392,7 @@ func (s *Service) TestProfile(ctx context.Context, c access.Caller, id string) (
|
||||
Model: rec.ChatModel, Effort: rec.Effort, MaxTokens: 64,
|
||||
Messages: []Message{{Role: "user", Content: "Reply with the single word: ready"}},
|
||||
}, func(d string) { out.WriteString(d) })
|
||||
s.record(rec, usage, err)
|
||||
s.record(rec.Workspace, rec, usage, err)
|
||||
if err != nil {
|
||||
res.OK, res.Error = false, err.Error()
|
||||
} else {
|
||||
@@ -394,7 +401,7 @@ func (s *Service) TestProfile(ctx context.Context, c access.Caller, id string) (
|
||||
}
|
||||
if rec.EmbedModel != "" && res.OK {
|
||||
vecs, usage, err := p.Embed(ctx, rec.EmbedModel, []string{"Docwell"})
|
||||
s.record(rec, usage, err)
|
||||
s.record(rec.Workspace, rec, usage, err)
|
||||
if err != nil {
|
||||
res.OK, res.Error = false, err.Error()
|
||||
} else {
|
||||
@@ -421,7 +428,9 @@ func (s *Service) provider(rec profileRecord) (Provider, error) {
|
||||
}
|
||||
|
||||
// record adds a call's usage to a profile's counters, and its error.
|
||||
func (s *Service) record(rec profileRecord, u Usage, callErr error) {
|
||||
// ws is the workspace the call was for ("" for none), whose monthly usage
|
||||
// grows by it too.
|
||||
func (s *Service) record(ws string, rec profileRecord, u Usage, callErr error) {
|
||||
s.usageMu.Lock()
|
||||
defer s.usageMu.Unlock()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
@@ -440,6 +449,11 @@ func (s *Service) record(rec profileRecord, u Usage, callErr error) {
|
||||
if _, err := pocketbase.Update[profileRecord](ctx, s.pb, "ai_profiles", rec.ID, body); err != nil {
|
||||
s.log.Warn("ai: recording usage", "profile", rec.ID, "err", err)
|
||||
}
|
||||
if ws != "" {
|
||||
if err := s.addUsage(ctx, ws, rec.Workspace == "", u); err != nil {
|
||||
s.log.Warn("ai: recording workspace usage", "workspace", ws, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- Workspace settings -----------------------------------------------------------
|
||||
@@ -450,6 +464,8 @@ type Settings struct {
|
||||
UseInstanceProfiles bool `json:"useInstanceProfiles"`
|
||||
Index bool `json:"index"`
|
||||
Ignored []string `json:"ignored"`
|
||||
// MonthlyTokenLimit caps the tokens the workspace uses per month; 0 is no cap.
|
||||
MonthlyTokenLimit int `json:"monthlyTokenLimit"`
|
||||
}
|
||||
|
||||
func defaultSettings() Settings {
|
||||
@@ -489,6 +505,9 @@ func (s *Service) SaveSettings(ctx context.Context, c access.Caller, wsID string
|
||||
if err := s.canManage(ctx, c, wsID); err != nil {
|
||||
return Settings{}, err
|
||||
}
|
||||
if in.MonthlyTokenLimit < 0 {
|
||||
return Settings{}, apperr.InvalidFields(map[string]string{"monthlyTokenLimit": "Use 0 for no limit, or a positive number."})
|
||||
}
|
||||
ignored := []string{}
|
||||
for _, id := range in.Ignored {
|
||||
if validID(id) && !slices.Contains(ignored, id) && len(ignored) < 2000 {
|
||||
@@ -538,7 +557,7 @@ var errNoProfile = apperr.Invalid("AI is not set up for this workspace: an admin
|
||||
|
||||
// chat runs a chat on the first profile of the chain that answers. It moves
|
||||
// to the next one only while nothing was streamed yet.
|
||||
func (s *Service) chat(ctx context.Context, chain []profileRecord, req ChatRequest, onDelta func(string)) (profileRecord, error) {
|
||||
func (s *Service) chat(ctx context.Context, ws string, chain []profileRecord, req ChatRequest, onDelta func(string)) (profileRecord, error) {
|
||||
var lastErr error = errNoProfile
|
||||
for _, rec := range chain {
|
||||
if rec.ChatModel == "" {
|
||||
@@ -556,7 +575,7 @@ func (s *Service) chat(ctx context.Context, chain []profileRecord, req ChatReque
|
||||
}
|
||||
streamed := false
|
||||
usage, err := p.Chat(ctx, r, func(d string) { streamed = true; onDelta(d) })
|
||||
s.record(rec, usage, err)
|
||||
s.record(ws, rec, usage, err)
|
||||
if err == nil || streamed || errors.Is(err, ErrRefused) || ctx.Err() != nil {
|
||||
return rec, err
|
||||
}
|
||||
|
||||
@@ -16,6 +16,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime/multipart"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
@@ -55,11 +56,16 @@ type Provider interface {
|
||||
Chat(ctx context.Context, req ChatRequest, onDelta func(string)) (Usage, error)
|
||||
// Embed returns one vector per input text.
|
||||
Embed(ctx context.Context, model string, texts []string) ([][]float32, Usage, error)
|
||||
// Transcribe turns speech in an audio or video file into text.
|
||||
Transcribe(ctx context.Context, model, filename string, data []byte) (string, error)
|
||||
}
|
||||
|
||||
// ErrNoEmbeddings is returned by providers that cannot embed text.
|
||||
var ErrNoEmbeddings = errors.New("this provider has no embeddings API")
|
||||
|
||||
// ErrNoTranscription is returned by providers that cannot transcribe audio.
|
||||
var ErrNoTranscription = errors.New("this provider has no speech-to-text API")
|
||||
|
||||
// ErrRefused is returned when the model declined to answer.
|
||||
var ErrRefused = errors.New("the model declined to answer this request")
|
||||
|
||||
@@ -268,6 +274,48 @@ func (p *openAI) Embed(ctx context.Context, model string, texts []string) ([][]f
|
||||
return out, Usage{InputTokens: body.Usage.Prompt}, nil
|
||||
}
|
||||
|
||||
// Transcribe posts the file to {base}/audio/transcriptions (Whisper and
|
||||
// compatible servers: Groq, LocalAI, faster-whisper-server, vLLM …).
|
||||
func (p *openAI) Transcribe(ctx context.Context, model, filename string, data []byte) (string, error) {
|
||||
var body bytes.Buffer
|
||||
w := multipart.NewWriter(&body)
|
||||
_ = w.WriteField("model", model)
|
||||
_ = w.WriteField("response_format", "json")
|
||||
part, err := w.CreateFormFile("file", filename)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := part.Write(data); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := w.Close(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, p.base+"/audio/transcriptions", &body)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
req.Header.Set("Content-Type", w.FormDataContentType())
|
||||
for k, v := range p.headers() {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
res, err := p.http.Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode >= 400 {
|
||||
return "", readProviderError(res)
|
||||
}
|
||||
var out struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
|
||||
return "", fmt.Errorf("transcription: %w", err)
|
||||
}
|
||||
return out.Text, nil
|
||||
}
|
||||
|
||||
// readSSE calls fn with the data of each server-sent event until the
|
||||
// stream ends or fn returns an error (io.EOF ends it cleanly).
|
||||
func readSSE(r io.Reader, fn func(data string) error) error {
|
||||
@@ -371,6 +419,10 @@ func (p *ollama) Chat(ctx context.Context, req ChatRequest, onDelta func(string)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ollama) Transcribe(context.Context, string, string, []byte) (string, error) {
|
||||
return "", ErrNoTranscription
|
||||
}
|
||||
|
||||
func (p *ollama) Embed(ctx context.Context, model string, texts []string) ([][]float32, Usage, error) {
|
||||
res, err := postJSON(ctx, p.http, p.base+"/api/embed", p.headers(), map[string]any{"model": model, "input": texts})
|
||||
if err != nil {
|
||||
|
||||
@@ -105,6 +105,8 @@ type Availability struct {
|
||||
Chat bool `json:"chat"`
|
||||
// Embeddings is true when the workspace is indexed for retrieval.
|
||||
Embeddings bool `json:"embeddings"`
|
||||
// Transcribe is true when a profile can turn audio into text.
|
||||
Transcribe bool `json:"transcribe"`
|
||||
CanManage bool `json:"canManage"`
|
||||
}
|
||||
|
||||
@@ -130,6 +132,9 @@ func (s *Service) Available(ctx context.Context, c access.Caller, wsID string) (
|
||||
if r.ChatModel != "" {
|
||||
out.Chat = true
|
||||
}
|
||||
if r.TranscribeModel != "" {
|
||||
out.Transcribe = true
|
||||
}
|
||||
}
|
||||
_, hasEmbed := embedProfile(chain)
|
||||
out.Embeddings = st.Index && hasEmbed
|
||||
@@ -153,5 +158,6 @@ func (s *Service) ready(ctx context.Context, c access.Caller, wsID string) (Sett
|
||||
if err != nil {
|
||||
return st, nil, err
|
||||
}
|
||||
return st, chain, nil
|
||||
chain, err = s.limit(ctx, wsID, st, chain)
|
||||
return st, chain, err
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package ai
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
)
|
||||
|
||||
// ---- Audio attachments → transcript and summary (E2) -------------------------------
|
||||
|
||||
// MaxTranscribeBytes is the largest file sent for transcription (the limit
|
||||
// of OpenAI's API, which most compatible servers share).
|
||||
const MaxTranscribeBytes = 25 << 20
|
||||
|
||||
// Transcript is what a transcription produced. Summary is "" when it was not
|
||||
// asked for or failed (SummaryError says why).
|
||||
type Transcript struct {
|
||||
Name string `json:"name"`
|
||||
Text string `json:"text"`
|
||||
Summary string `json:"summary"`
|
||||
SummaryError string `json:"summaryError,omitempty"`
|
||||
}
|
||||
|
||||
var mediaExt = []string{".mp3", ".mp4", ".mpeg", ".mpga", ".m4a", ".wav", ".webm", ".ogg", ".oga", ".flac", ".aac", ".opus", ".mov"}
|
||||
|
||||
// IsMedia reports whether a file looks like audio or video.
|
||||
func IsMedia(mime, name string) bool {
|
||||
if strings.HasPrefix(mime, "audio/") || strings.HasPrefix(mime, "video/") {
|
||||
return true
|
||||
}
|
||||
ext := strings.ToLower(filepath.Ext(name))
|
||||
for _, e := range mediaExt {
|
||||
if e == ext {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const transcriptSystem = `You summarise recordings for a team wiki. You get the transcript of an audio or video file. Reply in Markdown, in the language of the transcript, with:
|
||||
|
||||
- a short summary paragraph,
|
||||
- "Key points" as a bulleted list,
|
||||
- "Action items" as a task list ("- [ ] …", with who and when where the transcript says so), only if there are any.
|
||||
|
||||
No preamble. Do not invent anything that is not in the transcript.`
|
||||
|
||||
// Transcribe turns an audio or video attachment the caller can read into
|
||||
// text, and (summarize) a summary with key points and action items.
|
||||
func (s *Service) Transcribe(ctx context.Context, c access.Caller, fileID string, summarize bool) (Transcript, error) {
|
||||
dl, err := s.dir.OpenAttachment(ctx, c, fileID, nil)
|
||||
if err != nil {
|
||||
return Transcript{}, err
|
||||
}
|
||||
defer dl.Body.Close()
|
||||
if !IsMedia(dl.Mime, dl.Name) {
|
||||
return Transcript{}, apperr.Invalid("Only audio and video files can be transcribed.")
|
||||
}
|
||||
if dl.Size > MaxTranscribeBytes {
|
||||
return Transcript{}, apperr.Invalid("Files up to 25 MB can be transcribed; split or compress longer recordings.")
|
||||
}
|
||||
page, err := s.dir.ReadPage(ctx, c, dl.Page)
|
||||
if err != nil {
|
||||
return Transcript{}, err
|
||||
}
|
||||
_, chain, err := s.ready(ctx, c, page.Workspace)
|
||||
if err != nil {
|
||||
return Transcript{}, err
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(dl.Body, MaxTranscribeBytes+1))
|
||||
if err != nil {
|
||||
return Transcript{}, err
|
||||
}
|
||||
if len(data) > MaxTranscribeBytes {
|
||||
return Transcript{}, apperr.Invalid("Files up to 25 MB can be transcribed; split or compress longer recordings.")
|
||||
}
|
||||
|
||||
out := Transcript{Name: dl.Name}
|
||||
var lastErr error = apperr.Invalid("No AI provider here can transcribe audio: a workspace admin can add a speech-to-text model to an OpenAI-compatible provider.")
|
||||
done := false
|
||||
for _, rec := range chain {
|
||||
if rec.TranscribeModel == "" {
|
||||
continue
|
||||
}
|
||||
p, err := s.provider(rec)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
text, err := p.Transcribe(ctx, rec.TranscribeModel, dl.Name, data)
|
||||
// Speech-to-text APIs report no tokens; count the text's rough size.
|
||||
s.record(page.Workspace, rec, Usage{OutputTokens: utf8.RuneCountInString(text) / 4}, err)
|
||||
if err == nil {
|
||||
out.Text, done = strings.TrimSpace(text), true
|
||||
break
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return Transcript{}, ctx.Err()
|
||||
}
|
||||
s.log.Warn("ai: transcription failed, trying the next profile", "profile", rec.ID, "err", err)
|
||||
lastErr = err
|
||||
}
|
||||
if !done {
|
||||
if _, ok := apperr.As(lastErr); ok {
|
||||
return Transcript{}, lastErr
|
||||
}
|
||||
return Transcript{}, apperr.Invalid(userError(lastErr))
|
||||
}
|
||||
if out.Text == "" {
|
||||
return Transcript{}, apperr.Invalid("No speech was found in the recording.")
|
||||
}
|
||||
if !summarize {
|
||||
return out, nil
|
||||
}
|
||||
var summary strings.Builder
|
||||
_, err = s.chat(ctx, page.Workspace, chain, ChatRequest{
|
||||
System: transcriptSystem, MaxTokens: 4000,
|
||||
Messages: []Message{{Role: "user", Content: "Transcript of " + dl.Name + ":\n\n" + truncate(out.Text, 120000)}},
|
||||
}, func(d string) { summary.WriteString(d) })
|
||||
if err != nil {
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return Transcript{}, err
|
||||
}
|
||||
out.SummaryError = userError(err)
|
||||
} else {
|
||||
out.Summary = strings.TrimSpace(summary.String())
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -80,7 +80,7 @@ func (s *Service) Write(ctx context.Context, c access.Caller, wsID string, in Wr
|
||||
} else {
|
||||
prompt.WriteString("Text:\n<text>\n" + text + "\n</text>")
|
||||
}
|
||||
_, err = s.chat(ctx, chain, ChatRequest{
|
||||
_, err = s.chat(ctx, wsID, chain, ChatRequest{
|
||||
System: writeSystem, MaxTokens: 8000,
|
||||
Messages: []Message{{Role: "user", Content: prompt.String()}},
|
||||
}, onDelta)
|
||||
|
||||
@@ -902,6 +902,9 @@ type AiAvailability struct {
|
||||
|
||||
// Embeddings The workspace is indexed for retrieval
|
||||
Embeddings bool `json:"embeddings"`
|
||||
|
||||
// Transcribe A profile can turn audio attachments into text
|
||||
Transcribe bool `json:"transcribe"`
|
||||
}
|
||||
|
||||
// AiCitation defines model for AiCitation.
|
||||
@@ -953,6 +956,12 @@ type AiIndexStatus struct {
|
||||
Running bool `json:"running"`
|
||||
}
|
||||
|
||||
// AiInstanceSettings defines model for AiInstanceSettings.
|
||||
type AiInstanceSettings struct {
|
||||
// WorkspaceTokenLimit Tokens one workspace may use through the server's profiles per month; 0 is no cap
|
||||
WorkspaceTokenLimit int `json:"workspaceTokenLimit"`
|
||||
}
|
||||
|
||||
// AiMessage defines model for AiMessage.
|
||||
type AiMessage struct {
|
||||
Citations *[]AiCitation `json:"citations,omitempty"`
|
||||
@@ -994,7 +1003,10 @@ type AiProfile struct {
|
||||
LastUsed string `json:"lastUsed"`
|
||||
Name string `json:"name"`
|
||||
Position int `json:"position"`
|
||||
Usage struct {
|
||||
|
||||
// TranscribeModel Speech-to-text model (OpenAI-compatible); empty when unused
|
||||
TranscribeModel string `json:"transcribeModel"`
|
||||
Usage struct {
|
||||
InputTokens int `json:"inputTokens"`
|
||||
OutputTokens int `json:"outputTokens"`
|
||||
Requests int `json:"requests"`
|
||||
@@ -1015,8 +1027,9 @@ type AiProfileInput struct {
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
|
||||
// Kind openai is any OpenAI-compatible API
|
||||
Kind *AiProviderKind `json:"kind,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
Kind *AiProviderKind `json:"kind,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
TranscribeModel *string `json:"transcribeModel,omitempty"`
|
||||
}
|
||||
|
||||
// AiProfileInputEffort defines model for AiProfileInput.Effort.
|
||||
@@ -1071,6 +1084,9 @@ type AiSettings struct {
|
||||
// Index Embed pages for retrieval (sends every page to the embedding provider)
|
||||
Index bool `json:"index"`
|
||||
|
||||
// MonthlyTokenLimit Tokens the workspace may use per month; 0 is no cap
|
||||
MonthlyTokenLimit int `json:"monthlyTokenLimit"`
|
||||
|
||||
// UseInstanceProfiles After its own profiles
|
||||
UseInstanceProfiles bool `json:"useInstanceProfiles"`
|
||||
}
|
||||
@@ -1086,6 +1102,39 @@ type AiTestResult struct {
|
||||
Ok bool `json:"ok"`
|
||||
}
|
||||
|
||||
// AiTranscript defines model for AiTranscript.
|
||||
type AiTranscript struct {
|
||||
Name string `json:"name"`
|
||||
|
||||
// Summary Markdown; empty when not asked for or when it failed
|
||||
Summary string `json:"summary"`
|
||||
SummaryError *string `json:"summaryError,omitempty"`
|
||||
Text string `json:"text"`
|
||||
}
|
||||
|
||||
// AiUsage defines model for AiUsage.
|
||||
type AiUsage struct {
|
||||
InputTokens int `json:"inputTokens"`
|
||||
|
||||
// InstanceLimit The server's cap on instanceTokens; 0 is none
|
||||
InstanceLimit int `json:"instanceLimit"`
|
||||
|
||||
// InstanceTokens Tokens used through the server's own profiles
|
||||
InstanceTokens int `json:"instanceTokens"`
|
||||
|
||||
// Limit The workspace's monthly token cap; 0 is none
|
||||
Limit int `json:"limit"`
|
||||
|
||||
// Month Calendar month in UTC, e.g. 2026-11
|
||||
Month string `json:"month"`
|
||||
|
||||
// Name The workspace's name (admin listing)
|
||||
Name *string `json:"name,omitempty"`
|
||||
OutputTokens int `json:"outputTokens"`
|
||||
Requests int `json:"requests"`
|
||||
Workspace string `json:"workspace"`
|
||||
}
|
||||
|
||||
// AiWriteAction defines model for AiWriteAction.
|
||||
type AiWriteAction string
|
||||
|
||||
@@ -2377,6 +2426,11 @@ type DownloadFileParams struct {
|
||||
Token *string `form:"token,omitempty" json:"token,omitempty"`
|
||||
}
|
||||
|
||||
// TranscribeFileJSONBody defines parameters for TranscribeFile.
|
||||
type TranscribeFileJSONBody struct {
|
||||
Summarize *bool `json:"summarize,omitempty"`
|
||||
}
|
||||
|
||||
// ListInvitesParams defines parameters for ListInvites.
|
||||
type ListInvitesParams struct {
|
||||
Workspace *string `form:"workspace,omitempty" json:"workspace,omitempty"`
|
||||
@@ -2711,6 +2765,9 @@ type CreateInstanceAiProfileJSONRequestBody = AiProfileInput
|
||||
// OrderInstanceAiProfilesJSONRequestBody defines body for OrderInstanceAiProfiles for application/json ContentType.
|
||||
type OrderInstanceAiProfilesJSONRequestBody = IdList
|
||||
|
||||
// SaveInstanceAiSettingsJSONRequestBody defines body for SaveInstanceAiSettings for application/json ContentType.
|
||||
type SaveInstanceAiSettingsJSONRequestBody = AiInstanceSettings
|
||||
|
||||
// UpdateInstanceSettingsJSONRequestBody defines body for UpdateInstanceSettings for application/json ContentType.
|
||||
type UpdateInstanceSettingsJSONRequestBody = InstanceSettingsUpdate
|
||||
|
||||
@@ -2777,6 +2834,9 @@ type ReactToCommentJSONRequestBody ReactToCommentJSONBody
|
||||
// ResolveCommentJSONRequestBody defines body for ResolveComment for application/json ContentType.
|
||||
type ResolveCommentJSONRequestBody ResolveCommentJSONBody
|
||||
|
||||
// TranscribeFileJSONRequestBody defines body for TranscribeFile for application/json ContentType.
|
||||
type TranscribeFileJSONRequestBody TranscribeFileJSONBody
|
||||
|
||||
// UpdateGroupJSONRequestBody defines body for UpdateGroup for application/json ContentType.
|
||||
type UpdateGroupJSONRequestBody = GroupRequest
|
||||
|
||||
|
||||
@@ -46,6 +46,12 @@ type AIService interface {
|
||||
Write(ctx context.Context, c access.Caller, wsID string, in ai.WriteInput, onDelta func(string)) error
|
||||
|
||||
MCP(ctx context.Context, c access.Caller, canWrite bool, body []byte, onWrite func(tool, page string)) ([]byte, error)
|
||||
|
||||
Usage(ctx context.Context, c access.Caller, wsID string) (ai.UsageView, error)
|
||||
AllUsage(ctx context.Context, c access.Caller) ([]ai.UsageView, error)
|
||||
GetInstanceSettings(ctx context.Context, c access.Caller) (ai.InstanceSettings, error)
|
||||
SaveInstanceSettings(ctx context.Context, c access.Caller, in ai.InstanceSettings) (ai.InstanceSettings, error)
|
||||
Transcribe(ctx context.Context, c access.Caller, fileID string, summarize bool) (ai.Transcript, error)
|
||||
}
|
||||
|
||||
var errNoAI = apperr.NotFound("AI is not available on this server")
|
||||
@@ -166,6 +172,40 @@ func (a *api) aiRoutes(mux *routeMux) {
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
|
||||
// Monthly usage and its caps.
|
||||
mux.HandleFunc("GET "+ws("/usage"), a.withAI(func(w http.ResponseWriter, r *http.Request) {
|
||||
v, err := a.ai.Usage(r.Context(), caller(r), r.PathValue("id"))
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/admin/ai/usage", a.withAI(func(w http.ResponseWriter, r *http.Request) {
|
||||
v, err := a.ai.AllUsage(r.Context(), caller(r))
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
mux.HandleFunc("GET /api/v1/admin/ai/settings", a.withAI(func(w http.ResponseWriter, r *http.Request) {
|
||||
v, err := a.ai.GetInstanceSettings(r.Context(), caller(r))
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
mux.HandleFunc("PUT /api/v1/admin/ai/settings", a.withAI(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in ai.InstanceSettings
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
v, err := a.ai.SaveInstanceSettings(r.Context(), caller(r), in)
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
|
||||
// Audio and video attachments → transcript and summary.
|
||||
mux.HandleFunc("POST /api/v1/files/{id}/transcribe", a.withAI(func(w http.ResponseWriter, r *http.Request) {
|
||||
var in struct {
|
||||
Summarize bool `json:"summarize"`
|
||||
}
|
||||
if !a.decode(w, r, &in) {
|
||||
return
|
||||
}
|
||||
v, err := a.ai.Transcribe(r.Context(), caller(r), r.PathValue("id"), in.Summarize)
|
||||
a.respond(w, v, err)
|
||||
}))
|
||||
|
||||
// Embeddings index and extra files.
|
||||
mux.HandleFunc("GET "+ws("/index"), a.withAI(func(w http.ResponseWriter, r *http.Request) {
|
||||
v, err := a.ai.IndexStatus(r.Context(), caller(r), r.PathValue("id"))
|
||||
|
||||
@@ -44,6 +44,7 @@ var unaudited = map[string]bool{
|
||||
"POST /api/v1/workspaces/{id}/ai/write": true,
|
||||
"POST /api/v1/workspaces/{id}/ai/sessions": true,
|
||||
"POST /api/v1/ai/sessions/{id}/fork": true,
|
||||
"POST /api/v1/files/{id}/transcribe": true,
|
||||
"PATCH /api/v1/ai/sessions/{id}": true,
|
||||
"DELETE /api/v1/ai/sessions/{id}": true,
|
||||
}
|
||||
|
||||
@@ -4768,6 +4768,21 @@
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text2470468930",
|
||||
"max": 200,
|
||||
"min": 0,
|
||||
"name": "transcribe_model",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
}
|
||||
],
|
||||
"id": "pbc_1680285732",
|
||||
@@ -5038,5 +5053,137 @@
|
||||
"type": "base",
|
||||
"updateRule": null,
|
||||
"viewRule": null
|
||||
},
|
||||
{
|
||||
"createRule": null,
|
||||
"deleteRule": null,
|
||||
"fields": [
|
||||
{
|
||||
"autogeneratePattern": "[a-z0-9]{15}",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text3208210256",
|
||||
"max": 15,
|
||||
"min": 15,
|
||||
"name": "id",
|
||||
"pattern": "^[a-z0-9]+$",
|
||||
"presentable": false,
|
||||
"primaryKey": true,
|
||||
"required": true,
|
||||
"system": true,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"cascadeDelete": true,
|
||||
"collectionId": "pbc_2170078043",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "relation2375286809",
|
||||
"maxSelect": 1,
|
||||
"minSelect": 0,
|
||||
"name": "workspace",
|
||||
"presentable": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "relation"
|
||||
},
|
||||
{
|
||||
"autogeneratePattern": "",
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "text2394296326",
|
||||
"max": 7,
|
||||
"min": 0,
|
||||
"name": "month",
|
||||
"pattern": "",
|
||||
"presentable": false,
|
||||
"primaryKey": false,
|
||||
"required": true,
|
||||
"system": false,
|
||||
"type": "text"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "number2072368721",
|
||||
"max": null,
|
||||
"min": null,
|
||||
"name": "requests",
|
||||
"onlyInt": false,
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "number1726912723",
|
||||
"max": null,
|
||||
"min": null,
|
||||
"name": "input_tokens",
|
||||
"onlyInt": false,
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "number2122787687",
|
||||
"max": null,
|
||||
"min": null,
|
||||
"name": "output_tokens",
|
||||
"onlyInt": false,
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"help": "",
|
||||
"hidden": false,
|
||||
"id": "number3913246453",
|
||||
"max": null,
|
||||
"min": null,
|
||||
"name": "instance_tokens",
|
||||
"onlyInt": false,
|
||||
"presentable": false,
|
||||
"required": false,
|
||||
"system": false,
|
||||
"type": "number"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "autodate2990389176",
|
||||
"name": "created",
|
||||
"onCreate": true,
|
||||
"onUpdate": false,
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
},
|
||||
{
|
||||
"hidden": false,
|
||||
"id": "autodate3332085495",
|
||||
"name": "updated",
|
||||
"onCreate": true,
|
||||
"onUpdate": true,
|
||||
"presentable": false,
|
||||
"system": false,
|
||||
"type": "autodate"
|
||||
}
|
||||
],
|
||||
"id": "pbc_3423747372",
|
||||
"indexes": [
|
||||
"CREATE UNIQUE INDEX idx_ai_usage_month ON ai_usage (workspace, month)"
|
||||
],
|
||||
"listRule": null,
|
||||
"name": "ai_usage",
|
||||
"system": false,
|
||||
"type": "base",
|
||||
"updateRule": null,
|
||||
"viewRule": null
|
||||
}
|
||||
]
|
||||
@@ -32,6 +32,7 @@ const form = ref({
|
||||
apiKey: "",
|
||||
chatModel: "",
|
||||
embedModel: "",
|
||||
transcribeModel: "",
|
||||
effort: "",
|
||||
});
|
||||
const keyTouched = ref(false);
|
||||
@@ -62,6 +63,7 @@ function startNew() {
|
||||
apiKey: "",
|
||||
chatModel: d.chat,
|
||||
embedModel: d.embed,
|
||||
transcribeModel: "",
|
||||
effort: "",
|
||||
};
|
||||
keyTouched.value = false;
|
||||
@@ -75,6 +77,7 @@ function setKind(kind: AiProviderKind) {
|
||||
if (form.value.chatModel === old.chat) form.value.chatModel = d.chat;
|
||||
if (form.value.embedModel === old.embed) form.value.embedModel = d.embed;
|
||||
if (kind !== "anthropic") form.value.effort = "";
|
||||
if (kind !== "openai") form.value.transcribeModel = "";
|
||||
form.value.kind = kind;
|
||||
}
|
||||
|
||||
@@ -86,6 +89,7 @@ function startEdit(p: AiProfile) {
|
||||
apiKey: "",
|
||||
chatModel: p.chatModel,
|
||||
embedModel: p.embedModel,
|
||||
transcribeModel: p.transcribeModel,
|
||||
effort: p.effort,
|
||||
};
|
||||
keyTouched.value = false;
|
||||
@@ -100,6 +104,7 @@ const input = (): AiProfileInput => {
|
||||
baseUrl: f.baseUrl.trim(),
|
||||
chatModel: f.chatModel.trim(),
|
||||
embedModel: f.embedModel.trim(),
|
||||
transcribeModel: f.transcribeModel.trim(),
|
||||
effort: f.effort as AiProfileInput["effort"],
|
||||
};
|
||||
if (editing.value === "new" || keyTouched.value) out.apiKey = f.apiKey.trim();
|
||||
@@ -163,6 +168,7 @@ const fmt = computed(() => new Intl.NumberFormat(locale.value, { notation: "comp
|
||||
{{ $t(`ai.kinds.${p.kind}`) }}
|
||||
<template v-if="p.chatModel"> · {{ $t("ai.chat") }}: {{ p.chatModel }}</template>
|
||||
<template v-if="p.embedModel"> · {{ $t("ai.embeddings") }}: {{ p.embedModel }}</template>
|
||||
<template v-if="p.transcribeModel"> · {{ $t("ai.speech") }}: {{ p.transcribeModel }}</template>
|
||||
· {{ p.keySet ? $t("ai.keySet") : $t("ai.noKey") }}
|
||||
</p>
|
||||
<p class="text-ui-xs text-ink-faint">
|
||||
@@ -280,6 +286,11 @@ const fmt = computed(() => new Intl.NumberFormat(locale.value, { notation: "comp
|
||||
:placeholder="form.kind === 'anthropic' ? $t('ai.noEmbeddings') : $t('ai.optional')"
|
||||
/>
|
||||
</label>
|
||||
<label v-if="form.kind === 'openai'" class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("ai.transcribeModel") }}</span>
|
||||
<input v-model="form.transcribeModel" class="dw-input" :placeholder="$t('ai.optional')" />
|
||||
<span class="text-ui-xs text-ink-muted">{{ $t("ai.transcribeModelHint") }}</span>
|
||||
</label>
|
||||
<label v-if="form.kind === 'anthropic'" class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("ai.effort") }}</span>
|
||||
<select v-model="form.effort" class="dw-input">
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<!-- SPDX-License-Identifier: AGPL-3.0-or-later -->
|
||||
<script setup lang="ts">
|
||||
import type { AiFile, AiIndexStatus, AiSettings, SearchHit } from "@docwell/api-client";
|
||||
import type { AiFile, AiIndexStatus, AiSettings, AiUsage, SearchHit } from "@docwell/api-client";
|
||||
import { DwButton, DwCallout } from "@docwell/ui";
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
@@ -24,6 +24,8 @@ const busy = ref(false);
|
||||
const unavailable = ref(false);
|
||||
const query = ref("");
|
||||
const hits = ref<SearchHit[]>([]);
|
||||
const usage = ref<AiUsage | null>(null);
|
||||
const limitInput = ref("");
|
||||
|
||||
async function loadIndex() {
|
||||
index.value = await api.ai.index(props.workspace);
|
||||
@@ -37,7 +39,12 @@ async function load() {
|
||||
errors.show(e);
|
||||
return;
|
||||
}
|
||||
await Promise.all([loadIndex(), api.ai.files(props.workspace).then((f) => (files.value = f))]);
|
||||
limitInput.value = settings.value.monthlyTokenLimit ? String(settings.value.monthlyTokenLimit) : "";
|
||||
await Promise.all([
|
||||
loadIndex(),
|
||||
api.ai.files(props.workspace).then((f) => (files.value = f)),
|
||||
api.ai.usage(props.workspace).then((u) => (usage.value = u)),
|
||||
]);
|
||||
for (const id of settings.value.ignored) void title(id);
|
||||
}
|
||||
onMounted(() => load().catch(errors.show));
|
||||
@@ -83,6 +90,19 @@ const save = (patch: Partial<AiSettings>) =>
|
||||
await loadIndex();
|
||||
});
|
||||
|
||||
const saveLimit = () =>
|
||||
run(async () => {
|
||||
if (!settings.value) return;
|
||||
const n = Math.max(0, Math.round(Number(limitInput.value) || 0));
|
||||
settings.value = await api.ai.saveSettings(props.workspace, { ...settings.value, monthlyTokenLimit: n });
|
||||
limitInput.value = n ? String(n) : "";
|
||||
usage.value = await api.ai.usage(props.workspace);
|
||||
refreshAi(props.workspace);
|
||||
});
|
||||
|
||||
const used = computed(() => (usage.value ? usage.value.inputTokens + usage.value.outputTokens : 0));
|
||||
const num = (n: number) => new Intl.NumberFormat(locale.value).format(n);
|
||||
|
||||
function changed() {
|
||||
refreshAi(props.workspace);
|
||||
void loadIndex().catch(errors.show);
|
||||
@@ -186,6 +206,53 @@ const size = (n: number) =>
|
||||
<AiProfiles :workspace="workspace" @changed="changed" />
|
||||
</div>
|
||||
|
||||
<div v-if="usage" class="space-y-2" data-testid="ai-usage">
|
||||
<h3 class="text-ui-md font-semibold">{{ $t("ai.limitTitle") }}</h3>
|
||||
<p class="text-ui-sm text-ink-muted">
|
||||
{{
|
||||
$t("ai.usedThisMonth", {
|
||||
month: usage.month,
|
||||
tokens: num(used),
|
||||
requests: num(usage.requests),
|
||||
})
|
||||
}}
|
||||
<template v-if="usage.instanceLimit">
|
||||
· {{ $t("ai.instanceShare", { used: num(usage.instanceTokens), limit: num(usage.instanceLimit) }) }}
|
||||
</template>
|
||||
</p>
|
||||
<div
|
||||
v-if="usage.limit"
|
||||
class="h-2 max-w-md overflow-hidden rounded-full bg-surface-sunken"
|
||||
role="progressbar"
|
||||
:aria-valuenow="Math.min(100, Math.round((used / usage.limit) * 100))"
|
||||
aria-valuemin="0"
|
||||
aria-valuemax="100"
|
||||
:aria-label="$t('ai.limitTitle')"
|
||||
>
|
||||
<div
|
||||
class="h-full"
|
||||
:class="used >= usage.limit ? 'bg-danger' : 'bg-primary'"
|
||||
:style="{ width: `${Math.min(100, (used / usage.limit) * 100)}%` }"
|
||||
/>
|
||||
</div>
|
||||
<form class="flex flex-wrap items-end gap-2" @submit.prevent="saveLimit">
|
||||
<label class="flex flex-col gap-1.5">
|
||||
<span class="text-ui-sm font-semibold">{{ $t("ai.monthlyLimit") }}</span>
|
||||
<input
|
||||
v-model="limitInput"
|
||||
type="number"
|
||||
min="0"
|
||||
step="1000"
|
||||
class="dw-input w-48"
|
||||
:placeholder="$t('ai.noLimit')"
|
||||
data-testid="ai-limit"
|
||||
/>
|
||||
</label>
|
||||
<DwButton type="submit" variant="secondary" :disabled="busy">{{ $t("common.save") }}</DwButton>
|
||||
</form>
|
||||
<p class="text-ui-xs text-ink-muted">{{ $t("ai.monthlyLimitHint") }}</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-2">
|
||||
<h3 class="text-ui-md font-semibold">{{ $t("ai.indexTitle") }}</h3>
|
||||
<label class="flex items-start gap-2 text-ui-md">
|
||||
@@ -290,7 +357,7 @@ const size = (n: number) =>
|
||||
<input
|
||||
type="file"
|
||||
multiple
|
||||
accept=".txt,.md,.markdown,.html,.htm,.docx,.csv,.json"
|
||||
accept=".txt,.md,.markdown,.html,.htm,.docx,.pdf,.csv,.json"
|
||||
class="sr-only"
|
||||
:disabled="busy"
|
||||
@change="upload"
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { transcriptParagraphs } from "./useAi";
|
||||
|
||||
describe("transcriptParagraphs", () => {
|
||||
it("groups sentences into paragraphs near the size, never splitting one", () => {
|
||||
const sentence = "We agreed to ship the release on Friday.";
|
||||
const text = Array.from({ length: 40 }, () => sentence).join(" \n ");
|
||||
const paras = transcriptParagraphs(text, 200);
|
||||
expect(paras.length).toBeGreaterThan(5);
|
||||
for (const p of paras) {
|
||||
expect(p.length).toBeLessThanOrEqual(200 + sentence.length);
|
||||
expect(p.endsWith(".")).toBe(true);
|
||||
}
|
||||
expect(paras.join(" ")).toBe(Array.from({ length: 40 }, () => sentence).join(" "));
|
||||
});
|
||||
|
||||
it("keeps a text without punctuation whole", () => {
|
||||
expect(transcriptParagraphs("hello there")).toEqual(["hello there"]);
|
||||
expect(transcriptParagraphs(" ")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -47,9 +47,10 @@ export function useAiAvailability(workspace: () => string | undefined) {
|
||||
api.ai
|
||||
.available(id)
|
||||
.then((a) => void (availability[id] = a))
|
||||
.catch((e) => {
|
||||
// A server without AI answers 404; treat it as "no AI".
|
||||
if (e instanceof ApiError) availability[id] = { chat: false, embeddings: false, canManage: false };
|
||||
.catch(() => {
|
||||
// A server without AI answers 404; that, or no answer at all,
|
||||
// means "no AI" here (the page must not wait on it).
|
||||
availability[id] = { chat: false, embeddings: false, transcribe: false, canManage: false };
|
||||
}),
|
||||
);
|
||||
},
|
||||
@@ -102,3 +103,51 @@ export function useAiWriter(workspace: () => string | undefined) {
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
const escapeHTML = (s: string) =>
|
||||
s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!);
|
||||
|
||||
/** Cuts a long transcript into paragraphs of a few sentences. */
|
||||
export function transcriptParagraphs(text: string, size = 600): string[] {
|
||||
const out: string[] = [];
|
||||
let cur = "";
|
||||
for (const part of text
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.split(/(?<=[.!?…])\s+/)) {
|
||||
if (cur && cur.length + part.length > size) {
|
||||
out.push(cur);
|
||||
cur = "";
|
||||
}
|
||||
cur = cur ? `${cur} ${part}` : part;
|
||||
}
|
||||
if (cur) out.push(cur);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The editor's Transcribe action for attachments: the summary as a section
|
||||
* and the full transcript in a toggle, as HTML to put below the file.
|
||||
*/
|
||||
export function useAiTranscriber() {
|
||||
const api = useApi();
|
||||
const { t } = useI18n();
|
||||
return async (src: string, _name: string): Promise<string> => {
|
||||
const id = /^\/api\/v1\/files\/([^/?#]+)/.exec(src)?.[1];
|
||||
if (!id) throw new Error(t("ai.transcribe.notAttachment"));
|
||||
let res;
|
||||
try {
|
||||
res = await api.ai.transcribe(decodeURIComponent(id), true);
|
||||
} catch (e) {
|
||||
throw e instanceof ApiError ? new Error(aiErrorText(e) || t("ai.failed")) : e;
|
||||
}
|
||||
let html = `<h3>${escapeHTML(t("ai.transcribe.summaryTitle", { name: res.name }))}</h3>`;
|
||||
if (res.summary) html += markdownToEditorHTML(res.summary);
|
||||
else if (res.summaryError) html += `<p><em>${escapeHTML(res.summaryError)}</em></p>`;
|
||||
const paras = transcriptParagraphs(res.text)
|
||||
.map((p) => `<p>${escapeHTML(p)}</p>`)
|
||||
.join("");
|
||||
html += `<details><summary>${escapeHTML(t("ai.transcribe.transcript"))}</summary><div data-type="detailsContent">${paras}</div></details>`;
|
||||
return html;
|
||||
};
|
||||
}
|
||||
@@ -619,7 +619,11 @@
|
||||
"syncedUnfold": "Ausklappen",
|
||||
"syncedLoading": "Seite wird geladen…",
|
||||
"syncedDenied": "Du kannst diese Seite nicht öffnen.",
|
||||
"syncedSelf": "Eine Seite kann sich nicht selbst zeigen."
|
||||
"syncedSelf": "Eine Seite kann sich nicht selbst zeigen.",
|
||||
"transcribe": "Transkribieren",
|
||||
"transcribeHint": "Mit KI eine Zusammenfassung und das Transkript darunter einfügen",
|
||||
"transcribing": "Wird transkribiert …",
|
||||
"transcribeFailed": "Die Aufnahme konnte nicht transkribiert werden."
|
||||
},
|
||||
"colors": {
|
||||
"gray": "Grau",
|
||||
@@ -1376,7 +1380,7 @@
|
||||
"ignoredHint": "Diese Seiten und ihre Unterseiten werden weder indiziert noch in Antworten verwendet.",
|
||||
"ignoreSearch": "Seite zum Auslassen suchen",
|
||||
"filesTitle": "Zusätzliche Dokumente",
|
||||
"filesHint": "Text-, Markdown-, HTML- oder Word-Dateien, die der Chat als Quellen nutzen kann (je bis 10 MB).",
|
||||
"filesHint": "Text-, Markdown-, HTML-, Word- oder PDF-Dateien, die der Chat als Quellen nutzen kann (je bis 10 MB).",
|
||||
"fileIndexed": "indiziert",
|
||||
"fileWaiting": "wartet auf den Index",
|
||||
"addFiles": "Dateien hinzufügen …",
|
||||
@@ -1416,6 +1420,20 @@
|
||||
"effort": "Aufwand",
|
||||
"effortDefault": "Standard des Modells",
|
||||
"addProfile": "Anbieter hinzufügen",
|
||||
"cancel": "Abbrechen"
|
||||
"cancel": "Abbrechen",
|
||||
"speech": "Sprache",
|
||||
"transcribeModel": "Sprache-zu-Text-Modell",
|
||||
"transcribeModelHint": "Für den Button „Transkribieren“ an Audio- und Videodateien, z. B. whisper-1.",
|
||||
"limitTitle": "Monatliches Limit",
|
||||
"usedThisMonth": "Verbraucht im {month}: {tokens} Tokens in {requests} Anfragen",
|
||||
"instanceShare": "{used} von {limit} Tokens über die Anbieter des Servers",
|
||||
"monthlyLimit": "Tokens pro Monat",
|
||||
"noLimit": "Kein Limit",
|
||||
"monthlyLimitHint": "Ist es erreicht, pausiert die KI bis zum nächsten Monat (UTC). Leer lassen für kein Limit.",
|
||||
"transcribe": {
|
||||
"notAttachment": "Nur Dateien, die auf diese Seite hochgeladen wurden, können transkribiert werden.",
|
||||
"summaryTitle": "Zusammenfassung von {name}",
|
||||
"transcript": "Transkript"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -619,7 +619,11 @@
|
||||
"syncedUnfold": "Unfold",
|
||||
"syncedLoading": "Loading the page…",
|
||||
"syncedDenied": "You can't open this page.",
|
||||
"syncedSelf": "A page can't show itself."
|
||||
"syncedSelf": "A page can't show itself.",
|
||||
"transcribe": "Transcribe",
|
||||
"transcribeHint": "Add a summary and the transcript below, with AI",
|
||||
"transcribing": "Transcribing…",
|
||||
"transcribeFailed": "The recording could not be transcribed."
|
||||
},
|
||||
"colors": {
|
||||
"gray": "Grey",
|
||||
@@ -1376,7 +1380,7 @@
|
||||
"ignoredHint": "These pages and their subpages are not indexed or used in answers.",
|
||||
"ignoreSearch": "Find a page to leave out",
|
||||
"filesTitle": "Extra documents",
|
||||
"filesHint": "Text, Markdown, HTML or Word files the chat can use as sources (up to 10 MB each).",
|
||||
"filesHint": "Text, Markdown, HTML, Word or PDF files the chat can use as sources (up to 10 MB each).",
|
||||
"fileIndexed": "indexed",
|
||||
"fileWaiting": "waiting for the index",
|
||||
"addFiles": "Add files…",
|
||||
@@ -1416,6 +1420,20 @@
|
||||
"effort": "Effort",
|
||||
"effortDefault": "Model default",
|
||||
"addProfile": "Add a provider",
|
||||
"cancel": "Cancel"
|
||||
"cancel": "Cancel",
|
||||
"speech": "speech",
|
||||
"transcribeModel": "Speech-to-text model",
|
||||
"transcribeModelHint": "For the Transcribe button on audio and video files, e.g. whisper-1.",
|
||||
"limitTitle": "Monthly limit",
|
||||
"usedThisMonth": "Used in {month}: {tokens} tokens in {requests} requests",
|
||||
"instanceShare": "{used} of {limit} tokens from the server's providers",
|
||||
"monthlyLimit": "Tokens per month",
|
||||
"noLimit": "No limit",
|
||||
"monthlyLimitHint": "When the workspace reaches it, AI stops until the next month (UTC). Leave empty for no limit.",
|
||||
"transcribe": {
|
||||
"notAttachment": "Only files uploaded to this page can be transcribed.",
|
||||
"summaryTitle": "Summary of {name}",
|
||||
"transcript": "Transcript"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -619,7 +619,11 @@
|
||||
"syncedUnfold": "Desplegar",
|
||||
"syncedLoading": "Cargando la página…",
|
||||
"syncedDenied": "No puedes abrir esta página.",
|
||||
"syncedSelf": "Una página no puede mostrarse a sí misma."
|
||||
"syncedSelf": "Una página no puede mostrarse a sí misma.",
|
||||
"transcribe": "Transcribir",
|
||||
"transcribeHint": "Añadir debajo un resumen y la transcripción, con IA",
|
||||
"transcribing": "Transcribiendo…",
|
||||
"transcribeFailed": "No se pudo transcribir la grabación."
|
||||
},
|
||||
"colors": {
|
||||
"gray": "Gris",
|
||||
@@ -1376,7 +1380,7 @@
|
||||
"ignoredHint": "Estas páginas y sus subpáginas no se indexan ni se usan en las respuestas.",
|
||||
"ignoreSearch": "Buscar una página para excluir",
|
||||
"filesTitle": "Documentos adicionales",
|
||||
"filesHint": "Archivos de texto, Markdown, HTML o Word que el chat puede usar como fuentes (hasta 10 MB cada uno).",
|
||||
"filesHint": "Archivos de texto, Markdown, HTML, Word o PDF que el chat puede usar como fuentes (hasta 10 MB cada uno).",
|
||||
"fileIndexed": "indexado",
|
||||
"fileWaiting": "esperando al índice",
|
||||
"addFiles": "Añadir archivos…",
|
||||
@@ -1416,6 +1420,20 @@
|
||||
"effort": "Esfuerzo",
|
||||
"effortDefault": "El del modelo",
|
||||
"addProfile": "Añadir un proveedor",
|
||||
"cancel": "Cancelar"
|
||||
"cancel": "Cancelar",
|
||||
"speech": "voz",
|
||||
"transcribeModel": "Modelo de voz a texto",
|
||||
"transcribeModelHint": "Para el botón Transcribir de los archivos de audio y vídeo, p. ej. whisper-1.",
|
||||
"limitTitle": "Límite mensual",
|
||||
"usedThisMonth": "Usado en {month}: {tokens} tokens en {requests} solicitudes",
|
||||
"instanceShare": "{used} de {limit} tokens con los proveedores del servidor",
|
||||
"monthlyLimit": "Tokens al mes",
|
||||
"noLimit": "Sin límite",
|
||||
"monthlyLimitHint": "Al alcanzarlo, la IA se detiene hasta el mes siguiente (UTC). Déjalo vacío para no tener límite.",
|
||||
"transcribe": {
|
||||
"notAttachment": "Solo se pueden transcribir archivos subidos a esta página.",
|
||||
"summaryTitle": "Resumen de {name}",
|
||||
"transcript": "Transcripción"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -619,7 +619,11 @@
|
||||
"syncedUnfold": "Déplier",
|
||||
"syncedLoading": "Chargement de la page…",
|
||||
"syncedDenied": "Vous ne pouvez pas ouvrir cette page.",
|
||||
"syncedSelf": "Une page ne peut pas s’afficher elle-même."
|
||||
"syncedSelf": "Une page ne peut pas s’afficher elle-même.",
|
||||
"transcribe": "Transcrire",
|
||||
"transcribeHint": "Ajouter dessous un résumé et la transcription, avec l’IA",
|
||||
"transcribing": "Transcription…",
|
||||
"transcribeFailed": "L’enregistrement n’a pas pu être transcrit."
|
||||
},
|
||||
"colors": {
|
||||
"gray": "Gris",
|
||||
@@ -1376,7 +1380,7 @@
|
||||
"ignoredHint": "Ces pages et leurs sous-pages ne sont ni indexées ni utilisées dans les réponses.",
|
||||
"ignoreSearch": "Chercher une page à exclure",
|
||||
"filesTitle": "Documents supplémentaires",
|
||||
"filesHint": "Fichiers texte, Markdown, HTML ou Word que le chat peut citer (10 Mo chacun au plus).",
|
||||
"filesHint": "Fichiers texte, Markdown, HTML, Word ou PDF que le chat peut citer (10 Mo chacun au plus).",
|
||||
"fileIndexed": "indexé",
|
||||
"fileWaiting": "en attente de l’index",
|
||||
"addFiles": "Ajouter des fichiers…",
|
||||
@@ -1416,6 +1420,20 @@
|
||||
"effort": "Effort",
|
||||
"effortDefault": "Valeur du modèle",
|
||||
"addProfile": "Ajouter un fournisseur",
|
||||
"cancel": "Annuler"
|
||||
"cancel": "Annuler",
|
||||
"speech": "parole",
|
||||
"transcribeModel": "Modèle de transcription",
|
||||
"transcribeModelHint": "Pour le bouton Transcrire des fichiers audio et vidéo, par ex. whisper-1.",
|
||||
"limitTitle": "Limite mensuelle",
|
||||
"usedThisMonth": "Utilisé en {month} : {tokens} jetons en {requests} requêtes",
|
||||
"instanceShare": "{used} jetons sur {limit} via les fournisseurs du serveur",
|
||||
"monthlyLimit": "Jetons par mois",
|
||||
"noLimit": "Aucune limite",
|
||||
"monthlyLimitHint": "Une fois atteinte, l’IA s’arrête jusqu’au mois suivant (UTC). Laisser vide pour aucune limite.",
|
||||
"transcribe": {
|
||||
"notAttachment": "Seuls les fichiers téléversés sur cette page peuvent être transcrits.",
|
||||
"summaryTitle": "Résumé de {name}",
|
||||
"transcript": "Transcription"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -619,7 +619,11 @@
|
||||
"syncedUnfold": "Rozwiń",
|
||||
"syncedLoading": "Wczytywanie strony…",
|
||||
"syncedDenied": "Nie możesz otworzyć tej strony.",
|
||||
"syncedSelf": "Strona nie może pokazać samej siebie."
|
||||
"syncedSelf": "Strona nie może pokazać samej siebie.",
|
||||
"transcribe": "Transkrybuj",
|
||||
"transcribeHint": "Dodaj poniżej podsumowanie i transkrypcję z pomocą AI",
|
||||
"transcribing": "Transkrypcja…",
|
||||
"transcribeFailed": "Nie udało się przetranskrybować nagrania."
|
||||
},
|
||||
"colors": {
|
||||
"gray": "Szary",
|
||||
@@ -1376,7 +1380,7 @@
|
||||
"ignoredHint": "Te strony i ich podstrony nie są indeksowane ani używane w odpowiedziach.",
|
||||
"ignoreSearch": "Znajdź stronę do pominięcia",
|
||||
"filesTitle": "Dodatkowe dokumenty",
|
||||
"filesHint": "Pliki tekstowe, Markdown, HTML lub Word, z których czat może korzystać jako źródeł (do 10 MB każdy).",
|
||||
"filesHint": "Pliki tekstowe, Markdown, HTML, Word lub PDF, z których czat może korzystać jako źródeł (do 10 MB każdy).",
|
||||
"fileIndexed": "zaindeksowany",
|
||||
"fileWaiting": "czeka na indeks",
|
||||
"addFiles": "Dodaj pliki…",
|
||||
@@ -1416,6 +1420,20 @@
|
||||
"effort": "Wysiłek",
|
||||
"effortDefault": "Domyślny modelu",
|
||||
"addProfile": "Dodaj dostawcę",
|
||||
"cancel": "Anuluj"
|
||||
"cancel": "Anuluj",
|
||||
"speech": "mowa",
|
||||
"transcribeModel": "Model zamiany mowy na tekst",
|
||||
"transcribeModelHint": "Dla przycisku Transkrybuj przy plikach audio i wideo, np. whisper-1.",
|
||||
"limitTitle": "Limit miesięczny",
|
||||
"usedThisMonth": "Zużyto w {month}: tokeny: {tokens}, zapytania: {requests}",
|
||||
"instanceShare": "{used} z {limit} tokenów od dostawców serwera",
|
||||
"monthlyLimit": "Tokeny na miesiąc",
|
||||
"noLimit": "Bez limitu",
|
||||
"monthlyLimitHint": "Po jego osiągnięciu AI zatrzymuje się do następnego miesiąca (UTC). Zostaw puste, aby nie ustawiać limitu.",
|
||||
"transcribe": {
|
||||
"notAttachment": "Transkrybować można tylko pliki przesłane na tę stronę.",
|
||||
"summaryTitle": "Podsumowanie: {name}",
|
||||
"transcript": "Transkrypcja"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -27,7 +27,7 @@ import PageComments from "../../components/PageComments.vue";
|
||||
import PageList from "../../components/PageList.vue";
|
||||
import PageProperties from "../../components/PageProperties.vue";
|
||||
import ShareDialog from "../../components/ShareDialog.vue";
|
||||
import { useAiWriter } from "../../composables/useAi";
|
||||
import { useAiAvailability, useAiTranscriber, useAiWriter } from "../../composables/useAi";
|
||||
import { useEditorLabels, useMentions, usePageLinks } from "../../composables/useEditorHosts";
|
||||
import { useFileHost } from "../../composables/useFiles";
|
||||
import { useSplit } from "../../composables/useSplit";
|
||||
@@ -268,6 +268,13 @@ async function commentsChanged() {
|
||||
|
||||
// Attachments: images and files load through a short-lived file token.
|
||||
const files = useFileHost(() => page.value?.id ?? props.id);
|
||||
// Audio and video attachments get a Transcribe button where AI can do it.
|
||||
const aiAvail = useAiAvailability(() => page.value?.workspace);
|
||||
const transcribe = useAiTranscriber();
|
||||
Object.defineProperty(files.host, "transcribe", {
|
||||
get: () => (aiAvail.value?.transcribe ? transcribe : undefined),
|
||||
configurable: true,
|
||||
});
|
||||
const filesReady = ref(false);
|
||||
files
|
||||
.ready()
|
||||
@@ -944,7 +951,7 @@ const purge = () =>
|
||||
/>
|
||||
|
||||
<DocwellEditor
|
||||
v-if="provider && synced && filesReady"
|
||||
v-if="provider && synced && filesReady && aiAvail"
|
||||
ref="editorRef"
|
||||
:key="page.id"
|
||||
:provider="provider"
|
||||
|
||||
+121
-3
@@ -3479,6 +3479,91 @@ paths:
|
||||
schema: { type: object, additionalProperties: true }
|
||||
"202": { description: A notification was received }
|
||||
"401": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/workspaces/{id}/ai/usage:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
get:
|
||||
operationId: getAiUsage
|
||||
tags: [ai]
|
||||
summary: The workspace's AI usage this month, with its caps (workspace admin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/AiUsage" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/admin/ai/usage:
|
||||
get:
|
||||
operationId: listAiUsage
|
||||
tags: [admin]
|
||||
summary: Every workspace's AI usage this month, most first (superadmin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: array, items: { $ref: "#/components/schemas/AiUsage" } }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/admin/ai/settings:
|
||||
get:
|
||||
operationId: getInstanceAiSettings
|
||||
tags: [admin]
|
||||
summary: The server's AI rules (superadmin)
|
||||
security: [{ bearer: [] }]
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/AiInstanceSettings" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
put:
|
||||
operationId: saveInstanceAiSettings
|
||||
tags: [admin]
|
||||
summary: Replace the server's AI rules (superadmin)
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/AiInstanceSettings" }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/AiInstanceSettings" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
/api/v1/files/{id}/transcribe:
|
||||
parameters:
|
||||
- { name: id, in: path, required: true, schema: { type: string } }
|
||||
post:
|
||||
operationId: transcribeFile
|
||||
tags: [ai]
|
||||
summary: 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.
|
||||
security: [{ bearer: [] }]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema: { type: object, properties: { summarize: { type: boolean } } }
|
||||
responses:
|
||||
"200":
|
||||
description: OK
|
||||
content:
|
||||
application/json:
|
||||
schema: { $ref: "#/components/schemas/AiTranscript" }
|
||||
"400": { $ref: "#/components/responses/Error" }
|
||||
"403": { $ref: "#/components/responses/Error" }
|
||||
"404": { $ref: "#/components/responses/Error" }
|
||||
components:
|
||||
securitySchemes:
|
||||
bearer:
|
||||
@@ -4484,26 +4569,28 @@ components:
|
||||
ids: { type: array, items: { type: string }, maxItems: 200 }
|
||||
AiAvailability:
|
||||
type: object
|
||||
required: [chat, embeddings, canManage]
|
||||
required: [chat, embeddings, transcribe, canManage]
|
||||
properties:
|
||||
chat: { type: boolean, description: A profile with a chat model is set up and AI is on }
|
||||
embeddings: { type: boolean, description: The workspace is indexed for retrieval }
|
||||
transcribe: { type: boolean, description: A profile can turn audio attachments into text }
|
||||
canManage: { type: boolean, description: The caller may change the workspace's AI settings }
|
||||
AiSettings:
|
||||
type: object
|
||||
required: [enabled, useInstanceProfiles, index, ignored]
|
||||
required: [enabled, useInstanceProfiles, index, ignored, monthlyTokenLimit]
|
||||
properties:
|
||||
enabled: { type: boolean }
|
||||
useInstanceProfiles: { type: boolean, description: After its own profiles, the workspace uses the instance's }
|
||||
index: { type: boolean, description: Embed pages for retrieval (sends every page to the embedding provider) }
|
||||
ignored: { type: array, items: { type: string }, description: Pages (with their subpages) that are neither indexed nor retrieved }
|
||||
monthlyTokenLimit: { type: integer, minimum: 0, description: Tokens the workspace may use per month; 0 is no cap }
|
||||
AiProviderKind:
|
||||
type: string
|
||||
enum: [openai, anthropic, ollama]
|
||||
description: openai is any OpenAI-compatible API
|
||||
AiProfile:
|
||||
type: object
|
||||
required: [id, workspace, name, kind, baseUrl, keySet, chatModel, embedModel, effort, enabled, position, usage, lastUsed, lastError, created]
|
||||
required: [id, workspace, name, kind, baseUrl, keySet, chatModel, embedModel, transcribeModel, effort, enabled, position, usage, lastUsed, lastError, created]
|
||||
properties:
|
||||
id: { type: string }
|
||||
workspace: { type: string, description: Empty for an instance default }
|
||||
@@ -4513,6 +4600,7 @@ components:
|
||||
keySet: { type: boolean, description: An API key is stored (keys are never returned) }
|
||||
chatModel: { type: string }
|
||||
embedModel: { type: string, description: Empty when the profile is not used for embeddings }
|
||||
transcribeModel: { type: string, description: Speech-to-text model (OpenAI-compatible); empty when unused }
|
||||
effort: { type: string, description: Anthropic effort level, empty for the model's default }
|
||||
enabled: { type: boolean }
|
||||
position: { type: integer }
|
||||
@@ -4536,6 +4624,7 @@ components:
|
||||
apiKey: { type: string, description: "Write-only; an empty string removes the key" }
|
||||
chatModel: { type: string }
|
||||
embedModel: { type: string }
|
||||
transcribeModel: { type: string }
|
||||
effort: { type: string, enum: ["", low, medium, high, xhigh, max] }
|
||||
enabled: { type: boolean }
|
||||
AiTestResult:
|
||||
@@ -4635,3 +4724,32 @@ components:
|
||||
before: { type: string, description: Text in front of the selection (continue) }
|
||||
language: { type: string, description: Target language (translate) }
|
||||
instruction: { type: string, maxLength: 2000, description: What to do (custom) }
|
||||
AiUsage:
|
||||
type: object
|
||||
required: [workspace, month, requests, inputTokens, outputTokens, instanceTokens, limit, instanceLimit]
|
||||
properties:
|
||||
workspace: { type: string }
|
||||
name: { type: string, description: The workspace's name (admin listing) }
|
||||
month: { type: string, description: "Calendar month in UTC, e.g. 2026-11" }
|
||||
requests: { type: integer }
|
||||
inputTokens: { type: integer }
|
||||
outputTokens: { type: integer }
|
||||
instanceTokens: { type: integer, description: Tokens used through the server's own profiles }
|
||||
limit: { type: integer, description: The workspace's monthly token cap; 0 is none }
|
||||
instanceLimit: { type: integer, description: The server's cap on instanceTokens; 0 is none }
|
||||
AiInstanceSettings:
|
||||
type: object
|
||||
required: [workspaceTokenLimit]
|
||||
properties:
|
||||
workspaceTokenLimit:
|
||||
type: integer
|
||||
minimum: 0
|
||||
description: Tokens one workspace may use through the server's profiles per month; 0 is no cap
|
||||
AiTranscript:
|
||||
type: object
|
||||
required: [name, text, summary]
|
||||
properties:
|
||||
name: { type: string }
|
||||
text: { type: string }
|
||||
summary: { type: string, description: Markdown; empty when not asked for or when it failed }
|
||||
summaryError: { type: string }
|
||||
Reference in new issue
Block a user