6 Commits

Author SHA1 Message Date
muena
b630093075 feat: load available AI models from Raycast 2026-12-02 08:53:37 +01:00
muena
019f6b6d7c feat: improve Velum hit review and session creation 2026-12-02 08:53:37 +01:00
96d5f3f57d Merge pull request 'Velum Raycast: Standard-Typen alle außer IP, Datum, Referenz (agent/default-entity-types)' (#2) from paperclip-bot/velum-raycast:agent/default-entity-types into main
Reviewed-on: #2
2026-12-01 06:14:22 +00:00
e2df0cda33 feat: preselect all entity types except IP, Datum and Referenz
Forms and the project-file command now preselect the backend's
default_entity_types from /api/entity-types instead of every type. Older
backends without that field fall back to all types except IP, DATUM and
REFERENZ. Saved project selections are still loaded unchanged; the
project-file command keeps excluding ORT by default as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 06:04:40 +00:00
1eba3f5921 Merge pull request 'Velum Raycast: lokale DOCX-Verarbeitung im Hintergrund zur Freigabe (agent/velum-project-files)' (#1) from paperclip-bot/velum-raycast:agent/velum-project-files into main
Reviewed-on: #1
2026-11-30 20:15:21 +00:00
dd0ac92518 fix: propagate recognized person names across local DOCX segments
The local DOCX flow analyzes each paragraph separately, so the backend's
per-text person propagation never crosses paragraph boundaries. A name
recognized once ("Frau Jorinde Quastenberg") stayed in clear text wherever
the model missed it in context ("bei Quastenberg nachfragen").

After all segment batches of a file, add the remaining occurrences of
confidently recognized full names, their parts (3+ characters) and names
after a salutation (including a genitive s) as reviewable PERSON hits.
Whitelist, placeholder filtering and the hit review still apply.

Synthetic reproduction with de_core_news_lg: 59 unmasked name occurrences
before, 0 after; comments, insertions, deletions and anchors verified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 15:48:09 +00:00
29 changed files with 823 additions and 218 deletions

View File

@@ -14,18 +14,31 @@ nachverfolgten Änderungen, einschließlich gelöschter Texte und Feldcodes.
Kommentarverweise und Änderungsmarkierungen bleiben erhalten. Optionale Kommentarverweise und Änderungsmarkierungen bleiben erhalten. Optionale
Microsoft-Kontoverknüpfungen in `word/people.xml` werden entfernt. Microsoft-Kontoverknüpfungen in `word/people.xml` werden entfernt.
Die Erkennung bewertet jeden Absatz einzeln. Ein Name wird daher je nach Satz
erkannt oder nicht („Quastenberg prüft …“, aber nicht „bei Quastenberg
nachfragen“). Velum überträgt deshalb sicher erkannte Personennamen auf alle
weiteren Vorkommen in derselben Datei: vollständige Namen, deren Bestandteile
ab drei Zeichen und Namen nach einer Anrede wie `Frau` oder `Dr.`, auch mit
Genitiv-s. Diese Vorkommen erscheinen wie alle anderen in der Trefferprüfung und
lassen sich dort gemeinsam abwählen. Bleiben trotzdem Namen stehen, trage sie
als Projektbegriff ein, zum Beispiel `PERSON: Max Mustermann`.
Bei der Analyse und nach dem Bestätigen der Ausgabe kannst du Raycast Bei der Analyse und nach dem Bestätigen der Ausgabe kannst du Raycast
schließen. Öffne anschließend im selben Befehl denselben Projektordner, um schließen. Öffne anschließend im selben Befehl denselben Projektordner, um
den Status oder die Trefferprüfung zu öffnen. Vor dem Anwenden prüft der den Status oder die Trefferprüfung zu öffnen. Vor dem Anwenden prüft der
Hintergrundprozess den Datei-Hash. Hintergrundprozess den Datei-Hash.
Für die lokale DOCX-Verarbeitung muss `uv` installiert sein (zum Beispiel Für die lokale DOCX-Verarbeitung muss `uv` installiert sein (zum Beispiel
`brew install uv`). Beim ersten Lauf verwendet es Python 3.11 und richtet `brew install uv`). Beim ersten Lauf lädt es Python 3.11 und `lxml` 6.2.1 in
`lxml` aus seinem Paketcache ein. Das Velum-Backend muss den Segment-Endpunkt seinen Paketcache; dafür ist einmalig Internetzugang nötig. Dokumentinhalte
bereitstellen. Beim Bauen der Erweiterung werden der Python-Codec und der werden dabei nicht übertragen. Das Velum-Backend muss den Segment-Endpunkt
Hintergrundprozess mitgeliefert. Ist der Backend-Checkout an einem anderen bereitstellen, also mindestens Stand `2517637` („support local DOCX segment
Ort, setze `VELUM_BACKEND_DIR` vor `npm run build` oder `npm run dev` auf analysis“). Beim Bauen der Erweiterung werden der Python-Codec und der
seinen `backend`-Ordner. Hintergrundprozess aus dem Backend-Checkout mitgeliefert. Der Checkout sollte
deshalb denselben Stand haben wie das produktive Backend. Ohne Angabe sucht
der Build unter `../../velum/backend`, relativ zu diesem Repository. Liegt der
Backend-Checkout an einem anderen Ort, setze `VELUM_BACKEND_DIR` vor
`npm run build` oder `npm run dev` auf seinen `backend`-Ordner.
`Projektdateien pseudonymisieren` übernimmt zuerst den geöffneten Finder-Ordner; bei Bedarf kann er im Formular erneut übernommen oder manuell gewählt werden. Im Formular werden die zu erkennenden Kategorien ausgewählt (Orte sind wegen häufiger Fehlalarme zunächst abgewählt). Danach analysiert Velum alle geeigneten Text-, DOCX-, XLSX-, PPTX- und PDF-Dateien sowie ihre Namen. Unterstriche zwischen Namensbestandteilen werden bei der Erkennung als Worttrenner behandelt; bekannte Platzhalter und wörtliche Codebegriffe bleiben erhalten. Auch Namen unveränderter Dateien werden in einem Folgelauf erneut geprüft. Ältere Word-Projektstände werden einmalig auf Kommentatoren geprüft, sofern `PERSON` ausgewählt ist. Kleine Textdateien und Namen werden in Paketen analysiert, um die Anzahl der API-Aufrufe zu verringern. Die Prüfung zeigt jede eindeutige Zuordnung einmal, nach Kategorie gruppiert, mit der Anzahl ihrer Vorkommen. Eine Zuordnung an- oder abzuwählen gilt für alle betroffenen Dateien; einzelne Vorkommen lassen sich bei Bedarf ansehen. Nach der Auswahl lassen sich erkannte Personen optional zusammenfassen, sodass ihre Erwähnungen denselben Platzhalter erhalten. `Pseudonymisierte Kopien erstellen` schreibt Dateien in den Raycast-Support-Bereich außerhalb des Projektordners. Alternativ ersetzt `Originaldateien ersetzen` die Dateien und gegebenenfalls ihre Namen vor Ort; zuvor legt Velum eine private Sicherung der Originale im Raycast-Support-Bereich an. PDF wird dabei als DOCX ausgegeben. `Projektdateien pseudonymisieren` übernimmt zuerst den geöffneten Finder-Ordner; bei Bedarf kann er im Formular erneut übernommen oder manuell gewählt werden. Im Formular werden die zu erkennenden Kategorien ausgewählt (Orte sind wegen häufiger Fehlalarme zunächst abgewählt). Danach analysiert Velum alle geeigneten Text-, DOCX-, XLSX-, PPTX- und PDF-Dateien sowie ihre Namen. Unterstriche zwischen Namensbestandteilen werden bei der Erkennung als Worttrenner behandelt; bekannte Platzhalter und wörtliche Codebegriffe bleiben erhalten. Auch Namen unveränderter Dateien werden in einem Folgelauf erneut geprüft. Ältere Word-Projektstände werden einmalig auf Kommentatoren geprüft, sofern `PERSON` ausgewählt ist. Kleine Textdateien und Namen werden in Paketen analysiert, um die Anzahl der API-Aufrufe zu verringern. Die Prüfung zeigt jede eindeutige Zuordnung einmal, nach Kategorie gruppiert, mit der Anzahl ihrer Vorkommen. Eine Zuordnung an- oder abzuwählen gilt für alle betroffenen Dateien; einzelne Vorkommen lassen sich bei Bedarf ansehen. Nach der Auswahl lassen sich erkannte Personen optional zusammenfassen, sodass ihre Erwähnungen denselben Platzhalter erhalten. `Pseudonymisierte Kopien erstellen` schreibt Dateien in den Raycast-Support-Bereich außerhalb des Projektordners. Alternativ ersetzt `Originaldateien ersetzen` die Dateien und gegebenenfalls ihre Namen vor Ort; zuvor legt Velum eine private Sicherung der Originale im Raycast-Support-Bereich an. PDF wird dabei als DOCX ausgegeben.
@@ -128,7 +141,7 @@ Alle Werte sind in den Raycast-Einstellungen pro Extension einstellbar.
- `Ausgabe der Schnellbefehle` — `In die Zwischenablage kopieren` (Default) oder `Am Cursor einfügen` - `Ausgabe der Schnellbefehle` — `In die Zwischenablage kopieren` (Default) oder `Am Cursor einfügen`
- `Eigener Name` — Default-Signatur für AI-generierte Email-Antworten, im Antwort-Befehl pro Aufruf überschreibbar - `Eigener Name` — Default-Signatur für AI-generierte Email-Antworten, im Antwort-Befehl pro Aufruf überschreibbar
Das KI-Modell ist keine Preference: jeder AI-Befehl zeigt ein `KI-Modell`-Dropdown mit dem aktuellen Modell-Katalog aus `src/ai.ts`. Die Auswahl wird in `LocalStorage` (`velum.ai.last-model`) persistiert und ist beim nächsten Aufruf in jedem AI-Befehl vorausgewählt. Jeder KI-Befehl bezieht die Auswahl im Feld **KI-Modell** aus `AI.Model` der installierten Raycast-Version. Mit **Raycast-Standard** verwendet Velum das Standardmodell der Raycast-API. Velum merkt sich die letzte Auswahl für alle KI-Befehle. Fehlt das gespeicherte Modell im API-Katalog, ist beim nächsten Aufruf **Raycast-Standard** ausgewählt.
- `Maximale Anzahl gespeicherter Sitzungen` — älteste werden geprunt (Default 20) - `Maximale Anzahl gespeicherter Sitzungen` — älteste werden geprunt (Default 20)
- `Raycast nach Kopieren/Einfügen schließen` — Auto-Close und Pop-To-Root nach AI-Workflow-Abschluss (Default an) - `Raycast nach Kopieren/Einfügen schließen` — Auto-Close und Pop-To-Root nach AI-Workflow-Abschluss (Default an)

View File

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

View File

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

View File

@@ -76,6 +76,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]); const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL); const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -99,8 +100,9 @@ export default function Command() {
try { try {
const loadedEntityTypes = await getEntityTypes(); const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes); setEntityTypes(loadedEntityTypes.all);
setSelectedEntityTypes(loadedEntityTypes); setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch { } catch {
setEntityTypes([]); setEntityTypes([]);
} finally { } finally {
@@ -213,7 +215,8 @@ export default function Command() {
placeholder="Meeting-Notizen, Stichpunkte, Transkript …" placeholder="Meeting-Notizen, Stichpunkte, Transkript …"
/> />
<ContextPicker sessions={sessions} activeSessionId={activeSessionId} <ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} /> availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? ( {entityTypes.length > 0 ? (
<Form.TagPicker <Form.TagPicker
id="entityTypes" id="entityTypes"

View File

@@ -8,7 +8,8 @@ import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID } from "./context-values";
export type { ContextFormValues } from "./context-values"; export type { ContextFormValues } from "./context-values";
export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId?: string; export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId?: string;
availableEntityTypes: EntityType[]; onEntityTypesChange: (types: EntityType[]) => void }) { availableEntityTypes: EntityType[]; defaultEntityTypes: EntityType[];
onEntityTypesChange: (types: EntityType[]) => void }) {
const [projects, setProjects] = useState<Array<{ path: string; name: string }>>([]); const [projects, setProjects] = useState<Array<{ path: string; name: string }>>([]);
const [selected, setSelected] = useState(CHOOSE_CONTEXT_ID); const [selected, setSelected] = useState(CHOOSE_CONTEXT_ID);
@@ -32,7 +33,7 @@ export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId
try { try {
const saved = id.startsWith("project:") const saved = id.startsWith("project:")
? await loadProjectEntityTypes(id.slice("project:".length)) : null; ? await loadProjectEntityTypes(id.slice("project:".length)) : null;
props.onEntityTypesChange(saved ?? props.availableEntityTypes); props.onEntityTypesChange(saved ?? props.defaultEntityTypes);
setSelected(id); setSelected(id);
} catch (error) { } catch (error) {
await showToast({ style: Toast.Style.Failure, await showToast({ style: Toast.Style.Failure,
@@ -51,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

@@ -81,6 +81,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]); const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL); const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -104,8 +105,9 @@ export default function Command() {
try { try {
const loadedEntityTypes = await getEntityTypes(); const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes); setEntityTypes(loadedEntityTypes.all);
setSelectedEntityTypes(loadedEntityTypes); setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch { } catch {
setEntityTypes([]); setEntityTypes([]);
} finally { } finally {
@@ -218,7 +220,8 @@ export default function Command() {
placeholder="Meeting-Notizen, Email-Thread, Transkript …" placeholder="Meeting-Notizen, Email-Thread, Transkript …"
/> />
<ContextPicker sessions={sessions} activeSessionId={activeSessionId} <ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} /> availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? ( {entityTypes.length > 0 ? (
<Form.TagPicker <Form.TagPicker
id="entityTypes" id="entityTypes"

View File

@@ -102,6 +102,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]); const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL); const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -125,8 +126,9 @@ export default function Command() {
try { try {
const loadedEntityTypes = await getEntityTypes(); const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes); setEntityTypes(loadedEntityTypes.all);
setSelectedEntityTypes(loadedEntityTypes); setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch { } catch {
setEntityTypes([]); setEntityTypes([]);
} finally { } finally {
@@ -278,7 +280,8 @@ export default function Command() {
))} ))}
</Form.Dropdown> </Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId} <ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} /> availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? ( {entityTypes.length > 0 ? (
<Form.TagPicker <Form.TagPicker
id="entityTypes" id="entityTypes"

22
src/lib/entity-types.ts Normal file
View File

@@ -0,0 +1,22 @@
import type { EntityType } from "../types";
/** Fallback for Velum backends that do not report `default_entity_types` yet. */
export const DEFAULT_DISABLED_ENTITY_TYPES: readonly EntityType[] = [
"IP",
"DATUM",
"REFERENZ",
];
export type EntityTypeCatalog = { all: EntityType[]; defaults: EntityType[] };
/** Preselection for unconfigured contexts; the backend default wins when it is available. */
export function entityTypeCatalog(payload: {
entity_types: EntityType[];
default_entity_types?: EntityType[];
}): EntityTypeCatalog {
const all = payload.entity_types;
const defaults = payload.default_entity_types
? payload.default_entity_types.filter((type) => all.includes(type))
: all.filter((type) => !DEFAULT_DISABLED_ENTITY_TYPES.includes(type));
return { all, defaults };
}

View File

@@ -8,6 +8,7 @@ import { analyzeDocxSegments } from "../velum";
import type { EntityType, PlaceholderMapping } from "../types"; import type { EntityType, PlaceholderMapping } from "../types";
import { checkedImageReport } from "./image-policy"; import { checkedImageReport } from "./image-policy";
import type { ImagePolicy } from "./image-policy"; import type { ImagePolicy } from "./image-policy";
import { propagateDocxPersons } from "./person-propagation";
import { MAX_BATCH_CODEPOINTS } from "./project-review"; import { MAX_BATCH_CODEPOINTS } from "./project-review";
import { projectTextAnalyzer } from "./project-text-mapping"; import { projectTextAnalyzer } from "./project-text-mapping";
import type { Hit } from "./project-work"; import type { Hit } from "./project-work";
@@ -108,7 +109,9 @@ export async function inspectDocx(
size += segment.text.length + 2; size += segment.text.length + 2;
} }
await flush(); await flush();
return { hits, mapping: current, segmentCount: segments.length }; const propagated = types.includes("PERSON") ? propagateDocxPersons(segments, hits, current, relative)
: { hits, mapping: current };
return { ...propagated, segmentCount: segments.length };
} }
export async function writeDocx( export async function writeDocx(

View File

@@ -0,0 +1,107 @@
import type { PlaceholderMapping } from "../types";
import type { Hit } from "./project-work";
// Seeds follow the backend's per-text person propagation: only confident
// PERSON hits that look like capitalized names. Unlike the backend, the parts of
// a detected full name are propagated even if the model never recognized them
// alone, because lone surnames are what it misses most in running text.
// Common words stay out of reach unless the model put them into a name.
const NAME = /^[A-ZÄÖÜ][A-Za-zÄÖÜäöüß’'-]+(?:[ \t]+[A-ZÄÖÜ][A-Za-zÄÖÜäöüß’'-]+)*$/u;
const MIN_SEED_SCORE = 0.85;
// The backend's salutation recognizer ("Frau Müller", "Dr. Schmidt") scores
// 0.7, but its structure reliably marks the following words as a name.
const SALUTATION = /^(?:Frau|Herr|Dr\.|Prof\.|Mag\.|Ing\.|DI)\s+/u;
const MIN_SALUTATION_SCORE = 0.7;
function escape(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/**
* Velum analyzes every DOCX segment separately, so a name recognized in one
* paragraph is not propagated to paragraphs where the model misses it (for
* example "bei Quastenberg nachfragen"). Add those occurrences as reviewable
* hits for the whole file.
*/
export function propagateDocxPersons(
segments: Array<{ text: string; source: string; kind: string }>, hits: Hit[], mapping: PlaceholderMapping,
relative: string,
): { hits: Hit[]; mapping: PlaceholderMapping } {
const candidates = new Map<string, number>();
const add = (name: string, score: number) => candidates.set(name, Math.max(candidates.get(name) ?? 0, score));
for (const hit of hits) {
if (hit.kind !== "content" || hit.type !== "PERSON") continue;
const salutation = hit.original.trim().match(SALUTATION);
const name = hit.original.trim().slice(salutation?.[0].length ?? 0);
if (hit.score < (salutation ? MIN_SALUTATION_SCORE : MIN_SEED_SCORE) || !NAME.test(name)) continue;
const parts = name.split(/[ \t]+/);
if (parts.length < 2 && !salutation) continue;
add(name, hit.score);
for (const part of parts) if (parts.length > 1 && Array.from(part).length >= 3) add(part, hit.score);
}
if (!candidates.size) return { hits, mapping };
const next: PlaceholderMapping = { ...mapping };
const identities = new Map<string, string>();
let counter = 0;
for (const [key, entry] of Object.entries(next)) {
if (entry.type !== "PERSON") continue;
identities.set(entry.original.trim().toLowerCase(), key);
counter = Math.max(counter, Number(key.match(/_(\d+)$/)?.[1] ?? 0));
}
const canonical = (key: string): string => {
const seen = new Set<string>();
while (next[key]?.merged_into && !seen.has(key)) {
seen.add(key);
key = next[key].merged_into!;
}
return key;
};
const placeholderFor = (name: string): string => {
let key = identities.get(name.toLowerCase());
if (!key) {
key = `PERSON_${String(++counter).padStart(2, "0")}`;
if (next[key]) throw new Error("Doppelte Platzhalternummer in der Projektzuordnung.");
next[key] = { original: name, type: "PERSON" };
identities.set(name.toLowerCase(), key);
}
return canonical(key);
};
const occupied = new Map<number, Array<[number, number]>>();
for (const hit of hits) {
if (hit.segment === undefined) continue;
const ranges = occupied.get(hit.segment) ?? [];
ranges.push([hit.start, hit.end]);
occupied.set(hit.segment, ranges);
}
// Longest names first, so a full name is masked as a unit before its parts.
// A German genitive "s" stays outside the masked span.
const patterns = [...candidates.keys()].sort((a, b) => b.length - a.length || a.localeCompare(b))
.map((name) => [name, new RegExp(`(?<![\\p{L}\\p{N}_])${escape(name)}(?=s?(?![\\p{L}\\p{N}_]))`, "gu")] as const);
const added: Hit[] = [];
for (const [index, segment] of segments.entries()) {
if (segment.kind !== "text") continue;
const ranges = occupied.get(index) ?? [];
for (const [name, pattern] of patterns) {
for (const match of segment.text.matchAll(pattern)) {
// Hit offsets count code points, matching the Python codec.
const start = Array.from(segment.text.slice(0, match.index)).length;
const end = start + Array.from(name).length;
if (ranges.some(([s, e]) => start < e && s < end)) continue;
ranges.push([start, end]);
const characters = Array.from(segment.text);
added.push({
id: `${relative}:local-docx:${index}:${start}:${end}`, file: relative, source: segment.source,
original: name, placeholder: placeholderFor(name), type: "PERSON", score: candidates.get(name)!,
context: characters.slice(Math.max(0, start - 60), end + 60).join(""),
start, end, kind: "content", segment: index,
});
}
}
occupied.set(index, ranges);
}
if (!added.length) return { hits, mapping };
const merged = [...hits, ...added].sort((a, b) => (a.segment ?? 0) - (b.segment ?? 0) || a.start - b.start);
return { hits: merged, mapping: next };
}

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

@@ -136,6 +136,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]); const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL); const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -164,8 +165,9 @@ export default function Command() {
try { try {
const loadedEntityTypes = await getEntityTypes(); const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes); setEntityTypes(loadedEntityTypes.all);
setSelectedEntityTypes(loadedEntityTypes); setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch { } catch {
setEntityTypes([]); setEntityTypes([]);
} finally { } finally {
@@ -278,7 +280,8 @@ export default function Command() {
placeholder="Statusmeeting-Stichpunkte, Email-Auszüge, Risiken, Zahlen, Entscheidungen …" placeholder="Statusmeeting-Stichpunkte, Email-Auszüge, Risiken, Zahlen, Entscheidungen …"
/> />
<ContextPicker sessions={sessions} activeSessionId={activeSessionId} <ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} /> availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? ( {entityTypes.length > 0 ? (
<Form.TagPicker <Form.TagPicker
id="entityTypes" id="entityTypes"

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}`}
@@ -472,6 +452,7 @@ export default function Command() {
const [imagePolicy, setImagePolicy] = useState<ImagePolicy>(DEFAULT_IMAGE_POLICY); const [imagePolicy, setImagePolicy] = useState<ImagePolicy>(DEFAULT_IMAGE_POLICY);
const [rules, setRules] = useState(""); const [rules, setRules] = useState("");
const [availableTypes, setAvailableTypes] = useState<EntityType[]>([]); const [availableTypes, setAvailableTypes] = useState<EntityType[]>([]);
const [defaultTypes, setDefaultTypes] = useState<EntityType[]>([]);
const [selectedTypes, setSelectedTypes] = useState<EntityType[]>([]); const [selectedTypes, setSelectedTypes] = useState<EntityType[]>([]);
const [typesLoaded, setTypesLoaded] = useState(false); const [typesLoaded, setTypesLoaded] = useState(false);
const [typesReadyFor, setTypesReadyFor] = useState<string | null>(null); const [typesReadyFor, setTypesReadyFor] = useState<string | null>(null);
@@ -482,14 +463,15 @@ export default function Command() {
useEffect(() => { finderFolder().then((path) => { if (path) setRoot((current) => current || path); }); }, []); useEffect(() => { finderFolder().then((path) => { if (path) setRoot((current) => current || path); }); }, []);
useEffect(() => { useEffect(() => {
getEntityTypes().then((types) => { getEntityTypes().then((types) => {
setAvailableTypes(types); setAvailableTypes(types.all);
setDefaultTypes(types.defaults);
setTypesLoaded(true); setTypesLoaded(true);
}).catch((error: Error) => showToast({ style: Toast.Style.Failure, }).catch((error: Error) => showToast({ style: Toast.Style.Failure,
title: "Kategorien nicht verfügbar", message: error.message })); title: "Kategorien nicht verfügbar", message: error.message }));
}, []); }, []);
useEffect(() => { useEffect(() => {
if (!typesLoaded) return; if (!typesLoaded) return;
const defaults = availableTypes.filter((type) => type !== "ORT"); const defaults = defaultTypes.filter((type) => type !== "ORT");
if (!root) { setSelectedTypes(defaults); setTypesReadyFor(""); return; } if (!root) { setSelectedTypes(defaults); setTypesReadyFor(""); return; }
let active = true; let active = true;
setTypesReadyFor(null); setTypesReadyFor(null);
@@ -500,7 +482,7 @@ export default function Command() {
}).catch((error: Error) => showToast({ style: Toast.Style.Failure, }).catch((error: Error) => showToast({ style: Toast.Style.Failure,
title: "Projektkategorien nicht lesbar", message: error.message })); title: "Projektkategorien nicht lesbar", message: error.message }));
return () => { active = false; }; return () => { active = false; };
}, [root, availableTypes, typesLoaded]); }, [root, availableTypes, defaultTypes, typesLoaded]);
useEffect(() => { useEffect(() => {
if (!root) return; if (!root) return;
let active = true; let active = true;

View File

@@ -38,6 +38,7 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]); const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
const { push } = useNavigation(); const { push } = useNavigation();
@@ -62,8 +63,9 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
try { try {
const loadedEntityTypes = await getEntityTypes(); const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes); setEntityTypes(loadedEntityTypes.all);
setSelectedEntityTypes(loadedEntityTypes); setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch { } catch {
setEntityTypes([]); setEntityTypes([]);
} finally { } finally {
@@ -176,7 +178,8 @@ export default function Command(props: { initialSource?: "selection" | "clipboar
placeholder="Zu pseudonymisierender Text" placeholder="Zu pseudonymisierender Text"
/> />
<ContextPicker key={contextVersion} sessions={sessions} activeSessionId={activeSessionId} <ContextPicker key={contextVersion} sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} /> availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? ( {entityTypes.length > 0 ? (
<Form.TagPicker <Form.TagPicker
id="entityTypes" id="entityTypes"

View File

@@ -20,6 +20,7 @@ import {
DEFAULT_MODEL, DEFAULT_MODEL,
getLastUsedModel, getLastUsedModel,
MODEL_OPTIONS, MODEL_OPTIONS,
resolveRaycastModel,
setLastUsedModel, setLastUsedModel,
} from "./ai"; } from "./ai";
import { getPreferences } from "./preferences"; import { getPreferences } from "./preferences";
@@ -62,6 +63,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]); const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [greeting, setGreeting] = useState("Lieber"); const [greeting, setGreeting] = useState("Lieber");
const [signOff, setSignOff] = useState("Alles Liebe,"); const [signOff, setSignOff] = useState("Alles Liebe,");
@@ -99,8 +101,9 @@ export default function Command() {
try { try {
const loadedEntityTypes = await getEntityTypes(); const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes); setEntityTypes(loadedEntityTypes.all);
setSelectedEntityTypes(loadedEntityTypes); setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch { } catch {
setEntityTypes([]); setEntityTypes([]);
} finally { } finally {
@@ -299,7 +302,8 @@ export default function Command() {
/> />
<Form.Separator /> <Form.Separator />
<ContextPicker sessions={sessions} activeSessionId={activeSessionId} <ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} /> availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? ( {entityTypes.length > 0 ? (
<Form.TagPicker <Form.TagPicker
id="entityTypes" id="entityTypes"
@@ -557,7 +561,7 @@ function ReplyResult(props: StageProps) {
instructions: props.instructions, instructions: props.instructions,
}); });
const stream = AI.ask(prompt, { const stream = AI.ask(prompt, {
model: props.model as AI.Model, model: resolveRaycastModel(props.model),
creativity: props.creativity, creativity: props.creativity,
signal: controller.signal, signal: controller.signal,
}); });

View File

@@ -65,14 +65,17 @@ export async function setActiveSession(id: string): Promise<void> {
await LocalStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, id); 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

@@ -27,6 +27,7 @@ import {
DEFAULT_MODEL, DEFAULT_MODEL,
getLastUsedModel, getLastUsedModel,
MODEL_OPTIONS, MODEL_OPTIONS,
resolveRaycastModel,
setLastUsedModel, setLastUsedModel,
} from "./ai"; } from "./ai";
import { buildSummaryPrompt, type Creativity } from "./summarize"; import { buildSummaryPrompt, type Creativity } from "./summarize";
@@ -54,6 +55,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]); const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL); const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -77,8 +79,9 @@ export default function Command() {
try { try {
const loadedEntityTypes = await getEntityTypes(); const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes); setEntityTypes(loadedEntityTypes.all);
setSelectedEntityTypes(loadedEntityTypes); setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch { } catch {
setEntityTypes([]); setEntityTypes([]);
} finally { } finally {
@@ -183,7 +186,8 @@ export default function Command() {
placeholder="Email-Konversation einfügen oder laden" placeholder="Email-Konversation einfügen oder laden"
/> />
<ContextPicker sessions={sessions} activeSessionId={activeSessionId} <ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} /> availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? ( {entityTypes.length > 0 ? (
<Form.TagPicker <Form.TagPicker
id="entityTypes" id="entityTypes"
@@ -351,7 +355,7 @@ function SummarizeEmailResult({
try { try {
const prompt = buildSummaryPrompt(pseudonymizedText, instructions); const prompt = buildSummaryPrompt(pseudonymizedText, instructions);
const stream = AI.ask(prompt, { const stream = AI.ask(prompt, {
model: model as AI.Model, model: resolveRaycastModel(model),
creativity, creativity,
signal: controller.signal, signal: controller.signal,
}); });

View File

@@ -107,6 +107,7 @@ export default function Command() {
const [sessions, setSessions] = useState<VelumSession[]>([]); const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>(); const [activeSessionId, setActiveSessionId] = useState<string>();
const [entityTypes, setEntityTypes] = useState<EntityType[]>([]); const [entityTypes, setEntityTypes] = useState<EntityType[]>([]);
const [defaultEntityTypes, setDefaultEntityTypes] = useState<EntityType[]>([]);
const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]); const [selectedEntityTypes, setSelectedEntityTypes] = useState<string[]>([]);
const [model, setModel] = useState<string>(DEFAULT_MODEL); const [model, setModel] = useState<string>(DEFAULT_MODEL);
const [isLoading, setIsLoading] = useState(true); const [isLoading, setIsLoading] = useState(true);
@@ -130,8 +131,9 @@ export default function Command() {
try { try {
const loadedEntityTypes = await getEntityTypes(); const loadedEntityTypes = await getEntityTypes();
setEntityTypes(loadedEntityTypes); setEntityTypes(loadedEntityTypes.all);
setSelectedEntityTypes(loadedEntityTypes); setDefaultEntityTypes(loadedEntityTypes.defaults);
setSelectedEntityTypes(loadedEntityTypes.defaults);
} catch { } catch {
setEntityTypes([]); setEntityTypes([]);
} finally { } finally {
@@ -244,7 +246,8 @@ export default function Command() {
placeholder="Meeting-Notizen als Fließtext einfügen — z. B. handgeschriebene Protokollnotizen, ein diktiertes Transkript oder ein zusammenhängender Bericht." placeholder="Meeting-Notizen als Fließtext einfügen — z. B. handgeschriebene Protokollnotizen, ein diktiertes Transkript oder ein zusammenhängender Bericht."
/> />
<ContextPicker sessions={sessions} activeSessionId={activeSessionId} <ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} /> availableEntityTypes={entityTypes} defaultEntityTypes={defaultEntityTypes}
onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? ( {entityTypes.length > 0 ? (
<Form.TagPicker <Form.TagPicker
id="entityTypes" id="entityTypes"

View File

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

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,6 +1,7 @@
import { fetchWithAuth } from "./auth"; import { fetchWithAuth } from "./auth";
import { restoreXlsxBuffer } from "./lib/xlsx-restoration"; import { restoreXlsxBuffer } from "./lib/xlsx-restoration";
import { checkProjectCapabilities } from "./lib/project-capabilities"; import { checkProjectCapabilities } from "./lib/project-capabilities";
import { entityTypeCatalog, type EntityTypeCatalog } from "./lib/entity-types";
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY } from "./lib/image-policy"; import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY } from "./lib/image-policy";
import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy"; import type { ImagePolicy, DocumentImageReport } from "./lib/image-policy";
import { getPreferences } from "./preferences"; import { getPreferences } from "./preferences";
@@ -103,12 +104,13 @@ async function parseJsonResponse<T>(response: Response): Promise<T> {
return (await response.json()) as T; return (await response.json()) as T;
} }
export async function getEntityTypes(): Promise<EntityType[]> { export async function getEntityTypes(): Promise<EntityTypeCatalog> {
const response = await fetchWithAuth(apiUrl("/api/entity-types")); const response = await fetchWithAuth(apiUrl("/api/entity-types"));
const payload = await parseJsonResponse<{ entity_types: EntityType[] }>( const payload = await parseJsonResponse<{
response, entity_types: EntityType[];
); default_entity_types?: EntityType[];
return payload.entity_types; }>(response);
return entityTypeCatalog(payload);
} }
export async function pseudonymize( export async function pseudonymize(

View File

@@ -0,0 +1,22 @@
import { expect, it } from "bun:test";
import { entityTypeCatalog } from "../src/lib/entity-types";
const all = ["PERSON", "EMAIL", "REFERENZ", "ORT", "DATUM", "URL", "IP"];
it("uses the backend default selection when Velum reports one", () => {
expect(
entityTypeCatalog({
entity_types: all,
default_entity_types: ["PERSON", "IP", "UNBEKANNT"],
}),
).toEqual({ all, defaults: ["PERSON", "IP"] });
});
it("leaves IP, Datum and Referenz off for backends without a default list", () => {
expect(entityTypeCatalog({ entity_types: all }).defaults).toEqual([
"PERSON",
"EMAIL",
"ORT",
"URL",
]);
});

View File

@@ -6,6 +6,7 @@ import ts from "typescript";
import * as xlsxRestoration from "../src/lib/xlsx-restoration"; import * as xlsxRestoration from "../src/lib/xlsx-restoration";
import * as imagePolicy from "../src/lib/image-policy"; import * as imagePolicy from "../src/lib/image-policy";
import * as projectCapabilities from "../src/lib/project-capabilities"; import * as projectCapabilities from "../src/lib/project-capabilities";
import * as entityTypes from "../src/lib/entity-types";
import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "../src/lib/image-policy"; import { checkedImagePolicy, checkedImageReport, DEFAULT_IMAGE_POLICY, KEEP_IMAGE_WARNING, sameImagePolicyCoverage, summarizeImages } from "../src/lib/image-policy";
const policies = ["placeholder", "remove", "keep"] as const; const policies = ["placeholder", "remove", "keep"] as const;
@@ -64,6 +65,7 @@ it("übermittelt dieselbe Bildoption in Vorschau, Anwendung und erneutem Abgleic
"./lib/image-policy": imagePolicy, "./lib/image-policy": imagePolicy,
"./lib/xlsx-restoration": xlsxRestoration, "./lib/xlsx-restoration": xlsxRestoration,
"./lib/project-capabilities": projectCapabilities, "./lib/project-capabilities": projectCapabilities,
"./lib/entity-types": entityTypes,
}; };
const module = { exports: {} as { pseudonymizeDocument: (...args: unknown[]) => Promise<unknown>; requireProjectCapabilities: (images?: boolean) => Promise<void> } }; const module = { exports: {} as { pseudonymizeDocument: (...args: unknown[]) => Promise<unknown>; requireProjectCapabilities: (images?: boolean) => Promise<void> } };
new Function("require", "module", "exports", code)((id: string) => mocks[id] ?? require(id), module, module.exports); new Function("require", "module", "exports", code)((id: string) => mocks[id] ?? require(id), module, module.exports);
@@ -97,6 +99,7 @@ it("restores XLSX locally and keeps the API route for DOCX", async () => {
"./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) }, "./preferences": { getPreferences: () => ({ velumBaseUrl: "https://velum.test" }) },
"./lib/image-policy": imagePolicy, "./lib/image-policy": imagePolicy,
"./lib/project-capabilities": projectCapabilities, "./lib/project-capabilities": projectCapabilities,
"./lib/entity-types": entityTypes,
"./lib/xlsx-restoration": xlsxRestoration, "./lib/xlsx-restoration": xlsxRestoration,
}; };
const module = { exports: {} as { depseudonymizeDocument: (name: string, data: Buffer, mapping: Record<string, { original: string; type: string }>) => Promise<Buffer> } }; const module = { exports: {} as { depseudonymizeDocument: (name: string, data: Buffer, mapping: Record<string, { original: string; type: string }>) => Promise<Buffer> } };

View File

@@ -0,0 +1,88 @@
import { expect, it } from "bun:test";
import { propagateDocxPersons } from "../src/lib/person-propagation";
import type { Hit } from "../src/lib/project-work";
import type { PlaceholderMapping } from "../src/types";
// Synthetic names only. The model recognizes them in the introduction, but
// not in the later paragraphs (observed with de_core_news_lg).
const segments = [
{ text: "Projektleitung: Frau Jorinde Quastenberg, Fachbereich Planung.", source: "Absatz", kind: "text" },
{ text: "Grüße Talvin", source: "Absatz", kind: "text" },
...Array.from({ length: 26 }, () => [
{ text: "bei Quastenberg nachfragen", source: "Absatz", kind: "text" },
{ text: "Feedback Jorinde Quastenberg: passt. 😀 Quastenberg", source: "Absatz", kind: "text" },
]).flat(),
{ text: "Quastenbergstraße und Talvin bleiben", source: "Absatz", kind: "text" },
{ text: "Jorinde Quastenberg", source: "Kommentar-Link", kind: "link" },
];
function hit(segment: number, start: number, original: string, placeholder: string, score = 0.85): Hit {
return { id: `a.docx:local-docx:${segment}:${start}:${start + original.length}`, file: "a.docx", source: "Absatz",
original, placeholder, type: "PERSON", score, context: "", start, end: start + original.length,
kind: "content", segment };
}
it("masks every occurrence of a recognized person name across DOCX segments", () => {
const mapping: PlaceholderMapping = {
PERSON_01: { original: "Jorinde Quastenberg", type: "PERSON" },
PERSON_02: { original: "Talvin", type: "PERSON" },
};
const detected = [hit(0, 21, "Jorinde Quastenberg", "PERSON_01"), hit(1, 6, "Talvin", "PERSON_02", 0.99)];
const result = propagateDocxPersons(segments, detected, mapping, "a.docx");
const masked = segments.map((segment, index) => {
const characters = Array.from(segment.text);
for (const found of result.hits.filter((entry) => entry.segment === index)) {
expect(characters.slice(found.start, found.end).join("")).toBe(found.original);
for (let position = found.start; position < found.end; position++) characters[position] = "#";
}
return characters.join("");
});
const remaining = masked.slice(0, -1).join("\n").match(/(?<![\p{L}])Quastenberg(?![\p{L}])/gu) ?? [];
expect(remaining).toHaveLength(0);
expect(result.hits).toHaveLength(2 + 26 * 3);
const surname = result.hits.find((entry) => entry.original === "Quastenberg")!;
expect(surname.placeholder).toBe("PERSON_03");
expect(result.mapping.PERSON_03).toEqual({ original: "Quastenberg", type: "PERSON" });
expect(result.hits.filter((entry) => entry.original === "Jorinde Quastenberg").every(
(entry) => entry.placeholder === "PERSON_01")).toBe(true);
// Unicode offsets count code points, like the Python codec.
expect(result.hits.find((entry) => entry.segment === 3 && entry.start > 30)!.start).toBe(39);
// No partial words, no lone first name without a full name, no link fields.
expect(masked[54]).toBe("Quastenbergstraße und Talvin bleiben");
expect(result.hits.some((entry) => entry.segment === 55)).toBe(false);
expect(mapping.PERSON_03).toBeUndefined();
});
it("does not seed propagation from weak or merged-away hits", () => {
const mapping: PlaceholderMapping = {
PERSON_04: { original: "Jorinde Quastenberg", type: "PERSON" },
PERSON_07: { original: "Quastenberg", type: "PERSON", merged_into: "PERSON_04" },
};
const weak = propagateDocxPersons(segments, [hit(0, 21, "Jorinde Quastenberg", "PERSON_04", 0.6)], mapping, "a.docx");
expect(weak.hits).toHaveLength(1);
const merged = propagateDocxPersons(segments, [hit(0, 21, "Jorinde Quastenberg", "PERSON_04")], mapping, "a.docx");
expect(merged.hits.find((entry) => entry.original === "Quastenberg")!.placeholder).toBe("PERSON_04");
expect(Object.keys(merged.mapping)).toEqual(["PERSON_04", "PERSON_07"]);
});
it("seeds from salutation hits without the salutation and keeps the genitive s", () => {
const texts = ["Projektleitung: Frau Jorinde Quastenberg, Planung.", "Dr. Ostermeier ist informiert.",
"Quastenbergs Bericht und Ostermeiers Notiz liegen vor.", "Frau und Herr bleiben Wörter.", "Ostermeierhof"];
const result = propagateDocxPersons(texts.map((text) => ({ text, source: "Absatz", kind: "text" })), [
hit(0, 16, "Frau Jorinde Quastenberg", "PERSON_01", 0.7),
hit(1, 0, "Dr. Ostermeier", "PERSON_02", 0.7),
], {
PERSON_01: { original: "Frau Jorinde Quastenberg", type: "PERSON" },
PERSON_02: { original: "Dr. Ostermeier", type: "PERSON" },
}, "a.docx");
const added = result.hits.filter((entry) => !["PERSON_01", "PERSON_02"].includes(entry.placeholder));
expect(added.map((entry) => [entry.segment, entry.original, texts[entry.segment!].slice(entry.start, entry.end)]))
.toEqual([[2, "Quastenberg", "Quastenberg"], [2, "Ostermeier", "Ostermeier"]]);
expect(result.hits.filter((entry) => entry.segment === 3 || entry.segment === 4)).toHaveLength(0);
expect(Object.values(result.mapping).map((entry) => entry.original)).toEqual([
"Frau Jorinde Quastenberg", "Dr. Ostermeier", "Quastenberg", "Ostermeier",
]);
});

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, {