dsh-duet 0.1.10 → 0.2.1

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 (66) 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 +68 -3
  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 +83 -35
  33. package/src/client/composer-bridge.mjs +5 -2
  34. package/src/client/connection-hint.mjs +2 -1
  35. package/src/client/consent.mjs +3 -1
  36. package/src/client/controls-layout.mjs +21 -9
  37. package/src/client/entry.js +26 -3
  38. package/src/client/feedback.mjs +19 -4
  39. package/src/client/identity.mjs +2 -2
  40. package/src/client/input-effect.mjs +51 -0
  41. package/src/client/notice.mjs +20 -4
  42. package/src/client/rpc.mjs +2 -1
  43. package/src/client/settings.html +124 -4
  44. package/src/client/transport.mjs +2 -2
  45. package/src/client/tutorial-adapter.mjs +4 -4
  46. package/src/client/tutorial.mjs +5 -3
  47. package/src/client/voices.mjs +137 -0
  48. package/src/host/assets.mjs +13 -0
  49. package/src/host/avatar-activity.mjs +24 -0
  50. package/src/host/avatar-assets.mjs +18 -0
  51. package/src/host/avatar.mjs +130 -0
  52. package/src/host/diagnostics.mjs +111 -7
  53. package/src/host/feedback-files.mjs +5 -1
  54. package/src/host/plugin.mjs +59 -4
  55. package/src/host/proxy.mjs +41 -6
  56. package/src/host/settings-migration.mjs +2 -1
  57. package/src/host/settings.mjs +19 -4
  58. package/src/host/voices.mjs +205 -0
  59. package/src/shared/avatar-activity.mjs +33 -0
  60. package/src/shared/avatar-menu-ui.mjs +85 -0
  61. package/src/shared/avatar-menu.mjs +83 -0
  62. package/src/shared/avatar-surface.mjs +24 -0
  63. package/src/shared/avatar-ui.mjs +91 -0
  64. package/src/shared/avatar.mjs +125 -0
  65. package/src/shared/nickname.mjs +13 -0
  66. package/src/shared/state.mjs +15 -4
@@ -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.10'
2
- import { DuetAudio, AUDIO_STOP_PROTOCOL } from './audio.mjs?v=0.1.10'
3
- import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.1.10'
4
- import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.1.10'
5
- import { startComposerBridge } from './composer-bridge.mjs?v=0.1.10'
6
- import { mountTutorial } from './tutorial.mjs?v=0.1.10'
7
- import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.1.10'
8
- import { mountRating } from './feedback.mjs?v=0.1.10'
9
- import { createAudioUploadConsent } from './consent.mjs?v=0.1.10'
10
- import { bindDuetShortcuts } from './shortcuts.mjs?v=0.1.10'
11
- import { nativeInteractions } from './interactions.mjs?v=0.1.10'
12
- import { mountConnectionHint } from './connection-hint.mjs?v=0.1.10'
13
- import { mountControlsLayout } from './controls-layout.mjs?v=0.1.10'
14
- import { mountNotice } from './notice.mjs?v=0.1.10'
15
- import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.1.10'
16
- import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.1.10'
17
- import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.1.10'
18
- import { sessionLabel } from '../shared/catalog.mjs?v=0.1.10'
19
- import { resultNotification } from '../shared/result-notification.mjs?v=0.1.10'
20
- import { HarnessSync } from './harness-sync.mjs?v=0.1.10'
21
- import { LocalSync } from './local-sync.mjs?v=0.1.10'
22
- import { diagnosticPayload } from '../shared/diagnostics.mjs?v=0.1.10'
1
+ import { DuetState, PLUGIN_VERSION } from '../shared/state.mjs?v=0.2.1'
2
+ import { DuetAudio, AUDIO_STOP_PROTOCOL } from './audio.mjs?v=0.2.1'
3
+ import { HarnessRPCExecutor, rpcNavigationSession } from './rpc.mjs?v=0.2.1'
4
+ import { composerAccess, observeComposer, focusedSession, openLocalSession } from './composer.mjs?v=0.2.1'
5
+ import { startComposerBridge } from './composer-bridge.mjs?v=0.2.1'
6
+ import { mountTutorial } from './tutorial.mjs?v=0.2.1'
7
+ import { mountAvatarTasks } from './avatar-tasks.mjs'
8
+ import { tutorialAdapter } from './tutorial-adapter.mjs?v=0.2.1'
9
+ import { mountRating } from './feedback.mjs?v=0.2.1'
10
+ import { createAudioUploadConsent } from './consent.mjs?v=0.2.1'
11
+ import { bindDuetShortcuts } from './shortcuts.mjs?v=0.2.1'
12
+ import { nativeInteractions } from './interactions.mjs?v=0.2.1'
13
+ import { mountConnectionHint } from './connection-hint.mjs?v=0.2.1'
14
+ import { mountControlsLayout } from './controls-layout.mjs?v=0.2.1'
15
+ import { mountNotice } from './notice.mjs?v=0.2.1'
16
+ import { workspaceIssue, requireWorkspace, browserSessionCatalog, sessionCreationPayload } from './workspaces.mjs?v=0.2.1'
17
+ import { voiceSocketUrl, bindSettingsLink } from './transport.mjs?v=0.2.1'
18
+ import { identityFetch, identityVoiceProtocols } from './identity.mjs?v=0.2.1'
19
+ import { sessionLabel } from '../shared/catalog.mjs?v=0.2.1'
20
+ import { resultNotification } from '../shared/result-notification.mjs?v=0.2.1'
21
+ import { HarnessSync } from './harness-sync.mjs?v=0.2.1'
22
+ import { LocalSync } from './local-sync.mjs?v=0.2.1'
23
+ import { diagnosticPayload } from '../shared/diagnostics.mjs?v=0.2.1'
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]))
@@ -46,10 +53,10 @@ export function mountDuet(ctx) {
46
53
  const pageError = event => diagnostic({ event: 'browser.error', message: String(event.message || event.reason?.message || event.reason), stack: event.error?.stack || event.reason?.stack })
47
54
  window.addEventListener('error', pageError)
48
55
  window.addEventListener('unhandledrejection', pageError)
49
- const notice = (text, { upgrade = false } = {}) => {
56
+ const notice = (text, { upgrade = false, releaseNotes } = {}) => {
50
57
  connectionHint?.dismiss()
51
58
  if (upgrade) { ratingPanel?.dispose(); ratingPanel = null }
52
- notices.show(text, { upgrade })
59
+ notices.show(text, { upgrade, releaseNotes })
53
60
  }
54
61
  const draw = state => {
55
62
  if (pollGeneration !== state.generation) {
@@ -115,8 +122,12 @@ 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,
122
133
  focused: () => focusedSession(ctx),
@@ -150,6 +161,7 @@ export function mountDuet(ctx) {
150
161
  stopBridge?.(); stopBridge = null
151
162
  rpc.close()
152
163
  audio.stop()
164
+ avatar?.cancelInput()
153
165
  if (ws && ws.readyState !== WebSocket.CLOSED) {
154
166
  await new Promise(resolve => {
155
167
  const timer = setTimeout(resolve, 1200)
@@ -170,11 +182,12 @@ export function mountDuet(ctx) {
170
182
  if(!identity.ok)throw Error('voice_config_unavailable')
171
183
  requireWorkspace(ctx)
172
184
  if(closed)return
173
- 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))
174
187
  ws = new WebSocket(voiceSocketUrl({ mode, plugin_version: PLUGIN_VERSION, client_trace_id: connectionTraceId, page_id: pageId }), identityVoiceProtocols())
175
188
  ws.onopen = () => {
176
189
  report({ event: 'browser.connection_start', page_binding: 'connection_owner_v1' })
177
- send({ type: 'session.update', client: {audio_stop_protocol:AUDIO_STOP_PROTOCOL} })
190
+ send({ type: 'session.update', client: {audio_stop_protocol:AUDIO_STOP_PROTOCOL, audio_text_protocol:'audio_text_delta_v1'} })
178
191
  if (mode === 'online') stopComposer = observeComposer(ctx, composer, send)
179
192
  }
180
193
  ws.onmessage = async event => {
@@ -183,6 +196,7 @@ export function mountDuet(ctx) {
183
196
  try {
184
197
  message = JSON.parse(event.data)
185
198
  if (resultPush.event(message)) return
199
+ if(message.type==='voice.policy'){receive(message);return}
186
200
  if (message.type === 'harness.rpc.request') {
187
201
  if (mode !== 'online') throw new Error('harness_rpc_requires_online')
188
202
  await rpc.execute(message)
@@ -237,7 +251,10 @@ export function mountDuet(ctx) {
237
251
  try { audio.connectedChime() } catch { /* A notification must not break voice. */ }
238
252
  }
239
253
  }
240
- audio.event(message, send)
254
+ if (audio.event(message, send, visible => {
255
+ avatar?.event(visible); teaching?.observe(visible); receive(visible)
256
+ })) return
257
+ avatar?.event(message)
241
258
  teaching?.observe(message)
242
259
  receive(message)
243
260
  } catch (error) {
@@ -294,6 +311,12 @@ export function mountDuet(ctx) {
294
311
  dot.textContent = '.'; dot.dataset.duetMark = ''; dot.style.color = '#ed9b35'
295
312
  entry.append(dot)
296
313
  controls.append(entry)
314
+ const avatarButton=document.createElement('button')
315
+ avatarButton.type='button';avatarButton.dataset.duetAvatarToggle=''
316
+ avatarButton.style.cssText='position:relative;flex-shrink:0;border:0;border-radius:6px;background:transparent;cursor:pointer;padding:5px;display:flex'
317
+ 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>'
318
+ avatarButton.onclick=()=>avatar?.toggle()
319
+ controls.append(avatarButton)
297
320
  // Heroicons 24/outline (MIT); all controls share the same optical box/stroke.
298
321
  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"/>']]) {
299
322
  const button = document.createElement('button')
@@ -307,7 +330,7 @@ export function mountDuet(ctx) {
307
330
  // perimeter. Outer radius 6 matches the original button, not a circle.
308
331
  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>'
309
332
  button.append(ring)
310
- button.onclick = () => {
333
+ const changeMode = origin => {
311
334
  if (tutorial?.active) { notice('请先结束教学,再切换模式。'); return }
312
335
  const requestedMode = kind === 'mic' ? 'online' : 'tts_only'
313
336
  const checkWorkspace = () => {
@@ -322,19 +345,21 @@ export function mountDuet(ctx) {
322
345
  if (!checkWorkspace()) return
323
346
  // Unlock playback inside user activation, before any network await.
324
347
  const enabling = kind === 'mic' ? state.mode !== 'online' : state.mode !== 'tts_only'
325
- if (enabling) void audio.prepare().catch(() => state.fail('audio_permission_denied'))
348
+ if (enabling) { unlockPanel?.remove();unlockPanel=null;void audio.prepare().catch(() => state.fail('audio_permission_denied')) }
326
349
  const ticket = !enabling && state.ready ? state.connection?.feedbackTicket : null
327
350
  // Capture the ended connection, never consult the next session after await.
328
351
  void (async()=>{
329
352
  await (kind === 'mic' ? state.toggleMic() : state.toggleSpeaker())
330
- if(ticket && !disposed){ratingPanel?.dispose();ratingPanel=mountRating(controls,ticket)}
353
+ if(ticket && !disposed){ratingPanel?.dispose();ratingPanel=mountRating(controls,ticket,{origin})}
331
354
  })()
332
355
  }
333
356
  audioConsent.cancel()
334
357
  const mode = kind === 'mic' ? 'online' : 'tts_only'
335
- if (state.mode !== mode) audioConsent.request(activate)
358
+ if (state.mode !== mode) audioConsent.request(activate,undefined,{origin})
336
359
  else activate()
337
360
  }
361
+ button.onclick=()=>changeMode('page')
362
+ modeActions.set(kind==='mic'?'online':'tts_only',changeMode)
338
363
  controls.append(button)
339
364
  }
340
365
  const settings = document.createElement('a')
@@ -353,8 +378,23 @@ export function mountDuet(ctx) {
353
378
  connectionHint?.dispose()
354
379
  connectionHint = mountConnectionHint(controls,{onShown:hint=>reportHintShown?.(hint)})
355
380
  draw(state)
381
+ avatar?.syncToggle()
356
382
  }
357
383
  mount()
384
+ avatar = mountAvatar({controls:()=>controls, audio, state:()=>state, notice, onSurfaceAction:surfaces.action, onMenuAction:value=>avatarTasks?.action(value), focusedSession:()=>focusedSession(ctx), requestMode:mode=>{
385
+ if (!['online','tts_only'].includes(mode)) return
386
+ // Native IPC cannot grant browser user activation. First-use consent and
387
+ // audio permission remain in the owning DSH page, never bypassed by a pet.
388
+ if (state.mode !== mode && audio.context?.state !== 'running') {
389
+ unlockPanel?.remove()
390
+ unlockPanel=audioUnlockPanel({
391
+ onEnable:()=>{unlockPanel?.remove();unlockPanel=null;controls?.querySelector(`[data-voice=${mode==='online'?'mic':'speaker'}]`)?.click()},
392
+ onCancel:()=>{unlockPanel?.remove();unlockPanel=null},
393
+ })
394
+ document.body.append(unlockPanel);surfaces.sync();return
395
+ }
396
+ modeActions.get(mode)?.('avatar')
397
+ }})
358
398
  const stopShortcuts = bindDuetShortcuts(kind => controls?.querySelector(`[data-voice=${kind}]`)?.click())
359
399
  const observer = new MutationObserver(mount)
360
400
  observer.observe(document.body, { subtree: true, childList: true })
@@ -449,10 +489,18 @@ export function mountDuet(ctx) {
449
489
  if (!tutorial && controls) tutorial = mountTutorial({ controls, adapter: teaching })
450
490
  }
451
491
  mountTeaching()
492
+ avatarTasks=mountAvatarTasks({ctx,sync:localSync,avatar:()=>avatar,tutorial:()=>tutorial,settings:()=>{
493
+ closeMenuSettings?.()
494
+ const link=document.createElement('a');link.href='/duet/'
495
+ closeMenuSettings=bindSettingsLink(link,globalThis,{embedded:true});link.click()
496
+ }})
452
497
  const teachingObserver = new MutationObserver(mountTeaching)
453
498
  teachingObserver.observe(document.body, { subtree: true, childList: true })
454
499
  return () => {
455
500
  disposed = true
501
+ avatarTasks?.dispose();closeMenuSettings?.()
502
+ surfaces.dispose();unlockPanel?.remove()
503
+ avatar?.dispose()
456
504
  window.removeEventListener('pagehide', pageHide)
457
505
  pollController?.abort()
458
506
  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.10'
2
+ import { focusedSession as currentSession } from './composer.mjs?v=0.2.1'
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,
@@ -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.10'
2
+ import {normalizeGuidance} from '../shared/connection-guidance.mjs?v=0.2.1'
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.10').then(module => {
16
+ import('/duet/assets/client/browser.mjs?v=0.2.1').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
  }