Files
Docwell/Web-App/frontend/src/composables/useAi.ts
T
tajniak81andClaude Opus 5.5 0ebf064173
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
Add audio transcripts, monthly AI limits, PDF sources and AI chat on phones
Follow-ups to Phase E (ADR-15):

- Transcription (E2): OpenAI-compatible profiles can name a speech-to-text
  model; POST /files/{id}/transcribe turns an audio or video attachment
  (up to 25 MB) into text and a summary with key points and action items.
  The editor gets a Transcribe button on media files that inserts the
  summary and the transcript in a toggle.
- Monthly token limits: ai_usage counts requests and tokens per workspace
  and month. Workspace admins can cap their workspace; superadmins can cap
  what each workspace uses through the server's providers, after which
  the workspace's own providers keep working. The admin panel lists usage.
- PDF text for extra retrieval files (ledongthuc/pdf, pure Go).
- Phone app: an AI chat screen for the workspace or a page, with streamed
  answers and sources that open the cited block.
- OpenAPI, generated clients, migration, translations and docs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 22:26:27 +01:00

154 lines
5.3 KiB
TypeScript

// SPDX-License-Identifier: AGPL-3.0-or-later
import { ApiError, type AiAvailability } from "@docwell/api-client";
import type { AiHost } from "@docwell/editor";
import { computed, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { useApi } from "../api";
import { markdownToEditorHTML } from "../lib/markdown";
// What AI offers per workspace, loaded once per workspace and session.
const availability = reactive<Record<string, AiAvailability | undefined>>({});
const loading = new Map<string, Promise<void>>();
function readOpen(): boolean {
try {
return localStorage.getItem("docwell.aiPanel") === "1";
} catch {
return false;
}
}
/** Whether the AI chat panel is open (remembered per browser). */
export const aiPanelOpen = ref(readOpen());
watch(aiPanelOpen, (open) => {
try {
localStorage.setItem("docwell.aiPanel", open ? "1" : "0");
} catch {
// private mode: keep it for this tab only
}
});
/** Forgets what was loaded for a workspace, e.g. after its AI settings changed. */
export function refreshAi(workspace: string) {
delete availability[workspace];
loading.delete(workspace);
}
/** What AI offers in a workspace; undefined until loaded, or when the server has no AI. */
export function useAiAvailability(workspace: () => string | undefined) {
const api = useApi();
watch(
workspace,
(id) => {
if (!id || availability[id] || loading.has(id)) return;
loading.set(
id,
api.ai
.available(id)
.then((a) => void (availability[id] = a))
.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 };
}),
);
},
{ immediate: true },
);
return computed(() => {
const id = workspace();
return id ? availability[id] : undefined;
});
}
/** The server's words for a failed AI call. */
export function aiErrorText(e: ApiError): string {
return e.serverMessage || Object.values(e.fields)[0] || "";
}
const translateTo = ["en", "de", "fr", "es", "pl", "it", "pt", "nl", "uk", "cs", "sv", "ja", "zh", "ko"];
/** The editor's AI writing host for a workspace, when AI is set up there. */
export function useAiWriter(workspace: () => string | undefined) {
const api = useApi();
const { locale, t } = useI18n();
const avail = useAiAvailability(workspace);
return computed<AiHost | undefined>(() => {
const ws = workspace();
if (!ws || !avail.value?.chat) return undefined;
let names: Intl.DisplayNames | undefined;
try {
names = new Intl.DisplayNames([locale.value], { type: "language" });
} catch {
names = undefined;
}
// The reader's language first, then the rest.
const own = locale.value.split("-")[0] ?? "en";
const codes = [own, ...translateTo.filter((c) => c !== own)];
return {
languages: codes.map((c) => names?.of(c) ?? c),
toHTML: markdownToEditorHTML,
async run(req, onText, signal) {
try {
for await (const ev of api.ai.write(ws, req, signal)) {
const data = ev.data as { text?: string; message?: string };
if (ev.event === "delta" && data.text) onText(data.text);
else if (ev.event === "error") throw new Error(data.message || t("ai.failed"));
}
} catch (e) {
throw e instanceof ApiError ? new Error(aiErrorText(e) || t("ai.failed")) : e;
}
},
};
});
}
const escapeHTML = (s: string) =>
s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[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;
};
}