forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

rag-outputs-panel.tsx293 lines, 11.6 KiBHistoryRawDownload
1import { Show, Suspense, createSignal, onCleanup } from "solid-js";
2import { createResource } from "@/lib/create-resource";
3import { getAiCapabilities } from "@/api/ai";
4import { formatApiError } from "@/api/client";
5import type { RagOutput } from "@/api/client";
6import type { NoteFileSource } from "@/lib/note-source";
7import { Alert } from "@/components/ui/alert";
8import { Button } from "@/components/ui/button";
9import { ConfirmDialog } from "@/components/ui/confirm-dialog";
10import { PageSpinner } from "@/components/ui/page-spinner";
11import { TableRowActions } from "@/components/ui/table-row-actions";
12import { createFlash } from "@/lib/flash";
13import { formatDateTime } from "@/lib/format";
14import { usePreferences, useT } from "@/stores/preferences-context";
15import { IconCopy, IconDownload, IconFileText, IconSparkles, IconTrash } from "@/components/ui/icons";
16import { RagOutputContent } from "@/components/notes/rag-output-content";
17import {
18 buildRagOutputMarkdown,
19 ragOutputFileName,
20 readRagOutputDocument,
21 type RagOutputPassage,
22} from "@/components/notes/rag-output-document";
23import { ragOutputMessage, ragOutputPassagePages } from "@/components/notes/rag-output-messages";
24
25const RAG_PAGE_SIZE = 1;
26
27/**
28 * The capability a worker must have declared for a reindex call to have any
29 * chance of being answered. `/ai/capabilities` lists what connected services
30 * actually serve, so the button stays disabled until some worker serves this.
31 */
32const RAG_INDEX_CAPABILITY = "rag.index";
33
34export function RagOutputsPanel(props: {
35 noteId: string;
36 active: boolean;
37 source: NoteFileSource;
38 /** The note's title, shown by name in the output drawer. */
39 noteTitle?: string;
40 /** Delete control is teacher-only; readers see the list. Defaults to true. */
41 canManage?: boolean;
42}) {
43 const t = useT();
44 const { locale } = usePreferences();
45 const [error, setError] = createSignal("");
46 const [flash, setFlash] = createFlash();
47 const [deleteTarget, setDeleteTarget] = createSignal<RagOutput | null>(null);
48 const [generating, setGenerating] = createSignal(false);
49 const [copied, setCopied] = createSignal(false);
50 const [copyError, setCopyError] = createSignal("");
51 /** Set when a reindex attempt ended without a new output — the truthful state. */
52 const [missed, setMissed] = createSignal("");
53 let pollTimer: ReturnType<typeof setTimeout> | undefined;
54 let copiedTimer: ReturnType<typeof setTimeout> | undefined;
55
56 onCleanup(() => {
57 if (pollTimer) clearTimeout(pollTimer);
58 if (copiedTimer) clearTimeout(copiedTimer);
59 });
60
61 const [list, { refetch }] = createResource(
62 () => (props.active && props.source.listRagOutputs ? props.noteId : null),
63 async (noteId) => props.source.listRagOutputs!(noteId, { limit: RAG_PAGE_SIZE }),
64 );
65 const [capabilities] = createResource(
66 () => (props.active && props.source.reindexRag ? true : null),
67 () => getAiCapabilities(),
68 );
69
70 const outputs = () => list()?.items ?? [];
71 const output = () => outputs()[0] ?? null;
72 const noteTitle = () => props.noteTitle?.trim() ?? "";
73 const passageHeader = (passage: RagOutputPassage) => {
74 const source = passage.sourceName
75 ?? (passage.fromNote ? noteTitle() || ragOutputMessage(locale(), "noteText") : ragOutputMessage(locale(), "unnamedSource"));
76 const pages = ragOutputPassagePages(locale(), passage.pageStart, passage.pageEnd);
77 return pages ? `${source} · ${pages}` : source;
78 };
79 const passagesNote = (read: ReturnType<typeof readRagOutputDocument>) => {
80 if (!read.passagesTruncated) return "";
81 return read.chunksTotal != null
82 ? ragOutputMessage(locale(), "passagesTruncated", { shown: read.passages.length, total: read.chunksTotal })
83 : ragOutputMessage(locale(), "passagesTruncatedNoTotal", { shown: read.passages.length });
84 };
85 const markdown = () => {
86 const current = output();
87 const read = current ? readRagOutputDocument(current) : null;
88 if (!current || !read) return "";
89 return buildRagOutputMarkdown({
90 title: noteTitle() || ragOutputMessage(locale(), "drawerTitle"),
91 date: formatDateTime(current.generated_at, locale()),
92 noteTitle: noteTitle(),
93 document: read,
94 labels: {
95 date: ragOutputMessage(locale(), "date"),
96 note: ragOutputMessage(locale(), "note"),
97 sources: ragOutputMessage(locale(), "sources"),
98 failed: ragOutputMessage(locale(), "failedTitle"),
99 otherFields: ragOutputMessage(locale(), "otherFields"),
100 passages: ragOutputMessage(locale(), "passages"),
101 passageHeader,
102 passagesTruncated: passagesNote(read),
103 },
104 });
105 };
106 const copy = async () => {
107 setCopyError("");
108 if (!navigator.clipboard?.writeText) {
109 setCopyError(ragOutputMessage(locale(), "copyFailed"));
110 return;
111 }
112 try {
113 await navigator.clipboard.writeText(markdown());
114 setCopied(true);
115 copiedTimer = setTimeout(() => setCopied(false), 2500);
116 } catch {
117 setCopied(false);
118 setCopyError(ragOutputMessage(locale(), "copyFailed"));
119 }
120 };
121 const download = () => {
122 const current = output();
123 if (!current) return;
124 const blob = new Blob([markdown()], { type: "text/markdown;charset=utf-8" });
125 const url = URL.createObjectURL(blob);
126 const link = document.createElement("a");
127 link.href = url;
128 link.download = ragOutputFileName(current.generated_at);
129 document.body.appendChild(link);
130 link.click();
131 link.remove();
132 URL.revokeObjectURL(url);
133 };
134 // The button is live only when a worker actually serves `rag.index`. A
135 // discovery failure is not evidence of absence, so leave it live and let the
136 // call itself report; while the list is still loading we do not know either.
137 const available = () => {
138 if (capabilities.error || capabilities.loading) return true;
139 const caps = capabilities();
140 if (!caps || caps.enabled === false) return false;
141 return caps.capabilities.some((c) => c.capability === RAG_INDEX_CAPABILITY);
142 };
143
144 const generate = async () => {
145 if (!props.source.reindexRag || generating()) return;
146 setError("");
147 setMissed("");
148 setGenerating(true);
149 const previousId = outputs()[0]?.id;
150 try {
151 await props.source.reindexRag(props.noteId);
152 let attempts = 0;
153 const poll = async () => {
154 if (!props.active) {
155 setGenerating(false);
156 return;
157 }
158 attempts += 1;
159 const next = await refetch();
160 const firstId = next?.items?.[0]?.id;
161 if (firstId && firstId !== previousId) {
162 setGenerating(false);
163 setFlash(t("courseNotes.ragReady"));
164 return;
165 }
166 if (attempts >= 24) {
167 // Nothing was produced. Say that plainly: no worker indexed this
168 // note, and the button runs the whole call again.
169 setGenerating(false);
170 setMissed(t("courseNotes.ragNotIndexed"));
171 return;
172 }
173 pollTimer = setTimeout(() => void poll().catch(fail), 2500);
174 };
175 const fail = (err: unknown) => {
176 setGenerating(false);
177 setError(formatApiError(err));
178 };
179 pollTimer = setTimeout(() => void poll().catch(fail), 1500);
180 } catch (err) {
181 setGenerating(false);
182 setError(formatApiError(err));
183 }
184 };
185
186 const remove = async () => {
187 const target = deleteTarget();
188 if (!target || !props.source.deleteRagOutput) return;
189 setError("");
190 try {
191 await props.source.deleteRagOutput(props.noteId, target.id);
192 await refetch();
193 setFlash(t("common.deleted"));
194 } catch (err) {
195 setError(formatApiError(err));
196 } finally {
197 setDeleteTarget(null);
198 }
199 };
200
201 return (
202 <section class="space-y-3 rounded-xl border border-border-line bg-surface-base p-4">
203 <div class="flex flex-wrap items-start justify-between gap-3">
204 <div>
205 <h3 class="text-sm font-semibold">{t("courseNotes.ragTitle")}</h3>
206 <p class="mt-0.5 text-xs text-muted-foreground">{t("courseNotes.ragHint")}</p>
207 </div>
208 <div class="flex flex-wrap items-center justify-end gap-2">
209 <Show when={props.canManage !== false && props.source.reindexRag}>
210 <Button
211 type="button"
212 size="sm"
213 variant="ghost"
214 class="topbar-ai-control h-8 min-w-[78px] rounded-lg px-2"
215 disabled={!available() || generating()}
216 onClick={() => void generate()}
217 >
218 <IconSparkles class="h-3.5 w-3.5" />
219 {generating() ? t("courseNotes.ragGenerating") : t("courseNotes.ragGenerate")}
220 </Button>
221 </Show>
222 <Show when={output() && props.canManage !== false && props.source.deleteRagOutput}>
223 <TableRowActions
224 label={t("common.actions")}
225 triggerLabel={t("common.actions")}
226 actions={[{
227 label: t("common.delete"),
228 icon: <IconTrash class="h-4 w-4" />,
229 destructive: true,
230 onSelect: () => setDeleteTarget(output()),
231 }]}
232 />
233 </Show>
234 <Show when={output()}>
235 <TableRowActions
236 label={t("common.export")}
237 triggerLabel={t("common.export")}
238 actions={[
239 { label: ragOutputMessage(locale(), "copy"), icon: <IconCopy class="h-4 w-4" />, onSelect: () => void copy() },
240 { label: ragOutputMessage(locale(), "download"), icon: <IconDownload class="h-4 w-4" />, onSelect: download },
241 { label: ragOutputMessage(locale(), "print"), icon: <IconFileText class="h-4 w-4" />, onSelect: () => window.print() },
242 ]}
243 />
244 </Show>
245 </div>
246 </div>
247 <Show when={flash()}>
248 <Alert variant="success">{flash()}</Alert>
249 </Show>
250 <Show when={error()}>
251 <Alert variant="destructive">{error()}</Alert>
252 </Show>
253 <Show when={missed()}>
254 <Alert variant="warning">{missed()}</Alert>
255 </Show>
256 <Show when={copied()}>
257 <Alert variant="success">{ragOutputMessage(locale(), "copied")}</Alert>
258 </Show>
259 <Show when={copyError()}>
260 <Alert variant="destructive">{copyError()}</Alert>
261 </Show>
262 <Show when={!available()}>
263 <Alert variant="warning">{t("courseNotes.ragUnavailable")}</Alert>
264 </Show>
265 <Suspense fallback={<PageSpinner />}>
266 <Show when={list.error}>
267 <Alert variant="destructive">{formatApiError(list.error)}</Alert>
268 </Show>
269 <Show when={output()} fallback={<p class="text-sm text-muted-foreground">{missed() ? t("courseNotes.ragEmptyFailed") : t("courseNotes.ragEmpty")}</p>}>
270 {(current) => (
271 <article class="overflow-hidden rounded-lg border border-border/60 bg-background/50">
272 <header class="flex flex-wrap items-center justify-between gap-2 border-b border-border/60 px-3 py-2">
273 <span class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{t("courseNotes.markdownPreview")}</span>
274 <span class="text-xs text-muted-foreground">{formatDateTime(current().generated_at, locale())}</span>
275 </header>
276 <div class="p-4">
277 <RagOutputContent payload={current().payload} />
278 </div>
279 </article>
280 )}
281 </Show>
282 </Suspense>
283 <ConfirmDialog
284 open={deleteTarget() != null}
285 onOpenChange={(open) => !open && setDeleteTarget(null)}
286 title={t("confirm.deleteTitle")}
287 variant="destructive"
288 summary={deleteTarget() ? formatDateTime(deleteTarget()?.generated_at ?? 0, locale()) : ""}
289 onConfirm={() => void remove()}
290 />
291 </section>
292 );
293}