4 Commits

Author SHA1 Message Date
muena
b845062824 feat: add custom terms and consolidate session management
Show exact matches in red and add categorized custom terms to hit review. Move session administration into the translation tables command.
2026-12-02 10:18:43 +01:00
muena
b630093075 feat: load available AI models from Raycast 2026-12-02 08:53:37 +01:00
muena
019f6b6d7c feat: improve Velum hit review and session creation 2026-12-02 08:53:37 +01:00
96d5f3f57d Merge pull request 'Velum Raycast: Standard-Typen alle außer IP, Datum, Referenz (agent/default-entity-types)' (#2) from paperclip-bot/velum-raycast:agent/default-entity-types into main
Reviewed-on: r.muellner/velum-raycast#2
2026-12-01 06:14:22 +00:00
33 changed files with 1012 additions and 567 deletions

View File

@@ -141,7 +141,7 @@ Alle Werte sind in den Raycast-Einstellungen pro Extension einstellbar.
- `Ausgabe der Schnellbefehle` — `In die Zwischenablage kopieren` (Default) oder `Am Cursor einfügen`
- `Eigener Name` — Default-Signatur für AI-generierte Email-Antworten, im Antwort-Befehl pro Aufruf überschreibbar
Das KI-Modell ist keine Preference: jeder AI-Befehl zeigt ein `KI-Modell`-Dropdown mit dem aktuellen Modell-Katalog aus `src/ai.ts`. Die Auswahl wird in `LocalStorage` (`velum.ai.last-model`) persistiert und ist beim nächsten Aufruf in jedem AI-Befehl vorausgewählt.
Jeder KI-Befehl bezieht die Auswahl im Feld **KI-Modell** aus `AI.Model` der installierten Raycast-Version. Mit **Raycast-Standard** verwendet Velum das Standardmodell der Raycast-API. Velum merkt sich die letzte Auswahl für alle KI-Befehle. Fehlt das gespeicherte Modell im API-Katalog, ist beim nächsten Aufruf **Raycast-Standard** ausgewählt.
- `Maximale Anzahl gespeicherter Sitzungen` — älteste werden geprunt (Default 20)
- `Raycast nach Kopieren/Einfügen schließen` — Auto-Close und Pop-To-Root nach AI-Workflow-Abschluss (Default an)
@@ -174,7 +174,7 @@ Jeder AI-Befehl pseudonymisiert die Eingabe via Velum, zeigt einen Confirm-Schri
### Sitzungen
- `Sitzungen verwalten` — Sitzungen anlegen, aktivieren, ansehen, leeren oder löschen. Zeigt das Mapping je Sitzung als Markdown-Tabelle.
- **Übersetzungstabellen anzeigen → Sitzungen** — Sitzungen anlegen, umbenennen, aktivieren oder löschen. Die Übersetzungstabelle jeder Sitzung zeigt ihre Zuordnungen und bietet die Personenzusammenführung.
## Sitzungen

View File

@@ -104,13 +104,7 @@
{
"name": "show-translation-tables",
"title": "Übersetzungstabellen anzeigen",
"description": "Gespeicherte Zuordnungen je Projekt oder Sitzung durchsuchen.",
"mode": "view"
},
{
"name": "manage-sessions",
"title": "Sitzungen verwalten",
"description": "Velum-Sitzungen mit Zuordnungen anlegen, aktivieren, ansehen und löschen.",
"description": "Projekt- und Sitzungszuordnungen bearbeiten, Personen zusammenfassen und Sitzungen verwalten.",
"mode": "view"
},
{

View File

@@ -15,7 +15,7 @@ import {
} from "@raycast/api";
import { marked } from "marked";
import { type ReactNode, useEffect, useRef, useState } from "react";
import type { Creativity } from "./ai";
import { resolveRaycastModel, type Creativity } from "./ai";
import { getPreferences } from "./preferences";
import type { VelumSession } from "./types";
import { markdownCodeBlock, mappingDetailTable, sessionSubtitle } from "./ui";
@@ -143,7 +143,7 @@ export function AiStreamResult(props: PseudoStageProps) {
try {
const prompt = buildPrompt(pseudonymizedText, instructions);
const stream = AI.ask(prompt, {
model: model as AI.Model,
model: resolveRaycastModel(model),
creativity,
signal: controller.signal,
});

View File

@@ -1,4 +1,4 @@
import { LocalStorage } from "@raycast/api";
import { AI, LocalStorage } from "@raycast/api";
export type Creativity = "none" | "low" | "medium" | "high";
@@ -9,86 +9,29 @@ export const CREATIVITY_OPTIONS: Creativity[] = [
"high",
];
export type ModelOption = { value: string; title: string };
export const MODEL_OPTIONS: ModelOption[] = [
{ value: "anthropic-claude-opus-4-7", title: "Claude 4.7 Opus" },
{ value: "anthropic-claude-sonnet-4-6", title: "Claude 4.6 Sonnet" },
{ value: "anthropic-claude-opus-4-6", title: "Claude 4.6 Opus" },
{ value: "anthropic-claude-sonnet-4-5", title: "Claude 4.5 Sonnet" },
{ value: "anthropic-claude-opus-4-5", title: "Claude 4.5 Opus" },
{ value: "anthropic-claude-4-5-haiku", title: "Claude 4.5 Haiku" },
{ value: "anthropic-claude-sonnet-4", title: "Claude 4 Sonnet" },
{ value: "openai-gpt-5.4", title: "OpenAI GPT-5.4" },
{ value: "openai-gpt-5.4-mini", title: "OpenAI GPT-5.4 Mini" },
{ value: "openai-gpt-5.4-nano", title: "OpenAI GPT-5.4 Nano" },
{ value: "openai-gpt-5.3-instant", title: "OpenAI GPT-5.3 Instant" },
{ value: "openai-gpt-5.3-codex", title: "OpenAI GPT-5.3 Codex" },
{ value: "openai-gpt-5.2", title: "OpenAI GPT-5.2" },
{ value: "openai-gpt-5.2-instant", title: "OpenAI GPT-5.2 Instant" },
{ value: "openai-gpt-5.1", title: "OpenAI GPT-5.1" },
{ value: "openai-gpt-5.1-instant", title: "OpenAI GPT-5.1 Instant" },
{ value: "openai-gpt-5.1-codex", title: "OpenAI GPT-5.1 Codex" },
{ value: "openai_o1-gpt-5", title: "OpenAI GPT-5" },
{ value: "openai-gpt-5-mini", title: "OpenAI GPT-5 Mini" },
{ value: "openai-gpt-5-nano", title: "OpenAI GPT-5 Nano" },
{ value: "openai-gpt-4.1", title: "OpenAI GPT-4.1" },
{ value: "openai-gpt-4.1-mini", title: "OpenAI GPT-4.1 Mini" },
{ value: "openai-gpt-4.1-nano", title: "OpenAI GPT-4.1 Nano" },
{ value: "openai-gpt-4o", title: "OpenAI GPT-4o" },
{ value: "openai-gpt-4o-mini", title: "OpenAI GPT-4o mini" },
{ value: "openai_o1-o3", title: "OpenAI o3" },
{ value: "openai_o1-o3-mini", title: "OpenAI o3-mini" },
{ value: "openai_o1-o4-mini", title: "OpenAI o4-mini" },
{ value: "openai_o1-o1", title: "OpenAI o1" },
{ value: "google-gemini-3.1-pro", title: "Google Gemini 3.1 Pro" },
{ value: "google-gemini-3-flash", title: "Google Gemini 3 Flash" },
{
value: "google-gemini-3.1-flash-lite",
title: "Google Gemini 3.1 Flash Lite",
},
{ value: "google-gemini-2.5-pro", title: "Google Gemini 2.5 Pro" },
{ value: "google-gemini-2.5-flash", title: "Google Gemini 2.5 Flash" },
{
value: "google-gemini-2.5-flash-lite",
title: "Google Gemini 2.5 Flash Lite",
},
{ value: "xai-grok-4.20", title: "xAI Grok 4.20" },
{ value: "xai-grok-4", title: "xAI Grok 4" },
{ value: "xai-grok-4-fast", title: "xAI Grok 4 Fast" },
{ value: "xai-grok-4-1-fast", title: "xAI Grok 4.1 Fast" },
{ value: "xai-grok-code-fast", title: "xAI Grok Code Fast" },
{ value: "perplexity-sonar-pro", title: "Perplexity Sonar Pro" },
{ value: "perplexity-sonar", title: "Perplexity Sonar" },
{ value: "mistral-mistral-large-latest", title: "Mistral Large" },
{ value: "mistral-mistral-medium-latest", title: "Mistral Medium" },
{ value: "mistral-mistral-small-latest", title: "Mistral Small" },
{ value: "mistral-codestral-latest", title: "Mistral Codestral" },
{ value: "mistral-open-mistral-nemo", title: "Mistral Nemo" },
{ value: "groq-llama-3.3-70b-versatile", title: "Groq Llama 3.3 70B" },
{
value: "groq-meta-llama/llama-4-scout-17b-16e-instruct",
title: "Groq Llama 4 Scout",
},
{ value: "groq-llama-3.1-8b-instant", title: "Groq Llama 3.1 8B" },
{ value: "groq-qwen/qwen3-32b", title: "Groq Qwen3 32B" },
{ value: "groq-openai/gpt-oss-120b", title: "Groq GPT-OSS 120B" },
{ value: "groq-openai/gpt-oss-20b", title: "Groq GPT-OSS 20B" },
{ value: "together-deepseek-ai/DeepSeek-R1", title: "DeepSeek R1" },
{ value: "together-deepseek-ai/DeepSeek-V3", title: "DeepSeek V3" },
{ value: "together-moonshotai/Kimi-K2.5", title: "Kimi K2.5" },
];
export const DEFAULT_MODEL = "__raycast_default__";
const LAST_MODEL_STORAGE_KEY = "velum.ai.last-model";
export const DEFAULT_MODEL: string = MODEL_OPTIONS[0].value;
// Raycast lists current names before compatibility aliases for the same model ID.
const raycastModels = new Map<string, { value: AI.Model; title: string }>();
for (const [name, value] of Object.entries(AI.Model)) {
if (!raycastModels.has(value)) {
raycastModels.set(value, { value, title: name.replaceAll("_", " ") });
}
}
export const MODEL_OPTIONS = [
{ value: DEFAULT_MODEL, title: "Raycast-Standard" },
...raycastModels.values(),
];
export function resolveRaycastModel(selection: string): AI.Model | undefined {
return raycastModels.get(selection)?.value;
}
export async function getLastUsedModel(): Promise<string> {
const stored = await LocalStorage.getItem<string>(LAST_MODEL_STORAGE_KEY);
if (stored && MODEL_OPTIONS.some((option) => option.value === stored)) {
return stored;
}
return DEFAULT_MODEL;
return stored && raycastModels.has(stored) ? stored : DEFAULT_MODEL;
}
export async function setLastUsedModel(model: string): Promise<void> {

View File

@@ -158,7 +158,7 @@ export default function Command() {
toast.style = Toast.Style.Success;
toast.title = "Treffer zur Prüfung bereit";
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(
<PseudonymizationConfirm
session={updatedSession}

View File

@@ -52,6 +52,8 @@ export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId
icon={session.id === props.activeSessionId ? Icon.CheckCircle : Icon.Circle} />)}
<Form.Dropdown.Item value={NEW_SESSION_ID} title="Neue Sitzung" icon={Icon.Plus} />
</Form.Dropdown>
{selected === NEW_SESSION_ID && <Form.TextField id="newSessionName" title="Sitzungsname"
placeholder="Leer lassen für einen automatisch vergebenen Namen" />}
{selected === NEW_PROJECT_ID && <Form.FilePicker id="newProjectPath" title="Projektordner"
allowMultipleSelection={false} canChooseDirectories canChooseFiles={false} />}
</>;

View File

@@ -3,5 +3,6 @@ export const NEW_PROJECT_ID = "__new_project__";
export type ContextFormValues = {
sessionId: string;
newSessionName?: string;
newProjectPath?: string[];
};

75
src/custom-term-form.tsx Normal file
View File

@@ -0,0 +1,75 @@
import {
Action,
ActionPanel,
Form,
showToast,
Toast,
useNavigation,
} from "@raycast/api";
import { useState } from "react";
import { validCustomTerm } from "./lib/velum-project";
import type { CustomTerm, EntityType } from "./types";
export function CustomTermForm(props: {
entityTypes: EntityType[];
onAdd: (term: CustomTerm) => void | Promise<void>;
}) {
const { pop } = useNavigation();
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string>();
async function submit({ type, value }: CustomTerm) {
if (busy) return;
const term = value.trim().replace(/\s+/gu, " ");
if (!validCustomTerm(term)) {
setError("Bitte einen Begriff mit 2 bis 200 Zeichen eingeben.");
return;
}
if (!props.entityTypes.includes(type)) return;
setBusy(true);
try {
await props.onAdd({ type, value: term });
pop();
} catch (error) {
await showToast({
style: Toast.Style.Failure,
title: "Begriff konnte nicht hinzugefügt werden",
message: error instanceof Error ? error.message : String(error),
});
} finally {
setBusy(false);
}
}
return (
<Form
navigationTitle="Eigenen Begriff hinzufügen"
isLoading={busy}
actions={
<ActionPanel>
<Action.SubmitForm title="Begriff hinzufügen" onSubmit={submit} />
</ActionPanel>
}
>
<Form.TextField
id="value"
title="Begriff"
error={error}
onChange={() => setError(undefined)}
/>
<Form.Dropdown
id="type"
title="Kategorie"
defaultValue={
props.entityTypes.includes("BEGRIFF")
? "BEGRIFF"
: props.entityTypes[0]
}
>
{props.entityTypes.map((type) => (
<Form.Dropdown.Item key={type} value={type} title={type} />
))}
</Form.Dropdown>
</Form>
);
}

View File

@@ -163,7 +163,7 @@ export default function Command() {
toast.style = Toast.Style.Success;
toast.title = "Treffer zur Prüfung bereit";
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(
<PseudonymizationConfirm
session={updatedSession}

View File

@@ -191,7 +191,7 @@ export default function Command() {
toast.style = Toast.Style.Success;
toast.title = "Treffer zur Prüfung bereit";
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
const schema = values.schema;
const format = values.format;
const buildPrompt = (pseudonymizedText: string, instructions: string) =>

View File

@@ -90,9 +90,11 @@ export async function inspectDocx(
const begin = span.start - start;
const end = span.end - start;
if (begin < 0 || end > characters.length) throw new Error("DOCX-Treffer überschreitet sein Segment.");
const snippetStart = Math.max(0, begin - 60);
hits.push({ ...span, start: begin, end, segment: segmentIndex,
id: `${relative}:local-docx:${segmentIndex}:${begin}:${end}`, file: relative, source: segment.source,
context: characters.slice(Math.max(0, begin - 60), end + 60).join(""), kind: "content" });
context: characters.slice(snippetStart, end + 60).join(""),
contextOffset: characters.slice(snippetStart, begin).join("").length, kind: "content" });
}
start += characters.length + 2;
}

View File

@@ -257,7 +257,7 @@ export async function analyzeProjectTexts(
return { mapping: current, spansByFile };
}
export type StreamTextSpan = TextSpan & { context: string };
export type StreamTextSpan = TextSpan & { context: string; contextOffset: number };
/** Analyze complete-line parts lazily, sharing small requests across file boundaries. */
export async function analyzeProjectTextFiles(
@@ -290,8 +290,9 @@ export async function analyzeProjectTextFiles(
const end = part.scanStart + positions[span.end];
if (start < part.coreStart || start >= part.coreEnd) continue;
// Copy the short snippet, allowing the request's source string to be freed.
const context = Buffer.from(part.text.slice(Math.max(0, positions[span.start] - 70), positions[span.end] + 70), "utf8").toString("utf8");
spansByFile.get(part.file)!.push({ ...span, start, end, context });
const snippetStart = Math.max(0, positions[span.start] - 70);
const context = Buffer.from(part.text.slice(snippetStart, positions[span.end] + 70), "utf8").toString("utf8");
spansByFile.get(part.file)!.push({ ...span, start, end, context, contextOffset: positions[span.start] - snippetStart });
}
}
}

View File

@@ -121,6 +121,65 @@ export function groupReviewHits<T extends GroupableHit>(hits: T[]): ReviewGroup<
return [...groups.values()].sort((a, b) => a.type.localeCompare(b.type) || a.original.localeCompare(b.original));
}
/** Render source text literally, even if it contains Markdown or HTML. */
export function literalReviewContext(text: string): string {
let longestRun = 2;
for (const [run] of text.matchAll(/`+/g)) longestRun = Math.max(longestRun, run.length);
const fence = "`".repeat(longestRun + 1);
return `${fence}\n${text}\n${fence}`;
}
function escapeReviewMarkdown(text: string): string {
return text.replace(/[^\p{L}\p{M}\p{N} \r\n]/gu, (character) => `&#${character.codePointAt(0)};`)
.replace(/ {2,}/g, (spaces) => " " + "&#160;".repeat(spaces.length - 1))
.replace(/\r\n?|\n/g, " \n");
}
const latexTextEscapes: Record<string, string> = {
"\\": "\\textbackslash{}", "~": "\\textasciitilde{}", "^": "\\textasciicircum{}",
"{": "\\{", "}": "\\}", "%": "\\%", "$": "\\$", "&": "\\&", "#": "\\#", "_": "\\_",
"-": "{-}", " ": "\\ ", "\t": "\\ \\ \\ \\ ",
"'": "\\texttt{'}", "`": "\\texttt{`}",
};
/** Raycast renders inline LaTeX with color support in its Markdown detail views. */
export function highlightedReviewContext(text: string, start: number, length: number): string {
const end = start + length;
if (!Number.isInteger(start) || !Number.isInteger(length) || start < 0 || length <= 0 || end > text.length) {
return literalReviewContext(text);
}
const before = escapeReviewMarkdown(text.slice(0, start));
const match = text.slice(start, end).split(/\r\n?|\n/).map((line) => {
if (!line) return "";
const literal = line.replace(/[\\~^{}%$&#_ \t'`-]/g, (character) => latexTextEscapes[character]);
return String.raw`\(\textcolor{#dc2626}{\text{${literal}}}\)`;
}).join(" \n");
return before + match + escapeReviewMarkdown(text.slice(end));
}
/** Text API positions count Unicode code points. Mark the exact occurrence in each snippet. */
export function textHitContexts(text: string, spans: Array<{ start: number; end: number }>): string[] {
const characters = Array.from(text);
const contexts: string[] = [];
let cursor = 0;
let line = 1;
for (const { span, index } of spans.map((span, index) => ({ span, index })).sort((a, b) => a.span.start - b.span.start)) {
const { start, end } = span;
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start >= end || end > characters.length) {
contexts[index] = "Ungültige Trefferposition der Velum-API.";
continue;
}
for (; cursor < start; cursor++) {
if (characters[cursor] === "\n" || (characters[cursor] === "\r" && characters[cursor + 1] !== "\n")) line++;
}
const before = characters.slice(Math.max(0, start - 90), start).join("");
const match = characters.slice(start, end).join("");
const after = characters.slice(end, end + 90).join("");
contexts[index] = `**Zeile ${line}**\n\n${highlightedReviewContext(before + match + after, before.length, match.length)}`;
}
return contexts;
}
export function withoutWhitelistedHits<T extends GroupableHit>(hits: T[], whitelist: ProjectWhitelistEntry[]): T[] {
const excluded = new Set(whitelist.map(whitelistKey));
return hits.filter((hit) => !excluded.has(whitelistKey(hit)));

View File

@@ -114,6 +114,7 @@ export async function reviseProjectRun(args: {
run.origin = previous.origin;
run.revisedFrom = previous.id;
run.entityTypes = previous.entityTypes ? [...previous.entityTypes] : undefined;
run.customTermCoverage = previous.customTermCoverage;
run.commentAuthorCoverage = previous.commentAuthorCoverage;
run.reviewAuthorCoverage = previous.reviewAuthorCoverage;
run.mapping = plan.mapping;

View File

@@ -23,14 +23,14 @@ import { inspectDocx, writeDocx } from "./local-docx";
export type Hit = {
id: string; file: string; source: string; original: string; placeholder: string;
type: string; score: number; context: string; start: number; end: number;
kind: "content" | "path"; segment?: number;
kind: "content" | "path"; segment?: number; contextOffset?: number;
};
type Draft = { file: ProjectFile; hash: string; hits: Hit[]; analysisMapping?: PlaceholderMapping; docxSegmentCount?: number };
type PathDraft = { key: string; value: string; hits: Hit[] };
export type Preview = { drafts: Draft[]; retained: Array<{ file: ProjectFile; hash: string; output: string; directory: string; imageReport?: DocumentImageReport; localDocx?: true }>;
baseRunId?: string; paths: PathDraft[]; mapping: PlaceholderMapping; previousMapping: PlaceholderMapping;
matchModes?: Record<string, "token" | "anywhere">; hits: Hit[]; entityTypes: EntityType[];
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy };
skipped: SkippedProjectFile[]; sourceInPlace: boolean; imagePolicy: ImagePolicy; customTermCoverage?: string };
function isLocalDocx(file: ProjectFile): boolean {
return file.kind === "document" && extname(file.relPath).toLowerCase() === ".docx";
@@ -44,6 +44,7 @@ function isUnreadableDocument(error: unknown): boolean {
function documentHits(file: ProjectFile, hits: DocumentHit[]): Hit[] {
return hits.map((hit) => ({ ...hit, id: `${file.relPath}:document:${hit.id}`,
contextOffset: Array.from(hit.context).slice(0, Math.min(60, hit.start)).join("").length,
file: file.relPath, kind: "content" as const }));
}
@@ -69,6 +70,8 @@ export async function prepareProject(assets: string, root: string, files: Projec
const latestEntry = (await listRuns(root))[0];
const latest = latestEntry?.run;
const categoryCoverageChanged = Boolean(latest && !sameEntityTypeCoverage(latest, entityTypes));
const customTermCoverage = rules.length ? digest(Buffer.from(JSON.stringify(rules))) : undefined;
const customTermsChanged = latest?.customTermCoverage !== customTermCoverage;
if (categoryCoverageChanged) onProgress("Kategorien geändert oder alter Stand: Dateien erneut analysieren");
const previousMapping: PlaceholderMapping = latest?.mapping ?? {};
const previousPlaceholders = Object.keys(previousMapping);
@@ -89,7 +92,7 @@ export async function prepareProject(assets: string, root: string, files: Projec
continue;
}
const imageCoverageMatches = file.kind !== "document" || sameImagePolicyCoverage(latest, imagePolicy);
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && imageCoverageMatches && latest && previousDirectory
const previousOutput = !reanalyzeUnchanged && !categoryCoverageChanged && !customTermsChanged && imageCoverageMatches && latest && previousDirectory
? await reusableProjectOutput(latest, previousDirectory, file.relPath, hash) : undefined;
const previousFile = latest?.files.find((saved) => saved.output === previousOutput);
if (previousOutput && previousDirectory && (!isLocalDocx(file) || previousFile?.localDocx)) {
@@ -177,7 +180,7 @@ export async function prepareProject(assets: string, root: string, files: Projec
const found = toUtf16Offsets(segment.text, spans.get(path.key) ?? []).map((span, hitIndex) => ({
...span, id: `${path.key}:path:${hitIndex}`, file: path.key,
source: "Datei- oder Ordnername", kind: "path" as const,
context: path.value,
context: path.value, contextOffset: span.start,
}));
path.hits = withoutWhitelistedHits(withoutPlaceholderHits(found, previousPlaceholders), whitelist);
for (const hit of path.hits) hits.push(hit);
@@ -185,7 +188,7 @@ export async function prepareProject(assets: string, root: string, files: Projec
}
}
return { drafts, retained, paths, mapping, previousMapping, baseRunId: latest?.id,
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy };
matchModes: latest?.matchModes, hits, entityTypes, skipped, sourceInPlace, imagePolicy, customTermCoverage };
}
function outputPath(relPath: string, paths: PathDraft[], accepted: Set<string>, document: boolean,
@@ -236,6 +239,7 @@ export async function applyProject(
run.mapping = mappingForSelection(preview.mapping, preview.previousMapping,
acceptedHits, activeMerges);
run.entityTypes = [...preview.entityTypes];
run.customTermCoverage = preview.customTermCoverage;
run.imagePolicy = preview.imagePolicy;
run.sourceState = {};
run.commentAuthorCoverage = preview.entityTypes.includes("PERSON");

View File

@@ -3,7 +3,7 @@ import { createHash, randomUUID } from "node:crypto";
import { constants as fsConstants, promises as fs } from "node:fs";
import { basename, dirname, extname, join, relative, resolve, sep } from "node:path";
import { environment } from "@raycast/api";
import type { EntityType, MappingEntry, PlaceholderMapping } from "../types";
import type { CustomTerm, EntityType, MappingEntry, PlaceholderMapping } from "../types";
import { whitelistKey } from "./project-whitelist";
import type { DocumentImageReport, ImagePolicy } from "./image-policy";
import type { ProjectWhitelistEntry } from "./project-whitelist";
@@ -13,7 +13,7 @@ import { mappingForRestoration } from "./mapping-groups";
export { whitelistKey } from "./project-whitelist";
export type { ProjectWhitelistEntry } from "./project-whitelist";
export type ProjectRule = { type: "BEGRIFF" | "PERSON" | "ORG" | "ORT" | "FIRMA" | "KUNDE"; value: string };
export type ProjectRule = CustomTerm;
export type ProjectFile = { relPath: string; absPath: string; kind: "text" | "document"; size: number };
export type SkippedProjectFile = { path: string; reason: string };
export type RunFile = { source: string; output: string; kind: ProjectFile["kind"]; imageReport?: DocumentImageReport; localDocx?: true };
@@ -27,6 +27,7 @@ export type ProjectRun = {
mapping: PlaceholderMapping;
/** Categories actually used to analyze the files in this snapshot. */
entityTypes?: EntityType[];
customTermCoverage?: string;
/** Explicit image handling applied to documents in this snapshot. Unknown means reprocess. */
imagePolicy?: ImagePolicy;
/** Hash of each live project file and its immutable output in this run. */
@@ -204,18 +205,21 @@ export async function loadProjectRules(projectPath: string, support?: string): P
function isProjectRule(value: unknown): value is ProjectRule {
if (!value || typeof value !== "object") return false;
const rule = value as Record<string, unknown>;
return ["BEGRIFF", "PERSON", "ORG", "ORT", "FIRMA", "KUNDE"].includes(String(rule.type))
return typeof rule.type === "string" && /^[A-Z][A-Z0-9_]*$/.test(rule.type)
&& typeof rule.value === "string" && rule.value.trim().length >= 2;
}
export function parseProjectRules(input: string): ProjectRule[] {
export function parseProjectRules(input: string,
entityTypes: readonly string[] = ["BEGRIFF", "PERSON", "ORG", "ORT", "FIRMA", "KUNDE"]): ProjectRule[] {
const allowed = new Set(entityTypes);
const rules = input.split(/\r?\n/).map((line) => line.trim()).filter(Boolean).map((line) => {
const match = /^(BEGRIFF|PERSON|ORG|ORT|FIRMA|KUNDE):\s*(.+)$/i.exec(line);
return match
? { type: match[1].toUpperCase() as ProjectRule["type"], value: match[2].trim() }
const match = /^([A-Z][A-Z0-9_]*):\s*(.+)$/i.exec(line);
const type = match?.[1].toUpperCase();
return match && type && allowed.has(type)
? { type, value: match[2].trim() }
: { type: "BEGRIFF" as const, value: line };
});
if (rules.length > 500 || rules.some((rule) => rule.value.length < 2 || rule.value.length > 200)) {
if (rules.length > 500 || rules.some((rule) => !validCustomTerm(rule.value))) {
throw new Error("Maximal 500 Begriffe mit jeweils 2 bis 200 Zeichen sind erlaubt.");
}
return rules.filter((rule, index) => rules.findIndex(
@@ -223,10 +227,21 @@ export function parseProjectRules(input: string): ProjectRule[] {
) === index);
}
export function validCustomTerm(value: string): boolean {
const length = Array.from(value.trim()).length;
return length >= 2 && length <= 200;
}
export async function saveProjectRules(projectPath: string, rules: ProjectRule[], support?: string): Promise<void> {
const path = rulesPath(projectPath, support);
await fs.mkdir(dirname(path), { recursive: true, mode: 0o700 });
await fs.writeFile(path, JSON.stringify(rules), { encoding: "utf8", mode: 0o600 });
const temp = `${path}.${randomUUID()}.tmp`;
try {
await fs.writeFile(temp, JSON.stringify(rules), { encoding: "utf8", mode: 0o600 });
await fs.rename(temp, path);
} finally {
await fs.rm(temp, { force: true });
}
}
export function forceMasks(rules: ProjectRule[]): Record<string, string[]> {
@@ -481,6 +496,7 @@ export async function updateProjectMapping(projectPath: string,
run.revisedFrom = latest.run.id;
run.mapping = mapping;
run.entityTypes = latest.run.entityTypes ? [...latest.run.entityTypes] : undefined;
run.customTermCoverage = latest.run.customTermCoverage;
run.matchModes = { ...latest.run.matchModes };
run.files = latest.run.files.map((file) => ({ ...file }));
run.sourceState = latest.run.sourceState ? { ...latest.run.sourceState } : undefined;

View File

@@ -1,274 +0,0 @@
import {
Action,
ActionPanel,
Alert,
confirmAlert,
Detail,
Form,
Icon,
List,
showToast,
Toast,
useNavigation,
} from "@raycast/api";
import { useEffect, useState } from "react";
import {
clearSessionMapping,
countMappingEntries,
createSession,
deleteAllSessions,
deleteSession,
getActiveSessionId,
listSessions,
releaseSessionMappingGroup,
renameSession,
setActiveSession,
} from "./sessions";
import type { VelumSession } from "./types";
import { mappingSummary, sessionSubtitle } from "./ui";
import { TranslationTable } from "./show-translation-tables";
export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [isLoading, setIsLoading] = useState(true);
async function reload() {
const [loadedSessions, activeId] = await Promise.all([
listSessions(),
getActiveSessionId(),
]);
setSessions(loadedSessions);
setActiveSessionId(activeId);
setIsLoading(false);
}
useEffect(() => {
reload();
}, []);
async function activate(session: VelumSession) {
await setActiveSession(session.id);
await reload();
await showToast({
style: Toast.Style.Success,
title: "Aktive Sitzung geändert",
message: session.name,
});
}
async function clearMapping(session: VelumSession) {
const confirmed = await confirmAlert({
title: "Zuordnung leeren?",
message: `${session.name} behält den Namen, verliert aber alle Platzhalter-Zuordnungen.`,
primaryAction: {
title: "Zuordnung leeren",
style: Alert.ActionStyle.Destructive,
},
});
if (!confirmed) {
return;
}
await clearSessionMapping(session.id);
await reload();
await showToast({
style: Toast.Style.Success,
title: "Zuordnung geleert",
message: session.name,
});
}
async function remove(session: VelumSession) {
const confirmed = await confirmAlert({
title: "Sitzung löschen?",
message: `${session.name} und ihre Zuordnung werden gelöscht.`,
primaryAction: {
title: "Sitzung löschen",
style: Alert.ActionStyle.Destructive,
},
});
if (!confirmed) {
return;
}
await deleteSession(session.id);
await reload();
await showToast({
style: Toast.Style.Success,
title: "Sitzung gelöscht",
message: session.name,
});
}
async function removeAll() {
const confirmed = await confirmAlert({
title: "Alle Sitzungen löschen?",
message:
"Alle gespeicherten Velum-Zuordnungen dieser Raycast-Extension werden gelöscht.",
primaryAction: {
title: "Alle löschen",
style: Alert.ActionStyle.Destructive,
},
});
if (!confirmed) {
return;
}
await deleteAllSessions();
await reload();
await showToast({
style: Toast.Style.Success,
title: "Alle Sitzungen gelöscht",
});
}
return (
<List isLoading={isLoading} searchBarPlaceholder="Velum-Sitzungen suchen">
<List.EmptyView
title="Keine Sitzungen"
description="Lege eine Sitzung an oder pseudonymisiere Text, um Zuordnungen zu speichern."
actions={
<ActionPanel>
<Action.Push
title="Neue Sitzung"
icon={Icon.Plus}
target={<SessionNameForm onSaved={reload} />}
/>
</ActionPanel>
}
/>
{sessions.map((session) => (
<List.Item
key={session.id}
title={session.name}
subtitle={sessionSubtitle(session)}
icon={session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle}
accessories={[{ text: `${countMappingEntries(session.mapping)}` }]}
actions={
<ActionPanel>
<Action.Push
title="Übersetzungstabelle anzeigen"
icon={Icon.List}
target={<TranslationTable title={session.name} mapping={session.mapping}
createdAtByKey={session.mappingCreatedAt}
removeDescription="Die gesamte Gruppe wird aus der Sitzung entfernt und künftig dort nicht mehr vorgeschlagen. Bereits kopierte oder eingefügte Texte werden nicht rückwirkend geändert."
onRemove={async (root) => {
const updated = await releaseSessionMappingGroup(session.id, root);
await reload();
return updated.mapping;
}} />}
/>
<Action
title="Als Aktive Sitzung Setzen"
icon={Icon.CheckCircle}
onAction={() => activate(session)}
/>
<Action.Push
title="Details anzeigen"
icon={Icon.List}
target={<SessionDetail session={session} />}
/>
<Action.Push
title="Sitzung umbenennen"
icon={Icon.Pencil}
target={<SessionNameForm session={session} onSaved={reload} />}
/>
<Action.Push
title="Neue Sitzung"
icon={Icon.Plus}
target={<SessionNameForm onSaved={reload} />}
/>
<Action
title="Zuordnung leeren"
icon={Icon.XMarkCircle}
style={Action.Style.Destructive}
onAction={() => clearMapping(session)}
/>
<Action
title="Sitzung löschen"
icon={Icon.Trash}
style={Action.Style.Destructive}
onAction={() => remove(session)}
/>
<Action
title="Alle Sitzungen löschen"
icon={Icon.Trash}
style={Action.Style.Destructive}
onAction={removeAll}
/>
</ActionPanel>
}
/>
))}
</List>
);
}
function SessionNameForm({
session,
onSaved,
}: {
session?: VelumSession;
onSaved: () => Promise<void>;
}) {
const { pop } = useNavigation();
async function handleSubmit(values: { name: string }) {
if (session) {
await renameSession(session.id, values.name);
await showToast({
style: Toast.Style.Success,
title: "Sitzung umbenannt",
});
} else {
await createSession(values.name.trim() || undefined);
await showToast({
style: Toast.Style.Success,
title: "Sitzung erstellt",
});
}
await onSaved();
pop();
}
return (
<Form
actions={
<ActionPanel>
<Action.SubmitForm
title={session ? "Sitzung Umbenennen" : "Sitzung Erstellen"}
onSubmit={handleSubmit}
/>
</ActionPanel>
}
>
<Form.TextField
id="name"
title="Name"
defaultValue={session?.name}
placeholder="Sitzungsname"
/>
</Form>
);
}
function SessionDetail({ session }: { session: VelumSession }) {
const markdown = [
`# ${session.name}`,
sessionSubtitle(session),
"",
`Erstellt: ${new Date(session.createdAt).toLocaleString()}`,
"",
"## Zuordnung",
mappingSummary(session.mapping),
"",
"## Platzhalter",
...Object.entries(session.mapping)
.sort(([a], [b]) => a.localeCompare(b))
.map(([placeholder, entry]) => `- \`${placeholder}\` · ${entry.type}`),
].join("\n");
return <Detail markdown={markdown} />;
}

View File

@@ -0,0 +1,76 @@
import { Action, ActionPanel, Icon, List, useNavigation } from "@raycast/api";
import { useState } from "react";
const PAGE_SIZE = 200;
export function PersonMergeTargets(props: {
people: Array<{ placeholder: string; originals: string[] }>;
onChoose: (placeholder: string) => void;
}) {
const { pop } = useNavigation();
const [query, setQuery] = useState("");
const [page, setPage] = useState(0);
const matching = props.people.filter((person) =>
`${person.originals.join(" ")} ${person.placeholder}`
.toLowerCase()
.includes(query.trim().toLowerCase()),
);
const pages = Math.ceil(matching.length / PAGE_SIZE);
return (
<List
navigationTitle="Zusammenführen mit"
filtering={false}
searchText={query}
searchBarPlaceholder="Person oder Platzhalter suchen"
onSearchTextChange={(value) => {
setQuery(value);
setPage(0);
}}
>
{pages > 1 && (
<List.Item
id="page"
title={`Seite ${page + 1}/${pages}`}
actions={
<ActionPanel>
{page + 1 < pages && (
<Action
title="Nächste Seite"
onAction={() => setPage(page + 1)}
/>
)}
{page > 0 && (
<Action
title="Vorherige Seite"
onAction={() => setPage(page - 1)}
/>
)}
</ActionPanel>
}
/>
)}
{matching
.slice(page * PAGE_SIZE, (page + 1) * PAGE_SIZE)
.map((person) => (
<List.Item
key={person.placeholder}
id={person.placeholder}
title={person.originals.join(" · ")}
subtitle={person.placeholder}
actions={
<ActionPanel>
<Action
title="Personen zusammenfassen"
icon={Icon.Link}
onAction={() => {
props.onChoose(person.placeholder);
pop();
}}
/>
</ActionPanel>
}
/>
))}
</List>
);
}

View File

@@ -223,7 +223,7 @@ export default function Command() {
toast.style = Toast.Style.Success;
toast.title = "Treffer zur Prüfung bereit";
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(
<PseudonymizationConfirm
session={updatedSession}

View File

@@ -12,7 +12,8 @@ import {
saveProjectWhitelist, scanProjectFiles, whitelistKey, withoutExcludedProjectFiles,
} from "./lib/velum-project";
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, SkippedProjectFile } from "./lib/velum-project";
import { canonicalPerson, groupReviewHits, mergePeople } from "./lib/project-review";
import { canonicalPerson, groupReviewHits, highlightedReviewContext, mergePeople } from "./lib/project-review";
import { CustomTermForm } from "./custom-term-form";
import { checkedImagePolicy, DEFAULT_IMAGE_POLICY, IMAGE_POLICY_LABELS, KEEP_IMAGE_WARNING } from "./lib/image-policy";
import type { ImagePolicy } from "./lib/image-policy";
import {
@@ -20,6 +21,7 @@ import {
} from "./lib/project-jobs";
import type { ProjectJobState } from "./lib/project-jobs";
import type { Hit, Preview } from "./lib/project-work";
import { PersonMergeTargets } from "./person-merge-targets";
const run = promisify(execFile);
const REVIEW_PAGE_SIZE = 200;
@@ -57,34 +59,28 @@ function OccurrenceReview(props: { original: string; placeholder: string; hits:
const [page, setPage] = useState(0);
const pages = Math.ceil(props.hits.length / REVIEW_PAGE_SIZE);
return <List isShowingDetail navigationTitle={`${props.original} → ${props.placeholder}`}>
{pages > 1 && <List.Item title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel>
{pages > 1 && <List.Item id="page" title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel>
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
</ActionPanel>} />}
{props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => <List.Item key={hit.id} title={hit.source}
subtitle={hit.kind === "path" ? "Datei- oder Ordnername" : "Dateiinhalt"}
detail={<List.Item.Detail markdown={hit.context.replace(/</g, "&lt;")} />} />)}
</List>;
}
function PersonMergeTargets(props: { people: Array<{ placeholder: string; originals: string[] }>;
onChoose: (placeholder: string) => void }) {
const { pop } = useNavigation();
const [query, setQuery] = useState("");
const [page, setPage] = useState(0);
const matching = props.people.filter((person) => `${person.originals.join(" ")} ${person.placeholder}`
.toLowerCase().includes(query.trim().toLowerCase()));
const pages = Math.max(1, Math.ceil(matching.length / REVIEW_PAGE_SIZE));
return <List navigationTitle="Zusammenführen mit" filtering={false} searchText={query}
onSearchTextChange={(value) => { setQuery(value); setPage(0); }}>
{pages > 1 && <List.Item title={`Seite ${page + 1}/${pages}`} actions={<ActionPanel>
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
</ActionPanel>} />}
{matching.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((person) =>
<List.Item key={person.placeholder} title={person.originals.join(" · ")} subtitle={person.placeholder}
actions={<ActionPanel><Action title="Personen zusammenfassen" icon={Icon.Link}
onAction={() => { props.onChoose(person.placeholder); pop(); }} /></ActionPanel>} />)}
{props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => {
// Older jobs saved the same snippets without their relative hit positions.
const legacyOffset = hit.kind === "path" ? hit.start
: hit.segment !== undefined || hit.id.startsWith(`${hit.file}:document:`)
? Array.from(hit.context).slice(0, Math.min(hit.start, 60)).join("").length
: Math.min(hit.start, 70);
const first = hit.context.indexOf(hit.original);
const atLegacyOffset = hit.kind === "path" || hit.context.startsWith(hit.original, legacyOffset);
const offset = hit.contextOffset ?? (atLegacyOffset ? legacyOffset
: first === hit.context.lastIndexOf(hit.original) ? first : -1);
return <List.Item key={hit.id} id={hit.id} title={hit.file}
subtitle={hit.source === hit.file ? "Dateiinhalt" : hit.source}
detail={<List.Item.Detail
markdown={highlightedReviewContext(hit.context, offset, hit.original.length)}
metadata={offset < 0 ? <List.Item.Detail.Metadata>
<List.Item.Detail.Metadata.Label title="Treffer" text={{ color: Color.Red, value: hit.original }} />
</List.Item.Detail.Metadata> : undefined} />} />;
})}
</List>;
}
@@ -251,7 +247,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
</List.Section>}
{[...byType].map(([type, entries]) => <List.Section key={type}
title={`${labelForType(type)} · ${groups.filter((entry) => entry.type === type && selectedGroups.has(entry.key)).length}/${groups.filter((entry) => entry.type === type).length}`}>
{entries.map((group) => <List.Item key={group.key}
{entries.map((group) => <List.Item key={group.key} id={group.hits[0].id}
icon={{ source: selectedGroups.has(group.key) ? Icon.CheckCircle : Icon.Circle,
tintColor: selectedGroups.has(group.key) ? Color.Green : Color.SecondaryText }}
title={group.original} subtitle={`→ ${group.placeholder}`}
@@ -551,9 +547,10 @@ export default function Command() {
return;
}
if (typesReadyFor !== root) throw new Error("Projektkategorien werden noch geladen oder sind nicht lesbar.");
if (!selectedTypes.length) throw new Error("Bitte mindestens eine Kategorie wählen.");
const parsed = parseProjectRules(rules);
await saveProjectEntityTypes(root, selectedTypes);
const parsed = parseProjectRules(rules, availableTypes);
const types = [...new Set([...selectedTypes, ...parsed.map((rule) => rule.type)])];
if (!types.length) throw new Error("Bitte mindestens eine Kategorie wählen.");
await saveProjectEntityTypes(root, types);
await saveProjectRules(root, parsed);
toast.title = "Dateien werden erfasst";
const scan = await scanProjectFiles(root, undefined, false, { ".docx": 128 * 1024 * 1024 });
@@ -565,7 +562,7 @@ export default function Command() {
toast.style = Toast.Style.Success;
toast.title = `${scan.files.length} Dateien zur Auswahl`;
push(<FileSelection root={root} files={scan.files} skipped={scan.skipped} excluded={excluded}
rules={parsed} types={selectedTypes} reanalyzeUnchanged={reanalyzeUnchanged} imagePolicy={imagePolicy}
rules={parsed} types={types} reanalyzeUnchanged={reanalyzeUnchanged} imagePolicy={imagePolicy}
onWhitelistChanged={setWhitelist} />);
} catch (error) {
toast.style = Toast.Style.Failure;
@@ -581,6 +578,12 @@ export default function Command() {
}
return <Form isLoading={busy} actions={<ActionPanel>
<Action title="Projektdateien auswählen oder Auftrag öffnen" onAction={next} />
{availableTypes.length > 0 && <Action.Push title="Eigenen Begriff hinzufügen" icon={Icon.Plus}
target={<CustomTermForm entityTypes={availableTypes} onAdd={(term) => {
const next = parseProjectRules([rules, `${term.type}: ${term.value}`].filter(Boolean).join("\n"), availableTypes);
setRules(next.map((rule) => `${rule.type}: ${rule.value}`).join("\n"));
setSelectedTypes((current) => [...new Set([...current, term.type])]);
}} />} />}
<Action title="Geöffneten Finder-Ordner übernehmen" icon={Icon.Folder} onAction={useFinderFolder} />
<Action.Push title="Projekt-Whitelist bearbeiten" icon={Icon.List}
target={<ProjectWhitelist entries={whitelist} onRemove={removeFromWhitelist} />} />
@@ -593,7 +596,7 @@ export default function Command() {
: "Neues Projekt. Falls dieser Ordner aus einem bestehenden Projekt verschoben wurde, aktualisiere zuerst dessen Pfad über „Projektdateien wiederherstellen“ → „Projektordner ändern“."} />
<Form.TextArea id="projectRules" title="Begriffe nur für dieses Projekt" value={rules}
onChange={setRules} placeholder={"BEGRIFF: KundenSuite\nPERSON: Max Mustermann"}
info="Ein Begriff pro Zeile. Ohne Typ wird BEGRIFF verwendet. Diese Regeln werden nur für dieses Projekt gespeichert und bei der Velum-Anfrage mitgesendet." />
info="Ein Begriff pro Zeile. Ohne Typ wird BEGRIFF verwendet. Die Kategorien der Projektbegriffe werden für die Analyse aktiviert." />
<Form.TagPicker id="entityTypes" title="Kategorien pseudonymisieren" value={selectedTypes}
onChange={setSelectedTypes} info="Die Auswahl wird beim Prüfen für diesen Projektordner gespeichert. Word-Kommentatoren und Bearbeiter von Änderungen werden mit der Kategorie Personen maskiert. Bei neuen Projekten sind Orte zunächst abgewählt.">
{availableTypes.map((type) => <Form.TagPicker.Item key={type} value={type} title={labelForType(type)} />)}

View File

@@ -119,7 +119,7 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
toast.style = Toast.Style.Success;
toast.title = "Treffer zur Prüfung bereit";
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} onConfirmed={async (result, session) => {
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} onConfirmed={async (result, session) => {
if (props.autoOutput) {
const paste = props.forcePaste || getPreferences().quickOutput === "paste";
try {

View File

@@ -20,6 +20,7 @@ import {
DEFAULT_MODEL,
getLastUsedModel,
MODEL_OPTIONS,
resolveRaycastModel,
setLastUsedModel,
} from "./ai";
import { getPreferences } from "./preferences";
@@ -190,7 +191,7 @@ export default function Command() {
toast.style = Toast.Style.Success;
toast.title = "Treffer zur Prüfung bereit";
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(
<ConfirmReply
session={updatedSession}
@@ -560,7 +561,7 @@ function ReplyResult(props: StageProps) {
instructions: props.instructions,
});
const stream = AI.ask(prompt, {
model: props.model as AI.Model,
model: resolveRaycastModel(props.model),
creativity: props.creativity,
signal: controller.signal,
});

View File

@@ -65,14 +65,17 @@ export async function setActiveSession(id: string): Promise<void> {
await LocalStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, id);
}
export async function createSession(name?: string): Promise<VelumSession> {
export async function createSession(name?: string,
initial?: Pick<VelumSession, "mapping" | "entityTypes" | "excludedTerms" | "customTerms">): Promise<VelumSession> {
const timestamp = nowIso();
const session: VelumSession = {
id: randomUUID(),
name: name || `Sitzung ${new Date().toLocaleString()}`,
name: name?.trim() || `Sitzung ${new Date().toLocaleString()}`,
createdAt: timestamp,
updatedAt: timestamp,
mapping: {},
...initial,
...(initial && { mappingCreatedAt: mappingDates(undefined, initial.mapping, timestamp) }),
};
const sessions = await listSessions();
@@ -103,6 +106,7 @@ export async function updateSessionMapping(
mapping: PlaceholderMapping,
entityTypes?: string[],
excludedTerms?: VelumSession["excludedTerms"],
customTerms?: VelumSession["customTerms"],
): Promise<VelumSession> {
const sessions = await listSessions();
const timestamp = nowIso();
@@ -117,6 +121,7 @@ export async function updateSessionMapping(
mapping,
entityTypes,
excludedTerms,
customTerms,
mappingCreatedAt: mappingDates(undefined, mapping, timestamp),
};
await saveSessions([created, ...sessions]);
@@ -128,6 +133,7 @@ export async function updateSessionMapping(
mapping,
entityTypes,
excludedTerms: excludedTerms ?? sessions[index].excludedTerms,
customTerms: customTerms ?? sessions[index].customTerms,
mappingCreatedAt: mappingDates(sessions[index], mapping, timestamp),
updatedAt: timestamp,
};
@@ -190,7 +196,3 @@ export async function deleteAllSessions(): Promise<void> {
await LocalStorage.removeItem(SESSIONS_STORAGE_KEY);
await LocalStorage.removeItem(ACTIVE_SESSION_STORAGE_KEY);
}
export function countMappingEntries(mapping: PlaceholderMapping): number {
return Object.keys(mapping).length;
}

View File

@@ -3,6 +3,7 @@ import {
ActionPanel,
Alert,
confirmAlert,
Detail,
Form,
Icon,
List,
@@ -14,8 +15,21 @@ import {
import { useCallback, useEffect, useState } from "react";
import { addProjectMappingEntry, canonicalProjectPath, listAllRuns, prepareManualMappingEntry, updateProjectMapping } from "./lib/velum-project";
import { detachMappingGroup, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
import { getSession, listSessions, releaseSessionMappingGroup, updateSessionMapping } from "./sessions";
import type { PlaceholderMapping } from "./types";
import {
clearSessionMapping,
createSession,
deleteAllSessions,
deleteSession,
getActiveSessionId,
getSession,
listSessions,
releaseSessionMappingGroup,
renameSession,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import type { PlaceholderMapping, VelumSession } from "./types";
import { mappingSummary, sessionSubtitle } from "./ui";
import { releaseProjectMapping } from "./project-mapping-actions";
import { projectMappingCreatedAt, sortMappingRowsByCreatedAt } from "./lib/mapping-created-at";
import type { ProjectRun } from "./lib/velum-project";
@@ -244,43 +258,65 @@ export function TranslationTable({
export default function Command() {
const [projects, setProjects] = useState<TableSource[]>([]);
const [sessions, setSessions] = useState<TableSource[]>([]);
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
const [busy, setBusy] = useState(true);
const refresh = useCallback(async () => {
await Promise.all([listAllRuns(), listSessions()])
.then(([runs, savedSessions]) => {
const history = new Map<string, ProjectRun[]>();
for (const { run } of runs) {
const path = canonicalProjectPath(run.projectPath);
if (!history.has(path)) history.set(path, []);
history.get(path)!.push(run);
}
setProjects(
[...history].map(([path, entries]) => {
const latest = entries[0];
return { id: path, title: latest.projectName,
subtitle: `${path} · ${new Date(latest.createdAt).toLocaleString("de-AT")}`,
mapping: latest.mapping,
createdAtByKey: projectMappingCreatedAt(entries, latest.mapping) };
}).sort((a, b) => a.title.localeCompare(b.title)),
);
setSessions(
savedSessions.map((session) => ({
id: session.id,
title: session.name,
subtitle: `${Object.keys(session.mapping).length} Zuordnungen · ${new Date(session.updatedAt).toLocaleString("de-AT")}`,
mapping: session.mapping,
createdAtByKey: session.mappingCreatedAt ?? {},
})),
);
});
const refreshProjects = useCallback(async () => {
const history = new Map<string, ProjectRun[]>();
for (const { run } of await listAllRuns()) {
const path = canonicalProjectPath(run.projectPath);
if (!history.has(path)) history.set(path, []);
history.get(path)!.push(run);
}
setProjects([...history].map(([path, entries]) => {
const latest = entries[0];
return { id: path, title: latest.projectName,
subtitle: `${path} · ${new Date(latest.createdAt).toLocaleString("de-AT")}`,
mapping: latest.mapping,
createdAtByKey: projectMappingCreatedAt(entries, latest.mapping) };
}).sort((a, b) => a.title.localeCompare(b.title)));
}, []);
const refreshSessions = useCallback(async () => {
const [saved, active] = await Promise.all([listSessions(), getActiveSessionId()]);
setSessions(saved);
setActiveSessionId(active);
}, []);
useEffect(() => {
refresh().catch((error: Error) => showToast({ style: Toast.Style.Failure,
title: "Übersetzungstabellen nicht lesbar", message: error.message }))
.finally(() => setBusy(false));
}, [refresh]);
void Promise.allSettled([refreshProjects(), refreshSessions()]).then((results) => {
setBusy(false);
const failed = results.find((result) => result.status === "rejected");
if (failed) void showToast({ style: Toast.Style.Failure,
title: "Übersetzungstabellen konnten nicht vollständig geladen werden",
message: String(failed.reason) });
});
}, [refreshProjects, refreshSessions]);
async function changeSessions(action: () => Promise<void>, title: string) {
if (busy) return;
setBusy(true);
try {
await action();
await refreshSessions();
await showToast({ style: Toast.Style.Success, title });
} catch (error) {
await showToast({ style: Toast.Style.Failure, title: "Sitzung konnte nicht geändert werden",
message: error instanceof Error ? error.message : String(error) });
} finally { setBusy(false); }
}
async function confirmSessionChange(title: string, message: string, action: () => Promise<void>, success: string) {
if (busy) return;
if (await confirmAlert({ title: `${title}?`, message,
primaryAction: { title, style: Alert.ActionStyle.Destructive } })) {
await changeSessions(action, success);
}
}
const newSessionAction = <Action.Push title="Neue Sitzung" icon={Icon.Plus}
target={<SessionNameForm onSaved={refreshSessions} />} />;
return (
<List
@@ -289,8 +325,8 @@ export default function Command() {
searchBarPlaceholder="Projekt oder Sitzung suchen"
>
<List.EmptyView
title="Keine Tabellen"
description="Pseudonymisiere zuerst Text oder Projektdateien."
title="Keine passende Tabelle"
actions={<ActionPanel>{newSessionAction}</ActionPanel>}
/>
<List.Section title="Projekte">
{projects.map((source) => (
@@ -314,32 +350,32 @@ export default function Command() {
createdAtByKey={source.createdAtByKey}
onAdd={async (input) => {
const run = await addProjectMappingEntry(source.id, input);
await refresh();
await refreshProjects();
return run.mapping;
}}
onMerge={async (from, into) => {
const run = await updateProjectMapping(source.id,
(current) => mergeMappingGroups(current, from, into));
await refresh();
await refreshProjects();
return run.mapping;
}}
onDetach={async (key) => {
const run = await updateProjectMapping(source.id,
(current) => detachMappingGroup(current, key));
await refresh();
await refreshProjects();
return run.mapping;
}}
removeDescription="Die gesamte Gruppe wird als Projektausnahme gespeichert. Auch zwischenzeitlich bearbeitete Projektdateien werden anhand ihres aktuellen Stands korrigiert und vorher gesichert."
onRemove={async (root) => {
const revised = await releaseProjectMapping(source.id, root);
await refresh();
await refreshProjects();
return revised.run.mapping;
}}
/>
}
/>
<Action.Push title="Projektordner ändern" icon={Icon.Folder}
target={<RelocateProjectForm projectName={source.title} oldPath={source.id} onMoved={refresh} />} />
target={<RelocateProjectForm projectName={source.title} oldPath={source.id} onMoved={refreshProjects} />} />
</ActionPanel>
}
/>
@@ -349,9 +385,11 @@ export default function Command() {
{sessions.map((source) => (
<List.Item
key={source.id}
icon={Icon.Person}
title={source.title}
subtitle={source.subtitle}
id={source.id}
icon={source.id === activeSessionId ? Icon.CheckCircle : Icon.Person}
title={source.name}
subtitle={sessionSubtitle(source)}
accessories={source.id === activeSessionId ? [{ text: "Aktiv" }] : []}
actions={
<ActionPanel>
<Action.Push
@@ -359,9 +397,9 @@ export default function Command() {
icon={Icon.List}
target={
<TranslationTable
title={source.title}
title={source.name}
mapping={source.mapping}
createdAtByKey={source.createdAtByKey}
createdAtByKey={source.mappingCreatedAt}
onAdd={async (input) => {
const session = await getSession(source.id);
if (!session) throw new Error("Sitzung nicht gefunden.");
@@ -372,7 +410,7 @@ export default function Command() {
const key = bracketed ? `<${placeholder}>` : placeholder;
const updated = await updateSessionMapping(session.id,
{ ...session.mapping, [key]: entry }, session.entityTypes);
await refresh();
await refreshSessions();
return updated.mapping;
}}
onMerge={async (from, into) => {
@@ -380,7 +418,7 @@ export default function Command() {
if (!session) throw new Error("Sitzung nicht gefunden.");
const updated = await updateSessionMapping(session.id,
mergeMappingGroups(session.mapping, from, into), session.entityTypes);
await refresh();
await refreshSessions();
return updated.mapping;
}}
onDetach={async (key) => {
@@ -388,23 +426,91 @@ export default function Command() {
if (!session) throw new Error("Sitzung nicht gefunden.");
const updated = await updateSessionMapping(session.id,
detachMappingGroup(session.mapping, key), session.entityTypes);
await refresh();
await refreshSessions();
return updated.mapping;
}}
removeDescription="Die gesamte Gruppe wird aus der Sitzung entfernt und künftig dort nicht mehr vorgeschlagen. Bereits kopierte oder eingefügte Texte werden nicht rückwirkend geändert."
onRemove={async (root) => {
const updated = await releaseSessionMappingGroup(source.id, root);
await refresh();
await refreshSessions();
return updated.mapping;
}}
/>
}
/>
<ActionPanel.Section title="Sitzung">
{source.id !== activeSessionId && <Action title="Als aktive Sitzung setzen" icon={Icon.CheckCircle}
onAction={() => changeSessions(() => setActiveSession(source.id), "Aktive Sitzung geändert")} />}
<Action.Push title="Sitzungsdetails anzeigen" icon={Icon.Info}
target={<SessionDetail session={source} />} />
<Action.Push title="Sitzung umbenennen" icon={Icon.Pencil}
target={<SessionNameForm session={source} onSaved={refreshSessions} />} />
{newSessionAction}
</ActionPanel.Section>
<ActionPanel.Section>
<Action title="Zuordnungen leeren" icon={Icon.XMarkCircle} style={Action.Style.Destructive}
onAction={() => confirmSessionChange("Zuordnungen leeren",
`Alle Platzhalter-Zuordnungen aus „${source.name}“ werden gelöscht.`,
() => clearSessionMapping(source.id), "Zuordnungen geleert")} />
<Action title="Sitzung löschen" icon={Icon.Trash} style={Action.Style.Destructive}
onAction={() => confirmSessionChange("Sitzung löschen",
`„${source.name}“ und ihre Zuordnungen werden gelöscht.`,
() => deleteSession(source.id), "Sitzung gelöscht")} />
<Action title="Alle Sitzungen löschen" icon={Icon.Trash} style={Action.Style.Destructive}
onAction={() => confirmSessionChange("Alle Sitzungen löschen",
"Alle gespeicherten Sitzungen und ihre Zuordnungen werden gelöscht.",
deleteAllSessions, "Alle Sitzungen gelöscht")} />
</ActionPanel.Section>
</ActionPanel>
}
/>
))}
<List.Item id="new-session" icon={Icon.Plus} title="Neue Sitzung"
actions={<ActionPanel>{newSessionAction}</ActionPanel>} />
</List.Section>
</List>
);
}
function SessionNameForm({ session, onSaved }: { session?: VelumSession; onSaved: () => Promise<void> }) {
const { pop } = useNavigation();
const [busy, setBusy] = useState(false);
const title = session ? "Sitzung umbenennen" : "Sitzung anlegen";
async function save({ name }: { name: string }) {
if (busy) return;
setBusy(true);
try {
if (session) await renameSession(session.id, name);
else await createSession(name);
await onSaved();
await showToast({ style: Toast.Style.Success, title: session ? "Sitzung umbenannt" : "Sitzung angelegt" });
pop();
} catch (error) {
await showToast({ style: Toast.Style.Failure, title: "Sitzung konnte nicht gespeichert werden",
message: error instanceof Error ? error.message : String(error) });
} finally { setBusy(false); }
}
return <Form navigationTitle={title} isLoading={busy}
actions={<ActionPanel><Action.SubmitForm title={title} onSubmit={save} /></ActionPanel>}>
<Form.TextField id="name" title="Sitzungsname" defaultValue={session?.name}
placeholder={session ? undefined : "Leer lassen für einen automatisch vergebenen Namen"} />
</Form>;
}
function SessionDetail({ session }: { session: VelumSession }) {
const markdown = [
sessionSubtitle(session),
"",
`Erstellt am ${new Date(session.createdAt).toLocaleString()}`,
"",
"## Zuordnungen",
mappingSummary(session.mapping),
"",
"## Platzhalter",
...Object.entries(session.mapping).sort(([a], [b]) => a.localeCompare(b))
.map(([placeholder, entry]) => `- \`${placeholder}\` · ${entry.type}`),
].join("\n");
return <Detail navigationTitle={session.name} markdown={markdown} />;
}

View File

@@ -27,6 +27,7 @@ import {
DEFAULT_MODEL,
getLastUsedModel,
MODEL_OPTIONS,
resolveRaycastModel,
setLastUsedModel,
} from "./ai";
import { buildSummaryPrompt, type Creativity } from "./summarize";
@@ -136,7 +137,7 @@ export default function Command() {
toast.style = Toast.Style.Success;
toast.title = "Treffer zur Prüfung bereit";
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(
<ConfirmPseudonymized
session={updatedSession}
@@ -354,7 +355,7 @@ function SummarizeEmailResult({
try {
const prompt = buildSummaryPrompt(pseudonymizedText, instructions);
const stream = AI.ask(prompt, {
model: model as AI.Model,
model: resolveRaycastModel(model),
creativity,
signal: controller.signal,
});

View File

@@ -189,7 +189,7 @@ export default function Command() {
toast.style = Toast.Style.Success;
toast.title = "Treffer zur Prüfung bereit";
toast.message = `${prepared.raw.spans.length} Treffer prüfen`;
push(<TextHitReview prepared={prepared} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(<TextHitReview prepared={prepared} entityTypes={entityTypes} forAi onConfirmed={async (pseudoResult, updatedSession) => {
push(
<PseudonymizationConfirm
session={updatedSession}

View File

@@ -1,4 +1,5 @@
import { AI } from "@raycast/api";
import { resolveRaycastModel } from "./ai";
export type Creativity = "none" | "low" | "medium" | "high";
@@ -54,7 +55,7 @@ export async function runSummaryStream(
): Promise<string> {
let buffer = "";
const stream = AI.ask(options.prompt, {
model: options.model as AI.Model,
model: resolveRaycastModel(options.model),
creativity: options.creativity,
signal: options.signal,
});

View File

@@ -1,15 +1,16 @@
import { promises as fs } from "node:fs";
import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules,
loadProjectWhitelist, replaceSpans, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project";
import { mappingForRestoration } from "./lib/mapping-groups";
loadProjectWhitelist, replaceSpans, saveProjectRules, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping,
validCustomTerm, whitelistKey } from "./lib/velum-project";
import { mappingForRestoration, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
import type { ProjectWhitelistEntry } from "./lib/velum-project";
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values";
import { createSession, getSession, setActiveSession, updateSessionMapping } from "./sessions";
import type { EntityType, PlaceholderMapping, PseudonymizeResponse, VelumSession } from "./types";
import type { CustomTerm, EntityType, PlaceholderMapping, PseudonymizeResponse, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import { normalizePseudonymizeResponse, pseudonymize } from "./velum";
function projectMapping(mapping: PlaceholderMapping): PlaceholderMapping {
export function bareMapping(mapping: PlaceholderMapping): PlaceholderMapping {
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [
key.replace(/^<|>$/g, ""),
{ ...entry, merged_into: entry.merged_into?.replace(/^<|>$/g, "") },
@@ -26,8 +27,16 @@ function resultSession(path: string, name: string, mapping: PlaceholderMapping,
export function applyProjectWhitelist(text: string, response: PseudonymizeResponse,
previous: PlaceholderMapping, whitelist: ProjectWhitelistEntry[]): PseudonymizeResponse {
const excluded = new Set(whitelist.map(whitelistKey));
if (!excluded.size || !response.spans.some((span) => excluded.has(whitelistKey(span)))) return response;
const accepted = response.spans.filter((span) => !excluded.has(whitelistKey(span)));
if (!excluded.size) return response;
return filterTextHits(text, response, previous, (span) => !excluded.has(whitelistKey(span)));
}
type TextSpan = PseudonymizeResponse["spans"][number];
function filterTextHits(text: string, response: PseudonymizeResponse, previous: PlaceholderMapping,
keep: (span: TextSpan) => boolean): PseudonymizeResponse {
const accepted = response.spans.filter(keep);
if (accepted.length === response.spans.length) return response;
const spans = toUtf16Offsets(text, accepted).map((span, index) => ({ ...span, id: String(index) }));
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
const known = new Set(Object.keys(previous).map((key) => key.replace(/^<|>$/g, "")));
@@ -46,11 +55,65 @@ export type PreparedText = {
raw: PseudonymizeResponse;
previous: PlaceholderMapping;
exclusions: ProjectWhitelistEntry[];
customTerms: CustomTerm[];
addedTerms?: CustomTerm[];
selected: string;
newSessionName?: string;
projectPath?: string;
projectName?: string;
};
function termKey(type: EntityType, value: string): string {
return whitelistKey({ type, original: value.replace(/\s+/gu, " ") });
}
function mergeCustomTerms(previous: CustomTerm[], additions: CustomTerm[]): CustomTerm[] {
const replaced = new Set(additions.map(({ value }) => termKey("", value)));
const combined = [...previous.filter(({ value }) => !replaced.has(termKey("", value))), ...additions];
if (combined.length > 500) throw new Error("Maximal 500 eigene Begriffe sind erlaubt.");
return combined;
}
async function analyzeText(text: string, mapping: PlaceholderMapping, entityTypes: EntityType[],
customTerms: CustomTerm[], exclusions: ProjectWhitelistEntry[], request: typeof pseudonymize) {
const excluded = new Set(exclusions.map(({ type, original }) => termKey(type, original)));
const rules = customTerms.filter(({ type, value }) => !excluded.has(termKey(type, value)));
const effectiveTypes = [...new Set([...entityTypes, ...rules.map(({ type }) => type)])];
const response = await request(text, mapping, effectiveTypes, rules.length ? forceMasks(rules) : undefined);
if (!response.spans.length && response.pseudonymized_text !== text) {
throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert.");
}
const forced = new Set(rules.map(({ type, value }) => termKey(type, value)));
const automatic = new Set(entityTypes);
const filtered = filterTextHits(text, response, mapping, ({ type, original }) => {
const key = termKey(type, original);
return !excluded.has(key) && (automatic.has(type) || forced.has(key));
});
return { ...filtered, selected_entity_types: entityTypes };
}
export async function addTextReviewTerm(prepared: PreparedText, term: CustomTerm,
selected: Set<number>, request: typeof pseudonymize = pseudonymize):
Promise<{ prepared: PreparedText; selected: Set<number> }> {
if (!validCustomTerm(term.value)) throw new Error("Bitte einen Begriff mit 2 bis 200 Zeichen eingeben.");
const addedTerms = mergeCustomTerms(prepared.addedTerms ?? [], [term]);
const explicit = new Set(addedTerms.map(({ type, value }) => termKey(type, value)));
const exclusions = prepared.exclusions.filter(({ type, original }) => !explicit.has(termKey(type, original)));
const raw = await analyzeText(prepared.text, { ...bareMapping(prepared.previous), ...bareMapping(prepared.raw.mapping) },
prepared.raw.selected_entity_types, mergeCustomTerms(prepared.customTerms, addedTerms), exclusions, request);
const key = termKey(term.type, term.value);
if (!raw.spans.some(({ type, original }) => termKey(type, original) === key)) {
throw new Error("Kein Treffer für diesen Begriff in der gewählten Kategorie. Prüfe die Schreibweise und mögliche Überschneidungen.");
}
const occurrenceKey = (span: TextSpan) => JSON.stringify([span.start, span.end, span.type]);
const rejected = new Set(prepared.raw.spans.filter((_, index) => !selected.has(index)).map(occurrenceKey));
const next = new Set<number>();
for (const [index, span] of raw.spans.entries()) {
if (termKey(span.type, span.original) === key || !rejected.has(occurrenceKey(span))) next.add(index);
}
return { prepared: { ...prepared, raw, addedTerms }, selected: next };
}
/** The local API may propose hits, but this step never stores mappings or starts a cloud request. */
export async function prepareTextInContext(values: ContextFormValues, text: string,
entityTypes: EntityType[], request: typeof pseudonymize = pseudonymize): Promise<PreparedText> {
@@ -68,49 +131,68 @@ export async function prepareTextInContext(values: ContextFormValues, text: stri
throw new Error("Für diesen Ordner besteht bereits ein Projekt. Bitte es in der Liste wählen.");
}
if (selected !== NEW_PROJECT_ID && !latest) throw new Error("Projektstand nicht gefunden. Bitte die Liste aktualisieren.");
const [rules, exclusions] = await Promise.all([loadProjectRules(path), loadProjectWhitelist(path)]);
const excluded = new Set(exclusions.map(whitelistKey));
const masks = forceMasks(rules.filter((rule) => !excluded.has(whitelistKey({ type: rule.type, original: rule.value }))));
const [customTerms, exclusions] = await Promise.all([loadProjectRules(path), loadProjectWhitelist(path)]);
const previous = latest?.run.mapping ?? {};
const raw = applyProjectWhitelist(text, await request(text, previous, entityTypes, masks), previous, exclusions);
if (!raw.spans.length && raw.pseudonymized_text !== text) {
throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert.");
}
return { text, raw, previous, exclusions, selected, projectPath: path,
const raw = await analyzeText(text, previous, entityTypes, customTerms, exclusions, request);
return { text, raw, previous, exclusions, customTerms, selected, projectPath: path,
projectName: latest?.run.projectName ?? path.split("/").filter(Boolean).at(-1) ?? path };
}
const session = selected === NEW_SESSION_ID ? undefined : await getSession(selected);
if (selected !== NEW_SESSION_ID && !session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
const previous = session?.mapping ?? {};
const exclusions = session?.excludedTerms ?? [];
const raw = applyProjectWhitelist(text, await request(text, previous, entityTypes), previous, exclusions);
if (!raw.spans.length && raw.pseudonymized_text !== text) {
throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert.");
}
return { text, raw, previous, exclusions, selected };
const customTerms = session?.customTerms ?? [];
const raw = await analyzeText(text, bareMapping(previous), entityTypes, customTerms, exclusions, request);
return { text, raw, previous, exclusions, customTerms, selected, newSessionName: values.newSessionName };
}
/** Commit only the explicitly selected hits; rejected terms become context-specific exceptions. */
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false):
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false,
personMerges: Record<string, string> = {}):
Promise<{ result: PseudonymizeResponse; session: VelumSession }> {
const accepted = prepared.raw.spans.filter((_, index) => selectedHits.has(index));
const rejected = prepared.raw.spans.filter((_, index) => !selectedHits.has(index));
const spans = toUtf16Offsets(prepared.text, accepted).map((span, index) => ({ ...span, id: String(index) }));
const known = projectMapping(prepared.previous);
const preview = projectMapping(prepared.raw.mapping);
const known = bareMapping(prepared.previous);
const preview = { ...known, ...bareMapping(prepared.raw.mapping) };
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
const mapping: PlaceholderMapping = { ...known };
let mapping: PlaceholderMapping = { ...known };
for (const key of active) {
const entry = preview[key];
if (!entry) throw new Error(`Zuordnung für ${key} fehlt. Es wurde nichts gespeichert.`);
mapping[key] = entry;
if (entry.merged_into) {
const root = mappingRoot(key, preview);
mapping[key] = { ...entry, merged_into: root };
mapping[root] = preview[root];
}
}
const raw: PseudonymizeResponse = { ...prepared.raw, spans: accepted,
mapping, entity_count: active.size,
const selectedPeople = new Set(accepted.filter((span) => span.type === "PERSON")
.map((span) => mappingRoot(span.placeholder.replace(/^<|>$/g, ""), mapping)));
for (const [source, target] of Object.entries(personMerges)) {
if (!selectedPeople.has(source) || mapping[target]?.type !== "PERSON") {
throw new Error("Bitte nur ausgewählte Personen mit vorhandenen Zuordnungen zusammenfassen.");
}
mapping = mergeMappingGroups(mapping, source, target);
}
const mergedSpans = accepted.map((span) => {
if (span.type !== "PERSON") return span;
const key = span.placeholder.replace(/^<|>$/g, "");
const root = mappingRoot(key, mapping);
if (root === key) return span;
return { ...span, placeholder: span.placeholder.startsWith("<") ? `<${root}>` : root };
});
const spans = toUtf16Offsets(prepared.text, mergedSpans).map((span, index) => ({ ...span, id: String(index) }));
const raw: PseudonymizeResponse = { ...prepared.raw, spans: mergedSpans,
mapping, entity_count: new Set(mergedSpans.map((span) => span.placeholder.replace(/^<|>$/g, ""))).size,
pseudonymized_text: replaceSpans(prepared.text, spans, new Set(spans.map((span) => span.id))) };
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
const additions = rejected.map(({ type, original }) => ({ type, original }));
const exclusions = [...new Map([...prepared.exclusions, ...additions]
const acceptedKeys = new Set(accepted.map(({ type, original }) => termKey(type, original)));
const additions = rejected.filter(({ type, original }) => !acceptedKeys.has(termKey(type, original)))
.map(({ type, original }) => ({ type, original }));
const confirmedTerms = (prepared.addedTerms ?? []).filter(({ type, value }) => acceptedKeys.has(termKey(type, value)));
const confirmedKeys = new Set(confirmedTerms.map(({ type, value }) => termKey(type, value)));
const existingExclusions = prepared.exclusions.filter(({ type, original }) => !confirmedKeys.has(termKey(type, original)));
const exclusions = [...new Map([...existingExclusions, ...additions]
.map((item) => [whitelistKey(item), item])).values()];
if (prepared.projectPath) {
const path = prepared.projectPath;
@@ -119,23 +201,41 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
: !latest || JSON.stringify(latest.run.mapping) !== JSON.stringify(prepared.previous)) {
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
}
const updatedTerms = confirmedTerms.length ? mergeCustomTerms(await loadProjectRules(path), confirmedTerms) : undefined;
if (latest) {
await updateProjectMapping(path, () => mapping);
await updateProjectMapping(path, (current) => {
if (JSON.stringify(current) !== JSON.stringify(prepared.previous)) {
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
}
return mapping;
});
} else {
const created = await createRun(path);
created.run.mapping = mapping;
await saveRun(created.directory, created.run);
}
if (additions.length) await saveProjectWhitelist(path, exclusions);
if (updatedTerms) await saveProjectRules(path, updatedTerms);
if (additions.length || existingExclusions.length !== prepared.exclusions.length) {
await saveProjectWhitelist(path, exclusions);
}
return { result, session: resultSession(path, prepared.projectName ?? path,
mappingForRestoration(result.mapping), result.selected_entity_types) };
}
const session = prepared.selected === NEW_SESSION_ID ? await createSession() : await getSession(prepared.selected);
if (prepared.selected === NEW_SESSION_ID) {
const saved = await createSession(prepared.newSessionName, {
mapping: result.mapping, entityTypes: result.selected_entity_types, excludedTerms: exclusions, customTerms: confirmedTerms,
});
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
}
const session = await getSession(prepared.selected);
if (!session) throw new Error("Sitzung nicht gefunden. Bitte erneut analysieren.");
if (prepared.selected !== NEW_SESSION_ID && JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)) {
if (JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)
|| JSON.stringify(session.excludedTerms ?? []) !== JSON.stringify(prepared.exclusions)
|| JSON.stringify(session.customTerms ?? []) !== JSON.stringify(prepared.customTerms)) {
throw new Error("Die Sitzung wurde inzwischen geändert. Bitte erneut analysieren.");
}
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types, exclusions);
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types, exclusions,
confirmedTerms.length ? mergeCustomTerms(prepared.customTerms, confirmedTerms) : undefined);
await setActiveSession(saved.id);
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
}
@@ -169,7 +269,7 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
}))));
const raw = applyProjectWhitelist(text,
await request(text, latest?.run.mapping ?? {}, entityTypes, masks), latest?.run.mapping ?? {}, whitelist);
const mapping = projectMapping(raw.mapping);
const mapping = bareMapping(raw.mapping);
if (latest) {
await updateProjectMapping(path, (current) => {
if (JSON.stringify(current) !== JSON.stringify(latest.run.mapping)) {
@@ -188,10 +288,10 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
mappingForRestoration(resultMapping), result.selected_entity_types) };
}
const session = selected === NEW_SESSION_ID ? await createSession() : await getSession(selected);
const session = selected === NEW_SESSION_ID ? await createSession(values.newSessionName) : await getSession(selected);
if (!session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
await setActiveSession(session.id);
const raw = await request(text, session.mapping, entityTypes);
const raw = await request(text, bareMapping(session.mapping), entityTypes);
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types);
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };

View File

@@ -1,28 +1,129 @@
import { Action, ActionPanel, Icon, List, showToast, Toast } from "@raycast/api";
import {
Action,
ActionPanel,
Icon,
List,
showToast,
Toast,
useNavigation,
} from "@raycast/api";
import { useMemo, useState } from "react";
import { groupReviewHits } from "./lib/project-review";
import { commitPreparedText, type PreparedText } from "./text-context";
import type { PseudonymizeResponse, VelumSession } from "./types";
import { CustomTermForm } from "./custom-term-form";
import { mappingRoot } from "./lib/mapping-groups";
import {
canonicalPerson,
groupReviewHits,
mergePeople,
textHitContexts,
} from "./lib/project-review";
import { PersonMergeTargets } from "./person-merge-targets";
import {
addTextReviewTerm,
bareMapping,
commitPreparedText,
type PreparedText,
} from "./text-context";
import type {
CustomTerm,
EntityType,
PseudonymizeResponse,
VelumSession,
} from "./types";
export function TextHitReview(props: { prepared: PreparedText; forAi?: boolean;
onConfirmed: (result: PseudonymizeResponse, session: VelumSession) => Promise<void> | void }) {
export function TextHitReview(props: {
prepared: PreparedText;
entityTypes: EntityType[];
forAi?: boolean;
onConfirmed: (
result: PseudonymizeResponse,
session: VelumSession,
) => Promise<void> | void;
}) {
const { push } = useNavigation();
const [prepared, setPrepared] = useState(props.prepared);
const [selected, setSelected] = useState<Set<number>>(
() => new Set(props.prepared.raw.spans.map((_, index) => index)));
() => new Set(props.prepared.raw.spans.map((_, index) => index)),
);
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const groups = useMemo(() => groupReviewHits(props.prepared.raw.spans.map((span, index) => ({
...span, id: String(index),
}))), [props.prepared]);
const byType = new Map<string, typeof groups>();
for (const group of groups) {
if (!byType.has(group.type)) byType.set(group.type, []);
byType.get(group.type)!.push(group);
}
const { byType, people, personByHit } = useMemo(() => {
const { text, raw, previous } = prepared;
const contexts = textHitContexts(text, raw.spans);
const hits = raw.spans.map((span, index) => ({
...span,
id: String(index),
context: contexts[index],
}));
const groups = groupReviewHits(hits);
const byType = new Map<string, typeof groups>();
for (const group of groups) {
if (!byType.has(group.type)) byType.set(group.type, []);
byType.get(group.type)!.push(group);
}
const known = bareMapping(previous);
const mapping = { ...known, ...bareMapping(raw.mapping) };
const names = new Map<string, Set<string>>();
for (const [key, entry] of Object.entries(mapping)) {
if (entry.type !== "PERSON") continue;
const root = mappingRoot(key, mapping);
if (!names.has(root)) names.set(root, new Set([mapping[root].original]));
names.get(root)!.add(entry.original);
}
const personByHit = new Map<number, string>();
for (const [index, hit] of hits.entries()) {
if (hit.type !== "PERSON") continue;
const key = hit.placeholder.replace(/^<|>$/g, "");
if (!mapping[key]) continue;
const root = mappingRoot(key, mapping);
personByHit.set(index, root);
names.get(root)?.add(hit.original);
}
const people = [...names]
.map(([placeholder, originals]) => ({
placeholder,
originals: [...originals],
saved: Boolean(known[placeholder]),
}))
.sort((a, b) => a.originals[0].localeCompare(b.originals[0]));
return { byType, people, personByHit };
}, [prepared]);
const selectedPeople = new Set(
[...personByHit]
.filter(([index]) => selected.has(index))
.map(([, person]) => person),
);
const availablePeople = people.filter(
(person) => person.saved || selectedPeople.has(person.placeholder),
);
const availablePlaceholders = new Set(
availablePeople.map((person) => person.placeholder),
);
const activeMerges = Object.fromEntries(
Object.entries(personMerges).filter(
([source, target]) =>
selectedPeople.has(source) && availablePlaceholders.has(target),
),
);
const mergeTargets = availablePeople.filter(
({ placeholder }) => !activeMerges[placeholder],
);
async function confirm() {
if (busy) return;
setBusy(true);
const toast = await showToast({ style: Toast.Style.Animated, title: "Auswahl wird übernommen" });
const toast = await showToast({
style: Toast.Style.Animated,
title: "Auswahl wird übernommen",
});
try {
const { result, session } = await commitPreparedText(props.prepared, selected, props.forAi);
const { result, session } = await commitPreparedText(
prepared,
selected,
props.forAi,
activeMerges,
);
toast.style = Toast.Style.Success;
toast.title = "Auswahl übernommen";
toast.message = `${selected.size} Treffer bestätigt`;
@@ -31,42 +132,141 @@ export function TextHitReview(props: { prepared: PreparedText; forAi?: boolean;
toast.style = Toast.Style.Failure;
toast.title = "Auswahl nicht übernommen";
toast.message = error instanceof Error ? error.message : String(error);
} finally { setBusy(false); }
} finally {
setBusy(false);
}
}
function toggle(ids: number[]) {
setSelected((current) => {
const next = new Set(current);
const all = ids.every((id) => next.has(id));
for (const id of ids) { if (all) next.delete(id); else next.add(id); }
for (const id of ids) {
if (all) next.delete(id);
else next.add(id);
}
return next;
});
}
return <List isLoading={busy} isShowingDetail navigationTitle="Treffer vor Pseudonymisierung prüfen"
searchBarPlaceholder="Begriff, Kategorie oder Platzhalter suchen">
<List.Section title="Abschluss">
<List.Item icon={Icon.CheckCircle} title="Auswahl bestätigen"
subtitle={`${selected.size} von ${props.prepared.raw.spans.length} Treffern werden maskiert · Abgewählte werden als Ausnahme gespeichert`}
detail={<List.Item.Detail markdown="Prüfe die erkannten Begriffe unten. Klicke auf einen Treffer, um ihn ab- oder wieder anzuwählen. Erst mit **Auswahl bestätigen** werden die Zuordnungen gespeichert und der nächste Schritt gestartet." />}
actions={<ActionPanel><Action title="Auswahl bestätigen und fortfahren" icon={Icon.CheckCircle} onAction={confirm} /></ActionPanel>} />
</List.Section>
{[...byType].map(([type, typeGroups]) => <List.Section key={type} title={`${type} · ${typeGroups.length} Begriffe`}>
{typeGroups.map((group) => {
const ids = group.hits.map((hit) => Number(hit.id));
const all = ids.every((id) => selected.has(id));
const first = group.hits[0];
const start = Math.max(0, first.start - 90);
const end = Math.min([...props.prepared.text].length, first.end + 90);
const context = [...props.prepared.text].slice(start, end).join("");
return <List.Item key={group.key} icon={all ? Icon.CheckCircle : Icon.Circle}
title={`${group.original} → ${group.placeholder}`}
subtitle={group.hits.length > 1 ? `${group.hits.length} Vorkommen` : undefined}
detail={<List.Item.Detail markdown={`**Kontext**\n\n${context.replace(/`/g, "'")}`} />}
actions={<ActionPanel>
<Action title={all ? "Nicht maskieren" : "Maskieren"} icon={all ? Icon.XMarkCircle : Icon.CheckCircle}
onAction={() => toggle(ids)} />
<Action title="Auswahl bestätigen und fortfahren" icon={Icon.CheckCircle} onAction={confirm} />
</ActionPanel>} />;
})}
</List.Section>)}
</List>;
async function addTerm(term: CustomTerm) {
const updated = await addTextReviewTerm(prepared, term, selected);
setPrepared(updated.prepared);
setSelected(updated.selected);
}
const addTermAction = (
<Action.Push
title="Eigenen Begriff hinzufügen"
icon={Icon.Plus}
target={
<CustomTermForm entityTypes={props.entityTypes} onAdd={addTerm} />
}
/>
);
return (
<List
isLoading={busy}
isShowingDetail
navigationTitle="Treffer vor Pseudonymisierung prüfen"
searchBarPlaceholder="Begriff, Kategorie oder Platzhalter suchen"
>
<List.Section title="Abschluss">
<List.Item
id="confirm"
icon={Icon.CheckCircle}
title="Auswahl bestätigen"
subtitle={`${selected.size} von ${prepared.raw.spans.length} Treffern werden maskiert · Abgewählte werden als Ausnahme gespeichert`}
detail={
<List.Item.Detail markdown="Wähle einen Begriff aus, um seine Vorkommen zu sehen. Fehlende Treffer kannst du über **Eigenen Begriff hinzufügen** ergänzen. Mit **Auswahl bestätigen** speicherst du deine Änderungen." />
}
actions={
<ActionPanel>
<Action
title="Auswahl bestätigen und fortfahren"
icon={Icon.CheckCircle}
onAction={confirm}
/>
{addTermAction}
</ActionPanel>
}
/>
</List.Section>
{[...byType].map(([type, typeGroups]) => (
<List.Section
key={type}
title={`${type} · ${typeGroups.length} Begriffe`}
>
{typeGroups.map((group) => {
const ids = group.hits.map((hit) => Number(hit.id));
const all = ids.every((id) => selected.has(id));
const person = personByHit.get(ids[0]);
const canonical = person
? canonicalPerson(person, activeMerges)
: undefined;
return (
<List.Item
key={group.key}
id={`hit-${group.hits[0].start}-${group.hits[0].end}-${group.type}`}
icon={all ? Icon.CheckCircle : Icon.Circle}
title={`${group.original} → ${canonical ?? group.placeholder}`}
subtitle={
group.hits.length > 1
? `${group.hits.length} Vorkommen`
: undefined
}
detail={
<List.Item.Detail
markdown={group.hits.map((hit) => hit.context).join("\n\n")}
/>
}
actions={
<ActionPanel>
<Action
title={all ? "Nicht maskieren" : "Maskieren"}
icon={all ? Icon.XMarkCircle : Icon.CheckCircle}
onAction={() => toggle(ids)}
/>
{person && all && mergeTargets.length > 1 && (
<Action
title="Mit Person zusammenfassen"
icon={Icon.Link}
onAction={() =>
push(
<PersonMergeTargets
people={mergeTargets.filter(
({ placeholder }) => placeholder !== canonical,
)}
onChoose={(target) =>
setPersonMerges(
mergePeople(activeMerges, person, target),
)
}
/>,
)
}
/>
)}
{person && activeMerges[person] && (
<Action
title="Zusammenführung lösen"
onAction={() => {
const next = { ...activeMerges };
delete next[person];
setPersonMerges(next);
}}
/>
)}
<Action
title="Auswahl bestätigen und fortfahren"
icon={Icon.CheckCircle}
onAction={confirm}
/>
{addTermAction}
</ActionPanel>
}
/>
);
})}
</List.Section>
))}
</List>
);
}

View File

@@ -1,4 +1,5 @@
export type EntityType = string;
export type CustomTerm = { type: EntityType; value: string };
export type MappingEntry = {
original: string;
@@ -36,6 +37,7 @@ export type VelumSession = {
mapping: PlaceholderMapping;
entityTypes?: EntityType[];
excludedTerms?: Array<{ type: string; original: string }>;
customTerms?: CustomTerm[];
mappingCreatedAt?: Record<string, string>;
};

View File

@@ -1,7 +1,8 @@
import { expect, it } from "bun:test";
import {
canonicalPerson, filenameScanText, groupReviewHits, makeTextBatches, mappingForSelection, mergePeople, reconcileDocumentHitIds,
spansBySegment, withoutPlaceholderHits, withoutWhitelistedHits, withoutWhitelistedRules,
canonicalPerson, filenameScanText, groupReviewHits, highlightedReviewContext, literalReviewContext, makeTextBatches, mappingForSelection,
mergePeople, reconcileDocumentHitIds, spansBySegment, textHitContexts, withoutPlaceholderHits, withoutWhitelistedHits,
withoutWhitelistedRules,
} from "../src/lib/project-review";
it("liest Unterstriche in Namen als Leerzeichen und bewahrt bekannte Codebegriffe", () => {
@@ -45,6 +46,32 @@ it("zeigt gleiche Zuordnungen einmal mit der Anzahl ihrer Vorkommen", () => {
expect(groups.find((group) => group.placeholder === "PERSON_01")?.hits.map((hit) => hit.id)).toEqual(["a", "b"]);
});
it("ordnet E-Mail-Vorkommen nach Unicode-Position zu und markiert jeweils genau den ausgewählten Treffer", () => {
const [signature, sender, recipient] = textHitContexts("😀 Von: Max\nAn: Mia\nDanke, Max", [
{ start: 26, end: 29 }, { start: 7, end: 10 }, { start: 15, end: 18 },
]);
const max = String.raw`\(\textcolor{#dc2626}{\text{Max}}\)`;
const mia = String.raw`\(\textcolor{#dc2626}{\text{Mia}}\)`;
expect(signature).toContain("**Zeile 3**");
expect(signature).toContain(`Danke&#44; ${max}`);
expect(sender).toContain("**Zeile 1**");
expect(sender).toContain(`&#128512; Von&#58; ${max}`);
expect(recipient).toContain("**Zeile 2**");
expect(recipient).toContain(`An&#58; ${mia}`);
const source = ["**Von:** <max@example.com>", "```", "![Bild](https://example.com/image.png)"].join("\n");
expect(literalReviewContext(source)).toBe(["````", source, "````"].join("\n"));
expect(highlightedReviewContext("😀 Max, Max", 8, 3)).toBe(`&#128512; Max&#44; ${max}`);
});
it("zeigt Markdown-Sonderzeichen wörtlich und färbt mehrzeilige Treffer an ihrer Fundstelle", () => {
const before = "![Bild](https://example.com/)\n";
const match = String.raw`A\){#}&` + "\nB_20%";
const context = highlightedReviewContext(before + match, before.length, match.length);
expect(context).not.toContain("![");
expect(context).toContain(String.raw`\text{A\textbackslash{})\{\#\}\&}`);
expect(context).toContain(String.raw`\text{B\_20\%}`);
});
it("ordnet bestätigte Dokumenttreffer nach einem 409 nur bei identischem Vorkommen neu zu", () => {
const hit = { id: "alt", source: "Absatz 1", start: 4, end: 7, type: "PERSON",
original: "Max", context: "Herr Max antwortet" };

View File

@@ -16,7 +16,7 @@ mock.module("@raycast/api", () => ({
getPreferenceValues: () => ({ velumBaseUrl: "", authentikTokenUrl: "", clientId: "",
serviceAccountUsername: "", serviceAccountPassword: "", maxSessions: "20" }),
}));
const { applyProjectWhitelist, pseudonymizeInContext, prepareTextInContext, commitPreparedText } = await import("../src/text-context");
const { addTextReviewTerm, applyProjectWhitelist, pseudonymizeInContext, prepareTextInContext, commitPreparedText } = await import("../src/text-context");
const project = await import("../src/lib/velum-project");
const sessions = await import("../src/sessions");
const { relocateProject } = await import("../src/lib/project-relocation");
@@ -91,12 +91,14 @@ it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht er
spans: [{ start: 0, end: 11, type: "PERSON", score: 0.8,
placeholder: "PERSON_01", original: "Fachbegriff" }],
});
const prepared = await prepareTextInContext({ sessionId: "__new_session__" },
const prepared = await prepareTextInContext({ sessionId: "__new_session__", newSessionName: " Kundenmail " },
"Fachbegriff", ["PERSON"], request);
expect(await sessions.listSessions()).toHaveLength(0);
const { result, session } = await commitPreparedText(prepared, new Set());
expect(result.pseudonymized_text).toBe("Fachbegriff");
expect(session.name).toBe("Kundenmail");
expect(session.mapping).toEqual({});
expect(await sessions.getActiveSessionId()).toBe(session.id);
expect((await sessions.getSession(session.id))?.excludedTerms).toEqual([
{ type: "PERSON", original: "Fachbegriff" },
]);
@@ -104,6 +106,102 @@ it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht er
expect(next.raw.spans).toEqual([]);
});
it.each(["session", "project"])("ergänzt eigene Begriffe auch bei abgewählter Kategorie und merkt sie für Folgeläufe (%s)", async (context) => {
const values = { sessionId: "__new_session__", newProjectPath: [] as string[] };
if (context === "project") {
const root = await fs.mkdtemp(join(tmpdir(), "velum-custom-term-"));
roots.push(root);
const folder = join(root, "Projekt");
await fs.mkdir(folder);
roots.push(project.projectDataRoot(folder));
values.sessionId = "__new_project__";
values.newProjectPath = [folder];
}
const text = "Max, 4711, 2025, 4711";
const term = { type: "REFERENZ", value: "4711" };
const request: typeof import("../src/velum").pseudonymize = async (_text, mapping, types, masks) => {
expect(types).toEqual(masks ? ["PERSON", "REFERENZ"] : ["PERSON"]);
if (masks) expect(masks).toEqual({ REFERENZ: ["4711"] });
const spans = [{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" }];
if (masks) spans.push(
{ start: 5, end: 9, type: "REFERENZ", score: 1, placeholder: "REFERENZ_01", original: "4711" },
{ start: 11, end: 15, type: "REFERENZ", score: 1, placeholder: "REFERENZ_02", original: "2025" },
{ start: 17, end: 21, type: "REFERENZ", score: 1, placeholder: "REFERENZ_01", original: "4711" },
);
return {
spans, selected_entity_types: types ?? [], entity_count: masks ? 3 : 1,
mapping: { ...mapping, PERSON_01: { type: "PERSON", original: "Max" },
...(masks && { REFERENZ_01: { type: "REFERENZ", original: "4711" },
REFERENZ_02: { type: "REFERENZ", original: "2025" } }) },
pseudonymized_text: masks ? "PERSON_01, REFERENZ_01, REFERENZ_02, REFERENZ_01" : "PERSON_01, 4711, 2025, 4711",
};
};
const initial = await prepareTextInContext(values, text, ["PERSON"], request);
const updated = await addTextReviewTerm(initial, term, new Set(), request);
expect([...updated.selected]).toEqual([1, 2]);
expect(await sessions.listSessions()).toHaveLength(0);
if (context === "project") expect(await project.loadProjectRules(values.newProjectPath[0])).toEqual([]);
const { result, session } = await commitPreparedText(updated.prepared, updated.selected, true);
expect(result.pseudonymized_text).toBe("Max, <REFERENZ_01>, 2025, <REFERENZ_01>");
expect(result.selected_entity_types).toEqual(["PERSON"]);
const followup = await prepareTextInContext({ sessionId: session.id }, text, ["PERSON"], request);
expect(followup.raw.spans.map((span) => span.original)).toEqual(["4711", "4711"]);
expect(followup.customTerms).toEqual([term]);
});
it.each(["session", "project"])("fasst geprüfte Namensvarianten zusammen und speichert sie für Folgeläufe (%s)", async (context) => {
let values = { sessionId: "__new_session__", newProjectPath: [] as string[] };
if (context === "project") {
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-merge-"));
roots.push(root);
const folder = join(root, "Projekt");
await fs.mkdir(folder);
values = { sessionId: "__new_project__", newProjectPath: [folder] };
}
const source = "😀 Max Muster\nMax und Mia";
const prepared = await prepareTextInContext(values, source, ["PERSON"], async () => ({
pseudonymized_text: "😀 PERSON_01\nPERSON_02 und PERSON_03",
selected_entity_types: ["PERSON"], entity_count: 3,
mapping: {
PERSON_01: { type: "PERSON", original: "Max Muster" },
PERSON_02: { type: "PERSON", original: "Max" },
PERSON_03: { type: "PERSON", original: "Mia" },
},
spans: [
{ start: 2, end: 12, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max Muster" },
{ start: 13, end: 16, type: "PERSON", score: 1, placeholder: "PERSON_02", original: "Max" },
{ start: 21, end: 24, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Mia" },
],
}));
await expect(commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_03" }))
.rejects.toThrow("ausgewählte Personen");
const { result, session } = await commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_01" });
expect(result.pseudonymized_text).toBe("😀 <PERSON_01>\n<PERSON_01> und Mia");
expect(result.entity_count).toBe(1);
expect(result.spans.map((span) => span.placeholder)).toEqual(["PERSON_01", "PERSON_01"]);
expect(result.mapping["<PERSON_02>"]).toEqual({ type: "PERSON", original: "Max", merged_into: "<PERSON_01>" });
expect(result.mapping["<PERSON_03>"]).toBeUndefined();
expect(session.mapping["<PERSON_02>"].original).toBe("Max Muster");
const followup = await prepareTextInContext({ sessionId: session.id }, "Max und Maximilian", ["PERSON"],
async (_text, mapping) => {
expect(mapping.PERSON_02.merged_into).toBe("PERSON_01");
expect(mapping["<PERSON_02>"]).toBeUndefined();
return {
pseudonymized_text: "PERSON_01 und PERSON_03", selected_entity_types: ["PERSON"], entity_count: 2,
mapping: { ...mapping, PERSON_03: { type: "PERSON", original: "Maximilian" } },
spans: [
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
{ start: 8, end: 18, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Maximilian" },
],
};
});
const updated = await commitPreparedText(followup, new Set([0, 1]), false, { PERSON_01: "PERSON_03" });
expect(updated.result.pseudonymized_text).toBe("PERSON_03 und PERSON_03");
expect(updated.result.mapping.PERSON_02.merged_into).toBe("PERSON_03");
expect(updated.session.mapping.PERSON_02.original).toBe("Maximilian");
});
it("entfernt eine False-Positive-Gruppe aus der Sitzung und merkt alle Varianten", async () => {
const session = await sessions.createSession("Test");
await sessions.updateSessionMapping(session.id, {

View File

@@ -22,9 +22,13 @@ describe("Velum-Projektstände", () => {
const support = join(root, "Raycast");
await fs.mkdir(source);
await fs.writeFile(join(source, "Notiz.txt"), "Max Mustermann");
const rules = project.parseProjectRules("PERSON: Max Mustermann\nKundenSuite");
const rules = project.parseProjectRules("PERSON: Max Mustermann\nKundenSuite\nREFERENZ: 4711",
["BEGRIFF", "PERSON", "REFERENZ"]);
await project.saveProjectRules(source, rules, support);
expect(await project.loadProjectRules(source, support)).toEqual(rules);
expect(project.forceMasks(rules)).toEqual({
PERSON: ["Max Mustermann"], BEGRIFF: ["KundenSuite"], REFERENZ: ["4711"],
});
await project.saveProjectWhitelist(source, [
{ type: "PERSON", original: "Falscher Treffer" },
{ type: "PERSON", original: "falscher treffer" },