1 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
27 changed files with 537 additions and 410 deletions

View File

@@ -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

@@ -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}

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

@@ -129,6 +129,34 @@ export function literalReviewContext(text: string): string {
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);
@@ -147,7 +175,7 @@ export function textHitContexts(text: string, spans: Array<{ start: number; end:
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${literalReviewContext(`${before}⟦${match}⟧${after}`)}`;
contexts[index] = `**Zeile ${line}**\n\n${highlightedReviewContext(before + match + after, before.length, match.length)}`;
}
return contexts;
}

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

@@ -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, literalReviewContext, 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 {
@@ -62,9 +63,24 @@ function OccurrenceReview(props: { original: string; placeholder: string; hits:
{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} id={hit.id} title={hit.file} subtitle={hit.source === hit.file ? "Dateiinhalt" : hit.source}
detail={<List.Item.Detail markdown={literalReviewContext(hit.context)} />} />)}
{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>;
}
@@ -531,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 });
@@ -545,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;
@@ -561,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} />} />
@@ -573,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

@@ -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) => {
push(
<ConfirmReply
session={updatedSession}

View File

@@ -66,7 +66,7 @@ export async function setActiveSession(id: string): Promise<void> {
}
export async function createSession(name?: string,
initial?: Pick<VelumSession, "mapping" | "entityTypes" | "excludedTerms">): Promise<VelumSession> {
initial?: Pick<VelumSession, "mapping" | "entityTypes" | "excludedTerms" | "customTerms">): Promise<VelumSession> {
const timestamp = nowIso();
const session: VelumSession = {
id: randomUUID(),
@@ -106,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();
@@ -120,6 +121,7 @@ export async function updateSessionMapping(
mapping,
entityTypes,
excludedTerms,
customTerms,
mappingCreatedAt: mappingDates(undefined, mapping, timestamp),
};
await saveSessions([created, ...sessions]);
@@ -131,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,
};
@@ -193,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

@@ -137,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}

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,11 +1,12 @@
import { promises as fs } from "node:fs";
import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules,
loadProjectWhitelist, replaceSpans, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project";
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";
@@ -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,12 +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> {
@@ -69,26 +131,19 @@ 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, bareMapping(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, newSessionName: values.newSessionName };
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. */
@@ -131,8 +186,13 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
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;
@@ -141,6 +201,7 @@ 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, (current) => {
if (JSON.stringify(current) !== JSON.stringify(prepared.previous)) {
@@ -153,23 +214,28 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
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) };
}
if (prepared.selected === NEW_SESSION_ID) {
const saved = await createSession(prepared.newSessionName, {
mapping: result.mapping, entityTypes: result.selected_entity_types, excludedTerms: exclusions,
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 (JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)
|| JSON.stringify(session.excludedTerms ?? []) !== JSON.stringify(prepared.exclusions)) {
|| 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) } };
}

View File

@@ -8,6 +8,7 @@ import {
useNavigation,
} from "@raycast/api";
import { useMemo, useState } from "react";
import { CustomTermForm } from "./custom-term-form";
import { mappingRoot } from "./lib/mapping-groups";
import {
canonicalPerson,
@@ -17,14 +18,21 @@ import {
} from "./lib/project-review";
import { PersonMergeTargets } from "./person-merge-targets";
import {
addTextReviewTerm,
bareMapping,
commitPreparedText,
type PreparedText,
} from "./text-context";
import type { PseudonymizeResponse, VelumSession } from "./types";
import type {
CustomTerm,
EntityType,
PseudonymizeResponse,
VelumSession,
} from "./types";
export function TextHitReview(props: {
prepared: PreparedText;
entityTypes: EntityType[];
forAi?: boolean;
onConfirmed: (
result: PseudonymizeResponse,
@@ -32,13 +40,14 @@ export function TextHitReview(props: {
) => 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)),
);
const [personMerges, setPersonMerges] = useState<Record<string, string>>({});
const [busy, setBusy] = useState(false);
const { byType, people, personByHit } = useMemo(() => {
const { text, raw, previous } = props.prepared;
const { text, raw, previous } = prepared;
const contexts = textHitContexts(text, raw.spans);
const hits = raw.spans.map((span, index) => ({
...span,
@@ -78,7 +87,7 @@ export function TextHitReview(props: {
}))
.sort((a, b) => a.originals[0].localeCompare(b.originals[0]));
return { byType, people, personByHit };
}, [props.prepared]);
}, [prepared]);
const selectedPeople = new Set(
[...personByHit]
@@ -110,7 +119,7 @@ export function TextHitReview(props: {
});
try {
const { result, session } = await commitPreparedText(
props.prepared,
prepared,
selected,
props.forAi,
activeMerges,
@@ -138,6 +147,20 @@ export function TextHitReview(props: {
return next;
});
}
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}
@@ -150,9 +173,9 @@ export function TextHitReview(props: {
id="confirm"
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`}
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. Über das Aktionsmenü einer Person kannst du Namensvarianten zusammenfassen. Mit **Auswahl bestätigen** speicherst du deine Änderungen." />
<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>
@@ -161,6 +184,7 @@ export function TextHitReview(props: {
icon={Icon.CheckCircle}
onAction={confirm}
/>
{addTermAction}
</ActionPanel>
}
/>
@@ -180,7 +204,7 @@ export function TextHitReview(props: {
return (
<List.Item
key={group.key}
id={`hit-${ids[0]}`}
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={
@@ -235,6 +259,7 @@ export function TextHitReview(props: {
icon={Icon.CheckCircle}
onAction={confirm}
/>
{addTermAction}
</ActionPanel>
}
/>

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,6 +1,6 @@
import { expect, it } from "bun:test";
import {
canonicalPerson, filenameScanText, groupReviewHits, literalReviewContext, makeTextBatches, mappingForSelection,
canonicalPerson, filenameScanText, groupReviewHits, highlightedReviewContext, literalReviewContext, makeTextBatches, mappingForSelection,
mergePeople, reconcileDocumentHitIds, spansBySegment, textHitContexts, withoutPlaceholderHits, withoutWhitelistedHits,
withoutWhitelistedRules,
} from "../src/lib/project-review";
@@ -50,14 +50,26 @@ it("ordnet E-Mail-Vorkommen nach Unicode-Position zu und markiert jeweils genau
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, ⟦Max⟧");
expect(signature).toContain(`Danke&#44; ${max}`);
expect(sender).toContain("**Zeile 1**");
expect(sender).toContain("😀 Von: ⟦Max⟧");
expect(sender).toContain(`&#128512; Von&#58; ${max}`);
expect(recipient).toContain("**Zeile 2**");
expect(recipient).toContain("An: ⟦Mia⟧");
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", () => {

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");
@@ -106,6 +106,49 @@ 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") {

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" },