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.
- package/README.md +19 -1
- package/assets/avatar/THREE-LICENSE.txt +21 -0
- package/assets/avatar/character.glb +0 -0
- package/assets/avatar/desktop/character.glb +0 -0
- package/assets/avatar/desktop/companion.mjs +18 -0
- package/assets/avatar/desktop/index.html +33 -0
- package/assets/avatar/desktop/manifest.json +10 -0
- package/assets/avatar/desktop/portrait.png +0 -0
- package/assets/avatar/desktop/renderer.mjs +4230 -0
- package/assets/avatar/portrait.png +0 -0
- package/assets/avatar/renderer.mjs +4230 -0
- package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Info.plist +36 -0
- package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/MacOS/duet-avatar +0 -0
- package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Resources/duet companion.icns +0 -0
- package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/_CodeSignature/CodeResources +128 -0
- package/desktop/bin/darwin-arm64/manifest.json +14 -0
- package/desktop/bin/win32-x64/duet-avatar.exe +0 -0
- package/desktop/bin/win32-x64/manifest.json +11 -0
- package/package.json +17 -5
- package/src/avatar/companion.html +33 -0
- package/src/avatar/companion.mjs +210 -0
- package/src/avatar/idle.mjs +9 -0
- package/src/avatar/lipsync.mjs +13 -0
- package/src/avatar/motion.mjs +93 -0
- package/src/avatar/renderer.mjs +90 -0
- package/src/avatar/surface.mjs +45 -0
- package/src/avatar/toolbar.mjs +49 -0
- package/src/client/audio.mjs +145 -10
- package/src/client/avatar-surfaces.mjs +83 -0
- package/src/client/avatar-tasks.mjs +68 -0
- package/src/client/avatar.mjs +218 -0
- package/src/client/browser.mjs +81 -33
- package/src/client/composer-bridge.mjs +5 -2
- package/src/client/composer.mjs +3 -3
- package/src/client/connection-hint.mjs +2 -1
- package/src/client/consent.mjs +3 -1
- package/src/client/controls-layout.mjs +21 -9
- package/src/client/entry.js +26 -3
- package/src/client/feedback.mjs +19 -4
- package/src/client/identity.mjs +2 -2
- package/src/client/input-effect.mjs +51 -0
- package/src/client/interactions.mjs +5 -1
- package/src/client/notice.mjs +1 -0
- package/src/client/rpc.mjs +23 -5
- package/src/client/settings.html +78 -4
- package/src/client/transport.mjs +2 -2
- package/src/client/tutorial-adapter.mjs +4 -4
- package/src/client/tutorial.mjs +5 -3
- package/src/host/assets.mjs +12 -0
- package/src/host/avatar-activity.mjs +24 -0
- package/src/host/avatar-assets.mjs +18 -0
- package/src/host/avatar.mjs +130 -0
- package/src/host/diagnostics.mjs +111 -7
- package/src/host/feedback-files.mjs +5 -1
- package/src/host/plugin.mjs +67 -4
- package/src/host/proxy.mjs +16 -6
- package/src/host/settings-migration.mjs +2 -1
- package/src/host/settings.mjs +19 -4
- package/src/host/stop-task.mjs +37 -0
- package/src/shared/avatar-activity.mjs +33 -0
- package/src/shared/avatar-menu-ui.mjs +85 -0
- package/src/shared/avatar-menu.mjs +83 -0
- package/src/shared/avatar-surface.mjs +24 -0
- package/src/shared/avatar-ui.mjs +91 -0
- package/src/shared/avatar.mjs +125 -0
- package/src/shared/nickname.mjs +13 -0
- package/src/shared/state.mjs +1 -1
package/src/client/feedback.mjs
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
/** Optional, explicit rating; never opens voice or submits without a user click. */
|
|
2
|
-
import { identityFetch } from './identity.mjs?v=0.
|
|
2
|
+
import { identityFetch } from './identity.mjs?v=0.2.0'
|
|
3
3
|
|
|
4
|
-
export function mountRating(anchor, sessionTicket) {
|
|
4
|
+
export function mountRating(anchor, sessionTicket, {origin='page'} = {}) {
|
|
5
5
|
if(!sessionTicket)return null
|
|
6
6
|
const panel=document.createElement('section')
|
|
7
|
+
// Page ratings are never eligible for avatar projection, including older bridges.
|
|
8
|
+
if(origin==='avatar')panel.dataset.duetAvatarSurface='60'
|
|
9
|
+
panel.dataset.duetSurfaceOrigin=origin
|
|
7
10
|
panel.setAttribute('role','region');panel.setAttribute('aria-label','本次语音体验评分')
|
|
8
11
|
panel.style.cssText='position:fixed;z-index:100020;width:min(300px,calc(100vw - 24px));box-sizing:border-box;background:#17212f;color:#edf3ff;border:1px solid #52647d;border-radius:16px;padding:16px;box-shadow:0 12px 40px #0006;font:14px/1.6 system-ui'
|
|
9
12
|
const title=document.createElement('h3');title.textContent='这次语音体验怎么样?';title.style.margin='0 0 10px';panel.append(title)
|
|
@@ -19,10 +22,22 @@ export function mountRating(anchor, sessionTicket) {
|
|
|
19
22
|
const submit=document.createElement('button');submit.type='button';submit.textContent='提交评分';submit.disabled=true
|
|
20
23
|
submit.style.cssText='border:0;border-radius:8px;background:#b3e9cb;color:#152a1e;padding:8px 14px;cursor:pointer'
|
|
21
24
|
const skip=document.createElement('button');skip.type='button';skip.textContent='暂不评价(10s)';skip.style.cssText='border:0;background:transparent;color:#b9c9dc;padding:8px 14px;cursor:pointer'
|
|
25
|
+
skip.dataset.duetLiveText='';skip.setAttribute('aria-label','暂不评价')
|
|
22
26
|
const position=()=>{
|
|
23
27
|
const rect=anchor.getBoundingClientRect(),box=panel.getBoundingClientRect()
|
|
24
|
-
|
|
25
|
-
|
|
28
|
+
let left=Math.max(12,Math.min(rect.left,innerWidth-box.width-12))
|
|
29
|
+
let top=rect.top>=box.height+20?rect.top-box.height-12:rect.bottom+12
|
|
30
|
+
const avatar=origin==='page'?document.querySelector('[data-duet-avatar]:not([hidden])'):null
|
|
31
|
+
if(avatar){
|
|
32
|
+
const a=avatar.getBoundingClientRect()
|
|
33
|
+
if(left<a.right&&left+box.width>a.left&&top<a.bottom&&top+box.height>a.top){
|
|
34
|
+
if(Math.max(rect.right,a.right)+12+box.width<=innerWidth-12)left=Math.max(rect.right,a.right)+12
|
|
35
|
+
else if(Math.min(rect.left,a.left)-box.width-12>=12)left=Math.min(rect.left,a.left)-box.width-12
|
|
36
|
+
else top=a.top>=box.height+24?a.top-box.height-12:a.bottom+12
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
panel.style.left=left+'px'
|
|
40
|
+
panel.style.top=Math.max(12,Math.min(top,innerHeight-box.height-12))+'px'
|
|
26
41
|
}
|
|
27
42
|
let countdown,timeout
|
|
28
43
|
const dispose=()=>{disposed=true;clearInterval(countdown);clearTimeout(timeout);clearTimeout(requestTimeout);requestController?.abort();panel.remove();document.removeEventListener('keydown',onKey);window.removeEventListener('resize',position);window.removeEventListener('scroll',position,true)}
|
package/src/client/identity.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { IDENTITY_HEADER, IDENTITY_TRANSPORT_HEADER, IDENTITY_TRANSPORT, IDENTITY_STORAGE,
|
|
2
|
-
VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.
|
|
2
|
+
VOICE_PROTOCOL, IDENTITY_PROTOCOL_PREFIX, validIdentityToken } from '../shared/identity.mjs?v=0.2.0'
|
|
3
3
|
|
|
4
4
|
/** Desktop strips plugin cookies. Keep the Host-signed value in its origin storage. */
|
|
5
5
|
export function createIdentityClient(globals = globalThis) {
|
|
@@ -10,7 +10,7 @@ export function createIdentityClient(globals = globalThis) {
|
|
|
10
10
|
}
|
|
11
11
|
async function fetchIdentity(path, options = {}) {
|
|
12
12
|
if (!desktop()) return globals.fetch(path, options)
|
|
13
|
-
if (!['/duplex-control/api/voice/config', '/duplex-control/api/feedback'].includes(path)) {
|
|
13
|
+
if (!['/duplex-control/api/voice/config', '/duplex-control/api/feedback', '/duplex-control/api/duet/nickname', '/duplex-control/api/avatar/activity'].includes(path)) {
|
|
14
14
|
return globals.fetch(path, options)
|
|
15
15
|
}
|
|
16
16
|
const config = path.endsWith('/voice/config') && (!options.method || options.method === 'GET')
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/** Local, post-commit feedback only. Never delays a write or submits a draft. */
|
|
2
|
+
export function mountInputEffect({anchor, isCurrent, target = composerTarget}) {
|
|
3
|
+
let current, disposed=false
|
|
4
|
+
const clear=()=>{
|
|
5
|
+
const item=current;current=null
|
|
6
|
+
if(!item)return
|
|
7
|
+
clearTimeout(item.timer);clearInterval(item.watch);item.animation?.cancel();item.node.remove()
|
|
8
|
+
}
|
|
9
|
+
const show=(text,sessionId)=>{
|
|
10
|
+
clear()
|
|
11
|
+
if(disposed || !text || !isCurrent(sessionId) || document.hidden)return
|
|
12
|
+
const source=anchor()?.getBoundingClientRect()
|
|
13
|
+
if(!source || !source.width || !source.height)return
|
|
14
|
+
const node=document.createElement('div');node.dataset.duetInputEffect='';node.dataset.phase='preview'
|
|
15
|
+
node.setAttribute('role','status');node.setAttribute('aria-label','已写入输入框')
|
|
16
|
+
node.style.cssText='position:fixed;z-index:100020;pointer-events:none;box-sizing:border-box;width:260px;max-width:calc(100vw - 16px);padding:11px 13px;border:1px solid #7cb8e566;border-radius:15px;background:light-dark(#eef8ff,#172d40);color:light-dark(#194a6a,#e0f2ff);color-scheme:light dark;box-shadow:0 8px 26px #0002;display:flex;gap:9px;align-items:flex-start;font:13px/1.6 system-ui;transform-origin:center'
|
|
17
|
+
const icon=document.createElement('span')
|
|
18
|
+
icon.innerHTML='<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="2" y="5" width="20" height="14" rx="3"/><path d="M6 9h.01M10 9h.01M14 9h.01M18 9h.01M6 12h.01M10 12h.01M14 12h.01M18 12h.01M7 15h10"/></svg>'
|
|
19
|
+
const words=document.createElement('span');words.dataset.duetInputText=''
|
|
20
|
+
words.style.cssText='min-width:0;max-height:126px;overflow:hidden;white-space:pre-wrap;overflow-wrap:anywhere'
|
|
21
|
+
words.textContent=text.length>600?text.slice(0,600)+'…':text
|
|
22
|
+
node.append(icon,words);document.body.append(node)
|
|
23
|
+
node.style.left=`${Math.max(8,Math.min(source.left,innerWidth-node.offsetWidth-8))}px`
|
|
24
|
+
node.style.top=`${Math.max(8,Math.min(source.top-node.offsetHeight-10,innerHeight-node.offsetHeight-8))}px`
|
|
25
|
+
const item=current={node,animation:null}
|
|
26
|
+
item.watch=setInterval(()=>{if(!isCurrent(sessionId)||document.hidden)clear()},100)
|
|
27
|
+
item.timer=setTimeout(()=>{
|
|
28
|
+
if(current!==item || !isCurrent(sessionId)){clear();return}
|
|
29
|
+
const destination=target(),to=destination?.getBoundingClientRect(),from=node.getBoundingClientRect()
|
|
30
|
+
const visible=to&&to.width>0&&to.height>0&&to.bottom>0&&to.top<innerHeight&&to.right>0&&to.left<innerWidth
|
|
31
|
+
const dx=visible?to.left+to.width/2-from.left-from.width/2:0
|
|
32
|
+
const dy=visible?to.top+to.height/2-from.top-from.height/2:-10
|
|
33
|
+
node.dataset.phase=visible?'flying':'fading'
|
|
34
|
+
item.animation=node.animate([
|
|
35
|
+
{transform:'translate(0,0) scale(1)',opacity:1},
|
|
36
|
+
{transform:`translate(${dx}px,${dy}px) scale(${visible?.12:.98})`,opacity:0},
|
|
37
|
+
],{duration:visible?520:220,easing:'cubic-bezier(.4,0,.3,1)',fill:'forwards'})
|
|
38
|
+
item.animation.finished.then(()=>{if(current===item)clear()},()=>{})
|
|
39
|
+
},900)
|
|
40
|
+
}
|
|
41
|
+
return {show,clear,dispose(){disposed=true;clear()}}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Only known DSH composer surfaces; never select a search/settings field. */
|
|
45
|
+
export function composerTarget() {
|
|
46
|
+
const nodes=[...document.querySelectorAll('[data-composer-input]')].filter(node=>{
|
|
47
|
+
const r=node.getBoundingClientRect(),s=getComputedStyle(node)
|
|
48
|
+
return r.width>0&&r.height>0&&r.bottom>0&&r.top<innerHeight&&s.visibility!=='hidden'&&s.display!=='none'
|
|
49
|
+
})
|
|
50
|
+
return nodes.find(node=>node===document.activeElement||node.contains(document.activeElement)) || (nodes.length===1?nodes[0]:null)
|
|
51
|
+
}
|
|
@@ -26,7 +26,11 @@ export function nativeInteractions(ctx) {
|
|
|
26
26
|
if (value.kind === 'approval') {
|
|
27
27
|
if (!['allowed-once', 'rejected'].includes(payload.outcome)) throw Error('invalid_approval_outcome')
|
|
28
28
|
await value.answer(payload.outcome)
|
|
29
|
-
} else if (payload.cancelled === true)
|
|
29
|
+
} else if (payload.cancelled === true) {
|
|
30
|
+
if (typeof value.cancel === 'function') await value.cancel()
|
|
31
|
+
else if (value.dismissal === 'cancel' && typeof value.dismiss === 'function') await value.dismiss()
|
|
32
|
+
else throw Object.assign(Error('当前问题不能直接取消,请在 DSH 中处理。'), {code:'question_cancel_unavailable'})
|
|
33
|
+
}
|
|
30
34
|
else {
|
|
31
35
|
if (!Array.isArray(payload.answers)) throw Error('invalid_question_answers')
|
|
32
36
|
await value.answer({ answers: payload.answers })
|
package/src/client/notice.mjs
CHANGED
package/src/client/rpc.mjs
CHANGED
|
@@ -1,14 +1,17 @@
|
|
|
1
1
|
/** Reverse RPC executes on this authenticated DSH origin, never a supplied URL. */
|
|
2
2
|
import { orderSessionCatalog, readWorkspaceView } from '../shared/catalog.mjs'
|
|
3
3
|
const MAX_BYTES = 2_000_000
|
|
4
|
-
|
|
5
|
-
const
|
|
4
|
+
// Only colons may be escaped in a session segment: never decode arbitrary paths.
|
|
5
|
+
const SESSION = '(?:[A-Za-z0-9_:-]|%3[Aa]){1,256}'
|
|
6
|
+
const READ = new RegExp(`^/api/(?:health|sessions|jobs|results|interactions|composer/focused|sessions/${SESSION}/(?:composer|execution))$`)
|
|
7
|
+
const WRITE = new RegExp(`^/api/(?:duet/nickname|sessions|sessions/${SESSION}/(?:composer/submit|activate|rename|fork|cancel)|interactions/(?:(?:question|approval)(?::|%3[Aa])(?:[A-Za-z0-9_:-]|%3[Aa]){1,1024}|[A-Za-z0-9_-]{1,256})/respond)$`)
|
|
8
|
+
const sessionRoute = (path, suffix) => new RegExp(`^/api/sessions/${SESSION}/${suffix}$`).test(path)
|
|
6
9
|
|
|
7
10
|
// Navigate only the connection-owning page after a successful mutation.
|
|
8
11
|
export function rpcNavigationSession(request, body) {
|
|
9
12
|
if (request.method !== 'POST') return null
|
|
10
|
-
if (
|
|
11
|
-
if (request.path === '/api/sessions' ||
|
|
13
|
+
if (sessionRoute(request.path, 'activate')) return body.active_session_id
|
|
14
|
+
if (request.path === '/api/sessions' || sessionRoute(request.path, 'fork')) return body.session?.session_id
|
|
12
15
|
return null
|
|
13
16
|
}
|
|
14
17
|
|
|
@@ -17,8 +20,12 @@ export function validateRPC(request) {
|
|
|
17
20
|
|| !/^[a-f0-9]{32}$/.test(request.connection_id || '')) throw new Error('invalid_harness_rpc')
|
|
18
21
|
if (!((request.method === 'GET' && READ.test(request.path))
|
|
19
22
|
|| (request.method === 'POST' && WRITE.test(request.path))
|
|
20
|
-
|| (request.method === 'PUT' &&
|
|
23
|
+
|| (request.method === 'PUT' && sessionRoute(request.path, 'composer')))) throw new Error('harness_rpc_route_not_allowed')
|
|
21
24
|
if (new TextEncoder().encode(JSON.stringify(request)).length > MAX_BYTES) throw new Error('harness_rpc_too_large')
|
|
25
|
+
if (sessionRoute(request.path, 'cancel') && (typeof request.payload?.execution_id !== 'string'
|
|
26
|
+
|| !/^[a-f0-9-]{36}$/.test(request.payload.execution_id)
|
|
27
|
+
|| typeof request.payload.require_focus !== 'boolean'
|
|
28
|
+
|| Object.keys(request.payload).some(k => !['execution_id','require_focus'].includes(k)))) throw new Error('invalid_stop_request')
|
|
22
29
|
if (request.params != null) {
|
|
23
30
|
const focus = /\/composer$/.test(request.path) && JSON.stringify(request.params) === '{"require_focus":"true"}'
|
|
24
31
|
const results = request.path === '/api/results' && typeof request.params === 'object'
|
|
@@ -73,6 +80,13 @@ export class HarnessRPCExecutor {
|
|
|
73
80
|
const envelope = { type: 'harness.rpc.response', connection_id: request.connection_id, request_id: request.request_id }
|
|
74
81
|
try {
|
|
75
82
|
let payload = request.payload ?? {}
|
|
83
|
+
if (sessionRoute(request.path, '(?:execution|cancel)')) {
|
|
84
|
+
if (!this.stopSupported || !this.binding.id) return { ...envelope, status:409,
|
|
85
|
+
body:{error_code:'harness_stop_task_upgrade_required'} }
|
|
86
|
+
const id = decodeURIComponent(request.path.split('/')[3])
|
|
87
|
+
if (payload.require_focus && this.binding.focused?.() !== id) return { ...envelope, status:409,
|
|
88
|
+
body:{error_code:'focus_conflict'} }
|
|
89
|
+
}
|
|
76
90
|
if (request.method === 'POST' && request.path === '/api/sessions' && this.binding.creationPayload) {
|
|
77
91
|
try { payload = this.binding.creationPayload(payload) }
|
|
78
92
|
catch (error) { return { ...envelope, status: 409, body: { error_code: error.code || error.message || 'workspace_selection_required' } } }
|
|
@@ -104,7 +118,11 @@ export class HarnessRPCExecutor {
|
|
|
104
118
|
controller.signal.throwIfAborted()
|
|
105
119
|
if (response.ok && this.binding.completed) await this.binding.completed(request, body, controller.signal)
|
|
106
120
|
if (response.status === 200 && request.method === 'GET' && request.path === '/api/sessions' && Array.isArray(body.sessions)) {
|
|
121
|
+
this.stopSupported = body.duet_rpc_capabilities?.includes('stop_task_v1') === true
|
|
122
|
+
&& typeof this.binding.focused === 'function'
|
|
107
123
|
body.duet_rpc_capabilities = ['create_session_v1',
|
|
124
|
+
...(body.duet_rpc_capabilities?.includes('rename_duet_v1') ? ['rename_duet_v1'] : []),
|
|
125
|
+
...(this.stopSupported ? ['stop_task_v1'] : []),
|
|
108
126
|
...(this.binding.syncSupported?.() === false ? [] : ['harness_sync_v1'])]
|
|
109
127
|
// Both startup prompt and nth_N resolution read this same browser-local
|
|
110
128
|
// order, including manual drag order; archived rows cannot consume ranks.
|
package/src/client/settings.html
CHANGED
|
@@ -89,6 +89,25 @@
|
|
|
89
89
|
<div id="settingsMessage" role="status" style="margin-top:10px"></div>
|
|
90
90
|
</details>
|
|
91
91
|
</section>
|
|
92
|
+
<section class="panel" style="margin-bottom:18px">
|
|
93
|
+
<h2>助手昵称</h2>
|
|
94
|
+
<label for="assistantNickname">给助手起个名字</label>
|
|
95
|
+
<input id="assistantNickname" type="text" placeholder="duet" autocomplete="off">
|
|
96
|
+
<p class="section-note">最多 5 个汉字或 2 个英文单词;中英文混用时最多 5 个字符。</p>
|
|
97
|
+
<button id="saveNickname" type="button" disabled>保存昵称</button>
|
|
98
|
+
<p id="nicknameStatus" class="muted" role="status" aria-live="polite"></p>
|
|
99
|
+
</section>
|
|
100
|
+
<section class="panel" style="margin-bottom:18px">
|
|
101
|
+
<h2>3D 形象</h2>
|
|
102
|
+
<label><input id="avatarEnabled" type="checkbox" style="width:auto"> 打开3D形象(实验)</label>
|
|
103
|
+
<label><input id="avatarWebOnly" type="checkbox" style="width:auto"> 仅在网页端显示(适用于dsh装在服务器)</label>
|
|
104
|
+
<label for="avatarSize">形象大小</label>
|
|
105
|
+
<button id="avatarSize" type="button" style="display:inline-flex;align-items:center;gap:10px;width:auto"></button>
|
|
106
|
+
<p class="section-note">形象可以陪伴在桌面上,也可以显示在 duet 栏上方。打开形象不会开启语音。</p>
|
|
107
|
+
<p id="avatarPresentationStatus" class="muted" role="status">当前显示:等待 DSH 页面连接</p>
|
|
108
|
+
<button id="avatarRetryDesktop" type="button" hidden>重试桌面显示</button>
|
|
109
|
+
<p id="avatarSettingsStatus" class="muted" role="status"></p>
|
|
110
|
+
</section>
|
|
92
111
|
<section class="panel" style="margin-bottom:18px">
|
|
93
112
|
<h2>麦克风</h2>
|
|
94
113
|
<label for="microphoneDevice">交互模式使用的设备</label>
|
|
@@ -152,13 +171,46 @@
|
|
|
152
171
|
<footer><span>duet / DeepSeek Harness</span></footer>
|
|
153
172
|
</main>
|
|
154
173
|
<script type="module">
|
|
155
|
-
import {
|
|
174
|
+
import { AVATAR_KEY, AVATAR_PRESENTATION_LABELS, avatarPreferences, saveAvatarPreferences } from '/duet/assets/shared/avatar.mjs';
|
|
175
|
+
import { sizeButton, nextAvatarSize, avatarCloseConfirmation } from '/duet/assets/shared/avatar-ui.mjs';
|
|
176
|
+
const avatarConfirm=avatarCloseConfirmation();
|
|
177
|
+
const avatarChannel = typeof BroadcastChannel==='undefined'?null:new BroadcastChannel(AVATAR_KEY);
|
|
178
|
+
const avatarRead = () => {const p=avatarPreferences();document.getElementById('avatarEnabled').checked=p.enabled;document.getElementById('avatarWebOnly').checked=p.webOnly;sizeButton(document.getElementById('avatarSize'),p.size,{label:true});};
|
|
179
|
+
avatarRead();
|
|
180
|
+
const avatarStorage=e=>{if(e.key===AVATAR_KEY)avatarRead();};
|
|
181
|
+
window.addEventListener('storage',avatarStorage);
|
|
182
|
+
if(avatarChannel){
|
|
183
|
+
avatarChannel.onmessage=e=>{
|
|
184
|
+
avatarRead()
|
|
185
|
+
const mode=e.data?.type==='presentation'?e.data.mode:null
|
|
186
|
+
if(Object.hasOwn(AVATAR_PRESENTATION_LABELS,mode)){
|
|
187
|
+
document.getElementById('avatarPresentationStatus').textContent=AVATAR_PRESENTATION_LABELS[mode]
|
|
188
|
+
document.getElementById('avatarRetryDesktop').hidden=!['recovering','fallback','unavailable'].includes(mode)
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
avatarChannel.postMessage({type:'presentation_request'})
|
|
192
|
+
}
|
|
193
|
+
document.getElementById('avatarRetryDesktop').onclick=()=>avatarChannel?.postMessage({type:'retry_desktop'});
|
|
194
|
+
const avatarSave=patch=>{
|
|
195
|
+
try {saveAvatarPreferences({...avatarPreferences(),...patch});avatarRead();avatarChannel?.postMessage('changed');document.getElementById('avatarSettingsStatus').textContent='已保存';}
|
|
196
|
+
catch {document.getElementById('avatarSettingsStatus').textContent='设置未保存,请检查浏览器存储权限。';avatarRead();}
|
|
197
|
+
};
|
|
198
|
+
document.getElementById('avatarSize').onclick=()=>avatarSave({size:nextAvatarSize(avatarPreferences().size)});
|
|
199
|
+
document.getElementById('avatarWebOnly').onchange=e=>avatarSave({webOnly:e.target.checked});
|
|
200
|
+
document.getElementById('avatarEnabled').onchange=async e=>{
|
|
201
|
+
const enabled=e.target.checked;avatarRead();
|
|
202
|
+
if(enabled||await avatarConfirm.ask())avatarSave({enabled});
|
|
203
|
+
};
|
|
204
|
+
window.addEventListener('pagehide',()=>{avatarConfirm.dispose();avatarChannel?.close();window.removeEventListener('storage',avatarStorage);},{once:true});
|
|
205
|
+
import { identityFetch } from '/duet/assets/client/identity.mjs?v=0.2.0';
|
|
156
206
|
const base = "/duplex-control/api";
|
|
157
207
|
let debugEnabled = false, settingsRevision = null, feedbackSubmitting = false;
|
|
208
|
+
let nicknameDirty = false, nicknameRevision = null;
|
|
158
209
|
const composerChannel = typeof BroadcastChannel === "undefined" ? null : new BroadcastChannel("dsh-duplex-control-v1");
|
|
159
210
|
const composerPending = new Map();
|
|
160
211
|
const sessionLabels = new Map();
|
|
161
212
|
const $ = id => document.getElementById(id);
|
|
213
|
+
$('assistantNickname').oninput = () => { nicknameDirty = true; };
|
|
162
214
|
const escapeHtml = value => String(value ?? "").replace(/[&<>"']/g, c => ({"&":"&","<":"<",">":">",'"':""","'":"'"}[c]));
|
|
163
215
|
async function api(path, options = {}) {
|
|
164
216
|
const response = await identityFetch(base + path, {headers:{"Content-Type":"application/json"}, ...options});
|
|
@@ -291,6 +343,8 @@
|
|
|
291
343
|
async function refresh() { try { await Promise.all([loadSessions(), loadJobs()]); } catch (error) { showMessage(error.message, true); } }
|
|
292
344
|
async function loadDuetConfig(fill = false) {
|
|
293
345
|
const config = await api('/voice/config');
|
|
346
|
+
$('avatarWebOnly').disabled = config.avatar?.web_only === true;
|
|
347
|
+
if (config.avatar?.web_only) $('avatarWebOnly').checked = true;
|
|
294
348
|
showConnectionStatus(config);
|
|
295
349
|
const c = config.connection || {};
|
|
296
350
|
$('duetMark').style.color = c.online || c.tts_only ? '#7fd6a6' : '#ed9b35';
|
|
@@ -304,9 +358,15 @@
|
|
|
304
358
|
settingsRevision = config.revision;
|
|
305
359
|
$('backendUrl').value = config.backend_url || '';
|
|
306
360
|
}
|
|
361
|
+
if (fill || !nicknameDirty) {
|
|
362
|
+
nicknameRevision = config.revision;
|
|
363
|
+
$('assistantNickname').value = config.nickname || '';
|
|
364
|
+
nicknameDirty = false;
|
|
365
|
+
}
|
|
307
366
|
$('authState').textContent = config.backend_url ? '已配置' : '待配置';
|
|
308
367
|
$('pluginVersion').textContent = config.plugin_version || '—';
|
|
309
368
|
$('saveDuet').disabled = false;
|
|
369
|
+
$('saveNickname').disabled = false;
|
|
310
370
|
$('submitFeedback').disabled = feedbackSubmitting || config.feedback_enabled !== true;
|
|
311
371
|
if(config.feedback_enabled !== true)$('feedbackStatus').textContent = '反馈暂时不可用,请稍后再试。';
|
|
312
372
|
else if($('feedbackStatus').textContent.startsWith('正在检查') || $('feedbackStatus').textContent.startsWith('反馈暂时'))$('feedbackStatus').textContent = '';
|
|
@@ -337,6 +397,20 @@
|
|
|
337
397
|
} catch (error) { $('settingsMessage').textContent = debugEnabled ? `保存失败:${error.message}` : '保存失败,请稍后重试。'; }
|
|
338
398
|
finally { $('saveDuet').disabled = false; }
|
|
339
399
|
};
|
|
400
|
+
$('saveNickname').onclick = async () => {
|
|
401
|
+
$('saveNickname').disabled = true;
|
|
402
|
+
try {
|
|
403
|
+
const result = await api('/duet/nickname', {method:'POST',
|
|
404
|
+
headers:{'Content-Type':'application/json','X-Duplex-Settings':'1'},
|
|
405
|
+
body:JSON.stringify({nickname:$('assistantNickname').value, revision:nicknameRevision})});
|
|
406
|
+
if (!result.ok) { $('nicknameStatus').textContent = result.reason || '昵称保存失败,请重试'; return; }
|
|
407
|
+
settingsRevision = result.revision;
|
|
408
|
+
nicknameRevision = result.revision; nicknameDirty = false;
|
|
409
|
+
$('assistantNickname').value = result.nickname;
|
|
410
|
+
$('nicknameStatus').textContent = '已保存,下次开启语音时使用这个昵称。';
|
|
411
|
+
} catch { $('nicknameStatus').textContent = '昵称保存失败,请重试'; }
|
|
412
|
+
finally { $('saveNickname').disabled = false; }
|
|
413
|
+
};
|
|
340
414
|
async function loadNotices() {
|
|
341
415
|
const target = $('announcements');
|
|
342
416
|
try {
|
|
@@ -363,7 +437,7 @@
|
|
|
363
437
|
}
|
|
364
438
|
$('openTutorial').onclick = async () => {
|
|
365
439
|
try {
|
|
366
|
-
const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.
|
|
440
|
+
const {requestTutorial} = await import('/duet/assets/client/tutorial-request.mjs?v=0.2.0');
|
|
367
441
|
requestTutorial(localStorage);
|
|
368
442
|
$('tutorialStatus').textContent = '请回到 DSH 页面继续教学。';
|
|
369
443
|
} catch { $('tutorialStatus').textContent = '暂时无法打开教学,请允许浏览器存储后重试。'; }
|
|
@@ -372,11 +446,11 @@
|
|
|
372
446
|
setInterval(() => { loadDuetConfig().catch(showConnectionUnavailable); }, 2000);
|
|
373
447
|
void loadNotices();
|
|
374
448
|
setInterval(loadNotices, 60000);
|
|
375
|
-
import('/duet/assets/client/shortcuts.mjs?v=0.
|
|
449
|
+
import('/duet/assets/client/shortcuts.mjs?v=0.2.0').then(({mountShortcutSettings}) => {
|
|
376
450
|
const dispose = mountShortcutSettings({speaker:$('speakerShortcut'),mic:$('micShortcut'),clearSpeaker:$('clearSpeakerShortcut'),clearMic:$('clearMicShortcut'),status:$('shortcutStatus')});
|
|
377
451
|
window.addEventListener('pagehide', e => {if(!e.persisted)dispose()}, {once:true});
|
|
378
452
|
}).catch(() => { $('shortcutStatus').textContent = '暂时无法加载快捷键设置,请刷新重试。'; });
|
|
379
|
-
import('/duet/assets/client/microphone.mjs?v=0.
|
|
453
|
+
import('/duet/assets/client/microphone.mjs?v=0.2.0').then(({mountMicrophoneSettings}) => {
|
|
380
454
|
const dispose = mountMicrophoneSettings({select:$('microphoneDevice'),refresh:$('refreshMicrophones'),status:$('microphoneStatus')});
|
|
381
455
|
window.addEventListener('pagehide', dispose, {once:true});
|
|
382
456
|
}).catch(() => { $('microphoneStatus').textContent = '暂时无法加载麦克风设置,请刷新重试。'; });
|
package/src/client/transport.mjs
CHANGED
|
@@ -12,8 +12,8 @@ export function voiceSocketUrl(params, globals = globalThis, path = 'duplex-cont
|
|
|
12
12
|
}
|
|
13
13
|
|
|
14
14
|
/** Desktop refuses custom-protocol popups; keep settings in the owned window. */
|
|
15
|
-
export function bindSettingsLink(link, globals = globalThis) {
|
|
16
|
-
if (globals.location.protocol !== 'dsh-app:') return () => {}
|
|
15
|
+
export function bindSettingsLink(link, globals = globalThis, {embedded=false} = {}) {
|
|
16
|
+
if (!embedded && globals.location.protocol !== 'dsh-app:') return () => {}
|
|
17
17
|
let dialog
|
|
18
18
|
const close = () => { dialog?.close(); dialog?.remove(); dialog = null }
|
|
19
19
|
const open = event => {
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/** DSH browser services plus existing voice connection; never opens a microphone. */
|
|
2
|
-
import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.
|
|
3
|
-
import { focusedSession } from './composer.mjs?v=0.
|
|
4
|
-
import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.
|
|
5
|
-
import { startComposerBridge } from './composer-bridge.mjs?v=0.
|
|
2
|
+
import { PLUGIN_VERSION } from '../shared/state.mjs?v=0.2.0'
|
|
3
|
+
import { focusedSession } from './composer.mjs?v=0.2.0'
|
|
4
|
+
import { sessionCreationPayload, workspaceIssue } from './workspaces.mjs?v=0.2.0'
|
|
5
|
+
import { startComposerBridge } from './composer-bridge.mjs?v=0.2.0'
|
|
6
6
|
export function tutorialAdapter(ctx, state, audio, pollReady, startBridge = startComposerBridge) {
|
|
7
7
|
let narration
|
|
8
8
|
const completed = new Map()
|
package/src/client/tutorial.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Opt-in walkthrough. All writes are limited to sessions created by this run. */
|
|
2
|
-
import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.
|
|
2
|
+
import {consumeTutorialRequest} from './tutorial-request.mjs?v=0.2.0'
|
|
3
3
|
export const TUTORIAL_KEY = 'dsh-duplex-tutorial-v1'
|
|
4
4
|
export const QUESTION = '什么是语音交互?请用一句话简单解释,不使用工具。'
|
|
5
5
|
export const INPUT = '用一句话介绍语音助手。'
|
|
@@ -113,7 +113,7 @@ export class TutorialRun {
|
|
|
113
113
|
}
|
|
114
114
|
}
|
|
115
115
|
|
|
116
|
-
export function mountTutorial({ controls, adapter }) {
|
|
116
|
+
export function mountTutorial({ controls, adapter, origin='page' }) {
|
|
117
117
|
const element = (tag, text, parent) => { const n = document.createElement(tag); if (text) n.textContent = text; parent?.append(n); return n }
|
|
118
118
|
let run, closed = false, panel, highlight, pointer, lockRelease, active = false
|
|
119
119
|
const get = (store, key) => { try { return store.getItem(key) } catch { return null } }
|
|
@@ -166,6 +166,7 @@ export function mountTutorial({ controls, adapter }) {
|
|
|
166
166
|
document.body.append(pointer)
|
|
167
167
|
}
|
|
168
168
|
panel=element('section',null,document.body); panel.className='duet-tutorial'; panel.setAttribute('role','region'); panel.setAttribute('aria-label','duet 使用教学')
|
|
169
|
+
panel.dataset.duetAvatarSurface='80';panel.dataset.duetSurfaceOrigin=origin;panel.dataset.duetSurfaceTarget=selector?.includes('speaker')?'tts_only':selector?.includes('mic')?'online':''
|
|
169
170
|
element('small', finished?'duet':active ? 'duet / GUIDED TOUR · 可随时退出' : 'WELCOME TO duet',panel)
|
|
170
171
|
element('h3',title,panel); element('p',text,panel)
|
|
171
172
|
const footer=element('footer',null,panel)
|
|
@@ -260,9 +261,10 @@ export function mountTutorial({ controls, adapter }) {
|
|
|
260
261
|
void adapter.unlock().then(()=>{if(!closed&&view.panel.isConnected)return start(consent)}).catch(fail)
|
|
261
262
|
},true)
|
|
262
263
|
b.disabled=true;sound.onchange=chat.onchange=()=>{b.disabled=!(sound.checked&&chat.checked)}
|
|
264
|
+
b.dataset.duetUserGesture=''
|
|
263
265
|
position()
|
|
264
266
|
}
|
|
265
|
-
const open = () => { if(!active)welcome() }
|
|
267
|
+
const open = (options={}) => { if(!active){origin=options.origin==='avatar'?'avatar':'page';welcome()} }
|
|
266
268
|
const onKey=e=>{if(e.key==='Escape'&&panel)void dismiss()}
|
|
267
269
|
window.addEventListener('resize',position);window.addEventListener('scroll',position,true);window.addEventListener('keydown',onKey)
|
|
268
270
|
const layoutTimer=setInterval(position,300)
|
package/src/host/assets.mjs
CHANGED
|
@@ -18,6 +18,13 @@ const modules = {
|
|
|
18
18
|
workspaces: 'client/workspaces',
|
|
19
19
|
transport: 'client/transport',
|
|
20
20
|
identity: 'client/identity', identity_protocol: 'shared/identity',
|
|
21
|
+
avatar: 'client/avatar', avatar_protocol: 'shared/avatar',
|
|
22
|
+
avatar_activity: 'shared/avatar-activity',
|
|
23
|
+
avatar_ui: 'shared/avatar-ui',
|
|
24
|
+
avatar_menu: 'shared/avatar-menu', avatar_menu_ui: 'shared/avatar-menu-ui',
|
|
25
|
+
avatar_tasks: 'client/avatar-tasks',
|
|
26
|
+
avatar_surface: 'shared/avatar-surface', avatar_surfaces: 'client/avatar-surfaces',
|
|
27
|
+
input_effect: 'client/input-effect',
|
|
21
28
|
}
|
|
22
29
|
const aliases = {
|
|
23
30
|
state: 'DuetState as VoiceState', audio: 'DuetAudio as VoiceAudio',
|
|
@@ -26,6 +33,11 @@ const aliases = {
|
|
|
26
33
|
const publicModules = new Set(Object.values(modules))
|
|
27
34
|
|
|
28
35
|
export function publicAsset(pathname) {
|
|
36
|
+
const avatar = { '/duet/avatar/renderer.mjs':['renderer.mjs','text/javascript; charset=utf-8'],
|
|
37
|
+
'/duet/avatar/character.glb':['character.glb','model/gltf-binary'],
|
|
38
|
+
'/duet/avatar/portrait.png':['portrait.png','image/png'] }[pathname]
|
|
39
|
+
if (avatar) return {url:new URL(`../../assets/avatar/${avatar[0]}`,import.meta.url),contentType:avatar[1],
|
|
40
|
+
cacheControl:avatar[0].endsWith('.mjs')?'no-store':'private, max-age=3600'}
|
|
29
41
|
const modern = pathname.match(/^\/duet\/assets\/(client|shared)\/([a-z-]+)\.mjs$/)
|
|
30
42
|
if (modern && publicModules.has(`${modern[1]}/${modern[2]}`)) {
|
|
31
43
|
return { url: new URL(`../${modern[1]}/${modern[2]}.mjs`, import.meta.url) }
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import {mkdir,readdir,readFile,writeFile,rename,unlink,lstat} from 'node:fs/promises'
|
|
2
|
+
import {join} from 'node:path'
|
|
3
|
+
import {createHash} from 'node:crypto'
|
|
4
|
+
import {defaultStateFile} from './storage-paths.mjs'
|
|
5
|
+
import {avatarActivity} from '../shared/avatar-activity.mjs'
|
|
6
|
+
import {PLUGIN_VERSION} from '../shared/state.mjs'
|
|
7
|
+
export class AvatarActivityOutbox {
|
|
8
|
+
constructor(getConfig,{root=defaultStateFile('avatar-activity'),fetcher=fetch,now=Date.now}={}){
|
|
9
|
+
Object.assign(this,{getConfig,root,fetcher,now});this.records=new Map();this.closed=false;this.chain=Promise.resolve();this.ready=this.load().catch(error=>{this.loadError=error});this.timer=setInterval(()=>void this.flush(),60000);this.timer.unref?.()
|
|
10
|
+
}
|
|
11
|
+
async load(){await mkdir(this.root,{recursive:true,mode:0o700});if((await lstat(this.root)).isSymbolicLink())throw Error('invalid_activity_store');for(const name of (await readdir(this.root)).filter(n=>/^[a-f0-9]{64}\.json$/.test(n)).slice(0,512)){try{const path=join(this.root,name),stat=await lstat(path);if(!stat.isFile()||stat.isSymbolicLink()||stat.size>16384)continue;const item=JSON.parse(await readFile(path,'utf8'));avatarActivity(item.record);const url=new URL(item.url);if(!['http:','https:'].includes(url.protocol)||url.pathname!=='/avatar-events'||url.username||url.password||url.search||url.hash)continue;if(!Number.isFinite(item.expires)||item.expires>this.now()+86400000||item.expires<=this.now()){await unlink(path);continue}if(typeof item.authorization!=='string'||item.authorization.length>8192||!/^anon_[a-f0-9]{32}$/.test(item.record.user_id))continue;this.records.set(name,item)}catch{}}}
|
|
12
|
+
enqueue(value,user){const work=this.chain.then(async()=>{
|
|
13
|
+
await this.ready;if(this.loadError)throw this.loadError;const event=avatarActivity(value);if(!/^anon_[a-f0-9]{32}$/.test(user))throw Error('invalid_activity_user')
|
|
14
|
+
const name=createHash('sha256').update(user+':'+event.event_id).digest('hex')+'.json';if(this.records.has(name))return
|
|
15
|
+
if(this.records.size>=512)throw Error('activity_queue_full')
|
|
16
|
+
const config=await this.getConfig(),url=new URL(config.endpoints.online);url.protocol=url.protocol==='wss:'?'https:':'http:';url.pathname='/avatar-events';url.search='';url.hash=''
|
|
17
|
+
const item={url:url.href,authorization:config.authorization||'',expires:this.now()+86400000,record:{...event,user_id:user,plugin_version:PLUGIN_VERSION}}
|
|
18
|
+
const path=join(this.root,name),temp=path+'.tmp';await writeFile(temp,JSON.stringify(item),{mode:0o600});await rename(temp,path);this.records.set(name,item)
|
|
19
|
+
});this.chain=work.catch(()=>{});return work.then(()=>{void this.flush();return{accepted:true}})}
|
|
20
|
+
async flush(){await this.ready;if(this.loadError||this.closed||this.busy)return;this.busy=true;try{for(const [name,item]of this.records){if(this.closed)break;let done=item.expires<=this.now();if(!done){try{const response=await this.fetcher(item.url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(5000),headers:{'Content-Type':'application/json',...(item.authorization?{Authorization:item.authorization}:{})},body:JSON.stringify(item.record)});if(response.ok){const result=await response.json();done=result.persisted===true&&result.event_id===item.record.event_id}else await response.body?.cancel()}catch{}}
|
|
21
|
+
if(done){await unlink(join(this.root,name)).catch(()=>{});this.records.delete(name)}else break
|
|
22
|
+
}}finally{this.busy=false}}
|
|
23
|
+
close(){this.closed=true;clearInterval(this.timer)}
|
|
24
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import {readFileSync,realpathSync,statSync} from 'node:fs'
|
|
2
|
+
import {join,dirname} from 'node:path'
|
|
3
|
+
import {fileURLToPath} from 'node:url'
|
|
4
|
+
import {createHash} from 'node:crypto'
|
|
5
|
+
import {AVATAR_UI_PROTOCOL} from '../shared/avatar-surface.mjs'
|
|
6
|
+
export const desktopAssetsPath=fileURLToPath(new URL('../../assets/avatar/desktop/',import.meta.url))
|
|
7
|
+
export const DESKTOP_ASSET_FILES=['index.html','companion.mjs','renderer.mjs','character.glb','portrait.png']
|
|
8
|
+
/** Verify the distributed local UI before starting a privileged native webview. */
|
|
9
|
+
export function verifyDesktopAssets(path=desktopAssetsPath) {
|
|
10
|
+
const root=realpathSync(path),manifest=JSON.parse(readFileSync(join(root,'manifest.json'),'utf8'))
|
|
11
|
+
if(manifest.protocol!==AVATAR_UI_PROTOCOL||JSON.stringify(Object.keys(manifest.files||{}).sort())!==JSON.stringify([...DESKTOP_ASSET_FILES].sort()))throw Error('desktop_assets_incompatible')
|
|
12
|
+
for(const file of DESKTOP_ASSET_FILES){
|
|
13
|
+
const resolved=realpathSync(join(root,file))
|
|
14
|
+
if(dirname(resolved)!==root||statSync(resolved).size>64*1024*1024)throw Error('desktop_assets_invalid')
|
|
15
|
+
if(createHash('sha256').update(readFileSync(resolved)).digest('hex')!==manifest.files[file])throw Error('desktop_assets_damaged')
|
|
16
|
+
}
|
|
17
|
+
return root
|
|
18
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
import { WebSocketServer } from 'ws'
|
|
2
|
+
import { spawn } from 'node:child_process'
|
|
3
|
+
import { accessSync, constants } from 'node:fs'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
import { randomBytes, timingSafeEqual } from 'node:crypto'
|
|
6
|
+
import { AVATAR_SIZES, avatarSize, avatarFrame, avatarInputEffect, AvatarHeartbeat } from '../shared/avatar.mjs'
|
|
7
|
+
import { AVATAR_UI_PROTOCOL, avatarSurface, avatarSurfaceAction } from '../shared/avatar-surface.mjs'
|
|
8
|
+
import {verifyDesktopAssets,desktopAssetsPath} from './avatar-assets.mjs'
|
|
9
|
+
import {avatarMenuAction,avatarLocalState,avatarMenuResult} from '../shared/avatar-menu.mjs'
|
|
10
|
+
import {avatarGeometry} from '../shared/avatar-activity.mjs'
|
|
11
|
+
|
|
12
|
+
export function avatarBinary(platform = process.platform, arch = process.arch) {
|
|
13
|
+
if (!['darwin-arm64','win32-x64'].includes(`${platform}-${arch}`)) return null
|
|
14
|
+
const file=platform==='darwin'?'duet-avatar.app/Contents/MacOS/duet-avatar':`duet-avatar${platform==='win32'?'.exe':''}`
|
|
15
|
+
return fileURLToPath(new URL(`../../desktop/bin/${platform}-${arch}/${file}`,import.meta.url))
|
|
16
|
+
}
|
|
17
|
+
export function sameSecret(a, b) {
|
|
18
|
+
const x=Buffer.from(String(a)),y=Buffer.from(String(b))
|
|
19
|
+
return x.length===y.length && timingSafeEqual(x,y)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Private, loopback-only IPC. The companion never receives DSH/server credentials. */
|
|
23
|
+
export async function launchAvatar({onCommand,onExit,signal,size,ownerKind='browser'}, {spawnImpl=spawn, binary=avatarBinary(), env=process.env, assets=desktopAssetsPath}={}) {
|
|
24
|
+
if(!binary)throw Error('desktop_platform_unsupported')
|
|
25
|
+
if(process.platform==='linux'&&!env.DISPLAY&&!env.WAYLAND_DISPLAY)throw Error('desktop_display_unavailable')
|
|
26
|
+
try{accessSync(binary,constants.X_OK)}catch{throw Error('desktop_helper_missing')}
|
|
27
|
+
const assetsPath=verifyDesktopAssets(assets)
|
|
28
|
+
const token=randomBytes(32).toString('hex')
|
|
29
|
+
const ipc=new WebSocketServer({host:'127.0.0.1',port:0,maxPayload:2048,
|
|
30
|
+
verifyClient:({req})=>sameSecret(req.headers['sec-websocket-protocol'],`duet-avatar-${token}`)})
|
|
31
|
+
await new Promise((resolve,reject)=>{ipc.once('listening',resolve);ipc.once('error',reject)})
|
|
32
|
+
let child,peer,closed=false,ready=false,timeout,killTimer,abort
|
|
33
|
+
const stop=()=>{
|
|
34
|
+
if(closed)return
|
|
35
|
+
closed=true;clearTimeout(timeout)
|
|
36
|
+
signal?.removeEventListener('abort',abort)
|
|
37
|
+
for(const ws of ipc.clients)ws.terminate()
|
|
38
|
+
ipc.close()
|
|
39
|
+
if(child&&child.exitCode===null){child.kill();killTimer=setTimeout(()=>{if(child.exitCode===null)child.kill('SIGKILL')},2000);killTimer.unref()}
|
|
40
|
+
}
|
|
41
|
+
const initialized=new Promise((resolve,reject)=>{
|
|
42
|
+
const fail=code=>{if(closed)return;stop();if(!ready)reject(Error(code));else onExit(code)}
|
|
43
|
+
abort=()=>fail('desktop_cancelled')
|
|
44
|
+
signal?.addEventListener('abort',abort,{once:true})
|
|
45
|
+
if(signal?.aborted){abort();return}
|
|
46
|
+
ipc.on('connection',ws=>{
|
|
47
|
+
if(peer){ws.close(1008);return}peer=ws
|
|
48
|
+
ws.on('error',()=>{})
|
|
49
|
+
ws.on('message',raw=>{
|
|
50
|
+
try{
|
|
51
|
+
const msg=JSON.parse(raw)
|
|
52
|
+
if(msg.type==='ready'&&!ready){if(msg.protocol!==AVATAR_UI_PROTOCOL){fail('desktop_helper_upgrade_required');return}ready=true;clearTimeout(timeout);resolve()}
|
|
53
|
+
else if(ready&&msg.type==='surface_action')onCommand(avatarSurfaceAction(msg))
|
|
54
|
+
else if(ready&&msg.type==='menu_action')onCommand(avatarMenuAction(msg))
|
|
55
|
+
else if(ready&&msg.type==='avatar_geometry')onCommand({type:'avatar_geometry',position:avatarGeometry(msg.position)})
|
|
56
|
+
else if(ready&&msg.type==='mode'&&['online','tts_only'].includes(msg.mode))onCommand(msg)
|
|
57
|
+
else if(ready&&msg.type==='size'&&Object.hasOwn(AVATAR_SIZES,msg.size))onCommand({type:'size',size:msg.size})
|
|
58
|
+
else if(msg.type==='hide')onCommand({type:'hide'})
|
|
59
|
+
else if(msg.type==='failed')fail('desktop_renderer_failed')
|
|
60
|
+
else if(msg.type!=='alive')ws.close(1008)
|
|
61
|
+
}catch{ws.close(1008)}
|
|
62
|
+
})
|
|
63
|
+
ws.on('close',()=>fail('desktop_closed'))
|
|
64
|
+
})
|
|
65
|
+
ipc.on('error',()=>fail('desktop_ipc_failed'))
|
|
66
|
+
try{
|
|
67
|
+
// No shell, user-supplied executable, detached daemon, inherited credentials, or CLI token.
|
|
68
|
+
const safeEnv=Object.fromEntries(['PATH','HOME','USERPROFILE','LOCALAPPDATA','APPDATA','SYSTEMROOT','WINDIR','TEMP','TMP','TMPDIR','DISPLAY','WAYLAND_DISPLAY','XDG_RUNTIME_DIR','DBUS_SESSION_BUS_ADDRESS','LANG','LC_ALL'].filter(k=>env[k]).map(k=>[k,env[k]]))
|
|
69
|
+
child=spawnImpl(binary,[],{stdio:'ignore',windowsHide:true,env:{...safeEnv,
|
|
70
|
+
DUET_AVATAR_ASSETS:assetsPath,DUET_AVATAR_IPC:`ws://127.0.0.1:${ipc.address().port}`,DUET_AVATAR_TOKEN:token,DUET_AVATAR_SIZE:avatarSize(size),
|
|
71
|
+
DUET_AVATAR_OWNER_KIND:['desktop','chrome','edge','firefox','safari','browser'].includes(ownerKind)?ownerKind:'browser'}})
|
|
72
|
+
child.once('error',()=>fail('desktop_launch_failed'))
|
|
73
|
+
child.once('exit',code=>{clearTimeout(killTimer);fail(code===78?'desktop_webview2_missing':'desktop_closed')})
|
|
74
|
+
timeout=setTimeout(()=>fail('desktop_start_timeout'),20000);timeout.unref()
|
|
75
|
+
}catch{fail('desktop_launch_failed')}
|
|
76
|
+
})
|
|
77
|
+
await initialized
|
|
78
|
+
return {close:stop,send(frame){if(peer?.readyState===1&&peer.bufferedAmount<16000)peer.send(JSON.stringify(frame))}}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Exactly one owning DSH page per Host; other pages cannot drive its companion. */
|
|
82
|
+
export function registerAvatarHost(ctx, {launch=launchAvatar}={}) {
|
|
83
|
+
const server=new WebSocketServer({noServer:true,maxPayload:65536}),clients=new Set()
|
|
84
|
+
let owner=null,closed=false
|
|
85
|
+
const unregister=ctx.webServer.registerUpgrade({path:'/duet/avatar/ws',handler(req,socket,head){
|
|
86
|
+
let allowed=!req.headers.origin
|
|
87
|
+
try{if(req.headers.origin)allowed=new URL(req.headers.origin).host===req.headers.host}catch{}
|
|
88
|
+
if(closed||!allowed||ctx.connection.requestRejection(req)||clients.size>=8){socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');return}
|
|
89
|
+
server.handleUpgrade(req,socket,head,ws=>{
|
|
90
|
+
clients.add(ws);let helper,starting=false,ended=false,frames=0,second=Date.now(),alive=Date.now()
|
|
91
|
+
const lifetime=new AbortController()
|
|
92
|
+
const send=value=>{if(ws.readyState===1&&ws.bufferedAmount<16000)ws.send(JSON.stringify(value))}
|
|
93
|
+
const cleanup=()=>{ended=true;lifetime.abort();helper?.close();helper=null;if(owner===ws)owner=null}
|
|
94
|
+
// Background pages may be scheduled only once a minute. The Host keeps
|
|
95
|
+
// its native child alive independently while the owning page is present.
|
|
96
|
+
const liveness=new AvatarHeartbeat(15000,Date.now(),120000)
|
|
97
|
+
const heartbeat=setInterval(()=>{
|
|
98
|
+
if(liveness.expired())ws.terminate()
|
|
99
|
+
else helper?.send({type:'alive'})
|
|
100
|
+
},15000);heartbeat.unref()
|
|
101
|
+
ws.on('error',()=>{})
|
|
102
|
+
ws.on('message',async raw=>{
|
|
103
|
+
try{
|
|
104
|
+
alive=Date.now();liveness.touch(alive);if(alive-second>1000){second=alive;frames=0}if(++frames>40)throw Error('rate')
|
|
105
|
+
const msg=JSON.parse(raw)
|
|
106
|
+
if(msg.type==='start'&&!starting&&!helper){
|
|
107
|
+
if(owner&&owner!==ws){send({type:'fallback',reason:'desktop_in_use'});return}
|
|
108
|
+
owner=ws;starting=true
|
|
109
|
+
try{
|
|
110
|
+
const created=await launch({signal:lifetime.signal,size:avatarSize(msg.size),ownerKind:msg.owner_kind,onCommand:send,onExit:reason=>{helper=null;if(owner===ws)owner=null;send({type:'fallback',reason})}})
|
|
111
|
+
if(ended||closed||owner!==ws){created.close();return}
|
|
112
|
+
helper=created;send({type:'desktop_ready'})
|
|
113
|
+
}catch(error){if(owner===ws)owner=null;send({type:'fallback',reason:error.message})}
|
|
114
|
+
finally{starting=false}
|
|
115
|
+
}else if(msg.type==='frame'&&owner===ws){helper?.send(avatarFrame(msg))}
|
|
116
|
+
else if(msg.type==='surface'&&owner===ws){helper?.send(avatarSurface(msg))}
|
|
117
|
+
else if(msg.type==='owner_focus'&&owner===ws){helper?.send({type:'owner_focus'})}
|
|
118
|
+
else if(msg.type==='local_state'&&owner===ws){helper?.send(avatarLocalState(msg))}
|
|
119
|
+
else if(msg.type==='menu_result'&&owner===ws){helper?.send(avatarMenuResult(msg))}
|
|
120
|
+
else if(msg.type==='input_effect'&&owner===ws){helper?.send(avatarInputEffect(msg))}
|
|
121
|
+
else if(msg.type==='clear_input_effect'&&owner===ws){helper?.send({type:'clear_input_effect'})}
|
|
122
|
+
else if(msg.type==='alive')send({type:'alive'})
|
|
123
|
+
else throw Error('message')
|
|
124
|
+
}catch{ws.close(1008,'invalid_avatar_message')}
|
|
125
|
+
})
|
|
126
|
+
ws.on('close',()=>{clearInterval(heartbeat);clients.delete(ws);cleanup()})
|
|
127
|
+
})
|
|
128
|
+
}})
|
|
129
|
+
return {close(){closed=true;unregister();for(const ws of clients)ws.terminate();server.close()}}
|
|
130
|
+
}
|