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-output-drawer.test.tsx345 lines, 13.7 KiBHistoryRawDownload
1import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library";
2import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3import type { RagOutput } from "@/api/client";
4import { RagOutputDrawer } from "@/components/notes/rag-output-drawer";
5import {
6 buildRagOutputMarkdown,
7 readRagOutputDocument,
8 type RagOutputDocument,
9 type RagOutputMarkdownLabels,
10} from "@/components/notes/rag-output-document";
11import { ragOutputMessage, ragOutputPassagePages } from "@/components/notes/rag-output-messages";
12import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel";
13import { formatDateTime } from "@/lib/format";
14import type { NoteFileSource } from "@/lib/note-source";
15import { PreferencesProvider } from "@/stores/preferences-context";
16
17const aiApi = vi.hoisted(() => ({ getAiCapabilities: vi.fn() }));
18const toastApi = vi.hoisted(() => ({ showToast: vi.fn() }));
19
20vi.mock("@/api/ai", () => aiApi);
21vi.mock("@/components/ui/toast", () => ({ showToast: toastApi.showToast, Toaster: () => null }));
22
23const CAPABILITIES_WITH_RAG = {
24 enabled: true,
25 protocol: "hab/2",
26 capabilities: [{ capability: "rag.index", workers: 1, inflight: 0 }],
27};
28
29const NOTE_TITLE = "Hücre ve Canlılar";
30const SUMMARY = "Hücre konusu 18 parçaya bölünerek indekslendi.";
31const GENERATED_AT = Date.UTC(2026, 8, 18, 11, 30);
32
33const HEALTHY: RagOutput = {
34 id: "output-1",
35 course_note: "note-1",
36 course: "course-1",
37 sources: ["file-aaa1", "file-bbb2"],
38 generated_at: GENERATED_AT,
39 payload: {
40 course_note: "note-1",
41 chunks: 18,
42 summary: SUMMARY,
43 keywords: ["hücre zarı", "organel"],
44 files: [
45 { id: "file-aaa1", doc_id: "doc-ccc3", name: "hücre-notu.pdf" },
46 { id: "file-bbb2", doc_id: "doc-ddd4", name: "organeller.pdf" },
47 ],
48 failed: [],
49 },
50};
51
52const PASSAGE_TEXT_1 = "Hücre zarı seçici geçirgendir; madde alışverişini düzenler.\nZar proteinleri taşımayı üstlenir.";
53const PASSAGE_TEXT_2 = "Mitokondri, oksijenli solunumla ATP üretir.";
54
55/** HEALTHY's payload with extra keys — the shape the service evolved into. */
56function withPassages(extra: Record<string, unknown>): RagOutput {
57 return { ...HEALTHY, payload: { ...(HEALTHY.payload as Record<string, unknown>), ...extra } };
58}
59
60const WITH_PASSAGES = withPassages({
61 passages: [
62 { chunk_id: "chunk-1", doc_id: "doc-ccc3", text: PASSAGE_TEXT_1, page_start: 3, page_end: 4 },
63 { chunk_id: "chunk-2", doc_id: "doc-ddd4", text: PASSAGE_TEXT_2, page_start: 5, page_end: 5 },
64 ],
65 passages_truncated: false,
66});
67
68const WITH_TRUNCATED = withPassages({
69 passages: [
70 { chunk_id: "chunk-1", doc_id: "doc-ccc3", text: PASSAGE_TEXT_1, page_start: 3, page_end: 4 },
71 { chunk_id: "chunk-2", doc_id: "doc-ddd4", text: PASSAGE_TEXT_2, page_start: 5, page_end: 5 },
72 ],
73 passages_truncated: true,
74});
75
76/** The service stamps the note's own body chunks with the note key. */
77const WITH_NOTE_PASSAGE = withPassages({
78 passages: [
79 { chunk_id: "01NOTE:01NOTE:c0", doc_id: "note-1", text: PASSAGE_TEXT_2, page_start: null, page_end: null },
80 ],
81});
82
83function markdownLabels(document: RagOutputDocument): RagOutputMarkdownLabels {
84 return {
85 date: ragOutputMessage("en", "date"),
86 note: ragOutputMessage("en", "note"),
87 sources: ragOutputMessage("en", "sources"),
88 failed: ragOutputMessage("en", "failedTitle"),
89 otherFields: ragOutputMessage("en", "otherFields"),
90 passages: ragOutputMessage("en", "passages"),
91 passageHeader: (passage) => {
92 const source = passage.sourceName
93 ?? (passage.fromNote ? NOTE_TITLE : ragOutputMessage("en", "unnamedSource"));
94 const pages = ragOutputPassagePages("en", passage.pageStart, passage.pageEnd);
95 return pages ? `${source} · ${pages}` : source;
96 },
97 passagesTruncated: document.passagesTruncated
98 ? document.chunksTotal != null
99 ? ragOutputMessage("en", "passagesTruncated", { shown: document.passages.length, total: document.chunksTotal })
100 : ragOutputMessage("en", "passagesTruncatedNoTotal", { shown: document.passages.length })
101 : "",
102 };
103}
104
105function expectedMarkdown(output: RagOutput) {
106 const document = readRagOutputDocument(output);
107 return buildRagOutputMarkdown({
108 title: NOTE_TITLE,
109 date: formatDateTime(output.generated_at, "en"),
110 noteTitle: NOTE_TITLE,
111 document,
112 labels: markdownLabels(document),
113 });
114}
115
116/** The drawer's extracted-text section, so raw-record assertions stay scoped. */
117function passagesSection(): HTMLElement {
118 return screen.getByText("Extracted text").closest("div") as HTMLElement;
119}
120
121function stubSource(output: RagOutput): NoteFileSource {
122 return {
123 maxFiles: 10,
124 listFiles: async () => ({ items: [], total: 0, limit: 10, offset: 0 }),
125 uploadFile: async () => {
126 throw new Error("not used by this panel");
127 },
128 deleteFile: async () => {},
129 fileUrl: () => "",
130 fileBlob: async () => new Blob(),
131 listRagOutputs: async () => ({ items: [output], total: 1, limit: 10, offset: 0 }),
132 deleteRagOutput: async () => {},
133 reindexRag: async () => {},
134 };
135}
136
137function renderPanel(output: RagOutput) {
138 render(() => (
139 <PreferencesProvider>
140 <RagOutputsPanel noteId="note-1" active source={stubSource(output)} noteTitle={NOTE_TITLE} />
141 </PreferencesProvider>
142 ));
143}
144
145function renderDrawer(output: RagOutput) {
146 render(() => (
147 <PreferencesProvider>
148 <RagOutputDrawer output={output} noteTitle={NOTE_TITLE} onOpenChange={() => {}} />
149 </PreferencesProvider>
150 ));
151}
152
153const writeText = vi.fn<(text: string) => Promise<void>>();
154const createObjectURL = vi.fn<(blob: Blob) => string>(() => "blob:test");
155const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
156
157describe("RagOutputDrawer", () => {
158 beforeEach(() => {
159 aiApi.getAiCapabilities.mockResolvedValue(CAPABILITIES_WITH_RAG);
160 writeText.mockResolvedValue();
161 writeText.mockClear();
162 createObjectURL.mockClear();
163 clickSpy.mockClear();
164 Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true });
165 Object.defineProperty(URL, "createObjectURL", { value: createObjectURL, configurable: true });
166 Object.defineProperty(URL, "revokeObjectURL", { value: () => {}, configurable: true });
167 });
168
169 afterEach(() => {
170 cleanup();
171 localStorage.removeItem("hezarfen.locale");
172 vi.clearAllMocks();
173 });
174
175 it("renders the stored output inline and exposes grouped actions", async () => {
176 renderPanel(HEALTHY);
177 await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy());
178
179 expect(screen.getByText("Preview")).toBeTruthy();
180 expect(screen.getByText("hücre zarı")).toBeTruthy();
181 expect(screen.getByText("organel")).toBeTruthy();
182 expect(screen.queryByRole("button", { name: "Actions" })).toBeNull();
183 expect(screen.getByRole("button", { name: "Delete" })).toBeTruthy();
184 expect(screen.getByRole("button", { name: "Export" })).toBeTruthy();
185 expect(screen.queryByRole("button", { name: "View" })).toBeNull();
186 });
187
188 it("builds a Markdown document with title, date, source names and body — and no raw ids", () => {
189 const markdown = expectedMarkdown(HEALTHY);
190
191 expect(markdown).toContain(`# ${NOTE_TITLE}`);
192 expect(markdown).toContain(formatDateTime(GENERATED_AT, "en"));
193 expect(markdown).toContain("2026");
194 expect(markdown).toContain("hücre-notu.pdf");
195 expect(markdown).toContain("organeller.pdf");
196 expect(markdown).toContain(SUMMARY);
197 expect(markdown).toContain("- hücre zarı");
198 expect(markdown).toContain("18");
199 expect(markdown).not.toContain("file-aaa1");
200 expect(markdown).not.toContain("doc-ccc3");
201 expect(markdown).not.toContain("course_note");
202 });
203
204 it("copies exactly the built Markdown and confirms it visibly", async () => {
205 renderDrawer(HEALTHY);
206
207 fireEvent.click(screen.getByRole("button", { name: "Copy" }));
208
209 await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));
210 expect(writeText).toHaveBeenCalledWith(expectedMarkdown(HEALTHY));
211 await waitFor(() => expect(screen.getByText("Copied to the clipboard")).toBeTruthy());
212 });
213
214 it("downloads the Markdown under a dated .md file name", async () => {
215 renderDrawer(HEALTHY);
216
217 fireEvent.click(screen.getByRole("button", { name: "Download (.md)" }));
218
219 expect(createObjectURL).toHaveBeenCalledTimes(1);
220 const blob = createObjectURL.mock.calls[0][0];
221 await expect(blob.text()).resolves.toBe(expectedMarkdown(HEALTHY));
222 expect(clickSpy).toHaveBeenCalledTimes(1);
223 });
224
225 it("renders an honest sentence for a degraded output instead of a blank drawer", async () => {
226 const degraded: RagOutput = {
227 ...HEALTHY,
228 sources: ["file-zzz9"],
229 payload: { course_note: "note-1", files: [], failed: ["bozuk.pdf"], summary: "" },
230 };
231 renderDrawer(degraded);
232
233 await waitFor(() => expect(screen.getByText("Some attachments could not be processed")).toBeTruthy());
234 expect(screen.getByText("Not processed: bozuk.pdf")).toBeTruthy();
235 expect(screen.getByText("This output has no readable text. The raw record is below.")).toBeTruthy();
236 // The stored attachment id has no name to show, so it never leaks raw.
237 expect(screen.getByText("Unnamed attachment")).toBeTruthy();
238 expect(screen.queryByText(/file-zzz9/)).toBeNull();
239 });
240
241 it("shows the extracted passages with their source files, page ranges and line breaks", async () => {
242 renderDrawer(WITH_PASSAGES);
243
244 await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy());
245 expect(screen.getByText("hücre-notu.pdf · pp. 3-4")).toBeTruthy();
246 expect(screen.getByText("organeller.pdf · p. 5")).toBeTruthy();
247 // The section renders the passages — it does not dump their ids.
248 const section = passagesSection();
249 const first = within(section).getByText(/Hücre zarı seçici geçirgendir/);
250 expect(first.textContent).toBe(PASSAGE_TEXT_1);
251 expect(first.className).toContain("whitespace-pre-wrap");
252 expect(within(section).getByText(/Mitokondri, oksijenli solunumla/)).toBeTruthy();
253 expect(within(section).queryByText(/chunk-/)).toBeNull();
254 expect(within(section).queryByText(/doc-/)).toBeNull();
255 });
256
257 it("exports the same passages, in the same order, into the Markdown document", () => {
258 const markdown = expectedMarkdown(WITH_PASSAGES);
259
260 expect(markdown).toContain("## Extracted text");
261 expect(markdown).toContain("**hücre-notu.pdf · pp. 3-4**");
262 expect(markdown).toContain("**organeller.pdf · p. 5**");
263 const first = markdown.indexOf(PASSAGE_TEXT_1);
264 const second = markdown.indexOf(PASSAGE_TEXT_2);
265 expect(first).toBeGreaterThan(-1);
266 expect(second).toBeGreaterThan(first);
267 expect(markdown.indexOf("## Extracted text")).toBeLessThan(markdown.indexOf("## Other fields"));
268 expect(markdown).not.toContain("chunk-1");
269 expect(markdown).not.toContain("doc-ccc3");
270 expect(markdown).not.toContain("passages_truncated");
271 });
272
273 it("copies the passages exactly as exported, truncation note included", async () => {
274 renderDrawer(WITH_TRUNCATED);
275
276 fireEvent.click(screen.getByRole("button", { name: "Copy" }));
277
278 await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));
279 expect(writeText).toHaveBeenCalledWith(expectedMarkdown(WITH_TRUNCATED));
280 });
281
282 it("renders no extracted-text section for outputs stored before passages existed", async () => {
283 renderDrawer(HEALTHY);
284
285 await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy());
286 expect(screen.queryByText("Extracted text")).toBeNull();
287 });
288
289 it("survives an ill-typed passages value without rendering a section", async () => {
290 renderDrawer(withPassages({ passages: "bozuk" }));
291
292 await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy());
293 expect(screen.queryByText("Extracted text")).toBeNull();
294 });
295
296 it("says honestly how many passages were extracted when the list is capped", async () => {
297 renderDrawer(WITH_TRUNCATED);
298
299 await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy());
300 expect(
301 screen.getByText(ragOutputMessage("en", "passagesTruncated", { shown: 2, total: 18 })),
302 ).toBeTruthy();
303 });
304
305 it("renders the Turkish section title and truncation sentence", async () => {
306 localStorage.setItem("hezarfen.locale", "tr");
307 renderDrawer(WITH_TRUNCATED);
308
309 await waitFor(() => expect(screen.getByText("Çıkarılan metin")).toBeTruthy());
310 expect(
311 screen.getByText(ragOutputMessage("tr", "passagesTruncated", { shown: 2, total: 18 })),
312 ).toBeTruthy();
313 });
314
315 it("never shows a raw attachment id for a passage whose source cannot be resolved", async () => {
316 renderDrawer(
317 withPassages({
318 passages: [
319 { chunk_id: "chunk-9", doc_id: "doc-zzz9", text: PASSAGE_TEXT_2, page_start: null, page_end: null },
320 ],
321 }),
322 );
323
324 await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy());
325 expect(screen.getByText("Unnamed attachment")).toBeTruthy();
326 const section = passagesSection();
327 expect(within(section).getByText(/Mitokondri, oksijenli solunumla/)).toBeTruthy();
328 expect(within(section).queryByText(/doc-zzz9/)).toBeNull();
329 expect(within(section).queryByText(/chunk-9/)).toBeNull();
330 });
331
332 it("labels a note-body passage with the note title, never the note key", async () => {
333 renderDrawer(WITH_NOTE_PASSAGE);
334
335 await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy());
336 const section = passagesSection();
337 expect(within(section).getByText(NOTE_TITLE)).toBeTruthy();
338 expect(within(section).queryByText(/note-1/)).toBeNull();
339
340 // The export carries the same label the view shows.
341 fireEvent.click(screen.getByRole("button", { name: "Copy" }));
342 await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1));
343 expect(writeText).toHaveBeenCalledWith(expectedMarkdown(WITH_NOTE_PASSAGE));
344 });
345});