dsh-duet 0.1.10 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) 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 +80 -33
  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 +1 -0
  42. package/src/client/rpc.mjs +2 -1
  43. package/src/client/settings.html +78 -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/host/assets.mjs +12 -0
  48. package/src/host/avatar-activity.mjs +24 -0
  49. package/src/host/avatar-assets.mjs +18 -0
  50. package/src/host/avatar.mjs +130 -0
  51. package/src/host/diagnostics.mjs +111 -7
  52. package/src/host/feedback-files.mjs +5 -1
  53. package/src/host/plugin.mjs +39 -2
  54. package/src/host/proxy.mjs +13 -5
  55. package/src/host/settings-migration.mjs +2 -1
  56. package/src/host/settings.mjs +19 -4
  57. package/src/shared/avatar-activity.mjs +33 -0
  58. package/src/shared/avatar-menu-ui.mjs +85 -0
  59. package/src/shared/avatar-menu.mjs +83 -0
  60. package/src/shared/avatar-surface.mjs +24 -0
  61. package/src/shared/avatar-ui.mjs +91 -0
  62. package/src/shared/avatar.mjs +125 -0
  63. package/src/shared/nickname.mjs +13 -0
  64. package/src/shared/state.mjs +1 -1
@@ -1,16 +1,102 @@
1
1
  import { randomUUID } from 'node:crypto'
2
+ import { mkdirSync, readdirSync, lstatSync, readFileSync, writeFileSync, renameSync, unlinkSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { duetHome } from './storage-paths.mjs'
2
5
  import { diagnosticPayload, DIAGNOSTICS_PROTOCOL } from '../shared/diagnostics.mjs'
3
6
 
7
+ const TTL = 6 * 60 * 60 * 1000
8
+ const ownerAlive = pid => {
9
+ if (!Number.isInteger(pid) || pid <= 0) return false
10
+ try { process.kill(pid, 0); return true } catch (error) { return error.code === 'EPERM' }
11
+ }
12
+ /** Private, bounded outbox. Tickets/authorization never enter trace or public assets. */
13
+ export class DiagnosticOutbox {
14
+ constructor({root = join(duetHome(), 'diagnostic-outbox'), fetcher = fetch, now = Date.now,
15
+ isOwnerAlive = ownerAlive} = {}) {
16
+ this.root = root; this.fetcher = fetcher; this.now = now; this.active = new Set(); this.inflight = 0
17
+ this.closed = false
18
+ try {
19
+ mkdirSync(root, {recursive:true, mode:0o700})
20
+ if (lstatSync(root).isSymbolicLink()) throw Error('unsafe_outbox')
21
+ let index = 0
22
+ for (const name of readdirSync(root).filter(n => /^[a-f0-9-]{36}\.json$/.test(n))) {
23
+ const path = join(root, name)
24
+ try {
25
+ const stat = lstatSync(path)
26
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 65536) continue
27
+ const value = JSON.parse(readFileSync(path, 'utf8'))
28
+ if (!(value.expires > now() && value.expires <= now() + TTL) || index >= 128) {
29
+ unlinkSync(path); continue
30
+ }
31
+ // Another DSH profile/process may still append to this connection.
32
+ if (isOwnerAlive(value.owner_pid)) continue
33
+ const url = new URL(value.target)
34
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
35
+ url.pathname !== '/client-diagnostics' || url.search || url.hash ||
36
+ typeof value.ticket !== 'string' || value.ticket.length > 4096 ||
37
+ typeof value.authorization !== 'string' || value.authorization.length > 8192 ||
38
+ !Array.isArray(value.pending) || value.pending.length > 96) throw Error('invalid_outbox')
39
+ const d = new ConnectionDiagnostics({}, fetcher, this)
40
+ d.id = name.slice(0, -5); d.target = value.target; d.ticket = value.ticket
41
+ d.authorization = value.authorization; d.expires = value.expires
42
+ // Reapply the whitelist while retaining the original idempotency ID and sequence.
43
+ d.pending = value.pending.map(r => ({...diagnosticPayload(r), sequence:r.sequence}))
44
+ .filter(r => r.event && r.event_id && Number.isInteger(r.sequence) && r.sequence >= 0 && r.sequence < 96)
45
+ d.count = 96 // Recovered instances only replay; never manufacture new events.
46
+ this.save(d); d.schedule(index++ * 2000)
47
+ } catch { /* Corrupt evidence must not prevent plugin startup. */ }
48
+ }
49
+ } catch { this.unavailable = true }
50
+ }
51
+ save(d) {
52
+ // Socket close callbacks can arrive during plugin disposal: still persist them.
53
+ if (!d.target) return
54
+ const path = join(this.root, d.id + '.json')
55
+ if (!d.pending.length || d.expires <= this.now()) {
56
+ this.active.delete(d)
57
+ try { unlinkSync(path) } catch { /* already delivered or unavailable */ }
58
+ return
59
+ }
60
+ this.active.add(d)
61
+ if (this.unavailable) return
62
+ let temp
63
+ try {
64
+ if (readdirSync(this.root).filter(n => n.endsWith('.json')).length >= 128) {
65
+ try { lstatSync(path) } catch { return }
66
+ }
67
+ const body = JSON.stringify({target:d.target, ticket:d.ticket, authorization:d.authorization || '',
68
+ expires:d.expires, pending:d.pending, owner_pid:process.pid})
69
+ if (Buffer.byteLength(body) > 65536) return
70
+ temp = path + '.' + randomUUID() + '.tmp'
71
+ writeFileSync(temp, body, {mode:0o600, flag:'wx'}); renameSync(temp, path)
72
+ } catch {
73
+ if (!this.warned) { this.warned = true; console.warn('[duet] Diagnostic outbox unavailable; retrying in memory.') }
74
+ } finally { if (temp) try { unlinkSync(temp) } catch { /* renamed */ } }
75
+ }
76
+ dispose() {
77
+ this.closed = true
78
+ for (const d of this.active) { clearTimeout(d.timer); d.controller?.abort() }
79
+ this.active.clear()
80
+ }
81
+ }
82
+
4
83
  /** Bounded, asynchronous batches. Telemetry failure never closes a voice socket. */
5
84
  export class ConnectionDiagnostics {
6
- constructor(metadata, fetcher = fetch) {
85
+ constructor(metadata, fetcher = fetch, outbox = null) {
7
86
  this.metadata = metadata; this.fetcher = fetcher
8
87
  this.pending = []; this.seen = new Set(); this.count = 0; this.attempts = 0
88
+ this.outbox = outbox; this.id = randomUUID(); this.expires = (outbox?.now() ?? Date.now()) + TTL
9
89
  }
10
90
  add(value) {
11
91
  const row = diagnosticPayload({...value, ...this.metadata, event_id: value.event_id || randomUUID()})
12
92
  if (!row || this.seen.has(row.event_id) || this.count >= 96) return
93
+ const terminal = /close|failed|error|pagehide/.test(row.event)
94
+ if (!terminal && this.count >= 80) return // Reserve room for the actual ending.
95
+ const now = this.outbox?.now() ?? Date.now()
96
+ if (this.expires <= now) this.pending = []
97
+ if (!this.pending.length) this.expires = now + TTL // Retain queued events, not session age.
13
98
  this.seen.add(row.event_id); row.sequence=this.count++; this.pending.push(row)
99
+ this.outbox?.save(this)
14
100
  this.schedule()
15
101
  }
16
102
  offer(offer, config, endpoint) {
@@ -18,28 +104,46 @@ export class ConnectionDiagnostics {
18
104
  const url = new URL(endpoint); url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:'
19
105
  url.pathname = '/client-diagnostics'; url.search = ''; url.hash = ''
20
106
  this.target = url.href; this.ticket = offer.ticket; this.authorization = config.authorization
107
+ this.outbox?.save(this)
21
108
  this.schedule()
22
109
  }
23
110
  schedule(delay = 150) {
24
- if (!this.target || !this.pending.length || this.timer || this.busy || this.attempts >= 120) return
111
+ if (this.outbox?.closed || !this.target || !this.pending.length || this.timer || this.busy) return
112
+ if ((this.outbox?.now() ?? Date.now()) >= this.expires) {
113
+ this.pending = []; this.outbox?.save(this); return
114
+ }
25
115
  this.timer = setTimeout(() => { this.timer = null; void this.flush() }, delay); this.timer.unref?.()
26
116
  }
27
117
  async flush() {
28
- if (this.busy || !this.target || !this.pending.length) return
118
+ if (this.outbox?.closed || this.busy || !this.target || !this.pending.length) return
119
+ if ((this.outbox?.now() ?? Date.now()) >= this.expires) {
120
+ this.pending = []; this.outbox?.save(this); return
121
+ }
122
+ if (this.outbox && this.outbox.inflight >= 2) { this.schedule(1000); return }
29
123
  this.busy = true; this.attempts++
124
+ if (this.outbox) this.outbox.inflight++
125
+ this.controller = new AbortController()
126
+ const timeout = setTimeout(() => this.controller.abort(), 3000); timeout.unref?.()
30
127
  const rows = this.pending.slice(0, 16)
31
128
  let failed = false
32
129
  try {
33
130
  const response = await this.fetcher(this.target, { method: 'POST', redirect: 'error',
34
131
  headers: {'Content-Type':'application/json', ...(this.authorization ? {Authorization:this.authorization} : {})},
35
132
  body: JSON.stringify({protocol:DIAGNOSTICS_PROTOCOL, ticket:this.ticket, events:rows}),
36
- signal: AbortSignal.timeout(3000) })
133
+ signal: this.controller.signal })
134
+ if ([400, 401, 403, 413].includes(response.status)) {
135
+ await response.body?.cancel(); this.pending = []; return
136
+ }
37
137
  if (!response.ok) throw Error('diagnostic_upload_failed')
38
138
  await response.body?.cancel()
39
139
  this.pending.splice(0, rows.length); this.failures = 0
40
140
  } catch { failed = true; this.failures = (this.failures || 0) + 1 }
41
- finally { this.busy = false }
42
- // At most three retries in a row, even if the server disappeared at close.
43
- if (!failed || this.failures < 3) this.schedule(failed ? 1000 : 150)
141
+ finally {
142
+ clearTimeout(timeout); this.busy = false
143
+ if (this.outbox) this.outbox.inflight--
144
+ this.outbox?.save(this)
145
+ }
146
+ // Backoff through transient outages; bound lifetime, rate, storage and concurrency.
147
+ this.schedule(failed ? Math.min(60000, 1000 * 2 ** Math.min(this.failures - 1, 6)) : 150)
44
148
  }
45
149
  }
@@ -20,7 +20,11 @@ export class RemoteFeedback {
20
20
  const fd=openSync(tmp,'wx',0o600)
21
21
  try{writeFileSync(fd,randomBytes(32));fsyncSync(fd)}finally{closeSync(fd)}
22
22
  try{linkSync(tmp,this.keyPath)}catch(e){if(e.code!=='EEXIST')throw e}finally{unlinkSync(tmp)}
23
- const d=openSync(dirname(this.keyPath),'r');try{fsyncSync(d)}finally{closeSync(d)}
23
+ // Windows cannot flush this read-only directory handle (EPERM). The key
24
+ // file itself was already flushed above; keep directory durability on POSIX.
25
+ if(process.platform!=='win32'){
26
+ const d=openSync(dirname(this.keyPath),'r');try{fsyncSync(d)}finally{closeSync(d)}
27
+ }
24
28
  }
25
29
  const key=readFileSync(this.keyPath);if(key.length!==32)throw Error('feedback_identity_key_invalid')
26
30
  this.key=key;return key
@@ -4,6 +4,7 @@ import { readFile } from 'node:fs/promises'
4
4
  import { randomUUID } from 'node:crypto'
5
5
  import { registerDuetProxy, duetConfig } from './proxy.mjs'
6
6
  import { DuetSettings, settingsWriteAllowed } from './settings.mjs'
7
+ import { NICKNAME_LIMIT } from '../shared/nickname.mjs'
7
8
  import { IDENTITY_TRANSPORT_HEADER, IDENTITY_TRANSPORT } from '../shared/identity.mjs'
8
9
  import { ServiceNotices } from './notices.mjs'
9
10
  import { ServiceInfo } from './service-info.mjs'
@@ -14,6 +15,8 @@ import { PLUGIN_VERSION } from '../shared/state.mjs'
14
15
  import { buildSessionCatalog, sessionLabel } from '../shared/catalog.mjs'
15
16
  import { broadcastText, taskErrorText } from '../shared/result-notification.mjs'
16
17
  import { publicAsset } from './assets.mjs'
18
+ import { registerAvatarHost } from './avatar.mjs'
19
+ import { AvatarActivityOutbox } from './avatar-activity.mjs'
17
20
  import { duetEnv } from './environment.mjs'
18
21
  import { EndpointDiscovery } from './endpoint-discovery.mjs'
19
22
  import { StopTasks } from './stop-task.mjs'
@@ -185,7 +188,9 @@ export function apply(ctx, options = {}) {
185
188
 
186
189
  const voice = duetConfig()
187
190
  const settings = new DuetSettings(voice, { path: options.settingsPath, debug: options.debug === true || duetEnv('DEBUG') === '1' })
191
+ ctx.effect(() => { const avatar=registerAvatarHost(ctx);return ()=>avatar.close() })
188
192
  Object.assign(voice, settings.effective())
193
+ voice.nickname = () => settings.public().nickname
189
194
  const audit = new DuetTrace({ kind: 'host', plugin_version: PLUGIN_VERSION, pid: process.pid },
190
195
  { ...options.traceOptions, secrets: [voice.authorization] })
191
196
  ctx.effect(() => () => { void audit.close({ reason: 'plugin_dispose' }) })
@@ -195,6 +200,8 @@ export function apply(ctx, options = {}) {
195
200
  discovery.refreshIfDue()
196
201
  const feedbackStore = options.feedbackStore ?? (options.feedbackDisabled ? null : new RemoteFeedback(()=>discovery.effective(),{keyPath:options.feedbackIdentityPath}))
197
202
  const feedback = new FeedbackService(feedbackStore)
203
+ const avatarActivity = new AvatarActivityOutbox(()=>discovery.effective(), options.avatarActivityOptions)
204
+ ctx.effect(()=>()=>avatarActivity.close())
198
205
  let duetProxy
199
206
  ctx.effect(() => { duetProxy = registerDuetProxy(ctx, voice, feedback, () => (ctx.workspaceRegistry.list?.() || []).length > 0, discovery); return duetProxy })
200
207
 
@@ -416,6 +423,7 @@ export function apply(ctx, options = {}) {
416
423
  const turnKey = (sessionId, turn) => `${sessionId}:${String(turn)}`
417
424
 
418
425
  const completeJob = (job, event) => {
426
+ job.turn_end_reason = ['completed','aborted','error'].includes(event.data.reason?.kind) ? event.data.reason.kind : 'unknown'
419
427
  job.completed_at = nowSeconds()
420
428
  if (event.data.reason?.kind === 'aborted') {
421
429
  job.status = 'failed'
@@ -530,6 +538,33 @@ export function apply(ctx, options = {}) {
530
538
  })
531
539
 
532
540
  const handleApi = async (req, res, pathname) => {
541
+ if(req.method==='POST'&&pathname===`${ROUTE}/api/avatar/activity`){
542
+ const rejection=ctx.connection.requestRejection(req)
543
+ if(rejection){sendError(res,rejection,'DSH connection required');return}
544
+ if(!identityWriteAllowed(req)){sendError(res,403,'same-origin activity request required');return}
545
+ try{const value=await readJson(req);if(JSON.stringify(value).length>4096){sendError(res,413,'activity too large');return}sendJson(res,202,await avatarActivity.enqueue(value,feedback.user(req)))}
546
+ catch{sendError(res,400,'invalid_avatar_activity')}return
547
+ }
548
+ if (req.method === 'POST' && pathname === `${ROUTE}/api/duet/nickname`) {
549
+ const rejection = ctx.connection.requestRejection(req)
550
+ if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
551
+ const boundRPC = req.headers['x-duplex-control-client'] === 'realtime-client-rpc-v1' && browserOwner(req)
552
+ if (!identityWriteAllowed(req) && !boundRPC) { sendError(res, 403, 'same-origin nickname request required'); return }
553
+ try {
554
+ const body = await readJson(req)
555
+ const result = await settings.renameNickname(body.nickname, body.revision)
556
+ // Nicknames do not retarget or close an active voice connection.
557
+ sendJson(res, 200, {ok:true, nickname:result.nickname, revision:result.revision,
558
+ action_response:'<action_response>rename_duet:ok</action_response>'})
559
+ } catch (error) {
560
+ const reason = error.message === NICKNAME_LIMIT ? NICKNAME_LIMIT
561
+ : error.message === 'settings_revision_conflict' ? '设置已更新,请刷新后重试' : '昵称保存失败,请重试'
562
+ sendJson(res, 200, {ok:false, reason,
563
+ error_code:error.message === NICKNAME_LIMIT ? 'invalid_nickname' : 'nickname_save_failed',
564
+ action_response:`<action_response>rename_duet:failed:${reason}</action_response>`})
565
+ }
566
+ return
567
+ }
533
568
  if(req.method==='POST' && pathname===`${ROUTE}/api/feedback`){
534
569
  const rejection = ctx.connection.requestRejection(req)
535
570
  if(rejection){sendError(res,rejection,'请先打开并登录 DSH 主页面');return}
@@ -564,6 +599,7 @@ export function apply(ctx, options = {}) {
564
599
  else feedbackStore?.ensureIdentity?.(req,res)
565
600
  } catch {sendJson(res,503,{error_code:'feedback_identity_unavailable'});return}
566
601
  sendJson(res, 200, { ...settings.public(), plugin_version: PLUGIN_VERSION, feedback_enabled: feedback.enabled,
602
+ avatar: { web_only: duetEnv('AVATAR_WEB_ONLY') === '1' },
567
603
  ...(identity?{feedback_identity:identity}:{}), connection: duetProxy?.snapshot?.() || { online: 0, tts_only: 0 } })
568
604
  return
569
605
  }
@@ -837,7 +873,8 @@ export function apply(ctx, options = {}) {
837
873
  // before that page can select its own current blank session.
838
874
  const pageCatalog = browserOwner(req) || req.headers['x-duet-catalog-scope'] === 'page'
839
875
  sendJson(res, 200, { sessions: await listSessions({forCatalog:!pageCatalog}),
840
- duet_rpc_capabilities: typeof ctx.sessionController.cancel === 'function' ? ['stop_task_v1'] : [] })
876
+ duet_nickname: settings.public().nickname,
877
+ duet_rpc_capabilities: ['rename_duet_v1', ...(typeof ctx.sessionController.cancel === 'function' ? ['stop_task_v1'] : [])] })
841
878
  return
842
879
  }
843
880
  const stopRoute = pathname.match(new RegExp(`^${ROUTE}/api/sessions/([^/]+)/(execution|cancel)$`))
@@ -1191,7 +1228,7 @@ export function apply(ctx, options = {}) {
1191
1228
  const asset = publicAsset(pathname)
1192
1229
  if (req.method === 'GET' && asset) {
1193
1230
  const body = asset.body ?? await readFile(asset.url)
1194
- res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' })
1231
+ res.writeHead(200, { 'content-type': asset.contentType || 'text/javascript; charset=utf-8', 'cache-control': asset.cacheControl || (asset.contentType ? 'private, max-age=3600' : 'no-store') })
1195
1232
  res.end(body)
1196
1233
  return
1197
1234
  }
@@ -1,7 +1,7 @@
1
1
  /** Same-origin voice relay; endpoint and compatibility policy belong to the DSH host. */
2
2
  import { createRequire } from 'node:module'
3
3
  import { DuetTrace } from './trace.mjs'
4
- import { ConnectionDiagnostics } from './diagnostics.mjs'
4
+ import { ConnectionDiagnostics, DiagnosticOutbox } from './diagnostics.mjs'
5
5
  import { DIAGNOSTICS_PROTOCOL } from '../shared/diagnostics.mjs'
6
6
  import { PLUGIN_VERSION } from '../shared/state.mjs'
7
7
  import { duetEnv } from './environment.mjs'
@@ -10,11 +10,12 @@ import {sessionMetadata} from './session-metadata.mjs'
10
10
  import {VOICE_PROTOCOL} from '../shared/identity.mjs'
11
11
  import { broadcastText } from '../shared/result-notification.mjs'
12
12
  import { sessionLabel } from '../shared/catalog.mjs'
13
+ import { normalizeNickname } from '../shared/nickname.mjs'
13
14
  import { DEFAULT_DUET_URL, publicServiceAuthorization } from './service-defaults.mjs'
14
15
  export { DEFAULT_DUET_URL } from './service-defaults.mjs'
15
16
  const require = createRequire(import.meta.url)
16
17
 
17
- export function compatibleVersion(version, min = '0.1.0', maxExclusive = '0.2.0') {
18
+ export function compatibleVersion(version, min = '0.1.0', maxExclusive = '0.3.0') {
18
19
  const parse = v => /^\d+\.\d+\.\d+$/.test(v || '') ? v.split('.').map(Number) : null
19
20
  const compare = (a, b) => a[0] - b[0] || a[1] - b[1] || a[2] - b[2]
20
21
  const v = parse(version), low = parse(min), high = parse(maxExclusive)
@@ -28,7 +29,7 @@ export function duetConfig(env = process.env) {
28
29
  }
29
30
  return {
30
31
  min_version: duetEnv('MIN_VERSION', env) || '0.1.0',
31
- max_version_exclusive: duetEnv('MAX_VERSION_EXCLUSIVE', env) || '0.2.0',
32
+ max_version_exclusive: duetEnv('MAX_VERSION_EXCLUSIVE', env) || '0.3.0',
32
33
  control_transport: duetEnv('CONTROL_TRANSPORT', env) || 'client_rpc_v1',
33
34
  authorization: publicServiceAuthorization(endpoints),
34
35
  endpoints,
@@ -63,6 +64,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
63
64
  handleProtocols: protocols => protocols.has(VOICE_PROTOCOL) ? VOICE_PROTOCOL : false })
64
65
  const connections = new Map()
65
66
  const reporters = new Map()
67
+ const diagnosticOutbox = new DiagnosticOutbox(config.diagnosticOptions)
66
68
  const stop = ctx.webServer.registerUpgrade({
67
69
  path: '/duplex-control/voice/ws',
68
70
  handler(req, socket, head) {
@@ -111,7 +113,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
111
113
  try{anonymousUserId=feedback?.user(req)}catch{ /* Identity is optional, not admission. */ }
112
114
  const clientMetadata=sessionMetadata(params,mode,anonymousUserId)
113
115
  diagnostics = new ConnectionDiagnostics({client_trace_id:clientMetadata.client_trace_id,
114
- page_id:clientMetadata.page_id, plugin_version:clientMetadata.version, host_version:PLUGIN_VERSION, mode})
116
+ page_id:clientMetadata.page_id, plugin_version:clientMetadata.version, host_version:PLUGIN_VERSION, mode},
117
+ diagnosticOutbox.fetcher, diagnosticOutbox)
115
118
  reporters.set(clientMetadata.client_trace_id, {diagnostics, page_id:clientMetadata.page_id, user:anonymousUserId})
116
119
  // Allow keepalive HTTP diagnostics to arrive after the browser socket closed.
117
120
  front.once('close', () => { const timer=setTimeout(()=>reporters.delete(clientMetadata.client_trace_id),30000); timer.unref() })
@@ -171,12 +174,17 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
171
174
  if (message.type === 'session.update') {
172
175
  if (initialized) throw new Error('voice_mode_requires_reconnect')
173
176
  initialized = true
177
+ let nickname = null
178
+ try { nickname = normalizeNickname(config.nickname?.()) } catch { /* Default identity. */ }
174
179
  forward(JSON.stringify({ type: 'session.update',
175
180
  client: {...clientMetadata, diagnostics_protocol:DIAGNOSTICS_PROTOCOL,
181
+ ...(message.client?.audio_text_protocol === 'audio_text_delta_v1'
182
+ ? {audio_text_protocol:'audio_text_delta_v1'} : {}),
176
183
  ...(message.client?.audio_stop_protocol === 'audio_stop_candidates_v1'
177
184
  ? {audio_stop_protocol:'audio_stop_candidates_v1'} : {})},
178
185
  session: {
179
186
  type: 'realtime', preset_id: 'server_default',
187
+ duet_nickname: nickname,
180
188
  io_mode:mode === 'tts_only'?'external_only':'online',
181
189
  ...(clientRPC ? { harness: { transport: 'client_rpc_v1' } } : {}),
182
190
  audio: { input: { format: { type: 'audio/pcm', rate: 16000 } } },
@@ -284,7 +292,7 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
284
292
  })
285
293
  },
286
294
  })
287
- const dispose = () => { stop(); for (const socket of server.clients) socket.close(1001); server.close() }
295
+ const dispose = () => { stop(); for (const socket of server.clients) socket.close(1001); server.close(); diagnosticOutbox.dispose() }
288
296
  dispose.snapshot = () => ({
289
297
  online: [...connections.values()].filter(c => c.mode === 'online' && c.ready).length,
290
298
  tts_only: [...connections.values()].filter(c => c.mode === 'tts_only' && c.ready).length,
@@ -14,7 +14,8 @@ export function migrateRetiredSettings(data, path) {
14
14
  if (!retired.includes(url.hostname) || !['ws:', 'wss:', 'http:', 'https:'].includes(url.protocol)
15
15
  || url.port || url.username || url.password || url.hash || !['/', '/ws'].includes(url.pathname)
16
16
  || [...url.searchParams].some(([k,v]) => k !== 'protocol' || v !== 'realtime_v2')) return data
17
- const next = { backend_url: DEFAULT_DUET_URL }
17
+ const next = { backend_url: DEFAULT_DUET_URL,
18
+ ...(data.nickname != null ? {nickname:data.nickname} : {}) }
18
19
  const temp = `${path}.${randomUUID()}.tmp`
19
20
  try {
20
21
  writeFileSync(temp, JSON.stringify(next) + '\n', { mode: 0o600, flag: 'wx' })
@@ -7,6 +7,7 @@ import { randomUUID } from 'node:crypto'
7
7
  import { duetEnv } from './environment.mjs'
8
8
  import { publicServiceAuthorization, isPublicTrialEndpoint } from './service-defaults.mjs'
9
9
  import { migrateRetiredSettings } from './settings-migration.mjs'
10
+ import { normalizeNickname } from '../shared/nickname.mjs'
10
11
 
11
12
  export function normalizeBackendURL(value) {
12
13
  if (typeof value !== 'string' || value.length > 2048) throw new Error('invalid_backend_url')
@@ -45,14 +46,16 @@ export class DuetSettings {
45
46
 
46
47
  validate(data) {
47
48
  if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error('invalid_voice_settings')
49
+ if (data.backend_url === undefined && data.nickname != null) return {nickname:normalizeNickname(data.nickname)}
48
50
  const backend_url = validateBackendURL(data.backend_url, data.insecure_origin)
49
51
  const url = new URL(backend_url)
50
52
  const insecure_origin = url.protocol === 'ws:' && url.origin === data.insecure_origin ? url.origin : null
51
- return { backend_url, ...(insecure_origin ? { insecure_origin } : {}) }
53
+ return { backend_url, ...(insecure_origin ? { insecure_origin } : {}),
54
+ ...(data.nickname != null ? {nickname:normalizeNickname(data.nickname)} : {}) }
52
55
  }
53
56
 
54
57
  effective() {
55
- const endpoints = this.saved ? { online: this.saved.backend_url, tts_only: this.saved.backend_url } : this.base.endpoints
58
+ const endpoints = this.saved?.backend_url ? { online: this.saved.backend_url, tts_only: this.saved.backend_url } : this.base.endpoints
56
59
  return { ...this.base, endpoints, authorization: publicServiceAuthorization(endpoints) }
57
60
  }
58
61
 
@@ -67,9 +70,10 @@ export class DuetSettings {
67
70
  return {
68
71
  min_version: config.min_version, max_version_exclusive: config.max_version_exclusive,
69
72
  modes: Object.keys(config.endpoints), endpoints,
70
- backend_url: endpoints.online, config_source: this.saved ? 'plugin_settings' : 'environment_or_default',
73
+ backend_url: endpoints.online, config_source: this.saved?.backend_url ? 'plugin_settings' : 'environment_or_default',
71
74
  auth_configured: Boolean(config.authorization),
72
75
  debug: this.debug, revision: this.revision,
76
+ nickname: this.saved?.nickname ?? null,
73
77
  insecure_transport: new URL(config.endpoints.online).protocol !== 'wss:',
74
78
  }
75
79
  }
@@ -81,7 +85,14 @@ export class DuetSettings {
81
85
  const normalized = normalizeBackendURL(input.backend_url)
82
86
  const insecureOrigin = input.allow_insecure_http === true ? new URL(normalized).origin : this.saved?.insecure_origin
83
87
  const url = validateBackendURL(normalized, insecureOrigin)
84
- const next = this.validate({ backend_url: url, insecure_origin: insecureOrigin })
88
+ const next = this.validate({ backend_url: url, insecure_origin: insecureOrigin,
89
+ nickname: input.nickname === undefined ? this.saved?.nickname : input.nickname })
90
+ return this.persist(next, input.revision)
91
+ }
92
+
93
+ async persist(next, revision) {
94
+ if (this.writing) throw new Error('settings_write_in_progress')
95
+ if (revision !== this.revision) throw new Error('settings_revision_conflict')
85
96
  this.writing = true
86
97
  const temp = `${this.path}.${randomUUID()}.tmp`
87
98
  try {
@@ -93,6 +104,10 @@ export class DuetSettings {
93
104
  return this.public()
94
105
  } finally { this.writing = false; await unlink(temp).catch(() => {}) }
95
106
  }
107
+
108
+ async renameNickname(nickname, revision = this.revision) {
109
+ return this.persist({...this.saved, nickname:normalizeNickname(nickname)}, revision)
110
+ }
96
111
  }
97
112
 
98
113
  export function settingsWriteAllowed(req, { verifiedLocalIdentity = false } = {}) {
@@ -0,0 +1,33 @@
1
+ export const AVATAR_ACTIVITY_PROTOCOL='avatar_activity_v1'
2
+ export const AVATAR_ACTIVITY_HOUR=3600000
3
+ const sizes=['small','medium','large']
4
+ const id=v=>typeof v==='string'&&/^[a-zA-Z0-9_-]{1,64}$/.test(v)
5
+ const finite=(v,min,max)=>Number.isFinite(v)&&v>=min&&v<=max
6
+ const resolution=v=>v&&finite(v.width,1,1000000)&&finite(v.height,1,1000000)?{width:v.width,height:v.height}:null
7
+ export function avatarGeometry(v){
8
+ if(!v||!['desktop_physical','viewport_css'].includes(v.space))return null
9
+ const total=resolution(v.total_resolution),p=v.avatar_position
10
+ if(!total||!p||!finite(p.x,-1000000,1000000)||!finite(p.y,-1000000,1000000)||!resolution(p))return null
11
+ const out={space:v.space,total_resolution:total,avatar_position:{x:p.x,y:p.y,width:p.width,height:p.height}}
12
+ if(v.space==='desktop_physical'){
13
+ if(!v.desktop_origin||!finite(v.desktop_origin.x,-1000000,1000000)||!finite(v.desktop_origin.y,-1000000,1000000)||!finite(v.scale,0.25,16))return null
14
+ out.desktop_origin={x:v.desktop_origin.x,y:v.desktop_origin.y};out.scale=v.scale
15
+ }else{const viewport=resolution(v.viewport_resolution);if(!viewport)return null;out.viewport_resolution=viewport}
16
+ return out
17
+ }
18
+ export function avatarActivity(v){
19
+ if(!v||v.protocol!==AVATAR_ACTIVITY_PROTOCOL||!['avatar.started','avatar.stopped','avatar.hourly'].includes(v.event)||!id(v.event_id)||!id(v.instance_id)||!Number.isSafeInteger(v.sequence)||v.sequence<0||v.sequence>1000000)throw Error('invalid_avatar_activity')
20
+ if(!['web','desktop'].includes(v.presentation)||!sizes.includes(v.size)||!sizes.includes(v.bubble_size)||typeof v.notifications_enabled!=='boolean'||!finite(v.timestamp_ms,0,1e15)||!finite(v.uptime_ms,0,1e12))throw Error('invalid_avatar_activity')
21
+ for(const key of ['pending_count','notification_count'])if(v[key]!==null&&(!Number.isSafeInteger(v[key])||v[key]<0||v[key]>100000))throw Error('invalid_avatar_activity')
22
+ const position=v.position===null?null:avatarGeometry(v.position);if(v.position!==null&&!position)throw Error('invalid_avatar_position')
23
+ const out={protocol:AVATAR_ACTIVITY_PROTOCOL,event:v.event,event_id:v.event_id,instance_id:v.instance_id,sequence:v.sequence,timestamp_ms:v.timestamp_ms,uptime_ms:v.uptime_ms,presentation:v.presentation,size:v.size,bubble_size:v.bubble_size,notifications_enabled:v.notifications_enabled,pending_count:v.pending_count,notification_count:v.notification_count,position}
24
+ if(v.event==='avatar.stopped')out.reason=['disabled','pagehide','unmount','restart','unavailable'].includes(v.reason)?v.reason:'unavailable'
25
+ return out
26
+ }
27
+ export class AvatarActivityClock {
28
+ constructor({snapshot,send,now=Date.now,uuid=()=>crypto.randomUUID()}){Object.assign(this,{snapshot,send,now,uuid});this.active=null}
29
+ start(presentation){if(this.active?.presentation===presentation)return;if(this.active)this.stop('restart');const now=this.now();this.active={id:this.uuid(),presentation,start:now,next:now+AVATAR_ACTIVITY_HOUR,sequence:0};this.emit('avatar.started')}
30
+ emit(event,reason){const a=this.active;if(!a)return;const now=this.now();try{this.send(avatarActivity({...this.snapshot(),protocol:AVATAR_ACTIVITY_PROTOCOL,event,event_id:this.uuid(),instance_id:a.id,sequence:a.sequence++,timestamp_ms:now,uptime_ms:Math.max(0,now-a.start),presentation:a.presentation,reason}))}catch{}}
31
+ tick(){if(this.active&&this.now()>=this.active.next){this.active.next=this.now()+AVATAR_ACTIVITY_HOUR;this.emit('avatar.hourly')}}
32
+ stop(reason){if(!this.active)return;this.emit('avatar.stopped',reason);this.active=null}
33
+ }
@@ -0,0 +1,85 @@
1
+ import {avatarLocalState,avatarMenuAction,avatarMenuResult} from './avatar-menu.mjs'
2
+ import {sizeButton,nextAvatarSize} from './avatar-ui.mjs'
3
+ const labels={completed:'本轮已完成',failed:'执行失败',stopped:'已停止',approval:'等待授权',question:'等待回答',plan_review:'等待方案确认'}
4
+ const names={small:'紧凑',medium:'标准',large:'宽松'}
5
+ const paths={open:'M14 3h7v7m0-7L10 14M10 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5',pending:'M8 4h8m-9 0H5v17h14V4h-2M8 3h8v4H8zM8 12h8m-8 4h5',bubble:'M5 4h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-5 3v-3H3V6a2 2 0 0 1 2-2zM7 9h10m-10 4h6',tutorial:'m9 5 10 7-10 7z',settings:'M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8M9 3h6l1 3 3 1 2 5-2 5-3 1-1 3H9l-1-3-3-1-2-5 2-5 3-1z',hide:'m4 4 16 16M9 5a11 11 0 0 1 12 7l-3 4M6 6a13 13 0 0 0-5 6s4 7 11 7l3-1M10 10a3 3 0 0 0 4 4',back:'m14 5-7 7 7 7'}
6
+ const icon=name=>{const s=document.createElementNS('http://www.w3.org/2000/svg','svg');s.setAttribute('viewBox','0 0 24 24');s.setAttribute('aria-hidden','true');s.innerHTML=`<path d="${paths[name]||paths.pending}"/>`;return s}
7
+ export function mountAvatarMenu({anchor,viewport=()=>[0,0,innerWidth,innerHeight],send,changed=()=>{}}){
8
+ let state={items:[],running:0,enabled:true,size:'large',bubble:'medium'},root,toast,badge,section='main',timer,dead=false,point,previous,toastId,ackTimer
9
+ const style=document.createElement('style');style.textContent=`
10
+ .duet-pet-menu{position:fixed;z-index:2147483601;box-sizing:border-box;width:264px;max-width:calc(100vw - 24px);padding:9px;border:1px solid #a7c5dc30;border-radius:18px;background:#142330f7;color:#eaf2f8;font:13px/1.5 Inter,"PingFang SC",sans-serif;box-shadow:0 16px 48px #0004,0 2px 8px #0002;backdrop-filter:blur(20px);pointer-events:auto;overflow:auto}
11
+ .duet-pet-menu button{position:relative;display:flex;align-items:center;justify-content:flex-start;gap:10px;box-sizing:border-box;width:100%;min-height:39px;margin:0;border:0;border-radius:10px;padding:8px 11px;background:transparent;color:inherit;text-align:left;font:inherit;cursor:pointer;height:auto;flex-shrink:0;letter-spacing:normal}
12
+ .duet-pet-menu button>[data-label]{min-width:0;flex:1;overflow-wrap:anywhere}
13
+ .duet-pet-menu button>svg,.duet-pet-menu [data-size-icon]{display:flex;align-items:center;justify-content:center;width:20px;height:20px;flex:0 0 20px}
14
+ [data-duet-notice-badge][hidden]{display:none!important}
15
+ .duet-pet-menu button:hover,.duet-pet-menu button:focus-visible{background:#b3daff16;outline:none}
16
+ .duet-pet-menu svg{width:20px;height:20px;fill:none;stroke:currentColor;stroke-width:1.5;stroke-linecap:round;stroke-linejoin:round;flex-shrink:0;color:#a7bdd0}
17
+ .duet-pet-menu [data-wordmark]{font:700 28px/1.1 Inter,"PingFang SC",sans-serif;letter-spacing:-1.1px;padding:11px 12px 15px}
18
+ .duet-pet-menu [data-wordmark] span{color:#ed9b35}.duet-pet-menu hr{border:0;border-top:1px solid #a7c5dc1c;margin:6px 9px}
19
+ .duet-pet-menu [data-value]{margin-left:auto;color:#9eb1c0;font-size:12px}.duet-pet-menu [data-switch]{position:relative;display:block;width:28px;height:16px;border-radius:10px;background:#53616e;flex-shrink:0;transition:background .15s}
20
+ .duet-pet-menu [data-switch]:after{content:'';position:absolute;top:2px;left:2px;width:12px;height:12px;border-radius:50%;background:white;transition:transform .15s}.duet-pet-menu [aria-checked=true] [data-switch]{background:#6eabc9}.duet-pet-menu [aria-checked=true] [data-switch]:after{transform:translateX(12px)}
21
+ .duet-pet-menu [data-bubble-preview]{margin:12px 9px;padding:12px 14px;border-radius:15px 15px 15px 4px;border:1px solid #8dc5ed45;background:#213b4c;white-space:pre-wrap;overflow:auto;line-height:1.7;scrollbar-width:thin}
22
+ .duet-pet-menu p{margin:10px 12px;color:#a7bdd0}.duet-pet-menu [data-notice-title]{padding:8px 11px;font-weight:600}
23
+ `;document.head.append(style)
24
+ const place=node=>{
25
+ const [x,y,w,h]=viewport();node.style.maxHeight=Math.max(40,h-24)+'px';node.style.maxWidth=Math.max(40,w-24)+'px'
26
+ const a=anchor().getBoundingClientRect(),b=node.getBoundingClientRect(),top=point?.y??(a.top-b.height-12>=y?a.top-b.height-12:a.bottom+12)
27
+ node.style.left=Math.max(x+12,Math.min(point?.x??a.left,x+w-b.width-12))+'px';node.style.top=Math.max(y+12,Math.min(top,y+h-b.height-12))+'px'
28
+ }
29
+ const close=()=>{root?.remove();root=null;point=null;if(previous?.isConnected)previous.focus({preventScroll:true});changed()}
30
+ const command=(action,value,id)=>send(avatarMenuAction({type:'menu_action',request_id:crypto.randomUUID(),action,value,id}))
31
+ const row=(label,action,iconName=action,id)=>{
32
+ const b=document.createElement('button');b.type='button';b.setAttribute('role','menuitem');b.dataset.menuAction=action
33
+ if(paths[iconName])b.append(icon(iconName));const t=document.createElement('span');t.dataset.label='';t.textContent=label;b.append(t)
34
+ b.onclick=()=>{if(['pending','bubble_panel','back'].includes(action)){section=action==='back'?'main':action;render();return}close();command(action,undefined,id)};return b
35
+ }
36
+ const countLabel=()=>{const n=state.items.filter(i=>i.pending||i.unread).length;return '待处理事项与通知'+(n?`(${n})`:'')}
37
+ const valueSpan=b=>{const v=document.createElement('span');v.dataset.value='';b.append(v);return v}
38
+ const refreshControls=()=>{
39
+ if(!root)return
40
+ const size=root.querySelector('[data-menu-action=size]');if(size){const glyph=size.querySelector('[data-size-icon]');sizeButton(glyph,state.size);size.querySelector('[data-value]').textContent={large:'大',medium:'中',small:'小'}[state.size];size.setAttribute('aria-label',glyph.getAttribute('aria-label'))}
41
+ const notify=root.querySelector('[data-menu-action=notifications]');notify?.setAttribute('aria-checked',String(state.enabled))
42
+ const bubble=root.querySelector('[data-menu-action=bubble]');if(bubble){bubble.querySelector('[data-value]').textContent=names[state.bubble];bubble.setAttribute('aria-label',`气泡大小:${names[state.bubble]},点击切换`)}
43
+ const preview=root.querySelector('[data-bubble-preview]');if(preview){preview.style.maxHeight={small:60,medium:110,large:180}[state.bubble]+'px';preview.dataset.size=state.bubble}
44
+ const pending=root.querySelector('[data-menu-action=pending] span');if(pending)pending.textContent=countLabel()
45
+ place(root);changed()
46
+ }
47
+ const render=()=>{
48
+ if(!root)return;root.replaceChildren()
49
+ const title=document.createElement('div');title.dataset.wordmark='';title.append('duet');const dot=document.createElement('span');dot.textContent='.';title.append(dot);root.append(title)
50
+ const divider=()=>root.append(document.createElement('hr'))
51
+ if(section==='main'){
52
+ root.append(row('打开 DSH','open_dsh','open'),row(countLabel(),'pending'))
53
+ const notify=row('任务通知','notifications','pending');notify.setAttribute('role','menuitemcheckbox');const toggle=document.createElement('span');toggle.dataset.switch='';notify.append(toggle);notify.onclick=()=>{state.enabled=!state.enabled;refreshControls();command('notifications',state.enabled)};root.append(notify);divider()
54
+ const size=row('形象大小','size'),glyph=document.createElement('span');glyph.dataset.sizeIcon='';size.prepend(glyph);valueSpan(size);size.onclick=()=>{state.size=nextAvatarSize(state.size);refreshControls();command('size',state.size)}
55
+ root.append(size,row('气泡大小','bubble_panel','bubble'));divider()
56
+ root.append(row('使用教学','tutorial'),row('duet 设置','settings'),row('隐藏形象','hide'))
57
+ }else if(section==='bubble_panel'){
58
+ const cycle=row('气泡大小','bubble','bubble');valueSpan(cycle);cycle.onclick=()=>{state.bubble={small:'medium',medium:'large',large:'small'}[state.bubble];refreshControls();command('bubble',state.bubble)};root.append(cycle)
59
+ const sample=document.createElement('div');sample.dataset.bubblePreview='';sample.setAttribute('aria-label','示例气泡');sample.textContent='好的,我来帮你。\n任务完成后,我会在这里告诉你结果。\n也可以随时打断我,继续聊聊你的新想法。\n这是一段较长的文字,你可以看看当前气泡能显示多少内容。';root.append(sample,row('返回','back'))
60
+ }else{
61
+ if(!state.available){const p=document.createElement('p');p.textContent='正在连接 DSH';root.append(p)}
62
+ if(!state.items.length){const p=document.createElement('p');p.textContent='暂时没有待处理事项或新通知';root.append(p)}
63
+ for(const item of state.items){const b=row(`${item.unread?'● ':''}${item.name||'未命名会话'} · ${labels[item.status]}`,'view','pending',item.id);b.title=item.summary;root.append(b)}root.append(row('返回','back'))
64
+ }
65
+ refreshControls();root.querySelector('button')?.focus({preventScroll:true})
66
+ }
67
+ const open=(event,tab='main')=>{
68
+ if(dead)return;event?.preventDefault();event?.stopPropagation();close();previous=document.activeElement;section=tab;point=event&&Number.isFinite(event.clientX)&&event.clientX>0?{x:event.clientX,y:event.clientY}:null
69
+ root=document.createElement('div');root.className='duet-pet-menu';root.dataset.duetContextMenu='';root.setAttribute('role','menu');root.setAttribute('aria-label','duet 形象菜单');document.body.append(root);render()
70
+ }
71
+ const outside=e=>{if(root&&!root.contains(e.target)){e.preventDefault();e.stopPropagation();close()}}
72
+ const keys=e=>{if(!root)return;if(e.key==='Escape'){e.preventDefault();e.stopImmediatePropagation();close();return}const buttons=[...root.querySelectorAll('button')],index=buttons.indexOf(document.activeElement);if(['ArrowDown','ArrowUp','Home','End','Tab'].includes(e.key)){e.preventDefault();buttons[e.key==='Home'?0:e.key==='End'?buttons.length-1:(index+(e.key==='ArrowUp'||e.key==='Tab'&&e.shiftKey?-1:1)+buttons.length)%buttons.length]?.focus()}}
73
+ const decorate=(node,label)=>{node.className='duet-pet-menu';node.setAttribute('aria-label',label)}
74
+ const update=value=>{
75
+ state=avatarLocalState(value);badge??=document.createElement('button');badge.type='button';badge.dataset.duetNoticeBadge='';badge.style.cssText='position:fixed;z-index:2147483600;border:0;border-radius:12px;background:#dcefff;color:#185a89;font:12px system-ui;padding:4px 7px;cursor:pointer;pointer-events:auto'
76
+ const count=state.items.filter(i=>i.pending||i.unread).length;badge.textContent=count?String(count):'';badge.setAttribute('aria-label',countLabel());badge.hidden=!count||!state.enabled;badge.onclick=e=>open(e,'pending');if(!badge.isConnected)document.body.append(badge)
77
+ const a=anchor().getBoundingClientRect(),[x,y,w,h]=viewport();badge.style.left=Math.max(x+12,Math.min((a.right??a.left+a.width)-24,x+w-36))+'px';badge.style.top=Math.max(y+12,Math.min(a.top,y+h-30))+'px'
78
+ if(toastId!==state.toast){clearTimeout(timer);clearTimeout(ackTimer);toast?.remove();toast=null;toastId=state.toast;const item=state.items.find(i=>i.id===state.toast);if(item){toast=document.createElement('section');toast.dataset.duetLocalNotice='';decorate(toast,'DSH 任务通知');const p=document.createElement('div');p.dataset.noticeTitle='';p.textContent=`${item.name||'未命名会话'} · ${labels[item.status]}`;toast.append(p,row(item.pending?'去处理':'查看','view','open',item.id),row('收起','dismiss','hide',item.id));document.body.append(toast);place(toast);if(!item.pending)timer=setTimeout(()=>{toast?.remove();toast=null;changed()},8000)}}
79
+ refreshControls();changed()
80
+ }
81
+ const result=value=>{const r=avatarMenuResult(value);if(!r.message)return;clearTimeout(ackTimer);toast?.remove();toast=document.createElement('section');decorate(toast,'操作提示');toast.textContent=r.message;document.body.append(toast);place(toast);changed();ackTimer=setTimeout(()=>{toast?.remove();toast=null;changed()},4000)}
82
+ const reposition=()=>{if(root)place(root);if(toast)place(toast)}
83
+ document.addEventListener('pointerdown',outside,true);document.addEventListener('keydown',keys,true);window.addEventListener('resize',reposition);window.addEventListener('blur',close)
84
+ return{open,close,update,result,get active(){return Boolean(root)},regions(){return[root,toast,badge].filter(n=>n?.isConnected&&!n.hidden).map(n=>{const r=n.getBoundingClientRect();return[r.x,r.y,r.width,r.height]})},dispose(){dead=true;close();style.remove();clearTimeout(timer);clearTimeout(ackTimer);toast?.remove();badge?.remove();document.removeEventListener('pointerdown',outside,true);document.removeEventListener('keydown',keys,true);window.removeEventListener('resize',reposition);window.removeEventListener('blur',close)}}
85
+ }