diff --git a/src/components/notes/rag-outputs-panel.test.tsx b/src/components/notes/rag-outputs-panel.test.tsx new file mode 100644 index 0000000..4ef950c --- /dev/null +++ b/src/components/notes/rag-outputs-panel.test.tsx @@ -0,0 +1,106 @@ +import { cleanup, fireEvent, render, screen, waitFor } from "@solidjs/testing-library"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { RagOutputsPanel } from "@/components/notes/rag-outputs-panel"; +import type { NoteFileSource } from "@/lib/note-source"; +import { PreferencesProvider } from "@/stores/preferences-context"; + +const aiApi = vi.hoisted(() => ({ getAiCapabilities: vi.fn() })); +// The panel reports success through a toast; capture the text without a portal. +const toastApi = vi.hoisted(() => ({ showToast: vi.fn() })); + +vi.mock("@/api/ai", () => aiApi); +vi.mock("@/components/ui/toast", () => ({ showToast: toastApi.showToast, Toaster: () => null })); + +const CAPABILITIES_WITH_RAG = { + enabled: true, + protocol: "hab/2", + capabilities: [{ capability: "rag.index", workers: 1, inflight: 0 }], +}; + +/** A source whose list stays empty — the state a refused reindex leaves behind. */ +function stubSource(options: { rag?: boolean } = {}): NoteFileSource { + return { + maxFiles: 10, + listFiles: async () => ({ items: [], total: 0, limit: 10, offset: 0 }), + uploadFile: async () => { + throw new Error("not used by this panel"); + }, + deleteFile: async () => {}, + fileUrl: () => "", + fileBlob: async () => new Blob(), + listRagOutputs: async () => ({ items: [], total: 0, limit: 10, offset: 0 }), + deleteRagOutput: async () => {}, + reindexRag: async () => { + if (!options.rag) throw new Error("reindex should not be called without rag.index"); + }, + }; +} + +function renderPanel(source: NoteFileSource) { + render(() => ( + + + + )); +} + +const generateButton = () => screen.getByRole("button", { name: "Create summary" }) as HTMLButtonElement; + +describe("RagOutputsPanel", () => { + afterEach(() => { + cleanup(); + vi.useRealTimers(); + vi.clearAllMocks(); + }); + + it("reports that nothing was indexed when the poll ends without an output", async () => { + vi.useFakeTimers(); + aiApi.getAiCapabilities.mockResolvedValue(CAPABILITIES_WITH_RAG); + + renderPanel(stubSource({ rag: true })); + fireEvent.click(generateButton()); + + // 24 polls after the initial 1.5s delay is the panel's own ceiling. + for (let i = 0; i < 24; i += 1) await vi.advanceTimersByTimeAsync(2500); + + // The truthful message is on screen, twice: the notice and the empty list. + expect( + screen.getByText("The summary was not created. Nothing is indexed for this note yet — press Create summary to try again."), + ).toBeTruthy(); + expect(screen.getByText("Nothing is indexed for this note yet. Press Create summary to try again.")).toBeTruthy(); + // The false claim must be gone: nothing is running in the background. + expect(toastApi.showToast).not.toHaveBeenCalledWith({ title: "Summary generation continues in the background." }); + // The button can be pressed again. + expect(generateButton().disabled).toBe(false); + }); + + it("disables the button and names the reason when no worker serves rag.index", async () => { + aiApi.getAiCapabilities.mockResolvedValue({ + enabled: true, + protocol: "hab/2", + capabilities: [{ capability: "chat.reply", workers: 1, inflight: 0 }], + }); + + renderPanel(stubSource()); + + await waitFor(() => { + expect( + screen.getByText("The AI summary service is not connected right now. Try again when a worker is available."), + ).toBeTruthy(); + }); + expect(generateButton().disabled).toBe(true); + }); + + it("keeps the button live when rag.index is advertised", async () => { + aiApi.getAiCapabilities.mockResolvedValue(CAPABILITIES_WITH_RAG); + + renderPanel(stubSource({ rag: true })); + + await waitFor(() => { + expect(generateButton().disabled).toBe(false); + }); + expect( + screen.queryByText("The AI summary service is not connected right now. Try again when a worker is available."), + ).toBeNull(); + }); +}); diff --git a/src/components/notes/rag-outputs-panel.tsx b/src/components/notes/rag-outputs-panel.tsx index effb7da..f28671c 100644 --- a/src/components/notes/rag-outputs-panel.tsx +++ b/src/components/notes/rag-outputs-panel.tsx @@ -17,6 +17,13 @@ import { RagOutputContent } from "@/components/notes/rag-output-content"; const RAG_PAGE_SIZE = 10; +/** + * The capability a worker must have declared for a reindex call to have any + * chance of being answered. `/ai/capabilities` lists what connected services + * actually serve, so the button stays disabled until some worker serves this. + */ +const RAG_INDEX_CAPABILITY = "rag.index"; + export function RagOutputsPanel(props: { noteId: string; active: boolean; @@ -30,6 +37,8 @@ export function RagOutputsPanel(props: { const [flash, setFlash] = createFlash(); const [deleteTarget, setDeleteTarget] = createSignal(null); const [generating, setGenerating] = createSignal(false); + /** Set when a reindex attempt ended without a new output — the truthful state. */ + const [missed, setMissed] = createSignal(""); let pollTimer: ReturnType | undefined; onCleanup(() => pollTimer && clearTimeout(pollTimer)); @@ -44,11 +53,20 @@ export function RagOutputsPanel(props: { ); const outputs = () => list()?.items ?? []; - const available = () => capabilities.error || capabilities()?.enabled !== false; + // The button is live only when a worker actually serves `rag.index`. A + // discovery failure is not evidence of absence, so leave it live and let the + // call itself report; while the list is still loading we do not know either. + const available = () => { + if (capabilities.error || capabilities.loading) return true; + const caps = capabilities(); + if (!caps || caps.enabled === false) return false; + return caps.capabilities.some((c) => c.capability === RAG_INDEX_CAPABILITY); + }; const generate = async () => { if (!props.source.reindexRag || generating()) return; setError(""); + setMissed(""); setGenerating(true); const previousId = outputs()[0]?.id; try { @@ -62,9 +80,16 @@ export function RagOutputsPanel(props: { attempts += 1; const next = await refetch(); const firstId = next?.items?.[0]?.id; - if ((firstId && firstId !== previousId) || attempts >= 24) { + if (firstId && firstId !== previousId) { + setGenerating(false); + setFlash(t("courseNotes.ragReady")); + return; + } + if (attempts >= 24) { + // Nothing was produced. Say that plainly: no worker indexed this + // note, and the button runs the whole call again. setGenerating(false); - setFlash(firstId && firstId !== previousId ? t("courseNotes.ragReady") : t("courseNotes.ragQueued")); + setMissed(t("courseNotes.ragNotIndexed")); return; } pollTimer = setTimeout(() => void poll().catch(fail), 2500); @@ -115,6 +140,9 @@ export function RagOutputsPanel(props: { {error()} + + {missed()} + {t("courseNotes.ragUnavailable")} @@ -122,7 +150,7 @@ export function RagOutputsPanel(props: { {formatApiError(list.error)} - 0} fallback={

{t("courseNotes.ragEmpty")}

}> + 0} fallback={

{missed() ? t("courseNotes.ragEmptyFailed") : t("courseNotes.ragEmpty")}

}>
    {(output) => ( diff --git a/src/i18n/messages.ts b/src/i18n/messages.ts index f28b545..21b3651 100644 --- a/src/i18n/messages.ts +++ b/src/i18n/messages.ts @@ -875,7 +875,8 @@ export type MessageKey = | "courseNotes.ragGenerate" | "courseNotes.ragGenerating" | "courseNotes.ragReady" - | "courseNotes.ragQueued" + | "courseNotes.ragNotIndexed" + | "courseNotes.ragEmptyFailed" | "courseNotes.ragUnavailable" | "podcast.title" | "podcast.description" @@ -2984,7 +2985,8 @@ const en: Dict = { "courseNotes.ragGenerate": "Create summary", "courseNotes.ragGenerating": "Creating summary…", "courseNotes.ragReady": "The new summary is ready.", - "courseNotes.ragQueued": "Summary generation continues in the background.", + "courseNotes.ragNotIndexed": "The summary was not created. Nothing is indexed for this note yet — press Create summary to try again.", + "courseNotes.ragEmptyFailed": "Nothing is indexed for this note yet. Press Create summary to try again.", "courseNotes.ragUnavailable": "The AI summary service is not connected right now. Try again when a worker is available.", "podcast.title": "Audio workshop", "podcast.description": "Turn a lesson note into a listenable episode.", @@ -5095,7 +5097,8 @@ const tr: Dict = { "courseNotes.ragGenerate": "Özet oluştur", "courseNotes.ragGenerating": "Özet oluşturuluyor…", "courseNotes.ragReady": "Yeni özet hazır.", - "courseNotes.ragQueued": "Özet oluşturma arka planda devam ediyor.", + "courseNotes.ragNotIndexed": "Özet oluşmadı. Bu not için henüz bir dizin oluşturulmadı — yeniden denemek için Özet oluştur'a basın.", + "courseNotes.ragEmptyFailed": "Bu not için henüz bir dizin oluşturulmadı. Yeniden denemek için Özet oluştur'a basın.", "courseNotes.ragUnavailable": "YZ özet servisi şu anda bağlı değil. Bir worker hazır olduğunda tekrar deneyin.", "podcast.title": "Ses Atölyesi", "podcast.description": "Bir ders notunu dinlenebilir bir bölüme dönüştürün.",