✨ view and export AI outputs from the note studio
Browse files at this commit84c2372fa11f6f52aee71b9deb8e7ae87e6c4f27Parent: 30e1815- feat
- ✨ view and export AI outputs from the note studio
8 changed files +743 -45
- src/components/ai/note-studio-panel.tsx +1 -0
- src/components/notes/note-reader-panel.tsx +1 -1
- src/components/notes/rag-output-content.tsx +3 -33
- src/components/notes/rag-output-document.ts +196 -0
- src/components/notes/rag-output-drawer.test.tsx +192 -0
- src/components/notes/rag-output-drawer.tsx +236 -0
- src/components/notes/rag-output-messages.ts +81 -0
- src/components/notes/rag-outputs-panel.tsx +33 -11
src/components/ai/note-studio-panel.tsxmodified+1 -0
| @@ -96,6 +96,7 @@ export function NoteStudioPanel() { | ||
| 96 | 96 | source={courseNoteFiles} |
| 97 | 97 | canManage={canManageSelected()} |
| 98 | 98 | active |
| 99 | + noteTitle={note().title} | |
| 99 | 100 | /> |
| 100 | 101 | <PodcastPanel noteId={note().id} active /> |
| 101 | 102 | </div> |
src/components/notes/note-reader-panel.tsxmodified+1 -1
| @@ -39,7 +39,7 @@ export function NoteReaderPanel(props: { | ||
| 39 | 39 | </article> |
| 40 | 40 | <NoteFilesPanel noteId={n().id} source={props.source} canManage={props.canManage} active={props.open} /> |
| 41 | 41 | <Show when={props.source.listRagOutputs}> |
| 42 | - <RagOutputsPanel noteId={n().id} source={props.source} canManage={props.canManage} active={props.open} /> | |
| 42 | + <RagOutputsPanel noteId={n().id} source={props.source} canManage={props.canManage} active={props.open} noteTitle={n().title} /> | |
| 43 | 43 | <PodcastPanel noteId={n().id} active={props.open} /> |
| 44 | 44 | </Show> |
| 45 | 45 | </div> |
src/components/notes/rag-output-content.tsxmodified+3 -33
| @@ -1,40 +1,10 @@ | ||
| 1 | 1 | import { For, Show } from "solid-js"; |
| 2 | - | |
| 3 | -const SUMMARY_KEYS = ["summary", "ozet", "özet", "content", "text", "answer"]; | |
| 4 | -const LIST_KEYS = ["keywords", "key_points", "topics", "questions", "highlights"]; | |
| 5 | - | |
| 6 | -function asRecord(value: unknown): Record<string, unknown> | null { | |
| 7 | - return value != null && typeof value === "object" && !Array.isArray(value) | |
| 8 | - ? value as Record<string, unknown> | |
| 9 | - : null; | |
| 10 | -} | |
| 11 | - | |
| 12 | -function firstText(record: Record<string, unknown> | null): string | null { | |
| 13 | - if (!record) return null; | |
| 14 | - for (const key of SUMMARY_KEYS) { | |
| 15 | - const value = record[key]; | |
| 16 | - if (typeof value === "string" && value.trim()) return value.trim(); | |
| 17 | - } | |
| 18 | - return null; | |
| 19 | -} | |
| 20 | - | |
| 21 | -function firstList(record: Record<string, unknown> | null): string[] { | |
| 22 | - if (!record) return []; | |
| 23 | - for (const key of LIST_KEYS) { | |
| 24 | - const value = record[key]; | |
| 25 | - if (Array.isArray(value)) { | |
| 26 | - const rows = value.filter((item): item is string => typeof item === "string" && !!item.trim()); | |
| 27 | - if (rows.length > 0) return rows; | |
| 28 | - } | |
| 29 | - } | |
| 30 | - return []; | |
| 31 | -} | |
| 2 | +import { payloadPoints, payloadText } from "@/components/notes/rag-output-document"; | |
| 32 | 3 | |
| 33 | 4 | /** Render the useful parts of the AI service's open payload without exposing a JSON dump first. */ |
| 34 | 5 | export function RagOutputContent(props: { payload: unknown }) { |
| 35 | - const record = () => asRecord(props.payload); | |
| 36 | - const summary = () => typeof props.payload === "string" ? props.payload : firstText(record()); | |
| 37 | - const points = () => firstList(record()); | |
| 6 | + const summary = () => payloadText(props.payload); | |
| 7 | + const points = () => payloadPoints(props.payload); | |
| 38 | 8 | |
| 39 | 9 | return ( |
| 40 | 10 | <div class="space-y-3 text-sm leading-6"> |
src/components/notes/rag-output-document.tsadded+196 -0
| @@ -0,0 +1,196 @@ | ||
| 1 | +import type { RagOutput } from "@/api/client"; | |
| 2 | + | |
| 3 | +const SUMMARY_KEYS = ["summary", "ozet", "özet", "content", "text", "answer"]; | |
| 4 | +const POINT_KEYS = ["keywords", "key_points", "topics", "questions", "highlights"]; | |
| 5 | +/** Payload entries the drawer renders on their own; the rest land in `fields`. */ | |
| 6 | +const RENDERED_KEYS: Record<string, true> = { | |
| 7 | + summary: true, | |
| 8 | + ozet: true, | |
| 9 | + "özet": true, | |
| 10 | + content: true, | |
| 11 | + text: true, | |
| 12 | + answer: true, | |
| 13 | + keywords: true, | |
| 14 | + key_points: true, | |
| 15 | + topics: true, | |
| 16 | + questions: true, | |
| 17 | + highlights: true, | |
| 18 | + files: true, | |
| 19 | + failed: true, | |
| 20 | + course_note: true, | |
| 21 | +}; | |
| 22 | + | |
| 23 | +function asRecord(value: unknown): Record<string, unknown> | null { | |
| 24 | + return value != null && typeof value === "object" && !Array.isArray(value) | |
| 25 | + ? value as Record<string, unknown> | |
| 26 | + : null; | |
| 27 | +} | |
| 28 | + | |
| 29 | +/** The payload's own prose, whatever key the service used for it. */ | |
| 30 | +export function payloadText(payload: unknown): string { | |
| 31 | + if (typeof payload === "string") return payload.trim(); | |
| 32 | + const record = asRecord(payload); | |
| 33 | + if (!record) return ""; | |
| 34 | + for (const key of SUMMARY_KEYS) { | |
| 35 | + const value = record[key]; | |
| 36 | + if (typeof value === "string" && value.trim()) return value.trim(); | |
| 37 | + } | |
| 38 | + return ""; | |
| 39 | +} | |
| 40 | + | |
| 41 | +/** The payload's list-shaped highlights, whatever key the service used. */ | |
| 42 | +export function payloadPoints(payload: unknown): string[] { | |
| 43 | + const record = asRecord(payload); | |
| 44 | + if (!record) return []; | |
| 45 | + for (const key of POINT_KEYS) { | |
| 46 | + const value = record[key]; | |
| 47 | + if (Array.isArray(value)) { | |
| 48 | + const rows = value.filter((item): item is string => typeof item === "string" && !!item.trim()); | |
| 49 | + if (rows.length > 0) return rows; | |
| 50 | + } | |
| 51 | + } | |
| 52 | + return []; | |
| 53 | +} | |
| 54 | + | |
| 55 | +/** Attachment id → name, for the ids the service recorded in `payload.files`. */ | |
| 56 | +export function payloadFileNames(payload: unknown): Map<string, string> { | |
| 57 | + const names = new Map<string, string>(); | |
| 58 | + const files = asRecord(payload)?.files; | |
| 59 | + if (!Array.isArray(files)) return names; | |
| 60 | + for (const entry of files) { | |
| 61 | + const file = asRecord(entry); | |
| 62 | + const name = typeof file?.name === "string" && file.name.trim() ? file.name.trim() : null; | |
| 63 | + if (!name) continue; | |
| 64 | + for (const idKey of ["id", "doc_id"]) { | |
| 65 | + const id = file?.[idKey]; | |
| 66 | + if (typeof id === "string" && id && !names.has(id)) names.set(id, name); | |
| 67 | + } | |
| 68 | + } | |
| 69 | + return names; | |
| 70 | +} | |
| 71 | + | |
| 72 | +export type RagOutputDocument = { | |
| 73 | + /** The produced prose — the summary the service wrote. */ | |
| 74 | + summary: string; | |
| 75 | + points: string[]; | |
| 76 | + /** Attachment names in the order the output listed them; never raw ids. */ | |
| 77 | + sourceNames: string[]; | |
| 78 | + /** Stored attachment ids whose name the payload does not carry. */ | |
| 79 | + unnamedSources: number; | |
| 80 | + failed: string[]; | |
| 81 | + /** Payload entries with no dedicated rendering, in payload order. */ | |
| 82 | + fields: Array<{ key: string; value: unknown }>; | |
| 83 | + raw: unknown; | |
| 84 | +}; | |
| 85 | + | |
| 86 | +/** | |
| 87 | + * Read one stored AI output into everything the drawer shows. The payload is | |
| 88 | + * the service's own object served unread, so every read here is defensive: a | |
| 89 | + * shape the service did not send degrades to an empty value, never a crash. | |
| 90 | + */ | |
| 91 | +export function readRagOutputDocument(output: RagOutput): RagOutputDocument { | |
| 92 | + const raw = output.payload; | |
| 93 | + const record = asRecord(raw); | |
| 94 | + const names = payloadFileNames(raw); | |
| 95 | + const storedSources = Array.isArray(output.sources) ? output.sources : []; | |
| 96 | + | |
| 97 | + const sourceNames: string[] = []; | |
| 98 | + let unnamedSources = 0; | |
| 99 | + if (storedSources.length > 0) { | |
| 100 | + for (const id of storedSources) { | |
| 101 | + const name = names.get(id); | |
| 102 | + if (name) { | |
| 103 | + if (!sourceNames.includes(name)) sourceNames.push(name); | |
| 104 | + } else { | |
| 105 | + unnamedSources += 1; | |
| 106 | + } | |
| 107 | + } | |
| 108 | + } else { | |
| 109 | + // No stored id list — fall back to the names the payload itself recorded. | |
| 110 | + for (const name of new Set(names.values())) sourceNames.push(name); | |
| 111 | + } | |
| 112 | + | |
| 113 | + const failed = Array.isArray(record?.failed) | |
| 114 | + ? record.failed.filter((item): item is string => typeof item === "string" && !!item.trim()).map((item) => item.trim()) | |
| 115 | + : []; | |
| 116 | + | |
| 117 | + return { | |
| 118 | + summary: payloadText(raw), | |
| 119 | + points: payloadPoints(raw), | |
| 120 | + sourceNames, | |
| 121 | + unnamedSources, | |
| 122 | + failed, | |
| 123 | + fields: record | |
| 124 | + ? Object.entries(record) | |
| 125 | + .filter(([key]) => !RENDERED_KEYS[key]) | |
| 126 | + .map(([key, value]) => ({ key, value })) | |
| 127 | + : [], | |
| 128 | + raw, | |
| 129 | + }; | |
| 130 | +} | |
| 131 | + | |
| 132 | +export type RagOutputMarkdownLabels = { | |
| 133 | + date: string; | |
| 134 | + note: string; | |
| 135 | + sources: string; | |
| 136 | + failed: string; | |
| 137 | + otherFields: string; | |
| 138 | +}; | |
| 139 | + | |
| 140 | +/** | |
| 141 | + * The downloadable document: title, date, note, sources, body — built from the | |
| 142 | + * same view the drawer renders, in plain Markdown a teacher can open anywhere. | |
| 143 | + */ | |
| 144 | +export function buildRagOutputMarkdown(input: { | |
| 145 | + title: string; | |
| 146 | + date: string; | |
| 147 | + noteTitle?: string; | |
| 148 | + document: RagOutputDocument; | |
| 149 | + labels: RagOutputMarkdownLabels; | |
| 150 | +}): string { | |
| 151 | + const { document: doc, labels } = input; | |
| 152 | + const lines: string[] = [`# ${input.title}`, ""]; | |
| 153 | + lines.push(`- **${labels.date}:** ${input.date}`); | |
| 154 | + if (input.noteTitle?.trim()) lines.push(`- **${labels.note}:** ${input.noteTitle.trim()}`); | |
| 155 | + if (doc.sourceNames.length > 0 || doc.unnamedSources > 0) { | |
| 156 | + const named = [...doc.sourceNames]; | |
| 157 | + if (doc.unnamedSources > 0) named.push(`(${doc.unnamedSources})`); | |
| 158 | + lines.push(`- **${labels.sources}:** ${named.join(", ")}`); | |
| 159 | + } | |
| 160 | + lines.push(""); | |
| 161 | + if (doc.summary) { | |
| 162 | + lines.push(doc.summary, ""); | |
| 163 | + } | |
| 164 | + if (doc.points.length > 0) { | |
| 165 | + for (const point of doc.points) lines.push(`- ${point}`); | |
| 166 | + lines.push(""); | |
| 167 | + } | |
| 168 | + if (doc.failed.length > 0) { | |
| 169 | + lines.push(`## ${labels.failed}`, ""); | |
| 170 | + for (const name of doc.failed) lines.push(`- ${name}`); | |
| 171 | + lines.push(""); | |
| 172 | + } | |
| 173 | + if (doc.fields.length > 0) { | |
| 174 | + lines.push(`## ${labels.otherFields}`, ""); | |
| 175 | + for (const field of doc.fields) lines.push(`- **${field.key}:** ${fieldValueText(field.value)}`); | |
| 176 | + lines.push(""); | |
| 177 | + } | |
| 178 | + return lines.join("\n"); | |
| 179 | +} | |
| 180 | + | |
| 181 | +/** | |
| 182 | + * One value → one line of text. Exported so the drawer's field list and the | |
| 183 | + * Markdown export render unknown payload values identically. | |
| 184 | + */ | |
| 185 | +export function fieldValueText(value: unknown): string { | |
| 186 | + if (typeof value === "string") return value; | |
| 187 | + if (typeof value === "number" || typeof value === "boolean") return String(value); | |
| 188 | + return JSON.stringify(value) ?? String(value); | |
| 189 | +} | |
| 190 | + | |
| 191 | +/** Deterministic download name: `yz-cikti-YYYYMMDD-HHmm.md`. */ | |
| 192 | +export function ragOutputFileName(generatedAt: number): string { | |
| 193 | + const d = new Date(generatedAt); | |
| 194 | + const pad = (n: number) => String(n).padStart(2, "0"); | |
| 195 | + return `yz-cikti-${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.md`; | |
| 196 | +} |
src/components/notes/rag-output-drawer.test.tsxadded+192 -0
| @@ -0,0 +1,192 @@ | ||
| 1 | +import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; | |
| 2 | +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; | |
| 3 | +import type { RagOutput } from "@/api/client"; | |
| 4 | +import { RagOutputDrawer } from "@/components/notes/rag-output-drawer"; | |
| 5 | +import { buildRagOutputMarkdown, readRagOutputDocument } from "@/components/notes/rag-output-document"; | |
| 6 | +import { ragOutputMessage } from "@/components/notes/rag-output-messages"; | |
| 7 | +import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel"; | |
| 8 | +import { formatDateTime } from "@/lib/format"; | |
| 9 | +import type { NoteFileSource } from "@/lib/note-source"; | |
| 10 | +import { PreferencesProvider } from "@/stores/preferences-context"; | |
| 11 | + | |
| 12 | +const aiApi = vi.hoisted(() => ({ getAiCapabilities: vi.fn() })); | |
| 13 | +const toastApi = vi.hoisted(() => ({ showToast: vi.fn() })); | |
| 14 | + | |
| 15 | +vi.mock("@/api/ai", () => aiApi); | |
| 16 | +vi.mock("@/components/ui/toast", () => ({ showToast: toastApi.showToast, Toaster: () => null })); | |
| 17 | + | |
| 18 | +const CAPABILITIES_WITH_RAG = { | |
| 19 | + enabled: true, | |
| 20 | + protocol: "hab/2", | |
| 21 | + capabilities: [{ capability: "rag.index", workers: 1, inflight: 0 }], | |
| 22 | +}; | |
| 23 | + | |
| 24 | +const NOTE_TITLE = "Hücre ve Canlılar"; | |
| 25 | +const SUMMARY = "Hücre konusu 18 parçaya bölünerek indekslendi."; | |
| 26 | +const GENERATED_AT = Date.UTC(2026, 8, 18, 11, 30); | |
| 27 | + | |
| 28 | +const HEALTHY: RagOutput = { | |
| 29 | + id: "output-1", | |
| 30 | + course_note: "note-1", | |
| 31 | + course: "course-1", | |
| 32 | + sources: ["file-aaa1", "file-bbb2"], | |
| 33 | + generated_at: GENERATED_AT, | |
| 34 | + payload: { | |
| 35 | + course_note: "note-1", | |
| 36 | + chunks: 18, | |
| 37 | + summary: SUMMARY, | |
| 38 | + keywords: ["hücre zarı", "organel"], | |
| 39 | + files: [ | |
| 40 | + { id: "file-aaa1", doc_id: "doc-ccc3", name: "hücre-notu.pdf" }, | |
| 41 | + { id: "file-bbb2", doc_id: "doc-ddd4", name: "organeller.pdf" }, | |
| 42 | + ], | |
| 43 | + failed: [], | |
| 44 | + }, | |
| 45 | +}; | |
| 46 | + | |
| 47 | +const LABELS = { | |
| 48 | + date: ragOutputMessage("en", "date"), | |
| 49 | + note: ragOutputMessage("en", "note"), | |
| 50 | + sources: ragOutputMessage("en", "sources"), | |
| 51 | + failed: ragOutputMessage("en", "failedTitle"), | |
| 52 | + otherFields: ragOutputMessage("en", "otherFields"), | |
| 53 | +}; | |
| 54 | + | |
| 55 | +function expectedMarkdown(output: RagOutput) { | |
| 56 | + return buildRagOutputMarkdown({ | |
| 57 | + title: NOTE_TITLE, | |
| 58 | + date: formatDateTime(output.generated_at, "en"), | |
| 59 | + noteTitle: NOTE_TITLE, | |
| 60 | + document: readRagOutputDocument(output), | |
| 61 | + labels: LABELS, | |
| 62 | + }); | |
| 63 | +} | |
| 64 | + | |
| 65 | +function stubSource(output: RagOutput): NoteFileSource { | |
| 66 | + return { | |
| 67 | + maxFiles: 10, | |
| 68 | + listFiles: async () => ({ items: [], total: 0, limit: 10, offset: 0 }), | |
| 69 | + uploadFile: async () => { | |
| 70 | + throw new Error("not used by this panel"); | |
| 71 | + }, | |
| 72 | + deleteFile: async () => {}, | |
| 73 | + fileUrl: () => "", | |
| 74 | + fileBlob: async () => new Blob(), | |
| 75 | + listRagOutputs: async () => ({ items: [output], total: 1, limit: 10, offset: 0 }), | |
| 76 | + deleteRagOutput: async () => {}, | |
| 77 | + reindexRag: async () => {}, | |
| 78 | + }; | |
| 79 | +} | |
| 80 | + | |
| 81 | +function renderPanel(output: RagOutput) { | |
| 82 | + render(() => ( | |
| 83 | + <PreferencesProvider> | |
| 84 | + <RagOutputsPanel noteId="note-1" active source={stubSource(output)} noteTitle={NOTE_TITLE} /> | |
| 85 | + </PreferencesProvider> | |
| 86 | + )); | |
| 87 | +} | |
| 88 | + | |
| 89 | +function renderDrawer(output: RagOutput) { | |
| 90 | + render(() => ( | |
| 91 | + <PreferencesProvider> | |
| 92 | + <RagOutputDrawer output={output} noteTitle={NOTE_TITLE} onOpenChange={() => {}} /> | |
| 93 | + </PreferencesProvider> | |
| 94 | + )); | |
| 95 | +} | |
| 96 | + | |
| 97 | +const writeText = vi.fn<(text: string) => Promise<void>>(); | |
| 98 | +const createObjectURL = vi.fn<(blob: Blob) => string>(() => "blob:test"); | |
| 99 | +const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {}); | |
| 100 | + | |
| 101 | +describe("RagOutputDrawer", () => { | |
| 102 | + beforeEach(() => { | |
| 103 | + aiApi.getAiCapabilities.mockResolvedValue(CAPABILITIES_WITH_RAG); | |
| 104 | + writeText.mockResolvedValue(); | |
| 105 | + writeText.mockClear(); | |
| 106 | + createObjectURL.mockClear(); | |
| 107 | + clickSpy.mockClear(); | |
| 108 | + Object.defineProperty(navigator, "clipboard", { value: { writeText }, configurable: true }); | |
| 109 | + Object.defineProperty(URL, "createObjectURL", { value: createObjectURL, configurable: true }); | |
| 110 | + Object.defineProperty(URL, "revokeObjectURL", { value: () => {}, configurable: true }); | |
| 111 | + }); | |
| 112 | + | |
| 113 | + afterEach(() => { | |
| 114 | + cleanup(); | |
| 115 | + vi.clearAllMocks(); | |
| 116 | + }); | |
| 117 | + | |
| 118 | + it("opens the drawer from the card body and shows the stored output", async () => { | |
| 119 | + renderPanel(HEALTHY); | |
| 120 | + await waitFor(() => expect(screen.getByText(SUMMARY)).toBeTruthy()); | |
| 121 | + | |
| 122 | + fireEvent.click(screen.getByRole("button", { name: "View" })); | |
| 123 | + | |
| 124 | + await waitFor(() => expect(screen.getByText("Source attachments")).toBeTruthy()); | |
| 125 | + // Attachments by name, and the prose — now on screen twice: card and drawer. | |
| 126 | + expect(screen.getByText("hücre-notu.pdf")).toBeTruthy(); | |
| 127 | + expect(screen.getByText("organeller.pdf")).toBeTruthy(); | |
| 128 | + expect(screen.getAllByText(SUMMARY).length).toBeGreaterThanOrEqual(2); | |
| 129 | + expect(screen.getAllByText(NOTE_TITLE).length).toBeGreaterThanOrEqual(1); | |
| 130 | + // Every payload field stays reachable: the lesser ones in the open, the raw | |
| 131 | + // object behind the disclosure. | |
| 132 | + expect(screen.getByText("Text chunks")).toBeTruthy(); | |
| 133 | + expect(screen.getByText("18")).toBeTruthy(); | |
| 134 | + expect(screen.getByText("Technical details")).toBeTruthy(); | |
| 135 | + expect(screen.getByRole("button", { name: "Copy" })).toBeTruthy(); | |
| 136 | + expect(screen.getByRole("button", { name: "Download (.md)" })).toBeTruthy(); | |
| 137 | + expect(screen.getByRole("button", { name: "Print / PDF" })).toBeTruthy(); | |
| 138 | + }); | |
| 139 | + | |
| 140 | + it("builds a Markdown document with title, date, source names and body — and no raw ids", () => { | |
| 141 | + const markdown = expectedMarkdown(HEALTHY); | |
| 142 | + | |
| 143 | + expect(markdown).toContain(`# ${NOTE_TITLE}`); | |
| 144 | + expect(markdown).toContain(formatDateTime(GENERATED_AT, "en")); | |
| 145 | + expect(markdown).toContain("2026"); | |
| 146 | + expect(markdown).toContain("hücre-notu.pdf"); | |
| 147 | + expect(markdown).toContain("organeller.pdf"); | |
| 148 | + expect(markdown).toContain(SUMMARY); | |
| 149 | + expect(markdown).toContain("- hücre zarı"); | |
| 150 | + expect(markdown).toContain("18"); | |
| 151 | + expect(markdown).not.toContain("file-aaa1"); | |
| 152 | + expect(markdown).not.toContain("doc-ccc3"); | |
| 153 | + expect(markdown).not.toContain("course_note"); | |
| 154 | + }); | |
| 155 | + | |
| 156 | + it("copies exactly the built Markdown and confirms it visibly", async () => { | |
| 157 | + renderDrawer(HEALTHY); | |
| 158 | + | |
| 159 | + fireEvent.click(screen.getByRole("button", { name: "Copy" })); | |
| 160 | + | |
| 161 | + await waitFor(() => expect(writeText).toHaveBeenCalledTimes(1)); | |
| 162 | + expect(writeText).toHaveBeenCalledWith(expectedMarkdown(HEALTHY)); | |
| 163 | + await waitFor(() => expect(screen.getByText("Copied to the clipboard")).toBeTruthy()); | |
| 164 | + }); | |
| 165 | + | |
| 166 | + it("downloads the Markdown under a dated .md file name", async () => { | |
| 167 | + renderDrawer(HEALTHY); | |
| 168 | + | |
| 169 | + fireEvent.click(screen.getByRole("button", { name: "Download (.md)" })); | |
| 170 | + | |
| 171 | + expect(createObjectURL).toHaveBeenCalledTimes(1); | |
| 172 | + const blob = createObjectURL.mock.calls[0][0]; | |
| 173 | + await expect(blob.text()).resolves.toBe(expectedMarkdown(HEALTHY)); | |
| 174 | + expect(clickSpy).toHaveBeenCalledTimes(1); | |
| 175 | + }); | |
| 176 | + | |
| 177 | + it("renders an honest sentence for a degraded output instead of a blank drawer", async () => { | |
| 178 | + const degraded: RagOutput = { | |
| 179 | + ...HEALTHY, | |
| 180 | + sources: ["file-zzz9"], | |
| 181 | + payload: { course_note: "note-1", files: [], failed: ["bozuk.pdf"], summary: "" }, | |
| 182 | + }; | |
| 183 | + renderDrawer(degraded); | |
| 184 | + | |
| 185 | + await waitFor(() => expect(screen.getByText("Some attachments could not be processed")).toBeTruthy()); | |
| 186 | + expect(screen.getByText("Not processed: bozuk.pdf")).toBeTruthy(); | |
| 187 | + expect(screen.getByText("This output has no readable text. The raw record is below.")).toBeTruthy(); | |
| 188 | + // The stored attachment id has no name to show, so it never leaks raw. | |
| 189 | + expect(screen.getByText("Unnamed attachment")).toBeTruthy(); | |
| 190 | + expect(screen.queryByText(/file-zzz9/)).toBeNull(); | |
| 191 | + }); | |
| 192 | +}); |
src/components/notes/rag-output-drawer.tsxadded+236 -0
| @@ -0,0 +1,236 @@ | ||
| 1 | +import { For, Show, createSignal, onCleanup } from "solid-js"; | |
| 2 | +import type { RagOutput } from "@/api/client"; | |
| 3 | +import { Alert } from "@/components/ui/alert"; | |
| 4 | +import { Button } from "@/components/ui/button"; | |
| 5 | +import { SidePanel } from "@/components/ui/side-panel"; | |
| 6 | +import { IconCopy, IconDownload, IconFileText } from "@/components/ui/icons"; | |
| 7 | +import { | |
| 8 | + buildRagOutputMarkdown, | |
| 9 | + fieldValueText, | |
| 10 | + ragOutputFileName, | |
| 11 | + readRagOutputDocument, | |
| 12 | +} from "@/components/notes/rag-output-document"; | |
| 13 | +import { ragOutputMessage, type RagOutputMessageKey } from "@/components/notes/rag-output-messages"; | |
| 14 | +import { formatDateTime } from "@/lib/format"; | |
| 15 | +import { usePreferences } from "@/stores/preferences-context"; | |
| 16 | + | |
| 17 | +/** | |
| 18 | + * Print isolation: the SidePanel portals into the app's document, so a bare | |
| 19 | + * `window.print()` would capture the whole page. These rules hide every | |
| 20 | + * element except the document body, flatten the panel out of its fixed, | |
| 21 | + * scroll-clipped layout, and pull the document to the page origin. The action | |
| 22 | + * row and the technical disclosure opt out with `print:hidden`. | |
| 23 | + */ | |
| 24 | +const PRINT_STYLES = ` | |
| 25 | +@media print { | |
| 26 | + body * { visibility: hidden; } | |
| 27 | + .rag-output-print, .rag-output-print * { overflow: visible !important; } | |
| 28 | + .rag-output-print { position: static !important; max-width: none !important; height: auto !important; box-shadow: none !important; } | |
| 29 | + .rag-output-print [data-rag-print-doc], .rag-output-print [data-rag-print-doc] * { visibility: visible; } | |
| 30 | + .rag-output-print [data-rag-print-doc] { position: absolute; left: 0; top: 0; width: 100%; color: #000; } | |
| 31 | +} | |
| 32 | +`; | |
| 33 | + | |
| 34 | +/** Payload keys with a Turkish label; anything else is labelled by its key. */ | |
| 35 | +const FIELD_LABELS: Partial<Record<string, RagOutputMessageKey>> = { | |
| 36 | + chunks: "chunks", | |
| 37 | +}; | |
| 38 | + | |
| 39 | +/** | |
| 40 | + * One stored AI output, readable and exportable: the note it belongs to, the | |
| 41 | + * attachments by name, the produced prose, the lesser payload fields, and the | |
| 42 | + * raw record behind a disclosure. Copy / download / print all build their | |
| 43 | + * output from this same document. | |
| 44 | + */ | |
| 45 | +export function RagOutputDrawer(props: { | |
| 46 | + output: RagOutput | null; | |
| 47 | + /** The note the output belongs to — shown by title, never by id. */ | |
| 48 | + noteTitle?: string; | |
| 49 | + onOpenChange: (open: boolean) => void; | |
| 50 | +}) { | |
| 51 | + const { locale } = usePreferences(); | |
| 52 | + const rt = (key: RagOutputMessageKey, vars?: Record<string, string | number>) => | |
| 53 | + ragOutputMessage(locale(), key, vars); | |
| 54 | + const [copied, setCopied] = createSignal(false); | |
| 55 | + const [copyError, setCopyError] = createSignal(""); | |
| 56 | + let copiedTimer: ReturnType<typeof setTimeout> | undefined; | |
| 57 | + onCleanup(() => copiedTimer && clearTimeout(copiedTimer)); | |
| 58 | + | |
| 59 | + const doc = () => (props.output ? readRagOutputDocument(props.output) : null); | |
| 60 | + const noteTitle = () => props.noteTitle?.trim() ?? ""; | |
| 61 | + const markdown = () => { | |
| 62 | + const output = props.output; | |
| 63 | + const read = doc(); | |
| 64 | + if (!output || !read) return ""; | |
| 65 | + return buildRagOutputMarkdown({ | |
| 66 | + title: noteTitle() || rt("drawerTitle"), | |
| 67 | + date: formatDateTime(output.generated_at, locale()), | |
| 68 | + noteTitle: noteTitle(), | |
| 69 | + document: read, | |
| 70 | + labels: { | |
| 71 | + date: rt("date"), | |
| 72 | + note: rt("note"), | |
| 73 | + sources: rt("sources"), | |
| 74 | + failed: rt("failedTitle"), | |
| 75 | + otherFields: rt("otherFields"), | |
| 76 | + }, | |
| 77 | + }); | |
| 78 | + }; | |
| 79 | + | |
| 80 | + const copy = async () => { | |
| 81 | + setCopyError(""); | |
| 82 | + if (!navigator.clipboard?.writeText) { | |
| 83 | + setCopyError(rt("copyFailed")); | |
| 84 | + return; | |
| 85 | + } | |
| 86 | + try { | |
| 87 | + await navigator.clipboard.writeText(markdown()); | |
| 88 | + setCopied(true); | |
| 89 | + copiedTimer = setTimeout(() => setCopied(false), 2500); | |
| 90 | + } catch { | |
| 91 | + setCopied(false); | |
| 92 | + setCopyError(rt("copyFailed")); | |
| 93 | + } | |
| 94 | + }; | |
| 95 | + | |
| 96 | + const download = () => { | |
| 97 | + const output = props.output; | |
| 98 | + if (!output) return; | |
| 99 | + const blob = new Blob([markdown()], { type: "text/markdown;charset=utf-8" }); | |
| 100 | + const url = URL.createObjectURL(blob); | |
| 101 | + const link = document.createElement("a"); | |
| 102 | + link.href = url; | |
| 103 | + link.download = ragOutputFileName(output.generated_at); | |
| 104 | + document.body.appendChild(link); | |
| 105 | + link.click(); | |
| 106 | + link.remove(); | |
| 107 | + URL.revokeObjectURL(url); | |
| 108 | + }; | |
| 109 | + | |
| 110 | + return ( | |
| 111 | + <SidePanel | |
| 112 | + open={props.output != null} | |
| 113 | + onOpenChange={props.onOpenChange} | |
| 114 | + title={rt("drawerTitle")} | |
| 115 | + description={noteTitle()} | |
| 116 | + size="wide" | |
| 117 | + class="rag-output-print" | |
| 118 | + > | |
| 119 | + <style>{PRINT_STYLES}</style> | |
| 120 | + <Show when={props.output}> | |
| 121 | + {(output) => ( | |
| 122 | + <Show when={doc()}> | |
| 123 | + {(read) => ( | |
| 124 | + <article data-rag-print-doc class="space-y-4"> | |
| 125 | + <header class="space-y-0.5 border-b border-border/60 pb-3"> | |
| 126 | + <p class="text-xs uppercase tracking-wide text-muted-foreground">{rt("drawerTitle")}</p> | |
| 127 | + <h2 class="text-base font-semibold">{noteTitle() || rt("drawerTitle")}</h2> | |
| 128 | + <p class="text-xs text-muted-foreground">{formatDateTime(output().generated_at, locale())}</p> | |
| 129 | + </header> | |
| 130 | + | |
| 131 | + <div class="flex flex-wrap items-center gap-2 print:hidden"> | |
| 132 | + <Button type="button" size="sm" variant="outline" onClick={() => void copy()}> | |
| 133 | + <IconCopy class="h-4 w-4" /> | |
| 134 | + {rt("copy")} | |
| 135 | + </Button> | |
| 136 | + <Button type="button" size="sm" variant="outline" onClick={download}> | |
| 137 | + <IconDownload class="h-4 w-4" /> | |
| 138 | + {rt("download")} | |
| 139 | + </Button> | |
| 140 | + <Button type="button" size="sm" variant="outline" onClick={() => window.print()}> | |
| 141 | + <IconFileText class="h-4 w-4" /> | |
| 142 | + {rt("print")} | |
| 143 | + </Button> | |
| 144 | + </div> | |
| 145 | + <Show when={copied()}> | |
| 146 | + <Alert variant="success">{rt("copied")}</Alert> | |
| 147 | + </Show> | |
| 148 | + <Show when={copyError()}> | |
| 149 | + <Alert variant="destructive">{copyError()}</Alert> | |
| 150 | + </Show> | |
| 151 | + | |
| 152 | + <dl class="grid gap-1 text-sm sm:grid-cols-[auto_1fr] sm:gap-x-3"> | |
| 153 | + <dt class="text-muted-foreground">{rt("date")}</dt> | |
| 154 | + <dd class="mono text-xs sm:pt-0.5">{formatDateTime(output().generated_at, locale())}</dd> | |
| 155 | + <Show when={noteTitle()}> | |
| 156 | + <dt class="text-muted-foreground">{rt("note")}</dt> | |
| 157 | + <dd>{noteTitle()}</dd> | |
| 158 | + </Show> | |
| 159 | + </dl> | |
| 160 | + | |
| 161 | + <div class="space-y-1"> | |
| 162 | + <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground">{rt("sources")}</p> | |
| 163 | + <Show | |
| 164 | + when={read().sourceNames.length > 0 || read().unnamedSources > 0} | |
| 165 | + fallback={<p class="text-sm text-muted-foreground">{rt("noSources")}</p>} | |
| 166 | + > | |
| 167 | + <ul class="list-disc space-y-0.5 pl-5 text-sm"> | |
| 168 | + <For each={read().sourceNames}>{(name) => <li>{name}</li>}</For> | |
| 169 | + <Show when={read().unnamedSources > 0}> | |
| 170 | + <li> | |
| 171 | + {rt("unnamedSource")} | |
| 172 | + {read().unnamedSources > 1 ? ` × ${read().unnamedSources}` : ""} | |
| 173 | + </li> | |
| 174 | + </Show> | |
| 175 | + </ul> | |
| 176 | + </Show> | |
| 177 | + </div> | |
| 178 | + | |
| 179 | + <Show when={read().failed.length > 0}> | |
| 180 | + <Alert variant="warning"> | |
| 181 | + {/* One flex item: Alert lays its children out in a row. */} | |
| 182 | + <div class="space-y-0.5"> | |
| 183 | + <p class="font-medium">{rt("failedTitle")}</p> | |
| 184 | + <p>{rt("failedLine", { names: read().failed.join(", ") })}</p> | |
| 185 | + </div> | |
| 186 | + </Alert> | |
| 187 | + </Show> | |
| 188 | + | |
| 189 | + <Show | |
| 190 | + when={read().summary || read().points.length > 0} | |
| 191 | + fallback={<Alert variant="warning">{rt("emptyText")}</Alert>} | |
| 192 | + > | |
| 193 | + <Show when={read().summary}> | |
| 194 | + <p class="whitespace-pre-wrap text-sm leading-6">{read().summary}</p> | |
| 195 | + </Show> | |
| 196 | + <Show when={read().points.length > 0}> | |
| 197 | + <ul class="list-disc space-y-1 pl-5 text-sm text-foreground/85"> | |
| 198 | + <For each={read().points}>{(point) => <li>{point}</li>}</For> | |
| 199 | + </ul> | |
| 200 | + </Show> | |
| 201 | + </Show> | |
| 202 | + | |
| 203 | + <Show when={read().fields.length > 0}> | |
| 204 | + <div class="space-y-1.5"> | |
| 205 | + <p class="text-xs font-semibold uppercase tracking-wide text-muted-foreground"> | |
| 206 | + {rt("otherFields")} | |
| 207 | + </p> | |
| 208 | + <dl class="space-y-1.5 text-sm"> | |
| 209 | + <For each={read().fields}> | |
| 210 | + {(field) => ( | |
| 211 | + <div class="flex flex-wrap gap-x-2"> | |
| 212 | + <dt class="shrink-0 text-muted-foreground"> | |
| 213 | + {FIELD_LABELS[field.key] ? rt(FIELD_LABELS[field.key]!) : field.key} | |
| 214 | + </dt> | |
| 215 | + <dd class="min-w-0 break-words whitespace-pre-wrap">{fieldValueText(field.value)}</dd> | |
| 216 | + </div> | |
| 217 | + )} | |
| 218 | + </For> | |
| 219 | + </dl> | |
| 220 | + </div> | |
| 221 | + </Show> | |
| 222 | + | |
| 223 | + <details class="rounded-lg border border-border/60 p-3 print:hidden"> | |
| 224 | + <summary class="cursor-pointer text-xs font-medium text-muted-foreground">{rt("technical")}</summary> | |
| 225 | + <pre class="mt-2 overflow-x-auto whitespace-pre-wrap text-xs leading-5"> | |
| 226 | + {JSON.stringify(read().raw, null, 2)} | |
| 227 | + </pre> | |
| 228 | + </details> | |
| 229 | + </article> | |
| 230 | + )} | |
| 231 | + </Show> | |
| 232 | + )} | |
| 233 | + </Show> | |
| 234 | + </SidePanel> | |
| 235 | + ); | |
| 236 | +} |
src/components/notes/rag-output-messages.tsadded+81 -0
| @@ -0,0 +1,81 @@ | ||
| 1 | +import { formatMessage, type Locale } from "@/i18n/messages"; | |
| 2 | + | |
| 3 | +/** | |
| 4 | + * Copy for the AI output drawer and its export actions. | |
| 5 | + * | |
| 6 | + * These strings deliberately live in their own module instead of the shared | |
| 7 | + * `src/i18n/messages.ts` table: that file is being edited by sibling lanes on | |
| 8 | + * the same day this drawer was built. The shape mirrors the shared table — a | |
| 9 | + * typed key union, one dict per locale, `{var}` interpolation through | |
| 10 | + * `formatMessage` — so the entries can be folded into the shared table later | |
| 11 | + * without touching a call site. | |
| 12 | + */ | |
| 13 | +export type RagOutputMessageKey = | |
| 14 | + | "view" | |
| 15 | + | "drawerTitle" | |
| 16 | + | "date" | |
| 17 | + | "note" | |
| 18 | + | "sources" | |
| 19 | + | "noSources" | |
| 20 | + | "unnamedSource" | |
| 21 | + | "emptyText" | |
| 22 | + | "failedTitle" | |
| 23 | + | "failedLine" | |
| 24 | + | "otherFields" | |
| 25 | + | "chunks" | |
| 26 | + | "technical" | |
| 27 | + | "copy" | |
| 28 | + | "copied" | |
| 29 | + | "copyFailed" | |
| 30 | + | "download" | |
| 31 | + | "print"; | |
| 32 | + | |
| 33 | +const en: Record<RagOutputMessageKey, string> = { | |
| 34 | + "view": "View", | |
| 35 | + "drawerTitle": "AI output", | |
| 36 | + "date": "Date", | |
| 37 | + "note": "Note", | |
| 38 | + "sources": "Source attachments", | |
| 39 | + "noSources": "No attachments — built from the note text.", | |
| 40 | + "unnamedSource": "Unnamed attachment", | |
| 41 | + "emptyText": "This output has no readable text. The raw record is below.", | |
| 42 | + "failedTitle": "Some attachments could not be processed", | |
| 43 | + "failedLine": "Not processed: {names}", | |
| 44 | + "otherFields": "Other fields", | |
| 45 | + "chunks": "Text chunks", | |
| 46 | + "technical": "Technical details", | |
| 47 | + "copy": "Copy", | |
| 48 | + "copied": "Copied to the clipboard", | |
| 49 | + "copyFailed": "Could not copy to the clipboard.", | |
| 50 | + "download": "Download (.md)", | |
| 51 | + "print": "Print / PDF", | |
| 52 | +}; | |
| 53 | + | |
| 54 | +const tr: Record<RagOutputMessageKey, string> = { | |
| 55 | + "view": "Görüntüle", | |
| 56 | + "drawerTitle": "YZ çıktısı", | |
| 57 | + "date": "Tarih", | |
| 58 | + "note": "Not", | |
| 59 | + "sources": "Kaynak ekler", | |
| 60 | + "noSources": "Ek yok — not metninden oluşturuldu.", | |
| 61 | + "unnamedSource": "Adı bilinmeyen ek", | |
| 62 | + "emptyText": "Bu çıktıda okunabilir bir metin yok. Ham kayıt aşağıdadır.", | |
| 63 | + "failedTitle": "Bazı ekler işlenemedi", | |
| 64 | + "failedLine": "İşlenemeyenler: {names}", | |
| 65 | + "otherFields": "Diğer alanlar", | |
| 66 | + "chunks": "Metin parçaları", | |
| 67 | + "technical": "Teknik ayrıntı", | |
| 68 | + "copy": "Kopyala", | |
| 69 | + "copied": "Panoya kopyalandı", | |
| 70 | + "copyFailed": "Panoya kopyalanamadı.", | |
| 71 | + "download": "İndir (.md)", | |
| 72 | + "print": "Yazdır / PDF", | |
| 73 | +}; | |
| 74 | + | |
| 75 | +export function ragOutputMessage( | |
| 76 | + locale: Locale, | |
| 77 | + key: RagOutputMessageKey, | |
| 78 | + vars?: Record<string, string | number>, | |
| 79 | +): string { | |
| 80 | + return formatMessage((locale === "tr" ? tr : en)[key], vars); | |
| 81 | +} |
src/components/notes/rag-outputs-panel.tsxmodified+33 -11
| @@ -12,8 +12,10 @@ import { TableRowActions } from "@/components/ui/table-row-actions"; | ||
| 12 | 12 | import { createFlash } from "@/lib/flash"; |
| 13 | 13 | import { formatDateTime } from "@/lib/format"; |
| 14 | 14 | import { usePreferences, useT } from "@/stores/preferences-context"; |
| 15 | -import { IconSparkles, IconTrash } from "@/components/ui/icons"; | |
| 15 | +import { IconEye, IconSparkles, IconTrash } from "@/components/ui/icons"; | |
| 16 | 16 | import { RagOutputContent } from "@/components/notes/rag-output-content"; |
| 17 | +import { RagOutputDrawer } from "@/components/notes/rag-output-drawer"; | |
| 18 | +import { ragOutputMessage } from "@/components/notes/rag-output-messages"; | |
| 17 | 19 | |
| 18 | 20 | const RAG_PAGE_SIZE = 10; |
| 19 | 21 | |
| @@ -28,6 +30,8 @@ export function RagOutputsPanel(props: { | ||
| 28 | 30 | noteId: string; |
| 29 | 31 | active: boolean; |
| 30 | 32 | source: NoteFileSource; |
| 33 | + /** The note's title, shown by name in the output drawer. */ | |
| 34 | + noteTitle?: string; | |
| 31 | 35 | /** Delete control is teacher-only; readers see the list. Defaults to true. */ |
| 32 | 36 | canManage?: boolean; |
| 33 | 37 | }) { |
| @@ -36,6 +40,7 @@ export function RagOutputsPanel(props: { | ||
| 36 | 40 | const [error, setError] = createSignal(""); |
| 37 | 41 | const [flash, setFlash] = createFlash(); |
| 38 | 42 | const [deleteTarget, setDeleteTarget] = createSignal<RagOutput | null>(null); |
| 43 | + const [viewTarget, setViewTarget] = createSignal<RagOutput | null>(null); | |
| 39 | 44 | const [generating, setGenerating] = createSignal(false); |
| 40 | 45 | /** Set when a reindex attempt ended without a new output — the truthful state. */ |
| 41 | 46 | const [missed, setMissed] = createSignal(""); |
| @@ -160,28 +165,45 @@ export function RagOutputsPanel(props: { | ||
| 160 | 165 | {formatDateTime(output.generated_at, locale())} |
| 161 | 166 | </span> |
| 162 | 167 | <span class="ml-auto"> |
| 163 | - <Show when={props.canManage !== false && props.source.deleteRagOutput}> | |
| 164 | - <TableRowActions | |
| 165 | - label={t("common.actions")} | |
| 166 | - actions={[ | |
| 167 | - { | |
| 168 | + <TableRowActions | |
| 169 | + label={t("common.actions")} | |
| 170 | + actions={[ | |
| 171 | + { | |
| 172 | + label: ragOutputMessage(locale(), "view"), | |
| 173 | + icon: <IconEye class="h-4 w-4" />, | |
| 174 | + onSelect: () => setViewTarget(output), | |
| 175 | + }, | |
| 176 | + ...(props.canManage !== false && props.source.deleteRagOutput | |
| 177 | + ? [{ | |
| 168 | 178 | label: t("common.delete"), |
| 169 | 179 | icon: <IconTrash class="h-4 w-4" />, |
| 170 | 180 | destructive: true, |
| 171 | 181 | onSelect: () => setDeleteTarget(output), |
| 172 | - }, | |
| 173 | - ]} | |
| 174 | - /> | |
| 175 | - </Show> | |
| 182 | + }] | |
| 183 | + : []), | |
| 184 | + ]} | |
| 185 | + /> | |
| 176 | 186 | </span> |
| 177 | 187 | </div> |
| 178 | - <RagOutputContent payload={output.payload} /> | |
| 188 | + <button | |
| 189 | + type="button" | |
| 190 | + class="block w-full cursor-pointer rounded-md p-1.5 text-left transition-colors hover:bg-accent/40 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-ring" | |
| 191 | + aria-label={ragOutputMessage(locale(), "view")} | |
| 192 | + onClick={() => setViewTarget(output)} | |
| 193 | + > | |
| 194 | + <RagOutputContent payload={output.payload} /> | |
| 195 | + </button> | |
| 179 | 196 | </li> |
| 180 | 197 | )} |
| 181 | 198 | </For> |
| 182 | 199 | </ul> |
| 183 | 200 | </Show> |
| 184 | 201 | </Suspense> |
| 202 | + <RagOutputDrawer | |
| 203 | + output={viewTarget()} | |
| 204 | + noteTitle={props.noteTitle} | |
| 205 | + onOpenChange={(open) => !open && setViewTarget(null)} | |
| 206 | + /> | |
| 185 | 207 | <ConfirmDialog |
| 186 | 208 | open={deleteTarget() != null} |
| 187 | 209 | onOpenChange={(open) => !open && setDeleteTarget(null)} |