feat: choose project or session for text commands

This commit is contained in:
muena
2026-10-19 06:34:07 +02:00
parent 65134735f1
commit ebf78128c4
28 changed files with 386 additions and 641 deletions

View File

@@ -62,14 +62,14 @@
{
"name": "pseudonymize-selected-text",
"title": "Markierten Text pseudonymisieren",
"description": "Aktuell markierten Text pseudonymisieren und das Ergebnis kopieren oder einfügen.",
"mode": "no-view"
"description": "Markierten Text mit gewähltem Projekt oder Sitzung pseudonymisieren und kopieren oder einfügen.",
"mode": "view"
},
{
"name": "pseudonymize-clipboard",
"title": "Zwischenablage pseudonymisieren",
"description": "Aktuellen Zwischenablage-Text pseudonymisieren und das Ergebnis kopieren oder einfügen.",
"mode": "no-view"
"description": "Zwischenablage mit gewähltem Projekt oder Sitzung pseudonymisieren und kopieren oder einfügen.",
"mode": "view"
},
{
"name": "depseudonymize-text",
@@ -169,28 +169,6 @@
"required": false,
"default": "profile"
},
{
"name": "sessionMode",
"title": "Standard-Sitzungsmodus",
"description": "Bestimmt, wie Schnellbefehle eine Zuordnungs-Sitzung wählen.",
"type": "dropdown",
"required": true,
"default": "reuse-active",
"data": [
{
"title": "Aktive Sitzung wiederverwenden",
"value": "reuse-active"
},
{
"title": "Neue Sitzung pro Anfrage",
"value": "new-each-request"
},
{
"title": "Tagessitzung",
"value": "daily"
}
]
},
{
"name": "quickOutput",
"title": "Ausgabe der Schnellbefehle",

View File

@@ -90,7 +90,7 @@ export function PseudonymizationConfirm(props: PseudoStageProps) {
>
<Form.Description
title="Bestätigen"
text={`Prüfe den pseudonymisierten Text, bevor er an die KI gesendet wird. Sitzung: ${props.session.name} · ${Object.keys(props.session.mapping).length} Zuordnungen.`}
text={`Prüfe den pseudonymisierten Text, bevor er an die KI gesendet wird. Kontext: ${props.session.name} · ${Object.keys(props.session.mapping).length} Zuordnungen.`}
/>
<Form.TextArea
id="pseudonymizedText"

View File

@@ -8,7 +8,7 @@ import {
Toast,
useNavigation,
} from "@raycast/api";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useState } from "react";
import {
type Creativity,
CREATIVITY_OPTIONS,
@@ -20,20 +20,15 @@ import {
} from "./ai";
import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import type { EntityType, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import {
getEntityTypes,
normalizePseudonymizeResponse,
pseudonymize,
} from "./velum";
function buildBriefingPrompt(
@@ -67,9 +62,8 @@ function buildBriefingPrompt(
].join("\n");
}
type FormValues = {
type FormValues = ContextFormValues & {
text: string;
sessionId: string;
entityTypes: string[];
model: string;
creativity: Creativity;
@@ -115,11 +109,6 @@ export default function Command() {
load();
}, []);
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
@@ -162,23 +151,8 @@ export default function Command() {
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const rawResult = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const pseudoResult = normalizePseudonymizeResponse(rawResult);
const updatedSession = await updateSessionMapping(
session.id,
pseudoResult.mapping,
pseudoResult.selected_entity_types,
);
const { result: pseudoResult, session: updatedSession } =
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
@@ -238,27 +212,8 @@ export default function Command() {
onChange={setText}
placeholder="Meeting-Notizen, Stichpunkte, Transkript …"
/>
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

57
src/context-picker.tsx Normal file
View File

@@ -0,0 +1,57 @@
import { Form, Icon, showToast, Toast } from "@raycast/api";
import { useEffect, useState } from "react";
import { canonicalProjectPath, listAllRuns, loadProjectEntityTypes } from "./lib/velum-project";
import type { EntityType, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID } from "./context-values";
export type { ContextFormValues } from "./context-values";
export function ContextPicker(props: { sessions: VelumSession[]; activeSessionId?: string;
availableEntityTypes: EntityType[]; onEntityTypesChange: (types: EntityType[]) => void }) {
const [projects, setProjects] = useState<Array<{ path: string; name: string }>>([]);
const [selected, setSelected] = useState(CHOOSE_CONTEXT_ID);
useEffect(() => {
let active = true;
listAllRuns().then((runs) => {
if (!active) return;
const unique = new Map<string, string>();
for (const { run } of runs) {
const path = canonicalProjectPath(run.projectPath);
if (!unique.has(path)) unique.set(path, run.projectName);
}
setProjects([...unique].map(([path, name]) => ({ path, name })));
}).catch((error: Error) => showToast({ style: Toast.Style.Failure,
title: "Projekte nicht lesbar", message: error.message }));
return () => { active = false; };
}, []);
async function chooseContext(id: string) {
setSelected(CHOOSE_CONTEXT_ID);
try {
const saved = id.startsWith("project:")
? await loadProjectEntityTypes(id.slice("project:".length)) : null;
props.onEntityTypesChange(saved ?? props.availableEntityTypes);
setSelected(id);
} catch (error) {
await showToast({ style: Toast.Style.Failure,
title: "Projektkategorien nicht lesbar", message: (error as Error).message });
}
}
return <>
<Form.Dropdown id="sessionId" title="Projekt oder Sitzung" value={selected} onChange={chooseContext}>
<Form.Dropdown.Item value={CHOOSE_CONTEXT_ID} title="Bitte Kontext wählen" icon={Icon.Circle} />
{projects.map((project) => <Form.Dropdown.Item key={project.path}
value={`project:${project.path}`} title={`Projekt: ${project.name} · ${project.path}`} icon={Icon.Folder} />)}
<Form.Dropdown.Item value={NEW_PROJECT_ID} title="Neues Projekt aus Ordner" icon={Icon.Plus} />
{props.sessions.map((session) => <Form.Dropdown.Item key={session.id} value={session.id}
title={`Sitzung: ${session.name}`}
icon={session.id === props.activeSessionId ? Icon.CheckCircle : Icon.Circle} />)}
<Form.Dropdown.Item value={NEW_SESSION_ID} title="Neue Sitzung" icon={Icon.Plus} />
</Form.Dropdown>
{selected === NEW_PROJECT_ID && <Form.FilePicker id="newProjectPath" title="Projektordner"
allowMultipleSelection={false} canChooseDirectories canChooseFiles={false} />}
</>;
}

7
src/context-values.ts Normal file
View File

@@ -0,0 +1,7 @@
export const CHOOSE_CONTEXT_ID = "__choose_context__";
export const NEW_PROJECT_ID = "__new_project__";
export type ContextFormValues = {
sessionId: string;
newProjectPath?: string[];
};

View File

@@ -8,7 +8,7 @@ import {
Toast,
useNavigation,
} from "@raycast/api";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useState } from "react";
import {
type Creativity,
CREATIVITY_OPTIONS,
@@ -20,20 +20,15 @@ import {
} from "./ai";
import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import type { EntityType, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import {
getEntityTypes,
normalizePseudonymizeResponse,
pseudonymize,
} from "./velum";
function buildActionItemsPrompt(
@@ -72,9 +67,8 @@ function buildActionItemsPrompt(
].join("\n");
}
type FormValues = {
type FormValues = ContextFormValues & {
text: string;
sessionId: string;
entityTypes: string[];
model: string;
creativity: Creativity;
@@ -120,11 +114,6 @@ export default function Command() {
load();
}, []);
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
@@ -167,23 +156,8 @@ export default function Command() {
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const rawResult = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const pseudoResult = normalizePseudonymizeResponse(rawResult);
const updatedSession = await updateSessionMapping(
session.id,
pseudoResult.mapping,
pseudoResult.selected_entity_types,
);
const { result: pseudoResult, session: updatedSession } =
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
@@ -243,27 +217,8 @@ export default function Command() {
onChange={setText}
placeholder="Meeting-Notizen, Email-Thread, Transkript …"
/>
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -8,7 +8,7 @@ import {
Toast,
useNavigation,
} from "@raycast/api";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useState } from "react";
import {
type Creativity,
CREATIVITY_OPTIONS,
@@ -20,20 +20,15 @@ import {
} from "./ai";
import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import type { EntityType, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import {
getEntityTypes,
normalizePseudonymizeResponse,
pseudonymize,
} from "./velum";
type OutputFormat = "json" | "markdown-table";
@@ -91,11 +86,10 @@ function buildStructuredDataPrompt(args: {
].join("\n");
}
type FormValues = {
type FormValues = ContextFormValues & {
text: string;
schema: string;
format: OutputFormat;
sessionId: string;
entityTypes: string[];
model: string;
creativity: Creativity;
@@ -141,11 +135,6 @@ export default function Command() {
load();
}, []);
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
@@ -195,23 +184,8 @@ export default function Command() {
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const rawResult = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const pseudoResult = normalizePseudonymizeResponse(rawResult);
const updatedSession = await updateSessionMapping(
session.id,
pseudoResult.mapping,
pseudoResult.selected_entity_types,
);
const { result: pseudoResult, session: updatedSession } =
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
@@ -303,27 +277,8 @@ export default function Command() {
/>
))}
</Form.Dropdown>
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -8,9 +8,12 @@ export function mappingRoot(key: string, mapping: PlaceholderMapping): string {
while (mapping[current].merged_into) {
if (seen.has(current)) throw new Error(`Zyklische Zuordnung: ${key}`);
seen.add(current);
const target = mapping[current].merged_into!;
const reference = mapping[current].merged_into!;
const target = mapping[reference] ? reference
: mapping[`<${reference.replace(/^<|>$/g, "")}>`] ? `<${reference.replace(/^<|>$/g, "")}>`
: reference.replace(/^<|>$/g, "");
if (!mapping[target] || mapping[target].type !== initial.type) {
throw new Error(`Ungültiger Hauptbegriff für ${key}: ${target}`);
throw new Error(`Ungültiger Hauptbegriff für ${key}: ${reference}`);
}
current = target;
}

View File

@@ -1,5 +1,5 @@
import { getPreferenceValues } from "@raycast/api";
import type { ExtensionPreferences, QuickOutput, SessionMode } from "./types";
import type { ExtensionPreferences, QuickOutput } from "./types";
export type NormalizedPreferences = {
velumBaseUrl: string;
@@ -8,7 +8,6 @@ export type NormalizedPreferences = {
serviceAccountUsername: string;
serviceAccountPassword: string;
scope: string;
sessionMode: SessionMode;
quickOutput: QuickOutput;
userFullName: string;
maxSessions: number;
@@ -34,7 +33,6 @@ export function getPreferences(): NormalizedPreferences {
serviceAccountUsername: preferences.serviceAccountUsername.trim(),
serviceAccountPassword: preferences.serviceAccountPassword,
scope: preferences.scope?.trim() || "profile",
sessionMode: preferences.sessionMode,
quickOutput: preferences.quickOutput,
userFullName: preferences.userFullName?.trim() ?? "",
maxSessions: parsePositiveInteger(preferences.maxSessions, 20),

View File

@@ -21,20 +21,15 @@ import {
import { PseudonymizationConfirm } from "./ai-views";
import { getPreferences } from "./preferences";
import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import type { EntityType, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import {
getEntityTypes,
normalizePseudonymizeResponse,
pseudonymize,
} from "./velum";
function getIsoWeek(date: Date): number {
@@ -126,9 +121,8 @@ function buildProjectStatusPrompt(userFullName: string) {
};
}
type FormValues = {
type FormValues = ContextFormValues & {
text: string;
sessionId: string;
entityTypes: string[];
model: string;
creativity: Creativity;
@@ -180,11 +174,6 @@ export default function Command() {
load();
}, []);
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
@@ -227,23 +216,8 @@ export default function Command() {
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const rawResult = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const pseudoResult = normalizePseudonymizeResponse(rawResult);
const updatedSession = await updateSessionMapping(
session.id,
pseudoResult.mapping,
pseudoResult.selected_entity_types,
);
const { result: pseudoResult, session: updatedSession } =
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
@@ -303,27 +277,8 @@ export default function Command() {
onChange={setText}
placeholder="Statusmeeting-Stichpunkte, Email-Auszüge, Risiken, Zahlen, Entscheidungen …"
/>
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -1,7 +0,0 @@
import { Clipboard } from "@raycast/api";
import { pseudonymizeQuickText } from "./quick";
export default async function Command() {
const clipboardText = await Clipboard.readText();
await pseudonymizeQuickText(clipboardText ?? "", "Zwischenablage");
}

View File

@@ -0,0 +1,5 @@
import PseudonymizeTextForm from "./pseudonymize-text";
export default function Command() {
return <PseudonymizeTextForm initialSource="clipboard" autoOutput />;
}

View File

@@ -1,15 +0,0 @@
import { showToast, Toast } from "@raycast/api";
import { pseudonymizeQuickText } from "./quick";
import { getSelectedTextSafely } from "./selection";
export default async function Command() {
const selectedText = await getSelectedTextSafely();
if (!selectedText) {
await showToast({
style: Toast.Style.Failure,
title: "Kein markierter Text gefunden",
});
return;
}
await pseudonymizeQuickText(selectedText, "Selektion");
}

View File

@@ -0,0 +1,5 @@
import PseudonymizeTextForm from "./pseudonymize-text";
export default function Command() {
return <PseudonymizeTextForm initialSource="selection" autoOutput />;
}

View File

@@ -5,36 +5,31 @@ import {
Detail,
Form,
Icon,
showHUD,
showToast,
Toast,
useNavigation,
} from "@raycast/api";
import { getSelectedTextSafely } from "./selection";
import { useEffect, useMemo, useState } from "react";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import { useEffect, useState } from "react";
import { getActiveSessionId, listSessions } from "./sessions";
import type { EntityType, PseudonymizeResponse, VelumSession } from "./types";
import {
markdownCodeBlock,
mappingSummary,
NEW_SESSION_ID,
sessionSubtitle,
} from "./ui";
import { getEntityTypes, pseudonymize } from "./velum";
import { getEntityTypes } from "./velum";
import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context";
import { getPreferences } from "./preferences";
type FormValues = {
type FormValues = ContextFormValues & {
text: string;
sessionId: string;
entityTypes: string[];
};
export default function Command() {
export default function Command(props: { initialSource?: "selection" | "clipboard"; autoOutput?: boolean } = {}) {
const [text, setText] = useState("");
const [sessions, setSessions] = useState<VelumSession[]>([]);
const [activeSessionId, setActiveSessionId] = useState<string>();
@@ -51,6 +46,15 @@ export default function Command() {
]);
setSessions(loadedSessions);
setActiveSessionId(activeId);
if (props.initialSource === "selection") {
const selected = await getSelectedTextSafely();
if (selected) setText(selected);
else await showToast({ style: Toast.Style.Failure, title: "Kein markierter Text gefunden" });
} else if (props.initialSource === "clipboard") {
const clipboard = await Clipboard.readText();
if (clipboard) setText(clipboard);
else await showToast({ style: Toast.Style.Failure, title: "Zwischenablage enthält keinen Text" });
}
try {
const loadedEntityTypes = await getEntityTypes();
@@ -65,11 +69,6 @@ export default function Command() {
load();
}, []);
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
@@ -110,27 +109,21 @@ export default function Command() {
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const result = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const updatedSession = await updateSessionMapping(
session.id,
result.mapping,
result.selected_entity_types,
);
const { result, session } = await pseudonymizeInContext(values, input, values.entityTypes);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
toast.message = `${result.entity_count} Zuordnungen in ${updatedSession.name}`;
toast.message = `${result.entity_count} Zuordnungen in ${session.name}`;
push(<PseudonymizeResult result={result} session={updatedSession} />);
if (props.autoOutput) {
if (getPreferences().quickOutput === "paste") {
await Clipboard.paste(result.pseudonymized_text);
await showHUD(`Pseudonymisierten Text eingefügt (${session.name})`);
} else {
await Clipboard.copy(result.pseudonymized_text);
await showHUD(`Pseudonymisierten Text kopiert (${session.name})`);
}
} else push(<PseudonymizeResult result={result} session={session} />);
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen";
@@ -168,27 +161,8 @@ export default function Command() {
onChange={setText}
placeholder="Zu pseudonymisierender Text"
/>
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

View File

@@ -1,121 +0,0 @@
import { Clipboard, showHUD, showToast, Toast } from "@raycast/api";
import { getPreferences } from "./preferences";
import {
getActiveSession,
resolveDefaultSession,
updateSessionMapping,
} from "./sessions";
import type { VelumSession } from "./types";
import { localDepseudonymize, pseudonymize } from "./velum";
export async function pseudonymizeQuickText(
text: string,
source: string,
): Promise<void> {
const trimmed = text.trim();
if (!trimmed) {
await showToast({
style: Toast.Style.Failure,
title: `Kein Text in ${source} gefunden`,
});
return;
}
const toast = await showToast({
style: Toast.Style.Animated,
title: "Pseudonymisiere…",
});
try {
const session = await resolveDefaultSession();
const result = await pseudonymize(
trimmed,
session.mapping,
session.entityTypes,
);
const updatedSession = await updateSessionMapping(
session.id,
result.mapping,
result.selected_entity_types,
);
await writeQuickOutput(
result.pseudonymized_text,
updatedSession,
"Pseudonymisierten Text",
);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
toast.message = `${result.entity_count} Zuordnungen in ${updatedSession.name}`;
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Pseudonymisierung fehlgeschlagen";
toast.message = error instanceof Error ? error.message : String(error);
}
}
export async function depseudonymizeQuickText(
text: string,
source: string,
): Promise<void> {
const trimmed = text.trim();
if (!trimmed) {
await showToast({
style: Toast.Style.Failure,
title: `Kein Text in ${source} gefunden`,
});
return;
}
const toast = await showToast({
style: Toast.Style.Animated,
title: "Stelle wieder her…",
});
try {
const session = await getActiveSession();
if (Object.keys(session.mapping).length === 0) {
toast.style = Toast.Style.Failure;
toast.title = "Aktive Sitzung hat keine Zuordnungen";
toast.message = session.name;
return;
}
const result = localDepseudonymize(trimmed, session.mapping);
if (result.replacements_made === 0) {
toast.style = Toast.Style.Failure;
toast.title = "Keine Platzhalter ersetzt";
toast.message = `Sitzung: ${session.name}`;
return;
}
await writeQuickOutput(
result.original_text,
session,
"Wiederhergestellten Text",
);
toast.style = Toast.Style.Success;
toast.title = "Wiederhergestellt";
toast.message = `${result.replacements_made} Ersetzungen in ${session.name}`;
} catch (error) {
toast.style = Toast.Style.Failure;
toast.title = "Wiederherstellung fehlgeschlagen";
toast.message = error instanceof Error ? error.message : String(error);
}
}
async function writeQuickOutput(
text: string,
session: VelumSession,
textKind: string,
): Promise<void> {
if (getPreferences().quickOutput === "paste") {
await Clipboard.paste(text);
await showHUD(`${textKind} eingefügt (${session.name})`);
return;
}
await Clipboard.copy(text);
await showHUD(`${textKind} kopiert (${session.name})`);
}

View File

@@ -11,7 +11,9 @@ import {
useNavigation,
} from "@raycast/api";
import { getSelectedTextSafely } from "./selection";
import { useEffect, useMemo, useRef, useState } from "react";
import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context";
import { useEffect, useRef, useState } from "react";
import {
CREATIVITY_OPTIONS,
DEFAULT_MODEL,
@@ -32,31 +34,23 @@ import {
SIGN_OFF_OPTIONS,
} from "./reply";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import type { Creativity } from "./summarize";
import type { EntityType, VelumSession } from "./types";
import {
markdownCodeBlock,
mappingDetailTable,
NEW_SESSION_ID,
sessionSubtitle,
} from "./ui";
import {
getEntityTypes,
localDepseudonymize,
normalizePseudonymizeResponse,
pseudonymize,
} from "./velum";
type FormValues = {
type FormValues = ContextFormValues & {
text: string;
sessionId: string;
entityTypes: string[];
instructions: string;
};
@@ -133,11 +127,6 @@ export default function Command() {
});
}
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
@@ -194,23 +183,8 @@ export default function Command() {
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const rawResult = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const pseudoResult = normalizePseudonymizeResponse(rawResult);
const updatedSession = await updateSessionMapping(
session.id,
pseudoResult.mapping,
pseudoResult.selected_entity_types,
);
const { result: pseudoResult, session: updatedSession } =
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
@@ -324,27 +298,8 @@ export default function Command() {
info="Listet am Ende der Email auf, welche Originalbegriffe vor dem KI-Aufruf lokal durch Platzhalter ersetzt wurden."
/>
<Form.Separator />
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"
@@ -473,7 +428,7 @@ function ConfirmReply(props: StageProps) {
>
<Form.Description
title="Bestätigen"
text={`Prüfe den pseudonymisierten Text vor dem KI-Aufruf. Die KI verfasst die Anrede mit dem passenden Platzhalter selbst — nur die Signatur wird lokal angefügt. Sitzung: ${props.session.name} · ${Object.keys(props.session.mapping).length} Zuordnungen.`}
text={`Prüfe den pseudonymisierten Text vor dem KI-Aufruf. Die KI verfasst die Anrede mit dem passenden Platzhalter selbst — nur die Signatur wird lokal angefügt. Kontext: ${props.session.name} · ${Object.keys(props.session.mapping).length} Zuordnungen.`}
/>
<Form.TextArea
id="pseudonymizedText"

View File

@@ -1,7 +1,7 @@
import { LocalStorage } from "@raycast/api";
import { randomUUID } from "node:crypto";
import { getPreferences } from "./preferences";
import type { PlaceholderMapping, SessionMode, VelumSession } from "./types";
import type { PlaceholderMapping, VelumSession } from "./types";
const SESSIONS_STORAGE_KEY = "velum.sessions.v1";
const ACTIVE_SESSION_STORAGE_KEY = "velum.sessions.active.v1";
@@ -10,10 +10,6 @@ function nowIso(): string {
return new Date().toISOString();
}
function dayKey(date = new Date()): string {
return date.toISOString().slice(0, 10);
}
function sessionSort(a: VelumSession, b: VelumSession): number {
return Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
}
@@ -85,32 +81,6 @@ export async function getActiveSession(): Promise<VelumSession> {
return createSession();
}
export async function resolveSessionForMode(
mode: SessionMode,
): Promise<VelumSession> {
if (mode === "new-each-request") {
return createSession(`Anfrage ${new Date().toLocaleString()}`);
}
if (mode === "daily") {
const name = `Tag ${dayKey()}`;
const existing = (await listSessions()).find(
(session) => session.name === name,
);
if (existing) {
await setActiveSession(existing.id);
return existing;
}
return createSession(name);
}
return getActiveSession();
}
export async function resolveDefaultSession(): Promise<VelumSession> {
return resolveSessionForMode(getPreferences().sessionMode);
}
export async function updateSessionMapping(
id: string,
mapping: PlaceholderMapping,

View File

@@ -14,14 +14,12 @@ import {
import { markdownToHtml, maybeCloseRaycast } from "./ai-views";
import { copyRichText } from "./rich-clipboard";
import { getSelectedTextSafely } from "./selection";
import { useEffect, useMemo, useRef, useState } from "react";
import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context";
import { useEffect, useRef, useState } from "react";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import {
CREATIVITY_OPTIONS,
@@ -35,19 +33,15 @@ import type { EntityType, VelumSession } from "./types";
import {
markdownCodeBlock,
mappingDetailTable,
NEW_SESSION_ID,
sessionSubtitle,
} from "./ui";
import {
getEntityTypes,
localDepseudonymize,
normalizePseudonymizeResponse,
pseudonymize,
} from "./velum";
type FormValues = {
type FormValues = ContextFormValues & {
text: string;
sessionId: string;
entityTypes: string[];
model: string;
creativity: Creativity;
@@ -93,11 +87,6 @@ export default function Command() {
load();
}, []);
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
@@ -140,23 +129,8 @@ export default function Command() {
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const rawResult = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const pseudoResult = normalizePseudonymizeResponse(rawResult);
const updatedSession = await updateSessionMapping(
session.id,
pseudoResult.mapping,
pseudoResult.selected_entity_types,
);
const { result: pseudoResult, session: updatedSession } =
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
@@ -208,27 +182,8 @@ export default function Command() {
onChange={setText}
placeholder="Email-Konversation einfügen oder laden"
/>
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"
@@ -330,7 +285,7 @@ function ConfirmPseudonymized({
>
<Form.Description
title="Bestätigen"
text={`Prüfe den pseudonymisierten Text, bevor er an die KI gesendet wird. Platzhalter wie <PERSON_1> werden nach der Zusammenfassung wiederhergestellt. Sitzung: ${session.name} · ${Object.keys(session.mapping).length} Zuordnungen.`}
text={`Prüfe den pseudonymisierten Text, bevor er an die KI gesendet wird. Platzhalter wie <PERSON_1> werden nach der Zusammenfassung wiederhergestellt. Kontext: ${session.name} · ${Object.keys(session.mapping).length} Zuordnungen.`}
/>
<Form.TextArea
id="pseudonymizedText"

View File

@@ -8,7 +8,7 @@ import {
Toast,
useNavigation,
} from "@raycast/api";
import { useEffect, useMemo, useState } from "react";
import { useEffect, useState } from "react";
import {
type Creativity,
CREATIVITY_OPTIONS,
@@ -20,20 +20,15 @@ import {
} from "./ai";
import { PseudonymizationConfirm } from "./ai-views";
import { getSelectedTextSafely } from "./selection";
import { ContextPicker, type ContextFormValues } from "./context-picker";
import { pseudonymizeInContext } from "./text-context";
import {
createSession,
getActiveSessionId,
getSession,
listSessions,
setActiveSession,
updateSessionMapping,
} from "./sessions";
import type { EntityType, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import {
getEntityTypes,
normalizePseudonymizeResponse,
pseudonymize,
} from "./velum";
function buildMeetingNotesPrompt(
@@ -98,9 +93,8 @@ function buildMeetingNotesPrompt(
].join("\n");
}
type FormValues = {
type FormValues = ContextFormValues & {
text: string;
sessionId: string;
entityTypes: string[];
model: string;
creativity: Creativity;
@@ -146,11 +140,6 @@ export default function Command() {
load();
}, []);
const defaultSessionId = useMemo(
() => activeSessionId || sessions[0]?.id || NEW_SESSION_ID,
[activeSessionId, sessions],
);
async function loadSelectedText() {
const selected = await getSelectedTextSafely();
if (!selected) {
@@ -193,23 +182,8 @@ export default function Command() {
});
try {
const session =
values.sessionId === NEW_SESSION_ID
? await createSession()
: ((await getSession(values.sessionId)) ?? (await createSession()));
await setActiveSession(session.id);
const rawResult = await pseudonymize(
input,
session.mapping,
values.entityTypes,
);
const pseudoResult = normalizePseudonymizeResponse(rawResult);
const updatedSession = await updateSessionMapping(
session.id,
pseudoResult.mapping,
pseudoResult.selected_entity_types,
);
const { result: pseudoResult, session: updatedSession } =
await pseudonymizeInContext(values, input, values.entityTypes, true);
toast.style = Toast.Style.Success;
toast.title = "Pseudonymisiert";
@@ -269,27 +243,8 @@ export default function Command() {
onChange={setText}
placeholder="Meeting-Notizen als Fließtext einfügen — z. B. handgeschriebene Protokollnotizen, ein diktiertes Transkript oder ein zusammenhängender Bericht."
/>
<Form.Dropdown
id="sessionId"
title="Sitzung"
defaultValue={defaultSessionId}
>
<Form.Dropdown.Item
value={NEW_SESSION_ID}
title="Neue Sitzung"
icon={Icon.Plus}
/>
{sessions.map((session) => (
<Form.Dropdown.Item
key={session.id}
value={session.id}
title={session.name}
icon={
session.id === activeSessionId ? Icon.CheckCircle : Icon.Circle
}
/>
))}
</Form.Dropdown>
<ContextPicker sessions={sessions} activeSessionId={activeSessionId}
availableEntityTypes={entityTypes} onEntityTypesChange={setSelectedEntityTypes} />
{entityTypes.length > 0 ? (
<Form.TagPicker
id="entityTypes"

98
src/text-context.ts Normal file
View File

@@ -0,0 +1,98 @@
import { promises as fs } from "node:fs";
import { canonicalProjectPath, createRun, forceMasks, listRuns, loadProjectRules,
loadProjectWhitelist, replaceSpans, saveRun, toUtf16Offsets, updateProjectMapping, whitelistKey } from "./lib/velum-project";
import { mappingForRestoration } from "./lib/mapping-groups";
import type { ProjectWhitelistEntry } from "./lib/velum-project";
import { CHOOSE_CONTEXT_ID, NEW_PROJECT_ID, type ContextFormValues } from "./context-values";
import { createSession, getSession, setActiveSession, updateSessionMapping } from "./sessions";
import type { EntityType, PlaceholderMapping, PseudonymizeResponse, VelumSession } from "./types";
import { NEW_SESSION_ID } from "./ui";
import { normalizePseudonymizeResponse, pseudonymize } from "./velum";
function projectMapping(mapping: PlaceholderMapping): PlaceholderMapping {
return Object.fromEntries(Object.entries(mapping).map(([key, entry]) => [
key.replace(/^<|>$/g, ""),
{ ...entry, merged_into: entry.merged_into?.replace(/^<|>$/g, "") },
]));
}
function resultSession(path: string, name: string, mapping: PlaceholderMapping,
entityTypes: EntityType[]): VelumSession {
const now = new Date().toISOString();
return { id: `project:${path}`, name: `Projekt ${name}`, mapping,
entityTypes, createdAt: now, updatedAt: now };
}
export function applyProjectWhitelist(text: string, response: PseudonymizeResponse,
previous: PlaceholderMapping, whitelist: ProjectWhitelistEntry[]): PseudonymizeResponse {
const excluded = new Set(whitelist.map(whitelistKey));
if (!excluded.size || !response.spans.some((span) => excluded.has(whitelistKey(span)))) return response;
const accepted = response.spans.filter((span) => !excluded.has(whitelistKey(span)));
const spans = toUtf16Offsets(text, accepted).map((span, index) => ({ ...span, id: String(index) }));
const active = new Set(accepted.map((span) => span.placeholder.replace(/^<|>$/g, "")));
const known = new Set(Object.keys(previous).map((key) => key.replace(/^<|>$/g, "")));
return {
...response,
pseudonymized_text: replaceSpans(text, spans, new Set(spans.map((span) => span.id))),
spans: accepted,
entity_count: active.size,
mapping: Object.fromEntries(Object.entries(response.mapping).filter(([key]) =>
active.has(key.replace(/^<|>$/g, "")) || known.has(key.replace(/^<|>$/g, "")))),
};
}
/** A text command must use the context explicitly selected in its form. */
export async function pseudonymizeInContext(values: ContextFormValues, text: string,
entityTypes: EntityType[], forAi = false,
request: typeof pseudonymize = pseudonymize): Promise<{ result: PseudonymizeResponse; session: VelumSession }> {
const selected = values.sessionId;
if (!selected || selected === CHOOSE_CONTEXT_ID) {
throw new Error("Bitte ein Projekt oder eine Sitzung wählen.");
}
if (selected === NEW_PROJECT_ID || selected.startsWith("project:")) {
const folder = selected === NEW_PROJECT_ID ? values.newProjectPath?.[0] : selected.slice("project:".length);
if (!folder || !(await fs.stat(folder).catch(() => undefined))?.isDirectory()) {
throw new Error("Bitte einen vorhandenen Projektordner wählen.");
}
const path = canonicalProjectPath(folder);
const latest = (await listRuns(path))[0];
if (selected === NEW_PROJECT_ID && latest) {
throw new Error("Für diesen Ordner besteht bereits ein Projekt. Bitte es in der Liste wählen.");
}
if (selected !== NEW_PROJECT_ID && !latest) {
throw new Error("Projektstand nicht gefunden. Bitte die Liste aktualisieren.");
}
const [rules, whitelist] = await Promise.all([loadProjectRules(path), loadProjectWhitelist(path)]);
const excluded = new Set(whitelist.map(whitelistKey));
const masks = forceMasks(rules.filter((rule) => !excluded.has(whitelistKey({
type: rule.type, original: rule.value,
}))));
const raw = applyProjectWhitelist(text,
await request(text, latest?.run.mapping ?? {}, entityTypes, masks), latest?.run.mapping ?? {}, whitelist);
const mapping = projectMapping(raw.mapping);
if (latest) {
await updateProjectMapping(path, (current) => {
if (JSON.stringify(current) !== JSON.stringify(latest.run.mapping)) {
throw new Error("Der Projektstand wurde inzwischen geändert. Bitte den Befehl erneut öffnen.");
}
return mapping;
});
} else {
const created = await createRun(path);
created.run.mapping = mapping;
await saveRun(created.directory, created.run);
}
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
const resultMapping = forAi ? result.mapping : mapping;
return { result, session: resultSession(path, latest?.run.projectName ?? path.split("/").filter(Boolean).at(-1) ?? path,
mappingForRestoration(resultMapping), result.selected_entity_types) };
}
const session = selected === NEW_SESSION_ID ? await createSession() : await getSession(selected);
if (!session) throw new Error("Sitzung nicht gefunden. Bitte die Liste aktualisieren.");
await setActiveSession(session.id);
const raw = await request(text, session.mapping, entityTypes);
const result = forAi ? normalizePseudonymizeResponse(raw) : raw;
const saved = await updateSessionMapping(session.id, result.mapping, result.selected_entity_types);
return { result, session: { ...saved, mapping: mappingForRestoration(saved.mapping) } };
}

View File

@@ -37,7 +37,6 @@ export type VelumSession = {
entityTypes?: EntityType[];
};
export type SessionMode = "reuse-active" | "new-each-request" | "daily";
export type QuickOutput = "copy" | "paste";
export type ExtensionPreferences = {
@@ -47,7 +46,6 @@ export type ExtensionPreferences = {
serviceAccountUsername: string;
serviceAccountPassword: string;
scope?: string;
sessionMode: SessionMode;
quickOutput: QuickOutput;
userFullName?: string;
maxSessions: string;

View File

@@ -19,7 +19,10 @@ export function normalizePseudonymizeResponse(
for (const [key, entry] of Object.entries(response.mapping)) {
const stripped = key.replace(/[<>]/g, "");
normalizedMapping[`<${stripped}>`] = entry;
normalizedMapping[`<${stripped}>`] = {
...entry,
merged_into: entry.merged_into ? `<${entry.merged_into.replace(/[<>]/g, "")}>` : entry.merged_into,
};
strippedKeys.add(stripped);
}

View File

@@ -39,4 +39,11 @@ describe("Zuordnungen gruppieren und wiederherstellen", () => {
PERSON_02: { type: "PERSON", original: "B", merged_into: "PERSON_01" },
})).toThrow("Zyklische Zuordnung");
});
it("löst ältere Sitzungsverweise mit geklammerten Schlüsseln auf", () => {
expect(mappingForRestoration({
"<PERSON_01>": { type: "PERSON", original: "Franz Fuchs" },
"<PERSON_02>": { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
})["<PERSON_02>"].original).toBe("Franz Fuchs");
});
});

View File

@@ -5,7 +5,9 @@ import { join } from "node:path";
import { createHash } from "node:crypto";
import { migrate } from "../tools/migrate-ki-datenschutz.mjs";
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() } }));
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() },
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
LocalStorage: {}, getPreferenceValues: () => ({}) }));
const { restorePath, restoreText } = await import("../src/lib/velum-project");
const roots: string[] = [];
afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); });

View File

@@ -3,7 +3,9 @@ import { promises as fs } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() } }));
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() },
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
LocalStorage: {}, getPreferenceValues: () => ({}) }));
const project = await import("../src/lib/velum-project");
const revision = await import("../src/lib/project-revision");
const roots: string[] = [];

View File

@@ -0,0 +1,94 @@
import { afterEach, expect, it, mock } from "bun:test";
import { promises as fs } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import type { PlaceholderMapping, PseudonymizeResponse } from "../src/types";
mock.module("@raycast/api", () => ({
environment: { supportPath: tmpdir() },
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
LocalStorage: {}, getPreferenceValues: () => ({}),
}));
const { applyProjectWhitelist, pseudonymizeInContext } = await import("../src/text-context");
const project = await import("../src/lib/velum-project");
const { normalizePseudonymizeResponse } = await import("../src/velum");
const roots: string[] = [];
afterEach(async () => { await Promise.all(roots.splice(0).map((root) => fs.rm(root, { recursive: true, force: true }))); });
it("behält Verweise beim Umstellen auf KI-Platzhalter konsistent", () => {
const result = normalizePseudonymizeResponse({
pseudonymized_text: "PERSON_02", selected_entity_types: ["PERSON"], spans: [], entity_count: 1,
mapping: {
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
},
});
expect(result.mapping["<PERSON_02>"].merged_into).toBe("<PERSON_01>");
expect(result.pseudonymized_text).toBe("<PERSON_02>");
});
it("übernimmt eine Projekt-Ausnahme auch bei Textbefehlen", () => {
const result = applyProjectWhitelist("Max und Montag", {
pseudonymized_text: "PERSON_01 und ORT_01", selected_entity_types: ["PERSON", "ORT"],
spans: [
{ start: 0, end: 3, type: "PERSON", score: 1, placeholder: "PERSON_01", original: "Max" },
{ start: 8, end: 14, type: "ORT", score: 1, placeholder: "ORT_01", original: "Montag" },
], entity_count: 2,
mapping: {
PERSON_01: { type: "PERSON", original: "Max" },
ORT_01: { type: "ORT", original: "Montag" },
},
}, {}, [{ type: "ORT", original: "Montag" }]);
expect(result.pseudonymized_text).toBe("PERSON_01 und Montag");
expect(result.mapping.ORT_01).toBeUndefined();
expect(result.entity_count).toBe(1);
});
it("verlangt eine ausdrückliche Kontextwahl und legt ein Textprojekt nur einmal an", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-context-"));
roots.push(root);
const folder = join(root, "Projekt");
await fs.mkdir(folder);
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => ({
pseudonymized_text: "PERSON_01", mapping: {
...mapping, PERSON_01: { type: "PERSON", original: "Alex Beispiel" },
}, selected_entity_types: ["PERSON"], spans: [], entity_count: 1,
});
await expect(pseudonymizeInContext({ sessionId: "__choose_context__" }, "Alex Beispiel", ["PERSON"], false, request))
.rejects.toThrow("Bitte ein Projekt");
const created = await pseudonymizeInContext({ sessionId: "__new_project__", newProjectPath: [folder] },
"Alex Beispiel", ["PERSON"], false, request);
expect(created.session.name).toBe("Projekt Projekt");
expect((await project.listRuns(folder)).length).toBe(1);
await expect(pseudonymizeInContext({ sessionId: "__new_project__", newProjectPath: [folder] },
"Alex Beispiel", ["PERSON"], false, request)).rejects.toThrow("bereits ein Projekt");
});
it("verwendet die bestehende Projekttabelle und bewahrt ihre Verweise für spätere Läufe", async () => {
const root = await fs.mkdtemp(join(tmpdir(), "velum-text-reuse-"));
roots.push(root);
const folder = join(root, "Quelle");
await fs.mkdir(folder);
const saved = await project.createRun(folder);
saved.run.mapping = {
PERSON_01: { type: "PERSON", original: "Franz Fuchs" },
PERSON_02: { type: "PERSON", original: "Hr. Fuchs", merged_into: "PERSON_01" },
};
await project.saveRun(saved.directory, saved.run);
const request = async (_text: string, mapping: PlaceholderMapping): Promise<PseudonymizeResponse> => {
expect(mapping.PERSON_02.merged_into).toBe("PERSON_01");
return { pseudonymized_text: "PERSON_02 und PERSON_03", mapping: {
...mapping, PERSON_03: { type: "PERSON", original: "Mara Muster" },
}, selected_entity_types: ["PERSON"], spans: [], entity_count: 2 };
};
const { result, session } = await pseudonymizeInContext({ sessionId: `project:${folder}` },
"Hr. Fuchs und Mara Muster", ["PERSON"], true, request);
expect(result.pseudonymized_text).toBe("<PERSON_02> und <PERSON_03>");
expect(session.mapping["<PERSON_02>"].original).toBe("Franz Fuchs");
const runs = await project.listRuns(folder);
expect(runs).toHaveLength(2);
expect(runs[0].run.mapping.PERSON_02.original).toBe("Hr. Fuchs");
expect(runs[0].run.mapping.PERSON_02.merged_into).toBe("PERSON_01");
expect(runs[0].run.mapping.PERSON_03.original).toBe("Mara Muster");
expect(runs[1].run.mapping.PERSON_03).toBeUndefined();
});

View File

@@ -4,7 +4,9 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import type { RunFile } from "../src/lib/velum-project";
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() } }));
mock.module("@raycast/api", () => ({ environment: { supportPath: tmpdir() },
Form: {}, Icon: {}, Toast: { Style: {} }, showToast: async () => undefined,
LocalStorage: {}, getPreferenceValues: () => ({}) }));
const project = await import("../src/lib/velum-project");
const { mappingForRestoration } = await import("../src/lib/mapping-groups");
const { mergeMappingGroups } = await import("../src/lib/mapping-groups");