dsh-duet 0.3.1 → 0.3.3

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 (52) hide show
  1. package/README.md +2 -0
  2. package/assets/avatar/desktop/companion.mjs +3 -4
  3. package/assets/avatar/desktop/manifest.json +1 -1
  4. package/desktop/bin/darwin-arm64/duet-avatar.app/Contents/MacOS/duet-avatar +0 -0
  5. package/desktop/bin/darwin-arm64/manifest.json +3 -3
  6. package/desktop/bin/win32-x64/duet-avatar.exe +0 -0
  7. package/desktop/bin/win32-x64/manifest.json +3 -3
  8. package/node_modules/dsh-duet-superagent/lib/duet.d.ts +17 -2
  9. package/node_modules/dsh-duet-superagent/lib/duet.js +99 -4
  10. package/node_modules/dsh-duet-superagent/lib/{feishu-rAGM9U9b.js → feishu-CwKBb-B_.js} +1 -1
  11. package/node_modules/dsh-duet-superagent/lib/feishu-watch.d.ts +1 -1
  12. package/node_modules/dsh-duet-superagent/lib/feishu-watch.js +1 -1
  13. package/node_modules/dsh-duet-superagent/lib/{github-pull-gSbjzypm.js → github-pull-DyfAy0yE.js} +1 -1
  14. package/node_modules/dsh-duet-superagent/lib/github-watch.d.ts +1 -1
  15. package/node_modules/dsh-duet-superagent/lib/github-watch.js +2 -2
  16. package/node_modules/dsh-duet-superagent/lib/index.js +2 -2
  17. package/node_modules/dsh-duet-superagent/lib/{poll-Dh7J1cdM.js → poll-BBkmV_GM.js} +4 -1
  18. package/node_modules/dsh-duet-superagent/lib/{registry-BTgyFZ8S.d.ts → registry-Ehgir8LC.d.ts} +70 -61
  19. package/node_modules/dsh-duet-superagent/lib/{runtime-mbw1-2iK.js → runtime-Ow0S-7ZZ.js} +44 -4
  20. package/package.json +2 -2
  21. package/src/avatar/companion.mjs +5 -3
  22. package/src/avatar/surface.mjs +6 -1
  23. package/src/client/agent-tasks.mjs +144 -17
  24. package/src/client/audio.mjs +1 -1
  25. package/src/client/avatar-surfaces.mjs +3 -3
  26. package/src/client/avatar.mjs +15 -2
  27. package/src/client/browser.mjs +24 -24
  28. package/src/client/composer-bridge.mjs +1 -1
  29. package/src/client/connection-hint.mjs +1 -1
  30. package/src/client/entry.js +2 -2
  31. package/src/client/feedback.mjs +1 -1
  32. package/src/client/identity.mjs +1 -1
  33. package/src/client/interactions.mjs +5 -4
  34. package/src/client/notice.mjs +30 -9
  35. package/src/client/settings.html +5 -4
  36. package/src/client/sidebar-layout.mjs +26 -0
  37. package/src/client/tutorial-adapter.mjs +5 -5
  38. package/src/client/tutorial.mjs +1 -1
  39. package/src/client/work-mode.mjs +12 -6
  40. package/src/host/agent-connection.mjs +6 -1
  41. package/src/host/assets.mjs +1 -0
  42. package/src/host/auth.mjs +13 -0
  43. package/src/host/avatar.mjs +32 -13
  44. package/src/host/plugin.mjs +22 -17
  45. package/src/host/proxy.mjs +3 -2
  46. package/src/host/sync-feed.mjs +3 -2
  47. package/src/shared/avatar-menu-ui.mjs +30 -12
  48. package/src/shared/avatar-menu.mjs +4 -1
  49. package/src/shared/avatar-surface.mjs +1 -0
  50. package/src/shared/avatar-ui.mjs +2 -0
  51. package/src/shared/state.mjs +29 -4
  52. package/src/shared/work-mode.mjs +20 -0
@@ -1,5 +1,6 @@
1
1
  /** duet Host entry: session operations, authenticated settings, and client assets. */
2
2
 
3
+ import { requestRejection } from './auth.mjs'
3
4
  import { readFile, mkdir, realpath } from 'node:fs/promises'
4
5
  import { homedir } from 'node:os'
5
6
  import { join } from 'node:path'
@@ -583,9 +584,9 @@ export function apply(ctx, options = {}) {
583
584
  return () => syncFeed.close()
584
585
  })
585
586
 
586
- const handleApi = async (req, res, pathname) => {
587
+ const handleApi = async (req, res, pathname, peer) => {
587
588
  if(pathname===`${ROUTE}/api/voices`){
588
- const rejection=ctx.connection.requestRejection(req)
589
+ const rejection=requestRejection(ctx, req, peer)
589
590
  if(rejection){sendError(res,rejection,'DSH connection required');return}
590
591
  try {
591
592
  if(req.method==='GET'){sendJson(res,200,await voices.refreshAvailability());return}
@@ -596,14 +597,14 @@ export function apply(ctx, options = {}) {
596
597
  return
597
598
  }
598
599
  if(req.method==='POST'&&pathname===`${ROUTE}/api/avatar/activity`){
599
- const rejection=ctx.connection.requestRejection(req)
600
+ const rejection=requestRejection(ctx, req, peer)
600
601
  if(rejection){sendError(res,rejection,'DSH connection required');return}
601
602
  if(!identityWriteAllowed(req)){sendError(res,403,'same-origin activity request required');return}
602
603
  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)))}
603
604
  catch{sendError(res,400,'invalid_avatar_activity')}return
604
605
  }
605
606
  if (req.method === 'POST' && pathname === `${ROUTE}/api/duet/nickname`) {
606
- const rejection = ctx.connection.requestRejection(req)
607
+ const rejection = requestRejection(ctx, req, peer)
607
608
  if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
608
609
  const boundRPC = req.headers['x-duplex-control-client'] === 'realtime-client-rpc-v1' && browserOwner(req)
609
610
  if (!identityWriteAllowed(req) && !boundRPC) { sendError(res, 403, 'same-origin nickname request required'); return }
@@ -623,7 +624,7 @@ export function apply(ctx, options = {}) {
623
624
  return
624
625
  }
625
626
  if(req.method==='POST' && pathname===`${ROUTE}/api/feedback`){
626
- const rejection = ctx.connection.requestRejection(req)
627
+ const rejection = requestRejection(ctx, req, peer)
627
628
  if(rejection){sendError(res,rejection,'请先打开并登录 DSH 主页面');return}
628
629
  if(!identityWriteAllowed(req)){sendError(res,403,'same-origin feedback request required');return}
629
630
  try {sendJson(res,201,await feedback.submit(req,await readJson(req)))}
@@ -636,7 +637,7 @@ export function apply(ctx, options = {}) {
636
637
  return
637
638
  }
638
639
  if (req.method === 'POST' && pathname === `${ROUTE}/api/voice/diagnostic`) {
639
- const rejection = ctx.connection.requestRejection(req)
640
+ const rejection = requestRejection(ctx, req, peer)
640
641
  if (rejection) { sendError(res, rejection, 'DSH connection required'); return }
641
642
  if (!identityWriteAllowed(req)) { sendError(res, 403, 'same-origin diagnostic request required'); return }
642
643
  const body = await readJson(req)
@@ -653,7 +654,7 @@ export function apply(ctx, options = {}) {
653
654
  return
654
655
  }
655
656
  if (req.method === 'POST' && pathname === `${ROUTE}/api/voice/dedicated-workspace`) {
656
- const rejection=ctx.connection.requestRejection(req)
657
+ const rejection=requestRejection(ctx, req, peer)
657
658
  if(rejection || !identityWriteAllowed(req)){sendError(res,rejection||403,'DSH connection required');return}
658
659
  if(await workPolicy.get()==='direct_only'){sendError(res,403,'agent_mode_disabled');return}
659
660
  try {
@@ -671,13 +672,15 @@ export function apply(ctx, options = {}) {
671
672
  return
672
673
  }
673
674
  if(req.method==='GET' && pathname===`${ROUTE}/api/voice/agent-tasks`){
674
- const rejection=ctx.connection.requestRejection(req)
675
+ const rejection=requestRejection(ctx, req, peer)
675
676
  if(rejection){sendError(res,rejection,'DSH connection required');return}
676
677
  const policy=effectiveWorkPolicy(settings.public(),await workPolicy.get())
677
678
  if(policy.work_mode!=='agent'||policy.agent_permission_version!==1){sendJson(res,200,{rows:[]});return}
678
679
  try{
679
- const rows=await ctx.get('duetAgent').taskRows(policy.agent_options.workspace_id)
680
- sendJson(res,200,{rows:rows.map(({name,state,session_id,finished_at})=>({name,state,
680
+ const service=ctx.get('duetAgent'),workspace=policy.agent_options.workspace_id
681
+ const rows=await service.taskRows(workspace)
682
+ const main=await service.mainRow?.(workspace)??null
683
+ sendJson(res,200,{main,rows:rows.map(({name,state,session_id,finished_at,model_info})=>({name,state,model_info,
681
684
  ...(/^worker-[a-f0-9]{32}$/.test(session_id)?{session_id,finished_at}:{} )}))})
682
685
  }catch{sendError(res,503,'任务状态暂不可用')}
683
686
  return
@@ -1269,7 +1272,7 @@ export function apply(ctx, options = {}) {
1269
1272
  }
1270
1273
  if (req.method === 'GET' && [ `${ROUTE}/api/results`, `${ROUTE}/api/results/wait` ].includes(pathname)) {
1271
1274
  if (pathname.endsWith('/wait')) {
1272
- const rejection = ctx.connection.requestRejection(req)
1275
+ const rejection = requestRejection(ctx, req, peer)
1273
1276
  if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
1274
1277
  }
1275
1278
  const url = new URL(req.url || '/', 'http://localhost')
@@ -1309,16 +1312,18 @@ export function apply(ctx, options = {}) {
1309
1312
  sendError(res, 404, 'not found')
1310
1313
  }
1311
1314
 
1312
- const handler = async (req, res) => {
1315
+ const handler = async (req, res, peer) => {
1313
1316
  const pathname = new URL(req.url || '/', 'http://localhost').pathname
1314
1317
  try {
1318
+ const rejection = requestRejection(ctx, req, peer)
1319
+ if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
1315
1320
  if ([PAGE_ROUTE, `${PAGE_ROUTE}/`, ROUTE, `${ROUTE}/`, `${ROUTE}/api/voice/config`, `${ROUTE}/api/voice/work-options`, `${ROUTE}/api/voice/service-info`, `${ROUTE}/api/voice/diagnostic`, `${ROUTE}/api/announcements`].includes(pathname)) {
1316
- const rejection = ctx.connection.requestRejection(req)
1321
+ const rejection = requestRejection(ctx, req, peer)
1317
1322
  if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
1318
1323
  }
1319
1324
  const tutorialAudio = pathname.match(/^\/duplex-control\/tutorial-audio\/(modes_broadcast|modes_interaction|broadcast|input|edit|clear|reinput|send|switch)\.wav$/)
1320
1325
  if (req.method === 'GET' && tutorialAudio) {
1321
- const rejection = ctx.connection.requestRejection(req)
1326
+ const rejection = requestRejection(ctx, req, peer)
1322
1327
  if (rejection) { sendError(res, rejection, '请先打开并登录 DSH 主页面'); return }
1323
1328
  const body = await readFile(new URL(`../../assets/tutorial-audio/${tutorialAudio[1]}.wav`, import.meta.url))
1324
1329
  res.writeHead(200, { 'content-type': 'audio/wav', 'cache-control': 'private, max-age=3600', 'content-length': body.length })
@@ -1351,7 +1356,7 @@ export function apply(ctx, options = {}) {
1351
1356
  res.end(body)
1352
1357
  return
1353
1358
  }
1354
- await handleApi(req, res, pathname)
1359
+ await handleApi(req, res, pathname, peer)
1355
1360
  } catch (error) {
1356
1361
  audit.event('host.api_error', { method: req.method, path: pathname, message: error.message, stack: error.stack })
1357
1362
  const status = Number.isInteger(error?.status) ? error.status : 500
@@ -1362,6 +1367,6 @@ export function apply(ctx, options = {}) {
1362
1367
  }
1363
1368
  }
1364
1369
 
1365
- ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: ROUTE, handler }))
1366
- ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: PAGE_ROUTE, handler }))
1370
+ ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: ROUTE, auth: 'required', handler }))
1371
+ ctx.effect(() => ctx.webServer.register({ kind: 'prefix', path: PAGE_ROUTE, auth: 'required', handler }))
1367
1372
  }
@@ -1,3 +1,4 @@
1
+ import { requestRejection } from './auth.mjs'
1
2
  /** Same-origin voice relay; endpoint and compatibility policy belong to the DSH host. */
2
3
  import { createRequire } from 'node:module'
3
4
  import { DuetTrace } from './trace.mjs'
@@ -69,8 +70,8 @@ export function registerDuetProxy(ctx, config = duetConfig(), feedback = null, c
69
70
  acquireHostDiagnostics(ctx.webServer, config.diagnosticOptions)
70
71
  const stop = ctx.webServer.registerUpgrade({
71
72
  path: '/duplex-control/voice/ws',
72
- handler(req, socket, head) {
73
- const rejection = ctx.connection?.requestRejection(req)
73
+ handler(req, socket, head, peer) {
74
+ const rejection = requestRejection(ctx, req, peer)
74
75
  if (rejection) { socket.end(`HTTP/1.1 ${rejection} Forbidden\r\nConnection: close\r\n\r\n`); return }
75
76
  // No browser-selected target URLs and no cross-origin drive-by microphone sessions.
76
77
  const origin = req.headers.origin
@@ -1,3 +1,4 @@
1
+ import { requestRejection } from './auth.mjs'
1
2
  import { WebSocketServer } from 'ws'
2
3
 
3
4
  /** Authenticated local event stream. No timers that query DSH state. */
@@ -6,10 +7,10 @@ export function registerSyncFeed(ctx, { snapshot, touch, commands }) {
6
7
  const clients = new Set()
7
8
  const unregister = ctx.webServer.registerUpgrade({
8
9
  path: '/duplex-control/sync/ws',
9
- handler(req, socket, head) {
10
+ handler(req, socket, head, peer) {
10
11
  let allowed = !req.headers.origin
11
12
  try { if (req.headers.origin) allowed = new URL(req.headers.origin).host === req.headers.host } catch {}
12
- if (!allowed || ctx.connection?.requestRejection(req) || clients.size >= 64) {
13
+ if (!allowed || requestRejection(ctx, req, peer) || clients.size >= 64) {
13
14
  socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n'); return
14
15
  }
15
16
  server.handleUpgrade(req, socket, head, ws => {
@@ -1,18 +1,16 @@
1
- import {avatarLocalState,avatarMenuAction,avatarMenuResult} from './avatar-menu.mjs'
2
- import {sizeButton,nextAvatarSize} from './avatar-ui.mjs'
1
+ import {avatarLocalState,avatarMenuAction,avatarMenuResult,COMPLETION_NOTICE_MS} from './avatar-menu.mjs'
2
+ import {sizeButton,nextAvatarSize,taskBubbleCardStyle} from './avatar-ui.mjs'
3
3
  const labels={completed:'本轮已完成',failed:'执行失败',stopped:'已停止',approval:'等待授权',question:'等待回答',plan_review:'等待方案确认'}
4
4
  const names={small:'紧凑',medium:'标准',large:'宽松'}
5
- export const noticeBadgeStyle='border:0;border-radius:12px;background:#dcefff;color:#185a89;font:12px system-ui;padding:4px 7px;cursor:pointer;pointer-events:auto'
6
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'}
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}
8
7
  export function mountAvatarMenu({anchor,viewport=()=>[0,0,innerWidth,innerHeight],send,changed=()=>{}}){
9
- let state={items:[],running:0,enabled:true,size:'large',bubble:'medium'},root,toast,badge,section='main',timer,dead=false,point,previous,toastId,ackTimer
8
+ let state={items:[],running:0,enabled:true,size:'large',bubble:'medium'},root,toast,section='main',timer,dead=false,point,previous,toastId,ackTimer
10
9
  const style=document.createElement('style');style.textContent=`
11
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}
12
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}
13
12
  .duet-pet-menu button>[data-label]{min-width:0;flex:1;overflow-wrap:anywhere}
14
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}
15
- [data-duet-notice-badge][hidden]{display:none!important}
16
14
  .duet-pet-menu button:hover,.duet-pet-menu button:focus-visible{background:#b3daff16;outline:none}
17
15
  .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}
18
16
  .duet-pet-menu [data-wordmark]{font:700 28px/1.1 Inter,"PingFang SC",sans-serif;letter-spacing:-1.1px;padding:11px 12px 15px}
@@ -34,8 +32,7 @@ export function mountAvatarMenu({anchor,viewport=()=>[0,0,innerWidth,innerHeight
34
32
  if(paths[iconName])b.append(icon(iconName));const t=document.createElement('span');t.dataset.label='';t.textContent=label;b.append(t)
35
33
  b.onclick=()=>{if(['pending','bubble_panel','back'].includes(action)){section=action==='back'?'main':action;render();return}close();command(action,undefined,id)};return b
36
34
  }
37
- const unreadCount=()=>state.items.filter(i=>i.unread).length
38
- const countLabel=()=>{const n=unreadCount();return '待处理事项与通知'+(n?`(${n})`:'')}
35
+ const countLabel=()=> '待处理事项与通知'
39
36
  const valueSpan=b=>{const v=document.createElement('span');v.dataset.value='';b.append(v);return v}
40
37
  const refreshControls=()=>{
41
38
  if(!root)return
@@ -74,14 +71,35 @@ export function mountAvatarMenu({anchor,viewport=()=>[0,0,innerWidth,innerHeight
74
71
  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()}}
75
72
  const decorate=(node,label)=>{node.className='duet-pet-menu';node.setAttribute('aria-label',label)}
76
73
  const update=value=>{
77
- state=avatarLocalState(value);badge??=document.createElement('button');badge.type='button';badge.dataset.duetNoticeBadge='';badge.style.cssText='position:fixed;z-index:2147483600;'+noticeBadgeStyle
78
- const count=unreadCount();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)
79
- 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'
80
- 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)}}
74
+ state=avatarLocalState(value)
75
+ if(toastId!==state.toast){
76
+ clearTimeout(timer);clearTimeout(ackTimer);toast?.remove();toast=null;toastId=state.toast
77
+ const item=state.items.find(i=>i.id===state.toast)
78
+ if(item){
79
+ toast=document.createElement('section');toast.dataset.duetLocalNotice=''
80
+ if(item.status==='completed'){
81
+ toast.setAttribute('aria-label','DSH 任务通知');toast.setAttribute('role','status')
82
+ toast.style.cssText='position:fixed;z-index:2147483600;width:264px;max-width:calc(100vw - 24px);pointer-events:auto'
83
+ const card=document.createElement('button');card.type='button';card.dataset.completionCard='';card.style.cssText=taskBubbleCardStyle
84
+ const check=document.createElement('span');check.textContent='✓';check.setAttribute('aria-hidden','true')
85
+ check.style.cssText='flex:0 0 18px;width:18px;height:18px;border-radius:50%;background:#dcefe8;color:#23845e;text-align:center;font:600 14px/18px system-ui'
86
+ const copy=document.createElement('span'),name=document.createElement('strong'),status=document.createElement('small')
87
+ copy.style.cssText='min-width:0;overflow-wrap:anywhere';name.textContent=item.name||'未命名会话';name.style.cssText='display:block;font-size:13px;font-weight:550'
88
+ status.textContent='已完成';status.style.cssText='display:block;font-size:11px;opacity:.7'
89
+ copy.append(name,status);card.append(check,copy);card.setAttribute('aria-label',`${name.textContent} · 已完成,查看会话`)
90
+ card.onclick=()=>command('view',undefined,item.id);toast.append(card)
91
+ }else{
92
+ decorate(toast,'DSH 任务通知');const p=document.createElement('div');p.dataset.noticeTitle='';p.textContent=`${item.name||'未命名会话'} · ${labels[item.status]}`
93
+ toast.append(p,row(item.pending?'去处理':'查看','view','open',item.id),row('收起','dismiss','hide',item.id))
94
+ }
95
+ document.body.append(toast);place(toast)
96
+ if(!item.pending)timer=setTimeout(()=>{toast?.remove();toast=null;changed()},item.status==='completed'?COMPLETION_NOTICE_MS:8000)
97
+ }
98
+ }
81
99
  refreshControls();changed()
82
100
  }
83
101
  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)}
84
102
  const reposition=()=>{if(root)place(root);if(toast)place(toast)}
85
103
  document.addEventListener('pointerdown',outside,true);document.addEventListener('keydown',keys,true);window.addEventListener('resize',reposition);window.addEventListener('blur',close)
86
- 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)}}
104
+ return{open,close,update,result,get active(){return Boolean(root)},regions(){return[root,toast].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();document.removeEventListener('pointerdown',outside,true);document.removeEventListener('keydown',keys,true);window.removeEventListener('resize',reposition);window.removeEventListener('blur',close)}}
87
105
  }
@@ -1,6 +1,7 @@
1
1
  /** Local-only presentation protocol. No remote URLs, credentials or executable payloads. */
2
2
  export const AVATAR_LOCAL_PROTOCOL='avatar_local_v1'
3
3
  export const NOTICE_KEY='dsh.duet.avatar.notices.v1'
4
+ export const COMPLETION_NOTICE_MS=3000
4
5
  export const MENU_ACTIONS=['open_dsh','pending','settings','tutorial','hide','notifications','size','bubble','view','dismiss']
5
6
  const sizes=['small','medium','large'], statuses=['completed','failed','stopped','approval','question','plan_review']
6
7
  export function noticePreferences(storage=globalThis.localStorage){
@@ -62,7 +63,8 @@ export class AvatarNotices {
62
63
  const status=job.turn_end_reason==='aborted'?'stopped':job.status==='failed'?'failed':job.status==='succeeded'&&job.turn_end_reason==='completed'?'completed':null
63
64
  if(!status)continue
64
65
  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.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:status!=='completed',
67
+ ...(status==='completed'?{expiresAt:Date.now()+COMPLETION_NOTICE_MS}:{})})
66
68
  this.toast=id;this.toastAt=Date.now()
67
69
  }
68
70
  while(this.seen.size>1024)this.seen.delete(this.seen.values().next().value)
@@ -78,6 +80,7 @@ export class AvatarNotices {
78
80
  }
79
81
  dismiss(id){if(this.items.has(id))this.dismissed.add(id);if(this.toast===id)this.toast=null;this.revision++}
80
82
  state(prefs,size,available=true){
83
+ for(const [id,item]of this.items)if(item.expiresAt && Date.now()>=item.expiresAt){this.items.delete(id);if(this.toast===id)this.toast=null}
81
84
  const pending=[...this.items.values()].find(i=>i.pending&&i.unread&&!this.dismissed.has(i.id))
82
85
  const toast=pending?.id??(Date.now()-this.toastAt<=8000?this.toast:null)
83
86
  return avatarLocalState({type:'local_state',protocol:AVATAR_LOCAL_PROTOCOL,revision:this.revision,items:[...this.items.values()],
@@ -11,6 +11,7 @@ export function avatarSurface(value) {
11
11
  length+=n.text.length;if(length>10000)throw Error('invalid_surface')
12
12
  const node={kind:n.kind,text:n.text}
13
13
  if(['running','completed','waiting','failed','stopped'].includes(n.taskState))node.taskState=n.taskState
14
+ if(n.kind==='button'&&n.taskState==='completed'&&Number.isInteger(n.countdown)&&n.countdown>=0&&n.countdown<=10)node.countdown=n.countdown
14
15
  if(n.kind==='button'||n.kind==='checkbox') {
15
16
  if(!/^a\d+$/.test(n.action))throw Error('invalid_surface')
16
17
  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)})
@@ -1,4 +1,6 @@
1
1
  import {avatarSize,AVATAR_SIZES} from './avatar.mjs'
2
+ /** Shared by live agent tasks and short-lived completion notices. */
3
+ export const taskBubbleCardStyle='display:flex;align-items:center;gap:12px;width:100%;box-sizing:border-box;padding:14px 16px;margin:0;border:1px solid #ffffff90;border-radius:20px;background:#f7f9fbe8;color:#253344;text-align:left;cursor:pointer;box-shadow:0 6px 18px -8px #172c4938;backdrop-filter:blur(20px);-webkit-backdrop-filter:blur(20px);font:13px/1.5 -apple-system,BlinkMacSystemFont,system-ui,sans-serif'
2
4
  const sizes=Object.keys(AVATAR_SIZES),names={large:'大(100%)',medium:'中(75%)',small:'小(50%)'}
3
5
  export const nextAvatarSize=value=>sizes[(sizes.indexOf(avatarSize(value))+1)%sizes.length]
4
6
  export function sizeButton(button,value,{label=false}={}) {
@@ -1,8 +1,33 @@
1
1
  /** Desired voice mode is independent of a temporarily suspended connection. */
2
- export const PLUGIN_VERSION = '0.3.1'
2
+ export const PLUGIN_VERSION = '0.3.3'
3
3
  export const IDLE_RELEASE_MS = 60_000
4
4
 
5
5
  const safeVersion = value => typeof value === 'string' && value.length <= 32 && /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value) ? value : ''
6
+ const compareVersions = (a, b) => a.split('.').reduce((result, v, i) => result || Math.sign(Number(v) - Number(b.split('.')[i])), 0)
7
+
8
+ /** Display only upgrades the installed client has not received yet. */
9
+ export function updateDetails(info = {}, current = PLUGIN_VERSION) {
10
+ const target = safeVersion(info.recommended_client_version)
11
+ const entries = new Map()
12
+ if (safeVersion(current) && target && compareVersions(target, current) > 0) {
13
+ for (const row of (Array.isArray(info.release_history) ? info.release_history.slice(0, 64) : [])) {
14
+ if (!safeVersion(row?.version) || typeof row.notes !== 'string' || !row.notes.trim()) continue
15
+ if (compareVersions(row.version, current) > 0 && compareVersions(row.version, target) <= 0) {
16
+ entries.set(row.version, {version: row.version, notes: row.notes.slice(0, 1000).trim()})
17
+ }
18
+ }
19
+ if (!entries.has(target) && typeof info.recommended_release_notes === 'string' && info.recommended_release_notes.trim()) {
20
+ entries.set(target, {version: target, notes: info.recommended_release_notes.slice(0, 1000).trim()})
21
+ }
22
+ }
23
+ let remaining = 16000
24
+ const releases = [...entries.values()].sort((a, b) => compareVersions(b.version, a.version)).filter(row => {
25
+ remaining -= row.notes.length
26
+ return remaining >= 0
27
+ })
28
+ return {currentVersion: current, targetVersion: target, releases,
29
+ releaseNotes: info.recommended_release_notes}
30
+ }
6
31
  export function compatibilityNotice(code, details = {}, mode = 'online') {
7
32
  const key = mode === 'tts_only' ? 'tts_only' : 'online'
8
33
  const info = details.compatibility || {}
@@ -85,11 +110,11 @@ export class DuetState {
85
110
  if(event.reconnect_required===true&&this.mode!=='off')void this.replaceConnection({reason:'voice_policy_changed'})
86
111
  } else if (event.type === 'compatibility') {
87
112
  const recommended = safeVersion(event.compatibility?.recommended_client_version)
88
- const newer = recommended && recommended.split('.').reduce((result, v, i) => result || Math.sign(Number(v) - Number(PLUGIN_VERSION.split('.')[i])), 0) > 0
113
+ const newer = recommended && compareVersions(recommended, PLUGIN_VERSION) > 0
89
114
  if (newer && this.recommendationShown !== recommended) {
90
115
  this.recommendationShown = recommended
91
116
  this.notice(`当前插件 ${PLUGIN_VERSION},推荐更新到 ${recommended}。当前连接可以继续使用。`, {
92
- upgrade: true, releaseNotes: event.compatibility?.recommended_release_notes,
117
+ upgrade: true, ...updateDetails(event.compatibility),
93
118
  })
94
119
  }
95
120
  } else if (event.type === 'ready') {
@@ -122,7 +147,7 @@ export class DuetState {
122
147
  const compatibility = compatibilityNotice(code, details, this.mode)
123
148
  if (compatibility) {
124
149
  this.notice(compatibility, { upgrade: code !== 'client_version_unsupported',
125
- releaseNotes: details.compatibility?.recommended_release_notes || details.policy?.recommended_release_notes })
150
+ ...updateDetails({...details.policy, ...details.compatibility}) })
126
151
  void this.setMode('off', {reason:'error',code})
127
152
  return
128
153
  }
@@ -9,6 +9,20 @@ export function effectiveWorkPolicy(config,policy='recommend_agent'){
9
9
  const READ_KEY='duet.agent.visited.v1', visitKey=id=>READ_KEY+'.'+id
10
10
  export const nativeWorkerId=id=>typeof id==='string' && /^worker-[a-f0-9]{32}$/.test(id)
11
11
  const cachedVisits=new Map()
12
+ const completionTimers=new Map(),completionKey=id=>'duet.agent.completion-expiry.v1.'+id
13
+ /** Start once on receipt, not on the possibly skewed DSH completion clock. */
14
+ export function taskCompletionSeconds(row,now=Date.now()){
15
+ if(!nativeWorkerId(row?.session_id)||!Number.isFinite(row.finished_at)||taskCardState(row)!=='completed')return null
16
+ const stamp=JSON.stringify([row.run_id??null,row.finished_at]),key=completionKey(row.session_id)
17
+ let saved=completionTimers.get(key)
18
+ try{const stored=JSON.parse(localStorage.getItem(key));if(stored?.stamp===stamp&&Number.isFinite(stored.end))saved=stored}catch{}
19
+ if(saved?.stamp!==stamp||!Number.isFinite(saved.end)){
20
+ saved={stamp,end:now+10000};completionTimers.set(key,saved)
21
+ try{localStorage.setItem(key,JSON.stringify(saved))}catch{}
22
+ }
23
+ completionTimers.set(key,saved)
24
+ return Math.max(0,Math.min(10,Math.ceil((saved.end-now)/1000)))
25
+ }
12
26
  const waitingReads=new Map(),waitingKey=id=>'duet.agent.waiting-read.v1.'+id
13
27
  export function taskCardState(row){
14
28
  return ['completed','merged','ready','ended'].includes(row.state)?'completed':['failed'].includes(row.state)?'failed':
@@ -45,6 +59,7 @@ export function visibleTaskRows(rows){
45
59
  const old=legacyVisits()
46
60
  return rows.filter(r=>{
47
61
  if(!r)return false
62
+ if(taskCompletionSeconds(r)===0)return false
48
63
  const visited=Math.max(Number(old[r.session_id])||0,cachedVisits.get(r.session_id)||0,storedVisit(r.session_id))
49
64
  return r.finished_at ? visited<r.finished_at : taskCardState(r)!=='waiting'||!waitingWasRead(r)
50
65
  })
@@ -97,3 +112,8 @@ export function workModeIssue(config) {
97
112
  }
98
113
  return null
99
114
  }
115
+ export function taskModelLabel(info) {
116
+ if(!info || typeof info.provider!=='string' || typeof info.model!=='string')return '模型尚未记录'
117
+ const prefix={response:'最近使用',request:'最近请求',selection:'已选择',configured:'待使用'}[info.source]||'模型'
118
+ return `${prefix}:${info.provider} / ${info.model}`
119
+ }