diff --git a/CONTEXT.md b/CONTEXT.md index 55f83ebf..5132364a 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -95,9 +95,21 @@ messages, duplicate-submit prevention, and post-upload cleanup. ## Demo Source -A Demo Source is app-owned static content served to guest users and optionally -materialized into an authenticated workspace. Demo sources should not depend on -live workspace state for guest rendering. +A Demo Source is a shared public document available to guests and authenticated +users. A user's selection controls whether that source participates in their +questions; selecting or hiding it does not create or archive a private copy. + +## Demo Source Revision + +A Demo Source Revision is a complete published version of a shared document. +Normal browsing uses the current revision; a saved Citation identifies the +revision containing its original evidence. + +## Legacy Demo Copy + +A Legacy Demo Copy is a private document created by the former demo-copying +workflow. It remains available for historical Citations but does not appear as +a new shared Demo Source or automatically participate in new questions. ## Source Original Preview @@ -168,7 +180,8 @@ scrolling to the latest row. A Citation is the metadata that connects an assistant answer to a retrieval result. Fresh answers can include chunk content for focusing the UI; persisted -history stores only citation metadata. +history stores only citation metadata, including the source namespace and +published revision when available. ## Citation Focus diff --git a/docs/shared-demo-client-migration.md b/docs/shared-demo-client-migration.md new file mode 100644 index 00000000..2e8d2643 --- /dev/null +++ b/docs/shared-demo-client-migration.md @@ -0,0 +1,65 @@ +# Shared demo client behavior + +Notebook uses the published shared demo corpus directly. The Knowhere +`/api/v1/demo/materializations` endpoint returns 410 and must never be called. + +## Selection and retrieval + +The current catalog defines source IDs, canonical document IDs, and complete +revision IDs. Missing revision provenance is a boundary error. Catalog reads +are not cached across requests. + +`POST /api/demo-sources/select` accepts `{ "demoSourceIds": ["..."] }` and +returns `{ "sources": [...] }`. It restores local visibility idempotently and +does not create private documents. Unselected Official Library entries remain +outside the chat scope. Hiding a demo changes local visibility only. + +The Notebook `/api/demo-sources/materialize` route is a temporary compatibility +adapter: it returns shared metadata for still-visible selections without +restoring hidden sources, copying documents, or rewriting saved citations. + +Shared retrieval uses `__knowhere_demo__` with an explicit selected document +allowlist. Private retrieval retains its existing scope rules and excludes +legacy demo copies. Folder queries exclude shared demos. Empty selections do +not become unrestricted retrieval requests. + +When one requested scope fails and another yields evidence, the response +contains `retrievalWarnings` and the answer displays a coverage notice. The +notice is retained in the existing agent-trace JSON. If no scope supplies +usable evidence, the request fails rather than presenting a partial answer +as complete. + +## Reading citations + +Source and citation metadata carry `namespace` and `jobResultId`. Retrieval +responses determine citation revision identity; later catalog reads cannot +replace it. Cached chunks, pagination, media copies, and connected-asset +lookups keep revisions separate. + +Chat responses expose `citationSources` independently of selectable sources. +Historical private demo copies and hidden shared sources can therefore be +opened from saved citations without rejoining the current query scope. Missing +or unidentifiable historical evidence displays an unavailable state instead of +opening an unrelated current document. + +Original-file and asset URLs use stable Notebook routes with `job_result_id`. +The proxy forwards Range requests and meaningful upstream statuses, follows +the upstream signed redirect at request time, and does not cache signed URLs. + +## Deployment verification + +Run `pnpm lint`, `pnpm typecheck`, `pnpm test`, and `pnpm build`. Run browser +regressions with `pnpm test:e2e`; `PLAYWRIGHT_CHANNEL=chrome` can select an +already-installed Chrome for local verification. The PDF preview regression +uses a deterministic local PDF, not a live corpus dependency. + +After Vercel deploys `main`, verify shared-only and mixed chat, deselection, +hiding, persisted citation reads, and original-file preview using a dedicated +test account. Vercel and Knowhere Logfire records must show no upstream demo +materialization calls from the new client and the correct shared namespace and +document filters. Unit tests and guest reads do not replace authenticated +production acceptance. + +No schema migration, private-copy deletion, SDK upgrade, or Knowhere backend +change is required. A Notebook deployment rollback leaves the retired +upstream endpoint retired and may restore the original demo-chat failure. diff --git a/e2e/chunk-original-preview.e2e.ts b/e2e/chunk-original-preview.e2e.ts index c7e0426c..bc38b93c 100644 --- a/e2e/chunk-original-preview.e2e.ts +++ b/e2e/chunk-original-preview.e2e.ts @@ -3,12 +3,22 @@ import { expect, test, type Page } from "@playwright/test" const unsupportedPreviewText = "Preview is not available for this file." test("reopens the demo PDF preview after returning from original to parsed chunks", async ({ + context, page, }) => { - await page.goto("/") + await context.addCookies([{ name: "better-auth.session_token", value: "playwright", url: "http://localhost:3000" }]) + await page.route("**/api/sources/demo-report/chunks**", async (route) => { + await route.fulfill({ json: { chunks: [{ chunkId: "page-one", type: "text", content: "Report page one.", sourceTitle: "Shared report.pdf", pageNums: [1] }], pagination: { page: 1, pageSize: 50, total: 1, totalPages: 1 } } }) + }) + await page.route("**/api/demo-sources/demo-report/original**", async (route) => { + expect(new URL(route.request().url()).searchParams.get("job_result_id")).toBe("revision-current") + await route.fulfill({ contentType: "application/pdf", body: createPdfFixture() }) + }) + await page.goto("/e2e/shared-demo-chat") await expect( page.getByRole("heading", { name: "Parsed Results" }), ).toBeVisible() + await expect(page.getByRole("treeitem", { name: "Report page one. Text ยท Page 1", exact: true })).toBeVisible() await openFirstChunk(page) await expectDemoPdfPreview(page) @@ -27,15 +37,10 @@ test("reopens the demo PDF preview after returning from original to parsed chunk async function openFirstChunk(page: Page): Promise { await page - .locator('[data-testid^="chunk-card-shell-"]') - .first() - .getByRole("button", { name: "Open page 1" }) + .getByTestId("chunks-panel") + .getByRole("button", { name: "Original", exact: true }) .click() await expect(page.getByRole("heading", { name: "Original File" })).toBeVisible() - await expect(page.getByTestId("source-original-preview")).toHaveAttribute( - "data-target-page", - "1", - ) } async function expectDemoPdfPreview(page: Page): Promise { @@ -43,3 +48,25 @@ async function expectDemoPdfPreview(page: Page): Promise { await expect(page.locator("canvas.react-pdf__Page__canvas").first()).toBeVisible() await expect(page.getByText(unsupportedPreviewText)).toBeHidden() } + +function createPdfFixture(): Buffer { + const content: string = "BT /F1 16 Tf 40 100 Td (Notebook shared demo) Tj ET" + const objects: readonly string[] = [ + "<< /Type /Catalog /Pages 2 0 R >>", + "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", + "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>", + `<< /Length ${content.length} >>\nstream\n${content}\nendstream`, + "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", + ] + let document: string = "%PDF-1.4\n" + const offsets: number[] = [] + objects.forEach((object: string, index: number): void => { + offsets.push(Buffer.byteLength(document)) + document += `${index + 1} 0 obj\n${object}\nendobj\n` + }) + const crossReferenceOffset: number = Buffer.byteLength(document) + document += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n` + document += offsets.map((offset: number): string => `${String(offset).padStart(10, "0")} 00000 n \n`).join("") + document += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\nstartxref\n${crossReferenceOffset}\n%%EOF\n` + return Buffer.from(document) +} diff --git a/e2e/shared-demo-chat.e2e.ts b/e2e/shared-demo-chat.e2e.ts new file mode 100644 index 00000000..8e038273 --- /dev/null +++ b/e2e/shared-demo-chat.e2e.ts @@ -0,0 +1,40 @@ +import { expect, test } from "@playwright/test" + +test("sends shared demo chat without preparation and reads the cited revision", async ({ context, page }) => { + let materializationRequests: number = 0 + const chunkRevisions: string[] = [] + await context.addCookies([{ name: "better-auth.session_token", value: "playwright", url: "http://localhost:3000" }]) + await page.route("**/api/demo-sources/materialize", async (route) => { + materializationRequests += 1 + await route.fulfill({ status: 410, json: { message: "Personal demo materialization has been retired." } }) + }) + await page.route("**/api/sources/demo-report/chunks**", async (route) => { + const revision: string = new URL(route.request().url()).searchParams.get("jobResultId") ?? "" + chunkRevisions.push(revision) + await route.fulfill({ json: { + chunks: [{ chunkId: "row-report", parserChunkId: "report-chunk", documentId: "ddoc-report", jobResultId: revision, type: "text", content: revision === "revision-cited" ? "Historical report evidence." : "Current report evidence.", sourceTitle: "Shared report.pdf" }], + pagination: { page: 1, pageSize: 50, total: 1, totalPages: 1 }, + } }) + }) + await page.route("**/api/chat", async (route) => { + expect(route.request().postDataJSON()).toMatchObject({ message: "Summarize the shared report", excludedSourceIds: [] }) + await route.fulfill({ json: { + threadId: "thread-shared", + messages: [ + { id: "question", role: "user", content: "Summarize the shared report" }, + { id: "answer", role: "assistant", content: "The shared report provides evidence. [[cite:1]]", retrievalWarnings: [{ scope: "workspace", code: "RETRIEVAL_UNAVAILABLE", message: "Your documents could not be searched. This answer uses demo sources only." }], citations: [{ chunkId: "report-chunk", content: "Historical report evidence.", chunkType: "text", score: 0.9, source: { documentId: "ddoc-report", namespace: "__knowhere_demo__", jobResultId: "revision-cited", sourceFileName: "Shared report.pdf", sectionPath: "Root" } }] }, + ], + citationSources: [{ id: "demo-report", kind: "demo", demoSourceId: "demo-report", documentId: "ddoc-report", namespace: "__knowhere_demo__", jobResultId: "revision-cited", title: "Shared report.pdf", mimeType: "application/pdf", status: "ready" }], + } }) + }) + await page.goto("/e2e/shared-demo-chat") + const chatPanel = page.getByTestId("desktop-chat-panel") + await chatPanel.getByRole("textbox", { name: "Chat message" }).fill("Summarize the shared report") + await chatPanel.getByRole("button", { name: "Send message" }).click() + await expect(chatPanel.getByText("The shared report provides evidence.", { exact: false })).toBeVisible() + await expect(chatPanel.getByRole("status")).toContainText("Your documents could not be searched") + expect(materializationRequests).toBe(0) + await chatPanel.getByTestId("citation-chip").click() + await expect(page.getByText("Historical report evidence.", { exact: true })).toBeVisible() + expect(chunkRevisions).toContain("revision-cited") +}) diff --git a/playwright.config.ts b/playwright.config.ts index 77f738b3..fb8771d2 100644 --- a/playwright.config.ts +++ b/playwright.config.ts @@ -12,6 +12,7 @@ export default defineConfig({ }, use: { baseURL: "http://localhost:3000", + ...(process.env.PLAYWRIGHT_CHANNEL ? { channel: process.env.PLAYWRIGHT_CHANNEL } : {}), trace: "on-first-retry", }, projects: [ diff --git a/src/agent-harness/ledger.test.ts b/src/agent-harness/ledger.test.ts index 8f151b8c..4c7da9bf 100644 --- a/src/agent-harness/ledger.test.ts +++ b/src/agent-harness/ledger.test.ts @@ -5,6 +5,13 @@ import { createEvidenceLedger } from "./ledger" import type { ResolveConnectedAssets } from "./types" describe("createEvidenceLedger", () => { + it("preserves actual job-result provenance for retrieved and referenced evidence", () => { + const response = makeRetrievalResponse() + const snapshot = createEvidenceLedger().addRetrievalResponse({ ...response, results: response.results.map((result) => ({ ...result, metadata: { ...result.metadata, namespace: "__knowhere_demo__", jobResultId: "saved" } })), referencedChunks: response.referencedChunks.map((chunk) => ({ ...chunk, metadata: { ...chunk.metadata, namespace: "__knowhere_demo__", jobResultId: "saved" } })) }) + expect(snapshot.chunks.every((chunk) => chunk.source.namespace === "__knowhere_demo__" && chunk.source.jobResultId === "saved")).toBe(true) + expect(snapshot.chunks.every((chunk) => chunk.revisionKey === "saved")).toBe(true) + }) + it("normalizes retrieval chunks and media assets without treating candidates as final output", () => { const ledger = createEvidenceLedger() diff --git a/src/agent-harness/ledger.ts b/src/agent-harness/ledger.ts index 937fa707..22377687 100644 --- a/src/agent-harness/ledger.ts +++ b/src/agent-harness/ledger.ts @@ -4,6 +4,7 @@ import type { } from "@ontos-ai/knowhere-sdk" import type { + ConnectedAssetLookup, EvidenceAsset, EvidenceChunk, EvidenceLedgerSnapshot, @@ -97,6 +98,7 @@ export function createEvidenceLedger() { ref: `r${retrievalIndex}:referenced:${index + 1}`, kind: "referenced_chunk", chunkId: chunk.chunkId, + ...(getTrimmedString(chunk.metadata?.chunkRowId) ? { chunkRowId: getTrimmedString(chunk.metadata?.chunkRowId) ?? undefined } : {}), content, contentPreview: content, chunkType: chunk.chunkType, @@ -108,8 +110,9 @@ export function createEvidenceLedger() { documentId: chunk.documentId, sourceFileName: null, sectionPath: chunk.sectionPath, + ...getSourceProvenance(chunk.metadata), }, - ...(chunk.jobId ? { revisionKey: chunk.jobId } : {}), + ...(getSourceProvenance(chunk.metadata).jobResultId ? { revisionKey: getSourceProvenance(chunk.metadata).jobResultId } : chunk.jobId ? { revisionKey: chunk.jobId } : {}), ...(chunk.assetUrl ? { assetUrl: chunk.assetUrl } : {}), }, }) @@ -137,6 +140,8 @@ export function createEvidenceLedger() { documentId: candidate.documentId, chunkId: candidate.targetChunkId, type: candidate.type, + namespace: candidate.source.namespace, + jobResultId: candidate.source.jobResultId, }) const assetUrl = assetUrlByLookup.get(lookupKey) if (!assetUrl) { @@ -213,6 +218,7 @@ function addChunkFromResult(input: { chunkType: input.result.chunkType, score: input.result.score, chunkId: input.result.chunkId, + ...(getTrimmedString(input.result.metadata?.chunkRowId) ? { chunkRowId: getTrimmedString(input.result.metadata?.chunkRowId) ?? undefined } : {}), sourceChunkPath: input.result.sourceChunkPath, filePath: input.result.filePath, metadata: input.result.metadata, @@ -220,7 +226,9 @@ function addChunkFromResult(input: { documentId: input.result.source.documentId, sourceFileName: input.result.source.sourceFileName, sectionPath: input.result.source.sectionPath, + ...getSourceProvenance(input.result.metadata), }, + ...(getSourceProvenance(input.result.metadata).jobResultId ? { revisionKey: getSourceProvenance(input.result.metadata).jobResultId } : {}), ...(input.result.assetUrl ? { assetUrl: input.result.assetUrl } : {}), }, }) @@ -293,13 +301,15 @@ function uniqueConnectedAssetLookups( ) { const lookups = new Map< string, - { documentId: string; chunkId: string; type: EvidenceAsset["type"] } + ConnectedAssetLookup >() for (const candidate of candidates) { const lookup = { documentId: candidate.documentId, chunkId: candidate.targetChunkId, type: candidate.type, + ...(candidate.source.namespace ? { namespace: candidate.source.namespace } : {}), + ...(candidate.source.jobResultId ? { jobResultId: candidate.source.jobResultId } : {}), } lookups.set(connectedAssetLookupKey(lookup), lookup) } @@ -310,8 +320,10 @@ function connectedAssetLookupKey(input: { readonly documentId: string readonly chunkId: string readonly type: EvidenceAsset["type"] + readonly namespace?: string + readonly jobResultId?: string }): string { - return `${input.documentId}\u0000${input.type}\u0000${input.chunkId}` + return `${input.documentId}\u0000${input.namespace ?? ""}\u0000${input.jobResultId ?? ""}\u0000${input.type}\u0000${input.chunkId}` } function formatConnectedAssetLabel(candidate: ConnectedAssetCandidate): string { @@ -646,3 +658,9 @@ function getDecisionTrace(response: RetrievalQueryResponse): unknown | null { null ) } + +function getSourceProvenance(metadata?: Readonly>): { readonly namespace?: string; readonly jobResultId?: string } { + const namespace = getTrimmedString(metadata?.namespace) + const jobResultId = getTrimmedString(metadata?.jobResultId) + return { ...(namespace ? { namespace } : {}), ...(jobResultId ? { jobResultId } : {}) } +} diff --git a/src/agent-harness/types.ts b/src/agent-harness/types.ts index 907e43e4..2cb9d847 100644 --- a/src/agent-harness/types.ts +++ b/src/agent-harness/types.ts @@ -102,6 +102,8 @@ export type KnowhereToolRuntime = { } export type ConnectedAssetLookup = { + readonly namespace?: string + readonly jobResultId?: string readonly documentId: string readonly chunkId: string readonly type: "image" | "table" @@ -181,6 +183,7 @@ export type EvidencePart = export type EvidenceChunk = { readonly ref: string readonly kind: "result" | "referenced_chunk" + readonly chunkRowId?: string readonly chunkId?: string readonly content: string readonly contentPreview: string @@ -191,6 +194,8 @@ export type EvidenceChunk = { readonly metadata?: Readonly> readonly source: { readonly documentId?: string | null + readonly namespace?: string + readonly jobResultId?: string readonly sourceFileName?: string | null readonly sectionPath?: string | null } diff --git a/src/app/api/demo-sources/[demoSourceId]/assets/[...assetPath]/route.test.ts b/src/app/api/demo-sources/[demoSourceId]/assets/[...assetPath]/route.test.ts index aa1d09b2..7fbb789a 100644 --- a/src/app/api/demo-sources/[demoSourceId]/assets/[...assetPath]/route.test.ts +++ b/src/app/api/demo-sources/[demoSourceId]/assets/[...assetPath]/route.test.ts @@ -18,6 +18,27 @@ describe("GET /api/demo-sources/[demoSourceId]/assets/[...assetPath]", () => { vi.stubGlobal("fetch", mocks.fetch) }) + it("pins Range reads to the requested complete revision and preserves response headers", async () => { + mocks.fetch.mockResolvedValue(new Response("bytes", { status: 206, headers: { "content-type": "image/png", "content-range": "bytes 0-4/100", "accept-ranges": "bytes", "etag": "revision-one" } })) + const response = await GET(new Request("http://localhost/api/demo-sources/demo_1/assets/pages/1.png?job_result_id=revision-one", { headers: { range: "bytes=0-4" } }), { params: Promise.resolve({ demoSourceId: "demo_1", assetPath: ["pages", "1.png"] }) }) + expect(response.status).toBe(206) + expect(response.headers.get("content-range")).toBe("bytes 0-4/100") + expect(response.headers.get("accept-ranges")).toBe("bytes") + expect(mocks.fetch).toHaveBeenCalledWith(new URL("https://demo.example/api/v1/demo/sources/demo_1/assets/pages/1.png?job_result_id=revision-one"), expect.objectContaining({ headers: expect.objectContaining({ range: "bytes=0-4" }) })) + }) + it("preserves upstream preparing and unsatisfiable Range status", async () => { + for (const status of [409, 416, 503]) { + mocks.fetch.mockResolvedValue(new Response("unavailable", { status, headers: { "content-range": "bytes */100" } })) + const response = await GET(new Request("http://localhost/api/demo-sources/demo_1/assets/pages/1.png"), { params: Promise.resolve({ demoSourceId: "demo_1", assetPath: ["pages", "1.png"] }) }) + expect(response.status).toBe(status) + expect(response.headers.get("content-range")).toBe("bytes */100") + } + }) + it("rejects traversal before contacting Knowhere", async () => { + const response = await GET(new Request("http://localhost/api/demo-sources/demo_1/assets/bad"), { params: Promise.resolve({ demoSourceId: "demo_1", assetPath: ["..", "secret"] }) }) + expect(response.status).toBe(400) + expect(mocks.fetch).not.toHaveBeenCalled() + }) it("serves demo image assets inline", async () => { mocks.fetch.mockResolvedValue( new Response("image bytes", { @@ -44,8 +65,8 @@ describe("GET /api/demo-sources/[demoSourceId]/assets/[...assetPath]", () => { expect(response.headers.get("content-type")).toBe("image/png") expect(response.headers.get("content-disposition")).toBe("inline") expect(mocks.fetch).toHaveBeenCalledWith( - "https://demo.example/api/v1/demo/sources/demo_1/assets/images/page-1.png", - { cache: "no-store" }, + new URL("https://demo.example/api/v1/demo/sources/demo_1/assets/images/page-1.png"), + expect.objectContaining({ cache: "no-store" }), ) }) }) diff --git a/src/app/api/demo-sources/[demoSourceId]/assets/[...assetPath]/route.ts b/src/app/api/demo-sources/[demoSourceId]/assets/[...assetPath]/route.ts index 7dc89c36..609fc1ee 100644 --- a/src/app/api/demo-sources/[demoSourceId]/assets/[...assetPath]/route.ts +++ b/src/app/api/demo-sources/[demoSourceId]/assets/[...assetPath]/route.ts @@ -1,40 +1,16 @@ -import { knowhereDemoApi } from "@/integrations/knowhere-demo" +import { proxyKnowhereDemoFile } from "@/integrations/knowhere-demo-file-proxy" -type RouteContext = { - readonly params: Promise<{ - readonly demoSourceId: string - readonly assetPath: string[] - }> -} - -export async function GET( - _request: Request, - context: RouteContext, -): Promise { - const { assetPath, demoSourceId } = await context.params - const encodedAssetPath = assetPath.map(encodeURIComponent).join("/") - const response = await fetch( - knowhereDemoApi.resolveApiURL( - `/api/v1/demo/sources/${encodeURIComponent( - demoSourceId, - )}/assets/${encodedAssetPath}`, - ), - { cache: "no-store" }, - ) +type RouteContext = { readonly params: Promise<{ readonly demoSourceId: string; readonly assetPath: string[] }> } - if (!response.ok || !response.body) { - return Response.json( - { message: "Demo source asset not found." }, - { status: 404 }, - ) +export async function GET(request: Request, context: RouteContext): Promise { + const { demoSourceId, assetPath } = await context.params + if (assetPath.length === 0 || assetPath.some(isUnsafeAssetSegment)) { + return Response.json({ message: "Invalid demo asset path." }, { status: 400 }) } + const encodedAssetPath: string = assetPath.map(encodeURIComponent).join("/") + return proxyKnowhereDemoFile(request, `/api/v1/demo/sources/${encodeURIComponent(demoSourceId)}/assets/${encodedAssetPath}`) +} - return new Response(response.body, { - status: 200, - headers: { - "content-type": response.headers.get("content-type") ?? "application/octet-stream", - "content-disposition": "inline", - "cache-control": "public, max-age=3600", - }, - }) +function isUnsafeAssetSegment(segment: string): boolean { + return segment.length === 0 || segment === "." || segment === ".." || /[\\/\u0000]/u.test(segment) } diff --git a/src/app/api/demo-sources/[demoSourceId]/original/route.test.ts b/src/app/api/demo-sources/[demoSourceId]/original/route.test.ts new file mode 100644 index 00000000..3847cb74 --- /dev/null +++ b/src/app/api/demo-sources/[demoSourceId]/original/route.test.ts @@ -0,0 +1,17 @@ +import { afterEach, describe, expect, it, vi } from "vitest" +vi.mock("@/integrations/knowhere-demo", () => ({ knowhereDemoApi: { resolveApiURL: (path: string) => `https://demo.example${path}` } })) +import { GET } from "./route" +afterEach(() => vi.unstubAllGlobals()) +describe("shared demo original proxy", () => { + it("preserves revision, Range and partial original disposition", async () => { + const fetcher = vi.fn().mockResolvedValue(new Response("bytes", { status: 206, headers: { "content-type": "application/pdf", "content-disposition": "inline; filename=report.pdf", "content-range": "bytes 0-4/100", "content-length": "5" } })) + vi.stubGlobal("fetch", fetcher) + const response = await GET(new Request("http://localhost/api/demo-sources/demo-report/original?job_result_id=revision-one", { headers: { range: "bytes=0-4" } }), { params: Promise.resolve({ demoSourceId: "demo-report" }) }) + expect(response.status).toBe(206) + expect(response.headers.get("content-range")).toBe("bytes 0-4/100") + expect(response.headers.get("content-disposition")).toBe("inline; filename=report.pdf") + expect(response.headers.get("content-length")).toBe("5") + expect(await response.text()).toBe("bytes") + expect(fetcher).toHaveBeenCalledWith(new URL("https://demo.example/api/v1/demo/sources/demo-report/original?job_result_id=revision-one"), expect.objectContaining({ cache: "no-store", headers: expect.objectContaining({ range: "bytes=0-4" }) })) + }) +}) diff --git a/src/app/api/demo-sources/[demoSourceId]/original/route.ts b/src/app/api/demo-sources/[demoSourceId]/original/route.ts index c3b04d32..323a386e 100644 --- a/src/app/api/demo-sources/[demoSourceId]/original/route.ts +++ b/src/app/api/demo-sources/[demoSourceId]/original/route.ts @@ -1,35 +1,8 @@ -import { knowhereDemoApi } from "@/integrations/knowhere-demo" +import { proxyKnowhereDemoFile } from "@/integrations/knowhere-demo-file-proxy" -type RouteContext = { - readonly params: Promise<{ - readonly demoSourceId: string - }> -} +type RouteContext = { readonly params: Promise<{ readonly demoSourceId: string }> } -export async function GET( - _request: Request, - context: RouteContext, -): Promise { +export async function GET(request: Request, context: RouteContext): Promise { const { demoSourceId } = await context.params - const response = await fetch( - knowhereDemoApi.resolveApiURL( - `/api/v1/demo/sources/${encodeURIComponent(demoSourceId)}/original`, - ), - { cache: "no-store" }, - ) - - if (!response.ok || !response.body) { - return Response.json( - { message: "Demo original file not found." }, - { status: 404 }, - ) - } - - return new Response(response.body, { - status: 200, - headers: { - "content-type": response.headers.get("content-type") ?? "application/pdf", - "cache-control": "public, max-age=3600", - }, - }) + return proxyKnowhereDemoFile(request, `/api/v1/demo/sources/${encodeURIComponent(demoSourceId)}/original`) } diff --git a/src/app/api/demo-sources/materialize/route.test.ts b/src/app/api/demo-sources/materialize/route.test.ts index 618dc2c3..089157c4 100644 --- a/src/app/api/demo-sources/materialize/route.test.ts +++ b/src/app/api/demo-sources/materialize/route.test.ts @@ -1,251 +1,31 @@ import { beforeEach, describe, expect, it, vi } from "vitest" - -import type { Source, Workspace } from "@/infrastructure/db/schema" - -const mocks = vi.hoisted(() => ({ - getAuthenticatedWithClient: vi.fn(), - listHiddenDemoSourceIds: vi.fn(), - materializeSources: vi.fn(), - upsertMaterializedDemoSource: vi.fn(), -})) - -vi.mock("@/domains/workspace/request-context", () => ({ - notebookRequestContext: { - getAuthenticatedWithClient: mocks.getAuthenticatedWithClient, - }, -})) - -vi.mock("@/integrations/knowhere-demo", () => ({ - knowhereDemoApi: { - materializeSources: mocks.materializeSources, - }, -})) - -vi.mock("@/domains/sources/service", () => ({ - sourceService: { - listHiddenDemoSourceIds: mocks.listHiddenDemoSourceIds, - upsertMaterializedDemoSource: mocks.upsertMaterializedDemoSource, - }, -})) - +const mocks = vi.hoisted(() => ({ getOptionalAuthenticated: vi.fn(), listHiddenDemoSourceIds: vi.fn(), restoreDemoSource: vi.fn(), fetchCatalog: vi.fn(), materializeSources: vi.fn(), upsertMaterializedDemoSource: vi.fn() })) +vi.mock("@/domains/workspace/request-context", () => ({ notebookRequestContext: { getOptionalAuthenticated: mocks.getOptionalAuthenticated } })) +vi.mock("@/domains/sources/service", () => ({ sourceService: { listHiddenDemoSourceIds: mocks.listHiddenDemoSourceIds, restoreDemoSource: mocks.restoreDemoSource, upsertMaterializedDemoSource: mocks.upsertMaterializedDemoSource } })) +vi.mock("@/integrations/knowhere-demo", () => ({ knowhereDemoApi: { fetchCatalog: mocks.fetchCatalog, materializeSources: mocks.materializeSources } })) import { POST } from "./route" - -describe("POST /api/demo-sources/materialize", () => { +const source = { demoSourceId: "demo-report", canonicalDocumentId: "ddoc_report", jobResultId: "revision-1", namespace: "__knowhere_demo__", title: "report.pdf", mimeType: "application/pdf", sizeBytes: 10, status: "ready", chunkCount: 4, originalFile: { url: "/api/v1/demo/sources/demo-report/original?job_result_id=revision-1", mimeType: "application/pdf", sizeBytes: 10, canDownload: true }, examples: [] } +describe("POST /api/demo-sources/materialize compatibility", () => { beforeEach(() => { vi.clearAllMocks() + mocks.getOptionalAuthenticated.mockResolvedValue({ workspace: { id: "workspace-1" } }) mocks.listHiddenDemoSourceIds.mockResolvedValue([]) + mocks.fetchCatalog.mockResolvedValue({ sources: [source], officialLibrary: { sources: [], categories: [] } }) }) - - it("materializes selected demo sources through Knowhere and stores source rows", async () => { - const workspace = makeWorkspace() - mocks.getAuthenticatedWithClient.mockResolvedValue({ - apiKey: "jwt_123", - workspace, - }) - mocks.materializeSources.mockResolvedValue([ - { - demoSourceId: "demo-tsla-q4-2025", - documentId: "doc_user_copy", - title: "TSLA-Q4-2025-Update.pdf", - mimeType: "application/pdf", - sizeBytes: 5648867, - chunkCount: 70, - status: "created", - originalFile: { - url: "https://example.com/tsla-q4-2025.pdf", - mimeType: "application/pdf", - sizeBytes: 5648867, - canDownload: false, - }, - }, - ]) - mocks.upsertMaterializedDemoSource.mockResolvedValue( - makeSource(workspace.id, { chunkCount: 70 }), - ) - - const response = await POST( - new Request("http://localhost:3001/api/demo-sources/materialize", { - method: "POST", - body: JSON.stringify({ - demoSourceIds: ["demo-tsla-q4-2025", "demo-tsla-q4-2025"], - }), - }), - ) - - await expect(response.json()).resolves.toEqual({ - sources: [ - { - id: "source_demo", - kind: "workspace", - title: "TSLA-Q4-2025-Update.pdf", - mimeType: "application/pdf", - status: "ready", - demoSourceId: "demo-tsla-q4-2025", - documentId: "doc_user_copy", - originalFile: { - url: "https://example.com/tsla-q4-2025.pdf", - mimeType: "application/pdf", - sizeBytes: 5648867, - canDownload: false, - pdfPreviewMode: "browser", - }, - chunkCount: 70, - }, - ], - }) + it("returns shared metadata without copying rows or contacting materializations", async () => { + const response = await POST(request(["demo-report"])) expect(response.status).toBe(200) - expect(mocks.listHiddenDemoSourceIds).toHaveBeenCalledWith(workspace.id) - expect(mocks.materializeSources).toHaveBeenCalledWith({ - apiKey: "jwt_123", - namespace: workspace.namespace, - demoSourceIds: ["demo-tsla-q4-2025"], - }) - expect(mocks.upsertMaterializedDemoSource).toHaveBeenCalledWith( - workspace.id, - { - demoSourceId: "demo-tsla-q4-2025", - title: "TSLA-Q4-2025-Update.pdf", - mimeType: "application/pdf", - sizeBytes: 5648867, - knowhereDocumentId: "doc_user_copy", - originalBlobUrl: "https://example.com/tsla-q4-2025.pdf", - chunkCount: 70, - }, - ) - }) - - it("does not store non-public legacy demo original routes", async () => { - const workspace = makeWorkspace() - mocks.getAuthenticatedWithClient.mockResolvedValue({ - apiKey: "jwt_123", - workspace, - }) - mocks.materializeSources.mockResolvedValue([ - { - demoSourceId: "legacy-demo", - documentId: "doc_legacy_copy", - title: "Legacy-Demo.pdf", - mimeType: "application/pdf", - sizeBytes: 10, - chunkCount: 1, - status: "created", - originalFile: { - url: "https://api.knowhere.example/api/v1/demo/sources/legacy-demo/original", - mimeType: "application/pdf", - sizeBytes: 10, - canDownload: false, - }, - }, - ]) - mocks.upsertMaterializedDemoSource.mockResolvedValue( - makeSource(workspace.id, { originalBlobUrl: null }), - ) - - const response = await POST( - new Request("http://localhost:3001/api/demo-sources/materialize", { - method: "POST", - body: JSON.stringify({ - demoSourceIds: ["legacy-demo"], - }), - }), - ) - - expect(response.status).toBe(200) - expect(mocks.upsertMaterializedDemoSource).toHaveBeenCalledWith( - workspace.id, - expect.objectContaining({ - demoSourceId: "legacy-demo", - originalBlobUrl: null, - }), - ) - }) - - it("does not materialize demo sources hidden in the workspace", async () => { - const workspace = makeWorkspace() - mocks.getAuthenticatedWithClient.mockResolvedValue({ - apiKey: "jwt_123", - workspace, - }) - mocks.listHiddenDemoSourceIds.mockResolvedValue(["demo-tsla-q4-2025"]) - - const response = await POST( - new Request("http://localhost:3001/api/demo-sources/materialize", { - method: "POST", - body: JSON.stringify({ - demoSourceIds: ["demo-tsla-q4-2025"], - }), - }), - ) - - await expect(response.json()).resolves.toEqual({ - message: "Selected demo sources are no longer available.", - }) - expect(response.status).toBe(400) + expect(await response.json()).toMatchObject({ sources: [{ id: "demo-report", kind: "demo", documentId: "ddoc_report", jobResultId: "revision-1" }] }) expect(mocks.materializeSources).not.toHaveBeenCalled() expect(mocks.upsertMaterializedDemoSource).not.toHaveBeenCalled() + expect(mocks.restoreDemoSource).not.toHaveBeenCalled() }) - - it("filters hidden demo sources before materializing visible selections", async () => { - const workspace = makeWorkspace() - mocks.getAuthenticatedWithClient.mockResolvedValue({ - apiKey: "jwt_123", - workspace, - }) - mocks.listHiddenDemoSourceIds.mockResolvedValue(["hidden-demo"]) - mocks.materializeSources.mockResolvedValue([]) - - const response = await POST( - new Request("http://localhost:3001/api/demo-sources/materialize", { - method: "POST", - body: JSON.stringify({ - demoSourceIds: ["hidden-demo", "demo-tsla-q4-2025"], - }), - }), - ) - + it("never restores a hidden demo", async () => { + mocks.listHiddenDemoSourceIds.mockResolvedValue(["demo-report"]) + const response = await POST(request(["demo-report"])) expect(response.status).toBe(200) - expect(mocks.materializeSources).toHaveBeenCalledWith({ - apiKey: "jwt_123", - namespace: workspace.namespace, - demoSourceIds: ["demo-tsla-q4-2025"], - }) + expect(await response.json()).toEqual({ sources: [] }) + expect(mocks.restoreDemoSource).not.toHaveBeenCalled() }) }) - -function makeWorkspace(): Workspace { - return { - id: "workspace_1", - userId: "user_1", - namespace: "notebook-workspace_1", - createdAt: new Date("2026-05-10T00:00:00.000Z"), - } -} - -function makeSource( - workspaceId: string, - overrides: Partial = {}, -): Source { - return { - id: "source_demo", - workspaceId, - title: "TSLA-Q4-2025-Update.pdf", - mimeType: "application/pdf", - sizeBytes: 5648867, - status: "ready", - failureReason: null, - failureStage: null, - knowhereJobId: null, - knowhereDocumentId: "doc_user_copy", - stagedBlobPathname: null, - stagedBlobUrl: null, - originalBlobPathname: null, - originalBlobUrl: "https://example.com/tsla-q4-2025.pdf", - demoKey: "demo-tsla-q4-2025", - chunkCount: null, - folderId: null, - createdAt: new Date("2026-05-10T00:00:00.000Z"), - updatedAt: new Date("2026-05-10T00:00:00.000Z"), - deletedAt: null, - ...overrides, - } -} +function request(demoSourceIds: readonly string[]): Request { return new Request("http://localhost/api/demo-sources/materialize", { method: "POST", body: JSON.stringify({ demoSourceIds }) }) } diff --git a/src/app/api/demo-sources/materialize/route.ts b/src/app/api/demo-sources/materialize/route.ts index ae792ae9..77492c63 100644 --- a/src/app/api/demo-sources/materialize/route.ts +++ b/src/app/api/demo-sources/materialize/route.ts @@ -1,175 +1,7 @@ -import { Effect } from "effect" import type { NextResponse } from "next/server" +import { selectDemoSources } from "@/domains/demo/route-selection" -import { chatCitationPersistence } from "@/domains/chat/chat-citation-persistence" -import { chatMessageRepository } from "@/domains/chat/chat-message-repository" -import { chatThreadRepository } from "@/domains/chat/chat-thread-repository" -import type { ChatCitationView } from "@/domains/chat/types" -import { demoOriginalFile } from "@/domains/demo/original-file" -import { databaseRuntime } from "@/domains/workspace/database-runtime" -import { sourceService } from "@/domains/sources/service" -import { toSourceView } from "@/domains/sources/view" -import { notebookRequestContext } from "@/domains/workspace/request-context" -import { knowhereDemoApi } from "@/integrations/knowhere-demo" -import { nextRouteResponse } from "@/lib/next-route-response" -import { routeResult } from "@/lib/route-result" - -export async function POST(request: Request): Promise { - return Effect.runPromise( - Effect.gen(function* () { - const body = yield* Effect.tryPromise(() => - routeResult.readJson(request), - ) - if (!body.ok) { - return nextRouteResponse.toNextResponse( - routeResult.badRequest("Invalid request body."), - ) - } - - const demoSourceIds = getDemoSourceIds(body.value) - if (demoSourceIds.length === 0) { - return nextRouteResponse.toNextResponse( - routeResult.badRequest("Select at least one demo source."), - ) - } - - const { apiKey, workspace } = yield* Effect.tryPromise(() => - notebookRequestContext.getAuthenticatedWithClient(), - ) - const hiddenDemoSourceIds = new Set( - yield* Effect.tryPromise(() => - sourceService.listHiddenDemoSourceIds(workspace.id), - ), - ) - const visibleDemoSourceIds = demoSourceIds.filter( - (demoSourceId) => !hiddenDemoSourceIds.has(demoSourceId), - ) - if (visibleDemoSourceIds.length === 0) { - return nextRouteResponse.toNextResponse( - routeResult.badRequest( - "Selected demo sources are no longer available.", - ), - ) - } - - const materializedSources = yield* Effect.tryPromise(() => - knowhereDemoApi.materializeSources({ - apiKey, - namespace: workspace.namespace, - demoSourceIds: visibleDemoSourceIds, - }), - ) - - const sources = yield* Effect.all( - materializedSources.map((source) => - Effect.gen(function* () { - const row = yield* Effect.tryPromise(() => - sourceService.upsertMaterializedDemoSource(workspace.id, { - demoSourceId: source.demoSourceId, - title: source.title, - mimeType: source.mimeType, - sizeBytes: source.sizeBytes, - knowhereDocumentId: source.documentId, - originalBlobUrl: demoOriginalFile.getPublicUrl(source), - chunkCount: source.chunkCount, - }), - ) - return toSourceView(row) - }), - ), - { concurrency: "unbounded" }, - ) - - // After materialization, remap seeded demo-thread citations from their - // canonical document IDs to the new materialized document IDs so source - // citation resolution continues to work. - yield* Effect.tryPromise(() => - fixDemoThreadCitations(workspace.id, materializedSources), - ).pipe(Effect.catchAllCause(() => Effect.void)) - - return nextRouteResponse.toNextResponse(routeResult.ok({ sources })) - }).pipe( - Effect.catchAll(() => - Effect.succeed( - nextRouteResponse.toNextResponse( - routeResult.error( - 502, - "Demo sources could not be prepared right now.", - ), - ), - ), - ), - ), - ) -} - -function getDemoSourceIds(value: unknown): string[] { - if (!isRecord(value) || !Array.isArray(value.demoSourceIds)) return [] - - const selectedIds = value.demoSourceIds.filter( - (item): item is string => - typeof item === "string" && item.trim().length > 0, - ) - return Array.from(new Set(selectedIds.map((item) => item.trim()))) -} - -function isRecord(value: unknown): value is Readonly> { - return typeof value === "object" && value !== null -} - -const seededDemoChatKey = "knowhere-demo-chat" - -async function fixDemoThreadCitations( - workspaceId: string, - materializedSources: ReadonlyArray<{ - readonly demoSourceId: string - readonly documentId: string - }>, -): Promise { - const catalog = await knowhereDemoApi.fetchCatalog() - const canonicalIdByDemoSourceId = new Map( - catalog.sources.map((s) => [s.demoSourceId, s.canonicalDocumentId]), - ) - const documentIdMap = new Map() - for (const source of materializedSources) { - const canonical = canonicalIdByDemoSourceId.get(source.demoSourceId) - if (canonical) { - documentIdMap.set(canonical, source.documentId) - } - } - if (documentIdMap.size === 0) return - - const thread = await databaseRuntime.runPromise( - chatThreadRepository.findThreadByDemoKeyEffect( - workspaceId, - seededDemoChatKey, - ), - ) - if (!thread) return - - const messages = await databaseRuntime.runPromise( - chatMessageRepository.listMessagesForThreadEffect(workspaceId, thread.id), - ) - if (!messages || messages.length === 0) return - - await Promise.all( - messages.map(async (message) => { - const currentCitations = message.citations as - | ChatCitationView[] - | null - | undefined - const updated = chatCitationPersistence.replaceDemoCitationDocumentId( - currentCitations ?? undefined, - documentIdMap, - ) - if (!updated) return - - await databaseRuntime.runPromise( - chatMessageRepository.updateMessageCitationsEffect( - message.id, - chatCitationPersistence.normalizeCitations(updated), - ), - ) - }), - ) +/** Compatibility metadata read for older clients; selection writes use /select. */ +export function POST(request: Request): Promise { + return selectDemoSources(request, false) } diff --git a/src/app/api/demo-sources/select/route.test.ts b/src/app/api/demo-sources/select/route.test.ts new file mode 100644 index 00000000..0699982d --- /dev/null +++ b/src/app/api/demo-sources/select/route.test.ts @@ -0,0 +1,61 @@ +import { beforeEach, describe, expect, it, vi } from "vitest" +import { Effect } from "effect" +const mocks = vi.hoisted(() => ({ getOptionalAuthenticated: vi.fn(), listHiddenDemoSourceIds: vi.fn(), restoreDemoSource: vi.fn(), fetchCatalog: vi.fn() })) +vi.mock("@/domains/workspace/request-context", () => ({ notebookRequestContext: { getOptionalAuthenticated: mocks.getOptionalAuthenticated } })) +vi.mock("@/domains/sources/service", () => ({ sourceService: { listHiddenDemoSourceIds: mocks.listHiddenDemoSourceIds, restoreDemoSource: mocks.restoreDemoSource } })) +vi.mock("@/integrations/knowhere-demo", () => ({ knowhereDemoApi: { fetchCatalog: mocks.fetchCatalog } })) +import { POST } from "./route" +const source = { demoSourceId: "demo-report", canonicalDocumentId: "ddoc_report", jobResultId: "revision-1", namespace: "__knowhere_demo__", title: "report.pdf", mimeType: "application/pdf", sizeBytes: 10, status: "ready", chunkCount: 4, originalFile: { url: "/api/v1/demo/sources/demo-report/original", mimeType: "application/pdf", sizeBytes: 10, canDownload: true }, examples: [], officialLibrary: { librarySourceId: "official-report", categoryId: "reports", sourceUrl: "https://example.com/report.pdf" } } +describe("POST /api/demo-sources/select", () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.getOptionalAuthenticated.mockResolvedValue({ workspace: { id: "workspace-1" } }) + mocks.listHiddenDemoSourceIds.mockResolvedValue(["demo-report"]) + mocks.restoreDemoSource.mockResolvedValue(undefined) + mocks.fetchCatalog.mockResolvedValue({ sources: [source], officialLibrary: { sources: [{ demoSourceId: "demo-preparing", status: "planned" }], categories: [] } }) + }) + it("restores visibility once per selected ID and returns queryable current metadata", async () => { + const response = await POST(request(["demo-report", "demo-report"])) + expect(response.status).toBe(200) + const result = await response.json() + expect(result).toMatchObject({ sources: [{ id: "demo-report", kind: "demo", namespace: "__knowhere_demo__", documentId: "ddoc_report", jobResultId: "revision-1" }] }) + expect(result.sources[0].officialLibrary).toBeUndefined() + expect(mocks.restoreDemoSource).toHaveBeenCalledExactlyOnceWith("workspace-1", "demo-report") + }) + it("requires authentication", async () => { + mocks.getOptionalAuthenticated.mockResolvedValue(null) + const response = await POST(request(["demo-report"])) + expect(response.status).toBe(401) + expect(mocks.restoreDemoSource).not.toHaveBeenCalled() + }) + it("rejects a whole selection before writes when any ID is unknown", async () => { + const response = await POST(request(["demo-report", "unknown"])) + expect(response.status).toBe(404) + expect(mocks.restoreDemoSource).not.toHaveBeenCalled() + }) + it("reports known preparing selections", async () => { + const response = await POST(request(["demo-preparing"])) + expect(response.status).toBe(409) + expect(mocks.restoreDemoSource).not.toHaveBeenCalled() + }) + it("recognizes preparing IDs listed outside the Official Library", async () => { + mocks.fetchCatalog.mockResolvedValue({ sources: [], importStatuses: [{ demoSourceId: "demo-preparing", status: "processing" }], officialLibrary: { sources: [], categories: [] } }) + const response = await POST(request(["demo-preparing"])) + expect(response.status).toBe(409) + expect(mocks.restoreDemoSource).not.toHaveBeenCalled() + }) + it("preserves known upstream statuses across Effect promise failures", async () => { + for (const status of [401, 404, 409, 503]) { + mocks.fetchCatalog.mockImplementation(() => Effect.runPromise(Effect.fail({ _tag: "KnowhereDemoApiError", status, body: "upstream internal diagnostic" }))) + const response = await POST(request(["demo-report"])) + expect(response.status).toBe(status) + expect(await response.text()).not.toContain("internal diagnostic") + } + }) + it("rejects invalid IDs instead of silently filtering them", async () => { + const response = await POST(new Request("http://localhost/api/demo-sources/select", { method: "POST", body: JSON.stringify({ demoSourceIds: ["demo-report", 2] }) })) + expect(response.status).toBe(400) + expect(mocks.restoreDemoSource).not.toHaveBeenCalled() + }) +}) +function request(demoSourceIds: readonly string[]): Request { return new Request("http://localhost/api/demo-sources/select", { method: "POST", body: JSON.stringify({ demoSourceIds }) }) } diff --git a/src/app/api/demo-sources/select/route.ts b/src/app/api/demo-sources/select/route.ts new file mode 100644 index 00000000..da71812b --- /dev/null +++ b/src/app/api/demo-sources/select/route.ts @@ -0,0 +1,6 @@ +import type { NextResponse } from "next/server" +import { selectDemoSources } from "@/domains/demo/route-selection" + +export function POST(request: Request): Promise { + return selectDemoSources(request, true) +} diff --git a/src/app/api/sources/[sourceId]/chunks/route.test.ts b/src/app/api/sources/[sourceId]/chunks/route.test.ts index 3ff41881..55c281fd 100644 --- a/src/app/api/sources/[sourceId]/chunks/route.test.ts +++ b/src/app/api/sources/[sourceId]/chunks/route.test.ts @@ -1,4 +1,6 @@ import { NextRequest } from "next/server" +import { Effect } from "effect" +import { workspaceClient } from "@/domains/workspace/client" import { beforeEach, describe, expect, it, vi } from "vitest" const mocks = vi.hoisted(() => ({ @@ -70,6 +72,39 @@ describe("GET /api/sources/[sourceId]/chunks", () => { }) }) + it.each([401, 404, 409, 503])("preserves real upstream %s statuses and safe client state for current and saved demo reads", async (status) => { + const warnSpy = vi.spyOn(console, "warn").mockImplementation(() => undefined) + try { + mocks.getCurrentUser.mockResolvedValue(null) + mocks.fetchDemoChunkPage.mockImplementation(() => Effect.runPromise(Effect.fail({ _tag: "KnowhereDemoApiError", status, body: "internal upstream diagnostic" }))) + for (const jobResultId of [undefined, "saved_revision"]) { + const query: string = jobResultId ? "?page=1&jobResultId=saved_revision" : "?page=1" + const response = await GET(new NextRequest(`http://localhost:3001/api/sources/demo-report/chunks${query}`), { params: Promise.resolve({ sourceId: "demo-report" }) }) + expect(response.status).toBe(status) + const body: unknown = await response.clone().json() + expect(body).toMatchObject({ chunks: [], message: expect.any(String), ...(status === 409 ? { isProcessing: true } : { isUnavailable: true }) }) + expect(JSON.stringify(body)).not.toContain("internal upstream diagnostic") + if (status === 404 && jobResultId) expect(body).toMatchObject({ message: expect.stringMatching(/cited.*revision.*unavailable/i) }) + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(response)) + const page = await workspaceClient.fetchChunkPage("demo-report", 1, jobResultId ? { jobResultId } : undefined) + expect(page).toMatchObject(status === 409 ? { isProcessing: true } : { isUnavailable: true }) + expect(page.isProcessing === true).toBe(status === 409) + vi.unstubAllGlobals() + } + } finally { + vi.unstubAllGlobals() + warnSpy.mockRestore() + } + }) + + it("does not substitute the current shared revision when a pinned read returns another revision", async () => { + mocks.getCurrentUser.mockResolvedValue(null) + mocks.fetchDemoChunkPage.mockResolvedValue({ demoSourceId: "demo-report", canonicalDocumentId: "doc", namespace: "__knowhere_demo__", jobResultId: "current", title: "Report", mimeType: "application/pdf", chunks: [], pagination: { page: 1, pageSize: 50, total: 0, totalPages: 1 } }) + const response = await GET(new NextRequest("http://localhost:3001/api/sources/demo-report/chunks?page=1&jobResultId=saved"), { params: Promise.resolve({ sourceId: "demo-report" }) }) + expect(await response.json()).toMatchObject({ chunks: [], isUnavailable: true }) + expect(mocks.fetchDemoChunkPage).toHaveBeenCalledWith({ demoSourceId: "demo-report", page: 1, pageSize: 50, jobResultId: "saved" }) + }) + it("serves API-owned demo chunks for anonymous canonical demo sources", async () => { mocks.getCurrentUser.mockResolvedValue(null) mocks.fetchDemoChunkPage.mockResolvedValue({ @@ -136,6 +171,8 @@ describe("GET /api/sources/[sourceId]/chunks", () => { .mockResolvedValueOnce({ demoSourceId: "demo-tsla-q4-2025", canonicalDocumentId: "demo-doc-tsla-q4-2025", + namespace: "__knowhere_demo__", + jobResultId: "first_revision", title: "TSLA-Q4-2025-Update.pdf", mimeType: "application/pdf", chunks: [ @@ -162,6 +199,8 @@ describe("GET /api/sources/[sourceId]/chunks", () => { .mockResolvedValueOnce({ demoSourceId: "demo-tsla-q4-2025", canonicalDocumentId: "demo-doc-tsla-q4-2025", + namespace: "__knowhere_demo__", + jobResultId: "first_revision", title: "TSLA-Q4-2025-Update.pdf", mimeType: "application/pdf", chunks: [ @@ -209,6 +248,7 @@ describe("GET /api/sources/[sourceId]/chunks", () => { demoSourceId: "demo-tsla-q4-2025", page: 2, pageSize: 200, + jobResultId: "first_revision", }) }) @@ -284,7 +324,7 @@ describe("GET /api/sources/[sourceId]/chunks", () => { expect(mocks.makeKnowhereClient).not.toHaveBeenCalled() }) - it("serves demo chunks for authenticated materialized demo sources", async () => { + it("reads historical private demo documents through the authenticated document API", async () => { mocks.getCurrentUser.mockResolvedValue({ id: "user_1", email: null, @@ -317,6 +357,12 @@ describe("GET /api/sources/[sourceId]/chunks", () => { updatedAt: new Date("2026-05-10T00:00:00.000Z"), deletedAt: null, }) + mocks.ensureApiKeyForWorkspace.mockResolvedValue("key") + mocks.readChunks.mockResolvedValue({ + document: { resultDirectoryPath: "parsed-storage:private" }, + chunks: [{ chunkId: "private_parser", chunkType: "text", content: "Private historical content", metadata: {} }], + page: 1, pageSize: 100, totalChunks: 1, totalPages: 1, + }) mocks.fetchDemoChunkPage.mockResolvedValue({ demoSourceId: "demo-tsla-q4-2025", canonicalDocumentId: "demo-doc-tsla-q4-2025", @@ -351,28 +397,10 @@ describe("GET /api/sources/[sourceId]/chunks", () => { { params: Promise.resolve({ sourceId: "00000000-0000-0000-0000-000000000001" }) }, ) - await expect(response.json()).resolves.toMatchObject({ - chunks: [ - { - chunkId: "demo-tsla-q4-2025:chunk_1", - documentId: "copied-doc-tsla-q4-2025", - sourceTitle: "TSLA-Q4-2025-Update.pdf", - }, - ], - pagination: { - page: 1, - pageSize: 100, - total: 70, - }, - }) + await expect(response.json()).resolves.toMatchObject({ chunks: [{ documentId: "copied-doc-tsla-q4-2025", content: "Private historical content" }] }) expect(response.status).toBe(200) - expect(mocks.fetchDemoChunkPage).toHaveBeenCalledWith({ - demoSourceId: "demo-tsla-q4-2025", - page: 1, - pageSize: 100, - }) - expect(mocks.ensureApiKeyForWorkspace).not.toHaveBeenCalled() - expect(mocks.makeKnowhereClient).not.toHaveBeenCalled() + expect(mocks.fetchDemoChunkPage).not.toHaveBeenCalled() + expect(mocks.readChunks).toHaveBeenCalledWith({ documentId: "copied-doc-tsla-q4-2025", page: 1, pageSize: 100 }) }) it("logs the demo chunk load failure before returning 404", async () => { @@ -807,6 +835,7 @@ describe("GET /api/sources/[sourceId]/chunks", () => { }, }) expect(response.status).toBe(200) + expect(mocks.fetchDemoChunkPage).not.toHaveBeenCalled() expect(mocks.findSourceInWorkspace).not.toHaveBeenCalled() expect(mocks.ensureApiKeyForWorkspace).toHaveBeenCalledWith( "workspace_1", diff --git a/src/app/api/sources/[sourceId]/route.test.ts b/src/app/api/sources/[sourceId]/route.test.ts index 034d6777..ec48aeac 100644 --- a/src/app/api/sources/[sourceId]/route.test.ts +++ b/src/app/api/sources/[sourceId]/route.test.ts @@ -74,6 +74,7 @@ import { PATCH } from "./route"; describe("PATCH /api/sources/[sourceId]", () => { beforeEach(() => { vi.clearAllMocks(); + mocks.fetchDemoCatalog.mockResolvedValue({ sources: [], officialLibrary: { categories: [], sources: [] } }); }); it("archives the Knowhere document before soft deleting the source", async () => { @@ -244,7 +245,7 @@ describe("PATCH /api/sources/[sourceId]", () => { ); }); - it("archives materialized demo sources and records canonical visibility", async () => { + it("hides legacy demo selections and retains existing rows for citations", async () => { mocks.requireUser.mockResolvedValue({ id: "user_1" }); mocks.ensureWorkspace.mockResolvedValue({ id: "workspace_1" }); mocks.findSourceInWorkspace.mockResolvedValue({ @@ -274,16 +275,10 @@ describe("PATCH /api/sources/[sourceId]", () => { archived: true, }); expect(response.status).toBe(200); - expect(mocks.ensureApiKeyForWorkspace).toHaveBeenCalledWith( - "workspace_1", - "session=abc", - ); - expect(mocks.archive).toHaveBeenCalledWith("doc_user_copy"); + expect(mocks.ensureApiKeyForWorkspace).not.toHaveBeenCalled(); + expect(mocks.archive).not.toHaveBeenCalled(); expect(mocks.deleteBlob).not.toHaveBeenCalled(); - expect(mocks.softDeleteSource).toHaveBeenCalledWith( - "workspace_1", - "source_demo", - ); + expect(mocks.softDeleteSource).not.toHaveBeenCalled(); expect(mocks.hideDemoSource).toHaveBeenCalledWith( "workspace_1", "demo-tsla-q4-2025", diff --git a/src/app/e2e/shared-demo-chat/page.tsx b/src/app/e2e/shared-demo-chat/page.tsx new file mode 100644 index 00000000..70004d11 --- /dev/null +++ b/src/app/e2e/shared-demo-chat/page.tsx @@ -0,0 +1,37 @@ +import { notFound } from "next/navigation" + +import { WorkspaceShell } from "@/components/workspace-shell" +import type { SourceView } from "@/domains/sources/types" + +const sharedSource: SourceView = { + id: "demo-report", + kind: "demo", + demoSourceId: "demo-report", + documentId: "ddoc-report", + namespace: "__knowhere_demo__", + jobResultId: "revision-current", + title: "Shared report.pdf", + mimeType: "application/pdf", + status: "ready", + chunkCount: 1, + originalFile: { + url: "/api/demo-sources/demo-report/original?job_result_id=revision-current", + mimeType: "application/pdf", + canDownload: true, + }, +} + +export default function SharedDemoChatTestPage() { + if (process.env.NODE_ENV === "production") notFound() + + return ( + + ) +} diff --git a/src/components/chat-message-list.test.ts b/src/components/chat-message-list.test.ts index f62632e2..5c6a0cd6 100644 --- a/src/components/chat-message-list.test.ts +++ b/src/components/chat-message-list.test.ts @@ -28,6 +28,17 @@ describe("ChatMessageList", () => { vi.restoreAllMocks(); }); + it("shows retrieval coverage warnings beside the answer", () => { + render(React.createElement(ChatMessageList, { + messages: [{ + id: "partial-answer", role: "assistant", content: "Available evidence answer.", + retrievalWarnings: [{ scope: "demo", code: "DEMO_NOT_READY", message: "Demo sources could not be searched. This answer uses your documents only." }], + }], + })); + expect(screen.getByRole("status").textContent).toContain("Demo sources could not be searched"); + expect(screen.getByText("Available evidence answer.")).toBeTruthy(); + }); + it("renders assistant citations using Notebook source labels", () => { render( React.createElement(ChatMessageList, { diff --git a/src/components/chat-message-list.tsx b/src/components/chat-message-list.tsx index 2b7a5d13..b6694646 100644 --- a/src/components/chat-message-list.tsx +++ b/src/components/chat-message-list.tsx @@ -349,6 +349,13 @@ function MessageBubble({ pendingCitationId={pendingCitationId} sourceTitlesByDocumentId={sourceTitlesByDocumentId} /> + {message.retrievalWarnings && message.retrievalWarnings.length > 0 && ( +
+ {message.retrievalWarnings.map((warning) => ( +

{warning.message}

+ ))} +
+ )} {displayDerivedTables.length > 0 && (
{displayDerivedTables.map((artifact) => ( diff --git a/src/components/official-library-panel.test.ts b/src/components/official-library-panel.test.ts index 16d20624..6ea4ce10 100644 --- a/src/components/official-library-panel.test.ts +++ b/src/components/official-library-panel.test.ts @@ -142,7 +142,7 @@ describe("OfficialLibraryPanel", () => { expect(addButton.className).toContain("min-[1116px]:opacity-0"); }); - it("marks already added library documents and removes duplicate add actions", () => { + it("marks selected shared library documents and removes duplicate add actions", () => { const onOfficialLibrarySourceAdd = vi.fn(); render( @@ -150,7 +150,7 @@ describe("OfficialLibraryPanel", () => { sources: [ { id: "source_spacex", - kind: "workspace", + kind: "demo", demoSourceId: "demo-spacex-s1", title: "spacex-s1.pdf", status: "ready", diff --git a/src/components/official-library-panel.tsx b/src/components/official-library-panel.tsx index 86dee084..033f1cf9 100644 --- a/src/components/official-library-panel.tsx +++ b/src/components/official-library-panel.tsx @@ -295,7 +295,7 @@ function getLibraryItems( ): LibraryItem[] { const addedDemoSourceIdSet = new Set( sources - .filter((source) => source.kind !== "demo") + .filter((source) => source.officialLibrary === undefined) .flatMap((source) => (source.demoSourceId ? [source.demoSourceId] : [])), ); const metadataByLibrarySourceId = new Map( diff --git a/src/components/workspace-chat-workflow.test.ts b/src/components/workspace-chat-workflow.test.ts index 25ac6b98..fc3f5554 100644 --- a/src/components/workspace-chat-workflow.test.ts +++ b/src/components/workspace-chat-workflow.test.ts @@ -36,7 +36,7 @@ import { useWorkspaceChatWorkflow } from "./workspace-chat-workflow" describe("useWorkspaceChatWorkflow", () => { beforeEach(() => { - vi.clearAllMocks() + vi.resetAllMocks() }) it("creates a Chat Thread and makes it active without route knowledge in the caller", async () => { @@ -81,7 +81,7 @@ describe("useWorkspaceChatWorkflow", () => { currentFolderId: "folder_1", initialChatThreads: [], initialChatMessages: [], - sources: [source], + sources: [source, makeSource({ id: "source_included" })], }) await act(async () => { @@ -114,20 +114,22 @@ describe("useWorkspaceChatWorkflow", () => { ]) }) - it("shows a retryable error without sending chat when demo materialization fails", async () => { + it("sends directly with a shared demo even when the retired materialization API is unavailable", async () => { const demoSource = makeSource({ id: "demo-tsla-q4-2025", kind: "demo", demoSourceId: "demo-tsla-q4-2025", }) - const onSourcesMaterialized = vi.fn() mocks.fetchChatThreads.mockResolvedValue([]) mocks.materializeDemoSources.mockRejectedValue(new Error("Bad gateway")) + mocks.sendChatMessage.mockResolvedValue({ + threadId: "thread_demo", + messages: [{ id: "assistant_demo", role: "assistant", content: "Q4 answer" }], + }) const { result } = renderWorkspaceChatWorkflow({ initialChatThreads: [], initialChatMessages: [], - onSourcesMaterialized, sources: [demoSource], }) @@ -137,16 +139,62 @@ describe("useWorkspaceChatWorkflow", () => { }) }) - expect(mocks.materializeDemoSources).toHaveBeenCalledWith({ - demoSourceIds: ["demo-tsla-q4-2025"], + expect(mocks.materializeDemoSources).not.toHaveBeenCalled() + expect(mocks.sendChatMessage).toHaveBeenCalledWith(expect.objectContaining({ + message: "What changed in Q4?", + excludedSourceIds: [], + })) + expect(result.current.chat.error).toBeNull() + expect(result.current.chat.isSending).toBe(false) + }) + + it("does not send when every ready source is excluded", async () => { + mocks.fetchChatThreads.mockResolvedValue([]) + const { result } = renderWorkspaceChatWorkflow({ + initialChatThreads: [], initialChatMessages: [], + sources: [makeSource({ excludedFromQuery: true })], + }) + await act(async () => { + await result.current.handleChatSend("Summarize it", { useAgentic: true }) }) expect(mocks.sendChatMessage).not.toHaveBeenCalled() - expect(onSourcesMaterialized).not.toHaveBeenCalled() - expect(result.current.chat.messages).toEqual([]) - expect(result.current.chat.error).toBe( - "Demo sources could not be prepared right now.", - ) - expect(result.current.chat.isSending).toBe(false) + expect(result.current.chat.error).toBe("Add a ready source before asking questions.") + }) + + it("keeps historical citation sources separate from queryable sources", async () => { + const historicalSource = makeSource({ id: "legacy-demo-copy", documentId: "old-private-doc" }) + mocks.fetchChatThreads.mockResolvedValue([]) + mocks.fetchChatThread.mockResolvedValue({ + requestedThreadId: "thread_history", thread: makeThread({ id: "thread_history" }), + messages: [], citationSources: [historicalSource], + }) + const { result } = renderWorkspaceChatWorkflow({ + initialChatThreads: [], initialChatMessages: [], sources: [], + }) + await act(async () => result.current.handleSelectChatThread("thread_history")) + await waitFor(() => { + expect(result.current.citationSources).toEqual([historicalSource]) + }) + }) + + it("retains earlier historical citation sources after sending another turn", async () => { + const historicalSource = makeSource({ id: "legacy-copy", documentId: "legacy-doc" }) + const currentSource = makeSource({ id: "current-source", documentId: "current-doc" }) + mocks.fetchChatThreads.mockResolvedValue([]) + mocks.sendChatMessage.mockResolvedValue({ threadId: "thread_history", messages: [ + { id: "new-answer", role: "assistant", content: "New answer" }, + ], citationSources: [currentSource] }) + const { result } = renderWorkspaceChatWorkflow({ + activeChatThreadId: "thread_history", initialChatThreads: [makeThread({ id: "thread_history" })], + initialChatMessages: [], initialCitationSources: [historicalSource], sources: [currentSource], + }) + await act(async () => { + await result.current.handleChatSend("Another question", { useAgentic: true }) + }) + expect(result.current.citationSources).toEqual([historicalSource, currentSource]) + await act(async () => result.current.handleSelectChatThread("another-thread")) + await act(async () => result.current.handleSelectChatThread("thread_history")) + expect(result.current.citationSources).toEqual([historicalSource, currentSource]) }) it("blocks chat until Official Library demo sources are explicitly added", async () => { @@ -197,6 +245,7 @@ function renderWorkspaceChatWorkflow(input: { readonly currentFolderId?: string | null readonly initialChatMessages: readonly [] readonly initialChatThreads: readonly ChatThreadView[] + readonly initialCitationSources?: readonly SourceView[] readonly isGuest?: boolean readonly onSourcesMaterialized?: ( demoSourceIds: readonly string[], diff --git a/src/components/workspace-chat-workflow.ts b/src/components/workspace-chat-workflow.ts index feaa4025..dcf9ce4a 100644 --- a/src/components/workspace-chat-workflow.ts +++ b/src/components/workspace-chat-workflow.ts @@ -29,11 +29,8 @@ type WorkspaceChatWorkflowInput = { readonly analyticsContext?: AnalyticsContext readonly initialChatMessages?: readonly ChatMessageView[] readonly initialChatThreads?: readonly ChatThreadView[] + readonly initialCitationSources?: readonly SourceView[] readonly isGuest?: boolean - readonly onSourcesMaterialized?: ( - demoSourceIds: readonly string[], - materializedSources: readonly SourceView[], - ) => void readonly sources: readonly SourceView[] readonly currentFolderId?: string | null } @@ -41,6 +38,7 @@ type WorkspaceChatWorkflowInput = { type ChatMessageRequest = Parameters[0] type WorkspaceChatWorkflow = { + readonly citationSources: readonly SourceView[] readonly archivingThreadIds: string[] readonly chat: ReturnType readonly chatThreads: ChatThreadView[] @@ -65,8 +63,8 @@ export function useWorkspaceChatWorkflow({ analyticsContext, initialChatMessages = [], initialChatThreads = [], + initialCitationSources = [], isGuest = false, - onSourcesMaterialized, sources, currentFolderId = null, }: WorkspaceChatWorkflowInput): WorkspaceChatWorkflow { @@ -79,6 +77,9 @@ export function useWorkspaceChatWorkflow({ ), ) const optimisticMessageSequence = useRef(0) + const [citationSourcesByThreadId, setCitationSourcesByThreadId] = useState< + Readonly> + >(() => activeChatThreadId ? { [activeChatThreadId]: initialCitationSources } : {}) const didTrackFirstQuestionRef = useRef(initialChatMessages.length > 0) const { cache, mutate: mutateSWR } = useSWRConfig() const initialThreadRows = useMemo( @@ -112,7 +113,8 @@ export function useWorkspaceChatWorkflow({ fallbackData: chat.threadId === activeChatThreadId ? initialChatThreadData : undefined, revalidateIfStale: false, - revalidateOnMount: false, + revalidateOnMount: + chat.threadId === activeChatThreadId && initialChatThreadData ? false : undefined, onSuccess: handleChatThreadLoaded, onError: handleChatThreadLoadFailed, }) @@ -130,13 +132,25 @@ export function useWorkspaceChatWorkflow({ function handleChatThreadLoaded(body: ChatThreadDetailResponse): void { const requestedThreadId = body.requestedThreadId - + storeCitationSources(requestedThreadId, body.citationSources) setChat((current) => workspaceChatState.loadThread(current, body)) setLoadingThreadId((current) => current === requestedThreadId ? null : current, ) } + function storeCitationSources(threadId: string, citationSources: readonly SourceView[] | undefined): void { + if (!citationSources) return + setCitationSourcesByThreadId((current) => { + const sourcesByReference: Map = new Map( + [...(current[threadId] ?? []), ...citationSources].map((source): [string, SourceView] => [ + JSON.stringify([source.id, source.namespace, source.jobResultId]), source, + ]), + ) + return { ...current, [threadId]: [...sourcesByReference.values()] } + }) + } + function handleChatThreadLoadFailed(): void { setChat((current) => workspaceChatState.failLoad(current)) setLoadingThreadId(null) @@ -163,6 +177,7 @@ export function useWorkspaceChatWorkflow({ { revalidate: false }, ) setChat(workspaceChatState.createThread(body.thread.id, body.messages)) + storeCitationSources(body.thread.id, body.citationSources) } catch { setChat((current) => workspaceChatState.failCreate(current)) } @@ -176,6 +191,7 @@ export function useWorkspaceChatWorkflow({ (threadId === activeChatThreadId ? initialChatThreadData : null) if (workspaceClientCache.hasLoadedChatThreadData(cachedThreadData)) { + storeCitationSources(threadId, cachedThreadData.citationSources) void mutateSWR( workspaceClientCache.getChatThreadKey(threadId), cachedThreadData, @@ -238,6 +254,7 @@ export function useWorkspaceChatWorkflow({ const fresh = await workspaceClient.fetchChatThread(threadId) if (!fresh.thread || !Array.isArray(fresh.messages)) return const messages = fresh.messages + storeCitationSources(threadId, fresh.citationSources) void mutateSWR( workspaceClientCache.getChatThreadKey(threadId), @@ -262,27 +279,6 @@ export function useWorkspaceChatWorkflow({ (source) => isQueryableReadySource(source) && !source.excludedFromQuery, ).length - const demoSourceIds = getMaterializableDemoSourceIds(sources) - if (demoSourceIds.length > 0) { - setChat((current) => - workspaceChatState.prepareSend(current, "Thinking"), - ) - try { - const materializedSources = - await workspaceClient.materializeDemoSources({ demoSourceIds }) - onSourcesMaterialized?.(demoSourceIds, materializedSources) - await handleRefreshActiveChatThread() - } catch { - setChat((current) => ({ - ...current, - isSending: false, - isLoading: false, - pendingStatusText: null, - error: "Demo sources could not be prepared right now.", - })) - return - } - } if (!hasQueryableReadySource(sources)) { setChat((current) => ({ ...current, @@ -335,6 +331,7 @@ export function useWorkspaceChatWorkflow({ selectedSourcesCount, }) } + storeCitationSources(body.threadId, body.citationSources) void trackNotebookAssistantAnswerCompleted({ context: analyticsContext, threadId: body.threadId, @@ -365,6 +362,7 @@ export function useWorkspaceChatWorkflow({ requestedThreadId: body.threadId, thread: nextThread, messages: body.messages, + citationSources: body.citationSources, }, { revalidate: false }, ) @@ -382,6 +380,7 @@ export function useWorkspaceChatWorkflow({ } return { + citationSources: chat.threadId ? citationSourcesByThreadId[chat.threadId] ?? [] : [], archivingThreadIds, chat, chatThreads, @@ -395,20 +394,8 @@ export function useWorkspaceChatWorkflow({ } } -function getMaterializableDemoSourceIds( - sources: readonly SourceView[], -): string[] { - const demoSourceIds = sources - .filter((source) => source.kind === "demo") - .filter((source) => source.officialLibrary === undefined) - .filter((source) => !source.excludedFromQuery) - .map((source) => source.demoSourceId ?? source.id) - - return Array.from(new Set(demoSourceIds)) -} - function hasQueryableReadySource(sources: readonly SourceView[]): boolean { - return sources.some(isQueryableReadySource) + return sources.some((source) => isQueryableReadySource(source) && !source.excludedFromQuery) } function isQueryableReadySource(source: SourceView): boolean { diff --git a/src/components/workspace-citation-focus.test.ts b/src/components/workspace-citation-focus.test.ts index c3508b17..303e28f9 100644 --- a/src/components/workspace-citation-focus.test.ts +++ b/src/components/workspace-citation-focus.test.ts @@ -39,6 +39,38 @@ const prefetchedChunk: ParsedChunkView = { }; describe("useWorkspaceCitationFocus", () => { + it.each(["empty", "error"])("shows unavailable when an exact citation read is %s", async (mode) => { + const fetchChunks = vi.fn(async (): Promise => { if (mode === "error") throw new Error("Revision not found"); return [] }) + const { result } = renderHook(() => useWorkspaceCitationFocus({ fetchChunks, onSelectSource: vi.fn(), selectedSourceId: readySource.id, sources: [readySource] }), { wrapper: createSWRWrapper }) + await act(async () => { await result.current.handleCitationClick({ ...citation, chunkId: "missing" }, "missing:0") }) + expect(result.current.selectedChunksMessage).toEqual(expect.stringMatching(/unavailable/i)) + expect(result.current.focusedChunk.chunkId).toBeNull() + }) + + it("shows unavailable when an old citation cannot be resolved", async () => { + const fetchChunks = vi.fn(async () => [prefetchedChunk]) + const { result } = renderHook(() => useWorkspaceCitationFocus({ fetchChunks, onSelectSource: vi.fn(), selectedSourceId: readySource.id, sources: [readySource] }), { wrapper: createSWRWrapper }) + await act(async () => { await result.current.handleCitationClick({ ...citation, source: { documentId: "old_static_document" } }, "old:0") }) + expect(fetchChunks).not.toHaveBeenCalled() + expect(result.current.selectedChunksMessage).toMatch(/unavailable/i) + expect(result.current.selectedChunks).toEqual([]) + }) + + it("reads and retains hidden citations at their saved revision independently of sidebar selection", async () => { + const historicalSource: SourceView = { ...readySource, id: "demo-report", namespace: "__knowhere_demo__", jobResultId: "old" } + const historicalCitation: ChatCitationView = { ...citation, chunkId: "parser_old", source: { ...citation.source, namespace: "__knowhere_demo__", jobResultId: "old" } } + const historicalChunk: ParsedChunkView = { ...prefetchedChunk, chunkId: "row_old", parserChunkId: "parser_old", namespace: "__knowhere_demo__", jobResultId: "old" } + const fetchChunks = vi.fn(async () => [historicalChunk]) + const { result } = renderHook(() => useWorkspaceCitationFocus({ fetchChunks, onSelectSource: vi.fn(), selectedSourceId: readySource.id, sources: [readySource], citationSources: [historicalSource] }), { wrapper: createSWRWrapper }) + await act(async () => { await result.current.handleCitationClick(historicalCitation, "message:0") }) + expect(fetchChunks).toHaveBeenCalledWith("demo-report", { jobResultId: "old", namespace: "__knowhere_demo__" }) + expect(result.current.selectedSource).toMatchObject({ id: "demo-report", jobResultId: "old" }) + expect(result.current.selectedChunks).toEqual([historicalChunk]) + expect(result.current.focusedChunk.chunkId).toBe("row_old") + act(() => { result.current.handleSourceSelected(readySource.id) }) + expect(result.current.selectedSource?.id).toBe(readySource.id) + }) + it("loads all chunks, selects the source, and focuses the cited chunk", async () => { const fetchChunks = vi.fn(async () => [prefetchedChunk]); const selectSource = vi.fn(); @@ -283,7 +315,7 @@ describe("useWorkspaceCitationFocus", () => { }; const cache = new Map([ [ - unstable_serialize(["source-chunks", "source_1", 1]), + unstable_serialize(["source-chunks", "source_1", 1, "", "", "page"]), { data: { chunks: [pageChunk], @@ -367,7 +399,7 @@ describe("useWorkspaceCitationFocus", () => { expect(fetchChunks).toHaveBeenCalledWith("source_1", { chunkType: "page" }); }); expect(result.current.prefetchedChunksBySourceId).toEqual({ - source_1: [pageChunk], + [JSON.stringify(["source_1", "", "", "page"])]: [pageChunk], }); }); diff --git a/src/components/workspace-citation-focus.ts b/src/components/workspace-citation-focus.ts index f12d2778..5fc4b3fb 100644 --- a/src/components/workspace-citation-focus.ts +++ b/src/components/workspace-citation-focus.ts @@ -39,6 +39,7 @@ type WorkspaceCitationFocusInput = { readonly onSelectSource: (sourceId: string | null) => void readonly selectedSourceId: string | null readonly sources: readonly SourceView[] + readonly citationSources?: readonly SourceView[] } type WorkspaceCitationFocus = { @@ -71,7 +72,11 @@ export function useWorkspaceCitationFocus({ onSelectSource, selectedSourceId, sources, + citationSources = [], }: WorkspaceCitationFocusInput): WorkspaceCitationFocus { + const [citationUnavailableMessage, setCitationUnavailableMessage] = useState(null) + const [citationSourceOverride, setCitationSourceOverride] = useState(null) + const effectiveSourceId = citationSourceOverride?.id ?? selectedSourceId const [focusedChunk, setFocusedChunk] = useState({ chunkId: null, requestId: 0, @@ -110,7 +115,8 @@ export function useWorkspaceCitationFocus({ selectedChunks, selectedSource, } = useWorkspaceSelectedChunks({ - selectedSourceId, + selectedSourceId: effectiveSourceId, + selectedSourceOverride: citationSourceOverride, sources, prefetchedChunksBySourceId, }) @@ -151,6 +157,8 @@ export function useWorkspaceCitationFocus({ const handleSourceSelected = useCallback( (sourceId: string | null): void => { + setCitationUnavailableMessage(null) + setCitationSourceOverride(null) onSelectSource(sourceId) if (sourceId && sourceId !== selectedSourceId) { fullChunkRequestedSourceIdsRef.current.delete(sourceId) @@ -175,8 +183,9 @@ export function useWorkspaceCitationFocus({ sourceId: string, options?: FetchChunksOptions, ): Promise => { + const readKey = workspaceClientCache.getSourceReadKey(sourceId, options) const existingRequest = - fullChunkRequestsBySourceIdRef.current.get(sourceId) + fullChunkRequestsBySourceIdRef.current.get(readKey) if (existingRequest) return existingRequest setFullChunkLoadingSourceId(sourceId) @@ -195,11 +204,11 @@ export function useWorkspaceCitationFocus({ : fetchChunks(sourceId) ) .then((chunks) => { - partialPrefetchSourceIdsRef.current.delete(sourceId) + partialPrefetchSourceIdsRef.current.delete(readKey) updatePrefetchedChunksBySourceId((current) => workspaceCitationState.upsertPrefetchedChunks( current, - sourceId, + readKey, chunks, ), ) @@ -209,45 +218,32 @@ export function useWorkspaceCitationFocus({ }, sourceId, chunks, + options, ) return chunks }) .finally(() => { - fullChunkRequestsBySourceIdRef.current.delete(sourceId) + fullChunkRequestsBySourceIdRef.current.delete(readKey) setFullChunkLoadingSourceId((current) => current === sourceId ? null : current, ) }) - fullChunkRequestsBySourceIdRef.current.set(sourceId, request) + fullChunkRequestsBySourceIdRef.current.set(readKey, request) return request }, [fetchChunks, mutate, sources, updatePrefetchedChunksBySourceId], ) const handleLoadAllChunks = useCallback((): void => { - if (!selectedSourceId) return - - const hasPartialPrefetch = - partialPrefetchSourceIdsRef.current.has(selectedSourceId) - if ( - !hasPartialPrefetch && - (prefetchedChunksBySourceIdRef.current[selectedSourceId] || - fullChunkRequestedSourceIdsRef.current.has(selectedSourceId) || - fullChunkRequestsBySourceIdRef.current.has(selectedSourceId)) - ) { - return - } - - fullChunkRequestedSourceIdsRef.current.add(selectedSourceId) - const source = sources.find((candidate) => candidate.id === selectedSourceId) - void loadAllChunksForSource( - selectedSourceId, - source?.documentPresentation?.kind === "page-assets" - ? { chunkType: "page" } - : undefined, - ) - }, [loadAllChunksForSource, selectedSourceId, sources]) + if (!selectedSource) return + const options: FetchChunksOptions = getSourceReadOptions(selectedSource) + const readKey = workspaceClientCache.getSourceReadKey(selectedSource.id, options) + if (!partialPrefetchSourceIdsRef.current.has(readKey) && + (prefetchedChunksBySourceIdRef.current[readKey] || fullChunkRequestedSourceIdsRef.current.has(readKey) || fullChunkRequestsBySourceIdRef.current.has(readKey))) return + fullChunkRequestedSourceIdsRef.current.add(readKey) + void loadAllChunksForSource(selectedSource.id, Object.keys(options).length ? options : undefined) + }, [loadAllChunksForSource, selectedSource]) const handleCitationClick = useCallback( async ( @@ -259,10 +255,27 @@ export function useWorkspaceCitationFocus({ try { const source = workspaceCitationState.findCitationSource( - sources, + [...citationSources, ...sources], citation, ) - if (!source) return + if (!source) { + const message = "This cited source revision is unavailable." + setCitationUnavailableMessage(message) + setCitationSourceOverride({ id: `unavailable:${citationId}`, title: citation.source.sourceFileName ?? "Cited source", mimeType: "application/octet-stream", status: "failed", failureMessage: message, documentId: citation.source.documentId ?? undefined }) + requestChunkFocus(null) + requestPageFocus(null) + return + } + setCitationUnavailableMessage(null) + const readOptions = getSourceReadOptions(source, citation) + const readKey = workspaceClientCache.getSourceReadKey(source.id, readOptions) + setCitationSourceOverride({ + ...source, + ...readOptions, + ...(source.kind === "demo" && source.demoSourceId && source.originalFile && readOptions.jobResultId + ? { originalFile: { ...source.originalFile, url: `/api/demo-sources/${encodeURIComponent(source.demoSourceId)}/original?job_result_id=${encodeURIComponent(readOptions.jobResultId)}` } } + : {}), + }) setCitationListViewRequestId((current) => current + 1) const pageNumber = workspaceCitationState.getCitationPageNumber(citation) @@ -287,7 +300,7 @@ export function useWorkspaceCitationFocus({ requestPageFocus(pageNumber, citationId, highlightRegions) } - if (selectedSourceId === source.id) { + if (effectiveSourceId === source.id) { const loadedChunkId = workspaceCitationState.getLoadedCitationChunkId({ citation, selectedSourceId, @@ -302,7 +315,7 @@ export function useWorkspaceCitationFocus({ } } - const prefetchedChunks = prefetchedChunksBySourceIdRef.current[source.id] + const prefetchedChunks = prefetchedChunksBySourceIdRef.current[readKey] if (prefetchedChunks) { const prefetchedChunkId = focusFromChunks(prefetchedChunks, false) if (prefetchedChunkId) { @@ -314,6 +327,7 @@ export function useWorkspaceCitationFocus({ const swrChunks = workspaceClientCache.getCachedSourceChunks( cache, source.id, + readOptions, ) if (swrChunks && swrChunks.length > 0) { const cachedChunkId = focusFromChunks(swrChunks, true) @@ -324,9 +338,9 @@ export function useWorkspaceCitationFocus({ } if (!workspaceCitationState.hasExactCitationTargetHint(citation)) { - fullChunkRequestedSourceIdsRef.current.delete(source.id) + fullChunkRequestedSourceIdsRef.current.delete(readKey) updatePrefetchedChunksBySourceId((current) => - workspaceCitationState.removePrefetchedChunks(current, source.id), + workspaceCitationState.removePrefetchedChunks(current, readKey), ) if (selectedSourceId !== source.id) onSelectSource(source.id) requestChunkFocus(null) @@ -337,22 +351,23 @@ export function useWorkspaceCitationFocus({ requestChunkFocus(null) const fetchOptions: FetchChunksOptions | undefined = isPageAssetSource ? { + ...readOptions, chunkType: "page", ...(pageNumber !== null ? { untilPageNumber: pageNumber } : {}), } - : undefined + : Object.keys(readOptions).length ? readOptions : undefined const chunks = isPageAssetSource && pageNumber !== null ? await fetchChunks(source.id, fetchOptions) : await loadAllChunksForSource(source.id, fetchOptions) if (isPageAssetSource && pageNumber !== null) { - if (!fullChunkRequestsBySourceIdRef.current.has(source.id)) { - partialPrefetchSourceIdsRef.current.add(source.id) + if (!fullChunkRequestsBySourceIdRef.current.has(readKey)) { + partialPrefetchSourceIdsRef.current.add(readKey) updatePrefetchedChunksBySourceId((current) => workspaceCitationState.upsertPrefetchedChunks( current, - source.id, + readKey, chunks, ), ) @@ -362,13 +377,23 @@ export function useWorkspaceCitationFocus({ }, source.id, chunks, + readOptions, ) } } - applyFocus( - focusFromChunks(chunks, false), - ) + const chunkId: string | null = focusFromChunks(chunks, false) + if (chunkId === null) { + setCitationUnavailableMessage("This cited source revision is unavailable.") + requestChunkFocus(null) + requestPageFocus(null) + return + } + applyFocus(chunkId) + } catch { + setCitationUnavailableMessage("This cited source revision is unavailable.") + requestChunkFocus(null) + requestPageFocus(null) } finally { setPendingCitationId((current) => current === citationId ? null : current, @@ -377,6 +402,8 @@ export function useWorkspaceCitationFocus({ }, [ cache, + citationSources, + effectiveSourceId, fetchChunks, hasMoreSelectedChunks, loadAllChunksForSource, @@ -400,13 +427,13 @@ export function useWorkspaceCitationFocus({ handleLoadMoreChunks, handleSourceSelected, hasMoreSelectedChunks, - isSelectedAllChunksLoading: fullChunkLoadingSourceId === selectedSourceId, + isSelectedAllChunksLoading: fullChunkLoadingSourceId === effectiveSourceId, isSelectedChunksLoading, isSelectedChunksLoadingMore, pendingCitationId, prefetchedChunksBySourceId, requestChunkFocus, - selectedChunksMessage, + selectedChunksMessage: citationUnavailableMessage ?? selectedChunksMessage, selectedChunks, selectedSource, } @@ -418,3 +445,13 @@ function resolveFocusHighlightRegions( if (highlightRegions && highlightRegions.length > 0) return highlightRegions return [] } + +function getSourceReadOptions(source: SourceView, citation?: ChatCitationView): FetchChunksOptions { + const jobResultId = citation?.source.jobResultId ?? source.jobResultId + const namespace = citation?.source.namespace ?? source.namespace + return { + ...(jobResultId ? { jobResultId } : {}), + ...(namespace ? { namespace } : {}), + ...(source.documentPresentation?.kind === "page-assets" ? { chunkType: "page" as const } : {}), + } +} diff --git a/src/components/workspace-citation-state.ts b/src/components/workspace-citation-state.ts index 03534090..298acb15 100644 --- a/src/components/workspace-citation-state.ts +++ b/src/components/workspace-citation-state.ts @@ -45,11 +45,13 @@ function findCitationSource( sources: readonly SourceView[], citation: ChatCitationView, ): SourceView | null { - return ( - sources.find( - (source) => source.documentId === citation.source.documentId, - ) ?? null + const matches = sources.filter((source) => + source.documentId === citation.source.documentId && + (!citation.source.namespace || source.namespace === citation.source.namespace), ) + const source = matches.find((candidate) => candidate.jobResultId === citation.source.jobResultId) ?? matches[0] + if (source?.namespace === "__knowhere_demo__" && !citation.source.jobResultId) return null + return source ?? null } function getLoadedCitationChunkId( @@ -69,6 +71,7 @@ function getLoadedCitationChunkId( } function hasExactCitationTargetHint(citation: ChatCitationView): boolean { + if (citation.chunkId || citation.chunkRowId) return true if (typeof citation.content === "string" && citation.content.trim().length > 0) { return true } @@ -117,7 +120,9 @@ function resolveCitationPageChunkId( if (pageNumber === null) return null const documentChunks = citation.source.documentId - ? chunks.filter((chunk) => chunk.documentId === citation.source.documentId) + ? chunks.filter((chunk) => chunk.documentId === citation.source.documentId && + (!citation.source.namespace || chunk.namespace === citation.source.namespace) && + (!citation.source.jobResultId || chunk.jobResultId === citation.source.jobResultId)) : chunks const matches = documentChunks.filter((chunk) => isChunkForPageNumber(chunk, pageNumber), diff --git a/src/components/workspace-selected-chunks.ts b/src/components/workspace-selected-chunks.ts index da357e2b..1ef98ebc 100644 --- a/src/components/workspace-selected-chunks.ts +++ b/src/components/workspace-selected-chunks.ts @@ -14,6 +14,7 @@ import type { ParsedChunkView } from "@/domains/chunks/types" import type { SourceView } from "@/domains/sources/types" type WorkspaceSelectedChunksInput = { + readonly selectedSourceOverride?: SourceView | null readonly selectedSourceId: string | null readonly sources: readonly SourceView[] readonly prefetchedChunksBySourceId: Readonly> @@ -31,24 +32,27 @@ type WorkspaceSelectedChunks = { export function useWorkspaceSelectedChunks({ selectedSourceId, + selectedSourceOverride, sources, prefetchedChunksBySourceId, }: WorkspaceSelectedChunksInput): WorkspaceSelectedChunks { const rawSelectedSource = sources.find( (source) => source.id === selectedSourceId, ) - const selectedSource = rawSelectedSource - const prefetchedSelectedChunks = selectedSourceId - ? prefetchedChunksBySourceId[selectedSourceId] + const selectedSource = selectedSourceOverride ?? rawSelectedSource + const readOptions = { + ...(selectedSource?.jobResultId ? { jobResultId: selectedSource.jobResultId } : {}), + ...(selectedSource?.namespace ? { namespace: selectedSource.namespace } : {}), + ...(selectedSource?.documentPresentation?.kind === "page-assets" ? { chunkType: "page" as const } : {}), + } + const selectedReadKey = selectedSource ? workspaceClientCache.getSourceReadKey(selectedSource.id, readOptions) : null + const prefetchedSelectedChunks = selectedReadKey + ? prefetchedChunksBySourceId[selectedReadKey] : undefined const selectedChunkSourceId = selectedSource && selectedSource.status === "ready" ? selectedSource.id : null - const pageChunkType = - selectedSource?.documentPresentation?.kind === "page-assets" - ? "page" - : undefined const { data: selectedChunkPages, isLoading: isChunksLoading, @@ -60,12 +64,11 @@ export function useWorkspaceSelectedChunks({ selectedChunkSourceId, pageIndex, previousPageData, + readOptions, ), - ([, sourceId, page]: SourceChunksKey) => - pageChunkType - ? workspaceClient.fetchChunkPage(sourceId, page, { - chunkType: pageChunkType, - }) + ([, sourceId, page, jobResultId, namespace, chunkType]: SourceChunksKey) => + jobResultId || namespace || chunkType + ? workspaceClient.fetchChunkPage(sourceId, page, readOptions) : workspaceClient.fetchChunkPage(sourceId, page), { revalidateIfStale: false, diff --git a/src/components/workspace-shell.test.ts b/src/components/workspace-shell.test.ts index 660471f6..a42c75ff 100644 --- a/src/components/workspace-shell.test.ts +++ b/src/components/workspace-shell.test.ts @@ -1220,24 +1220,24 @@ describe("WorkspaceShell", () => { expect(desktopSourcesPanel.queryByText("No sources yet.")).toBeNull(); }); - it("refreshes the active chat after adding an Official Library source", async () => { + it("selects a shared Official Library source without rewriting the active chat", async () => { const fetch = vi.fn(async (input, init) => { const request = input instanceof Request ? input : new Request(new URL(String(input), "http://localhost").toString(), init); const path = getRequestPath(request); - if (path === "/api/demo-sources/materialize" && request.method === "POST") { + if (path === "/api/demo-sources/select" && request.method === "POST") { return Response.json({ sources: [ { - id: "source_spacex", - kind: "workspace", + id: "demo-spacex-s1", + kind: "demo", title: "spacex-s1.pdf", status: "ready", mimeType: "application/pdf", demoSourceId: "demo-spacex-s1", - documentId: "doc_user_copy", + documentId: "ddoc_spacex", chunkCount: 1, }, ], @@ -1263,7 +1263,7 @@ describe("WorkspaceShell", () => { chunkType: "text", score: 0.91, source: { - documentId: "doc_user_copy", + documentId: "ddoc_spacex", sourceFileName: "spacex-s1.pdf", sectionPath: "Overview", }, @@ -1279,7 +1279,7 @@ describe("WorkspaceShell", () => { chunks: [ { chunkId: "source_spacex:chunk_1", - documentId: "doc_user_copy", + documentId: "ddoc_spacex", sectionPath: "Overview", type: "text", content: "User-copy cited section", @@ -1380,8 +1380,8 @@ describe("WorkspaceShell", () => { ); const desktopChatPanel = within(screen.getByTestId("desktop-chat-panel")); - await desktopChatPanel.findByText("Refreshed materialized answer."); - expect(desktopChatPanel.queryByText("Seeded canonical answer.")).toBeNull(); + expect(desktopChatPanel.getByText("Seeded canonical answer.")).toBeTruthy(); + expect(desktopChatPanel.queryByText("Refreshed materialized answer.")).toBeNull(); const refreshedLibraryPanel = within( within(screen.getByTestId("desktop-chunks-panel")).getByTestId( "official-library-panel", @@ -1397,7 +1397,7 @@ describe("WorkspaceShell", () => { name: "Add spacex-s1.pdf to sources", }), ).toBeNull(); - expect(countFetches(fetch, "/api/chat/threads/thread_1")).toBe(1); + expect(countFetches(fetch, "/api/chat/threads/thread_1")).toBe(0); }); it("uses cached chat data when reopening a previously loaded thread", async () => { diff --git a/src/components/workspace-shell.tsx b/src/components/workspace-shell.tsx index 3c218027..bf0f230e 100644 --- a/src/components/workspace-shell.tsx +++ b/src/components/workspace-shell.tsx @@ -57,6 +57,7 @@ export type WorkspaceShellProps = { chatThreads?: ChatThreadView[] activeChatThreadId?: string | null chatMessages?: ChatMessageView[] + citationSources?: SourceView[] chunkViewDocumentId?: string | null dashboardUrl?: string initialPrefetchedChunksBySourceId?: Record @@ -88,6 +89,7 @@ function WorkspaceShellContent({ chatThreads: initialChatThreads, activeChatThreadId, chatMessages: initialChatMessages, + citationSources: initialCitationSources, chunkViewDocumentId, dashboardUrl, workspace, @@ -119,24 +121,25 @@ function WorkspaceShellContent({ }), [isGuest, user?.id, workspace?.id, workspace?.namespace], ) - const citationFocus = useWorkspaceCitationFocus({ - fetchChunks: workspaceClient.fetchChunks, - initialPrefetchedChunksBySourceId: - initialPrefetchedChunksBySourceId ?? undefined, - onSelectSource: handleCitationSourceSelected, - selectedSourceId: sourceWorkflow.selectedSourceId, - sources: sourceWorkflow.sources, - }) const chatWorkflow = useWorkspaceChatWorkflow({ activeChatThreadId: activeChatThreadId ?? null, analyticsContext, initialChatMessages: initialChatMessages ?? [], initialChatThreads: initialChatThreads ?? [], + initialCitationSources: initialCitationSources ?? [], isGuest, - onSourcesMaterialized: sourceWorkflow.handleSourcesMaterialized, sources: sourceWorkflow.sources, currentFolderId: folderWorkflow.currentFolderId, }) + const citationFocus = useWorkspaceCitationFocus({ + fetchChunks: workspaceClient.fetchChunks, + initialPrefetchedChunksBySourceId: + initialPrefetchedChunksBySourceId ?? undefined, + onSelectSource: handleCitationSourceSelected, + selectedSourceId: sourceWorkflow.selectedSourceId, + sources: sourceWorkflow.sources, + citationSources: chatWorkflow.citationSources, + }) const { desktopPanelWidths, minimumDesktopPanelWidth, @@ -167,11 +170,7 @@ function WorkspaceShellContent({ async function handleOfficialLibrarySourceAdd( demoSourceId: string, ): Promise { - const didMaterialize = - await sourceWorkflow.handleOfficialLibrarySourceAdd(demoSourceId) - if (didMaterialize) { - await chatWorkflow.handleRefreshActiveChatThread() - } + await sourceWorkflow.handleOfficialLibrarySourceAdd(demoSourceId) } function handleLibraryOpen(): void { diff --git a/src/components/workspace-source-workflow.test.ts b/src/components/workspace-source-workflow.test.ts index c0414f58..89c65f41 100644 --- a/src/components/workspace-source-workflow.test.ts +++ b/src/components/workspace-source-workflow.test.ts @@ -9,7 +9,7 @@ import type { SourceView } from "@/domains/sources/types" const mocks = vi.hoisted(() => ({ archiveSource: vi.fn(), fetchSources: vi.fn(), - materializeDemoSources: vi.fn(), + selectDemoSources: vi.fn(), retrySource: vi.fn(), })) @@ -17,13 +17,13 @@ vi.mock("@/domains/workspace/client", () => ({ workspaceClient: { keys: { archiveSource: "archive-source", - materializeDemoSources: "/api/demo-sources/materialize", + selectDemoSources: "/api/demo-sources/select", retrySource: "retry-source", sources: "/api/sources", }, archiveSource: mocks.archiveSource, fetchSources: mocks.fetchSources, - materializeDemoSources: mocks.materializeDemoSources, + selectDemoSources: mocks.selectDemoSources, retrySource: mocks.retrySource, }, })) @@ -170,7 +170,7 @@ describe("useWorkspaceSourceWorkflow", () => { }) }) - it("materializes one Official Library source through the workflow", async () => { + it("selects one shared Official Library source through the workflow", async () => { const demoSource = makeSource({ id: "demo-spacex-s1", kind: "demo", @@ -183,14 +183,14 @@ describe("useWorkspaceSourceWorkflow", () => { }, }) const materializedSource = makeSource({ - id: "source_spacex", - kind: "workspace", + id: "demo-spacex-s1", + kind: "demo", demoSourceId: "demo-spacex-s1", title: "spacex-s1.pdf", documentId: "doc_spacex", }) mocks.fetchSources.mockResolvedValue([demoSource]) - mocks.materializeDemoSources.mockResolvedValue([materializedSource]) + mocks.selectDemoSources.mockResolvedValue([materializedSource]) const { result } = renderWorkspaceSourceWorkflow({ initialSources: [demoSource], @@ -203,16 +203,16 @@ describe("useWorkspaceSourceWorkflow", () => { ).resolves.toBe(true) }) - expect(mocks.materializeDemoSources).toHaveBeenCalledWith({ + expect(mocks.selectDemoSources).toHaveBeenCalledWith({ demoSourceIds: ["demo-spacex-s1"], }) expect(result.current.sources.map((source) => source.id)).toEqual([ - "source_spacex", + "demo-spacex-s1", ]) expect(result.current.sources[0]).toMatchObject({ demoSourceId: "demo-spacex-s1", }) - expect(result.current.selectedSourceId).toBe("source_spacex") + expect(result.current.selectedSourceId).toBe("demo-spacex-s1") }) it("does not count unmaterialized Official Library sources as chat-ready", () => { @@ -236,7 +236,7 @@ describe("useWorkspaceSourceWorkflow", () => { expect(result.current.readySourceCount).toBe(0) }) - it("reports failed Official Library materialization without changing sources", async () => { + it("reports failed Official Library selection without changing sources", async () => { const demoSource = makeSource({ id: "demo-spacex-s1", kind: "demo", @@ -244,7 +244,7 @@ describe("useWorkspaceSourceWorkflow", () => { title: "spacex-s1.pdf", }) mocks.fetchSources.mockResolvedValue([demoSource]) - mocks.materializeDemoSources.mockRejectedValue(new Error("Bad gateway")) + mocks.selectDemoSources.mockRejectedValue(new Error("Bad gateway")) const { result } = renderWorkspaceSourceWorkflow({ initialSources: [demoSource], diff --git a/src/components/workspace-source-workflow.ts b/src/components/workspace-source-workflow.ts index 64bb3998..f8c97fb0 100644 --- a/src/components/workspace-source-workflow.ts +++ b/src/components/workspace-source-workflow.ts @@ -23,9 +23,9 @@ type WorkspaceSourceWorkflow = { readonly handleOfficialLibrarySourceAdd: (demoSourceId: string) => Promise readonly handleSelectedSourceChange: (sourceId: string | null) => void readonly handleSourcesRefresh: () => void - readonly handleSourcesMaterialized: ( + readonly handleSourcesSelected: ( demoSourceIds: readonly string[], - materializedSources: readonly SourceView[], + selectedSources: readonly SourceView[], ) => void readonly handleSourceUploaded: (source: SourceView) => void readonly handleSourceMoved: (source: SourceView) => void @@ -41,7 +41,7 @@ type WorkspaceSourceWorkflow = { const sourcesSWRKey = workspaceClient.keys.sources const archiveSourceSWRKey = workspaceClient.keys.archiveSource const retrySourceSWRKey = workspaceClient.keys.retrySource -const materializeDemoSourceSWRKey = workspaceClient.keys.materializeDemoSources +const selectDemoSourceSWRKey = workspaceClient.keys.selectDemoSources export function useWorkspaceSourceWorkflow({ initialSelectedDocumentId = null, @@ -105,9 +105,9 @@ export function useWorkspaceSourceWorkflow({ retrySourceSWRKey, retrySourceMutation, ) - const { trigger: materializeDemoSources } = useSWRMutation( - materializeDemoSourceSWRKey, - materializeDemoSourcesMutation, + const { trigger: selectDemoSources } = useSWRMutation( + selectDemoSourceSWRKey, + selectDemoSourcesMutation, ) function handleSourceMoved(source: SourceView): void { @@ -127,25 +127,25 @@ export function useWorkspaceSourceWorkflow({ void mutateSources() } - function handleSourcesMaterialized( + function handleSourcesSelected( demoSourceIds: readonly string[], - materializedSources: readonly SourceView[], + selectedSources: readonly SourceView[], ): void { - const materializedDemoSourceIdSet = new Set(demoSourceIds) + const selectedDemoSourceIdSet = new Set(demoSourceIds) void mutateSources( (current) => [ ...(current ?? sourceRows).filter( (source) => !source.demoSourceId || - !materializedDemoSourceIdSet.has(source.demoSourceId), + !selectedDemoSourceIdSet.has(source.demoSourceId), ), - ...materializedSources, + ...selectedSources, ], { revalidate: false }, ) setSelectedSourceId((current) => { - if (!current || materializedDemoSourceIdSet.has(current)) { - return materializedSources[0]?.id ?? current + if (!current || selectedDemoSourceIdSet.has(current)) { + return selectedSources[0]?.id ?? current } return current @@ -231,11 +231,11 @@ export function useWorkspaceSourceWorkflow({ workspaceSourceState.addPendingId(current, demoSourceId), ) try { - const materializedSources = await materializeDemoSources([demoSourceId]) - handleSourcesMaterialized([demoSourceId], materializedSources) + const selectedSources = await selectDemoSources([demoSourceId]) + handleSourcesSelected([demoSourceId], selectedSources) return true } catch { - // Keep the library source visible when materialization fails. + // Keep the library source visible when selection fails. return false } finally { setAddingLibrarySourceIds((current) => @@ -252,7 +252,7 @@ export function useWorkspaceSourceWorkflow({ handleOfficialLibrarySourceAdd, handleSelectedSourceChange, handleSourcesRefresh, - handleSourcesMaterialized, + handleSourcesSelected, handleSourceUploaded, handleSourceMoved, handleToggleIncluded, @@ -293,11 +293,11 @@ function retrySourceMutation( return workspaceClient.retrySource(sourceId) } -function materializeDemoSourcesMutation( +function selectDemoSourcesMutation( _key: string, { arg: demoSourceIds }: { readonly arg: readonly string[] }, -): ReturnType { - return workspaceClient.materializeDemoSources({ +): ReturnType { + return workspaceClient.selectDemoSources({ demoSourceIds: [...demoSourceIds], }) } diff --git a/src/domains/chat/agent-trace.ts b/src/domains/chat/agent-trace.ts index ece42728..a34cd6fa 100644 --- a/src/domains/chat/agent-trace.ts +++ b/src/domains/chat/agent-trace.ts @@ -1,3 +1,4 @@ +import type { RetrievalWarning } from "./types" import type { HarnessTrace } from "@/agent-harness" export const RECENT_CONTEXT_TURN_LIMIT = 5 @@ -12,6 +13,7 @@ export type ChatAgentTrace = { readonly intentTask: string readonly toolCalls: readonly ChatAgentTraceToolCall[] readonly referencedDocumentIds: readonly string[] + readonly retrievalWarnings?: readonly RetrievalWarning[] } export type RecentCaptureContextTurn = { @@ -105,6 +107,7 @@ export function readChatAgentTrace(value: unknown): ChatAgentTrace | undefined { intentTask: value.intentTask, toolCalls, referencedDocumentIds, + ...(Array.isArray(value.retrievalWarnings) ? { retrievalWarnings: value.retrievalWarnings.filter(isRetrievalWarning) } : {}), } } @@ -123,3 +126,8 @@ function collectReferencedDocumentIds(trace: HarnessTrace): string[] { function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null } + +function isRetrievalWarning(value: unknown): value is RetrievalWarning { + return isRecord(value) && (value.scope === "demo" || value.scope === "workspace") && + typeof value.code === "string" && typeof value.message === "string" +} diff --git a/src/domains/chat/chat-citation-persistence.ts b/src/domains/chat/chat-citation-persistence.ts index d48281dc..4db20820 100644 --- a/src/domains/chat/chat-citation-persistence.ts +++ b/src/domains/chat/chat-citation-persistence.ts @@ -15,10 +15,7 @@ type ChatCitationPersistence = { readonly normalizeArtifacts: ( artifacts: readonly ChatArtifactView[] | null | undefined, ) => ChatArtifactView[] | null - readonly replaceDemoCitationDocumentId: ( - citations: readonly ChatCitationView[] | undefined, - documentIdMap: ReadonlyMap, - ) => ChatCitationView[] | undefined + } function normalizeCitations( @@ -58,34 +55,14 @@ function toArtifactView(artifact: ChatArtifactView): ChatArtifactView { } } -function replaceDemoCitationDocumentId( - citations: readonly ChatCitationView[] | undefined, - documentIdMap: ReadonlyMap, -): ChatCitationView[] | undefined { - if (!citations) return undefined - - return citations.map((citation) => { - const newId = citation.source.documentId - ? documentIdMap.get(citation.source.documentId) - : undefined - if (!newId) return citation - - return { - ...citation, - source: { - ...citation.source, - documentId: newId, - }, - } - }) -} - function toCitationView( citation: ChatCitationView | CitationView | RetrievalResultView, ): CitationView { const highlightRegions = "highlightRegions" in citation ? citation.highlightRegions : undefined return { + chunkId: citation.chunkId, + chunkRowId: citation.chunkRowId, chunkType: citation.chunkType, score: citation.score, assetUrl: citation.assetUrl, @@ -97,6 +74,8 @@ function toCitationView( : {}), source: { documentId: citation.source.documentId, + namespace: citation.source.namespace, + jobResultId: citation.source.jobResultId, sourceFileName: citation.source.sourceFileName, sectionPath: citation.source.sectionPath, }, @@ -106,5 +85,4 @@ function toCitationView( export const chatCitationPersistence: ChatCitationPersistence = { normalizeCitations, normalizeArtifacts, - replaceDemoCitationDocumentId, } diff --git a/src/domains/chat/citation-source-revision.ts b/src/domains/chat/citation-source-revision.ts new file mode 100644 index 00000000..d3c8b269 --- /dev/null +++ b/src/domains/chat/citation-source-revision.ts @@ -0,0 +1,27 @@ +import type { ChatSource } from "./contracts" + +/** Bind an asset read to retrieval provenance instead of the latest catalog. */ +export function bindCitationSourceRevision( + source: ChatSource, + reference: unknown, + metadata?: Readonly>, +): ChatSource | null { + const fields = isRecord(reference) ? reference : {} + const namespace = getString(fields.namespace) ?? getString(metadata?.namespace) + const jobResultId = getString(fields.jobResultId) ?? getString(metadata?.jobResultId) + if (namespace && source.namespace && namespace !== source.namespace) return null + if (source.namespace === "__knowhere_demo__" && !jobResultId) return null + return { + ...source, + ...(namespace ? { namespace } : {}), + ...(jobResultId ? { jobResultId, knowhereJobId: jobResultId } : {}), + } +} + +function getString(value: unknown): string | undefined { + return typeof value === "string" && value.trim() ? value : undefined +} + +function isRecord(value: unknown): value is Readonly> { + return typeof value === "object" && value !== null +} diff --git a/src/domains/chat/citation-sources.test.ts b/src/domains/chat/citation-sources.test.ts new file mode 100644 index 00000000..c2417bb7 --- /dev/null +++ b/src/domains/chat/citation-sources.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest" +import { resolveCitationSources } from "./citation-sources" +import type { Source } from "@/infrastructure/db/schema" +import type { DemoCatalog } from "@/integrations/knowhere-demo" +import type { ChatMessageView } from "./types" + +const catalog: DemoCatalog = { sources: [{ demoSourceId: "demo-report", canonicalDocumentId: "shared_doc", namespace: "__knowhere_demo__", jobResultId: "current", title: "Report", mimeType: "application/pdf", sizeBytes: 1, status: "ready", chunkCount: 1, originalFile: { url: "/demo", mimeType: "application/pdf", sizeBytes: 1, canDownload: false }, examples: [] }], officialLibrary: { categories: [], sources: [] } } +function makeMessages(documentId: string, namespace?: string, jobResultId?: string): ChatMessageView[] { + return [{ id: "m", role: "assistant", content: "Answer", citations: [{ chunkType: "text", score: 1, source: { documentId, namespace, jobResultId } }] }] +} + +describe("resolveCitationSources", () => { + it("returns hidden shared source metadata at the saved revision", () => { + expect(resolveCitationSources({ messages: makeMessages("shared_doc", "__knowhere_demo__", "saved"), sources: [], catalog, namespace: "personal" })).toMatchObject([{ id: "demo-report", documentId: "shared_doc", jobResultId: "saved", namespace: "__knowhere_demo__" }]) + expect(resolveCitationSources({ messages: makeMessages("shared_doc", "__knowhere_demo__", "saved"), sources: [], catalog, namespace: "personal" })[0]?.originalFile?.url).toContain("job_result_id=saved") + }) + it("uses the compatible actual private namespace from a saved citation", () => { + const source = { id: "private", knowhereDocumentId: "private_doc", title: "Report", mimeType: "application/pdf", status: "ready", knowhereJobId: "job" } as Source + expect(resolveCitationSources({ messages: makeMessages("private_doc", "default", "saved"), sources: [source], catalog, namespace: "notebook-personal" })).toMatchObject([{ id: "private", namespace: "default", jobResultId: "saved" }]) + expect(resolveCitationSources({ messages: makeMessages("private_doc", "other-tenant", "saved"), sources: [source], catalog, namespace: "notebook-personal" })).toEqual([]) + }) + it("does not redirect unresolved old demo document identifiers to the shared corpus", () => { + expect(resolveCitationSources({ messages: makeMessages("old_static_doc"), sources: [], catalog, namespace: "personal" })).toEqual([]) + }) + it("resolves private legacy rows using their actual document and namespace", () => { + const source = { id: "legacy", knowhereDocumentId: "private_doc", title: "Report", mimeType: "application/pdf", status: "ready", demoKey: "demo-report", knowhereJobId: "job" } as Source + expect(resolveCitationSources({ messages: makeMessages("private_doc"), sources: [source], catalog, namespace: "personal" })).toMatchObject([{ id: "legacy", documentId: "private_doc", namespace: "personal", kind: "workspace" }]) + }) +}) diff --git a/src/domains/chat/citation-sources.ts b/src/domains/chat/citation-sources.ts new file mode 100644 index 00000000..d3ffa25b --- /dev/null +++ b/src/domains/chat/citation-sources.ts @@ -0,0 +1,47 @@ +import { demoView } from "@/domains/demo/view" +import { getCompatibleNamespaces } from "@/domains/sources/namespace" +import { toSourceView } from "@/domains/sources/view" +import type { Source } from "@/infrastructure/db/schema" +import type { SourceView } from "@/domains/sources/types" +import type { DemoCatalog } from "@/integrations/knowhere-demo" +import type { ChatMessageView } from "./types" + +type CitationSourcesInput = { + readonly messages: readonly ChatMessageView[] + readonly sources: readonly Source[] + readonly catalog: DemoCatalog | null + readonly namespace: string +} + +export function resolveCitationSources(input: CitationSourcesInput): SourceView[] { + const citations = input.messages.flatMap((message) => [ + ...(message.citations ?? []), + ...(message.artifacts ?? []).flatMap((artifact) => artifact.citation ? [artifact.citation] : []), + ]) + const resolved = new Map() + for (const citation of citations) { + const reference = citation.source + if (!reference.documentId) continue + const localSource = input.sources.find((source) => + source.knowhereDocumentId === reference.documentId && + (!reference.namespace || getCompatibleNamespaces({ namespace: input.namespace }).includes(reference.namespace)), + ) + const sharedSource = input.catalog?.sources.find((source) => + source.canonicalDocumentId === reference.documentId && + (!reference.namespace || source.namespace === reference.namespace), + ) + const source = localSource + ? { ...toSourceView(localSource), namespace: reference.namespace ?? input.namespace } + : sharedSource ? demoView.toSourceView({ ...sharedSource, ...(reference.jobResultId ? { jobResultId: reference.jobResultId } : {}) }) : undefined + if (!source) continue + // A shared citation without an immutable revision cannot identify the + // original evidence safely, even when its document is still in the catalog. + if (!localSource && !reference.jobResultId && source.namespace) continue + const view: SourceView = { + ...source, + ...(reference.jobResultId ? { jobResultId: reference.jobResultId } : {}), + } + resolved.set(JSON.stringify([view.id, view.namespace, view.jobResultId]), view) + } + return [...resolved.values()] +} diff --git a/src/domains/chat/citations.ts b/src/domains/chat/citations.ts index 18304aa4..36ce9014 100644 --- a/src/domains/chat/citations.ts +++ b/src/domains/chat/citations.ts @@ -1,6 +1,6 @@ import type { RetrievalResult } from "@ontos-ai/knowhere-sdk" -import type { Source } from "@/infrastructure/db/schema" +import type { ChatSource } from "./contracts" import type { ChatCitationView } from "@/domains/chat/types" import { resolvePageCitationPageNumber, @@ -21,6 +21,7 @@ export function toChatCitationViews( chunkType: result.chunkType, score: result.score, ...(result.chunkId ? { chunkId: result.chunkId } : {}), + ...(result.chunkRowId ? { chunkRowId: result.chunkRowId } : {}), ...(result.assetUrl ? { assetUrl: result.assetUrl } : {}), ...(result.pageCitationAssetUrl ? { pageCitationAssetUrl: result.pageCitationAssetUrl } @@ -34,6 +35,8 @@ export function toChatCitationViews( : {}), source: { documentId: result.source.documentId, + ...(getProvenanceString(result.source.namespace ?? result.metadata?.namespace) ? { namespace: getProvenanceString(result.source.namespace ?? result.metadata?.namespace) } : {}), + ...(getProvenanceString(result.source.jobResultId ?? result.metadata?.jobResultId) ? { jobResultId: getProvenanceString(result.source.jobResultId ?? result.metadata?.jobResultId) } : {}), sourceFileName: result.source.sourceFileName, sectionPath: result.source.sectionPath, }, @@ -43,7 +46,7 @@ export function toChatCitationViews( export function useNotebookSourceTitles( results: readonly RetrievalResult[], - sources: readonly Source[], + sources: readonly ChatSource[], ): RetrievalResult[] { const sourceTitlesByDocumentId = new Map( sources.flatMap((source): readonly [string, string][] => @@ -91,3 +94,7 @@ function getCitationDescriptions(answer: string): Map { return descriptions } + +function getProvenanceString(value: unknown): string | undefined { + return typeof value === "string" && value.trim() ? value : undefined +} diff --git a/src/domains/chat/connected-assets.ts b/src/domains/chat/connected-assets.ts index fa5c7dd0..6fbe8ad2 100644 --- a/src/domains/chat/connected-assets.ts +++ b/src/domains/chat/connected-assets.ts @@ -48,7 +48,7 @@ function groupLookups( ): Map { const groups = new Map() for (const lookup of lookups) { - const key = `${lookup.documentId}\u0000${lookup.type}` + const key = `${lookup.documentId}\u0000${lookup.jobResultId ?? ""}\u0000${lookup.namespace ?? ""}\u0000${lookup.type}` const group = groups.get(key) ?? [] group.push(lookup) groups.set(key, group) @@ -74,6 +74,7 @@ async function resolveLookupGroup( pageSize: documentChunkApiMaximumPageSize, chunkType: first.type, includeAssetUrls: true, + ...(first.jobResultId ? { jobResultId: first.jobResultId } : {}), }) totalPages = response.pagination.totalPages @@ -87,6 +88,8 @@ async function resolveLookupGroup( } resolved.push({ documentId: first.documentId, + ...(first.jobResultId ? { jobResultId: first.jobResultId } : {}), + ...(first.namespace ? { namespace: first.namespace } : {}), chunkId: chunk.chunkId, type: first.type, assetUrl, @@ -101,5 +104,5 @@ async function resolveLookupGroup( } function lookupKey(lookup: ConnectedAssetLookup): string { - return `${lookup.documentId}\u0000${lookup.type}\u0000${lookup.chunkId}` + return `${lookup.documentId}\u0000${lookup.jobResultId ?? ""}\u0000${lookup.namespace ?? ""}\u0000${lookup.type}\u0000${lookup.chunkId}` } diff --git a/src/domains/chat/contracts.ts b/src/domains/chat/contracts.ts index 282688c3..e6b50d0b 100644 --- a/src/domains/chat/contracts.ts +++ b/src/domains/chat/contracts.ts @@ -15,10 +15,24 @@ import type { ChatAgentTrace } from "./agent-trace" import type { ChatArtifactView, ChatCitationView, + RetrievalWarning, } from "@/domains/chat/types" import type { HardenMediaAssetUrls } from "./media-asset-hardening" import type { HardenChatAssetUrl } from "./media-assets" +export type ChatSource = Pick< + Source, + "id" | "title" | "status" | "knowhereDocumentId" | "knowhereJobId" | "demoKey" | "mimeType" +> & { + readonly namespace?: string + readonly jobResultId?: string +} + +export type RetrievalPreparationFailure = { + readonly warning: RetrievalWarning + readonly cause: unknown +} + export type RetrievalClient = { query(params: RetrievalQueryParams): Promise } @@ -55,7 +69,7 @@ export type SearchSources = ( export type GenerateAnswer = (input: { question: string messages: readonly ChatHistoryMessage[] - sources: readonly Source[] + sources: readonly ChatSource[] excludedSourceIds: readonly string[] folderScopeSourceIds?: readonly string[] searchSources: SearchSources @@ -68,7 +82,7 @@ export type AnswerQuestionInput = { workspaceId?: string namespace: string namespaces?: readonly string[] - sources: readonly Source[] + sources: readonly ChatSource[] excludedSourceIds: readonly string[] folderScopeSourceIds?: readonly string[] useAgentic?: boolean @@ -79,6 +93,8 @@ export type AnswerQuestionInput = { hardenMediaAssetUrls?: HardenMediaAssetUrls resolveConnectedAssets?: ResolveConnectedAssets messages: readonly ChatHistoryMessage[] + retrievalPreparationFailures?: readonly RetrievalPreparationFailure[] + excludedWorkspaceDemoDocumentIds?: readonly string[] } export type AnswerQuestionResult = { @@ -86,4 +102,5 @@ export type AnswerQuestionResult = { citations: ChatCitationView[] artifacts?: ChatArtifactView[] agentTrace: ChatAgentTrace + retrievalWarnings?: readonly RetrievalWarning[] } diff --git a/src/domains/chat/index.test.ts b/src/domains/chat/index.test.ts index c2041b5a..29b27a4c 100644 --- a/src/domains/chat/index.test.ts +++ b/src/domains/chat/index.test.ts @@ -443,7 +443,7 @@ describe("answerQuestionWithRetrieval", () => { topK: 2, }); - expect(searchResponse.results).toEqual([result]); + expect(searchResponse.results).toMatchObject([result]); return makeHarnessRunResult("Runtime answer."); }, ); @@ -2302,7 +2302,7 @@ describe("answerQuestionWithRetrieval", () => { expect(generateCallCount).toBe(1); expect(answer.answer).toBe("Information hiding is a module design principle."); expect(answer.artifacts).toEqual([]); - expect(answer.citations.map((citation) => citation.source)).toEqual([ + expect(answer.citations.map((citation) => citation.source)).toMatchObject([ { documentId: "doc_information_hiding", sourceFileName: "information_hiding.pdf", diff --git a/src/domains/chat/index.ts b/src/domains/chat/index.ts index 2cf563ea..fad18f98 100644 --- a/src/domains/chat/index.ts +++ b/src/domains/chat/index.ts @@ -12,6 +12,7 @@ import type { ChatArtifactView, ChatCitationView, ChatImageHighlightBox, + RetrievalWarning, } from "@/domains/chat/types" import type { DerivedTableArtifact, @@ -48,6 +49,7 @@ import { } from "./page-citation-assets" import type { HardenableRetrievalResult } from "./media-asset-hardening" import { notebookKnowhereTools } from "./knowhere-tools" +import { decodeNotebookRetrievalResponse } from "./retrieval-response" import { toChatAgentTrace } from "./agent-trace" import { listActivations } from "@/integrations/memento/client" import { @@ -149,6 +151,8 @@ export const answerQuestionWithRetrieval = ( Effect.gen(function* () { const question = input.question.trim() const retrievalResponses: RetrievalQueryResponse[] = [] + const retrievalWarnings: RetrievalWarning[] = input.retrievalPreparationFailures?.map((failure) => failure.warning) ?? [] + const retrievalFailures: unknown[] = input.retrievalPreparationFailures?.map((failure) => failure.cause) ?? [] logger.info("chat-agent: answer start", { questionLength: question.length, @@ -222,6 +226,13 @@ export const answerQuestionWithRetrieval = ( queryResponses.push(outcome.response) } else { queryFailures.push(outcome.error) + retrievalFailures.push(outcome.error) + const scope: RetrievalWarning["scope"] = outcome.namespace === "__knowhere_demo__" ? "demo" : "workspace" + if (!retrievalWarnings.some((warning) => warning.scope === scope)) { + retrievalWarnings.push({ scope, code: "retrieval_failed", message: scope === "demo" + ? "Demo sources could not be searched. The answer uses available sources." + : "Workspace sources could not be searched. The answer uses available sources." }) + } } } @@ -233,6 +244,7 @@ export const answerQuestionWithRetrieval = ( rateLimitFallbackCount: rateLimitedOutcomes.length, }) + if (finalOutcomes.length === 0) return emptyRetrievalResponse(question, retrievalPlan) if (queryResponses.length === 0) throw queryFailures[0] if ( queryFailures.length > 0 && @@ -273,6 +285,10 @@ export const answerQuestionWithRetrieval = ( }), ) + if (retrievalFailures.length > 0 && !retrievalResponses.some(hasRetrievalEvidence)) { + return yield* Effect.die(retrievalFailures[0]) + } + logger.info("chat-agent: answer generated", { answerLength: generatedAnswer.manifest.text.length, retrievalCallCount: retrievalResponses.length, @@ -347,7 +363,9 @@ export const answerQuestionWithRetrieval = ( answer, citations: toChatCitationViews(hardenedMedia.results, answer), artifacts: displayArtifacts, - agentTrace: toChatAgentTrace(generatedAnswer.trace), + agentTrace: { ...toChatAgentTrace(generatedAnswer.trace), + ...(retrievalWarnings.length > 0 ? { retrievalWarnings } : {}) }, + ...(retrievalWarnings.length > 0 ? { retrievalWarnings } : {}), } }) @@ -454,6 +472,8 @@ function normalizeHarnessSource( return { documentId: source.documentId, + ...(source.namespace ? { namespace: source.namespace } : {}), + ...(source.jobResultId ? { jobResultId: source.jobResultId } : {}), sourceFileName: sourceTitle ?? source.sourceFileName, sectionPath: source.sectionPath, } @@ -685,7 +705,12 @@ function queryRetrievalNamespaces(input: { }): Promise { return Effect.runPromise( Effect.all( - input.namespaces.map((namespace) => + input.namespaces.filter((namespace) => { + const scope = getRetrievalDocumentScope(input.answerInput.sources, input.answerInput.excludedSourceIds, + input.queryInput, input.answerInput.folderScopeSourceIds, namespace, input.answerInput.excludedWorkspaceDemoDocumentIds) + if (namespace !== "__knowhere_demo__" && input.answerInput.folderScopeSourceIds === undefined && input.queryInput.includeDocumentIds?.length === 0) return true + return scope.includeDocumentIds === undefined || scope.includeDocumentIds.some((documentId) => !scope.excludeDocumentIds?.includes(documentId)) + }).map((namespace) => Effect.promise(() => queryRetrievalNamespace({ namespace, @@ -719,6 +744,7 @@ async function queryRetrievalNamespace(input: { sources: input.answerInput.sources, excludedSourceIds: input.answerInput.excludedSourceIds, folderScopeSourceIds: input.answerInput.folderScopeSourceIds, + excludedWorkspaceDemoDocumentIds: input.answerInput.excludedWorkspaceDemoDocumentIds, }) logger.info("chat-agent: searchSources start", { namespace: input.namespace, @@ -735,7 +761,7 @@ async function queryRetrievalNamespace(input: { }) try { - const response = await input.answerInput.retrieval.query(retrievalQueryParams) + const response = decodeNotebookRetrievalResponse(await input.answerInput.retrieval.query(retrievalQueryParams)) logger.info("chat-agent: searchSources ok", { namespace: input.namespace, query: response.query, @@ -809,13 +835,16 @@ function getUnknownProperty(value: unknown, key: string): unknown { } function getRetrievalNamespaces(input: AnswerQuestionInput): readonly string[] { + const excludedSourceIds: ReadonlySet = new Set(input.excludedSourceIds) + const hasWorkspaceSources: boolean = input.sources.some((source) => !source.demoKey && source.status === "ready" && Boolean(source.knowhereDocumentId) && !excludedSourceIds.has(source.id)) + const hasDemoSources: boolean = input.folderScopeSourceIds === undefined && input.sources.some((source) => source.namespace === "__knowhere_demo__" && source.status === "ready" && Boolean(source.knowhereDocumentId) && !excludedSourceIds.has(source.id)) const candidates = input.namespaces && input.namespaces.length > 0 ? input.namespaces : [input.namespace] const namespaces: string[] = [] - for (const namespace of candidates) { + for (const namespace of [...(hasWorkspaceSources ? candidates.filter((candidate) => candidate !== "__knowhere_demo__") : []), ...(hasDemoSources ? ["__knowhere_demo__"] : [])]) { if (namespaces.includes(namespace)) continue namespaces.push(namespace) } @@ -916,6 +945,11 @@ function mergeRetrievalResponses( } } +function emptyRetrievalResponse(query: string, retrievalPlan: AgenticRetrievalPlan): AgenticRetrievalResponse { + return { namespace: "", query, routerUsed: "notebook_empty_scope", answerText: null, + evidenceText: null, results: [], referencedChunks: [], retrievalPlan } +} + function getAgenticMergedEvidenceLimits(input: { readonly namespaceCount: number readonly topK: number | undefined @@ -952,7 +986,7 @@ function hasRetrievalEvidence(response: RetrievalQueryResponse): boolean { response.results.length > 0 || response.referencedChunks.some(hasReferencedChunkEvidence) || hasEvidenceParts(response) || - Boolean(response.answerText?.trim()) + Boolean(response.evidenceText?.trim()) ) } @@ -991,6 +1025,7 @@ function buildRetrievalQueryParams(input: { readonly sources: AnswerQuestionInput["sources"] readonly excludedSourceIds: readonly string[] readonly folderScopeSourceIds?: readonly string[] + readonly excludedWorkspaceDemoDocumentIds?: readonly string[] }): RetrievalQueryParams { const query = normalizeRetrievalQuery( input.input.query, @@ -1015,6 +1050,8 @@ function buildRetrievalQueryParams(input: { input.excludedSourceIds, input.input, input.folderScopeSourceIds, + input.namespace, + input.excludedWorkspaceDemoDocumentIds, ), } } @@ -1192,7 +1229,7 @@ function resolveCitationImageAssetRefs( (candidate) => candidate.ref !== chunk.ref && candidate.chunkId === chunk.chunkId && - candidate.source.documentId === chunk.source.documentId, + hasSameSourceRevision(candidate, chunk), ) .map((candidate) => candidate.ref), ) @@ -1284,6 +1321,7 @@ function mergeChunkPageMetadata( (candidate) => candidate.ref !== chunk.ref && candidate.chunkId === chunk.chunkId && + hasSameSourceRevision(candidate, chunk) && hasResolvablePageNumber(candidate), ) if (!donor?.metadata) return chunk @@ -1304,6 +1342,7 @@ async function hydrateMissingCitationPageMetadata(input: { (chunk) => Boolean(result.chunkId) && chunk.chunkId === result.chunkId && + hasSameSourceRevision(chunk, result) && hasResolvablePageNumber(chunk), ) if (!donor?.metadata || resolvePageCitationPageNumber(result)) { @@ -1335,7 +1374,9 @@ async function hydrateResultPageMetadataFromKnowledge( if (!documentId || !chunkId) return result try { - const response = await knowledge.readChunks({ documentId, chunkId }) + const revisionKey: string | undefined = getSourceRevision(result) + if (getSourceNamespace(result) === "__knowhere_demo__" && !revisionKey) return result + const response = await knowledge.readChunks({ documentId, chunkId, ...(revisionKey ? { revisionKey } : {}) }) const chunk = response.chunks[0] if (!chunk) return result return { @@ -1364,6 +1405,8 @@ function hasResolvablePageNumber(chunk: EvidenceChunk): boolean { documentId: chunk.source.documentId ?? undefined, sourceFileName: chunk.source.sourceFileName ?? undefined, sectionPath: chunk.source.sectionPath ?? undefined, + ...(chunk.source.namespace ? { namespace: chunk.source.namespace } : {}), + ...(chunk.source.jobResultId ? { jobResultId: chunk.source.jobResultId } : {}), }, }) !== undefined ) @@ -1374,6 +1417,7 @@ function toRetrievalResultFromEvidenceChunk( ): RetrievalResult { return { ...(chunk.chunkId ? { chunkId: chunk.chunkId } : {}), + ...(chunk.chunkRowId ? { chunkRowId: chunk.chunkRowId } : {}), content: chunk.content, chunkType: chunk.chunkType, score: chunk.score, @@ -1385,6 +1429,8 @@ function toRetrievalResultFromEvidenceChunk( documentId: chunk.source.documentId ?? undefined, sourceFileName: chunk.source.sourceFileName ?? undefined, sectionPath: chunk.source.sectionPath ?? undefined, + ...(chunk.source.namespace ? { namespace: chunk.source.namespace } : {}), + ...(chunk.source.jobResultId ? { jobResultId: chunk.source.jobResultId } : {}), }, } } @@ -1396,7 +1442,7 @@ function hasDisplayedManifestArtifacts(result: HarnessRunResult): boolean { function getRetrievalResultKey(result: RetrievalResult): string { const source = result.source return [ - source.documentId ?? "", + getSourceRevisionIdentity(result), source.sourceFileName ?? "", source.sectionPath ?? "", result.chunkType, @@ -1406,3 +1452,31 @@ function getRetrievalResultKey(result: RetrievalResult): string { .map((part) => `${part.length}:${part}`) .join("|") } + +type RetrievalSourceReference = { + readonly source: { + readonly documentId?: string | null + readonly namespace?: string | null + readonly jobResultId?: string | null + } + readonly revisionKey?: string | null + readonly metadata?: Readonly> +} + +function hasSameSourceRevision(first: RetrievalSourceReference, second: RetrievalSourceReference): boolean { + return getSourceRevisionIdentity(first) === getSourceRevisionIdentity(second) +} + +function getSourceRevisionIdentity(reference: RetrievalSourceReference): string { + return JSON.stringify([reference.source.documentId ?? "", getSourceNamespace(reference) ?? "", getSourceRevision(reference) ?? ""]) +} + +function getSourceNamespace(reference: RetrievalSourceReference): string | undefined { + const value: unknown = reference.source.namespace ?? reference.metadata?.namespace + return typeof value === "string" && value.trim() ? value : undefined +} + +function getSourceRevision(reference: RetrievalSourceReference): string | undefined { + const value: unknown = reference.source.jobResultId ?? reference.metadata?.jobResultId ?? reference.revisionKey + return typeof value === "string" && value.trim() ? value : undefined +} diff --git a/src/domains/chat/knowhere-tools.ts b/src/domains/chat/knowhere-tools.ts index 032b5999..38c9656c 100644 --- a/src/domains/chat/knowhere-tools.ts +++ b/src/domains/chat/knowhere-tools.ts @@ -1,11 +1,10 @@ import type { KnowhereToolRuntime } from "@/agent-harness" import { hasReferencedChunkEvidence } from "@/agent-harness/referenced-chunks" -import type { SearchSources } from "./contracts" -import type { Source } from "@/infrastructure/db/schema" +import type { ChatSource, SearchSources } from "./contracts" type NotebookKnowhereToolsInput = { readonly searchSources: SearchSources - readonly sources: readonly Source[] + readonly sources: readonly ChatSource[] } export const notebookKnowhereTools = { diff --git a/src/domains/chat/media-asset-hardening.test.ts b/src/domains/chat/media-asset-hardening.test.ts index 462dde00..ee6d918d 100644 --- a/src/domains/chat/media-asset-hardening.test.ts +++ b/src/domains/chat/media-asset-hardening.test.ts @@ -22,6 +22,12 @@ afterEach(() => { }) describe("hardenChatMediaAssetUrls", () => { + it("hardens assets against the actual retrieval revision instead of the current catalog", async () => { + const hardenChatAssetUrl = vi.fn(async () => "https://blob.example/saved.png") + await hardenChatMediaAssetUrls({ workspaceId: "workspace_1", sources: [{ ...makeSource({ knowhereDocumentId: "doc_1" }), namespace: "__knowhere_demo__", jobResultId: "current" }], results: [makeRetrievalResult({ assetUrl: "https://storage.example/images/a.png", metadata: { namespace: "__knowhere_demo__", jobResultId: "saved" }, source: { documentId: "doc_1", sectionPath: "images/a.png" } })], hardenChatAssetUrl }) + expect(hardenChatAssetUrl).toHaveBeenCalledWith(expect.objectContaining({ source: expect.objectContaining({ jobResultId: "saved", knowhereJobId: "saved" }) })) + }) + it("keeps an already Notebook-owned asset URL without calling the hardener", async () => { const ownedUrl = "https://fake.public.blob.vercel-storage.com/workspaces/workspace_1/parsed-documents/doc_1/rev_1/images/a.png" diff --git a/src/domains/chat/media-asset-hardening.ts b/src/domains/chat/media-asset-hardening.ts index ba88bb1f..ed1fa188 100644 --- a/src/domains/chat/media-asset-hardening.ts +++ b/src/domains/chat/media-asset-hardening.ts @@ -4,7 +4,8 @@ import type { ChatArtifactView, ChatCitationView, } from "@/domains/chat/types" -import type { Source } from "@/infrastructure/db/schema" +import { bindCitationSourceRevision } from "./citation-source-revision" +import type { ChatSource } from "./contracts" import { logger } from "@/lib/logger" import type { HardenChatAssetUrl } from "./media-assets" @@ -29,7 +30,7 @@ export type HardenMediaAssetUrls = ( export type HardenChatMediaAssetUrlsForWorkspaceInput = HardenMediaAssetUrlsInput & { readonly workspaceId: string - readonly sources: readonly Source[] + readonly sources: readonly ChatSource[] readonly hardenChatAssetUrl: HardenChatAssetUrl } @@ -39,10 +40,11 @@ type AssetUrlReference = { readonly assetUrl: string readonly source?: AssetReferenceSource readonly content?: string + readonly metadata?: Readonly> } type HardeningContext = { - readonly sourcesByDocumentId: ReadonlyMap + readonly sourcesByDocumentId: ReadonlyMap readonly hardenChatAssetUrl: HardenChatAssetUrl } @@ -99,7 +101,7 @@ async function hardenRetrievalResult( const hardenedAssetUrl = assetUrl ? await resolveDurableAssetUrl( - { assetUrl, source: result.source, content: result.content }, + { assetUrl, source: result.source, content: result.content, metadata: result.metadata }, context, ) : undefined @@ -109,6 +111,7 @@ async function hardenRetrievalResult( assetUrl: pageCitationAssetUrl, source: result.source, content: result.content, + metadata: result.metadata, }, context, ) @@ -351,16 +354,17 @@ function decodeUrlText(value: string): string { function resolveSourceForReference( reference: AssetUrlReference, context: HardeningContext, -): Source | undefined { +): ChatSource | undefined { const documentId = getTrimmedString(reference.source?.documentId) - return documentId ? context.sourcesByDocumentId.get(documentId) : undefined + const source = documentId ? context.sourcesByDocumentId.get(documentId) : undefined + return source ? bindCitationSourceRevision(source, reference.source, reference.metadata) ?? undefined : undefined } function createSourcesByDocumentId( - sources: readonly Source[], -): ReadonlyMap { + sources: readonly ChatSource[], +): ReadonlyMap { return new Map( - sources.flatMap((source): readonly [string, Source][] => + sources.flatMap((source): readonly [string, ChatSource][] => source.knowhereDocumentId ? [[source.knowhereDocumentId, source]] : [], ), ) diff --git a/src/domains/chat/media-assets.test.ts b/src/domains/chat/media-assets.test.ts index 46bfd3c3..5df9d57d 100644 --- a/src/domains/chat/media-assets.test.ts +++ b/src/domains/chat/media-assets.test.ts @@ -19,6 +19,11 @@ vi.mock("@/lib/logger", () => ({ })) describe("chat media assets", () => { + it("keeps media from separate revisions of the same document distinct", () => { + const result = makeRetrievalResult({ chunkType: "image", assetUrl: "https://assets.example/images/a.png", source: { documentId: "doc", sectionPath: "images/a.png" } }) + expect(dedupeMediaCitationResults([{ ...result, metadata: { namespace: "__knowhere_demo__", jobResultId: "old" } }, { ...result, metadata: { namespace: "__knowhere_demo__", jobResultId: "new" } }])).toHaveLength(2) + }) + it("enriches retrieved image chunks from Notebook parsed asset URLs", async () => { const hardenChatAssetUrl = vi .fn() diff --git a/src/domains/chat/media-assets.ts b/src/domains/chat/media-assets.ts index 09c9cd07..ffa7967c 100644 --- a/src/domains/chat/media-assets.ts +++ b/src/domains/chat/media-assets.ts @@ -1,7 +1,8 @@ import type { RetrievalResult } from "@ontos-ai/knowhere-sdk" import { logger } from "@/lib/logger" -import type { Source } from "@/infrastructure/db/schema" +import { bindCitationSourceRevision } from "./citation-source-revision" +import type { ChatSource } from "./contracts" // Knowhere's chunkType is declared as a required string in the SDK type, // but real retrieval results can omit it. Normalize defensively instead of @@ -21,7 +22,7 @@ const internalMetadataKeys = new Set([ ]) export type HardenChatAssetUrlInput = { - readonly source: Source + readonly source: ChatSource readonly sourcePath: string readonly assetUrl?: string | null readonly contentType?: string | null @@ -33,7 +34,7 @@ export type HardenChatAssetUrl = ( export type RetrievalResultAssetInput = { readonly results: readonly RetrievalResult[] - readonly sources: readonly Source[] + readonly sources: readonly ChatSource[] readonly hardenChatAssetUrl?: HardenChatAssetUrl } @@ -47,14 +48,15 @@ export async function enrichRetrievalResultsWithAssetUrls({ } const sourcesByDocumentId = new Map( - sources.flatMap((source): readonly [string, Source][] => + sources.flatMap((source): readonly [string, ChatSource][] => source.knowhereDocumentId ? [[source.knowhereDocumentId, source]] : [], ), ) const enrichedResults = await Promise.all( results.map(async (result): Promise => { const documentId = getTrimmedString(result.source.documentId) - const source = documentId ? sourcesByDocumentId.get(documentId) : undefined + const candidate = documentId ? sourcesByDocumentId.get(documentId) : undefined + const source = candidate ? bindCitationSourceRevision(candidate, result.source, result.metadata) : null if (!source) return [result] return addAssetCitationResults(result, source, hardenChatAssetUrl) @@ -209,10 +211,13 @@ function getMediaCitationDedupeKey( getTrimmedString(result.source.documentId) ?? getTrimmedString(result.source.sourceFileName) ?? "unknown" + const namespace = typeof result.metadata?.namespace === "string" ? result.metadata.namespace : "" + const jobResultId = typeof result.metadata?.jobResultId === "string" ? result.metadata.jobResultId : "" + const revisionKey = JSON.stringify([namespace, jobResultId]) const assetPath = getCanonicalAssetPathFromSource(result) ?? getCanonicalAssetPathFromUrl(assetUrl) - return assetPath ? `asset:${documentKey}:${assetPath}` : `url:${assetUrl}` + return assetPath ? `asset:${documentKey}:${revisionKey}:${assetPath}` : `url:${revisionKey}:${assetUrl}` } function getCanonicalAssetPathFromSource( @@ -248,7 +253,7 @@ function isNotebookParsedAssetUrl(assetUrl: string): boolean { async function addAssetCitationResults( result: RetrievalResult, - source: Source, + source: ChatSource, hardenChatAssetUrl: HardenChatAssetUrl, ): Promise { if (normalizeChunkType(result.chunkType) === "page") return [result] diff --git a/src/domains/chat/page-citation-assets.ts b/src/domains/chat/page-citation-assets.ts index 07e93197..70a8a198 100644 --- a/src/domains/chat/page-citation-assets.ts +++ b/src/domains/chat/page-citation-assets.ts @@ -2,10 +2,16 @@ import "server-only" import type { RetrievalResult } from "@ontos-ai/knowhere-sdk" -import type { Source } from "@/infrastructure/db/schema" +import { bindCitationSourceRevision } from "./citation-source-revision" +import type { ChatSource } from "./contracts" import type { HardenChatAssetUrl } from "./media-assets" export type PageCitationAssetRetrievalResult = RetrievalResult & { + readonly chunkRowId?: string + readonly source: RetrievalResult["source"] & { + readonly namespace?: string + readonly jobResultId?: string + } readonly pageCitationAssetUrl?: string readonly pageCitationPageNumber?: number readonly highlightRegions?: readonly { @@ -18,7 +24,7 @@ export type PageCitationAssetRetrievalResult = RetrievalResult & { type EnrichRetrievalResultsWithPageCitationAssetUrlsInput = { readonly results: readonly RetrievalResult[] - readonly sources: readonly Source[] + readonly sources: readonly ChatSource[] readonly hardenChatAssetUrl?: HardenChatAssetUrl } @@ -39,7 +45,7 @@ export async function enrichRetrievalResultsWithPageCitationAssetUrls({ if (results.length === 0) return [] const sourcesByDocumentId = new Map( - sources.flatMap((source): readonly [string, Source][] => + sources.flatMap((source): readonly [string, ChatSource][] => source.knowhereDocumentId ? [[source.knowhereDocumentId, source]] : [], ), ) @@ -72,7 +78,7 @@ export function resolvePageCitationPageNumber( async function enrichRetrievalResultWithPageCitationAssetUrl(input: { readonly result: RetrievalResult - readonly sourcesByDocumentId: ReadonlyMap + readonly sourcesByDocumentId: ReadonlyMap readonly hardenChatAssetUrl?: HardenChatAssetUrl }): Promise { const pageNumbers = getPageNumbers(input.result.metadata) @@ -103,14 +109,15 @@ async function enrichRetrievalResultWithPageCitationAssetUrl(input: { async function getStoredPageCitationAssetUrl(input: { readonly result: RetrievalResult readonly directAsset: PageCitationAssetCandidate | null - readonly sourcesByDocumentId: ReadonlyMap + readonly sourcesByDocumentId: ReadonlyMap readonly hardenChatAssetUrl?: HardenChatAssetUrl }): Promise { const artifactRef = getTrimmedString(input.directAsset?.artifactRef) const documentId = getTrimmedString(input.result.source.documentId) if (!artifactRef || !documentId || !input.hardenChatAssetUrl) return null - const source = input.sourcesByDocumentId.get(documentId) + const candidate = input.sourcesByDocumentId.get(documentId) + const source = candidate ? bindCitationSourceRevision(candidate, input.result.source, input.result.metadata) : null if (!source) return null return input.hardenChatAssetUrl({ diff --git a/src/domains/chat/prompt.ts b/src/domains/chat/prompt.ts index d55b86ac..59dbc617 100644 --- a/src/domains/chat/prompt.ts +++ b/src/domains/chat/prompt.ts @@ -2,7 +2,6 @@ import { Effect } from "effect" import { CHAT_MODEL } from "@/lib/ai" import { logger } from "@/lib/logger" -import type { Source } from "@/infrastructure/db/schema" import type { ChatCitationView } from "@/domains/chat/types" import { runAgentHarness, @@ -13,6 +12,7 @@ import { type ResolveConnectedAssets, } from "@/agent-harness" import type { + ChatSource, ChatHistoryMessage, SearchSources, } from "./contracts" @@ -34,7 +34,7 @@ type GenerateAgenticOutputManifestInput = { workspaceId: string question: string messages: readonly ChatHistoryMessage[] - sources: readonly Source[] + sources: readonly ChatSource[] excludedSourceIds: readonly string[] searchSources: SearchSources knowhereTools?: KnowhereToolRuntime diff --git a/src/domains/chat/retrieval-response.test.ts b/src/domains/chat/retrieval-response.test.ts new file mode 100644 index 00000000..97b3d211 --- /dev/null +++ b/src/domains/chat/retrieval-response.test.ts @@ -0,0 +1,29 @@ +import { describe, expect, it } from "vitest" +import { decodeNotebookRetrievalResponse } from "./retrieval-response" + +const response = { + namespace: "__knowhere_demo__", query: "question", routerUsed: "test", answerText: null, + results: [{ content: "Evidence", chunkType: "text", score: 1, + source: { documentId: "demo-doc", namespace: "__knowhere_demo__", jobResultId: "result-at-retrieval" } }], + referencedChunks: [{ chunkId: "chunk", documentId: "demo-doc", chunkType: "page", sectionPath: "page 1", + namespace: "__knowhere_demo__", jobResultId: "reference-at-retrieval" }], +} +describe("Notebook retrieval response boundary", () => { + it("preserves actual revisions for raw results and referenced evidence", () => { + const decoded = decodeNotebookRetrievalResponse(response) + expect(decoded.results[0]).toMatchObject({ source: { jobResultId: "result-at-retrieval", namespace: "__knowhere_demo__" }, + metadata: { jobResultId: "result-at-retrieval", namespace: "__knowhere_demo__" } }) + expect(decoded.referencedChunks[0]).toMatchObject({ jobResultId: "reference-at-retrieval", + metadata: { jobResultId: "reference-at-retrieval", namespace: "__knowhere_demo__" } }) + }) + it("rejects invalid response shapes before the harness reads evidence", () => { + expect(() => decodeNotebookRetrievalResponse({ ...response, results: [{ content: 42 }] })).toThrow() + expect(() => decodeNotebookRetrievalResponse({ ...response, results: [{ ...response.results[0], source: { jobResultId: 42 } }] })).toThrow() + }) + it("leaves missing revisions missing while using the actual response namespace", () => { + const decoded = decodeNotebookRetrievalResponse({ ...response, + results: [{ content: "Evidence", chunkType: "text", score: null, source: { documentId: "demo-doc" } }] }) + expect(decoded.results[0]?.metadata).toEqual({ namespace: "__knowhere_demo__" }) + expect(decoded.results[0]?.source).not.toHaveProperty("jobResultId") + }) +}) diff --git a/src/domains/chat/retrieval-response.ts b/src/domains/chat/retrieval-response.ts new file mode 100644 index 00000000..65cee06b --- /dev/null +++ b/src/domains/chat/retrieval-response.ts @@ -0,0 +1,99 @@ +import { Schema } from "effect" +import type { RetrievalQueryResponse, RetrievalResult, RetrievalReferencedChunk } from "@ontos-ai/knowhere-sdk" + +const optionalString = Schema.optional(Schema.NullOr(Schema.String)) +const metadataSchema = Schema.Record({ key: Schema.String, value: Schema.Unknown }) +const retrievalSourceSchema = Schema.Struct({ + documentId: optionalString, + sourceFileName: optionalString, + sectionPath: optionalString, + namespace: optionalString, + jobResultId: optionalString, +}) +const retrievalResultSchema = Schema.Struct({ + chunkId: Schema.optional(Schema.String), + chunkRowId: Schema.optional(Schema.String), + content: Schema.String, + chunkType: Schema.String, + contentSource: Schema.optional(Schema.String), + score: Schema.NullOr(Schema.Number), + assetUrl: Schema.optional(Schema.String), + sourceChunkPath: optionalString, + filePath: optionalString, + metadata: Schema.optional(metadataSchema), + namespace: optionalString, + jobResultId: optionalString, + source: retrievalSourceSchema, +}) +const referencedChunkSchema = Schema.Struct({ + chunkId: Schema.String, + chunkRowId: Schema.optional(Schema.String), + documentId: Schema.String, + // Older gateways can return ID-only provenance without chunk evidence. + chunkType: Schema.optionalWith(Schema.String, { default: () => "" }), + sectionPath: Schema.optionalWith(Schema.String, { default: () => "" }), + contentSource: optionalString, + sourceChunkPath: optionalString, + filePath: optionalString, + jobId: optionalString, + namespace: optionalString, + jobResultId: optionalString, + assetUrl: optionalString, + metadata: Schema.optional(metadataSchema), +}) +const retrievalResponseSchema = Schema.Struct({ + namespace: Schema.String, + query: Schema.String, + routerUsed: Schema.String, + answerText: Schema.NullOr(Schema.String), + results: Schema.Array(retrievalResultSchema), + referencedChunks: Schema.Array(referencedChunkSchema), + evidenceText: optionalString, + stopReason: optionalString, + failureReason: optionalString, + decisionTrace: Schema.optional(Schema.Array(metadataSchema)), + evidence: Schema.optional(Schema.Array(Schema.Union( + Schema.Struct({ type: Schema.Literal("text"), text: Schema.String }), + Schema.Struct({ type: Schema.Literal("image"), mediaType: Schema.String, data: Schema.String }), + ))), +}) + +type RetrievalProvenance = { + readonly namespace?: string | null + readonly jobResultId?: string | null +} +type NotebookRetrievalResult = RetrievalResult & { + readonly source: RetrievalResult["source"] & RetrievalProvenance + readonly chunkRowId?: string +} +type NotebookRetrievalResponse = RetrievalQueryResponse & { + results: NotebookRetrievalResult[] + referencedChunks: (RetrievalReferencedChunk & RetrievalProvenance)[] +} + +/** Validate SDK responses while retaining retrieval-time revision identity. */ +export function decodeNotebookRetrievalResponse(value: unknown): NotebookRetrievalResponse { + const response = Schema.decodeUnknownSync(retrievalResponseSchema)(value, { onExcessProperty: "preserve" }) + return { + ...response, + evidence: response.evidence?.map((part) => ({ ...part })), + decisionTrace: response.decisionTrace?.map((trace) => ({ ...trace })), + results: response.results.map((result): NotebookRetrievalResult => { + const namespace: string = result.source.namespace ?? result.namespace ?? response.namespace + const jobResultId: string | undefined = result.source.jobResultId ?? result.jobResultId ?? readMetadataString(result.metadata, "jobResultId") + return { ...result, source: { ...result.source, namespace, ...(jobResultId ? { jobResultId } : {}) }, + metadata: { ...result.metadata, namespace, ...(jobResultId ? { jobResultId } : {}), ...(result.chunkRowId ? { chunkRowId: result.chunkRowId } : {}) } } + }), + referencedChunks: response.referencedChunks.map((chunk) => { + const namespace: string = chunk.namespace ?? response.namespace + const jobResultId: string | undefined = chunk.jobResultId ?? readMetadataString(chunk.metadata, "jobResultId") + return { ...chunk, namespace, ...(jobResultId ? { jobResultId } : {}), + metadata: { ...chunk.metadata, namespace, ...(jobResultId ? { jobResultId } : {}), ...(chunk.chunkRowId ? { chunkRowId: chunk.chunkRowId } : {}) } } + }), + } +} + +function readMetadataString(metadata: Readonly> | undefined, key: string): string | undefined { + const value: unknown = metadata?.[key] + return typeof value === "string" && value.trim().length > 0 ? value : undefined +} diff --git a/src/domains/chat/retrieval.ts b/src/domains/chat/retrieval.ts index d166baaa..457b2c95 100644 --- a/src/domains/chat/retrieval.ts +++ b/src/domains/chat/retrieval.ts @@ -1,6 +1,6 @@ import type { KnowhereSearchRequest } from "@/agent-harness/types" -import type { Source } from "@/infrastructure/db/schema" +import type { ChatSource } from "./contracts" import { decodeRemoteSourceId } from "@/domains/sources/remote-library" const RETRIEVAL_QUERY_CHAR_LIMIT = 600 @@ -26,24 +26,40 @@ export const emptyFolderSearchMessage = export function isEmptyFolderScope( folderScopeSourceIds: readonly string[] | undefined, - sources: readonly Source[], + sources: readonly ChatSource[], ): boolean { if (folderScopeSourceIds === undefined) return false const scoped = new Set(folderScopeSourceIds) return !sources.some( - (source) => scoped.has(source.id) && Boolean(source.knowhereDocumentId), + (source) => !source.demoKey && scoped.has(source.id) && Boolean(source.knowhereDocumentId), ) } export function getRetrievalDocumentScope( - sources: readonly Source[], + sources: readonly ChatSource[], excludedSourceIds: readonly string[], request: Pick, folderScopeSourceIds?: readonly string[], + namespace?: string, + excludedWorkspaceDemoDocumentIds: readonly string[] = [], ): Pick { const excluded = new Set(excludedSourceIds) + if (namespace === "__knowhere_demo__") { + if (folderScopeSourceIds !== undefined) return { includeDocumentIds: [] } + const requested: ReadonlySet | undefined = request.includeDocumentIds === undefined + ? undefined : new Set(request.includeDocumentIds) + const excludedDocuments: ReadonlySet = new Set(request.excludeDocumentIds ?? []) + return { + includeDocumentIds: [...new Set(sources.flatMap((source): string[] => { + const documentId: string | null = source.knowhereDocumentId + if (source.namespace !== namespace || source.status !== "ready" || !documentId || + excluded.has(source.id) || excludedDocuments.has(documentId) || (requested && !requested.has(documentId))) return [] + return [documentId] + }))], + } + } const localDocumentIds = sources - .filter((source) => excluded.has(source.id)) + .filter((source) => source.namespace !== "__knowhere_demo__" && (excluded.has(source.id) || Boolean(source.demoKey))) .map((source) => source.knowhereDocumentId) .filter((documentId): documentId is string => Boolean(documentId)) const remoteDocumentIds = excludedSourceIds @@ -52,18 +68,26 @@ export function getRetrievalDocumentScope( const documentIds = Array.from( new Set([ ...localDocumentIds, + ...excludedWorkspaceDemoDocumentIds, ...remoteDocumentIds, ...(request.excludeDocumentIds ?? []), ]), ) - const includeDocumentIds = getFolderScopeDocumentIds( - sources, + const folderDocumentIds = getFolderScopeDocumentIds( + sources.filter((source) => !source.demoKey), folderScopeSourceIds, ) + const sharedDocumentIds: ReadonlySet = new Set(sources.flatMap((source) => source.namespace === "__knowhere_demo__" && source.knowhereDocumentId ? [source.knowhereDocumentId] : [])) + const requestedDocumentIds: readonly string[] | undefined = request.includeDocumentIds?.filter((documentId) => + !sharedDocumentIds.has(documentId) && !excludedWorkspaceDemoDocumentIds.includes(documentId) && + !sources.some((source) => source.demoKey && source.namespace !== "__knowhere_demo__" && source.knowhereDocumentId === documentId)) + const includeDocumentIds: readonly string[] | undefined = folderDocumentIds !== undefined + ? folderDocumentIds.filter((documentId) => requestedDocumentIds === undefined || requestedDocumentIds.includes(documentId)) + : requestedDocumentIds return { ...(includeDocumentIds !== undefined - ? { includeDocumentIds } + ? { includeDocumentIds: [...new Set(includeDocumentIds)] } : request.includeDocumentIds !== undefined ? { includeDocumentIds: [...new Set(request.includeDocumentIds)] } : {}), @@ -72,7 +96,7 @@ export function getRetrievalDocumentScope( } function getFolderScopeDocumentIds( - sources: readonly Source[], + sources: readonly ChatSource[], folderScopeSourceIds: readonly string[] | undefined, ): string[] | undefined { if (folderScopeSourceIds === undefined) return undefined diff --git a/src/domains/chat/revision-safety.test.ts b/src/domains/chat/revision-safety.test.ts new file mode 100644 index 00000000..48fa7e5b --- /dev/null +++ b/src/domains/chat/revision-safety.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from "vitest" +import { toChatCitationViews } from "./citations" +import { chatCitationPersistence } from "./chat-citation-persistence" +import { toChatMessageView } from "./view" +import { resolveCitationChunk } from "@/domains/chunks" +import { workspaceClientCache } from "@/domains/workspace/client-cache" +import type { ChatCitationView } from "./types" +import type { ChatMessage } from "@/infrastructure/db/schema" + +const citation: ChatCitationView = { + chunkId: "parser_1", + chunkRowId: "row_1", + chunkType: "text", + score: 0.9, + source: { documentId: "doc_1", namespace: "__knowhere_demo__", jobResultId: "revision_old", sectionPath: "Summary" }, +} + +describe("revision-safe citations", () => { + it("keeps the actual retrieval revision and separate parser and row identifiers", () => { + const result = toChatCitationViews([{ ...citation, content: "Body" }], "Answer") + expect(result[0]).toMatchObject(citation) + }) + + it("round trips citation provenance without storing retrieved content", () => { + const persisted = chatCitationPersistence.normalizeCitations([{ ...citation, content: "Do not persist" }]) + expect(persisted?.[0]).toMatchObject(citation) + expect(persisted?.[0]).not.toHaveProperty("content") + const message: ChatMessage = { id: "m1", threadId: "t1", role: "assistant", content: "Answer", citations: persisted, artifacts: null, agentTrace: null, createdAt: new Date() } + expect(toChatMessageView(message).citations?.[0]).toMatchObject(citation) + }) + + it("exposes saved partial retrieval warnings from the validated trace", () => { + const warning = { scope: "demo", code: "demo_unavailable", message: "Shared documents were unavailable." } as const + const message: ChatMessage = { id: "m1", threadId: "t1", role: "assistant", content: "Answer", citations: null, artifacts: null, agentTrace: { intentTask: "answer", toolCalls: [], referencedDocumentIds: [], retrievalWarnings: [warning] }, createdAt: new Date() } + expect(toChatMessageView(message).retrievalWarnings).toEqual([warning]) + }) + + it("focuses an exact parser identifier only within the cited revision", () => { + const makeChunk = (jobResultId: string, chunkId: string) => ({ chunkId, parserChunkId: "parser_1", documentId: "doc_1", namespace: "__knowhere_demo__", jobResultId, type: "text" as const, content: "Body", sectionPath: "Summary", sourceTitle: "Report" }) + expect(resolveCitationChunk(citation, [makeChunk("revision_new", "row_new")])).toBeNull() + expect(resolveCitationChunk(citation, [makeChunk("revision_new", "row_new"), makeChunk("revision_old", "row_1")])?.chunkId).toBe("row_1") + }) + + it("isolates chunk cache entries by revision, namespace and chunk type", () => { + const current = workspaceClientCache.getSourceChunksKey("demo_1", 0, null, { jobResultId: "new", namespace: "__knowhere_demo__", chunkType: "page" }) + const saved = workspaceClientCache.getSourceChunksKey("demo_1", 0, null, { jobResultId: "old", namespace: "__knowhere_demo__", chunkType: "page" }) + const text = workspaceClientCache.getSourceChunksKey("demo_1", 0, null, { jobResultId: "old", namespace: "__knowhere_demo__", chunkType: "text" }) + expect(current).not.toEqual(saved) + expect(saved).not.toEqual(text) + }) +}) diff --git a/src/domains/chat/route-answer.ts b/src/domains/chat/route-answer.ts index 063cab0b..c18aa813 100644 --- a/src/domains/chat/route-answer.ts +++ b/src/domains/chat/route-answer.ts @@ -1,4 +1,4 @@ -import { Cause, Effect, Either, Option } from "effect" +import { Cause, Effect, Either, Option, Runtime, Schema } from "effect" import { parseChatRequestBody } from "@/domains/chat" import { commitAgenticChatTurn } from "@/domains/chat/commit-turn" @@ -15,6 +15,11 @@ import { BlobParsedDocumentStorage } from "@/domains/sources/parsed-document-blo import { sourceWorkflowRuntime } from "@/domains/sources/workflow-runtime" import { notebookRequestContext } from "@/domains/workspace/request-context" import type { Source } from "@/infrastructure/db/schema" +import { resolveCitationSources } from "./citation-sources" +import type { DemoCatalog } from "@/integrations/knowhere-demo" +import type { ChatSource, RetrievalPreparationFailure } from "./contracts" +import { sourceService } from "@/domains/sources/service" +import { resolveWorkspaceDemoSources } from "@/domains/demo/workspace-source-resolution" import type { HardenChatAssetUrl } from "./media-assets" import { isAuthError } from "@/integrations/dashboard/api-key-service" import { makeKnowhereClientWithParsedStorage } from "@/integrations/knowhere" @@ -30,10 +35,15 @@ type MessageBody = { } type ChatRouteFailure = { - readonly status: 401 | 502 + readonly status: 401 | 409 | 429 | 502 | 503 readonly message: string } +class ChatDemoCatalogUnavailable extends Schema.TaggedError()("ChatDemoCatalogUnavailable", { + message: Schema.String, + cause: Schema.Unknown, +}) {} + type ChatAnswerFailure = ChatTurnError | ChatRouteFailure type AnswerChatInput = { @@ -60,16 +70,45 @@ const answerChatEffect = (input: AnswerChatInput) => const { workspace, client, apiKey } = yield* Effect.tryPromise(() => notebookRequestContext.getAuthenticatedWithClient(), ) - const sources = yield* Effect.tryPromise(() => + const listedSources = yield* Effect.tryPromise(() => sourceWorkflowRuntime.listForWorkspace(workspace.id), ) yield* Effect.sync(() => triggerBackgroundReconciliationForParsingSources({ workspaceId: workspace.id, - sources, + sources: listedSources, apiKey, }), ) + const preparation = yield* Effect.all({ + catalog: Effect.either(Effect.tryPromise({ try: () => knowhereDemoApi.fetchCatalog(), catch: (cause: unknown) => new ChatDemoCatalogUnavailable({ message: summarizeUnknownError(cause), cause }) })), + hiddenDemoSourceIds: Effect.tryPromise(() => sourceService.listHiddenDemoSourceIds(workspace.id)), + selectedDemoSourceIds: Effect.tryPromise(() => sourceService.listSelectedDemoSourceIds(workspace.id)), + legacyDemoDocumentIds: Effect.tryPromise(() => sourceService.listLegacyDemoDocumentIds(workspace.id)), + }, { concurrency: 4 }) + const { hiddenDemoSourceIds, selectedDemoSourceIds, legacyDemoDocumentIds } = preparation + const catalog: DemoCatalog = Either.isRight(preparation.catalog) ? preparation.catalog.right : { sources: [], officialLibrary: { categories: [], sources: [] } } + const retrievalPreparationFailures: readonly RetrievalPreparationFailure[] = Either.isLeft(preparation.catalog) + ? [{ warning: { scope: "demo", code: "demo_catalog_unavailable", message: "Demo sources are unavailable. The answer uses available workspace sources." }, cause: preparation.catalog.left }] + : [] + if (Either.isLeft(preparation.catalog) && !listedSources.some((source) => !source.demoKey && source.status === "ready" && source.knowhereDocumentId)) { + const failure = toChatRouteFailure(summarizeUnknownError(preparation.catalog.left), preparation.catalog.left) + return routeResult.error(failure.status, failure.message) + } + const resolvedSources = resolveWorkspaceDemoSources(listedSources, catalog, new Set(hiddenDemoSourceIds), new Set(selectedDemoSourceIds)) + const sources: readonly ChatSource[] = [ + ...resolvedSources.workspaceSources, + ...resolvedSources.demoSources.filter((source) => source.officialLibrary === undefined).map((source): ChatSource => ({ + id: source.id, title: source.title, mimeType: source.mimeType, status: source.status, + knowhereDocumentId: source.documentId ?? null, knowhereJobId: null, + demoKey: source.demoSourceId ?? source.id, namespace: "__knowhere_demo__", + ...(source.jobResultId ? { jobResultId: source.jobResultId } : {}), + })), + ] + const excludedWorkspaceDemoDocumentIds: readonly string[] = [...new Set([ + ...legacyDemoDocumentIds, + ...listedSources.flatMap((source) => source.demoKey && source.knowhereDocumentId ? [source.knowhereDocumentId] : []), + ])] const parsedStorage = new BlobParsedDocumentStorage({ workspaceId: workspace.id, }) @@ -99,6 +138,8 @@ const answerChatEffect = (input: AnswerChatInput) => commitAgenticChatTurn({ workspace, sources, + excludedWorkspaceDemoDocumentIds, + retrievalPreparationFailures, question: body.value.question, threadId: body.value.threadId, useAgentic: body.value.useAgentic, @@ -130,7 +171,7 @@ const answerChatEffect = (input: AnswerChatInput) => Effect.gen(function* () { const detail = getCauseSummary(cause) const prettyCause = Cause.pretty(cause).slice(0, 2_000) - const failure = toChatRouteFailure(detail) + const failure = toChatRouteFailure(detail, Cause.squash(cause)) yield* Effect.logError("chat: answer failed").pipe( Effect.annotateLogs({ status: failure.status, @@ -155,7 +196,9 @@ const answerChatEffect = (input: AnswerChatInput) => onLeft: (error): RouteResponse => routeResult.error(error.status, error.message), onRight: (value): RouteResponse => - routeResult.ok(value), + routeResult.ok({ ...value, citationSources: resolveCitationSources({ + messages: value.messages, sources: listedSources, catalog, namespace: workspace.namespace, + }) }), }) }) @@ -166,7 +209,10 @@ const answerChatEffect = (input: AnswerChatInput) => async function answerChat( input: AnswerChatInput, ): Promise> { - return Effect.runPromise(answerChatEffect(input)) + return Effect.runPromise(answerChatEffect(input).pipe(Effect.catchAllCause((cause) => { + const failure = toChatRouteFailure(getCauseSummary(cause), Cause.squash(cause)) + return Effect.succeed(routeResult.error(failure.status, failure.message)) + }))) } export const chatAnswerRouteService: ChatAnswerRouteService = { @@ -176,7 +222,7 @@ export const chatAnswerRouteService: ChatAnswerRouteService = { async function hardenSingleChatAsset(input: { readonly workspaceId: string readonly parsedStorage: BlobParsedDocumentStorage - readonly source: Source + readonly source: ChatSource readonly sourcePath: string readonly assetUrl?: string | null readonly contentType?: string | null @@ -186,9 +232,11 @@ async function hardenSingleChatAsset(input: { } if (input.source.demoKey) { + if (input.source.namespace === "__knowhere_demo__" && !input.source.jobResultId) return null const demoAssetUrl = resolveDemoSourceAssetUrl({ demoSourceId: input.source.demoKey, sourcePath: input.sourcePath, + jobResultId: input.source.jobResultId, }) if (!demoAssetUrl) return null @@ -196,7 +244,7 @@ async function hardenSingleChatAsset(input: { workspaceId: input.workspaceId, parsedStorage: input.parsedStorage, documentId: input.source.knowhereDocumentId, - revisionKey: input.source.knowhereDocumentId, + revisionKey: input.source.jobResultId ?? input.source.knowhereDocumentId, sourcePath: input.sourcePath, assetUrl: demoAssetUrl, contentType: input.contentType, @@ -221,6 +269,7 @@ async function hardenSingleChatAsset(input: { function resolveDemoSourceAssetUrl(input: { readonly demoSourceId: string readonly sourcePath: string + readonly jobResultId?: string }): string | null { const normalizedPath = input.sourcePath .replaceAll("\\", "/") @@ -236,7 +285,7 @@ function resolveDemoSourceAssetUrl(input: { const encodedPath = pathSegments.map(encodeURIComponent).join("/") return knowhereDemoApi.resolveApiURL( - `/api/v1/demo/sources/${encodeURIComponent(input.demoSourceId)}/assets/${encodedPath}`, + `/api/v1/demo/sources/${encodeURIComponent(input.demoSourceId)}/assets/${encodedPath}${input.jobResultId ? `?job_result_id=${encodeURIComponent(input.jobResultId)}` : ""}`, ) } @@ -363,8 +412,10 @@ function triggerBackgroundReconciliationForParsingSources(input: { } } -function toChatRouteFailure(detail: string): ChatRouteFailure { +function toChatRouteFailure(detail: string, error?: unknown): ChatRouteFailure { const routeDetail = getSafeRouteDetail(detail) + const status = resolveUpstreamFailureStatus(error) + if (status) return { status, message: `Chat generation failed: ${routeDetail}` } if (isAuthError({ message: routeDetail })) { return { status: 401, @@ -416,3 +467,19 @@ function getTrimmedString(value: string | null | undefined): string | null { const trimmedValue = value?.trim() ?? "" return trimmedValue.length > 0 ? trimmedValue : null } + +function resolveUpstreamFailureStatus(error: unknown, depth: number = 0): ChatRouteFailure["status"] | undefined { + if (depth > 5 || typeof error !== "object" || error === null) return undefined + if (Runtime.isFiberFailure(error)) { + const cause: Cause.Cause = error[Runtime.FiberFailureCauseId] + const status: ChatRouteFailure["status"] | undefined = resolveUpstreamFailureStatus(Cause.squash(cause), depth + 1) + if (status) return status + } + const status: unknown = Reflect.get(error, "status") ?? Reflect.get(error, "statusCode") + if (status === 401 || status === 409 || status === 429 || status === 503) return status + for (const key of ["cause", "error", "response", "defect"]) { + const nested: ChatRouteFailure["status"] | undefined = resolveUpstreamFailureStatus(Reflect.get(error, key), depth + 1) + if (nested) return nested + } + return undefined +} diff --git a/src/domains/chat/route-service.test.ts b/src/domains/chat/route-service.test.ts index f87cf381..c2ffd38a 100644 --- a/src/domains/chat/route-service.test.ts +++ b/src/domains/chat/route-service.test.ts @@ -1,10 +1,14 @@ -import { Either } from "effect" +import { Effect, Either } from "effect" import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import type { ChatMessage, ChatThread, Source, Workspace } from "@/infrastructure/db/schema" const mocks = vi.hoisted(() => ({ appendMessageToThread: vi.fn(), + fetchDemoCatalog: vi.fn(), + listHiddenDemoSourceIds: vi.fn(), + listSelectedDemoSourceIds: vi.fn(), + listLegacyDemoDocumentIds: vi.fn(), createChatThread: vi.fn(), documentListChunks: vi.fn(), ensureDefaultChatThread: vi.fn(), @@ -45,6 +49,7 @@ vi.mock("@/integrations/knowhere", () => ({ vi.mock("@/integrations/knowhere-demo", () => ({ knowhereDemoApi: { + fetchCatalog: mocks.fetchDemoCatalog, resolveApiURL: (pathname: string) => `https://demo.example${pathname}`, }, })) @@ -73,9 +78,18 @@ vi.mock("@/integrations/memento/client", () => ({ searchRelevantAgentFeedback: vi.fn().mockResolvedValue([]), })) +vi.mock("@/domains/sources/service", () => ({ sourceService: { + listForWorkspace: mocks.listSourcesForWorkspace, + listLegacyDemoSources: async () => [], + listHiddenDemoSourceIds: mocks.listHiddenDemoSourceIds, + listSelectedDemoSourceIds: mocks.listSelectedDemoSourceIds, + listLegacyDemoDocumentIds: mocks.listLegacyDemoDocumentIds, +} })) + vi.mock("@/domains/sources/workflow-runtime", () => ({ sourceWorkflowRuntime: { listForWorkspace: mocks.listSourcesForWorkspace, + listLegacyDemoSources: async () => [], }, })) @@ -121,6 +135,11 @@ import { chatThreadRouteService } from "./route-threads" describe("chat route services", () => { beforeEach(() => { vi.clearAllMocks() + mocks.listSourcesForWorkspace.mockResolvedValue([]) + mocks.fetchDemoCatalog.mockResolvedValue({ sources: [], officialLibrary: { categories: [], sources: [] } }) + mocks.listHiddenDemoSourceIds.mockResolvedValue([]) + mocks.listSelectedDemoSourceIds.mockResolvedValue([]) + mocks.listLegacyDemoDocumentIds.mockResolvedValue([]) mocks.parsedStorageGetAssetUrl.mockResolvedValue(null) mocks.parsedStorageWriteAsset.mockResolvedValue({ url: null }) mocks.makeKnowhereClientWithParsedStorage.mockReturnValue({ @@ -166,6 +185,7 @@ describe("chat route services", () => { mocks.handleChatTurn.mockResolvedValue( Either.right({ threadId: "thread_1", + citationSources: [], messages: [ { id: "message_user", role: "user", content: "Summarize it" }, { id: "message_assistant", role: "assistant", content: "Answer" }, @@ -186,6 +206,7 @@ describe("chat route services", () => { status: 200, body: { threadId: "thread_1", + citationSources: [], messages: [ { id: "message_user", role: "user", content: "Summarize it" }, { id: "message_assistant", role: "assistant", content: "Answer" }, @@ -216,6 +237,77 @@ describe("chat route services", () => { ) }) + it("resolves demo chat sources from the current server catalog and excludes hidden and historical rows", async () => { + const workspace = makeWorkspace() + const visible = { demoSourceId: "visible", canonicalDocumentId: "shared-document", namespace: "__knowhere_demo__", jobResultId: "catalog-revision", + title: "Shared", mimeType: "text/plain", sizeBytes: 1, status: "ready", chunkCount: 1, + originalFile: { url: "https://example.com/source", mimeType: "text/plain", sizeBytes: 1, canDownload: false }, examples: [] } + mocks.getAuthenticatedWithClient.mockResolvedValue({ workspace, apiKey: "key", client: { retrieval: { query: vi.fn() } } }) + mocks.fetchDemoCatalog.mockResolvedValue({ sources: [visible, + { ...visible, demoSourceId: "hidden", canonicalDocumentId: "hidden-document" }, + { ...visible, demoSourceId: "not-added-official", canonicalDocumentId: "official-document", officialLibrary: { librarySourceId: "official", categoryId: "reports", title: "Official", sourceUrl: "https://example.com", mimeType: "text/plain", status: "ready" } }, + ], officialLibrary: { categories: [], sources: [] } }) + mocks.listHiddenDemoSourceIds.mockResolvedValue(["hidden"]) + mocks.listLegacyDemoDocumentIds.mockResolvedValue(["deleted-private-demo"]) + mocks.listSourcesForWorkspace.mockResolvedValue([makeSource({ demoKey: "visible", knowhereDocumentId: "old-private-demo" })]) + mocks.handleChatTurn.mockResolvedValue(Either.right({ threadId: "thread", messages: [ + { id: "user", role: "user", content: "question" }, { id: "assistant", role: "assistant", content: "answer" }, + ] })) + await chatAnswerRouteService.answerChat({ body: { message: "question", namespace: "browser-namespace", documentIds: ["hidden-document"] } }) + expect(mocks.fetchDemoCatalog).toHaveBeenCalledOnce() + expect(mocks.listHiddenDemoSourceIds).toHaveBeenCalledWith(workspace.id) + expect(mocks.handleChatTurn).toHaveBeenCalledWith(expect.objectContaining({ sources: [expect.objectContaining({ + id: "visible", knowhereDocumentId: "shared-document", namespace: "__knowhere_demo__", jobResultId: "catalog-revision" })], + excludedWorkspaceDemoDocumentIds: expect.arrayContaining(["old-private-demo", "deleted-private-demo"]) })) + }) + + it("keeps private retrieval available with a demo preparation warning when the catalog is unavailable", async () => { + mocks.getAuthenticatedWithClient.mockResolvedValue({ workspace: makeWorkspace(), apiKey: "key", client: { retrieval: { query: vi.fn() } } }) + mocks.listSourcesForWorkspace.mockResolvedValue([makeSource()]) + mocks.fetchDemoCatalog.mockRejectedValue(Object.assign(new Error("catalog unavailable"), { status: 503 })) + mocks.handleChatTurn.mockResolvedValue(Either.right({ threadId: "thread", messages: [ + { id: "user", role: "user", content: "question" }, { id: "assistant", role: "assistant", content: "answer" }, + ] })) + const result = await chatAnswerRouteService.answerChat({ body: { message: "question" } }) + expect(result.status).toBe(200) + expect(mocks.handleChatTurn).toHaveBeenCalledWith(expect.objectContaining({ sources: [makeSource()], retrievalPreparationFailures: [ + expect.objectContaining({ warning: expect.objectContaining({ scope: "demo", code: "demo_catalog_unavailable" }) }), + ] })) + }) + + it.each([401, 409, 503])("preserves upstream status %s when catalog failure leaves no searchable sources", async (status) => { + mocks.getAuthenticatedWithClient.mockResolvedValue({ workspace: makeWorkspace(), apiKey: "key", client: { retrieval: { query: vi.fn() } } }) + mocks.listSourcesForWorkspace.mockResolvedValue([]) + mocks.fetchDemoCatalog.mockRejectedValue(Object.assign(new Error("catalog unavailable"), { status })) + const result = await chatAnswerRouteService.answerChat({ body: { message: "question" } }) + expect(result.status).toBe(status) + expect(mocks.handleChatTurn).not.toHaveBeenCalled() + }) + + it("preserves catalog status inside an actual Effect FiberFailure", async () => { + mocks.getAuthenticatedWithClient.mockResolvedValue({ workspace: makeWorkspace(), apiKey: "key", client: { retrieval: { query: vi.fn() } } }) + mocks.listSourcesForWorkspace.mockResolvedValue([]) + mocks.fetchDemoCatalog.mockImplementation(() => Effect.runPromise(Effect.fail({ status: 503, message: "Catalog unavailable" }))) + const result = await chatAnswerRouteService.answerChat({ body: { message: "question" } }) + expect(result.status).toBe(503) + }) + + it("pins a shared media request and Blob key to the retrieval result revision", async () => { + mocks.getAuthenticatedWithClient.mockResolvedValue({ workspace: makeWorkspace(), apiKey: "key", client: { retrieval: { query: vi.fn() } } }) + mocks.parsedStorageWriteAsset.mockResolvedValue({ url: "https://blob.example/pinned.png" }) + mocks.handleChatTurn.mockImplementation(async (input) => { + const url = await input.hardenChatAssetUrl({ source: { ...makeSource(), demoKey: "shared", namespace: "__knowhere_demo__", + knowhereDocumentId: "shared-doc", knowhereJobId: null, jobResultId: "retrieval-revision" }, sourcePath: "pages/page-1.png" }) + expect(url).toBe("https://blob.example/pinned.png") + return Either.right({ threadId: "thread", messages: [ + { id: "user", role: "user", content: "question" }, { id: "assistant", role: "assistant", content: "answer" }, + ] }) + }) + await chatAnswerRouteService.answerChat({ body: { message: "question" } }) + expect(fetch).toHaveBeenCalledWith("https://demo.example/api/v1/demo/sources/shared/assets/pages/page-1.png?job_result_id=retrieval-revision") + expect(mocks.parsedStorageWriteAsset).toHaveBeenCalledWith(expect.objectContaining({ documentId: "shared-doc", revisionKey: "retrieval-revision" })) + }) + it("injects a resolver that matches connected assets by parser chunk id", async () => { const workspace = makeWorkspace() const client = { retrieval: { query: vi.fn() } } @@ -550,6 +642,7 @@ describe("chat route services", () => { createdAt: "2026-05-06T00:00:00.000Z", updatedAt: "2026-05-06T00:00:00.000Z", }, + citationSources: [], messages: [ { id: "message_1", diff --git a/src/domains/chat/route-threads.ts b/src/domains/chat/route-threads.ts index 3a851a6c..de0cc7d5 100644 --- a/src/domains/chat/route-threads.ts +++ b/src/domains/chat/route-threads.ts @@ -1,5 +1,9 @@ import { Effect } from "effect" +import { resolveCitationSources } from "./citation-sources" +import { sourceService } from "@/domains/sources/service" +import { knowhereDemoApi } from "@/integrations/knowhere-demo" +import type { SourceView } from "@/domains/sources/types" import { chatThreadService } from "@/domains/chat/thread-service" import { toChatMessageView, toChatThreadView } from "@/domains/chat/view" import { notebookRequestContext } from "@/domains/workspace/request-context" @@ -28,6 +32,7 @@ type ThreadInput = { type GetThreadBody = { readonly thread: ChatThreadView readonly messages: ChatMessageView[] + readonly citationSources: readonly SourceView[] } export type ArchiveThreadInput = { @@ -101,11 +106,16 @@ const getThreadEffect = (input: ThreadInput) => return routeResult.error(404, "Chat thread not found.") } + const messageViews = messages.map((message): ChatMessageView => toChatMessageView(message)) + const [sources, legacyDemoSources, catalog] = yield* Effect.tryPromise(() => Promise.all([ + sourceService.listForWorkspace(workspace.id), + sourceService.listLegacyDemoSources(workspace.id), + knowhereDemoApi.fetchCatalog().catch(() => null), + ])) return routeResult.ok({ thread: toChatThreadView(thread), - messages: messages.map((message): ChatMessageView => - toChatMessageView(message), - ), + messages: messageViews, + citationSources: resolveCitationSources({ messages: messageViews, sources: [...sources, ...legacyDemoSources], catalog, namespace: workspace.namespace }), }) }) diff --git a/src/domains/chat/service.test.ts b/src/domains/chat/service.test.ts index 27fce976..c2382c09 100644 --- a/src/domains/chat/service.test.ts +++ b/src/domains/chat/service.test.ts @@ -94,6 +94,48 @@ describe("handleChatTurn", () => { }); }); + it("answers from shared demo projections without local database rows", async () => { + const repository = makeRepository() + const sharedSource = { id: "demo:visible", title: "Shared", mimeType: "text/plain", status: "ready" as const, + knowhereDocumentId: "shared-doc", knowhereJobId: null, demoKey: "visible", namespace: "__knowhere_demo__", jobResultId: "catalog-revision" } + const query = vi.fn().mockResolvedValue({ namespace: "__knowhere_demo__", query: "question", routerUsed: "test", answerText: null, + results: [], referencedChunks: [] }) + const result = await handleChatTurn({ workspace: makeWorkspace(), sources: [sharedSource], question: "question", excludedSourceIds: [], + repository, retrieval: { query }, generateAnswer: async ({ searchSources }) => { + await searchSources({ query: "question" }) + return makeHarnessRunResult("Shared answer") + } }) + expect(Either.isRight(result)).toBe(true) + expect(query).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ namespace: "__knowhere_demo__", includeDocumentIds: ["shared-doc"] })) + }) + + it("removes historical demo rows from agent context while retaining their private exclusions", async () => { + const legacy = makeSource({ id: "legacy", demoKey: "demo", knowhereDocumentId: "old-demo" }) + const query = vi.fn().mockResolvedValue({ namespace: "default", query: "question", routerUsed: "test", answerText: null, results: [], referencedChunks: [] }) + const generateAnswer = vi.fn(async ({ searchSources }) => { + await searchSources({ query: "question" }) + return makeHarnessRunResult("Answer") + }) + await handleChatTurn({ workspace: makeWorkspace(), sources: [makeSource(), legacy], question: "question", excludedSourceIds: [], + repository: makeRepository(), retrieval: { query }, generateAnswer }) + expect(generateAnswer).toHaveBeenCalledWith(expect.objectContaining({ sources: [makeSource()] })) + expect(query).toHaveBeenCalledWith(expect.objectContaining({ excludeDocumentIds: ["old-demo"] })) + }) + + it.each(["workspace", "demo"])("rejects all deselected %s sources before persisting a turn", async (kind) => { + const source = kind === "workspace" ? makeSource() : { ...makeSource(), demoKey: "shared", namespace: "__knowhere_demo__" } + const repository = makeRepository() + const generateAnswer = vi.fn(async () => makeHarnessRunResult("Unexpected answer")) + const query = vi.fn() + const result = await handleChatTurn({ workspace: makeWorkspace(), sources: [source], question: "question", excludedSourceIds: [source.id], + repository, retrieval: { query }, generateAnswer }) + expect(Either.isLeft(result)).toBe(true) + if (Either.isLeft(result)) expect(result.left.status).toBe(409) + expect(repository.appendMessageToThread).not.toHaveBeenCalled() + expect(generateAnswer).not.toHaveBeenCalled() + expect(query).not.toHaveBeenCalled() + }) + it("rejects a turn with no local sources without calling retrieval", async () => { const retrieval = { query: vi.fn() }; const repository = makeRepository(); @@ -264,7 +306,7 @@ describe("handleChatTurn", () => { }); }); - it("answers in an empty folder without searching", async () => { + it("rejects an empty folder before persisting a turn", async () => { const retrieval = { query: vi.fn() }; const repository = makeRepository(); const generateAnswer = vi.fn(async ({ searchSources, folderScopeSourceIds }) => { @@ -287,9 +329,10 @@ describe("handleChatTurn", () => { repository, }); - expect(Either.isRight(result)).toBe(true); + expect(Either.isLeft(result)).toBe(true); + expect(repository.appendMessageToThread).not.toHaveBeenCalled(); + expect(generateAnswer).not.toHaveBeenCalled(); expect(retrieval.query).not.toHaveBeenCalled(); - expect(repository.appendMessageToThread).toHaveBeenCalled(); }); it("scopes retrieval to the ready documents in the current folder", async () => { diff --git a/src/domains/chat/service.ts b/src/domains/chat/service.ts index 0dc07170..cb7fcfde 100644 --- a/src/domains/chat/service.ts +++ b/src/domains/chat/service.ts @@ -1,4 +1,4 @@ -import { Effect, Either } from "effect" +import { Cause, Effect, Either } from "effect" import { answerQuestionWithRetrieval, @@ -7,8 +7,10 @@ import { type GenerateAnswer, type RetrievalClient, } from "." +import type { SourceView } from "@/domains/sources/types" +import type { ChatSource } from "./contracts" import { toChatMessageView } from "./view" -import type { ChatMessage, ChatThread, Source, Workspace } from "@/infrastructure/db/schema" +import type { ChatMessage, ChatThread, Workspace } from "@/infrastructure/db/schema" import { sharedLibraryNamespace } from "@/domains/sources/namespace" import type { ChatArtifactView, @@ -42,6 +44,7 @@ export type ChatRepository = { export type ChatTurnError = | { _tag: "NoReadySources"; message: string; status: 409 } + | { _tag: "NoSelectedSources"; message: string; status: 409 } | { _tag: "ThreadNotFound"; message: string; status: 404 } const noReadySources = { @@ -59,15 +62,18 @@ const threadNotFound = { export type ChatTurnValue = { threadId: string messages: [ChatMessageView, ChatMessageView] + citationSources?: readonly SourceView[] } type ChatTurnInput = { workspace: Workspace - sources: readonly Source[] + sources: readonly ChatSource[] question: string threadId?: string useAgentic?: boolean excludedSourceIds: readonly string[] + retrievalPreparationFailures?: AnswerQuestionInput["retrievalPreparationFailures"] + excludedWorkspaceDemoDocumentIds?: readonly string[] folderId?: string resolveFolderScopeSourceIds?: ( workspaceId: string, @@ -84,18 +90,25 @@ type ChatTurnInput = { /** Wrap a Promise as an Effect, treating rejections as defects. */ const tryPromiseOrDie = (f: () => Promise) => - Effect.tryPromise(f).pipe(Effect.catchAllCause(Effect.die)) + Effect.tryPromise(f).pipe(Effect.catchAllCause((cause) => Effect.die(Cause.squash(cause)))) export const handleChatTurnEffect = (input: ChatTurnInput) => Effect.gen(function* () { const readySources = input.sources.filter( - (source) => source.status === "ready" && source.knowhereDocumentId, + (source) => source.status === "ready" && source.knowhereDocumentId && (!source.demoKey || source.namespace === "__knowhere_demo__"), ) if (readySources.length === 0) { return yield* Effect.fail(noReadySources) } const folderScopeSourceIds = yield* resolveFolderScopeSourceIdsEffect(input) + const excludedSourceIds: ReadonlySet = new Set(input.excludedSourceIds) + const hasSelectedReadySource: boolean = readySources.some((source) => !excludedSourceIds.has(source.id) && + (folderScopeSourceIds === undefined || (!source.demoKey && folderScopeSourceIds.includes(source.id)))) + if (!hasSelectedReadySource) { + return yield* Effect.fail({ _tag: "NoSelectedSources" as const, status: 409 as const, + message: "Select at least one ready source before asking questions." }) + } const thread = input.threadId ? yield* tryPromiseOrDie(() => @@ -136,6 +149,11 @@ export const handleChatTurnEffect = (input: ChatTurnInput) => namespace: input.workspace.namespace, namespaces: [sharedLibraryNamespace], sources: readySources, + retrievalPreparationFailures: input.retrievalPreparationFailures, + excludedWorkspaceDemoDocumentIds: [...new Set([ + ...(input.excludedWorkspaceDemoDocumentIds ?? []), + ...input.sources.flatMap((source) => source.demoKey && source.namespace !== "__knowhere_demo__" && source.knowhereDocumentId ? [source.knowhereDocumentId] : []), + ])], useAgentic: input.useAgentic ?? true, excludedSourceIds: input.excludedSourceIds, folderScopeSourceIds, @@ -148,7 +166,7 @@ export const handleChatTurnEffect = (input: ChatTurnInput) => ? { resolveConnectedAssets: input.resolveConnectedAssets } : {}), messages: chatHistoryMessages, - }).pipe(Effect.catchAllCause(Effect.die)) + }).pipe(Effect.catchAllCause((cause) => Effect.die(Cause.squash(cause)))) const assistantMessage = yield* tryPromiseOrDie(() => input.repository.appendMessageToThread(input.workspace.id, { @@ -168,7 +186,8 @@ export const handleChatTurnEffect = (input: ChatTurnInput) => threadId: thread.id, messages: [ toChatMessageView(userMessage), - toChatMessageView(assistantMessage, answer.citations, answer.artifacts), + { ...toChatMessageView(assistantMessage, answer.citations, answer.artifacts), + ...(answer.retrievalWarnings ? { retrievalWarnings: answer.retrievalWarnings } : {}) }, ] as [ChatMessageView, ChatMessageView], } }) diff --git a/src/domains/chat/shared-retrieval.test.ts b/src/domains/chat/shared-retrieval.test.ts new file mode 100644 index 00000000..3db8d5bf --- /dev/null +++ b/src/domains/chat/shared-retrieval.test.ts @@ -0,0 +1,164 @@ +import { Effect } from "effect" +import { describe, expect, it, vi } from "vitest" +import type { RetrievalQueryParams, RetrievalQueryResponse } from "@ontos-ai/knowhere-sdk" +import type { HarnessRunResult } from "@/agent-harness" +import type { Source } from "@/infrastructure/db/schema" +import { answerQuestionWithRetrieval } from "./index" +import type { AnswerQuestionInput, GenerateAnswer } from "./contracts" + +vi.mock("@/lib/logger", () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } })) +vi.mock("@/integrations/memento/client", () => ({ listActivations: vi.fn().mockResolvedValue([]) })) + +const DEMO_NAMESPACE = "__knowhere_demo__" +const privateSource: Source = { + id: "private", workspaceId: "workspace", title: "Private", mimeType: "text/plain", sizeBytes: 1, + status: "ready", knowhereDocumentId: "private-doc", knowhereJobId: "private-job", demoKey: null, + failureReason: null, failureStage: null, stagedBlobPathname: null, stagedBlobUrl: null, + originalBlobPathname: null, originalBlobUrl: null, chunkCount: 1, folderId: null, + createdAt: new Date(0), updatedAt: new Date(0), deletedAt: null, +} +const sharedSource = { ...privateSource, id: "demo:visible", title: "Shared", demoKey: "visible", + knowhereDocumentId: "shared-doc", knowhereJobId: null, namespace: DEMO_NAMESPACE, jobResultId: "catalog-revision" } +const legacySource = { ...privateSource, id: "legacy", demoKey: "visible", knowhereDocumentId: "old-private-demo" } + +function makeResponse(namespace: string, results: RetrievalQueryResponse["results"] = []): RetrievalQueryResponse { + return { namespace, query: "question", routerUsed: "test", answerText: null, results, referencedChunks: [] } +} +function makeHarnessResult(): HarnessRunResult { + return { manifest: { text: "Available evidence", citations: [], artifacts: [], unresolved: [], memoryCitations: [] }, + memoryItems: [], trace: { ledger: { retrievalCount: 0, chunks: [], assets: [], evidence: [], stopReasons: [], failureReasons: [], decisionTraces: [] }, + finalized: true, priorTurnReads: [], toolCalls: [], imageHighlights: [], validationErrors: [], revisionsUsed: 0 } } +} +function makeInput(overrides: Partial = {}): AnswerQuestionInput { + return { question: "question", namespace: "default", sources: [privateSource, sharedSource, legacySource], + excludedSourceIds: [], messages: [], retrieval: { query: vi.fn(async (params: RetrievalQueryParams) => makeResponse(params.namespace ?? "default")) }, + generateAnswer: async ({ searchSources }) => { await searchSources({ query: "question" }); return makeHarnessResult() }, ...overrides } +} + +describe("shared demo retrieval", () => { + it("queries demo-only sources with an explicit include scope and no private namespace", async () => { + const input = makeInput({ sources: [sharedSource] }) + await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(input.retrieval.query).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ namespace: DEMO_NAMESPACE, includeDocumentIds: ["shared-doc"] })) + }) + + it("separates mixed scopes and always excludes historical private demos", async () => { + const input = makeInput() + await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(input.retrieval.query).toHaveBeenCalledTimes(2) + expect(input.retrieval.query).toHaveBeenCalledWith(expect.objectContaining({ namespace: "default", excludeDocumentIds: ["old-private-demo"] })) + expect(input.retrieval.query).toHaveBeenCalledWith(expect.objectContaining({ namespace: DEMO_NAMESPACE, includeDocumentIds: ["shared-doc"] })) + }) + + it("skips the shared query when all visible demos are deselected", async () => { + const input = makeInput({ sources: [sharedSource], excludedSourceIds: [sharedSource.id] }) + await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(input.retrieval.query).not.toHaveBeenCalled() + }) + + it("keeps a private folder separate from shared demos and intersects agent includes", async () => { + const input = makeInput({ folderScopeSourceIds: [privateSource.id, legacySource.id], + generateAnswer: async ({ searchSources }) => { await searchSources({ query: "question", includeDocumentIds: ["shared-doc", "old-private-demo"] }); return makeHarnessResult() } }) + await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(input.retrieval.query).not.toHaveBeenCalled() + }) + + it("intersects agent demo includes with the selected visible demos", async () => { + const input = makeInput({ sources: [sharedSource], generateAnswer: async ({ searchSources }) => { + await searchSources({ query: "question", includeDocumentIds: ["hidden-demo", "shared-doc"] }); return makeHarnessResult() + } }) + await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(input.retrieval.query).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ namespace: DEMO_NAMESPACE, includeDocumentIds: ["shared-doc"] })) + }) + + it("returns and persists a warning when private retrieval fails but demo evidence is available", async () => { + const input = makeInput({ retrieval: { query: vi.fn(async (params: RetrievalQueryParams) => { + if (params.namespace === "default") throw new Error("private unavailable") + return makeResponse(DEMO_NAMESPACE, [{ content: "Evidence", chunkType: "text", score: 1, source: { documentId: "shared-doc" } }]) + }) } }) + const answer = await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(answer).toMatchObject({ retrievalWarnings: [{ scope: "workspace", code: "retrieval_failed" }], + agentTrace: { retrievalWarnings: [{ scope: "workspace", code: "retrieval_failed" }] } }) + }) + + it("fails when a retrieval failure has no successful evidence even if the agent catches it", async () => { + const generateAnswer: GenerateAnswer = async ({ searchSources }) => { + try { await searchSources({ query: "question" }) } catch { /* Harness can catch tool errors. */ } + return makeHarnessResult() + } + const input = makeInput({ generateAnswer, retrieval: { query: vi.fn(async (params: RetrievalQueryParams) => { + if (params.namespace === "default") throw new Error("private unavailable") + return makeResponse(DEMO_NAMESPACE) + }) } }) + await expect(Effect.runPromise(answerQuestionWithRetrieval(input))).rejects.toThrow("private unavailable") + }) + it("does not treat an answer without evidence as recovery from a failed scope", async () => { + const input = makeInput({ retrieval: { query: vi.fn(async (params: RetrievalQueryParams) => { + if (params.namespace === "default") throw new Error("workspace unavailable") + return { ...makeResponse(DEMO_NAMESPACE), answerText: "I could not find evidence." } + }) } }) + await expect(Effect.runPromise(answerQuestionWithRetrieval(input))).rejects.toThrow() + }) + + it("warns about a failed demo scope while preserving private evidence and filters", async () => { + const input = makeInput({ retrieval: { query: vi.fn(async (params: RetrievalQueryParams) => { + if (params.namespace === DEMO_NAMESPACE) throw new Error("demo unavailable") + return makeResponse("default", [{ content: "Evidence", chunkType: "text", score: 1, source: { documentId: "private-doc" } }]) + }) }, generateAnswer: async ({ searchSources }) => { + await searchSources({ query: "question", signalPaths: ["table"], filterMode: "keep", threshold: 0.25, targetContent: "table" }) + return makeHarnessResult() + } }) + const answer = await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(answer).toMatchObject({ retrievalWarnings: [{ scope: "demo", code: "retrieval_failed" }] }) + expect(input.retrieval.query).toHaveBeenCalledWith(expect.objectContaining({ namespace: DEMO_NAMESPACE, + includeDocumentIds: ["shared-doc"], signalPaths: ["table"], filterMode: "keep", threshold: 0.25, dataType: 4 })) + }) + + it("keeps shared document IDs out of a private agent include scope", async () => { + const input = makeInput({ generateAnswer: async ({ searchSources }) => { + await searchSources({ query: "question", includeDocumentIds: ["shared-doc", "private-doc", "old-private-demo"] }) + return makeHarnessResult() + } }) + await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(input.retrieval.query).toHaveBeenCalledWith(expect.objectContaining({ namespace: "default", includeDocumentIds: ["private-doc"] })) + }) + + it("keeps a catalog preparation failure visible when private retrieval supplies evidence", async () => { + const warning = { scope: "demo" as const, code: "demo_catalog_unavailable", message: "Demo catalog is unavailable." } + const input = makeInput({ sources: [privateSource], retrievalPreparationFailures: [{ warning, cause: new Error("catalog unavailable") }], + retrieval: { query: vi.fn(async () => makeResponse("default", [{ content: "Evidence", chunkType: "text", score: 1, source: { documentId: "private-doc" } }])) } }) + const answer = await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(answer).toMatchObject({ retrievalWarnings: [warning], agentTrace: { retrievalWarnings: [warning] } }) + }) + + it("does not borrow page metadata from a different document revision", async () => { + const chunk = { ref: "actual", kind: "result" as const, chunkId: "stable-parser-id", content: "Evidence", contentPreview: "Evidence", + chunkType: "text", score: 1, source: { documentId: "shared-doc", namespace: DEMO_NAMESPACE, jobResultId: "actual-retrieval-revision" } } + const donor = { ...chunk, ref: "different-revision", source: { ...chunk.source, jobResultId: "newer-catalog-revision" }, metadata: { pageNums: [99] } } + const generated = makeHarnessResult() + const input = makeInput({ sources: [sharedSource], generateAnswer: async () => ({ ...generated, + manifest: { ...generated.manifest, citations: [{ ref: "actual" }] }, + trace: { ...generated.trace, ledger: { ...generated.trace.ledger, chunks: [chunk, donor] } } }) }) + const answer = await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(answer.citations[0]?.source).toMatchObject({ namespace: DEMO_NAMESPACE, jobResultId: "actual-retrieval-revision" }) + expect(answer.citations[0]?.pageCitationPageNumber).toBeUndefined() + }) + + it.each(["image", "table"] as const)("retains actual provenance for a displayed shared %s artifact", async (type) => { + const generated = makeHarnessResult() + const reference = { documentId: "shared-doc", namespace: DEMO_NAMESPACE, jobResultId: "actual-artifact-revision" } + const input = makeInput({ sources: [sharedSource], generateAnswer: async () => ({ ...generated, + manifest: { ...generated.manifest, artifacts: [{ type, ref: "asset", display: true, reason: "Requested source artifact" }] }, + trace: { ...generated.trace, ledger: { ...generated.trace.ledger, + assets: [{ ref: "asset", chunkRef: "chunk", type, label: "Shared artifact", source: reference, revisionKey: "actual-artifact-revision", assetUrl: "https://example.com/asset" }] } } }) }) + const answer = await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(answer.artifacts?.[0]?.citation?.source).toMatchObject(reference) + }) + + it("skips the private namespace when all private rows are deselected and a demo remains selected", async () => { + const input = makeInput({ excludedSourceIds: [privateSource.id] }) + await Effect.runPromise(answerQuestionWithRetrieval(input)) + expect(input.retrieval.query).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ namespace: DEMO_NAMESPACE, includeDocumentIds: ["shared-doc"] })) + }) + +}) diff --git a/src/domains/chat/types.ts b/src/domains/chat/types.ts index e10644f6..ddef39bd 100644 --- a/src/domains/chat/types.ts +++ b/src/domains/chat/types.ts @@ -6,11 +6,14 @@ export type RetrievalResultView = { readonly chunkType: string readonly score: number | null readonly chunkId?: string + readonly chunkRowId?: string readonly assetUrl?: string readonly pageCitationAssetUrl?: string readonly pageCitationPageNumber?: number readonly source: { readonly documentId?: string | null + readonly namespace?: string + readonly jobResultId?: string readonly sourceFileName?: string | null readonly sectionPath?: string | null } @@ -59,12 +62,19 @@ export type ChatArtifactView = { readonly citation?: ChatCitationView } +export type RetrievalWarning = { + readonly scope: "workspace" | "demo" + readonly code: string + readonly message: string +} + export type ChatMessageView = { readonly id: string readonly role: "user" | "assistant" readonly content: string readonly citations?: readonly ChatCitationView[] readonly artifacts?: readonly ChatArtifactView[] + readonly retrievalWarnings?: readonly RetrievalWarning[] } export type ChatThreadView = { diff --git a/src/domains/chat/view.ts b/src/domains/chat/view.ts index c11ea793..13fb9dfb 100644 --- a/src/domains/chat/view.ts +++ b/src/domains/chat/view.ts @@ -1,4 +1,5 @@ import { normalizeHighlightBoxes } from "@/agent-harness/image-highlights" +import { readChatAgentTrace } from "./agent-trace" import { deriveChatThreadTitle } from "./title" import type { ChatMessage, ChatThread } from "@/infrastructure/db/schema" import type { @@ -32,12 +33,14 @@ export function toChatMessageView( ? [...artifacts] : toPersistedArtifactViews(message.artifacts) + const retrievalWarnings = readChatAgentTrace(message.agentTrace)?.retrievalWarnings return { id: message.id, role: message.role === "assistant" ? "assistant" : "user", content: message.content, citations: citationViews, ...(artifactViews !== undefined ? { artifacts: artifactViews } : {}), + ...(retrievalWarnings?.length ? { retrievalWarnings } : {}), } } @@ -49,6 +52,8 @@ function toPersistedCitationViews(value: unknown): ChatCitationView[] | undefine return [ { + chunkId: getString(item.chunkId), + chunkRowId: getString(item.chunkRowId), chunkType: getString(item.chunkType) ?? "text", score: getNumber(item.score) ?? 0, assetUrl: getString(item.assetUrl), @@ -58,6 +63,8 @@ function toPersistedCitationViews(value: unknown): ChatCitationView[] | undefine highlightRegions: getHighlightRegions(item.highlightRegions), source: { documentId: getString(item.source.documentId), + namespace: getString(item.source.namespace), + jobResultId: getString(item.source.jobResultId), sourceFileName: getString(item.source.sourceFileName), sectionPath: getString(item.source.sectionPath), }, @@ -82,6 +89,8 @@ function toPersistedArtifactViews(value: unknown): ChatArtifactView[] | undefine const citation = isRecord(item.citation) && isRecord(item.citation.source) ? { + chunkId: getString(item.citation.chunkId), + chunkRowId: getString(item.citation.chunkRowId), chunkType: getString(item.citation.chunkType) ?? "text", score: getNumber(item.citation.score) ?? 0, assetUrl: getString(item.citation.assetUrl), @@ -97,6 +106,8 @@ function toPersistedArtifactViews(value: unknown): ChatArtifactView[] | undefine ), source: { documentId: getString(item.citation.source.documentId), + namespace: getString(item.citation.source.namespace), + jobResultId: getString(item.citation.source.jobResultId), sourceFileName: getString(item.citation.source.sourceFileName), sectionPath: getString(item.citation.source.sectionPath), }, diff --git a/src/domains/chunks/index.ts b/src/domains/chunks/index.ts index 7a38b886..010c84e4 100644 --- a/src/domains/chunks/index.ts +++ b/src/domains/chunks/index.ts @@ -19,6 +19,7 @@ export type ChunkKnowhereClient = { pageSize: number chunkType?: "text" | "image" | "table" | "page" includeAssetUrls: boolean + jobResultId?: string }, ): Promise<{ documentId?: string @@ -46,6 +47,8 @@ export type ChunkPageParams = { page: number pageSize: number chunkType?: ChunkReadType + jobResultId?: string + namespace?: string } export type ChunkPagePagination = { @@ -64,6 +67,8 @@ export function getChunkPageParams( searchParams: URLSearchParams, ): ChunkPageParams { const chunkType = parseChunkReadType(searchParams.get("chunkType")) + const jobResultId = searchParams.get("jobResultId")?.trim() + const namespace = searchParams.get("namespace")?.trim() return { page: normalizePositiveInteger(searchParams.get("page"), 1), pageSize: normalizePageSize( @@ -73,6 +78,8 @@ export function getChunkPageParams( ), ), ...(chunkType ? { chunkType } : {}), + ...(jobResultId ? { jobResultId } : {}), + ...(namespace ? { namespace } : {}), } } diff --git a/src/domains/chunks/normalization.ts b/src/domains/chunks/normalization.ts index 4e39ac57..80ca6812 100644 --- a/src/domains/chunks/normalization.ts +++ b/src/domains/chunks/normalization.ts @@ -10,6 +10,8 @@ type ParsedChunkNormalizationInput = { readonly chunkId: string readonly parserChunkId?: unknown readonly documentId?: string + readonly namespace?: string + readonly jobResultId?: string readonly sectionPath?: string | null readonly chunkType: unknown readonly contentSource?: unknown @@ -47,6 +49,8 @@ function createParsedChunkView( return { chunkId: input.chunkId, documentId: input.documentId, + namespace: input.namespace, + jobResultId: input.jobResultId, parserChunkId: getString(input.parserChunkId), sectionPath: input.sectionPath, type, @@ -134,6 +138,8 @@ function resolveCitationChunk( chunks: readonly ParsedChunkView[], ): ParsedChunkView | null { const documentChunks = getCitationDocumentChunks(citation, chunks) + const byIdentifier = findByCitationIdentifier(citation, documentChunks) + if (byIdentifier) return byIdentifier const byContent = findByContent(documentChunks, citation.content) if (byContent) return byContent @@ -150,8 +156,9 @@ function resolveCitationChunkByContent( citation: ChatCitationView, chunks: readonly ParsedChunkView[], ): ParsedChunkView | null { - return findByContent( - getCitationDocumentChunks(citation, chunks), + const documentChunks = getCitationDocumentChunks(citation, chunks) + return findByCitationIdentifier(citation, documentChunks) ?? findByContent( + documentChunks, citation.content, ) } @@ -249,8 +256,11 @@ function getCitationDocumentChunks( citation: ChatCitationView, chunks: readonly ParsedChunkView[], ): readonly ParsedChunkView[] { - if (!citation.source.documentId) return chunks - return chunks.filter((chunk) => chunk.documentId === citation.source.documentId) + return chunks.filter((chunk) => + (!citation.source.documentId || chunk.documentId === citation.source.documentId) && + (!citation.source.namespace || chunk.namespace === citation.source.namespace) && + (!citation.source.jobResultId || chunk.jobResultId === citation.source.jobResultId), + ) } function findByContent( @@ -379,3 +389,8 @@ export const parsedChunkNormalization = { resolveCitationChunkByContent, resolveConnectionTargets, } as const + +function findByCitationIdentifier(citation: ChatCitationView, chunks: readonly ParsedChunkView[]): ParsedChunkView | null { + const matches = chunks.filter((chunk) => citation.chunkRowId ? chunk.chunkId === citation.chunkRowId : Boolean(citation.chunkId && (chunk.parserChunkId === citation.chunkId || chunk.chunkId === citation.chunkId))) + return matches.length === 1 ? matches[0]! : null +} diff --git a/src/domains/chunks/read.test.ts b/src/domains/chunks/read.test.ts index 32bf8cd6..94c4b478 100644 --- a/src/domains/chunks/read.test.ts +++ b/src/domains/chunks/read.test.ts @@ -288,3 +288,13 @@ describe("readAllSourceChunks", () => { expect(chunks.map((chunk) => chunk.parserChunkId)).toEqual(["c1", "c2"]) }) }) + +describe("pinned source revision reads", () => { + it("bypasses the latest parsed snapshot and requests the cited job result", async () => { + const readChunks = vi.fn(async () => ({ document: { resultDirectoryPath: "parsed-storage:doc_1" }, chunks: [] })) + const listChunks = vi.fn(async () => ({ chunks: [], pagination: { totalPages: 1 } })) + await readSourceChunkPage({ client: { documents: { listChunks } }, knowledge: { readChunks } as unknown as Knowledge, source: { documentId: "doc_1", title: "Report", jobResultId: "saved_revision", namespace: "__knowhere_demo__" }, params: { page: 1, pageSize: 50 } }) + expect(readChunks).not.toHaveBeenCalled() + expect(listChunks).toHaveBeenCalledWith("doc_1", { page: 1, pageSize: 50, includeAssetUrls: true, jobResultId: "saved_revision" }) + }) +}) diff --git a/src/domains/chunks/read.ts b/src/domains/chunks/read.ts index 552ba383..52d8ef84 100644 --- a/src/domains/chunks/read.ts +++ b/src/domains/chunks/read.ts @@ -21,6 +21,8 @@ const loadAllPageSize = 200 type ReadableSource = { readonly documentId: string readonly title: string + readonly namespace?: string + readonly jobResultId?: string readonly revisionKey?: string | null } @@ -33,6 +35,7 @@ type DisplayReadClient = { readonly pageSize: number readonly chunkType?: ChunkReadType readonly includeAssetUrls: true + readonly jobResultId?: string }, ): Promise<{ readonly chunks: readonly DocumentChunk[] @@ -59,16 +62,18 @@ export async function readSourceChunkPage(input: { readonly source: ReadableSource readonly params: ChunkPageParams }): Promise { - const response = await input.knowledge.readChunks({ - documentId: input.source.documentId, - ...(input.source.revisionKey ? { revisionKey: input.source.revisionKey } : {}), - page: input.params.page, - pageSize: input.params.pageSize, - ...(input.params.chunkType ? { chunkType: input.params.chunkType } : {}), - }) - - if (shouldUseKnowledgeChunkResponse(response)) { - return toChunkPageFromKnowledgeResponse(response, input.source, input.params) + if (!input.source.jobResultId) { + const response = await input.knowledge.readChunks({ + documentId: input.source.documentId, + ...(input.source.revisionKey ? { revisionKey: input.source.revisionKey } : {}), + page: input.params.page, + pageSize: input.params.pageSize, + ...(input.params.chunkType ? { chunkType: input.params.chunkType } : {}), + }) + + if (shouldUseKnowledgeChunkResponse(response)) { + return toChunkPageFromKnowledgeResponse(response, input.source, input.params) + } } const remoteResponse = await input.client.documents.listChunks( @@ -78,6 +83,7 @@ export async function readSourceChunkPage(input: { pageSize: input.params.pageSize, ...(input.params.chunkType ? { chunkType: input.params.chunkType } : {}), includeAssetUrls: true, + ...(input.source.jobResultId ? { jobResultId: input.source.jobResultId } : {}), }, ) const chunks = remoteResponse.chunks.map((chunk) => @@ -86,7 +92,7 @@ export async function readSourceChunkPage(input: { input.source.title, input.source.documentId, ), - ) + ).map((chunk) => ({ ...chunk, namespace: input.source.namespace, jobResultId: input.source.jobResultId })) return { chunks, @@ -107,7 +113,7 @@ function toChunkPageFromKnowledgeResponse( params: ChunkPageParams, ): ChunkPage { const chunks = response.chunks.map((chunk) => - toParsedChunkViewFromReadChunk(chunk, source.title, source.documentId), + ({ ...toParsedChunkViewFromReadChunk(chunk, source.title, source.documentId), namespace: source.namespace, jobResultId: source.jobResultId }), ) return { @@ -136,51 +142,13 @@ export async function readAllSourceChunks(input: { const chunks: ParsedChunkView[] = [] let page = 1 let totalPages = 1 - do { - const response = await input.knowledge.readChunks({ - documentId: input.source.documentId, - ...(input.source.revisionKey - ? { revisionKey: input.source.revisionKey } - : {}), - page, - pageSize: loadAllPageSize, - ...(input.chunkType ? { chunkType: input.chunkType } : {}), + const result = await readSourceChunkPage({ + ...input, + params: { page, pageSize: loadAllPageSize, ...(input.chunkType ? { chunkType: input.chunkType } : {}) }, }) - if (shouldUseKnowledgeChunkResponse(response)) { - for (const chunk of response.chunks) { - chunks.push( - toParsedChunkViewFromReadChunk( - chunk, - input.source.title, - input.source.documentId, - ), - ) - } - totalPages = Math.max(1, response.totalPages ?? 1) - page += 1 - continue - } - - const remoteResponse = await input.client.documents.listChunks( - input.source.documentId, - { - page, - pageSize: loadAllPageSize, - ...(input.chunkType ? { chunkType: input.chunkType } : {}), - includeAssetUrls: true, - }, - ) - for (const chunk of remoteResponse.chunks) { - chunks.push( - toParsedChunkView( - chunk, - input.source.title, - input.source.documentId, - ), - ) - } - totalPages = Math.max(1, remoteResponse.pagination?.totalPages ?? 1) + chunks.push(...result.chunks) + totalPages = Math.max(1, result.pagination.totalPages) page += 1 } while (page <= totalPages) diff --git a/src/domains/chunks/types.ts b/src/domains/chunks/types.ts index 23129a36..360fdfd6 100644 --- a/src/domains/chunks/types.ts +++ b/src/domains/chunks/types.ts @@ -27,6 +27,8 @@ export type ParsedChunkView = { readonly parserChunkId?: string /** Knowhere document ID. Present when loaded through a Notebook source. */ readonly documentId?: string + readonly namespace?: string + readonly jobResultId?: string /** Human-readable section path from Knowhere, used to focus citations. */ readonly sectionPath?: string | null readonly type: ChunkType diff --git a/src/domains/demo/original-file.test.ts b/src/domains/demo/original-file.test.ts index 7d19a40b..9bd925cb 100644 --- a/src/domains/demo/original-file.test.ts +++ b/src/domains/demo/original-file.test.ts @@ -1,66 +1,23 @@ import { describe, expect, it } from "vitest" - -import { demoOriginalFile } from "@/domains/demo/original-file" +import { demoOriginalFile } from "./original-file" describe("demoOriginalFile", () => { - it("keeps public original URLs for demo source preview", () => { - expect( - demoOriginalFile.getPublicUrl( - makeDemoOriginalSource({ - originalUrl: "https://example.com/report.pdf", - }), - ), - ).toBe("https://example.com/report.pdf") - }) - - it("falls back to the Official Library file URL instead of Knowhere API originals", () => { - const source = makeDemoOriginalSource({ - originalUrl: - "https://api.knowhere.example/api/v1/demo/sources/demo-report/original", - sourceUrl: "https://example.com/library-report.pdf", - }) - - expect(demoOriginalFile.getPublicUrl(source)).toBe( - "https://example.com/library-report.pdf", - ) - expect(demoOriginalFile.toSourceOriginalFileView(source)).toMatchObject({ - url: "https://example.com/library-report.pdf", - pdfPreviewMode: "browser", - }) + it("uses a stable same-origin revision proxy for catalog originals", () => { + const source = { + demoSourceId: "demo-report", + jobResultId: "revision-1", + originalFile: { + url: "/api/v1/demo/sources/demo-report/original?job_result_id=revision-1", + mimeType: "application/pdf", sizeBytes: 1024, canDownload: true, + }, + } + expect(demoOriginalFile.getPublicUrl(source)).toBe("/api/demo-sources/demo-report/original?job_result_id=revision-1") + expect(demoOriginalFile.toSourceOriginalFileView(source)).toMatchObject({ canDownload: true }) }) - - it("returns no original URL for legacy demo originals without a public file", () => { - expect( - demoOriginalFile.getPublicUrl( - makeDemoOriginalSource({ - originalUrl: - "https://api.knowhere.example/api/v1/demo/sources/demo-report/original", - }), - ), - ).toBeNull() + it("does not retain signed or curated external URLs for shared original files", () => { + expect(demoOriginalFile.getPublicUrl({ + demoSourceId: "demo-report", jobResultId: "revision-2", + originalFile: { url: "https://storage.example/report.pdf?signature=expired", mimeType: "application/pdf", sizeBytes: 10, canDownload: false }, + })).toBe("/api/demo-sources/demo-report/original?job_result_id=revision-2") }) }) - -function makeDemoOriginalSource({ - originalUrl, - sourceUrl, -}: { - readonly originalUrl: string - readonly sourceUrl?: string -}): Parameters[0] { - return { - originalFile: { - url: originalUrl, - mimeType: "application/pdf", - sizeBytes: 1024, - canDownload: false, - }, - ...(sourceUrl - ? { - officialLibrary: { - sourceUrl, - }, - } - : {}), - } -} diff --git a/src/domains/demo/original-file.ts b/src/domains/demo/original-file.ts index e31b79ff..8289727f 100644 --- a/src/domains/demo/original-file.ts +++ b/src/domains/demo/original-file.ts @@ -1,30 +1,21 @@ import type { SourceOriginalFileView } from "@/domains/sources/types" type DemoOriginalSource = { + readonly demoSourceId: string + readonly jobResultId?: string readonly originalFile: { readonly url: string readonly mimeType: string readonly sizeBytes: number readonly canDownload: boolean } - readonly officialLibrary?: { - readonly sourceUrl: string - } } -export const demoOriginalFile = { - getPublicUrl, - toSourceOriginalFileView, -} as const - -function toSourceOriginalFileView( - source: DemoOriginalSource, -): SourceOriginalFileView | null { - const url = getPublicUrl(source) - if (!url) return null +export const demoOriginalFile = { getPublicUrl, toSourceOriginalFileView } as const +function toSourceOriginalFileView(source: DemoOriginalSource): SourceOriginalFileView { return { - url, + url: getPublicUrl(source), mimeType: source.originalFile.mimeType, sizeBytes: source.originalFile.sizeBytes, canDownload: source.originalFile.canDownload, @@ -32,31 +23,11 @@ function toSourceOriginalFileView( } } -function getPublicUrl(source: DemoOriginalSource): string | null { - const originalUrl = toPublicHttpUrl(source.originalFile.url) - if (originalUrl) return originalUrl - - return source.officialLibrary - ? toPublicHttpUrl(source.officialLibrary.sourceUrl) - : null -} - -function toPublicHttpUrl(value: string): string | null { - try { - const parsedUrl = new URL(value) - if (parsedUrl.protocol !== "http:" && parsedUrl.protocol !== "https:") { - return null - } - if (isDemoOriginalProxyPath(parsedUrl.pathname)) return null - return parsedUrl.toString() - } catch { - return null - } -} - -function isDemoOriginalProxyPath(pathname: string): boolean { - return ( - /^\/api\/v1\/demo\/sources\/[^/]+\/original\/?$/.test(pathname) || - /^\/api\/demo-sources\/[^/]+\/original\/?$/.test(pathname) - ) +function getPublicUrl(source: DemoOriginalSource): string { + const originalUrl: URL = new URL(source.originalFile.url, "https://notebook.invalid") + const jobResultId: string | null | undefined = source.jobResultId ?? originalUrl.searchParams.get("job_result_id") + const parameters: URLSearchParams = new URLSearchParams() + if (jobResultId) parameters.set("job_result_id", jobResultId) + const query: string = parameters.size > 0 ? `?${parameters.toString()}` : "" + return `/api/demo-sources/${encodeURIComponent(source.demoSourceId)}/original${query}` } diff --git a/src/domains/demo/route-selection.ts b/src/domains/demo/route-selection.ts new file mode 100644 index 00000000..bc1c17e8 --- /dev/null +++ b/src/domains/demo/route-selection.ts @@ -0,0 +1,67 @@ +import { Cause, Effect, Option, Runtime, Schema } from "effect" +import type { NextResponse } from "next/server" + +import { demoView } from "@/domains/demo/view" +import { sourceService } from "@/domains/sources/service" +import { notebookRequestContext } from "@/domains/workspace/request-context" +import { knowhereDemoApi } from "@/integrations/knowhere-demo" +import { nextRouteResponse } from "@/lib/next-route-response" +import { routeResult } from "@/lib/route-result" +import { logger } from "@/lib/logger" +import { formatUnknownForLog } from "@/lib/format-log-value" + +const SelectionRequest = Schema.Struct({ + demoSourceIds: Schema.Array(Schema.String.pipe(Schema.minLength(1))).pipe(Schema.minItems(1), Schema.maxItems(200)), +}) + +export function selectDemoSources(request: Request, shouldRestore: boolean): Promise { + return Effect.runPromise(Effect.gen(function* () { + const body = yield* Effect.tryPromise(() => routeResult.readJson(request)) + if (!body.ok) return nextRouteResponse.toNextResponse(routeResult.badRequest("Invalid request body.")) + const decoded = Schema.decodeUnknownEither(SelectionRequest)(body.value) + if (decoded._tag === "Left") return nextRouteResponse.toNextResponse(routeResult.badRequest("Select valid demo source IDs.")) + const demoSourceIds: readonly string[] = Array.from(new Set(decoded.right.demoSourceIds.map((id) => id.trim()))) + if (demoSourceIds.some((id) => id.length === 0)) return nextRouteResponse.toNextResponse(routeResult.badRequest("Select valid demo source IDs.")) + const context = yield* Effect.tryPromise(() => notebookRequestContext.getOptionalAuthenticated()) + if (!context) return nextRouteResponse.toNextResponse(routeResult.error(401, "Sign in to select demo sources.")) + const catalog = yield* Effect.tryPromise(() => knowhereDemoApi.fetchCatalog()) + const selectedSources = demoSourceIds.map((id) => catalog.sources.find((source) => source.demoSourceId === id)) + const missingSourceId: string | undefined = demoSourceIds.find((id) => !catalog.sources.some((source) => source.demoSourceId === id)) + if (missingSourceId) { + const isPreparing: boolean = catalog.officialLibrary.sources.some((source) => source.demoSourceId === missingSourceId && source.status !== "ready") || (catalog.importStatuses ?? []).some((source) => source.demoSourceId === missingSourceId && source.status !== "ready") + return nextRouteResponse.toNextResponse(routeResult.error(isPreparing ? 409 : 404, isPreparing ? "Selected demo source is still preparing." : "Selected demo source not found.")) + } + const hiddenSourceIds: ReadonlySet = shouldRestore ? new Set() : new Set(yield* Effect.tryPromise(() => sourceService.listHiddenDemoSourceIds(context.workspace.id))) + const sources = yield* Effect.all(selectedSources.flatMap((source) => { + if (!source || hiddenSourceIds.has(source.demoSourceId)) return [] + return [Effect.gen(function* () { + if (shouldRestore) yield* Effect.tryPromise(() => sourceService.restoreDemoSource(context.workspace.id, source.demoSourceId)) + return shouldRestore ? demoView.toSelectedSourceView(source) : demoView.toSourceView(source) + })] + }), { concurrency: 1 }) + return nextRouteResponse.toNextResponse(routeResult.ok({ sources })) + }).pipe(Effect.catchAll((error) => { + const status: number | undefined = readExpectedStatus(error) + if (status !== undefined) return Effect.succeed(nextRouteResponse.toNextResponse(routeResult.error(status, getStatusMessage(status)))) + logger.error("Demo source selection failed", { operation: shouldRestore ? "selectDemoSources" : "readDemoSourceMetadata", error: formatUnknownForLog(error) }) + return Effect.succeed(nextRouteResponse.toNextResponse(routeResult.error(502, "Demo sources could not be loaded right now. Please try again."))) + }))) +} + +function readExpectedStatus(error: unknown, depth: number = 0): number | undefined { + if (depth > 8) return undefined + if (Runtime.isFiberFailure(error)) { + const failure = Cause.failureOption(error[Runtime.FiberFailureCauseId]) + return Option.isSome(failure) ? readExpectedStatus(failure.value, depth + 1) : undefined + } + if (typeof error !== "object" || error === null) return undefined + if ("status" in error && typeof error.status === "number" && [401, 404, 409, 503].includes(error.status)) return error.status + return "cause" in error ? readExpectedStatus(error.cause, depth + 1) : undefined +} + +function getStatusMessage(status: number): string { + if (status === 401) return "Sign in to select demo sources." + if (status === 404) return "Selected demo source not found." + if (status === 409) return "Selected demo source is still preparing. Please try again shortly." + return "Demo sources are being prepared. Please try again shortly." +} diff --git a/src/domains/demo/view.test.ts b/src/domains/demo/view.test.ts index 593ff12b..98cf78f1 100644 --- a/src/domains/demo/view.test.ts +++ b/src/domains/demo/view.test.ts @@ -5,6 +5,16 @@ import { demoView } from "@/domains/demo/view" import type { DemoCatalog, DemoCitation, DemoSource } from "@/integrations/knowhere-demo" describe("demoView.toChatMessages", () => { + it("preserves shared namespace, revision and both chunk identifiers in seeded citations", () => { + const messages = demoView.toChatMessages(makeCatalog({ answer: "Report answer.", citations: [makeCitation({ namespace: "__knowhere_demo__", jobResultId: "revision-1" })] })) + expect(messages[1]?.citations?.[0]).toMatchObject({ chunkRowId: "demo-tsla-q4-2025:chunk", chunkId: "chunk", source: { namespace: "__knowhere_demo__", jobResultId: "revision-1" } }) + }) + it("preserves shared revision on normalized parsed chunks", () => { + const source = { id: "demo-report", kind: "demo" as const, demoSourceId: "demo-report", namespace: "__knowhere_demo__", jobResultId: "revision-1", title: "report.pdf", mimeType: "application/pdf", status: "ready" as const, documentId: "ddoc_report" } + const chunk = { id: "dchk_row", chunkId: "node-content", chunkType: "text", content: "content", sortOrder: 0, metadata: {} } + expect(demoView.toParsedChunkView(source, chunk)).toMatchObject({ chunkId: "dchk_row", parserChunkId: "node-content", namespace: "__knowhere_demo__", jobResultId: "revision-1" }) + }) + it("uses the live citation mapper so demo answers render title/pN chips", () => { const messages = demoView.toChatMessages( makeCatalog({ diff --git a/src/domains/demo/view.ts b/src/domains/demo/view.ts index 129c7fe9..317fc1f5 100644 --- a/src/domains/demo/view.ts +++ b/src/domains/demo/view.ts @@ -16,21 +16,32 @@ export const demoView = { toChatMessages, toParsedChunkView, toSourceView, + toSelectedSourceView, } as const function toSourceView(source: DemoSource): SourceView { + return buildSourceView(source, false) +} + +function toSelectedSourceView(source: DemoSource): SourceView { + return buildSourceView(source, true) +} + +function buildSourceView(source: DemoSource, isSelected: boolean): SourceView { const originalFile = demoOriginalFile.toSourceOriginalFileView(source) return { id: source.demoSourceId, kind: "demo", demoSourceId: source.demoSourceId, + namespace: source.namespace ?? "__knowhere_demo__", + ...(source.jobResultId ? { jobResultId: source.jobResultId } : {}), title: source.title, mimeType: source.mimeType, status: "ready", documentId: source.canonicalDocumentId, ...(originalFile ? { originalFile } : {}), - ...(source.officialLibrary + ...(source.officialLibrary && !isSelected ? { officialLibrary: { librarySourceId: source.officialLibrary.librarySourceId, @@ -85,6 +96,8 @@ function toDemoRetrievalResult( ): PageCitationAssetRetrievalResult { return { content: citation.content, + chunkId: citation.chunkId, + chunkRowId: citation.canonicalChunkId, chunkType: citation.chunkType, score: 0.95, ...(citation.pageCitationAssetUrl @@ -98,6 +111,8 @@ function toDemoRetrievalResult( : {}), source: { documentId: citation.canonicalDocumentId, + ...(citation.namespace ? { namespace: citation.namespace } : {}), + ...(citation.jobResultId ? { jobResultId: citation.jobResultId } : {}), sourceFileName: citation.source.sourceFileName, sectionPath: citation.source.sectionPath, }, @@ -112,6 +127,8 @@ function toParsedChunkView( chunkId: chunk.id, parserChunkId: chunk.chunkId, documentId: source.documentId, + namespace: source.namespace, + jobResultId: source.jobResultId, sectionPath: chunk.sectionPath, chunkType: chunk.chunkType, content: chunk.content, diff --git a/src/domains/demo/workspace-source-resolution.test.ts b/src/domains/demo/workspace-source-resolution.test.ts new file mode 100644 index 00000000..0ac37c69 --- /dev/null +++ b/src/domains/demo/workspace-source-resolution.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it } from "vitest" +import type { Source } from "@/infrastructure/db/schema" +import type { DemoCatalog } from "@/integrations/knowhere-demo" +import { resolveWorkspaceDemoSources } from "./workspace-source-resolution" + +const catalog: DemoCatalog = { officialLibrary: { categories: [], sources: [] }, sources: [{ + demoSourceId: "demo-report", canonicalDocumentId: "ddoc_report", namespace: "__knowhere_demo__", jobResultId: "revision-1", + title: "report.pdf", mimeType: "application/pdf", sizeBytes: 10, status: "ready", chunkCount: 4, + originalFile: { url: "/api/v1/demo/sources/demo-report/original", mimeType: "application/pdf", sizeBytes: 10, canDownload: true }, examples: [], +}] } +const legacySource: Source = { + id: "source-old-copy", workspaceId: "workspace-1", title: "report.pdf", mimeType: "application/pdf", sizeBytes: 10, status: "ready", + failureReason: null, failureStage: null, knowhereJobId: null, knowhereDocumentId: "private-copy", + stagedBlobPathname: null, stagedBlobUrl: null, originalBlobPathname: null, originalBlobUrl: null, demoKey: "demo-report", chunkCount: 4, folderId: null, + createdAt: new Date(0), updatedAt: new Date(0), deletedAt: null, +} +describe("resolveWorkspaceDemoSources", () => { + it("replaces every legacy demo row with the current shared catalog identity", () => { + const result = resolveWorkspaceDemoSources([legacySource], catalog) + expect(result.workspaceSources).toEqual([]) + expect(result.demoSources).toEqual([expect.objectContaining({ id: "demo-report", kind: "demo", documentId: "ddoc_report", namespace: "__knowhere_demo__", jobResultId: "revision-1" })]) + }) + it("preserves only private rows while respecting hidden shared selections", () => { + const privateSource: Source = { ...legacySource, id: "source-private", demoKey: null } + const result = resolveWorkspaceDemoSources([legacySource, privateSource], catalog, new Set(["demo-report"])) + expect(result.workspaceSources).toEqual([privateSource]) + expect(result.demoSources).toEqual([]) + }) + it("marks explicitly selected official entries as ordinary queryable shared sources", () => { + const source = catalog.sources[0]! + const officialCatalog: DemoCatalog = { ...catalog, sources: [{ ...source, officialLibrary: { + librarySourceId: "official-report", categoryId: "reports", title: "report.pdf", sourceUrl: "https://example.com/report.pdf", mimeType: "application/pdf", status: "ready", + } }] } + const result = resolveWorkspaceDemoSources([], officialCatalog, new Set(), new Set(["demo-report"])) + expect(result.demoSources[0]?.officialLibrary).toBeUndefined() + expect(result.demoSources[0]?.kind).toBe("demo") + }) +}) diff --git a/src/domains/demo/workspace-source-resolution.ts b/src/domains/demo/workspace-source-resolution.ts index e14339f8..1a9ac869 100644 --- a/src/domains/demo/workspace-source-resolution.ts +++ b/src/domains/demo/workspace-source-resolution.ts @@ -1,70 +1,25 @@ +import { demoView } from "@/domains/demo/view" +import type { SourceView } from "@/domains/sources/types" import type { Source } from "@/infrastructure/db/schema" import type { DemoCatalog } from "@/integrations/knowhere-demo" type WorkspaceDemoSourceResolution = { - readonly materializedDemoSourceIds: ReadonlySet readonly workspaceSources: readonly Source[] + readonly demoSources: readonly SourceView[] } export function resolveWorkspaceDemoSources( sources: readonly Source[], catalog: DemoCatalog, + hiddenDemoSourceIds: ReadonlySet = new Set(), + selectedDemoSourceIds: ReadonlySet = new Set(), ): WorkspaceDemoSourceResolution { - const canonicalDocumentIdByDemoSourceId: Map = new Map( - catalog.sources.map((source) => [ - source.demoSourceId, - source.canonicalDocumentId, - ]), - ) - const workspaceSources: Source[] = sources.filter( - (source) => - !isLegacyCanonicalDemoSource(source, canonicalDocumentIdByDemoSourceId), - ) - const materializedDemoSourceIds: Set = new Set( - workspaceSources.flatMap((source) => { - if (!isMaterializedDemoSource(source, canonicalDocumentIdByDemoSourceId)) { - return [] - } - return source.demoKey ? [source.demoKey] : [] - }), - ) - return { - materializedDemoSourceIds, - workspaceSources, - } -} - -function isLegacyCanonicalDemoSource( - source: Source, - canonicalDocumentIdByDemoSourceId: ReadonlyMap, -): boolean { - if (!source.demoKey) return false - if ( - source.knowhereJobId === null && - (source.knowhereDocumentId === null || - source.knowhereDocumentId.startsWith("demo-doc-")) - ) { - return true + workspaceSources: sources.filter((source) => source.demoKey === null), + demoSources: catalog.sources + .filter((source) => !hiddenDemoSourceIds.has(source.demoSourceId)) + .map((source) => selectedDemoSourceIds.has(source.demoSourceId) + ? demoView.toSelectedSourceView(source) + : demoView.toSourceView(source)), } - - const canonicalDocumentId = canonicalDocumentIdByDemoSourceId.get( - source.demoKey, - ) - if (canonicalDocumentId === undefined) return false - return source.knowhereDocumentId === canonicalDocumentId -} - -function isMaterializedDemoSource( - source: Source, - canonicalDocumentIdByDemoSourceId: ReadonlyMap, -): boolean { - if (!source.demoKey || !source.knowhereDocumentId) return false - const canonicalDocumentId = canonicalDocumentIdByDemoSourceId.get( - source.demoKey, - ) - return ( - canonicalDocumentId === undefined || - source.knowhereDocumentId !== canonicalDocumentId - ) } diff --git a/src/domains/sources/demo-source-repository.ts b/src/domains/sources/demo-source-repository.ts index 71f92618..b8a37617 100644 --- a/src/domains/sources/demo-source-repository.ts +++ b/src/domains/sources/demo-source-repository.ts @@ -1,6 +1,6 @@ import "server-only" -import { and, eq, isNotNull, or, sql } from "drizzle-orm" +import { and, eq, isNotNull, isNull, or, sql } from "drizzle-orm" import { Effect } from "effect" import { DbClient } from "@/infrastructure/db" @@ -21,6 +21,11 @@ type UpsertMaterializedDemoSourceInput = { } type DemoSourceRepository = { + readonly listLegacyDemoSourcesEffect: (workspaceId: string) => Effect.Effect + readonly findLegacyDemoSourceEffect: (workspaceId: string, sourceId: string) => Effect.Effect + readonly listLegacyDemoDocumentIdsEffect: (workspaceId: string) => Effect.Effect + readonly listSelectedDemoSourceIdsEffect: (workspaceId: string) => Effect.Effect + readonly restoreDemoSourceEffect: (workspaceId: string, demoSourceId: string) => Effect.Effect readonly listHiddenDemoSourceIdsEffect: ( workspaceId: string, ) => Effect.Effect @@ -34,6 +39,38 @@ type DemoSourceRepository = { ) => Effect.Effect } +const listLegacyDemoSourcesEffect: DemoSourceRepository["listLegacyDemoSourcesEffect"] = Effect.fn("demoSources.listLegacySources")(function* (workspaceId: string) { + const db = yield* DbClient + return yield* Effect.promise(() => db.select().from(sources).where(and(eq(sources.workspaceId, workspaceId), isNotNull(sources.demoKey)))) +}) + +const findLegacyDemoSourceEffect: DemoSourceRepository["findLegacyDemoSourceEffect"] = Effect.fn("demoSources.findLegacySource")(function* (workspaceId: string, sourceId: string) { + if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(sourceId)) return null + const db = yield* DbClient + const rows = yield* Effect.promise(() => db.select().from(sources).where(and(eq(sources.workspaceId, workspaceId), eq(sources.id, sourceId), isNotNull(sources.demoKey))).limit(1)) + return rows[0] ?? null +}) + +const listLegacyDemoDocumentIdsEffect: DemoSourceRepository["listLegacyDemoDocumentIdsEffect"] = Effect.fn("demoSources.listLegacyDocumentIds")(function* (workspaceId: string) { + const db = yield* DbClient + const rows = yield* Effect.promise(() => db.select({ documentId: sources.knowhereDocumentId }).from(sources).where(and(eq(sources.workspaceId, workspaceId), isNotNull(sources.demoKey), isNotNull(sources.knowhereDocumentId)))) + return rows.flatMap((row) => row.documentId ? [row.documentId] : []) +}) + +const listSelectedDemoSourceIdsEffect: DemoSourceRepository["listSelectedDemoSourceIdsEffect"] = Effect.fn("demoSources.listSelected")(function* (workspaceId: string) { + const db = yield* DbClient + const rows = yield* Effect.promise(() => db.select({ demoSourceId: demoSourceVisibilities.demoSourceId }).from(demoSourceVisibilities).where(and(eq(demoSourceVisibilities.workspaceId, workspaceId), isNull(demoSourceVisibilities.hiddenAt), isNull(demoSourceVisibilities.deletedAt)))) + return rows.map((row) => row.demoSourceId) +}) + +const restoreDemoSourceEffect: DemoSourceRepository["restoreDemoSourceEffect"] = Effect.fn("demoSources.restore")(function* (workspaceId: string, demoSourceId: string) { + const db = yield* DbClient + yield* Effect.promise(() => db.insert(demoSourceVisibilities).values({ workspaceId, demoSourceId, hiddenAt: null, deletedAt: null }).onConflictDoUpdate({ + target: [demoSourceVisibilities.workspaceId, demoSourceVisibilities.demoSourceId], + set: { hiddenAt: null, deletedAt: null, updatedAt: sql`now()` }, + })) +}) + const listHiddenDemoSourceIdsEffect: DemoSourceRepository["listHiddenDemoSourceIdsEffect"] = (workspaceId: string) => Effect.gen(function* () { @@ -138,6 +175,11 @@ const upsertMaterializedDemoSourceEffect: DemoSourceRepository["upsertMaterializ }) export const demoSourceRepository: DemoSourceRepository = { + listLegacyDemoSourcesEffect, + findLegacyDemoSourceEffect, + listLegacyDemoDocumentIdsEffect, + listSelectedDemoSourceIdsEffect, + restoreDemoSourceEffect, listHiddenDemoSourceIdsEffect, hideDemoSourceEffect, upsertMaterializedDemoSourceEffect, diff --git a/src/domains/sources/remote-library.test.ts b/src/domains/sources/remote-library.test.ts index b9e3bb91..99ae8289 100644 --- a/src/domains/sources/remote-library.test.ts +++ b/src/domains/sources/remote-library.test.ts @@ -31,6 +31,14 @@ const localSource: Source = { } describe("listRemoteLibrarySourceViews", () => { + it("does not reintroduce hidden or deleted private demo copies as remote rows", async () => { + const sources = await Effect.runPromise(listRemoteLibrarySourceViews({ + workspace: { namespace: "private" }, localSources: [], excludedDocumentIds: new Set(["doc-old-demo"]), + client: { documents: { list: async () => ({ documents: [{ documentId: "doc-old-demo", namespace: "default", status: "active", sourceFileName: "report.pdf", documentMetadata: { createdByClient: "notebook" } }] }) } }, + })) + expect(sources).toEqual([]) + }) + it("keeps notebook, cli, and mcp remotes and hides other origins", async () => { const list = vi.fn( async (params?: { readonly namespace?: string }) => { diff --git a/src/domains/sources/remote-library.ts b/src/domains/sources/remote-library.ts index 77746d18..ddd95d30 100644 --- a/src/domains/sources/remote-library.ts +++ b/src/domains/sources/remote-library.ts @@ -68,6 +68,7 @@ type RemoteLibraryProjectionInput = { readonly workspace: RemoteLibraryWorkspace readonly client: RemoteDocumentClient readonly localSources: readonly Source[] + readonly excludedDocumentIds?: ReadonlySet } type RemoteLibraryLocalizationInput = RemoteLibraryProjectionInput & { @@ -158,6 +159,7 @@ export function listRemoteLibrarySourceViews( (document) => isNotebookVisibleRemoteDocument(document) && !localDocumentIds.has(document.documentId) && + !input.excludedDocumentIds?.has(document.documentId) && !matchesActiveNotebookParsingSource(document, input.localSources), ) diff --git a/src/domains/sources/repository.ts b/src/domains/sources/repository.ts index 3b92508e..12869de7 100644 --- a/src/domains/sources/repository.ts +++ b/src/domains/sources/repository.ts @@ -5,6 +5,11 @@ import { sourceParseResultRepository } from "./source-parse-result-repository" import { sourceRowRepository } from "./source-row-repository" type SourceRepository = { + readonly listLegacyDemoSourcesEffect: typeof demoSourceRepository.listLegacyDemoSourcesEffect + readonly findLegacyDemoSourceEffect: typeof demoSourceRepository.findLegacyDemoSourceEffect + readonly listLegacyDemoDocumentIdsEffect: typeof demoSourceRepository.listLegacyDemoDocumentIdsEffect + readonly listSelectedDemoSourceIdsEffect: typeof demoSourceRepository.listSelectedDemoSourceIdsEffect + readonly restoreDemoSourceEffect: typeof demoSourceRepository.restoreDemoSourceEffect readonly findInWorkspaceEffect: typeof sourceRowRepository.findInWorkspaceEffect readonly findByKnowhereDocumentIdEffect: typeof sourceRowRepository.findByKnowhereDocumentIdEffect readonly listForWorkspaceEffect: typeof sourceRowRepository.listForWorkspaceEffect @@ -30,6 +35,11 @@ type SourceRepository = { } export const sourceRepository: SourceRepository = { + listLegacyDemoSourcesEffect: demoSourceRepository.listLegacyDemoSourcesEffect, + findLegacyDemoSourceEffect: demoSourceRepository.findLegacyDemoSourceEffect, + listLegacyDemoDocumentIdsEffect: demoSourceRepository.listLegacyDemoDocumentIdsEffect, + listSelectedDemoSourceIdsEffect: demoSourceRepository.listSelectedDemoSourceIdsEffect, + restoreDemoSourceEffect: demoSourceRepository.restoreDemoSourceEffect, findInWorkspaceEffect: sourceRowRepository.findInWorkspaceEffect, findByKnowhereDocumentIdEffect: sourceRowRepository.findByKnowhereDocumentIdEffect, diff --git a/src/domains/sources/route-archive.test.ts b/src/domains/sources/route-archive.test.ts new file mode 100644 index 00000000..7873901a --- /dev/null +++ b/src/domains/sources/route-archive.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from "vitest" +import type { Source } from "@/infrastructure/db/schema" +import { createSourceRouteService } from "./route-service" + +const sharedSource = { demoSourceId: "demo-report", canonicalDocumentId: "ddoc_report", namespace: "__knowhere_demo__", jobResultId: "revision-1", title: "report.pdf", mimeType: "application/pdf", sizeBytes: 10, status: "ready" as const, chunkCount: 4, originalFile: { url: "/api/v1/demo/sources/demo-report/original", mimeType: "application/pdf", sizeBytes: 10, canDownload: true }, examples: [] } +const localSource: Source = { id: "81ec8318-ae96-4c17-85fc-64ece5f752f5", workspaceId: "workspace-1", title: "report.pdf", mimeType: "application/pdf", sizeBytes: 10, status: "ready", failureReason: null, failureStage: null, knowhereJobId: null, knowhereDocumentId: "ddoc_report", stagedBlobPathname: null, stagedBlobUrl: null, originalBlobPathname: null, originalBlobUrl: null, demoKey: "demo-report", chunkCount: 4, folderId: null, createdAt: new Date(0), updatedAt: new Date(0), deletedAt: null } +function createArchiveService(source: Source | null = null) { + const archive = vi.fn(async () => undefined) + const softDelete = vi.fn(async () => true) + const hideDemoSource = vi.fn(async () => undefined) + const fetchCatalog = vi.fn(async () => ({ sources: [sharedSource], officialLibrary: { categories: [], sources: [] } })) + const service = createSourceRouteService({ + demoApi: { fetchCatalog }, + ensureWorkspace: vi.fn(async () => ({ id: "workspace-1", userId: "user-1", namespace: "private", createdAt: new Date(0) })), + requireUser: vi.fn(async () => ({ id: "user-1", email: null, name: null })), + ensureApiKeyForWorkspace: vi.fn(async () => "jwt"), + makeKnowhereClient: vi.fn(() => ({ documents: { archive, listChunks: vi.fn() }, jobs: { create: vi.fn(), get: vi.fn(), upload: vi.fn() } })), + sourceService: { findInWorkspace: vi.fn(async () => source), findByKnowhereDocumentId: vi.fn(async () => localSource), hideDemoSource, softDelete }, + }) + return { service, archive, hideDemoSource, softDelete, fetchCatalog } +} +describe("shared demo removal", () => { + it("hides a stale local demo row without deleting its old citation metadata", async () => { + const operations = createArchiveService(localSource) + expect((await operations.service.archiveSource({ sourceId: localSource.id, cookieHeader: "" })).status).toBe(200) + expect(operations.hideDemoSource).toHaveBeenCalledWith("workspace-1", "demo-report") + expect(operations.archive).not.toHaveBeenCalled() + expect(operations.softDelete).not.toHaveBeenCalled() + }) + it("guards a stale non-demo UUID referencing a shared canonical document", async () => { + const operations = createArchiveService({ ...localSource, demoKey: null }) + expect((await operations.service.archiveSource({ sourceId: localSource.id, cookieHeader: "" })).status).toBe(200) + expect(operations.archive).not.toHaveBeenCalled() + expect(operations.softDelete).not.toHaveBeenCalled() + }) + it("guards shared remote IDs and only updates visibility", async () => { + const operations = createArchiveService() + expect((await operations.service.archiveSource({ sourceId: "knowhere-doc:__knowhere_demo__:ddoc_report", cookieHeader: "" })).status).toBe(200) + expect(operations.hideDemoSource).toHaveBeenCalledWith("workspace-1", "demo-report") + expect(operations.archive).not.toHaveBeenCalled() + }) + it("hides a stale remote ID for an old personal demo copy without destroying citation metadata", async () => { + const operations = createArchiveService() + expect((await operations.service.archiveSource({ sourceId: "knowhere-doc:default:doc-old-copy", cookieHeader: "" })).status).toBe(200) + expect(operations.hideDemoSource).toHaveBeenCalledWith("workspace-1", "demo-report") + expect(operations.archive).not.toHaveBeenCalled() + expect(operations.softDelete).not.toHaveBeenCalled() + }) + it("archives a known private source independently of demo catalog availability", async () => { + const operations = createArchiveService({ ...localSource, demoKey: null, knowhereDocumentId: "doc-private" }) + operations.fetchCatalog.mockRejectedValue(new Error("catalog unavailable")) + expect((await operations.service.archiveSource({ sourceId: localSource.id, cookieHeader: "" })).status).toBe(200) + expect(operations.fetchCatalog).not.toHaveBeenCalled() + expect(operations.archive).toHaveBeenCalledWith("doc-private") + expect(operations.softDelete).toHaveBeenCalledWith("workspace-1", localSource.id) + }) + it("never archives an unknown shared document disguised as a default namespace remote", async () => { + const operations = createArchiveService() + expect((await operations.service.archiveSource({ sourceId: "knowhere-doc:default:ddoc_unknown", cookieHeader: "" })).status).toBe(404) + expect(operations.archive).not.toHaveBeenCalled() + }) + it("never archives unknown shared remote documents", async () => { + const operations = createArchiveService() + expect((await operations.service.archiveSource({ sourceId: "knowhere-doc:__knowhere_demo__:ddoc_unknown", cookieHeader: "" })).status).toBe(404) + expect(operations.archive).not.toHaveBeenCalled() + }) +}) diff --git a/src/domains/sources/route-archive.ts b/src/domains/sources/route-archive.ts index dc968ece..2221f582 100644 --- a/src/domains/sources/route-archive.ts +++ b/src/domains/sources/route-archive.ts @@ -1,6 +1,7 @@ import { Effect } from "effect" import type { Source } from "@/infrastructure/db/schema" +import type { DemoCatalog } from "@/integrations/knowhere-demo" import { routeResult } from "@/lib/route-result" import { getClientForWorkspace } from "./route-dependencies" import { decodeRemoteSourceId } from "./remote-library" @@ -53,6 +54,34 @@ const archiveSourceEffect = ( deps.sourceService.findInWorkspace(workspace.id, input.sourceId), ) + if (source?.demoKey) { + yield* Effect.tryPromise(() => deps.sourceService.hideDemoSource(workspace.id, source.demoKey ?? "")) + return routeResult.ok({ id: input.sourceId, archived: true as const }) + } + + const remoteSource = decodeRemoteSourceId(input.sourceId) + const documentId: string | null | undefined = source?.knowhereDocumentId ?? remoteSource?.documentId + const canReferenceSharedDemo: boolean = + (!source && !remoteSource) || + remoteSource?.namespace === "__knowhere_demo__" || + documentId?.startsWith("ddoc_") === true || + documentId?.startsWith("demo-doc-") === true + const catalog: DemoCatalog = canReferenceSharedDemo + ? yield* Effect.tryPromise(() => deps.demoApi.fetchCatalog()) + : { sources: [], officialLibrary: { categories: [], sources: [] } } + const sharedSource = catalog.sources.find((candidate) => + candidate.demoSourceId === input.sourceId || + candidate.canonicalDocumentId === source?.knowhereDocumentId || + candidate.canonicalDocumentId === remoteSource?.documentId, + ) + if (sharedSource) { + yield* Effect.tryPromise(() => deps.sourceService.hideDemoSource(workspace.id, sharedSource.demoSourceId)) + return routeResult.ok({ id: input.sourceId, archived: true as const }) + } + if (remoteSource?.namespace === "__knowhere_demo__" || documentId?.startsWith("ddoc_") || documentId?.startsWith("demo-doc-")) { + return routeResult.error(404, "Shared demo source not found.") + } + if (source) { if (source.knowhereDocumentId) { yield* archiveKnowhereDocument( @@ -67,22 +96,21 @@ const archiveSourceEffect = ( return routeResult.ok({ id: input.sourceId, archived: true as const }) } - const catalog = yield* Effect.tryPromise(() => deps.demoApi.fetchCatalog()) - const isDemoSource = catalog.sources.some( - (candidate) => candidate.demoSourceId === input.sourceId, - ) - if (isDemoSource) { - yield* Effect.tryPromise(() => - deps.sourceService.hideDemoSource(workspace.id, input.sourceId), - ) - return routeResult.ok({ id: input.sourceId, archived: true as const }) - } - - const remoteSource = decodeRemoteSourceId(input.sourceId) if (!remoteSource) { return routeResult.error(404, "Source not found.") } + const localSource = yield* Effect.tryPromise(() => + deps.sourceService.findByKnowhereDocumentId( + workspace.id, + remoteSource.documentId, + ), + ) + if (localSource?.demoKey) { + yield* Effect.tryPromise(() => deps.sourceService.hideDemoSource(workspace.id, localSource.demoKey ?? "")) + return routeResult.ok({ id: input.sourceId, archived: true as const }) + } + yield* archiveKnowhereDocument( workspace.id, input.cookieHeader, @@ -90,12 +118,6 @@ const archiveSourceEffect = ( deps, ) - const localSource = yield* Effect.tryPromise(() => - deps.sourceService.findByKnowhereDocumentId( - workspace.id, - remoteSource.documentId, - ), - ) if (localSource) { yield* cleanupLocalSource(workspace.id, localSource, deps) } diff --git a/src/domains/sources/route-chunks.ts b/src/domains/sources/route-chunks.ts index 9cfc99e2..8318c951 100644 --- a/src/domains/sources/route-chunks.ts +++ b/src/domains/sources/route-chunks.ts @@ -1,4 +1,4 @@ -import { Effect } from "effect" +import { Cause, Effect, Option, Runtime } from "effect" import { demoView } from "@/domains/demo/view" import { readAllSourceChunks, readSourceChunkPage } from "@/domains/chunks/read" @@ -7,6 +7,7 @@ import type { ParsedChunkView } from "@/domains/chunks/types" import type { DemoChunkPage } from "@/integrations/knowhere-demo" import { logger } from "@/lib/logger" import { routeResult } from "@/lib/route-result" +import { getCompatibleNamespaces } from "./namespace" import { displayReadUnavailable } from "./display-read-unavailable" import { decodeRemoteSourceId, @@ -57,11 +58,12 @@ const loadSourceChunksEffect = ( ) => Effect.gen(function* () { if (!sourceRowRepository.isWorkspaceSourceId(input.sourceId)) { + if (decodeRemoteSourceId(input.sourceId)) { + const remoteResult = yield* loadRemoteChunkPageEffect(input, deps) + return remoteResult ?? sourceNotFound() + } const demoResult = yield* loadDemoChunkPageEffect(input, deps) - if (demoResult) return demoResult - - const remoteResult = yield* loadRemoteChunkPageEffect(input, deps) - return remoteResult ?? sourceNotFound() + return demoResult ?? sourceNotFound() } const user = yield* Effect.tryPromise(() => deps.getCurrentUser()) @@ -72,24 +74,17 @@ const loadSourceChunksEffect = ( const workspace = yield* Effect.tryPromise(() => deps.ensureWorkspace(user.id), ) - const source = yield* Effect.tryPromise(() => - deps.sourceService.findInWorkspace(workspace.id, input.sourceId), + const source = yield* Effect.tryPromise( + async () => { + const source = await deps.sourceService.findInWorkspace(workspace.id, input.sourceId) + return source ?? await deps.sourceService.findLegacyDemoSource?.(workspace.id, input.sourceId) ?? null + }, ) if (!source) { return sourceNotFound() } - if (source.demoKey) { - const demoResult = yield* loadDemoChunkPageEffect( - input, - deps, - source.demoKey, - source.knowhereDocumentId, - ) - return demoResult ?? sourceNotFound() - } - // Reads never return zero chunks for a ready remote document; the SDK falls // back to Knowhere when Blob storage is missing or stale. A source that is // not yet ready has no published document to read. @@ -97,6 +92,7 @@ const loadSourceChunksEffect = ( return sourceSnapshotProcessing(input) } + if (input.pageParams.namespace && !getCompatibleNamespaces(workspace).includes(input.pageParams.namespace)) return sourceChunksUnavailable(input) const apiKey = yield* Effect.tryPromise(() => deps.ensureApiKeyForWorkspace(workspace.id, input.cookieHeader), ) @@ -110,6 +106,8 @@ const loadSourceChunksEffect = ( const readableSource = { documentId: source.knowhereDocumentId, title: source.title, + namespace: input.pageParams.namespace ?? workspace.namespace, + ...(input.pageParams.jobResultId ? { jobResultId: input.pageParams.jobResultId } : {}), revisionKey: source.knowhereJobId, } @@ -194,6 +192,8 @@ const loadRemoteChunkPageEffect = ( const readableSource = { documentId, title: source.title, + namespace: input.pageParams.namespace ?? remoteDocument.namespace, + ...(input.pageParams.jobResultId ? { jobResultId: input.pageParams.jobResultId } : {}), revisionKey: source.knowhereJobId ?? remoteDocument.revisionKey ?? null, } @@ -232,7 +232,6 @@ const loadDemoChunkPageEffect = ( input: LoadSourceChunksInput, deps: RouteChunksDependencies, demoSourceId: string = input.sourceId, - documentIdOverride?: string | null, ) => Effect.gen(function* () { const pages = input.shouldLoadAll @@ -245,11 +244,15 @@ const loadDemoChunkPageEffect = ( demoSourceId, page: input.pageParams.page, pageSize: input.pageParams.pageSize, + ...(input.pageParams.jobResultId ? { jobResultId: input.pageParams.jobResultId } : {}), + ...(input.pageParams.chunkType ? { chunkType: input.pageParams.chunkType } : {}), }), ), ] const page = pages[0] if (!page) return null + const expectedJobResultId: string | undefined = input.pageParams.jobResultId ?? page.jobResultId + if (expectedJobResultId && pages.some((candidate) => candidate.jobResultId !== expectedJobResultId)) return sourceChunksUnavailable(input) const source = { id: page.demoSourceId, kind: "demo" as const, @@ -257,12 +260,14 @@ const loadDemoChunkPageEffect = ( title: page.title, mimeType: page.mimeType, status: "ready" as const, - documentId: documentIdOverride ?? page.canonicalDocumentId, + documentId: page.canonicalDocumentId, + namespace: page.namespace, + jobResultId: page.jobResultId, } const chunks = filterChunksByType( pages.flatMap((demoChunkPage) => demoChunkPage.chunks.map((chunk) => - demoView.toParsedChunkView(source, chunk), + ({ ...demoView.toParsedChunkView(source, chunk), namespace: page.namespace, jobResultId: page.jobResultId }), ), ), input.pageParams.chunkType, @@ -288,11 +293,44 @@ const loadDemoChunkPageEffect = ( knowhereBaseUrl: process.env.KNOWHERE_BASE_URL ?? "(default)", error: getErrorMessage(error), }) - return null + const status: DemoReadFailureStatus | undefined = readDemoFailureStatus(error) + if (status !== undefined) return createDemoReadFailure(input, status) + return input.pageParams.jobResultId ? sourceChunksUnavailable(input) : null }), ), ) +type DemoReadFailureStatus = 401 | 404 | 409 | 503 + +function readDemoFailureStatus(error: unknown, depth: number = 0): DemoReadFailureStatus | undefined { + if (depth > 8) return undefined + if (Runtime.isFiberFailure(error)) { + const failure = Cause.failureOption(error[Runtime.FiberFailureCauseId]) + return Option.isSome(failure) ? readDemoFailureStatus(failure.value, depth + 1) : undefined + } + if (typeof error !== "object" || error === null) return undefined + if ("status" in error && (error.status === 401 || error.status === 404 || error.status === 409 || error.status === 503)) return error.status + return "cause" in error ? readDemoFailureStatus(error.cause, depth + 1) : undefined +} + +function createDemoReadFailure(input: LoadSourceChunksInput, status: DemoReadFailureStatus): JsonRouteResult { + const message: string = status === 401 + ? "Sign in to read this demo source." + : status === 404 + ? input.pageParams.jobResultId ? "This cited source revision is unavailable." : "Demo source not found." + : status === 409 + ? "Demo source is still being prepared. Please try again shortly." + : "Demo sources are temporarily unavailable. Please try again shortly." + return routeResult.ok({ + chunks: [], + ...(!input.shouldLoadAll ? { + pagination: { page: input.pageParams.page, pageSize: input.pageParams.pageSize, total: 0, totalPages: 0 }, + } : {}), + message, + ...(status === 409 ? { isProcessing: true } : { isUnavailable: true }), + }, status) +} + async function loadAllDemoChunkPages( input: LoadSourceChunksInput, deps: RouteChunksDependencies, @@ -303,8 +341,11 @@ async function loadAllDemoChunkPages( demoSourceId, page: 1, pageSize, + ...(input.pageParams.jobResultId ? { jobResultId: input.pageParams.jobResultId } : {}), + ...(input.pageParams.chunkType ? { chunkType: input.pageParams.chunkType } : {}), }) const pages = [firstPage] + const jobResultId: string | undefined = input.pageParams.jobResultId ?? firstPage.jobResultId for ( let pageNumber = 2; pageNumber <= firstPage.pagination.totalPages; @@ -315,6 +356,8 @@ async function loadAllDemoChunkPages( demoSourceId, page: pageNumber, pageSize, + ...(jobResultId ? { jobResultId } : {}), + ...(input.pageParams.chunkType ? { chunkType: input.pageParams.chunkType } : {}), }), ) } @@ -416,7 +459,7 @@ function recoverUnavailableChunks( input: LoadSourceChunksInput, error: unknown, ): Effect.Effect, unknown> { - return displayReadUnavailable.isError(error) + return input.pageParams.jobResultId || displayReadUnavailable.isError(error) ? Effect.succeed(sourceChunksUnavailable(input)) : Effect.fail(error) } diff --git a/src/domains/sources/route-dependencies.ts b/src/domains/sources/route-dependencies.ts index 04ceab9a..0e4bcc4d 100644 --- a/src/domains/sources/route-dependencies.ts +++ b/src/domains/sources/route-dependencies.ts @@ -38,9 +38,12 @@ const defaultDependencies: SourceRouteServiceDependencies = { requireUser, sourceService: { findInWorkspace: defaultSourceService.findInWorkspace, + findLegacyDemoSource: defaultSourceService.findLegacyDemoSource, findByKnowhereDocumentId: defaultSourceService.findByKnowhereDocumentId, hideDemoSource: defaultSourceService.hideDemoSource, listHiddenDemoSourceIds: defaultSourceService.listHiddenDemoSourceIds, + listSelectedDemoSourceIds: defaultSourceService.listSelectedDemoSourceIds, + listLegacyDemoDocumentIds: defaultSourceService.listLegacyDemoDocumentIds, localizeRemoteDocument: defaultSourceService.localizeRemoteDocument, softDelete: defaultSourceService.softDelete, upsertMaterializedDemoSource: diff --git a/src/domains/sources/route-listing.ts b/src/domains/sources/route-listing.ts index ba6e699d..08176dd5 100644 --- a/src/domains/sources/route-listing.ts +++ b/src/domains/sources/route-listing.ts @@ -32,7 +32,7 @@ type RouteListingDependencies = Pick< > readonly sourceService: Pick< SourceRouteServiceDependencies["sourceService"], - "listHiddenDemoSourceIds" | "localizeRemoteDocument" + "listHiddenDemoSourceIds" | "listSelectedDemoSourceIds" | "listLegacyDemoDocumentIds" | "localizeRemoteDocument" > readonly reconcileSourcesForWorkspace: SourceRouteServiceDependencies[ "reconcileSourcesForWorkspace" @@ -84,41 +84,30 @@ const listSourcesEffect = ( ) const client = deps.makeKnowhereClient(apiKey) const sources = listedSources - const demoSourceResolution = resolveWorkspaceDemoSources(sources, catalog) + const hiddenDemoSourceIds: ReadonlySet = new Set(yield* Effect.tryPromise(() => deps.sourceService.listHiddenDemoSourceIds(workspace.id))) + const selectedDemoSourceIds: ReadonlySet = new Set(yield* Effect.tryPromise(() => deps.sourceService.listSelectedDemoSourceIds?.(workspace.id) ?? Promise.resolve([]))) + const demoSourceResolution = resolveWorkspaceDemoSources(sources, catalog, hiddenDemoSourceIds, selectedDemoSourceIds) const workspaceSources = demoSourceResolution.workspaceSources + const excludedLegacyDocumentIds: ReadonlySet = new Set(yield* Effect.tryPromise(() => deps.sourceService.listLegacyDemoDocumentIds?.(workspace.id) ?? Promise.resolve([]))) const remoteSourceViews = yield* listRemoteLibrarySourceViews({ workspace, client, - localSources: demoSourceResolution.workspaceSources, + localSources: sources, + excludedDocumentIds: excludedLegacyDocumentIds, }) yield* Effect.sync(() => triggerBackgroundReconciliationForParsingSources({ workspaceId: workspace.id, - sources, + sources: workspaceSources, apiKey, startBackgroundReconciliation: deps.startBackgroundReconciliation ?? defaultStartBackgroundReconciliation, }), ) - const hiddenDemoSourceIds = new Set( - yield* Effect.tryPromise(() => - deps.sourceService.listHiddenDemoSourceIds(workspace.id), - ), - ) - const visibleDemoSources = catalog.sources - .filter( - (source) => - !demoSourceResolution.materializedDemoSourceIds.has( - source.demoSourceId, - ), - ) - .filter((source) => !hiddenDemoSourceIds.has(source.demoSourceId)) - .map(demoView.toSourceView) - return routeResult.ok({ sources: [ - ...visibleDemoSources, + ...demoSourceResolution.demoSources, ...workspaceSources.map((source) => toSourceView(source)), ...remoteSourceViews, ], diff --git a/src/domains/sources/route-service.test.ts b/src/domains/sources/route-service.test.ts index bd079b3d..cc3609b9 100644 --- a/src/domains/sources/route-service.test.ts +++ b/src/domains/sources/route-service.test.ts @@ -561,13 +561,14 @@ describe("source route service", () => { { id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", demoSourceId: "demo-tsla-q4-2025", title: "TSLA-Q4-2025-Update.pdf", mimeType: "application/pdf", status: "ready", documentId: "demo-doc-tsla-q4-2025", originalFile: { - url: "https://example.com/tsla-q4-2025.pdf", + url: "/api/demo-sources/demo-tsla-q4-2025/original", mimeType: "application/pdf", sizeBytes: 1024, canDownload: false, @@ -637,6 +638,7 @@ describe("source route service", () => { expect.objectContaining({ id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", demoSourceId: "demo-tsla-q4-2025", }), ], @@ -644,7 +646,7 @@ describe("source route service", () => { }); }); - it("uses stored chunk counts for materialized demo sources", async () => { + it("uses current shared metadata instead of persisted personal demo copies", async () => { const materializedSource: Source = { ...source, id: "source_demo", @@ -703,10 +705,11 @@ describe("source route service", () => { body: { sources: [ expect.objectContaining({ - id: "source_demo", - kind: "workspace", + id: "demo-tsla-q4-2025", + kind: "demo", + namespace: "__knowhere_demo__", demoSourceId: "demo-tsla-q4-2025", - documentId: "doc_user_copy", + documentId: "demo-doc-tsla-q4-2025", chunkCount: 70, }), ], @@ -733,13 +736,14 @@ describe("source route service", () => { { id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", demoSourceId: "demo-tsla-q4-2025", title: "TSLA-Q4-2025-Update.pdf", mimeType: "application/pdf", status: "ready", documentId: "demo-doc-tsla-q4-2025", originalFile: { - url: "https://example.com/tsla-q4-2025.pdf", + url: "/api/demo-sources/demo-tsla-q4-2025/original", mimeType: "application/pdf", sizeBytes: 1024, canDownload: false, @@ -842,6 +846,7 @@ describe("source route service", () => { }); const softDelete = vi.fn(async () => true); const service = createSourceRouteService({ + demoApi: { fetchCatalog: vi.fn(async () => emptyDemoCatalog) }, ensureApiKeyForWorkspace: vi.fn(async () => "jwt_123"), ensureWorkspace: vi.fn(async () => workspace), makeKnowhereClient: vi.fn(() => ({ @@ -899,6 +904,7 @@ describe("source route service", () => { }; const softDelete = vi.fn(async () => true); const service = createSourceRouteService({ + demoApi: { fetchCatalog: vi.fn(async () => emptyDemoCatalog) }, ensureApiKeyForWorkspace: vi.fn(async () => "jwt_123"), ensureWorkspace: vi.fn(async () => workspace), makeKnowhereClient: vi.fn(() => ({ @@ -1086,7 +1092,7 @@ const demoCatalog: DemoCatalog = { status: "ready", chunkCount: 70, originalFile: { - url: "https://example.com/tsla-q4-2025.pdf", + url: "/api/demo-sources/demo-tsla-q4-2025/original", mimeType: "application/pdf", sizeBytes: 1024, canDownload: false, diff --git a/src/domains/sources/route-types.ts b/src/domains/sources/route-types.ts index 548a8fb3..c4478589 100644 --- a/src/domains/sources/route-types.ts +++ b/src/domains/sources/route-types.ts @@ -2,6 +2,7 @@ import type { ChunkKnowhereClient, ChunkPage, ChunkPageParams, + ChunkReadType, } from "@/domains/chunks" import type { ParsedChunkView } from "@/domains/chunks/types" import type { @@ -182,6 +183,7 @@ type SourceRouteService = { } type SourceWorkflowService = { + readonly findLegacyDemoSource?: (workspaceId: string, sourceId: string) => Promise readonly uploadSourceToKnowhere: ( workspace: Workspace, file: File, @@ -214,6 +216,8 @@ type SourceWorkflowService = { demoSourceId: string, ) => Promise readonly listHiddenDemoSourceIds: (workspaceId: string) => Promise + readonly listSelectedDemoSourceIds?: (workspaceId: string) => Promise + readonly listLegacyDemoDocumentIds?: (workspaceId: string) => Promise readonly localizeRemoteDocument: ( workspaceId: string, input: { @@ -245,6 +249,8 @@ type SourceRouteDemoApi = { readonly demoSourceId: string readonly page: number readonly pageSize: number + readonly jobResultId?: string + readonly chunkType?: ChunkReadType }) => Promise } diff --git a/src/domains/sources/service.ts b/src/domains/sources/service.ts index 1e4801cb..de088295 100644 --- a/src/domains/sources/service.ts +++ b/src/domains/sources/service.ts @@ -13,6 +13,11 @@ import { retrySourceToKnowhereEffect } from "./retry" import { sourceWorkflowRuntime } from "./workflow-runtime" type SourceService = { + readonly listLegacyDemoSources: (workspaceId: string) => Promise + readonly findLegacyDemoSource: (workspaceId: string, sourceId: string) => Promise + readonly listLegacyDemoDocumentIds: (workspaceId: string) => Promise + readonly listSelectedDemoSourceIds: (workspaceId: string) => Promise + readonly restoreDemoSource: (workspaceId: string, demoSourceId: string) => Promise readonly findInWorkspace: ( workspaceId: string, sourceId: string, @@ -99,6 +104,11 @@ const retrySourceToKnowhere: SourceService["retrySourceToKnowhere"] = ( ) export const sourceService: SourceService = { + listLegacyDemoSources: sourceWorkflowRuntime.listLegacyDemoSources, + findLegacyDemoSource: sourceWorkflowRuntime.findLegacyDemoSource, + listLegacyDemoDocumentIds: sourceWorkflowRuntime.listLegacyDemoDocumentIds, + listSelectedDemoSourceIds: sourceWorkflowRuntime.listSelectedDemoSourceIds, + restoreDemoSource: sourceWorkflowRuntime.restoreDemoSource, findInWorkspace: sourceWorkflowRuntime.findInWorkspace, findByKnowhereDocumentId: sourceWorkflowRuntime.findByKnowhereDocumentId, hideDemoSource: sourceWorkflowRuntime.hideDemoSource, diff --git a/src/domains/sources/types.ts b/src/domains/sources/types.ts index cdfd33a1..b14f5cc2 100644 --- a/src/domains/sources/types.ts +++ b/src/domains/sources/types.ts @@ -48,6 +48,8 @@ export type SourceView = { readonly kind?: SourceKind readonly demoSourceId?: string readonly namespace?: string + /** Complete Knowhere revision used by shared demo reads and citations. */ + readonly jobResultId?: string readonly title: string /** Browser-provided content type for preview routing. */ readonly mimeType: string diff --git a/src/domains/sources/workflow-runtime.ts b/src/domains/sources/workflow-runtime.ts index ba428de4..ede6d26e 100644 --- a/src/domains/sources/workflow-runtime.ts +++ b/src/domains/sources/workflow-runtime.ts @@ -48,6 +48,11 @@ type UploadRepositoryRuntime = { } type SourceWorkflowRuntime = UploadRepositoryRuntime & { + readonly listLegacyDemoSources: (workspaceId: string) => Promise + readonly findLegacyDemoSource: (workspaceId: string, sourceId: string) => Promise + readonly listLegacyDemoDocumentIds: (workspaceId: string) => Promise + readonly listSelectedDemoSourceIds: (workspaceId: string) => Promise + readonly restoreDemoSource: (workspaceId: string, demoSourceId: string) => Promise readonly createUploadRepository: ( runtime?: UploadRepositoryRuntime, ) => UploadSourceRepository @@ -155,6 +160,12 @@ const localizeRemoteDocument: SourceWorkflowRuntime["localizeRemoteDocument"] = sourceRepository.localizeRemoteDocumentEffect(workspaceId, input), ) +const listLegacyDemoSources: SourceWorkflowRuntime["listLegacyDemoSources"] = (workspaceId: string) => databaseRuntime.runPromise(sourceRepository.listLegacyDemoSourcesEffect(workspaceId)) +const findLegacyDemoSource: SourceWorkflowRuntime["findLegacyDemoSource"] = (workspaceId: string, sourceId: string) => databaseRuntime.runPromise(sourceRepository.findLegacyDemoSourceEffect(workspaceId, sourceId)) +const listLegacyDemoDocumentIds: SourceWorkflowRuntime["listLegacyDemoDocumentIds"] = (workspaceId: string) => databaseRuntime.runPromise(sourceRepository.listLegacyDemoDocumentIdsEffect(workspaceId)) +const listSelectedDemoSourceIds: SourceWorkflowRuntime["listSelectedDemoSourceIds"] = (workspaceId: string) => databaseRuntime.runPromise(sourceRepository.listSelectedDemoSourceIdsEffect(workspaceId)) +const restoreDemoSource: SourceWorkflowRuntime["restoreDemoSource"] = (workspaceId: string, demoSourceId: string) => databaseRuntime.runPromise(sourceRepository.restoreDemoSourceEffect(workspaceId, demoSourceId)) + const listHiddenDemoSourceIds: SourceWorkflowRuntime["listHiddenDemoSourceIds"] = (workspaceId: string) => databaseRuntime.runPromise( @@ -357,6 +368,11 @@ function requireSource(source: Source | null, message: string): Source { } export const sourceWorkflowRuntime: SourceWorkflowRuntime = { + listLegacyDemoSources, + findLegacyDemoSource, + listLegacyDemoDocumentIds, + listSelectedDemoSourceIds, + restoreDemoSource, clearStagedBlob, createUploadRepository, createUploading, diff --git a/src/domains/workspace/client-cache.test.ts b/src/domains/workspace/client-cache.test.ts index e2ee2cc8..3a02b883 100644 --- a/src/domains/workspace/client-cache.test.ts +++ b/src/domains/workspace/client-cache.test.ts @@ -9,7 +9,7 @@ describe("workspaceClientCache", () => { it("builds chunk page keys until the selected Source has no more pages", () => { expect(workspaceClientCache.getSourceChunksKey(null, 0, null)).toBeNull(); expect(workspaceClientCache.getSourceChunksKey("source_1", 1, null)).toEqual( - ["source-chunks", "source_1", 2], + ["source-chunks", "source_1", 2, "", "", ""], ); expect( workspaceClientCache.getSourceChunksKey("source_1", 1, { @@ -56,7 +56,7 @@ describe("workspaceClientCache", () => { it("reads cached source chunk pages for citation jumps", () => { const cache = new Map([ [ - unstable_serialize(["source-chunks", "source_1", 1]), + unstable_serialize(["source-chunks", "source_1", 1, "", "", ""]), { data: { chunks: [ diff --git a/src/domains/workspace/client-cache.ts b/src/domains/workspace/client-cache.ts index 1902db90..7223b178 100644 --- a/src/domains/workspace/client-cache.ts +++ b/src/domains/workspace/client-cache.ts @@ -15,7 +15,12 @@ type SourceChunksResponse = Awaited< type ChatThreadDetailResponse = Awaited< ReturnType > -type SourceChunksKey = readonly ["source-chunks", string, number] +type SourceChunksCacheOptions = { + readonly namespace?: string + readonly jobResultId?: string + readonly chunkType?: "text" | "image" | "table" | "page" +} +type SourceChunksKey = readonly ["source-chunks", string, number, string, string, string] type ChatThreadKey = readonly ["chat-thread", string] type LoadedChatThreadDetail = ChatThreadDetailResponse & { @@ -24,6 +29,7 @@ type LoadedChatThreadDetail = ChatThreadDetailResponse & { } type WorkspaceClientCache = { + readonly getSourceReadKey: (sourceId: string, options?: SourceChunksCacheOptions) => string readonly getCachedChatThreadData: ( cache: Cache, threadId: string, @@ -31,12 +37,14 @@ type WorkspaceClientCache = { readonly getCachedSourceChunks: ( cache: Cache, sourceId: string, + options?: SourceChunksCacheOptions, ) => ParsedChunkView[] | null readonly getChatThreadKey: (threadId: string) => ChatThreadKey readonly getSourceChunksKey: ( sourceId: string | null, pageIndex: number, previousPageData: SourceChunksResponse | null, + options?: SourceChunksCacheOptions, ) => SourceChunksKey | null readonly hasLoadedChatThreadData: ( value: ChatThreadDetailResponse | null | undefined, @@ -49,6 +57,7 @@ type WorkspaceClientCache = { mutate: (key: SourceChunksKey, data: SourceChunksResponse) => unknown, sourceId: string, chunks: readonly ParsedChunkView[], + options?: SourceChunksCacheOptions, ) => void } @@ -56,10 +65,11 @@ function getSourceChunksKey( sourceId: string | null, pageIndex: number, previousPageData: SourceChunksResponse | null, + options: SourceChunksCacheOptions = {}, ): SourceChunksKey | null { if (!sourceId) return null if (previousPageData && !hasMoreChunkPage(previousPageData)) return null - return ["source-chunks", sourceId, pageIndex + 1] as const + return ["source-chunks", sourceId, pageIndex + 1, options.jobResultId ?? "", options.namespace ?? "", options.chunkType ?? ""] as const } function hasMoreChunkPages( @@ -110,12 +120,13 @@ function isSourceChunksResponse( function getCachedSourceChunks( cache: Cache, sourceId: string, + options: SourceChunksCacheOptions = {}, ): ParsedChunkView[] | null { const chunks: ParsedChunkView[] = [] let previous: SourceChunksResponse | null = null for (let pageIndex = 0; pageIndex < 200; pageIndex += 1) { - const key = getSourceChunksKey(sourceId, pageIndex, previous) + const key = getSourceChunksKey(sourceId, pageIndex, previous, options) if (!key) break const cachedState = cache.get(unstable_serialize(key)) @@ -135,8 +146,9 @@ function hydrateSourceChunks( mutate: (key: SourceChunksKey, data: SourceChunksResponse) => unknown, sourceId: string, chunks: readonly ParsedChunkView[], + options: SourceChunksCacheOptions = {}, ): void { - const key = getSourceChunksKey(sourceId, 0, null) + const key = getSourceChunksKey(sourceId, 0, null, options) if (!key) return const total = chunks.length @@ -161,7 +173,13 @@ function isChatThreadDetailResponse( return response.requestedThreadId === threadId } +function getSourceReadKey(sourceId: string, options: SourceChunksCacheOptions = {}): string { + if (!options.jobResultId && !options.namespace && !options.chunkType) return sourceId + return JSON.stringify([sourceId, options.jobResultId ?? "", options.namespace ?? "", options.chunkType ?? ""]) +} + export const workspaceClientCache: WorkspaceClientCache = { + getSourceReadKey, getCachedChatThreadData, getCachedSourceChunks, getChatThreadKey, @@ -176,5 +194,6 @@ export type { ChatThreadDetailResponse, ChatThreadKey, SourceChunksKey, + SourceChunksCacheOptions, SourceChunksResponse, } diff --git a/src/domains/workspace/client.test.ts b/src/domains/workspace/client.test.ts index f92cd32f..93a1129a 100644 --- a/src/domains/workspace/client.test.ts +++ b/src/domains/workspace/client.test.ts @@ -22,6 +22,28 @@ describe("workspaceClient", () => { vi.clearAllMocks() }) + it("selects shared demos through the metadata selection endpoint", async () => { + mockRouteClient.postJsonWithStatus.mockResolvedValue({ + status: 200, + body: { sources: [{ id: "demo-tsla-q4-2025", kind: "demo" }] }, + }) + await expect(workspaceClient.selectDemoSources({ demoSourceIds: ["demo-tsla-q4-2025"] })) + .resolves.toEqual([{ id: "demo-tsla-q4-2025", kind: "demo" }]) + expect(mockRouteClient.postJsonWithStatus).toHaveBeenCalledWith( + "/api/demo-sources/select", { demoSourceIds: ["demo-tsla-q4-2025"] }, + ) + }) + + it("passes revision identity through filtered chunk pagination", async () => { + mockRouteClient.getJson.mockResolvedValue({ chunks: [], pagination: { page: 1, totalPages: 1 } }) + await workspaceClient.fetchChunks("demo-report", { + chunkType: "page", jobResultId: "revision-old", untilPageNumber: 2, + }) + expect(mockRouteClient.getJson).toHaveBeenCalledWith( + "/api/sources/demo-report/chunks?page=1&pageSize=50&chunkType=page&jobResultId=revision-old", + ) + }) + it("fetches a normalized chunk page with an encoded source id", async () => { mockRouteClient.getJson.mockResolvedValue({ chunks: [ diff --git a/src/domains/workspace/client.ts b/src/domains/workspace/client.ts index 2a30edfd..629195af 100644 --- a/src/domains/workspace/client.ts +++ b/src/domains/workspace/client.ts @@ -16,6 +16,7 @@ const workspaceClientKeys = { chatDiagram: "/api/chat/diagram", chat: "/api/chat", materializeDemoSources: "/api/demo-sources/materialize", + selectDemoSources: "/api/demo-sources/select", folders: "/api/folders", archiveSource: "archive-source", retrySource: "retry-source", @@ -29,6 +30,8 @@ const workspaceClientConfig = { export type FetchChunksOptions = { readonly chunkType?: "text" | "image" | "table" | "page" + readonly jobResultId?: string + readonly namespace?: string readonly untilPageNumber?: number } @@ -49,6 +52,7 @@ type ChatThreadResponse = { thread?: ChatThreadView messages?: ChatMessageView[] message?: string + citationSources?: SourceView[] } type ChatThreadDetailResponse = ChatThreadResponse & { @@ -98,6 +102,7 @@ type ChatMessageResponse = { threadId?: string messages?: ChatMessageView[] message?: string + citationSources?: SourceView[] } type ChatDiagramRequest = { @@ -135,6 +140,7 @@ export const workspaceClient = { createChatDiagram, sendChatMessage, materializeDemoSources, + selectDemoSources, archiveSource, retrySource, archiveChatThread, @@ -152,6 +158,8 @@ async function fetchChunks( try { const searchParams = new URLSearchParams() if (options?.chunkType) searchParams.set("chunkType", options.chunkType) + if (options?.jobResultId) searchParams.set("jobResultId", options.jobResultId) + if (options?.namespace) searchParams.set("namespace", options.namespace) const query = searchParams.toString() const body = await workspaceRouteClient.getJson<{ chunks?: ParsedChunkView[] @@ -167,13 +175,15 @@ async function fetchChunks( async function fetchChunkPage( sourceId: string, page: number, - options?: Pick, + options?: Pick, ): Promise { const searchParams = new URLSearchParams({ page: String(page), pageSize: String(workspaceClientConfig.sourceChunkPageSize), }) if (options?.chunkType) searchParams.set("chunkType", options.chunkType) + if (options?.jobResultId) searchParams.set("jobResultId", options.jobResultId) + if (options?.namespace) searchParams.set("namespace", options.namespace) const body = await workspaceRouteClient.getJson( `/api/sources/${encodeURIComponent(sourceId)}/chunks?${searchParams.toString()}`, ) @@ -204,6 +214,8 @@ async function fetchChunkPagesUntil( do { const result = await fetchChunkPage(sourceId, page, { chunkType: options.chunkType, + jobResultId: options.jobResultId, + namespace: options.namespace, }) pages.push(result) chunks.push(...(result.chunks ?? [])) @@ -298,6 +310,22 @@ async function materializeDemoSources( return Array.isArray(body.sources) ? body.sources : [] } +async function selectDemoSources( + input: MaterializeDemoSourcesRequest, +): Promise { + const response = await workspaceRouteClient.postJsonWithStatus( + workspaceClientKeys.selectDemoSources, + input, + ) + if (response.status < 200 || response.status >= 300) { + throw new Error(response.body.message ?? "Demo sources could not be selected right now.") + } + if (!Array.isArray(response.body.sources)) { + throw new Error("Demo selection returned an invalid source list.") + } + return response.body.sources +} + function archiveSource(sourceId: string): Promise { return workspaceRouteClient.patchJson( `/api/sources/${encodeURIComponent(sourceId)}`, diff --git a/src/domains/workspace/initial-state.test.ts b/src/domains/workspace/initial-state.test.ts index 2ed2d251..687b51f0 100644 --- a/src/domains/workspace/initial-state.test.ts +++ b/src/domains/workspace/initial-state.test.ts @@ -42,13 +42,14 @@ describe("loadWorkspaceShellInitialState", () => { { id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", demoSourceId: "demo-tsla-q4-2025", title: "TSLA-Q4-2025-Update.pdf", mimeType: "application/pdf", status: "ready", documentId: "demo-doc-tsla-q4-2025", originalFile: { - url: "https://example.com/tsla-q4-2025.pdf", + url: "/api/demo-sources/demo-tsla-q4-2025/original", mimeType: "application/pdf", sizeBytes: 1024, canDownload: false, @@ -88,6 +89,8 @@ describe("loadWorkspaceShellInitialState", () => { citations: [ { chunkType: "text", + chunkId: "parser-chunk-1", + chunkRowId: "demo-chunk-1", score: 0.95, content: "Automotive revenue increased.", source: { @@ -103,6 +106,19 @@ describe("loadWorkspaceShellInitialState", () => { expect(deps.listSourcesForWorkspace).not.toHaveBeenCalled() }) + it("keys guest prefetched demo chunks by namespace and immutable revision", async () => { + const catalog: DemoCatalog = makeDemoCatalog() + const source = catalog.sources[0]! + const fetcher = vi.fn().mockResolvedValue(new Response(JSON.stringify({ demo_source_id: source.demoSourceId, canonical_document_id: source.canonicalDocumentId, namespace: "__knowhere_demo__", job_result_id: "revision-one", title: source.title, mime_type: source.mimeType, chunks: [{ id: "row-one", chunk_id: "node-one", chunk_type: "text", content: "content", sort_order: 0, metadata: {} }], pagination: { page: 1, page_size: 50, total: 1, total_pages: 1 } }), { headers: { "content-type": "application/json" } })) + vi.stubGlobal("fetch", fetcher) + try { + const state = await loadWorkspaceShellInitialState(createDependencies({ getOptionalAuthenticated: vi.fn(async () => null), fetchDemoCatalog: vi.fn(async () => ({ ...catalog, sources: [{ ...source, namespace: "__knowhere_demo__", jobResultId: "revision-one" }] })) })) + const readKey: string = JSON.stringify([source.demoSourceId, "revision-one", "__knowhere_demo__", ""]) + expect(Object.keys(state.initialPrefetchedChunksBySourceId ?? {})).toEqual([readKey]) + expect(state.initialPrefetchedChunksBySourceId?.[readKey]?.[0]).toMatchObject({ jobResultId: "revision-one", namespace: "__knowhere_demo__" }) + } finally { vi.unstubAllGlobals() } + }) + it("exposes the configured Dashboard origin to the shell", async () => { process.env.DASHBOARD_ORIGIN = "https://dashboard.staging.example" @@ -128,6 +144,7 @@ describe("loadWorkspaceShellInitialState", () => { expect.objectContaining({ id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", demoSourceId: "demo-tsla-q4-2025", }), { @@ -174,7 +191,7 @@ describe("loadWorkspaceShellInitialState", () => { ]) }) - it("hides canonical demos that are hidden or already materialized", async () => { + it("uses the shared catalog even when an old private demo copy exists", async () => { const workspace = makeWorkspace() const materializedSource = makeSource(workspace.id, { id: "source_demo", @@ -192,9 +209,10 @@ describe("loadWorkspaceShellInitialState", () => { expect(state.sources).toEqual([ expect.objectContaining({ - id: "source_demo", - kind: "workspace", - documentId: "doc_user_copy", + id: "demo-tsla-q4-2025", + kind: "demo", + namespace: "__knowhere_demo__", + documentId: "demo-doc-tsla-q4-2025", chunkCount: 70, }), ]) @@ -219,6 +237,7 @@ describe("loadWorkspaceShellInitialState", () => { expect.objectContaining({ id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", demoSourceId: "demo-tsla-q4-2025", documentId: "demo-doc-tsla-q4-2025", }), @@ -244,6 +263,7 @@ describe("loadWorkspaceShellInitialState", () => { expect.objectContaining({ id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", }), ]) }) @@ -351,6 +371,7 @@ describe("loadWorkspaceShellInitialState", () => { expect.objectContaining({ id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", }), { id: readySource.id, @@ -438,6 +459,7 @@ describe("loadWorkspaceShellInitialState", () => { expect.objectContaining({ id: "demo-tsla-q4-2025", kind: "demo", + namespace: "__knowhere_demo__", }), { id: parsingSource.id, diff --git a/src/domains/workspace/initial-state.ts b/src/domains/workspace/initial-state.ts index 3d6ce4d1..aed70afe 100644 --- a/src/domains/workspace/initial-state.ts +++ b/src/domains/workspace/initial-state.ts @@ -2,6 +2,7 @@ import "server-only" import { Effect } from "effect" +import { resolveCitationSources } from "@/domains/chat/citation-sources" import type { ChatMessageView } from "@/domains/chat/types" import type { ParsedChunkView } from "@/domains/chunks/types" import { demoView } from "@/domains/demo/view" @@ -40,6 +41,7 @@ import { import { effectOperation } from "@/lib/effect-operation" import { logger } from "@/lib/logger" import { notebookRequestContext } from "./request-context" +import { workspaceClientCache } from "./client-cache" type WorkspaceShellInitialState = { readonly activeChatThreadId?: string | null @@ -52,6 +54,7 @@ type WorkspaceShellInitialState = { readonly officialLibrarySources?: OfficialLibrarySourceView[] readonly folders?: FolderView[] readonly sources?: SourceView[] + readonly citationSources?: SourceView[] readonly user?: { readonly id: string readonly name: string | null @@ -70,9 +73,11 @@ const workspaceInitialStateContext = "Workspace initial state" async function getDemoChunksForSource( demoSourceId: string, + jobResultId: string, ): Promise { const chunkPage = await knowhereDemoApi.fetchChunkPage({ demoSourceId, + jobResultId, page: 1, pageSize: DEMO_CHUNK_PREFETCH_PAGE_SIZE, }) @@ -86,6 +91,8 @@ async function getDemoChunksForSource( mimeType: chunkPage.mimeType, status: "ready", documentId: chunkPage.canonicalDocumentId, + namespace: chunkPage.namespace ?? "__knowhere_demo__", + ...(chunkPage.jobResultId ? { jobResultId: chunkPage.jobResultId } : {}), } return chunkPage.chunks.map((chunk) => demoView.toParsedChunkView(sourceView, chunk), @@ -133,6 +140,9 @@ type WorkspaceShellInitialStateDependencies = { workspaceId: string, ) => Promise readonly listHiddenDemoSourceIds: (workspaceId: string) => Promise + readonly listSelectedDemoSourceIds?: (workspaceId: string) => Promise + readonly listLegacyDemoDocumentIds?: (workspaceId: string) => Promise + readonly listLegacyDemoSources?: (workspaceId: string) => Promise readonly listMessages: ( workspaceId: string, threadId: string, @@ -158,6 +168,9 @@ const defaultDependencies: WorkspaceShellInitialStateDependencies = { ensureDemoChatThread: chatThreadService.ensureDemo, listChatThreads: chatThreadService.listForWorkspace, listHiddenDemoSourceIds: sourceService.listHiddenDemoSourceIds, + listSelectedDemoSourceIds: sourceService.listSelectedDemoSourceIds, + listLegacyDemoDocumentIds: sourceService.listLegacyDemoDocumentIds, + listLegacyDemoSources: sourceService.listLegacyDemoSources, listMessages: chatThreadService.listMessages, listFoldersForWorkspace: folderWorkflowRuntime.listForWorkspace, listSourcesForWorkspace: sourceWorkflowRuntime.listForWorkspace, @@ -202,20 +215,20 @@ export const loadWorkspaceShellInitialStateEffect = ( string, ParsedChunkView[] > = {} - if (firstDemoSource) { + if (firstDemoSource?.jobResultId) { const chunks = yield* Effect.catchAll( effectOperation.tryPromise( { context: workspaceInitialStateContext, operation: "getDemoChunksForSource", }, - () => getDemoChunksForSource(firstDemoSource.demoSourceId), + () => getDemoChunksForSource(firstDemoSource.demoSourceId, firstDemoSource.jobResultId ?? ""), ), - () => Effect.succeed([] as ParsedChunkView[]), + () => Effect.succeed([]), ) if (chunks.length > 0) { initialPrefetchedChunksBySourceId = { - [firstDemoSource.demoSourceId]: chunks, + [workspaceClientCache.getSourceReadKey(firstDemoSource.demoSourceId, { jobResultId: firstDemoSource.jobResultId, namespace: firstDemoSource.namespace ?? "__knowhere_demo__" })]: chunks, } } } @@ -312,20 +325,12 @@ export const loadWorkspaceShellInitialStateEffect = ( }, () => Promise.resolve(listedSources), ) - const demoSourceResolution = resolveWorkspaceDemoSources( - sources, - demoCatalog, - ) - const visibleDemoCatalogSources = demoCatalog.sources - .filter( - (source) => - !demoSourceResolution.materializedDemoSourceIds.has( - source.demoSourceId, - ), - ) - .filter((source) => !hiddenDemoSourceIds.has(source.demoSourceId)) - const demoSources = visibleDemoCatalogSources.map(demoView.toSourceView) + const selectedDemoSourceIds: ReadonlySet = new Set(yield* effectOperation.tryPromise({ context: workspaceInitialStateContext, operation: "listSelectedDemoSourceIds" }, () => deps.listSelectedDemoSourceIds?.(workspace.id) ?? Promise.resolve([]))) + const demoSourceResolution = resolveWorkspaceDemoSources(sources, demoCatalog, hiddenDemoSourceIds, selectedDemoSourceIds) + const demoSources = demoSourceResolution.demoSources const workspaceSources = demoSourceResolution.workspaceSources + const legacyDemoSources: readonly Source[] = yield* effectOperation.tryPromise({ context: workspaceInitialStateContext, operation: "listLegacyDemoSources" }, () => deps.listLegacyDemoSources?.(workspace.id) ?? Promise.resolve([])) + const excludedLegacyDocumentIds: ReadonlySet = new Set(yield* effectOperation.tryPromise({ context: workspaceInitialStateContext, operation: "listLegacyDemoDocumentIds" }, () => deps.listLegacyDemoDocumentIds?.(workspace.id) ?? Promise.resolve([]))) const remoteSourceViews = yield* effectOperation.addContext( { context: workspaceInitialStateContext, @@ -334,13 +339,14 @@ export const loadWorkspaceShellInitialStateEffect = ( listRemoteLibrarySourceViews({ workspace, client, - localSources: demoSourceResolution.workspaceSources, + localSources: sources, + excludedDocumentIds: excludedLegacyDocumentIds, }), ) yield* Effect.sync(() => triggerBackgroundReconciliationForParsingSources({ workspaceId: workspace.id, - sources, + sources: workspaceSources, apiKey, startBackgroundReconciliation: deps.startBackgroundReconciliation ?? @@ -364,6 +370,7 @@ export const loadWorkspaceShellInitialStateEffect = ( ...workspaceSources.map((source) => toSourceView(source)), ...remoteSourceViews, ], + citationSources: resolveCitationSources({ messages: chatMessages, sources: [...sources, ...legacyDemoSources], catalog: demoCatalog, namespace: workspace.namespace }), officialLibrarySources: toOfficialLibrarySourceViews(demoCatalog), folders: listedFolders.map(toFolderView), chatThreads: chatThreads.map(toChatThreadView), diff --git a/src/integrations/knowhere-demo-file-proxy.ts b/src/integrations/knowhere-demo-file-proxy.ts new file mode 100644 index 00000000..d1e8ce1a --- /dev/null +++ b/src/integrations/knowhere-demo-file-proxy.ts @@ -0,0 +1,35 @@ +import { FetchHttpClient, HttpClient, HttpClientRequest } from "@effect/platform" +import { Effect, Stream } from "effect" + +import { knowhereDemoApi } from "./knowhere-demo" + +const forwardedRequestHeaders: readonly string[] = ["range", "if-range", "if-none-match", "if-modified-since"] +const forwardedResponseHeaders: readonly string[] = ["content-type", "content-disposition", "content-length", "content-range", "accept-ranges", "etag", "last-modified", "retry-after"] + +export function proxyKnowhereDemoFile(request: Request, path: string): Promise { + return Effect.runPromise(Effect.gen(function* () { + const incomingUrl: URL = new URL(request.url) + const upstreamUrl: URL = new URL(knowhereDemoApi.resolveApiURL(path)) + const jobResultId: string | null = incomingUrl.searchParams.get("job_result_id") + if (jobResultId) upstreamUrl.searchParams.set("job_result_id", jobResultId) + const requestHeaders: Record = {} + for (const name of forwardedRequestHeaders) { + const value: string | null = request.headers.get(name) + if (value) requestHeaders[name] = value + } + const http = yield* HttpClient.HttpClient + const response = yield* http.execute(HttpClientRequest.get(upstreamUrl.toString()).pipe(HttpClientRequest.setHeaders(requestHeaders))) + const responseHeaders: Headers = new Headers({ "cache-control": "no-store" }) + for (const name of forwardedResponseHeaders) { + const value: string | undefined = response.headers[name] + if (value) responseHeaders.set(name, value) + } + if (!responseHeaders.has("content-disposition") && response.status >= 200 && response.status < 300) responseHeaders.set("content-disposition", "inline") + const hasNoBody: boolean = response.status === 204 || response.status === 304 + return new Response(hasNoBody ? null : Stream.toReadableStream(response.stream), { status: response.status, headers: responseHeaders }) + }).pipe( + Effect.provide(FetchHttpClient.layer), + Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }), + Effect.catchAll(() => Effect.succeed(Response.json({ message: "Demo file could not be loaded right now." }, { status: 502 }))), + )) +} diff --git a/src/integrations/knowhere-demo.test.ts b/src/integrations/knowhere-demo.test.ts index 69101beb..13043c93 100644 --- a/src/integrations/knowhere-demo.test.ts +++ b/src/integrations/knowhere-demo.test.ts @@ -36,7 +36,7 @@ describe("knowhereDemoApi", () => { expect(url).toBe("https://api.knowhereto.ai/api/v1/demo/catalog") }) - it("uses deploy-lifetime cache profiles for demo catalog data", async () => { + it("keeps catalog requests no-store without deploy-lifetime caching", async () => { globalThis.fetch = vi.fn().mockResolvedValue( new Response(JSON.stringify({ sources: [] }), { status: 200, @@ -52,16 +52,54 @@ describe("knowhereDemoApi", () => { }, }) - expect(nextCacheMocks.cacheLife).toHaveBeenCalledWith("max") - expect(nextCacheMocks.cacheTag).toHaveBeenCalledWith("demo-catalog") + expect(nextCacheMocks.cacheLife).not.toHaveBeenCalled() + expect(globalThis.fetch).toHaveBeenCalledWith(expect.any(URL), expect.objectContaining({ cache: "no-store" })) }) + it("preserves source and chunk revisions in upstream requests and stable media URLs", async () => { + globalThis.fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ + demo_source_id: "demo-report", canonical_document_id: "ddoc_report", namespace: "__knowhere_demo__", job_result_id: "revision-1", title: "report.pdf", mime_type: "application/pdf", + chunks: [{ id: "dchk_row", chunk_id: "node-content", chunk_type: "page", content: "page", sort_order: 0, metadata: {}, asset_url: "https://api.example/api/v1/demo/sources/demo-report/assets/pages/1.png?job_result_id=revision-1&signature=expired" }], + pagination: { page: 1, page_size: 50, total: 1, total_pages: 1 }, + }), { headers: { "content-type": "application/json" } })) + const page = await knowhereDemoApi.fetchChunkPage({ demoSourceId: "demo-report", jobResultId: "revision-1", page: 1, pageSize: 50 }) + expect(page).toMatchObject({ namespace: "__knowhere_demo__", jobResultId: "revision-1" }) + expect(page.chunks[0]).toMatchObject({ id: "dchk_row", chunkId: "node-content", assetUrl: "/api/demo-sources/demo-report/assets/pages/1.png?job_result_id=revision-1" }) + expect(globalThis.fetch).toHaveBeenCalledWith(new URL("https://api.knowhereto.ai/api/v1/demo/sources/demo-report/chunks?page=1&page_size=50&job_result_id=revision-1"), expect.objectContaining({ cache: "no-store" })) + }) + + it("replaces signed storage media with manifest paths and pinned same-origin URLs", async () => { + globalThis.fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ + demo_source_id: "demo-report", canonical_document_id: "ddoc_report", job_result_id: "revision-1", title: "report.pdf", mime_type: "application/pdf", + chunks: [{ id: "dchk_row", chunk_id: "node-content", chunk_type: "image", content: "image", sort_order: 0, + file_path: "images/figure-1.png", asset_url: "https://s3.example/jobs/job/raw/images/figure-1.png?X-Amz-Signature=expires", + metadata: { page_assets: [{ page_num: 1, artifact_ref: "source.pdf", content_type: "application/pdf", asset_url: "https://s3.example/jobs/job/raw/source.pdf?X-Amz-Signature=expires" }] } }], + pagination: { page: 1, page_size: 50, total: 1, total_pages: 1 }, + }), { headers: { "content-type": "application/json" } })) + const page = await knowhereDemoApi.fetchChunkPage({ demoSourceId: "demo-report", jobResultId: "revision-1", page: 1, pageSize: 50 }) + expect(page.chunks[0]?.assetUrl).toBe("/api/demo-sources/demo-report/assets/images/figure-1.png?job_result_id=revision-1") + expect(page.chunks[0]?.metadata).toMatchObject({ pageAssets: [{ assetUrl: "/api/demo-sources/demo-report/assets/source.pdf?job_result_id=revision-1" }] }) + expect(JSON.stringify(page)).not.toContain("X-Amz") + }) + it("rejects ready catalog entries missing immutable provenance or using the private namespace", async () => { + const source = { demo_source_id: "demo-report", canonical_document_id: "ddoc_report", title: "report.pdf", mime_type: "application/pdf", size_bytes: 10, chunk_count: 1, original_file: { url: "/api/v1/demo/sources/demo-report/original", mime_type: "application/pdf", size_bytes: 10, can_download: true } } + for (const provenance of [{ namespace: "__knowhere_demo__" }, { namespace: "default", job_result_id: "revision-1" }, { namespace: "__knowhere_demo__", job_result_id: "" }]) { + globalThis.fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ sources: [{ ...source, ...provenance }] }), { headers: { "content-type": "application/json" } })) + await expect(knowhereDemoApi.fetchCatalog()).rejects.toThrow() + } + }) + it("retains import readiness for known sources outside the ready subset", async () => { + globalThis.fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({ sources: [], import_status: [{ demo_source_id: "demo-new", status: "processing" }] }), { headers: { "content-type": "application/json" } })) + expect(await knowhereDemoApi.fetchCatalog()).toMatchObject({ importStatuses: [{ demoSourceId: "demo-new", status: "processing" }] }) + }) it("accepts empty demo chunk content from parser output", async () => { globalThis.fetch = vi.fn().mockResolvedValue( new Response( JSON.stringify({ demo_source_id: "demo-tsla-q4-2025", canonical_document_id: "demo-doc-tsla-q4-2025", + namespace: "__knowhere_demo__", + job_result_id: "revision-fixture", title: "TSLA-Q4-2025-Update.pdf", mime_type: "application/pdf", chunks: [ @@ -99,11 +137,7 @@ describe("knowhereDemoApi", () => { id: "demo-tsla-q4-2025:chunk-empty", content: "", }) - expect(nextCacheMocks.cacheLife).toHaveBeenCalledWith("max") - expect(nextCacheMocks.cacheTag).toHaveBeenCalledWith( - "demo-chunks", - "demo-tsla-q4-2025", - ) + expect(nextCacheMocks.cacheLife).not.toHaveBeenCalled() }) it("rewrites demo page citation assets onto the Notebook asset proxy", async () => { @@ -112,6 +146,8 @@ describe("knowhereDemoApi", () => { JSON.stringify({ demo_source_id: "demo-tsla-q4-2025", canonical_document_id: "demo-doc-tsla-q4-2025", + namespace: "__knowhere_demo__", + job_result_id: "revision-fixture", title: "TSLA-Q4-2025-Update.pdf", mime_type: "application/pdf", chunks: [ @@ -164,14 +200,14 @@ describe("knowhereDemoApi", () => { chunkType: "page", filePath: "page_citation_assets/page-8.png", assetUrl: - "/api/demo-sources/demo-tsla-q4-2025/assets/page_citation_assets/page-8.png", + "/api/demo-sources/demo-tsla-q4-2025/assets/page_citation_assets/page-8.png?job_result_id=revision-fixture", metadata: { pageAssets: [ { pageNum: 8, contentType: "image/png", assetUrl: - "/api/demo-sources/demo-tsla-q4-2025/assets/page_citation_assets/page-8.png", + "/api/demo-sources/demo-tsla-q4-2025/assets/page_citation_assets/page-8.png?job_result_id=revision-fixture", width: 1200, height: 1600, }, @@ -188,6 +224,8 @@ describe("knowhereDemoApi", () => { { demo_source_id: "demo-spacex-s1", canonical_document_id: "demo-doc-spacex-s1", + namespace: "__knowhere_demo__", + job_result_id: "revision-fixture", title: "spacex-s1.pdf", mime_type: "application/pdf", size_bytes: 7441414, @@ -261,6 +299,8 @@ describe("knowhereDemoApi", () => { { demo_source_id: "demo-tsla-q4-2025", canonical_document_id: "demo-doc-tsla-q4-2025", + namespace: "__knowhere_demo__", + job_result_id: "revision-fixture", title: "TSLA-Q4-2025-Update.pdf", mime_type: "application/pdf", size_bytes: 1024, @@ -325,6 +365,8 @@ describe("knowhereDemoApi", () => { { demo_source_id: "demo-tsla-q4-2025", canonical_document_id: "ddoc_d55868b790cd", + namespace: "__knowhere_demo__", + job_result_id: "revision-fixture", title: "TSLA-Q4-2025-Update.pdf", mime_type: "application/pdf", size_bytes: 5648867, @@ -425,6 +467,8 @@ describe("knowhereDemoApi", () => { { demo_source_id: "demo-tsla-q4-2025", canonical_document_id: "ddoc_d55868b790cd", + namespace: "__knowhere_demo__", + job_result_id: "revision-fixture", title: "TSLA-Q4-2025-Update.pdf", mime_type: "application/pdf", size_bytes: 5648867, @@ -463,11 +507,13 @@ describe("knowhereDemoApi", () => { }) expect(globalThis.fetch).toHaveBeenNthCalledWith( 1, - "https://api.knowhereto.ai/api/v1/demo/sources/demo-tsla-q4-2025/chunks?page=1&page_size=50", + new URL("https://api.knowhereto.ai/api/v1/demo/sources/demo-tsla-q4-2025/chunks?page=1&page_size=50"), + expect.objectContaining({ cache: "no-store" }), ) expect(globalThis.fetch).toHaveBeenNthCalledWith( 2, - "https://api.knowhereto.ai/api/v1/demo/catalog", + new URL("https://api.knowhereto.ai/api/v1/demo/catalog"), + expect.objectContaining({ cache: "no-store" }), ) }) }) diff --git a/src/integrations/knowhere-demo.ts b/src/integrations/knowhere-demo.ts index 33ba6abb..de5db579 100644 --- a/src/integrations/knowhere-demo.ts +++ b/src/integrations/knowhere-demo.ts @@ -1,11 +1,13 @@ import "server-only" import { Effect, Schema } from "effect" -import { cacheLife, cacheTag } from "next/cache" +import { FetchHttpClient, HttpClient, HttpClientRequest } from "@effect/platform" export type DemoCitation = { readonly demoSourceId: string readonly canonicalDocumentId: string + readonly namespace?: string + readonly jobResultId?: string readonly canonicalChunkId: string readonly chunkId: string readonly chunkType: string @@ -31,6 +33,8 @@ export type DemoExample = { export type DemoSource = { readonly demoSourceId: string readonly canonicalDocumentId: string + readonly namespace?: string + readonly jobResultId?: string readonly title: string readonly mimeType: string readonly sizeBytes: number @@ -49,6 +53,7 @@ export type DemoSource = { export type DemoCatalog = { readonly sources: readonly DemoSource[] readonly officialLibrary: OfficialLibraryCatalog + readonly importStatuses?: readonly { readonly demoSourceId: string; readonly status: string }[] } export type OfficialLibraryCategory = { @@ -91,6 +96,8 @@ export type DemoChunk = { export type DemoChunkPage = { readonly demoSourceId: string readonly canonicalDocumentId: string + readonly namespace?: string + readonly jobResultId?: string readonly title: string readonly mimeType: string readonly chunks: readonly DemoChunk[] @@ -102,31 +109,11 @@ export type DemoChunkPage = { } } -export type MaterializedDemoSource = { - readonly demoSourceId: string - readonly documentId: string - readonly status: "created" | "existing" - readonly title: string - readonly mimeType: string - readonly sizeBytes: number - readonly chunkCount: number - readonly originalFile: { - readonly url: string - readonly mimeType: string - readonly sizeBytes: number - readonly canDownload: boolean - } -} - -type DemoCatalogResponse = { - readonly sources?: readonly DemoSourceResponse[] - readonly official_library?: OfficialLibraryCatalogResponse -} - type DemoSourceResponse = { readonly demo_source_id?: unknown readonly canonical_document_id?: unknown readonly job_result_id?: unknown + readonly namespace?: unknown readonly title?: unknown readonly mime_type?: unknown readonly size_bytes?: unknown @@ -168,6 +155,8 @@ type DemoCitationResponse = { readonly page_citation_page_number?: unknown readonly page_citation_asset_url?: unknown readonly page_nums?: unknown + readonly job_result_id?: unknown + readonly namespace?: unknown readonly source?: { readonly document_id?: unknown readonly source_file_name?: unknown @@ -180,6 +169,7 @@ type DemoChunkPageResponse = { readonly demo_source_id?: unknown readonly canonical_document_id?: unknown readonly job_result_id?: unknown + readonly namespace?: unknown readonly title?: unknown readonly mime_type?: unknown readonly chunks?: readonly DemoChunkResponse[] @@ -228,21 +218,6 @@ type OfficialLibrarySourceResponse = { readonly chunk_count?: unknown } -type MaterializeResponse = { - readonly sources?: readonly MaterializedDemoSourceResponse[] -} - -type MaterializedDemoSourceResponse = { - readonly demo_source_id?: unknown - readonly document_id?: unknown - readonly status?: unknown - readonly title?: unknown - readonly mime_type?: unknown - readonly size_bytes?: unknown - readonly chunk_count?: unknown - readonly original_file?: DemoOriginalFileResponse -} - const DEFAULT_KNOWHERE_BASE_URL = "https://api.knowhereto.ai" const emptyCatalog: DemoCatalog = { @@ -254,18 +229,44 @@ const emptyCatalog: DemoCatalog = { // Effect core // --------------------------------------------------------------------------- -const fetchCatalogEffect = Effect.fn("knowhereDemo.fetchCatalog")(function* () { - const response = yield* Effect.tryPromise(() => - fetch(resolveApiURL("/api/v1/demo/catalog")), - ) - yield* assertOkEffect(response) +const readJsonEffect = Effect.fn("knowhereDemo.readJson")(function* (path: string) { + const http = yield* HttpClient.HttpClient + const response = yield* http.execute(HttpClientRequest.get(resolveApiURL(path))) + if (response.status < 200 || response.status >= 300) { + const body = yield* response.text.pipe(Effect.orElseSucceed(() => "")) + return yield* Effect.fail(new KnowhereDemoApiError(response.status, body)) + } + return yield* response.json +}) + +const DemoResponseRecord = Schema.Record({ key: Schema.String, value: Schema.Unknown }) +const DemoCatalogResponseSchema = Schema.Struct({ + import_status: Schema.optional(Schema.Array(Schema.Struct({ demo_source_id: Schema.String, status: Schema.String }))), + sources: Schema.optional(Schema.Array(DemoResponseRecord)), + official_library: Schema.optional(Schema.Struct({ + categories: Schema.optional(Schema.Array(DemoResponseRecord)), + sources: Schema.optional(Schema.Array(DemoResponseRecord)), + })), +}) +const DemoChunkPageResponseSchema = Schema.Struct({ + demo_source_id: Schema.optional(Schema.Unknown), + document_id: Schema.optional(Schema.Unknown), + canonical_document_id: Schema.optional(Schema.Unknown), + namespace: Schema.optional(Schema.Unknown), + job_result_id: Schema.optional(Schema.Unknown), + title: Schema.optional(Schema.Unknown), + mime_type: Schema.optional(Schema.Unknown), + chunks: Schema.optional(Schema.Array(DemoResponseRecord)), + pagination: Schema.optional(DemoResponseRecord), +}) - const body = (yield* Effect.tryPromise(() => - response.json(), - )) as DemoCatalogResponse +const fetchCatalogEffect = Effect.fn("knowhereDemo.fetchCatalog")(function* () { + const response = yield* readJsonEffect("/api/v1/demo/catalog") + const body = yield* Schema.decodeUnknown(DemoCatalogResponseSchema)(response) return { - sources: (body.sources ?? []).map(toDemoSource), + sources: (body.sources ?? []).map(decodeDemoSource), officialLibrary: toOfficialLibraryCatalog(body.official_library), + ...(body.import_status ? { importStatuses: body.import_status.map((entry) => ({ demoSourceId: entry.demo_source_id, status: entry.status })) } : {}), } }) @@ -274,25 +275,13 @@ const fetchChunkPageEffect = Effect.fn("knowhereDemo.fetchChunkPage")( readonly demoSourceId: string readonly page: number readonly pageSize: number + readonly jobResultId?: string }) { - const params = new URLSearchParams({ - page: String(input.page), - page_size: String(input.pageSize), - }) - const response = yield* Effect.tryPromise(() => - fetch( - resolveApiURL( - `/api/v1/demo/sources/${encodeURIComponent(input.demoSourceId)}/chunks?${params.toString()}`, - ), - ), - ) - yield* assertOkEffect(response) - - const body = (yield* Effect.tryPromise(() => - response.json(), - )) as DemoChunkPageResponse + const params: URLSearchParams = new URLSearchParams({ page: String(input.page), page_size: String(input.pageSize) }) + if (input.jobResultId) params.set("job_result_id", input.jobResultId) + const response = yield* readJsonEffect(`/api/v1/demo/sources/${encodeURIComponent(input.demoSourceId)}/chunks?${params.toString()}`) + const body = yield* Schema.decodeUnknown(DemoChunkPageResponseSchema)(response) const source = yield* readDemoSourceFallback(input.demoSourceId, body) - return toDemoChunkPage(body, source) }, ) @@ -305,7 +294,7 @@ function readDemoSourceFallback( readonly canonicalDocumentId?: string readonly title?: string readonly mimeType?: string -}, never> { +}, never, HttpClient.HttpClient> { const hasCompleteMetadata = optionalString(response.demo_source_id) !== undefined && (optionalString(response.canonical_document_id) ?? @@ -336,91 +325,31 @@ function readDemoSourceFallback( ) } -const materializeSourcesEffect = Effect.fn("knowhereDemo.materializeSources")( - function* (input: { - readonly apiKey: string - readonly namespace: string - readonly demoSourceIds: readonly string[] - }) { - const requestBody = yield* Schema.encode(MaterializeSourcesRequestJson)({ - namespace: input.namespace, - demo_source_ids: input.demoSourceIds, - }) - const response = yield* Effect.tryPromise(() => - fetch(resolveApiURL("/api/v1/demo/materializations"), { - method: "POST", - headers: { - authorization: `Bearer ${input.apiKey}`, - "content-type": "application/json", - }, - body: requestBody, - }), - ) - yield* assertOkEffect(response) - - const body = (yield* Effect.tryPromise(() => - response.json(), - )) as MaterializeResponse - return (body.sources ?? []).map(toMaterializedDemoSource) - }, -) - -const MaterializeSourcesRequestJson = Schema.parseJson( - Schema.Struct({ - namespace: Schema.String, - demo_source_ids: Schema.Array(Schema.String), - }), -) - -const fetchOptionalCatalogEffect = ( - fetcher?: () => Effect.Effect, -) => - (fetcher ?? fetchCatalogEffect)().pipe( - Effect.catchAll(() => Effect.succeed(emptyCatalog)), - ) - // --------------------------------------------------------------------------- // Async wrappers (backward-compatible) // --------------------------------------------------------------------------- async function fetchCatalog(): Promise { - "use cache" - cacheLife("max") - cacheTag("demo-catalog") - - return Effect.runPromise(fetchCatalogEffect()) + return Effect.runPromise(fetchCatalogEffect().pipe(Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }))) } async function fetchOptionalCatalog( fetcher?: () => Promise, ): Promise { - const effectFetcher = fetcher - ? () => - Effect.tryPromise(() => fetcher()).pipe( - Effect.catchAll(() => Effect.succeed(emptyCatalog)), - ) - : undefined - return Effect.runPromise(fetchOptionalCatalogEffect(effectFetcher)) + return Effect.runPromise( + Effect.tryPromise(() => (fetcher ?? fetchCatalog)()).pipe( + Effect.orElseSucceed(() => emptyCatalog), + ), + ) } async function fetchChunkPage(input: { readonly demoSourceId: string readonly page: number readonly pageSize: number + readonly jobResultId?: string }): Promise { - "use cache" - cacheLife("max") - cacheTag("demo-chunks", input.demoSourceId) - - return Effect.runPromise(fetchChunkPageEffect(input)) -} - -async function materializeSources(input: { - readonly apiKey: string - readonly namespace: string - readonly demoSourceIds: readonly string[] -}): Promise { - return Effect.runPromise(materializeSourcesEffect(input)) + return Effect.runPromise(fetchChunkPageEffect(input).pipe(Effect.provide(FetchHttpClient.layer), Effect.provideService(FetchHttpClient.RequestInit, { cache: "no-store" }))) } // --------------------------------------------------------------------------- @@ -431,7 +360,6 @@ export const knowhereDemoApi = { fetchCatalog, fetchOptionalCatalog, fetchChunkPage, - materializeSources, resolveApiURL, } as const @@ -452,19 +380,27 @@ class KnowhereDemoApiError { ) {} } -function assertOkEffect( - response: Response, -): Effect.Effect { - if (response.ok) return Effect.void +function decodeDemoSource(source: Readonly>): DemoSource { + const decoded = Schema.decodeUnknownSync(Schema.Struct({ + demo_source_id: Schema.Unknown, canonical_document_id: Schema.Unknown, + namespace: Schema.Literal("__knowhere_demo__"), job_result_id: Schema.String.pipe(Schema.minLength(1)), + title: Schema.Unknown, mime_type: Schema.Unknown, size_bytes: Schema.Unknown, + chunk_count: Schema.Unknown, status: Schema.optional(Schema.Unknown), + original_file: Schema.optional(DemoResponseRecord), + official_library: Schema.optional(DemoResponseRecord), + }))(source) + return toDemoSource({ ...decoded, examples: decodeDemoExamples(source.examples) }) +} - return Effect.gen(function* () { - const body = yield* Effect.tryPromise(() => - response.text().catch(() => ""), - ).pipe(Effect.orDie) - return yield* Effect.fail( - new KnowhereDemoApiError(response.status, body), - ) - }) +function decodeDemoExamples(value: unknown): readonly DemoExampleResponse[] { + if (!Array.isArray(value)) return [] + return value.filter(isRecord).map((example) => ({ + ...example, + citations: Array.isArray(example.citations) ? example.citations.filter(isRecord).map((citation) => ({ + ...citation, + source: isRecord(citation.source) ? citation.source : undefined, + })) : [], + })) } function toDemoSource(source: DemoSourceResponse): DemoSource { @@ -476,6 +412,8 @@ function toDemoSource(source: DemoSourceResponse): DemoSource { return { demoSourceId, canonicalDocumentId: requireString(source.canonical_document_id), + namespace: optionalString(source.namespace) ?? "__knowhere_demo__", + ...(optionalString(source.job_result_id) ? { jobResultId: optionalString(source.job_result_id) } : {}), title, mimeType: requireString(source.mime_type), sizeBytes: requireNumber(source.size_bytes), @@ -525,10 +463,13 @@ function toDemoCitation( const pageCitationAssetUrl = toDemoAssetUrl( optionalString(citation.demo_source_id) ?? demoSourceId, optionalString(citation.page_citation_asset_url), + optionalString(citation.job_result_id), ) return { demoSourceId: optionalString(citation.demo_source_id) ?? demoSourceId, canonicalDocumentId, + namespace: optionalString(citation.namespace) ?? "__knowhere_demo__", + ...(optionalString(citation.job_result_id) ? { jobResultId: optionalString(citation.job_result_id) } : {}), canonicalChunkId: requireString( citation.canonical_chunk_id ?? citation.id ?? citation.demo_chunk_id, ), @@ -570,12 +511,15 @@ function toDemoChunkPage( response.document_id ?? fallback.canonicalDocumentId, ), + namespace: optionalString(response.namespace) ?? "__knowhere_demo__", + ...(optionalString(response.job_result_id) ? { jobResultId: optionalString(response.job_result_id) } : {}), title: requireString(response.title ?? fallback.title), mimeType: requireString(response.mime_type ?? fallback.mimeType), chunks: (response.chunks ?? []).map((chunk) => toDemoChunk( requireString(response.demo_source_id ?? fallback.demoSourceId), chunk, + optionalString(response.job_result_id), ), ), pagination: { @@ -590,10 +534,12 @@ function toDemoChunkPage( function toDemoChunk( demoSourceId: string, chunk: DemoChunkResponse, + jobResultId?: string, ): DemoChunk { const metadata = rewriteDemoPageAssetMetadata( demoSourceId, toRecord(chunk.metadata), + jobResultId, ) return { id: requireString(chunk.id), @@ -606,27 +552,12 @@ function toDemoChunk( sortOrder: requireNumber(chunk.sort_order), metadata, assetUrl: - toDemoAssetUrl(demoSourceId, optionalString(chunk.asset_url)) ?? + toDemoArtifactUrl(demoSourceId, optionalString(chunk.file_path), jobResultId) ?? + toDemoAssetUrl(demoSourceId, optionalString(chunk.asset_url), jobResultId) ?? firstDemoPageAssetUrl(metadata), } } -function toMaterializedDemoSource( - source: MaterializedDemoSourceResponse, -): MaterializedDemoSource { - const status = requireString(source.status) - return { - demoSourceId: requireString(source.demo_source_id), - documentId: requireString(source.document_id), - status: status === "existing" ? "existing" : "created", - title: requireString(source.title), - mimeType: requireString(source.mime_type), - sizeBytes: requireNumber(source.size_bytes), - chunkCount: requireNumber(source.chunk_count), - originalFile: toOriginalFile(source.original_file), - } -} - function toOfficialLibraryCatalog( input: OfficialLibraryCatalogResponse | undefined, ): OfficialLibraryCatalog { @@ -716,12 +647,13 @@ function toRecord(value: unknown): Readonly> { if (typeof value !== "object" || value === null || Array.isArray(value)) { return {} } - return value as Readonly> + return Schema.decodeUnknownSync(DemoResponseRecord)(value) } function rewriteDemoPageAssetMetadata( demoSourceId: string, metadata: Readonly>, + jobResultId?: string, ): Readonly> { const rawAssets = metadata.pageAssets ?? metadata.page_assets if (!Array.isArray(rawAssets)) return metadata @@ -730,7 +662,7 @@ function rewriteDemoPageAssetMetadata( if (typeof item !== "object" || item === null || Array.isArray(item)) { return [] } - const asset = item as Readonly> + const asset = toRecord(item) const pageNum = optionalPositiveNumber(asset.pageNum) ?? optionalPositiveNumber(asset.pageNumber) ?? @@ -738,13 +670,11 @@ function rewriteDemoPageAssetMetadata( const contentType = optionalString(asset.contentType) ?? optionalString(asset.content_type) const artifactRef = optionalString(asset.artifact_ref) - const remoteAssetUrl = - optionalString(asset.assetUrl) ?? - optionalString(asset.asset_url) ?? - (artifactRef - ? `/api/v1/demo/sources/${encodeURIComponent(demoSourceId)}/assets/${artifactRef}` - : undefined) - const assetUrl = toDemoAssetUrl(demoSourceId, remoteAssetUrl) + const assetUrl: string | null = toDemoArtifactUrl(demoSourceId, artifactRef, jobResultId) ?? toDemoAssetUrl( + demoSourceId, + optionalString(asset.assetUrl) ?? optionalString(asset.asset_url), + jobResultId, + ) if (!pageNum || !contentType || !assetUrl) return [] return [ @@ -774,7 +704,7 @@ function firstDemoPageAssetUrl( if (!Array.isArray(pageAssets) || pageAssets.length === 0) return null const first = pageAssets[0] if (typeof first !== "object" || first === null) return null - return optionalString((first as Readonly>).assetUrl) ?? null + return optionalString(toRecord(first).assetUrl) ?? null } function optionalPositiveNumber(value: unknown): number | undefined { @@ -807,19 +737,28 @@ function toPositiveIntegers( function toDemoAssetUrl( demoSourceId: string, assetUrl: string | undefined, + jobResultId?: string, ): string | null { if (!assetUrl) return null - - const assetPath = extractDemoAssetPath(assetUrl) - if (!assetPath) return null - - return `/api/demo-sources/${encodeURIComponent(demoSourceId)}/assets/${assetPath}` + const remoteUrl: URL = new URL(assetUrl, "https://notebook.invalid") + const marker: string = "/assets/" + const markerIndex: number = remoteUrl.pathname.indexOf(marker) + if (markerIndex === -1) return null + const assetPath: string = remoteUrl.pathname.slice(markerIndex + marker.length) + const parameters: URLSearchParams = new URLSearchParams() + const revision: string | null | undefined = jobResultId ?? remoteUrl.searchParams.get("job_result_id") + if (revision) parameters.set("job_result_id", revision) + const query: string = parameters.size > 0 ? `?${parameters.toString()}` : "" + return `/api/demo-sources/${encodeURIComponent(demoSourceId)}/assets/${assetPath}${query}` } -function extractDemoAssetPath(assetUrl: string): string | null { - const marker = "/assets/" - const markerIndex = assetUrl.indexOf(marker) - if (markerIndex === -1) return null +function isRecord(value: unknown): value is Readonly> { + return typeof value === "object" && value !== null && !Array.isArray(value) +} - return assetUrl.slice(markerIndex + marker.length) +function toDemoArtifactUrl(demoSourceId: string, artifactRef: string | undefined, jobResultId: string | undefined): string | null { + if (!artifactRef || artifactRef.startsWith("/") || artifactRef.includes("\\")) return null + const segments: readonly string[] = artifactRef.split("/") + if (segments.some((segment) => segment.length === 0 || segment === "." || segment === "..")) return null + return toDemoAssetUrl(demoSourceId, `/api/v1/demo/sources/${encodeURIComponent(demoSourceId)}/assets/${segments.map(encodeURIComponent).join("/")}`, jobResultId) }