diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 253c63d..635391d 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -16,7 +16,8 @@ concurrency: jobs: local-payments: runs-on: ubuntu-24.04 - timeout-minutes: 30 + # The complete local suite takes about 29 minutes; leave room for slower runners. + timeout-minutes: 40 steps: - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 with: diff --git a/README.md b/README.md index 859c868..8edb88e 100644 --- a/README.md +++ b/README.md @@ -53,7 +53,7 @@ The demo executes native NEAR transfers on a disposable local chain. It uses fix [Local payment desk, contract and operator guide](docs/local-guide.md) -The local desk opens on Demo café. Choose **Agent payments**, or visit http://127.0.0.1:4317/#agent-payments, to import a supplier's signed bill, request payment and read the receipt (needs a local agent vault with a policy and a pinned supplier key). The page calls the same functions as `agent:desk import`, `run` and `resume` and adds no payment logic. The manual payment desk and dry-run 1Click lab are under **Tools**. See [Agent payments in the desk](docs/local-guide.md#agent-payments-in-the-desk). +The local desk opens on **Agent payments** at http://127.0.0.1:4317/#agent-payments on every network. Choose **Demo café** from the sidebar to try the demo. In Agent payments, import a supplier's signed bill, request payment and read the receipt (needs a local agent vault with a policy and a pinned supplier key). The page calls the same functions as `agent:desk import`, `run` and `resume` and adds no payment logic. The manual payment desk and dry-run 1Click lab are under **Tools**. See [Agent payments in the desk](docs/local-guide.md#agent-payments-in-the-desk). Ask Dave also runs in the desk: open http://127.0.0.1:4317/#ask-dave (needs a local agent vault: npm run agent:desk -- init). Its questions read `work/agent-vault` (or `COUNTERSIGN_AGENT_DIR`), while the manual payment desk uses `work/local-vault` (or `COUNTERSIGN_SANDBOX_DIR`). The page and each answer identify the source account. Standalone account checks show their selected network separately; questions always read the local agent vault. diff --git a/agent/demo-cafe.ts b/agent/demo-cafe.ts index 77a6710..f623e44 100644 --- a/agent/demo-cafe.ts +++ b/agent/demo-cafe.ts @@ -7,11 +7,59 @@ import {SandboxDesk,parseNear} from '../app/sandbox.ts'; import {saveJson} from '../app/local-chain.ts'; import {signInvoice,publicKeyBase64} from '../merchant/invoice.ts'; import {setDeskMerchantKey,setDeskPolicy,addDeskWeeklyService} from './desk-setup.ts'; +import {renewLocalPolicy} from './policy-renewal.ts'; import {createDeskInbox,importDeskInvoice} from './desk-core.ts'; import {readAgentState,runAgentBill,resumeAgentBill,DeskWebError} from './desk-web.ts'; type Supplier={id:string;name:string;payee:string;baseline:string;privateKey:string;version:string;domain:string}; -type Cafe={suppliers:Supplier[];scam:{payee:string;baseline:string};rejected:{id:string;reason:string}[];ready:boolean}; +// Display copy of each delivered invoice, for the demo mailbox only. It is never read +// by import or payment code; the vault still decides from the signed invoice itself. +type MailInvoice={id:string;merchant:string;supplier:string;payee:string;amount:string;expires_at:string;week:number|null}; +type BankEntry={at:string;kind:'faucet'|'deposit';amount:string}; +type Cafe={suppliers:Supplier[];scam:{payee:string;baseline:string};rejected:({id:string;reason:string}&Partial)[];ready:boolean; + mail?:{issued_at:string;invoices:MailInvoice[]};bank?:BankEntry[]; + // The latest payment run (processing order) and the vault when the day's first run began. + run?:{order:string[];vault_before:string};day_vault_start?:string}; +const YOCTO=10n**24n; +export const WALLET_FAUCET=5n*YOCTO,GAS_RESERVE=YOCTO/2n; +export const RESERVE_MESSAGE='Keep 0.5 NEAR in your wallet for fees.'; +// Demo deposit amounts: positive NEAR with up to 24 decimals, exact in yoctoNEAR. +export function parseDemoAmount(value:unknown){ + if(typeof value!=='string'||!/^\d{1,9}(\.\d{1,24})?$/.test(value))throw new DeskWebError('Enter an amount in NEAR, like 2 or 0.25 (up to 24 decimals).'); + const [whole,fraction='']=value.split('.');const amount=BigInt(whole)*YOCTO+BigInt(fraction.padEnd(24,'0')); + if(amount<=0n)throw new DeskWebError('Enter an amount greater than 0.'); + return amount; +} +// Your rules. The shared CLI operations (setDeskPolicy, renewLocalPolicy) accept +// 1–1440 minutes and at most 5 NEAR per amount, inside the contract's 30-day limit. +export const MAX_RULE_HOURS=24,MAX_RULE_YOCTO=5n*YOCTO,RENEW_MINUTES=120; +export type DemoRules={per:bigint;daily:bigint;hours:number}; +function ruleAmount(label:string,value:unknown){ + if(typeof value!=='string'||!/^\d{1,9}(\.\d{1,24})?$/.test(value))throw new DeskWebError(`${label}: enter an amount in NEAR, like 0.5 (up to 24 decimals).`); + const [whole,fraction='']=value.split('.');const amount=BigInt(whole)*YOCTO+BigInt(fraction.padEnd(24,'0')); + if(amount<=0n)throw new DeskWebError(`${label}: enter an amount greater than 0.`); + if(amount>MAX_RULE_YOCTO)throw new DeskWebError(`${label}: the local sandbox allows at most 5 NEAR.`); + return amount; +} +export function parseDemoRules(input:{per_bill?:unknown;daily_budget?:unknown;hours?:unknown}):DemoRules{ + const per=ruleAmount('Most per bill',input.per_bill),daily=ruleAmount('Daily budget',input.daily_budget); + if(per>daily)throw new DeskWebError("Most per bill can't be more than the daily budget."); + if(typeof input.hours!=='string'||!/^\d{1,4}$/.test(input.hours)||Number(input.hours)<1||Number(input.hours)>MAX_RULE_HOURS) + throw new DeskWebError(`Rules can last from 1 to ${MAX_RULE_HOURS} hours.`); + return {per,daily,hours:Number(input.hours)}; +} +const walletOf=async(desk:SandboxDesk)=>BigInt((await desk.owner.balance()).available.toString()); +// NEAR refunds unused gas to the signer a few blocks after a call. Wait until the +// owner's balance stops moving so the wallet shown (and any delta) is settled. +async function settleWallet(desk:SandboxDesk){ + let last=await walletOf(desk),steady=0; + for(let i=0;i<20&&steady<2;i++){ + await new Promise(r=>setTimeout(r,700)); + const next=await walletOf(desk);steady=next===last?steady+1:0;last=next; + } + return last; +} +const WEEK_MS=7*24*60*60*1000; export function requireLocalDemo(network=process.env.COUNTERSIGN_NETWORK){ if(network!==undefined&&network!=='local')throw new DeskWebError('Demo café is available only on the local sandbox.'); } @@ -36,11 +84,13 @@ export async function setupCafe(directory:string){ const key=await setDeskMerchantKey(desk,id,publicKeyBase64(pair.publicKey)); cafe.suppliers.push({id,name,payee:account.accountId,baseline:(await account.balance()).total.toString(),privateKey:pair.privateKey.export({type:'pkcs8',format:'pem'}).toString(),version:key.version,domain:key.domain});save(); } - const scam=await desk.worker.rootAccount.createSubAccount('scam'); + // A lookalike of Bean Co's payout (5 for s): the tampered invoice pays here. + const scam=await desk.worker.rootAccount.createSubAccount('bean5'); cafe.scam={payee:scam.accountId,baseline:(await scam.balance()).total.toString()};save(); await setDeskPolicy(desk,'0.5','1.2',120,undefined,cafe.suppliers.map(s=>({id:s.id,payee:s.payee}))); const now=String((await desk.vault.view('policy_snapshot',{})).now); await addDeskWeeklyService(desk,'weekly-milk','Milk-Co','0.5',now); + await settleWallet(desk); cafe.ready=true;save(); }); return readCafe(directory); @@ -67,7 +117,9 @@ export async function readCafe(directory:string){ } const scamReceived=(BigInt((await desk.worker.account(cafe.scam.payee).balance()).total.toString())-BigInt(cafe.scam.baseline)).toString(); return {ready:true,network:'LOCAL_SANDBOX',vault:state.vault,available:await desk.vault.view('available_balance',{}),policy:state.policy, - suppliers,scam:{payee:cafe.scam.payee,received:scamReceived},rejected:cafe.rejected,bills:state.bills,read_at:new Date().toISOString()}; + suppliers,scam:{payee:cafe.scam.payee,received:scamReceived},rejected:cafe.rejected,mail:cafe.mail??null,bank:cafe.bank??[], + run:cafe.run??null,day_vault_start:cafe.day_vault_start??null, + wallet_yocto:(await walletOf(desk)).toString(),bills:state.bills,read_at:new Date().toISOString()}; }); } export async function receiveCafe(directory:string){ @@ -87,11 +139,18 @@ export async function receiveCafe(directory:string){ make(beans,'BEANS-02','beans-delivery','0.4'),make(milk,'MILK-02','milk-delivery-2','0.4',true),make(pastry,'PASTRY-02','pastry-delivery-2','0.5')]; const tampered=make(beans,'BEANS-03','beans-delivery-3','0.4');tampered.invoice.payee=cafe.scam.payee;bills.push(tampered); for(let i=bills.length-1;i>0;i--){const j=randomInt(i+1);[bills[i],bills[j]]=[bills[j],bills[i]];} + const weekly:any=await desk.vault.view('get_weekly_service',{agreement_id:'weekly-milk'}); + const week=(bill:typeof bills[number])=>bill.service&&weekly?Math.floor((Number(bill.service.period_start_ms)-Number(weekly.anchor_ms))/WEEK_MS)+1:null; + // As delivered: the payee is what is written on the invoice, tampered or not. + const display=(bill:typeof bills[number]):MailInvoice=>({id:bill.invoice.id,merchant:bill.merchant_id,supplier:cafe.suppliers.find(s=>s.id===bill.merchant_id)!.name, + payee:bill.invoice.payee,amount:bill.invoice.amount,expires_at:bill.expires_at,week:week(bill)}); + // Keep earlier deliveries visible when another batch arrives the same day. + cafe.mail={issued_at:cafe.mail?.issued_at??new Date().toISOString(),invoices:[...(cafe.mail?.invoices??[]),...bills.map(display)]}; for(const bill of bills){ try{await importDeskInvoice(desk,inbox,bill);} catch(error){ if(!(error instanceof Error)||error.message!=='Invalid merchant signature')throw error; - cafe.rejected.push({id:bill.invoice.id,reason:error.message}); + cafe.rejected.push({...display(bill),reason:error.message}); } } saveJson(join(directory,'cafe.json'),cafe); @@ -99,27 +158,123 @@ export async function receiveCafe(directory:string){ }); return readCafe(directory); } -export type CafeProgress={running:boolean;completed:number;total:number;current:string|null}; +// results: each bill's real outcome, appended the moment its run finishes, in processing order. +export type CafeResult={id:string;outcome:string;error:string|null;explanation:{meaning:string}|null}; +export type CafeProgress={running:boolean;completed:number;total:number;current:string|null;order?:string[];results?:CafeResult[];vault_before?:string|null}; +async function beginCafeRun(directory:string,order:string[]){ + return withDesk(directory,async desk=>{ + const before=String(await desk.vault.view('available_balance',{})); + if(order.length){ + const cafe=config(directory);cafe.run={order,vault_before:before};cafe.day_vault_start??=before; + // Save before submission so a restart cannot lose the original balance. + saveJson(join(directory,'cafe.json'),cafe); + } + return before; + }); +} +export async function payCafeBill(directory:string,id:string){ + requireLocalDemo();const cafe=config(directory); + if(!cafe.ready||!cafe.mail?.invoices.some(invoice=>invoice.id===id))throw new DeskWebError('Unknown café invoice.'); + const before=await readAgentState(directory); + if(!before.bills.some(bill=>bill.id===id&&['queued','proposed'].includes(bill.outcome)))throw new DeskWebError('This invoice is no longer queued.'); + await beginCafeRun(directory,[id]); + const {record}=await runAgentBill(directory,id,false); + return {record,state:await readCafe(directory)}; +} export async function payCafe(directory:string,live:boolean,progress:CafeProgress){ requireLocalDemo();if(!config(directory).ready)throw new DeskWebError('Open the café first.'); const state=await readAgentState(directory); + const mailbox=new Set(config(directory).mail?.invoices.map(invoice=>invoice.id)??[]); // Invoice references establish a stable queue independent of shuffled delivery. // There is no outcome classification here: every queued bill goes through run. - const queue=state.bills.filter(b=>['queued','proposed'].includes(b.outcome)).sort((a,b)=>a.id.localeCompare(b.id)); + const queue=state.bills.filter(b=>mailbox.has(b.id)&&['queued','proposed'].includes(b.outcome)).sort((a,b)=>a.id.localeCompare(b.id)); // Round-robin deliveries: first bill from each supplier, then subsequent bills. queue.sort((a,b)=>{const order=(id:string)=>Number(id.match(/-(\d\d)-/)?.[1]??0);return order(a.id)-order(b.id);}); - Object.assign(progress,{running:true,completed:0,total:queue.length,current:null}); + const vaultBefore=await beginCafeRun(directory,queue.map(b=>b.id)); + Object.assign(progress,{running:true,completed:0,total:queue.length,current:null,order:queue.map(b=>b.id),results:[],vault_before:vaultBefore}); try{ - for(const bill of queue){progress.current=bill.id;await runAgentBill(directory,bill.id,live);progress.completed++;} - // Reconcile only genuinely pending saved transfers; no new proposal is made. + for(const bill of queue){ + progress.current=bill.id; + const {record}=await runAgentBill(directory,bill.id,live); + progress.results!.push({id:record.id,outcome:record.outcome,error:record.error??null,explanation:record.explanation?{meaning:record.explanation.meaning}:null}); + progress.completed++; + } + // Recover only this mailbox's pending bills, leaving other agent work untouched. const after=await readAgentState(directory); - for(const bill of after.bills.filter(b=>b.outcome==='pending'))await resumeAgentBill(directory,bill.id); + for(const bill of after.bills.filter(b=>mailbox.has(b.id)&&b.outcome==='pending'))await resumeAgentBill(directory,bill.id); }finally{progress.running=false;progress.current=null;} return readCafe(directory); } export async function topUpCafe(directory:string){ requireLocalDemo();if(!config(directory).ready)throw new DeskWebError('Open the café first.'); - await withDesk(directory,async desk=>{await desk.worker.rootAccount.transfer(desk.owner,parseNear('5'));await desk.owner.call(desk.vault,'fund',{}, {attachedDeposit:parseNear('5')});}); + await withDesk(directory,async desk=>{await desk.worker.rootAccount.transfer(desk.owner,parseNear('5'));await desk.owner.call(desk.vault,'fund',{}, {attachedDeposit:parseNear('5')});await settleWallet(desk);}); + return readCafe(directory); +} +function logBank(directory:string,kind:BankEntry['kind'],amount:bigint){ + const cafe=config(directory);cafe.bank=[...(cafe.bank??[]),{at:new Date().toISOString(),kind,amount:amount.toString()}]; + saveJson(join(directory,'cafe.json'),cafe); +} +// First half of the old faucet: 5 test NEAR from the sandbox root to Dave's wallet. +export async function walletFaucetCafe(directory:string){ + requireLocalDemo();if(!config(directory).ready)throw new DeskWebError('Open the café first.'); + await withDesk(directory,async desk=>{await desk.worker.rootAccount.transfer(desk.owner,WALLET_FAUCET.toString());await settleWallet(desk);}); + logBank(directory,'faucet',WALLET_FAUCET); + return readCafe(directory); +} +// Second half of the old faucet, with Dave's chosen amount: the owner's existing `fund`. +export async function depositCafe(directory:string,value:unknown){ + requireLocalDemo();const amount=typeof value==='bigint'?value:parseDemoAmount(value); + if(amount<=0n)throw new DeskWebError('Enter an amount greater than 0.'); + if(!config(directory).ready)throw new DeskWebError('Open the café first.'); + await withDesk(directory,async desk=>{ + const wallet=await walletOf(desk),limit=wallet>GAS_RESERVE?wallet-GAS_RESERVE:0n; + if(amount>limit)throw new DeskWebError(`You can deposit up to ${formatYocto(limit)} NEAR. ${RESERVE_MESSAGE}`); + await desk.owner.call(desk.vault,'fund',{},{attachedDeposit:amount.toString()}); + await settleWallet(desk); + }); + logBank(directory,'deposit',amount); + return readCafe(directory); +} +const formatYocto=(v:bigint)=>{const whole=v/YOCTO,fraction=(v%YOCTO).toString().padStart(24,'0').replace(/0+$/,'');return fraction?`${whole}.${fraction}`:String(whole);}; +// Same operation as `agent:desk policy`, keeping the pinned suppliers and minimum. +export async function setRulesCafe(directory:string,input:DemoRules|{per_bill?:unknown;daily_budget?:unknown;hours?:unknown}){ + requireLocalDemo();const rules='per' in input?input:parseDemoRules(input); + if(!config(directory).ready)throw new DeskWebError('Open the café first.'); + await withDesk(directory,async desk=>{ + const snapshot:any=await desk.vault.view('policy_snapshot',{}); + const merchants=(snapshot.policy?.merchants??[]).map((m:any)=>({id:m.id,payee:m.payee})); + if(!merchants.length)throw new DeskWebError('No suppliers are pinned. Start a new day to set the café up again.'); + const minimum=BigInt(snapshot.min_payment); + if(rules.per{ + try{await renewLocalPolicy(desk,`demo-${Date.now()}-${randomUUID().slice(0,8)}`,RENEW_MINUTES);} + catch(error){ + if(error instanceof Error&&/must extend (the current )?policy expiry/i.test(error.message))throw new DeskWebError('Your rules already last longer than 2 more hours.'); + throw error; + } + await settleWallet(desk); + }); + return readCafe(directory); +} +// "Try again" for a bill the vault stopped only because of the daily budget: +// the existing resume path re-requests the saved proposal (no model call). +export const BUDGET_STOP=/rolling daily budget exceeded/i; +export const budgetRetryable=(bill:{outcome?:string;error?:string|null;has_proposal?:boolean})=>bill.outcome==='blocked'&&bill.has_proposal===true&&BUDGET_STOP.test(bill.error??''); +export async function retryCafeBill(directory:string,id:string){ + requireLocalDemo();const cafe=config(directory);if(!cafe.ready)throw new DeskWebError('Open the café first.'); + if(!cafe.mail?.invoices.some(invoice=>invoice.id===id))throw new DeskWebError("That bill isn't in today's café mailbox."); + const bill=(await readAgentState(directory)).bills.find(b=>b.id===id); + if(!bill)throw new DeskWebError('Unknown invoice.'); + if(!budgetRetryable(bill))throw new DeskWebError('Only bills stopped by the daily budget can be tried again.'); + await resumeAgentBill(directory,id); return readCafe(directory); } export async function backupCafe(directory:string){ diff --git a/app/ask-widget.test.ts b/app/ask-widget.test.ts index 76c7519..82524d0 100644 --- a/app/ask-widget.test.ts +++ b/app/ask-widget.test.ts @@ -1,13 +1,15 @@ import {test} from 'node:test'; import assert from 'node:assert/strict'; import {createAskWidget} from './public/ask-widget.js'; -import {askCard, applyAsk} from './public/ask-shared.js'; +import {askCard, applyAsk, questionBox, splitAnswer, createAskHistory, showHistory, HISTORY_KEY, HISTORY_MAX} from './public/ask-shared.js'; +import {readFileSync} from 'node:fs'; // Exercise the real browser modules with HTTP mocked, without a model or chain. class Element { tag:string; children:Element[]=[]; parent:Element|null=null; attributes:Record={}; handlers:Record={}; className=''; value=''; hidden=false; disabled=false; id=''; private text=''; + style:{height:string}={height:''}; scrollHeight=42; submission:unknown; constructor(tag:string){this.tag=tag;} get childElementCount(){return this.children.length;} get lastElementChild(){return this.children.at(-1)!;} @@ -28,13 +30,14 @@ class Element { contains(n:Element):boolean{return this===n || this.children.some(child=>child.contains(n));} getClientRects():object[]{return this.hidden || !this.isConnected || this.parent?.getClientRects().length===0 ? [] : [{}];} focus(){(globalThis as any).document.activeElement=this;} + requestSubmit(){this.submission=this.event('submit');} find(predicate:(n:Element)=>boolean):Element|undefined{ if(predicate(this))return this; for(const n of this.children){const found=n.find(predicate);if(found)return found;} } event(name:string,extra={}){return this.handlers[name]?.({currentTarget:this,preventDefault(){},...extra});} } -function setup(t:any){ +function setup(t:any,history=createAskHistory({storage:null})){ const body=new Element('body'), handlers:Record={}; const dom={body,activeElement:body,createElement:(tag:string)=>new Element(tag),createElementNS:(_:string,tag:string)=>new Element(tag), querySelector:(selector:string)=>selector==='[data-view="ask-dave"]'?body.find(n=>n.attributes['data-view']==='ask-dave'):null,addEventListener:(name:string,fn:Function)=>handlers[name]=fn}; @@ -43,12 +46,12 @@ function setup(t:any){ t.after(()=>{if(previous)Object.defineProperty(globalThis,'document',previous);else delete (globalThis as any).document;}); const fullInput=new Element('input');body.append(fullInput); const navLink=new Element('a');navLink.setAttribute('data-view','ask-dave');body.append(navLink); - const widget=createAskWidget({onNavigate:()=>{widget.setOnAskDaveView(true);fullInput.focus();}}); + const widget=createAskWidget({history,onNavigate:()=>{widget.setOnAskDaveView(true);fullInput.focus();}}); const panel=widget.panel as Element, button=widget.button as Element; - const input=panel.find(n=>n.tag==='input')!, form=panel.find(n=>n.tag==='form')!; + const input=panel.find(n=>n.tag==='textarea')!, form=panel.find(n=>n.tag==='form')!; const answers=panel.find(n=>n.className.includes('ask-widget-answers '))!; const bill=new Element('button');body.append(bill); - return {widget,panel,button,input,form,answers,bill,dom,handlers,fullInput,navLink}; + return {widget,panel,button,input,form,answers,bill,dom,handlers,fullInput,navLink,history}; } const reply=(text:string,ok=true)=>({ok,json:async()=>ok?{ok:true,text}:{ok:false,error:text}} as Response); @@ -108,6 +111,57 @@ test('429 is an error card; submitted text remains available to retry and is nev assert.ok(answers.textContent.includes(message));assert.equal(answers.find(n=>n.tag==='img'),undefined); }); +test('both question boxes send on Enter, add a line on Shift+Enter, and grow',t=>{ + const {input,form}=setup(t); + assert.equal(input.tag,'textarea'); + const html=readFileSync(new URL('./public/index.html',import.meta.url),'utf8'); + assert.match(html,//); + const pageInput=new Element('textarea'),pageForm=new Element('form'); + const page=questionBox(pageInput,pageForm); + for(const [box,owner] of [[input,form],[pageInput,pageForm]] as const){ + let prevented=false,submitted=0; + owner.addEventListener('submit',()=>{submitted++;}); + box.value='First line';box.event('keydown',{key:'Enter',shiftKey:true,preventDefault(){prevented=true;}}); + assert.equal(prevented,false);assert.equal(submitted,0); + box.value+='\nSecond line';box.scrollHeight=72;box.event('input');assert.equal(box.style.height,'74px'); + box.event('keydown',{key:'Enter',shiftKey:false,preventDefault(){prevented=true;}}); + assert.equal(prevented,true);assert.equal(submitted,1); + } + page.clear();assert.equal(pageInput.value,''); +}); + +test('verified reply folds records and Sources; plain facts stay visible',t=>{ + setup(t); + const text='Dave says hello.\nAnother line.\n\n[INV-1] Paid.\nSources: vault at block 9'; + assert.deepEqual(splitAnswer(text),{reply:'Dave says hello.\nAnother line.',records:'[INV-1] Paid.\nSources: vault at block 9'}); + const {head,body}=askCard('Question'); + assert.equal(applyAsk(new Element('article'),head,body,{ok:true,text}),true); + const toggle=body.find(n=>n.className==='ask-records-toggle')!,records=body.find(n=>n.className==='ask-records')!; + assert.equal(body.children[0].textContent,'Dave says hello.'); + assert.equal(toggle.textContent,'Show the vault records'); + assert.equal(toggle.attributes['aria-expanded'],'false'); + assert.equal(toggle.attributes['aria-controls'],records.id); + assert.equal(records.hidden,true);assert.match(records.textContent,/Sources: vault at block 9/); + toggle.event('click');assert.equal(records.hidden,false);assert.equal(toggle.attributes['aria-expanded'],'true'); + toggle.event('click');assert.equal(records.hidden,true);assert.equal(toggle.attributes['aria-expanded'],'false'); + const plain=askCard('Plain'); + const facts='[INV-1] Paid.\nSources: vault at block 9'; + applyAsk(plain.card,plain.head,plain.body,{ok:true,text:facts}); + assert.equal(splitAnswer(facts),null); + assert.equal(plain.body.find(n=>n.className==='ask-records-toggle'),undefined); + assert.deepEqual(plain.body.children.map(n=>n.textContent),facts.split('\n')); +}); + +test('successful Ask clears its question; a failed Ask keeps it for retry',async t=>{ + const {widget,input,form}=setup(t);widget.open(); + let calls=0; + t.mock.method(globalThis,'fetch',async()=>++calls===1?reply('No answer.',false):reply('A verified answer.')); + input.value='Why did it fail?';await form.event('submit'); + assert.equal(input.value,'Why did it fail?'); + await form.event('submit'); + assert.equal(input.value,'');assert.equal(calls,2); +}); + test('history stays at three during requests, duplicate submits are ignored, and newer drafts survive',async t=>{ const {widget,input,form,answers,bill}=setup(t);widget.open(); let finish:(r:Response)=>void=()=>{}; @@ -133,13 +187,120 @@ test('panel follow-ups use the question API and retain focus when old cards are assert.equal(answers.children[0].find(n=>n.tag==='button'),undefined); }); -test('shared account answers keep verdict colors and Sources text without parsing markup',t=>{ +test('account check keeps its account visible beside yes/no/not yet, with details folded',t=>{ setup(t); - for(const [verdict,tone] of [['STOP','danger'],['WARN','warning'],['PAY','success']]){ - const {card,head,body}=askCard('Account'); - assert.equal(applyAsk(card,head,body,{ok:true,text:`${verdict}: \nSources: chain`},true),true); + for(const [verdict,tone,opening] of [['STOP','danger','No —'],['WARN','warning','Not yet —'],['PAY','success','Yes —']] as const){ + const {card,head,body}=askCard('beans.test.near'); + assert.equal(head.children[0].className,'ask-card-title'); + assert.equal(head.children[0].textContent,'beans.test.near'); + assert.equal(applyAsk(card,head,body,{ok:true,text:`${verdict}: Account not pinned.\n- Exists: yes.\nSources: chain`},true),true); assert.ok(head.find((n:Element)=>n.className===`badge ${tone}`)); - assert.ok(body.find((n:Element)=>n.className==='ask-sources')); + assert.equal(body.children[0].textContent.startsWith(opening),true); + const details=body.find((n:Element)=>n.tag==='details')!; + assert.equal(details.children[0].textContent,'Show account checks'); + assert.equal(details.attributes.open,undefined); + assert.match(details.textContent,/Sources: chain/); assert.equal(body.find((n:Element)=>n.tag==='script'),undefined); } }); + + +test('Ask immediately empties the composer while waiting; an error restores the question for retry',async t=>{ + const {widget,input,form,answers}=setup(t);widget.open(); + let resolveRequest:(response:Response)=>void=()=>{}; + t.mock.method(globalThis,'fetch',async()=>new Promise(r=>{resolveRequest=r;})); + input.value='How much do I have?'; + const pending=form.event('submit'); + assert.equal(input.value,''); // No manual deletion while Dave is thinking. + assert.equal(answers.children[0].find(n=>n.tag==='h3')!.textContent,'How much do I have?'); + assert.equal(answers.children[0].find(n=>n.tag==='h3')!.className,'ask-card-title'); + assert.equal(form.hidden,false); // Keep the composer available, don't hide it. + resolveRequest(reply('Temporary failure',false)); + await pending; + assert.equal(input.value,'How much do I have?'); + assert.equal(answers.children[0].find(n=>n.tag==='h3')!.textContent,'How much do I have?'); + assert.match(answers.textContent,/Temporary failure/); +}); + +test('Ask leaves newly typed draft alone when the previous answer completes',async t=>{ + const {widget,input,form}=setup(t);widget.open(); + let resolveRequest:(response:Response)=>void=()=>{}; + t.mock.method(globalThis,'fetch',async()=>new Promise(r=>{resolveRequest=r;})); + input.value='How much do I have?'; + const pending=form.event('submit'); + assert.equal(input.value,''); + input.value='What are my rules?'; + resolveRequest(reply('Your vault holds 4.6 NEAR.')); + await pending; + assert.equal(input.value,'What are my rules?'); +}); + +// --- One shared answer history ------------------------------------------------ +class MemoryStorage{data=new Map();getItem(k:string){return this.data.get(k)??null;}setItem(k:string,v:string){this.data.set(k,String(v));}removeItem(k:string){this.data.delete(k);}} +const titles=(list:Element)=>list.children.map(c=>c.find(n=>n.tag==='h3')?.textContent); +function page(history:any){const list=new Element('div'),empty=new Element('p');empty.textContent='Ask a question or check an account to see an answer here.';showHistory(history,list,{empty});return {list,empty};} + +test('an answer asked in the panel appears on the full page, newest first, with the same card',async t=>{ + const history=createAskHistory({storage:new MemoryStorage()}); + const {widget,input,form,answers}=setup(t,history);widget.open(); + const full=page(history); + assert.deepEqual(full.list.children,[full.empty]); + t.mock.method(globalThis,'fetch',async(_u:string,o:any)=>reply('Answer to '+JSON.parse(o.body).text+'\nSources: vault at block 9')); + input.value='How much do I have?';await form.event('submit'); + input.value='What are my rules?';await form.event('submit'); + assert.deepEqual(titles(full.list),['What are my rules?','How much do I have?']); + assert.deepEqual(titles(answers),titles(full.list)); + assert.equal(full.list.children[0].textContent,answers.children[0].textContent); + // And the other way round: an answer recorded from the full page shows in the panel. + const id=history.begin('account','Account: beans.test.near'); + history.finish(id,{ok:true,text:'PAY: Pinned supplier.\nSources: chain'}); + assert.equal(titles(answers)[0],'Account: beans.test.near');assert.equal(titles(full.list)[0],'Account: beans.test.near'); +}); + +test('a reload keeps the history; in-flight answers are not saved; it is capped at 30',async t=>{ + const storage=new MemoryStorage(),history=createAskHistory({storage}); + t.mock.method(globalThis,'fetch',async()=>reply('[INV-1] Paid.\nSources: vault')); + const {input,form,widget}=setup(t,history);widget.open(); + input.value='Was INV-1 paid?';await form.event('submit'); + history.begin('question','Still waiting'); + const reloaded=createAskHistory({storage}),full=page(reloaded); + assert.deepEqual(titles(full.list),['Was INV-1 paid?']); + assert.match(full.list.textContent,/\[INV-1\] Paid\./); + for(let i=0;ix',data:{ok:true,text:''}},{kind:'evil',label:'y',data:{}},null])); + const odd=page(createAskHistory({storage})); + assert.deepEqual(titles(odd.list),['x']);assert.equal(odd.list.find(n=>n.tag==='img'||n.tag==='b'),undefined); +}); + +test('Clear empties both the page and the panel, and the saved copy',async t=>{ + const storage=new MemoryStorage(),history=createAskHistory({storage}); + const {input,form,answers,widget}=setup(t,history);widget.open();const full=page(history); + t.mock.method(globalThis,'fetch',async()=>reply('Answer')); + input.value='How is my agent doing?';await form.event('submit'); + assert.equal(answers.children.length,1); + history.clear(); + assert.equal(answers.children.length,0);assert.deepEqual(full.list.children,[full.empty]); + assert.equal(storage.getItem(HISTORY_KEY),null); + assert.deepEqual(createAskHistory({storage}).entries(),[]); + const html=readFileSync(new URL('./public/index.html',import.meta.url),'utf8'),app=readFileSync(new URL('./public/app.js',import.meta.url),'utf8'); + assert.match(html,/ -

-

Supplier ledger

-

Today's invoices

Rejected at intake

+
Questions
+
SUPPLIERS[merchant] ?? FALLBACK; + +// Exact split in yoctoNEAR: weighted shares, the first line takes the remainder, +// so the lines always add up to the invoice amount. +export function lineItems(merchant, amount) { + const total = BigInt(amount), + lines = supplierInfo(merchant).lines, + weight = lines.reduce((sum, [, w]) => sum + w, 0n); + const amounts = lines.map(([, w]) => (total * w) / weight); + amounts[0] += total - amounts.reduce((sum, a) => sum + a, 0n); + return lines.map(([label], i) => ({ label, amount: amounts[i].toString() })); +} + +// INV-BEANS-01-3f9cbc12 → BEANS-01 +export function shortBill(id) { + const match = String(id ?? "").match(/^INV-([A-Z]+-\d+)-/); + return match ? match[1] : String(id ?? ""); +} + +export const SIGNATURE_SENTENCE = (supplier) => + `The signature doesn't match. Something on this invoice was changed after ${supplier} signed it.`; + +const near = (yocto) => formatUnits(yocto) + " NEAR"; +export function dueLine(invoice) { + if (invoice.week) return "Week " + invoice.week; + if (invoice.expires_at == null) return "—"; + const at = new Date(Number(invoice.expires_at)); + return Number.isNaN(at.getTime()) ? "—" : at.toLocaleDateString() + " " + at.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }); +} +function meta(label, value) { + const cell = el("div", "", "inv-meta-cell"); + cell.append(el("span", label, "inv-label"), el("strong", value)); + return cell; +} + +// invoice: {id, merchant, supplier, payee, amount (yocto), expires_at, week} +export function invoiceDocument(invoice, issuedAt) { + const info = supplierInfo(invoice.merchant), + doc = el("article", "", "inv-doc"), + head = el("header", "", "inv-head"), + who = el("div", "", "inv-who"), + title = el("div", "", "inv-title"); + who.append(el("h3", invoice.supplier, "inv-supplier"), el("p", info.description, "inv-desc")); + title.append(el("span", "INVOICE", "inv-label"), el("strong", shortBill(invoice.id), "inv-no")); + head.append(who, title); + const metaRow = el("div", "", "inv-meta"), + issued = new Date(issuedAt ?? Date.now()); + metaRow.append(meta("Billed to", "Dave's Café"), meta("Issued", issued.toLocaleDateString()), meta("Due", dueLine(invoice))); + const lines = el("div", "", "inv-lines"); + for (const line of lineItems(invoice.merchant, invoice.amount)) { + const row = el("div", "", "inv-line"); + row.append(el("span", line.label), el("span", near(line.amount), "inv-amount")); + lines.append(row); + } + const total = el("div", "", "inv-line inv-total"); + total.append(el("span", "Total due"), el("span", near(invoice.amount), "inv-amount")); + const pay = el("div", "", "inv-pay"); + pay.append(el("span", "Pay to", "inv-label"), el("strong", invoice.payee, "inv-payee")); + doc.append(head, metaRow, lines, total, pay, el("footer", `Digitally signed by ${invoice.supplier} · Ed25519`, "inv-foot")); + doc.setAttribute("aria-label", `Invoice ${shortBill(invoice.id)} from ${invoice.supplier}`); + return doc; +} diff --git a/app/public/style.css b/app/public/style.css index 63b5491..126f2e3 100644 --- a/app/public/style.css +++ b/app/public/style.css @@ -1178,6 +1178,22 @@ input[aria-invalid="true"] { .ask-forms .panel-header { padding-bottom: 22px; } +#ask-text, +.ask-widget-input { + font: inherit; + font-size: 12px; + line-height: 1.5; + min-height: 42px; + max-height: calc(9em + 22px); + padding: 11px 12px; + border: 1px solid #dbe2de; + border-radius: 7px; + background: #fdfefb; + color: var(--ink); + resize: none; + overflow-y: auto; +} +#ask-text { display: block; width: 100%; } .ask-check { border-top: 1px solid var(--line); margin-top: 23px; @@ -1252,6 +1268,20 @@ input[aria-invalid="true"] { .ask-card-body .ask-line + .ask-line { margin-top: 5px; } +.ask-records-toggle { + display: block; + margin: 10px 0 4px; + padding: 4px 0; + border: 0; + background: transparent; + color: var(--teal-dark); + font: inherit; + font-size: 11px; + font-weight: 700; + text-decoration: underline; + text-underline-offset: 3px; +} +.ask-records { margin-top: 7px; } .ask-sources { font-size: 10px; color: var(--muted); @@ -1671,3 +1701,10 @@ input[aria-invalid="true"] { min-height: 40px; } } + +/* Account checks: readable conclusion, optional technical evidence. */ +.ask-account-decision { font-size: 14px; line-height: 1.5; font-weight: 700; margin: 0 0 8px; } +.ask-account-reason { font-size: 12px; line-height: 1.5; margin: 0 0 8px; } +.ask-account-note { font-size: 11px; line-height: 1.55; color: var(--muted); margin: 0 0 10px; } +.ask-account-checks summary { cursor: pointer; color: var(--teal-dark); font-size: 11px; text-decoration: underline; text-underline-offset: 3px; } +.ask-account-checks .ask-records { padding-top: 9px; } diff --git a/app/server.ts b/app/server.ts index 6bc8dff..18ae106 100644 --- a/app/server.ts +++ b/app/server.ts @@ -1,5 +1,5 @@ import {createDemoRoute} from './demo-route.ts'; -import {readCafe,setupCafe,receiveCafe,payCafe,topUpCafe,resetCafe} from '../agent/demo-cafe.ts'; +import {readCafe,setupCafe,receiveCafe,payCafe,payCafeBill,topUpCafe,walletFaucetCafe,depositCafe,setRulesCafe,renewRulesCafe,retryCafeBill,resetCafe} from '../agent/demo-cafe.ts'; import {publicError,validateDeskPolicy} from './errors.ts'; import { SandboxDesk } from './sandbox.ts'; import { fileURLToPath } from 'node:url'; @@ -20,7 +20,7 @@ const assets: Record={ '/sandbox.js':['public/sandbox.js','text/javascript'], '/style.css':['public/style.css','text/css'], '/components.js':['public/components.js','text/javascript'], '/state.js':['public/state.js','text/javascript'], '/agent-payments.js':['public/agent-payments.js','text/javascript'], '/agent-payments.css':['public/agent-payments.css','text/css'], - '/demo-cafe.js':['public/demo-cafe.js','text/javascript'], '/demo-cafe.css':['public/demo-cafe.css','text/css'], + '/demo-cafe.js':['public/demo-cafe.js','text/javascript'], '/demo-world.js':['public/demo-world.js','text/javascript'], '/invoice-doc.js':['public/invoice-doc.js','text/javascript'], '/demo-cafe.css':['public/demo-cafe.css','text/css'], '/ask-source.js':['public/ask-source.js','text/javascript'], '/ask-shared.js':['public/ask-shared.js','text/javascript'], '/ask-widget.js':['public/ask-widget.js','text/javascript'], '/ask-suggest.js':['public/ask-suggest.js','text/javascript'], '/ask-widget.css':['public/ask-widget.css','text/css'], @@ -32,7 +32,7 @@ const paymentDir=resolve(process.env.COUNTERSIGN_SANDBOX_DIR ?? process.env.AEGI const agentDir=resolve(process.env.COUNTERSIGN_AGENT_DIR??fileURLToPath(new URL('../work/agent-vault/',import.meta.url))); const agentRoute=createAgentRoute({state:()=>readAgentState(agentDir),importBill:invoice=>importAgentBill(agentDir,invoice), run:(id,live)=>runAgentBill(agentDir,id,live),resume:id=>resumeAgentBill(agentDir,id),modelReady:liveAgentModelReady,error:agentWebError}); -const demoRoute=createDemoRoute({network:()=>process.env.COUNTERSIGN_NETWORK,state:()=>readCafe(agentDir),setup:()=>setupCafe(agentDir),receive:()=>receiveCafe(agentDir),pay:(live,progress)=>payCafe(agentDir,live,progress),faucet:()=>topUpCafe(agentDir),reset:()=>resetCafe(agentDir),modelReady:liveAgentModelReady}); +const demoRoute=createDemoRoute({network:()=>process.env.COUNTERSIGN_NETWORK,state:()=>readCafe(agentDir),setup:()=>setupCafe(agentDir),receive:()=>receiveCafe(agentDir),pay:(live,progress)=>payCafe(agentDir,live,progress),payOne:id=>payCafeBill(agentDir,id),faucet:()=>topUpCafe(agentDir),walletFaucet:()=>walletFaucetCafe(agentDir),deposit:amount=>depositCafe(agentDir,amount),setRules:rules=>setRulesCafe(agentDir,rules),renewRules:()=>renewRulesCafe(agentDir),retry:id=>retryCafeBill(agentDir,id),reset:()=>resetCafe(agentDir),modelReady:liveAgentModelReady}); let agentMutation=false; const source=()=>askSource(agentDir,paymentDir,process.env.COUNTERSIGN_NETWORK); const sandbox=new SandboxDesk(paymentDir); diff --git a/app/ui.test.ts b/app/ui.test.ts index ec821b7..dc3eb5c 100644 --- a/app/ui.test.ts +++ b/app/ui.test.ts @@ -167,3 +167,69 @@ test("café budget note follows the vault's rolling remaining figure", () => { assert.equal(cafeBudgetSpent(null, [queued], policy), false); assert.equal(cafeBudgetSpent(spending(null), [], policy), false); }); + +// --- Demo world: chapter routing and the separate shell ------------------- +import { readFileSync } from "node:fs"; +import { CHAPTERS, demoRoute, applyDemoWorld, landingHash } from "./public/demo-world.js"; + +test("the bare URL opens Agent payments on every network", () => { + assert.equal(landingHash(""), "#agent-payments"); + assert.equal(demoRoute(landingHash("")), null); + assert.equal(landingHash("#demo"), "#demo"); + assert.equal(landingHash("#ask-dave"), "#ask-dave"); +}); + +test("demo hashes route to the five chapters; bare #demo opens the morning post", () => { + assert.deepEqual( + CHAPTERS.map((c) => c.id), + ["bank", "rules", "post", "pay", "end"], + ); + for (const id of ["bank", "rules", "post", "pay", "end"]) + assert.deepEqual(demoRoute("#demo/" + id), { chapter: id, hash: "#demo/" + id }); + for (const hash of ["#demo", "#demo/", "#demo/unknown"]) + assert.deepEqual(demoRoute(hash), { chapter: "post", hash: "#demo/post" }); + for (const hash of ["#agent-payments", "#ask-dave", "#payments", "", "#demolition"]) + assert.equal(demoRoute(hash), null); +}); + +test("the demo world hides the product sidebar and header, and restores them outside", () => { + const node = (dataset: Record = {}) => ({ + hidden: false, + dataset, + attrs: {} as Record, + setAttribute(name: string, value: string) { this.attrs[name] = value; }, + removeAttribute(name: string) { delete this.attrs[name]; }, + }); + const classes = new Set(); + const sidebar = node(), topbar = node(); + const chapters = CHAPTERS.map((c) => node({ chapter: c.id })); + const tabs = CHAPTERS.map((c) => node({ chapter: c.id })); + const doc = { + body: { classList: { toggle: (name: string, on: boolean) => (on ? classes.add(name) : classes.delete(name)) } }, + querySelector: (s: string) => (s === ".sidebar" ? sidebar : s === ".topbar" ? topbar : null), + querySelectorAll: (s: string) => (s === ".dw-chapter" ? chapters : s === ".dw-tab" ? tabs : []), + }; + applyDemoWorld(doc, "pay"); + assert.ok(classes.has("demo-world")); + assert.equal(sidebar.hidden, true); + assert.equal(topbar.hidden, true); + assert.deepEqual(chapters.map((c) => c.hidden), [true, true, true, false, true]); + assert.deepEqual(tabs.map((t) => t.attrs["aria-current"] ?? null), [null, null, null, "page", null]); + applyDemoWorld(doc, null); + assert.ok(!classes.has("demo-world")); + assert.equal(sidebar.hidden, false); + assert.equal(topbar.hidden, false); + assert.ok(chapters.every((c) => c.hidden)); + assert.ok(tabs.every((t) => !("aria-current" in t.attrs))); +}); + +test("the demo shell links each chapter tab and exits to the product app", () => { + const html = readFileSync(new URL("./public/index.html", import.meta.url), "utf8"); + assert.match(html, /← Workspace<\/a>/); + assert.match(html, /Local test funds<\/span>/); + for (const c of CHAPTERS) + assert.match(html, new RegExp(`href="#demo/${c.id}" data-chapter="${c.id}">${c.number}${c.label}`)); + for (const id of ["demo-cafe", "cafe-feedback", "cafe-actions", "cafe-summary", "cafe-ledger", "cafe-bills", "cafe-progress", "cafe-read-at", "cafe-ask"]) + assert.match(html, new RegExp(`id="${id}"`), id); + assert.doesNotMatch(html, /