agentroam-runtime-darwin-arm64 0.2.0-preview.39 → 0.2.0-preview.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/manifest.json +1 -1
- package/package.json +1 -1
- package/runtime/.next/BUILD_ID +1 -1
- package/runtime/.next/app-build-manifest.json +8 -8
- package/runtime/.next/app-path-routes-manifest.json +1 -1
- package/runtime/.next/build-manifest.json +3 -3
- package/runtime/.next/prerender-manifest.json +1 -1
- package/runtime/.next/required-server-files.json +1 -1
- package/runtime/.next/server/app/_not-found/page.js +1 -1
- package/runtime/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app/_not-found.html +1 -1
- package/runtime/.next/server/app/_not-found.rsc +1 -1
- package/runtime/.next/server/app/api/agent/abort/route.js +1 -1
- package/runtime/.next/server/app/api/agent/answer/route.js +1 -1
- package/runtime/.next/server/app/api/agent/harness/status/route.js +1 -1
- package/runtime/.next/server/app/api/agent/model/route.js +1 -1
- package/runtime/.next/server/app/api/agent/models/route.js +1 -1
- package/runtime/.next/server/app/api/agent/run/route.js +2 -2
- package/runtime/.next/server/app/api/agent/runtime-health/route.js +1 -1
- package/runtime/.next/server/app/api/agent/steer/route.js +1 -1
- package/runtime/.next/server/app/api/agent/stream/route.js +3 -3
- package/runtime/.next/server/app/api/agent-workspaces/[workspaceId]/sessions/route.js +1 -1
- package/runtime/.next/server/app/api/agent-workspaces/route.js +1 -1
- package/runtime/.next/server/app/api/auth/verify/route.js +1 -1
- package/runtime/.next/server/app/api/business/route.js +1 -1
- package/runtime/.next/server/app/api/client-logs/route.js +1 -1
- package/runtime/.next/server/app/api/flow/v1/catalog/route.js +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/[runId]/cancel/route.js +1 -1
- package/runtime/.next/server/app/api/flow/v1/runs/[runId]/events/route.js +2 -2
- package/runtime/.next/server/app/api/flow/v1/runs/route.js +1 -1
- package/runtime/.next/server/app/api/flow-studio/config/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/connect/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/disconnect/route.js +1 -1
- package/runtime/.next/server/app/api/mcp/servers/route.js +1 -1
- package/runtime/.next/server/app/api/memory/[key]/route.js +1 -1
- package/runtime/.next/server/app/api/memory/route.js +1 -1
- package/runtime/.next/server/app/api/plugins/load/route.js +1 -1
- package/runtime/.next/server/app/api/projects/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/projects/check/route.js +1 -1
- package/runtime/.next/server/app/api/projects/directories/route.js +1 -1
- package/runtime/.next/server/app/api/projects/roots/route.js +1 -1
- package/runtime/.next/server/app/api/projects/route.js +1 -1
- package/runtime/.next/server/app/api/push/subscribe/route.js +2 -2
- package/runtime/.next/server/app/api/push/unsubscribe/route.js +2 -2
- package/runtime/.next/server/app/api/push/vapid/route.js +2 -2
- package/runtime/.next/server/app/api/push/vapid.body +1 -1
- package/runtime/.next/server/app/api/remote-tools/register/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/changes/route.js +2 -2
- package/runtime/.next/server/app/api/sessions/[id]/fork/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/fork-at/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/goals/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/handoff/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/query-index/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/release/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/thread-goal/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/[id]/tool-result/route.js +1 -1
- package/runtime/.next/server/app/api/sessions/route.js +1 -1
- package/runtime/.next/server/app/api/settings/route.js +1 -1
- package/runtime/.next/server/app/api/skills/route.js +1 -1
- package/runtime/.next/server/app/api/tool-policies/[policyId]/route.js +1 -1
- package/runtime/.next/server/app/api/tool-policies/route.js +1 -1
- package/runtime/.next/server/app/api/tools/route.js +1 -1
- package/runtime/.next/server/app/api/update/check/route.js +1 -1
- package/runtime/.next/server/app/api/update/install/route.js +1 -1
- package/runtime/.next/server/app/api/update/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/login/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/logout/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/revoke-all/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/setup/route.js +1 -1
- package/runtime/.next/server/app/api/web-auth/status/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/bootstrap/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/device-state/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/history/route.js +1 -1
- package/runtime/.next/server/app/api/web-console/preferences/route.js +1 -1
- package/runtime/.next/server/app/web/page.js +2 -2
- package/runtime/.next/server/app/web/page_client-reference-manifest.js +1 -1
- package/runtime/.next/server/app-paths-manifest.json +28 -28
- package/runtime/.next/server/chunks/1322.js +1 -1
- package/runtime/.next/server/chunks/1773.js +1 -1
- package/runtime/.next/server/chunks/5303.js +1 -1
- package/runtime/.next/server/middleware-build-manifest.js +1 -1
- package/runtime/.next/server/pages/404.html +1 -1
- package/runtime/.next/server/pages/500.html +1 -1
- package/runtime/.next/server/server-reference-manifest.json +1 -1
- package/runtime/.next/static/chunks/app/web/{error-f69dbd3718cb2107.js → error-eea6b6c270ef86cb.js} +1 -1
- package/runtime/.next/static/chunks/app/web/layout-0991128047cc5e14.js +1 -0
- package/runtime/.next/static/chunks/app/web/{page-f9926cbf4c1badd4.js → page-d615bce909fdda0b.js} +1 -1
- package/runtime/.next/static/chunks/{main-app-d527fa0b25a0c755.js → main-app-9aaee005b4835e70.js} +1 -1
- package/runtime/server.js +1 -1
- package/runtime/webapp/dist/assets/{App-COIcZZvf.js → App-Bnv7-jUZ.js} +16 -16
- package/runtime/webapp/dist/assets/{abnfDiagram-VCTEODGH-d4urtMQU.js → abnfDiagram-VCTEODGH-CyHhjdFC.js} +1 -1
- package/runtime/webapp/dist/assets/{arc-DiQEpEJQ.js → arc-YykeV-yA.js} +1 -1
- package/runtime/webapp/dist/assets/{architectureDiagram-5GKGNRK7-CWYKGqND.js → architectureDiagram-5GKGNRK7-CPXGrnO0.js} +1 -1
- package/runtime/webapp/dist/assets/{blockDiagram-I7D4REHJ-J2I0b5Zn.js → blockDiagram-I7D4REHJ-DY5fPlHV.js} +1 -1
- package/runtime/webapp/dist/assets/{c4Diagram-7LVT6UL2-C-0xWeN3.js → c4Diagram-7LVT6UL2-D9IqQaEZ.js} +1 -1
- package/runtime/webapp/dist/assets/channel-DQNFzknQ.js +1 -0
- package/runtime/webapp/dist/assets/{chunk-2Q5K7J3B-CqodmK6L.js → chunk-2Q5K7J3B-Dq03q8Ff.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-5VM5RSS4-DClUnQcr.js → chunk-5VM5RSS4-V40WX1nt.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-F27PBJKO-CpaDg7Bg.js → chunk-F27PBJKO-CiCQWcQf.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-IMKFNOWR-CTIf9EjK.js → chunk-IMKFNOWR-EJT0DATb.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-JWPE2WC7-DKalSWMm.js → chunk-JWPE2WC7-B0T3KRl6.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-POPQ4Y6H-69MmeyRW.js → chunk-POPQ4Y6H-CBoqnL3A.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-SVP7TREG-DCXWXzhU.js → chunk-SVP7TREG-vc6mvklc.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-TICWLB2K-B5nbTEng.js → chunk-TICWLB2K-Co7ACWND.js} +1 -1
- package/runtime/webapp/dist/assets/{chunk-XXDRQBXY-DsJvkUuN.js → chunk-XXDRQBXY-CvByXr6J.js} +1 -1
- package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-DjmQeVYo.js +1 -0
- package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-DjmQeVYo.js +1 -0
- package/runtime/webapp/dist/assets/{codeSyntax-DJH88FPL.js → codeSyntax-CEVVRDzr.js} +1 -1
- package/runtime/webapp/dist/assets/{cose-bilkent-JH36ORCC-BamzQ_e_.js → cose-bilkent-JH36ORCC-B6ijVOa6.js} +1 -1
- package/runtime/webapp/dist/assets/{cynefin-OW5HDTMX-BI_j1tbW.js → cynefin-OW5HDTMX-DNC_aald.js} +1 -1
- package/runtime/webapp/dist/assets/{cynefinDiagram-5FMLGOSQ-DuxMrVM2.js → cynefinDiagram-5FMLGOSQ-DMwAVRmf.js} +1 -1
- package/runtime/webapp/dist/assets/{dagre-GXQ25YYZ-Y9_ne36w.js → dagre-GXQ25YYZ-DtA0NmZw.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-S7CK7UJ4-DIIjO29m.js → diagram-S7CK7UJ4-B7SEmc9A.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-UQ7AKVKN-C4m2VMIy.js → diagram-UQ7AKVKN-CP_Xy1AP.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-VSXAHHWV-Cw5aPZ0o.js → diagram-VSXAHHWV-CMq6cPW9.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-VX7I27RA-W8nmVcOl.js → diagram-VX7I27RA-KIUvVPO4.js} +1 -1
- package/runtime/webapp/dist/assets/{diagram-Z3DM3KII-TksnHlQo.js → diagram-Z3DM3KII-UiMEplzj.js} +1 -1
- package/runtime/webapp/dist/assets/{ebnfDiagram-PWID7BFC-B3WM1b4a.js → ebnfDiagram-PWID7BFC-D221JIeM.js} +1 -1
- package/runtime/webapp/dist/assets/{erDiagram-RLTQ6QDP-BWctPuya.js → erDiagram-RLTQ6QDP-XKInLFA3.js} +1 -1
- package/runtime/webapp/dist/assets/{flowDiagram-HODETNUW-BG5RMrLN.js → flowDiagram-HODETNUW-BeT9GYtM.js} +1 -1
- package/runtime/webapp/dist/assets/{ganttDiagram-EL5Y4UJY-CPcR7Kn_.js → ganttDiagram-EL5Y4UJY-Dk8Uwf7E.js} +1 -1
- package/runtime/webapp/dist/assets/{gitGraphDiagram-WWUBYQGX-Sg6KChEd.js → gitGraphDiagram-WWUBYQGX-DiVf0w01.js} +1 -1
- package/runtime/webapp/dist/assets/{index-tQnPGo1_.js → index-D1I5RKVk.js} +3 -3
- package/runtime/webapp/dist/assets/{infoDiagram-27XIBGKW-BvrtvnrY.js → infoDiagram-27XIBGKW-DpVFXIO9.js} +1 -1
- package/runtime/webapp/dist/assets/{ishikawaDiagram-5VMMS53U-Bz-dZQLJ.js → ishikawaDiagram-5VMMS53U-ChWOHTzh.js} +1 -1
- package/runtime/webapp/dist/assets/{journeyDiagram-3NMN7TZE-Cb4s9jRE.js → journeyDiagram-3NMN7TZE-CTm0xDi4.js} +1 -1
- package/runtime/webapp/dist/assets/{kanban-definition-UXKFOSKX-IjMPUHg9.js → kanban-definition-UXKFOSKX-zVtWbTTX.js} +1 -1
- package/runtime/webapp/dist/assets/{layout-DHjqr0PJ.js → layout-C8tlpprW.js} +1 -1
- package/runtime/webapp/dist/assets/{linear-COctZkFy.js → linear-CArf8t7h.js} +1 -1
- package/runtime/webapp/dist/assets/{mermaid.core-BnonXfHT.js → mermaid.core-BVUH1a8m.js} +5 -5
- package/runtime/webapp/dist/assets/{mindmap-definition-YA3MSWOX-hxBlXJJE.js → mindmap-definition-YA3MSWOX-Cx7RFt-X.js} +1 -1
- package/runtime/webapp/dist/assets/{pegDiagram-XKGWAZYB-D6KJ8Ftm.js → pegDiagram-XKGWAZYB-BvEhVZgX.js} +1 -1
- package/runtime/webapp/dist/assets/{pieDiagram-E7YTZNPT-BzKWZmHN.js → pieDiagram-E7YTZNPT-U0qmhh14.js} +1 -1
- package/runtime/webapp/dist/assets/{quadrantDiagram-AXDQQJYC-ZhiPKt96.js → quadrantDiagram-AXDQQJYC-BbUHWejy.js} +1 -1
- package/runtime/webapp/dist/assets/{railroadDiagram-O6MQD6OU-BtKhiOPG.js → railroadDiagram-O6MQD6OU-SXZBMND2.js} +1 -1
- package/runtime/webapp/dist/assets/{requirementDiagram-BXWQKSXE-OFr_TA8V.js → requirementDiagram-BXWQKSXE-Cv9h1clg.js} +1 -1
- package/runtime/webapp/dist/assets/{sankeyDiagram-P5KCCOFB-qNTDFxAX.js → sankeyDiagram-P5KCCOFB-CSWUhEDJ.js} +1 -1
- package/runtime/webapp/dist/assets/{sequenceDiagram-WJ2MYXX4-B7s5-R4s.js → sequenceDiagram-WJ2MYXX4-Cy7gfOPU.js} +1 -1
- package/runtime/webapp/dist/assets/{sizeCapture-INFHLROL-DdFabbN6.js → sizeCapture-INFHLROL-DEJ8653D.js} +1 -1
- package/runtime/webapp/dist/assets/{stateDiagram-D77RDMKH-CmAN4pX7.js → stateDiagram-D77RDMKH-C9znHj1A.js} +1 -1
- package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-D4PTr_9g.js +1 -0
- package/runtime/webapp/dist/assets/{swimlanes-42K2YHIH-BQlIJAhf.js → swimlanes-42K2YHIH-D-1OGDuC.js} +1 -1
- package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-BnGs6oif.js +8 -0
- package/runtime/webapp/dist/assets/{timeline-definition-24CTP7MA--Y1zJ9mc.js → timeline-definition-24CTP7MA-fmk9SWID.js} +1 -1
- package/runtime/webapp/dist/assets/{vennDiagram-4TSXK5OY-CUn6FScx.js → vennDiagram-4TSXK5OY-CoJrdpIF.js} +1 -1
- package/runtime/webapp/dist/assets/{wardleyDiagram-VM6X3IG4-Bbz-WBd5.js → wardleyDiagram-VM6X3IG4-CQd2ig95.js} +1 -1
- package/runtime/webapp/dist/assets/{web-DzBEnE5q.js → web-CICIlrjx.js} +1 -1
- package/runtime/webapp/dist/assets/{web-harvpkJj.js → web-DdNvGACS.js} +1 -1
- package/runtime/webapp/dist/assets/{xychartDiagram-S5SC5T6Z-RA9edGdQ.js → xychartDiagram-S5SC5T6Z-Slg0Vzat.js} +1 -1
- package/runtime/webapp/dist/index.html +1 -1
- package/runtime/.next/static/chunks/app/web/layout-e0dd41d18df8ee9e.js +0 -1
- package/runtime/webapp/dist/assets/channel-B6S3kcST.js +0 -1
- package/runtime/webapp/dist/assets/classDiagram-ZZMXUADV-CyUA2YaV.js +0 -1
- package/runtime/webapp/dist/assets/classDiagram-v2-VYDZK3BY-CyUA2YaV.js +0 -1
- package/runtime/webapp/dist/assets/stateDiagram-v2-MP3YSRHH-DsxpCqde.js +0 -1
- package/runtime/webapp/dist/assets/swimlanesDiagram-VR7AAH4N-tji3GZVz.js +0 -8
- /package/runtime/.next/static/{BmUH3xLHQfGkG3yzEK37i → rwWTikOeChITsRklIaUDw}/_buildManifest.js +0 -0
- /package/runtime/.next/static/{BmUH3xLHQfGkG3yzEK37i → rwWTikOeChITsRklIaUDw}/_ssgManifest.js +0 -0
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./mermaid.core-
|
|
2
|
-
var ll=t=>{throw TypeError(t)};var Gu=(t,n,r)=>n.has(t)||ll("Cannot "+r);var cl=(t,n,r)=>n.has(t)?ll("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(t):n.set(t,r);var dl=(t,n,r)=>(Gu(t,n,"access private method"),r);import{r as a,R as Ku,j as e,_ as Vc,b as On,d as Gc,B as Qu,i as Vo,O as ul,u as bn,e as Xu,S as Yu,L as Ju}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./mermaid.core-BVUH1a8m.js","./index-D1I5RKVk.js","./index-CtJgsVah.css","./codeSyntax-CEVVRDzr.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var ll=t=>{throw TypeError(t)};var Gu=(t,n,r)=>n.has(t)||ll("Cannot "+r);var cl=(t,n,r)=>n.has(t)?ll("Cannot add the same private member more than once"):n instanceof WeakSet?n.add(t):n.set(t,r);var dl=(t,n,r)=>(Gu(t,n,"access private method"),r);import{r as a,R as Ku,j as e,_ as Vc,b as On,d as Gc,B as Qu,i as Vo,O as ul,u as bn,e as Xu,S as Yu,L as Ju}from"./index-D1I5RKVk.js";/**
|
|
3
3
|
* @license lucide-react v0.468.0 - ISC
|
|
4
4
|
*
|
|
5
5
|
* This source code is licensed under the ISC license.
|
|
@@ -439,10 +439,10 @@ var ll=t=>{throw TypeError(t)};var Gu=(t,n,r)=>n.has(t)||ll("Cannot "+r);var cl=
|
|
|
439
439
|
*
|
|
440
440
|
* This source code is licensed under the ISC license.
|
|
441
441
|
* See the LICENSE file in the root directory of this source tree.
|
|
442
|
-
*/const pd=ie("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);function Fp(t,n){if(Object.is(t,n))return!0;if(typeof t!="object"||t===null||typeof n!="object"||n===null)return!1;if(t instanceof Map&&n instanceof Map){if(t.size!==n.size)return!1;for(const[s,i]of t)if(!Object.is(i,n.get(s)))return!1;return!0}if(t instanceof Set&&n instanceof Set){if(t.size!==n.size)return!1;for(const s of t)if(!n.has(s))return!1;return!0}const r=Object.keys(t);if(r.length!==Object.keys(n).length)return!1;for(const s of r)if(!Object.prototype.hasOwnProperty.call(n,s)||!Object.is(t[s],n[s]))return!1;return!0}const{useRef:Bp}=Ku;function Op(t){const n=Bp();return r=>{const s=t(r);return Fp(n.current,s)?n.current:n.current=s}}function wo(t,n){var r;if((r=t.presentation)!=null&&r.forkPoint)return t.presentation.forkPoint;if(!n.startsWith("runtime:")&&t.id.startsWith("history-message.v1."))return{messageId:t.id}}function $p(t,n){return!t.ctrlKey&&t.deltaY<0&&Math.abs(t.deltaX)<-t.deltaY&&n<=240}class Hp{constructor(){this.origin=null}start(n){this.origin=n.length===1?{clientX:n[0].clientX,clientY:n[0].clientY}:null}reset(){this.origin=null}move(n,r){if(n.length!==1)return this.reset(),!1;if(!this.origin)return!1;const s=n[0].clientX-this.origin.clientX,i=n[0].clientY-this.origin.clientY;return i<48||Math.abs(s)>=i||r>240?!1:(this.reset(),!0)}}const _i={completionEnabled:!0,soundEnabled:!0,notifyWhileForeground:!1};function wl(t,n){const r=Array.from(t.trim());return r.length<=n?r.join(""):`${r.slice(0,n-1).join("")}…`}function Up(t){return{completionEnabled:(t==null?void 0:t.completionEnabled)??_i.completionEnabled,soundEnabled:(t==null?void 0:t.soundEnabled)??_i.soundEnabled,notifyWhileForeground:(t==null?void 0:t.notifyWhileForeground)??_i.notifyWhileForeground}}function qp(t,n){return!n.completionEnabled||t.outcome!=="completed"||t.stale||!t.sessionId||!t.runId?null:{notificationId:`${t.sessionId}:${t.runId}:completed`,sessionId:t.sessionId,runId:t.runId,title:wl(t.title,80)||"任务已完成",body:wl(t.finalText??"",160)||"运行已结束"}}const Vp="m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z",Gp="M75.91 73.628V62.232c0-.96.36-1.68 1.199-2.16l22.912-13.194c3.119-1.8 6.838-2.639 10.676-2.639 14.394 0 23.511 11.157 23.511 23.032 0 .839 0 1.799-.12 2.758l-23.752-13.914c-1.439-.84-2.879-.84-4.318 0L75.91 73.627Zm53.499 44.383v-27.23c0-1.68-.72-2.88-2.159-3.719L97.142 69.55l9.836-5.638c.839-.48 1.559-.48 2.399 0l22.912 13.195c6.598 3.839 11.035 11.995 11.035 19.912 0 9.116-5.397 17.513-13.915 20.992v.001Zm-60.577-23.99-9.836-5.758c-.84-.48-1.2-1.2-1.2-2.16v-26.39c0-12.834 9.837-22.55 23.152-22.55 5.039 0 9.716 1.679 13.676 4.678L70.993 55.516c-1.44.84-2.16 2.039-2.16 3.719v34.787-.002Zm21.173 12.234L75.91 98.339V81.546l14.095-7.917 14.094 7.917v16.793l-14.094 7.916Zm9.056 36.467c-5.038 0-9.716-1.68-13.675-4.678l23.631-13.676c1.439-.839 2.159-2.038 2.159-3.718V85.863l9.956 5.757c.84.48 1.2 1.2 1.2 2.16v26.389c0 12.835-9.957 22.552-23.27 22.552v.001Zm-28.43-26.75L47.72 102.778c-6.599-3.84-11.036-11.996-11.036-19.913 0-9.236 5.518-17.513 14.034-20.992v27.35c0 1.68.72 2.879 2.16 3.718l29.989 17.393-9.837 5.638c-.84.48-1.56.48-2.399 0Zm-1.318 19.673c-13.555 0-23.512-10.196-23.512-22.792 0-.959.12-1.919.24-2.879l23.63 13.675c1.44.84 2.88.84 4.32 0l30.108-17.392v11.395c0 .96-.361 1.68-1.2 2.16l-22.912 13.194c-3.119 1.8-6.837 2.639-10.675 2.639Zm29.748 14.274c14.515 0 26.63-10.316 29.39-23.991 13.434-3.479 22.071-16.074 22.071-28.91 0-8.396-3.598-16.553-10.076-22.43.6-2.52.96-5.039.96-7.557 0-17.153-13.915-29.99-29.989-29.99-3.239 0-6.358.48-9.477 1.56-5.398-5.278-12.835-8.637-20.992-8.637-14.515 0-26.63 10.316-29.39 23.991-13.434 3.48-22.07 16.074-22.07 28.91 0 8.396 3.598 16.553 10.075 22.431-.6 2.519-.96 5.038-.96 7.556 0 17.154 13.915 29.989 29.99 29.989 3.238 0 6.357-.479 9.476-1.559 5.397 5.278 12.835 8.637 20.992 8.637Z";function pa({agentType:t,size:n=16,className:r}){return t==="customer-agent"?e.jsxs("svg",{className:r,"data-agent-icon":t,width:n,height:n,viewBox:"50 48 180 180",fill:"none","aria-hidden":"true",children:[e.jsx("path",{d:"M76 187V90Q76 74 92 74H188Q204 74 204 90V187",stroke:"currentColor",strokeWidth:"18",strokeLinecap:"round"}),e.jsx("path",{d:"m108 116 26 24-26 24m47 0h22M100 207h80",stroke:"currentColor",strokeWidth:"14",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("circle",{cx:"204",cy:"207",r:"11",fill:"currentColor"})]}):t==="codex"?e.jsx("svg",{className:r,"data-agent-icon":t,width:n,height:n,viewBox:"29.487 29.964 121.035 119.954","aria-hidden":"true",children:e.jsx("path",{fill:"currentColor",d:Gp})}):t==="claude-code"?e.jsx("svg",{className:r,"data-agent-icon":t,width:n,height:n,viewBox:"0 0 24 24","aria-hidden":"true",children:e.jsx("path",{fill:"currentColor",d:Vp})}):e.jsx("svg",{className:r,"data-agent-icon":t,width:n,height:n,viewBox:"0 0 24 24","aria-hidden":"true",children:e.jsx("path",{fill:"currentColor",d:"M22 24H2V0h20zM17 4.8H7v14.4h10z",fillRule:"evenodd"})})}let kl=Promise.resolve(),Kp=0;function fd(t,n=!1){const r=kl.then(async()=>{if(t.length>5e4)throw new Error("图表源码过长,请查看源码");const s=(await Vc(async()=>{const{default:o}=await import("./mermaid.core-BnonXfHT.js").then(l=>l.cb);return{default:o}},__vite__mapDeps([0,1,2]),import.meta.url)).default;s.initialize({startOnLoad:!1,securityLevel:"strict",theme:"neutral",suppressErrorRendering:!0,maxTextSize:5e4,maxEdges:500,...n?{htmlLabels:!1,flowchart:{htmlLabels:!1}}:{},secure:["secure","securityLevel","startOnLoad","maxTextSize","maxEdges","suppressErrorRendering",...n?["htmlLabels","flowchart"]:[]]});const i=document.createElement("div");i.style.cssText="position:fixed;left:-100000px;top:0;visibility:hidden;pointer-events:none",document.body.appendChild(i);try{const{svg:o}=await s.render(`agentroam-mermaid-${++Kp}`,t,i);return o}finally{i.remove()}});return kl=r.catch(()=>{}),r}function hd(t){var r;const n=(r=t.match(/<svg\b[^>]*\bviewBox=["']([^"']+)["']/i))==null?void 0:r[1].trim().split(/[\s,]+/).map(Number);return!n||n.length!==4||!n.every(Number.isFinite)||n[2]<=0||n[3]<=0?{width:640,height:480}:{width:n[2],height:n[3]}}function Qp(t,n,r){return Math.max(.001,Math.min(1,Math.max(1,n)/t.width,r===void 0?1:Math.max(1,r)/t.height))}function jl(t,n){return Math.min(4,Math.max(Math.min(.1,n),t))}function Xp(t){const n=Math.min(2,4096/t.width,4096/t.height);return{width:Math.max(1,Math.round(t.width*n)),height:Math.max(1,Math.round(t.height*n))}}async function Yp(t){const n=await fd(t,!0),r=new DOMParser().parseFromString(n,"image/svg+xml");if(r.querySelector("parsererror, foreignObject"))throw new Error("此图包含暂不支持导出的内容,请查看源码。");if([...r.querySelectorAll("image")].some(l=>!String(l.getAttribute("href")??l.getAttribute("xlink:href")??"").startsWith("data:")))throw new Error("此图包含外部图片,暂不能导出 PNG。");const s=Xp(hd(n)),i=r.documentElement;i.setAttribute("xmlns","http://www.w3.org/2000/svg"),i.setAttribute("width",String(s.width)),i.setAttribute("height",String(s.height)),i.style.maxWidth="none",i.style.width=`${s.width}px`,i.style.height=`${s.height}px`;const o=URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(i)],{type:"image/svg+xml;charset=utf-8"}));try{const l=new Image;await new Promise((f,p)=>{l.onload=()=>f(),l.onerror=()=>p(new Error("图表图片转换失败,请重试。")),l.src=o});const d=window.document.createElement("canvas");d.width=s.width,d.height=s.height;const u=d.getContext("2d");if(!u)throw new Error("当前浏览器无法导出图片。");return u.fillStyle="#fff",u.fillRect(0,0,s.width,s.height),u.drawImage(l,0,0,s.width,s.height),await new Promise((f,p)=>{d.toBlob(v=>v?f(v):p(new Error("图片导出失败,请重试。")),"image/png")})}finally{URL.revokeObjectURL(o)}}function Sl({label:t,onClose:n,children:r}){const s=a.useRef(null);return a.useEffect(()=>{var l,d;const i=document.activeElement,o=document.body.style.overflow;return document.body.style.overflow="hidden",(d=(l=s.current)==null?void 0:l.querySelector("button"))==null||d.focus(),()=>{document.body.style.overflow=o,i instanceof HTMLElement&&i.isConnected&&i.focus()}},[]),On.createPortal(e.jsxs("div",{className:"mermaid-dialog","data-tab-swipe-ignore":!0,ref:s,role:"dialog","aria-modal":"true","aria-label":t,onKeyDown:i=>{var u;if(i.key==="Escape"&&(i.stopPropagation(),n()),i.key!=="Tab")return;const o=[...((u=s.current)==null?void 0:u.querySelectorAll('button:not(:disabled), a[href], [tabindex="0"]'))??[]],l=o[0],d=o[o.length-1];i.shiftKey&&document.activeElement===l?(i.preventDefault(),d==null||d.focus()):!i.shiftKey&&document.activeElement===d&&(i.preventDefault(),l==null||l.focus())},children:[e.jsxs("div",{className:"mermaid-dialog-header",children:[e.jsx("strong",{children:t}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":`关闭${t}`,onClick:n,children:e.jsx(Tr,{size:20})})]}),r]}),document.body)}function Jp({svg:t,fullscreen:n,onFullscreen:r,onExport:s,exporting:i}){const o=a.useMemo(()=>hd(t),[t]),l=a.useRef(null),[d,u]=a.useState(o),[f,p]=a.useState(null),v=Qp(o,d.width,n?d.height:void 0),x=f===null?v:jl(f,v),w=a.useRef(x);w.current=x;const j=a.useRef(!1),E=a.useRef(null);a.useLayoutEffect(()=>{const C=l.current;if(!C)return;const k=()=>u({width:Math.max(1,C.clientWidth-24),height:Math.max(1,C.clientHeight-24)});k();const z=new ResizeObserver(k);return z.observe(C),()=>z.disconnect()},[]);const S=a.useCallback((C,k)=>{const z=l.current;if(!z)return;const M=jl(C,v),H=M/w.current,L=k??{x:z.clientWidth/2,y:z.clientHeight/2},T=(z.scrollLeft+L.x)*H-L.x,A=(z.scrollTop+L.y)*H-L.y;w.current=M,p(M),requestAnimationFrame(()=>{z.scrollLeft=T,z.scrollTop=A})},[v]);return a.useEffect(()=>{const C=l.current;if(!C)return;let k=null;const z=A=>Math.hypot(A[0].clientX-A[1].clientX,A[0].clientY-A[1].clientY),M=A=>{j.current=!1,A.touches.length===2&&(k={distance:Math.max(1,z(A.touches)),scale:w.current},j.current=!0)},H=A=>{if(j.current=!0,!k||A.touches.length!==2)return;A.preventDefault();const R=C.getBoundingClientRect();S(k.scale*z(A.touches)/k.distance,{x:(A.touches[0].clientX+A.touches[1].clientX)/2-R.left,y:(A.touches[0].clientY+A.touches[1].clientY)/2-R.top})},L=()=>{k=null},T=A=>{if(!A.ctrlKey&&!A.metaKey)return;A.preventDefault();const R=C.getBoundingClientRect();S(w.current*Math.exp(-A.deltaY*.01),{x:A.clientX-R.left,y:A.clientY-R.top})};return C.addEventListener("touchstart",M,{passive:!0}),C.addEventListener("touchmove",H,{passive:!1}),C.addEventListener("touchend",L),C.addEventListener("touchcancel",L),C.addEventListener("wheel",T,{passive:!1}),()=>{C.removeEventListener("touchstart",M),C.removeEventListener("touchmove",H),C.removeEventListener("touchend",L),C.removeEventListener("touchcancel",L),C.removeEventListener("wheel",T)}},[S]),e.jsxs("div",{className:`mermaid-viewer${n?" mermaid-viewer-fullscreen":""}`,children:[e.jsxs("div",{className:"mermaid-toolbar",role:"toolbar","aria-label":"图表操作",children:[e.jsx("button",{type:"button",className:"mermaid-control","aria-label":"缩小图表",title:"缩小",disabled:x<=Math.min(.1,v),onClick:()=>S(x/1.25),children:e.jsx(pd,{size:18})}),e.jsxs("span",{className:"mermaid-zoom-value","aria-label":"缩放比例",children:[Math.round(x*100),"%"]}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":"放大图表",title:"放大",disabled:x>=4,onClick:()=>S(x*1.25),children:e.jsx(ud,{size:18})}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":"自适应图表",title:"自适应",onClick:()=>{var C;p(null),(C=l.current)==null||C.scrollTo(0,0)},children:e.jsx(da,{size:18})}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":n?"退出图表全屏":"全屏查看图表",title:n?"退出全屏":"全屏",onClick:r,children:n?e.jsx(kp,{size:18}):e.jsx(yp,{size:18})}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":"导出图表 PNG",title:"导出 PNG",disabled:i,onClick:s,children:e.jsx(la,{size:18})})]}),e.jsx("div",{className:"mermaid-block-preview",ref:l,tabIndex:0,"aria-label":"图表预览,可滚动或双指缩放",onPointerDown:C=>{if(C.pointerType!=="mouse"||C.button!==0)return;const k=C.currentTarget;j.current=!1,E.current={x:C.clientX,y:C.clientY,left:k.scrollLeft,top:k.scrollTop}},onPointerMove:C=>{const k=E.current;k&&(Math.hypot(C.clientX-k.x,C.clientY-k.y)>4&&(j.current||C.currentTarget.setPointerCapture(C.pointerId),j.current=!0),C.currentTarget.scrollLeft=k.left-(C.clientX-k.x),C.currentTarget.scrollTop=k.top-(C.clientY-k.y))},onPointerUp:()=>{E.current=null},onPointerCancel:()=>{E.current=null},children:e.jsx("div",{className:"mermaid-diagram-canvas",style:{width:o.width*x,height:o.height*x},role:n?"img":"button","aria-label":n?"Mermaid 图表":"点击全屏查看 Mermaid 图表",tabIndex:n?void 0:0,onClick:()=>{!n&&!j.current&&r()},onKeyDown:C=>{!n&&(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),r())},dangerouslySetInnerHTML:{__html:t}})}),e.jsx("div",{className:"mermaid-viewer-hint",children:i?"正在生成完整 PNG…":n?"双指缩放 · 滑动查看 · 导出完整图片":"点击图表全屏 · 双指缩放"})]})}function Zp({code:t,svg:n}){const r=a.useRef(null),[s,i]=a.useState(!1),[o,l]=a.useState(!1),[d,u]=a.useState(null),[f,p]=a.useState(null),v=a.useRef(0),x=a.useCallback(()=>{i(!1),requestAnimationFrame(()=>{var S,C;return(C=(S=r.current)==null?void 0:S.querySelector('button[aria-label="全屏查看图表"]'))==null?void 0:C.focus()})},[]),w=a.useCallback(()=>u(null),[]);a.useEffect(()=>()=>{v.current++},[t]),a.useEffect(()=>()=>{d&&URL.revokeObjectURL(d)},[d]);const j=async()=>{if(o)return;const S=v.current;l(!0),p(null);try{const C=await Yp(t);S===v.current&&u(URL.createObjectURL(C))}catch(C){S===v.current&&p(C instanceof Error?C.message:"图片导出失败,请重试。")}finally{S===v.current&&l(!1)}},E=e.jsx(Jp,{svg:n,fullscreen:s,onFullscreen:()=>s?x():i(!0),onExport:()=>void j(),exporting:o});return e.jsxs("div",{className:"mermaid-diagram","data-tab-swipe-ignore":!0,ref:r,children:[s?e.jsxs(Sl,{label:"图表全屏",onClose:x,children:[E,f&&e.jsx("div",{className:"mermaid-block-status",role:"alert",children:f})]}):E,!s&&f&&e.jsx("div",{className:"mermaid-block-status",role:"alert",children:f}),d&&e.jsxs(Sl,{label:"导出图表图片",onClose:w,children:[e.jsxs("div",{className:"mermaid-export-actions",children:[e.jsx("span",{children:"手机可长按图片保存,或下载 PNG"}),e.jsx("a",{href:d,download:"mermaid-diagram.png",children:"下载 PNG"})]}),e.jsx("div",{className:"mermaid-export-preview",children:e.jsx("img",{src:d,alt:"完整 Mermaid 图表 PNG"})})]})]})}function ef({code:t,complete:n}){const[r,s]=a.useState(!1),[i,o]=a.useState(null),l=n&&(i==null?void 0:i.code)===t?i:null;a.useEffect(()=>{if(!n||!t.trim())return;let u=!1;const f=setTimeout(()=>{fd(t).then(p=>{u||o({code:t,svg:p})},()=>{u||o({code:t,error:"图表暂时无法渲染,请查看源码。"})})},150);return()=>{u=!0,clearTimeout(f)}},[t,n]);const d=n?t.trim()?(l==null?void 0:l.error)??(l!=null&&l.svg?null:"正在渲染图表…"):"暂无图表内容":"图表生成中…";return e.jsxs("div",{className:"mermaid-block",children:[e.jsxs("div",{className:"mermaid-block-header",children:[e.jsx("span",{children:"Mermaid"}),e.jsx("button",{type:"button","aria-pressed":r,onClick:()=>s(!r),children:r?"图表":"源码"})]}),d&&e.jsx("div",{className:"mermaid-block-status",role:"status",children:d}),r||!(l!=null&&l.svg)?e.jsx("pre",{className:"mermaid-block-source",children:e.jsx("code",{children:t})}):e.jsx(Zp,{code:t,svg:l.svg},t)]})}function tf(t){if(typeof document>"u"||!document.body||typeof document.execCommand!="function")return!1;const n=document.createElement("textarea");n.value=t,n.setAttribute("readonly",""),Object.assign(n.style,{position:"fixed",top:"0",left:"-9999px",width:"1px",height:"1px",fontSize:"16px",opacity:"0",pointerEvents:"none"}),document.body.appendChild(n);try{return n.focus(),n.select(),n.setSelectionRange(0,n.value.length),document.execCommand("copy")}catch{return!1}finally{n.remove()}}async function zi(t){const n=typeof navigator>"u"?void 0:navigator.clipboard;if(typeof(n==null?void 0:n.writeText)=="function"&&(typeof isSecureContext>"u"||isSecureContext))try{return await n.writeText(t),!0}catch{}return tf(t)}const gd=2e5,nf=24,rf=12,sf=80,of=30,af=500,lf=160,cf=1e3,Di=200,df={"/help":"使用帮助","/whoami":"关于我","/works":"项目与作品","/jobs":"求职信息","/timeline":"经历时间线","/contact":"联系方式"};function Qo(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function fs(t,n){if(typeof t!="string")return;const r=t.trim();return r?r.slice(0,n):void 0}function Cl(t,n,r){return Array.isArray(t)?t.slice(0,n).filter(s=>typeof s=="string").map(s=>s.trim().slice(0,r)).filter(Boolean):[]}function uf(t){if(Qo(t)){const n=fs(t.type,Di)??"unknown";if(n==="text"){const r=fs(t.text,gd);if(r){const s=fs(t.tone,Di);return{kind:"text",text:r,...s?{tone:s}:{}}}}return{kind:"unknown",blockType:n,value:t}}return{kind:"unknown",blockType:"unknown",value:t}}function pf(t){if(typeof t.schemaVersion!="number"||!Number.isFinite(t.schemaVersion))return null;const n=fs(t.title,lf);if(!n||!Array.isArray(t.blocks))return null;const r=fs(t.skill,Di),s=fs(t.summary,cf),i=fs(t.generatedAt,Di);return{schemaVersion:t.schemaVersion,title:n,...r?{skill:r}:{},...s?{summary:s}:{},...i?{generatedAt:i}:{},blocks:t.blocks.slice(0,nf).map(uf),suggestions:Cl(t.suggestions,rf,sf),sources:Cl(t.sources,of,af),original:t}}function ff(t,n=!0){const r=t.trim();if(!n||r.length===0||r.length>gd||r.startsWith("```"))return null;let s;try{s=JSON.parse(r)}catch{return null}if(!Qo(s)&&!Array.isArray(s))return null;if(Qo(s)){const i=pf(s);if(i)return{kind:"envelope",raw:r,value:i}}return{kind:"json",raw:r,value:s}}function Il(t){const n=t.trim(),r=df[n.toLowerCase()];if(r)return r;const s=n.match(/^\/project\s+([a-z0-9-]+)$/i);return s?`查看项目:${s[1]}`:n}const hf=40,Rl=8;function gf(t){return Array.isArray(t)?t.map((n,r)=>[String(r),n]):Object.entries(t)}function mf({value:t}){return t===null?e.jsx("span",{className:"json-tree__value json-tree__value--null",children:"null"}):typeof t=="boolean"?e.jsx("span",{className:"json-tree__value json-tree__value--boolean",children:String(t)}):typeof t=="number"?e.jsx("span",{className:"json-tree__value json-tree__value--number",children:t}):e.jsxs("span",{className:"json-tree__value json-tree__value--string",children:[e.jsx("span",{"aria-hidden":"true",children:'"'}),t,e.jsx("span",{"aria-hidden":"true",children:'"'})]})}function fa({value:t,label:n,depth:r=0}){const[s,i]=a.useState(!1);if(t===null||typeof t!="object")return e.jsxs("div",{className:"json-tree__row",children:[n!==void 0&&e.jsx("span",{className:"json-tree__key",children:n}),n!==void 0&&e.jsx("span",{className:"json-tree__separator",children:":"}),e.jsx(mf,{value:t})]});const o=gf(t),l=Array.isArray(t)?`数组 · ${o.length} 项`:`对象 · ${o.length} 项`;if(r>=Rl)return e.jsxs("div",{className:"json-tree__row json-tree__row--limit",children:[n!==void 0&&e.jsx("span",{className:"json-tree__key",children:n}),e.jsxs("span",{className:"json-tree__limit",children:[l,",已折叠至深度 ",Rl]})]});const d=s?o:o.slice(0,hf),u=o.length-d.length;return e.jsxs("details",{className:"json-tree",open:r===0,children:[e.jsxs("summary",{className:"json-tree__summary",children:[n!==void 0&&e.jsx("span",{className:"json-tree__key",children:n}),e.jsx("span",{className:"json-tree__container-label",children:l})]}),e.jsxs("div",{className:"json-tree__children",children:[o.length===0&&e.jsx("div",{className:"json-tree__empty",children:"空"}),d.map(([f,p])=>e.jsx(fa,{value:p,label:f,depth:r+1},f)),u>0&&e.jsxs("button",{type:"button",className:"json-tree__more",onClick:()=>i(!0),children:["显示其余 ",u," 项"]})]})]})}function xf(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}function md({raw:t,onCopyFailed:n}){const r=async()=>{await zi(t)||n==null||n()};return e.jsxs("details",{className:"structured-agent-message__raw",children:[e.jsx("summary",{children:"查看原始 JSON"}),e.jsx("div",{className:"structured-agent-message__raw-toolbar",children:e.jsx("button",{type:"button",title:"复制原始 JSON","aria-label":"复制原始 JSON",onClick:()=>{r()},children:e.jsx(Ni,{size:14,strokeWidth:1.8,"aria-hidden":"true"})})}),e.jsx("pre",{children:xf(t)})]})}function bf({envelope:t,raw:n,renderText:r,suggestionsEnabled:s,onSuggestionSend:i,onCopyFailed:o}){return e.jsxs("section",{className:"structured-agent-message","data-kind":"envelope",children:[e.jsxs("header",{className:"structured-agent-message__header",children:[e.jsx("h3",{className:"structured-agent-message__title",children:t.title}),t.summary&&e.jsx("p",{className:"structured-agent-message__summary",children:t.summary})]}),e.jsx("div",{className:"structured-agent-message__blocks",children:t.blocks.map((l,d)=>l.kind==="text"?e.jsx("div",{className:"structured-agent-message__text","data-tone":l.tone??"body",children:r(l.text)},d):e.jsxs("details",{className:"structured-agent-message__unknown-block",children:[e.jsxs("summary",{children:[l.blockType," 内容"]}),e.jsx(fa,{value:l.value})]},d))}),t.suggestions.length>0&&e.jsx("div",{className:"structured-agent-message__suggestions","aria-label":"继续提问",children:t.suggestions.map(l=>e.jsx("button",{type:"button",className:"structured-agent-suggestion",disabled:!s,title:`发送 ${l}`,"aria-label":`${Il(l)},发送 ${l}`,onClick:()=>i(l),children:Il(l)},l))}),t.sources.length>0&&e.jsxs("details",{className:"structured-agent-message__details",children:[e.jsxs("summary",{children:["参考来源 ",t.sources.length]}),e.jsx("ul",{children:t.sources.map(l=>e.jsx("li",{children:l},l))})]}),e.jsxs("details",{className:"structured-agent-message__details",children:[e.jsx("summary",{children:"消息信息"}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"格式版本"}),e.jsx("dd",{children:t.schemaVersion})]}),t.skill&&e.jsxs("div",{children:[e.jsx("dt",{children:"能力"}),e.jsx("dd",{children:t.skill})]}),t.generatedAt&&e.jsxs("div",{children:[e.jsx("dt",{children:"生成时间"}),e.jsx("dd",{children:t.generatedAt})]})]})]}),e.jsx(md,{raw:n,onCopyFailed:o})]})}function yf({message:t,renderText:n,suggestionsEnabled:r,onSuggestionSend:s,onCopyFailed:i}){return t.kind==="envelope"?e.jsx(bf,{envelope:t.value,raw:t.raw,renderText:n,suggestionsEnabled:r,onSuggestionSend:s,onCopyFailed:i}):e.jsxs("section",{className:"structured-agent-message","data-kind":"json",children:[e.jsxs("div",{className:"structured-agent-message__data-title",children:[e.jsx(sp,{size:15,strokeWidth:1.8,"aria-hidden":"true"}),e.jsx("span",{children:"结构化数据"})]}),e.jsx(fa,{value:t.value}),e.jsx(md,{raw:t.raw,onCopyFailed:i})]})}function vf({text:t,complete:n,renderText:r,suggestionsEnabled:s,onSuggestionSend:i,onCopyFailed:o}){const l=a.useMemo(()=>ff(t,n),[n,t]);return l?e.jsx(yf,{message:l,renderText:r,suggestionsEnabled:s,onSuggestionSend:i,onCopyFailed:o}):e.jsx(e.Fragment,{children:r(t)})}const xd="webapp.nativeAgentRunPrefs.v1",wf=["codex","claude-code","opencode"];function bd(){try{const t=JSON.parse(localStorage.getItem(xd)??"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Wi(t){return wf.includes(t)}function El(t){return Wi(t)?bd()[t]??{}:{}}function Ml(t,n){if(!Wi(t))return;const r=bd();r[t]=n;try{localStorage.setItem(xd,JSON.stringify(r))}catch{}}function kf(t,n,r){var s;return!r||!((s=t.model)!=null&&s.id)||n.has(oi(t.model))?t:{}}function oi(t){return t.providerID?`${t.providerID}/${t.id}`:t.id}function jf(t){const n=t.indexOf("/");return n>0?{providerID:t.slice(0,n),id:t.slice(n+1)}:{id:t}}function Sf(t){var r,s;const n=new Map;for(const i of t){const o=(r=i.providerID)==null?void 0:r.trim(),l=((s=i.providerDisplayName)==null?void 0:s.trim())||o||"其他供应商",d=o||"__other__",u=n.get(d)??{key:d,label:o==="opencode-go"?`${l}(需订阅)`:l,models:[]};u.models.push({...i,optionLabel:i.displayName||i.id}),n.set(d,u)}return[...n.values()]}const yd="context-compaction";function Fi(t,n){const r=t??[],s=r.findIndex(o=>o.itemId===n.itemId&&o.sectionIndex===n.sectionIndex);return(s<0?[...r,{itemId:n.itemId,sectionIndex:n.sectionIndex,text:n.delta}]:r.map((o,l)=>l===s?{...o,text:o.text+n.delta}:o)).sort((o,l)=>o.sectionIndex-l.sectionIndex)}function Al(t){let n=[];for(const r of t)if(r.type==="runtime_progress"){const{type:s,...i}=r;n=vd(n,i)}else r.type==="context_usage"?n=n.filter(s=>s.progressId!==yd):(r.type==="done"||r.type==="turn_aborted"||r.type==="error")&&(n=[]);return n}function vd(t,n){const r=t.findIndex(s=>s.progressId===n.progressId);return r<0?[...t,n]:t.map((s,i)=>i===r?n:s)}function wd(t,n){return[...t].reverse().find(r=>r.toolCallId===n)}function Cf(t){return[...t].reverse().find(n=>!n.toolCallId)}function If(t,n){var i,o;const r=[],s=new Map;for(let l=0;l<t.length;l+=1){const d=t[l];r.push(d);const u=d.role==="user"?(i=d.presentation)==null?void 0:i.executionTrace:void 0,f=u==null?void 0:u.turnId;if(!f)continue;const p=u.segmentIndex??s.get(f)??0;s.set(f,Math.max(s.get(f)??0,p+1));const v=t[l+1];((o=v==null?void 0:v.executionTrace)==null?void 0:o.turnId)===f&&(v.executionTrace.segmentIndex??0)===p?(r.push({...v,executionTrace:{...v.executionTrace,turnId:f,revision:n,segmentIndex:p}}),l+=1):r.push({id:jd(f,p),role:"assistant",content:"",executionTrace:{turnId:f,revision:n,segmentIndex:p},timestamp:d.timestamp})}return r}function Rf(t){var n,r,s,i;return t.role==="assistant"&&!!((n=t.toolCalls)!=null&&n.length||(s=(r=t.presentation)==null?void 0:r.reasoning)!=null&&s.length||((i=t.presentation)==null?void 0:i.agentMessagePhase)==="commentary")}function kd(t,n,r,s){return t.map(i=>{var o;return(o=i.toolCalls)!=null&&o.some(l=>l.id===n)?{...i,toolCalls:i.toolCalls.map(l=>l.id===n?{...l,result:r,isError:s}:l)}:i})}function Ef(t,n,r,s){if(n.type==="text_chunk"){if(!n.text||n.messagePhase!=="commentary")return[...t];const i=n.itemId?`codex-trace:${s}:agent:${n.itemId}`:`codex-live-commentary:${s}`,o=t.findIndex(l=>l.id===i);return o<0?[...t,{id:i,role:"assistant",content:n.text,presentation:{agentMessagePhase:"commentary"},timestamp:r}]:t.map((l,d)=>d===o?{...l,content:l.content+n.text}:l)}if(n.type==="reasoning_summary_delta"){const i=t.findIndex(o=>{var l,d;return(d=(l=o.presentation)==null?void 0:l.reasoning)==null?void 0:d.some(u=>u.itemId===n.itemId)});return i<0?[...t,{id:`codex-live-reasoning:${n.itemId}`,role:"assistant",content:"",presentation:{reasoning:Fi(void 0,n)},timestamp:r}]:t.map((o,l)=>{var d;return l===i?{...o,presentation:{...o.presentation,reasoning:Fi((d=o.presentation)==null?void 0:d.reasoning,n)}}:o})}if(n.type==="tool_call"){const i=t.findIndex(o=>{var l;return(l=o.toolCalls)==null?void 0:l.some(d=>d.id===n.toolCall.id)});return i>=0?t.map((o,l)=>{var d;return l===i?{...o,toolCalls:(d=o.toolCalls)==null?void 0:d.map(u=>u.id===n.toolCall.id?{...u,name:n.toolCall.name,arguments:n.toolCall.arguments}:u)}:o}):[...t,{id:`codex-live-tool:${n.toolCall.id}`,role:"assistant",content:"",toolCalls:[{...n.toolCall}],timestamp:r}]}return t.some(i=>{var o;return(o=i.toolCalls)==null?void 0:o.some(l=>l.id===n.result.toolCallId)})?kd(t,n.result.toolCallId,n.result.content,n.result.isError):[...t]}function Xo(t,n,r,s=Date.now()){var w,j;const i=t.findLastIndex(E=>{var S;return((S=E.executionTrace)==null?void 0:S.turnId)===n&&Mf(E.executionTrace.liveMessages??[],r)}),o=t.findLastIndex(E=>{var S;return((S=E.executionTrace)==null?void 0:S.turnId)===n}),l=t.findLastIndex(E=>E.role==="user"&&!E.isQueued),d=i>=0?i:o>l||o>=0&&!((w=t[l])!=null&&w.isSteered)?o:-1,u=d>=0?((j=t[d].executionTrace)==null?void 0:j.liveMessages)??[]:[],f=Ef(u,r,s,n);if(f.length===0&&u.length===0)return[...t];if(d>=0)return t.map((E,S)=>S===d?{...E,executionTrace:{...E.executionTrace,liveMessages:f}}:E);if(f===u)return[...t];const p=l;if(p<0)return[...t];const v=t.reduce((E,S)=>{var C;return((C=S.executionTrace)==null?void 0:C.turnId)===n?Math.max(E,S.executionTrace.segmentIndex??0):E},-1)+1,x={id:jd(n,v),role:"assistant",content:"",executionTrace:{turnId:n,revision:`live:${n}`,segmentIndex:v,liveMessages:f},timestamp:s};return[...t.slice(0,p+1),x,...t.slice(p+1)]}function jd(t,n){return n===0?`codex-execution-trace:${t}`:`codex-execution-trace:${t}:${n}`}function Mf(t,n){if(n.type==="text_chunk")return n.itemId?t.some(s=>s.id===`codex-trace:${n.turnId}:agent:${n.itemId}`):!1;if(n.type==="reasoning_summary_delta")return t.some(s=>{var i,o;return(o=(i=s.presentation)==null?void 0:i.reasoning)==null?void 0:o.some(l=>l.itemId===n.itemId)});const r=n.type==="tool_call"?n.toolCall.id:n.result.toolCallId;return t.some(s=>{var i;return(i=s.toolCalls)==null?void 0:i.some(o=>o.id===r)})}function Af(t,n){return t.some(s=>{var i,o;return((o=(i=s.presentation)==null?void 0:i.executionTrace)==null?void 0:o.segmentIndex)!==void 0})?t.filter(s=>{var i,o;return((o=(i=s.presentation)==null?void 0:i.executionTrace)==null?void 0:o.segmentIndex)===n}):n===0?[...t]:[]}function Yo(t,n){const r=new Map(t.map(s=>[`${s.itemId}:${s.sectionIndex}`,s]));for(const s of n){const i=`${s.itemId}:${s.sectionIndex}`,o=r.get(i),l=o?s.text.startsWith(o.text)?s.text:o.text.startsWith(s.text)?o.text:s.text:s.text;r.set(i,{...s,text:l})}return[...r.values()]}function Tl(t){var n,r;return[...((n=t.presentation)==null?void 0:n.agentMessagePhase)==="commentary"?[`agent:${t.id}`]:[],...(((r=t.presentation)==null?void 0:r.reasoning)??[]).map(s=>`reasoning:${s.itemId}:${s.sectionIndex}`),...(t.toolCalls??[]).map(s=>`tool:${s.id}`)]}function Tf(t,n){var r,s;return((r=t.presentation)==null?void 0:r.agentMessagePhase)==="commentary"&&((s=n.presentation)==null?void 0:s.agentMessagePhase)==="commentary"&&(t.id.startsWith("codex-live-commentary:")||n.id.startsWith("codex-live-commentary:"))&&(t.content.startsWith(n.content)||n.content.startsWith(t.content))}function Nf(t){var o,l,d,u,f,p,v,x,w,j,E;const n=[],r=new Map,s=new Map,i=new Map;for(const S of t){if(((o=S.presentation)==null?void 0:o.agentMessagePhase)==="commentary"){const L=r.get(S.id);if(L!==void 0){const T=n[L],A=S.content.startsWith(T.content)?S.content:T.content.startsWith(S.content)?T.content:S.content;n[L]={...T,...S,id:T.id,content:A};continue}}const C={...S,toolCalls:S.toolCalls?[]:void 0,presentation:(l=S.presentation)!=null&&l.reasoning?{...S.presentation,reasoning:[]}:S.presentation};for(const L of((d=S.presentation)==null?void 0:d.reasoning)??[]){const T=`${L.itemId}:${L.sectionIndex}`,A=s.get(T);if(A){const R=n[A.messageIndex],$=[...((u=R.presentation)==null?void 0:u.reasoning)??[]],F=$[A.sectionIndex];$[A.sectionIndex]=Yo([F],[L])[0],n[A.messageIndex]={...R,presentation:{...R.presentation,reasoning:$}}}else{const R=C.presentation.reasoning.findIndex($=>$.itemId===L.itemId&&$.sectionIndex===L.sectionIndex);R>=0?C.presentation.reasoning[R]=Yo([C.presentation.reasoning[R]],[L])[0]:C.presentation.reasoning.push(L)}}for(const L of S.toolCalls??[]){const T=i.get(L.id);if(T){const A=n[T.messageIndex],R=[...A.toolCalls??[]];R[T.toolIndex]={...R[T.toolIndex],...L},n[T.messageIndex]={...A,toolCalls:R}}else{const A=C.toolCalls.findIndex(R=>R.id===L.id);A>=0?C.toolCalls[A]={...C.toolCalls[A],...L}:C.toolCalls.push(L)}}const k=((f=C.presentation)==null?void 0:f.agentMessagePhase)==="commentary",z=!!((v=(p=C.presentation)==null?void 0:p.reasoning)!=null&&v.length),M=!!((x=C.toolCalls)!=null&&x.length);if(!k&&!z&&!M)continue;const H=n.length;n.push(C),k&&r.set(C.id,H);for(let L=0;L<(((j=(w=C.presentation)==null?void 0:w.reasoning)==null?void 0:j.length)??0);L+=1){const T=C.presentation.reasoning[L];s.set(`${T.itemId}:${T.sectionIndex}`,{messageIndex:H,sectionIndex:L})}for(let L=0;L<(((E=C.toolCalls)==null?void 0:E.length)??0);L+=1)i.set(C.toolCalls[L].id,{messageIndex:H,toolIndex:L})}return n}function _f(t,n,r){if(t.length<2)return t;const s=new Map;t.forEach((S,C)=>{for(const k of Tl(S))s.set(k,C)});const i=S=>{for(const C of Tl(S)){const k=s.get(C);if(k!==void 0)return k}return t.findIndex(C=>Tf(C,S))},o=S=>{const C=[];for(const k of S){const z=i(k);z<0||C.at(-1)===z||C.push(z)}return C},l=o(n),d=o(r),u=Array.from({length:t.length},()=>new Set),f=Array.from({length:t.length},()=>0),p=S=>{for(let C=1;C<S.length;C+=1){const k=S[C-1],z=S[C];k===z||u[k].has(z)||(u[k].add(z),f[z]+=1)}};p(l),p(d);const v=new Map(l.map((S,C)=>[S,C])),x=new Map(d.map((S,C)=>[S,C])),w=(S,C)=>{const k=v.get(S)??Number.POSITIVE_INFINITY,z=v.get(C)??Number.POSITIVE_INFINITY;if(k!==z)return k-z;const M=x.get(S)??Number.POSITIVE_INFINITY,H=x.get(C)??Number.POSITIVE_INFINITY;return M!==H?M-H:S-C},j=f.flatMap((S,C)=>S===0?[C]:[]).sort(w),E=[];for(;j.length>0;){const S=j.shift();E.push(t[S]);for(const C of u[S])f[C]-=1,f[C]===0&&(j.push(C),j.sort(w))}return E.length===t.length?E:t}function zf(t,n){var s,i,o,l,d;const r=t.map(u=>{var f,p;return{...u,toolCalls:(f=u.toolCalls)==null?void 0:f.map(v=>({...v})),presentation:(p=u.presentation)!=null&&p.reasoning?{...u.presentation,reasoning:[...u.presentation.reasoning]}:u.presentation}});for(const u of n){if(((s=u.presentation)==null?void 0:s.agentMessagePhase)==="commentary"){const p=r.findIndex(v=>{var x;return v.id===u.id||((x=v.presentation)==null?void 0:x.agentMessagePhase)==="commentary"&&(v.id.startsWith("codex-live-commentary:")||u.id.startsWith("codex-live-commentary:"))&&(u.content.startsWith(v.content)||v.content.startsWith(u.content))});if(p<0)r.push(u);else{const v=r[p],x=u.content.startsWith(v.content)?u.content:v.content.startsWith(u.content)?v.content:u.content;r[p]={...v,content:x,presentation:{...v.presentation,agentMessagePhase:"commentary"}}}continue}const f=(i=u.presentation)==null?void 0:i.reasoning;if(f!=null&&f.length){const p=r.findIndex(v=>{var x,w;return(w=(x=v.presentation)==null?void 0:x.reasoning)==null?void 0:w.some(j=>f.some(E=>E.itemId===j.itemId))});if(p>=0){const v=r[p];r[p]={...v,presentation:{...v.presentation,reasoning:Yo(((o=v.presentation)==null?void 0:o.reasoning)??[],f)}}}else r.push(u)}for(const p of u.toolCalls??[]){const v=r.findIndex(x=>{var w;return(w=x.toolCalls)==null?void 0:w.some(j=>j.id===p.id)});if(v>=0){const x=r[v];r[v]={...x,toolCalls:(l=x.toolCalls)==null?void 0:l.map(w=>w.id===p.id?{...w,...p}:w)}}else r.push({...u,id:(((d=u.toolCalls)==null?void 0:d.length)??0)>1?`${u.id}:tool:${p.id}`:u.id,presentation:void 0,toolCalls:[p]})}}return _f(Nf(r),t,n)}function Nl(t){for(let n=t.length-1;n>=0;n--)if(t[n].type==="context_usage"&&t[n].usage)return t[n].usage}function _l(t){var r;const n=new Map;for(const s of t)s.type==="native_subagent_update"&&((r=s.activity)!=null&&r.parentToolCallId)&&n.set(s.activity.parentToolCallId,s.activity);return[...n.values()]}function Lf(t,n,r,s){return s!==void 0&&s!==r?s?n[s]??[]:[]:t}function Sd(t){var n;return!!(t&&t.role==="assistant"&&!((n=t.toolCalls)!=null&&n.length)&&!t.widget&&!t.askUser&&!t.isCompactionSummary&&!t.executionTrace)}function zl(t,n){var r;if(n.role==="assistant"&&((r=n.toolCalls)!=null&&r.length)){const s=t[t.length-1];if(Sd(s))return[...t.slice(0,-1),{...s,content:s.content,toolCalls:n.toolCalls}]}return[...t,n]}function Pf(t,n){if(!n)return t;const r=t[t.length-1];if(Sd(r)){const s=[...t];return s[s.length-1]={...r,content:r.content+n},s}return[...t,{id:crypto.randomUUID(),role:"assistant",content:n,timestamp:Date.now()}]}function Ll(t,n,r,s){return t.map(i=>{if(!i.toolCalls)return i;const o=i.toolCalls.map(l=>l.id===n?{...l,result:r,isError:s}:l);return{...i,toolCalls:o}})}function Pl(t,n,r,s){return t.map(i=>{if(!i.toolCalls)return i;const o=i.toolCalls.map(l=>l.name==="dispatch_agent"&&l.arguments.subSessionId===n?{...l,arguments:{...l.arguments,subAgentStatus:r,subAgentDetail:s}}:l);return{...i,toolCalls:o}})}function Dl(t,n,r){return t.map(s=>{if(!s.toolCalls)return s;const i=s.toolCalls.map(o=>o.name==="dispatch_agent"&&o.arguments.subSessionId===n?{...o,arguments:{...o.arguments,subAgentProgress:(o.arguments.subAgentProgress?o.arguments.subAgentProgress+`
|
|
442
|
+
*/const pd=ie("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);function Fp(t,n){if(Object.is(t,n))return!0;if(typeof t!="object"||t===null||typeof n!="object"||n===null)return!1;if(t instanceof Map&&n instanceof Map){if(t.size!==n.size)return!1;for(const[s,i]of t)if(!Object.is(i,n.get(s)))return!1;return!0}if(t instanceof Set&&n instanceof Set){if(t.size!==n.size)return!1;for(const s of t)if(!n.has(s))return!1;return!0}const r=Object.keys(t);if(r.length!==Object.keys(n).length)return!1;for(const s of r)if(!Object.prototype.hasOwnProperty.call(n,s)||!Object.is(t[s],n[s]))return!1;return!0}const{useRef:Bp}=Ku;function Op(t){const n=Bp();return r=>{const s=t(r);return Fp(n.current,s)?n.current:n.current=s}}function wo(t,n){var r;if((r=t.presentation)!=null&&r.forkPoint)return t.presentation.forkPoint;if(!n.startsWith("runtime:")&&t.id.startsWith("history-message.v1."))return{messageId:t.id}}function $p(t,n){return!t.ctrlKey&&t.deltaY<0&&Math.abs(t.deltaX)<-t.deltaY&&n<=240}class Hp{constructor(){this.origin=null}start(n){this.origin=n.length===1?{clientX:n[0].clientX,clientY:n[0].clientY}:null}reset(){this.origin=null}move(n,r){if(n.length!==1)return this.reset(),!1;if(!this.origin)return!1;const s=n[0].clientX-this.origin.clientX,i=n[0].clientY-this.origin.clientY;return i<48||Math.abs(s)>=i||r>240?!1:(this.reset(),!0)}}const _i={completionEnabled:!0,soundEnabled:!0,notifyWhileForeground:!1};function wl(t,n){const r=Array.from(t.trim());return r.length<=n?r.join(""):`${r.slice(0,n-1).join("")}…`}function Up(t){return{completionEnabled:(t==null?void 0:t.completionEnabled)??_i.completionEnabled,soundEnabled:(t==null?void 0:t.soundEnabled)??_i.soundEnabled,notifyWhileForeground:(t==null?void 0:t.notifyWhileForeground)??_i.notifyWhileForeground}}function qp(t,n){return!n.completionEnabled||t.outcome!=="completed"||t.stale||!t.sessionId||!t.runId?null:{notificationId:`${t.sessionId}:${t.runId}:completed`,sessionId:t.sessionId,runId:t.runId,title:wl(t.title,80)||"任务已完成",body:wl(t.finalText??"",160)||"运行已结束"}}const Vp="m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z",Gp="M75.91 73.628V62.232c0-.96.36-1.68 1.199-2.16l22.912-13.194c3.119-1.8 6.838-2.639 10.676-2.639 14.394 0 23.511 11.157 23.511 23.032 0 .839 0 1.799-.12 2.758l-23.752-13.914c-1.439-.84-2.879-.84-4.318 0L75.91 73.627Zm53.499 44.383v-27.23c0-1.68-.72-2.88-2.159-3.719L97.142 69.55l9.836-5.638c.839-.48 1.559-.48 2.399 0l22.912 13.195c6.598 3.839 11.035 11.995 11.035 19.912 0 9.116-5.397 17.513-13.915 20.992v.001Zm-60.577-23.99-9.836-5.758c-.84-.48-1.2-1.2-1.2-2.16v-26.39c0-12.834 9.837-22.55 23.152-22.55 5.039 0 9.716 1.679 13.676 4.678L70.993 55.516c-1.44.84-2.16 2.039-2.16 3.719v34.787-.002Zm21.173 12.234L75.91 98.339V81.546l14.095-7.917 14.094 7.917v16.793l-14.094 7.916Zm9.056 36.467c-5.038 0-9.716-1.68-13.675-4.678l23.631-13.676c1.439-.839 2.159-2.038 2.159-3.718V85.863l9.956 5.757c.84.48 1.2 1.2 1.2 2.16v26.389c0 12.835-9.957 22.552-23.27 22.552v.001Zm-28.43-26.75L47.72 102.778c-6.599-3.84-11.036-11.996-11.036-19.913 0-9.236 5.518-17.513 14.034-20.992v27.35c0 1.68.72 2.879 2.16 3.718l29.989 17.393-9.837 5.638c-.84.48-1.56.48-2.399 0Zm-1.318 19.673c-13.555 0-23.512-10.196-23.512-22.792 0-.959.12-1.919.24-2.879l23.63 13.675c1.44.84 2.88.84 4.32 0l30.108-17.392v11.395c0 .96-.361 1.68-1.2 2.16l-22.912 13.194c-3.119 1.8-6.837 2.639-10.675 2.639Zm29.748 14.274c14.515 0 26.63-10.316 29.39-23.991 13.434-3.479 22.071-16.074 22.071-28.91 0-8.396-3.598-16.553-10.076-22.43.6-2.52.96-5.039.96-7.557 0-17.153-13.915-29.99-29.989-29.99-3.239 0-6.358.48-9.477 1.56-5.398-5.278-12.835-8.637-20.992-8.637-14.515 0-26.63 10.316-29.39 23.991-13.434 3.48-22.07 16.074-22.07 28.91 0 8.396 3.598 16.553 10.075 22.431-.6 2.519-.96 5.038-.96 7.556 0 17.154 13.915 29.989 29.99 29.989 3.238 0 6.357-.479 9.476-1.559 5.397 5.278 12.835 8.637 20.992 8.637Z";function pa({agentType:t,size:n=16,className:r}){return t==="customer-agent"?e.jsxs("svg",{className:r,"data-agent-icon":t,width:n,height:n,viewBox:"50 48 180 180",fill:"none","aria-hidden":"true",children:[e.jsx("path",{d:"M76 187V90Q76 74 92 74H188Q204 74 204 90V187",stroke:"currentColor",strokeWidth:"18",strokeLinecap:"round"}),e.jsx("path",{d:"m108 116 26 24-26 24m47 0h22M100 207h80",stroke:"currentColor",strokeWidth:"14",strokeLinecap:"round",strokeLinejoin:"round"}),e.jsx("circle",{cx:"204",cy:"207",r:"11",fill:"currentColor"})]}):t==="codex"?e.jsx("svg",{className:r,"data-agent-icon":t,width:n,height:n,viewBox:"29.487 29.964 121.035 119.954","aria-hidden":"true",children:e.jsx("path",{fill:"currentColor",d:Gp})}):t==="claude-code"?e.jsx("svg",{className:r,"data-agent-icon":t,width:n,height:n,viewBox:"0 0 24 24","aria-hidden":"true",children:e.jsx("path",{fill:"currentColor",d:Vp})}):e.jsx("svg",{className:r,"data-agent-icon":t,width:n,height:n,viewBox:"0 0 24 24","aria-hidden":"true",children:e.jsx("path",{fill:"currentColor",d:"M22 24H2V0h20zM17 4.8H7v14.4h10z",fillRule:"evenodd"})})}let kl=Promise.resolve(),Kp=0;function fd(t,n=!1){const r=kl.then(async()=>{if(t.length>5e4)throw new Error("图表源码过长,请查看源码");const s=(await Vc(async()=>{const{default:o}=await import("./mermaid.core-BVUH1a8m.js").then(l=>l.cb);return{default:o}},__vite__mapDeps([0,1,2]),import.meta.url)).default;s.initialize({startOnLoad:!1,securityLevel:"strict",theme:"neutral",suppressErrorRendering:!0,maxTextSize:5e4,maxEdges:500,...n?{htmlLabels:!1,flowchart:{htmlLabels:!1}}:{},secure:["secure","securityLevel","startOnLoad","maxTextSize","maxEdges","suppressErrorRendering",...n?["htmlLabels","flowchart"]:[]]});const i=document.createElement("div");i.style.cssText="position:fixed;left:-100000px;top:0;visibility:hidden;pointer-events:none",document.body.appendChild(i);try{const{svg:o}=await s.render(`agentroam-mermaid-${++Kp}`,t,i);return o}finally{i.remove()}});return kl=r.catch(()=>{}),r}function hd(t){var r;const n=(r=t.match(/<svg\b[^>]*\bviewBox=["']([^"']+)["']/i))==null?void 0:r[1].trim().split(/[\s,]+/).map(Number);return!n||n.length!==4||!n.every(Number.isFinite)||n[2]<=0||n[3]<=0?{width:640,height:480}:{width:n[2],height:n[3]}}function Qp(t,n,r){return Math.max(.001,Math.min(1,Math.max(1,n)/t.width,r===void 0?1:Math.max(1,r)/t.height))}function jl(t,n){return Math.min(4,Math.max(Math.min(.1,n),t))}function Xp(t){const n=Math.min(2,4096/t.width,4096/t.height);return{width:Math.max(1,Math.round(t.width*n)),height:Math.max(1,Math.round(t.height*n))}}async function Yp(t){const n=await fd(t,!0),r=new DOMParser().parseFromString(n,"image/svg+xml");if(r.querySelector("parsererror, foreignObject"))throw new Error("此图包含暂不支持导出的内容,请查看源码。");if([...r.querySelectorAll("image")].some(l=>!String(l.getAttribute("href")??l.getAttribute("xlink:href")??"").startsWith("data:")))throw new Error("此图包含外部图片,暂不能导出 PNG。");const s=Xp(hd(n)),i=r.documentElement;i.setAttribute("xmlns","http://www.w3.org/2000/svg"),i.setAttribute("width",String(s.width)),i.setAttribute("height",String(s.height)),i.style.maxWidth="none",i.style.width=`${s.width}px`,i.style.height=`${s.height}px`;const o=URL.createObjectURL(new Blob([new XMLSerializer().serializeToString(i)],{type:"image/svg+xml;charset=utf-8"}));try{const l=new Image;await new Promise((f,p)=>{l.onload=()=>f(),l.onerror=()=>p(new Error("图表图片转换失败,请重试。")),l.src=o});const d=window.document.createElement("canvas");d.width=s.width,d.height=s.height;const u=d.getContext("2d");if(!u)throw new Error("当前浏览器无法导出图片。");return u.fillStyle="#fff",u.fillRect(0,0,s.width,s.height),u.drawImage(l,0,0,s.width,s.height),await new Promise((f,p)=>{d.toBlob(v=>v?f(v):p(new Error("图片导出失败,请重试。")),"image/png")})}finally{URL.revokeObjectURL(o)}}function Sl({label:t,onClose:n,children:r}){const s=a.useRef(null);return a.useEffect(()=>{var l,d;const i=document.activeElement,o=document.body.style.overflow;return document.body.style.overflow="hidden",(d=(l=s.current)==null?void 0:l.querySelector("button"))==null||d.focus(),()=>{document.body.style.overflow=o,i instanceof HTMLElement&&i.isConnected&&i.focus()}},[]),On.createPortal(e.jsxs("div",{className:"mermaid-dialog","data-tab-swipe-ignore":!0,ref:s,role:"dialog","aria-modal":"true","aria-label":t,onKeyDown:i=>{var u;if(i.key==="Escape"&&(i.stopPropagation(),n()),i.key!=="Tab")return;const o=[...((u=s.current)==null?void 0:u.querySelectorAll('button:not(:disabled), a[href], [tabindex="0"]'))??[]],l=o[0],d=o[o.length-1];i.shiftKey&&document.activeElement===l?(i.preventDefault(),d==null||d.focus()):!i.shiftKey&&document.activeElement===d&&(i.preventDefault(),l==null||l.focus())},children:[e.jsxs("div",{className:"mermaid-dialog-header",children:[e.jsx("strong",{children:t}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":`关闭${t}`,onClick:n,children:e.jsx(Tr,{size:20})})]}),r]}),document.body)}function Jp({svg:t,fullscreen:n,onFullscreen:r,onExport:s,exporting:i}){const o=a.useMemo(()=>hd(t),[t]),l=a.useRef(null),[d,u]=a.useState(o),[f,p]=a.useState(null),v=Qp(o,d.width,n?d.height:void 0),x=f===null?v:jl(f,v),w=a.useRef(x);w.current=x;const j=a.useRef(!1),E=a.useRef(null);a.useLayoutEffect(()=>{const C=l.current;if(!C)return;const k=()=>u({width:Math.max(1,C.clientWidth-24),height:Math.max(1,C.clientHeight-24)});k();const z=new ResizeObserver(k);return z.observe(C),()=>z.disconnect()},[]);const S=a.useCallback((C,k)=>{const z=l.current;if(!z)return;const M=jl(C,v),H=M/w.current,L=k??{x:z.clientWidth/2,y:z.clientHeight/2},T=(z.scrollLeft+L.x)*H-L.x,A=(z.scrollTop+L.y)*H-L.y;w.current=M,p(M),requestAnimationFrame(()=>{z.scrollLeft=T,z.scrollTop=A})},[v]);return a.useEffect(()=>{const C=l.current;if(!C)return;let k=null;const z=A=>Math.hypot(A[0].clientX-A[1].clientX,A[0].clientY-A[1].clientY),M=A=>{j.current=!1,A.touches.length===2&&(k={distance:Math.max(1,z(A.touches)),scale:w.current},j.current=!0)},H=A=>{if(j.current=!0,!k||A.touches.length!==2)return;A.preventDefault();const R=C.getBoundingClientRect();S(k.scale*z(A.touches)/k.distance,{x:(A.touches[0].clientX+A.touches[1].clientX)/2-R.left,y:(A.touches[0].clientY+A.touches[1].clientY)/2-R.top})},L=()=>{k=null},T=A=>{if(!A.ctrlKey&&!A.metaKey)return;A.preventDefault();const R=C.getBoundingClientRect();S(w.current*Math.exp(-A.deltaY*.01),{x:A.clientX-R.left,y:A.clientY-R.top})};return C.addEventListener("touchstart",M,{passive:!0}),C.addEventListener("touchmove",H,{passive:!1}),C.addEventListener("touchend",L),C.addEventListener("touchcancel",L),C.addEventListener("wheel",T,{passive:!1}),()=>{C.removeEventListener("touchstart",M),C.removeEventListener("touchmove",H),C.removeEventListener("touchend",L),C.removeEventListener("touchcancel",L),C.removeEventListener("wheel",T)}},[S]),e.jsxs("div",{className:`mermaid-viewer${n?" mermaid-viewer-fullscreen":""}`,children:[e.jsxs("div",{className:"mermaid-toolbar",role:"toolbar","aria-label":"图表操作",children:[e.jsx("button",{type:"button",className:"mermaid-control","aria-label":"缩小图表",title:"缩小",disabled:x<=Math.min(.1,v),onClick:()=>S(x/1.25),children:e.jsx(pd,{size:18})}),e.jsxs("span",{className:"mermaid-zoom-value","aria-label":"缩放比例",children:[Math.round(x*100),"%"]}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":"放大图表",title:"放大",disabled:x>=4,onClick:()=>S(x*1.25),children:e.jsx(ud,{size:18})}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":"自适应图表",title:"自适应",onClick:()=>{var C;p(null),(C=l.current)==null||C.scrollTo(0,0)},children:e.jsx(da,{size:18})}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":n?"退出图表全屏":"全屏查看图表",title:n?"退出全屏":"全屏",onClick:r,children:n?e.jsx(kp,{size:18}):e.jsx(yp,{size:18})}),e.jsx("button",{type:"button",className:"mermaid-control","aria-label":"导出图表 PNG",title:"导出 PNG",disabled:i,onClick:s,children:e.jsx(la,{size:18})})]}),e.jsx("div",{className:"mermaid-block-preview",ref:l,tabIndex:0,"aria-label":"图表预览,可滚动或双指缩放",onPointerDown:C=>{if(C.pointerType!=="mouse"||C.button!==0)return;const k=C.currentTarget;j.current=!1,E.current={x:C.clientX,y:C.clientY,left:k.scrollLeft,top:k.scrollTop}},onPointerMove:C=>{const k=E.current;k&&(Math.hypot(C.clientX-k.x,C.clientY-k.y)>4&&(j.current||C.currentTarget.setPointerCapture(C.pointerId),j.current=!0),C.currentTarget.scrollLeft=k.left-(C.clientX-k.x),C.currentTarget.scrollTop=k.top-(C.clientY-k.y))},onPointerUp:()=>{E.current=null},onPointerCancel:()=>{E.current=null},children:e.jsx("div",{className:"mermaid-diagram-canvas",style:{width:o.width*x,height:o.height*x},role:n?"img":"button","aria-label":n?"Mermaid 图表":"点击全屏查看 Mermaid 图表",tabIndex:n?void 0:0,onClick:()=>{!n&&!j.current&&r()},onKeyDown:C=>{!n&&(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),r())},dangerouslySetInnerHTML:{__html:t}})}),e.jsx("div",{className:"mermaid-viewer-hint",children:i?"正在生成完整 PNG…":n?"双指缩放 · 滑动查看 · 导出完整图片":"点击图表全屏 · 双指缩放"})]})}function Zp({code:t,svg:n}){const r=a.useRef(null),[s,i]=a.useState(!1),[o,l]=a.useState(!1),[d,u]=a.useState(null),[f,p]=a.useState(null),v=a.useRef(0),x=a.useCallback(()=>{i(!1),requestAnimationFrame(()=>{var S,C;return(C=(S=r.current)==null?void 0:S.querySelector('button[aria-label="全屏查看图表"]'))==null?void 0:C.focus()})},[]),w=a.useCallback(()=>u(null),[]);a.useEffect(()=>()=>{v.current++},[t]),a.useEffect(()=>()=>{d&&URL.revokeObjectURL(d)},[d]);const j=async()=>{if(o)return;const S=v.current;l(!0),p(null);try{const C=await Yp(t);S===v.current&&u(URL.createObjectURL(C))}catch(C){S===v.current&&p(C instanceof Error?C.message:"图片导出失败,请重试。")}finally{S===v.current&&l(!1)}},E=e.jsx(Jp,{svg:n,fullscreen:s,onFullscreen:()=>s?x():i(!0),onExport:()=>void j(),exporting:o});return e.jsxs("div",{className:"mermaid-diagram","data-tab-swipe-ignore":!0,ref:r,children:[s?e.jsxs(Sl,{label:"图表全屏",onClose:x,children:[E,f&&e.jsx("div",{className:"mermaid-block-status",role:"alert",children:f})]}):E,!s&&f&&e.jsx("div",{className:"mermaid-block-status",role:"alert",children:f}),d&&e.jsxs(Sl,{label:"导出图表图片",onClose:w,children:[e.jsxs("div",{className:"mermaid-export-actions",children:[e.jsx("span",{children:"手机可长按图片保存,或下载 PNG"}),e.jsx("a",{href:d,download:"mermaid-diagram.png",children:"下载 PNG"})]}),e.jsx("div",{className:"mermaid-export-preview",children:e.jsx("img",{src:d,alt:"完整 Mermaid 图表 PNG"})})]})]})}function ef({code:t,complete:n}){const[r,s]=a.useState(!1),[i,o]=a.useState(null),l=n&&(i==null?void 0:i.code)===t?i:null;a.useEffect(()=>{if(!n||!t.trim())return;let u=!1;const f=setTimeout(()=>{fd(t).then(p=>{u||o({code:t,svg:p})},()=>{u||o({code:t,error:"图表暂时无法渲染,请查看源码。"})})},150);return()=>{u=!0,clearTimeout(f)}},[t,n]);const d=n?t.trim()?(l==null?void 0:l.error)??(l!=null&&l.svg?null:"正在渲染图表…"):"暂无图表内容":"图表生成中…";return e.jsxs("div",{className:"mermaid-block",children:[e.jsxs("div",{className:"mermaid-block-header",children:[e.jsx("span",{children:"Mermaid"}),e.jsx("button",{type:"button","aria-pressed":r,onClick:()=>s(!r),children:r?"图表":"源码"})]}),d&&e.jsx("div",{className:"mermaid-block-status",role:"status",children:d}),r||!(l!=null&&l.svg)?e.jsx("pre",{className:"mermaid-block-source",children:e.jsx("code",{children:t})}):e.jsx(Zp,{code:t,svg:l.svg},t)]})}function tf(t){if(typeof document>"u"||!document.body||typeof document.execCommand!="function")return!1;const n=document.createElement("textarea");n.value=t,n.setAttribute("readonly",""),Object.assign(n.style,{position:"fixed",top:"0",left:"-9999px",width:"1px",height:"1px",fontSize:"16px",opacity:"0",pointerEvents:"none"}),document.body.appendChild(n);try{return n.focus(),n.select(),n.setSelectionRange(0,n.value.length),document.execCommand("copy")}catch{return!1}finally{n.remove()}}async function zi(t){const n=typeof navigator>"u"?void 0:navigator.clipboard;if(typeof(n==null?void 0:n.writeText)=="function"&&(typeof isSecureContext>"u"||isSecureContext))try{return await n.writeText(t),!0}catch{}return tf(t)}const gd=2e5,nf=24,rf=12,sf=80,of=30,af=500,lf=160,cf=1e3,Di=200,df={"/help":"使用帮助","/whoami":"关于我","/works":"项目与作品","/jobs":"求职信息","/timeline":"经历时间线","/contact":"联系方式"};function Qo(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function fs(t,n){if(typeof t!="string")return;const r=t.trim();return r?r.slice(0,n):void 0}function Cl(t,n,r){return Array.isArray(t)?t.slice(0,n).filter(s=>typeof s=="string").map(s=>s.trim().slice(0,r)).filter(Boolean):[]}function uf(t){if(Qo(t)){const n=fs(t.type,Di)??"unknown";if(n==="text"){const r=fs(t.text,gd);if(r){const s=fs(t.tone,Di);return{kind:"text",text:r,...s?{tone:s}:{}}}}return{kind:"unknown",blockType:n,value:t}}return{kind:"unknown",blockType:"unknown",value:t}}function pf(t){if(typeof t.schemaVersion!="number"||!Number.isFinite(t.schemaVersion))return null;const n=fs(t.title,lf);if(!n||!Array.isArray(t.blocks))return null;const r=fs(t.skill,Di),s=fs(t.summary,cf),i=fs(t.generatedAt,Di);return{schemaVersion:t.schemaVersion,title:n,...r?{skill:r}:{},...s?{summary:s}:{},...i?{generatedAt:i}:{},blocks:t.blocks.slice(0,nf).map(uf),suggestions:Cl(t.suggestions,rf,sf),sources:Cl(t.sources,of,af),original:t}}function ff(t,n=!0){const r=t.trim();if(!n||r.length===0||r.length>gd||r.startsWith("```"))return null;let s;try{s=JSON.parse(r)}catch{return null}if(!Qo(s)&&!Array.isArray(s))return null;if(Qo(s)){const i=pf(s);if(i)return{kind:"envelope",raw:r,value:i}}return{kind:"json",raw:r,value:s}}function Il(t){const n=t.trim(),r=df[n.toLowerCase()];if(r)return r;const s=n.match(/^\/project\s+([a-z0-9-]+)$/i);return s?`查看项目:${s[1]}`:n}const hf=40,Rl=8;function gf(t){return Array.isArray(t)?t.map((n,r)=>[String(r),n]):Object.entries(t)}function mf({value:t}){return t===null?e.jsx("span",{className:"json-tree__value json-tree__value--null",children:"null"}):typeof t=="boolean"?e.jsx("span",{className:"json-tree__value json-tree__value--boolean",children:String(t)}):typeof t=="number"?e.jsx("span",{className:"json-tree__value json-tree__value--number",children:t}):e.jsxs("span",{className:"json-tree__value json-tree__value--string",children:[e.jsx("span",{"aria-hidden":"true",children:'"'}),t,e.jsx("span",{"aria-hidden":"true",children:'"'})]})}function fa({value:t,label:n,depth:r=0}){const[s,i]=a.useState(!1);if(t===null||typeof t!="object")return e.jsxs("div",{className:"json-tree__row",children:[n!==void 0&&e.jsx("span",{className:"json-tree__key",children:n}),n!==void 0&&e.jsx("span",{className:"json-tree__separator",children:":"}),e.jsx(mf,{value:t})]});const o=gf(t),l=Array.isArray(t)?`数组 · ${o.length} 项`:`对象 · ${o.length} 项`;if(r>=Rl)return e.jsxs("div",{className:"json-tree__row json-tree__row--limit",children:[n!==void 0&&e.jsx("span",{className:"json-tree__key",children:n}),e.jsxs("span",{className:"json-tree__limit",children:[l,",已折叠至深度 ",Rl]})]});const d=s?o:o.slice(0,hf),u=o.length-d.length;return e.jsxs("details",{className:"json-tree",open:r===0,children:[e.jsxs("summary",{className:"json-tree__summary",children:[n!==void 0&&e.jsx("span",{className:"json-tree__key",children:n}),e.jsx("span",{className:"json-tree__container-label",children:l})]}),e.jsxs("div",{className:"json-tree__children",children:[o.length===0&&e.jsx("div",{className:"json-tree__empty",children:"空"}),d.map(([f,p])=>e.jsx(fa,{value:p,label:f,depth:r+1},f)),u>0&&e.jsxs("button",{type:"button",className:"json-tree__more",onClick:()=>i(!0),children:["显示其余 ",u," 项"]})]})]})}function xf(t){try{return JSON.stringify(JSON.parse(t),null,2)}catch{return t}}function md({raw:t,onCopyFailed:n}){const r=async()=>{await zi(t)||n==null||n()};return e.jsxs("details",{className:"structured-agent-message__raw",children:[e.jsx("summary",{children:"查看原始 JSON"}),e.jsx("div",{className:"structured-agent-message__raw-toolbar",children:e.jsx("button",{type:"button",title:"复制原始 JSON","aria-label":"复制原始 JSON",onClick:()=>{r()},children:e.jsx(Ni,{size:14,strokeWidth:1.8,"aria-hidden":"true"})})}),e.jsx("pre",{children:xf(t)})]})}function bf({envelope:t,raw:n,renderText:r,suggestionsEnabled:s,onSuggestionSend:i,onCopyFailed:o}){return e.jsxs("section",{className:"structured-agent-message","data-kind":"envelope",children:[e.jsxs("header",{className:"structured-agent-message__header",children:[e.jsx("h3",{className:"structured-agent-message__title",children:t.title}),t.summary&&e.jsx("p",{className:"structured-agent-message__summary",children:t.summary})]}),e.jsx("div",{className:"structured-agent-message__blocks",children:t.blocks.map((l,d)=>l.kind==="text"?e.jsx("div",{className:"structured-agent-message__text","data-tone":l.tone??"body",children:r(l.text)},d):e.jsxs("details",{className:"structured-agent-message__unknown-block",children:[e.jsxs("summary",{children:[l.blockType," 内容"]}),e.jsx(fa,{value:l.value})]},d))}),t.suggestions.length>0&&e.jsx("div",{className:"structured-agent-message__suggestions","aria-label":"继续提问",children:t.suggestions.map(l=>e.jsx("button",{type:"button",className:"structured-agent-suggestion",disabled:!s,title:`发送 ${l}`,"aria-label":`${Il(l)},发送 ${l}`,onClick:()=>i(l),children:Il(l)},l))}),t.sources.length>0&&e.jsxs("details",{className:"structured-agent-message__details",children:[e.jsxs("summary",{children:["参考来源 ",t.sources.length]}),e.jsx("ul",{children:t.sources.map(l=>e.jsx("li",{children:l},l))})]}),e.jsxs("details",{className:"structured-agent-message__details",children:[e.jsx("summary",{children:"消息信息"}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"格式版本"}),e.jsx("dd",{children:t.schemaVersion})]}),t.skill&&e.jsxs("div",{children:[e.jsx("dt",{children:"能力"}),e.jsx("dd",{children:t.skill})]}),t.generatedAt&&e.jsxs("div",{children:[e.jsx("dt",{children:"生成时间"}),e.jsx("dd",{children:t.generatedAt})]})]})]}),e.jsx(md,{raw:n,onCopyFailed:o})]})}function yf({message:t,renderText:n,suggestionsEnabled:r,onSuggestionSend:s,onCopyFailed:i}){return t.kind==="envelope"?e.jsx(bf,{envelope:t.value,raw:t.raw,renderText:n,suggestionsEnabled:r,onSuggestionSend:s,onCopyFailed:i}):e.jsxs("section",{className:"structured-agent-message","data-kind":"json",children:[e.jsxs("div",{className:"structured-agent-message__data-title",children:[e.jsx(sp,{size:15,strokeWidth:1.8,"aria-hidden":"true"}),e.jsx("span",{children:"结构化数据"})]}),e.jsx(fa,{value:t.value}),e.jsx(md,{raw:t.raw,onCopyFailed:i})]})}function vf({text:t,complete:n,renderText:r,suggestionsEnabled:s,onSuggestionSend:i,onCopyFailed:o}){const l=a.useMemo(()=>ff(t,n),[n,t]);return l?e.jsx(yf,{message:l,renderText:r,suggestionsEnabled:s,onSuggestionSend:i,onCopyFailed:o}):e.jsx(e.Fragment,{children:r(t)})}const xd="webapp.nativeAgentRunPrefs.v1",wf=["codex","claude-code","opencode"];function bd(){try{const t=JSON.parse(localStorage.getItem(xd)??"{}");return t&&typeof t=="object"?t:{}}catch{return{}}}function Wi(t){return wf.includes(t)}function El(t){return Wi(t)?bd()[t]??{}:{}}function Ml(t,n){if(!Wi(t))return;const r=bd();r[t]=n;try{localStorage.setItem(xd,JSON.stringify(r))}catch{}}function kf(t,n,r){var s;return!r||!((s=t.model)!=null&&s.id)||n.has(oi(t.model))?t:{}}function oi(t){return t.providerID?`${t.providerID}/${t.id}`:t.id}function jf(t){const n=t.indexOf("/");return n>0?{providerID:t.slice(0,n),id:t.slice(n+1)}:{id:t}}function Sf(t){var r,s;const n=new Map;for(const i of t){const o=(r=i.providerID)==null?void 0:r.trim(),l=((s=i.providerDisplayName)==null?void 0:s.trim())||o||"其他供应商",d=o||"__other__",u=n.get(d)??{key:d,label:o==="opencode-go"?`${l}(需订阅)`:l,models:[]};u.models.push({...i,optionLabel:i.displayName||i.id}),n.set(d,u)}return[...n.values()]}const yd="context-compaction";function Fi(t,n){const r=t??[],s=r.findIndex(o=>o.itemId===n.itemId&&o.sectionIndex===n.sectionIndex);return(s<0?[...r,{itemId:n.itemId,sectionIndex:n.sectionIndex,text:n.delta}]:r.map((o,l)=>l===s?{...o,text:o.text+n.delta}:o)).sort((o,l)=>o.sectionIndex-l.sectionIndex)}function Al(t){let n=[];for(const r of t)if(r.type==="runtime_progress"){const{type:s,...i}=r;n=vd(n,i)}else r.type==="context_usage"?n=n.filter(s=>s.progressId!==yd):(r.type==="done"||r.type==="turn_aborted"||r.type==="error")&&(n=[]);return n}function vd(t,n){const r=t.findIndex(s=>s.progressId===n.progressId);return r<0?[...t,n]:t.map((s,i)=>i===r?n:s)}function wd(t,n){return[...t].reverse().find(r=>r.toolCallId===n)}function Cf(t){return[...t].reverse().find(n=>!n.toolCallId)}function If(t,n){var i,o;const r=[],s=new Map;for(let l=0;l<t.length;l+=1){const d=t[l];r.push(d);const u=d.role==="user"?(i=d.presentation)==null?void 0:i.executionTrace:void 0,f=u==null?void 0:u.turnId;if(!f)continue;const p=u.segmentIndex??s.get(f)??0;s.set(f,Math.max(s.get(f)??0,p+1));const v=t[l+1];((o=v==null?void 0:v.executionTrace)==null?void 0:o.turnId)===f&&(v.executionTrace.segmentIndex??0)===p?(r.push({...v,executionTrace:{...v.executionTrace,turnId:f,revision:n,segmentIndex:p}}),l+=1):r.push({id:jd(f,p),role:"assistant",content:"",executionTrace:{turnId:f,revision:n,segmentIndex:p},timestamp:d.timestamp})}return r}function Rf(t){var n,r,s,i;return t.role==="assistant"&&!!((n=t.toolCalls)!=null&&n.length||(s=(r=t.presentation)==null?void 0:r.reasoning)!=null&&s.length||((i=t.presentation)==null?void 0:i.agentMessagePhase)==="commentary")}function kd(t,n,r,s){return t.map(i=>{var o;return(o=i.toolCalls)!=null&&o.some(l=>l.id===n)?{...i,toolCalls:i.toolCalls.map(l=>l.id===n?{...l,result:r,isError:s}:l)}:i})}function Ef(t,n,r,s){if(n.type==="text_chunk"){if(!n.text||n.messagePhase!=="commentary")return[...t];const i=n.itemId?`codex-trace:${s}:agent:${n.itemId}`:`codex-live-commentary:${s}`,o=t.findIndex(l=>l.id===i);return o<0?[...t,{id:i,role:"assistant",content:n.text,presentation:{agentMessagePhase:"commentary"},timestamp:r}]:t.map((l,d)=>d===o?{...l,content:l.content+n.text}:l)}if(n.type==="reasoning_summary_delta"){const i=t.findIndex(o=>{var l,d;return(d=(l=o.presentation)==null?void 0:l.reasoning)==null?void 0:d.some(u=>u.itemId===n.itemId)});return i<0?[...t,{id:`codex-live-reasoning:${n.itemId}`,role:"assistant",content:"",presentation:{reasoning:Fi(void 0,n)},timestamp:r}]:t.map((o,l)=>{var d;return l===i?{...o,presentation:{...o.presentation,reasoning:Fi((d=o.presentation)==null?void 0:d.reasoning,n)}}:o})}if(n.type==="tool_call"){const i=t.findIndex(o=>{var l;return(l=o.toolCalls)==null?void 0:l.some(d=>d.id===n.toolCall.id)});return i>=0?t.map((o,l)=>{var d;return l===i?{...o,toolCalls:(d=o.toolCalls)==null?void 0:d.map(u=>u.id===n.toolCall.id?{...u,name:n.toolCall.name,arguments:n.toolCall.arguments}:u)}:o}):[...t,{id:`codex-live-tool:${n.toolCall.id}`,role:"assistant",content:"",toolCalls:[{...n.toolCall}],timestamp:r}]}return t.some(i=>{var o;return(o=i.toolCalls)==null?void 0:o.some(l=>l.id===n.result.toolCallId)})?kd(t,n.result.toolCallId,n.result.content,n.result.isError):[...t]}function Xo(t,n,r,s=Date.now()){var w,j;const i=t.findLastIndex(E=>{var S;return((S=E.executionTrace)==null?void 0:S.turnId)===n&&Mf(E.executionTrace.liveMessages??[],r)}),o=t.findLastIndex(E=>{var S;return((S=E.executionTrace)==null?void 0:S.turnId)===n}),l=t.findLastIndex(E=>E.role==="user"&&!E.isQueued),d=i>=0?i:o>l||o>=0&&!((w=t[l])!=null&&w.isSteered)?o:-1,u=d>=0?((j=t[d].executionTrace)==null?void 0:j.liveMessages)??[]:[],f=Ef(u,r,s,n);if(f.length===0&&u.length===0)return[...t];if(d>=0)return t.map((E,S)=>S===d?{...E,executionTrace:{...E.executionTrace,liveMessages:f}}:E);if(f===u)return[...t];const p=l;if(p<0)return[...t];const v=t.reduce((E,S)=>{var C;return((C=S.executionTrace)==null?void 0:C.turnId)===n?Math.max(E,S.executionTrace.segmentIndex??0):E},-1)+1,x={id:jd(n,v),role:"assistant",content:"",executionTrace:{turnId:n,revision:`live:${n}`,segmentIndex:v,liveMessages:f},timestamp:s};return[...t.slice(0,p+1),x,...t.slice(p+1)]}function jd(t,n){return n===0?`codex-execution-trace:${t}`:`codex-execution-trace:${t}:${n}`}function Mf(t,n){if(n.type==="text_chunk")return n.itemId?t.some(s=>s.id===`codex-trace:${n.turnId}:agent:${n.itemId}`):!1;if(n.type==="reasoning_summary_delta")return t.some(s=>{var i,o;return(o=(i=s.presentation)==null?void 0:i.reasoning)==null?void 0:o.some(l=>l.itemId===n.itemId)});const r=n.type==="tool_call"?n.toolCall.id:n.result.toolCallId;return t.some(s=>{var i;return(i=s.toolCalls)==null?void 0:i.some(o=>o.id===r)})}function Af(t,n){return t.some(s=>{var i,o;return((o=(i=s.presentation)==null?void 0:i.executionTrace)==null?void 0:o.segmentIndex)!==void 0})?t.filter(s=>{var i,o;return((o=(i=s.presentation)==null?void 0:i.executionTrace)==null?void 0:o.segmentIndex)===n}):n===0?[...t]:[]}function Yo(t,n){const r=new Map(t.map(s=>[`${s.itemId}:${s.sectionIndex}`,s]));for(const s of n){const i=`${s.itemId}:${s.sectionIndex}`,o=r.get(i),l=o?s.text.startsWith(o.text)?s.text:o.text.startsWith(s.text)?o.text:s.text:s.text;r.set(i,{...s,text:l})}return[...r.values()]}function Tl(t){var n,r;return[...((n=t.presentation)==null?void 0:n.agentMessagePhase)==="commentary"?[`agent:${t.id}`]:[],...(((r=t.presentation)==null?void 0:r.reasoning)??[]).map(s=>`reasoning:${s.itemId}:${s.sectionIndex}`),...(t.toolCalls??[]).map(s=>`tool:${s.id}`)]}function Tf(t,n){var r,s;return((r=t.presentation)==null?void 0:r.agentMessagePhase)==="commentary"&&((s=n.presentation)==null?void 0:s.agentMessagePhase)==="commentary"&&(t.id.startsWith("codex-live-commentary:")||n.id.startsWith("codex-live-commentary:"))&&(t.content.startsWith(n.content)||n.content.startsWith(t.content))}function Nf(t){var o,l,d,u,f,p,v,x,w,j,E;const n=[],r=new Map,s=new Map,i=new Map;for(const S of t){if(((o=S.presentation)==null?void 0:o.agentMessagePhase)==="commentary"){const L=r.get(S.id);if(L!==void 0){const T=n[L],A=S.content.startsWith(T.content)?S.content:T.content.startsWith(S.content)?T.content:S.content;n[L]={...T,...S,id:T.id,content:A};continue}}const C={...S,toolCalls:S.toolCalls?[]:void 0,presentation:(l=S.presentation)!=null&&l.reasoning?{...S.presentation,reasoning:[]}:S.presentation};for(const L of((d=S.presentation)==null?void 0:d.reasoning)??[]){const T=`${L.itemId}:${L.sectionIndex}`,A=s.get(T);if(A){const R=n[A.messageIndex],$=[...((u=R.presentation)==null?void 0:u.reasoning)??[]],F=$[A.sectionIndex];$[A.sectionIndex]=Yo([F],[L])[0],n[A.messageIndex]={...R,presentation:{...R.presentation,reasoning:$}}}else{const R=C.presentation.reasoning.findIndex($=>$.itemId===L.itemId&&$.sectionIndex===L.sectionIndex);R>=0?C.presentation.reasoning[R]=Yo([C.presentation.reasoning[R]],[L])[0]:C.presentation.reasoning.push(L)}}for(const L of S.toolCalls??[]){const T=i.get(L.id);if(T){const A=n[T.messageIndex],R=[...A.toolCalls??[]];R[T.toolIndex]={...R[T.toolIndex],...L},n[T.messageIndex]={...A,toolCalls:R}}else{const A=C.toolCalls.findIndex(R=>R.id===L.id);A>=0?C.toolCalls[A]={...C.toolCalls[A],...L}:C.toolCalls.push(L)}}const k=((f=C.presentation)==null?void 0:f.agentMessagePhase)==="commentary",z=!!((v=(p=C.presentation)==null?void 0:p.reasoning)!=null&&v.length),M=!!((x=C.toolCalls)!=null&&x.length);if(!k&&!z&&!M)continue;const H=n.length;n.push(C),k&&r.set(C.id,H);for(let L=0;L<(((j=(w=C.presentation)==null?void 0:w.reasoning)==null?void 0:j.length)??0);L+=1){const T=C.presentation.reasoning[L];s.set(`${T.itemId}:${T.sectionIndex}`,{messageIndex:H,sectionIndex:L})}for(let L=0;L<(((E=C.toolCalls)==null?void 0:E.length)??0);L+=1)i.set(C.toolCalls[L].id,{messageIndex:H,toolIndex:L})}return n}function _f(t,n,r){if(t.length<2)return t;const s=new Map;t.forEach((S,C)=>{for(const k of Tl(S))s.set(k,C)});const i=S=>{for(const C of Tl(S)){const k=s.get(C);if(k!==void 0)return k}return t.findIndex(C=>Tf(C,S))},o=S=>{const C=[];for(const k of S){const z=i(k);z<0||C.at(-1)===z||C.push(z)}return C},l=o(n),d=o(r),u=Array.from({length:t.length},()=>new Set),f=Array.from({length:t.length},()=>0),p=S=>{for(let C=1;C<S.length;C+=1){const k=S[C-1],z=S[C];k===z||u[k].has(z)||(u[k].add(z),f[z]+=1)}};p(l),p(d);const v=new Map(l.map((S,C)=>[S,C])),x=new Map(d.map((S,C)=>[S,C])),w=(S,C)=>{const k=v.get(S)??Number.POSITIVE_INFINITY,z=v.get(C)??Number.POSITIVE_INFINITY;if(k!==z)return k-z;const M=x.get(S)??Number.POSITIVE_INFINITY,H=x.get(C)??Number.POSITIVE_INFINITY;return M!==H?M-H:S-C},j=f.flatMap((S,C)=>S===0?[C]:[]).sort(w),E=[];for(;j.length>0;){const S=j.shift();E.push(t[S]);for(const C of u[S])f[C]-=1,f[C]===0&&(j.push(C),j.sort(w))}return E.length===t.length?E:t}function zf(t,n){var s,i,o,l,d;const r=t.map(u=>{var f,p;return{...u,toolCalls:(f=u.toolCalls)==null?void 0:f.map(v=>({...v})),presentation:(p=u.presentation)!=null&&p.reasoning?{...u.presentation,reasoning:[...u.presentation.reasoning]}:u.presentation}});for(const u of n){if(((s=u.presentation)==null?void 0:s.agentMessagePhase)==="commentary"){const p=r.findIndex(v=>{var x;return v.id===u.id||((x=v.presentation)==null?void 0:x.agentMessagePhase)==="commentary"&&(v.id.startsWith("codex-live-commentary:")||u.id.startsWith("codex-live-commentary:"))&&(u.content.startsWith(v.content)||v.content.startsWith(u.content))});if(p<0)r.push(u);else{const v=r[p],x=u.content.startsWith(v.content)?u.content:v.content.startsWith(u.content)?v.content:u.content;r[p]={...v,content:x,presentation:{...v.presentation,agentMessagePhase:"commentary"}}}continue}const f=(i=u.presentation)==null?void 0:i.reasoning;if(f!=null&&f.length){const p=r.findIndex(v=>{var x,w;return(w=(x=v.presentation)==null?void 0:x.reasoning)==null?void 0:w.some(j=>f.some(E=>E.itemId===j.itemId))});if(p>=0){const v=r[p];r[p]={...v,presentation:{...v.presentation,reasoning:Yo(((o=v.presentation)==null?void 0:o.reasoning)??[],f)}}}else r.push(u)}for(const p of u.toolCalls??[]){const v=r.findIndex(x=>{var w;return(w=x.toolCalls)==null?void 0:w.some(j=>j.id===p.id)});if(v>=0){const x=r[v];r[v]={...x,toolCalls:(l=x.toolCalls)==null?void 0:l.map(w=>w.id===p.id?{...w,...p}:w)}}else r.push({...u,id:(((d=u.toolCalls)==null?void 0:d.length)??0)>1?`${u.id}:tool:${p.id}`:u.id,presentation:void 0,toolCalls:[p]})}}return _f(Nf(r),t,n)}function Nl(t){for(let n=t.length-1;n>=0;n--)if(t[n].type==="context_usage"&&t[n].usage)return t[n].usage}function _l(t){var r;const n=new Map;for(const s of t)s.type==="native_subagent_update"&&((r=s.activity)!=null&&r.parentToolCallId)&&n.set(s.activity.parentToolCallId,s.activity);return[...n.values()]}function Lf(t,n,r,s){return s!==void 0&&s!==r?s?n[s]??[]:[]:t}function Sd(t){var n;return!!(t&&t.role==="assistant"&&!((n=t.toolCalls)!=null&&n.length)&&!t.widget&&!t.askUser&&!t.isCompactionSummary&&!t.executionTrace)}function zl(t,n){var r;if(n.role==="assistant"&&((r=n.toolCalls)!=null&&r.length)){const s=t[t.length-1];if(Sd(s))return[...t.slice(0,-1),{...s,content:s.content,toolCalls:n.toolCalls}]}return[...t,n]}function Pf(t,n){if(!n)return t;const r=t[t.length-1];if(Sd(r)){const s=[...t];return s[s.length-1]={...r,content:r.content+n},s}return[...t,{id:crypto.randomUUID(),role:"assistant",content:n,timestamp:Date.now()}]}function Ll(t,n,r,s){return t.map(i=>{if(!i.toolCalls)return i;const o=i.toolCalls.map(l=>l.id===n?{...l,result:r,isError:s}:l);return{...i,toolCalls:o}})}function Pl(t,n,r,s){return t.map(i=>{if(!i.toolCalls)return i;const o=i.toolCalls.map(l=>l.name==="dispatch_agent"&&l.arguments.subSessionId===n?{...l,arguments:{...l.arguments,subAgentStatus:r,subAgentDetail:s}}:l);return{...i,toolCalls:o}})}function Dl(t,n,r){return t.map(s=>{if(!s.toolCalls)return s;const i=s.toolCalls.map(o=>o.name==="dispatch_agent"&&o.arguments.subSessionId===n?{...o,arguments:{...o.arguments,subAgentProgress:(o.arguments.subAgentProgress?o.arguments.subAgentProgress+`
|
|
443
443
|
`+r:r).split(`
|
|
444
444
|
`).slice(-30).join(`
|
|
445
|
-
`)}}:o);return{...s,toolCalls:i}})}function Wl(t,n,r){return t.map(s=>s.id===n?r(s):s)}function Fl(t,n){const r=t.findIndex(s=>{var i,o;return(o=(i=s.presentation)==null?void 0:i.reasoning)==null?void 0:o.some(l=>l.itemId===n.itemId)});return r<0?[...t,{id:`native-reasoning:${n.itemId}`,role:"assistant",content:"",presentation:{reasoning:Fi(void 0,n)},timestamp:Date.now()}]:t.map((s,i)=>{var o;return i===r?{...s,presentation:{...s.presentation,reasoning:Fi((o=s.presentation)==null?void 0:o.reasoning,n)}}:s})}const Ze=Gc((t,n)=>({messages:[],messagesBySession:{},historyWindowsBySession:{},contextUsageBySession:{},runtimeProgressBySession:{},nativeSubagentsBySession:{},runningSessionId:null,currentText:"",sessionId:null,todos:[],cronTasks:[],addMessage:(r,s)=>t(i=>{const o=s??i.sessionId??void 0,l=o&&o!==i.sessionId?i.messages:zl(i.messages,r),d=o?{...i.messagesBySession,[o]:zl(i.messagesBySession[o]??(o===i.sessionId?i.messages:[]),r)}:i.messagesBySession;return{messages:l,messagesBySession:d,currentText:o&&o!==i.sessionId?i.currentText:""}}),appendText:(r,s)=>t(i=>{if(!r)return i;const o=s??i.sessionId??void 0,l=!o||o===i.sessionId,d=Pf(l?i.messages:i.messagesBySession[o]??[],r),u=o?{...i.messagesBySession,[o]:d}:i.messagesBySession;return{messages:l?d:i.messages,messagesBySession:u,currentText:o&&o!==i.sessionId?i.currentText:i.currentText+r}}),setRunningSession:r=>t({runningSessionId:r}),setSessionId:r=>t(s=>s.sessionId===r?s:{sessionId:r,messages:s.messagesBySession[r]??[],currentText:""}),updateToolResult:(r,s,i,o)=>t(l=>{const d=o??l.sessionId??void 0,u=d&&d!==l.sessionId?l.messages:Ll(l.messages,r,s,i),f=d?{...l.messagesBySession,[d]:Ll(l.messagesBySession[d]??(d===l.sessionId?l.messages:[]),r,s,i)}:l.messagesBySession;return{messages:u,messagesBySession:f}}),setMessages:(r,s,i)=>t(o=>{const l=s??o.sessionId??void 0,d=!l||l===o.sessionId;return{messages:d?r:o.messages,messagesBySession:l?{...o.messagesBySession,[l]:r}:o.messagesBySession,historyWindowsBySession:l&&i?{...o.historyWindowsBySession,[l]:i}:o.historyWindowsBySession,currentText:d?"":o.currentText}}),getMessagesForSession:r=>n().messagesBySession[r]??[],getSessionHistoryWindow:r=>n().historyWindowsBySession[r],setContextUsage:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{contextUsageBySession:{...i.contextUsageBySession,[o]:r}}:i}),getContextUsageForSession:r=>n().contextUsageBySession[r],applyRuntimeProgress:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{runtimeProgressBySession:{...i.runtimeProgressBySession,[o]:vd(i.runtimeProgressBySession[o]??[],r)}}:i}),setRuntimeProgress:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{runtimeProgressBySession:{...i.runtimeProgressBySession,[o]:r}}:i}),clearRuntimeProgress:r=>t(s=>{var d;const i=r??s.sessionId??void 0;if(!i||!((d=s.runtimeProgressBySession[i])!=null&&d.length))return s;const{[i]:o,...l}=s.runtimeProgressBySession;return{runtimeProgressBySession:l}}),applyNativeSubagentActivity:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{nativeSubagentsBySession:{...i.nativeSubagentsBySession,[o]:{...i.nativeSubagentsBySession[o]??{},[r.parentToolCallId]:r}}}:i}),setNativeSubagentActivities:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{nativeSubagentsBySession:{...i.nativeSubagentsBySession,[o]:Object.fromEntries(r.map(l=>[l.parentToolCallId,l]))}}:i}),applyReasoningSummary:(r,s)=>t(i=>{const o=s??i.sessionId??void 0,l=o&&o!==i.sessionId?i.messages:Fl(i.messages,r),d=o?{...i.messagesBySession,[o]:Fl(i.messagesBySession[o]??(o===i.sessionId?i.messages:[]),r)}:i.messagesBySession;return{messages:l,messagesBySession:d}}),applyCodexExecutionEvent:(r,s,i)=>t(o=>{const l=i??o.sessionId??void 0,d=Date.now(),u=l&&l!==o.sessionId?o.messages:Xo(o.messages,r,s,d),f=l?{...o.messagesBySession,[l]:Xo(o.messagesBySession[l]??(l===o.sessionId?o.messages:[]),r,s,d)}:o.messagesBySession;return{messages:u,messagesBySession:f}}),updateMessage:(r,s,i)=>t(o=>{const l=i??o.sessionId??void 0,d=l&&l!==o.sessionId?o.messages:Wl(o.messages,r,s),u=l?{...o.messagesBySession,[l]:Wl(o.messagesBySession[l]??(l===o.sessionId?o.messages:[]),r,s)}:o.messagesBySession;return{messages:d,messagesBySession:u}}),updateSubAgentStatus:(r,s,i,o)=>t(l=>{const d=o??l.sessionId??void 0,u=d&&d!==l.sessionId?l.messages:Pl(l.messages,r,s,i),f=d?{...l.messagesBySession,[d]:Pl(l.messagesBySession[d]??(d===l.sessionId?l.messages:[]),r,s,i)}:l.messagesBySession;return{messages:u,messagesBySession:f}}),updateSubAgentProgress:(r,s,i)=>t(o=>{const l=i??o.sessionId??void 0,d=l&&l!==o.sessionId?o.messages:Dl(o.messages,r,s),u=l?{...o.messagesBySession,[l]:Dl(o.messagesBySession[l]??(l===o.sessionId?o.messages:[]),r,s)}:o.messagesBySession;return{messages:d,messagesBySession:u}}),clearMessages:r=>t(s=>{const i=r??s.sessionId??void 0;if(!i)return{messages:[],currentText:""};const{[i]:o,...l}=s.messagesBySession,{[i]:d,...u}=s.historyWindowsBySession,{[i]:f,...p}=s.contextUsageBySession,{[i]:v,...x}=s.runtimeProgressBySession,{[i]:w,...j}=s.nativeSubagentsBySession;return{messages:i===s.sessionId?[]:s.messages,messagesBySession:l,historyWindowsBySession:u,contextUsageBySession:p,runtimeProgressBySession:x,nativeSubagentsBySession:j,currentText:i===s.sessionId?"":s.currentText}}),setTodos:r=>t({todos:r}),setCronTasks:r=>t({cronTasks:r})}));function ha(){const t=window;return t.SpeechRecognition??t.webkitSpeechRecognition??null}function Cd(){if(typeof window>"u")return null;const t=window.agentApi;return typeof(t==null?void 0:t.dictationStart)!="function"||typeof t.dictationStop!="function"||typeof t.onDictation!="function"||typeof t.onDictationError!="function"?null:t}function Df(){return Cd()!==null||ha()!==null}function Wf(t){var o,l;const n=Cd();if(n){let d=!1,u=()=>{},f=()=>{};const p=()=>{var v;d||(d=!0,u(),f(),(v=t.onEnd)==null||v.call(t))};return u=n.onDictation(({text:v,isFinal:x})=>{const w=v.trim();w&&(x?(t.onFinal(w),p()):t.onInterim(w))}),f=n.onDictationError(v=>{var x;(x=t.onError)==null||x.call(t,v),p()}),n.dictationStart().then(v=>{var x;v.ok||((x=t.onError)==null||x.call(t,v.reason||"无法启动语音识别"),p())}).catch(()=>{var v;(v=t.onError)==null||v.call(t,"无法启动语音识别"),p()}),{stop:()=>{n.dictationStop()}}}const r=ha();if(!r)return(o=t.onError)==null||o.call(t,"当前环境不支持语音识别"),null;const s=new r;s.lang=t.lang??"zh-CN",s.continuous=!1,s.interimResults=!0;let i="";s.onresult=d=>{let u="";for(let f=d.resultIndex;f<d.results.length;f++){const p=d.results[f];p.isFinal?i+=p[0].transcript:u+=p[0].transcript}u&&t.onInterim(i+u)},s.onerror=d=>{var u;d.error!=="no-speech"&&d.error!=="aborted"&&((u=t.onError)==null||u.call(t,`语音识别失败:${d.error??"未知错误"}`))},s.onend=()=>{var d;i&&t.onFinal(i.trim()),(d=t.onEnd)==null||d.call(t)};try{s.start()}catch{return(l=t.onEnd)==null||l.call(t),null}return{stop:()=>s.stop()}}function Ff(t){var l;const n=ha();if(!n)return(l=t.onError)==null||l.call(t,"当前环境不支持语音唤醒"),null;let r=!1,s=null,i=null;const o=()=>{if(!r){s=new n,s.lang=t.lang??"zh-CN",s.continuous=!0,s.interimResults=!0,s.onresult=d=>{var p,v,x;const u=d.results[d.results.length-1],f=(v=(p=u==null?void 0:u[0])==null?void 0:p.transcript)==null?void 0:v.trim();f&&(u.isFinal&&((x=t.onHeard)==null||x.call(t,f)),f.includes(t.wakeWord)&&t.onWake(f))},s.onerror=d=>{var u;d.error==="not-allowed"&&((u=t.onError)==null||u.call(t,"麦克风权限被拒绝,语音唤醒已停用"),r=!0)},s.onend=()=>{r||(i=setTimeout(o,400))};try{s.start()}catch{i=setTimeout(o,800)}}};return o(),{stop:()=>{r=!0,i&&clearTimeout(i);try{s==null||s.abort()}catch{}}}}function ti(){typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}function Ci(t,n){return n(),typeof(t==null?void 0:t.ttsStop)=="function"?t.ttsStop().then(()=>{}):Promise.resolve()}const Bf={createContext:()=>new AudioContext,createNode:t=>new AudioWorkletNode(t,"pcm-stream-player",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[1]}),workletUrl:"./pcm-audio-worklet.js"};function Of(t){const n=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(n.byteLength%2!==0)throw new Error("PCM chunk contains an incomplete int16 sample");const r=new Float32Array(n.byteLength/2),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let i=0;i<r.length;i+=1)r[i]=s.getInt16(i*2,!0)/32768;return r}class $f{constructor(n,r=Bf){this.api=n,this.dependencies=r,this.context=null,this.node=null,this.ready=null,this.current=null}start(n){var s;this.current&&!this.current.acknowledged&&((s=this.node)==null||s.port.postMessage({type:"flush",generation:this.current.metadata.generation}));const r={metadata:n,pending:[],pendingSamples:0,finished:!1,acknowledged:!1};this.current=r,this.ensureReady().then(()=>{if(!(this.current!==r||!this.node)){this.node.port.postMessage({type:"start",generation:n.generation,sampleRate:n.sampleRate});for(const i of r.pending)this.postSamples(n.generation,i);r.pending=[],r.pendingSamples=0,r.finished&&this.node.port.postMessage({type:"finish",generation:n.generation})}}).catch(i=>this.fail(r,i))}enqueue(n,r){const s=this.current;if(!s||s.metadata.generation!==n||s.acknowledged)return;let i;try{i=Of(r)}catch(o){this.fail(s,o);return}if(this.node){this.postSamples(n,i);return}if(s.pendingSamples+i.length>s.metadata.sampleRate){this.fail(s,new Error("TTS PCM queue overflow"));return}s.pending.push(i),s.pendingSamples+=i.length}finish(n){var s;const r=this.current;!r||r.metadata.generation!==n||r.acknowledged||(r.finished=!0,(s=this.node)==null||s.port.postMessage({type:"finish",generation:n}))}flush(n){var s;const r=this.current;!r||r.metadata.generation!==n||r.acknowledged||((s=this.node)==null||s.port.postMessage({type:"flush",generation:n}),r.pending=[],r.pendingSamples=0,this.acknowledge(r))}dispose(){var n,r;this.current&&this.flush(this.current.metadata.generation),(n=this.node)==null||n.disconnect(),this.node=null,(r=this.context)==null||r.close(),this.context=null,this.ready=null}ensureReady(){return this.ready?this.ready:(this.ready=(async()=>{const n=this.dependencies.createContext();this.context=n,await n.audioWorklet.addModule(this.dependencies.workletUrl);const r=this.dependencies.createNode(n);r.port.onmessage=s=>this.onWorkletMessage(s.data),r.connect(n.destination),this.node=r,n.state!=="running"&&await n.resume()})(),this.ready)}postSamples(n,r){var s;(s=this.node)==null||s.port.postMessage({type:"chunk",generation:n,samples:r},[r.buffer])}onWorkletMessage(n){const r=this.current;if(!(!r||n.generation!==r.metadata.generation)){if(n.type==="drained"||n.type==="stopped"){this.acknowledge(r);return}n.type==="overflow"&&this.fail(r,new Error("TTS AudioWorklet buffer overflow"))}}fail(n,r){this.current!==n||n.acknowledged||(console.error("[tts] PCM playback failed",r),n.acknowledged=!0,this.current=null,this.api.ttsStop(),this.api.ttsPlaybackEnded(n.metadata.generation))}acknowledge(n){this.current!==n||n.acknowledged||(n.acknowledged=!0,this.current=null,this.api.ttsPlaybackEnded(n.metadata.generation))}}async function Hf(t,n,r,s=50){var d;const i=u=>t.getSession(n,{view:"trace",revision:u,turnId:r.turnId});try{return{detail:await i(r.revision),revision:r.revision,recovered:!1}}catch(u){if(u.code!=="STALE_SESSION_ANCHOR")throw u}const o=await t.getSession(n,{view:"core",limit:s}),l=(d=o==null?void 0:o.history)==null?void 0:d.revision;if(!l)throw new Error("会话内容已更新,请刷新后重试");return{detail:await i(l),revision:l,recovered:!0}}async function Ss(t,n,r,s,i,o,l){if(r!=="codex"){const u=l?await l():await t.getSession(n,s);o()&&i(u,"full");return}const d=l?await l():await t.getSession(n,{...s,view:"core"});o()&&i(d,"core")}function Uf(t,n,r){var i,o;const s=((i=n==null?void 0:n.history)==null?void 0:i.nextCursor)??null;return((o=n==null?void 0:n.history)==null?void 0:o.hasMore)===!1||!s||r===0&&s===t?null:s}function qf(t,n,r,s){const i=r==="core"&&(s==null?void 0:s.delivery)!=="legacy-full"&&!!(s!=null&&s.revision),o=t.some(l=>!l.isQueued);return i&&o?Vf(t,n):Rd(t,n)}function Bl(t,n,r,s,i){const o=(i==null?void 0:i.kind)==="anchored"?t.filter(l=>l.isQueued):Jo(t);return{messages:qf(o,n,r,s),window:{kind:"latest",olderCursor:(i==null?void 0:i.kind)==="latest"&&o.some(l=>!l.isQueued)?i.olderCursor:(s==null?void 0:s.nextCursor)??null}}}function Ol(t,n,r){const s=Jo(t),i=new Set(s.map(l=>l.id)),o=Jo(n).filter(l=>!i.has(l.id));return o.length===0?s:r==="older"?[...o,...s]:[...s,...o]}function Jo(t){const n=new Set,r=[];for(let s=t.length-1;s>=0;s-=1){const i=t[s];n.has(i.id)||(n.add(i.id),r.push(i))}return r.length===t.length?t:r.reverse()}function Vf(t,n){var z,M;if(n.length===0)return t;if(t.length===0)return n;let r=t.filter(H=>!H.isQueued);const s=t.filter(H=>H.isQueued),i=n.findLastIndex(H=>H.role==="user"&&!H.isCompactionSummary);if(i<0)return t;const o=n[i],l=r.findIndex(H=>H.role==="user"&&H.id===o.id);let d=l>=0?l:r.findLastIndex(H=>H.role==="user"&&!H.isCompactionSummary&&or(H)===or(o));if(d<0)return[...r,...n.slice(i),...s];const u=r[d].sendState&&Ed(r,n,Md(r,n,Math.max(0,r.length-n.length))??0,d),f=Rd(r.slice(0,d),n.slice(0,i));r=[...f,...r.slice(d)],d=f.length;const p=r.findIndex((H,L)=>L>d&&H.role==="user"&&!H.isCompactionSummary),v=p<0?r.length:p,x=[];for(let H=d+1;H<v;H+=1)$l(r[H])&&x.push(H);const w=n.slice(i+1).filter($l),j=(M=(z=n.find(H=>H.executionTrace))==null?void 0:z.executionTrace)==null?void 0:M.revision,E=r.map(H=>H.executionTrace&&j?{...H,executionTrace:{...H.executionTrace,revision:j}}:H);u&&(E[d]={...E[d],id:o.id.startsWith("history-message.v1.")?o.id:E[d].id,sendState:void 0});const S=n.slice(i+1).find(H=>H.executionTrace),C=r.findIndex((H,L)=>{var T,A;return L>d&&L<v&&((T=H.executionTrace)==null?void 0:T.turnId)===((A=S==null?void 0:S.executionTrace)==null?void 0:A.turnId)});if(S&&C>=0){const H=r[C].executionTrace;E[C]={...S,id:r[C].id,timestamp:r[C].timestamp,executionTrace:{...S.executionTrace,...H!=null&&H.liveMessages?{liveMessages:H.liveMessages}:{}}}}const k=Math.min(x.length,w.length);for(let H=0;H<k;H+=1){const L=x[H],T=E[L],A=w[H];E[L]={...T,...A,id:A.id.startsWith("history-message.v1.")?A.id:T.id,timestamp:T.timestamp,images:A.images??T.images,presentation:A.presentation??T.presentation}}return w.length>k&&E.splice(v,0,...w.slice(k)),[...E,...s]}function $l(t){var n,r,s;return t.role==="assistant"&&!t.executionTrace&&!((n=t.toolCalls)!=null&&n.length)&&!t.askUser&&!t.isCompactionSummary&&!((s=(r=t.presentation)==null?void 0:r.reasoning)!=null&&s.length)}function cs(t){var i,o;const n=((i=t==null?void 0:t.history)==null?void 0:i.delivery)==="core",r=Id(t,!n),s=(o=t==null?void 0:t.history)==null?void 0:o.revision;return!n||!s?r:Jf(If(r,s),(t==null?void 0:t.events)??[])}function Gf(t){return Id(t).filter(Rf)}function Id(t,n=!0){var v;const r=(t==null?void 0:t.messages)??[],s=(t==null?void 0:t.events)??[],i=new Set(s.filter(x=>x.type==="approval_resolved"&&x.questionId).map(x=>x.questionId)),o=new Map;for(const x of s)x.type==="tool_result"&&((v=x.result)!=null&&v.toolCallId)&&o.set(x.result.toolCallId,{content:x.result.content??"",isError:x.result.isError});const l=r.filter(x=>(x.role==="user"||x.role==="assistant"||x.role==="tool")&&x.name!=="__interrupt__").map(Yf),d=new Map;for(const x of l)x.role==="tool"&&x.toolCallId&&d.set(x.toolCallId,x);let u=l.filter(x=>x.role!=="tool").map(x=>{var w;if(x.isCompactionSummary)return x;if(x.role==="assistant"&&((w=x.toolCalls)!=null&&w.length)){const j=x.toolCalls.filter(E=>E.name!=="ask_user");return j.length===0&&!x.content.trim()?null:{...x,toolCalls:j.map(E=>{const S=d.get(E.id);if(S)return{...E,...S.toolResultRef?{resultRef:S.toolResultRef,isError:S.toolResultRef.isError}:{result:S.content}};const C=o.get(E.id);return C?{...E,result:C.content,isError:C.isError}:E})}}return x.role==="user"&&x.name&&x.name!=="__compaction_checkpoint__"&&!x.name.startsWith("__native_")?{...x,agentName:x.name}:x}).filter(x=>x!==null);const f=Zf(s,n);if(!u.some(x=>x.role==="assistant"&&!x.isCompactionSummary)&&f){const x=u.findLastIndex(w=>w.role==="user"&&!w.isCompactionSummary);u=x>=0?[...u.slice(0,x+1),f,...u.slice(x+1)]:[...u,f]}const p=new Set(u.flatMap(x=>{var w;return(w=x.askUser)!=null&&w.questionId?[x.askUser.questionId]:[]}));for(const x of s)x.type!=="ask_user"||!x.questionId||i.has(x.questionId)||p.has(x.questionId)||(p.add(x.questionId),u.push({id:crypto.randomUUID(),role:"assistant",content:"",askUser:{questionId:x.questionId,question:x.question??"",options:x.options,fields:x.fields,multiSelect:x.multiSelect},timestamp:Date.now()}));return u}function Rd(t,n){if(n.length===0)return t;if(t.length===0)return n;const r=t.map(Zo),s=n.map(Zo),i=Math.max(0,t.length-n.length),o=Md(t,n,i);let l={currentStart:i,length:0,distance:1/0};for(let j=0;j<r.length;j++)for(let E=0;E<s.length;E++){if(r[j]!==s[E])continue;const S=j-E;if(S<0)continue;let C=0;for(;j+C<r.length&&E+C<s.length&&r[j+C]===s[E+C];)C+=1;const k=Math.abs(S-i);(C>l.length||C===l.length&&k<l.distance)&&(l={currentStart:S,length:C,distance:k})}const d=o??(l.length>0?l.currentStart:i),u=n.map((j,E)=>{var M,H,L;const S=t[d+E];if(!S||!Xf(S,j,s[E]))return j;const C=(H=(M=j.presentation)==null?void 0:M.attachments)==null?void 0:H.some(T=>T.dataUrl),k=(L=j.toolCalls)==null?void 0:L.map(T=>{var R;const A=(R=S.toolCalls)==null?void 0:R.find($=>$.id===T.id);return(A==null?void 0:A.result)===void 0?T:{...T,result:A.result,isError:A.isError}});return{...Kf(S,j),id:j.id.startsWith("history-message.v1.")?j.id:S.id,timestamp:S.timestamp,images:C?void 0:j.images??S.images,...k?{toolCalls:k}:{}}}),f=t.filter(j=>j.isQueued),p=t.slice(d).filter(j=>!j.isQueued),v=Qf(p,u),x=t.findLastIndex((j,E)=>E>=d&&j.role==="user"&&(j.sendState==="pending"||j.sendState==="failed")&&!j.isQueued&&!Ed(t,u,d,E)),w=x<0?[]:t.slice(x).filter(j=>!j.isQueued);return[...t.slice(0,d).filter(j=>!j.isQueued),...v,...w,...f]}function Ed(t,n,r,s){const i=t[s];if(!i||i.role!=="user")return!1;if(n.some(u=>u.id===i.id))return!0;const o=or(i),l=t.slice(r,s+1).filter(u=>u.role==="user"&&!u.isQueued&&or(u)===o).length;return n.filter(u=>u.role==="user"&&or(u)===o).length>=l}function Kf(t,n){var o,l;const r=(o=n.presentation)==null?void 0:o.attachments,s=(l=t==null?void 0:t.presentation)==null?void 0:l.attachments;if(!(r!=null&&r.length)||!(s!=null&&s.length)||r.every(d=>d.dataUrl||d.unavailable))return n;const i=r.map(d=>{if(d.dataUrl||d.unavailable||!d.omitted)return d;const u=s.find(f=>f.name===d.name&&f.dataUrl);return u?{...d,dataUrl:u.dataUrl,omitted:void 0}:d});return{...n,presentation:{...n.presentation,attachments:i}}}function Qf(t,n){const r=n.findLastIndex(j=>j.role==="user"&&!j.isQueued);if(r<0)return n;const s=or(n[r]);let i=-1,o=1/0;for(let j=0;j<t.length;j+=1){const E=t[j];if(E.role!=="user"||E.isQueued||or(E)!==s)continue;const S=Math.abs(j-r);S<o&&(i=j,o=S)}if(i<0)return n;const l=t.findIndex((j,E)=>E>i&&j.role==="user"&&!j.isQueued),d=t.slice(i+1,l<0?t.length:l),u=n.slice(r+1),f=Hl(d),p=Hl(u);if(f.length<=p.length||!f.startsWith(p))return n;const v=f.slice(p.length),x=n.findLastIndex((j,E)=>{var S;return E>r&&j.role==="assistant"&&!((S=j.toolCalls)!=null&&S.length)&&!j.askUser&&!j.isCompactionSummary});if(x>=0)return n.map((j,E)=>E===x?{...j,content:j.content+v}:j);const w=d.findLast(j=>j.role==="assistant"&&!!j.content&&!j.isCompactionSummary);return[...n,{id:(w==null?void 0:w.id)??crypto.randomUUID(),role:"assistant",content:v,timestamp:(w==null?void 0:w.timestamp)??Date.now()}]}function Hl(t){return t.filter(n=>n.role==="assistant"&&!n.isCompactionSummary).map(n=>n.content).join("")}function Md(t,n,r){const s=n[0];if((s==null?void 0:s.role)!=="user")return null;const i=or(s);let o=null;for(let l=0;l<t.length;l+=1){if(t[l].role!=="user"||t[l].isQueued||or(t[l])!==i)continue;const d=Math.abs(l-r);(!o||d<o.distance)&&(o={start:l,distance:d})}return(o==null?void 0:o.start)??null}function Xf(t,n,r){var s,i;return Zo(t)===r||t.role==="assistant"&&n.role==="assistant"&&t.content===n.content&&JSON.stringify(((s=t.toolCalls)==null?void 0:s.map(o=>o.id))??[])===JSON.stringify(((i=n.toolCalls)==null?void 0:i.map(o=>o.id))??[])?!0:t.role==="user"&&n.role==="user"&&or(t)===or(n)}function or(t){var n;return JSON.stringify({role:t.role,content:t.content,name:(n=t.name)!=null&&n.startsWith("__native_")?void 0:t.name,agentName:t.agentName,isCompactionSummary:t.isCompactionSummary})}function Zo(t){return JSON.stringify({role:t.role,content:t.content,toolCalls:t.toolCalls,toolCallId:t.toolCallId,toolResultRef:t.toolResultRef,name:t.name,agentName:t.agentName,presentation:t.role==="user"?void 0:t.presentation,isCompactionSummary:t.isCompactionSummary})}function Yf(t){var n;if(t.name==="__compaction_checkpoint__"){let r="";try{r=JSON.parse(t.content??"{}").summary??""}catch{}return{id:crypto.randomUUID(),role:"user",content:r,name:t.name,isCompactionSummary:!0,timestamp:Date.now()}}return{id:t.historyId??crypto.randomUUID(),role:t.role,content:t.content??"",toolCalls:(n=t.toolCalls)!=null&&n.length?t.toolCalls:void 0,toolCallId:t.toolCallId,toolResultRef:t.toolResultRef,name:t.name,presentation:t.presentation,timestamp:Date.now()}}function Jf(t,n){return n.reduce((r,s)=>{var o;if(!s.turnId)return r;let i=null;return s.type==="text_chunk"&&s.messagePhase==="commentary"&&typeof s.text=="string"&&s.text?i={type:"text_chunk",text:s.text,turnId:s.turnId,itemId:s.itemId,messagePhase:"commentary"}:s.type==="reasoning_summary_delta"&&s.itemId&&Number.isSafeInteger(s.sectionIndex)&&typeof s.delta=="string"?i={type:"reasoning_summary_delta",turnId:s.turnId,itemId:s.itemId,sectionIndex:s.sectionIndex,delta:s.delta}:s.type==="tool_call"&&s.toolCall?i={type:"tool_call",turnId:s.turnId,toolCall:s.toolCall}:s.type==="tool_result"&&((o=s.result)!=null&&o.toolCallId)&&(i={type:"tool_result",turnId:s.turnId,result:{toolCallId:s.result.toolCallId,content:s.result.content??"",isError:s.result.isError}}),i?Xo(r,s.turnId,i):r},t)}function Zf(t,n=!0){var o;let r="";const s=[],i=new Map;for(const l of t){if(l.type==="text_chunk"&&l.text&&(r+=l.text),n&&l.type==="tool_call"&&l.toolCall){const d={id:l.toolCall.id,name:l.toolCall.name,arguments:l.toolCall.arguments};s.push(d),i.set(d.id,d)}if(n&&l.type==="tool_result"&&((o=l.result)!=null&&o.toolCallId)){const d=i.get(l.result.toolCallId);d&&(d.result=l.result.content??"",d.isError=l.result.isError)}}return!r.trim()&&s.length===0?null:{id:crypto.randomUUID(),role:"assistant",content:r.trim(),toolCalls:s.length>0?s:void 0,timestamp:Date.now()}}class eh{constructor(){this.slot=null}prefetch(n,r,s){return this.getOrStart(n,r,s).promise}async consume(n,r,s){const i=this.getOrStart(n,r,s);try{return await i.promise}finally{this.slot===i&&(this.slot=null)}}invalidate(){this.slot=null}getOrStart(n,r,s){var l;if(((l=this.slot)==null?void 0:l.sessionId)===n&&this.slot.cursor===r)return this.slot;let i;try{i=s()}catch(d){i=Promise.reject(d)}const o={sessionId:n,cursor:r,promise:i};return this.slot=o,i.catch(()=>{this.slot===o&&(this.slot=null)}),o}}function th(t,n){const r=nh(t);return n?r.map(s=>{var o,l,d;if(s.role!=="user"||s.askUser||s.isQueued||s.isCompactionSummary||(o=s.images)!=null&&o.length||(d=(l=s.presentation)==null?void 0:l.attachments)!=null&&d.length)return s;const i=/^关于“([\s\S]+?)”的回答:\r?\n([\s\S]+)$/.exec(s.content);return!i||!i[1].trim()||!i[2].trim()?s:{...s,askUser:{questionId:`answered-history:${s.id}`,question:i[1],answered:!0,answer:i[2]}}}):r}function nh(t){var s,i,o,l;const n=new Map;for(let d=0;d<t.length;d+=1){const u=t[d];if(u.role!=="user"||u.isQueued||(s=u.images)!=null&&s.length||(o=(i=u.presentation)==null?void 0:i.attachments)!=null&&o.length)continue;const f=n.get(u.content)??[];f.push(d),n.set(u.content,f)}const r=new Set;for(let d=0;d<t.length;d+=1){const u=t[d].askUser;if(!(u!=null&&u.answered)||!u.questionId.includes(":async:")||!((l=u.answer)!=null&&l.trim()))continue;const f=`关于“${u.question}”的回答:
|
|
445
|
+
`)}}:o);return{...s,toolCalls:i}})}function Wl(t,n,r){return t.map(s=>s.id===n?r(s):s)}function Fl(t,n){const r=t.findIndex(s=>{var i,o;return(o=(i=s.presentation)==null?void 0:i.reasoning)==null?void 0:o.some(l=>l.itemId===n.itemId)});return r<0?[...t,{id:`native-reasoning:${n.itemId}`,role:"assistant",content:"",presentation:{reasoning:Fi(void 0,n)},timestamp:Date.now()}]:t.map((s,i)=>{var o;return i===r?{...s,presentation:{...s.presentation,reasoning:Fi((o=s.presentation)==null?void 0:o.reasoning,n)}}:s})}const et=Gc((t,n)=>({messages:[],messagesBySession:{},historyWindowsBySession:{},contextUsageBySession:{},runtimeProgressBySession:{},nativeSubagentsBySession:{},runningSessionId:null,currentText:"",sessionId:null,todos:[],cronTasks:[],addMessage:(r,s)=>t(i=>{const o=s??i.sessionId??void 0,l=o&&o!==i.sessionId?i.messages:zl(i.messages,r),d=o?{...i.messagesBySession,[o]:zl(i.messagesBySession[o]??(o===i.sessionId?i.messages:[]),r)}:i.messagesBySession;return{messages:l,messagesBySession:d,currentText:o&&o!==i.sessionId?i.currentText:""}}),appendText:(r,s)=>t(i=>{if(!r)return i;const o=s??i.sessionId??void 0,l=!o||o===i.sessionId,d=Pf(l?i.messages:i.messagesBySession[o]??[],r),u=o?{...i.messagesBySession,[o]:d}:i.messagesBySession;return{messages:l?d:i.messages,messagesBySession:u,currentText:o&&o!==i.sessionId?i.currentText:i.currentText+r}}),setRunningSession:r=>t({runningSessionId:r}),setSessionId:r=>t(s=>s.sessionId===r?s:{sessionId:r,messages:s.messagesBySession[r]??[],currentText:""}),updateToolResult:(r,s,i,o)=>t(l=>{const d=o??l.sessionId??void 0,u=d&&d!==l.sessionId?l.messages:Ll(l.messages,r,s,i),f=d?{...l.messagesBySession,[d]:Ll(l.messagesBySession[d]??(d===l.sessionId?l.messages:[]),r,s,i)}:l.messagesBySession;return{messages:u,messagesBySession:f}}),setMessages:(r,s,i)=>t(o=>{const l=s??o.sessionId??void 0,d=!l||l===o.sessionId;return{messages:d?r:o.messages,messagesBySession:l?{...o.messagesBySession,[l]:r}:o.messagesBySession,historyWindowsBySession:l&&i?{...o.historyWindowsBySession,[l]:i}:o.historyWindowsBySession,currentText:d?"":o.currentText}}),getMessagesForSession:r=>n().messagesBySession[r]??[],getSessionHistoryWindow:r=>n().historyWindowsBySession[r],setContextUsage:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{contextUsageBySession:{...i.contextUsageBySession,[o]:r}}:i}),getContextUsageForSession:r=>n().contextUsageBySession[r],applyRuntimeProgress:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{runtimeProgressBySession:{...i.runtimeProgressBySession,[o]:vd(i.runtimeProgressBySession[o]??[],r)}}:i}),setRuntimeProgress:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{runtimeProgressBySession:{...i.runtimeProgressBySession,[o]:r}}:i}),clearRuntimeProgress:r=>t(s=>{var d;const i=r??s.sessionId??void 0;if(!i||!((d=s.runtimeProgressBySession[i])!=null&&d.length))return s;const{[i]:o,...l}=s.runtimeProgressBySession;return{runtimeProgressBySession:l}}),applyNativeSubagentActivity:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{nativeSubagentsBySession:{...i.nativeSubagentsBySession,[o]:{...i.nativeSubagentsBySession[o]??{},[r.parentToolCallId]:r}}}:i}),setNativeSubagentActivities:(r,s)=>t(i=>{const o=s??i.sessionId??void 0;return o?{nativeSubagentsBySession:{...i.nativeSubagentsBySession,[o]:Object.fromEntries(r.map(l=>[l.parentToolCallId,l]))}}:i}),applyReasoningSummary:(r,s)=>t(i=>{const o=s??i.sessionId??void 0,l=o&&o!==i.sessionId?i.messages:Fl(i.messages,r),d=o?{...i.messagesBySession,[o]:Fl(i.messagesBySession[o]??(o===i.sessionId?i.messages:[]),r)}:i.messagesBySession;return{messages:l,messagesBySession:d}}),applyCodexExecutionEvent:(r,s,i)=>t(o=>{const l=i??o.sessionId??void 0,d=Date.now(),u=l&&l!==o.sessionId?o.messages:Xo(o.messages,r,s,d),f=l?{...o.messagesBySession,[l]:Xo(o.messagesBySession[l]??(l===o.sessionId?o.messages:[]),r,s,d)}:o.messagesBySession;return{messages:u,messagesBySession:f}}),updateMessage:(r,s,i)=>t(o=>{const l=i??o.sessionId??void 0,d=l&&l!==o.sessionId?o.messages:Wl(o.messages,r,s),u=l?{...o.messagesBySession,[l]:Wl(o.messagesBySession[l]??(l===o.sessionId?o.messages:[]),r,s)}:o.messagesBySession;return{messages:d,messagesBySession:u}}),updateSubAgentStatus:(r,s,i,o)=>t(l=>{const d=o??l.sessionId??void 0,u=d&&d!==l.sessionId?l.messages:Pl(l.messages,r,s,i),f=d?{...l.messagesBySession,[d]:Pl(l.messagesBySession[d]??(d===l.sessionId?l.messages:[]),r,s,i)}:l.messagesBySession;return{messages:u,messagesBySession:f}}),updateSubAgentProgress:(r,s,i)=>t(o=>{const l=i??o.sessionId??void 0,d=l&&l!==o.sessionId?o.messages:Dl(o.messages,r,s),u=l?{...o.messagesBySession,[l]:Dl(o.messagesBySession[l]??(l===o.sessionId?o.messages:[]),r,s)}:o.messagesBySession;return{messages:d,messagesBySession:u}}),clearMessages:r=>t(s=>{const i=r??s.sessionId??void 0;if(!i)return{messages:[],currentText:""};const{[i]:o,...l}=s.messagesBySession,{[i]:d,...u}=s.historyWindowsBySession,{[i]:f,...p}=s.contextUsageBySession,{[i]:v,...x}=s.runtimeProgressBySession,{[i]:w,...j}=s.nativeSubagentsBySession;return{messages:i===s.sessionId?[]:s.messages,messagesBySession:l,historyWindowsBySession:u,contextUsageBySession:p,runtimeProgressBySession:x,nativeSubagentsBySession:j,currentText:i===s.sessionId?"":s.currentText}}),setTodos:r=>t({todos:r}),setCronTasks:r=>t({cronTasks:r})}));function ha(){const t=window;return t.SpeechRecognition??t.webkitSpeechRecognition??null}function Cd(){if(typeof window>"u")return null;const t=window.agentApi;return typeof(t==null?void 0:t.dictationStart)!="function"||typeof t.dictationStop!="function"||typeof t.onDictation!="function"||typeof t.onDictationError!="function"?null:t}function Df(){return Cd()!==null||ha()!==null}function Wf(t){var o,l;const n=Cd();if(n){let d=!1,u=()=>{},f=()=>{};const p=()=>{var v;d||(d=!0,u(),f(),(v=t.onEnd)==null||v.call(t))};return u=n.onDictation(({text:v,isFinal:x})=>{const w=v.trim();w&&(x?(t.onFinal(w),p()):t.onInterim(w))}),f=n.onDictationError(v=>{var x;(x=t.onError)==null||x.call(t,v),p()}),n.dictationStart().then(v=>{var x;v.ok||((x=t.onError)==null||x.call(t,v.reason||"无法启动语音识别"),p())}).catch(()=>{var v;(v=t.onError)==null||v.call(t,"无法启动语音识别"),p()}),{stop:()=>{n.dictationStop()}}}const r=ha();if(!r)return(o=t.onError)==null||o.call(t,"当前环境不支持语音识别"),null;const s=new r;s.lang=t.lang??"zh-CN",s.continuous=!1,s.interimResults=!0;let i="";s.onresult=d=>{let u="";for(let f=d.resultIndex;f<d.results.length;f++){const p=d.results[f];p.isFinal?i+=p[0].transcript:u+=p[0].transcript}u&&t.onInterim(i+u)},s.onerror=d=>{var u;d.error!=="no-speech"&&d.error!=="aborted"&&((u=t.onError)==null||u.call(t,`语音识别失败:${d.error??"未知错误"}`))},s.onend=()=>{var d;i&&t.onFinal(i.trim()),(d=t.onEnd)==null||d.call(t)};try{s.start()}catch{return(l=t.onEnd)==null||l.call(t),null}return{stop:()=>s.stop()}}function Ff(t){var l;const n=ha();if(!n)return(l=t.onError)==null||l.call(t,"当前环境不支持语音唤醒"),null;let r=!1,s=null,i=null;const o=()=>{if(!r){s=new n,s.lang=t.lang??"zh-CN",s.continuous=!0,s.interimResults=!0,s.onresult=d=>{var p,v,x;const u=d.results[d.results.length-1],f=(v=(p=u==null?void 0:u[0])==null?void 0:p.transcript)==null?void 0:v.trim();f&&(u.isFinal&&((x=t.onHeard)==null||x.call(t,f)),f.includes(t.wakeWord)&&t.onWake(f))},s.onerror=d=>{var u;d.error==="not-allowed"&&((u=t.onError)==null||u.call(t,"麦克风权限被拒绝,语音唤醒已停用"),r=!0)},s.onend=()=>{r||(i=setTimeout(o,400))};try{s.start()}catch{i=setTimeout(o,800)}}};return o(),{stop:()=>{r=!0,i&&clearTimeout(i);try{s==null||s.abort()}catch{}}}}function ti(){typeof window<"u"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}function Ci(t,n){return n(),typeof(t==null?void 0:t.ttsStop)=="function"?t.ttsStop().then(()=>{}):Promise.resolve()}const Bf={createContext:()=>new AudioContext,createNode:t=>new AudioWorkletNode(t,"pcm-stream-player",{numberOfInputs:0,numberOfOutputs:1,outputChannelCount:[1]}),workletUrl:"./pcm-audio-worklet.js"};function Of(t){const n=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(n.byteLength%2!==0)throw new Error("PCM chunk contains an incomplete int16 sample");const r=new Float32Array(n.byteLength/2),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let i=0;i<r.length;i+=1)r[i]=s.getInt16(i*2,!0)/32768;return r}class $f{constructor(n,r=Bf){this.api=n,this.dependencies=r,this.context=null,this.node=null,this.ready=null,this.current=null}start(n){var s;this.current&&!this.current.acknowledged&&((s=this.node)==null||s.port.postMessage({type:"flush",generation:this.current.metadata.generation}));const r={metadata:n,pending:[],pendingSamples:0,finished:!1,acknowledged:!1};this.current=r,this.ensureReady().then(()=>{if(!(this.current!==r||!this.node)){this.node.port.postMessage({type:"start",generation:n.generation,sampleRate:n.sampleRate});for(const i of r.pending)this.postSamples(n.generation,i);r.pending=[],r.pendingSamples=0,r.finished&&this.node.port.postMessage({type:"finish",generation:n.generation})}}).catch(i=>this.fail(r,i))}enqueue(n,r){const s=this.current;if(!s||s.metadata.generation!==n||s.acknowledged)return;let i;try{i=Of(r)}catch(o){this.fail(s,o);return}if(this.node){this.postSamples(n,i);return}if(s.pendingSamples+i.length>s.metadata.sampleRate){this.fail(s,new Error("TTS PCM queue overflow"));return}s.pending.push(i),s.pendingSamples+=i.length}finish(n){var s;const r=this.current;!r||r.metadata.generation!==n||r.acknowledged||(r.finished=!0,(s=this.node)==null||s.port.postMessage({type:"finish",generation:n}))}flush(n){var s;const r=this.current;!r||r.metadata.generation!==n||r.acknowledged||((s=this.node)==null||s.port.postMessage({type:"flush",generation:n}),r.pending=[],r.pendingSamples=0,this.acknowledge(r))}dispose(){var n,r;this.current&&this.flush(this.current.metadata.generation),(n=this.node)==null||n.disconnect(),this.node=null,(r=this.context)==null||r.close(),this.context=null,this.ready=null}ensureReady(){return this.ready?this.ready:(this.ready=(async()=>{const n=this.dependencies.createContext();this.context=n,await n.audioWorklet.addModule(this.dependencies.workletUrl);const r=this.dependencies.createNode(n);r.port.onmessage=s=>this.onWorkletMessage(s.data),r.connect(n.destination),this.node=r,n.state!=="running"&&await n.resume()})(),this.ready)}postSamples(n,r){var s;(s=this.node)==null||s.port.postMessage({type:"chunk",generation:n,samples:r},[r.buffer])}onWorkletMessage(n){const r=this.current;if(!(!r||n.generation!==r.metadata.generation)){if(n.type==="drained"||n.type==="stopped"){this.acknowledge(r);return}n.type==="overflow"&&this.fail(r,new Error("TTS AudioWorklet buffer overflow"))}}fail(n,r){this.current!==n||n.acknowledged||(console.error("[tts] PCM playback failed",r),n.acknowledged=!0,this.current=null,this.api.ttsStop(),this.api.ttsPlaybackEnded(n.metadata.generation))}acknowledge(n){this.current!==n||n.acknowledged||(n.acknowledged=!0,this.current=null,this.api.ttsPlaybackEnded(n.metadata.generation))}}async function Hf(t,n,r,s=50){var d;const i=u=>t.getSession(n,{view:"trace",revision:u,turnId:r.turnId});try{return{detail:await i(r.revision),revision:r.revision,recovered:!1}}catch(u){if(u.code!=="STALE_SESSION_ANCHOR")throw u}const o=await t.getSession(n,{view:"core",limit:s}),l=(d=o==null?void 0:o.history)==null?void 0:d.revision;if(!l)throw new Error("会话内容已更新,请刷新后重试");return{detail:await i(l),revision:l,recovered:!0}}async function Ss(t,n,r,s,i,o,l){if(r!=="codex"){const u=l?await l():await t.getSession(n,s);o()&&i(u,"full");return}const d=l?await l():await t.getSession(n,{...s,view:"core"});o()&&i(d,"core")}function Uf(t,n,r){var i,o;const s=((i=n==null?void 0:n.history)==null?void 0:i.nextCursor)??null;return((o=n==null?void 0:n.history)==null?void 0:o.hasMore)===!1||!s||r===0&&s===t?null:s}function qf(t,n,r,s){const i=r==="core"&&(s==null?void 0:s.delivery)!=="legacy-full"&&!!(s!=null&&s.revision),o=t.some(l=>!l.isQueued);return i&&o?Vf(t,n):Rd(t,n)}function Bl(t,n,r,s,i){const o=(i==null?void 0:i.kind)==="anchored"?t.filter(l=>l.isQueued):Jo(t);return{messages:qf(o,n,r,s),window:{kind:"latest",olderCursor:(i==null?void 0:i.kind)==="latest"&&o.some(l=>!l.isQueued)?i.olderCursor:(s==null?void 0:s.nextCursor)??null}}}function Ol(t,n,r){const s=Jo(t),i=new Set(s.map(l=>l.id)),o=Jo(n).filter(l=>!i.has(l.id));return o.length===0?s:r==="older"?[...o,...s]:[...s,...o]}function Jo(t){const n=new Set,r=[];for(let s=t.length-1;s>=0;s-=1){const i=t[s];n.has(i.id)||(n.add(i.id),r.push(i))}return r.length===t.length?t:r.reverse()}function Vf(t,n){var z,M;if(n.length===0)return t;if(t.length===0)return n;let r=t.filter(H=>!H.isQueued);const s=t.filter(H=>H.isQueued),i=n.findLastIndex(H=>H.role==="user"&&!H.isCompactionSummary);if(i<0)return t;const o=n[i],l=r.findIndex(H=>H.role==="user"&&H.id===o.id);let d=l>=0?l:r.findLastIndex(H=>H.role==="user"&&!H.isCompactionSummary&&or(H)===or(o));if(d<0)return[...r,...n.slice(i),...s];const u=r[d].sendState&&Ed(r,n,Md(r,n,Math.max(0,r.length-n.length))??0,d),f=Rd(r.slice(0,d),n.slice(0,i));r=[...f,...r.slice(d)],d=f.length;const p=r.findIndex((H,L)=>L>d&&H.role==="user"&&!H.isCompactionSummary),v=p<0?r.length:p,x=[];for(let H=d+1;H<v;H+=1)$l(r[H])&&x.push(H);const w=n.slice(i+1).filter($l),j=(M=(z=n.find(H=>H.executionTrace))==null?void 0:z.executionTrace)==null?void 0:M.revision,E=r.map(H=>H.executionTrace&&j?{...H,executionTrace:{...H.executionTrace,revision:j}}:H);u&&(E[d]={...E[d],id:o.id.startsWith("history-message.v1.")?o.id:E[d].id,sendState:void 0});const S=n.slice(i+1).find(H=>H.executionTrace),C=r.findIndex((H,L)=>{var T,A;return L>d&&L<v&&((T=H.executionTrace)==null?void 0:T.turnId)===((A=S==null?void 0:S.executionTrace)==null?void 0:A.turnId)});if(S&&C>=0){const H=r[C].executionTrace;E[C]={...S,id:r[C].id,timestamp:r[C].timestamp,executionTrace:{...S.executionTrace,...H!=null&&H.liveMessages?{liveMessages:H.liveMessages}:{}}}}const k=Math.min(x.length,w.length);for(let H=0;H<k;H+=1){const L=x[H],T=E[L],A=w[H];E[L]={...T,...A,id:A.id.startsWith("history-message.v1.")?A.id:T.id,timestamp:T.timestamp,images:A.images??T.images,presentation:A.presentation??T.presentation}}return w.length>k&&E.splice(v,0,...w.slice(k)),[...E,...s]}function $l(t){var n,r,s;return t.role==="assistant"&&!t.executionTrace&&!((n=t.toolCalls)!=null&&n.length)&&!t.askUser&&!t.isCompactionSummary&&!((s=(r=t.presentation)==null?void 0:r.reasoning)!=null&&s.length)}function cs(t){var i,o;const n=((i=t==null?void 0:t.history)==null?void 0:i.delivery)==="core",r=Id(t,!n),s=(o=t==null?void 0:t.history)==null?void 0:o.revision;return!n||!s?r:Jf(If(r,s),(t==null?void 0:t.events)??[])}function Gf(t){return Id(t).filter(Rf)}function Id(t,n=!0){var v;const r=(t==null?void 0:t.messages)??[],s=(t==null?void 0:t.events)??[],i=new Set(s.filter(x=>x.type==="approval_resolved"&&x.questionId).map(x=>x.questionId)),o=new Map;for(const x of s)x.type==="tool_result"&&((v=x.result)!=null&&v.toolCallId)&&o.set(x.result.toolCallId,{content:x.result.content??"",isError:x.result.isError});const l=r.filter(x=>(x.role==="user"||x.role==="assistant"||x.role==="tool")&&x.name!=="__interrupt__").map(Yf),d=new Map;for(const x of l)x.role==="tool"&&x.toolCallId&&d.set(x.toolCallId,x);let u=l.filter(x=>x.role!=="tool").map(x=>{var w;if(x.isCompactionSummary)return x;if(x.role==="assistant"&&((w=x.toolCalls)!=null&&w.length)){const j=x.toolCalls.filter(E=>E.name!=="ask_user");return j.length===0&&!x.content.trim()?null:{...x,toolCalls:j.map(E=>{const S=d.get(E.id);if(S)return{...E,...S.toolResultRef?{resultRef:S.toolResultRef,isError:S.toolResultRef.isError}:{result:S.content}};const C=o.get(E.id);return C?{...E,result:C.content,isError:C.isError}:E})}}return x.role==="user"&&x.name&&x.name!=="__compaction_checkpoint__"&&!x.name.startsWith("__native_")?{...x,agentName:x.name}:x}).filter(x=>x!==null);const f=Zf(s,n);if(!u.some(x=>x.role==="assistant"&&!x.isCompactionSummary)&&f){const x=u.findLastIndex(w=>w.role==="user"&&!w.isCompactionSummary);u=x>=0?[...u.slice(0,x+1),f,...u.slice(x+1)]:[...u,f]}const p=new Set(u.flatMap(x=>{var w;return(w=x.askUser)!=null&&w.questionId?[x.askUser.questionId]:[]}));for(const x of s)x.type!=="ask_user"||!x.questionId||i.has(x.questionId)||p.has(x.questionId)||(p.add(x.questionId),u.push({id:crypto.randomUUID(),role:"assistant",content:"",askUser:{questionId:x.questionId,question:x.question??"",options:x.options,fields:x.fields,multiSelect:x.multiSelect},timestamp:Date.now()}));return u}function Rd(t,n){if(n.length===0)return t;if(t.length===0)return n;const r=t.map(Zo),s=n.map(Zo),i=Math.max(0,t.length-n.length),o=Md(t,n,i);let l={currentStart:i,length:0,distance:1/0};for(let j=0;j<r.length;j++)for(let E=0;E<s.length;E++){if(r[j]!==s[E])continue;const S=j-E;if(S<0)continue;let C=0;for(;j+C<r.length&&E+C<s.length&&r[j+C]===s[E+C];)C+=1;const k=Math.abs(S-i);(C>l.length||C===l.length&&k<l.distance)&&(l={currentStart:S,length:C,distance:k})}const d=o??(l.length>0?l.currentStart:i),u=n.map((j,E)=>{var M,H,L;const S=t[d+E];if(!S||!Xf(S,j,s[E]))return j;const C=(H=(M=j.presentation)==null?void 0:M.attachments)==null?void 0:H.some(T=>T.dataUrl),k=(L=j.toolCalls)==null?void 0:L.map(T=>{var R;const A=(R=S.toolCalls)==null?void 0:R.find($=>$.id===T.id);return(A==null?void 0:A.result)===void 0?T:{...T,result:A.result,isError:A.isError}});return{...Kf(S,j),id:j.id.startsWith("history-message.v1.")?j.id:S.id,timestamp:S.timestamp,images:C?void 0:j.images??S.images,...k?{toolCalls:k}:{}}}),f=t.filter(j=>j.isQueued),p=t.slice(d).filter(j=>!j.isQueued),v=Qf(p,u),x=t.findLastIndex((j,E)=>E>=d&&j.role==="user"&&(j.sendState==="pending"||j.sendState==="failed")&&!j.isQueued&&!Ed(t,u,d,E)),w=x<0?[]:t.slice(x).filter(j=>!j.isQueued);return[...t.slice(0,d).filter(j=>!j.isQueued),...v,...w,...f]}function Ed(t,n,r,s){const i=t[s];if(!i||i.role!=="user")return!1;if(n.some(u=>u.id===i.id))return!0;const o=or(i),l=t.slice(r,s+1).filter(u=>u.role==="user"&&!u.isQueued&&or(u)===o).length;return n.filter(u=>u.role==="user"&&or(u)===o).length>=l}function Kf(t,n){var o,l;const r=(o=n.presentation)==null?void 0:o.attachments,s=(l=t==null?void 0:t.presentation)==null?void 0:l.attachments;if(!(r!=null&&r.length)||!(s!=null&&s.length)||r.every(d=>d.dataUrl||d.unavailable))return n;const i=r.map(d=>{if(d.dataUrl||d.unavailable||!d.omitted)return d;const u=s.find(f=>f.name===d.name&&f.dataUrl);return u?{...d,dataUrl:u.dataUrl,omitted:void 0}:d});return{...n,presentation:{...n.presentation,attachments:i}}}function Qf(t,n){const r=n.findLastIndex(j=>j.role==="user"&&!j.isQueued);if(r<0)return n;const s=or(n[r]);let i=-1,o=1/0;for(let j=0;j<t.length;j+=1){const E=t[j];if(E.role!=="user"||E.isQueued||or(E)!==s)continue;const S=Math.abs(j-r);S<o&&(i=j,o=S)}if(i<0)return n;const l=t.findIndex((j,E)=>E>i&&j.role==="user"&&!j.isQueued),d=t.slice(i+1,l<0?t.length:l),u=n.slice(r+1),f=Hl(d),p=Hl(u);if(f.length<=p.length||!f.startsWith(p))return n;const v=f.slice(p.length),x=n.findLastIndex((j,E)=>{var S;return E>r&&j.role==="assistant"&&!((S=j.toolCalls)!=null&&S.length)&&!j.askUser&&!j.isCompactionSummary});if(x>=0)return n.map((j,E)=>E===x?{...j,content:j.content+v}:j);const w=d.findLast(j=>j.role==="assistant"&&!!j.content&&!j.isCompactionSummary);return[...n,{id:(w==null?void 0:w.id)??crypto.randomUUID(),role:"assistant",content:v,timestamp:(w==null?void 0:w.timestamp)??Date.now()}]}function Hl(t){return t.filter(n=>n.role==="assistant"&&!n.isCompactionSummary).map(n=>n.content).join("")}function Md(t,n,r){const s=n[0];if((s==null?void 0:s.role)!=="user")return null;const i=or(s);let o=null;for(let l=0;l<t.length;l+=1){if(t[l].role!=="user"||t[l].isQueued||or(t[l])!==i)continue;const d=Math.abs(l-r);(!o||d<o.distance)&&(o={start:l,distance:d})}return(o==null?void 0:o.start)??null}function Xf(t,n,r){var s,i;return Zo(t)===r||t.role==="assistant"&&n.role==="assistant"&&t.content===n.content&&JSON.stringify(((s=t.toolCalls)==null?void 0:s.map(o=>o.id))??[])===JSON.stringify(((i=n.toolCalls)==null?void 0:i.map(o=>o.id))??[])?!0:t.role==="user"&&n.role==="user"&&or(t)===or(n)}function or(t){var n;return JSON.stringify({role:t.role,content:t.content,name:(n=t.name)!=null&&n.startsWith("__native_")?void 0:t.name,agentName:t.agentName,isCompactionSummary:t.isCompactionSummary})}function Zo(t){return JSON.stringify({role:t.role,content:t.content,toolCalls:t.toolCalls,toolCallId:t.toolCallId,toolResultRef:t.toolResultRef,name:t.name,agentName:t.agentName,presentation:t.role==="user"?void 0:t.presentation,isCompactionSummary:t.isCompactionSummary})}function Yf(t){var n;if(t.name==="__compaction_checkpoint__"){let r="";try{r=JSON.parse(t.content??"{}").summary??""}catch{}return{id:crypto.randomUUID(),role:"user",content:r,name:t.name,isCompactionSummary:!0,timestamp:Date.now()}}return{id:t.historyId??crypto.randomUUID(),role:t.role,content:t.content??"",toolCalls:(n=t.toolCalls)!=null&&n.length?t.toolCalls:void 0,toolCallId:t.toolCallId,toolResultRef:t.toolResultRef,name:t.name,presentation:t.presentation,timestamp:Date.now()}}function Jf(t,n){return n.reduce((r,s)=>{var o;if(!s.turnId)return r;let i=null;return s.type==="text_chunk"&&s.messagePhase==="commentary"&&typeof s.text=="string"&&s.text?i={type:"text_chunk",text:s.text,turnId:s.turnId,itemId:s.itemId,messagePhase:"commentary"}:s.type==="reasoning_summary_delta"&&s.itemId&&Number.isSafeInteger(s.sectionIndex)&&typeof s.delta=="string"?i={type:"reasoning_summary_delta",turnId:s.turnId,itemId:s.itemId,sectionIndex:s.sectionIndex,delta:s.delta}:s.type==="tool_call"&&s.toolCall?i={type:"tool_call",turnId:s.turnId,toolCall:s.toolCall}:s.type==="tool_result"&&((o=s.result)!=null&&o.toolCallId)&&(i={type:"tool_result",turnId:s.turnId,result:{toolCallId:s.result.toolCallId,content:s.result.content??"",isError:s.result.isError}}),i?Xo(r,s.turnId,i):r},t)}function Zf(t,n=!0){var o;let r="";const s=[],i=new Map;for(const l of t){if(l.type==="text_chunk"&&l.text&&(r+=l.text),n&&l.type==="tool_call"&&l.toolCall){const d={id:l.toolCall.id,name:l.toolCall.name,arguments:l.toolCall.arguments};s.push(d),i.set(d.id,d)}if(n&&l.type==="tool_result"&&((o=l.result)!=null&&o.toolCallId)){const d=i.get(l.result.toolCallId);d&&(d.result=l.result.content??"",d.isError=l.result.isError)}}return!r.trim()&&s.length===0?null:{id:crypto.randomUUID(),role:"assistant",content:r.trim(),toolCalls:s.length>0?s:void 0,timestamp:Date.now()}}class eh{constructor(){this.slot=null}prefetch(n,r,s){return this.getOrStart(n,r,s).promise}async consume(n,r,s){const i=this.getOrStart(n,r,s);try{return await i.promise}finally{this.slot===i&&(this.slot=null)}}invalidate(){this.slot=null}getOrStart(n,r,s){var l;if(((l=this.slot)==null?void 0:l.sessionId)===n&&this.slot.cursor===r)return this.slot;let i;try{i=s()}catch(d){i=Promise.reject(d)}const o={sessionId:n,cursor:r,promise:i};return this.slot=o,i.catch(()=>{this.slot===o&&(this.slot=null)}),o}}function th(t,n){const r=nh(t);return n?r.map(s=>{var o,l,d;if(s.role!=="user"||s.askUser||s.isQueued||s.isCompactionSummary||(o=s.images)!=null&&o.length||(d=(l=s.presentation)==null?void 0:l.attachments)!=null&&d.length)return s;const i=/^关于“([\s\S]+?)”的回答:\r?\n([\s\S]+)$/.exec(s.content);return!i||!i[1].trim()||!i[2].trim()?s:{...s,askUser:{questionId:`answered-history:${s.id}`,question:i[1],answered:!0,answer:i[2]}}}):r}function nh(t){var s,i,o,l;const n=new Map;for(let d=0;d<t.length;d+=1){const u=t[d];if(u.role!=="user"||u.isQueued||(s=u.images)!=null&&s.length||(o=(i=u.presentation)==null?void 0:i.attachments)!=null&&o.length)continue;const f=n.get(u.content)??[];f.push(d),n.set(u.content,f)}const r=new Set;for(let d=0;d<t.length;d+=1){const u=t[d].askUser;if(!(u!=null&&u.answered)||!u.questionId.includes(":async:")||!((l=u.answer)!=null&&l.trim()))continue;const f=`关于“${u.question}”的回答:
|
|
446
446
|
${u.answer.trim()}`,p=n.get(f),v=p==null?void 0:p.find(x=>x>d&&!r.has(x));v!==void 0&&r.add(v)}return t.filter((d,u)=>!r.has(u))}const Ad=60,rh=32,sh=240,ih=6,oh=10;function Ul(t,n,r,s){if(s<=1||r<=0)return 0;const i=Math.max(0,Math.min(1,(t-n)/r));return Math.round(i*(s-1))}function ah(t){const n=Math.min(Math.max(0,t),Ad);return n<=1?n===1?[0]:[]:Array.from({length:n},(r,s)=>Math.round(s/(n-1)*(t-1)))}function ql(t,n=ih){return Math.min(sh,Math.max(rh,Math.min(Math.max(0,t),Ad)*n))}function lh(t,n,r){if(r<=0)return null;const s=Math.max(5,Math.round(r/10));return n==="ArrowUp"||n==="ArrowLeft"?Math.max(0,t-1):n==="ArrowDown"||n==="ArrowRight"?Math.min(r-1,t+1):n==="PageUp"?Math.max(0,t-s):n==="PageDown"?Math.min(r-1,t+s):n==="Home"?0:n==="End"?r-1:null}function ch({entries:t,activeMessageId:n,loadingMessageId:r,onActivate:s}){const i=t.findIndex(S=>S.messageId===n),o=i>=0?i:Math.max(0,t.length-1),[l,d]=a.useState(o),[u,f]=a.useState(!1),p=a.useRef(!1),v=a.useMemo(()=>ah(t.length),[t.length]);if(a.useEffect(()=>d(o),[o]),t.length<2)return null;const x=Math.min(l,t.length-1),w=t[x],j=r===w.messageId,E=(S,C)=>{const k=C.getBoundingClientRect();d(Ul(S,k.top,k.height,t.length))};return e.jsxs("div",{className:`query-navigation-rail${u?" query-navigation-rail--open":""}`,style:{"--query-navigation-rail-height":`${ql(t.length)}px`,"--query-navigation-rail-web-height":`${ql(t.length,oh)}px`},role:"slider",tabIndex:0,"aria-label":"用户消息导航","aria-orientation":"vertical","aria-valuemin":1,"aria-valuemax":t.length,"aria-valuenow":w.ordinal,"aria-valuetext":`第 ${w.ordinal} 条:${w.preview}`,"aria-busy":j||void 0,onPointerEnter:S=>{f(!0),E(S.clientY,S.currentTarget)},onPointerMove:S=>{S.pointerType==="touch"&&!p.current||E(S.clientY,S.currentTarget)},onPointerLeave:()=>{p.current||f(!1)},onPointerDown:S=>{p.current=!0,f(!0),S.currentTarget.setPointerCapture(S.pointerId),E(S.clientY,S.currentTarget)},onPointerUp:S=>{E(S.clientY,S.currentTarget);const C=Ul(S.clientY,S.currentTarget.getBoundingClientRect().top,S.currentTarget.getBoundingClientRect().height,t.length);p.current=!1,S.currentTarget.releasePointerCapture(S.pointerId),s(t[C]),S.pointerType==="touch"&&f(!1)},onPointerCancel:()=>{p.current=!1,f(!1)},onFocus:()=>f(!0),onBlur:()=>f(!1),onKeyDown:S=>{if(S.key==="Enter"){S.preventDefault(),s(w);return}const C=lh(x,S.key,t.length);C!==null&&(S.preventDefault(),d(C))},children:[e.jsxs("div",{className:"query-navigation-rail__track","aria-hidden":"true",children:[v.map(S=>e.jsx("span",{className:`query-navigation-rail__tick${S===x?" is-selected":""}${t[S].messageId===n?" is-active":""}`},S)),e.jsx("span",{className:"query-navigation-rail__marker",style:{top:`${x/Math.max(1,t.length-1)*100}%`}})]}),j&&e.jsx("span",{className:"query-navigation-rail__loading",role:"status","aria-label":"正在定位消息",children:e.jsx(ot,{size:14,"aria-hidden":"true"})}),u&&e.jsxs("div",{className:"query-navigation-rail__preview",role:"status",children:[e.jsxs("span",{children:[w.ordinal," / ",t.length]}),e.jsx("p",{children:w.preview})]})]})}const dh=/^(?:load failed|failed to fetch|network request failed|networkerror when attempting to fetch resource\.?|the network connection was lost\.?|fetch failed)$/i;function Td(t){return t instanceof Error&&t.name!=="AbortError"&&dh.test(t.message.trim())}function uh(t){return Td(t)?"网络连接中断,会话加载失败,请重新加载":t instanceof Error?t.message:"会话加载失败"}async function ph(t,n={}){const r=Math.max(1,Math.floor(n.maxAttempts??4)),s=Math.max(0,n.baseDelayMs??500),i=n.sleep??(o=>new Promise(l=>{setTimeout(l,o)}));for(let o=1;o<=r;o+=1)try{return await t()}catch(l){if(o===r||!Td(l))throw l;await i(s*2**(o-1))}throw new Error("会话加载失败")}const fh=2048,hh=2*1024*1024,gh=.85;function mh(t,n,r=fh){const s=Math.max(t,n);if(s<=r)return{width:t,height:n};const i=r/s;return{width:Math.max(1,Math.round(t*i)),height:Math.max(1,Math.round(n*i))}}async function Vl(t,n=xh){if(t.type.toLowerCase()==="image/gif")return t;let r=null;try{r=await n.decode(t);const s=mh(r.width,r.height);if(!(s.width!==r.width||s.height!==r.height)&&t.size<=hh)return t;const o=t.type.toLowerCase()==="image/jpeg"?"image/jpeg":"image/webp",l=await n.encode(r,s.width,s.height,o,gh);return l&&l.size<t.size?l:t}catch{return t}finally{r==null||r.dispose()}}const xh={decode(t){return new Promise((n,r)=>{const s=URL.createObjectURL(t),i=new Image;let o=!1;const l=()=>URL.revokeObjectURL(s);i.onload=()=>{o=!0,n({source:i,width:i.naturalWidth,height:i.naturalHeight,dispose:l})},i.onerror=()=>{o||l(),r(new Error("无法解码图片"))},i.src=s})},encode(t,n,r,s,i){const o=document.createElement("canvas");o.width=n,o.height=r;const l=o.getContext("2d");return l?(l.drawImage(t.source,0,0,n,r),new Promise(d=>o.toBlob(d,s,i))):Promise.resolve(null)}};function bh(t){return t==="customer-agent"||t==="codex"||t==="claude-code"}function Gl(t){return t!=null&&t.length?[...t]:void 0}function yh(t){const n=Gl(t.agentIds),r=Gl(t.images);return{text:t.text.trim(),origin:"composer",applyGoalMode:!0,clearComposer:!0,restoreDraftOnFailure:!0,...n?{agentIds:n}:{},...t.agentName?{agentName:t.agentName}:{},...r?{images:r}:{}}}function vh(t){return{text:t.trim(),origin:"suggestion",applyGoalMode:!1,clearComposer:!1,restoreDraftOnFailure:!1}}const wh="agentroam:draft:";function Bi(t){return`${wh}${t}`}function kh(t){if(!t||typeof window>"u")return"";try{return window.localStorage.getItem(Bi(t))??""}catch{return""}}function Hr(t,n){if(!(!t||typeof window>"u"))try{n?window.localStorage.setItem(Bi(t),n):window.localStorage.removeItem(Bi(t))}catch{}}function Cs(t){if(!(!t||typeof window>"u"))try{window.localStorage.removeItem(Bi(t))}catch{}}function jh(t,n,r){return n?t!==n?{type:"restore",ownerSessionId:n}:{type:"persist",ownerSessionId:n,value:r}:{type:"inactive",ownerSessionId:null}}const Sh="agentroam-composer-drafts",Ch=1,Is="session-image-drafts";function Kl(t){if(!t||typeof t!="object")return[];const n=t.images;return Array.isArray(n)?n.filter(r=>typeof r=="string"&&r.startsWith("data:image/")):[]}class Ih{constructor(n){this.databasePromise=null,this.mutationQueue=Promise.resolve(),this.factory=n===void 0?typeof indexedDB>"u"?null:indexedDB:n}async read(n){if(!n||!this.factory)return[];await this.mutationQueue;const r=await this.openDatabase();return r?await new Promise(s=>{try{const i=r.transaction(Is,"readonly"),o=i.objectStore(Is).get(n);o.onsuccess=()=>s(Kl(o.result)),o.onerror=()=>s([]),i.onabort=()=>s([])}catch{s([])}}):[]}write(n,r){if(!n||!this.factory)return Promise.resolve();const s=Kl({images:r});return this.enqueueMutation(async()=>{const i=await this.openDatabase();i&&await this.runMutation(i,o=>{s.length===0?o.delete(n):o.put({sessionId:n,images:s})})})}clear(n){return!n||!this.factory?Promise.resolve():this.enqueueMutation(async()=>{const r=await this.openDatabase();r&&await this.runMutation(r,s=>s.delete(n))})}enqueueMutation(n){const r=this.mutationQueue.then(n,n).catch(()=>{});return this.mutationQueue=r,r}openDatabase(){return this.databasePromise?this.databasePromise:this.factory?(this.databasePromise=new Promise(n=>{try{const r=this.factory.open(Sh,Ch);r.onupgradeneeded=()=>{const s=r.result;s.objectStoreNames.contains(Is)||s.createObjectStore(Is,{keyPath:"sessionId"})},r.onsuccess=()=>n(r.result),r.onerror=()=>n(null),r.onblocked=()=>n(null)}catch{n(null)}}),this.databasePromise):Promise.resolve(null)}runMutation(n,r){return new Promise(s=>{try{const i=n.transaction(Is,"readwrite");r(i.objectStore(Is)),i.oncomplete=()=>s(),i.onerror=()=>s(),i.onabort=()=>s()}catch{s()}})}}class Rh{constructor(n){this.repository=n,this.selectedSessionId=null,this.selectionGeneration=0}async restore(n){const r=++this.selectionGeneration;if(this.selectedSessionId=n??null,!n)return null;const s=await this.repository.read(n);return r!==this.selectionGeneration||this.selectedSessionId!==n?null:{sessionId:n,images:s}}save(n,r){return this.invalidatePendingRestore(n),this.repository.write(n,r)}saveSelected(n,r){return this.selectedSessionId!==n?Promise.resolve():this.repository.write(n,r)}clear(n){return this.invalidatePendingRestore(n),this.repository.clear(n)}invalidatePendingRestore(n){this.selectedSessionId===n&&(this.selectionGeneration+=1)}}const Eh="agent-webapp:artifact-open:v1";let Ql=0;function Xl(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)||/^\\\\[^\\/]+[\\/][^\\/]+/.test(t)}function ga(t,n){const r=t.trim();if(!r||/[\0\r\n]/.test(r))return null;if(Xl(r))return r;if(!n||!Xl(n))return null;const s=r.replaceAll("\\","/").split("/").filter(o=>o&&o!==".");if(s.length===0||s.some(o=>o===".."))return null;const i=/^[A-Za-z]:[\\/]/.test(n)||n.startsWith("\\\\")?"\\":"/";return`${n.replace(/[\\/]+$/,"")}${i}${s.join(i)}`}function Mh(t,n=window){return n.parent===n?!1:(Ql+=1,n.parent.postMessage({type:Eh,requestId:Ql,path:t},n.location.origin),!0)}function Ah(t){var n;return((n=[...t].reverse().find(r=>r.role==="user"&&!r.isQueued))==null?void 0:n.id)??null}function Th(t){var n;return((n=[...t].reverse().find(r=>r.role==="user"&&!r.isQueued&&r.sendState==="pending"))==null?void 0:n.id)??null}function Nh(t,n){const r=new Set(n.flatMap(s=>s.sourceMessageId?[s.sourceMessageId]:[]));return r.size===0?t:t.filter(s=>!r.has(s.id))}function Yl(t,n,r=Date.now()){const s=t.findIndex(l=>l.id===n);if(s<0)return t;const o={...t[s],timestamp:r,isQueued:!1,isSteered:!0,queueItemId:void 0,sendState:void 0};return[...t.slice(0,s),...t.slice(s+1),o]}function ko(t,n){var l,d,u;const r=t.filter(f=>!f.isQueued),s=new Map(t.filter(f=>f.isQueued&&f.queueItemId).map(f=>[f.queueItemId,f])),i=((l=n.active)==null?void 0:l.kind)==="message"?n.active:null;if(i){const f=s.get(i.id),p=i.sourceMessageId||(f==null?void 0:f.id)||i.id,v=r.findLastIndex(S=>S.role==="user"),x=r.findLastIndex((S,C)=>S.id===p||S.queueItemId===i.id||!f&&C===v&&S.role==="user"&&S.content===i.objective),w=x>=0?r[x]:f,j=x>=0&&r.slice(x+1).some(S=>S.role==="assistant"),E={...w??{},id:(w==null?void 0:w.id)||p,role:"user",content:i.objective,timestamp:(w==null?void 0:w.timestamp)??i.createdAt,agentName:(w==null?void 0:w.agentName)??((d=i.messagePayload)==null?void 0:d.agentName),images:(w==null?void 0:w.images)??((u=i.messagePayload)==null?void 0:u.images),isQueued:!1,queueItemId:void 0,...w&&"sendState"in w?{sendState:w.sendState}:j?{}:{sendState:"pending"}};x>=0?r[x]=E:r.push(E)}const o=n.queued.filter(f=>f.kind==="message").map(f=>{var v,x;const p=s.get(f.id);return{...p??{},id:f.sourceMessageId||(p==null?void 0:p.id)||f.id,role:"user",content:f.objective,timestamp:(p==null?void 0:p.timestamp)??f.createdAt,agentName:(v=f.messagePayload)==null?void 0:v.agentName,images:(x=f.messagePayload)==null?void 0:x.images,isQueued:!0,queueItemId:f.id}});return[...r,...o]}function Jl(t){var n;return{active:((n=t.active)==null?void 0:n.kind)==="message"?null:t.active,queued:t.queued.filter(r=>r.kind!=="message"),history:t.history.filter(r=>r.kind!=="message")}}function _h(t,n,r){if(n===r)return t;const s=t.filter(f=>f.isQueued),i=s.findIndex(f=>f.id===n),o=s.findIndex(f=>f.id===r);if(i<0||o<0)return t;const l=[...s],[d]=l.splice(i,1);l.splice(o,0,d);let u=0;return t.map(f=>f.isQueued?l[u++]:f)}function zh(t){let n=!0,r=!1;return{onScroll(s){const i=s>t;return i?r||(n=!1):(n=!0,r=!1),i},requestReturn(){n=!0,r=!0},reset(){n=!0,r=!1},shouldFollow(s){return s==="skip"?!1:(s==="instant"&&(n=!0,r=!1),n)},isFollowing(){return n}}}function Lh(t,n,r){return t?(n==null?void 0:n.id)!==t?{agentType:r,ready:!1}:{agentType:n.agentType,ready:!0}:{agentType:r,ready:!0}}function Ph(t){return typeof t=="string"&&t.trim().length>0?t:null}function Dh(t){return!["run_admitted","done","error","turn_aborted","goal_updated","goal_cleared"].includes(t)}function Wh(t,n){return((t==null?void 0:t.agentType)??n)!=="customer-agent"}function ma(t){return(t==null?void 0:t.agentType)!==void 0&&t.agentType!=="customer-agent"&&t.status==="running"}function Fh(t){return ma(t)&&(t==null?void 0:t.occupancy)==="owned-externally"}function Nd(t){return ma(t)&&(t==null?void 0:t.occupancy)!=="owned-externally"}function Bh(t){return(t==null?void 0:t.agentType)==="customer-agent"&&t.status==="active"}function Oh(t,n){return n||Nd(t)}function $h(t,n,r){return!!(n&&t&&t.agentType!=="customer-agent")}const _d=["modelProvider","modelId","apiKey","baseUrl","maxIterations","contextWindow","workingDirectory","isConfigured","profiles","activeProfileId","reasoningEffort","taskNotifications"];let Zl=null;function ec(t){return Object.fromEntries(_d.map(n=>[n,t[n]]))}function Hh(t,n){return t?Object.fromEntries(_d.filter(r=>JSON.stringify(t[r])!==JSON.stringify(n[r])).map(r=>[r,n[r]])):n}function Ii(t,n){return t.find(r=>r.id===n)??null}function jo(t){return t.provider==="aihub"?!!t.modelId:!!(t.apiKey&&t.modelId)}const qi=Gc((t,n)=>({modelProvider:"anthropic",modelId:"claude-sonnet-4-6",apiKey:"",baseUrl:"",maxIterations:10,contextWindow:100,workingDirectory:"/",isConfigured:!1,profiles:[],activeProfileId:"",reasoningEffort:"off",taskNotifications:_i,setField:(r,s)=>t(i=>{const o={...i,[r]:s};return o.isConfigured=o.modelProvider==="aihub"?!!o.modelId:!!(o.apiKey&&o.modelId),o}),loadFromSystem:async()=>{if(window.agentApi)try{const r=await window.agentApi.getSettings(),s=r.profiles??[],i=r.activeProfileId??"",o=Ii(s,i),l={revision:r.revision,modelProvider:(o==null?void 0:o.provider)??r.modelProvider??"anthropic",modelId:(o==null?void 0:o.modelId)??r.modelId??"claude-sonnet-4-6",apiKey:(o==null?void 0:o.apiKey)??r.apiKey??"",baseUrl:(o==null?void 0:o.baseUrl)??r.baseUrl??"",maxIterations:r.maxIterations??10,contextWindow:r.contextWindow??100,workingDirectory:r.workingDirectory??"/",isConfigured:((o==null?void 0:o.provider)??r.modelProvider)==="aihub"?!!((o==null?void 0:o.modelId)??r.modelId):!!(((o==null?void 0:o.apiKey)??r.apiKey)&&((o==null?void 0:o.modelId)??r.modelId)),profiles:s,activeProfileId:i,reasoningEffort:["off","low","medium","high"].includes(r.reasoningEffort??"")?r.reasoningEffort:"off",taskNotifications:Up(r.taskNotifications)};Zl=ec(l),t(l)}catch(r){console.error("Failed to load settings:",r)}},saveToSystem:async()=>{if(!window.agentApi)return;const r=n(),s=ec(r),i=Hh(Zl,s);try{await window.agentApi.saveSettings({...i,revision:r.revision})}catch(o){if((o==null?void 0:o.status)!==409)throw o;const l=await window.agentApi.getSettings();await window.agentApi.saveSettings({...i,revision:l.revision})}await n().loadFromSystem()},addProfile:r=>{const i={id:crypto.randomUUID(),...r};t(o=>({profiles:[...o.profiles,i]}))},updateProfile:(r,s)=>{t(o=>({profiles:o.profiles.map(l=>l.id===r?{...l,...s}:l)}));const i=n();if(i.activeProfileId===r){const o=Ii(i.profiles,r);o&&t({modelProvider:o.provider,modelId:o.modelId,apiKey:o.apiKey,baseUrl:o.baseUrl,isConfigured:jo(o)})}},deleteProfile:r=>{t(s=>{var d;const i=s.profiles.filter(u=>u.id!==r),o=s.activeProfileId===r?((d=i[0])==null?void 0:d.id)??"":s.activeProfileId,l=Ii(i,o);return{profiles:i,activeProfileId:o,...l?{modelProvider:l.provider,modelId:l.modelId,apiKey:l.apiKey,baseUrl:l.baseUrl,isConfigured:jo(l)}:{},...l?{}:{modelProvider:"anthropic",modelId:"",apiKey:"",baseUrl:"",isConfigured:!1}}})},setActiveProfileLocal:r=>{const s=n(),i=Ii(s.profiles,r);i&&t({activeProfileId:r,modelProvider:i.provider,modelId:i.modelId,apiKey:i.apiKey,baseUrl:i.baseUrl,isConfigured:jo(i)})},switchActiveProfile:async r=>{window.agentApi&&(await window.agentApi.setActiveProfile(r),await n().loadFromSystem())}}));function Qr(t){if(!t)return[];const n=t.replace(/\r\n/g,`
|
|
447
447
|
`).split(`
|
|
448
448
|
`);return n.at(-1)===""&&n.pop(),n}function xa(t){var r;const n=typeof t.kind=="string"?t.kind:(r=t.kind)==null?void 0:r.type;return n==="add"||n==="update"||n==="delete"?n:null}function zd(t){if(!t||typeof t!="object")return!1;const n=t;return Number.isSafeInteger(n.added)&&n.added>=0&&Number.isSafeInteger(n.removed)&&n.removed>=0}function Ld(t){if(zd(t.lineStats))return t.lineStats;if(typeof t.diff!="string")return null;const n=xa(t);if(n==="add")return{added:Qr(t.diff).length,removed:0};if(n==="delete")return{added:0,removed:Qr(t.diff).length};if(n!=="update")return null;let r=!1;const s={added:0,removed:0};for(const i of t.diff.split(`
|
|
@@ -454,34 +454,34 @@ ${u.answer.trim()}`,p=n.get(f),v=p==null?void 0:p.find(x=>x>d&&!r.has(x));v!==vo
|
|
|
454
454
|
...`:n;return e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em",marginBottom:5},children:t}),e.jsx("pre",{style:{fontSize:11,color:r?"var(--danger)":"var(--text-secondary)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontFamily:"var(--font-mono)",padding:"9px 11px",borderRadius:7,boxSizing:"border-box",maxWidth:"100%",background:r?"rgba(220,38,38,0.04)":"var(--bg-surface)",border:r?"1px solid rgba(220,38,38,0.15)":"1px solid var(--border-subtle)",borderLeft:r?"3px solid var(--danger)":"3px solid var(--success)",maxHeight:l?o:i,overflow:"auto",margin:0,lineHeight:1.6},children:p}),f&&e.jsx("button",{onClick:()=>d(!l),style:{marginTop:4,padding:"2px 10px",borderRadius:5,border:"1px solid var(--border-subtle)",background:"var(--bg-deep)",color:"var(--text-muted)",fontSize:10,cursor:"pointer",fontWeight:500},children:l?"收起":`展开全部 (${u.length} 行)`})]})}function ig({arguments:t}){var r;const n=t.task??"";return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4,padding:"6px 0"},children:[e.jsxs("div",{style:{display:"flex",gap:8,fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text-secondary)",flexWrap:"wrap"},children:[e.jsx(li,{label:`agent: ${t.agentName}`,color:"var(--accent)",bg:"var(--accent-dim)"}),e.jsx(li,{label:`sid: ${(r=t.subSessionId)==null?void 0:r.slice(0,8)}…`,color:"var(--text-muted)",bg:"var(--bg-surface)"})]}),n&&e.jsx(Ts,{label:"任务",content:n,error:!1,maxPreviewLines:3,maxPreviewHeight:80,maxExpandedHeight:2e3})]})}function og({raw:t}){const[n,r]=a.useState(!1);let s;try{const u=JSON.parse(t);delete u.subAgentProgress,delete u.subAgentStatus,delete u.subAgentDetail,s=JSON.stringify(u,null,2)}catch{s=t}const i=8,o=s.split(`
|
|
455
455
|
`),l=o.length>i,d=l&&!n?o.slice(0,i).join(`
|
|
456
456
|
`)+`
|
|
457
|
-
...`:s;return e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em",marginBottom:5},children:"参数"}),e.jsx("pre",{style:{fontSize:11,color:"var(--text-secondary)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontFamily:"var(--font-mono)",padding:"9px 11px",borderRadius:7,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",maxHeight:n?2e3:200,overflow:"auto",margin:0,lineHeight:1.6,boxSizing:"border-box",maxWidth:"100%"},children:d}),l&&e.jsx("button",{onClick:()=>r(!n),style:{marginTop:4,padding:"2px 10px",borderRadius:5,border:"1px solid var(--border-subtle)",background:"var(--bg-deep)",color:"var(--text-muted)",fontSize:10,cursor:"pointer",fontWeight:500},children:n?"收起":`展开全部 (${o.length} 行)`})]})}function ag({activity:t,workspacePath:n,onOpenArtifact:r}){const s=new Map(t.messages.flatMap(i=>i.role==="tool"&&i.toolCallId?[[i.toolCallId,{content:i.content,isError:i.name==="error"}]]:[]));return e.jsxs("div",{className:"native-subagent-activity",children:[e.jsxs("div",{className:"native-subagent-activity__meta",children:[t.elapsedSeconds!==void 0&&e.jsxs("span",{children:[t.elapsedSeconds," 秒"]}),t.toolUses!==void 0&&e.jsxs("span",{children:[t.toolUses," 次工具调用"]}),t.lastToolName&&e.jsxs("span",{children:["正在使用 ",t.lastToolName]})]}),t.messages.map((i,o)=>{var l;return e.jsxs("div",{className:"native-subagent-activity__entry",children:[i.role==="assistant"&&i.content&&e.jsx("pre",{className:"native-subagent-activity__text",children:i.content}),i.role==="assistant"&&((l=i.toolCalls)==null?void 0:l.map(d=>{const u=s.get(d.id);return e.jsxs("div",{className:"native-subagent-activity__tool",children:[e.jsx(Qi,{toolCall:{...d,...u?{result:u.content,isError:u.isError}:{}},workspacePath:n,onOpenArtifact:r}),u&&e.jsx("pre",{className:`native-subagent-activity__tool-result${u.isError?" native-subagent-activity__tool-result--error":""}`,children:u.content})]},d.id)})),i.role==="tool"&&i.toolCallId&&!t.messages.some(d=>{var u;return(u=d.toolCalls)==null?void 0:u.some(f=>f.id===i.toolCallId)})&&e.jsx(Ts,{label:"工具结果",content:i.content,error:i.name==="error",maxPreviewHeight:180})]},`${i.role}-${o}`)}),t.summary&&e.jsx(Ts,{label:t.status==="failed"?"错误信息":"执行摘要",content:t.summary,error:t.status==="failed",maxPreviewHeight:180}),t.status==="running"&&t.messages.length===0&&!t.summary&&e.jsxs("div",{className:"native-subagent-activity__waiting",children:[e.jsx(zs,{isDone:!1,color:"var(--accent)",size:10}),"子 agent 正在工作"]})]})}function lg({toolCall:t,onSelectSession:n,nativeSubagent:r,previewPaths:s,workspacePath:i,onOpenArtifact:o,onLoadResult:l}){const d=
|
|
458
|
-
`)[0];return We.length>80?We.slice(0,80)+"…":We})():Qh(t.name,t.arguments),A=a.useMemo(()=>t.name==="apply_patch"?Yh(t.arguments,t.result):null,[t.name,t.arguments,t.result]),R=a.useMemo(()=>t.name==="apply_patch"?ka(t.arguments,t.result):[],[t.name,t.arguments,t.result]),$=a.useRef(null),F=t.name==="apply_patch"&&!(A!=null&&A.lineStats)&&!!(t.resultRef&&t.result===void 0&&l)&&!C&&!u.loadingResult&&!u.resultError;a.useEffect(()=>{if(!F||!$.current)return;const Ie=new IntersectionObserver(We=>{We.some(at=>at.isIntersecting)&&(Ie.disconnect(),u.loadResult())});return Ie.observe($.current),()=>Ie.disconnect()},[F,t.id,t.resultRef,l]);const Ee=t.name==="apply_patch"?(A==null?void 0:A.lineStats)??null:t.name==="MultiEdit"?Zh(t.arguments):null,Ke=x?`@${r.agentName??"agent"}`:v?`@${t.arguments.agentName??"agent"}`:t.name==="apply_patch"?Jh(A):Fd(t.name)??t.name,ae=ya(t.name),ke=!k||!!C||!!L,Pe=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tool-call-shell__icon",children:e.jsx(di,{name:t.name,color:M})}),e.jsx("span",{className:"tool-call-shell__label",title:H?t.name:void 0,style:{fontFamily:H?"var(--font-body)":"var(--font-mono)",fontSize:11.5,color:"var(--text-primary)",fontWeight:600,flexShrink:0},children:Ke}),T&&e.jsx("span",{className:"tool-call-shell__preview",style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text-muted)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T}),!T&&e.jsx("span",{style:{flex:1}}),!C&&e.jsx(Oi,{stats:Ee,pending:!k}),t.name==="apply_patch"&&!Ee&&u.loadingResult&&e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",flexShrink:0},children:"行数加载中"}),ke&&e.jsxs("span",{className:"tool-call-shell__state",style:{color:z},children:[e.jsx(zs,{isDone:k,isError:!!C,color:z}),L&&e.jsx("span",{children:L})]})]});return e.jsxs(Vi,{visibilityRef:$,statusColor:z,isDone:k,expanded:f,onToggle:u.toggle,header:Pe,maxBodyHeight:800,primaryAction:s.length===1&&o?()=>o(s[0]):void 0,primaryActionLabel:s.length===1?`预览文件 ${Ar(s[0])}`:void 0,primaryActionTitle:s.length===1?`预览 ${s[0]}`:void 0,children:[e.jsx(Ki,{toolCall:t,loading:u.loadingResult,error:u.resultError,retry:u.loadResult}),s.length>1&&e.jsx("div",{className:"tool-call-file-list","aria-label":"改动文件",children:s.map(Ie=>e.jsxs("button",{type:"button",onClick:()=>o==null?void 0:o(Ie),"aria-label":`预览文件 ${Ar(Ie)}`,title:`预览 ${Ie}`,children:[e.jsx(ci,{size:12,strokeWidth:1.8,"aria-hidden":"true"}),e.jsx("span",{style:{flex:1},children:Ar(Ie)}),(()=>{const We=R.find(qe=>ga(String(qe.path??""),i)===Ie);if(!We)return null;const at=xa(We);return e.jsxs(e.Fragment,{children:[e.jsx("span",{children:at==="add"?"写入":at==="delete"?"删除":"编辑"}),!C&&e.jsx(Oi,{stats:Ld(We),pending:!k})]})})()]},Ie))}),x?e.jsx(ag,{activity:r,workspacePath:i,onOpenArtifact:o}):v?e.jsx(ig,{arguments:t.arguments}):ae==="command"&&typeof t.arguments.command=="string"?e.jsxs(e.Fragment,{children:[typeof t.arguments.cwd=="string"&&t.arguments.cwd&&e.jsxs("div",{style:{fontSize:10,color:"var(--text-muted)",fontFamily:"var(--font-mono)",wordBreak:"break-all"},children:["工作目录 ",t.arguments.cwd]}),e.jsx(Ts,{label:"命令",content:t.arguments.command,maxPreviewLines:6,maxPreviewHeight:160})]}):e.jsx(og,{raw:JSON.stringify(t.arguments,null,2)}),t.result&&!v&&!x&&e.jsx(Ts,{label:t.isError?"错误信息":"返回结果",content:t.result,error:t.isError,maxPreviewHeight:240}),v&&w&&j&&e.jsx(Ts,{label:w==="failed"?"错误信息":"执行摘要",content:j,error:w==="failed",maxPreviewHeight:180}),v&&!w&&E&&(!!d||!S)&&e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em",marginBottom:5},children:"实时输出"}),e.jsxs("pre",{style:{fontSize:11,color:"var(--text-secondary)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontFamily:"var(--font-mono)",padding:"9px 11px",borderRadius:7,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",borderLeft:"3px solid var(--accent)",maxHeight:240,overflow:"auto",margin:0,lineHeight:1.6,boxSizing:"border-box",maxWidth:"100%"},children:[E,e.jsx("span",{style:{display:"inline-block",width:"0.5em",height:"1em",background:"var(--accent)",verticalAlign:"text-bottom",animation:"blink 1s step-end infinite"},children:""})]})]}),v&&!w&&!E&&!!d&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 0",fontSize:11,color:"var(--text-muted)",fontStyle:"italic"},children:[[0,1,2].map(Ie=>e.jsx("span",{style:{width:5,height:5,borderRadius:"50%",background:"var(--accent)",display:"inline-block",animation:"wave 1.1s ease-in-out infinite",animationDelay:`${Ie*.16}s`}},Ie)),"等待子 agent 响应..."]}),v&&t.arguments.subSessionId&&n&&e.jsxs("button",{onClick:()=>n(t.arguments.subSessionId),style:{alignSelf:"flex-start",padding:"4px 10px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--accent-dim)",color:"var(--accent)",fontSize:11,fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",gap:5,transition:"background 0.15s"},onMouseEnter:Ie=>{Ie.currentTarget.style.background="var(--accent)",Ie.currentTarget.style.color="white"},onMouseLeave:Ie=>{Ie.currentTarget.style.background="var(--accent-dim)",Ie.currentTarget.style.color="var(--accent)"},children:[e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[e.jsx("path",{d:"M12 2a5 5 0 1 0 0 10A5 5 0 0 0 12 2z"}),e.jsx("path",{d:"M12 12c-5.33 0-8 2.67-8 4v2h16v-2c0-1.33-2.67-4-8-4z"})]}),"查看子会话"]})]})}function qd({items:t,onSelectSession:n,workspacePath:r,onOpenArtifact:s,onLoadResult:i}){var j;const[o,l]=a.useState(!1),d=(j=t[0])==null?void 0:j.toolCall,u=d?va(d.name):null;if(!d||!u||t.length<2)return null;const f=t.every(({toolCall:E})=>_s(E)),p=t.filter(({toolCall:E})=>E.isError).length,v=p>0?"var(--danger)":f?"var(--text-muted)":"var(--accent)",x=Fd(d.name)??u.done,w=`${x},${t.length} 项,${o?"收起":"展开"}`;return e.jsxs("div",{className:"tool-call-group",children:[e.jsxs("button",{type:"button",className:"tool-call-group__summary","aria-expanded":o,"aria-label":w,onClick:()=>l(E=>!E),children:[e.jsx("span",{className:"tool-call-group__icon","aria-hidden":"true",children:e.jsx(di,{name:d.name,color:v})}),e.jsx("span",{className:"tool-call-group__label",children:x}),e.jsxs("span",{className:"tool-call-group__count",children:[t.length," 项"]}),e.jsx("span",{className:"tool-call-group__spacer"}),p>0&&e.jsxs("span",{className:"tool-call-group__error",children:[p," 项失败"]}),!f&&e.jsx(zs,{isDone:!1,color:v,size:11}),e.jsx(Kr,{className:"tool-call-group__chevron",size:13,strokeWidth:2.2,"aria-hidden":"true"})]}),o&&e.jsx("div",{className:"tool-call-group__items",children:t.map(({toolCall:E,beforeContent:S,progress:C,nativeSubagent:k})=>e.jsx(Qi,{toolCall:E,beforeContent:S,progress:C,nativeSubagent:k,onSelectSession:n,workspacePath:r,onOpenArtifact:s,onLoadResult:i},E.id))})]})}function cg(t,n){if(ya(t.name)!=="file")return[];const r=t.name==="apply_patch"?ka(t.arguments,t.result).map(s=>s.path):[t.arguments.file_path??t.arguments.path??t.arguments.notebook_path];return[...new Set(r.filter(s=>typeof s=="string").map(s=>ga(s,n)).filter(s=>!!s))]}function Qi({toolCall:t,onSelectSession:n,beforeContent:r,progress:s,nativeSubagent:i,workspacePath:o,onOpenArtifact:l,onLoadResult:d}){const u=l?cg(t,o):[],f=t.name==="write_file"||t.name==="Write"?e.jsx(ng,{toolCall:t,beforeContent:r,previewPath:u[0],onOpenArtifact:l,onLoadResult:d}):t.name==="read_file"?e.jsx(rg,{toolCall:t,previewPath:u[0],onOpenArtifact:l,onLoadResult:d}):t.name==="str_replace"||t.name==="Edit"?e.jsx(sg,{toolCall:t,previewPath:u[0],onOpenArtifact:l,onLoadResult:d}):e.jsx(lg,{toolCall:t,onSelectSession:n,nativeSubagent:i,previewPaths:u,workspacePath:o,onOpenArtifact:l,onLoadResult:d});return e.jsxs("div",{className:"tool-call-with-progress",children:[f,s&&e.jsx(Bd,{progress:s,compact:!0})]})}function dg({question:t,options:n,fields:r,multiSelect:s,answered:i,answer:o,onAnswer:l}){const[d,u]=a.useState(new Set),[f,p]=a.useState(""),[v,x]=a.useState({}),w=a.useRef(!1),[j,E]=a.useState(!1),[S,C]=a.useState(""),k=async(R,$)=>{if(!(i||w.current)){w.current=!0,E(!0),C("");try{await l(R,$)}catch(F){C(F instanceof Error?F.message:"回答发送失败,请重试。")}finally{w.current=!1,E(!1)}}},z=!!(n!=null&&n.length),M=!!(r!=null&&r.length),H=R=>{i||u($=>{const F=new Set($);return s?F.has(R)?F.delete(R):F.add(R):(F.clear(),F.add(R)),F})},L=()=>{if(d.size===0)return;const R=Array.from(d).map($=>n[$].label);k(R.join(", "),Array.from(d))},T=()=>{const R=Array.from(d).map(F=>n[F].label),$=Object.fromEntries((r??[]).map(F=>{var Ee;return[F.name,((Ee=v[F.name])==null?void 0:Ee.trim())??""]}));!$.model&&R.length>0&&($.model=R[0]),!(!Object.values($).some(Boolean)&&R.length===0)&&k(JSON.stringify({fields:$,selectedOptions:R}),Array.from(d))},A=()=>{f.trim()&&k(f.trim())};return e.jsxs("div",{style:{marginBottom:12},children:[S&&!i&&e.jsx("div",{role:"alert",style:{color:"var(--danger)",marginBottom:8},children:S}),j&&e.jsx("div",{role:"status",children:"正在发送回答…"}),e.jsxs("div",{style:{borderRadius:12,border:"1px solid",borderColor:i?"var(--border-subtle)":"rgba(79,110,247,0.35)",background:i?"var(--bg-deep)":"linear-gradient(135deg, rgba(79,110,247,0.04) 0%, var(--bg-deep) 100%)",overflow:"hidden",transition:"border-color 0.2s ease"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",borderBottom:i?"1px solid var(--border-subtle)":"1px solid rgba(79,110,247,0.15)"},children:[e.jsx("div",{style:{width:24,height:24,borderRadius:6,background:i?"var(--bg-surface)":"rgba(79,110,247,0.1)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:i?e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-muted)",strokeWidth:"2.5",strokeLinecap:"round",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})}):e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}),e.jsx("span",{style:{fontSize:10,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",color:i?"var(--text-muted)":"var(--accent)",flex:1},children:i?"已回答":"向你提问"}),s&&!i&&e.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:10,background:"var(--accent-dim)",color:"var(--accent)",fontWeight:500},children:"可多选"})]}),e.jsx("div",{style:{padding:"12px 14px 8px",fontSize:13,color:"var(--text-primary)",lineHeight:1.6,fontWeight:500,whiteSpace:"pre-wrap"},children:t}),i&&e.jsxs("div",{style:{padding:"6px 14px 12px",fontSize:12,color:"var(--text-secondary)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[e.jsx("span",{style:{fontWeight:500},children:"回答:"}),M?"配置已提交(敏感字段已隐藏)":o]}),z&&!i&&e.jsxs("div",{style:{padding:"4px 14px 6px",display:"flex",flexDirection:"column",gap:6},children:[n.map((R,$)=>{const F=d.has($);return e.jsxs("button",{onClick:()=>H($),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"9px 12px",borderRadius:8,border:"1px solid",borderColor:F?"var(--accent)":"var(--border-subtle)",background:F?"rgba(79,110,247,0.06)":"var(--bg-surface)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-body)",transition:"all 0.15s ease",width:"100%"},children:[e.jsx("div",{style:{width:16,height:16,borderRadius:s?4:8,border:`2px solid ${F?"var(--accent)":"var(--border-subtle)"}`,background:F?"var(--accent)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:1,transition:"all 0.15s ease"},children:F&&e.jsx("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:F?600:500,color:F?"var(--text-primary)":"var(--text-secondary)"},children:R.label}),R.description&&e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2,lineHeight:1.4},children:R.description})]})]},$)}),!M&&e.jsx("button",{onClick:L,disabled:j||d.size===0,style:{marginTop:2,padding:"7px 16px",borderRadius:8,border:"none",background:d.size>0?"var(--accent)":"var(--bg-surface)",color:d.size>0?"white":"var(--text-muted)",cursor:d.size>0?"pointer":"default",fontSize:12,fontWeight:600,fontFamily:"var(--font-body)",alignSelf:"flex-end",transition:"all 0.15s ease"},children:"确认选择"})]}),M&&!i&&e.jsxs("div",{style:{padding:"6px 14px 12px",display:"flex",flexDirection:"column",gap:10},children:[r.map(R=>e.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[e.jsx("span",{style:{fontSize:11.5,fontWeight:600,color:"var(--text-secondary)"},children:R.label}),e.jsx("input",{type:R.type==="secret"?"password":"text",value:v[R.name]??"",onChange:$=>x(F=>({...F,[R.name]:$.target.value})),placeholder:R.description,autoComplete:R.type==="secret"?"off":void 0,style:{padding:"8px 12px",borderRadius:8,border:"1px solid var(--border-subtle)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:13,fontFamily:"var(--font-body)",outline:"none"}}),R.description&&e.jsx("span",{style:{fontSize:10.5,color:"var(--text-muted)",lineHeight:1.4},children:R.description})]},R.name)),e.jsx("button",{onClick:T,disabled:j,style:{padding:"8px 16px",borderRadius:8,border:"none",background:"var(--accent)",color:"white",cursor:"pointer",fontSize:12,fontWeight:600,fontFamily:"var(--font-body)",alignSelf:"flex-end"},children:"确认配置"})]}),!i&&!M&&e.jsxs("div",{style:{padding:"4px 14px 12px",display:"flex",gap:8,borderTop:z?"1px solid var(--border-subtle)":"none",marginTop:z?2:0},children:[e.jsx("input",{type:"text",value:f,onChange:R=>p(R.target.value),onKeyDown:R=>{R.key==="Enter"&&!R.shiftKey&&(R.preventDefault(),A())},placeholder:z?"或输入自定义回答…":"输入你的回答…",style:{flex:1,padding:"8px 12px",borderRadius:8,border:"1px solid var(--border-subtle)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:13,fontFamily:"var(--font-body)",outline:"none",transition:"border-color 0.15s ease"},onFocus:R=>{R.currentTarget.style.borderColor="var(--accent)"},onBlur:R=>{R.currentTarget.style.borderColor="var(--border-subtle)"}}),e.jsx("button",{onClick:A,disabled:j||!f.trim(),style:{padding:"8px 16px",borderRadius:8,border:"none",background:f.trim()?"var(--accent)":"var(--bg-surface)",color:f.trim()?"white":"var(--text-muted)",cursor:f.trim()?"pointer":"default",fontSize:12,fontWeight:600,fontFamily:"var(--font-body)",transition:"all 0.15s ease"},children:"发送"})]})]})]})}const Io={systemBase:{label:"系统基础提示",group:"system"},environment:{label:"运行环境",group:"system"},projectContext:{label:"项目上下文",group:"system"},skills:{label:"技能指令",group:"system"},memory:{label:"Memory",group:"system"},embeddedTools:{label:"系统内嵌工具定义",group:"system"},conversationHistory:{label:"历史用户消息",group:"messages"},currentUserMessage:{label:"当前用户消息",group:"messages"},assistantMessages:{label:"AI 历史回复",group:"messages"},compactionSummary:{label:"上下文压缩摘要",group:"messages"},toolCalls:{label:"工具调用",group:"tools"},toolResults:{label:"工具结果",group:"tools"},nativeToolDefinitions:{label:"原生工具定义",group:"tools"},images:{label:"图片",group:"images"},messageOverhead:{label:"协议与消息开销",group:"overhead"}},Ro={system:{label:"系统",color:"#8b5cf6"},messages:{label:"消息",color:"#4f6ef7"},tools:{label:"工具",color:"#f59e0b"},images:{label:"图片",color:"#ec4899"},overhead:{label:"协议开销",color:"#94a3b8"}},nc=["system","messages","tools","images","overhead"];function ug(t,n){const r=(t==null?void 0:t.maxTokens)??Math.max(1,n*1e3),s=(t==null?void 0:t.totalTokens)??0,i=Object.fromEntries(nc.map(u=>[u,0]));for(const u of(t==null?void 0:t.segments)??[]){const f=Io[u.category];f&&(i[f.group]+=u.tokens)}const o=Math.min(s/r,1),l=o*100,d=l===0?"0%":l<1?`${l.toFixed(2)}%`:l<10?`${l.toFixed(1)}%`:`${Math.round(l)}%`;return{hasUsage:!!t,totalTokens:s,maxTokens:r,ratio:o,percent:Math.round(o*100),percentLabel:d,groups:nc.map(u=>({key:u,label:Ro[u].label,color:Ro[u].color,tokens:i[u]})),details:((t==null?void 0:t.segments)??[]).filter(u=>u.tokens>0).map(u=>{var f,p;return{category:u.category,label:((f=Io[u.category])==null?void 0:f.label)??u.category,color:Ro[((p=Io[u.category])==null?void 0:p.group)??"overhead"].color,tokens:u.tokens}}),requestLabel:t?`${t.providerId} · ${t.modelId} · 第 ${t.requestIndex} 次请求`:void 0}}function ea(t){return t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)}K`:`${t}`}function rc(t,n){return n?t.percentLabel:t.hasUsage?`${ea(t.totalTokens)} / ${ea(t.maxTokens)} · ${t.percentLabel}`:"尚无模型请求"}function pg({usage:t,contextWindowK:n,compact:r=!1}){const[s,i]=a.useState(!1),[o,l]=a.useState(null),d=a.useRef(null),u=a.useMemo(()=>ug(t,n),[t,n]),f=u.ratio>=.85?"var(--danger)":u.ratio>=.6?"#f59e0b":"var(--accent)",p=typeof window>"u"?1024:window.innerWidth;return e.jsxs("div",{className:"context-usage-ribbon",style:{position:"relative",borderBottom:"1px solid var(--border-subtle)"},children:[e.jsx("button",{className:"context-usage-ribbon__button",ref:d,type:"button",onClick:()=>{var x;const v=((x=d.current)==null?void 0:x.getBoundingClientRect())??null;l(v),i(w=>!w)},title:"查看完整请求上下文占用估算",style:{width:"100%",display:"flex",alignItems:"center",gap:10,padding:"6px 10px",border:0,background:"transparent",cursor:"pointer",fontFamily:"var(--font-body)"},children:r?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"context-usage-ribbon__ring",width:"28",height:"28",viewBox:"0 0 28 28","aria-hidden":"true",children:[e.jsx("circle",{cx:"14",cy:"14",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.14"}),e.jsx("circle",{cx:"14",cy:"14",r:"10",fill:"none",stroke:u.hasUsage?f:"currentColor",strokeWidth:"4",strokeLinecap:"round",strokeDasharray:`${u.ratio*62.832} 62.832`,transform:"rotate(-90 14 14)"})]}),e.jsx("span",{className:"context-usage-ribbon__summary context-usage-ribbon__summary--compact",children:rc(u,!0)})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"context-usage-ribbon__label",style:{fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap"},children:"上下文"}),e.jsx("div",{className:"context-usage-ribbon__meter",style:{flex:1,height:6,borderRadius:999,overflow:"hidden",background:"rgba(0,0,0,0.06)",display:"flex"},children:u.groups.map(v=>e.jsx("div",{style:{width:`${Math.max(0,Math.min(v.tokens/u.maxTokens*100,100))}%`,background:v.color,opacity:v.key==="overhead"?.65:1,minWidth:v.tokens>0?1:0}},v.key))}),e.jsx("span",{className:"context-usage-ribbon__summary",style:{fontSize:11,color:u.hasUsage?f:"var(--text-muted)",fontVariantNumeric:"tabular-nums",minWidth:110,textAlign:"right"},children:rc(u,!1)})]})}),s&&o&&e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:()=>i(!1),style:{position:"fixed",inset:0,zIndex:9998,background:"transparent"}}),e.jsxs("div",{style:{position:"fixed",left:r?Math.min(Math.max(8,o.left),Math.max(8,p-Math.min(340,p-16)-8)):Math.max(8,o.left),top:o.top-8,transform:"translateY(-100%)",width:Math.min(r?340:o.width,p-16),maxHeight:"min(520px, calc(100vh - 32px))",overflowY:"auto",zIndex:9999,padding:12,borderRadius:12,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",boxShadow:"var(--shadow-lg)"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[e.jsx("div",{style:{fontSize:12,fontWeight:700,color:"var(--text-primary)"},children:"完整请求上下文估算"}),e.jsx("div",{style:{fontSize:11,color:u.hasUsage?f:"var(--text-muted)",fontVariantNumeric:"tabular-nums"},children:u.hasUsage?u.percentLabel:"暂无"})]}),u.requestLabel&&e.jsx("div",{style:{marginBottom:10,fontSize:10,color:"var(--text-muted)",wordBreak:"break-all"},children:u.requestLabel}),u.hasUsage?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:7},children:u.details.map(v=>{const x=u.totalTokens>0?Math.round(v.tokens/u.totalTokens*100):0;return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:v.color}}),e.jsx("span",{style:{flex:1,fontSize:12,color:"var(--text-secondary)"},children:v.label}),e.jsxs("span",{style:{fontSize:12,color:"var(--text-muted)",fontVariantNumeric:"tabular-nums"},children:[ea(v.tokens)," · ",x,"%"]})]},v.category)})}):e.jsx("div",{style:{padding:"8px 0",fontSize:12,color:"var(--text-muted)"},children:"发送第一条消息后,将显示最新一次模型请求的完整上下文组成。"})]})]})]})}function fg({startedAt:t}){return e.jsxs("div",{className:"agent-activity-indicator",role:"status","aria-live":"polite",children:[e.jsx("span",{className:"agent-activity-icon","aria-hidden":"true",children:e.jsx(aa,{size:17,strokeWidth:1.8})}),e.jsxs("span",{children:["思考中",e.jsx(wa,{startedAt:t})]})]})}function Vd({sections:t,streaming:n=!1,startedAt:r,renderContent:s}){const i=a.useMemo(()=>[...t].sort((f,p)=>f.sectionIndex-p.sectionIndex).map(f=>f.text.trim()).filter(Boolean).join(`
|
|
457
|
+
...`:s;return e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em",marginBottom:5},children:"参数"}),e.jsx("pre",{style:{fontSize:11,color:"var(--text-secondary)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontFamily:"var(--font-mono)",padding:"9px 11px",borderRadius:7,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",maxHeight:n?2e3:200,overflow:"auto",margin:0,lineHeight:1.6,boxSizing:"border-box",maxWidth:"100%"},children:d}),l&&e.jsx("button",{onClick:()=>r(!n),style:{marginTop:4,padding:"2px 10px",borderRadius:5,border:"1px solid var(--border-subtle)",background:"var(--bg-deep)",color:"var(--text-muted)",fontSize:10,cursor:"pointer",fontWeight:500},children:n?"收起":`展开全部 (${o.length} 行)`})]})}function ag({activity:t,workspacePath:n,onOpenArtifact:r}){const s=new Map(t.messages.flatMap(i=>i.role==="tool"&&i.toolCallId?[[i.toolCallId,{content:i.content,isError:i.name==="error"}]]:[]));return e.jsxs("div",{className:"native-subagent-activity",children:[e.jsxs("div",{className:"native-subagent-activity__meta",children:[t.elapsedSeconds!==void 0&&e.jsxs("span",{children:[t.elapsedSeconds," 秒"]}),t.toolUses!==void 0&&e.jsxs("span",{children:[t.toolUses," 次工具调用"]}),t.lastToolName&&e.jsxs("span",{children:["正在使用 ",t.lastToolName]})]}),t.messages.map((i,o)=>{var l;return e.jsxs("div",{className:"native-subagent-activity__entry",children:[i.role==="assistant"&&i.content&&e.jsx("pre",{className:"native-subagent-activity__text",children:i.content}),i.role==="assistant"&&((l=i.toolCalls)==null?void 0:l.map(d=>{const u=s.get(d.id);return e.jsxs("div",{className:"native-subagent-activity__tool",children:[e.jsx(Qi,{toolCall:{...d,...u?{result:u.content,isError:u.isError}:{}},workspacePath:n,onOpenArtifact:r}),u&&e.jsx("pre",{className:`native-subagent-activity__tool-result${u.isError?" native-subagent-activity__tool-result--error":""}`,children:u.content})]},d.id)})),i.role==="tool"&&i.toolCallId&&!t.messages.some(d=>{var u;return(u=d.toolCalls)==null?void 0:u.some(f=>f.id===i.toolCallId)})&&e.jsx(Ts,{label:"工具结果",content:i.content,error:i.name==="error",maxPreviewHeight:180})]},`${i.role}-${o}`)}),t.summary&&e.jsx(Ts,{label:t.status==="failed"?"错误信息":"执行摘要",content:t.summary,error:t.status==="failed",maxPreviewHeight:180}),t.status==="running"&&t.messages.length===0&&!t.summary&&e.jsxs("div",{className:"native-subagent-activity__waiting",children:[e.jsx(zs,{isDone:!1,color:"var(--accent)",size:10}),"子 agent 正在工作"]})]})}function lg({toolCall:t,onSelectSession:n,nativeSubagent:r,previewPaths:s,workspacePath:i,onOpenArtifact:o,onLoadResult:l}){const d=et(Ie=>Ie.runningSessionId),u=Gi(t,l,!!r),{expanded:f,setExpanded:p}=u,v=t.name==="dispatch_agent",x=t.name==="Agent"&&!!r,w=t.arguments.subAgentStatus,j=t.arguments.subAgentDetail,E=t.arguments.subAgentProgress,S=_s(t);a.useEffect(()=>{v&&!w&&E&&p(!0),x&&(r.messages.length>0||r.summary)&&p(!0)},[v,x,r,w,E]);const C=v?w==="failed":x?r.status==="failed":t.isError,k=v?!!w||S&&!d:x?r.status!=="running":S,z=k?C?"var(--danger)":"var(--success)":"var(--accent)",M=C?"var(--danger)":k?"var(--text-muted)":"var(--accent)",H=v?null:va(t.name),L=C?"错误":H?"":x?r.status==="stopped"?"已停止":k?"已完成":"运行中":v?w==="failed"?"失败":k?"已完成":"运行中":k?"完成":"执行中",T=x?r.description:v?(()=>{const We=(t.arguments.task??"").split(`
|
|
458
|
+
`)[0];return We.length>80?We.slice(0,80)+"…":We})():Qh(t.name,t.arguments),A=a.useMemo(()=>t.name==="apply_patch"?Yh(t.arguments,t.result):null,[t.name,t.arguments,t.result]),R=a.useMemo(()=>t.name==="apply_patch"?ka(t.arguments,t.result):[],[t.name,t.arguments,t.result]),$=a.useRef(null),F=t.name==="apply_patch"&&!(A!=null&&A.lineStats)&&!!(t.resultRef&&t.result===void 0&&l)&&!C&&!u.loadingResult&&!u.resultError;a.useEffect(()=>{if(!F||!$.current)return;const Ie=new IntersectionObserver(We=>{We.some(at=>at.isIntersecting)&&(Ie.disconnect(),u.loadResult())});return Ie.observe($.current),()=>Ie.disconnect()},[F,t.id,t.resultRef,l]);const Ee=t.name==="apply_patch"?(A==null?void 0:A.lineStats)??null:t.name==="MultiEdit"?Zh(t.arguments):null,Qe=x?`@${r.agentName??"agent"}`:v?`@${t.arguments.agentName??"agent"}`:t.name==="apply_patch"?Jh(A):Fd(t.name)??t.name,ae=ya(t.name),ke=!k||!!C||!!L,De=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"tool-call-shell__icon",children:e.jsx(di,{name:t.name,color:M})}),e.jsx("span",{className:"tool-call-shell__label",title:H?t.name:void 0,style:{fontFamily:H?"var(--font-body)":"var(--font-mono)",fontSize:11.5,color:"var(--text-primary)",fontWeight:600,flexShrink:0},children:Qe}),T&&e.jsx("span",{className:"tool-call-shell__preview",style:{fontSize:11,fontFamily:"var(--font-mono)",color:"var(--text-muted)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:T}),!T&&e.jsx("span",{style:{flex:1}}),!C&&e.jsx(Oi,{stats:Ee,pending:!k}),t.name==="apply_patch"&&!Ee&&u.loadingResult&&e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",flexShrink:0},children:"行数加载中"}),ke&&e.jsxs("span",{className:"tool-call-shell__state",style:{color:z},children:[e.jsx(zs,{isDone:k,isError:!!C,color:z}),L&&e.jsx("span",{children:L})]})]});return e.jsxs(Vi,{visibilityRef:$,statusColor:z,isDone:k,expanded:f,onToggle:u.toggle,header:De,maxBodyHeight:800,primaryAction:s.length===1&&o?()=>o(s[0]):void 0,primaryActionLabel:s.length===1?`预览文件 ${Ar(s[0])}`:void 0,primaryActionTitle:s.length===1?`预览 ${s[0]}`:void 0,children:[e.jsx(Ki,{toolCall:t,loading:u.loadingResult,error:u.resultError,retry:u.loadResult}),s.length>1&&e.jsx("div",{className:"tool-call-file-list","aria-label":"改动文件",children:s.map(Ie=>e.jsxs("button",{type:"button",onClick:()=>o==null?void 0:o(Ie),"aria-label":`预览文件 ${Ar(Ie)}`,title:`预览 ${Ie}`,children:[e.jsx(ci,{size:12,strokeWidth:1.8,"aria-hidden":"true"}),e.jsx("span",{style:{flex:1},children:Ar(Ie)}),(()=>{const We=R.find(Ge=>ga(String(Ge.path??""),i)===Ie);if(!We)return null;const at=xa(We);return e.jsxs(e.Fragment,{children:[e.jsx("span",{children:at==="add"?"写入":at==="delete"?"删除":"编辑"}),!C&&e.jsx(Oi,{stats:Ld(We),pending:!k})]})})()]},Ie))}),x?e.jsx(ag,{activity:r,workspacePath:i,onOpenArtifact:o}):v?e.jsx(ig,{arguments:t.arguments}):ae==="command"&&typeof t.arguments.command=="string"?e.jsxs(e.Fragment,{children:[typeof t.arguments.cwd=="string"&&t.arguments.cwd&&e.jsxs("div",{style:{fontSize:10,color:"var(--text-muted)",fontFamily:"var(--font-mono)",wordBreak:"break-all"},children:["工作目录 ",t.arguments.cwd]}),e.jsx(Ts,{label:"命令",content:t.arguments.command,maxPreviewLines:6,maxPreviewHeight:160})]}):e.jsx(og,{raw:JSON.stringify(t.arguments,null,2)}),t.result&&!v&&!x&&e.jsx(Ts,{label:t.isError?"错误信息":"返回结果",content:t.result,error:t.isError,maxPreviewHeight:240}),v&&w&&j&&e.jsx(Ts,{label:w==="failed"?"错误信息":"执行摘要",content:j,error:w==="failed",maxPreviewHeight:180}),v&&!w&&E&&(!!d||!S)&&e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em",marginBottom:5},children:"实时输出"}),e.jsxs("pre",{style:{fontSize:11,color:"var(--text-secondary)",whiteSpace:"pre-wrap",wordBreak:"break-all",fontFamily:"var(--font-mono)",padding:"9px 11px",borderRadius:7,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",borderLeft:"3px solid var(--accent)",maxHeight:240,overflow:"auto",margin:0,lineHeight:1.6,boxSizing:"border-box",maxWidth:"100%"},children:[E,e.jsx("span",{style:{display:"inline-block",width:"0.5em",height:"1em",background:"var(--accent)",verticalAlign:"text-bottom",animation:"blink 1s step-end infinite"},children:""})]})]}),v&&!w&&!E&&!!d&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 0",fontSize:11,color:"var(--text-muted)",fontStyle:"italic"},children:[[0,1,2].map(Ie=>e.jsx("span",{style:{width:5,height:5,borderRadius:"50%",background:"var(--accent)",display:"inline-block",animation:"wave 1.1s ease-in-out infinite",animationDelay:`${Ie*.16}s`}},Ie)),"等待子 agent 响应..."]}),v&&t.arguments.subSessionId&&n&&e.jsxs("button",{onClick:()=>n(t.arguments.subSessionId),style:{alignSelf:"flex-start",padding:"4px 10px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--accent-dim)",color:"var(--accent)",fontSize:11,fontWeight:500,cursor:"pointer",display:"flex",alignItems:"center",gap:5,transition:"background 0.15s"},onMouseEnter:Ie=>{Ie.currentTarget.style.background="var(--accent)",Ie.currentTarget.style.color="white"},onMouseLeave:Ie=>{Ie.currentTarget.style.background="var(--accent-dim)",Ie.currentTarget.style.color="var(--accent)"},children:[e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[e.jsx("path",{d:"M12 2a5 5 0 1 0 0 10A5 5 0 0 0 12 2z"}),e.jsx("path",{d:"M12 12c-5.33 0-8 2.67-8 4v2h16v-2c0-1.33-2.67-4-8-4z"})]}),"查看子会话"]})]})}function qd({items:t,onSelectSession:n,workspacePath:r,onOpenArtifact:s,onLoadResult:i}){var j;const[o,l]=a.useState(!1),d=(j=t[0])==null?void 0:j.toolCall,u=d?va(d.name):null;if(!d||!u||t.length<2)return null;const f=t.every(({toolCall:E})=>_s(E)),p=t.filter(({toolCall:E})=>E.isError).length,v=p>0?"var(--danger)":f?"var(--text-muted)":"var(--accent)",x=Fd(d.name)??u.done,w=`${x},${t.length} 项,${o?"收起":"展开"}`;return e.jsxs("div",{className:"tool-call-group",children:[e.jsxs("button",{type:"button",className:"tool-call-group__summary","aria-expanded":o,"aria-label":w,onClick:()=>l(E=>!E),children:[e.jsx("span",{className:"tool-call-group__icon","aria-hidden":"true",children:e.jsx(di,{name:d.name,color:v})}),e.jsx("span",{className:"tool-call-group__label",children:x}),e.jsxs("span",{className:"tool-call-group__count",children:[t.length," 项"]}),e.jsx("span",{className:"tool-call-group__spacer"}),p>0&&e.jsxs("span",{className:"tool-call-group__error",children:[p," 项失败"]}),!f&&e.jsx(zs,{isDone:!1,color:v,size:11}),e.jsx(Kr,{className:"tool-call-group__chevron",size:13,strokeWidth:2.2,"aria-hidden":"true"})]}),o&&e.jsx("div",{className:"tool-call-group__items",children:t.map(({toolCall:E,beforeContent:S,progress:C,nativeSubagent:k})=>e.jsx(Qi,{toolCall:E,beforeContent:S,progress:C,nativeSubagent:k,onSelectSession:n,workspacePath:r,onOpenArtifact:s,onLoadResult:i},E.id))})]})}function cg(t,n){if(ya(t.name)!=="file")return[];const r=t.name==="apply_patch"?ka(t.arguments,t.result).map(s=>s.path):[t.arguments.file_path??t.arguments.path??t.arguments.notebook_path];return[...new Set(r.filter(s=>typeof s=="string").map(s=>ga(s,n)).filter(s=>!!s))]}function Qi({toolCall:t,onSelectSession:n,beforeContent:r,progress:s,nativeSubagent:i,workspacePath:o,onOpenArtifact:l,onLoadResult:d}){const u=l?cg(t,o):[],f=t.name==="write_file"||t.name==="Write"?e.jsx(ng,{toolCall:t,beforeContent:r,previewPath:u[0],onOpenArtifact:l,onLoadResult:d}):t.name==="read_file"?e.jsx(rg,{toolCall:t,previewPath:u[0],onOpenArtifact:l,onLoadResult:d}):t.name==="str_replace"||t.name==="Edit"?e.jsx(sg,{toolCall:t,previewPath:u[0],onOpenArtifact:l,onLoadResult:d}):e.jsx(lg,{toolCall:t,onSelectSession:n,nativeSubagent:i,previewPaths:u,workspacePath:o,onOpenArtifact:l,onLoadResult:d});return e.jsxs("div",{className:"tool-call-with-progress",children:[f,s&&e.jsx(Bd,{progress:s,compact:!0})]})}function dg({question:t,options:n,fields:r,multiSelect:s,answered:i,answer:o,onAnswer:l}){const[d,u]=a.useState(new Set),[f,p]=a.useState(""),[v,x]=a.useState({}),w=a.useRef(!1),[j,E]=a.useState(!1),[S,C]=a.useState(""),k=async(R,$)=>{if(!(i||w.current)){w.current=!0,E(!0),C("");try{await l(R,$)}catch(F){C(F instanceof Error?F.message:"回答发送失败,请重试。")}finally{w.current=!1,E(!1)}}},z=!!(n!=null&&n.length),M=!!(r!=null&&r.length),H=R=>{i||u($=>{const F=new Set($);return s?F.has(R)?F.delete(R):F.add(R):(F.clear(),F.add(R)),F})},L=()=>{if(d.size===0)return;const R=Array.from(d).map($=>n[$].label);k(R.join(", "),Array.from(d))},T=()=>{const R=Array.from(d).map(F=>n[F].label),$=Object.fromEntries((r??[]).map(F=>{var Ee;return[F.name,((Ee=v[F.name])==null?void 0:Ee.trim())??""]}));!$.model&&R.length>0&&($.model=R[0]),!(!Object.values($).some(Boolean)&&R.length===0)&&k(JSON.stringify({fields:$,selectedOptions:R}),Array.from(d))},A=()=>{f.trim()&&k(f.trim())};return e.jsxs("div",{style:{marginBottom:12},children:[S&&!i&&e.jsx("div",{role:"alert",style:{color:"var(--danger)",marginBottom:8},children:S}),j&&e.jsx("div",{role:"status",children:"正在发送回答…"}),e.jsxs("div",{style:{borderRadius:12,border:"1px solid",borderColor:i?"var(--border-subtle)":"rgba(79,110,247,0.35)",background:i?"var(--bg-deep)":"linear-gradient(135deg, rgba(79,110,247,0.04) 0%, var(--bg-deep) 100%)",overflow:"hidden",transition:"border-color 0.2s ease"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"10px 14px",borderBottom:i?"1px solid var(--border-subtle)":"1px solid rgba(79,110,247,0.15)"},children:[e.jsx("div",{style:{width:24,height:24,borderRadius:6,background:i?"var(--bg-surface)":"rgba(79,110,247,0.1)",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:i?e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-muted)",strokeWidth:"2.5",strokeLinecap:"round",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})}):e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",strokeLinecap:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]})}),e.jsx("span",{style:{fontSize:10,fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",color:i?"var(--text-muted)":"var(--accent)",flex:1},children:i?"已回答":"向你提问"}),s&&!i&&e.jsx("span",{style:{fontSize:9,padding:"1px 6px",borderRadius:10,background:"var(--accent-dim)",color:"var(--accent)",fontWeight:500},children:"可多选"})]}),e.jsx("div",{style:{padding:"12px 14px 8px",fontSize:13,color:"var(--text-primary)",lineHeight:1.6,fontWeight:500,whiteSpace:"pre-wrap"},children:t}),i&&e.jsxs("div",{style:{padding:"6px 14px 12px",fontSize:12,color:"var(--text-secondary)",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:[e.jsx("span",{style:{fontWeight:500},children:"回答:"}),M?"配置已提交(敏感字段已隐藏)":o]}),z&&!i&&e.jsxs("div",{style:{padding:"4px 14px 6px",display:"flex",flexDirection:"column",gap:6},children:[n.map((R,$)=>{const F=d.has($);return e.jsxs("button",{onClick:()=>H($),style:{display:"flex",alignItems:"flex-start",gap:10,padding:"9px 12px",borderRadius:8,border:"1px solid",borderColor:F?"var(--accent)":"var(--border-subtle)",background:F?"rgba(79,110,247,0.06)":"var(--bg-surface)",cursor:"pointer",textAlign:"left",fontFamily:"var(--font-body)",transition:"all 0.15s ease",width:"100%"},children:[e.jsx("div",{style:{width:16,height:16,borderRadius:s?4:8,border:`2px solid ${F?"var(--accent)":"var(--border-subtle)"}`,background:F?"var(--accent)":"transparent",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0,marginTop:1,transition:"all 0.15s ease"},children:F&&e.jsx("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:F?600:500,color:F?"var(--text-primary)":"var(--text-secondary)"},children:R.label}),R.description&&e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2,lineHeight:1.4},children:R.description})]})]},$)}),!M&&e.jsx("button",{onClick:L,disabled:j||d.size===0,style:{marginTop:2,padding:"7px 16px",borderRadius:8,border:"none",background:d.size>0?"var(--accent)":"var(--bg-surface)",color:d.size>0?"white":"var(--text-muted)",cursor:d.size>0?"pointer":"default",fontSize:12,fontWeight:600,fontFamily:"var(--font-body)",alignSelf:"flex-end",transition:"all 0.15s ease"},children:"确认选择"})]}),M&&!i&&e.jsxs("div",{style:{padding:"6px 14px 12px",display:"flex",flexDirection:"column",gap:10},children:[r.map(R=>e.jsxs("label",{style:{display:"flex",flexDirection:"column",gap:4},children:[e.jsx("span",{style:{fontSize:11.5,fontWeight:600,color:"var(--text-secondary)"},children:R.label}),e.jsx("input",{type:R.type==="secret"?"password":"text",value:v[R.name]??"",onChange:$=>x(F=>({...F,[R.name]:$.target.value})),placeholder:R.description,autoComplete:R.type==="secret"?"off":void 0,style:{padding:"8px 12px",borderRadius:8,border:"1px solid var(--border-subtle)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:13,fontFamily:"var(--font-body)",outline:"none"}}),R.description&&e.jsx("span",{style:{fontSize:10.5,color:"var(--text-muted)",lineHeight:1.4},children:R.description})]},R.name)),e.jsx("button",{onClick:T,disabled:j,style:{padding:"8px 16px",borderRadius:8,border:"none",background:"var(--accent)",color:"white",cursor:"pointer",fontSize:12,fontWeight:600,fontFamily:"var(--font-body)",alignSelf:"flex-end"},children:"确认配置"})]}),!i&&!M&&e.jsxs("div",{style:{padding:"4px 14px 12px",display:"flex",gap:8,borderTop:z?"1px solid var(--border-subtle)":"none",marginTop:z?2:0},children:[e.jsx("input",{type:"text",value:f,onChange:R=>p(R.target.value),onKeyDown:R=>{R.key==="Enter"&&!R.shiftKey&&(R.preventDefault(),A())},placeholder:z?"或输入自定义回答…":"输入你的回答…",style:{flex:1,padding:"8px 12px",borderRadius:8,border:"1px solid var(--border-subtle)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:13,fontFamily:"var(--font-body)",outline:"none",transition:"border-color 0.15s ease"},onFocus:R=>{R.currentTarget.style.borderColor="var(--accent)"},onBlur:R=>{R.currentTarget.style.borderColor="var(--border-subtle)"}}),e.jsx("button",{onClick:A,disabled:j||!f.trim(),style:{padding:"8px 16px",borderRadius:8,border:"none",background:f.trim()?"var(--accent)":"var(--bg-surface)",color:f.trim()?"white":"var(--text-muted)",cursor:f.trim()?"pointer":"default",fontSize:12,fontWeight:600,fontFamily:"var(--font-body)",transition:"all 0.15s ease"},children:"发送"})]})]})]})}const Io={systemBase:{label:"系统基础提示",group:"system"},environment:{label:"运行环境",group:"system"},projectContext:{label:"项目上下文",group:"system"},skills:{label:"技能指令",group:"system"},memory:{label:"Memory",group:"system"},embeddedTools:{label:"系统内嵌工具定义",group:"system"},conversationHistory:{label:"历史用户消息",group:"messages"},currentUserMessage:{label:"当前用户消息",group:"messages"},assistantMessages:{label:"AI 历史回复",group:"messages"},compactionSummary:{label:"上下文压缩摘要",group:"messages"},toolCalls:{label:"工具调用",group:"tools"},toolResults:{label:"工具结果",group:"tools"},nativeToolDefinitions:{label:"原生工具定义",group:"tools"},images:{label:"图片",group:"images"},messageOverhead:{label:"协议与消息开销",group:"overhead"}},Ro={system:{label:"系统",color:"#8b5cf6"},messages:{label:"消息",color:"#4f6ef7"},tools:{label:"工具",color:"#f59e0b"},images:{label:"图片",color:"#ec4899"},overhead:{label:"协议开销",color:"#94a3b8"}},nc=["system","messages","tools","images","overhead"];function ug(t,n){const r=(t==null?void 0:t.maxTokens)??Math.max(1,n*1e3),s=(t==null?void 0:t.totalTokens)??0,i=Object.fromEntries(nc.map(u=>[u,0]));for(const u of(t==null?void 0:t.segments)??[]){const f=Io[u.category];f&&(i[f.group]+=u.tokens)}const o=Math.min(s/r,1),l=o*100,d=l===0?"0%":l<1?`${l.toFixed(2)}%`:l<10?`${l.toFixed(1)}%`:`${Math.round(l)}%`;return{hasUsage:!!t,totalTokens:s,maxTokens:r,ratio:o,percent:Math.round(o*100),percentLabel:d,groups:nc.map(u=>({key:u,label:Ro[u].label,color:Ro[u].color,tokens:i[u]})),details:((t==null?void 0:t.segments)??[]).filter(u=>u.tokens>0).map(u=>{var f,p;return{category:u.category,label:((f=Io[u.category])==null?void 0:f.label)??u.category,color:Ro[((p=Io[u.category])==null?void 0:p.group)??"overhead"].color,tokens:u.tokens}}),requestLabel:t?`${t.providerId} · ${t.modelId} · 第 ${t.requestIndex} 次请求`:void 0}}function ea(t){return t>=1e3?`${(t/1e3).toFixed(t>=1e4?0:1)}K`:`${t}`}function rc(t,n){return n?t.percentLabel:t.hasUsage?`${ea(t.totalTokens)} / ${ea(t.maxTokens)} · ${t.percentLabel}`:"尚无模型请求"}function pg({usage:t,contextWindowK:n,compact:r=!1}){const[s,i]=a.useState(!1),[o,l]=a.useState(null),d=a.useRef(null),u=a.useMemo(()=>ug(t,n),[t,n]),f=u.ratio>=.85?"var(--danger)":u.ratio>=.6?"#f59e0b":"var(--accent)",p=typeof window>"u"?1024:window.innerWidth;return e.jsxs("div",{className:"context-usage-ribbon",style:{position:"relative",borderBottom:"1px solid var(--border-subtle)"},children:[e.jsx("button",{className:"context-usage-ribbon__button",ref:d,type:"button",onClick:()=>{var x;const v=((x=d.current)==null?void 0:x.getBoundingClientRect())??null;l(v),i(w=>!w)},title:"查看完整请求上下文占用估算",style:{width:"100%",display:"flex",alignItems:"center",gap:10,padding:"6px 10px",border:0,background:"transparent",cursor:"pointer",fontFamily:"var(--font-body)"},children:r?e.jsxs(e.Fragment,{children:[e.jsxs("svg",{className:"context-usage-ribbon__ring",width:"28",height:"28",viewBox:"0 0 28 28","aria-hidden":"true",children:[e.jsx("circle",{cx:"14",cy:"14",r:"10",fill:"none",stroke:"currentColor",strokeWidth:"4",opacity:"0.14"}),e.jsx("circle",{cx:"14",cy:"14",r:"10",fill:"none",stroke:u.hasUsage?f:"currentColor",strokeWidth:"4",strokeLinecap:"round",strokeDasharray:`${u.ratio*62.832} 62.832`,transform:"rotate(-90 14 14)"})]}),e.jsx("span",{className:"context-usage-ribbon__summary context-usage-ribbon__summary--compact",children:rc(u,!0)})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"context-usage-ribbon__label",style:{fontSize:11,color:"var(--text-muted)",whiteSpace:"nowrap"},children:"上下文"}),e.jsx("div",{className:"context-usage-ribbon__meter",style:{flex:1,height:6,borderRadius:999,overflow:"hidden",background:"rgba(0,0,0,0.06)",display:"flex"},children:u.groups.map(v=>e.jsx("div",{style:{width:`${Math.max(0,Math.min(v.tokens/u.maxTokens*100,100))}%`,background:v.color,opacity:v.key==="overhead"?.65:1,minWidth:v.tokens>0?1:0}},v.key))}),e.jsx("span",{className:"context-usage-ribbon__summary",style:{fontSize:11,color:u.hasUsage?f:"var(--text-muted)",fontVariantNumeric:"tabular-nums",minWidth:110,textAlign:"right"},children:rc(u,!1)})]})}),s&&o&&e.jsxs(e.Fragment,{children:[e.jsx("div",{onClick:()=>i(!1),style:{position:"fixed",inset:0,zIndex:9998,background:"transparent"}}),e.jsxs("div",{style:{position:"fixed",left:r?Math.min(Math.max(8,o.left),Math.max(8,p-Math.min(340,p-16)-8)):Math.max(8,o.left),top:o.top-8,transform:"translateY(-100%)",width:Math.min(r?340:o.width,p-16),maxHeight:"min(520px, calc(100vh - 32px))",overflowY:"auto",zIndex:9999,padding:12,borderRadius:12,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",boxShadow:"var(--shadow-lg)"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:4},children:[e.jsx("div",{style:{fontSize:12,fontWeight:700,color:"var(--text-primary)"},children:"完整请求上下文估算"}),e.jsx("div",{style:{fontSize:11,color:u.hasUsage?f:"var(--text-muted)",fontVariantNumeric:"tabular-nums"},children:u.hasUsage?u.percentLabel:"暂无"})]}),u.requestLabel&&e.jsx("div",{style:{marginBottom:10,fontSize:10,color:"var(--text-muted)",wordBreak:"break-all"},children:u.requestLabel}),u.hasUsage?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:7},children:u.details.map(v=>{const x=u.totalTokens>0?Math.round(v.tokens/u.totalTokens*100):0;return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{width:8,height:8,borderRadius:"50%",background:v.color}}),e.jsx("span",{style:{flex:1,fontSize:12,color:"var(--text-secondary)"},children:v.label}),e.jsxs("span",{style:{fontSize:12,color:"var(--text-muted)",fontVariantNumeric:"tabular-nums"},children:[ea(v.tokens)," · ",x,"%"]})]},v.category)})}):e.jsx("div",{style:{padding:"8px 0",fontSize:12,color:"var(--text-muted)"},children:"发送第一条消息后,将显示最新一次模型请求的完整上下文组成。"})]})]})]})}function fg({startedAt:t}){return e.jsxs("div",{className:"agent-activity-indicator",role:"status","aria-live":"polite",children:[e.jsx("span",{className:"agent-activity-icon","aria-hidden":"true",children:e.jsx(aa,{size:17,strokeWidth:1.8})}),e.jsxs("span",{children:["思考中",e.jsx(wa,{startedAt:t})]})]})}function Vd({sections:t,streaming:n=!1,startedAt:r,renderContent:s}){const i=a.useMemo(()=>[...t].sort((f,p)=>f.sectionIndex-p.sectionIndex).map(f=>f.text.trim()).filter(Boolean).join(`
|
|
459
459
|
|
|
460
460
|
`),[t]),o=a.useMemo(()=>(i.split(`
|
|
461
|
-
`).find(p=>p.trim())??"").replace(/^#{1,6}\s+/,"").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1"),[i]),[l,d]=a.useState(n);if(a.useEffect(()=>{d(n)},[n]),!i)return null;const u=n?"思考中":"思考";return e.jsxs("div",{className:"reasoning-summary",children:[e.jsxs("button",{type:"button",className:"reasoning-summary__toggle","aria-expanded":l,"aria-label":`${u},${l?"收起":"展开"}`,onClick:()=>d(f=>!f),children:[e.jsx("span",{className:"reasoning-summary__brain","aria-hidden":"true",children:e.jsx(aa,{size:17,strokeWidth:1.8})}),e.jsxs("span",{className:"reasoning-summary__label",children:[u,n&&r!==void 0&&e.jsx(wa,{startedAt:r})]}),!l&&e.jsx("span",{className:"reasoning-summary__preview",children:o}),e.jsx("span",{className:"reasoning-summary__spacer"}),n&&e.jsx(ot,{className:"reasoning-summary__spinner",size:13,strokeWidth:2,"aria-hidden":"true"}),e.jsx(Kr,{className:"reasoning-summary__chevron",size:13,strokeWidth:2,"aria-hidden":"true"})]}),l&&e.jsx("div",{className:"reasoning-summary__content",children:s(i)})]})}function Gd(t){var r,s;const n=Object.keys(t.presentation??{});return t.role==="assistant"&&!!((r=t.toolCalls)!=null&&r.length)&&!t.isCompactionSummary&&!t.widget&&!t.askUser&&!((s=t.images)!=null&&s.length)&&n.every(i=>i==="executionTrace")}function hg(t){return Gd(t)&&t.content.trim().length===0}function Kd(t){const n=[];for(const r of t){const s=n[n.length-1];if(s&&Gd(s)&&hg(r)){n[n.length-1]={...s,toolCalls:[...s.toolCalls,...r.toolCalls],timestamp:r.timestamp};continue}n.push(r)}return n}function Qd(t){const n=[];for(const r of t){const s=Kh(r.toolCall.name),i=n[n.length-1];s&&(i==null?void 0:i.action)===s?i.items.push(r):n.push({action:s,items:[r]})}return n}function gg({trace:t,loadTrace:n,loadToolResult:r,renderContent:s,runtimeProgress:i,nativeSubagents:o,onSelectSession:l,workspacePath:d,onOpenArtifact:u,refreshSignal:f=0,autoLoad:p=!1}){const v=t.segmentIndex??0,x=`${t.turnId}:${v}`,w=a.useRef(x),j=a.useRef(t.revision),E=a.useRef(f),S=a.useRef(null),[C,k]=a.useState(!1),[z,M]=a.useState(null),[H,L]=a.useState(null);a.useEffect(()=>{w.current=x,S.current=null,k(!1),M(null),L(null),E.current=f},[x]),a.useEffect(()=>{j.current=t.revision,S.current=null,k(!1),M(ae=>(ae==null?void 0:ae.map(ke=>{var Pe;return{...ke,toolCalls:(Pe=ke.toolCalls)==null?void 0:Pe.map(Ie=>Ie.resultRef?{...Ie,resultRef:{...Ie.resultRef,revision:t.revision}}:Ie)}}))??null)},[t.revision]);const T=t.liveMessages??[],A=a.useMemo(()=>Af(z??[],v),[z,v]),R=a.useMemo(()=>zf(A,T),[T,A]),$=z!==null||T.length>0,F=a.useCallback(async(ae=!1)=>{if(!ae&&z)return z;if(!ae&&T.length>0)return T;if(S.current)return S.current;const ke=x,Pe=t.revision;k(!0),L(null);const Ie=n(t);S.current=Ie;try{const We=await Ie;return w.current===ke&&j.current===Pe&&M(We),We}catch(We){throw w.current===ke&&j.current===Pe&&L(We instanceof Error?We.message:"执行过程加载失败"),We}finally{w.current===ke&&j.current===Pe&&(S.current=null,k(!1))}},[T,n,z,x,t]);a.useEffect(()=>{!p||$||F().catch(()=>{})},[p,F,$]),a.useEffect(()=>{!$&&!p||f===0||E.current!==f&&(E.current=f,F(!0).catch(()=>{}))},[p,F,$,f]);const Ee=a.useCallback(async ae=>{const ke=await r(ae);w.current===x&&M(Pe=>Pe&&kd(Pe,ae.itemId,ke.content,ke.isError))},[r,x]),Ke=C?"正在加载执行过程":H?"重新加载执行过程":"查看执行过程";return e.jsx("div",{className:"codex-execution-trace","data-turn-id":t.turnId,children:$?e.jsx(mg,{messages:R,renderContent:s,runtimeProgress:i,nativeSubagents:o,onSelectSession:l,workspacePath:d,onOpenArtifact:u,onLoadResult:Ee}):p&&!H?e.jsxs("div",{className:"codex-execution-trace__status",role:"status","aria-live":"polite","aria-busy":"true",children:[e.jsx("span",{className:"codex-execution-trace__icon","aria-hidden":"true",children:e.jsx(ot,{size:14,strokeWidth:2})}),e.jsx("span",{className:"codex-execution-trace__label",children:"正在加载会话"})]}):e.jsxs("button",{type:"button",className:"codex-execution-trace__load","aria-busy":C||void 0,disabled:C,onClick:()=>void F().catch(()=>{}),children:[e.jsx("span",{className:"codex-execution-trace__icon","aria-hidden":"true",children:C?e.jsx(ot,{size:14,strokeWidth:2}):H?e.jsx(Qc,{size:14,strokeWidth:2}):e.jsx(Wp,{size:14,strokeWidth:1.8})}),e.jsx("span",{className:"codex-execution-trace__label",children:Ke}),H&&e.jsx("span",{className:"codex-execution-trace__error",children:"加载失败"})]})})}function mg({messages:t,renderContent:n,runtimeProgress:r,nativeSubagents:s,onSelectSession:i,workspacePath:o,onOpenArtifact:l,onLoadResult:d}){const u=a.useMemo(()=>{const f=new Map;return Kd(t).map(p=>{const v=(p.toolCalls??[]).map(x=>{const w=typeof x.arguments.file_path=="string"?x.arguments.file_path:void 0,j=x.name==="write_file"&&w?f.get(w):void 0;return x.name==="read_file"&&w&&x.result!==void 0&&!x.isError&&f.set(w,x.result),{toolCall:x,beforeContent:j,progress:wd(r,x.id),nativeSubagent:s[x.id]}});return{message:p,toolGroups:Qd(v)}})},[t,s,r]);return u.length===0?e.jsx("div",{className:"codex-execution-trace__empty",children:"这一轮没有可显示的执行过程"}):e.jsx("div",{className:"codex-execution-trace__timeline",children:u.map(({message:f,toolGroups:p})=>{var v,x,w;return e.jsxs("div",{className:"codex-execution-trace__item",children:[(x=(v=f.presentation)==null?void 0:v.reasoning)!=null&&x.length?e.jsx(Vd,{sections:f.presentation.reasoning,renderContent:n}):null,((w=f.presentation)==null?void 0:w.agentMessagePhase)==="commentary"&&f.content?e.jsx("div",{className:"codex-execution-trace__commentary",children:n(f.content)}):null,p.map(j=>j.action&&j.items.length>1?e.jsx(qd,{items:j.items,onSelectSession:i,workspacePath:o,onOpenArtifact:l,onLoadResult:d},`group-${j.items[0].toolCall.id}`):e.jsx(Qi,{toolCall:j.items[0].toolCall,beforeContent:j.items[0].beforeContent,progress:j.items[0].progress,nativeSubagent:j.items[0].nativeSubagent,onSelectSession:i,workspacePath:o,onOpenArtifact:l,onLoadResult:d},j.items[0].toolCall.id))]},f.id)})})}function xg(t){return t.supported?t.needsSetup||t.status.enabled&&(t.status.permissionScreen!=="granted"||t.status.accessibilityTrusted!==!0):!1}function bg(t){const[n,r]=a.useState(!1);return a.useEffect(()=>{if(!t)return;const s=window.agentApi;if(!(s!=null&&s.desktopLiveSetup)||!(s!=null&&s.onDesktopLiveStatus))return;let i=!0,o=null,l=null;const d=()=>{i&&o&&l&&r(xg({...o,status:l}))},u=()=>void s.desktopLiveSetup().then(p=>{i&&(o={supported:p.supported,needsSetup:p.needsSetup},d())}).catch(()=>{});u();const f=s.onDesktopLiveStatus(p=>{l=p,o!=null&&o.needsSetup&&p.enabled&&p.permissionScreen==="granted"&&p.accessibilityTrusted===!0&&u(),d()});return()=>{i=!1,f()}},[t]),n}function yg({appearanceOpen:t,settingsOpen:n,showSettings:r=!0,hideToBackgroundTitle:s="隐藏到后台",codexReleaseState:i="idle",onHideToBackground:o,onReleaseCodex:l,onOpenHub:d,onOpenDesktopLive:u,desktopLiveOpen:f=!1,filesOpen:p=!1,onToggleFiles:v,onToggleAppearance:x,onOpenSettings:w}){const j=bg(!!u),E=i==="releasing"?"正在停止 AgentRoam 使用此会话":i==="released"?"已停止在 AgentRoam 中使用;Codex Desktop 最长约 30 分钟后可用":"停止在 AgentRoam 中使用(Codex Desktop 最长约 30 分钟后可用)";return e.jsxs("div",{className:"chat-header-actions",style:{WebkitAppRegion:"no-drag"},children:[u&&e.jsxs("button",{type:"button",onClick:u,title:j?"桌面直播与远程控制(待授权)":"桌面直播与远程控制","aria-label":"桌面直播与远程控制","aria-expanded":f,className:`ui-icon-button chat-header-action ${f?"is-active":""}`,style:{position:"relative"},children:[e.jsx(jp,{size:15,"aria-hidden":"true"}),j&&e.jsx("span",{"data-desktop-live-pending":"","aria-hidden":"true",style:{position:"absolute",top:5,right:5,width:7,height:7,borderRadius:"50%",background:"var(--warning, #f59e0b)",border:"1px solid var(--bg-surface, #fff)"}})]}),d&&e.jsx("button",{type:"button",onClick:d,title:"AI Hub · 多模型网页对比","aria-label":"打开 AI Hub",className:"ui-icon-button chat-header-action chat-header-action--ai-hub",children:e.jsx(fp,{size:15,"aria-hidden":"true"})}),v&&e.jsx("button",{type:"button",onClick:v,title:"我的文件","aria-label":"我的文件","aria-expanded":p,className:`ui-icon-button chat-header-action chat-header-action--files ${p?"is-active":""}`,children:e.jsx(Cp,{size:15,"aria-hidden":"true"})}),l&&e.jsx("button",{type:"button",onClick:l,title:E,"aria-label":E,disabled:i!=="idle",className:`ui-icon-button chat-header-action chat-header-action--codex-release is-${i}`,children:i==="releasing"?e.jsx(ot,{size:15,className:"spin","aria-hidden":"true"}):i==="released"?e.jsx(Gr,{size:15,"aria-hidden":"true"}):e.jsx(ld,{size:15,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:o,title:s,"aria-label":"隐藏后台",className:"ui-icon-button chat-header-action chat-header-action--background",children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"3",y:"4",width:"18",height:"14",rx:"2"}),e.jsx("path",{d:"m9 11 3 3 3-3M12 7v7M8 21h8"})]})}),e.jsx("button",{type:"button",onClick:S=>x(S.currentTarget.getBoundingClientRect()),title:"皮肤与布局","aria-label":"皮肤与布局","aria-expanded":t,className:`ui-icon-button chat-header-action chat-header-action--appearance ${t?"is-active":""}`,children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor"}),e.jsx("circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor"}),e.jsx("circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor"}),e.jsx("circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor"}),e.jsx("path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"})]})}),r&&e.jsx("button",{type:"button",onClick:w,title:"设置","aria-label":"设置","aria-expanded":n,className:`ui-icon-button chat-header-action chat-header-action--settings ${n?"is-active":""}`,children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]})}function sc({label:t,title:n,value:r,busy:s,disabled:i,compact:o,onChange:l,children:d}){return e.jsxs("span",{className:`live-view-select${o?" live-view-select--compact":""}`,children:[e.jsx("select",{"aria-label":t,"aria-busy":s,title:n,value:r,disabled:i||s,onChange:u=>l(u.target.value),children:d}),s?e.jsx("span",{className:"live-view-select-icon",role:"status","aria-label":`${t}正在切换`,children:e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"})}):e.jsx(Pi,{size:14,className:"live-view-select-icon","aria-hidden":"true"})]})}const vg=5e3,wg=1e4;class kg{constructor(){this.startedAt=null,this.lastFrameAt=null,this.lastFrameCount=null}begin(n){this.startedAt=n,this.lastFrameAt=null,this.lastFrameCount=null}resume(n){this.startedAt!==null&&(this.startedAt=n),this.lastFrameAt!==null&&(this.lastFrameAt=n)}observe(n,r){return typeof n!="number"||!Number.isFinite(n)||n<0||n===this.lastFrameCount||(this.lastFrameCount=n,n===0)?!1:(this.lastFrameAt=r,!0)}evaluate(n){const r=this.lastFrameAt??this.startedAt;if(r===null)return{state:"streaming",silentForMs:0};const s=Math.max(0,n-r),i=this.lastFrameAt===null?vg:wg;return{state:s>=i?"stalled":"streaming",silentForMs:s}}}var Ui,Xd;class jg{constructor(){cl(this,Ui);this.points=new Map,this.origin=null,this.originDistance=0,this.moved=!1}reset(){this.points.clear(),this.origin=null,this.originDistance=0,this.moved=!1}down(n,r){this.points.size||(this.origin=r,this.moved=!1),this.points.set(n,r),this.points.size>1&&(this.moved=!0),this.originDistance=dl(this,Ui,Xd).call(this)}move(n,r){const s=this.points.get(n);if(!s)return null;const i=[...this.points.values()];if(this.points.set(n,r),this.origin&&Math.hypot(r.x-this.origin.x,r.y-this.origin.y)>8&&(this.moved=!0),this.points.size===1)return this.moved?{scale:1,distanceRatio:1,from:s,to:r,pointers:1}:null;const o=[...this.points.values()],l=p=>({x:(p[0].x+p[1].x)/2,y:(p[0].y+p[1].y)/2}),d=p=>Math.hypot(p[0].x-p[1].x,p[0].y-p[1].y),u=d(i),f=this.originDistance>0?d(o)/this.originDistance:1;return{scale:u>0?d(o)/u:1,distanceRatio:f,from:l(i),to:l(o),pointers:this.points.size}}up(n,r,s=!1){if(!this.points.has(n))return!1;const i=!s&&!this.moved&&this.points.size===1&&!!this.origin&&Math.hypot(r.x-this.origin.x,r.y-this.origin.y)<=8;return this.points.delete(n),s&&(this.moved=!0),this.points.size||this.reset(),i}}Ui=new WeakSet,Xd=function(){const n=[...this.points.values()];return n.length>=2?Math.hypot(n[0].x-n[1].x,n[0].y-n[1].y):0};function Sg(t,n,r){const s=Math.max(t.top,n.top-r.top),i=Math.max(t.left,n.left-r.left),o=Math.min(t.top+t.height,n.top+n.height-r.top),l=Math.min(t.left+t.width,n.left+n.width-r.left);return{top:s,left:i,height:Math.max(0,o-s),width:Math.max(0,l-i)}}function ic(t){const n=t.visualViewport;return{top:(n==null?void 0:n.offsetTop)??0,left:(n==null?void 0:n.offsetLeft)??0,width:(n==null?void 0:n.width)??t.innerWidth,height:(n==null?void 0:n.height)??t.innerHeight}}function Cg(t,n=window){let r=null,s=null;try{n.parent!==n&&n.parent.location.origin===n.location.origin&&(r=n.parent,s=n.frameElement)}catch{}let i=null,o=null;const l=()=>{let p=ic(n);r&&s&&!n.document.fullscreenElement&&(p=Sg(p,ic(r),s.getBoundingClientRect()));for(const[v,x]of Object.entries(p))t.style.setProperty(`--browser-live-${v}`,`${x}px`)},d=()=>{i!==null&&n.cancelAnimationFrame(i),i=n.requestAnimationFrame(()=>{i=null,l()}),o!==null&&n.clearTimeout(o),o=n.setTimeout(l,250)},u=[n,n.document];n.visualViewport&&u.push(n.visualViewport),r&&(u.push(r),r.visualViewport&&u.push(r.visualViewport));const f=["resize","scroll","orientationchange","pageshow","visibilitychange","fullscreenchange"];for(const p of u)for(const v of f)p.addEventListener(v,d);return l(),()=>{for(const p of u)for(const v of f)p.removeEventListener(v,d);i!==null&&n.cancelAnimationFrame(i),o!==null&&n.clearTimeout(o);for(const p of["top","left","width","height"])t.style.removeProperty(`--browser-live-${p}`)}}const Bn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Ig(t,n){var r;try{const s=(r=t==null?void 0:t.getVideoPlaybackQuality)==null?void 0:r.call(t);if(s&&Number.isFinite(s.totalVideoFrames)&&Number.isFinite(s.droppedVideoFrames))return Math.max(0,s.totalVideoFrames-s.droppedVideoFrames)}catch{}return Bn(t==null?void 0:t.webkitDecodedFrameCount)??Bn(n)}function Rg(t){var r,s,i;const n=new Set;for(const o of t??[]){if(((r=o.mimeType)==null?void 0:r.toLowerCase())!=="video/h264")continue;const l=(i=(s=/(?:^|;)\s*profile-level-id=([0-9a-f]{6})/i.exec(o.sdpFmtpLine??""))==null?void 0:s[1])==null?void 0:i.toLowerCase();l!=null&&l.startsWith("64")&&n.add("high"),(!l||l.startsWith("42"))&&n.add("baseline")}return[...n]}function Eg(){var n;if(typeof RTCRtpReceiver>"u"||typeof RTCRtpReceiver.getCapabilities!="function")return["baseline"];const t=Rg((n=RTCRtpReceiver.getCapabilities("video"))==null?void 0:n.codecs);return t.length?t:["baseline"]}function Mg(t){var r,s;const n=(s=(r=/(?:^|;)\s*profile-level-id=([0-9a-f]{6})/i.exec(typeof t=="string"?t:""))==null?void 0:r[1])==null?void 0:s.toLowerCase();if(n!=null&&n.startsWith("64"))return"high";if(!n||n.startsWith("42"))return"baseline"}function Ag(t,n,r=Date.now()){const i=[...typeof t.values=="function"?t.values():t],o=i.find(F=>F.type==="inbound-rtp"&&(F.kind==="video"||F.mediaType==="video"));if(!o)return null;const l=i.find(F=>F.id===o.codecId),d=i.find(F=>F.type==="candidate-pair"&&F.state==="succeeded"&&(F.nominated===!0||F.selected===!0)),u=i.find(F=>F.id===(d==null?void 0:d.localCandidateId)),f=i.find(F=>F.id===(d==null?void 0:d.remoteCandidateId)),p=[u==null?void 0:u.candidateType,f==null?void 0:f.candidateType].map(String),v=["relay","srflx","prflx","host"].find(F=>p.includes(F))??void 0,x=Bn(o.bytesReceived)??0,w=Bn(o.packetsReceived)??0,j=Bn(o.packetsLost)??0,E=Bn(o.framesDropped)??0,S=n?Math.max(1,r-n.at):0,C=n?Math.max(0,w-n.packetsReceived):0,k=n?Math.max(0,j-n.packetsLost):0,z=n?Math.max(0,E-n.framesDropped):0,M=Bn(d==null?void 0:d.currentRoundTripTime),H=Bn(o.jitter),L=typeof o.decoderImplementation=="string"?o.decoderImplementation.slice(0,120):void 0,T=typeof o.powerEfficientDecoder=="boolean"?o.powerEfficientDecoder:void 0,A=L!==void 0||T!==void 0?{implementation:L,powerEfficient:T,acceleration:T===!0?"hardware":T===!1?"software":"unknown"}:void 0,R={codec:typeof(l==null?void 0:l.mimeType)=="string"?l.mimeType.replace(/^video\//i,""):void 0,codecProfile:Mg(l==null?void 0:l.sdpFmtpLine),decoder:A,width:Bn(o.frameWidth),height:Bn(o.frameHeight),fps:Bn(o.framesPerSecond),rttMs:M!==void 0?M*1e3:void 0,jitterMs:H!==void 0?H*1e3:void 0,lossRate:C+k>0?k/(C+k):0,droppedFrames:z,receiveBitrate:n?Math.max(0,Math.round((x-n.bytesReceived)*8e3/S)):void 0,availableBitrate:Bn(d==null?void 0:d.availableIncomingBitrate),candidateType:v,protocol:(u==null?void 0:u.protocol)==="tcp"||(f==null?void 0:f.protocol)==="tcp"?"tcp":d?"udp":void 0};for(const F of Object.keys(R))R[F]===void 0&&delete R[F];const $=Bn(o.framesDecoded);return{sample:R,cursor:{at:r,bytesReceived:x,packetsReceived:w,packetsLost:j,framesDropped:E,...$!==void 0?{framesDecoded:$}:{}}}}function Tg(t){if(!t)return null;const n=[t.candidateType==="relay"?"TURN 中继":t.candidateType?"P2P 直连":null];return t.codec&&n.push(t.codec),t.width&&t.height&&n.push(`${t.width}x${t.height}${t.fps?`@${Math.round(t.fps)}`:""}`),t.receiveBitrate&&n.push(`${(t.receiveBitrate/1e6).toFixed(1)}Mbps`),t.rttMs!==void 0&&n.push(`${Math.round(t.rttMs)}ms`),n.filter(Boolean).join(" · ")||null}function Ng(t){const n=t==null?void 0:t.decoder;if(!n)return null;const r=n.acceleration==="hardware"?"硬件解码":n.acceleration==="software"?"软件解码":"解码方式未知";return n.implementation?`${r} · ${n.implementation}`:r}const _g={"agent-controlled":"Agent 操作中","handoff-requested":"正在交接","user-controlled":"你正在操作","return-requested":"正在归还",resyncing:"Agent 正在同步页面"},zg={smooth:"流畅",hd:"高清",original:"原画"};function Eo(t){return t==="desktop"?"桌面屏幕":t==="ego-browser"?"ego-browser":"内置 Browser"}function oc(t,n,r){var s,i;return t||(((s=n.find(o=>o.agentSessionId===r))==null?void 0:s.id)??((i=n[0])==null?void 0:i.id)??null)}function ac(t){return[t.altKey?"Alt":"",t.ctrlKey?"Control":"",t.metaKey?"Meta":"",t.shiftKey?"Shift":""].filter(Boolean)}function Lg(t){const n=new Uint8Array(t.length*2),r=new DataView(n.buffer);for(let i=0;i<t.length;i+=1){const o=Math.max(-1,Math.min(1,t[i]));r.setInt16(i*2,o<0?o*32768:o*32767,!0)}let s="";for(let i=0;i<n.length;i+=8192)s+=String.fromCharCode(...n.subarray(i,i+8192));return btoa(s)}function Pg(t,n){const r=atob(t),s=Math.floor(r.length/2/n),i=Array.from({length:n},()=>new Float32Array(s));for(let o=0;o<s;o+=1)for(let l=0;l<n;l+=1){const d=(o*n+l)*2,u=r.charCodeAt(d)|r.charCodeAt(d+1)<<8;i[l][o]=(u&32768?u-65536:u)/32768}return i}async function Dg(t){const n=[],r=()=>{for(const i of n.splice(0))i()};let s=!1;t.addEventListener("abort",r);try{if(t.aborted)return null;const i=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});if(n.push(()=>{for(const x of i.getTracks())x.stop()}),t.aborted)return null;const o=window.AudioContext,l=new o({latencyHint:"interactive"});n.push(()=>{l.close().catch(()=>{})});const d=new o({latencyHint:"interactive"});if(n.push(()=>{d.close().catch(()=>{})}),await Promise.all([l.resume(),d.resume()]),t.aborted)return null;const u=d.createGain();u.connect(d.destination);const f=l.createMediaStreamSource(i),p=l.createScriptProcessor(2048,1,1),v=l.createGain();return v.gain.value=0,f.connect(p),p.connect(v),v.connect(l.destination),s=!0,{stream:i,microphoneContext:l,remoteContext:d,remoteGain:u,source:f,processor:p,sink:v,dispose:r}}finally{t.removeEventListener("abort",r),s||r()}}function Wg(t,n){return t?t.state==="user-controlled"&&t.isController===!0&&n.state==="handoff-requested"||t.state==="agent-controlled"&&n.state==="return-requested":!1}const Fg=2;function Bg(t,n,r,s,i=.02){if(!t||!n||!n.width||!n.height)return!1;const o=t.x/n.width-i,l=t.y/n.height-i,d=(t.x+t.w)/n.width+i,u=(t.y+t.h)/n.height+i;return r>=o&&r<=d&&s>=l&&s<=u}function Og(t,n,r=Fg){const s={deltaX:Math.round(t.x-n.x),deltaY:Math.round(t.y-n.y)};return Math.abs(s.deltaX)<r&&Math.abs(s.deltaY)<r?null:s}function $g({open:t,agentSessionId:n,onClose:r}){const s=a.useContext(Qu),i=typeof window>"u"?void 0:window.browserLiveApi,o=a.useRef(null),l=a.useRef(null);a.useLayoutEffect(()=>{if(!(!t||!o.current))return Cg(o.current)},[t]);const[d,u]=a.useState(!1),f=async()=>{const b=l.current;if(b){if(d){document.fullscreenElement===b&&await document.exitFullscreen().catch(()=>{}),u(!1);return}u(!0),b.requestFullscreen&&await b.requestFullscreen().catch(()=>{})}};a.useEffect(()=>{if(!t){u(!1);return}const b=l.current,N=()=>u(document.fullscreenElement===b),D=re=>{re.key==="Escape"&&(document.fullscreenElement===b||b!=null&&b.classList.contains("is-fullscreen"))&&(re.preventDefault(),re.stopPropagation(),document.fullscreenElement===b&&document.exitFullscreen().catch(()=>{}),u(!1))};return document.addEventListener("fullscreenchange",N),document.addEventListener("keydown",D,!0),()=>{document.removeEventListener("fullscreenchange",N),document.removeEventListener("keydown",D,!0),b&&document.fullscreenElement===b&&document.exitFullscreen().catch(()=>{})}},[t]);const[p,v]=a.useState([]),[x,w]=a.useState(null),[j,E]=a.useState(null),[S,C]=a.useState("hd"),[k,z]=a.useState(null),[M,H]=a.useState(null),[L,T]=a.useState(!1),[A,R]=a.useState(0),[$,F]=a.useState(null),[Ee,Ke]=a.useState(!1),[ae,ke]=a.useState(null),[Pe,Ie]=a.useState(!1),[We,at]=a.useState(""),[qe,ne]=a.useState(!1),[be,Ye]=a.useState(null),[W,te]=a.useState(1),[G,le]=a.useState(!1),[pe,ye]=a.useState({width:0,height:0}),we=a.useRef(null),Te=a.useRef(null),dt=a.useRef(!1),lt=a.useRef(null),st=a.useRef(new jg),Tt=a.useRef(W),$e=a.useRef(null);a.useLayoutEffect(()=>{Tt.current=W;const b=$e.current,N=we.current,D=N==null?void 0:N.querySelector(".browser-live-image-hit-area");if(!b||!N||!D)return;const re=D.getBoundingClientRect();N.scrollLeft+=re.left+b.x*re.width-b.clientX,N.scrollTop+=re.top+b.y*re.height-b.clientY,$e.current=null},[W]);const Nt=a.useRef(null),[ct,B]=a.useState(!1),Y=a.useRef(!1),q=a.useRef(null),se=a.useRef(0);a.useEffect(()=>{t||(Ie(!1),at(""),Ye(null))},[t]);const[ee,Ve]=a.useState(!1),ut=a.useRef(null),nn=a.useRef(0),et=a.useRef("none"),Ge=a.useRef(null),Gt=a.useRef(null),[rt,Pt]=a.useState(null),[ht,_t]=a.useState(!1),ln=a.useRef(null),vn=a.useRef(null),[He,Dt]=a.useState("off"),[Xn,$n]=a.useState(null),cn=a.useRef(null),X=a.useRef(null),dn=a.useRef(0),Jt=a.useRef(null),wt=a.useRef(new kg),Rt=a.useRef(!1),[gt,Wt]=a.useState(null),[mt,wn]=a.useState("idle"),[Yn,Jn]=a.useState(!1),[Zt,Hn]=a.useState(!1),en=a.useRef(!1),Zn=a.useRef(!1),kn=a.useRef(null),un=a.useRef(null),ar=a.useRef(null),jn=a.useRef(null),Un=a.useRef(null),Ne=a.useRef(null),it=a.useRef(null),Ht=a.useRef(0),er=a.useRef(0),Wn=a.useRef(0),Ft=a.useRef(null);a.useLayoutEffect(()=>{Y.current=ct,ct&&Ve(!1)},[ct]);const I=a.useMemo(()=>p.find(b=>b.id===x)??null,[x,p]),Q=(I==null?void 0:I.backend)==="desktop",fe=Q&&(I==null?void 0:I.platform)==="win32",ze=(I==null?void 0:I.availability)==="unavailable"&&(I==null?void 0:I.capabilityErrorCode)==="desktop-locked",ge=(I==null?void 0:I.isController)&&I.state==="user-controlled",Ut=I==null?void 0:I.audioCapabilities,rn=!!(Ut!=null&&Ut.fullDuplex&&Ut.systemAudio&&Ut.microphonePlayback&&Ut.selfPlaybackExclusion),pt=!!(I!=null&&I.online&&I.availability==="ready"&&!I.controlledByAnotherViewer);a.useEffect(()=>{if(!t||!i||!x){Pt(null);return}let b=!0;const N=()=>{const re=performance.now();i.request("browser:ping",{t:re}).then(()=>{b&&Pt(Math.round(performance.now()-re))}).catch(()=>{b&&Pt(null)})};N();const D=window.setInterval(N,3e3);return()=>{b=!1,window.clearInterval(D),Pt(null)}},[i,t,x]),a.useEffect(()=>{const b=navigator;if(!ge||!b.wakeLock)return;let N=!1,D=null;return b.wakeLock.request("screen").then(re=>{if(N){re.release();return}D=re,ln.current=re}).catch(()=>{}),()=>{N=!0,D==null||D.release().catch(()=>{}),ln.current=null}},[ge]);const Sn=(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport),hr=Sn&&pe.width&&pe.height?Math.min(pe.width/Sn.width,pe.height/Sn.height):null;a.useEffect(()=>{var b;te(1),le(!1),Te.current=null,st.current.reset(),$e.current=null,q.current=null,vn.current=null,(b=we.current)==null||b.scrollTo(0,0)},[t,x]),a.useEffect(()=>{const b=we.current;if(!t||!b)return;const N=new ResizeObserver(()=>{ye({width:b.clientWidth,height:b.clientHeight})});return N.observe(b),()=>N.disconnect()},[t,Q]),a.useEffect(()=>{const b=we.current;if(!t||!b||!ge||G)return;const N=D=>D.preventDefault();return b.addEventListener("wheel",N,{passive:!1}),()=>b.removeEventListener("wheel",N)},[t,ge,G]);const hs=a.useCallback(()=>{const b=Nt.current;b&&(ct?(b.blur(),B(!1)):(b.focus({preventScroll:!0}),B(!0)))},[ct]);a.useEffect(()=>{var b;(!ge||G)&&ct&&((b=Nt.current)==null||b.blur(),B(!1))},[ge,G,ct]);const lr=a.useCallback(b=>{const N=(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport),D=we.current,re=D==null?void 0:D.querySelector(".browser-live-image-hit-area");if(!b||!N||!D||!re)return;const ce=re.getBoundingClientRect(),Qe=D.getBoundingClientRect(),De=ce.top+b.y/N.height*ce.height,Ue=De+b.h/N.height*ce.height,Xe=16;De>=Qe.top+Xe&&Ue<=Qe.bottom-Xe||(D.scrollTop+=De-(Qe.top+Math.max(Xe,Qe.height*.3)))},[M==null?void 0:M.viewport,I==null?void 0:I.viewport]);a.useEffect(()=>{if(!ct||!q.current)return;const b=window.setTimeout(()=>lr(q.current),420);return()=>window.clearTimeout(b)},[ct,pe.width,pe.height,lr]);const Bt=a.useCallback(b=>{var D;const N=b&&typeof b.input=="object"&&b.input!==null?b.input:b;if(typeof(N==null?void 0:N.editable)=="boolean"){if(!N.editable&&N.kind==="control"){const re=N.bounds;re&&["x","y","w","h"].every(ce=>typeof re[ce]=="number")&&(vn.current={rect:{x:re.x,y:re.y,w:re.w,h:re.h},at:Date.now()});return}if(N.editable){const re=N.bounds,ce=re&&["x","y","w","h"].every(Qe=>typeof re[Qe]=="number")?{x:re.x,y:re.y,w:re.w,h:re.h}:null;ce&&(q.current=ce,se.current=Date.now()),Y.current?lr(ce??q.current):Ve(!0)}else q.current=null,Y.current&&((D=Nt.current)==null||D.blur(),B(!1))}},[lr]),sn=a.useCallback((b=!0)=>{var ce,Qe,De,Ue,Xe;(ce=Ft.current)==null||ce.abort(),Ft.current=null;const N=kn.current;kn.current=null;for(const jt of(N==null?void 0:N.getTracks())??[])jt.stop();(Qe=ar.current)==null||Qe.disconnect(),(De=jn.current)==null||De.disconnect(),(Ue=Un.current)==null||Ue.disconnect(),ar.current=null,jn.current=null,Un.current=null;const D=un.current;un.current=null,D&&D.close().catch(()=>{});const re=Ne.current;Ne.current=null,(Xe=it.current)==null||Xe.disconnect(),it.current=null,Ht.current=0,Wn.current=0,re&&re.close().catch(()=>{}),en.current=!1,Zn.current=!1,Jn(!1),Hn(!1),wn("idle"),b&&i&&x&&i.request("browser:webrtc",{sessionId:x,data:{kind:"audio-stop"}}).catch(()=>{})},[i,x]),tr=a.useCallback(b=>{var zt;if(Zn.current||typeof b.data!="string")return;const N=Ne.current,D=Number(b.sampleRate),re=Number(b.channels);if(!N||!Number.isSafeInteger(D)||!Number.isSafeInteger(re)||re<1||re>2)return;const ce=Pg(b.data,re);if(!((zt=ce[0])!=null&&zt.length))return;const Qe=N.createBuffer(re,ce[0].length,D);for(let $t=0;$t<re;$t+=1)Qe.copyToChannel(ce[$t],$t);const De=N.createBufferSource();De.buffer=Qe;const Ue=it.current;if(!Ue)return;De.connect(Ue);const Xe=N.currentTime,jt=Math.max(Xe+.02,Ht.current);Ht.current=jt-Xe>.35?Xe+.02:jt,De.start(Ht.current),Ht.current+=Qe.duration},[]),gr=a.useCallback(async()=>{var N;if(!i||!x||!ge||!rn||document.visibilityState!=="visible")return;const b=new AbortController;(N=Ft.current)==null||N.abort(),Ft.current=b,F(null),wn("starting");try{const D=await Dg(b.signal);if(!D||b.signal.aborted||document.visibilityState!=="visible"){D==null||D.dispose();return}const{stream:re,microphoneContext:ce,remoteContext:Qe,remoteGain:De,source:Ue,processor:Xe,sink:jt}=D;kn.current=re,un.current=ce,ar.current=Ue,jn.current=Xe,Un.current=jt,Ne.current=Qe,it.current=De,er.current=0,Xe.onaudioprocess=zt=>{if(b.signal.aborted||en.current||!kn.current||!i||!x||Wn.current>=4)return;const $t=new Float32Array(zt.inputBuffer.getChannelData(0));Wn.current+=1,i.request("browser:webrtc",{sessionId:x,data:{kind:"audio-microphone",sequence:++er.current,sampleRate:ce.sampleRate,channels:1,data:Lg($t)}}).catch(()=>{}).finally(()=>{Wn.current=Math.max(0,Wn.current-1)})},await i.request("browser:webrtc",{sessionId:x,data:{kind:"audio-start"}})}catch(D){if(b.signal.aborted)return;sn(!1),wn("failed"),F(D instanceof Error?D.message:"无法开始语音")}},[i,ge,x,sn,rn]);a.useEffect(()=>{t&&ge&&rn||mt!=="idle"&&sn(!0)},[mt,ge,t,sn,rn]),a.useEffect(()=>{const b=()=>{document.visibilityState!=="visible"&&mt!=="idle"&&sn(!0)};return document.addEventListener("visibilitychange",b),()=>document.removeEventListener("visibilitychange",b)},[mt,sn]),a.useEffect(()=>()=>sn(!0),[sn]);const qt=a.useMemo(()=>[{urls:"stun:stun.l.google.com:19302"}],[]),Xr=a.useCallback(async(b,N,D)=>{if(!(!i||!b||!N))try{const re=X.current;X.current=null,re==null||re.close();let ce=X.current;if(ce||(ce=new RTCPeerConnection({iceServers:D!=null&&D.length?D:qt}),ce.onicecandidate=De=>{De.candidate&&i.request("browser:webrtc",{sessionId:b,data:{kind:"ice",candidate:De.candidate.toJSON()}}).catch(()=>{})},ce.ontrack=De=>{const Ue=Jt.current;Ue&&De.streams[0]&&(Ue.srcObject=De.streams[0],Ue.play().catch(()=>{}))},ce.onconnectionstatechange=()=>{if(X.current!==ce)return;const De=ce==null?void 0:ce.connectionState;De==="connected"?Dt("live"):(De==="failed"||De==="disconnected"||De==="closed")&&Dt("failed")},X.current=ce),await ce.setRemoteDescription(N),X.current!==ce)return;const Qe=await ce.createAnswer();if(await ce.setLocalDescription(Qe),X.current!==ce)return;Dt("connecting"),await i.request("browser:webrtc",{sessionId:b,data:{kind:"answer",sdp:ce.localDescription.toJSON()}})}catch{Dt("failed")}},[i,qt]),Yr=a.useCallback((b,N)=>{if(N){if(N.kind==="quality-state"&&["smooth","hd","original"].includes(String(N.quality))){C(String(N.quality)),z(null),typeof N.error=="string"&&F(N.error);return}if(N.kind==="audio-system"){tr(N);return}if(N.kind==="audio-state"){const D=String(N.state);["idle","starting","live","failed"].includes(D)&&wn(D),typeof N.error=="string"&&(F(N.error),sn(!1),wn("failed"));return}if(N.kind==="offer"){typeof N.warning=="string"&&F(N.warning),Xr(b,N.sdp,Array.isArray(N.iceServers)?N.iceServers:void 0);return}if(N.kind==="ice"){const D=N.candidate,re=X.current;re&&D&&re.addIceCandidate(D).catch(()=>{});return}if(N.kind==="state"){const D=String(N.state);D==="connected"?Dt("live"):(D==="failed"||D==="disconnected"||D==="closed")&&Dt("failed")}}},[Xr,tr,sn]),[Mn,cr]=a.useState(null);a.useEffect(()=>{if(!M){cr(null);return}const b=typeof M.data=="string"?`data:${M.mime};base64,${M.data}`:URL.createObjectURL(new Blob([M.data],{type:M.mime}));let N=!1,D=!1;const re=new Image;return re.src=b,re.decode().then(()=>{N||(D=!0,cr(b))}).catch(()=>{}),()=>{N=!0,!D&&b.startsWith("blob:")&&URL.revokeObjectURL(b)}},[M]),a.useEffect(()=>()=>{Mn!=null&&Mn.startsWith("blob:")&&URL.revokeObjectURL(Mn)},[Mn]);const on=a.useCallback(b=>{v(N=>{const D=N.findIndex(ce=>ce.id===b.id);if(D>=0&&Wg(N[D],b))return N;if(D<0)return[b,...N];const re=[...N];return re[D]=b,re.sort((ce,Qe)=>Qe.updatedAt-ce.updatedAt)}),w(N=>oc(N,[b],n)),Ke(!1)},[n]),pn=a.useCallback(async()=>{if(!(!i||!t)){T(!0),F(null);try{const b=await i.request("browser:list");v(b.sessions),w(N=>{const D=N&&b.sessions.some(re=>re.id===N)?N:null;return oc(D,b.sessions,n)}),x&&await i.request("browser:watch",{sessionId:x}).then(N=>on(N.session)).catch(()=>{}),R(N=>N+1)}catch(b){F(b instanceof Error?b.message:"无法读取浏览器会话")}finally{T(!1)}}},[n,i,on,t,x]);a.useEffect(()=>{if(!(!t||!i))return pn(),i.onEvent(b=>{var N;if(b.type==="browser:connection"){(N=X.current)==null||N.close(),X.current=null,Dt("off"),Ke(!1),v([]),H(null),b.connected===!0?pn():F("远程连接已断开,正在重新连接");return}if(b.type==="browser:frame"){const D=b;D.sessionId===x&&H(D);return}if(b.type==="browser:webrtc"){const D=b.data;b.sessionId===x&&Yr(x,D);return}if(b.session&&typeof b.session=="object"&&on(b.session),b.type==="browser:closed"){const D=b.session;D&&(v(re=>re.filter(ce=>ce.id!==D.id)),D.id===x&&(H(null),w(null)))}})},[i,Yr,on,t,pn,x]),a.useEffect(()=>{if(!(!t||!i||!x))return H(null),F(null),Rt.current=!1,Wt(null),i.request("browser:watch",{sessionId:x}).then(b=>on(b.session)).catch(b=>F(b instanceof Error?b.message:"无法观看浏览器")),()=>{i.request("browser:unwatch").catch(()=>{})}},[i,on,t,x]),a.useEffect(()=>{var b,N;if(!t||!i||!ge||!Q||!x){Rt.current=!1,Wt(null),dn.current=0,(b=X.current)==null||b.close(),X.current=null,Jt.current&&(Jt.current.srcObject=null),cn.current=null,$n(null),Dt("off");return}return(N=X.current)==null||N.close(),X.current=null,cn.current=null,$n(null),Dt("connecting"),wt.current.begin(performance.now()),i.request("browser:webrtc",{sessionId:x,data:{kind:"start",receiverProfiles:Eg()}}).catch(()=>Dt("failed")),()=>{var D;(D=X.current)==null||D.close(),X.current=null,Jt.current&&(Jt.current.srcObject=null),cn.current=null,$n(null),i.request("browser:webrtc",{sessionId:x,data:{kind:"stop"}}).catch(()=>{})}},[i,ge,Q,t,x,A]),a.useEffect(()=>{if(!t||!ge||!Q||He!=="failed"||dn.current>=2)return;const b=window.setTimeout(()=>{dn.current+=1,R(N=>N+1)},2e3*(dn.current+1));return()=>window.clearTimeout(b)},[t,ge,Q,He]),a.useEffect(()=>{if(!i||!x||He!=="live"){cn.current=null,$n(null);return}let b=!0,N=!1;const D=Jt.current,re=typeof(D==null?void 0:D.requestVideoFrameCallback)=="function";let ce,Qe=null;wt.current.begin(performance.now());const De=zt=>{!b||document.visibilityState==="hidden"||wt.current.observe(zt,performance.now())&&Rt.current&&(Rt.current=!1,Wt(null),i.request("browser:webrtc",{sessionId:x,data:{kind:"viewer-trace",event:"stall-recovered",...Qe?{sample:Qe}:{}}}).catch(()=>{}))};if(re&&D){const zt=($t,Vn)=>{De(Vn.presentedFrames),b&&(ce=D.requestVideoFrameCallback(zt))};ce=D.requestVideoFrameCallback(zt)}const Ue=()=>{document.visibilityState!=="hidden"&&wt.current.resume(performance.now())};document.addEventListener("visibilitychange",Ue);const Xe=async()=>{const zt=X.current;if(!(!zt||N)){N=!0;try{const $t=await zt.getStats().catch(()=>null);if(!b||zt!==X.current)return;const Vn=performance.now(),zn=$t&&Ag($t,cn.current);zn&&(cn.current=zn.cursor,Qe=zn.sample,$n(zn.sample),i.request("browser:webrtc",{sessionId:x,data:{kind:"stats",...zn.sample}}).catch(()=>{}));const yr=Ig(D,zn==null?void 0:zn.cursor.framesDecoded);re||De(yr);const Je=re||yr!==void 0||!(D!=null&&D.videoWidth);if(document.visibilityState!=="hidden"&&Je&&wt.current.evaluate(Vn).state==="stalled"){const zr=wt.current.evaluate(Vn);wt.current.begin(Vn),Dt(Lt=>Lt==="live"?"failed":Lt),Rt.current=!0,Wt("实时画面超时,已切换为 JPEG 兜底画面"),i.request("browser:webrtc",{sessionId:x,data:{kind:"viewer-trace",event:"jpeg-fallback",silentForMs:zr.silentForMs,...Qe?{sample:Qe}:{}}}).catch(()=>{})}}catch{}finally{N=!1}}};Xe();const jt=window.setInterval(()=>void Xe(),1e3);return()=>{b=!1,window.clearInterval(jt),ce!==void 0&&(D==null||D.cancelVideoFrameCallback(ce)),document.removeEventListener("visibilitychange",Ue)}},[i,x,He]);const qn=a.useCallback(async()=>{if(!(!i||!I)){Ke(!0),F(null);try{const b=await i.request("browser:takeover",{sessionId:I.id});on(b.session)}catch(b){Ke(!1),F(b instanceof Error?b.message:"无法接管浏览器")}}},[i,on,I]),gs=a.useCallback(async()=>{if(!(!i||!I)){Ke(!0),F(null);try{const b=await i.request("browser:return",{sessionId:I.id});on(b.session)}catch(b){Ke(!1),F(b instanceof Error?b.message:"无法归还浏览器")}}},[i,on,I]),mr=a.useCallback(async(b,N)=>{if(!(!i||!x)){ke(b),F(null);try{await i.request("browser:system",{sessionId:x,action:b,...N?{password:N}:{}}),window.setTimeout(()=>R(D=>D+1),800)}catch(D){F(D instanceof Error?D.message:"系统操作失败")}finally{ke(null)}}},[i,x]),An=a.useCallback(async()=>{if(!(!i||!x||!We)){ne(!0),Ye(null);try{await i.request("browser:system",{sessionId:x,action:"unlock",password:We}),at(""),Ie(!1),window.setTimeout(()=>R(b=>b+1),2500)}catch(b){Ye(b instanceof Error?b.message:"解锁失败")}finally{at(""),ne(!1)}}},[i,x,We]),xt=a.useCallback(b=>{!i||j||k||!(I!=null&&I.isController)||I.state!=="user-controlled"||i.request("browser:input",{sessionId:I.id,input:{...b,mobile:window.matchMedia("(pointer: coarse)").matches}}).catch(N=>{F(N instanceof Error?N.message:"浏览器输入失败")})},[i,I,j,k]),kt=a.useCallback((b,N,D=[])=>{xt({kind:"key",action:"down",key:b,code:N,text:"",modifiers:D}),xt({kind:"key",action:"up",key:b,code:N,text:"",modifiers:D})},[xt]),Tn=a.useCallback(b=>{kt(b,`Key${b.toUpperCase()}`,["Control"])},[kt]),fn=a.useCallback(b=>!i||j||k||!(I!=null&&I.isController)||I.state!=="user-controlled"?Promise.resolve(null):i.request("browser:input",{sessionId:I.id,input:{...b,mobile:window.matchMedia("(pointer: coarse)").matches}}).then(N=>N&&typeof N=="object"?N:null).catch(()=>null),[i,I,j,k]),Vt=a.useCallback((b,N)=>{fn({kind:"pointer",action:"up",...b,button:"left",...N&&N>1?{click:N}:{}}).then(Bt)},[Bt,fn]),Nn=a.useRef(!1),nr=a.useRef(""),Nr=a.useCallback(b=>{const N=nr.current;if(b!==N){if(b.startsWith(N)){const D=b.slice(N.length);D&&xt({kind:"key",action:"down",text:D,key:"",code:"",modifiers:[]})}nr.current=b}},[xt]),Ot=(I==null?void 0:I.displays)??null;a.useEffect(()=>{if(!k)return;const b=window.setTimeout(()=>{z(null),F("画质切换未完成,请刷新画面后重试")},14e3);return()=>window.clearTimeout(b)},[k]),a.useEffect(()=>{z(null),C("hd")},[t,x]);const xr=b=>{!i||!pt||j||k||!x||(z(b),i.request("browser:webrtc",{sessionId:x,data:{kind:"quality",quality:b}}).catch(N=>{z(null),F(N instanceof Error?N.message:"画质切换失败")}))};a.useEffect(()=>{if(!j)return;if(Ot!=null&&Ot.some(N=>N.id===j&&N.selected)){E(null);return}const b=window.setTimeout(()=>{E(null),F("切换屏幕未完成,请刷新画面后重试")},14e3);return()=>window.clearTimeout(b)},[Ot,j]),a.useEffect(()=>{E(null)},[t,x]);const Cn=a.useRef(0),dr=a.useCallback(b=>{!i||j||k||!x||!pt||!(Ot!=null&&Ot.some(N=>N.id===b&&!N.selected))||(E(b),i.request("browser:set-display",{sessionId:x,displayId:b}).catch(N=>{E(null),F(N instanceof Error?N.message:"切换屏幕失败")}))},[i,Ot,x,pt,j,k]),_n=a.useCallback(b=>{const N=b.currentTarget.getBoundingClientRect(),D=(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport);if(!D)return null;const re=Math.min(N.width/D.width,N.height/D.height),ce=D.width*re,Qe=D.height*re,De=(N.width-ce)/2,Ue=(N.height-Qe)/2,Xe=(b.clientX-N.left-De)/ce,jt=(b.clientY-N.top-Ue)/Qe;return Xe<0||Xe>1||jt<0||jt>1?null:{x:Xe,y:jt}},[M==null?void 0:M.viewport,I==null?void 0:I.viewport]);if(!t||typeof document>"u")return null;const _r=(I==null?void 0:I.online)&&!I.controlledByAnotherViewer,br=(I==null?void 0:I.availability)==="unavailable"?Q?"桌面直播不可用":"浏览器直播不可用":(I==null?void 0:I.availability)==="starting"?"正在连接画面":Q&&(I==null?void 0:I.state)==="agent-controlled"?"未被远程控制":I?_g[I.state]:Q?"等待桌面直播":"等待浏览器",Ls=(I==null?void 0:I.availability)==="unavailable"?Q?"桌面直播不可用":"浏览器直播不可用":(I==null?void 0:I.availability)==="starting"?"正在连接画面":p.length?"等待第一帧":Q?"暂无桌面直播":"暂无浏览器直播",rr=(I==null?void 0:I.availability)==="unavailable"?I.capabilityError||(Q?"需要在桌面 App 中开启并授予屏幕录制权限":"当前浏览器不支持实时画面传输"):p.length?"画面开始后会自动显示":Q?"在桌面 App 设置中开启「桌面直播与远程控制」后,画面会出现在这里":"Agent 开始浏览网页后,会话会出现在这里",ur=Tg(Xn),Kt=Ng(Xn),Qt=He==="live"?ur||"WebRTC 实时流":He==="connecting"?"正在连接 WebRTC":Mn?"JPEG 兜底":null;return On.createPortal(e.jsxs("div",{ref:o,className:"browser-live-backdrop","data-tab-swipe-ignore":!0,role:"presentation",onMouseDown:b=>{b.target===b.currentTarget&&r()},children:[e.jsxs("section",{ref:l,className:`browser-live-panel ${d?"is-fullscreen":""}`,role:"dialog","aria-modal":"true","aria-label":"浏览器直播",children:[e.jsxs("header",{className:"browser-live-header",children:[e.jsxs("div",{className:"browser-live-heading",children:[e.jsx(bl,{size:17,"aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("strong",{children:"浏览器直播"}),e.jsx("span",{children:I?Eo(I.backend):"实时观看与接管"})]}),s]}),e.jsxs("div",{className:"browser-live-header-actions",children:[e.jsx("button",{type:"button",className:"ui-icon-button",onClick:()=>void f(),title:d?"退出全屏":"全屏","aria-label":d?"退出全屏":"全屏","aria-pressed":d,children:d?e.jsx(vo,{size:17}):e.jsx(vp,{size:17})}),e.jsx("button",{type:"button",className:"ui-icon-button",onClick:()=>void pn(),title:"刷新画面与会话","aria-label":"刷新直播画面与会话",children:e.jsx(da,{size:15,className:L?"spin":void 0,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"ui-icon-button",onClick:r,title:"关闭","aria-label":"关闭浏览器直播",children:e.jsx(Tr,{size:17,"aria-hidden":"true"})})]})]}),e.jsxs("div",{className:`browser-live-surface ${ge?"is-controlling":""} has-zoom ${ge&&!G&&ht?"has-quickkeys":""}`,children:[e.jsxs("div",{className:"browser-live-zoom",role:"group","aria-label":"桌面画面缩放",children:[d&&e.jsxs("button",{type:"button","aria-label":"退出全屏",title:"退出全屏",onClick:()=>void f(),children:[e.jsx(vo,{size:15,"aria-hidden":"true"}),"退出全屏"]}),p.length>1&&e.jsx("div",{className:"browser-live-session-tabs",role:"tablist","aria-label":"切换直播屏幕",children:p.map(b=>e.jsx("button",{type:"button",role:"tab","aria-selected":b.id===x,className:b.id===x?"is-active":"",title:`${Eo(b.backend)} · ${b.title||"浏览器"}`,onClick:()=>w(b.id),children:b.title||Eo(b.backend)},b.id))}),Q&&Ot&&Ot.length>1&&e.jsx(sc,{label:"选择直播屏幕",title:pt?"选择直播屏幕":"其他设备控制中或画面暂不可用",value:(Ot.find(b=>b.selected)??Ot[0]).id,busy:!!j,disabled:!M||!pt||k||Ot.length<2,onChange:dr,children:Ot.map((b,N)=>e.jsx("option",{value:b.id,children:`第 ${N+1} 屏${b.primary?"(主屏)":""}`},b.id))}),Q&&e.jsxs(sc,{label:"视频画质",title:pt?"视频画质":"其他设备控制中或画面暂不可用",value:S,busy:k!==null,disabled:!pt||!!j,compact:!0,onChange:xr,children:[e.jsx("option",{value:"smooth",children:"流畅"}),e.jsx("option",{value:"hd",children:"高清"}),e.jsx("option",{value:"original",children:"原画"})]}),Q&&ge&&rn&&mt!=="live"&&e.jsxs("button",{type:"button","aria-label":"开始语音",title:"开始双向语音",disabled:mt==="starting",onClick:()=>void gr(),children:[mt==="starting"?e.jsx(ot,{size:15,className:"spin","aria-hidden":"true"}):e.jsx(xl,{size:15,"aria-hidden":"true"}),mt==="starting"?"正在连接":"开始语音"]}),Q&&ge&&rn&&mt==="live"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","aria-label":Yn?"取消麦克风静音":"麦克风静音","aria-pressed":Yn,title:Yn?"打开麦克风":"关闭麦克风",onClick:()=>{var N;const b=!en.current;en.current=b;for(const D of((N=kn.current)==null?void 0:N.getAudioTracks())??[])D.enabled=!b;Jn(b)},children:Yn?e.jsx(wp,{size:15,"aria-hidden":"true"}):e.jsx(xl,{size:15,"aria-hidden":"true"})}),e.jsx("button",{type:"button","aria-label":Zt?"取消扬声器静音":"扬声器静音","aria-pressed":Zt,title:Zt?"打开电脑声音":"关闭电脑声音",onClick:()=>{const b=!Zn.current;Zn.current=b,it.current&&(it.current.gain.value=b?0:1),Hn(b),b&&(Ht.current=0)},children:Zt?e.jsx(Dp,{size:15,"aria-hidden":"true"}):e.jsx(cd,{size:15,"aria-hidden":"true"})}),e.jsx("button",{type:"button","aria-label":"结束语音",title:"结束双向语音",onClick:()=>sn(!0),children:e.jsx(Rp,{size:15,"aria-hidden":"true"})})]}),e.jsx("button",{type:"button","aria-label":"缩小桌面画面",title:"缩小",disabled:!M||W<=.5,onClick:()=>te(b=>Math.max(.5,b-.25)),children:e.jsx(pd,{size:16})}),e.jsxs("output",{"aria-label":"桌面缩放比例",children:[Math.round(W*100),"%"]}),e.jsx("button",{type:"button","aria-label":"放大桌面画面",title:"放大",disabled:!M||W>=5,onClick:()=>te(b=>Math.min(5,b+.25)),children:e.jsx(ud,{size:16})}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>{var b;te(1),le(!1),(b=we.current)==null||b.scrollTo(0,0)},children:"适应窗口"}),e.jsxs("button",{type:"button","aria-label":"移动桌面画面","aria-pressed":G,title:"拖动或滚动画面,不发送远程输入",disabled:!M,onClick:()=>le(b=>!b),children:[e.jsx(up,{size:15}),"移动画面"]}),e.jsxs("button",{type:"button","aria-label":"唤起键盘","aria-pressed":ct,title:"唤起/收起键盘(轻点输入框也会自动弹起)",className:ee&&!ct?"is-hint":void 0,disabled:!M||!ge,onClick:()=>{Ve(!1),hs()},children:[e.jsx(yo,{size:15}),"键盘"]}),e.jsxs("button",{type:"button","aria-label":"快捷键条","aria-pressed":ht,title:"展开/收起快捷键(Esc/Tab/复制/粘贴/方向键)",disabled:!M||!ge,onClick:()=>_t(b=>!b),children:[e.jsx(yo,{size:15}),ht?"收起":"快捷键"]}),e.jsxs("button",{type:"button","aria-label":"窗口控制",title:"全屏看不到左上角按钮时用:第 1 次点=退出全屏(ESC + Ctrl+Cmd+F),第 2 次点=关闭窗口(Cmd+W)",disabled:!M||!ge,onClick:()=>{const b=Date.now();if(b-Cn.current<2500){kt("w","KeyW",["Meta"]),Cn.current=0;return}Cn.current=b,kt("Escape","Escape"),window.setTimeout(()=>{kt("f","KeyF",["Control","Meta"])},150)},children:[e.jsx(yo,{size:15}),"窗口"]}),fe&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button","aria-label":"锁屏",title:"锁屏(锁屏后仍可从空态区唤醒或远程解锁)",disabled:!M||!!ae,onClick:()=>void mr("lock"),children:[ae==="lock"?e.jsx(ot,{size:15,className:"spin"}):e.jsx(bp,{size:15}),"锁屏"]}),e.jsxs("button",{type:"button","aria-label":"唤醒屏幕",title:"唤醒显示器或锁屏界面",disabled:!!ae,onClick:()=>void mr("wake"),children:[ae==="wake"?e.jsx(ot,{size:15,className:"spin"}):e.jsx(yl,{size:15}),"唤醒"]})]})]}),ge&&!G&&ht&&e.jsxs("div",{className:"browser-live-quickkeys",role:"group","aria-label":"快捷键",children:[e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("Escape","Escape"),children:"Esc"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("Tab","Tab"),children:"Tab"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("c"),children:"复制"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("v"),children:"粘贴"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("a"),children:"全选"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("z"),children:"撤销"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("s"),children:"保存"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("f"),children:"查找"}),e.jsx("button",{type:"button",disabled:!M,title:"退出当前前台应用(Cmd+Q)",onClick:()=>kt("q","KeyQ",["Meta"]),children:"⌘Q"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("ArrowLeft","ArrowLeft"),children:"←"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("ArrowUp","ArrowUp"),children:"↑"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("ArrowDown","ArrowDown"),children:"↓"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("ArrowRight","ArrowRight"),children:"→"})]}),e.jsx("div",{className:"browser-live-touch-hint",children:"滑动滚动 · 轻点点击 · 双击打开 · 长按拖动 · 按住1秒右键 · 双指缩放"}),e.jsx("div",{ref:we,className:"browser-live-viewport",children:M&&Mn?e.jsxs("div",{className:"browser-live-image-hit-area",style:hr&&Sn?{width:Sn.width*hr*W,height:Sn.height*hr*W,cursor:G?"grab":void 0}:void 0,tabIndex:ge&&!G?0:-1,onContextMenu:b=>b.preventDefault(),onPointerDown:b=>{if(b.pointerType==="touch"){b.preventDefault(),st.current.down(b.pointerId,{x:b.clientX,y:b.clientY}),lt.current=ge&&!G?_n(b):null,b.currentTarget.setPointerCapture(b.pointerId),Ge.current&&window.clearTimeout(Ge.current),et.current="none",ut.current=ge&&!G?{x:b.clientX,y:b.clientY}:null,nn.current=Date.now(),ut.current&&(Ge.current=window.setTimeout(()=>{et.current="armed"},550));return}if(G&&we.current){const D=we.current;Te.current={x:b.clientX,y:b.clientY,left:D.scrollLeft,top:D.scrollTop},b.currentTarget.setPointerCapture(b.pointerId);return}if(!ge)return;const N=_n(b);N&&(dt.current=!0,b.currentTarget.setPointerCapture(b.pointerId),xt({kind:"pointer",action:"down",...N,button:"left"}))},onPointerMove:b=>{if(b.pointerType==="touch"){b.preventDefault();const D=st.current.move(b.pointerId,{x:b.clientX,y:b.clientY}),re=we.current;if(!D||!re)return;const ce=D.pointers>=2&&Math.abs(D.distanceRatio-1)>.05,Qe=Math.max(.5,Math.min(5,Tt.current*D.scale));if(ce&&Qe!==Tt.current){const Ue=b.currentTarget.getBoundingClientRect();$e.current={x:(D.from.x-Ue.left)/Ue.width,y:(D.from.y-Ue.top)/Ue.height,clientX:D.to.x,clientY:D.to.y},Tt.current=Qe,On.flushSync(()=>te(Qe));return}if(Ge.current&&(window.clearTimeout(Ge.current),Ge.current=null),et.current==="armed"&&ut.current){et.current="drag";const Ue=_n(b);Ue&&xt({kind:"pointer",action:"down",...Ue,button:"left"})}if(et.current==="drag"){const Ue=_n(b);Ue&&xt({kind:"pointer",action:"move",...Ue,button:"left"});return}const De=Tt.current<=1.001;if(ge&&!G&&(D.pointers>=2||De)){const Ue=Og(D.from,D.to);if(Ue){const Xe=lt.current??_n(b);Xe&&xt({kind:"pointer",action:"wheel",...Xe,...Ue})}return}re.scrollLeft+=D.from.x-D.to.x,re.scrollTop+=D.from.y-D.to.y;return}if(G&&Te.current&&we.current){const D=Te.current;we.current.scrollTo(D.left+D.x-b.clientX,D.top+D.y-b.clientY);return}if(!ge||!dt.current)return;const N=_n(b);N&&xt({kind:"pointer",action:"move",...N,button:"left"})},onPointerUp:b=>{var D,re;if(b.pointerType==="touch"){b.preventDefault(),Ge.current&&(window.clearTimeout(Ge.current),Ge.current=null);const ce=_n(b);if(lt.current=null,et.current==="armed"&&(et.current="none",(nn.current?Date.now()-nn.current:0)>=800&&ce&&ge&&!G)){st.current.reset(),xt({kind:"pointer",action:"down",...ce,button:"right"}),xt({kind:"pointer",action:"up",...ce,button:"right"});return}if(et.current==="drag"){et.current="none",st.current.reset(),ce&&ge&&xt({kind:"pointer",action:"up",...ce,button:"left"});return}if(st.current.up(b.pointerId,{x:b.clientX,y:b.clientY})&&ce&&ge&&!G){const De=q.current,Ue=De!==null&&Date.now()-se.current<6e4&&Bg(De,(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport),ce.x,ce.y,.03);Ue&&!Y.current?((D=Nt.current)==null||D.focus({preventScroll:!0}),B(!0),Ve(!1)):!Ue&&Y.current&&((re=Nt.current)==null||re.blur(),B(!1));const Xe=(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport),jt=Gt.current;jt!==null&&Date.now()-jt.at<400&&Xe!==void 0&&Math.hypot((ce.x-jt.x)*Xe.width,(ce.y-jt.y)*Xe.height)<Xe.width*.03?(xt({kind:"pointer",action:"down",...ce,button:"left",click:2}),Vt(ce,2),Gt.current=null):(xt({kind:"pointer",action:"down",...ce,button:"left"}),Vt(ce),Gt.current={at:Date.now(),x:ce.x,y:ce.y})}return}if(G){Te.current=null;return}if(!ge)return;const N=_n(b);dt.current=!1,N&&Vt(N)},onPointerCancel:b=>{st.current.up(b.pointerId,{x:b.clientX,y:b.clientY},!0),Te.current=null,dt.current=!1,lt.current=null,Ge.current&&(window.clearTimeout(Ge.current),Ge.current=null),et.current="none"},onLostPointerCapture:b=>{st.current.up(b.pointerId,{x:b.clientX,y:b.clientY},!0)},onWheel:b=>{if(!ge||G)return;const N=_n(b);N&&xt({kind:"pointer",action:"wheel",...N,deltaX:b.deltaX,deltaY:b.deltaY})},onKeyDown:b=>{!ge||G||b.target===Nt.current&&b.key.length===1&&!b.ctrlKey&&!b.metaKey&&!b.altKey||(xt({kind:"key",action:"down",key:b.key,code:b.code,text:b.key.length===1?b.key:"",modifiers:ac(b)}),["Backspace","Tab","Enter","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End","Escape"].includes(b.key)&&b.preventDefault())},onKeyUp:b=>{!ge||G||b.target===Nt.current&&b.key.length===1&&!b.ctrlKey&&!b.metaKey&&!b.altKey||ge&&xt({kind:"key",action:"up",key:b.key,code:b.code,modifiers:ac(b)})},children:[e.jsx("img",{src:Mn,alt:(I==null?void 0:I.title)||"浏览器实时画面",draggable:!1,decoding:"async"}),e.jsx("video",{ref:Jt,className:`browser-live-video ${He==="live"?"is-live":""}`,"aria-label":Q?"桌面实时视频流":"浏览器实时视频流",autoPlay:!0,playsInline:!0,muted:!0}),e.jsx("input",{ref:Nt,className:"browser-live-mobile-input","aria-label":"浏览器键盘输入",defaultValue:"",inputMode:"text",autoCapitalize:"none",autoCorrect:"off",autoComplete:"off",spellCheck:!1,onCompositionStart:()=>{Nn.current=!0},onCompositionEnd:b=>{Nn.current=!1,G||Nr(b.target.value)},onBlur:b=>{Nn.current=!1,nr.current="",b.target.value="",B(!1)},onChange:b=>{!G&&!Nn.current&&Nr(b.target.value)}}),k&&e.jsxs("div",{className:"browser-live-quality-pending",role:"status",children:[e.jsx(ot,{size:13,className:"spin","aria-hidden":"true"}),"正在切换至",zg[k]??k,"画质…"]})]}):e.jsxs("div",{className:"browser-live-empty",children:[L||(I==null?void 0:I.availability)==="starting"?e.jsx(ot,{size:22,className:"spin","aria-hidden":"true"}):e.jsx(bl,{size:24,"aria-hidden":"true"}),e.jsx("strong",{children:L?"正在连接浏览器":Ls}),e.jsx("span",{children:rr}),ze&&e.jsxs("div",{role:"group","aria-label":"锁屏远程操作",style:{display:"flex",gap:8,marginTop:12},children:[e.jsxs("button",{type:"button",className:"browser-live-control-button",disabled:!!ae,onClick:()=>void mr("wake"),children:[ae==="wake"?e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}):e.jsx(yl,{size:14,"aria-hidden":"true"}),"唤醒屏幕"]}),fe&&e.jsxs("button",{type:"button",className:"browser-live-control-button",disabled:qe,onClick:()=>{Ye(null),Ie(!0)},children:[e.jsx(ml,{size:14,"aria-hidden":"true"}),"远程解锁"]})]})]})}),d&&e.jsxs("button",{type:"button",className:"browser-live-exit-fullscreen",onClick:()=>void f(),children:[e.jsx(vo,{size:14,"aria-hidden":"true"}),"退出全屏"]}),ge&&!G&&e.jsxs("div",{className:"browser-live-control-cue",children:[e.jsx(Sp,{size:13,"aria-hidden":"true"})," ",Q?"当前输入会发送到本机":"当前输入会发送到浏览器",Q&&Qt?` · ${Qt}`:"",Q&&Kt?` · ${Kt}`:"",rt!=null?` · 控制 ${rt}ms`:""]})]}),e.jsxs("footer",{className:"browser-live-footer",children:[e.jsxs("div",{className:"browser-live-location",children:[e.jsx("span",{className:`browser-live-status-dot is-${(I==null?void 0:I.state)??"idle"}`,"aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("strong",{children:br}),e.jsx("span",{title:I==null?void 0:I.url,children:(I==null?void 0:I.capabilityError)||(Q?"本机屏幕":I==null?void 0:I.url)||$||"等待可观看的直播会话"})]}),(I==null?void 0:I.url)&&!Q&&e.jsx(lp,{size:13,"aria-hidden":"true"})]}),I&&(ge?e.jsxs("button",{type:"button",className:"browser-live-control-button is-return",onClick:()=>void gs(),disabled:Ee,children:[Ee&&e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}),Q?"结束控制":"归还给 Agent"]}):e.jsxs("button",{type:"button",className:"browser-live-control-button",onClick:()=>void qn(),disabled:!_r||Ee||I.state!=="agent-controlled"||I.availability!=="ready",children:[Ee&&e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}),I.controlledByAnotherViewer?"其他设备操作中":Q?"开始控制":"接管浏览器"]}))]}),($??gt)&&e.jsx("div",{className:"browser-live-error",role:"alert",children:$??gt})]}),Pe&&e.jsx("div",{className:"browser-live-unlock-backdrop",role:"presentation",onMouseDown:b=>{b.target===b.currentTarget&&!qe&&(Ie(!1),at(""),Ye(null))},children:e.jsxs("form",{className:"browser-live-unlock-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"browser-live-unlock-title",onSubmit:b=>{b.preventDefault(),An()},children:[e.jsxs("div",{className:"browser-live-unlock-heading",children:[e.jsx(ml,{size:18,"aria-hidden":"true"}),e.jsx("strong",{id:"browser-live-unlock-title",children:"远程解锁 Windows"})]}),e.jsx("label",{htmlFor:"browser-live-unlock-password",children:"Windows 密码或 PIN"}),e.jsx("input",{id:"browser-live-unlock-password",type:"password",autoComplete:"off",autoFocus:!0,maxLength:256,value:We,disabled:qe,onChange:b=>at(b.target.value)}),be&&e.jsx("p",{role:"alert",children:be}),e.jsxs("div",{className:"browser-live-unlock-actions",children:[e.jsx("button",{type:"button",className:"browser-live-control-button is-return",disabled:qe,onClick:()=>{Ie(!1),at(""),Ye(null)},children:"取消"}),e.jsxs("button",{type:"submit",className:"browser-live-control-button",disabled:qe||!We,children:[qe&&e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}),"解锁"]})]})]})})]}),document.body)}const Hg=[{prompt:"带我熟悉这个项目",Icon:np},{prompt:"帮我排查一个问题",Icon:dd},{prompt:"一起实现一个新想法",Icon:hp}];function Ug(t){return t>=5&&t<9?{title:"早啊。",prompt:"新的一天,想做点什么?"}:t>=9&&t<12?{title:"上午好。",prompt:"今天想一起做点什么?"}:t>=12&&t<14?{title:"中午好。",prompt:"想趁午休推进点什么?"}:t>=14&&t<18?{title:"下午好。",prompt:"这个下午,想做点什么?"}:t>=18&&t<23?{title:"晚上好。",prompt:"今晚想一起做点什么?"}:{title:"夜深了。",prompt:"注意休息,重要的事可以先留给我。"}}const qg={"customer-agent":"Customer Agent",codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode"};function Vg({agentType:t,ready:n,now:r,onSelectPrompt:s}){const i=qg[t],o=Ug((r??new Date).getHours());return e.jsxs("section",{className:"empty-session-welcome","aria-labelledby":"empty-session-welcome-title",children:[e.jsxs("div",{className:"empty-session-welcome__core","aria-hidden":"true",children:[e.jsx("span",{className:"empty-session-welcome__glow"}),e.jsxs("svg",{viewBox:"0 0 120 120",role:"presentation",children:[e.jsx("circle",{className:"empty-session-welcome__orbit empty-session-welcome__orbit--outer",cx:"60",cy:"60",r:"44"}),e.jsx("circle",{className:"empty-session-welcome__orbit empty-session-welcome__orbit--inner",cx:"60",cy:"60",r:"33"}),e.jsx("rect",{className:"empty-session-welcome__diamond",x:"43",y:"43",width:"34",height:"34",rx:"2"}),e.jsx("circle",{className:"empty-session-welcome__pulse",cx:"60",cy:"60",r:"3"})]})]}),e.jsxs("div",{className:"empty-session-welcome__copy",children:[e.jsx("p",{className:"empty-session-welcome__status",children:n?`${i} · 已准备好`:`${i} · 等待配置`}),e.jsx("h2",{id:"empty-session-welcome-title",children:o.title}),e.jsx("p",{className:"empty-session-welcome__prompt",children:n?o.prompt:"配置好 API Key 后,我就能开始。"})]}),e.jsx("div",{className:"empty-session-welcome__starters","aria-label":"开始一个任务",children:Hg.map(({prompt:l,Icon:d})=>e.jsxs("button",{type:"button","data-prompt":l,disabled:!n,onClick:()=>s(l),children:[e.jsx(d,{size:16,strokeWidth:1.8,"aria-hidden":"true"}),e.jsx("span",{children:l})]},l))})]})}function Gg({image:t,onClose:n}){return a.useEffect(()=>{if(!t)return;const r=document.body.style.overflow,s=i=>{i.key==="Escape"&&n()};return document.body.style.overflow="hidden",window.addEventListener("keydown",s),()=>{window.removeEventListener("keydown",s),document.body.style.overflow=r}},[t,n]),t?On.createPortal(e.jsxs("div",{className:"message-image-lightbox",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:r=>{r.target===r.currentTarget&&n()},children:[e.jsx("img",{className:"message-image-lightbox__image",src:t.src,alt:t.alt}),e.jsx("button",{type:"button",className:"message-image-lightbox__close",onClick:n,"aria-label":"关闭图片预览",title:"关闭",autoFocus:!0,children:e.jsx(Tr,{size:22,"aria-hidden":"true"})})]}),document.body):null}const Kg={pending:"⏳",image_generating:"🎨",video_generating:"🎬",done:"✅",error:"❌"};function Qg(t){const{title:n="视频工作台",shots:r=[],status:s="generating",composedVideoUrl:i,isAgentRunning:o}=t,[l,d]=a.useState(!1),[u,f]=a.useState(null);return e.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:"var(--radius-md)",background:"var(--bg-surface)",overflow:"hidden",maxWidth:600},children:[e.jsxs("div",{onClick:()=>d(!l),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",background:"var(--bg-deep)",cursor:"pointer",userSelect:"none",borderBottom:l?"none":"1px solid var(--border-subtle)"},children:[e.jsxs("span",{style:{fontSize:14,fontWeight:600,color:"var(--text-primary)"},children:["🎬 ",n]}),e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[r.filter(p=>p.status==="done").length,"/",r.length," 完成",e.jsx("span",{style:{marginLeft:6,transform:l?"rotate(-90deg)":"none",display:"inline-block",transition:"transform 0.2s"},children:"▼"})]})]}),!l&&e.jsxs("div",{style:{padding:"12px 16px"},children:[e.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:13,marginBottom:12},children:[e.jsx("thead",{children:e.jsxs("tr",{style:{background:"var(--bg-deep)"},children:[e.jsx("th",{style:ni,children:"#"}),e.jsx("th",{style:{...ni,textAlign:"left",minWidth:120},children:"画面描述"}),e.jsx("th",{style:ni,children:"时长"}),e.jsx("th",{style:ni,children:"状态"}),e.jsx("th",{style:ni,children:"预览"})]})}),e.jsx("tbody",{children:r.map(p=>e.jsxs("tr",{style:{borderBottom:"1px solid var(--border-subtle)"},children:[e.jsx("td",{style:ri,children:p.index}),e.jsx("td",{style:{...ri,textAlign:"left",maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:p.description,children:p.description}),e.jsxs("td",{style:ri,children:[p.duration,"s"]}),e.jsxs("td",{style:ri,children:[Kg[p.status]??"⏳",p.error&&e.jsx("span",{style:{color:"var(--danger)",fontSize:11,marginLeft:4},title:p.error,children:"!"})]}),e.jsx("td",{style:ri,children:p.videoUrl?e.jsx("button",{onClick:()=>f(p.videoUrl),style:{background:"var(--accent-dim)",color:"var(--accent)",border:"1px solid rgba(79,110,247,0.22)",borderRadius:6,padding:"2px 8px",fontSize:11,cursor:"pointer"},children:"▶ 播放"}):p.previewImageUrl?e.jsx("img",{src:p.previewImageUrl,alt:`shot-${p.index}`,style:{width:48,height:32,objectFit:"cover",borderRadius:4,border:"1px solid var(--border-subtle)"}}):e.jsx("span",{style:{color:"var(--text-muted)",fontSize:11},children:"—"})})]},p.index))})]}),u&&e.jsx("video",{src:u,controls:!0,autoPlay:!0,style:{width:"100%",borderRadius:8,marginBottom:12,border:"1px solid var(--border-subtle)"}}),i&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-primary)",marginBottom:6},children:"完整视频"}),e.jsx("video",{src:i,controls:!0,style:{width:"100%",borderRadius:8,border:"1px solid var(--border-subtle)"}})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-muted)"},children:[s==="generating"&&e.jsx("span",{children:o===!1?"本轮已结束":"🔄 生成中..."}),s==="preview_ready"&&e.jsx("span",{children:"📷 预览图已就绪"}),s==="video_ready"&&e.jsx("span",{children:"🎬 视频片段已就绪"}),s==="composed"&&e.jsx("span",{children:"✅ 合成完成"})]})]})]})}const ni={padding:"6px 10px",textAlign:"center",fontWeight:600,fontSize:12,color:"var(--text-muted)",borderBottom:"1px solid var(--border-subtle)"},ri={padding:"6px 10px",textAlign:"center",fontSize:13,color:"var(--text-secondary)"},Xg={storyboard_workbench:Qg};function Yg(t,n,r){return!t||n!==t?!1:r===null||r===t}function Jg(t,n,r=Date.now()){return!t||t.sessionId!==n?t:{...t,until:r+9e4}}async function Zg(t){const{text:n,projectId:r,createSession:s,activateSession:i,showUserMessage:o,onSessionCreated:l,isCancelled:d}=t,u=!t.sessionId;let f=t.sessionId??null;if(!f){const p=await s(n.slice(0,60)||"语音任务",r||void 0);if(d!=null&&d())return null;f=p.id}return i(f),o(n,f),u&&l&&await l(f),f}async function lc(t){var i,o,l;const n=((i=t.sessionId)==null?void 0:i.trim())||null,r=!n,s=n??(await t.createSession(t.text.slice(0,60)||"New Session",t.projectId||void 0)).id.trim();if(!s)throw new Error("创建会话失败:服务端未返回会话 ID");return t.activateSession(s),t.showUserMessage(t.text,s),await((o=t.afterUserMessageShown)==null?void 0:o.call(t)),r&&await((l=t.onSessionCreated)==null?void 0:l.call(t,s)),s}function em(t=window){return new Promise(n=>{let r=!1,s;const i=()=>{r||(r=!0,s!==void 0&&t.clearTimeout(s),n())};s=t.setTimeout(i,100),t.requestAnimationFrame(()=>{t.setTimeout(i,0)})})}const tm=/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+|[ \t]*\/[^)\n]+)\)/gi,nm=/`([^`\n]+)`/g,rm=/:codex-file-citation\{([^}\n]*)\}/g,cc=/([A-Za-z][\w-]*)="([^"\n]*)"/g,sm=/\uE200visualize\uE202([^\uE201\n]+)\uE201/g;function ja(t){if(!t.startsWith("/")||t.includes("?")||t.includes("#")||t.includes("\0"))return null;const n=t.match(/^(\/.*):([1-9]\d*)$/);return n?{path:n[1],line:Number(n[2])}:{path:t}}function im(t){const n={};for(const i of t.matchAll(cc)){const o=i[1];if(o!=="path"&&o!=="purpose"||n[o]!==void 0)return null;n[o]=i[2]}if(t.replace(cc,"").trim())return null;const r=ja(n.path??"");if(!r||r.line!==void 0)return null;const s=r.path.slice(r.path.lastIndexOf("/")+1)||r.path;return{path:r.path,label:s}}function om(t){try{const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return null;const{path:r,title:s,mode:i}=n;if(typeof r!="string"||s!==void 0&&typeof s!="string"||i!==void 0&&typeof i!="string")return null;const o=ja(r);if(!o||o.line!==void 0)return null;const l=(s==null?void 0:s.trim())||o.path.slice(o.path.lastIndexOf("/")+1)||o.path;return{path:o.path,label:l}}catch{return null}}function am(t,n){const r=[];let s=0;const i=[...[...t.matchAll(tm)].map(o=>({kind:"markdown",match:o})),...[...t.matchAll(rm)].map(o=>({kind:"citation",match:o})),...[...t.matchAll(sm)].map(o=>({kind:"visualize",match:o})),...[...t.matchAll(nm)].map(o=>({kind:"code",match:o}))].sort((o,l)=>(o.match.index??0)-(l.match.index??0));for(const o of i){const{match:l}=o,d=l.index??0;if(d<s)continue;if(d>s&&r.push({type:"text",value:t.slice(s,d)}),o.kind==="code"){r.push({type:"code",value:l[1]}),s=d+l[0].length;continue}if(o.kind==="citation"){const f=im(l[1]);r.push(f?{type:"artifact",label:f.label,path:f.path,raw:l[0]}:{type:"text",value:l[0]}),s=d+l[0].length;continue}if(o.kind==="visualize"){const f=om(l[1]);r.push(f?{type:"artifact",label:f.label,path:f.path,raw:l[0]}:{type:"text",value:l[0]}),s=d+l[0].length;continue}const u=l[2];if(/^https?:\/\//i.test(u))r.push({type:"link",label:l[1],href:u});else{const f=ja(u.replace(/^[ \t]+/,""));f?r.push({type:"artifact",label:l[1],path:f.path,...f.line?{line:f.line}:{},raw:l[0]}):r.push({type:"text",value:l[0]})}s=d+l[0].length}return s<t.length&&r.push({type:"text",value:t.slice(s)}),r.length>0?r:[{type:"text",value:t}]}function lm(t){return am(t)}function Yd(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function cm(t){const n=Yd(t);return n===void 0?void 0:`${Math.round(n/1e3)} 秒`}function dm(t){return t.role==="user"&&!t.isQueued&&!t.isSteered}function um(t){var n,r,s;return t.role==="assistant"&&!!(t.content.trim()||(n=t.toolCalls)!=null&&n.length||(s=(r=t.presentation)==null?void 0:r.reasoning)!=null&&s.length||t.askUser||t.widget)}function pm(t,n,r){var o;const s=t[n];if((s==null?void 0:s.role)!=="assistant"||!s.content.trim()||(o=s.toolCalls)!=null&&o.length||s.isCompactionSummary)return!1;let i=!r;for(let l=n+1;l<t.length;l++){const d=t[l];if(!d.isCompactionSummary){if(dm(d)){i=!0;break}if(um(d))return!1}}return i}function fm(t,n,r){const s=t[n];if(!s)return{showCopy:!1,showSpeak:!1,showCompletion:!1,compact:!1};if(s.role==="user")return{showCopy:!!s.content,showSpeak:!1,showCompletion:!1,compact:!1};const i=pm(t,n,r);return{showCopy:i,showSpeak:i,showCompletion:i,compact:s.role==="assistant"&&!i&&!s.isCompactionSummary}}const hm=new Set(["image/jpeg","image/png","image/gif","image/webp"]);async function gm(t,n){const r=[],s=[],i=[];for(const l of t){const d=l.type.trim().toLowerCase();d.startsWith("image/")?hm.has(d)?r.push(l):i.push(l):s.push(l)}const o=await Promise.all(r.map(async l=>{try{return{file:l,dataUrl:await n(l)}}catch{return{file:l,dataUrl:null}}}));return{images:o.flatMap(l=>l.dataUrl?[l.dataUrl]:[]),attachments:s,unsupportedImages:i,failedImages:o.flatMap(l=>l.dataUrl?[]:[l.file])}}function Rs(t,n){return n?t[n]:void 0}function mm(t,n){const r=Object.fromEntries(Object.entries(t).filter(([,s])=>s.token!==n.token&&s.sourceSessionId!==n.sourceSessionId));return r[n.sourceSessionId]=n,n.forkSessionId&&(r[n.forkSessionId]=n),r}function xm(t,n){const r=t[n];return r?Object.fromEntries(Object.entries(t).filter(([,s])=>s.token!==r.token)):t}function bm(t,n,r=crypto.randomUUID()){return{token:r,sourceSessionId:t,payload:{...n,images:n.images?[...n.images]:void 0,agentIds:n.agentIds?[...n.agentIds]:void 0,restoreDraftOnFailure:n.restoreDraftOnFailure},sendAttempted:!1}}function dc(t,n){return t.forkSessionId===n&&t.sendAttempted?t:{...t,forkSessionId:n,sendAttempted:!0}}function uc(t){return`occupied-recovery:${t.token}`}function ym(t,n){return!!(t&&n&&(t.sourceSessionId===n||t.forkSessionId===n))}async function pc(t){const n=await t.forkSession(t.sourceSessionId);return t.activateSession(n.id),await t.refreshAndSelect(n),n}const Rr=50,Mo=1,si=1,fc=160;function hc(t){return t.trim().replace(/^\/goal\s+/i,"").replace(/^\$([\w-]+)/,"/$1").trim()}function Ao(t){const r=t.trim().replace(/^每(?:隔)?/,"").match(/^(\d+(?:\.\d+)?)\s*(s|sec|秒|m|min|分钟?|h|hr|小时)$/i);if(r){const o=parseFloat(r[1]),l=r[2].toLowerCase(),d=l==="s"||l==="sec"||l==="秒"?o*1e3:l==="m"||l==="min"||l==="分"||l==="分钟"?o*6e4:o*36e5;return d>=36e5&&d%36e5===0?`每 ${d/36e5} 小时`:d>=6e4&&d%6e4===0?`每 ${d/6e4} 分钟`:`每 ${d/1e3} 秒`}const[s,i]=t.trim().split(/\s+/);return s==="0"&&i&&i!=="*"&&!i.includes("/")&&!i.includes(",")?`每天 ${i.padStart(2,"0")}:00`:`cron: ${t}`}function vm(t){const n=t.split(/(`[^`\n]+`)/g);return n.length<=1?t:e.jsx(e.Fragment,{children:n.map((r,s)=>s%2===1?e.jsx("code",{style:{fontFamily:"var(--font-mono)",fontSize:"0.84em",background:"rgba(17,24,39,0.06)",padding:"1px 5px",borderRadius:4,color:"var(--accent)",border:"1px solid var(--border-subtle)"},children:r.slice(1,-1)},s):e.jsx("span",{children:r},s))})}function Jd(t,n){return t.split(/(\*\*[^*]+\*\*|\*[^*]+\*)/g).map((s,i)=>{const o=`${n}-${i}`;return s.startsWith("**")&&s.endsWith("**")&&s.length>4?e.jsx("strong",{style:{fontWeight:600,color:"var(--text-primary)"},children:s.slice(2,-2)},o):s.startsWith("*")&&s.endsWith("*")&&s.length>2?e.jsx("em",{children:s.slice(1,-1)},o):e.jsx("span",{children:s},o)})}function gc(t,n){return t.split(/(`[^`\n]+`)/g).map((s,i)=>i%2===1?e.jsx("code",{style:{fontFamily:"var(--font-mono)",fontSize:"0.84em",background:"rgba(17,24,39,0.06)",padding:"1px 5px",borderRadius:4,color:"var(--accent)",border:"1px solid var(--border-subtle)"},children:s.slice(1,-1)},`${n}-${i}`):Jd(s,`${n}-${i}`))}function ta(t,n){return lm(t).map((r,s)=>{if(r.type==="code")return e.jsx("code",{style:{fontFamily:"var(--font-mono)",fontSize:"0.84em",background:"rgba(17,24,39,0.06)",padding:"1px 5px",borderRadius:4,color:"var(--accent)",border:"1px solid var(--border-subtle)"},children:r.value},s);if(r.type==="link")return e.jsx("a",{className:"chat-message-link",href:r.href,target:"_blank",rel:"noopener noreferrer",children:gc(r.label,`${s}-label`)},s);if(r.type==="artifact"){if(!n)return e.jsx("span",{children:r.raw},s);const i=r.line?`${r.path}:${r.line}`:r.path,o=r.label.replace(/^`([^`\n]+)`$/,"$1");return e.jsxs("button",{type:"button",className:"chat-message-artifact-link",title:i,"aria-label":`打开交付物 ${o}`,onClick:()=>n(r.path),children:[e.jsx(ci,{size:16,strokeWidth:1.8,"aria-hidden":"true"}),e.jsx("span",{children:gc(r.label,`${s}-label`)})]},s)}return Jd(r.value,`${s}`)})}function wm(t){if(t.length<2)return null;const n=o=>o.replace(/^\|/,"").replace(/\|$/,"").split("|").map(l=>l.trim()),r=n(t[0]),s=t[1].replace(/^\|/,"").replace(/\|$/,"");if(!/^[\s\-:|]+$/.test(s))return null;const i=t.slice(2).map(n);return{headers:r,rows:i}}function km(t,n,r){const s=i=>({padding:"6px 14px",textAlign:"left",fontSize:13,fontWeight:i?600:400,color:i?"var(--text-primary)":"var(--text-secondary)",borderBottom:"1px solid var(--border-subtle)",whiteSpace:"pre-wrap",wordBreak:"break-word"});return e.jsx("div",{style:{margin:"8px 0",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",overflow:"auto",background:"var(--bg-surface)"},children:e.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:13},children:[e.jsx("thead",{children:e.jsx("tr",{style:{background:"var(--bg-deep)"},children:t.map((i,o)=>e.jsx("th",{style:s(!0),children:ta(i,r)},o))})}),e.jsx("tbody",{children:n.map((i,o)=>e.jsx("tr",{style:{background:o%2===0?"transparent":"rgba(0,0,0,0.015)"},children:i.map((l,d)=>e.jsx("td",{style:s(!1),children:ta(l,r)},d))},o))})]})})}function jm(t,n,r){return t.toLowerCase()==="mermaid"?e.jsx(ef,{code:n,complete:r}):e.jsxs("div",{style:{margin:"8px 0",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",overflow:"hidden",background:"var(--bg-surface)"},children:[e.jsx("div",{style:{padding:"4px 10px",background:"var(--bg-deep)",borderBottom:"1px solid var(--border-subtle)",fontSize:10,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em"},children:t||"code"}),e.jsx("pre",{style:{margin:0,padding:"10px 12px",fontSize:12,lineHeight:1.6,fontFamily:"var(--font-mono)",color:"var(--text-secondary)",whiteSpace:"pre-wrap",wordBreak:"break-word",overflow:"auto",maxHeight:420},children:n})]})}function Zd(t,n){const s=t.replace(/(^|\n)(?:[a-z][\w+#.-]{0,20}\n)?(?:复制|copy)\n(?:下载|download)(?:\n|$)/gi,"$1").split(`
|
|
461
|
+
`).find(p=>p.trim())??"").replace(/^#{1,6}\s+/,"").replace(/\*\*([^*]+)\*\*/g,"$1").replace(/`([^`]+)`/g,"$1"),[i]),[l,d]=a.useState(n);if(a.useEffect(()=>{d(n)},[n]),!i)return null;const u=n?"思考中":"思考";return e.jsxs("div",{className:"reasoning-summary",children:[e.jsxs("button",{type:"button",className:"reasoning-summary__toggle","aria-expanded":l,"aria-label":`${u},${l?"收起":"展开"}`,onClick:()=>d(f=>!f),children:[e.jsx("span",{className:"reasoning-summary__brain","aria-hidden":"true",children:e.jsx(aa,{size:17,strokeWidth:1.8})}),e.jsxs("span",{className:"reasoning-summary__label",children:[u,n&&r!==void 0&&e.jsx(wa,{startedAt:r})]}),!l&&e.jsx("span",{className:"reasoning-summary__preview",children:o}),e.jsx("span",{className:"reasoning-summary__spacer"}),n&&e.jsx(ot,{className:"reasoning-summary__spinner",size:13,strokeWidth:2,"aria-hidden":"true"}),e.jsx(Kr,{className:"reasoning-summary__chevron",size:13,strokeWidth:2,"aria-hidden":"true"})]}),l&&e.jsx("div",{className:"reasoning-summary__content",children:s(i)})]})}function Gd(t){var r,s;const n=Object.keys(t.presentation??{});return t.role==="assistant"&&!!((r=t.toolCalls)!=null&&r.length)&&!t.isCompactionSummary&&!t.widget&&!t.askUser&&!((s=t.images)!=null&&s.length)&&n.every(i=>i==="executionTrace")}function hg(t){return Gd(t)&&t.content.trim().length===0}function Kd(t){const n=[];for(const r of t){const s=n[n.length-1];if(s&&Gd(s)&&hg(r)){n[n.length-1]={...s,toolCalls:[...s.toolCalls,...r.toolCalls],timestamp:r.timestamp};continue}n.push(r)}return n}function Qd(t){const n=[];for(const r of t){const s=Kh(r.toolCall.name),i=n[n.length-1];s&&(i==null?void 0:i.action)===s?i.items.push(r):n.push({action:s,items:[r]})}return n}function gg({trace:t,loadTrace:n,loadToolResult:r,renderContent:s,runtimeProgress:i,nativeSubagents:o,onSelectSession:l,workspacePath:d,onOpenArtifact:u,refreshSignal:f=0,autoLoad:p=!1}){const v=t.segmentIndex??0,x=`${t.turnId}:${v}`,w=a.useRef(x),j=a.useRef(t.revision),E=a.useRef(f),S=a.useRef(null),[C,k]=a.useState(!1),[z,M]=a.useState(null),[H,L]=a.useState(null);a.useEffect(()=>{w.current=x,S.current=null,k(!1),M(null),L(null),E.current=f},[x]),a.useEffect(()=>{j.current=t.revision,S.current=null,k(!1),M(ae=>(ae==null?void 0:ae.map(ke=>{var De;return{...ke,toolCalls:(De=ke.toolCalls)==null?void 0:De.map(Ie=>Ie.resultRef?{...Ie,resultRef:{...Ie.resultRef,revision:t.revision}}:Ie)}}))??null)},[t.revision]);const T=t.liveMessages??[],A=a.useMemo(()=>Af(z??[],v),[z,v]),R=a.useMemo(()=>zf(A,T),[T,A]),$=z!==null||T.length>0,F=a.useCallback(async(ae=!1)=>{if(!ae&&z)return z;if(!ae&&T.length>0)return T;if(S.current)return S.current;const ke=x,De=t.revision;k(!0),L(null);const Ie=n(t);S.current=Ie;try{const We=await Ie;return w.current===ke&&j.current===De&&M(We),We}catch(We){throw w.current===ke&&j.current===De&&L(We instanceof Error?We.message:"执行过程加载失败"),We}finally{w.current===ke&&j.current===De&&(S.current=null,k(!1))}},[T,n,z,x,t]);a.useEffect(()=>{!p||$||F().catch(()=>{})},[p,F,$]),a.useEffect(()=>{!$&&!p||f===0||E.current!==f&&(E.current=f,F(!0).catch(()=>{}))},[p,F,$,f]);const Ee=a.useCallback(async ae=>{const ke=await r(ae);w.current===x&&M(De=>De&&kd(De,ae.itemId,ke.content,ke.isError))},[r,x]),Qe=C?"正在加载执行过程":H?"重新加载执行过程":"查看执行过程";return e.jsx("div",{className:"codex-execution-trace","data-turn-id":t.turnId,children:$?e.jsx(mg,{messages:R,renderContent:s,runtimeProgress:i,nativeSubagents:o,onSelectSession:l,workspacePath:d,onOpenArtifact:u,onLoadResult:Ee}):p&&!H?e.jsxs("div",{className:"codex-execution-trace__status",role:"status","aria-live":"polite","aria-busy":"true",children:[e.jsx("span",{className:"codex-execution-trace__icon","aria-hidden":"true",children:e.jsx(ot,{size:14,strokeWidth:2})}),e.jsx("span",{className:"codex-execution-trace__label",children:"正在加载会话"})]}):e.jsxs("button",{type:"button",className:"codex-execution-trace__load","aria-busy":C||void 0,disabled:C,onClick:()=>void F().catch(()=>{}),children:[e.jsx("span",{className:"codex-execution-trace__icon","aria-hidden":"true",children:C?e.jsx(ot,{size:14,strokeWidth:2}):H?e.jsx(Qc,{size:14,strokeWidth:2}):e.jsx(Wp,{size:14,strokeWidth:1.8})}),e.jsx("span",{className:"codex-execution-trace__label",children:Qe}),H&&e.jsx("span",{className:"codex-execution-trace__error",children:"加载失败"})]})})}function mg({messages:t,renderContent:n,runtimeProgress:r,nativeSubagents:s,onSelectSession:i,workspacePath:o,onOpenArtifact:l,onLoadResult:d}){const u=a.useMemo(()=>{const f=new Map;return Kd(t).map(p=>{const v=(p.toolCalls??[]).map(x=>{const w=typeof x.arguments.file_path=="string"?x.arguments.file_path:void 0,j=x.name==="write_file"&&w?f.get(w):void 0;return x.name==="read_file"&&w&&x.result!==void 0&&!x.isError&&f.set(w,x.result),{toolCall:x,beforeContent:j,progress:wd(r,x.id),nativeSubagent:s[x.id]}});return{message:p,toolGroups:Qd(v)}})},[t,s,r]);return u.length===0?e.jsx("div",{className:"codex-execution-trace__empty",children:"这一轮没有可显示的执行过程"}):e.jsx("div",{className:"codex-execution-trace__timeline",children:u.map(({message:f,toolGroups:p})=>{var v,x,w;return e.jsxs("div",{className:"codex-execution-trace__item",children:[(x=(v=f.presentation)==null?void 0:v.reasoning)!=null&&x.length?e.jsx(Vd,{sections:f.presentation.reasoning,renderContent:n}):null,((w=f.presentation)==null?void 0:w.agentMessagePhase)==="commentary"&&f.content?e.jsx("div",{className:"codex-execution-trace__commentary",children:n(f.content)}):null,p.map(j=>j.action&&j.items.length>1?e.jsx(qd,{items:j.items,onSelectSession:i,workspacePath:o,onOpenArtifact:l,onLoadResult:d},`group-${j.items[0].toolCall.id}`):e.jsx(Qi,{toolCall:j.items[0].toolCall,beforeContent:j.items[0].beforeContent,progress:j.items[0].progress,nativeSubagent:j.items[0].nativeSubagent,onSelectSession:i,workspacePath:o,onOpenArtifact:l,onLoadResult:d},j.items[0].toolCall.id))]},f.id)})})}function xg(t){return t.supported?t.needsSetup||t.status.enabled&&(t.status.permissionScreen!=="granted"||t.status.accessibilityTrusted!==!0):!1}function bg(t){const[n,r]=a.useState(!1);return a.useEffect(()=>{if(!t)return;const s=window.agentApi;if(!(s!=null&&s.desktopLiveSetup)||!(s!=null&&s.onDesktopLiveStatus))return;let i=!0,o=null,l=null;const d=()=>{i&&o&&l&&r(xg({...o,status:l}))},u=()=>void s.desktopLiveSetup().then(p=>{i&&(o={supported:p.supported,needsSetup:p.needsSetup},d())}).catch(()=>{});u();const f=s.onDesktopLiveStatus(p=>{l=p,o!=null&&o.needsSetup&&p.enabled&&p.permissionScreen==="granted"&&p.accessibilityTrusted===!0&&u(),d()});return()=>{i=!1,f()}},[t]),n}function yg({appearanceOpen:t,settingsOpen:n,showSettings:r=!0,hideToBackgroundTitle:s="隐藏到后台",codexReleaseState:i="idle",onHideToBackground:o,onReleaseCodex:l,onOpenHub:d,onOpenDesktopLive:u,desktopLiveOpen:f=!1,filesOpen:p=!1,onToggleFiles:v,onToggleAppearance:x,onOpenSettings:w}){const j=bg(!!u),E=i==="releasing"?"正在停止 AgentRoam 使用此会话":i==="released"?"已停止在 AgentRoam 中使用;Codex Desktop 最长约 30 分钟后可用":"停止在 AgentRoam 中使用(Codex Desktop 最长约 30 分钟后可用)";return e.jsxs("div",{className:"chat-header-actions",style:{WebkitAppRegion:"no-drag"},children:[u&&e.jsxs("button",{type:"button",onClick:u,title:j?"桌面直播与远程控制(待授权)":"桌面直播与远程控制","aria-label":"桌面直播与远程控制","aria-expanded":f,className:`ui-icon-button chat-header-action ${f?"is-active":""}`,style:{position:"relative"},children:[e.jsx(jp,{size:15,"aria-hidden":"true"}),j&&e.jsx("span",{"data-desktop-live-pending":"","aria-hidden":"true",style:{position:"absolute",top:5,right:5,width:7,height:7,borderRadius:"50%",background:"var(--warning, #f59e0b)",border:"1px solid var(--bg-surface, #fff)"}})]}),d&&e.jsx("button",{type:"button",onClick:d,title:"AI Hub · 多模型网页对比","aria-label":"打开 AI Hub",className:"ui-icon-button chat-header-action chat-header-action--ai-hub",children:e.jsx(fp,{size:15,"aria-hidden":"true"})}),v&&e.jsx("button",{type:"button",onClick:v,title:"我的文件","aria-label":"我的文件","aria-expanded":p,className:`ui-icon-button chat-header-action chat-header-action--files ${p?"is-active":""}`,children:e.jsx(Cp,{size:15,"aria-hidden":"true"})}),l&&e.jsx("button",{type:"button",onClick:l,title:E,"aria-label":E,disabled:i!=="idle",className:`ui-icon-button chat-header-action chat-header-action--codex-release is-${i}`,children:i==="releasing"?e.jsx(ot,{size:15,className:"spin","aria-hidden":"true"}):i==="released"?e.jsx(Gr,{size:15,"aria-hidden":"true"}):e.jsx(ld,{size:15,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:o,title:s,"aria-label":"隐藏后台",className:"ui-icon-button chat-header-action chat-header-action--background",children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"3",y:"4",width:"18",height:"14",rx:"2"}),e.jsx("path",{d:"m9 11 3 3 3-3M12 7v7M8 21h8"})]})}),e.jsx("button",{type:"button",onClick:S=>x(S.currentTarget.getBoundingClientRect()),title:"皮肤与布局","aria-label":"皮肤与布局","aria-expanded":t,className:`ui-icon-button chat-header-action chat-header-action--appearance ${t?"is-active":""}`,children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor"}),e.jsx("circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor"}),e.jsx("circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor"}),e.jsx("circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor"}),e.jsx("path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z"})]})}),r&&e.jsx("button",{type:"button",onClick:w,title:"设置","aria-label":"设置","aria-expanded":n,className:`ui-icon-button chat-header-action chat-header-action--settings ${n?"is-active":""}`,children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("circle",{cx:"12",cy:"12",r:"3"}),e.jsx("path",{d:"M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"})]})})]})}function sc({label:t,title:n,value:r,busy:s,disabled:i,compact:o,onChange:l,children:d}){return e.jsxs("span",{className:`live-view-select${o?" live-view-select--compact":""}`,children:[e.jsx("select",{"aria-label":t,"aria-busy":s,title:n,value:r,disabled:i||s,onChange:u=>l(u.target.value),children:d}),s?e.jsx("span",{className:"live-view-select-icon",role:"status","aria-label":`${t}正在切换`,children:e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"})}):e.jsx(Pi,{size:14,className:"live-view-select-icon","aria-hidden":"true"})]})}const vg=5e3,wg=1e4;class kg{constructor(){this.startedAt=null,this.lastFrameAt=null,this.lastFrameCount=null}begin(n){this.startedAt=n,this.lastFrameAt=null,this.lastFrameCount=null}resume(n){this.startedAt!==null&&(this.startedAt=n),this.lastFrameAt!==null&&(this.lastFrameAt=n)}observe(n,r){return typeof n!="number"||!Number.isFinite(n)||n<0||n===this.lastFrameCount||(this.lastFrameCount=n,n===0)?!1:(this.lastFrameAt=r,!0)}evaluate(n){const r=this.lastFrameAt??this.startedAt;if(r===null)return{state:"streaming",silentForMs:0};const s=Math.max(0,n-r),i=this.lastFrameAt===null?vg:wg;return{state:s>=i?"stalled":"streaming",silentForMs:s}}}var Ui,Xd;class jg{constructor(){cl(this,Ui);this.points=new Map,this.origin=null,this.originDistance=0,this.moved=!1}reset(){this.points.clear(),this.origin=null,this.originDistance=0,this.moved=!1}down(n,r){this.points.size||(this.origin=r,this.moved=!1),this.points.set(n,r),this.points.size>1&&(this.moved=!0),this.originDistance=dl(this,Ui,Xd).call(this)}move(n,r){const s=this.points.get(n);if(!s)return null;const i=[...this.points.values()];if(this.points.set(n,r),this.origin&&Math.hypot(r.x-this.origin.x,r.y-this.origin.y)>8&&(this.moved=!0),this.points.size===1)return this.moved?{scale:1,distanceRatio:1,from:s,to:r,pointers:1}:null;const o=[...this.points.values()],l=p=>({x:(p[0].x+p[1].x)/2,y:(p[0].y+p[1].y)/2}),d=p=>Math.hypot(p[0].x-p[1].x,p[0].y-p[1].y),u=d(i),f=this.originDistance>0?d(o)/this.originDistance:1;return{scale:u>0?d(o)/u:1,distanceRatio:f,from:l(i),to:l(o),pointers:this.points.size}}up(n,r,s=!1){if(!this.points.has(n))return!1;const i=!s&&!this.moved&&this.points.size===1&&!!this.origin&&Math.hypot(r.x-this.origin.x,r.y-this.origin.y)<=8;return this.points.delete(n),s&&(this.moved=!0),this.points.size||this.reset(),i}}Ui=new WeakSet,Xd=function(){const n=[...this.points.values()];return n.length>=2?Math.hypot(n[0].x-n[1].x,n[0].y-n[1].y):0};function Sg(t,n,r){const s=Math.max(t.top,n.top-r.top),i=Math.max(t.left,n.left-r.left),o=Math.min(t.top+t.height,n.top+n.height-r.top),l=Math.min(t.left+t.width,n.left+n.width-r.left);return{top:s,left:i,height:Math.max(0,o-s),width:Math.max(0,l-i)}}function ic(t){const n=t.visualViewport;return{top:(n==null?void 0:n.offsetTop)??0,left:(n==null?void 0:n.offsetLeft)??0,width:(n==null?void 0:n.width)??t.innerWidth,height:(n==null?void 0:n.height)??t.innerHeight}}function Cg(t,n=window){let r=null,s=null;try{n.parent!==n&&n.parent.location.origin===n.location.origin&&(r=n.parent,s=n.frameElement)}catch{}let i=null,o=null;const l=()=>{let p=ic(n);r&&s&&!n.document.fullscreenElement&&(p=Sg(p,ic(r),s.getBoundingClientRect()));for(const[v,x]of Object.entries(p))t.style.setProperty(`--browser-live-${v}`,`${x}px`)},d=()=>{i!==null&&n.cancelAnimationFrame(i),i=n.requestAnimationFrame(()=>{i=null,l()}),o!==null&&n.clearTimeout(o),o=n.setTimeout(l,250)},u=[n,n.document];n.visualViewport&&u.push(n.visualViewport),r&&(u.push(r),r.visualViewport&&u.push(r.visualViewport));const f=["resize","scroll","orientationchange","pageshow","visibilitychange","fullscreenchange"];for(const p of u)for(const v of f)p.addEventListener(v,d);return l(),()=>{for(const p of u)for(const v of f)p.removeEventListener(v,d);i!==null&&n.cancelAnimationFrame(i),o!==null&&n.clearTimeout(o);for(const p of["top","left","width","height"])t.style.removeProperty(`--browser-live-${p}`)}}const Bn=t=>typeof t=="number"&&Number.isFinite(t)?t:void 0;function Ig(t,n){var r;try{const s=(r=t==null?void 0:t.getVideoPlaybackQuality)==null?void 0:r.call(t);if(s&&Number.isFinite(s.totalVideoFrames)&&Number.isFinite(s.droppedVideoFrames))return Math.max(0,s.totalVideoFrames-s.droppedVideoFrames)}catch{}return Bn(t==null?void 0:t.webkitDecodedFrameCount)??Bn(n)}function Rg(t){var r,s,i;const n=new Set;for(const o of t??[]){if(((r=o.mimeType)==null?void 0:r.toLowerCase())!=="video/h264")continue;const l=(i=(s=/(?:^|;)\s*profile-level-id=([0-9a-f]{6})/i.exec(o.sdpFmtpLine??""))==null?void 0:s[1])==null?void 0:i.toLowerCase();l!=null&&l.startsWith("64")&&n.add("high"),(!l||l.startsWith("42"))&&n.add("baseline")}return[...n]}function Eg(){var n;if(typeof RTCRtpReceiver>"u"||typeof RTCRtpReceiver.getCapabilities!="function")return["baseline"];const t=Rg((n=RTCRtpReceiver.getCapabilities("video"))==null?void 0:n.codecs);return t.length?t:["baseline"]}function Mg(t){var r,s;const n=(s=(r=/(?:^|;)\s*profile-level-id=([0-9a-f]{6})/i.exec(typeof t=="string"?t:""))==null?void 0:r[1])==null?void 0:s.toLowerCase();if(n!=null&&n.startsWith("64"))return"high";if(!n||n.startsWith("42"))return"baseline"}function Ag(t,n,r=Date.now()){const i=[...typeof t.values=="function"?t.values():t],o=i.find(F=>F.type==="inbound-rtp"&&(F.kind==="video"||F.mediaType==="video"));if(!o)return null;const l=i.find(F=>F.id===o.codecId),d=i.find(F=>F.type==="candidate-pair"&&F.state==="succeeded"&&(F.nominated===!0||F.selected===!0)),u=i.find(F=>F.id===(d==null?void 0:d.localCandidateId)),f=i.find(F=>F.id===(d==null?void 0:d.remoteCandidateId)),p=[u==null?void 0:u.candidateType,f==null?void 0:f.candidateType].map(String),v=["relay","srflx","prflx","host"].find(F=>p.includes(F))??void 0,x=Bn(o.bytesReceived)??0,w=Bn(o.packetsReceived)??0,j=Bn(o.packetsLost)??0,E=Bn(o.framesDropped)??0,S=n?Math.max(1,r-n.at):0,C=n?Math.max(0,w-n.packetsReceived):0,k=n?Math.max(0,j-n.packetsLost):0,z=n?Math.max(0,E-n.framesDropped):0,M=Bn(d==null?void 0:d.currentRoundTripTime),H=Bn(o.jitter),L=typeof o.decoderImplementation=="string"?o.decoderImplementation.slice(0,120):void 0,T=typeof o.powerEfficientDecoder=="boolean"?o.powerEfficientDecoder:void 0,A=L!==void 0||T!==void 0?{implementation:L,powerEfficient:T,acceleration:T===!0?"hardware":T===!1?"software":"unknown"}:void 0,R={codec:typeof(l==null?void 0:l.mimeType)=="string"?l.mimeType.replace(/^video\//i,""):void 0,codecProfile:Mg(l==null?void 0:l.sdpFmtpLine),decoder:A,width:Bn(o.frameWidth),height:Bn(o.frameHeight),fps:Bn(o.framesPerSecond),rttMs:M!==void 0?M*1e3:void 0,jitterMs:H!==void 0?H*1e3:void 0,lossRate:C+k>0?k/(C+k):0,droppedFrames:z,receiveBitrate:n?Math.max(0,Math.round((x-n.bytesReceived)*8e3/S)):void 0,availableBitrate:Bn(d==null?void 0:d.availableIncomingBitrate),candidateType:v,protocol:(u==null?void 0:u.protocol)==="tcp"||(f==null?void 0:f.protocol)==="tcp"?"tcp":d?"udp":void 0};for(const F of Object.keys(R))R[F]===void 0&&delete R[F];const $=Bn(o.framesDecoded);return{sample:R,cursor:{at:r,bytesReceived:x,packetsReceived:w,packetsLost:j,framesDropped:E,...$!==void 0?{framesDecoded:$}:{}}}}function Tg(t){if(!t)return null;const n=[t.candidateType==="relay"?"TURN 中继":t.candidateType?"P2P 直连":null];return t.codec&&n.push(t.codec),t.width&&t.height&&n.push(`${t.width}x${t.height}${t.fps?`@${Math.round(t.fps)}`:""}`),t.receiveBitrate&&n.push(`${(t.receiveBitrate/1e6).toFixed(1)}Mbps`),t.rttMs!==void 0&&n.push(`${Math.round(t.rttMs)}ms`),n.filter(Boolean).join(" · ")||null}function Ng(t){const n=t==null?void 0:t.decoder;if(!n)return null;const r=n.acceleration==="hardware"?"硬件解码":n.acceleration==="software"?"软件解码":"解码方式未知";return n.implementation?`${r} · ${n.implementation}`:r}const _g={"agent-controlled":"Agent 操作中","handoff-requested":"正在交接","user-controlled":"你正在操作","return-requested":"正在归还",resyncing:"Agent 正在同步页面"},zg={smooth:"流畅",hd:"高清",original:"原画"};function Eo(t){return t==="desktop"?"桌面屏幕":t==="ego-browser"?"ego-browser":"内置 Browser"}function oc(t,n,r){var s,i;return t||(((s=n.find(o=>o.agentSessionId===r))==null?void 0:s.id)??((i=n[0])==null?void 0:i.id)??null)}function ac(t){return[t.altKey?"Alt":"",t.ctrlKey?"Control":"",t.metaKey?"Meta":"",t.shiftKey?"Shift":""].filter(Boolean)}function Lg(t){const n=new Uint8Array(t.length*2),r=new DataView(n.buffer);for(let i=0;i<t.length;i+=1){const o=Math.max(-1,Math.min(1,t[i]));r.setInt16(i*2,o<0?o*32768:o*32767,!0)}let s="";for(let i=0;i<n.length;i+=8192)s+=String.fromCharCode(...n.subarray(i,i+8192));return btoa(s)}function Pg(t,n){const r=atob(t),s=Math.floor(r.length/2/n),i=Array.from({length:n},()=>new Float32Array(s));for(let o=0;o<s;o+=1)for(let l=0;l<n;l+=1){const d=(o*n+l)*2,u=r.charCodeAt(d)|r.charCodeAt(d+1)<<8;i[l][o]=(u&32768?u-65536:u)/32768}return i}async function Dg(t){const n=[],r=()=>{for(const i of n.splice(0))i()};let s=!1;t.addEventListener("abort",r);try{if(t.aborted)return null;const i=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1});if(n.push(()=>{for(const x of i.getTracks())x.stop()}),t.aborted)return null;const o=window.AudioContext,l=new o({latencyHint:"interactive"});n.push(()=>{l.close().catch(()=>{})});const d=new o({latencyHint:"interactive"});if(n.push(()=>{d.close().catch(()=>{})}),await Promise.all([l.resume(),d.resume()]),t.aborted)return null;const u=d.createGain();u.connect(d.destination);const f=l.createMediaStreamSource(i),p=l.createScriptProcessor(2048,1,1),v=l.createGain();return v.gain.value=0,f.connect(p),p.connect(v),v.connect(l.destination),s=!0,{stream:i,microphoneContext:l,remoteContext:d,remoteGain:u,source:f,processor:p,sink:v,dispose:r}}finally{t.removeEventListener("abort",r),s||r()}}function Wg(t,n){return t?t.state==="user-controlled"&&t.isController===!0&&n.state==="handoff-requested"||t.state==="agent-controlled"&&n.state==="return-requested":!1}const Fg=2;function Bg(t,n,r,s,i=.02){if(!t||!n||!n.width||!n.height)return!1;const o=t.x/n.width-i,l=t.y/n.height-i,d=(t.x+t.w)/n.width+i,u=(t.y+t.h)/n.height+i;return r>=o&&r<=d&&s>=l&&s<=u}function Og(t,n,r=Fg){const s={deltaX:Math.round(t.x-n.x),deltaY:Math.round(t.y-n.y)};return Math.abs(s.deltaX)<r&&Math.abs(s.deltaY)<r?null:s}function $g({open:t,agentSessionId:n,onClose:r}){const s=a.useContext(Qu),i=typeof window>"u"?void 0:window.browserLiveApi,o=a.useRef(null),l=a.useRef(null);a.useLayoutEffect(()=>{if(!(!t||!o.current))return Cg(o.current)},[t]);const[d,u]=a.useState(!1),f=async()=>{const b=l.current;if(b){if(d){document.fullscreenElement===b&&await document.exitFullscreen().catch(()=>{}),u(!1);return}u(!0),b.requestFullscreen&&await b.requestFullscreen().catch(()=>{})}};a.useEffect(()=>{if(!t){u(!1);return}const b=l.current,N=()=>u(document.fullscreenElement===b),D=re=>{re.key==="Escape"&&(document.fullscreenElement===b||b!=null&&b.classList.contains("is-fullscreen"))&&(re.preventDefault(),re.stopPropagation(),document.fullscreenElement===b&&document.exitFullscreen().catch(()=>{}),u(!1))};return document.addEventListener("fullscreenchange",N),document.addEventListener("keydown",D,!0),()=>{document.removeEventListener("fullscreenchange",N),document.removeEventListener("keydown",D,!0),b&&document.fullscreenElement===b&&document.exitFullscreen().catch(()=>{})}},[t]);const[p,v]=a.useState([]),[x,w]=a.useState(null),[j,E]=a.useState(null),[S,C]=a.useState("hd"),[k,z]=a.useState(null),[M,H]=a.useState(null),[L,T]=a.useState(!1),[A,R]=a.useState(0),[$,F]=a.useState(null),[Ee,Qe]=a.useState(!1),[ae,ke]=a.useState(null),[De,Ie]=a.useState(!1),[We,at]=a.useState(""),[Ge,ne]=a.useState(!1),[be,Ye]=a.useState(null),[W,te]=a.useState(1),[G,le]=a.useState(!1),[pe,ye]=a.useState({width:0,height:0}),we=a.useRef(null),Te=a.useRef(null),ut=a.useRef(!1),lt=a.useRef(null),st=a.useRef(new jg),Tt=a.useRef(W),He=a.useRef(null);a.useLayoutEffect(()=>{Tt.current=W;const b=He.current,N=we.current,D=N==null?void 0:N.querySelector(".browser-live-image-hit-area");if(!b||!N||!D)return;const re=D.getBoundingClientRect();N.scrollLeft+=re.left+b.x*re.width-b.clientX,N.scrollTop+=re.top+b.y*re.height-b.clientY,He.current=null},[W]);const Nt=a.useRef(null),[ct,B]=a.useState(!1),Y=a.useRef(!1),q=a.useRef(null),se=a.useRef(0);a.useEffect(()=>{t||(Ie(!1),at(""),Ye(null))},[t]);const[ee,Ke]=a.useState(!1),dt=a.useRef(null),Jt=a.useRef(0),Ze=a.useRef("none"),$e=a.useRef(null),Gt=a.useRef(null),[rt,Pt]=a.useState(null),[ht,_t]=a.useState(!1),ln=a.useRef(null),vn=a.useRef(null),[Ue,Dt]=a.useState("off"),[Xn,$n]=a.useState(null),cn=a.useRef(null),X=a.useRef(null),dn=a.useRef(0),Zt=a.useRef(null),wt=a.useRef(new kg),Rt=a.useRef(!1),[gt,Wt]=a.useState(null),[mt,wn]=a.useState("idle"),[Yn,Jn]=a.useState(!1),[en,Hn]=a.useState(!1),tn=a.useRef(!1),Zn=a.useRef(!1),kn=a.useRef(null),un=a.useRef(null),ar=a.useRef(null),jn=a.useRef(null),Un=a.useRef(null),Ne=a.useRef(null),it=a.useRef(null),Ht=a.useRef(0),er=a.useRef(0),Wn=a.useRef(0),Ft=a.useRef(null);a.useLayoutEffect(()=>{Y.current=ct,ct&&Ke(!1)},[ct]);const I=a.useMemo(()=>p.find(b=>b.id===x)??null,[x,p]),Q=(I==null?void 0:I.backend)==="desktop",fe=Q&&(I==null?void 0:I.platform)==="win32",ze=(I==null?void 0:I.availability)==="unavailable"&&(I==null?void 0:I.capabilityErrorCode)==="desktop-locked",ge=(I==null?void 0:I.isController)&&I.state==="user-controlled",Ut=I==null?void 0:I.audioCapabilities,rn=!!(Ut!=null&&Ut.fullDuplex&&Ut.systemAudio&&Ut.microphonePlayback&&Ut.selfPlaybackExclusion),pt=!!(I!=null&&I.online&&I.availability==="ready"&&!I.controlledByAnotherViewer);a.useEffect(()=>{if(!t||!i||!x){Pt(null);return}let b=!0;const N=()=>{const re=performance.now();i.request("browser:ping",{t:re}).then(()=>{b&&Pt(Math.round(performance.now()-re))}).catch(()=>{b&&Pt(null)})};N();const D=window.setInterval(N,3e3);return()=>{b=!1,window.clearInterval(D),Pt(null)}},[i,t,x]),a.useEffect(()=>{const b=navigator;if(!ge||!b.wakeLock)return;let N=!1,D=null;return b.wakeLock.request("screen").then(re=>{if(N){re.release();return}D=re,ln.current=re}).catch(()=>{}),()=>{N=!0,D==null||D.release().catch(()=>{}),ln.current=null}},[ge]);const Sn=(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport),hr=Sn&&pe.width&&pe.height?Math.min(pe.width/Sn.width,pe.height/Sn.height):null;a.useEffect(()=>{var b;te(1),le(!1),Te.current=null,st.current.reset(),He.current=null,q.current=null,vn.current=null,(b=we.current)==null||b.scrollTo(0,0)},[t,x]),a.useEffect(()=>{const b=we.current;if(!t||!b)return;const N=new ResizeObserver(()=>{ye({width:b.clientWidth,height:b.clientHeight})});return N.observe(b),()=>N.disconnect()},[t,Q]),a.useEffect(()=>{const b=we.current;if(!t||!b||!ge||G)return;const N=D=>D.preventDefault();return b.addEventListener("wheel",N,{passive:!1}),()=>b.removeEventListener("wheel",N)},[t,ge,G]);const hs=a.useCallback(()=>{const b=Nt.current;b&&(ct?(b.blur(),B(!1)):(b.focus({preventScroll:!0}),B(!0)))},[ct]);a.useEffect(()=>{var b;(!ge||G)&&ct&&((b=Nt.current)==null||b.blur(),B(!1))},[ge,G,ct]);const lr=a.useCallback(b=>{const N=(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport),D=we.current,re=D==null?void 0:D.querySelector(".browser-live-image-hit-area");if(!b||!N||!D||!re)return;const ce=re.getBoundingClientRect(),Ve=D.getBoundingClientRect(),Pe=ce.top+b.y/N.height*ce.height,qe=Pe+b.h/N.height*ce.height,Xe=16;Pe>=Ve.top+Xe&&qe<=Ve.bottom-Xe||(D.scrollTop+=Pe-(Ve.top+Math.max(Xe,Ve.height*.3)))},[M==null?void 0:M.viewport,I==null?void 0:I.viewport]);a.useEffect(()=>{if(!ct||!q.current)return;const b=window.setTimeout(()=>lr(q.current),420);return()=>window.clearTimeout(b)},[ct,pe.width,pe.height,lr]);const Bt=a.useCallback(b=>{var D;const N=b&&typeof b.input=="object"&&b.input!==null?b.input:b;if(typeof(N==null?void 0:N.editable)=="boolean"){if(!N.editable&&N.kind==="control"){const re=N.bounds;re&&["x","y","w","h"].every(ce=>typeof re[ce]=="number")&&(vn.current={rect:{x:re.x,y:re.y,w:re.w,h:re.h},at:Date.now()});return}if(N.editable){const re=N.bounds,ce=re&&["x","y","w","h"].every(Ve=>typeof re[Ve]=="number")?{x:re.x,y:re.y,w:re.w,h:re.h}:null;ce&&(q.current=ce,se.current=Date.now()),Y.current?lr(ce??q.current):Ke(!0)}else q.current=null,Y.current&&((D=Nt.current)==null||D.blur(),B(!1))}},[lr]),sn=a.useCallback((b=!0)=>{var ce,Ve,Pe,qe,Xe;(ce=Ft.current)==null||ce.abort(),Ft.current=null;const N=kn.current;kn.current=null;for(const jt of(N==null?void 0:N.getTracks())??[])jt.stop();(Ve=ar.current)==null||Ve.disconnect(),(Pe=jn.current)==null||Pe.disconnect(),(qe=Un.current)==null||qe.disconnect(),ar.current=null,jn.current=null,Un.current=null;const D=un.current;un.current=null,D&&D.close().catch(()=>{});const re=Ne.current;Ne.current=null,(Xe=it.current)==null||Xe.disconnect(),it.current=null,Ht.current=0,Wn.current=0,re&&re.close().catch(()=>{}),tn.current=!1,Zn.current=!1,Jn(!1),Hn(!1),wn("idle"),b&&i&&x&&i.request("browser:webrtc",{sessionId:x,data:{kind:"audio-stop"}}).catch(()=>{})},[i,x]),tr=a.useCallback(b=>{var zt;if(Zn.current||typeof b.data!="string")return;const N=Ne.current,D=Number(b.sampleRate),re=Number(b.channels);if(!N||!Number.isSafeInteger(D)||!Number.isSafeInteger(re)||re<1||re>2)return;const ce=Pg(b.data,re);if(!((zt=ce[0])!=null&&zt.length))return;const Ve=N.createBuffer(re,ce[0].length,D);for(let $t=0;$t<re;$t+=1)Ve.copyToChannel(ce[$t],$t);const Pe=N.createBufferSource();Pe.buffer=Ve;const qe=it.current;if(!qe)return;Pe.connect(qe);const Xe=N.currentTime,jt=Math.max(Xe+.02,Ht.current);Ht.current=jt-Xe>.35?Xe+.02:jt,Pe.start(Ht.current),Ht.current+=Ve.duration},[]),gr=a.useCallback(async()=>{var N;if(!i||!x||!ge||!rn||document.visibilityState!=="visible")return;const b=new AbortController;(N=Ft.current)==null||N.abort(),Ft.current=b,F(null),wn("starting");try{const D=await Dg(b.signal);if(!D||b.signal.aborted||document.visibilityState!=="visible"){D==null||D.dispose();return}const{stream:re,microphoneContext:ce,remoteContext:Ve,remoteGain:Pe,source:qe,processor:Xe,sink:jt}=D;kn.current=re,un.current=ce,ar.current=qe,jn.current=Xe,Un.current=jt,Ne.current=Ve,it.current=Pe,er.current=0,Xe.onaudioprocess=zt=>{if(b.signal.aborted||tn.current||!kn.current||!i||!x||Wn.current>=4)return;const $t=new Float32Array(zt.inputBuffer.getChannelData(0));Wn.current+=1,i.request("browser:webrtc",{sessionId:x,data:{kind:"audio-microphone",sequence:++er.current,sampleRate:ce.sampleRate,channels:1,data:Lg($t)}}).catch(()=>{}).finally(()=>{Wn.current=Math.max(0,Wn.current-1)})},await i.request("browser:webrtc",{sessionId:x,data:{kind:"audio-start"}})}catch(D){if(b.signal.aborted)return;sn(!1),wn("failed"),F(D instanceof Error?D.message:"无法开始语音")}},[i,ge,x,sn,rn]);a.useEffect(()=>{t&&ge&&rn||mt!=="idle"&&sn(!0)},[mt,ge,t,sn,rn]),a.useEffect(()=>{const b=()=>{document.visibilityState!=="visible"&&mt!=="idle"&&sn(!0)};return document.addEventListener("visibilitychange",b),()=>document.removeEventListener("visibilitychange",b)},[mt,sn]),a.useEffect(()=>()=>sn(!0),[sn]);const qt=a.useMemo(()=>[{urls:"stun:stun.l.google.com:19302"}],[]),Xr=a.useCallback(async(b,N,D)=>{if(!(!i||!b||!N))try{const re=X.current;X.current=null,re==null||re.close();let ce=X.current;if(ce||(ce=new RTCPeerConnection({iceServers:D!=null&&D.length?D:qt}),ce.onicecandidate=Pe=>{Pe.candidate&&i.request("browser:webrtc",{sessionId:b,data:{kind:"ice",candidate:Pe.candidate.toJSON()}}).catch(()=>{})},ce.ontrack=Pe=>{const qe=Zt.current;qe&&Pe.streams[0]&&(qe.srcObject=Pe.streams[0],qe.play().catch(()=>{}))},ce.onconnectionstatechange=()=>{if(X.current!==ce)return;const Pe=ce==null?void 0:ce.connectionState;Pe==="connected"?Dt("live"):(Pe==="failed"||Pe==="disconnected"||Pe==="closed")&&Dt("failed")},X.current=ce),await ce.setRemoteDescription(N),X.current!==ce)return;const Ve=await ce.createAnswer();if(await ce.setLocalDescription(Ve),X.current!==ce)return;Dt("connecting"),await i.request("browser:webrtc",{sessionId:b,data:{kind:"answer",sdp:ce.localDescription.toJSON()}})}catch{Dt("failed")}},[i,qt]),Yr=a.useCallback((b,N)=>{if(N){if(N.kind==="quality-state"&&["smooth","hd","original"].includes(String(N.quality))){C(String(N.quality)),z(null),typeof N.error=="string"&&F(N.error);return}if(N.kind==="audio-system"){tr(N);return}if(N.kind==="audio-state"){const D=String(N.state);["idle","starting","live","failed"].includes(D)&&wn(D),typeof N.error=="string"&&(F(N.error),sn(!1),wn("failed"));return}if(N.kind==="offer"){typeof N.warning=="string"&&F(N.warning),Xr(b,N.sdp,Array.isArray(N.iceServers)?N.iceServers:void 0);return}if(N.kind==="ice"){const D=N.candidate,re=X.current;re&&D&&re.addIceCandidate(D).catch(()=>{});return}if(N.kind==="state"){const D=String(N.state);D==="connected"?Dt("live"):(D==="failed"||D==="disconnected"||D==="closed")&&Dt("failed")}}},[Xr,tr,sn]),[Mn,cr]=a.useState(null);a.useEffect(()=>{if(!M){cr(null);return}const b=typeof M.data=="string"?`data:${M.mime};base64,${M.data}`:URL.createObjectURL(new Blob([M.data],{type:M.mime}));let N=!1,D=!1;const re=new Image;return re.src=b,re.decode().then(()=>{N||(D=!0,cr(b))}).catch(()=>{}),()=>{N=!0,!D&&b.startsWith("blob:")&&URL.revokeObjectURL(b)}},[M]),a.useEffect(()=>()=>{Mn!=null&&Mn.startsWith("blob:")&&URL.revokeObjectURL(Mn)},[Mn]);const on=a.useCallback(b=>{v(N=>{const D=N.findIndex(ce=>ce.id===b.id);if(D>=0&&Wg(N[D],b))return N;if(D<0)return[b,...N];const re=[...N];return re[D]=b,re.sort((ce,Ve)=>Ve.updatedAt-ce.updatedAt)}),w(N=>oc(N,[b],n)),Qe(!1)},[n]),pn=a.useCallback(async()=>{if(!(!i||!t)){T(!0),F(null);try{const b=await i.request("browser:list");v(b.sessions),w(N=>{const D=N&&b.sessions.some(re=>re.id===N)?N:null;return oc(D,b.sessions,n)}),x&&await i.request("browser:watch",{sessionId:x}).then(N=>on(N.session)).catch(()=>{}),R(N=>N+1)}catch(b){F(b instanceof Error?b.message:"无法读取浏览器会话")}finally{T(!1)}}},[n,i,on,t,x]);a.useEffect(()=>{if(!(!t||!i))return pn(),i.onEvent(b=>{var N;if(b.type==="browser:connection"){(N=X.current)==null||N.close(),X.current=null,Dt("off"),Qe(!1),v([]),H(null),b.connected===!0?pn():F("远程连接已断开,正在重新连接");return}if(b.type==="browser:frame"){const D=b;D.sessionId===x&&H(D);return}if(b.type==="browser:webrtc"){const D=b.data;b.sessionId===x&&Yr(x,D);return}if(b.session&&typeof b.session=="object"&&on(b.session),b.type==="browser:closed"){const D=b.session;D&&(v(re=>re.filter(ce=>ce.id!==D.id)),D.id===x&&(H(null),w(null)))}})},[i,Yr,on,t,pn,x]),a.useEffect(()=>{if(!(!t||!i||!x))return H(null),F(null),Rt.current=!1,Wt(null),i.request("browser:watch",{sessionId:x}).then(b=>on(b.session)).catch(b=>F(b instanceof Error?b.message:"无法观看浏览器")),()=>{i.request("browser:unwatch").catch(()=>{})}},[i,on,t,x]),a.useEffect(()=>{var b,N;if(!t||!i||!ge||!Q||!x){Rt.current=!1,Wt(null),dn.current=0,(b=X.current)==null||b.close(),X.current=null,Zt.current&&(Zt.current.srcObject=null),cn.current=null,$n(null),Dt("off");return}return(N=X.current)==null||N.close(),X.current=null,cn.current=null,$n(null),Dt("connecting"),wt.current.begin(performance.now()),i.request("browser:webrtc",{sessionId:x,data:{kind:"start",receiverProfiles:Eg()}}).catch(()=>Dt("failed")),()=>{var D;(D=X.current)==null||D.close(),X.current=null,Zt.current&&(Zt.current.srcObject=null),cn.current=null,$n(null),i.request("browser:webrtc",{sessionId:x,data:{kind:"stop"}}).catch(()=>{})}},[i,ge,Q,t,x,A]),a.useEffect(()=>{if(!t||!ge||!Q||Ue!=="failed"||dn.current>=2)return;const b=window.setTimeout(()=>{dn.current+=1,R(N=>N+1)},2e3*(dn.current+1));return()=>window.clearTimeout(b)},[t,ge,Q,Ue]),a.useEffect(()=>{if(!i||!x||Ue!=="live"){cn.current=null,$n(null);return}let b=!0,N=!1;const D=Zt.current,re=typeof(D==null?void 0:D.requestVideoFrameCallback)=="function";let ce,Ve=null;wt.current.begin(performance.now());const Pe=zt=>{!b||document.visibilityState==="hidden"||wt.current.observe(zt,performance.now())&&Rt.current&&(Rt.current=!1,Wt(null),i.request("browser:webrtc",{sessionId:x,data:{kind:"viewer-trace",event:"stall-recovered",...Ve?{sample:Ve}:{}}}).catch(()=>{}))};if(re&&D){const zt=($t,Vn)=>{Pe(Vn.presentedFrames),b&&(ce=D.requestVideoFrameCallback(zt))};ce=D.requestVideoFrameCallback(zt)}const qe=()=>{document.visibilityState!=="hidden"&&wt.current.resume(performance.now())};document.addEventListener("visibilitychange",qe);const Xe=async()=>{const zt=X.current;if(!(!zt||N)){N=!0;try{const $t=await zt.getStats().catch(()=>null);if(!b||zt!==X.current)return;const Vn=performance.now(),zn=$t&&Ag($t,cn.current);zn&&(cn.current=zn.cursor,Ve=zn.sample,$n(zn.sample),i.request("browser:webrtc",{sessionId:x,data:{kind:"stats",...zn.sample}}).catch(()=>{}));const yr=Ig(D,zn==null?void 0:zn.cursor.framesDecoded);re||Pe(yr);const Je=re||yr!==void 0||!(D!=null&&D.videoWidth);if(document.visibilityState!=="hidden"&&Je&&wt.current.evaluate(Vn).state==="stalled"){const zr=wt.current.evaluate(Vn);wt.current.begin(Vn),Dt(Lt=>Lt==="live"?"failed":Lt),Rt.current=!0,Wt("实时画面超时,已切换为 JPEG 兜底画面"),i.request("browser:webrtc",{sessionId:x,data:{kind:"viewer-trace",event:"jpeg-fallback",silentForMs:zr.silentForMs,...Ve?{sample:Ve}:{}}}).catch(()=>{})}}catch{}finally{N=!1}}};Xe();const jt=window.setInterval(()=>void Xe(),1e3);return()=>{b=!1,window.clearInterval(jt),ce!==void 0&&(D==null||D.cancelVideoFrameCallback(ce)),document.removeEventListener("visibilitychange",qe)}},[i,x,Ue]);const qn=a.useCallback(async()=>{if(!(!i||!I)){Qe(!0),F(null);try{const b=await i.request("browser:takeover",{sessionId:I.id});on(b.session)}catch(b){Qe(!1),F(b instanceof Error?b.message:"无法接管浏览器")}}},[i,on,I]),gs=a.useCallback(async()=>{if(!(!i||!I)){Qe(!0),F(null);try{const b=await i.request("browser:return",{sessionId:I.id});on(b.session)}catch(b){Qe(!1),F(b instanceof Error?b.message:"无法归还浏览器")}}},[i,on,I]),mr=a.useCallback(async(b,N)=>{if(!(!i||!x)){ke(b),F(null);try{await i.request("browser:system",{sessionId:x,action:b,...N?{password:N}:{}}),window.setTimeout(()=>R(D=>D+1),800)}catch(D){F(D instanceof Error?D.message:"系统操作失败")}finally{ke(null)}}},[i,x]),An=a.useCallback(async()=>{if(!(!i||!x||!We)){ne(!0),Ye(null);try{await i.request("browser:system",{sessionId:x,action:"unlock",password:We}),at(""),Ie(!1),window.setTimeout(()=>R(b=>b+1),2500)}catch(b){Ye(b instanceof Error?b.message:"解锁失败")}finally{at(""),ne(!1)}}},[i,x,We]),xt=a.useCallback(b=>{!i||j||k||!(I!=null&&I.isController)||I.state!=="user-controlled"||i.request("browser:input",{sessionId:I.id,input:{...b,mobile:window.matchMedia("(pointer: coarse)").matches}}).catch(N=>{F(N instanceof Error?N.message:"浏览器输入失败")})},[i,I,j,k]),kt=a.useCallback((b,N,D=[])=>{xt({kind:"key",action:"down",key:b,code:N,text:"",modifiers:D}),xt({kind:"key",action:"up",key:b,code:N,text:"",modifiers:D})},[xt]),Tn=a.useCallback(b=>{kt(b,`Key${b.toUpperCase()}`,["Control"])},[kt]),fn=a.useCallback(b=>!i||j||k||!(I!=null&&I.isController)||I.state!=="user-controlled"?Promise.resolve(null):i.request("browser:input",{sessionId:I.id,input:{...b,mobile:window.matchMedia("(pointer: coarse)").matches}}).then(N=>N&&typeof N=="object"?N:null).catch(()=>null),[i,I,j,k]),Vt=a.useCallback((b,N)=>{fn({kind:"pointer",action:"up",...b,button:"left",...N&&N>1?{click:N}:{}}).then(Bt)},[Bt,fn]),Nn=a.useRef(!1),nr=a.useRef(""),Nr=a.useCallback(b=>{const N=nr.current;if(b!==N){if(b.startsWith(N)){const D=b.slice(N.length);D&&xt({kind:"key",action:"down",text:D,key:"",code:"",modifiers:[]})}nr.current=b}},[xt]),Ot=(I==null?void 0:I.displays)??null;a.useEffect(()=>{if(!k)return;const b=window.setTimeout(()=>{z(null),F("画质切换未完成,请刷新画面后重试")},14e3);return()=>window.clearTimeout(b)},[k]),a.useEffect(()=>{z(null),C("hd")},[t,x]);const xr=b=>{!i||!pt||j||k||!x||(z(b),i.request("browser:webrtc",{sessionId:x,data:{kind:"quality",quality:b}}).catch(N=>{z(null),F(N instanceof Error?N.message:"画质切换失败")}))};a.useEffect(()=>{if(!j)return;if(Ot!=null&&Ot.some(N=>N.id===j&&N.selected)){E(null);return}const b=window.setTimeout(()=>{E(null),F("切换屏幕未完成,请刷新画面后重试")},14e3);return()=>window.clearTimeout(b)},[Ot,j]),a.useEffect(()=>{E(null)},[t,x]);const Cn=a.useRef(0),dr=a.useCallback(b=>{!i||j||k||!x||!pt||!(Ot!=null&&Ot.some(N=>N.id===b&&!N.selected))||(E(b),i.request("browser:set-display",{sessionId:x,displayId:b}).catch(N=>{E(null),F(N instanceof Error?N.message:"切换屏幕失败")}))},[i,Ot,x,pt,j,k]),_n=a.useCallback(b=>{const N=b.currentTarget.getBoundingClientRect(),D=(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport);if(!D)return null;const re=Math.min(N.width/D.width,N.height/D.height),ce=D.width*re,Ve=D.height*re,Pe=(N.width-ce)/2,qe=(N.height-Ve)/2,Xe=(b.clientX-N.left-Pe)/ce,jt=(b.clientY-N.top-qe)/Ve;return Xe<0||Xe>1||jt<0||jt>1?null:{x:Xe,y:jt}},[M==null?void 0:M.viewport,I==null?void 0:I.viewport]);if(!t||typeof document>"u")return null;const _r=(I==null?void 0:I.online)&&!I.controlledByAnotherViewer,br=(I==null?void 0:I.availability)==="unavailable"?Q?"桌面直播不可用":"浏览器直播不可用":(I==null?void 0:I.availability)==="starting"?"正在连接画面":Q&&(I==null?void 0:I.state)==="agent-controlled"?"未被远程控制":I?_g[I.state]:Q?"等待桌面直播":"等待浏览器",Ls=(I==null?void 0:I.availability)==="unavailable"?Q?"桌面直播不可用":"浏览器直播不可用":(I==null?void 0:I.availability)==="starting"?"正在连接画面":p.length?"等待第一帧":Q?"暂无桌面直播":"暂无浏览器直播",rr=(I==null?void 0:I.availability)==="unavailable"?I.capabilityError||(Q?"需要在桌面 App 中开启并授予屏幕录制权限":"当前浏览器不支持实时画面传输"):p.length?"画面开始后会自动显示":Q?"在桌面 App 设置中开启「桌面直播与远程控制」后,画面会出现在这里":"Agent 开始浏览网页后,会话会出现在这里",ur=Tg(Xn),Kt=Ng(Xn),Qt=Ue==="live"?ur||"WebRTC 实时流":Ue==="connecting"?"正在连接 WebRTC":Mn?"JPEG 兜底":null;return On.createPortal(e.jsxs("div",{ref:o,className:"browser-live-backdrop","data-tab-swipe-ignore":!0,role:"presentation",onMouseDown:b=>{b.target===b.currentTarget&&r()},children:[e.jsxs("section",{ref:l,className:`browser-live-panel ${d?"is-fullscreen":""}`,role:"dialog","aria-modal":"true","aria-label":"浏览器直播",children:[e.jsxs("header",{className:"browser-live-header",children:[e.jsxs("div",{className:"browser-live-heading",children:[e.jsx(bl,{size:17,"aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("strong",{children:"浏览器直播"}),e.jsx("span",{children:I?Eo(I.backend):"实时观看与接管"})]}),s]}),e.jsxs("div",{className:"browser-live-header-actions",children:[e.jsx("button",{type:"button",className:"ui-icon-button",onClick:()=>void f(),title:d?"退出全屏":"全屏","aria-label":d?"退出全屏":"全屏","aria-pressed":d,children:d?e.jsx(vo,{size:17}):e.jsx(vp,{size:17})}),e.jsx("button",{type:"button",className:"ui-icon-button",onClick:()=>void pn(),title:"刷新画面与会话","aria-label":"刷新直播画面与会话",children:e.jsx(da,{size:15,className:L?"spin":void 0,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"ui-icon-button",onClick:r,title:"关闭","aria-label":"关闭浏览器直播",children:e.jsx(Tr,{size:17,"aria-hidden":"true"})})]})]}),e.jsxs("div",{className:`browser-live-surface ${ge?"is-controlling":""} has-zoom ${ge&&!G&&ht?"has-quickkeys":""}`,children:[e.jsxs("div",{className:"browser-live-zoom",role:"group","aria-label":"桌面画面缩放",children:[d&&e.jsxs("button",{type:"button","aria-label":"退出全屏",title:"退出全屏",onClick:()=>void f(),children:[e.jsx(vo,{size:15,"aria-hidden":"true"}),"退出全屏"]}),p.length>1&&e.jsx("div",{className:"browser-live-session-tabs",role:"tablist","aria-label":"切换直播屏幕",children:p.map(b=>e.jsx("button",{type:"button",role:"tab","aria-selected":b.id===x,className:b.id===x?"is-active":"",title:`${Eo(b.backend)} · ${b.title||"浏览器"}`,onClick:()=>w(b.id),children:b.title||Eo(b.backend)},b.id))}),Q&&Ot&&Ot.length>1&&e.jsx(sc,{label:"选择直播屏幕",title:pt?"选择直播屏幕":"其他设备控制中或画面暂不可用",value:(Ot.find(b=>b.selected)??Ot[0]).id,busy:!!j,disabled:!M||!pt||k||Ot.length<2,onChange:dr,children:Ot.map((b,N)=>e.jsx("option",{value:b.id,children:`第 ${N+1} 屏${b.primary?"(主屏)":""}`},b.id))}),Q&&e.jsxs(sc,{label:"视频画质",title:pt?"视频画质":"其他设备控制中或画面暂不可用",value:S,busy:k!==null,disabled:!pt||!!j,compact:!0,onChange:xr,children:[e.jsx("option",{value:"smooth",children:"流畅"}),e.jsx("option",{value:"hd",children:"高清"}),e.jsx("option",{value:"original",children:"原画"})]}),Q&&ge&&rn&&mt!=="live"&&e.jsxs("button",{type:"button","aria-label":"开始语音",title:"开始双向语音",disabled:mt==="starting",onClick:()=>void gr(),children:[mt==="starting"?e.jsx(ot,{size:15,className:"spin","aria-hidden":"true"}):e.jsx(xl,{size:15,"aria-hidden":"true"}),mt==="starting"?"正在连接":"开始语音"]}),Q&&ge&&rn&&mt==="live"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button","aria-label":Yn?"取消麦克风静音":"麦克风静音","aria-pressed":Yn,title:Yn?"打开麦克风":"关闭麦克风",onClick:()=>{var N;const b=!tn.current;tn.current=b;for(const D of((N=kn.current)==null?void 0:N.getAudioTracks())??[])D.enabled=!b;Jn(b)},children:Yn?e.jsx(wp,{size:15,"aria-hidden":"true"}):e.jsx(xl,{size:15,"aria-hidden":"true"})}),e.jsx("button",{type:"button","aria-label":en?"取消扬声器静音":"扬声器静音","aria-pressed":en,title:en?"打开电脑声音":"关闭电脑声音",onClick:()=>{const b=!Zn.current;Zn.current=b,it.current&&(it.current.gain.value=b?0:1),Hn(b),b&&(Ht.current=0)},children:en?e.jsx(Dp,{size:15,"aria-hidden":"true"}):e.jsx(cd,{size:15,"aria-hidden":"true"})}),e.jsx("button",{type:"button","aria-label":"结束语音",title:"结束双向语音",onClick:()=>sn(!0),children:e.jsx(Rp,{size:15,"aria-hidden":"true"})})]}),e.jsx("button",{type:"button","aria-label":"缩小桌面画面",title:"缩小",disabled:!M||W<=.5,onClick:()=>te(b=>Math.max(.5,b-.25)),children:e.jsx(pd,{size:16})}),e.jsxs("output",{"aria-label":"桌面缩放比例",children:[Math.round(W*100),"%"]}),e.jsx("button",{type:"button","aria-label":"放大桌面画面",title:"放大",disabled:!M||W>=5,onClick:()=>te(b=>Math.min(5,b+.25)),children:e.jsx(ud,{size:16})}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>{var b;te(1),le(!1),(b=we.current)==null||b.scrollTo(0,0)},children:"适应窗口"}),e.jsxs("button",{type:"button","aria-label":"移动桌面画面","aria-pressed":G,title:"拖动或滚动画面,不发送远程输入",disabled:!M,onClick:()=>le(b=>!b),children:[e.jsx(up,{size:15}),"移动画面"]}),e.jsxs("button",{type:"button","aria-label":"唤起键盘","aria-pressed":ct,title:"唤起/收起键盘(轻点输入框也会自动弹起)",className:ee&&!ct?"is-hint":void 0,disabled:!M||!ge,onClick:()=>{Ke(!1),hs()},children:[e.jsx(yo,{size:15}),"键盘"]}),e.jsxs("button",{type:"button","aria-label":"快捷键条","aria-pressed":ht,title:"展开/收起快捷键(Esc/Tab/复制/粘贴/方向键)",disabled:!M||!ge,onClick:()=>_t(b=>!b),children:[e.jsx(yo,{size:15}),ht?"收起":"快捷键"]}),e.jsxs("button",{type:"button","aria-label":"窗口控制",title:"全屏看不到左上角按钮时用:第 1 次点=退出全屏(ESC + Ctrl+Cmd+F),第 2 次点=关闭窗口(Cmd+W)",disabled:!M||!ge,onClick:()=>{const b=Date.now();if(b-Cn.current<2500){kt("w","KeyW",["Meta"]),Cn.current=0;return}Cn.current=b,kt("Escape","Escape"),window.setTimeout(()=>{kt("f","KeyF",["Control","Meta"])},150)},children:[e.jsx(yo,{size:15}),"窗口"]}),fe&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button","aria-label":"锁屏",title:"锁屏(锁屏后仍可从空态区唤醒或远程解锁)",disabled:!M||!!ae,onClick:()=>void mr("lock"),children:[ae==="lock"?e.jsx(ot,{size:15,className:"spin"}):e.jsx(bp,{size:15}),"锁屏"]}),e.jsxs("button",{type:"button","aria-label":"唤醒屏幕",title:"唤醒显示器或锁屏界面",disabled:!!ae,onClick:()=>void mr("wake"),children:[ae==="wake"?e.jsx(ot,{size:15,className:"spin"}):e.jsx(yl,{size:15}),"唤醒"]})]})]}),ge&&!G&&ht&&e.jsxs("div",{className:"browser-live-quickkeys",role:"group","aria-label":"快捷键",children:[e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("Escape","Escape"),children:"Esc"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("Tab","Tab"),children:"Tab"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("c"),children:"复制"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("v"),children:"粘贴"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("a"),children:"全选"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("z"),children:"撤销"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("s"),children:"保存"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>Tn("f"),children:"查找"}),e.jsx("button",{type:"button",disabled:!M,title:"退出当前前台应用(Cmd+Q)",onClick:()=>kt("q","KeyQ",["Meta"]),children:"⌘Q"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("ArrowLeft","ArrowLeft"),children:"←"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("ArrowUp","ArrowUp"),children:"↑"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("ArrowDown","ArrowDown"),children:"↓"}),e.jsx("button",{type:"button",disabled:!M,onClick:()=>kt("ArrowRight","ArrowRight"),children:"→"})]}),e.jsx("div",{className:"browser-live-touch-hint",children:"滑动滚动 · 轻点点击 · 双击打开 · 长按拖动 · 按住1秒右键 · 双指缩放"}),e.jsx("div",{ref:we,className:"browser-live-viewport",children:M&&Mn?e.jsxs("div",{className:"browser-live-image-hit-area",style:hr&&Sn?{width:Sn.width*hr*W,height:Sn.height*hr*W,cursor:G?"grab":void 0}:void 0,tabIndex:ge&&!G?0:-1,onContextMenu:b=>b.preventDefault(),onPointerDown:b=>{if(b.pointerType==="touch"){b.preventDefault(),st.current.down(b.pointerId,{x:b.clientX,y:b.clientY}),lt.current=ge&&!G?_n(b):null,b.currentTarget.setPointerCapture(b.pointerId),$e.current&&window.clearTimeout($e.current),Ze.current="none",dt.current=ge&&!G?{x:b.clientX,y:b.clientY}:null,Jt.current=b.timeStamp,dt.current&&($e.current=window.setTimeout(()=>{Ze.current="armed"},550));return}if(G&&we.current){const D=we.current;Te.current={x:b.clientX,y:b.clientY,left:D.scrollLeft,top:D.scrollTop},b.currentTarget.setPointerCapture(b.pointerId);return}if(!ge)return;const N=_n(b);N&&(ut.current=!0,b.currentTarget.setPointerCapture(b.pointerId),xt({kind:"pointer",action:"down",...N,button:"left"}))},onPointerMove:b=>{if(b.pointerType==="touch"){b.preventDefault();const D=st.current.move(b.pointerId,{x:b.clientX,y:b.clientY}),re=we.current;if(!D||!re)return;const ce=D.pointers>=2&&Math.abs(D.distanceRatio-1)>.05,Ve=Math.max(.5,Math.min(5,Tt.current*D.scale));if(ce&&Ve!==Tt.current){const qe=b.currentTarget.getBoundingClientRect();He.current={x:(D.from.x-qe.left)/qe.width,y:(D.from.y-qe.top)/qe.height,clientX:D.to.x,clientY:D.to.y},Tt.current=Ve,On.flushSync(()=>te(Ve));return}if($e.current&&(window.clearTimeout($e.current),$e.current=null),Ze.current==="armed"&&dt.current){Ze.current="drag";const qe=_n(b);qe&&xt({kind:"pointer",action:"down",...qe,button:"left"})}if(Ze.current==="drag"){const qe=_n(b);qe&&xt({kind:"pointer",action:"move",...qe,button:"left"});return}const Pe=Tt.current<=1.001;if(ge&&!G&&(D.pointers>=2||Pe)){const qe=Og(D.from,D.to);if(qe){const Xe=lt.current??_n(b);Xe&&xt({kind:"pointer",action:"wheel",...Xe,...qe})}return}re.scrollLeft+=D.from.x-D.to.x,re.scrollTop+=D.from.y-D.to.y;return}if(G&&Te.current&&we.current){const D=Te.current;we.current.scrollTo(D.left+D.x-b.clientX,D.top+D.y-b.clientY);return}if(!ge||!ut.current)return;const N=_n(b);N&&xt({kind:"pointer",action:"move",...N,button:"left"})},onPointerUp:b=>{var D,re;if(b.pointerType==="touch"){b.preventDefault(),$e.current&&(window.clearTimeout($e.current),$e.current=null);const ce=_n(b);lt.current=null;const Ve=st.current.up(b.pointerId,{x:b.clientX,y:b.clientY});if(Ze.current==="armed"){Ze.current="none";const Pe=b.timeStamp-Jt.current;if(Ve&&Pe>=800&&ce&&ge&&!G){st.current.reset(),xt({kind:"pointer",action:"down",...ce,button:"right"}),xt({kind:"pointer",action:"up",...ce,button:"right"});return}}if(Ze.current==="drag"){Ze.current="none",st.current.reset(),ce&&ge&&xt({kind:"pointer",action:"up",...ce,button:"left"});return}if(Ve&&ce&&ge&&!G){const Pe=q.current,qe=Pe!==null&&Date.now()-se.current<6e4&&Bg(Pe,(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport),ce.x,ce.y,.03);qe&&!Y.current?((D=Nt.current)==null||D.focus({preventScroll:!0}),B(!0),Ke(!1)):!qe&&Y.current&&((re=Nt.current)==null||re.blur(),B(!1));const Xe=(M==null?void 0:M.viewport)??(I==null?void 0:I.viewport),jt=Gt.current;jt!==null&&Date.now()-jt.at<400&&Xe!==void 0&&Math.hypot((ce.x-jt.x)*Xe.width,(ce.y-jt.y)*Xe.height)<Xe.width*.03?(xt({kind:"pointer",action:"down",...ce,button:"left",click:2}),Vt(ce,2),Gt.current=null):(xt({kind:"pointer",action:"down",...ce,button:"left"}),Vt(ce),Gt.current={at:Date.now(),x:ce.x,y:ce.y})}return}if(G){Te.current=null;return}if(!ge)return;const N=_n(b);ut.current=!1,N&&Vt(N)},onPointerCancel:b=>{st.current.up(b.pointerId,{x:b.clientX,y:b.clientY},!0),Te.current=null,ut.current=!1,lt.current=null,$e.current&&(window.clearTimeout($e.current),$e.current=null),Ze.current="none",dt.current=null,Jt.current=0},onLostPointerCapture:b=>{st.current.up(b.pointerId,{x:b.clientX,y:b.clientY},!0),$e.current&&(window.clearTimeout($e.current),$e.current=null),Ze.current="none",dt.current=null,Jt.current=0},onWheel:b=>{if(!ge||G)return;const N=_n(b);N&&xt({kind:"pointer",action:"wheel",...N,deltaX:b.deltaX,deltaY:b.deltaY})},onKeyDown:b=>{!ge||G||b.target===Nt.current&&b.key.length===1&&!b.ctrlKey&&!b.metaKey&&!b.altKey||(xt({kind:"key",action:"down",key:b.key,code:b.code,text:b.key.length===1?b.key:"",modifiers:ac(b)}),["Backspace","Tab","Enter","ArrowUp","ArrowDown","ArrowLeft","ArrowRight","PageUp","PageDown","Home","End","Escape"].includes(b.key)&&b.preventDefault())},onKeyUp:b=>{!ge||G||b.target===Nt.current&&b.key.length===1&&!b.ctrlKey&&!b.metaKey&&!b.altKey||ge&&xt({kind:"key",action:"up",key:b.key,code:b.code,modifiers:ac(b)})},children:[e.jsx("img",{src:Mn,alt:(I==null?void 0:I.title)||"浏览器实时画面",draggable:!1,decoding:"async"}),e.jsx("video",{ref:Zt,className:`browser-live-video ${Ue==="live"?"is-live":""}`,"aria-label":Q?"桌面实时视频流":"浏览器实时视频流",autoPlay:!0,playsInline:!0,muted:!0}),e.jsx("input",{ref:Nt,className:"browser-live-mobile-input","aria-label":"浏览器键盘输入",defaultValue:"",inputMode:"text",autoCapitalize:"none",autoCorrect:"off",autoComplete:"off",spellCheck:!1,onCompositionStart:()=>{Nn.current=!0},onCompositionEnd:b=>{Nn.current=!1,G||Nr(b.target.value)},onBlur:b=>{Nn.current=!1,nr.current="",b.target.value="",B(!1)},onChange:b=>{!G&&!Nn.current&&Nr(b.target.value)}}),k&&e.jsxs("div",{className:"browser-live-quality-pending",role:"status",children:[e.jsx(ot,{size:13,className:"spin","aria-hidden":"true"}),"正在切换至",zg[k]??k,"画质…"]})]}):e.jsxs("div",{className:"browser-live-empty",children:[L||(I==null?void 0:I.availability)==="starting"?e.jsx(ot,{size:22,className:"spin","aria-hidden":"true"}):e.jsx(bl,{size:24,"aria-hidden":"true"}),e.jsx("strong",{children:L?"正在连接浏览器":Ls}),e.jsx("span",{children:rr}),ze&&e.jsxs("div",{role:"group","aria-label":"锁屏远程操作",style:{display:"flex",gap:8,marginTop:12},children:[e.jsxs("button",{type:"button",className:"browser-live-control-button",disabled:!!ae,onClick:()=>void mr("wake"),children:[ae==="wake"?e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}):e.jsx(yl,{size:14,"aria-hidden":"true"}),"唤醒屏幕"]}),fe&&e.jsxs("button",{type:"button",className:"browser-live-control-button",disabled:Ge,onClick:()=>{Ye(null),Ie(!0)},children:[e.jsx(ml,{size:14,"aria-hidden":"true"}),"远程解锁"]})]})]})}),d&&e.jsxs("button",{type:"button",className:"browser-live-exit-fullscreen",onClick:()=>void f(),children:[e.jsx(vo,{size:14,"aria-hidden":"true"}),"退出全屏"]}),ge&&!G&&e.jsxs("div",{className:"browser-live-control-cue",children:[e.jsx(Sp,{size:13,"aria-hidden":"true"})," ",Q?"当前输入会发送到本机":"当前输入会发送到浏览器",Q&&Qt?` · ${Qt}`:"",Q&&Kt?` · ${Kt}`:"",rt!=null?` · 控制 ${rt}ms`:""]})]}),e.jsxs("footer",{className:"browser-live-footer",children:[e.jsxs("div",{className:"browser-live-location",children:[e.jsx("span",{className:`browser-live-status-dot is-${(I==null?void 0:I.state)??"idle"}`,"aria-hidden":"true"}),e.jsxs("div",{children:[e.jsx("strong",{children:br}),e.jsx("span",{title:I==null?void 0:I.url,children:(I==null?void 0:I.capabilityError)||(Q?"本机屏幕":I==null?void 0:I.url)||$||"等待可观看的直播会话"})]}),(I==null?void 0:I.url)&&!Q&&e.jsx(lp,{size:13,"aria-hidden":"true"})]}),I&&(ge?e.jsxs("button",{type:"button",className:"browser-live-control-button is-return",onClick:()=>void gs(),disabled:Ee,children:[Ee&&e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}),Q?"结束控制":"归还给 Agent"]}):e.jsxs("button",{type:"button",className:"browser-live-control-button",onClick:()=>void qn(),disabled:!_r||Ee||I.state!=="agent-controlled"||I.availability!=="ready",children:[Ee&&e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}),I.controlledByAnotherViewer?"其他设备操作中":Q?"开始控制":"接管浏览器"]}))]}),($??gt)&&e.jsx("div",{className:"browser-live-error",role:"alert",children:$??gt})]}),De&&e.jsx("div",{className:"browser-live-unlock-backdrop",role:"presentation",onMouseDown:b=>{b.target===b.currentTarget&&!Ge&&(Ie(!1),at(""),Ye(null))},children:e.jsxs("form",{className:"browser-live-unlock-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"browser-live-unlock-title",onSubmit:b=>{b.preventDefault(),An()},children:[e.jsxs("div",{className:"browser-live-unlock-heading",children:[e.jsx(ml,{size:18,"aria-hidden":"true"}),e.jsx("strong",{id:"browser-live-unlock-title",children:"远程解锁 Windows"})]}),e.jsx("label",{htmlFor:"browser-live-unlock-password",children:"Windows 密码或 PIN"}),e.jsx("input",{id:"browser-live-unlock-password",type:"password",autoComplete:"off",autoFocus:!0,maxLength:256,value:We,disabled:Ge,onChange:b=>at(b.target.value)}),be&&e.jsx("p",{role:"alert",children:be}),e.jsxs("div",{className:"browser-live-unlock-actions",children:[e.jsx("button",{type:"button",className:"browser-live-control-button is-return",disabled:Ge,onClick:()=>{Ie(!1),at(""),Ye(null)},children:"取消"}),e.jsxs("button",{type:"submit",className:"browser-live-control-button",disabled:Ge||!We,children:[Ge&&e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}),"解锁"]})]})]})})]}),document.body)}const Hg=[{prompt:"带我熟悉这个项目",Icon:np},{prompt:"帮我排查一个问题",Icon:dd},{prompt:"一起实现一个新想法",Icon:hp}];function Ug(t){return t>=5&&t<9?{title:"早啊。",prompt:"新的一天,想做点什么?"}:t>=9&&t<12?{title:"上午好。",prompt:"今天想一起做点什么?"}:t>=12&&t<14?{title:"中午好。",prompt:"想趁午休推进点什么?"}:t>=14&&t<18?{title:"下午好。",prompt:"这个下午,想做点什么?"}:t>=18&&t<23?{title:"晚上好。",prompt:"今晚想一起做点什么?"}:{title:"夜深了。",prompt:"注意休息,重要的事可以先留给我。"}}const qg={"customer-agent":"Customer Agent",codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode"};function Vg({agentType:t,ready:n,now:r,onSelectPrompt:s}){const i=qg[t],o=Ug((r??new Date).getHours());return e.jsxs("section",{className:"empty-session-welcome","aria-labelledby":"empty-session-welcome-title",children:[e.jsxs("div",{className:"empty-session-welcome__core","aria-hidden":"true",children:[e.jsx("span",{className:"empty-session-welcome__glow"}),e.jsxs("svg",{viewBox:"0 0 120 120",role:"presentation",children:[e.jsx("circle",{className:"empty-session-welcome__orbit empty-session-welcome__orbit--outer",cx:"60",cy:"60",r:"44"}),e.jsx("circle",{className:"empty-session-welcome__orbit empty-session-welcome__orbit--inner",cx:"60",cy:"60",r:"33"}),e.jsx("rect",{className:"empty-session-welcome__diamond",x:"43",y:"43",width:"34",height:"34",rx:"2"}),e.jsx("circle",{className:"empty-session-welcome__pulse",cx:"60",cy:"60",r:"3"})]})]}),e.jsxs("div",{className:"empty-session-welcome__copy",children:[e.jsx("p",{className:"empty-session-welcome__status",children:n?`${i} · 已准备好`:`${i} · 等待配置`}),e.jsx("h2",{id:"empty-session-welcome-title",children:o.title}),e.jsx("p",{className:"empty-session-welcome__prompt",children:n?o.prompt:"配置好 API Key 后,我就能开始。"})]}),e.jsx("div",{className:"empty-session-welcome__starters","aria-label":"开始一个任务",children:Hg.map(({prompt:l,Icon:d})=>e.jsxs("button",{type:"button","data-prompt":l,disabled:!n,onClick:()=>s(l),children:[e.jsx(d,{size:16,strokeWidth:1.8,"aria-hidden":"true"}),e.jsx("span",{children:l})]},l))})]})}function Gg({image:t,onClose:n}){return a.useEffect(()=>{if(!t)return;const r=document.body.style.overflow,s=i=>{i.key==="Escape"&&n()};return document.body.style.overflow="hidden",window.addEventListener("keydown",s),()=>{window.removeEventListener("keydown",s),document.body.style.overflow=r}},[t,n]),t?On.createPortal(e.jsxs("div",{className:"message-image-lightbox",role:"dialog","aria-modal":"true","aria-label":"图片预览",onClick:r=>{r.target===r.currentTarget&&n()},children:[e.jsx("img",{className:"message-image-lightbox__image",src:t.src,alt:t.alt}),e.jsx("button",{type:"button",className:"message-image-lightbox__close",onClick:n,"aria-label":"关闭图片预览",title:"关闭",autoFocus:!0,children:e.jsx(Tr,{size:22,"aria-hidden":"true"})})]}),document.body):null}const Kg={pending:"⏳",image_generating:"🎨",video_generating:"🎬",done:"✅",error:"❌"};function Qg(t){const{title:n="视频工作台",shots:r=[],status:s="generating",composedVideoUrl:i,isAgentRunning:o}=t,[l,d]=a.useState(!1),[u,f]=a.useState(null);return e.jsxs("div",{style:{border:"1px solid var(--border-subtle)",borderRadius:"var(--radius-md)",background:"var(--bg-surface)",overflow:"hidden",maxWidth:600},children:[e.jsxs("div",{onClick:()=>d(!l),style:{display:"flex",alignItems:"center",justifyContent:"space-between",padding:"10px 16px",background:"var(--bg-deep)",cursor:"pointer",userSelect:"none",borderBottom:l?"none":"1px solid var(--border-subtle)"},children:[e.jsxs("span",{style:{fontSize:14,fontWeight:600,color:"var(--text-primary)"},children:["🎬 ",n]}),e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:[r.filter(p=>p.status==="done").length,"/",r.length," 完成",e.jsx("span",{style:{marginLeft:6,transform:l?"rotate(-90deg)":"none",display:"inline-block",transition:"transform 0.2s"},children:"▼"})]})]}),!l&&e.jsxs("div",{style:{padding:"12px 16px"},children:[e.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:13,marginBottom:12},children:[e.jsx("thead",{children:e.jsxs("tr",{style:{background:"var(--bg-deep)"},children:[e.jsx("th",{style:ni,children:"#"}),e.jsx("th",{style:{...ni,textAlign:"left",minWidth:120},children:"画面描述"}),e.jsx("th",{style:ni,children:"时长"}),e.jsx("th",{style:ni,children:"状态"}),e.jsx("th",{style:ni,children:"预览"})]})}),e.jsx("tbody",{children:r.map(p=>e.jsxs("tr",{style:{borderBottom:"1px solid var(--border-subtle)"},children:[e.jsx("td",{style:ri,children:p.index}),e.jsx("td",{style:{...ri,textAlign:"left",maxWidth:180,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:p.description,children:p.description}),e.jsxs("td",{style:ri,children:[p.duration,"s"]}),e.jsxs("td",{style:ri,children:[Kg[p.status]??"⏳",p.error&&e.jsx("span",{style:{color:"var(--danger)",fontSize:11,marginLeft:4},title:p.error,children:"!"})]}),e.jsx("td",{style:ri,children:p.videoUrl?e.jsx("button",{onClick:()=>f(p.videoUrl),style:{background:"var(--accent-dim)",color:"var(--accent)",border:"1px solid rgba(79,110,247,0.22)",borderRadius:6,padding:"2px 8px",fontSize:11,cursor:"pointer"},children:"▶ 播放"}):p.previewImageUrl?e.jsx("img",{src:p.previewImageUrl,alt:`shot-${p.index}`,style:{width:48,height:32,objectFit:"cover",borderRadius:4,border:"1px solid var(--border-subtle)"}}):e.jsx("span",{style:{color:"var(--text-muted)",fontSize:11},children:"—"})})]},p.index))})]}),u&&e.jsx("video",{src:u,controls:!0,autoPlay:!0,style:{width:"100%",borderRadius:8,marginBottom:12,border:"1px solid var(--border-subtle)"}}),i&&e.jsxs("div",{style:{marginBottom:12},children:[e.jsx("div",{style:{fontSize:12,fontWeight:600,color:"var(--text-primary)",marginBottom:6},children:"完整视频"}),e.jsx("video",{src:i,controls:!0,style:{width:"100%",borderRadius:8,border:"1px solid var(--border-subtle)"}})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-muted)"},children:[s==="generating"&&e.jsx("span",{children:o===!1?"本轮已结束":"🔄 生成中..."}),s==="preview_ready"&&e.jsx("span",{children:"📷 预览图已就绪"}),s==="video_ready"&&e.jsx("span",{children:"🎬 视频片段已就绪"}),s==="composed"&&e.jsx("span",{children:"✅ 合成完成"})]})]})]})}const ni={padding:"6px 10px",textAlign:"center",fontWeight:600,fontSize:12,color:"var(--text-muted)",borderBottom:"1px solid var(--border-subtle)"},ri={padding:"6px 10px",textAlign:"center",fontSize:13,color:"var(--text-secondary)"},Xg={storyboard_workbench:Qg};function Yg(t,n,r){return!t||n!==t?!1:r===null||r===t}function Jg(t,n,r=Date.now()){return!t||t.sessionId!==n?t:{...t,until:r+9e4}}async function Zg(t){const{text:n,projectId:r,createSession:s,activateSession:i,showUserMessage:o,onSessionCreated:l,isCancelled:d}=t,u=!t.sessionId;let f=t.sessionId??null;if(!f){const p=await s(n.slice(0,60)||"语音任务",r||void 0);if(d!=null&&d())return null;f=p.id}return i(f),o(n,f),u&&l&&await l(f),f}async function lc(t){var i,o,l;const n=((i=t.sessionId)==null?void 0:i.trim())||null,r=!n,s=n??(await t.createSession(t.text.slice(0,60)||"New Session",t.projectId||void 0)).id.trim();if(!s)throw new Error("创建会话失败:服务端未返回会话 ID");return t.activateSession(s),t.showUserMessage(t.text,s),await((o=t.afterUserMessageShown)==null?void 0:o.call(t)),r&&await((l=t.onSessionCreated)==null?void 0:l.call(t,s)),s}function em(t=window){return new Promise(n=>{let r=!1,s;const i=()=>{r||(r=!0,s!==void 0&&t.clearTimeout(s),n())};s=t.setTimeout(i,100),t.requestAnimationFrame(()=>{t.setTimeout(i,0)})})}const tm=/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+|[ \t]*\/[^)\n]+)\)/gi,nm=/`([^`\n]+)`/g,rm=/:codex-file-citation\{([^}\n]*)\}/g,cc=/([A-Za-z][\w-]*)="([^"\n]*)"/g,sm=/\uE200visualize\uE202([^\uE201\n]+)\uE201/g;function ja(t){if(!t.startsWith("/")||t.includes("?")||t.includes("#")||t.includes("\0"))return null;const n=t.match(/^(\/.*):([1-9]\d*)$/);return n?{path:n[1],line:Number(n[2])}:{path:t}}function im(t){const n={};for(const i of t.matchAll(cc)){const o=i[1];if(o!=="path"&&o!=="purpose"||n[o]!==void 0)return null;n[o]=i[2]}if(t.replace(cc,"").trim())return null;const r=ja(n.path??"");if(!r||r.line!==void 0)return null;const s=r.path.slice(r.path.lastIndexOf("/")+1)||r.path;return{path:r.path,label:s}}function om(t){try{const n=JSON.parse(t);if(!n||typeof n!="object"||Array.isArray(n))return null;const{path:r,title:s,mode:i}=n;if(typeof r!="string"||s!==void 0&&typeof s!="string"||i!==void 0&&typeof i!="string")return null;const o=ja(r);if(!o||o.line!==void 0)return null;const l=(s==null?void 0:s.trim())||o.path.slice(o.path.lastIndexOf("/")+1)||o.path;return{path:o.path,label:l}}catch{return null}}function am(t,n){const r=[];let s=0;const i=[...[...t.matchAll(tm)].map(o=>({kind:"markdown",match:o})),...[...t.matchAll(rm)].map(o=>({kind:"citation",match:o})),...[...t.matchAll(sm)].map(o=>({kind:"visualize",match:o})),...[...t.matchAll(nm)].map(o=>({kind:"code",match:o}))].sort((o,l)=>(o.match.index??0)-(l.match.index??0));for(const o of i){const{match:l}=o,d=l.index??0;if(d<s)continue;if(d>s&&r.push({type:"text",value:t.slice(s,d)}),o.kind==="code"){r.push({type:"code",value:l[1]}),s=d+l[0].length;continue}if(o.kind==="citation"){const f=im(l[1]);r.push(f?{type:"artifact",label:f.label,path:f.path,raw:l[0]}:{type:"text",value:l[0]}),s=d+l[0].length;continue}if(o.kind==="visualize"){const f=om(l[1]);r.push(f?{type:"artifact",label:f.label,path:f.path,raw:l[0]}:{type:"text",value:l[0]}),s=d+l[0].length;continue}const u=l[2];if(/^https?:\/\//i.test(u))r.push({type:"link",label:l[1],href:u});else{const f=ja(u.replace(/^[ \t]+/,""));f?r.push({type:"artifact",label:l[1],path:f.path,...f.line?{line:f.line}:{},raw:l[0]}):r.push({type:"text",value:l[0]})}s=d+l[0].length}return s<t.length&&r.push({type:"text",value:t.slice(s)}),r.length>0?r:[{type:"text",value:t}]}function lm(t){return am(t)}function Yd(t){return typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0}function cm(t){const n=Yd(t);return n===void 0?void 0:`${Math.round(n/1e3)} 秒`}function dm(t){return t.role==="user"&&!t.isQueued&&!t.isSteered}function um(t){var n,r,s;return t.role==="assistant"&&!!(t.content.trim()||(n=t.toolCalls)!=null&&n.length||(s=(r=t.presentation)==null?void 0:r.reasoning)!=null&&s.length||t.askUser||t.widget)}function pm(t,n,r){var o;const s=t[n];if((s==null?void 0:s.role)!=="assistant"||!s.content.trim()||(o=s.toolCalls)!=null&&o.length||s.isCompactionSummary)return!1;let i=!r;for(let l=n+1;l<t.length;l++){const d=t[l];if(!d.isCompactionSummary){if(dm(d)){i=!0;break}if(um(d))return!1}}return i}function fm(t,n,r){const s=t[n];if(!s)return{showCopy:!1,showSpeak:!1,showCompletion:!1,compact:!1};if(s.role==="user")return{showCopy:!!s.content,showSpeak:!1,showCompletion:!1,compact:!1};const i=pm(t,n,r);return{showCopy:i,showSpeak:i,showCompletion:i,compact:s.role==="assistant"&&!i&&!s.isCompactionSummary}}const hm=new Set(["image/jpeg","image/png","image/gif","image/webp"]);async function gm(t,n){const r=[],s=[],i=[];for(const l of t){const d=l.type.trim().toLowerCase();d.startsWith("image/")?hm.has(d)?r.push(l):i.push(l):s.push(l)}const o=await Promise.all(r.map(async l=>{try{return{file:l,dataUrl:await n(l)}}catch{return{file:l,dataUrl:null}}}));return{images:o.flatMap(l=>l.dataUrl?[l.dataUrl]:[]),attachments:s,unsupportedImages:i,failedImages:o.flatMap(l=>l.dataUrl?[]:[l.file])}}function Rs(t,n){return n?t[n]:void 0}function mm(t,n){const r=Object.fromEntries(Object.entries(t).filter(([,s])=>s.token!==n.token&&s.sourceSessionId!==n.sourceSessionId));return r[n.sourceSessionId]=n,n.forkSessionId&&(r[n.forkSessionId]=n),r}function xm(t,n){const r=t[n];return r?Object.fromEntries(Object.entries(t).filter(([,s])=>s.token!==r.token)):t}function bm(t,n,r=crypto.randomUUID()){return{token:r,sourceSessionId:t,payload:{...n,images:n.images?[...n.images]:void 0,agentIds:n.agentIds?[...n.agentIds]:void 0,restoreDraftOnFailure:n.restoreDraftOnFailure},sendAttempted:!1}}function dc(t,n){return t.forkSessionId===n&&t.sendAttempted?t:{...t,forkSessionId:n,sendAttempted:!0}}function uc(t){return`occupied-recovery:${t.token}`}function ym(t,n){return!!(t&&n&&(t.sourceSessionId===n||t.forkSessionId===n))}async function pc(t){const n=await t.forkSession(t.sourceSessionId);return t.activateSession(n.id),await t.refreshAndSelect(n),n}const Rr=50,Mo=1,si=1,fc=160;function hc(t){return t.trim().replace(/^\/goal\s+/i,"").replace(/^\$([\w-]+)/,"/$1").trim()}function Ao(t){const r=t.trim().replace(/^每(?:隔)?/,"").match(/^(\d+(?:\.\d+)?)\s*(s|sec|秒|m|min|分钟?|h|hr|小时)$/i);if(r){const o=parseFloat(r[1]),l=r[2].toLowerCase(),d=l==="s"||l==="sec"||l==="秒"?o*1e3:l==="m"||l==="min"||l==="分"||l==="分钟"?o*6e4:o*36e5;return d>=36e5&&d%36e5===0?`每 ${d/36e5} 小时`:d>=6e4&&d%6e4===0?`每 ${d/6e4} 分钟`:`每 ${d/1e3} 秒`}const[s,i]=t.trim().split(/\s+/);return s==="0"&&i&&i!=="*"&&!i.includes("/")&&!i.includes(",")?`每天 ${i.padStart(2,"0")}:00`:`cron: ${t}`}function vm(t){const n=t.split(/(`[^`\n]+`)/g);return n.length<=1?t:e.jsx(e.Fragment,{children:n.map((r,s)=>s%2===1?e.jsx("code",{style:{fontFamily:"var(--font-mono)",fontSize:"0.84em",background:"rgba(17,24,39,0.06)",padding:"1px 5px",borderRadius:4,color:"var(--accent)",border:"1px solid var(--border-subtle)"},children:r.slice(1,-1)},s):e.jsx("span",{children:r},s))})}function Jd(t,n){return t.split(/(\*\*[^*]+\*\*|\*[^*]+\*)/g).map((s,i)=>{const o=`${n}-${i}`;return s.startsWith("**")&&s.endsWith("**")&&s.length>4?e.jsx("strong",{style:{fontWeight:600,color:"var(--text-primary)"},children:s.slice(2,-2)},o):s.startsWith("*")&&s.endsWith("*")&&s.length>2?e.jsx("em",{children:s.slice(1,-1)},o):e.jsx("span",{children:s},o)})}function gc(t,n){return t.split(/(`[^`\n]+`)/g).map((s,i)=>i%2===1?e.jsx("code",{style:{fontFamily:"var(--font-mono)",fontSize:"0.84em",background:"rgba(17,24,39,0.06)",padding:"1px 5px",borderRadius:4,color:"var(--accent)",border:"1px solid var(--border-subtle)"},children:s.slice(1,-1)},`${n}-${i}`):Jd(s,`${n}-${i}`))}function ta(t,n){return lm(t).map((r,s)=>{if(r.type==="code")return e.jsx("code",{style:{fontFamily:"var(--font-mono)",fontSize:"0.84em",background:"rgba(17,24,39,0.06)",padding:"1px 5px",borderRadius:4,color:"var(--accent)",border:"1px solid var(--border-subtle)"},children:r.value},s);if(r.type==="link")return e.jsx("a",{className:"chat-message-link",href:r.href,target:"_blank",rel:"noopener noreferrer",children:gc(r.label,`${s}-label`)},s);if(r.type==="artifact"){if(!n)return e.jsx("span",{children:r.raw},s);const i=r.line?`${r.path}:${r.line}`:r.path,o=r.label.replace(/^`([^`\n]+)`$/,"$1");return e.jsxs("button",{type:"button",className:"chat-message-artifact-link",title:i,"aria-label":`打开交付物 ${o}`,onClick:()=>n(r.path),children:[e.jsx(ci,{size:16,strokeWidth:1.8,"aria-hidden":"true"}),e.jsx("span",{children:gc(r.label,`${s}-label`)})]},s)}return Jd(r.value,`${s}`)})}function wm(t){if(t.length<2)return null;const n=o=>o.replace(/^\|/,"").replace(/\|$/,"").split("|").map(l=>l.trim()),r=n(t[0]),s=t[1].replace(/^\|/,"").replace(/\|$/,"");if(!/^[\s\-:|]+$/.test(s))return null;const i=t.slice(2).map(n);return{headers:r,rows:i}}function km(t,n,r){const s=i=>({padding:"6px 14px",textAlign:"left",fontSize:13,fontWeight:i?600:400,color:i?"var(--text-primary)":"var(--text-secondary)",borderBottom:"1px solid var(--border-subtle)",whiteSpace:"pre-wrap",wordBreak:"break-word"});return e.jsx("div",{style:{margin:"8px 0",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",overflow:"auto",background:"var(--bg-surface)"},children:e.jsxs("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:13},children:[e.jsx("thead",{children:e.jsx("tr",{style:{background:"var(--bg-deep)"},children:t.map((i,o)=>e.jsx("th",{style:s(!0),children:ta(i,r)},o))})}),e.jsx("tbody",{children:n.map((i,o)=>e.jsx("tr",{style:{background:o%2===0?"transparent":"rgba(0,0,0,0.015)"},children:i.map((l,d)=>e.jsx("td",{style:s(!1),children:ta(l,r)},d))},o))})]})})}function jm(t,n,r){return t.toLowerCase()==="mermaid"?e.jsx(ef,{code:n,complete:r}):e.jsxs("div",{style:{margin:"8px 0",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",overflow:"hidden",background:"var(--bg-surface)"},children:[e.jsx("div",{style:{padding:"4px 10px",background:"var(--bg-deep)",borderBottom:"1px solid var(--border-subtle)",fontSize:10,color:"var(--text-muted)",fontFamily:"var(--font-mono)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em"},children:t||"code"}),e.jsx("pre",{style:{margin:0,padding:"10px 12px",fontSize:12,lineHeight:1.6,fontFamily:"var(--font-mono)",color:"var(--text-secondary)",whiteSpace:"pre-wrap",wordBreak:"break-word",overflow:"auto",maxHeight:420},children:n})]})}function Zd(t,n){const s=t.replace(/(^|\n)(?:[a-z][\w+#.-]{0,20}\n)?(?:复制|copy)\n(?:下载|download)(?:\n|$)/gi,"$1").split(`
|
|
462
462
|
`),i=[];let o=0,l=0;const d=f=>f.trimStart().startsWith("```"),u=f=>s[f].trimStart().startsWith("|")&&f+1<s.length&&/^\|[\s\-:|]+\|$/.test(s[f+1].trim());for(;o<s.length;){if(d(s[o])){const f=s[o].trim().slice(3).trim();o++;const p=[];for(;o<s.length&&!d(s[o]);)p.push(s[o]),o++;const v=o<s.length;o++,i.push(e.jsx("div",{children:jm(f,p.join(`
|
|
463
463
|
`),v)},`code-${l++}`));continue}if(u(o)){const f=[];for(;o<s.length&&s[o].trimStart().startsWith("|");)f.push(s[o].trim()),o++;const p=wm(f);p?i.push(e.jsx("div",{children:km(p.headers,p.rows,n)},`tbl-${l++}`)):i.push(e.jsx("span",{children:f.map((v,x)=>e.jsxs("span",{children:[vm(v),x<f.length-1?`
|
|
464
464
|
`:null]},x))},`tbl-fb-${l++}`))}else{const f=[];for(;o<s.length&&!u(o)&&!d(s[o]);)f.push(s[o]),o++;f.length>0&&i.push(e.jsx("span",{children:f.map((p,v)=>e.jsxs("span",{children:[ta(p,n),v<f.length-1?`
|
|
465
|
-
`:null]},v))},`txt-${l++}`))}}return e.jsx(e.Fragment,{children:i})}const eu=[{value:"off",label:"关"},{value:"low",label:"低"},{value:"medium",label:"中"},{value:"high",label:"高"}],mc=Object.fromEntries(eu.map(t=>[t.value,t.label])),Sm=750,To={low:"低",medium:"中",high:"高",xhigh:"超高",max:"最大"},xc={codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode"};function Cm(t,n){return n==="codex"?t==="openai":n==="claude-code"?t==="anthropic":!1}const Li=[{value:"request-approval",label:"请求批准",description:"编辑外部文件和使用互联网时始终询问"},{value:"auto-approval",label:"帮我批准",description:"仅对检测到的风险操作请求批准"},{value:"full-access",label:"完全访问权限",description:"可不受限制地访问互联网和你电脑上的任何文件"}];function bc(t){return Li.some(n=>n.value===t)?t:"full-access"}function Im({activeAgentType:t="customer-agent",selectedProjectId:n=null,selectedSessionId:r=null,onSessionCreated:s,onMessageSent:i,onSubSessionCreated:o,onSelectSession:l,onSubAgentEvent:d,onRunComplete:u,sessionTitle:f,sessionSummary:p,workspacePath:v=null,onOpenSettings:x,settingsOpen:w=!1,onHideToBackground:j,onOpenHub:E,onOpenDesktopLive:S,desktopLiveOpen:C=!1,fileDrawerOpen:k=!1,onToggleFiles:z,onOpenArtifact:M,onToggleAppearance:H,appearanceOpen:L=!1,hideToBackgroundTitle:T,voiceCommand:A=null}){var Ya,Ja,Za,el,tl,nl,rl,sl,il,ol;const R=a.useCallback(c=>Zd(c,M),[M]),{messages:$,messagesBySession:F,runningSessionId:Ee,appendText:Ke,addMessage:ae,setRunningSession:ke,setSessionId:Pe,updateToolResult:Ie,updateSubAgentStatus:We,updateSubAgentProgress:at,updateMessage:qe,setMessages:ne,getMessagesForSession:be,getSessionHistoryWindow:Ye,contextUsageBySession:W,runtimeProgressBySession:te,nativeSubagentsBySession:G,setContextUsage:le,applyRuntimeProgress:pe,setRuntimeProgress:ye,clearRuntimeProgress:we,applyNativeSubagentActivity:Te,setNativeSubagentActivities:dt,applyReasoningSummary:lt,applyCodexExecutionEvent:st,clearMessages:Tt,sessionId:$e,todos:Nt,setTodos:ct,cronTasks:B,setCronTasks:Y}=Ze(),[q,se]=a.useState({active:null,queued:[],history:[]}),[ee,Ve]=a.useState(null),[ut,nn]=a.useState(0),et=Lf($,F,$e,r),Ge=a.useMemo(()=>Kd(th(Nh(et.filter(c=>!c.isQueued),q.queued),t==="codex")),[t,q.queued,et]),Gt=a.useMemo(()=>{var c,m;return(m=(c=Ge.findLast(h=>h.executionTrace))==null?void 0:c.executionTrace)==null?void 0:m.turnId},[Ge]),{revision:rt,isConfigured:Pt,profiles:ht,activeProfileId:_t,switchActiveProfile:ln,loadFromSystem:vn,contextWindow:He,reasoningEffort:Dt,taskNotifications:Xn,setField:$n,saveToSystem:cn}=qi(),X=r||$e,[dn,Jt]=a.useState({}),wt=a.useRef({}),Rt=a.useCallback((c,m)=>{const h=c?mm(wt.current,c):m?xm(wt.current,m):wt.current;wt.current=h,Jt(h)},[]),gt=Rs(dn,X),[Wt,mt]=a.useState(!1),[wn,Yn]=a.useState(null),Jn=a.useRef(!1),[Zt,Hn]=a.useState("idle"),[en,Zn]=a.useState(!1);a.useEffect(()=>{if(!Vo()||!window.browserLiveApi)return;const c=()=>Zn(!0);return window.addEventListener(ul,c),()=>window.removeEventListener(ul,c)},[]);const[kn,un]=a.useState(null),[ar,jn]=a.useState(null),Un=Lh(r,p,t),Ne=Un.agentType,it=Un.ready&&Wh(p,t),[Ht,er]=a.useState([]),[Wn,Ft]=a.useState(null),I=a.useRef(null),[Q,fe]=a.useState(()=>El(Ne)),[ze,ge]=a.useState(!1),Ut=a.useRef(null);a.useEffect(()=>{fe(El(Ne)),ge(!1)},[Ne]),a.useEffect(()=>{var m;if(!it||!((m=window.agentApi)!=null&&m.listAgentModels)||I.current===Ne)return;const c=Ne;I.current=c,er([]),Ft(null),window.agentApi.listAgentModels(c).then(h=>{I.current===c&&(er(h.models??[]),Ft(c))}).catch(()=>{I.current===c&&(er([]),Ft(null),I.current=null)})},[it,Ne]),a.useEffect(()=>{if(!ze)return;const c=m=>{Ut.current&&!Ut.current.contains(m.target)&&ge(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[ze]);const rn=a.useCallback(c=>{fe(m=>{const h={...m,...c};return Ml(Ne,h),h})},[Ne]),pt=a.useMemo(()=>it?Ht.map(c=>({key:oi(c),label:c.displayName||c.id,model:{id:c.id,...c.providerID?{providerID:c.providerID}:{}},reasoningEfforts:c.reasoningEfforts})):[],[it,Ht]),Sn=a.useMemo(()=>it?(ht??[]).filter(c=>{var m;return(m=c.modelId)==null?void 0:m.trim()}).filter(c=>Ne==="opencode"||Cm(c.provider,Ne)).map(c=>({key:Ne==="opencode"?oi({id:c.modelId,providerID:c.provider}):c.modelId,label:c.name||c.modelId,model:{id:c.modelId,...Ne==="opencode"?{providerID:c.provider}:{}}})):[],[it,ht,Ne]),hr=a.useMemo(()=>Ne==="opencode"?Sf(Ht):[],[Ne,Ht]),hs=a.useMemo(()=>new Set([...pt.map(c=>c.key),...Sn.map(c=>c.key)]),[pt,Sn]),lr=Wn===Ne&&rt!==void 0,Bt=a.useMemo(()=>kf(Q,hs,lr),[hs,lr,Q]);a.useEffect(()=>{Bt!==Q&&(fe(Bt),Ml(Ne,Bt))},[Ne,Bt,Q]);const sn=(Ya=Bt.model)!=null&&Ya.id?oi(Bt.model):"",tr=a.useMemo(()=>{var m;const c=pt.find(h=>h.key===sn);if((m=c==null?void 0:c.reasoningEfforts)!=null&&m.length)return c.reasoningEfforts;if(Ne==="claude-code")return["low","medium","high","xhigh"]},[pt,sn,Ne]),gr=a.useMemo(()=>it?Ne==="codex"?tr??[]:Ne==="claude-code"?tr??["low","medium","high","xhigh"]:[]:[],[it,Ne,tr]),qt=Bt.reasoningEffort&&gr.includes(Bt.reasoningEffort)?Bt.reasoningEffort:void 0,Xr=pt.length>0||Sn.length>0,Yr=(p==null?void 0:p.messageQueueVersion)===1,Mn=bh(p==null?void 0:p.agentType),cr=kn===X?"direct":ar?"incompatible":(Ja=p==null?void 0:p.compatibility)==null?void 0:Ja.status,on=cr!==void 0&&cr!=="direct",pn=on||(p==null?void 0:p.occupancy)==="owned-externally"&&p.agentType!=="codex",qn=ym(gt,X),gs=qn&&(gt==null?void 0:gt.forkSessionId)!==X,mr=Pt||it,An=Un.ready&&mr&&!pn&&!qn&&Zt!=="released",xt=a.useRef(new Set),[kt,Tn]=a.useState("idle"),fn=a.useRef("idle"),Vt=a.useRef(null),[Nn,nr]=a.useState(()=>Date.now()),Nr=a.useCallback(c=>{Vt.current=c,fn.current="thinking",nr(Date.now()),Tn("thinking")},[]),Ot=!!(X&&(Ee===X||xt.current.has(X))),xr=Oh(p,Ot),Cn=Ot||Fh(p),dr=X?te[X]??[]:[],_n=X?G[X]??{}:{},_r=Cf(dr),br=Ge[Ge.length-1],Ls=!!((br==null?void 0:br.role)==="assistant"&&kt==="thinking"&&((el=(Za=br.presentation)==null?void 0:Za.reasoning)!=null&&el.some(c=>c.text.trim()))),rr=kt==="tools"&&Ge.some(c=>{var m;return((m=c.toolCalls)==null?void 0:m.length)&&!So(c.toolCalls)}),ur=Cn&&!_r&&!Ls&&!rr;a.useEffect(()=>{vn()},[]),a.useEffect(()=>{window.agentApi&&window.agentApi.cronList().then(c=>Y(c))},[]);const[Kt,Qt]=a.useState(""),[b,N]=a.useState(null),[D,re]=a.useState(""),[ce,Qe]=a.useState(null),[De,Ue]=a.useState(()=>new Set),Xe=a.useRef(new Set),[jt,zt]=a.useState(null),$t=a.useRef(null),[Vn,zn]=a.useState(!1),[yr,Je]=a.useState(!1),[zr,Lt]=a.useState(!1),[Ln,Lr]=a.useState("full-access"),[sr,ui]=a.useState(!1),[pi,hn]=a.useState(null),[fi,Ps]=a.useState(!1),ms=a.useRef(null),Pr=a.useRef(null),an=a.useCallback((c,m)=>{var O;const h=nt.current||yt.current;if(m===h&&(se(Jl(c)),((O=c.active)==null?void 0:O.kind)==="message"&&(fn.current!=="thinking"||Vt.current!==m)&&Nr(m),V.current==="anchored"))return;const y=be(m);ne(ko(y,c),m)},[Nr,be,ne]);a.useEffect(()=>{if(!yr)return;const c=m=>{ms.current&&!ms.current.contains(m.target)&&Je(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[yr]),a.useEffect(()=>{if(!zr)return;const c=m=>{Pr.current&&!Pr.current.contains(m.target)&&Lt(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[zr]),a.useEffect(()=>{Lt(!1),Lr(bc(p==null?void 0:p.permissionMode))},[it,r,p==null?void 0:p.permissionMode]);const[Gn,Ce]=a.useState(null),[Jr,vr]=a.useState(null),[xs,Ds]=a.useState(null),[Ws,Xi]=a.useState(0),[hi,Fs]=a.useState([]),[pr,gn]=a.useState([]),[Bs,bs]=a.useState(0),[Yi,Dr]=a.useState(null),Pn=a.useRef(null),Os=a.useRef(null),wr=a.useRef(null),Zr=a.useRef(()=>{}),es=a.useRef(new Hp),$s=a.useRef(()=>{}),g=a.useRef(null),_=a.useRef(null);_.current||(_.current=new eh);const U=a.useRef(null),V=a.useRef("latest"),K=a.useRef(null),Re=a.useRef(!1),me=a.useRef(null),Le=a.useRef(0),Fe=a.useRef(0),tn=a.useRef(null),Fn=a.useRef(!1),_e=a.useRef(!1),Et=a.useRef(null),In=a.useRef(!1),St=a.useRef(!1),Rn=a.useRef(null),Wr=a.useRef(null),ir=a.useRef(0),ts=a.useRef(null),Kn=a.useRef(new Map),Fr=a.useRef(new Set),kr=a.useRef(null),tt=a.useRef(!1),ft=a.useRef(null),ns=a.useRef(null),Ji=a.useRef(null);Ji.current||(Ji.current=new Rh(new Ih));const Xt=Ji.current,gi=a.useRef(!1),Zi=a.useRef(null),jr=a.useRef(null),mi=a.useRef(zh(fc)),[Ia,Ra]=a.useState(!1),[eo,xi]=a.useState(null),[to,no]=a.useState(null),[Hs,pu]=a.useState("latest"),[fu,ys]=a.useState(null),[hu,vs]=a.useState(null),[gu,ws]=a.useState(!1),[mu,Ea]=a.useState(!1),[ro,bi]=a.useState(!1),[xu,so]=a.useState(!1),[ks,yi]=a.useState(!1),[bu,vi]=a.useState(!1),Ma=a.useRef(null),Us=a.useRef(null),io=a.useRef(null),[Br,Aa]=a.useState(null),[yu,Ta]=a.useState([]),[vu,Na]=a.useState([]),[qs,oo]=a.useState([]),[Vs,rs]=a.useState(null),[ss,is]=a.useState(null),bt=a.useCallback(c=>nt.current===c?p==null?void 0:p.agentType:c.startsWith("runtime:codex:")?"codex":void 0,[p==null?void 0:p.agentType]),mn=a.useCallback((c,m)=>{if(!m)return;const h=`${c}:${m}`;ts.current!==h&&(ts.current=h,Kn.current.clear())},[]),ao=a.useCallback(async c=>{const m=window.agentApi,h=nt.current;if(!m||!h)throw new Error("当前会话不可用");mn(h,c.revision);const y=`${c.turnId}:${c.itemId}`;let O=Kn.current.get(y);O||(O=m.getSessionToolResult(h,c),Kn.current.set(y,O),O.catch(()=>{Kn.current.get(y)===O&&Kn.current.delete(y)}));const P=await O;return nt.current!==h||ts.current!==`${h}:${c.revision}`,P},[mn]),_a=a.useCallback(async c=>{const m=nt.current;if(!m)throw new Error("当前会话不可用");const h=await ao(c);nt.current===m&&Ie(c.itemId,h.content,h.isError,m)},[ao,Ie]),wu=a.useCallback(async c=>{var P;const m=window.agentApi,h=nt.current;if(!m||!h)throw new Error("当前会话不可用");const y=await Hf(m,h,c,Rr),O=y.detail;if(nt.current!==h)throw new DOMException("Session selection changed","AbortError");if(((P=O==null?void 0:O.history)==null?void 0:P.revision)!==y.revision)throw new Error("会话内容已更新,请重新展开执行过程");return y.recovered&&ne(be(h).map(he=>he.executionTrace?{...he,executionTrace:{...he.executionTrace,revision:y.revision}}:he),h),mn(h,y.revision),Gf(O)},[be,ne,mn]);a.useEffect(()=>{ts.current=null,Kn.current.clear()},[r]);const fr=a.useCallback((c,m)=>{const h=window.agentApi;!m||!h||_.current.prefetch(c,m,()=>h.getSession(c,{before:m,limit:bt(c)==="codex"?si:Rr,...bt(c)==="codex"?{view:"core"}:{}})).catch(y=>{console.warn("[chat] failed to prefetch older history",{sessionId:c,error:y})})},[bt]),os=a.useCallback(c=>{V.current=c,pu(c)},[]);a.useEffect(()=>{const c=jh(kr.current,X,Kt);if(kr.current=c.ownerSessionId,c.type==="inactive"){ns.current=null,Xt.restore(null),gn([]);return}if(c.type==="restore"){const h=c.ownerSessionId.startsWith("runtime:")?Rs(wt.current,c.ownerSessionId):void 0;Qt((h==null?void 0:h.payload.content)??kh(c.ownerSessionId)),gn([]),ns.current=c.ownerSessionId,Xt.restore(c.ownerSessionId).then(y=>{if(!y||kr.current!==y.sessionId)return;ns.current===y.sessionId&&(ns.current=null);const O=(h==null?void 0:h.payload.images)??y.images;gn(O),h&&Xt.save(y.sessionId,O)});return}if(tt.current&&Kt===""){tt.current=!1;return}Hr(c.ownerSessionId,c.value)},[Xt,Kt,X]),a.useEffect(()=>{if(!(!X||kr.current!==X)&&ns.current!==X){if(ft.current===X&&pr.length===0){ft.current=null;return}Xt.saveSelected(X,pr)}},[Xt,pr,X]);const ku=()=>{const c=Pn.current;if(!c)return;const m=c.scrollHeight-c.scrollTop-c.clientHeight;c.scrollTop<=240&&Zr.current(),V.current==="anchored"&&m<=240&&$s.current(),so(mi.current.onScroll(m)),c.classList.add("is-scrolling"),wr.current!==null&&window.clearTimeout(wr.current),wr.current=window.setTimeout(()=>{c.classList.remove("is-scrolling"),wr.current=null},700)};a.useEffect(()=>()=>{wr.current!==null&&window.clearTimeout(wr.current)},[]);const ju=a.useCallback(()=>{const c=Pn.current;if(!c)return;mi.current.requestReturn();const m=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;c.scrollTo({top:c.scrollHeight,behavior:m?"auto":"smooth"})},[]);a.useEffect(()=>{mi.current.reset(),so(!1)},[r]),a.useLayoutEffect(()=>{const c=Zi.current,m=Pn.current;!c||!m||(m.scrollTop=c.scrollTop+(m.scrollHeight-c.scrollHeight),Zi.current=null)},[et]),a.useLayoutEffect(()=>{const c=tn.current,m=Pn.current;if(!c||!m)return;const h=Array.from(m.querySelectorAll("[data-message-id]")).find(y=>y.dataset.messageId===c);h&&(No(m,h),tn.current=null,ys(c))},[et]),a.useLayoutEffect(()=>{const c=Pn.current;!Fn.current||!c||Hs!=="latest"||(Fn.current=!1,c.scrollTop=c.scrollHeight)},[Hs,et]),a.useLayoutEffect(()=>{if(jr.current!=="skip")return;const c=Pn.current;c&&so(c.scrollHeight-c.scrollTop-c.clientHeight>fc)},[et]);const[za,lo]=a.useState(!1),[Gs,Ks]=a.useState(null),wi=a.useRef(null);a.useEffect(()=>{const c=window.agentApi;if(!(c!=null&&c.onTtsStart)||!c.onTtsPcm||!c.onTtsStreamEnd||!c.onTtsFlush)return;const m=new $f(c),h=[c.onTtsStart(y=>m.start(y)),c.onTtsPcm(({generation:y,pcm:O})=>m.enqueue(y,O)),c.onTtsStreamEnd(({generation:y})=>m.finish(y)),c.onTtsFlush(({generation:y})=>m.flush(y)),c.onTtsEnd(()=>Ks(null))];return()=>{for(const y of h)y();m.dispose()}},[]);const Su=()=>{var h;if(za){(h=wi.current)==null||h.stop(),wi.current=null,lo(!1);return}Ci(window.agentApi,ti);const c=Kt?`${Kt.trimEnd()} `:"",m=Wf({onInterim:y=>Qt(c+y),onFinal:y=>{var O;Qt(c+y),(O=Us.current)==null||O.focus()},onError:y=>Ce(y),onEnd:()=>{lo(!1),wi.current=null}});m&&(wi.current=m,lo(!0))},Cu=async(c,m)=>{var h;if(Gs===c){await Ci(window.agentApi,ti),Ks(null);return}if(await Ci(window.agentApi,ti),!((h=window.agentApi)!=null&&h.ttsSpeak)){Ce("TTS 模型服务不可用");return}Ks(c);try{(await window.agentApi.ttsSpeak(m)).ok||(Ks(null),Ce("TTS 模型播报失败"))}catch(y){Ks(null),Ce(y instanceof Error?y.message:"TTS 模型播报失败")}},Ct=a.useRef(null),as=a.useRef(!1),Sr=a.useRef(new Set),Qs=a.useRef(new Map),La=a.useRef(new Set),Qn=a.useRef(new Map),Or=a.useRef(null),nt=a.useRef(r??null),Pa=a.useRef({onRunComplete:u,selectedProjectId:n}),yt=a.useRef(null),Dn=a.useRef(0);a.useEffect(()=>{nt.current=r??null},[r]),a.useEffect(()=>{Pa.current={onRunComplete:u,selectedProjectId:n}},[u,n]),a.useEffect(()=>{yt.current=$e},[$e]),a.useEffect(()=>()=>{for(const c of Qs.current.values())window.clearTimeout(c);Qs.current.clear()},[]);const ki=a.useCallback(async c=>{var h;const m=c||nt.current||yt.current;if(!m||!((h=window.agentApi)!=null&&h.getSessionGoals)){se({active:null,queued:[],history:[]});return}try{const y=await window.agentApi.getSessionGoals(m);an(y,m),y.active&&(Ct.current=m,ke(m))}catch(y){Ce(y instanceof Error?y.message:"目标状态加载失败")}},[an,ke]);a.useEffect(()=>{ki(X)},[X,ki]);const Xs=a.useCallback(async c=>{var h;const m=c||nt.current||yt.current;if(!m||typeof((h=window.agentApi)==null?void 0:h.getThreadGoal)!="function"){Ve(null);return}try{Ve(await window.agentApi.getThreadGoal(m))}catch{Ve(null)}},[]);a.useEffect(()=>{Xs(X)},[X,Xs]);const co=a.useCallback(async c=>{var h;const m=nt.current||yt.current;if(!(!m||typeof((h=window.agentApi)==null?void 0:h.clearThreadGoal)!="function"))try{c==="clear"?(await window.agentApi.clearThreadGoal(m),Ve(null)):typeof window.agentApi.updateThreadGoal=="function"&&Ve(await window.agentApi.updateThreadGoal(m,c))}catch(y){Ce(y instanceof Error?y.message:"目标模式操作失败")}},[Ce]),xn=a.useCallback(c=>{const m=nt.current||yt.current;c==="thinking"&&(fn.current!=="thinking"||Vt.current!==m)?(Vt.current=m,nr(Date.now())):c!=="thinking"&&(Vt.current=null),fn.current=c,Tn(c)},[]);a.useEffect(()=>{mt(!1),Hn("idle"),vr(null),Dr(null)},[r]),a.useEffect(()=>{window.agentApi&&(window.agentApi.listAgentDefs().then(c=>Ta(c)),window.agentApi.listSkills().then(c=>Na(c.filter(m=>m.name))).catch(c=>console.error("[listSkills] mount error:",c)))},[]);const Da=Vs===null?[]:yu.filter(c=>Vs===""||c.name.toLowerCase().includes(Vs.toLowerCase())),uo=ss===null?[]:[...[{name:"goal",description:"目标模式:持续推进当前目标,后续目标自动排队"},{name:"compact",description:"主动压缩当前会话上下文,并在下轮重新注入环境"},{name:"loop",description:"定时任务:/loop 5m 任务 | list | pause/resume/delete <id> | stop"}].filter(c=>ss===""||c.name.toLowerCase().includes(ss.toLowerCase())),...vu.filter(c=>ss===""||c.name.toLowerCase().includes(ss.toLowerCase()))],Iu=c=>{oo(m=>m.find(h=>h.id===c.id)?m:[...m,c]),Qt(m=>m.replace(/@[\w\u4e00-\u9fff]*$/,"")),rs(null),setTimeout(()=>{var m;return(m=Us.current)==null?void 0:m.focus()},0)},Ru=c=>{oo(m=>m.filter(h=>h.id!==c))},Eu=c=>{Qt(m=>m.replace(/\/[\w\u4e00-\u9fff\-_]*$/,`/${c.name} `)),is(null),setTimeout(()=>{var m;return(m=Us.current)==null?void 0:m.focus()},0)},Wa=c=>{var y,O;Qt(c);const m=c.match(/@([\w\u4e00-\u9fff]*)$/);if(m){window.agentApi&&window.agentApi.listAgentDefs().then(P=>Ta(P)),Aa(((y=io.current)==null?void 0:y.getBoundingClientRect())??null),rs(m[1]),is(null);return}const h=c.match(/\/([-\w\u4e00-\u9fff]*)$/);if(h){window.agentApi&&window.agentApi.listSkills().then(P=>Na(P.filter(he=>he.name))).catch(P=>console.error("[listSkills] slash error:",P)),Aa(((O=io.current)==null?void 0:O.getBoundingClientRect())??null),is(h[1]),rs(null);return}rs(null),is(null)},Mu=c=>{Wa(c),rs(null),is(null),requestAnimationFrame(()=>{var m;return(m=Us.current)==null?void 0:m.focus()})},Au=c=>{c.key==="Escape"&&(Vs!==null||ss!==null)?(c.preventDefault(),rs(null),is(null)):c.key==="Escape"&&Ot?(c.preventDefault(),go()):c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Xa())},Tu=async c=>{const m=Array.from(c.target.files??[]);if(c.target.value="",m.length===0)return;const h=m.filter(y=>y.type.toLowerCase().startsWith("image/")).length;h>0&&bs(y=>y+1);try{const y=await gm(m,async P=>Fa(await Vl(P)));y.attachments.length>0&&Fs(P=>[...P,...y.attachments]),y.images.length>0&&(gn(P=>[...P,...y.images]),it||zu());const O=[...y.unsupportedImages,...y.failedImages];O.length>0&&Ce(`无法添加图片:${O.map(P=>P.name).join("、")}。仅支持 JPG、PNG、GIF 和 WebP。`)}finally{h>0&&bs(y=>Math.max(0,y-1))}},Nu=c=>{Fs(m=>m.filter((h,y)=>y!==c))},_u=/claude-3|gpt-4-vision|gpt-4o|gpt-4-turbo|gemini|deepseek-vl/i,po=c=>_u.test(c),zu=()=>{const c=ht.find(h=>h.id===_t);if(c&&po(c.modelId))return;const m=ht.find(h=>po(h.modelId));m&&ln(m.id)},Lu=c=>{gn(m=>[...m,c])},Pu=c=>{gn(m=>m.filter((h,y)=>y!==c))},Fa=c=>new Promise((m,h)=>{const y=new FileReader;y.onload=()=>m(y.result),y.onerror=h,y.readAsDataURL(c)});a.useEffect(()=>{const c=async m=>{if(!m.clipboardData)return;const h=Array.from(m.clipboardData.items).find(O=>O.type.startsWith("image/"));if(!h)return;m.preventDefault();const y=h.getAsFile();if(y){bs(O=>O+1);try{Lu(await Fa(await Vl(y)))}catch{Ce("无法添加图片。仅支持 JPG、PNG、GIF 和 WebP。")}finally{bs(O=>Math.max(0,O-1))}}};return window.addEventListener("paste",c),()=>window.removeEventListener("paste",c)},[ht,_t]),a.useEffect(()=>{var m;const c=jr.current;jr.current=null,mi.current.shouldFollow(c)&&((m=Os.current)==null||m.scrollIntoView({behavior:"auto"}))},[et]),a.useEffect(()=>window.agentApi?window.agentApi.onEvent(m=>Du(m)):void 0,[$e]),a.useEffect(()=>{const c=++Dn.current,m=r,h=()=>Dn.current===c&&nt.current===m;return(async()=>{var he,Z,Ae;const O=window.agentApi;if(!O||Yg(Ct.current,yt.current,m))return;if(!m){if(!h())return;(he=_.current)==null||he.invalidate(),Tt(),Ce(null),Ds(null),un(null),jn(null),g.current=null,K.current=null,Le.current+=1,me.current=null,no(null),os("latest"),ys(null),vs(null),_e.current=!1,bi(!1),ws(!1),xi(null),yi(!1),vi(!1),U.current=null,yt.current=null,Pe(""),Lr("full-access");return}Ce(null),Ds(null),un(null),jn(null),xi(null),(Z=_.current)==null||Z.invalidate(),Fe.current+=1,g.current=null,K.current=null,os("latest"),ws(!1),ys(null),vs(null),_e.current=!1,bi(!1),((Ae=me.current)==null?void 0:Ae.sessionId)!==m&&(Le.current+=1,me.current=null,no(null)),yi(!0),vi(!0),U.current=m,yt.current=m,Pe(m);const P=be(m);ne(P,m);try{await ph(async()=>{if(!h())throw new DOMException("Session selection changed","AbortError");return await Ss(O,m,bt(m),{limit:bt(m)==="codex"?Mo:Rr},(oe,J)=>{var Mt,vt,xe;if(!h())return;const je=oe,ue=Nl((oe==null?void 0:oe.events)??[]),Be=Al((oe==null?void 0:oe.events)??[]),de=_l((oe==null?void 0:oe.events)??[]),ve=cs(oe);mn(m,(Mt=oe==null?void 0:oe.history)==null?void 0:Mt.revision),p!=null&&p.compatibility&&un(m),Lr(bc((je==null?void 0:je.permissionMode)??((vt=je==null?void 0:je.metadata)==null?void 0:vt.permissionMode))),K.current=null;const Me=be(m),Se=Bl(Me,ve,J,oe==null?void 0:oe.history,Ye(m)),It=oe!=null&&oe.goalState?ko(Se.messages,oe.goalState):Se.messages;g.current=Se.window.olderCursor,jr.current="instant",ne(It,m,Se.window),fr(m,Se.window.olderCursor),ye(Be,m),dt(de,m),Nd(oe)||Bh(oe)?(Ct.current=m,ke(m)):Ct.current===m&&(Ct.current=null,ke(null)),ue&&le(ue,m);const Oe=It[It.length-1];(Oe==null?void 0:Oe.role)==="assistant"&&((xe=Oe.toolCalls)!=null&&xe.length)?xn(So(Oe.toolCalls)?"thinking":"tools"):xn((oe==null?void 0:oe.agentType)!=="customer-agent"&&(oe==null?void 0:oe.status)==="running"?"thinking":"idle"),yi(!1),vi(!1)},h),!0})}catch(oe){if(!h())return;console.error("[chat] failed to restore session",{sessionId:m,error:oe});const J=uh(oe);Ds(J),p!=null&&p.compatibility&&jn(J)}finally{h()&&(yi(!1),vi(!1))}})(),()=>{Dn.current===c&&(Dn.current+=1)}},[Tt,be,Ye,bt,fr,r,Ws,le,os,ne,Pe,mn,xn]);const $r=a.useCallback(async c=>{const m=window.agentApi;if(!(m!=null&&m.getSessionQueryIndex))return null;const h=++Le.current;try{const y=await m.getSessionQueryIndex(c);return Le.current!==h||nt.current!==c||y.sessionId!==c?null:(me.current=y,no(y),y)}catch(y){return Le.current===h&&console.warn("[chat] failed to load query index",{sessionId:c,error:y}),null}},[]),Ba=a.useCallback(c=>{if(Wr.current!==c&&(Rn.current!==null&&window.clearTimeout(Rn.current),Wr.current=c,Rn.current=null,ir.current=0),Rn.current!==null)return;const m=Math.max(0,Sm-(Date.now()-ir.current));Rn.current=window.setTimeout(()=>{Rn.current=null,ir.current=Date.now(),nt.current===c&&nn(h=>h+1)},m)},[]);a.useEffect(()=>{var P;const c=r;if(!c||ks||!((P=window.agentApi)!=null&&P.getSessionQueryIndex))return;let m=!1;const h=()=>{!m&&nt.current===c&&$r(c)},y=window,O=y.requestIdleCallback?y.requestIdleCallback(h,{timeout:1e3}):window.setTimeout(h,0);return()=>{m=!0,y.cancelIdleCallback&&y.requestIdleCallback?y.cancelIdleCallback(O):window.clearTimeout(O)}},[ks,$r,r,Ws]);const Ys=a.useCallback(async c=>{if(!window.agentApi||document.visibilityState==="hidden")return;if(V.current==="anchored"){ws(!0);return}if(Et.current!==c&&(Et.current=c,In.current=!1,St.current=!1),In.current){St.current=!0;return}const m=Dn.current,h=Fe.current;In.current=!0;try{do St.current=!1,await Ss(window.agentApi,c,bt(c),{limit:bt(c)==="codex"?Mo:Rr},(y,O)=>{var Be,de,ve,Me,Se;const P=cs(y),he=be(c),Z=Bl(he,P,O,y==null?void 0:y.history,Ye(c)),Ae=y!=null&&y.goalState?ko(Z.messages,y.goalState):Z.messages,oe=Pn.current,J=!oe||oe.scrollHeight-oe.scrollTop-oe.clientHeight<80;jr.current=J?null:"skip",ne(Ae,c,Z.window),mn(c,(Be=y==null?void 0:y.history)==null?void 0:Be.revision),y!=null&&y.goalState&&se(Jl(y.goalState)),g.current!==Z.window.olderCursor&&((de=_.current)==null||de.invalidate(),g.current=Z.window.olderCursor,fr(c,Z.window.olderCursor)),(ve=y==null?void 0:y.history)!=null&&ve.revision&&y.history.revision!==((Me=me.current)==null?void 0:Me.revision)&&$r(c);const je=Nl((y==null?void 0:y.events)??[]);ye(Al((y==null?void 0:y.events)??[]),c),dt(_l((y==null?void 0:y.events)??[]),c),je&&le(je,c);const ue=Ae[Ae.length-1];(ue==null?void 0:ue.role)==="assistant"&&((Se=ue.toolCalls)!=null&&Se.length)?xn(So(ue.toolCalls)?"thinking":"tools"):xn(ma(y)?"thinking":"idle")},()=>nt.current===c&&U.current===c&&Dn.current===m&&Fe.current===h&&V.current==="latest"),bt(c)==="codex"&&Ba(c);while(St.current)}catch(y){console.error("[chat] failed to refresh native session history",{sessionId:c,error:y})}finally{Et.current===c&&(In.current=!1)}},[be,Ye,bt,$r,fr,Ba,le,ne,mn,xn]);a.useEffect(()=>{const c=r,m=$h(p,c)||(p==null?void 0:p.agentType)==="customer-agent"&&c!==Ee,h=(p==null?void 0:p.agentType)==="customer-agent"||(p==null?void 0:p.occupancy)==="owned-externally"||(p==null?void 0:p.status)==="running";if(!c||!m||!window.agentApi)return;let y=null,O=null,P=!1;const he=()=>{!P&&document.visibilityState!=="hidden"&&Ys(c)},Z=()=>{y==null||y(),y=null,O!==null&&window.clearInterval(O),O=null},Ae=()=>{P||O!==null||document.visibilityState==="hidden"||(he(),O=window.setInterval(he,2e3))},oe=()=>{if(!(P||document.visibilityState==="hidden")){if(typeof window.agentApi.observeSession!="function"){h&&Ae();return}try{y=window.agentApi.observeSession(c,he,()=>{y=null,h&&Ae()})}catch{h&&Ae()}}},J=()=>{Z(),document.visibilityState!=="hidden"&&(he(),oe())};return oe(),document.addEventListener("visibilitychange",J),()=>{P=!0,document.removeEventListener("visibilitychange",J),Z(),Et.current===c&&(Et.current=null,St.current=!1),Wr.current===c&&(Rn.current!==null&&window.clearTimeout(Rn.current),Wr.current=null,Rn.current=null,ir.current=0)}},[Ys,r,Ee,p==null?void 0:p.agentType,p==null?void 0:p.occupancy,p==null?void 0:p.status]);const fo=a.useCallback(async()=>{const c=U.current,m=g.current,h=window.agentApi;if(!h||!c||!m||ks||gi.current)return;const y=Dn.current,O=Fe.current,P=()=>U.current===c&&nt.current===c&&Dn.current===y&&Fe.current===O&&g.current===m;gi.current=!0,xi(null);const he=window.setTimeout(()=>{P()&&gi.current&&Ra(!0)},500);try{await Ss(h,c,bt(c),{before:m,limit:bt(c)==="codex"?si:Rr},(Z,Ae)=>{var Me;const oe=cs(Z),J=be(c),je=new Set(J.map(Se=>Se.id)),ue=oe.filter(Se=>!je.has(Se.id)).length,Be=Ol(J,oe,"older"),de=Pn.current;Ae!=="trace"&&de&&ue>0&&(Zi.current={scrollHeight:de.scrollHeight,scrollTop:de.scrollTop},jr.current="skip");const ve=Uf(m,Z,ue);g.current=ve,mn(c,(Me=Z==null?void 0:Z.history)==null?void 0:Me.revision),ne(Be,c,{kind:V.current,olderCursor:ve}),Ae!=="trace"&&fr(c,ve)},P,()=>_.current.consume(c,m,()=>h.getSession(c,{before:m,limit:bt(c)==="codex"?si:Rr,...bt(c)==="codex"?{view:"core"}:{}})))}catch(Z){if(!P())return;console.error("[chat] failed to load older history",{sessionId:c,error:Z}),xi(Z instanceof Error?Z.message:"历史消息加载失败")}finally{window.clearTimeout(he),gi.current=!1,U.current===c&&Ra(!1)}},[be,bt,ks,fr,ne,mn]);a.useEffect(()=>{Zr.current=()=>{fo()}},[fo]);const Oa=a.useCallback(async()=>{const c=U.current,m=K.current;if(!window.agentApi||!c||!m||V.current!=="anchored"||Re.current)return;const h=Dn.current,y=Fe.current,O=()=>nt.current===c&&U.current===c&&V.current==="anchored"&&Dn.current===h&&Fe.current===y&&K.current===m;Re.current=!0,Ea(!0);try{await Ss(window.agentApi,c,bt(c),{after:m,limit:bt(c)==="codex"?si:Rr},P=>{var Ae,oe;const he=be(c),Z=Ol(he,cs(P),"newer");K.current=((Ae=P==null?void 0:P.history)==null?void 0:Ae.newerCursor)??null,mn(c,(oe=P==null?void 0:P.history)==null?void 0:oe.revision),Z!==he&&(jr.current="skip",ne(Z,c,{kind:"anchored",olderCursor:g.current}))},O)}catch(P){if(!O())return;console.error("[chat] failed to load newer anchored history",{sessionId:c,error:P})}finally{Re.current=!1,Ea(!1)}},[be,bt,ne,mn]);a.useEffect(()=>{$s.current=()=>{Oa()}},[Oa]);const $a=a.useCallback(async()=>{const c=nt.current;if(!window.agentApi||!c||_e.current)return!1;const m=++Fe.current;_e.current=!0,bi(!0),vs(null);try{let h=!1;return await Ss(window.agentApi,c,bt(c),{limit:bt(c)==="codex"?Mo:Rr},(y,O)=>{var Z,Ae,oe,J,je,ue,Be;h=!0;const P=cs(y),he=((Z=y==null?void 0:y.history)==null?void 0:Z.nextCursor)??null;O!=="trace"&&((Ae=_.current)==null||Ae.invalidate()),g.current=he,K.current=null,mn(c,(oe=y==null?void 0:y.history)==null?void 0:oe.revision),os("latest"),ws(!1),ys(((je=(J=me.current)==null?void 0:J.entries.at(-1))==null?void 0:je.messageId)??null),Fn.current=!0,jr.current="skip",ne(P,c,{kind:"latest",olderCursor:he}),O!=="trace"&&fr(c,he),((ue=y==null?void 0:y.history)==null?void 0:ue.revision)!==((Be=me.current)==null?void 0:Be.revision)&&$r(c)},()=>Fe.current===m&&nt.current===c),h}catch(h){return Ce(h instanceof Error?h.message:"返回最新消息失败"),!1}finally{_e.current=!1,bi(!1)}},[bt,$r,fr,os,ne,mn]),Ha=a.useCallback(async(c,m=!0)=>{var he;const h=nt.current,y=Pn.current;if(!window.agentApi||!h||!y)return;const O=++Fe.current;ys(c.messageId);const P=Array.from(y.querySelectorAll("[data-message-id]")).find(Z=>Z.dataset.messageId===c.messageId);if(P){vs(null),No(y,P,"smooth");return}vs(c.messageId),(he=_.current)==null||he.invalidate();try{await Ss(window.agentApi,h,bt(h),{anchor:c.pageToken,limit:bt(h)==="codex"?si:Rr},(Z,Ae)=>{var je,ue,Be,de,ve,Me;if(((je=me.current)==null?void 0:je.revision)!==((ue=Z==null?void 0:Z.history)==null?void 0:ue.revision))return;const oe=cs(Z),J=((Be=Z==null?void 0:Z.history)==null?void 0:Be.olderCursor)??((de=Z==null?void 0:Z.history)==null?void 0:de.nextCursor)??null;g.current=J,K.current=((ve=Z==null?void 0:Z.history)==null?void 0:ve.newerCursor)??null,mn(h,(Me=Z==null?void 0:Z.history)==null?void 0:Me.revision),os("anchored"),ws(!1),tn.current=c.messageId,jr.current="skip",ne(oe,h,{kind:"anchored",olderCursor:J}),Ae!=="trace"&&(window.requestAnimationFrame(()=>{if(Fe.current!==O||nt.current!==h)return;const Se=Pn.current,It=Array.from((Se==null?void 0:Se.querySelectorAll("[data-message-id]"))??[]).find(Oe=>Oe.dataset.messageId===c.messageId);!Se||!It||(No(Se,It),tn.current=null,ys(c.messageId))}),fr(h,J))},()=>Fe.current===O&&nt.current===h)}catch(Z){if(Z.code==="STALE_SESSION_ANCHOR"&&m){const oe=await $r(h),J=oe==null?void 0:oe.entries.find(je=>je.ordinal===c.ordinal);J&&await Ha(J,!1);return}console.error("[chat] failed to open indexed query",{sessionId:h,error:Z}),Ce(Z instanceof Error?Z.message:"无法打开这条消息")}finally{Fe.current===O&&vs(null)}},[bt,$r,fr,os,ne,mn]),Ua=c=>{if(Sr.current.has(c)||Qs.current.has(c))return;const m=window.setTimeout(()=>{Qs.current.delete(c),(async()=>{var h;if(!Sr.current.has(c))try{const y=await((h=window.agentApi)==null?void 0:h.getSessionGoals(c));if(Sr.current.has(c))return;const O=nt.current||yt.current;if(y&&c===O&&an(y,c),y!=null&&y.active){Ct.current=c,c===O&&(as.current=!1,Ce(null),ke(c));return}if(as.current)return;const P=Ze.getState().getMessagesForSession(c).find(he=>he.isQueued&&!he.queueItemId);if(!P){Ct.current===c&&(Ct.current=null),Ze.getState().runningSessionId===c&&ke(null);return}qe(P.id,he=>({...he,isQueued:!1}),c),js(P,c)}catch(y){Ce(y instanceof Error?y.message:"排队消息自动发送失败")}})()},150);Qs.current.set(c,m)},ji=(c,m)=>{const h=Ze.getState().getMessagesForSession(c),y=Th(h);y&&qe(y,O=>({...O,sendState:m}),c)},ho=(c,m)=>{const h=uc(m),y=Ze.getState().getMessagesForSession(c);ne(y.filter(O=>O.id!==h),c),Hr(c,m.payload.content),Xt.save(c,m.payload.images??[]),(nt.current||yt.current)===c&&(Qt(m.payload.content),gn(m.payload.images??[])),Qn.current.delete(c),ft.current===c&&(ft.current=null),Rt(void 0,c)},Du=c=>{var he,Z,Ae,oe;const m=nt.current||yt.current,h=Ph(c._sid)??void 0;if(!h&&c.type!=="cron_update")return;if(c._nativeRunId&&Number.isSafeInteger(c._nativeSequence)){const J=`${c._nativeRunId}:${c._nativeSequence}`;if(Fr.current.has(J))return;Fr.current.add(J),Fr.current.size>2e3&&(Fr.current=new Set([...Fr.current].slice(-1e3)))}const y=!h||h===m,O=y&&V.current==="anchored",P=(h==null?void 0:h.startsWith("runtime:"))&&(c.type==="run_admitted"||c.type==="done")&&be(h).some(J=>J.role==="user"&&!J.isQueued&&J.sendState==="failed");if(h&&y&&(c._nativeRecoveredFromSnapshot||P)&&Ys(h),!(O&&(ws(!0),Dh(c.type)))){if(h&&["run_admitted","thinking","text_chunk","reasoning_summary_delta","runtime_progress","tool_call","todo_update","done"].includes(c.type)&&ji(h),h&&y&&!c._preserveActiveRun&&["done","error","turn_aborted"].includes(c.type)&&!Sr.current.has(h)){const J=Pa.current;(he=J.onRunComplete)==null||he.call(J,J.selectedProjectId??null,h)}switch(c.type){case"run_admitted":if(h&&Jr===h&&(vr(null),y&&Ce(null)),h){Qn.current.delete(h);const J=Rs(wt.current,h);J&&(Or.current===J.token&&(Or.current=null),Rt(void 0,h)),Cs(h),Xt.clear(h),ft.current===h&&(ft.current=null)}break;case"context_usage":if(c.usage&&(le(c.usage,h),h&&!h.startsWith("runtime:"))){const J=(Ze.getState().runtimeProgressBySession[h]??[]).filter(je=>je.progressId!==yd);ye(J,h)}break;case"text_chunk":c.text&&(h&&c.turnId&&c.messagePhase==="commentary"&&bt(h)==="codex"?st(c.turnId,{type:"text_chunk",text:c.text,turnId:c.turnId,itemId:c.itemId,messagePhase:"commentary"},h):Ke(c.text,h),y&&xn("thinking"));break;case"reasoning_summary_delta":if(typeof c.itemId=="string"&&Number.isSafeInteger(c.sectionIndex)&&typeof c.delta=="string"){const J={type:"reasoning_summary_delta",itemId:c.itemId,sectionIndex:c.sectionIndex,delta:c.delta,...c.turnId?{turnId:c.turnId}:{}};h&&c.turnId&&bt(h)==="codex"?st(c.turnId,J,h):lt(J,h),y&&xn("thinking")}break;case"runtime_progress":if(typeof c.progressId=="string"&&typeof c.label=="string"&&["thinking","tool","retry","status"].includes(c.phase??"")){const J={progressId:c.progressId,phase:c.phase,label:c.label,...c.detail===void 0?{}:{detail:c.detail},...c.toolCallId===void 0?{}:{toolCallId:c.toolCallId},...c.elapsedSeconds===void 0?{}:{elapsedSeconds:c.elapsedSeconds},...c.current===void 0?{}:{current:c.current},...c.total===void 0?{}:{total:c.total}};pe(J,h),y&&xn(J.phase==="tool"?"tools":"thinking")}break;case"native_subagent_update":(Z=c.activity)!=null&&Z.parentToolCallId&&(Te(c.activity,h),y&&c.activity.status==="running"&&xn("tools"));break;case"tool_call":y&&xn("tools"),c.toolCall&&c.toolCall.name!=="dispatch_agent"&&c.toolCall.name!=="ask_user"&&c.toolCall.name!=="show_widget"&&(h&&c.turnId&&bt(h)==="codex"?st(c.turnId,{type:"tool_call",toolCall:c.toolCall,turnId:c.turnId},h):ae({id:crypto.randomUUID(),role:"assistant",content:"",toolCalls:[{id:c.toolCall.id,name:c.toolCall.name,arguments:c.toolCall.arguments}],timestamp:Date.now()},h));break;case"tool_result":c.result&&(h&&c.turnId&&bt(h)==="codex"?st(c.turnId,{type:"tool_result",result:c.result,turnId:c.turnId},h):Ie(c.result.toolCallId,c.result.content,c.result.isError,h));break;case"todo_update":c.todos&&ct(c.todos);break;case"cron_update":c.tasks&&Y(c.tasks);break;case"agent_dispatch":if(ae({id:crypto.randomUUID(),role:"assistant",content:"",toolCalls:[{id:crypto.randomUUID(),name:"dispatch_agent",arguments:{agentName:c.agentName,task:c.task??"",subSessionId:c.subSessionId}}],timestamp:Date.now()},h),c.subSessionId){xt.current.add(c.subSessionId);const J=Ct.current||$e;J&&o&&o(J)}d==null||d({type:"started",agentName:c.agentName??"",task:c.task??"",subSessionId:c.subSessionId});break;case"agent_done":c.subSessionId&&(xt.current.delete(c.subSessionId),We(c.subSessionId,c.status??"completed",c.status==="failed"?c.error:c.summary,h)),d==null||d({type:c.status==="failed"?"failed":"completed",agentName:c.agentName??"",task:c.task??"",subSessionId:c.subSessionId});break;case"agent_progress":c.subSessionId&&c.text&&at(c.subSessionId,c.text,h);break;case"compacted":ae({id:crypto.randomUUID(),role:"assistant",content:c.summary??"",isCompactionSummary:!0,timestamp:Date.now()},h);break;case"show_widget":{const J=c.data??c.widgetData,je={widgetId:c.widgetId,widgetType:c.widgetType,data:J??{}},Be=(h?Ze.getState().getMessagesForSession(h):Ze.getState().messages).find(de=>{var ve;return((ve=de.widget)==null?void 0:ve.widgetId)===je.widgetId});Be?qe(Be.id,de=>({...de,widget:je}),h):ae({id:crypto.randomUUID(),role:"assistant",content:"",widget:je,timestamp:Date.now()},h);break}case"ask_user":if(c.questionId&&(h?Ze.getState().getMessagesForSession(h):Ze.getState().messages).some(je=>{var ue;return((ue=je.askUser)==null?void 0:ue.questionId)===c.questionId}))break;ae({id:crypto.randomUUID(),role:"assistant",content:"",askUser:{questionId:c.questionId??"",question:c.question??"",options:c.options,fields:c.fields,multiSelect:c.multiSelect},timestamp:Date.now()},h);break;case"approval_resolved":{if(!c.questionId)break;const je=(h?Ze.getState().getMessagesForSession(h):Ze.getState().messages).find(ue=>{var Be;return((Be=ue.askUser)==null?void 0:Be.questionId)===c.questionId});je&&qe(je.id,ue=>({...ue,askUser:ue.askUser?{...ue.askUser,answered:!0,answer:ue.askUser.answer??"已处理"}:ue.askUser}),h);break}case"text_done":break;case"thinking":y&&xn("thinking");break;case"done":if(h&&Jr===h&&(vr(null),y&&Ce(null)),h&&!O){const J=Yd(c.durationMs);if(J!==void 0||c.forkPoint){const je=[...be(h)].reverse().find(ue=>{var Be;return ue.role==="assistant"&&!!ue.content.trim()&&!((Be=ue.toolCalls)!=null&&Be.length)&&!ue.isCompactionSummary});je&&qe(je.id,ue=>({...ue,presentation:{...ue.presentation,...J!==void 0?{completionDurationMs:J}:{},...c.forkPoint?{forkPoint:c.forkPoint}:{}}}),h)}}if(we(h),h&&!be(h).some(J=>J.isQueued)&&(Ct.current===h&&(Ct.current=null),Ze.getState().runningSessionId===h&&ke(null)),y&&(xn("idle"),!O&&bn.getState().autoSpeak)){const je=[...Ze.getState().messages].reverse().find(ue=>ue.role==="assistant"&&ue.content&&!ue.isCompactionSummary);je!=null&&je.content&&(Ae=window.agentApi)!=null&&Ae.ttsSpeak&&(ti(),window.agentApi.ttsSpeak(je.content.slice(0,600)).then(ue=>{ue.ok||Ce("TTS 模型播报失败")}).catch(ue=>{Ce(ue instanceof Error?ue.message:"TTS 模型播报失败")}))}h&&(Sr.current.has(h)?window.setTimeout(()=>{ki(h)},150):Ua(h),Xs(h));break;case"error":if(c._preserveActiveRun||we(h),h&&c.code==="SESSION_OCCUPIED"&&!O){const J=Ze.getState().getMessagesForSession(h),je=Qn.current.get(h),ue=Rs(wt.current,h),Be=(ue==null?void 0:ue.forkSessionId)===h?ue:void 0,de=je??(ue==null?void 0:ue.payload),ve=de?[...J].reverse().find(Se=>Se.role==="user"&&!Se.isQueued&&Se.content===de.content):y?[...J].reverse().find(Se=>Se.role==="user"&&!Se.isQueued):void 0,Me=de??(ve?{content:ve.content,images:ve.images,agentName:ve.agentName}:void 0);Be?ho(h,Be):(ve&&ne(J.filter(Se=>Se.id!==ve.id),h),Qn.current.delete(h),Me!=null&&Me.content&&(Rt(ue??bm(h,Me)),Hr(h,Me.content),Xt.save(h,Me.images??[]),y&&(Qt(Me.content),gn(Me.images??[]))),ft.current===h&&(ft.current=null)),y&&Ce(null)}if(h&&h.startsWith("runtime:")&&c.code!=="SESSION_OCCUPIED"&&c.code!=="SESSION_ALREADY_RUNNING"&&c.code!=="CANCEL_CONFIRMATION_TIMEOUT"&&!O){const J=Ze.getState().getMessagesForSession(h),je=Qn.current.get(h),ue=Rs(wt.current,h),Be=(ue==null?void 0:ue.forkSessionId)===h?ue:void 0,de=je?[...J].reverse().find(Me=>Me.role==="user"&&!Me.isQueued&&Me.content===je.content):[...J].reverse().find(Me=>Me.role==="user"&&!Me.isQueued),ve=je??(de?{content:de.content,images:de.images,agentName:de.agentName}:void 0);Be?ho(h,Be):ve!=null&&ve.content&&(Hr(h,ve.content),Xt.save(h,ve.images??[]),y&&(Qt(ve.content),gn(ve.images??[]))),Qn.current.delete(h),ft.current===h&&(ft.current=null)}if(y)if(c._preserveActiveRun&&h&&(La.current.add(h),Ct.current=h,ke(h),xn("thinking")),c.code==="SESSION_ALREADY_RUNNING"&&!O){const J=h?Qn.current.get(h):void 0,je=h?Ze.getState().getMessagesForSession(h):Ze.getState().messages,ue=Ah(je);if(ue){const Be=je.find(de=>de.id===ue);qe(ue,de=>({...de,isQueued:!0,sendState:void 0}),h),Yr&&h&&Be&&((oe=window.agentApi)!=null&&oe.enqueueSessionMessage)?window.agentApi.enqueueSessionMessage(h,{sourceMessageId:Be.id,content:Be.content,images:Be.images,agentName:Be.agentName}).then(de=>{an(de,h),Cs(h),Xt.clear(h)}).catch(de=>{const ve=(J==null?void 0:J.content)??Be.content,Me=(J==null?void 0:J.images)??Be.images??[];Hr(h,ve),Xt.save(h,Me),(nt.current||yt.current)===h&&(Qt(ve),gn(Me)),Ce(de instanceof Error?de.message:"排队消息保存失败")}):h&&(Cs(h),Xt.clear(h))}h&&Qn.current.delete(h),h&&ft.current===h&&(ft.current=null),h&&Rt(void 0,h),Ce(null)}else c.code!=="SESSION_OCCUPIED"&&(Ce(c.message??"Unknown error"),vr(c.code==="CANCEL_CONFIRMATION_TIMEOUT"?h??null:null),h&&c.code==="CANCEL_CONFIRMATION_TIMEOUT"&&(Qn.current.delete(h),ft.current===h&&(ft.current=null)),h&&c.code!=="CANCEL_CONFIRMATION_TIMEOUT"&&ji(h,"failed"));if(!c._preserveActiveRun){const J=h??m;(!J||Ct.current===J)&&(Ct.current=null),(!J||Ze.getState().runningSessionId===J)&&ke(null),y&&xn("idle")}h&&!c._preserveActiveRun&&(Sr.current.has(h)?window.setTimeout(()=>{ki(h)},150):Ua(h),Xs(h));break;case"turn_aborted":h&&Jr===h&&(vr(null),y&&Ce(null)),we(h),Ct.current===h&&(Ct.current=null),Ze.getState().runningSessionId===h&&ke(null),y&&xn("idle"),Xs(h);break;case"goal_updated":h===(nt.current||yt.current)&&Ve(c.goal??null);break;case"goal_cleared":h===(nt.current||yt.current)&&Ve(null);break}}},Wu=async c=>{var h;if(!X||!((h=window.agentApi)!=null&&h.setSessionPermissionMode)||fi)return;const m=Ln;Lr(c),Lt(!1),Ps(!0);try{await window.agentApi.setSessionPermissionMode(X,c)}catch(y){Lr(m),Ce(y instanceof Error?y.message:"权限模式更新失败")}finally{Ps(!1)}},qa=async()=>{var c;if(!(!X||(p==null?void 0:p.agentType)!=="codex"||!((c=window.agentApi)!=null&&c.releaseCodexSession)||Zt!=="idle")&&!(Cn&&!window.confirm("停止当前执行并退出此会话?Codex Desktop 最长约 30 分钟后可用。"))){Hn("releasing");try{await window.agentApi.releaseCodexSession(X),as.current=!0,Dn.current+=1,Ct.current=null,ke(null),xt.current.clear(),se(m=>({...m,active:null,queued:[]})),Tn("idle"),Ce(null),vr(null),Hn("released")}catch(m){Hn("idle"),Ce(m instanceof Error?m.message:"释放 Codex 会话失败")}}},Fu=a.useCallback(async c=>{var P;const m=yt.current;if(!m||!((P=window.agentApi)!=null&&P.forkSession)||Jn.current||Wt)return;let h=wo(c,m);Jn.current=!0,Yn(c.id),Ce(null);let y=!1;const O=Dn.current;try{if(!h){const Z=await window.agentApi.getSession(m,{limit:100,view:"core"}),Ae=cs(Z).filter(oe=>{var J;return oe.role==="assistant"&&!((J=oe.toolCalls)!=null&&J.length)&&oe.content===c.content});if(Ae.length===1&&(h=wo(Ae[0],m)),!h)throw Ys(m),new Error("轮次正在同步,请刷新会话后重试 Fork")}const he=h;await pc({sourceSessionId:m,forkSession:Z=>window.agentApi.forkSession(Z,he),activateSession:Z=>{yt.current!==m||Dn.current!==O||(y=!0,yt.current=Z,Pe(Z))},refreshAndSelect:async Z=>{!y||yt.current!==Z.id||(s?await s(Z.id,Z):l==null||l(Z.id))}})}catch(he){(yt.current===m||y)&&Ce(he instanceof Error?he.message:"Fork 失败,请重试")}finally{Jn.current=!1,Yn(null)}},[Wt,s,l,Ys,Pe]),Bu=async()=>{var h;const c=gt;if(!c||!X||Wt||Jn.current||Or.current===c.token)return;Or.current=c.token;const m=(y,O)=>{const P=uc(y);if(be(O).some(Z=>Z.id===P)){qe(P,Z=>({...Z,sendState:"pending"}),O);return}ae({id:P,role:"user",content:y.payload.content,timestamp:Date.now(),agentName:y.payload.agentName,images:y.payload.images,sendState:"pending"},O)};if(c.forkSessionId){mt(!0);const y=dc(c,c.forkSessionId);Rt(y),m(y,y.forkSessionId),js(y.payload,y.forkSessionId,y.payload.agentIds).finally(()=>{Or.current=null,mt(!1)});return}if(!((h=window.agentApi)!=null&&h.forkSession)){Or.current=null;return}mt(!0);try{const y=await pc({sourceSessionId:c.sourceSessionId,forkSession:P=>window.agentApi.forkSession(P),activateSession:P=>{yt.current=P,Pe(P)},refreshAndSelect:async P=>{s?await s(P.id,P):l==null||l(P.id)}}),O=dc(c,y.id);Rt(O),m(O,y.id),js(O.payload,y.id,O.payload.agentIds).finally(()=>{Or.current=null,mt(!1)}),Ce(null)}catch(y){Or.current=null,Ce(y instanceof Error?y.message:"创建会话副本失败"),mt(!1)}},go=()=>{as.current=!0,Dn.current+=1,window.agentApi&&window.agentApi.abort(X||void 0).catch(c=>{Ce(c instanceof Error?c.message:"停止执行失败")}),Ne!=="codex"&&(Ct.current=null,ke(null),xt.current.clear())},Va=async c=>{const m=r||$e;if(!m||!window.agentApi||Xe.current.has(c))return;const h=be(m).find(y=>y.id===c);if(!(!h||!h.isQueued)){Xe.current.add(c),Ue(new Set(Xe.current));try{if(h.queueItemId){const y=await window.agentApi.steerSessionMessage(m,h.queueItemId);ne(Yl(be(m),c,Date.now()),m),an(y,m)}else await window.agentApi.steer(h.content,m,h.agentName),ne(Yl(be(m),c,Date.now()),m);b===c&&(N(null),re(""))}catch(y){Ce(y instanceof Error?y.message:"引导失败")}finally{Xe.current.delete(c),Ue(new Set(Xe.current))}}},Ou=c=>{const m=Ze.getState().messages.find(h=>h.id===c&&h.isQueued);m&&(N(c),re(m.content))},mo=()=>{N(null),re("")},Ga=async c=>{const m=D.trim(),h=Ze.getState().messages.find(y=>y.id===c&&y.isQueued);if(!(!h||!m))try{h.queueItemId&&X?an(await window.agentApi.updateSessionMessage(X,h.queueItemId,m),X):qe(c,y=>y.isQueued?{...y,content:m}:y,X||void 0),mo()}catch(y){Ce(y instanceof Error?y.message:"排队消息保存失败")}},$u=async c=>{const m=Ze.getState().messages.find(h=>h.id===c&&h.isQueued);if(m){if(!await zi(m.content)){Ce("复制排队消息失败");return}Qe(c),window.setTimeout(()=>Qe(h=>h===c?null:h),1200)}},Hu=async c=>{const m=Ze.getState().messages,h=m.find(y=>y.id===c&&y.isQueued);if(h)try{h.queueItemId&&X?an(await window.agentApi.cancelSessionMessage(X,h.queueItemId),X):ne(m.filter(y=>y.id!==c),X||void 0),b===c&&mo()}catch(y){Ce(y instanceof Error?y.message:"排队消息删除失败")}},xo=async(c,m)=>{const h=Ze.getState().messages,y=_h(h,c,m);if(y!==h){ne(y,X||void 0);const O=y.filter(P=>P.isQueued&&P.queueItemId);if(X&&O.length>0)try{an(await window.agentApi.reorderSessionMessages(X,O.map(P=>P.queueItemId)),X)}catch(P){ne(h,X),Ce(P instanceof Error?P.message:"排队消息排序保存失败")}}},Uu=(c,m)=>{const h=Ze.getState().messages.filter(P=>P.isQueued),y=h.findIndex(P=>P.id===c),O=h[y+m];O&&xo(c,O.id)},qu=async c=>{const m=pi;if(hn(null),!X||!m||m===c)return;const h=q.queued.map(Z=>Z.id),y=h.indexOf(m),O=h.indexOf(c);if(y<0||O<0)return;const P=[...h];P.splice(O,0,P.splice(y,1)[0]);const he=q;se({...q,queued:P.map((Z,Ae)=>({...q.queued.find(oe=>oe.id===Z),position:Ae}))});try{an(await window.agentApi.reorderSessionGoals(X,P),X)}catch(Z){se(he),Ce(Z instanceof Error?Z.message:"目标排序保存失败")}},Ka=async c=>{if(!X)return;const m=q.queued.find(h=>h.id===c);try{const h=await window.agentApi.cancelSessionGoal(X,c);if(an(h,X),m!=null&&m.sourceMessageId){const y=Ze.getState().getMessagesForSession(X);ne(y.filter(O=>O.id!==m.sourceMessageId),X)}h.active||ke(null)}catch(h){Ce(h instanceof Error?h.message:"目标删除失败")}};a.useEffect(()=>{b&&($.some(c=>c.id===b&&c.isQueued)||(N(null),re("")))},[b,$]);async function js(c,m,h){var P,he,Z,Ae;const y=crypto.randomUUID();let O=!1;m.startsWith("runtime:")&&Qn.current.set(m,{content:c.content,images:c.images?[...c.images]:void 0,agentIds:h?[...h]:void 0,agentName:c.agentName,restoreDraftOnFailure:c.restoreDraftOnFailure}),as.current=!1,Sr.current.add(m),Nr(m),Ct.current=m,ke(m);try{if(window.agentApi){const oe=it&&Wi(Ne)?{...(P=Bt.model)!=null&&P.id?{model:Bt.model}:{},...qt?{reasoningEffort:qt}:{}}:_t?{profileId:_t}:void 0;await window.agentApi.run(c.content,m,h,c.agentName,c.images,oe),O=!0}}catch(oe){const J=Rs(wt.current,m);if((J==null?void 0:J.forkSessionId)===m)ho(m,J);else{ji(m,"failed");const je=Qn.current.get(m);m.startsWith("runtime:")&&(je!=null&&je.content)&&(je.restoreDraftOnFailure!==!1&&(Hr(m,je.content),Xt.save(m,je.images??[]),(nt.current||yt.current)===m&&(Qt(je.content),gn(je.images??[]))),Qn.current.delete(m),ft.current===m&&(ft.current=null))}Ce(oe instanceof Error?oe.message:"Agent run failed")}finally{if(Sr.current.delete(m),La.current.delete(m)){Ct.current=m,ke(m);return}const J=(he=window.agentApi)!=null&&he.getSessionGoals?await window.agentApi.getSessionGoals(m).catch(()=>{}):void 0;if(Sr.current.has(m))return;if(J&&m===(nt.current||yt.current)&&an(J,m),J!=null&&J.active){Ct.current=m,ke(m),u&&u(n,m);return}const je=as.current?void 0:Ze.getState().getMessagesForSession(m).find(ue=>ue.isQueued&&!ue.queueItemId);if(je)qe(je.id,ue=>({...ue,isQueued:!1}),m),u&&u(n,m),js(je,m);else{if(O&&((Z=window.agentApi)!=null&&Z.notifyTaskCompletion)){const ue=(Ae=[...Ze.getState().getMessagesForSession(m)].reverse().find(de=>de.role==="assistant"&&de.content.trim()&&!de.isCompactionSummary))==null?void 0:Ae.content,Be=qp({sessionId:m,runId:y,title:"任务已完成",finalText:ue,outcome:"completed"},Xn);Be&&window.agentApi.notifyTaskCompletion(Be,Xn)}Ct.current===m&&(Ct.current=null),Ze.getState().runningSessionId===m&&ke(null),u&&u(n,m)}}}const Qa=async c=>{var ue,Be;if(!c.text||!An||Bs>0||V.current==="anchored"&&!await $a())return;Ci(window.agentApi,ti),Jr!==X&&Ce(null);const m=c.text,h=()=>{c.clearComposer&&(Qt(""),Fs([]),gn([]))};if(/^\/loop\b/i.test(m)){const de=m.slice(5).trim();if(h(),ae({id:crypto.randomUUID(),role:"user",content:m,timestamp:Date.now()}),/^stop$/i.test(de)){window.agentApi&&(await window.agentApi.cronDeleteAll(),Y([]),ae({id:crypto.randomUUID(),role:"assistant",content:"✅ 所有定时任务已删除。",timestamp:Date.now()}));return}if(/^(?:list|status|查看|列表)$/i.test(de)||de===""){if(window.agentApi){const Oe=await window.agentApi.cronList();Y(Oe);const Mt=Oe.length===0?"当前没有定时任务。":Oe.map((vt,xe)=>`**${xe+1}.** \`${vt.id.slice(0,6)}\` · ${Ao(vt.cron)} · ${vt.enabled?"▶ 启用":"⏸ 已暂停"}
|
|
465
|
+
`:null]},v))},`txt-${l++}`))}}return e.jsx(e.Fragment,{children:i})}const eu=[{value:"off",label:"关"},{value:"low",label:"低"},{value:"medium",label:"中"},{value:"high",label:"高"}],mc=Object.fromEntries(eu.map(t=>[t.value,t.label])),Sm=750,To={low:"低",medium:"中",high:"高",xhigh:"超高",max:"最大"},xc={codex:"Codex","claude-code":"Claude Code",opencode:"OpenCode"};function Cm(t,n){return n==="codex"?t==="openai":n==="claude-code"?t==="anthropic":!1}const Li=[{value:"request-approval",label:"请求批准",description:"编辑外部文件和使用互联网时始终询问"},{value:"auto-approval",label:"帮我批准",description:"仅对检测到的风险操作请求批准"},{value:"full-access",label:"完全访问权限",description:"可不受限制地访问互联网和你电脑上的任何文件"}];function bc(t){return Li.some(n=>n.value===t)?t:"full-access"}function Im({activeAgentType:t="customer-agent",selectedProjectId:n=null,selectedSessionId:r=null,onSessionCreated:s,onMessageSent:i,onSubSessionCreated:o,onSelectSession:l,onSubAgentEvent:d,onRunComplete:u,sessionTitle:f,sessionSummary:p,workspacePath:v=null,onOpenSettings:x,settingsOpen:w=!1,onHideToBackground:j,onOpenHub:E,onOpenDesktopLive:S,desktopLiveOpen:C=!1,fileDrawerOpen:k=!1,onToggleFiles:z,onOpenArtifact:M,onToggleAppearance:H,appearanceOpen:L=!1,hideToBackgroundTitle:T,voiceCommand:A=null}){var Ya,Ja,Za,el,tl,nl,rl,sl,il,ol;const R=a.useCallback(c=>Zd(c,M),[M]),{messages:$,messagesBySession:F,runningSessionId:Ee,appendText:Qe,addMessage:ae,setRunningSession:ke,setSessionId:De,updateToolResult:Ie,updateSubAgentStatus:We,updateSubAgentProgress:at,updateMessage:Ge,setMessages:ne,getMessagesForSession:be,getSessionHistoryWindow:Ye,contextUsageBySession:W,runtimeProgressBySession:te,nativeSubagentsBySession:G,setContextUsage:le,applyRuntimeProgress:pe,setRuntimeProgress:ye,clearRuntimeProgress:we,applyNativeSubagentActivity:Te,setNativeSubagentActivities:ut,applyReasoningSummary:lt,applyCodexExecutionEvent:st,clearMessages:Tt,sessionId:He,todos:Nt,setTodos:ct,cronTasks:B,setCronTasks:Y}=et(),[q,se]=a.useState({active:null,queued:[],history:[]}),[ee,Ke]=a.useState(null),[dt,Jt]=a.useState(0),Ze=Lf($,F,He,r),$e=a.useMemo(()=>Kd(th(Nh(Ze.filter(c=>!c.isQueued),q.queued),t==="codex")),[t,q.queued,Ze]),Gt=a.useMemo(()=>{var c,m;return(m=(c=$e.findLast(h=>h.executionTrace))==null?void 0:c.executionTrace)==null?void 0:m.turnId},[$e]),{revision:rt,isConfigured:Pt,profiles:ht,activeProfileId:_t,switchActiveProfile:ln,loadFromSystem:vn,contextWindow:Ue,reasoningEffort:Dt,taskNotifications:Xn,setField:$n,saveToSystem:cn}=qi(),X=r||He,[dn,Zt]=a.useState({}),wt=a.useRef({}),Rt=a.useCallback((c,m)=>{const h=c?mm(wt.current,c):m?xm(wt.current,m):wt.current;wt.current=h,Zt(h)},[]),gt=Rs(dn,X),[Wt,mt]=a.useState(!1),[wn,Yn]=a.useState(null),Jn=a.useRef(!1),[en,Hn]=a.useState("idle"),[tn,Zn]=a.useState(!1);a.useEffect(()=>{if(!Vo()||!window.browserLiveApi)return;const c=()=>Zn(!0);return window.addEventListener(ul,c),()=>window.removeEventListener(ul,c)},[]);const[kn,un]=a.useState(null),[ar,jn]=a.useState(null),Un=Lh(r,p,t),Ne=Un.agentType,it=Un.ready&&Wh(p,t),[Ht,er]=a.useState([]),[Wn,Ft]=a.useState(null),I=a.useRef(null),[Q,fe]=a.useState(()=>El(Ne)),[ze,ge]=a.useState(!1),Ut=a.useRef(null);a.useEffect(()=>{fe(El(Ne)),ge(!1)},[Ne]),a.useEffect(()=>{var m;if(!it||!((m=window.agentApi)!=null&&m.listAgentModels)||I.current===Ne)return;const c=Ne;I.current=c,er([]),Ft(null),window.agentApi.listAgentModels(c).then(h=>{I.current===c&&(er(h.models??[]),Ft(c))}).catch(()=>{I.current===c&&(er([]),Ft(null),I.current=null)})},[it,Ne]),a.useEffect(()=>{if(!ze)return;const c=m=>{Ut.current&&!Ut.current.contains(m.target)&&ge(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[ze]);const rn=a.useCallback(c=>{fe(m=>{const h={...m,...c};return Ml(Ne,h),h})},[Ne]),pt=a.useMemo(()=>it?Ht.map(c=>({key:oi(c),label:c.displayName||c.id,model:{id:c.id,...c.providerID?{providerID:c.providerID}:{}},reasoningEfforts:c.reasoningEfforts})):[],[it,Ht]),Sn=a.useMemo(()=>it?(ht??[]).filter(c=>{var m;return(m=c.modelId)==null?void 0:m.trim()}).filter(c=>Ne==="opencode"||Cm(c.provider,Ne)).map(c=>({key:Ne==="opencode"?oi({id:c.modelId,providerID:c.provider}):c.modelId,label:c.name||c.modelId,model:{id:c.modelId,...Ne==="opencode"?{providerID:c.provider}:{}}})):[],[it,ht,Ne]),hr=a.useMemo(()=>Ne==="opencode"?Sf(Ht):[],[Ne,Ht]),hs=a.useMemo(()=>new Set([...pt.map(c=>c.key),...Sn.map(c=>c.key)]),[pt,Sn]),lr=Wn===Ne&&rt!==void 0,Bt=a.useMemo(()=>kf(Q,hs,lr),[hs,lr,Q]);a.useEffect(()=>{Bt!==Q&&(fe(Bt),Ml(Ne,Bt))},[Ne,Bt,Q]);const sn=(Ya=Bt.model)!=null&&Ya.id?oi(Bt.model):"",tr=a.useMemo(()=>{var m;const c=pt.find(h=>h.key===sn);if((m=c==null?void 0:c.reasoningEfforts)!=null&&m.length)return c.reasoningEfforts;if(Ne==="claude-code")return["low","medium","high","xhigh"]},[pt,sn,Ne]),gr=a.useMemo(()=>it?Ne==="codex"?tr??[]:Ne==="claude-code"?tr??["low","medium","high","xhigh"]:[]:[],[it,Ne,tr]),qt=Bt.reasoningEffort&&gr.includes(Bt.reasoningEffort)?Bt.reasoningEffort:void 0,Xr=pt.length>0||Sn.length>0,Yr=(p==null?void 0:p.messageQueueVersion)===1,Mn=bh(p==null?void 0:p.agentType),cr=kn===X?"direct":ar?"incompatible":(Ja=p==null?void 0:p.compatibility)==null?void 0:Ja.status,on=cr!==void 0&&cr!=="direct",pn=on||(p==null?void 0:p.occupancy)==="owned-externally"&&p.agentType!=="codex",qn=ym(gt,X),gs=qn&&(gt==null?void 0:gt.forkSessionId)!==X,mr=Pt||it,An=Un.ready&&mr&&!pn&&!qn&&en!=="released",xt=a.useRef(new Set),[kt,Tn]=a.useState("idle"),fn=a.useRef("idle"),Vt=a.useRef(null),[Nn,nr]=a.useState(()=>Date.now()),Nr=a.useCallback(c=>{Vt.current=c,fn.current="thinking",nr(Date.now()),Tn("thinking")},[]),Ot=!!(X&&(Ee===X||xt.current.has(X))),xr=Oh(p,Ot),Cn=Ot||Fh(p),dr=X?te[X]??[]:[],_n=X?G[X]??{}:{},_r=Cf(dr),br=$e[$e.length-1],Ls=!!((br==null?void 0:br.role)==="assistant"&&kt==="thinking"&&((el=(Za=br.presentation)==null?void 0:Za.reasoning)!=null&&el.some(c=>c.text.trim()))),rr=kt==="tools"&&$e.some(c=>{var m;return((m=c.toolCalls)==null?void 0:m.length)&&!So(c.toolCalls)}),ur=Cn&&!_r&&!Ls&&!rr;a.useEffect(()=>{vn()},[]),a.useEffect(()=>{window.agentApi&&window.agentApi.cronList().then(c=>Y(c))},[]);const[Kt,Qt]=a.useState(""),[b,N]=a.useState(null),[D,re]=a.useState(""),[ce,Ve]=a.useState(null),[Pe,qe]=a.useState(()=>new Set),Xe=a.useRef(new Set),[jt,zt]=a.useState(null),$t=a.useRef(null),[Vn,zn]=a.useState(!1),[yr,Je]=a.useState(!1),[zr,Lt]=a.useState(!1),[Ln,Lr]=a.useState("full-access"),[sr,ui]=a.useState(!1),[pi,hn]=a.useState(null),[fi,Ps]=a.useState(!1),ms=a.useRef(null),Pr=a.useRef(null),an=a.useCallback((c,m)=>{var O;const h=nt.current||yt.current;if(m===h&&(se(Jl(c)),((O=c.active)==null?void 0:O.kind)==="message"&&(fn.current!=="thinking"||Vt.current!==m)&&Nr(m),V.current==="anchored"))return;const y=be(m);ne(ko(y,c),m)},[Nr,be,ne]);a.useEffect(()=>{if(!yr)return;const c=m=>{ms.current&&!ms.current.contains(m.target)&&Je(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[yr]),a.useEffect(()=>{if(!zr)return;const c=m=>{Pr.current&&!Pr.current.contains(m.target)&&Lt(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[zr]),a.useEffect(()=>{Lt(!1),Lr(bc(p==null?void 0:p.permissionMode))},[it,r,p==null?void 0:p.permissionMode]);const[Gn,Ce]=a.useState(null),[Jr,vr]=a.useState(null),[xs,Ds]=a.useState(null),[Ws,Xi]=a.useState(0),[hi,Fs]=a.useState([]),[pr,gn]=a.useState([]),[Bs,bs]=a.useState(0),[Yi,Dr]=a.useState(null),Pn=a.useRef(null),Os=a.useRef(null),wr=a.useRef(null),Zr=a.useRef(()=>{}),es=a.useRef(new Hp),$s=a.useRef(()=>{}),g=a.useRef(null),_=a.useRef(null);_.current||(_.current=new eh);const U=a.useRef(null),V=a.useRef("latest"),K=a.useRef(null),Re=a.useRef(!1),me=a.useRef(null),Le=a.useRef(0),Fe=a.useRef(0),nn=a.useRef(null),Fn=a.useRef(!1),_e=a.useRef(!1),Et=a.useRef(null),In=a.useRef(!1),St=a.useRef(!1),Rn=a.useRef(null),Wr=a.useRef(null),ir=a.useRef(0),ts=a.useRef(null),Kn=a.useRef(new Map),Fr=a.useRef(new Set),kr=a.useRef(null),tt=a.useRef(!1),ft=a.useRef(null),ns=a.useRef(null),Ji=a.useRef(null);Ji.current||(Ji.current=new Rh(new Ih));const Xt=Ji.current,gi=a.useRef(!1),Zi=a.useRef(null),jr=a.useRef(null),mi=a.useRef(zh(fc)),[Ia,Ra]=a.useState(!1),[eo,xi]=a.useState(null),[to,no]=a.useState(null),[Hs,pu]=a.useState("latest"),[fu,ys]=a.useState(null),[hu,vs]=a.useState(null),[gu,ws]=a.useState(!1),[mu,Ea]=a.useState(!1),[ro,bi]=a.useState(!1),[xu,so]=a.useState(!1),[ks,yi]=a.useState(!1),[bu,vi]=a.useState(!1),Ma=a.useRef(null),Us=a.useRef(null),io=a.useRef(null),[Br,Aa]=a.useState(null),[yu,Ta]=a.useState([]),[vu,Na]=a.useState([]),[qs,oo]=a.useState([]),[Vs,rs]=a.useState(null),[ss,is]=a.useState(null),bt=a.useCallback(c=>nt.current===c?p==null?void 0:p.agentType:c.startsWith("runtime:codex:")?"codex":void 0,[p==null?void 0:p.agentType]),mn=a.useCallback((c,m)=>{if(!m)return;const h=`${c}:${m}`;ts.current!==h&&(ts.current=h,Kn.current.clear())},[]),ao=a.useCallback(async c=>{const m=window.agentApi,h=nt.current;if(!m||!h)throw new Error("当前会话不可用");mn(h,c.revision);const y=`${c.turnId}:${c.itemId}`;let O=Kn.current.get(y);O||(O=m.getSessionToolResult(h,c),Kn.current.set(y,O),O.catch(()=>{Kn.current.get(y)===O&&Kn.current.delete(y)}));const P=await O;return nt.current!==h||ts.current!==`${h}:${c.revision}`,P},[mn]),_a=a.useCallback(async c=>{const m=nt.current;if(!m)throw new Error("当前会话不可用");const h=await ao(c);nt.current===m&&Ie(c.itemId,h.content,h.isError,m)},[ao,Ie]),wu=a.useCallback(async c=>{var P;const m=window.agentApi,h=nt.current;if(!m||!h)throw new Error("当前会话不可用");const y=await Hf(m,h,c,Rr),O=y.detail;if(nt.current!==h)throw new DOMException("Session selection changed","AbortError");if(((P=O==null?void 0:O.history)==null?void 0:P.revision)!==y.revision)throw new Error("会话内容已更新,请重新展开执行过程");return y.recovered&&ne(be(h).map(he=>he.executionTrace?{...he,executionTrace:{...he.executionTrace,revision:y.revision}}:he),h),mn(h,y.revision),Gf(O)},[be,ne,mn]);a.useEffect(()=>{ts.current=null,Kn.current.clear()},[r]);const fr=a.useCallback((c,m)=>{const h=window.agentApi;!m||!h||_.current.prefetch(c,m,()=>h.getSession(c,{before:m,limit:bt(c)==="codex"?si:Rr,...bt(c)==="codex"?{view:"core"}:{}})).catch(y=>{console.warn("[chat] failed to prefetch older history",{sessionId:c,error:y})})},[bt]),os=a.useCallback(c=>{V.current=c,pu(c)},[]);a.useEffect(()=>{const c=jh(kr.current,X,Kt);if(kr.current=c.ownerSessionId,c.type==="inactive"){ns.current=null,Xt.restore(null),gn([]);return}if(c.type==="restore"){const h=c.ownerSessionId.startsWith("runtime:")?Rs(wt.current,c.ownerSessionId):void 0;Qt((h==null?void 0:h.payload.content)??kh(c.ownerSessionId)),gn([]),ns.current=c.ownerSessionId,Xt.restore(c.ownerSessionId).then(y=>{if(!y||kr.current!==y.sessionId)return;ns.current===y.sessionId&&(ns.current=null);const O=(h==null?void 0:h.payload.images)??y.images;gn(O),h&&Xt.save(y.sessionId,O)});return}if(tt.current&&Kt===""){tt.current=!1;return}Hr(c.ownerSessionId,c.value)},[Xt,Kt,X]),a.useEffect(()=>{if(!(!X||kr.current!==X)&&ns.current!==X){if(ft.current===X&&pr.length===0){ft.current=null;return}Xt.saveSelected(X,pr)}},[Xt,pr,X]);const ku=()=>{const c=Pn.current;if(!c)return;const m=c.scrollHeight-c.scrollTop-c.clientHeight;c.scrollTop<=240&&Zr.current(),V.current==="anchored"&&m<=240&&$s.current(),so(mi.current.onScroll(m)),c.classList.add("is-scrolling"),wr.current!==null&&window.clearTimeout(wr.current),wr.current=window.setTimeout(()=>{c.classList.remove("is-scrolling"),wr.current=null},700)};a.useEffect(()=>()=>{wr.current!==null&&window.clearTimeout(wr.current)},[]);const ju=a.useCallback(()=>{const c=Pn.current;if(!c)return;mi.current.requestReturn();const m=typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;c.scrollTo({top:c.scrollHeight,behavior:m?"auto":"smooth"})},[]);a.useEffect(()=>{mi.current.reset(),so(!1)},[r]),a.useLayoutEffect(()=>{const c=Zi.current,m=Pn.current;!c||!m||(m.scrollTop=c.scrollTop+(m.scrollHeight-c.scrollHeight),Zi.current=null)},[Ze]),a.useLayoutEffect(()=>{const c=nn.current,m=Pn.current;if(!c||!m)return;const h=Array.from(m.querySelectorAll("[data-message-id]")).find(y=>y.dataset.messageId===c);h&&(No(m,h),nn.current=null,ys(c))},[Ze]),a.useLayoutEffect(()=>{const c=Pn.current;!Fn.current||!c||Hs!=="latest"||(Fn.current=!1,c.scrollTop=c.scrollHeight)},[Hs,Ze]),a.useLayoutEffect(()=>{if(jr.current!=="skip")return;const c=Pn.current;c&&so(c.scrollHeight-c.scrollTop-c.clientHeight>fc)},[Ze]);const[za,lo]=a.useState(!1),[Gs,Ks]=a.useState(null),wi=a.useRef(null);a.useEffect(()=>{const c=window.agentApi;if(!(c!=null&&c.onTtsStart)||!c.onTtsPcm||!c.onTtsStreamEnd||!c.onTtsFlush)return;const m=new $f(c),h=[c.onTtsStart(y=>m.start(y)),c.onTtsPcm(({generation:y,pcm:O})=>m.enqueue(y,O)),c.onTtsStreamEnd(({generation:y})=>m.finish(y)),c.onTtsFlush(({generation:y})=>m.flush(y)),c.onTtsEnd(()=>Ks(null))];return()=>{for(const y of h)y();m.dispose()}},[]);const Su=()=>{var h;if(za){(h=wi.current)==null||h.stop(),wi.current=null,lo(!1);return}Ci(window.agentApi,ti);const c=Kt?`${Kt.trimEnd()} `:"",m=Wf({onInterim:y=>Qt(c+y),onFinal:y=>{var O;Qt(c+y),(O=Us.current)==null||O.focus()},onError:y=>Ce(y),onEnd:()=>{lo(!1),wi.current=null}});m&&(wi.current=m,lo(!0))},Cu=async(c,m)=>{var h;if(Gs===c){await Ci(window.agentApi,ti),Ks(null);return}if(await Ci(window.agentApi,ti),!((h=window.agentApi)!=null&&h.ttsSpeak)){Ce("TTS 模型服务不可用");return}Ks(c);try{(await window.agentApi.ttsSpeak(m)).ok||(Ks(null),Ce("TTS 模型播报失败"))}catch(y){Ks(null),Ce(y instanceof Error?y.message:"TTS 模型播报失败")}},Ct=a.useRef(null),as=a.useRef(!1),Sr=a.useRef(new Set),Qs=a.useRef(new Map),La=a.useRef(new Set),Qn=a.useRef(new Map),Or=a.useRef(null),nt=a.useRef(r??null),Pa=a.useRef({onRunComplete:u,selectedProjectId:n}),yt=a.useRef(null),Dn=a.useRef(0);a.useEffect(()=>{nt.current=r??null},[r]),a.useEffect(()=>{Pa.current={onRunComplete:u,selectedProjectId:n}},[u,n]),a.useEffect(()=>{yt.current=He},[He]),a.useEffect(()=>()=>{for(const c of Qs.current.values())window.clearTimeout(c);Qs.current.clear()},[]);const ki=a.useCallback(async c=>{var h;const m=c||nt.current||yt.current;if(!m||!((h=window.agentApi)!=null&&h.getSessionGoals)){se({active:null,queued:[],history:[]});return}try{const y=await window.agentApi.getSessionGoals(m);an(y,m),y.active&&(Ct.current=m,ke(m))}catch(y){Ce(y instanceof Error?y.message:"目标状态加载失败")}},[an,ke]);a.useEffect(()=>{ki(X)},[X,ki]);const Xs=a.useCallback(async c=>{var h;const m=c||nt.current||yt.current;if(!m||typeof((h=window.agentApi)==null?void 0:h.getThreadGoal)!="function"){Ke(null);return}try{Ke(await window.agentApi.getThreadGoal(m))}catch{Ke(null)}},[]);a.useEffect(()=>{Xs(X)},[X,Xs]);const co=a.useCallback(async c=>{var h;const m=nt.current||yt.current;if(!(!m||typeof((h=window.agentApi)==null?void 0:h.clearThreadGoal)!="function"))try{c==="clear"?(await window.agentApi.clearThreadGoal(m),Ke(null)):typeof window.agentApi.updateThreadGoal=="function"&&Ke(await window.agentApi.updateThreadGoal(m,c))}catch(y){Ce(y instanceof Error?y.message:"目标模式操作失败")}},[Ce]),xn=a.useCallback(c=>{const m=nt.current||yt.current;c==="thinking"&&(fn.current!=="thinking"||Vt.current!==m)?(Vt.current=m,nr(Date.now())):c!=="thinking"&&(Vt.current=null),fn.current=c,Tn(c)},[]);a.useEffect(()=>{mt(!1),Hn("idle"),vr(null),Dr(null)},[r]),a.useEffect(()=>{window.agentApi&&(window.agentApi.listAgentDefs().then(c=>Ta(c)),window.agentApi.listSkills().then(c=>Na(c.filter(m=>m.name))).catch(c=>console.error("[listSkills] mount error:",c)))},[]);const Da=Vs===null?[]:yu.filter(c=>Vs===""||c.name.toLowerCase().includes(Vs.toLowerCase())),uo=ss===null?[]:[...[{name:"goal",description:"目标模式:持续推进当前目标,后续目标自动排队"},{name:"compact",description:"主动压缩当前会话上下文,并在下轮重新注入环境"},{name:"loop",description:"定时任务:/loop 5m 任务 | list | pause/resume/delete <id> | stop"}].filter(c=>ss===""||c.name.toLowerCase().includes(ss.toLowerCase())),...vu.filter(c=>ss===""||c.name.toLowerCase().includes(ss.toLowerCase()))],Iu=c=>{oo(m=>m.find(h=>h.id===c.id)?m:[...m,c]),Qt(m=>m.replace(/@[\w\u4e00-\u9fff]*$/,"")),rs(null),setTimeout(()=>{var m;return(m=Us.current)==null?void 0:m.focus()},0)},Ru=c=>{oo(m=>m.filter(h=>h.id!==c))},Eu=c=>{Qt(m=>m.replace(/\/[\w\u4e00-\u9fff\-_]*$/,`/${c.name} `)),is(null),setTimeout(()=>{var m;return(m=Us.current)==null?void 0:m.focus()},0)},Wa=c=>{var y,O;Qt(c);const m=c.match(/@([\w\u4e00-\u9fff]*)$/);if(m){window.agentApi&&window.agentApi.listAgentDefs().then(P=>Ta(P)),Aa(((y=io.current)==null?void 0:y.getBoundingClientRect())??null),rs(m[1]),is(null);return}const h=c.match(/\/([-\w\u4e00-\u9fff]*)$/);if(h){window.agentApi&&window.agentApi.listSkills().then(P=>Na(P.filter(he=>he.name))).catch(P=>console.error("[listSkills] slash error:",P)),Aa(((O=io.current)==null?void 0:O.getBoundingClientRect())??null),is(h[1]),rs(null);return}rs(null),is(null)},Mu=c=>{Wa(c),rs(null),is(null),requestAnimationFrame(()=>{var m;return(m=Us.current)==null?void 0:m.focus()})},Au=c=>{c.key==="Escape"&&(Vs!==null||ss!==null)?(c.preventDefault(),rs(null),is(null)):c.key==="Escape"&&Ot?(c.preventDefault(),go()):c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),Xa())},Tu=async c=>{const m=Array.from(c.target.files??[]);if(c.target.value="",m.length===0)return;const h=m.filter(y=>y.type.toLowerCase().startsWith("image/")).length;h>0&&bs(y=>y+1);try{const y=await gm(m,async P=>Fa(await Vl(P)));y.attachments.length>0&&Fs(P=>[...P,...y.attachments]),y.images.length>0&&(gn(P=>[...P,...y.images]),it||zu());const O=[...y.unsupportedImages,...y.failedImages];O.length>0&&Ce(`无法添加图片:${O.map(P=>P.name).join("、")}。仅支持 JPG、PNG、GIF 和 WebP。`)}finally{h>0&&bs(y=>Math.max(0,y-1))}},Nu=c=>{Fs(m=>m.filter((h,y)=>y!==c))},_u=/claude-3|gpt-4-vision|gpt-4o|gpt-4-turbo|gemini|deepseek-vl/i,po=c=>_u.test(c),zu=()=>{const c=ht.find(h=>h.id===_t);if(c&&po(c.modelId))return;const m=ht.find(h=>po(h.modelId));m&&ln(m.id)},Lu=c=>{gn(m=>[...m,c])},Pu=c=>{gn(m=>m.filter((h,y)=>y!==c))},Fa=c=>new Promise((m,h)=>{const y=new FileReader;y.onload=()=>m(y.result),y.onerror=h,y.readAsDataURL(c)});a.useEffect(()=>{const c=async m=>{if(!m.clipboardData)return;const h=Array.from(m.clipboardData.items).find(O=>O.type.startsWith("image/"));if(!h)return;m.preventDefault();const y=h.getAsFile();if(y){bs(O=>O+1);try{Lu(await Fa(await Vl(y)))}catch{Ce("无法添加图片。仅支持 JPG、PNG、GIF 和 WebP。")}finally{bs(O=>Math.max(0,O-1))}}};return window.addEventListener("paste",c),()=>window.removeEventListener("paste",c)},[ht,_t]),a.useEffect(()=>{var m;const c=jr.current;jr.current=null,mi.current.shouldFollow(c)&&((m=Os.current)==null||m.scrollIntoView({behavior:"auto"}))},[Ze]),a.useEffect(()=>window.agentApi?window.agentApi.onEvent(m=>Du(m)):void 0,[He]),a.useEffect(()=>{const c=++Dn.current,m=r,h=()=>Dn.current===c&&nt.current===m;return(async()=>{var he,Z,Ae;const O=window.agentApi;if(!O||Yg(Ct.current,yt.current,m))return;if(!m){if(!h())return;(he=_.current)==null||he.invalidate(),Tt(),Ce(null),Ds(null),un(null),jn(null),g.current=null,K.current=null,Le.current+=1,me.current=null,no(null),os("latest"),ys(null),vs(null),_e.current=!1,bi(!1),ws(!1),xi(null),yi(!1),vi(!1),U.current=null,yt.current=null,De(""),Lr("full-access");return}Ce(null),Ds(null),un(null),jn(null),xi(null),(Z=_.current)==null||Z.invalidate(),Fe.current+=1,g.current=null,K.current=null,os("latest"),ws(!1),ys(null),vs(null),_e.current=!1,bi(!1),((Ae=me.current)==null?void 0:Ae.sessionId)!==m&&(Le.current+=1,me.current=null,no(null)),yi(!0),vi(!0),U.current=m,yt.current=m,De(m);const P=be(m);ne(P,m);try{await ph(async()=>{if(!h())throw new DOMException("Session selection changed","AbortError");return await Ss(O,m,bt(m),{limit:bt(m)==="codex"?Mo:Rr},(oe,J)=>{var Mt,vt,xe;if(!h())return;const je=oe,ue=Nl((oe==null?void 0:oe.events)??[]),Be=Al((oe==null?void 0:oe.events)??[]),de=_l((oe==null?void 0:oe.events)??[]),ve=cs(oe);mn(m,(Mt=oe==null?void 0:oe.history)==null?void 0:Mt.revision),p!=null&&p.compatibility&&un(m),Lr(bc((je==null?void 0:je.permissionMode)??((vt=je==null?void 0:je.metadata)==null?void 0:vt.permissionMode))),K.current=null;const Me=be(m),Se=Bl(Me,ve,J,oe==null?void 0:oe.history,Ye(m)),It=oe!=null&&oe.goalState?ko(Se.messages,oe.goalState):Se.messages;g.current=Se.window.olderCursor,jr.current="instant",ne(It,m,Se.window),fr(m,Se.window.olderCursor),ye(Be,m),ut(de,m),Nd(oe)||Bh(oe)?(Ct.current=m,ke(m)):Ct.current===m&&(Ct.current=null,ke(null)),ue&&le(ue,m);const Oe=It[It.length-1];(Oe==null?void 0:Oe.role)==="assistant"&&((xe=Oe.toolCalls)!=null&&xe.length)?xn(So(Oe.toolCalls)?"thinking":"tools"):xn((oe==null?void 0:oe.agentType)!=="customer-agent"&&(oe==null?void 0:oe.status)==="running"?"thinking":"idle"),yi(!1),vi(!1)},h),!0})}catch(oe){if(!h())return;console.error("[chat] failed to restore session",{sessionId:m,error:oe});const J=uh(oe);Ds(J),p!=null&&p.compatibility&&jn(J)}finally{h()&&(yi(!1),vi(!1))}})(),()=>{Dn.current===c&&(Dn.current+=1)}},[Tt,be,Ye,bt,fr,r,Ws,le,os,ne,De,mn,xn]);const $r=a.useCallback(async c=>{const m=window.agentApi;if(!(m!=null&&m.getSessionQueryIndex))return null;const h=++Le.current;try{const y=await m.getSessionQueryIndex(c);return Le.current!==h||nt.current!==c||y.sessionId!==c?null:(me.current=y,no(y),y)}catch(y){return Le.current===h&&console.warn("[chat] failed to load query index",{sessionId:c,error:y}),null}},[]),Ba=a.useCallback(c=>{if(Wr.current!==c&&(Rn.current!==null&&window.clearTimeout(Rn.current),Wr.current=c,Rn.current=null,ir.current=0),Rn.current!==null)return;const m=Math.max(0,Sm-(Date.now()-ir.current));Rn.current=window.setTimeout(()=>{Rn.current=null,ir.current=Date.now(),nt.current===c&&Jt(h=>h+1)},m)},[]);a.useEffect(()=>{var P;const c=r;if(!c||ks||!((P=window.agentApi)!=null&&P.getSessionQueryIndex))return;let m=!1;const h=()=>{!m&&nt.current===c&&$r(c)},y=window,O=y.requestIdleCallback?y.requestIdleCallback(h,{timeout:1e3}):window.setTimeout(h,0);return()=>{m=!0,y.cancelIdleCallback&&y.requestIdleCallback?y.cancelIdleCallback(O):window.clearTimeout(O)}},[ks,$r,r,Ws]);const Ys=a.useCallback(async c=>{if(!window.agentApi||document.visibilityState==="hidden")return;if(V.current==="anchored"){ws(!0);return}if(Et.current!==c&&(Et.current=c,In.current=!1,St.current=!1),In.current){St.current=!0;return}const m=Dn.current,h=Fe.current;In.current=!0;try{do St.current=!1,await Ss(window.agentApi,c,bt(c),{limit:bt(c)==="codex"?Mo:Rr},(y,O)=>{var Be,de,ve,Me,Se;const P=cs(y),he=be(c),Z=Bl(he,P,O,y==null?void 0:y.history,Ye(c)),Ae=y!=null&&y.goalState?ko(Z.messages,y.goalState):Z.messages,oe=Pn.current,J=!oe||oe.scrollHeight-oe.scrollTop-oe.clientHeight<80;jr.current=J?null:"skip",ne(Ae,c,Z.window),mn(c,(Be=y==null?void 0:y.history)==null?void 0:Be.revision),y!=null&&y.goalState&&se(Jl(y.goalState)),g.current!==Z.window.olderCursor&&((de=_.current)==null||de.invalidate(),g.current=Z.window.olderCursor,fr(c,Z.window.olderCursor)),(ve=y==null?void 0:y.history)!=null&&ve.revision&&y.history.revision!==((Me=me.current)==null?void 0:Me.revision)&&$r(c);const je=Nl((y==null?void 0:y.events)??[]);ye(Al((y==null?void 0:y.events)??[]),c),ut(_l((y==null?void 0:y.events)??[]),c),je&&le(je,c);const ue=Ae[Ae.length-1];(ue==null?void 0:ue.role)==="assistant"&&((Se=ue.toolCalls)!=null&&Se.length)?xn(So(ue.toolCalls)?"thinking":"tools"):xn(ma(y)?"thinking":"idle")},()=>nt.current===c&&U.current===c&&Dn.current===m&&Fe.current===h&&V.current==="latest"),bt(c)==="codex"&&Ba(c);while(St.current)}catch(y){console.error("[chat] failed to refresh native session history",{sessionId:c,error:y})}finally{Et.current===c&&(In.current=!1)}},[be,Ye,bt,$r,fr,Ba,le,ne,mn,xn]);a.useEffect(()=>{const c=r,m=$h(p,c)||(p==null?void 0:p.agentType)==="customer-agent"&&c!==Ee,h=(p==null?void 0:p.agentType)==="customer-agent"||(p==null?void 0:p.occupancy)==="owned-externally"||(p==null?void 0:p.status)==="running";if(!c||!m||!window.agentApi)return;let y=null,O=null,P=!1;const he=()=>{!P&&document.visibilityState!=="hidden"&&Ys(c)},Z=()=>{y==null||y(),y=null,O!==null&&window.clearInterval(O),O=null},Ae=()=>{P||O!==null||document.visibilityState==="hidden"||(he(),O=window.setInterval(he,2e3))},oe=()=>{if(!(P||document.visibilityState==="hidden")){if(typeof window.agentApi.observeSession!="function"){h&&Ae();return}try{y=window.agentApi.observeSession(c,he,()=>{y=null,h&&Ae()})}catch{h&&Ae()}}},J=()=>{Z(),document.visibilityState!=="hidden"&&(he(),oe())};return oe(),document.addEventListener("visibilitychange",J),()=>{P=!0,document.removeEventListener("visibilitychange",J),Z(),Et.current===c&&(Et.current=null,St.current=!1),Wr.current===c&&(Rn.current!==null&&window.clearTimeout(Rn.current),Wr.current=null,Rn.current=null,ir.current=0)}},[Ys,r,Ee,p==null?void 0:p.agentType,p==null?void 0:p.occupancy,p==null?void 0:p.status]);const fo=a.useCallback(async()=>{const c=U.current,m=g.current,h=window.agentApi;if(!h||!c||!m||ks||gi.current)return;const y=Dn.current,O=Fe.current,P=()=>U.current===c&&nt.current===c&&Dn.current===y&&Fe.current===O&&g.current===m;gi.current=!0,xi(null);const he=window.setTimeout(()=>{P()&&gi.current&&Ra(!0)},500);try{await Ss(h,c,bt(c),{before:m,limit:bt(c)==="codex"?si:Rr},(Z,Ae)=>{var Me;const oe=cs(Z),J=be(c),je=new Set(J.map(Se=>Se.id)),ue=oe.filter(Se=>!je.has(Se.id)).length,Be=Ol(J,oe,"older"),de=Pn.current;Ae!=="trace"&&de&&ue>0&&(Zi.current={scrollHeight:de.scrollHeight,scrollTop:de.scrollTop},jr.current="skip");const ve=Uf(m,Z,ue);g.current=ve,mn(c,(Me=Z==null?void 0:Z.history)==null?void 0:Me.revision),ne(Be,c,{kind:V.current,olderCursor:ve}),Ae!=="trace"&&fr(c,ve)},P,()=>_.current.consume(c,m,()=>h.getSession(c,{before:m,limit:bt(c)==="codex"?si:Rr,...bt(c)==="codex"?{view:"core"}:{}})))}catch(Z){if(!P())return;console.error("[chat] failed to load older history",{sessionId:c,error:Z}),xi(Z instanceof Error?Z.message:"历史消息加载失败")}finally{window.clearTimeout(he),gi.current=!1,U.current===c&&Ra(!1)}},[be,bt,ks,fr,ne,mn]);a.useEffect(()=>{Zr.current=()=>{fo()}},[fo]);const Oa=a.useCallback(async()=>{const c=U.current,m=K.current;if(!window.agentApi||!c||!m||V.current!=="anchored"||Re.current)return;const h=Dn.current,y=Fe.current,O=()=>nt.current===c&&U.current===c&&V.current==="anchored"&&Dn.current===h&&Fe.current===y&&K.current===m;Re.current=!0,Ea(!0);try{await Ss(window.agentApi,c,bt(c),{after:m,limit:bt(c)==="codex"?si:Rr},P=>{var Ae,oe;const he=be(c),Z=Ol(he,cs(P),"newer");K.current=((Ae=P==null?void 0:P.history)==null?void 0:Ae.newerCursor)??null,mn(c,(oe=P==null?void 0:P.history)==null?void 0:oe.revision),Z!==he&&(jr.current="skip",ne(Z,c,{kind:"anchored",olderCursor:g.current}))},O)}catch(P){if(!O())return;console.error("[chat] failed to load newer anchored history",{sessionId:c,error:P})}finally{Re.current=!1,Ea(!1)}},[be,bt,ne,mn]);a.useEffect(()=>{$s.current=()=>{Oa()}},[Oa]);const $a=a.useCallback(async()=>{const c=nt.current;if(!window.agentApi||!c||_e.current)return!1;const m=++Fe.current;_e.current=!0,bi(!0),vs(null);try{let h=!1;return await Ss(window.agentApi,c,bt(c),{limit:bt(c)==="codex"?Mo:Rr},(y,O)=>{var Z,Ae,oe,J,je,ue,Be;h=!0;const P=cs(y),he=((Z=y==null?void 0:y.history)==null?void 0:Z.nextCursor)??null;O!=="trace"&&((Ae=_.current)==null||Ae.invalidate()),g.current=he,K.current=null,mn(c,(oe=y==null?void 0:y.history)==null?void 0:oe.revision),os("latest"),ws(!1),ys(((je=(J=me.current)==null?void 0:J.entries.at(-1))==null?void 0:je.messageId)??null),Fn.current=!0,jr.current="skip",ne(P,c,{kind:"latest",olderCursor:he}),O!=="trace"&&fr(c,he),((ue=y==null?void 0:y.history)==null?void 0:ue.revision)!==((Be=me.current)==null?void 0:Be.revision)&&$r(c)},()=>Fe.current===m&&nt.current===c),h}catch(h){return Ce(h instanceof Error?h.message:"返回最新消息失败"),!1}finally{_e.current=!1,bi(!1)}},[bt,$r,fr,os,ne,mn]),Ha=a.useCallback(async(c,m=!0)=>{var he;const h=nt.current,y=Pn.current;if(!window.agentApi||!h||!y)return;const O=++Fe.current;ys(c.messageId);const P=Array.from(y.querySelectorAll("[data-message-id]")).find(Z=>Z.dataset.messageId===c.messageId);if(P){vs(null),No(y,P,"smooth");return}vs(c.messageId),(he=_.current)==null||he.invalidate();try{await Ss(window.agentApi,h,bt(h),{anchor:c.pageToken,limit:bt(h)==="codex"?si:Rr},(Z,Ae)=>{var je,ue,Be,de,ve,Me;if(((je=me.current)==null?void 0:je.revision)!==((ue=Z==null?void 0:Z.history)==null?void 0:ue.revision))return;const oe=cs(Z),J=((Be=Z==null?void 0:Z.history)==null?void 0:Be.olderCursor)??((de=Z==null?void 0:Z.history)==null?void 0:de.nextCursor)??null;g.current=J,K.current=((ve=Z==null?void 0:Z.history)==null?void 0:ve.newerCursor)??null,mn(h,(Me=Z==null?void 0:Z.history)==null?void 0:Me.revision),os("anchored"),ws(!1),nn.current=c.messageId,jr.current="skip",ne(oe,h,{kind:"anchored",olderCursor:J}),Ae!=="trace"&&(window.requestAnimationFrame(()=>{if(Fe.current!==O||nt.current!==h)return;const Se=Pn.current,It=Array.from((Se==null?void 0:Se.querySelectorAll("[data-message-id]"))??[]).find(Oe=>Oe.dataset.messageId===c.messageId);!Se||!It||(No(Se,It),nn.current=null,ys(c.messageId))}),fr(h,J))},()=>Fe.current===O&&nt.current===h)}catch(Z){if(Z.code==="STALE_SESSION_ANCHOR"&&m){const oe=await $r(h),J=oe==null?void 0:oe.entries.find(je=>je.ordinal===c.ordinal);J&&await Ha(J,!1);return}console.error("[chat] failed to open indexed query",{sessionId:h,error:Z}),Ce(Z instanceof Error?Z.message:"无法打开这条消息")}finally{Fe.current===O&&vs(null)}},[bt,$r,fr,os,ne,mn]),Ua=c=>{if(Sr.current.has(c)||Qs.current.has(c))return;const m=window.setTimeout(()=>{Qs.current.delete(c),(async()=>{var h;if(!Sr.current.has(c))try{const y=await((h=window.agentApi)==null?void 0:h.getSessionGoals(c));if(Sr.current.has(c))return;const O=nt.current||yt.current;if(y&&c===O&&an(y,c),y!=null&&y.active){Ct.current=c,c===O&&(as.current=!1,Ce(null),ke(c));return}if(as.current)return;const P=et.getState().getMessagesForSession(c).find(he=>he.isQueued&&!he.queueItemId);if(!P){Ct.current===c&&(Ct.current=null),et.getState().runningSessionId===c&&ke(null);return}Ge(P.id,he=>({...he,isQueued:!1}),c),js(P,c)}catch(y){Ce(y instanceof Error?y.message:"排队消息自动发送失败")}})()},150);Qs.current.set(c,m)},ji=(c,m)=>{const h=et.getState().getMessagesForSession(c),y=Th(h);y&&Ge(y,O=>({...O,sendState:m}),c)},ho=(c,m)=>{const h=uc(m),y=et.getState().getMessagesForSession(c);ne(y.filter(O=>O.id!==h),c),Hr(c,m.payload.content),Xt.save(c,m.payload.images??[]),(nt.current||yt.current)===c&&(Qt(m.payload.content),gn(m.payload.images??[])),Qn.current.delete(c),ft.current===c&&(ft.current=null),Rt(void 0,c)},Du=c=>{var he,Z,Ae,oe;const m=nt.current||yt.current,h=Ph(c._sid)??void 0;if(!h&&c.type!=="cron_update")return;if(c._nativeRunId&&Number.isSafeInteger(c._nativeSequence)){const J=`${c._nativeRunId}:${c._nativeSequence}`;if(Fr.current.has(J))return;Fr.current.add(J),Fr.current.size>2e3&&(Fr.current=new Set([...Fr.current].slice(-1e3)))}const y=!h||h===m,O=y&&V.current==="anchored",P=(h==null?void 0:h.startsWith("runtime:"))&&(c.type==="run_admitted"||c.type==="done")&&be(h).some(J=>J.role==="user"&&!J.isQueued&&J.sendState==="failed");if(h&&y&&(c._nativeRecoveredFromSnapshot||P)&&Ys(h),!(O&&(ws(!0),Dh(c.type)))){if(h&&["run_admitted","thinking","text_chunk","reasoning_summary_delta","runtime_progress","tool_call","todo_update","done"].includes(c.type)&&ji(h),h&&y&&!c._preserveActiveRun&&["done","error","turn_aborted"].includes(c.type)&&!Sr.current.has(h)){const J=Pa.current;(he=J.onRunComplete)==null||he.call(J,J.selectedProjectId??null,h)}switch(c.type){case"run_admitted":if(h&&Jr===h&&(vr(null),y&&Ce(null)),h){Qn.current.delete(h);const J=Rs(wt.current,h);J&&(Or.current===J.token&&(Or.current=null),Rt(void 0,h)),Cs(h),Xt.clear(h),ft.current===h&&(ft.current=null)}break;case"context_usage":if(c.usage&&(le(c.usage,h),h&&!h.startsWith("runtime:"))){const J=(et.getState().runtimeProgressBySession[h]??[]).filter(je=>je.progressId!==yd);ye(J,h)}break;case"text_chunk":c.text&&(h&&c.turnId&&c.messagePhase==="commentary"&&bt(h)==="codex"?st(c.turnId,{type:"text_chunk",text:c.text,turnId:c.turnId,itemId:c.itemId,messagePhase:"commentary"},h):Qe(c.text,h),y&&xn("thinking"));break;case"reasoning_summary_delta":if(typeof c.itemId=="string"&&Number.isSafeInteger(c.sectionIndex)&&typeof c.delta=="string"){const J={type:"reasoning_summary_delta",itemId:c.itemId,sectionIndex:c.sectionIndex,delta:c.delta,...c.turnId?{turnId:c.turnId}:{}};h&&c.turnId&&bt(h)==="codex"?st(c.turnId,J,h):lt(J,h),y&&xn("thinking")}break;case"runtime_progress":if(typeof c.progressId=="string"&&typeof c.label=="string"&&["thinking","tool","retry","status"].includes(c.phase??"")){const J={progressId:c.progressId,phase:c.phase,label:c.label,...c.detail===void 0?{}:{detail:c.detail},...c.toolCallId===void 0?{}:{toolCallId:c.toolCallId},...c.elapsedSeconds===void 0?{}:{elapsedSeconds:c.elapsedSeconds},...c.current===void 0?{}:{current:c.current},...c.total===void 0?{}:{total:c.total}};pe(J,h),y&&xn(J.phase==="tool"?"tools":"thinking")}break;case"native_subagent_update":(Z=c.activity)!=null&&Z.parentToolCallId&&(Te(c.activity,h),y&&c.activity.status==="running"&&xn("tools"));break;case"tool_call":y&&xn("tools"),c.toolCall&&c.toolCall.name!=="dispatch_agent"&&c.toolCall.name!=="ask_user"&&c.toolCall.name!=="show_widget"&&(h&&c.turnId&&bt(h)==="codex"?st(c.turnId,{type:"tool_call",toolCall:c.toolCall,turnId:c.turnId},h):ae({id:crypto.randomUUID(),role:"assistant",content:"",toolCalls:[{id:c.toolCall.id,name:c.toolCall.name,arguments:c.toolCall.arguments}],timestamp:Date.now()},h));break;case"tool_result":c.result&&(h&&c.turnId&&bt(h)==="codex"?st(c.turnId,{type:"tool_result",result:c.result,turnId:c.turnId},h):Ie(c.result.toolCallId,c.result.content,c.result.isError,h));break;case"todo_update":c.todos&&ct(c.todos);break;case"cron_update":c.tasks&&Y(c.tasks);break;case"agent_dispatch":if(ae({id:crypto.randomUUID(),role:"assistant",content:"",toolCalls:[{id:crypto.randomUUID(),name:"dispatch_agent",arguments:{agentName:c.agentName,task:c.task??"",subSessionId:c.subSessionId}}],timestamp:Date.now()},h),c.subSessionId){xt.current.add(c.subSessionId);const J=Ct.current||He;J&&o&&o(J)}d==null||d({type:"started",agentName:c.agentName??"",task:c.task??"",subSessionId:c.subSessionId});break;case"agent_done":c.subSessionId&&(xt.current.delete(c.subSessionId),We(c.subSessionId,c.status??"completed",c.status==="failed"?c.error:c.summary,h)),d==null||d({type:c.status==="failed"?"failed":"completed",agentName:c.agentName??"",task:c.task??"",subSessionId:c.subSessionId});break;case"agent_progress":c.subSessionId&&c.text&&at(c.subSessionId,c.text,h);break;case"compacted":ae({id:crypto.randomUUID(),role:"assistant",content:c.summary??"",isCompactionSummary:!0,timestamp:Date.now()},h);break;case"show_widget":{const J=c.data??c.widgetData,je={widgetId:c.widgetId,widgetType:c.widgetType,data:J??{}},Be=(h?et.getState().getMessagesForSession(h):et.getState().messages).find(de=>{var ve;return((ve=de.widget)==null?void 0:ve.widgetId)===je.widgetId});Be?Ge(Be.id,de=>({...de,widget:je}),h):ae({id:crypto.randomUUID(),role:"assistant",content:"",widget:je,timestamp:Date.now()},h);break}case"ask_user":if(c.questionId&&(h?et.getState().getMessagesForSession(h):et.getState().messages).some(je=>{var ue;return((ue=je.askUser)==null?void 0:ue.questionId)===c.questionId}))break;ae({id:crypto.randomUUID(),role:"assistant",content:"",askUser:{questionId:c.questionId??"",question:c.question??"",options:c.options,fields:c.fields,multiSelect:c.multiSelect},timestamp:Date.now()},h);break;case"approval_resolved":{if(!c.questionId)break;const je=(h?et.getState().getMessagesForSession(h):et.getState().messages).find(ue=>{var Be;return((Be=ue.askUser)==null?void 0:Be.questionId)===c.questionId});je&&Ge(je.id,ue=>({...ue,askUser:ue.askUser?{...ue.askUser,answered:!0,answer:ue.askUser.answer??"已处理"}:ue.askUser}),h);break}case"text_done":break;case"thinking":y&&xn("thinking");break;case"done":if(h&&Jr===h&&(vr(null),y&&Ce(null)),h&&!O){const J=Yd(c.durationMs);if(J!==void 0||c.forkPoint){const je=[...be(h)].reverse().find(ue=>{var Be;return ue.role==="assistant"&&!!ue.content.trim()&&!((Be=ue.toolCalls)!=null&&Be.length)&&!ue.isCompactionSummary});je&&Ge(je.id,ue=>({...ue,presentation:{...ue.presentation,...J!==void 0?{completionDurationMs:J}:{},...c.forkPoint?{forkPoint:c.forkPoint}:{}}}),h)}}if(we(h),h&&!be(h).some(J=>J.isQueued)&&(Ct.current===h&&(Ct.current=null),et.getState().runningSessionId===h&&ke(null)),y&&(xn("idle"),!O&&bn.getState().autoSpeak)){const je=[...et.getState().messages].reverse().find(ue=>ue.role==="assistant"&&ue.content&&!ue.isCompactionSummary);je!=null&&je.content&&(Ae=window.agentApi)!=null&&Ae.ttsSpeak&&(ti(),window.agentApi.ttsSpeak(je.content.slice(0,600)).then(ue=>{ue.ok||Ce("TTS 模型播报失败")}).catch(ue=>{Ce(ue instanceof Error?ue.message:"TTS 模型播报失败")}))}h&&(Sr.current.has(h)?window.setTimeout(()=>{ki(h)},150):Ua(h),Xs(h));break;case"error":if(c._preserveActiveRun||we(h),h&&c.code==="SESSION_OCCUPIED"&&!O){const J=et.getState().getMessagesForSession(h),je=Qn.current.get(h),ue=Rs(wt.current,h),Be=(ue==null?void 0:ue.forkSessionId)===h?ue:void 0,de=je??(ue==null?void 0:ue.payload),ve=de?[...J].reverse().find(Se=>Se.role==="user"&&!Se.isQueued&&Se.content===de.content):y?[...J].reverse().find(Se=>Se.role==="user"&&!Se.isQueued):void 0,Me=de??(ve?{content:ve.content,images:ve.images,agentName:ve.agentName}:void 0);Be?ho(h,Be):(ve&&ne(J.filter(Se=>Se.id!==ve.id),h),Qn.current.delete(h),Me!=null&&Me.content&&(Rt(ue??bm(h,Me)),Hr(h,Me.content),Xt.save(h,Me.images??[]),y&&(Qt(Me.content),gn(Me.images??[]))),ft.current===h&&(ft.current=null)),y&&Ce(null)}if(h&&h.startsWith("runtime:")&&c.code!=="SESSION_OCCUPIED"&&c.code!=="SESSION_ALREADY_RUNNING"&&c.code!=="CANCEL_CONFIRMATION_TIMEOUT"&&!O){const J=et.getState().getMessagesForSession(h),je=Qn.current.get(h),ue=Rs(wt.current,h),Be=(ue==null?void 0:ue.forkSessionId)===h?ue:void 0,de=je?[...J].reverse().find(Me=>Me.role==="user"&&!Me.isQueued&&Me.content===je.content):[...J].reverse().find(Me=>Me.role==="user"&&!Me.isQueued),ve=je??(de?{content:de.content,images:de.images,agentName:de.agentName}:void 0);Be?ho(h,Be):ve!=null&&ve.content&&(Hr(h,ve.content),Xt.save(h,ve.images??[]),y&&(Qt(ve.content),gn(ve.images??[]))),Qn.current.delete(h),ft.current===h&&(ft.current=null)}if(y)if(c._preserveActiveRun&&h&&(La.current.add(h),Ct.current=h,ke(h),xn("thinking")),c.code==="SESSION_ALREADY_RUNNING"&&!O){const J=h?Qn.current.get(h):void 0,je=h?et.getState().getMessagesForSession(h):et.getState().messages,ue=Ah(je);if(ue){const Be=je.find(de=>de.id===ue);Ge(ue,de=>({...de,isQueued:!0,sendState:void 0}),h),Yr&&h&&Be&&((oe=window.agentApi)!=null&&oe.enqueueSessionMessage)?window.agentApi.enqueueSessionMessage(h,{sourceMessageId:Be.id,content:Be.content,images:Be.images,agentName:Be.agentName}).then(de=>{an(de,h),Cs(h),Xt.clear(h)}).catch(de=>{const ve=(J==null?void 0:J.content)??Be.content,Me=(J==null?void 0:J.images)??Be.images??[];Hr(h,ve),Xt.save(h,Me),(nt.current||yt.current)===h&&(Qt(ve),gn(Me)),Ce(de instanceof Error?de.message:"排队消息保存失败")}):h&&(Cs(h),Xt.clear(h))}h&&Qn.current.delete(h),h&&ft.current===h&&(ft.current=null),h&&Rt(void 0,h),Ce(null)}else c.code!=="SESSION_OCCUPIED"&&(Ce(c.message??"Unknown error"),vr(c.code==="CANCEL_CONFIRMATION_TIMEOUT"?h??null:null),h&&c.code==="CANCEL_CONFIRMATION_TIMEOUT"&&(Qn.current.delete(h),ft.current===h&&(ft.current=null)),h&&c.code!=="CANCEL_CONFIRMATION_TIMEOUT"&&ji(h,"failed"));if(!c._preserveActiveRun){const J=h??m;(!J||Ct.current===J)&&(Ct.current=null),(!J||et.getState().runningSessionId===J)&&ke(null),y&&xn("idle")}h&&!c._preserveActiveRun&&(Sr.current.has(h)?window.setTimeout(()=>{ki(h)},150):Ua(h),Xs(h));break;case"turn_aborted":h&&Jr===h&&(vr(null),y&&Ce(null)),we(h),Ct.current===h&&(Ct.current=null),et.getState().runningSessionId===h&&ke(null),y&&xn("idle"),Xs(h);break;case"goal_updated":h===(nt.current||yt.current)&&Ke(c.goal??null);break;case"goal_cleared":h===(nt.current||yt.current)&&Ke(null);break}}},Wu=async c=>{var h;if(!X||!((h=window.agentApi)!=null&&h.setSessionPermissionMode)||fi)return;const m=Ln;Lr(c),Lt(!1),Ps(!0);try{await window.agentApi.setSessionPermissionMode(X,c)}catch(y){Lr(m),Ce(y instanceof Error?y.message:"权限模式更新失败")}finally{Ps(!1)}},qa=async()=>{var c;if(!(!X||(p==null?void 0:p.agentType)!=="codex"||!((c=window.agentApi)!=null&&c.releaseCodexSession)||en!=="idle")&&!(Cn&&!window.confirm("停止当前执行并退出此会话?Codex Desktop 最长约 30 分钟后可用。"))){Hn("releasing");try{await window.agentApi.releaseCodexSession(X),as.current=!0,Dn.current+=1,Ct.current=null,ke(null),xt.current.clear(),se(m=>({...m,active:null,queued:[]})),Tn("idle"),Ce(null),vr(null),Hn("released")}catch(m){Hn("idle"),Ce(m instanceof Error?m.message:"释放 Codex 会话失败")}}},Fu=a.useCallback(async c=>{var P;const m=yt.current;if(!m||!((P=window.agentApi)!=null&&P.forkSession)||Jn.current||Wt)return;let h=wo(c,m);Jn.current=!0,Yn(c.id),Ce(null);let y=!1;const O=Dn.current;try{if(!h){const Z=await window.agentApi.getSession(m,{limit:100,view:"core"}),Ae=cs(Z).filter(oe=>{var J;return oe.role==="assistant"&&!((J=oe.toolCalls)!=null&&J.length)&&oe.content===c.content});if(Ae.length===1&&(h=wo(Ae[0],m)),!h)throw Ys(m),new Error("轮次正在同步,请刷新会话后重试 Fork")}const he=h;await pc({sourceSessionId:m,forkSession:Z=>window.agentApi.forkSession(Z,he),activateSession:Z=>{yt.current!==m||Dn.current!==O||(y=!0,yt.current=Z,De(Z))},refreshAndSelect:async Z=>{!y||yt.current!==Z.id||(s?await s(Z.id,Z):l==null||l(Z.id))}})}catch(he){(yt.current===m||y)&&Ce(he instanceof Error?he.message:"Fork 失败,请重试")}finally{Jn.current=!1,Yn(null)}},[Wt,s,l,Ys,De]),Bu=async()=>{var h;const c=gt;if(!c||!X||Wt||Jn.current||Or.current===c.token)return;Or.current=c.token;const m=(y,O)=>{const P=uc(y);if(be(O).some(Z=>Z.id===P)){Ge(P,Z=>({...Z,sendState:"pending"}),O);return}ae({id:P,role:"user",content:y.payload.content,timestamp:Date.now(),agentName:y.payload.agentName,images:y.payload.images,sendState:"pending"},O)};if(c.forkSessionId){mt(!0);const y=dc(c,c.forkSessionId);Rt(y),m(y,y.forkSessionId),js(y.payload,y.forkSessionId,y.payload.agentIds).finally(()=>{Or.current=null,mt(!1)});return}if(!((h=window.agentApi)!=null&&h.forkSession)){Or.current=null;return}mt(!0);try{const y=await pc({sourceSessionId:c.sourceSessionId,forkSession:P=>window.agentApi.forkSession(P),activateSession:P=>{yt.current=P,De(P)},refreshAndSelect:async P=>{s?await s(P.id,P):l==null||l(P.id)}}),O=dc(c,y.id);Rt(O),m(O,y.id),js(O.payload,y.id,O.payload.agentIds).finally(()=>{Or.current=null,mt(!1)}),Ce(null)}catch(y){Or.current=null,Ce(y instanceof Error?y.message:"创建会话副本失败"),mt(!1)}},go=()=>{as.current=!0,Dn.current+=1,window.agentApi&&window.agentApi.abort(X||void 0).catch(c=>{Ce(c instanceof Error?c.message:"停止执行失败")}),Ne!=="codex"&&(Ct.current=null,ke(null),xt.current.clear())},Va=async c=>{const m=r||He;if(!m||!window.agentApi||Xe.current.has(c))return;const h=be(m).find(y=>y.id===c);if(!(!h||!h.isQueued)){Xe.current.add(c),qe(new Set(Xe.current));try{if(h.queueItemId){const y=await window.agentApi.steerSessionMessage(m,h.queueItemId);ne(Yl(be(m),c,Date.now()),m),an(y,m)}else await window.agentApi.steer(h.content,m,h.agentName),ne(Yl(be(m),c,Date.now()),m);b===c&&(N(null),re(""))}catch(y){Ce(y instanceof Error?y.message:"引导失败")}finally{Xe.current.delete(c),qe(new Set(Xe.current))}}},Ou=c=>{const m=et.getState().messages.find(h=>h.id===c&&h.isQueued);m&&(N(c),re(m.content))},mo=()=>{N(null),re("")},Ga=async c=>{const m=D.trim(),h=et.getState().messages.find(y=>y.id===c&&y.isQueued);if(!(!h||!m))try{h.queueItemId&&X?an(await window.agentApi.updateSessionMessage(X,h.queueItemId,m),X):Ge(c,y=>y.isQueued?{...y,content:m}:y,X||void 0),mo()}catch(y){Ce(y instanceof Error?y.message:"排队消息保存失败")}},$u=async c=>{const m=et.getState().messages.find(h=>h.id===c&&h.isQueued);if(m){if(!await zi(m.content)){Ce("复制排队消息失败");return}Ve(c),window.setTimeout(()=>Ve(h=>h===c?null:h),1200)}},Hu=async c=>{const m=et.getState().messages,h=m.find(y=>y.id===c&&y.isQueued);if(h)try{h.queueItemId&&X?an(await window.agentApi.cancelSessionMessage(X,h.queueItemId),X):ne(m.filter(y=>y.id!==c),X||void 0),b===c&&mo()}catch(y){Ce(y instanceof Error?y.message:"排队消息删除失败")}},xo=async(c,m)=>{const h=et.getState().messages,y=_h(h,c,m);if(y!==h){ne(y,X||void 0);const O=y.filter(P=>P.isQueued&&P.queueItemId);if(X&&O.length>0)try{an(await window.agentApi.reorderSessionMessages(X,O.map(P=>P.queueItemId)),X)}catch(P){ne(h,X),Ce(P instanceof Error?P.message:"排队消息排序保存失败")}}},Uu=(c,m)=>{const h=et.getState().messages.filter(P=>P.isQueued),y=h.findIndex(P=>P.id===c),O=h[y+m];O&&xo(c,O.id)},qu=async c=>{const m=pi;if(hn(null),!X||!m||m===c)return;const h=q.queued.map(Z=>Z.id),y=h.indexOf(m),O=h.indexOf(c);if(y<0||O<0)return;const P=[...h];P.splice(O,0,P.splice(y,1)[0]);const he=q;se({...q,queued:P.map((Z,Ae)=>({...q.queued.find(oe=>oe.id===Z),position:Ae}))});try{an(await window.agentApi.reorderSessionGoals(X,P),X)}catch(Z){se(he),Ce(Z instanceof Error?Z.message:"目标排序保存失败")}},Ka=async c=>{if(!X)return;const m=q.queued.find(h=>h.id===c);try{const h=await window.agentApi.cancelSessionGoal(X,c);if(an(h,X),m!=null&&m.sourceMessageId){const y=et.getState().getMessagesForSession(X);ne(y.filter(O=>O.id!==m.sourceMessageId),X)}h.active||ke(null)}catch(h){Ce(h instanceof Error?h.message:"目标删除失败")}};a.useEffect(()=>{b&&($.some(c=>c.id===b&&c.isQueued)||(N(null),re("")))},[b,$]);async function js(c,m,h){var P,he,Z,Ae;const y=crypto.randomUUID();let O=!1;m.startsWith("runtime:")&&Qn.current.set(m,{content:c.content,images:c.images?[...c.images]:void 0,agentIds:h?[...h]:void 0,agentName:c.agentName,restoreDraftOnFailure:c.restoreDraftOnFailure}),as.current=!1,Sr.current.add(m),Nr(m),Ct.current=m,ke(m);try{if(window.agentApi){const oe=it&&Wi(Ne)?{...(P=Bt.model)!=null&&P.id?{model:Bt.model}:{},...qt?{reasoningEffort:qt}:{}}:_t?{profileId:_t}:void 0;await window.agentApi.run(c.content,m,h,c.agentName,c.images,oe),O=!0}}catch(oe){const J=Rs(wt.current,m);if((J==null?void 0:J.forkSessionId)===m)ho(m,J);else{ji(m,"failed");const je=Qn.current.get(m);m.startsWith("runtime:")&&(je!=null&&je.content)&&(je.restoreDraftOnFailure!==!1&&(Hr(m,je.content),Xt.save(m,je.images??[]),(nt.current||yt.current)===m&&(Qt(je.content),gn(je.images??[]))),Qn.current.delete(m),ft.current===m&&(ft.current=null))}Ce(oe instanceof Error?oe.message:"Agent run failed")}finally{if(Sr.current.delete(m),La.current.delete(m)){Ct.current=m,ke(m);return}const J=(he=window.agentApi)!=null&&he.getSessionGoals?await window.agentApi.getSessionGoals(m).catch(()=>{}):void 0;if(Sr.current.has(m))return;if(J&&m===(nt.current||yt.current)&&an(J,m),J!=null&&J.active){Ct.current=m,ke(m),u&&u(n,m);return}const je=as.current?void 0:et.getState().getMessagesForSession(m).find(ue=>ue.isQueued&&!ue.queueItemId);if(je)Ge(je.id,ue=>({...ue,isQueued:!1}),m),u&&u(n,m),js(je,m);else{if(O&&((Z=window.agentApi)!=null&&Z.notifyTaskCompletion)){const ue=(Ae=[...et.getState().getMessagesForSession(m)].reverse().find(de=>de.role==="assistant"&&de.content.trim()&&!de.isCompactionSummary))==null?void 0:Ae.content,Be=qp({sessionId:m,runId:y,title:"任务已完成",finalText:ue,outcome:"completed"},Xn);Be&&window.agentApi.notifyTaskCompletion(Be,Xn)}Ct.current===m&&(Ct.current=null),et.getState().runningSessionId===m&&ke(null),u&&u(n,m)}}}const Qa=async c=>{var ue,Be;if(!c.text||!An||Bs>0||V.current==="anchored"&&!await $a())return;Ci(window.agentApi,ti),Jr!==X&&Ce(null);const m=c.text,h=()=>{c.clearComposer&&(Qt(""),Fs([]),gn([]))};if(/^\/loop\b/i.test(m)){const de=m.slice(5).trim();if(h(),ae({id:crypto.randomUUID(),role:"user",content:m,timestamp:Date.now()}),/^stop$/i.test(de)){window.agentApi&&(await window.agentApi.cronDeleteAll(),Y([]),ae({id:crypto.randomUUID(),role:"assistant",content:"✅ 所有定时任务已删除。",timestamp:Date.now()}));return}if(/^(?:list|status|查看|列表)$/i.test(de)||de===""){if(window.agentApi){const Oe=await window.agentApi.cronList();Y(Oe);const Mt=Oe.length===0?"当前没有定时任务。":Oe.map((vt,xe)=>`**${xe+1}.** \`${vt.id.slice(0,6)}\` · ${Ao(vt.cron)} · ${vt.enabled?"▶ 启用":"⏸ 已暂停"}
|
|
466
466
|
${vt.prompt}`).join(`
|
|
467
467
|
|
|
468
|
-
`);ae({id:crypto.randomUUID(),role:"assistant",content:Mt,timestamp:Date.now()})}return}const ve=de.match(/^(?:pause|暂停)\s+(\S+)$/i);if(ve){if(window.agentApi){const Oe=B.find(vt=>vt.id.startsWith(ve[1])),Mt=await window.agentApi.cronPause((Oe==null?void 0:Oe.id)??ve[1]);if(Mt){const vt=await window.agentApi.cronList();Y(vt),ae({id:crypto.randomUUID(),role:"assistant",content:`⏸ 定时任务 \`${Mt.id.slice(0,6)}\` 已暂停。`,timestamp:Date.now()})}else ae({id:crypto.randomUUID(),role:"assistant",content:`未找到 ID 以 \`${ve[1]}\` 开头的定时任务。`,timestamp:Date.now()})}return}const Me=de.match(/^(?:resume|恢复)\s+(\S+)$/i);if(Me){if(window.agentApi){const Oe=B.find(vt=>vt.id.startsWith(Me[1])),Mt=await window.agentApi.cronResume((Oe==null?void 0:Oe.id)??Me[1]);if(Mt){const vt=await window.agentApi.cronList();Y(vt),ae({id:crypto.randomUUID(),role:"assistant",content:`▶ 定时任务 \`${Mt.id.slice(0,6)}\` 已恢复。`,timestamp:Date.now()})}else ae({id:crypto.randomUUID(),role:"assistant",content:`未找到 ID 以 \`${Me[1]}\` 开头的定时任务。`,timestamp:Date.now()})}return}const Se=de.match(/^(?:delete|del|删除|stop)\s+(\S+)$/i);if(Se){if(window.agentApi){const Oe=B.find(vt=>vt.id.startsWith(Se[1]));if(await window.agentApi.cronDelete((Oe==null?void 0:Oe.id)??Se[1])){const vt=await window.agentApi.cronList();Y(vt),ae({id:crypto.randomUUID(),role:"assistant",content:`🗑 定时任务 \`${Se[1]}\` 已删除。`,timestamp:Date.now()})}else ae({id:crypto.randomUUID(),role:"assistant",content:`未找到 ID 以 \`${Se[1]}\` 开头的定时任务。`,timestamp:Date.now()})}return}const It=de.match(/^(\S+)\s+(.+)$/s);if(It){const Oe=It[1],Mt=It[2].trim();if(window.agentApi){let vt=r||$e;if(!vt){const xe=await window.agentApi.createSession(Mt.slice(0,60)||"定时任务",n||void 0);vt=xe.id,Pe(xe.id),s&&await s(xe.id)}try{const xe=await window.agentApi.cronCreate(Oe,Mt,{sessionId:vt}),Yt=await window.agentApi.cronList();Y(Yt),ae({id:crypto.randomUUID(),role:"assistant",content:`⏰ 定时任务已创建(ID: \`${xe.id.slice(0,6)}\`),${Ao(Oe)}执行:${Mt}`,timestamp:Date.now()})}catch(xe){ae({id:crypto.randomUUID(),role:"assistant",content:`❌ 创建失败:${xe instanceof Error?xe.message:String(xe)}`,timestamp:Date.now()})}}return}ae({id:crypto.randomUUID(),role:"assistant",content:"**定时任务用法:**\n- `/loop <间隔/cron> <任务>` — 创建,如 `/loop 5m 检查系统状态` 或 `/loop 0 9 * * * 早报`\n- `/loop list` — 查看所有定时任务\n- `/loop pause <id>` — 暂停\n- `/loop resume <id>` — 恢复\n- `/loop delete <id>` — 删除\n- `/loop stop` — 删除全部\n\n间隔支持:`30s`、`5m`、`2h`;也支持 5 字段 cron 表达式。",timestamp:Date.now()});return}const y=m.match(/(?:每(?:隔)?|定时每)\s*(\d+(?:\.\d+)?)\s*(分钟|秒|小时|min|sec|h)\s*(.+)/is);if(y){const de=y[1]+y[2],ve=y[3].trim();if(ve&&window.agentApi){let Me=r||$e;if(!Me){const Se=await window.agentApi.createSession(ve.slice(0,60)||"定时任务",n||void 0,Ne,Ne!=="customer-agent"?v??void 0:void 0);Me=Se.id,Pe(Se.id),s&&await s(Se.id)}try{const Se=await window.agentApi.cronCreate(de,ve,{sessionId:Me}),It=await window.agentApi.cronList();Y(It),h(),ae({id:crypto.randomUUID(),role:"user",content:m,timestamp:Date.now()}),ae({id:crypto.randomUUID(),role:"assistant",content:`⏰ 定时任务已创建(ID: \`${Se.id.slice(0,6)}\`),${Ao(de)}执行:${ve}`,timestamp:Date.now()})}catch(Se){ae({id:crypto.randomUUID(),role:"assistant",content:`❌ 创建失败:${Se instanceof Error?Se.message:String(Se)}`,timestamp:Date.now()})}return}}const O=c.text,P=O.match(/^\/goal(?:\s+([\s\S]+))?$/i),he=P?((ue=P[1])==null?void 0:ue.trim())??"":c.applyGoalMode&&sr?O:null;if(he!==null&&!he){Ce("请输入目标内容");return}const Z=c.agentName,Ae=c.images,oe=c.agentIds??[];if(c.clearComposer&&oo([]),he!==null){const de=crypto.randomUUID();let ve=null,Me=null;as.current=!1,c.clearComposer&&X&&(Cs(X),Xt.clear(X)),h();try{const Se=await lc({text:he,projectId:n??null,sessionId:r||$e,createSession:async(Oe,Mt)=>{if(!window.agentApi)throw new Error("agentApi 未就绪");return await window.agentApi.createSession(Oe,Mt,Ne,Ne!=="customer-agent"?v??void 0:void 0)},activateSession:Oe=>{yt.current=Oe,Pe(Oe),Ct.current=Oe,ke(Oe)},showUserMessage:(Oe,Mt)=>{ve=Mt,ae({id:de,role:"user",content:Oe,timestamp:Date.now(),agentName:Z,images:Ae,isGoal:!0,goalId:de},Mt)},onSessionCreated:s});Me=Se,c.clearComposer&&Se!==X&&(Cs(Se),Xt.clear(Se));const It=await window.agentApi.enqueueSessionGoal(Se,he,de);an(It,Se),i&&i(Se,he)}catch(Se){if(ve){const Mt=Ze.getState().getMessagesForSession(ve);ne(Mt.filter(vt=>vt.id!==de),ve)}const It=Me??ve??X;c.restoreDraftOnFailure&&It&&(Hr(It,O),Xt.save(It,Ae??[]));const Oe=nt.current||yt.current;c.restoreDraftOnFailure&&(It&&Oe===It||!It&&!Oe)&&(Qt(O),gn(Ae??[])),ke(null),Ce(Se instanceof Error?Se.message:"目标创建失败")}return}if(xr){const de=X,ve=crypto.randomUUID(),Me={id:ve,role:"user",content:O,timestamp:Date.now(),agentName:Z,images:Ae,isQueued:!0};if(c.clearComposer&&de&&(Cs(de),Xt.clear(de)),h(),Yr&&de&&((Be=window.agentApi)!=null&&Be.enqueueSessionMessage)){ae(Me,de);try{const Se=await window.agentApi.enqueueSessionMessage(de,{sourceMessageId:ve,content:O,images:Ae,agentIds:oe,agentName:Z});an(Se,de)}catch(Se){const It=Ze.getState().getMessagesForSession(de);ne(It.filter(Oe=>Oe.id!==ve),de),c.restoreDraftOnFailure&&(Hr(de,O),Xt.save(de,Ae??[]),(nt.current||yt.current)===de&&(Qt(O),gn(Ae??[]))),Ce(Se instanceof Error?Se.message:"排队消息保存失败")}}else ae(Me,de??void 0);return}const J=r||$e;c.clearComposer&&it&&J&&(tt.current=!0,ft.current=J),h(),ct([]);const je=crypto.randomUUID();try{const de=await lc({text:O,projectId:n??null,sessionId:r||$e,createSession:async(ve,Me)=>{if(!window.agentApi)throw new Error("agentApi 未就绪");return await window.agentApi.createSession(ve,Me,Ne,Ne!=="customer-agent"?v??void 0:void 0)},activateSession:ve=>{yt.current=ve,Pe(ve),Ct.current=ve},showUserMessage:(ve,Me)=>ae({id:je,role:"user",content:ve,timestamp:Date.now(),agentName:Z,images:Ae,sendState:"pending"},Me),afterUserMessageShown:em,onSessionCreated:s});i&&i(de,O),await js({content:O,agentName:Z,images:Ae,restoreDraftOnFailure:c.restoreDraftOnFailure},de,oe.length>0?oe:void 0)}catch(de){const ve=r||$e;ve&&ji(ve,"failed"),Ce(de instanceof Error?de.message:"Agent run failed")}},Xa=async()=>Qa(yh({text:Kt,agentIds:qs.map(c=>c.id),agentName:qs.length>0?qs.map(c=>c.name).join(", "):void 0,images:pr})),Vu=c=>{Qa(vh(c))};return a.useEffect(()=>{if(!A||!window.agentApi)return;const{text:c,projectId:m,sessionId:h}=A;let y=!1;return(async()=>{try{ct([]);const O=await Zg({text:c,projectId:m,sessionId:h,createSession:async(P,he)=>await window.agentApi.createSession(P,he,Ne,Ne!=="customer-agent"?v??void 0:void 0),activateSession:P=>{yt.current=P,Pe(P),Ct.current=P,ke(P)},showUserMessage:(P,he)=>ae({id:crypto.randomUUID(),role:"user",content:P,timestamp:Date.now()},he),onSessionCreated:s,isCancelled:()=>y});if(!O)return;i&&i(O,c),await js({content:c},O)}catch(O){Ce(O instanceof Error?O.message:"语音指令执行失败")}})(),()=>{y=!0}},[A==null?void 0:A.nonce]),e.jsxs("div",{className:"chat-view chat-view--codex-history",style:{display:"flex",flexDirection:"column",height:"100%",maxWidth:"var(--chat-max-width)",margin:"0 auto"},children:[e.jsxs("div",{className:"chat-top-bar",style:{display:"flex",alignItems:"center",padding:"var(--chat-header-padding)",height:"var(--chat-header-height)",flexShrink:0,borderBottom:"1px solid var(--border-subtle)",WebkitAppRegion:"drag"},children:[e.jsx("span",{style:{flex:1,minWidth:0,fontSize:14,fontWeight:500,color:f?"var(--text-primary)":"var(--text-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:"-0.01em"},children:f||"会话"}),x&&j&&H&&e.jsx(yg,{appearanceOpen:L,settingsOpen:w,showSettings:Ne==="customer-agent",onOpenDesktopLive:S,desktopLiveOpen:C,filesOpen:k,onToggleFiles:z,hideToBackgroundTitle:T,codexReleaseState:Zt,onHideToBackground:j,onReleaseCodex:(p==null?void 0:p.agentType)==="codex"&&p.occupancy!=="owned-externally"?()=>{qa()}:void 0,onOpenHub:E,onToggleAppearance:H,onOpenSettings:x})]}),e.jsx($g,{open:en,agentSessionId:X,onClose:()=>Zn(!1)}),e.jsxs("div",{className:"chat-messages-frame",children:[e.jsxs("div",{ref:Pn,className:"chat-messages",onScroll:ku,onWheel:c=>{$p(c,c.currentTarget.scrollTop)&&Zr.current()},onTouchStart:c=>es.current.start(c.touches),onTouchMove:c=>{es.current.move(c.touches,c.currentTarget.scrollTop)&&Zr.current()},onTouchEnd:()=>es.current.reset(),onTouchCancel:()=>es.current.reset(),style:{overflow:"auto",position:"relative",padding:"var(--chat-messages-padding)"},children:[et.length>0&&(Ia||eo)&&e.jsx("div",{className:"chat-history-page-status",role:eo?"alert":"status","aria-live":"polite",children:Ia?e.jsx(e.Fragment,{children:e.jsxs("span",{className:"chat-history-loading-pill",children:[e.jsxs("span",{className:"chat-history-loading-dots","aria-hidden":"true",children:[e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{})]}),e.jsx("span",{children:"正在加载更早消息"})]})}):e.jsxs("button",{type:"button",onClick:()=>void fo(),className:"chat-history-retry",style:{border:"1px solid color-mix(in srgb, var(--danger) 30%, transparent)",background:"color-mix(in srgb, var(--danger) 7%, transparent)",color:"var(--danger)",borderRadius:6,padding:"5px 10px",cursor:"pointer",fontSize:12},children:[eo,",点击重试"]})}),et.length===0&&ks&&bu&&e.jsxs("div",{className:"chat-history-initial-loading",role:"status",style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",gap:9,color:"var(--text-muted)",fontSize:13},children:[e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:e.jsx("path",{d:"M21 12a9 9 0 1 1-6.22-8.56"})}),e.jsx("span",{children:"正在加载历史消息"})]}),et.length===0&&!Cn&&!ks&&!Gn&&e.jsx(Vg,{agentType:(p==null?void 0:p.agentType)??t,ready:An,onSelectPrompt:Mu},X??"initial-empty-session"),Ge.map((c,m)=>{var Be,de,ve,Me,Se,It,Oe,Mt,vt;const h=c;if(h.isQueued)return null;if(h.executionTrace)return e.jsx(gg,{trace:h.executionTrace,loadTrace:wu,loadToolResult:ao,renderContent:R,runtimeProgress:dr,nativeSubagents:_n,onSelectSession:l,workspacePath:v,onOpenArtifact:M,refreshSignal:h.executionTrace.turnId===Gt?ut:0,autoLoad:Hs==="latest"&&h.executionTrace.turnId===Gt},c.id);const y=c.role==="user",O=y&&(h.isGoal===!0||[q.active,...q.queued,...q.history].some(xe=>!!(xe&&hc(xe.objective)===hc(c.content)))),P=fm(Ge,m,Cn),he=cm((Be=h.presentation)==null?void 0:Be.completionDurationMs);if(h.isCompactionSummary)return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,margin:"20px 0",color:"var(--text-muted)",fontSize:12},children:[e.jsx("div",{style:{flex:1,height:1,background:"var(--border-subtle)"}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",borderRadius:20,border:"1px solid var(--border-subtle)",background:"var(--bg-deep)",color:"var(--text-muted)",fontSize:11,cursor:"default",userSelect:"none"},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"17 1 21 5 17 9"}),e.jsx("path",{d:"M3 11V9a4 4 0 0 1 4-4h14"}),e.jsx("polyline",{points:"7 23 3 19 7 15"}),e.jsx("path",{d:"M21 13v2a4 4 0 0 1-4 4H3"})]}),"上下文已压缩"]}),e.jsx("div",{style:{flex:1,height:1,background:"var(--border-subtle)"}})]},c.id);if(h.widget){const xe=Xg[h.widget.widgetType];return xe?e.jsx("div",{style:{marginBottom:16,display:"flex",justifyContent:"flex-start"},children:e.jsx(xe,{...h.widget.data,widgetId:h.widget.widgetId,isAgentRunning:Cn&&!Ge.slice(m+1).some(Yt=>Yt.role==="user"&&!Yt.isQueued&&!Yt.isSteered)})},c.id):e.jsx("div",{style:{marginBottom:16,padding:12,borderRadius:8,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",fontFamily:"var(--font-mono, monospace)",fontSize:12,whiteSpace:"pre-wrap",maxHeight:300,overflow:"auto"},children:JSON.stringify(h.widget.data,null,2)},c.id)}if(h.askUser)return e.jsx(dg,{questionId:h.askUser.questionId,question:h.askUser.question,options:h.askUser.options,fields:h.askUser.fields,multiSelect:h.askUser.multiSelect,answered:h.askUser.answered,answer:h.askUser.answer,onAnswer:async(xe,Yt)=>{var At;if(!await((At=window.agentApi)==null?void 0:At.answerQuestion(h.askUser.questionId,xe,Yt)))throw new Error("回答未发送成功,请重试;若问题已结束,请刷新会话。");qe(c.id,En=>({...En,askUser:{...En.askUser,answered:!0,answer:xe}}),X??void 0)}},c.id);const Z=h.agentName?h.agentName.charAt(0).toUpperCase():"你",Ae=!y&&m===Ge.length-1,oe=Ge[m+1],J=oe&&oe.role!==c.role&&!oe.isCompactionSummary,je=(c.toolCalls??[]).map((xe,Yt)=>{let Js;if(xe.name==="write_file"&&xe.arguments.file_path){const At=xe.arguments.file_path;e:for(let En=m;En>=0;En--){const Cr=Ge[En].toolCalls;if(!Cr)continue;const Zs=En===m?Yt-1:Cr.length-1;for(let ls=Zs;ls>=0;ls--){const Ir=Cr[ls];if(Ir.name==="read_file"&&Ir.arguments.file_path===At&&Ir.result&&!Ir.isError){Js=Ir.result;break e}}}}return{toolCall:xe,beforeContent:Js,progress:wd(dr,xe.id),nativeSubagent:_n[xe.id]}}),ue=Qd(je);return e.jsx("div",{"data-message-id":c.id,className:`chat-message-group${P.compact?" chat-message-group--intermediate":""}`,style:{marginBottom:P.compact?0:J?"var(--chat-turn-gap)":"var(--chat-message-gap)"},children:e.jsxs("div",{className:`chat-message-row chat-message-row--${y?"user":"assistant"}`,style:{display:"flex",flexDirection:y?"row-reverse":"row",alignItems:"flex-start",gap:"var(--chat-row-gap)",animation:"fadeInUp 0.3s var(--ease-out) both"},children:[y?e.jsx("div",{className:"chat-message-avatar",style:{width:"var(--chat-avatar-size)",height:"var(--chat-avatar-size)",borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--accent)",color:"#fff",fontSize:12,fontWeight:700,letterSpacing:0,userSelect:"none"},children:Z}):e.jsx("div",{className:"chat-message-avatar",style:{width:"var(--chat-avatar-size)",height:"var(--chat-avatar-size)",borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-deep)",color:"var(--text-muted)",border:"1px solid var(--border-subtle)"},children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),e.jsx("path",{d:"M12 11V7"}),e.jsx("circle",{cx:"12",cy:"5",r:"2"}),e.jsx("circle",{cx:"8",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"16",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("path",{d:"M8 20h8"})]})}),e.jsxs("div",{className:`chat-message-content chat-message-content--${y?"user":"assistant"}`,style:{maxWidth:"var(--chat-content-max-width)",display:"flex",flexDirection:"column",gap:4,alignItems:y?"flex-end":"flex-start",minWidth:0},children:[e.jsxs("div",{className:`chat-message-bubble chat-message-bubble--${y?"user":"assistant"} ${c.role==="assistant"&&c.content?"message-card":""}`,style:{padding:c.content||y&&((de=h.images)!=null&&de.length)?y?"var(--chat-user-bubble-padding)":"var(--chat-assistant-bubble-padding)":0,borderRadius:y?"14px 4px 14px 14px":"4px 14px 14px 14px",background:c.content||y&&((ve=h.images)!=null&&ve.length)?y?"rgba(79, 110, 247, 0.08)":void 0:"transparent",border:c.content||y&&((Me=h.images)!=null&&Me.length)?y?"1px solid rgba(79, 110, 247, 0.18)":void 0:"none",fontSize:"var(--chat-bubble-font-size)",lineHeight:"var(--chat-bubble-line-height)",color:"var(--chat-history-text)",letterSpacing:"0.01em"},children:[c.role==="assistant"&&((Se=c.presentation)==null?void 0:Se.reasoning)&&e.jsx(Vd,{sections:c.presentation.reasoning,streaming:Cn&&Ae&&kt==="thinking",startedAt:Nn,renderContent:R}),y&&h.agentName?e.jsxs("div",{children:[e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,fontWeight:700,color:"var(--accent)",background:"var(--accent-dim)",border:"1px solid rgba(79,110,247,0.22)",borderRadius:10,padding:"1px 7px 1px 5px",letterSpacing:"0.04em",marginRight:7,verticalAlign:"middle"},children:[e.jsxs("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("circle",{cx:"12",cy:"8",r:"4"}),e.jsx("path",{d:"M20 21a8 8 0 1 0-16 0"})]}),h.agentName]}),e.jsx("span",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",verticalAlign:"middle"},children:c.content})]}):c.role==="assistant"&&c.content?e.jsx("div",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:e.jsx(vf,{text:c.content,complete:!(Cn&&Ae),renderText:R,suggestionsEnabled:An&&Bs===0,onSuggestionSend:Vu,onCopyFailed:()=>Ce("复制失败,请选择文字后复制")})}):c.content&&e.jsx("div",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:y?c.content:R(c.content)}),y&&h.images&&h.images.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:c.content?8:0},children:h.images.map((xe,Yt)=>e.jsx("button",{type:"button",className:"chat-message-image-button","aria-label":"放大查看图片",onClick:()=>Dr({src:xe,alt:`用户发送的图片 ${Yt+1}`}),children:e.jsx("img",{className:"chat-message-attachment-image",src:xe,alt:`用户发送的图片 ${Yt+1}`})},Yt))}),y&&!((It=h.images)!=null&&It.length)&&((Oe=h.presentation)==null?void 0:Oe.attachments)&&h.presentation.attachments.length>0&&e.jsx("div",{className:"chat-message-attachments",children:h.presentation.attachments.map((xe,Yt)=>xe.dataUrl?e.jsx("button",{type:"button",className:"chat-message-image-button","aria-label":`放大查看图片:${xe.name}`,onClick:()=>Dr({src:xe.dataUrl,alt:xe.name}),children:e.jsx("img",{className:"chat-message-attachment-image",src:xe.dataUrl,alt:xe.name,title:xe.name})},`${xe.name}-${Yt}`):e.jsxs("div",{className:"chat-message-attachment-unavailable","aria-label":`${xe.name},${xe.omitted&&!xe.unavailable?"图片未随页面加载":"图片已失效"}`,children:[e.jsx("span",{className:"chat-message-attachment-name",children:xe.name}),e.jsx("span",{children:xe.omitted&&!xe.unavailable?"图片未随页面加载":"图片已失效"})]},`${xe.name}-${Yt}`))}),y&&((Mt=h.presentation)==null?void 0:Mt.rawContent)&&e.jsxs("details",{className:"chat-message-raw-content",children:[e.jsx("summary",{children:"查看原始内容"}),e.jsx("pre",{children:h.presentation.rawContent})]}),ue.map(xe=>xe.action&&xe.items.length>1?e.jsx(qd,{items:xe.items,onSelectSession:l,workspacePath:v,onOpenArtifact:M,onLoadResult:_a},`group-${xe.items[0].toolCall.id}`):e.jsx(Qi,{toolCall:xe.items[0].toolCall,beforeContent:xe.items[0].beforeContent,progress:xe.items[0].progress,nativeSubagent:xe.items[0].nativeSubagent,onSelectSession:l,workspacePath:v,onOpenArtifact:M,onLoadResult:_a},xe.items[0].toolCall.id)),(()=>{const xe=(c.toolCalls??[]).filter(At=>At.name==="write_file"&&At.result&&!At.isError);if(xe.length===0)return null;const Yt=new Map;for(const At of xe){const En=At.arguments.file_path??"",Cr=At.arguments.content??"",Zs=Cr?Cr.split(`
|
|
469
|
-
`).length:0;let ls=0;e:for(let Ir=m;Ir>=0;Ir--){const al
|
|
470
|
-
`).length;break e}}}Yt.set(En,{path:En,lines:Zs,added:Math.max(0,Zs-ls),removed:Math.max(0,ls-Zs)})}const Js=[...Yt.values()];return e.jsxs("div",{style:{marginTop:10,padding:"8px 12px",borderRadius:8,background:"var(--bg-deep)",border:"1px solid var(--border-subtle)",display:"flex",flexWrap:"wrap",gap:8,alignItems:"center"},children:[e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em",flexShrink:0},children:"变更汇总"}),Js.map(At=>{const En=ga(At.path,v),Cr=e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{color:"var(--text-secondary)",maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:At.path,children:At.path.replace(/\\/g,"/").split("/").pop()}),At.added>0&&e.jsxs("span",{style:{color:"var(--success)",fontWeight:600},children:["+",At.added]}),At.removed>0&&e.jsxs("span",{style:{color:"var(--danger)",fontWeight:600},children:["−",At.removed]}),At.added===0&&At.removed===0&&e.jsxs("span",{style:{color:"var(--text-muted)"},children:[At.lines,"行"]})]});return M&&En?e.jsx("button",{type:"button",className:"chat-file-change-link",onClick:()=>M(En),title:`预览 ${En}`,"aria-label":`预览改动文件 ${At.path.replace(/\\/g,"/").split("/").pop()}`,children:Cr},At.path):e.jsx("span",{className:"chat-file-change-link chat-file-change-link--static",children:Cr},At.path)})]})})(),y&&(h.sendState||h.isSteered)&&e.jsxs("div",{className:`msg-send-status${h.sendState?` is-${h.sendState}`:""}`,role:"status","aria-label":h.sendState==="pending"?"正在发送":h.sendState==="failed"?"发送失败":"已引导",children:[h.sendState==="pending"&&e.jsxs("span",{className:"msg-send-status__dots","aria-hidden":"true",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),h.sendState==="failed"&&e.jsx("span",{children:"发送失败"}),h.isSteered&&e.jsx("span",{className:"msg-steered-status",title:"已引导","aria-label":"已引导",role:"img",children:e.jsx(fl,{size:13,strokeWidth:2,"aria-hidden":"true"})})]})]}),P.showCompletion&&e.jsxs("div",{className:"msg-completion-footer",children:[e.jsxs("span",{className:"msg-completion-status",children:[e.jsx(Gr,{size:13,strokeWidth:2,"aria-hidden":"true"}),e.jsx("span",{children:"已完成"}),he&&e.jsxs("span",{children:[" · 总耗时 ",he]})]}),e.jsxs("span",{className:"msg-completion-actions",children:[X&&(wo(c,X)||!X.startsWith("runtime:"))&&e.jsx("button",{type:"button",onClick:()=>{Fu(c)},disabled:!!wn||Wt,title:"从此轮 Fork 为新会话","aria-label":"从此轮 Fork 为新会话",className:"ui-icon-button ui-icon-button--small msg-action-button",children:wn===c.id?e.jsx(ot,{size:13,className:"animate-spin","aria-hidden":"true"}):e.jsx(dp,{size:13,strokeWidth:1.8,"aria-hidden":"true"})}),!Vo()&&P.showSpeak&&typeof((vt=window.agentApi)==null?void 0:vt.ttsSpeak)=="function"&&e.jsx("button",{type:"button",onClick:()=>Cu(c.id,c.content),title:Gs===c.id?"停止播报":"语音播报","aria-label":Gs===c.id?"停止播报":"语音播报",className:`ui-icon-button ui-icon-button--small msg-action-button ${Gs===c.id?"is-active":""}`,children:Gs===c.id?e.jsx(vl,{size:12,fill:"currentColor","aria-hidden":"true"}):e.jsx(cd,{size:13,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:()=>{zi(c.content)},title:"复制内容","aria-label":"复制内容",className:"ui-icon-button ui-icon-button--small msg-action-button",children:e.jsx(Ni,{size:13,strokeWidth:1.8,"aria-hidden":"true"})})]})]}),!P.showCompletion&&(P.showCopy||O)&&e.jsxs("div",{className:"msg-actions",style:{display:"flex",alignItems:"center",gap:4},children:[O&&e.jsx("span",{className:"ui-icon-button ui-icon-button--small msg-action-button msg-goal-marker",title:"目标消息","aria-label":"目标消息",role:"img",children:e.jsx(Si,{size:13,strokeWidth:1.9,"aria-hidden":"true"})}),P.showCopy&&e.jsx("button",{type:"button",onClick:()=>{zi(c.content)},title:"复制内容","aria-label":"复制内容",className:"ui-icon-button ui-icon-button--small msg-action-button",children:e.jsx(Ni,{size:13,strokeWidth:1.8,"aria-hidden":"true"})})]}),y&&h.isQueued&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4},children:[e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,color:"var(--text-muted)",padding:"2px 8px",borderRadius:20,background:"var(--bg-deep)",border:"1px solid var(--border-subtle)"},children:[e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("polyline",{points:"12 6 12 12 16 14"})]}),"排队中"]}),Mn&&e.jsxs("button",{onClick:()=>void Va(c.id),disabled:De.has(c.id),title:De.has(c.id)?"正在引导":"将此消息引导到当前对话",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontWeight:600,color:"var(--accent)",padding:"2px 10px",borderRadius:20,border:"1px solid rgba(79,110,247,0.3)",background:"var(--accent-dim)",cursor:De.has(c.id)?"wait":"pointer",opacity:De.has(c.id)?.6:1,transition:"all 0.15s",fontFamily:"var(--font-body)"},onMouseEnter:xe=>{xe.currentTarget.style.background="rgba(79,110,247,0.18)",xe.currentTarget.style.borderColor="var(--accent)"},onMouseLeave:xe=>{xe.currentTarget.style.background="var(--accent-dim)",xe.currentTarget.style.borderColor="rgba(79,110,247,0.3)"},children:[e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M3 12h18M3 6h18M3 18h18"}),e.jsx("path",{d:"M12 3v18",opacity:"0.3"})]}),De.has(c.id)?"引导中":"引导"]})]})]})]})},c.id)}),Cn&&_r&&e.jsx(Bd,{progress:_r,startedAt:Nn}),ur&&e.jsx("div",{className:"chat-message-activity",style:{display:"flex",alignItems:"flex-start",padding:"4px 0 4px",animation:"fadeInUp 0.3s var(--ease-out)"},children:e.jsx(fg,{startedAt:Nn})}),(xs||Gn)&&e.jsxs("div",{style:{padding:12,margin:"8px 0",borderRadius:"var(--radius-sm)",background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.2)",color:"var(--danger)",fontSize:13,animation:"fadeIn 0.2s var(--ease-out)",fontFamily:"var(--font-mono)",display:"flex",alignItems:"center",flexWrap:"wrap",gap:10},children:[e.jsx("span",{style:{flex:1,minWidth:0},children:xs||Gn}),!xs&&Jr===X&&e.jsxs("div",{style:{display:"inline-flex",gap:6,flexShrink:0},children:[e.jsx("button",{type:"button",onClick:go,"aria-label":"再次停止",title:"再次停止",className:"ui-icon-button",children:e.jsx(vl,{size:14,fill:"currentColor","aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:()=>{qa()},"aria-label":"释放会话",title:"释放会话",className:"ui-icon-button",disabled:Zt!=="idle",children:Zt==="releasing"?e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}):e.jsx(ld,{size:14,"aria-hidden":"true"})})]}),xs&&e.jsxs("button",{type:"button",onClick:()=>Xi(c=>c+1),"aria-label":"重新加载会话",title:"重新加载会话",style:{flexShrink:0,minHeight:30,display:"inline-flex",alignItems:"center",gap:5,padding:"5px 9px",border:"1px solid rgba(248,113,113,0.35)",borderRadius:5,background:"var(--bg-workspace)",color:"var(--danger)",cursor:"pointer",fontSize:12},children:[e.jsx(Ns,{size:14,"aria-hidden":"true"}),"重新加载"]})]}),e.jsx("div",{ref:Os})]}),e.jsx(ch,{entries:(to==null?void 0:to.entries)??[],activeMessageId:fu,loadingMessageId:hu,onActivate:c=>{Ha(c)}}),Hs==="anchored"&&e.jsx("button",{type:"button",className:"chat-history-return-latest","data-has-updates":gu,"data-loading-newer":mu,"aria-busy":ro||void 0,"aria-label":"回到最新消息",title:"回到最新消息",disabled:ro,onClick:()=>{$a()},children:ro?e.jsx(ot,{className:"chat-history-return-latest__spinner",size:16,"aria-hidden":"true"}):e.jsx(pl,{size:16,"aria-hidden":"true"})}),Hs!=="anchored"&&xu&&e.jsx("button",{type:"button",className:"chat-jump-to-bottom","aria-label":"回到底部",title:"回到底部",onClick:ju,children:e.jsx(pl,{size:16,"aria-hidden":"true"})})]}),e.jsxs("div",{className:"chat-input-area",style:{padding:"var(--chat-input-padding)",background:"var(--bg-workspace)"},children:[on&&e.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:9,padding:"8px 10px",border:"1px solid var(--border-default)",borderRadius:6,background:"var(--bg-surface)",color:cr==="incompatible"?"var(--danger)":"var(--text-muted)",fontSize:12},children:e.jsx("span",{style:{flex:1},children:cr==="incompatible"?ar||((tl=p==null?void 0:p.compatibility)==null?void 0:tl.reason)||`Codex ${((nl=p==null?void 0:p.compatibility)==null?void 0:nl.producerVersion)??"未知版本"} 与当前 ${((rl=p==null?void 0:p.compatibility)==null?void 0:rl.readerVersion)??"运行时"} 不兼容`:`正在使用 Codex ${((sl=p==null?void 0:p.compatibility)==null?void 0:sl.readerVersion)??"当前版本"} 验证此会话`})}),gs&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:9,padding:"8px 10px",border:"1px solid var(--border-default)",borderRadius:6,background:"var(--bg-surface)",color:"var(--text-muted)",fontSize:12},children:[e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"5",y:"11",width:"14",height:"10",rx:"2"}),e.jsx("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"})]}),e.jsx("span",{style:{flex:1},children:gt!=null&>.forkSessionId?"副本已创建,但消息尚未发送成功。":"此会话仍由原客户端持有,可创建副本继续。"}),gs&&e.jsx("button",{type:"button",onClick:()=>void Bu(),disabled:Wt,style:{flexShrink:0,border:"1px solid var(--border-default)",borderRadius:5,padding:"5px 9px",background:"var(--bg-workspace)",color:"var(--text-primary)",fontSize:12,fontWeight:600,cursor:Wt?"wait":"pointer",opacity:Wt?.65:1},children:Wt?gt!=null&>.forkSessionId?"正在发送…":"正在创建…":gt!=null&>.forkSessionId?"重新发送":"以副本继续"})]}),Nt.length>0&&e.jsxs("div",{style:{marginBottom:10,padding:"8px 12px",borderRadius:10,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",boxShadow:"var(--shadow-sm)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5,marginBottom:6,fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.07em"},children:[e.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("path",{d:"M9 11l3 3L22 4"}),e.jsx("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]}),"任务列表"]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(()=>{const c=new Set(Nt.filter(m=>m.status==="completed").map(m=>m.title.toLowerCase()));return Nt.map(m=>{const h=m.status==="pending",y=m.status==="in-progress",O=m.status==="completed",P=h&&(m.dependsOn??[]).some(he=>!c.has(he.toLowerCase()));return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,opacity:O?.65:1,transition:"opacity 0.3s"},children:[e.jsxs("div",{style:{width:16,height:16,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:O?"rgba(52,211,153,0.15)":y?"var(--accent-dim)":P?"rgba(239,68,68,0.08)":"rgba(0,0,0,0.04)",border:O?"1.5px solid rgba(52,211,153,0.6)":y?"1.5px solid var(--accent)":P?"1.5px solid rgba(239,68,68,0.5)":"1.5px solid var(--border-default)"},children:[O&&e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(52,211,153,0.9)",strokeWidth:"3",strokeLinecap:"round",children:e.jsx("path",{d:"M20 6L9 17l-5-5"})}),y&&e.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:"var(--accent)",animation:"pulse 1.2s ease-in-out infinite"}}),P&&e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(239,68,68,0.8)",strokeWidth:"3",strokeLinecap:"round",children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12"})}),h&&!P&&e.jsx("div",{style:{width:5,height:5,borderRadius:"50%",background:"var(--border-default)"}})]}),e.jsx("span",{style:{fontSize:12,color:O?"var(--text-muted)":P?"rgba(239,68,68,0.8)":"var(--text-primary)",textDecoration:O?"line-through":"none",flex:1},children:m.title}),P&&e.jsx("span",{title:`等待: ${(m.dependsOn??[]).join(", ")}`,style:{fontSize:10,color:"rgba(239,68,68,0.9)",background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)",borderRadius:8,padding:"1px 6px",flexShrink:0},children:"等待前置"}),m.agentName&&e.jsxs("span",{style:{fontSize:10,color:"var(--accent)",background:"var(--accent-dim)",border:"1px solid rgba(79,110,247,0.2)",borderRadius:8,padding:"1px 6px",flexShrink:0},children:["@",m.agentName]})]},m.id)})})()})]}),B.length>0&&e.jsxs("div",{style:{marginBottom:10,borderRadius:10,background:"var(--bg-surface)",border:"1px solid rgba(251,191,36,0.25)",overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 12px",borderBottom:"1px solid rgba(251,191,36,0.15)",background:"rgba(251,191,36,0.06)"},children:[e.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"#d97706",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("polyline",{points:"12 6 12 12 16 14"})]}),e.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#d97706",textTransform:"uppercase",letterSpacing:"0.07em",flex:1},children:"定时任务"}),e.jsx("button",{onClick:async()=>{window.agentApi&&(await window.agentApi.cronDeleteAll(),Y([]),ae({id:crypto.randomUUID(),role:"assistant",content:"✅ 所有定时任务已删除。",timestamp:Date.now()}))},title:"删除全部",style:{background:"none",border:"1px solid rgba(251,191,36,0.35)",borderRadius:6,color:"#d97706",cursor:"pointer",padding:"1px 7px",fontSize:10},children:"全部删除"})]}),B.map(c=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border-subtle)",opacity:c.enabled?1:.7},children:[e.jsx("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:c.enabled?"#22c55e":"#9ca3af",boxShadow:c.enabled?"0 0 5px rgba(34,197,94,0.55)":"none",animation:c.enabled?"pulse 2s ease-in-out infinite":"none"}}),e.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#d97706",background:"rgba(251,191,36,0.12)",border:"1px solid rgba(251,191,36,0.25)",borderRadius:6,padding:"1px 6px",flexShrink:0,fontFamily:"var(--font-mono)"},children:c.cron}),e.jsx("span",{style:{fontSize:12,color:"var(--text-primary)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.label||c.prompt}),e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",fontFamily:"var(--font-mono)",flexShrink:0},children:c.id.slice(0,6)}),e.jsxs("div",{style:{display:"flex",gap:4,flexShrink:0},children:[c.enabled?e.jsx("button",{title:"暂停",onClick:async()=>{if(window.agentApi){await window.agentApi.cronPause(c.id);const m=await window.agentApi.cronList();Y(m)}},style:{background:"none",border:"1px solid var(--border-default)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",padding:"2px 7px",fontSize:11},onMouseEnter:m=>{m.currentTarget.style.borderColor="#d97706",m.currentTarget.style.color="#d97706"},onMouseLeave:m=>{m.currentTarget.style.borderColor="var(--border-default)",m.currentTarget.style.color="var(--text-muted)"},children:"⏸"}):e.jsx("button",{title:"恢复",onClick:async()=>{if(window.agentApi){await window.agentApi.cronResume(c.id);const m=await window.agentApi.cronList();Y(m)}},style:{background:"none",border:"1px solid var(--border-default)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",padding:"2px 7px",fontSize:11},onMouseEnter:m=>{m.currentTarget.style.borderColor="#22c55e",m.currentTarget.style.color="#22c55e"},onMouseLeave:m=>{m.currentTarget.style.borderColor="var(--border-default)",m.currentTarget.style.color="var(--text-muted)"},children:"▶"}),e.jsx("button",{title:"删除",onClick:async()=>{if(window.agentApi){await window.agentApi.cronDelete(c.id);const m=await window.agentApi.cronList();Y(m)}},style:{background:"none",border:"1px solid var(--border-default)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",padding:"2px 7px",fontSize:11},onMouseEnter:m=>{m.currentTarget.style.borderColor="var(--danger)",m.currentTarget.style.color="var(--danger)"},onMouseLeave:m=>{m.currentTarget.style.borderColor="var(--border-default)",m.currentTarget.style.color="var(--text-muted)"},children:"🗑"})]})]},c.id))]}),hi.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:hi.map((c,m)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5,padding:"3px 10px 3px 8px",borderRadius:20,background:"var(--accent-dim)",border:"1px solid rgba(79,110,247,0.18)",fontSize:12,color:"var(--accent)",maxWidth:220},children:[e.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),e.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.name}),e.jsx("button",{onClick:()=>Nu(m),style:{background:"none",border:"none",color:"rgba(79,110,247,0.55)",cursor:"pointer",padding:0,marginLeft:2,fontSize:13,lineHeight:1,display:"flex"},children:"✕"})]},m))}),pr.length>0&&(()=>{const c=ht.find(h=>h.id===_t),m=!it&&(!c||!po(c.modelId));return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:[m&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",borderRadius:8,background:"rgba(234,179,8,0.1)",border:"1px solid rgba(234,179,8,0.4)",color:"rgba(202,138,4,1)",fontSize:12},children:[e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[e.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),e.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),"当前模型(",(c==null?void 0:c.modelId)??"未配置",")不支持图片,发送前请切换到支持视觉的模型(如 claude-3、gpt-4o)"]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:pr.map((h,y)=>e.jsxs("div",{style:{position:"relative",display:"inline-block"},children:[e.jsx("button",{type:"button",className:"chat-message-image-button pending-image-preview-button","aria-label":`预览待发送图片 ${y+1}`,onClick:()=>Dr({src:h,alt:`待发送图片 ${y+1}`}),children:e.jsx("img",{src:h,alt:`待发送图片 ${y+1}`,style:{width:72,height:72,objectFit:"cover",borderRadius:8,border:"1.5px solid var(--border-default)",display:"block"}})}),e.jsx("button",{type:"button","aria-label":`删除待发送图片 ${y+1}`,onClick:()=>Pu(y),style:{position:"absolute",top:-6,right:-6,width:18,height:18,borderRadius:"50%",background:"var(--danger, #e53e3e)",border:"none",color:"#fff",fontSize:11,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,padding:0},children:"✕"})]},y))})]})})(),ee&&(()=>{const c={active:"推进中",paused:"已暂停",blocked:"已受阻",usage_limited:"用量受限",budget_limited:"预算耗尽",complete:"已完成"},m=ee.status!=="active"&&ee.status!=="complete";return e.jsxs("div",{className:`goal-queue thread-goal is-${ee.status}`,"aria-label":"目标模式",children:[e.jsxs("div",{className:"goal-queue__header",children:[e.jsx(Si,{size:14,strokeWidth:1.9,"aria-hidden":"true"}),e.jsx("span",{children:"目标模式"}),e.jsx("span",{className:"goal-queue__count",children:c[ee.status]}),e.jsx("span",{className:"thread-goal__usage",children:ee.tokenBudget!==null?`${ee.tokensUsed}/${ee.tokenBudget} tokens · ${ee.turnCount} 轮`:`${ee.tokensUsed} tokens · ${ee.turnCount} 轮`})]}),e.jsxs("div",{className:"goal-queue__row is-active",children:[e.jsx("span",{className:"goal-queue__objective",title:ee.objective,children:ee.objective}),ee.status==="active"&&e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{co("pause")},title:"暂停目标续跑","aria-label":"暂停目标续跑",children:"⏸"}),m&&e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{co("resume")},title:"恢复目标续跑","aria-label":"恢复目标续跑",children:e.jsx(Mp,{size:12,strokeWidth:2,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{co("clear")},title:"清除目标,停止续跑","aria-label":"清除目标,停止续跑",children:e.jsx(As,{size:12,strokeWidth:2,"aria-hidden":"true"})})]})]})})(),(q.active||q.queued.length>0)&&e.jsxs("div",{className:"goal-queue","aria-label":"目标队列",children:[e.jsxs("div",{className:"goal-queue__header",children:[e.jsx(Si,{size:14,strokeWidth:1.9,"aria-hidden":"true"}),e.jsx("span",{children:"目标"}),e.jsx("span",{className:"goal-queue__count",children:q.queued.length+(q.active?1:0)})]}),q.active&&e.jsxs("div",{className:"goal-queue__row is-active",children:[e.jsx("span",{className:"goal-queue__state",children:"进行中"}),e.jsx("span",{className:"goal-queue__objective",title:q.active.objective,children:q.active.objective}),e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{Ka(q.active.id)},title:"停止当前目标","aria-label":"停止当前目标",children:e.jsx(As,{size:14,strokeWidth:1.8,"aria-hidden":"true"})})]}),q.queued.map((c,m)=>e.jsxs("div",{className:`goal-queue__row is-queued${pi===c.id?" is-dragging":""}`,draggable:!0,onDragStart:()=>hn(c.id),onDragEnd:()=>hn(null),onDragOver:h=>h.preventDefault(),onDrop:()=>{qu(c.id)},children:[e.jsx(gl,{className:"goal-queue__grip",size:14,strokeWidth:1.8,"aria-hidden":"true"}),e.jsxs("span",{className:"goal-queue__state",children:["#",m+1]}),e.jsx("span",{className:"goal-queue__objective",title:c.objective,children:c.objective}),e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{Ka(c.id)},title:"移出目标队列","aria-label":"移出目标队列",children:e.jsx(As,{size:14,strokeWidth:1.8,"aria-hidden":"true"})})]},c.id))]}),(()=>{const c=$.filter(m=>m.isQueued);return c.length===0?null:e.jsx("div",{className:"queued-message-list",children:c.map(m=>{const h=m,y=b===m.id,O=h.content.length>80?h.content.slice(0,80)+"…":h.content;return e.jsxs("div",{className:`queued-message-row${jt===m.id?" is-dragging":""}`,"data-queued-message-id":m.id,onDragOver:P=>{!jt||jt===m.id||(P.preventDefault(),P.dataTransfer.dropEffect="move")},onDrop:P=>{P.preventDefault(),jt&&xo(jt,m.id),zt(null)},children:[e.jsx("button",{type:"button",className:"queued-message-grip",draggable:!y,"aria-label":"拖动调整排队顺序",title:"拖动调整顺序",onDragStart:P=>{zt(m.id),P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",m.id)},onDragEnd:()=>zt(null),onKeyDown:P=>{(P.key==="ArrowUp"||P.key==="ArrowDown")&&(P.preventDefault(),Uu(m.id,P.key==="ArrowUp"?-1:1))},onPointerDown:P=>{P.pointerType==="mouse"||y||($t.current={id:m.id,pointerId:P.pointerId},P.currentTarget.setPointerCapture(P.pointerId),zt(m.id))},onPointerMove:P=>{var oe;const he=$t.current;if(!he||he.pointerId!==P.pointerId)return;P.preventDefault();const Z=(oe=document.elementFromPoint(P.clientX,P.clientY))==null?void 0:oe.closest("[data-queued-message-id]"),Ae=Z==null?void 0:Z.dataset.queuedMessageId;Ae&&Ae!==he.id&&xo(he.id,Ae)},onPointerUp:P=>{var he;((he=$t.current)==null?void 0:he.pointerId)===P.pointerId&&($t.current=null,zt(null))},onPointerCancel:()=>{$t.current=null,zt(null)},children:e.jsx(gl,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsxs("div",{className:"queued-message-content",children:[h.agentName&&e.jsxs("span",{className:"queued-message-agent",children:["@",h.agentName]}),y?e.jsx("input",{autoFocus:!0,className:"queued-message-edit-input",value:D,onChange:P=>re(P.target.value),onKeyDown:P=>{P.key==="Enter"&&!P.nativeEvent.isComposing?(P.preventDefault(),Ga(m.id)):P.key==="Escape"&&(P.preventDefault(),mo())},"aria-label":"编辑排队消息内容"}):e.jsx("span",{className:"queued-message-text",title:h.content,children:O})]}),e.jsxs("div",{className:"queued-message-actions",children:[Mn&&e.jsx("button",{type:"button",className:"queued-message-action queued-message-action--accent",onClick:()=>void Va(m.id),disabled:De.has(m.id),title:De.has(m.id)?"正在引导":"引导到当前对话","aria-label":De.has(m.id)?"正在引导排队消息":"引导排队消息到当前对话",children:De.has(m.id)?e.jsx(ot,{className:"spin",size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(fl,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"queued-message-action",onClick:()=>void $u(m.id),title:ce===m.id?"已复制":"复制","aria-label":"复制排队消息",children:ce===m.id?e.jsx(Gr,{size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(Ni,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"queued-message-action",onClick:()=>y?Ga(m.id):Ou(m.id),disabled:y&&!D.trim(),title:y?"保存":"编辑","aria-label":y?"保存排队消息":"编辑排队消息",children:y?e.jsx(Gr,{size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(ca,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"queued-message-action queued-message-action--danger",onClick:()=>Hu(m.id),title:"删除","aria-label":"删除排队消息",children:e.jsx(As,{size:15,strokeWidth:1.8,"aria-hidden":"true"})})]})]},m.id)})})})(),e.jsx("div",{ref:io,className:"composer-anchor",style:{position:"relative"},children:e.jsx("div",{className:"composer-shell",style:{display:"flex",flexDirection:"column",gap:0,background:"var(--bg-surface)",borderRadius:14,overflow:"visible"},children:e.jsxs("div",{className:"composer-input-row",style:{display:"flex",alignItems:"center",gap:8,padding:"var(--composer-row-padding)"},children:[e.jsx("input",{ref:Ma,type:"file",multiple:!0,style:{display:"none"},onChange:Tu}),qs.length>0&&e.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0,flexWrap:"nowrap",overflow:"hidden",maxWidth:300},children:qs.map(c=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,padding:"2px 7px 2px 6px",borderRadius:20,background:"var(--accent-dim)",border:"1px solid rgba(79,110,247,0.25)",fontSize:12,color:"var(--accent)",flexShrink:0,whiteSpace:"nowrap"},children:[e.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("circle",{cx:"12",cy:"8",r:"4"}),e.jsx("path",{d:"M20 21a8 8 0 1 0-16 0"})]}),"@",c.name,e.jsx("button",{onClick:()=>Ru(c.id),style:{background:"none",border:"none",color:"rgba(79,110,247,0.55)",cursor:"pointer",padding:0,lineHeight:1,fontSize:12,display:"flex"},children:"✕"})]},c.id))}),e.jsx("textarea",{className:"composer-text-input web-native-composer-textarea",ref:Us,rows:3,value:Kt,onChange:c=>Wa(c.target.value),onBlur:()=>setTimeout(()=>{rs(null),is(null)},120),onKeyDown:Au,placeholder:Zt==="released"?"已停止在 AgentRoam 中使用;Codex Desktop 最长约 30 分钟后可用":on?cr==="incompatible"?"Codex 版本不兼容":"正在验证会话兼容性":pn?"原客户端使用中,当前只读":mr?sr?"输入要持续推进的目标":xr?"输入下一条排队消息":"提出后续修改要求":"请先在设置中配置 API Key",disabled:!An}),e.jsxs("div",{className:"web-native-composer-toolbar",children:[e.jsxs("div",{className:"web-native-add-wrap",children:[e.jsx("button",{type:"button",className:"web-native-add-button","aria-label":"添加附件、图片或语音","aria-expanded":Vn,onClick:()=>zn(c=>!c),children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})}),Vn&&e.jsxs("div",{className:"web-native-add-menu",children:[e.jsx("button",{type:"button",onClick:()=>{var c;zn(!1),(c=Ma.current)==null||c.click()},children:"附件 / 图片"}),e.jsx("button",{type:"button",onClick:()=>{zn(!1),Su()},children:"语音输入"})]})]}),e.jsx("button",{type:"button",className:`web-native-runtime-status goal-mode-toggle${sr?" is-active":""}`,"aria-pressed":sr,"aria-label":sr?"关闭目标模式":"开启目标模式",title:sr?"目标模式已开启":"目标模式",onClick:()=>ui(c=>!c),children:e.jsx(Si,{size:18,strokeWidth:1.9,"aria-hidden":"true"})}),e.jsxs("div",{className:"web-native-permission-wrap",ref:Pr,children:[e.jsx("button",{type:"button",className:`web-native-runtime-status web-native-permission-button mode-${Ln}`,"aria-label":`会话权限:${(il=Li.find(c=>c.value===Ln))==null?void 0:il.label}`,"aria-haspopup":"menu","aria-expanded":zr,title:`会话权限:${(ol=Li.find(c=>c.value===Ln))==null?void 0:ol.label}`,disabled:!X||fi,onClick:()=>Lt(c=>!c),children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"}),e.jsx("path",{d:"M12 8v4"}),e.jsx("path",{d:"M12 16h.01"})]})}),zr&&e.jsx("div",{className:"web-native-permission-menu",role:"menu","aria-label":"会话权限模式",children:Li.map(c=>e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":Ln===c.value,className:Ln===c.value?"is-active":"",onClick:()=>{Wu(c.value)},children:[e.jsx("span",{className:"web-native-permission-check","aria-hidden":"true",children:Ln===c.value?"✓":""}),e.jsxs("span",{className:"web-native-permission-copy",children:[e.jsx("strong",{children:c.label}),e.jsx("small",{children:c.description})]})]},c.value))})]}),e.jsx("div",{className:"web-native-context-control",children:e.jsx(pg,{usage:X?W[X]:void 0,contextWindowK:He,compact:!0})}),e.jsx("label",{className:`web-native-model-control${it?" web-native-model-control--native":""}`,title:"切换模型",children:it&&Wi(Ne)?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"web-native-model-agent",title:`${xc[Ne]} 会话`,children:[e.jsx(pa,{agentType:Ne,size:14}),e.jsx("span",{className:"web-native-model-agent-name",children:xc[Ne]})]}),Xr&&e.jsxs("select",{"aria-label":"当前模型",title:"切换模型",value:sn,onChange:c=>{rn({model:c.target.value?jf(c.target.value):void 0})},children:[e.jsx("option",{value:"",children:"默认模型"}),Ne==="opencode"?hr.map(c=>e.jsx("optgroup",{label:c.label,children:c.models.map(m=>{const h=oi(m);return e.jsx("option",{value:h,children:m.optionLabel},h)})},c.key)):pt.map(c=>e.jsx("option",{value:c.key,children:c.label},c.key)),Sn.length>0&&e.jsx("optgroup",{label:"设置里的模型",children:Sn.map(c=>e.jsx("option",{value:c.key,children:c.label},c.key))})]})]}):e.jsx("select",{"aria-label":"当前模型",value:_t,disabled:ht.length===0,onChange:c=>{ln(c.target.value)},children:ht.length===0?e.jsx("option",{value:"",children:"未配置模型"}):ht.map(c=>e.jsx("option",{value:c.id,children:c.name||c.modelId},c.id))})}),Ot?e.jsx("button",{type:"button",onClick:go,className:"web-native-stop-button","aria-label":"停止生成",title:"停止生成",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})}):it&&gr.length>0?e.jsxs("div",{className:"web-native-effort-wrap",ref:Ut,children:[e.jsx("button",{type:"button",className:"web-native-effort-button","aria-expanded":ze,"aria-label":`推理强度:${qt?To[qt]:"默认"}`,title:`推理强度:${qt?To[qt]:"默认"}(点击切换)`,onClick:()=>ge(c=>!c),children:e.jsxs("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M9.5 4.5A3.5 3.5 0 0 0 6 8v1a3 3 0 0 0-2 2.83V14a3 3 0 0 0 3 3h.25A3.75 3.75 0 0 0 11 20.75V3.25A3.75 3.75 0 0 0 9.5 4.5Z"}),e.jsx("path",{d:"M14.5 4.5A3.5 3.5 0 0 1 18 8v1a3 3 0 0 1 2 2.83V14a3 3 0 0 1-3 3h-.25A3.75 3.75 0 0 1 13 20.75V3.25a3.75 3.75 0 0 1 1.5 1.25Z"})]})}),ze&&e.jsxs("div",{className:"web-native-effort-menu",role:"menu","aria-label":"推理强度",children:[e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":!qt,className:qt?void 0:"is-active",onClick:()=>{rn({reasoningEffort:void 0}),ge(!1)},children:[e.jsx("span",{className:"web-native-effort-check","aria-hidden":"true",children:qt?"":"✓"}),"默认"]}),gr.map(c=>e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":qt===c,className:qt===c?"is-active":void 0,onClick:()=>{rn({reasoningEffort:c}),ge(!1)},children:[e.jsx("span",{className:"web-native-effort-check","aria-hidden":"true",children:qt===c?"✓":""}),To[c]]},c))]})]}):it?e.jsxs("span",{className:"web-native-agent-status",role:"status","aria-label":"Agent 空闲",title:"Agent 空闲",children:[e.jsxs("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M9.5 4.5A3.5 3.5 0 0 0 6 8v1a3 3 0 0 0-2 2.83V14a3 3 0 0 0 3 3h.25A3.75 3.75 0 0 0 11 20.75V3.25A3.75 3.75 0 0 0 9.5 4.5Z"}),e.jsx("path",{d:"M14.5 4.5A3.5 3.5 0 0 1 18 8v1a3 3 0 0 1 2 2.83V14a3 3 0 0 1-3 3h-.25A3.75 3.75 0 0 1 13 20.75V3.25a3.75 3.75 0 0 1 1.5 1.25Z"})]}),e.jsx("span",{"aria-hidden":"true"})]}):e.jsxs("div",{className:"web-native-effort-wrap",ref:ms,children:[e.jsx("button",{type:"button",className:"web-native-effort-button","aria-expanded":yr,"aria-label":`推理强度:${mc[Dt]}`,title:`推理强度:${mc[Dt]}(点击切换)`,onClick:()=>Je(c=>!c),children:e.jsxs("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M9.5 4.5A3.5 3.5 0 0 0 6 8v1a3 3 0 0 0-2 2.83V14a3 3 0 0 0 3 3h.25A3.75 3.75 0 0 0 11 20.75V3.25A3.75 3.75 0 0 0 9.5 4.5Z"}),e.jsx("path",{d:"M14.5 4.5A3.5 3.5 0 0 1 18 8v1a3 3 0 0 1 2 2.83V14a3 3 0 0 1-3 3h-.25A3.75 3.75 0 0 1 13 20.75V3.25a3.75 3.75 0 0 1 1.5 1.25Z"})]})}),yr&&e.jsx("div",{className:"web-native-effort-menu",role:"menu","aria-label":"推理强度",children:eu.map(c=>e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":Dt===c.value,className:Dt===c.value?"is-active":void 0,onClick:()=>{$n("reasoningEffort",c.value),cn(),Je(!1)},children:[e.jsx("span",{className:"web-native-effort-check","aria-hidden":"true",children:Dt===c.value?"✓":""}),c.label]},c.value))})]}),e.jsx("button",{type:"button",onClick:Xa,disabled:!An||Bs>0||!Kt.trim(),className:"web-native-send-button","aria-label":xr?"排队发送":"发送",title:xr?"排队发送":"发送",children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M12 19V5M5 12l7-7 7 7"})})})]})]})})}),e.jsxs("div",{className:"chat-composer-hint",style:{textAlign:"center",marginTop:7,fontSize:11,color:"var(--text-muted)",letterSpacing:"0.03em",opacity:.6},children:["Enter 发送",sr?"目标":xr?"(排队)":""," · @智能体(可多选)· /技能 · Shift+Enter 换行",za?" · 🎤 正在聆听…":""]})]}),e.jsx(Gg,{image:Yi,onClose:()=>Dr(null)}),Br&&Vs!==null&&Da.length>0&&On.createPortal(e.jsxs("div",{style:{position:"fixed",bottom:window.innerHeight-Br.top+8,left:Br.left,width:Br.width,background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:10,boxShadow:"var(--shadow-md)",overflow:"hidden",zIndex:99999},children:[e.jsx("div",{style:{padding:"6px 10px 4px",fontSize:10,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em"},children:"智能体"}),Da.map(c=>e.jsxs("button",{onMouseDown:m=>{m.preventDefault(),Iu(c)},style:{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",border:"none",background:"transparent",cursor:"pointer"},onMouseEnter:m=>{m.currentTarget.style.background="var(--accent-dim)"},onMouseLeave:m=>{m.currentTarget.style.background="transparent"},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:600,color:"var(--text-primary)"},children:["@",c.name]}),c.description&&e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:1},children:c.description})]},c.id))]}),document.body),Br&&ss!==null&&uo.length>0&&On.createPortal(e.jsxs("div",{style:{position:"fixed",bottom:window.innerHeight-Br.top+8,left:Br.left,width:Br.width,background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:10,boxShadow:"var(--shadow-md)",zIndex:99999,display:"flex",flexDirection:"column",maxHeight:320},children:[e.jsxs("div",{style:{padding:"6px 10px 4px",fontSize:10,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",flexShrink:0},children:["技能 (",uo.length,")"]}),e.jsx("div",{style:{overflowY:"auto",flex:1},children:uo.map(c=>e.jsxs("button",{onMouseDown:m=>{m.preventDefault(),Eu(c)},style:{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",border:"none",background:"transparent",cursor:"pointer"},onMouseEnter:m=>{m.currentTarget.style.background="var(--accent-dim)"},onMouseLeave:m=>{m.currentTarget.style.background="transparent"},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:600,color:"var(--text-primary)"},children:["/",c.name]}),c.description&&e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.description})]},c.name))})]}),document.body)]})}function No(t,n,r="auto"){const s=t.getBoundingClientRect(),i=n.getBoundingClientRect(),o=t.scrollTop+i.top-s.top-Math.max(0,(t.clientHeight-i.height)/2);t.scrollTo({top:Math.max(0,o),behavior:r})}const Ri=4,Rm=4e6,Em=8,Mm=.12;function Am(t,n,r=Mm){if(n<=0)return[];const s=Array.from({length:n},(u,f)=>{const p=Number(t[f]);return Number.isFinite(p)&&p>0?p:1}),i=s.reduce((u,f)=>u+f,0),l=s.map(u=>u/i).map(u=>Math.max(u,r)),d=l.reduce((u,f)=>u+f,0);return l.map(u=>u/d)}function Tm(t,n,r,s=Em){if(n<=1||t.width<=0||t.height<=0)return t.width<=0||t.height<=0?[]:[{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}];const i=Math.min(n,6),o=s*(i-1),l=t.width-o;if(l<=0)return[];const d=Am(r,i),u=[];let f=t.x;for(let p=0;p<i;p+=1){const x=p===i-1?t.x+t.width-f:Math.floor(l*d[p]);u.push({x:Math.round(f),y:Math.round(t.y),width:Math.round(x),height:Math.round(t.height)}),f+=x+s}return u}function Nm({siteId:t,name:n,onSetup:r}){const s=window.agentApi,[i,o]=a.useState(null),[l,d]=a.useState({connected:!1,tabs:[]}),[u,f]=a.useState(""),[p,v]=a.useState(!1),[x,w]=a.useState(Date.now()),[j,E]=a.useState(!0),S=a.useRef(null),C=!l.paused&&l.compatible!==!1&&l.tabs.some(M=>M.siteId===t);a.useEffect(()=>{let M=!1,H=!1,L=!1;s.hubChromeStatus().then(R=>{!M&&!H&&d(R)}),typeof s.hubChromeConversation!="function"?f("请重启 AI Hub 桌面端以启用消息面板"):s.hubChromeConversation(t).then(R=>{!M&&!L&&o(R)});const T=s.onHubChromeEvent(R=>{R.type==="chrome-conversation"&&R.conversation.siteId===t&&(L=!0,o($=>!$||R.conversation.revision>$.revision?R.conversation:$),f("")),R.type==="chrome-status"&&(H=!0,d(R.status),R.status.tabs.some($=>$.siteId===t)||(o(null),f(""))),R.type==="chrome-page-error"&&R.siteId===t&&f(R.error)}),A=setInterval(()=>w(Date.now()),1e3);return()=>{M=!0,T(),clearInterval(A)}},[s,t]),a.useLayoutEffect(()=>{j&&S.current&&(S.current.scrollTop=S.current.scrollHeight)},[i==null?void 0:i.revision,j]);const k=C&&!!i&&x-i.receivedAt>6e3,z=l.paused?"Chrome 网页连接已暂停,点击下方按钮即可恢复。":l.connected&&l.compatible===!1?"请从「连接 Chrome」加载新版自动连接扩展。":C?i?i.generating?"正在回复…":i.composerAvailable?"已同步 · 从下方输入框发送消息":"未找到输入框,请在 Chrome 检查页面":"正在读取网页对话…":"在日常 Chrome 中打开并登录此站点,扩展会自动接入;若已暂停,请在扩展中恢复自动连接。";return e.jsxs("div",{"data-aihub-native-pane":t,style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",minWidth:0},children:[e.jsx("div",{role:"status",style:{padding:"10px 16px",fontSize:12,lineHeight:1.6,color:"var(--text-secondary)",borderBottom:"1px solid var(--border-subtle)"},children:z}),e.jsx("div",{ref:S,onScroll:()=>{const M=S.current;M&&E(M.scrollHeight-M.scrollTop-M.clientHeight<60)},style:{flex:1,minHeight:0,overflow:"auto",padding:"18px 16px",overflowWrap:"anywhere"},children:C?i!=null&&i.messages.length?i.messages.map(M=>e.jsxs("article",{"data-message-id":M.id,style:{marginBottom:24,padding:M.role==="user"?"12px 14px":"0 2px",borderRadius:12,background:M.role==="user"?"var(--bg-deep)":"transparent"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8,fontSize:12,color:"var(--text-muted)"},children:[e.jsx("strong",{children:M.role==="user"?"你":n}),e.jsx("button",{className:"ui-icon-button ui-icon-button--auto","aria-label":`复制 ${M.role==="user"?"消息":n+" 回复"}`,style:{padding:"2px 5px",fontSize:11},onClick:()=>{navigator.clipboard.writeText(M.content).catch(()=>f("未能复制,请选择文字复制"))},children:"复制"})]}),e.jsx("div",{style:{fontSize:15,lineHeight:1.8,whiteSpace:"pre-wrap",color:"var(--text-primary)"},children:Zd(M.content)})]},`${i.conversationId}:${M.id}`)):e.jsx("p",{style:{margin:"32px 0",color:"var(--text-muted)",fontSize:15,lineHeight:1.8},children:"连接后会显示当前网页对话。可以在下方输入消息,也可以在 Chrome 中继续聊天。"}):e.jsxs("div",{style:{display:"grid",gap:14,paddingTop:36,textAlign:"center",justifyItems:"center"},children:[e.jsx("strong",{style:{fontSize:18},children:l.paused?`${n} 已暂停`:`连接 ${n}`}),e.jsx("span",{style:{fontSize:14,color:"var(--text-secondary)",lineHeight:1.7},children:l.paused?"取消 Chrome 的调试提示也会暂停连接,无需重新登录。":"登录态保留在 Chrome,回复会以文字显示在这里。"}),l.paused&&e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",disabled:p,style:{padding:"8px 12px",color:"var(--accent)"},onClick:async()=>{v(!0),f("");try{d(await s.hubChromeResume())}catch(M){f(M instanceof Error?M.message:"恢复连接失败,请检查 Chrome 扩展")}finally{v(!1)}},children:p?"正在恢复…":"恢复全部 Chrome 连接"}),e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",style:{padding:"8px 12px"},onClick:()=>{s.hubOpenChrome(t).catch(()=>f("无法打开 Chrome,请检查是否已安装"))},children:"登录 / 打开原网页"}),e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",style:{padding:"8px 12px"},onClick:r,children:"连接设置"})]})}),!j&&e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",style:{alignSelf:"center",padding:"7px 12px",margin:8},onClick:()=>E(!0),children:"回到最新回复 ↓"}),(u||k)&&e.jsx("div",{role:u?"alert":"status",title:u||"暂未收到网页更新,请检查 Chrome 标签页或扩展连接;不代表 AI 已停止回答",style:{padding:"6px 16px",fontSize:12,lineHeight:1.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",color:u?"var(--danger)":"var(--text-muted)"},children:u||"同步暂未更新"})]})}function _m({onClose:t}){const n=window.agentApi,[r,s]=a.useState(""),[i,o]=a.useState(!1),[l,d]=a.useState(""),[u,f]=a.useState(!1);a.useEffect(()=>{let v=!0;n.hubChromeStatus().then(w=>{v&&f(w.connected&&w.compatible!==!1)}).catch(()=>{v&&s("暂时无法检测插件连接,请稍后重试")});const x=n.onHubChromeEvent(w=>{w.type==="chrome-status"&&f(w.status.connected&&w.status.compatible!==!1)});return()=>{v=!1,x()}},[n]);const p=async()=>{o(!0),s("");try{const v=await n.hubChromeInstallExtension();d(v.path),s(v.browserOpened?"已打开 Chrome 扩展管理页,插件目录路径已复制。":"未能打开 Chrome。请先安装或打开 Google Chrome,再进入 chrome://extensions;插件目录路径已复制。")}catch{s("未能准备插件,请确认桌面端已启动,稍后重试。")}finally{o(!1)}};return e.jsxs("div",{"data-aihub-chrome-setup":"",style:{flexShrink:0,padding:"12px 18px",background:"var(--bg-elevated)",borderBottom:"1px solid var(--border-subtle)",fontSize:12},children:[e.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",marginBottom:8},children:[e.jsx("strong",{children:"连接日常 Google Chrome"}),e.jsx("span",{role:"status",children:u?"扩展已连接":"等待扩展连接"}),e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",style:{marginLeft:"auto"},onClick:t,children:"收起"})]}),e.jsx("p",{style:{margin:"0 0 8px",lineHeight:1.7},children:"插件已随桌面端附带,无需另行下载。首次加载需要在 Chrome 中确认;加载后自动连接,连接成功后此引导会自动收起。已安装时刷新 AI Hub 扩展即可更新。"}),e.jsxs("ol",{style:{margin:0,paddingLeft:20,lineHeight:1.9},children:[e.jsx("li",{children:"点击「安装浏览器插件」,在打开的 Chrome 扩展管理页开启「开发者模式」。"}),e.jsx("li",{children:"选择「加载已解压的扩展程序」,选中 ai-hub-chrome-extension 文件夹。macOS 文件选择窗口可按 ⌘⇧G,粘贴已复制的路径并打开。"}),e.jsx("li",{children:"在同一个 Chrome 中完成网站登录,即可回到 AI Hub 查看回复并同步发送。取消 Chrome 顶部的调试提示会暂停连接;在 AI Hub 点击「恢复全部 Chrome 连接」即可继续。"})]}),e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",marginTop:8},children:[e.jsx("button",{type:"button",disabled:i,className:"ui-icon-button ui-icon-button--auto",onClick:()=>void p(),style:{padding:"5px 10px"},children:i?"正在打开…":"安装浏览器插件"}),e.jsx("button",{type:"button",className:"ui-icon-button ui-icon-button--auto",onClick:()=>{n.hubChromeRevealExtension().catch(()=>s("未能打开扩展目录"))},style:{padding:"5px 10px"},children:"打开插件文件夹"}),r&&e.jsx("span",{role:"status",children:r})]}),l&&e.jsxs("p",{style:{margin:"8px 0 0",overflowWrap:"anywhere",userSelect:"text"},children:["插件目录:",l]})]})}const zm=["chatgpt","gemini","grok"];function Ei(t){return zm.includes(t)}const Lm=52,_o=30,Pm=4;function Dm(t,n){return t.includes(n)?t.length>1?t.filter(r=>r!==n):t:t.length<Pm?[...t,n]:t}function Wm(t){return(t.trim()[0]||"?").toUpperCase()}function yc(t){try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function Fm({onExit:t,conversationId:n}){const r=typeof window<"u"?window.agentApi:void 0,s=typeof(r==null?void 0:r.hubGetConfig)=="function",[i,o]=a.useState([]),[l,d]=a.useState([]),[u,f]=a.useState([]),[p,v]=a.useState(null),[x,w]=a.useState({}),[j,E]=a.useState({}),[S,C]=a.useState({}),[k,z]=a.useState(""),[M,H]=a.useState([]),[L,T]=a.useState(""),[A,R]=a.useState(!1),$=a.useRef(null),F=a.useRef(null),[Ee,Ke]=a.useState(!1),[ae,ke]=a.useState([]),[Pe,Ie]=a.useState(!1),[We,at]=a.useState(!1),[qe,ne]=a.useState(""),[be,Ye]=a.useState(""),[W,te]=a.useState(!1),[G,le]=a.useState([]);a.useEffect(()=>{if(!(r!=null&&r.hubChromeStatus))return;let B=!1,Y=!1;const q=ee=>{if(B)return;const Ve=ee.connected&&ee.compatible!==!1;le(Ve?ee.tabs.map(ut=>ut.siteId):[]),Ve?te(!1):Y||te(!0),Y=!0};r.hubChromeStatus().then(q).catch(()=>{!B&&!Y&&(Y=!0,te(!0))});const se=r.onHubChromeEvent(ee=>{ee.type==="chrome-status"&&q(ee.status)});return()=>{B=!0,se()}},[r]);const pe=a.useRef(null),ye=a.useRef(null);a.useRef(0),a.useLayoutEffect(()=>{const B=F.current;B&&(B.style.height="32px",k&&(B.style.height=`${Math.max(32,Math.min(B.scrollHeight,120))}px`))},[k,l.length]);const we=async B=>{if(!(Ee||A)){R(!0),T("");try{if(B.length+M.length>Ri)throw new Error(`最多添加 ${Ri} 张图片`);const Y=await Promise.all(B.map(async q=>{if(!/^image\/(png|jpeg|webp)$/.test(q.type))throw new Error("请选择 PNG、JPEG 或 WebP 图片");if(q.size*4/3+32>Rm)throw new Error("单张图片不能超过约 3 MB");return new Promise((se,ee)=>{const Ve=new FileReader;Ve.onload=()=>se(String(Ve.result)),Ve.onerror=()=>ee(new Error("图片读取失败,请重试")),Ve.readAsDataURL(q)})}));H(q=>[...q,...Y].slice(0,Ri))}catch(Y){T(Y instanceof Error?Y.message:"图片读取失败")}finally{R(!1)}}},Te=a.useMemo(()=>p?Tm(p,l.length,u):[],[p,l.length,u]);a.useEffect(()=>{if(!s||Te.length===0)return;const B=l.map((Y,q)=>{const se=Te[q];return{siteId:Y,...n?{conversationId:n}:{},x:se.x,y:se.y+_o,width:se.width,height:Math.max(se.height-_o,0)}});r==null||r.hubSetBounds(B)},[s,r,Te,l,n]),a.useEffect(()=>{if(s)for(const B of l)r==null||r.hubOpenSite(B,n??void 0)},[s,r,l,n]),a.useEffect(()=>{if(!s)return;const B=pe.current;if(!B)return;const Y=()=>{const ee=B.getBoundingClientRect();v(Ve=>Ve&&Math.abs(Ve.x-ee.x)<.5&&Math.abs(Ve.y-ee.y)<.5&&Math.abs(Ve.width-ee.width)<.5&&Math.abs(Ve.height-ee.height)<.5?Ve:{x:ee.x,y:ee.y,width:ee.width,height:ee.height})},q={current:0},se=new ResizeObserver(()=>{cancelAnimationFrame(q.current),q.current=requestAnimationFrame(Y)});return se.observe(B),Y(),()=>{se.disconnect(),cancelAnimationFrame(q.current)}},[s,We]),a.useEffect(()=>{if(!Pe)return;const B=q=>{var se;(se=ye.current)!=null&&se.contains(q.target)||Ie(!1)},Y=()=>Ie(!1);return document.addEventListener("pointerdown",B),window.addEventListener("blur",Y),()=>{document.removeEventListener("pointerdown",B),window.removeEventListener("blur",Y)}},[Pe]),a.useEffect(()=>{if(!s||!r)return;let B=!1;r.hubGetConfig().then(q=>{B||(o(q.sites),d(se=>se.length>0?se:q.sites.slice(0,1).map(ee=>ee.id)))});const Y=r.onHubEvent(q=>{q.type==="load-failed"?(w(se=>({...se,[q.siteId]:q.errorCode??-1})),E(se=>({...se,[q.siteId]:!1}))):q.type==="loaded"?(w(se=>{if(!(q.siteId in se))return se;const ee={...se};return delete ee[q.siteId],ee}),E(se=>({...se,[q.siteId]:!1}))):q.type==="loading"?(E(se=>({...se,[q.siteId]:!0})),C(se=>{if(!(q.siteId in se))return se;const ee={...se};return delete ee[q.siteId],ee})):q.type==="google-auth-external"&&C(se=>({...se,[q.siteId]:!0}))});return()=>{B=!0,Y(),r.hubHideAll()}},[s,r]),a.useEffect(()=>{const B=Math.max(l.length,0);f(Y=>Y.length===B?Y:Array.from({length:B},()=>B>0?1/B:0))},[l.length]);const dt=a.useCallback(B=>{d(Y=>Dm(Y,B))},[]),lt=a.useCallback(B=>{w(Y=>{const q={...Y};return delete q[B],q}),r==null||r.hubReload(B,n??void 0),r==null||r.hubOpenSite(B,n??void 0)},[r,n]),st=a.useCallback(B=>{l.length<=1||(r==null||r.hubCloseSite(B,n??void 0),d(Y=>Y.filter(q=>q!==B)))},[r,l.length,n]),Tt=a.useCallback(async()=>{const B=k.trim();if(!(!B&&M.length===0||!r||Ee||A||l.length===0)){Ke(!0);try{const Y=await r.hubBroadcast(B,l,M),q=Y.map(se=>({...se,at:Date.now()}));ke(q),Y.length>0&&Y.every(se=>se.ok)&&(z(""),H([]),T("")),setTimeout(()=>{ke(se=>se.filter(ee=>!ee.ok||Date.now()-ee.at<8e3))},8200)}catch(Y){T(Y instanceof Error?Y.message:"发送失败,请重试")}finally{Ke(!1)}}},[r,k,M,A,Ee,l]),$e=a.useCallback(async()=>{if(!r||!yc(be))return;const B=be.trim(),Y=qe.trim()||new URL(B).hostname,q={id:`custom-${Math.random().toString(36).slice(2,10)}`,name:Y,url:B,adapter:"generic"},se=await r.hubSetConfig({version:1,sites:[...i,q]});o(se.sites),ne(""),Ye(""),at(!1)},[r,qe,be,i]),Nt=a.useCallback(async B=>{if(!r||i.length<=1)return;r.hubCloseSite(B,n??void 0);const Y=await r.hubSetConfig({version:1,sites:i.filter(q=>q.id!==B)});o(Y.sites),d(q=>{const se=q.filter(ee=>ee!==B);return se.length>0?se:Y.sites.slice(0,1).map(ee=>ee.id)})},[r,i,n]),ct=a.useCallback((B,Y)=>{Y.preventDefault();const q=Te.length,se=q>1?8:0,ee=((p==null?void 0:p.width)??0)-se*(q-1);if(ee<=0)return;const Ve=Y.clientX,ut=[...u],nn=Te[B].width,et=ut[B]+ut[B+1],Ge=rt=>{const Pt=rt.clientX-Ve,ht=80,_t=et*ee,ln=Math.min(Math.max(nn+Pt,ht),_t-ht),vn=[...ut];vn[B]=ln/ee,vn[B+1]=(_t-ln)/ee,f(vn)},Gt=()=>{window.removeEventListener("pointermove",Ge),window.removeEventListener("pointerup",Gt)};window.addEventListener("pointermove",Ge),window.addEventListener("pointerup",Gt)},[u,Te,p]);return s?e.jsxs("div",{style:{position:"absolute",inset:0,zIndex:30,display:"flex",flexDirection:"column",background:"var(--bg-workspace)"},children:[e.jsxs("div",{className:"aihub-topbar",style:{height:Lm,display:"flex",alignItems:"center",gap:10,padding:"0 14px",borderBottom:"1px solid var(--border-subtle)",WebkitAppRegion:"drag"},children:[e.jsx("button",{type:"button",onClick:t,title:"返回会话列表","aria-label":"返回会话列表",className:"ui-icon-button",style:{WebkitAppRegion:"no-drag",width:34,height:34,flexShrink:0},children:e.jsx(oa,{size:18,"aria-hidden":"true"})}),e.jsx("strong",{style:{fontSize:14,color:"var(--text-secondary)"},children:"AI Hub"}),e.jsx("button",{type:"button",className:"ui-icon-button ui-icon-button--auto",onClick:()=>te(B=>!B),style:{WebkitAppRegion:"no-drag",marginLeft:"auto",padding:"5px 10px"},children:"连接 Chrome"})]}),W&&e.jsx(_m,{onClose:()=>te(!1)}),e.jsxs("div",{ref:pe,style:{flex:1,position:"relative",overflow:"hidden",minHeight:0},children:[Te.map((B,Y)=>{const q=l[Y],se=i.find(Ve=>Ve.id===q),ee=q in x;return e.jsxs("div",{"data-aihub-pane":q,style:{position:"absolute",left:B.x-((p==null?void 0:p.x)??0),top:B.y-((p==null?void 0:p.y)??0),width:B.width,height:B.height,display:"flex",flexDirection:"column",borderRight:Y<Te.length-1?"1px solid var(--border-subtle)":void 0},children:[e.jsxs("div",{style:{height:_o,display:"flex",alignItems:"center",gap:6,padding:"0 8px",borderBottom:"1px solid var(--border-subtle)",fontSize:12,color:"var(--text-secondary)"},children:[e.jsx("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:"50%",background:Ei(q)?G.includes(q)?"var(--success)":"var(--text-muted)":ee?"#f7768e":j[q]?"var(--accent-glow)":"#9ece6a",flexShrink:0}}),e.jsx("span",{style:{flex:1,minWidth:40,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:(se==null?void 0:se.name)??q}),S[q]&&e.jsx("span",{title:"Google 登录已在系统浏览器打开,登录状态不会同步回 AI Hub。如需继续内嵌使用,请选择邮箱登录。","aria-label":"Google 登录受限",style:{flexShrink:0,fontSize:10,padding:"1px 6px",borderRadius:999,color:"#f7768e",border:"1px solid currentColor",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:180},children:"Google 登录已转至浏览器,内嵌请用邮箱"}),Ei(q)&&e.jsx("button",{type:"button","aria-label":`打开 ${(se==null?void 0:se.name)??q} Chrome 页面`,title:"在日常 Chrome 中登录或查看页面",className:"ui-icon-button ui-icon-button--auto",onClick:()=>{r.hubOpenChrome(q).catch(()=>te(!0))},style:{padding:"2px 6px",fontSize:11},children:"Chrome ↗"}),e.jsx("button",{type:"button",title:"刷新","aria-label":`刷新 ${(se==null?void 0:se.name)??q}`,onClick:()=>lt(q),className:"ui-icon-button",style:{padding:2},children:"⟳"}),l.length>1&&e.jsx("button",{type:"button",title:"关闭页面","aria-label":`关闭 ${(se==null?void 0:se.name)??q}`,onClick:()=>st(q),className:"ui-icon-button",style:{padding:2},children:"×"})]}),e.jsxs("div",{style:{flex:1,position:"relative",background:"var(--bg-surface)"},children:[Ei(q)&&e.jsx(Nm,{siteId:q,name:(se==null?void 0:se.name)??q,onSetup:()=>te(!0)}),!Ei(q)&&ee&&e.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:e.jsxs("div",{style:{textAlign:"center",display:"grid",gap:10,color:"var(--text-muted)",fontSize:12},children:[e.jsxs("span",{children:["页面加载失败(",x[q],")"]}),e.jsx("button",{type:"button",onClick:()=>lt(q),className:"ui-icon-button ui-icon-button--auto",style:{justifySelf:"center",padding:"5px 12px"},children:"重试"})]})})]}),Y<Te.length-1&&e.jsx("div",{"data-aihub-divider":Y,onPointerDown:Ve=>ct(Y,Ve),title:"拖动调整宽度",style:{position:"absolute",top:0,bottom:0,right:-5,width:10,cursor:"col-resize",zIndex:5}})]},q)}),Te.length===0&&e.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",color:"var(--text-muted)",fontSize:13},children:"从输入框选择一个 AI 站点"})]}),e.jsxs("div",{style:{borderTop:"1px solid var(--border-subtle)",padding:"8px 12px 10px",display:"flex",flexDirection:"column",gap:8,background:"var(--bg-surface)"},children:[e.jsxs("div",{ref:ye,style:{position:"relative",display:"flex",flexDirection:"column",gap:8},children:[Pe&&e.jsxs("div",{role:"listbox","aria-label":"选择要发送的 AI 站点","data-aihub-site-picker":"",style:{width:"min(320px, 100%)",maxHeight:280,overflowY:"auto",padding:4,border:"1px solid var(--border-default)",borderRadius:8,background:"var(--bg-workspace)",boxShadow:"0 -8px 24px rgba(0, 0, 0, 0.12)"},children:[i.map(B=>{const Y=l.includes(B.id),q=B.id.startsWith("custom-");return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[e.jsxs("button",{type:"button",role:"option","aria-selected":Y,onClick:()=>dt(B.id),style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8,padding:"8px 9px",border:0,borderRadius:6,background:Y?"var(--bg-glass)":"transparent",color:"var(--text-secondary)",cursor:"pointer",textAlign:"left"},children:[e.jsx("span",{"aria-hidden":"true",style:{width:20,height:20,display:"grid",placeItems:"center",borderRadius:"50%",border:`1px solid ${Y?"var(--accent)":"var(--border-default)"}`,background:Y?"var(--accent)":"transparent",color:Y?"var(--bg-workspace)":"transparent",flexShrink:0},children:e.jsx(Gr,{size:13,strokeWidth:2.5})}),e.jsx("span",{"aria-hidden":"true",style:{width:24,height:24,display:"grid",placeItems:"center",borderRadius:6,background:"var(--accent-glow)",fontSize:12,fontWeight:600,flexShrink:0},children:Wm(B.name)}),e.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:B.name})]}),q&&e.jsx("button",{type:"button",title:`删除站点 ${B.name}`,"aria-label":`删除站点 ${B.name}`,onClick:()=>void Nt(B.id),className:"ui-icon-button",style:{width:30,height:30,padding:0,flexShrink:0},children:e.jsx(As,{size:14,"aria-hidden":"true"})})]},B.id)}),e.jsx("div",{style:{height:1,margin:"4px 6px",background:"var(--border-subtle)"}}),We?e.jsxs("div",{style:{display:"grid",gap:6,padding:6},children:[e.jsx("input",{value:qe,onChange:B=>ne(B.target.value),placeholder:"名称(可选)",style:{minWidth:0,padding:"7px 8px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-secondary)",fontSize:12}}),e.jsx("input",{value:be,onChange:B=>Ye(B.target.value),placeholder:"https://...",style:{minWidth:0,padding:"7px 8px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-secondary)",fontSize:12}}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{type:"button",onClick:()=>void $e(),disabled:!yc(be),className:"ui-icon-button ui-icon-button--auto",style:{padding:"5px 10px",fontSize:12},children:"添加"}),e.jsx("button",{type:"button",onClick:()=>at(!1),className:"ui-icon-button ui-icon-button--auto",style:{padding:"5px 10px",fontSize:12},children:"取消"})]})]}):e.jsxs("button",{type:"button",onClick:()=>at(!0),className:"ui-icon-button ui-icon-button--auto",style:{width:"100%",justifyContent:"flex-start",gap:7,padding:"7px 9px",fontSize:12},children:[e.jsx(Ko,{size:14,"aria-hidden":"true"}),"添加站点"]})]}),e.jsxs("div",{"data-aihub-composer":"",style:{display:"flex",alignItems:"center",gap:8,minHeight:48,padding:"6px 8px",borderRadius:8,border:"1px solid var(--border-default)",background:"var(--bg-workspace)"},children:[e.jsxs("button",{type:"button",onClick:()=>Ie(B=>!B),"aria-haspopup":"listbox","aria-expanded":Pe,"aria-label":"选择 AI 站点",title:"选择 AI 站点",className:"ui-icon-button ui-icon-button--auto",style:{height:34,gap:5,padding:"0 10px",fontSize:12,whiteSpace:"nowrap",flexShrink:0},children:[l.length," 个 AI",e.jsx(Pi,{size:14,"aria-hidden":"true",style:{transform:Pe?"rotate(180deg)":void 0}})]}),e.jsx("input",{ref:$,type:"file",accept:"image/png,image/jpeg,image/webp",multiple:!0,hidden:!0,onChange:B=>{const Y=Array.from(B.target.files??[]);B.target.value="",we(Y)}}),e.jsx("button",{type:"button","aria-label":"添加图片附件",title:"添加图片附件(也可粘贴截图)",disabled:Ee||A||M.length>=Ri,onClick:()=>{var B;return(B=$.current)==null?void 0:B.click()},className:"ui-icon-button",style:{width:34,height:34,padding:0,flexShrink:0},children:e.jsx(Ip,{size:17,"aria-hidden":"true"})}),e.jsx("textarea",{ref:F,"aria-label":"发送给选中的 AI",disabled:Ee,value:k,onChange:B=>z(B.target.value),onPaste:B=>{const Y=Array.from(B.clipboardData.files);Y.length!==0&&(B.preventDefault(),we(Y))},onKeyDown:B=>{B.nativeEvent.isComposing||B.nativeEvent.keyCode===229||(B.key==="Enter"&&(!B.shiftKey||B.metaKey||B.ctrlKey)?(B.preventDefault(),Tt()):B.key==="Escape"&&Pe&&(B.preventDefault(),Ie(!1)))},rows:1,placeholder:`一次输入,发到 ${l.length} 个选中的 AI(Enter 发送,Shift+Enter 换行)`,style:{flex:1,minWidth:0,height:32,minHeight:32,maxHeight:120,boxSizing:"border-box",resize:"none",padding:"4px 2px",border:0,outline:"none",boxShadow:"none",background:"transparent",color:"var(--text-primary)",fontSize:13,lineHeight:1.5,textAlign:k?"left":"center"}}),e.jsx("button",{type:"button",onClick:()=>void Tt(),disabled:!k.trim()&&M.length===0||Ee||A||l.length===0,title:"同步发送(Enter)","aria-label":"同步发送",className:"ui-icon-button",style:{width:36,height:36,padding:0,borderRadius:"50%",background:(k.trim()||M.length>0)&&!Ee?"var(--accent)":"var(--bg-glass)",color:(k.trim()||M.length>0)&&!Ee?"var(--bg-workspace)":"var(--text-muted)",flexShrink:0},children:e.jsx(Np,{size:16,"aria-hidden":"true"})})]})]}),M.length>0&&e.jsx("div",{"aria-label":"待发送图片",style:{display:"flex",gap:8,flexWrap:"wrap"},children:M.map((B,Y)=>e.jsxs("div",{style:{position:"relative",width:56,height:56},children:[e.jsx("img",{src:B,alt:`附件 ${Y+1}`,style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:6}}),e.jsx("button",{type:"button","aria-label":`移除附件 ${Y+1}`,disabled:Ee,onClick:()=>H(q=>q.filter((se,ee)=>ee!==Y)),className:"ui-icon-button",style:{position:"absolute",top:0,right:0,padding:2,background:"var(--bg-workspace)"},children:e.jsx(Tr,{size:12})})]},`${Y}-${B.length}`))}),L&&e.jsx("div",{role:"alert",style:{fontSize:12,color:"var(--text-secondary)",textAlign:"center"},children:L}),ae.length>0&&e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center",minHeight:18},children:ae.map(B=>{var Y;return e.jsx("span",{role:"status",style:{fontSize:11,padding:"3px 10px",borderRadius:999,color:B.ok?"#9ece6a":"#f7768e",background:"var(--bg-glass)",whiteSpace:"normal",overflowWrap:"anywhere"},children:(((Y=i.find(q=>q.id===B.siteId))==null?void 0:Y.name)??B.siteId)+(B.ok?" ✓":` ✕ ${B.reason??"失败"}`)},B.siteId)})})]})]}):e.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",background:"var(--bg-workspace)",zIndex:30},children:e.jsxs("div",{style:{textAlign:"center",color:"var(--text-muted)",fontSize:13,display:"grid",gap:12},children:[e.jsx("span",{children:"AI Hub 仅在桌面端可用"}),e.jsx("button",{type:"button",onClick:t,className:"ui-icon-button ui-icon-button--auto",style:{justifySelf:"center",padding:"6px 14px"},children:"返回"})]})})}const tu=new Set(["downloading","installing","reconnecting"]),Bm=new Set(["checking",...tu]),Om=6e3,$m=24e3;function Hm(){const[t,n]=a.useState(null),[r,s]=a.useState(()=>sessionStorage.getItem("agentroam.dismissed-update"));if(a.useEffect(()=>{var j;let p=!0;const v=window.agentApi,x=((j=v.onUpdateStatus)==null?void 0:j.call(v,E=>{p&&n(E)}))??(()=>{});v.getUpdateStatus().then(E=>{p&&n(E)}).catch(()=>{});const w=window.setTimeout(()=>{v.checkForUpdate().then(E=>{p&&n(E)}).catch(()=>{})},Om+Math.floor(Math.random()*($m+1)));return()=>{p=!1,window.clearTimeout(w),x()}},[]),a.useEffect(()=>{if(!t||!Bm.has(t.phase))return;const p=window.setInterval(()=>{window.agentApi.getUpdateStatus().then(n).catch(()=>{})},1500);return()=>window.clearInterval(p)},[t==null?void 0:t.phase]),!t||["idle","checking","up-to-date","unavailable"].includes(t.phase)||t.phase==="available"&&t.targetVersion===r)return null;const i=tu.has(t.phase),o=t.phase==="failed",l=t.phase==="complete",d=i?t.phase==="downloading"?`正在下载${t.progress!==void 0?` ${t.progress}%`:""}`:t.phase==="installing"?"正在安装":"正在重连":o?"更新失败,重试":l?t.message??"更新已就绪":`发现 AgentRoam ${t.targetVersion}`,u=async()=>{try{n(await window.agentApi.installUpdate())}catch(p){n({...t,phase:"failed",message:p instanceof Error?p.message:"更新失败"})}},f=()=>{t.targetVersion&&(sessionStorage.setItem("agentroam.dismissed-update",t.targetVersion),s(t.targetVersion))};return e.jsxs("aside",{className:`update-notice${o?" update-notice--failed":""}`,"aria-live":"polite",children:[e.jsxs("div",{className:"update-notice__content",children:[e.jsx("strong",{children:d}),!i&&!l&&e.jsx("span",{children:"点击后才会下载安装文件"}),o&&t.message&&e.jsx("span",{children:t.message})]}),!i&&!l&&e.jsxs("button",{className:"update-notice__action",type:"button",onClick:()=>void u(),title:o?"重试更新":"下载更新",children:[o?e.jsx(Ns,{size:16}):e.jsx(la,{size:16}),e.jsx("span",{children:o?"重试":"更新"})]}),!i&&e.jsx("button",{className:"update-notice__close",type:"button",onClick:f,title:"关闭更新提醒","aria-label":"关闭更新提醒",children:e.jsx(Tr,{size:16})})]})}function Um(){const[t,n]=a.useState(null);a.useEffect(()=>{const o=window.agentApi;if(!(o!=null&&o.desktopLiveGetStatus)||!(o!=null&&o.onDesktopLiveStatus))return;let l=!0;o.desktopLiveGetStatus().then(u=>{l&&n(u)}).catch(()=>{});const d=o.onDesktopLiveStatus(u=>n(u));return()=>{l=!1,d()}},[]);const r=t==null?void 0:t.controlState;if(!((t==null?void 0:t.enabled)&&r!==null&&r!==void 0&&r!=="agent-controlled"))return null;const i=r==="return-requested"||r==="resyncing";return e.jsxs("div",{className:"desktop-live-control-banner",role:"status",style:{position:"fixed",top:"calc(env(safe-area-inset-top) + 10px)",left:"50%",transform:"translateX(-50%)",zIndex:1300,display:"flex",alignItems:"center",gap:8,padding:"7px 14px",borderRadius:999,border:"1px solid rgba(251,191,36,0.45)",background:"rgba(69,49,10,0.92)",color:"#fcd34d",fontSize:13,fontWeight:600,backdropFilter:"blur(8px)",pointerEvents:"none"},children:[e.jsx("span",{"aria-hidden":"true",children:"●"}),i?"正在结束远程控制":"正在被远程控制"]})}function zo(t){return t==="idle"?"completed":t}const Lo={"needs-input":"需要输入",running:"运行中",completed:"执行完成",stale:"状态待刷新",error:"执行错误"};function Sa(t,n){return t.map((r,s)=>({session:r,index:s})).sort((r,s)=>n(r.session,s.session)||r.index-s.index).map(({session:r})=>r)}function qm(t){return Sa(t,(n,r)=>r.created.localeCompare(n.created))}function na(t,n){return n==="codex"?[...t]:qm(t)}function vc(t,n){return Sa(t,(r,s)=>Number(n(s))-Number(n(r)))}function Vm(t,n){return Sa(t,(r,s)=>Number(n(s))-Number(n(r)))}const Po={projectId:null,sessionId:null};function ra(t){return typeof t=="string"&&t.trim()?t.trim():null}function wc(t){return{projectId:ra(t),sessionId:null}}function Do(t,n){return{projectId:ra(t),sessionId:ra(n)}}function Gm(t){return t.agentType==="customer-agent"?`确定永久删除会话“${t.title}”吗?此操作不可恢复。`:t.agentType==="codex"?`确定归档 Codex 会话“${t.title}”并从 AgentRoam 中移除吗?可在 Codex 的已归档会话中恢复。`:`确定从 AgentRoam 中移除会话“${t.title}”吗?原生客户端中的历史记录会保留。`}function Km(t,n){const r=new Set(n);return{...t,selectedSessionId:t.selectedSessionId&&r.has(t.selectedSessionId)?null:t.selectedSessionId,sessions:Object.fromEntries(Object.entries(t.sessions).map(([s,i])=>[s,{...i,data:i.data.filter(o=>!r.has(o.id))}]))}}function Qm(t,n){const r=new Set(n);let s=!1;const i=Object.fromEntries(Object.entries(t).map(([o,l])=>{const d=l.filter(u=>!r.has(u.id));return d.length!==l.length&&(s=!0),[o,d.length===l.length?l:d]}));return s?i:t}function Xm(t,n,r,s){const i=[s,...(n[s]??[]).map(d=>d.id)],o=new Set(i),l=Object.fromEntries(Object.entries(n).flatMap(([d,u])=>{if(o.has(d))return[];const f=u.filter(p=>!o.has(p.id));return[[d,f.length===u.length?u:f]]}));return{sessionsByProject:Qm(t,i),childSessionsByParent:l,otherLocalSessions:r.filter(d=>!o.has(d.id)),removedIds:i}}function Ym(t){if(!t.trim())return null;const n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null}function nu({message:t,type:n}){return t?On.createPortal(e.jsxs("div",{className:`app-action-notice is-${n}`,role:n==="error"?"alert":"status","aria-live":n==="error"?"assertive":"polite",children:[e.jsx("span",{className:"app-action-notice-mark","aria-hidden":"true",children:n==="success"?"✓":n==="info"?"i":"!"}),e.jsx("span",{children:t})]}),document.body):null}const Jm=()=>({id:"",name:"",enabled:!0,allowedTools:[],filesystem:{readRoots:[],writeRoots:[],followSymlinks:!1},commands:{mode:"deny",programs:[],inheritedEnvironment:[]},network:"deny",limits:{timeoutMs:12e4,maxOutputBytes:1048576}});function Zm({onNotice:t}){const[n,r]=a.useState([]),[s,i]=a.useState([]),[o,l]=a.useState(null),[d,u]=a.useState(!1),f=a.useMemo(()=>[...s].sort(),[s]),p=async()=>{var j;if(!((j=window.agentApi)!=null&&j.listToolPolicies))return;const w=await window.agentApi.listToolPolicies();r(w.policies),i(w.tools)};a.useEffect(()=>{p().catch(w=>t(String(w),"error"))},[]);const v=async()=>{var w;if(!(!o||!((w=window.agentApi)!=null&&w.saveToolPolicy)))try{await window.agentApi.saveToolPolicy(o,d),await p(),l(null),t("工具策略已保存","success")}catch(j){t(j instanceof Error?j.message:"工具策略保存失败","error")}},x=async w=>{var j;if((j=window.agentApi)!=null&&j.deleteToolPolicy)try{await window.agentApi.deleteToolPolicy(w),await p(),(o==null?void 0:o.id)===w&&l(null),t("工具策略已删除","success")}catch(E){t(E instanceof Error?E.message:"工具策略删除失败","error")}};return e.jsxs("section",{className:"tool-policy-manager",children:[e.jsxs("div",{className:"settings-head-row",children:[e.jsx("h3",{children:"工具执行策略"}),e.jsx("button",{type:"button",className:"tool-policy-button",onClick:()=>{l(Jm()),u(!1)},children:"+ 添加"})]}),e.jsxs("div",{className:"tool-policy-list",children:[n.map(w=>e.jsxs("div",{className:"tool-policy-row",children:[e.jsxs("div",{children:[e.jsx("strong",{children:w.name}),e.jsxs("small",{children:[w.id," · ",w.enabled?"已启用":"已停用"]})]}),e.jsxs("div",{className:"tool-policy-actions",children:[e.jsx("button",{type:"button",onClick:()=>{l(structuredClone(w)),u(!0)},children:"编辑"}),e.jsx("button",{type:"button",className:"is-danger",onClick:()=>void x(w.id),children:"删除"})]})]},w.id)),n.length===0&&e.jsx("div",{className:"tool-policy-empty",children:"暂无工具执行策略"})]}),o&&e.jsxs("div",{className:"tool-policy-form",children:[e.jsxs("div",{className:"tool-policy-grid two",children:[e.jsx(yn,{label:"策略 ID",children:e.jsx("input",{value:o.id,disabled:d,onChange:w=>l({...o,id:w.target.value})})}),e.jsx(yn,{label:"名称",children:e.jsx("input",{value:o.name,onChange:w=>l({...o,name:w.target.value})})})]}),e.jsxs("label",{className:"tool-policy-check",children:[e.jsx("input",{type:"checkbox",checked:o.enabled,onChange:w=>l({...o,enabled:w.target.checked})}),"启用"]}),e.jsx(yn,{label:"允许的工具",children:e.jsx("div",{className:"tool-policy-tools",children:f.map(w=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:o.allowedTools.includes(w),onChange:()=>l({...o,allowedTools:tx(o.allowedTools,w)})}),w]},w))})}),e.jsxs("div",{className:"tool-policy-grid two",children:[e.jsx(yn,{label:"只读根目录(每行一个)",children:e.jsx("textarea",{value:o.filesystem.readRoots.join(`
|
|
468
|
+
`);ae({id:crypto.randomUUID(),role:"assistant",content:Mt,timestamp:Date.now()})}return}const ve=de.match(/^(?:pause|暂停)\s+(\S+)$/i);if(ve){if(window.agentApi){const Oe=B.find(vt=>vt.id.startsWith(ve[1])),Mt=await window.agentApi.cronPause((Oe==null?void 0:Oe.id)??ve[1]);if(Mt){const vt=await window.agentApi.cronList();Y(vt),ae({id:crypto.randomUUID(),role:"assistant",content:`⏸ 定时任务 \`${Mt.id.slice(0,6)}\` 已暂停。`,timestamp:Date.now()})}else ae({id:crypto.randomUUID(),role:"assistant",content:`未找到 ID 以 \`${ve[1]}\` 开头的定时任务。`,timestamp:Date.now()})}return}const Me=de.match(/^(?:resume|恢复)\s+(\S+)$/i);if(Me){if(window.agentApi){const Oe=B.find(vt=>vt.id.startsWith(Me[1])),Mt=await window.agentApi.cronResume((Oe==null?void 0:Oe.id)??Me[1]);if(Mt){const vt=await window.agentApi.cronList();Y(vt),ae({id:crypto.randomUUID(),role:"assistant",content:`▶ 定时任务 \`${Mt.id.slice(0,6)}\` 已恢复。`,timestamp:Date.now()})}else ae({id:crypto.randomUUID(),role:"assistant",content:`未找到 ID 以 \`${Me[1]}\` 开头的定时任务。`,timestamp:Date.now()})}return}const Se=de.match(/^(?:delete|del|删除|stop)\s+(\S+)$/i);if(Se){if(window.agentApi){const Oe=B.find(vt=>vt.id.startsWith(Se[1]));if(await window.agentApi.cronDelete((Oe==null?void 0:Oe.id)??Se[1])){const vt=await window.agentApi.cronList();Y(vt),ae({id:crypto.randomUUID(),role:"assistant",content:`🗑 定时任务 \`${Se[1]}\` 已删除。`,timestamp:Date.now()})}else ae({id:crypto.randomUUID(),role:"assistant",content:`未找到 ID 以 \`${Se[1]}\` 开头的定时任务。`,timestamp:Date.now()})}return}const It=de.match(/^(\S+)\s+(.+)$/s);if(It){const Oe=It[1],Mt=It[2].trim();if(window.agentApi){let vt=r||He;if(!vt){const xe=await window.agentApi.createSession(Mt.slice(0,60)||"定时任务",n||void 0);vt=xe.id,De(xe.id),s&&await s(xe.id)}try{const xe=await window.agentApi.cronCreate(Oe,Mt,{sessionId:vt}),Yt=await window.agentApi.cronList();Y(Yt),ae({id:crypto.randomUUID(),role:"assistant",content:`⏰ 定时任务已创建(ID: \`${xe.id.slice(0,6)}\`),${Ao(Oe)}执行:${Mt}`,timestamp:Date.now()})}catch(xe){ae({id:crypto.randomUUID(),role:"assistant",content:`❌ 创建失败:${xe instanceof Error?xe.message:String(xe)}`,timestamp:Date.now()})}}return}ae({id:crypto.randomUUID(),role:"assistant",content:"**定时任务用法:**\n- `/loop <间隔/cron> <任务>` — 创建,如 `/loop 5m 检查系统状态` 或 `/loop 0 9 * * * 早报`\n- `/loop list` — 查看所有定时任务\n- `/loop pause <id>` — 暂停\n- `/loop resume <id>` — 恢复\n- `/loop delete <id>` — 删除\n- `/loop stop` — 删除全部\n\n间隔支持:`30s`、`5m`、`2h`;也支持 5 字段 cron 表达式。",timestamp:Date.now()});return}const y=m.match(/(?:每(?:隔)?|定时每)\s*(\d+(?:\.\d+)?)\s*(分钟|秒|小时|min|sec|h)\s*(.+)/is);if(y){const de=y[1]+y[2],ve=y[3].trim();if(ve&&window.agentApi){let Me=r||He;if(!Me){const Se=await window.agentApi.createSession(ve.slice(0,60)||"定时任务",n||void 0,Ne,Ne!=="customer-agent"?v??void 0:void 0);Me=Se.id,De(Se.id),s&&await s(Se.id)}try{const Se=await window.agentApi.cronCreate(de,ve,{sessionId:Me}),It=await window.agentApi.cronList();Y(It),h(),ae({id:crypto.randomUUID(),role:"user",content:m,timestamp:Date.now()}),ae({id:crypto.randomUUID(),role:"assistant",content:`⏰ 定时任务已创建(ID: \`${Se.id.slice(0,6)}\`),${Ao(de)}执行:${ve}`,timestamp:Date.now()})}catch(Se){ae({id:crypto.randomUUID(),role:"assistant",content:`❌ 创建失败:${Se instanceof Error?Se.message:String(Se)}`,timestamp:Date.now()})}return}}const O=c.text,P=O.match(/^\/goal(?:\s+([\s\S]+))?$/i),he=P?((ue=P[1])==null?void 0:ue.trim())??"":c.applyGoalMode&&sr?O:null;if(he!==null&&!he){Ce("请输入目标内容");return}const Z=c.agentName,Ae=c.images,oe=c.agentIds??[];if(c.clearComposer&&oo([]),he!==null){const de=crypto.randomUUID();let ve=null,Me=null;as.current=!1,c.clearComposer&&X&&(Cs(X),Xt.clear(X)),h();try{const Se=await lc({text:he,projectId:n??null,sessionId:r||He,createSession:async(Oe,Mt)=>{if(!window.agentApi)throw new Error("agentApi 未就绪");return await window.agentApi.createSession(Oe,Mt,Ne,Ne!=="customer-agent"?v??void 0:void 0)},activateSession:Oe=>{yt.current=Oe,De(Oe),Ct.current=Oe,ke(Oe)},showUserMessage:(Oe,Mt)=>{ve=Mt,ae({id:de,role:"user",content:Oe,timestamp:Date.now(),agentName:Z,images:Ae,isGoal:!0,goalId:de},Mt)},onSessionCreated:s});Me=Se,c.clearComposer&&Se!==X&&(Cs(Se),Xt.clear(Se));const It=await window.agentApi.enqueueSessionGoal(Se,he,de);an(It,Se),i&&i(Se,he)}catch(Se){if(ve){const Mt=et.getState().getMessagesForSession(ve);ne(Mt.filter(vt=>vt.id!==de),ve)}const It=Me??ve??X;c.restoreDraftOnFailure&&It&&(Hr(It,O),Xt.save(It,Ae??[]));const Oe=nt.current||yt.current;c.restoreDraftOnFailure&&(It&&Oe===It||!It&&!Oe)&&(Qt(O),gn(Ae??[])),ke(null),Ce(Se instanceof Error?Se.message:"目标创建失败")}return}if(xr){const de=X,ve=crypto.randomUUID(),Me={id:ve,role:"user",content:O,timestamp:Date.now(),agentName:Z,images:Ae,isQueued:!0};if(c.clearComposer&&de&&(Cs(de),Xt.clear(de)),h(),Yr&&de&&((Be=window.agentApi)!=null&&Be.enqueueSessionMessage)){ae(Me,de);try{const Se=await window.agentApi.enqueueSessionMessage(de,{sourceMessageId:ve,content:O,images:Ae,agentIds:oe,agentName:Z});an(Se,de)}catch(Se){const It=et.getState().getMessagesForSession(de);ne(It.filter(Oe=>Oe.id!==ve),de),c.restoreDraftOnFailure&&(Hr(de,O),Xt.save(de,Ae??[]),(nt.current||yt.current)===de&&(Qt(O),gn(Ae??[]))),Ce(Se instanceof Error?Se.message:"排队消息保存失败")}}else ae(Me,de??void 0);return}const J=r||He;c.clearComposer&&it&&J&&(tt.current=!0,ft.current=J),h(),ct([]);const je=crypto.randomUUID();try{const de=await lc({text:O,projectId:n??null,sessionId:r||He,createSession:async(ve,Me)=>{if(!window.agentApi)throw new Error("agentApi 未就绪");return await window.agentApi.createSession(ve,Me,Ne,Ne!=="customer-agent"?v??void 0:void 0)},activateSession:ve=>{yt.current=ve,De(ve),Ct.current=ve},showUserMessage:(ve,Me)=>ae({id:je,role:"user",content:ve,timestamp:Date.now(),agentName:Z,images:Ae,sendState:"pending"},Me),afterUserMessageShown:em,onSessionCreated:s});i&&i(de,O),await js({content:O,agentName:Z,images:Ae,restoreDraftOnFailure:c.restoreDraftOnFailure},de,oe.length>0?oe:void 0)}catch(de){const ve=r||He;ve&&ji(ve,"failed"),Ce(de instanceof Error?de.message:"Agent run failed")}},Xa=async()=>Qa(yh({text:Kt,agentIds:qs.map(c=>c.id),agentName:qs.length>0?qs.map(c=>c.name).join(", "):void 0,images:pr})),Vu=c=>{Qa(vh(c))};return a.useEffect(()=>{if(!A||!window.agentApi)return;const{text:c,projectId:m,sessionId:h}=A;let y=!1;return(async()=>{try{ct([]);const O=await Zg({text:c,projectId:m,sessionId:h,createSession:async(P,he)=>await window.agentApi.createSession(P,he,Ne,Ne!=="customer-agent"?v??void 0:void 0),activateSession:P=>{yt.current=P,De(P),Ct.current=P,ke(P)},showUserMessage:(P,he)=>ae({id:crypto.randomUUID(),role:"user",content:P,timestamp:Date.now()},he),onSessionCreated:s,isCancelled:()=>y});if(!O)return;i&&i(O,c),await js({content:c},O)}catch(O){Ce(O instanceof Error?O.message:"语音指令执行失败")}})(),()=>{y=!0}},[A==null?void 0:A.nonce]),e.jsxs("div",{className:"chat-view chat-view--codex-history",style:{display:"flex",flexDirection:"column",height:"100%",maxWidth:"var(--chat-max-width)",margin:"0 auto"},children:[e.jsxs("div",{className:"chat-top-bar",style:{display:"flex",alignItems:"center",padding:"var(--chat-header-padding)",height:"var(--chat-header-height)",flexShrink:0,borderBottom:"1px solid var(--border-subtle)",WebkitAppRegion:"drag"},children:[e.jsx("span",{style:{flex:1,minWidth:0,fontSize:14,fontWeight:500,color:f?"var(--text-primary)":"var(--text-muted)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",letterSpacing:"-0.01em"},children:f||"会话"}),x&&j&&H&&e.jsx(yg,{appearanceOpen:L,settingsOpen:w,showSettings:Ne==="customer-agent",onOpenDesktopLive:S,desktopLiveOpen:C,filesOpen:k,onToggleFiles:z,hideToBackgroundTitle:T,codexReleaseState:en,onHideToBackground:j,onReleaseCodex:(p==null?void 0:p.agentType)==="codex"&&p.occupancy!=="owned-externally"?()=>{qa()}:void 0,onOpenHub:E,onToggleAppearance:H,onOpenSettings:x})]}),e.jsx($g,{open:tn,agentSessionId:X,onClose:()=>Zn(!1)}),e.jsxs("div",{className:"chat-messages-frame",children:[e.jsxs("div",{ref:Pn,className:"chat-messages",onScroll:ku,onWheel:c=>{$p(c,c.currentTarget.scrollTop)&&Zr.current()},onTouchStart:c=>es.current.start(c.touches),onTouchMove:c=>{es.current.move(c.touches,c.currentTarget.scrollTop)&&Zr.current()},onTouchEnd:()=>es.current.reset(),onTouchCancel:()=>es.current.reset(),style:{overflow:"auto",position:"relative",padding:"var(--chat-messages-padding)"},children:[Ze.length>0&&(Ia||eo)&&e.jsx("div",{className:"chat-history-page-status",role:eo?"alert":"status","aria-live":"polite",children:Ia?e.jsx(e.Fragment,{children:e.jsxs("span",{className:"chat-history-loading-pill",children:[e.jsxs("span",{className:"chat-history-loading-dots","aria-hidden":"true",children:[e.jsx("i",{}),e.jsx("i",{}),e.jsx("i",{})]}),e.jsx("span",{children:"正在加载更早消息"})]})}):e.jsxs("button",{type:"button",onClick:()=>void fo(),className:"chat-history-retry",style:{border:"1px solid color-mix(in srgb, var(--danger) 30%, transparent)",background:"color-mix(in srgb, var(--danger) 7%, transparent)",color:"var(--danger)",borderRadius:6,padding:"5px 10px",cursor:"pointer",fontSize:12},children:[eo,",点击重试"]})}),Ze.length===0&&ks&&bu&&e.jsxs("div",{className:"chat-history-initial-loading",role:"status",style:{height:"100%",display:"flex",alignItems:"center",justifyContent:"center",gap:9,color:"var(--text-muted)",fontSize:13},children:[e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"var(--accent)",strokeWidth:"2",style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true",children:e.jsx("path",{d:"M21 12a9 9 0 1 1-6.22-8.56"})}),e.jsx("span",{children:"正在加载历史消息"})]}),Ze.length===0&&!Cn&&!ks&&!Gn&&e.jsx(Vg,{agentType:(p==null?void 0:p.agentType)??t,ready:An,onSelectPrompt:Mu},X??"initial-empty-session"),$e.map((c,m)=>{var Be,de,ve,Me,Se,It,Oe,Mt,vt;const h=c;if(h.isQueued)return null;if(h.executionTrace)return e.jsx(gg,{trace:h.executionTrace,loadTrace:wu,loadToolResult:ao,renderContent:R,runtimeProgress:dr,nativeSubagents:_n,onSelectSession:l,workspacePath:v,onOpenArtifact:M,refreshSignal:h.executionTrace.turnId===Gt?dt:0,autoLoad:Hs==="latest"&&h.executionTrace.turnId===Gt},c.id);const y=c.role==="user",O=y&&(h.isGoal===!0||[q.active,...q.queued,...q.history].some(xe=>!!(xe&&hc(xe.objective)===hc(c.content)))),P=fm($e,m,Cn),he=cm((Be=h.presentation)==null?void 0:Be.completionDurationMs);if(h.isCompactionSummary)return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,margin:"20px 0",color:"var(--text-muted)",fontSize:12},children:[e.jsx("div",{style:{flex:1,height:1,background:"var(--border-subtle)"}}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"4px 12px",borderRadius:20,border:"1px solid var(--border-subtle)",background:"var(--bg-deep)",color:"var(--text-muted)",fontSize:11,cursor:"default",userSelect:"none"},children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"17 1 21 5 17 9"}),e.jsx("path",{d:"M3 11V9a4 4 0 0 1 4-4h14"}),e.jsx("polyline",{points:"7 23 3 19 7 15"}),e.jsx("path",{d:"M21 13v2a4 4 0 0 1-4 4H3"})]}),"上下文已压缩"]}),e.jsx("div",{style:{flex:1,height:1,background:"var(--border-subtle)"}})]},c.id);if(h.widget){const xe=Xg[h.widget.widgetType];return xe?e.jsx("div",{style:{marginBottom:16,display:"flex",justifyContent:"flex-start"},children:e.jsx(xe,{...h.widget.data,widgetId:h.widget.widgetId,isAgentRunning:Cn&&!$e.slice(m+1).some(Yt=>Yt.role==="user"&&!Yt.isQueued&&!Yt.isSteered)})},c.id):e.jsx("div",{style:{marginBottom:16,padding:12,borderRadius:8,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",fontFamily:"var(--font-mono, monospace)",fontSize:12,whiteSpace:"pre-wrap",maxHeight:300,overflow:"auto"},children:JSON.stringify(h.widget.data,null,2)},c.id)}if(h.askUser)return e.jsx(dg,{questionId:h.askUser.questionId,question:h.askUser.question,options:h.askUser.options,fields:h.askUser.fields,multiSelect:h.askUser.multiSelect,answered:h.askUser.answered,answer:h.askUser.answer,onAnswer:async(xe,Yt)=>{var At;if(!await((At=window.agentApi)==null?void 0:At.answerQuestion(h.askUser.questionId,xe,Yt)))throw new Error("回答未发送成功,请重试;若问题已结束,请刷新会话。");Ge(c.id,En=>({...En,askUser:{...En.askUser,answered:!0,answer:xe}}),X??void 0)}},c.id);const Z=h.agentName?h.agentName.charAt(0).toUpperCase():"你",Ae=!y&&m===$e.length-1,oe=$e[m+1],J=oe&&oe.role!==c.role&&!oe.isCompactionSummary,je=(c.toolCalls??[]).map((xe,Yt)=>{let Js;if(xe.name==="write_file"&&xe.arguments.file_path){const At=xe.arguments.file_path;e:for(let En=m;En>=0;En--){const Cr=$e[En].toolCalls;if(!Cr)continue;const Zs=En===m?Yt-1:Cr.length-1;for(let ls=Zs;ls>=0;ls--){const Ir=Cr[ls];if(Ir.name==="read_file"&&Ir.arguments.file_path===At&&Ir.result&&!Ir.isError){Js=Ir.result;break e}}}}return{toolCall:xe,beforeContent:Js,progress:wd(dr,xe.id),nativeSubagent:_n[xe.id]}}),ue=Qd(je);return e.jsx("div",{"data-message-id":c.id,className:`chat-message-group${P.compact?" chat-message-group--intermediate":""}`,style:{marginBottom:P.compact?0:J?"var(--chat-turn-gap)":"var(--chat-message-gap)"},children:e.jsxs("div",{className:`chat-message-row chat-message-row--${y?"user":"assistant"}`,style:{display:"flex",flexDirection:y?"row-reverse":"row",alignItems:"flex-start",gap:"var(--chat-row-gap)",animation:"fadeInUp 0.3s var(--ease-out) both"},children:[y?e.jsx("div",{className:"chat-message-avatar",style:{width:"var(--chat-avatar-size)",height:"var(--chat-avatar-size)",borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--accent)",color:"#fff",fontSize:12,fontWeight:700,letterSpacing:0,userSelect:"none"},children:Z}):e.jsx("div",{className:"chat-message-avatar",style:{width:"var(--chat-avatar-size)",height:"var(--chat-avatar-size)",borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:"var(--bg-deep)",color:"var(--text-muted)",border:"1px solid var(--border-subtle)"},children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),e.jsx("path",{d:"M12 11V7"}),e.jsx("circle",{cx:"12",cy:"5",r:"2"}),e.jsx("circle",{cx:"8",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"16",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("path",{d:"M8 20h8"})]})}),e.jsxs("div",{className:`chat-message-content chat-message-content--${y?"user":"assistant"}`,style:{maxWidth:"var(--chat-content-max-width)",display:"flex",flexDirection:"column",gap:4,alignItems:y?"flex-end":"flex-start",minWidth:0},children:[e.jsxs("div",{className:`chat-message-bubble chat-message-bubble--${y?"user":"assistant"} ${c.role==="assistant"&&c.content?"message-card":""}`,style:{padding:c.content||y&&((de=h.images)!=null&&de.length)?y?"var(--chat-user-bubble-padding)":"var(--chat-assistant-bubble-padding)":0,borderRadius:y?"14px 4px 14px 14px":"4px 14px 14px 14px",background:c.content||y&&((ve=h.images)!=null&&ve.length)?y?"rgba(79, 110, 247, 0.08)":void 0:"transparent",border:c.content||y&&((Me=h.images)!=null&&Me.length)?y?"1px solid rgba(79, 110, 247, 0.18)":void 0:"none",fontSize:"var(--chat-bubble-font-size)",lineHeight:"var(--chat-bubble-line-height)",color:"var(--chat-history-text)",letterSpacing:"0.01em"},children:[c.role==="assistant"&&((Se=c.presentation)==null?void 0:Se.reasoning)&&e.jsx(Vd,{sections:c.presentation.reasoning,streaming:Cn&&Ae&&kt==="thinking",startedAt:Nn,renderContent:R}),y&&h.agentName?e.jsxs("div",{children:[e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3,fontSize:10,fontWeight:700,color:"var(--accent)",background:"var(--accent-dim)",border:"1px solid rgba(79,110,247,0.22)",borderRadius:10,padding:"1px 7px 1px 5px",letterSpacing:"0.04em",marginRight:7,verticalAlign:"middle"},children:[e.jsxs("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("circle",{cx:"12",cy:"8",r:"4"}),e.jsx("path",{d:"M20 21a8 8 0 1 0-16 0"})]}),h.agentName]}),e.jsx("span",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",verticalAlign:"middle"},children:c.content})]}):c.role==="assistant"&&c.content?e.jsx("div",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:e.jsx(vf,{text:c.content,complete:!(Cn&&Ae),renderText:R,suggestionsEnabled:An&&Bs===0,onSuggestionSend:Vu,onCopyFailed:()=>Ce("复制失败,请选择文字后复制")})}):c.content&&e.jsx("div",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word"},children:y?c.content:R(c.content)}),y&&h.images&&h.images.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginTop:c.content?8:0},children:h.images.map((xe,Yt)=>e.jsx("button",{type:"button",className:"chat-message-image-button","aria-label":"放大查看图片",onClick:()=>Dr({src:xe,alt:`用户发送的图片 ${Yt+1}`}),children:e.jsx("img",{className:"chat-message-attachment-image",src:xe,alt:`用户发送的图片 ${Yt+1}`})},Yt))}),y&&!((It=h.images)!=null&&It.length)&&((Oe=h.presentation)==null?void 0:Oe.attachments)&&h.presentation.attachments.length>0&&e.jsx("div",{className:"chat-message-attachments",children:h.presentation.attachments.map((xe,Yt)=>xe.dataUrl?e.jsx("button",{type:"button",className:"chat-message-image-button","aria-label":`放大查看图片:${xe.name}`,onClick:()=>Dr({src:xe.dataUrl,alt:xe.name}),children:e.jsx("img",{className:"chat-message-attachment-image",src:xe.dataUrl,alt:xe.name,title:xe.name})},`${xe.name}-${Yt}`):e.jsxs("div",{className:"chat-message-attachment-unavailable","aria-label":`${xe.name},${xe.omitted&&!xe.unavailable?"图片未随页面加载":"图片已失效"}`,children:[e.jsx("span",{className:"chat-message-attachment-name",children:xe.name}),e.jsx("span",{children:xe.omitted&&!xe.unavailable?"图片未随页面加载":"图片已失效"})]},`${xe.name}-${Yt}`))}),y&&((Mt=h.presentation)==null?void 0:Mt.rawContent)&&e.jsxs("details",{className:"chat-message-raw-content",children:[e.jsx("summary",{children:"查看原始内容"}),e.jsx("pre",{children:h.presentation.rawContent})]}),ue.map(xe=>xe.action&&xe.items.length>1?e.jsx(qd,{items:xe.items,onSelectSession:l,workspacePath:v,onOpenArtifact:M,onLoadResult:_a},`group-${xe.items[0].toolCall.id}`):e.jsx(Qi,{toolCall:xe.items[0].toolCall,beforeContent:xe.items[0].beforeContent,progress:xe.items[0].progress,nativeSubagent:xe.items[0].nativeSubagent,onSelectSession:l,workspacePath:v,onOpenArtifact:M,onLoadResult:_a},xe.items[0].toolCall.id)),(()=>{const xe=(c.toolCalls??[]).filter(At=>At.name==="write_file"&&At.result&&!At.isError);if(xe.length===0)return null;const Yt=new Map;for(const At of xe){const En=At.arguments.file_path??"",Cr=At.arguments.content??"",Zs=Cr?Cr.split(`
|
|
469
|
+
`).length:0;let ls=0;e:for(let Ir=m;Ir>=0;Ir--){const al=$e[Ir].toolCalls??[];for(let bo=al.length-1;bo>=0;bo--){const ei=al[bo];if(ei.name==="read_file"&&ei.arguments.file_path===En&&ei.result&&!ei.isError){ls=ei.result.split(`
|
|
470
|
+
`).length;break e}}}Yt.set(En,{path:En,lines:Zs,added:Math.max(0,Zs-ls),removed:Math.max(0,ls-Zs)})}const Js=[...Yt.values()];return e.jsxs("div",{style:{marginTop:10,padding:"8px 12px",borderRadius:8,background:"var(--bg-deep)",border:"1px solid var(--border-subtle)",display:"flex",flexWrap:"wrap",gap:8,alignItems:"center"},children:[e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.07em",flexShrink:0},children:"变更汇总"}),Js.map(At=>{const En=ga(At.path,v),Cr=e.jsxs(e.Fragment,{children:[e.jsx("span",{style:{color:"var(--text-secondary)",maxWidth:160,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:At.path,children:At.path.replace(/\\/g,"/").split("/").pop()}),At.added>0&&e.jsxs("span",{style:{color:"var(--success)",fontWeight:600},children:["+",At.added]}),At.removed>0&&e.jsxs("span",{style:{color:"var(--danger)",fontWeight:600},children:["−",At.removed]}),At.added===0&&At.removed===0&&e.jsxs("span",{style:{color:"var(--text-muted)"},children:[At.lines,"行"]})]});return M&&En?e.jsx("button",{type:"button",className:"chat-file-change-link",onClick:()=>M(En),title:`预览 ${En}`,"aria-label":`预览改动文件 ${At.path.replace(/\\/g,"/").split("/").pop()}`,children:Cr},At.path):e.jsx("span",{className:"chat-file-change-link chat-file-change-link--static",children:Cr},At.path)})]})})(),y&&(h.sendState||h.isSteered)&&e.jsxs("div",{className:`msg-send-status${h.sendState?` is-${h.sendState}`:""}`,role:"status","aria-label":h.sendState==="pending"?"正在发送":h.sendState==="failed"?"发送失败":"已引导",children:[h.sendState==="pending"&&e.jsxs("span",{className:"msg-send-status__dots","aria-hidden":"true",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]}),h.sendState==="failed"&&e.jsx("span",{children:"发送失败"}),h.isSteered&&e.jsx("span",{className:"msg-steered-status",title:"已引导","aria-label":"已引导",role:"img",children:e.jsx(fl,{size:13,strokeWidth:2,"aria-hidden":"true"})})]})]}),P.showCompletion&&e.jsxs("div",{className:"msg-completion-footer",children:[e.jsxs("span",{className:"msg-completion-status",children:[e.jsx(Gr,{size:13,strokeWidth:2,"aria-hidden":"true"}),e.jsx("span",{children:"已完成"}),he&&e.jsxs("span",{children:[" · 总耗时 ",he]})]}),e.jsxs("span",{className:"msg-completion-actions",children:[X&&(wo(c,X)||!X.startsWith("runtime:"))&&e.jsx("button",{type:"button",onClick:()=>{Fu(c)},disabled:!!wn||Wt,title:"从此轮 Fork 为新会话","aria-label":"从此轮 Fork 为新会话",className:"ui-icon-button ui-icon-button--small msg-action-button",children:wn===c.id?e.jsx(ot,{size:13,className:"animate-spin","aria-hidden":"true"}):e.jsx(dp,{size:13,strokeWidth:1.8,"aria-hidden":"true"})}),!Vo()&&P.showSpeak&&typeof((vt=window.agentApi)==null?void 0:vt.ttsSpeak)=="function"&&e.jsx("button",{type:"button",onClick:()=>Cu(c.id,c.content),title:Gs===c.id?"停止播报":"语音播报","aria-label":Gs===c.id?"停止播报":"语音播报",className:`ui-icon-button ui-icon-button--small msg-action-button ${Gs===c.id?"is-active":""}`,children:Gs===c.id?e.jsx(vl,{size:12,fill:"currentColor","aria-hidden":"true"}):e.jsx(cd,{size:13,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:()=>{zi(c.content)},title:"复制内容","aria-label":"复制内容",className:"ui-icon-button ui-icon-button--small msg-action-button",children:e.jsx(Ni,{size:13,strokeWidth:1.8,"aria-hidden":"true"})})]})]}),!P.showCompletion&&(P.showCopy||O)&&e.jsxs("div",{className:"msg-actions",style:{display:"flex",alignItems:"center",gap:4},children:[O&&e.jsx("span",{className:"ui-icon-button ui-icon-button--small msg-action-button msg-goal-marker",title:"目标消息","aria-label":"目标消息",role:"img",children:e.jsx(Si,{size:13,strokeWidth:1.9,"aria-hidden":"true"})}),P.showCopy&&e.jsx("button",{type:"button",onClick:()=>{zi(c.content)},title:"复制内容","aria-label":"复制内容",className:"ui-icon-button ui-icon-button--small msg-action-button",children:e.jsx(Ni,{size:13,strokeWidth:1.8,"aria-hidden":"true"})})]}),y&&h.isQueued&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4},children:[e.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,color:"var(--text-muted)",padding:"2px 8px",borderRadius:20,background:"var(--bg-deep)",border:"1px solid var(--border-subtle)"},children:[e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("polyline",{points:"12 6 12 12 16 14"})]}),"排队中"]}),Mn&&e.jsxs("button",{onClick:()=>void Va(c.id),disabled:Pe.has(c.id),title:Pe.has(c.id)?"正在引导":"将此消息引导到当前对话",style:{display:"inline-flex",alignItems:"center",gap:4,fontSize:11,fontWeight:600,color:"var(--accent)",padding:"2px 10px",borderRadius:20,border:"1px solid rgba(79,110,247,0.3)",background:"var(--accent-dim)",cursor:Pe.has(c.id)?"wait":"pointer",opacity:Pe.has(c.id)?.6:1,transition:"all 0.15s",fontFamily:"var(--font-body)"},onMouseEnter:xe=>{xe.currentTarget.style.background="rgba(79,110,247,0.18)",xe.currentTarget.style.borderColor="var(--accent)"},onMouseLeave:xe=>{xe.currentTarget.style.background="var(--accent-dim)",xe.currentTarget.style.borderColor="rgba(79,110,247,0.3)"},children:[e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M3 12h18M3 6h18M3 18h18"}),e.jsx("path",{d:"M12 3v18",opacity:"0.3"})]}),Pe.has(c.id)?"引导中":"引导"]})]})]})]})},c.id)}),Cn&&_r&&e.jsx(Bd,{progress:_r,startedAt:Nn}),ur&&e.jsx("div",{className:"chat-message-activity",style:{display:"flex",alignItems:"flex-start",padding:"4px 0 4px",animation:"fadeInUp 0.3s var(--ease-out)"},children:e.jsx(fg,{startedAt:Nn})}),(xs||Gn)&&e.jsxs("div",{style:{padding:12,margin:"8px 0",borderRadius:"var(--radius-sm)",background:"rgba(248,113,113,0.08)",border:"1px solid rgba(248,113,113,0.2)",color:"var(--danger)",fontSize:13,animation:"fadeIn 0.2s var(--ease-out)",fontFamily:"var(--font-mono)",display:"flex",alignItems:"center",flexWrap:"wrap",gap:10},children:[e.jsx("span",{style:{flex:1,minWidth:0},children:xs||Gn}),!xs&&Jr===X&&e.jsxs("div",{style:{display:"inline-flex",gap:6,flexShrink:0},children:[e.jsx("button",{type:"button",onClick:go,"aria-label":"再次停止",title:"再次停止",className:"ui-icon-button",children:e.jsx(vl,{size:14,fill:"currentColor","aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:()=>{qa()},"aria-label":"释放会话",title:"释放会话",className:"ui-icon-button",disabled:en!=="idle",children:en==="releasing"?e.jsx(ot,{size:14,className:"spin","aria-hidden":"true"}):e.jsx(ld,{size:14,"aria-hidden":"true"})})]}),xs&&e.jsxs("button",{type:"button",onClick:()=>Xi(c=>c+1),"aria-label":"重新加载会话",title:"重新加载会话",style:{flexShrink:0,minHeight:30,display:"inline-flex",alignItems:"center",gap:5,padding:"5px 9px",border:"1px solid rgba(248,113,113,0.35)",borderRadius:5,background:"var(--bg-workspace)",color:"var(--danger)",cursor:"pointer",fontSize:12},children:[e.jsx(Ns,{size:14,"aria-hidden":"true"}),"重新加载"]})]}),e.jsx("div",{ref:Os})]}),e.jsx(ch,{entries:(to==null?void 0:to.entries)??[],activeMessageId:fu,loadingMessageId:hu,onActivate:c=>{Ha(c)}}),Hs==="anchored"&&e.jsx("button",{type:"button",className:"chat-history-return-latest","data-has-updates":gu,"data-loading-newer":mu,"aria-busy":ro||void 0,"aria-label":"回到最新消息",title:"回到最新消息",disabled:ro,onClick:()=>{$a()},children:ro?e.jsx(ot,{className:"chat-history-return-latest__spinner",size:16,"aria-hidden":"true"}):e.jsx(pl,{size:16,"aria-hidden":"true"})}),Hs!=="anchored"&&xu&&e.jsx("button",{type:"button",className:"chat-jump-to-bottom","aria-label":"回到底部",title:"回到底部",onClick:ju,children:e.jsx(pl,{size:16,"aria-hidden":"true"})})]}),e.jsxs("div",{className:"chat-input-area",style:{padding:"var(--chat-input-padding)",background:"var(--bg-workspace)"},children:[on&&e.jsx("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:9,padding:"8px 10px",border:"1px solid var(--border-default)",borderRadius:6,background:"var(--bg-surface)",color:cr==="incompatible"?"var(--danger)":"var(--text-muted)",fontSize:12},children:e.jsx("span",{style:{flex:1},children:cr==="incompatible"?ar||((tl=p==null?void 0:p.compatibility)==null?void 0:tl.reason)||`Codex ${((nl=p==null?void 0:p.compatibility)==null?void 0:nl.producerVersion)??"未知版本"} 与当前 ${((rl=p==null?void 0:p.compatibility)==null?void 0:rl.readerVersion)??"运行时"} 不兼容`:`正在使用 Codex ${((sl=p==null?void 0:p.compatibility)==null?void 0:sl.readerVersion)??"当前版本"} 验证此会话`})}),gs&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:9,padding:"8px 10px",border:"1px solid var(--border-default)",borderRadius:6,background:"var(--bg-surface)",color:"var(--text-muted)",fontSize:12},children:[e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("rect",{x:"5",y:"11",width:"14",height:"10",rx:"2"}),e.jsx("path",{d:"M8 11V7a4 4 0 0 1 8 0v4"})]}),e.jsx("span",{style:{flex:1},children:gt!=null&>.forkSessionId?"副本已创建,但消息尚未发送成功。":"此会话仍由原客户端持有,可创建副本继续。"}),gs&&e.jsx("button",{type:"button",onClick:()=>void Bu(),disabled:Wt,style:{flexShrink:0,border:"1px solid var(--border-default)",borderRadius:5,padding:"5px 9px",background:"var(--bg-workspace)",color:"var(--text-primary)",fontSize:12,fontWeight:600,cursor:Wt?"wait":"pointer",opacity:Wt?.65:1},children:Wt?gt!=null&>.forkSessionId?"正在发送…":"正在创建…":gt!=null&>.forkSessionId?"重新发送":"以副本继续"})]}),Nt.length>0&&e.jsxs("div",{style:{marginBottom:10,padding:"8px 12px",borderRadius:10,background:"var(--bg-surface)",border:"1px solid var(--border-subtle)",boxShadow:"var(--shadow-sm)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5,marginBottom:6,fontSize:10,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.07em"},children:[e.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("path",{d:"M9 11l3 3L22 4"}),e.jsx("path",{d:"M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"})]}),"任务列表"]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:4},children:(()=>{const c=new Set(Nt.filter(m=>m.status==="completed").map(m=>m.title.toLowerCase()));return Nt.map(m=>{const h=m.status==="pending",y=m.status==="in-progress",O=m.status==="completed",P=h&&(m.dependsOn??[]).some(he=>!c.has(he.toLowerCase()));return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,opacity:O?.65:1,transition:"opacity 0.3s"},children:[e.jsxs("div",{style:{width:16,height:16,borderRadius:"50%",flexShrink:0,display:"flex",alignItems:"center",justifyContent:"center",background:O?"rgba(52,211,153,0.15)":y?"var(--accent-dim)":P?"rgba(239,68,68,0.08)":"rgba(0,0,0,0.04)",border:O?"1.5px solid rgba(52,211,153,0.6)":y?"1.5px solid var(--accent)":P?"1.5px solid rgba(239,68,68,0.5)":"1.5px solid var(--border-default)"},children:[O&&e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(52,211,153,0.9)",strokeWidth:"3",strokeLinecap:"round",children:e.jsx("path",{d:"M20 6L9 17l-5-5"})}),y&&e.jsx("div",{style:{width:6,height:6,borderRadius:"50%",background:"var(--accent)",animation:"pulse 1.2s ease-in-out infinite"}}),P&&e.jsx("svg",{width:"8",height:"8",viewBox:"0 0 24 24",fill:"none",stroke:"rgba(239,68,68,0.8)",strokeWidth:"3",strokeLinecap:"round",children:e.jsx("path",{d:"M18 6L6 18M6 6l12 12"})}),h&&!P&&e.jsx("div",{style:{width:5,height:5,borderRadius:"50%",background:"var(--border-default)"}})]}),e.jsx("span",{style:{fontSize:12,color:O?"var(--text-muted)":P?"rgba(239,68,68,0.8)":"var(--text-primary)",textDecoration:O?"line-through":"none",flex:1},children:m.title}),P&&e.jsx("span",{title:`等待: ${(m.dependsOn??[]).join(", ")}`,style:{fontSize:10,color:"rgba(239,68,68,0.9)",background:"rgba(239,68,68,0.08)",border:"1px solid rgba(239,68,68,0.25)",borderRadius:8,padding:"1px 6px",flexShrink:0},children:"等待前置"}),m.agentName&&e.jsxs("span",{style:{fontSize:10,color:"var(--accent)",background:"var(--accent-dim)",border:"1px solid rgba(79,110,247,0.2)",borderRadius:8,padding:"1px 6px",flexShrink:0},children:["@",m.agentName]})]},m.id)})})()})]}),B.length>0&&e.jsxs("div",{style:{marginBottom:10,borderRadius:10,background:"var(--bg-surface)",border:"1px solid rgba(251,191,36,0.25)",overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 12px",borderBottom:"1px solid rgba(251,191,36,0.15)",background:"rgba(251,191,36,0.06)"},children:[e.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"#d97706",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"10"}),e.jsx("polyline",{points:"12 6 12 12 16 14"})]}),e.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#d97706",textTransform:"uppercase",letterSpacing:"0.07em",flex:1},children:"定时任务"}),e.jsx("button",{onClick:async()=>{window.agentApi&&(await window.agentApi.cronDeleteAll(),Y([]),ae({id:crypto.randomUUID(),role:"assistant",content:"✅ 所有定时任务已删除。",timestamp:Date.now()}))},title:"删除全部",style:{background:"none",border:"1px solid rgba(251,191,36,0.35)",borderRadius:6,color:"#d97706",cursor:"pointer",padding:"1px 7px",fontSize:10},children:"全部删除"})]}),B.map(c=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,padding:"7px 12px",borderBottom:"1px solid var(--border-subtle)",opacity:c.enabled?1:.7},children:[e.jsx("div",{style:{width:7,height:7,borderRadius:"50%",flexShrink:0,background:c.enabled?"#22c55e":"#9ca3af",boxShadow:c.enabled?"0 0 5px rgba(34,197,94,0.55)":"none",animation:c.enabled?"pulse 2s ease-in-out infinite":"none"}}),e.jsx("span",{style:{fontSize:10,fontWeight:700,color:"#d97706",background:"rgba(251,191,36,0.12)",border:"1px solid rgba(251,191,36,0.25)",borderRadius:6,padding:"1px 6px",flexShrink:0,fontFamily:"var(--font-mono)"},children:c.cron}),e.jsx("span",{style:{fontSize:12,color:"var(--text-primary)",flex:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.label||c.prompt}),e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",fontFamily:"var(--font-mono)",flexShrink:0},children:c.id.slice(0,6)}),e.jsxs("div",{style:{display:"flex",gap:4,flexShrink:0},children:[c.enabled?e.jsx("button",{title:"暂停",onClick:async()=>{if(window.agentApi){await window.agentApi.cronPause(c.id);const m=await window.agentApi.cronList();Y(m)}},style:{background:"none",border:"1px solid var(--border-default)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",padding:"2px 7px",fontSize:11},onMouseEnter:m=>{m.currentTarget.style.borderColor="#d97706",m.currentTarget.style.color="#d97706"},onMouseLeave:m=>{m.currentTarget.style.borderColor="var(--border-default)",m.currentTarget.style.color="var(--text-muted)"},children:"⏸"}):e.jsx("button",{title:"恢复",onClick:async()=>{if(window.agentApi){await window.agentApi.cronResume(c.id);const m=await window.agentApi.cronList();Y(m)}},style:{background:"none",border:"1px solid var(--border-default)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",padding:"2px 7px",fontSize:11},onMouseEnter:m=>{m.currentTarget.style.borderColor="#22c55e",m.currentTarget.style.color="#22c55e"},onMouseLeave:m=>{m.currentTarget.style.borderColor="var(--border-default)",m.currentTarget.style.color="var(--text-muted)"},children:"▶"}),e.jsx("button",{title:"删除",onClick:async()=>{if(window.agentApi){await window.agentApi.cronDelete(c.id);const m=await window.agentApi.cronList();Y(m)}},style:{background:"none",border:"1px solid var(--border-default)",borderRadius:6,color:"var(--text-muted)",cursor:"pointer",padding:"2px 7px",fontSize:11},onMouseEnter:m=>{m.currentTarget.style.borderColor="var(--danger)",m.currentTarget.style.color="var(--danger)"},onMouseLeave:m=>{m.currentTarget.style.borderColor="var(--border-default)",m.currentTarget.style.color="var(--text-muted)"},children:"🗑"})]})]},c.id))]}),hi.length>0&&e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6,marginBottom:10},children:hi.map((c,m)=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:5,padding:"3px 10px 3px 8px",borderRadius:20,background:"var(--accent-dim)",border:"1px solid rgba(79,110,247,0.18)",fontSize:12,color:"var(--accent)",maxWidth:220},children:[e.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48"})}),e.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.name}),e.jsx("button",{onClick:()=>Nu(m),style:{background:"none",border:"none",color:"rgba(79,110,247,0.55)",cursor:"pointer",padding:0,marginLeft:2,fontSize:13,lineHeight:1,display:"flex"},children:"✕"})]},m))}),pr.length>0&&(()=>{const c=ht.find(h=>h.id===_t),m=!it&&(!c||!po(c.modelId));return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:10},children:[m&&e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,padding:"6px 10px",borderRadius:8,background:"rgba(234,179,8,0.1)",border:"1px solid rgba(234,179,8,0.4)",color:"rgba(202,138,4,1)",fontSize:12},children:[e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0},children:[e.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),e.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),"当前模型(",(c==null?void 0:c.modelId)??"未配置",")不支持图片,发送前请切换到支持视觉的模型(如 claude-3、gpt-4o)"]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:8},children:pr.map((h,y)=>e.jsxs("div",{style:{position:"relative",display:"inline-block"},children:[e.jsx("button",{type:"button",className:"chat-message-image-button pending-image-preview-button","aria-label":`预览待发送图片 ${y+1}`,onClick:()=>Dr({src:h,alt:`待发送图片 ${y+1}`}),children:e.jsx("img",{src:h,alt:`待发送图片 ${y+1}`,style:{width:72,height:72,objectFit:"cover",borderRadius:8,border:"1.5px solid var(--border-default)",display:"block"}})}),e.jsx("button",{type:"button","aria-label":`删除待发送图片 ${y+1}`,onClick:()=>Pu(y),style:{position:"absolute",top:-6,right:-6,width:18,height:18,borderRadius:"50%",background:"var(--danger, #e53e3e)",border:"none",color:"#fff",fontSize:11,cursor:"pointer",display:"flex",alignItems:"center",justifyContent:"center",lineHeight:1,padding:0},children:"✕"})]},y))})]})})(),ee&&(()=>{const c={active:"推进中",paused:"已暂停",blocked:"已受阻",usage_limited:"用量受限",budget_limited:"预算耗尽",complete:"已完成"},m=ee.status!=="active"&&ee.status!=="complete";return e.jsxs("div",{className:`goal-queue thread-goal is-${ee.status}`,"aria-label":"目标模式",children:[e.jsxs("div",{className:"goal-queue__header",children:[e.jsx(Si,{size:14,strokeWidth:1.9,"aria-hidden":"true"}),e.jsx("span",{children:"目标模式"}),e.jsx("span",{className:"goal-queue__count",children:c[ee.status]}),e.jsx("span",{className:"thread-goal__usage",children:ee.tokenBudget!==null?`${ee.tokensUsed}/${ee.tokenBudget} tokens · ${ee.turnCount} 轮`:`${ee.tokensUsed} tokens · ${ee.turnCount} 轮`})]}),e.jsxs("div",{className:"goal-queue__row is-active",children:[e.jsx("span",{className:"goal-queue__objective",title:ee.objective,children:ee.objective}),ee.status==="active"&&e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{co("pause")},title:"暂停目标续跑","aria-label":"暂停目标续跑",children:"⏸"}),m&&e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{co("resume")},title:"恢复目标续跑","aria-label":"恢复目标续跑",children:e.jsx(Mp,{size:12,strokeWidth:2,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{co("clear")},title:"清除目标,停止续跑","aria-label":"清除目标,停止续跑",children:e.jsx(As,{size:12,strokeWidth:2,"aria-hidden":"true"})})]})]})})(),(q.active||q.queued.length>0)&&e.jsxs("div",{className:"goal-queue","aria-label":"目标队列",children:[e.jsxs("div",{className:"goal-queue__header",children:[e.jsx(Si,{size:14,strokeWidth:1.9,"aria-hidden":"true"}),e.jsx("span",{children:"目标"}),e.jsx("span",{className:"goal-queue__count",children:q.queued.length+(q.active?1:0)})]}),q.active&&e.jsxs("div",{className:"goal-queue__row is-active",children:[e.jsx("span",{className:"goal-queue__state",children:"进行中"}),e.jsx("span",{className:"goal-queue__objective",title:q.active.objective,children:q.active.objective}),e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{Ka(q.active.id)},title:"停止当前目标","aria-label":"停止当前目标",children:e.jsx(As,{size:14,strokeWidth:1.8,"aria-hidden":"true"})})]}),q.queued.map((c,m)=>e.jsxs("div",{className:`goal-queue__row is-queued${pi===c.id?" is-dragging":""}`,draggable:!0,onDragStart:()=>hn(c.id),onDragEnd:()=>hn(null),onDragOver:h=>h.preventDefault(),onDrop:()=>{qu(c.id)},children:[e.jsx(gl,{className:"goal-queue__grip",size:14,strokeWidth:1.8,"aria-hidden":"true"}),e.jsxs("span",{className:"goal-queue__state",children:["#",m+1]}),e.jsx("span",{className:"goal-queue__objective",title:c.objective,children:c.objective}),e.jsx("button",{type:"button",className:"goal-queue__action",onClick:()=>{Ka(c.id)},title:"移出目标队列","aria-label":"移出目标队列",children:e.jsx(As,{size:14,strokeWidth:1.8,"aria-hidden":"true"})})]},c.id))]}),(()=>{const c=$.filter(m=>m.isQueued);return c.length===0?null:e.jsx("div",{className:"queued-message-list",children:c.map(m=>{const h=m,y=b===m.id,O=h.content.length>80?h.content.slice(0,80)+"…":h.content;return e.jsxs("div",{className:`queued-message-row${jt===m.id?" is-dragging":""}`,"data-queued-message-id":m.id,onDragOver:P=>{!jt||jt===m.id||(P.preventDefault(),P.dataTransfer.dropEffect="move")},onDrop:P=>{P.preventDefault(),jt&&xo(jt,m.id),zt(null)},children:[e.jsx("button",{type:"button",className:"queued-message-grip",draggable:!y,"aria-label":"拖动调整排队顺序",title:"拖动调整顺序",onDragStart:P=>{zt(m.id),P.dataTransfer.effectAllowed="move",P.dataTransfer.setData("text/plain",m.id)},onDragEnd:()=>zt(null),onKeyDown:P=>{(P.key==="ArrowUp"||P.key==="ArrowDown")&&(P.preventDefault(),Uu(m.id,P.key==="ArrowUp"?-1:1))},onPointerDown:P=>{P.pointerType==="mouse"||y||($t.current={id:m.id,pointerId:P.pointerId},P.currentTarget.setPointerCapture(P.pointerId),zt(m.id))},onPointerMove:P=>{var oe;const he=$t.current;if(!he||he.pointerId!==P.pointerId)return;P.preventDefault();const Z=(oe=document.elementFromPoint(P.clientX,P.clientY))==null?void 0:oe.closest("[data-queued-message-id]"),Ae=Z==null?void 0:Z.dataset.queuedMessageId;Ae&&Ae!==he.id&&xo(he.id,Ae)},onPointerUp:P=>{var he;((he=$t.current)==null?void 0:he.pointerId)===P.pointerId&&($t.current=null,zt(null))},onPointerCancel:()=>{$t.current=null,zt(null)},children:e.jsx(gl,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsxs("div",{className:"queued-message-content",children:[h.agentName&&e.jsxs("span",{className:"queued-message-agent",children:["@",h.agentName]}),y?e.jsx("input",{autoFocus:!0,className:"queued-message-edit-input",value:D,onChange:P=>re(P.target.value),onKeyDown:P=>{P.key==="Enter"&&!P.nativeEvent.isComposing?(P.preventDefault(),Ga(m.id)):P.key==="Escape"&&(P.preventDefault(),mo())},"aria-label":"编辑排队消息内容"}):e.jsx("span",{className:"queued-message-text",title:h.content,children:O})]}),e.jsxs("div",{className:"queued-message-actions",children:[Mn&&e.jsx("button",{type:"button",className:"queued-message-action queued-message-action--accent",onClick:()=>void Va(m.id),disabled:Pe.has(m.id),title:Pe.has(m.id)?"正在引导":"引导到当前对话","aria-label":Pe.has(m.id)?"正在引导排队消息":"引导排队消息到当前对话",children:Pe.has(m.id)?e.jsx(ot,{className:"spin",size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(fl,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"queued-message-action",onClick:()=>void $u(m.id),title:ce===m.id?"已复制":"复制","aria-label":"复制排队消息",children:ce===m.id?e.jsx(Gr,{size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(Ni,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"queued-message-action",onClick:()=>y?Ga(m.id):Ou(m.id),disabled:y&&!D.trim(),title:y?"保存":"编辑","aria-label":y?"保存排队消息":"编辑排队消息",children:y?e.jsx(Gr,{size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(ca,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",className:"queued-message-action queued-message-action--danger",onClick:()=>Hu(m.id),title:"删除","aria-label":"删除排队消息",children:e.jsx(As,{size:15,strokeWidth:1.8,"aria-hidden":"true"})})]})]},m.id)})})})(),e.jsx("div",{ref:io,className:"composer-anchor",style:{position:"relative"},children:e.jsx("div",{className:"composer-shell",style:{display:"flex",flexDirection:"column",gap:0,background:"var(--bg-surface)",borderRadius:14,overflow:"visible"},children:e.jsxs("div",{className:"composer-input-row",style:{display:"flex",alignItems:"center",gap:8,padding:"var(--composer-row-padding)"},children:[e.jsx("input",{ref:Ma,type:"file",multiple:!0,style:{display:"none"},onChange:Tu}),qs.length>0&&e.jsx("div",{style:{display:"flex",alignItems:"center",gap:4,flexShrink:0,flexWrap:"nowrap",overflow:"hidden",maxWidth:300},children:qs.map(c=>e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:3,padding:"2px 7px 2px 6px",borderRadius:20,background:"var(--accent-dim)",border:"1px solid rgba(79,110,247,0.25)",fontSize:12,color:"var(--accent)",flexShrink:0,whiteSpace:"nowrap"},children:[e.jsxs("svg",{width:"9",height:"9",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[e.jsx("circle",{cx:"12",cy:"8",r:"4"}),e.jsx("path",{d:"M20 21a8 8 0 1 0-16 0"})]}),"@",c.name,e.jsx("button",{onClick:()=>Ru(c.id),style:{background:"none",border:"none",color:"rgba(79,110,247,0.55)",cursor:"pointer",padding:0,lineHeight:1,fontSize:12,display:"flex"},children:"✕"})]},c.id))}),e.jsx("textarea",{className:"composer-text-input web-native-composer-textarea",ref:Us,rows:3,value:Kt,onChange:c=>Wa(c.target.value),onBlur:()=>setTimeout(()=>{rs(null),is(null)},120),onKeyDown:Au,placeholder:en==="released"?"已停止在 AgentRoam 中使用;Codex Desktop 最长约 30 分钟后可用":on?cr==="incompatible"?"Codex 版本不兼容":"正在验证会话兼容性":pn?"原客户端使用中,当前只读":mr?sr?"输入要持续推进的目标":xr?"输入下一条排队消息":"提出后续修改要求":"请先在设置中配置 API Key",disabled:!An}),e.jsxs("div",{className:"web-native-composer-toolbar",children:[e.jsxs("div",{className:"web-native-add-wrap",children:[e.jsx("button",{type:"button",className:"web-native-add-button","aria-label":"添加附件、图片或语音","aria-expanded":Vn,onClick:()=>zn(c=>!c),children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round","aria-hidden":"true",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})}),Vn&&e.jsxs("div",{className:"web-native-add-menu",children:[e.jsx("button",{type:"button",onClick:()=>{var c;zn(!1),(c=Ma.current)==null||c.click()},children:"附件 / 图片"}),e.jsx("button",{type:"button",onClick:()=>{zn(!1),Su()},children:"语音输入"})]})]}),e.jsx("button",{type:"button",className:`web-native-runtime-status goal-mode-toggle${sr?" is-active":""}`,"aria-pressed":sr,"aria-label":sr?"关闭目标模式":"开启目标模式",title:sr?"目标模式已开启":"目标模式",onClick:()=>ui(c=>!c),children:e.jsx(Si,{size:18,strokeWidth:1.9,"aria-hidden":"true"})}),e.jsxs("div",{className:"web-native-permission-wrap",ref:Pr,children:[e.jsx("button",{type:"button",className:`web-native-runtime-status web-native-permission-button mode-${Ln}`,"aria-label":`会话权限:${(il=Li.find(c=>c.value===Ln))==null?void 0:il.label}`,"aria-haspopup":"menu","aria-expanded":zr,title:`会话权限:${(ol=Li.find(c=>c.value===Ln))==null?void 0:ol.label}`,disabled:!X||fi,onClick:()=>Lt(c=>!c),children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"}),e.jsx("path",{d:"M12 8v4"}),e.jsx("path",{d:"M12 16h.01"})]})}),zr&&e.jsx("div",{className:"web-native-permission-menu",role:"menu","aria-label":"会话权限模式",children:Li.map(c=>e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":Ln===c.value,className:Ln===c.value?"is-active":"",onClick:()=>{Wu(c.value)},children:[e.jsx("span",{className:"web-native-permission-check","aria-hidden":"true",children:Ln===c.value?"✓":""}),e.jsxs("span",{className:"web-native-permission-copy",children:[e.jsx("strong",{children:c.label}),e.jsx("small",{children:c.description})]})]},c.value))})]}),e.jsx("div",{className:"web-native-context-control",children:e.jsx(pg,{usage:X?W[X]:void 0,contextWindowK:Ue,compact:!0})}),e.jsx("label",{className:`web-native-model-control${it?" web-native-model-control--native":""}`,title:"切换模型",children:it&&Wi(Ne)?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"web-native-model-agent",title:`${xc[Ne]} 会话`,children:[e.jsx(pa,{agentType:Ne,size:14}),e.jsx("span",{className:"web-native-model-agent-name",children:xc[Ne]})]}),Xr&&e.jsxs("select",{"aria-label":"当前模型",title:"切换模型",value:sn,onChange:c=>{rn({model:c.target.value?jf(c.target.value):void 0})},children:[e.jsx("option",{value:"",children:"默认模型"}),Ne==="opencode"?hr.map(c=>e.jsx("optgroup",{label:c.label,children:c.models.map(m=>{const h=oi(m);return e.jsx("option",{value:h,children:m.optionLabel},h)})},c.key)):pt.map(c=>e.jsx("option",{value:c.key,children:c.label},c.key)),Sn.length>0&&e.jsx("optgroup",{label:"设置里的模型",children:Sn.map(c=>e.jsx("option",{value:c.key,children:c.label},c.key))})]})]}):e.jsx("select",{"aria-label":"当前模型",value:_t,disabled:ht.length===0,onChange:c=>{ln(c.target.value)},children:ht.length===0?e.jsx("option",{value:"",children:"未配置模型"}):ht.map(c=>e.jsx("option",{value:c.id,children:c.name||c.modelId},c.id))})}),Ot?e.jsx("button",{type:"button",onClick:go,className:"web-native-stop-button","aria-label":"停止生成",title:"停止生成",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:e.jsx("rect",{x:"6",y:"6",width:"12",height:"12",rx:"2"})})}):it&&gr.length>0?e.jsxs("div",{className:"web-native-effort-wrap",ref:Ut,children:[e.jsx("button",{type:"button",className:"web-native-effort-button","aria-expanded":ze,"aria-label":`推理强度:${qt?To[qt]:"默认"}`,title:`推理强度:${qt?To[qt]:"默认"}(点击切换)`,onClick:()=>ge(c=>!c),children:e.jsxs("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M9.5 4.5A3.5 3.5 0 0 0 6 8v1a3 3 0 0 0-2 2.83V14a3 3 0 0 0 3 3h.25A3.75 3.75 0 0 0 11 20.75V3.25A3.75 3.75 0 0 0 9.5 4.5Z"}),e.jsx("path",{d:"M14.5 4.5A3.5 3.5 0 0 1 18 8v1a3 3 0 0 1 2 2.83V14a3 3 0 0 1-3 3h-.25A3.75 3.75 0 0 1 13 20.75V3.25a3.75 3.75 0 0 1 1.5 1.25Z"})]})}),ze&&e.jsxs("div",{className:"web-native-effort-menu",role:"menu","aria-label":"推理强度",children:[e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":!qt,className:qt?void 0:"is-active",onClick:()=>{rn({reasoningEffort:void 0}),ge(!1)},children:[e.jsx("span",{className:"web-native-effort-check","aria-hidden":"true",children:qt?"":"✓"}),"默认"]}),gr.map(c=>e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":qt===c,className:qt===c?"is-active":void 0,onClick:()=>{rn({reasoningEffort:c}),ge(!1)},children:[e.jsx("span",{className:"web-native-effort-check","aria-hidden":"true",children:qt===c?"✓":""}),To[c]]},c))]})]}):it?e.jsxs("span",{className:"web-native-agent-status",role:"status","aria-label":"Agent 空闲",title:"Agent 空闲",children:[e.jsxs("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M9.5 4.5A3.5 3.5 0 0 0 6 8v1a3 3 0 0 0-2 2.83V14a3 3 0 0 0 3 3h.25A3.75 3.75 0 0 0 11 20.75V3.25A3.75 3.75 0 0 0 9.5 4.5Z"}),e.jsx("path",{d:"M14.5 4.5A3.5 3.5 0 0 1 18 8v1a3 3 0 0 1 2 2.83V14a3 3 0 0 1-3 3h-.25A3.75 3.75 0 0 1 13 20.75V3.25a3.75 3.75 0 0 1 1.5 1.25Z"})]}),e.jsx("span",{"aria-hidden":"true"})]}):e.jsxs("div",{className:"web-native-effort-wrap",ref:ms,children:[e.jsx("button",{type:"button",className:"web-native-effort-button","aria-expanded":yr,"aria-label":`推理强度:${mc[Dt]}`,title:`推理强度:${mc[Dt]}(点击切换)`,onClick:()=>Je(c=>!c),children:e.jsxs("svg",{width:"19",height:"19",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M9.5 4.5A3.5 3.5 0 0 0 6 8v1a3 3 0 0 0-2 2.83V14a3 3 0 0 0 3 3h.25A3.75 3.75 0 0 0 11 20.75V3.25A3.75 3.75 0 0 0 9.5 4.5Z"}),e.jsx("path",{d:"M14.5 4.5A3.5 3.5 0 0 1 18 8v1a3 3 0 0 1 2 2.83V14a3 3 0 0 1-3 3h-.25A3.75 3.75 0 0 1 13 20.75V3.25a3.75 3.75 0 0 1 1.5 1.25Z"})]})}),yr&&e.jsx("div",{className:"web-native-effort-menu",role:"menu","aria-label":"推理强度",children:eu.map(c=>e.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":Dt===c.value,className:Dt===c.value?"is-active":void 0,onClick:()=>{$n("reasoningEffort",c.value),cn(),Je(!1)},children:[e.jsx("span",{className:"web-native-effort-check","aria-hidden":"true",children:Dt===c.value?"✓":""}),c.label]},c.value))})]}),e.jsx("button",{type:"button",onClick:Xa,disabled:!An||Bs>0||!Kt.trim(),className:"web-native-send-button","aria-label":xr?"排队发送":"发送",title:xr?"排队发送":"发送",children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.4",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M12 19V5M5 12l7-7 7 7"})})})]})]})})}),e.jsxs("div",{className:"chat-composer-hint",style:{textAlign:"center",marginTop:7,fontSize:11,color:"var(--text-muted)",letterSpacing:"0.03em",opacity:.6},children:["Enter 发送",sr?"目标":xr?"(排队)":""," · @智能体(可多选)· /技能 · Shift+Enter 换行",za?" · 🎤 正在聆听…":""]})]}),e.jsx(Gg,{image:Yi,onClose:()=>Dr(null)}),Br&&Vs!==null&&Da.length>0&&On.createPortal(e.jsxs("div",{style:{position:"fixed",bottom:window.innerHeight-Br.top+8,left:Br.left,width:Br.width,background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:10,boxShadow:"var(--shadow-md)",overflow:"hidden",zIndex:99999},children:[e.jsx("div",{style:{padding:"6px 10px 4px",fontSize:10,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em"},children:"智能体"}),Da.map(c=>e.jsxs("button",{onMouseDown:m=>{m.preventDefault(),Iu(c)},style:{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",border:"none",background:"transparent",cursor:"pointer"},onMouseEnter:m=>{m.currentTarget.style.background="var(--accent-dim)"},onMouseLeave:m=>{m.currentTarget.style.background="transparent"},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:600,color:"var(--text-primary)"},children:["@",c.name]}),c.description&&e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:1},children:c.description})]},c.id))]}),document.body),Br&&ss!==null&&uo.length>0&&On.createPortal(e.jsxs("div",{style:{position:"fixed",bottom:window.innerHeight-Br.top+8,left:Br.left,width:Br.width,background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:10,boxShadow:"var(--shadow-md)",zIndex:99999,display:"flex",flexDirection:"column",maxHeight:320},children:[e.jsxs("div",{style:{padding:"6px 10px 4px",fontSize:10,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",flexShrink:0},children:["技能 (",uo.length,")"]}),e.jsx("div",{style:{overflowY:"auto",flex:1},children:uo.map(c=>e.jsxs("button",{onMouseDown:m=>{m.preventDefault(),Eu(c)},style:{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",border:"none",background:"transparent",cursor:"pointer"},onMouseEnter:m=>{m.currentTarget.style.background="var(--accent-dim)"},onMouseLeave:m=>{m.currentTarget.style.background="transparent"},children:[e.jsxs("div",{style:{fontSize:13,fontWeight:600,color:"var(--text-primary)"},children:["/",c.name]}),c.description&&e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.description})]},c.name))})]}),document.body)]})}function No(t,n,r="auto"){const s=t.getBoundingClientRect(),i=n.getBoundingClientRect(),o=t.scrollTop+i.top-s.top-Math.max(0,(t.clientHeight-i.height)/2);t.scrollTo({top:Math.max(0,o),behavior:r})}const Ri=4,Rm=4e6,Em=8,Mm=.12;function Am(t,n,r=Mm){if(n<=0)return[];const s=Array.from({length:n},(u,f)=>{const p=Number(t[f]);return Number.isFinite(p)&&p>0?p:1}),i=s.reduce((u,f)=>u+f,0),l=s.map(u=>u/i).map(u=>Math.max(u,r)),d=l.reduce((u,f)=>u+f,0);return l.map(u=>u/d)}function Tm(t,n,r,s=Em){if(n<=1||t.width<=0||t.height<=0)return t.width<=0||t.height<=0?[]:[{x:Math.round(t.x),y:Math.round(t.y),width:Math.round(t.width),height:Math.round(t.height)}];const i=Math.min(n,6),o=s*(i-1),l=t.width-o;if(l<=0)return[];const d=Am(r,i),u=[];let f=t.x;for(let p=0;p<i;p+=1){const x=p===i-1?t.x+t.width-f:Math.floor(l*d[p]);u.push({x:Math.round(f),y:Math.round(t.y),width:Math.round(x),height:Math.round(t.height)}),f+=x+s}return u}function Nm({siteId:t,name:n,onSetup:r}){const s=window.agentApi,[i,o]=a.useState(null),[l,d]=a.useState({connected:!1,tabs:[]}),[u,f]=a.useState(""),[p,v]=a.useState(!1),[x,w]=a.useState(Date.now()),[j,E]=a.useState(!0),S=a.useRef(null),C=!l.paused&&l.compatible!==!1&&l.tabs.some(M=>M.siteId===t);a.useEffect(()=>{let M=!1,H=!1,L=!1;s.hubChromeStatus().then(R=>{!M&&!H&&d(R)}),typeof s.hubChromeConversation!="function"?f("请重启 AI Hub 桌面端以启用消息面板"):s.hubChromeConversation(t).then(R=>{!M&&!L&&o(R)});const T=s.onHubChromeEvent(R=>{R.type==="chrome-conversation"&&R.conversation.siteId===t&&(L=!0,o($=>!$||R.conversation.revision>$.revision?R.conversation:$),f("")),R.type==="chrome-status"&&(H=!0,d(R.status),R.status.tabs.some($=>$.siteId===t)||(o(null),f(""))),R.type==="chrome-page-error"&&R.siteId===t&&f(R.error)}),A=setInterval(()=>w(Date.now()),1e3);return()=>{M=!0,T(),clearInterval(A)}},[s,t]),a.useLayoutEffect(()=>{j&&S.current&&(S.current.scrollTop=S.current.scrollHeight)},[i==null?void 0:i.revision,j]);const k=C&&!!i&&x-i.receivedAt>6e3,z=l.paused?"Chrome 网页连接已暂停,点击下方按钮即可恢复。":l.connected&&l.compatible===!1?"请从「连接 Chrome」加载新版自动连接扩展。":C?i?i.generating?"正在回复…":i.composerAvailable?"已同步 · 从下方输入框发送消息":"未找到输入框,请在 Chrome 检查页面":"正在读取网页对话…":"在日常 Chrome 中打开并登录此站点,扩展会自动接入;若已暂停,请在扩展中恢复自动连接。";return e.jsxs("div",{"data-aihub-native-pane":t,style:{position:"absolute",inset:0,display:"flex",flexDirection:"column",minWidth:0},children:[e.jsx("div",{role:"status",style:{padding:"10px 16px",fontSize:12,lineHeight:1.6,color:"var(--text-secondary)",borderBottom:"1px solid var(--border-subtle)"},children:z}),e.jsx("div",{ref:S,onScroll:()=>{const M=S.current;M&&E(M.scrollHeight-M.scrollTop-M.clientHeight<60)},style:{flex:1,minHeight:0,overflow:"auto",padding:"18px 16px",overflowWrap:"anywhere"},children:C?i!=null&&i.messages.length?i.messages.map(M=>e.jsxs("article",{"data-message-id":M.id,style:{marginBottom:24,padding:M.role==="user"?"12px 14px":"0 2px",borderRadius:12,background:M.role==="user"?"var(--bg-deep)":"transparent"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:8,fontSize:12,color:"var(--text-muted)"},children:[e.jsx("strong",{children:M.role==="user"?"你":n}),e.jsx("button",{className:"ui-icon-button ui-icon-button--auto","aria-label":`复制 ${M.role==="user"?"消息":n+" 回复"}`,style:{padding:"2px 5px",fontSize:11},onClick:()=>{navigator.clipboard.writeText(M.content).catch(()=>f("未能复制,请选择文字复制"))},children:"复制"})]}),e.jsx("div",{style:{fontSize:15,lineHeight:1.8,whiteSpace:"pre-wrap",color:"var(--text-primary)"},children:Zd(M.content)})]},`${i.conversationId}:${M.id}`)):e.jsx("p",{style:{margin:"32px 0",color:"var(--text-muted)",fontSize:15,lineHeight:1.8},children:"连接后会显示当前网页对话。可以在下方输入消息,也可以在 Chrome 中继续聊天。"}):e.jsxs("div",{style:{display:"grid",gap:14,paddingTop:36,textAlign:"center",justifyItems:"center"},children:[e.jsx("strong",{style:{fontSize:18},children:l.paused?`${n} 已暂停`:`连接 ${n}`}),e.jsx("span",{style:{fontSize:14,color:"var(--text-secondary)",lineHeight:1.7},children:l.paused?"取消 Chrome 的调试提示也会暂停连接,无需重新登录。":"登录态保留在 Chrome,回复会以文字显示在这里。"}),l.paused&&e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",disabled:p,style:{padding:"8px 12px",color:"var(--accent)"},onClick:async()=>{v(!0),f("");try{d(await s.hubChromeResume())}catch(M){f(M instanceof Error?M.message:"恢复连接失败,请检查 Chrome 扩展")}finally{v(!1)}},children:p?"正在恢复…":"恢复全部 Chrome 连接"}),e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",style:{padding:"8px 12px"},onClick:()=>{s.hubOpenChrome(t).catch(()=>f("无法打开 Chrome,请检查是否已安装"))},children:"登录 / 打开原网页"}),e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",style:{padding:"8px 12px"},onClick:r,children:"连接设置"})]})}),!j&&e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",style:{alignSelf:"center",padding:"7px 12px",margin:8},onClick:()=>E(!0),children:"回到最新回复 ↓"}),(u||k)&&e.jsx("div",{role:u?"alert":"status",title:u||"暂未收到网页更新,请检查 Chrome 标签页或扩展连接;不代表 AI 已停止回答",style:{padding:"6px 16px",fontSize:12,lineHeight:1.6,whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",color:u?"var(--danger)":"var(--text-muted)"},children:u||"同步暂未更新"})]})}function _m({onClose:t}){const n=window.agentApi,[r,s]=a.useState(""),[i,o]=a.useState(!1),[l,d]=a.useState(""),[u,f]=a.useState(!1);a.useEffect(()=>{let v=!0;n.hubChromeStatus().then(w=>{v&&f(w.connected&&w.compatible!==!1)}).catch(()=>{v&&s("暂时无法检测插件连接,请稍后重试")});const x=n.onHubChromeEvent(w=>{w.type==="chrome-status"&&f(w.status.connected&&w.status.compatible!==!1)});return()=>{v=!1,x()}},[n]);const p=async()=>{o(!0),s("");try{const v=await n.hubChromeInstallExtension();d(v.path),s(v.browserOpened?"已打开 Chrome 扩展管理页,插件目录路径已复制。":"未能打开 Chrome。请先安装或打开 Google Chrome,再进入 chrome://extensions;插件目录路径已复制。")}catch{s("未能准备插件,请确认桌面端已启动,稍后重试。")}finally{o(!1)}};return e.jsxs("div",{"data-aihub-chrome-setup":"",style:{flexShrink:0,padding:"12px 18px",background:"var(--bg-elevated)",borderBottom:"1px solid var(--border-subtle)",fontSize:12},children:[e.jsxs("div",{style:{display:"flex",gap:12,alignItems:"center",marginBottom:8},children:[e.jsx("strong",{children:"连接日常 Google Chrome"}),e.jsx("span",{role:"status",children:u?"扩展已连接":"等待扩展连接"}),e.jsx("button",{className:"ui-icon-button ui-icon-button--auto",style:{marginLeft:"auto"},onClick:t,children:"收起"})]}),e.jsx("p",{style:{margin:"0 0 8px",lineHeight:1.7},children:"插件已随桌面端附带,无需另行下载。首次加载需要在 Chrome 中确认;加载后自动连接,连接成功后此引导会自动收起。已安装时刷新 AI Hub 扩展即可更新。"}),e.jsxs("ol",{style:{margin:0,paddingLeft:20,lineHeight:1.9},children:[e.jsx("li",{children:"点击「安装浏览器插件」,在打开的 Chrome 扩展管理页开启「开发者模式」。"}),e.jsx("li",{children:"选择「加载已解压的扩展程序」,选中 ai-hub-chrome-extension 文件夹。macOS 文件选择窗口可按 ⌘⇧G,粘贴已复制的路径并打开。"}),e.jsx("li",{children:"在同一个 Chrome 中完成网站登录,即可回到 AI Hub 查看回复并同步发送。取消 Chrome 顶部的调试提示会暂停连接;在 AI Hub 点击「恢复全部 Chrome 连接」即可继续。"})]}),e.jsxs("div",{style:{display:"flex",gap:10,alignItems:"center",marginTop:8},children:[e.jsx("button",{type:"button",disabled:i,className:"ui-icon-button ui-icon-button--auto",onClick:()=>void p(),style:{padding:"5px 10px"},children:i?"正在打开…":"安装浏览器插件"}),e.jsx("button",{type:"button",className:"ui-icon-button ui-icon-button--auto",onClick:()=>{n.hubChromeRevealExtension().catch(()=>s("未能打开扩展目录"))},style:{padding:"5px 10px"},children:"打开插件文件夹"}),r&&e.jsx("span",{role:"status",children:r})]}),l&&e.jsxs("p",{style:{margin:"8px 0 0",overflowWrap:"anywhere",userSelect:"text"},children:["插件目录:",l]})]})}const zm=["chatgpt","gemini","grok"];function Ei(t){return zm.includes(t)}const Lm=52,_o=30,Pm=4;function Dm(t,n){return t.includes(n)?t.length>1?t.filter(r=>r!==n):t:t.length<Pm?[...t,n]:t}function Wm(t){return(t.trim()[0]||"?").toUpperCase()}function yc(t){try{const n=new URL(t);return n.protocol==="http:"||n.protocol==="https:"}catch{return!1}}function Fm({onExit:t,conversationId:n}){const r=typeof window<"u"?window.agentApi:void 0,s=typeof(r==null?void 0:r.hubGetConfig)=="function",[i,o]=a.useState([]),[l,d]=a.useState([]),[u,f]=a.useState([]),[p,v]=a.useState(null),[x,w]=a.useState({}),[j,E]=a.useState({}),[S,C]=a.useState({}),[k,z]=a.useState(""),[M,H]=a.useState([]),[L,T]=a.useState(""),[A,R]=a.useState(!1),$=a.useRef(null),F=a.useRef(null),[Ee,Qe]=a.useState(!1),[ae,ke]=a.useState([]),[De,Ie]=a.useState(!1),[We,at]=a.useState(!1),[Ge,ne]=a.useState(""),[be,Ye]=a.useState(""),[W,te]=a.useState(!1),[G,le]=a.useState([]);a.useEffect(()=>{if(!(r!=null&&r.hubChromeStatus))return;let B=!1,Y=!1;const q=ee=>{if(B)return;const Ke=ee.connected&&ee.compatible!==!1;le(Ke?ee.tabs.map(dt=>dt.siteId):[]),Ke?te(!1):Y||te(!0),Y=!0};r.hubChromeStatus().then(q).catch(()=>{!B&&!Y&&(Y=!0,te(!0))});const se=r.onHubChromeEvent(ee=>{ee.type==="chrome-status"&&q(ee.status)});return()=>{B=!0,se()}},[r]);const pe=a.useRef(null),ye=a.useRef(null);a.useRef(0),a.useLayoutEffect(()=>{const B=F.current;B&&(B.style.height="32px",k&&(B.style.height=`${Math.max(32,Math.min(B.scrollHeight,120))}px`))},[k,l.length]);const we=async B=>{if(!(Ee||A)){R(!0),T("");try{if(B.length+M.length>Ri)throw new Error(`最多添加 ${Ri} 张图片`);const Y=await Promise.all(B.map(async q=>{if(!/^image\/(png|jpeg|webp)$/.test(q.type))throw new Error("请选择 PNG、JPEG 或 WebP 图片");if(q.size*4/3+32>Rm)throw new Error("单张图片不能超过约 3 MB");return new Promise((se,ee)=>{const Ke=new FileReader;Ke.onload=()=>se(String(Ke.result)),Ke.onerror=()=>ee(new Error("图片读取失败,请重试")),Ke.readAsDataURL(q)})}));H(q=>[...q,...Y].slice(0,Ri))}catch(Y){T(Y instanceof Error?Y.message:"图片读取失败")}finally{R(!1)}}},Te=a.useMemo(()=>p?Tm(p,l.length,u):[],[p,l.length,u]);a.useEffect(()=>{if(!s||Te.length===0)return;const B=l.map((Y,q)=>{const se=Te[q];return{siteId:Y,...n?{conversationId:n}:{},x:se.x,y:se.y+_o,width:se.width,height:Math.max(se.height-_o,0)}});r==null||r.hubSetBounds(B)},[s,r,Te,l,n]),a.useEffect(()=>{if(s)for(const B of l)r==null||r.hubOpenSite(B,n??void 0)},[s,r,l,n]),a.useEffect(()=>{if(!s)return;const B=pe.current;if(!B)return;const Y=()=>{const ee=B.getBoundingClientRect();v(Ke=>Ke&&Math.abs(Ke.x-ee.x)<.5&&Math.abs(Ke.y-ee.y)<.5&&Math.abs(Ke.width-ee.width)<.5&&Math.abs(Ke.height-ee.height)<.5?Ke:{x:ee.x,y:ee.y,width:ee.width,height:ee.height})},q={current:0},se=new ResizeObserver(()=>{cancelAnimationFrame(q.current),q.current=requestAnimationFrame(Y)});return se.observe(B),Y(),()=>{se.disconnect(),cancelAnimationFrame(q.current)}},[s,We]),a.useEffect(()=>{if(!De)return;const B=q=>{var se;(se=ye.current)!=null&&se.contains(q.target)||Ie(!1)},Y=()=>Ie(!1);return document.addEventListener("pointerdown",B),window.addEventListener("blur",Y),()=>{document.removeEventListener("pointerdown",B),window.removeEventListener("blur",Y)}},[De]),a.useEffect(()=>{if(!s||!r)return;let B=!1;r.hubGetConfig().then(q=>{B||(o(q.sites),d(se=>se.length>0?se:q.sites.slice(0,1).map(ee=>ee.id)))});const Y=r.onHubEvent(q=>{q.type==="load-failed"?(w(se=>({...se,[q.siteId]:q.errorCode??-1})),E(se=>({...se,[q.siteId]:!1}))):q.type==="loaded"?(w(se=>{if(!(q.siteId in se))return se;const ee={...se};return delete ee[q.siteId],ee}),E(se=>({...se,[q.siteId]:!1}))):q.type==="loading"?(E(se=>({...se,[q.siteId]:!0})),C(se=>{if(!(q.siteId in se))return se;const ee={...se};return delete ee[q.siteId],ee})):q.type==="google-auth-external"&&C(se=>({...se,[q.siteId]:!0}))});return()=>{B=!0,Y(),r.hubHideAll()}},[s,r]),a.useEffect(()=>{const B=Math.max(l.length,0);f(Y=>Y.length===B?Y:Array.from({length:B},()=>B>0?1/B:0))},[l.length]);const ut=a.useCallback(B=>{d(Y=>Dm(Y,B))},[]),lt=a.useCallback(B=>{w(Y=>{const q={...Y};return delete q[B],q}),r==null||r.hubReload(B,n??void 0),r==null||r.hubOpenSite(B,n??void 0)},[r,n]),st=a.useCallback(B=>{l.length<=1||(r==null||r.hubCloseSite(B,n??void 0),d(Y=>Y.filter(q=>q!==B)))},[r,l.length,n]),Tt=a.useCallback(async()=>{const B=k.trim();if(!(!B&&M.length===0||!r||Ee||A||l.length===0)){Qe(!0);try{const Y=await r.hubBroadcast(B,l,M),q=Y.map(se=>({...se,at:Date.now()}));ke(q),Y.length>0&&Y.every(se=>se.ok)&&(z(""),H([]),T("")),setTimeout(()=>{ke(se=>se.filter(ee=>!ee.ok||Date.now()-ee.at<8e3))},8200)}catch(Y){T(Y instanceof Error?Y.message:"发送失败,请重试")}finally{Qe(!1)}}},[r,k,M,A,Ee,l]),He=a.useCallback(async()=>{if(!r||!yc(be))return;const B=be.trim(),Y=Ge.trim()||new URL(B).hostname,q={id:`custom-${Math.random().toString(36).slice(2,10)}`,name:Y,url:B,adapter:"generic"},se=await r.hubSetConfig({version:1,sites:[...i,q]});o(se.sites),ne(""),Ye(""),at(!1)},[r,Ge,be,i]),Nt=a.useCallback(async B=>{if(!r||i.length<=1)return;r.hubCloseSite(B,n??void 0);const Y=await r.hubSetConfig({version:1,sites:i.filter(q=>q.id!==B)});o(Y.sites),d(q=>{const se=q.filter(ee=>ee!==B);return se.length>0?se:Y.sites.slice(0,1).map(ee=>ee.id)})},[r,i,n]),ct=a.useCallback((B,Y)=>{Y.preventDefault();const q=Te.length,se=q>1?8:0,ee=((p==null?void 0:p.width)??0)-se*(q-1);if(ee<=0)return;const Ke=Y.clientX,dt=[...u],Jt=Te[B].width,Ze=dt[B]+dt[B+1],$e=rt=>{const Pt=rt.clientX-Ke,ht=80,_t=Ze*ee,ln=Math.min(Math.max(Jt+Pt,ht),_t-ht),vn=[...dt];vn[B]=ln/ee,vn[B+1]=(_t-ln)/ee,f(vn)},Gt=()=>{window.removeEventListener("pointermove",$e),window.removeEventListener("pointerup",Gt)};window.addEventListener("pointermove",$e),window.addEventListener("pointerup",Gt)},[u,Te,p]);return s?e.jsxs("div",{style:{position:"absolute",inset:0,zIndex:30,display:"flex",flexDirection:"column",background:"var(--bg-workspace)"},children:[e.jsxs("div",{className:"aihub-topbar",style:{height:Lm,display:"flex",alignItems:"center",gap:10,padding:"0 14px",borderBottom:"1px solid var(--border-subtle)",WebkitAppRegion:"drag"},children:[e.jsx("button",{type:"button",onClick:t,title:"返回会话列表","aria-label":"返回会话列表",className:"ui-icon-button",style:{WebkitAppRegion:"no-drag",width:34,height:34,flexShrink:0},children:e.jsx(oa,{size:18,"aria-hidden":"true"})}),e.jsx("strong",{style:{fontSize:14,color:"var(--text-secondary)"},children:"AI Hub"}),e.jsx("button",{type:"button",className:"ui-icon-button ui-icon-button--auto",onClick:()=>te(B=>!B),style:{WebkitAppRegion:"no-drag",marginLeft:"auto",padding:"5px 10px"},children:"连接 Chrome"})]}),W&&e.jsx(_m,{onClose:()=>te(!1)}),e.jsxs("div",{ref:pe,style:{flex:1,position:"relative",overflow:"hidden",minHeight:0},children:[Te.map((B,Y)=>{const q=l[Y],se=i.find(Ke=>Ke.id===q),ee=q in x;return e.jsxs("div",{"data-aihub-pane":q,style:{position:"absolute",left:B.x-((p==null?void 0:p.x)??0),top:B.y-((p==null?void 0:p.y)??0),width:B.width,height:B.height,display:"flex",flexDirection:"column",borderRight:Y<Te.length-1?"1px solid var(--border-subtle)":void 0},children:[e.jsxs("div",{style:{height:_o,display:"flex",alignItems:"center",gap:6,padding:"0 8px",borderBottom:"1px solid var(--border-subtle)",fontSize:12,color:"var(--text-secondary)"},children:[e.jsx("span",{"aria-hidden":"true",style:{width:8,height:8,borderRadius:"50%",background:Ei(q)?G.includes(q)?"var(--success)":"var(--text-muted)":ee?"#f7768e":j[q]?"var(--accent-glow)":"#9ece6a",flexShrink:0}}),e.jsx("span",{style:{flex:1,minWidth:40,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:(se==null?void 0:se.name)??q}),S[q]&&e.jsx("span",{title:"Google 登录已在系统浏览器打开,登录状态不会同步回 AI Hub。如需继续内嵌使用,请选择邮箱登录。","aria-label":"Google 登录受限",style:{flexShrink:0,fontSize:10,padding:"1px 6px",borderRadius:999,color:"#f7768e",border:"1px solid currentColor",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:180},children:"Google 登录已转至浏览器,内嵌请用邮箱"}),Ei(q)&&e.jsx("button",{type:"button","aria-label":`打开 ${(se==null?void 0:se.name)??q} Chrome 页面`,title:"在日常 Chrome 中登录或查看页面",className:"ui-icon-button ui-icon-button--auto",onClick:()=>{r.hubOpenChrome(q).catch(()=>te(!0))},style:{padding:"2px 6px",fontSize:11},children:"Chrome ↗"}),e.jsx("button",{type:"button",title:"刷新","aria-label":`刷新 ${(se==null?void 0:se.name)??q}`,onClick:()=>lt(q),className:"ui-icon-button",style:{padding:2},children:"⟳"}),l.length>1&&e.jsx("button",{type:"button",title:"关闭页面","aria-label":`关闭 ${(se==null?void 0:se.name)??q}`,onClick:()=>st(q),className:"ui-icon-button",style:{padding:2},children:"×"})]}),e.jsxs("div",{style:{flex:1,position:"relative",background:"var(--bg-surface)"},children:[Ei(q)&&e.jsx(Nm,{siteId:q,name:(se==null?void 0:se.name)??q,onSetup:()=>te(!0)}),!Ei(q)&&ee&&e.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center"},children:e.jsxs("div",{style:{textAlign:"center",display:"grid",gap:10,color:"var(--text-muted)",fontSize:12},children:[e.jsxs("span",{children:["页面加载失败(",x[q],")"]}),e.jsx("button",{type:"button",onClick:()=>lt(q),className:"ui-icon-button ui-icon-button--auto",style:{justifySelf:"center",padding:"5px 12px"},children:"重试"})]})})]}),Y<Te.length-1&&e.jsx("div",{"data-aihub-divider":Y,onPointerDown:Ke=>ct(Y,Ke),title:"拖动调整宽度",style:{position:"absolute",top:0,bottom:0,right:-5,width:10,cursor:"col-resize",zIndex:5}})]},q)}),Te.length===0&&e.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",color:"var(--text-muted)",fontSize:13},children:"从输入框选择一个 AI 站点"})]}),e.jsxs("div",{style:{borderTop:"1px solid var(--border-subtle)",padding:"8px 12px 10px",display:"flex",flexDirection:"column",gap:8,background:"var(--bg-surface)"},children:[e.jsxs("div",{ref:ye,style:{position:"relative",display:"flex",flexDirection:"column",gap:8},children:[De&&e.jsxs("div",{role:"listbox","aria-label":"选择要发送的 AI 站点","data-aihub-site-picker":"",style:{width:"min(320px, 100%)",maxHeight:280,overflowY:"auto",padding:4,border:"1px solid var(--border-default)",borderRadius:8,background:"var(--bg-workspace)",boxShadow:"0 -8px 24px rgba(0, 0, 0, 0.12)"},children:[i.map(B=>{const Y=l.includes(B.id),q=B.id.startsWith("custom-");return e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:4},children:[e.jsxs("button",{type:"button",role:"option","aria-selected":Y,onClick:()=>ut(B.id),style:{minWidth:0,flex:1,display:"flex",alignItems:"center",gap:8,padding:"8px 9px",border:0,borderRadius:6,background:Y?"var(--bg-glass)":"transparent",color:"var(--text-secondary)",cursor:"pointer",textAlign:"left"},children:[e.jsx("span",{"aria-hidden":"true",style:{width:20,height:20,display:"grid",placeItems:"center",borderRadius:"50%",border:`1px solid ${Y?"var(--accent)":"var(--border-default)"}`,background:Y?"var(--accent)":"transparent",color:Y?"var(--bg-workspace)":"transparent",flexShrink:0},children:e.jsx(Gr,{size:13,strokeWidth:2.5})}),e.jsx("span",{"aria-hidden":"true",style:{width:24,height:24,display:"grid",placeItems:"center",borderRadius:6,background:"var(--accent-glow)",fontSize:12,fontWeight:600,flexShrink:0},children:Wm(B.name)}),e.jsx("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",fontSize:13},children:B.name})]}),q&&e.jsx("button",{type:"button",title:`删除站点 ${B.name}`,"aria-label":`删除站点 ${B.name}`,onClick:()=>void Nt(B.id),className:"ui-icon-button",style:{width:30,height:30,padding:0,flexShrink:0},children:e.jsx(As,{size:14,"aria-hidden":"true"})})]},B.id)}),e.jsx("div",{style:{height:1,margin:"4px 6px",background:"var(--border-subtle)"}}),We?e.jsxs("div",{style:{display:"grid",gap:6,padding:6},children:[e.jsx("input",{value:Ge,onChange:B=>ne(B.target.value),placeholder:"名称(可选)",style:{minWidth:0,padding:"7px 8px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-secondary)",fontSize:12}}),e.jsx("input",{value:be,onChange:B=>Ye(B.target.value),placeholder:"https://...",style:{minWidth:0,padding:"7px 8px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-secondary)",fontSize:12}}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{type:"button",onClick:()=>void He(),disabled:!yc(be),className:"ui-icon-button ui-icon-button--auto",style:{padding:"5px 10px",fontSize:12},children:"添加"}),e.jsx("button",{type:"button",onClick:()=>at(!1),className:"ui-icon-button ui-icon-button--auto",style:{padding:"5px 10px",fontSize:12},children:"取消"})]})]}):e.jsxs("button",{type:"button",onClick:()=>at(!0),className:"ui-icon-button ui-icon-button--auto",style:{width:"100%",justifyContent:"flex-start",gap:7,padding:"7px 9px",fontSize:12},children:[e.jsx(Ko,{size:14,"aria-hidden":"true"}),"添加站点"]})]}),e.jsxs("div",{"data-aihub-composer":"",style:{display:"flex",alignItems:"center",gap:8,minHeight:48,padding:"6px 8px",borderRadius:8,border:"1px solid var(--border-default)",background:"var(--bg-workspace)"},children:[e.jsxs("button",{type:"button",onClick:()=>Ie(B=>!B),"aria-haspopup":"listbox","aria-expanded":De,"aria-label":"选择 AI 站点",title:"选择 AI 站点",className:"ui-icon-button ui-icon-button--auto",style:{height:34,gap:5,padding:"0 10px",fontSize:12,whiteSpace:"nowrap",flexShrink:0},children:[l.length," 个 AI",e.jsx(Pi,{size:14,"aria-hidden":"true",style:{transform:De?"rotate(180deg)":void 0}})]}),e.jsx("input",{ref:$,type:"file",accept:"image/png,image/jpeg,image/webp",multiple:!0,hidden:!0,onChange:B=>{const Y=Array.from(B.target.files??[]);B.target.value="",we(Y)}}),e.jsx("button",{type:"button","aria-label":"添加图片附件",title:"添加图片附件(也可粘贴截图)",disabled:Ee||A||M.length>=Ri,onClick:()=>{var B;return(B=$.current)==null?void 0:B.click()},className:"ui-icon-button",style:{width:34,height:34,padding:0,flexShrink:0},children:e.jsx(Ip,{size:17,"aria-hidden":"true"})}),e.jsx("textarea",{ref:F,"aria-label":"发送给选中的 AI",disabled:Ee,value:k,onChange:B=>z(B.target.value),onPaste:B=>{const Y=Array.from(B.clipboardData.files);Y.length!==0&&(B.preventDefault(),we(Y))},onKeyDown:B=>{B.nativeEvent.isComposing||B.nativeEvent.keyCode===229||(B.key==="Enter"&&(!B.shiftKey||B.metaKey||B.ctrlKey)?(B.preventDefault(),Tt()):B.key==="Escape"&&De&&(B.preventDefault(),Ie(!1)))},rows:1,placeholder:`一次输入,发到 ${l.length} 个选中的 AI(Enter 发送,Shift+Enter 换行)`,style:{flex:1,minWidth:0,height:32,minHeight:32,maxHeight:120,boxSizing:"border-box",resize:"none",padding:"4px 2px",border:0,outline:"none",boxShadow:"none",background:"transparent",color:"var(--text-primary)",fontSize:13,lineHeight:1.5,textAlign:k?"left":"center"}}),e.jsx("button",{type:"button",onClick:()=>void Tt(),disabled:!k.trim()&&M.length===0||Ee||A||l.length===0,title:"同步发送(Enter)","aria-label":"同步发送",className:"ui-icon-button",style:{width:36,height:36,padding:0,borderRadius:"50%",background:(k.trim()||M.length>0)&&!Ee?"var(--accent)":"var(--bg-glass)",color:(k.trim()||M.length>0)&&!Ee?"var(--bg-workspace)":"var(--text-muted)",flexShrink:0},children:e.jsx(Np,{size:16,"aria-hidden":"true"})})]})]}),M.length>0&&e.jsx("div",{"aria-label":"待发送图片",style:{display:"flex",gap:8,flexWrap:"wrap"},children:M.map((B,Y)=>e.jsxs("div",{style:{position:"relative",width:56,height:56},children:[e.jsx("img",{src:B,alt:`附件 ${Y+1}`,style:{width:"100%",height:"100%",objectFit:"cover",borderRadius:6}}),e.jsx("button",{type:"button","aria-label":`移除附件 ${Y+1}`,disabled:Ee,onClick:()=>H(q=>q.filter((se,ee)=>ee!==Y)),className:"ui-icon-button",style:{position:"absolute",top:0,right:0,padding:2,background:"var(--bg-workspace)"},children:e.jsx(Tr,{size:12})})]},`${Y}-${B.length}`))}),L&&e.jsx("div",{role:"alert",style:{fontSize:12,color:"var(--text-secondary)",textAlign:"center"},children:L}),ae.length>0&&e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center",minHeight:18},children:ae.map(B=>{var Y;return e.jsx("span",{role:"status",style:{fontSize:11,padding:"3px 10px",borderRadius:999,color:B.ok?"#9ece6a":"#f7768e",background:"var(--bg-glass)",whiteSpace:"normal",overflowWrap:"anywhere"},children:(((Y=i.find(q=>q.id===B.siteId))==null?void 0:Y.name)??B.siteId)+(B.ok?" ✓":` ✕ ${B.reason??"失败"}`)},B.siteId)})})]})]}):e.jsx("div",{style:{position:"absolute",inset:0,display:"grid",placeItems:"center",background:"var(--bg-workspace)",zIndex:30},children:e.jsxs("div",{style:{textAlign:"center",color:"var(--text-muted)",fontSize:13,display:"grid",gap:12},children:[e.jsx("span",{children:"AI Hub 仅在桌面端可用"}),e.jsx("button",{type:"button",onClick:t,className:"ui-icon-button ui-icon-button--auto",style:{justifySelf:"center",padding:"6px 14px"},children:"返回"})]})})}const tu=new Set(["downloading","installing","reconnecting"]),Bm=new Set(["checking",...tu]),Om=6e3,$m=24e3;function Hm(){const[t,n]=a.useState(null),[r,s]=a.useState(()=>sessionStorage.getItem("agentroam.dismissed-update"));if(a.useEffect(()=>{var j;let p=!0;const v=window.agentApi,x=((j=v.onUpdateStatus)==null?void 0:j.call(v,E=>{p&&n(E)}))??(()=>{});v.getUpdateStatus().then(E=>{p&&n(E)}).catch(()=>{});const w=window.setTimeout(()=>{v.checkForUpdate().then(E=>{p&&n(E)}).catch(()=>{})},Om+Math.floor(Math.random()*($m+1)));return()=>{p=!1,window.clearTimeout(w),x()}},[]),a.useEffect(()=>{if(!t||!Bm.has(t.phase))return;const p=window.setInterval(()=>{window.agentApi.getUpdateStatus().then(n).catch(()=>{})},1500);return()=>window.clearInterval(p)},[t==null?void 0:t.phase]),!t||["idle","checking","up-to-date","unavailable"].includes(t.phase)||t.phase==="available"&&t.targetVersion===r)return null;const i=tu.has(t.phase),o=t.phase==="failed",l=t.phase==="complete",d=i?t.phase==="downloading"?`正在下载${t.progress!==void 0?` ${t.progress}%`:""}`:t.phase==="installing"?"正在安装":"正在重连":o?"更新失败,重试":l?t.message??"更新已就绪":`发现 AgentRoam ${t.targetVersion}`,u=async()=>{try{n(await window.agentApi.installUpdate())}catch(p){n({...t,phase:"failed",message:p instanceof Error?p.message:"更新失败"})}},f=()=>{t.targetVersion&&(sessionStorage.setItem("agentroam.dismissed-update",t.targetVersion),s(t.targetVersion))};return e.jsxs("aside",{className:`update-notice${o?" update-notice--failed":""}`,"aria-live":"polite",children:[e.jsxs("div",{className:"update-notice__content",children:[e.jsx("strong",{children:d}),!i&&!l&&e.jsx("span",{children:"点击后才会下载安装文件"}),o&&t.message&&e.jsx("span",{children:t.message})]}),!i&&!l&&e.jsxs("button",{className:"update-notice__action",type:"button",onClick:()=>void u(),title:o?"重试更新":"下载更新",children:[o?e.jsx(Ns,{size:16}):e.jsx(la,{size:16}),e.jsx("span",{children:o?"重试":"更新"})]}),!i&&e.jsx("button",{className:"update-notice__close",type:"button",onClick:f,title:"关闭更新提醒","aria-label":"关闭更新提醒",children:e.jsx(Tr,{size:16})})]})}function Um(){const[t,n]=a.useState(null);a.useEffect(()=>{const o=window.agentApi;if(!(o!=null&&o.desktopLiveGetStatus)||!(o!=null&&o.onDesktopLiveStatus))return;let l=!0;o.desktopLiveGetStatus().then(u=>{l&&n(u)}).catch(()=>{});const d=o.onDesktopLiveStatus(u=>n(u));return()=>{l=!1,d()}},[]);const r=t==null?void 0:t.controlState;if(!((t==null?void 0:t.enabled)&&r!==null&&r!==void 0&&r!=="agent-controlled"))return null;const i=r==="return-requested"||r==="resyncing";return e.jsxs("div",{className:"desktop-live-control-banner",role:"status",style:{position:"fixed",top:"calc(env(safe-area-inset-top) + 10px)",left:"50%",transform:"translateX(-50%)",zIndex:1300,display:"flex",alignItems:"center",gap:8,padding:"7px 14px",borderRadius:999,border:"1px solid rgba(251,191,36,0.45)",background:"rgba(69,49,10,0.92)",color:"#fcd34d",fontSize:13,fontWeight:600,backdropFilter:"blur(8px)",pointerEvents:"none"},children:[e.jsx("span",{"aria-hidden":"true",children:"●"}),i?"正在结束远程控制":"正在被远程控制"]})}function zo(t){return t==="idle"?"completed":t}const Lo={"needs-input":"需要输入",running:"运行中",completed:"执行完成",stale:"状态待刷新",error:"执行错误"};function Sa(t,n){return t.map((r,s)=>({session:r,index:s})).sort((r,s)=>n(r.session,s.session)||r.index-s.index).map(({session:r})=>r)}function qm(t){return Sa(t,(n,r)=>r.created.localeCompare(n.created))}function na(t,n){return n==="codex"?[...t]:qm(t)}function vc(t,n){return Sa(t,(r,s)=>Number(n(s))-Number(n(r)))}function Vm(t,n){return Sa(t,(r,s)=>Number(n(s))-Number(n(r)))}const Po={projectId:null,sessionId:null};function ra(t){return typeof t=="string"&&t.trim()?t.trim():null}function wc(t){return{projectId:ra(t),sessionId:null}}function Do(t,n){return{projectId:ra(t),sessionId:ra(n)}}function Gm(t){return t.agentType==="customer-agent"?`确定永久删除会话“${t.title}”吗?此操作不可恢复。`:t.agentType==="codex"?`确定归档 Codex 会话“${t.title}”并从 AgentRoam 中移除吗?可在 Codex 的已归档会话中恢复。`:`确定从 AgentRoam 中移除会话“${t.title}”吗?原生客户端中的历史记录会保留。`}function Km(t,n){const r=new Set(n);return{...t,selectedSessionId:t.selectedSessionId&&r.has(t.selectedSessionId)?null:t.selectedSessionId,sessions:Object.fromEntries(Object.entries(t.sessions).map(([s,i])=>[s,{...i,data:i.data.filter(o=>!r.has(o.id))}]))}}function Qm(t,n){const r=new Set(n);let s=!1;const i=Object.fromEntries(Object.entries(t).map(([o,l])=>{const d=l.filter(u=>!r.has(u.id));return d.length!==l.length&&(s=!0),[o,d.length===l.length?l:d]}));return s?i:t}function Xm(t,n,r,s){const i=[s,...(n[s]??[]).map(d=>d.id)],o=new Set(i),l=Object.fromEntries(Object.entries(n).flatMap(([d,u])=>{if(o.has(d))return[];const f=u.filter(p=>!o.has(p.id));return[[d,f.length===u.length?u:f]]}));return{sessionsByProject:Qm(t,i),childSessionsByParent:l,otherLocalSessions:r.filter(d=>!o.has(d.id)),removedIds:i}}function Ym(t){if(!t.trim())return null;const n=Number(t);return Number.isSafeInteger(n)&&n>=0?n:null}function nu({message:t,type:n}){return t?On.createPortal(e.jsxs("div",{className:`app-action-notice is-${n}`,role:n==="error"?"alert":"status","aria-live":n==="error"?"assertive":"polite",children:[e.jsx("span",{className:"app-action-notice-mark","aria-hidden":"true",children:n==="success"?"✓":n==="info"?"i":"!"}),e.jsx("span",{children:t})]}),document.body):null}const Jm=()=>({id:"",name:"",enabled:!0,allowedTools:[],filesystem:{readRoots:[],writeRoots:[],followSymlinks:!1},commands:{mode:"deny",programs:[],inheritedEnvironment:[]},network:"deny",limits:{timeoutMs:12e4,maxOutputBytes:1048576}});function Zm({onNotice:t}){const[n,r]=a.useState([]),[s,i]=a.useState([]),[o,l]=a.useState(null),[d,u]=a.useState(!1),f=a.useMemo(()=>[...s].sort(),[s]),p=async()=>{var j;if(!((j=window.agentApi)!=null&&j.listToolPolicies))return;const w=await window.agentApi.listToolPolicies();r(w.policies),i(w.tools)};a.useEffect(()=>{p().catch(w=>t(String(w),"error"))},[]);const v=async()=>{var w;if(!(!o||!((w=window.agentApi)!=null&&w.saveToolPolicy)))try{await window.agentApi.saveToolPolicy(o,d),await p(),l(null),t("工具策略已保存","success")}catch(j){t(j instanceof Error?j.message:"工具策略保存失败","error")}},x=async w=>{var j;if((j=window.agentApi)!=null&&j.deleteToolPolicy)try{await window.agentApi.deleteToolPolicy(w),await p(),(o==null?void 0:o.id)===w&&l(null),t("工具策略已删除","success")}catch(E){t(E instanceof Error?E.message:"工具策略删除失败","error")}};return e.jsxs("section",{className:"tool-policy-manager",children:[e.jsxs("div",{className:"settings-head-row",children:[e.jsx("h3",{children:"工具执行策略"}),e.jsx("button",{type:"button",className:"tool-policy-button",onClick:()=>{l(Jm()),u(!1)},children:"+ 添加"})]}),e.jsxs("div",{className:"tool-policy-list",children:[n.map(w=>e.jsxs("div",{className:"tool-policy-row",children:[e.jsxs("div",{children:[e.jsx("strong",{children:w.name}),e.jsxs("small",{children:[w.id," · ",w.enabled?"已启用":"已停用"]})]}),e.jsxs("div",{className:"tool-policy-actions",children:[e.jsx("button",{type:"button",onClick:()=>{l(structuredClone(w)),u(!0)},children:"编辑"}),e.jsx("button",{type:"button",className:"is-danger",onClick:()=>void x(w.id),children:"删除"})]})]},w.id)),n.length===0&&e.jsx("div",{className:"tool-policy-empty",children:"暂无工具执行策略"})]}),o&&e.jsxs("div",{className:"tool-policy-form",children:[e.jsxs("div",{className:"tool-policy-grid two",children:[e.jsx(yn,{label:"策略 ID",children:e.jsx("input",{value:o.id,disabled:d,onChange:w=>l({...o,id:w.target.value})})}),e.jsx(yn,{label:"名称",children:e.jsx("input",{value:o.name,onChange:w=>l({...o,name:w.target.value})})})]}),e.jsxs("label",{className:"tool-policy-check",children:[e.jsx("input",{type:"checkbox",checked:o.enabled,onChange:w=>l({...o,enabled:w.target.checked})}),"启用"]}),e.jsx(yn,{label:"允许的工具",children:e.jsx("div",{className:"tool-policy-tools",children:f.map(w=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:o.allowedTools.includes(w),onChange:()=>l({...o,allowedTools:tx(o.allowedTools,w)})}),w]},w))})}),e.jsxs("div",{className:"tool-policy-grid two",children:[e.jsx(yn,{label:"只读根目录(每行一个)",children:e.jsx("textarea",{value:o.filesystem.readRoots.join(`
|
|
471
471
|
`),onChange:w=>l({...o,filesystem:{...o.filesystem,readRoots:kc(w.target.value)}})})}),e.jsx(yn,{label:"可写根目录(每行一个)",children:e.jsx("textarea",{value:o.filesystem.writeRoots.join(`
|
|
472
472
|
`),onChange:w=>l({...o,filesystem:{...o.filesystem,writeRoots:kc(w.target.value)}})})})]}),e.jsxs("label",{className:"tool-policy-check",children:[e.jsx("input",{type:"checkbox",checked:o.filesystem.followSymlinks,onChange:w=>l({...o,filesystem:{...o.filesystem,followSymlinks:w.target.checked}})}),"允许根目录内符号链接"]}),e.jsxs("div",{className:"tool-policy-grid three",children:[e.jsx(yn,{label:"命令模式",children:e.jsxs("select",{value:o.commands.mode,onChange:w=>l({...o,commands:{...o.commands,mode:w.target.value}}),children:[e.jsx("option",{value:"deny",children:"禁止"}),e.jsx("option",{value:"allowlist",children:"白名单"}),e.jsx("option",{value:"unrestricted",children:"不限制"})]})}),e.jsx(yn,{label:"网络模式",children:e.jsxs("select",{value:o.network,onChange:w=>l({...o,network:w.target.value}),children:[e.jsx("option",{value:"deny",children:"禁止"}),e.jsx("option",{value:"read-only",children:"只读"}),e.jsx("option",{value:"allow",children:"允许"})]})}),e.jsx(yn,{label:"继承环境变量",children:e.jsx("input",{value:o.commands.inheritedEnvironment.join(", "),onChange:w=>l({...o,commands:{...o.commands,inheritedEnvironment:Ms(w.target.value)}})})})]}),o.commands.mode==="allowlist"&&e.jsxs("div",{className:"tool-policy-programs",children:[e.jsxs("div",{className:"settings-head-row",children:[e.jsx("h4",{children:"允许的程序"}),e.jsx("button",{type:"button",onClick:()=>l({...o,commands:{...o.commands,programs:[...o.commands.programs,{executable:""}]}}),children:"+ 程序"})]}),o.commands.programs.map((w,j)=>e.jsx(ex,{program:w,onChange:E=>l({...o,commands:{...o.commands,programs:nx(o.commands.programs,j,E)}}),onDelete:()=>l({...o,commands:{...o.commands,programs:o.commands.programs.filter((E,S)=>S!==j)}})},j))]}),e.jsxs("div",{className:"tool-policy-grid two",children:[e.jsx(yn,{label:"超时(毫秒)",children:e.jsx("input",{type:"number",min:100,max:6e5,value:o.limits.timeoutMs,onChange:w=>l({...o,limits:{...o.limits,timeoutMs:Number(w.target.value)}})})}),e.jsx(yn,{label:"最大输出(字节)",children:e.jsx("input",{type:"number",min:1024,max:10485760,value:o.limits.maxOutputBytes,onChange:w=>l({...o,limits:{...o.limits,maxOutputBytes:Number(w.target.value)}})})})]}),e.jsxs("div",{className:"tool-policy-actions",children:[e.jsx("button",{type:"button",className:"is-primary",onClick:()=>void v(),children:"保存策略"}),e.jsx("button",{type:"button",onClick:()=>l(null),children:"取消"})]})]})]})}function ex({program:t,onChange:n,onDelete:r}){return e.jsxs("div",{className:"tool-policy-program",children:[e.jsxs("div",{className:"tool-policy-grid two",children:[e.jsx(yn,{label:"可执行文件",children:e.jsx("input",{value:t.executable,onChange:s=>n({...t,executable:s.target.value})})}),e.jsx(yn,{label:"子命令",children:e.jsx("input",{value:(t.subcommands??[]).join(", "),onChange:s=>n({...t,subcommands:Ms(s.target.value)})})})]}),e.jsxs("div",{className:"tool-policy-grid three",children:[e.jsx(yn,{label:"允许参数",children:e.jsx("input",{value:(t.allowedFlags??[]).join(", "),onChange:s=>n({...t,allowedFlags:Ms(s.target.value)})})}),e.jsx(yn,{label:"禁止参数",children:e.jsx("input",{value:(t.deniedFlags??[]).join(", "),onChange:s=>n({...t,deniedFlags:Ms(s.target.value)})})}),e.jsx(yn,{label:"路径参数",children:e.jsx("input",{value:(t.pathFlags??[]).join(", "),onChange:s=>n({...t,pathFlags:Ms(s.target.value)})})})]}),e.jsxs("div",{className:"tool-policy-program-footer",children:[e.jsx(yn,{label:"位置路径索引",children:e.jsx("input",{value:(t.positionalPathIndexes??[]).join(", "),onChange:s=>n({...t,positionalPathIndexes:Ms(s.target.value).map(Number)})})}),e.jsx("button",{type:"button",className:"is-danger",onClick:r,children:"删除程序"})]})]})}function yn({label:t,children:n}){return e.jsxs("label",{className:"tool-policy-field",children:[e.jsx("span",{children:t}),n]})}function kc(t){return t.split(`
|
|
473
|
-
`).map(n=>n.trim()).filter(Boolean)}function Ms(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function tx(t,n){return t.includes(n)?t.filter(r=>r!==n):[...t,n]}function nx(t,n,r){return t.map((s,i)=>i===n?r:s)}const rx=[{value:"anthropic",label:"Anthropic"},{value:"openai",label:"OpenAI"},{value:"deepseek",label:"DeepSeek"},{value:"aihub",label:"AI Hub(网页版)"}],jc={anthropic:"claude-sonnet-4-6",openai:"gpt-4o",deepseek:"deepseek-chat",aihub:"deepseek"},$i={anthropic:120,openai:300,deepseek:300,aihub:240};function Sc(){return{name:"",provider:"anthropic",modelId:"claude-sonnet-4-6",apiKey:"",baseUrl:"",maxOutputTokens:16384,requestTimeoutSeconds:$i.anthropic}}function sx(){const{maxIterations:t,contextWindow:n,isConfigured:r,profiles:s,activeProfileId:i,taskNotifications:o,setField:l,loadFromSystem:d,saveToSystem:u,addProfile:f,updateProfile:p,deleteProfile:v,switchActiveProfile:x}=qi(),[w,j]=a.useState(null),[E,S]=a.useState("success"),[C,k]=a.useState(null),[z,M]=a.useState(String(t)),[H,L]=a.useState(String(Math.round((n??100)*1e3)));a.useEffect(()=>{M(String(t))},[t]),a.useEffect(()=>{L(String(Math.round((n??100)*1e3)))},[n]);const[T,A]=a.useState(null),[R,$]=a.useState(!1),[F,Ee]=a.useState(Sc());a.useEffect(()=>{d()},[]),a.useEffect(()=>{if(!C)return;const ne=window.setTimeout(()=>k(null),C.type==="error"?4e3:2500);return()=>window.clearTimeout(ne)},[C]);const Ke=()=>{$(!0),A(null),Ee(Sc())},ae=ne=>{$(!1),A(ne.id),Ee({name:ne.name,provider:ne.provider,modelId:ne.modelId,apiKey:["managed","__agentroam_stored_secret__"].includes(ne.apiKey)?"":ne.apiKey,baseUrl:ne.baseUrl,maxOutputTokens:ne.maxOutputTokens??16384,requestTimeoutSeconds:ne.requestTimeoutSeconds??$i[ne.provider]??300})},ke=()=>{A(null),$(!1)},Pe=async()=>{const ne=F.provider!=="aihub",be=T?s.find(W=>W.id===T):void 0,Ye=be?["managed","__agentroam_stored_secret__"].includes(be.apiKey):!1;if(!F.name.trim()||ne&&!F.apiKey.trim()&&!Ye||!F.modelId.trim()){j(ne?"名称、API Key 和模型 ID 为必填项":"名称和模型 ID(AI Hub 站点 ID)为必填项"),S("error");return}if(F.maxOutputTokens!==void 0&&(!Number.isInteger(F.maxOutputTokens)||F.maxOutputTokens<256||F.maxOutputTokens>131072)){j("单轮最大输出请输入 256 到 131072 之间的整数 tokens"),S("error");return}if(F.requestTimeoutSeconds!==void 0&&(!Number.isInteger(F.requestTimeoutSeconds)||F.requestTimeoutSeconds<30||F.requestTimeoutSeconds>1800)){j("单次请求超时请输入 30 到 1800 之间的整数秒"),S("error");return}try{R?f(F):T&&p(T,F),await u(),A(null),$(!1),j(null),k({message:"模型配置保存成功",type:"success"})}catch(W){k({message:W instanceof Error?W.message:"模型配置保存失败",type:"error"})}},Ie=async ne=>{v(ne),setTimeout(()=>u(),0)},We=async ne=>{await x(ne),j("已切换模型"),S("success"),setTimeout(()=>j(null),1500)},at=async()=>{j(null);const ne=Ym(z);if(ne===null){j("最大迭代次数不能为空,请输入非负整数;0 表示无限制。"),S("error");return}const be=Number(H);if(!Number.isInteger(be)||be<1024||be>2e6){j("上下文窗口请输入 1024 到 2000000 之间的整数 tokens,例如 8192。"),S("error");return}l("maxIterations",ne),l("contextWindow",be/1e3);try{await u(),j(null),k({message:"设置保存成功",type:"success"})}catch(Ye){k({message:Ye instanceof Error?Ye.message:"设置保存失败",type:"error"})}},qe=R||T!==null;return e.jsxs("div",{style:{padding:"40px 48px",maxWidth:640,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsx("h2",{style:{fontFamily:"var(--font-display)",fontSize:28,color:"var(--text-primary)",fontWeight:400,marginBottom:8,letterSpacing:"-0.02em"},children:"设置"}),e.jsx("p",{style:{color:"var(--text-muted)",fontSize:14,marginBottom:36},children:"管理模型提供商和运行参数。工作目录在项目设置中配置。"}),e.jsxs("section",{style:{marginBottom:40},children:[e.jsxs("div",{className:"settings-head-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:14},children:[e.jsx("h3",{style:{fontSize:13,fontWeight:600,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",margin:0},children:"模型提供商"}),e.jsx("button",{onClick:Ke,style:ox,children:"+ 添加"})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.length===0&&!qe&&e.jsx("div",{style:{padding:"20px 16px",borderRadius:"var(--radius-sm)",border:"1px dashed var(--border-subtle)",textAlign:"center",color:"var(--text-muted)",fontSize:13},children:"暂无配置,点击「+ 添加」创建第一个模型提供商"}),s.map(ne=>{const be=ne.id===i,Ye=ne.id===T,W=["managed","__agentroam_stored_secret__"].includes(ne.apiKey);return e.jsxs("div",{style:{borderRadius:"var(--radius-sm)",border:`1px solid ${be?"var(--accent)":"var(--border-default)"}`,background:be?"var(--accent-dim)":"var(--bg-surface)",overflow:"hidden",transition:"border-color 0.2s"},children:[e.jsxs("div",{className:"profile-row",style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px"},children:[e.jsx("span",{style:{fontSize:10,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",padding:"2px 7px",borderRadius:4,background:be?"var(--accent)":"var(--bg-deep)",color:be?"#fff":"var(--text-muted)",flexShrink:0},children:ne.provider}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ne.name||ne.modelId}),e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ne.modelId})]}),be&&e.jsx("span",{style:{fontSize:11,color:"var(--accent)",fontWeight:600,flexShrink:0},children:"● 使用中"}),e.jsxs("div",{className:"profile-row-actions",style:{display:"flex",gap:6,flexShrink:0},children:[!be&&e.jsx("button",{onClick:()=>We(ne.id),style:Wo,children:"切换"}),e.jsx("button",{onClick:()=>Ye?ke():ae(ne),style:Wo,children:Ye?"收起":"编辑"}),e.jsx("button",{onClick:()=>Ie(ne.id),style:{...Wo,color:"var(--danger)",borderColor:"rgba(244,63,94,0.25)"},children:"删除"})]})]}),Ye&&e.jsx(Cc,{draft:F,setDraft:Ee,hasStoredApiKey:W,onSave:Pe,onCancel:ke})]},ne.id)}),R&&e.jsxs("div",{style:{borderRadius:"var(--radius-sm)",border:"1px solid var(--accent)",background:"var(--bg-surface)"},children:[e.jsx("div",{style:{padding:"10px 14px 0",fontSize:13,fontWeight:600,color:"var(--accent)"},children:"新建提供商"}),e.jsx(Cc,{draft:F,setDraft:Ee,hasStoredApiKey:!1,onSave:Pe,onCancel:ke})]})]})]}),e.jsxs("section",{children:[e.jsx("h3",{style:{fontSize:13,fontWeight:600,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:14},children:"常规"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsxs(Er,{label:"最大迭代次数",children:[e.jsx("input",{type:"number",value:z,onChange:ne=>M(ne.target.value),min:0,step:1,style:Mr}),e.jsx("div",{style:{fontSize:12,opacity:.65},children:"输入 0 表示不限制迭代次数。"})]}),e.jsxs(Er,{label:"上下文窗口(tokens,输入与输出合计)",children:[e.jsx("input",{type:"number",value:H,onChange:ne=>L(ne.target.value),min:1024,max:2e6,step:1,style:Mr}),e.jsx("div",{style:{fontSize:12,opacity:.65},children:"8K 模型填 8192;不能超过模型服务实际启动的上下文大小。"})]})]})]}),e.jsxs("section",{style:{marginTop:40},children:[e.jsx("h3",{style:{fontSize:13,fontWeight:600,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:14},children:"任务完成提醒"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[["completionEnabled","任务完成通知"],["soundEnabled","播放提示音"],["notifyWhileForeground","前台运行时也通知"]].map(([ne,be])=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:10,color:"var(--text-primary)",fontSize:14},children:[e.jsx("input",{type:"checkbox",checked:o[ne],onChange:Ye=>l("taskNotifications",{...o,[ne]:Ye.target.checked})}),be]},ne))})]}),e.jsx(Zm,{onNotice:(ne,be)=>k({message:ne,type:be})}),e.jsxs("div",{style:{marginTop:28,display:"flex",gap:14,alignItems:"center"},children:[e.jsx("button",{onClick:at,style:ru,children:"保存"}),e.jsx("span",{style:{padding:"7px 14px",borderRadius:"var(--radius-sm)",fontSize:12,fontWeight:500,background:r?"rgba(52,211,153,0.1)":"rgba(255,255,255,0.04)",color:r?"var(--success)":"var(--text-muted)",border:`1px solid ${r?"rgba(52,211,153,0.2)":"var(--border-subtle)"}`},children:r?"● 已连接":"○ 未配置"})]}),w&&e.jsx("div",{style:{marginTop:12,padding:"10px 12px",borderRadius:"var(--radius-sm)",border:E==="success"?"1px solid rgba(52,211,153,0.35)":"1px solid rgba(244,63,94,0.35)",background:E==="success"?"rgba(52,211,153,0.08)":"rgba(244,63,94,0.08)",color:E==="success"?"var(--success)":"var(--danger)",fontSize:13},children:w}),e.jsx(nu,{message:(C==null?void 0:C.message)??null,type:(C==null?void 0:C.type)??"success"})]})}function Cc({draft:t,setDraft:n,hasStoredApiKey:r,onSave:s,onCancel:i}){const o=(l,d)=>n(u=>{const f={...u,[l]:d};return l==="provider"&&!u.modelId&&(f.modelId=jc[d]??""),f});return e.jsxs("div",{style:{padding:"12px 14px 14px",display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[e.jsx(Er,{label:"名称",children:e.jsx("input",{value:t.name,onChange:l=>o("name",l.target.value),placeholder:"我的 Claude",style:Mr})}),e.jsx(Er,{label:"提供商",children:e.jsx("select",{value:t.provider,onChange:l=>{const d=l.target.value;n(u=>({...u,provider:d,modelId:jc[d]??"",requestTimeoutSeconds:$i[d]??300}))},style:Mr,children:rx.map(l=>e.jsx("option",{value:l.value,children:l.label},l.value))})})]}),e.jsx(Er,{label:"模型 ID",children:e.jsx("input",{value:t.modelId,onChange:l=>o("modelId",l.target.value),placeholder:t.provider==="aihub"?"deepseek":"claude-sonnet-4-6",style:Mr})}),e.jsx(Er,{label:"单轮最大输出(tokens)",children:e.jsx("input",{type:"number",value:t.maxOutputTokens??16384,onChange:l=>n(d=>({...d,maxOutputTokens:Number(l.target.value)})),min:256,max:131072,step:1024,style:Mr})}),e.jsx(Er,{label:"单次请求超时(秒)",children:e.jsx("input",{type:"number",value:t.requestTimeoutSeconds??$i[t.provider]??300,onChange:l=>n(d=>({...d,requestTimeoutSeconds:Number(l.target.value)})),min:30,max:1800,step:30,style:Mr})}),t.provider==="aihub"?e.jsx("div",{style:{padding:"8px 10px",background:"rgba(96,165,250,0.08)",border:"1px solid rgba(96,165,250,0.2)",borderRadius:8,fontSize:12,lineHeight:1.6},children:"AI Hub 网页模型来源:模型 ID 填 AI Hub 站点 ID(deepseek / chatgpt / gemini / grok 或自定义站点),无需 API Key。 运行时由桌面端 AI Hub 把上下文模拟人为发送给该站点并抓取回复;支持通过受控 JSON 协议调用 Agent 工具。需要桌面 App 在线且站点已登录。"}):e.jsxs(e.Fragment,{children:[e.jsx(Er,{label:"API 密钥",children:e.jsx("input",{type:"password",value:t.apiKey,onChange:l=>o("apiKey",l.target.value),placeholder:r?"••••••••••••":"sk-...","aria-label":r?"API 密钥(已保存)":"API 密钥",style:Mr})}),e.jsx(Er,{label:"接口地址(可选)",children:e.jsx("input",{value:t.baseUrl,onChange:l=>o("baseUrl",l.target.value),placeholder:"https://api.anthropic.com",style:Mr})})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:2},children:[e.jsx("button",{onClick:s,style:ru,children:"保存"}),e.jsx("button",{onClick:i,style:ix,children:"取消"})]})]})}function Er({label:t,children:n}){return e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:12,color:"var(--text-secondary)",marginBottom:6,fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:t}),n]})}const Mr={width:"100%",padding:"9px 12px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:14,outline:"none",fontFamily:"var(--font-body)",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",boxSizing:"border-box"},ru={padding:"11px 28px",borderRadius:"var(--radius-sm)",border:"1px solid transparent",background:"var(--accent)",color:"var(--text-inverse)",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"var(--font-body)",boxShadow:"0 2px 16px var(--accent-glow)",transition:"transform 0.15s var(--ease-out), box-shadow 0.15s var(--ease-out)"},ix={padding:"11px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-secondary)",fontSize:14,fontWeight:500,cursor:"pointer",fontFamily:"var(--font-body)",whiteSpace:"nowrap",transition:"all 0.15s var(--ease-out)"},ox={padding:"6px 14px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-secondary)",fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:"var(--font-body)"},Wo={padding:"4px 10px",borderRadius:6,border:"1px solid var(--border-subtle)",background:"transparent",color:"var(--text-muted)",fontSize:12,cursor:"pointer",fontFamily:"var(--font-body)"},ax={fontSize:13,fontWeight:600,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:14},Ic={display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"8px 12px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",background:"var(--bg-surface)",fontSize:13};function lx({onboarding:t=!1}){const n=typeof window>"u"?void 0:window.agentApi,r=!!(n!=null&&n.desktopLiveGetStatus),[s,i]=a.useState(null),[o,l]=a.useState(!1),[d,u]=a.useState(null),[f,p]=a.useState(!0);a.useEffect(()=>{if(!(n!=null&&n.desktopLiveGetStatus)||!(n!=null&&n.onDesktopLiveStatus))return;let S=!0;n.desktopLiveSetup().then(k=>{S&&(i(k.status),p(k.supported))}).catch(()=>{});const C=n.onDesktopLiveStatus(k=>i(k));return()=>{S=!1,C()}},[n]);const v=async()=>{if(n!=null&&n.desktopLiveRecheck)try{i(await n.desktopLiveRecheck()),u(null)}catch(S){u(S instanceof Error?S.message:String(S))}};a.useEffect(()=>{if(!r||!f)return;let S=!0,C=!1;const k=async()=>{if(!C){C=!0;try{const M=await n.desktopLiveRecheck();S&&i(M)}catch{}finally{C=!1}}};window.addEventListener("focus",k);const z=s!=null&&s.enabled&&(s.permissionScreen!=="granted"||s.accessibilityTrusted!==!0)?window.setInterval(k,3e3):void 0;return()=>{S=!1,window.removeEventListener("focus",k),z&&window.clearInterval(z)}},[n,r,f,s==null?void 0:s.enabled,s==null?void 0:s.permissionScreen,s==null?void 0:s.accessibilityTrusted]);const x=async S=>{if(n){l(!0);try{i(await n.desktopLiveSetEnabled(!0)),await n.desktopLiveOpenPermission(S),u(null)}catch(C){u(C instanceof Error?C.message:String(C))}finally{l(!1)}}};if(!r)return null;const w=async()=>{if(n!=null&&n.desktopLiveSetEnabled){l(!0);try{i(await n.desktopLiveSetEnabled(!(s!=null&&s.enabled))),u(null)}catch(S){u(S instanceof Error?S.message:String(S))}finally{l(!1)}}},j=(s==null?void 0:s.permissionScreen)==="granted",E=(s==null?void 0:s.accessibilityTrusted)===!0;return e.jsxs("section",{className:"desktop-permission-settings",children:[e.jsx("h3",{style:ax,children:t?"设置桌面端权限":"桌面直播与远程控制"}),e.jsx("p",{style:{fontSize:13,color:"var(--text-muted)",margin:"0 0 14px",lineHeight:1.6},children:t?"欢迎使用 AgentRoam。请为桌面端开启以下系统权限,完成后手机即可查看电脑画面;允许辅助功能后还可操作鼠标和键盘。":"开启后,已配对手机可查看电脑画面,并在授予辅助功能权限后操作鼠标和键盘。"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[e.jsx("button",{type:"button",onClick:()=>void w(),disabled:o||!f,style:{padding:"7px 16px",borderRadius:"var(--radius-sm)",border:`1px solid ${s!=null&&s.enabled?"rgba(244,63,94,0.35)":"var(--accent)"}`,background:s!=null&&s.enabled?"rgba(244,63,94,0.1)":"var(--accent-dim)",color:s!=null&&s.enabled?"var(--danger)":"var(--accent)",fontSize:13,fontWeight:600,cursor:"pointer"},children:o?"处理中…":s!=null&&s.enabled?t?"暂停手机查看":"关闭桌面直播":t?"开启手机查看":"开启桌面直播"}),(s==null?void 0:s.enabled)&&e.jsx("span",{style:{fontSize:12,color:s.sessionOnline?"var(--success)":"var(--text-muted)"},children:s.sessionOnline?"● 已连接,可从手机查看":"○ 未连接"})]}),!f&&e.jsx("p",{role:"status",children:"当前远程桌面仅支持 macOS,其他桌面功能可正常使用。"}),f&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{className:"desktop-permission-row",style:Ic,children:[e.jsx("span",{children:"屏幕录制(画面采集)"}),e.jsx("span",{style:{color:j?"var(--success)":"var(--danger)",fontWeight:600},children:j?"已授权":"未授权"}),!j&&e.jsx("button",{type:"button",className:"ui-quiet-button desktop-permission-button",disabled:o,onClick:()=>void x("screen"),children:"去授权"})]}),e.jsxs("div",{className:"desktop-permission-row",style:Ic,children:[e.jsx("span",{children:"辅助功能(键鼠控制)"}),e.jsx("span",{style:{color:E?"var(--success)":"var(--danger)",fontWeight:600},children:(s==null?void 0:s.accessibilityTrusted)===null?"待检测":E?"已授权":"未授权"}),!E&&e.jsx("button",{type:"button",className:"ui-quiet-button desktop-permission-button",disabled:o,onClick:()=>void x("accessibility"),children:"去授权"})]})]}),f&&e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{marginTop:14,fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:"点击对应权限的「去授权」,在系统设置中允许 AgentRoam,返回后自动检测。"}),e.jsxs("details",{className:"desktop-permission-more",children:[e.jsx("summary",{children:"更多操作"}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:8},children:[e.jsx("button",{type:"button",className:"ui-quiet-button",onClick:()=>void v(),children:"重新检测"}),!j&&e.jsx("button",{type:"button",className:"ui-quiet-button",onClick:()=>void(n==null?void 0:n.desktopLiveRestart()),children:"重启桌面端"})]})]})]}),d&&e.jsx("p",{role:"alert",style:{color:"var(--danger)"},children:d}),(s==null?void 0:s.error)&&e.jsx("div",{style:{marginTop:10,fontSize:12,color:"var(--danger)"},role:"alert",children:s.error})]})}function cx({onClose:t}){const n=a.useRef(null);return a.useEffect(()=>{var r;(r=n.current)==null||r.showModal()},[]),On.createPortal(e.jsx("dialog",{ref:n,"aria-label":"桌面直播与远程控制",onCancel:t,onClick:r=>{r.target===r.currentTarget&&t()},style:{width:"min(680px, calc(100vw - 48px))",maxHeight:"calc(100vh - 48px)",padding:0,margin:"auto",inset:0,overflowY:"auto",color:"var(--text-primary)",background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-md)"},children:e.jsxs("div",{style:{padding:24},children:[e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:8},children:e.jsx("button",{type:"button",onClick:t,"aria-label":"关闭桌面直播设置",className:"ui-icon-button ui-icon-button--close",children:"×"})}),e.jsx(lx,{}),e.jsx("div",{className:"desktop-permission-footer",children:e.jsx("button",{type:"button",className:"ui-quiet-button",onClick:t,children:"关闭"})})]})}),document.body)}const Fo={id:"",name:"",command:"",args:"",url:"",headersRaw:""};function dx(){const[t,n]=a.useState([]),[r,s]=a.useState("stdio"),[i,o]=a.useState(Fo),[l,d]=a.useState(!1),[u,f]=a.useState({id:!1,command:!1,url:!1}),[p,v]=a.useState({}),[x,w]=a.useState({}),[j,E]=a.useState(new Set),[S,C]=a.useState(null),[k,z]=a.useState(""),[M,H]=a.useState(!1),L=async W=>{var G;if(!((G=window.agentApi)!=null&&G.mcpProbe))return;E(le=>new Set([...le,W.id])),w(le=>{const pe={...le};return delete pe[W.id],pe});const te=new Promise((le,pe)=>setTimeout(()=>pe(new Error("连接超时(15s)")),15e3));try{const le=await Promise.race([window.agentApi.mcpProbe(W),te]);v(pe=>({...pe,[W.id]:le}))}catch(le){const pe=le instanceof Error?le.message:String(le);console.warn(`[MCP] probe failed for ${W.id}:`,pe),v(ye=>{const we={...ye};return delete we[W.id],we}),w(ye=>({...ye,[W.id]:pe})),(W.transport==="sse"||/401|403|unauthorized|forbidden|需要认证|访问被拒绝/i.test(pe))&&(z(""),C({server:W}))}finally{E(le=>{const pe=new Set(le);return pe.delete(W.id),pe})}};a.useEffect(()=>{window.agentApi&&window.agentApi.mcpList().then(W=>{n(W),W.filter(te=>te.enabled!==!1).forEach(te=>L(te))}).catch(console.error)},[]);const[T,A]=a.useState(""),[R,$]=a.useState(""),[F,Ee]=a.useState(!1),Ke=async()=>{$("");let W;try{W=JSON.parse(T.trim());const te=W.mcpServers??W,G=Object.entries(te);if(G.length===0){$("未找到任何服务器");return}Ee(!0);const le=[];for(const[ye,we]of G){const Te=we,dt=Te.name||ye,st=Te.disabled!==!0;let Tt;if(Te.url||Te.type==="streamableHttp"||Te.type==="sse"){const $e=Te.type==="sse"?"sse":"streamableHttp";Tt={id:ye,name:dt,transport:$e,url:Te.url,headers:Te.headers??{},env:Te.env??{},enabled:st}}else Tt={id:ye,name:dt,transport:"stdio",command:Te.command,args:Te.args??[],env:Te.env??{},enabled:st};await window.agentApi.mcpSave(Tt),le.push(Tt)}const pe=await window.agentApi.mcpList();n(pe),A(""),le.filter(ye=>ye.enabled!==!1).forEach(ye=>L(ye))}catch(te){$(te instanceof Error?te.message:"JSON 解析失败")}finally{Ee(!1)}},ae=()=>i.id.trim()!==""&&i.command.trim()!=="",ke=()=>i.id.trim()!==""&&i.url.trim()!=="",Pe=W=>{const te={};for(const G of W.split(`
|
|
474
|
-
`)){const le=G.indexOf(":");if(le<1)continue;const pe=G.slice(0,le).trim(),ye=G.slice(le+1).trim();pe&&(te[pe]=ye)}return te},Ie=async()=>{if(f({id:!0,command:!0,url:!0}),!(r==="stdio"&&!ae())&&!((r==="sse"||r==="streamableHttp")&&!ke())){d(!0);try{const W=r==="sse"||r==="streamableHttp"?
|
|
473
|
+
`).map(n=>n.trim()).filter(Boolean)}function Ms(t){return t.split(",").map(n=>n.trim()).filter(Boolean)}function tx(t,n){return t.includes(n)?t.filter(r=>r!==n):[...t,n]}function nx(t,n,r){return t.map((s,i)=>i===n?r:s)}const rx=[{value:"anthropic",label:"Anthropic"},{value:"openai",label:"OpenAI"},{value:"deepseek",label:"DeepSeek"},{value:"aihub",label:"AI Hub(网页版)"}],jc={anthropic:"claude-sonnet-4-6",openai:"gpt-4o",deepseek:"deepseek-chat",aihub:"deepseek"},$i={anthropic:120,openai:300,deepseek:300,aihub:240};function Sc(){return{name:"",provider:"anthropic",modelId:"claude-sonnet-4-6",apiKey:"",baseUrl:"",maxOutputTokens:16384,requestTimeoutSeconds:$i.anthropic}}function sx(){const{maxIterations:t,contextWindow:n,isConfigured:r,profiles:s,activeProfileId:i,taskNotifications:o,setField:l,loadFromSystem:d,saveToSystem:u,addProfile:f,updateProfile:p,deleteProfile:v,switchActiveProfile:x}=qi(),[w,j]=a.useState(null),[E,S]=a.useState("success"),[C,k]=a.useState(null),[z,M]=a.useState(String(t)),[H,L]=a.useState(String(Math.round((n??100)*1e3)));a.useEffect(()=>{M(String(t))},[t]),a.useEffect(()=>{L(String(Math.round((n??100)*1e3)))},[n]);const[T,A]=a.useState(null),[R,$]=a.useState(!1),[F,Ee]=a.useState(Sc());a.useEffect(()=>{d()},[]),a.useEffect(()=>{if(!C)return;const ne=window.setTimeout(()=>k(null),C.type==="error"?4e3:2500);return()=>window.clearTimeout(ne)},[C]);const Qe=()=>{$(!0),A(null),Ee(Sc())},ae=ne=>{$(!1),A(ne.id),Ee({name:ne.name,provider:ne.provider,modelId:ne.modelId,apiKey:["managed","__agentroam_stored_secret__"].includes(ne.apiKey)?"":ne.apiKey,baseUrl:ne.baseUrl,maxOutputTokens:ne.maxOutputTokens??16384,requestTimeoutSeconds:ne.requestTimeoutSeconds??$i[ne.provider]??300})},ke=()=>{A(null),$(!1)},De=async()=>{const ne=F.provider!=="aihub",be=T?s.find(W=>W.id===T):void 0,Ye=be?["managed","__agentroam_stored_secret__"].includes(be.apiKey):!1;if(!F.name.trim()||ne&&!F.apiKey.trim()&&!Ye||!F.modelId.trim()){j(ne?"名称、API Key 和模型 ID 为必填项":"名称和模型 ID(AI Hub 站点 ID)为必填项"),S("error");return}if(F.maxOutputTokens!==void 0&&(!Number.isInteger(F.maxOutputTokens)||F.maxOutputTokens<256||F.maxOutputTokens>131072)){j("单轮最大输出请输入 256 到 131072 之间的整数 tokens"),S("error");return}if(F.requestTimeoutSeconds!==void 0&&(!Number.isInteger(F.requestTimeoutSeconds)||F.requestTimeoutSeconds<30||F.requestTimeoutSeconds>1800)){j("单次请求超时请输入 30 到 1800 之间的整数秒"),S("error");return}try{R?f(F):T&&p(T,F),await u(),A(null),$(!1),j(null),k({message:"模型配置保存成功",type:"success"})}catch(W){k({message:W instanceof Error?W.message:"模型配置保存失败",type:"error"})}},Ie=async ne=>{v(ne),setTimeout(()=>u(),0)},We=async ne=>{await x(ne),j("已切换模型"),S("success"),setTimeout(()=>j(null),1500)},at=async()=>{j(null);const ne=Ym(z);if(ne===null){j("最大迭代次数不能为空,请输入非负整数;0 表示无限制。"),S("error");return}const be=Number(H);if(!Number.isInteger(be)||be<1024||be>2e6){j("上下文窗口请输入 1024 到 2000000 之间的整数 tokens,例如 8192。"),S("error");return}l("maxIterations",ne),l("contextWindow",be/1e3);try{await u(),j(null),k({message:"设置保存成功",type:"success"})}catch(Ye){k({message:Ye instanceof Error?Ye.message:"设置保存失败",type:"error"})}},Ge=R||T!==null;return e.jsxs("div",{style:{padding:"40px 48px",maxWidth:640,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsx("h2",{style:{fontFamily:"var(--font-display)",fontSize:28,color:"var(--text-primary)",fontWeight:400,marginBottom:8,letterSpacing:"-0.02em"},children:"设置"}),e.jsx("p",{style:{color:"var(--text-muted)",fontSize:14,marginBottom:36},children:"管理模型提供商和运行参数。工作目录在项目设置中配置。"}),e.jsxs("section",{style:{marginBottom:40},children:[e.jsxs("div",{className:"settings-head-row",style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:14},children:[e.jsx("h3",{style:{fontSize:13,fontWeight:600,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",margin:0},children:"模型提供商"}),e.jsx("button",{onClick:Qe,style:ox,children:"+ 添加"})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[s.length===0&&!Ge&&e.jsx("div",{style:{padding:"20px 16px",borderRadius:"var(--radius-sm)",border:"1px dashed var(--border-subtle)",textAlign:"center",color:"var(--text-muted)",fontSize:13},children:"暂无配置,点击「+ 添加」创建第一个模型提供商"}),s.map(ne=>{const be=ne.id===i,Ye=ne.id===T,W=["managed","__agentroam_stored_secret__"].includes(ne.apiKey);return e.jsxs("div",{style:{borderRadius:"var(--radius-sm)",border:`1px solid ${be?"var(--accent)":"var(--border-default)"}`,background:be?"var(--accent-dim)":"var(--bg-surface)",overflow:"hidden",transition:"border-color 0.2s"},children:[e.jsxs("div",{className:"profile-row",style:{display:"flex",alignItems:"center",gap:10,padding:"10px 14px"},children:[e.jsx("span",{style:{fontSize:10,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",padding:"2px 7px",borderRadius:4,background:be?"var(--accent)":"var(--bg-deep)",color:be?"#fff":"var(--text-muted)",flexShrink:0},children:ne.provider}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:14,fontWeight:600,color:"var(--text-primary)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ne.name||ne.modelId}),e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",marginTop:1,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ne.modelId})]}),be&&e.jsx("span",{style:{fontSize:11,color:"var(--accent)",fontWeight:600,flexShrink:0},children:"● 使用中"}),e.jsxs("div",{className:"profile-row-actions",style:{display:"flex",gap:6,flexShrink:0},children:[!be&&e.jsx("button",{onClick:()=>We(ne.id),style:Wo,children:"切换"}),e.jsx("button",{onClick:()=>Ye?ke():ae(ne),style:Wo,children:Ye?"收起":"编辑"}),e.jsx("button",{onClick:()=>Ie(ne.id),style:{...Wo,color:"var(--danger)",borderColor:"rgba(244,63,94,0.25)"},children:"删除"})]})]}),Ye&&e.jsx(Cc,{draft:F,setDraft:Ee,hasStoredApiKey:W,onSave:De,onCancel:ke})]},ne.id)}),R&&e.jsxs("div",{style:{borderRadius:"var(--radius-sm)",border:"1px solid var(--accent)",background:"var(--bg-surface)"},children:[e.jsx("div",{style:{padding:"10px 14px 0",fontSize:13,fontWeight:600,color:"var(--accent)"},children:"新建提供商"}),e.jsx(Cc,{draft:F,setDraft:Ee,hasStoredApiKey:!1,onSave:De,onCancel:ke})]})]})]}),e.jsxs("section",{children:[e.jsx("h3",{style:{fontSize:13,fontWeight:600,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:14},children:"常规"}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:16},children:[e.jsxs(Er,{label:"最大迭代次数",children:[e.jsx("input",{type:"number",value:z,onChange:ne=>M(ne.target.value),min:0,step:1,style:Mr}),e.jsx("div",{style:{fontSize:12,opacity:.65},children:"输入 0 表示不限制迭代次数。"})]}),e.jsxs(Er,{label:"上下文窗口(tokens,输入与输出合计)",children:[e.jsx("input",{type:"number",value:H,onChange:ne=>L(ne.target.value),min:1024,max:2e6,step:1,style:Mr}),e.jsx("div",{style:{fontSize:12,opacity:.65},children:"8K 模型填 8192;不能超过模型服务实际启动的上下文大小。"})]})]})]}),e.jsxs("section",{style:{marginTop:40},children:[e.jsx("h3",{style:{fontSize:13,fontWeight:600,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:14},children:"任务完成提醒"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[["completionEnabled","任务完成通知"],["soundEnabled","播放提示音"],["notifyWhileForeground","前台运行时也通知"]].map(([ne,be])=>e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:10,color:"var(--text-primary)",fontSize:14},children:[e.jsx("input",{type:"checkbox",checked:o[ne],onChange:Ye=>l("taskNotifications",{...o,[ne]:Ye.target.checked})}),be]},ne))})]}),e.jsx(Zm,{onNotice:(ne,be)=>k({message:ne,type:be})}),e.jsxs("div",{style:{marginTop:28,display:"flex",gap:14,alignItems:"center"},children:[e.jsx("button",{onClick:at,style:ru,children:"保存"}),e.jsx("span",{style:{padding:"7px 14px",borderRadius:"var(--radius-sm)",fontSize:12,fontWeight:500,background:r?"rgba(52,211,153,0.1)":"rgba(255,255,255,0.04)",color:r?"var(--success)":"var(--text-muted)",border:`1px solid ${r?"rgba(52,211,153,0.2)":"var(--border-subtle)"}`},children:r?"● 已连接":"○ 未配置"})]}),w&&e.jsx("div",{style:{marginTop:12,padding:"10px 12px",borderRadius:"var(--radius-sm)",border:E==="success"?"1px solid rgba(52,211,153,0.35)":"1px solid rgba(244,63,94,0.35)",background:E==="success"?"rgba(52,211,153,0.08)":"rgba(244,63,94,0.08)",color:E==="success"?"var(--success)":"var(--danger)",fontSize:13},children:w}),e.jsx(nu,{message:(C==null?void 0:C.message)??null,type:(C==null?void 0:C.type)??"success"})]})}function Cc({draft:t,setDraft:n,hasStoredApiKey:r,onSave:s,onCancel:i}){const o=(l,d)=>n(u=>{const f={...u,[l]:d};return l==="provider"&&!u.modelId&&(f.modelId=jc[d]??""),f});return e.jsxs("div",{style:{padding:"12px 14px 14px",display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[e.jsx(Er,{label:"名称",children:e.jsx("input",{value:t.name,onChange:l=>o("name",l.target.value),placeholder:"我的 Claude",style:Mr})}),e.jsx(Er,{label:"提供商",children:e.jsx("select",{value:t.provider,onChange:l=>{const d=l.target.value;n(u=>({...u,provider:d,modelId:jc[d]??"",requestTimeoutSeconds:$i[d]??300}))},style:Mr,children:rx.map(l=>e.jsx("option",{value:l.value,children:l.label},l.value))})})]}),e.jsx(Er,{label:"模型 ID",children:e.jsx("input",{value:t.modelId,onChange:l=>o("modelId",l.target.value),placeholder:t.provider==="aihub"?"deepseek":"claude-sonnet-4-6",style:Mr})}),e.jsx(Er,{label:"单轮最大输出(tokens)",children:e.jsx("input",{type:"number",value:t.maxOutputTokens??16384,onChange:l=>n(d=>({...d,maxOutputTokens:Number(l.target.value)})),min:256,max:131072,step:1024,style:Mr})}),e.jsx(Er,{label:"单次请求超时(秒)",children:e.jsx("input",{type:"number",value:t.requestTimeoutSeconds??$i[t.provider]??300,onChange:l=>n(d=>({...d,requestTimeoutSeconds:Number(l.target.value)})),min:30,max:1800,step:30,style:Mr})}),t.provider==="aihub"?e.jsx("div",{style:{padding:"8px 10px",background:"rgba(96,165,250,0.08)",border:"1px solid rgba(96,165,250,0.2)",borderRadius:8,fontSize:12,lineHeight:1.6},children:"AI Hub 网页模型来源:模型 ID 填 AI Hub 站点 ID(deepseek / chatgpt / gemini / grok 或自定义站点),无需 API Key。 运行时由桌面端 AI Hub 把上下文模拟人为发送给该站点并抓取回复;支持通过受控 JSON 协议调用 Agent 工具。需要桌面 App 在线且站点已登录。"}):e.jsxs(e.Fragment,{children:[e.jsx(Er,{label:"API 密钥",children:e.jsx("input",{type:"password",value:t.apiKey,onChange:l=>o("apiKey",l.target.value),placeholder:r?"••••••••••••":"sk-...","aria-label":r?"API 密钥(已保存)":"API 密钥",style:Mr})}),e.jsx(Er,{label:"接口地址(可选)",children:e.jsx("input",{value:t.baseUrl,onChange:l=>o("baseUrl",l.target.value),placeholder:"https://api.anthropic.com",style:Mr})})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:2},children:[e.jsx("button",{onClick:s,style:ru,children:"保存"}),e.jsx("button",{onClick:i,style:ix,children:"取消"})]})]})}function Er({label:t,children:n}){return e.jsxs("div",{children:[e.jsx("label",{style:{display:"block",fontSize:12,color:"var(--text-secondary)",marginBottom:6,fontWeight:500,textTransform:"uppercase",letterSpacing:"0.06em"},children:t}),n]})}const Mr={width:"100%",padding:"9px 12px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:14,outline:"none",fontFamily:"var(--font-body)",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)",boxSizing:"border-box"},ru={padding:"11px 28px",borderRadius:"var(--radius-sm)",border:"1px solid transparent",background:"var(--accent)",color:"var(--text-inverse)",fontSize:14,fontWeight:600,cursor:"pointer",fontFamily:"var(--font-body)",boxShadow:"0 2px 16px var(--accent-glow)",transition:"transform 0.15s var(--ease-out), box-shadow 0.15s var(--ease-out)"},ix={padding:"11px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-secondary)",fontSize:14,fontWeight:500,cursor:"pointer",fontFamily:"var(--font-body)",whiteSpace:"nowrap",transition:"all 0.15s var(--ease-out)"},ox={padding:"6px 14px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-secondary)",fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:"var(--font-body)"},Wo={padding:"4px 10px",borderRadius:6,border:"1px solid var(--border-subtle)",background:"transparent",color:"var(--text-muted)",fontSize:12,cursor:"pointer",fontFamily:"var(--font-body)"},ax={fontSize:13,fontWeight:600,color:"var(--text-secondary)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:14},Ic={display:"flex",alignItems:"center",justifyContent:"space-between",gap:10,padding:"8px 12px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",background:"var(--bg-surface)",fontSize:13};function lx({onboarding:t=!1}){const n=typeof window>"u"?void 0:window.agentApi,r=!!(n!=null&&n.desktopLiveGetStatus),[s,i]=a.useState(null),[o,l]=a.useState(!1),[d,u]=a.useState(null),[f,p]=a.useState(!0);a.useEffect(()=>{if(!(n!=null&&n.desktopLiveGetStatus)||!(n!=null&&n.onDesktopLiveStatus))return;let S=!0;n.desktopLiveSetup().then(k=>{S&&(i(k.status),p(k.supported))}).catch(()=>{});const C=n.onDesktopLiveStatus(k=>i(k));return()=>{S=!1,C()}},[n]);const v=async()=>{if(n!=null&&n.desktopLiveRecheck)try{i(await n.desktopLiveRecheck()),u(null)}catch(S){u(S instanceof Error?S.message:String(S))}};a.useEffect(()=>{if(!r||!f)return;let S=!0,C=!1;const k=async()=>{if(!C){C=!0;try{const M=await n.desktopLiveRecheck();S&&i(M)}catch{}finally{C=!1}}};window.addEventListener("focus",k);const z=s!=null&&s.enabled&&(s.permissionScreen!=="granted"||s.accessibilityTrusted!==!0)?window.setInterval(k,3e3):void 0;return()=>{S=!1,window.removeEventListener("focus",k),z&&window.clearInterval(z)}},[n,r,f,s==null?void 0:s.enabled,s==null?void 0:s.permissionScreen,s==null?void 0:s.accessibilityTrusted]);const x=async S=>{if(n){l(!0);try{i(await n.desktopLiveSetEnabled(!0)),await n.desktopLiveOpenPermission(S),u(null)}catch(C){u(C instanceof Error?C.message:String(C))}finally{l(!1)}}};if(!r)return null;const w=async()=>{if(n!=null&&n.desktopLiveSetEnabled){l(!0);try{i(await n.desktopLiveSetEnabled(!(s!=null&&s.enabled))),u(null)}catch(S){u(S instanceof Error?S.message:String(S))}finally{l(!1)}}},j=(s==null?void 0:s.permissionScreen)==="granted",E=(s==null?void 0:s.accessibilityTrusted)===!0;return e.jsxs("section",{className:"desktop-permission-settings",children:[e.jsx("h3",{style:ax,children:t?"设置桌面端权限":"桌面直播与远程控制"}),e.jsx("p",{style:{fontSize:13,color:"var(--text-muted)",margin:"0 0 14px",lineHeight:1.6},children:t?"欢迎使用 AgentRoam。请为桌面端开启以下系统权限,完成后手机即可查看电脑画面;允许辅助功能后还可操作鼠标和键盘。":"开启后,已配对手机可查看电脑画面,并在授予辅助功能权限后操作鼠标和键盘。"}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,marginBottom:12},children:[e.jsx("button",{type:"button",onClick:()=>void w(),disabled:o||!f,style:{padding:"7px 16px",borderRadius:"var(--radius-sm)",border:`1px solid ${s!=null&&s.enabled?"rgba(244,63,94,0.35)":"var(--accent)"}`,background:s!=null&&s.enabled?"rgba(244,63,94,0.1)":"var(--accent-dim)",color:s!=null&&s.enabled?"var(--danger)":"var(--accent)",fontSize:13,fontWeight:600,cursor:"pointer"},children:o?"处理中…":s!=null&&s.enabled?t?"暂停手机查看":"关闭桌面直播":t?"开启手机查看":"开启桌面直播"}),(s==null?void 0:s.enabled)&&e.jsx("span",{style:{fontSize:12,color:s.sessionOnline?"var(--success)":"var(--text-muted)"},children:s.sessionOnline?"● 已连接,可从手机查看":"○ 未连接"})]}),!f&&e.jsx("p",{role:"status",children:"当前远程桌面仅支持 macOS,其他桌面功能可正常使用。"}),f&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[e.jsxs("div",{className:"desktop-permission-row",style:Ic,children:[e.jsx("span",{children:"屏幕录制(画面采集)"}),e.jsx("span",{style:{color:j?"var(--success)":"var(--danger)",fontWeight:600},children:j?"已授权":"未授权"}),!j&&e.jsx("button",{type:"button",className:"ui-quiet-button desktop-permission-button",disabled:o,onClick:()=>void x("screen"),children:"去授权"})]}),e.jsxs("div",{className:"desktop-permission-row",style:Ic,children:[e.jsx("span",{children:"辅助功能(键鼠控制)"}),e.jsx("span",{style:{color:E?"var(--success)":"var(--danger)",fontWeight:600},children:(s==null?void 0:s.accessibilityTrusted)===null?"待检测":E?"已授权":"未授权"}),!E&&e.jsx("button",{type:"button",className:"ui-quiet-button desktop-permission-button",disabled:o,onClick:()=>void x("accessibility"),children:"去授权"})]})]}),f&&e.jsxs(e.Fragment,{children:[e.jsx("p",{style:{marginTop:14,fontSize:12,color:"var(--text-muted)",lineHeight:1.6},children:"点击对应权限的「去授权」,在系统设置中允许 AgentRoam,返回后自动检测。"}),e.jsxs("details",{className:"desktop-permission-more",children:[e.jsx("summary",{children:"更多操作"}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:8},children:[e.jsx("button",{type:"button",className:"ui-quiet-button",onClick:()=>void v(),children:"重新检测"}),!j&&e.jsx("button",{type:"button",className:"ui-quiet-button",onClick:()=>void(n==null?void 0:n.desktopLiveRestart()),children:"重启桌面端"})]})]})]}),d&&e.jsx("p",{role:"alert",style:{color:"var(--danger)"},children:d}),(s==null?void 0:s.error)&&e.jsx("div",{style:{marginTop:10,fontSize:12,color:"var(--danger)"},role:"alert",children:s.error})]})}function cx({onClose:t}){const n=a.useRef(null);return a.useEffect(()=>{var r;(r=n.current)==null||r.showModal()},[]),On.createPortal(e.jsx("dialog",{ref:n,"aria-label":"桌面直播与远程控制",onCancel:t,onClick:r=>{r.target===r.currentTarget&&t()},style:{width:"min(680px, calc(100vw - 48px))",maxHeight:"calc(100vh - 48px)",padding:0,margin:"auto",inset:0,overflowY:"auto",color:"var(--text-primary)",background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-md)"},children:e.jsxs("div",{style:{padding:24},children:[e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:8},children:e.jsx("button",{type:"button",onClick:t,"aria-label":"关闭桌面直播设置",className:"ui-icon-button ui-icon-button--close",children:"×"})}),e.jsx(lx,{}),e.jsx("div",{className:"desktop-permission-footer",children:e.jsx("button",{type:"button",className:"ui-quiet-button",onClick:t,children:"关闭"})})]})}),document.body)}const Fo={id:"",name:"",command:"",args:"",url:"",headersRaw:""};function dx(){const[t,n]=a.useState([]),[r,s]=a.useState("stdio"),[i,o]=a.useState(Fo),[l,d]=a.useState(!1),[u,f]=a.useState({id:!1,command:!1,url:!1}),[p,v]=a.useState({}),[x,w]=a.useState({}),[j,E]=a.useState(new Set),[S,C]=a.useState(null),[k,z]=a.useState(""),[M,H]=a.useState(!1),L=async W=>{var G;if(!((G=window.agentApi)!=null&&G.mcpProbe))return;E(le=>new Set([...le,W.id])),w(le=>{const pe={...le};return delete pe[W.id],pe});const te=new Promise((le,pe)=>setTimeout(()=>pe(new Error("连接超时(15s)")),15e3));try{const le=await Promise.race([window.agentApi.mcpProbe(W),te]);v(pe=>({...pe,[W.id]:le}))}catch(le){const pe=le instanceof Error?le.message:String(le);console.warn(`[MCP] probe failed for ${W.id}:`,pe),v(ye=>{const we={...ye};return delete we[W.id],we}),w(ye=>({...ye,[W.id]:pe})),(W.transport==="sse"||/401|403|unauthorized|forbidden|需要认证|访问被拒绝/i.test(pe))&&(z(""),C({server:W}))}finally{E(le=>{const pe=new Set(le);return pe.delete(W.id),pe})}};a.useEffect(()=>{window.agentApi&&window.agentApi.mcpList().then(W=>{n(W),W.filter(te=>te.enabled!==!1).forEach(te=>L(te))}).catch(console.error)},[]);const[T,A]=a.useState(""),[R,$]=a.useState(""),[F,Ee]=a.useState(!1),Qe=async()=>{$("");let W;try{W=JSON.parse(T.trim());const te=W.mcpServers??W,G=Object.entries(te);if(G.length===0){$("未找到任何服务器");return}Ee(!0);const le=[];for(const[ye,we]of G){const Te=we,ut=Te.name||ye,st=Te.disabled!==!0;let Tt;if(Te.url||Te.type==="streamableHttp"||Te.type==="sse"){const He=Te.type==="sse"?"sse":"streamableHttp";Tt={id:ye,name:ut,transport:He,url:Te.url,headers:Te.headers??{},env:Te.env??{},enabled:st}}else Tt={id:ye,name:ut,transport:"stdio",command:Te.command,args:Te.args??[],env:Te.env??{},enabled:st};await window.agentApi.mcpSave(Tt),le.push(Tt)}const pe=await window.agentApi.mcpList();n(pe),A(""),le.filter(ye=>ye.enabled!==!1).forEach(ye=>L(ye))}catch(te){$(te instanceof Error?te.message:"JSON 解析失败")}finally{Ee(!1)}},ae=()=>i.id.trim()!==""&&i.command.trim()!=="",ke=()=>i.id.trim()!==""&&i.url.trim()!=="",De=W=>{const te={};for(const G of W.split(`
|
|
474
|
+
`)){const le=G.indexOf(":");if(le<1)continue;const pe=G.slice(0,le).trim(),ye=G.slice(le+1).trim();pe&&(te[pe]=ye)}return te},Ie=async()=>{if(f({id:!0,command:!0,url:!0}),!(r==="stdio"&&!ae())&&!((r==="sse"||r==="streamableHttp")&&!ke())){d(!0);try{const W=r==="sse"||r==="streamableHttp"?De(i.headersRaw):{},te=r==="stdio"?{id:i.id,name:i.name||i.id,transport:"stdio",command:i.command,args:i.args.split(" ").filter(Boolean),enabled:!0}:{id:i.id,name:i.name||i.id,transport:r,url:i.url,headers:W,enabled:!0};await window.agentApi.mcpSave(te);const G=await window.agentApi.mcpList();n(G),o(Fo),f({id:!1,command:!1,url:!1}),L(te)}catch(W){console.error("Failed to save MCP server",W)}finally{d(!1)}}},We=async W=>{await window.agentApi.mcpDelete(W),n(t.filter(te=>te.id!==W))},at=async(W,te)=>{await window.agentApi.mcpSetEnabled(W,te),n(t.map(G=>G.id===W?{...G,enabled:te}:G))},Ge=async()=>{if(!(!S||!k.trim())){H(!0);try{const W=S.server.transport==="streamableHttp"?{...S.server,headers:{...S.server.headers??{},Authorization:`Bearer ${k.trim()}`}}:{...S.server,env:{...S.server.env??{},Authorization:`Bearer ${k.trim()}`}};await window.agentApi.mcpSave(W);const te=await window.agentApi.mcpList();n(te),C(null),z("");const G=te.find(le=>le.id===W.id)??W;L(G)}finally{H(!1)}}},ne=W=>W==="stdio"?"本地":W==="streamableHttp"?"HTTP":"SSE",be=W=>W==="stdio"?"#68d391":W==="streamableHttp"?"#f6ad55":"#63b3ed",Ye=W=>W==="stdio"?"rgba(154,230,180,0.15)":W==="streamableHttp"?"rgba(246,173,85,0.15)":"rgba(99,179,237,0.15)";return e.jsxs("div",{style:{padding:"40px 48px",maxWidth:660,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsx("h2",{style:{fontFamily:"var(--font-display)",fontSize:28,color:"var(--text-primary)",fontWeight:400,marginBottom:8,letterSpacing:"-0.02em"},children:"MCP 服务器"}),e.jsx("p",{style:{color:"var(--text-muted)",fontSize:14,marginBottom:32},children:"通过模型上下文协议连接外部工具。"}),e.jsxs("div",{style:{padding:20,background:"var(--bg-glass)",borderRadius:"var(--radius-md)",border:"1px solid var(--border-subtle)",marginBottom:28,backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:16},children:[e.jsx("h3",{style:{fontSize:14,fontWeight:600,color:"var(--text-primary)",margin:0},children:"添加服务器"}),e.jsx("div",{style:{display:"flex",background:"var(--bg-surface)",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",overflow:"hidden"},children:["stdio","sse","streamableHttp"].map(W=>e.jsx("button",{onClick:()=>{s(W),f({id:!1,command:!1,url:!1}),o(te=>({...Fo,id:te.id,name:te.name}))},style:{padding:"5px 14px",border:"none",fontSize:12,fontWeight:500,cursor:"pointer",fontFamily:"var(--font-body)",transition:"background 0.15s",background:r===W?"var(--accent)":"transparent",color:r===W?"var(--text-inverse)":"var(--text-muted)"},children:W==="stdio"?"本地 stdio":W==="sse"?"远程 SSE":"HTTP"},W))})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsxs("div",{style:{display:"flex",gap:10},children:[e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4},children:[e.jsx("input",{value:i.id,onChange:W=>o(te=>({...te,id:W.target.value})),onBlur:()=>f(W=>({...W,id:!0})),placeholder:"服务器 ID *",style:{...Ur,...u.id&&!i.id?Bo:{}}}),u.id&&!i.id&&e.jsx("span",{style:{fontSize:11,color:"var(--danger)"},children:"必填"})]}),e.jsx("input",{value:i.name,onChange:W=>o(te=>({...te,name:W.target.value})),placeholder:"显示名称",style:{...Ur,flex:1}})]}),r==="stdio"?e.jsxs("div",{style:{display:"flex",gap:10},children:[e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",gap:4},children:[e.jsx("input",{value:i.command,onChange:W=>o(te=>({...te,command:W.target.value})),onBlur:()=>f(W=>({...W,command:!0})),placeholder:"命令(如 npx)*",style:{...Ur,...u.command&&!i.command?Bo:{}}}),u.command&&!i.command&&e.jsx("span",{style:{fontSize:11,color:"var(--danger)"},children:"必填"})]}),e.jsx("input",{value:i.args,onChange:W=>o(te=>({...te,args:W.target.value})),placeholder:"参数(如 -y @anthropic/mcp-server)",style:{...Ur,flex:2}})]}):e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[e.jsx("input",{value:i.url,onChange:W=>o(te=>({...te,url:W.target.value})),onBlur:()=>f(W=>({...W,url:!0})),placeholder:r==="streamableHttp"?"HTTP URL(如 http://host/mcp)*":"SSE URL(如 https://mcp.example.com/sse)*",style:{...Ur,...u.url&&!i.url?Bo:{}}}),u.url&&!i.url&&e.jsx("span",{style:{fontSize:11,color:"var(--danger)"},children:"必填"})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[e.jsx("label",{style:{fontSize:12,color:"var(--text-muted)"},children:"请求头(每行 key: value)"}),e.jsx("textarea",{value:i.headersRaw,onChange:W=>o(te=>({...te,headersRaw:W.target.value})),placeholder:`access_token: abc123
|
|
475
475
|
Authorization: Bearer sk-...`,rows:3,style:{...Ur,fontFamily:"var(--font-mono)",fontSize:12,resize:"vertical"}})]})]}),e.jsx("button",{onClick:Ie,disabled:l,style:{alignSelf:"flex-start",padding:"10px 22px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"var(--text-inverse)",fontSize:13,fontWeight:600,cursor:l?"not-allowed":"pointer",fontFamily:"var(--font-body)"},children:l?"保存中…":"添加服务器"})]})]}),e.jsxs("div",{style:{marginBottom:28,padding:20,background:"var(--bg-glass)",borderRadius:"var(--radius-md)",border:"1px solid var(--border-subtle)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},children:[e.jsx("h3",{style:{fontSize:14,fontWeight:600,color:"var(--text-primary)",margin:"0 0 8px"},children:"导入 JSON 配置"}),e.jsx("p",{style:{fontSize:12,color:"var(--text-muted)",margin:"0 0 10px"},children:"兼容 Claude Desktop / Cursor 格式,粘贴后点导入。"}),e.jsx("textarea",{value:T,onChange:W=>{A(W.target.value),$("")},placeholder:`{
|
|
476
476
|
"my-server": {
|
|
477
477
|
"command": "npx",
|
|
478
478
|
"args": ["-y", "some-mcp"]
|
|
479
479
|
}
|
|
480
|
-
}`,rows:5,style:{...Ur,width:"100%",boxSizing:"border-box",fontFamily:"var(--font-mono)",fontSize:12,resize:"vertical",marginBottom:8}}),R&&e.jsx("div",{style:{fontSize:12,color:"var(--danger)",marginBottom:8},children:R}),e.jsx("button",{onClick:Ke,disabled:!T.trim()||F,style:{padding:"8px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"var(--text-inverse)",fontSize:13,fontWeight:600,cursor:T.trim()&&!F?"pointer":"not-allowed",fontFamily:"var(--font-body)",opacity:T.trim()&&!F?1:.5},children:F?"导入中…":"导入"})]}),t.filter(W=>W.transport===r).length===0?e.jsxs("div",{style:{color:"var(--text-muted)",fontSize:14,padding:"40px 0",textAlign:"center"},children:["暂无",r==="stdio"?"本地 stdio":r==="sse"?"远程 SSE":"HTTP"," 服务器,点击上方添加。"]}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:t.filter(W=>W.transport===r).map(W=>e.jsxs("div",{style:{padding:"14px 16px",background:"var(--bg-glass)",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",display:"flex",justifyContent:"space-between",alignItems:"center",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",transition:"border-color 0.2s"},children:[e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"var(--text-primary)"},children:W.name||W.id}),e.jsx("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:4,background:Ye(W.transport),color:be(W.transport),fontWeight:600},children:ne(W.transport)})]}),e.jsxs("div",{style:{fontSize:12,color:"var(--text-muted)",marginTop:2,fontFamily:"var(--font-mono)"},children:[W.transport==="stdio"?`${W.command} ${(W.args??[]).join(" ")}`:W.url,W.transport!=="stdio"&&W.headers&&Object.keys(W.headers).length>0&&e.jsxs("span",{style:{marginLeft:6,fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-body)"},children:["· ",Object.keys(W.headers).length," 个请求头"]})]}),j.has(W.id)?e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:6,display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",border:"2px solid var(--accent)",borderTopColor:"transparent",animation:"spin 0.8s linear infinite"}}),"探测工具中…"]}):x[W.id]?e.jsxs("div",{style:{marginTop:6,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:11,color:"var(--danger)"},children:x[W.id]}),W.transport==="sse"||/401|403|unauthorized|forbidden|需要认证|访问被拒绝/i.test(x[W.id])?e.jsx("button",{onClick:()=>{z(""),C({server:W})},style:{fontSize:11,padding:"2px 8px",borderRadius:4,border:"1px solid rgba(251,191,36,0.4)",background:"rgba(251,191,36,0.1)",color:"#fbbf24",cursor:"pointer",fontFamily:"var(--font-body)"},children:"输入 Token"}):null,e.jsx("button",{onClick:()=>L(W),style:{fontSize:11,padding:"2px 8px",borderRadius:4,border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontFamily:"var(--font-body)"},children:"重试"})]}):p[W.id]&&p[W.id].length>0?e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6},children:p[W.id].map(te=>e.jsx("span",{title:te.description,style:{fontSize:11,padding:"2px 8px",borderRadius:10,background:"rgba(168,85,247,0.12)",color:"#c084fc",border:"1px solid rgba(168,85,247,0.2)",fontFamily:"var(--font-mono)",cursor:"default"},children:te.name},te.name))}):p[W.id]!==void 0?e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:6},children:"无可用工具"}):null]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsxs("label",{style:{fontSize:12,color:"var(--text-muted)",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:[e.jsx("input",{type:"checkbox",checked:W.enabled!==!1,onChange:te=>at(W.id,te.target.checked),style:{cursor:"pointer"}}),"启用"]}),e.jsx("button",{onClick:()=>We(W.id),style:{padding:"5px 12px",borderRadius:"var(--radius-sm)",border:"1px solid rgba(248,113,113,0.2)",background:"transparent",color:"var(--danger)",fontSize:12,cursor:"pointer",fontFamily:"var(--font-body)",fontWeight:500,transition:"background 0.15s"},onMouseEnter:te=>{te.currentTarget.style.background="rgba(248,113,113,0.1)"},onMouseLeave:te=>{te.currentTarget.style.background="transparent"},children:"移除"})]})]},W.id))}),S&&e.jsx("div",{style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)",backdropFilter:"blur(4px)"},onClick:W=>{W.target===W.currentTarget&&C(null)},children:e.jsxs("div",{style:{width:420,background:"var(--bg-surface)",borderRadius:"var(--radius-md)",border:"1px solid var(--border-default)",padding:28,boxShadow:"0 24px 48px rgba(0,0,0,0.4)"},children:[e.jsx("h3",{style:{margin:"0 0 6px",fontSize:16,fontWeight:600,color:"var(--text-primary)"},children:"需要认证"}),e.jsxs("p",{style:{margin:"0 0 20px",fontSize:13,color:"var(--text-muted)"},children:["服务器 ",e.jsx("strong",{style:{color:"var(--text-primary)"},children:S.server.name||S.server.id})," 返回了 401/403,请输入访问令牌(Bearer Token)。"]}),e.jsx("input",{autoFocus:!0,type:"password",value:k,onChange:W=>z(W.target.value),onKeyDown:W=>{W.key==="Enter"&&qe(),W.key==="Escape"&&C(null)},placeholder:"sk-… 或 Bearer token",style:{...Ur,width:"100%",boxSizing:"border-box",marginBottom:16}}),e.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end"},children:[e.jsx("button",{onClick:()=>C(null),style:{padding:"8px 18px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-muted)",fontSize:13,cursor:"pointer",fontFamily:"var(--font-body)"},children:"取消"}),e.jsx("button",{onClick:qe,disabled:!k.trim()||M,style:{padding:"8px 18px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"var(--text-inverse)",fontSize:13,fontWeight:600,cursor:k.trim()&&!M?"pointer":"not-allowed",fontFamily:"var(--font-body)",opacity:k.trim()&&!M?1:.5},children:M?"保存中…":"保存并重试"})]})]})}),e.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})}const Ur={padding:"10px 14px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:13,outline:"none",fontFamily:"var(--font-body)"},Bo={border:"1px solid var(--danger)",boxShadow:"0 0 0 2px rgba(248,113,113,0.15)"};function ux(){const[t,n]=a.useState([]),[r,s]=a.useState(""),[i,o]=a.useState(null),[l,d]=a.useState(!1),[u,f]=a.useState(""),[p,v]=a.useState(""),[x,w]=a.useState("user"),[j,E]=a.useState(""),[S,C]=a.useState(null),[k,z]=a.useState("success"),M=async()=>{if(window.agentApi){const A=await window.agentApi.listMemories();n(A)}};a.useEffect(()=>{M()},[]);const H=async()=>{if(!r.trim()){M();return}if(window.agentApi){const A=await window.agentApi.searchMemories(r);n(A.map(R=>R.entry))}},L=async()=>{if(!(!u.trim()||!window.agentApi))try{await window.agentApi.setMemory({name:u.trim(),description:p,type:x,content:j,created:(i==null?void 0:i.created)??new Date().toISOString(),updated:new Date().toISOString()}),d(!1),o(null),f(""),v(""),E(""),w("user"),C("保存成功"),z("success"),await M()}catch(A){C(A instanceof Error?A.message:"保存失败"),z("error")}},T=A=>{o(A),f(A.name),v(A.description),w(A.type),E(A.content),d(!0)};return e.jsxs("div",{style:{padding:"40px 48px",maxWidth:720,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:24},children:[e.jsxs("div",{children:[e.jsx("h2",{style:{fontFamily:"var(--font-display)",fontSize:28,color:"var(--text-primary)",fontWeight:400,letterSpacing:"-0.02em"},children:"记忆"}),e.jsx("p",{style:{color:"var(--text-muted)",fontSize:14,marginTop:4},children:"跨会话的持久化知识库。"})]}),e.jsx("button",{onClick:()=>{d(!0),o(null),f(""),v(""),E(""),w("user")},style:{padding:"10px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"var(--text-inverse)",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"var(--font-body)"},children:"+ 新建"})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginBottom:24},children:[e.jsx("input",{value:r,onChange:A=>s(A.target.value),onKeyDown:A=>A.key==="Enter"&&H(),placeholder:"搜索记忆...",style:{flex:1,padding:"10px 14px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:14,outline:"none",fontFamily:"var(--font-body)",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)"}}),e.jsx("button",{onClick:H,style:Rc,children:"搜索"})]}),S&&e.jsx("div",{style:{padding:"10px 12px",borderRadius:"var(--radius-sm)",border:k==="success"?"1px solid rgba(52,211,153,0.35)":"1px solid rgba(244,63,94,0.35)",background:k==="success"?"rgba(52,211,153,0.08)":"rgba(244,63,94,0.08)",color:k==="success"?"var(--success)":"var(--danger)",fontSize:13,marginBottom:16},children:S}),l&&e.jsxs("div",{style:{padding:20,marginBottom:24,background:"var(--bg-glass)",borderRadius:"var(--radius-md)",border:"1px solid var(--border-subtle)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},children:[e.jsx("input",{value:u,onChange:A=>f(A.target.value),placeholder:"名称",style:{...Mi,marginBottom:10},disabled:!!i}),e.jsx("input",{value:p,onChange:A=>v(A.target.value),placeholder:"描述",style:{...Mi,marginBottom:10}}),e.jsxs("select",{value:x,onChange:A=>w(A.target.value),style:{...Mi,marginBottom:10},children:[e.jsx("option",{value:"user",children:"用户"}),e.jsx("option",{value:"feedback",children:"反馈"}),e.jsx("option",{value:"project",children:"项目"}),e.jsx("option",{value:"reference",children:"参考"})]}),e.jsx("textarea",{value:j,onChange:A=>E(A.target.value),placeholder:"内容",rows:5,style:{...Mi,marginBottom:12,resize:"vertical"}}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:L,style:{padding:"9px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--success)",color:"#000",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"var(--font-body)"},children:"保存"}),e.jsx("button",{onClick:()=>d(!1),style:Rc,children:"取消"})]})]}),t.map(A=>e.jsxs("div",{style:{padding:"14px 16px",marginBottom:8,background:"var(--bg-glass)",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",transition:"border-color 0.2s"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontSize:14},children:A.name}),e.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:10,background:"rgba(255,255,255,0.04)",color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:500},children:A.type})]}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:()=>T(A),style:Ec,children:"编辑"}),e.jsx("button",{onClick:async()=>{if(window.agentApi)try{await window.agentApi.deleteMemory(A.name),C("删除成功"),z("success"),await M()}catch(R){C(R instanceof Error?R.message:"删除失败"),z("error")}},style:{...Ec,color:"var(--danger)"},children:"删除"})]})]}),A.description&&e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)",marginTop:4},children:A.description}),e.jsxs("div",{style:{fontSize:12,color:"var(--text-muted)",marginTop:4,lineHeight:1.5},children:[A.content.slice(0,180),A.content.length>180?"…":""]})]},A.name)),t.length===0&&!l&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:14,padding:"60px 0",textAlign:"center"},children:"暂无记忆,点击「新建」创建一条。"})]})}const Mi={width:"100%",padding:"11px 14px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:14,outline:"none",fontFamily:"var(--font-body)",boxSizing:"border-box"},Rc={padding:"10px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-secondary)",fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:"var(--font-body)"},Ec={padding:"4px 10px",borderRadius:6,fontSize:11,border:"none",background:"rgba(255,255,255,0.05)",color:"var(--text-secondary)",cursor:"pointer",fontFamily:"var(--font-body)",fontWeight:500},px=()=>({name:"",description:"",triggers:[],prompt:"",filePath:"",enabled:!0});function fx(){const[t,n]=a.useState([]),[r,s]=a.useState(null),[i,o]=a.useState(!1),[l,d]=a.useState(null),[u,f]=a.useState("success"),[p,v]=a.useState(""),x=(T,A="success")=>{d(T),f(A),setTimeout(()=>d(null),3e3)},w=async()=>{if(!window.agentApi)return;const T=await window.agentApi.listSkills();n(T)};a.useEffect(()=>{w()},[]);const j=T=>{s({...T}),v((T.triggers??[]).join(", ")),o(!1)},E=()=>{s(px()),v(""),o(!0)},S=()=>{s(null),o(!1)},C=async()=>{if(!r||!window.agentApi)return;if(!r.name.trim()){x("名称不能为空","error");return}const T=p.split(",").map(A=>A.trim()).filter(Boolean);try{await window.agentApi.saveSkill({name:r.name.trim(),description:r.description,triggers:T,prompt:r.prompt,filePath:r.filePath??""}),x(i?"技能已创建":"技能已保存"),s(null),await w()}catch(A){x(A instanceof Error?A.message:"保存失败","error")}},k=async T=>{if(window.agentApi)try{await window.agentApi.deleteSkill(T),x("已删除"),(r==null?void 0:r.name)===T&&s(null),await w()}catch(A){x(A instanceof Error?A.message:"删除失败","error")}},z=async T=>{if(!window.agentApi)return;const A=!T.enabled;await window.agentApi.setSkillEnabled(T.name,A),await w()},M=async()=>{if(window.agentApi)try{const T=await window.agentApi.importSkill();if(!T)return;x(`已导入技能「${T.name}」,本次会话立即生效`),await w()}catch(T){x(T instanceof Error?T.message:"导入失败","error")}},H={width:"100%",padding:"8px 10px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:13,fontFamily:"var(--font-body)",outline:"none",boxSizing:"border-box"},L={fontSize:11,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4,display:"block"};return e.jsxs("div",{style:{padding:"40px 48px",maxWidth:720,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:24},children:[e.jsxs("div",{children:[e.jsx("h2",{style:{fontSize:20,fontWeight:600,color:"var(--text-primary)",margin:0},children:"技能管理"}),e.jsx("p",{style:{fontSize:13,color:"var(--text-muted)",margin:"4px 0 0"},children:"配置触发词和提示词,让 Agent 自动激活专属技能"})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:M,style:{padding:"8px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-secondary)",fontSize:13,fontWeight:600,cursor:"pointer"},children:"↓ 导入技能"}),e.jsx("button",{onClick:E,style:{padding:"8px 16px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer"},children:"+ 新建技能"})]})]}),l&&e.jsx("div",{style:{marginBottom:16,padding:"8px 12px",borderRadius:"var(--radius-sm)",border:u==="success"?"1px solid rgba(52,211,153,0.35)":"1px solid rgba(244,63,94,0.35)",background:u==="success"?"rgba(52,211,153,0.08)":"rgba(244,63,94,0.08)",color:u==="success"?"var(--success)":"var(--danger)",fontSize:13},children:l}),r&&e.jsxs("div",{style:{marginBottom:24,padding:"20px 24px",borderRadius:"var(--radius-md)",border:"1px solid var(--border-glow)",background:"var(--bg-glass)"},children:[e.jsx("h3",{style:{margin:"0 0 16px",fontSize:14,fontWeight:600,color:"var(--text-primary)"},children:i?"新建技能":`编辑:${r.name}`}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsxs("div",{children:[e.jsx("label",{style:L,children:"名称"}),e.jsx("input",{style:H,value:r.name,disabled:!i,onChange:T=>s({...r,name:T.target.value}),placeholder:"技能唯一标识,如 code-review"})]}),e.jsxs("div",{children:[e.jsx("label",{style:L,children:"描述"}),e.jsx("input",{style:H,value:r.description,onChange:T=>s({...r,description:T.target.value}),placeholder:"简短说明这个技能的用途"})]}),e.jsxs("div",{children:[e.jsx("label",{style:L,children:"触发词(逗号分隔)"}),e.jsx("input",{style:H,value:p,onChange:T=>v(T.target.value),placeholder:"代码审查, review, 审查代码"})]}),e.jsxs("div",{children:[e.jsx("label",{style:L,children:"提示词"}),e.jsx("textarea",{style:{...H,minHeight:120,resize:"vertical"},value:r.prompt,onChange:T=>s({...r,prompt:T.target.value}),placeholder:"当触发词匹配时,注入到系统提示的内容..."})]})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:16},children:[e.jsx("button",{onClick:C,style:{padding:"8px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer"},children:"保存"}),e.jsx("button",{onClick:S,style:{padding:"8px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-secondary)",fontSize:13,cursor:"pointer"},children:"取消"})]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.length===0&&!r&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:13,padding:"20px 0",textAlign:"center"},children:"暂无技能,点击「新建技能」创建第一个"}),t.map(T=>{var A;return e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:"14px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",background:"var(--bg-glass)",opacity:T.enabled===!1?.5:1},children:[e.jsx("button",{onClick:()=>z(T),title:T.enabled===!1?"已禁用,点击启用":"点击禁用",style:{flexShrink:0,marginTop:2,width:32,height:18,borderRadius:9,border:"none",background:T.enabled===!1?"var(--border-default)":"var(--accent)",cursor:"pointer",position:"relative",transition:"background 0.2s"},children:e.jsx("span",{style:{position:"absolute",top:2,left:T.enabled===!1?2:14,width:14,height:14,borderRadius:"50%",background:"#fff",transition:"left 0.2s"}})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:2},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:"var(--text-primary)"},children:T.name}),((A=T.triggers)==null?void 0:A.length)>0&&e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["触发词:",T.triggers.slice(0,3).join(" · "),T.triggers.length>3?" ...":""]})]}),T.description&&e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:4},children:T.description}),T.prompt&&e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",opacity:.7},children:[T.prompt.slice(0,80),T.prompt.length>80?"...":""]})]}),e.jsxs("div",{style:{display:"flex",gap:6,flexShrink:0},children:[e.jsx("button",{onClick:()=>j(T),style:{padding:"5px 12px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-secondary)",fontSize:12,cursor:"pointer"},children:"编辑"}),e.jsx("button",{onClick:()=>k(T.name),style:{padding:"5px 12px",borderRadius:"var(--radius-sm)",border:"1px solid rgba(244,63,94,0.3)",background:"transparent",color:"var(--danger)",fontSize:12,cursor:"pointer"},children:"删除"})]})]},T.name)})]})]})}const Ai=[{name:"read_file",label:"读取文件"},{name:"write_file",label:"写入文件"},{name:"bash",label:"执行命令"},{name:"web_fetch",label:"网页抓取"},{name:"web_search",label:"网络搜索"},{name:"grep",label:"文件搜索"}];function su(){return{profileId:"",enabledTools:[],enabledSkills:[],enabledMCPServers:[]}}function hx(){return{name:"",description:"",systemPrompt:"",contextPlaceholders:[],capabilities:su(),maxIterations:0,isDefault:!1}}const sa={padding:"5px 12px",borderRadius:7,border:"1px solid var(--border-default)",background:"var(--bg-deep)",color:"var(--text-secondary)",fontSize:12,fontWeight:500,cursor:"pointer"},ai={padding:"3px 9px",borderRadius:6,border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-muted)",fontSize:11,cursor:"pointer"},Vr={width:"100%",padding:"7px 10px",borderRadius:7,border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:13,outline:"none",boxSizing:"border-box"},qr={fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:5,display:"block"};function gx({ph:t,onChange:n,onDelete:r}){return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1.5fr 1fr auto",gap:6,alignItems:"center"},children:[e.jsx("input",{style:Vr,placeholder:"变量名 (e.g. project)",value:t.key,onChange:s=>n({...t,key:s.target.value})}),e.jsx("input",{style:Vr,placeholder:"说明",value:t.description,onChange:s=>n({...t,description:s.target.value})}),e.jsx("input",{style:Vr,placeholder:"默认值",value:t.defaultValue,onChange:s=>n({...t,defaultValue:s.target.value})}),e.jsx("button",{onClick:r,style:{...ai,color:"var(--danger)",borderColor:"rgba(244,63,94,0.25)",flexShrink:0},children:"✕"})]})}function Mc({initial:t,activeAgentId:n,onSave:r,onCancel:s}){const{profiles:i}=qi(),[o,l]=a.useState([]),[d,u]=a.useState([]),[f,p]=a.useState({...hx(),...t,capabilities:{...su(),...t.capabilities??{}}}),[v,x]=a.useState(null),[w,j]=a.useState(!1);a.useEffect(()=>{var R,$;window.agentApi&&(window.agentApi.listSkills().then(F=>{l(F.filter(Ee=>Ee.name))}),($=(R=window.agentApi).listMCPServers)==null||$.call(R).then(F=>{u(F??[])}).catch(()=>{}))},[]);const E=R=>p($=>({...$,capabilities:{...$.capabilities,...R}})),S=R=>{const $=f.capabilities.enabledTools;if($.length===0){const F=Ai.map(Ee=>Ee.name).filter(Ee=>Ee!==R);E({enabledTools:F})}else if($.includes(R)){const F=$.filter(Ee=>Ee!==R);E({enabledTools:F})}else{const F=[...$,R];F.length===Ai.length?E({enabledTools:[]}):E({enabledTools:F})}},C=R=>{const $=f.capabilities.enabledSkills;E({enabledSkills:$.includes(R)?$.filter(F=>F!==R):[...$,R]})},k=R=>{const $=f.capabilities.enabledMCPServers;E({enabledMCPServers:$.includes(R)?$.filter(F=>F!==R):[...$,R]})},z=()=>p(R=>({...R,contextPlaceholders:[...R.contextPlaceholders,{key:"",description:"",defaultValue:""}]})),M=(R,$)=>p(F=>{const Ee=[...F.contextPlaceholders];return Ee[R]=$,{...F,contextPlaceholders:Ee}}),H=R=>p($=>({...$,contextPlaceholders:$.contextPlaceholders.filter((F,Ee)=>Ee!==R)})),L=async()=>{if(!f.name.trim()){x("名称为必填项");return}j(!0);try{await r(f)}catch(R){x(R instanceof Error?R.message:"保存失败")}finally{j(!1)}},T=R=>f.capabilities.enabledTools.length===0||f.capabilities.enabledTools.includes(R),A={fontSize:11,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.07em",marginBottom:10,marginTop:22,paddingBottom:5,borderBottom:"1px solid var(--border-subtle)"};return e.jsxs("div",{style:{padding:"24px 28px",background:"transparent",borderTop:"1px solid var(--border-subtle)"},children:[v&&e.jsx("div",{style:{marginBottom:12,padding:"8px 12px",borderRadius:7,background:"rgba(244,63,94,0.08)",border:"1px solid rgba(244,63,94,0.25)",color:"var(--danger)",fontSize:12},children:v}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[e.jsxs("div",{children:[e.jsx("label",{style:qr,children:"名称 *"}),e.jsx("input",{style:Vr,value:f.name,onChange:R=>p($=>({...$,name:R.target.value})),placeholder:"智能体名称"})]}),e.jsxs("div",{children:[e.jsx("label",{style:qr,children:"描述"}),e.jsx("input",{style:Vr,value:f.description,onChange:R=>p($=>({...$,description:R.target.value})),placeholder:"一句话描述"})]})]}),e.jsxs("div",{style:{marginTop:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:5},children:[e.jsx("label",{style:{...qr,marginBottom:0},children:"角色设定 / 工作指令"}),e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)",opacity:.6},children:["支持 ","{{变量名}}"," 占位符"]})]}),e.jsx("textarea",{value:f.systemPrompt,onChange:R=>p($=>({...$,systemPrompt:R.target.value})),placeholder:`你是一名专业的代码审查助手,请用中文回复所有问题。
|
|
480
|
+
}`,rows:5,style:{...Ur,width:"100%",boxSizing:"border-box",fontFamily:"var(--font-mono)",fontSize:12,resize:"vertical",marginBottom:8}}),R&&e.jsx("div",{style:{fontSize:12,color:"var(--danger)",marginBottom:8},children:R}),e.jsx("button",{onClick:Qe,disabled:!T.trim()||F,style:{padding:"8px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"var(--text-inverse)",fontSize:13,fontWeight:600,cursor:T.trim()&&!F?"pointer":"not-allowed",fontFamily:"var(--font-body)",opacity:T.trim()&&!F?1:.5},children:F?"导入中…":"导入"})]}),t.filter(W=>W.transport===r).length===0?e.jsxs("div",{style:{color:"var(--text-muted)",fontSize:14,padding:"40px 0",textAlign:"center"},children:["暂无",r==="stdio"?"本地 stdio":r==="sse"?"远程 SSE":"HTTP"," 服务器,点击上方添加。"]}):e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8},children:t.filter(W=>W.transport===r).map(W=>e.jsxs("div",{style:{padding:"14px 16px",background:"var(--bg-glass)",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",display:"flex",justifyContent:"space-between",alignItems:"center",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",transition:"border-color 0.2s"},children:[e.jsxs("div",{children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[e.jsx("div",{style:{fontSize:14,fontWeight:500,color:"var(--text-primary)"},children:W.name||W.id}),e.jsx("span",{style:{fontSize:10,padding:"1px 6px",borderRadius:4,background:Ye(W.transport),color:be(W.transport),fontWeight:600},children:ne(W.transport)})]}),e.jsxs("div",{style:{fontSize:12,color:"var(--text-muted)",marginTop:2,fontFamily:"var(--font-mono)"},children:[W.transport==="stdio"?`${W.command} ${(W.args??[]).join(" ")}`:W.url,W.transport!=="stdio"&&W.headers&&Object.keys(W.headers).length>0&&e.jsxs("span",{style:{marginLeft:6,fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-body)"},children:["· ",Object.keys(W.headers).length," 个请求头"]})]}),j.has(W.id)?e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:6,display:"flex",alignItems:"center",gap:6},children:[e.jsx("span",{style:{display:"inline-block",width:8,height:8,borderRadius:"50%",border:"2px solid var(--accent)",borderTopColor:"transparent",animation:"spin 0.8s linear infinite"}}),"探测工具中…"]}):x[W.id]?e.jsxs("div",{style:{marginTop:6,display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:11,color:"var(--danger)"},children:x[W.id]}),W.transport==="sse"||/401|403|unauthorized|forbidden|需要认证|访问被拒绝/i.test(x[W.id])?e.jsx("button",{onClick:()=>{z(""),C({server:W})},style:{fontSize:11,padding:"2px 8px",borderRadius:4,border:"1px solid rgba(251,191,36,0.4)",background:"rgba(251,191,36,0.1)",color:"#fbbf24",cursor:"pointer",fontFamily:"var(--font-body)"},children:"输入 Token"}):null,e.jsx("button",{onClick:()=>L(W),style:{fontSize:11,padding:"2px 8px",borderRadius:4,border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-muted)",cursor:"pointer",fontFamily:"var(--font-body)"},children:"重试"})]}):p[W.id]&&p[W.id].length>0?e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4,marginTop:6},children:p[W.id].map(te=>e.jsx("span",{title:te.description,style:{fontSize:11,padding:"2px 8px",borderRadius:10,background:"rgba(168,85,247,0.12)",color:"#c084fc",border:"1px solid rgba(168,85,247,0.2)",fontFamily:"var(--font-mono)",cursor:"default"},children:te.name},te.name))}):p[W.id]!==void 0?e.jsx("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:6},children:"无可用工具"}):null]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsxs("label",{style:{fontSize:12,color:"var(--text-muted)",cursor:"pointer",display:"flex",alignItems:"center",gap:4},children:[e.jsx("input",{type:"checkbox",checked:W.enabled!==!1,onChange:te=>at(W.id,te.target.checked),style:{cursor:"pointer"}}),"启用"]}),e.jsx("button",{onClick:()=>We(W.id),style:{padding:"5px 12px",borderRadius:"var(--radius-sm)",border:"1px solid rgba(248,113,113,0.2)",background:"transparent",color:"var(--danger)",fontSize:12,cursor:"pointer",fontFamily:"var(--font-body)",fontWeight:500,transition:"background 0.15s"},onMouseEnter:te=>{te.currentTarget.style.background="rgba(248,113,113,0.1)"},onMouseLeave:te=>{te.currentTarget.style.background="transparent"},children:"移除"})]})]},W.id))}),S&&e.jsx("div",{style:{position:"fixed",inset:0,zIndex:1e3,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(0,0,0,0.5)",backdropFilter:"blur(4px)"},onClick:W=>{W.target===W.currentTarget&&C(null)},children:e.jsxs("div",{style:{width:420,background:"var(--bg-surface)",borderRadius:"var(--radius-md)",border:"1px solid var(--border-default)",padding:28,boxShadow:"0 24px 48px rgba(0,0,0,0.4)"},children:[e.jsx("h3",{style:{margin:"0 0 6px",fontSize:16,fontWeight:600,color:"var(--text-primary)"},children:"需要认证"}),e.jsxs("p",{style:{margin:"0 0 20px",fontSize:13,color:"var(--text-muted)"},children:["服务器 ",e.jsx("strong",{style:{color:"var(--text-primary)"},children:S.server.name||S.server.id})," 返回了 401/403,请输入访问令牌(Bearer Token)。"]}),e.jsx("input",{autoFocus:!0,type:"password",value:k,onChange:W=>z(W.target.value),onKeyDown:W=>{W.key==="Enter"&&Ge(),W.key==="Escape"&&C(null)},placeholder:"sk-… 或 Bearer token",style:{...Ur,width:"100%",boxSizing:"border-box",marginBottom:16}}),e.jsxs("div",{style:{display:"flex",gap:10,justifyContent:"flex-end"},children:[e.jsx("button",{onClick:()=>C(null),style:{padding:"8px 18px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-muted)",fontSize:13,cursor:"pointer",fontFamily:"var(--font-body)"},children:"取消"}),e.jsx("button",{onClick:Ge,disabled:!k.trim()||M,style:{padding:"8px 18px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"var(--text-inverse)",fontSize:13,fontWeight:600,cursor:k.trim()&&!M?"pointer":"not-allowed",fontFamily:"var(--font-body)",opacity:k.trim()&&!M?1:.5},children:M?"保存中…":"保存并重试"})]})]})}),e.jsx("style",{children:"@keyframes spin { to { transform: rotate(360deg); } }"})]})}const Ur={padding:"10px 14px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:13,outline:"none",fontFamily:"var(--font-body)"},Bo={border:"1px solid var(--danger)",boxShadow:"0 0 0 2px rgba(248,113,113,0.15)"};function ux(){const[t,n]=a.useState([]),[r,s]=a.useState(""),[i,o]=a.useState(null),[l,d]=a.useState(!1),[u,f]=a.useState(""),[p,v]=a.useState(""),[x,w]=a.useState("user"),[j,E]=a.useState(""),[S,C]=a.useState(null),[k,z]=a.useState("success"),M=async()=>{if(window.agentApi){const A=await window.agentApi.listMemories();n(A)}};a.useEffect(()=>{M()},[]);const H=async()=>{if(!r.trim()){M();return}if(window.agentApi){const A=await window.agentApi.searchMemories(r);n(A.map(R=>R.entry))}},L=async()=>{if(!(!u.trim()||!window.agentApi))try{await window.agentApi.setMemory({name:u.trim(),description:p,type:x,content:j,created:(i==null?void 0:i.created)??new Date().toISOString(),updated:new Date().toISOString()}),d(!1),o(null),f(""),v(""),E(""),w("user"),C("保存成功"),z("success"),await M()}catch(A){C(A instanceof Error?A.message:"保存失败"),z("error")}},T=A=>{o(A),f(A.name),v(A.description),w(A.type),E(A.content),d(!0)};return e.jsxs("div",{style:{padding:"40px 48px",maxWidth:720,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:24},children:[e.jsxs("div",{children:[e.jsx("h2",{style:{fontFamily:"var(--font-display)",fontSize:28,color:"var(--text-primary)",fontWeight:400,letterSpacing:"-0.02em"},children:"记忆"}),e.jsx("p",{style:{color:"var(--text-muted)",fontSize:14,marginTop:4},children:"跨会话的持久化知识库。"})]}),e.jsx("button",{onClick:()=>{d(!0),o(null),f(""),v(""),E(""),w("user")},style:{padding:"10px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"var(--text-inverse)",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"var(--font-body)"},children:"+ 新建"})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginBottom:24},children:[e.jsx("input",{value:r,onChange:A=>s(A.target.value),onKeyDown:A=>A.key==="Enter"&&H(),placeholder:"搜索记忆...",style:{flex:1,padding:"10px 14px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:14,outline:"none",fontFamily:"var(--font-body)",backdropFilter:"blur(8px)",WebkitBackdropFilter:"blur(8px)"}}),e.jsx("button",{onClick:H,style:Rc,children:"搜索"})]}),S&&e.jsx("div",{style:{padding:"10px 12px",borderRadius:"var(--radius-sm)",border:k==="success"?"1px solid rgba(52,211,153,0.35)":"1px solid rgba(244,63,94,0.35)",background:k==="success"?"rgba(52,211,153,0.08)":"rgba(244,63,94,0.08)",color:k==="success"?"var(--success)":"var(--danger)",fontSize:13,marginBottom:16},children:S}),l&&e.jsxs("div",{style:{padding:20,marginBottom:24,background:"var(--bg-glass)",borderRadius:"var(--radius-md)",border:"1px solid var(--border-subtle)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},children:[e.jsx("input",{value:u,onChange:A=>f(A.target.value),placeholder:"名称",style:{...Mi,marginBottom:10},disabled:!!i}),e.jsx("input",{value:p,onChange:A=>v(A.target.value),placeholder:"描述",style:{...Mi,marginBottom:10}}),e.jsxs("select",{value:x,onChange:A=>w(A.target.value),style:{...Mi,marginBottom:10},children:[e.jsx("option",{value:"user",children:"用户"}),e.jsx("option",{value:"feedback",children:"反馈"}),e.jsx("option",{value:"project",children:"项目"}),e.jsx("option",{value:"reference",children:"参考"})]}),e.jsx("textarea",{value:j,onChange:A=>E(A.target.value),placeholder:"内容",rows:5,style:{...Mi,marginBottom:12,resize:"vertical"}}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:L,style:{padding:"9px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--success)",color:"#000",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"var(--font-body)"},children:"保存"}),e.jsx("button",{onClick:()=>d(!1),style:Rc,children:"取消"})]})]}),t.map(A=>e.jsxs("div",{style:{padding:"14px 16px",marginBottom:8,background:"var(--bg-glass)",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)",transition:"border-color 0.2s"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10},children:[e.jsx("span",{style:{color:"var(--text-primary)",fontWeight:600,fontSize:14},children:A.name}),e.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:10,background:"rgba(255,255,255,0.04)",color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",fontWeight:500},children:A.type})]}),e.jsxs("div",{style:{display:"flex",gap:6},children:[e.jsx("button",{onClick:()=>T(A),style:Ec,children:"编辑"}),e.jsx("button",{onClick:async()=>{if(window.agentApi)try{await window.agentApi.deleteMemory(A.name),C("删除成功"),z("success"),await M()}catch(R){C(R instanceof Error?R.message:"删除失败"),z("error")}},style:{...Ec,color:"var(--danger)"},children:"删除"})]})]}),A.description&&e.jsx("div",{style:{fontSize:12,color:"var(--text-secondary)",marginTop:4},children:A.description}),e.jsxs("div",{style:{fontSize:12,color:"var(--text-muted)",marginTop:4,lineHeight:1.5},children:[A.content.slice(0,180),A.content.length>180?"…":""]})]},A.name)),t.length===0&&!l&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:14,padding:"60px 0",textAlign:"center"},children:"暂无记忆,点击「新建」创建一条。"})]})}const Mi={width:"100%",padding:"11px 14px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:14,outline:"none",fontFamily:"var(--font-body)",boxSizing:"border-box"},Rc={padding:"10px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-secondary)",fontSize:13,fontWeight:500,cursor:"pointer",fontFamily:"var(--font-body)"},Ec={padding:"4px 10px",borderRadius:6,fontSize:11,border:"none",background:"rgba(255,255,255,0.05)",color:"var(--text-secondary)",cursor:"pointer",fontFamily:"var(--font-body)",fontWeight:500},px=()=>({name:"",description:"",triggers:[],prompt:"",filePath:"",enabled:!0});function fx(){const[t,n]=a.useState([]),[r,s]=a.useState(null),[i,o]=a.useState(!1),[l,d]=a.useState(null),[u,f]=a.useState("success"),[p,v]=a.useState(""),x=(T,A="success")=>{d(T),f(A),setTimeout(()=>d(null),3e3)},w=async()=>{if(!window.agentApi)return;const T=await window.agentApi.listSkills();n(T)};a.useEffect(()=>{w()},[]);const j=T=>{s({...T}),v((T.triggers??[]).join(", ")),o(!1)},E=()=>{s(px()),v(""),o(!0)},S=()=>{s(null),o(!1)},C=async()=>{if(!r||!window.agentApi)return;if(!r.name.trim()){x("名称不能为空","error");return}const T=p.split(",").map(A=>A.trim()).filter(Boolean);try{await window.agentApi.saveSkill({name:r.name.trim(),description:r.description,triggers:T,prompt:r.prompt,filePath:r.filePath??""}),x(i?"技能已创建":"技能已保存"),s(null),await w()}catch(A){x(A instanceof Error?A.message:"保存失败","error")}},k=async T=>{if(window.agentApi)try{await window.agentApi.deleteSkill(T),x("已删除"),(r==null?void 0:r.name)===T&&s(null),await w()}catch(A){x(A instanceof Error?A.message:"删除失败","error")}},z=async T=>{if(!window.agentApi)return;const A=!T.enabled;await window.agentApi.setSkillEnabled(T.name,A),await w()},M=async()=>{if(window.agentApi)try{const T=await window.agentApi.importSkill();if(!T)return;x(`已导入技能「${T.name}」,本次会话立即生效`),await w()}catch(T){x(T instanceof Error?T.message:"导入失败","error")}},H={width:"100%",padding:"8px 10px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:13,fontFamily:"var(--font-body)",outline:"none",boxSizing:"border-box"},L={fontSize:11,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4,display:"block"};return e.jsxs("div",{style:{padding:"40px 48px",maxWidth:720,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:24},children:[e.jsxs("div",{children:[e.jsx("h2",{style:{fontSize:20,fontWeight:600,color:"var(--text-primary)",margin:0},children:"技能管理"}),e.jsx("p",{style:{fontSize:13,color:"var(--text-muted)",margin:"4px 0 0"},children:"配置触发词和提示词,让 Agent 自动激活专属技能"})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:M,style:{padding:"8px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-secondary)",fontSize:13,fontWeight:600,cursor:"pointer"},children:"↓ 导入技能"}),e.jsx("button",{onClick:E,style:{padding:"8px 16px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer"},children:"+ 新建技能"})]})]}),l&&e.jsx("div",{style:{marginBottom:16,padding:"8px 12px",borderRadius:"var(--radius-sm)",border:u==="success"?"1px solid rgba(52,211,153,0.35)":"1px solid rgba(244,63,94,0.35)",background:u==="success"?"rgba(52,211,153,0.08)":"rgba(244,63,94,0.08)",color:u==="success"?"var(--success)":"var(--danger)",fontSize:13},children:l}),r&&e.jsxs("div",{style:{marginBottom:24,padding:"20px 24px",borderRadius:"var(--radius-md)",border:"1px solid var(--border-glow)",background:"var(--bg-glass)"},children:[e.jsx("h3",{style:{margin:"0 0 16px",fontSize:14,fontWeight:600,color:"var(--text-primary)"},children:i?"新建技能":`编辑:${r.name}`}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsxs("div",{children:[e.jsx("label",{style:L,children:"名称"}),e.jsx("input",{style:H,value:r.name,disabled:!i,onChange:T=>s({...r,name:T.target.value}),placeholder:"技能唯一标识,如 code-review"})]}),e.jsxs("div",{children:[e.jsx("label",{style:L,children:"描述"}),e.jsx("input",{style:H,value:r.description,onChange:T=>s({...r,description:T.target.value}),placeholder:"简短说明这个技能的用途"})]}),e.jsxs("div",{children:[e.jsx("label",{style:L,children:"触发词(逗号分隔)"}),e.jsx("input",{style:H,value:p,onChange:T=>v(T.target.value),placeholder:"代码审查, review, 审查代码"})]}),e.jsxs("div",{children:[e.jsx("label",{style:L,children:"提示词"}),e.jsx("textarea",{style:{...H,minHeight:120,resize:"vertical"},value:r.prompt,onChange:T=>s({...r,prompt:T.target.value}),placeholder:"当触发词匹配时,注入到系统提示的内容..."})]})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:16},children:[e.jsx("button",{onClick:C,style:{padding:"8px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer"},children:"保存"}),e.jsx("button",{onClick:S,style:{padding:"8px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-secondary)",fontSize:13,cursor:"pointer"},children:"取消"})]})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:8},children:[t.length===0&&!r&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:13,padding:"20px 0",textAlign:"center"},children:"暂无技能,点击「新建技能」创建第一个"}),t.map(T=>{var A;return e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12,padding:"14px 16px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-subtle)",background:"var(--bg-glass)",opacity:T.enabled===!1?.5:1},children:[e.jsx("button",{onClick:()=>z(T),title:T.enabled===!1?"已禁用,点击启用":"点击禁用",style:{flexShrink:0,marginTop:2,width:32,height:18,borderRadius:9,border:"none",background:T.enabled===!1?"var(--border-default)":"var(--accent)",cursor:"pointer",position:"relative",transition:"background 0.2s"},children:e.jsx("span",{style:{position:"absolute",top:2,left:T.enabled===!1?2:14,width:14,height:14,borderRadius:"50%",background:"#fff",transition:"left 0.2s"}})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,marginBottom:2},children:[e.jsx("span",{style:{fontSize:13,fontWeight:600,color:"var(--text-primary)"},children:T.name}),((A=T.triggers)==null?void 0:A.length)>0&&e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)"},children:["触发词:",T.triggers.slice(0,3).join(" · "),T.triggers.length>3?" ...":""]})]}),T.description&&e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",marginBottom:4},children:T.description}),T.prompt&&e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono)",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis",maxWidth:"100%",opacity:.7},children:[T.prompt.slice(0,80),T.prompt.length>80?"...":""]})]}),e.jsxs("div",{style:{display:"flex",gap:6,flexShrink:0},children:[e.jsx("button",{onClick:()=>j(T),style:{padding:"5px 12px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-secondary)",fontSize:12,cursor:"pointer"},children:"编辑"}),e.jsx("button",{onClick:()=>k(T.name),style:{padding:"5px 12px",borderRadius:"var(--radius-sm)",border:"1px solid rgba(244,63,94,0.3)",background:"transparent",color:"var(--danger)",fontSize:12,cursor:"pointer"},children:"删除"})]})]},T.name)})]})]})}const Ai=[{name:"read_file",label:"读取文件"},{name:"write_file",label:"写入文件"},{name:"bash",label:"执行命令"},{name:"web_fetch",label:"网页抓取"},{name:"web_search",label:"网络搜索"},{name:"grep",label:"文件搜索"}];function su(){return{profileId:"",enabledTools:[],enabledSkills:[],enabledMCPServers:[]}}function hx(){return{name:"",description:"",systemPrompt:"",contextPlaceholders:[],capabilities:su(),maxIterations:0,isDefault:!1}}const sa={padding:"5px 12px",borderRadius:7,border:"1px solid var(--border-default)",background:"var(--bg-deep)",color:"var(--text-secondary)",fontSize:12,fontWeight:500,cursor:"pointer"},ai={padding:"3px 9px",borderRadius:6,border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-muted)",fontSize:11,cursor:"pointer"},Vr={width:"100%",padding:"7px 10px",borderRadius:7,border:"1px solid var(--border-default)",background:"var(--bg-surface)",color:"var(--text-primary)",fontSize:13,outline:"none",boxSizing:"border-box"},qr={fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:5,display:"block"};function gx({ph:t,onChange:n,onDelete:r}){return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1.5fr 1fr auto",gap:6,alignItems:"center"},children:[e.jsx("input",{style:Vr,placeholder:"变量名 (e.g. project)",value:t.key,onChange:s=>n({...t,key:s.target.value})}),e.jsx("input",{style:Vr,placeholder:"说明",value:t.description,onChange:s=>n({...t,description:s.target.value})}),e.jsx("input",{style:Vr,placeholder:"默认值",value:t.defaultValue,onChange:s=>n({...t,defaultValue:s.target.value})}),e.jsx("button",{onClick:r,style:{...ai,color:"var(--danger)",borderColor:"rgba(244,63,94,0.25)",flexShrink:0},children:"✕"})]})}function Mc({initial:t,activeAgentId:n,onSave:r,onCancel:s}){const{profiles:i}=qi(),[o,l]=a.useState([]),[d,u]=a.useState([]),[f,p]=a.useState({...hx(),...t,capabilities:{...su(),...t.capabilities??{}}}),[v,x]=a.useState(null),[w,j]=a.useState(!1);a.useEffect(()=>{var R,$;window.agentApi&&(window.agentApi.listSkills().then(F=>{l(F.filter(Ee=>Ee.name))}),($=(R=window.agentApi).listMCPServers)==null||$.call(R).then(F=>{u(F??[])}).catch(()=>{}))},[]);const E=R=>p($=>({...$,capabilities:{...$.capabilities,...R}})),S=R=>{const $=f.capabilities.enabledTools;if($.length===0){const F=Ai.map(Ee=>Ee.name).filter(Ee=>Ee!==R);E({enabledTools:F})}else if($.includes(R)){const F=$.filter(Ee=>Ee!==R);E({enabledTools:F})}else{const F=[...$,R];F.length===Ai.length?E({enabledTools:[]}):E({enabledTools:F})}},C=R=>{const $=f.capabilities.enabledSkills;E({enabledSkills:$.includes(R)?$.filter(F=>F!==R):[...$,R]})},k=R=>{const $=f.capabilities.enabledMCPServers;E({enabledMCPServers:$.includes(R)?$.filter(F=>F!==R):[...$,R]})},z=()=>p(R=>({...R,contextPlaceholders:[...R.contextPlaceholders,{key:"",description:"",defaultValue:""}]})),M=(R,$)=>p(F=>{const Ee=[...F.contextPlaceholders];return Ee[R]=$,{...F,contextPlaceholders:Ee}}),H=R=>p($=>({...$,contextPlaceholders:$.contextPlaceholders.filter((F,Ee)=>Ee!==R)})),L=async()=>{if(!f.name.trim()){x("名称为必填项");return}j(!0);try{await r(f)}catch(R){x(R instanceof Error?R.message:"保存失败")}finally{j(!1)}},T=R=>f.capabilities.enabledTools.length===0||f.capabilities.enabledTools.includes(R),A={fontSize:11,fontWeight:700,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.07em",marginBottom:10,marginTop:22,paddingBottom:5,borderBottom:"1px solid var(--border-subtle)"};return e.jsxs("div",{style:{padding:"24px 28px",background:"transparent",borderTop:"1px solid var(--border-subtle)"},children:[v&&e.jsx("div",{style:{marginBottom:12,padding:"8px 12px",borderRadius:7,background:"rgba(244,63,94,0.08)",border:"1px solid rgba(244,63,94,0.25)",color:"var(--danger)",fontSize:12},children:v}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[e.jsxs("div",{children:[e.jsx("label",{style:qr,children:"名称 *"}),e.jsx("input",{style:Vr,value:f.name,onChange:R=>p($=>({...$,name:R.target.value})),placeholder:"智能体名称"})]}),e.jsxs("div",{children:[e.jsx("label",{style:qr,children:"描述"}),e.jsx("input",{style:Vr,value:f.description,onChange:R=>p($=>({...$,description:R.target.value})),placeholder:"一句话描述"})]})]}),e.jsxs("div",{style:{marginTop:14},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:5},children:[e.jsx("label",{style:{...qr,marginBottom:0},children:"角色设定 / 工作指令"}),e.jsxs("span",{style:{fontSize:11,color:"var(--text-muted)",opacity:.6},children:["支持 ","{{变量名}}"," 占位符"]})]}),e.jsx("textarea",{value:f.systemPrompt,onChange:R=>p($=>({...$,systemPrompt:R.target.value})),placeholder:`你是一名专业的代码审查助手,请用中文回复所有问题。
|
|
481
481
|
|
|
482
482
|
当前项目:{{project_name}}`,rows:6,style:{...Vr,resize:"vertical",fontFamily:"var(--font-mono)",fontSize:12,lineHeight:1.6}})]}),e.jsx("p",{style:A,children:"上下文占位符"}),f.contextPlaceholders.length>0&&e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,marginBottom:8},children:[e.jsx("div",{style:{display:"grid",gridTemplateColumns:"1fr 1.5fr 1fr auto",gap:6},children:["变量名","说明","默认值",""].map(R=>e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",letterSpacing:"0.05em"},children:R},R))}),f.contextPlaceholders.map((R,$)=>e.jsx(gx,{ph:R,onChange:F=>M($,F),onDelete:()=>H($)},$))]}),e.jsx("button",{onClick:z,style:{...ai,color:"var(--accent)",borderColor:"rgba(79,110,247,0.25)"},children:"+ 添加占位符"}),e.jsx("p",{style:A,children:"能力配置"}),e.jsxs("div",{style:{marginBottom:14},children:[e.jsx("label",{style:qr,children:"模型"}),e.jsxs("select",{value:f.capabilities.profileId,onChange:R=>E({profileId:R.target.value}),style:{...Vr,cursor:"pointer"},children:[e.jsx("option",{value:"",children:"使用全局活跃模型"}),i.map(R=>e.jsxs("option",{value:R.id,children:[R.name||R.modelId," (",R.provider,")"]},R.id))]})]}),e.jsxs("div",{style:{marginBottom:14},children:[e.jsxs("label",{style:qr,children:["内置工具 ",f.capabilities.enabledTools.length===0?"(全部启用)":`(${f.capabilities.enabledTools.length}/${Ai.length})`]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:Ai.map(R=>{const $=T(R.name);return e.jsx("button",{onClick:()=>S(R.name),style:{padding:"4px 10px",borderRadius:20,border:$?"1px solid var(--accent)":"1px solid var(--border-subtle)",background:$?"var(--accent-dim)":"transparent",color:$?"var(--accent)":"var(--text-muted)",fontSize:12,cursor:"pointer",transition:"all 0.12s"},children:R.label},R.name)})}),e.jsx("p",{style:{fontSize:11,color:"var(--text-muted)",marginTop:5,opacity:.7},children:'点击切换;全选时恢复为"全部启用"'})]}),o.length>0&&e.jsxs("div",{style:{marginBottom:14},children:[e.jsxs("label",{style:qr,children:["技能 ",f.capabilities.enabledSkills.length===0?"(全部)":`(${f.capabilities.enabledSkills.length}/${o.length})`]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:o.map(R=>{const $=f.capabilities.enabledSkills.length===0||f.capabilities.enabledSkills.includes(R.name);return e.jsx("button",{onClick:()=>C(R.name),title:R.description,style:{padding:"4px 10px",borderRadius:20,border:$?"1px solid var(--accent)":"1px solid var(--border-subtle)",background:$?"var(--accent-dim)":"transparent",color:$?"var(--accent)":"var(--text-muted)",fontSize:12,cursor:"pointer",transition:"all 0.12s"},children:R.name},R.name)})})]}),d.length>0&&e.jsxs("div",{style:{marginBottom:14},children:[e.jsxs("label",{style:qr,children:["MCP 服务器 ",f.capabilities.enabledMCPServers.length===0?"(全部)":`(${f.capabilities.enabledMCPServers.length}/${d.length})`]}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:d.map(R=>{const $=f.capabilities.enabledMCPServers.length===0||f.capabilities.enabledMCPServers.includes(R.id);return e.jsx("button",{onClick:()=>k(R.id),style:{padding:"4px 10px",borderRadius:20,border:$?"1px solid var(--accent)":"1px solid var(--border-subtle)",background:$?"var(--accent-dim)":"transparent",color:$?"var(--accent)":"var(--text-muted)",fontSize:12,cursor:"pointer",transition:"all 0.12s"},children:R.name},R.id)})})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12,marginBottom:16},children:[e.jsxs("div",{children:[e.jsx("label",{style:qr,children:"最大迭代次数(0 = 全局)"}),e.jsx("input",{type:"number",style:Vr,value:f.maxIterations,min:0,max:100,onChange:R=>p($=>({...$,maxIterations:Number(R.target.value)}))})]}),e.jsx("div",{style:{display:"flex",alignItems:"flex-end",paddingBottom:2},children:e.jsxs("label",{style:{display:"flex",alignItems:"center",gap:8,cursor:"pointer",fontSize:13,color:"var(--text-secondary)"},children:[e.jsx("input",{type:"checkbox",checked:f.isDefault,onChange:R=>p($=>({...$,isDefault:R.target.checked})),style:{width:14,height:14,accentColor:"var(--accent)",cursor:"pointer"}}),"新会话默认使用此智能体"]})})]}),e.jsxs("div",{style:{display:"flex",gap:8},children:[e.jsx("button",{onClick:L,disabled:w,style:{...sa,background:"var(--accent)",color:"#fff",border:"none",fontWeight:600,opacity:w?.6:1},children:w?"保存中…":"保存"}),e.jsx("button",{onClick:s,style:sa,children:"取消"})]})]})}function mx(){const[t,n]=a.useState([]),[r,s]=a.useState([]),[i,o]=a.useState(null),[l,d]=a.useState(!1),[u,f]=a.useState(null),[p,v]=a.useState("success"),x=(k,z="success")=>{f(k),v(z),setTimeout(()=>f(null),2e3)},w=async()=>{if(!window.agentApi)return;const k=await window.agentApi.listAgentDefs();n(k);const z=await window.agentApi.getSettings();s(z.activeAgentIds??[])};a.useEffect(()=>{w()},[]);const j=async k=>{await window.agentApi.createAgentDef(k),d(!1),x("智能体已创建"),await w()},E=async(k,z)=>{await window.agentApi.updateAgentDef(k,z),o(null),x("保存成功"),await w()},S=async k=>{await window.agentApi.deleteAgentDef(k),i===k&&o(null),x("已删除"),await w()},C=async k=>{const M=(await window.agentApi.setActiveAgentDef(k)).activeAgentIds??[];s(M),x(M.includes(k)?"已激活":"已取消激活")};return e.jsxs("div",{style:{padding:"40px 48px",maxWidth:720,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsx("h2",{style:{fontFamily:"var(--font-display)",fontSize:28,color:"var(--text-primary)",fontWeight:400,marginBottom:8,letterSpacing:"-0.02em"},children:"智能体"}),e.jsx("p",{style:{color:"var(--text-muted)",fontSize:14,marginBottom:28},children:"配置具有自定义角色、工具和模型的智能体,在消息框中按需切换。"}),u&&e.jsx("div",{style:{marginBottom:16,padding:"8px 14px",borderRadius:8,border:p==="success"?"1px solid rgba(52,211,153,0.35)":"1px solid rgba(244,63,94,0.35)",background:p==="success"?"rgba(52,211,153,0.08)":"rgba(244,63,94,0.08)",color:p==="success"?"var(--success)":"var(--danger)",fontSize:13},children:u}),e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",marginBottom:14},children:e.jsx("button",{onClick:()=>{d(!0),o(null)},style:{...sa,background:"var(--accent)",color:"#fff",border:"none",fontWeight:600},children:"+ 新建智能体"})}),l&&e.jsxs("div",{style:{borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",overflow:"hidden",marginBottom:16},children:[e.jsx("div",{style:{padding:"10px 16px",background:"var(--bg-surface)",display:"flex",alignItems:"center",gap:8},children:e.jsx("span",{style:{fontSize:13,fontWeight:600,color:"var(--text-secondary)"},children:"新建智能体"})}),e.jsx(Mc,{initial:{},activeAgentId:r[0]??"",onSave:j,onCancel:()=>d(!1)})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10},children:[t.length===0&&!l&&e.jsx("div",{style:{padding:"28px 20px",borderRadius:"var(--radius-sm)",border:"1px dashed var(--border-subtle)",textAlign:"center",color:"var(--text-muted)",fontSize:13},children:"暂无智能体配置,点击「新建智能体」开始创建"}),t.map(k=>{const z=r.includes(k.id),M=k.id===i;return e.jsxs("div",{style:{borderRadius:"var(--radius-sm)",border:`1px solid ${z?"var(--accent)":"var(--border-default)"}`,background:z?"var(--accent-dim)":"var(--bg-surface)",overflow:"hidden",transition:"border-color 0.2s, background 0.2s"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"12px 16px"},children:[e.jsx("div",{style:{width:34,height:34,borderRadius:8,flexShrink:0,background:z?"var(--accent)":"var(--bg-deep)",display:"flex",alignItems:"center",justifyContent:"center"},children:e.jsxs("svg",{width:"15",height:"15",viewBox:"0 0 24 24",fill:"none",stroke:z?"#fff":"var(--text-muted)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"8",r:"4"}),e.jsx("path",{d:"M20 21a8 8 0 1 0-16 0"})]})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("span",{style:{fontSize:14,fontWeight:600,color:"var(--text-primary)"},children:k.name}),z&&e.jsx("span",{style:{fontSize:10,fontWeight:700,color:"var(--accent)",background:"rgba(79,110,247,0.12)",padding:"1px 6px",borderRadius:4,letterSpacing:"0.05em"},children:"激活"}),k.isDefault&&e.jsx("span",{style:{fontSize:10,color:"var(--text-muted)",background:"var(--bg-deep)",padding:"1px 6px",borderRadius:4},children:"默认"})]}),k.description&&e.jsx("div",{style:{fontSize:12,color:"var(--text-muted)",marginTop:2,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:k.description}),e.jsxs("div",{style:{display:"flex",gap:5,marginTop:5,flexWrap:"wrap"},children:[k.capabilities.profileId&&e.jsx("span",{style:{fontSize:10,padding:"1px 7px",borderRadius:10,background:"rgba(79,110,247,0.08)",color:"var(--accent)",border:"1px solid rgba(79,110,247,0.15)"},children:"自定义模型"}),k.capabilities.enabledTools.length>0&&e.jsxs("span",{style:{fontSize:10,padding:"1px 7px",borderRadius:10,background:"var(--bg-deep)",color:"var(--text-muted)",border:"1px solid var(--border-subtle)"},children:[k.capabilities.enabledTools.length," 工具"]}),k.capabilities.enabledSkills.length>0&&e.jsxs("span",{style:{fontSize:10,padding:"1px 7px",borderRadius:10,background:"var(--bg-deep)",color:"var(--text-muted)",border:"1px solid var(--border-subtle)"},children:[k.capabilities.enabledSkills.length," 技能"]}),k.contextPlaceholders.length>0&&e.jsxs("span",{style:{fontSize:10,padding:"1px 7px",borderRadius:10,background:"var(--bg-deep)",color:"var(--text-muted)",border:"1px solid var(--border-subtle)"},children:[k.contextPlaceholders.length," 变量"]})]})]}),e.jsxs("div",{style:{display:"flex",gap:6,flexShrink:0},children:[e.jsx("button",{onClick:()=>C(k.id),style:{...ai,color:z?"var(--accent)":"var(--text-muted)",borderColor:z?"var(--accent)":"var(--border-default)",background:z?"var(--accent-dim)":"transparent"},children:z?"取消激活":"激活"}),e.jsx("button",{onClick:()=>o(M?null:k.id),style:ai,children:M?"收起":"编辑"}),e.jsx("button",{onClick:()=>S(k.id),style:{...ai,color:"var(--danger)",borderColor:"rgba(244,63,94,0.25)"},children:"删除"})]})]}),M&&e.jsx(Mc,{initial:k,activeAgentId:r[0]??"",onSave:H=>E(k.id,H),onCancel:()=>o(null)})]},k.id)})]})]})}const xx=[{label:"TypeScript / JavaScript",language:"typescript",fileTypes:".ts,.tsx,.js,.jsx",command:"typescript-language-server",args:"--stdio"},{label:"Python (pylsp)",language:"python",fileTypes:".py",command:"pylsp",args:""},{label:"Python (pyright)",language:"python",fileTypes:".py",command:"pyright-langserver",args:"--stdio"},{label:"Rust (rust-analyzer)",language:"rust",fileTypes:".rs",command:"rust-analyzer",args:""},{label:"Go (gopls)",language:"go",fileTypes:".go",command:"gopls",args:""},{label:"C/C++ (clangd)",language:"cpp",fileTypes:".c,.cpp,.cc,.h,.hpp",command:"clangd",args:""},{label:"Java (jdtls via brew)",language:"java",fileTypes:".java",command:"jdtls",args:"--data /tmp/jdtls-workspace"}],Oo={id:"",name:"",language:"",fileTypes:"",command:"",args:"",envRaw:""};function bx(){const[t,n]=a.useState([]),[r,s]=a.useState(Oo),[i,o]=a.useState(!1),[l,d]=a.useState(null),[u,f]=a.useState(null),p=async()=>{var k;if((k=window.agentApi)!=null&&k.lspList)try{const z=await window.agentApi.lspList();n(z)}catch(z){console.error("[LSP] load error",z)}};a.useEffect(()=>{p()},[]);const v=k=>{s(z=>({...z,name:k.label,language:k.language,fileTypes:k.fileTypes,command:k.command,args:k.args}))},x=k=>{d(k.id),s({id:k.id,name:k.name,language:k.language,fileTypes:k.fileTypes.join(","),command:k.command,args:k.args.join(" "),envRaw:k.env?Object.entries(k.env).map(([z,M])=>`${z}=${M}`).join(`
|
|
483
483
|
`):""}),f(null)},w=()=>{d(null),s(Oo)},j=async()=>{var L;if(!((L=window.agentApi)!=null&&L.lspSave))return;const k=r.name.trim(),z=r.command.trim();if(!k||!z)return;let M;if(r.envRaw.trim()){M={};for(const T of r.envRaw.split(`
|
|
484
484
|
`)){const A=T.indexOf("=");A>0&&(M[T.slice(0,A).trim()]=T.slice(A+1).trim())}}const H={id:l??crypto.randomUUID(),name:k,language:r.language.trim(),fileTypes:r.fileTypes.split(",").map(T=>T.trim()).filter(Boolean),command:z,args:r.args.trim()?r.args.trim().split(/\s+/):[],env:M,enabled:!0};o(!0);try{await window.agentApi.lspSave(H),await p(),w()}finally{o(!1)}},E=async k=>{var z;(z=window.agentApi)!=null&&z.lspDelete&&confirm("删除此 LSP 服务器配置?")&&(await window.agentApi.lspDelete(k),await p())},S=async k=>{var z;(z=window.agentApi)!=null&&z.lspSetEnabled&&(await window.agentApi.lspSetEnabled(k.id,!k.enabled),await p())},C=l!==null;return C&&l===null||!l&&r.name,e.jsxs("div",{style:{padding:"40px 48px",maxWidth:720,animation:"fadeInUp 0.4s var(--ease-out)"},children:[e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"flex-start",marginBottom:24},children:[e.jsxs("div",{children:[e.jsx("h2",{style:{fontSize:20,fontWeight:600,color:"var(--text-primary)",margin:0},children:"LSP 服务器"}),e.jsxs("p",{style:{fontSize:13,color:"var(--text-muted)",margin:"4px 0 0"},children:["配置 Language Server Protocol 服务器,让 Agent 可通过"," ",e.jsx("code",{style:{fontFamily:"var(--font-mono, monospace)",fontSize:12,color:"var(--text-secondary)",background:"var(--bg-deep)",padding:"1px 5px",borderRadius:4},children:"lsp_diagnostics"}),"、",e.jsx("code",{style:{fontFamily:"var(--font-mono, monospace)",fontSize:12,color:"var(--text-secondary)",background:"var(--bg-deep)",padding:"1px 5px",borderRadius:4},children:"lsp_hover"}),"、",e.jsx("code",{style:{fontFamily:"var(--font-mono, monospace)",fontSize:12,color:"var(--text-secondary)",background:"var(--bg-deep)",padding:"1px 5px",borderRadius:4},children:"lsp_definition"})," ","等工具进行代码分析。"]})]}),!C&&e.jsx("button",{onClick:()=>{d(""),s(Oo)},style:{padding:"8px 16px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer",flexShrink:0},children:"+ 添加服务器"})]}),t.length===0&&!C&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:14,padding:"40px 0",textAlign:"center"},children:"尚未配置任何 LSP 服务器"}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:8,marginBottom:C?24:0},children:t.map(k=>e.jsxs("div",{style:{background:"var(--bg-glass)",border:"1px solid var(--border-subtle)",borderRadius:"var(--radius-md)",overflow:"hidden"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:12,padding:"12px 16px",cursor:"pointer"},onClick:()=>f(u===k.id?null:k.id),children:[e.jsx("div",{onClick:z=>{z.stopPropagation(),S(k)},style:{width:32,height:18,borderRadius:9,background:k.enabled?"var(--success, #34d399)":"var(--border-default)",position:"relative",cursor:"pointer",flexShrink:0,transition:"background 0.2s"},children:e.jsx("div",{style:{position:"absolute",top:2,left:k.enabled?16:2,width:14,height:14,borderRadius:"50%",background:"#fff",transition:"left 0.2s"}})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontWeight:500,fontSize:13,color:"var(--text-primary)"},children:k.name}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",marginTop:2},children:[k.language,k.fileTypes.length>0?` · ${k.fileTypes.join(", ")}`:""]})]}),e.jsxs("div",{style:{fontSize:11,color:"var(--text-muted)",fontFamily:"var(--font-mono, monospace)",flexShrink:0},children:[k.command,k.args.length?" "+k.args.join(" "):""]}),e.jsx("button",{onClick:z=>{z.stopPropagation(),x(k)},style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:13,padding:"2px 8px",fontFamily:"var(--font-body)"},children:"编辑"}),e.jsx("button",{onClick:z=>{z.stopPropagation(),E(k.id)},style:{background:"none",border:"none",cursor:"pointer",color:"var(--danger, #f43f5e)",fontSize:13,padding:"2px 8px",fontFamily:"var(--font-body)"},children:"删除"}),e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-muted)",strokeWidth:"2.5",strokeLinecap:"round",style:{flexShrink:0,transition:"transform 0.2s",transform:u===k.id?"rotate(180deg)":"none"},children:e.jsx("path",{d:"M6 9l6 6 6-6"})})]}),u===k.id&&e.jsxs("div",{style:{padding:"12px 16px",fontSize:12,color:"var(--text-muted)",borderTop:"1px solid var(--border-subtle)",display:"flex",flexDirection:"column",gap:6},children:[e.jsxs("div",{children:[e.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:"命令:"}),e.jsxs("code",{style:{fontFamily:"var(--font-mono, monospace)",background:"var(--bg-deep)",padding:"1px 5px",borderRadius:4},children:[k.command," ",k.args.join(" ")]})]}),k.fileTypes.length>0&&e.jsxs("div",{children:[e.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:"文件类型:"}),k.fileTypes.join(", ")]}),k.env&&Object.keys(k.env).length>0&&e.jsxs("div",{children:[e.jsx("span",{style:{color:"var(--text-secondary)",fontWeight:500},children:"环境变量:"}),Object.entries(k.env).map(([z,M])=>`${z}=${M}`).join(", ")]})]})]},k.id))}),C&&e.jsxs("div",{style:{padding:"20px 24px",borderRadius:"var(--radius-md)",border:"1px solid var(--border-glow)",background:"var(--bg-glass)"},children:[e.jsx("h3",{style:{margin:"0 0 16px",fontSize:14,fontWeight:600,color:"var(--text-primary)"},children:l?"编辑 LSP 服务器":"添加 LSP 服务器"}),e.jsxs("div",{style:{marginBottom:16},children:[e.jsx("label",{style:ds,children:"快速预设"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:xx.map(k=>e.jsx("button",{onClick:()=>v(k),style:{background:"var(--bg-deep)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-sm)",padding:"4px 10px",fontSize:11,cursor:"pointer",color:"var(--text-secondary)",fontFamily:"var(--font-body)"},children:k.label},k.label))})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:14},children:[e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[e.jsxs("div",{children:[e.jsxs("label",{style:ds,children:["名称 ",e.jsx("span",{style:{color:"var(--danger, #f43f5e)",textTransform:"none"},children:"*"})]}),e.jsx("input",{value:r.name,onChange:k=>s(z=>({...z,name:k.target.value})),placeholder:"TypeScript Language Server",style:Es})]}),e.jsxs("div",{children:[e.jsx("label",{style:ds,children:"语言"}),e.jsx("input",{value:r.language,onChange:k=>s(z=>({...z,language:k.target.value})),placeholder:"typescript",style:Es})]})]}),e.jsxs("div",{children:[e.jsxs("label",{style:ds,children:["文件类型",e.jsx("span",{style:{textTransform:"none",letterSpacing:0,fontWeight:400,marginLeft:6,color:"var(--text-muted)"},children:"逗号分隔,如 .ts,.tsx"})]}),e.jsx("input",{value:r.fileTypes,onChange:k=>s(z=>({...z,fileTypes:k.target.value})),placeholder:".ts,.tsx,.js,.jsx",style:Es})]}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:12},children:[e.jsxs("div",{children:[e.jsxs("label",{style:ds,children:["命令 ",e.jsx("span",{style:{color:"var(--danger, #f43f5e)",textTransform:"none"},children:"*"})]}),e.jsx("input",{value:r.command,onChange:k=>s(z=>({...z,command:k.target.value})),placeholder:"typescript-language-server",style:{...Es,fontFamily:"var(--font-mono, monospace)"}})]}),e.jsxs("div",{children:[e.jsxs("label",{style:ds,children:["参数",e.jsx("span",{style:{textTransform:"none",letterSpacing:0,fontWeight:400,marginLeft:6,color:"var(--text-muted)"},children:"空格分隔"})]}),e.jsx("input",{value:r.args,onChange:k=>s(z=>({...z,args:k.target.value})),placeholder:"--stdio",style:{...Es,fontFamily:"var(--font-mono, monospace)"}})]})]}),e.jsxs("div",{children:[e.jsxs("label",{style:ds,children:["环境变量",e.jsx("span",{style:{textTransform:"none",letterSpacing:0,fontWeight:400,marginLeft:6,color:"var(--text-muted)"},children:"每行 KEY=VALUE"})]}),e.jsx("textarea",{value:r.envRaw,onChange:k=>s(z=>({...z,envRaw:k.target.value})),placeholder:`NODE_ENV=production
|
|
485
485
|
TSPROTOCOL_LOG=verbose`,rows:3,style:{...Es,fontFamily:"var(--font-mono, monospace)",resize:"vertical"}})]}),r.language==="java"&&e.jsxs("div",{style:{background:"rgba(234,179,8,0.08)",border:"1px solid rgba(234,179,8,0.3)",borderRadius:"var(--radius-sm)",padding:"10px 14px",fontSize:12,color:"var(--text-secondary)",lineHeight:1.65},children:[e.jsx("strong",{style:{color:"rgba(202,138,4,1)"},children:"Java 提示:"})," ","使用 ",e.jsx("code",{style:{fontFamily:"var(--font-mono, monospace)",background:"var(--bg-deep)",padding:"1px 5px",borderRadius:3},children:"jdtls"})," 预设需先通过"," ",e.jsx("code",{style:{fontFamily:"var(--font-mono, monospace)",background:"var(--bg-deep)",padding:"1px 5px",borderRadius:3},children:"brew install jdtls"})," ","安装包装脚本。若手动安装,请将命令改为"," ",e.jsx("code",{style:{fontFamily:"var(--font-mono, monospace)",background:"var(--bg-deep)",padding:"1px 5px",borderRadius:3},children:"java"}),", 并在参数中填入完整的 JVM 参数和"," ",e.jsx("code",{style:{fontFamily:"var(--font-mono, monospace)",background:"var(--bg-deep)",padding:"1px 5px",borderRadius:3},children:"-jar .../launcher.jar -data /path/to/workspace"}),"。"]})]}),e.jsxs("div",{style:{display:"flex",gap:8,marginTop:20},children:[e.jsx("button",{onClick:()=>void j(),disabled:i||!r.name.trim()||!r.command.trim(),style:{padding:"8px 20px",borderRadius:"var(--radius-sm)",border:"none",background:"var(--accent)",color:"#fff",fontSize:13,fontWeight:600,cursor:"pointer",opacity:i||!r.name.trim()||!r.command.trim()?.45:1,fontFamily:"var(--font-body)"},children:i?"保存中…":"保存"}),e.jsx("button",{onClick:w,style:{padding:"8px 20px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"transparent",color:"var(--text-secondary)",fontSize:13,fontWeight:600,cursor:"pointer",fontFamily:"var(--font-body)"},children:"取消"})]})]})]})}const Es={width:"100%",padding:"8px 10px",borderRadius:"var(--radius-sm)",border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:13,fontFamily:"var(--font-body)",outline:"none",boxSizing:"border-box"},ds={fontSize:11,color:"var(--text-muted)",fontWeight:600,textTransform:"uppercase",letterSpacing:"0.06em",marginBottom:4,display:"block"};function yx({trigger:t,heardText:n}){const[r,s]=a.useState(!1);return a.useEffect(()=>{if(t<=0)return;s(!0);const i=setTimeout(()=>s(!1),2400);return()=>clearTimeout(i)},[t]),r?On.createPortal(e.jsxs("div",{style:{position:"fixed",inset:0,zIndex:3e4,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:22,background:"radial-gradient(circle at 50% 50%, var(--accent-glow), transparent 60%)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",animation:"fadeIn 0.3s var(--ease-out)",pointerEvents:"none",WebkitAppRegion:"no-drag"},children:[e.jsxs("div",{style:{position:"relative",width:120,height:120},children:[[0,.45,.9].map(i=>e.jsx("div",{style:{position:"absolute",inset:0,borderRadius:"50%",border:"2px solid var(--accent)",animation:`wakeRing 1.6s ${i}s var(--ease-out) infinite`}},i)),e.jsx("div",{style:{position:"absolute",inset:30,borderRadius:"50%",background:"var(--accent)",display:"flex",alignItems:"center",justifyContent:"center",animation:"wakeCore 1.6s var(--ease-out) infinite"},children:e.jsxs("svg",{width:"26",height:"26",viewBox:"0 0 24 24",fill:"none",stroke:"var(--text-inverse)",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),e.jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),e.jsx("line",{x1:"12",y1:"19",x2:"12",y2:"22"})]})})]}),e.jsx("div",{style:{fontSize:16,fontWeight:600,color:"var(--text-primary)",letterSpacing:"0.12em",animation:"wakeText 0.9s var(--ease-out) both",fontFamily:"var(--font-display)"},children:"已唤醒 · 随时待命"}),n&&e.jsxs("div",{style:{fontSize:12,color:"var(--text-muted)",maxWidth:320,textAlign:"center",animation:"fadeIn 0.6s var(--ease-out) 0.3s both"},children:["“",n.slice(0,40),"”"]})]},t),document.body):null}const vx=[{agentType:"customer-agent",label:"Customer Agent"},{agentType:"codex",label:"Codex"},{agentType:"claude-code",label:"Claude Code"},{agentType:"opencode",label:"OpenCode"}];function wx({value:t,health:n,onChange:r}){return e.jsx("div",{className:"agent-workspace-switcher",role:"tablist","aria-label":"切换 Agent",children:vx.map(s=>{const i=n.find(l=>l.agentType===s.agentType),o=(i==null?void 0:i.available)===!1;return e.jsxs("button",{type:"button",role:"tab","aria-selected":t===s.agentType,"aria-label":s.label,title:o?`${s.label} 不可用:${(i==null?void 0:i.error)??"未检测到运行时"}`:s.label,className:t===s.agentType?"is-active":"",onClick:()=>r(s.agentType),children:[e.jsx(pa,{agentType:s.agentType,size:22}),e.jsx("i",{className:o?"is-unavailable":"","aria-hidden":"true"})]},s.agentType)})})}function kx({onOpenFlowStudio:t,openingFlowStudio:n=!1}){return e.jsx("div",{className:"desktop-app-actions",role:"toolbar","aria-label":"应用快捷操作",children:e.jsx("button",{type:"button",className:"ui-icon-button desktop-app-action desktop-app-action--flow-studio",onClick:t,disabled:n,title:"数字人 · Flow Studio","aria-label":"打开 Flow Studio","aria-busy":n,children:n?e.jsx(ot,{className:"desktop-app-action-spinner",size:17,"aria-hidden":"true"}):e.jsx(rp,{size:17,"aria-hidden":"true"})})})}function jx({entryUrl:t,onBack:n}){const r=typeof window<"u"?window.agentApi:void 0,s=typeof(r==null?void 0:r.flowStudioOpen)=="function",i=a.useRef(null),o=a.useRef(null),[l,d]=a.useState("loading"),u=a.useCallback(()=>{o.current&&(r==null||r.flowStudioSetBounds(o.current))},[r]),f=a.useCallback(async()=>{if(!s||!r){d("error");return}if(d("loading"),!(await r.flowStudioOpen(t).catch(()=>({ok:!1}))).ok){d("error");return}u()},[r,s,t,u]);return a.useEffect(()=>{if(!s||!r){d("error");return}const p=r.onFlowStudioEvent(v=>{v.siteId==="flow-studio"&&(v.type==="loading"&&d("loading"),v.type==="loaded"&&(d("ready"),u()),v.type==="load-failed"&&d("error"))});return f(),()=>{p(),r.flowStudioSetBounds(null)}},[r,s,f,u]),a.useEffect(()=>{if(!s||!r)return;const p=i.current;if(!p)return;let v=0;const x=()=>{const j=p.getBoundingClientRect(),E={x:j.x,y:j.y,width:j.width,height:j.height};o.current=E,r.flowStudioSetBounds(E)},w=new ResizeObserver(()=>{cancelAnimationFrame(v),v=requestAnimationFrame(x)});return w.observe(p),x(),()=>{w.disconnect(),cancelAnimationFrame(v)}},[r,s]),e.jsxs("section",{className:"desktop-flow-studio-view","aria-label":"Flow Studio","aria-busy":l==="loading",children:[e.jsx("header",{className:"desktop-flow-studio-topbar",children:e.jsx("button",{type:"button",className:"desktop-flow-studio-back ui-icon-button",onClick:n,title:"返回 AgentRoam","aria-label":"返回 AgentRoam",children:e.jsx(oa,{size:18,"aria-hidden":"true"})})}),e.jsx("div",{ref:i,className:"desktop-flow-studio-content",children:l!=="ready"&&e.jsxs("div",{className:"desktop-flow-studio-status",role:l==="error"?"alert":"status","aria-live":"polite",children:[l==="loading"?e.jsx(ot,{className:"desktop-flow-studio-spinner",size:20,"aria-hidden":"true"}):null,e.jsx("strong",{children:l==="error"?"无法打开 Flow Studio":"正在打开 Flow Studio"}),l==="error"&&e.jsxs("button",{type:"button",className:"desktop-flow-studio-retry",onClick:()=>void f(),children:[e.jsx(Ap,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:"重试"})]})]})})]})}const $o=264,Ac=126;function Sx(t){const n=typeof window>"u"?1024:window.innerWidth,r=typeof window>"u"?768:window.innerHeight,s=Math.max(8,Math.min(t.left+t.width-$o,n-$o-8)),i=t.top+t.height+7,o=i+Ac<=r-8?i:Math.max(8,t.top-Ac-7);return{left:s,top:o,width:$o}}function Tc({title:t,message:n,anchor:r,mobile:s,pending:i,onCancel:o,onConfirm:l}){const d=u=>u.stopPropagation();return e.jsx("div",{className:`sidebar-delete-confirmation-layer${s?" is-mobile":""}`,onClick:i?void 0:o,children:e.jsxs("div",{className:"sidebar-delete-confirmation",role:"alertdialog","aria-modal":"true","aria-labelledby":"sidebar-delete-confirmation-title","aria-describedby":"sidebar-delete-confirmation-message",style:s?void 0:Sx(r),onClick:d,children:[e.jsx("strong",{id:"sidebar-delete-confirmation-title",children:t??"删除会话"}),e.jsx("p",{id:"sidebar-delete-confirmation-message",children:n}),e.jsxs("div",{className:"sidebar-delete-confirmation-actions",children:[e.jsx("button",{type:"button",onClick:o,disabled:i,children:"取消"}),e.jsx("button",{type:"button",className:"is-danger",onClick:l,disabled:i,children:i?"正在删除...":"删除"})]})]})})}function Ho({session:t,deleteLabel:n="删除会话",onSelect:r,onPin:s,onDelete:i}){var o,l;return e.jsxs("div",{className:`sidebar-row sidebar-session-row${t.child?" sidebar-session-row--child":""}${t.active?" sidebar-row-active":""}`,children:[e.jsxs("button",{type:"button",className:"sidebar-session-button",onClick:r,"aria-pressed":t.active,"aria-expanded":t.hasChildren?!!t.expanded:void 0,title:t.title,children:[e.jsx("span",{className:`sidebar-status-dot is-${t.visualState}`,title:t.statusLabel,"aria-label":t.statusLabel}),e.jsx("span",{className:"sidebar-session-title",children:t.title}),((o=t.compatibility)==null?void 0:o.status)==="checking"&&e.jsx("span",{className:"sidebar-session-compatibility",title:`Codex ${t.compatibility.producerVersion??"未知版本"} 会话兼容性待验证,打开会话时检查`,"aria-label":"会话兼容性待验证,打开会话时检查",children:e.jsx(ip,{size:13,"aria-hidden":"true"})}),((l=t.compatibility)==null?void 0:l.status)==="incompatible"&&e.jsx("span",{className:"sidebar-session-compatibility",title:t.compatibility.reason??"Codex 版本不兼容","aria-label":"Codex 版本不兼容",children:e.jsx(Qc,{size:13,"aria-hidden":"true"})}),t.occupiedExternally&&e.jsx("span",{className:"sidebar-session-lock",title:"原客户端正在使用,只读","aria-label":"原客户端正在使用,只读",children:e.jsx(xp,{size:13,"aria-hidden":"true"})}),t.hasChildren&&e.jsx(Kr,{size:13,className:`sidebar-session-disclosure${t.expanded?" is-expanded":""}`,"aria-hidden":"true"})]}),s&&!t.child&&e.jsx("button",{type:"button",onClick:d=>{d.stopPropagation(),s()},title:t.pinned?"取消置顶":"置顶会话","aria-label":`${t.pinned?"取消置顶":"置顶会话"}:${t.title}`,"aria-pressed":!!t.pinned,className:`sidebar-session-pin sidebar-row-action ui-icon-button ui-icon-button--small${t.pinned?" sidebar-row-action--accent":""}`,children:e.jsx(Ep,{size:14,"aria-hidden":"true"})}),t.canDelete&&i&&e.jsx("button",{type:"button",onClick:d=>{d.stopPropagation();const u=d.currentTarget.getBoundingClientRect();i({top:u.top,left:u.left,width:u.width,height:u.height})},title:n,"aria-label":`${n}:${t.title}`,className:"sidebar-session-delete sidebar-row-action ui-icon-button ui-icon-button--small ui-icon-button--danger",children:e.jsx(As,{size:14,"aria-hidden":"true"})})]})}const Cx=[["style",new Set(["css","scss","sass","less","styl"])],["image",new Set(["png","jpg","jpeg","gif","webp","avif","bmp","ico","svg","tif","tiff"])],["video",new Set(["mp4","mov","m4v","webm","mkv","avi","wmv","flv","mpeg","mpg"])],["audio",new Set(["mp3","wav","m4a","aac","ogg","flac","opus"])],["markdown",new Set(["md","mdx","markdown"])],["json",new Set(["json","jsonc","geojson"])],["archive",new Set(["zip","tar","gz","tgz","bz2","xz","7z","rar"])],["spreadsheet",new Set(["csv","tsv","xls","xlsx","ods"])],["presentation",new Set(["ppt","pptx","key","odp"])],["database",new Set(["db","sqlite","sqlite3"])],["text",new Set(["txt","log","rtf","ini","cfg","conf","env","yaml","yml","toml","xml","pdf","doc","docx","odt"])],["code",new Set(["js","jsx","mjs","cjs","ts","tsx","vue","svelte","java","kt","kts","py","rb","go","rs","php","c","cc","cpp","h","hpp","cs","swift","scala","sh","bash","zsh","fish","sql","html"])]],Ix=new Map([["dockerfile","code"],["makefile","code"],["gemfile","code"],["rakefile","code"],["license","text"]]);function iu(t){var i;const n=t.toLocaleLowerCase(),r=Ix.get(n);if(r)return r;if(n.startsWith(".env")||n===".gitignore"||n===".npmrc")return"text";const s=n.includes(".")&&n.split(".").pop()||"";return((i=Cx.find(([,o])=>o.has(s)))==null?void 0:i[0])??"file"}const Rx={folder:{icon:Go,label:"文件夹"},code:{icon:Zc,label:"代码文件"},style:{icon:od,label:"样式文件"},image:{icon:ed,label:"图片文件"},video:{icon:rd,label:"视频文件"},audio:{icon:Jc,label:"音频文件"},markdown:{icon:id,label:"Markdown 文件"},text:{icon:ci,label:"文本文件"},json:{icon:td,label:"JSON 文件"},archive:{icon:Yc,label:"压缩文件"},spreadsheet:{icon:nd,label:"表格文件"},presentation:{icon:ad,label:"演示文件"},database:{icon:Xc,label:"数据库文件"},file:{icon:sd,label:"文件"}};function Ex(t,n){return n==="directory"?"folder":iu(t)}const Nc=t=>t.replace(/\\/g,"/").replace(/\/+$/,"")||"/";function Mx(t,n){const r=Nc(t),s=Nc(n),o=[{label:r==="/"?"/":r.split("/").filter(Boolean).pop()||r,path:r}];if(s===r)return o;const l=s.slice(r==="/"?1:r.length+1);let d=r;for(const u of l.split("/").filter(Boolean))d=d==="/"?`/${u}`:`${d}/${u}`,o.push({label:u,path:d});return o}function Ax({open:t,onCancel:n,onConfirm:r}){const[s,i]=a.useState([]),[o,l]=a.useState(""),[d,u]=a.useState(""),[f,p]=a.useState([]),[v,x]=a.useState(!1),[w,j]=a.useState(""),[E,S]=a.useState(!1),C=a.useMemo(()=>Mx(o||"/",d||o||"/"),[o,d]),k=async L=>{if(window.agentApi){x(!0),j("");try{const T=await window.agentApi.listProjectDirectories(L);p(T),u(L)}catch(T){j(T instanceof Error?T.message:"无法读取目录")}finally{x(!1)}}};if(a.useEffect(()=>{if(!t||!window.agentApi)return;let L=!1;return x(!0),j(""),window.agentApi.listProjectRoots().then(async T=>{if(L)return;i(T);const A=T[0]??"";l(A),A?await k(A):j("未配置可用的宿主机目录")}).catch(T=>{L||j(T instanceof Error?T.message:"无法读取宿主机目录")}).finally(()=>{L||x(!1)}),()=>{L=!0}},[t]),a.useEffect(()=>{if(!t)return;const L=T=>{T.key==="Escape"&&n()};return window.addEventListener("keydown",L),()=>window.removeEventListener("keydown",L)},[t,n]),!t)return null;const z=L=>{l(L),k(L)},M=()=>{C.length<=1||k(C[C.length-2].path)},H=async()=>{if(!(!d||E)){S(!0),j("");try{await r(d)}catch(L){j(L instanceof Error?L.message:"项目导入失败")}finally{S(!1)}}};return On.createPortal(e.jsx("div",{className:"host-project-picker-backdrop",role:"presentation",onMouseDown:L=>{L.target===L.currentTarget&&n()},children:e.jsxs("section",{className:"host-project-picker",role:"dialog","aria-modal":"true","aria-labelledby":"host-project-picker-title",children:[e.jsxs("header",{className:"host-project-picker-header",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"host-project-picker-title",children:"选择宿主机项目"}),e.jsx("p",{children:"文件将直接在运行 AgentRoam 的机器上读写"})]}),e.jsx("button",{type:"button",className:"ui-icon-button",onClick:n,"aria-label":"关闭目录选择器",title:"关闭",children:e.jsx(Tr,{size:16,"aria-hidden":"true"})})]}),s.length>1&&e.jsxs("label",{className:"host-project-picker-root",children:[e.jsx("span",{children:"根目录"}),e.jsx("select",{value:o,onChange:L=>z(L.target.value),children:s.map(L=>e.jsx("option",{value:L,children:L},L))})]}),e.jsxs("nav",{className:"host-project-picker-nav","aria-label":"当前目录",children:[e.jsx("button",{type:"button",className:"ui-icon-button",onClick:M,disabled:C.length<=1,"aria-label":"返回上级目录",title:"返回上级目录",children:e.jsx(oa,{size:16,"aria-hidden":"true"})}),e.jsx("div",{className:"host-project-picker-breadcrumbs",children:C.map((L,T)=>e.jsxs("span",{children:[T>0&&e.jsx("i",{children:"/"}),e.jsx("button",{type:"button",onClick:()=>void k(L.path),children:L.label})]},L.path))}),e.jsx("button",{type:"button",className:"ui-icon-button",onClick:()=>d&&void k(d),disabled:!d||v,"aria-label":"刷新目录",title:"刷新目录",children:e.jsx(Ns,{size:15,"aria-hidden":"true"})})]}),o==="/"&&e.jsx("div",{className:"host-project-picker-warning",children:"当前允许访问宿主机根目录,请谨慎选择项目。"}),e.jsx("div",{className:"host-project-picker-list","aria-busy":v,children:v?e.jsx("div",{className:"host-project-picker-state",children:"正在读取目录…"}):w?e.jsx("div",{className:"host-project-picker-state is-error",children:w}):f.length===0?e.jsx("div",{className:"host-project-picker-state",children:"此目录为空"}):f.map(L=>{const T=Ex(L.name,L.kind),{icon:A,label:R}=Rx[T],$=e.jsxs(e.Fragment,{children:[e.jsx("span",{className:`host-project-picker-entry-icon is-${T}`,"aria-hidden":"true",children:e.jsx(A,{size:18,strokeWidth:1.8})}),e.jsx("span",{className:"host-project-picker-name",children:L.name})]});return L.kind==="file"?e.jsx("div",{className:"host-project-picker-row is-file",title:R,children:$},`${L.name}:${L.path}`):e.jsxs("button",{type:"button",className:"host-project-picker-row is-directory",onClick:()=>void k(L.path),title:R,children:[$,L.hasChildren&&e.jsx("span",{className:"host-project-picker-chevron","aria-hidden":"true",children:e.jsx(Kr,{size:16})})]},`${L.name}:${L.path}`)})}),e.jsxs("footer",{className:"host-project-picker-footer",children:[e.jsx("code",{title:d,children:d}),e.jsxs("div",{children:[e.jsx("button",{type:"button",className:"host-project-picker-cancel",onClick:n,children:"取消"}),e.jsx("button",{type:"button",className:"host-project-picker-confirm",disabled:!d||v||E,onClick:()=>void H(),children:E?"正在导入…":"选择此文件夹"})]})]})]})}),document.body)}const Tx=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;function Nx(t){if(!t.trim())return{rows:[],added:0,removed:0};const n=[];let r=0,s=0,i=!1,o=0,l=0;for(const d of t.replace(/\n$/,"").split(`
|
|
486
|
-
`)){const u=d.match(Tx);if(u){r=Number(u[1]),s=Number(u[2]),i=!0,n.push({kind:"hunk",text:d,oldLine:null,newLine:null});continue}if(!i){!d.startsWith("diff --git ")&&!d.startsWith("index ")&&!d.startsWith("--- ")&&!d.startsWith("+++ ")&&n.push({kind:"meta",text:d,oldLine:null,newLine:null});continue}d.startsWith("+")?(n.push({kind:"added",text:d.slice(1),oldLine:null,newLine:s}),s+=1,o+=1):d.startsWith("-")?(n.push({kind:"removed",text:d.slice(1),oldLine:r,newLine:null}),r+=1,l+=1):d.startsWith(" ")?(n.push({kind:"context",text:d.slice(1),oldLine:r,newLine:s}),r+=1,s+=1):n.push({kind:"note",text:d,oldLine:null,newLine:null})}return{rows:n,added:o,removed:l}}const _c=256*1024,A1=16*1024,_x={java:"java",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",ts:"typescript",tsx:"typescript",json:"json",py:"python",sh:"bash",bash:"bash",zsh:"bash",css:"css",scss:"scss",html:"xml",htm:"xml",xml:"xml",vue:"xml",svelte:"xml",astro:"xml",yml:"yaml",yaml:"yaml",toml:"ini",env:"ini",sql:"sql",c:"c",h:"c",cpp:"cpp",hpp:"cpp",go:"go",rs:"rust",kt:"kotlin",rb:"ruby",md:"markdown",markdown:"markdown",mdown:"markdown",mkdn:"markdown",mdx:"markdown",dockerfile:"dockerfile",gradle:"groovy",properties:"properties",graphql:"graphql",proto:"protobuf"};function zx(t){var s;const n=((s=t.split(/[/\\]/).pop())==null?void 0:s.toLowerCase())??"";if(n==="dockerfile"||n.startsWith("dockerfile."))return"dockerfile";if(n===".env"||n.startsWith(".env."))return"ini";if(n===".bashrc"||n===".zshrc")return"bash";const r=n.includes(".")?n.slice(n.lastIndexOf(".")+1):"";return _x[r]??null}function Lx({path:t,chunks:n,fileSize:r}){const[s,i]=a.useState(null),o=zx(t),l=n.length>0&&o!==null&&(r===void 0||r<=_c)&&n.reduce((u,f)=>u+f.length,0)<=_c;a.useEffect(()=>{if(!l)return;let u=!1;return Vc(async()=>{const{highlightCode:f}=await import("./codeSyntax-
|
|
487
|
-
`))}const mt=a.useCallback((I,Q)=>{const fe=++rt.current,ze=Lc(I);Pt.current=!1,dn(),ln.current=null,o([]),d(null),f(""),v(null),H(null),z(null),C(0),T(null),R(null),F(!1),Ke(null),ke(null),Ie(!1),at(!0),ne(null),Ye("unavailable"),te(!1),le(null),ye("file"),lt(!1),Tt(!1),Nt(!1),B(""),ee(null),ut(!1),w("initial-loading"),Gt.current=!1,Ge.current=0,ht.current=new TextDecoder("utf-8",{fatal:!1}),s("fs:watch",{path:r1(I)}).catch(()=>{}),Q==="text"?(wt(I,fe),Jt(I,!0,fe),ze&&vn.current&&Rt(I,fe)):Q==="image"||Q==="video"||Q==="audio"||Q==="pdf"?Rt(I,fe):Q==="hex"&&(s("fs:stat",{path:I}).then(ge=>{fe===rt.current&&v(ge)}).catch(()=>{}),gt(I,fe))},[Jt,gt,Rt,wt,dn,s]);a.useEffect(()=>{if(t)return vn.current=!1,Te(!1),mt(t,He),()=>{rt.current++,Pt.current=!1,dn()}},[t]),a.useEffect(()=>{let I=null;const Q=fe=>{const ze=fe.detail;!ze||ze!==t||(I!==null&&window.clearTimeout(I),I=window.setTimeout(()=>{He==="text"&&Gt.current?ut(!0):t&&mt(t,He)},350))};return window.addEventListener("file-changed",Q),()=>{window.removeEventListener("file-changed",Q),I!==null&&window.clearTimeout(I)}},[t,He,mt]),a.useEffect(()=>{Gt.current=$e},[$e]),a.useEffect(()=>{if(x!=="initial-loading"){E(!1);return}const I=window.setTimeout(()=>E(!0),120);return()=>window.clearTimeout(I)},[t,x]),a.useEffect(()=>{const I=et.current,Q=nn.current;if(!I||!Q||!t||He!=="text"||We||$e||pe!=="file"||x!=="ready"||k)return;const fe=new IntersectionObserver(ze=>{ze.some(ge=>ge.isIntersecting)&&Jt(t)},{root:Q,rootMargin:"0px 0px 360px 0px"});return fe.observe(I),()=>fe.disconnect()},[$e,We,He,Jt,k,t,x,pe]);const wn=a.useCallback((I,Q)=>{const fe=URL.createObjectURL(I),ze=document.createElement("a");ze.href=fe,ze.download=ii(Q),ze.style.display="none",document.body.appendChild(ze),ze.click(),ze.remove(),window.setTimeout(()=>URL.revokeObjectURL(fe),1e3)},[]),Yn=a.useCallback(async()=>{if(!t||A!==null||ae!==null)return;const I=t;T(null),Ke(null),F(!1),R(0);try{const Q=await zc(I,s,R);wn(Q,I),F(!0),window.setTimeout(()=>F(!1),1500)}catch(Q){T((Q==null?void 0:Q.message)??String(Q))}finally{R(null)}},[wn,A,t,s,ae]),Jn=a.useCallback(async()=>{if(!t||ae!==null||A!==null)return;const I=t;T(null),Ke(null),Ie(!1);const Q=Qx(navigator,window.isSecureContext);if(Q==="insecure-context"){Ke("当前页面是 HTTP,手机 Chrome 仅允许 HTTPS 页面分享文件,请改用 HTTPS 地址后重试");return}if(Q==="unsupported-browser"){Ke("当前浏览器不支持分享文件,请使用最新版手机 Chrome 或系统浏览器");return}ke(0);try{const fe=await zc(I,s,ke),ze=new File([fe],ii(I),{type:Xx(I),lastModified:(p==null?void 0:p.mtime)??Date.now()}),ge=await Yx(ze,navigator);ge==="unsupported"?Ke("当前浏览器不支持分享此文件类型,请使用下载按钮"):ge==="shared"&&(Ie(!0),window.setTimeout(()=>Ie(!1),1500))}catch(fe){Ke((fe==null?void 0:fe.message)??String(fe))}finally{ke(null)}},[A,p==null?void 0:p.mtime,t,s,ae]),Zt=a.useCallback(async(I,Q)=>{const fe=await s("fs:inspect-text",{path:I},6e4);return Q!==rt.current?null:(v({size:fe.size,mtime:fe.mtime}),Ye(fe.diffStatus),ne(fe.patch),lt(!fe.tooLarge&&fe.validUtf8),fe)},[s]),Hn=a.useCallback(async()=>{if(!t||st)return;const I=rt.current;Tt(!0),ee(null);try{const Q=await Zt(t,I);if(!Q)return;if(Q.tooLarge||Q.data===null)throw new Error("文件超过 8M,无法在线编辑");if(!Q.validUtf8)throw new Error("此文件不是有效的 UTF-8 文本,无法在线编辑");const fe=new TextDecoder("utf-8",{fatal:!1}).decode(Ca(Q.data));o([fe]),C(Q.size),Ge.current=Q.size,at(!0),B(fe),ut(!1),Gt.current=!0,Nt(!0)}catch(Q){I===rt.current&&ee(Q.message??String(Q))}finally{I===rt.current&&Tt(!1)}},[st,Zt,t]),en=a.useCallback(async()=>{if(!t||W||(ye("diff"),qe!==null))return;const I=rt.current;te(!0),le(null);try{await Zt(t,I)}catch(Q){I===rt.current&&le(Q.message??String(Q))}finally{I===rt.current&&te(!1)}},[W,Zt,qe,t]),Zn=a.useCallback(()=>{if(!t)return;const I=!we;vn.current=I,Te(I),I&&!l&&Rt(t,rt.current)},[Rt,l,t,we]),kn=a.useCallback(I=>{ln.current===I&&(H(null),w("ready"))},[]),un=a.useCallback(I=>{ln.current===I&&(H("文件预览加载失败,请重试"),w("error"))},[]),ar=a.useCallback(()=>{t&&mt(t,He)},[He,t,mt]),jn=a.useCallback(()=>{ct!==X&&!window.confirm("放弃未保存的修改?")||(Gt.current=!1,Nt(!1),B(""),ee(null),ut(!1))},[ct,X]),Un=a.useCallback(()=>{$e&&ct!==X&&!window.confirm("放弃未保存的修改并关闭预览?")||(rt.current++,dn(),r())},[ct,$e,r,dn,X]),Ne=a.useCallback(()=>{t&&(Gt.current=!1,Nt(!1),B(""),mt(t,"text"))},[t,mt]),it=a.useCallback(async()=>{if(!(!t||!p||Y||ct===X)){q(!0),ee(null);try{await s("fs:write-text",{path:t,content:ct,expectedSize:p.size,expectedMtime:p.mtime},6e4),Gt.current=!1,Nt(!1),B(""),mt(t,"text")}catch(I){ee((I==null?void 0:I.message)??String(I))}finally{q(!1)}}},[ct,p,t,s,Y,mt,X]),Ht=a.useMemo(()=>Nx(qe??""),[qe]);if(!t)return null;const er=((p==null?void 0:p.size)??0)>Ux,Wn=!er&&(be==="changed"||be==="untracked"),Ft=He==="text"&&dt&&x!=="initial-loading"&&!st&&!M;return e.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",background:"var(--ui-term-col-bg, #101014)",color:"var(--ui-text, #e8e8ee)",colorScheme:"var(--ui-color-scheme, dark)",accentColor:"var(--ui-tab-accent, #7aa2f7)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"9px 12px",borderBottom:"1px solid var(--ui-tree-border, #222)",background:"var(--ui-tree-bg, #121218)",flexShrink:0},children:[e.jsx("span",{className:"pv-name",style:{minWidth:0,flex:"1 1 auto",fontSize:12.5,color:"var(--ui-text, #e8e8ee)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ii(t)}),p&&e.jsx("span",{style:{fontSize:10.5,color:"var(--ui-history-meta, #666)",flexShrink:0},children:Uo(p.size)}),$e?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:jn,disabled:Y,style:us,"aria-label":"取消编辑",title:"取消编辑",children:e.jsx(da,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:it,disabled:Y||ct===X,style:{...us,color:"var(--ui-tab-accent, #7aa2f7)",opacity:Y||ct===X?.55:1},"aria-label":Y?"正在保存":"保存修改",title:Y?"正在保存":"保存修改",children:Y?e.jsx(ot,{className:"tree-spin",size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(Tp,{size:15,strokeWidth:1.8,"aria-hidden":"true"})})]}):e.jsxs(e.Fragment,{children:[He==="text"&&e.jsx("button",{type:"button",onClick:Hn,disabled:!Ft,style:{...us,opacity:Ft?1:.45},"aria-label":"编辑文件",title:er?"文件超过 8M,无法在线编辑":dt?"编辑文件":"此文件不可编辑",children:e.jsx(ca,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:Yn,disabled:A!==null||ae!==null,style:{...us,opacity:A!==null||ae!==null?.72:1},"aria-label":A===null?"下载到当前设备":`正在下载 ${A}%`,title:A===null?"下载到当前设备":`正在下载 ${A}%`,children:A!==null?e.jsx(ot,{className:"tree-spin",size:15,strokeWidth:1.8,"aria-hidden":"true"}):$?e.jsx(Gr,{size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(la,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:Jn,disabled:ae!==null||A!==null,style:{...us,opacity:ae!==null||A!==null?.72:1},"aria-label":"分享文件",title:ae===null?"分享文件":`正在准备 ${ae}%`,children:ae!==null?e.jsx(ot,{className:"tree-spin",size:15,strokeWidth:1.8,"aria-hidden":"true"}):Pe?e.jsx(Gr,{size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(_p,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),cn&&e.jsx("button",{type:"button",onClick:Zn,"aria-pressed":we,style:{...us,...we?{color:"var(--ui-tab-accent, #7aa2f7)",borderColor:"var(--ui-tab-accent, #7aa2f7)"}:{}},"aria-label":we?"退出浏览器预览":"浏览器预览",title:we?"退出浏览器预览":Dt?"在浏览器中预览渲染效果":Xn?"预览 Markdown 排版效果":"在浏览器中查看原始文件",children:e.jsx(cp,{size:15,strokeWidth:1.8,"aria-hidden":"true"})})]}),e.jsx("button",{type:"button",onClick:Un,style:us,"aria-label":"关闭预览",title:"关闭预览",children:e.jsx(Tr,{size:15,strokeWidth:1.8,"aria-hidden":"true"})})]}),He==="text"&&Wn&&!$e&&!we&&e.jsxs("div",{style:{display:"flex",alignItems:"center",minHeight:34,padding:"0 12px",borderBottom:"1px solid var(--ui-tree-border, #222)",background:"var(--ui-tree-bg, #121218)",flexShrink:0},children:[e.jsxs("div",{role:"tablist","aria-label":"文件预览模式",style:{display:"inline-flex",gap:2,padding:2,border:"1px solid var(--ui-panel-input-border, #333)",borderRadius:6,background:"var(--ui-muted-surface, #1b1b22)"},children:[e.jsx(Pc,{active:pe==="diff",onClick:en,children:"变更"}),e.jsx(Pc,{active:pe==="file",onClick:()=>ye("file"),children:"文件"})]}),e.jsxs("span",{style:{marginLeft:9,display:"inline-flex",gap:7,fontFamily:'"SF Mono", Menlo, Consolas, monospace',fontSize:10.5},children:[Ht.added>0&&e.jsxs("span",{style:{color:"var(--ui-success, #059669)"},children:["+",Ht.added]}),Ht.removed>0&&e.jsxs("span",{style:{color:"var(--ui-error, #dc2626)"},children:["-",Ht.removed]})]})]}),Ee&&e.jsxs("div",{role:"alert",style:{flexShrink:0,padding:"8px 12px",borderBottom:"1px solid var(--ui-tree-border, #222)",background:"var(--ui-tree-bg, #121218)",color:"var(--ui-error, #f7768e)",fontSize:12.5,lineHeight:1.5},children:["分享失败:",Ee]}),e.jsxs("div",{ref:nn,className:"pv-body",style:{position:"relative",flex:1,minHeight:0,overflow:"auto",background:"var(--ui-term-col-bg, #101014)",WebkitOverflowScrolling:"touch"},children:[L&&e.jsxs("div",{style:{padding:"10px 14px 0",color:"var(--ui-error, #f7768e)",fontSize:12.5},children:["下载失败:",L]}),se&&e.jsx("div",{role:"alert",style:{padding:"10px 14px",color:"var(--ui-error, #f7768e)",fontSize:12.5},children:se}),Ve&&$e&&e.jsxs("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:"1px solid var(--ui-tree-border, #222)",color:"var(--ui-error, #f7768e)",fontSize:12},children:[e.jsx("span",{style:{flex:1},children:"文件已在其他位置更新"}),e.jsxs("button",{type:"button",onClick:Ne,style:ia,children:[e.jsx(Ns,{size:13,strokeWidth:1.8,"aria-hidden":"true"}),"重新加载"]})]}),l&&!M&&He==="image"&&e.jsx("img",{src:l,alt:t,onLoad:()=>kn(l),onError:()=>un(l),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",display:"block",margin:"0 auto"}}),l&&!M&&He==="video"&&e.jsx("video",{src:l,controls:!0,autoPlay:!0,onLoadedMetadata:()=>kn(l),onError:()=>un(l),style:{maxWidth:"100%",maxHeight:"100%",display:"block",margin:"0 auto"}}),l&&!M&&He==="audio"&&e.jsx("div",{style:{display:"grid",placeItems:"center",height:"100%"},children:e.jsx("audio",{src:l,controls:!0,autoPlay:!0,onLoadedMetadata:()=>kn(l),onError:()=>un(l),style:{width:"min(420px, 88%)"}})}),l&&!M&&He==="pdf"&&e.jsx("iframe",{src:l,title:t,onLoad:()=>kn(l),onError:()=>un(l),style:{width:"100%",height:"100%",border:"none"}}),l&&!M&&He==="text"&&cn&&we&&!$e&&e.jsx("iframe",{src:$n?`${l}/${encodeURIComponent(ii(t))}`:l,sandbox:Bx,title:t,onLoad:()=>kn(l),onError:()=>un(l),style:{width:"100%",height:"100%",border:"none",background:"#fff"}}),He==="text"&&$e&&!M&&e.jsx("textarea",{value:ct,onChange:I=>B(I.target.value),spellCheck:!1,autoCapitalize:"off",autoCorrect:"off","aria-label":`编辑 ${ii(t)}`,style:{width:"100%",minHeight:"100%",boxSizing:"border-box",resize:"none",margin:0,padding:"12px 14px calc(env(safe-area-inset-bottom) + 36px)",border:0,outline:0,background:"var(--ui-term-col-bg, #101014)",color:"var(--ui-history-item-text, var(--ui-text, #d6d6de))",fontFamily:'"SF Mono", Menlo, Consolas, monospace',fontSize:12,lineHeight:1.5,tabSize:2}}),He==="text"&&!$e&&!M&&Wn&&pe==="diff"&&(G?e.jsx(Ti,{label:G,actionLabel:"重试",onAction:()=>void en(),tone:"error"}):W?e.jsx(Ti,{label:"正在加载变更"}):e.jsx(s1,{rows:Ht.rows})),(He==="hex"||He==="text"&&!$e&&!we&&(!Wn||pe==="file"))&&!M&&e.jsxs(e.Fragment,{children:[e.jsx("pre",{style:{margin:0,padding:"11px 13px calc(env(safe-area-inset-bottom) + 36px)",fontFamily:'"SF Mono", Menlo, Consolas, monospace',fontSize:He==="hex"?10.5:12,lineHeight:1.45,color:He==="hex"?"var(--ui-muted-text, #9aa)":"var(--ui-history-item-text, var(--ui-text, #d6d6de))",whiteSpace:He==="hex"?"pre":"pre-wrap",wordBreak:He==="hex"?"normal":"break-word"},children:He==="hex"?u:e.jsx(Lx,{path:t,chunks:i,fileSize:p==null?void 0:p.size})}),He==="text"&&!We&&e.jsxs("div",{ref:et,role:"status","aria-live":"polite",style:{minHeight:44,padding:"0 14px calc(env(safe-area-inset-bottom) + 8px)",display:"flex",alignItems:"center",justifyContent:"center",gap:7,color:"var(--ui-history-meta, #666)",fontSize:11.5},children:[x==="loading-more"&&e.jsx(ot,{className:"tree-spin",size:14,strokeWidth:1.8,"aria-hidden":"true",style:{color:"var(--ui-tab-accent, #7aa2f7)"}}),k?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"加载失败"}),e.jsxs("button",{type:"button",onClick:()=>Jt(t),style:ia,children:[e.jsx(Ns,{size:13,strokeWidth:1.8,"aria-hidden":"true"}),"重试"]})]}):e.jsx("span",{children:x==="loading-more"?"正在加载更多":`${Uo(S)} / ${Uo((p==null?void 0:p.size)??S)}`})]})]}),j&&x==="initial-loading"&&e.jsx(Ti,{label:"正在加载文件"}),M&&x==="error"&&e.jsx(Ti,{label:M,actionLabel:"重试",onAction:ar,tone:"error"})]})]})}function ii(t){return t.slice(t.lastIndexOf("/")+1)||t}function r1(t){const n=t.lastIndexOf("/");return n>0?t.slice(0,n):"/"}function Uo(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}K`:`${(t/1024/1024).toFixed(1)}M`}const us={width:28,height:28,borderRadius:7,border:"1px solid var(--ui-panel-input-border, #333)",display:"inline-flex",alignItems:"center",justifyContent:"center",background:"var(--ui-muted-surface, #1b1b22)",color:"var(--ui-muted-text, #ccc)",flexShrink:0,cursor:"pointer",WebkitAppRegion:"no-drag"},ia={minHeight:28,padding:"0 9px",borderRadius:6,border:"1px solid var(--ui-panel-input-border, #333)",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,background:"var(--ui-muted-surface, #1b1b22)",color:"var(--ui-muted-text, #ccc)",cursor:"pointer",fontSize:11};function Ti({label:t,actionLabel:n,onAction:r,tone:s="muted"}){return e.jsxs("div",{role:s==="error"?"alert":"status",style:{position:"absolute",inset:0,minHeight:120,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:10,color:s==="error"?"var(--ui-error, #f7768e)":"var(--ui-muted-text, #9aa)",fontSize:12.5},children:[s!=="error"&&e.jsx(ot,{className:"tree-spin",size:18,strokeWidth:1.8,"aria-hidden":"true",style:{color:"var(--ui-tab-accent, #7aa2f7)"}}),e.jsx("span",{children:t}),n&&r&&e.jsxs("button",{type:"button",onClick:r,style:ia,children:[e.jsx(Ns,{size:13,strokeWidth:1.8,"aria-hidden":"true"}),n]})]})}function Pc({active:t,onClick:n,children:r}){return e.jsx("button",{type:"button",role:"tab","aria-selected":t,onClick:n,style:{minWidth:48,height:24,padding:"0 9px",border:0,borderRadius:4,background:t?"var(--ui-tab-accent, #7aa2f7)":"transparent",color:t?"var(--ui-tab-active-text, #fff)":"var(--ui-muted-text, #9aa)",fontSize:11,fontWeight:600,cursor:"pointer"},children:r})}function s1({rows:t}){return e.jsx("div",{style:{minWidth:"100%",width:"max-content",paddingBottom:"calc(env(safe-area-inset-bottom) + 36px)",fontFamily:'"SF Mono", Menlo, Consolas, monospace',fontSize:11.5,lineHeight:1.55},children:t.map((n,r)=>{const s=n.kind==="added",i=n.kind==="removed",o=n.kind==="hunk"||n.kind==="meta"||n.kind==="note",l=s?"color-mix(in srgb, var(--ui-success, #059669) 12%, transparent)":i?"color-mix(in srgb, var(--ui-error, #dc2626) 11%, transparent)":n.kind==="hunk"?"color-mix(in srgb, var(--ui-tab-accent, #7aa2f7) 10%, transparent)":"transparent",d=s?"var(--ui-success, #059669)":i?"var(--ui-error, #dc2626)":o?"var(--ui-muted-text, #9aa)":"var(--ui-history-item-text, var(--ui-text, #d6d6de))";return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"42px 42px 22px minmax(0, 1fr)",minHeight:18,background:l,color:d},children:[e.jsx("span",{style:Dc,children:n.oldLine??""}),e.jsx("span",{style:Dc,children:n.newLine??""}),e.jsx("span",{style:{textAlign:"center",userSelect:"none",color:d},children:s?"+":i?"-":" "}),e.jsx("span",{style:{padding:"0 12px 0 6px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.text||" "})]},`${n.kind}-${r}`)})})}const Dc={padding:"0 6px",borderRight:"1px solid var(--ui-tree-border, #222)",color:"var(--ui-history-meta, #666)",textAlign:"right",userSelect:"none"};function Hi(t){const n=t.replace(/\/{2,}/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function au(t){const n=Hi(t),r=n.lastIndexOf("/");return r<=0?"/":n.slice(0,r)}function lu(t,n){const r=Hi(t),s=Hi(n);return s==="/"?r.startsWith("/"):r.startsWith(`${s}/`)}function i1(t,n){const r=Hi(t);if(!lu(n,r))return[];const s=au(n);if(s===r)return[r];const i=s.slice(r==="/"?1:r.length+1),o=[r];let l=r;for(const d of i.split("/").filter(Boolean))l=l==="/"?`/${d}`:`${l}/${d}`,o.push(l);return o}const o1={code:{icon:Zc,color:"#7aa2f7",label:"代码文件"},style:{icon:od,color:"#bb9af7",label:"样式文件"},image:{icon:ed,color:"#9ece6a",label:"图片文件"},video:{icon:rd,color:"#f7768e",label:"视频文件"},audio:{icon:Jc,color:"#c099ff",label:"音频文件"},markdown:{icon:id,color:"#73daca",label:"Markdown 文件"},text:{icon:ci,color:"#a9b1d6",label:"文本文件"},json:{icon:td,color:"#e0af68",label:"JSON 文件"},archive:{icon:Yc,color:"#ff9e64",label:"压缩文件"},spreadsheet:{icon:nd,color:"#9ece6a",label:"表格文件"},presentation:{icon:ad,color:"#f7768e",label:"演示文件"},database:{icon:Xc,color:"#2ac3de",label:"数据库文件"},file:{icon:sd,color:"#c8c8d0",label:"文件"}};function a1(t){return o1[iu(t)]}function Wc(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}K`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)}M`:`${(t/1024/1024/1024).toFixed(1)}G`}function l1({gateway:t,onOpenFile:n,selectedPath:r,ready:s,cwd:i,followCwd:o,initialRoot:l,initialFollow:d=!0,onTreeStateChange:u,revealRequest:f}){const p=t.request,v=t.subscribe,[x,w]=a.useState(null),[j,E]=a.useState(""),[S,C]=a.useState(""),[k,z]=a.useState(!d),[M,H]=a.useState(""),L=a.useRef(new Map),T=a.useRef(null),A=a.useRef(null),R=a.useRef(0),$=a.useRef(0),[,F]=a.useState(0),Ee=()=>F(G=>G+1),Ke=a.useCallback(async(G,le)=>{const pe={path:G,depth:le,expanded:!0,children:null,loading:!0};L.current.set(G,pe),Ee();try{const ye=await p("fs:list",{path:G});pe.children=ye.entries,p("fs:watch",{path:G}).catch(()=>{})}catch(ye){pe.children=[],pe.error=(ye==null?void 0:ye.message)??"read failed"}return pe.loading=!1,Ee(),pe},[p]),ae=!!o&&!k,ke=a.useCallback(G=>{const le=G.length>1?G.replace(/\/+$/,""):G;T.current=le,L.current.clear(),w({path:le,depth:0,expanded:!1,children:null,loading:!1}),C(le)},[]);a.useEffect(()=>{!s||!i||!ae||T.current!==i&&(ke(i),u==null||u(i,!0))},[s,i,ae,ke]),a.useEffect(()=>{!s||!l||d||T.current||(z(!0),ke(l))},[s,l,d,ke]),a.useEffect(()=>{s&&p("hello").then(G=>{H(G.home),ae&&!i&&!T.current&&ke(G.home)}).catch(()=>{})},[s,i,ae,p,ke]);const Pe=()=>{let G=S.trim();G&&(G==="~"?G=M||i||"/":G.startsWith("~/")?G=`${M||i||""}${G.slice(1)}`:G.startsWith("/")||(G=`${i||(x==null?void 0:x.path)||M||"/"}/${G}`),G=G.replace(/\/+/g,"/"),z(!0),ke(G),u==null||u(G,!1))},Ie=()=>{z(!1),i&&(ke(i),u==null||u(i,!0))},We=a.useCallback(async G=>{let le=L.current.get(G);le||(le={path:G,depth:0,expanded:!1,children:null,loading:!1},L.current.set(G,le)),le.expanded?le.expanded=!1:(le.expanded=!0,!le.children&&!le.loading&&await Ke(G,le.depth)),Ee()},[Ke]),at=a.useCallback(async(G,le)=>{let pe=L.current.get(G);pe?!pe.children&&!pe.loading&&await Ke(G,le):pe=await Ke(G,le),pe.expanded=!0,Ee()},[Ke]),qe=a.useCallback(async(G,le)=>{const pe=au(G);let ye=(x==null?void 0:x.path)??pe;lu(G,ye)||(ye=pe,z(!0),ke(ye),u==null||u(ye,!1));const we=i1(ye,G);for(let dt=0;dt<we.length;dt+=1){if(R.current!==le)return;await at(we[dt],dt)}const Te=()=>{var lt;if(R.current!==le)return;const dt=Array.from(((lt=A.current)==null?void 0:lt.querySelectorAll("[data-tree-path]"))??[]).find(st=>st.dataset.treePath===G);dt==null||dt.scrollIntoView({block:"center",inline:"nearest"})};requestAnimationFrame(()=>requestAnimationFrame(Te))},[ke,u,at,x==null?void 0:x.path]);a.useEffect(()=>{!s||!f||$.current!==f.requestId&&($.current=f.requestId,R.current=f.requestId,qe(f.path,f.requestId))},[s,qe,f==null?void 0:f.requestId]),a.useEffect(()=>v("fs:event",G=>{for(const le of G.events??[]){const pe=le.path;pe===r&&window.dispatchEvent(new CustomEvent("file-changed",{detail:pe}));const ye=pe.slice(0,pe.lastIndexOf("/"))||"/",we=L.current.get(ye);we!=null&&we.expanded&&we.children&&!we.loading&&Ke(ye,we.depth).catch(()=>{})}}),[v,r,Ke]);const ne=(G,le)=>G.endsWith("/")?G+le:`${G}/${le}`,be=j.trim().toLowerCase(),Ye=(G,le)=>{var we;if(!be||le.name.toLowerCase().includes(be))return!0;if(!le.dir)return!1;const pe=ne(G,le.name),ye=(we=L.current.get(pe))==null?void 0:we.children;return(ye==null?void 0:ye.some(Te=>Ye(pe,Te)))??!1},W=(G,le,pe)=>le.filter(ye=>Ye(G,ye)).map(ye=>{const we=ne(G,ye.name);if(ye.dir){const lt=L.current.get(we),st=(lt==null?void 0:lt.expanded)??!1;return e.jsxs("div",{children:[e.jsxs("div",{className:"tree-row",onClick:()=>We(we),style:{paddingLeft:6+pe*12},children:[e.jsx("span",{className:"tree-disclosure","aria-hidden":"true",children:lt!=null&<.loading?e.jsx(ot,{className:"tree-spin",size:13}):st?e.jsx(Pi,{size:13}):e.jsx(Kr,{size:13})}),e.jsx("span",{className:"tree-entry-icon tree-folder-icon","aria-hidden":"true",children:st?e.jsx(hl,{size:16}):e.jsx(Go,{size:16})}),e.jsx("span",{className:"tree-entry-name",children:ye.name})]}),st&&(lt.error?e.jsx("div",{className:"tree-error",role:"alert",style:{paddingLeft:22+pe*12},children:lt.error}):lt.children?W(we,lt.children,pe+1):e.jsx("div",{className:"tree-row",style:{paddingLeft:22+pe*12,color:"#556"},children:"…"}))]},we)}const Te=a1(ye.name),dt=Te.icon;return e.jsxs("div",{className:"tree-row","data-tree-path":we,"data-selected":we===r?"1":void 0,onClick:()=>n(we),title:`${Te.label} · ${we} · ${Wc(ye.size)}`,style:{paddingLeft:6+pe*12},children:[e.jsx("span",{className:"tree-disclosure","aria-hidden":"true"}),e.jsx("span",{className:"tree-entry-icon",style:{color:Te.color},"aria-hidden":"true",children:e.jsx(dt,{size:16,strokeWidth:1.8})}),e.jsx("span",{className:"tree-entry-name",children:ye.name}),e.jsx("span",{className:"tree-size",children:Wc(ye.size)})]},we)});if(!x)return e.jsx("div",{style:{padding:14,fontSize:12,color:"#556"},children:ae?s?"等待终端目录…":"连接中…":"…"});const te=L.current.get(x.path);return e.jsxs("div",{className:"tree-scroll",ref:A,children:[e.jsxs("div",{className:"tree-location",children:[e.jsx("input",{value:S,onChange:G=>C(G.target.value),onKeyDown:G=>{G.key==="Enter"&&Pe()},placeholder:"输入目录路径","aria-label":"文件树目录路径",spellCheck:!1}),e.jsx("button",{tabIndex:-1,onClick:Pe,title:"定位目录","aria-label":"定位目录",children:e.jsx(ap,{size:14,"aria-hidden":"true"})}),e.jsx("button",{tabIndex:-1,onClick:Ie,title:"跟随终端目录","aria-label":"跟随终端目录","data-active":ae?"1":void 0,children:e.jsx(mp,{size:14,"aria-hidden":"true"})})]}),e.jsxs("div",{className:"tree-filter",children:[e.jsx(ua,{size:14,"aria-hidden":"true"}),e.jsx("input",{value:j,onChange:G=>E(G.target.value),placeholder:"筛选已加载文件","aria-label":"筛选文件树"}),j&&e.jsx("button",{tabIndex:-1,onClick:()=>E(""),"aria-label":"清除筛选",children:e.jsx(Tr,{size:13,"aria-hidden":"true"})})]}),e.jsxs("div",{className:"tree-row",onClick:()=>We(x.path),children:[e.jsx("span",{className:"tree-disclosure","aria-hidden":"true",children:te!=null&&te.loading?e.jsx(ot,{className:"tree-spin",size:13}):te!=null&&te.expanded?e.jsx(Pi,{size:13}):e.jsx(Kr,{size:13})}),e.jsx("span",{className:"tree-entry-icon tree-folder-icon","aria-hidden":"true",children:te!=null&&te.expanded?e.jsx(hl,{size:16}):e.jsx(Go,{size:16})}),e.jsx("span",{className:"tree-entry-name",style:{direction:"rtl",textAlign:"left"},children:x.path})]}),(te==null?void 0:te.expanded)&&(te.error?e.jsx("div",{className:"tree-error",role:"alert",children:te.error}):te.children?W(x.path,te.children,1):e.jsx("div",{className:"tree-row",style:{paddingLeft:24,color:"#556"},children:"…"}))]})}function c1({open:t,tab:n,gateway:r,cwd:s,selectedPath:i,revealRequest:o,onTabChange:l,onSelectPath:d,onClose:u}){return t?e.jsxs("section",{className:`desktop-file-workspace${i?" has-preview":""}`,"aria-label":"我的文件",children:[e.jsxs("aside",{className:"desktop-file-drawer",children:[e.jsxs("header",{className:"desktop-file-drawer-header",children:[e.jsxs("div",{className:"desktop-file-drawer-tabs",role:"tablist","aria-label":"文件工作区视图",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":n==="files",className:n==="files"?"is-active":"",onClick:()=>l("files"),children:"文件"}),e.jsx("button",{type:"button",role:"tab","aria-selected":n==="history",className:n==="history"?"is-active":"",onClick:()=>l("history"),children:"历史"})]}),e.jsx("button",{type:"button",className:"desktop-file-workspace-close ui-icon-button ui-icon-button--small",onClick:u,"aria-label":"关闭我的文件",title:"关闭",children:e.jsx(Tr,{size:15,"aria-hidden":"true"})})]}),n==="files"?s?e.jsx(l1,{gateway:r,ready:!0,followCwd:!0,cwd:s,onOpenFile:f=>d(f),selectedPath:i,revealRequest:o}):e.jsx("div",{className:"desktop-file-workspace-empty",children:"请先选择一个项目目录"}):e.jsxs("div",{className:"desktop-file-workspace-empty",children:[e.jsx("strong",{children:"终端历史在 Web 控制台中可用"}),e.jsx("span",{children:"Electron 当前没有终端上下文,因此不会提供填入或执行操作。"})]}),e.jsxs("footer",{className:"desktop-file-drawer-footer",children:[e.jsx("span",{}),"实时同步"]})]}),i&&e.jsx("div",{className:"desktop-file-preview",children:e.jsx(n1,{path:i,gateway:r,onClose:()=>d(null)})})]}):null}const cu="agentroam.agent-workspaces.v2",d1=2,du=["customer-agent","codex","claude-code","opencode"];function Fc(){return{version:2,activeAgent:"customer-agent",agents:{}}}function Bc(){return{workspaces:[],nextCursor:null,watermark:null,expandedWorkspaceIds:[],selectedWorkspaceId:null,selectedSessionId:null,sidebarScrollTop:0,sessions:{}}}function u1(t=localStorage){try{const n=JSON.parse(t.getItem(cu)??"null");if(!ps(n)||n.version!==d1)return Fc();const r=m1(n.activeAgent)?n.activeAgent:"customer-agent",s=ps(n.agents)?n.agents:{},i={};for(const o of du){const l=g1(s[o],o);l&&(i[o]=l)}return{version:2,activeAgent:r,agents:i}}catch{return Fc()}}function Oc(t,n=localStorage){try{n.setItem(cu,JSON.stringify(t))}catch{}}function p1(t,n,r){const s=new Set(n.data.map(l=>l.workspaceId)),i=r?n.nextCursor?[...n.data,...t.filter(l=>!s.has(l.workspaceId))]:n.data:[...t,...n.data],o=new Set;return i.filter(l=>o.has(l.workspaceId)?!1:(o.add(l.workspaceId),!0))}function uu(t,n,r){const s=new Set(n.data.map(u=>u.id)),i=new Map(n.data.map(u=>[u.id,u])),o=new Set(t.map(u=>u.id)),l=r?n.nextCursor?[...n.data,...t.filter(u=>!s.has(u.id))]:n.data:[...t.map(u=>i.get(u.id)??u),...n.data.filter(u=>!o.has(u.id))],d=new Set;return l.filter(u=>d.has(u.id)?!1:(d.add(u.id),!0))}async function f1(t,n,r,s){if(n.stale)return n;const i=new Set(n.data.map(p=>p.id)),o=new Set(t.filter(p=>p.status==="running"&&p.id!==s&&!i.has(p.id)).map(p=>p.id));if(o.size===0||!n.nextCursor)return n;let l=[...n.data],d=n.nextCursor,u=n.watermark;const f=new Set;for(;d&&o.size>0;){const p=d;if(f.has(p))return{data:l,nextCursor:p,watermark:u,stale:!0};f.add(p);const v=await r(p);if(v.stale)return{data:l,nextCursor:p,watermark:u,stale:!0};l=uu(l,v,!1);for(const x of v.data)o.delete(x.id);d=v.nextCursor,u=v.watermark??u}return{data:l,nextCursor:d,watermark:u}}function h1(t,n){return!n||t.some(r=>r.id===n.id)?[...t]:[n,...t]}function g1(t,n){if(!ps(t))return null;const r=Array.isArray(t.workspaces)?t.workspaces.filter(i=>ps(i)&&i.agentType===n&&typeof i.workspaceId=="string"&&typeof i.name=="string"&&Array.isArray(i.roots)&&i.roots.every(o=>typeof o=="string")&&typeof i.order=="number"&&(i.canCreateSession===void 0||typeof i.canCreateSession=="boolean")):[],s={};if(ps(t.sessions))for(const[i,o]of Object.entries(t.sessions))!ps(o)||!Array.isArray(o.data)||(s[i]={data:o.data.filter(l=>ps(l)&&l.agentType===n&&typeof l.id=="string"),nextCursor:typeof o.nextCursor=="string"?o.nextCursor:null,loaded:o.loaded===!0});return{workspaces:r,nextCursor:typeof t.nextCursor=="string"?t.nextCursor:null,watermark:typeof t.watermark=="string"?t.watermark:null,expandedWorkspaceIds:Array.isArray(t.expandedWorkspaceIds)?t.expandedWorkspaceIds.filter(i=>typeof i=="string"):[],selectedWorkspaceId:typeof t.selectedWorkspaceId=="string"?t.selectedWorkspaceId:null,selectedSessionId:typeof t.selectedSessionId=="string"?t.selectedSessionId:null,sidebarScrollTop:typeof t.sidebarScrollTop=="number"&&t.sidebarScrollTop>=0?t.sidebarScrollTop:0,sessions:s}}function m1(t){return typeof t=="string"&&du.includes(t)}function ps(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function x1(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)||/^\\\\[^\\/]+[\\/][^\\/]+/.test(t)}function b1(t,n){if(n.webShell||n.isInvalid||!n.supported)return null;const r=t.description;return!r||/[\0\r\n]/.test(r)||!x1(r)?null:r}function y1(t){return{request:(n,r)=>t.fileWorkspaceRequest(n,r),subscribe:(n,r)=>n!=="fs:event"?()=>{}:t.onFileWorkspaceEvent(r)}}function v1(t){try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.toString()}catch{return null}}async function w1(){var t;try{const n=window.sharedServiceApi;if(!(n!=null&&n.request))return null;const r=await n.request("/api/flow-studio/config","GET");if(r.status!==200)return null;const s=(t=JSON.parse(r.body).entryUrl)==null?void 0:t.trim();return s?v1(s):null}catch{return null}}function k1({authoritativeStatus:t,locallyRunning:n,needsInput:r,stale:s}){return t==="failed"||t==="error"?"error":s&&!n?"stale":n||t==="running"?r?"needs-input":"running":"idle"}function j1(t,n){const r=new Set;t&&r.add(t);for(const s of n)s&&r.add(s);return[...r]}function S1(t,n,r){return[...t].filter(s=>!n.has(s)&&!r.has(s))}function $c(t,n){var i;const r={},s={};for(const[o,l]of Object.entries(t)){const d=l.data;r[o]=na(d.filter(u=>!u.parentSessionId),n);for(const u of d.filter(f=>f.parentSessionId))(s[i=u.parentSessionId]??(s[i]=[])).push(u)}for(const o of Object.values(s))o.sort((l,d)=>l.created.localeCompare(d.created));return{roots:r,children:s,projectIds:new Set(Object.entries(t).filter(([,o])=>o.loaded).map(([o])=>o))}}function Hc(t,n,r){return t==="codex"&&(n==null?void 0:n.canCreateSession)!==!1?!0:r}function qo(t){return{id:t.workspaceId,name:t.name,description:t.roots[0]??"",created:t.updatedAt??"",updated:t.updatedAt??"",agentType:t.agentType,source:t.source,canCreateSession:t.canCreateSession}}function Uc(){return e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M3 6h18"}),e.jsx("path",{d:"M8 6V4h8v2"}),e.jsx("path",{d:"M19 6l-1 14H6L5 6"}),e.jsx("path",{d:"M10 11v5M14 11v5"})]})}function qc(t,n){n&&t.detail>0&&t.currentTarget.blur()}function C1(){const t=document.activeElement;t instanceof HTMLElement&&(t.matches("input, textarea, select")||t.isContentEditable)&&t.blur()}function I1(){var Pn,Os,wr,Zr,es,$s;const[t]=a.useState(u1),n=t.activeAgent,r=t.agents[n]??Bc(),[s]=a.useState(()=>$c(r.sessions,n)),i=a.useRef(t),[o,l]=a.useState(n),d=a.useRef(o);d.current=o;const[u,f]=a.useState(r.workspaces.map(qo)),[p,v]=a.useState(r.nextCursor),[x,w]=a.useState(r.watermark),[j,E]=a.useState(!1),[S,C]=a.useState(!1),[k,z]=a.useState(null),[M,H]=a.useState(!1),[L,T]=a.useState(s.roots),[A,R]=a.useState(""),[$,F]=a.useState(!1),[Ee,Ke]=a.useState(10),[ae,ke]=a.useState(null),[Pe,Ie]=a.useState(!1),[We,at]=a.useState(null),[qe,ne]=a.useState(!1),[be,Ye]=a.useState(null),W=a.useRef(!1),[te,G]=a.useState([]),[le,pe]=a.useState(s.children),ye=a.useRef(L),we=a.useRef(le);ye.current=L,we.current=le;const[Te,dt]=a.useState(s.projectIds),[lt,st]=a.useState(new Set),[Tt,$e]=a.useState({}),[Nt,ct]=a.useState(new Set),[B,Y]=a.useState(Object.fromEntries(Object.entries(r.sessions).map(([g,_])=>[g,_.nextCursor]))),q=a.useRef(new Map),se=a.useRef(new Map),[ee,Ve]=a.useState(r.selectedWorkspaceId),[ut,nn]=a.useState(r.selectedSessionId),et=a.useRef(ee),Ge=a.useRef(ut);et.current=ee,Ge.current=ut;const[Gt,rt]=a.useState(new Set),[Pt,ht]=a.useState(new Set(r.expandedWorkspaceIds)),[_t,ln]=a.useState(new Set),[vn,He]=a.useState(!1),[Dt,Xn]=a.useState(!1),[$n,cn]=a.useState(!1),[X,dn]=a.useState("settings"),Jt=Ze(g=>g.setTodos),wt=bn(g=>g.skin),Rt=bn(g=>g.layout),gt=bn(g=>g.wakeEnabled),Wt=bn(g=>g.wakeWord),mt=bn(g=>g.setSkin),wn=bn(g=>g.setLayout),Yn=bn(g=>g.setWakeEnabled),Jn=bn(g=>g.setWakeWord),Zt=bn(g=>g.autoSpeak),Hn=bn(g=>g.setAutoSpeak),en=bn(g=>g.runningFirst),Zn=bn(g=>g.setRunningFirst),kn=bn(g=>g.pinnedSessionIds),un=bn(g=>g.togglePinnedSession),ar=bn(g=>g.removePinnedSessions),jn=new Set(kn),Un=Ze(g=>g.runningSessionId),Ne=Ze(Op(g=>Object.entries(g.messagesBySession).filter(([,_])=>_.some(U=>U.askUser&&!U.askUser.answered)).map(([_])=>_))),it=a.useCallback((g,_=g.projectId)=>k1({authoritativeStatus:g.status,locallyRunning:Un===g.id,needsInput:Ne.includes(g.id),stale:!!(_&&(Nt.has(_)||Tt[_]))}),[Tt,Un,Ne,Nt]),Ht=a.useCallback(g=>{const _=it(g);return _==="running"||_==="needs-input"},[it]),er=()=>{ht(new Set),rt(new Set(Object.keys(le)))},Wn=()=>{const g=u.filter(U=>!_t.has(U.id)),_=g.map(U=>U.id);ht(new Set(_)),rt(new Set);for(const U of g){const V=U.id;if(Vt.current.has(V))continue;const K=fn.current.has(V),Re=Hc(d.current,U,K);Ce(V,{refresh:Re,background:K})}},Ft=Vo(),I=Xu(),Q=Ft&&I,[fe,ze]=a.useState(!1),[ge,Ut]=a.useState(!1),[rn,pt]=a.useState("files"),[Sn,hr]=a.useState(null),[hs,lr]=a.useState(null),Bt=a.useMemo(()=>{var g;return!Ft&&typeof((g=window.agentApi)==null?void 0:g.fileWorkspaceRequest)=="function"?y1(window.agentApi):null},[Ft]),sn=a.useCallback(g=>{if(Ft){Mh(g);return}Bt&&(pt("files"),Ut(!0),hr(g),lr(_=>({path:g,requestId:((_==null?void 0:_.requestId)??0)+1})))},[Bt,Ft]);a.useEffect(()=>{hr(null),lr(null)},[ee]);const[tr,gr]=a.useState(!1),[qt,Xr]=a.useState(null),[Yr,Mn]=a.useState(0),[cr,on]=a.useState(void 0),pn=a.useRef(null),qn=a.useRef(!1),[gs,mr]=a.useState(null),An=a.useRef(null),xt=a.useRef(!1),kt=a.useRef(u);kt.current=u;const Tn=a.useRef(_t);Tn.current=_t;const fn=a.useRef(Te);fn.current=Te;const Vt=a.useRef(lt);Vt.current=lt;const Nn=a.useRef(null);a.useEffect(()=>{document.documentElement.setAttribute("data-skin",wt)},[wt]),a.useEffect(()=>{document.body.classList.toggle("layout-compact",Rt==="compact")},[Rt]),a.useEffect(()=>{var V;const g=u.map((K,Re)=>({agentType:o,workspaceId:K.id,name:K.name,roots:K.description?[K.description]:[],order:Re,updatedAt:K.updated||void 0,source:K.source??(K.agentType==="claude-code"?"derived":"native"),canCreateSession:K.canCreateSession})),_=Object.fromEntries(u.map(K=>[K.id,{data:[...L[K.id]??[],...Object.values(le).flat().filter(Re=>(L[K.id]??[]).some(me=>me.id===Re.parentSessionId))],nextCursor:B[K.id]??null,loaded:Te.has(K.id)}])),U={...i.current,version:2,activeAgent:o,agents:{...i.current.agents,[o]:{workspaces:g,nextCursor:p,watermark:x,expandedWorkspaceIds:[...Pt],selectedWorkspaceId:ee,selectedSessionId:ut,sidebarScrollTop:((V=Nn.current)==null?void 0:V.scrollTop)??0,sessions:_}}};i.current=U,Oc(U)},[o,le,Pt,Te,u,ee,ut,B,L,p,x]);const nr=a.useCallback(()=>{if(!window.agentApi||!gt||qn.current||pn.current)return;const g=()=>{Df()&&!pn.current&&(pn.current=Ff({wakeWord:Wt,onWake:_=>{var U;on(_),Mn(V=>V+1),(U=window.agentApi)==null||U.showWindow()},onError:_=>console.warn("[wake]",_)}))};typeof window.agentApi.wakeStart=="function"?(qn.current=!0,window.agentApi.wakeStart(Wt).then(_=>{_.ok||(qn.current=!1,g())}).catch(()=>{qn.current=!1,g()})):g()},[gt,Wt]);a.useEffect(()=>{var g;if((g=window.agentApi)!=null&&g.onWake)return window.agentApi.onWake(_=>{qn.current=!1,on(_),Mn(U=>U+1)})},[]),a.useEffect(()=>{var g;if((g=window.agentApi)!=null&&g.onWakeAiHub)return window.agentApi.onWakeAiHub(()=>{cn(!0),wn("focus")})},[]),a.useEffect(()=>{var g;if((g=window.agentApi)!=null&&g.onWakeCommand)return window.agentApi.onWakeCommand(_=>{var Re;const U=((_==null?void 0:_.text)||"").trim();if(!U)return;const V=An.current&&Date.now()<An.current.until?An.current:null;if(V){V.until=Date.now()+9e4,nn(V.sessionId),(Re=window.agentApi)==null||Re.wakeConversation(!0),mr({text:U,projectId:null,sessionId:V.sessionId,nonce:Date.now()}),Je(`语音追问:${U.length>40?U.slice(0,40)+"…":U}`),Lt("success"),setTimeout(()=>Je(null),4e3);return}const K=kt.current.find(me=>me.name&&U.includes(me.name)&&!Tn.current.has(me.id));K&&(Ve(K.id),ht(me=>{const Le=new Set(me);return Le.add(K.id),Le})),nn(null),xt.current=!0,Hn(!0),mr({text:U,projectId:(K==null?void 0:K.id)??null,nonce:Date.now()}),Je(`语音指令:${U.length>40?U.slice(0,40)+"…":U}${K?`(项目:${K.name})`:""}`),Lt("success"),setTimeout(()=>Je(null),4e3)})},[]);const Nr=a.useCallback(async()=>{window.agentApi&&(nr(),await window.agentApi.hideWindow())},[nr]),Ot=a.useCallback(g=>{He(!1),Xr({right:g.right,bottom:g.bottom}),gr(_=>!_)},[]),xr=a.useCallback(()=>{gr(!1),He(g=>!g)},[]);a.useEffect(()=>{if(!tr)return;const g=()=>{const U=document.querySelector(".chat-header-action--appearance");if(!U)return;const V=U.getBoundingClientRect();Xr(K=>(K==null?void 0:K.right)===V.right&&K.bottom===V.bottom?K:{right:V.right,bottom:V.bottom})},_=window.requestAnimationFrame(g);return window.addEventListener("resize",g),()=>{window.cancelAnimationFrame(_),window.removeEventListener("resize",g)}},[Rt,tr]),a.useEffect(()=>{window.agentApi&&nr()},[nr]),a.useEffect(()=>{const g=()=>{var _;(_=pn.current)==null||_.stop(),pn.current=null};return window.addEventListener("focus",g),()=>window.removeEventListener("focus",g)},[]),a.useEffect(()=>{var g,_;gt||((g=pn.current)==null||g.stop(),pn.current=null,qn.current=!1,(_=window.agentApi)==null||_.wakeStop())},[gt]),a.useEffect(()=>{!gt||!window.agentApi||qn.current&&window.agentApi.wakeStart(Wt)},[Wt]),a.useEffect(()=>()=>{var g;(g=pn.current)==null||g.stop()},[]);const Cn=[...Object.values(L).flat(),...Object.values(le).flat()],dr=Vm(Cn,g=>jn.has(g.id)),_n=Object.entries(L).flatMap(([g,_])=>_.filter(U=>jn.has(U.id)).map(U=>({projectId:g,session:U,created:U.created}))),_r=na(_n,o),br=en?vc(_r,({session:g})=>Ht(g)):_r,Ls=Cn,rr=A.trim().toLowerCase(),ur=rr?dr.filter(g=>g.title.toLowerCase().includes(rr)||(g.cwd||"").toLowerCase().includes(rr)):null,Kt=ut?Ls.find(g=>g.id===ut):void 0,Qt=Kt==null?void 0:Kt.title,b=(Kt==null?void 0:Kt.cwd)||((Pn=u.find(g=>g.id===ee))==null?void 0:Pn.description)||null,N=u.filter(g=>!_t.has(g.id)).map(g=>g.id),D=[...u.filter(g=>!_t.has(g.id)),...u.filter(g=>_t.has(g.id))],re=N.length>0&&N.every(g=>!Pt.has(g)),[ce,Qe]=a.useState(300),[De,Ue]=a.useState(!1),Xe=a.useRef(!1),jt=a.useRef(0),zt=a.useRef(0),$t=a.useCallback(g=>{if(!Xe.current)return;const _=Math.min(480,Math.max(160,zt.current+g.clientX-jt.current));Qe(_)},[]),Vn=a.useCallback(()=>{Xe.current=!1,Ue(!1),document.removeEventListener("mousemove",$t),document.removeEventListener("mouseup",Vn)},[$t]),zn=a.useCallback(g=>{Xe.current=!0,Ue(!0),jt.current=g.clientX,zt.current=ce,document.addEventListener("mousemove",$t),document.addEventListener("mouseup",Vn)},[ce,$t,Vn]),[yr,Je]=a.useState(null),[zr,Lt]=a.useState("success"),[Ln,Lr]=a.useState(null),[sr,ui]=a.useState(!1),pi=a.useCallback(async()=>{if(!sr){ui(!0);try{const g=await w1();if(g){cn(!1),ze(!1),Lr(g);return}Je("Flow Studio 入口不可用,请检查服务配置"),Lt("error"),setTimeout(()=>Je(null),4e3)}finally{ui(!1)}}},[sr]),hn=g=>{et.current=g.projectId,Ge.current=g.sessionId,Ve(g.projectId),nn(g.sessionId),g.sessionId||Jt([])},fi=g=>{var me;if(g===d.current)return;const _=d.current,U=i.current.agents[_];U&&(i.current={...i.current,agents:{...i.current.agents,[_]:{...U,sidebarScrollTop:((me=Nn.current)==null?void 0:me.scrollTop)??U.sidebarScrollTop}}});const V=i.current.agents[g]??Bc(),K=$c(V.sessions,g),Re=V.workspaces.map(qo);d.current=g,kt.current=Re,l(g),f(Re),v(V.nextCursor),w(V.watermark),E(!1),C(!1),z(null),ye.current=K.roots,we.current=K.children,T(K.roots),pe(K.children),dt(K.projectIds),fn.current=K.projectIds,st(new Set),Vt.current=new Set,$e({}),ct(new Set),Y(Object.fromEntries(Object.entries(V.sessions).map(([Le,Fe])=>[Le,Fe.nextCursor]))),ht(new Set(V.expandedWorkspaceIds)),ln(new Set),hn({projectId:V.selectedWorkspaceId,sessionId:V.selectedSessionId}),window.requestAnimationFrame(()=>{Nn.current&&(Nn.current.scrollTop=V.sidebarScrollTop)}),Gn(g,{refresh:V.workspaces.length>0,since:V.watermark})},[Ps,ms]=a.useState([]),Pr=a.useCallback(g=>{ms(_=>_.filter(U=>U.id!==g))},[]),an=a.useCallback(g=>{const _=crypto.randomUUID();ms(U=>[...U,{...g,id:_}]),setTimeout(()=>Pr(_),12e3)},[Pr]);async function Gn(g=d.current,_={}){if(!window.agentApi)return;const U=(se.current.get(g)??0)+1;se.current.set(g,U),E(!0),z(null);try{const V=await window.agentApi.listAgentWorkspaces(g,{cursor:_.cursor,limit:50,refresh:_.refresh,since:_.refresh?_.since??x:null});if(d.current!==g||se.current.get(g)!==U)return;const K=kt.current.map((_e,Et)=>({agentType:g,workspaceId:_e.id,name:_e.name,roots:_e.description?[_e.description]:[],order:Et,updatedAt:_e.updated,source:_e.source??(g==="claude-code"?"derived":"native"),canCreateSession:_e.canCreateSession})),me=p1(K,V,!_.cursor).map(qo);kt.current=me,f(me),v(V.nextCursor),w(V.watermark),C(V.stale===!0);const Le=new Set(me.map(_e=>_e.id)),Fe=et.current;Fe&&!Le.has(Fe)&&hn(Po);const tn=new Set([...fn.current].filter(_e=>Le.has(_e)));Fe&&Le.has(Fe)&&tn.add(Fe),T(_e=>Object.fromEntries(Object.entries(_e).filter(([Et])=>Le.has(Et)))),dt(_e=>{const Et=new Set([..._e].filter(In=>Le.has(In)));return fn.current=Et,Et}),st(_e=>{const Et=new Set([..._e].filter(In=>Le.has(In)));return Vt.current=Et,Et}),$e(_e=>Object.fromEntries(Object.entries(_e).filter(([Et])=>Le.has(Et))));const Fn=new Set;if(await Promise.all(me.map(async _e=>{_e.description&&!await window.agentApi.checkProjectPath(_e.description)&&Fn.add(_e.id)})),d.current!==g||se.current.get(g)!==U)return;if(ln(Fn),_.refreshLoadedSessions!==!1)for(const _e of tn)Fn.has(_e)||Vt.current.has(_e)||Ce(_e,{refresh:!0,background:!0})}catch(V){d.current===g&&(kt.current.length>0&&C(!0),z(V instanceof Error?V.message:"目录加载失败"))}finally{d.current===g&&se.current.get(g)===U&&E(!1)}}async function Ce(g,_={}){var me;const U=window.agentApi;if(!U)return;const V=d.current,K=`${V}:${g}`,Re=(q.current.get(K)??0)+1;q.current.set(K,Re),st(Le=>{const Fe=new Set(Le).add(g);return Vt.current=Fe,Fe}),$e(Le=>{if(!(g in Le))return Le;const Fe={...Le};return delete Fe[g],Fe});try{const Le=await U.listAgentWorkspaceSessions(V,g,{cursor:_.cursor,limit:20,refresh:_.refresh});if(d.current!==V||q.current.get(K)!==Re)return;const Fe=ye.current[g]??[],tn=_.pendingSession?{..._.pendingSession,projectId:g}:void 0,Fn=tn?[tn,...Fe.filter(tt=>tt.id!==tn.id)]:Fe,_e=new Set(Fn.map(tt=>tt.id)),Et=[...Fn,...[..._e].flatMap(tt=>we.current[tt]??[])],In=_.refresh&&!_.cursor?await f1(Et,Le,tt=>U.listAgentWorkspaceSessions(V,g,{cursor:tt,limit:200,refresh:!1}),tn==null?void 0:tn.id):Le;if(d.current!==V||q.current.get(K)!==Re)return;const St=uu(Et,In,!_.cursor).map(tt=>({...tt,projectId:tt.projectId??g})),Rn=na(St.filter(tt=>!tt.parentSessionId),V),Wr=et.current,ir=Ge.current,ts=h1(Rn,tn);Wr===g&&ir&&!St.some(tt=>tt.id===ir)&&!ts.some(tt=>tt.id===ir)&&hn(Po);const Kn={};for(const tt of St.filter(ft=>ft.parentSessionId))(Kn[me=tt.parentSessionId]??(Kn[me]=[])).push(tt);for(const tt of Object.values(Kn))tt.sort((ft,ns)=>ft.created.localeCompare(ns.created));Y(tt=>({...tt,[g]:In.nextCursor})),ct(tt=>{const ft=new Set(tt);return In.stale?ft.add(g):ft.delete(g),ft});const Fr={...ye.current,[g]:ts},kr={...we.current};for(const tt of _e)delete kr[tt];for(const[tt,ft]of Object.entries(Kn))kr[tt]=ft;ye.current=Fr,we.current=kr,T(Fr),pe(kr),dt(tt=>{const ft=new Set(tt).add(g);return fn.current=ft,ft})}catch(Le){if(q.current.get(K)!==Re)return;ct(Fe=>new Set(Fe).add(g)),$e(Fe=>({...Fe,[g]:Le instanceof Error?Le.message:"会话加载失败"}))}finally{q.current.get(K)===Re&&st(Le=>{const Fe=new Set(Le);return Fe.delete(g),Vt.current=Fe,Fe})}}const Jr=async g=>{if(!window.agentApi)return;const _=await window.agentApi.listChildSessions(g);pe(U=>({...U,[g]:_.sort((V,K)=>V.created<K.created?-1:1)}))},vr=async(g,_)=>{if(!window.agentApi)return;const U=kt.current.find(V=>V.id===g);if(!U||U.canCreateSession===!1){Je("请先选择目录"),Lt("info"),setTimeout(()=>Je(null),3e3);return}if(!W.current){W.current=!0,Ye({projectId:g,agentType:_});try{const V=(U==null?void 0:U.source)==="imported"?void 0:g,K=await window.agentApi.createSession("新会话",V,_,U==null?void 0:U.description);if(d.current!==_)return;const Re=K.projectId===g?K:{...K,projectId:g},me={...ye.current,[g]:[Re,...(ye.current[g]??[]).filter(Le=>Le.id!==K.id)]};ye.current=me,T(me),hn({projectId:g,sessionId:K.id}),Q&&ze(!1),_==="customer-agent"&&Ce(g,{refresh:!0,background:!0,pendingSession:Re})}catch(V){Je(V instanceof Error?V.message:"新建会话失败"),Lt("error"),setTimeout(()=>Je(null),3e3)}finally{W.current=!1,Ye(null)}}},xs=()=>{const g=kt.current.find(_=>_.id===ee);if(!ee||(g==null?void 0:g.canCreateSession)===!1){Je("请先选择目录"),Lt("info"),setTimeout(()=>Je(null),3e3);return}vr(ee,o)};a.useEffect(()=>{var g;window.agentApi&&(Gn(d.current,{refresh:(((g=i.current.agents[d.current])==null?void 0:g.workspaces.length)??0)>0}),qi.getState().loadFromSystem(),window.agentApi.getRuntimeHealth().then(G).catch(()=>{}))},[]),a.useEffect(()=>{const g=window.setInterval(()=>{document.visibilityState!=="visible"||j||Gn(o,{refresh:!0,since:x,refreshLoadedSessions:!1})},15e3);return()=>window.clearInterval(g)},[o,j,x]),a.useEffect(()=>{if(!window.agentApi)return;let g=!1;const _=()=>{if(g||document.visibilityState!=="visible")return;const K=j1(ee,Pt),Re=S1(K,Tn.current,Vt.current);for(const me of Re)Ce(me,{refresh:!0,background:fn.current.has(me)})},U=()=>{document.visibilityState==="visible"&&_()},V=window.setInterval(_,1e4);return window.addEventListener("focus",_),document.addEventListener("visibilitychange",U),()=>{g=!0,window.clearInterval(V),window.removeEventListener("focus",_),document.removeEventListener("visibilitychange",U)}},[o,Pt,ee]),a.useEffect(()=>{if(!ee||!window.agentApi)return;const g=u.find(U=>U.id===ee),_=g==null?void 0:g.description;_&&window.agentApi.setProjectWorkingDir(_)},[ee,u]);const Ds=g=>{hn(wc(g));const _=!Pt.has(g);if(ht(U=>{const V=new Set(U);return _?V.add(g):V.delete(g),V}),_&&!Vt.current.has(g)){const U=fn.current.has(g),V=kt.current.find(Re=>Re.id===g),K=Hc(d.current,V,U);Ce(g,{refresh:K,background:U})}},Ws=async g=>{if(!window.agentApi)throw new Error("agentApi 未就绪,请重启应用");const _=g.replace(/\\/g,"/"),U=_.split("/").filter(Boolean),V=U[U.length-1]||_||"导入的项目",K=await window.agentApi.importAgentWorkspace(d.current,_,V);await Gn(d.current,{refresh:!0,refreshLoadedSessions:!1}),hn(wc(K.workspace.workspaceId)),await Ce(K.workspace.workspaceId,{refresh:!0}),ht(Re=>{const me=new Set(Re);return me.add(K.workspace.workspaceId),me}),Je(K.existing?"该文件夹已在当前 Agent 的目录中":`已导入:${K.workspace.name}`),Lt(K.existing?"info":"success"),setTimeout(()=>Je(null),3e3)},Xi=async()=>{try{if(!window.agentApi){Je("agentApi 未就绪,请重启应用"),Lt("error");return}if(Ft){H(!0);return}const g=await window.agentApi.openFileDialog();if(console.log("[import] selectedPath:",g),!g)return;await Ws(g)}catch(g){console.error("[import] error:",g),Je(g instanceof Error?g.message:String(g)),Lt("error"),setTimeout(()=>Je(null),5e3)}},hi=async g=>{if(window.agentApi)try{await window.agentApi.deleteProject(g),ee===g&&(Ve(null),nn(null),Jt([])),Je("项目删除成功"),Lt("success"),setTimeout(()=>Je(null),2500),await Gn()}catch(_){Je(_ instanceof Error?_.message:"项目删除失败"),Lt("error"),setTimeout(()=>Je(null),4e3)}},Fs=(g,_,U)=>{var Re;const V=(Re=window.agentApi)==null?void 0:Re.showDirectoryContextMenu,K=b1(_,{isInvalid:U,supported:typeof V=="function",webShell:Ft});!K||!V||(g.preventDefault(),V(K).catch(me=>{Je(me instanceof Error?me.message:"无法打开当前文件夹"),Lt("error"),setTimeout(()=>Je(null),4e3)}))},pr=(g,_)=>{ke({session:g,anchor:_})},gn=(g,_)=>{const U=_.getBoundingClientRect();at({project:g,anchor:{top:U.top,left:U.left,width:U.width,height:U.height}})},Bs=async()=>{if(!window.agentApi||!We||qe)return;const{project:g}=We,_=d.current;ne(!0);try{let U=null,V=0;do{const K=await window.agentApi.listAgentWorkspaceSessions(_,g.id,{cursor:U,limit:50,refresh:U===null});for(const Re of K.data)await window.agentApi.deleteSession(Re.id),V+=1;U=K.data.length>0?K.nextCursor:null}while(U);et.current===g.id&&hn(Po),Je(V>0?`已删除目录「${g.name}」及 ${V} 个会话`:`已删除目录「${g.name}」`),Lt("success"),setTimeout(()=>Je(null),2500),await Gn(_,{refresh:!0})}catch(U){Je(U instanceof Error?U.message:"目录删除失败"),Lt("error"),setTimeout(()=>Je(null),4e3)}finally{ne(!1),at(null)}},bs=async()=>{if(!window.agentApi||!ae||Pe)return;const{session:g}=ae;Ie(!0);try{await window.agentApi.deleteSession(g.id);const _=g.projectId??et.current,U=g.agentType;if(_){const Re=`${U}:${_}`;q.current.set(Re,(q.current.get(Re)??0)+1)}const V=Xm(ye.current,we.current,[],g.id);ye.current=V.sessionsByProject,we.current=V.childSessionsByParent,T(V.sessionsByProject),pe(V.childSessionsByParent),ar(V.removedIds);const K=i.current.agents[U];if(K){const Re={...i.current,agents:{...i.current.agents,[U]:Km(K,V.removedIds)}};i.current=Re,Oc(Re)}Ge.current&&V.removedIds.includes(Ge.current)&&hn({projectId:et.current,sessionId:null}),Je("会话删除成功"),Lt("success"),setTimeout(()=>Je(null),2500),ke(null),_&&Ce(_,{refresh:!0,background:!0})}catch(_){Je(_ instanceof Error?_.message:"会话删除失败"),Lt("error"),setTimeout(()=>Je(null),4e3)}finally{Ie(!1)}},Yi=[{id:"settings",label:"设置"},{id:"mcp",label:"MCP"},{id:"memory",label:"记忆"},{id:"skill",label:"技能"},{id:"agent",label:"智能体"},{id:"lsp",label:"LSP"}],Dr=(g,_)=>{const U=ut===g.id,V=zo(it(g,_)),K=le[g.id]??[],Re=!Gt.has(g.id);return e.jsxs("div",{className:"sidebar-session-tree",children:[e.jsx(Ho,{session:{id:g.id,title:g.title,visualState:V,statusLabel:Lo[V],occupiedExternally:g.agentType!=="codex"&&g.occupancy==="owned-externally",canDelete:g.canDelete,active:U,hasChildren:K.length>0,expanded:Re,compatibility:g.compatibility,pinned:jn.has(g.id)},onSelect:()=>{Q&&ze(!1),hn(Do(_,g.id)),K.length>0&&rt(me=>{const Le=new Set(me);return Le.has(g.id)?Le.delete(g.id):Le.add(g.id),Le})},onPin:()=>un(g.id),onDelete:me=>pr(g,me)}),e.jsx("div",{className:"sidebar-child-sessions",style:{maxHeight:Re?K.length*40:0,opacity:Re?1:0},children:K.map(me=>{const Le=zo(it(me,_));return e.jsx(Ho,{session:{id:me.id,title:me.title,visualState:Le,statusLabel:Lo[Le],occupiedExternally:me.agentType!=="codex"&&me.occupancy==="owned-externally",canDelete:me.canDelete,active:ut===me.id,child:!0,compatibility:me.compatibility},deleteLabel:"删除子会话",onSelect:()=>{Q&&ze(!1),hn(Do(_,me.id))},onDelete:Fe=>pr(me,Fe)},me.id)})})]},g.id)};return e.jsxs("div",{className:"app-shell",style:{display:"flex",height:Ft?"100dvh":"100vh",width:"100vw",background:"var(--bg-deepest)",position:"relative",overflow:"hidden"},children:[e.jsx(Hm,{}),e.jsx(Um,{}),!Ln&&Q&&fe&&e.jsx("div",{className:"mobile-drawer-scrim",onClick:()=>ze(!1),style:{position:"fixed",inset:0,background:"rgba(0,0,0,.45)",zIndex:1150}}),!Ln&&Q&&!fe&&e.jsx("button",{className:"mobile-drawer-toggle",onClick:()=>ze(!0),"aria-label":"会话列表","aria-expanded":!1,style:{position:"fixed",top:"calc(env(safe-area-inset-top) + 8px)",left:10,zIndex:1250,width:34,height:34,borderRadius:9,border:"1px solid var(--border-default)",background:"var(--bg-glass, rgba(18,20,28,.82))",color:"var(--text-secondary)",display:"grid",placeItems:"center",backdropFilter:"blur(8px)",WebkitAppRegion:"no-drag",cursor:"pointer"},children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:e.jsx("path",{d:"M3 6h18M3 12h18M3 18h18"})})}),e.jsx("div",{className:"app-drag-region",style:{position:"fixed",top:0,left:0,right:0,height:52,zIndex:9999,WebkitAppRegion:"drag",pointerEvents:"none"}}),e.jsx("div",{className:"app-accent-glow",style:{position:"absolute",top:"-120px",left:"-80px",width:320,height:320,borderRadius:"50%",background:"radial-gradient(circle, var(--accent-glow) 0%, transparent 70%)",pointerEvents:"none",zIndex:0}}),Rt!=="focus"&&!Ln&&e.jsxs(e.Fragment,{children:[e.jsxs("aside",{className:"app-sidebar",style:{width:ce,display:"flex",flexDirection:"column",background:"var(--bg-surface)",borderRight:"1px solid var(--border-subtle)",padding:"56px 0 0",position:"relative",zIndex:10,overflow:"hidden",...Q?{position:"fixed",top:0,bottom:0,left:0,width:"min(82vw, 320px)",zIndex:1200,transform:fe?"translateX(0)":"translateX(-103%)",transition:"transform .24s ease",boxShadow:"12px 0 32px rgba(0,0,0,.5)",padding:"calc(env(safe-area-inset-top) + 12px) 0 0"}:{}},children:[e.jsx("div",{className:"app-sidebar-brand",style:{padding:"0 20px 10px"},children:e.jsxs("div",{className:"sidebar-brand-row",children:[e.jsx("div",{className:"sidebar-brand-mark","aria-hidden":"true",children:e.jsx(pa,{agentType:"customer-agent",size:24})}),e.jsx("span",{className:"sidebar-brand-name",children:"AgentRoam"}),!Ft&&e.jsx(kx,{onOpenFlowStudio:pi,openingFlowStudio:sr})]})}),e.jsx(wx,{value:o,health:te,onChange:fi}),e.jsxs("button",{type:"button",className:"sidebar-search-field",onClick:()=>{F(!0),Ke(10)},title:"搜索会话","aria-label":"搜索会话",children:[e.jsx(ua,{size:15,"aria-hidden":"true"}),e.jsx("span",{children:"搜索会话"}),e.jsx("kbd",{children:"⌘ K"})]}),e.jsxs("div",{className:"sidebar-project-toolbar",children:[e.jsxs("div",{className:"sidebar-project-heading",children:[e.jsx("span",{className:"sidebar-project-title",children:"目录"}),e.jsx("span",{className:"sidebar-project-count","aria-label":`${u.length} 个目录`,children:u.length})]}),e.jsxs("div",{className:"sidebar-project-actions",children:[e.jsx("button",{type:"button",onClick:g=>{re?Wn():er(),qc(g,re)},title:re?"展开全部会话":"折叠全部会话","aria-label":re?"展开全部会话":"折叠全部会话","aria-pressed":re,disabled:N.length===0,className:`ui-icon-button sidebar-collapse-all${re?" is-active":""}`,children:e.jsx("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:re?e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"m7 6 5 5 5-5"}),e.jsx("path",{d:"m7 13 5 5 5-5"})]}):e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"m17 11-5-5-5 5"}),e.jsx("path",{d:"m17 18-5-5-5 5"})]})})}),e.jsx("button",{type:"button",onClick:g=>{Zn(!en),qc(g,en)},title:en?"按新建时间排序":"进行中会话优先","aria-label":en?"按新建时间排序":"进行中会话优先","aria-pressed":en,className:`ui-icon-button sidebar-session-sort${en?" is-active":""}`,children:e.jsxs("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M3 6h10M3 12h7M3 18h4"}),e.jsx("path",{d:"m15 9 3-3 3 3M18 6v12"})]})}),e.jsx("button",{type:"button",onClick:()=>void Xi(),title:"导入目录","aria-label":"导入目录",className:"ui-icon-button",children:e.jsx("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})})]})]}),e.jsx("div",{ref:Nn,className:"app-sidebar-scroll",onPointerDownCapture:C1,onScroll:g=>{const _=g.currentTarget;if(_.scrollHeight-_.scrollTop-_.clientHeight<120&&p&&!j&&Gn(o,{cursor:p}),Q){const V=_.getBoundingClientRect(),K=_.querySelectorAll("[data-sidebar-project-id]");for(const Re of K){const me=Re.dataset.sidebarProjectId;if(!me||!Pt.has(me))continue;const Le=Re.getBoundingClientRect();if(Le.bottom<V.top||Le.bottom>V.bottom+120)continue;const Fe=B[me];Fe&&!Vt.current.has(me)&&Ce(me,{cursor:Fe})}}},style:{minHeight:0,flex:1,overflow:"auto",padding:"0 10px"},children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,marginBottom:12},children:[br.length>0&&e.jsxs("section",{className:"sidebar-pinned-section","aria-label":"置顶会话",children:[e.jsx("div",{className:"sidebar-pinned-heading",children:"置顶"}),br.map(({projectId:g,session:_})=>Dr(_,g))]}),D.map(g=>{var In;const _=ee===g.id&&ut===null,U=Pt.has(g.id),V=Te.has(g.id),K=lt.has(g.id),Re=Tt[g.id],me=L[g.id]??[],Le=me.filter(St=>!jn.has(St.id)),tn=en?vc(Le,Ht):Le,Fn=tn.length>10,_e=_t.has(g.id),Et=(be==null?void 0:be.agentType)===o&&be.projectId===g.id;return e.jsxs("div",{className:"sidebar-project-block","data-sidebar-project-id":g.id,"aria-busy":K,children:[e.jsxs("div",{className:`sidebar-row sidebar-project-row ${_&&!_e?"sidebar-row-active":""}`,onContextMenu:St=>Fs(St,g,_e),style:{paddingRight:4,opacity:_e?.45:1},children:[e.jsxs("button",{className:"sidebar-project-button",onClick:()=>{_e||Ds(g.id)},disabled:_e,"aria-expanded":U,"aria-pressed":_,title:_e?`路径不存在:${g.description}`:g.name,style:{flex:1,display:"flex",alignItems:"center",gap:8,minWidth:0,padding:"8px 10px",border:"none",background:"transparent",color:_e?"var(--text-muted)":_?"var(--accent)":"var(--text-secondary)",fontSize:13,fontWeight:_&&!_e?600:400,cursor:_e?"not-allowed":"pointer",textAlign:"left",transition:"color 0.15s"},children:[_e?e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.6},children:[e.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),e.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}):g.canCreateSession===!1?e.jsx(pp,{size:13,"aria-hidden":"true",style:{flexShrink:0,opacity:_?1:.5}}):e.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:_?1:.5},children:U?e.jsx("path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6A2 2 0 0 1 18.46 20H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}):e.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})}),e.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:g.name})]}),o==="customer-agent"&&!Ft&&g.canCreateSession!==!1?e.jsx("button",{onClick:St=>{St.stopPropagation(),hi(g.id)},title:"删除目录","aria-label":`删除目录:${g.name}`,className:"sidebar-project-delete sidebar-row-action ui-icon-button ui-icon-button--small ui-icon-button--danger",style:{flexShrink:0},children:e.jsx(Uc,{})}):_e?e.jsx("button",{onClick:St=>{St.stopPropagation(),gn(g,St.currentTarget)},title:"删除失效目录","aria-label":`删除失效目录:${g.name}`,className:"sidebar-project-delete sidebar-row-action ui-icon-button ui-icon-button--small ui-icon-button--danger",style:{flexShrink:0},children:e.jsx(Uc,{})}):null,g.canCreateSession!==!1&&e.jsx("button",{type:"button",onClick:St=>{St.stopPropagation(),vr(g.id,o)},title:Et?"正在创建会话":`新建 ${o==="customer-agent"?"Customer Agent":o==="claude-code"?"Claude Code":o==="codex"?"Codex":"OpenCode"} 会话`,"aria-label":Et?"正在创建会话":`在 ${g.name} 中新建会话`,"aria-busy":Et,disabled:be!==null||_e||((In=te.find(St=>St.agentType===o))==null?void 0:In.available)===!1,className:"sidebar-runtime-create sidebar-project-add-action ui-icon-button ui-icon-button--small",children:Et?e.jsx(ot,{size:13,style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true"}):e.jsx(Ko,{size:13,"aria-hidden":"true"})})]}),e.jsx("div",{style:{overflow:"hidden",maxHeight:U?Q?1e5:Fn?300:800:0,opacity:U?1:0,transition:"max-height 0.45s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease"},children:e.jsxs("div",{className:"sidebar-project-sessions",onScroll:St=>{const Rn=St.currentTarget,Wr=Rn.scrollHeight-Rn.scrollTop-Rn.clientHeight<80,ir=B[g.id];Wr&&ir&&!K&&Ce(g.id,{cursor:ir})},style:{display:"flex",flexDirection:"column",gap:1,marginTop:2,paddingLeft:10,paddingBottom:4,...Fn&&!Q?{maxHeight:280,overflowY:"auto"}:{}},children:[tn.map(St=>Dr(St,g.id)),K&&!V&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:11,padding:"4px 10px",opacity:.7},children:"正在加载会话..."}),Re&&e.jsxs("div",{title:Re,style:{display:"flex",alignItems:"center",gap:8,color:"var(--danger)",fontSize:11,padding:"4px 10px"},children:[e.jsx("span",{style:{flex:1},children:"会话加载失败"}),e.jsx("button",{type:"button",onClick:()=>void Ce(g.id,{refresh:V,background:V}),style:{border:0,background:"transparent",color:"inherit",fontSize:11,cursor:"pointer",padding:0},children:"重试"})]}),Nt.has(g.id)&&!Re&&e.jsx("div",{className:"sidebar-cache-state",children:"显示缓存,会话将在下次刷新时更新"}),me.length===0&&V&&!K&&!Re&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:11,padding:"4px 10px",opacity:.7},children:"暂无会话"})]})})]},g.id)}),u.length===0&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:12,padding:"24px 10px",textAlign:"center",opacity:.7},children:j?"正在加载目录...":"暂无目录"}),u.length>0&&j&&e.jsx("div",{className:"sidebar-cache-state",children:"正在同步目录..."}),S&&!k&&e.jsx("div",{className:"sidebar-cache-state",children:"当前显示缓存目录"}),k&&e.jsxs("div",{className:"sidebar-load-error",title:k,children:[e.jsx("span",{children:u.length>0?"目录刷新失败,当前显示缓存":"目录加载失败"}),e.jsx("button",{type:"button",onClick:()=>void Gn(o,{refresh:u.length>0}),children:"重试"})]})]})}),e.jsx("div",{className:"sidebar-bottom-action",children:e.jsx("button",{type:"button",className:"sidebar-new-session-primary",disabled:be!==null||ee!==null&&_t.has(ee)||((Os=te.find(g=>g.agentType===o))==null?void 0:Os.available)===!1,"aria-busy":be!==null,"aria-disabled":be!==null||!ee||((wr=u.find(g=>g.id===ee))==null?void 0:wr.canCreateSession)===!1,title:be?"正在创建会话":ee&&((Zr=u.find(g=>g.id===ee))==null?void 0:Zr.canCreateSession)!==!1?"新建会话":"请先选择目录",onClick:xs,children:be?e.jsxs(e.Fragment,{children:[e.jsx(ot,{size:16,style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true"}),e.jsx("span",{children:"正在创建..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ko,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:"新建会话"})]})})})]}),ae&&e.jsx(Tc,{message:Gm(ae.session),anchor:ae.anchor,mobile:Q,pending:Pe,onCancel:()=>ke(null),onConfirm:()=>void bs()}),We&&e.jsx(Tc,{title:"删除失效目录",message:`目录「${We.project.name}」的路径(${We.project.description||"未知"})已不存在。删除将同时归档其下的全部会话记录,确定删除吗?`,anchor:We.anchor,mobile:Q,pending:qe,onCancel:()=>at(null),onConfirm:()=>void Bs()}),!Q&&e.jsx("div",{className:`app-sidebar-resizer${De?" is-dragging":""}`,onMouseDown:zn,style:{left:ce}}),$&&e.jsx("div",{onClick:()=>F(!1),style:{position:"fixed",inset:0,zIndex:1300,background:"rgba(17,24,39,0.34)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",display:"flex",alignItems:"flex-start",justifyContent:"center",padding:"12vh 16px 16px"},children:e.jsxs("div",{onClick:g=>g.stopPropagation(),style:{width:"min(560px, 100%)",maxHeight:"64vh",display:"flex",flexDirection:"column",borderRadius:12,border:"1px solid var(--border-default)",background:"var(--bg-surface)",boxShadow:"0 18px 48px rgba(17,24,39,0.28)",overflow:"hidden"},children:[e.jsx("div",{style:{padding:10,borderBottom:"1px solid var(--border-subtle)"},children:e.jsx("input",{autoFocus:!0,value:A,onChange:g=>R(g.target.value),onKeyDown:g=>{g.key==="Escape"&&F(!1)},placeholder:"搜索所有会话(标题或目录)…","aria-label":"搜索所有会话",style:{width:"100%",padding:"9px 12px",borderRadius:8,border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:14,outline:"none",fontFamily:"var(--font-body)",boxSizing:"border-box"}})}),e.jsxs("div",{style:{overflowY:"auto",padding:8},children:[rr&&ur&&ur.length>0&&e.jsxs("div",{style:{padding:"4px 10px 3px",fontSize:9,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",color:"var(--text-muted)"},children:[ur.length," 个结果"]}),rr&&ur&&ur.length===0&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:12,padding:"16px 10px",textAlign:"center",opacity:.7},children:"无匹配会话"}),!rr&&dr.length===0&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:12,padding:"16px 10px",textAlign:"center",opacity:.7},children:"暂无会话"}),(ur??dr.slice(0,Ee)).map(g=>{const _=ut===g.id,U=zo(it(g));return e.jsx(Ho,{session:{id:g.id,title:g.title,visualState:U,statusLabel:Lo[U],occupiedExternally:g.agentType!=="codex"&&g.occupancy==="owned-externally",canDelete:g.canDelete,active:_,child:!!g.parentSessionId,compatibility:g.compatibility,pinned:jn.has(g.id)},onSelect:()=>{const V=g.projectId&&u.some(K=>K.id===g.projectId)?g.projectId:null;hn(Do(V,g.id)),F(!1),Q&&ze(!1)},onPin:g.parentSessionId?void 0:()=>un(g.id),onDelete:V=>pr(g,V)},g.id)}),!rr&&dr.length>Ee&&e.jsx("button",{type:"button",onClick:()=>Ke(g=>g+10),style:{width:"100%",padding:"8px 10px",border:0,borderTop:"1px solid var(--border-subtle)",background:"transparent",color:"var(--text-muted)",fontSize:12,cursor:"pointer",textAlign:"center"},children:"更多…"})]})]})})]}),e.jsx(nu,{message:yr,type:zr}),e.jsxs("main",{className:`app-main${Bt?" file-workspace-capable":""}${ge&&Bt?" file-workspace-open":""}${ge&&Bt&&Sn?" file-workspace-preview-open":""}`,style:{flex:1,overflow:"hidden",background:"var(--bg-workspace)",position:"relative",zIndex:5},children:[Rt==="focus"&&!Ln&&e.jsx("button",{onClick:()=>wn("standard"),title:"返回标准布局",style:{position:"absolute",top:12,left:12,zIndex:100,padding:"5px 10px",borderRadius:8,border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-muted)",fontSize:11,cursor:"pointer",backdropFilter:"blur(8px)",WebkitAppRegion:"no-drag"},children:"← 侧边栏"}),e.jsx("div",{className:"app-chat-surface",style:{height:"100%",paddingTop:0,display:$n?"none":void 0,background:"var(--chat-history-bg)"},children:e.jsx(Im,{activeAgentType:o,selectedProjectId:ee,selectedSessionId:ut,sessionTitle:Qt,sessionSummary:Kt,workspacePath:b,voiceCommand:gs,onOpenSettings:xr,settingsOpen:vn,desktopLiveOpen:Dt,fileDrawerOpen:ge,onOpenArtifact:sn,onToggleFiles:Bt?()=>{Ut(g=>!g),pt("files")}:void 0,onOpenDesktopLive:!Ft&&((es=window.agentApi)!=null&&es.desktopLiveGetStatus)?()=>Xn(!0):void 0,onHideToBackground:()=>void Nr(),onOpenHub:($s=window.agentApi)!=null&&$s.hubGetConfig?()=>cn(!0):void 0,onToggleAppearance:Ot,appearanceOpen:tr,hideToBackgroundTitle:gt?`隐藏到后台(说“${Wt}”唤醒)`:"隐藏到后台",onSessionCreated:async(g,_)=>{var V;const U=et.current;hn({projectId:U,sessionId:g}),xt.current&&(xt.current=!1,An.current={sessionId:g,until:Date.now()+9e4},(V=window.agentApi)==null||V.wakeConversation(!0)),U&&await Ce(U,{pendingSession:_})},onSubSessionCreated:async g=>{await Jr(g)},onSelectSession:g=>{nn(g)},onSubAgentEvent:g=>{g.type==="started"?an({type:"info",title:"子会话已启动",body:`${g.agentName}:${g.task.slice(0,60)}`,sessionId:g.subSessionId}):g.type==="completed"?an({type:"success",title:"子会话已完成",body:`${g.agentName}:${g.task.slice(0,60)}`,sessionId:g.subSessionId}):an({type:"error",title:"子会话出错",body:`${g.agentName}:${g.task.slice(0,60)}`,sessionId:g.subSessionId})},onMessageSent:(g,_)=>{T(U=>{const V={};for(const[K,Re]of Object.entries(U))V[K]=Re.map(me=>me.id===g?{...me,title:_.slice(0,60)||me.title}:me);return V})},onRunComplete:async(g,_)=>{var Re;const U=An.current,V=Jg(U,_);An.current=V,V!==U&&((Re=window.agentApi)==null||Re.wakeConversation(!0));const K=g||ee;K&&await Ce(K,{refresh:!0,background:!0})}})}),$n&&e.jsx(Fm,{conversationId:ut,onExit:()=>cn(!1)}),Bt&&e.jsx(c1,{open:ge,tab:rn,gateway:Bt,cwd:b,selectedPath:Sn,revealRequest:hs,onTabChange:pt,onSelectPath:hr,onClose:()=>Ut(!1)}),Ln&&e.jsx(jx,{entryUrl:Ln,onBack:()=>Lr(null)})]}),Dt&&e.jsx(cx,{onClose:()=>Xn(!1)}),vn&&On.createPortal(e.jsx("div",{onClick:()=>He(!1),style:{position:"fixed",inset:0,zIndex:10001,background:"rgba(17,24,39,0.18)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.2s var(--ease-out)",WebkitAppRegion:"no-drag"},children:e.jsxs("div",{onClick:g=>g.stopPropagation(),style:{width:"min(920px, calc(100vw - 48px))",height:"min(760px, calc(100vh - 48px))",background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",backdropFilter:"blur(14px)",WebkitBackdropFilter:"blur(14px)",boxShadow:"var(--shadow-md)",overflow:"hidden",display:"flex",flexDirection:"column",animation:"fadeInUp 0.25s var(--ease-out)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:"1px solid var(--border-subtle)",padding:"8px 10px",background:"var(--bg-deepest)"},children:[e.jsx("div",{style:{display:"flex",gap:6},children:Yi.map(g=>e.jsx("button",{onClick:()=>dn(g.id),className:`settings-tab ${X===g.id?"settings-tab-active":""}`,children:g.label},g.id))}),e.jsx("button",{onClick:()=>He(!1),title:"关闭",className:"ui-icon-button ui-icon-button--close ui-icon-button--danger",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:e.jsx("path",{d:"M18 6 6 18M6 6l12 12"})})})]}),e.jsxs("div",{style:{flex:1,overflow:"auto"},children:[X==="settings"&&e.jsx(sx,{}),X==="mcp"&&e.jsx(dx,{}),X==="memory"&&e.jsx(ux,{}),X==="skill"&&e.jsx(fx,{}),X==="agent"&&e.jsx(mx,{}),X==="lsp"&&e.jsx(bx,{})]})]})}),document.body),e.jsx("div",{className:"noise-overlay"}),tr&&qt&&On.createPortal(e.jsx("div",{onClick:()=>gr(!1),style:{position:"fixed",inset:0,zIndex:1e4,WebkitAppRegion:"no-drag"},children:e.jsxs("div",{onClick:g=>g.stopPropagation(),className:"appearance-panel",style:{position:"absolute",left:Math.max(12,Math.min(qt.right-320,window.innerWidth-332)),top:qt.bottom+8,width:320,maxHeight:`calc(100vh - ${qt.bottom+20}px)`,overflowY:"auto",background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-md)",padding:"16px",display:"flex",flexDirection:"column",gap:16,animation:"fadeInUp 0.2s var(--ease-out)",backdropFilter:"blur(14px)",WebkitBackdropFilter:"blur(14px)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8},children:"皮肤"}),e.jsx("div",{className:"appearance-choices",children:Yu.map(g=>e.jsxs("button",{onClick:()=>mt(g.id),className:`appearance-choice ${wt===g.id?"appearance-choice-active":""}`,children:[e.jsx("span",{className:"appearance-swatch",style:{background:`linear-gradient(135deg, ${g.preview[0]} 55%, ${g.preview[1]} 55%)`}}),e.jsx("span",{className:"appearance-choice-label",style:{fontWeight:wt===g.id?600:400},children:g.label}),wt===g.id&&e.jsx("svg",{className:"appearance-choice-check",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"m5 12 4 4L19 6"})})]},g.id))})]}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8},children:"布局"}),e.jsx("div",{className:"appearance-segmented",children:Ju.map(g=>e.jsx("button",{onClick:()=>wn(g.id),title:g.description,className:`appearance-segment ${Rt===g.id?"appearance-segment-active":""}`,children:g.label},g.id))})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,borderTop:"1px solid var(--border-subtle)",paddingTop:12},children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.08em"},children:"语音"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:12,color:"var(--text-secondary)",cursor:"pointer"},children:["助手回复自动播报",e.jsx("input",{className:"appearance-switch",type:"checkbox",checked:Zt,onChange:g=>Hn(g.target.checked)})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:12,color:"var(--text-secondary)",cursor:"pointer"},children:["隐藏后语音唤醒",e.jsx("input",{className:"appearance-switch",type:"checkbox",checked:gt,onChange:g=>Yn(g.target.checked)})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-secondary)"},children:[e.jsx("span",{style:{flexShrink:0},children:"唤醒词"}),e.jsx("input",{value:Wt,onChange:g=>Jn(g.target.value||"小智"),style:{flex:1,padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--bg-deep)",color:"var(--text-primary)",fontSize:12}})]})]})]})}),document.body),e.jsx(Ax,{open:M,onCancel:()=>H(!1),onConfirm:async g=>{await Ws(g),H(!1)}}),e.jsx(yx,{trigger:Yr,heardText:cr}),Ps.length>0&&On.createPortal(e.jsx("div",{style:{position:"fixed",bottom:24,right:24,zIndex:2e4,display:"flex",flexDirection:"column",gap:10,alignItems:"flex-end",pointerEvents:"none"},children:Ps.map(g=>e.jsxs("div",{style:{pointerEvents:"auto",width:320,background:"var(--bg-surface)",border:`1px solid ${g.type==="error"?"rgba(220,38,38,0.25)":g.type==="success"?"rgba(5,150,105,0.25)":"var(--border-default)"}`,borderLeft:`3px solid ${g.type==="error"?"var(--danger)":g.type==="success"?"var(--success)":"var(--accent)"}`,borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-md)",padding:"12px 14px",animation:"fadeInUp 0.22s var(--ease-out)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[e.jsxs("span",{style:{fontSize:12,fontWeight:600,color:g.type==="error"?"var(--danger)":g.type==="success"?"var(--success)":"var(--accent)",display:"flex",alignItems:"center",gap:5},children:[g.type==="error"?"✕":g.type==="success"?"✓":"◎"," ",g.title]}),e.jsx("button",{onClick:()=>Pr(g.id),title:"关闭",style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:14,lineHeight:1,padding:"2px 4px",borderRadius:4,transition:"color 0.15s"},onMouseEnter:_=>_.currentTarget.style.color="var(--text-primary)",onMouseLeave:_=>_.currentTarget.style.color="var(--text-muted)",children:"×"})]}),e.jsx("p",{style:{margin:0,fontSize:12,color:"var(--text-secondary)",lineHeight:1.5,wordBreak:"break-all"},children:g.body}),g.sessionId&&e.jsx("button",{onClick:()=>{nn(g.sessionId),Pr(g.id)},style:{marginTop:8,padding:"4px 10px",fontSize:11,fontWeight:500,background:"var(--accent-dim)",color:"var(--accent)",border:"1px solid var(--border-glow)",borderRadius:6,cursor:"pointer",transition:"background 0.15s",WebkitAppRegion:"no-drag"},onMouseEnter:_=>_.currentTarget.style.background="var(--accent-glow)",onMouseLeave:_=>_.currentTarget.style.background="var(--accent-dim)",children:"进入会话 →"})]},g.id))}),document.body)]})}const T1=Object.freeze(Object.defineProperty({__proto__:null,default:I1},Symbol.toStringTag,{value:"Module"}));export{T1 as A,_c as M,A1 as a,zx as c};
|
|
486
|
+
`)){const u=d.match(Tx);if(u){r=Number(u[1]),s=Number(u[2]),i=!0,n.push({kind:"hunk",text:d,oldLine:null,newLine:null});continue}if(!i){!d.startsWith("diff --git ")&&!d.startsWith("index ")&&!d.startsWith("--- ")&&!d.startsWith("+++ ")&&n.push({kind:"meta",text:d,oldLine:null,newLine:null});continue}d.startsWith("+")?(n.push({kind:"added",text:d.slice(1),oldLine:null,newLine:s}),s+=1,o+=1):d.startsWith("-")?(n.push({kind:"removed",text:d.slice(1),oldLine:r,newLine:null}),r+=1,l+=1):d.startsWith(" ")?(n.push({kind:"context",text:d.slice(1),oldLine:r,newLine:s}),r+=1,s+=1):n.push({kind:"note",text:d,oldLine:null,newLine:null})}return{rows:n,added:o,removed:l}}const _c=256*1024,A1=16*1024,_x={java:"java",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",ts:"typescript",tsx:"typescript",json:"json",py:"python",sh:"bash",bash:"bash",zsh:"bash",css:"css",scss:"scss",html:"xml",htm:"xml",xml:"xml",vue:"xml",svelte:"xml",astro:"xml",yml:"yaml",yaml:"yaml",toml:"ini",env:"ini",sql:"sql",c:"c",h:"c",cpp:"cpp",hpp:"cpp",go:"go",rs:"rust",kt:"kotlin",rb:"ruby",md:"markdown",markdown:"markdown",mdown:"markdown",mkdn:"markdown",mdx:"markdown",dockerfile:"dockerfile",gradle:"groovy",properties:"properties",graphql:"graphql",proto:"protobuf"};function zx(t){var s;const n=((s=t.split(/[/\\]/).pop())==null?void 0:s.toLowerCase())??"";if(n==="dockerfile"||n.startsWith("dockerfile."))return"dockerfile";if(n===".env"||n.startsWith(".env."))return"ini";if(n===".bashrc"||n===".zshrc")return"bash";const r=n.includes(".")?n.slice(n.lastIndexOf(".")+1):"";return _x[r]??null}function Lx({path:t,chunks:n,fileSize:r}){const[s,i]=a.useState(null),o=zx(t),l=n.length>0&&o!==null&&(r===void 0||r<=_c)&&n.reduce((u,f)=>u+f.length,0)<=_c;a.useEffect(()=>{if(!l)return;let u=!1;return Vc(async()=>{const{highlightCode:f}=await import("./codeSyntax-CEVVRDzr.js");return{highlightCode:f}},__vite__mapDeps([3,1,2]),import.meta.url).then(({highlightCode:f})=>{u||i(()=>f)}).catch(()=>{}),()=>{u=!0}},[l]);const d=a.useMemo(()=>l&&s?s(t,n.join("")):null,[n,l,s,t]);return d!==null?e.jsx("code",{className:"file-code-preview","data-language":o,dangerouslySetInnerHTML:{__html:d}}):e.jsx("code",{className:"file-code-preview",children:n.map((u,f)=>e.jsx("span",{children:u},f))})}const ou=new Set(["ts","tsx","js","jsx","mjs","cjs","json","md","markdown","mdown","mkdn","mdx","css","scss","html","htm","xml","yml","yaml","toml","sh","zsh","bash","py","rb","go","rs","java","kt","c","h","cpp","hpp","sql","env","gitignore","dockerfile","txt","log","conf","properties","gradle","lock","csv","vue","svelte","astro","graphql","prisma","proto"]),Px=new Set(["png","jpg","jpeg","gif","webp","bmp","ico","svg"]),Dx=new Set(["html","htm"]),Wx=new Set(["md","markdown","mdown","mkdn","mdx"]),Fx=new Set(ou),Bx="allow-scripts allow-popups allow-forms allow-modals",Ox=new Set(["mp4","webm","mov","m4v"]),$x=new Set(["mp3","wav","m4a","aac","ogg","flac"]),Hx=new Set(["pdf"]),Ux=8*1024*1024,qx=4096,Vx=512*1024,Gx=256*1024*1024,Kx={aac:"audio/aac",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",gif:"image/gif",html:"text/html",jpeg:"image/jpeg",jpg:"image/jpeg",json:"application/json",m4a:"audio/mp4",m4v:"video/mp4",md:"text/markdown",mov:"video/quicktime",mp3:"audio/mpeg",mp4:"video/mp4",ogg:"audio/ogg",pdf:"application/pdf",png:"image/png",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",svg:"image/svg+xml",tar:"application/x-tar",txt:"text/plain",wav:"audio/wav",webm:"video/webm",webp:"image/webp",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",zip:"application/zip"};function Qx(t,n){return n?!t.share||!t.canShare?"unsupported-browser":"ready":"insecure-context"}function Xx(t){var r;const n=((r=t.split(".").pop())==null?void 0:r.toLowerCase())??"";return Kx[n]??"application/octet-stream"}async function Yx(t,n){var r;if(!n.share||!((r=n.canShare)!=null&&r.call(n,{files:[t]})))return"unsupported";try{return await n.share({files:[t],title:t.name}),"shared"}catch(s){if(s&&typeof s=="object"&&"name"in s&&s.name==="AbortError")return"cancelled";throw s}}function Ca(t){return Uint8Array.from(atob(t),n=>n.charCodeAt(0))}function Jx(t,n,r){return t.decode(Ca(n),{stream:!r})}async function zc(t,n,r=()=>{},s=Vx){const i=await n("fs:stat",{path:t});if(i.dir)throw new Error("文件夹不能下载");if(i.size>Gx)throw new Error("文件超过 256M,请通过终端传输");const o=[];let l=0;do{const d=await n("fs:read",{path:t,offset:l,length:s},6e4),u=Ca(d.data);if(u.byteLength!==d.bytes)throw new Error("文件分块长度不一致,请重试");o.push(u.slice().buffer);const f=d.offset+d.bytes;if(!d.eof&&f<=l)throw new Error("文件下载未取得进展,请重试");if(l=f,r(i.size===0?100:Math.min(100,Math.round(l/i.size*100))),d.eof)break}while(l<i.size);return new Blob(o,{type:"application/octet-stream"})}function Zx(t){var r;const n=((r=t.split(".").pop())==null?void 0:r.toLowerCase())??"";return Dx.has(n)}function e1(t){var r;const n=((r=t.split(".").pop())==null?void 0:r.toLowerCase())??"";return Wx.has(n)}function Lc(t){var r;const n=((r=t.split(".").pop())==null?void 0:r.toLowerCase())??"";return Fx.has(n)}function t1(t){var r;const n=((r=t.split(".").pop())==null?void 0:r.toLowerCase())??"";return ou.has(n)||!t.includes(".")?"text":Px.has(n)?"image":Ox.has(n)?"video":$x.has(n)?"audio":Hx.has(n)?"pdf":"hex"}function n1({path:t,gateway:n,onClose:r}){const s=n.request,[i,o]=a.useState([]),[l,d]=a.useState(null),[u,f]=a.useState(""),[p,v]=a.useState(null),[x,w]=a.useState("initial-loading"),[j,E]=a.useState(!1),[S,C]=a.useState(0),[k,z]=a.useState(null),[M,H]=a.useState(null),[L,T]=a.useState(null),[A,R]=a.useState(null),[$,F]=a.useState(!1),[Ee,Qe]=a.useState(null),[ae,ke]=a.useState(null),[De,Ie]=a.useState(!1),[We,at]=a.useState(!0),[Ge,ne]=a.useState(null),[be,Ye]=a.useState("unavailable"),[W,te]=a.useState(!1),[G,le]=a.useState(null),[pe,ye]=a.useState("file"),[we,Te]=a.useState(!1),[ut,lt]=a.useState(!1),[st,Tt]=a.useState(!1),[He,Nt]=a.useState(!1),[ct,B]=a.useState(""),[Y,q]=a.useState(!1),[se,ee]=a.useState(null),[Ke,dt]=a.useState(!1),Jt=a.useRef(null),Ze=a.useRef(null),$e=a.useRef(0),Gt=a.useRef(!1),rt=a.useRef(0),Pt=a.useRef(!1),ht=a.useRef(new TextDecoder("utf-8",{fatal:!1})),_t=a.useRef(null),ln=a.useRef(null),vn=a.useRef(!1),Ue=t?t1(t):"unsupported",Dt=t?Zx(t):!1,Xn=t?e1(t):!1,$n=Dt||Xn,cn=t?Lc(t):!1,X=a.useMemo(()=>i.join(""),[i]),dn=a.useCallback(()=>{const I=_t.current;_t.current=null,I&&s("fs:preview-close",{ticketId:I}).catch(()=>{})},[s]),Zt=a.useCallback(async(I,Q=!1,fe=rt.current)=>{if(!Pt.current){Pt.current=!0,w(Q?"initial-loading":"loading-more"),z(null);try{const ze=Q?0:$e.current,ge=await s("fs:read",{path:I,offset:ze,length:256*1024});if(fe!==rt.current)return;const Ut=ge.offset+ge.bytes;if(!ge.eof&&Ut<=ze)throw new Error("文件加载未取得进展,请重试");Q&&(ht.current=new TextDecoder("utf-8",{fatal:!1}));const rn=Jx(ht.current,ge.data,ge.eof);$e.current=Ut,at(ge.eof),C(Ut),o(pt=>Q?[rn]:[...pt,rn]),v(pt=>({size:ge.size,mtime:(pt==null?void 0:pt.mtime)??0})),H(null),w("ready")}catch(ze){if(fe!==rt.current)return;const ge=ze.message??String(ze);Q?(H(ge),w("error")):(z(ge),w("ready"))}finally{fe===rt.current&&(Pt.current=!1)}}},[s]),wt=a.useCallback(async(I,Q)=>{try{const fe=await s("fs:inspect-text-status",{path:I});if(Q!==rt.current)return;v({size:fe.size,mtime:fe.mtime}),Ye(fe.diffStatus),lt(!fe.tooLarge),dt(!1),ee(null)}catch{}},[s]),Rt=a.useCallback(async(I,Q=rt.current)=>{dn(),w("initial-loading"),H(null);try{const fe=await s("fs:preview-open",{path:I});if(Q!==rt.current){s("fs:preview-close",{ticketId:fe.ticketId}).catch(()=>{});return}_t.current=fe.ticketId,ln.current=fe.url,d(fe.url),v({size:fe.size,mtime:fe.mtime})}catch(fe){if(Q!==rt.current)return;H(fe.message??String(fe)),w("error")}},[dn,s]),gt=a.useCallback(async(I,Q=rt.current)=>{w("initial-loading"),H(null);try{const fe=await s("fs:read",{path:I,offset:0,length:qx});if(Q!==rt.current)return;Wt(fe.data),C(fe.bytes),v(ze=>({size:fe.size,mtime:(ze==null?void 0:ze.mtime)??0})),w("ready")}catch(fe){if(Q!==rt.current)return;H(fe.message??String(fe)),w("error")}},[s]);function Wt(I){const Q=atob(I),fe=[];for(let ze=0;ze+16<=Q.length||ze===0;ze+=16){const ge=Q.slice(ze,ze+16),Ut=[...ge].map(pt=>pt.charCodeAt(0).toString(16).padStart(2,"0")).join(" ").padEnd(47," "),rn=[...ge].map(pt=>pt.charCodeAt(0)>=32&&pt.charCodeAt(0)<127?pt:".").join("");if(fe.push(`${ze.toString(16).padStart(8,"0")} ${Ut} |${rn}|`),ze+16>Q.length)break}f(fe.join(`
|
|
487
|
+
`))}const mt=a.useCallback((I,Q)=>{const fe=++rt.current,ze=Lc(I);Pt.current=!1,dn(),ln.current=null,o([]),d(null),f(""),v(null),H(null),z(null),C(0),T(null),R(null),F(!1),Qe(null),ke(null),Ie(!1),at(!0),ne(null),Ye("unavailable"),te(!1),le(null),ye("file"),lt(!1),Tt(!1),Nt(!1),B(""),ee(null),dt(!1),w("initial-loading"),Gt.current=!1,$e.current=0,ht.current=new TextDecoder("utf-8",{fatal:!1}),s("fs:watch",{path:r1(I)}).catch(()=>{}),Q==="text"?(wt(I,fe),Zt(I,!0,fe),ze&&vn.current&&Rt(I,fe)):Q==="image"||Q==="video"||Q==="audio"||Q==="pdf"?Rt(I,fe):Q==="hex"&&(s("fs:stat",{path:I}).then(ge=>{fe===rt.current&&v(ge)}).catch(()=>{}),gt(I,fe))},[Zt,gt,Rt,wt,dn,s]);a.useEffect(()=>{if(t)return vn.current=!1,Te(!1),mt(t,Ue),()=>{rt.current++,Pt.current=!1,dn()}},[t]),a.useEffect(()=>{let I=null;const Q=fe=>{const ze=fe.detail;!ze||ze!==t||(I!==null&&window.clearTimeout(I),I=window.setTimeout(()=>{Ue==="text"&&Gt.current?dt(!0):t&&mt(t,Ue)},350))};return window.addEventListener("file-changed",Q),()=>{window.removeEventListener("file-changed",Q),I!==null&&window.clearTimeout(I)}},[t,Ue,mt]),a.useEffect(()=>{Gt.current=He},[He]),a.useEffect(()=>{if(x!=="initial-loading"){E(!1);return}const I=window.setTimeout(()=>E(!0),120);return()=>window.clearTimeout(I)},[t,x]),a.useEffect(()=>{const I=Ze.current,Q=Jt.current;if(!I||!Q||!t||Ue!=="text"||We||He||pe!=="file"||x!=="ready"||k)return;const fe=new IntersectionObserver(ze=>{ze.some(ge=>ge.isIntersecting)&&Zt(t)},{root:Q,rootMargin:"0px 0px 360px 0px"});return fe.observe(I),()=>fe.disconnect()},[He,We,Ue,Zt,k,t,x,pe]);const wn=a.useCallback((I,Q)=>{const fe=URL.createObjectURL(I),ze=document.createElement("a");ze.href=fe,ze.download=ii(Q),ze.style.display="none",document.body.appendChild(ze),ze.click(),ze.remove(),window.setTimeout(()=>URL.revokeObjectURL(fe),1e3)},[]),Yn=a.useCallback(async()=>{if(!t||A!==null||ae!==null)return;const I=t;T(null),Qe(null),F(!1),R(0);try{const Q=await zc(I,s,R);wn(Q,I),F(!0),window.setTimeout(()=>F(!1),1500)}catch(Q){T((Q==null?void 0:Q.message)??String(Q))}finally{R(null)}},[wn,A,t,s,ae]),Jn=a.useCallback(async()=>{if(!t||ae!==null||A!==null)return;const I=t;T(null),Qe(null),Ie(!1);const Q=Qx(navigator,window.isSecureContext);if(Q==="insecure-context"){Qe("当前页面是 HTTP,手机 Chrome 仅允许 HTTPS 页面分享文件,请改用 HTTPS 地址后重试");return}if(Q==="unsupported-browser"){Qe("当前浏览器不支持分享文件,请使用最新版手机 Chrome 或系统浏览器");return}ke(0);try{const fe=await zc(I,s,ke),ze=new File([fe],ii(I),{type:Xx(I),lastModified:(p==null?void 0:p.mtime)??Date.now()}),ge=await Yx(ze,navigator);ge==="unsupported"?Qe("当前浏览器不支持分享此文件类型,请使用下载按钮"):ge==="shared"&&(Ie(!0),window.setTimeout(()=>Ie(!1),1500))}catch(fe){Qe((fe==null?void 0:fe.message)??String(fe))}finally{ke(null)}},[A,p==null?void 0:p.mtime,t,s,ae]),en=a.useCallback(async(I,Q)=>{const fe=await s("fs:inspect-text",{path:I},6e4);return Q!==rt.current?null:(v({size:fe.size,mtime:fe.mtime}),Ye(fe.diffStatus),ne(fe.patch),lt(!fe.tooLarge&&fe.validUtf8),fe)},[s]),Hn=a.useCallback(async()=>{if(!t||st)return;const I=rt.current;Tt(!0),ee(null);try{const Q=await en(t,I);if(!Q)return;if(Q.tooLarge||Q.data===null)throw new Error("文件超过 8M,无法在线编辑");if(!Q.validUtf8)throw new Error("此文件不是有效的 UTF-8 文本,无法在线编辑");const fe=new TextDecoder("utf-8",{fatal:!1}).decode(Ca(Q.data));o([fe]),C(Q.size),$e.current=Q.size,at(!0),B(fe),dt(!1),Gt.current=!0,Nt(!0)}catch(Q){I===rt.current&&ee(Q.message??String(Q))}finally{I===rt.current&&Tt(!1)}},[st,en,t]),tn=a.useCallback(async()=>{if(!t||W||(ye("diff"),Ge!==null))return;const I=rt.current;te(!0),le(null);try{await en(t,I)}catch(Q){I===rt.current&&le(Q.message??String(Q))}finally{I===rt.current&&te(!1)}},[W,en,Ge,t]),Zn=a.useCallback(()=>{if(!t)return;const I=!we;vn.current=I,Te(I),I&&!l&&Rt(t,rt.current)},[Rt,l,t,we]),kn=a.useCallback(I=>{ln.current===I&&(H(null),w("ready"))},[]),un=a.useCallback(I=>{ln.current===I&&(H("文件预览加载失败,请重试"),w("error"))},[]),ar=a.useCallback(()=>{t&&mt(t,Ue)},[Ue,t,mt]),jn=a.useCallback(()=>{ct!==X&&!window.confirm("放弃未保存的修改?")||(Gt.current=!1,Nt(!1),B(""),ee(null),dt(!1))},[ct,X]),Un=a.useCallback(()=>{He&&ct!==X&&!window.confirm("放弃未保存的修改并关闭预览?")||(rt.current++,dn(),r())},[ct,He,r,dn,X]),Ne=a.useCallback(()=>{t&&(Gt.current=!1,Nt(!1),B(""),mt(t,"text"))},[t,mt]),it=a.useCallback(async()=>{if(!(!t||!p||Y||ct===X)){q(!0),ee(null);try{await s("fs:write-text",{path:t,content:ct,expectedSize:p.size,expectedMtime:p.mtime},6e4),Gt.current=!1,Nt(!1),B(""),mt(t,"text")}catch(I){ee((I==null?void 0:I.message)??String(I))}finally{q(!1)}}},[ct,p,t,s,Y,mt,X]),Ht=a.useMemo(()=>Nx(Ge??""),[Ge]);if(!t)return null;const er=((p==null?void 0:p.size)??0)>Ux,Wn=!er&&(be==="changed"||be==="untracked"),Ft=Ue==="text"&&ut&&x!=="initial-loading"&&!st&&!M;return e.jsxs("div",{style:{height:"100%",display:"flex",flexDirection:"column",background:"var(--ui-term-col-bg, #101014)",color:"var(--ui-text, #e8e8ee)",colorScheme:"var(--ui-color-scheme, dark)",accentColor:"var(--ui-tab-accent, #7aa2f7)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:10,padding:"9px 12px",borderBottom:"1px solid var(--ui-tree-border, #222)",background:"var(--ui-tree-bg, #121218)",flexShrink:0},children:[e.jsx("span",{className:"pv-name",style:{minWidth:0,flex:"1 1 auto",fontSize:12.5,color:"var(--ui-text, #e8e8ee)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:ii(t)}),p&&e.jsx("span",{style:{fontSize:10.5,color:"var(--ui-history-meta, #666)",flexShrink:0},children:Uo(p.size)}),He?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:jn,disabled:Y,style:us,"aria-label":"取消编辑",title:"取消编辑",children:e.jsx(da,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:it,disabled:Y||ct===X,style:{...us,color:"var(--ui-tab-accent, #7aa2f7)",opacity:Y||ct===X?.55:1},"aria-label":Y?"正在保存":"保存修改",title:Y?"正在保存":"保存修改",children:Y?e.jsx(ot,{className:"tree-spin",size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(Tp,{size:15,strokeWidth:1.8,"aria-hidden":"true"})})]}):e.jsxs(e.Fragment,{children:[Ue==="text"&&e.jsx("button",{type:"button",onClick:Hn,disabled:!Ft,style:{...us,opacity:Ft?1:.45},"aria-label":"编辑文件",title:er?"文件超过 8M,无法在线编辑":ut?"编辑文件":"此文件不可编辑",children:e.jsx(ca,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:Yn,disabled:A!==null||ae!==null,style:{...us,opacity:A!==null||ae!==null?.72:1},"aria-label":A===null?"下载到当前设备":`正在下载 ${A}%`,title:A===null?"下载到当前设备":`正在下载 ${A}%`,children:A!==null?e.jsx(ot,{className:"tree-spin",size:15,strokeWidth:1.8,"aria-hidden":"true"}):$?e.jsx(Gr,{size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(la,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),e.jsx("button",{type:"button",onClick:Jn,disabled:ae!==null||A!==null,style:{...us,opacity:ae!==null||A!==null?.72:1},"aria-label":"分享文件",title:ae===null?"分享文件":`正在准备 ${ae}%`,children:ae!==null?e.jsx(ot,{className:"tree-spin",size:15,strokeWidth:1.8,"aria-hidden":"true"}):De?e.jsx(Gr,{size:15,strokeWidth:1.8,"aria-hidden":"true"}):e.jsx(_p,{size:15,strokeWidth:1.8,"aria-hidden":"true"})}),cn&&e.jsx("button",{type:"button",onClick:Zn,"aria-pressed":we,style:{...us,...we?{color:"var(--ui-tab-accent, #7aa2f7)",borderColor:"var(--ui-tab-accent, #7aa2f7)"}:{}},"aria-label":we?"退出浏览器预览":"浏览器预览",title:we?"退出浏览器预览":Dt?"在浏览器中预览渲染效果":Xn?"预览 Markdown 排版效果":"在浏览器中查看原始文件",children:e.jsx(cp,{size:15,strokeWidth:1.8,"aria-hidden":"true"})})]}),e.jsx("button",{type:"button",onClick:Un,style:us,"aria-label":"关闭预览",title:"关闭预览",children:e.jsx(Tr,{size:15,strokeWidth:1.8,"aria-hidden":"true"})})]}),Ue==="text"&&Wn&&!He&&!we&&e.jsxs("div",{style:{display:"flex",alignItems:"center",minHeight:34,padding:"0 12px",borderBottom:"1px solid var(--ui-tree-border, #222)",background:"var(--ui-tree-bg, #121218)",flexShrink:0},children:[e.jsxs("div",{role:"tablist","aria-label":"文件预览模式",style:{display:"inline-flex",gap:2,padding:2,border:"1px solid var(--ui-panel-input-border, #333)",borderRadius:6,background:"var(--ui-muted-surface, #1b1b22)"},children:[e.jsx(Pc,{active:pe==="diff",onClick:tn,children:"变更"}),e.jsx(Pc,{active:pe==="file",onClick:()=>ye("file"),children:"文件"})]}),e.jsxs("span",{style:{marginLeft:9,display:"inline-flex",gap:7,fontFamily:'"SF Mono", Menlo, Consolas, monospace',fontSize:10.5},children:[Ht.added>0&&e.jsxs("span",{style:{color:"var(--ui-success, #059669)"},children:["+",Ht.added]}),Ht.removed>0&&e.jsxs("span",{style:{color:"var(--ui-error, #dc2626)"},children:["-",Ht.removed]})]})]}),Ee&&e.jsxs("div",{role:"alert",style:{flexShrink:0,padding:"8px 12px",borderBottom:"1px solid var(--ui-tree-border, #222)",background:"var(--ui-tree-bg, #121218)",color:"var(--ui-error, #f7768e)",fontSize:12.5,lineHeight:1.5},children:["分享失败:",Ee]}),e.jsxs("div",{ref:Jt,className:"pv-body",style:{position:"relative",flex:1,minHeight:0,overflow:"auto",background:"var(--ui-term-col-bg, #101014)",WebkitOverflowScrolling:"touch"},children:[L&&e.jsxs("div",{style:{padding:"10px 14px 0",color:"var(--ui-error, #f7768e)",fontSize:12.5},children:["下载失败:",L]}),se&&e.jsx("div",{role:"alert",style:{padding:"10px 14px",color:"var(--ui-error, #f7768e)",fontSize:12.5},children:se}),Ke&&He&&e.jsxs("div",{role:"alert",style:{display:"flex",alignItems:"center",gap:8,padding:"8px 12px",borderBottom:"1px solid var(--ui-tree-border, #222)",color:"var(--ui-error, #f7768e)",fontSize:12},children:[e.jsx("span",{style:{flex:1},children:"文件已在其他位置更新"}),e.jsxs("button",{type:"button",onClick:Ne,style:ia,children:[e.jsx(Ns,{size:13,strokeWidth:1.8,"aria-hidden":"true"}),"重新加载"]})]}),l&&!M&&Ue==="image"&&e.jsx("img",{src:l,alt:t,onLoad:()=>kn(l),onError:()=>un(l),style:{maxWidth:"100%",maxHeight:"100%",objectFit:"contain",display:"block",margin:"0 auto"}}),l&&!M&&Ue==="video"&&e.jsx("video",{src:l,controls:!0,autoPlay:!0,onLoadedMetadata:()=>kn(l),onError:()=>un(l),style:{maxWidth:"100%",maxHeight:"100%",display:"block",margin:"0 auto"}}),l&&!M&&Ue==="audio"&&e.jsx("div",{style:{display:"grid",placeItems:"center",height:"100%"},children:e.jsx("audio",{src:l,controls:!0,autoPlay:!0,onLoadedMetadata:()=>kn(l),onError:()=>un(l),style:{width:"min(420px, 88%)"}})}),l&&!M&&Ue==="pdf"&&e.jsx("iframe",{src:l,title:t,onLoad:()=>kn(l),onError:()=>un(l),style:{width:"100%",height:"100%",border:"none"}}),l&&!M&&Ue==="text"&&cn&&we&&!He&&e.jsx("iframe",{src:$n?`${l}/${encodeURIComponent(ii(t))}`:l,sandbox:Bx,title:t,onLoad:()=>kn(l),onError:()=>un(l),style:{width:"100%",height:"100%",border:"none",background:"#fff"}}),Ue==="text"&&He&&!M&&e.jsx("textarea",{value:ct,onChange:I=>B(I.target.value),spellCheck:!1,autoCapitalize:"off",autoCorrect:"off","aria-label":`编辑 ${ii(t)}`,style:{width:"100%",minHeight:"100%",boxSizing:"border-box",resize:"none",margin:0,padding:"12px 14px calc(env(safe-area-inset-bottom) + 36px)",border:0,outline:0,background:"var(--ui-term-col-bg, #101014)",color:"var(--ui-history-item-text, var(--ui-text, #d6d6de))",fontFamily:'"SF Mono", Menlo, Consolas, monospace',fontSize:12,lineHeight:1.5,tabSize:2}}),Ue==="text"&&!He&&!M&&Wn&&pe==="diff"&&(G?e.jsx(Ti,{label:G,actionLabel:"重试",onAction:()=>void tn(),tone:"error"}):W?e.jsx(Ti,{label:"正在加载变更"}):e.jsx(s1,{rows:Ht.rows})),(Ue==="hex"||Ue==="text"&&!He&&!we&&(!Wn||pe==="file"))&&!M&&e.jsxs(e.Fragment,{children:[e.jsx("pre",{style:{margin:0,padding:"11px 13px calc(env(safe-area-inset-bottom) + 36px)",fontFamily:'"SF Mono", Menlo, Consolas, monospace',fontSize:Ue==="hex"?10.5:12,lineHeight:1.45,color:Ue==="hex"?"var(--ui-muted-text, #9aa)":"var(--ui-history-item-text, var(--ui-text, #d6d6de))",whiteSpace:Ue==="hex"?"pre":"pre-wrap",wordBreak:Ue==="hex"?"normal":"break-word"},children:Ue==="hex"?u:e.jsx(Lx,{path:t,chunks:i,fileSize:p==null?void 0:p.size})}),Ue==="text"&&!We&&e.jsxs("div",{ref:Ze,role:"status","aria-live":"polite",style:{minHeight:44,padding:"0 14px calc(env(safe-area-inset-bottom) + 8px)",display:"flex",alignItems:"center",justifyContent:"center",gap:7,color:"var(--ui-history-meta, #666)",fontSize:11.5},children:[x==="loading-more"&&e.jsx(ot,{className:"tree-spin",size:14,strokeWidth:1.8,"aria-hidden":"true",style:{color:"var(--ui-tab-accent, #7aa2f7)"}}),k?e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"加载失败"}),e.jsxs("button",{type:"button",onClick:()=>Zt(t),style:ia,children:[e.jsx(Ns,{size:13,strokeWidth:1.8,"aria-hidden":"true"}),"重试"]})]}):e.jsx("span",{children:x==="loading-more"?"正在加载更多":`${Uo(S)} / ${Uo((p==null?void 0:p.size)??S)}`})]})]}),j&&x==="initial-loading"&&e.jsx(Ti,{label:"正在加载文件"}),M&&x==="error"&&e.jsx(Ti,{label:M,actionLabel:"重试",onAction:ar,tone:"error"})]})]})}function ii(t){return t.slice(t.lastIndexOf("/")+1)||t}function r1(t){const n=t.lastIndexOf("/");return n>0?t.slice(0,n):"/"}function Uo(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}K`:`${(t/1024/1024).toFixed(1)}M`}const us={width:28,height:28,borderRadius:7,border:"1px solid var(--ui-panel-input-border, #333)",display:"inline-flex",alignItems:"center",justifyContent:"center",background:"var(--ui-muted-surface, #1b1b22)",color:"var(--ui-muted-text, #ccc)",flexShrink:0,cursor:"pointer",WebkitAppRegion:"no-drag"},ia={minHeight:28,padding:"0 9px",borderRadius:6,border:"1px solid var(--ui-panel-input-border, #333)",display:"inline-flex",alignItems:"center",justifyContent:"center",gap:5,background:"var(--ui-muted-surface, #1b1b22)",color:"var(--ui-muted-text, #ccc)",cursor:"pointer",fontSize:11};function Ti({label:t,actionLabel:n,onAction:r,tone:s="muted"}){return e.jsxs("div",{role:s==="error"?"alert":"status",style:{position:"absolute",inset:0,minHeight:120,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:10,color:s==="error"?"var(--ui-error, #f7768e)":"var(--ui-muted-text, #9aa)",fontSize:12.5},children:[s!=="error"&&e.jsx(ot,{className:"tree-spin",size:18,strokeWidth:1.8,"aria-hidden":"true",style:{color:"var(--ui-tab-accent, #7aa2f7)"}}),e.jsx("span",{children:t}),n&&r&&e.jsxs("button",{type:"button",onClick:r,style:ia,children:[e.jsx(Ns,{size:13,strokeWidth:1.8,"aria-hidden":"true"}),n]})]})}function Pc({active:t,onClick:n,children:r}){return e.jsx("button",{type:"button",role:"tab","aria-selected":t,onClick:n,style:{minWidth:48,height:24,padding:"0 9px",border:0,borderRadius:4,background:t?"var(--ui-tab-accent, #7aa2f7)":"transparent",color:t?"var(--ui-tab-active-text, #fff)":"var(--ui-muted-text, #9aa)",fontSize:11,fontWeight:600,cursor:"pointer"},children:r})}function s1({rows:t}){return e.jsx("div",{style:{minWidth:"100%",width:"max-content",paddingBottom:"calc(env(safe-area-inset-bottom) + 36px)",fontFamily:'"SF Mono", Menlo, Consolas, monospace',fontSize:11.5,lineHeight:1.55},children:t.map((n,r)=>{const s=n.kind==="added",i=n.kind==="removed",o=n.kind==="hunk"||n.kind==="meta"||n.kind==="note",l=s?"color-mix(in srgb, var(--ui-success, #059669) 12%, transparent)":i?"color-mix(in srgb, var(--ui-error, #dc2626) 11%, transparent)":n.kind==="hunk"?"color-mix(in srgb, var(--ui-tab-accent, #7aa2f7) 10%, transparent)":"transparent",d=s?"var(--ui-success, #059669)":i?"var(--ui-error, #dc2626)":o?"var(--ui-muted-text, #9aa)":"var(--ui-history-item-text, var(--ui-text, #d6d6de))";return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"42px 42px 22px minmax(0, 1fr)",minHeight:18,background:l,color:d},children:[e.jsx("span",{style:Dc,children:n.oldLine??""}),e.jsx("span",{style:Dc,children:n.newLine??""}),e.jsx("span",{style:{textAlign:"center",userSelect:"none",color:d},children:s?"+":i?"-":" "}),e.jsx("span",{style:{padding:"0 12px 0 6px",whiteSpace:"pre-wrap",overflowWrap:"anywhere"},children:n.text||" "})]},`${n.kind}-${r}`)})})}const Dc={padding:"0 6px",borderRight:"1px solid var(--ui-tree-border, #222)",color:"var(--ui-history-meta, #666)",textAlign:"right",userSelect:"none"};function Hi(t){const n=t.replace(/\/{2,}/g,"/");return n.length>1?n.replace(/\/+$/,""):n}function au(t){const n=Hi(t),r=n.lastIndexOf("/");return r<=0?"/":n.slice(0,r)}function lu(t,n){const r=Hi(t),s=Hi(n);return s==="/"?r.startsWith("/"):r.startsWith(`${s}/`)}function i1(t,n){const r=Hi(t);if(!lu(n,r))return[];const s=au(n);if(s===r)return[r];const i=s.slice(r==="/"?1:r.length+1),o=[r];let l=r;for(const d of i.split("/").filter(Boolean))l=l==="/"?`/${d}`:`${l}/${d}`,o.push(l);return o}const o1={code:{icon:Zc,color:"#7aa2f7",label:"代码文件"},style:{icon:od,color:"#bb9af7",label:"样式文件"},image:{icon:ed,color:"#9ece6a",label:"图片文件"},video:{icon:rd,color:"#f7768e",label:"视频文件"},audio:{icon:Jc,color:"#c099ff",label:"音频文件"},markdown:{icon:id,color:"#73daca",label:"Markdown 文件"},text:{icon:ci,color:"#a9b1d6",label:"文本文件"},json:{icon:td,color:"#e0af68",label:"JSON 文件"},archive:{icon:Yc,color:"#ff9e64",label:"压缩文件"},spreadsheet:{icon:nd,color:"#9ece6a",label:"表格文件"},presentation:{icon:ad,color:"#f7768e",label:"演示文件"},database:{icon:Xc,color:"#2ac3de",label:"数据库文件"},file:{icon:sd,color:"#c8c8d0",label:"文件"}};function a1(t){return o1[iu(t)]}function Wc(t){return t<1024?`${t}B`:t<1024*1024?`${(t/1024).toFixed(1)}K`:t<1024*1024*1024?`${(t/1024/1024).toFixed(1)}M`:`${(t/1024/1024/1024).toFixed(1)}G`}function l1({gateway:t,onOpenFile:n,selectedPath:r,ready:s,cwd:i,followCwd:o,initialRoot:l,initialFollow:d=!0,onTreeStateChange:u,revealRequest:f}){const p=t.request,v=t.subscribe,[x,w]=a.useState(null),[j,E]=a.useState(""),[S,C]=a.useState(""),[k,z]=a.useState(!d),[M,H]=a.useState(""),L=a.useRef(new Map),T=a.useRef(null),A=a.useRef(null),R=a.useRef(0),$=a.useRef(0),[,F]=a.useState(0),Ee=()=>F(G=>G+1),Qe=a.useCallback(async(G,le)=>{const pe={path:G,depth:le,expanded:!0,children:null,loading:!0};L.current.set(G,pe),Ee();try{const ye=await p("fs:list",{path:G});pe.children=ye.entries,p("fs:watch",{path:G}).catch(()=>{})}catch(ye){pe.children=[],pe.error=(ye==null?void 0:ye.message)??"read failed"}return pe.loading=!1,Ee(),pe},[p]),ae=!!o&&!k,ke=a.useCallback(G=>{const le=G.length>1?G.replace(/\/+$/,""):G;T.current=le,L.current.clear(),w({path:le,depth:0,expanded:!1,children:null,loading:!1}),C(le)},[]);a.useEffect(()=>{!s||!i||!ae||T.current!==i&&(ke(i),u==null||u(i,!0))},[s,i,ae,ke]),a.useEffect(()=>{!s||!l||d||T.current||(z(!0),ke(l))},[s,l,d,ke]),a.useEffect(()=>{s&&p("hello").then(G=>{H(G.home),ae&&!i&&!T.current&&ke(G.home)}).catch(()=>{})},[s,i,ae,p,ke]);const De=()=>{let G=S.trim();G&&(G==="~"?G=M||i||"/":G.startsWith("~/")?G=`${M||i||""}${G.slice(1)}`:G.startsWith("/")||(G=`${i||(x==null?void 0:x.path)||M||"/"}/${G}`),G=G.replace(/\/+/g,"/"),z(!0),ke(G),u==null||u(G,!1))},Ie=()=>{z(!1),i&&(ke(i),u==null||u(i,!0))},We=a.useCallback(async G=>{let le=L.current.get(G);le||(le={path:G,depth:0,expanded:!1,children:null,loading:!1},L.current.set(G,le)),le.expanded?le.expanded=!1:(le.expanded=!0,!le.children&&!le.loading&&await Qe(G,le.depth)),Ee()},[Qe]),at=a.useCallback(async(G,le)=>{let pe=L.current.get(G);pe?!pe.children&&!pe.loading&&await Qe(G,le):pe=await Qe(G,le),pe.expanded=!0,Ee()},[Qe]),Ge=a.useCallback(async(G,le)=>{const pe=au(G);let ye=(x==null?void 0:x.path)??pe;lu(G,ye)||(ye=pe,z(!0),ke(ye),u==null||u(ye,!1));const we=i1(ye,G);for(let ut=0;ut<we.length;ut+=1){if(R.current!==le)return;await at(we[ut],ut)}const Te=()=>{var lt;if(R.current!==le)return;const ut=Array.from(((lt=A.current)==null?void 0:lt.querySelectorAll("[data-tree-path]"))??[]).find(st=>st.dataset.treePath===G);ut==null||ut.scrollIntoView({block:"center",inline:"nearest"})};requestAnimationFrame(()=>requestAnimationFrame(Te))},[ke,u,at,x==null?void 0:x.path]);a.useEffect(()=>{!s||!f||$.current!==f.requestId&&($.current=f.requestId,R.current=f.requestId,Ge(f.path,f.requestId))},[s,Ge,f==null?void 0:f.requestId]),a.useEffect(()=>v("fs:event",G=>{for(const le of G.events??[]){const pe=le.path;pe===r&&window.dispatchEvent(new CustomEvent("file-changed",{detail:pe}));const ye=pe.slice(0,pe.lastIndexOf("/"))||"/",we=L.current.get(ye);we!=null&&we.expanded&&we.children&&!we.loading&&Qe(ye,we.depth).catch(()=>{})}}),[v,r,Qe]);const ne=(G,le)=>G.endsWith("/")?G+le:`${G}/${le}`,be=j.trim().toLowerCase(),Ye=(G,le)=>{var we;if(!be||le.name.toLowerCase().includes(be))return!0;if(!le.dir)return!1;const pe=ne(G,le.name),ye=(we=L.current.get(pe))==null?void 0:we.children;return(ye==null?void 0:ye.some(Te=>Ye(pe,Te)))??!1},W=(G,le,pe)=>le.filter(ye=>Ye(G,ye)).map(ye=>{const we=ne(G,ye.name);if(ye.dir){const lt=L.current.get(we),st=(lt==null?void 0:lt.expanded)??!1;return e.jsxs("div",{children:[e.jsxs("div",{className:"tree-row",onClick:()=>We(we),style:{paddingLeft:6+pe*12},children:[e.jsx("span",{className:"tree-disclosure","aria-hidden":"true",children:lt!=null&<.loading?e.jsx(ot,{className:"tree-spin",size:13}):st?e.jsx(Pi,{size:13}):e.jsx(Kr,{size:13})}),e.jsx("span",{className:"tree-entry-icon tree-folder-icon","aria-hidden":"true",children:st?e.jsx(hl,{size:16}):e.jsx(Go,{size:16})}),e.jsx("span",{className:"tree-entry-name",children:ye.name})]}),st&&(lt.error?e.jsx("div",{className:"tree-error",role:"alert",style:{paddingLeft:22+pe*12},children:lt.error}):lt.children?W(we,lt.children,pe+1):e.jsx("div",{className:"tree-row",style:{paddingLeft:22+pe*12,color:"#556"},children:"…"}))]},we)}const Te=a1(ye.name),ut=Te.icon;return e.jsxs("div",{className:"tree-row","data-tree-path":we,"data-selected":we===r?"1":void 0,onClick:()=>n(we),title:`${Te.label} · ${we} · ${Wc(ye.size)}`,style:{paddingLeft:6+pe*12},children:[e.jsx("span",{className:"tree-disclosure","aria-hidden":"true"}),e.jsx("span",{className:"tree-entry-icon",style:{color:Te.color},"aria-hidden":"true",children:e.jsx(ut,{size:16,strokeWidth:1.8})}),e.jsx("span",{className:"tree-entry-name",children:ye.name}),e.jsx("span",{className:"tree-size",children:Wc(ye.size)})]},we)});if(!x)return e.jsx("div",{style:{padding:14,fontSize:12,color:"#556"},children:ae?s?"等待终端目录…":"连接中…":"…"});const te=L.current.get(x.path);return e.jsxs("div",{className:"tree-scroll",ref:A,children:[e.jsxs("div",{className:"tree-location",children:[e.jsx("input",{value:S,onChange:G=>C(G.target.value),onKeyDown:G=>{G.key==="Enter"&&De()},placeholder:"输入目录路径","aria-label":"文件树目录路径",spellCheck:!1}),e.jsx("button",{tabIndex:-1,onClick:De,title:"定位目录","aria-label":"定位目录",children:e.jsx(ap,{size:14,"aria-hidden":"true"})}),e.jsx("button",{tabIndex:-1,onClick:Ie,title:"跟随终端目录","aria-label":"跟随终端目录","data-active":ae?"1":void 0,children:e.jsx(mp,{size:14,"aria-hidden":"true"})})]}),e.jsxs("div",{className:"tree-filter",children:[e.jsx(ua,{size:14,"aria-hidden":"true"}),e.jsx("input",{value:j,onChange:G=>E(G.target.value),placeholder:"筛选已加载文件","aria-label":"筛选文件树"}),j&&e.jsx("button",{tabIndex:-1,onClick:()=>E(""),"aria-label":"清除筛选",children:e.jsx(Tr,{size:13,"aria-hidden":"true"})})]}),e.jsxs("div",{className:"tree-row",onClick:()=>We(x.path),children:[e.jsx("span",{className:"tree-disclosure","aria-hidden":"true",children:te!=null&&te.loading?e.jsx(ot,{className:"tree-spin",size:13}):te!=null&&te.expanded?e.jsx(Pi,{size:13}):e.jsx(Kr,{size:13})}),e.jsx("span",{className:"tree-entry-icon tree-folder-icon","aria-hidden":"true",children:te!=null&&te.expanded?e.jsx(hl,{size:16}):e.jsx(Go,{size:16})}),e.jsx("span",{className:"tree-entry-name",style:{direction:"rtl",textAlign:"left"},children:x.path})]}),(te==null?void 0:te.expanded)&&(te.error?e.jsx("div",{className:"tree-error",role:"alert",children:te.error}):te.children?W(x.path,te.children,1):e.jsx("div",{className:"tree-row",style:{paddingLeft:24,color:"#556"},children:"…"}))]})}function c1({open:t,tab:n,gateway:r,cwd:s,selectedPath:i,revealRequest:o,onTabChange:l,onSelectPath:d,onClose:u}){return t?e.jsxs("section",{className:`desktop-file-workspace${i?" has-preview":""}`,"aria-label":"我的文件",children:[e.jsxs("aside",{className:"desktop-file-drawer",children:[e.jsxs("header",{className:"desktop-file-drawer-header",children:[e.jsxs("div",{className:"desktop-file-drawer-tabs",role:"tablist","aria-label":"文件工作区视图",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":n==="files",className:n==="files"?"is-active":"",onClick:()=>l("files"),children:"文件"}),e.jsx("button",{type:"button",role:"tab","aria-selected":n==="history",className:n==="history"?"is-active":"",onClick:()=>l("history"),children:"历史"})]}),e.jsx("button",{type:"button",className:"desktop-file-workspace-close ui-icon-button ui-icon-button--small",onClick:u,"aria-label":"关闭我的文件",title:"关闭",children:e.jsx(Tr,{size:15,"aria-hidden":"true"})})]}),n==="files"?s?e.jsx(l1,{gateway:r,ready:!0,followCwd:!0,cwd:s,onOpenFile:f=>d(f),selectedPath:i,revealRequest:o}):e.jsx("div",{className:"desktop-file-workspace-empty",children:"请先选择一个项目目录"}):e.jsxs("div",{className:"desktop-file-workspace-empty",children:[e.jsx("strong",{children:"终端历史在 Web 控制台中可用"}),e.jsx("span",{children:"Electron 当前没有终端上下文,因此不会提供填入或执行操作。"})]}),e.jsxs("footer",{className:"desktop-file-drawer-footer",children:[e.jsx("span",{}),"实时同步"]})]}),i&&e.jsx("div",{className:"desktop-file-preview",children:e.jsx(n1,{path:i,gateway:r,onClose:()=>d(null)})})]}):null}const cu="agentroam.agent-workspaces.v2",d1=2,du=["customer-agent","codex","claude-code","opencode"];function Fc(){return{version:2,activeAgent:"customer-agent",agents:{}}}function Bc(){return{workspaces:[],nextCursor:null,watermark:null,expandedWorkspaceIds:[],selectedWorkspaceId:null,selectedSessionId:null,sidebarScrollTop:0,sessions:{}}}function u1(t=localStorage){try{const n=JSON.parse(t.getItem(cu)??"null");if(!ps(n)||n.version!==d1)return Fc();const r=m1(n.activeAgent)?n.activeAgent:"customer-agent",s=ps(n.agents)?n.agents:{},i={};for(const o of du){const l=g1(s[o],o);l&&(i[o]=l)}return{version:2,activeAgent:r,agents:i}}catch{return Fc()}}function Oc(t,n=localStorage){try{n.setItem(cu,JSON.stringify(t))}catch{}}function p1(t,n,r){const s=new Set(n.data.map(l=>l.workspaceId)),i=r?n.nextCursor?[...n.data,...t.filter(l=>!s.has(l.workspaceId))]:n.data:[...t,...n.data],o=new Set;return i.filter(l=>o.has(l.workspaceId)?!1:(o.add(l.workspaceId),!0))}function uu(t,n,r){const s=new Set(n.data.map(u=>u.id)),i=new Map(n.data.map(u=>[u.id,u])),o=new Set(t.map(u=>u.id)),l=r?n.nextCursor?[...n.data,...t.filter(u=>!s.has(u.id))]:n.data:[...t.map(u=>i.get(u.id)??u),...n.data.filter(u=>!o.has(u.id))],d=new Set;return l.filter(u=>d.has(u.id)?!1:(d.add(u.id),!0))}async function f1(t,n,r,s){if(n.stale)return n;const i=new Set(n.data.map(p=>p.id)),o=new Set(t.filter(p=>p.status==="running"&&p.id!==s&&!i.has(p.id)).map(p=>p.id));if(o.size===0||!n.nextCursor)return n;let l=[...n.data],d=n.nextCursor,u=n.watermark;const f=new Set;for(;d&&o.size>0;){const p=d;if(f.has(p))return{data:l,nextCursor:p,watermark:u,stale:!0};f.add(p);const v=await r(p);if(v.stale)return{data:l,nextCursor:p,watermark:u,stale:!0};l=uu(l,v,!1);for(const x of v.data)o.delete(x.id);d=v.nextCursor,u=v.watermark??u}return{data:l,nextCursor:d,watermark:u}}function h1(t,n){return!n||t.some(r=>r.id===n.id)?[...t]:[n,...t]}function g1(t,n){if(!ps(t))return null;const r=Array.isArray(t.workspaces)?t.workspaces.filter(i=>ps(i)&&i.agentType===n&&typeof i.workspaceId=="string"&&typeof i.name=="string"&&Array.isArray(i.roots)&&i.roots.every(o=>typeof o=="string")&&typeof i.order=="number"&&(i.canCreateSession===void 0||typeof i.canCreateSession=="boolean")):[],s={};if(ps(t.sessions))for(const[i,o]of Object.entries(t.sessions))!ps(o)||!Array.isArray(o.data)||(s[i]={data:o.data.filter(l=>ps(l)&&l.agentType===n&&typeof l.id=="string"),nextCursor:typeof o.nextCursor=="string"?o.nextCursor:null,loaded:o.loaded===!0});return{workspaces:r,nextCursor:typeof t.nextCursor=="string"?t.nextCursor:null,watermark:typeof t.watermark=="string"?t.watermark:null,expandedWorkspaceIds:Array.isArray(t.expandedWorkspaceIds)?t.expandedWorkspaceIds.filter(i=>typeof i=="string"):[],selectedWorkspaceId:typeof t.selectedWorkspaceId=="string"?t.selectedWorkspaceId:null,selectedSessionId:typeof t.selectedSessionId=="string"?t.selectedSessionId:null,sidebarScrollTop:typeof t.sidebarScrollTop=="number"&&t.sidebarScrollTop>=0?t.sidebarScrollTop:0,sessions:s}}function m1(t){return typeof t=="string"&&du.includes(t)}function ps(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function x1(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)||/^\\\\[^\\/]+[\\/][^\\/]+/.test(t)}function b1(t,n){if(n.webShell||n.isInvalid||!n.supported)return null;const r=t.description;return!r||/[\0\r\n]/.test(r)||!x1(r)?null:r}function y1(t){return{request:(n,r)=>t.fileWorkspaceRequest(n,r),subscribe:(n,r)=>n!=="fs:event"?()=>{}:t.onFileWorkspaceEvent(r)}}function v1(t){try{const n=new URL(t);return n.protocol!=="http:"&&n.protocol!=="https:"?null:n.toString()}catch{return null}}async function w1(){var t;try{const n=window.sharedServiceApi;if(!(n!=null&&n.request))return null;const r=await n.request("/api/flow-studio/config","GET");if(r.status!==200)return null;const s=(t=JSON.parse(r.body).entryUrl)==null?void 0:t.trim();return s?v1(s):null}catch{return null}}function k1({authoritativeStatus:t,locallyRunning:n,needsInput:r,stale:s}){return t==="failed"||t==="error"?"error":s&&!n?"stale":n||t==="running"?r?"needs-input":"running":"idle"}function j1(t,n){const r=new Set;t&&r.add(t);for(const s of n)s&&r.add(s);return[...r]}function S1(t,n,r){return[...t].filter(s=>!n.has(s)&&!r.has(s))}function $c(t,n){var i;const r={},s={};for(const[o,l]of Object.entries(t)){const d=l.data;r[o]=na(d.filter(u=>!u.parentSessionId),n);for(const u of d.filter(f=>f.parentSessionId))(s[i=u.parentSessionId]??(s[i]=[])).push(u)}for(const o of Object.values(s))o.sort((l,d)=>l.created.localeCompare(d.created));return{roots:r,children:s,projectIds:new Set(Object.entries(t).filter(([,o])=>o.loaded).map(([o])=>o))}}function Hc(t,n,r){return t==="codex"&&(n==null?void 0:n.canCreateSession)!==!1?!0:r}function qo(t){return{id:t.workspaceId,name:t.name,description:t.roots[0]??"",created:t.updatedAt??"",updated:t.updatedAt??"",agentType:t.agentType,source:t.source,canCreateSession:t.canCreateSession}}function Uc(){return e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M3 6h18"}),e.jsx("path",{d:"M8 6V4h8v2"}),e.jsx("path",{d:"M19 6l-1 14H6L5 6"}),e.jsx("path",{d:"M10 11v5M14 11v5"})]})}function qc(t,n){n&&t.detail>0&&t.currentTarget.blur()}function C1(){const t=document.activeElement;t instanceof HTMLElement&&(t.matches("input, textarea, select")||t.isContentEditable)&&t.blur()}function I1(){var Pn,Os,wr,Zr,es,$s;const[t]=a.useState(u1),n=t.activeAgent,r=t.agents[n]??Bc(),[s]=a.useState(()=>$c(r.sessions,n)),i=a.useRef(t),[o,l]=a.useState(n),d=a.useRef(o);d.current=o;const[u,f]=a.useState(r.workspaces.map(qo)),[p,v]=a.useState(r.nextCursor),[x,w]=a.useState(r.watermark),[j,E]=a.useState(!1),[S,C]=a.useState(!1),[k,z]=a.useState(null),[M,H]=a.useState(!1),[L,T]=a.useState(s.roots),[A,R]=a.useState(""),[$,F]=a.useState(!1),[Ee,Qe]=a.useState(10),[ae,ke]=a.useState(null),[De,Ie]=a.useState(!1),[We,at]=a.useState(null),[Ge,ne]=a.useState(!1),[be,Ye]=a.useState(null),W=a.useRef(!1),[te,G]=a.useState([]),[le,pe]=a.useState(s.children),ye=a.useRef(L),we=a.useRef(le);ye.current=L,we.current=le;const[Te,ut]=a.useState(s.projectIds),[lt,st]=a.useState(new Set),[Tt,He]=a.useState({}),[Nt,ct]=a.useState(new Set),[B,Y]=a.useState(Object.fromEntries(Object.entries(r.sessions).map(([g,_])=>[g,_.nextCursor]))),q=a.useRef(new Map),se=a.useRef(new Map),[ee,Ke]=a.useState(r.selectedWorkspaceId),[dt,Jt]=a.useState(r.selectedSessionId),Ze=a.useRef(ee),$e=a.useRef(dt);Ze.current=ee,$e.current=dt;const[Gt,rt]=a.useState(new Set),[Pt,ht]=a.useState(new Set(r.expandedWorkspaceIds)),[_t,ln]=a.useState(new Set),[vn,Ue]=a.useState(!1),[Dt,Xn]=a.useState(!1),[$n,cn]=a.useState(!1),[X,dn]=a.useState("settings"),Zt=et(g=>g.setTodos),wt=bn(g=>g.skin),Rt=bn(g=>g.layout),gt=bn(g=>g.wakeEnabled),Wt=bn(g=>g.wakeWord),mt=bn(g=>g.setSkin),wn=bn(g=>g.setLayout),Yn=bn(g=>g.setWakeEnabled),Jn=bn(g=>g.setWakeWord),en=bn(g=>g.autoSpeak),Hn=bn(g=>g.setAutoSpeak),tn=bn(g=>g.runningFirst),Zn=bn(g=>g.setRunningFirst),kn=bn(g=>g.pinnedSessionIds),un=bn(g=>g.togglePinnedSession),ar=bn(g=>g.removePinnedSessions),jn=new Set(kn),Un=et(g=>g.runningSessionId),Ne=et(Op(g=>Object.entries(g.messagesBySession).filter(([,_])=>_.some(U=>U.askUser&&!U.askUser.answered)).map(([_])=>_))),it=a.useCallback((g,_=g.projectId)=>k1({authoritativeStatus:g.status,locallyRunning:Un===g.id,needsInput:Ne.includes(g.id),stale:!!(_&&(Nt.has(_)||Tt[_]))}),[Tt,Un,Ne,Nt]),Ht=a.useCallback(g=>{const _=it(g);return _==="running"||_==="needs-input"},[it]),er=()=>{ht(new Set),rt(new Set(Object.keys(le)))},Wn=()=>{const g=u.filter(U=>!_t.has(U.id)),_=g.map(U=>U.id);ht(new Set(_)),rt(new Set);for(const U of g){const V=U.id;if(Vt.current.has(V))continue;const K=fn.current.has(V),Re=Hc(d.current,U,K);Ce(V,{refresh:Re,background:K})}},Ft=Vo(),I=Xu(),Q=Ft&&I,[fe,ze]=a.useState(!1),[ge,Ut]=a.useState(!1),[rn,pt]=a.useState("files"),[Sn,hr]=a.useState(null),[hs,lr]=a.useState(null),Bt=a.useMemo(()=>{var g;return!Ft&&typeof((g=window.agentApi)==null?void 0:g.fileWorkspaceRequest)=="function"?y1(window.agentApi):null},[Ft]),sn=a.useCallback(g=>{if(Ft){Mh(g);return}Bt&&(pt("files"),Ut(!0),hr(g),lr(_=>({path:g,requestId:((_==null?void 0:_.requestId)??0)+1})))},[Bt,Ft]);a.useEffect(()=>{hr(null),lr(null)},[ee]);const[tr,gr]=a.useState(!1),[qt,Xr]=a.useState(null),[Yr,Mn]=a.useState(0),[cr,on]=a.useState(void 0),pn=a.useRef(null),qn=a.useRef(!1),[gs,mr]=a.useState(null),An=a.useRef(null),xt=a.useRef(!1),kt=a.useRef(u);kt.current=u;const Tn=a.useRef(_t);Tn.current=_t;const fn=a.useRef(Te);fn.current=Te;const Vt=a.useRef(lt);Vt.current=lt;const Nn=a.useRef(null);a.useEffect(()=>{document.documentElement.setAttribute("data-skin",wt)},[wt]),a.useEffect(()=>{document.body.classList.toggle("layout-compact",Rt==="compact")},[Rt]),a.useEffect(()=>{var V;const g=u.map((K,Re)=>({agentType:o,workspaceId:K.id,name:K.name,roots:K.description?[K.description]:[],order:Re,updatedAt:K.updated||void 0,source:K.source??(K.agentType==="claude-code"?"derived":"native"),canCreateSession:K.canCreateSession})),_=Object.fromEntries(u.map(K=>[K.id,{data:[...L[K.id]??[],...Object.values(le).flat().filter(Re=>(L[K.id]??[]).some(me=>me.id===Re.parentSessionId))],nextCursor:B[K.id]??null,loaded:Te.has(K.id)}])),U={...i.current,version:2,activeAgent:o,agents:{...i.current.agents,[o]:{workspaces:g,nextCursor:p,watermark:x,expandedWorkspaceIds:[...Pt],selectedWorkspaceId:ee,selectedSessionId:dt,sidebarScrollTop:((V=Nn.current)==null?void 0:V.scrollTop)??0,sessions:_}}};i.current=U,Oc(U)},[o,le,Pt,Te,u,ee,dt,B,L,p,x]);const nr=a.useCallback(()=>{if(!window.agentApi||!gt||qn.current||pn.current)return;const g=()=>{Df()&&!pn.current&&(pn.current=Ff({wakeWord:Wt,onWake:_=>{var U;on(_),Mn(V=>V+1),(U=window.agentApi)==null||U.showWindow()},onError:_=>console.warn("[wake]",_)}))};typeof window.agentApi.wakeStart=="function"?(qn.current=!0,window.agentApi.wakeStart(Wt).then(_=>{_.ok||(qn.current=!1,g())}).catch(()=>{qn.current=!1,g()})):g()},[gt,Wt]);a.useEffect(()=>{var g;if((g=window.agentApi)!=null&&g.onWake)return window.agentApi.onWake(_=>{qn.current=!1,on(_),Mn(U=>U+1)})},[]),a.useEffect(()=>{var g;if((g=window.agentApi)!=null&&g.onWakeAiHub)return window.agentApi.onWakeAiHub(()=>{cn(!0),wn("focus")})},[]),a.useEffect(()=>{var g;if((g=window.agentApi)!=null&&g.onWakeCommand)return window.agentApi.onWakeCommand(_=>{var Re;const U=((_==null?void 0:_.text)||"").trim();if(!U)return;const V=An.current&&Date.now()<An.current.until?An.current:null;if(V){V.until=Date.now()+9e4,Jt(V.sessionId),(Re=window.agentApi)==null||Re.wakeConversation(!0),mr({text:U,projectId:null,sessionId:V.sessionId,nonce:Date.now()}),Je(`语音追问:${U.length>40?U.slice(0,40)+"…":U}`),Lt("success"),setTimeout(()=>Je(null),4e3);return}const K=kt.current.find(me=>me.name&&U.includes(me.name)&&!Tn.current.has(me.id));K&&(Ke(K.id),ht(me=>{const Le=new Set(me);return Le.add(K.id),Le})),Jt(null),xt.current=!0,Hn(!0),mr({text:U,projectId:(K==null?void 0:K.id)??null,nonce:Date.now()}),Je(`语音指令:${U.length>40?U.slice(0,40)+"…":U}${K?`(项目:${K.name})`:""}`),Lt("success"),setTimeout(()=>Je(null),4e3)})},[]);const Nr=a.useCallback(async()=>{window.agentApi&&(nr(),await window.agentApi.hideWindow())},[nr]),Ot=a.useCallback(g=>{Ue(!1),Xr({right:g.right,bottom:g.bottom}),gr(_=>!_)},[]),xr=a.useCallback(()=>{gr(!1),Ue(g=>!g)},[]);a.useEffect(()=>{if(!tr)return;const g=()=>{const U=document.querySelector(".chat-header-action--appearance");if(!U)return;const V=U.getBoundingClientRect();Xr(K=>(K==null?void 0:K.right)===V.right&&K.bottom===V.bottom?K:{right:V.right,bottom:V.bottom})},_=window.requestAnimationFrame(g);return window.addEventListener("resize",g),()=>{window.cancelAnimationFrame(_),window.removeEventListener("resize",g)}},[Rt,tr]),a.useEffect(()=>{window.agentApi&&nr()},[nr]),a.useEffect(()=>{const g=()=>{var _;(_=pn.current)==null||_.stop(),pn.current=null};return window.addEventListener("focus",g),()=>window.removeEventListener("focus",g)},[]),a.useEffect(()=>{var g,_;gt||((g=pn.current)==null||g.stop(),pn.current=null,qn.current=!1,(_=window.agentApi)==null||_.wakeStop())},[gt]),a.useEffect(()=>{!gt||!window.agentApi||qn.current&&window.agentApi.wakeStart(Wt)},[Wt]),a.useEffect(()=>()=>{var g;(g=pn.current)==null||g.stop()},[]);const Cn=[...Object.values(L).flat(),...Object.values(le).flat()],dr=Vm(Cn,g=>jn.has(g.id)),_n=Object.entries(L).flatMap(([g,_])=>_.filter(U=>jn.has(U.id)).map(U=>({projectId:g,session:U,created:U.created}))),_r=na(_n,o),br=tn?vc(_r,({session:g})=>Ht(g)):_r,Ls=Cn,rr=A.trim().toLowerCase(),ur=rr?dr.filter(g=>g.title.toLowerCase().includes(rr)||(g.cwd||"").toLowerCase().includes(rr)):null,Kt=dt?Ls.find(g=>g.id===dt):void 0,Qt=Kt==null?void 0:Kt.title,b=(Kt==null?void 0:Kt.cwd)||((Pn=u.find(g=>g.id===ee))==null?void 0:Pn.description)||null,N=u.filter(g=>!_t.has(g.id)).map(g=>g.id),D=[...u.filter(g=>!_t.has(g.id)),...u.filter(g=>_t.has(g.id))],re=N.length>0&&N.every(g=>!Pt.has(g)),[ce,Ve]=a.useState(300),[Pe,qe]=a.useState(!1),Xe=a.useRef(!1),jt=a.useRef(0),zt=a.useRef(0),$t=a.useCallback(g=>{if(!Xe.current)return;const _=Math.min(480,Math.max(160,zt.current+g.clientX-jt.current));Ve(_)},[]),Vn=a.useCallback(()=>{Xe.current=!1,qe(!1),document.removeEventListener("mousemove",$t),document.removeEventListener("mouseup",Vn)},[$t]),zn=a.useCallback(g=>{Xe.current=!0,qe(!0),jt.current=g.clientX,zt.current=ce,document.addEventListener("mousemove",$t),document.addEventListener("mouseup",Vn)},[ce,$t,Vn]),[yr,Je]=a.useState(null),[zr,Lt]=a.useState("success"),[Ln,Lr]=a.useState(null),[sr,ui]=a.useState(!1),pi=a.useCallback(async()=>{if(!sr){ui(!0);try{const g=await w1();if(g){cn(!1),ze(!1),Lr(g);return}Je("Flow Studio 入口不可用,请检查服务配置"),Lt("error"),setTimeout(()=>Je(null),4e3)}finally{ui(!1)}}},[sr]),hn=g=>{Ze.current=g.projectId,$e.current=g.sessionId,Ke(g.projectId),Jt(g.sessionId),g.sessionId||Zt([])},fi=g=>{var me;if(g===d.current)return;const _=d.current,U=i.current.agents[_];U&&(i.current={...i.current,agents:{...i.current.agents,[_]:{...U,sidebarScrollTop:((me=Nn.current)==null?void 0:me.scrollTop)??U.sidebarScrollTop}}});const V=i.current.agents[g]??Bc(),K=$c(V.sessions,g),Re=V.workspaces.map(qo);d.current=g,kt.current=Re,l(g),f(Re),v(V.nextCursor),w(V.watermark),E(!1),C(!1),z(null),ye.current=K.roots,we.current=K.children,T(K.roots),pe(K.children),ut(K.projectIds),fn.current=K.projectIds,st(new Set),Vt.current=new Set,He({}),ct(new Set),Y(Object.fromEntries(Object.entries(V.sessions).map(([Le,Fe])=>[Le,Fe.nextCursor]))),ht(new Set(V.expandedWorkspaceIds)),ln(new Set),hn({projectId:V.selectedWorkspaceId,sessionId:V.selectedSessionId}),window.requestAnimationFrame(()=>{Nn.current&&(Nn.current.scrollTop=V.sidebarScrollTop)}),Gn(g,{refresh:V.workspaces.length>0,since:V.watermark})},[Ps,ms]=a.useState([]),Pr=a.useCallback(g=>{ms(_=>_.filter(U=>U.id!==g))},[]),an=a.useCallback(g=>{const _=crypto.randomUUID();ms(U=>[...U,{...g,id:_}]),setTimeout(()=>Pr(_),12e3)},[Pr]);async function Gn(g=d.current,_={}){if(!window.agentApi)return;const U=(se.current.get(g)??0)+1;se.current.set(g,U),E(!0),z(null);try{const V=await window.agentApi.listAgentWorkspaces(g,{cursor:_.cursor,limit:50,refresh:_.refresh,since:_.refresh?_.since??x:null});if(d.current!==g||se.current.get(g)!==U)return;const K=kt.current.map((_e,Et)=>({agentType:g,workspaceId:_e.id,name:_e.name,roots:_e.description?[_e.description]:[],order:Et,updatedAt:_e.updated,source:_e.source??(g==="claude-code"?"derived":"native"),canCreateSession:_e.canCreateSession})),me=p1(K,V,!_.cursor).map(qo);kt.current=me,f(me),v(V.nextCursor),w(V.watermark),C(V.stale===!0);const Le=new Set(me.map(_e=>_e.id)),Fe=Ze.current;Fe&&!Le.has(Fe)&&hn(Po);const nn=new Set([...fn.current].filter(_e=>Le.has(_e)));Fe&&Le.has(Fe)&&nn.add(Fe),T(_e=>Object.fromEntries(Object.entries(_e).filter(([Et])=>Le.has(Et)))),ut(_e=>{const Et=new Set([..._e].filter(In=>Le.has(In)));return fn.current=Et,Et}),st(_e=>{const Et=new Set([..._e].filter(In=>Le.has(In)));return Vt.current=Et,Et}),He(_e=>Object.fromEntries(Object.entries(_e).filter(([Et])=>Le.has(Et))));const Fn=new Set;if(await Promise.all(me.map(async _e=>{_e.description&&!await window.agentApi.checkProjectPath(_e.description)&&Fn.add(_e.id)})),d.current!==g||se.current.get(g)!==U)return;if(ln(Fn),_.refreshLoadedSessions!==!1)for(const _e of nn)Fn.has(_e)||Vt.current.has(_e)||Ce(_e,{refresh:!0,background:!0})}catch(V){d.current===g&&(kt.current.length>0&&C(!0),z(V instanceof Error?V.message:"目录加载失败"))}finally{d.current===g&&se.current.get(g)===U&&E(!1)}}async function Ce(g,_={}){var me;const U=window.agentApi;if(!U)return;const V=d.current,K=`${V}:${g}`,Re=(q.current.get(K)??0)+1;q.current.set(K,Re),st(Le=>{const Fe=new Set(Le).add(g);return Vt.current=Fe,Fe}),He(Le=>{if(!(g in Le))return Le;const Fe={...Le};return delete Fe[g],Fe});try{const Le=await U.listAgentWorkspaceSessions(V,g,{cursor:_.cursor,limit:20,refresh:_.refresh});if(d.current!==V||q.current.get(K)!==Re)return;const Fe=ye.current[g]??[],nn=_.pendingSession?{..._.pendingSession,projectId:g}:void 0,Fn=nn?[nn,...Fe.filter(tt=>tt.id!==nn.id)]:Fe,_e=new Set(Fn.map(tt=>tt.id)),Et=[...Fn,...[..._e].flatMap(tt=>we.current[tt]??[])],In=_.refresh&&!_.cursor?await f1(Et,Le,tt=>U.listAgentWorkspaceSessions(V,g,{cursor:tt,limit:200,refresh:!1}),nn==null?void 0:nn.id):Le;if(d.current!==V||q.current.get(K)!==Re)return;const St=uu(Et,In,!_.cursor).map(tt=>({...tt,projectId:tt.projectId??g})),Rn=na(St.filter(tt=>!tt.parentSessionId),V),Wr=Ze.current,ir=$e.current,ts=h1(Rn,nn);Wr===g&&ir&&!St.some(tt=>tt.id===ir)&&!ts.some(tt=>tt.id===ir)&&hn(Po);const Kn={};for(const tt of St.filter(ft=>ft.parentSessionId))(Kn[me=tt.parentSessionId]??(Kn[me]=[])).push(tt);for(const tt of Object.values(Kn))tt.sort((ft,ns)=>ft.created.localeCompare(ns.created));Y(tt=>({...tt,[g]:In.nextCursor})),ct(tt=>{const ft=new Set(tt);return In.stale?ft.add(g):ft.delete(g),ft});const Fr={...ye.current,[g]:ts},kr={...we.current};for(const tt of _e)delete kr[tt];for(const[tt,ft]of Object.entries(Kn))kr[tt]=ft;ye.current=Fr,we.current=kr,T(Fr),pe(kr),ut(tt=>{const ft=new Set(tt).add(g);return fn.current=ft,ft})}catch(Le){if(q.current.get(K)!==Re)return;ct(Fe=>new Set(Fe).add(g)),He(Fe=>({...Fe,[g]:Le instanceof Error?Le.message:"会话加载失败"}))}finally{q.current.get(K)===Re&&st(Le=>{const Fe=new Set(Le);return Fe.delete(g),Vt.current=Fe,Fe})}}const Jr=async g=>{if(!window.agentApi)return;const _=await window.agentApi.listChildSessions(g);pe(U=>({...U,[g]:_.sort((V,K)=>V.created<K.created?-1:1)}))},vr=async(g,_)=>{if(!window.agentApi)return;const U=kt.current.find(V=>V.id===g);if(!U||U.canCreateSession===!1){Je("请先选择目录"),Lt("info"),setTimeout(()=>Je(null),3e3);return}if(!W.current){W.current=!0,Ye({projectId:g,agentType:_});try{const V=(U==null?void 0:U.source)==="imported"?void 0:g,K=await window.agentApi.createSession("新会话",V,_,U==null?void 0:U.description);if(d.current!==_)return;const Re=K.projectId===g?K:{...K,projectId:g},me={...ye.current,[g]:[Re,...(ye.current[g]??[]).filter(Le=>Le.id!==K.id)]};ye.current=me,T(me),hn({projectId:g,sessionId:K.id}),Q&&ze(!1),_==="customer-agent"&&Ce(g,{refresh:!0,background:!0,pendingSession:Re})}catch(V){Je(V instanceof Error?V.message:"新建会话失败"),Lt("error"),setTimeout(()=>Je(null),3e3)}finally{W.current=!1,Ye(null)}}},xs=()=>{const g=kt.current.find(_=>_.id===ee);if(!ee||(g==null?void 0:g.canCreateSession)===!1){Je("请先选择目录"),Lt("info"),setTimeout(()=>Je(null),3e3);return}vr(ee,o)};a.useEffect(()=>{var g;window.agentApi&&(Gn(d.current,{refresh:(((g=i.current.agents[d.current])==null?void 0:g.workspaces.length)??0)>0}),qi.getState().loadFromSystem(),window.agentApi.getRuntimeHealth().then(G).catch(()=>{}))},[]),a.useEffect(()=>{const g=window.setInterval(()=>{document.visibilityState!=="visible"||j||Gn(o,{refresh:!0,since:x,refreshLoadedSessions:!1})},15e3);return()=>window.clearInterval(g)},[o,j,x]),a.useEffect(()=>{if(!window.agentApi)return;let g=!1;const _=()=>{if(g||document.visibilityState!=="visible")return;const K=j1(ee,Pt),Re=S1(K,Tn.current,Vt.current);for(const me of Re)Ce(me,{refresh:!0,background:fn.current.has(me)})},U=()=>{document.visibilityState==="visible"&&_()},V=window.setInterval(_,1e4);return window.addEventListener("focus",_),document.addEventListener("visibilitychange",U),()=>{g=!0,window.clearInterval(V),window.removeEventListener("focus",_),document.removeEventListener("visibilitychange",U)}},[o,Pt,ee]),a.useEffect(()=>{if(!ee||!window.agentApi)return;const g=u.find(U=>U.id===ee),_=g==null?void 0:g.description;_&&window.agentApi.setProjectWorkingDir(_)},[ee,u]);const Ds=g=>{hn(wc(g));const _=!Pt.has(g);if(ht(U=>{const V=new Set(U);return _?V.add(g):V.delete(g),V}),_&&!Vt.current.has(g)){const U=fn.current.has(g),V=kt.current.find(Re=>Re.id===g),K=Hc(d.current,V,U);Ce(g,{refresh:K,background:U})}},Ws=async g=>{if(!window.agentApi)throw new Error("agentApi 未就绪,请重启应用");const _=g.replace(/\\/g,"/"),U=_.split("/").filter(Boolean),V=U[U.length-1]||_||"导入的项目",K=await window.agentApi.importAgentWorkspace(d.current,_,V);await Gn(d.current,{refresh:!0,refreshLoadedSessions:!1}),hn(wc(K.workspace.workspaceId)),await Ce(K.workspace.workspaceId,{refresh:!0}),ht(Re=>{const me=new Set(Re);return me.add(K.workspace.workspaceId),me}),Je(K.existing?"该文件夹已在当前 Agent 的目录中":`已导入:${K.workspace.name}`),Lt(K.existing?"info":"success"),setTimeout(()=>Je(null),3e3)},Xi=async()=>{try{if(!window.agentApi){Je("agentApi 未就绪,请重启应用"),Lt("error");return}if(Ft){H(!0);return}const g=await window.agentApi.openFileDialog();if(console.log("[import] selectedPath:",g),!g)return;await Ws(g)}catch(g){console.error("[import] error:",g),Je(g instanceof Error?g.message:String(g)),Lt("error"),setTimeout(()=>Je(null),5e3)}},hi=async g=>{if(window.agentApi)try{await window.agentApi.deleteProject(g),ee===g&&(Ke(null),Jt(null),Zt([])),Je("项目删除成功"),Lt("success"),setTimeout(()=>Je(null),2500),await Gn()}catch(_){Je(_ instanceof Error?_.message:"项目删除失败"),Lt("error"),setTimeout(()=>Je(null),4e3)}},Fs=(g,_,U)=>{var Re;const V=(Re=window.agentApi)==null?void 0:Re.showDirectoryContextMenu,K=b1(_,{isInvalid:U,supported:typeof V=="function",webShell:Ft});!K||!V||(g.preventDefault(),V(K).catch(me=>{Je(me instanceof Error?me.message:"无法打开当前文件夹"),Lt("error"),setTimeout(()=>Je(null),4e3)}))},pr=(g,_)=>{ke({session:g,anchor:_})},gn=(g,_)=>{const U=_.getBoundingClientRect();at({project:g,anchor:{top:U.top,left:U.left,width:U.width,height:U.height}})},Bs=async()=>{if(!window.agentApi||!We||Ge)return;const{project:g}=We,_=d.current;ne(!0);try{let U=null,V=0;do{const K=await window.agentApi.listAgentWorkspaceSessions(_,g.id,{cursor:U,limit:50,refresh:U===null});for(const Re of K.data)await window.agentApi.deleteSession(Re.id),V+=1;U=K.data.length>0?K.nextCursor:null}while(U);Ze.current===g.id&&hn(Po),Je(V>0?`已删除目录「${g.name}」及 ${V} 个会话`:`已删除目录「${g.name}」`),Lt("success"),setTimeout(()=>Je(null),2500),await Gn(_,{refresh:!0})}catch(U){Je(U instanceof Error?U.message:"目录删除失败"),Lt("error"),setTimeout(()=>Je(null),4e3)}finally{ne(!1),at(null)}},bs=async()=>{if(!window.agentApi||!ae||De)return;const{session:g}=ae;Ie(!0);try{await window.agentApi.deleteSession(g.id);const _=g.projectId??Ze.current,U=g.agentType;if(_){const Re=`${U}:${_}`;q.current.set(Re,(q.current.get(Re)??0)+1)}const V=Xm(ye.current,we.current,[],g.id);ye.current=V.sessionsByProject,we.current=V.childSessionsByParent,T(V.sessionsByProject),pe(V.childSessionsByParent),ar(V.removedIds);const K=i.current.agents[U];if(K){const Re={...i.current,agents:{...i.current.agents,[U]:Km(K,V.removedIds)}};i.current=Re,Oc(Re)}$e.current&&V.removedIds.includes($e.current)&&hn({projectId:Ze.current,sessionId:null}),Je("会话删除成功"),Lt("success"),setTimeout(()=>Je(null),2500),ke(null),_&&Ce(_,{refresh:!0,background:!0})}catch(_){Je(_ instanceof Error?_.message:"会话删除失败"),Lt("error"),setTimeout(()=>Je(null),4e3)}finally{Ie(!1)}},Yi=[{id:"settings",label:"设置"},{id:"mcp",label:"MCP"},{id:"memory",label:"记忆"},{id:"skill",label:"技能"},{id:"agent",label:"智能体"},{id:"lsp",label:"LSP"}],Dr=(g,_)=>{const U=dt===g.id,V=zo(it(g,_)),K=le[g.id]??[],Re=!Gt.has(g.id);return e.jsxs("div",{className:"sidebar-session-tree",children:[e.jsx(Ho,{session:{id:g.id,title:g.title,visualState:V,statusLabel:Lo[V],occupiedExternally:g.agentType!=="codex"&&g.occupancy==="owned-externally",canDelete:g.canDelete,active:U,hasChildren:K.length>0,expanded:Re,compatibility:g.compatibility,pinned:jn.has(g.id)},onSelect:()=>{Q&&ze(!1),hn(Do(_,g.id)),K.length>0&&rt(me=>{const Le=new Set(me);return Le.has(g.id)?Le.delete(g.id):Le.add(g.id),Le})},onPin:()=>un(g.id),onDelete:me=>pr(g,me)}),e.jsx("div",{className:"sidebar-child-sessions",style:{maxHeight:Re?K.length*40:0,opacity:Re?1:0},children:K.map(me=>{const Le=zo(it(me,_));return e.jsx(Ho,{session:{id:me.id,title:me.title,visualState:Le,statusLabel:Lo[Le],occupiedExternally:me.agentType!=="codex"&&me.occupancy==="owned-externally",canDelete:me.canDelete,active:dt===me.id,child:!0,compatibility:me.compatibility},deleteLabel:"删除子会话",onSelect:()=>{Q&&ze(!1),hn(Do(_,me.id))},onDelete:Fe=>pr(me,Fe)},me.id)})})]},g.id)};return e.jsxs("div",{className:"app-shell",style:{display:"flex",height:Ft?"100dvh":"100vh",width:"100vw",background:"var(--bg-deepest)",position:"relative",overflow:"hidden"},children:[e.jsx(Hm,{}),e.jsx(Um,{}),!Ln&&Q&&fe&&e.jsx("div",{className:"mobile-drawer-scrim",onClick:()=>ze(!1),style:{position:"fixed",inset:0,background:"rgba(0,0,0,.45)",zIndex:1150}}),!Ln&&Q&&!fe&&e.jsx("button",{className:"mobile-drawer-toggle",onClick:()=>ze(!0),"aria-label":"会话列表","aria-expanded":!1,style:{position:"fixed",top:"calc(env(safe-area-inset-top) + 8px)",left:10,zIndex:1250,width:34,height:34,borderRadius:9,border:"1px solid var(--border-default)",background:"var(--bg-glass, rgba(18,20,28,.82))",color:"var(--text-secondary)",display:"grid",placeItems:"center",backdropFilter:"blur(8px)",WebkitAppRegion:"no-drag",cursor:"pointer"},children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:e.jsx("path",{d:"M3 6h18M3 12h18M3 18h18"})})}),e.jsx("div",{className:"app-drag-region",style:{position:"fixed",top:0,left:0,right:0,height:52,zIndex:9999,WebkitAppRegion:"drag",pointerEvents:"none"}}),e.jsx("div",{className:"app-accent-glow",style:{position:"absolute",top:"-120px",left:"-80px",width:320,height:320,borderRadius:"50%",background:"radial-gradient(circle, var(--accent-glow) 0%, transparent 70%)",pointerEvents:"none",zIndex:0}}),Rt!=="focus"&&!Ln&&e.jsxs(e.Fragment,{children:[e.jsxs("aside",{className:"app-sidebar",style:{width:ce,display:"flex",flexDirection:"column",background:"var(--bg-surface)",borderRight:"1px solid var(--border-subtle)",padding:"56px 0 0",position:"relative",zIndex:10,overflow:"hidden",...Q?{position:"fixed",top:0,bottom:0,left:0,width:"min(82vw, 320px)",zIndex:1200,transform:fe?"translateX(0)":"translateX(-103%)",transition:"transform .24s ease",boxShadow:"12px 0 32px rgba(0,0,0,.5)",padding:"calc(env(safe-area-inset-top) + 12px) 0 0"}:{}},children:[e.jsx("div",{className:"app-sidebar-brand",style:{padding:"0 20px 10px"},children:e.jsxs("div",{className:"sidebar-brand-row",children:[e.jsx("div",{className:"sidebar-brand-mark","aria-hidden":"true",children:e.jsx(pa,{agentType:"customer-agent",size:24})}),e.jsx("span",{className:"sidebar-brand-name",children:"AgentRoam"}),!Ft&&e.jsx(kx,{onOpenFlowStudio:pi,openingFlowStudio:sr})]})}),e.jsx(wx,{value:o,health:te,onChange:fi}),e.jsxs("button",{type:"button",className:"sidebar-search-field",onClick:()=>{F(!0),Qe(10)},title:"搜索会话","aria-label":"搜索会话",children:[e.jsx(ua,{size:15,"aria-hidden":"true"}),e.jsx("span",{children:"搜索会话"}),e.jsx("kbd",{children:"⌘ K"})]}),e.jsxs("div",{className:"sidebar-project-toolbar",children:[e.jsxs("div",{className:"sidebar-project-heading",children:[e.jsx("span",{className:"sidebar-project-title",children:"目录"}),e.jsx("span",{className:"sidebar-project-count","aria-label":`${u.length} 个目录`,children:u.length})]}),e.jsxs("div",{className:"sidebar-project-actions",children:[e.jsx("button",{type:"button",onClick:g=>{re?Wn():er(),qc(g,re)},title:re?"展开全部会话":"折叠全部会话","aria-label":re?"展开全部会话":"折叠全部会话","aria-pressed":re,disabled:N.length===0,className:`ui-icon-button sidebar-collapse-all${re?" is-active":""}`,children:e.jsx("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:re?e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"m7 6 5 5 5-5"}),e.jsx("path",{d:"m7 13 5 5 5-5"})]}):e.jsxs(e.Fragment,{children:[e.jsx("path",{d:"m17 11-5-5-5 5"}),e.jsx("path",{d:"m17 18-5-5-5 5"})]})})}),e.jsx("button",{type:"button",onClick:g=>{Zn(!tn),qc(g,tn)},title:tn?"按新建时间排序":"进行中会话优先","aria-label":tn?"按新建时间排序":"进行中会话优先","aria-pressed":tn,className:`ui-icon-button sidebar-session-sort${tn?" is-active":""}`,children:e.jsxs("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[e.jsx("path",{d:"M3 6h10M3 12h7M3 18h4"}),e.jsx("path",{d:"m15 9 3-3 3 3M18 6v12"})]})}),e.jsx("button",{type:"button",onClick:()=>void Xi(),title:"导入目录","aria-label":"导入目录",className:"ui-icon-button",children:e.jsx("svg",{width:"17",height:"17",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})})]})]}),e.jsx("div",{ref:Nn,className:"app-sidebar-scroll",onPointerDownCapture:C1,onScroll:g=>{const _=g.currentTarget;if(_.scrollHeight-_.scrollTop-_.clientHeight<120&&p&&!j&&Gn(o,{cursor:p}),Q){const V=_.getBoundingClientRect(),K=_.querySelectorAll("[data-sidebar-project-id]");for(const Re of K){const me=Re.dataset.sidebarProjectId;if(!me||!Pt.has(me))continue;const Le=Re.getBoundingClientRect();if(Le.bottom<V.top||Le.bottom>V.bottom+120)continue;const Fe=B[me];Fe&&!Vt.current.has(me)&&Ce(me,{cursor:Fe})}}},style:{minHeight:0,flex:1,overflow:"auto",padding:"0 10px"},children:e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:2,marginBottom:12},children:[br.length>0&&e.jsxs("section",{className:"sidebar-pinned-section","aria-label":"置顶会话",children:[e.jsx("div",{className:"sidebar-pinned-heading",children:"置顶"}),br.map(({projectId:g,session:_})=>Dr(_,g))]}),D.map(g=>{var In;const _=ee===g.id&&dt===null,U=Pt.has(g.id),V=Te.has(g.id),K=lt.has(g.id),Re=Tt[g.id],me=L[g.id]??[],Le=me.filter(St=>!jn.has(St.id)),nn=tn?vc(Le,Ht):Le,Fn=nn.length>10,_e=_t.has(g.id),Et=(be==null?void 0:be.agentType)===o&&be.projectId===g.id;return e.jsxs("div",{className:"sidebar-project-block","data-sidebar-project-id":g.id,"aria-busy":K,children:[e.jsxs("div",{className:`sidebar-row sidebar-project-row ${_&&!_e?"sidebar-row-active":""}`,onContextMenu:St=>Fs(St,g,_e),style:{paddingRight:4,opacity:_e?.45:1},children:[e.jsxs("button",{className:"sidebar-project-button",onClick:()=>{_e||Ds(g.id)},disabled:_e,"aria-expanded":U,"aria-pressed":_,title:_e?`路径不存在:${g.description}`:g.name,style:{flex:1,display:"flex",alignItems:"center",gap:8,minWidth:0,padding:"8px 10px",border:"none",background:"transparent",color:_e?"var(--text-muted)":_?"var(--accent)":"var(--text-secondary)",fontSize:13,fontWeight:_&&!_e?600:400,cursor:_e?"not-allowed":"pointer",textAlign:"left",transition:"color 0.15s"},children:[_e?e.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:.6},children:[e.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),e.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),e.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}):g.canCreateSession===!1?e.jsx(pp,{size:13,"aria-hidden":"true",style:{flexShrink:0,opacity:_?1:.5}}):e.jsx("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",style:{flexShrink:0,opacity:_?1:.5},children:U?e.jsx("path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6A2 2 0 0 1 18.46 20H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}):e.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})}),e.jsx("span",{style:{whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},children:g.name})]}),o==="customer-agent"&&!Ft&&g.canCreateSession!==!1?e.jsx("button",{onClick:St=>{St.stopPropagation(),hi(g.id)},title:"删除目录","aria-label":`删除目录:${g.name}`,className:"sidebar-project-delete sidebar-row-action ui-icon-button ui-icon-button--small ui-icon-button--danger",style:{flexShrink:0},children:e.jsx(Uc,{})}):_e?e.jsx("button",{onClick:St=>{St.stopPropagation(),gn(g,St.currentTarget)},title:"删除失效目录","aria-label":`删除失效目录:${g.name}`,className:"sidebar-project-delete sidebar-row-action ui-icon-button ui-icon-button--small ui-icon-button--danger",style:{flexShrink:0},children:e.jsx(Uc,{})}):null,g.canCreateSession!==!1&&e.jsx("button",{type:"button",onClick:St=>{St.stopPropagation(),vr(g.id,o)},title:Et?"正在创建会话":`新建 ${o==="customer-agent"?"Customer Agent":o==="claude-code"?"Claude Code":o==="codex"?"Codex":"OpenCode"} 会话`,"aria-label":Et?"正在创建会话":`在 ${g.name} 中新建会话`,"aria-busy":Et,disabled:be!==null||_e||((In=te.find(St=>St.agentType===o))==null?void 0:In.available)===!1,className:"sidebar-runtime-create sidebar-project-add-action ui-icon-button ui-icon-button--small",children:Et?e.jsx(ot,{size:13,style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true"}):e.jsx(Ko,{size:13,"aria-hidden":"true"})})]}),e.jsx("div",{style:{overflow:"hidden",maxHeight:U?Q?1e5:Fn?300:800:0,opacity:U?1:0,transition:"max-height 0.45s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.3s ease"},children:e.jsxs("div",{className:"sidebar-project-sessions",onScroll:St=>{const Rn=St.currentTarget,Wr=Rn.scrollHeight-Rn.scrollTop-Rn.clientHeight<80,ir=B[g.id];Wr&&ir&&!K&&Ce(g.id,{cursor:ir})},style:{display:"flex",flexDirection:"column",gap:1,marginTop:2,paddingLeft:10,paddingBottom:4,...Fn&&!Q?{maxHeight:280,overflowY:"auto"}:{}},children:[nn.map(St=>Dr(St,g.id)),K&&!V&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:11,padding:"4px 10px",opacity:.7},children:"正在加载会话..."}),Re&&e.jsxs("div",{title:Re,style:{display:"flex",alignItems:"center",gap:8,color:"var(--danger)",fontSize:11,padding:"4px 10px"},children:[e.jsx("span",{style:{flex:1},children:"会话加载失败"}),e.jsx("button",{type:"button",onClick:()=>void Ce(g.id,{refresh:V,background:V}),style:{border:0,background:"transparent",color:"inherit",fontSize:11,cursor:"pointer",padding:0},children:"重试"})]}),Nt.has(g.id)&&!Re&&e.jsx("div",{className:"sidebar-cache-state",children:"显示缓存,会话将在下次刷新时更新"}),me.length===0&&V&&!K&&!Re&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:11,padding:"4px 10px",opacity:.7},children:"暂无会话"})]})})]},g.id)}),u.length===0&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:12,padding:"24px 10px",textAlign:"center",opacity:.7},children:j?"正在加载目录...":"暂无目录"}),u.length>0&&j&&e.jsx("div",{className:"sidebar-cache-state",children:"正在同步目录..."}),S&&!k&&e.jsx("div",{className:"sidebar-cache-state",children:"当前显示缓存目录"}),k&&e.jsxs("div",{className:"sidebar-load-error",title:k,children:[e.jsx("span",{children:u.length>0?"目录刷新失败,当前显示缓存":"目录加载失败"}),e.jsx("button",{type:"button",onClick:()=>void Gn(o,{refresh:u.length>0}),children:"重试"})]})]})}),e.jsx("div",{className:"sidebar-bottom-action",children:e.jsx("button",{type:"button",className:"sidebar-new-session-primary",disabled:be!==null||ee!==null&&_t.has(ee)||((Os=te.find(g=>g.agentType===o))==null?void 0:Os.available)===!1,"aria-busy":be!==null,"aria-disabled":be!==null||!ee||((wr=u.find(g=>g.id===ee))==null?void 0:wr.canCreateSession)===!1,title:be?"正在创建会话":ee&&((Zr=u.find(g=>g.id===ee))==null?void 0:Zr.canCreateSession)!==!1?"新建会话":"请先选择目录",onClick:xs,children:be?e.jsxs(e.Fragment,{children:[e.jsx(ot,{size:16,style:{animation:"spin 0.8s linear infinite"},"aria-hidden":"true"}),e.jsx("span",{children:"正在创建..."})]}):e.jsxs(e.Fragment,{children:[e.jsx(Ko,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:"新建会话"})]})})})]}),ae&&e.jsx(Tc,{message:Gm(ae.session),anchor:ae.anchor,mobile:Q,pending:De,onCancel:()=>ke(null),onConfirm:()=>void bs()}),We&&e.jsx(Tc,{title:"删除失效目录",message:`目录「${We.project.name}」的路径(${We.project.description||"未知"})已不存在。删除将同时归档其下的全部会话记录,确定删除吗?`,anchor:We.anchor,mobile:Q,pending:Ge,onCancel:()=>at(null),onConfirm:()=>void Bs()}),!Q&&e.jsx("div",{className:`app-sidebar-resizer${Pe?" is-dragging":""}`,onMouseDown:zn,style:{left:ce}}),$&&e.jsx("div",{onClick:()=>F(!1),style:{position:"fixed",inset:0,zIndex:1300,background:"rgba(17,24,39,0.34)",backdropFilter:"blur(2px)",WebkitBackdropFilter:"blur(2px)",display:"flex",alignItems:"flex-start",justifyContent:"center",padding:"12vh 16px 16px"},children:e.jsxs("div",{onClick:g=>g.stopPropagation(),style:{width:"min(560px, 100%)",maxHeight:"64vh",display:"flex",flexDirection:"column",borderRadius:12,border:"1px solid var(--border-default)",background:"var(--bg-surface)",boxShadow:"0 18px 48px rgba(17,24,39,0.28)",overflow:"hidden"},children:[e.jsx("div",{style:{padding:10,borderBottom:"1px solid var(--border-subtle)"},children:e.jsx("input",{autoFocus:!0,value:A,onChange:g=>R(g.target.value),onKeyDown:g=>{g.key==="Escape"&&F(!1)},placeholder:"搜索所有会话(标题或目录)…","aria-label":"搜索所有会话",style:{width:"100%",padding:"9px 12px",borderRadius:8,border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-primary)",fontSize:14,outline:"none",fontFamily:"var(--font-body)",boxSizing:"border-box"}})}),e.jsxs("div",{style:{overflowY:"auto",padding:8},children:[rr&&ur&&ur.length>0&&e.jsxs("div",{style:{padding:"4px 10px 3px",fontSize:9,fontWeight:700,letterSpacing:"0.08em",textTransform:"uppercase",color:"var(--text-muted)"},children:[ur.length," 个结果"]}),rr&&ur&&ur.length===0&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:12,padding:"16px 10px",textAlign:"center",opacity:.7},children:"无匹配会话"}),!rr&&dr.length===0&&e.jsx("div",{style:{color:"var(--text-muted)",fontSize:12,padding:"16px 10px",textAlign:"center",opacity:.7},children:"暂无会话"}),(ur??dr.slice(0,Ee)).map(g=>{const _=dt===g.id,U=zo(it(g));return e.jsx(Ho,{session:{id:g.id,title:g.title,visualState:U,statusLabel:Lo[U],occupiedExternally:g.agentType!=="codex"&&g.occupancy==="owned-externally",canDelete:g.canDelete,active:_,child:!!g.parentSessionId,compatibility:g.compatibility,pinned:jn.has(g.id)},onSelect:()=>{const V=g.projectId&&u.some(K=>K.id===g.projectId)?g.projectId:null;hn(Do(V,g.id)),F(!1),Q&&ze(!1)},onPin:g.parentSessionId?void 0:()=>un(g.id),onDelete:V=>pr(g,V)},g.id)}),!rr&&dr.length>Ee&&e.jsx("button",{type:"button",onClick:()=>Qe(g=>g+10),style:{width:"100%",padding:"8px 10px",border:0,borderTop:"1px solid var(--border-subtle)",background:"transparent",color:"var(--text-muted)",fontSize:12,cursor:"pointer",textAlign:"center"},children:"更多…"})]})]})})]}),e.jsx(nu,{message:yr,type:zr}),e.jsxs("main",{className:`app-main${Bt?" file-workspace-capable":""}${ge&&Bt?" file-workspace-open":""}${ge&&Bt&&Sn?" file-workspace-preview-open":""}`,style:{flex:1,overflow:"hidden",background:"var(--bg-workspace)",position:"relative",zIndex:5},children:[Rt==="focus"&&!Ln&&e.jsx("button",{onClick:()=>wn("standard"),title:"返回标准布局",style:{position:"absolute",top:12,left:12,zIndex:100,padding:"5px 10px",borderRadius:8,border:"1px solid var(--border-default)",background:"var(--bg-glass)",color:"var(--text-muted)",fontSize:11,cursor:"pointer",backdropFilter:"blur(8px)",WebkitAppRegion:"no-drag"},children:"← 侧边栏"}),e.jsx("div",{className:"app-chat-surface",style:{height:"100%",paddingTop:0,display:$n?"none":void 0,background:"var(--chat-history-bg)"},children:e.jsx(Im,{activeAgentType:o,selectedProjectId:ee,selectedSessionId:dt,sessionTitle:Qt,sessionSummary:Kt,workspacePath:b,voiceCommand:gs,onOpenSettings:xr,settingsOpen:vn,desktopLiveOpen:Dt,fileDrawerOpen:ge,onOpenArtifact:sn,onToggleFiles:Bt?()=>{Ut(g=>!g),pt("files")}:void 0,onOpenDesktopLive:!Ft&&((es=window.agentApi)!=null&&es.desktopLiveGetStatus)?()=>Xn(!0):void 0,onHideToBackground:()=>void Nr(),onOpenHub:($s=window.agentApi)!=null&&$s.hubGetConfig?()=>cn(!0):void 0,onToggleAppearance:Ot,appearanceOpen:tr,hideToBackgroundTitle:gt?`隐藏到后台(说“${Wt}”唤醒)`:"隐藏到后台",onSessionCreated:async(g,_)=>{var V;const U=Ze.current;hn({projectId:U,sessionId:g}),xt.current&&(xt.current=!1,An.current={sessionId:g,until:Date.now()+9e4},(V=window.agentApi)==null||V.wakeConversation(!0)),U&&await Ce(U,{pendingSession:_})},onSubSessionCreated:async g=>{await Jr(g)},onSelectSession:g=>{Jt(g)},onSubAgentEvent:g=>{g.type==="started"?an({type:"info",title:"子会话已启动",body:`${g.agentName}:${g.task.slice(0,60)}`,sessionId:g.subSessionId}):g.type==="completed"?an({type:"success",title:"子会话已完成",body:`${g.agentName}:${g.task.slice(0,60)}`,sessionId:g.subSessionId}):an({type:"error",title:"子会话出错",body:`${g.agentName}:${g.task.slice(0,60)}`,sessionId:g.subSessionId})},onMessageSent:(g,_)=>{T(U=>{const V={};for(const[K,Re]of Object.entries(U))V[K]=Re.map(me=>me.id===g?{...me,title:_.slice(0,60)||me.title}:me);return V})},onRunComplete:async(g,_)=>{var Re;const U=An.current,V=Jg(U,_);An.current=V,V!==U&&((Re=window.agentApi)==null||Re.wakeConversation(!0));const K=g||ee;K&&await Ce(K,{refresh:!0,background:!0})}})}),$n&&e.jsx(Fm,{conversationId:dt,onExit:()=>cn(!1)}),Bt&&e.jsx(c1,{open:ge,tab:rn,gateway:Bt,cwd:b,selectedPath:Sn,revealRequest:hs,onTabChange:pt,onSelectPath:hr,onClose:()=>Ut(!1)}),Ln&&e.jsx(jx,{entryUrl:Ln,onBack:()=>Lr(null)})]}),Dt&&e.jsx(cx,{onClose:()=>Xn(!1)}),vn&&On.createPortal(e.jsx("div",{onClick:()=>Ue(!1),style:{position:"fixed",inset:0,zIndex:10001,background:"rgba(17,24,39,0.18)",display:"flex",alignItems:"center",justifyContent:"center",animation:"fadeIn 0.2s var(--ease-out)",WebkitAppRegion:"no-drag"},children:e.jsxs("div",{onClick:g=>g.stopPropagation(),style:{width:"min(920px, calc(100vw - 48px))",height:"min(760px, calc(100vh - 48px))",background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",backdropFilter:"blur(14px)",WebkitBackdropFilter:"blur(14px)",boxShadow:"var(--shadow-md)",overflow:"hidden",display:"flex",flexDirection:"column",animation:"fadeInUp 0.25s var(--ease-out)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",borderBottom:"1px solid var(--border-subtle)",padding:"8px 10px",background:"var(--bg-deepest)"},children:[e.jsx("div",{style:{display:"flex",gap:6},children:Yi.map(g=>e.jsx("button",{onClick:()=>dn(g.id),className:`settings-tab ${X===g.id?"settings-tab-active":""}`,children:g.label},g.id))}),e.jsx("button",{onClick:()=>Ue(!1),title:"关闭",className:"ui-icon-button ui-icon-button--close ui-icon-button--danger",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:e.jsx("path",{d:"M18 6 6 18M6 6l12 12"})})})]}),e.jsxs("div",{style:{flex:1,overflow:"auto"},children:[X==="settings"&&e.jsx(sx,{}),X==="mcp"&&e.jsx(dx,{}),X==="memory"&&e.jsx(ux,{}),X==="skill"&&e.jsx(fx,{}),X==="agent"&&e.jsx(mx,{}),X==="lsp"&&e.jsx(bx,{})]})]})}),document.body),e.jsx("div",{className:"noise-overlay"}),tr&&qt&&On.createPortal(e.jsx("div",{onClick:()=>gr(!1),style:{position:"fixed",inset:0,zIndex:1e4,WebkitAppRegion:"no-drag"},children:e.jsxs("div",{onClick:g=>g.stopPropagation(),className:"appearance-panel",style:{position:"absolute",left:Math.max(12,Math.min(qt.right-320,window.innerWidth-332)),top:qt.bottom+8,width:320,maxHeight:`calc(100vh - ${qt.bottom+20}px)`,overflowY:"auto",background:"var(--bg-surface)",border:"1px solid var(--border-default)",borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-md)",padding:"16px",display:"flex",flexDirection:"column",gap:16,animation:"fadeInUp 0.2s var(--ease-out)",backdropFilter:"blur(14px)",WebkitBackdropFilter:"blur(14px)"},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8},children:"皮肤"}),e.jsx("div",{className:"appearance-choices",children:Yu.map(g=>e.jsxs("button",{onClick:()=>mt(g.id),className:`appearance-choice ${wt===g.id?"appearance-choice-active":""}`,children:[e.jsx("span",{className:"appearance-swatch",style:{background:`linear-gradient(135deg, ${g.preview[0]} 55%, ${g.preview[1]} 55%)`}}),e.jsx("span",{className:"appearance-choice-label",style:{fontWeight:wt===g.id?600:400},children:g.label}),wt===g.id&&e.jsx("svg",{className:"appearance-choice-check",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:e.jsx("path",{d:"m5 12 4 4L19 6"})})]},g.id))})]}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.08em",marginBottom:8},children:"布局"}),e.jsx("div",{className:"appearance-segmented",children:Ju.map(g=>e.jsx("button",{onClick:()=>wn(g.id),title:g.description,className:`appearance-segment ${Rt===g.id?"appearance-segment-active":""}`,children:g.label},g.id))})]}),e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:10,borderTop:"1px solid var(--border-subtle)",paddingTop:12},children:[e.jsx("div",{style:{fontSize:11,fontWeight:600,color:"var(--text-muted)",textTransform:"uppercase",letterSpacing:"0.08em"},children:"语音"}),e.jsxs("label",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:12,color:"var(--text-secondary)",cursor:"pointer"},children:["助手回复自动播报",e.jsx("input",{className:"appearance-switch",type:"checkbox",checked:en,onChange:g=>Hn(g.target.checked)})]}),e.jsxs("label",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",fontSize:12,color:"var(--text-secondary)",cursor:"pointer"},children:["隐藏后语音唤醒",e.jsx("input",{className:"appearance-switch",type:"checkbox",checked:gt,onChange:g=>Yn(g.target.checked)})]}),e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,fontSize:12,color:"var(--text-secondary)"},children:[e.jsx("span",{style:{flexShrink:0},children:"唤醒词"}),e.jsx("input",{value:Wt,onChange:g=>Jn(g.target.value||"小智"),style:{flex:1,padding:"4px 8px",borderRadius:6,border:"1px solid var(--border-default)",background:"var(--bg-deep)",color:"var(--text-primary)",fontSize:12}})]})]})]})}),document.body),e.jsx(Ax,{open:M,onCancel:()=>H(!1),onConfirm:async g=>{await Ws(g),H(!1)}}),e.jsx(yx,{trigger:Yr,heardText:cr}),Ps.length>0&&On.createPortal(e.jsx("div",{style:{position:"fixed",bottom:24,right:24,zIndex:2e4,display:"flex",flexDirection:"column",gap:10,alignItems:"flex-end",pointerEvents:"none"},children:Ps.map(g=>e.jsxs("div",{style:{pointerEvents:"auto",width:320,background:"var(--bg-surface)",border:`1px solid ${g.type==="error"?"rgba(220,38,38,0.25)":g.type==="success"?"rgba(5,150,105,0.25)":"var(--border-default)"}`,borderLeft:`3px solid ${g.type==="error"?"var(--danger)":g.type==="success"?"var(--success)":"var(--accent)"}`,borderRadius:"var(--radius-md)",boxShadow:"var(--shadow-md)",padding:"12px 14px",animation:"fadeInUp 0.22s var(--ease-out)",backdropFilter:"blur(12px)",WebkitBackdropFilter:"blur(12px)"},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:4},children:[e.jsxs("span",{style:{fontSize:12,fontWeight:600,color:g.type==="error"?"var(--danger)":g.type==="success"?"var(--success)":"var(--accent)",display:"flex",alignItems:"center",gap:5},children:[g.type==="error"?"✕":g.type==="success"?"✓":"◎"," ",g.title]}),e.jsx("button",{onClick:()=>Pr(g.id),title:"关闭",style:{background:"none",border:"none",cursor:"pointer",color:"var(--text-muted)",fontSize:14,lineHeight:1,padding:"2px 4px",borderRadius:4,transition:"color 0.15s"},onMouseEnter:_=>_.currentTarget.style.color="var(--text-primary)",onMouseLeave:_=>_.currentTarget.style.color="var(--text-muted)",children:"×"})]}),e.jsx("p",{style:{margin:0,fontSize:12,color:"var(--text-secondary)",lineHeight:1.5,wordBreak:"break-all"},children:g.body}),g.sessionId&&e.jsx("button",{onClick:()=>{Jt(g.sessionId),Pr(g.id)},style:{marginTop:8,padding:"4px 10px",fontSize:11,fontWeight:500,background:"var(--accent-dim)",color:"var(--accent)",border:"1px solid var(--border-glow)",borderRadius:6,cursor:"pointer",transition:"background 0.15s",WebkitAppRegion:"no-drag"},onMouseEnter:_=>_.currentTarget.style.background="var(--accent-glow)",onMouseLeave:_=>_.currentTarget.style.background="var(--accent-dim)",children:"进入会话 →"})]},g.id))}),document.body)]})}const T1=Object.freeze(Object.defineProperty({__proto__:null,default:I1},Symbol.toStringTag,{value:"Module"}));export{T1 as A,_c as M,A1 as a,zx as c};
|