Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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

Expand Down
65 changes: 65 additions & 0 deletions docs/shared-demo-client-migration.md
Original file line number Diff line number Diff line change
@@ -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.
43 changes: 35 additions & 8 deletions e2e/chunk-original-preview.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -27,19 +37,36 @@ test("reopens the demo PDF preview after returning from original to parsed chunk

async function openFirstChunk(page: Page): Promise<void> {
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<void> {
await expect(page.getByText(unsupportedPreviewText)).toBeHidden()
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)
}
40 changes: 40 additions & 0 deletions e2e/shared-demo-chat.e2e.ts
Original file line number Diff line number Diff line change
@@ -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")
})
1 change: 1 addition & 0 deletions playwright.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand Down
7 changes: 7 additions & 0 deletions src/agent-harness/ledger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
24 changes: 21 additions & 3 deletions src/agent-harness/ledger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
} from "@ontos-ai/knowhere-sdk"

import type {
ConnectedAssetLookup,
EvidenceAsset,
EvidenceChunk,
EvidenceLedgerSnapshot,
Expand Down Expand Up @@ -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,
Expand All @@ -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 } : {}),
},
})
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -213,14 +218,17 @@ 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,
source: {
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 } : {}),
},
})
Expand Down Expand Up @@ -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)
}
Expand All @@ -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 {
Expand Down Expand Up @@ -646,3 +658,9 @@ function getDecisionTrace(response: RetrievalQueryResponse): unknown | null {
null
)
}

function getSourceProvenance(metadata?: Readonly<Record<string, unknown>>): { readonly namespace?: string; readonly jobResultId?: string } {
const namespace = getTrimmedString(metadata?.namespace)
const jobResultId = getTrimmedString(metadata?.jobResultId)
return { ...(namespace ? { namespace } : {}), ...(jobResultId ? { jobResultId } : {}) }
}
5 changes: 5 additions & 0 deletions src/agent-harness/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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
Expand All @@ -191,6 +194,8 @@ export type EvidenceChunk = {
readonly metadata?: Readonly<Record<string, unknown>>
readonly source: {
readonly documentId?: string | null
readonly namespace?: string
readonly jobResultId?: string
readonly sourceFileName?: string | null
readonly sectionPath?: string | null
}
Expand Down
Loading
Loading