SPB Git

Repository Public

next-p-cv-inbox.test.ts 9.9 KB 111 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Note SPBoucher AI8 * File             : tests/unit/next-p-cv-inbox.test.ts9 * Description      : Smart Inbox checklist (SPEC §4.12). Pure selection model10 *                    (nothing ticked at the start, only the ticked subset is11 *                    sent, with the owner's edits), the wording of errors, and12 *                    — on the scratch database, without any model — that a body13 *                    built by the checklist is accepted by `applySuggestions`,14 *                    changes exactly the chosen things and is undone by the15 *                    journal.16 * Module           : tests17 * Repository       : https://git.spboucher.ai/note-spboucher-ai18 * Project Website  : https://note.spboucher.ai19 * Created          : 2026-11-1920 * Last Modified    : 2026-11-1921 *22 * Author           : Simon-Pierre Boucher23 * Position         : Professor of Finance24 * Institution      : Université du Québec en Outaouais (UQO)25 * Organization     : SP Boucher26 * Website          : https://spboucher.ai27 * Git              : https://git.spboucher.ai28 *29 * Preferred Contact: contact@spboucher.ai30 * Development      : dev@spboucher.ai31 * Support          : support@spboucher.ai32 * Security/Admin   : admin@spboucher.ai33 *34 * Copyright (c) 202635 * Simon-Pierre Boucher36 * All rights reserved where applicable. This file is governed by the37 * applicable project license, copyright notices and relevant law.38 * Existing third-party rights and notices remain unaffected.39 *40 * License          : None specified (no license file in this repository)41 *42 * Do not embed credentials, private keys, access tokens,43 * certificates or confidential personal information.44 *45 * =============================================================================46 * END OF SP BOUCHER SOURCE HEADER47 * =============================================================================48 */4950import "../helpers/testdb";51import { test, after } from "node:test";52import assert from "node:assert/strict";53import { and, eq, inArray } from "drizzle-orm";54import { db, schema, sql } from "../../src/db/index";55import { capture, pageTags } from "../../src/lib/inbox/service";56import { createPage, getPage } from "../../src/lib/pages/service";57import { applySuggestions, undoInboxAction } from "../../src/lib/ai/inbox";58import type { PMNode } from "../../src/lib/editor/text";59import { buildApplyBody, countChosen, countOffered, destinationLabel, emptyChoice, hasSuggestions, selectAll, suggestionError, type Suggestions } from "../../src/lib/client/inbox-suggest";6061const TAG = `pcvi${Date.now().toString(36)}`; const made: string[] = [];62const REL = "11111111-1111-4111-8111-111111111111", PARENT = "22222222-2222-4222-8222-222222222222";63const S: Suggestions = { title: { value: "Rappeler la banque", current: "rappeler banque" }, tags: [{ name: "banque", existing: true }, { name: "triplex", existing: false }], destination: { section: "projects", parentId: PARENT, parentTitle: "Refinancement" }, relations: [{ pageId: REL, title: "Offre", icon: null, reason: "Même financement." }], summary: "Rappeler la banque pour la garantie de taux." };64after(async () => {65  if (made.length) { await db.delete(schema.knowledgeEdges).where(inArray(schema.knowledgeEdges.fromId, made)); await db.delete(schema.inboxActions).where(inArray(schema.inboxActions.pageId, made)); await db.delete(schema.knowledgeEvents).where(inArray(schema.knowledgeEvents.pageId, made)); await db.delete(schema.pages).where(inArray(schema.pages.id, made)); await db.delete(schema.syncTombstones).where(inArray(schema.syncTombstones.id, made)); }66  const [w] = await db.select().from(schema.workspaces).limit(1); if (w) await db.delete(schema.tags).where(and(eq(schema.tags.workspaceId, w.id), inArray(schema.tags.name, [`a${TAG}`, `b${TAG}`])));67  await sql.end();68});6970test("checklist: nothing is ticked at the start, so nothing can be applied by accident", () => {71  const c = emptyChoice(S);72  assert.equal(countOffered(S), 6); assert.equal(hasSuggestions(S), true); assert.equal(countChosen(S, c), 0); assert.equal(buildApplyBody(S, c), null);73  assert.equal(c.titleValue, "Rappeler la banque"); assert.equal(c.summaryValue, S.summary);74  const none: Suggestions = { title: null, tags: [], destination: null, relations: [], summary: null }; assert.equal(hasSuggestions(none), false); assert.equal(buildApplyBody(none, selectAll(none, emptyChoice(none), true)), null);75});76test("checklist: only the ticked subset is sent, with the owner's edits; an emptied text is not sent", () => {77  let c = emptyChoice(S); c = { ...c, tags: { triplex: true }, summary: true, summaryValue: "  Mon   résumé corrigé. " };78  assert.equal(countChosen(S, c), 2); assert.deepEqual(buildApplyBody(S, c), { tags: ["triplex"], summary: "Mon résumé corrigé." });79  c = { ...c, title: true, titleValue: "   " }; assert.equal(countChosen(S, c), 2, "an emptied title does not count"); assert.equal("title" in buildApplyBody(S, c)!, false);80  const all = selectAll(S, emptyChoice(S), true); assert.equal(countChosen(S, all), 6);81  assert.deepEqual(buildApplyBody(S, all), { title: "Rappeler la banque", tags: ["banque", "triplex"], destination: { section: "projects", parentId: PARENT }, relations: [{ pageId: REL, reason: "Même financement." }], summary: "Rappeler la banque pour la garantie de taux." });82  assert.equal(countChosen(S, selectAll(S, all, false)), 0); assert.deepEqual(buildApplyBody(S, { ...emptyChoice(S), destination: true }), { destination: { section: "projects", parentId: PARENT } });83  assert.deepEqual(buildApplyBody(S, { ...emptyChoice(S), tags: { ghost: true } }), null, "a tick on something the server did not offer is ignored");84  assert.equal(destinationLabel(S.destination!), "Projects › Refinancement"); assert.equal(destinationLabel({ section: "research", parentId: null, parentTitle: null }), "Research");85});86test("errors are worded for the owner, and say whether a retry makes sense", () => {87  assert.deepEqual([suggestionError({ status: 503, code: "no_model" }).title, suggestionError({ status: 503, code: "no_model" }).retry], ["No AI model is available", false]);88  assert.equal(suggestionError({ status: 502, code: "provider_error", message: "The AI provider failed: 529" }).hint, "The AI provider failed: 529"); assert.equal(suggestionError({ status: 502, code: "refused" }).title, "The model declined this capture");89  assert.equal(suggestionError({ status: 409, code: "not_in_inbox" }).retry, false); assert.equal(suggestionError({ status: 409, code: "conflict" }).retry, true); assert.equal(suggestionError({ status: 0, code: "network" }).title, "No connection");90  assert.equal(suggestionError({ status: 400, code: "bad_relation" }).title, "A suggested page no longer exists"); assert.equal(suggestionError({ status: 500, message: "boom" }).hint, "boom"); assert.equal(suggestionError(null).retry, true);91});92test("a body built by the checklist is accepted by the server, applies exactly the chosen subset and is fully undone", async () => {93  const [w] = await db.select().from(schema.workspaces).limit(1); assert.ok(w); const ws = w.id;94  const parent = await createPage(ws, { title: `Projet ${TAG}`, section: "projects" }); made.push(parent.id); const rel = await createPage(ws, { title: `Lié ${TAG}` }); made.push(rel.id);95  const cap = await capture(ws, { kind: "note", text: `capture brute ${TAG}\nSeconde ligne.` }); made.push(cap.id); const before = await getPage(ws, cap.id);96  const offered: Suggestions = { title: { value: `Capture propre ${TAG}`, current: cap.title }, tags: [{ name: `a${TAG}`, existing: false }, { name: `b${TAG}`, existing: false }], destination: { section: "projects", parentId: parent.id, parentTitle: parent.title }, relations: [{ pageId: rel.id, title: rel.title, icon: null, reason: "Même sujet." }], summary: "Résumé proposé." };97  // the owner keeps the title (edited), one tag out of two, the relation and the summary — NOT the destination98  const choice = { ...emptyChoice(offered), title: true, titleValue: `Titre choisi ${TAG}`, tags: { [`a${TAG}`]: true }, relations: { [rel.id]: true }, summary: true };99  const r = await applySuggestions(ws, cap.id, buildApplyBody(offered, choice)!);100  assert.deepEqual([...r.applied].sort(), ["relations", "summary", "tags", "title"]); assert.equal(r.filed, false);101  const p = await getPage(ws, cap.id); assert.equal(p.title, `Titre choisi ${TAG}`); assert.ok(p.inboxAt, "not moved: the destination was not ticked"); assert.equal(p.parentId, null); assert.deepEqual(await pageTags(cap.id), [`a${TAG}`]);102  const first = (p.content as unknown as PMNode).content![0]; assert.equal(first.type, "aiBlock"); assert.equal(first.attrs!.action, "summary", "the applied summary stays visibly AI");103  assert.equal((await db.select().from(schema.knowledgeEdges).where(and(eq(schema.knowledgeEdges.fromId, cap.id), eq(schema.knowledgeEdges.toId, rel.id)))).length, 1);104  assert.deepEqual(await undoInboxAction(ws, r.actionId), { ok: true, already: false });105  const u = await getPage(ws, cap.id); assert.equal(u.title, before.title); assert.deepEqual(await pageTags(cap.id), []); assert.equal((u.content as unknown as PMNode).content!.some((n) => n.type === "aiBlock"), false); assert.ok(u.inboxAt);106  assert.equal((await db.select().from(schema.knowledgeEdges).where(eq(schema.knowledgeEdges.fromId, cap.id))).length, 0);107  // ticking the destination files the capture; undo brings it back108  const f = await applySuggestions(ws, cap.id, buildApplyBody(offered, { ...emptyChoice(offered), destination: true })!); assert.equal(f.filed, true); const filed = await getPage(ws, cap.id); assert.equal(filed.inboxAt, null); assert.equal(filed.parentId, parent.id);109  await undoInboxAction(ws, f.actionId); assert.ok((await getPage(ws, cap.id)).inboxAt);110});111
Files main
Menu

Theme