Files
order-notification-automation/tests/assistant/events-client.test.cjs
T

32 lines
6.3 KiB
JavaScript

'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),vm=require('node:vm'),fs=require('node:fs');
const source=fs.readFileSync('web/modules/assistant/events-client.js','utf8');
const settle=async()=>{for(let i=0;i<15;i++)await Promise.resolve();};
test('event transport falls back after stream failures, resumes by cursor and never posts messages',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let fetches=0,polls=0,changes=0;const accepted=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{fetches++;throw new TypeError('disconnected');}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async route=>{assert.match(route,/\/events\?after=0$/);polls++;return {events:[{conversationId:'own',seq:1,kind:'completed'}],nextCursor:1,hasMore:false};},onEvents:rows=>accepted.push(...rows),onChange:async()=>{changes++;}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(fetches,3);assert.equal(polls,1);assert.equal(client.cursor,1);assert.equal(changes,1);assert.equal(accepted.length,1);client.dispose();t.mock.timers.tick(120000);await settle();assert.equal(polls,1);
});
test('event transport treats login failure as terminal instead of reconnecting forever',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let failures=0,requests=0;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{requests++;return new Response('{}',{status:401});}};vm.runInNewContext(source,scope);scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('no fallback after auth failure'),onEvents:()=>assert.fail('no data'),onChange:async()=>{},onAuth:error=>{assert.equal(error.status,401);failures++;}});await settle();t.mock.timers.tick(60000);await settle();assert.equal(failures,1);assert.equal(requests,1);
});
test('SSE parsing tolerates chunk boundaries and ignores replayed sequence IDs',async()=>{
const received=[];let controller,changed=0;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async(_url,options)=>new Response(new ReadableStream({start(c){controller=c;options.signal.addEventListener('abort',()=>c.close(),{once:true});}}),{headers:{'Content-Type':'text/event-stream'}})};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',cursor:1,api:async()=>assert.fail('no polling on a healthy stream'),onEvents:rows=>received.push(...rows),onChange:async()=>{changed++;}});await settle();const encoder=new TextEncoder(),frame=seq=>'event: assistant_event\ndata: '+JSON.stringify({conversationId:'own',seq,kind:'completed'})+'\n\n';controller.enqueue(encoder.encode(frame(1)+frame(2).slice(0,20)));controller.enqueue(encoder.encode(frame(2).slice(20)));await settle();assert.equal(received.length,1);assert.equal(received[0].seq,2);assert.equal(changed,1);client.dispose();
});
test('a failed authoritative reload does not acknowledge the final event before recovery',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let streamCount=0,reloads=0;const cursors=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async url=>{cursors.push(url);streamCount++;return new Response(new ReadableStream({start(c){c.enqueue(new TextEncoder().encode('event: assistant_event\ndata: '+JSON.stringify({conversationId:'own',seq:1,kind:'completed'})+'\n\n'));}}),{headers:{'Content-Type':'text/event-stream'}});}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('not polling yet'),onEvents:()=>{},onChange:async()=>{reloads++;if(reloads===1)throw Error('temporary GET failure');}});await settle();assert.equal(client.cursor,0);t.mock.timers.tick(1000);await settle();assert.equal(streamCount,2);assert.match(cursors[1],/after=0$/);assert.equal(client.cursor,1);client.dispose();
});
test('a failed SSE probe does not start a second outstanding polling loop',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let polls=0;const releases=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{throw Error('offline');}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>{polls++;return await new Promise(resolve=>releases.push(()=>resolve({events:[],nextCursor:0,hasMore:false})));},onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(polls,1);t.mock.timers.tick(60000);await settle();assert.equal(polls,1);client.dispose();for(const release of releases)release();await settle();
});
test('stream negotiation is bounded even when the proxy never returns headers',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let signal;const scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async(_url,options)=>{signal=options.signal;return await new Promise((_resolve,reject)=>signal.addEventListener('abort',()=>reject(Error('connection timed out')),{once:true}));}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>assert.fail('not polling yet'),onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(45000);await settle();assert.equal(signal.aborted,true);client.dispose();
});
test('a probe that connects then ends cannot overlap the pending polling owner',async t=>{
t.mock.timers.enable({apis:['setTimeout']});let fetches=0,polls=0;const releases=[],scope={window:{},setTimeout,clearTimeout,AbortController,TextDecoder,fetch:async()=>{if(++fetches<=3)throw Error('offline');return new Response(new ReadableStream({start(c){c.close();}}),{headers:{'Content-Type':'text/event-stream'}});}};vm.runInNewContext(source,scope);
const client=scope.window.AssistantEvents.connect({id:'own',api:async()=>{polls++;return new Promise(resolve=>releases.push(()=>resolve({events:[],hasMore:false})));},onEvents:()=>{},onChange:async()=>{}});await settle();t.mock.timers.tick(1000);await settle();t.mock.timers.tick(2000);await settle();assert.equal(polls,1);t.mock.timers.tick(60000);await settle();assert.equal(fetches,4);assert.equal(polls,1);client.dispose();for(const release of releases)release();await settle();
});