import { Action, ActionPanel, AI, Clipboard, closeMainWindow, Detail, Form, Icon, PopToRootType, showHUD, showToast, Toast, useNavigation, } from "@raycast/api"; 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"; import { copyRichText } from "./rich-clipboard"; export async function maybeCloseRaycast(): Promise { if (getPreferences().closeAfterAction) { await closeMainWindow({ popToRootType: PopToRootType.Immediate }); } } 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( , ); } return (
} > ); } 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(null); const [replacementsMade, setReplacementsMade] = useState(0); const [phase, setPhase] = useState("running"); const [error, setError] = useState(null); const controllerRef = useRef(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 ( {restored ? ( <> {extraResultActions ? extraResultActions(restored) : null} { 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, }); }} /> { await Clipboard.copy(restored); await showHUD("Als Markdown kopiert"); await closeMainWindow({ popToRootType: PopToRootType.Immediate, }); }} /> { await Clipboard.paste({ html: markdownToHtml(restored), text: restored, }); await closeMainWindow({ popToRootType: PopToRootType.Immediate, }); }} /> ) : null} {aiBuffer ? ( ) : null} } /> ); } 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; }