dsh-duet 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/README.md +19 -1
  2. package/assets/avatar/THREE-LICENSE.txt +21 -0
  3. package/assets/avatar/character.glb +0 -0
  4. package/assets/avatar/desktop/character.glb +0 -0
  5. package/assets/avatar/desktop/companion.mjs +18 -0
  6. package/assets/avatar/desktop/index.html +33 -0
  7. package/assets/avatar/desktop/manifest.json +10 -0
  8. package/assets/avatar/desktop/portrait.png +0 -0
  9. package/assets/avatar/desktop/renderer.mjs +4230 -0
  10. package/assets/avatar/portrait.png +0 -0
  11. package/assets/avatar/renderer.mjs +4230 -0
  12. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Info.plist +36 -0
  13. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/MacOS/duet-avatar +0 -0
  14. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Resources/duet companion.icns +0 -0
  15. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/_CodeSignature/CodeResources +128 -0
  16. package/desktop/bin/darwin-arm64/manifest.json +14 -0
  17. package/desktop/bin/win32-x64/duet-avatar.exe +0 -0
  18. package/desktop/bin/win32-x64/manifest.json +11 -0
  19. package/package.json +17 -5
  20. package/src/avatar/companion.html +33 -0
  21. package/src/avatar/companion.mjs +210 -0
  22. package/src/avatar/idle.mjs +9 -0
  23. package/src/avatar/lipsync.mjs +13 -0
  24. package/src/avatar/motion.mjs +93 -0
  25. package/src/avatar/renderer.mjs +90 -0
  26. package/src/avatar/surface.mjs +45 -0
  27. package/src/avatar/toolbar.mjs +49 -0
  28. package/src/client/audio.mjs +145 -10
  29. package/src/client/avatar-surfaces.mjs +83 -0
  30. package/src/client/avatar-tasks.mjs +68 -0
  31. package/src/client/avatar.mjs +218 -0
  32. package/src/client/browser.mjs +81 -33
  33. package/src/client/composer-bridge.mjs +5 -2
  34. package/src/client/composer.mjs +3 -3
  35. package/src/client/connection-hint.mjs +2 -1
  36. package/src/client/consent.mjs +3 -1
  37. package/src/client/controls-layout.mjs +21 -9
  38. package/src/client/entry.js +26 -3
  39. package/src/client/feedback.mjs +19 -4
  40. package/src/client/identity.mjs +2 -2
  41. package/src/client/input-effect.mjs +51 -0
  42. package/src/client/interactions.mjs +5 -1
  43. package/src/client/notice.mjs +1 -0
  44. package/src/client/rpc.mjs +23 -5
  45. package/src/client/settings.html +78 -4
  46. package/src/client/transport.mjs +2 -2
  47. package/src/client/tutorial-adapter.mjs +4 -4
  48. package/src/client/tutorial.mjs +5 -3
  49. package/src/host/assets.mjs +12 -0
  50. package/src/host/avatar-activity.mjs +24 -0
  51. package/src/host/avatar-assets.mjs +18 -0
  52. package/src/host/avatar.mjs +130 -0
  53. package/src/host/diagnostics.mjs +111 -7
  54. package/src/host/feedback-files.mjs +5 -1
  55. package/src/host/plugin.mjs +67 -4
  56. package/src/host/proxy.mjs +16 -6
  57. package/src/host/settings-migration.mjs +2 -1
  58. package/src/host/settings.mjs +19 -4
  59. package/src/host/stop-task.mjs +37 -0
  60. package/src/shared/avatar-activity.mjs +33 -0
  61. package/src/shared/avatar-menu-ui.mjs +85 -0
  62. package/src/shared/avatar-menu.mjs +83 -0
  63. package/src/shared/avatar-surface.mjs +24 -0
  64. package/src/shared/avatar-ui.mjs +91 -0
  65. package/src/shared/avatar.mjs +125 -0
  66. package/src/shared/nickname.mjs +13 -0
  67. package/src/shared/state.mjs +1 -1
@@ -0,0 +1,90 @@
1
+ import * as THREE from 'three'
2
+ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js'
3
+ import { IdleDirector, Spring } from './idle.mjs'
4
+ import { LipSyncFilter } from './lipsync.mjs'
5
+ import { MotionDirector, gesturePose } from './motion.mjs'
6
+
7
+ /** Shared real-time GLB renderer. Never opens a microphone or replays audio. */
8
+ export function mountAvatarRenderer(root, { modelURL, onError = () => {}, onReady = () => {} }) {
9
+ const renderer = new THREE.WebGLRenderer({antialias:true,alpha:true,powerPreference:'low-power'})
10
+ renderer.setPixelRatio(Math.min(1.75, devicePixelRatio || 1)); renderer.setClearColor(0,0)
11
+ renderer.outputColorSpace=THREE.SRGBColorSpace;renderer.toneMapping=THREE.AgXToneMapping
12
+ renderer.domElement.style.cssText='display:block;width:100%;height:100%';root.append(renderer.domElement)
13
+ const scene=new THREE.Scene(),camera=new THREE.OrthographicCamera(-1.28,1.28,1.28,-1.28,.1,100)
14
+ camera.position.set(1,5.85,18);camera.lookAt(0,5.39,-.02)
15
+ const resize=()=>{const w=Math.max(1,root.clientWidth),h=Math.max(1,root.clientHeight),a=w/h,v=Math.max(2.56,2.35/a);renderer.setSize(w,h,false);Object.assign(camera,{left:-v*a/2,right:v*a/2,top:v/2,bottom:-v/2});camera.updateProjectionMatrix()}
16
+ const observer=new ResizeObserver(resize);observer.observe(root);resize()
17
+ const idle=new IdleDirector(),lips=new LipSyncFilter(),mouths=[],eyes=[],hair=[],rests=[]
18
+ const springs=Object.fromEntries(['L','C','R'].map(c=>[c,[9,5.5,3.4,2.3].map(w=>({n:new Spring(w,.66),r:new Spring(w,.62),y:new Spring(w,.67)}))]))
19
+ let model,dead=false,frame,last=performance.now(),start=last,lastInput=0
20
+ let input={rms:0,viseme:'A',text:'',utterance:''}
21
+ const motion=new MotionDirector()
22
+ const morph=(o,key,value)=>{const i=o.morphTargetDictionary?.[key];if(i!==undefined)o.morphTargetInfluences[i]=value}
23
+ const release=tree=>{const textures=new Set(),materials=new Set(),geometries=new Set();tree?.traverse(o=>{if(o.geometry)geometries.add(o.geometry);for(const m of [o.material].flat().filter(Boolean)){materials.add(m);for(const v of Object.values(m))if(v?.isTexture)textures.add(v)}});for(const v of [...textures,...materials,...geometries])v.dispose()}
24
+ new GLTFLoader().load(modelURL,gltf=>{
25
+ if(dead){release(gltf.scene);return}
26
+ model=gltf.scene;model.updateMatrixWorld(true);const names=new Map()
27
+ model.traverse(o=>{
28
+ const a=gltf.parser.associations.get(o),name=a?.nodes!==undefined?gltf.parser.json.nodes[a.nodes].name:o.name
29
+ names.set(name,o);if(!o.isMesh)return;o.frustumCulled=false
30
+ for(const m of [o.material].flat()){
31
+ m.toneMapped=false
32
+ if(name?.startsWith('Hair V7')){m.transparent=true;m.alphaTest=.015;m.depthWrite=false;m.forceSinglePass=true}
33
+ else if(name?.startsWith('Eye |')){
34
+ // Keep the painted lash texture's soft edge. Alpha-to-coverage can
35
+ // reduce face opacity on a transparent canvas; blending preserves it.
36
+ m.transparent=true;m.alphaTest=.015;m.depthWrite=false;m.forceSinglePass=true
37
+ // Paint eyes over opaque skin, then let the transparent fringe cover
38
+ // them. Do not let transparent-object sorting flip this on head turns.
39
+ o.renderOrder=-1
40
+ }
41
+ else if(m.transparent){m.alphaTest=.28;m.depthWrite=true;m.transparent=false}
42
+ m.needsUpdate=true
43
+ }
44
+ if(name?.startsWith('Mouth |'))mouths.push(o)
45
+ if(name?.startsWith('Eye |'))eyes.push(o)
46
+ })
47
+ for(const name of ['RIG | 颈部转动支点','V1_NeckHead']){const o=names.get(name);if(o)rests.push({o,q:o.quaternion.clone(),parent:o.parent.getWorldQuaternion(new THREE.Quaternion())})}
48
+ for(const col of ['L','C','R'])for(let i=0;i<4;i++){const o=names.get(`Flow ${col} ${i}`);if(o)hair.push({o,col,i,q:o.quaternion.clone()})}
49
+ scene.add(model);onReady()
50
+ },undefined,()=>{if(!dead)onError('3D 形象加载失败')})
51
+ const animate=now=>{
52
+ if(dead)return
53
+ frame=requestAnimationFrame(animate)
54
+ if(document.hidden){last=now;return}
55
+ if(now-last<1000/(input.rms>.01?40:24))return
56
+ const dt=Math.min(.1,(now-last)/1000);last=now
57
+ if(now-lastInput>500)input={...input,rms:0}
58
+ const weights=lips.step(input.rms,input.viseme,dt,input.rms>0),t=(now-start)/1000,p=idle.sample(t)
59
+ const action=motion.sample(input,now),gesture=action.kind,e=action.envelope
60
+ root.dataset.duetGesture=gesture;root.dataset.duetGestureSequence=String(action.sequence)
61
+ const pose=gesturePose(action)
62
+ root.dataset.duetMotionPolicy='independent'
63
+ root.dataset.duetGesturePose=JSON.stringify(pose)
64
+ // Head gestures share one scheduler; do not layer a second independent
65
+ // random head track over semantic gestures or bypass repetition cooldown.
66
+ const nod=pose.nod,yaw=pose.yaw,roll=pose.roll
67
+ const q=new THREE.Quaternion().setFromEuler(new THREE.Euler(nod,yaw,-roll,'XYZ'))
68
+ for(const r of rests)r.o.quaternion.copy(r.parent).invert().multiply(q).multiply(r.parent).multiply(r.q)
69
+ if(model)model.position.y=p.breath*.003
70
+ for(const o of eyes){morph(o,'V1_Blink',p.blink);morph(o,'Gaze slightly right',p.gaze)}
71
+ for(const o of mouths){for(const k of ['A','I','U','E','O'])morph(o,k,weights[k]);morph(o,'Open',0);const smile=p.smile*(1-lips.envelope*.8);morph(o,'Smile',gesture==='laugh'?smile+(.65-smile)*e:smile)}
72
+ const values={}
73
+ for(const col of ['L','C','R']){let prev={n:nod,r:roll,y:yaw};values[col]=springs[col].map(s=>{const v={n:s.n.step(nod,dt),r:s.r.step(roll,dt),y:s.y.step(yaw,dt)};const d={n:v.n-prev.n,r:v.r-prev.r,y:v.y-prev.y};prev=v;return d})}
74
+ for(const h of hair){const d=values[h.col][h.i];h.o.quaternion.copy(h.q).multiply(new THREE.Quaternion().setFromEuler(new THREE.Euler(THREE.MathUtils.clamp(d.n,-.045,.045)*.45,THREE.MathUtils.clamp(d.y,-.06,.06)*.3,THREE.MathUtils.clamp(d.r,-.045,.045)*.75)))}
75
+ renderer.render(scene,camera)
76
+ }
77
+ frame=requestAnimationFrame(animate)
78
+ const hitCanvas=document.createElement('canvas');hitCanvas.width=48;hitCanvas.height=64
79
+ const hitContext=hitCanvas.getContext('2d',{willReadFrequently:true})
80
+ return {
81
+ update(value){input=value;lastInput=performance.now()},
82
+ hitMask(){
83
+ // Redraw immediately: preserveDrawingBuffer is intentionally disabled.
84
+ renderer.render(scene,camera);hitContext.clearRect(0,0,48,64);hitContext.drawImage(renderer.domElement,0,0,48,64)
85
+ const rgba=hitContext.getImageData(0,0,48,64).data
86
+ return Array.from({length:48*64},(_,i)=>rgba[i*4+3]>24?1:0)
87
+ },
88
+ dispose(){dead=true;cancelAnimationFrame(frame);observer.disconnect();release(model);renderer.dispose();renderer.forceContextLoss();renderer.domElement.remove()},
89
+ }
90
+ }
@@ -0,0 +1,45 @@
1
+ import {avatarSurface} from '../shared/avatar-surface.mjs'
2
+ /** No innerHTML, URLs, eval or native side effects from projected content. */
3
+ export function mountCompanionSurface(root,{send,changed}) {
4
+ let current=null,key='',elements=new Map()
5
+ return {update(value){
6
+ const panel=avatarSurface(value).panel,next=JSON.stringify(panel)
7
+ if(next===key)return
8
+ const focused=root.contains(document.activeElement)?document.activeElement.dataset.surfaceAction:null,scroll=root.scrollTop
9
+ const samePanel=current?.id===panel?.id
10
+ key=next;current=panel;root.hidden=!panel
11
+ const desired=[],nextElements=new Map()
12
+ const element=(id,tag)=>{
13
+ const old=samePanel?elements.get(id):null
14
+ const e=old?.tagName.toLowerCase()===tag?old:document.createElement(tag)
15
+ nextElements.set(id,e);desired.push(e);return e
16
+ }
17
+ if(panel) {
18
+ if(panel.nodes.some(n=>n.gesture)){
19
+ const action=panel.nodes.find(n=>n.gesture&&n.kind==='button')
20
+ const note=element('gesture','p');note.className='gesture-note';note.textContent=action?.text==='开始教学'?'请回到 DSH,点击“开始教学”。':'请回到 DSH,点击“启动音频播放”。'
21
+ }
22
+ for(const [index,n] of panel.nodes.entries()){
23
+ const tag=n.kind==='break'?'br':n.kind==='heading'?'h3':n.kind==='button'?'button':n.kind==='checkbox'?'input':'span'
24
+ const e=element(n.action||'node'+index,tag)
25
+ if(e.textContent!==n.text)e.textContent=n.text
26
+ if(n.kind==='checkbox'){e.type='checkbox';e.checked=n.checked}
27
+ if(n.kind==='button'||n.kind==='checkbox'){
28
+ e.dataset.surfaceAction=n.action
29
+ if(n.kind==='button')e.type='button'
30
+ e.disabled=n.disabled||n.gesture
31
+ if(n.label)e.setAttribute('aria-label',n.label);else e.removeAttribute('aria-label')
32
+ const callback=()=>{if(current!==panel||e.disabled)return;send({type:'surface_action',id:panel.id,revision:panel.revision,action:n.action,checked:e.checked===true})}
33
+ if(n.kind==='checkbox')e.onchange=callback;else e.onclick=callback
34
+ }
35
+ }
36
+ }
37
+ // Do not detach unchanged buttons between pointerdown and pointerup.
38
+ desired.forEach((e,i)=>{if(root.children[i]!==e)root.insertBefore(e,root.children[i]||null)})
39
+ while(root.children.length>desired.length)root.lastElementChild.remove()
40
+ elements=nextElements
41
+ if(focused){const node=elements.get(focused);if(node&&!node.disabled&&document.activeElement!==node)node.focus({preventScroll:true})}
42
+ root.scrollTop=scroll
43
+ changed(Boolean(panel),panel?.target)
44
+ }}
45
+ }
@@ -0,0 +1,49 @@
1
+ /** Presentation state only. Native mouse passthrough uses the same current regions. */
2
+ export function maskContains(mask,rect,x,y){
3
+ const [ax,ay,w,h]=rect
4
+ if(!w||!h||x<ax||y<ay||x>=ax+w||y>=ay+h||mask?.length!==48*64)return false
5
+ return mask[Math.floor((y-ay)/h*64)*48+Math.floor((x-ax)/w*48)]===1
6
+ }
7
+ export function mountAvatarToolbar({tools,avatar,hitTest=()=>false,onChange=()=>{}}){
8
+ let dead=false,revealed=false,interactive=false,confirming=false,pointer={x:-1,y:-1,overAvatar:false},leaveTimer,finishTimer
9
+ const bounds=node=>{const r=node.getBoundingClientRect();return[r.x,r.y,r.width,r.height]}
10
+ const inside=([x,y,w,h])=>pointer.x>=x&&pointer.y>=y&&pointer.x<x+w&&pointer.y<y+h
11
+ const bridge=()=>{const a=avatar.getBoundingClientRect(),t=tools.getBoundingClientRect();return[Math.min(a.left,t.left),a.bottom-2,Math.max(a.right,t.right)-Math.min(a.left,t.left),Math.max(0,t.top-a.bottom)+4]}
12
+ const publish=()=>{tools.dataset.revealed=String(revealed);tools.dataset.interactive=String(interactive);tools.dataset.confirming=String(confirming);onChange()}
13
+ const wants=()=>confirming||(tools.dataset.keyboard==='true'&&Boolean(tools.querySelector(':focus-visible')))||pointer.overAvatar||
14
+ (interactive&&(inside(bounds(tools))||inside(bridge())))
15
+ const sync=()=>{
16
+ if(dead)return
17
+ if(wants()){
18
+ clearTimeout(leaveTimer);leaveTimer=null;clearTimeout(finishTimer);finishTimer=null
19
+ if(!revealed||!interactive){revealed=true;interactive=true;publish()}
20
+ }else if(revealed&&!leaveTimer){
21
+ leaveTimer=setTimeout(()=>{
22
+ leaveTimer=null;if(dead||wants())return sync()
23
+ revealed=false;publish()
24
+ finishTimer=setTimeout(()=>{finishTimer=null;if(dead)return;if(wants())return sync();interactive=false;publish()},500)
25
+ },180)
26
+ }
27
+ }
28
+ const update=value=>{if(dead)return;pointer={x:Number.isFinite(value.x)?value.x:-1,y:Number.isFinite(value.y)?value.y:-1,overAvatar:value.overAvatar===true};avatar.style.pointerEvents=pointer.overAvatar?'auto':'none';sync()}
29
+ const move=e=>update({x:e.clientX,y:e.clientY,overAvatar:hitTest(e.clientX,e.clientY)})
30
+ const leave=()=>update({x:-1,y:-1,overAvatar:false})
31
+ const focus=()=>queueMicrotask(sync)
32
+ const keyboard=e=>{if(!['Shift','Control','Alt','Meta'].includes(e.key))tools.dataset.keyboard='true';focus()}
33
+ const mouse=()=>{tools.dataset.keyboard='false';focus()}
34
+ const blur=()=>{tools.dataset.keyboard='false';leave()}
35
+ const listen=(node,type,fn)=>{node.addEventListener(type,fn);return()=>node.removeEventListener(type,fn)}
36
+ const remove=[listen(document,'pointermove',move),listen(document,'pointerleave',leave),
37
+ listen(document,'focusin',focus),listen(document,'focusout',focus),listen(document,'keydown',keyboard),
38
+ listen(document,'pointerdown',mouse),listen(window,'blur',blur)]
39
+ // opacity (not visibility/display) preserves keyboard tab access while hidden.
40
+ tools.dataset.keyboard='false';tools.dataset.revealed='false';tools.dataset.interactive='false';tools.dataset.confirming='false';avatar.style.pointerEvents='none'
41
+ return{
42
+ pointer:update,
43
+ refresh(){sync()},
44
+ setConfirmation(value){confirming=Boolean(value);publish();sync()},
45
+ get interactive(){return interactive},
46
+ regions(){return interactive?[bounds(tools),bridge()]:[]},
47
+ dispose(){dead=true;clearTimeout(leaveTimer);clearTimeout(finishTimer);remove.forEach(fn=>fn())},
48
+ }
49
+ }
@@ -1,4 +1,7 @@
1
- import { microphoneConstraints } from './microphone.mjs?v=0.1.9'
1
+ import { microphoneConstraints } from './microphone.mjs?v=0.2.0'
2
+ import { captionCue, captionAt, AudioCaptionTimeline } from '../shared/avatar.mjs'
3
+
4
+ export const AUDIO_STOP_PROTOCOL = 'audio_stop_candidates_v1'
2
5
 
3
6
  /** Browser-owned microphone and PCM playback. No microphone is requested in tts_only. */
4
7
  export class DuetAudio {
@@ -13,6 +16,7 @@ export class DuetAudio {
13
16
  this.nextTime = 0
14
17
  this.tones = new Set()
15
18
  this.captureCleanup = null
19
+ this.captionTimeline = new AudioCaptionTimeline()
16
20
  }
17
21
 
18
22
  prepare() {
@@ -97,9 +101,20 @@ export class DuetAudio {
97
101
  report({event:'browser.capture_started'})
98
102
  }
99
103
 
100
- event(event, send) {
104
+ event(event, send, present = () => {}) {
101
105
  const key = `${event.response_id}:${event.generation}`
102
- if (event.type === 'output_audio_buffer.clear') { this.cleared.add(key); this.clear(send); return }
106
+ if (['response.output_text.delta','response.output_text.done'].includes(event.type)
107
+ && Object.hasOwn(event,'audio_sample_end')) {
108
+ if (this.cleared.has(key)) return true
109
+ this.captionTimeline.ingestDelta(key,event,present)
110
+ const response=this.responses.get(key)
111
+ if(response && this.context)this.captionTimeline.text(key,this.playedAt(response,this.context.currentTime))
112
+ if (this.avatarCaption?.key === key) {
113
+ this.avatarCaption.text = this.captionTimeline.text(key,this.avatarCaption.played) ?? this.avatarCaption.text
114
+ }
115
+ return true
116
+ }
117
+ if (event.type === 'output_audio_buffer.clear') { this.interrupt(event, send); return }
103
118
  if (event.type === 'response.output_audio.done') {
104
119
  const response = this.responses.get(key)
105
120
  if (response) { response.done = true; this.progress(send) }
@@ -115,44 +130,164 @@ export class DuetAudio {
115
130
  for (let i = 0; i < pcm.length; i++) data[i] = pcm[i] / 32768
116
131
  const node = this.context.createBufferSource()
117
132
  node.buffer = buffer
118
- node.connect(this.context.destination)
133
+ const gain = this.context.createGain()
134
+ node.connect(gain)
135
+ gain.connect(this.avatarOutput())
119
136
  const start = Math.max(this.context.currentTime + 0.04, this.nextTime)
120
137
  this.nextTime = start + pcm.length / rate
121
- const response = this.responses.get(key) || { response_id: event.response_id, generation: event.generation, played: 0, basePlayed: 0, chunks: [] }
122
- response.chunks.push({ start, samples: pcm.length, rate })
138
+ const response = this.responses.get(key) || { response_id: event.response_id, generation: event.generation, played: 0, basePlayed: 0, received: 0, chunks: [] }
139
+ const chunk = { start, samples: pcm.length, rate, sampleStart: response.received, node, gain, ended: false }
140
+ chunk.caption = captionCue(response, event)
141
+ response.received += pcm.length
142
+ response.chunks.push(chunk)
123
143
  this.responses.set(key, response)
124
144
  this.nodes.add(node)
125
- node.onended = () => { this.nodes.delete(node); node.disconnect(); this.progress(send) }
145
+ node.onended = () => {
146
+ const until = Math.min(this.context.currentTime, response.stopAt ?? Infinity)
147
+ if (until > chunk.start) {
148
+ const played=this.playedAt(response,until)
149
+ this.avatarCaption = { text: this.captionTimeline.text(key,played) ?? captionAt(chunk.caption, (until-chunk.start)*rate/pcm.length), at: performance.now(), key, played }
150
+ }
151
+ chunk.ended = true
152
+ this.nodes.delete(node); node.disconnect(); gain.disconnect()
153
+ this.progress(send)
154
+ this.finishStop(key, response, send)
155
+ }
126
156
  node.start(start)
127
157
  }
128
158
 
159
+ playedAt(r, time) {
160
+ const until = Math.min(time, r.stopAt ?? Infinity)
161
+ return r.chunks.reduce((n, c) => n + Math.min(c.samples, Math.max(0,
162
+ Math.floor((until - c.start) * c.rate + 1e-6))), r.basePlayed)
163
+ }
164
+
129
165
  progress(send) {
130
166
  if (!this.context) return
131
167
  for (const [key, r] of this.responses) {
132
- const played = r.chunks.reduce((n, c) => n + Math.min(c.samples, Math.max(0, Math.floor((this.context.currentTime - c.start) * c.rate))), r.basePlayed)
168
+ const played = this.playedAt(r, this.context.currentTime)
169
+ this.captionTimeline.text(key,played)
133
170
  if (played > r.played) {
134
171
  r.played = played
135
172
  send({ type: 'output_audio_buffer.playback_progress', response_id: r.response_id, generation: r.generation, played_samples: played })
136
173
  }
137
- while (r.chunks.length && this.context.currentTime >= r.chunks[0].start + r.chunks[0].samples / r.chunks[0].rate) {
174
+ while (!r.stopping && r.chunks.length && this.context.currentTime >= r.chunks[0].start + r.chunks[0].samples / r.chunks[0].rate) {
138
175
  r.basePlayed += r.chunks.shift().samples
139
176
  }
140
- if (r.done && !r.chunks.length) this.responses.delete(key)
177
+ if (r.done && !r.stopping && !r.chunks.length) this.responses.delete(key)
141
178
  }
142
179
  }
143
180
 
144
181
  playing() { return this.nodes.size > 0 }
145
182
 
183
+ avatarOutput() {
184
+ if (!this.context?.createAnalyser) return this.context.destination
185
+ if (!this.avatarAnalyser) {
186
+ this.avatarAnalyser = this.context.createAnalyser()
187
+ this.avatarAnalyser.fftSize = 1024
188
+ this.avatarAnalyser.smoothingTimeConstant = .6
189
+ this.avatarAnalyser.connect(this.context.destination)
190
+ this.avatarWave = new Float32Array(1024)
191
+ this.avatarFrequency = new Uint8Array(512)
192
+ }
193
+ return this.avatarAnalyser
194
+ }
195
+
196
+ /** Meter actual post-gain playback, not network arrival or microphone input. */
197
+ avatarSample() {
198
+ const silent = {rms:0,viseme:'A',utterance:'',text:performance.now()-(this.avatarCaption?.at ?? -Infinity)<2000?this.avatarCaption.text:''}
199
+ if (!this.context || this.context.state !== 'running' || !this.avatarAnalyser) return silent
200
+ const now = this.context.currentTime
201
+ let utterance = '', response_id = '', text = ''
202
+ for (const [key,r] of this.responses) {
203
+ if (now >= (r.stopAt ?? Infinity)) continue
204
+ const chunk=r.chunks.find(c => !c.ended && now >= c.start && now < c.start + c.samples/c.rate)
205
+ if (chunk) {
206
+ utterance=key;response_id=r.response_id
207
+ const played=this.playedAt(r,now)
208
+ text=this.captionTimeline.text(key,played) ?? captionAt(chunk.caption,(now-chunk.start)*chunk.rate/chunk.samples)
209
+ this.avatarCaption={text,at:performance.now(),key,played}
210
+ break
211
+ }
212
+ }
213
+ if (!utterance) return silent
214
+ this.avatarAnalyser.getFloatTimeDomainData(this.avatarWave)
215
+ this.avatarAnalyser.getByteFrequencyData(this.avatarFrequency)
216
+ let square=0;for(const v of this.avatarWave)square+=v*v
217
+ const rms=Math.min(1,Math.sqrt(square/this.avatarWave.length))
218
+ const band=(lo,hi)=>{let sum=0,n=0;const hz=this.context.sampleRate/1024;for(let i=Math.ceil(lo/hz);i<Math.min(512,hi/hz);i++){sum+=this.avatarFrequency[i];n++}return sum/Math.max(1,n)}
219
+ const low=band(160,600),mid=band(650,1250),high=band(1500,3200)
220
+ const viseme=high>mid*1.16?'I':mid>low*1.13?'E':low>mid*1.3?(high>mid*.85?'O':'U'):'A'
221
+ return {rms,viseme,utterance,response_id,text}
222
+ }
223
+
224
+ interrupt(event, send) {
225
+ const key = `${event.response_id}:${event.generation}`
226
+ if (this.cleared.has(key)) return
227
+ this.cleared.add(key)
228
+ const r = this.responses.get(key)
229
+ if (!r || !this.context) return
230
+ const now = this.context.currentTime, played = this.playedAt(r, now)
231
+ const smooth = event.audio_stop_protocol === AUDIO_STOP_PROTOCOL
232
+ const bound = Number.isFinite(event.max_wait_ms) ? Math.max(0, Math.min(300, event.max_wait_ms)) / 1000 : 0.3
233
+ const fadeMs = Number.isFinite(event.fade_ms) ? Math.max(0, Math.min(12, event.fade_ms)) : 12
234
+ const fade = smooth ? Math.min(fadeMs / 1000, bound) : 0
235
+ let cut = now + fade, selected = null, reason = 'immediate_fallback'
236
+ const candidates = event.stop_candidates_samples
237
+ const valid = smooth && Array.isArray(candidates) && candidates.length <= 3 &&
238
+ candidates.every((v, i) => Number.isSafeInteger(v) && v >= 0 && v <= r.received && (!i || v > candidates[i - 1]))
239
+ if (valid) {
240
+ for (const sample of candidates) {
241
+ if (sample <= played) continue
242
+ const c = r.chunks.find(c => c.sampleStart < sample && sample <= c.sampleStart + c.samples)
243
+ if (!c) continue
244
+ const when = c.start + (sample - c.sampleStart) / c.rate
245
+ if (when > now && when <= now + bound) { cut = when; selected = sample; reason = 'candidate'; break }
246
+ }
247
+ }
248
+ r.stopping = true; r.stopAt = cut; r.stopReason = reason; r.selectedStop = selected
249
+ for (const c of r.chunks) {
250
+ if (c.ended) continue
251
+ const end = c.start + c.samples / c.rate
252
+ const fadeStart = Math.max(now, cut - fade)
253
+ if (end > fadeStart) {
254
+ c.gain.gain.setValueAtTime(1, fadeStart)
255
+ c.gain.gain.linearRampToValueAtTime(0, cut)
256
+ }
257
+ if (end >= cut) c.node.stop(c.start >= cut ? now : cut)
258
+ }
259
+ // Only the interrupted response is shortened. A newer response keeps its queue.
260
+ this.nextTime = Math.max(now, ...[...this.responses.values()].flatMap(response =>
261
+ response.chunks.filter(c => !c.ended).map(c => Math.min(
262
+ c.start + c.samples / c.rate, response.stopAt ?? Infinity))))
263
+ this.finishStop(key, r, send)
264
+ }
265
+
266
+ finishStop(key, r, send) {
267
+ if (!r.stopping || r.acknowledged || r.chunks.some(c => !c.ended)) return
268
+ r.acknowledged = true
269
+ const played = this.playedAt(r, this.context.currentTime)
270
+ this.captionTimeline.text(key,played)
271
+ this.captionTimeline.discardPending(key)
272
+ send({type:'output_audio_buffer.cleared', response_id:r.response_id, generation:r.generation,
273
+ played_samples:played, audio_stop_protocol:AUDIO_STOP_PROTOCOL,
274
+ selected_stop_sample:r.selectedStop, stop_reason:r.stopReason})
275
+ this.responses.delete(key)
276
+ }
277
+
146
278
  clear(send = () => {}) {
147
279
  this.progress(send)
148
280
  for (const [key, r] of this.responses) {
149
281
  this.cleared.add(key)
150
282
  send({ type: 'output_audio_buffer.cleared', response_id: r.response_id, generation: r.generation, played_samples: r.played })
151
283
  }
284
+ for (const r of this.responses.values()) for (const c of r.chunks) c.gain.disconnect()
152
285
  for (const node of this.nodes) { node.onended = null; node.stop(); node.disconnect() }
153
286
  this.nodes.clear()
154
287
  this.responses.clear()
155
288
  this.nextTime = 0
289
+ this.avatarCaption = null
290
+ this.captionTimeline.clear()
156
291
  }
157
292
 
158
293
  stop() {
@@ -0,0 +1,83 @@
1
+ import {avatarSurface,avatarSurfaceAction} from '../shared/avatar-surface.mjs'
2
+
3
+ /** Only opt-in duet panels are projected. The original page remains the state owner. */
4
+ export function mountAvatarSurfaces({avatar,canActivate=()=>false}) {
5
+ let current=null,serial=0,actionSerial=0,last='',semantic='',disposed=false,nativeBefore=false
6
+ const ids=new WeakMap(),actionIds=new WeakMap(),actions=new Map(),moved=new Map()
7
+ const style=document.createElement('style')
8
+ style.textContent='[data-duet-surface-native]{visibility:hidden!important;pointer-events:none!important}[data-duet-surface-positioned]{position:fixed!important;left:var(--duet-surface-x)!important;top:var(--duet-surface-y)!important;margin:0!important;max-height:calc(100vh - 24px)!important;overflow:auto!important;box-sizing:border-box!important}'
9
+ document.head.append(style)
10
+ const restore=node=>{node.removeAttribute('data-duet-surface-native');node.removeAttribute('data-duet-surface-positioned');node.style.removeProperty('--duet-surface-x');node.style.removeProperty('--duet-surface-y');moved.delete(node)}
11
+ function snapshot(panel) {
12
+ const nodes=[];actions.clear()
13
+ const walk=node=>{
14
+ if(nodes.length>=160)return
15
+ if(node.nodeType===3){if(node.textContent.trim())nodes.push({kind:'text',text:node.textContent.slice(0,4000)});return}
16
+ if(node.nodeType!==1||node.hidden||node.getAttribute('aria-hidden')==='true'||['SVG','SCRIPT','STYLE'].includes(node.tagName))return
17
+ if(node.matches('button,input[type=checkbox],summary')) {
18
+ let action=actionIds.get(node);if(!action){action=`a${++actionSerial}`;actionIds.set(node,action)}
19
+ const gesture=node.hasAttribute('data-duet-user-gesture')&&!canActivate()
20
+ actions.set(action,node)
21
+ nodes.push({kind:node.matches('input')?'checkbox':'button',text:node.matches('input')?'':node.textContent.slice(0,4000),action,disabled:node.disabled===true,checked:node.checked===true,gesture,label:node.getAttribute('aria-label')||node.closest('label')?.textContent.slice(0,100)||''})
22
+ return
23
+ }
24
+ if(/^H[1-6]$/.test(node.tagName)){nodes.push({kind:'heading',text:node.textContent.slice(0,4000)});return}
25
+ if(node.tagName==='BR'){nodes.push({kind:'break',text:''});return}
26
+ for(const child of node.childNodes)walk(child)
27
+ if(['P','DIV','LABEL','FOOTER'].includes(node.tagName))nodes.push({kind:'break',text:''})
28
+ }
29
+ walk(panel)
30
+ return nodes.slice(0,160)
31
+ }
32
+ function sync() {
33
+ if(disposed)return
34
+ const view=avatar()?.presentation?.()||{},native=view.native===true
35
+ // Sidebar branding uses data-duet-surface too; only explicit numeric panels are eligible.
36
+ const candidates=[...document.querySelectorAll('[data-duet-avatar-surface]')].filter(n=>/^\d{1,3}$/.test(n.dataset.duetAvatarSurface)&&n.dataset.duetSurfaceOrigin!=='page'&&!n.hidden&&n.isConnected&&(n.tagName!=='DIALOG'||n.open))
37
+ const panel=candidates.sort((a,b)=>Number(b.dataset.duetAvatarSurface)-Number(a.dataset.duetAvatarSurface))[0]
38
+ for(const node of moved.keys())if(!candidates.includes(node))restore(node)
39
+ for(const node of candidates)if(node!==panel){restore(node);if(native){node.setAttribute('data-duet-surface-native','');moved.set(node,true)}}
40
+ if(!panel){if(current||last||native!==nativeBefore)avatar()?.surface?.({type:'surface',panel:null});last='';semantic='';current=null;actions.clear();nativeBefore=native;return}
41
+ let id=ids.get(panel);if(!id){id=`s${++serial}`;ids.set(panel,id)}
42
+ const nodes=snapshot(panel),target=panel.dataset.duetSurfaceTarget||null
43
+ const key=JSON.stringify({id,nodes,target}),changed=key!==last
44
+ // Cosmetic countdown text does not invalidate an in-flight click. All other
45
+ // content and action state still fence stale confirmations.
46
+ const actionKey=JSON.stringify({id,target,nodes:nodes.map(n=>n.action&&actions.get(n.action)?.hasAttribute('data-duet-live-text')?{...n,text:''}:n)})
47
+ if(changed)current={id,revision:(current?.revision||0)+(actionKey!==semantic?1:0),nodes,target}
48
+ semantic=actionKey
49
+ // A real click must happen in the playback document. Keep that counterpart visible.
50
+ const audioUnlock=panel.hasAttribute('data-duet-audio-unlock')
51
+ panel.toggleAttribute('data-duet-surface-native',native&&!audioUnlock&&!nodes.some(n=>n.gesture))
52
+ const anchor=view.anchor
53
+ if(!audioUnlock&&anchor?.isConnected&&!anchor.hidden) {
54
+ const r=anchor.getBoundingClientRect(),b=panel.getBoundingClientRect()
55
+ const right=r.right+12,side=right+b.width<innerWidth-12
56
+ panel.style.setProperty('--duet-surface-x',`${Math.max(12,Math.min(side?right:r.left,innerWidth-b.width-12))}px`)
57
+ panel.style.setProperty('--duet-surface-y',`${Math.max(12,Math.min(side?r.top:r.top-b.height-12,innerHeight-b.height-12))}px`)
58
+ panel.setAttribute('data-duet-surface-positioned','')
59
+ }else panel.removeAttribute('data-duet-surface-positioned')
60
+ moved.set(panel,true)
61
+ if(native&&(changed||!nativeBefore)) {
62
+ try{
63
+ const projected=audioUnlock
64
+ ? {...current,nodes:[{kind:'text',text:'请回到 DSH,点击“启动音频播放”。'}]}
65
+ : current
66
+ if(avatar()?.surface?.(avatarSurface({type:'surface',panel:projected}))===false){nativeBefore=false;return}}catch{restore(panel);current=null;last='';return}
67
+ }
68
+ last=key;nativeBefore=native
69
+ }
70
+ function action(value) {
71
+ let v;try{v=avatarSurfaceAction(value)}catch{return}
72
+ if(!current||v.id!==current.id||v.revision!==current.revision)return
73
+ const node=actions.get(v.action)
74
+ if(!node?.isConnected||node.disabled||(node.hasAttribute('data-duet-user-gesture')&&!canActivate()))return
75
+ // Invalidate before invoking: a double-click cannot send twice or replay a stale step.
76
+ current.revision++;last=''
77
+ if(node.matches('input[type=checkbox]')){node.checked=v.checked;node.dispatchEvent(new Event('change',{bubbles:true}))}
78
+ else node.click()
79
+ sync()
80
+ }
81
+ const timer=setInterval(sync,100)
82
+ return {sync,action,dispose(){disposed=true;clearInterval(timer);for(const n of moved.keys())restore(n);style.remove();avatar()?.surface?.({type:'surface',panel:null});actions.clear()}}
83
+ }
@@ -0,0 +1,68 @@
1
+ import {AvatarNotices,noticePreferences,saveNoticePreferences,NOTICE_KEY,avatarMenuAction,avatarMenuResult} from '../shared/avatar-menu.mjs'
2
+ import {avatarPreferences} from '../shared/avatar.mjs'
3
+ import {nativeInteractions} from './interactions.mjs'
4
+ import {focusedSession,openLocalSession} from './composer.mjs'
5
+ /** Local DSH feed only: does not own/open a voice connection or call TTS. */
6
+ export function mountAvatarTasks({ctx,sync,avatar,tutorial,settings,focus=()=>window.focus()}){
7
+ const model=new AvatarNotices(),seenCommands=new Set(),controller=new AbortController()
8
+ let dead=false,interactions,unwatch=()=>{},last='',prefs=noticePreferences()
9
+ try{interactions=nativeInteractions(ctx)}catch{}
10
+ const scope=()=>{
11
+ const work=ctx.workspaces?.list?.getSnapshot(),current=focusedSession(ctx)
12
+ const workspace=work?.items?.find(w=>w.sessionIds?.includes(current))??(work?.items?.length===1?work.items[0]:null)
13
+ const id=workspace?.workspaceId||workspace?.id
14
+ if(!id)return {id:null,rows:[]}
15
+ const member=new Set(workspace.sessionIds||[]),archived=new Set(work.archivedSessionIds||[])
16
+ return {id,rows:(sync.snapshot?.sessions||[]).filter(s=>!archived.has(s.session_id)&&s.origin!=='subagent'&&(s.workspace_id===id||member.has(s.session_id)))}
17
+ }
18
+ const publish=()=>{
19
+ if(dead)return
20
+ const state=model.state(prefs,avatarPreferences().size,sync.active)
21
+ const fingerprint=JSON.stringify({...state,revision:0})
22
+ if(last!==fingerprint){last=fingerprint;avatar()?.localState?.(state)}
23
+ }
24
+ const refresh=()=>{
25
+ if(dead)return
26
+ const s=scope()
27
+ let pending=[];try{pending=interactions?.snapshot()||[]}catch{}
28
+ model.update({scope:s.id,epoch:sync.epoch,sessions:s.rows,results:sync.active?(sync.snapshot?.results||[]):[],interactions:pending})
29
+ publish()
30
+ }
31
+ const unsubscribe=sync.subscribe(refresh),workspaceStop=ctx.workspaces?.list?.subscribe?.(refresh),sessionStop=ctx.sessions?.list?.subscribe?.(refresh)
32
+ if(interactions)unwatch=interactions.subscribe(refresh)
33
+ const preferenceChange=()=>{prefs=noticePreferences();publish()}
34
+ window.addEventListener('storage',preferenceChange)
35
+ const channel=typeof BroadcastChannel==='undefined'?null:new BroadcastChannel(NOTICE_KEY)
36
+ if(channel)channel.onmessage=preferenceChange
37
+ const change=patch=>{prefs=saveNoticePreferences({...prefs,...patch});channel?.postMessage('changed');publish()}
38
+ const result=(request,ok,message='')=>avatar()?.menuResult?.(avatarMenuResult({type:'menu_result',request_id:request.request_id,ok,message}))
39
+ const action=async raw=>{
40
+ let request;try{request=avatarMenuAction(raw)}catch{return}
41
+ if(dead||seenCommands.has(request.request_id))return
42
+ seenCommands.add(request.request_id);while(seenCommands.size>256)seenCommands.delete(seenCommands.values().next().value)
43
+ try{
44
+ switch(request.action){
45
+ case 'open_dsh':focus();return result(request,true)
46
+ case 'view':{
47
+ refresh()
48
+ const item=model.items.get(request.id)
49
+ if(!sync.active||!item||!scope().rows.some(s=>s.session_id===item.session_id))throw Error('这条通知已失效,请回到 DSH 查看')
50
+ await openLocalSession(ctx,item.session_id,controller.signal);focus();model.read(item.id);publish()
51
+ return result(request,true)
52
+ }
53
+ case 'dismiss':model.dismiss(request.id);publish();break
54
+ case 'size':avatar()?.setSize?.(request.value);publish();break
55
+ case 'bubble':change({bubble:request.value});break
56
+ case 'notifications':change({enabled:request.value,snoozeUntil:0});break
57
+ case 'settings':settings();focus();return result(request,true)
58
+ case 'tutorial':tutorial()?.open({origin:'avatar'});return result(request,true)
59
+ case 'hide':await avatar()?.toggle?.();break
60
+ default:return
61
+ }
62
+ result(request,true)
63
+ }catch(error){if(!dead)result(request,false,/通知已失效/.test(error.message)?error.message:'操作未完成,请回到 DSH 重试')}
64
+ }
65
+ // Only expires local DND; never polls a server.
66
+ const timer=setInterval(publish,1000);refresh()
67
+ return{action,refresh,dispose(){dead=true;controller.abort();clearInterval(timer);unsubscribe();unwatch();workspaceStop?.();sessionStop?.();channel?.close();window.removeEventListener('storage',preferenceChange)}}
68
+ }