1 Commits

Author SHA1 Message Date
muena
4591ead8c8 feat: add standalone document pseudonymization to Raycast 2026-11-30 16:11:44 +01:00
9 changed files with 1050 additions and 19 deletions

View File

@@ -40,10 +40,36 @@ Jeder AI-Befehl pseudonymisiert die Eingabe via Velum, zeigt einen Confirm-Schri
### Pseudonymisieren ### Pseudonymisieren
- `Text pseudonymisieren` (View) — Text manuell eingeben, Sitzung und Entitätstypen wählen, Mapping inspizieren. - `Text oder Dokument pseudonymisieren` (View) — Text manuell eingeben oder ein Office-/PDF-Dokument auswählen, Sitzung und Entitätstypen wählen, Mapping inspizieren.
- `Markierten Text pseudonymisieren` (No-View) — Schnellbefehl: aktuelle Selektion wird pseudonymisiert und je nach Preference kopiert oder eingefügt. - `Markierten Text pseudonymisieren` (No-View) — Schnellbefehl: aktuelle Selektion wird pseudonymisiert und je nach Preference kopiert oder eingefügt.
- `Zwischenablage pseudonymisieren` (No-View) — analog für den Zwischenablage-Inhalt. - `Zwischenablage pseudonymisieren` (No-View) — analog für den Zwischenablage-Inhalt.
Im View-Befehl unter **Eingabe → Office-Dokument oder PDF** sind DOCX, XLSX, PPTX
und PDF bis 20 MiB auswählbar. Die Bildauswahl gilt pro Aufruf:
- **Datenschutz-Platzhalter** (`placeholder`) ist der Standard bei jedem neuen Aufruf.
- **Bilder vollständig entfernen** (`remove`) entfernt die Bildobjekte.
- **Bilder behalten** (`keep`) übernimmt Office-Bilder unverändert und zeigt vor dem
Aufruf sowie im Ergebnis einen deutlichen Datenschutz-Warnhinweis.
Die Bildbehandlung erfolgt ausschließlich im Velum-Backend, ohne OCR oder zusätzliche
Modelle. Bei Platzhaltern bleiben Position und Größe soweit unterstützt erhalten.
PDF wird als Word-Dokument neu aufgebaut; dort bleiben Bildpositionen nicht erhalten.
Nicht sicher bereinigbare Inhalte werden abgewiesen. Entfernte Bilder lassen sich
mit dem Mapping nicht wiederherstellen.
Das Ergebnis zeigt Bildzähler und sämtliche Backend-Warnungen. Die Zuordnung wird in
der gewählten Velum-Sitzung gespeichert. Die verarbeitete Kopie liegt im gewählten
Ausgabeordner oder standardmäßig neben dem Original und lässt sich im Finder anzeigen
oder öffnen. Vorhandene Dateien werden niemals überschrieben; Namenskollisionen
erhalten einen nummerierten Zusatz.
Dieser Flow benötigt ein Backend mit `document_image_policy: true` unter
`/api/project-capabilities`. Die Extension übermittelt `image_policy` explizit an
`/api/pseudonymize-document` und prüft dessen Bestätigung. Ältere Backends werden vor
dem Upload abgewiesen. Es gibt keinen automatischen Rückfall auf einen Textaufruf
oder unbereinigte Bilder. Die Schnellbefehle verarbeiten weiterhin Text.
### Wiederherstellen ### Wiederherstellen
- `Text wiederherstellen` (View) — Platzhalter-Text und Sitzung wählen, Originale per Velum oder lokal einsetzen. - `Text wiederherstellen` (View) — Platzhalter-Text und Sitzung wählen, Originale per Velum oder lokal einsetzen.
@@ -78,7 +104,13 @@ Die Extension läuft auf der stabilen Raycast-Version sowie der 2.0 Beta. Für d
npm install npm install
npm run dev # ray develop — live reload, lädt die Extension in den lokalen Raycast npm run dev # ray develop — live reload, lädt die Extension in den lokalen Raycast
npm run lint npm run lint
npm run build # ray build -e dist npm run build # ray build -e dist -o dist: erzeugt nur lokale Artefakte
node --test tests/*.test.cjs # Dokumenttransport, Bildoptionen, sichere Dateiausgabe
``` ```
Voraussetzungen: macOS, Node 22+, Raycast (Pro für die AI-Befehle). Voraussetzungen: macOS, Node 22+, Raycast (Pro für die AI-Befehle).
`build` schreibt ausdrücklich in `dist/` und ersetzt keine installierte Extension.
Raycasts CLI verwendet ohne `-o` standardmäßig den gemeinsamen Installationsordner
der Extension `velum`; bei mehreren Checkouts können dadurch Befehle einer anderen
Velum-Version verschwinden. `dev` aktualisiert die Installation bewusst.

View File

@@ -29,6 +29,12 @@
"description": "Aus Notizen, Stichpunkten oder einem Transkript ein strukturiertes Briefing per Raycast-KI erstellen — pseudonymisiert.", "description": "Aus Notizen, Stichpunkten oder einem Transkript ein strukturiertes Briefing per Raycast-KI erstellen — pseudonymisiert.",
"mode": "view" "mode": "view"
}, },
{
"name": "summarize-meeting-notes",
"title": "Meeting Notes strukturieren",
"description": "Aus Meeting-Notizen in Prosa eine sauber strukturierte Zusammenfassung (Kontext, Teilnehmer, Themen, Entscheidungen, Action Items) per Raycast-KI erstellen — pseudonymisiert.",
"mode": "view"
},
{ {
"name": "extract-action-items", "name": "extract-action-items",
"title": "Action Items extrahieren", "title": "Action Items extrahieren",
@@ -49,8 +55,8 @@
}, },
{ {
"name": "pseudonymize-text", "name": "pseudonymize-text",
"title": "Text pseudonymisieren", "title": "Text oder Dokument pseudonymisieren",
"description": "Eingegebenen, markierten oder Zwischenablage-Text pseudonymisieren.", "description": "Text oder Office-/PDF-Dokumente pseudonymisieren, mit wählbarer Bildbehandlung.",
"mode": "view" "mode": "view"
}, },
{ {
@@ -203,7 +209,7 @@
} }
], ],
"scripts": { "scripts": {
"build": "ray build -e dist", "build": "ray build -e dist -o dist",
"dev": "ray develop", "dev": "ray develop",
"fix-lint": "ray lint --fix", "fix-lint": "ray lint --fix",
"lint": "ray lint", "lint": "ray lint",

53
src/document-result.tsx Normal file
View File

@@ -0,0 +1,53 @@
import { Action, ActionPanel, Detail } from "@raycast/api";
import type { PseudonymizeDocumentResponse, VelumSession } from "./types";
import { markdownCodeBlock, mappingSummary, sessionSubtitle } from "./ui";
export function DocumentResult({
result,
session,
path,
}: {
result: PseudonymizeDocumentResponse;
session: VelumSession;
path: string;
}) {
const warnings = result.warnings.flatMap((warning) => [
"> " + warning.replace(/\n/g, "\n> "),
"",
]);
return (
<Detail
markdown={[
result.warnings.length
? "# Dokument mit Warnhinweis bereit"
: "# Pseudonymisiertes Dokument bereit",
"",
...warnings,
markdownCodeBlock(path),
"",
`**${result.entity_count} Zuordnungen** · ${result.segment_count} Textabschnitte`,
"",
`**${result.images_replaced} Bilder ersetzt · ${result.images_removed} Bilder entfernt**`,
"",
`${result.media_parts_removed} Medienbestandteile und Vorschaubilder entfernt.`,
"",
result.image_policy === "keep"
? "Bildinhalte wurden nicht geprüft."
: "Entfernte Bilder lassen sich mit der Zuordnung nicht wiederherstellen.",
"",
`## ${session.name}`,
sessionSubtitle(session),
"",
"## Zuordnung",
mappingSummary(result.mapping),
].join("\n")}
actions={
<ActionPanel>
<Action.ShowInFinder title="Datei im Finder zeigen" path={path} />
<Action.Open title="Dokument öffnen" target={path} />
<Action.CopyToClipboard title="Dateipfad kopieren" content={path} />
</ActionPanel>
}
/>
);
}

180
src/documents.ts Normal file
View File

@@ -0,0 +1,180 @@
import { File } from "node:buffer";
import { link, mkdtemp, open, rm, writeFile } from "node:fs/promises";
import { basename, extname, join, parse, win32 } from "node:path";
import type {
ImagePolicy,
PlaceholderMapping,
PseudonymizeDocumentResponse,
} from "./types";
export const DOCUMENT_TYPES: Record<string, string> = {
".docx":
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
".pptx":
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
".pdf": "application/pdf",
};
export const KEEP_IMAGE_WARNING =
"Achtung: Bilder wurden unverändert übernommen und können sensible Informationen enthalten. Bildinhalte werden nicht auf personenbezogene Daten geprüft.";
const MAX_UPLOAD_BYTES = 20 * 1024 * 1024;
const MAX_OUTPUT_BYTES = 128 * 1024 * 1024;
export async function documentForm(
filePath: string,
mapping: PlaceholderMapping,
entityTypes?: string[],
imagePolicy: ImagePolicy = "placeholder",
): Promise<FormData> {
if (!["placeholder", "remove", "keep"].includes(imagePolicy)) {
throw new Error("Ungültige Bildbehandlung.");
}
const type = DOCUMENT_TYPES[extname(filePath).toLowerCase()];
if (!type)
throw new Error("Bitte eine DOCX-, XLSX-, PPTX- oder PDF-Datei auswählen.");
const source = await open(filePath, "r");
try {
const stat = await source.stat();
if (!stat.isFile() || stat.size === 0)
throw new Error("Bitte eine nicht leere Datei auswählen.");
if (stat.size > MAX_UPLOAD_BYTES)
throw new Error("Datei zu groß (maximal 20 MiB).");
const data = await source.readFile();
if (!data.length || data.length > MAX_UPLOAD_BYTES)
throw new Error("Datei ist leer oder zu groß.");
const form = new FormData();
form.append("file", new File([data], basename(filePath), { type }));
form.append("mapping", JSON.stringify(mapping));
if (entityTypes !== undefined)
form.append("entity_types", JSON.stringify(entityTypes));
form.append("image_policy", imagePolicy);
return form;
} finally {
await source.close();
}
}
function documentBytes(result: PseudonymizeDocumentResponse): Buffer {
const name = result.filename;
const extension = typeof name === "string" ? extname(name).toLowerCase() : "";
if (
typeof name !== "string" ||
!name ||
name !== basename(name) ||
name !== win32.basename(name) ||
[...name].some(
(character) =>
character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127,
) ||
extension === ".pdf" ||
!DOCUMENT_TYPES[extension] ||
result.content_type !== DOCUMENT_TYPES[extension]
) {
throw new Error(
"Backend hat einen ungültigen Office-Dateinamen oder Dateityp geliefert.",
);
}
const encoded = result.file_base64;
if (
typeof encoded !== "string" ||
!encoded ||
encoded.length > Math.ceil(MAX_OUTPUT_BYTES / 3) * 4 ||
encoded.length % 4 !== 0 ||
!/^[A-Za-z0-9+/]*={0,2}$/.test(encoded)
) {
throw new Error("Backend hat ungültige Dokumentdaten geliefert.");
}
const data = Buffer.from(encoded, "base64");
if (
data.length > MAX_OUTPUT_BYTES ||
data.toString("base64") !== encoded ||
!data.subarray(0, 4).equals(Buffer.from("PK\x03\x04", "binary"))
) {
throw new Error("Backend hat kein lesbares Office-Paket geliefert.");
}
return data;
}
export function validateDocumentResponse(
result: PseudonymizeDocumentResponse,
requestedPolicy: ImagePolicy,
): PseudonymizeDocumentResponse {
if (!result || result.image_policy !== requestedPolicy) {
throw new Error(
"Das Backend bestätigt die gewählte Bildbehandlung nicht. Bitte Velum aktualisieren.",
);
}
for (const count of [
result.entity_count,
result.segment_count,
result.images_replaced,
result.images_removed,
result.media_parts_removed,
]) {
if (!Number.isSafeInteger(count) || count < 0)
throw new Error(
"Backend hat keine gültigen Dokument- und Bildzähler geliefert.",
);
}
if (
!Array.isArray(result.warnings) ||
result.warnings.some((item) => typeof item !== "string")
) {
throw new Error("Backend hat keine gültigen Bildwarnungen geliefert.");
}
if (
!result.mapping ||
typeof result.mapping !== "object" ||
Array.isArray(result.mapping) ||
Object.values(result.mapping).some(
(entry) =>
!entry ||
typeof entry.original !== "string" ||
typeof entry.type !== "string",
)
) {
throw new Error("Backend hat keine gültige Zuordnung geliefert.");
}
documentBytes(result);
return {
...result,
warnings:
requestedPolicy === "keep" &&
!result.warnings.includes(KEEP_IMAGE_WARNING)
? [KEEP_IMAGE_WARNING, ...result.warnings]
: result.warnings,
};
}
/** Never overwrite the input or an earlier export, even across concurrent runs. */
export async function saveDocumentCopy(
result: PseudonymizeDocumentResponse,
outputDirectory: string,
): Promise<string> {
const data = documentBytes(result);
const { name, ext } = parse(result.filename);
const temporaryDirectory = await mkdtemp(join(outputDirectory, ".velum-"));
try {
const temporaryFile = join(temporaryDirectory, "document");
await writeFile(temporaryFile, data, { flag: "wx", mode: 0o600 });
for (let index = 0; index < 1000; index++) {
const path = join(
outputDirectory,
index ? `${name} (${index})${ext}` : result.filename,
);
try {
// Publish the finished file atomically and exclusively. An interrupted
// write cannot leave a truncated final document or replace an original.
await link(temporaryFile, path);
return path;
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
}
}
throw new Error(
"Zu viele gleichnamige Ausgabedateien. Bitte einen anderen Ausgabeordner wählen.",
);
} finally {
await rm(temporaryDirectory, { recursive: true, force: true });
}
}

View File

@@ -11,6 +11,9 @@ import {
} from "@raycast/api"; } from "@raycast/api";
import { getSelectedTextSafely } from "./selection"; import { getSelectedTextSafely } from "./selection";
import { useEffect, useMemo, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { dirname } from "node:path";
import { DocumentResult } from "./document-result";
import { saveDocumentCopy } from "./documents";
import { import {
createSession, createSession,
getActiveSessionId, getActiveSessionId,
@@ -19,23 +22,36 @@ import {
setActiveSession, setActiveSession,
updateSessionMapping, updateSessionMapping,
} from "./sessions"; } from "./sessions";
import type { EntityType, PseudonymizeResponse, VelumSession } from "./types"; import type {
EntityType,
ImagePolicy,
PseudonymizeResponse,
VelumSession,
} from "./types";
import { import {
markdownCodeBlock, markdownCodeBlock,
mappingSummary, mappingSummary,
NEW_SESSION_ID, NEW_SESSION_ID,
sessionSubtitle, sessionSubtitle,
} from "./ui"; } from "./ui";
import { getEntityTypes, pseudonymize } from "./velum"; import { getEntityTypes, pseudonymize, pseudonymizeDocument } from "./velum";
type FormValues = { type FormValues = {
text: string; text?: string;
inputMode: "text" | "document";
files?: string[];
outputDirectory?: string[];
imagePolicy?: ImagePolicy;
sessionId: string; sessionId: string;
entityTypes: string[]; entityTypes: string[];
}; };
export default function Command() { export default function Command() {
const [text, setText] = useState(""); const [text, setText] = useState("");
const [inputMode, setInputMode] = useState("text");
const [imagePolicy, setImagePolicy] = useState<ImagePolicy>("placeholder");
const [files, setFiles] = useState<string[]>([]);
const [isSubmitting, setIsSubmitting] = useState(false);
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
@@ -79,6 +95,7 @@ export default function Command() {
}); });
return; return;
} }
setInputMode("text");
setText(selected); setText(selected);
} }
@@ -91,19 +108,26 @@ export default function Command() {
}); });
return; return;
} }
setInputMode("text");
setText(clipboardText); setText(clipboardText);
} }
async function handleSubmit(values: FormValues) { async function handleSubmit(values: FormValues) {
const input = values.text.trim(); if (isSubmitting || isLoading) return;
if (!input) { const isDocument = values.inputMode === "document";
const input = (values.text ?? "").trim();
const filePath = values.files?.[0];
if (isDocument ? !filePath : !input) {
await showToast({ await showToast({
style: Toast.Style.Failure, style: Toast.Style.Failure,
title: "Text zum Pseudonymisieren eingeben", title: isDocument
? "Dokument zum Pseudonymisieren auswählen"
: "Text zum Pseudonymisieren eingeben",
}); });
return; return;
} }
setIsSubmitting(true);
const toast = await showToast({ const toast = await showToast({
style: Toast.Style.Animated, style: Toast.Style.Animated,
title: "Pseudonymisiere…", title: "Pseudonymisiere…",
@@ -115,6 +139,36 @@ export default function Command() {
? await createSession() ? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession())); : ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id); await setActiveSession(session.id);
if (isDocument && filePath) {
const result = await pseudonymizeDocument(
filePath,
session.mapping,
values.entityTypes,
values.imagePolicy ?? "placeholder",
);
const updatedSession = await updateSessionMapping(
session.id,
result.mapping,
values.entityTypes,
);
const path = await saveDocumentCopy(
result,
values.outputDirectory?.[0] ?? dirname(filePath),
);
toast.style = Toast.Style.Success;
toast.title = result.warnings.length
? "Dokument mit Warnhinweis bereit"
: "Dokument pseudonymisiert";
toast.message = `${result.images_replaced} Bilder ersetzt · ${result.images_removed} entfernt`;
push(
<DocumentResult
result={result}
session={updatedSession}
path={path}
/>,
);
return;
}
const result = await pseudonymize( const result = await pseudonymize(
input, input,
session.mapping, session.mapping,
@@ -135,12 +189,14 @@ export default function Command() {
toast.style = Toast.Style.Failure; toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen"; toast.title = "Pseudonymisierung fehlgeschlagen";
toast.message = error instanceof Error ? error.message : String(error); toast.message = error instanceof Error ? error.message : String(error);
} finally {
setIsSubmitting(false);
} }
} }
return ( return (
<Form <Form
isLoading={isLoading} isLoading={isLoading || isSubmitting}
actions={ actions={
<ActionPanel> <ActionPanel>
<Action.SubmitForm <Action.SubmitForm
@@ -161,13 +217,76 @@ export default function Command() {
</ActionPanel> </ActionPanel>
} }
> >
<Form.TextArea <Form.Dropdown
id="text" id="inputMode"
title="Text" title="Eingabe"
value={text} value={inputMode}
onChange={setText} onChange={setInputMode}
placeholder="Zu pseudonymisierender Text" >
/> <Form.Dropdown.Item value="text" title="Text" icon={Icon.Text} />
<Form.Dropdown.Item
value="document"
title="Office-Dokument oder PDF"
icon={Icon.Document}
/>
</Form.Dropdown>
{inputMode === "text" ? (
<Form.TextArea
id="text"
title="Text"
value={text}
onChange={setText}
placeholder="Zu pseudonymisierender Text"
/>
) : (
<>
<Form.FilePicker
id="files"
title="Dokument"
allowMultipleSelection={false}
canChooseDirectories={false}
value={files}
onChange={setFiles}
/>
<Form.Description text="DOCX, XLSX, PPTX oder PDF · maximal 20 MiB. PDF wird als Word-Dokument ausgegeben." />
<Form.Dropdown
id="imagePolicy"
title="Bilder im Dokument"
value={imagePolicy}
onChange={(value) => setImagePolicy(value as ImagePolicy)}
>
<Form.Dropdown.Item
value="placeholder"
title="Datenschutz-Platzhalter (Standard)"
/>
<Form.Dropdown.Item
value="remove"
title="Bilder vollständig entfernen"
/>
<Form.Dropdown.Item
value="keep"
title="Bilder behalten — Datenschutzrisiko"
icon={Icon.Warning}
/>
</Form.Dropdown>
<Form.Description
title={imagePolicy === "keep" ? "Achtung" : "Bildbehandlung"}
text={
imagePolicy === "keep"
? "Bilder können sensible Informationen enthalten. Sie werden unverändert übernommen und nicht auf personenbezogene Daten geprüft."
: "Bildinhalte werden nicht analysiert. Platzhalter behalten Position und Größe soweit möglich bei. Nicht sicher bereinigbare Inhalte werden abgewiesen."
}
/>
<Form.FilePicker
id="outputDirectory"
title="Ausgabeordner"
canChooseFiles={false}
canChooseDirectories
allowMultipleSelection={false}
/>
<Form.Description text="Ohne Ordnerauswahl wird die Kopie neben dem Original gespeichert. Bestehende Dateien werden nicht überschrieben." />
</>
)}
<Form.Dropdown <Form.Dropdown
id="sessionId" id="sessionId"
title="Sitzung" title="Sitzung"

View File

@@ -0,0 +1,335 @@
import {
Action,
ActionPanel,
Clipboard,
Form,
Icon,
showToast,
Toast,
useNavigation,
} from "@raycast/api";
import { useEffect, useMemo, useState } from "react";
import {
type Creativity,
CREATIVITY_OPTIONS,
DEFAULT_MODEL,
getLastUsedModel,
MODEL_OPTIONS,
setLastUsedModel,
STRICT_PLACEHOLDER_RULE,
} from "./ai";
import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import type { EntityType, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import {
getEntityTypes,
normalizePseudonymizeResponse,
pseudonymize,
} from "./velum";
function buildMeetingNotesPrompt(
pseudonymizedText: string,
instructions: string,
): string {
const extra = instructions.trim()
? `\n\nZusätzliche Anweisungen des Nutzers:\n${instructions.trim()}`
: "";
return [
"Du erhältst pseudonymisierte Meeting-Notizen als FLIESSTEXT / PROSA.",
"Personenbezogene Daten wurden bereits durch Platzhalter wie <PERSON_1>, <ORG_2>, <DATE_3>, <EMAIL_4> ersetzt.",
"",
STRICT_PLACEHOLDER_RULE,
"",
"Aufgabe: Verwandle den Fließtext in eine SAUBER STRUKTURIERTE, deutschsprachige Meeting-Zusammenfassung in Markdown.",
"Ziehe Struktur, Verantwortlichkeiten, Entscheidungen und Aufgaben aus der Prosa heraus — verdichte, ohne Inhalte zu erfinden.",
"",
"Verwende GENAU diese Abschnitte in dieser Reihenfolge:",
"",
"## Kontext",
"Ein kurzer Absatz (2–4 Sätze): Worum ging es im Meeting, Anlass, Rahmen. Datum/Ort nur, wenn aus dem Text ableitbar (sonst weglassen).",
"",
"## Teilnehmer",
"- Stichpunktliste der beteiligten Platzhalter, jeweils mit Rolle/Funktion (falls aus dem Text ableitbar).",
"- Format pro Zeile: `- <PERSON_X> — Rolle/Funktion`",
"",
"## Themen & Diskussion",
"Pro behandeltem Thema ein eigener Unter-Absatz:",
"### <Themenbezeichnung in 3–6 Wörtern>",
"Ein kurzer Absatz (2–5 Sätze), der Kernaussagen, Positionen und Argumente verdichtet. Wer hat was gesagt — nur wenn relevant. Keine wörtlichen Zitate, außer sie sind im Quelltext markiert.",
"",
"## Entscheidungen",
"- Eine Stichpunktliste mit jeweils einer klar formulierten Entscheidung pro Zeile.",
"- Nur tatsächlich getroffene Entscheidungen; keine Vorschläge oder Überlegungen.",
"",
"## Action Items",
"Markdown-Tabelle mit GENAU dieser Kopfzeile:",
"| Aufgabe | Verantwortlich | Deadline | Status |",
"| --- | --- | --- | --- |",
"- Status MUSS gesetzt sein, genau einer von: „offen“, „abgeschlossen“. „abgeschlossen“ nur wenn der Text die Erledigung explizit beschreibt.",
"- Verantwortlich als Platzhalter (z. B. <PERSON_1>); wenn nicht ableitbar: „—“.",
"- Deadline nur, wenn ein konkretes Datum/Zeitraum genannt ist; sonst leer lassen. Niemals Deadlines erfinden.",
"- Wenn keine Action Items vorkommen, schreibe stattdessen die einzelne Zeile: „Keine Action Items.“",
"",
"## Offene Punkte",
"- Stichpunktliste der Themen, die NICHT abschließend geklärt wurden bzw. Klärungsbedarf haben.",
"",
"## Nächste Schritte",
"Ein kurzer Absatz (1–3 Sätze): Wie geht es nach diesem Meeting weiter? Nur wenn aus dem Text ableitbar.",
"",
"Regeln:",
'Wenn ein Abschnitt im Text nicht vorkommt, schreibe „—" als einzigen Inhalt darunter.',
"Nichts erfinden, nichts ausschmücken — strikt am Quelltext bleiben.",
"Antworte ausschließlich in Markdown, ohne einleitende Floskeln und ohne umschließende Code-Fences (keine ``` Zeilen am Anfang oder Ende).",
extra,
"",
"--- Meeting-Notizen (pseudonymisiert, Prosa) ---",
pseudonymizedText,
"--- Ende ---",
].join("\n");
}
type FormValues = {
text: string;
sessionId: string;
entityTypes: string[];
model: string;
creativity: Creativity;
instructions: string;
};
export default function Command() {
const [text, setText] = useState("");
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true);
const { push } = useNavigation();
useEffect(() => {
async function load() {
const [loadedSessions, activeId, lastModel] = await Promise.all([
listSessions(),
getActiveSessionId(),
getLastUsedModel(),
]);
setSessions(loadedSessions);
setActiveSessionId(activeId);
setModel(lastModel);
const selection = await getSelectedTextSafely();
if (selection && selection.trim()) {
setText(selection);
}
try {
const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes);
setSelectedEntityTypes(loadedEntityTypes);
} catch {
setEntityTypes([]);
} finally {
setIsLoading(false);
}
}
load();
}, []);
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
await showToast({
style: Toast.Style.Failure,
title: "Kein markierter Text gefunden",
});
return;
}
setText(selected);
}
async function loadClipboardText() {
const clipboardText = await Clipboard.readText();
if (!clipboardText) {
await showToast({
style: Toast.Style.Failure,
title: "Zwischenablage enthält keinen Text",
});
return;
}
setText(clipboardText);
}
async function handleSubmit(values: FormValues) {
const input = values.text.trim();
if (!input) {
await showToast({
style: Toast.Style.Failure,
title: "Meeting-Notizen eingeben",
});
return;
}
void setLastUsedModel(values.model);
const toast = await showToast({
style: Toast.Style.Animated,
title: "Pseudonymisiere…",
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const rawResult = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const pseudoResult = normalizePseudonymizeResponse(rawResult);
const updatedSession = await updateSessionMapping(
session.id,
pseudoResult.mapping,
pseudoResult.selected_entity_types,
);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
toast.message = `${pseudoResult.entity_count} Zuordnungen`;
push(
<PseudonymizationConfirm
session={updatedSession}
pseudonymizedText={pseudoResult.pseudonymized_text}
model={values.model}
creativity={values.creativity}
instructions={values.instructions}
buildPrompt={buildMeetingNotesPrompt}
labels={{
pageHeading: "Meeting-Zusammenfassung",
runningLabel: "KI strukturiert Meeting-Notizen …",
failureTitle: "Zusammenfassung fehlgeschlagen",
copyTitle: "Zusammenfassung kopieren",
pasteTitle: "Zusammenfassung einfügen",
}}
/>,
);
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen";
toast.message = error instanceof Error ? error.message : String(error);
}
}
return (
<Form
isLoading={isLoading}
actions={
<ActionPanel>
<Action.SubmitForm
title="Meeting-Notizen strukturieren"
icon={Icon.Document}
onSubmit={handleSubmit}
/>
<Action
title="Markierten Text übernehmen"
icon={Icon.TextSelection}
onAction={loadSelectedText}
/>
<Action
title="Zwischenablage übernehmen"
icon={Icon.Clipboard}
onAction={loadClipboardText}
/>
</ActionPanel>
}
>
<Form.TextArea
id="text"
title="Meeting-Notizen (Prosa)"
value={text}
onChange={setText}
placeholder="Meeting-Notizen als Fließtext einfügen — z. B. handgeschriebene Protokollnotizen, ein diktiertes Transkript oder ein zusammenhängender Bericht."
/>
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"
title="Entitätstypen"
value={selectedEntityTypes}
onChange={setSelectedEntityTypes}
>
{entityTypes.map((entityType) => (
<Form.TagPicker.Item
key={entityType}
value={entityType}
title={entityType}
/>
))}
</Form.TagPicker>
) : null}
<Form.Dropdown
id="model"
title="KI-Modell"
value={model}
onChange={setModel}
>
{MODEL_OPTIONS.map((option) => (
<Form.Dropdown.Item
key={option.value}
value={option.value}
title={option.title}
/>
))}
</Form.Dropdown>
<Form.Dropdown id="creativity" title="Kreativität" defaultValue="low">
{CREATIVITY_OPTIONS.map((value) => (
<Form.Dropdown.Item key={value} value={value} title={value} />
))}
</Form.Dropdown>
<Form.TextArea
id="instructions"
title="Zusätzliche Anweisungen"
placeholder="Optional: Fokus auf bestimmte Themen, Tonalität, Zielpublikum (z. B. „für Lenkungsausschuss verdichten“), …"
/>
</Form>
);
}

View File

@@ -27,6 +27,22 @@ export type DepseudonymizeResponse = {
replacements_made: number; replacements_made: number;
}; };
export type ImagePolicy = "placeholder" | "remove" | "keep";
export type PseudonymizeDocumentResponse = {
filename: string;
content_type: string;
file_base64: string;
mapping: PlaceholderMapping;
entity_count: number;
segment_count: number;
image_policy: ImagePolicy;
images_replaced: number;
images_removed: number;
media_parts_removed: number;
warnings: string[];
};
export type VelumSession = { export type VelumSession = {
id: string; id: string;
name: string; name: string;

View File

@@ -1,10 +1,13 @@
import { fetchWithAuth } from "./auth"; import { fetchWithAuth } from "./auth";
import { getPreferences } from "./preferences"; import { getPreferences } from "./preferences";
import { documentForm, validateDocumentResponse } from "./documents";
import type { import type {
DepseudonymizeResponse, DepseudonymizeResponse,
EntityType, EntityType,
PlaceholderMapping, PlaceholderMapping,
PseudonymizeResponse, PseudonymizeResponse,
ImagePolicy,
PseudonymizeDocumentResponse,
} from "./types"; } from "./types";
function escapeRegExp(value: string): string { function escapeRegExp(value: string): string {
@@ -142,3 +145,31 @@ export async function depseudonymize(
return parseJsonResponse<DepseudonymizeResponse>(response); return parseJsonResponse<DepseudonymizeResponse>(response);
} }
export async function pseudonymizeDocument(
filePath: string,
mapping: PlaceholderMapping,
entityTypes?: EntityType[],
imagePolicy: ImagePolicy = "placeholder",
): Promise<PseudonymizeDocumentResponse> {
const capabilitiesResponse = await fetchWithAuth(
apiUrl("/api/project-capabilities"),
);
const capabilities = await parseJsonResponse<{
document_image_policy?: boolean;
}>(capabilitiesResponse);
if (capabilities.document_image_policy !== true) {
throw new Error(
"Das Backend unterstützt die Bildbehandlung noch nicht. Bitte Velum aktualisieren.",
);
}
const body = await documentForm(filePath, mapping, entityTypes, imagePolicy);
const response = await fetchWithAuth(apiUrl("/api/pseudonymize-document"), {
method: "POST",
body,
});
return validateDocumentResponse(
await parseJsonResponse<PseudonymizeDocumentResponse>(response),
imagePolicy,
);
}

259
tests/documents.test.cjs Normal file
View File

@@ -0,0 +1,259 @@
const assert = require("node:assert/strict");
const { readFileSync } = require("node:fs");
const {
mkdtemp,
readFile,
readdir,
rm,
stat,
truncate,
writeFile,
} = require("node:fs/promises");
const { tmpdir } = require("node:os");
const { join } = require("node:path");
const test = require("node:test");
const ts = require("typescript");
// Exercise the real transport/file helpers with native Node FormData and File,
// replacing only Raycast's credentials/preferences boundary.
function loadTs(name, mocks = {}) {
const file = join(__dirname, "../src", name + ".ts");
const source = ts.transpileModule(readFileSync(file, "utf8"), {
compilerOptions: {
module: ts.ModuleKind.CommonJS,
target: ts.ScriptTarget.ES2023,
esModuleInterop: true,
},
}).outputText;
const module = { exports: {} };
new Function("require", "module", "exports", source)(
(id) => mocks[id] ?? require(id),
module,
module.exports,
);
return module.exports;
}
const documents = loadTs("documents");
const bytes = Buffer.from("PK\x03\x04pseudonymized-package");
const mapping = { PERSON_01: { original: "Testperson", type: "PERSON" } };
function result(policy = "placeholder", changes = {}) {
return {
filename: "bericht.pseudonymisiert.docx",
content_type: documents.DOCUMENT_TYPES[".docx"],
file_base64: bytes.toString("base64"),
mapping,
entity_count: 1,
segment_count: 4,
image_policy: policy,
images_replaced: policy === "placeholder" ? 2 : 0,
images_removed: policy === "remove" ? 2 : 0,
media_parts_removed: policy === "keep" ? 0 : 3,
warnings: [],
...changes,
};
}
function json(body, status = 200) {
return Response.json(body, { status });
}
function client(fetchWithAuth) {
return loadTs("velum", {
"./auth": { fetchWithAuth },
"./preferences": {
getPreferences: () => ({ velumBaseUrl: "https://velum.test" }),
},
"./documents": documents,
});
}
async function fixture(t, extension = ".docx") {
const directory = await mkdtemp(join(tmpdir(), "velum-raycast-documents-"));
t.after(() => rm(directory, { recursive: true, force: true }));
const path = join(directory, "Quelle" + extension);
await writeFile(path, "original image and text");
return { directory, path };
}
for (const extension of [".docx", ".xlsx", ".pptx", ".pdf"]) {
test(`document form preserves bytes and defaults to placeholder for ${extension}`, async (t) => {
const { path } = await fixture(t, extension);
const form = await documents.documentForm(path, mapping, []);
assert.equal(form.get("image_policy"), "placeholder");
assert.equal(form.get("entity_types"), "[]");
assert.deepEqual(JSON.parse(form.get("mapping")), mapping);
const file = form.get("file");
assert.equal(file.name, "Quelle" + extension);
assert.equal(file.type, documents.DOCUMENT_TYPES[extension]);
assert.equal(await file.text(), "original image and text");
});
}
for (const policy of ["placeholder", "remove", "keep"]) {
test(`authenticated document flow sends and confirms ${policy}`, async (t) => {
const { directory, path } = await fixture(t);
const calls = [];
const api = client(async (url, init) => {
calls.push(url);
if (url.endsWith("/api/project-capabilities"))
return json({ document_image_policy: true });
assert.equal(init.method, "POST");
assert.equal(init.headers, undefined); // fetch must set the multipart boundary
assert.equal(init.body.get("image_policy"), policy);
assert.deepEqual(JSON.parse(init.body.get("entity_types")), ["PERSON"]);
assert.equal(
await init.body.get("file").text(),
"original image and text",
);
return json(result(policy));
});
const response = await api.pseudonymizeDocument(
path,
mapping,
["PERSON"],
policy,
);
assert.deepEqual(calls, [
"https://velum.test/api/project-capabilities",
"https://velum.test/api/pseudonymize-document",
]);
assert.equal(response.image_policy, policy);
assert.equal(
response.warnings.includes(documents.KEEP_IMAGE_WARNING),
policy === "keep",
);
const saved = await documents.saveDocumentCopy(response, directory);
assert.deepEqual(await readFile(saved), bytes);
assert.equal(await readFile(path, "utf8"), "original image and text");
});
}
test("API defaults to placeholder when the caller omits the option", async (t) => {
const { path } = await fixture(t);
const api = client(async (url, init) => {
if (url.endsWith("capabilities"))
return json({ document_image_policy: true });
assert.equal(init.body.get("image_policy"), "placeholder");
return json(result());
});
await api.pseudonymizeDocument(path, {});
});
test("old backend is rejected before uploading document data", async (t) => {
const { path, directory } = await fixture(t);
const calls = [];
const api = client(async (url) => {
calls.push(url);
return json({ document_hit_review: true });
});
await assert.rejects(api.pseudonymizeDocument(path, {}), /aktualisieren/);
assert.deepEqual(calls, ["https://velum.test/api/project-capabilities"]);
assert.deepEqual(await readdir(directory), ["Quelle.docx"]);
});
test("missing or mismatched policy confirmation and HTTP 422 fail closed", async (t) => {
const { path, directory } = await fixture(t);
for (const response of [
json(result("keep")),
json(result(undefined, { image_policy: undefined })),
json({ detail: "Office-Datei kann nicht sicher bereinigt werden." }, 422),
]) {
const api = client(async (url) =>
url.endsWith("capabilities")
? json({ document_image_policy: true })
: response,
);
await assert.rejects(api.pseudonymizeDocument(path, {}));
}
assert.deepEqual(await readdir(directory), ["Quelle.docx"]);
});
test("invalid files, image options and upload sizes are rejected", async (t) => {
const { path, directory } = await fixture(t);
await assert.rejects(
documents.documentForm(path, {}, [], "unknown"),
/Bildbehandlung/,
);
await assert.rejects(
documents.documentForm(join(directory, "report.doc"), {}),
/DOCX/,
);
await writeFile(path, "");
await assert.rejects(documents.documentForm(path, {}), /nicht leere/);
await truncate(path, 20 * 1024 * 1024 + 1);
await assert.rejects(documents.documentForm(path, {}), /zu groß/);
});
test("unsafe or incomplete backend results cannot become output files", async (t) => {
const { directory } = await fixture(t);
for (const changes of [
{ filename: "../Original.docx" },
{ filename: "..\\Original.docx" },
{ filename: "report.pdf" },
{ content_type: "text/html" },
{ file_base64: "%%%%" },
{ file_base64: Buffer.from("not an office file").toString("base64") },
{ images_replaced: -1 },
{ images_removed: undefined },
{ warnings: undefined },
{ mapping: { PERSON_01: { type: "PERSON" } } },
]) {
assert.throws(() =>
documents.validateDocumentResponse(
result("placeholder", changes),
"placeholder",
),
);
}
await assert.rejects(
documents.saveDocumentCopy(
result("placeholder", { filename: "../Original.docx" }),
directory,
),
);
assert.deepEqual(await readdir(directory), ["Quelle.docx"]);
});
test("concurrent exports cannot overwrite the original or earlier copies", async (t) => {
const { path, directory } = await fixture(t);
const response = result("placeholder", { filename: "Quelle.docx" });
const paths = await Promise.all(
Array.from({ length: 5 }, () =>
documents.saveDocumentCopy(response, directory),
),
);
assert.equal(new Set(paths).size, 5);
assert.equal(await readFile(path, "utf8"), "original image and text");
for (const exported of paths) {
assert.deepEqual(await readFile(exported), bytes);
assert.equal((await stat(exported)).mode & 0o777, 0o600);
}
assert.equal((await readdir(directory)).length, 6); // no temporary directories remain
});
test("failed export publishes no partial document and removes temporary data", async (t) => {
const { directory } = await fixture(t);
const broken = loadTs("documents", {
"node:fs/promises": {
...require("node:fs/promises"),
writeFile: async (path) => {
await writeFile(path, "partial");
throw new Error("simulated disk failure");
},
},
});
await assert.rejects(
broken.saveDocumentCopy(result(), directory),
/disk failure/,
);
assert.deepEqual(await readdir(directory), ["Quelle.docx"]);
});
test("keep always displays an image warning while preserving backend warnings", () => {
const response = documents.validateDocumentResponse(
result("keep", { warnings: ["Backend-Hinweis"] }),
"keep",
);
assert.deepEqual(response.warnings, [
documents.KEEP_IMAGE_WARNING,
"Backend-Hinweis",
]);
});