diff --git a/src/components/notes/rag-output-document.ts b/src/components/notes/rag-output-document.ts index 4f812df..1d4a3e7 100644 --- a/src/components/notes/rag-output-document.ts +++ b/src/components/notes/rag-output-document.ts @@ -18,6 +18,8 @@ const RENDERED_KEYS: Record = { files: true, failed: true, course_note: true, + passages: true, + passages_truncated: true, }; function asRecord(value: unknown): Record | null { @@ -78,11 +80,61 @@ export type RagOutputDocument = { /** Stored attachment ids whose name the payload does not carry. */ unnamedSources: number; failed: string[]; + /** The indexed chunks the service handed back, in the order it wrote them. */ + passages: RagOutputPassage[]; + /** The service dropped passages above its response budget. */ + passagesTruncated: boolean; + /** The payload's own `chunks` — the total it indexed — when it recorded one. */ + chunksTotal: number | null; /** Payload entries with no dedicated rendering, in payload order. */ fields: Array<{ key: string; value: unknown }>; raw: unknown; }; +/** One indexed chunk as the service returned it — the extraction, readable. */ +export type RagOutputPassage = { + /** The attachment the passage came from, by name; null when unresolvable. */ + sourceName: string | null; + /** The passage came from the note's own text, not from an attachment. */ + fromNote: boolean; + /** The chunk's own text, verbatim. */ + text: string; + pageStart: number | null; + pageEnd: number | null; +}; + +/** The note key the answer stamps its own body chunks with — the payload's own + * `course_note` first, the stored row's link as the fallback. */ +function payloadNoteKey(record: Record | null, output: RagOutput): string { + if (typeof record?.course_note === "string" && record.course_note) return record.course_note; + return typeof output.course_note === "string" ? output.course_note : ""; +} + +/** The passages the service recorded, dropping entries with no readable text. */ +function payloadPassages( + record: Record | null, + names: Map, + noteId: string, +): RagOutputPassage[] { + if (!Array.isArray(record?.passages)) return []; + const pages = (value: unknown) => (typeof value === "number" && Number.isInteger(value) ? value : null); + const passages: RagOutputPassage[] = []; + for (const entry of record.passages) { + const passage = asRecord(entry); + if (typeof passage?.text !== "string" || !passage.text.trim()) continue; + const docId = typeof passage.doc_id === "string" ? passage.doc_id : ""; + passages.push({ + sourceName: (docId ? names.get(docId) : undefined) ?? null, + // The service stamps the note's own chunks with the note key, not a file id. + fromNote: docId !== "" && docId === noteId, + text: passage.text, + pageStart: pages(passage.page_start), + pageEnd: pages(passage.page_end), + }); + } + return passages; +} + /** * Read one stored AI output into everything the drawer shows. The payload is * the service's own object served unread, so every read here is defensive: a @@ -120,6 +172,9 @@ export function readRagOutputDocument(output: RagOutput): RagOutputDocument { sourceNames, unnamedSources, failed, + passages: payloadPassages(record, names, payloadNoteKey(record, output)), + passagesTruncated: record?.passages_truncated === true, + chunksTotal: typeof record?.chunks === "number" && Number.isFinite(record.chunks) ? record.chunks : null, fields: record ? Object.entries(record) .filter(([key]) => !RENDERED_KEYS[key]) @@ -135,6 +190,12 @@ export type RagOutputMarkdownLabels = { sources: string; failed: string; otherFields: string; + /** Heading of the extracted-text section. */ + passages: string; + /** One passage's heading: source name and page range, never a raw id. */ + passageHeader: (passage: RagOutputPassage) => string; + /** Honest note when the service dropped passages; "" when it did not. */ + passagesTruncated: string; }; /** @@ -170,6 +231,13 @@ export function buildRagOutputMarkdown(input: { for (const name of doc.failed) lines.push(`- ${name}`); lines.push(""); } + if (doc.passages.length > 0) { + lines.push(`## ${labels.passages}`, ""); + for (const passage of doc.passages) { + lines.push(`**${labels.passageHeader(passage)}**`, "", passage.text, ""); + } + if (doc.passagesTruncated && labels.passagesTruncated) lines.push(labels.passagesTruncated, ""); + } if (doc.fields.length > 0) { lines.push(`## ${labels.otherFields}`, ""); for (const field of doc.fields) lines.push(`- **${field.key}:** ${fieldValueText(field.value)}`); diff --git a/src/components/notes/rag-output-drawer.test.tsx b/src/components/notes/rag-output-drawer.test.tsx index df60b02..28bfcab 100644 --- a/src/components/notes/rag-output-drawer.test.tsx +++ b/src/components/notes/rag-output-drawer.test.tsx @@ -1,9 +1,14 @@ -import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; +import { cleanup, fireEvent, render, screen, waitFor, within } from "@solidjs/testing-library"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import type { RagOutput } from "@/api/client"; import { RagOutputDrawer } from "@/components/notes/rag-output-drawer"; -import { buildRagOutputMarkdown, readRagOutputDocument } from "@/components/notes/rag-output-document"; -import { ragOutputMessage } from "@/components/notes/rag-output-messages"; +import { + buildRagOutputMarkdown, + readRagOutputDocument, + type RagOutputDocument, + type RagOutputMarkdownLabels, +} from "@/components/notes/rag-output-document"; +import { ragOutputMessage, ragOutputPassagePages } from "@/components/notes/rag-output-messages"; import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel"; import { formatDateTime } from "@/lib/format"; import type { NoteFileSource } from "@/lib/note-source"; @@ -44,24 +49,75 @@ const HEALTHY: RagOutput = { }, }; -const LABELS = { - date: ragOutputMessage("en", "date"), - note: ragOutputMessage("en", "note"), - sources: ragOutputMessage("en", "sources"), - failed: ragOutputMessage("en", "failedTitle"), - otherFields: ragOutputMessage("en", "otherFields"), -}; +const PASSAGE_TEXT_1 = "Hücre zarı seçici geçirgendir; madde alışverişini düzenler.\nZar proteinleri taşımayı üstlenir."; +const PASSAGE_TEXT_2 = "Mitokondri, oksijenli solunumla ATP üretir."; + +/** HEALTHY's payload with extra keys — the shape the service evolved into. */ +function withPassages(extra: Record): RagOutput { + return { ...HEALTHY, payload: { ...(HEALTHY.payload as Record), ...extra } }; +} + +const WITH_PASSAGES = withPassages({ + passages: [ + { chunk_id: "chunk-1", doc_id: "doc-ccc3", text: PASSAGE_TEXT_1, page_start: 3, page_end: 4 }, + { chunk_id: "chunk-2", doc_id: "doc-ddd4", text: PASSAGE_TEXT_2, page_start: 5, page_end: 5 }, + ], + passages_truncated: false, +}); + +const WITH_TRUNCATED = withPassages({ + passages: [ + { chunk_id: "chunk-1", doc_id: "doc-ccc3", text: PASSAGE_TEXT_1, page_start: 3, page_end: 4 }, + { chunk_id: "chunk-2", doc_id: "doc-ddd4", text: PASSAGE_TEXT_2, page_start: 5, page_end: 5 }, + ], + passages_truncated: true, +}); + +/** The service stamps the note's own body chunks with the note key. */ +const WITH_NOTE_PASSAGE = withPassages({ + passages: [ + { chunk_id: "01NOTE:01NOTE:c0", doc_id: "note-1", text: PASSAGE_TEXT_2, page_start: null, page_end: null }, + ], +}); + +function markdownLabels(document: RagOutputDocument): RagOutputMarkdownLabels { + return { + date: ragOutputMessage("en", "date"), + note: ragOutputMessage("en", "note"), + sources: ragOutputMessage("en", "sources"), + failed: ragOutputMessage("en", "failedTitle"), + otherFields: ragOutputMessage("en", "otherFields"), + passages: ragOutputMessage("en", "passages"), + passageHeader: (passage) => { + const source = passage.sourceName + ?? (passage.fromNote ? NOTE_TITLE : ragOutputMessage("en", "unnamedSource")); + const pages = ragOutputPassagePages("en", passage.pageStart, passage.pageEnd); + return pages ? `${source} · ${pages}` : source; + }, + passagesTruncated: document.passagesTruncated + ? document.chunksTotal != null + ? ragOutputMessage("en", "passagesTruncated", { shown: document.passages.length, total: document.chunksTotal }) + : ragOutputMessage("en", "passagesTruncatedNoTotal", { shown: document.passages.length }) + : "", + }; +} function expectedMarkdown(output: RagOutput) { + const document = readRagOutputDocument(output); return buildRagOutputMarkdown({ title: NOTE_TITLE, date: formatDateTime(output.generated_at, "en"), noteTitle: NOTE_TITLE, - document: readRagOutputDocument(output), - labels: LABELS, + document, + labels: markdownLabels(document), }); } +/** The drawer's extracted-text section, so raw-record assertions stay scoped. */ +function passagesSection(): HTMLElement { + return screen.getByText("Extracted text").closest("div") as HTMLElement; +} + function stubSource(output: RagOutput): NoteFileSource { return { maxFiles: 10, @@ -112,6 +168,7 @@ describe("RagOutputDrawer", () => { afterEach(() => { cleanup(); + localStorage.removeItem("hezarfen.locale"); vi.clearAllMocks(); }); @@ -189,4 +246,109 @@ describe("RagOutputDrawer", () => { expect(screen.getByText("Unnamed attachment")).toBeTruthy(); expect(screen.queryByText(/file-zzz9/)).toBeNull(); }); + + it("shows the extracted passages with their source files, page ranges and line breaks", async () => { + renderDrawer(WITH_PASSAGES); + + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); + expect(screen.getByText("hücre-notu.pdf · pp. 3-4")).toBeTruthy(); + expect(screen.getByText("organeller.pdf · p. 5")).toBeTruthy(); + // The section renders the passages — it does not dump their ids. + const section = passagesSection(); + const first = within(section).getByText(/Hücre zarı seçici geçirgendir/); + expect(first.textContent).toBe(PASSAGE_TEXT_1); + expect(first.className).toContain("whitespace-pre-wrap"); + expect(within(section).getByText(/Mitokondri, oksijenli solunumla/)).toBeTruthy(); + expect(within(section).queryByText(/chunk-/)).toBeNull(); + expect(within(section).queryByText(/doc-/)).toBeNull(); + }); + + it("exports the same passages, in the same order, into the Markdown document", () => { + const markdown = expectedMarkdown(WITH_PASSAGES); + + expect(markdown).toContain("## Extracted text"); + expect(markdown).toContain("**hücre-notu.pdf · pp. 3-4**"); + expect(markdown).toContain("**organeller.pdf · p. 5**"); + const first = markdown.indexOf(PASSAGE_TEXT_1); + const second = markdown.indexOf(PASSAGE_TEXT_2); + expect(first).toBeGreaterThan(-1); + expect(second).toBeGreaterThan(first); + expect(markdown.indexOf("## Extracted text")).toBeLessThan(markdown.indexOf("## Other fields")); + expect(markdown).not.toContain("chunk-1"); + expect(markdown).not.toContain("doc-ccc3"); + expect(markdown).not.toContain("passages_truncated"); + }); + + it("copies the passages exactly as exported, truncation note included", async () => { + renderDrawer(WITH_TRUNCATED); + + fireEvent.click(screen.getByRole("button", { name: "Copy" })); + + await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1)); + expect(writeText).toHaveBeenCalledWith(expectedMarkdown(WITH_TRUNCATED)); + }); + + it("renders no extracted-text section for outputs stored before passages existed", async () => { + renderDrawer(HEALTHY); + + await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy()); + expect(screen.queryByText("Extracted text")).toBeNull(); + }); + + it("survives an ill-typed passages value without rendering a section", async () => { + renderDrawer(withPassages({ passages: "bozuk" })); + + await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy()); + expect(screen.queryByText("Extracted text")).toBeNull(); + }); + + it("says honestly how many passages were extracted when the list is capped", async () => { + renderDrawer(WITH_TRUNCATED); + + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); + expect( + screen.getByText(ragOutputMessage("en", "passagesTruncated", { shown: 2, total: 18 })), + ).toBeTruthy(); + }); + + it("renders the Turkish section title and truncation sentence", async () => { + localStorage.setItem("hezarfen.locale", "tr"); + renderDrawer(WITH_TRUNCATED); + + await waitFor(() => expect(screen.getByText("Çıkarılan metin")).toBeTruthy()); + expect( + screen.getByText(ragOutputMessage("tr", "passagesTruncated", { shown: 2, total: 18 })), + ).toBeTruthy(); + }); + + it("never shows a raw attachment id for a passage whose source cannot be resolved", async () => { + renderDrawer( + withPassages({ + passages: [ + { chunk_id: "chunk-9", doc_id: "doc-zzz9", text: PASSAGE_TEXT_2, page_start: null, page_end: null }, + ], + }), + ); + + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); + expect(screen.getByText("Unnamed attachment")).toBeTruthy(); + const section = passagesSection(); + expect(within(section).getByText(/Mitokondri, oksijenli solunumla/)).toBeTruthy(); + expect(within(section).queryByText(/doc-zzz9/)).toBeNull(); + expect(within(section).queryByText(/chunk-9/)).toBeNull(); + }); + + it("labels a note-body passage with the note title, never the note key", async () => { + renderDrawer(WITH_NOTE_PASSAGE); + + await waitFor(() => expect(screen.getByText("Extracted text")).toBeTruthy()); + const section = passagesSection(); + expect(within(section).getByText(NOTE_TITLE)).toBeTruthy(); + expect(within(section).queryByText(/note-1/)).toBeNull(); + + // The export carries the same label the view shows. + fireEvent.click(screen.getByRole("button", { name: "Copy" })); + await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1)); + expect(writeText).toHaveBeenCalledWith(expectedMarkdown(WITH_NOTE_PASSAGE)); + }); }); diff --git a/src/components/notes/rag-output-drawer.tsx b/src/components/notes/rag-output-drawer.tsx index 6078b94..7805cc7 100644 --- a/src/components/notes/rag-output-drawer.tsx +++ b/src/components/notes/rag-output-drawer.tsx @@ -9,8 +9,14 @@ import { fieldValueText, ragOutputFileName, readRagOutputDocument, + type RagOutputDocument, + type RagOutputPassage, } from "@/components/notes/rag-output-document"; -import { ragOutputMessage, type RagOutputMessageKey } from "@/components/notes/rag-output-messages"; +import { + ragOutputMessage, + ragOutputPassagePages, + type RagOutputMessageKey, +} from "@/components/notes/rag-output-messages"; import { formatDateTime } from "@/lib/format"; import { usePreferences } from "@/stores/preferences-context"; @@ -58,6 +64,20 @@ export function RagOutputDrawer(props: { const doc = () => (props.output ? readRagOutputDocument(props.output) : null); const noteTitle = () => props.noteTitle?.trim() ?? ""; + /** One passage's heading: the source file by name, its page range if any. */ + const passageHeader = (passage: RagOutputPassage) => { + const source = passage.sourceName + ?? (passage.fromNote ? noteTitle() || rt("noteText") : rt("unnamedSource")); + const pages = ragOutputPassagePages(locale(), passage.pageStart, passage.pageEnd); + return pages ? `${source} · ${pages}` : source; + }; + /** The honest note when the service's cap means more passages exist. */ + const passagesNote = (read: RagOutputDocument) => { + if (!read.passagesTruncated) return ""; + return read.chunksTotal != null + ? rt("passagesTruncated", { shown: read.passages.length, total: read.chunksTotal }) + : rt("passagesTruncatedNoTotal", { shown: read.passages.length }); + }; const markdown = () => { const output = props.output; const read = doc(); @@ -73,6 +93,9 @@ export function RagOutputDrawer(props: { sources: rt("sources"), failed: rt("failedTitle"), otherFields: rt("otherFields"), + passages: rt("passages"), + passageHeader, + passagesTruncated: passagesNote(read), }, }); }; @@ -200,6 +223,28 @@ export function RagOutputDrawer(props: { + 0}> +
+

{rt("passages")}

+
    + + {(passage) => ( +
  • +

    {passageHeader(passage)}

    + {/* Scrolls past its cap on screen; print flows it out in full. */} +
    +

    {passage.text}

    +
    +
  • + )} +
    +
+ +

{passagesNote(read())}

+
+
+
+ 0}>

diff --git a/src/components/notes/rag-output-messages.ts b/src/components/notes/rag-output-messages.ts index 4ec3f9a..29618be 100644 --- a/src/components/notes/rag-output-messages.ts +++ b/src/components/notes/rag-output-messages.ts @@ -23,6 +23,12 @@ export type RagOutputMessageKey = | "failedLine" | "otherFields" | "chunks" + | "passages" + | "passagePagesSingle" + | "passagePagesRange" + | "passagesTruncated" + | "passagesTruncatedNoTotal" + | "noteText" | "technical" | "copy" | "copied" @@ -43,6 +49,12 @@ const en: Record = { "failedLine": "Not processed: {names}", "otherFields": "Other fields", "chunks": "Text chunks", + "passages": "Extracted text", + "passagePagesSingle": "p. {page}", + "passagePagesRange": "pp. {start}-{end}", + "passagesTruncated": "{total} passages were extracted in total; the first {shown} are listed here.", + "passagesTruncatedNoTotal": "Only the first {shown} extracted passages are listed here.", + "noteText": "Note text", "technical": "Technical details", "copy": "Copy", "copied": "Copied to the clipboard", @@ -64,6 +76,12 @@ const tr: Record = { "failedLine": "İşlenemeyenler: {names}", "otherFields": "Diğer alanlar", "chunks": "Metin parçaları", + "passages": "Çıkarılan metin", + "passagePagesSingle": "s. {page}", + "passagePagesRange": "s. {start}-{end}", + "passagesTruncated": "Toplam {total} metin parçası çıkarıldı; burada ilk {shown} tanesi gösteriliyor.", + "passagesTruncatedNoTotal": "Çıkarılan parçaların yalnızca ilk {shown} tanesi gösteriliyor.", + "noteText": "Not metni", "technical": "Teknik ayrıntı", "copy": "Kopyala", "copied": "Panoya kopyalandı", @@ -79,3 +97,19 @@ export function ragOutputMessage( ): string { return formatMessage((locale === "tr" ? tr : en)[key], vars); } + +/** + * One passage's page range (`s. 3-4`), or an empty string when the service + * recorded no page — the label is then left off entirely. + */ +export function ragOutputPassagePages( + locale: Locale, + pageStart: number | null, + pageEnd: number | null, +): string { + if (pageStart == null) return ""; + if (pageEnd == null || pageEnd <= pageStart) { + return ragOutputMessage(locale, "passagePagesSingle", { page: pageStart }); + } + return ragOutputMessage(locale, "passagePagesRange", { start: pageStart, end: pageEnd }); +}