SPB Git

Repository Public

next-canvas-index.test.ts 7.5 KB 106 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/next-canvas-index.test.ts9 * Description      : the text written on a canvas is searchable — `putCanvas`10 *                    copies the text of the cards (text, LaTeX, addresses, edge11 *                    labels) into the plain text of the canvas page (full-text12 *                    `tsv`, word count), keeps it in step with later saves, and13 *                    a rename of the page does not erase it. Runs against a14 *                    *_dev database.15 * Module           : tests16 * Repository       : https://git.spboucher.ai/note-spboucher-ai17 * Project Website  : https://note.spboucher.ai18 * Created          : 2026-11-1919 * Last Modified    : 2026-11-1920 *21 * Author           : Simon-Pierre Boucher22 * Position         : Professor of Finance23 * Institution      : Université du Québec en Outaouais (UQO)24 * Organization     : SP Boucher25 * Website          : https://spboucher.ai26 * Git              : https://git.spboucher.ai27 *28 * Preferred Contact: contact@spboucher.ai29 * Development      : dev@spboucher.ai30 * Support          : support@spboucher.ai31 * Security/Admin   : admin@spboucher.ai32 *33 * Copyright (c) 202634 * Simon-Pierre Boucher35 * All rights reserved where applicable. This file is governed by the36 * applicable project license, copyright notices and relevant law.37 * Existing third-party rights and notices remain unaffected.38 *39 * License          : None specified (no license file in this repository)40 *41 * Do not embed credentials, private keys, access tokens,42 * certificates or confidential personal information.43 *44 * =============================================================================45 * END OF SP BOUCHER SOURCE HEADER46 * =============================================================================47 */4849import { test, before, after } from "node:test";50import assert from "node:assert/strict";51import { eq } from "drizzle-orm";52import { db, schema, sql } from "../../src/db/index";53import { workspace, mk, cleanup } from "../helpers/next";54import { putCanvas } from "../../src/lib/canvas/service";55import { EMPTY_CANVAS, type CanvasData } from "../../src/lib/canvas/format";56import { updatePage } from "../../src/lib/pages/service";57import http from "node:http";58import type { AddressInfo } from "node:net";5960let ws: string; const PFX = "nx-canvas-index ·";61before(async () => { ws = await workspace(); }); after(() => cleanup(ws, PFX));62const plain = async (id: string) => { const [p] = await db.select({ plainText: schema.pages.plainText, wordCount: schema.pages.wordCount }).from(schema.pages).where(eq(schema.pages.id, id)); return p; };63const fts = async (q: string) => (await sql`select id from pages where workspace_id = ${ws} and deleted_at is null and tsv @@ plainto_tsquery('simple', ${q})`).map((r) => r.id as string);6465test("saving a canvas indexes the text of its cards and edge labels into the page; later saves replace it; a rename keeps it", async () => {66  const p = await mk(ws, `${PFX} map`, undefined, { type: "canvas" });67  assert.equal((await plain(p.id)).plainText, "");68  const data: CanvasData = { ...EMPTY_CANVAS(), nodes: [69    { id: "a", kind: "text", x: 0, y: 0, w: 200, h: 80, z: 0, text: "Zygomorphic hypothesis about prices" },70    { id: "b", kind: "math", x: 300, y: 0, w: 200, h: 80, z: 1, latex: "\\sigma_t^2" },71    { id: "c", kind: "link", x: 600, y: 0, w: 200, h: 80, z: 2, url: "https://example.org/quokkapaper", text: "Quokka paper" },72    { id: "d", kind: "table", x: 0, y: 200, w: 200, h: 80, z: 3, text: "| Year | Rate |\n| --- | --- |\n| 2025 | wombatrate |" },73  ], edges: [{ id: "e1", from: "a", to: "b", label: "xylophonic link" }] };74  await putCanvas(ws, p.id, data, 1);75  const one = await plain(p.id);76  assert.equal(one.plainText, "Zygomorphic hypothesis about prices\n\\sigma_t^2\nQuokka paper\nhttps://example.org/quokkapaper\nYear Rate\n2025 wombatrate\nxylophonic link");77  assert.equal(one.wordCount > 8, true);78  for (const word of ["zygomorphic", "quokka", "wombatrate", "xylophonic"]) assert.ok((await fts(word)).includes(p.id), `full-text search finds the canvas by "${word}"`);79  await updatePage(ws, p.id, { title: `${PFX} map renamed` });80  assert.ok((await fts("zygomorphic")).includes(p.id), "renaming the page keeps the canvas text");81  await putCanvas(ws, p.id, { ...data, nodes: data.nodes.slice(1), edges: [] }, 2);82  assert.ok(!(await fts("zygomorphic")).includes(p.id), "text of a removed card is no longer found"); assert.ok(!(await fts("xylophonic")).includes(p.id)); assert.ok((await fts("quokka")).includes(p.id));83  await putCanvas(ws, p.id, EMPTY_CANVAS(), 3); assert.deepEqual(await plain(p.id), { plainText: "", wordCount: 0 });84});8586test("the index worker reads a canvas page from its cards' text: passages are stored and the search finds the canvas (fake embeddings endpoint, no network)", async () => {87  // local stand-in for the embeddings API: same wire format, constant vectors — no key, no cost88  const seen: string[] = [];89  const server = http.createServer((req, res) => { let body = ""; req.on("data", (c) => (body += c)); req.on("end", () => { const input: string[] = JSON.parse(body).input; seen.push(...input); res.setHeader("content-type", "application/json"); res.end(JSON.stringify({ object: "list", model: "fake", data: input.map((_t, index) => ({ object: "embedding", index, embedding: Array.from({ length: 1536 }, (_v, i) => (i === 0 ? 1 : 0)) })), usage: { prompt_tokens: 1, total_tokens: 1 } })); }); });90  await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));91  const saved = { url: process.env.OPENAI_BASE_URL, key: process.env.OPENAI_API_KEY };92  process.env.OPENAI_BASE_URL = `http://127.0.0.1:${(server.address() as AddressInfo).port}/v1`; process.env.OPENAI_API_KEY = "sk-fake-canvas-index";93  try {94    const { handleIndex } = await import("../../src/worker/handlers/index-source");95    const { hybridSearch } = await import("../../src/lib/search/index");96    const p = await mk(ws, `${PFX} indexed`, undefined, { type: "canvas" });97    await putCanvas(ws, p.id, { ...EMPTY_CANVAS(), nodes: [{ id: "a", kind: "text", x: 0, y: 0, w: 200, h: 80, z: 0, text: "Brachiosaurus liquidity premium" }], edges: [] }, 1);98    const r = (await handleIndex({ sourceType: "page", sourceId: p.id, workspaceId: ws })) as { skipped?: boolean; chunks?: number };99    assert.equal(r.skipped, false); assert.ok((r.chunks ?? 0) >= 1);100    const chunks = await db.select({ content: schema.chunks.content }).from(schema.chunks).where(eq(schema.chunks.sourceId, p.id));101    assert.ok(chunks.some((c) => c.content.includes("Brachiosaurus liquidity premium")), "the passage holds the card's text"); assert.ok(seen.some((t) => t.includes("Brachiosaurus")), "…and it was embedded");102    const hits = await hybridSearch(ws, "brachiosaurus", { semantic: false, limit: 5 }); assert.ok(hits.some((h) => h.pageId === p.id), "search finds the canvas by a word of a card");103    await db.delete(schema.chunks).where(eq(schema.chunks.sourceId, p.id)); await db.delete(schema.indexState).where(eq(schema.indexState.sourceId, p.id));104  } finally { if (saved.url === undefined) delete process.env.OPENAI_BASE_URL; else process.env.OPENAI_BASE_URL = saved.url; if (saved.key === undefined) delete process.env.OPENAI_API_KEY; else process.env.OPENAI_API_KEY = saved.key; await new Promise((r) => server.close(r)); }105});106
Files main
Menu

Theme