File size: 9,582 Bytes
08df380
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
<!doctype html>
<html><head><meta charset="utf-8"><title>Aiden — live duplex</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<style>
 :root{--bg:#0a0c10;--fg:#e9edf4;--dim:#6f7a8d;--acc:#5b8cff;--warn:#ffb454}
 body{margin:0;background:var(--bg);color:var(--fg);font:15px/1.55 system-ui,sans-serif}
 #app{max-width:780px;margin:0 auto;padding:28px 22px;display:flex;flex-direction:column;height:94vh}
 h1{font-size:15px;font-weight:600;letter-spacing:.02em;margin:0 0 4px}
 #hud{font:11.5px ui-monospace,Consolas,monospace;color:var(--dim);margin-bottom:14px}
 #log{flex:1;overflow:auto;padding-right:6px}
 .u{margin:0 0 10px;color:#9fb4d8}
 .a{margin:0 0 14px}
 .t{color:var(--dim);font:12px ui-monospace,Consolas,monospace;margin:12px 0 4px}
 .sys{color:var(--dim);font-size:12px;margin:8px 0}
 #row{display:flex;gap:10px;margin-top:14px}
 textarea{flex:1;height:52px;background:transparent;color:var(--fg);border:1px solid #1c222e;
   border-radius:13px;padding:12px 14px;font:inherit;resize:none;outline:none}
 button{background:transparent;color:var(--acc);border:1px solid #233050;border-radius:13px;
   padding:12px 16px;font:inherit;cursor:pointer}
 button.on{border-color:var(--warn);color:var(--warn)}
 #st{font-size:12px;color:var(--dim);margin-top:8px;display:flex;gap:14px;flex-wrap:wrap}
 .dot{display:inline-block;width:7px;height:7px;border-radius:50%;background:#2a3140;margin-right:6px}
 .dot.live{background:#3ecf8e}.dot.thk{background:var(--warn)}.dot.spk{background:var(--acc)}
 #vid{width:320px;height:320px;border-radius:14px;background:#0d1016;display:none;margin:0 0 14px}
</style></head><body><div id="app">
<h1>Aiden · live duplex</h1>
<div id="hud">Wear headphones. Try “search the web for…” or /search. The weather demo uses mock data.</div>
<canvas id="vid" width="512" height="512"></canvas>
<div id="log"></div>
<div id="row"><textarea id="t" placeholder="Type, or just talk"></textarea>
<button id="mic">Enable mic</button><button id="s">Send</button><button id="b" title="Stop Aiden">Stop</button></div>
<div id="st"><span><i class="dot" id="d"></i><span id="state">connecting</span></span>
<span id="lat"></span></div>
</div>
<script>
const log=document.getElementById('log'), hud=document.getElementById('hud'),
      vid=document.getElementById('vid'), vctx=vid.getContext('2d'),
      stEl=document.getElementById('state'), dot=document.getElementById('d'),
      latEl=document.getElementById('lat');
let ws=null, ac=null, playhead=0, chain=Promise.resolve(), stopped=0, current=0, retry=0, retryTimer=0;
const sources=new Map();
let micNode=null, micStream=null;

function add(c,t){const d=document.createElement('div');d.className=c;d.textContent=t;
  log.appendChild(d);log.scrollTop=log.scrollHeight;}
function toolEvent(m){
  if(m.name!=='web_search'){add('t',`tool ${m.stage} · ${m.name} ${JSON.stringify(m.args||m.result)}`);return;}
  if(m.stage==='pending'){add('t','Tavily searching · '+m.args.query);return;}
  if(m.result.status!=='ok'){add('t','Tavily · '+(m.result.reason||'No results'));return;}
  const row=document.createElement('div');row.className='t';row.textContent='Tavily sources:';
  for(const source of m.result.results){
    const url=new URL(source.url);
    if(!['https:','http:'].includes(url.protocol))continue;
    const a=document.createElement('a');a.href=url.href;a.textContent=source.title;
    a.target='_blank';a.rel='noopener noreferrer';a.style.color='var(--acc)';
    row.append(document.createElement('br'),a);
  }
  log.appendChild(row);log.scrollTop=log.scrollHeight;
}
function setState(s){stEl.textContent=s;dot.className='dot '+(s==='listening'?'live':
  s==='thinking'||s==='hold'?'thk':s==='speaking'?'spk':'');}
function ctx(){if(!ac)ac=new (window.AudioContext||window.webkitAudioContext)({sampleRate:16000});return ac;}
function send(data){if(ws?.readyState===1)ws.send(JSON.stringify(data));}
function stopAudio(epoch){
  stopped=Math.max(stopped,epoch);
  for(const [s, entry] of sources){if(entry.epoch>stopped)continue;
    clearTimeout(entry.timer);sources.delete(s);try{s.stop()}catch(e){}}
  playhead=0;
}

function drawJpeg(u8){
  vid.style.display='block';
  const blob=new Blob([u8],{type:'image/jpeg'});
  createImageBitmap(blob).then(b=>{vctx.drawImage(b,0,0,512,512);b.close();}).catch(()=>{});
}
function playPcm24(u8){
  if(u8.length<2)return;
  const c=ctx(); if(c.state!=='running')return;
  const pcm=u8.slice();
  const i16=new Int16Array(pcm.buffer,0,Math.floor(pcm.byteLength/2));
  const f=new Float32Array(i16.length);
  for(let i=0;i<i16.length;i++)f[i]=i16[i]/32768;
  const b=c.createBuffer(1,f.length,24000); b.copyToChannel(f,0);
  const s=c.createBufferSource(); s.buffer=b; s.connect(c.destination);
  const t=Math.max(c.currentTime+0.03,playhead); s.start(t); playhead=t+b.duration;
  sources.set(s,{epoch:current,timer:null});
  s.onended=()=>{sources.delete(s);s.disconnect();};
}
function handleBinary(buf){
  const u8=new Uint8Array(buf);
  if(u8.length<52)return;
  if(String.fromCharCode(u8[0],u8[1],u8[2],u8[3])!=='ADAV')return;
  const epoch=new DataView(u8.buffer,u8.byteOffset+4,4).getUint32(0,true);
  if(epoch<=stopped)return;
  const p=u8.subarray(8);
  if(String.fromCharCode(p[0],p[1],p[2],p[3])!=='AV01')return;
  const dv=new DataView(p.buffer,p.byteOffset,p.byteLength);
  const jl=dv.getUint32(24,true), pl=dv.getUint32(28,true);
  if(44+jl+pl>p.length)return;
  drawJpeg(p.subarray(44,44+jl));
  playPcm24(p.subarray(44+jl,44+jl+pl));
}
function connect(){
  ws=new WebSocket((location.protocol==='https:'?'wss://':'ws://')+location.host+'/ws');
  ws.binaryType='arraybuffer';
  ws.onopen=()=>{retry=0;setState('listening');};
  ws.onclose=()=>{
    stopAudio(current);micStream?.getTracks().forEach(t=>t.stop());setState('disconnected');
    // Recover by itself after a proxy idle timeout, laptop sleep or server restart,
    // instead of sitting on "disconnected" until the page is reloaded by hand.
    const wait=Math.min(15000,1000*Math.pow(2,retry++));
    clearTimeout(retryTimer);retryTimer=setTimeout(connect,wait);
  };
  ws.onerror=()=>{setState('error');};
  ws.onmessage=async ev=>{
    if(ev.data instanceof ArrayBuffer){handleBinary(ev.data);return;}
    const m=JSON.parse(ev.data);
    current=Math.max(current,m.epoch||0);
    if(m.type==='state'){setState(m.state);}
    else if(m.type==='user'){add('u','you: '+m.text);if(m.asr_ms)latEl.textContent='asr '+m.asr_ms+'ms';}
    else if(m.type==='ctrl'){hud.textContent=`ctrl ${m.control} · prefill ${m.prefill_ms}ms`;}
    else if(m.type==='latency'){latEl.textContent=`ttft ${m.ttft_ms}ms · ${m.decode_p50}ms/tok · ${m.tokens} tok · ${m.prompt_tokens} ctx`;}
    else if(m.type==='tool'){toolEvent(m);}
    else if(m.type==='floor'){
      const label=m.provisional?'Prosody suggestion: '+m.control:
        m.source==='acknowledgment only'?'Backchannel · no reply':m.control+' · '+m.source;
      add('sys',label+(m.ms!=null?' · '+m.ms+' ms':''));
    }
    else if(m.type==='error'){add('sys',m.message);}
    else if(m.type==='cancel'){stopAudio(m.epoch);add('sys','Playback stopped · '+m.reason);}
    else if(m.type==='audio'){chain=chain.then(()=>play(m)).catch(e=>add('sys','Audio: '+e.message));}
  };
}
async function play(m){
  if(m.epoch<=stopped)return;
  const c=ctx();const u=Uint8Array.from(atob(m.b64),ch=>ch.charCodeAt(0));
  const ab=await c.decodeAudioData(u.buffer);
  if(m.epoch<=stopped)return;
  if(c.state!=='running'){add('sys','Click Enable mic or Send to enable audio.');return;}
  const s=c.createBufferSource();s.buffer=ab;s.connect(c.destination);
  const t=Math.max(c.currentTime+0.035,playhead);s.start(t);playhead=t+ab.duration;
  const report=type=>send({type,seq:m.seq,epoch:m.epoch});
  const timer=setTimeout(()=>{if(m.epoch<=stopped)return;
    report('playing');add('a',m.text);setState('speaking');
  },Math.max(0,(t-c.currentTime)*1000));
  sources.set(s,{epoch:m.epoch,timer});
  s.onended=()=>{sources.delete(s);s.disconnect();if(m.epoch>stopped)report('played');};
}
async function startMic(){
  try{
    if(micStream)return;
    const micCtx=ctx();await micCtx.resume();
    micStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:true,
      noiseSuppression:true,autoGainControl:true,channelCount:1}});
    const src=micCtx.createMediaStreamSource(micStream);
    if(micCtx.sampleRate!==16000)throw new Error('16 kHz browser audio is required');
    micNode=micCtx.createScriptProcessor(512,1,1);
    micNode.onaudioprocess=e=>{
      const f=e.inputBuffer.getChannelData(0);
      const pcm=new Int16Array(f.length);
      for(let i=0;i<f.length;i++)pcm[i]=Math.max(-1,Math.min(1,f[i]))*32767;
      if(ws&&ws.readyState===1)ws.send(pcm.buffer);
    };
    src.connect(micNode);micNode.connect(micCtx.destination);
    document.getElementById('mic').textContent='Mic live';
  }catch(e){add('sys','mic blocked: '+e.message);}
}
document.getElementById('mic').onclick=startMic;
document.getElementById('s').onclick=async()=>{const t=document.getElementById('t');
  if(ws?.readyState!==1){add('sys','Server not connected.');return;}
  await ctx().resume();
  const v=t.value.trim();if(!v)return;t.value='';add('u','you: '+v);
  send({type:'text',text:v});};
document.getElementById('t').addEventListener('keydown',e=>{
  if(e.key==='Enter'&&!e.shiftKey){e.preventDefault();document.getElementById('s').click();}});
document.getElementById('b').onclick=()=>{stopAudio(current);send({type:'stop'});setState('listening');};
connect();
</script></body></html>