dsh-duet 0.1.10 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +19 -1
  2. package/assets/avatar/THREE-LICENSE.txt +21 -0
  3. package/assets/avatar/character.glb +0 -0
  4. package/assets/avatar/desktop/character.glb +0 -0
  5. package/assets/avatar/desktop/companion.mjs +18 -0
  6. package/assets/avatar/desktop/index.html +33 -0
  7. package/assets/avatar/desktop/manifest.json +10 -0
  8. package/assets/avatar/desktop/portrait.png +0 -0
  9. package/assets/avatar/desktop/renderer.mjs +4230 -0
  10. package/assets/avatar/portrait.png +0 -0
  11. package/assets/avatar/renderer.mjs +4230 -0
  12. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Info.plist +36 -0
  13. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/MacOS/duet-avatar +0 -0
  14. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/Resources/duet companion.icns +0 -0
  15. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/_CodeSignature/CodeResources +128 -0
  16. package/desktop/bin/darwin-arm64/manifest.json +14 -0
  17. package/desktop/bin/win32-x64/duet-avatar.exe +0 -0
  18. package/desktop/bin/win32-x64/manifest.json +11 -0
  19. package/package.json +17 -5
  20. package/src/avatar/companion.html +33 -0
  21. package/src/avatar/companion.mjs +210 -0
  22. package/src/avatar/idle.mjs +9 -0
  23. package/src/avatar/lipsync.mjs +13 -0
  24. package/src/avatar/motion.mjs +93 -0
  25. package/src/avatar/renderer.mjs +90 -0
  26. package/src/avatar/surface.mjs +45 -0
  27. package/src/avatar/toolbar.mjs +49 -0
  28. package/src/client/audio.mjs +68 -3
  29. package/src/client/avatar-surfaces.mjs +83 -0
  30. package/src/client/avatar-tasks.mjs +68 -0
  31. package/src/client/avatar.mjs +218 -0
  32. package/src/client/browser.mjs +83 -35
  33. package/src/client/composer-bridge.mjs +5 -2
  34. package/src/client/connection-hint.mjs +2 -1
  35. package/src/client/consent.mjs +3 -1
  36. package/src/client/controls-layout.mjs +21 -9
  37. package/src/client/entry.js +26 -3
  38. package/src/client/feedback.mjs +19 -4
  39. package/src/client/identity.mjs +2 -2
  40. package/src/client/input-effect.mjs +51 -0
  41. package/src/client/notice.mjs +20 -4
  42. package/src/client/rpc.mjs +2 -1
  43. package/src/client/settings.html +124 -4
  44. package/src/client/transport.mjs +2 -2
  45. package/src/client/tutorial-adapter.mjs +4 -4
  46. package/src/client/tutorial.mjs +5 -3
  47. package/src/client/voices.mjs +137 -0
  48. package/src/host/assets.mjs +13 -0
  49. package/src/host/avatar-activity.mjs +24 -0
  50. package/src/host/avatar-assets.mjs +18 -0
  51. package/src/host/avatar.mjs +130 -0
  52. package/src/host/diagnostics.mjs +111 -7
  53. package/src/host/feedback-files.mjs +5 -1
  54. package/src/host/plugin.mjs +59 -4
  55. package/src/host/proxy.mjs +41 -6
  56. package/src/host/settings-migration.mjs +2 -1
  57. package/src/host/settings.mjs +19 -4
  58. package/src/host/voices.mjs +205 -0
  59. package/src/shared/avatar-activity.mjs +33 -0
  60. package/src/shared/avatar-menu-ui.mjs +85 -0
  61. package/src/shared/avatar-menu.mjs +83 -0
  62. package/src/shared/avatar-surface.mjs +24 -0
  63. package/src/shared/avatar-ui.mjs +91 -0
  64. package/src/shared/avatar.mjs +125 -0
  65. package/src/shared/nickname.mjs +13 -0
  66. package/src/shared/state.mjs +15 -4
@@ -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,205 @@
1
+ /** User-authorized reference upload and original-file proof. */
2
+ import {mkdir,readFile,writeFile,rename,lstat} from 'node:fs/promises'
3
+ import {join} from 'node:path'
4
+ import {randomUUID,createHash,createHmac} from 'node:crypto'
5
+ import {Agent as HTTPAgent,request as httpRequest} from 'node:http'
6
+ import {Agent as HTTPSAgent,request as httpsRequest} from 'node:https'
7
+ import {duetHome} from './storage-paths.mjs'
8
+
9
+ const VID=/^voice_[a-f0-9]{32}$/
10
+ const MAX=10*1024*1024
11
+ const VOICE_ISSUES=new Set(['voice_disabled','voice_audio_missing','voice_not_found'])
12
+ function voiceHTTP(){
13
+ const agents={'http:':new HTTPAgent({keepAlive:true,maxSockets:1,maxTotalSockets:4}),
14
+ 'https:':new HTTPSAgent({keepAlive:true,maxSockets:1,maxTotalSockets:4})}
15
+ return {close(){for(const agent of Object.values(agents))agent.destroy()},
16
+ fetch(url,options){return new Promise((resolve,reject)=>{
17
+ const request=(url.protocol==='https:'?httpsRequest:httpRequest)(url,{method:'POST',
18
+ agent:agents[url.protocol],headers:options.headers,signal:options.signal},response=>{
19
+ const chunks=[];let size=0
20
+ response.on('error',reject)
21
+ response.on('data',chunk=>{size+=chunk.length;if(size>16384){response.destroy();reject(Error('voice_response_too_large'))}else chunks.push(chunk)})
22
+ response.on('end',()=>{try{resolve(new Response([204,205,304].includes(response.statusCode)?null:Buffer.concat(chunks),{status:response.statusCode}))}catch(error){reject(error)}})
23
+ });request.on('error',reject);request.end(options.body)
24
+ })}}
25
+ }
26
+ export class DuetVoices {
27
+ constructor(getConfig,{root=join(duetHome(),'voices'),fetchImpl,scope}={}){
28
+ this.transport=fetchImpl?null:voiceHTTP()
29
+ this.getConfig=getConfig;this.root=root;this.fetch=fetchImpl||this.transport.fetch;this.scope=scope||(async()=>(await this.getConfig()).endpoints.online);this.tail=Promise.resolve()
30
+ this.feature={enabled:true,revision:-1};this.featureAt=0;this.featureEpoch=0
31
+ }
32
+ close(){this.transport?.close()}
33
+ async state(){
34
+ try{return JSON.parse(await readFile(join(this.root,'links.json'),'utf8'))}
35
+ catch(e){if(e.code==='ENOENT')return {selected:'default',voices:[]};throw Error('voice_links_unavailable')}
36
+ }
37
+ async save(state){
38
+ await mkdir(this.root,{recursive:true,mode:0o700})
39
+ const path=join(this.root,'links.json'),temp=path+'.'+randomUUID()+'.tmp'
40
+ await writeFile(temp,JSON.stringify(state),{mode:0o600,flag:'wx'});await rename(temp,path)
41
+ }
42
+ async public(){const s=await this.state();return {selected:this.feature.enabled?s.selected:'default',custom_voice_enabled:this.feature.enabled,voices:s.voices.map(({file,...v})=>v)}}
43
+ queue(work){const next=this.tail.then(work,work);this.tail=next.catch(()=>{});return next}
44
+ async resetDefault(){const s=await this.state();if(s.selected!=='default'){s.selected='default';await this.save(s)}}
45
+ async checkAvailability(force=false){
46
+ if(!force&&Date.now()-this.featureAt<15000)return
47
+ const epoch=this.featureEpoch
48
+ try{
49
+ const value=await this.remote('status',{})
50
+ if(epoch===this.featureEpoch&&typeof value.enabled==='boolean'&&Number.isInteger(value.revision)&&value.revision>=this.feature.revision){
51
+ this.feature=value;this.featureAt=Date.now()
52
+ }
53
+ }catch{/* A temporary outage does not reverse a known disabled policy. */}
54
+ if(!this.feature.enabled)await this.resetDefault()
55
+ }
56
+ refreshAvailability(){return this.queue(async()=>{
57
+ await this.checkAvailability()
58
+ if(this.feature.enabled){
59
+ const s=await this.state();let changed=false
60
+ for(const row of s.voices.filter(v=>v.issue)){
61
+ try{await this.remote('check',{voice_id:row.voice_id});delete row.issue;changed=true}
62
+ catch(e){if(VOICE_ISSUES.has(e.message)&&row.issue!==e.message){row.issue=e.message;changed=true}}
63
+ }
64
+ if(changed)await this.save(s)
65
+ }
66
+ return this.public()
67
+ })}
68
+ applyPolicy(value){
69
+ if(value?.enabled!==false||value?.selected!=='default')return Promise.resolve()
70
+ ++this.featureEpoch;this.feature={...this.feature,enabled:false};this.featureAt=0
71
+ return this.queue(()=>this.resetDefault())
72
+ }
73
+ applyIssue(value){
74
+ if(!VOICE_ISSUES.has(value?.code)||!VID.test(value?.voice_id))return Promise.resolve()
75
+ return this.queue(async()=>{
76
+ const s=await this.state(),row=s.voices.find(v=>v.voice_id===value.voice_id)
77
+ if(row){row.issue=value.code;if(s.selected===row.voice_id)s.selected='default';await this.save(s)}
78
+ })
79
+ }
80
+ async original(row){
81
+ if(!/^[a-f0-9]{64}\.audio$/.test(row.file))throw Error('voice_original_unavailable')
82
+ try{
83
+ const p=join(this.root,row.file),st=await lstat(p)
84
+ if(!st.isFile()||st.isSymbolicLink()||st.size>MAX)throw Error('voice_original_unavailable')
85
+ return await readFile(p)
86
+ }catch{throw Error('voice_original_unavailable')}
87
+ }
88
+ async remote(operation,body,raw,uploadId,voiceId){
89
+ const c=await this.getConfig(),url=new URL(c.endpoints.online)
90
+ url.protocol=url.protocol==='wss:'?'https:':'http:';url.pathname='/voices/'+operation;url.search='';url.hash=''
91
+ const r=await this.fetch(url,{method:'POST',redirect:'error',signal:AbortSignal.timeout(operation==='status'?3000:45000),
92
+ headers:{...(c.authorization?{Authorization:c.authorization}:{}),'Content-Type':raw?'application/octet-stream':'application/json',...(uploadId?{'X-Upload-Id':uploadId}:{}),...(voiceId?{'X-Voice-Id':voiceId}:{})},body:raw||JSON.stringify(body)})
93
+ const reader=r.body.getReader();let data=Buffer.alloc(0)
94
+ try{while(true){const {done,value}=await reader.read();if(done)break;data=Buffer.concat([data,value]);if(data.length>16384)throw Error('voice_response_too_large')}}finally{await reader.cancel().catch(()=>{})}
95
+ let result;try{result=JSON.parse(data)}catch{throw Error('voice_service_unavailable')}
96
+ if(!r.ok)throw Error(result.error?.code||result.detail||'voice_service_unavailable')
97
+ return result
98
+ }
99
+ update(body){return this.queue(async()=>{
100
+ try{return await this.mutate(body)}catch(error){
101
+ if(error.message==='custom_voice_disabled'){++this.featureEpoch;this.feature.enabled=false;this.featureAt=0;await this.resetDefault()}
102
+ if(VOICE_ISSUES.has(error.message)&&VID.test(body.voice_id)){
103
+ const s=await this.state(),row=s.voices.find(v=>v.voice_id===body.voice_id)
104
+ if(row){row.issue=error.message;if(s.selected===row.voice_id)s.selected='default';await this.save(s)}
105
+ }
106
+ throw error
107
+ }
108
+ })}
109
+ async mutate(body){
110
+ if(body.op!=='remove'&&!(body.op==='select'&&body.voice_id==='default')){
111
+ await this.checkAvailability()
112
+ if(!this.feature.enabled)throw Error('custom_voice_disabled')
113
+ }
114
+ const s=await this.state()
115
+ if(body.op==='select'){
116
+ if(body.voice_id!=='default'&&!s.voices.some(v=>v.voice_id===body.voice_id))throw Error('voice_not_found')
117
+ const row=s.voices.find(v=>v.voice_id===body.voice_id)
118
+ if(row?.issue){await this.remote('check',{voice_id:row.voice_id});delete row.issue}
119
+ s.selected=body.voice_id;await this.save(s);return this.public()
120
+ }
121
+ if(body.op==='upload'){
122
+ if(s.voices.length>=5)throw Error('local_voice_limit')
123
+ if(typeof body.audio!=='string'||body.audio.length>Math.ceil(MAX/3)*4)throw Error('invalid_audio_size')
124
+ const raw=Buffer.from(body.audio,'base64');if(!raw.length||raw.length>MAX||raw.toString('base64')!==body.audio)throw Error('invalid_audio_size')
125
+ const label=typeof body.name==='string'?body.name.trim():''
126
+ if(!label||label.length>40||/[\x00-\x1f]/.test(label))throw Error('invalid_voice_name')
127
+ const file=createHash('sha256').update(raw).digest('hex')+'.audio'
128
+ await mkdir(this.root,{recursive:true,mode:0o700})
129
+ await writeFile(join(this.root,file),raw,{mode:0o600})
130
+ const scope=await this.scope()
131
+ const value=await this.remote('upload',null,raw,randomUUID())
132
+ if(!VID.test(value.voice_id))throw Error('invalid_voice_response')
133
+ s.voices.push({voice_id:value.voice_id,name:label,file,scope,ref_text:value.ref_text||'',status:value.status})
134
+ await this.save(s);return this.public()
135
+ }
136
+ const row=s.voices.find(v=>v.voice_id===body.voice_id)
137
+ if(!row)throw Error('voice_not_found')
138
+ const sameService=row.scope===await this.scope()
139
+ if(!sameService&&body.op!=='remove')throw Error('voice_service_changed')
140
+ if(body.op==='restore'){
141
+ if(row.issue==='voice_disabled')throw Error('voice_disabled')
142
+ let raw
143
+ if(body.audio!==undefined){
144
+ if(typeof body.audio!=='string'||body.audio.length>Math.ceil(MAX/3)*4)throw Error('invalid_audio_size')
145
+ raw=Buffer.from(body.audio,'base64')
146
+ if(!raw.length||raw.length>MAX||raw.toString('base64')!==body.audio)throw Error('invalid_audio_size')
147
+ }else raw=await this.original(row)
148
+ const v=await this.remote('restore',null,raw,undefined,row.voice_id)
149
+ if(v.voice_id!==row.voice_id)throw Error('invalid_voice_response')
150
+ const file=createHash('sha256').update(raw).digest('hex')+'.audio'
151
+ await writeFile(join(this.root,file),raw,{mode:0o600})
152
+ Object.assign(row,{file,ref_text:v.ref_text,status:v.status});delete row.issue;s.selected=row.voice_id
153
+ }else if(body.op==='refresh'){
154
+ const v=await this.withProof(row,'info',{voice_id:row.voice_id});row.ref_text=v.ref_text;row.status=v.status
155
+ }else if(body.op==='text'){
156
+ if(typeof body.ref_text!=='string'||!body.ref_text.trim()||body.ref_text.length>400)throw Error('invalid_ref_text')
157
+ const v=await this.withProof(row,'text',{voice_id:row.voice_id,ref_text:body.ref_text})
158
+ if(!VID.test(v.voice_id))throw Error('invalid_voice_response')
159
+ if(s.selected===row.voice_id)s.selected=v.voice_id
160
+ Object.assign(row,{voice_id:v.voice_id,ref_text:v.ref_text,status:v.status})
161
+ }else if(body.op==='remove'){
162
+ if(sameService)await this.remote('release',{voice_id:row.voice_id})
163
+ s.voices=s.voices.filter(v=>v!==row);if(s.selected===row.voice_id)s.selected='default'
164
+ }else throw Error('invalid_voice_operation')
165
+ await this.save(s);return this.public()
166
+ }
167
+ async prepare(){
168
+ return this.queue(async()=>{
169
+ if((await this.state()).selected==='default')return 'default'
170
+ await this.checkAvailability(true)
171
+ const s=await this.state();if(s.selected==='default'||!this.feature.enabled)return 'default'
172
+ const row=s.voices.find(v=>v.voice_id===s.selected);if(!row)throw Error('voice_not_found')
173
+ if(row.scope!==await this.scope())throw Error('voice_service_changed')
174
+ return row.voice_id
175
+ })
176
+ }
177
+ async withProof(row,op,body){
178
+ try{return await this.remote(op,body)}catch(error){
179
+ if(error.message!=='voice_proof_required')throw error
180
+ await this.authorize(row)
181
+ return this.remote(op,body)
182
+ }
183
+ }
184
+ async authorize(row){
185
+ const c=await this.remote('challenge',{voice_id:row.voice_id})
186
+ if(c.authorized===true)return
187
+ const result=await this.remote('verify',await this.proof(c,row))
188
+ if(result.authorized!==true)throw Error('voice_proof_invalid')
189
+ }
190
+ async respondChallenge(c){
191
+ await this.tail
192
+ const s=await this.state(),row=s.voices.find(v=>v.voice_id===s.selected)
193
+ if(!row||row.voice_id!==c?.voice_id||row.scope!==await this.scope())throw Error('voice_proof_invalid')
194
+ return this.proof(c,row)
195
+ }
196
+ async proof(c,row){
197
+ if(c.protocol!=='voice_possession_v1'||c.voice_id!==row.voice_id||!/^\w{32}$/.test(c.challenge_id)||
198
+ !/^[a-f0-9]{64}$/.test(c.nonce)||!/^[a-f0-9]{64}$/.test(c.binding)||!Number.isInteger(c.expires_at)||
199
+ c.expires_at<=Date.now()/1000||c.expires_at>Date.now()/1000+300)throw Error('invalid_voice_challenge')
200
+ const raw=await this.original(row),context={}
201
+ for(const k of ['binding','challenge_id','expires_at','protocol','voice_id'])context[k]=c[k]
202
+ const proof=createHmac('sha256',Buffer.from(c.nonce,'hex')).update(JSON.stringify(context)).update(Buffer.from([0])).update(raw).digest('hex')
203
+ return {challenge_id:c.challenge_id,proof}
204
+ }
205
+ }
@@ -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
+ }
@@ -0,0 +1,83 @@
1
+ /** Local-only presentation protocol. No remote URLs, credentials or executable payloads. */
2
+ export const AVATAR_LOCAL_PROTOCOL='avatar_local_v1'
3
+ export const NOTICE_KEY='dsh.duet.avatar.notices.v1'
4
+ export const MENU_ACTIONS=['open_dsh','pending','settings','tutorial','hide','notifications','size','bubble','view','dismiss']
5
+ const sizes=['small','medium','large'], statuses=['completed','failed','stopped','approval','question','plan_review']
6
+ export function noticePreferences(storage=globalThis.localStorage){
7
+ try {const p=JSON.parse(storage.getItem(NOTICE_KEY));return {enabled:p?.enabled!==false,snoozeUntil:0,bubble:sizes.includes(p?.bubble)?p.bubble:'medium'}}
8
+ catch{return {enabled:true,snoozeUntil:0,bubble:'medium'}}
9
+ }
10
+ export function saveNoticePreferences(p,storage=globalThis.localStorage){
11
+ const clean={enabled:p.enabled!==false,snoozeUntil:Number.isFinite(p.snoozeUntil)?Math.max(0,p.snoozeUntil):0,bubble:sizes.includes(p.bubble)?p.bubble:'medium'}
12
+ storage.setItem(NOTICE_KEY,JSON.stringify(clean));return clean
13
+ }
14
+ const text=(v,n)=>typeof v==='string'?v.slice(0,n):''
15
+ export function avatarMenuAction(v){
16
+ if(v?.type!=='menu_action'||!MENU_ACTIONS.includes(v.action)||!/^[a-zA-Z0-9-]{1,64}$/.test(v.request_id||''))throw Error('invalid_avatar_menu_action')
17
+ const out={type:'menu_action',request_id:v.request_id,action:v.action}
18
+ if(['size','bubble'].includes(v.action)){if(!sizes.includes(v.value))throw Error('invalid_avatar_size');out.value=v.value}
19
+ if(['view','dismiss'].includes(v.action)){if(typeof v.id!=='string'||!v.id||v.id.length>512)throw Error('invalid_avatar_notice');out.id=v.id}
20
+ if(v.action==='notifications'){if(typeof v.value!=='boolean')throw Error('invalid_avatar_preference');out.value=v.value}
21
+ if(v.action==='snooze'){if(![0,30].includes(v.value))throw Error('invalid_avatar_snooze');out.value=v.value}
22
+ return out
23
+ }
24
+ export function avatarLocalState(v){
25
+ if(v?.type!=='local_state'||v.protocol!==AVATAR_LOCAL_PROTOCOL||!Number.isSafeInteger(v.revision)||v.revision<0||!Array.isArray(v.items)||v.items.length>32)throw Error('invalid_avatar_local_state')
26
+ const items=v.items.map(i=>{
27
+ if(!statuses.includes(i.status)||!i.id||typeof i.id!=='string'||i.id.length>512)throw Error('invalid_avatar_notice')
28
+ return {id:i.id,session_id:text(i.session_id,256),name:text(i.name,100),status:i.status,summary:text(i.summary,240),pending:i.pending===true,unread:i.unread===true}
29
+ })
30
+ while(JSON.stringify(items).length>12000)items.pop()
31
+ return {type:'local_state',protocol:AVATAR_LOCAL_PROTOCOL,revision:v.revision,items,
32
+ size:sizes.includes(v.size)?v.size:'large',bubble:sizes.includes(v.bubble)?v.bubble:'medium',enabled:v.enabled!==false,
33
+ snoozed:v.snoozed===true,running:Math.max(0,Math.min(10000,Number(v.running)||0)),available:v.available===true,
34
+ toast:items.some(i=>i.id===v.toast)?v.toast:null}
35
+ }
36
+ export function avatarMenuResult(v){
37
+ if(v?.type!=='menu_result'||!/^[a-zA-Z0-9-]{1,64}$/.test(v.request_id||''))throw Error('invalid_avatar_menu_result')
38
+ return {type:'menu_result',request_id:v.request_id,ok:v.ok===true,message:text(v.message,180)}
39
+ }
40
+ /** Incremental snapshots, scope fencing and stable IDs; never infer success from text. */
41
+ export class AvatarNotices {
42
+ constructor(){this.items=new Map();this.seen=new Set();this.dismissed=new Set();this.scope=null;this.epoch=null;this.revision=0;this.order=0;this.toast=null;this.toastAt=0;this.running=0}
43
+ update({scope,epoch,sessions=[],results=[],interactions=[]}){
44
+ if(scope!==this.scope||epoch!==this.epoch){this.items.clear();this.seen.clear();this.dismissed.clear();this.toast=null;this.scope=scope;this.epoch=epoch}
45
+ const allowed=new Map(sessions.filter(s=>!s.archived&&s.origin!=='subagent').map(s=>[s.session_id,s]))
46
+ this.running=[...allowed.values()].filter(s=>s.running===true).length
47
+ for(const [id,item]of this.items)if(!allowed.has(item.session_id))this.items.delete(id)
48
+ const pending=new Set()
49
+ for(const p of interactions){
50
+ if(!allowed.has(p.session_id)||!['approval','question','plan_review'].includes(p.kind)||!p.id)continue
51
+ const id='pending:'+p.id;pending.add(id)
52
+ const row=allowed.get(p.session_id),old=this.items.get(id)
53
+ const summary=p.kind==='approval'?p.reason:(p.questions?.[0]?.question||p.questions?.[0]?.text||'请到 DSH 查看并回答')
54
+ this.items.set(id,{id,order:old?.order??++this.order,session_id:p.session_id,name:row.label,status:p.kind,summary:typeof summary==='string'?summary.slice(0,240):'',pending:true,unread:old?.unread??true})
55
+ if(!old){this.toast=id;this.toastAt=Date.now()}
56
+ }
57
+ for(const[id,item]of this.items)if(item.pending&&!pending.has(id))this.items.delete(id)
58
+ for(const job of results){
59
+ if(!allowed.has(job.session_id)||!Number.isSafeInteger(job.completion_seq)||typeof job.id!=='string')continue
60
+ const id=`job:${epoch}:${job.id}:${job.completion_seq}`;if(this.seen.has(id))continue
61
+ this.seen.add(id)
62
+ const status=job.turn_end_reason==='aborted'?'stopped':job.status==='failed'?'failed':job.status==='succeeded'&&job.turn_end_reason==='completed'?'completed':null
63
+ if(!status)continue
64
+ const row=allowed.get(job.session_id)
65
+ this.items.set(id,{id,order:++this.order,session_id:job.session_id,name:row.label,status,summary:status==='failed'?text(job.error,240):'',pending:false,unread:true})
66
+ this.toast=id;this.toastAt=Date.now()
67
+ }
68
+ while(this.seen.size>1024)this.seen.delete(this.seen.values().next().value)
69
+ const rows=[...this.items.values()].sort((a,b)=>Number(b.pending)-Number(a.pending)||Number(b.unread)-Number(a.unread)||b.order-a.order)
70
+ this.items=new Map(rows.slice(0,32).map(i=>[i.id,i]))
71
+ if(!this.items.has(this.toast))this.toast=null
72
+ for(const id of this.dismissed)if(!this.items.has(id))this.dismissed.delete(id)
73
+ this.revision++
74
+ }
75
+ read(id){const item=this.items.get(id);if(item)item.unread=false;if(this.toast===id)this.toast=null;this.revision++}
76
+ dismiss(id){if(this.items.has(id))this.dismissed.add(id);if(this.toast===id)this.toast=null;this.revision++}
77
+ state(prefs,size,available=true){
78
+ const pending=[...this.items.values()].find(i=>i.pending&&i.unread&&!this.dismissed.has(i.id))
79
+ const toast=pending?.id??(Date.now()-this.toastAt<=8000?this.toast:null)
80
+ return avatarLocalState({type:'local_state',protocol:AVATAR_LOCAL_PROTOCOL,revision:this.revision,items:[...this.items.values()],
81
+ ...prefs,size,available,running:this.running,snoozed:prefs.snoozeUntil>Date.now(),toast:available&&prefs.enabled&&prefs.snoozeUntil<=Date.now()?toast:null})
82
+ }
83
+ }
@@ -0,0 +1,24 @@
1
+ /** Bounded presentation-only IPC: never transfer DOM, HTML, tickets or callbacks. */
2
+ export const AVATAR_UI_PROTOCOL = 2
3
+ export function avatarSurface(value) {
4
+ if(value?.type!=='surface')throw Error('invalid_surface')
5
+ if(value.panel===null)return {type:'surface',panel:null}
6
+ const p=value.panel
7
+ if(!p||!/^s\d+$/.test(p.id)||!Number.isSafeInteger(p.revision)||p.revision<1||!Array.isArray(p.nodes)||p.nodes.length>160)throw Error('invalid_surface')
8
+ let length=0
9
+ const nodes=p.nodes.map(n=>{
10
+ if(!n||!['text','heading','button','checkbox','break'].includes(n.kind)||typeof n.text!=='string'||n.text.length>4000)throw Error('invalid_surface')
11
+ length+=n.text.length;if(length>10000)throw Error('invalid_surface')
12
+ const node={kind:n.kind,text:n.text}
13
+ if(n.kind==='button'||n.kind==='checkbox') {
14
+ if(!/^a\d+$/.test(n.action))throw Error('invalid_surface')
15
+ Object.assign(node,{action:n.action,disabled:n.disabled===true,checked:n.checked===true,gesture:n.gesture===true,label:String(n.label||'').slice(0,100)})
16
+ }
17
+ return node
18
+ })
19
+ return {type:'surface',panel:{id:p.id,revision:p.revision,nodes,target:['online','tts_only'].includes(p.target)?p.target:null}}
20
+ }
21
+ export function avatarSurfaceAction(v) {
22
+ if(v?.type!=='surface_action'||!/^s\d+$/.test(v.id)||!/^a\d+$/.test(v.action)||!Number.isSafeInteger(v.revision)||v.revision<1)throw Error('invalid_surface_action')
23
+ return {type:'surface_action',id:v.id,revision:v.revision,action:v.action,checked:v.checked===true}
24
+ }
@@ -0,0 +1,91 @@
1
+ import {avatarSize,AVATAR_SIZES} from './avatar.mjs'
2
+ const sizes=Object.keys(AVATAR_SIZES),names={large:'大(100%)',medium:'中(75%)',small:'小(50%)'}
3
+ export const nextAvatarSize=value=>sizes[(sizes.indexOf(avatarSize(value))+1)%sizes.length]
4
+ export function sizeButton(button,value,{label=false}={}) {
5
+ const size=avatarSize(value),title=`形象大小:${names[size]},点击切换为${names[nextAvatarSize(size)]}`
6
+ button.type='button';button.dataset.size=size;button.setAttribute('aria-label',title);button.title=title
7
+ const squares=sizes.filter(s=>s!==size).concat(size).map(s=>{
8
+ const side={large:18,medium:12,small:6}[s]
9
+ return `<rect data-size-square="${s}" x="3" y="${21-side}" width="${side}" height="${side}" stroke-width="${s===size?'2.8':'1'}"/>`
10
+ }).join('')
11
+ button.innerHTML=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">${squares}</svg>${label?`<span>${names[size]}</span>`:''}`
12
+ }
13
+
14
+ /** Same local confirmation in settings, web and the native companion. */
15
+ export function avatarCloseConfirmation({onChange=()=>{},floating=false,origin='page',anchor=()=>null,viewport=()=>[0,0,innerWidth,innerHeight]}={}) {
16
+ let pending=null,resolve,node,previous,dead=false
17
+ const position=()=>{
18
+ if(!floating||!node)return
19
+ const r=anchor()?.getBoundingClientRect();if(!r)return
20
+ const b=node.getBoundingClientRect()
21
+ const [x,y,w,h]=viewport()
22
+ const top=r.top-b.height-16>=y+12?r.top-b.height-16:r.bottom+12
23
+ node.style.left=Math.max(x+12,Math.min(r.left+r.width/2-b.width/2,x+w-b.width-12))+'px'
24
+ node.style.top=Math.max(y+12,Math.min(top,y+h-b.height-12))+'px'
25
+ node.style.bottom='auto'
26
+ }
27
+ const finish=accepted=>{
28
+ if(!pending)return
29
+ const done=resolve;pending=null;resolve=null
30
+ document.removeEventListener('keydown',keys,true);window.removeEventListener('resize',position);node?.remove();node=null
31
+ if(previous?.isConnected)previous.focus({preventScroll:true})
32
+ onChange();done(accepted)
33
+ }
34
+ const keys=e=>{
35
+ if(e.key==='Escape'){e.preventDefault();e.stopImmediatePropagation();finish(false)}
36
+ else if(e.key==='Tab'&&!floating){
37
+ e.preventDefault();const buttons=[...node.querySelectorAll('button')],index=buttons.indexOf(document.activeElement)
38
+ buttons[(index+(e.shiftKey?-1:1)+buttons.length)%buttons.length].focus()
39
+ }
40
+ }
41
+ return {
42
+ ask(){
43
+ if(dead)return Promise.resolve(false)
44
+ if(pending)return pending
45
+ previous=document.activeElement
46
+ pending=new Promise(r=>resolve=r)
47
+ node=document.createElement('div');node.dataset.avatarCloseOverlay=''
48
+ node.style.cssText='position:fixed;inset:0;z-index:2147483600;display:flex;align-items:center;justify-content:center;padding:12px;box-sizing:border-box;background:#0003;pointer-events:auto'
49
+ if(floating){node.dataset.duetAvatarSurface='110';node.dataset.duetSurfaceOrigin=origin;node.style.cssText='position:fixed;left:12px;bottom:100px;width:260px;max-width:calc(100vw - 24px);z-index:2147483600;pointer-events:auto'}
50
+ const panel=document.createElement('div');panel.dataset.avatarCloseConfirm=''
51
+ panel.setAttribute('role','alertdialog');panel.setAttribute('aria-modal',String(!floating));panel.setAttribute('aria-label','隐藏拟人角色?')
52
+ panel.style.cssText='box-sizing:border-box;width:260px;max-width:100%;padding:16px;border:1px solid #8dc5ed55;border-radius:16px;background:#142638;color:#e9f4ff;font:13px/1.6 system-ui;box-shadow:0 8px 28px #0005'
53
+ const title=document.createElement('div');title.textContent='隐藏拟人角色?';title.style.cssText='font-size:14px;font-weight:600;margin-bottom:14px'
54
+ const row=document.createElement('div');row.style.cssText='display:flex;justify-content:flex-end;gap:8px'
55
+ for(const [text,accept] of [['取消',false],['隐藏拟人角色',true]]){
56
+ const button=document.createElement('button');button.type='button';button.textContent=text;button.dataset.avatarCloseChoice=accept?'confirm':'cancel'
57
+ button.style.cssText=`font:13px system-ui;display:block;width:auto;min-width:56px;min-height:32px;padding:6px 10px;border:0;border-radius:8px;cursor:pointer;background:${accept?'#dcefff':'#294154'};color:${accept?'#185a89':'#e9f4ff'}`
58
+ button.onclick=()=>finish(accept);row.append(button)
59
+ }
60
+ panel.append(title,row);node.append(panel);document.body.append(node)
61
+ document.addEventListener('keydown',keys,true);window.addEventListener('resize',position);position();row.firstChild.focus();onChange()
62
+ return pending
63
+ },
64
+ cancel(){finish(false)},
65
+ dispose(){dead=true;finish(false)},
66
+ get element(){return node},
67
+ }
68
+ }
69
+
70
+ /** The real playback-page click stays here; native projection cannot grant activation. */
71
+ export function audioUnlockPanel({onEnable,onCancel}) {
72
+ const panel=document.createElement('section')
73
+ panel.dataset.duetAvatarSurface='95';panel.dataset.duetSurfaceOrigin='avatar';panel.dataset.duetAudioUnlock=''
74
+ panel.setAttribute('role','region');panel.setAttribute('aria-label','启用 duet 声音')
75
+ panel.style.cssText='position:fixed;z-index:100030;right:12px;bottom:88px;box-sizing:border-box;width:320px;max-width:calc(100vw - 24px);max-height:calc(100vh - 100px);overflow:auto;padding:22px;border-radius:20px;background:linear-gradient(145deg,#20364b,#142333);color:#edf6ff;border:1px solid #8dc5ed55;font:14px/1.65 system-ui,sans-serif;box-shadow:0 16px 48px #07152240;isolation:isolate;text-align:left'
76
+ const style=document.createElement('style')
77
+ style.textContent='[data-duet-audio-unlock] button:hover{filter:brightness(1.12)}[data-duet-audio-unlock] button:focus-visible{outline:2px solid #a4dcff;outline-offset:3px}[data-duet-audio-unlock] button:active{transform:translateY(1px)}'
78
+ const brand=document.createElement('div');brand.setAttribute('aria-hidden','true');brand.textContent='duet';brand.style.cssText='font:750 25px/1.2 system-ui;letter-spacing:-1px;margin:0 0 17px;color:#edf6ff'
79
+ const dot=document.createElement('span');dot.textContent='.';dot.style.color='#ed9b35';brand.append(dot)
80
+ const title=document.createElement('h3');title.textContent='音频播放权限';title.style.cssText='font:650 18px/1.4 system-ui;margin:0 0 8px;color:#edf6ff'
81
+ const text=document.createElement('p');text.textContent='点击启动音频播放权限。';text.style.cssText='font:14px/1.75 system-ui;margin:0;color:#bdcedf;white-space:normal;overflow-wrap:anywhere'
82
+ const actions=document.createElement('div');actions.style.cssText='display:flex;flex-wrap:wrap;justify-content:flex-end;gap:10px;margin-top:22px'
83
+ for(const [label,primary,callback] of [['暂不开启',false,onCancel],['启动音频播放',true,onEnable]]){
84
+ const button=document.createElement('button');button.type='button';button.textContent=label
85
+ button.style.cssText='appearance:none;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;min-height:40px;padding:9px 16px;border-radius:11px;font:600 14px/1.4 system-ui;cursor:pointer;white-space:nowrap;'+(primary?'background:#dcefff;color:#185a89;border:1px solid #dcefff;box-shadow:0 3px 10px #0002':'background:#ffffff08;color:#c2d3e3;border:1px solid #8dc5ed40')
86
+ if(primary)button.dataset.duetUserGesture=''
87
+ button.onclick=callback;actions.append(button)
88
+ }
89
+ panel.append(style,brand,title,text,actions)
90
+ return panel
91
+ }