feat: improve Velum hit review and session creation

This commit is contained in:
muena
2026-12-02 08:53:37 +01:00
parent 96d5f3f57d
commit 019f6b6d7c
10 changed files with 467 additions and 95 deletions

View File

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

View File

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

View File

@@ -121,6 +121,37 @@ export function groupReviewHits<T extends GroupableHit>(hits: T[]): ReviewGroup<
return [...groups.values()].sort((a, b) => a.type.localeCompare(b.type) || a.original.localeCompare(b.original)); return [...groups.values()].sort((a, b) => a.type.localeCompare(b.type) || a.original.localeCompare(b.original));
} }
/** Render source text literally, even if it contains Markdown or HTML. */
export function literalReviewContext(text: string): string {
let longestRun = 2;
for (const [run] of text.matchAll(/`+/g)) longestRun = Math.max(longestRun, run.length);
const fence = "`".repeat(longestRun + 1);
return `${fence}\n${text}\n${fence}`;
}
/** Text API positions count Unicode code points. Mark the exact occurrence in each snippet. */
export function textHitContexts(text: string, spans: Array<{ start: number; end: number }>): string[] {
const characters = Array.from(text);
const contexts: string[] = [];
let cursor = 0;
let line = 1;
for (const { span, index } of spans.map((span, index) => ({ span, index })).sort((a, b) => a.span.start - b.span.start)) {
const { start, end } = span;
if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || start >= end || end > characters.length) {
contexts[index] = "Ungültige Trefferposition der Velum-API.";
continue;
}
for (; cursor < start; cursor++) {
if (characters[cursor] === "\n" || (characters[cursor] === "\r" && characters[cursor + 1] !== "\n")) line++;
}
const before = characters.slice(Math.max(0, start - 90), start).join("");
const match = characters.slice(start, end).join("");
const after = characters.slice(end, end + 90).join("");
contexts[index] = `**Zeile ${line}**\n\n${literalReviewContext(`${before}⟦${match}⟧${after}`)}`;
}
return contexts;
}
export function withoutWhitelistedHits<T extends GroupableHit>(hits: T[], whitelist: ProjectWhitelistEntry[]): T[] { export function withoutWhitelistedHits<T extends GroupableHit>(hits: T[], whitelist: ProjectWhitelistEntry[]): T[] {
const excluded = new Set(whitelist.map(whitelistKey)); const excluded = new Set(whitelist.map(whitelistKey));
return hits.filter((hit) => !excluded.has(whitelistKey(hit))); return hits.filter((hit) => !excluded.has(whitelistKey(hit)));

View File

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

View File

@@ -12,7 +12,7 @@ import {
saveProjectWhitelist, scanProjectFiles, whitelistKey, withoutExcludedProjectFiles, saveProjectWhitelist, scanProjectFiles, whitelistKey, withoutExcludedProjectFiles,
} from "./lib/velum-project"; } from "./lib/velum-project";
import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, SkippedProjectFile } from "./lib/velum-project"; import type { ProjectFile, ProjectRule, ProjectWhitelistEntry, SkippedProjectFile } from "./lib/velum-project";
import { canonicalPerson, groupReviewHits, mergePeople } from "./lib/project-review"; import { canonicalPerson, groupReviewHits, literalReviewContext, mergePeople } from "./lib/project-review";
import { checkedImagePolicy, DEFAULT_IMAGE_POLICY, IMAGE_POLICY_LABELS, KEEP_IMAGE_WARNING } from "./lib/image-policy"; import { checkedImagePolicy, DEFAULT_IMAGE_POLICY, IMAGE_POLICY_LABELS, KEEP_IMAGE_WARNING } from "./lib/image-policy";
import type { ImagePolicy } from "./lib/image-policy"; import type { ImagePolicy } from "./lib/image-policy";
import { import {
@@ -20,6 +20,7 @@ import {
} from "./lib/project-jobs"; } from "./lib/project-jobs";
import type { ProjectJobState } from "./lib/project-jobs"; import type { ProjectJobState } from "./lib/project-jobs";
import type { Hit, Preview } from "./lib/project-work"; import type { Hit, Preview } from "./lib/project-work";
import { PersonMergeTargets } from "./person-merge-targets";
const run = promisify(execFile); const run = promisify(execFile);
const REVIEW_PAGE_SIZE = 200; const REVIEW_PAGE_SIZE = 200;
@@ -57,34 +58,13 @@ function OccurrenceReview(props: { original: string; placeholder: string; hits:
const [page, setPage] = useState(0); const [page, setPage] = useState(0);
const pages = Math.ceil(props.hits.length / REVIEW_PAGE_SIZE); const pages = Math.ceil(props.hits.length / REVIEW_PAGE_SIZE);
return <List isShowingDetail navigationTitle={`${props.original} → ${props.placeholder}`}> return <List isShowingDetail navigationTitle={`${props.original} → ${props.placeholder}`}>
{pages > 1 && <List.Item title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel> {pages > 1 && <List.Item id="page" title={`Vorkommen · Seite ${page + 1}/${pages}`} actions={<ActionPanel>
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />} {page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />} {page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
</ActionPanel>} />} </ActionPanel>} />}
{props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => <List.Item key={hit.id} title={hit.source} {props.hits.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((hit) => <List.Item
subtitle={hit.kind === "path" ? "Datei- oder Ordnername" : "Dateiinhalt"} key={hit.id} id={hit.id} title={hit.file} subtitle={hit.source === hit.file ? "Dateiinhalt" : hit.source}
detail={<List.Item.Detail markdown={hit.context.replace(/</g, "&lt;")} />} />)} detail={<List.Item.Detail markdown={literalReviewContext(hit.context)} />} />)}
</List>;
}
function PersonMergeTargets(props: { people: Array<{ placeholder: string; originals: string[] }>;
onChoose: (placeholder: string) => void }) {
const { pop } = useNavigation();
const [query, setQuery] = useState("");
const [page, setPage] = useState(0);
const matching = props.people.filter((person) => `${person.originals.join(" ")} ${person.placeholder}`
.toLowerCase().includes(query.trim().toLowerCase()));
const pages = Math.max(1, Math.ceil(matching.length / REVIEW_PAGE_SIZE));
return <List navigationTitle="Zusammenführen mit" filtering={false} searchText={query}
onSearchTextChange={(value) => { setQuery(value); setPage(0); }}>
{pages > 1 && <List.Item title={`Seite ${page + 1}/${pages}`} actions={<ActionPanel>
{page + 1 < pages && <Action title="Nächste Seite" onAction={() => setPage(page + 1)} />}
{page > 0 && <Action title="Vorherige Seite" onAction={() => setPage(page - 1)} />}
</ActionPanel>} />}
{matching.slice(page * REVIEW_PAGE_SIZE, (page + 1) * REVIEW_PAGE_SIZE).map((person) =>
<List.Item key={person.placeholder} title={person.originals.join(" · ")} subtitle={person.placeholder}
actions={<ActionPanel><Action title="Personen zusammenfassen" icon={Icon.Link}
onAction={() => { props.onChoose(person.placeholder); pop(); }} /></ActionPanel>} />)}
</List>; </List>;
} }
@@ -251,7 +231,7 @@ function HitReview(props: { root: string; rules: ProjectRule[]; whitelist: Proje
</List.Section>} </List.Section>}
{[...byType].map(([type, entries]) => <List.Section key={type} {[...byType].map(([type, entries]) => <List.Section key={type}
title={`${labelForType(type)} · ${groups.filter((entry) => entry.type === type && selectedGroups.has(entry.key)).length}/${groups.filter((entry) => entry.type === type).length}`}> title={`${labelForType(type)} · ${groups.filter((entry) => entry.type === type && selectedGroups.has(entry.key)).length}/${groups.filter((entry) => entry.type === type).length}`}>
{entries.map((group) => <List.Item key={group.key} {entries.map((group) => <List.Item key={group.key} id={group.hits[0].id}
icon={{ source: selectedGroups.has(group.key) ? Icon.CheckCircle : Icon.Circle, icon={{ source: selectedGroups.has(group.key) ? Icon.CheckCircle : Icon.Circle,
tintColor: selectedGroups.has(group.key) ? Color.Green : Color.SecondaryText }} tintColor: selectedGroups.has(group.key) ? Color.Green : Color.SecondaryText }}
title={group.original} subtitle={`→ ${group.placeholder}`} title={group.original} subtitle={`→ ${group.placeholder}`}

View File

@@ -65,14 +65,17 @@ export async function setActiveSession(id: string): Promise<void> {
await LocalStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, id); await LocalStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, id);
} }
export async function createSession(name?: string): Promise<VelumSession> { export async function createSession(name?: string,
initial?: Pick<VelumSession, "mapping" | "entityTypes" | "excludedTerms">): Promise<VelumSession> {
const timestamp = nowIso(); const timestamp = nowIso();
const session: VelumSession = { const session: VelumSession = {
id: randomUUID(), id: randomUUID(),
name: name || `Sitzung ${new Date().toLocaleString()}`, name: name?.trim() || `Sitzung ${new Date().toLocaleString()}`,
createdAt: timestamp, createdAt: timestamp,
updatedAt: timestamp, updatedAt: timestamp,
mapping: {}, mapping: {},
...initial,
...(initial && { mappingCreatedAt: mappingDates(undefined, initial.mapping, timestamp) }),
}; };
const sessions = await listSessions(); const sessions = await listSessions();

View File

@@ -1,7 +1,7 @@
import { promises as fs } from "node:fs"; import { promises as fs } from "node:fs";
import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules, import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules,
loadProjectWhitelist, replaceSpans, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project"; loadProjectWhitelist, replaceSpans, saveProjectWhitelist, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project";
import { mappingForRestoration } from "./lib/mapping-groups"; import { mappingForRestoration, mappingRoot, mergeMappingGroups } from "./lib/mapping-groups";
import type { ProjectWhitelistEntry } from "./lib/velum-project"; import type { ProjectWhitelistEntry } from "./lib/velum-project";
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values"; import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values";
import { createSession, getSession, setActiveSession, updateSessionMapping } from "./sessions"; import { createSession, getSession, setActiveSession, updateSessionMapping } from "./sessions";
@@ -9,7 +9,7 @@ import type { EntityType, PlaceholderMapping, PseudonymizeResponse, VelumSession
import { NEW_SESSION_ID } from "./ui"; import { NEW_SESSION_ID } from "./ui";
import { normalizePseudonymizeResponse, pseudonymize } from "./velum"; import { normalizePseudonymizeResponse, pseudonymize } from "./velum";
function projectMapping(mapping: PlaceholderMapping): PlaceholderMapping { export function bareMapping(mapping: PlaceholderMapping): PlaceholderMapping {
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [ return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [
key.replace(/^<|>$/g, ""), key.replace(/^<|>$/g, ""),
{ ...entry, merged_into: entry.merged_into?.replace(/^<|>$/g, "") }, { ...entry, merged_into: entry.merged_into?.replace(/^<|>$/g, "") },
@@ -47,6 +47,7 @@ export type PreparedText = {
previous: PlaceholderMapping; previous: PlaceholderMapping;
exclusions: ProjectWhitelistEntry[]; exclusions: ProjectWhitelistEntry[];
selected: string; selected: string;
newSessionName?: string;
projectPath?: string; projectPath?: string;
projectName?: string; projectName?: string;
}; };
@@ -83,30 +84,51 @@ export async function prepareTextInContext(values: ContextFormValues, text: stri
if (selected !== NEW_SESSION_ID && !session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren."); if (selected !== NEW_SESSION_ID && !session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
const previous = session?.mapping ?? {}; const previous = session?.mapping ?? {};
const exclusions = session?.excludedTerms ?? []; const exclusions = session?.excludedTerms ?? [];
const raw = applyProjectWhitelist(text, await request(text, previous, entityTypes), previous, exclusions); const raw = applyProjectWhitelist(text, await request(text, bareMapping(previous), entityTypes), previous, exclusions);
if (!raw.spans.length && raw.pseudonymized_text !== text) { if (!raw.spans.length && raw.pseudonymized_text !== text) {
throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert."); throw new Error("Die Analyse lieferte Maskierungen ohne überprüfbare Treffer. Es wurde nichts gespeichert.");
} }
return { text, raw, previous, exclusions, selected }; return { text, raw, previous, exclusions, selected, newSessionName: values.newSessionName };
} }
/** Commit only the explicitly selected hits; rejected terms become context-specific exceptions. */ /** Commit only the explicitly selected hits; rejected terms become context-specific exceptions. */
export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false): export async function commitPreparedText(prepared: PreparedText, selectedHits: Set<number>, forAi = false,
personMerges: Record<string, string> = {}):
Promise<{ result: PseudonymizeResponse; session: VelumSession }> { Promise<{ result: PseudonymizeResponse; session: VelumSession }> {
const accepted = prepared.raw.spans.filter((_, index) => selectedHits.has(index)); const accepted = prepared.raw.spans.filter((_, index) => selectedHits.has(index));
const rejected = prepared.raw.spans.filter((_, index) => !selectedHits.has(index)); const rejected = prepared.raw.spans.filter((_, index) => !selectedHits.has(index));
const spans = toUtf16Offsets(prepared.text, accepted).map((span, index) => ({ ...span, id: String(index) })); const known = bareMapping(prepared.previous);
const known = projectMapping(prepared.previous); const preview = { ...known, ...bareMapping(prepared.raw.mapping) };
const preview = projectMapping(prepared.raw.mapping);
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, ""))); const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
const mapping: PlaceholderMapping = { ...known }; let mapping: PlaceholderMapping = { ...known };
for (const key of active) { for (const key of active) {
const entry = preview[key]; const entry = preview[key];
if (!entry) throw new Error(`Zuordnung für ${key} fehlt. Es wurde nichts gespeichert.`); if (!entry) throw new Error(`Zuordnung für ${key} fehlt. Es wurde nichts gespeichert.`);
mapping[key] = entry; mapping[key] = entry;
if (entry.merged_into) {
const root = mappingRoot(key, preview);
mapping[key] = { ...entry, merged_into: root };
mapping[root] = preview[root];
}
} }
const raw: PseudonymizeResponse = { ...prepared.raw, spans: accepted, const selectedPeople = new Set(accepted.filter((span) => span.type === "PERSON")
mapping, entity_count: active.size, .map((span) => mappingRoot(span.placeholder.replace(/^<|>$/g, ""), mapping)));
for (const [source, target] of Object.entries(personMerges)) {
if (!selectedPeople.has(source) || mapping[target]?.type !== "PERSON") {
throw new Error("Bitte nur ausgewählte Personen mit vorhandenen Zuordnungen zusammenfassen.");
}
mapping = mergeMappingGroups(mapping, source, target);
}
const mergedSpans = accepted.map((span) => {
if (span.type !== "PERSON") return span;
const key = span.placeholder.replace(/^<|>$/g, "");
const root = mappingRoot(key, mapping);
if (root === key) return span;
return { ...span, placeholder: span.placeholder.startsWith("<") ? `<${root}>` : root };
});
const spans = toUtf16Offsets(prepared.text, mergedSpans).map((span, index) => ({ ...span, id: String(index) }));
const raw: PseudonymizeResponse = { ...prepared.raw, spans: mergedSpans,
mapping, entity_count: new Set(mergedSpans.map((span) => span.placeholder.replace(/^<|>$/g, ""))).size,
pseudonymized_text: replaceSpans(prepared.text, spans, new Set(spans.map((span) => span.id))) }; pseudonymized_text: replaceSpans(prepared.text, spans, new Set(spans.map((span) => span.id))) };
const result = forAi ? normalizePseudonymizeResponse(raw) : raw; const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
const additions = rejected.map(({ type, original }) => ({ type, original })); const additions = rejected.map(({ type, original }) => ({ type, original }));
@@ -120,7 +142,12 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren."); throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
} }
if (latest) { if (latest) {
await updateProjectMapping(path, () => mapping); await updateProjectMapping(path, (current) => {
if (JSON.stringify(current) !== JSON.stringify(prepared.previous)) {
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte erneut analysieren.");
}
return mapping;
});
} else { } else {
const created = await createRun(path); const created = await createRun(path);
created.run.mapping = mapping; created.run.mapping = mapping;
@@ -130,9 +157,16 @@ export async function commitPreparedText(prepared: PreparedText, selectedHits: S
return { result, session: resultSession(path, prepared.projectName ?? path, return { result, session: resultSession(path, prepared.projectName ?? path,
mappingForRestoration(result.mapping), result.selected_entity_types) }; mappingForRestoration(result.mapping), result.selected_entity_types) };
} }
const session = prepared.selected === NEW_SESSION_ID ? await createSession() : await getSession(prepared.selected); if (prepared.selected === NEW_SESSION_ID) {
const saved = await createSession(prepared.newSessionName, {
mapping: result.mapping, entityTypes: result.selected_entity_types, excludedTerms: exclusions,
});
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 (!session) throw new Error("Sitzung nicht gefunden. Bitte erneut analysieren.");
if (prepared.selected !== NEW_SESSION_ID && JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)) { if (JSON.stringify(session.mapping) !== JSON.stringify(prepared.previous)
|| JSON.stringify(session.excludedTerms ?? []) !== JSON.stringify(prepared.exclusions)) {
throw new Error("Die Sitzung wurde inzwischen geändert. Bitte erneut analysieren."); 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);
@@ -169,7 +203,7 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
})))); }))));
const raw = applyProjectWhitelist(text, const raw = applyProjectWhitelist(text,
await request(text, latest?.run.mapping ?? {}, entityTypes, masks), latest?.run.mapping ?? {}, whitelist); await request(text, latest?.run.mapping ?? {}, entityTypes, masks), latest?.run.mapping ?? {}, whitelist);
const mapping = projectMapping(raw.mapping); const mapping = bareMapping(raw.mapping);
if (latest) { if (latest) {
await updateProjectMapping(path, (current) => { await updateProjectMapping(path, (current) => {
if (JSON.stringify(current) !== JSON.stringify(latest.run.mapping)) { if (JSON.stringify(current) !== JSON.stringify(latest.run.mapping)) {
@@ -188,10 +222,10 @@ export async function pseudonymizeInContext(values: ContextFormValues, text: str
mappingForRestoration(resultMapping), result.selected_entity_types) }; mappingForRestoration(resultMapping), result.selected_entity_types) };
} }
const session = selected === NEW_SESSION_ID ? await createSession() : await getSession(selected); const session = selected === NEW_SESSION_ID ? await createSession(values.newSessionName) : await getSession(selected);
if (!session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren."); if (!session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
await setActiveSession(session.id); await setActiveSession(session.id);
const raw = await request(text, session.mapping, entityTypes); const raw = await request(text, bareMapping(session.mapping), entityTypes);
const result = forAi ? normalizePseudonymizeResponse(raw) : raw; const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types); const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types);
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } }; return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };

View File

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

View File

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

View File

@@ -91,12 +91,14 @@ it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht er
spans: [{ start: 0, end: 11, type: "PERSON", score: 0.8, spans: [{ start: 0, end: 11, type: "PERSON", score: 0.8,
placeholder: "PERSON_01", original: "Fachbegriff" }], placeholder: "PERSON_01", original: "Fachbegriff" }],
}); });
const prepared = await prepareTextInContext({ sessionId: "__new_session__" }, const prepared = await prepareTextInContext({ sessionId: "__new_session__", newSessionName: " Kundenmail " },
"Fachbegriff", ["PERSON"], request); "Fachbegriff", ["PERSON"], request);
expect(await sessions.listSessions()).toHaveLength(0); expect(await sessions.listSessions()).toHaveLength(0);
const { result, session } = await commitPreparedText(prepared, new Set()); const { result, session } = await commitPreparedText(prepared, new Set());
expect(result.pseudonymized_text).toBe("Fachbegriff"); expect(result.pseudonymized_text).toBe("Fachbegriff");
expect(session.name).toBe("Kundenmail");
expect(session.mapping).toEqual({}); expect(session.mapping).toEqual({});
expect(await sessions.getActiveSessionId()).toBe(session.id);
expect((await sessions.getSession(session.id))?.excludedTerms).toEqual([ expect((await sessions.getSession(session.id))?.excludedTerms).toEqual([
{ type: "PERSON", original: "Fachbegriff" }, { type: "PERSON", original: "Fachbegriff" },
]); ]);
@@ -104,6 +106,59 @@ it("merkt abgelehnte Sitzungstreffer und schlägt sie im nächsten Lauf nicht er
expect(next.raw.spans).toEqual([]); expect(next.raw.spans).toEqual([]);
}); });
it.each(["session", "project"])("fasst geprüfte Namensvarianten zusammen und speichert sie für Folgeläufe (%s)", async (context) => {
let values = { sessionId: "__new_session__", newProjectPath: [] as string[] };
if (context === "project") {
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-merge-"));
roots.push(root);
const folder = join(root, "Projekt");
await fs.mkdir(folder);
values = { sessionId: "__new_project__", newProjectPath: [folder] };
}
const source = "😀 Max Muster\nMax und Mia";
const prepared = await prepareTextInContext(values, source, ["PERSON"], async () => ({
pseudonymized_text: "😀 PERSON_01\nPERSON_02 und PERSON_03",
selected_entity_types: ["PERSON"], entity_count: 3,
mapping: {
PERSON_01: { type: "PERSON", original: "Max Muster" },
PERSON_02: { type: "PERSON", original: "Max" },
PERSON_03: { type: "PERSON", original: "Mia" },
},
spans: [
{ start: 2, end: 12, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max Muster" },
{ start: 13, end: 16, type: "PERSON", score: 1, placeholder: "PERSON_02", original: "Max" },
{ start: 21, end: 24, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Mia" },
],
}));
await expect(commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_03" }))
.rejects.toThrow("ausgewählte Personen");
const { result, session } = await commitPreparedText(prepared, new Set([0, 1]), true, { PERSON_02: "PERSON_01" });
expect(result.pseudonymized_text).toBe("😀 <PERSON_01>\n<PERSON_01> und Mia");
expect(result.entity_count).toBe(1);
expect(result.spans.map((span) => span.placeholder)).toEqual(["PERSON_01", "PERSON_01"]);
expect(result.mapping["<PERSON_02>"]).toEqual({ type: "PERSON", original: "Max", merged_into: "<PERSON_01>" });
expect(result.mapping["<PERSON_03>"]).toBeUndefined();
expect(session.mapping["<PERSON_02>"].original).toBe("Max Muster");
const followup = await prepareTextInContext({ sessionId: session.id }, "Max und Maximilian", ["PERSON"],
async (_text, mapping) => {
expect(mapping.PERSON_02.merged_into).toBe("PERSON_01");
expect(mapping["<PERSON_02>"]).toBeUndefined();
return {
pseudonymized_text: "PERSON_01 und PERSON_03", selected_entity_types: ["PERSON"], entity_count: 2,
mapping: { ...mapping, PERSON_03: { type: "PERSON", original: "Maximilian" } },
spans: [
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
{ start: 8, end: 18, type: "PERSON", score: 1, placeholder: "PERSON_03", original: "Maximilian" },
],
};
});
const updated = await commitPreparedText(followup, new Set([0, 1]), false, { PERSON_01: "PERSON_03" });
expect(updated.result.pseudonymized_text).toBe("PERSON_03 und PERSON_03");
expect(updated.result.mapping.PERSON_02.merged_into).toBe("PERSON_03");
expect(updated.session.mapping.PERSON_02.original).toBe("Maximilian");
});
it("entfernt eine False-Positive-Gruppe aus der Sitzung und merkt alle Varianten", async () => { it("entfernt eine False-Positive-Gruppe aus der Sitzung und merkt alle Varianten", async () => {
const session = await sessions.createSession("Test"); const session = await sessions.createSession("Test");
await sessions.updateSessionMapping(session.id, { await sessions.updateSessionMapping(session.id, {