Files
velum-raycast/src/ai-views.tsx
muena 1843479884 Initial commit: Velum Raycast extension
Pseudonymize-and-AI workflow for handling PII-sensitive text via the
Velum API and Raycast AI. Commands cover end-to-end email summary and
reply, briefing/action-items/structured-data extraction, manual
pseudonymize/depseudonymize on selection or clipboard, and session
management. Includes Raycast 2.0 Beta workarounds for selection capture
and rich-text clipboard.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-20 06:46:42 +02:00

342 lines
9.7 KiB
TypeScript

import {
Action,
ActionPanel,
AI,
Clipboard,
closeMainWindow,
Detail,
Form,
Icon,
PopToRootType,
showHUD,
showToast,
Toast,
useNavigation,
} from "@raycast/api";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { marked } from "marked";
import { type ReactNode, useEffect, useRef, useState } from "react";
import type { Creativity } from "./ai";
import { getPreferences } from "./preferences";
import type { VelumSession } from "./types";
import { markdownCodeBlock, mappingDetailTable, sessionSubtitle } from "./ui";
import { localDepseudonymize } from "./velum";
export async function maybeCloseRaycast(): Promise<void> {
if (getPreferences().closeAfterAction) {
await closeMainWindow({ popToRootType: PopToRootType.Immediate });
}
}
const execFileAsync = promisify(execFile);
// Raycast 2.0 Beta's Clipboard.copy with { html, text } only writes plain text
// to the system pasteboard. We bypass it via osascript / JXA, which sets both
// the HTML and plain-text pasteboard types directly on NSPasteboard. Content
// is passed via environment variables to avoid shell-quoting hazards.
const RICH_COPY_SCRIPT = [
"ObjC.import('AppKit');",
"const env = $.NSProcessInfo.processInfo.environment;",
"const html = env.objectForKey('VELUM_HTML');",
"const text = env.objectForKey('VELUM_TEXT');",
"const pb = $.NSPasteboard.generalPasteboard;",
"pb.clearContents;",
"pb.setStringForType(html, 'public.html');",
"pb.setStringForType(text, 'public.utf8-plain-text');",
].join("\n");
export async function copyRichText(html: string, text: string): Promise<void> {
await execFileAsync(
"osascript",
["-l", "JavaScript", "-e", RICH_COPY_SCRIPT],
{
env: { ...process.env, VELUM_HTML: html, VELUM_TEXT: text },
},
);
}
export type AiCommandLabels = {
pageHeading: string;
runningLabel: string;
doneLabel?: string;
failureTitle: string;
copyTitle: string;
pasteTitle: string;
};
export type PseudoStageProps = {
session: VelumSession;
pseudonymizedText: string;
model: string;
creativity: Creativity;
instructions: string;
buildPrompt: (pseudonymizedText: string, instructions: string) => string;
labels: AiCommandLabels;
extraResultActions?: (restored: string) => ReactNode;
};
export function PseudonymizationConfirm(props: PseudoStageProps) {
const [editedText, setEditedText] = useState(props.pseudonymizedText);
const [editedInstructions, setEditedInstructions] = useState(
props.instructions,
);
const { push } = useNavigation();
async function handleSubmit() {
if (!editedText.trim()) {
await showToast({
style: Toast.Style.Failure,
title: "Pseudonymisierter Text ist leer",
});
return;
}
push(
<AiStreamResult
{...props}
pseudonymizedText={editedText}
instructions={editedInstructions}
/>,
);
}
return (
<Form
actions={
<ActionPanel>
<Action.SubmitForm
title="An KI senden"
icon={Icon.Wand}
onSubmit={handleSubmit}
/>
<Action.CopyToClipboard
title="Pseudonymisierten Text kopieren"
content={editedText}
/>
</ActionPanel>
}
>
<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.`}
/>
<Form.TextArea
id="pseudonymizedText"
title="Pseudonymisierter Text"
value={editedText}
onChange={setEditedText}
/>
<Form.TextArea
id="instructions"
title="Zusätzliche Anweisungen"
value={editedInstructions}
onChange={setEditedInstructions}
placeholder="Optional"
/>
</Form>
);
}
type Phase = "running" | "restoring" | "done" | "error";
export function AiStreamResult(props: PseudoStageProps) {
const {
session,
pseudonymizedText,
model,
creativity,
instructions,
buildPrompt,
labels,
extraResultActions,
} = props;
const [aiBuffer, setAiBuffer] = useState("");
const [restored, setRestored] = useState<string | null>(null);
const [replacementsMade, setReplacementsMade] = useState<number>(0);
const [phase, setPhase] = useState<Phase>("running");
const [error, setError] = useState<string | null>(null);
const controllerRef = useRef<AbortController | null>(null);
useEffect(() => {
const controller = new AbortController();
controllerRef.current = controller;
let cancelled = false;
async function run() {
const toast = await showToast({
style: Toast.Style.Animated,
title: labels.runningLabel,
});
try {
const prompt = buildPrompt(pseudonymizedText, instructions);
const stream = AI.ask(prompt, {
model: model as AI.Model,
creativity,
signal: controller.signal,
});
stream.on("data", (chunk) => {
if (cancelled) return;
setAiBuffer((prev) => prev + chunk);
});
const aiText = await stream;
if (cancelled) return;
toast.title = "Stelle wieder her…";
setPhase("restoring");
const restoreResult = localDepseudonymize(aiText, session.mapping);
if (cancelled) return;
setRestored(restoreResult.original_text);
setReplacementsMade(restoreResult.replacements_made);
setPhase("done");
toast.style = Toast.Style.Success;
toast.title = labels.doneLabel ?? "Fertig";
toast.message = `${restoreResult.replacements_made} Ersetzungen`;
} catch (err) {
if (cancelled || controller.signal.aborted) return;
const message = err instanceof Error ? err.message : String(err);
setError(message);
setPhase("error");
toast.style = Toast.Style.Failure;
toast.title = labels.failureTitle;
toast.message = message;
}
}
run();
return () => {
cancelled = true;
controller.abort();
};
}, [
pseudonymizedText,
model,
creativity,
instructions,
session.mapping,
buildPrompt,
labels.runningLabel,
labels.doneLabel,
labels.failureTitle,
]);
const phaseLabel =
phase === "running"
? labels.runningLabel
: phase === "restoring"
? "Platzhalter werden ersetzt …"
: phase === "error"
? "Fehler"
: (labels.doneLabel ?? "Fertig");
const body = restored ?? aiBuffer;
const markdown = [
`# ${labels.pageHeading} — ${session.name}`,
sessionSubtitle(session),
`*Status:* ${phaseLabel}`,
"",
body.trim() ? body : "_Noch keine Inhalte — warte auf das Modell …_",
"",
restored ? `*${replacementsMade} Platzhalter ersetzt.*` : "",
"",
"## Pseudonymisierte Eingabe",
markdownCodeBlock(pseudonymizedText),
"",
"## Pseudonymisierte KI-Ausgabe",
aiBuffer.trim()
? markdownCodeBlock(aiBuffer)
: "_Noch nichts vom Modell empfangen._",
"",
"## Zuordnung",
mappingDetailTable(session.mapping),
error ? `\n> Fehler: ${error}` : "",
].join("\n");
const isLoading = phase === "running" || phase === "restoring";
return (
<Detail
isLoading={isLoading}
markdown={markdown}
actions={
<ActionPanel>
{restored ? (
<>
{extraResultActions ? extraResultActions(restored) : null}
<Action
title={labels.copyTitle}
icon={Icon.Clipboard}
onAction={async () => {
try {
await copyRichText(markdownToHtml(restored), restored);
await showHUD("Als Rich Text kopiert");
} catch {
await Clipboard.copy(restored);
await showHUD("Kopiert (Plain Text Fallback)");
}
await closeMainWindow({
popToRootType: PopToRootType.Immediate,
});
}}
/>
<Action
title={`${labels.copyTitle} (Markdown)`}
icon={Icon.CodeBlock}
onAction={async () => {
await Clipboard.copy(restored);
await showHUD("Als Markdown kopiert");
await closeMainWindow({
popToRootType: PopToRootType.Immediate,
});
}}
/>
<Action
title={labels.pasteTitle}
icon={Icon.TextCursor}
onAction={async () => {
await Clipboard.paste({
html: markdownToHtml(restored),
text: restored,
});
await closeMainWindow({
popToRootType: PopToRootType.Immediate,
});
}}
/>
</>
) : null}
{aiBuffer ? (
<Action.CopyToClipboard
title="Pseudonymisierte KI-Ausgabe kopieren"
content={aiBuffer}
/>
) : null}
<Action.CopyToClipboard
title="Pseudonymisierte Eingabe kopieren"
content={pseudonymizedText}
/>
</ActionPanel>
}
/>
);
}
function stripOuterFence(text: string): string {
const trimmed = text.trim();
const match = trimmed.match(/^```[a-zA-Z0-9-]*\s*\n([\s\S]*?)\n```\s*$/);
return match ? match[1].trim() : trimmed;
}
export function markdownToHtml(markdownText: string): string {
return marked.parse(stripOuterFence(markdownText), {
async: false,
gfm: true,
breaks: false,
}) as string;
}