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,218 @@
1
+ import { AVATAR_KEY, AVATAR_SIZES, avatarScale, avatarPreferences, saveAvatarPreferences } from '../shared/avatar.mjs'
2
+ import { voiceSocketUrl } from './transport.mjs'
3
+ import { identityFetch } from './identity.mjs'
4
+ import { PLUGIN_VERSION } from '../shared/state.mjs'
5
+ import { mountInputEffect } from './input-effect.mjs'
6
+ import { avatarCloseConfirmation } from '../shared/avatar-ui.mjs'
7
+ import {mountAvatarMenu} from '../shared/avatar-menu-ui.mjs'
8
+ import {avatarLocalState,avatarMenuResult,noticePreferences} from '../shared/avatar-menu.mjs'
9
+ import {AvatarActivityClock,avatarGeometry} from '../shared/avatar-activity.mjs'
10
+
11
+ /** Page-bound presentation. The native helper cannot acquire its own voice session. */
12
+ export function mountAvatar({controls, audio, state, notice, requestMode, onSurfaceAction=()=>{}, onMenuAction=()=>{}, focusedSession=()=>null}) {
13
+ let dead=false,renderer,root,stage,caption,ws,native=false,epoch=0,loading=false,lastState='',timer
14
+ let prefs=avatarPreferences()
15
+ const closeConfirmation=avatarCloseConfirmation({floating:true,origin:'page',anchor:()=>controls()})
16
+ let forceWebOnly=false,configLoaded=false
17
+ let menu,localState,lastNotice,retryTimer,connectTimer,reconnect,retryCount=0,presentationMode='off'
18
+ let desktopPosition=null,activityStartTimer
19
+ const activity=new AvatarActivityClock({snapshot:()=>{
20
+ const p=noticePreferences(),r=root?.getBoundingClientRect(),screen=window.screen
21
+ const position=native?desktopPosition:r?avatarGeometry({space:'viewport_css',total_resolution:{width:screen.width,height:screen.height},viewport_resolution:{width:innerWidth,height:innerHeight},avatar_position:{x:r.x,y:r.y,width:r.width,height:r.height}}):null
22
+ return{size:prefs.size,bubble_size:p.bubble,notifications_enabled:p.enabled,pending_count:localState?.available?localState.items.filter(i=>i.pending).length:null,notification_count:localState?.available?localState.items.filter(i=>!i.pending).length:null,position}
23
+ },send:value=>{void identityFetch('/duplex-control/api/avatar/activity',{method:'POST',headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'},body:JSON.stringify(value),keepalive:true}).catch(()=>{})}})
24
+ const activityTimer=setInterval(()=>activity.tick(),30000)
25
+ const pagehide=()=>{clearTimeout(activityStartTimer);activityStartTimer=null;activity.stop('pagehide')}
26
+ window.addEventListener('pagehide',pagehide)
27
+ const publishPresentation=mode=>{presentationMode=mode;channel?.postMessage({type:'presentation',mode})}
28
+ const ownerKind=location.protocol==='dsh-app:'?'desktop':/Edg\//.test(navigator.userAgent)?'edge':/Firefox\//.test(navigator.userAgent)?'firefox':/Chrome\//.test(navigator.userAgent)?'chrome':/Safari\//.test(navigator.userAgent)?'safari':'browser'
29
+ const rememberOwner=()=>{if(native&&document.visibilityState==='visible'&&document.hasFocus())send({type:'owner_focus'})}
30
+ window.addEventListener('focus',rememberOwner)
31
+ const inputEffect=mountInputEffect({anchor:()=>{
32
+ if(root&&!root.hidden)return caption&&!caption.hidden?caption:root
33
+ return controls()?.querySelector('#dsh-duet-entry')||controls()
34
+ },isCurrent:id=>focusedSession()===id})
35
+ const syncToggle=()=>{
36
+ const button=controls()?.querySelector('[data-duet-avatar-toggle]');if(!button)return
37
+ const enabled=avatarPreferences().enabled
38
+ button.setAttribute('aria-pressed',String(enabled))
39
+ button.title=enabled?'隐藏拟人角色':'打开拟人角色';button.setAttribute('aria-label',button.title)
40
+ button.style.background=enabled?'#dcefff':'transparent';button.style.color=enabled?'#185a89':'currentColor'
41
+ }
42
+ const channel=typeof BroadcastChannel==='undefined'?null:new BroadcastChannel(AVATAR_KEY)
43
+ const send=frame=>{if(ws?.readyState===1&&ws.bufferedAmount<16000){ws.send(JSON.stringify(frame));return true}return false}
44
+ const frame=()=>{
45
+ const s=state(),sample=audio.avatarSample?.() || {rms:0,viseme:'A',utterance:''}
46
+ return {type:'frame',mode:s.mode,ready:s.ready===true,size:prefs.size,rms:sample.rms,viseme:sample.viseme,utterance:sample.utterance,text:sample.text||''}
47
+ }
48
+ const place=()=>{
49
+ if(!root)return
50
+ const c=controls(),r=c?.getBoundingClientRect()
51
+ root.hidden=!r||c.dataset.compact==='true'
52
+ if(r){
53
+ const base=Math.min(260,Math.max(180,r.width)),scale=Math.min(avatarScale(prefs.size),Math.max(1,innerWidth-16)/base)
54
+ const width=base*scale,height=210*scale,top=Math.max(0,r.top-height-4)
55
+ root.dataset.size=prefs.size;root.style.width=`${width}px`;root.style.height=`${height}px`
56
+ root.style.left=`${Math.max(8,Math.min(innerWidth-width-8,r.left))}px`;root.style.top=`${top}px`
57
+ stage.style.width=`${base}px`;stage.style.transform=`scale(${scale})`
58
+ const bubbleWidth=Math.min(base-8,innerWidth-16),left=parseFloat(root.style.left)
59
+ caption.style.width=`${bubbleWidth}px`;caption.style.left=`${Math.max(8,Math.min(innerWidth-bubbleWidth-8,left+width/2-bubbleWidth/2))-left}px`
60
+ caption.style.maxHeight=`${Math.max(30,Math.min({small:90,medium:180,large:260}[noticePreferences().bubble],top-18))}px`
61
+ // Reveal and constrain the caption before scrolling, including size changes.
62
+ if(!caption.hidden)caption.scrollTop=caption.scrollHeight
63
+ }
64
+ }
65
+ const clear=(reason='restart')=>{clearTimeout(activityStartTimer);activityStartTimer=null;activity.stop(reason);clearTimeout(retryTimer);clearTimeout(connectTimer);reconnect=null;retryCount=0;closeConfirmation.cancel();menu?.dispose();menu=null;epoch++;loading=false;native=false;desktopPosition=null;const old=ws;ws=null;old?.close();renderer?.dispose();renderer=null;root?.remove();root=null;clearInterval(timer);inputEffect.clear()}
66
+ const web=async ticket=>{
67
+ if(dead||ticket!==epoch||renderer||loading)return
68
+ loading=true
69
+ try{
70
+ const {mountAvatarRenderer}=await import(`/duet/avatar/renderer.mjs?v=${PLUGIN_VERSION}`)
71
+ if(dead||ticket!==epoch)return
72
+ root=document.createElement('div');root.dataset.duetAvatar='';root.setAttribute('aria-label','duet 3D 形象')
73
+ root.style.cssText='position:fixed;height:210px;z-index:20;pointer-events:none'
74
+ stage=document.createElement('div');stage.style.cssText='position:absolute;left:0;top:0;height:210px;transform-origin:top left';stage.dataset.duetAvatarStage=''
75
+ const viewport=document.createElement('div');viewport.style.cssText='width:100%;height:100%'
76
+ caption=document.createElement('div');caption.dataset.duetCaption='';caption.style.cssText='position:absolute;bottom:calc(100% + 10px);left:4px;right:4px;box-sizing:border-box;text-align:left;font:13px system-ui;line-height:1.65;white-space:pre-wrap;overflow-wrap:anywhere;color:CanvasText;background:Canvas;border:1px solid color-mix(in srgb, CanvasText 12%, transparent);border-radius:16px;padding:12px 14px;max-height:180px;overflow-y:auto;box-shadow:0 6px 24px #0002;pointer-events:auto';caption.hidden=true
77
+ const tail=document.createElement('div');tail.dataset.duetCaptionTail='';tail.style.cssText='position:absolute;bottom:calc(100% + 3px);left:48%;width:14px;height:14px;background:Canvas;transform:rotate(45deg);border-right:1px solid color-mix(in srgb, CanvasText 12%, transparent);border-bottom:1px solid color-mix(in srgb, CanvasText 12%, transparent)';tail.hidden=true
78
+ stage.append(viewport);root.append(stage,caption,tail);document.body.append(root);place()
79
+ viewport.style.pointerEvents='auto';viewport.tabIndex=0;viewport.setAttribute('aria-label','duet 形象,右键打开菜单')
80
+ menu=mountAvatarMenu({anchor:()=>root,send:onMenuAction})
81
+ viewport.oncontextmenu=e=>menu.open(e)
82
+ viewport.onkeydown=e=>{if(e.key==='ContextMenu'||e.key==='F10'&&e.shiftKey)menu.open(e)}
83
+ if(localState)menu.update(localState)
84
+ renderer=mountAvatarRenderer(viewport,{modelURL:'/duet/avatar/character.glb',onReady:()=>{if(!dead&&ticket===epoch&&root){root.dataset.ready='true';activity.start('web')}},onError:()=>{activity.stop('unavailable');publishPresentation('unavailable');notice('3D 形象暂不可用,可在设置中关闭。')}})
85
+ }catch{root?.remove();root=null;publishPresentation('unavailable');notice('3D 形象暂不可用,语音功能不受影响。')}
86
+ finally{if(ticket===epoch)loading=false}
87
+ }
88
+ const start=()=>{
89
+ syncToggle()
90
+ if(!configLoaded)return
91
+ clear(avatarPreferences().enabled?'restart':'disabled');prefs=avatarPreferences();const ticket=epoch
92
+ if(dead||!prefs.enabled){publishPresentation('off');return}
93
+ let lastReceive=Date.now(),lastTick=Date.now()
94
+ const permanent=new Set(['desktop_platform_unsupported','desktop_display_unavailable','desktop_helper_missing','desktop_helper_upgrade_required','desktop_webview2_missing','desktop_assets_invalid','desktop_assets_damaged','desktop_assets_incompatible'])
95
+ const fallback=reason=>{
96
+ if(dead||ticket!==epoch)return
97
+ activity.stop('unavailable')
98
+ clearTimeout(connectTimer);native=false
99
+ const old=ws;ws=null;old?.close()
100
+ if(permanent.has(reason)){
101
+ reconnect=null;publishPresentation('fallback')
102
+ notice(reason==='desktop_webview2_missing'?'桌面形象需要 WebView2 Runtime,当前临时在网页中显示。':'桌面组件不可用,当前临时在网页中显示;可在设置中重试桌面显示。')
103
+ void web(ticket);return
104
+ }
105
+ // Temporary loss (including sleep/wake) must not move the character into
106
+ // the page or rewrite the user's desktop preference. Explicit hide is
107
+ // handled by the separate hide command, never inferred from a crash.
108
+ publishPresentation(reason==='desktop_in_use'?'other':'recovering')
109
+ clearTimeout(retryTimer)
110
+ retryTimer=setTimeout(()=>connect(),[1000,2000,5000,10000,30000][Math.min(retryCount++,4)])
111
+ }
112
+ const connect=()=>{
113
+ if(dead||ticket!==epoch||ws)return
114
+ clearTimeout(retryTimer)
115
+ try{
116
+ lastReceive=Date.now()
117
+ const socket=ws=new WebSocket(voiceSocketUrl({},globalThis,'duet/avatar/ws'))
118
+ const current=()=>!dead&&ticket===epoch&&ws===socket
119
+ connectTimer=setTimeout(()=>{if(current())fallback('desktop_start_timeout')},25000)
120
+ socket.onopen=()=>{if(current())send({type:'start',size:prefs.size,owner_kind:ownerKind})}
121
+ socket.onmessage=e=>{
122
+ if(!current())return
123
+ lastReceive=Date.now()
124
+ try{
125
+ const value=JSON.parse(e.data)
126
+ if(value.type==='desktop_ready'){
127
+ clearTimeout(connectTimer);retryCount=0;native=true;publishPresentation('desktop')
128
+ clearTimeout(activityStartTimer);activityStartTimer=setTimeout(()=>{activityStartTimer=null;if(current()&&native)activity.start('desktop')},1500)
129
+ send(frame());if(localState)send(localState);rememberOwner()
130
+ }
131
+ else if(value.type==='alive')return
132
+ else if(value.type==='avatar_geometry'){desktopPosition=avatarGeometry(value.position);if(activityStartTimer&&native&&desktopPosition){clearTimeout(activityStartTimer);activityStartTimer=null;activity.start('desktop')}}
133
+ else if(value.type==='fallback')fallback(value.reason)
134
+ else if(value.type==='mode')requestMode(value.mode)
135
+ else if(value.type==='surface_action'&&native)onSurfaceAction(value)
136
+ else if(value.type==='menu_action'&&native)onMenuAction(value)
137
+ else if(value.type==='size' && Object.hasOwn(AVATAR_SIZES,value.size))setSize(value.size)
138
+ else if(value.type==='hide')hide()
139
+ }catch{fallback('desktop_failed')}
140
+ }
141
+ socket.onerror=()=>{}
142
+ socket.onclose=()=>{if(current())fallback('desktop_disconnected')}
143
+ }catch{fallback('desktop_unavailable')}
144
+ }
145
+ reconnect=()=>{if(!ws)connect();else send({type:'alive'})}
146
+ if(forceWebOnly||prefs.webOnly){reconnect=null;publishPresentation('web');void web(ticket)}
147
+ else{publishPresentation('connecting');connect()}
148
+ let lastPing=0,lastFrame=0
149
+ timer=setInterval(()=>{
150
+ if(dead||ticket!==epoch)return
151
+ const now=Date.now()
152
+ if(now-lastTick>5000||now<lastTick){lastReceive=now;reconnect?.()}
153
+ lastTick=now
154
+ if(ws&&now-lastPing>=5000){send({type:'alive'});lastPing=now}
155
+ if(native&&now-lastReceive>20000)fallback('desktop_disconnected')
156
+ const value=frame(),summary=JSON.stringify(value)
157
+ if(renderer){
158
+ renderer.update(value)
159
+ if(caption.textContent!==value.text)caption.textContent=value.text
160
+ caption.hidden=!value.text;root.querySelector('[data-duet-caption-tail]').hidden=!value.text;place()
161
+ }
162
+ // Active speech at 20 Hz; idle state at 1 Hz. No PCM or microphone data.
163
+ if(native&&(summary!==lastState||now-lastFrame>=1000)){send(value);lastState=summary;lastFrame=now}
164
+ },50)
165
+ }
166
+ const setEnabled=enabled=>{
167
+ try{saveAvatarPreferences({...avatarPreferences(),enabled});channel?.postMessage('changed');changed()}
168
+ catch{notice('头像设置未保存,请检查浏览器存储权限。')}
169
+ }
170
+ const hide=()=>setEnabled(false)
171
+ const changed=e=>{
172
+ if(e&&e.key!==AVATAR_KEY)return
173
+ const next=avatarPreferences()
174
+ if(next.enabled!==prefs.enabled||next.webOnly!==prefs.webOnly){start();return}
175
+ prefs=next;syncToggle();place();if(native)send(frame())
176
+ }
177
+ const setSize=size=>{
178
+ if(!Object.hasOwn(AVATAR_SIZES,size))return
179
+ try{saveAvatarPreferences({...avatarPreferences(),size});channel?.postMessage('changed');changed()}
180
+ catch{notice('形象大小未保存,请检查浏览器存储权限。')}
181
+ }
182
+ window.addEventListener('storage',changed)
183
+ const resume=()=>{if(document.visibilityState==='visible'){reconnect?.();if(native)activity.start('desktop');else if(root?.dataset.ready==='true')activity.start('web')}}
184
+ window.addEventListener('online',resume);window.addEventListener('pageshow',resume);window.addEventListener('focus',resume)
185
+ document.addEventListener('visibilitychange',resume)
186
+ if(channel)channel.onmessage=e=>{
187
+ if(e.data?.type==='presentation_request')publishPresentation(presentationMode)
188
+ else if(e.data?.type==='retry_desktop'&&!forceWebOnly&&!avatarPreferences().webOnly)start()
189
+ else if(e.data==='changed')changed()
190
+ }
191
+ syncToggle()
192
+ const configAbort=new AbortController()
193
+ const configTimeout=setTimeout(()=>configAbort.abort(),3000)
194
+ void identityFetch('/duplex-control/api/voice/config',{cache:'no-store',signal:configAbort.signal})
195
+ .then(r=>r.ok?r.json():{}).then(config=>{forceWebOnly=config.avatar?.web_only===true})
196
+ .catch(()=>{}).finally(()=>{clearTimeout(configTimeout);configLoaded=true;if(!dead)start()})
197
+ return {
198
+ presentation(){return {native,mode:presentationMode,anchor:root&&!root.hidden?root:null}},
199
+ surface(value){return native&&send(value)},
200
+ syncToggle,
201
+ setSize,
202
+ localState(value){
203
+ localState=avatarLocalState(value);menu?.update(localState);place();if(native)send(localState)
204
+ if(localState.toast&&localState.toast!==lastNotice&&state().mode==='off'&&localState.items.find(i=>i.id===localState.toast)?.status==='completed')
205
+ renderer?.update({...frame(),text:'完成了',utterance:'notice-'+localState.toast})
206
+ lastNotice=localState.toast
207
+ },
208
+ menuResult(value){const result=avatarMenuResult(value);if(native)send(result);else menu?.result(result)},
209
+ async toggle(){if(!avatarPreferences().enabled)setEnabled(true);else if(await closeConfirmation.ask()&&avatarPreferences().enabled)hide()},
210
+ inputWritten(text,id){try{
211
+ inputEffect.show(text,id)
212
+ if(native&&text&&focusedSession()===id)send({type:'input_effect',text:text.slice(0,600)})
213
+ }catch{inputEffect.clear()}},
214
+ cancelInput(){inputEffect.clear();if(native)send({type:'clear_input_effect'})},
215
+ event(){}, // Captions and mouth animation are driven solely by actual PCM playback.
216
+ dispose(){dead=true;clearInterval(activityTimer);window.removeEventListener('pagehide',pagehide);closeConfirmation.dispose();inputEffect.dispose();configAbort.abort();clearTimeout(configTimeout);clear('unmount');window.removeEventListener('storage',changed);window.removeEventListener('focus',rememberOwner);window.removeEventListener('online',resume);window.removeEventListener('pageshow',resume);window.removeEventListener('focus',resume);document.removeEventListener('visibilitychange',resume);publishPresentation('off');channel?.close()},
217
+ }
218
+ }
@@ -1,25 +1,29 @@
1
- import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.1.9'
2
- import { DuetAudio } from './audio.mjs?v=0.1.9'
3
- import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.9'
4
- import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.9'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.9'
6
- import { mountTutorial } from './tutorial.mjs?v=0.1.9'
7
- import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.9'
8
- import { mountRating } from './feedback.mjs?v=0.1.9'
9
- import { createAudioUploadConsent } from './consent.mjs?v=0.1.9'
10
- import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.9'
11
- import { nativeInteractions } from './interactions.mjs?v=0.1.9'
12
- import { mountConnectionHint } from './connection-hint.mjs?v=0.1.9'
13
- import { mountControlsLayout } from './controls-layout.mjs?v=0.1.9'
14
- import { mountNotice } from './notice.mjs?v=0.1.9'
15
- import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.9'
16
- import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.9'
17
- import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.9'
18
- import { sessionLabel } from '../shared/catalog.mjs?v=0.1.9'
19
- import { resultNotification } from '../shared/result-notification.mjs?v=0.1.9'
20
- import { HarnessSync } from './harness-sync.mjs?v=0.1.9'
21
- import { LocalSync } from './local-sync.mjs?v=0.1.9'
22
- import { diagnosticPayload } from '../shared/diagnostics.mjs?v=0.1.9'
1
+ import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.2.0'
2
+ import { DuetAudio, AUDIO_STOP_PROTOCOL } from './audio.mjs?v=0.2.0'
3
+ import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.2.0'
4
+ import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.2.0'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.2.0'
6
+ import { mountTutorial } from './tutorial.mjs?v=0.2.0'
7
+ import { mountAvatarTasks } from './avatar-tasks.mjs'
8
+ import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.2.0'
9
+ import { mountRating } from './feedback.mjs?v=0.2.0'
10
+ import { createAudioUploadConsent } from './consent.mjs?v=0.2.0'
11
+ import { bindDuetShortcuts } from './shortcuts.mjs?v=0.2.0'
12
+ import { nativeInteractions } from './interactions.mjs?v=0.2.0'
13
+ import { mountConnectionHint } from './connection-hint.mjs?v=0.2.0'
14
+ import { mountControlsLayout } from './controls-layout.mjs?v=0.2.0'
15
+ import { mountNotice } from './notice.mjs?v=0.2.0'
16
+ import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.2.0'
17
+ import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.2.0'
18
+ import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.2.0'
19
+ import { sessionLabel } from '../shared/catalog.mjs?v=0.2.0'
20
+ import { resultNotification } from '../shared/result-notification.mjs?v=0.2.0'
21
+ import { HarnessSync } from './harness-sync.mjs?v=0.2.0'
22
+ import { LocalSync } from './local-sync.mjs?v=0.2.0'
23
+ import { diagnosticPayload } from '../shared/diagnostics.mjs?v=0.2.0'
24
+ import { mountAvatar } from './avatar.mjs'
25
+ import { mountAvatarSurfaces } from './avatar-surfaces.mjs'
26
+ import { audioUnlockPanel } from '../shared/avatar-ui.mjs'
23
27
 
24
28
  export function mountDuet(ctx) {
25
29
  const pageId = crypto.randomUUID()
@@ -30,10 +34,13 @@ export function mountDuet(ctx) {
30
34
  const notices = mountNotice(() => controls)
31
35
  const labels = new Map()
32
36
  const resultResume = {}
33
- let localSync
37
+ let localSync,avatarTasks,closeMenuSettings
34
38
  let clientTraceId = null, diagnosticCount = 0
35
39
  let connectionGuidance = null, reportHintShown = null
36
- let tutorial, teaching, ratingPanel, connectionHint, stopControlsLayout, stopSettings
40
+ let tutorial, teaching, ratingPanel, connectionHint, stopControlsLayout, stopSettings, avatar
41
+ const modeActions=new Map()
42
+ let unlockPanel
43
+ const surfaces = mountAvatarSurfaces({avatar:()=>avatar,canActivate:()=>audio.context?.state==='running'})
37
44
  const diagnostic = data => {
38
45
  if (++diagnosticCount > 100 && !diagnosticPayload(data)) return
39
46
  const bounded = Object.fromEntries(Object.entries(data).map(([k, v]) => [k, typeof v === 'string' ? v.slice(0, 4000) : v]))
@@ -115,10 +122,15 @@ export function mountDuet(ctx) {
115
122
  interactions: interactions.snapshot(),
116
123
  }), report, resultResume)
117
124
  const stopInteractions = interactions.subscribe(() => resultPush.changed())
118
- const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) =>
119
- (await interactions(request, signal)) ?? composer.execute(request, signal), rows =>
125
+ const rpc = new HarnessRPCExecutor(send, fetch, report, async (request, signal) => {
126
+ const result=(await interactions(request, signal)) ?? await composer.execute(request, signal)
127
+ if(request.method==='PUT' && /\/composer$/.test(request.path) && result?.composer && !signal.aborted)
128
+ avatar?.inputWritten(result.composer.text,result.composer.session_id)
129
+ return result
130
+ }, rows =>
120
131
  browserSessionCatalog(ctx, rows).map(row => ({ ...row, active: row.session_id === focusedSession(ctx) })), {
121
132
  id: connectionTraceId,
133
+ focused: () => focusedSession(ctx),
122
134
  syncSupported: () => localSync?.active && interactions.supportsSync,
123
135
  creationPayload: payload => sessionCreationPayload(ctx, payload),
124
136
  completed: async (request, body, signal) => {
@@ -149,6 +161,7 @@ export function mountDuet(ctx) {
149
161
  stopBridge?.(); stopBridge = null
150
162
  rpc.close()
151
163
  audio.stop()
164
+ avatar?.cancelInput()
152
165
  if (ws && ws.readyState !== WebSocket.CLOSED) {
153
166
  await new Promise(resolve => {
154
167
  const timer = setTimeout(resolve, 1200)
@@ -169,11 +182,12 @@ export function mountDuet(ctx) {
169
182
  if(!identity.ok)throw Error('voice_config_unavailable')
170
183
  requireWorkspace(ctx)
171
184
  if(closed)return
172
- if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId, fetch, localSync)
185
+ if (mode === 'online') stopBridge = startComposerBridge(ctx, connectionTraceId, fetch, localSync,
186
+ (text,id)=>avatar?.inputWritten(text,id))
173
187
  ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
174
188
  ws.onopen = () => {
175
189
  report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
176
- send({ type: 'session.update' })
190
+ send({ type: 'session.update', client: {audio_stop_protocol:AUDIO_STOP_PROTOCOL, audio_text_protocol:'audio_text_delta_v1'} })
177
191
  if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
178
192
  }
179
193
  ws.onmessage = async event => {
@@ -236,7 +250,10 @@ export function mountDuet(ctx) {
236
250
  try { audio.connectedChime() } catch { /* A notification must not break voice. */ }
237
251
  }
238
252
  }
239
- audio.event(message, send)
253
+ if (audio.event(message, send, visible => {
254
+ avatar?.event(visible); teaching?.observe(visible); receive(visible)
255
+ })) return
256
+ avatar?.event(message)
240
257
  teaching?.observe(message)
241
258
  receive(message)
242
259
  } catch (error) {
@@ -293,6 +310,12 @@ export function mountDuet(ctx) {
293
310
  dot.textContent = '.'; dot.dataset.duetMark = ''; dot.style.color = '#ed9b35'
294
311
  entry.append(dot)
295
312
  controls.append(entry)
313
+ const avatarButton=document.createElement('button')
314
+ avatarButton.type='button';avatarButton.dataset.duetAvatarToggle=''
315
+ avatarButton.style.cssText='position:relative;flex-shrink:0;border:0;border-radius:6px;background:transparent;cursor:pointer;padding:5px;display:flex'
316
+ avatarButton.innerHTML='<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="12" cy="12" r="9"/><circle cx="12" cy="9" r="3"/><path d="M5.6 18.2a6.7 6.7 0 0 1 12.8 0"/></svg>'
317
+ avatarButton.onclick=()=>avatar?.toggle()
318
+ controls.append(avatarButton)
296
319
  // Heroicons 24/outline (MIT); all controls share the same optical box/stroke.
297
320
  for (const [kind, path] of [['mic', '<path d="M7.5 3.75 3 8.25m0 0 4.5 4.5M3 8.25h18m-4.5 3L21 15.75m0 0-4.5 4.5M21 15.75H3"/>'], ['speaker', '<path d="M19.114 5.636a9 9 0 0 1 0 12.728M16.463 8.288a5.25 5.25 0 0 1 0 7.424M6.75 8.25l4.72-4.72a.75.75 0 0 1 1.28.53v15.88a.75.75 0 0 1-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.009 9.009 0 0 1 2.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75Z"/>']]) {
298
321
  const button = document.createElement('button')
@@ -306,7 +329,7 @@ export function mountDuet(ctx) {
306
329
  // perimeter. Outer radius 6 matches the original button, not a circle.
307
330
  ring.innerHTML = '<svg viewBox="0 0 30 30" preserveAspectRatio="none" aria-hidden="true"><rect x="1" y="1" width="28" height="28" rx="5" pathLength="100"/></svg>'
308
331
  button.append(ring)
309
- button.onclick = () => {
332
+ const changeMode = origin => {
310
333
  if (tutorial?.active) { notice('请先结束教学,再切换模式。'); return }
311
334
  const requestedMode = kind === 'mic' ? 'online' : 'tts_only'
312
335
  const checkWorkspace = () => {
@@ -321,19 +344,21 @@ export function mountDuet(ctx) {
321
344
  if (!checkWorkspace()) return
322
345
  // Unlock playback inside user activation, before any network await.
323
346
  const enabling = kind === 'mic' ? state.mode !== 'online' : state.mode !== 'tts_only'
324
- if (enabling) void audio.prepare().catch(() => state.fail('audio_permission_denied'))
347
+ if (enabling) { unlockPanel?.remove();unlockPanel=null;void audio.prepare().catch(() => state.fail('audio_permission_denied')) }
325
348
  const ticket = !enabling && state.ready ? state.connection?.feedbackTicket : null
326
349
  // Capture the ended connection, never consult the next session after await.
327
350
  void (async()=>{
328
351
  await (kind === 'mic' ? state.toggleMic() : state.toggleSpeaker())
329
- if(ticket && !disposed){ratingPanel?.dispose();ratingPanel=mountRating(controls,ticket)}
352
+ if(ticket && !disposed){ratingPanel?.dispose();ratingPanel=mountRating(controls,ticket,{origin})}
330
353
  })()
331
354
  }
332
355
  audioConsent.cancel()
333
356
  const mode = kind === 'mic' ? 'online' : 'tts_only'
334
- if (state.mode !== mode) audioConsent.request(activate)
357
+ if (state.mode !== mode) audioConsent.request(activate,undefined,{origin})
335
358
  else activate()
336
359
  }
360
+ button.onclick=()=>changeMode('page')
361
+ modeActions.set(kind==='mic'?'online':'tts_only',changeMode)
337
362
  controls.append(button)
338
363
  }
339
364
  const settings = document.createElement('a')
@@ -352,8 +377,23 @@ export function mountDuet(ctx) {
352
377
  connectionHint?.dispose()
353
378
  connectionHint = mountConnectionHint(controls,{onShown:hint=>reportHintShown?.(hint)})
354
379
  draw(state)
380
+ avatar?.syncToggle()
355
381
  }
356
382
  mount()
383
+ avatar = mountAvatar({controls:()=>controls, audio, state:()=>state, notice, onSurfaceAction:surfaces.action, onMenuAction:value=>avatarTasks?.action(value), focusedSession:()=>focusedSession(ctx), requestMode:mode=>{
384
+ if (!['online','tts_only'].includes(mode)) return
385
+ // Native IPC cannot grant browser user activation. First-use consent and
386
+ // audio permission remain in the owning DSH page, never bypassed by a pet.
387
+ if (state.mode !== mode && audio.context?.state !== 'running') {
388
+ unlockPanel?.remove()
389
+ unlockPanel=audioUnlockPanel({
390
+ onEnable:()=>{unlockPanel?.remove();unlockPanel=null;controls?.querySelector(`[data-voice=${mode==='online'?'mic':'speaker'}]`)?.click()},
391
+ onCancel:()=>{unlockPanel?.remove();unlockPanel=null},
392
+ })
393
+ document.body.append(unlockPanel);surfaces.sync();return
394
+ }
395
+ modeActions.get(mode)?.('avatar')
396
+ }})
357
397
  const stopShortcuts = bindDuetShortcuts(kind => controls?.querySelector(`[data-voice=${kind}]`)?.click())
358
398
  const observer = new MutationObserver(mount)
359
399
  observer.observe(document.body, { subtree: true, childList: true })
@@ -448,10 +488,18 @@ export function mountDuet(ctx) {
448
488
  if (!tutorial && controls) tutorial = mountTutorial({ controls, adapter: teaching })
449
489
  }
450
490
  mountTeaching()
491
+ avatarTasks=mountAvatarTasks({ctx,sync:localSync,avatar:()=>avatar,tutorial:()=>tutorial,settings:()=>{
492
+ closeMenuSettings?.()
493
+ const link=document.createElement('a');link.href='/duet/'
494
+ closeMenuSettings=bindSettingsLink(link,globalThis,{embedded:true});link.click()
495
+ }})
451
496
  const teachingObserver = new MutationObserver(mountTeaching)
452
497
  teachingObserver.observe(document.body, { subtree: true, childList: true })
453
498
  return () => {
454
499
  disposed = true
500
+ avatarTasks?.dispose();closeMenuSettings?.()
501
+ surfaces.dispose();unlockPanel?.remove()
502
+ avatar?.dispose()
455
503
  window.removeEventListener('pagehide', pageHide)
456
504
  pollController?.abort()
457
505
  unwatchSessions?.(); unwatchWorkspaces?.()
@@ -1,7 +1,7 @@
1
1
  /** Composer requests belong to one explicit voice/tutorial connection, never all tabs. */
2
- import { focusedSession as currentSession } from './composer.mjs?v=0.1.9'
2
+ import { focusedSession as currentSession } from './composer.mjs?v=0.2.0'
3
3
 
4
- export function startComposerBridge(ctx, clientId, fetchImpl = fetch, feed = null) {
4
+ export function startComposerBridge(ctx, clientId, fetchImpl = fetch, feed = null, onWrite = () => {}) {
5
5
  const focusedSession = () => currentSession(ctx)
6
6
  const bridgeFetch = async (url, options = {}, timeoutMs = 8000) => {
7
7
  const request = new AbortController()
@@ -99,6 +99,9 @@ export function startComposerBridge(ctx, clientId, fetchImpl = fetch, feed = nul
99
99
  input.setDraft(["clear", "consume"].includes(request.type) ? "" : String(request.text ?? ""))
100
100
  await new Promise(resolve => setTimeout(resolve, 0))
101
101
  const after = await composerState(request.session_id, input)
102
+ if(request.type==='set' && !controller.signal.aborted && focusedSession()===request.session_id){
103
+ try{onWrite(after.text,request.session_id)}catch{ /* Presentation never fails an applied edit. */ }
104
+ }
102
105
  if (consumed !== null) {
103
106
  return {
104
107
  ...after,
@@ -58,16 +58,16 @@ export function composerAccess(ctx, label = () => '') {
58
58
  if (!value) fail('session_not_ready')
59
59
  return { composer: value }
60
60
  }
61
- const match = request.path.match(/^\/api\/sessions\/([A-Za-z0-9_-]+)\/composer$/)
61
+ const match = request.path.match(/^\/api\/sessions\/((?:[A-Za-z0-9_:-]|%3[Aa]){1,256})\/composer$/)
62
62
  if (request.method === 'GET' && match) {
63
- const id = match[1]
63
+ const id = decodeURIComponent(match[1])
64
64
  const value = await snapshot(id, inputFor(id))
65
65
  signal?.throwIfAborted()
66
66
  if (request.params?.require_focus === 'true' && focused() !== id) fail('focus_conflict')
67
67
  return { composer: value }
68
68
  }
69
69
  if (request.method !== 'PUT' || !match) return undefined
70
- const id = match[1], payload = request.payload || {}, input = inputFor(id)
70
+ const id = decodeURIComponent(match[1]), payload = request.payload || {}, input = inputFor(id)
71
71
  const overwrite = payload.overwrite === true
72
72
  const before = overwrite ? null : await snapshot(id, input)
73
73
  signal?.throwIfAborted()
@@ -1,8 +1,9 @@
1
1
  /** A brief, non-modal invitation after the microphone is actually ready. */
2
- import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.1.9'
2
+ import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.2.0'
3
3
  export function mountConnectionHint(controls, { duration = 8000, onShown = ()=>{} } = {}) {
4
4
  const hint = document.createElement('div')
5
5
  hint.dataset.duetConnectionHint = ''
6
+ hint.dataset.duetAvatarSurface = '30'
6
7
  hint.setAttribute('role', 'status')
7
8
  hint.setAttribute('aria-live', 'polite')
8
9
  hint.hidden = true
@@ -18,12 +18,13 @@ export function createAudioUploadConsent(storage) {
18
18
  const notify = dismissed; dismissed = null
19
19
  if (!confirmed) notify?.()
20
20
  }
21
- const request = (onAccept, onDismiss) => {
21
+ const request = (onAccept, onDismiss, {origin='page'} = {}) => {
22
22
  if (granted()) { onAccept(); return }
23
23
  if (dialog) { dialog.querySelector('button')?.focus(); return }
24
24
  dismissed = onDismiss
25
25
  dialog = document.createElement('dialog')
26
26
  dialog.id = 'duet-audio-consent'
27
+ dialog.dataset.duetAvatarSurface = '100';dialog.dataset.duetSurfaceOrigin=origin
27
28
  dialog.setAttribute('aria-labelledby', 'duet-audio-consent-title')
28
29
  dialog.setAttribute('aria-describedby', 'duet-audio-consent-description')
29
30
  dialog.style.cssText = 'max-width:380px;width:calc(100vw - 40px);border:1px solid #9aa8b8;border-radius:16px;padding:24px;background:Canvas;color:CanvasText;font:14px/1.7 system-ui;box-shadow:0 16px 60px #0004'
@@ -39,6 +40,7 @@ export function createAudioUploadConsent(storage) {
39
40
  for (const [label, agree] of [['暂不开启', false], ['同意并开启', true]]) {
40
41
  const button = document.createElement('button')
41
42
  button.type = 'button'; button.textContent = label
43
+ if(agree)button.dataset.duetUserGesture=''
42
44
  button.style.cssText = `padding:8px 14px;border-radius:8px;border:1px solid #9aa8b8;cursor:pointer;background:${agree ? '#dcefff' : 'transparent'};color:${agree ? '#185a89' : 'inherit'}`
43
45
  button.onclick = () => {
44
46
  if (!agree) { cancel(); return }
@@ -30,7 +30,7 @@ export function mountControlsLayout(controls) {
30
30
  actions.id = 'dsh-duet-actions'
31
31
  actions.setAttribute('role', 'group')
32
32
  actions.setAttribute('aria-label', 'duet 语音控制')
33
- for (const node of [...controls.children]) if (node.matches('[data-voice],a')) actions.append(node)
33
+ for (const node of [...controls.children]) if (node.matches('[data-voice],[data-duet-avatar-toggle],a')) actions.append(node)
34
34
  controls.append(actions)
35
35
  let compact = false, opened = false, timer, disposed = false, pinned = false, suppressFocus = false
36
36
  const listeners = []
@@ -69,22 +69,33 @@ export function mountControlsLayout(controls) {
69
69
  }, 220)
70
70
  }
71
71
  const update = () => {
72
- const next = geometry().width < 160 && typeof actions.showPopover === 'function'
73
- if (controls.dataset.compact === String(next)) { position(); return }
72
+ const expandedWidth=controls.querySelector('[data-duet-avatar-toggle]')?220:160
73
+ // A content-sized slot shrinks with our launcher. Measure with its normal
74
+ // minimum footprint, otherwise d. itself prevents recovery on expansion.
75
+ // Restore both styles synchronously, before painting or moving focus.
76
+ const previousMin=controls.style.minWidth,previousHost=parent.getAttribute('data-duet-compact-host')
77
+ parent.removeAttribute('data-duet-compact-host');controls.style.minWidth=`${expandedWidth}px`
78
+ const available=geometry().width
79
+ controls.style.minWidth=previousMin
80
+ if(previousHost!==null)parent.setAttribute('data-duet-compact-host',previousHost)
81
+ const next = available < expandedWidth && typeof actions.showPopover === 'function'
82
+ const collapsed=next&&available<80
83
+ if (controls.dataset.compact === String(next)&&controls.dataset.collapsed===String(collapsed)) { position(); return }
74
84
  close(); compact = next
75
85
  controls.dataset.compact = String(compact)
76
- if (compact) parent.setAttribute('data-duet-compact-host', 'true')
86
+ controls.dataset.collapsed = String(collapsed)
87
+ if (collapsed) parent.setAttribute('data-duet-compact-host', 'true')
77
88
  else if (hostCompact === null) parent.removeAttribute('data-duet-compact-host')
78
89
  else parent.setAttribute('data-duet-compact-host', hostCompact)
79
90
  controls.style.flexDirection = 'row'
80
- controls.style.margin = compact ? '4px 0' : '4px 8px'
81
- controls.style.padding = compact ? '2px 0' : '6px 8px'
82
- controls.style.justifyContent = compact ? 'center' : ''
91
+ controls.style.margin = collapsed ? '4px 0' : '4px 8px'
92
+ controls.style.padding = collapsed ? '2px 0' : '6px 8px'
93
+ controls.style.justifyContent = collapsed ? 'center' : ''
83
94
  controls.style.minWidth = '0'
84
95
  entry.style.cssText = initial.entry
85
- if (label) label.textContent = compact ? 'D' : labelText
96
+ if (label) label.textContent = collapsed ? 'd' : labelText
86
97
  if (compact) {
87
- entry.style.cssText += ';display:flex;align-items:center;gap:2px;margin:0;padding:4px;box-sizing:border-box;min-width:32px;height:32px;font-size:23px;cursor:pointer'
98
+ entry.style.cssText += ';display:flex;align-items:center;gap:0;margin:0;padding:4px;box-sizing:border-box;min-width:32px;height:32px;font-size:23px;white-space:nowrap;flex-shrink:0;cursor:pointer'
88
99
  entry.setAttribute('role', 'button'); entry.tabIndex = 0
89
100
  entry.setAttribute('aria-label', 'duet 语音控制')
90
101
  entry.setAttribute('aria-expanded', 'false'); entry.setAttribute('aria-controls', actions.id)
@@ -133,6 +144,7 @@ export function mountControlsLayout(controls) {
133
144
  controls.style.cssText = initial.controls; entry.style.cssText = initial.entry
134
145
  controls.append(...actions.children); actions.remove(); style.remove()
135
146
  delete controls.dataset.compact
147
+ delete controls.dataset.collapsed
136
148
  if (hostCompact === null) parent.removeAttribute('data-duet-compact-host')
137
149
  else parent.setAttribute('data-duet-compact-host', hostCompact)
138
150
  }
@@ -8,19 +8,40 @@ window.__ModuleLoader__.load({
8
8
  const inject = ["sessions", "conversation", "uiSession", "workspaces"]
9
9
 
10
10
  function apply(ctx) {
11
+ let loadFailure = false
12
+ let showLoadFailure = () => {}
11
13
  ctx.effect(() => {
12
14
  let active = true
13
15
  let dispose
14
- import('/duet/assets/client/browser.mjs?v=0.1.9').then(module => {
16
+ import('/duet/assets/client/browser.mjs?v=0.2.0').then(module => {
15
17
  if (active) dispose = module.mountDuet(ctx)
16
- }).catch(error => console.warn('duet controls could not load:', error))
18
+ }).catch(error => {
19
+ console.warn('duet controls could not load:', error)
20
+ if (!active) return
21
+ loadFailure = true
22
+ showLoadFailure()
23
+ })
17
24
  return () => { active = false; dispose?.() }
18
25
  }, 'duet-client: three-state microphone and playback controls')
19
26
  ctx.effect(() => {
20
27
  const entryId = "dsh-duet-entry"
21
28
 
29
+ // Keep this fallback self-contained: the browser module or its dependencies
30
+ // may be unavailable while an older DSH host is still running.
31
+ showLoadFailure = () => {
32
+ const entry = document.getElementById(entryId)
33
+ if (!loadFailure || !entry || entry.querySelector('[data-duet-load-error]')) return
34
+ const notice = document.createElement('span')
35
+ notice.setAttribute('data-duet-load-error', '')
36
+ notice.setAttribute('role', 'status')
37
+ notice.textContent = 'duet 加载失败,请刷新页面;如刚更新插件,请重启 DSH。'
38
+ notice.style.cssText = 'display:block;font-size:12px;line-height:1.5;font-weight:400;letter-spacing:normal;white-space:normal;overflow-wrap:anywhere;margin-top:4px;color:var(--foreground,currentColor)'
39
+ entry.style.whiteSpace = 'normal'
40
+ entry.append(notice)
41
+ }
42
+
22
43
  const mountEntry = () => {
23
- if (document.getElementById(entryId) !== null) return
44
+ if (document.getElementById(entryId) !== null) { showLoadFailure(); return }
24
45
  const settingsSlot = document.querySelector('[data-slot="sidebar.settings"]')
25
46
  const settingsButton = settingsSlot?.querySelector("button")
26
47
  const settingsLabel = settingsSlot?.querySelector("span")
@@ -39,12 +60,14 @@ window.__ModuleLoader__.load({
39
60
  entry.style.letterSpacing = "-0.4px"
40
61
  entry.append(label)
41
62
  settingsSlot.parentElement.insertBefore(entry, settingsSlot)
63
+ showLoadFailure()
42
64
  }
43
65
 
44
66
  mountEntry()
45
67
  const observer = new MutationObserver(mountEntry)
46
68
  observer.observe(document.body, { childList: true, subtree: true })
47
69
  return () => {
70
+ showLoadFailure = () => {}
48
71
  observer.disconnect()
49
72
  document.getElementById(entryId)?.remove()
50
73
  }