diff --git a/README.md b/README.md index 6a38e6c..f0296ac 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/package.json b/package.json index 8faba1f..40ca30e 100644 --- a/package.json +++ b/package.json @@ -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" }, { diff --git a/src/briefing-from-notes.tsx b/src/briefing-from-notes.tsx index 12fee78..028c7ef 100644 --- a/src/briefing-from-notes.tsx +++ b/src/briefing-from-notes.tsx @@ -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( { + push( { push( void | Promise; +}) { + const { pop } = useNavigation(); + const [busy, setBusy] = useState(false); + const [error, setError] = useState(); + + 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 ( +
+ + + } + > + setError(undefined)} + /> + + {props.entityTypes.map((type) => ( + + ))} + + + ); +} diff --git a/src/extract-action-items.tsx b/src/extract-action-items.tsx index 713e420..252a432 100644 --- a/src/extract-action-items.tsx +++ b/src/extract-action-items.tsx @@ -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( { + push( { push( { + push( { const schema = values.schema; const format = values.format; const buildPrompt = (pseudonymizedText: string, instructions: string) => diff --git a/src/lib/local-docx.ts b/src/lib/local-docx.ts index 819c331..1676a83 100644 --- a/src/lib/local-docx.ts +++ b/src/lib/local-docx.ts @@ -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; } diff --git a/src/lib/project-analysis.ts b/src/lib/project-analysis.ts index c391b27..0a76838 100644 --- a/src/lib/project-analysis.ts +++ b/src/lib/project-analysis.ts @@ -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 }); } } } diff --git a/src/lib/project-review.ts b/src/lib/project-review.ts index 7d91a55..8eb25a4 100644 --- a/src/lib/project-review.ts +++ b/src/lib/project-review.ts @@ -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) => " " + " ".repeat(spaces.length - 1)) + .replace(/\r\n?|\n/g, " \n"); +} + +const latexTextEscapes: Record = { + "\\": "\\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; } diff --git a/src/lib/project-revision.ts b/src/lib/project-revision.ts index 7239f6c..11d9e5d 100644 --- a/src/lib/project-revision.ts +++ b/src/lib/project-revision.ts @@ -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; diff --git a/src/lib/project-work.ts b/src/lib/project-work.ts index 72ecd86..fda556d 100644 --- a/src/lib/project-work.ts +++ b/src/lib/project-work.ts @@ -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; 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, 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"); diff --git a/src/lib/velum-project.ts b/src/lib/velum-project.ts index 056f3d4..343d075 100644 --- a/src/lib/velum-project.ts +++ b/src/lib/velum-project.ts @@ -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; - 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 { 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 { @@ -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; diff --git a/src/manage-sessions.tsx b/src/manage-sessions.tsx deleted file mode 100644 index 773613c..0000000 --- a/src/manage-sessions.tsx +++ /dev/null @@ -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([]); - const [activeSessionId, setActiveSessionId] = useState(); - 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 ( - - - } - /> - - } - /> - {sessions.map((session) => ( - - { - const updated = await releaseSessionMappingGroup(session.id, root); - await reload(); - return updated.mapping; - }} />} - /> - activate(session)} - /> - } - /> - } - /> - } - /> - clearMapping(session)} - /> - remove(session)} - /> - - - } - /> - ))} - - ); -} - -function SessionNameForm({ - session, - onSaved, -}: { - session?: VelumSession; - onSaved: () => Promise; -}) { - 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 ( -
- - - } - > - - - ); -} - -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 ; -} diff --git a/src/project-status.tsx b/src/project-status.tsx index d6deae0..21b0991 100644 --- a/src/project-status.tsx +++ b/src/project-status.tsx @@ -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( { + push( { push( setPage(page + 1)} />} {page > 0 && setPage(page - 1)} />} } />} - {props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => } />)} + {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 + + : undefined} />} />; + })} ; } @@ -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(); } catch (error) { toast.style = Toast.Style.Failure; @@ -561,6 +578,12 @@ export default function Command() { } return
+ {availableTypes.length > 0 && { + 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])]); + }} />} />} } /> @@ -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“."} /> + info="Ein Begriff pro Zeile. Ohne Typ wird BEGRIFF verwendet. Die Kategorien der Projektbegriffe werden für die Analyse aktiviert." /> {availableTypes.map((type) => )} diff --git a/src/pseudonymize-text.tsx b/src/pseudonymize-text.tsx index e6a180a..857c1ee 100644 --- a/src/pseudonymize-text.tsx +++ b/src/pseudonymize-text.tsx @@ -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( { + push( { if (props.autoOutput) { const paste = props.forcePaste || getPreferences().quickOutput === "paste"; try { diff --git a/src/reply-email.tsx b/src/reply-email.tsx index e501dc2..88e05d8 100644 --- a/src/reply-email.tsx +++ b/src/reply-email.tsx @@ -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( { + push( { push( { } export async function createSession(name?: string, - initial?: Pick): Promise { + initial?: Pick): Promise { 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 { 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 { await LocalStorage.removeItem(SESSIONS_STORAGE_KEY); await LocalStorage.removeItem(ACTIVE_SESSION_STORAGE_KEY); } - -export function countMappingEntries(mapping: PlaceholderMapping): number { - return Object.keys(mapping).length; -} diff --git a/src/show-translation-tables.tsx b/src/show-translation-tables.tsx index e4553d5..cc8b918 100644 --- a/src/show-translation-tables.tsx +++ b/src/show-translation-tables.tsx @@ -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([]); - const [sessions, setSessions] = useState([]); + const [sessions, setSessions] = useState([]); + const [activeSessionId, setActiveSessionId] = useState(); const [busy, setBusy] = useState(true); - const refresh = useCallback(async () => { - await Promise.all([listAllRuns(), listSessions()]) - .then(([runs, savedSessions]) => { - const history = new Map(); - 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(); + 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, 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, success: string) { + if (busy) return; + if (await confirmAlert({ title: `${title}?`, message, + primaryAction: { title, style: Alert.ActionStyle.Destructive } })) { + await changeSessions(action, success); + } + } + + const newSessionAction = } />; return ( {newSessionAction}} /> {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; }} /> } /> } /> + target={} /> } /> @@ -349,9 +385,11 @@ export default function Command() { {sessions.map((source) => ( { 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; }} /> } /> + + {source.id !== activeSessionId && changeSessions(() => setActiveSession(source.id), "Aktive Sitzung geändert")} />} + } /> + } /> + {newSessionAction} + + + confirmSessionChange("Zuordnungen leeren", + `Alle Platzhalter-Zuordnungen aus „${source.name}“ werden gelöscht.`, + () => clearSessionMapping(source.id), "Zuordnungen geleert")} /> + confirmSessionChange("Sitzung löschen", + `„${source.name}“ und ihre Zuordnungen werden gelöscht.`, + () => deleteSession(source.id), "Sitzung gelöscht")} /> + confirmSessionChange("Alle Sitzungen löschen", + "Alle gespeicherten Sitzungen und ihre Zuordnungen werden gelöscht.", + deleteAllSessions, "Alle Sitzungen gelöscht")} /> + } /> ))} + {newSessionAction}} /> ); } + +function SessionNameForm({ session, onSaved }: { session?: VelumSession; onSaved: () => Promise }) { + 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 }> + + ; +} + +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 ; +} diff --git a/src/summarize-email.tsx b/src/summarize-email.tsx index 864fd45..a408524 100644 --- a/src/summarize-email.tsx +++ b/src/summarize-email.tsx @@ -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( { + push( { push( { + push( { push( 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, request: typeof pseudonymize = pseudonymize): + Promise<{ prepared: PreparedText; selected: Set }> { + 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(); + 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 { @@ -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) } }; } diff --git a/src/text-hit-review.tsx b/src/text-hit-review.tsx index f3621d8..c042ff5 100644 --- a/src/text-hit-review.tsx +++ b/src/text-hit-review.tsx @@ -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; }) { const { push } = useNavigation(); + const [prepared, setPrepared] = useState(props.prepared); const [selected, setSelected] = useState>( () => new Set(props.prepared.raw.spans.map((_, index) => index)), ); const [personMerges, setPersonMerges] = useState>({}); 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 = ( + + } + /> + ); return ( + } actions={ @@ -161,6 +184,7 @@ export function TextHitReview(props: { icon={Icon.CheckCircle} onAction={confirm} /> + {addTermAction} } /> @@ -180,7 +204,7 @@ export function TextHitReview(props: { return ( + {addTermAction} } /> diff --git a/src/types.ts b/src/types.ts index 3ed05fd..0fa45da 100644 --- a/src/types.ts +++ b/src/types.ts @@ -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; }; diff --git a/tests/project-review.test.ts b/tests/project-review.test.ts index b4e0d9e..4f977f3 100644 --- a/tests/project-review.test.ts +++ b/tests/project-review.test.ts @@ -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, ${max}`); expect(sender).toContain("**Zeile 1**"); - expect(sender).toContain("😀 Von: ⟦Max⟧"); + expect(sender).toContain(`😀 Von: ${max}`); expect(recipient).toContain("**Zeile 2**"); - expect(recipient).toContain("An: ⟦Mia⟧"); + expect(recipient).toContain(`An: ${mia}`); const source = ["**Von:** ", "```", "![Bild](https://example.com/image.png)"].join("\n"); expect(literalReviewContext(source)).toBe(["````", source, "````"].join("\n")); + expect(highlightedReviewContext("😀 Max, Max", 8, 3)).toBe(`😀 Max, ${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", () => { diff --git a/tests/text-context.test.ts b/tests/text-context.test.ts index 0c23d0e..3040f5c 100644 --- a/tests/text-context.test.ts +++ b/tests/text-context.test.ts @@ -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, , 2025, "); + 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") { diff --git a/tests/velum-project.test.ts b/tests/velum-project.test.ts index a3a5374..42700f2 100644 --- a/tests/velum-project.test.ts +++ b/tests/velum-project.test.ts @@ -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" },