Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
f09e04c
Demo world, step 1: new look and chapter shell
Nov 13, 2026
e9da565
Demo world, step 2: real invoice documents
Nov 13, 2026
aa86c0b
Demo world, step 2b: remove the tampered invoice's giveaways
Nov 13, 2026
34bf1d4
Demo world, step 3: The bank
Nov 13, 2026
b5310dc
Demo world, step 4: Your rules
Nov 13, 2026
9feef40
Demo world, step 5: Agent pays and End of day
Nov 13, 2026
fff6690
Ask Dave input: auto-growing box, clear on send, fold vault records
Nov 13, 2026
f9a9f79
Fix Ask Dave question clearing and account explanations
Nov 13, 2026
d3df7d9
Demo world: pay invoices one at a time
Nov 13, 2026
d83a519
Merge remote-tracking branch 'origin/main' into codex/demo20-validation
Pradeeppilotdev Nov 13, 2026
3c91dab
Preserve cafe payment history and improve mobile invoice review
Pradeeppilotdev Nov 13, 2026
fa9b0c5
Give finished cafe results more space
Pradeeppilotdev Nov 13, 2026
9356c20
Keep the checked account visible in Ask Dave replies
Pradeeppilotdev Nov 13, 2026
844865a
Allow headroom for the full local payment verification suite
Pradeeppilotdev Nov 13, 2026
2ca7f50
Demo café: keep Pay all and Retry inside the café mailbox
Nov 13, 2026
9f8a02b
Keep cafe crash recovery within its own mailbox
Pradeeppilotdev Nov 13, 2026
d2c548f
Ask Dave: one shared answer history across panel and page
Nov 14, 2026
6a51d22
Open on the product; clearer exit from the demo
Nov 14, 2026
51a1ba0
Keep cafe chapters clear of balances on smaller laptops
Pradeeppilotdev Nov 14, 2026
ffe718f
Give the cafe a clear warm light layout
Pradeeppilotdev Nov 14, 2026
47cd063
Refine cafe totals and receipts with finance dashboard hierarchy
Pradeeppilotdev Nov 14, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/verify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
177 changes: 166 additions & 11 deletions agent/demo-cafe.ts

Large diffs are not rendered by default.

181 changes: 171 additions & 10 deletions app/ask-widget.test.ts
Original file line number Diff line number Diff line change
@@ -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<string,string>={}; handlers:Record<string,Function>={};
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)!;}
Expand All @@ -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<string,Function>={};
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};
Expand All @@ -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);

Expand Down Expand Up @@ -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,/<textarea\s+id="ask-text"[\s\S]*?<\/textarea>/);
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=()=>{};
Expand All @@ -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}: <script>unsafe</script>\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<Response>(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<Response>(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<string,string>();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;i<HISTORY_MAX+5;i++){const n=reloaded.begin('question','Q'+i);reloaded.finish(n,{ok:true,text:'A'+i});}
assert.equal(reloaded.entries().length,30);assert.equal(JSON.parse(storage.getItem(HISTORY_KEY)!).length,30);
assert.equal(titles(full.list)[0],'Q34');
// Saved data is never trusted as markup, and junk entries are dropped.
storage.setItem(HISTORY_KEY,JSON.stringify([{kind:'question',label:'<b>x</b>',data:{ok:true,text:'<img src=x>'}},{kind:'evil',label:'y',data:{}},null]));
const odd=page(createAskHistory({storage}));
assert.deepEqual(titles(odd.list),['<b>x</b>']);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,/<button id="ask-clear"[^>]*type="button">Clear<\/button>/);
assert.match(app,/#ask-clear"\)\.addEventListener\("click", \(\) => askHistory\.clear\(\)\)/);
});

test('storage that throws never breaks asking: the history falls back to memory',async t=>{
const broken={getItem(){throw Error('denied');},setItem(){throw Error('quota');},removeItem(){throw Error('denied');}};
for(const storage of [broken,()=>{throw Error('SecurityError');}]){
const history=createAskHistory({storage});
const {input,form,answers,widget}=setup(t,history);widget.open();const full=page(history);
t.mock.method(globalThis,'fetch',async()=>reply('Your vault holds 4.6 NEAR.'));
input.value='How much do I have?';await form.event('submit');
assert.equal(input.value,'');
assert.deepEqual(titles(answers),['How much do I have?']);assert.deepEqual(titles(full.list),['How much do I have?']);
assert.match(full.list.textContent,/4\.6 NEAR/);
history.clear();assert.deepEqual(full.list.children,[full.empty]);
(globalThis.fetch as any).mock.restore();
}
});
5 changes: 3 additions & 2 deletions app/demo-cafe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ for(const failedOperation of ['refresh','setup'])test(`café refresh replaces a
finish(Response.json({ok:true,state:{ready:true,vault:'cafe.test.near',available:'4960000000000000000000000',policy:{per_payment_near:'0.5',rolling_24h_limit_near:'1.2',expires_at:Date.now()+3600000},suppliers:[],scam:{payee:'scam.test.near',received:'0'},bills:[],rejected:[],read_at:new Date().toISOString()}}));
await refreshing;
assert.match(get('#cafe-summary').textContent,/4\.96 test NEAR available/);
assert.equal(feedback.textContent,'Ledger refreshed.');
assert.equal(feedback.children[0].className,'notice success');
// The demo shows a status line only for errors: a good read clears it.
assert.equal(feedback.textContent,'');
assert.equal(feedback.children.length,0);
assert.equal(get('#demo-cafe').attributes['aria-busy'],'false');
respond=async()=>Response.json({ok:false,error:'Ledger is temporarily unavailable'});
await ui.refreshCafe();
Expand Down
Loading
Loading