SOURCE / PINNED RELEASE
Made of little things.
Body Journal
- Release
- e8049f8da4e2…
- Author-recorded commit
- 61c04bf0e8aa…
- License
- LICENSE
- Author’s source reference
- nostr://npub182jczunncwe0jn6frpqwq3e0qjws7yqqnc3auccqv9nte2dnd63scjm4rf/wss%3A%2F%2Fgit.napplet.soy%2F/n-6c4554844c7
Archive hash verified: 4369d778da046a8b…. The source-to-build association is the author’s claim; it has not been independently rebuilt.
import { detailedReport } from "./report-fixture.mjs";
import { seedSyntheticCase } from "./synthetic-case-ui.mjs";
import assert from "node:assert/strict";
import { createHash, randomBytes } from "node:crypto";
import { schnorr } from "@noble/curves/secp256k1.js";
import QRCode from "qrcode";
const canon=v=>JSON.stringify(v,(_k,x)=>x&&typeof x==='object'&&!Array.isArray(x)?Object.fromEntries(Object.keys(x).sort().map(k=>[k,x[k]])):x);
const hash=v=>createHash('sha256').update(canon(v)).digest('hex');
const identities=new Map(), challenges=new Map();
let exportedPdf, qrImage, privateRecovery;
import { createRequire } from "node:module";
import { realpathSync } from "node:fs";
import { readFile, mkdir, writeFile } from "node:fs/promises";
import { execFileSync } from "node:child_process";
import { resolve } from "node:path";
const require = createRequire(
realpathSync("node_modules/@napplet/conformance-cli/package.json"),
);
const { chromium } = require("playwright");
const info = JSON.parse(
execFileSync("soyli", ["browser", "path", "--json"], { encoding: "utf8" }),
);
const browser = await chromium.launch({
executablePath: info.executables.find(
(e) => e.name === "chromium" && e.installed,
)?.path,
headless: true,
});
const html = await readFile("dist/index.html", "utf8"),
output = resolve(".napplet-space/llm-value-checks");
await mkdir(output, { recursive: true });
const saved = new Map(),
calls = [],
errors = [];
let settled = false,
walletPaid = false,
confirmations = 0,
statusReads = 0,
order,
finish = "stop",
unexpectedBlock = false,
checkoutEnabled = true,
jsonMode = false,
selectionRequirements = [],
quotes = 0,
payments = 0,
nativeCalls = 0;
const report = detailedReport([1, 2]);
let paidReport = detailedReport([999]),
onInfo;
try {
const page = await browser.newPage({
viewport: { width: 1200, height: 800 },
});
page.setDefaultTimeout(15000);
page.on("pageerror", (e) => errors.push(e.message));
await page.exposeFunction("__saveBackup", (_path,data)=>{ exportedPdf=Buffer.from(data,'base64');return {bytesWritten:exportedPdf.length}; });
await page.exposeFunction("__readQr", (_path,options)=>{const bytes=qrImage.subarray(options.offset,options.offset+options.length);return {data:bytes.toString('base64'),offset:options.offset,bytesRead:bytes.length,eof:options.offset+bytes.length>=qrImage.length};});
await page.exposeFunction("__get", (k) => saved.get(k) ?? null);
await page.exposeFunction("__set", (k, v) => {
saved.set(k, v);
});
await page.exposeFunction("__remove", (k) => {
saved.delete(k);
});
await page.exposeFunction("__select", (requirements) => {
selectionRequirements.push(requirements);
// Existing Studio connections have no declared JSON capability.
if (requirements.json && !jsonMode) throw new Error("No saved connection meets the requested capabilities.");
return { handle: 'fixture', name: 'Test connection', model: 'fixture', route: 'Fixture only', images: true, json: jsonMode };
});
await page.exposeFunction("__generate", (r) => {
calls.push(r);
assert.equal(r.messages[0].role, "system");
assert.equal(r.format, jsonMode ? "json" : "text");
if (unexpectedBlock) return { content: [{ type: "toolCall", name: "unexpected", toolCallId: "test", arguments: {} }], finish };
const json = JSON.stringify(report);
return { content: [
{ type: "thinking", text: "Display-only fixture; this is not report JSON." },
{ type: "text", text: json.slice(0, 35) },
{ type: "text", text: json.slice(35) },
], finish };
});
await page.exposeFunction("__tool", async (ref, tool, args, options) => {
assert.equal(
options.payment,
tool === "body_journal_paid_run" ? "prompt" : "deny",
);
assert.equal(ref.pubkey, "a".repeat(64));
let state;
if (tool === "body_journal_paid_info") {
if (onInfo) await onInfo();
state = {
ok: true,
version: 2,
reportIdentity: true,
paymentProtocol: "cep8",
checkoutEnabled,
encryptionRequired: true,
priceSats: 21,
paymentConfirmation: "manual",
provider: "fixture",
model: "test",
retention: "Fixture only",
refundPolicy: "Fixture only",
};
} else if(tool === "body_journal_identity_challenge") {
const c={service:ref.pubkey,pubkey:args.pubkey,action:args.action,digest:args.digest,nonce:randomBytes(32).toString('hex'),expiresAt:Date.now()+120000};challenges.set(c.nonce,c);state={ok:true,challenge:c};
} else if(tool === "body_journal_identity_execute") {
const c=challenges.get(args.challenge.nonce);assert.ok(c);assert.equal(c.digest,hash(args.args));
const digest=createHash('sha256').update(JSON.stringify(['ai-doc-identity/v1',c.service,c.pubkey,c.nonce,c.action,c.digest,c.expiresAt])).digest();
assert.equal(schnorr.verify(Buffer.from(args.signature,'hex'),digest,Buffer.from(c.pubkey,'hex')),true);
assert.ok(!privateRecovery || !JSON.stringify(args).includes(privateRecovery),'private key never sent to CVM');challenges.delete(c.nonce);
const rows=identities.get(c.pubkey)||[];
if(c.action==='attach'){rows.push({...args.args,orderId:'d'.repeat(64),expectedMsat:21000});identities.set(c.pubkey,rows);state={ok:true};}
else if(c.action==='list')state={ok:true,reports:rows.map(r=>({orderId:r.orderId,status:'complete',createdAt:Date.now(),amountMsat:21000}))};
else if(c.action==='read')state={ok:true,recovery:rows.find(r=>r.orderId===args.args.orderId)};
else throw Error('unexpected identity action');
} else if (tool === "body_journal_paid_prepare") {
quotes++;
order = {
ok: true,
status: "prepared",
paymentProtocol: "cep8",
paymentConfirmation: "manual",
amountMsat: 21000,
orderId: "d".repeat(64),
};
state = order;
} else if (tool === "body_journal_paid_run") {
nativeCalls++;
if (settled) {
order = { ...order, status: "generating" };
state = order;
} else {
order = { ...order, status: "awaiting-payment" };
if (nativeCalls > 1 && !walletPaid) {
walletPaid = true;
payments++;
}
throw new Error(
"CVM_PAYMENT_PENDING: Use the service’s explicit confirmation action. Do not pay again.",
);
}
} else if (tool === "body_journal_paid_confirm") {
confirmations++;
await new Promise((r) => setTimeout(r, 150));
settled = walletPaid;
order = { ...order, paymentReceived: settled };
state = order;
} else if (tool === "body_journal_paid_status") {
statusReads++;
state =
settled && order.status === "generating"
? {
...order,
status: "complete",
result: { report: paidReport, model: "paid-fixture" },
}
: order;
} else throw new Error("Unexpected tool " + tool);
return { structuredContent: state, content: [] };
});
const fixture = `<script>window.napplet={fs:{pickSaveFile:async()=>({entries:[{path:'/files/recovery.pdf',kind:'file'}]}),write:(p,d)=>__saveBackup(p,d),pickFile:async()=>({entries:[{path:'/files/qr.png',kind:'file'}]}),read:(p,o)=>__readQr(p,o),remove:async()=>{}},storage:{getItem:k=>__get(k),setItem:(k,v)=>__set(k,v),removeItem:k=>__remove(k)},llm:{select:r=>__select(r),generate:r=>__generate(r)},cvm:{callTool:(r,t,a,o)=>__tool(r,t,a,o),close:async()=>{}}};</script>`;
await page.route("https://body-journal.test/", (route) =>
route.fulfill({ body: "<html></html>", contentType: "text/html" }),
);
await page.goto("https://body-journal.test/");
await page.setContent(
'<iframe sandbox="allow-scripts" style="position:fixed;inset:0;width:100%;height:100%;border:0"></iframe>',
);
const iframe = page.locator("iframe");
await iframe.evaluate(
(el, h) => (el.srcdoc = h),
html.replace("<head>", "<head>" + fixture),
);
let frame = await (await iframe.elementHandle()).contentFrame();
await seedSyntheticCase(frame);
await frame.locator("#connectionsButton").click();
assert.equal(await frame.locator("#apiKey").count(), 0);
await frame.locator("[data-ai=select]").click();
await frame.locator("#modalContent").getByText("Test connection · fixture", { exact: true }).waitFor();
assert.equal(selectionRequirements[0].json, undefined, "JSON transport is optional; validated report JSON remains mandatory");
await frame.locator("#closeModal").click();
await frame.locator("[data-page=review]").first().click();
await frame.locator(".analysis-card [data-ai=request]").click();
assert.equal(calls.length, 0);
await frame.locator("[data-ai=send-text]").click();
await frame.locator(".ai-report").waitFor();
assert.equal(calls.length, 1);
assert.ok(
!calls[0].messages
.flatMap((m) => m.content)
.some((c) => c.type === "image"),
);
jsonMode = true;
await frame.locator("#connectionsButton").click();
await frame.locator("[data-ai=select]").click();
await frame.locator("#modalContent").getByText("Test connection · fixture", { exact: true }).waitFor();
await frame.locator("#closeModal").click();
finish = "length";
await frame.locator(".analysis-card [data-ai=request]").click();
await frame.locator("[data-ai=send-text]").click();
await frame.getByText(/did not finish the report/).waitFor();
assert.equal(
await frame.locator(".ai-report").count(),
1,
"last completed report retained",
);
finish = "refusal";
await frame.locator(".analysis-card [data-ai=request]").click();
await frame.locator("[data-ai=send-text]").click();
await frame.getByText(/did not finish the report \(refusal\)/).waitFor();
assert.equal(await frame.locator(".ai-report").count(), 1);
finish = "stop";
unexpectedBlock = true;
await frame.locator(".analysis-card [data-ai=request]").click();
await frame.locator("[data-ai=send-text]").click();
await frame.getByText(/unexpected content block/).waitFor();
assert.equal(await frame.locator(".ai-report").count(), 1);
unexpectedBlock = false;
await frame.locator("#connectionsButton").click();
await frame.locator("[data-ai=paid]").click();
assert.equal(
await frame.locator("#paidKey").inputValue(),
"02f43ef61bd1be1a1887b6f638db169ce5461f72a18dcf11afece1588539f8e5",
);
assert.equal(await frame.locator("#paidKey").isVisible(), false);
await frame.getByText("AI Doc report service", { exact: true }).waitFor();
await frame.getByText("Change service (advanced)", { exact: true }).click();
await frame.locator("#paidKey").fill("a".repeat(64));
await frame.locator("[data-ai=save-service]").click();
await frame
.getByText("Your custom report service", { exact: true })
.waitFor();
await frame.locator('[data-ai=identity]').click();
await frame.locator('[data-identity=create]').click();
await frame.locator('#identitySecret').waitFor();
privateRecovery=await frame.locator('#identitySecret').inputValue();
assert.ok(privateRecovery.startsWith('nsec1'));
assert.equal(saved.has('body-journal:report-identity:v1'),false,'key is session-only until explicit remember');
await frame.locator('[data-identity=pdf]').click();
await frame.waitForTimeout(200);
assert.ok(exportedPdf.toString().includes(privateRecovery));
await writeFile(resolve(output,'synthetic-browser-recovery.pdf'),exportedPdf,{mode:0o600});
await page.screenshot({path:resolve(output,'identity-backup.png')});
await frame.locator('#rememberIdentity').check();
await frame.locator('[data-identity=use]').click();
await frame.getByText('No reports attached to this identity at this service yet.').waitFor();
assert.equal(saved.get('body-journal:report-identity:v1'),privateRecovery);
await frame.locator('#closeModal').click();
await frame.locator('#connectionsButton').click();
checkoutEnabled = false;
assert.equal(await frame.locator('#modal [data-ai=request]').isVisible(), true, "Paid choice needs a next step inside its dialog");
await frame.locator("#modal [data-ai=request]").click();
await frame.locator('#aiOptionsStatus').filter({ hasText: /not accepting paid reports/ }).waitFor();
assert.equal(quotes, 0, "closed checkout never sends the case");
checkoutEnabled = true;
let releaseInfo, notifyInfo;
const infoStarted = new Promise((resolve) => {
notifyInfo = resolve;
});
const infoWait = new Promise((resolve) => {
releaseInfo = resolve;
});
onInfo = () => {
onInfo = undefined;
notifyInfo();
return infoWait;
};
await frame.locator("#modal [data-ai=request]").click();
await infoStarted;
await frame.locator('#aiOptionsStatus').filter({ hasText: /Loading service price/ }).waitFor();
assert.equal(await frame.locator('#modal [data-ai=request]').isDisabled(), true);
assert.equal(quotes, 0, "price review never stages medical input");
releaseInfo();
await frame.locator('[data-ai=send-text]').waitFor({ state: 'visible' });
await page.screenshot({ path: resolve(output, "paid-price-review.png") });
assert.match(await frame.locator('#modalContent').textContent(), /21 sats/);
assert.equal(quotes, 0);
await frame.locator('#closeModal').click();
// Closed options remain in the DOM; the review-page action must still work.
await frame.locator('#connectionsButton').click();
await frame.locator('#closeModal').click();
let releaseBackgroundInfo, notifyBackgroundInfo;
const backgroundStarted = new Promise(resolve => { notifyBackgroundInfo = resolve; });
const backgroundWait = new Promise(resolve => { releaseBackgroundInfo = resolve; });
onInfo = () => { onInfo = undefined; notifyBackgroundInfo(); return backgroundWait; };
await frame.locator('.analysis-card [data-ai=request]').click();
await backgroundStarted;
await frame
.getByRole("button", { name: "Step 2: Context", exact: true })
.click();
await frame
.locator("#conditions")
.fill("Synthetic update while connection permission was pending.");
await frame
.getByRole("button", { name: "Step 3: Review", exact: true })
.click();
releaseBackgroundInfo();
await frame.locator("[data-ai=send-text]").waitFor({ state: "visible" });
assert.match(
await frame.locator("#modalContent pre").textContent(),
/Synthetic update while connection permission was pending/,
);
await frame.locator("[data-ai=send-text]").click();
await frame.locator("[data-ai=pay]").waitFor();
assert.equal(
await frame.locator("#paidInvoice").count(),
0,
"native invoice belongs to shell checkout",
);
assert.equal(settled, false);
assert.equal(await frame.locator("[data-ai=confirm-payment]").count(), 1);
assert.equal(
await frame
.locator("[data-paid-checkout]")
.evaluate((el) => el.scrollWidth <= el.clientWidth),
true,
"checkout contents must fit the dialog",
);
assert.ok(saved.get("body-journal:paid-order:v1").includes("receipt"));
await page.screenshot({ path: resolve(output, "invoice-fallback.png") });
const receipt = JSON.parse(saved.get("body-journal:paid-order:v1"));
await iframe.evaluate(
(el, h) => (el.srcdoc = h),
html.replace("<head>", "<head>" + fixture),
);
frame = await (await iframe.elementHandle()).contentFrame();
await frame.locator('#app[data-ready="true"]').waitFor();
await frame.locator("[data-page=review]").first().click();
await frame.locator("[data-ai=recover]").click();
await frame.locator("[data-ai=pay]").waitFor();
assert.equal(
await frame.locator("#paidInvoice").count(),
0,
"native invoice belongs to shell checkout",
);
assert.equal(quotes, 1, "reload recovers the original invoice");
assert.equal(payments, 0, "reload never dispatches payment");
assert.equal(
confirmations,
0,
"reload/status never wake the receiving wallet",
);
await frame.locator("[data-ai=confirm-payment]").click();
await frame.getByText(/Payment is not confirmed yet/).waitFor();
assert.equal(confirmations, 1, "one explicit check, no repeated lookup");
const callsBefore = nativeCalls;
await new Promise((r) => setTimeout(r, 200));
assert.equal(
nativeCalls,
callsBefore,
"status recovery never re-enters native checkout",
);
assert.equal(confirmations, 1, "no automatic receiver lookup");
assert.equal(
JSON.parse(saved.get("body-journal:paid-order:v1")).receipt,
receipt.receipt,
);
await frame.locator("[data-ai=pay]").click();
await frame.locator("[data-ai=confirm-payment]").waitFor();
await frame.getByText(/CVM_PAYMENT_PENDING/).waitFor();
assert.equal(
confirmations,
1,
"shell payment does not trigger a hidden receiver lookup",
);
await frame.locator("[data-ai=confirm-payment]").click();
await frame
.locator("#paidError")
.filter({ hasText: /omitted or invented an observation/ })
.waitFor();
assert.equal(
await frame.locator(".ai-report").count(),
1,
"invalid paid report retains prior report",
);
await frame.locator("#closeModal").click();
paidReport = report;
await frame
.getByRole("button", { name: "Open saved paid report", exact: true })
.click();
await frame.getByText(/paid-fixture/).waitFor();
assert.equal(payments, 1, "recovering a completed order never pays again");
assert.equal(settled, true);
assert.equal(
confirmations,
2,
"completed report recovery does not recheck payment",
);
assert.equal(await frame.locator("[data-paid-checkout]").isVisible(), false);
await frame.locator("#connectionsButton").click();
await frame.locator('[data-ai=identity]').click();
await frame.locator('[data-identity=history]').click();
await frame.getByText(/1 retained report/).waitFor();
await frame.locator('[data-identity=home]').click();
await frame.locator('[data-identity=confirm-forget]').click();
await frame.locator('[data-identity=forget]').click();
assert.equal(saved.has('body-journal:report-identity:v1'),false);
qrImage=await QRCode.toBuffer(privateRecovery,{width:400,margin:4});
await frame.locator('[data-identity=scan]').click();
await frame.locator('#identitySecret').waitFor();
assert.equal(await frame.locator('#identitySecret').inputValue(),privateRecovery,'QR restore recovers exact reusable key');
await frame.locator('[data-identity=use]').click();
await frame.getByText(/1 retained report/).waitFor();
assert.equal(saved.has('body-journal:report-identity:v1'),false,'restored session-only key remains unpersisted');
await frame.locator('[data-identity^="read:"]').click();
await frame.getByText(/paid-fixture/).waitFor();
assert.equal(payments,1);assert.equal(confirmations,2);
await frame.locator('#connectionsButton').click();
for (const [w, h] of [
[900, 600],
[320, 560],
[200, 160],
[1600, 1000],
]) {
await page.setViewportSize({ width: w, height: h });
await frame.waitForFunction(
({ w, h }) => innerWidth === w && innerHeight === h,
{ w, h },
);
assert.equal(
await frame.evaluate(
() => document.documentElement.scrollWidth <= innerWidth,
),
true,
);
await page.screenshot({ path: resolve(output, `frame-${w}x${h}.png`) });
}
assert.deepEqual(errors, []);
await writeFile(
resolve(output, "results.json"),
JSON.stringify(
{
checks: [
"explicit BYOK review with a legacy text-only connection and with JSON mode",
"paid options CTA, loading, inline errors and price review without sharing input",
"no provider key fields; local reusable report identity only",
"identity create, printable PDF, remember, forget and QR restore with signed history lookup",
"text-only choice",
"truncated result rejected",
"default service and advanced custom service",
"closed checkout sends no case",
"native payment is shell-owned; no VALUE binding",
"manual confirmation only on explicit click; remains available after shell payment",
"status polling and reload send zero confirmation calls",
"reload retains invoice without duplicate payment",
"receipt persisted before invoice",
"native CVM payment approval",
"invalid paid report rejected without losing prior report",
"QR removed and report delivered",
"four frame widths",
],
errors,
},
null,
2,
),
);
console.log(
"AI UI: BYOK, paid CVM, QR settlement and responsive checks passed.",
);
} finally {
await browser.close();
}
