- Settings: question mode (needed / valuable only / never), value threshold, max questions per item, value from which to research deeply - ask_humans enforces the limits server-side and tells the AI to finish - Skip - don't ask again (web, Questions page, Android To-do), Dismiss all, Allow questions again per item - App 1.3.0
189 lines
16 KiB
JavaScript
189 lines
16 KiB
JavaScript
// End-to-end smoke test: node test/e2e.js (starts its own server on a temp data dir)
|
||
import { spawn } from 'node:child_process';
|
||
import fs from 'node:fs';
|
||
import os from 'node:os';
|
||
import path from 'node:path';
|
||
import sharp from 'sharp';
|
||
import assert from 'node:assert/strict';
|
||
|
||
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ipx-'));
|
||
const port = 18000 + Math.floor(Math.random() * 1000);
|
||
const base = `http://localhost:${port}`;
|
||
const srv = spawn('node', ['src/index.js'], { env: { ...process.env, DATA_DIR: dataDir, PORT: port, ADMIN_PASSWORD: 'adminpw1' }, stdio: ['ignore', 'pipe', 'inherit'] });
|
||
await new Promise((r) => srv.stdout.on('data', (d) => d.toString().includes('listening') && r()));
|
||
|
||
let ok = 0;
|
||
const step = (name) => { ok++; console.log('✓', name); };
|
||
const cookieOf = (r) => r.headers.get('set-cookie').split(';')[0];
|
||
try {
|
||
let r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'wrong' }) });
|
||
assert.equal(r.status, 401); step('wrong password rejected');
|
||
r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'admin', password: 'adminpw1' }) });
|
||
assert.equal(r.status, 200); const admin = cookieOf(r); step('admin login (username + password)');
|
||
const A = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: admin, 'content-type': 'application/json', ...(o.headers || {}) } });
|
||
|
||
const info = await (await fetch(`${base}/api/info`)).json();
|
||
if (info.app.available) {
|
||
assert.match(info.app.url, /\/download\/IndexiPro-[\d.]+\.apk$/);
|
||
const apk = await fetch(info.app.url.replace(/^https?:\/\/[^/]+/, base));
|
||
assert.equal(apk.status, 200);
|
||
const bytes = Buffer.from(await apk.arrayBuffer());
|
||
if (info.app.sha256) assert.equal((await import('node:crypto')).createHash('sha256').update(bytes).digest('hex'), info.app.sha256);
|
||
assert.equal((await fetch(`${base}/download/IndexiPro-0.0.1.apk`)).status, 404);
|
||
step('APK offered under its versioned name, checksum matches');
|
||
}
|
||
const join = await (await A('/api/join')).json();
|
||
assert.match(join.url, /\/join\/[A-Z0-9]{8}$/); assert.match(join.svg, /<svg/); step('join QR');
|
||
|
||
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, name: 'Sam', kind: 'android' }) });
|
||
assert.equal(r.status, 400); step('joining requires a password');
|
||
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, name: 'Sam', password: 'secret1', kind: 'android' }) });
|
||
const pair = await r.json(); assert.ok(pair.token); assert.equal(pair.username, 'sam'); assert.ok(pair.created); step('phone join creates editor account "sam"');
|
||
r = await fetch(`${base}/api/login`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ username: 'sam', password: 'secret1' }) });
|
||
const samWeb = cookieOf(r); assert.equal(r.status, 200); step('helper can log in on the web');
|
||
const S = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: samWeb, 'content-type': 'application/json', ...(o.headers || {}) } });
|
||
assert.equal((await S('/api/users')).status, 403); assert.equal((await S('/api/shares')).status, 403); step('editor cannot manage team or share links');
|
||
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: join.code, username: 'sam', password: 'secret1', kind: 'android' }) });
|
||
assert.ok((await r.json()).token); step('existing account can sign in a second phone with the join code');
|
||
const personal = await (await S('/api/me/pair')).json();
|
||
const pcode = personal.url.split('/').pop();
|
||
assert.equal((await (await fetch(`${base}/api/invite/${pcode}`)).json()).person, 'Sam');
|
||
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: pcode, kind: 'android' }) });
|
||
assert.ok((await r.json()).token);
|
||
r = await fetch(`${base}/api/pair`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ code: pcode, kind: 'android' }) });
|
||
assert.equal(r.status, 404); step('personal "pair my phone" code works once');
|
||
const P = (p, o = {}) => fetch(base + p, { ...o, headers: { authorization: `Bearer ${pair.token}`, ...(o.headers || {}) } });
|
||
|
||
const img = await sharp({ create: { width: 1600, height: 1200, channels: 3, background: '#a0522d' } }).jpeg().toBuffer();
|
||
const fd = new FormData();
|
||
fd.append('photos', new Blob([img], { type: 'image/jpeg' }), 'a.jpg');
|
||
fd.append('photos', new Blob([img], { type: 'image/jpeg' }), 'b.jpg');
|
||
fd.append('note', 'old book from the attic, looks like a first edition');
|
||
fd.append('location', 'Attic box 3'); fd.append('client_id', 'abc-1');
|
||
r = await P('/api/items', { method: 'POST', body: fd });
|
||
const item = await r.json(); assert.equal(r.status, 201); assert.equal(item.photos.length, 2); step('upload item with photos');
|
||
r = await P('/api/items', { method: 'POST', body: fd }); assert.equal((await r.json()).id, item.id); step('upload retry is idempotent');
|
||
|
||
r = await P(`/photos/${item.photos[0].id}/thumb`); assert.equal(r.status, 200); step('photo thumb');
|
||
|
||
const keyRes = await (await S('/api/aikeys', { method: 'POST', body: JSON.stringify({ label: "Sam's Claude" }) })).json();
|
||
const mcpUrl = keyRes.url;
|
||
assert.ok(mcpUrl.includes(keyRes.key)); step('editor creates a personal AI connection');
|
||
assert.equal((await (await S('/api/aikeys')).json()).connected, false);
|
||
let rpcId = 0;
|
||
const mcp = async (method, params) => {
|
||
const res = await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: ++rpcId, method, params }) });
|
||
const j = await res.json(); if (j.error) throw new Error(JSON.stringify(j.error)); return j.result;
|
||
};
|
||
for (const probe of ['/.well-known/oauth-protected-resource', '/.well-known/oauth-authorization-server', '/.well-known/openid-configuration']) {
|
||
for (const url of [`${base}${probe}`, `${mcpUrl}${probe}`]) {
|
||
const pr = await fetch(url);
|
||
assert.equal(pr.status, 404, url); assert.match(pr.headers.get('content-type'), /json/, url);
|
||
}
|
||
}
|
||
step('OAuth discovery probes get a clean JSON 404 (no HTML)');
|
||
const init = await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'test', version: '1' } });
|
||
assert.match(init.instructions, /cataloguer/); step('MCP initialize');
|
||
const res = await mcp('resources/list', {});
|
||
assert.ok(res.resources.some((r) => r.uri === 'indexipro://instructions'));
|
||
assert.equal((await mcp('resources/templates/list', {})).resourceTemplates.length, 0); step('MCP resources/list and templates/list answer normally');
|
||
const tools = (await mcp('tools/list', {})).tools.map((t) => t.name);
|
||
for (const t of ['next_items_to_identify', 'update_item', 'field_conventions', 'add_comparables', 'ask_humans', 'save_listing', 'research_links']) assert.ok(tools.includes(t), t);
|
||
step(`MCP tools/list (${tools.length} tools)`);
|
||
const call = (name, args) => mcp('tools/call', { name, arguments: args });
|
||
const next = await call('next_items_to_identify', { limit: 2 });
|
||
assert.ok(next.content.some((c) => c.type === 'image')); step('MCP next items includes images');
|
||
let u = await call('update_item', { id: item.id, title: 'J.R.R. Tolkien – The Hobbit (1937)', category: 'Books', tier: 'notable', value_low: 2000, value_high: 6000, attributes: { author: 'J.R.R. Tolkien', isbn: 'n/a', publisher: 'George Allen & Unwin' } });
|
||
assert.ok(!u.isError, JSON.stringify(u));
|
||
u = await call('update_item', { id: item.id, attributes: { isbn: null, edition: 'First edition, first impression' } });
|
||
const full = await (await A(`/api/items/${item.id}`)).json();
|
||
assert.equal(full.status, 'identified'); assert.equal(full.attributes.author, 'J.R.R. Tolkien'); assert.equal(full.attributes.isbn, undefined); assert.ok(full.attributes.edition);
|
||
step('MCP update_item with custom attributes (merge + delete)');
|
||
const conv = await call('field_conventions', {});
|
||
assert.match(conv.content[0].text, /publisher/); step('MCP field_conventions');
|
||
await call('add_comparables', { item_id: item.id, comparables: [{ source: 'Test', kind: 'sold', title: 'Hobbit 1937', price: 4000, currency: 'EUR' }] });
|
||
await call('ask_humans', { item_id: item.id, question: 'Please photograph the title page' });
|
||
const links = JSON.parse((await call('research_links', { query: 'Delft plate' })).content[0].text);
|
||
assert.ok(links.ebay_sold_by_country.de.includes('ebay.de') && links.marketplaces.marktplaats_nl && links.identify.google_images); step('research_links spans many sites and countries');
|
||
const rep = await call('submit_run_report', { report: 'Identified #1 as The Hobbit. Could not verify the printing.', processed: [item.id], uncertain: [item.id] });
|
||
assert.ok(!rep.isError);
|
||
const reports = await (await A('/api/reports')).json();
|
||
assert.equal(reports[0].uncertain[0], item.id); step('AI run report saved and visible to the team');
|
||
const todo = await (await P('/api/todo')).json(); assert.equal(todo.total, 1); step('AI question reaches the phone to-do list');
|
||
const ans = new FormData(); ans.append('photos', new Blob([img], { type: 'image/jpeg' }), 'c.jpg'); ans.append('note', 'here it is');
|
||
r = await P(`/api/items/${item.id}/photos`, { method: 'POST', body: ans });
|
||
const answered = await r.json();
|
||
assert.equal(answered.status, 'new'); assert.match(answered.human_notes, /Q: Please photograph the title page\nA \(Sam\): here it is \(added 1 photo\)/);
|
||
step('answering puts item back in the AI queue, question + answer kept in notes');
|
||
const second = await call('ask_humans', { item_id: item.id, question: 'Photograph the spine' });
|
||
assert.ok(second.isError && /Not asked: 1 question/.test(second.content[0].text)); step('policy: max 1 question per item by default');
|
||
const setS = (body) => A('/api/settings', { method: 'PUT', body: JSON.stringify(body) });
|
||
await setS({ questions_max_per_item: '2' });
|
||
assert.ok(!(await call('ask_humans', { item_id: item.id, question: 'Photograph the spine' })).isError);
|
||
const onlyPhoto = new FormData(); onlyPhoto.append('photos', new Blob([img], { type: 'image/jpeg' }), 'd.jpg');
|
||
const op = await (await P(`/api/items/${item.id}/photos`, { method: 'POST', body: onlyPhoto })).json();
|
||
assert.equal(op.status, 'new'); assert.match(op.human_notes, /Q: Photograph the spine\nA \(Sam\): added 1 photo/); step('photo-only answer also records the question');
|
||
// a fresh, cheap item to exercise the other rules
|
||
const fd2 = new FormData(); fd2.append('photos', new Blob([img], { type: 'image/jpeg' }), 'x.jpg'); fd2.append('note', 'some cables');
|
||
const cheap = await (await P('/api/items', { method: 'POST', body: fd2 })).json();
|
||
await call('update_item', { id: cheap.id, title: 'Box of USB cables', value_low: 2, value_high: 5 });
|
||
await setS({ questions_mode: 'valuable', questions_min_value: '50' });
|
||
let q = await call('ask_humans', { item_id: cheap.id, question: 'How many?' });
|
||
assert.ok(q.isError && /only allowed for items marked "notable"/.test(q.content[0].text)); step('policy: low-value items get no questions');
|
||
await call('update_item', { id: cheap.id, value_high: 80 });
|
||
assert.ok(!(await call('ask_humans', { item_id: cheap.id, question: 'How many?' })).isError); step('policy: valuable items may get a question');
|
||
const sk = await (await P(`/api/items/${cheap.id}/skip-question`, { method: 'POST' })).json();
|
||
assert.equal(sk.status, 'identified'); assert.equal(sk.question, null);
|
||
await setS({ questions_mode: 'needed', questions_max_per_item: '5' });
|
||
q = await call('ask_humans', { item_id: cheap.id, question: 'Again?' });
|
||
assert.ok(q.isError && /switched off questions for this item/.test(q.content[0].text)); step('skip: "don\'t ask again" sticks for that item');
|
||
await setS({ questions_mode: 'off' });
|
||
q = await call('ask_humans', { item_id: item.id, question: 'x' });
|
||
assert.ok(q.isError && /switched off in Settings/.test(q.content[0].text)); step('policy: questions can be switched off entirely');
|
||
await setS({ questions_mode: 'needed' });
|
||
await call('ask_humans', { item_id: item.id, question: 'One more look please' });
|
||
const dis = await (await P('/api/questions/dismiss-all', { method: 'POST' })).json();
|
||
assert.ok(dis.dismissed >= 1); assert.equal((await (await P('/api/todo')).json()).total, 0); step('dismiss all open questions');
|
||
const instr = (await mcp('initialize', { protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 't', version: '1' } })).instructions;
|
||
assert.match(instr, /QUESTIONS TO THE TEAM/); step('AI instructions include the question policy');
|
||
const ak = await (await S('/api/aikeys')).json();
|
||
assert.ok(ak.connected && !ak.session_prompt.includes(keyRes.key)); step('connection shows as connected; session message holds no secret');
|
||
const act = await (await A(`/api/items/${item.id}`)).json();
|
||
assert.ok(act.activity.some((a) => a.actor === "AI (Sam's Claude)")); step('AI edits are attributed to the key');
|
||
const bearer = await fetch(`${base}/mcp`, { method: 'POST', headers: { authorization: `Bearer ${keyRes.key}`, 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 99, method: 'tools/list' }) });
|
||
assert.equal(bearer.status, 200); step('MCP also accepts the key as a Bearer header');
|
||
const s = await (await A('/api/items?q=tolkien')).json(); assert.equal(s.total, 1);
|
||
const s2 = await (await A('/api/items?q=unwin')).json(); assert.equal(s2.total, 1); step('full-text search incl. custom fields');
|
||
|
||
// share links
|
||
const sh = await (await A('/api/shares', { method: 'POST', body: JSON.stringify({ label: 'Aunt Mia', show_values: false }) })).json();
|
||
r = await fetch(sh.url, { redirect: 'manual' }); assert.equal(r.status, 302); const viewer = cookieOf(r);
|
||
const V = (p, o = {}) => fetch(base + p, { ...o, headers: { cookie: viewer, 'content-type': 'application/json', ...(o.headers || {}) } });
|
||
const vi = await (await V(`/api/items/${item.id}`)).json();
|
||
assert.equal(vi.title, full.title); assert.equal(vi.value_high, null); assert.equal(vi.comparables.length, 0); step('share link: read-only view, values hidden');
|
||
r = await V(`/api/items/${item.id}`, { method: 'PATCH', body: JSON.stringify({ title: 'x' }) }); assert.equal(r.status, 403); step('share link cannot edit');
|
||
r = await V('/api/devices'); assert.equal(r.status, 403); step('share link cannot see admin pages');
|
||
r = await V(`/photos/${item.photos[0].id}/medium`); assert.equal(r.status, 200); step('share link sees photos');
|
||
const st = await (await V('/api/stats')).json(); assert.equal(st.totals.value_high, null); step('share-link stats redacted');
|
||
const shares = await (await A('/api/shares')).json();
|
||
await A(`/api/shares/${shares[0].id}`, { method: 'DELETE' });
|
||
r = await V(`/api/items/${item.id}`); assert.equal(r.status, 401); step('switched-off link stops working');
|
||
|
||
await S(`/api/aikeys/${keyRes.id}`, { method: 'DELETE' });
|
||
r = await fetch(mcpUrl, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/list' }) });
|
||
assert.equal(r.status, 401); step('revoked AI key stops working');
|
||
const users = (await (await A('/api/users')).json()).users;
|
||
const sam = users.find((u) => u.username === 'sam');
|
||
await A(`/api/users/${sam.id}`, { method: 'PATCH', body: JSON.stringify({ disabled: true }) });
|
||
assert.equal((await P('/api/me')).status, 401); assert.equal((await S('/api/me')).status, 401); step('disabling an account signs out its phones and browsers');
|
||
const adminRow = users.find((u) => u.username === 'admin');
|
||
r = await A(`/api/users/${adminRow.id}`, { method: 'PATCH', body: JSON.stringify({ role: 'editor' }) });
|
||
assert.equal(r.status, 400); step('cannot remove the last admin');
|
||
r = await A('/api/export.csv'); const csv = await r.text(); assert.match(csv, /publisher/); step('CSV export includes custom fields');
|
||
console.log(`\nAll ${ok} checks passed.`);
|
||
} catch (e) {
|
||
console.error('✗ FAILED:', e); process.exitCode = 1;
|
||
} finally {
|
||
srv.kill(); fs.rmSync(dataDir, { recursive: true, force: true });
|
||
}
|