Add authenticated upload, review, retry and knowledge-selection HTTP flows with bounded JSON processing and frozen OCR policy. Preserve Gemini/OpenAI provider selection and fenced lifecycle semantics; retain FAQ preambles and uncertain vision candidates, and expose opt-in uncalibrated voice transport diagnostics. Include frontend integration examples, aligned contracts and deterministic regressions. Validation: 1767 provider-free tests passed; all 404 PostgreSQL scenarios have passing evidence across the documented runs.
266 lines
13 KiB
JavaScript
266 lines
13 KiB
JavaScript
import fs from 'node:fs';
|
|
import vm from 'node:vm';
|
|
import assert from 'node:assert/strict';
|
|
import {VoiceClient,environment,tick} from './voice_client_harness.mjs';
|
|
const processors={};
|
|
globalThis.AudioWorkletProcessor=class {constructor(){this.messages=[];this.port={postMessage:m=>this.messages.push(m)};}};
|
|
globalThis.registerProcessor=(name,p)=>processors[name]=p;
|
|
vm.runInThisContext(fs.readFileSync(new URL('../../examples/voice-audio-worklet.js',import.meta.url),'utf8'));
|
|
function playback(){const p=new processors['rag-playback']();p.send=data=>p.port.onmessage({data});return p;}
|
|
// Independent count bound retains partially consumed messages across references.
|
|
{
|
|
const p=playback();p.send({type:'start',ref:'a'});p.send({type:'start',ref:'b'});
|
|
for(let n=0;n<100;n++)p.send({type:'pcm',ref:n%2?'a':'b',packet_id:String(n),samples:new Float32Array(2).buffer});
|
|
assert.equal(p.queue.length,100);assert.equal(p.messages.length,0);
|
|
p.process([],[[new Float32Array(1)]]);assert.equal(p.queue.length,100);
|
|
p.send({type:'pcm',ref:'a',packet_id:'excess',samples:new Float32Array(1).buffer});assert.equal(p.messages.at(-1).type,'overflow');
|
|
p.process([],[[new Float32Array(1)]]);assert.equal(p.queue.length,99);
|
|
p.send({type:'pcm',ref:'a',packet_id:'accepted',samples:new Float32Array(1).buffer});assert.equal(p.queue.length,100);
|
|
p.send({type:'flush',id:'flush'});assert.equal(p.queue.length,0);assert.equal(p.queued,0);
|
|
assert.equal(p.messages.at(-1).released.length,100);assert.equal(p.messages.filter(m=>m.type==='progress').every(m=>m.played_ms===0),true);
|
|
}
|
|
// Exact byte boundary is independent of packet count and references.
|
|
{
|
|
const p=playback();p.send({type:'start',ref:'a'});p.send({type:'start',ref:'b'});
|
|
for(let n=0;n<10;n++)p.send({type:'pcm',ref:n%2?'a':'b',packet_id:String(n),samples:new Float32Array(4800).buffer});
|
|
assert.equal(p.queued,48000);
|
|
p.send({type:'pcm',ref:'b',packet_id:'excess',samples:new Float32Array(1).buffer});assert.equal(p.messages.at(-1).type,'overflow');
|
|
p.process([],[[new Float32Array(120)]]);assert.equal(p.messages.at(-1).played_ms,5);
|
|
p.send({type:'flush',id:'f'});assert.equal(p.messages.at(-2).played_ms,5);
|
|
}
|
|
// Real client with delayed MessagePort deliveries: pending handoffs count immediately.
|
|
for(const bytes of [2,9600]) {
|
|
const e=environment(),c=e.client();let processor,mail=[];
|
|
globalThis.AudioWorkletNode=class {
|
|
constructor(context,name){this.name=name;this.port={postMessage:m=>{
|
|
if(name!=='rag-playback')return;
|
|
if(m.type==='pcm')mail.push(m);else processor.port.onmessage({data:m});
|
|
}};
|
|
if(name==='rag-playback') {processor=playback();processor.port.postMessage=m=>this.port.onmessage?.({data:m});}}
|
|
connect(){} disconnect(){}
|
|
};
|
|
const pending=c.connect();await tick();e.ready();e.permission().resolve(e.media());await pending;
|
|
const socket=c.socket,connection=c.connection;
|
|
const control=event=>socket.onmessage({data:JSON.stringify(event)});
|
|
control({type:'audio_started',audio_ref:'a'});
|
|
const count=bytes===2?100:10;
|
|
for(let n=0;n<count;n++)socket.onmessage({data:new ArrayBuffer(bytes)});
|
|
assert.equal(connection.playbackPackets.size,count);assert.equal(connection.playbackBytes,bytes*count);
|
|
// Deliver/consume part of one packet; only actual consumption reduces bytes.
|
|
for(const m of mail)processor.port.onmessage({data:m});mail=[];
|
|
processor.process([],[[new Float32Array(1)]]);
|
|
assert.equal(connection.playbackBytes,bytes*count-2);
|
|
if(bytes===9600) {
|
|
const packetID=processor.queue[0].id;
|
|
c.releasePlayback(connection,packetID,2,false); // Duplicate cumulative consumption is inert.
|
|
assert.equal(connection.playbackBytes,bytes*count-2);
|
|
}
|
|
if(bytes===9600)assert.equal(connection.playbackPackets.size,10);
|
|
// Interruption flush releases every remaining reservation once, without fabricated progress.
|
|
control({type:'turn_interrupted'});await tick();assert.equal(connection.playbackPackets.size,0);assert.equal(connection.playbackBytes,0);
|
|
control({type:'audio_started',audio_ref:'b'});
|
|
for(let n=0;n<count;n++)socket.onmessage({data:new ArrayBuffer(bytes)});
|
|
socket.onmessage({data:new ArrayBuffer(2)});await c.cleanup(connection);
|
|
assert.equal(c.connection,null);assert.equal(connection.playbackBytes,0);assert.equal(connection.playbackPackets.size,0);
|
|
const progress=socket.sent.filter(m=>typeof m==='string').map(m=>JSON.parse(m)).filter(m=>m.type==='playback_progress');
|
|
assert.equal(progress.every(m=>m.played_ms===0),true);
|
|
}
|
|
// C01 and V01 commit but lose their first response. Retry identical retained payloads.
|
|
for(const lost of ['/conversations','/voice/sessions']) {
|
|
const c=new VoiceClient(()=>{}),attempt=c.newCreationAttempt(),requests=[],committed=new Map();let dropped=false;
|
|
c.request=async(path,method,body)=>{
|
|
if(path==='/me')return {csrf_token:'csrf'};
|
|
if(path.includes('/by-request/'))return committed.get('/voice/sessions');
|
|
requests.push({path,body:JSON.stringify(body)});
|
|
if(committed.has(path)&&committed.get(path).payload!==JSON.stringify(body))throw new Error('IDEMPOTENCY_CONFLICT');
|
|
const response=path==='/conversations'?{id:'cid'}:{session_id:'sid',status:'connecting',stream_path:'/stream'};
|
|
committed.set(path,{...response,payload:JSON.stringify(body)});
|
|
assert.equal(c.creationAttempt,attempt);assert.equal(c.conversationRequestID,attempt.conversationRequestID);assert.equal(c.requestID,attempt.sessionRequestID);
|
|
if(path===lost&&!dropped){dropped=true;throw new Error('lost committed response');}
|
|
return response;
|
|
};
|
|
await assert.rejects(c.reserve(),/lost committed response/);
|
|
assert.equal(c.creationAttempt,attempt);assert.equal(c.connection,null);
|
|
if(lost==='/voice/sessions'){const recovered=await c.recover();assert.equal(recovered.session_id,'sid');assert.equal(c.connection,null);}
|
|
await c.retryCreation();assert.equal(c.session.session_id,'sid');assert.equal(c.connection,null);
|
|
const duplicates=requests.filter(r=>r.path===lost);assert.equal(duplicates.length,2);assert.equal(duplicates[0].body,duplicates[1].body);
|
|
assert.throws(()=>{attempt.conversationPayload.mode='text';},TypeError);
|
|
assert.throws(()=>{attempt.sessionPayload.conversation_id='changed';},TypeError);
|
|
await assert.rejects(c.reserve('changed','changed'),/newCreationAttempt/);
|
|
const fresh=c.newCreationAttempt();assert.notEqual(fresh.conversationRequestID,attempt.conversationRequestID);assert.notEqual(fresh.sessionRequestID,attempt.sessionRequestID);
|
|
}
|
|
console.log('Playback bounds, consumed capacity, flush, cleanup and lost-response replay passed');
|
|
// Intentional freshSession performs reconciliation before a new C01/V01 attempt and media.
|
|
{
|
|
const c=new VoiceClient(()=>{}),old=c.newCreationAttempt(),order=[];
|
|
c.session={session_id:'old'};
|
|
c.close=async()=>{order.push('close');};
|
|
c.recover=async()=>{order.push('recover');return {status:'closed'};};
|
|
c.request=async(path,method,body)=>{
|
|
if(path==='/me')return {csrf_token:'fresh'};
|
|
if(path==='/conversations'){order.push('C01');assert.notEqual(body.client_request_id,old.conversationRequestID);return {id:'fresh-cid'};}
|
|
order.push('V01');assert.equal(body.conversation_id,'fresh-cid');assert.notEqual(body.client_request_id,old.sessionRequestID);return {session_id:'fresh',stream_path:'/fresh'};
|
|
};
|
|
c.connect=async()=>{order.push('connect');assert.equal(c.session.session_id,'fresh');};
|
|
await c.freshSession();assert.deepEqual(order,['close','recover','C01','V01','connect']);
|
|
}
|
|
|
|
// Standalone delivered worklet 100/101 boundary
|
|
{
|
|
const capture = new processors['rag-capture']();
|
|
const delivered = [];
|
|
capture.port.postMessage = m => delivered.push(m);
|
|
for (let i = 0; i < 100; i++) capture.process([[new Float32Array(240).fill(0.1)]]);
|
|
assert.equal(delivered.length, 100);
|
|
assert.equal(capture.pending, 100);
|
|
assert.equal(capture.pendingBytes, 48000);
|
|
const overflowed = !capture.process([[new Float32Array(240).fill(0.1)]]);
|
|
assert.equal(overflowed, true);
|
|
assert.equal(delivered.at(-1).type, 'overflow');
|
|
assert.equal(capture.active, false);
|
|
}
|
|
|
|
// Delivered client + worklet: 100/101 boundary with stalled socket (48,000 bytes, exactly 100 packets admitted)
|
|
{
|
|
const e = environment();
|
|
let captureProc = null;
|
|
globalThis.AudioWorkletNode = class {
|
|
constructor(ctx, name) {
|
|
this.name = name;
|
|
if (name === 'rag-capture') {
|
|
captureProc = new processors['rag-capture']();
|
|
this.port = {
|
|
postMessage: m => captureProc.port.onmessage?.({data: m}),
|
|
onmessage: null
|
|
};
|
|
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
|
|
} else {
|
|
this.port = { postMessage: () => {}, onmessage: null };
|
|
}
|
|
}
|
|
connect() {} disconnect() {}
|
|
};
|
|
const c = e.client();
|
|
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
|
|
const socket = c.socket;
|
|
const origSend = socket.send.bind(socket);
|
|
socket.bufferedAmount = 0;
|
|
socket.send = (m) => {
|
|
origSend(m);
|
|
socket.bufferedAmount += m.byteLength || 0;
|
|
};
|
|
for (let i = 0; i < 100; i++) captureProc.process([[new Float32Array(240).fill(0.1)]]);
|
|
assert.equal(socket.sent.length, 100);
|
|
assert.equal(socket.bufferedAmount, 48000);
|
|
assert.equal(c.connection.capturePackets.length, 100);
|
|
assert.equal(c.connection.captureBytes, 48000);
|
|
assert.equal(captureProc.pending, 100);
|
|
// 101st chunk into worklet triggers overflow, stopping capture and cleaning up client
|
|
captureProc.process([[new Float32Array(240).fill(0.1)]]);
|
|
await tick();
|
|
await c.cleanup();
|
|
assert.equal(c.connection, null);
|
|
assert.equal(socket.sent.length, 100);
|
|
assert.equal(socket.bufferedAmount, 48000);
|
|
}
|
|
|
|
// Partial drain releases capacity conservatively only for fully drained packets
|
|
{
|
|
const e = environment();
|
|
let captureProc = null;
|
|
globalThis.AudioWorkletNode = class {
|
|
constructor(ctx, name) {
|
|
this.name = name;
|
|
if (name === 'rag-capture') {
|
|
captureProc = new processors['rag-capture']();
|
|
this.port = {
|
|
postMessage: m => captureProc.port.onmessage?.({data: m}),
|
|
onmessage: null
|
|
};
|
|
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
|
|
} else {
|
|
this.port = { postMessage: () => {}, onmessage: null };
|
|
}
|
|
}
|
|
connect() {} disconnect() {}
|
|
};
|
|
const c = e.client();
|
|
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
|
|
const socket = c.socket;
|
|
socket.bufferedAmount = 0;
|
|
socket.send = (m) => { socket.sent.push(m); socket.bufferedAmount += m.byteLength || 0; };
|
|
for (let i = 0; i < 100; i++) captureProc.process([[new Float32Array(240).fill(0.1)]]);
|
|
assert.equal(socket.bufferedAmount, 48000);
|
|
assert.equal(captureProc.pending, 100);
|
|
|
|
// Partial drain of 240 bytes (half a packet): must not drain packet
|
|
socket.bufferedAmount -= 240;
|
|
let drained = Math.max(0, c.connection.captureBytes - socket.bufferedAmount);
|
|
assert.equal(drained < c.connection.capturePackets[0], true);
|
|
|
|
// Drain 4800 bytes total (10 packets):
|
|
socket.bufferedAmount -= 4560;
|
|
for (let n = 0; n < 10 && c.connection.capturePackets.length; n++) {
|
|
const p = c.connection.capturePackets.shift();
|
|
c.connection.captureBytes -= p;
|
|
captureProc.port.onmessage?.({data: {type: 'accepted', bytes: p}});
|
|
}
|
|
assert.equal(c.connection.capturePackets.length, 90);
|
|
assert.equal(captureProc.pending, 90);
|
|
assert.equal(c.connection.captureBytes, 43200);
|
|
|
|
// Worklet can now admit 10 more packets
|
|
for (let i = 0; i < 10; i++) {
|
|
const ok = captureProc.process([[new Float32Array(240).fill(0.1)]]);
|
|
assert.equal(ok, true);
|
|
}
|
|
assert.equal(captureProc.pending, 100);
|
|
await c.cleanup();
|
|
}
|
|
|
|
// Delayed handoffs, terminal cleanup, and stale callbacks cannot mutate newer session
|
|
{
|
|
const e = environment();
|
|
let captureProc = null;
|
|
globalThis.AudioWorkletNode = class {
|
|
constructor(ctx, name) {
|
|
this.name = name;
|
|
if (name === 'rag-capture') {
|
|
captureProc = new processors['rag-capture']();
|
|
this.port = {
|
|
postMessage: m => captureProc.port.onmessage?.({data: m}),
|
|
onmessage: null
|
|
};
|
|
captureProc.port.postMessage = m => this.port.onmessage?.({data: m});
|
|
} else {
|
|
this.port = { postMessage: () => {}, onmessage: null };
|
|
}
|
|
}
|
|
connect() {} disconnect() {}
|
|
};
|
|
const c = e.client();
|
|
const pending = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending;
|
|
const oldConn = c.connection;
|
|
const oldSocket = c.socket;
|
|
oldSocket.bufferedAmount = 4800;
|
|
oldConn.capturePackets = [480, 480, 480];
|
|
oldConn.captureBytes = 1440;
|
|
await c.cleanup(oldConn);
|
|
assert.equal(oldConn.capturePackets.length, 0);
|
|
assert.equal(oldConn.captureBytes, 0);
|
|
assert.equal(oldConn.drainTimer, null);
|
|
assert.equal(c.connection, null);
|
|
|
|
// Stale callback on old connection is inert
|
|
oldConn.capturePackets.push(480);
|
|
oldConn.captureBytes = 480;
|
|
|
|
e.resetPermission();
|
|
const pending2 = c.connect(); await tick(); e.ready(); e.permission().resolve(e.media()); await pending2;
|
|
assert.notEqual(c.connection, oldConn);
|
|
assert.equal(c.connection.capturePackets.length, 0);
|
|
assert.equal(c.connection.captureBytes, 0);
|
|
await c.cleanup();
|
|
}
|
|
console.log('Capture bounds, 100/101 stalled socket, drain, delayed handoffs and cleanup passed');
|