@xopcai/xopc 0.0.471 → 0.0.473

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 (97) hide show
  1. package/dist/browser-ext/manifest.json +1 -1
  2. package/dist/extensions/discord/src/index.js +1 -1
  3. package/dist/extensions/telegram/xopc.extension.json +1 -1
  4. package/dist/gateway/static/root/assets/{apps-page-O944fHx0.js → apps-page-BlDivdQ0.js} +1 -1
  5. package/dist/gateway/static/root/assets/{automations-page-Cflfmbrc.js → automations-page-BoYv4mr2.js} +1 -1
  6. package/dist/gateway/static/root/assets/{automations-workspace-DM6e37bB.js → automations-workspace-DdHpajzk.js} +2 -2
  7. package/dist/gateway/static/root/assets/{capabilities-page-DYU6WSde.js → capabilities-page-DWslQZCv.js} +2 -2
  8. package/dist/gateway/static/root/assets/{capabilities-settings-panel-DfyND0IO.js → capabilities-settings-panel-Drpf_JGM.js} +2 -2
  9. package/dist/gateway/static/root/assets/{channels-DwUmMnA1.js → channels-CjDJ2Mmb.js} +1 -1
  10. package/dist/gateway/static/root/assets/{chat-page-C0ONpQcA.js → chat-page-4Agzfc_0.js} +30 -30
  11. package/dist/gateway/static/root/assets/{chat-terminal-dock-Dn7Cm1O4.js → chat-terminal-dock-1VI02yzQ.js} +1 -1
  12. package/dist/gateway/static/root/assets/{connectors-page-DfDVgGh_.js → connectors-page-T7W-zTEK.js} +1 -1
  13. package/dist/gateway/static/root/assets/{extension-debug-page-DIAyDA-a.js → extension-debug-page-DIU2PfhR.js} +1 -1
  14. package/dist/gateway/static/root/assets/{extension-iframe-host-CCe4R7L7.js → extension-iframe-host-0xdd5xm5.js} +1 -1
  15. package/dist/gateway/static/root/assets/{extension-message-router-BD0ZamBV.js → extension-message-router-CN1KAjhe.js} +1 -1
  16. package/dist/gateway/static/root/assets/{extension-page-C09dlV3J.js → extension-page-BiAzQtvI.js} +1 -1
  17. package/dist/gateway/static/root/assets/{extension-provider-BhluafoX.js → extension-provider-CYVVZ21G.js} +1 -1
  18. package/dist/gateway/static/root/assets/{extension-settings-page-CB8KLYoG.js → extension-settings-page-B71tjY9p.js} +1 -1
  19. package/dist/gateway/static/root/assets/{home-page-8KwhWlYt.js → home-page-C79KZbb1.js} +3 -3
  20. package/dist/gateway/static/root/assets/{index-CwEEoE-7.js → index-Ek2aSUt6.js} +6 -6
  21. package/dist/gateway/static/root/assets/{local-app-workbench-page-DmzgjJNj.js → local-app-workbench-page-TZ7JoORJ.js} +1 -1
  22. package/dist/gateway/static/root/assets/{note-detail-panel-Cu_YCIN6.js → note-detail-panel-C8o-hv5U.js} +3 -3
  23. package/dist/gateway/static/root/assets/{notes-page-CQtqNBlW.js → notes-page-VWv-Q26S.js} +1 -1
  24. package/dist/gateway/static/root/assets/{page-context-capture-button-Cn4zi3Mt.js → page-context-capture-button-zG-782MJ.js} +1 -1
  25. package/dist/gateway/static/root/assets/{personal-page-OK0-3ovb.js → personal-page-CweKnHPY.js} +1 -1
  26. package/dist/gateway/static/root/assets/{personal-profile-settings-CNI5Eor6.js → personal-profile-settings-OoFMAniP.js} +1 -1
  27. package/dist/gateway/static/root/assets/{personal-settings-panel-BcrpYRn9.js → personal-settings-panel-BVv8cYny.js} +1 -1
  28. package/dist/gateway/static/root/assets/{preview-runtime-RnBDP-Lq.js → preview-runtime-pJGZe5Jx.js} +1 -1
  29. package/dist/gateway/static/root/assets/{project-detail-page-ydVvC7Fi.js → project-detail-page-CR9prGyI.js} +1 -1
  30. package/dist/gateway/static/root/assets/{route-preload-g-LvDQgh.js → route-preload-D3c2DaKJ.js} +2 -2
  31. package/dist/gateway/static/root/assets/{routine-panel-rjq-8nZ8.js → routine-panel-BsUWc1HR.js} +2 -2
  32. package/dist/gateway/static/root/assets/session-manager-DzSlogQc.js +22 -0
  33. package/dist/gateway/static/root/assets/{settings-page-DHXt4EPc.js → settings-page-De1H4SjW.js} +1 -1
  34. package/dist/gateway/static/root/assets/{share-preview-page-nzWjWhqF.js → share-preview-page-DDd5iT5G.js} +1 -1
  35. package/dist/gateway/static/root/assets/{shares-settings-LB3SYKFS.js → shares-settings-Dmk9W8r9.js} +1 -1
  36. package/dist/gateway/static/root/assets/{space-page-D7YRR6ZW.js → space-page-fq1NyJx5.js} +1 -1
  37. package/dist/gateway/static/root/assets/{task-detail-page-BUn6GRzz.js → task-detail-page-DqVRV32Y.js} +2 -2
  38. package/dist/gateway/static/root/assets/task-header-title-D3zA4Ho1.js +1 -0
  39. package/dist/gateway/static/root/assets/{task-result-evidence-Bmgta9z9.js → task-result-evidence-DCHcXh04.js} +1 -1
  40. package/dist/gateway/static/root/assets/{use-composer-attachments-sszsCdh5.js → use-composer-attachments-B6CKcx51.js} +1 -1
  41. package/dist/gateway/static/root/assets/{use-file-preview-expanded-D4b4fDeu.js → use-file-preview-expanded-1ZjXWaYM.js} +1 -1
  42. package/dist/gateway/static/root/assets/{use-personal-work-CNK4dpEh.js → use-personal-work-BJ1yKsau.js} +1 -1
  43. package/dist/gateway/static/root/assets/{use-realtime-voice-cugjs8cK.js → use-realtime-voice-D5-XzM7H.js} +1 -1
  44. package/dist/gateway/static/root/assets/{use-workspace-tree-Crfx5ctU.js → use-workspace-tree-DsuGqCMo.js} +1 -1
  45. package/dist/gateway/static/root/assets/{voice-settings-BzfNK5Jm.js → voice-settings-lJN2e9mQ.js} +1 -1
  46. package/dist/gateway/static/root/assets/{workspace-api-g-wCKoQU.js → workspace-api-CFPK3JR6.js} +2 -2
  47. package/dist/gateway/static/root/assets/{workspace-file-preview-dialog-DxaxVC3q.js → workspace-file-preview-dialog-35uL-ra3.js} +1 -1
  48. package/dist/gateway/static/root/index.html +16 -16
  49. package/dist/package.js +1 -1
  50. package/dist/src/agent/context/connection-objective-context.js +5 -1
  51. package/dist/src/agent/inbound/turn-dispatcher.d.ts +2 -0
  52. package/dist/src/agent/inbound/turn-dispatcher.js +3 -1
  53. package/dist/src/agent/service/process-direct-streaming.js +14 -0
  54. package/dist/src/agent/tools/factory.js +1 -1
  55. package/dist/src/agent/tools/personal-request-tool.d.ts +24 -1
  56. package/dist/src/agent/tools/personal-request-tool.js +180 -261
  57. package/dist/src/agent/tools/personal-task-tool.d.ts +8 -0
  58. package/dist/src/agent/tools/personal-task-tool.js +108 -46
  59. package/dist/src/channels/enterprise/plugin.js +1 -1
  60. package/dist/src/cli/commands/doctor/checks/database-schema.js +52 -17
  61. package/dist/src/cli/commands/doctor/checks/tool-runtimes.js +12 -1
  62. package/dist/src/cli/commands/doctor/flow.js +11 -6
  63. package/dist/src/cli/index.js +8 -2
  64. package/dist/src/connectors/connection-candidates.d.ts +1 -0
  65. package/dist/src/connectors/connection-candidates.js +20 -1
  66. package/dist/src/gateway/chat-stream/mapper.js +10 -4
  67. package/dist/src/gateway/hono/routes/sessions.js +5 -2
  68. package/dist/src/gateway/hono/routes/video-generation.js +6 -5
  69. package/dist/src/gateway/service/session-input-coordinator.d.ts +2 -1
  70. package/dist/src/gateway/service/session-input-coordinator.js +3 -1
  71. package/dist/src/music-generation/artifact.d.ts +1 -1
  72. package/dist/src/music-generation/artifact.js +4 -3
  73. package/dist/src/music-generation/provider.d.ts +1 -0
  74. package/dist/src/music-generation/providers.js +4 -1
  75. package/dist/src/music-generation/worker.js +1 -1
  76. package/dist/src/music-generation/xopc-cloud.js +22 -0
  77. package/dist/src/personal-agent/prompts.js +29 -6
  78. package/dist/src/personal-agent/request-repository.d.ts +4 -0
  79. package/dist/src/personal-agent/request-repository.js +17 -1
  80. package/dist/src/session/manager.d.ts +3 -1
  81. package/dist/src/session/manager.js +2 -2
  82. package/dist/src/session/store.d.ts +3 -1
  83. package/dist/src/session/store.js +2 -2
  84. package/dist/src/session/user-round-delete.d.ts +3 -1
  85. package/dist/src/session/user-round-delete.js +6 -4
  86. package/dist/src/storage/sqlite/session-turn-replace-repository.js +6 -1
  87. package/dist/src/tasks/task-context-assembler.js +5 -2
  88. package/dist/src/tasks/task-deliverables.js +73 -38
  89. package/dist/src/tasks/task-main-update-delivery.js +1 -1
  90. package/dist/src/tasks/task-origin-repository.d.ts +2 -0
  91. package/dist/src/tasks/task-origin-repository.js +15 -6
  92. package/dist/src/video-generation/drafts.js +3 -3
  93. package/dist/src/video-generation/settings.d.ts +1 -0
  94. package/dist/src/video-generation/settings.js +23 -7
  95. package/package.json +1 -1
  96. package/dist/gateway/static/root/assets/session-manager-BVS3zxRZ.js +0 -22
  97. package/dist/gateway/static/root/assets/task-header-title-BsYL4R80.js +0 -1
@@ -1 +1 @@
1
- import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t,n,t as r}from"./vendor-react-BOUWij0V.js";import{u as i}from"./chunk-KS7C4IRE-CiwuuyV8.js";import{n as a}from"./locale-store-Cit_aHqC.js";import{t as o}from"./messages-DQveK9sk.js";import{t as s}from"./createLucideIcon-DPHK1VkS.js";import{t as c}from"./app-window-DXFNqt_0.js";import{t as l}from"./check-DUBLcKHA.js";import{t as u}from"./chevron-down-ccbiQQz_.js";import{t as d}from"./copy-Dv6d4Dvw.js";import{t as f}from"./download-Dk-ZjtO6.js";import{t as p}from"./ellipsis-0k4rZLoy.js";import{t as ee}from"./external-link-DjqjBmc3.js";import{t as te}from"./eye-CABVeTq0.js";import{t as ne}from"./folder-open-CyzJ19I9.js";import{t as re}from"./link-2-D_ZKYUW7.js";import{t as ie}from"./loader-circle-CifKLtgG.js";import{q as ae}from"./markdown-view-Dm01GIXv.js";import{t as oe}from"./message-square-plus-XP0tGdlV.js";import{t as m}from"./minimize-2-DtOGrlpo.js";import{t as h}from"./paperclip-f1HujQY1.js";import{t as g}from"./pencil-DmIY3Oa-.js";import{t as se}from"./refresh-cw-BRlGaq2w.js";import{t as ce}from"./save-DRDABU--.js";import{c as _,i as le,n as ue,r as de,s as fe,t as pe}from"./preview-runtime-RnBDP-Lq.js";import{t as me}from"./x-B_N4OPjy.js";import{t as v}from"./cn-0WouolD0.js";import{a as y}from"./session-api-CkOliupg.js";import{i as b}from"./attachment-utils-core-BPYdUI6y.js";import{t as x}from"./constants-D5Z-mUto.js";import{n as he}from"./interaction-BdhHBbYa.js";import{t as S}from"./composer-notifications-B0IZsy8x.js";import{r as ge}from"./app-chrome-BeB4KgOf.js";import{n as _e}from"./electron-env-DHOGevH3.js";import{t as ve}from"./sliding-tab-list-CmcrqRzN.js";import{a as ye,l as be,m as C,n as w,o as xe,r as T,t as E,u as D}from"./dist-ZrL34Ps4.js";var Se=s(`folders`,[[`path`,{d:`M20 5a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h2.5a1.5 1.5 0 0 1 1.2.6l.6.8a1.5 1.5 0 0 0 1.2.6z`,key:`a4852j`}],[`path`,{d:`M3 8.268a2 2 0 0 0-1 1.738V19a2 2 0 0 0 2 2h11a2 2 0 0 0 1.732-1`,key:`yxbcw3`}]]),Ce=s(`text-wrap`,[[`path`,{d:`m16 16-3 3 3 3`,key:`117b85`}],[`path`,{d:`M3 12h14.5a1 1 0 0 1 0 7H13`,key:`18xa6z`}],[`path`,{d:`M3 19h6`,key:`1ygdsz`}],[`path`,{d:`M3 5h18`,key:`1u36vt`}]]),O=e(t(),1),k=(0,O.createContext)(null);function A(){return(0,O.useContext)(k)}var j=(0,O.createContext)([]),we=(0,O.createContext)(null),M=new Map;function Te(e,t){return M.set(e,t),()=>{M.get(e)===t&&M.delete(e)}}async function N(e,t){return await M.get(e)?.(t)??!1}var P=n(),F=r();function I(e){let t=(0,P.c)(3),{app:n}=e,[r,i]=(0,O.useState)(),a;return t[0]!==n||t[1]!==r?(a=n?.iconDataUrl&&n.iconDataUrl!==r?(0,F.jsx)(`img`,{src:n.iconDataUrl,alt:``,width:20,height:20,className:`size-5 shrink-0 object-contain`,onError:()=>i(n.iconDataUrl)}):(0,F.jsx)(c,{className:`size-5 shrink-0 text-fg-muted`,strokeWidth:1.75,"aria-hidden":!0}),t[0]=n,t[1]=r,t[2]=a):a=t[2],a}function Ee({variant:e=`split`,onAction:t,systemApp:n,chooseApp:r,recommendedApps:i,recentApps:s,onOpenWithApp:d}){let f=a(e=>e.language),p=o(f).workspace,[te,ne]=(0,O.useState)(),[re,ae]=(0,O.useState)(!1),oe=[...i,...s],m=d&&te!==null?oe.find(e=>e.path===te?.path)??te??oe[0]:void 0,h=!!(re||n?.loading||r?.loading),g=h||!!n?.disabled,se=m?f===`zh`?`用 ${m.name} 打开`:`Open with ${m.name}`:p.openSystemApp,ce=`flex min-h-9 cursor-default items-center gap-2.5 rounded-md px-2.5 py-2 text-sm text-fg outline-none data-[highlighted]:bg-surface-hover data-[disabled]:pointer-events-none data-[disabled]:opacity-40`,_=`my-1 h-px bg-edge-subtle`;if(!n&&!r&&(!d||!oe.length))return null;if(e===`menu`){let e=e=>t?t(e):e(),a=`flex min-h-9 w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-sm text-fg hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-40`;return(0,F.jsxs)(F.Fragment,{children:[n?(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,className:a,disabled:g,onClick:()=>e(n.onClick),children:[(0,F.jsx)(ee,{className:`size-5 shrink-0 text-fg-muted`,"aria-hidden":!0}),(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:p.openSystemApp})]}):null,d?[{label:p.recommendedApps,apps:i},{label:p.recentApps,apps:s.filter(e=>!i.some(t=>t.path===e.path))}].map(t=>t.apps.length?(0,F.jsxs)(`div`,{role:`group`,"aria-label":t.label,children:[(0,F.jsx)(`div`,{className:`px-2.5 pb-1 pt-1.5 text-xs font-medium text-fg-muted`,children:t.label}),t.apps.map(t=>(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,className:a,disabled:g,onClick:()=>e(()=>d(t.path)),children:[(0,F.jsx)(I,{app:t}),(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:t.name})]},t.path))]},t.label):null):null,r?(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,className:a,disabled:g||r.disabled,onClick:()=>e(()=>{r.onClick()}),children:[(0,F.jsx)(c,{className:`size-5 shrink-0 text-fg-muted`,"aria-hidden":!0}),(0,F.jsx)(`span`,{className:`min-w-0 truncate`,children:p.chooseApp})]}):null,(0,F.jsx)(`div`,{className:`my-1 border-t border-edge-subtle dark:border-edge`})]})}return(0,F.jsxs)(`div`,{className:`inline-flex h-9 shrink-0 items-stretch rounded-full border border-edge-subtle bg-surface-panel`,children:[(0,F.jsxs)(`button`,{type:`button`,"aria-label":se,title:se,disabled:g||!m&&!n,onClick:()=>m?d?.(m.path):n?.onClick(),className:v(`inline-flex min-w-0 items-center gap-2 rounded-l-full pl-3 pr-2 text-sm font-medium text-fg transition-colors hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-40`,he.focusRingPanel),children:[h?(0,F.jsx)(ie,{className:`size-5 animate-spin`,"aria-hidden":!0}):(0,F.jsx)(I,{app:m}),(0,F.jsx)(`span`,{children:f===`zh`?`打开`:`Open`})]}),(0,F.jsxs)(be,{modal:!1,children:[(0,F.jsx)(C,{asChild:!0,children:(0,F.jsx)(`button`,{type:`button`,"aria-label":p.chooseApp,title:p.chooseApp,disabled:g,className:v(`inline-flex w-8 shrink-0 items-center justify-center rounded-r-full text-fg-muted transition-colors hover:bg-surface-hover hover:text-fg disabled:cursor-not-allowed disabled:opacity-40`,he.focusRingPanel),children:(0,F.jsx)(u,{className:`size-4`,strokeWidth:1.75,"aria-hidden":!0})})}),(0,F.jsx)(xe,{children:(0,F.jsxs)(E,{align:`end`,sideOffset:6,collisionPadding:8,"aria-label":p.chooseApp,onEscapeKeyDown:e=>e.stopPropagation(),className:`z-[150] max-h-[var(--radix-dropdown-menu-content-available-height)] w-64 max-w-[calc(100vw-1rem)] overflow-y-auto overscroll-contain rounded-xl border border-edge bg-surface-overlay p-1 shadow-popover outline-none`,children:[n?(0,F.jsxs)(T,{className:ce,disabled:n.disabled||h,onSelect:()=>{ne(null),n.onClick()},children:[(0,F.jsx)(ee,{className:`size-5 shrink-0 text-fg-muted`,strokeWidth:1.75,"aria-hidden":!0}),(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:p.openSystemApp}),m?null:(0,F.jsx)(l,{className:`size-4 shrink-0`,"aria-hidden":!0})]}):null,d?[{label:p.recommendedApps,apps:i},{label:p.recentApps,apps:s.filter(e=>!i.some(t=>t.path===e.path))}].map(e=>e.apps.length?(0,F.jsxs)(w,{children:[(0,F.jsx)(D,{className:_}),(0,F.jsx)(ye,{className:`px-2.5 pb-1 pt-1.5 text-xs font-medium text-fg-muted`,children:e.label}),e.apps.map(e=>(0,F.jsxs)(T,{className:ce,disabled:h,title:e.name,onSelect:()=>{ne(e),d(e.path)},children:[(0,F.jsx)(I,{app:e}),(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e.name}),e.path===m?.path?(0,F.jsx)(l,{className:`size-4 shrink-0`,"aria-hidden":!0}):null]},e.path))]},e.label):null):null,r?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(D,{className:_}),(0,F.jsxs)(T,{className:ce,disabled:r.disabled||h,onSelect:async()=>{ae(!0);try{let e=await r.onClick();e&&ne(e)}finally{ae(!1)}},children:[(0,F.jsx)(c,{className:`size-5 shrink-0 text-fg-muted`,strokeWidth:1.75,"aria-hidden":!0}),(0,F.jsx)(`span`,{className:`min-w-0 truncate`,children:p.chooseApp})]})]}):null]})})]})]})}function De(e){let t=(0,P.c)(9),{label:n,active:r,disabled:i,onClick:a,children:o}=e,s=r&&`border-accent/20 bg-accent-soft text-accent-fg`,c;t[0]===s?c=t[1]:(c=v(`inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-edge-subtle bg-surface-panel text-fg-muted transition-colors hover:bg-surface-hover hover:text-fg disabled:cursor-not-allowed disabled:opacity-40`,s,he.focusRingPanel),t[0]=s,t[1]=c);let l;return t[2]!==r||t[3]!==o||t[4]!==i||t[5]!==n||t[6]!==a||t[7]!==c?(l=(0,F.jsx)(`button`,{type:`button`,className:c,title:n,"aria-label":n,"aria-pressed":r,disabled:i,onClick:a,children:o}),t[2]=r,t[3]=o,t[4]=i,t[5]=n,t[6]=a,t[7]=c,t[8]=l):l=t[8],l}function L(e){let t=(0,P.c)(14),{icon:n,label:r,active:i,disabled:a,onClick:o}=e,s=i===void 0?`menuitem`:`menuitemcheckbox`,c;t[0]===n?c=t[1]:(c=(0,F.jsx)(`span`,{className:`flex size-4 shrink-0 items-center justify-center text-fg-muted`,"aria-hidden":!0,children:n}),t[0]=n,t[1]=c);let u;t[2]===r?u=t[3]:(u=(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:r}),t[2]=r,t[3]=u);let d;t[4]===i?d=t[5]:(d=i?(0,F.jsx)(l,{className:`size-4 shrink-0`,"aria-hidden":!0}):null,t[4]=i,t[5]=d);let f;return t[6]!==i||t[7]!==a||t[8]!==o||t[9]!==s||t[10]!==c||t[11]!==u||t[12]!==d?(f=(0,F.jsxs)(`button`,{type:`button`,role:s,"aria-checked":i,className:`flex h-9 w-full min-w-0 items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-fg hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-40`,disabled:a,onClick:o,children:[c,u,d]}),t[6]=i,t[7]=a,t[8]=o,t[9]=s,t[10]=c,t[11]=u,t[12]=d,t[13]=f):f=t[13],f}function R(e){let t=(0,P.c)(90),{referenceActions:n,onRefresh:r,onRetrySave:i,subtitle:s,controller:c,actions:u,expanded:_,onToggleExpanded:le,onClose:ue,hideClose:de,hideExpand:fe,edit:y,wordWrap:b,editInNewChat:x,share:S,openWithSystemApp:ye,chooseApp:be,recommendedApps:C,recentApps:w,onOpenWithApp:xe,onRevealInFolder:T,copyPath:E,textView:D,openInBrowser:k}=e,A;t[0]===n?A=t[1]:(A=n===void 0?[]:n,t[0]=n,t[1]=A);let j=A,M;t[2]===C?M=t[3]:(M=C===void 0?[]:C,t[2]=C,t[3]=M);let Te=M,N;t[4]===w?N=t[5]:(N=w===void 0?[]:w,t[4]=w,t[5]=N);let I=N,R=a(Ae),je;t[6]===R?je=t[7]:(je=o(R),t[6]=R,t[7]=je);let z=je,B=z.workspace,Me=c.plugin.id===`pdf`?z.chat.attachmentPreviewPdf:c.plugin.id===`docx`?z.chat.attachmentPreviewDocument:c.plugin.id===`spreadsheet`?z.chat.attachmentPreviewSpreadsheet:B.preview,Ne;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(Ne=_e(),t[8]=Ne):Ne=t[8];let Pe=Ne,V=(0,O.useContext)(we),Fe=(0,O.useRef)(null),Ie=(0,O.useRef)(null),[H,Le]=(0,O.useState)(!1),Re;t[9]===c.plugin.capabilities?Re=t[10]:(Re=c.plugin.capabilities.some(ke),t[9]=c.plugin.capabilities,t[10]=Re);let ze=Re,Be,Ve;t[11]===H?(Be=t[12],Ve=t[13]):(Be=()=>{if(!H)return;Fe.current?.querySelector(`button:not(:disabled), a`)?.focus();let e=e=>{if([`ArrowDown`,`ArrowUp`,`Home`,`End`].includes(e.key)&&Fe.current?.contains(document.activeElement)){e.preventDefault(),e.stopImmediatePropagation();let t=[...Fe.current.querySelectorAll(`button:not(:disabled), a`)],n=t.indexOf(document.activeElement);t[e.key===`Home`?0:e.key===`End`?t.length-1:(n+(e.key===`ArrowDown`?1:-1)+t.length)%t.length]?.focus();return}e.key===`Escape`&&(e.preventDefault(),e.stopImmediatePropagation(),Le(!1),Ie.current?.focus())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},Ve=[H],t[11]=H,t[12]=Be,t[13]=Ve),(0,O.useEffect)(Be,Ve);let He;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(He=e=>{Le(!1),Ie.current?.focus(),e()},t[14]=He):He=t[14];let U=He,Ue;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(Ue=v(`shrink-0 bg-surface-base px-3 py-2 sm:px-4`,ge),t[15]=Ue):Ue=t[15];let W;t[16]===V?W=t[17]:(W=V?(0,F.jsx)(De,{label:V.label,active:V.active,onClick:V.onToggle,children:(0,F.jsx)(Se,{className:`size-4`,strokeWidth:1.75,"aria-hidden":!0})}):null,t[16]=V,t[17]=W);let G;t[18]!==_||t[19]!==fe||t[20]!==B.collapsePreview||t[21]!==B.expandPreview||t[22]!==le?(G=fe?null:(0,F.jsx)(De,{label:_?B.collapsePreview:B.expandPreview,active:_,disabled:!le,onClick:le,children:_?(0,F.jsx)(m,{className:`size-4`,"aria-hidden":!0}):(0,F.jsx)(ae,{className:`size-4`,"aria-hidden":!0})}),t[18]=_,t[19]=fe,t[20]=B.collapsePreview,t[21]=B.expandPreview,t[22]=le,t[23]=G):G=t[23];let K;t[24]===H?K=t[25]:(K=H?(0,F.jsx)(`button`,{type:`button`,className:`fixed inset-0 z-40 cursor-default bg-transparent`,"aria-hidden":!0,tabIndex:-1,onPointerDown:e=>{e.preventDefault(),Le(!1)}}):null,t[24]=H,t[25]=K);let We;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(We=v(`inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-edge-subtle bg-surface-panel text-fg-muted transition-colors hover:bg-surface-hover hover:text-fg`,he.focusRingPanel),t[26]=We):We=t[26];let Ge,Ke;t[27]===Symbol.for(`react.memo_cache_sentinel`)?(Ge=()=>Le(Oe),Ke=(0,F.jsx)(p,{className:`size-4`}),t[27]=Ge,t[28]=Ke):(Ge=t[27],Ke=t[28]);let q;t[29]!==B.moreActions||t[30]!==H?(q=(0,F.jsx)(`button`,{ref:Ie,type:`button`,className:We,title:B.moreActions,"aria-label":B.moreActions,"aria-haspopup":`menu`,"aria-expanded":H,onClick:Ge,children:Ke}),t[29]=B.moreActions,t[30]=H,t[31]=q):q=t[31];let J;t[32]!==u||t[33]!==be||t[34]!==c.plugin.capabilities||t[35]!==E||t[36]!==y||t[37]!==x||t[38]!==R||t[39]!==B.copyFilePath||t[40]!==B.copyWorkspacePath||t[41]!==B.download||t[42]!==B.edit||t[43]!==B.editInNewChat||t[44]!==B.moreActions||t[45]!==B.openInBrowser||t[46]!==B.pathCopied||t[47]!==B.preview||t[48]!==B.revealInFolder||t[49]!==B.saveCopy||t[50]!==B.shareLink||t[51]!==B.wordWrap||t[52]!==H||t[53]!==xe||t[54]!==r||t[55]!==i||t[56]!==T||t[57]!==k||t[58]!==ye||t[59]!==I||t[60]!==Te||t[61]!==j||t[62]!==S||t[63]!==b?(J=H?(0,F.jsxs)(`div`,{ref:Fe,role:`menu`,"aria-label":B.moreActions,"data-file-preview-menu":!0,className:`absolute right-0 top-full z-50 mt-1 max-h-[min(32rem,calc(100dvh-8rem))] w-60 max-w-[calc(100vw-2rem)] overflow-y-auto overscroll-contain rounded-lg border border-edge bg-surface-overlay p-1 shadow-popover`,children:[(0,F.jsx)(Ee,{variant:`menu`,onAction:U,systemApp:ye,chooseApp:be,recommendedApps:Te,recentApps:I,onOpenWithApp:xe}),j.map(e=>(0,F.jsx)(L,{icon:(0,F.jsx)(h,{className:`size-4`}),label:e.label,disabled:e.disabled,onClick:()=>U(e.onClick)},e.label)),i?(0,F.jsx)(L,{icon:(0,F.jsx)(ce,{className:`size-4`}),label:R===`zh`?`重试保存`:`Retry save`,onClick:()=>U(i)}):null,r?(0,F.jsx)(L,{icon:(0,F.jsx)(se,{className:`size-4`}),label:R===`zh`?`刷新文件`:`Refresh file`,onClick:()=>U(r)}):null,c.plugin.capabilities.includes(`edit`)?(0,F.jsx)(L,{icon:y?.active?(0,F.jsx)(te,{className:`size-4`}):(0,F.jsx)(g,{className:`size-4`}),label:y?.active?B.preview:B.edit,disabled:!y,onClick:()=>U(()=>y?.onToggle())}):null,b?(0,F.jsx)(L,{icon:(0,F.jsx)(Ce,{className:`size-4`}),label:B.wordWrap,active:b.active,onClick:()=>U(b.onToggle)}):null,(0,F.jsx)(`div`,{className:`my-1 border-t border-edge-subtle dark:border-edge`}),(0,F.jsx)(L,{icon:x?.loading?(0,F.jsx)(ie,{className:`size-4 animate-spin`}):(0,F.jsx)(oe,{className:`size-4`}),label:B.editInNewChat,disabled:!x||x.disabled||x.loading,onClick:()=>U(()=>x?.onClick())}),(0,F.jsx)(L,{icon:S?.loading?(0,F.jsx)(ie,{className:`size-4 animate-spin`}):(0,F.jsx)(re,{className:`size-4`}),label:B.shareLink,disabled:!S||S.disabled||S.loading,onClick:()=>U(()=>S?.onClick())}),(0,F.jsx)(`div`,{className:`my-1 border-t border-edge-subtle dark:border-edge`}),k?(0,F.jsxs)(`a`,{href:k.href,target:`_blank`,rel:`noopener noreferrer`,role:`menuitem`,className:`flex h-9 w-full items-center gap-2.5 rounded-md px-2.5 text-sm text-fg hover:bg-surface-hover`,onClick:()=>Le(!1),children:[(0,F.jsx)(ee,{className:`size-4 text-fg-muted`,"aria-hidden":!0}),B.openInBrowser]}):null,T?(0,F.jsx)(L,{icon:(0,F.jsx)(ne,{className:`size-4`}),label:B.revealInFolder,onClick:()=>U(T)}):null,T?(0,F.jsx)(`div`,{className:`my-1 border-t border-edge-subtle dark:border-edge`}):null,(0,F.jsx)(L,{icon:(0,F.jsx)(f,{className:`size-4`}),label:Pe?B.saveCopy:B.download,disabled:!u.canDownload,onClick:()=>U(()=>void u.onDownload())}),E?(0,F.jsx)(L,{icon:E.copied?(0,F.jsx)(l,{className:`size-4 text-emerald-500`}):(0,F.jsx)(d,{className:`size-4`}),label:E.copied?B.pathCopied:Pe?B.copyFilePath:B.copyWorkspacePath,onClick:()=>U(E.onClick)}):null]}):null,t[32]=u,t[33]=be,t[34]=c.plugin.capabilities,t[35]=E,t[36]=y,t[37]=x,t[38]=R,t[39]=B.copyFilePath,t[40]=B.copyWorkspacePath,t[41]=B.download,t[42]=B.edit,t[43]=B.editInNewChat,t[44]=B.moreActions,t[45]=B.openInBrowser,t[46]=B.pathCopied,t[47]=B.preview,t[48]=B.revealInFolder,t[49]=B.saveCopy,t[50]=B.shareLink,t[51]=B.wordWrap,t[52]=H,t[53]=xe,t[54]=r,t[55]=i,t[56]=T,t[57]=k,t[58]=ye,t[59]=I,t[60]=Te,t[61]=j,t[62]=S,t[63]=b,t[64]=J):J=t[64];let Y;t[65]!==K||t[66]!==q||t[67]!==J?(Y=(0,F.jsxs)(`div`,{className:`relative shrink-0`,children:[K,q,J]}),t[65]=K,t[66]=q,t[67]=J,t[68]=Y):Y=t[68];let X;t[69]!==de||t[70]!==B.close||t[71]!==ue?(X=de?null:(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`mx-0.5 h-5 w-px bg-edge-subtle`,"aria-hidden":!0}),(0,F.jsx)(De,{label:B.close,onClick:ue,children:(0,F.jsx)(me,{className:`size-4`,strokeWidth:1.75})})]}),t[69]=de,t[70]=B.close,t[71]=ue,t[72]=X):X=t[72];let Z;t[73]!==W||t[74]!==G||t[75]!==Y||t[76]!==X?(Z=(0,F.jsx)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:(0,F.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1.5`,children:[W,G,Y,X]})}),t[73]=W,t[74]=G,t[75]=Y,t[76]=X,t[77]=Z):Z=t[77];let Q;t[78]===s?Q=t[79]:(Q=s?(0,F.jsx)(`div`,{className:`mt-1.5 flex min-h-4 min-w-0 items-center gap-2 px-3 text-xs leading-4 text-fg-muted`,children:s}):null,t[78]=s,t[79]=Q);let $;t[80]!==c||t[81]!==ze||t[82]!==z.chat||t[83]!==Me||t[84]!==D?($=ze||D?(0,F.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 overflow-x-auto pb-0.5`,children:[D?(0,F.jsx)(ve,{className:`mr-2 flex shrink-0 rounded-lg bg-surface-hover p-0.5`,role:`group`,"aria-label":z.chat.attachmentPreviewText,children:[{active:!1,label:Me},{active:!0,label:z.chat.attachmentPreviewText}].map(e=>(0,F.jsx)(`button`,{type:`button`,"aria-pressed":D.active===e.active,className:v(`rounded-md px-2.5 py-1 text-xs font-medium`,D.active===e.active?`bg-surface-hover text-fg`:`text-fg-muted hover:text-fg`),onClick:()=>D.onChange(e.active),children:e.label},e.label))}):null,ze?(0,F.jsx)(pe,{controller:c}):null]}):null,t[80]=c,t[81]=ze,t[82]=z.chat,t[83]=Me,t[84]=D,t[85]=$):$=t[85];let qe;return t[86]!==Z||t[87]!==Q||t[88]!==$?(qe=(0,F.jsxs)(`div`,{"data-workspace-toolbar":!0,className:Ue,children:[Z,Q,$]}),t[86]=Z,t[87]=Q,t[88]=$,t[89]=qe):qe=t[89],qe}function Oe(e){return!e}function ke(e){return[`zoom`,`search`,`rotate`,`pageNavigation`].includes(e)}function Ae(e){return e.language}function je({header:e,chat:t,...n}){let r=(0,O.useRef)(null);(0,O.useEffect)(()=>{let e=r.current;if(!e)return;let t=()=>{let t=fe(n.descriptor.id).scroll;e.querySelectorAll(`[class*="overflow-auto"], [class*="overflow-y-auto"], .cm-scroller`).forEach((e,n)=>{t[n]!=null&&(e.scrollTop=t[n])})},i=requestAnimationFrame(t),a=typeof MutationObserver<`u`?new MutationObserver(t):null;a?.observe(e,{childList:!0,subtree:!0});let o=()=>_(n.descriptor.id,{scroll:[...e.querySelectorAll(`[class*="overflow-auto"], [class*="overflow-y-auto"], .cm-scroller`)].map(e=>e.scrollTop)});return e.addEventListener(`scroll`,o,!0),()=>{cancelAnimationFrame(i),a?.disconnect(),e.removeEventListener(`scroll`,o,!0)}},[n.descriptor.id]);let a=(0,O.useContext)(j),[s,c]=(0,O.useState)(!1),l=de(n.descriptor),u=i(),d=o(n.language),[f,p]=(0,O.useState)(!1),ee=async()=>{if(!(!t||f)){p(!0);try{let[n,r]=await Promise.all([t.createFile(),t.conversationId?y(t.conversationId).catch(()=>null):Promise.resolve(null)]);if(n.size>33554432){S(`warning`,d.chat.attachmentFileTooLarge,{name:n.name,maxSize:b(x)});return}let i=new URLSearchParams({attachmentHandoff:le(n)}),a=t.projectId?.trim()||r?.projectId?.trim(),o=t.agentId?.trim()||r?.routing?.agentId?.trim();a&&i.set(`projectId`,a),u({pathname:`/chat/new`,search:`?${i}`},{state:{forceNewChat:!0,agentId:o||void 0}}),e.onClose()}catch{S(`error`,d.workspace.editInNewChatFailed)}finally{p(!1)}}};return(0,F.jsxs)(`div`,{ref:r,className:`flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-transparent`,children:[(0,F.jsx)(R,{...e,name:n.descriptor.fileName,filePath:n.descriptor.source.kind===`workspace`?n.descriptor.source.path:void 0,controller:l,actions:n.actions,referenceActions:t?a.map(e=>({label:e.label,disabled:s||n.loading||!!n.loadError||t.disabled,onClick:async()=>{if(!s){c(!0);try{let r=await t.createFile(),i=await N(e.id,r);S(i?`success`:`warning`,n.language===`zh`?i?`已添加到目标聊天草稿`:`未能添加附件,请确认目标聊天可用及附件限制`:i?`Added to the target chat draft`:`Could not add attachment. Check the target chat and attachment limits.`)}catch{S(`error`,n.language===`zh`?`文件引用失败,原草稿已保留`:`Could not reference file. Your draft is retained.`)}finally{c(!1)}}}})):void 0,editInNewChat:t?{onClick:()=>void ee(),loading:f,disabled:n.loading||!!n.loadError||t.disabled}:void 0},n.descriptor.id),(0,F.jsx)(ue,{...n,controller:l})]})}function z(e,t){let n=(0,P.c)(7),r=e===void 0||e,i=t!==void 0&&t,[a,o]=(0,O.useState)(!1);!r&&a&&o(!1);let s,c;n[0]!==r||n[1]!==i||n[2]!==a?(s=()=>{if(!r||!a)return;let e=document.body.style.overflow;document.body.style.overflow=`hidden`;let t=e=>{i||e.key!==`Escape`||e.defaultPrevented||document.querySelector(`[data-file-preview-menu]`)||(e.preventDefault(),e.stopImmediatePropagation(),o(!1))};return window.addEventListener(`keydown`,t,!0),()=>{document.body.style.overflow=e,window.removeEventListener(`keydown`,t,!0)}},c=[r,a,i],n[0]=r,n[1]=i,n[2]=a,n[3]=s,n[4]=c):(s=n[3],c=n[4]),(0,O.useEffect)(s,c);let l;return n[5]===a?l=n[6]:(l={expanded:a,setExpanded:o},n[5]=a,n[6]=l),l}export{k as a,Ce as c,j as i,Se as l,je as n,we as o,Te as r,A as s,z as t};
1
+ import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t,n,t as r}from"./vendor-react-BOUWij0V.js";import{u as i}from"./chunk-KS7C4IRE-CiwuuyV8.js";import{n as a}from"./locale-store-Cit_aHqC.js";import{t as o}from"./messages-DQveK9sk.js";import{t as s}from"./createLucideIcon-DPHK1VkS.js";import{t as c}from"./app-window-DXFNqt_0.js";import{t as l}from"./check-DUBLcKHA.js";import{t as u}from"./chevron-down-ccbiQQz_.js";import{t as d}from"./copy-Dv6d4Dvw.js";import{t as f}from"./download-Dk-ZjtO6.js";import{t as p}from"./ellipsis-0k4rZLoy.js";import{t as ee}from"./external-link-DjqjBmc3.js";import{t as te}from"./eye-CABVeTq0.js";import{t as ne}from"./folder-open-CyzJ19I9.js";import{t as re}from"./link-2-D_ZKYUW7.js";import{t as ie}from"./loader-circle-CifKLtgG.js";import{q as ae}from"./markdown-view-Dm01GIXv.js";import{t as oe}from"./message-square-plus-XP0tGdlV.js";import{t as m}from"./minimize-2-DtOGrlpo.js";import{t as h}from"./paperclip-f1HujQY1.js";import{t as g}from"./pencil-DmIY3Oa-.js";import{t as se}from"./refresh-cw-BRlGaq2w.js";import{t as ce}from"./save-DRDABU--.js";import{c as _,i as le,n as ue,r as de,s as fe,t as pe}from"./preview-runtime-pJGZe5Jx.js";import{t as me}from"./x-B_N4OPjy.js";import{t as v}from"./cn-0WouolD0.js";import{a as y}from"./session-api-CkOliupg.js";import{i as b}from"./attachment-utils-core-BPYdUI6y.js";import{t as x}from"./constants-D5Z-mUto.js";import{n as he}from"./interaction-BdhHBbYa.js";import{t as S}from"./composer-notifications-B0IZsy8x.js";import{r as ge}from"./app-chrome-BeB4KgOf.js";import{n as _e}from"./electron-env-DHOGevH3.js";import{t as ve}from"./sliding-tab-list-CmcrqRzN.js";import{a as ye,l as be,m as C,n as w,o as xe,r as T,t as E,u as D}from"./dist-ZrL34Ps4.js";var Se=s(`folders`,[[`path`,{d:`M20 5a2 2 0 0 1 2 2v7a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h2.5a1.5 1.5 0 0 1 1.2.6l.6.8a1.5 1.5 0 0 0 1.2.6z`,key:`a4852j`}],[`path`,{d:`M3 8.268a2 2 0 0 0-1 1.738V19a2 2 0 0 0 2 2h11a2 2 0 0 0 1.732-1`,key:`yxbcw3`}]]),Ce=s(`text-wrap`,[[`path`,{d:`m16 16-3 3 3 3`,key:`117b85`}],[`path`,{d:`M3 12h14.5a1 1 0 0 1 0 7H13`,key:`18xa6z`}],[`path`,{d:`M3 19h6`,key:`1ygdsz`}],[`path`,{d:`M3 5h18`,key:`1u36vt`}]]),O=e(t(),1),k=(0,O.createContext)(null);function A(){return(0,O.useContext)(k)}var j=(0,O.createContext)([]),we=(0,O.createContext)(null),M=new Map;function Te(e,t){return M.set(e,t),()=>{M.get(e)===t&&M.delete(e)}}async function N(e,t){return await M.get(e)?.(t)??!1}var P=n(),F=r();function I(e){let t=(0,P.c)(3),{app:n}=e,[r,i]=(0,O.useState)(),a;return t[0]!==n||t[1]!==r?(a=n?.iconDataUrl&&n.iconDataUrl!==r?(0,F.jsx)(`img`,{src:n.iconDataUrl,alt:``,width:20,height:20,className:`size-5 shrink-0 object-contain`,onError:()=>i(n.iconDataUrl)}):(0,F.jsx)(c,{className:`size-5 shrink-0 text-fg-muted`,strokeWidth:1.75,"aria-hidden":!0}),t[0]=n,t[1]=r,t[2]=a):a=t[2],a}function Ee({variant:e=`split`,onAction:t,systemApp:n,chooseApp:r,recommendedApps:i,recentApps:s,onOpenWithApp:d}){let f=a(e=>e.language),p=o(f).workspace,[te,ne]=(0,O.useState)(),[re,ae]=(0,O.useState)(!1),oe=[...i,...s],m=d&&te!==null?oe.find(e=>e.path===te?.path)??te??oe[0]:void 0,h=!!(re||n?.loading||r?.loading),g=h||!!n?.disabled,se=m?f===`zh`?`用 ${m.name} 打开`:`Open with ${m.name}`:p.openSystemApp,ce=`flex min-h-9 cursor-default items-center gap-2.5 rounded-md px-2.5 py-2 text-sm text-fg outline-none data-[highlighted]:bg-surface-hover data-[disabled]:pointer-events-none data-[disabled]:opacity-40`,_=`my-1 h-px bg-edge-subtle`;if(!n&&!r&&(!d||!oe.length))return null;if(e===`menu`){let e=e=>t?t(e):e(),a=`flex min-h-9 w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-sm text-fg hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-40`;return(0,F.jsxs)(F.Fragment,{children:[n?(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,className:a,disabled:g,onClick:()=>e(n.onClick),children:[(0,F.jsx)(ee,{className:`size-5 shrink-0 text-fg-muted`,"aria-hidden":!0}),(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:p.openSystemApp})]}):null,d?[{label:p.recommendedApps,apps:i},{label:p.recentApps,apps:s.filter(e=>!i.some(t=>t.path===e.path))}].map(t=>t.apps.length?(0,F.jsxs)(`div`,{role:`group`,"aria-label":t.label,children:[(0,F.jsx)(`div`,{className:`px-2.5 pb-1 pt-1.5 text-xs font-medium text-fg-muted`,children:t.label}),t.apps.map(t=>(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,className:a,disabled:g,onClick:()=>e(()=>d(t.path)),children:[(0,F.jsx)(I,{app:t}),(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:t.name})]},t.path))]},t.label):null):null,r?(0,F.jsxs)(`button`,{type:`button`,role:`menuitem`,className:a,disabled:g||r.disabled,onClick:()=>e(()=>{r.onClick()}),children:[(0,F.jsx)(c,{className:`size-5 shrink-0 text-fg-muted`,"aria-hidden":!0}),(0,F.jsx)(`span`,{className:`min-w-0 truncate`,children:p.chooseApp})]}):null,(0,F.jsx)(`div`,{className:`my-1 border-t border-edge-subtle dark:border-edge`})]})}return(0,F.jsxs)(`div`,{className:`inline-flex h-9 shrink-0 items-stretch rounded-full border border-edge-subtle bg-surface-panel`,children:[(0,F.jsxs)(`button`,{type:`button`,"aria-label":se,title:se,disabled:g||!m&&!n,onClick:()=>m?d?.(m.path):n?.onClick(),className:v(`inline-flex min-w-0 items-center gap-2 rounded-l-full pl-3 pr-2 text-sm font-medium text-fg transition-colors hover:bg-surface-hover disabled:cursor-not-allowed disabled:opacity-40`,he.focusRingPanel),children:[h?(0,F.jsx)(ie,{className:`size-5 animate-spin`,"aria-hidden":!0}):(0,F.jsx)(I,{app:m}),(0,F.jsx)(`span`,{children:f===`zh`?`打开`:`Open`})]}),(0,F.jsxs)(be,{modal:!1,children:[(0,F.jsx)(C,{asChild:!0,children:(0,F.jsx)(`button`,{type:`button`,"aria-label":p.chooseApp,title:p.chooseApp,disabled:g,className:v(`inline-flex w-8 shrink-0 items-center justify-center rounded-r-full text-fg-muted transition-colors hover:bg-surface-hover hover:text-fg disabled:cursor-not-allowed disabled:opacity-40`,he.focusRingPanel),children:(0,F.jsx)(u,{className:`size-4`,strokeWidth:1.75,"aria-hidden":!0})})}),(0,F.jsx)(xe,{children:(0,F.jsxs)(E,{align:`end`,sideOffset:6,collisionPadding:8,"aria-label":p.chooseApp,onEscapeKeyDown:e=>e.stopPropagation(),className:`z-[150] max-h-[var(--radix-dropdown-menu-content-available-height)] w-64 max-w-[calc(100vw-1rem)] overflow-y-auto overscroll-contain rounded-xl border border-edge bg-surface-overlay p-1 shadow-popover outline-none`,children:[n?(0,F.jsxs)(T,{className:ce,disabled:n.disabled||h,onSelect:()=>{ne(null),n.onClick()},children:[(0,F.jsx)(ee,{className:`size-5 shrink-0 text-fg-muted`,strokeWidth:1.75,"aria-hidden":!0}),(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:p.openSystemApp}),m?null:(0,F.jsx)(l,{className:`size-4 shrink-0`,"aria-hidden":!0})]}):null,d?[{label:p.recommendedApps,apps:i},{label:p.recentApps,apps:s.filter(e=>!i.some(t=>t.path===e.path))}].map(e=>e.apps.length?(0,F.jsxs)(w,{children:[(0,F.jsx)(D,{className:_}),(0,F.jsx)(ye,{className:`px-2.5 pb-1 pt-1.5 text-xs font-medium text-fg-muted`,children:e.label}),e.apps.map(e=>(0,F.jsxs)(T,{className:ce,disabled:h,title:e.name,onSelect:()=>{ne(e),d(e.path)},children:[(0,F.jsx)(I,{app:e}),(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:e.name}),e.path===m?.path?(0,F.jsx)(l,{className:`size-4 shrink-0`,"aria-hidden":!0}):null]},e.path))]},e.label):null):null,r?(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(D,{className:_}),(0,F.jsxs)(T,{className:ce,disabled:r.disabled||h,onSelect:async()=>{ae(!0);try{let e=await r.onClick();e&&ne(e)}finally{ae(!1)}},children:[(0,F.jsx)(c,{className:`size-5 shrink-0 text-fg-muted`,strokeWidth:1.75,"aria-hidden":!0}),(0,F.jsx)(`span`,{className:`min-w-0 truncate`,children:p.chooseApp})]})]}):null]})})]})]})}function De(e){let t=(0,P.c)(9),{label:n,active:r,disabled:i,onClick:a,children:o}=e,s=r&&`border-accent/20 bg-accent-soft text-accent-fg`,c;t[0]===s?c=t[1]:(c=v(`inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-edge-subtle bg-surface-panel text-fg-muted transition-colors hover:bg-surface-hover hover:text-fg disabled:cursor-not-allowed disabled:opacity-40`,s,he.focusRingPanel),t[0]=s,t[1]=c);let l;return t[2]!==r||t[3]!==o||t[4]!==i||t[5]!==n||t[6]!==a||t[7]!==c?(l=(0,F.jsx)(`button`,{type:`button`,className:c,title:n,"aria-label":n,"aria-pressed":r,disabled:i,onClick:a,children:o}),t[2]=r,t[3]=o,t[4]=i,t[5]=n,t[6]=a,t[7]=c,t[8]=l):l=t[8],l}function L(e){let t=(0,P.c)(14),{icon:n,label:r,active:i,disabled:a,onClick:o}=e,s=i===void 0?`menuitem`:`menuitemcheckbox`,c;t[0]===n?c=t[1]:(c=(0,F.jsx)(`span`,{className:`flex size-4 shrink-0 items-center justify-center text-fg-muted`,"aria-hidden":!0,children:n}),t[0]=n,t[1]=c);let u;t[2]===r?u=t[3]:(u=(0,F.jsx)(`span`,{className:`min-w-0 flex-1 truncate`,children:r}),t[2]=r,t[3]=u);let d;t[4]===i?d=t[5]:(d=i?(0,F.jsx)(l,{className:`size-4 shrink-0`,"aria-hidden":!0}):null,t[4]=i,t[5]=d);let f;return t[6]!==i||t[7]!==a||t[8]!==o||t[9]!==s||t[10]!==c||t[11]!==u||t[12]!==d?(f=(0,F.jsxs)(`button`,{type:`button`,role:s,"aria-checked":i,className:`flex h-9 w-full min-w-0 items-center gap-2.5 rounded-md px-2.5 text-left text-sm text-fg hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent disabled:cursor-not-allowed disabled:opacity-40`,disabled:a,onClick:o,children:[c,u,d]}),t[6]=i,t[7]=a,t[8]=o,t[9]=s,t[10]=c,t[11]=u,t[12]=d,t[13]=f):f=t[13],f}function R(e){let t=(0,P.c)(90),{referenceActions:n,onRefresh:r,onRetrySave:i,subtitle:s,controller:c,actions:u,expanded:_,onToggleExpanded:le,onClose:ue,hideClose:de,hideExpand:fe,edit:y,wordWrap:b,editInNewChat:x,share:S,openWithSystemApp:ye,chooseApp:be,recommendedApps:C,recentApps:w,onOpenWithApp:xe,onRevealInFolder:T,copyPath:E,textView:D,openInBrowser:k}=e,A;t[0]===n?A=t[1]:(A=n===void 0?[]:n,t[0]=n,t[1]=A);let j=A,M;t[2]===C?M=t[3]:(M=C===void 0?[]:C,t[2]=C,t[3]=M);let Te=M,N;t[4]===w?N=t[5]:(N=w===void 0?[]:w,t[4]=w,t[5]=N);let I=N,R=a(Ae),je;t[6]===R?je=t[7]:(je=o(R),t[6]=R,t[7]=je);let z=je,B=z.workspace,Me=c.plugin.id===`pdf`?z.chat.attachmentPreviewPdf:c.plugin.id===`docx`?z.chat.attachmentPreviewDocument:c.plugin.id===`spreadsheet`?z.chat.attachmentPreviewSpreadsheet:B.preview,Ne;t[8]===Symbol.for(`react.memo_cache_sentinel`)?(Ne=_e(),t[8]=Ne):Ne=t[8];let Pe=Ne,V=(0,O.useContext)(we),Fe=(0,O.useRef)(null),Ie=(0,O.useRef)(null),[H,Le]=(0,O.useState)(!1),Re;t[9]===c.plugin.capabilities?Re=t[10]:(Re=c.plugin.capabilities.some(ke),t[9]=c.plugin.capabilities,t[10]=Re);let ze=Re,Be,Ve;t[11]===H?(Be=t[12],Ve=t[13]):(Be=()=>{if(!H)return;Fe.current?.querySelector(`button:not(:disabled), a`)?.focus();let e=e=>{if([`ArrowDown`,`ArrowUp`,`Home`,`End`].includes(e.key)&&Fe.current?.contains(document.activeElement)){e.preventDefault(),e.stopImmediatePropagation();let t=[...Fe.current.querySelectorAll(`button:not(:disabled), a`)],n=t.indexOf(document.activeElement);t[e.key===`Home`?0:e.key===`End`?t.length-1:(n+(e.key===`ArrowDown`?1:-1)+t.length)%t.length]?.focus();return}e.key===`Escape`&&(e.preventDefault(),e.stopImmediatePropagation(),Le(!1),Ie.current?.focus())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},Ve=[H],t[11]=H,t[12]=Be,t[13]=Ve),(0,O.useEffect)(Be,Ve);let He;t[14]===Symbol.for(`react.memo_cache_sentinel`)?(He=e=>{Le(!1),Ie.current?.focus(),e()},t[14]=He):He=t[14];let U=He,Ue;t[15]===Symbol.for(`react.memo_cache_sentinel`)?(Ue=v(`shrink-0 bg-surface-base px-3 py-2 sm:px-4`,ge),t[15]=Ue):Ue=t[15];let W;t[16]===V?W=t[17]:(W=V?(0,F.jsx)(De,{label:V.label,active:V.active,onClick:V.onToggle,children:(0,F.jsx)(Se,{className:`size-4`,strokeWidth:1.75,"aria-hidden":!0})}):null,t[16]=V,t[17]=W);let G;t[18]!==_||t[19]!==fe||t[20]!==B.collapsePreview||t[21]!==B.expandPreview||t[22]!==le?(G=fe?null:(0,F.jsx)(De,{label:_?B.collapsePreview:B.expandPreview,active:_,disabled:!le,onClick:le,children:_?(0,F.jsx)(m,{className:`size-4`,"aria-hidden":!0}):(0,F.jsx)(ae,{className:`size-4`,"aria-hidden":!0})}),t[18]=_,t[19]=fe,t[20]=B.collapsePreview,t[21]=B.expandPreview,t[22]=le,t[23]=G):G=t[23];let K;t[24]===H?K=t[25]:(K=H?(0,F.jsx)(`button`,{type:`button`,className:`fixed inset-0 z-40 cursor-default bg-transparent`,"aria-hidden":!0,tabIndex:-1,onPointerDown:e=>{e.preventDefault(),Le(!1)}}):null,t[24]=H,t[25]=K);let We;t[26]===Symbol.for(`react.memo_cache_sentinel`)?(We=v(`inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-edge-subtle bg-surface-panel text-fg-muted transition-colors hover:bg-surface-hover hover:text-fg`,he.focusRingPanel),t[26]=We):We=t[26];let Ge,Ke;t[27]===Symbol.for(`react.memo_cache_sentinel`)?(Ge=()=>Le(Oe),Ke=(0,F.jsx)(p,{className:`size-4`}),t[27]=Ge,t[28]=Ke):(Ge=t[27],Ke=t[28]);let q;t[29]!==B.moreActions||t[30]!==H?(q=(0,F.jsx)(`button`,{ref:Ie,type:`button`,className:We,title:B.moreActions,"aria-label":B.moreActions,"aria-haspopup":`menu`,"aria-expanded":H,onClick:Ge,children:Ke}),t[29]=B.moreActions,t[30]=H,t[31]=q):q=t[31];let J;t[32]!==u||t[33]!==be||t[34]!==c.plugin.capabilities||t[35]!==E||t[36]!==y||t[37]!==x||t[38]!==R||t[39]!==B.copyFilePath||t[40]!==B.copyWorkspacePath||t[41]!==B.download||t[42]!==B.edit||t[43]!==B.editInNewChat||t[44]!==B.moreActions||t[45]!==B.openInBrowser||t[46]!==B.pathCopied||t[47]!==B.preview||t[48]!==B.revealInFolder||t[49]!==B.saveCopy||t[50]!==B.shareLink||t[51]!==B.wordWrap||t[52]!==H||t[53]!==xe||t[54]!==r||t[55]!==i||t[56]!==T||t[57]!==k||t[58]!==ye||t[59]!==I||t[60]!==Te||t[61]!==j||t[62]!==S||t[63]!==b?(J=H?(0,F.jsxs)(`div`,{ref:Fe,role:`menu`,"aria-label":B.moreActions,"data-file-preview-menu":!0,className:`absolute right-0 top-full z-50 mt-1 max-h-[min(32rem,calc(100dvh-8rem))] w-60 max-w-[calc(100vw-2rem)] overflow-y-auto overscroll-contain rounded-lg border border-edge bg-surface-overlay p-1 shadow-popover`,children:[(0,F.jsx)(Ee,{variant:`menu`,onAction:U,systemApp:ye,chooseApp:be,recommendedApps:Te,recentApps:I,onOpenWithApp:xe}),j.map(e=>(0,F.jsx)(L,{icon:(0,F.jsx)(h,{className:`size-4`}),label:e.label,disabled:e.disabled,onClick:()=>U(e.onClick)},e.label)),i?(0,F.jsx)(L,{icon:(0,F.jsx)(ce,{className:`size-4`}),label:R===`zh`?`重试保存`:`Retry save`,onClick:()=>U(i)}):null,r?(0,F.jsx)(L,{icon:(0,F.jsx)(se,{className:`size-4`}),label:R===`zh`?`刷新文件`:`Refresh file`,onClick:()=>U(r)}):null,c.plugin.capabilities.includes(`edit`)?(0,F.jsx)(L,{icon:y?.active?(0,F.jsx)(te,{className:`size-4`}):(0,F.jsx)(g,{className:`size-4`}),label:y?.active?B.preview:B.edit,disabled:!y,onClick:()=>U(()=>y?.onToggle())}):null,b?(0,F.jsx)(L,{icon:(0,F.jsx)(Ce,{className:`size-4`}),label:B.wordWrap,active:b.active,onClick:()=>U(b.onToggle)}):null,(0,F.jsx)(`div`,{className:`my-1 border-t border-edge-subtle dark:border-edge`}),(0,F.jsx)(L,{icon:x?.loading?(0,F.jsx)(ie,{className:`size-4 animate-spin`}):(0,F.jsx)(oe,{className:`size-4`}),label:B.editInNewChat,disabled:!x||x.disabled||x.loading,onClick:()=>U(()=>x?.onClick())}),(0,F.jsx)(L,{icon:S?.loading?(0,F.jsx)(ie,{className:`size-4 animate-spin`}):(0,F.jsx)(re,{className:`size-4`}),label:B.shareLink,disabled:!S||S.disabled||S.loading,onClick:()=>U(()=>S?.onClick())}),(0,F.jsx)(`div`,{className:`my-1 border-t border-edge-subtle dark:border-edge`}),k?(0,F.jsxs)(`a`,{href:k.href,target:`_blank`,rel:`noopener noreferrer`,role:`menuitem`,className:`flex h-9 w-full items-center gap-2.5 rounded-md px-2.5 text-sm text-fg hover:bg-surface-hover`,onClick:()=>Le(!1),children:[(0,F.jsx)(ee,{className:`size-4 text-fg-muted`,"aria-hidden":!0}),B.openInBrowser]}):null,T?(0,F.jsx)(L,{icon:(0,F.jsx)(ne,{className:`size-4`}),label:B.revealInFolder,onClick:()=>U(T)}):null,T?(0,F.jsx)(`div`,{className:`my-1 border-t border-edge-subtle dark:border-edge`}):null,(0,F.jsx)(L,{icon:(0,F.jsx)(f,{className:`size-4`}),label:Pe?B.saveCopy:B.download,disabled:!u.canDownload,onClick:()=>U(()=>void u.onDownload())}),E?(0,F.jsx)(L,{icon:E.copied?(0,F.jsx)(l,{className:`size-4 text-emerald-500`}):(0,F.jsx)(d,{className:`size-4`}),label:E.copied?B.pathCopied:Pe?B.copyFilePath:B.copyWorkspacePath,onClick:()=>U(E.onClick)}):null]}):null,t[32]=u,t[33]=be,t[34]=c.plugin.capabilities,t[35]=E,t[36]=y,t[37]=x,t[38]=R,t[39]=B.copyFilePath,t[40]=B.copyWorkspacePath,t[41]=B.download,t[42]=B.edit,t[43]=B.editInNewChat,t[44]=B.moreActions,t[45]=B.openInBrowser,t[46]=B.pathCopied,t[47]=B.preview,t[48]=B.revealInFolder,t[49]=B.saveCopy,t[50]=B.shareLink,t[51]=B.wordWrap,t[52]=H,t[53]=xe,t[54]=r,t[55]=i,t[56]=T,t[57]=k,t[58]=ye,t[59]=I,t[60]=Te,t[61]=j,t[62]=S,t[63]=b,t[64]=J):J=t[64];let Y;t[65]!==K||t[66]!==q||t[67]!==J?(Y=(0,F.jsxs)(`div`,{className:`relative shrink-0`,children:[K,q,J]}),t[65]=K,t[66]=q,t[67]=J,t[68]=Y):Y=t[68];let X;t[69]!==de||t[70]!==B.close||t[71]!==ue?(X=de?null:(0,F.jsxs)(F.Fragment,{children:[(0,F.jsx)(`div`,{className:`mx-0.5 h-5 w-px bg-edge-subtle`,"aria-hidden":!0}),(0,F.jsx)(De,{label:B.close,onClick:ue,children:(0,F.jsx)(me,{className:`size-4`,strokeWidth:1.75})})]}),t[69]=de,t[70]=B.close,t[71]=ue,t[72]=X):X=t[72];let Z;t[73]!==W||t[74]!==G||t[75]!==Y||t[76]!==X?(Z=(0,F.jsx)(`div`,{className:`flex min-w-0 flex-wrap items-center gap-2`,children:(0,F.jsxs)(`div`,{className:`ml-auto flex shrink-0 items-center gap-1.5`,children:[W,G,Y,X]})}),t[73]=W,t[74]=G,t[75]=Y,t[76]=X,t[77]=Z):Z=t[77];let Q;t[78]===s?Q=t[79]:(Q=s?(0,F.jsx)(`div`,{className:`mt-1.5 flex min-h-4 min-w-0 items-center gap-2 px-3 text-xs leading-4 text-fg-muted`,children:s}):null,t[78]=s,t[79]=Q);let $;t[80]!==c||t[81]!==ze||t[82]!==z.chat||t[83]!==Me||t[84]!==D?($=ze||D?(0,F.jsxs)(`div`,{className:`mt-2 flex items-center gap-2 overflow-x-auto pb-0.5`,children:[D?(0,F.jsx)(ve,{className:`mr-2 flex shrink-0 rounded-lg bg-surface-hover p-0.5`,role:`group`,"aria-label":z.chat.attachmentPreviewText,children:[{active:!1,label:Me},{active:!0,label:z.chat.attachmentPreviewText}].map(e=>(0,F.jsx)(`button`,{type:`button`,"aria-pressed":D.active===e.active,className:v(`rounded-md px-2.5 py-1 text-xs font-medium`,D.active===e.active?`bg-surface-hover text-fg`:`text-fg-muted hover:text-fg`),onClick:()=>D.onChange(e.active),children:e.label},e.label))}):null,ze?(0,F.jsx)(pe,{controller:c}):null]}):null,t[80]=c,t[81]=ze,t[82]=z.chat,t[83]=Me,t[84]=D,t[85]=$):$=t[85];let qe;return t[86]!==Z||t[87]!==Q||t[88]!==$?(qe=(0,F.jsxs)(`div`,{"data-workspace-toolbar":!0,className:Ue,children:[Z,Q,$]}),t[86]=Z,t[87]=Q,t[88]=$,t[89]=qe):qe=t[89],qe}function Oe(e){return!e}function ke(e){return[`zoom`,`search`,`rotate`,`pageNavigation`].includes(e)}function Ae(e){return e.language}function je({header:e,chat:t,...n}){let r=(0,O.useRef)(null);(0,O.useEffect)(()=>{let e=r.current;if(!e)return;let t=()=>{let t=fe(n.descriptor.id).scroll;e.querySelectorAll(`[class*="overflow-auto"], [class*="overflow-y-auto"], .cm-scroller`).forEach((e,n)=>{t[n]!=null&&(e.scrollTop=t[n])})},i=requestAnimationFrame(t),a=typeof MutationObserver<`u`?new MutationObserver(t):null;a?.observe(e,{childList:!0,subtree:!0});let o=()=>_(n.descriptor.id,{scroll:[...e.querySelectorAll(`[class*="overflow-auto"], [class*="overflow-y-auto"], .cm-scroller`)].map(e=>e.scrollTop)});return e.addEventListener(`scroll`,o,!0),()=>{cancelAnimationFrame(i),a?.disconnect(),e.removeEventListener(`scroll`,o,!0)}},[n.descriptor.id]);let a=(0,O.useContext)(j),[s,c]=(0,O.useState)(!1),l=de(n.descriptor),u=i(),d=o(n.language),[f,p]=(0,O.useState)(!1),ee=async()=>{if(!(!t||f)){p(!0);try{let[n,r]=await Promise.all([t.createFile(),t.conversationId?y(t.conversationId).catch(()=>null):Promise.resolve(null)]);if(n.size>33554432){S(`warning`,d.chat.attachmentFileTooLarge,{name:n.name,maxSize:b(x)});return}let i=new URLSearchParams({attachmentHandoff:le(n)}),a=t.projectId?.trim()||r?.projectId?.trim(),o=t.agentId?.trim()||r?.routing?.agentId?.trim();a&&i.set(`projectId`,a),u({pathname:`/chat/new`,search:`?${i}`},{state:{forceNewChat:!0,agentId:o||void 0}}),e.onClose()}catch{S(`error`,d.workspace.editInNewChatFailed)}finally{p(!1)}}};return(0,F.jsxs)(`div`,{ref:r,className:`flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-transparent`,children:[(0,F.jsx)(R,{...e,name:n.descriptor.fileName,filePath:n.descriptor.source.kind===`workspace`?n.descriptor.source.path:void 0,controller:l,actions:n.actions,referenceActions:t?a.map(e=>({label:e.label,disabled:s||n.loading||!!n.loadError||t.disabled,onClick:async()=>{if(!s){c(!0);try{let r=await t.createFile(),i=await N(e.id,r);S(i?`success`:`warning`,n.language===`zh`?i?`已添加到目标聊天草稿`:`未能添加附件,请确认目标聊天可用及附件限制`:i?`Added to the target chat draft`:`Could not add attachment. Check the target chat and attachment limits.`)}catch{S(`error`,n.language===`zh`?`文件引用失败,原草稿已保留`:`Could not reference file. Your draft is retained.`)}finally{c(!1)}}}})):void 0,editInNewChat:t?{onClick:()=>void ee(),loading:f,disabled:n.loading||!!n.loadError||t.disabled}:void 0},n.descriptor.id),(0,F.jsx)(ue,{...n,controller:l})]})}function z(e,t){let n=(0,P.c)(7),r=e===void 0||e,i=t!==void 0&&t,[a,o]=(0,O.useState)(!1);!r&&a&&o(!1);let s,c;n[0]!==r||n[1]!==i||n[2]!==a?(s=()=>{if(!r||!a)return;let e=document.body.style.overflow;document.body.style.overflow=`hidden`;let t=e=>{i||e.key!==`Escape`||e.defaultPrevented||document.querySelector(`[data-file-preview-menu]`)||(e.preventDefault(),e.stopImmediatePropagation(),o(!1))};return window.addEventListener(`keydown`,t,!0),()=>{document.body.style.overflow=e,window.removeEventListener(`keydown`,t,!0)}},c=[r,a,i],n[0]=r,n[1]=i,n[2]=a,n[3]=s,n[4]=c):(s=n[3],c=n[4]),(0,O.useEffect)(s,c);let l;return n[5]===a?l=n[6]:(l={expanded:a,setExpanded:o},n[5]=a,n[6]=l),l}export{k as a,Ce as c,j as i,Se as l,je as n,we as o,Te as r,A as s,z as t};
@@ -1 +1 @@
1
- import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t,n}from"./vendor-react-BOUWij0V.js";import{i as r,l as i,o as a}from"./locale-store-Cit_aHqC.js";import{t as o}from"./createLucideIcon-DPHK1VkS.js";import{L as s}from"./chat-page-C0ONpQcA.js";import{i as c,t as l}from"./vendor-swr-CdRzEUwF.js";import{c as u}from"./composer-payload-handoff-CRCz17sd.js";var d=o(`phone`,[[`path`,{d:`M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384`,key:`9njp5v`}]]),f=n(),p=e(t(),1),m=10;function h(e){return r(`/api/personal-agent/activity?view=work&limit=${m}&offset=${e}`)}async function g([e]){return(await a(e)).payload}function _(e){let t=(0,f.c)(3),n=i(v),r;return t[0]!==e||t[1]!==n?(r=e?[h(0),e,n]:null,t[0]=e,t[1]=n,t[2]=r):r=t[2],c(r,g)}function v(e){return e.conversationId}function y(e,t,n){let r=(0,f.c)(36),a=i(S),[o,s]=(0,p.useState)(!1),c=t?.total??0,u;r[0]!==a||r[1]!==e||r[2]!==o||r[3]!==c?(u=(t,n)=>{let r=(t+1)*m;return!o||r>=c||n&&n.items.length<m?null:[h(r),e,a]},r[0]=a,r[1]=e,r[2]=o,r[3]=c,r[4]=u):u=r[4];let d;r[5]===Symbol.for(`react.memo_cache_sentinel`)?(d={revalidateFirstPage:!1,shouldRetryOnError:!1},r[5]=d):d=r[5];let{data:_,error:v,isValidating:y,size:C,setSize:w,mutate:T}=l(u,g,d),E;r[6]!==t?.items||r[7]!==c?(E=JSON.stringify([c,t?.items.map(x)]),r[6]=t?.items,r[7]=c,r[8]=E):E=r[8];let D=E,O=(0,p.useRef)(D),k,A;r[9]!==D||r[10]!==T||r[11]!==o?(k=()=>{let e=O.current!==D;O.current=D,e&&o&&T()},A=[D,T,o],r[9]=D,r[10]=T,r[11]=o,r[12]=k,r[13]=A):(k=r[12],A=r[13]),(0,p.useEffect)(k,A);let j=_?.length??0,M;r[14]!==_||r[15]!==j||r[16]!==c?(M=(j+1)*m<c&&(j===0||_?.at(-1)?.items.length===m),r[14]=_,r[15]=j,r[16]=c,r[17]=M):M=r[17];let N=M,P=o&&!v&&N&&(y||C>j),F;r[18]!==w||r[19]!==C||r[20]!==o?(F=()=>{o?w(C+1):s(!0)},r[18]=w,r[19]=C,r[20]=o,r[21]=F):F=r[21];let I=F,L;r[22]===t?.items?L=r[23]:(L=t?.items??[],r[22]=t?.items,r[23]=L);let R;r[24]!==_||r[25]!==L?(R=[...L,...(_??[]).flatMap(b)],r[24]=_,r[25]=L,r[26]=R):R=r[26];let z=n?v:void 0,B=n&&N,V=n&&P,H;r[27]===T?H=r[28]:(H=()=>void T(),r[27]=T,r[28]=H);let U;return r[29]!==I||r[30]!==B||r[31]!==V||r[32]!==H||r[33]!==R||r[34]!==z?(U={items:R,error:z,hasMore:B,loading:V,loadMore:I,retry:H},r[29]=I,r[30]=B,r[31]=V,r[32]=H,r[33]=R,r[34]=z,r[35]=U):U=r[35],U}function b(e){return e.items}function x(e){return e.id}function S(e){return e.conversationId}function C(e){let t=(0,f.c)(6),n=i(T),a=`/api/sessions/${encodeURIComponent(e??``)}/clarification`,o;t[0]===a?o=t[1]:(o=r(a),t[0]=a,t[1]=o);let s=o,l;return t[2]!==e||t[3]!==n||t[4]!==s?(l=e?[s,e,n]:null,t[2]=e,t[3]=n,t[4]=s,t[5]=l):l=t[5],c(l,w)}async function w(e){let[t]=e;return(await a(t)).payload?.clarification??null}function T(e){return e.conversationId}function E(e){return!!e.attention||e.presentation.status===`needsUser`||e.presentation.status===`review`}function D(e,t,n){let r=(0,f.c)(5),i,a;r[0]!==e||r[1]!==n||r[2]!==t?(i=()=>{if(!e)return;let r,i=()=>{window.clearTimeout(r),r=window.setTimeout(()=>{Promise.allSettled([t(),n?.()])},120)},a=[`task-changed-v2`,`task-updated`,`clarification-updated`,`gateway-realtime-connected`],o=t=>{t.detail?.key===e&&i()};a.forEach(e=>window.addEventListener(e,i)),window.addEventListener(`session-transcript-updated`,o);let s=window.setInterval(()=>{document.visibilityState===`visible`&&i()},15e3);return()=>{window.clearTimeout(r),window.clearInterval(s),a.forEach(e=>window.removeEventListener(e,i)),window.removeEventListener(`session-transcript-updated`,o)}},a=[e,t,n],r[0]=e,r[1]=n,r[2]=t,r[3]=i,r[4]=a):(i=r[3],a=r[4]),(0,p.useEffect)(i,a)}function O(e,t){let n=(0,f.c)(5),r=(0,p.useRef)(null),i=(0,p.useRef)(null),a,o;n[0]!==e||n[1]!==t?(a=()=>{let n=r.current,a=i.current;if(!e||!n||!a||typeof IntersectionObserver>`u`)return;let o=new IntersectionObserver(e=>{e.some(k)&&t()},{root:n,rootMargin:`0px 0px 120px`});return o.observe(a),()=>o.disconnect()},o=[e,t],n[0]=e,n[1]=t,n[2]=a,n[3]=o):(a=n[2],o=n[3]),(0,p.useEffect)(a,o);let s;return n[4]===Symbol.for(`react.memo_cache_sentinel`)?(s={listRef:r,loadMoreRef:i},n[4]=s):s=n[4],s}function k(e){return e.isIntersecting}function A(e){return e?.status===`open`&&(e.expiresAt===void 0||e.expiresAt>Date.now())}function j(e,t){let{status:n}=e.presentation,r=n===`failed`?`bg-danger`:[`needsUser`,`review`,`waiting`,`blocked`,`paused`].includes(n)?`bg-warning`:[`running`,`verifying`,`completed`].includes(n)?`bg-accent`:`bg-fg-subtle`;return[u(t?`zh`:`en`).detailStatuses[n],r]}function M(e,t){let n=(0,f.c)(26),r;n[0]===e?r=n[1]:(r=t=>e?t.runs[e]:void 0,n[0]=e,n[1]=r);let i=s(r),{data:a,mutate:o,error:c}=_(e),{data:l,mutate:u,error:d}=C(e),m,h,g,v;if(n[2]!==l||n[3]!==a?.current){m=a?.current??[];let e=m.filter(E);v=e.length,h=Number,g=A(l)&&!e.some(e=>e.prompt?.id===l.id),n[2]=l,n[3]=a?.current,n[4]=m,n[5]=h,n[6]=g,n[7]=v}else m=n[4],h=n[5],g=n[6],v=n[7];let y=v+h(g),b;n[8]===m?b=n[9]:(b=m.filter(F),n[8]=m,n[9]=b);let x=b,S;n[10]===m?S=n[11]:(S=m.filter(P),n[10]=m,n[11]=S);let w=S,T;n[12]===a?.items?T=n[13]:(T=a?.items.find(N)?.updatedAt,n[12]=a?.items,n[13]=T);let D=T,[O,k]=(0,p.useState)(),j,M;n[14]===D?(j=n[15],M=n[16]):(j=()=>{if(D===void 0)return;let e=D+4e3-Date.now();if(e<=0)return;k(D);let t=window.setTimeout(()=>k(void 0),e);return()=>window.clearTimeout(t)},M=[D],n[14]=D,n[15]=j,n[16]=M),(0,p.useEffect)(j,M);let I=O!==void 0&&O===D,L=y?`waiting`:x.length||w.length||i?.status===`running`?`working`:i?.status===`waiting`?`waiting`:I?`delivered`:`idle`,R=``;y?R=t?`有 ${y} 项待你处理`:`${y} to review`:x.length>1?R=t?`有 ${x.length} 项正在推进`:`${x.length} in progress`:x[0]?R=t?`正在推进 · ${x[0].title}`:`Working · ${x[0].title}`:i?.status===`running`?R=t?`正在回复`:`Responding`:w.length?R=t?`有 ${w.length} 项等待开始`:`${w.length} queued`:i?.status===`waiting`?R=t?`等待继续`:`Waiting to resume`:I?R=t?`刚刚完成交付`:`Just delivered`:(c||d)&&(R=t?`暂时无法更新状态`:`Status unavailable`);let z;return n[17]!==y||n[18]!==L||n[19]!==l||n[20]!==u||n[21]!==o||n[22]!==R||n[23]!==a||n[24]!==c?(z={work:a,workError:c,prompt:l,avatarState:L,summary:R,attentionCount:y,refreshWork:o,refreshPrompt:u},n[17]=y,n[18]=L,n[19]=l,n[20]=u,n[21]=o,n[22]=R,n[23]=a,n[24]=c,n[25]=z):z=n[25],z}function N(e){return e.resolution===`done`}function P(e){return e.operationalState===`queued`||e.operationalState===`allocating`}function F(e){return e.operationalState===`running`||e.operationalState===`verifying`}export{y as a,d as c,O as i,E as n,M as o,j as r,D as s,A as t};
1
+ import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t,n}from"./vendor-react-BOUWij0V.js";import{i as r,l as i,o as a}from"./locale-store-Cit_aHqC.js";import{t as o}from"./createLucideIcon-DPHK1VkS.js";import{L as s}from"./chat-page-4Agzfc_0.js";import{i as c,t as l}from"./vendor-swr-CdRzEUwF.js";import{c as u}from"./composer-payload-handoff-CRCz17sd.js";var d=o(`phone`,[[`path`,{d:`M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384`,key:`9njp5v`}]]),f=n(),p=e(t(),1),m=10;function h(e){return r(`/api/personal-agent/activity?view=work&limit=${m}&offset=${e}`)}async function g([e]){return(await a(e)).payload}function _(e){let t=(0,f.c)(3),n=i(v),r;return t[0]!==e||t[1]!==n?(r=e?[h(0),e,n]:null,t[0]=e,t[1]=n,t[2]=r):r=t[2],c(r,g)}function v(e){return e.conversationId}function y(e,t,n){let r=(0,f.c)(36),a=i(S),[o,s]=(0,p.useState)(!1),c=t?.total??0,u;r[0]!==a||r[1]!==e||r[2]!==o||r[3]!==c?(u=(t,n)=>{let r=(t+1)*m;return!o||r>=c||n&&n.items.length<m?null:[h(r),e,a]},r[0]=a,r[1]=e,r[2]=o,r[3]=c,r[4]=u):u=r[4];let d;r[5]===Symbol.for(`react.memo_cache_sentinel`)?(d={revalidateFirstPage:!1,shouldRetryOnError:!1},r[5]=d):d=r[5];let{data:_,error:v,isValidating:y,size:C,setSize:w,mutate:T}=l(u,g,d),E;r[6]!==t?.items||r[7]!==c?(E=JSON.stringify([c,t?.items.map(x)]),r[6]=t?.items,r[7]=c,r[8]=E):E=r[8];let D=E,O=(0,p.useRef)(D),k,A;r[9]!==D||r[10]!==T||r[11]!==o?(k=()=>{let e=O.current!==D;O.current=D,e&&o&&T()},A=[D,T,o],r[9]=D,r[10]=T,r[11]=o,r[12]=k,r[13]=A):(k=r[12],A=r[13]),(0,p.useEffect)(k,A);let j=_?.length??0,M;r[14]!==_||r[15]!==j||r[16]!==c?(M=(j+1)*m<c&&(j===0||_?.at(-1)?.items.length===m),r[14]=_,r[15]=j,r[16]=c,r[17]=M):M=r[17];let N=M,P=o&&!v&&N&&(y||C>j),F;r[18]!==w||r[19]!==C||r[20]!==o?(F=()=>{o?w(C+1):s(!0)},r[18]=w,r[19]=C,r[20]=o,r[21]=F):F=r[21];let I=F,L;r[22]===t?.items?L=r[23]:(L=t?.items??[],r[22]=t?.items,r[23]=L);let R;r[24]!==_||r[25]!==L?(R=[...L,...(_??[]).flatMap(b)],r[24]=_,r[25]=L,r[26]=R):R=r[26];let z=n?v:void 0,B=n&&N,V=n&&P,H;r[27]===T?H=r[28]:(H=()=>void T(),r[27]=T,r[28]=H);let U;return r[29]!==I||r[30]!==B||r[31]!==V||r[32]!==H||r[33]!==R||r[34]!==z?(U={items:R,error:z,hasMore:B,loading:V,loadMore:I,retry:H},r[29]=I,r[30]=B,r[31]=V,r[32]=H,r[33]=R,r[34]=z,r[35]=U):U=r[35],U}function b(e){return e.items}function x(e){return e.id}function S(e){return e.conversationId}function C(e){let t=(0,f.c)(6),n=i(T),a=`/api/sessions/${encodeURIComponent(e??``)}/clarification`,o;t[0]===a?o=t[1]:(o=r(a),t[0]=a,t[1]=o);let s=o,l;return t[2]!==e||t[3]!==n||t[4]!==s?(l=e?[s,e,n]:null,t[2]=e,t[3]=n,t[4]=s,t[5]=l):l=t[5],c(l,w)}async function w(e){let[t]=e;return(await a(t)).payload?.clarification??null}function T(e){return e.conversationId}function E(e){return!!e.attention||e.presentation.status===`needsUser`||e.presentation.status===`review`}function D(e,t,n){let r=(0,f.c)(5),i,a;r[0]!==e||r[1]!==n||r[2]!==t?(i=()=>{if(!e)return;let r,i=()=>{window.clearTimeout(r),r=window.setTimeout(()=>{Promise.allSettled([t(),n?.()])},120)},a=[`task-changed-v2`,`task-updated`,`clarification-updated`,`gateway-realtime-connected`],o=t=>{t.detail?.key===e&&i()};a.forEach(e=>window.addEventListener(e,i)),window.addEventListener(`session-transcript-updated`,o);let s=window.setInterval(()=>{document.visibilityState===`visible`&&i()},15e3);return()=>{window.clearTimeout(r),window.clearInterval(s),a.forEach(e=>window.removeEventListener(e,i)),window.removeEventListener(`session-transcript-updated`,o)}},a=[e,t,n],r[0]=e,r[1]=n,r[2]=t,r[3]=i,r[4]=a):(i=r[3],a=r[4]),(0,p.useEffect)(i,a)}function O(e,t){let n=(0,f.c)(5),r=(0,p.useRef)(null),i=(0,p.useRef)(null),a,o;n[0]!==e||n[1]!==t?(a=()=>{let n=r.current,a=i.current;if(!e||!n||!a||typeof IntersectionObserver>`u`)return;let o=new IntersectionObserver(e=>{e.some(k)&&t()},{root:n,rootMargin:`0px 0px 120px`});return o.observe(a),()=>o.disconnect()},o=[e,t],n[0]=e,n[1]=t,n[2]=a,n[3]=o):(a=n[2],o=n[3]),(0,p.useEffect)(a,o);let s;return n[4]===Symbol.for(`react.memo_cache_sentinel`)?(s={listRef:r,loadMoreRef:i},n[4]=s):s=n[4],s}function k(e){return e.isIntersecting}function A(e){return e?.status===`open`&&(e.expiresAt===void 0||e.expiresAt>Date.now())}function j(e,t){let{status:n}=e.presentation,r=n===`failed`?`bg-danger`:[`needsUser`,`review`,`waiting`,`blocked`,`paused`].includes(n)?`bg-warning`:[`running`,`verifying`,`completed`].includes(n)?`bg-accent`:`bg-fg-subtle`;return[u(t?`zh`:`en`).detailStatuses[n],r]}function M(e,t){let n=(0,f.c)(26),r;n[0]===e?r=n[1]:(r=t=>e?t.runs[e]:void 0,n[0]=e,n[1]=r);let i=s(r),{data:a,mutate:o,error:c}=_(e),{data:l,mutate:u,error:d}=C(e),m,h,g,v;if(n[2]!==l||n[3]!==a?.current){m=a?.current??[];let e=m.filter(E);v=e.length,h=Number,g=A(l)&&!e.some(e=>e.prompt?.id===l.id),n[2]=l,n[3]=a?.current,n[4]=m,n[5]=h,n[6]=g,n[7]=v}else m=n[4],h=n[5],g=n[6],v=n[7];let y=v+h(g),b;n[8]===m?b=n[9]:(b=m.filter(F),n[8]=m,n[9]=b);let x=b,S;n[10]===m?S=n[11]:(S=m.filter(P),n[10]=m,n[11]=S);let w=S,T;n[12]===a?.items?T=n[13]:(T=a?.items.find(N)?.updatedAt,n[12]=a?.items,n[13]=T);let D=T,[O,k]=(0,p.useState)(),j,M;n[14]===D?(j=n[15],M=n[16]):(j=()=>{if(D===void 0)return;let e=D+4e3-Date.now();if(e<=0)return;k(D);let t=window.setTimeout(()=>k(void 0),e);return()=>window.clearTimeout(t)},M=[D],n[14]=D,n[15]=j,n[16]=M),(0,p.useEffect)(j,M);let I=O!==void 0&&O===D,L=y?`waiting`:x.length||w.length||i?.status===`running`?`working`:i?.status===`waiting`?`waiting`:I?`delivered`:`idle`,R=``;y?R=t?`有 ${y} 项待你处理`:`${y} to review`:x.length>1?R=t?`有 ${x.length} 项正在推进`:`${x.length} in progress`:x[0]?R=t?`正在推进 · ${x[0].title}`:`Working · ${x[0].title}`:i?.status===`running`?R=t?`正在回复`:`Responding`:w.length?R=t?`有 ${w.length} 项等待开始`:`${w.length} queued`:i?.status===`waiting`?R=t?`等待继续`:`Waiting to resume`:I?R=t?`刚刚完成交付`:`Just delivered`:(c||d)&&(R=t?`暂时无法更新状态`:`Status unavailable`);let z;return n[17]!==y||n[18]!==L||n[19]!==l||n[20]!==u||n[21]!==o||n[22]!==R||n[23]!==a||n[24]!==c?(z={work:a,workError:c,prompt:l,avatarState:L,summary:R,attentionCount:y,refreshWork:o,refreshPrompt:u},n[17]=y,n[18]=L,n[19]=l,n[20]=u,n[21]=o,n[22]=R,n[23]=a,n[24]=c,n[25]=z):z=n[25],z}function N(e){return e.resolution===`done`}function P(e){return e.operationalState===`queued`||e.operationalState===`allocating`}function F(e){return e.operationalState===`running`||e.operationalState===`verifying`}export{y as a,d as c,O as i,E as n,M as o,j as r,D as s,A as t};
@@ -1 +1 @@
1
- import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t}from"./vendor-react-BOUWij0V.js";import{i as n,o as r,p as i,r as a}from"./locale-store-Cit_aHqC.js";import{a as o,r as s}from"./voice-CDlC6XMH.js";import{t as c}from"./session-manager-BVS3zxRZ.js";import{t as l}from"./middleware-Pd0e8Igk.js";import{t as u}from"./composer-notifications-B0IZsy8x.js";var d=e(t(),1),ee=i()(l(e=>({captions:!0,microphoneId:``,setCaptions:t=>e({captions:t}),setMicrophoneId:t=>e({microphoneId:t})}),{name:`xopc-voice-preferences`}));function te(){let e=ee.getState().microphoneId;return{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,...e?{deviceId:{exact:e}}:{}}}function ne(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=(e,n)=>{o||(o=!0,clearTimeout(l),t.removeEventListener(`abort`,c),e===void 0?i(n):a(e))},c=()=>s(t.reason??new DOMException(`Cancelled`,`AbortError`)),l=setTimeout(()=>s(new DOMException(`Voice startup timed out`,`TimeoutError`)),n);e.then(e=>{o?r?.(e):s(void 0,e)},e=>s(e)),t.addEventListener(`abort`,c,{once:!0}),t.aborted&&c()})}function re(e,t,n,r){let i=e.get(t);if(i&&(n<i.revision||i.final&&!r||n===i.revision&&(i.final||!r)))return!1;if(!e.has(t)&&e.size>=256){let t=e.keys().next().value;t!==void 0&&e.delete(t)}return e.set(t,{revision:n,final:r}),!0}var f=32,p=1481592883,ie=3,ae=1,oe=2,m=1,h=64*1024,g=new TextEncoder,_=new TextDecoder(`utf-8`,{fatal:!0});function se(e){let t=g.encode(e.id);if(!t.length||t.length>160||!Number.isInteger(e.connectionEpoch)||e.connectionEpoch<1||e.connectionEpoch>4294967295||!Number.isInteger(e.seq)||e.seq<1||e.seq>4294967295||!Number.isFinite(e.timestampMs)||e.timestampMs<0||e.durationMs!==20||e.flags<0||e.flags>3||!e.audio.length||e.audio.length%2||f+t.length+e.audio.length>h)throw Error(`Invalid voice media frame`);let n=new Uint8Array(f+t.length+e.audio.length),r=new DataView(n.buffer);return r.setUint32(0,p),r.setUint8(4,ie),r.setUint8(5,e.kind),r.setUint8(6,m),r.setUint8(7,e.flags),r.setUint32(8,e.connectionEpoch),r.setUint32(12,e.seq),r.setFloat64(16,e.timestampMs),r.setUint16(24,e.durationMs),r.setUint16(26,t.length),r.setUint32(28,e.audio.length),n.set(t,f),n.set(e.audio,f+t.length),n}function ce(e,t){if(e.length<=f||e.length>h)throw Error(`Invalid voice media frame`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(5),i=n.getUint32(8),a=n.getUint32(12),o=n.getFloat64(16),s=n.getUint16(24),c=n.getUint16(26),l=n.getUint32(28),u=f+c,d=n.getUint8(7);if(n.getUint32(0)!==p||n.getUint8(4)!==ie||r!==t||n.getUint8(6)!==m||d>3||!i||!a||!Number.isFinite(o)||o<0||s!==20||!c||c>160||!l||l%2||u+l!==e.length)throw Error(`Invalid voice media header`);return{kind:r,connectionEpoch:i,id:_.decode(e.subarray(f,u)),seq:a,timestampMs:o,durationMs:s,flags:d,audio:e.slice(u)}}function le(e){let t=ce(e,oe);return{connectionEpoch:t.connectionEpoch,responseId:t.id,seq:t.seq,mediaTimestampMs:t.timestampMs,durationMs:t.durationMs,audio:t.audio}}function ue(e){return se({kind:ae,connectionEpoch:e.connectionEpoch,id:e.utteranceId,seq:e.audioSeq,timestampMs:e.capturedAtMonotonicMs,durationMs:e.durationMs,flags:!!e.start|(e.end?2:0),audio:e.audio})}var de=class{session;eventSeq=0;audioSeq=0;ready=!1;closed=!1;cancelled=new Set;constructor(e){this.session=e}event(e){if(this.closed)throw Error(`Voice session closed`);if(e.sessionId!==this.session.sessionId||e.seq!==this.eventSeq+1)throw Error(`Invalid voice event sequence`);if(this.eventSeq=e.seq,e.type===`session.ready`){if(this.ready||e.payload.connectionEpoch!==this.session.connectionEpoch||e.payload.purpose!==this.session.purpose||e.payload.inputMode!==this.session.inputMode||e.payload.inputFormat.sampleRate!==this.session.inputFormat.sampleRate||e.payload.mode!==this.session.mode||e.payload.route.engine!==this.session.route.engine)throw Error(`Voice session mismatch`);this.ready=!0}e.type===`response.cancelled`&&this.cancel(e.payload.responseId),e.type===`session.closed`&&(this.ready=!1,this.closed=!0)}audio(e){if(!this.ready||e.connectionEpoch!==this.session.connectionEpoch||e.seq!==this.audioSeq+1)throw Error(`Invalid voice audio sequence`);return this.audioSeq=e.seq,!this.cancelled.has(e.responseId)}cancel(e){if(!this.cancelled.has(e)){if(this.cancelled.size>=1e4)throw Error(`Voice response limit exceeded`);this.cancelled.add(e)}}};function v(e,t){return{protocolVersion:3,messageId:crypto.randomUUID(),type:e,sentAt:Date.now(),payload:t}}function y(e){let t=new URL(n(e));return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.toString()}var fe=class e{socket;session;timingMetrics;receive;heartbeatId;inputRemainder=new Uint8Array;utteranceId=crypto.randomUUID();inputSeq=0;constructor(e,t,n=[]){this.socket=e,this.session=t,this.timingMetrics=n,this.receive=new de(t)}static async preflight(e){return e.purpose===`conversation`&&e.conversationId&&await new c().materialize(e.conversationId,`voice`),(await r(n(`/api/voice/realtime/preflight`),{method:`POST`,signal:e.signal,body:JSON.stringify({purpose:e.purpose,mode:e.mode,naturalBackend:e.naturalBackend,testHiggsVoice:e.testHiggsVoice,conversationId:e.conversationId,supportedProtocolVersions:[3],mediaPreferences:[`websocket-pcm`]})})).timingMetrics??[]}static async connect(t){t.signal?.throwIfAborted();let i=await r(n(`/api/voice/realtime/sessions`),{method:`POST`,signal:t.signal,body:JSON.stringify({purpose:t.purpose,...t.language?{language:t.language}:{},...t.purpose===`conversation`&&t.mode!==`natural`&&t.logicalCallId?{openingGreeting:{logicalCallId:t.logicalCallId,initiation:t.recovery?`recovery`:`user`,supportsOutputReady:!0}}:{},...t.mode?{mode:t.mode}:{},...t.naturalBackend?{naturalBackend:t.naturalBackend}:{},...t.testHiggsVoice?{testHiggsVoice:t.testHiggsVoice}:{},...t.conversationId?{conversationId:t.conversationId}:{},supportedProtocolVersions:[3],mediaPreferences:[`websocket-pcm`]})}),a=s.parse(i.payload);t.signal?.throwIfAborted();let c=new WebSocket(y(a.websocketPath));c.binaryType=`arraybuffer`;let l=new e(c,a,t.timingMetrics);return await new Promise((e,n)=>{let r=!1,i,s=e=>{r||(r=!0,i!==void 0&&window.clearTimeout(i),c.close(),n(e))};i=window.setTimeout(()=>s(Error(`Realtime voice connection timed out`)),15e3);let u=()=>{r?c.close():s(Error(`Realtime voice connection cancelled`))};if(t.signal?.addEventListener(`abort`,u,{once:!0}),c.addEventListener(`close`,()=>t.signal?.removeEventListener(`abort`,u),{once:!0}),t.signal?.aborted){u();return}c.onerror=()=>s(Error(`Realtime voice connection failed`)),c.onclose=e=>{r?t.onClose?.(e.reason):s(Error(e.reason||`Realtime voice connection closed`))},c.onopen=()=>{c.send(JSON.stringify(v(`session.start`,{sessionId:a.sessionId,ticket:a.ticket})))},c.onmessage=n=>{if(typeof n.data!=`string`){try{let e=le(new Uint8Array(n.data));l.receive.audio(e)&&t.onAudio?.(e.audio.slice().buffer,e.responseId)}catch{c.close(4400,`Invalid voice audio frame`)}return}try{let c=o(JSON.parse(n.data));if(l.receive.event(c),t.onEvent(c),c.type===`session.ready`&&!r){if(c.payload.connectionEpoch!==a.connectionEpoch||c.payload.mode!==a.mode)throw Error(`Voice session mismatch`);r=!0,window.clearTimeout(i),l.startHeartbeat(c.payload.heartbeatIntervalMs),e()}else c.type===`session.error`&&!c.payload.recoverable&&s(Error(c.payload.message))}catch(e){r?c.close(4400,`Invalid voice protocol frame`):s(e instanceof Error?e:Error(String(e)))}}}),l}outputReady(){this.session.openingGreeting?.accepted&&this.sendControl(`session.output_ready`,{connectionEpoch:this.session.connectionEpoch})}sendAudio(e){if(!e.byteLength||this.socket.readyState!==WebSocket.OPEN)return;let t=new Uint8Array(e),n=new Uint8Array(this.inputRemainder.byteLength+t.byteLength);n.set(this.inputRemainder),n.set(t,this.inputRemainder.byteLength);let r=0;for(;r+640<=n.byteLength;){let e=ue({connectionEpoch:this.session.connectionEpoch,utteranceId:this.utteranceId,audioSeq:++this.inputSeq,capturedAtMonotonicMs:performance.now(),durationMs:20,...this.inputSeq===1?{start:!0}:{},audio:n.slice(r,r+640)});this.socket.send(e.buffer),r+=640}this.inputRemainder=n.slice(r)}reportMetric(e,t,n){t===`speech_end_to_audio_scheduled`&&!this.timingMetrics.includes(t)||this.sendControl(`session.metric`,{responseId:e,metric:t,durationMs:Math.min(6e5,Math.max(0,n))})}setInputMuted(e){this.sendControl(`input.mute`,{muted:e}),this.inputRemainder=new Uint8Array,e||(this.utteranceId=crypto.randomUUID(),this.inputSeq=0)}commit(){this.sendControl(`input.commit`,{})}cancelResponse(e){this.sendControl(`response.stop_playback`,{responseId:e})}cancelTask(e){this.sendControl(`task.cancel`,{taskId:e})}acknowledgeAudio(e,t){this.sendControl(`response.audio.played`,{responseId:e,playedDurationMs:Math.floor(t/48)})}stop(e=`user_finished`){this.stopHeartbeat(),this.socket.readyState===WebSocket.OPEN?this.sendControl(`session.stop`,{reason:e}):this.socket.close()}sendControl(e,t){this.socket.readyState===WebSocket.OPEN&&(e===`response.stop_playback`&&`responseId`in t&&this.receive.cancel(t.responseId),this.socket.send(JSON.stringify(v(e,t))))}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatId=window.setInterval(()=>this.sendControl(`session.ping`,{}),e),this.socket.addEventListener(`close`,()=>this.stopHeartbeat(),{once:!0})}stopHeartbeat(){this.heartbeatId!==void 0&&(window.clearInterval(this.heartbeatId),this.heartbeatId=void 0)}},b=1.7,pe=class{context=new AudioContext({sampleRate:24e3,latencyHint:`interactive`});output=this.context.createGain();ringbackOutput=this.context.createGain();limiter=this.context.createDynamicsCompressor();sources=new Set;ringbackSources=new Map;ringbackDelay=null;ringbackInterval=null;ringbackActive=!1;nextStartTime=0;hasStartedAudio=!1;confirmedSpeech=!1;tentativeDuckTimer;constructor(){this.output.gain.value=b,this.limiter.threshold.value=-6,this.limiter.knee.value=6,this.limiter.ratio.value=12,this.limiter.attack.value=.003,this.limiter.release.value=.12,this.output.connect(this.limiter),this.limiter.connect(this.context.destination),this.ringbackOutput.gain.value=0,this.ringbackOutput.connect(this.context.destination)}async start(){await this.context.resume()}get hasPendingAudio(){return this.sources.size>0}startRingback(){this.stopRingback(),this.context.state!==`closed`&&(this.ringbackActive=!0,this.ringbackDelay=setTimeout(()=>{this.ringbackDelay=null,!(!this.ringbackActive||this.context.state!==`running`)&&(this.ringbackOutput.gain.cancelScheduledValues(this.context.currentTime),this.ringbackOutput.gain.setValueAtTime(.14,this.context.currentTime),this.playRingbackPulse(),this.ringbackInterval=setInterval(()=>this.playRingbackPulse(),3e3))},500))}playRingbackPulse(){if(!this.ringbackActive||this.context.state!==`running`)return;let e=this.context.currentTime;for(let[t,n]of[392,494].entries()){let r=e+t*.4,i=this.context.createOscillator(),a=this.context.createGain();i.type=`sine`,i.frequency.value=n,a.gain.setValueAtTime(0,r),a.gain.linearRampToValueAtTime(.5,r+.04),a.gain.setValueAtTime(.5,r+.18),a.gain.linearRampToValueAtTime(0,r+.28),i.connect(a),a.connect(this.ringbackOutput),this.ringbackSources.set(i,a),i.onended=()=>{this.ringbackSources.delete(i),i.disconnect(),a.disconnect()},i.start(r),i.stop(r+.29)}}stopRingback(){if(this.ringbackActive=!1,this.ringbackDelay!==null&&clearTimeout(this.ringbackDelay),this.ringbackInterval!==null&&clearInterval(this.ringbackInterval),this.ringbackDelay=null,this.ringbackInterval=null,this.context.state!==`closed`){this.ringbackOutput.gain.cancelScheduledValues(this.context.currentTime),this.ringbackOutput.gain.setTargetAtTime(0,this.context.currentTime,.025);for(let[e,t]of this.ringbackSources){t.gain.cancelScheduledValues(this.context.currentTime),t.gain.setTargetAtTime(0,this.context.currentTime,.02);try{e.stop(this.context.currentTime+.12)}catch{}}}}enqueue(e,t,n=24e3){if(e.byteLength<2||this.context.state===`closed`)return;let r=new DataView(e),i=new Float32Array(Math.floor(e.byteLength/2));for(let e=0;e<i.length;e+=1)i[e]=r.getInt16(e*2,!0)/32768;let a=this.context.createBuffer(1,i.length,n);a.copyToChannel(i,0);let o=this.context.createBufferSource();o.buffer=a,o.connect(this.output);let s=this.hasStartedAudio?.015:.02,c=Math.max(this.context.currentTime+s,this.nextStartTime);return o.start(c),this.hasStartedAudio=!0,this.nextStartTime=c+a.duration,this.sources.add(o),o.onended=()=>{this.sources.delete(o)&&(o.disconnect(),t())},Math.max(0,c-this.context.currentTime)*1e3}duck(e){clearTimeout(this.tentativeDuckTimer),this.tentativeDuckTimer=void 0,this.confirmedSpeech=e,this.setOutputGain(e?.15:1)}duckForVoiceOnset(){this.confirmedSpeech||this.tentativeDuckTimer!==void 0||!this.hasPendingAudio||(this.setOutputGain(.55),this.tentativeDuckTimer=setTimeout(()=>{this.tentativeDuckTimer=void 0,this.setOutputGain(1)},280))}setOutputGain(e){this.context.state!==`closed`&&(this.output.gain.cancelScheduledValues(this.context.currentTime),this.output.gain.setTargetAtTime(b*e,this.context.currentTime,.015))}clear(){for(let e of this.sources){e.onended=null;try{e.stop()}catch{}e.disconnect()}this.sources.clear(),this.nextStartTime=this.context.currentTime,this.hasStartedAudio=!1,this.duck(!1)}async close(){this.stopRingback(),this.clear(),this.output.disconnect(),this.ringbackOutput.disconnect(),this.limiter.disconnect(),this.context.state!==`closed`&&await this.context.close();for(let[e,t]of this.ringbackSources)e.onended=null,e.disconnect(),t.disconnect();this.ringbackSources.clear()}},x=`/assets/pcm-capture-worklet-CpXsv44v.js`,S=16e3;function C(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.min(1,Math.sqrt(t/e.length))}function w(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function me(e,t,n=S){if(t===n)return e;let r=Math.max(1,Math.round(e.length*n/t)),i=new Float32Array(r),a=t/n;for(let t=0;t<r;t+=1){let n=t*a,r=Math.min(e.length-1,Math.floor(n)),o=Math.min(e.length-1,r+1),s=n-r;i[t]=e[r]*(1-s)+e[o]*s}return i}function he(e,t=S){let n=new ArrayBuffer(44+e.length*2),r=new DataView(n),i=(e,t)=>{for(let n=0;n<t.length;n+=1)r.setUint8(e+n,t.charCodeAt(n))};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t+=1){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}function T(e){let t=new ArrayBuffer(e.length*2),n=new DataView(t);for(let t=0;t<e.length;t+=1){let r=Math.max(-1,Math.min(1,e[t]));n.setInt16(t*2,r<0?r*32768:r*32767,!0)}return t}var ge=class{sourceRate;targetRate;pending=new Float32Array;position=0;constructor(e,t=S){if(this.sourceRate=e,this.targetRate=t,e<=0||t<=0)throw Error(`PCM sample rates must be positive`)}push(e){if(e.length===0)return new ArrayBuffer(0);let t=new Float32Array(this.pending.length+e.length);t.set(this.pending),t.set(e,this.pending.length);let n=this.sourceRate/this.targetRate,r=[];for(;this.position+1<t.length;){let e=Math.floor(this.position),i=this.position-e;r.push(t[e]*(1-i)+t[e+1]*i),this.position+=n}let i=Math.min(t.length-1,Math.floor(this.position));return this.pending=t.slice(i),this.position-=i,T(Float32Array.from(r))}flush(){if(this.pending.length===0)return new ArrayBuffer(0);let e=this.pending[Math.min(this.pending.length-1,Math.floor(this.position))];return this.pending=new Float32Array,this.position=0,T(Float32Array.of(e))}},_e=`xopc-pcm-capture`,E=1e3,D=1e4,ve=class e{context;source;node;mutedOutput;options;sampleRate;paused=!1;accepting=!0;processorFailed=!1;stopPromise;flushResolve;constructor(e,t,n,r,i){this.context=e,this.source=t,this.node=n,this.mutedOutput=r,this.options=i,this.sampleRate=e.sampleRate,this.node.port.onmessage=e=>{if(e.data.type===`flushed`){this.flushResolve?.();return}if(!this.accepting||this.paused)return;let t=new Float32Array(e.data.buffer);if(this.options.onSamples(t),this.options.onAudioLevel){let e=C(t);this.options.onAudioLevel({level:e,speaking:e>=(this.options.speechThreshold??.015)})}},this.node.onprocessorerror=()=>{this.processorFailed=!0,this.flushResolve?.()}}static async start(t,n){if(typeof AudioWorkletNode>`u`)throw Error(`PCM audio recording is not supported in this browser`);let r=new AudioContext,i,a,o=new Promise((e,t)=>{a=setTimeout(()=>{t(new DOMException(`PCM audio capture startup timed out`,`TimeoutError`))},D)});try{await Promise.race([r.audioWorklet.addModule(x),o]);let a=r.createMediaStreamSource(t),s=n.frameDurationMs===void 0?void 0:Math.round(r.sampleRate*n.frameDurationMs/1e3),c=new AudioWorkletNode(r,_e,{processorOptions:{frameSamples:s}}),l=r.createGain();return l.gain.value=0,i=new e(r,a,c,l,n),a.connect(c),c.connect(l),l.connect(r.destination),await Promise.race([r.resume(),o]),i}catch(e){throw i?i.cancel():r.close().catch(()=>void 0),e}finally{clearTimeout(a)}}pause(){this.paused=!0}resume(){this.paused=!1}stop(){return this.stopPromise??=this.finish(),this.stopPromise}cancel(){this.accepting&&(this.accepting=!1,this.flushResolve?.(),this.flushResolve=void 0,this.disconnect(),this.context.close().catch(()=>void 0))}async finish(){this.accepting&&(this.processorFailed||await this.flushWorklet(),this.flushResolve=void 0,this.accepting&&(this.accepting=!1,this.disconnect(),await this.context.close().catch(()=>void 0)))}flushWorklet(){return new Promise(e=>{let t=!1,n=()=>{t||(t=!0,globalThis.clearTimeout(r),e())},r=globalThis.setTimeout(n,E);this.flushResolve=n;try{this.node.port.postMessage(`flush`)}catch{n()}})}disconnect(){this.node.port.onmessage=null,this.node.onprocessorerror=null,this.source.disconnect(),this.node.disconnect(),this.mutedOutput.disconnect()}},ye=class e{capture;chunks;stopped=!1;constructor(e,t){this.capture=e,this.chunks=t}static async start(t,n={}){let r=[],i=await ve.start(t,{...n,onSamples:e=>r.push(e)});return new e(i,r)}async stop(){if(this.stopped)return new Blob([],{type:`audio/wav`});this.stopped=!0,await this.capture.stop();let e=me(w(this.chunks),this.capture.sampleRate);return new Blob([he(e)],{type:`audio/wav`})}cancel(){this.stopped||(this.stopped=!0,this.capture.cancel(),this.chunks.length=0)}};function O(e){return e.includes(`ogg`)?`ogg`:e.includes(`mp4`)||e.includes(`m4a`)?`m4a`:e.includes(`mpeg`)||e.includes(`mp3`)?`mp3`:e.includes(`wav`)?`wav`:`webm`}async function k(e,t,i,a){let o=e.type||t||`audio/webm`,s=e.type?e:new Blob([e],{type:o}),c=new FormData;c.append(`audio`,s,`recording.${O(o)}`),a&&c.append(`expectedProvider`,a);let l=await r(n(`/api/voice/transcriptions`),{method:`POST`,body:c,...i?{signal:i}:{}});if(!l.payload)throw Error(`Missing transcription payload`);return l.payload}async function be(e){let t=await r(n(`/api/status`),{signal:e});if(!t.voice?.dictation)throw Error(`Missing dictation status`);return t.voice.dictation}function A(){}typeof window<`u`&&(window.addEventListener(`voice-config-changed`,A),window.addEventListener(`config-reload`,A));var j=null;function xe(e){return j&&j!==e?!1:(j=e,!0)}function M(e){j===e&&(j=null)}function Se(e){if(!(e instanceof Error))return!1;let t=e.body,n=typeof t?.error==`object`?t.error.code:void 0;return n===`VOICE_DISABLED`||n===`PROVIDER_UNAVAILABLE`}function Ce(e){if(!Number.isFinite(e)||e<0)return`0:00`;let t=Math.floor(e%60);return`${Math.floor(e/60)}:${t.toString().padStart(2,`0`)}`}function we(e){return e===`requesting`||e===`connecting`||e===`starting`}async function Te(){if(!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return null}}function Ee(e){return e instanceof DOMException||e instanceof Error?e.name:``}function De(e,t){if(e===`permission`)return`permission`;if(e===`recorder`)return`recorder`;if(e===`session`)return`session`;let n=Ee(t);return n===`NotAllowedError`||n===`SecurityError`?`permission`:`device`}function Oe(e){let{disabled:t,chat:i,onTranscript:o}=e,[s,c]=(0,d.useState)(`idle`),[l,ee]=(0,d.useState)(!1),f=(0,d.useRef)(null),p=(0,d.useRef)(null),ie=(0,d.useRef)(void 0),[ae,oe]=(0,d.useState)(0),[m,h]=(0,d.useState)(0),[g,_]=(0,d.useState)(``),[se,ce]=(0,d.useState)(``),[le,ue]=(0,d.useState)(``),[de,v]=(0,d.useState)([]),[y,b]=(0,d.useState)(null),[x,S]=(0,d.useState)(`idle`),[C,w]=(0,d.useState)(null),[me,he]=(0,d.useState)(!1),T=(0,d.useRef)(!1),[_e,E]=(0,d.useState)(null),[D,O]=(0,d.useState)(null),[A,j]=(0,d.useState)(!1),[Oe,ke]=(0,d.useState)(null),N=(0,d.useRef)(void 0),P=(0,d.useRef)(null),[Ae,je]=(0,d.useState)(`dictation`),Me=(0,d.useRef)(Symbol(`voice-capture`)),F=(0,d.useRef)(`idle`),I=(0,d.useRef)(0),L=(0,d.useRef)(null),Ne=(0,d.useRef)(null),R=(0,d.useRef)(null),Pe=(0,d.useRef)(void 0),Fe=(0,d.useRef)(void 0),Ie=(0,d.useRef)(void 0),z=(0,d.useRef)(null),Le=(0,d.useRef)(null),Re=(0,d.useRef)(null),B=(0,d.useRef)(new Map),V=(0,d.useRef)(!1),ze=(0,d.useRef)(()=>{}),Be=(0,d.useRef)(new Map),H=(0,d.useRef)(null),U=(0,d.useRef)(new Set),[Ve,He]=(0,d.useState)([]),Ue=(0,d.useRef)(!1),W=(0,d.useRef)(null),We=(0,d.useRef)(!1),G=(0,d.useRef)(new Set),Ge=(0,d.useRef)(0),Ke=(0,d.useRef)(6e5),qe=(0,d.useRef)(null),K=(0,d.useRef)(null),Je=(0,d.useRef)(o);Je.current=o;let Ye=(0,d.useRef)(e.onTestAudioPlayed);Ye.current=e.onTestAudioPlayed;let q=(0,d.useCallback)(e=>{F.current=e,c(e)},[]),J=(0,d.useCallback)(()=>{qe.current!=null&&(clearInterval(qe.current),qe.current=null)},[]),Y=(0,d.useCallback)(()=>{Le.current?.getTracks().forEach(e=>e.stop()),Le.current=null},[]),X=(0,d.useCallback)(()=>{M(Me.current),I.current+=1,P.current?.abort(),P.current=null,J(),K.current!==null&&clearTimeout(K.current),K.current=null,z.current?.stopRingback(),Y(),f.current?.cancel(),f.current=null,p.current=null,ie.current=void 0,ee(!1),L.current?.cancel(),L.current=null,Ne.current=null,R.current=null;let e=z.current;z.current=null,e?.close(),Re.current=null,oe(0),h(0),_(``),ce(``),ue(``),S(`idle`),w(null),v([]),b(null),W.current=null,G.current.clear(),T.current=!1,he(!1),j(!1),Be.current.clear(),B.current.clear(),V.current=!1,H.current=null,U.current.clear(),He([])},[Y,J]),Z=(0,d.useCallback)(()=>{X(),q(`idle`)},[X,q]),Xe=(0,d.useCallback)(()=>{R.current?.stop(`user_finished`),Z(),E(null),O(null),ke(null)},[Z]),Q=(0,d.useCallback)(async e=>{if(V.current)return;V.current=!0;let t=I.current,a=e??[...B.current.values()].join(` `).trim();if(Y(),J(),L.current?.cancel(),L.current=null,q(`transcribing`),!a){u(`warning`,i.voiceTranscribeEmpty),Z();return}let o=a;try{let e=await r(n(`/api/voice/transcriptions/refine`),{method:`POST`,body:JSON.stringify({text:a}),signal:AbortSignal.any([P.current.signal,AbortSignal.timeout(15e3)])});e.payload.text.trim()&&(o=e.payload.text)}catch{if(t!==I.current)return;u(`warning`,i.voiceRefinementFailed)}t===I.current&&(Je.current(o),Z())},[Z,i.voiceRefinementFailed,i.voiceTranscribeEmpty,Y,J,q]),Ze=(0,d.useCallback)(async()=>{if(V.current)return;V.current=!0;let e=I.current;J(),q(`transcribing`);try{let t=f.current;if(!p.current&&t){let n=await t.stop();if(e!==I.current)return;p.current=n}if(f.current=null,Y(),e!==I.current)return;let n=p.current;if(!n)throw Error(i.voiceTranscribeEmpty);let r=await k(n,n.type,AbortSignal.any([P.current.signal,AbortSignal.timeout(9e4)]),ie.current);if(e!==I.current)return;V.current=!1,await Q(r.text.trim())}catch(t){if(e!==I.current)return;Y(),V.current=!1,E(t instanceof Error?t.message:i.voiceTranscribeFailed),O(`session`),q(`error`)}},[Q,i.voiceTranscribeEmpty,i.voiceTranscribeFailed,Y,J,q]),Qe=(0,d.useCallback)(e=>{ke(e);let t=F.current;if(!(t===`idle`||t===`error`||V.current)){if(!N.current){if(t===`transcribing`&&e===`input_committed`){Q();return}J(),Y(),L.current?.cancel(),L.current=null,R.current=null,E(i.voiceTranscribeFailed),q(`error`);return}Z()}},[Q,Z,i.voiceTranscribeFailed,Y,J,q]),$e=(0,d.useCallback)(()=>{J(),qe.current=setInterval(()=>{let e=Re.current;if(e===null)return;let t=performance.now()-e;if(oe(Math.max(0,t/1e3)),t>=Ke.current&&F.current===`recording`){if(!N.current){ze.current();return}ke(`session_limit`),R.current?.stop(`user_finished`),Z()}},200)},[Z,J]),$=(0,d.useCallback)(async(e,n,r,o,s=!1,c)=>{if(t||F.current!==`idle`||e===`conversation`&&!r&&!c)return;if(!xe(Me.current)){E(i.callCaptureBusy),e===`dictation`&&u(`error`,i.callCaptureBusy);return}N.current=r;let l=new AbortController;P.current=l,E(null),O(null),ke(null);let d=++I.current,p=()=>d===I.current;je(e),w(e===`conversation`?`preparing`:null),(!s||!Pe.current)&&(Pe.current=crypto.randomUUID()),Fe.current=n,Ie.current=o,ue(``),q(`connecting`);let ae=performance.now(),m=(e,t,n)=>ne(e,l.signal,t,n),g=`permission`;try{if(e===`conversation`){g=`recorder`;let e=new pe;if(z.current=e,await m(e.start(),1e4),!p()){e.close();return}}g=`session`;let t=e===`dictation`?await m(be(l.signal),2e4):null;if(!p())return;if(t?.mode===`unavailable`){let e=Error(i.voiceSttNotConfigured);throw Object.assign(e,{body:{error:{code:`PROVIDER_UNAVAILABLE`}}}),e}let d=t?.mode===`recorded`,ne=e===`conversation`?{mode:n,...o?{naturalBackend:o}:{},...c?{testHiggsVoice:c}:{},conversationId:r}:{},ae=d?[]:await m(fe.preflight({purpose:e,...ne,signal:l.signal}),2e4),se=!1;if(!p())return;g=`permission`;let le=window.electronAPI?.system,de=await m(Te(),5e3);if(!p()||!we(F.current))return;if(le&&de!==`granted`){q(`requesting`);let e=await m(le.requestMicrophone(),6e4);if(!p())return;let t=window.electronAPI?.platform===`darwin`&&e.status!==`granted`;if(e.status===`denied`||t)throw Error(`Microphone permission denied`)}else!le&&de!==`granted`&&q(`requesting`);if(!p()||!we(F.current))return;q(`starting`),window.dispatchEvent(new Event(`xopc-voice-recording-start`)),g=`media`;let y=await m(navigator.mediaDevices.getUserMedia({audio:te()}),15e3,e=>e.getTracks().forEach(e=>e.stop()));if(!p()||!we(F.current)){y.getTracks().forEach(e=>e.stop());return}if(Le.current=y,d){g=`recorder`;let e=await m(ye.start(y,{onAudioLevel:({level:e})=>{p()&&h(Math.min(1,e*8))}}),15e3,e=>e.cancel());if(!p()){e.cancel();return}f.current=e,ie.current=t.provider,ee(!0),Ke.current=6e5,Re.current=performance.now(),oe(0),q(`recording`),$e();return}e===`conversation`&&(w(`dialing`),z.current?.startRingback(),K.current=setTimeout(()=>{p()&&(z.current?.stopRingback(),w(`slow`),K.current=null)},12e3)),g=`session`,q(`connecting`),B.current.clear();let x=await m(fe.connect({timingMetrics:ae,logicalCallId:Pe.current,recovery:s,language:a(),purpose:e,signal:l.signal,...ne,onEvent:t=>{if(p()&&!((t.type===`input.transcript.delta`||t.type===`input.transcript.final`)&&!re(Be.current,t.payload.utteranceId,t.payload.revision,t.type===`input.transcript.final`))){if(t.type===`input.transcript.delta`&&_(t.payload.text),t.type===`input.transcript.final`){let n=t.payload.text.trim();_(``),ce(n),n&&e===`dictation`&&(B.current.set(t.payload.utteranceId,n),[...B.current.values()].join(` `).length>=2e4&&F.current===`recording`&&ze.current(),ce([...B.current.values()].join(` `)))}if(t.type===`input.speech_started`&&!T.current&&R.current?.session.bargeIn&&H.current&&We.current&&(G.current.size<32&&G.current.add(t.payload.utteranceId),z.current?.duck(!0)),t.type===`input.speech_stopped`&&(W.current=performance.now(),G.current.delete(t.payload.utteranceId)&&G.current.size===0&&z.current?.duck(!1)),t.type===`response.created`){if(H.current){H.current!==t.payload.responseId&&R.current?.cancelResponse(t.payload.responseId);return}H.current=t.payload.responseId,G.current.clear(),z.current?.duck(!1),Ue.current=!1,We.current=!1,Ge.current=0,ue(``),U.current.size||(v([]),b(null)),S(`thinking`)}if(t.type===`task.created`&&(U.current.add(t.payload.taskId),He([...U.current])),t.type===`task.activity`&&U.current.has(t.payload.taskId)){let e={toolCallId:t.payload.toolCallId,toolName:t.payload.toolName,status:t.payload.status};v(t=>[...t.filter(t=>t.toolCallId!==e.toolCallId),e].slice(-8))}if(t.type===`task.done`&&(U.current.delete(t.payload.taskId),He([...U.current]),U.current.size||v([])),t.type===`response.clarification`&&b(t.payload),t.type===`response.text.delta`&&H.current===t.payload.responseId&&(S(`speaking`),ue(e=>e+t.payload.delta)),t.type===`response.audio.started`&&H.current===t.payload.responseId&&S(`speaking`),t.type===`response.done`&&H.current===t.payload.responseId&&(Ue.current=!0,z.current?.hasPendingAudio||(H.current=null,S(`idle`))),t.type===`response.cancelled`&&H.current===t.payload.responseId&&(G.current.clear(),H.current=null,S(`idle`),z.current?.clear()),t.type===`session.error`&&t.payload.recoverable&&t.payload.code===`RESPONSE_FAILED`&&u(`warning`,i.voiceResponseFailed),t.type===`session.error`&&t.payload.recoverable&&t.payload.code===`INPUT_DROPPED`&&u(`warning`,i.voiceInputDropped),t.type===`session.error`&&!t.payload.recoverable){let n=t.payload.code===`PROVIDER_UNAVAILABLE`,r=t.payload.code===`CONTEXT_CHANGED`?i.voiceContextChanged:n?i.voiceSttNotConfigured:t.payload.message;E(r),O(`session`),j(n),e===`dictation`&&u(`error`,r,void 0,n?{href:`/settings/capabilities/models?configure=transcription`}:void 0),R.current?.stop(`surface_closed`),e===`conversation`?X():(J(),Y(),L.current?.cancel(),L.current=null,R.current=null),q(`error`)}}},onAudio:(e,t)=>{if(!p())return;let n=H.current;if(!n||t!==n)return;let r=!We.current,i=W.current;r&&(We.current=!0,W.current!==null&&R.current?.reportMetric(n,`speech_end_to_audio_received`,performance.now()-W.current),W.current=null);let a=z.current?.enqueue(e,()=>{H.current===n&&(Ge.current+=e.byteLength,R.current?.acknowledgeAudio(n,Ge.current),c&&!se&&new Int16Array(e).some(e=>Math.abs(e)>96)&&(se=!0,Ye.current?.()),Ue.current&&!z.current?.hasPendingAudio&&(H.current=null,S(`idle`)))});r&&i!==null&&a!==void 0&&R.current?.reportMetric(n,`speech_end_to_audio_scheduled`,performance.now()-i+a)},onClose:e=>{p()&&Qe(e)}}),2e4,e=>e.stop(`surface_closed`));if(!p()){x.stop(`surface_closed`);return}z.current?.stopRingback(),K.current!==null&&clearTimeout(K.current),K.current=null,R.current=x,Ke.current=x.session.limits.maxSessionMs,g=`recorder`,q(`starting`);let C,me=[],he=e===`conversation`&&y.getAudioTracks()[0]?.getSettings?.().echoCancellation===!0,_e=.005,D=0,k=0,A=!1,xe=0,M=await m(ve.start(y,{frameDurationMs:20,onSamples:e=>{if(!p()||T.current)return;if(!C){me.push(e);return}let t=(Ne.current??C).push(e);t&&x.sendAudio(t)},onAudioLevel:({level:e})=>{if(p()){if(T.current){D=k=0,A=!1;return}if(xe++%2==0&&h(Math.min(1,e*8)),!(!he||!x.session.bargeIn)){if(!H.current||!We.current||!z.current?.hasPendingAudio){e<.02&&(_e+=(e-_e)*.05),D=k=0,A=!1;return}e>=Math.max(.022,_e*3)?(k=0,!A&&++D>=3&&(A=!0,z.current.duckForVoiceOnset())):(D=0,++k>=6&&(A=!1))}}}}),15e3,e=>e.cancel());if(!p()||!we(F.current)){M.cancel(),x.stop(`surface_closed`),y.getTracks().forEach(e=>e.stop());return}if(L.current=M,e===`conversation`&&(await m(z.current.start(),1e4),!p()))return;x.outputReady(),C=new ge(M.sampleRate,x.session.inputFormat.sampleRate),Ne.current=C;for(let e of me)x.sendAudio(C.push(e));Re.current=performance.now(),oe(0),q(`recording`),w(null),$e()}catch(t){if(!p())return;let n=De(g,t);console.error(`[chat:voice] realtime capture start failed`,{stage:g,durationMs:Math.round(performance.now()-ae),kind:n,errorName:Ee(t),errorMessage:t instanceof Error?t.message:String(t)}),R.current?.stop(`surface_closed`),X(),q(n===`session`?`error`:`idle`);let r=n===`session`&&Se(t),a=Ee(t)===`TimeoutError`?g===`session`?i.voiceConnectionTimeout:i.voiceMicrophoneTimeout:n===`permission`?i.voiceMicDenied:n===`device`?i.voiceMicUnavailable:n===`recorder`?i.voiceRecorderFailed:r?i.voiceSttNotConfigured:t instanceof Error?t.message:i.voiceSttNotConfigured;E(a),O(n),j(r),e===`dictation`&&u(`error`,a,void 0,r?{href:`/settings/capabilities/models?configure=transcription`}:void 0)}},[t,Qe,i,X,$e,Y,J,q]),et=(0,d.useCallback)(()=>{if(N.current)return;if(f.current||p.current){Ze();return}if(F.current===`error`&&B.current.size){Q();return}if(F.current!==`recording`)return;q(`transcribing`),J(),Y();let e=L.current,t=I.current;L.current=null,e?.stop().then(()=>{if(t!==I.current)return;let e=Ne.current?.flush();e&&R.current?.sendAudio(e),R.current?.commit()}).catch(()=>{t===I.current&&(u(`error`,i.voiceTranscribeFailed),R.current?.stop(`surface_closed`),X(),q(`error`))})},[Q,Ze,i.voiceTranscribeFailed,X,Y,J,q]);ze.current=et,(0,d.useEffect)(()=>()=>{M(Me.current),I.current+=1,P.current?.abort(),f.current?.cancel(),p.current=null,L.current?.cancel(),R.current?.stop(`surface_closed`),z.current?.close(),K.current!==null&&clearTimeout(K.current),Y(),J()},[Y,J]);let tt=(0,d.useCallback)(()=>{if(F.current===`error`){if(p.current){Ze();return}X(),q(`idle`),$(Ae,Fe.current,N.current,Ie.current,!0)}},[$,Ze,Ae,X,q]),nt=(0,d.useCallback)(()=>$(`dictation`),[$]),rt=(0,d.useCallback)((e,t,n)=>$(`conversation`,t,e,n),[$]),it=(0,d.useCallback)(e=>$(`conversation`,`natural`,void 0,void 0,!1,e),[$]),at=(0,d.useCallback)(()=>{let e=performance.now(),t=H.current;z.current?.clear(),G.current.clear(),H.current=null,S(`idle`),t&&(R.current?.reportMetric(t,`local_stop`,performance.now()-e),R.current?.cancelResponse(t))},[]),ot=(0,d.useCallback)(()=>{let e=!T.current;T.current=e,e&&(G.current.clear(),z.current?.duck(!1)),Le.current?.getAudioTracks().forEach(t=>{t.enabled=!e});let t=L.current,n=R.current;t&&n&&(Ne.current=new ge(t.sampleRate,n.session.inputFormat.sampleRate)),n?.setInputMuted(e),_(``),h(0),z.current?.duck(!1),he(e)},[]);return{phase:s,voiceActive:s!==`idle`,recordedDictation:l,elapsedLabel:Ce(ae),audioLevel:m,partialTranscript:g,finalTranscript:se,responseText:le,activeTaskIds:Ve,cancelTask:e=>{U.current.has(e)&&R.current?.cancelTask(e)},activities:de,clarification:y,dismissClarification:e=>b(t=>t?.requestId===e?null:t),responsePhase:x,callConnectionStage:C,muted:me,error:_e,failureKind:D,settingsRequired:A,endedReason:Oe,mode:Ae,startVoiceInput:nt,startVoiceConversation:rt,startHiggsTest:it,interruptResponse:at,toggleMute:ot,cancelVoiceInput:Xe,confirmVoiceInput:et,retryVoiceInput:tt}}export{ve as a,he as c,fe as d,ee as f,be as i,me as l,xe as n,ge as o,te as p,M as r,C as s,Oe as t,pe as u};
1
+ import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t}from"./vendor-react-BOUWij0V.js";import{i as n,o as r,p as i,r as a}from"./locale-store-Cit_aHqC.js";import{a as o,r as s}from"./voice-CDlC6XMH.js";import{t as c}from"./session-manager-DzSlogQc.js";import{t as l}from"./middleware-Pd0e8Igk.js";import{t as u}from"./composer-notifications-B0IZsy8x.js";var d=e(t(),1),ee=i()(l(e=>({captions:!0,microphoneId:``,setCaptions:t=>e({captions:t}),setMicrophoneId:t=>e({microphoneId:t})}),{name:`xopc-voice-preferences`}));function te(){let e=ee.getState().microphoneId;return{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,...e?{deviceId:{exact:e}}:{}}}function ne(e,t,n,r){return new Promise((i,a)=>{let o=!1,s=(e,n)=>{o||(o=!0,clearTimeout(l),t.removeEventListener(`abort`,c),e===void 0?i(n):a(e))},c=()=>s(t.reason??new DOMException(`Cancelled`,`AbortError`)),l=setTimeout(()=>s(new DOMException(`Voice startup timed out`,`TimeoutError`)),n);e.then(e=>{o?r?.(e):s(void 0,e)},e=>s(e)),t.addEventListener(`abort`,c,{once:!0}),t.aborted&&c()})}function re(e,t,n,r){let i=e.get(t);if(i&&(n<i.revision||i.final&&!r||n===i.revision&&(i.final||!r)))return!1;if(!e.has(t)&&e.size>=256){let t=e.keys().next().value;t!==void 0&&e.delete(t)}return e.set(t,{revision:n,final:r}),!0}var f=32,p=1481592883,ie=3,ae=1,oe=2,m=1,h=64*1024,g=new TextEncoder,_=new TextDecoder(`utf-8`,{fatal:!0});function se(e){let t=g.encode(e.id);if(!t.length||t.length>160||!Number.isInteger(e.connectionEpoch)||e.connectionEpoch<1||e.connectionEpoch>4294967295||!Number.isInteger(e.seq)||e.seq<1||e.seq>4294967295||!Number.isFinite(e.timestampMs)||e.timestampMs<0||e.durationMs!==20||e.flags<0||e.flags>3||!e.audio.length||e.audio.length%2||f+t.length+e.audio.length>h)throw Error(`Invalid voice media frame`);let n=new Uint8Array(f+t.length+e.audio.length),r=new DataView(n.buffer);return r.setUint32(0,p),r.setUint8(4,ie),r.setUint8(5,e.kind),r.setUint8(6,m),r.setUint8(7,e.flags),r.setUint32(8,e.connectionEpoch),r.setUint32(12,e.seq),r.setFloat64(16,e.timestampMs),r.setUint16(24,e.durationMs),r.setUint16(26,t.length),r.setUint32(28,e.audio.length),n.set(t,f),n.set(e.audio,f+t.length),n}function ce(e,t){if(e.length<=f||e.length>h)throw Error(`Invalid voice media frame`);let n=new DataView(e.buffer,e.byteOffset,e.byteLength),r=n.getUint8(5),i=n.getUint32(8),a=n.getUint32(12),o=n.getFloat64(16),s=n.getUint16(24),c=n.getUint16(26),l=n.getUint32(28),u=f+c,d=n.getUint8(7);if(n.getUint32(0)!==p||n.getUint8(4)!==ie||r!==t||n.getUint8(6)!==m||d>3||!i||!a||!Number.isFinite(o)||o<0||s!==20||!c||c>160||!l||l%2||u+l!==e.length)throw Error(`Invalid voice media header`);return{kind:r,connectionEpoch:i,id:_.decode(e.subarray(f,u)),seq:a,timestampMs:o,durationMs:s,flags:d,audio:e.slice(u)}}function le(e){let t=ce(e,oe);return{connectionEpoch:t.connectionEpoch,responseId:t.id,seq:t.seq,mediaTimestampMs:t.timestampMs,durationMs:t.durationMs,audio:t.audio}}function ue(e){return se({kind:ae,connectionEpoch:e.connectionEpoch,id:e.utteranceId,seq:e.audioSeq,timestampMs:e.capturedAtMonotonicMs,durationMs:e.durationMs,flags:!!e.start|(e.end?2:0),audio:e.audio})}var de=class{session;eventSeq=0;audioSeq=0;ready=!1;closed=!1;cancelled=new Set;constructor(e){this.session=e}event(e){if(this.closed)throw Error(`Voice session closed`);if(e.sessionId!==this.session.sessionId||e.seq!==this.eventSeq+1)throw Error(`Invalid voice event sequence`);if(this.eventSeq=e.seq,e.type===`session.ready`){if(this.ready||e.payload.connectionEpoch!==this.session.connectionEpoch||e.payload.purpose!==this.session.purpose||e.payload.inputMode!==this.session.inputMode||e.payload.inputFormat.sampleRate!==this.session.inputFormat.sampleRate||e.payload.mode!==this.session.mode||e.payload.route.engine!==this.session.route.engine)throw Error(`Voice session mismatch`);this.ready=!0}e.type===`response.cancelled`&&this.cancel(e.payload.responseId),e.type===`session.closed`&&(this.ready=!1,this.closed=!0)}audio(e){if(!this.ready||e.connectionEpoch!==this.session.connectionEpoch||e.seq!==this.audioSeq+1)throw Error(`Invalid voice audio sequence`);return this.audioSeq=e.seq,!this.cancelled.has(e.responseId)}cancel(e){if(!this.cancelled.has(e)){if(this.cancelled.size>=1e4)throw Error(`Voice response limit exceeded`);this.cancelled.add(e)}}};function v(e,t){return{protocolVersion:3,messageId:crypto.randomUUID(),type:e,sentAt:Date.now(),payload:t}}function y(e){let t=new URL(n(e));return t.protocol=t.protocol===`https:`?`wss:`:`ws:`,t.toString()}var fe=class e{socket;session;timingMetrics;receive;heartbeatId;inputRemainder=new Uint8Array;utteranceId=crypto.randomUUID();inputSeq=0;constructor(e,t,n=[]){this.socket=e,this.session=t,this.timingMetrics=n,this.receive=new de(t)}static async preflight(e){return e.purpose===`conversation`&&e.conversationId&&await new c().materialize(e.conversationId,`voice`),(await r(n(`/api/voice/realtime/preflight`),{method:`POST`,signal:e.signal,body:JSON.stringify({purpose:e.purpose,mode:e.mode,naturalBackend:e.naturalBackend,testHiggsVoice:e.testHiggsVoice,conversationId:e.conversationId,supportedProtocolVersions:[3],mediaPreferences:[`websocket-pcm`]})})).timingMetrics??[]}static async connect(t){t.signal?.throwIfAborted();let i=await r(n(`/api/voice/realtime/sessions`),{method:`POST`,signal:t.signal,body:JSON.stringify({purpose:t.purpose,...t.language?{language:t.language}:{},...t.purpose===`conversation`&&t.mode!==`natural`&&t.logicalCallId?{openingGreeting:{logicalCallId:t.logicalCallId,initiation:t.recovery?`recovery`:`user`,supportsOutputReady:!0}}:{},...t.mode?{mode:t.mode}:{},...t.naturalBackend?{naturalBackend:t.naturalBackend}:{},...t.testHiggsVoice?{testHiggsVoice:t.testHiggsVoice}:{},...t.conversationId?{conversationId:t.conversationId}:{},supportedProtocolVersions:[3],mediaPreferences:[`websocket-pcm`]})}),a=s.parse(i.payload);t.signal?.throwIfAborted();let c=new WebSocket(y(a.websocketPath));c.binaryType=`arraybuffer`;let l=new e(c,a,t.timingMetrics);return await new Promise((e,n)=>{let r=!1,i,s=e=>{r||(r=!0,i!==void 0&&window.clearTimeout(i),c.close(),n(e))};i=window.setTimeout(()=>s(Error(`Realtime voice connection timed out`)),15e3);let u=()=>{r?c.close():s(Error(`Realtime voice connection cancelled`))};if(t.signal?.addEventListener(`abort`,u,{once:!0}),c.addEventListener(`close`,()=>t.signal?.removeEventListener(`abort`,u),{once:!0}),t.signal?.aborted){u();return}c.onerror=()=>s(Error(`Realtime voice connection failed`)),c.onclose=e=>{r?t.onClose?.(e.reason):s(Error(e.reason||`Realtime voice connection closed`))},c.onopen=()=>{c.send(JSON.stringify(v(`session.start`,{sessionId:a.sessionId,ticket:a.ticket})))},c.onmessage=n=>{if(typeof n.data!=`string`){try{let e=le(new Uint8Array(n.data));l.receive.audio(e)&&t.onAudio?.(e.audio.slice().buffer,e.responseId)}catch{c.close(4400,`Invalid voice audio frame`)}return}try{let c=o(JSON.parse(n.data));if(l.receive.event(c),t.onEvent(c),c.type===`session.ready`&&!r){if(c.payload.connectionEpoch!==a.connectionEpoch||c.payload.mode!==a.mode)throw Error(`Voice session mismatch`);r=!0,window.clearTimeout(i),l.startHeartbeat(c.payload.heartbeatIntervalMs),e()}else c.type===`session.error`&&!c.payload.recoverable&&s(Error(c.payload.message))}catch(e){r?c.close(4400,`Invalid voice protocol frame`):s(e instanceof Error?e:Error(String(e)))}}}),l}outputReady(){this.session.openingGreeting?.accepted&&this.sendControl(`session.output_ready`,{connectionEpoch:this.session.connectionEpoch})}sendAudio(e){if(!e.byteLength||this.socket.readyState!==WebSocket.OPEN)return;let t=new Uint8Array(e),n=new Uint8Array(this.inputRemainder.byteLength+t.byteLength);n.set(this.inputRemainder),n.set(t,this.inputRemainder.byteLength);let r=0;for(;r+640<=n.byteLength;){let e=ue({connectionEpoch:this.session.connectionEpoch,utteranceId:this.utteranceId,audioSeq:++this.inputSeq,capturedAtMonotonicMs:performance.now(),durationMs:20,...this.inputSeq===1?{start:!0}:{},audio:n.slice(r,r+640)});this.socket.send(e.buffer),r+=640}this.inputRemainder=n.slice(r)}reportMetric(e,t,n){t===`speech_end_to_audio_scheduled`&&!this.timingMetrics.includes(t)||this.sendControl(`session.metric`,{responseId:e,metric:t,durationMs:Math.min(6e5,Math.max(0,n))})}setInputMuted(e){this.sendControl(`input.mute`,{muted:e}),this.inputRemainder=new Uint8Array,e||(this.utteranceId=crypto.randomUUID(),this.inputSeq=0)}commit(){this.sendControl(`input.commit`,{})}cancelResponse(e){this.sendControl(`response.stop_playback`,{responseId:e})}cancelTask(e){this.sendControl(`task.cancel`,{taskId:e})}acknowledgeAudio(e,t){this.sendControl(`response.audio.played`,{responseId:e,playedDurationMs:Math.floor(t/48)})}stop(e=`user_finished`){this.stopHeartbeat(),this.socket.readyState===WebSocket.OPEN?this.sendControl(`session.stop`,{reason:e}):this.socket.close()}sendControl(e,t){this.socket.readyState===WebSocket.OPEN&&(e===`response.stop_playback`&&`responseId`in t&&this.receive.cancel(t.responseId),this.socket.send(JSON.stringify(v(e,t))))}startHeartbeat(e){this.stopHeartbeat(),this.heartbeatId=window.setInterval(()=>this.sendControl(`session.ping`,{}),e),this.socket.addEventListener(`close`,()=>this.stopHeartbeat(),{once:!0})}stopHeartbeat(){this.heartbeatId!==void 0&&(window.clearInterval(this.heartbeatId),this.heartbeatId=void 0)}},b=1.7,pe=class{context=new AudioContext({sampleRate:24e3,latencyHint:`interactive`});output=this.context.createGain();ringbackOutput=this.context.createGain();limiter=this.context.createDynamicsCompressor();sources=new Set;ringbackSources=new Map;ringbackDelay=null;ringbackInterval=null;ringbackActive=!1;nextStartTime=0;hasStartedAudio=!1;confirmedSpeech=!1;tentativeDuckTimer;constructor(){this.output.gain.value=b,this.limiter.threshold.value=-6,this.limiter.knee.value=6,this.limiter.ratio.value=12,this.limiter.attack.value=.003,this.limiter.release.value=.12,this.output.connect(this.limiter),this.limiter.connect(this.context.destination),this.ringbackOutput.gain.value=0,this.ringbackOutput.connect(this.context.destination)}async start(){await this.context.resume()}get hasPendingAudio(){return this.sources.size>0}startRingback(){this.stopRingback(),this.context.state!==`closed`&&(this.ringbackActive=!0,this.ringbackDelay=setTimeout(()=>{this.ringbackDelay=null,!(!this.ringbackActive||this.context.state!==`running`)&&(this.ringbackOutput.gain.cancelScheduledValues(this.context.currentTime),this.ringbackOutput.gain.setValueAtTime(.14,this.context.currentTime),this.playRingbackPulse(),this.ringbackInterval=setInterval(()=>this.playRingbackPulse(),3e3))},500))}playRingbackPulse(){if(!this.ringbackActive||this.context.state!==`running`)return;let e=this.context.currentTime;for(let[t,n]of[392,494].entries()){let r=e+t*.4,i=this.context.createOscillator(),a=this.context.createGain();i.type=`sine`,i.frequency.value=n,a.gain.setValueAtTime(0,r),a.gain.linearRampToValueAtTime(.5,r+.04),a.gain.setValueAtTime(.5,r+.18),a.gain.linearRampToValueAtTime(0,r+.28),i.connect(a),a.connect(this.ringbackOutput),this.ringbackSources.set(i,a),i.onended=()=>{this.ringbackSources.delete(i),i.disconnect(),a.disconnect()},i.start(r),i.stop(r+.29)}}stopRingback(){if(this.ringbackActive=!1,this.ringbackDelay!==null&&clearTimeout(this.ringbackDelay),this.ringbackInterval!==null&&clearInterval(this.ringbackInterval),this.ringbackDelay=null,this.ringbackInterval=null,this.context.state!==`closed`){this.ringbackOutput.gain.cancelScheduledValues(this.context.currentTime),this.ringbackOutput.gain.setTargetAtTime(0,this.context.currentTime,.025);for(let[e,t]of this.ringbackSources){t.gain.cancelScheduledValues(this.context.currentTime),t.gain.setTargetAtTime(0,this.context.currentTime,.02);try{e.stop(this.context.currentTime+.12)}catch{}}}}enqueue(e,t,n=24e3){if(e.byteLength<2||this.context.state===`closed`)return;let r=new DataView(e),i=new Float32Array(Math.floor(e.byteLength/2));for(let e=0;e<i.length;e+=1)i[e]=r.getInt16(e*2,!0)/32768;let a=this.context.createBuffer(1,i.length,n);a.copyToChannel(i,0);let o=this.context.createBufferSource();o.buffer=a,o.connect(this.output);let s=this.hasStartedAudio?.015:.02,c=Math.max(this.context.currentTime+s,this.nextStartTime);return o.start(c),this.hasStartedAudio=!0,this.nextStartTime=c+a.duration,this.sources.add(o),o.onended=()=>{this.sources.delete(o)&&(o.disconnect(),t())},Math.max(0,c-this.context.currentTime)*1e3}duck(e){clearTimeout(this.tentativeDuckTimer),this.tentativeDuckTimer=void 0,this.confirmedSpeech=e,this.setOutputGain(e?.15:1)}duckForVoiceOnset(){this.confirmedSpeech||this.tentativeDuckTimer!==void 0||!this.hasPendingAudio||(this.setOutputGain(.55),this.tentativeDuckTimer=setTimeout(()=>{this.tentativeDuckTimer=void 0,this.setOutputGain(1)},280))}setOutputGain(e){this.context.state!==`closed`&&(this.output.gain.cancelScheduledValues(this.context.currentTime),this.output.gain.setTargetAtTime(b*e,this.context.currentTime,.015))}clear(){for(let e of this.sources){e.onended=null;try{e.stop()}catch{}e.disconnect()}this.sources.clear(),this.nextStartTime=this.context.currentTime,this.hasStartedAudio=!1,this.duck(!1)}async close(){this.stopRingback(),this.clear(),this.output.disconnect(),this.ringbackOutput.disconnect(),this.limiter.disconnect(),this.context.state!==`closed`&&await this.context.close();for(let[e,t]of this.ringbackSources)e.onended=null,e.disconnect(),t.disconnect();this.ringbackSources.clear()}},x=`/assets/pcm-capture-worklet-CpXsv44v.js`,S=16e3;function C(e){if(e.length===0)return 0;let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.min(1,Math.sqrt(t/e.length))}function w(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function me(e,t,n=S){if(t===n)return e;let r=Math.max(1,Math.round(e.length*n/t)),i=new Float32Array(r),a=t/n;for(let t=0;t<r;t+=1){let n=t*a,r=Math.min(e.length-1,Math.floor(n)),o=Math.min(e.length-1,r+1),s=n-r;i[t]=e[r]*(1-s)+e[o]*s}return i}function he(e,t=S){let n=new ArrayBuffer(44+e.length*2),r=new DataView(n),i=(e,t)=>{for(let n=0;n<t.length;n+=1)r.setUint8(e+n,t.charCodeAt(n))};i(0,`RIFF`),r.setUint32(4,36+e.length*2,!0),i(8,`WAVE`),i(12,`fmt `),r.setUint32(16,16,!0),r.setUint16(20,1,!0),r.setUint16(22,1,!0),r.setUint32(24,t,!0),r.setUint32(28,t*2,!0),r.setUint16(32,2,!0),r.setUint16(34,16,!0),i(36,`data`),r.setUint32(40,e.length*2,!0);for(let t=0;t<e.length;t+=1){let n=Math.max(-1,Math.min(1,e[t]));r.setInt16(44+t*2,n<0?n*32768:n*32767,!0)}return n}function T(e){let t=new ArrayBuffer(e.length*2),n=new DataView(t);for(let t=0;t<e.length;t+=1){let r=Math.max(-1,Math.min(1,e[t]));n.setInt16(t*2,r<0?r*32768:r*32767,!0)}return t}var ge=class{sourceRate;targetRate;pending=new Float32Array;position=0;constructor(e,t=S){if(this.sourceRate=e,this.targetRate=t,e<=0||t<=0)throw Error(`PCM sample rates must be positive`)}push(e){if(e.length===0)return new ArrayBuffer(0);let t=new Float32Array(this.pending.length+e.length);t.set(this.pending),t.set(e,this.pending.length);let n=this.sourceRate/this.targetRate,r=[];for(;this.position+1<t.length;){let e=Math.floor(this.position),i=this.position-e;r.push(t[e]*(1-i)+t[e+1]*i),this.position+=n}let i=Math.min(t.length-1,Math.floor(this.position));return this.pending=t.slice(i),this.position-=i,T(Float32Array.from(r))}flush(){if(this.pending.length===0)return new ArrayBuffer(0);let e=this.pending[Math.min(this.pending.length-1,Math.floor(this.position))];return this.pending=new Float32Array,this.position=0,T(Float32Array.of(e))}},_e=`xopc-pcm-capture`,E=1e3,D=1e4,ve=class e{context;source;node;mutedOutput;options;sampleRate;paused=!1;accepting=!0;processorFailed=!1;stopPromise;flushResolve;constructor(e,t,n,r,i){this.context=e,this.source=t,this.node=n,this.mutedOutput=r,this.options=i,this.sampleRate=e.sampleRate,this.node.port.onmessage=e=>{if(e.data.type===`flushed`){this.flushResolve?.();return}if(!this.accepting||this.paused)return;let t=new Float32Array(e.data.buffer);if(this.options.onSamples(t),this.options.onAudioLevel){let e=C(t);this.options.onAudioLevel({level:e,speaking:e>=(this.options.speechThreshold??.015)})}},this.node.onprocessorerror=()=>{this.processorFailed=!0,this.flushResolve?.()}}static async start(t,n){if(typeof AudioWorkletNode>`u`)throw Error(`PCM audio recording is not supported in this browser`);let r=new AudioContext,i,a,o=new Promise((e,t)=>{a=setTimeout(()=>{t(new DOMException(`PCM audio capture startup timed out`,`TimeoutError`))},D)});try{await Promise.race([r.audioWorklet.addModule(x),o]);let a=r.createMediaStreamSource(t),s=n.frameDurationMs===void 0?void 0:Math.round(r.sampleRate*n.frameDurationMs/1e3),c=new AudioWorkletNode(r,_e,{processorOptions:{frameSamples:s}}),l=r.createGain();return l.gain.value=0,i=new e(r,a,c,l,n),a.connect(c),c.connect(l),l.connect(r.destination),await Promise.race([r.resume(),o]),i}catch(e){throw i?i.cancel():r.close().catch(()=>void 0),e}finally{clearTimeout(a)}}pause(){this.paused=!0}resume(){this.paused=!1}stop(){return this.stopPromise??=this.finish(),this.stopPromise}cancel(){this.accepting&&(this.accepting=!1,this.flushResolve?.(),this.flushResolve=void 0,this.disconnect(),this.context.close().catch(()=>void 0))}async finish(){this.accepting&&(this.processorFailed||await this.flushWorklet(),this.flushResolve=void 0,this.accepting&&(this.accepting=!1,this.disconnect(),await this.context.close().catch(()=>void 0)))}flushWorklet(){return new Promise(e=>{let t=!1,n=()=>{t||(t=!0,globalThis.clearTimeout(r),e())},r=globalThis.setTimeout(n,E);this.flushResolve=n;try{this.node.port.postMessage(`flush`)}catch{n()}})}disconnect(){this.node.port.onmessage=null,this.node.onprocessorerror=null,this.source.disconnect(),this.node.disconnect(),this.mutedOutput.disconnect()}},ye=class e{capture;chunks;stopped=!1;constructor(e,t){this.capture=e,this.chunks=t}static async start(t,n={}){let r=[],i=await ve.start(t,{...n,onSamples:e=>r.push(e)});return new e(i,r)}async stop(){if(this.stopped)return new Blob([],{type:`audio/wav`});this.stopped=!0,await this.capture.stop();let e=me(w(this.chunks),this.capture.sampleRate);return new Blob([he(e)],{type:`audio/wav`})}cancel(){this.stopped||(this.stopped=!0,this.capture.cancel(),this.chunks.length=0)}};function O(e){return e.includes(`ogg`)?`ogg`:e.includes(`mp4`)||e.includes(`m4a`)?`m4a`:e.includes(`mpeg`)||e.includes(`mp3`)?`mp3`:e.includes(`wav`)?`wav`:`webm`}async function k(e,t,i,a){let o=e.type||t||`audio/webm`,s=e.type?e:new Blob([e],{type:o}),c=new FormData;c.append(`audio`,s,`recording.${O(o)}`),a&&c.append(`expectedProvider`,a);let l=await r(n(`/api/voice/transcriptions`),{method:`POST`,body:c,...i?{signal:i}:{}});if(!l.payload)throw Error(`Missing transcription payload`);return l.payload}async function be(e){let t=await r(n(`/api/status`),{signal:e});if(!t.voice?.dictation)throw Error(`Missing dictation status`);return t.voice.dictation}function A(){}typeof window<`u`&&(window.addEventListener(`voice-config-changed`,A),window.addEventListener(`config-reload`,A));var j=null;function xe(e){return j&&j!==e?!1:(j=e,!0)}function M(e){j===e&&(j=null)}function Se(e){if(!(e instanceof Error))return!1;let t=e.body,n=typeof t?.error==`object`?t.error.code:void 0;return n===`VOICE_DISABLED`||n===`PROVIDER_UNAVAILABLE`}function Ce(e){if(!Number.isFinite(e)||e<0)return`0:00`;let t=Math.floor(e%60);return`${Math.floor(e/60)}:${t.toString().padStart(2,`0`)}`}function we(e){return e===`requesting`||e===`connecting`||e===`starting`}async function Te(){if(!navigator.permissions?.query)return null;try{return(await navigator.permissions.query({name:`microphone`})).state}catch{return null}}function Ee(e){return e instanceof DOMException||e instanceof Error?e.name:``}function De(e,t){if(e===`permission`)return`permission`;if(e===`recorder`)return`recorder`;if(e===`session`)return`session`;let n=Ee(t);return n===`NotAllowedError`||n===`SecurityError`?`permission`:`device`}function Oe(e){let{disabled:t,chat:i,onTranscript:o}=e,[s,c]=(0,d.useState)(`idle`),[l,ee]=(0,d.useState)(!1),f=(0,d.useRef)(null),p=(0,d.useRef)(null),ie=(0,d.useRef)(void 0),[ae,oe]=(0,d.useState)(0),[m,h]=(0,d.useState)(0),[g,_]=(0,d.useState)(``),[se,ce]=(0,d.useState)(``),[le,ue]=(0,d.useState)(``),[de,v]=(0,d.useState)([]),[y,b]=(0,d.useState)(null),[x,S]=(0,d.useState)(`idle`),[C,w]=(0,d.useState)(null),[me,he]=(0,d.useState)(!1),T=(0,d.useRef)(!1),[_e,E]=(0,d.useState)(null),[D,O]=(0,d.useState)(null),[A,j]=(0,d.useState)(!1),[Oe,ke]=(0,d.useState)(null),N=(0,d.useRef)(void 0),P=(0,d.useRef)(null),[Ae,je]=(0,d.useState)(`dictation`),Me=(0,d.useRef)(Symbol(`voice-capture`)),F=(0,d.useRef)(`idle`),I=(0,d.useRef)(0),L=(0,d.useRef)(null),Ne=(0,d.useRef)(null),R=(0,d.useRef)(null),Pe=(0,d.useRef)(void 0),Fe=(0,d.useRef)(void 0),Ie=(0,d.useRef)(void 0),z=(0,d.useRef)(null),Le=(0,d.useRef)(null),Re=(0,d.useRef)(null),B=(0,d.useRef)(new Map),V=(0,d.useRef)(!1),ze=(0,d.useRef)(()=>{}),Be=(0,d.useRef)(new Map),H=(0,d.useRef)(null),U=(0,d.useRef)(new Set),[Ve,He]=(0,d.useState)([]),Ue=(0,d.useRef)(!1),W=(0,d.useRef)(null),We=(0,d.useRef)(!1),G=(0,d.useRef)(new Set),Ge=(0,d.useRef)(0),Ke=(0,d.useRef)(6e5),qe=(0,d.useRef)(null),K=(0,d.useRef)(null),Je=(0,d.useRef)(o);Je.current=o;let Ye=(0,d.useRef)(e.onTestAudioPlayed);Ye.current=e.onTestAudioPlayed;let q=(0,d.useCallback)(e=>{F.current=e,c(e)},[]),J=(0,d.useCallback)(()=>{qe.current!=null&&(clearInterval(qe.current),qe.current=null)},[]),Y=(0,d.useCallback)(()=>{Le.current?.getTracks().forEach(e=>e.stop()),Le.current=null},[]),X=(0,d.useCallback)(()=>{M(Me.current),I.current+=1,P.current?.abort(),P.current=null,J(),K.current!==null&&clearTimeout(K.current),K.current=null,z.current?.stopRingback(),Y(),f.current?.cancel(),f.current=null,p.current=null,ie.current=void 0,ee(!1),L.current?.cancel(),L.current=null,Ne.current=null,R.current=null;let e=z.current;z.current=null,e?.close(),Re.current=null,oe(0),h(0),_(``),ce(``),ue(``),S(`idle`),w(null),v([]),b(null),W.current=null,G.current.clear(),T.current=!1,he(!1),j(!1),Be.current.clear(),B.current.clear(),V.current=!1,H.current=null,U.current.clear(),He([])},[Y,J]),Z=(0,d.useCallback)(()=>{X(),q(`idle`)},[X,q]),Xe=(0,d.useCallback)(()=>{R.current?.stop(`user_finished`),Z(),E(null),O(null),ke(null)},[Z]),Q=(0,d.useCallback)(async e=>{if(V.current)return;V.current=!0;let t=I.current,a=e??[...B.current.values()].join(` `).trim();if(Y(),J(),L.current?.cancel(),L.current=null,q(`transcribing`),!a){u(`warning`,i.voiceTranscribeEmpty),Z();return}let o=a;try{let e=await r(n(`/api/voice/transcriptions/refine`),{method:`POST`,body:JSON.stringify({text:a}),signal:AbortSignal.any([P.current.signal,AbortSignal.timeout(15e3)])});e.payload.text.trim()&&(o=e.payload.text)}catch{if(t!==I.current)return;u(`warning`,i.voiceRefinementFailed)}t===I.current&&(Je.current(o),Z())},[Z,i.voiceRefinementFailed,i.voiceTranscribeEmpty,Y,J,q]),Ze=(0,d.useCallback)(async()=>{if(V.current)return;V.current=!0;let e=I.current;J(),q(`transcribing`);try{let t=f.current;if(!p.current&&t){let n=await t.stop();if(e!==I.current)return;p.current=n}if(f.current=null,Y(),e!==I.current)return;let n=p.current;if(!n)throw Error(i.voiceTranscribeEmpty);let r=await k(n,n.type,AbortSignal.any([P.current.signal,AbortSignal.timeout(9e4)]),ie.current);if(e!==I.current)return;V.current=!1,await Q(r.text.trim())}catch(t){if(e!==I.current)return;Y(),V.current=!1,E(t instanceof Error?t.message:i.voiceTranscribeFailed),O(`session`),q(`error`)}},[Q,i.voiceTranscribeEmpty,i.voiceTranscribeFailed,Y,J,q]),Qe=(0,d.useCallback)(e=>{ke(e);let t=F.current;if(!(t===`idle`||t===`error`||V.current)){if(!N.current){if(t===`transcribing`&&e===`input_committed`){Q();return}J(),Y(),L.current?.cancel(),L.current=null,R.current=null,E(i.voiceTranscribeFailed),q(`error`);return}Z()}},[Q,Z,i.voiceTranscribeFailed,Y,J,q]),$e=(0,d.useCallback)(()=>{J(),qe.current=setInterval(()=>{let e=Re.current;if(e===null)return;let t=performance.now()-e;if(oe(Math.max(0,t/1e3)),t>=Ke.current&&F.current===`recording`){if(!N.current){ze.current();return}ke(`session_limit`),R.current?.stop(`user_finished`),Z()}},200)},[Z,J]),$=(0,d.useCallback)(async(e,n,r,o,s=!1,c)=>{if(t||F.current!==`idle`||e===`conversation`&&!r&&!c)return;if(!xe(Me.current)){E(i.callCaptureBusy),e===`dictation`&&u(`error`,i.callCaptureBusy);return}N.current=r;let l=new AbortController;P.current=l,E(null),O(null),ke(null);let d=++I.current,p=()=>d===I.current;je(e),w(e===`conversation`?`preparing`:null),(!s||!Pe.current)&&(Pe.current=crypto.randomUUID()),Fe.current=n,Ie.current=o,ue(``),q(`connecting`);let ae=performance.now(),m=(e,t,n)=>ne(e,l.signal,t,n),g=`permission`;try{if(e===`conversation`){g=`recorder`;let e=new pe;if(z.current=e,await m(e.start(),1e4),!p()){e.close();return}}g=`session`;let t=e===`dictation`?await m(be(l.signal),2e4):null;if(!p())return;if(t?.mode===`unavailable`){let e=Error(i.voiceSttNotConfigured);throw Object.assign(e,{body:{error:{code:`PROVIDER_UNAVAILABLE`}}}),e}let d=t?.mode===`recorded`,ne=e===`conversation`?{mode:n,...o?{naturalBackend:o}:{},...c?{testHiggsVoice:c}:{},conversationId:r}:{},ae=d?[]:await m(fe.preflight({purpose:e,...ne,signal:l.signal}),2e4),se=!1;if(!p())return;g=`permission`;let le=window.electronAPI?.system,de=await m(Te(),5e3);if(!p()||!we(F.current))return;if(le&&de!==`granted`){q(`requesting`);let e=await m(le.requestMicrophone(),6e4);if(!p())return;let t=window.electronAPI?.platform===`darwin`&&e.status!==`granted`;if(e.status===`denied`||t)throw Error(`Microphone permission denied`)}else!le&&de!==`granted`&&q(`requesting`);if(!p()||!we(F.current))return;q(`starting`),window.dispatchEvent(new Event(`xopc-voice-recording-start`)),g=`media`;let y=await m(navigator.mediaDevices.getUserMedia({audio:te()}),15e3,e=>e.getTracks().forEach(e=>e.stop()));if(!p()||!we(F.current)){y.getTracks().forEach(e=>e.stop());return}if(Le.current=y,d){g=`recorder`;let e=await m(ye.start(y,{onAudioLevel:({level:e})=>{p()&&h(Math.min(1,e*8))}}),15e3,e=>e.cancel());if(!p()){e.cancel();return}f.current=e,ie.current=t.provider,ee(!0),Ke.current=6e5,Re.current=performance.now(),oe(0),q(`recording`),$e();return}e===`conversation`&&(w(`dialing`),z.current?.startRingback(),K.current=setTimeout(()=>{p()&&(z.current?.stopRingback(),w(`slow`),K.current=null)},12e3)),g=`session`,q(`connecting`),B.current.clear();let x=await m(fe.connect({timingMetrics:ae,logicalCallId:Pe.current,recovery:s,language:a(),purpose:e,signal:l.signal,...ne,onEvent:t=>{if(p()&&!((t.type===`input.transcript.delta`||t.type===`input.transcript.final`)&&!re(Be.current,t.payload.utteranceId,t.payload.revision,t.type===`input.transcript.final`))){if(t.type===`input.transcript.delta`&&_(t.payload.text),t.type===`input.transcript.final`){let n=t.payload.text.trim();_(``),ce(n),n&&e===`dictation`&&(B.current.set(t.payload.utteranceId,n),[...B.current.values()].join(` `).length>=2e4&&F.current===`recording`&&ze.current(),ce([...B.current.values()].join(` `)))}if(t.type===`input.speech_started`&&!T.current&&R.current?.session.bargeIn&&H.current&&We.current&&(G.current.size<32&&G.current.add(t.payload.utteranceId),z.current?.duck(!0)),t.type===`input.speech_stopped`&&(W.current=performance.now(),G.current.delete(t.payload.utteranceId)&&G.current.size===0&&z.current?.duck(!1)),t.type===`response.created`){if(H.current){H.current!==t.payload.responseId&&R.current?.cancelResponse(t.payload.responseId);return}H.current=t.payload.responseId,G.current.clear(),z.current?.duck(!1),Ue.current=!1,We.current=!1,Ge.current=0,ue(``),U.current.size||(v([]),b(null)),S(`thinking`)}if(t.type===`task.created`&&(U.current.add(t.payload.taskId),He([...U.current])),t.type===`task.activity`&&U.current.has(t.payload.taskId)){let e={toolCallId:t.payload.toolCallId,toolName:t.payload.toolName,status:t.payload.status};v(t=>[...t.filter(t=>t.toolCallId!==e.toolCallId),e].slice(-8))}if(t.type===`task.done`&&(U.current.delete(t.payload.taskId),He([...U.current]),U.current.size||v([])),t.type===`response.clarification`&&b(t.payload),t.type===`response.text.delta`&&H.current===t.payload.responseId&&(S(`speaking`),ue(e=>e+t.payload.delta)),t.type===`response.audio.started`&&H.current===t.payload.responseId&&S(`speaking`),t.type===`response.done`&&H.current===t.payload.responseId&&(Ue.current=!0,z.current?.hasPendingAudio||(H.current=null,S(`idle`))),t.type===`response.cancelled`&&H.current===t.payload.responseId&&(G.current.clear(),H.current=null,S(`idle`),z.current?.clear()),t.type===`session.error`&&t.payload.recoverable&&t.payload.code===`RESPONSE_FAILED`&&u(`warning`,i.voiceResponseFailed),t.type===`session.error`&&t.payload.recoverable&&t.payload.code===`INPUT_DROPPED`&&u(`warning`,i.voiceInputDropped),t.type===`session.error`&&!t.payload.recoverable){let n=t.payload.code===`PROVIDER_UNAVAILABLE`,r=t.payload.code===`CONTEXT_CHANGED`?i.voiceContextChanged:n?i.voiceSttNotConfigured:t.payload.message;E(r),O(`session`),j(n),e===`dictation`&&u(`error`,r,void 0,n?{href:`/settings/capabilities/models?configure=transcription`}:void 0),R.current?.stop(`surface_closed`),e===`conversation`?X():(J(),Y(),L.current?.cancel(),L.current=null,R.current=null),q(`error`)}}},onAudio:(e,t)=>{if(!p())return;let n=H.current;if(!n||t!==n)return;let r=!We.current,i=W.current;r&&(We.current=!0,W.current!==null&&R.current?.reportMetric(n,`speech_end_to_audio_received`,performance.now()-W.current),W.current=null);let a=z.current?.enqueue(e,()=>{H.current===n&&(Ge.current+=e.byteLength,R.current?.acknowledgeAudio(n,Ge.current),c&&!se&&new Int16Array(e).some(e=>Math.abs(e)>96)&&(se=!0,Ye.current?.()),Ue.current&&!z.current?.hasPendingAudio&&(H.current=null,S(`idle`)))});r&&i!==null&&a!==void 0&&R.current?.reportMetric(n,`speech_end_to_audio_scheduled`,performance.now()-i+a)},onClose:e=>{p()&&Qe(e)}}),2e4,e=>e.stop(`surface_closed`));if(!p()){x.stop(`surface_closed`);return}z.current?.stopRingback(),K.current!==null&&clearTimeout(K.current),K.current=null,R.current=x,Ke.current=x.session.limits.maxSessionMs,g=`recorder`,q(`starting`);let C,me=[],he=e===`conversation`&&y.getAudioTracks()[0]?.getSettings?.().echoCancellation===!0,_e=.005,D=0,k=0,A=!1,xe=0,M=await m(ve.start(y,{frameDurationMs:20,onSamples:e=>{if(!p()||T.current)return;if(!C){me.push(e);return}let t=(Ne.current??C).push(e);t&&x.sendAudio(t)},onAudioLevel:({level:e})=>{if(p()){if(T.current){D=k=0,A=!1;return}if(xe++%2==0&&h(Math.min(1,e*8)),!(!he||!x.session.bargeIn)){if(!H.current||!We.current||!z.current?.hasPendingAudio){e<.02&&(_e+=(e-_e)*.05),D=k=0,A=!1;return}e>=Math.max(.022,_e*3)?(k=0,!A&&++D>=3&&(A=!0,z.current.duckForVoiceOnset())):(D=0,++k>=6&&(A=!1))}}}}),15e3,e=>e.cancel());if(!p()||!we(F.current)){M.cancel(),x.stop(`surface_closed`),y.getTracks().forEach(e=>e.stop());return}if(L.current=M,e===`conversation`&&(await m(z.current.start(),1e4),!p()))return;x.outputReady(),C=new ge(M.sampleRate,x.session.inputFormat.sampleRate),Ne.current=C;for(let e of me)x.sendAudio(C.push(e));Re.current=performance.now(),oe(0),q(`recording`),w(null),$e()}catch(t){if(!p())return;let n=De(g,t);console.error(`[chat:voice] realtime capture start failed`,{stage:g,durationMs:Math.round(performance.now()-ae),kind:n,errorName:Ee(t),errorMessage:t instanceof Error?t.message:String(t)}),R.current?.stop(`surface_closed`),X(),q(n===`session`?`error`:`idle`);let r=n===`session`&&Se(t),a=Ee(t)===`TimeoutError`?g===`session`?i.voiceConnectionTimeout:i.voiceMicrophoneTimeout:n===`permission`?i.voiceMicDenied:n===`device`?i.voiceMicUnavailable:n===`recorder`?i.voiceRecorderFailed:r?i.voiceSttNotConfigured:t instanceof Error?t.message:i.voiceSttNotConfigured;E(a),O(n),j(r),e===`dictation`&&u(`error`,a,void 0,r?{href:`/settings/capabilities/models?configure=transcription`}:void 0)}},[t,Qe,i,X,$e,Y,J,q]),et=(0,d.useCallback)(()=>{if(N.current)return;if(f.current||p.current){Ze();return}if(F.current===`error`&&B.current.size){Q();return}if(F.current!==`recording`)return;q(`transcribing`),J(),Y();let e=L.current,t=I.current;L.current=null,e?.stop().then(()=>{if(t!==I.current)return;let e=Ne.current?.flush();e&&R.current?.sendAudio(e),R.current?.commit()}).catch(()=>{t===I.current&&(u(`error`,i.voiceTranscribeFailed),R.current?.stop(`surface_closed`),X(),q(`error`))})},[Q,Ze,i.voiceTranscribeFailed,X,Y,J,q]);ze.current=et,(0,d.useEffect)(()=>()=>{M(Me.current),I.current+=1,P.current?.abort(),f.current?.cancel(),p.current=null,L.current?.cancel(),R.current?.stop(`surface_closed`),z.current?.close(),K.current!==null&&clearTimeout(K.current),Y(),J()},[Y,J]);let tt=(0,d.useCallback)(()=>{if(F.current===`error`){if(p.current){Ze();return}X(),q(`idle`),$(Ae,Fe.current,N.current,Ie.current,!0)}},[$,Ze,Ae,X,q]),nt=(0,d.useCallback)(()=>$(`dictation`),[$]),rt=(0,d.useCallback)((e,t,n)=>$(`conversation`,t,e,n),[$]),it=(0,d.useCallback)(e=>$(`conversation`,`natural`,void 0,void 0,!1,e),[$]),at=(0,d.useCallback)(()=>{let e=performance.now(),t=H.current;z.current?.clear(),G.current.clear(),H.current=null,S(`idle`),t&&(R.current?.reportMetric(t,`local_stop`,performance.now()-e),R.current?.cancelResponse(t))},[]),ot=(0,d.useCallback)(()=>{let e=!T.current;T.current=e,e&&(G.current.clear(),z.current?.duck(!1)),Le.current?.getAudioTracks().forEach(t=>{t.enabled=!e});let t=L.current,n=R.current;t&&n&&(Ne.current=new ge(t.sampleRate,n.session.inputFormat.sampleRate)),n?.setInputMuted(e),_(``),h(0),z.current?.duck(!1),he(e)},[]);return{phase:s,voiceActive:s!==`idle`,recordedDictation:l,elapsedLabel:Ce(ae),audioLevel:m,partialTranscript:g,finalTranscript:se,responseText:le,activeTaskIds:Ve,cancelTask:e=>{U.current.has(e)&&R.current?.cancelTask(e)},activities:de,clarification:y,dismissClarification:e=>b(t=>t?.requestId===e?null:t),responsePhase:x,callConnectionStage:C,muted:me,error:_e,failureKind:D,settingsRequired:A,endedReason:Oe,mode:Ae,startVoiceInput:nt,startVoiceConversation:rt,startHiggsTest:it,interruptResponse:at,toggleMute:ot,cancelVoiceInput:Xe,confirmVoiceInput:et,retryVoiceInput:tt}}export{ve as a,he as c,fe as d,ee as f,be as i,me as l,xe as n,ge as o,te as p,M as r,C as s,Oe as t,pe as u};
@@ -1 +1 @@
1
- import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t}from"./vendor-react-BOUWij0V.js";import{i as n,o as r,s as i}from"./workspace-api-g-wCKoQU.js";var a=e(t(),1);function o(e){return e.map(e=>({fileId:e.id,name:e.name,path:e.path,isDirectory:e.isDirectory,children:e.isDirectory?[]:void 0}))}function s(e,t,n){return e.map(e=>e.path===t?{...e,children:n}:e.isDirectory&&e.children?.length?{...e,children:s(e.children,t,n)}:e)}function c(e,t,c){let[l,u]=(0,a.useState)([]),[d,f]=(0,a.useState)(null),[p,m]=(0,a.useState)(!1),[h,g]=(0,a.useState)(null),_=(0,a.useRef)(new Set),v=e.trim(),y=t?.trim()??``,b=c?.trim()??``,x=b?``:y,S=!b&&!y?v:``,C=(0,a.useMemo)(()=>{if(b)return{projectId:b};if(x)return{conversationId:x};if(S)return{agentId:S}},[b,x,S]);return{tree:l,rootResource:d,loading:p,error:h,loadRoot:(0,a.useCallback)(async()=>{m(!0),g(null),_.current.clear();try{let[e,t]=await Promise.all([n(``,C),r(C)]);u(o(e.entries)),f(o([t])[0]??null),_.current.add(``)}catch(e){f(null),g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[C]),loadChildren:(0,a.useCallback)(async e=>{if(!_.current.has(e)){_.current.add(e);try{let t=o(await i(e,C));u(n=>s(n,e,t))}catch{_.current.delete(e)}}},[C]),refreshDirectory:(0,a.useCallback)(async e=>{let t=o(await i(e,C));u(e?n=>s(n,e,t):t),_.current.add(e)},[C]),reset:(0,a.useCallback)(()=>{u([]),f(null),g(null),_.current.clear()},[])}}export{c as t};
1
+ import{i as e}from"./rolldown-runtime-aKtaBQYM.js";import{a as t}from"./vendor-react-BOUWij0V.js";import{i as n,o as r,s as i}from"./workspace-api-CFPK3JR6.js";var a=e(t(),1);function o(e){return e.map(e=>({fileId:e.id,name:e.name,path:e.path,isDirectory:e.isDirectory,children:e.isDirectory?[]:void 0}))}function s(e,t,n){return e.map(e=>e.path===t?{...e,children:n}:e.isDirectory&&e.children?.length?{...e,children:s(e.children,t,n)}:e)}function c(e,t,c){let[l,u]=(0,a.useState)([]),[d,f]=(0,a.useState)(null),[p,m]=(0,a.useState)(!1),[h,g]=(0,a.useState)(null),_=(0,a.useRef)(new Set),v=e.trim(),y=t?.trim()??``,b=c?.trim()??``,x=b?``:y,S=!b&&!y?v:``,C=(0,a.useMemo)(()=>{if(b)return{projectId:b};if(x)return{conversationId:x};if(S)return{agentId:S}},[b,x,S]);return{tree:l,rootResource:d,loading:p,error:h,loadRoot:(0,a.useCallback)(async()=>{m(!0),g(null),_.current.clear();try{let[e,t]=await Promise.all([n(``,C),r(C)]);u(o(e.entries)),f(o([t])[0]??null),_.current.add(``)}catch(e){f(null),g(e instanceof Error?e.message:String(e))}finally{m(!1)}},[C]),loadChildren:(0,a.useCallback)(async e=>{if(!_.current.has(e)){_.current.add(e);try{let t=o(await i(e,C));u(n=>s(n,e,t))}catch{_.current.delete(e)}}},[C]),refreshDirectory:(0,a.useCallback)(async e=>{let t=o(await i(e,C));u(e?n=>s(n,e,t):t),_.current.add(e)},[C]),reset:(0,a.useCallback)(()=>{u([]),f(null),g(null),_.current.clear()},[])}}export{c as t};