Implement CE-WP-0005 T01-T08: demo app — sessions, uploads, ZIP archive

Turn the MVP into a self-contained demo. Users now:
  1. Land on an empty-state and create a named session.
  2. Drag-drop or pick arbitrary PDFs into that session.
  3. Annotate, build evidence, link to form fields — all session-scoped.
  4. Export the whole session as a single .zip archive (manifest +
     per-document PDFs).
  5. Import a .zip back — into a new session, or merged into an
     existing one (documents deduped by SHA-256 fingerprint;
     annotations/evidence/links added additively).

Architecture:
- New shared types: SessionId, Session, SessionArchiveManifest +
  parseSessionArchiveManifest with schema-version validation.
- SessionService (engine/services/sessions.ts) handles lifecycle
  (create/rename/delete/setActive) + emits 4 new events through its
  own bus; SharedContracts.md §4 lists the additions.
- SessionProvider (work/SessionContext.tsx) owns the cross-session
  state: service, per-session PdfByteStore registry, per-session
  version counter that drives EngineProvider remounts after imports.
- EngineProvider becomes session-aware (sessionId prop drives per-
  session localStorage keys). Bumping engineRevision after
  restoreFromStorage forces consumers to re-render so restored repos
  show up immediately.
- PdfByteStore (source/pdf/byte-store.ts) holds Uint8Array bytes per
  document and mints blob URLs; ingestPdfFromFile is the upload
  entry-point that wraps the existing ingestPdf pipeline.
- ADR-0008 locks the ZIP layout (manifest.json + documents/<id>.pdf),
  the manifest schema (schemaVersion 1), and the merge-on-collision
  policy. JSZip is the only new dependency.
- App.tsx restructured: SessionProvider at the root, EngineProvider
  keyed by ${sessionId}:${version}, hash routing #/s/<id>[/forms/demo],
  SessionMenu top-bar, CreateFirstSession empty state.
- New DocumentRemoved event for per-document delete cleanup in
  CollectionList; engine.documents.remove() is the new service method.

Tests:
- Unit: 16 SessionService lifecycle + persistence tests;
  per-session snapshot round-trip; PdfByteStore + ingestPdfFromFile;
  SessionArchive parser; exportSessionZip + importSessionZip with
  create + merge + corrupt-archive paths.
- DOM: UploadDropzone, session-scoped CollectionList delete,
  SessionMenu create/switch/rename, routing parser.
- E2E: tests/integration/session-export-reimport.dom.test.tsx walks
  the full create → annotate → export → reimport flow and asserts
  the additive merge (deduped doc + doubled evidence rows).
- Legacy E2Es updated to use a seed-session helper instead of the
  removed fixture-button flow.

Known limitation (documented in ADR-0008): re-importing your own
freshly-exported ZIP creates duplicate annotations. Forward pointer
left for an importBundleId follow-up.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-26 14:57:28 +02:00
parent 8632f7b04a
commit 779ae0d317
53 changed files with 5657 additions and 372 deletions

View File

@@ -28,8 +28,6 @@ import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Selector } from "@shared/selector";
import type { DocumentId, RepresentationId } from "@shared/ids";
import type { Document, DocumentRepresentation } from "@shared/document";
import type { PdfSelectionCapture } from "@anchor/index";
import manifest from "../../fixtures/pdfs/manifest.json" with { type: "json" };
@@ -90,42 +88,8 @@ const SYNTHETIC_CANONICAL = [
"Trailing prose that comes after the quote.",
].join(" ");
vi.mock("@source/index", async (importOriginal) => {
const original = await importOriginal<typeof import("@source/index")>();
return {
...original,
ingestPdf: vi.fn(async (_input: unknown, options?: { filename?: string }) => {
const documentId = ("doc_test_" + Math.random().toString(36).slice(2, 10)) as DocumentId;
const representationId = ("rep_test_" + Math.random().toString(36).slice(2, 10)) as RepresentationId;
const document: Document = {
id: documentId,
mediaType: "application/pdf",
...(options?.filename ? { title: options.filename } : {}),
fingerprint: "synthetic-fingerprint-for-test",
createdAt: "2026-05-25T00:00:00.000Z",
updatedAt: "2026-05-25T00:00:00.000Z",
};
const representation: DocumentRepresentation = {
id: representationId,
documentId,
representationType: "pdf-text",
contentHash: "synthetic-fingerprint-for-test",
canonicalText: SYNTHETIC_CANONICAL,
pageMap: [{ page: 1, width: 595, height: 842 }],
offsetMap: [
{
page: 1,
globalStart: 0,
globalEnd: SYNTHETIC_CANONICAL.length,
pageLength: SYNTHETIC_CANONICAL.length,
},
],
generatedAt: "2026-05-25T00:00:00.000Z",
};
return { document, representation };
}),
};
});
// CE-WP-0005: pre-seed a session with the fixture doc; no ingestPdf mock needed.
import { seedSessionWithDoc, type SeedResult } from "./helpers/seed-session";
// ---------------------------------------------------------------------------
// Helpers
@@ -160,40 +124,40 @@ async function loadApp() {
// ---------------------------------------------------------------------------
describe("App — PRD scenario steps 1-8 (CE-WP-0002-T09)", () => {
let seeded: SeedResult;
beforeEach(() => {
resetViewerSnapshot();
// Each test starts with empty localStorage.
globalThis.localStorage?.clear();
// The fetch isn't reached (ingestPdf is mocked) — but stub it so that
// any accidental call returns gracefully instead of TypeError.
globalThis.fetch = vi.fn(async () =>
new Response(new Uint8Array([0x25, 0x50, 0x44, 0x46]).buffer, {
status: 200,
headers: { "Content-Type": "application/pdf" },
}),
);
if (typeof window !== "undefined") {
history.replaceState(null, "", window.location.pathname);
}
seeded = seedSessionWithDoc({
sessionName: "Demo",
documentTitle: FIXTURE.filename,
canonicalText: SYNTHETIC_CANONICAL,
});
});
afterEach(() => {
vi.restoreAllMocks();
});
it("walks the full slice-1 scenario: load → select → save → reload → click → scroll", async () => {
it("walks the full slice-1 scenario: load → select → save → reload → click → scroll", { timeout: 15000 }, async () => {
const user = userEvent.setup();
// Step 1: open the app.
// Step 1: open the app. CE-WP-0005: a pre-seeded session boots
// straight into the active layout (no empty state).
const { unmount } = await loadApp();
expect(screen.getByText("Collection")).toBeTruthy();
expect(screen.queryByTestId("empty-state")).toBeNull();
expect(screen.getByTestId("session-menu-toggle").textContent).toContain("Demo");
// Step 2: pick a fixture.
const fixtureButton = screen.getByRole("button", { name: new RegExp(FIXTURE.id) });
await user.click(fixtureButton);
// The mock viewer should have mounted with our test URL.
// Step 2: the fixture doc is pre-seeded into the active session, so
// the viewer mounts automatically — no fixture-button click needed.
await waitFor(() => {
expect(viewerSnapshot.pdfUrl).toBeTruthy();
expect(viewerSnapshot.onSelectionCaptured).not.toBeNull();
});
expect(decodeURIComponent(viewerSnapshot.pdfUrl!)).toContain(FIXTURE.filename);
// Step 3: programmatically inject a selection for the known-good quote.
expect(viewerSnapshot.onSelectionCaptured).not.toBeNull();
@@ -223,9 +187,11 @@ describe("App — PRD scenario steps 1-8 (CE-WP-0002-T09)", () => {
});
const savedAnnotationId = viewerSnapshot.storedAnnotationIds[0]!;
// Snapshot key from EngineContext.STORAGE_KEY — implementation detail
// Per-session snapshot key from CE-WP-0005 — implementation detail
// but worth asserting once at the integration layer.
const stored = globalThis.localStorage?.getItem("citation-evidence:engine-snapshot:v1");
const stored = globalThis.localStorage?.getItem(
`citation-evidence:session:${seeded.sessionId}:engine-snapshot:v1`,
);
expect(stored).toBeTruthy();
// Step 6: reload — unmount and remount the App. The same localStorage is
@@ -237,9 +203,8 @@ describe("App — PRD scenario steps 1-8 (CE-WP-0002-T09)", () => {
// The viewer should re-mount automatically because the active document
// was persisted.
await waitFor(() => {
expect(viewerSnapshot.pdfUrl).toBeTruthy();
expect(viewerSnapshot.onSelectionCaptured).not.toBeNull();
});
expect(decodeURIComponent(viewerSnapshot.pdfUrl!)).toContain(FIXTURE.filename);
// The sidebar should show the restored item.
const restoredItem = await screen.findByText(/Important deadline clause/);