Add cookie authentication, owned conversations, durable Live reservations, tool completion/replay fencing, revocation, and startup reconciliation. Introduce forward lifecycle/owner-chain migrations and the temporary Gemini adapter while preserving the existing OpenAI Realtime adapter. Include the executable audio client, regression coverage, configuration, API/database documentation, and recorded acceptance evidence. Validation: focused review suite 82 passed; Python/TOML parsing, JavaScript syntax, and whitespace checks passed. Full PostgreSQL/provider-free results are recorded in the repair report; real-provider/browser acceptance is unrun. Follow-up work remains for configurable OpenAI/Gemini selection, transport admission, authority diagnostics, playback message bounds, and client replay identity after ambiguous creation responses.
166 lines
10 KiB
JavaScript
166 lines
10 KiB
JavaScript
import fs from 'node:fs';
|
|
import assert from 'node:assert/strict';
|
|
import vm from 'node:vm';
|
|
export const {VoiceClient} = await import('data:text/javascript;base64,' + fs.readFileSync(new URL('../../examples/voice-client.js', import.meta.url)).toString('base64'));
|
|
export const tick = () => new Promise(resolve => setImmediate(resolve));
|
|
export const deferred = () => {let resolve, reject; const promise = new Promise((a,b) => {resolve=a;reject=b;}); return {promise,resolve,reject};};
|
|
export function environment() {
|
|
const sockets=[],contexts=[],tracks=[],requests=[];
|
|
let permission=deferred(),module=Promise.resolve(),flush=Promise.resolve();
|
|
globalThis.location={origin:'http://localhost:8000',protocol:'http:'};
|
|
Object.defineProperty(globalThis,'navigator',{configurable:true,value:{mediaDevices:{getUserMedia:()=>permission.promise}}});
|
|
globalThis.AudioContext=class {
|
|
constructor(){this.sampleRate=24000;this.state='running';this.destination={};this.audioWorklet={addModule:()=>module};contexts.push(this);}
|
|
async resume(){} async close(){this.state='closed';this.closed=(this.closed||0)+1;}
|
|
createMediaStreamSource(){return {connect(){},disconnect(){}};}
|
|
createGain(){return {gain:{value:1},connect(){},disconnect(){}};}
|
|
};
|
|
globalThis.AudioWorkletNode=class {
|
|
constructor(context,name){this.name=name;this.port={postMessage:m=>{
|
|
if(m.type==='flush') {
|
|
this.port.onmessage?.({data:{type:'progress',ref:'audio',played_ms:5}});
|
|
flush.then(()=>this.port.onmessage?.({data:{type:'flushed',id:m.id}}));
|
|
}
|
|
}};}
|
|
connect(){} disconnect(){}
|
|
};
|
|
globalThis.WebSocket=class {
|
|
static OPEN=1;
|
|
constructor(){this.readyState=1;this.bufferedAmount=0;this.sent=[];sockets.push(this);}
|
|
send(m){this.sent.push(m);}
|
|
close(){this.readyState=3;this.closes=(this.closes||0)+1;this.onclose?.();}
|
|
};
|
|
globalThis.fetch=async(path,options)=>{
|
|
requests.push({path,options});
|
|
return {status:200,ok:true,json:async()=>path.endsWith('/me')?{csrf_token:'valid',expires_at:'actual'}:{status:'closed'}};
|
|
};
|
|
const media=()=>{const track={stops:0,stop(){this.stops++;}};tracks.push(track);return {getTracks:()=>[track]};};
|
|
const client=()=>{const c=new VoiceClient(()=>{});c.session={session_id:'sid',stream_path:'/stream'};return c;};
|
|
const ready=()=>sockets.at(-1).onmessage({data:JSON.stringify({type:'session_ready',session_id:'sid',input_audio:{sample_rate:24000},output_audio:{sample_rate:24000}})});
|
|
return {sockets,contexts,tracks,requests,media,client,ready,
|
|
permission:()=>permission, resetPermission:()=>permission=deferred(),setModule:p=>module=p,setFlush:p=>flush=p};
|
|
}
|
|
export async function unitScenarios() {
|
|
// Permission resolves while cleanup is flushing, and after cleanup has completed.
|
|
for(const during of [false,true]) {
|
|
const e=environment(),c=e.client(),flush=deferred();
|
|
if(during)e.setFlush(flush.promise);
|
|
const connecting=c.connect().catch(e=>e);await tick();e.ready();await tick();
|
|
const cleaning=c.cleanup(),again=c.cleanup();assert.equal(cleaning,again);
|
|
if(!during)await cleaning;
|
|
const media=e.media();e.permission().resolve(media);await connecting;
|
|
flush.resolve();await cleaning;
|
|
assert.equal(e.tracks[0].stops,1);assert.equal(e.contexts[0].closed,1);assert.equal(e.sockets[0].closes,1);
|
|
}
|
|
// Preparation cancellation must not create a socket after addModule completes.
|
|
{
|
|
const e=environment(),c=e.client(),module=deferred();e.setModule(module.promise);
|
|
const pending=c.connect().catch(e=>e);await tick();await c.cleanup();module.resolve();await pending;
|
|
assert.equal(e.sockets.length,0);assert.equal(e.contexts[0].closed,1);
|
|
}
|
|
// A browser close promise cannot indefinitely retain cleanup ownership.
|
|
{
|
|
const e=environment(),c=e.client(),pending=c.connect().catch(e=>e);await tick();e.ready();await tick();
|
|
e.contexts[0].close=()=>new Promise(()=>{});
|
|
await c.cleanup();assert.equal(c.connection,null);assert.equal(e.sockets[0].closes,1);
|
|
e.permission().resolve(e.media());await pending;assert.equal(e.tracks[0].stops,1);
|
|
}
|
|
// Rejected acquisition releases context/socket without pretending capture exists.
|
|
{
|
|
const e=environment(),c=e.client(),pending=c.connect().catch(e=>e);await tick();e.ready();await tick();
|
|
e.permission().reject(new Error('permission denied'));assert.equal((await pending).message,'permission denied');
|
|
assert.equal(c.connection,null);assert.equal(e.contexts[0].closed,1);
|
|
}
|
|
// Old callbacks are inert after a new generation owns media.
|
|
{
|
|
const e=environment(),c=e.client(),pending=c.connect().catch(e=>e);await tick();e.ready();await tick();
|
|
const old=e.sockets[0],onclose=old.onclose,onmessage=old.onmessage;
|
|
await c.cleanup();e.permission().resolve(e.media());await pending;
|
|
e.resetPermission();const newer=c.connect();await tick();e.ready();e.permission().resolve(e.media());await newer;
|
|
onclose();onmessage({data:JSON.stringify({type:'error',error:{code:'LIVE_TRANSPORT_FAILED'}})});
|
|
assert.equal(c.socket,e.sockets[1]);assert.equal(c.socket.readyState,1);await c.cleanup();
|
|
}
|
|
// Nonterminal errors preserve authorized speech and later capture; fatal errors stop.
|
|
for(const code of ['SEARCH_TIMEOUT','SEARCH_FAILED','LIVE_BUFFER_OVERFLOW','CONTEXT_REVOKED']) {
|
|
const e=environment(),c=e.client(),events=[];c.onEvent=e=>events.push(e);
|
|
const pending=c.connect();await tick();e.ready();e.permission().resolve(e.media());await pending;
|
|
e.sockets[0].onmessage({data:JSON.stringify({type:'error',turn_ref:'turn',error:{code,retryable:false}})});await tick();
|
|
if(code.startsWith('SEARCH_')) {
|
|
assert.equal(c.ready,true);
|
|
e.sockets[0].onmessage({data:JSON.stringify({type:'transcript',role:'assistant',text:'explanation'})});
|
|
assert.equal(events.at(-1).text,'explanation');await c.cleanup();
|
|
} else assert.equal(c.connection,null);
|
|
}
|
|
// Logout must reach backend even when identity is expired/revoked or V04 fails.
|
|
for(const failure of ['expired','revoked','close','none']) {
|
|
const e=environment(),c=e.client();c.csrf='old';
|
|
globalThis.fetch=async(path,options)=> {
|
|
e.requests.push({path,options});
|
|
if(path.endsWith('/me')&&['expired','revoked'].includes(failure))return {status:401,ok:false,json:async()=>({error:{code:'AUTH_REQUIRED'}})};
|
|
if(path.endsWith('/close')&&failure==='close')throw new Error('lost close');
|
|
return {status:path.endsWith('/logout')?204:200,ok:true,json:async()=>({csrf_token:'fresh'})};
|
|
};
|
|
await c.logout();await c.logout();
|
|
assert.equal(e.requests.filter(r=>r.path.endsWith('/logout')).length,2);assert.equal(c.csrf,null);
|
|
if(failure==='none')assert.equal(e.requests.find(r=>r.path.endsWith('/logout')).options.headers['X-CSRF-Token'],'fresh');
|
|
}
|
|
// Explicit close sends final progress, then commits V04, then closes transport.
|
|
{
|
|
const e=environment(),c=e.client(),pending=c.connect();await tick();e.ready();e.permission().resolve(e.media());await pending;
|
|
const order=[],socket=c.socket;socket.send=m=>order.push(JSON.parse(m).type);socket.close=()=>order.push('transport-close');
|
|
globalThis.fetch=async(path)=>{order.push(path.endsWith('/close')?'V04':'me');return {status:200,ok:true,json:async()=>({csrf_token:'fresh'})};};
|
|
await c.close();assert.deepEqual(order,['playback_progress','me','V04','transport-close']);
|
|
}
|
|
}
|
|
if(process.argv[2]==='unit') {await unitScenarios();console.log('VoiceClient ownership, errors, logout and close scenarios passed');}
|
|
|
|
if(process.argv[2]==='asgi') {
|
|
const bridge=process.argv[3], nativeFetch=globalThis.fetch, e=environment();
|
|
const processors={}, played=deferred();
|
|
globalThis.AudioWorkletProcessor=class {constructor(){this.port={postMessage:m=>this.emit?.(m)};}};
|
|
globalThis.registerProcessor=(name,processor)=>processors[name]=processor;
|
|
vm.runInThisContext(fs.readFileSync(new URL('../../examples/voice-audio-worklet.js',import.meta.url),'utf8'));
|
|
globalThis.AudioWorkletNode=class {
|
|
constructor(context,name){
|
|
const processor=new processors[name]();
|
|
processor.emit=m=>{this.port.onmessage?.({data:m});if(m.type==='progress')played.resolve();};
|
|
this.port={postMessage:m=>{
|
|
processor.port.onmessage({data:m});
|
|
if(m.type==='pcm')processor.process([],[[new Float32Array(120)]]);
|
|
}};
|
|
}
|
|
connect(){} disconnect(){}
|
|
};
|
|
async function rpc(path,body) {
|
|
const response=await nativeFetch(bridge+path,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body||{})});
|
|
return response.json();
|
|
}
|
|
globalThis.fetch=async(path,options={})=>{
|
|
const r=await rpc('/http',{path,method:options.method||'GET',headers:options.headers,body:options.body});
|
|
return {status:r.status,ok:r.status<400,json:async()=>r.body};
|
|
};
|
|
globalThis.WebSocket=class {
|
|
static OPEN=1;
|
|
constructor(url) {
|
|
this.readyState=1;this.bufferedAmount=0;this.chain=Promise.resolve();this.polling=false;
|
|
rpc('/open',{path:new URL(url).pathname}).then(()=>{
|
|
this.timer=setInterval(async()=>{
|
|
if(this.polling||this.readyState!==1)return;
|
|
this.polling=true;
|
|
try {const messages=await rpc('/events');for(const data of messages){const payload=data.binary?Uint8Array.from(Buffer.from(data.binary,'base64')).buffer:JSON.stringify(data);this.onmessage?.({data:payload});}}
|
|
finally {this.polling=false;}
|
|
},5);
|
|
});
|
|
}
|
|
send(data) {const body=typeof data==='string'?{data}:{audio:Buffer.from(data).toString('base64')};this.chain=this.chain.then(()=>rpc('/send',body));}
|
|
close() {clearInterval(this.timer);this.readyState=3;this.done=this.chain.then(()=>rpc('/disconnect'));}
|
|
};
|
|
const c=new VoiceClient(()=>{});
|
|
await c.login('fixture','fixture-password');await c.reserve();e.permission().resolve(e.media());await c.connect();
|
|
const socket=c.socket;
|
|
if(process.argv[4]==='audio') {socket.send(new ArrayBuffer(9600));await socket.chain;await rpc('/generate');await played.promise;}
|
|
await c.close();await socket.done;
|
|
const state=await c.poll();assert.equal(state.status,'closed');assert.equal(state.close_reason,'user_requested');
|
|
console.log(JSON.stringify(state));
|
|
}
|