keel-agent 0.129.0 → 0.130.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +31 -1
- package/README.md +12 -16
- package/README.zh-CN.md +12 -16
- package/README.zh-TW.md +74 -189
- package/bin/keel.mjs +295 -55
- package/dist/packages/keel/src/adapters/sdk/prompt-render.js +3 -1
- package/dist/packages/keel/src/adapters/sdk/session-opener.js +2 -1
- package/dist/packages/keel/src/adapters/tools/guarded.js +31 -4
- package/dist/packages/keel/src/adapters/tools/patch.js +16 -0
- package/dist/packages/keel/src/app/client-assembly.js +43 -24
- package/dist/packages/keel/src/app/client-runtime.js +37 -2
- package/dist/packages/keel/src/app/connection-init.js +4 -2
- package/dist/packages/keel/src/app/conversation-content.js +14 -0
- package/dist/packages/keel/src/app/core-engine.js +6 -2
- package/dist/packages/keel/src/app/engine-coordination.js +4 -0
- package/dist/packages/keel/src/app/engine-elsewhere.js +8 -2
- package/dist/packages/keel/src/app/engine-orphans.js +8 -1
- package/dist/packages/keel/src/app/engine-sessions.js +26 -22
- package/dist/packages/keel/src/app/engine-takeover.js +13 -8
- package/dist/packages/keel/src/app/extra-handlers.js +8 -5
- package/dist/packages/keel/src/app/host-faces.js +1 -0
- package/dist/packages/keel/src/app/host-tool-mounts.js +12 -0
- package/dist/packages/keel/src/app/note-delivery.js +2 -2
- package/dist/packages/keel/src/app/session-registry.js +3 -1
- package/dist/packages/keel/src/app/session-surface.js +2 -1
- package/dist/packages/keel/src/app/subagent-model-choice.js +44 -30
- package/dist/packages/keel/src/bg-job-notice.js +1 -0
- package/dist/packages/keel/src/composer-complete-settings.js +43 -0
- package/dist/packages/keel/src/conversation-rows.js +8 -0
- package/dist/packages/keel/src/domains/background/handlers.js +1 -0
- package/dist/packages/keel/src/domains/bots/chat.js +1 -1
- package/dist/packages/keel/src/domains/snapshots/builders.js +4 -0
- package/dist/packages/keel/src/domains/turns/turn-runner.js +18 -0
- package/dist/packages/keel/src/settings-schema.js +9 -0
- package/dist/packages/keel/src/subagent-model-policy.js +49 -0
- package/dist/packages/keel/src/subagent-templates-hant.js +3 -3
- package/dist/packages/keel/src/subagent-templates.js +6 -6
- package/dist/packages/keel/src/tool-catalog.js +9 -0
- package/dist/packages/keel/src/tool-names.js +2 -0
- package/dist/server/background-task-service.js +61 -22
- package/dist/server/bg-tasks/client.js +5 -4
- package/dist/server/bg-tasks/registry.js +29 -18
- package/dist/server/bot-memory-tool.js +15 -3
- package/dist/server/client-state.js +65 -0
- package/dist/server/composer-complete-settings.js +1 -0
- package/dist/server/composer-complete.js +243 -0
- package/dist/server/control-socket.js +13 -1
- package/dist/server/conversation-import/engines/agy.js +222 -0
- package/dist/server/conversation-import/engines/claude.js +171 -0
- package/dist/server/conversation-import/engines/codex.js +178 -0
- package/dist/server/conversation-import/engines/dsh.js +240 -0
- package/dist/server/conversation-import/engines/opencode.js +160 -0
- package/dist/server/conversation-import/index.js +183 -0
- package/dist/server/conversation-import/jsonl.js +100 -0
- package/dist/server/conversation-import/messages.js +147 -0
- package/dist/server/conversation-import/sqlite.js +47 -0
- package/dist/server/conversation-import/types.js +8 -0
- package/dist/server/conversation-import-routes.js +53 -0
- package/dist/server/core-bot-adapter.js +5 -1
- package/dist/server/core-plugin-adapter.js +4 -1
- package/dist/server/core-settings-adapter.js +19 -9
- package/dist/server/custom-cli-routes.js +59 -0
- package/dist/server/custom-cli-store.js +134 -0
- package/dist/server/delegate-task.js +18 -7
- package/dist/server/device-center/bot-chat.js +34 -17
- package/dist/server/device-center/bot-creation-tool.js +8 -64
- package/dist/server/device-center/bot-drafts.js +24 -0
- package/dist/server/device-center/bot-memory.js +101 -12
- package/dist/server/device-center/bot-tool-face.js +24 -20
- package/dist/server/device-center/local.js +59 -9
- package/dist/server/durable/durable-agent-service.js +27 -0
- package/dist/server/engine-owner-route.js +43 -0
- package/dist/server/files-service.js +10 -6
- package/dist/server/index.js +236 -47
- package/dist/server/marker-service.js +19 -0
- package/dist/server/message-window.js +2 -2
- package/dist/server/multi-engine.js +1 -0
- package/dist/server/native-cli.js +3 -1
- package/dist/server/obs-recall-tool.js +173 -0
- package/dist/server/plugin-facilities.js +9 -1
- package/dist/server/plugins.js +11 -4
- package/dist/server/preset-fields.js +9 -0
- package/dist/server/protocol-version.js +1 -1
- package/dist/server/remote-ssh-service.js +13 -0
- package/dist/server/schedule-agent-tool.js +2 -0
- package/dist/server/scheduler-tasks.js +5 -0
- package/dist/server/settings-commit.js +2 -0
- package/dist/server/settings-service.js +2 -0
- package/dist/server/shell-activate.js +118 -1
- package/dist/server/slash-commands.js +48 -12
- package/dist/server/tool-bridge-host.js +5 -0
- package/dist/server/universal/acp/acp-driver.js +96 -22
- package/dist/server/universal/drivers/claude-acp-driver.js +3 -0
- package/dist/server/universal/internal-mcp.js +7 -3
- package/dist/server/universal/seat-takeover.js +145 -0
- package/dist/server/universal/subagent-slash.js +54 -0
- package/dist/server/universal/universal-service.js +28 -0
- package/dist/server/universal/universal-session.js +242 -88
- package/dist/server/update-service.js +12 -8
- package/package.json +20 -15
- package/plugins/catalog.json +128 -90
- package/plugins/superagent/manifest.json +2 -2
- package/themes/flow-zurich.css +2 -2
- package/web/dist/.build-assets.json +1 -1
- package/web/dist/assets/ApprovalRulesTab-QmzsJItk.js +1 -0
- package/web/dist/assets/BgTasksModal-COLmy-4E.js +1 -0
- package/web/dist/assets/{BotDraftSettings-BcXWHOSd.js → BotDraftSettings-nP4g1fge.js} +1 -1
- package/web/dist/assets/BottomDock-BZXSlOom.js +1 -0
- package/web/dist/assets/{CanvasStudio-KZ0MmCL7.js → CanvasStudio-BL1BWXpp.js} +3 -3
- package/web/dist/assets/CommunityThemesSection-BLd_oox1.js +1 -0
- package/web/dist/assets/DesktopAppSettings-Dn18vrLK.js +1 -0
- package/web/dist/assets/DeviceCenter-DxoAwlTt.js +3 -0
- package/web/dist/assets/{DeviceExecutionSettings-VONJ-2Ns.js → DeviceExecutionSettings-B1mya5TJ.js} +1 -1
- package/web/dist/assets/{DeviceGroups-DUq2YZ8O.js → DeviceGroups-C-xwewog.js} +1 -1
- package/web/dist/assets/DisplayTab-DRGFt78v.js +1 -0
- package/web/dist/assets/{FieldRow-CHxkNX2z.js → FieldRow-DHxAXFtL.js} +1 -1
- package/web/dist/assets/FilePreview-DcyP9paf.js +2 -0
- package/web/dist/assets/GlobalSearchModal-Cs6hB5KO.js +1 -0
- package/web/dist/assets/GroupConversation-B7NfTB89.js +9 -0
- package/web/dist/assets/{GroupWorkItems-B-wweVMR.js → GroupWorkItems-CSUjIxDT.js} +1 -1
- package/web/dist/assets/{HintTip-lXOOr9p3.js → HintTip-CKxIx9CD.js} +1 -1
- package/web/dist/assets/LayoutTab-9popvCLQ.js +1 -0
- package/web/dist/assets/McpServersPanel-dRwq7Wjq.js +1 -0
- package/web/dist/assets/ModelConfigModal-C0CXhSl0.js +2 -0
- package/web/dist/assets/{ModelsTab-CMSi1MT-.js → ModelsTab-CyG2rYeY.js} +1 -1
- package/web/dist/assets/{NativeCliPanel-DotHqKv_.js → NativeCliPanel-mlB4dw42.js} +2 -2
- package/web/dist/assets/{PiSetupModal-Dd0w2Koi.js → PiSetupModal-D7PjlTVx.js} +1 -1
- package/web/dist/assets/PluginsTab-0s0qClcC.js +2 -0
- package/web/dist/assets/PresetShareModal-Dw4t6p6s.js +11 -0
- package/web/dist/assets/{PresetsTab-BnFFB24b.js → PresetsTab-DdXvpc2d.js} +1 -1
- package/web/dist/assets/{PromptHistoryTab-CNUzjdJl.js → PromptHistoryTab-DirJHaH6.js} +1 -1
- package/web/dist/assets/{PromptOverrideEditor-DZOQdWy3.js → PromptOverrideEditor-ldLRCp0e.js} +1 -1
- package/web/dist/assets/PromptTab-SV01BMC0.js +11 -0
- package/web/dist/assets/{ProviderOAuthControls-BSqBp-QA.js → ProviderOAuthControls-Clyn3fnw.js} +1 -1
- package/web/dist/assets/QuestionTab-Bi1NYK5U.js +1 -0
- package/web/dist/assets/{QuickAskSettings-DICkDFsE.js → QuickAskSettings-dzG95DYl.js} +2 -2
- package/web/dist/assets/QuickTab-C8bknYDU.js +5 -0
- package/web/dist/assets/{ReviewTab-DRMQoVjL.js → ReviewTab-D9lbphZe.js} +1 -1
- package/web/dist/assets/SCMPanel-BfrlvHxI.js +7 -0
- package/web/dist/assets/SchedulerPanel-DDDWOSsw.js +2 -0
- package/web/dist/assets/SettingsModal-BqzfvDlI.js +2 -0
- package/web/dist/assets/SkillsTab-D8C-kghN.js +1 -0
- package/web/dist/assets/{SoundTab-BR6gVIOZ.js → SoundTab-CXcWmvkX.js} +1 -1
- package/web/dist/assets/{SubagentTemplatesTab-BonIA-lD.js → SubagentTemplatesTab-KjPMnYN4.js} +1 -1
- package/web/dist/assets/{TermXterm-EHBR2avX.js → TermXterm-B7klZwgq.js} +1 -1
- package/web/dist/assets/TerminalDockControls-lbPY2V5U.js +1 -0
- package/web/dist/assets/TerminalPanel-ERotdy8I.js +1 -0
- package/web/dist/assets/{ThemeMarketModal-CGaoF3NZ.js → ThemeMarketModal-BZJZ7doZ.js} +1 -1
- package/web/dist/assets/{ToggleRow-DvouPLLK.js → ToggleRow-irywH1NJ.js} +1 -1
- package/web/dist/assets/ToolBridgeSettings-CG1HleEp.js +1 -0
- package/web/dist/assets/ToolsTab-_OJA76Sw.js +4 -0
- package/web/dist/assets/TuiOverlayModal-CDqXNwW-.js +1 -0
- package/web/dist/assets/{VisionTab-HDlpKVeq.js → VisionTab-B580SGpU.js} +1 -1
- package/web/dist/assets/{api-client-J4QrjRw8.js → api-client-B2iSv9kK.js} +1 -1
- package/web/dist/assets/{canvas-client-BsNp2mr3.js → canvas-client-DRiwRbfy.js} +1 -1
- package/web/dist/assets/{desktop-BcTQigaN.js → desktop-DRyQQXnx.js} +1 -1
- package/web/dist/assets/host-icon-DMg5PU4C.js +1 -0
- package/web/dist/assets/i18n-D2DJ-AHq.js +225 -0
- package/web/dist/assets/index-CP0EEOA0.js +423 -0
- package/web/dist/assets/index-Ds_pheLF.css +1 -0
- package/web/dist/assets/plugin-host-VU6JOOPu.js +1 -0
- package/web/dist/assets/{theme-7DF4yEv3.js → theme-ZteIcUdF.js} +1 -1
- package/web/dist/assets/{tool-inventory-D2UKR8Ja.js → tool-inventory-DnzKVLYq.js} +1 -1
- package/web/dist/index.html +10 -9
- package/web/dist/sw.js +1 -1
- package/web/dist/assets/ApprovalRulesTab-BlcxVgms.js +0 -1
- package/web/dist/assets/BgTasksModal-wL4p27CE.js +0 -1
- package/web/dist/assets/BottomDock-CUnQsIDW.js +0 -1
- package/web/dist/assets/CommunityThemesSection-BAcS2VQK.js +0 -1
- package/web/dist/assets/DesktopAppSettings-BeikxSqV.js +0 -1
- package/web/dist/assets/DeviceCenter-BWKRVpWt.js +0 -3
- package/web/dist/assets/DisplayTab-B5x4nQh5.js +0 -1
- package/web/dist/assets/FilePreview-0IDddE5F.js +0 -2
- package/web/dist/assets/GlobalSearchModal-BaXs1zRG.js +0 -1
- package/web/dist/assets/GroupConversation-EaMawnF-.js +0 -9
- package/web/dist/assets/LayoutTab-8N74U83U.js +0 -1
- package/web/dist/assets/McpServersPanel-BAhwoE87.js +0 -1
- package/web/dist/assets/ModelConfigModal-i3m9glTy.js +0 -2
- package/web/dist/assets/PluginsTab-DL8j6LEI.js +0 -2
- package/web/dist/assets/PresetShareModal-BGhCpas6.js +0 -11
- package/web/dist/assets/PromptTab-DPYuPM07.js +0 -11
- package/web/dist/assets/QuestionTab-C7oF1MYO.js +0 -1
- package/web/dist/assets/QuickTab-DDaxH3XV.js +0 -1
- package/web/dist/assets/SCMPanel-CfOxsL8H.js +0 -7
- package/web/dist/assets/SchedulerPanel-BLaVSPXj.js +0 -2
- package/web/dist/assets/SettingsModal-6jgsnLF0.js +0 -2
- package/web/dist/assets/SkillsTab-C5XuZ4a-.js +0 -1
- package/web/dist/assets/TerminalDockControls-Dn51FqM9.js +0 -1
- package/web/dist/assets/TerminalPanel-D2Bpt0f_.js +0 -1
- package/web/dist/assets/ToolBridgeSettings-8vlLWWvW.js +0 -1
- package/web/dist/assets/ToolsTab-Byx7wDZe.js +0 -4
- package/web/dist/assets/TuiOverlayModal-Bj6jyAvr.js +0 -1
- package/web/dist/assets/i18n-CaWsBwiA.js +0 -225
- package/web/dist/assets/index-2jVkYOYt.css +0 -1
- package/web/dist/assets/index-KuttBaFw.js +0 -420
- package/web/dist/assets/plugin-host-C2Iki5ig.js +0 -1
|
@@ -1,420 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./math-DKgf_YcR.js","./markdown-BA0rplmj.js","./rolldown-runtime-BLXQ4ufn.js","./react-D0RUMPTR.js","./markdown-C8LL_u4z.css","./math-DMZ4qLFT.css","./FilePreview-0IDddE5F.js","./i18n-CaWsBwiA.js","./overlay-stack-rkpi4Wf5.js","./app-globals-D2ZB_kzX.js","./PiSetupModal-Dd0w2Koi.js","./desktop-BcTQigaN.js","./theme-7DF4yEv3.js","./api-client-J4QrjRw8.js","./ProviderOAuthControls-BSqBp-QA.js","./ModelConfigModal-i3m9glTy.js","./SettingsModal-6jgsnLF0.js","./shortcut-stack-D0d3XzNw.js","./uuid-BzDIGCwP.js","./HintTip-lXOOr9p3.js","./SettingsModal-Cy5lRC97.css","./ThemeMarketModal-CGaoF3NZ.js","./CommunityThemesSection-BAcS2VQK.js","./plugin-links-8dfevFjx.js","./BgTasksModal-wL4p27CE.js","./file-preview-bridge-F9LjmrJs.js","./TuiOverlayModal-Bj6jyAvr.js","./xterm-Cqm0K84T.js","./xterm-B1njb2Cr.css","./GlobalSearchModal-BaXs1zRG.js","./plugin-host-C2Iki5ig.js","./composer-bridge-CImnjDHq.js","./use-copy-feedback-UoOlBc20.js","./DeviceGroups-DUq2YZ8O.js","./group-view-state-CGCzYF8k.js","./BottomDock-CUnQsIDW.js","./TerminalDockControls-Dn51FqM9.js","./NativeCliPanel-DotHqKv_.js","./TermXterm-EHBR2avX.js","./DeviceCenter-BWKRVpWt.js","./DeviceExecutionSettings-VONJ-2Ns.js","./GroupWorkItems-B-wweVMR.js","./CanvasStudio-KZ0MmCL7.js","./es-C5BHljgM.js","./canvas-client-BsNp2mr3.js","./SchedulerPanel-BLaVSPXj.js","./GroupConversation-EaMawnF-.js","./GroupConversation-wV-lmZkz.css","./TerminalPanel-D2Bpt0f_.js","./use-click-outside-DZ7f2Ktv.js","./SCMPanel-CfOxsL8H.js","./SCMPanel-BVYmayDJ.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e}from"./rolldown-runtime-BLXQ4ufn.js";import{$ as t,$t as n,A as r,An as i,B as a,Bn as o,Bt as s,C as c,Cn as l,D as u,Dn as d,Dt as f,En as p,Et as m,F as h,Fn as g,Ft as _,G as v,H as y,Hn as b,Ht as x,I as S,It as C,J as w,K as T,Kt as E,L as D,Ln as O,Lt as k,M as A,Mn as j,Mt as M,N,Nn as P,Nt as F,O as I,On as L,Ot as R,P as z,Pn as B,Pt as V,Q as H,Qt as ee,R as U,Rn as W,Rt as G,Sn as K,St as q,T as te,Tn as ne,U as re,Un as J,Ut as ie,V as ae,Vn as oe,Vt as se,W as Y,Wn as ce,X as le,Xt as ue,Y as de,Z as fe,Zt as pe,_ as me,_n as he,_t as ge,a as _e,at as ve,b as ye,bt as be,c as xe,cn as Se,ct as Ce,d as we,dn as Te,dt as Ee,en as De,et as Oe,f as ke,fn as Ae,ft as je,g as Me,gn as Ne,gt as Pe,h as Fe,hn as Ie,ht as Le,i as Re,in as ze,it as Be,j as Ve,jn as He,jt as Ue,kn as We,kt as Ge,l as Ke,ln as qe,lt as Je,m as Ye,mn as Xe,mt as Ze,n as Qe,nn as $e,nt as et,o as tt,on as nt,ot as rt,p as it,pn as at,pt as ot,q as st,qt as ct,r as lt,rn as ut,rt as dt,s as X,st as ft,t as pt,tn as mt,tt as ht,u as gt,un as _t,ut as vt,v as yt,vn as bt,vt as xt,w as St,wn as Ct,wt,x as Tt,xn as Et,y as Dt,yn as Ot,yt as kt,z as At,zn as jt,zt as Mt}from"./i18n-CaWsBwiA.js";import{i as Nt,n as Pt,r as Ft,t as It}from"./react-D0RUMPTR.js";import{t as Lt}from"./shortcut-stack-D0d3XzNw.js";import{t as Rt}from"./overlay-stack-rkpi4Wf5.js";import{a as zt,c as Bt,d as Vt,f as Ht,g as Ut,h as Wt,i as Gt,l as Kt,m as qt,n as Jt,o as Yt,p as Xt,r as Zt,s as Qt,t as $t,u as en}from"./file-preview-bridge-F9LjmrJs.js";import{a as tn,c as nn,n as rn,o as an,r as on,s as sn,t as cn}from"./desktop-BcTQigaN.js";import{a as ln,n as un,t as dn}from"./api-client-J4QrjRw8.js";import{a as fn,c as pn,i as mn,l as hn,n as gn,o as _n,r as vn,s as yn,t as Z}from"./app-globals-D2ZB_kzX.js";import{n as bn,t as xn}from"./HintTip-lXOOr9p3.js";import{C as Sn,D as Cn,E as wn,S as Tn,T as En,_ as Dn,a as On,c as kn,d as An,f as jn,g as Mn,h as Nn,i as Pn,l as Fn,m as In,n as Ln,o as Rn,p as zn,r as Bn,t as Vn,v as Hn,w as Un,y as Wn}from"./plugin-host-C2Iki5ig.js";import{n as Gn,t as Kn}from"./use-copy-feedback-UoOlBc20.js";import{a as qn,c as Jn,d as Yn,f as Xn,h as Zn,i as Qn,m as $n,n as er,p as tr,r as nr,s as rr,t as ir,u as ar}from"./composer-bridge-CImnjDHq.js";import{t as or}from"./uuid-BzDIGCwP.js";import{a as sr,c as cr,d as lr,h as ur,l as dr,m as fr,s as pr,t as mr,u as hr}from"./markdown-BA0rplmj.js";import{l as gr,n as _r,o as vr,t as yr}from"./theme-7DF4yEv3.js";import{t as br}from"./use-click-outside-DZ7f2Ktv.js";(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();function xr(e){let t=new Map;return{get length(){return t.size},clear(){let n=[...t.keys()];t.clear();for(let t of n)e?.(t,null)},getItem(e){return t.get(String(e))??null},key(e){return[...t.keys()][Number(e)>>>0]??null},removeItem(n){n=String(n),t.delete(n)&&e?.(n,null)},setItem(n,r){n=String(n),r=String(r),t.set(n,r),e?.(n,r)}}}function Sr(e){let t=B(e.location.pathname);if(!t)return!1;let n=!1;for(let t of[`localStorage`,`sessionStorage`])try{e[t]}catch{n=!0,Object.defineProperty(e,t,{configurable:!0,enumerable:!0,value:xr(t===`localStorage`?(t,n)=>{t===`pi-theme`&&e.parent.postMessage({type:`device-portal-theme-write`,value:n},e.location.origin)}:void 0)})}if(!n)return!1;try{e.navigator.serviceWorker}catch{try{Object.defineProperty(e.navigator,"serviceWorker",{configurable:!0,get:()=>void 0})}catch{}}let r=e.fetch;return e.fetch=(n,i)=>{let a=typeof n==`string`?n:n instanceof URL?n.href:n.url,o=new URL(a,e.document.baseURI||e.location.href);return o.origin===e.location.origin&&o.pathname.startsWith(t)?r.call(e,n,{...i,credentials:`omit`}):r.call(e,n,i)},!0}function Cr(e,t=500){return new Promise(n=>{let r=()=>{clearTimeout(a),e.removeEventListener(`message`,i),n()},i=t=>{if(t.source!==e.parent||t.origin!==e.location.origin||t.data?.type!==`device-portal-theme`)return;let n=t.data.value;n===null?e.localStorage.removeItem(`pi-theme`):typeof n==`string`&&/^[A-Za-z0-9_-]{1,256}$/.test(n)&&e.localStorage.setItem(`pi-theme`,n),r()},a=setTimeout(r,t);e.addEventListener(`message`,i),e.parent.postMessage({type:`device-portal-theme-read`},e.location.origin)})}var wr=typeof window<`u`&&Sr(window),Tr=Pt(),Q=e(Nt(),1),Er=Ft(),$=It(),Dr=0,Or=``;function kr(){typeof document<`u`&&(Dr===0&&(Or=document.body.style.overflow,document.body.style.overflow=`hidden`),Dr++)}function Ar(){typeof document<`u`&&(Dr=Math.max(0,Dr-1),Dr===0&&(document.body.style.overflow=Or))}function jr({open:e=!0,onClose:t,title:n,icon:r,headerActions:i,allowFullscreen:a=!1,fullscreen:o,onFullscreenChange:s,children:c,className:l=``,backdropClassName:u=``,style:d,closeOnBackdropClick:f=!0,closeOnEscape:p=!0,showCloseButton:m=!0,ariaLabel:h,lockScroll:g=!0}){let _=X(),v=(0,Q.useRef)(t);(0,Q.useLayoutEffect)(()=>{v.current=t});let y=o!==void 0,[b,x]=(0,Q.useState)(!1),S=a?y?o:b:!1,C=()=>{let e=!S;y||x(e),s?.(e)};if(Lt(()=>a&&S?(y||x(!1),s?.(!1),!0):p?(v.current(),!0):!1,e),(0,Q.useEffect)(()=>{if(e&&g)return kr(),()=>{Ar()}},[e,g]),!e)return null;let w=e=>{e.target===e.currentTarget&&f&&v.current()},T=h??(typeof n==`string`?n:void 0),E=`modal-backdrop ${u} ${S?`fullscreen`:``}`.trim(),D=`modal ${l} ${a?`has-fullscreen-toggle`:``} ${S?`fullscreen`:``}`.trim();return(0,Er.createPortal)((0,$.jsx)(`div`,{className:E,onClick:w,role:`presentation`,children:(0,$.jsxs)(`div`,{className:D,role:`dialog`,"aria-modal":`true`,"aria-label":T,style:d,onClick:e=>e.stopPropagation(),children:[a&&(0,$.jsx)(`button`,{type:`button`,className:`modal-fullscreen-btn ${S?`active`:``}`,"aria-label":_(S?`exitFullscreen`:`fullscreen`),title:_(S?`exitFullscreen`:`fullscreen`),onClick:C,children:S?(0,$.jsx)(G,{}):(0,$.jsx)(M,{})}),m&&(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,"aria-label":_(`close`),onClick:()=>v.current(),children:`✕`}),n?(0,$.jsxs)(`div`,{className:`modal-head`,onDoubleClick:e=>{if(!a)return;let t=e.target;t&&!t.closest(`button, a, input, textarea, select`)&&C()},children:[r?(0,$.jsx)(`span`,{className:`modal-head-icon`,"aria-hidden":!0,children:r}):null,(0,$.jsx)(`span`,{className:`modal-head-title`,children:n}),i?(0,$.jsx)(`div`,{className:`modal-head-actions`,children:i}):null]}):null,c]})}),document.body)}function Mr(e,t){(0,Q.useEffect)(()=>{let e=()=>{document.visibilityState===`visible`&&t()};e();let n=window.setInterval(e,3e4);return window.addEventListener(`focus`,e),document.addEventListener(`visibilitychange`,e),()=>{window.clearInterval(n),window.removeEventListener(`focus`,e),document.removeEventListener(`visibilitychange`,e)}},[e,t])}function Nr({open:e=!0,worktree:t,onRefresh:n,onSwitch:r,onRemove:i,onClose:a}){let o=X();(0,Q.useEffect)(()=>{e&&n()},[e,n]);let s=t?.linkedWorktrees??[],c=t?[{path:t.mainPath,branch:t.mainBranch,isMain:!0,isDirty:void 0},...s.map(e=>({...e,isMain:!1}))]:[];return t?.isLinkedWorktree&&!c.some(e=>e.path===t.currentPath)&&c.push({path:t.currentPath,branch:t.branch,isMain:!1,isDirty:void 0}),(0,$.jsx)(jr,{open:e,onClose:a,className:`worktree-modal`,title:o(`worktreeViewTitle`),icon:(0,$.jsx)(ot,{}),headerActions:(0,$.jsx)(`button`,{type:`button`,className:`worktree-refresh-btn`,onClick:n,"aria-label":o(`worktreeRefresh`),title:o(`worktreeRefresh`),children:(0,$.jsx)(pe,{})}),children:(0,$.jsxs)(`div`,{className:`worktree-modal-body`,children:[(0,$.jsx)(`p`,{className:`worktree-view-hint`,children:o(`worktreeViewHint`)}),!t&&(0,$.jsx)(`p`,{className:`worktree-empty`,children:o(`worktreeEmpty`)}),(0,$.jsx)(`div`,{className:`worktree-view-list`,children:c.map(e=>{let n=e.path===t?.currentPath,a=e.branch||o(`worktreeDetached`);return(0,$.jsxs)(`article`,{className:`worktree-card${n?` current`:``}`,children:[(0,$.jsxs)(`div`,{className:`worktree-card-title`,children:[(0,$.jsx)(ot,{}),(0,$.jsx)(`strong`,{children:a}),n&&(0,$.jsx)(`span`,{className:`worktree-current`,children:o(`worktreeCurrent`)})]}),(0,$.jsx)(`div`,{className:`worktree-card-path`,children:e.path}),(0,$.jsxs)(`div`,{className:`worktree-card-actions`,children:[(0,$.jsx)(`span`,{className:e.isDirty?`worktree-dirty`:`worktree-status`,children:e.isMain?o(`worktreeMain`):e.isDirty===void 0?o(`worktreeBadgeLinked`):e.isDirty?o(`worktreeHasChanges`):o(`worktreeClean`)}),!n&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>r(e.path),children:e.isMain?o(`worktreeActionSwitchMain`):o(`worktreeSwitch`)})]}),!e.isMain&&(0,$.jsxs)(`details`,{className:`worktree-card-details`,children:[(0,$.jsx)(`summary`,{children:o(`worktreeManage`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn danger`,onClick:()=>{window.confirm(o(`worktreeActionRemoveConfirm`,{path:e.path}))&&i(e.path)},children:[(0,$.jsx)(Ne,{}),o(`worktreeActionRemove`)]})]})]},e.path)})})]})})}var Pr=`<background-task-notification>`;function Fr(e){return typeof e==`string`&&e.includes(Pr)}function Ir(e){return e.replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'|'/g,`'`).replace(/&/g,`&`)}function Lr(e,t){let n=RegExp(`<${t}>([\\s\\S]*?)</${t}>`).exec(e);return n?Ir(n[1].trim()):``}function Rr(e){if(!e)return;let t=Number(e);return Number.isFinite(t)?t:void 0}function zr(e){return typeof e==`string`?e.trim():``}function Br(e){if(!Fr(e))return null;let t=Lr(e,`task-id`);if(!t)return null;let n=Ht(Lr(e,`status`))??`completed`,r=Rr(Lr(e,`exit-code`)),i=Lr(e,`error`),a=Lr(e,`summary`),o=Lr(e,`guidance`);return{id:t,name:Lr(e,`task-name`)||t,status:n,outputPath:Lr(e,`output-file`),...r===void 0?{}:{exitCode:r},...i?{error:i}:{},...a?{summary:a}:{},...o?{guidance:o}:{}}}function Vr(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=zr(t.kind),r=zr(t.taskId),i=zr(t.id)||r;if(!i||n&&n!==`job`)return null;let a=Ht(t.status)??`running`,o=zr(t.command),s=zr(t.logPath),c=zr(t.name)||zr(t.label)||o||i,l=typeof t.exitCode==`number`&&Number.isFinite(t.exitCode)?t.exitCode:void 0,u=zr(t.error),d=typeof t.since==`number`&&Number.isFinite(t.since)?t.since:void 0,f=typeof t.endedAt==`number`&&Number.isFinite(t.endedAt)?t.endedAt:void 0,p=typeof t.pid==`number`&&Number.isFinite(t.pid)&&t.pid>0?t.pid:void 0;return{id:i,...r?{taskId:r}:{},name:c,status:a,outputPath:s,...o?{command:o}:{},...l===void 0?{}:{exitCode:l},...u?{error:u}:{},...d===void 0?{}:{startedAt:d},...f===void 0?{}:{endedAt:f},...p===void 0?{}:{pid:p}}}function Hr(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e,n=zr(t.id),r=Ht(t.status),i=zr(t.outputPath),a=zr(t.command);if(!n||!r||!i&&!a)return null;let o=zr(t.name)||n,s=typeof t.exitCode==`number`&&Number.isFinite(t.exitCode)?t.exitCode:void 0,c=zr(t.error),l=typeof t.startTime==`number`&&Number.isFinite(t.startTime)?t.startTime:void 0,u=typeof t.endTime==`number`&&Number.isFinite(t.endTime)?t.endTime:void 0;return{id:n,name:o,status:r,outputPath:i,...a?{command:a}:{},...s===void 0?{}:{exitCode:s},...c?{error:c}:{},...l===void 0?{}:{startedAt:l},...u===void 0?{}:{endedAt:u}}}function Ur(e,t){let n=Hr(t);return n?Wr(n,e):Br(e)}function Wr(e,t){let n=Br(t);return n?{...e,...e.summary||!n.summary?{}:{summary:n.summary},...e.guidance||!n.guidance?{}:{guidance:n.guidance},...e.error||!n.error?{}:{error:n.error}}:e}var Gr=new Set([`bg_run`,`bg_status`,`bg_logs`,`bg_result`,`bg_kill`,`bg_task`]);function Kr(e){let t=``;for(let n of e.content)n.type===`text`&&typeof n.text==`string`&&(t+=`${t?`
|
|
3
|
-
`:``}${n.text}`);return t}function qr(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function Jr(e){if(!qr(e))return[];let t=[],n=Vr(e.job);if(n&&t.push(n),Array.isArray(e.jobs))for(let n of e.jobs){let e=Vr(n);e&&t.push(e)}let r=Hr(e.task);if(r&&t.push(r),Array.isArray(e.tasks))for(let n of e.tasks){let e=Hr(n);e&&t.push(e)}return t}function Yr(e){return Xt(e).map(e=>({id:e.id,name:e.name||e.id,status:e.status,outputPath:e.outputPath,...e.exitCode===void 0?{}:{exitCode:e.exitCode}}))}function Xr(e){let t=Jr(e.details);return t.length>0?t:!e.toolName||!Gr.has(e.toolName)?[]:Yr(e.text??``)}function Zr(e){if(e.role===`custom`){if(e.customType!==`background-task-notification`)return[];let t=Jr(e.details);if(t.length>0)return t;let n=Ur(Kr(e),e.details);return n?[n]:[]}return e.role===`toolResult`?Xr({toolName:e.toolName,details:e.details,text:Kr(e)}):[]}function Qr(e){return e.endedAt??e.startedAt??0}function $r(e,t){let n=t.name&&t.name!==t.id?t.name:e.name||t.name,r=t.outputPath||e.outputPath,i=t.command&&t.command!==t.id?t.command:e.command??t.command,a=t.taskId??e.taskId,o=t.startedAt??e.startedAt;return{...t,name:n,outputPath:r,...a?{taskId:a}:{},...i?{command:i}:{},...o===void 0?{}:{startedAt:o}}}function ei(e,t=new Set){if(!e||e.length===0)return[];let n=new Map;for(let t of e)for(let e of Zr(t)){let t=n.get(e.id);n.set(e.id,t?$r(t,e):e)}let r=[];for(let e of n.values())Ut(e.status)&&t.has(e.id)||r.push(e);return r.sort((e,t)=>{let n=e.status===`running`?0:1,r=t.status===`running`?0:1;return n===r?Qr(t)-Qr(e):n-r}),r}function ti(e){let t=0,n=0;for(let r of e)r.status===`running`?t++:n++;return{running:t,finished:n}}var ni=`pi-web-ui:bg-tasks-cleared:`,ri=new Map,ii=new Set,ai=new Set;function oi(e){return`${ni}${e}`}function si(e){if(!Array.isArray(e))return ai;let t=e.filter(e=>typeof e==`string`&&e.length>0).slice(-200);return t.length===0?ai:new Set(t)}function ci(e){try{let t=localStorage.getItem(oi(e));return t?si(JSON.parse(t)):ai}catch{return ai}}function li(e){if(!e)return ai;let t=ri.get(e);if(t)return t;let n=ci(e);return ri.set(e,n),n}function ui(e,t){if(e){ri.set(e,t);try{t.size===0?localStorage.removeItem(oi(e)):localStorage.setItem(oi(e),JSON.stringify([...t].slice(-200)))}catch{}for(let e of ii)e()}}function di(e){return ii.add(e),()=>{ii.delete(e)}}var fi=new WeakMap;function pi(e,t){if(!e||e.length===0)return[];let n=fi.get(e);if(n&&n.cleared===t)return n.result;let r=ei(e,t);return fi.set(e,{cleared:t,result:r}),r}function mi(e,t){let n=t??``,r=(0,Q.useSyncExternalStore)(di,()=>li(n),()=>ai),i=(0,Q.useMemo)(()=>pi(e,r),[e,r]),a=(0,Q.useMemo)(()=>ti(i),[i]),o=(0,Q.useCallback)(e=>{if(!n||!e)return;let t=li(n);if(t.has(e))return;let r=new Set(t);r.add(e),ui(n,r)},[n]);return{tasks:i,counts:a,clearFinished:(0,Q.useCallback)(()=>{if(!n)return;let e=li(n),t=new Set(e);for(let e of i)Ut(e.status)&&t.add(e.id);t.size!==e.size&&ui(n,t)},[n,i]),clearTask:o}}var hi=0,gi=[],_i=new Map,vi=new Set;function yi(){for(let e of vi)try{e()}catch{}}function bi(e){let t=_i.get(e);t!==void 0&&(clearTimeout(t),_i.delete(e))}function xi(e){let t=e.id||`banner-${Date.now()}-${++hi}`,n={...e,id:t,type:e.type||`info`,persistent:!!e.persistent,timeoutMs:e.timeoutMs??5e3,dismissible:e.dismissible!==!1};if(bi(t),!n.persistent&&n.timeoutMs&&n.timeoutMs>0){let e=setTimeout(()=>{Si(t)},n.timeoutMs);_i.set(t,e)}let r=gi.findIndex(e=>e.id===t);if(r>=0){let e=[...gi];e[r]=n,gi=e}else gi=[...gi,n];return yi(),t}function Si(e,t){bi(e);let n=gi.find(t=>t.id===e);if(n){if(gi=gi.filter(t=>t.id!==e),!t?.silent)try{n.onClose?.()}catch{}yi()}}function Ci(e,t){let n=gi.filter(e);if(n.length!==0){for(let e of n)if(bi(e.id),!t?.silent)try{e.onClose?.()}catch{}gi=gi.filter(t=>!e(t)),yi()}}function wi(){return gi}function Ti(e){return vi.add(e),()=>{vi.delete(e)}}function Ei(){return(0,Q.useSyncExternalStore)(Ti,wi,wi)}function Di({type:e}){switch(e){case`question`:return(0,$.jsx)(xt,{className:`banner-icon banner-icon-question`});case`warning`:return(0,$.jsx)(me,{className:`banner-icon banner-icon-warning`});case`error`:return(0,$.jsx)(Me,{className:`banner-icon banner-icon-error`});case`success`:return(0,$.jsx)(h,{className:`banner-icon banner-icon-success`});default:return(0,$.jsx)(q,{className:`banner-icon banner-icon-info`})}}var Oi=(0,Q.memo)(function({banner:e}){let t=X(),n=typeof e.onClick==`function`;return(0,$.jsxs)(`div`,{className:`banner-card banner-type-${e.type||`info`} ${n?`banner-clickable`:``}`,onClick:n?e.onClick:void 0,role:n?`button`:`status`,tabIndex:n?0:void 0,onKeyDown:n?t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),e.onClick?.())}:void 0,children:[(0,$.jsx)(`div`,{className:`banner-icon-col`,children:(0,$.jsx)(Di,{type:e.type})}),(0,$.jsxs)(`div`,{className:`banner-content-col`,children:[e.title&&(0,$.jsx)(`div`,{className:`banner-title`,title:e.title,children:e.title}),(0,$.jsx)(`div`,{className:`banner-message`,title:e.message,children:e.message})]}),e.dismissible&&(0,$.jsx)(`button`,{type:`button`,className:`banner-close`,onClick:t=>{t.stopPropagation(),Si(e.id)},"aria-label":`Close banner`,title:t(`close`),children:(0,$.jsx)(Ct,{})})]})}),ki=(0,Q.memo)(function(){let e=Ei();return e.length===0?null:(0,$.jsx)(`aside`,{className:`banner-container`,"aria-label":`Notifications`,children:e.map(e=>(0,$.jsx)(Oi,{banner:e},e.id))})});function Ai({active:e,children:t}){let n=(0,Q.useRef)(!1);return e&&(n.current=!0),n.current?(0,$.jsx)(Q.Suspense,{fallback:null,children:t}):null}function ji(){let e=X(),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(.5),l=(0,Q.useRef)(0),u=(0,Q.useRef)(0),d=(0,Q.useRef)(0),f=(0,Q.useRef)(0),p=typeof window<`u`&&an(),m=typeof window<`u`?window.piDesktop?.browser:void 0;if((0,Q.useEffect)(()=>{if(!m||!p)return;m.getState().then(e=>{e&&typeof e==`object`&&n(e)});let e=m.onState(e=>{e&&typeof e==`object`&&n(e)});return()=>{e?.()}},[m,p]),!p||!m||t?.mode!==`split`)return null;let h=e=>{if(e.button!==0)return;e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId);let n=window.innerWidth,r=Number(t?.splitRatio)||.5,a=n>0&&r>0?Math.round(n/r):window.screen.width;l.current=e.clientX,u.current=n,d.current=a,i(!0),o(null),c(r),document.body.classList.add(`desktop-is-resizing`)},g=e=>{if(!r)return;let t=e.clientX-l.current,n=u.current+t,i=d.current;if(i<=0)return;let a=n/i;if(a>.92||n>i-60)o(`agent`),c(1);else if(a<.08||n<60)o(`browser`),c(0);else{o(null);let e=Math.max(.2,Math.min(.8,a));c(e),cancelAnimationFrame(f.current),f.current=requestAnimationFrame(()=>{m.setSplitRatio?.(e)})}},_=e=>{if(!r)return;i(!1),document.body.classList.remove(`desktop-is-resizing`);try{e.currentTarget.releasePointerCapture(e.pointerId)}catch{}let t=e.clientX-l.current,n=u.current+t,a=d.current,s=a>0?n/a:.5;if(s>.92||n>a-60)m.setMode(`agent`);else if(s<.08||n<60)m.setMode(`browser`);else{let e=Math.max(.2,Math.min(.8,s));m.setSplitRatio?.(e)}o(null)};return(0,$.jsxs)(`div`,{className:`desktop-split-resizer ${r?`dragging`:``} ${a?`snap-${a}`:``}`,onPointerDown:h,onPointerMove:g,onPointerUp:_,onPointerCancel:_,title:e(`desktopSplitResizerTip`),children:[(0,$.jsx)(`div`,{className:`desktop-split-resizer-line`}),r&&(0,$.jsx)(`div`,{className:`desktop-split-resizer-badge`,children:a===`agent`?e(`desktopSplitHideBrowser`):a===`browser`?e(`desktopSplitHideAgent`):`${Math.round(s*100)}% | ${Math.round((1-s)*100)}%`})]})}var Mi=new Set;function Ni(e){return Mi.add(e),()=>{Mi.delete(e)}}function Pi(e){for(let t of Mi)try{t(e)}catch(e){console.error(`[remote-ssh-client] listener error:`,e)}}function Fi(e,t,n,r){return`ssh://${e}@${t}:${n}${r.startsWith(`/`)?r:`/${r}`}`}function Ii(e){return!!(e&&e.startsWith(`ssh://`))}function Li(e){if(!Ii(e))return null;let t=/^ssh:\/\/([^@]+)@([^:]+):(\d+)(\/.*)$/.exec(e);return t?{username:t[1],host:t[2],port:parseInt(t[3],10),remotePath:t[4]}:null}var Ri=1;function zi(e,t){let n=`probe_${Date.now()}_${Ri++}`;return new Promise(r=>{let i=Ni(e=>{e.type===`remote_ssh_probe_result`&&e.reqId===n&&(i(),r({ok:e.ok,connectionId:e.connectionId,error:e.error,system:e.system,tools:e.tools,packageManager:e.packageManager,suggestedInstall:e.suggestedInstall,hostTrust:e.hostTrust,profileSaveError:e.profileSaveError}))});Z({type:`remote_ssh_probe`,reqId:n,params:e})||(i(),r({ok:!1,error:t(`remoteSshSocketDownRetry`)}))})}function Bi(e,t,n){let r=`listdir_${Date.now()}_${Ri++}`;return new Promise(i=>{let a=Ni(e=>{e.type===`remote_ssh_list_dir_result`&&e.reqId===r&&(a(),i({ok:e.ok,connectionId:e.connectionId,path:e.path,parentPath:e.parentPath,items:e.items,error:e.error}))});Z({type:`remote_ssh_list_dir`,reqId:r,connectionId:e,path:n})||(a(),i({ok:!1,connectionId:e,path:n||`/`,items:[],error:t(`remoteSshSocketDown`)}))})}function Vi(e,t,n){let r=`install_${Date.now()}_${Ri++}`;return new Promise(i=>{let a=Ni(e=>{e.type===`remote_ssh_install_result`&&e.reqId===r&&(a(),i({ok:e.ok,connectionId:e.connectionId,tool:e.tool,output:e.output,error:e.error}))});Z({type:`remote_ssh_install_tools`,reqId:r,connectionId:e,tools:t})||(a(),i({ok:!1,connectionId:e,tool:t[0]||``,error:n(`remoteSshSocketDown`)}))})}function Hi(){let e=`profiles_${Date.now()}_${Ri++}`;return new Promise(t=>{let n=Ni(r=>{r.type===`remote_ssh_profiles_result`&&r.reqId===e&&(n(),t({profiles:r.profiles,localKeys:r.localKeys??[]}))});Z({type:`remote_ssh_list_profiles`,reqId:e})||(n(),t({profiles:[],localKeys:[]}))})}function Ui(e){Z({type:`remote_ssh_delete_profile`,name:e})}function Wi(e,t){let n=`trust_${Date.now()}_${Ri++}`;return new Promise(r=>{let i=Ni(e=>{e.type===`remote_ssh_trust_host_result`&&e.reqId===n&&(i(),r({ok:e.ok,error:e.error}))});Z({type:`remote_ssh_trust_host`,reqId:n,...e})||(i(),r({ok:!1,error:t(`remoteSshSocketDown`)}))})}var Gi=`@root`,Ki=e=>e.endsWith(`/`)?e:e+`/`;function qi(e,t){let n=t.trim(),r=e.replace(/\\/g,`/`);return r.endsWith(`/`)?r+n:(/^[A-Za-z]:$/.test(r),r+`/`+n)}function Ji(e){let t=e.trim();return!(!t||t===`.`||t===`..`||t.includes(`/`)||t.includes(`\\`))}var Yi=e=>{let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e;if(t===`@root`||t===`/`)return null;let n=t.lastIndexOf(`/`);if(n<0)return/^[A-Za-z]:$/.test(t)?Gi:null;if(n===0)return`/`;let r=t.slice(0,n);return/^[A-Za-z]:$/.test(r)?r+`/`:r},Xi=`pi-web-ui:project-picker-tab`;function Zi(){try{let e=localStorage.getItem(Xi);return e===`local`||e===`remote`?e:null}catch{return null}}function Qi({activeTab:e,currentCwd:t,mode:n,customProjectName:r,onSelectDirectory:i,onCreateProject:a,onClose:o}){let s=X(),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)(``),[f,p]=(0,Q.useState)(`22`),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(`password`),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)([]),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(!0),[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(!1),[M,N]=(0,Q.useState)(null),[P,F]=(0,Q.useState)(!1),[I,L]=(0,Q.useState)(!1),[R,z]=(0,Q.useState)(null),[B,V]=(0,Q.useState)(null),[H,ee]=(0,Q.useState)(null),[U,W]=(0,Q.useState)(null),[G,K]=(0,Q.useState)([]),[q,te]=(0,Q.useState)(!1),[ne,re]=(0,Q.useState)(`/`),[J,ie]=(0,Q.useState)(`/`),[ae,oe]=(0,Q.useState)([]),[se,Y]=(0,Q.useState)(!1),[ce,le]=(0,Q.useState)(!1),[ue,de]=(0,Q.useState)(``),[fe,pe]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!Ii(t))return;let e=Li(t);e&&(d(e.host),p(String(e.port)),h(e.username),re(e.remotePath),ie(e.remotePath))},[t]);let me=async(e,t)=>{Y(!0),N(null);let n=await Bi(e,s,t);Y(!1),n.ok?(re(n.path),ie(n.path),oe(n.items)):N(n.error||s(`directoryBrowser.readDirFailed`))},he=async e=>{let n=(e?.host??u).trim(),r=e?.port??(parseInt(f,10)||22),i=(e?.username??m).trim();if(!n||!i){N(s(`directoryBrowser.missingHost`));return}j(!0),N(null);let a=await zi({host:n,port:r,username:i,auth:e?.auth??(g===`password`?{type:`password`,password:v}:g===`key`?{type:`key`,privateKeyPath:b}:{type:`agent`}),saveProfile:E,profileName:e?.profileName||O.trim()||void 0},s);if(j(!1),!a.ok||!a.connectionId){z(a.hostTrust??null),F(!1),N(a.error||s(`directoryBrowser.connectFailed`));return}V(a.connectionId),a.profileSaveError&&N(a.profileSaveError),ee(a.system??null),W(a.tools??null),K(a.suggestedInstall??[]);let o=Ii(t)?Li(t)?.remotePath:null,c=o&&o!==`/`?o:a.system?.homeDir||`/`;re(c),ie(c),me(a.connectionId,c),Hi().then(({profiles:e,localKeys:t})=>{l(e),C(t)})},ge=(0,Q.useRef)(!1);return(0,Q.useEffect)(()=>{e===`remote`&&Hi().then(({profiles:e,localKeys:n})=>{if(l(e),C(n),x(e=>e||n[0]||``),!ge.current&&!B&&!A&&Ii(t)){let n=Li(t);if(n){let t=e.find(e=>e.host===n.host&&(e.username===n.username||!n.username)&&(e.port===n.port||!n.port&&e.port===22))||e.find(e=>e.host===n.host&&e.username===n.username)||e.find(e=>e.host===n.host);t&&(ge.current=!0,d(t.host),p(String(t.port)),h(t.username),_(t.authType),t.privateKeyPath&&x(t.privateKeyPath),he({host:t.host,port:t.port,username:t.username,profileName:t.name,auth:t.authType===`password`?{type:`password`,password:``}:t.authType===`key`?{type:`key`,privateKeyPath:t.privateKeyPath}:{type:`agent`}}))}}})},[e,t,B,A]),{profiles:c,setProfiles:l,sshHost:u,setSshHost:d,sshPort:f,setSshPort:p,sshUser:m,setSshUser:h,sshAuthType:g,setSshAuthType:_,sshPassword:v,setSshPassword:y,sshKeyPath:b,setSshKeyPath:x,localKeys:S,customKeyPathMode:w,setCustomKeyPathMode:T,sshSaveProfile:E,setSshSaveProfile:D,sshProfileName:O,setSshProfileName:k,connecting:A,sshError:M,setSshError:N,trustVerified:P,setTrustVerified:F,trusting:I,setTrusting:L,hostTrustOffer:R,setHostTrustOffer:z,connectionId:B,setConnectionId:V,remoteSystem:H,setRemoteSystem:ee,remoteTools:U,setRemoteTools:W,suggestedTools:G,setSuggestedTools:K,installingTool:q,remoteCwd:ne,remoteDraft:J,setRemoteDraft:ie,remoteItems:ae,loadingRemoteDir:se,showRemoteNew:ce,setShowRemoteNew:le,remoteNewName:ue,setRemoteNewName:de,remoteCreateError:fe,setRemoteCreateError:pe,remoteUpPath:Yi(ne),handleConnectAndProbe:he,loadRemoteDir:me,handleInstallTool:async e=>{if(!B)return;te(!0),N(null);let t=await Vi(B,[e],s);te(!1),t.ok?(K(t=>t.filter(t=>t!==e)),U&&e===`git`&&W({...U,git:{installed:!0,version:s(`directoryBrowser.installed`)}})):N(t.error||s(`directoryBrowser.installToolFailed`,{tool:e}))},commitRemote:e=>{let t=parseInt(f,10)||22,n=H?.homeDir||`/`,a=(e||``).trim()||ne||`/`;a===`~`?a=n:(a.startsWith(`~/`)||a.startsWith(`~\\`))&&(a=`${n.replace(/\/+$/,``)}/${a.slice(2).replace(/\\/g,`/`)}`),i(Fi(m,u,t,a),r),o()},handleCreateRemote:async()=>{let e=ue.trim();if(!e||!B)return;if(n===`project`&&!Ji(e)){pe(s(`invalidProjectName`));return}let t=parseInt(f,10)||22,r=ne.replace(/\/+$/,``)||`/`,i=r===`/`?`/${e}`:`${r}/${e}`,a=Fi(m,u,t,i);pe(null);try{await ln(`/api/fs/mkdir`,{body:{path:a,cwd:a,lang:typeof document<`u`&&document.documentElement.lang||`zh`}}),de(``),le(!1),pe(null),await me(B,ne)}catch(e){pe(e instanceof Error?e.message:String(e))}}}}function $i({mode:e,projectNameDraft:t,setProjectNameDraft:n,ssh:r}){let i=X(),{profiles:a,setProfiles:o,sshHost:s,setSshHost:c,sshPort:l,setSshPort:u,sshUser:d,setSshUser:f,sshAuthType:p,setSshAuthType:m,sshPassword:h,setSshPassword:g,sshKeyPath:_,setSshKeyPath:v,localKeys:y,customKeyPathMode:b,setCustomKeyPathMode:x,sshSaveProfile:S,setSshSaveProfile:C,sshProfileName:w,setSshProfileName:T,connecting:E,sshError:D,setSshError:O,trustVerified:k,setTrustVerified:A,trusting:j,setTrusting:M,hostTrustOffer:N,setHostTrustOffer:P,connectionId:F,setConnectionId:I,remoteSystem:L,setRemoteSystem:R,remoteTools:B,setRemoteTools:V,suggestedTools:H,setSuggestedTools:ee,installingTool:U,remoteCwd:W,remoteDraft:G,setRemoteDraft:K,remoteItems:q,loadingRemoteDir:ne,showRemoteNew:re,setShowRemoteNew:J,remoteNewName:ie,setRemoteNewName:ae,remoteCreateError:oe,setRemoteCreateError:se,remoteUpPath:Y,handleConnectAndProbe:ce,loadRemoteDir:le,handleInstallTool:ue,commitRemote:de,handleCreateRemote:fe}=r;return(0,$.jsx)(`div`,{className:`cwd-ssh-container`,children:F?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-probe-box`,children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-probe-header`,children:[(0,$.jsxs)(`span`,{children:[`🌐 `,d,`@`,s,` (`,L?.os,` `,L?.arch,`)`]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-ssh-profile-del`,onClick:()=>{I(null),R(null),V(null)},children:i(`sshDisconnect`)})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`6px`,flexWrap:`wrap`,fontSize:`10px`},children:[(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${B?.git.installed?`ok`:`missing`}`,children:[`Git: `,B?.git.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${B?.node.installed?`ok`:`missing`}`,children:[`Node: `,B?.node.installed?`✓`:`✗`]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-tool-badge ${B?.bash.installed?`ok`:`missing`}`,children:[`Bash: `,B?.bash.installed?`✓`:`✗`]})]}),H.length>0&&(0,$.jsxs)(`div`,{className:`cwd-ssh-install-box`,children:[(0,$.jsxs)(`div`,{children:[`⚠️ `,i(`directoryBrowser.remoteToolsMissing`)]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`6px`,marginTop:`2px`},children:[(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,disabled:U,onClick:()=>void ue(H[0]),children:U?i(`sshInstalling`):`⚡ ${i(`sshInstallTool`)} ${H[0]}`}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn`,onClick:()=>ee([]),children:i(`sshSkipAndBrowse`)})]})]})]}),(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:W,children:[(0,$.jsx)(Le,{}),(0,$.jsx)(`span`,{children:W})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":i(`workspaceModeRemote`),children:[(0,$.jsx)(bn,{className:`cwd-jump tool-up`,tip:W===`/`?`${i(`cwdGoUp`)} · ${i(`directoryBrowser.alreadyAtTop`)}`:`${i(`cwdGoUp`)} · ${Yi(W)||`/`}`,"aria-disabled":W===`/`||ne,onClick:()=>{if(ne)return;let e=Yi(W);e&&F&&le(F,e)},children:(0,$.jsx)(te,{})}),(0,$.jsx)(bn,{className:`cwd-jump tool-new ${re?`active`:``}`,tip:i(re?`cwdCancel`:`cwdNewFolder`),onClick:()=>J(e=>!e),children:(0,$.jsx)(je,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-spacer`})]}),(0,$.jsxs)(`div`,{className:`cwd-picker-row`,children:[(0,$.jsx)(`input`,{className:`status-cwd-input cwd-picker-input`,value:G,placeholder:i(`enterPath`),spellCheck:!1,onChange:e=>K(e.target.value),onKeyDown:e=>{e.key===`Enter`&&F&&le(F,G)}}),G.trim()&&G.trim()!==W&&F&&(0,$.jsx)(bn,{className:`cwd-jump tool-enter`,tip:`${i(`cwdEnter`)} · ${G.trim()}`,onClick:()=>void le(F,G),children:(0,$.jsx)(St,{})}),(0,$.jsx)(bn,{className:`cwd-jump primary tool-pick`,tip:`${i(`sshOpenRemoteWorkspace`)} · ${G.trim()||W}`,onClick:()=>de(G.trim()||W),children:(0,$.jsx)(z,{})})]}),e===`project`&&(0,$.jsxs)(`div`,{className:`cwd-picker-row cwd-project-name-row`,children:[(0,$.jsx)(Ae,{className:`cwd-project-name-icon`,"aria-hidden":`true`}),(0,$.jsx)(`input`,{className:`status-cwd-input cwd-picker-input`,value:t,placeholder:i(`projectNamePlaceholder`),spellCheck:!1,onChange:e=>n(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),de(G.trim()||W))}})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[!ne&&Y&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${i(`cwdGoUp`)} · ${Y}`,onClick:()=>{F&&le(F,Y)},children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),ne?(0,$.jsx)(`div`,{className:`cwd-empty`,children:i(`directoryBrowser.loadingRemoteDir`)}):q.length===0?(0,$.jsx)(`div`,{className:`cwd-empty`,children:i(`cwdEmpty`)}):q.map(e=>(0,$.jsxs)(`div`,{className:`cwd-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${e.type===`dir`?i(`cwdEnter`):``} ${e.path}`,onClick:()=>{e.type===`dir`&&F&&le(F,e.path)},children:[e.type===`dir`?(0,$.jsx)(Ee,{}):(0,$.jsx)(`span`,{children:`📄`}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),e.type===`dir`&&(0,$.jsx)(bn,{className:`cwd-jump tool-choose`,tip:`${i(`cwdChoose`)} · ${e.path}`,onClick:()=>de(e.path),children:(0,$.jsx)(z,{})})]},e.path))]}),F&&re&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{value:ie,autoFocus:!0,spellCheck:!1,placeholder:i(`cwdNewName`),onChange:e=>{ae(e.target.value),oe&&se(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),fe()):e.key===`Escape`&&(e.stopPropagation(),J(!1),ae(``),se(null))}}),(0,$.jsx)(bn,{className:`cwd-jump primary`,tip:i(`cwdCreate`),onClick:fe,children:(0,$.jsx)(z,{})}),(0,$.jsx)(bn,{className:`cwd-jump`,tip:i(`cwdCancel`),onClick:()=>{J(!1),ae(``),se(null)},children:(0,$.jsx)(Ct,{})})]}),oe&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:oe})]})]}):(0,$.jsxs)(`div`,{className:`cwd-ssh-form`,children:[a.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-profiles-title`,children:[`📋 `,i(`sshSavedProfiles`)]}),a.map(e=>(0,$.jsxs)(`div`,{className:`cwd-ssh-profile-card`,onClick:()=>{c(e.host),u(String(e.port)),f(e.username),m(e.authType),e.privateKeyPath&&v(e.privateKeyPath),ce({host:e.host,port:e.port,username:e.username,profileName:e.name,auth:e.authType===`password`?{type:`password`,password:``}:e.authType===`key`?{type:`key`,privateKeyPath:e.privateKeyPath}:{type:`agent`}})},children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-profile-meta`,children:[(0,$.jsxs)(`span`,{className:`cwd-ssh-profile-name`,children:[(0,$.jsx)(ut,{style:{marginRight:`4px`}}),e.name]}),(0,$.jsxs)(`span`,{className:`cwd-ssh-profile-addr`,children:[e.username,`@`,e.host,`:`,e.port]})]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-ssh-profile-del`,title:i(`delete`),onClick:t=>{t.stopPropagation(),confirm(i(`sshDeleteProfileConfirm`))&&(Ui(e.name),o(t=>t.filter(t=>t.name!==e.name)))},children:(0,$.jsx)(Ne,{})})]},e.name))]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,style:{marginTop:`4px`},children:[(0,$.jsxs)(`label`,{children:[i(`sshHost`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:s,placeholder:`192.168.1.100`,onChange:e=>c(e.target.value)}),(0,$.jsxs)(`label`,{style:{width:`32px`,textAlign:`right`},children:[i(`sshPort`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,style:{width:`45px`,flex:`none`},value:l,onChange:e=>u(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[i(`sshUser`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:d,placeholder:`root / ubuntu`,onChange:e=>f(e.target.value)})]}),(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[i(`sshAuthType`),`:`]}),(0,$.jsxs)(`select`,{className:`cwd-ssh-select`,value:p,onChange:e=>m(e.target.value),children:[(0,$.jsx)(`option`,{value:`password`,children:i(`sshPassword`)}),(0,$.jsx)(`option`,{value:`key`,children:i(`sshKeyPath`)}),(0,$.jsx)(`option`,{value:`agent`,children:i(`sshAgent`)})]})]}),p===`password`&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[i(`sshPassword`),`:`]}),(0,$.jsx)(`input`,{type:`password`,className:`cwd-ssh-input`,value:h,placeholder:`••••••••`,onChange:e=>g(e.target.value)})]}),p===`key`&&(0,$.jsx)($.Fragment,{children:y.length>0?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[i(`sshKeyPath`),`:`]}),(0,$.jsxs)(`select`,{className:`cwd-ssh-select`,value:b||_&&!y.includes(_)?`__custom__`:_,onChange:e=>{let t=e.target.value;t===`__custom__`?x(!0):(x(!1),v(t))},children:[y.map(e=>(0,$.jsx)(`option`,{value:e,children:e},e)),(0,$.jsx)(`option`,{value:`__custom__`,children:i(`sshKeyCustom`)})]})]}),(b||_&&!y.includes(_))&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsx)(`label`,{}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:_,placeholder:`~/.ssh/id_ed25519`,onChange:e=>v(e.target.value)})]})]}):(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[i(`sshKeyPath`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:_,placeholder:`~/.ssh/id_ed25519`,onChange:e=>v(e.target.value)})]})}),(0,$.jsx)(`div`,{className:`cwd-ssh-row`,style:{fontSize:`11px`,color:`var(--text-dim)`},children:(0,$.jsxs)(`label`,{style:{width:`auto`},children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:S,onChange:e=>C(e.target.checked),style:{marginRight:`4px`}}),i(`sshSaveProfile`)]})}),S&&(0,$.jsxs)(`div`,{className:`cwd-ssh-row`,children:[(0,$.jsxs)(`label`,{children:[i(`sshProfileName`),`:`]}),(0,$.jsx)(`input`,{className:`cwd-ssh-input`,value:w,placeholder:`my-server`,onChange:e=>T(e.target.value)})]}),N&&(0,$.jsxs)(`div`,{style:{border:`1px solid #d97706`,borderRadius:`8px`,padding:`8px`,marginTop:`6px`},children:[(0,$.jsx)(`div`,{style:{fontSize:`12px`,fontWeight:600,marginBottom:`4px`},children:N.status===`changed`?i(`directoryBrowser.hostKeyChanged`):i(`directoryBrowser.newHostKey`)}),(0,$.jsxs)(`div`,{style:{fontSize:`11px`,wordBreak:`break-all`,marginBottom:`4px`},children:[N.host,`:`,N.port,` `,N.algorithm,` `,N.fingerprint]}),(0,$.jsx)(`div`,{style:{fontSize:`11px`,color:`var(--text-dim)`,marginBottom:`6px`},children:i(`directoryBrowser.fingerprintHint`)}),(0,$.jsxs)(`label`,{style:{fontSize:`11px`,display:`flex`,gap:`6px`,marginBottom:`6px`},children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:k,onChange:e=>A(e.target.checked)}),(0,$.jsx)(`span`,{children:i(`directoryBrowser.fingerprintVerified`)})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,gap:`8px`},children:[(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,disabled:!k||j,onClick:async()=>{M(!0);let e=await Wi({host:N.host,port:N.port,fingerprint:N.fingerprint,replace:N.status===`changed`},i);M(!1),e.ok?(P(null),ce()):O(e.error||i(`directoryBrowser.trustFailed`))},children:i(`directoryBrowser.trustAndRetry`)}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn`,onClick:()=>{P(null),A(!1)},children:i(`cancel`)})]})]}),D&&(0,$.jsxs)(`div`,{style:{color:`var(--red)`,fontSize:`11px`,padding:`2px 0`},children:[`⚠️ `,D]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-choose-btn primary`,style:{marginTop:`4px`},disabled:E,onClick:()=>void ce(),children:i(E?`sshConnecting`:`sshConnectAndProbe`)})]})})}function ea({currentCwd:e,pathCompletions:t,workspaceRoots:n,onClose:r,onSelectDirectory:i,mode:a=`folder`,onCreateProject:o,className:s,backdropClassName:c,role:l,ariaLabel:u,localOnly:d=!1,initialTab:f,portalContainer:p}){let m=X(),h=_n().remoteSsh&&!d,g=mn(`homeDir`),_=mn(`desktopDir`),v=mn(`pathCompletions`),y=mn(`workspaceRoots`),b=t&&t.length>0?t:v??[],x=n&&n.length>0?n:y??[],[S,C]=(0,Q.useState)(()=>h?f===`local`||f===`remote`?f:Zi()||(Ii(e)?`remote`:`local`):`local`),[w,T]=(0,Q.useState)(``),E=a===`project`&&w.trim()||void 0,D=e=>{C(e);try{localStorage.setItem(Xi,e)}catch{}};(0,Q.useEffect)(()=>{!h&&S===`remote`&&D(`local`)},[h,S]);let[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(``),[M,N]=(0,Q.useState)(!1),[P,F]=(0,Q.useState)(``),[I,L]=(0,Q.useState)(null),[R,B]=(0,Q.useState)(!1),[V,H]=(0,Q.useState)(null),[ee,U]=(0,Q.useState)(-1),W=(0,Q.useRef)(null),G=(0,Q.useRef)(null),K=(0,Q.useRef)(null),q=Qi({activeTab:S,currentCwd:e,mode:a,customProjectName:E,onSelectDirectory:i,onCreateProject:o,onClose:r}),ne=b.filter(e=>e.type===`dir`),re=e=>e.replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase();(0,Q.useEffect)(()=>{V&&ne.some(e=>re(e.path)===re(V))&&K.current?.scrollIntoView({block:`nearest`})},[ne,V]),(0,Q.useEffect)(()=>{if(!Ii(e)){let t=(e||``).replace(/\\/g,`/`)||`@root`;k(t),j(t)}N(!1),F(``),L(null),U(-1)},[e]),(0,Q.useEffect)(()=>{let e=requestAnimationFrame(()=>{W.current?.focus()});return()=>cancelAnimationFrame(e)},[S]),Lt(()=>{M||q.showRemoteNew?(N(!1),F(``),L(null),q.setShowRemoteNew(!1),q.setRemoteNewName(``),q.setRemoteCreateError(null)):r()}),(0,Q.useEffect)(()=>{if(S!==`local`)return;let e=setTimeout(()=>{Z({type:`complete_path`,path:Ki(O)})},60);return()=>clearTimeout(e)},[O,S]),(0,Q.useEffect)(()=>{if(S!==`local`||A===O)return;let e=setTimeout(()=>{Z({type:`complete_path`,path:A})},150);return()=>clearTimeout(e)},[A,O,S]);let J=e=>{let t=e.trim();t&&t!==`@root`&&i(t,E)},ie=e=>{k(e),j(e),U(-1),L(null)},ae=async()=>{let e=P.trim();if(!e||O===`@root`||R)return;if(a===`project`&&!Ji(e)){L(m(`invalidProjectName`));return}let t=a===`project`?qi(O,e):`${Ki(O)}${e}`;B(!0),L(null);try{let e=typeof document<`u`&&document.documentElement.lang||`zh`,n=((await ln(`/api/fs/mkdir`,{body:{path:t,cwd:O,lang:e}})).path||t).replace(/\\/g,`/`);N(!1),F(``),L(null),H(n),j(n),Z({type:`complete_path`,path:Ki(O)})}catch(e){L(e instanceof Error?e.message:String(e))}finally{B(!1)}},oe=e=>{if(e.key===`Escape`)e.stopPropagation(),M?(N(!1),F(``),L(null)):r();else if(e.key===`Enter`&&!e.nativeEvent.isComposing)J(A);else if(e.key===`Tab`){if(ne.length===0)return;e.preventDefault();let t=ee>=0?(ee+1)%ne.length:0;U(t),j(ne[t].path),k(ne[t].path)}},Y=Yi(O),ce=e=>{let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);return/^[A-Za-z]:/.test(t)?t.toLowerCase():t},le=ce(O),ue=!!O&&O!==`@root`&&le!==ce(e)&&!x.some(e=>ce(e)===le);return(0,Er.createPortal)((0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`status-cwd-backdrop ${c??``}`.trim(),onClick:r,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation()}),(0,$.jsxs)(`div`,{className:`cwd-picker ${s??``}`.trim(),role:l,"aria-label":u,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[h?(0,$.jsxs)(`div`,{className:`cwd-mode-tabs`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${S===`local`?`active`:``}`,onClick:()=>D(`local`),children:[`💻 `,m(`workspaceModeLocal`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`cwd-mode-tab ${S===`remote`?`active`:``}`,onClick:()=>D(`remote`),children:[`🌐 `,m(`workspaceModeRemote`)]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-close`,title:m(`close`),"aria-label":m(`close`),onClick:r,children:(0,$.jsx)(Ct,{})})]}):(0,$.jsxs)(`div`,{className:`cwd-mode-tabs cwd-mode-tabs-single`,children:[(0,$.jsxs)(`div`,{className:`cwd-mode-tab active`,style:{cursor:`default`},children:[`💻 `,m(`workspaceModeLocal`)]}),(0,$.jsx)(`button`,{type:`button`,className:`cwd-close`,title:m(`close`),"aria-label":m(`close`),onClick:r,children:(0,$.jsx)(Ct,{})})]}),S===`local`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`cwd-picker-head`,children:(0,$.jsxs)(`span`,{className:`cwd-picker-title`,title:O===`@root`?m(`computer`):O,children:[O===`@root`?(0,$.jsx)(ge,{}):(0,$.jsx)(Ee,{}),(0,$.jsx)(`span`,{children:O===`@root`?m(`computer`):O})]})}),(0,$.jsxs)(`div`,{className:`cwd-toolbar`,role:`toolbar`,"aria-label":m(`projectPickerTitle`),children:[(0,$.jsx)(bn,{className:`cwd-jump ${O===`@root`?`active`:``}`,tip:m(`computer`),onClick:()=>ie(`@root`),children:(0,$.jsx)(ge,{})}),g!==``&&(0,$.jsx)(bn,{className:`cwd-jump ${ce(O)===ce(g)?`active`:``}`,tip:`${m(`homeDir`)} ${g}`,onClick:()=>ie(g),children:(0,$.jsx)(kt,{})}),_!==``&&(0,$.jsx)(bn,{className:`cwd-jump ${ce(O)===ce(_)?`active`:``}`,tip:`${m(`desktopDir`)} ${_}`,onClick:()=>ie(_),children:(0,$.jsx)(se,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-sep`,"aria-hidden":`true`}),(0,$.jsx)(bn,{className:`cwd-jump tool-up`,tip:Y?`${m(`cwdGoUp`)} · ${Y}`:`${m(`cwdGoUp`)} · ${m(`directoryBrowser.alreadyAtTop`)}`,"aria-disabled":!Y,onClick:()=>{Y&&ie(Y)},children:(0,$.jsx)(te,{})}),(0,$.jsx)(bn,{className:`cwd-jump tool-root`,tip:ue?m(`addWorkspaceRootHint`):O===`@root`?`${m(`addWorkspaceRoot`)} · ${m(`directoryBrowser.thisPcNotDirectory`)}`:le===ce(e)?`${m(`addWorkspaceRoot`)} · ${m(`directoryBrowser.alreadyCurrentProject`)}`:`${m(`addWorkspaceRoot`)} · ${m(`directoryBrowser.alreadyWorkspaceRoot`)}`,"aria-disabled":!ue,onClick:()=>{ue&&Z({type:`set_workspace_roots`,roots:[...x,O]})},children:(0,$.jsx)(Ve,{})}),(0,$.jsx)(bn,{className:`cwd-jump tool-new ${M?`active`:``}`,tip:O===`@root`?`${m(`cwdNewFolder`)} · ${m(`directoryBrowser.cannotCreateHere`)}`:m(M?`cwdCancel`:`cwdNewFolder`),"aria-disabled":O===`@root`,onClick:()=>{O!==`@root`&&(M?(N(!1),F(``),L(null)):(F(``),L(null),N(!0)))},children:(0,$.jsx)(je,{})}),(0,$.jsx)(`span`,{className:`cwd-toolbar-spacer`}),(0,$.jsx)(bn,{className:`cwd-jump primary tool-pick`,tip:O===`@root`?`${m(`cwdPickCurrent`)} · ${m(`directoryBrowser.thisPcCannotBeWorkspace`)}`:`${m(`cwdPickCurrent`)} · ${O}`,"aria-disabled":O===`@root`,onClick:()=>J(O),children:(0,$.jsx)(z,{})})]}),(0,$.jsxs)(`div`,{className:`cwd-picker-row`,children:[(0,$.jsx)(`input`,{ref:W,className:`status-cwd-input cwd-picker-input`,value:A,placeholder:m(`enterPath`),spellCheck:!1,onChange:e=>{j(e.target.value),U(-1)},onKeyDown:oe}),A.trim()!==``&&A!==O&&(0,$.jsx)(bn,{className:`cwd-jump tool-enter`,tip:`${m(`cwdEnter`)} · ${A.trim()}`,onClick:()=>{k(A.trim()),U(-1)},children:(0,$.jsx)(St,{})})]}),a===`project`&&(0,$.jsxs)(`div`,{className:`cwd-picker-row cwd-project-name-row`,children:[(0,$.jsx)(Ae,{className:`cwd-project-name-icon`,"aria-hidden":`true`}),(0,$.jsx)(`input`,{className:`status-cwd-input cwd-picker-input`,value:w,placeholder:m(`projectNamePlaceholder`),spellCheck:!1,onChange:e=>T(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&(e.preventDefault(),J(A.trim()||O))}})]}),(0,$.jsxs)(`div`,{className:`cwd-list`,children:[Y&&(0,$.jsx)(`div`,{className:`cwd-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${m(`cwdGoUp`)} · ${Y}`,onClick:()=>ie(Y),children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:`..`})]})},`..`),ne.length===0&&!Y&&(0,$.jsx)(`div`,{className:`cwd-empty`,children:m(`cwdEmpty`)}),ne.map(e=>{let t=!!V&&re(e.path)===re(V);return(0,$.jsxs)(`div`,{ref:t?K:void 0,className:`cwd-item${t?` highlighted`:``}`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`cwd-enter`,title:`${m(`cwdEnter`)} ${e.path}`,onClick:()=>{k(e.path),j(e.path),H(null),U(-1)},children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`span`,{className:`cwd-name`,children:e.name})]}),(0,$.jsx)(bn,{className:`cwd-jump tool-choose`,tip:`${m(`cwdChoose`)} · ${e.path}`,onClick:()=>J(e.path),children:(0,$.jsx)(z,{})})]},e.path)})]}),M&&(0,$.jsxs)(`div`,{className:`cwd-picker-foot`,children:[(0,$.jsxs)(`div`,{className:`cwd-newrow`,children:[(0,$.jsx)(`input`,{ref:G,value:P,autoFocus:!0,spellCheck:!1,placeholder:m(`cwdNewName`),onChange:e=>{F(e.target.value),I&&L(null)},onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?(e.preventDefault(),ae()):e.key===`Escape`&&(e.stopPropagation(),N(!1),F(``),L(null))}}),(0,$.jsx)(bn,{className:`cwd-jump primary`,tip:m(`cwdCreate`),onClick:ae,children:(0,$.jsx)(z,{})}),(0,$.jsx)(bn,{className:`cwd-jump`,tip:m(`cwdCancel`),onClick:()=>{N(!1),F(``),L(null)},children:(0,$.jsx)(Ct,{})})]}),I&&(0,$.jsx)(`div`,{className:`project-picker-error`,style:{color:`var(--red)`,fontSize:`11px`,marginTop:`4px`},children:I})]})]}),S===`remote`&&(0,$.jsx)($i,{mode:a,projectNameDraft:w,setProjectNameDraft:T,ssh:q})]})]}),p??document.body)}function ta(e,t,n,r,i){return{x:Math.max(0,Math.min(r,(e-n.left)*r/Math.max(1,n.width))),y:Math.max(0,Math.min(i,(t-n.top)*i/Math.max(1,n.height)))}}function na(e,t){let n=t.points[0];if(!n)return;let r=t.points[t.points.length-1];if(e.save(),e.strokeStyle=t.color,e.fillStyle=t.color,e.lineWidth=t.width,e.lineCap=`round`,e.lineJoin=`round`,t.tool===`text`){e.font=`600 ${Math.max(16,t.width*6)}px system-ui, sans-serif`,e.textBaseline=`top`;for(let[r,i]of(t.text||``).split(`
|
|
4
|
-
`).entries())e.fillText(i,n.x,n.y+r*Math.max(20,t.width*7.5))}else if(t.tool===`rectangle`)e.strokeRect(n.x,n.y,r.x-n.x,r.y-n.y);else if(t.tool===`pen`&&t.points.length===1)e.beginPath(),e.arc(n.x,n.y,t.width/2,0,Math.PI*2),e.fill();else{e.beginPath(),e.moveTo(n.x,n.y);for(let n of t.points.slice(1))e.lineTo(n.x,n.y);if(e.stroke(),t.tool===`arrow`){let i=Math.atan2(r.y-n.y,r.x-n.x),a=Math.max(12,t.width*4);e.beginPath(),e.moveTo(r.x-a*Math.cos(i-Math.PI/6),r.y-a*Math.sin(i-Math.PI/6)),e.lineTo(r.x,r.y),e.lineTo(r.x-a*Math.cos(i+Math.PI/6),r.y-a*Math.sin(i+Math.PI/6)),e.stroke()}}e.restore()}function ra({src:e,onSave:t,onCancel:n,saveLabel:r}){let i=X(),a=(0,Q.useRef)(null),o=(0,Q.useRef)(null),s=(0,Q.useRef)(null),c=(0,Q.useRef)(null),[l,d]=(0,Q.useState)(0),[f,p]=(0,Q.useState)([]),[m,h]=(0,Q.useState)(`pen`),[g,_]=(0,Q.useState)(`#ef4444`),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(!1),[w,T]=(0,Q.useState)(``),E=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>{E.current=!0,x(!1),p([]),T(``);let t=new Image;return t.crossOrigin=`anonymous`,t.onload=()=>{if(!E.current||!a.current)return;o.current=t;let e=Math.min(1,4096/Math.max(t.naturalWidth,t.naturalHeight));a.current.width=Math.max(1,Math.round(t.naturalWidth*e)),a.current.height=Math.max(1,Math.round(t.naturalHeight*e)),x(!0),d(e=>e+1)},t.onerror=()=>{E.current&&T(i(`imagePreviewFailed`))},t.src=e,()=>{E.current=!1,t.onload=null,t.onerror=null,s.current=null,o.current=null}},[e,i]),(0,Q.useEffect)(()=>{let e=a.current,t=e?.getContext(`2d`);if(e&&t&&o.current){t.clearRect(0,0,e.width,e.height),t.drawImage(o.current,0,0,e.width,e.height);for(let e of f)na(t,e);s.current&&na(t,s.current)}},[f,l,b]);let D=e=>ta(e.clientX,e.clientY,e.currentTarget.getBoundingClientRect(),e.currentTarget.width,e.currentTarget.height),O=(e,t)=>{if(c.current===e.pointerId){if(t&&s.current){let t=s.current;t.tool!==`pen`&&(t.points=[t.points[0],D(e)]),p(e=>[...e,t])}s.current=null,c.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId),d(e=>e+1)}};return(0,$.jsxs)(`div`,{className:`image-annotation-editor`,children:[(0,$.jsxs)(`div`,{className:`image-annotation-toolbar`,role:`toolbar`,"aria-label":i(`imageAnnotate`),children:[[[`pen`,dt,`imageAnnotatePen`],[`arrow`,u,`imageAnnotateArrow`],[`rectangle`,_t,`imageAnnotateRectangle`],[`text`,he,`imageAnnotateText`]].map(([e,t,n])=>(0,$.jsxs)(`button`,{type:`button`,className:`btn ${m===e?`active`:``}`,"aria-pressed":m===e,disabled:S,onClick:()=>h(e),children:[(0,$.jsx)(t,{}),i(n)]},e)),(0,$.jsx)(`input`,{type:`color`,"aria-label":i(`imageAnnotateColor`),value:g,disabled:S,onChange:e=>_(e.target.value)}),m===`text`&&(0,$.jsx)(`input`,{type:`text`,className:`image-annotation-text`,"aria-label":i(`imageAnnotateText`),placeholder:i(`imageAnnotateTextHint`),value:v,maxLength:280,disabled:S,onChange:e=>y(e.target.value)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,disabled:!f.length||S,onClick:()=>p(e=>e.slice(0,-1)),children:[(0,$.jsx)(le,{}),i(`imageAnnotateUndo`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:S,onClick:n,children:i(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,disabled:!b||!f.length||S,onClick:async()=>{if(a.current&&!S){C(!0),T(``);try{await t(a.current.toDataURL(`image/png`))}catch{E.current&&T(i(`imageAnnotateSaveFailed`))}finally{E.current&&C(!1)}}},children:r??i(`imageAnnotateSave`)})]}),(0,$.jsx)(`p`,{className:`img-lightbox-hint`,children:i(m===`text`?`imageAnnotateTextHint`:`imageAnnotateHint`)}),w&&(0,$.jsx)(`p`,{role:`alert`,children:w}),(0,$.jsx)(`div`,{className:`image-annotation-stage`,children:(0,$.jsx)(`canvas`,{ref:a,className:`image-annotation-canvas`,"aria-label":i(`imageAnnotateCanvas`),onPointerDown:e=>{if(!b||S||c.current!==null||e.pointerType===`mouse`&&e.button!==0)return;let t=D(e),n={tool:m,color:g,width:Math.max(3,e.currentTarget.width/300),points:[t]};m===`text`?v.trim()&&p(e=>[...e,{...n,text:v.trim()}]):(e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),c.current=e.pointerId,s.current=n,d(e=>e+1))},onPointerMove:e=>{if(!s.current||c.current!==e.pointerId)return;e.preventDefault();let t=D(e);s.current.points=m===`pen`?[...s.current.points,t]:[s.current.points[0],t],d(e=>e+1)},onPointerUp:e=>O(e,!0),onPointerCancel:e=>O(e,!1),onLostPointerCapture:e=>O(e,!1)})})]})}var ia=null,aa={busy:!1,error:``},oa=new Set;function sa(e,t=``){if(aa.busy!==e||aa.error!==t){aa={busy:e,error:t};for(let e of oa)e()}}function ca(){return aa}function la(e){return oa.add(e),()=>{oa.delete(e)}}function ua(e){ia=e}function da(){if(!aa.busy){sa(!0);try{if(!ia)throw Error(`OCR installation is unavailable. Reconnect and retry.`);ia()}catch(e){sa(!1,e instanceof Error?e.message:String(e))}}}var fa=1568,pa=2097152;function ma(e){return e.startsWith(`image/`)&&e!==`image/svg+xml`&&e!==`image/svg`}async function ha(e){if(!e.type.startsWith(`image/`))return null;let t;try{t=await createImageBitmap(e,{imageOrientation:`from-image`})}catch{return null}try{let n=Math.min(1,fa/Math.max(t.width,t.height)),r=Math.max(1,Math.round(t.width*n)),i=Math.max(1,Math.round(t.height*n)),a=e.type===`image/jpeg`||e.type===`image/jpg`?[[`image/jpeg`,.85],[`image/jpeg`,.6],[`image/webp`,.8]]:[[`image/png`,1],[`image/jpeg`,.85],[`image/jpeg`,.6]],o=null;for(let[n,s]of a){let a=document.createElement(`canvas`);a.width=r,a.height=i;let c=a.getContext(`2d`);if(!c)continue;n!==`image/png`&&(c.fillStyle=`#ffffff`,c.fillRect(0,0,r,i)),c.drawImage(t,0,0,r,i);let l=a.toDataURL(n,s),u=l.match(/^data:([^;]+);base64,/),d=u?u[1]:n,f=l.replace(/^data:[^;]*;base64,/,``),p=Math.floor(f.length*3/4);if(o={data:f,mimeType:d,name:e.name,size:p},p<=pa)return o}return o}finally{t.close()}}function ga(e,t){return!!e.trim()||!!(t&&t.length>0)}function _a(e){return e.key?e.key:e.mode===`conversation`?`conv|${e.conversationId??``}|${e.sessionPath??``}`:e.path}function va(e){let{attachments:t,conversationRefSupported:n}=e;return!n&&t.some(e=>e.mode===`conversation`)?{level:`warning`,key:`chatInputConversationRefUnsupported`}:null}function ya(e){let t=[],n=[],r=[];for(let i of e){let e=(i.path??``).trim();if(e){t.includes(e)||t.push(e);continue}let a=(i.imageData??i.fileData??``).trim();a?n.push({...i.name?{name:i.name}:{},...i.mimeType?{mimeType:i.mimeType}:{},data:a}):r.push(i.name?.trim()||`(unnamed)`)}return{materials:t,blobs:n,unusable:r}}function ba(e,t){let n=e.indexOf(t);return n<0?[...e]:[...e.slice(0,n),...e.slice(n+1)]}function xa(e,t,n){return typeof n==`number`&&Number.isInteger(n)&&n>=0&&n<e.length&&e[n]===t?[...e.slice(0,n),...e.slice(n+1)]:ba(e,t)}function Sa(e){if(!e||typeof e!=`object`)return null;let t=e;return typeof t.text!=`string`||!t.text.trim()||typeof t.messageId!=`string`||!t.messageId||typeof t.role!=`string`||!t.role?null:{text:t.text,messageId:t.messageId,role:t.role,...typeof t.sessionId==`string`&&t.sessionId?{sessionId:t.sessionId}:{}}}function Ca(e){return`<quoted-text>\n${JSON.stringify(e)}\n</quoted-text>`}function wa(e){let t=/^<quoted-text>\n([^\n]*)\n<\/quoted-text>$/.exec(e);if(!t)return null;try{return Sa(JSON.parse(t[1]))}catch{return null}}function Ta(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function Ea(e,t=[],n=[],r=[]){let i=[],a=(e??``).trim();a&&i.push(a);for(let e of r)e&&i.push(`<attached-image name="${Ta(e)}" />`);for(let e of t){let t=(e??``).trim();t&&i.push(t)}for(let e of n)i.push(Ca(e));return i.join(`
|
|
5
|
-
|
|
6
|
-
`)}function Da(e){let t=e,n=[];for(;;){let e=/(?:^|\n\n)(<quoted-text>\n[^\n]*\n<\/quoted-text>)$/.exec(t),r=e?wa(e[1]):null;if(!e||!r)break;n.unshift(r),t=t.slice(0,e.index)}let r=[];return t=t.replace(/(?:^|\n\n)?<attached-image name="([^"]*)"\s*\/>/g,(e,t)=>(r.push({type:`image`,name:t}),``)),t=t.replace(/(?:^|\n\n)?<file path="([^"]*)"(?:\s+size="[^"]*")?(?:\s+lines="(\d+)-(\d+)")?\s*\/>/g,(e,t,n,i)=>{let a=t.split(/[\\/]/).pop()??t,o=n&&i?{start:Number(n),end:Number(i)}:void 0;return r.push({type:`file`,name:a,path:t,lines:o}),``}),t=t.replace(/(?:^|\n\n)?<folder path="([^"]*)"\s*\/>/g,(e,t)=>{let n=t.split(/[\\/]/).pop()??t;return r.push({type:`folder`,name:n,path:t}),``}),t=t.replace(/(?:^|\n\n)?<browser-page url="([^"]*)" title="([^"]*)">[\s\S]*?<\/browser-page>/g,(e,t,n)=>(r.push({type:`page`,name:n||t,url:t}),``)),t=t.replace(/(?:^|\n\n)?<conversation-ref[^>]*title="([^"]*)"[^>]*>[\s\S]*?<\/conversation-ref>/g,(e,t)=>(r.push({type:`conversation`,name:t}),``)),t=t.replace(/(?:^|\n\n)?<canvas-ref id="([^"]*)" title="([^"]*)">[\s\S]*?<\/canvas-ref>/g,(e,t,n)=>{let i=e=>e.replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/g,`&`);return r.push({type:`canvas`,path:i(t),name:i(n)||i(t)}),``}),t=t.replace(/(?:^|\n\n)?<vision-bridge>[\s\S]*?<\/vision-bridge>/g,()=>(r.push({type:`vision-bridge`,name:`视觉转写`}),``)),r.length>0&&(t=t.trim()),{text:t,quotes:n,...r.length?{attachments:r}:{}}}var Oa=15e3,ka=6e5,Aa=`echo-`;function ja(e){return`${Aa}${e}`}function Ma(e){return typeof e==`string`&&e.startsWith(`echo-`)}function Na(){return{adds:[],removes:[],echoes:[]}}function Pa(e){return e.replace(/&/g,`&`).replace(/"/g,`"`).replace(/</g,`<`).replace(/>/g,`>`)}function Fa(e,t){let n=(t??[]).filter(e=>e.mode===`quote`).map(e=>Sa(e.quote)).filter(e=>e!==null),r=[],i=[];for(let e of t??[])if(e.mode!==`quote`){if(e.imageData)r.push(e.name||`image.png`);else if(e.fileData){let t=e.name||`file`;i.push(`<file path="${Pa(t)}" />`)}else if(e.mode===`page`){let t=e.path||``,n=e.name||t;i.push(`<browser-page url="${Pa(t)}" title="${Pa(n)}"></browser-page>`)}else if(e.mode===`canvas`)i.push(`<canvas-ref id="${Pa(e.path)}" title="${Pa(e.name||e.path)}"></canvas-ref>`);else if(e.mode===`conversation`){let t=e.name||e.conversationId||e.sessionPath||`conversation`;i.push(`<conversation-ref title="${Pa(t)}"></conversation-ref>`)}else if(e.path){let t=e.lines?` lines="${e.lines.start}-${e.lines.end}"`:``;i.push(`<file path="${Pa(e.path)}"${t} />`)}}return Ea(e,i,n,r)}function Ia(e){let t=Da(e);return`${t.text.trim()}\u0000${t.quotes.map(e=>`${e.role}:${e.messageId}:${e.text.trim()}`).join(`|`)}`}function La(e,t){return e===t||Ia(e)===Ia(t)}function Ra(e,t){let n=0;for(let r of e)La(r,t)&&(n+=1);return n}function za(e,t){let n=t.trim(),r=0;for(let t of e)t.role===`user`&&(Ma(t.id)||(t.content.find(e=>e.type===`text`)?.text??``).trim()===n&&(r+=1));return r}function Ba(e){let{state:t,text:n,attachments:r,queue:i=!1,goalReviewing:a=!1}=e;if(!t||!t.isStreaming||t.delegateMode===!0)return!1;let o=(n??``).trim();return!(!ga(o,r)||o.startsWith(`/`)||a&&!i)}function Va(e){let{state:t,text:n,attachments:r}=e;if(!t||t.isStreaming||t.delegateMode===!0)return!1;let i=(n??``).trim();return!(!ga(i,r)||i.startsWith(`/`))}function Ha(e,t,n){let r=n.now??Date.now();if(!t||!Va({state:t,text:n.text,attachments:n.attachments}))return{tracker:e,state:t};let i=(n.text??``).trim(),a=Ka(e),o={conversationId:t.conversationId,rawText:i,messageId:qa(a),baselineUserMsgMatches:za(t.messages,i),createdAt:r},s=Ja(o,r);return{tracker:{...e,echoes:[...Ua(e),o]},state:{...t,messages:[...t.messages,s]}}}function Ua(e){return e.echoes??[]}function Wa(e,t){return e.queuedAt===void 0?t-e.createdAt>=Oa:t-e.queuedAt>=ka}function Ga(e,t,n,r=Date.now()){let i=(n??``).trim();if(!i)return e;let a=!1,o=Ua(e).map(e=>a||e.queuedAt!==void 0||e.conversationId!==t||e.rawText!==i?e:(a=!0,{...e,queuedAt:r}));return a?{...e,echoes:o}:e}function Ka(e){let t=0;for(let n of Ua(e)){let e=Number.parseInt(n.messageId.slice(5),10);Number.isFinite(e)&&e>t&&(t=e)}return t+1}function qa(e){return ja(e)}function Ja(e,t){let n=[];return e.rawText&&n.push({type:`text`,text:e.rawText}),{id:e.messageId,role:`user`,content:n,timestamp:t}}function Ya(e,t,n){let r=n.now??Date.now();if(!Ba({state:t,text:n.text,attachments:n.attachments,queue:n.queue,goalReviewing:n.goalReviewing})||!t)return{tracker:e,state:t};let i=t?.engineCapabilities?.steer!==!1&&n.engine!==`dsh`,a=n.queue||!i?`followUp`:`steer`,o=Fa(n.text,n.attachments),s=Da(o).text.trim(),c=a===`steer`?t.queue.steering:t.queue.followUp,l=e.adds.filter(e=>e.conversationId===t.conversationId&&e.kind===a&&La(e.formattedText,o)).length,u=Ra(c,o),d=Math.max(0,u-l),f=za(t.messages,s),p={conversationId:t.conversationId,kind:a,rawText:s,formattedText:o,baselineQueueMatches:d,baselineUserMsgMatches:f,createdAt:r},m=a===`steer`?{...t.queue,steering:[...t.queue.steering,o]}:{...t.queue,followUp:[...t.queue.followUp,o]};return{tracker:{adds:[...e.adds,p],removes:e.removes,echoes:Ua(e)},state:{...t,queue:m}}}function Xa(e,t,n){if(!t)return{tracker:e,state:t};let r=n.now??Date.now(),{kind:i,text:a,index:o}=n,s=xa(i===`steer`?t.queue.steering:t.queue.followUp,a,o),c=e.adds,l=c.findIndex(e=>e.conversationId===t.conversationId&&e.kind===i&&La(e.formattedText,a));l>=0&&(c=[...c.slice(0,l),...c.slice(l+1)]);let u=Ra(s,a),d={conversationId:t.conversationId,kind:i,text:a,index:o,expectedRemainingMatches:u,createdAt:r},f=i===`steer`?{...t.queue,steering:s}:{...t.queue,followUp:s};return{tracker:{adds:c,removes:[...e.removes,d],echoes:Ua(e)},state:{...t,queue:f}}}function Za(e,t,n=Date.now()){if(e.adds.length===0&&e.removes.length===0)return{tracker:e,state:t};let r=t.conversationId;if(!t.isStreaming){let i=e.adds.filter(e=>e.conversationId!==r&&n-e.createdAt<15e3),a=e.removes.filter(e=>e.conversationId!==r&&n-e.createdAt<3e3);return i.length===e.adds.length&&a.length===e.removes.length?{tracker:e,state:t}:{tracker:{...e,adds:i,removes:a},state:t}}let i=[...t.queue.steering],a=[...t.queue.followUp],o=!1,s=[];for(let t of e.removes){if(n-t.createdAt>=3e3)continue;if(t.conversationId!==r){s.push(t);continue}let e=t.kind===`steer`?i:a;if(Ra(e,t.text)>t.expectedRemainingMatches){let n=xa(e,t.text,t.index);if(n.length===e.length){let r=e.findIndex(e=>La(e,t.text));r>=0&&(n=[...e.slice(0,r),...e.slice(r+1)])}t.kind===`steer`?i=n:a=n,o=!0,s.push(t)}}let c=[],l=new Map;for(let s of e.adds){if(n-s.createdAt>=15e3)continue;if(s.conversationId!==r){c.push(s);continue}let e=s.kind===`steer`?i:a,u=`${s.kind}:${Ia(s.formattedText)}`,d=l.get(u)??0,f=Ra(e,s.formattedText),p=za(t.messages,s.rawText),m=f>s.baselineQueueMatches+d,h=p>s.baselineUserMsgMatches;m?l.set(u,d+1):h||(s.kind===`steer`?i.push(s.formattedText):a.push(s.formattedText),l.set(u,d+1),o=!0,c.push(s))}let u=c.length===e.adds.length&&s.length===e.removes.length?e:{...e,adds:c,removes:s};return o?{tracker:u,state:{...t,queue:{steering:i,followUp:a}}}:{tracker:u,state:t}}function Qa(e,t){if(!t)return{tracker:e,state:t};let n=t.conversationId,r=e.adds.filter(e=>e.conversationId===n),i=Ua(e).filter(e=>e.conversationId===n);if(r.length===0&&i.length===0)return{tracker:e,state:t};let a=[...t.queue.steering],o=[...t.queue.followUp];for(let e of r)e.kind===`steer`?a=xa(a,e.formattedText):o=xa(o,e.formattedText);let s=new Set(i.map(e=>e.messageId)),c=s.size>0?t.messages.filter(e=>!s.has(e.id)):t.messages;return{tracker:{adds:e.adds.filter(e=>e.conversationId!==n),removes:e.removes,echoes:Ua(e).filter(e=>e.conversationId!==n)},state:{...t,queue:{steering:a,followUp:o},messages:c}}}function $a(e,t,n=Date.now()){if(Ua(e).length===0)return{tracker:e,state:t};if(t.isStreaming){let r=new Set,i=[];for(let a of Ua(e))Wa(a,n)?a.conversationId===t.conversationId&&r.add(a.messageId):a.conversationId===t.conversationId?r.add(a.messageId):i.push(a);let a=i.length===Ua(e).length?e:{...e,echoes:i};return r.size===0?{tracker:a,state:t}:{tracker:a,state:{...t,messages:t.messages.filter(e=>!r.has(e.id))}}}let r=t.conversationId,i=[],a=new Set,o=[];for(let s of Ua(e))Wa(s,n)?s.conversationId===r&&a.add(s.messageId):s.conversationId===r?za(t.messages,s.rawText)>s.baselineUserMsgMatches?a.add(s.messageId):(i.push(s),t.messages.some(e=>e.id===s.messageId)||o.push(Ja(s,s.createdAt))):i.push(s);let s=i.length===Ua(e).length?e:{adds:e.adds,removes:e.removes,echoes:i};if(a.size===0&&o.length===0)return{tracker:s,state:t};let c=a.size>0?t.messages.filter(e=>!a.has(e.id)):[...t.messages];return{tracker:s,state:{...t,messages:o.length>0?[...c,...o]:c}}}function eo(e){let{current:t,source:n,snapshot:r,answered:i,activeConversationId:a,pendingDelivery:o}=e,s=!!(r?.conversationId&&a&&r.conversationId!==a),c=!!(t?.id&&(i.has(t.id)||o?.(t.id))),l=!!(r?.id&&(i.has(r.id)||o?.(r.id,r.owner)));return c||l&&t?.id===r?.id?{changed:!0,question:null,source:`live`}:r&&r.id&&!l&&!s?t?.id===r.id?{changed:!1,question:t,source:n}:{changed:!0,question:r,source:`snapshot`}:t&&t.conversationId&&a&&t.conversationId!==a||!r&&t&&n===`snapshot`&&!s?{changed:!0,question:null,source:`live`}:{changed:!1,question:t,source:n}}function to(){return{flows:[],results:{}}}function no(e,t){let n=e.findIndex(e=>e.flowId===t.flowId);return n<0?[...e,t]:e.map((e,r)=>r===n?t:e)}function ro(e,t){switch(t.type){case`provider_oauth_started`:{let n={...e.results};return delete n[t.provider],{flows:[...e.flows.filter(e=>e.provider!==t.provider),{flowId:t.flowId,provider:t.provider}],results:n}}case`provider_oauth_flows`:return{...e,flows:t.flows.map(e=>({...e}))};case`provider_oauth_prompt`:{let n=e.flows.find(e=>e.flowId===t.flowId);return{...e,flows:no(e.flows,{...n,flowId:t.flowId,provider:t.provider,promptId:t.promptId,prompt:t.prompt})}}case`provider_oauth_event`:{let n=e.flows.find(e=>e.flowId===t.flowId);return{...e,flows:no(e.flows,{...n,flowId:t.flowId,provider:t.provider,event:t.event,promptId:void 0,prompt:void 0})}}case`provider_oauth_result`:return{flows:e.flows.filter(e=>e.flowId!==t.flowId),results:{...e.results,[t.provider]:{ok:t.ok,...t.cancelled===void 0?{}:{cancelled:t.cancelled},...t.error===void 0?{}:{error:t.error}}}};case`provider_oauth_logout_result`:return{...e,results:{...e.results,[t.provider]:{ok:t.ok,...t.error===void 0?{}:{error:t.error}}}}}}function io(e,t){return t?`${t}\u0000${e}`:e}var ao=new Map;function oo(e){let t=io(e.id,e.owner);if(ao.delete(t),ao.set(t,e),ao.size>64){let e=ao.keys().next().value;e!==void 0&&ao.delete(e)}return Z(e)}function so(e,t){if(t)ao.delete(io(e,t));else{ao.delete(e);for(let t of ao.keys())t.endsWith(`\u0000${e}`)&&ao.delete(t)}}function co(e,t){if(ao.has(io(e,t)))return!0;if(!t){for(let t of ao.keys())if(t===e||t.endsWith(`\u0000${e}`))return!0}return!1}function lo(){let e=Array.from(ao.values());for(let t of e)if(!Z(t))return}function uo(){ao.clear()}var fo=e=>e.trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase(),po=`pi-web-ui:conv-order-promoted:v1`,mo=(e=`pi`,t)=>JSON.stringify([e,fo(t)]),ho=new class{positions=new Map;initialized=new Set;bottom=new Map;nextKey=0;version=0;listeners=new Set;submittedEvents=new Set;persistedPromoted=new Map;constructor(){this.restorePromoted()}restorePromoted(){try{if(typeof sessionStorage>`u`)return;let e=sessionStorage.getItem(po);if(!e)return;let t=JSON.parse(e);if(typeof t.version==`number`&&t.version>this.version&&(this.version=t.version),Array.isArray(t.entries))for(let[e,n]of t.entries)typeof e==`string`&&typeof n==`number`&&n>0&&this.persistedPromoted.set(e,n)}catch{}}savePromoted(){try{if(typeof sessionStorage>`u`)return;for(;this.persistedPromoted.size>512;)this.persistedPromoted.delete(this.persistedPromoted.keys().next().value);sessionStorage.setItem(po,JSON.stringify({version:this.version,entries:[...this.persistedPromoted.entries()]}))}catch{}}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));getSnapshot=()=>this.version;aliases(e,t){let n=t.sessionId&&(!t.id||fo(t.sessionId)!==fo(t.id))?fo(t.sessionId):``;return[n?`session:${n}`:``,t.sessionFile||t.path?`file:${fo(t.sessionFile||t.path)}`:``,t.id?`conversation:${t.id}`:``].filter(Boolean).map(t=>`${e}:${t}`)}remember(e,t){let n=this.aliases(e,t),r=n.flatMap(e=>this.positions.get(e)??[]),i=(t.sessionId&&(!t.id||fo(t.sessionId)!==fo(t.id))?fo(t.sessionId):void 0)??r.find(e=>e.sessionId)?.sessionId,a=[...new Set(r.filter(e=>!i||!e.sessionId||e.sessionId===i))].sort((e,t)=>e.key-t.key),o=this.initialized.has(e)?(this.bottom.get(e)??0)-1:t.modified??Date.now(),s=a[0]??{key:this.nextKey++,modified:o,promoted:0};if(s.promoted===0&&this.persistedPromoted.size>0)for(let e of n){let t=this.persistedPromoted.get(e);t&&t>s.promoted&&(s.promoted=t)}i&&(s.sessionId=i),!this.initialized.has(e)&&t.modified!=null&&(s.modified=t.modified),this.bottom.set(e,Math.min(this.bottom.get(e)??s.modified,s.modified));for(let e of a.slice(1)){s.promoted=Math.max(s.promoted,e.promoted);for(let[t,n]of this.positions)n===e&&this.positions.set(t,s),n.parent===e&&(n.parent=s)}for(let e of n)this.positions.set(e,s);return t.parentId?s.parent=this.positions.get(`${e}:conversation:${t.parentId}`):t.id&&delete s.parent,this.promoteAncestors(s),s}promoteAncestors(e){let t=new Set;for(let n=e.parent;n&&!t.has(n);n=n.parent)t.add(n),n.promoted=Math.max(n.promoted,e.promoted)}observe(e,t,n=!0){for(let n of t)this.remember(e,n);n&&t.length>0&&this.initialized.add(e)}sort(e,t,n,r=!0){let i=t.map(e=>({item:e,target:n(e)}));this.observe(e,i.map(e=>e.target),r);let a=i.map(({item:t,target:n})=>({item:t,position:this.remember(e,n)}));return a.sort((e,t)=>t.position.promoted-e.position.promoted||t.position.modified-e.position.modified||e.position.key-t.position.key),a.map(({item:e})=>e)}key(e,t){return this.remember(e,t).key}promote(e,t,n){let r=this.remember(e,t);if(n){let r=JSON.stringify([e,t.sessionId||t.id,n]);if(this.submittedEvents.has(r))return;this.submittedEvents.add(r),this.submittedEvents.size>512&&this.submittedEvents.delete(this.submittedEvents.values().next().value)}r.promoted=++this.version;for(let n of this.aliases(e,t))this.persistedPromoted.delete(n),this.persistedPromoted.set(n,r.promoted);this.savePromoted(),this.promoteAncestors(r);for(let e of this.listeners)e()}clear(){this.positions.clear(),this.initialized.clear(),this.bottom.clear(),this.submittedEvents.clear(),this.persistedPromoted.clear();try{typeof sessionStorage<`u`&&sessionStorage.removeItem(po)}catch{}this.nextKey=0,this.version++;for(let e of this.listeners)e()}};function go(e,t,n){let r=new Map(t.map(e=>[e.id,e])),i=r.get(e.conversationId),a={...i,id:e.conversationId,sessionId:e.sessionId||i?.sessionId,sessionFile:e.sessionFile||i?.sessionFile},o=[a],s=new Set([a.id]),c=i;for(;c?.parentId&&!s.has(c.parentId);){let e=r.get(c.parentId);if(!e)break;s.add(c.parentId),o.push(e),c=e}let l=c?.cwd??e.cwd,u=mo(`all`,l);if(ho.observe(u,o,!1),ho.promote(u,a,n),e.engine&&e.engine!==`all`){let t=mo(e.engine,l);ho.observe(t,o,!1),ho.promote(t,a,n)}}function _o(){return(0,Q.useSyncExternalStore)(ho.subscribe,ho.getSnapshot)}var vo=15e3;function yo(e){return(e??``).trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase()}function bo(e,t,n=Date.now()){return t.type===`set_cwd`&&t.path?{path:t.path,at:n}:e}function xo(e,t,n,r=Date.now()){return e.type!==`new_chat`||e.cwd||!t||r-t.at>vo||yo(t.path)===yo(n)?e:{...e,cwd:t.path}}function So(e,t){return e&&(t.kind===`snapshot`?yo(t.cwd)===yo(e.path)?null:e:t.transitionKind!==`cwd`||t.phase!==`done`&&t.phase!==`error`?e:yo(t.target)===yo(e.path)?null:e)}var Co=e=>e?e.trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase():``,wo=`pi-web-client-id`,To=`pi-web-client-id:`,Eo=`__PI_CID__:`,Do=6e4,Oo=new Map,ko=new Map;function Ao(e,t=Date.now()){let n=(Oo.get(e)??0)+1;Oo.set(e,n),t-(ko.get(e)??-1/0)<Do||(ko.set(e,t),console.debug(`[ws] 未处理的服务端消息类型「${e}」(累计 ${n} 条)`))}var jo=null;function Mo(){try{if(typeof window<`u`){let e=window.piDesktop?.agentClientId;if(typeof e==`string`&&e.trim())return e.trim()}}catch{}try{if(typeof window<`u`&&typeof window.name==`string`&&window.name){let e=window.name;if(e.startsWith(To)){let t=e.slice(17).trim();if(t)return t}let t=e.indexOf(Eo);if(t!==-1){let n=e.slice(t+11).trim();if(n)return n}}}catch{}try{if(typeof sessionStorage<`u`){let e=sessionStorage.getItem(wo);if(e)return e}}catch{}return null}function No(e){try{if(typeof window<`u`){let t=typeof window.name==`string`?window.name:``;if(!t||t.startsWith(To))window.name=`${To}${e}`;else{let n=t.indexOf(Eo),r=n===-1?t:t.slice(0,n);window.name=`${r}${Eo}${e}`}}}catch{}try{typeof sessionStorage<`u`&&sessionStorage.setItem(wo,e)}catch{}}function Po(){if(jo)return jo;let e=Mo();return e||=or(),No(e),jo=e,e}var Fo=`pi-web-last-cwd`;function Io(){try{return localStorage.getItem(Fo)}catch{return null}}function Lo(e){try{localStorage.setItem(Fo,e)}catch{}}function Ro(e){try{let t=localStorage.getItem(Fo);if(!t)return;let n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase();(t===e||n(t)===n(e))&&localStorage.removeItem(Fo)}catch{}}var zo=`pi-web-recent-sessions:`;function Bo(e,t){let n=t??`pi`;return e?`${zo}${n}:${Co(e)}`:`pi-web-recent-sessions:${n}:default`}function Vo(e,t){try{let n=e??Io();if(t){let e=Bo(n,t),r=localStorage.getItem(e);if(r){let e=JSON.parse(r);if(Array.isArray(e))return e}}else for(let e of[`all`,`pi`]){let t=localStorage.getItem(Bo(n,e));if(t){let n=JSON.parse(t);if(Array.isArray(n)&&(e!==`all`||n.length>0))return n}}if(n){for(let e of[`all`,`pi`,`default`]){if(e===(t??`pi`))continue;let r=Bo(n,e),i=localStorage.getItem(r);if(i){let e=JSON.parse(i);if(Array.isArray(e)&&e.length>0)return e}}let e=`:${Co(n)}`;for(let t=0;t<localStorage.length;t++){let n=localStorage.key(t);if(n&&n.startsWith(zo)&&n.endsWith(e)){let e=localStorage.getItem(n);if(e){let t=JSON.parse(e);if(Array.isArray(t)&&t.length>0)return t}}}}return[]}catch{return[]}}var Ho=new Map;function Uo(e){let t=Ho.get(e);if(t)return t;let n=e.toLowerCase().replace(/\\/g,`/`).replace(/\/+$/,``),r=n.replace(/^\/+/,``);return t={normP:n,sdkSlug1:`--${r.replace(/[/:]/g,`-`)}--`,sdkSlugRoot:r.endsWith(`:`)?`--${r.replace(/[/:]/g,`-`)}----`:``,sdkSlug2:`--${r.replace(/[^a-zA-Z0-9]/g,`-`)}--`},Ho.size>=256&&Ho.clear(),Ho.set(e,t),t}function Wo(e,t){if(!e||!t)return!0;if(typeof e==`object`&&e.cwd)return Co(e.cwd)===Co(t);let n=typeof e==`object`?e.path:e;if(!n||n.startsWith(`conv:`)||n.startsWith(`virtual:`))return!0;let r=n.toLowerCase().replace(/\\/g,`/`),{sdkSlug1:i,sdkSlugRoot:a,sdkSlug2:o}=Uo(t);if(!r.includes(`/`))return!0;let s=r.split(`/`).filter(Boolean).slice(0,-1).find(e=>e.startsWith(`--`)&&e.endsWith(`--`));return!s||s===i||!!a&&s===a||s===o}function Go(e,t,n){try{let r=e??Io(),i=r?t.filter(e=>Wo(e,r)):t,a=Bo(r,n);if(localStorage.setItem(a,JSON.stringify(i.slice(0,50))),n===`all`)for(let e of[`pi`,`default`])localStorage.removeItem(Bo(r,e))}catch{}}function Ko(e,t,n){try{let r=Co(e);if(!r)return;let i=e=>{let t=localStorage.getItem(e);if(!t)return;let n=JSON.parse(t);if(!Array.isArray(n))return;let i=n.filter(e=>Co(e?.path)!==r);i.length!==n.length&&localStorage.setItem(e,JSON.stringify(i.slice(0,50)))};if(n&&n!==`all`){i(Bo(t??Io(),n));return}let a=t??Io(),o=a?Co(a):``,s=o?`:${o}`:``;for(let e=0;e<localStorage.length;e++){let t=localStorage.key(e);t&&t.startsWith(zo)&&(!s||t.endsWith(s))&&i(t)}}catch{}}function qo(e){try{let t=Co(e);if(!t)return;let n=`:${t}`;for(let e=localStorage.length-1;e>=0;e--){let t=localStorage.key(e);t&&t.startsWith(zo)&&t.endsWith(n)&&localStorage.removeItem(t)}}catch{}}var Jo=`pi-web-recent-conversations:v1`;function Yo(e){try{localStorage.setItem(Jo,JSON.stringify({conversations:e.conversations.slice(0,100),elsewhere:e.elsewhere.slice(0,50),activeConversationId:e.activeConversationId}))}catch{}}function Xo(){return W(P())}var Zo=`pi-web-recent-projects`,Qo=`pi-web-removed-projects`,$o=new Set;function es(){try{let e=localStorage.getItem(Qo);if(!e)return new Set;let t=JSON.parse(e);return Array.isArray(t)?new Set(t.filter(e=>typeof e==`string`)):new Set}catch{return new Set}}function ts(e){try{e.size===0?localStorage.removeItem(Qo):localStorage.setItem(Qo,JSON.stringify([...e].slice(-50)))}catch{}}function ns(e){let t=Co(e);if(!t)return;$o.add(t);let n=es();n.add(t),ts(n)}function rs(e){let t=Co(e);if(!t)return;$o.delete(t);let n=es();n.delete(t)&&ts(n)}function is(e){let t=Co(e);return!!(t&&$o.has(t))}function as(e){let t=new Set(e.map(e=>Co(e.path)).filter(Boolean));for(let e of $o)t.has(e)||$o.delete(e);let n=es(),r=!1;for(let e of t)!$o.has(e)&&n.delete(e)&&(r=!0);r&&ts(n)}function os(){try{let e=localStorage.getItem(Zo);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t:[]}catch{return[]}}function ss(e){try{localStorage.setItem(Zo,JSON.stringify(e.slice(0,20)))}catch{}}function cs(e){try{let t=os(),n=e=>e.trim().replace(/[\\/]+$/,``).toLowerCase(),r=n(e);ss(t.filter(e=>n(e.path)!==r))}catch{}}var ls=typeof WebSocket<`u`&&WebSocket.OPEN!==void 0?WebSocket.OPEN:1,us=e=>!!(e&&e.readyState===ls);function ds(e,t,n){let{wsRef:r,chatApi:i,pendingCwdRef:a,pendingNewChatPromoteRef:o,answeredQuestionsRef:s,questionSourceRef:c,dispatch:l}=e,u=r.current;if(!us(u))return!1;let d=i.current.chat;t.type!==`terminal_input`&&t.type!==`terminal_resize`&&t.type!==`terminal_kill`&&t.type!==`rename_terminal`&&t.type!==`terminal_attach`||t.ownerKind||(t={...t,ownerKind:`client`});let f=d.state;if(a.current=bo(a.current,t),t=xo(t,a.current,f?.cwd),t.type===`load_earlier_messages`&&f&&(!t.conversationId||t.conversationId===f.conversationId)&&(t={...t,conversationId:f.conversationId,historyGeneration:t.historyGeneration??f.historyGeneration,beforeId:t.beforeId??f.messages[0]?.id,before:t.before??f.historyStart}),(t.type===`new_chat`||t.type===`new_cli_chat`||t.type===`open_bot_chat`&&t.botId||t.type===`switch_session`&&(t.path||t.sessionId)||(t.type===`switch_conversation`||t.type===`open_shared_conversation`||t.type===`take_over_conversation`)&&t.id||t.type===`open_scheduled_conversation`)&&rr(),t.type===`delete_session`&&t.path&&l({type:`optimistic_delete_session`,path:t.path}),t.type===`delete_project_sessions`&&t.path&&l({type:`optimistic_delete_project_sessions`,cwd:t.path}),t.type===`remove_project`||t.type===`destroy_sandbox`)`path`in t&&typeof t.path==`string`&&t.path&&(ns(t.path),cs(t.path));else if(t.type===`set_cwd`&&t.path){rs(t.path);let e=(f?.cwd??``).trim().replace(/[\\/]+$/,``).toLowerCase(),n=t.path.trim().replace(/[\\/]+$/,``).toLowerCase();n&&n!==e&&l({type:`transition_start`,kind:`cwd`,target:t.path,progress:14,textKey:`transitionSwitchWorkspace`,textVars:{path:t.path}})}else if(t.type===`switch_session`&&(t.path||t.sessionId)){let e=e=>(e??``).trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase(),n=e(f?.sessionFile),r=e(f?.sessionId),i=e(f?.conversationId),a=e(t.path||t.sessionId),o=a===n||a===r||a===i||r&&(r.includes(a)||a.includes(r))||n&&(n.includes(a)||a.includes(n));a&&!o&&l({type:`transition_start`,kind:`session`,target:t.path||t.sessionId||``,progress:14,textKey:`transitionStreamingSession`})}else t.type===`new_chat`||t.type===`new_cli_chat`?(t.cwd&&rs(t.cwd),o.current={prevConvId:f?.conversationId},f&&(t.type===`new_cli_chat`||f.nativeCli||f.messages.length>0||f.isStreaming)&&l({type:`transition_start`,kind:`new_chat`,target:f.cwd,progress:22,textKey:`transitionNewChat`})):t.type===`switch_conversation`&&t.id?f&&t.id!==f.conversationId&&l({type:`transition_start`,kind:`conversation`,target:t.id,progress:35,textKey:`transitionSwitchConversation`}):t.type===`make_dir`&&t.setAsCwd&&t.path&&rs(t.path);if(us(u)){if(t.type===`check_updates_all`&&t.force===!0&&l({type:`updates_check_started`}),t.type===`check_plugin_updates`&&l({type:`plugin_updates_check_started`}),t.type===`edit_message`&&f?.conversationId&&l({type:`reask_start`,conversationId:f.conversationId}),u.send(JSON.stringify(t)),t.type===`prompt`){if(n?.userInitiated&&(t.text.trim()||t.attachments?.length)){let e=t.targetConversationId||f?.conversationId,n=e?d.conversations.find(t=>t.id===e||t.sessionId===e):null;n?go({...n,engine:d.engine,conversationId:n.id},d.conversations):f&&e===f.conversationId&&go({...f,engine:d.engine},d.conversations)}l({type:`optimistic_queue_add`,text:t.text,attachments:t.attachments,queue:t.queue}),l({type:`optimistic_prompt_echo`,text:t.text,attachments:t.attachments})}else if(t.type===`terminal_cli_paste`){if(t.data?.trim()||t.attachments?.length){let e=t.conversationId||f?.conversationId,n=e?d.conversations.find(t=>t.id===e||t.sessionId===e):null;n?go({...n,engine:d.engine,conversationId:n.id},d.conversations):f&&e===f.conversationId&&go({...f,engine:d.engine},d.conversations)}}else t.type===`queue_remove`&&l({type:`optimistic_queue_remove`,kind:t.kind,text:t.text,index:t.index});if(t.type===`question_answer`&&t.global)l({type:`global_question`,id:t.id,owner:t.owner});else if(t.type===`question_answer`){if(l({type:`question_queue_answered`,id:t.id,owner:t.owner}),s.current.add(t.id),s.current.size>64){let e=s.current.values().next().value;e!==void 0&&s.current.delete(e)}if(t.owner){i.current.chat.question?.id===t.id&&l({type:`question`,question:null});let e=i.current.chat.remoteQuestion;e&&e.id===t.id&&e.owner===t.owner&&l({type:`remote_question`,question:null})}else c.current=`live`,l({type:`question`,question:null})}return!0}return!1}var fs=`pi:canvas-list-result`,ps=new Set([`canvas`,`canvases`,`画布`,`工作流`,`workflow`,`workflows`]);function ms(e,t,n,r=10){let i=t.toLowerCase();return e.filter(e=>!i||ps.has(i)||e.name.toLowerCase().includes(i)||e.id.toLowerCase().includes(i)).slice(0,Math.max(0,r)).map(e=>({providerId:`host:canvases`,providerLabel:n,title:`${n} · ${e.name}`,text:e.name,hint:e.id,attachments:[{path:e.id,name:e.name,mode:`canvas`}]}))}function hs(e,t=1800){return new Promise(n=>{let r=e=>{clearTimeout(a),window.removeEventListener(fs,i),n(e)},i=e=>{let t=e.detail;r(t.graphs)},a=setTimeout(()=>r([]),t);window.addEventListener(fs,i);try{e()||r([])}catch{r([])}})}var gs=Object.freeze({status:`idle`,messages:[]}),_s=new Map,vs=new Set,ys=16;function bs(){for(;_s.size>ys;){let e=_s.keys().next().value;if(e===void 0)break;_s.delete(e)}}function xs(){for(let e of vs)e()}function Ss(e,t){let n=(e??``).trim();if(!n)return;let r=_s.get(n);(!r||r.status!==`loading`&&r.status!==`ready`)&&(_s.set(n,{status:`loading`,messages:r?.messages??[]}),bs(),xs(),Z({type:`get_compacted_messages`,compactionMessageId:n,conversationId:t}))}function Cs(e){let t=e.compactionMessageId;t&&(e.error?_s.set(t,{status:`error`,messages:[],error:e.error}):_s.set(t,{status:`ready`,messages:e.messages??[]}),bs(),xs())}function ws(e){let t=_s.get(e);return t?(_s.delete(e),_s.set(e,t),t):gs}function Ts(e){return vs.add(e),()=>{vs.delete(e)}}function Es(e){return(0,Q.useSyncExternalStore)(Ts,()=>ws(e),()=>gs)}function Ds({quote:e,onRemove:t,forceOpen:n=!1}){let r=X(),[i,a]=(0,Q.useState)(!1),o=e.role===`user`?`role.user`:e.role===`assistant`?`role.assistant`:e.role===`toolResult`?`role.tool`:e.role===`bashExecution`?`role.bash`:e.role===`page`?`role.page`:`attachment`;return(0,$.jsxs)(`div`,{className:`quote-card`,children:[(0,$.jsxs)(`details`,{open:i||n,onToggle:e=>a(e.currentTarget.open),children:[(0,$.jsxs)(`summary`,{title:r(`quoteSource`,{id:e.messageId}),children:[(0,$.jsxs)(`span`,{className:`quote-source`,children:[`↪ `,r(`quoteText`),` · `,r(o)]}),(0,$.jsx)(`span`,{className:`quote-preview`,children:e.text.replace(/\s+/g,` `).slice(0,80)})]}),(0,$.jsx)(`pre`,{className:`quote-content`,children:e.text})]}),t&&(0,$.jsx)(`button`,{type:`button`,className:`quote-remove`,"aria-label":r(`removeQuote`),title:r(`removeQuote`),onClick:t,children:`×`})]})}var Os=function(){let e=this.data();(e.micromarkExtensions??=[]).push({flow:{92:ks(!0)},text:{92:ks(!1)}});let t={enter:{backslashMathInline:As,backslashMathDisplay:As,backslashMathBlock:As},exit:{backslashMathInline:js,backslashMathDisplay:js,backslashMathBlock:js}};(e.fromMarkdownExtensions??=[]).push(t)};function ks(e){return{tokenize:function(t,n,r){let i=this,a=93,o=e?`backslashMathBlock`:`backslashMathDisplay`,s;return c;function c(e){return e===92?(s=t.enter(o),t.consume(e),l):r(e)}function l(n){return n!==91&&(e||n!==40)?r(n):(a=n===91?93:41,!e&&n===40&&(s.type=o=`backslashMathInline`),t.consume(n),u)}function u(n){return n===null||e&&i.parser.lazy[i.now().line]?r(n):n===-5||n===-4||n===-3?(t.enter(`lineEnding`),t.consume(n),t.exit(`lineEnding`),u):(f(n),n===92?d:u)}function d(i){return i===a?(f(i),t.exit(o),e?p:n):i===null?r(i):i===-5||i===-4||i===-3?u(i):(f(i),u)}function f(e){t.enter(`backslashMathData`),t.consume(e),t.exit(`backslashMathData`)}function p(e){return e===null||e===-5||e===-4||e===-3?n(e):e===32||e===-2||e===-1?(t.enter(`whitespace`),t.consume(e),t.exit(`whitespace`),p):r(e)}},concrete:e,name:e?`backslashMathBlock`:`backslashMathText`}}var As=function(e){let t=e.type===`backslashMathBlock`,n=e.type!==`backslashMathInline`,r=this.sliceSerialize(e).slice(2,-2).trim(),i={type:`element`,tagName:`code`,properties:{className:[`language-math`,n?`math-display`:`math-inline`]},children:[{type:`text`,value:r}]},a=t?{type:`math`,meta:null,value:r,data:{hName:`pre`,hChildren:[i]}}:{type:`inlineMath`,value:r,data:{hName:`code`,hProperties:i.properties,hChildren:i.children}};this.enter(a,e)},js=function(e){this.exit(e)},Ms=`modulepreload`,Ns=function(e,t){return new URL(e,t).href},Ps={},Fs={},Is=function(e){return e.pathname.endsWith(`.css`)},Ls=function(e,t,n){if(t in e)return e[t];let r=n();if(!r){e[t]=void 0;return}let i=r.then(()=>{e[t]=void 0},n=>{throw delete e[t],n});return e[t]=i,i},Rs=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e,i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?new URL(import.meta.resolve(e)):new URL(e,import.meta.url)}r=o(t.map(t=>{t=Ns(t,n);let r=s(t),i=Is(r);return Ls(Ps,r.href,()=>{if(e===void 0){e={all:new Set,styles:new Set};let t=document.getElementsByTagName(`link`);for(let n=t.length-1;n>=0;n--){let r=t[n];e.all.add(r.href),r.rel===`stylesheet`&&e.styles.add(r.href)}}let t=i?e.styles:e.all,n=i?Fs[r.href]:void 0;if(!n&&t.has(r.href))return;let o=document.createElement(`link`);if(o.rel=i?`stylesheet`:Ms,i||(o.as=`script`),o.crossOrigin=``,o.href=r.href,a&&o.setAttribute(`nonce`,a),n&&delete Fs[r.href],n?.isConnected?n.replaceWith(o):document.head.appendChild(o),i)return new Promise((e,t)=>{let n=i=>{o.removeEventListener(`load`,n),o.removeEventListener(`error`,n),i.type===`error`?(Fs[r.href]=o,t(Error(`Unable to preload CSS for ${r}`))):e(i)};o.addEventListener(`load`,n),o.addEventListener(`error`,n)})})}).filter(e=>e!==void 0))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},zs,Bs,Vs=new Set,Hs={load:()=>Rs(()=>import(`./math-DKgf_YcR.js`),__vite__mapDeps([0,1,2,3,4,5]),import.meta.url)};function Us(){return zs}function Ws(e){return Vs.add(e),()=>{Vs.delete(e)}}function Gs(){return zs?Promise.resolve():(Bs||=Hs.load().then(e=>{zs=e.default,Bs=void 0;for(let e of Vs)e()},()=>{Bs=void 0}),Bs)}var Ks=[`ariaDescribedBy`,`ariaLabel`,`ariaLabelledBy`],qs={ancestors:{tbody:[`table`],td:[`table`],th:[`table`],thead:[`table`],tfoot:[`table`],tr:[`table`]},attributes:{a:[...Ks,`dataFootnoteBackref`,`dataFootnoteRef`,[`className`,`data-footnote-backref`],`href`],blockquote:[`cite`],code:[[`className`,/^language-./]],del:[`cite`],div:[`itemScope`,`itemType`],dl:[...Ks],h2:[[`className`,`sr-only`]],img:[...Ks,`longDesc`,`src`],input:[[`disabled`,!0],[`type`,`checkbox`]],ins:[`cite`],li:[[`className`,`task-list-item`]],ol:[...Ks,[`className`,`contains-task-list`]],q:[`cite`],section:[`dataFootnotes`,[`className`,`footnotes`]],source:[`srcSet`],summary:[...Ks],table:[...Ks],ul:[...Ks,[`className`,`contains-task-list`]],"*":`abbr.accept.acceptCharset.accessKey.action.align.alt.axis.border.cellPadding.cellSpacing.char.charOff.charSet.checked.clear.colSpan.color.cols.compact.coords.dateTime.dir.encType.frame.hSpace.headers.height.hrefLang.htmlFor.id.isMap.itemProp.label.lang.maxLength.media.method.multiple.name.noHref.noShade.noWrap.open.prompt.readOnly.rev.rowSpan.rows.rules.scope.selected.shape.size.span.start.summary.tabIndex.title.useMap.vAlign.value.width`.split(`.`)},clobber:[`ariaDescribedBy`,`ariaLabelledBy`,`id`,`name`],clobberPrefix:`user-content-`,protocols:{cite:[`http`,`https`],href:[`http`,`https`,`irc`,`ircs`,`mailto`,`xmpp`],longDesc:[`http`,`https`],src:[`http`,`https`]},required:{input:{disabled:!0,type:`checkbox`}},strip:[`script`],tagNames:`a.b.blockquote.br.code.dd.del.details.div.dl.dt.em.h1.h2.h3.h4.h5.h6.hr.i.img.input.ins.kbd.li.ol.p.picture.pre.q.rp.rt.ruby.s.samp.section.source.span.strike.strong.sub.summary.sup.table.tbody.td.tfoot.th.thead.tr.tt.ul.var`.split(`.`)},Js={}.hasOwnProperty;function Ys(e,t){let n={type:`root`,children:[]},r=Xs({schema:t?{...qs,...t}:qs,stack:[]},e);return r&&(Array.isArray(r)?r.length===1?n=r[0]:n.children=r:n=r),n}function Xs(e,t){if(t&&typeof t==`object`){let n=t;switch(typeof n.type==`string`?n.type:``){case`comment`:return Zs(e,n);case`doctype`:return Qs(e,n);case`element`:return $s(e,n);case`root`:return ec(e,n);case`text`:return tc(e,n)}}}function Zs(e,t){if(e.schema.allowComments){let e=typeof t.value==`string`?t.value:``,n=e.indexOf(`-->`),r={type:`comment`,value:n<0?e:e.slice(0,n)};return cc(r,t),r}}function Qs(e,t){if(e.schema.allowDoctypes){let e={type:`doctype`};return cc(e,t),e}}function $s(e,t){let n=typeof t.tagName==`string`?t.tagName:``;e.stack.push(n);let r=nc(e,t.children),i=rc(e,t.properties);e.stack.pop();let a=!1;if(n&&n!==`*`&&(!e.schema.tagNames||e.schema.tagNames.includes(n))&&(a=!0,e.schema.ancestors&&Js.call(e.schema.ancestors,n))){let t=e.schema.ancestors[n],r=-1;for(a=!1;++r<t.length;)e.stack.includes(t[r])&&(a=!0)}if(!a)return e.schema.strip&&!e.schema.strip.includes(n)?r:void 0;let o={type:`element`,tagName:n,properties:i,children:r};return cc(o,t),o}function ec(e,t){let n={type:`root`,children:nc(e,t.children)};return cc(n,t),n}function tc(e,t){let n={type:`text`,value:typeof t.value==`string`?t.value:``};return cc(n,t),n}function nc(e,t){let n=[];if(Array.isArray(t)){let r=t,i=-1;for(;++i<r.length;){let t=Xs(e,r[i]);t&&(Array.isArray(t)?n.push(...t):n.push(t))}}return n}function rc(e,t){let n=e.stack[e.stack.length-1],r=e.schema.attributes,i=e.schema.required,a=r&&Js.call(r,n)?r[n]:void 0,o=r&&Js.call(r,`*`)?r[`*`]:void 0,s=t&&typeof t==`object`?t:{},c={},l;for(l in s)if(Js.call(s,l)){let t=s[l],n=ic(e,lc(a,l),l,t);n??=ic(e,lc(o,l),l,t),n!=null&&(c[l]=n)}if(i&&Js.call(i,n)){let e=i[n];for(l in e)Js.call(e,l)&&!Js.call(c,l)&&(c[l]=e[l])}return c}function ic(e,t,n,r){return t?Array.isArray(r)?ac(e,t,n,r):oc(e,t,n,r):void 0}function ac(e,t,n,r){let i=-1,a=[];for(;++i<r.length;){let o=oc(e,t,n,r[i]);(typeof o==`number`||typeof o==`string`)&&a.push(o)}return a}function oc(e,t,n,r){if((typeof r==`boolean`||typeof r==`number`||typeof r==`string`)&&sc(e,n,r)){if(typeof t==`object`&&t.length>1){let e=!1,n=0;for(;++n<t.length;){let i=t[n];if(i&&typeof i==`object`&&`flags`in i){if(i.test(String(r))){e=!0;break}}else if(i===r){e=!0;break}}if(!e)return}return e.schema.clobber&&e.schema.clobberPrefix&&e.schema.clobber.includes(n)?e.schema.clobberPrefix+r:r}}function sc(e,t,n){let r=e.schema.protocols&&Js.call(e.schema.protocols,t)?e.schema.protocols[t]:void 0;if(!r||r.length===0)return!0;let i=String(n),a=i.indexOf(`:`),o=i.indexOf(`?`),s=i.indexOf(`#`),c=i.indexOf(`/`);if(a<0||c>-1&&a>c||o>-1&&a>o||s>-1&&a>s)return!0;let l=-1;for(;++l<r.length;){let e=r[l];if(a===e.length&&i.slice(0,e.length)===e)return!0}return!1}function cc(e,t){let n=ur(t);t.data&&(e.data=fr(t.data)),n&&(e.position=n)}function lc(e,t){let n,r=-1;if(e)for(;++r<e.length;){let i=e[r],a=typeof i==`string`?i:i[0];if(a===t)return i;a===`data*`&&(n=i)}if(t.length>4&&t.slice(0,4).toLowerCase()===`data`)return n}function uc(e){return function(t){return Ys(t,e)}}var dc=(0,Q.memo)(function({text:e}){let t=X(),{copied:n,copy:r}=Gn({duration:1200});return e?(0,$.jsx)(`button`,{type:`button`,className:`copy-btn`,title:t(`copy`),onClick:()=>void r(e),children:n?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}):null});function fc(e){let t=e.trim();return t?t.split(/\r?\n/).map(e=>e.replace(/^\s*[$%>]\s+/,``)).join(`
|
|
7
|
-
`).trim():``}function pc(e){let t=e.split(/\r?\n/).map(e=>e.trim()).filter(e=>e.length>0);if(t.length===0)return``;let n=t.find(e=>!e.startsWith(`#`)&&!e.startsWith(`//`))??t[0];return n.length>28?n.slice(0,25).trimEnd()+`…`:n}function mc(e,t){if(typeof window>`u`)return!1;let n=fc(e);if(!n)return!1;let r=t||pc(n);return window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:r,command:n}})),!0}var hc=(0,Q.memo)(function({code:e,title:t}){let n=X(),[r,i]=(0,Q.useState)(!1),a=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{a.current&&clearTimeout(a.current)},[]);let o=(0,Q.useCallback)(()=>{mc(e,t)&&(i(!0),a.current&&clearTimeout(a.current),a.current=setTimeout(()=>{i(!1),a.current=null},1200))},[e,t]);return!e||!e.trim()?null:(0,$.jsx)(`button`,{type:`button`,className:`term-run-btn`,title:n(r?`executedInTerminal`:`runInTerminal`),"aria-label":n(`runInTerminal`),onClick:o,children:r?(0,$.jsx)(z,{}):(0,$.jsx)(Xe,{})})});function gc(e){let t=e=>{if(typeof e==`string`||typeof e==`number`){let t=String(e);return t===``?[[]]:t.split(`
|
|
8
|
-
`).map(e=>e===``?[]:[e])}if(Array.isArray(e)){let n=[];for(let r of e){let e=t(r);if(n.length===0)n=e;else{let t=e[0]??[];n[n.length-1].push(...t),n.push(...e.slice(1))}}return n}if(e&&typeof e==`object`&&`props`in e){let n=e,r=n.props?.children,i={...n.props,children:void 0},a=r==null?[]:t(r);return a.length===0?[[(0,Q.createElement)(n.type,i)]]:a.map(e=>[(0,Q.createElement)(n.type,i,...e)])}return[[e]]},n=t(e);return n.length>1&&n[n.length-1].length===0&&n.pop(),n}function _c(e){return typeof e==`string`?e:Array.isArray(e)?e.map(_c).join(``):e&&typeof e==`object`&&`props`in e?_c(e.props?.children):``}function vc(e){let t=Array.isArray(e)?e[0]:e;return!t||typeof t!=`object`||!(`props`in t)?null:t}function yc(e){let t=vc(e)?.props?.className;if(typeof t!=`string`)return null;let n=t.match(/(?:^|\s)language-([A-Za-z0-9_+-]+)(?:\s|$)/);return n?n[1]:null}var bc=`pi-web-ui:plugin-data`,xc=new Map,Sc=new Map,Cc=new Set,wc=-1,Tc=0,Ec=new Set;function Dc(){Tc++;for(let e of Ec)e()}function Oc(e){return Ec.add(e),()=>{Ec.delete(e)}}function kc(){return Tc}var Ac=null;function jc(e){Ac=e}function Mc(e,t){J()&&(e=[]),t!==wc&&(wc=t,Sc.clear(),Cc.clear());let n=new Map;for(let t of e)if(!t.error&&t.renderers)for(let e of t.renderers)n.has(e)||n.set(e,t.id);let r=n.size!==xc.size;if(!r){for(let[e,t]of n)if(xc.get(e)!==t){r=!0;break}}if(r){for(let e of Sc.keys())n.has(e)||Sc.delete(e);for(let e of Cc)n.has(e)||Cc.delete(e);xc=n,Dc()}}async function Nc(e,t){if(J())return null;let n=xc.get(e);if(!n)return null;let r=Sc.get(e);if(!r&&!Cc.has(e))try{let t=(await import(j(`/plugins/${encodeURIComponent(n)}/client/entry.mjs?e=${wc}`))).default?.renderers?.[e];typeof t==`function`?(r={pluginId:n,renderer:t},Sc.set(e,r)):(Cc.add(e),console.error(`[plugin:${n}] entry.mjs 未提供 renderers["${e}"]`))}catch(t){Cc.add(e),console.error(`[plugin:${n}] renderer 加载失败(${e}):`,t)}if(!r)return null;let i={pluginId:r.pluginId,send:e=>{Ac?.({type:`plugin_message`,pluginId:r.pluginId,payload:e})},onData:e=>{let t=t=>{let n=t.detail;n.pluginId===r.pluginId&&e(n.payload)};return window.addEventListener(bc,t),()=>window.removeEventListener(bc,t)}};try{let e=await r.renderer(t,i);return e instanceof HTMLElement?e:null}catch(t){return console.error(`[plugin:${r.pluginId}] renderer("${e}") 执行失败:`,t),null}}function Pc(e){return xc.has(e)}var Fc=new Map,Ic=new Map,Lc=new Set,Rc=-1;function zc(e,t){J()&&(e=[]),t!==Rc&&(Rc=t,Ic.clear(),Lc.clear());let n=new Map;for(let t of e){if(t.error)continue;let e=t.messageWidgets;if(Array.isArray(e))for(let r of e)typeof r==`string`&&r&&(n.has(r)||n.set(r,t.id))}for(let e of Array.from(Fc.keys()))n.has(e)||Fc.delete(e);for(let[e,t]of n)Fc.set(e,t);for(let e of Ic.keys())n.has(e)||Ic.delete(e);for(let e of Lc)n.has(e)||Lc.delete(e)}function Bc(e){return Fc.has(e)}async function Vc(e){if(J())return null;let t=Fc.get(e);if(!t)return null;let n=Ic.get(e);if(!n&&!Lc.has(e))try{let r=(await import(j(`/plugins/${encodeURIComponent(t)}/client/entry.mjs?e=${Rc}`))).default?.messageWidgets?.[e];typeof r==`function`?(n={pluginId:t,renderer:r},Ic.set(e,n)):(Lc.add(e),console.error(`[plugin:${t}] entry.mjs 未提供 messageWidgets["${e}"]`))}catch(n){Lc.add(e),console.error(`[plugin:${t}] messageWidget 加载失败(${e}):`,n)}return n?.renderer??null}function Hc({lang:e,code:t}){let n=(0,Q.useRef)(null),r=(0,Q.useRef)(null),i=(0,Q.useRef)(0),a=(0,Q.useRef)(new WeakMap),[o,s]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let e=()=>{let e=++i.current,t=r.current;t&&(t.dispatchEvent(new CustomEvent(yr)),a.current.set(t,e))};return window.addEventListener(yr,e),()=>window.removeEventListener(yr,e)},[]),(0,Q.useEffect)(()=>{let n=!1,r=i.current;return s(null),Nc(e,t).then(e=>{n||(e&&a.current.set(e,r),s(e))}),()=>{n=!0}},[e,t]),(0,Q.useEffect)(()=>{r.current=o;let e=n.current;return e&&(e.replaceChildren(),o&&(e.appendChild(o),(a.current.get(o)??i.current)<i.current&&(o.dispatchEvent(new CustomEvent(yr)),a.current.set(o,i.current)))),()=>{r.current===o&&(r.current=null)}},[o]),o?(0,$.jsx)(`div`,{className:`plugin-fence`,ref:n}):(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsxs)(`div`,{className:`codeblock-actions`,children:[(0,$.jsx)(hc,{code:t}),(0,$.jsx)(dc,{text:t})]}),(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:t})})]})}function Uc(e=typeof window<`u`?window.location.hostname:``){if(!e)return!1;let t=e.toLowerCase().trim();return!!(t===`localhost`||t.endsWith(`.localhost`)||t===`::1`||t===`[::1]`||t.startsWith(`127.`))}function Wc(e){if(!e)return!0;let t=e.trim();return!t||t.startsWith(`#`)||t.startsWith(`?`)||t.startsWith(`//`)||t.startsWith(`pi-file://`)?!0:/^[a-z]:[\\/]/i.test(t)||/^file:\/\//i.test(t)?!1:/^[a-z][a-z\d+.-]*:/i.test(t)}function Gc(e,t){return(t===`href`||t===`src`)&&/^(?:[a-z]:[\\/]|file:\/\/|pi-file:\/\/)/i.test(e)?e:lr(e)}function Kc(e,t){let n=e.trim();n=n.replace(/^file:\/\/(?:localhost(?=\/))?/i,``);try{n=decodeURIComponent(n)}catch{}if(n=n.replace(/\\/g,`/`).replace(/^\/([a-z]:\/)/i,`$1`),n=n.replace(/:\d+(?::\d+)?$/,``),t){let e=t.replace(/\\/g,`/`).replace(/\/+$/,``),r=/^[a-z]:\//i.test(e);(r?n.toLowerCase():n).startsWith((r?e.toLowerCase():e)+`/`)&&(n=n.slice(e.length+1))}return n}function qc(e){let t=e.split(`?`)[0]?.split(`#`)[0]?.toLowerCase()??``;return t.endsWith(`.html`)||t.endsWith(`.htm`)||t.endsWith(`.xhtml`)}function Jc(e,t){let n=Kc(e,t),r=Po();if(qc(n)){let e=/^[A-Za-z]:\//.test(n)||n.startsWith(`/`),t=n.split(`/`).map(e=>encodeURIComponent(e)).join(`/`),i=e?`/api/preview/__abs__/${t}`:`/api/preview/${t}`;return W(j(`${i}?clientId=${encodeURIComponent(r)}&allowJs=1`))}let i=new URLSearchParams({clientId:r,path:n});return W(j(`/api/file?${i}`))}var Yc=[dr,pr,Os],Xc=[dr],Zc=[dr,cr,pr,Os],Qc=[dr,cr],$c=[[sr,{detect:!1,ignoreMissing:!0}]];function el(e){if(!e||!e.includes(`@`))return e;let t=e.split(RegExp("(```[\\s\\S]*?```|`[^`\\r\\n]+`)",`g`)),n=/(^|[\s((“"'[])@((?:[\w.-]+\/)*[\w.-]+\.(?:[a-zA-Z0-9]{1,10}))(?=[)\s\],.;:!?,。!?’”"']|$)/g;for(let e=0;e<t.length;e+=2)t[e]&&(t[e]=t[e].replace(n,(e,t,n)=>t+`[@`+n+`](pi-file://`+encodeURIComponent(n)+`)`));return t.join(``)}function tl({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){let i=(0,Q.useSyncExternalStore)(Ws,Us,Us),a=!r&&(t||/[$\\\\]|math/i.test(e));(0,Q.useEffect)(()=>{a&&!i&&Gs()},[a,i]);let o=!r&&i?[[i,{strict:!1,throwOnError:!1}],...$c]:$c,s=t?[mr,uc,...o]:o,c=(0,Q.useMemo)(()=>el(e),[e]);return(0,$.jsx)(hr,{remarkPlugins:r?n?Qc:Xc:n?Zc:Yc,rehypePlugins:s,urlTransform:Gc,components:{pre:al,a:rl,img:il},children:c})}var nl=(0,Q.memo)(function({text:e,rawHtml:t=!1,hardBreaks:n=!1,disableMath:r=!1}){return(0,$.jsx)(`div`,{className:`md`,children:(0,$.jsx)(tl,{text:e,rawHtml:t,hardBreaks:n,disableMath:r})})});function rl({node:e,href:t,children:n,...r}){let i=String(t??``),a=X(),o=mn(`cwd`);if(i.startsWith(`pi-file://`)){let e=i.slice(10),t=e;try{t=decodeURIComponent(e)}catch{t=e}let r=typeof n==`string`&&n.trim()?n.trim():t.split(`/`).pop()??t;return(0,$.jsxs)(`button`,{type:`button`,className:`file-pill`,title:a(`markdownPreviewFileTip`,{path:t}),onClick:e=>{e.preventDefault(),e.stopPropagation(),Jt({path:t,name:r.replace(/^@/,``)})},children:[(0,$.jsx)(`span`,{className:`file-pill-icon`,"aria-hidden":`true`,children:`📄`}),(0,$.jsx)(`span`,{className:`file-pill-name`,children:r})]})}if(!Wc(i)){let e=Kc(i,o),t=e.split(`/`).pop()||e,s=Jc(i,o);return(0,$.jsx)(`a`,{...r,href:s,onClick:n=>{n.button!==0||n.ctrlKey||n.metaKey||n.shiftKey||n.altKey||!Jt({path:e,name:t})||(n.preventDefault(),n.stopPropagation())},target:`_blank`,rel:`noreferrer noopener`,title:a(`markdownPreviewTip`,{path:e}),children:n})}return/^(https?:|mailto:|tel:)/i.test(i)?(0,$.jsx)(`a`,{...r,href:t,target:`_blank`,rel:`noreferrer noopener`,children:n}):(0,$.jsx)(`a`,{href:t,...r,children:n})}function il({node:e,src:t,alt:n,...r}){let a=String(t??``),o=mn(`cwd`),s=a;return J()&&a.startsWith(`/api/`)?s=He(a):a&&!Wc(a)&&!a.startsWith(`data:`)&&!a.startsWith(`blob:`)&&(s=Jc(a,o)),i(s)&&(s=He(s)),(0,$.jsx)(`button`,{type:`button`,className:`image-preview-trigger`,"aria-label":n||`Image preview`,onClick:e=>{e.preventDefault(),e.stopPropagation(),Tn({src:s,alt:n})},children:(0,$.jsx)(`img`,{...r,crossOrigin:i(s)??r.crossOrigin,src:s,alt:n,loading:`lazy`})})}function al({children:e,...t}){(0,Q.useSyncExternalStore)(Oc,kc,kc);let n=yc(e);return n&&Pc(n)?(0,$.jsx)(Hc,{lang:n,code:_c(e)}):(0,$.jsx)(sl,{children:e,...t})}var ol=200,sl=(0,Q.memo)(function({children:e,...t}){let n=e&&typeof e==`object`&&`props`in e?e.props?.children:e,r=cl(e);if((r?r.split(`
|
|
9
|
-
`).length:1)>ol)return(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsxs)(`div`,{className:`codeblock-actions`,children:[(0,$.jsx)(hc,{code:r}),(0,$.jsx)(dc,{text:r})]}),(0,$.jsx)(`pre`,{...t,children:(0,$.jsx)(`code`,{className:`code-line-body code-block-raw`,children:n})})]});let i=gc(n),a=i.length>1,o=a?`${String(i.length).length+1}ch`:void 0;return(0,$.jsxs)(`div`,{className:`codeblock`,children:[(0,$.jsxs)(`div`,{className:`codeblock-actions`,children:[(0,$.jsx)(hc,{code:r}),(0,$.jsx)(dc,{text:r})]}),(0,$.jsx)(`pre`,{...t,children:i.map((e,t)=>(0,$.jsxs)(`div`,{className:`code-line`,children:[a&&(0,$.jsx)(`span`,{className:`code-num`,style:o?{width:o}:void 0,children:t+1}),(0,$.jsx)(`code`,{className:`code-line-body`,children:e})]},t))})]})});function cl(e){return typeof e==`string`?e:Array.isArray(e)?e.map(cl).join(``):e&&typeof e==`object`&&`props`in e?cl(e.props?.children):``}function ll({type:e,code:t,children:n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{let n=!1;if(a(null),Bc(e))return Vc(e).then(async r=>{if(!n&&r)try{let i=await r(t,{pluginId:Fc.get(e)??e,send:()=>void 0,onData:()=>()=>void 0});!n&&i instanceof HTMLElement&&a(i)}catch(t){console.error(`[plugin-widget:${e}] 渲染失败:`,t)}}),()=>{n=!0}},[e,t]),(0,Q.useEffect)(()=>{let e=r.current;e&&(e.replaceChildren(),i&&e.appendChild(i))},[i]),i?(0,$.jsx)(`div`,{className:`plugin-widget`,ref:r}):(0,$.jsx)($.Fragment,{children:n})}function ul({task:e}){let t=X(),[n,r]=(0,Q.useState)(!1),{copied:i,copy:a}=Gn({duration:1200}),o=t(Wt(e.status)),s=[];return e.summary&&s.push({label:t(`bgTaskSummary`),value:e.summary}),e.guidance&&s.push({label:t(`bgTaskGuidance`),value:e.guidance}),(0,$.jsxs)(`div`,{className:`bgn bgn-${e.status}`,"data-bg-task-id":e.id,children:[(0,$.jsxs)(`div`,{className:`bgn-head`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`bgn-toggle`,"aria-expanded":n,disabled:s.length===0,title:s.length===0?o:t(n?`collapseMsg`:`expandMsg`),onClick:()=>r(e=>!e),children:[s.length>0?(0,$.jsx)(`span`,{className:`bgn-caret`,"aria-hidden":!0,children:n?(0,$.jsx)(D,{}):(0,$.jsx)(At,{})}):(0,$.jsx)(`span`,{className:`bgn-caret`,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:qt(e.status),"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`bgn-name`,title:e.name,children:e.name}),(0,$.jsx)(`span`,{className:`bgn-id`,children:e.id}),(0,$.jsx)(`span`,{className:`bgn-status ${e.status}`,children:o}),e.exitCode!==void 0&&e.status!==`completed`&&(0,$.jsx)(`span`,{className:`bgn-exit`,children:t(`exitCode`,{code:e.exitCode})})]}),e.outputPath&&(0,$.jsx)(`button`,{type:`button`,className:`bgn-copy`,title:t(i?`copied`:`bgTaskCopyPath`),"aria-label":t(i?`copied`:`bgTaskCopyPath`),onClick:()=>{a(e.outputPath)},children:i?(0,$.jsx)(h,{}):(0,$.jsx)(st,{})})]}),e.command&&(0,$.jsxs)(`div`,{className:`bgn-command`,title:e.command,children:[(0,$.jsx)(`span`,{className:`bgn-prompt`,"aria-hidden":!0,children:`$`}),(0,$.jsx)(`code`,{children:e.command})]}),e.outputPath&&(0,$.jsx)(`div`,{className:`bgn-output`,children:(0,$.jsx)(`button`,{type:`button`,className:`bgn-path`,title:`${t(`bgTaskOpenOutput`)}\n${e.outputPath}`,onClick:()=>Jt({path:e.outputPath,name:e.outputPath.split(/[\\/]/).pop()||e.name}),children:e.outputPath})}),e.error&&(0,$.jsx)(`pre`,{className:`bgn-error`,children:e.error}),n&&s.length>0&&(0,$.jsx)(`div`,{className:`bgn-detail`,children:s.map(e=>(0,$.jsxs)(`div`,{className:`bgn-detail-row`,children:[(0,$.jsx)(`span`,{className:`bgn-detail-label`,children:e.label}),(0,$.jsx)(`span`,{className:`bgn-detail-value`,children:e.value})]},e.label))})]})}var dl=/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/;function fl(e){let t=e.match(dl);return t?{name:t[1],location:t[2],content:t[3],userMessage:t[4]?.trim()||void 0}:null}function pl(e){let t=[];for(let n of e)n?.type===`text`&&typeof n.text==`string`&&n.text.length>0&&t.push(n.text);return t}function ml(e){return pl(e).join(`
|
|
10
|
-
|
|
11
|
-
`)}function hl(e){return gl(ml(e))}function gl(e){let t=e.split(`
|
|
12
|
-
`),n=[],r=!1;for(let e of t)/^\s*```/.test(e)?r=!r:r?n.push(e):(e=e.replace(/^\s{0,3}#{1,6}\s+/,``).replace(/^\s*(>\s*)+/,``).replace(/^\s*(?:[-*+]\s+|\d{1,9}[.)]\s+)/,``).replace(/^\s*\[[ xX]\]\s+/,``),/^\s*\|?\s*[:-]+\s*(\|\s*[:-]+\s*)*\|?\s*$/.test(e)&&/[-:]/.test(e)||n.push(e));return n.join(`
|
|
13
|
-
`).replace(/!\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/`([^`]*)`/g,`$1`).replace(/(\*\*|__)(.+?)\1/g,`$2`).replace(/(^|\W)\*([^*\n]+)\*(?=\W|$)/g,`$1$2`).replace(/(^|\W)_([^_\n]+)_(?=\W|$)/g,`$1$2`).replace(/~~(.+?)~~/g,`$1`).replace(/^\s*\|/gm,``).replace(/\|\s*$/gm,``).replace(/\|/g,` `).replace(/<[^>]+>/g,``).replace(/\s+#+\s*$/gm,``).split(`
|
|
14
|
-
`).map(e=>e.replace(/[ \t]+/g,` `).replace(/^\s+|\s+$/g,``)).join(`
|
|
15
|
-
`).replace(/\n{3,}/g,`
|
|
16
|
-
|
|
17
|
-
`).trim()}var _l={open:!1,triggerId:``,selectedIds:[],includeTools:!1,includeThinking:!1},vl=_l,yl=[],bl=new Set;function xl(){for(let e of bl)e()}function Sl(e){return(e.role===`user`||e.role===`assistant`)&&ml(e.content).length>0}function Cl(e,t=yl){let n=new Map(t.map((e,t)=>[e.id,t]));return[...new Set(e)].filter(e=>n.has(e)).sort((e,t)=>(n.get(e)??0)-(n.get(t)??0))}function wl(e){if(yl=e,vl.open){let e=Cl(vl.selectedIds,yl);e.join(`\0`)!==vl.selectedIds.join(`\0`)&&(vl={...vl,selectedIds:e},xl())}}function Tl(){return vl}function El(e){return bl.add(e),()=>{bl.delete(e)}}function Dl(){return(0,Q.useSyncExternalStore)(El,Tl,Tl)}function Ol(){vl.open&&(vl=_l,xl())}function kl(e){let t=yl.find(t=>t.id===e);t&&Sl(t)&&(vl.open?(vl={...vl,selectedIds:Cl([...vl.selectedIds,e])},xl()):(vl={open:!0,triggerId:e,selectedIds:[e],includeTools:!1,includeThinking:!1},xl()))}function Al(e){vl.open&&(vl={...vl,includeTools:e.includeTools??vl.includeTools,includeThinking:e.includeThinking??vl.includeThinking},xl())}function jl(e){if(!vl.open||!yl.filter(Sl).map(e=>e.id).includes(e))return;let t=vl.selectedIds.includes(e)?vl.selectedIds.filter(t=>t!==e):Cl([...vl.selectedIds,e]);vl={...vl,selectedIds:t},xl()}var Ml=/^(This operation was aborted|Request aborted)$/;function Nl(e){return e.stopReason===`aborted`||e.stopReason===`error`&&Ml.test((e.errorMessage??``).trim())}function Pl({open:e,onToggle:t,headClassName:n,titleText:r,icon:i,iconClassName:a,titleClassName:o,toggleClassName:s,toggle:c,onHeadContextMenu:l,children:u,after:d}){return(0,$.jsxs)(`div`,{className:`chead ${n}`,"data-disclosure":``,role:`button`,tabIndex:0,"aria-expanded":e,title:r,onClick:t,onContextMenu:l,onKeyDown:e=>{e.target===e.currentTarget&&(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),t())},children:[c===void 0?(0,$.jsx)(`button`,{type:`button`,className:s?`chead-toggle ${s}`:`chead-toggle`,title:r,"aria-label":r,"aria-expanded":e,onClick:e=>{e.stopPropagation(),t()},children:e?(0,$.jsx)(D,{}):(0,$.jsx)(At,{})}):c,(0,$.jsx)(`span`,{className:a?`chead-icon ${a}`:`chead-icon`,children:i}),(0,$.jsx)(`span`,{className:o?`chead-title ${o}`:`chead-title`,children:u}),d]})}function Fl(e){return e==null||!Number.isFinite(e)?``:e>=1048576?`${(e/1048576).toFixed(1)} MB`:e>=1024?`${Math.round(e/1024)} KB`:`${e} B`}var Il=/\[\[\s*([A-Za-z][A-Za-z0-9_-]*)\s*:\s*([A-Za-z][A-Za-z0-9_-]*)\s*:(.*?)\s*\]\]/g,Ll={gateway:`modelError.gateway`,auth:`modelError.auth`,quota:`modelError.quota`,model:`modelError.model`,unknown:`modelError.unknown`},Rl=new Set([`todo`,`notify`,`conv`,`rename`,`title`,`action`,`suggest`]),zl=new Set(Rl);function Bl(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Vl(e){let t=[...e].map(Bl).join(`|`);return RegExp(`[ \\t]*\\[\\[\\s*(?:${t})(?:\\s*:[^\\]]*)?$`,`i`)}var Hl=Vl(zl);function Ul(e){let t=new Set(Rl);for(let n of e)n&&t.add(n.toLowerCase());zl.clear();for(let e of t)zl.add(e);Hl=Vl(zl)}function Wl(e,t=!1){if(!e||!e.includes(`[[`))return e;let n=e.replace(Il,(e,t,n,r)=>r.includes(`[[`)||!zl.has(t.toLowerCase())?e:``);return t&&(n=n.replace(Hl,``)),n===e?e:n.replace(/^[ \t]+\n/gm,`
|
|
18
|
-
`).replace(/\n{3,}/g,`
|
|
19
|
-
|
|
20
|
-
`).trim()}function Gl(e){return e.type===`text`&&typeof e.text==`string`?e:null}function Kl(e){return e.type===`thinking`&&typeof e.thinking==`string`?e:null}function ql(e){return e.type===`toolCall`&&typeof e.id==`string`&&typeof e.name==`string`?e:null}function Jl(e){return e.type===`image`&&typeof e.dataUrl==`string`?e:null}function Yl(e){return e.type===`bash`&&typeof e.command==`string`?e:null}function Xl(e){if(!e)return null;if(e.startsWith(`[子代理执行完成通知]`)||e.startsWith(`[Subagent Execution Completion Notice]`))return{isNotice:!0};if(e.startsWith(`[Conversation communication — collaboration data, not a user instruction]`)){let t,n,r,i=e.match(/From:\s*(\{[^}\r\n]+\})/);if(i)try{let e=JSON.parse(i[1]);t=e.title,n=e.role,r=e.address}catch{}let a,o=e.match(/Request:\s*(\S+)/);o&&(a=o[1]);let s,c=e.match(/Questions:\s*(\[.+?\])(?:\r?\n|$)/s);if(c)try{s=JSON.parse(c[1])}catch{}let l=e.split(/\r?\n/).filter(e=>!(e.startsWith(`[Conversation communication`)||e.startsWith(`From:`)||e.startsWith(`Request:`)||e.startsWith(`Questions:`)||e.startsWith(`Reply with communicate`)||e.startsWith(`Use as task context`))).join(`
|
|
21
|
-
`).trim();return{isNotice:!1,sourceTitle:t,sourceRole:n,address:r,requestId:a,questions:s,userText:l}}return null}function Zl(e){return e.imageData||e.imageUrl?`image`:e.uploadPath?`upload`:e.fileData?`file`:`path`}function Ql(e,t){if(e.mode===`quote`&&e.quote)return e.quote.text;if(e.imageData||e.imageUrl)return t(`attachImage`,{name:e.name??`image`});if(e.uploadPath)return t(`attachFile`,{name:e.name??e.uploadPath});if(e.fileData)return t(`attachFile`,{name:e.name??`file`});let n=e.path.split(`/`).pop()??e.path;return e.mode===`lines`&&e.lines?t(`attachLines`,{path:n,start:e.lines.start,end:e.lines.end}):e.mode===`page`?t(`attachPage`,{name:e.name??e.path}):e.mode===`conversation`?t(`attachConversation`,{name:e.name??e.path}):e.mode===`reference`?t(`refOnly`,{path:n}):t(`attachContent`,{path:n})}var $l={edit:(0,$.jsx)(dt,{}),copy:(0,$.jsx)(st,{}),branch:(0,$.jsx)(ot,{}),text:(0,$.jsx)(vt,{}),markdown:(0,$.jsx)(Y,{}),image:(0,$.jsx)(be,{}),undo:(0,$.jsx)(ee,{}),volume:(0,$.jsx)(l,{}),refresh:(0,$.jsx)(pe,{}),x:(0,$.jsx)(Ct,{})};function eu(e){let t=(e??``).trim();return t?$l[t.toLowerCase()]||(!/[\p{L}\p{N}]/u.test(t)&&t.length<=4?(0,$.jsx)(`span`,{className:`msg-action-glyph`,children:t}):(0,$.jsx)(ne,{})):(0,$.jsx)(ne,{})}function tu(e,t){let n=e.replace(/\s+/g,` `).trim();return n.length>t?`${n.slice(0,t)}…`:n}function nu(e,t){switch(e){case`user`:return t(`role.user`);case`assistant`:return t(`role.assistant`);case`toolResult`:return t(`role.tool`);case`bashExecution`:return t(`role.bash`);case`branchSummary`:return t(`role.branch`);case`compactionSummary`:return t(`role.compaction`);default:return e}}function ru(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}function iu(e){let t=e.match(/^\s*<file path="[^"]*"(?:\s+lines="[^"]*")?>\s*```\s*\n?([\s\S]*?)\n?```\s*<\/file>\s*$/);if(t)return t[1].trim();let n=e.match(/^\s*<vision-bridge>\s*([\s\S]*?)\s*<\/vision-bridge>\s*$/);return n?n[1].trim():e.trim()}function au({message:e,forceOpen:t=!1}){let n=X(),[r,a]=(0,Q.useState)(!1),{copied:o,copy:s}=Gn({duration:1200}),c=r||t,l=e.details??{},u=l.name??l.path??n(`attachment`),d=l.type===`folder`,f=l.mode===`canvas`,p=l.mode===`terminal`,m=l.mode===`reference`||f||p,g=l.mode===`bridged`,_=l.mode===`page`,v=l.mode===`conversation`,y=l.path&&/^https?:\/\//i.test(l.path.trim())?l.path.trim():null,b=iu(e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
22
|
-
`)),x=e.content.find(e=>e.type===`image`),S=b.split(`
|
|
23
|
-
`).length,C=!m&&!_&&!v&&b.length>0;return(0,$.jsxs)(`div`,{className:`attachcard ${m?`reference`:``}${_?` page`:``}${v?` conversation`:``}`,children:[(0,$.jsx)(Pl,{open:c,headClassName:`attachcard-head`,titleText:n(c?`collapseMsg`:`expandMsg`),onToggle:()=>a(e=>t?!0:!e),toggle:!m&&!_&&!v?(0,$.jsx)(`span`,{className:`chead-toggle`,children:c?(0,$.jsx)(D,{}):(0,$.jsx)(At,{})}):null,icon:f?`◈`:p?`🖥`:d?`📁`:_?`🌐`:v?`💬`:`📎`,iconClassName:`attachcard-icon`,titleClassName:`attachcard-name`,after:(0,$.jsxs)($.Fragment,{children:[l.path&&(_&&y?(0,$.jsx)(`a`,{className:`attachcard-path attachcard-link`,href:y,target:`_blank`,rel:`noreferrer`,children:l.path}):!_&&!v&&!d?(0,$.jsx)(`span`,{className:`attachcard-path attachcard-path-clickable`,title:n(`fileOpenPreview`),onClick:e=>{e.stopPropagation(),Jt({path:l.path,name:u})},children:l.path}):(0,$.jsx)(`span`,{className:`attachcard-path`,children:l.path})),(0,$.jsx)(`span`,{className:`attachcard-mode ${l.mode===`lines`?`lines`:m?`ref`:_?`page`:v?`conversation`:g?`bridged`:`inline`}`,children:f?n(`canvasTab`):_?n(`attachPageShort`):v?n(`attachConversationShort`):m?d?n(`folderRefShort`):`${n(`refOnlyShort`)} · ${Fl(l.size)}`:g?n(`bridgedVision`):x?n(`image`):l.mode===`lines`?n(`inlineLinesRange`,{start:l.startLine??1,end:l.endLine??l.lines??1}):n(`inlineLines`,{n:l.lines??S})}),C&&(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:n(o?`copied`:`copyMessage`),"aria-label":n(`copyMessage`),onClick:e=>{e.stopPropagation(),s(b)},children:o?(0,$.jsx)(h,{}):(0,$.jsx)(st,{})})]}),children:u}),!m&&c&&(()=>{let e=x?.dataUrl?x.dataUrl.startsWith(`/`)?He(x.dataUrl):x.dataUrl:void 0;return g?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`attachcard-bridgenote`,children:n(`bridgedVisionDetail`)}),e&&(0,$.jsx)(`div`,{className:`attachcard-image`,children:(0,$.jsx)(`img`,{crossOrigin:i(e),src:e,loading:`lazy`,decoding:`async`,alt:u,className:`attachcard-image-clickable`,title:n(`toolImageZoom`),onClick:()=>Tn({src:e,alt:u})})}),b&&(0,$.jsx)(`pre`,{className:`attachcard-content`,children:b})]}):e?(0,$.jsx)(`div`,{className:`attachcard-image`,children:(0,$.jsx)(`img`,{crossOrigin:i(e),src:e,loading:`lazy`,decoding:`async`,alt:u,className:`attachcard-image-clickable`,title:n(`toolImageZoom`),onClick:()=>Tn({src:e,alt:u})})}):(0,$.jsx)(`pre`,{className:`attachcard-content`,children:b})})(),m&&(0,$.jsxs)(`div`,{className:`attachcard-refnote`,children:[(0,$.jsx)(`span`,{children:d?n(`folderNotExpanded`):n(`fileNotExpanded`,{size:Fl(l.size)})}),!d&&l.path&&(0,$.jsxs)(`button`,{type:`button`,className:`attachcard-ref-open`,onClick:()=>Jt({path:l.path,name:u}),children:[(0,$.jsx)(ve,{}),` `,n(`fileOpenPreview`)]})]})]})}function ou({messages:e,renderMessage:t}){let n=X(),r=(0,Q.useMemo)(()=>{let t=new Map;for(let n of e)n.role===`toolResult`&&n.toolCallId&&t.set(n.toolCallId,n);return t},[e]);return(0,$.jsxs)(`div`,{className:`compacted-history-stream`,children:[(0,$.jsxs)(`div`,{className:`compacted-history-stream-header`,children:[(0,$.jsxs)(`span`,{className:`compacted-history-badge`,children:[(0,$.jsx)(ye,{}),` `,n(`compactedHistoryBadge`)]}),(0,$.jsx)(`span`,{className:`compacted-history-count`,children:n(`compactedHistoryTurns`,{count:e.length})})]}),(0,$.jsx)(`div`,{className:`compacted-history-messages`,children:e.map(e=>t(e,r))})]})}function su({message:e,forceOpen:t=!1,autoExpand:n=!1,renderMessage:r}){let i=X(),[a,o]=(0,Q.useState)(!1),{copied:s,copy:c}=Gn({duration:1200}),[l,u]=(0,Q.useState)(n);n!==l&&(u(n),n&&o(!0));let d=a||t,f=Es(e.id),[p,m]=(0,Q.useState)(!1),g=()=>{p?m(!1):(m(!0),f.status===`idle`&&Ss(e.id))},_=e.content.map(e=>Gl(e)?.text??``).filter(Boolean).join(`
|
|
24
|
-
`),v=typeof e.tokensBefore==`number`?e.tokensBefore.toLocaleString():null;return(0,$.jsxs)(`div`,{className:`msg msg-compactionSummary`,"data-role":e.role,"data-msg-id":e.id,children:[(0,$.jsxs)(`div`,{className:`msg-meta`,children:[(0,$.jsx)(`span`,{className:`msg-role`,children:i(`role.compaction`)}),e.timestamp&&(0,$.jsx)(`span`,{className:`msg-time`,children:ru(e.timestamp)})]}),(0,$.jsxs)(`div`,{className:`compaction-card${a?` expanded`:``}`,children:[(0,$.jsx)(Pl,{open:d,headClassName:`compaction-head`,titleText:i(d?`collapseMsg`:`expandMsg`),onToggle:()=>o(e=>t?!0:!e),toggle:(0,$.jsx)(`span`,{className:`chead-toggle`,children:d?(0,$.jsx)(D,{}):(0,$.jsx)(At,{})}),icon:(0,$.jsx)(ye,{}),iconClassName:`compaction-icon`,titleClassName:`compaction-title`,after:_&&(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:i(s?`copied`:`copyMessage`),"aria-label":i(`copyMessage`),onClick:e=>{e.stopPropagation(),c(_)},children:s?(0,$.jsx)(h,{}):(0,$.jsx)(st,{})}),children:v?i(`compactionFrom`,{tokens:v}):i(`role.compaction`)}),d&&(0,$.jsxs)(`div`,{className:`compaction-body`,children:[(0,$.jsx)(`div`,{className:`compaction-summary`,children:(0,$.jsx)(nl,{text:_})}),(0,$.jsx)(`div`,{className:`compaction-hint`,children:i(`compactionKeptHint`)}),(0,$.jsx)(`div`,{className:`compacted-history-action`,children:(0,$.jsxs)(`button`,{type:`button`,className:`compacted-history-toggle-btn`,"data-disclosure":``,onClick:g,"aria-expanded":p,children:[(0,$.jsx)(`span`,{className:`compacted-history-chevron`,children:p?(0,$.jsx)(D,{}):(0,$.jsx)(At,{})}),(0,$.jsx)(re,{className:`compacted-history-clock-icon`}),(0,$.jsx)(`span`,{className:`compacted-history-btn-text`,children:i(p?`hideCompactedHistory`:`viewCompactedHistory`)}),f.status===`ready`&&f.messages.length>0&&(0,$.jsx)(`span`,{className:`compacted-history-count-pill`,children:i(`compactedHistoryTurns`,{count:f.messages.length})})]})}),p&&(0,$.jsxs)(`div`,{className:`compacted-history-panel`,children:[f.status===`loading`&&(0,$.jsxs)(`div`,{className:`compacted-history-loading`,children:[(0,$.jsx)(`span`,{className:`compact-pulse`}),(0,$.jsx)(`span`,{children:i(`compactedHistoryLoading`)})]}),f.status===`error`&&(0,$.jsx)(`div`,{className:`compacted-history-error`,children:(0,$.jsx)(`span`,{children:f.error===`compactedHistoryNotFound`||f.error===`Compaction entry not found`?i(`compactedHistoryNotFound`):f.error||i(`compactedHistoryEmpty`)})}),f.status===`ready`&&f.messages.length===0&&(0,$.jsx)(`div`,{className:`compacted-history-empty`,children:i(`compactedHistoryEmpty`)}),f.status===`ready`&&f.messages.length>0&&(0,$.jsx)(ou,{messages:f.messages,renderMessage:r})]})]})]})]})}function cu({block:e,forceOpen:t=!1}){let n=X(),[i,a]=(0,Q.useState)(!1),{copied:o,copy:s}=Gn({duration:1200}),c=i||t;return(0,$.jsxs)(`div`,{className:`skillcard${i?` expanded`:``}`,children:[(0,$.jsx)(Pl,{open:c,headClassName:`skillcard-head`,titleText:e.location,onToggle:()=>a(e=>t?!0:!e),toggle:(0,$.jsx)(`span`,{className:`chead-toggle`,children:c?(0,$.jsx)(D,{}):(0,$.jsx)(At,{})}),icon:(0,$.jsx)(r,{}),iconClassName:`skillcard-icon`,titleClassName:`skillcard-name`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`skillcard-path`,children:e.location}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy`,title:n(o?`copied`:`copyMessage`),"aria-label":n(`copyMessage`),onClick:t=>{t.stopPropagation(),s(e.content)},children:o?(0,$.jsx)(h,{}):(0,$.jsx)(st,{})})]}),children:e.name}),c&&(0,$.jsx)(`div`,{className:`skillcard-body`,children:(0,$.jsx)(nl,{text:e.content})})]})}var lu=`canvas`,uu=`terminal`,du=[uu],fu=[`terminal_create`,`terminal_list`,`terminal_close`,`terminal_input`,`terminal_key`,`terminal_read`,`terminal_wait`],pu=`conversation`,mu=`communicate`,hu=[`subagent`,`subagent_spawn`,`subagent_get_result`,`subagent_steer`,`subagent_list`,`subagent_stop`,`subagent_wait_all`,`subagent_templates`,`subagent_handoff`],gu=`delegate_task`,_u=`ask_user_question`,vu=`browser_page`,yu=`browser_script`,bu=`browser_design`,xu=`phone`,Su=`skill`,Cu=`schedule`,wu=`bg_task`,Tu=[`schedule_task`,`schedule_list`,`schedule_cancel`],Eu=`eval`,Du=`present_files`,Ou=`claim_files`,ku=`plan_update`,Au=`compact_context`,ju=`patch`,Mu=`mcp_manage`,Nu=`sandbox`,Pu=`worktree`,Fu=`device_collab`,Iu=`memory`,Lu=`agent_bot`,Ru=`codemode`,zu=`tool_search`,Bu=`load_tools`,Vu=[`bash`,`read`,`edit`,`write`],Hu=[...du.map(e=>({name:e,group:`terminal`,defaultOn:!1})),{name:pu,group:`subagent`,defaultOn:!0},{name:mu,group:`subagent`,defaultOn:!0,descKey:`communicateEnabledDesc`,offHintKey:`communicateOffHint`},{name:gu,group:`other`,defaultOn:!1,descKey:`delegateTaskEnabledDesc`,offHintKey:`delegateTaskOffHint`},{name:_u,group:`other`,defaultOn:!0,descKey:`questionnaireEnabledDesc`,offHintKey:`questionnaireOffHint`},{name:vu,group:`other`,defaultOn:!1,descKey:`browserPageEnabledDesc`,offHintKey:`browserPageOffHint`},{name:yu,group:`other`,defaultOn:!1,descKey:`browserScriptEnabledDesc`,offHintKey:`browserScriptOffHint`},{name:bu,group:`other`,defaultOn:!1,descKey:`browserDesignEnabledDesc`,offHintKey:`browserDesignOffHint`},{name:xu,group:`other`,defaultOn:!1,descKey:`phoneEnabledDesc`,offHintKey:`phoneOffHint`},{name:Ou,group:`other`,defaultOn:!0,descKey:`claimFilesEnabledDesc`,offHintKey:`claimFilesOffHint`},{name:ku,group:`other`,defaultOn:!0,descKey:`planUpdateEnabledDesc`,offHintKey:`planUpdateOffHint`},{name:Lu,group:`other`,defaultOn:!0,descKey:`agentBotToolEnabledDesc`,offHintKey:`agentBotToolOffHint`},{name:ju,group:`other`,defaultOn:!1,descKey:`patchToolEnabledDesc`,offHintKey:`patchToolOffHint`},{name:`lsp`,group:`other`,defaultOn:!1,descKey:`lspToolEnabledDesc`,offHintKey:`lspToolOffHint`},{name:Du,group:`other`,defaultOn:!0,descKey:`presentFilesEnabledDesc`,offHintKey:`presentFilesOffHint`},{name:Su,group:`other`,defaultOn:!0,descKey:`skillEnabledDesc`,offHintKey:`skillOffHint`},{name:Eu,group:`other`,defaultOn:!1,descKey:`evalEnabledDesc`,offHintKey:`evalOffHint`},{name:Ru,group:`other`,defaultOn:!1,descKey:`codemodeEnabledDesc`,offHintKey:`codemodeOffHint`},{name:zu,group:`other`,defaultOn:!1,descKey:`toolSearchEnabledDesc`,offHintKey:`toolSearchOffHint`},{name:Cu,group:`other`,defaultOn:!0,descKey:`scheduleTaskEnabledDesc`,offHintKey:`scheduleTaskOffHint`},{name:wu,group:`other`,defaultOn:!0,descKey:`bgTaskEnabledDesc`,offHintKey:`bgTaskOffHint`},{name:Au,group:`other`,defaultOn:!0,descKey:`compactContextEnabledDesc`,offHintKey:`compactContextOffHint`},{name:Mu,group:`other`,defaultOn:!1,descKey:`mcpManageEnabledDesc`,offHintKey:`mcpManageOffHint`},{name:Nu,group:`other`,defaultOn:!1,descKey:`sandboxEnabledDesc`,offHintKey:`sandboxOffHint`},{name:Pu,group:`other`,defaultOn:!1,descKey:`toolsWorktreeDesc`,offHintKey:`toolsWorktreeOffHint`},{name:lu,group:`other`,defaultOn:!1,descKey:`canvasToolEnabledDesc`,offHintKey:`canvasToolOffHint`}],Uu=[{name:Fu,group:`other`,defaultOn:!1,allowAgentToggle:!1,descKey:`toolsDeviceCollabDesc`,offHintKey:`toolsDeviceCollabOffHint`},{name:Iu,group:`other`,defaultOn:!1,allowAgentToggle:!1}],Wu=[{name:`bash`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreBashDesc`},{name:`read`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreReadDesc`},{name:`edit`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreEditDesc`},{name:`write`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreWriteDesc`},{name:`powershell`,group:`core`,defaultOn:!1,platform:`win32`,allowAgentToggle:!1,descKey:`toolCorePowershellDesc`},{name:`ls`,group:`core`,defaultOn:!1,allowAgentToggle:!1,descKey:`toolCoreLsDesc`},{name:`grep`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreGrepDesc`},{name:`find`,group:`core`,defaultOn:!0,allowAgentToggle:!1,descKey:`toolCoreFindDesc`}],Gu=[...Wu.map(e=>({name:e.name,group:`core`,defaultOn:e.defaultOn,platform:e.platform,allowAgentToggle:e.allowAgentToggle,descKey:e.descKey})),...Hu,...Uu],Ku=new Map(Gu.map(e=>[e.name,e]));function qu(e){return Ku.get(e)}var Ju=new Set(Gu.map(e=>e.name)),Yu=Gu.map(e=>e.name);function Xu(e){let t=new Set(Zu(e));return Yu.filter(e=>!t.has(e))}function Zu(e){if(!Array.isArray(e))return Qu();let t=[];for(let n of e){let e=n;typeof e==`string`&&fu.includes(e)&&(e=uu),typeof e==`string`&&hu.includes(e)&&(e=pu),e===`conversation_read`&&(e=pu),typeof e==`string`&&Tu.includes(e)&&(e=Cu),typeof e==`string`&&Ju.has(e)&&!t.includes(e)&&t.push(e)}return t}function Qu(){return Gu.filter(e=>!e.defaultOn).map(e=>e.name)}function $u(e,t){let n=Array.from(e);if(!t||t===`standard`)return n;if(t===`ask`)return[];if(t===`minimal`)return n.filter(e=>e===`bash`||e===`read`);if(t===`code`){let e=new Set([`bash`,`read`,`edit`,`write`]);return n.filter(t=>e.has(t))}if(t===`reader`){let e=new Set([`write`,`edit`,`bash`,`powershell`,`terminal_create`,`terminal_input`,`terminal_close`,`terminal_key`,`codemode`]);return n.filter(t=>!e.has(t))}return n}function ed(e){return $u([Su],e).includes(Su)}var td=[{id:`phone.gesture`,ops:[`tap`,`long_press`,`swipe`],label:`手机操控:点击 / 长按 / 滑动`,labelEn:`Phone control: tap / long-press / swipe`,reason:`模型要在你的手机屏幕上点击或滑动`,reasonEn:`The model wants to tap or swipe on your phone screen`},{id:`phone.input`,ops:[`input`],label:`手机操控:输入文本`,labelEn:`Phone control: type text`,reason:`模型要向手机当前输入框打字(聊天、短信、搜索框等)`,reasonEn:`The model wants to type into the focused input on your phone (chat, SMS, search field)`},{id:`phone.key`,ops:[`key`],label:`手机操控:系统按键`,labelEn:`Phone control: system keys`,reason:`模型要按返回 / 主页 / 最近任务等系统按键`,reasonEn:`The model wants to press system keys (back / home / recents)`},{id:`phone.launch`,ops:[`launch`],label:`手机操控:启动应用`,labelEn:`Phone control: launch app`,reason:`模型要启动手机上的某个应用`,reasonEn:`The model wants to launch an app on your phone`}];function nd(e){return`"op"\\s*:\\s*"\\s*(?:${e.map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,e=>`\\${e}`)).join(`|`)})\\s*"`}var rd=td.map(e=>({id:`builtin.${e.id}`,enabled:!0,tools:[xu],field:`params`,match:`regex`,value:nd(e.ops),action:`ask`,label:e.label,labelEn:e.labelEn,reason:e.reason,reasonEn:e.reasonEn,categoryId:e.id,builtin:!0})),id=[{id:`builtin.bash.rm-rf`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\brm\\s+((-[a-zA-Z0-9]*[rf][a-zA-Z0-9]*|--recursive|--force)\\s+)+(((\\/)|(~)|(\\.\\.)|(\\*)|(\\.\\/))|[a-zA-Z]:[\\\\/])`,action:`ask`,label:`递归/强制删除 (rm -rf)`,labelEn:`Recursive/force delete (rm -rf)`,reason:`检测到高风险的递归/强制删除大范围路径命令 (rm -rf)`,reasonEn:`Detected high-risk recursive/force deletion of wide paths (rm -rf)`,categoryId:`bash.rm-rf`,builtin:!0},{id:`builtin.bash.win-del`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\b(del|rmdir|rd)\\s+[/\\-][fsq]`,action:`ask`,label:`Windows 强制删除 (del/rmdir/rd)`,labelEn:`Windows force delete (del/rmdir/rd)`,reason:`检测到高风险的 Windows 强制/递归删除目录命令 (del/rmdir/rd /s /q)`,reasonEn:`Detected high-risk Windows force/recursive deletion command (del/rmdir/rd /s /q)`,categoryId:`bash.win-del`,builtin:!0},{id:`builtin.bash.disk`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\b(mkfs|format\\s+[a-zA-Z]:|dd\\s+if=)`,action:`ask`,label:`磁盘格式化/底层写入`,labelEn:`Disk format / raw block write`,reason:`检测到磁盘格式化或底层块写入危险命令 (format/mkfs/dd)`,reasonEn:`Detected dangerous disk formatting or raw block write command (format/mkfs/dd)`,categoryId:`bash.disk`,builtin:!0},{id:`builtin.bash.git-destructive`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bgit(?:\\.exe)?(?:\\s+(?:-[cC]\\s+\\S+|--[a-zA-Z-]+=\\S+))*\\s+(?:push\\s+(?:[^;&|\\n]*?\\s)?(?:--force|-[a-zA-Z0-9]*f)\\b|push\\s+(?:[^;&|\\n]*?\\s)?(?:\\+\\S+|:[^\\s/]\\S*)|reset\\s+--hard|clean\\s+(?:-[a-zA-Z]+\\s+)*-[a-zA-Z0-9]*f[a-zA-Z0-9]*|branch\\s+-[dD]\\b|checkout\\s+(?:--\\s+)?\\.(?=\\s|$|[;&|])|restore\\s+(?:--(?!staged\\b)\\S+\\s+)*\\.(?=\\s|$|[;&|])|stash\\s+(?:drop|clear)\\b)`,action:`ask`,label:`破坏性 Git 操作`,labelEn:`Destructive git operation`,reason:`检测到不可逆的破坏性 Git 操作 (force push / reset --hard / clean -f / checkout . / stash drop|clear / branch -D)`,reasonEn:`Detected irreversible destructive Git operation (force push / reset --hard / clean -f / checkout . / stash drop|clear / branch -D)`,categoryId:`bash.git-destructive`,builtin:!0},{id:`builtin.bash.git-worktree`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bgit(?:\\.exe)?(?:\\s+(?:-[cC]\\s+\\S+|--[a-zA-Z-]+=\\S+))*\\s+worktree\\s+(add|remove|prune)\\b`,action:`ask`,label:`Git 工作树操作 (git worktree)`,labelEn:`Git worktree operation (git worktree)`,reason:`检测到通过 Bash 执行 git worktree 操作;建议使用专门的 worktree 工具(该工具同样受注册校验与审批)`,reasonEn:`Detected git worktree via Bash; prefer the dedicated worktree tool (that tool is also subject to registration checks and approval)`,categoryId:`bash.git-worktree`,builtin:!0},{id:`builtin.worktree.outside-workspace`,enabled:!0,tools:[Pu],field:`path`,match:`outside_workspace`,value:``,action:`ask`,label:`工作树切到工作区外`,labelEn:`Worktree switch outside workspace`,reason:`尝试把当前工作区切换到工作区之外的目录(切换后本会话的写入边界会跟着变)`,reasonEn:`Attempting to switch the active workspace to a directory outside the workspace (the write boundary follows the switch)`,categoryId:`worktree.outside-workspace`,builtin:!0},{id:`builtin.bash.chmod`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`\\bchmod\\s+(-R\\s+)?(777|000)\\b`,action:`ask`,label:`危险权限修改 (chmod)`,labelEn:`Dangerous permission change (chmod)`,reason:`检测到过度开放或全局破坏性的文件权限修改 (chmod 777/000)`,reasonEn:`Detected overly permissive or globally destructive file permission change (chmod 777/000)`,categoryId:`bash.chmod`,builtin:!0},{id:`builtin.bash.system-redirect`,enabled:!0,tools:[`bash`],field:`command`,match:`regex`,value:`>\\s*(\\/etc\\/|\\/boot\\/|C:\\\\Windows)`,action:`ask`,label:`写入系统关键目录`,labelEn:`Write into system directories`,reason:`检测到重定向写入系统关键目录的危险操作`,reasonEn:`Detected dangerous redirection writing into critical system directories`,categoryId:`bash.system-redirect`,builtin:!0},{id:`builtin.file.sensitive.env`,enabled:!0,tools:[`write`,`edit`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])\\.env(\\.[a-zA-Z0-9_-]+)?$`,action:`ask`,label:`敏感配置 (.env)`,labelEn:`Sensitive config (.env)`,reason:`尝试修改敏感环境变量/密钥配置文件 (.env)`,reasonEn:`Attempting to modify sensitive environment/secret configuration (.env)`,categoryId:`file.sensitive.env`,builtin:!0},{id:`builtin.file.sensitive.ssh`,enabled:!0,tools:[`write`,`edit`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])(id_rsa|id_ed25519|authorized_keys|known_hosts)$`,action:`ask`,label:`SSH 密钥/凭据`,labelEn:`SSH keys / credentials`,reason:`尝试修改 SSH 密钥或认证凭据文件`,reasonEn:`Attempting to modify SSH keys or authentication credentials`,categoryId:`file.sensitive.ssh`,builtin:!0},{id:`builtin.file.sensitive.shell`,enabled:!0,tools:[`write`,`edit`,`patch`],field:`path`,match:`regex`,value:`(^|[\\/\\\\])(\\.bashrc|\\.zshrc|\\.profile|\\.bash_profile)$`,action:`ask`,label:`Shell 启动配置`,labelEn:`Shell profile`,reason:`尝试修改用户全局 Shell 启动配置文件`,reasonEn:`Attempting to modify user global Shell profile configuration`,categoryId:`file.sensitive.shell`,builtin:!0},{id:`builtin.file.outside-workspace`,enabled:!0,tools:[`write`,`edit`,`patch`],field:`path`,match:`outside_workspace`,value:``,action:`ask`,label:`工作区外写入`,labelEn:`Write outside workspace`,reason:`尝试在工作区外部写入/修改文件`,reasonEn:`Attempting to write/modify file outside the workspace`,categoryId:`file.outside-workspace`,builtin:!0},...rd].filter(e=>e.enabled&&e.field===`command`&&e.match===`regex`&&e.tools.some(e=>e.trim().toLowerCase()===`bash`));function ad(e){if(e.length<=1)return e;let t=[...e].sort((e,t)=>e.start-t.start),n=[t[0]];for(let e=1;e<t.length;e++){let r=t[e],i=n[n.length-1];r.start<=i.end?(i.end=Math.max(i.end,r.end),!r.label||i.label&&i.label.includes(r.label)||(i.label=i.label?`${i.label} / ${r.label}`:r.label)):n.push(r)}return n}function od(e,t){if(!e||typeof e!=`string`)return[];if(t&&t.length>0){let n=[];for(let r of t)if(r.field===`command`&&r.length>0){let t=Math.max(0,r.index),i=Math.min(e.length,t+r.length);i>t&&n.push({start:t,end:i,label:r.label})}if(n.length>0)return ad(n)}let n=[];for(let t of id){let r;try{r=new RegExp(t.value,`gi`)}catch{continue}for(let i of e.matchAll(r)){let e=i.index??0;i[0].length>0&&n.push({start:e,end:e+i[0].length,label:t.label})}}return ad(n)}function sd(e,t,n){let r=od(e,n);if(r.length===0)return e;let i=[],a=0;return r.forEach((n,r)=>{n.start>a&&i.push(e.slice(a,n.start));let o=e.slice(n.start,n.end);i.push((0,$.jsx)(`mark`,{className:`bash-danger-hit`,title:n.label??t(`bashDangerSegment`),children:o},r)),a=n.end}),a<e.length&&i.push(e.slice(a)),(0,$.jsx)($.Fragment,{children:i})}function cd(e,t){e&&Z({type:`open_bot_chat`,botId:e,...t?.fresh?{fresh:!0}:{}})}function ld(){window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{}}))}function ud(e,t,n,r){return e.flatMap(e=>[{providerId:`host:group-devices`,providerLabel:r(`newChat`),title:e.name,hint:e.id,text:`@${e.name} · ${r(`newChat`)}`},...t.filter(t=>t.botId===e.id&&t.status!==`closed`&&!t.stale).map(t=>({providerId:`host:group-conversations`,providerLabel:r(`deviceGroupMentionContinue`),title:`${e.name} · ${t.name||r(`groupDeliveriesUntitledConversation`)}`,hint:t.id,text:`@${e.name} · ${r(`deviceGroupMentionContinuePrefix`)}${t.name||r(`groupDeliveriesUntitledConversation`)}`}))].filter(t=>`${t.title} ${t.providerLabel} ${e.id}`.toLocaleLowerCase().includes(n.toLocaleLowerCase())))}function dd(e){return`@${e.name}(${e.id})`}function fd(e){return e.replace(/@([^\s()]+)\([a-f0-9-]{8,}\)/g,`@$1`)}function pd(e,t){let n=fd(e),r=n.match(/^@([^\s()]+)\s*(.*)$/);return r?{botPrefix:`@${r[1]}`,summary:r[2].trim()||n}:{botPrefix:t?`@${t}`:``,summary:n}}function md(e,t){if(!e.includes(`Device task failed`))return fd(e);let n=e.match(/Device task failed\s*\[phase=([^;]+);\s*category=([^\]]+)\]\.\s*(.*)/s);if(!n)return fd(e);let[,r,i,a]=n,o={model:t(`deviceGroupFailurePhaseModel`),tool:t(`deviceGroupFailurePhaseTool`),approval:t(`deviceGroupFailurePhaseApproval`),connection:t(`deviceGroupFailurePhaseConnection`),handshake:t(`deviceGroupFailurePhaseHandshake`),init:t(`deviceGroupFailurePhaseInit`),switch_session:t(`deviceGroupFailurePhaseSwitchSession`),new_chat:t(`deviceGroupFailurePhaseNewChat`)}[r]||r,s=a.trim();return[t(`deviceGroupFailureTitle`,{phase:o}),`>`,t(`deviceGroupFailureMeta`,{phase:r,category:i}),`>`,`> ${s||t(`deviceGroupFailureDetailFallback`)}`].join(`
|
|
25
|
-
`)}function hd(e,t){return[...new Set(t.filter(t=>e.includes(dd(t))).map(e=>e.id))]}function gd(e,t,n,r){let i=new Map,a=[],o=new Map(n.map(e=>[e.id,e]));for(let e of t?.bots??[])o.set(e.id,{...o.get(e.id),...e});let s={queued:r(`groupWorkItemsStatusQueued`),waiting:r(`deviceGroupStatusWaitingDependency`),running:r(`tabRunning`),completed:r(`groupWorkItemsStatusCompleted`),failed:r(`groupWorkItemsStatusFailed`),interrupted:r(`groupWorkItemsStatusInterrupted`)},c=new Map((t?.tasks??[]).map(e=>[e.id,e])),l=new Set,u=(e,t,n)=>{let r=e?o.get(e):void 0,i=r?.deviceName||n||r?.deviceId;return i?`${t} · ${i}`:t};for(let e of t?.messages??[]){let n=`group-message:${e.id}`,d=e.sender.type===`bot`,f=e.text,p=d?md(f,r):fd(f);if(e.sharedFrom){let t=o.get(e.sharedFrom.botId)?.name??e.sharedFrom.botId;p=`${e.sharedFrom.mode===`as_bot`?r(`deviceGroupSharedFromBot`,{bot:t}):r(`deviceGroupSharedFromForward`,{bot:t})}\n\n${p}`}let m=e.replyToMessageId?t?.messages.find(t=>t.id===e.replyToMessageId):void 0;if(m){let e=fd(m.text).replace(/\s+/g,` `).slice(0,120);p=`> ↩ ${m.sender.name}: ${e}\n\n${p}`}if(a.push({id:n,role:d?`assistant`:`user`,timestamp:e.createdAt,content:[{type:`text`,text:p}]}),!d){let t=e.sender.type===`webhook`?` [Webhook]`:``;i.set(n,`${e.sender.name}${t}`);continue}let h=(e.taskIds??[]).map(e=>c.get(e)).filter(t=>!!t&&t.botId===e.sender.id);for(let e of h)e.report&&l.add(e.id);let g=[...new Set(h.map(e=>s[e.status]))].join(` · `),_=t?.room.primaryBotId&&e.sender.id===t.room.primaryBotId?` [${r(`deviceGroupCoordinatorTag`)}]`:``,v=`${u(e.sender.id,e.sender.name,e.sender.sourceDeviceId)}${_}`;i.set(n,g?`${v} · ${g}`:v)}for(let e of t?.tasks??[]){if(l.has(e.id)||e.kind===`result`)continue;let t=`group-task:${e.id}`,n=o.get(e.botId),d=!!(e.parentTaskId||e.sourceBotId&&e.sourceBotId!==e.botId),f=r(`deviceGroupWorkerSubagent`),p=u(e.botId,n?.name??e.botId,e.deviceId),m=e.status===`waiting`?e.dependsOnTaskId?r(`groupConversationWaitingUpstream`):r(`deviceGroupStatusWaitingDependency`):s[e.status]??e.status;i.set(t,d?`${p} [${f}] · ${m}`:`${p} · ${m}`);let h=e.report,g=fd(e.text),_;if(h){if(d){let t=r(`deviceGroupSubagentSummary`);_=[r(`deviceGroupSubagentCompleted`,{bot:n?.name??e.botId}),r(`deviceGroupInstructionLine`,{label:r(`deviceGroupInstructionAssigned`),text:g}),``,`<details>`,`<summary>${t}</summary>`,``,md(h,r),``,`</details>`].join(`
|
|
26
|
-
`)}else _=md(h,r)}else if(e.status===`running`){let t=r(d?`deviceGroupSubagentRunning`:`deviceGroupTaskRunning`),i=e.progress?.phase,a=e.progress?.toolName,o=e.progress?.text?.trim();_=[`⏳ **${t}**${d?` · \`@${n?.name??e.botId}\``:``}`,r(`deviceGroupInstructionLine`,{label:r(d?`deviceGroupInstructionAssigned`:`deviceGroupInstructionGoal`),text:g}),...i?[r(`deviceGroupProgressPhaseLine`,{phase:i,tool:a?` · \`${a}\``:``})]:[],...o?[``,`> ${o}`]:[]].join(`
|
|
27
|
-
`)}else if(e.status===`waiting`){let t=e.dependsOnTaskId?c.get(e.dependsOnTaskId):void 0,i=t?o.get(t.botId)?.name??t.botId:void 0,a=t?pd(t.text,i).summary:e.dependsOnTaskId;_=[`${r(`deviceGroupWaitingUpstreamTitle`)}${d?` · \`@${n?.name??e.botId}\``:``}`,r(`deviceGroupInstructionLine`,{label:r(d?`deviceGroupInstructionAssigned`:`deviceGroupInstructionGoal`),text:g}),...e.dependsOnTaskId?[r(`deviceGroupDependsOnLine`,{dep:`${i?`@${i} · `:``}${a||e.dependsOnTaskId}`})]:[]].join(`
|
|
28
|
-
`)}else _=e.status===`queued`?[`⏱️ **${r(d?`deviceGroupSubagentQueued`:`deviceGroupTaskQueued`)}**${d?` · \`@${n?.name??e.botId}\``:``}`,r(`deviceGroupInstructionLine`,{label:r(d?`deviceGroupInstructionAssigned`:`deviceGroupInstructionGoal`),text:g})].join(`
|
|
29
|
-
`):e.status===`failed`&&d?[r(`deviceGroupSubagentFailed`,{bot:n?.name??e.botId}),r(`deviceGroupInstructionLine`,{label:r(`deviceGroupInstructionAssigned`),text:g}),...h?[``,md(h,r)]:[]].join(`
|
|
30
|
-
`):`${s[e.status]||e.status}\n\n${g}`;a.push({id:t,role:`assistant`,timestamp:e.createdAt,content:[{type:`text`,text:_}]})}return a.sort((e,t)=>(e.timestamp??0)-(t.timestamp??0)),{state:{clientId:`device-group`,cwd:``,sessionId:`device-group:${e}`,conversationId:`device-group:${e}`,rev:0,messages:a,streamingMessage:null,isStreaming:!1,model:null,thinkingLevel:``,availableThinkingLevels:[],queue:{steering:[],followUp:[]},tools:[],version:0,piConfigured:!0,piAgentInstalled:!0,stats:{totalMessages:a.length,tokens:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0},cost:0,contextUsage:{tokens:null,contextWindow:0,percent:null}}},labels:i}}function _d(e,t,n,r,i){let a=JSON.stringify({roomId:t,text:n,targetBotIds:[...r].sort()});return e?.fingerprint===a?e:{fingerprint:a,key:i()}}function vd(e){let t=e.filter(e=>e.conversationId);if(!t.length)return;let n=t[0].conversationId;if(e.some(e=>e.conversationId!==n))throw Error(`同一条消息只能继续一个对话,请移除其他 @ 目标。 / Continue one conversation per message. Remove other @ targets.`);return n}function yd(e,t,n){let r=0;for(;r<e.length&&r<t.length&&e[r]===t[r];)r++;let i=e.length,a=t.length;for(;i>r&&a>r&&e[i-1]===t[a-1];)i--,a--;return n.flatMap(e=>{if(e.end<=r)return[e];if(e.start>=i){let t=a-i;return[{...e,start:e.start+t,end:e.end+t}]}return[]})}function bd(e,t){let n=e;for(let e of[...t].sort((e,t)=>t.start-e.start))n=n.slice(0,e.start)+dd(e.member)+n.slice(e.end);return{text:n,targets:[...new Set(t.map(e=>e.member.id))]}}function xd(e,t,n,r,i){let a=i.filter(i=>t===n?r===`Backspace`?t>i.start&&t<=i.end+ +(e[i.end]===` `):t>=i.start&&t<i.end:t<i.end&&n>i.start);return a.length?{start:Math.min(t,...a.map(e=>e.start)),end:Math.max(n,...a.map(e=>e.end))}:null}var Sd=new Map,Cd=new Map;function wd(e,t){let n=Cd.get(e);if(n)n(t);else{let n=Sd.get(e)??[];n.some(e=>e.id===t.id)||n.push(t),Sd.set(e,n)}window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{roomId:e}}))}function Td(e,t){Cd.set(e,t);let n=Sd.get(e)??[];Sd.delete(e);for(let e of n)t(e);return()=>{Cd.get(e)===t&&Cd.delete(e)}}function Ed(e,t,n){let r=`@${n.name}`,i=e.slice(0,t),a=`${i&&!/\s$/.test(i)?` `:``}${r} `;return{text:i+a+e.slice(t),cursor:t+a.length}}function Dd(e,t,n=`Device`){let r=e=>typeof e==`string`?e.trim().slice(0,256):``,i=r(e),a=r(t);return a&&i&&a!==i?`${a} · ${i}`:a||i||n}function Od(e){if(e.transport===`p2p`)return e.relayed===!0?`turn`:e.route===`peer`?`peer`:`p2p`;if(e.transport===`lan`||e.transport===`hub`)return e.transport}function kd(e,t){switch(e){case`lan`:return t(`desktop.lan`);case`p2p`:return t(`desktop.p2p`);case`turn`:return`TURN`;case`peer`:return t(`connected`);case`hub`:return t(`desktop.hub`);case`current`:return t(`desktop.currentConnection`);default:return t(`desktop.connecting`)}}function Ad(){return We().match(/\/(?:device|device-lan)\/([a-z0-9][a-z0-9-]{0,62})\/__relay\/[a-f0-9]{64}\/$/)?.[1]}async function jd(e,t,n){let r=Ad();if(!r)return;let i=Pd;if(Nd)return;let a=await fetch(W(j(`/api/device-center/chat-status`)),{credentials:`same-origin`,signal:n?AbortSignal.any([n,AbortSignal.timeout(15e3)]):AbortSignal.timeout(15e3)});if(!a.ok)throw Error(`Device status unavailable`);let o=await a.json();n?.aborted||Pd!==i||Nd||await Hd(r,typeof o.hubUrl==`string`?o.hubUrl:``,!0,e,!1,Dd(o.name,o.remark,t))}function Md(e){return e.local===!0&&!Ad()}var Nd=null,Pd=0,Fd=new Set,Id=()=>Fd.forEach(e=>e()),Ld=e=>(Fd.add(e),()=>{Fd.delete(e)}),Rd=()=>Nd;function zd(e){Nd?.revision===e.revision&&(Nd=null,Id())}function Bd(e,t){Nd?.revision===e.revision&&(Nd={...Nd,mode:t},Id(),t===`preview`&&window.dispatchEvent(new Event(`pi:desktop-open`)))}async function Vd(e,t,n,r,i=!1,a,o=!1){if(n&&(o||e===Ad()))return{url:new URL(W(j(i?`/desktop-preview`:`/desktop`)),window.location.href).href,transport:`current`,fallbackOrigin:void 0};if(n&&Ad()){let t=new URL(j(`/__desktop_target`),window.location.href);return t.searchParams.set(`device`,e),t.searchParams.set(`preview`,i?`1`:`0`),{url:t.href,transport:`hub`,fallbackOrigin:void 0}}let s=await fetch(W(j(`/api/device-center/devices/${encodeURIComponent(e)}/open`)),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({preferLan:!0,desktop:n,basePath:new URL(j(`/`),window.location.href).pathname}),credentials:`same-origin`,signal:a?AbortSignal.any([a,AbortSignal.timeout(3e4)]):AbortSignal.timeout(3e4)});if(!s.ok)throw Error(r(`deviceAccessOpenFailed`));let c=await s.json(),l=c.transport===`lan`||c.transport===`p2p`,u=l?new URL(j(c.url),window.location.href):new URL(c.url),d=new URL(t),f=new URL(j(`/device-lan/${e}/__open`),window.location.href),p=l?typeof c.url==`string`&&/^\/device-lan\/[a-z0-9][a-z0-9-]{0,62}\/__open\?ticket=[a-f0-9]{64}$/.test(c.url)&&u.origin===f.origin&&u.pathname===f.pathname:u.hostname===d.hostname&&(u.pathname===`/__device/open`||u.origin===d.origin&&u.pathname===`/device/${encodeURIComponent(e)}/__open`);if(![`http:`,`https:`].includes(u.protocol)||u.username||u.password||!p)throw Error(`Invalid device access URL`);return u.searchParams.delete(`next`),n&&u.searchParams.set(`next`,i?`/desktop-preview`:`/desktop`),{url:u.href,transport:Od(c)??`hub`,fallbackOrigin:c.fallbackOrigin}}async function Hd(e,t,n,r,i=!1,a,o){let s=oe();if(s){if(!s.deviceAdapter)throw Error(`Native device access is unavailable`);await s.deviceAdapter.openDevice(e,t);return}if(n&&!i){Nd={id:e,hubUrl:t,name:a,revision:++Pd,...o,mode:o?.mode??`preview`},Id(),window.dispatchEvent(new Event(`pi:desktop-open`));return}if(n&&i&&Ad()&&window.parent!==window){await Ud(r,e);return}let c=window.piDesktop,l=c?.openHub?null:window.open(`about:blank`,`_blank`);if(!c?.openHub&&!l)throw Error(r(`deviceAccessPopupBlocked`));if(l){try{l.document.open(),l.document.write(`<!doctype html><meta charset="utf-8"><title>${r(`deviceAccessOpening`)}</title><style>html,body{height:100%;margin:0}body{display:grid;place-items:center;background:#0d0e12;color:#9aa1b4;font:14px/1.6 -apple-system,"PingFang SC","Microsoft YaHei",sans-serif}</style><body>${r(`deviceAccessOpening`)}</body>`),l.document.close()}catch{}l.opener=null}try{let i=await Vd(e,t,n,r,!1,void 0,o?.local),a=new URL(i.url);if(c?.openHub){if(i.transport!==`hub`&&(a.searchParams.set(`hub`,new URL(t).origin),typeof i.fallbackOrigin==`string`&&a.searchParams.set(`portal`,i.fallbackOrigin)),!await c.openHub(a.href))throw Error(r(`deviceAccessWindowFailed`))}else l&&l.location.replace(a.href)}catch(e){throw l?.close(),e}}function Ud(e,t){let n=or(),r=new URL(j(`/`),window.location.href).origin;return new Promise((i,a)=>{let o=e=>{clearTimeout(l),window.removeEventListener(`message`,c),e?a(Error(e)):i()},s=e(`deviceAccessTabFailed`),c=t=>{t.source===window.parent&&t.origin===r&&t.data?.type===`device-desktop-open-result`&&t.data.requestId===n&&o(t.data.ok===!0?void 0:t.data.error===`popup`?e(`deviceAccessPopupBlocked`):s)},l=setTimeout(()=>o(s),3e4);window.addEventListener(`message`,c),window.parent.postMessage({type:`device-desktop-open`,requestId:n,deviceId:t},r)})}function Wd({botIds:e,roomId:t}){let n=X(),[r,i]=(0,Q.useState)(null),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=!1,t,r;async function a(){t=new AbortController;try{let r=async e=>{let r=await fetch(W(j(`/api/device-center/${e}`)),{credentials:`same-origin`,signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)])});if(!r.ok)throw Error(n(`deviceGroupMembers.loadFailed`));return r.json()},[a,s]=await Promise.all([r(`chat-status`),r(`bots`)]);if(!a.hubUrl||!Array.isArray(s.bots))throw Error(n(`deviceGroupMembers.invalidBinding`));e||(i({hubUrl:a.hubUrl,deviceId:a.deviceId,bots:s.bots}),o(``))}catch(t){e||o(t instanceof Error?t.message:String(t))}finally{t.abort(),e||(r=setTimeout(a,15e3))}}return a(),()=>{e=!0,t?.abort(),clearTimeout(r)}},[n]);async function l(e,t){if(r&&!s){c(!0);try{await Hd(e.deviceId,r.hubUrl,t,n,!1,e.name),o(``)}catch(e){o(e instanceof Error?e.message:String(e))}finally{c(!1)}}}return(0,$.jsxs)(`div`,{className:`dg-side-members`,children:[a&&(0,$.jsx)(`div`,{className:`dg-side-error`,role:`alert`,children:a}),!r&&!a&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:n(`loading`)}),e.length===0&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:n(`deviceGroupMembers.empty`)}),r&&e.map(e=>{let i=r.bots.find(t=>t.id===e);return(0,$.jsx)(`div`,{className:`dg-side-member`,children:(0,$.jsxs)(`div`,{className:`dg-side-member-name`,title:i?.name||e,children:[(0,$.jsx)(`span`,{children:i?.name||e}),(0,$.jsx)(`small`,{children:i?.online?n(`deviceHubOnline`):n(`deviceHubOffline`)}),t&&i&&(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:n(`deviceGroupMembers.reference`),"aria-label":`${n(`deviceGroupMembers.reference`)} · ${i.name}`,onClick:()=>wd(t,i),children:(0,$.jsx)(I,{"aria-hidden":!0})}),i?.deviceId&&r.deviceId&&i.deviceId!==r.deviceId&&(0,$.jsxs)(`div`,{className:`dg-side-member-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:n(`deviceDirectory.remoteDesktop`),"aria-label":n(`deviceDirectory.remoteDesktop`),disabled:s||!i?.deviceId,onClick:()=>i&&void l(i,!0),children:(0,$.jsx)(se,{"aria-hidden":!0})}),(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,title:n(`deviceGroupMembers.openDevice`),"aria-label":n(`deviceGroupMembers.openDevice`),disabled:s||!i?.deviceId,onClick:()=>i&&void l(i,!1),children:(0,$.jsx)(Be,{"aria-hidden":!0})})]})]})},e)})]})}async function Gd(e,t){let n;try{n=JSON.parse(await e.text())}catch{throw Error(`Bot bundle is not valid JSON`)}let r=await wp(`bot-import`,t??new AbortController().signal,{bundle:n});return window.dispatchEvent(new CustomEvent(`pi-web-ui:device-bots-changed`)),{name:r?.bot?.name??e.name,imported:r?.imported??0,skipped:r?.skipped??0}}function Kd(e,t){let n=e.trim();if(/^ssh:\/\//i.test(n))return n;let r=n.replace(/\\/g,`/`);if(!r)return``;let i=/^(?:[a-z]:\/|\/)/i.test(r)?r:`${t.replace(/\\/g,`/`).replace(/\/$/,``)}/${r}`,a=i.match(/^(?:[a-z]:\/|\/\/[^/]+\/[^/]+\/?|\/)/i)?.[0];if(!a)return r;let o=[];for(let e of i.slice(a.length).split(`/`))e===`..`?o.pop():e&&e!==`.`&&o.push(e);return a.replace(/\/$/,``)+`/`+o.join(`/`)}function qd({open:e,currentCwd:t,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:a,onCreateProject:o,mode:s=`project`,localOnly:c,initialTab:l,portalContainer:u}){let d=X();return e?(0,$.jsx)(ea,{portalContainer:u,localOnly:c,initialTab:l,currentCwd:t,pathCompletions:n,workspaceRoots:r,onClose:i,onSelectDirectory:(e,t)=>{a(e,t),i()},onCreateProject:o,mode:s,className:`project-picker`,backdropClassName:`project-picker-backdrop`,role:`dialog`,ariaLabel:d(`projectPickerTitle`)}):null}function Jd({cwd:e,onSelectCwd:t,onOpenProjectPicker:n,projects:r=[],workspaceRoots:i,pathCompletions:a,mode:o=`project`,baseCwd:s,onCreateProject:c,className:l=``,placeholder:u,inputId:d,disabled:f=!1,commitOnBlur:p=!1,localOnly:m=!1,onPickerOpenChange:h}){let g=mn(`pathCompletions`),_=mn(`workspaceRoots`),v=a&&a.length>0?a:g??[],y=i&&i.length>0?i:_??[],[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(e);(0,Q.useEffect)(()=>C(e),[e]);let[w,T]=(0,Q.useState)(!1),E=(0,Q.useRef)(null),O=X();(0,Q.useEffect)(()=>{let e=e=>{E.current&&!E.current.contains(e.target)&&x(!1)};if(b)return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[b]);let k=[{label:O(`universalPathDirRoot`),value:`.`},{label:O(`universalPathDirWeb`),value:`web`},{label:O(`universalPathDirServer`),value:`server`},{label:O(`universalPathDirTests`),value:`tests`},{label:O(`universalPathDirSrc`),value:`src`},{label:O(`universalPathDirDocs`),value:`docs`}],A=()=>{T(!1),h?.(!1)},j=()=>{f||(n?n():(x(!1),T(!0),h?.(!0)))},M=e&&e!==`.`?e:s||e||`.`;return(0,$.jsxs)(`div`,{className:`universal-path-picker-root ${l}`,ref:E,children:[(0,$.jsxs)(`div`,{className:`universal-path-input-group`,children:[(0,$.jsx)(Ee,{className:`universal-path-icon`}),(0,$.jsx)(`input`,{type:`text`,className:`universal-path-input`,value:p?S:e,id:d,disabled:f,onChange:e=>p?C(e.target.value):t(e.target.value),onBlur:()=>{p&&S!==e&&t(S)},onKeyDown:n=>{p&&n.key===`Enter`&&(n.preventDefault(),S!==e&&t(S))},placeholder:u??O(`universalPathPlaceholder`),title:O(`universalPathCwdTitle`,{cwd:e||`.`})}),(0,$.jsx)(`button`,{type:`button`,className:`universal-path-dropdown-toggle`,disabled:f,onClick:()=>x(!b),title:O(`universalPathDropdownTip`),children:(0,$.jsx)(D,{})})]}),(0,$.jsx)(bn,{className:`universal-path-browse-btn`,tip:O(`projectPickerTitle`),disabled:f,onClick:j,children:(0,$.jsx)(je,{})}),b&&(0,$.jsxs)(`div`,{className:`universal-path-menu`,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:[y.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`universal-path-menu-header`,children:`工作区根目录`}),y.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e),x(!1)},children:(0,$.jsx)(`span`,{className:`path-label`,children:e})},e))]}),(0,$.jsx)(`div`,{className:`universal-path-menu-header`,children:`推荐子目录`}),k.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e.value),x(!1)},children:(0,$.jsx)(`span`,{className:`path-label`,children:e.label})},e.value)),r.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`universal-path-menu-header`,children:[(0,$.jsx)(re,{}),` 最近项目`]}),r.slice(0,6).map(e=>{let n=e.path.split(/[/\\]/).filter(Boolean).pop()||e.path;return(0,$.jsxs)(`button`,{type:`button`,className:`universal-path-menu-item`,onClick:()=>{t(e.path),x(!1)},title:e.path,children:[(0,$.jsx)(`span`,{className:`path-title`,children:n}),(0,$.jsx)(`span`,{className:`path-sub`,children:e.path})]},e.path)})]})]}),!n&&w&&(0,$.jsx)(qd,{portalContainer:E.current?.closest(`dialog`)??void 0,localOnly:m,open:!0,currentCwd:M,pathCompletions:v,workspaceRoots:y,onClose:A,onSelectDirectory:e=>{t(e),A()},onCreateProject:c?e=>{c(e),A()}:void 0,mode:o})]})}function Yd({align:e,triggerLeft:t,triggerRight:n,menuWidth:r,viewportWidth:i,margin:a=8}){if(r<=0||i<=0)return 0;let o=e===`left`?t:n-r,s=Math.max(a,i-a-r);return Math.round(Math.max(a,Math.min(o,s))-o)}function Xd({triggerRect:e,menuWidth:t,menuHeight:n,viewportWidth:r,viewportHeight:i,direction:a=`down`,align:o=`right`,gap:s=6,margin:c=8}){if(t<=0||r<=0||i<=0)return{left:Math.round(e.left),top:Math.round(e.bottom+s)};let l=Math.max(c,r-c-t),u=Math.max(c,i-c-n),d=c,f=c,p,m=Math.max(0,e.top-s-c),h=Math.max(0,i-e.bottom-s-c);if(a===`right`)d=e.right+s,d+t>r-c&&e.left-t-s>=c&&(d=e.left-t-s),d=Math.max(c,Math.min(d,l)),f=e.top,f+n>i-c&&(f=i-c-n),f=Math.max(c,Math.min(f,u)),p=Math.max(0,i-2*c);else if(a===`left`)d=e.left-t-s,d<c&&e.right+s+t<=r-c&&(d=e.right+s),d=Math.max(c,Math.min(d,l)),f=e.top,f+n>i-c&&(f=i-c-n),f=Math.max(c,Math.min(f,u)),p=Math.max(0,i-2*c);else if(a===`up`){m>=n?(f=e.top-n-s,p=m):h>=n||h>m?(f=e.bottom+s,p=h):(p=m,f=e.top-Math.min(n,m)-s);let r=Math.max(c,i-c-Math.min(n,p));f=Math.max(c,Math.min(f,r));let a=o===`left`?e.left:e.right-t;d=Math.max(c,Math.min(a,l))}else{h>=n?(f=e.bottom+s,p=h):m>=n?(f=e.top-n-s,p=m):m>h?(f=e.top-Math.min(n,m)-s,p=m):(f=e.bottom+s,p=h);let r=Math.max(c,i-c-Math.min(n,p));f=Math.max(c,Math.min(f,r));let a=o===`left`?e.left:e.right-t;d=Math.max(c,Math.min(a,l))}return{left:Math.round(d),top:Math.round(f),...p===void 0?{}:{maxHeight:Math.round(p)}}}function Zd({trigger:e,open:t,onOpenChange:n,children:r,align:i=`right`,fit:a=!1,direction:o=`down`,portal:s=!1,tip:c,caret:l=!0,menuClassName:u,triggerClassName:d,onContextMenu:f,dataBarItem:p,menuRef:m,menuStyle:h,className:g}){let _=(0,Q.useRef)(null),v=(0,Q.useRef)(null),[y,b]=(0,Q.useState)(0),[x,S]=(0,Q.useState)(null),C=e=>{v.current=e,typeof m==`function`?m(e):m&&`current`in m&&(m.current=e)},w=()=>{let e=_.current,t=v.current;if(!e||!t)return;if(window.innerWidth<=768){y!==0&&b(0);return}let n=t.getBoundingClientRect(),r=e.getBoundingClientRect();if(r.width===0&&r.height===0||n.width===0)y!==0&&b(0);else if(s){let e=Xd({triggerRect:r,menuWidth:n.width,menuHeight:n.height,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,direction:o,align:i,gap:6,margin:8});S(t=>t?.left===e.left&&t?.top===e.top&&t?.maxHeight===e.maxHeight?t:e)}else{let e=n.width,t=Yd({align:i,triggerLeft:r.left,triggerRight:r.right,menuWidth:e,viewportWidth:window.innerWidth,margin:8});t!==y&&b(t)}};(0,Q.useLayoutEffect)(()=>{t?w():(y!==0&&b(0),x!==null&&S(null))}),(0,Q.useEffect)(()=>{if(t)return window.addEventListener(`resize`,w),s&&window.addEventListener(`scroll`,w,!0),()=>{window.removeEventListener(`resize`,w),s&&window.removeEventListener(`scroll`,w,!0)}},[t,y,s,o,i]),br(_,()=>n(!1),{enabled:t,ignore:v}),Lt(()=>n(!1),t);let T=typeof window<`u`&&window.innerWidth<=768?{...h,pointerEvents:`auto`}:{...h,position:`fixed`,left:x?`${x.left}px`:`-9999px`,top:x?`${x.top}px`:`-9999px`,maxHeight:x?.maxHeight==null?h?.maxHeight:h?.maxHeight==null?`${x.maxHeight}px`:`min(${x.maxHeight}px, ${h.maxHeight})`,right:`auto`,bottom:`auto`,pointerEvents:`auto`,visibility:x?`visible`:`hidden`},E=x!=null&&_.current?x.top<_.current.getBoundingClientRect().top:o===`up`;return(0,$.jsxs)(`div`,{className:`dropdown ${i} ${a?`fit`:``} ${o===`up`?`dd-up`:``} ${g??``}`.trim(),ref:_,children:[(0,$.jsxs)(`button`,{type:`button`,className:d??`chip`,onClick:()=>n(!t),onContextMenu:f,"aria-expanded":t,"data-tip":c,"data-bar-item":p,children:[e,l&&(0,$.jsx)(D,{className:`dd-caret ${t?`up`:``}`})]}),t&&(s?(0,Er.createPortal)((0,$.jsx)(`div`,{className:`dd-portal-wrapper dropdown ${i} ${a?`fit`:``} ${E?`dd-up`:``}`,style:{position:`fixed`,left:0,top:0,width:`100%`,height:`100%`,pointerEvents:`none`,zIndex:9999},children:(0,$.jsx)(`div`,{className:`dd-menu ${u??``}`,ref:C,style:T,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),children:r})}),document.body):(0,$.jsx)(`div`,{className:`dd-menu ${u??``}`,ref:C,onPointerDown:e=>e.stopPropagation(),onMouseDown:e=>e.stopPropagation(),onWheel:e=>e.stopPropagation(),style:y===0?h:{...h,transform:h?.transform?`${h.transform} translateX(${y}px)`:`translateX(${y}px)`},children:r}))]})}function Qd({active:e,disabled:t=!1,title:n,onClick:r,children:i}){return(0,$.jsx)(`button`,{type:`button`,className:`dd-item ${e?`active`:``}`,disabled:t,title:n,onClick:r,children:i})}var $d=`pi-web-model-usage`;function ef(e){if(!e||typeof e!=`object`)return{};let t={};for(let[n,r]of Object.entries(e)){let e=typeof r==`number`?Math.floor(r):0;Number.isFinite(e)&&e>0&&(t[n]=e)}return t}function tf(e,t){return t?{...e,[t]:(e[t]??0)+1}:e}function nf(e,t){let n=t;return e.map((e,t)=>({m:e,i:t,count:n[e.id]??0})).sort((e,t)=>t.count-e.count||e.i-t.i).map(e=>e.m)}function rf(){try{let e=localStorage.getItem($d);return e?ef(JSON.parse(e)):{}}catch{return{}}}function af(e){try{localStorage.setItem($d,JSON.stringify(e))}catch{}}function of(e){let t=tf(rf(),e);return af(t),t}function sf(e,t){return t?t===e.id||`${e.provider}/${e.id}`===t||t.includes(`/`)&&t.split(`/`)[1]===e.id:!1}function cf(e,t){return(e?t?.find(t=>t.id===e)?.name?.trim():``)||e}function lf(e,t){return Z(t?{type:`clear_default_model`}:{type:`set_default_model`,modelId:e.id})}function uf(e,t,n,r){let i=e?.trim();if(!i)return null;let a=i.indexOf(`/`),o=a>0?i.slice(0,a):``,s=a>0?i.slice(a+1):i,c=e=>e.includes(`/`)?e.slice(e.indexOf(`/`)+1):e,l=t.find(e=>e.id===i)??t.find(e=>`${e.provider}/${c(e.id)}`===i)??t.find(e=>e.provider===o&&c(e.id)===s)??null,u=l?.provider||o,d=u?r?.[u]:void 0;return{modelName:l?.name||s,modelId:l?c(l.id):s,provider:u,providerLabel:cf(u,n),keyName:d&&d.length>1?d.find(e=>e.active)?.name??null:null}}function df({models:e,modelsLoading:t=!1,providerKeys:n={},providers:r,defaultModel:i,currentModelId:a,active:o,onEnsureModels:s,loading:c=!1,onRefresh:l,onManageModels:u,onPickModel:d,onToggleDefault:f,isRowActive:p,extraTopRow:m,listRef:h,autoFocusSearch:g=!1,hideTitle:_=!1,bodyStyle:v,scrollStyle:y}){let b=X(),[x,S]=(0,Q.useState)(``),[C,w]=(0,Q.useState)(null),[T,E]=(0,Q.useState)({}),[D,O]=(0,Q.useState)(!1),k=(0,Q.useRef)(s);k.current=s;let A=(0,Q.useRef)(null),j=(0,Q.useCallback)(e=>{A.current=e,h&&(h.current=e)},[h]),M=(0,Q.useMemo)(()=>uf(a,e,r,n),[a,e,r,n]),N=()=>{S(``),w(null),requestAnimationFrame(()=>{let e=A.current?.querySelector(`.dd-item.active`);e&&typeof e.scrollIntoView==`function`&&e.scrollIntoView({block:`nearest`})})};(0,Q.useEffect)(()=>{o?(E(rf()),k.current()):(S(``),w(null),O(!1))},[o]);let P=(0,Q.useMemo)(()=>e.filter(e=>e.enabled!==!1).length,[e]),F=e.some(e=>e.enabled===!1),I=(0,Q.useMemo)(()=>!F||D?e:e.filter(e=>e.enabled!==!1||sf(e,a)),[e,F,D,a]),L=(0,Q.useMemo)(()=>{let e=x.trim().toLowerCase(),t=I;return C&&(t=t.filter(e=>e.provider===C.provider)),nf(e?t.filter(t=>t.name.toLowerCase().includes(e)||t.id.toLowerCase().includes(e)||t.provider.toLowerCase().includes(e)):t,T)},[I,x,C,T]),R=(0,Q.useMemo)(()=>{let e=new Map;for(let t of I)e.set(t.provider,(e.get(t.provider)??0)+1);let t=[];for(let[r,i]of[...e.entries()].sort((e,t)=>e[0].localeCompare(t[0]))){let e=n[r];if(e&&e.length>1)for(let n of e)t.push({provider:r,count:i,keyName:n.name});else t.push({provider:r,count:i,keyName:null})}return t},[I,n]),z=(0,Q.useMemo)(()=>{let e=[];for(let t of L){let r=null,i=n[t.provider];if(i&&i.length>1&&(r=i.find(e=>e.active)??i[0],C?.provider===t.provider&&C.keyName)){let e=i.find(e=>e.name===C.keyName);e&&(r=e)}let o=p?p(t,r):sf(t,a)&&(!r||r.active);e.push({model:t,key:r,active:o})}return e},[L,n,C,p,a]),B=i!==void 0;return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dd-header dd-header-flex`,children:[!_&&(0,$.jsx)(`span`,{className:`dd-header-title`,children:b(`availableModels`)}),(0,$.jsxs)(`div`,{className:`dd-header-actions`,style:_?{marginLeft:`auto`}:void 0,children:[!!i&&(0,$.jsxs)(`div`,{className:`dd-header-default`,title:b(`defaultModelLabel`,{model:i??``}),children:[(0,$.jsx)(`span`,{className:`dd-header-default-star`,children:`★`}),(0,$.jsx)(`span`,{className:`dd-header-default-name`,children:i.includes(`/`)?i.split(`/`).slice(1).join(`/`):i}),(0,$.jsx)(`button`,{type:`button`,className:`dd-header-default-clear`,title:b(`clearDefaultModel`),onClick:e=>{e.stopPropagation(),Z({type:`clear_default_model`})},children:`✕`})]}),F&&(0,$.jsx)(`button`,{type:`button`,className:`dd-scope-toggle ${D?`active`:``}`,onClick:()=>O(e=>!e),title:D?b(`showEnabledModelsTitle`,{n:P}):b(`showAllModelsTitle`,{n:e.length}),children:D?b(`showEnabledModels`,{n:P}):b(`showAllModels`,{n:e.length})}),(0,$.jsx)(`button`,{type:`button`,className:`dd-header-btn dd-refresh-btn`,onClick:l,title:b(`refreshModels`),"aria-label":b(`refreshModels`),children:(0,$.jsx)(pe,{className:c||t?`spin`:``})}),u&&(0,$.jsx)(`button`,{type:`button`,className:`dd-header-btn dd-manage-btn`,onClick:u,title:b(`manageModels`),"aria-label":b(`manageModels`),children:(0,$.jsx)(ze,{})})]})]}),(0,$.jsxs)(`div`,{className:`dd-search-row`,children:[(0,$.jsx)(mt,{}),(0,$.jsx)(`input`,{className:`dd-search`,type:`text`,autoFocus:g,placeholder:b(`searchModels`),value:x,onChange:e=>S(e.target.value)})]}),M&&(0,$.jsxs)(`button`,{type:`button`,className:`dd-current-row`,title:b(`currentModelHint`),onClick:N,children:[(0,$.jsx)(`span`,{className:`dd-current-tag`,children:b(`currentModelLabel`)}),(0,$.jsx)(`span`,{className:`dd-current-name`,children:M.modelName}),(0,$.jsx)(`span`,{className:`dd-current-provider`,title:M.provider,children:M.providerLabel}),M.keyName&&(0,$.jsx)(`span`,{className:`dd-current-key`,children:M.keyName})]}),(0,$.jsxs)(`div`,{className:`dd-model-body`,style:v,children:[R.length>1&&(0,$.jsxs)(`div`,{className:`dd-provider-col`,children:[(0,$.jsx)(`div`,{className:`dd-provider-head`,children:b(`providers`)}),(0,$.jsx)(`button`,{type:`button`,className:`dd-provider-item ${C===null?`active`:``}`,onClick:()=>w(null),children:(0,$.jsx)(`span`,{children:b(`allProviders`)})}),R.map(e=>{let t=C?.provider===e.provider&&C?.keyName===e.keyName;return(0,$.jsxs)(`button`,{type:`button`,className:`dd-provider-item ${t?`active`:``}`,onClick:()=>w(t?null:{provider:e.provider,keyName:e.keyName}),title:e.keyName?`${cf(e.provider,r)} (${e.provider}) · ${e.keyName}`:`${cf(e.provider,r)} (${e.provider}) · ${e.count}`,children:[(0,$.jsxs)(`span`,{className:`dd-provider-txt`,children:[(0,$.jsx)(`span`,{className:`dd-provider-name`,children:cf(e.provider,r)}),e.keyName&&(0,$.jsx)(`span`,{className:`dd-provider-key`,children:e.keyName})]}),(0,$.jsx)(`span`,{className:`dd-provider-count`,children:e.count})]},e.keyName?`${e.provider}::${e.keyName}`:e.provider)})]}),(0,$.jsxs)(`div`,{className:`dd-model-scroll`,ref:j,style:y,children:[(c||t)&&(0,$.jsx)(`div`,{className:`dd-loading`,children:b(`loading`)}),e.length===0&&!c&&!t&&(0,$.jsx)(`div`,{className:`dd-loading`,children:b(`noModels`)}),m,L.length===0&&I.length>0&&(0,$.jsxs)(`div`,{className:`dd-loading`,children:[(0,$.jsx)(`div`,{children:b(`noModelMatches`)}),F&&!D&&(0,$.jsx)(`button`,{type:`button`,className:`dd-scope-switch-link`,onClick:()=>O(!0),children:b(`searchAllModelsHint`,{n:e.length})})]}),z.map(e=>{let t=e.model,n=i!==void 0&&i===t.id;return(0,$.jsxs)(Qd,{active:e.active,onClick:()=>d(t,e.key),children:[(0,$.jsxs)(`span`,{className:`dd-model-cell`,children:[(0,$.jsxs)(`span`,{className:`dd-model-head`,children:[(0,$.jsx)(`span`,{className:`dd-model-name`,children:t.name}),e.active&&(0,$.jsx)(`span`,{className:`dd-model-current`,children:b(`currentModelBadge`)})]}),(0,$.jsxs)(`span`,{className:`dd-model-meta`,children:[(0,$.jsx)(`span`,{className:`dd-model-provider`,title:t.provider,children:cf(t.provider,r)}),(0,$.jsx)(`span`,{className:`dd-model-id`,children:t.id.includes(`/`)?t.id.split(`/`).slice(1).join(`/`):t.id}),e.key&&(0,$.jsxs)(`span`,{className:`dd-model-key ${e.key.active?`active`:``}`,children:[e.key.active?`●`:`○`,` `,e.key.name]}),(T[t.id]??0)>0&&(0,$.jsx)(`span`,{className:`dd-model-usage`,children:b(`modelUsedCount`,{n:T[t.id]})}),(t.reasoning||t.vision||D&&t.enabled===!1)&&(0,$.jsxs)(`span`,{className:`dd-model-badges`,children:[t.reasoning&&(0,$.jsx)(`span`,{className:`dd-model-badge`,children:b(`reasoning`)}),t.vision&&(0,$.jsx)(`span`,{className:`dd-model-badge`,children:b(`vision`)}),D&&t.enabled===!1&&(0,$.jsx)(`span`,{className:`dd-model-badge out-of-scope`,children:b(`notInScopeBadge`)})]})]})]}),B&&(f?(0,$.jsx)(`button`,{type:`button`,className:`dd-star-btn ${n?`active`:``}`,title:b(n?`cancelDefaultTooltip`:`setDefaultTooltip`),onClick:e=>{e.stopPropagation(),f(t,n)},children:n?`★`:`☆`}):(0,$.jsx)(`span`,{className:`dd-star-btn ${n?`active`:``}`,children:n?`★`:`☆`}))]},e.key?`${t.id}::${e.key.name}`:t.id)})]})]})]})}function ff({title:e,entries:t,selected:n,onChange:r,disabled:i,pending:a}){let o=X(),s=(0,Q.useId)(),[c,l]=(0,Q.useState)(``),u=new Set(t.map(e=>e.id)),d=n.filter(e=>!u.has(e)),f=[...t,...d.map(e=>({id:e,name:e}))],p=c.trim().toLowerCase(),m=f.filter(e=>[e.name,e.id,e.description,e.path].some(e=>e?.toLowerCase().includes(p))),h=m.filter(e=>u.has(e.id)&&e.status!==`disabled`);return(0,$.jsxs)(`fieldset`,{className:`dc-bot-catalog`,disabled:i,children:[(0,$.jsxs)(`legend`,{children:[e,` `,(0,$.jsxs)(`span`,{className:`dc-bot-count`,children:[n.length,` `,o(`localBotSelected`)]})]}),(0,$.jsxs)(`div`,{className:`dc-bot-catalog-actions`,children:[(0,$.jsx)(`input`,{type:`search`,"aria-label":`${o(`localBotSearch`)} ${e}`,placeholder:o(`localBotSearch`),value:c,onChange:e=>l(e.target.value)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:a||!h.length,onClick:()=>r([...new Set([...n,...h.map(e=>e.id)])]),children:o(p?`localBotSelectVisible`:`localBotSelectAll`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:!n.length,onClick:()=>r([]),children:o(`localBotClear`)})]}),(0,$.jsxs)(`div`,{className:`dc-bot-catalog-list`,children:[m.map((e,t)=>(0,$.jsxs)(`label`,{className:`dc-bot-option${n.includes(e.id)?` is-selected`:``}`,htmlFor:`${s}-${t}`,children:[(0,$.jsx)(`input`,{id:`${s}-${t}`,type:`checkbox`,checked:n.includes(e.id),disabled:e.status===`disabled`&&!n.includes(e.id),onChange:t=>r(t.target.checked?[...new Set([...n,e.id])]:n.filter(t=>t!==e.id))}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.name}),e.warning===`high_privilege`&&(0,$.jsx)(`small`,{children:o(`localBotToolHighPrivilege`)}),e.warning===`unsupported_platform`&&(0,$.jsx)(`small`,{children:o(`localBotToolUnsupportedPlatform`)}),!u.has(e.id)&&(0,$.jsx)(`small`,{children:o(a?`localBotUnverified`:`localBotUnavailable`)}),e.description&&(0,$.jsx)(`small`,{className:`dc-bot-option-description`,title:e.description,children:e.description}),e.status===`not_loaded`&&(0,$.jsx)(`small`,{children:o(`localBotMcpNotLoaded`)}),e.status===`disabled`&&(0,$.jsx)(`small`,{children:o(`localBotMcpDisabled`)}),e.source&&e.source!==`builtin`&&(0,$.jsx)(`small`,{className:`dc-bot-option-source`,children:e.source}),e.path&&(0,$.jsx)(`small`,{className:`dc-bot-option-path`,title:e.path,children:e.path})]})]},e.id)),!m.length&&(0,$.jsx)(`p`,{children:o(a?`localBotOptionsLoading`:`localBotNoOptions`)})]})]})}var pf=e=>e.id.startsWith(`${e.provider}/`)?e.id.slice(e.provider.length+1):e.id;function mf(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{if(!e)return;let t=new AbortController;return i(!0),o(``),un(`/api/device-center/local-bot-options`,{method:`GET`,credentials:`same-origin`,signal:t.signal}).then(async e=>{let t=await e.json();if(!e.ok)throw Error(t.error||String(e.status));return t}).then(e=>{t.signal.aborted||(n(e),i(!1))}).catch(e=>{t.signal.aborted||(o(e instanceof Error?e.message:String(e)),i(!1))}),()=>t.abort()},[e,s]),{options:t,loading:r,error:a,reload:(0,Q.useCallback)(()=>c(e=>e+1),[])}}var hf=[`soul`,`context`,`tools`,`markers`,`skills`,`cwd`,`append`,`plugin_dev`,`execution`,`memory`],gf=new Set([`soul`,`context`,`markers`,`append`,`plugin_dev`]),_f=[`soul`,`context`,`tools`,`skills`,`cwd`,`append`,`execution`,`memory`],vf=[`tools`,`skills`,`cwd`,`memory`];function yf(e){return Array.isArray(e.promptSections)?e.promptSections:e.useGlobalPrompt===!1?[...vf]:[..._f]}function bf({value:e,onChange:t,options:n,optionsLoading:r,optionsError:i,onReloadOptions:a,busy:o=!1,baseCwd:s=``,variant:c=`dialog`,modelPortalTarget:l,modelOpen:u,onModelOpenChange:d,dialogChrome:f}){let p=X(),m=(0,Q.useId)(),[h,g]=(0,Q.useState)(`identity`),[_,v]=(0,Q.useState)(`tools`),[y,b]=(0,Q.useState)(!1),x=u??y,S=(0,Q.useCallback)(e=>{d?d(e):b(e)},[d]),C=(0,Q.useRef)(s||e.cwd);s&&(C.current=s);let[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(``),{copied:A,copy:j}=Gn({duration:1500}),M=yf(e);(0,Q.useEffect)(()=>{if(h!==`identity`)return;let t=new AbortController,n=setTimeout(()=>{D(!0),k(``),ln(`/api/device-center/local-bot-prompt-preview`,{body:{id:e.id,systemPrompt:e.systemPrompt,cwd:e.cwd,tools:e.tools,skills:e.skills,promptSections:e.promptSections,useGlobalPrompt:e.useGlobalPrompt},signal:t.signal}).then(e=>{t.signal.aborted||(T(e),D(!1))}).catch(e=>{t.signal.aborted||(k(e instanceof Error?e.message:String(e)),D(!1))})},220);return()=>{clearTimeout(n),t.abort()}},[h,e.id,e.systemPrompt,e.cwd,e.tools,e.skills,e.promptSections,e.useGlobalPrompt]);let N=(0,Q.useCallback)(n=>{let r=n.some(e=>gf.has(e));t({...e,promptSections:n,useGlobalPrompt:r})},[t,e]);Lt(()=>S(!1),x);let P=n?.models.find(t=>t.provider===e.model?.provider&&pf(t)===e.model?.modelId),F=c===`inline`,I=!F&&!!f,L=F?m:`bot`,R=F?`${m}-cwd`:`local-bot-cwd`,z=F?5:3,B=[[`identity`,p(`localBotIdentity`),void 0],[`runtime`,p(`localBotRuntime`),void 0],[`permissions`,p(`localBotPermissions`),e.tools.length+e.skills.length+e.mcpServers.length]],V=(0,$.jsx)(`div`,{className:I?`dc-bot-b-nav`:F?`bot-form-tabs`:`dc-bot-tabs`,role:`tablist`,"aria-label":p(`localBotTitle`),children:B.map(([e,t,n],r,i)=>(0,$.jsxs)(`button`,{type:`button`,role:`tab`,id:`${L}-tab-${e}`,"aria-controls":`${L}-panel-${e}`,"aria-selected":h===e,tabIndex:h===e?0:-1,onClick:()=>g(e),onKeyDown:e=>{let t=r;if(e.key===`ArrowRight`||I&&e.key===`ArrowDown`)t=(r+1)%i.length;else if(e.key===`ArrowLeft`||I&&e.key===`ArrowUp`)t=(r+i.length-1)%i.length;else if(e.key===`Home`)t=0;else if(e.key===`End`)t=i.length-1;else return;e.preventDefault(),g(i[t][0]),document.getElementById(`${L}-tab-${i[t][0]}`)?.focus()},children:[(0,$.jsx)(`span`,{children:t}),n!==void 0&&n>0&&(0,$.jsx)(`span`,{style:{fontSize:`11px`,opacity:.65},children:n})]},e))}),H=B.find(([e])=>e===h)?.[1]??p(`localBotIdentity`),ee=(0,$.jsxs)(`div`,{className:F?`bot-form-body`:void 0,children:[(0,$.jsx)(`div`,{role:`tabpanel`,id:`${L}-panel-identity`,"aria-labelledby":`${L}-tab-identity`,hidden:h!==`identity`,children:(0,$.jsxs)(`div`,{className:F?`bot-form-stack`:`dc-bot-section`,style:F?void 0:{gap:`12px`},children:[(0,$.jsxs)(`div`,{className:F?void 0:`dc-bot-row-2`,children:[(0,$.jsxs)(`label`,{className:F?`bot-form-field`:`dc-field`,children:[(0,$.jsx)(`span`,{children:p(`localBotName`)}),(0,$.jsx)(`input`,{required:!0,disabled:o,value:e.name,onChange:n=>t({...e,name:n.target.value})})]}),(0,$.jsxs)(`label`,{className:F?`bot-form-field`:`dc-field`,children:[(0,$.jsx)(`span`,{children:p(`localBotDescription`)}),(0,$.jsx)(`textarea`,{rows:F?2:1,disabled:o,value:e.description,onChange:n=>t({...e,description:n.target.value}),style:F?void 0:{minHeight:`36px`,resize:`none`}})]})]}),(0,$.jsxs)(`label`,{className:F?`bot-form-field`:`dc-field`,children:[(0,$.jsx)(`span`,{children:p(`localBotSystemPrompt`)}),(0,$.jsx)(`textarea`,{rows:z,className:F?`bot-form-prompt`:`dc-bot-prompt`,spellCheck:!1,disabled:o,value:e.systemPrompt,onChange:n=>t({...e,systemPrompt:n.target.value})})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:`6px`},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`8px`,flexWrap:`wrap`},children:[(0,$.jsx)(`span`,{style:{fontSize:`12px`,fontWeight:500,color:`var(--text-dim)`},children:p(`localBotPromptComposition`)}),(0,$.jsxs)(`div`,{style:{display:`inline-flex`,gap:`4px`,flexWrap:`wrap`},children:[(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,style:{padding:`3px 8px`,fontSize:`11px`},disabled:o,onClick:()=>N([...hf]),children:p(`localBotSelectAll`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,style:{padding:`3px 8px`,fontSize:`11px`},disabled:o,onClick:()=>N([]),children:p(`localBotPromptPureOnly`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,style:{padding:`3px 8px`,fontSize:`11px`},disabled:o,onClick:()=>N([..._f]),children:p(`localBotPromptResetDefault`)})]})]}),(0,$.jsx)(`div`,{className:`dc-bot-chips`,children:hf.map(e=>{let t=M.includes(e),n=w?.sections.find(t=>t.id===e),r=`promptTok_${e}`,i=`promptTok_${e}_desc`;return(0,$.jsxs)(`label`,{className:`dc-bot-chip${t?` is-on`:``}`,title:p(i),children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:o,checked:t,onChange:t=>{let n=t.target.checked?[...M,e]:M.filter(t=>t!==e);N(n)}}),(0,$.jsx)(`span`,{children:p(r)}),n&&(0,$.jsx)(`span`,{className:`tok dc-bot-chip-tok`,children:n.tokens})]},e)})})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:`6px`},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`8px`},children:[(0,$.jsxs)(`span`,{style:{fontSize:`12px`,fontWeight:500,color:`var(--text-dim)`},children:[p(`localBotPromptFullPreview`),w?` (≈${w.totalTokens} tokens)`:``]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,style:{padding:`3px 8px`,fontSize:`11px`},disabled:!w?.full,onClick:()=>{w?.full&&j(w.full)},children:p(A?`localBotPromptCopied`:`localBotPromptCopy`)})]}),O&&(0,$.jsx)(`small`,{role:`alert`,style:{color:`var(--err-text, #e5534b)`},children:O}),(0,$.jsx)(`textarea`,{readOnly:!0,rows:F?5:4,className:F?`bot-form-prompt`:`dc-bot-prompt`,spellCheck:!1,value:E&&!w?p(`localBotPromptPreviewLoading`):w?.full??``,style:{width:`100%`,minHeight:F?void 0:`88px`,opacity:E?.75:1,fontFamily:`var(--mono)`,fontSize:`11.5px`,lineHeight:1.5,padding:`8px 10px`,background:`var(--bg-elev)`,border:`1px solid var(--border)`,borderRadius:`7px`,color:`var(--text)`}})]})]})}),(0,$.jsx)(`div`,{role:`tabpanel`,id:`${L}-panel-runtime`,"aria-labelledby":`${L}-tab-runtime`,hidden:h!==`runtime`,children:(0,$.jsxs)(`div`,{className:F?`bot-form-stack`:`dc-bot-section`,children:[(0,$.jsxs)(`div`,{className:F?`bot-form-field`:`dc-field`,children:[(0,$.jsx)(`label`,{htmlFor:R,children:p(`localBotCwd`)}),(0,$.jsx)(Jd,{inputId:R,commitOnBlur:!0,cwd:e.cwd,baseCwd:C.current||e.cwd,projects:n?.projects.map(e=>({...e,lastUsed:0}))??[],disabled:o,onSelectCwd:n=>t({...e,cwd:Kd(n,C.current||e.cwd)})})]}),(0,$.jsxs)(`div`,{className:F?`bot-form-field`:`dc-field`,children:[(0,$.jsx)(`span`,{children:p(`localBotModel`)}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:o,"aria-haspopup":`dialog`,onClick:()=>S(!0),children:e.model?P?.name??`${e.model.provider}/${e.model.modelId}`:p(`localBotInheritModel`)}),e.model&&(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:o,onClick:()=>t({...e,model:void 0}),children:p(`localBotInheritModel`)})]}),e.model&&!P&&(0,$.jsx)(`small`,{children:p(r?`localBotUnverified`:`localBotUnavailable`)})]})]})}),(0,$.jsxs)(`div`,{role:`tabpanel`,id:`${L}-panel-permissions`,"aria-labelledby":`${L}-tab-permissions`,hidden:h!==`permissions`,children:[(0,$.jsxs)(`div`,{className:`dc-bot-options-status`,"aria-live":`polite`,children:[r&&(0,$.jsx)(`span`,{children:p(`localBotOptionsLoading`)}),i&&(0,$.jsx)(`span`,{role:`alert`,children:i}),(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:r||o,onClick:a,children:p(i?`deviceHubRetry`:`localBotReload`)})]}),(0,$.jsx)(`div`,{className:`dc-bot-catalog-tabs`,role:`tablist`,"aria-label":p(`localBotPermissions`),children:[[`tools`,p(`localBotTools`)],[`skills`,p(`localBotSkills`)],[`mcpServers`,p(`localBotMcpServers`)]].map(([t,n])=>(0,$.jsxs)(`button`,{type:`button`,role:`tab`,id:`${m}-catalog-tab-${t}`,"aria-controls":`${m}-catalog-${t}`,"aria-selected":_===t,onClick:()=>v(t),children:[n,(0,$.jsx)(`span`,{children:e[t].length})]},t))}),(0,$.jsx)(`div`,{className:`dc-bot-permissions`,children:[[`tools`,p(`localBotTools`)],[`skills`,p(`localBotSkills`)],[`mcpServers`,p(`localBotMcpServers`)]].map(([a,s])=>(0,$.jsx)(`div`,{role:`tabpanel`,id:`${m}-catalog-${a}`,"aria-labelledby":`${m}-catalog-tab-${a}`,hidden:_!==a,children:(0,$.jsx)(ff,{title:s,entries:n?.[a]??[],selected:e[a],disabled:o,pending:r||!!i,onChange:n=>t({...e,[a]:n})})},a))})]})]});return(0,$.jsxs)($.Fragment,{children:[I&&f?(0,$.jsxs)(`div`,{className:`dc-bot-b-shell`,children:[(0,$.jsxs)(`aside`,{className:`dc-bot-b-rail`,children:[f.railHeader,V,f.railFooter]}),(0,$.jsxs)(`div`,{className:`dc-bot-b-main`,children:[(0,$.jsxs)(`header`,{className:`dc-bot-b-head`,children:[(0,$.jsx)(`strong`,{children:H}),f.closeButton]}),(0,$.jsxs)(`div`,{className:`dc-bot-b-body`,children:[f.errorBanner,ee]}),(0,$.jsx)(`footer`,{className:`dc-actions dc-bot-b-foot`,children:f.footer})]})]}):(0,$.jsxs)(`div`,{className:`bot-form${F?` is-inline`:``}`,children:[V,ee]}),x&&(0,Er.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop dc-bot-model-backdrop`,onClick:e=>{e.target===e.currentTarget&&S(!1)},children:(0,$.jsxs)(`div`,{className:`dc-bot-model-modal dd-menu-model`,role:`dialog`,"aria-modal":`true`,"aria-label":p(`localBotModel`),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsx)(`h3`,{children:p(`localBotModel`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>S(!1),children:p(`localBotCancel`)})]}),(0,$.jsx)(df,{models:n?.models??[],modelsLoading:r,defaultModel:n?.defaultModel,currentModelId:e.model?`${e.model.provider}/${e.model.modelId}`:null,active:!0,onEnsureModels:()=>{},onRefresh:a,onPickModel:n=>{t({...e,model:{provider:n.provider,modelId:pf(n)}}),S(!1)},isRowActive:t=>t.provider===e.model?.provider&&pf(t)===e.model.modelId,extraTopRow:(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>{t({...e,model:void 0}),S(!1)},children:p(`localBotInheritModel`)}),autoFocusSearch:!0,hideTitle:!0,bodyStyle:{flex:1,minHeight:0},scrollStyle:{overflowY:`auto`,minHeight:0}}),i&&(0,$.jsx)(`p`,{role:`alert`,children:i})]})}),l??document.body)]})}var xf=(e=``)=>({name:``,description:``,systemPrompt:``,useGlobalPrompt:!0,cwd:e,tools:[],skills:[],mcpServers:[],enabled:!0});async function Sf(e,t,n){let r=await fetch(W(j(`/api/device-center/${e}`)),{method:n?`POST`:`GET`,credentials:`same-origin`,signal:t,...n?{headers:{"Content-Type":`application/json`},body:JSON.stringify(n)}:{}}),i=await r.json();if(!r.ok)throw Error(i.error||String(r.status));return i}function Cf({createOnly:e=!1,initialCwd:t,editBot:n,onCreated:r,onFinished:i,onCancel:a}){let o=X(),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(()=>n?structuredClone(n):e?xf(t??``):null),p=()=>{f(null),a?.()},[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(0),[O,k]=(0,Q.useState)(!1),[A,j]=(0,Q.useState)(!1),M=(0,Q.useRef)(null),N=(0,Q.useRef)(null),P=e,F=(0,Q.useRef)(``),I=(0,Q.useRef)(null),L=d!==null,R=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{if(R.current=!1,!L)return;let e=I.current,t=document.activeElement,n=document.body.style.overflow;return document.body.style.overflow=`hidden`,e?.showModal?.(),()=>{e?.close?.(),document.body.style.overflow=n,t?.focus()}},[L]),(0,Q.useEffect)(()=>{if(P)return;let e=new AbortController;return Sf(`local-bots`,e.signal).then(t=>{if(!e.signal.aborted){if(!Array.isArray(t.bots))throw Error(`Invalid Bot list`);c(t.bots)}}).catch(t=>{e.signal.aborted||_(String(t))}),()=>e.abort()},[P]),(0,Q.useEffect)(()=>()=>N.current?.abort(),[]);let z=async e=>{j(!0),_(``);try{let t=await Gd(e);y(o(`agentBotsImportReceipt`,{name:t.name,imported:t.imported,skipped:t.skipped})),D(e=>e+1),Sf(`local-bots`,new AbortController().signal).then(e=>{Array.isArray(e.bots)&&c(e.bots)}).catch(()=>{})}catch(e){_(e instanceof Error?e.message:o(`localBotImportFailed`))}finally{j(!1)}},B=d?.cwd;(0,Q.useEffect)(()=>{if(B===void 0)return;let e=new AbortController;return T(!0),C(``),x(null),Sf(B?`local-bot-options?cwd=${encodeURIComponent(B)}`:`local-bot-options`,e.signal).then(t=>{if(e.signal.aborted)return;if(![t.models,t.tools,t.skills,t.mcpServers,t.projects].every(Array.isArray)||!t.defaultCwd||!t.cwd)throw Error(o(`localBotOptionsInvalid`));F.current=t.defaultCwd,x(t);let n=!R.current;R.current=!0,f(e=>e&&{...e,...e.cwd?{}:{cwd:t.cwd},...n&&!e.id?{tools:[...t.defaultTools??[]]}:{}})}).catch(t=>{e.signal.aborted||C(String(t))}).finally(()=>{e.signal.aborted||T(!1)}),()=>e.abort()},[B,E]);async function V(e=!1){if(!d||m)return;let t=new AbortController;N.current=t,h(!0),_(``),y(``);try{let n=await Sf(e?`local-bots/${encodeURIComponent(d.id)}/delete`:`local-bots`,t.signal,e?{revision:d.revision}:d);if(t.signal.aborted)return;c(t=>e?t.filter(e=>e.id!==d.id):[...t.filter(e=>e.id!==n.bot.id),n.bot]),f(null),k(!1),y(n.synced===!1?o(`localBotSyncFailed`):o(`localBotSaved`)),e||r?.(n.bot,n.synced!==!1),i?.(),window.dispatchEvent(new CustomEvent(`pi-web-ui:device-bots-changed`))}catch(e){t.signal.aborted||_(e instanceof Error?e.message:String(e))}finally{t.signal.aborted||h(!1)}}async function H(e){if(!l){u(e),_(``);try{cd(e)}catch(e){_(e instanceof Error?e.message:String(e))}finally{u(null)}}}return(0,$.jsxs)(`section`,{className:`dc-card dc-bots${P?` is-solo`:``}`,"aria-label":o(`localBotTitle`),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsx)(`h2`,{children:o(`localBotTitle`)}),(0,$.jsxs)(`div`,{className:`dc-bots-actions`,children:[(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:m,onClick:()=>{f(xf()),_(``),k(!1)},children:o(`localBotCreate`)}),(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:m||A,title:o(`localBotImportTip`),onClick:()=>M.current?.click(),children:o(A?`localBotImporting`:`localBotImport`)}),(0,$.jsx)(`input`,{ref:M,type:`file`,accept:`application/json,.json`,hidden:!0,onChange:e=>{let t=e.target.files?.[0];e.target.value=``,t&&z(t)}})]})]}),(0,$.jsx)(`p`,{children:o(`localBotHint`)}),g&&!d&&(0,$.jsx)(`p`,{role:`alert`,children:g}),v&&(0,$.jsx)(`p`,{role:`status`,children:v}),(0,$.jsxs)(`div`,{className:`dc-bot-workspace${d?` is-editing`:``}`,children:[(0,$.jsx)(`div`,{className:`dc-bot-list`,"aria-label":o(`localBotTitle`),children:s.map(e=>(0,$.jsxs)(`div`,{className:`dc-bot-entry`,children:[(0,$.jsxs)(`button`,{className:`dc-button dc-bot-item${d?.id===e.id?` is-selected`:``}`,"aria-pressed":d?.id===e.id,disabled:m,onClick:()=>{f(structuredClone(e)),_(``),k(!1)},children:[(0,$.jsx)(`span`,{className:`dc-bot-avatar`,"aria-hidden":`true`,children:e.name.slice(0,2).toUpperCase()}),(0,$.jsxs)(`span`,{className:`dc-bot-item-copy`,children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsxs)(`small`,{className:e.enabled?`is-enabled`:``,children:[e.enabled?o(`localBotEnabled`):o(`localBotDisabled`),` · r`,e.revision]}),e.cwd.startsWith(`ssh://`)&&(0,$.jsx)(`small`,{title:e.cwd,children:o(`nativeCliRemoteLocation`,{host:e.cwd.replace(/^ssh:\/\/([^@]+)@([^:/]+).*$/,`$1@$2`)})})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-bot-chat`,title:o(`botChat`,{name:e.name}),"aria-label":o(`botChat`,{name:e.name}),disabled:m||l!==null,onClick:()=>void H(e.id),children:l===e.id?`…`:o(`botChatShort`)})]},e.id))}),d&&(0,$.jsx)(`dialog`,{ref:I,className:`dc-bot-drawer`,"aria-label":o(`localBotTitle`),onCancel:e=>{e.preventDefault(),!m&&!O&&p()},onClick:e=>{if(e.target!==e.currentTarget||m)return;let t=e.currentTarget.getBoundingClientRect();(e.clientX<t.left||e.clientX>t.right||e.clientY<t.top||e.clientY>t.bottom)&&p()},children:(0,$.jsx)(`form`,{className:`dc-bot-editor`,onSubmit:e=>{e.preventDefault(),V()},children:(0,$.jsx)(bf,{variant:`dialog`,value:d,onChange:e=>f({...d,...e}),options:b,optionsLoading:w,optionsError:S,onReloadOptions:()=>D(e=>e+1),busy:m,baseCwd:F.current||d.cwd,modelPortalTarget:I.current??document.body,modelOpen:O,onModelOpenChange:k,dialogChrome:{railHeader:(0,$.jsxs)(`div`,{className:`dc-bot-b-badge`,children:[(0,$.jsx)(`span`,{className:`dc-bot-avatar`,"aria-hidden":`true`,children:d.name.slice(0,2).toUpperCase()||`B`}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`h3`,{children:d.name||o(`localBotCreate`)}),d.id&&(0,$.jsxs)(`small`,{children:[d.id,` · r`,d.revision]})]})]}),railFooter:(0,$.jsxs)(`div`,{className:`dc-bot-b-rail-foot`,children:[(0,$.jsxs)(`label`,{className:`dc-bot-enabled`,children:[(0,$.jsx)(`input`,{type:`checkbox`,role:`switch`,disabled:m,checked:d.enabled,onChange:e=>f({...d,enabled:e.target.checked})}),o(`localBotEnable`)]}),d.id&&(0,$.jsx)(`button`,{className:`dc-button is-danger`,type:`button`,style:{width:`100%`},disabled:m,onClick:()=>{window.confirm(o(`localBotDeleteConfirm`))&&V(!0)},children:o(`localBotDelete`)})]}),closeButton:(0,$.jsx)(`button`,{className:`dc-button dc-bot-drawer-close`,type:`button`,"aria-label":o(`localBotCancel`),disabled:m,onClick:p,children:`×`}),errorBanner:g?(0,$.jsx)(`p`,{className:`dc-bot-error`,role:`alert`,children:g}):void 0,footer:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{className:`dc-button`,type:`button`,disabled:m,onClick:()=>{p(),k(!1)},children:o(`localBotCancel`)}),(0,$.jsx)(`button`,{className:`dc-button dc-bot-save`,disabled:m||!d.cwd||!d.name.trim(),children:o(`localBotSave`)})]})}})})})]})]})}function wf({room:e,onClose:t}){let n=X(),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(e.botIds),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(!0),[p,m]=(0,Q.useState)(!1),[h,g]=(0,Q.useState)(``),[_,v]=(0,Q.useState)(0),y=(0,Q.useRef)(null),b=()=>{!p&&!l&&t()};Lt(b),(0,Q.useEffect)(()=>()=>y.current?.abort(),[]),(0,Q.useEffect)(()=>{let t=new AbortController;return f(!0),Promise.all([wp(`bots`,t.signal),wp(`rooms/${encodeURIComponent(e.id)}`,t.signal)]).then(([e,n])=>{t.signal.aborted||(i(e.bots),o(n.room.botIds))}).catch(e=>{t.signal.aborted||g(e instanceof Error?e.message:String(e))}).finally(()=>{t.signal.aborted||f(!1)}),()=>t.abort()},[e.id,_]);async function x(n){if(y.current)return;let r=new AbortController;y.current=r,m(!0),g(``);try{let i=`rooms/${encodeURIComponent(e.id)}`,a=await wp(i,r.signal);if(r.signal.aborted||(await wp(`${i}/members`,r.signal,{botIds:[...new Set([...a.room.botIds,...n])]}),r.signal.aborted))return;window.dispatchEvent(new CustomEvent(gp)),t()}catch(e){r.signal.aborted||g(e instanceof Error?e.message:String(e))}finally{y.current=null,r.signal.aborted||m(!1)}}return(0,Er.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:b,children:(0,$.jsxs)(`div`,{className:`device-group-bot-dialog`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`deviceGroupSectionAddOrCreateBot`),onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`dg-heading`,children:[(0,$.jsxs)(`h2`,{children:[n(`deviceGroupSectionAddBot`),` · `,e.name]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:p||l,onClick:b,children:n(`close`)})]}),h&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:h}),(0,$.jsx)(`p`,{children:n(`deviceGroupBotDialogLead`)}),d?(0,$.jsx)(`p`,{children:n(`loading`)}):(0,$.jsxs)(`div`,{className:`dg-bot-choices`,children:[r.filter(e=>e.enabled&&!a.includes(e.id)).map(e=>(0,$.jsxs)(`label`,{className:`dg-bot-choice`,children:[(0,$.jsx)(`input`,{type:`checkbox`,disabled:p||l,checked:s.includes(e.id),onChange:t=>c(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id))}),(0,$.jsxs)(`span`,{children:[e.name,e.deviceName&&(0,$.jsx)(`small`,{children:e.deviceName})]})]},e.id)),!r.some(e=>e.enabled&&!a.includes(e.id))&&(0,$.jsx)(`p`,{children:n(`deviceGroupBotDialogEmpty`)})]}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:p||l,onClick:()=>{u(!0),g(``)},children:n(`deviceGroupsCreateBot`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:d||p||l||!s.length,onClick:()=>void x(s),children:n(p?`deviceGroupBotDialogAdding`:`deviceGroupBotDialogAddToGroup`)})]}),l&&(0,$.jsx)(Cf,{createOnly:!0,onCancel:()=>u(!1),onCreated:(e,t)=>{u(!1),v(e=>e+1),!t||!e.enabled?g(n(`deviceGroupBotDialogSaved`)):x([e.id])}})]})}),document.body)}var Tf=`pi-web-ui:device-groups-changed`;async function Ef(e,t,n){return ln(`/api/device-center/${e}`,{body:n,signal:AbortSignal.any([t,AbortSignal.timeout(15e3)]),errorFor:e=>new dn(e.status,e.error,e.code)})}function Df({roomId:e,onClose:t,onSaved:n}){let r=X();Lt(t);let[i,a]=(0,Q.useState)(!0),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)([]),[u,d]=(0,Q.useState)(new Set),[f,p]=(0,Q.useState)(!1),[m,h]=(0,Q.useState)(`local`),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(``),[b,x]=(0,Q.useState)([]),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(!1),E=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{let t=++E.current,n=new AbortController,r=()=>E.current===t&&!n.signal.aborted;return(async()=>{try{let[t,i]=await Promise.all([Ef(`bots`,n.signal).catch(()=>({bots:[]})),Ef(`shared-bots`,n.signal).then(e=>({...e,ok:!0})).catch(()=>({bots:[],ok:!1}))]);if(!r())return;let a=Array.isArray(t.bots)?t.bots:[],o=Array.isArray(i.bots)?i.bots:[];p(!!i.ok&&o.length>0),d(new Set(a.map(e=>e.id)));let c=new Map;for(let e of a)c.set(e.id,e);for(let e of o)c.has(e.id)||c.set(e.id,e);l([...c.values()]);let u=null,f=`local`;try{u=(await Ef(`rooms/${encodeURIComponent(e)}`,n.signal)).room,f=`local`}catch(t){if(t.status!==404)throw t;u=(await Ef(`shared-rooms/${encodeURIComponent(e)}`,n.signal)).room,f=`shared`}if(!r()||!u)return;h(u.scope===`shared`?`shared`:f),_(!!u.router?.enabled),y(u.name??``),x([...u.botIds??[]]),C(u.primaryBotId??``),s(``)}catch(e){r()&&s(e instanceof Error?e.message:String(e))}finally{r()&&a(!1)}})(),()=>{n.abort()}},[e]);let D=b.every(e=>u.has(e))?`local`:`shared`,O=!i&&!o&&D!==m;async function k(){if(w||i)return;let a=v.trim();if(!a||b.length===0)return;if(D===`shared`&&!f&&m!==`shared`){s(r(`deviceGroupManagerNoBots`));return}T(!0),s(``);let o=new AbortController;try{let i=D===`shared`?`shared-rooms`:`rooms`;if(D===m){a&&await Ef(`${i}/${encodeURIComponent(e)}/rename`,o.signal,{name:a});let r=(await Ef(`${i}/${encodeURIComponent(e)}/members`,o.signal,{botIds:b,primaryBotId:b.includes(S)?S:null})).room?.id??e;window.dispatchEvent(new CustomEvent(Tf)),n?.(r),t()}else{let s=(await Ef(i,o.signal,{name:a,botIds:b,...b.includes(S)?{primaryBotId:S}:{}})).room?.id;if(!s)throw Error(r(`deviceGroupsFailed`));await Ef(`${m===`shared`?`shared-rooms`:`rooms`}/${encodeURIComponent(e)}/delete`,o.signal,{}),window.dispatchEvent(new CustomEvent(Tf)),n?.(s),t()}}catch(e){o.signal.aborted||s(e instanceof Error?e.message:String(e))}finally{T(!1)}}return(0,Er.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>!w&&t(),children:(0,$.jsxs)(`div`,{className:`dc-card device-group-create-dialog`,role:`dialog`,"aria-modal":`true`,"aria-label":`${r(`edit`)} · ${v||e}`,onClick:e=>e.stopPropagation(),style:{minWidth:`min(480px, 92vw)`},children:[(0,$.jsxs)(`div`,{className:`dg-heading`,style:{marginBottom:`12px`},children:[(0,$.jsxs)(`h3`,{children:[r(`edit`),` · `,v||e,m===`shared`?` · ${r(`deviceGroupManagerSharedSuffix`)}`:``]}),(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,onClick:t,disabled:w,children:[(0,$.jsx)(Ct,{"aria-hidden":!0}),r(`close`)]})]}),i&&(0,$.jsx)(`p`,{role:`status`,children:r(`loading`)}),o&&(0,$.jsx)(`p`,{className:`dc-error`,role:`alert`,children:o}),!i&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dc-field`,style:{marginBottom:`12px`},children:[(0,$.jsx)(`label`,{htmlFor:`dg-edit-name`,children:r(`deviceGroupManagerNameLabel`)}),(0,$.jsx)(`input`,{id:`dg-edit-name`,type:`text`,maxLength:80,value:v,onChange:e=>y(e.target.value),disabled:w,placeholder:r(`deviceGroupManagerRenamePlaceholder`),style:{width:`100%`,background:`var(--bg-elev)`,border:`1px solid var(--border)`,borderRadius:`6px`,padding:`6px 10px`,color:`var(--text)`,fontSize:`13px`}})]}),(0,$.jsxs)(`div`,{style:{marginBottom:`12px`},children:[(0,$.jsx)(`label`,{style:{display:`block`,marginBottom:`6px`,fontSize:`12px`,color:`var(--text-dim)`},children:r(`deviceGroupManagerSelectMembers`)}),(0,$.jsx)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:`6px`,maxHeight:`220px`,overflowY:`auto`,border:`1px solid var(--border)`,borderRadius:`6px`,padding:`8px`,background:`var(--bg-elev)`},children:c.length===0?(0,$.jsx)(`p`,{style:{margin:0,fontSize:`12px`,color:`var(--text-faint)`},children:r(`deviceGroupManagerNoBots`)}):c.map(e=>(0,$.jsxs)(`label`,{style:{display:`flex`,alignItems:`center`,gap:`8px`,cursor:`pointer`,fontSize:`12px`},children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:b.includes(e.id),disabled:w,onChange:t=>{x(n=>t.target.checked?[...n,e.id]:n.filter(t=>t!==e.id))}}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsxs)(`small`,{style:{color:`var(--text-faint)`,marginInlineStart:`6px`},children:[e.deviceName??(u.has(e.id)?``:e.deviceId??``),e.online===void 0?``:` · ${e.online?r(`deviceHubOnline`):r(`deviceHubOffline`)}`,e.enabled?``:r(`deviceGroupManagerDisabledSuffix`),u.has(e.id)?``:` · ${r(`deviceGroupManagerSharedSuffix`)}`]})]})]},e.id))})]}),!g&&(0,$.jsxs)(`div`,{className:`dc-field`,style:{marginBottom:`16px`},children:[(0,$.jsx)(`label`,{htmlFor:`dg-edit-primary`,children:r(`deviceGroupManagerLegacyPrimary`)}),(0,$.jsxs)(`select`,{id:`dg-edit-primary`,value:b.includes(S)?S:``,onChange:e=>C(e.target.value),disabled:w,style:{width:`100%`,background:`var(--bg-elev)`,border:`1px solid var(--border)`,borderRadius:`6px`,padding:`6px 10px`,color:`var(--text)`,fontSize:`13px`},children:[(0,$.jsx)(`option`,{value:``,children:r(`deviceGroupManagerNoPrimary`)}),c.filter(e=>b.includes(e.id)).map(e=>(0,$.jsx)(`option`,{value:e.id,children:e.name},e.id))]})]}),O&&(0,$.jsx)(`p`,{className:`dc-notice`,role:`status`,children:r(D===`shared`?`deviceGroupManagerMigrateToSharedHint`:`deviceGroupManagerMigrateToLocalHint`)}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`dc-button is-primary`,disabled:w||!v.trim()||b.length===0,onClick:()=>void k(),children:[(0,$.jsx)(z,{"aria-hidden":!0}),r(w?`saving`:`deviceGroupManagerSaveMembers`)]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:t,disabled:w,children:r(`cancel`)})]})]})]})}),document.body)}var Of=null,kf=new Set;function Af(){for(let e of kf)e()}function jf(e){Of={x:Number.isFinite(e.x)?e.x:0,y:Number.isFinite(e.y)?e.y:0,slot:e.slot,target:e.target??{id:``},entries:Array.isArray(e.entries)?e.entries:[],...typeof e.onHostAction==`function`?{onHostAction:e.onHostAction}:{}},Af()}function Mf(){Of!==null&&(Of=null,Af())}function Nf(e){return kf.add(e),()=>{kf.delete(e)}}function Pf(){return Of}function Ff(){return(0,Q.useSyncExternalStore)(Nf,Pf,Pf)}function If(e){return Number.isFinite(e)?e:0}function Lf(e,t,n,r,i,a){let o=Math.max(0,If(n)),s=Math.max(0,If(r)),c=Math.max(8,If(i)-o-8),l=Math.max(8,If(a)-s-8);return{x:Math.min(Math.max(8,If(e)),c),y:Math.min(Math.max(8,If(t)),l)}}function Rf(e,t){let n=String(t?.kind??``);if(e===`contextmenu.file`)return{"file.isDir":n===`dir`||n===`list`&&t?.id!==`@root`,"file.isFile":n===`file`};if(e===`contextmenu.session`)return{"session.isRunning":n===`running`};if(e===`contextmenu.search`)return{"search.isSession":n===`session`,"search.isProject":n===`project`,"search.isFile":n===`file`,"search.isFolder":n===`folder`,"search.isPlugin":n===`plugin`};if(e===`contextmenu.message`){let e=!1;try{let t=window.getSelection?.();e=!!t&&!t.isCollapsed&&t.toString().trim().length>0}catch{e=!1}return{"message.hasSelection":e}}return{}}function zf(e,t){if(!Array.isArray(e)||e.length===0)return!1;for(let n of e){if(typeof n!=`string`||!n)continue;let e=n.trim();if(e===`disabled`||e===`never`)return!0;if(e!==`always`){if(e.startsWith(`!`)){let n=e.slice(1).trim();if(!n)continue;if(!t||t[n]!==!0)return!0}else if(t&&t[e]===!1)return!0}}return!1}function Bf(e,t){return!e||zf(e.when,t)}function Vf(e){let t=new Map;return{items:(Array.isArray(e)?e:[]).map(e=>{if(!e||e.kind!==`select`||!e.options?.length||e.children?.length)return e;let n=e.options.map((t,n)=>({id:`${e.id}#${n}`,slot:e.slot,source:e.source,label:t.label,kind:`action`,order:100,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}));return n.forEach((n,r)=>t.set(n.id,{parent:e,value:e.options[r].value})),{...e,kind:`menu`,children:n}}),selectParents:t}}function Hf(e){if(!Array.isArray(e)||e.length===0)return[];let t=e.filter(e=>e&&e.hidden!==!0),n=t.filter(e=>e.kind!==`divider`),r=new Map,i=new Map;n.forEach((e,t)=>{let n=e.group??``;r.has(n)||r.set(n,t);let a=Number.isFinite(e.order)?e.order:100,o=i.get(n);(o===void 0||a<o)&&i.set(n,a)});let a=[...r.keys()].sort((e,t)=>{let n=i.get(e)??100,a=i.get(t)??100;return n===a?(r.get(e)??0)-(r.get(t)??0):n-a}),o=new Map(a.map((e,t)=>[e,t])),s=new Map;n.forEach((e,t)=>s.set(e,t));let c=[...n].sort((e,t)=>{let n=o.get(e.group??``)??0,r=o.get(t.group??``)??0;if(n!==r)return n-r;let i=Number.isFinite(e.order)?e.order:100,a=Number.isFinite(t.order)?t.order:100;return i===a?(s.get(e)??0)-(s.get(t)??0):i-a}),l=new Map;t.forEach((e,n)=>{if(e.kind!==`divider`)return;let r=t.slice(n+1).find(e=>e.kind!==`divider`);if(!r)return;let i=l.get(r)??[];i.push(e),l.set(r,i)});let u=[];for(let e of c){for(let t of l.get(e)??[])u.push(t);u.push(e)}return u}function Uf(e){let t=[],n=null,r=!1;return e.forEach((e,i)=>{if(!e||e.kind===`divider`){r=!0;return}let a=e.group??``;n!==null&&(r||a!==n)&&t.push({kind:`sep`,key:`sep:${i}`}),t.push({kind:`item`,key:`${e.id}#${i}`,index:i,entry:e}),n=a,r=!1}),t}function Wf(e,t){return!e||e.kind===`divider`||e.hidden===!0?!1:!Bf(e,t)}function Gf(e,t,n,r){let i=Array.isArray(e)?e.length:0;if(i===0)return-1;let a=n>=0?1:-1,o=Number.isFinite(t)?Math.trunc(t):-1;(o<0||o>=i)&&(o=a>0?-1:i);for(let t=0;t<i;t++)if(o=(o+a+i)%i,Wf(e[o],r))return o;return-1}var Kf={menu:`☰`,folder:`📁`,plus:`+`,chat:`💬`,terminal:`▙`,git:`⎇`,search:`🔍`,browser:`🌐`,layers:`🗂`,settings:`⚙`,sound:`🔊`,globe:`🌍`,sun:`☀`,download:`⤓`,github:`⌗`,x:`✕`,upload:`⬆`,copy:`⧉`,cut:`✂`,paste:`📋`,trash:`🗑`,file:`📄`,open:`↗`,refresh:`⟳`,link:`🔗`,edit:`✎`,dot:`●`,info:`ⓘ`,cpu:`▣`,gauge:`▤`,coins:`◉`,database:`▥`,message:`✉`,activity:`〜`,markdown:`📄`,text:`≡`,image:`🖼`,branch:`⚚`,undo:`↺`,pin:`📌`,volume:`🔊`};function qf(e){let t=(e??``).trim();return t?Kf[t.toLowerCase()]||(/[^\p{L}\p{N}\s]/u.test(t)&&t.length<=4?t:``):``}function Jf(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`rect`,attr:{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`},child:[]},{tag:`path`,attr:{d:`M7 11v4a2 2 0 0 0 2 2h4`},child:[]},{tag:`rect`,attr:{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`},child:[]}]})(e)}function Yf(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8`},child:[]},{tag:`path`,attr:{d:`M10 19v-3.96 3.15`},child:[]},{tag:`path`,attr:{d:`M7 19h5`},child:[]},{tag:`rect`,attr:{width:`6`,height:`10`,x:`16`,y:`12`,rx:`2`},child:[]}]})(e)}function Xf(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z`},child:[]},{tag:`path`,attr:{d:`M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1`},child:[]}]})(e)}function Zf(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M10 17H7l-4 4v-7`},child:[]},{tag:`path`,attr:{d:`M14 17h1`},child:[]},{tag:`path`,attr:{d:`M14 3h1`},child:[]},{tag:`path`,attr:{d:`M19 3a2 2 0 0 1 2 2`},child:[]},{tag:`path`,attr:{d:`M21 14v1a2 2 0 0 1-2 2`},child:[]},{tag:`path`,attr:{d:`M21 9v1`},child:[]},{tag:`path`,attr:{d:`M3 9v1`},child:[]},{tag:`path`,attr:{d:`M5 3a2 2 0 0 0-2 2`},child:[]},{tag:`path`,attr:{d:`M9 3h1`},child:[]}]})(e)}function Qf(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`m5 8 6 6`},child:[]},{tag:`path`,attr:{d:`m4 14 6-6 2-3`},child:[]},{tag:`path`,attr:{d:`M2 5h12`},child:[]},{tag:`path`,attr:{d:`M7 2h1`},child:[]},{tag:`path`,attr:{d:`m22 22-5-10-5 10`},child:[]},{tag:`path`,attr:{d:`M14 18h6`},child:[]}]})(e)}function $f(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M20 17a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3.9a2 2 0 0 1-1.69-.9l-.81-1.2a2 2 0 0 0-1.67-.9H8a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2Z`},child:[]},{tag:`path`,attr:{d:`M2 8v11a2 2 0 0 0 2 2h14`},child:[]}]})(e)}function ep(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z`},child:[]}]})(e)}function tp(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z`},child:[]},{tag:`path`,attr:{d:`M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z`},child:[]},{tag:`path`,attr:{d:`M3 5a2 2 0 0 0 2 2h3`},child:[]},{tag:`path`,attr:{d:`M3 3v13a2 2 0 0 0 2 2h3`},child:[]}]})(e)}function np(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{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-1.95 1.5H4a2 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`},child:[]}]})(e)}function rp(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2`},child:[]},{tag:`path`,attr:{d:`M8.5 2h7`},child:[]},{tag:`path`,attr:{d:`M7 16h10`},child:[]}]})(e)}function ip(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`},child:[{tag:`path`,attr:{d:`m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z`},child:[]},{tag:`circle`,attr:{cx:`12`,cy:`12`,r:`10`},child:[]}]})(e)}var ap=new Set([`svg`,`g`,`path`,`circle`,`rect`,`line`,`polyline`,`polygon`,`ellipse`,`use`,`defs`,`clipPath`,`linearGradient`,`radialGradient`,`stop`]),op=new Set(`viewBox.xmlns.d.fill.stroke.stroke-width.stroke-linecap.stroke-linejoin.stroke-dasharray.opacity.x.y.x1.y1.x2.y2.cx.cy.r.rx.ry.width.height.points.offset.stop-color.stop-opacity.fill-opacity.stroke-opacity.stroke-miterlimit.fill-rule.clip-rule.vector-effect.preserveAspectRatio.transform.clip-path.id.href.xlink:href.xmlns:xlink.gradientUnits.gradientTransform`.split(`.`)),sp=new Set([`script`,`style`,`title`,`desc`,`foreignobject`]),cp=new Set([...ap].map(e=>e.toLowerCase())),lp=new Set([...op].map(e=>e.toLowerCase()));function up(e){return cp.has(e.toLowerCase())}function dp(e){return lp.has(e.toLowerCase())}function fp(e){if(typeof e!=`string`)return null;let t=e.trim();if(!t||t.length>8192||!/^<svg[\s>]/.test(t.startsWith(`<?xml`)?t.slice(t.indexOf(`?>`)+2).trimStart():t))return null;if(typeof DOMParser>`u`)return/<script[\s>]/i.test(t)||/\son\w+\s*=/i.test(t)||/javascript\s*:/i.test(t)?null:t;let n=new DOMParser().parseFromString(t,`image/svg+xml`);if(n.querySelector(`parsererror`))return null;let r=n.documentElement;if(r.tagName.toLowerCase()!==`svg`)return null;let i=e=>{for(let t of Array.from(e.children)){let e=t.tagName.toLowerCase();if(!up(e))sp.has(e)?t.remove():(i(t),t.replaceWith(...t.childNodes));else{for(let e of Array.from(t.attributes)){let n=e.name.toLowerCase();(!dp(n)||/^on/i.test(n)||/^(javascript|data|vbscript):/i.test(e.value.trim()))&&t.removeAttribute(e.name)}i(t)}}};for(let e of Array.from(r.attributes)){let t=e.name.toLowerCase();(!dp(t)||/^on/i.test(t))&&r.removeAttribute(e.name)}return i(r),new XMLSerializer().serializeToString(r)}function pp({icon:e,iconSvg:t,className:n}){let r=fp(t);return r?(0,$.jsx)(`span`,{className:n??`plugin-icon-svg`,"aria-hidden":!0,dangerouslySetInnerHTML:{__html:r}}):e?(0,$.jsx)(`span`,{className:n?`${n} plugin-icon-glyph`:`plugin-icon-glyph`,"aria-hidden":!0,children:e}):null}var mp={activity:(0,$.jsx)(Fe,{}),aperture:(0,$.jsx)(Dt,{}),branch:(0,$.jsx)(ot,{}),browser:(0,$.jsx)(Le,{}),command:(0,$.jsx)(v,{}),chat:(0,$.jsx)(C,{}),check:(0,$.jsx)(z,{}),"chevron-up":(0,$.jsx)(a,{}),clock:(0,$.jsx)(re,{}),code:(0,$.jsx)(Y,{}),coins:(0,$.jsx)(Oe,{}),copy:(0,$.jsx)(st,{}),cpu:(0,$.jsx)(fe,{}),cut:(0,$.jsx)(De,{}),database:(0,$.jsx)(t,{}),dot:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`●`}),download:(0,$.jsx)(ht,{}),edit:(0,$.jsx)(et,{}),engine:(0,$.jsx)(Dt,{}),eye:(0,$.jsx)(ve,{}),feather:(0,$.jsx)(ft,{}),file:(0,$.jsx)(Ce,{}),folder:(0,$.jsx)(Ee,{}),folders:(0,$.jsx)($f,{}),gauge:(0,$.jsx)(Fe,{}),git:(0,$.jsx)(ot,{}),github:(0,$.jsx)(Ze,{}),globe:(0,$.jsx)(Le,{}),grid:(0,$.jsx)(Pe,{}),hash:(0,$.jsx)(`span`,{className:`host-icon-char`,children:`#`}),image:(0,$.jsx)(be,{}),info:(0,$.jsx)(q,{}),layers:(0,$.jsx)(wt,{}),link:(0,$.jsx)(m,{}),list:(0,$.jsx)(f,{}),lock:(0,$.jsx)(Ge,{}),markdown:(0,$.jsx)(vt,{}),maximize:(0,$.jsx)(F,{}),menu:(0,$.jsx)(V,{}),minimize:(0,$.jsx)(Mt,{}),message:(0,$.jsx)(C,{}),open:(0,$.jsx)(Be,{}),paste:(0,$.jsx)(y,{}),pin:(0,$.jsx)(yt,{}),plus:(0,$.jsx)(ue,{}),refresh:(0,$.jsx)(pe,{}),sandbox:(0,$.jsx)(rp,{}),save:(0,$.jsx)(n,{}),share:(0,$.jsx)(Jf,{}),search:(0,$.jsx)(mt,{}),send:(0,$.jsx)($e,{}),settings:(0,$.jsx)(ze,{}),sound:(0,$.jsx)(l,{}),sun:(0,$.jsx)(Te,{}),target:(0,$.jsx)(H,{}),terminal:(0,$.jsx)(Xe,{}),text:(0,$.jsx)(he,{}),trash:(0,$.jsx)(Ne,{}),undo:(0,$.jsx)(le,{}),upload:(0,$.jsx)(Ot,{}),users:(0,$.jsx)(K,{}),volume:(0,$.jsx)(l,{}),wrap:(0,$.jsx)(w,{}),x:(0,$.jsx)(Ct,{}),zap:(0,$.jsx)(ne,{}),zoom:(0,$.jsx)(p,{})};Object.keys(mp);function hp(e){if(e.iconSvg)return(0,$.jsx)(pp,{icon:e.icon,iconSvg:e.iconSvg});if(!e.icon)return null;let t=mp[e.icon];return t===void 0?/[a-z]/i.test(e.icon)?null:(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:e.icon}):t}var gp=`pi-web-ui:device-groups-changed`,_p={rename:`deviceGroupManagerRename`,edit:`edit`,clear:`deviceGroupSectionClearMessages`,delete:`deviceGroupSectionDeleteGroup`},vp={bind:`deviceGroupSectionBind`,running:`deviceGroupSectionRunning`,forbidden:`deviceGroupSectionForbidden`,failed:`deviceGroupSectionFailed`},yp=class extends Error{status;code;detail;constructor(e,t,n=``){super(`Device group request failed (${e})`),this.status=e,this.code=t,this.detail=n}},bp=[`bot-drafts`],xp=15e3,Sp=12e4;function Cp(e){return bp.some(t=>e===t||e.startsWith(`${t}/`))}async function wp(e,t,n){return ln(`/api/device-center/${e}`,{body:n,signal:AbortSignal.any([t,AbortSignal.timeout(Cp(e)?Sp:xp)]),errorFor:t=>new yp(t.status,t.code,Cp(e)?t.detail.trim():``)})}function Tp(e){return e instanceof yp?[`NOT_PAIRED`,`REPAIR_REQUIRED`,`DEVICE_CHANGED`].includes(e.code)?`bind`:[`ROOM_BUSY`,`ROOM_RUNNING`,`TASKS_RUNNING`,`ACTIVE_TASKS`].includes(e.code)?`running`:e.status===403?`forbidden`:`failed`:`failed`}function Ep(e,t,n){let r,i=0,a=!1,o=!1,s=()=>{if(o)return;let c=++i;if(r){a=!0;return}let l=new AbortController;r=l,e(l.signal).then(e=>{!o&&c===i&&t(e)},e=>{!o&&c===i&&!l.signal.aborted&&n(e)}).finally(()=>{r=void 0,a&&!o&&(a=!1,s())})};return{refresh:s,pause:()=>{i++,a=!1,r?.abort()},stop:()=>{o=!0,i++,a=!1,r?.abort()}}}function Dp(e){window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:e}))}function Op({active:e=!0,entry:t,selectedRoomId:n,flex:r,onCollapsedChange:i,hideWhenEmpty:o=!1,autoHeight:s=!1}){let c=X(),l=t?.labelExplicit?t.label:c(`deviceGroups`),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(()=>new Set);(0,Q.useEffect)(()=>i?.(u),[u,i]);let[v,y]=(0,Q.useState)([]),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(!0),[w,T]=(0,Q.useState)(null),[E,O]=(0,Q.useState)(null),[k,A]=(0,Q.useState)(``),[j,M]=(0,Q.useState)(!1),N=(0,Q.useRef)(null),P=(0,Q.useRef)(null),F=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>(F.current=!0,()=>{F.current=!1,P.current?.abort()}),[]),(0,Q.useEffect)(()=>{if(!e)return;let t=!1,n=Ep(async e=>{let n=await wp(`chat-status`,e);if(t=n.roomsReady===!0||!!(n.hubUrl&&n.deviceId),!t)return[];let[r,i]=await Promise.all([wp(`rooms`,e),wp(`shared-rooms`,e).catch(()=>({rooms:[]}))]);if(!Array.isArray(r.rooms))throw Error(`Invalid rooms response`);let a=new Set,o=[];for(let e of r.rooms)a.add(e.id),o.push(e.scope?e:{...e,scope:`local`});for(let e of Array.isArray(i.rooms)?i.rooms:[])a.has(e.id)||(a.add(e.id),o.push(e.scope?e:{...e,scope:`shared`}));return o},e=>{x(t),y(e),T(null),C(!1)},e=>{T(Tp(e)),C(!1)});N.current=n;let r=()=>{document.hidden||n.refresh()},i=()=>{document.hidden?n.pause():r()};r();let a=window.setInterval(r,15e3);return window.addEventListener(gp,r),document.addEventListener(`visibilitychange`,i),()=>{n.stop(),N.current=null,window.clearInterval(a),window.removeEventListener(gp,r),document.removeEventListener(`visibilitychange`,i)}},[e]);let I=async(e,t)=>{if(P.current||t===`delete`&&!window.confirm(c(`deviceGroupSectionConfirmDelete`,{name:e.name}))||t===`clear`&&!window.confirm(c(`deviceGroupSectionConfirmClear`,{name:e.name})))return;let n=new AbortController;P.current=n,M(!0),T(null);try{if(await wp(`${e.scope===`shared`?`shared-rooms`:`rooms`}/${encodeURIComponent(e.id)}/${t}`,n.signal,t===`rename`?{name:k.trim()}:{}),!F.current||n.signal.aborted)return;O(null),window.dispatchEvent(new CustomEvent(gp))}catch(e){F.current&&!n.signal.aborted&&T(Tp(e))}finally{P.current=null,F.current&&M(!1)}},L=(e,t)=>{e.preventDefault(),e.stopPropagation();let n=[`rename`,`edit`,`clear`,`delete`].map((e,t)=>({id:`host:device-group-${e}`,slot:`contextmenu.project`,source:`host`,label:c(_p[e]),kind:`action`,action:e,order:t,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}));jf({x:e.clientX,y:e.clientY,slot:`contextmenu.project`,target:{id:t.id,kind:`device-group`,label:t.name},entries:n,onHostAction:e=>{P.current||(e.action===`rename`?(O(t.id),A(t.name)):e.action===`edit`?h(t):(e.action===`clear`||e.action===`delete`)&&I(t,e.action))}})};if(b===!1||b===null&&S||o&&v.length===0&&!w)return null;let R=(0,$.jsxs)(`div`,{className:`lp-section-body dg-side-body`,children:[w&&(0,$.jsxs)(`div`,{className:`dg-side-error`,role:`status`,children:[c(vp[w]),w===`bind`?(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>Dp({}),children:c(`deviceGroupSectionOpenDeviceCenter`)}):(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,onClick:()=>N.current?.refresh(),children:c(`retryNow`)})]}),!w&&v.length===0&&(0,$.jsx)(`div`,{className:`dg-side-empty`,children:c(S?`loading`:`deviceGroupSectionEmpty`)}),v.map(e=>(0,$.jsxs)(`div`,{className:`dg-side-item`,children:[(0,$.jsxs)(`div`,{className:`dg-side-heading`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,"aria-expanded":g.has(e.id),"aria-label":`${e.name} · ${c(`deviceGroupSectionMembers`)}`,onClick:()=>_(t=>{let n=new Set(t);return n.has(e.id)?n.delete(e.id):n.add(e.id),n}),children:g.has(e.id)?(0,$.jsx)(a,{}):(0,$.jsx)(D,{})}),(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,className:`dg-side-row${n===e.id?` is-selected`:``}`,"aria-current":n===e.id?`page`:void 0,title:e.name,onClick:()=>Dp({roomId:e.id}),onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),Dp({roomId:e.id}))},onContextMenu:t=>L(t,e),children:[(0,$.jsx)(K,{}),(0,$.jsxs)(`span`,{className:`dg-side-name`,children:[e.name,e.scope===`shared`&&(0,$.jsx)(`small`,{style:{marginInlineStart:6,opacity:.75},children:c(`deviceGroupManagerSharedSuffix`)})]})]}),(0,$.jsx)(`button`,{type:`button`,className:`dg-side-toggle`,"aria-label":`${e.name} · ${c(`deviceGroupSectionAddBot`)}`,title:c(`deviceGroupSectionAddOrCreateBot`),onClick:()=>p(e),children:(0,$.jsx)(ue,{})})]}),g.has(e.id)&&(0,$.jsx)(Wd,{botIds:e.botIds,roomId:e.id}),E===e.id&&(0,$.jsxs)(`form`,{className:`dg-side-rename`,onSubmit:t=>{t.preventDefault(),k.trim()&&I(e,`rename`)},children:[(0,$.jsx)(`input`,{className:`dc-input`,"aria-label":c(`deviceGroupManagerNameLabel`),value:k,maxLength:120,autoFocus:!0,disabled:j,onChange:e=>A(e.target.value),onKeyDown:e=>{e.key===`Escape`&&O(null)}}),(0,$.jsx)(`button`,{type:`submit`,className:`dc-button`,disabled:j||!k.trim(),children:c(`save`)}),(0,$.jsx)(`button`,{type:`button`,className:`dc-button`,disabled:j,onClick:()=>O(null),children:c(`cancel`)})]})]},e.id))]});return(0,$.jsxs)(`section`,{className:`lp-section dg-side-section${u?` collapsed`:``}${s?` lp-section-auto`:``}`,"aria-label":l,style:!u&&r!==void 0?{flex:`${r} 1 0px`}:void 0,children:[(0,$.jsxs)(`div`,{className:`lp-section-header`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-section-title panel-section-title`,"aria-expanded":!u,title:c(u?`deviceGroupSectionExpand`:`deviceGroupSectionCollapse`),onClick:()=>d(!u),children:[(0,$.jsxs)(`span`,{className:`lp-section-title-text lp-section-title-chip`,children:[t&&hp(t),(0,$.jsx)(`span`,{children:l}),(0,$.jsxs)(`span`,{className:`lp-section-count`,children:[`(`,v.length,`)`]})]}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,children:u?(0,$.jsx)(D,{}):(0,$.jsx)(a,{})})]}),(0,$.jsx)(`div`,{className:`lp-section-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action`,title:c(`deviceGroupsCreate`),"aria-label":c(`deviceGroupsCreate`),onClick:()=>Dp({create:!0}),children:(0,$.jsx)(ue,{})})})]}),!u&&R,f&&(0,$.jsx)(wf,{room:f,onClose:()=>p(null)}),m&&(0,$.jsx)(Df,{roomId:m.id,onClose:()=>h(null)})]})}var kp={DRAFT_NEEDS_APPROVAL:`needs-approval`,BOT_CWD_INVALID:`cwd-invalid`,WORKSPACE_INVALID:`cwd-invalid`,BOT_BUSY:`busy`,DRAFT_MISSING:`missing`};function Ap(e){return e instanceof yp?kp[e.code]??`failed`:`failed`}function jp(e,t){if(e instanceof yp){if(e.detail)return e.detail;let n=Ap(e);return n===`failed`?e.code?`${t.failed}(${e.code})`:t.failed:t[n]}let n=e instanceof Error?e.message.trim():``;return n?`${t.failed}:${n}`:t.failed}function Mp(e){if(!e||typeof e!=`object`||Array.isArray(e))return null;let t=e;if(t.op!==`draft`||!t.draft||typeof t.draft!=`object`||Array.isArray(t.draft))return null;let n=t.draft;if(typeof n.id!=`string`||!n.id||typeof n.name!=`string`)return null;let r=n.model,i=r&&typeof r.provider==`string`&&typeof r.modelId==`string`?{provider:r.provider,modelId:r.modelId}:void 0,a=t.status===`created`||t.status===`revised`||t.status===`discarded`?t.status:void 0;return{id:n.id,name:n.name,description:typeof n.description==`string`?n.description:``,systemPrompt:typeof n.systemPrompt==`string`?n.systemPrompt:``,trigger:typeof n.trigger==`string`?n.trigger:`on_demand`,cwd:typeof n.cwd==`string`?n.cwd:``,model:i,tools:Array.isArray(n.tools)?n.tools.filter(e=>typeof e==`string`):[],skills:Array.isArray(n.skills)?n.skills.filter(e=>typeof e==`string`):[],mcpServers:Array.isArray(n.mcpServers)?n.mcpServers.filter(e=>typeof e==`string`):[],needsApproval:Array.isArray(n.needsApproval)?n.needsApproval.filter(e=>typeof e==`string`):[],rationale:typeof n.rationale==`string`?n.rationale:void 0,settledStatus:a,settledBotId:typeof t.botId==`string`?t.botId:void 0,settledFeedback:typeof t.feedback==`string`?t.feedback:void 0}}function Np(e){if(!e)return null;try{return Mp(JSON.parse(e))}catch{return null}}function Pp(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t;if(n.op!==`draft`||typeof n.name!=`string`||!n.name.trim())return null;let r=n.model,i=r&&typeof r.provider==`string`&&typeof r.modelId==`string`?{provider:r.provider,modelId:r.modelId}:void 0;return{id:``,name:n.name,description:typeof n.description==`string`?n.description:``,systemPrompt:typeof n.systemPrompt==`string`?n.systemPrompt:``,trigger:`on_demand`,cwd:typeof n.cwd==`string`?n.cwd:``,model:i,tools:Array.isArray(n.tools)?n.tools.filter(e=>typeof e==`string`):[],skills:Array.isArray(n.skills)?n.skills.filter(e=>typeof e==`string`):[],mcpServers:Array.isArray(n.mcpServers)?n.mcpServers.filter(e=>typeof e==`string`):[],rationale:typeof n.rationale==`string`?n.rationale:void 0}}function Fp(e){return{"needs-approval":e(`agentBotsDraftNeedsApproval`),"cwd-invalid":e(`agentBotsDraftCwdInvalid`),busy:e(`agentBotsDraftBusy`),missing:e(`agentBotsDraftMissing`),failed:e(`agentBotsDraftActionFailed`)}}function Ip({draft:e}){let t=X(),[n,r]=(0,Q.useState)({name:e.name,description:e.description,systemPrompt:e.systemPrompt??``,cwd:e.cwd,model:e.model,tools:e.tools,skills:e.skills??[],mcpServers:e.mcpServers??[]}),[i,a]=(0,Q.useState)(e.id),o=e.id||i,[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)(e.settledStatus??`pending`),[_,v]=(0,Q.useState)(e.settledBotId??null),y=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{!y.current&&h===`pending`&&r({name:e.name,description:e.description,systemPrompt:e.systemPrompt??``,cwd:e.cwd,model:e.model,tools:e.tools,skills:e.skills??[],mcpServers:e.mcpServers??[]})},[e.id,e.name,e.description,e.systemPrompt,e.cwd,e.model,e.tools,e.skills,e.mcpServers,h]),(0,Q.useEffect)(()=>{e.settledStatus&&h===`pending`&&g(e.settledStatus),e.settledBotId&&!_&&v(e.settledBotId)},[e.settledStatus,e.settledBotId,h,_]);let{options:b,loading:x,error:S,reload:C}=mf(h===`pending`);(0,Q.useEffect)(()=>{if(e.settledStatus)return;let t=!1,n=new AbortController,i=async()=>{try{let i=await wp(`bot-panel`,n.signal);if(n.signal.aborted||t)return!1;let o=i.drafts??[],s=e.id?o.find(t=>t.id===e.id):o.find(t=>t.name===e.name);return s?(e.id||a(s.id),r(t=>({name:t.name===e.name?s.name:t.name,description:t.description===e.description?s.description:t.description,cwd:t.cwd===e.cwd?s.cwd:t.cwd,systemPrompt:t.systemPrompt===(e.systemPrompt??``)&&typeof s.systemPrompt==`string`?s.systemPrompt:t.systemPrompt,model:t.model??s.model,tools:t.tools.length===e.tools.length?s.tools:t.tools,skills:t.skills.length===(e.skills?.length??0)&&s.skills?s.skills:t.skills,mcpServers:t.mcpServers.length===(e.mcpServers?.length??0)&&s.mcpServers?s.mcpServers:t.mcpServers})),!0):(e.id&&g(e=>e===`pending`?`missing`:e),!1)}catch{return!1}},o;return i().then(n=>{n||e.id||t||(o=window.setInterval(()=>{i().then(e=>{e&&o!==void 0&&(window.clearInterval(o),o=void 0)})},600))}),()=>{t=!0,o!==void 0&&window.clearInterval(o),n.abort()}},[e.id,e.name,e.settledStatus]);let w=(0,Q.useMemo)(()=>{let t=new Set(e.needsApproval??[]);for(let e of b?.tools??[])e.warning===`high_privilege`&&t.add(e.id);return t},[e.needsApproval,b?.tools]),T=(0,Q.useMemo)(()=>n.tools.filter(e=>w.has(e)),[n.tools,w]),E=h===`pending`&&!!o&&n.name.trim().length>0&&n.cwd.trim().length>0&&n.systemPrompt.trim().length>0&&T.every(e=>s.includes(e)),D=(0,Q.useCallback)((e,t)=>{c(n=>t?[...new Set([...n,e])]:n.filter(t=>t!==e))},[]),O=(0,Q.useCallback)(async()=>{if(!E||d||!o)return;f(!0),m(``);let e=new AbortController;try{let t=[...new Set([...n.tools.filter(e=>!w.has(e)),...s])],r=await wp(`bot-drafts/${encodeURIComponent(o)}/approve`,e.signal,{name:n.name.trim(),description:n.description.trim(),systemPrompt:n.systemPrompt.trim(),cwd:n.cwd.trim(),model:n.model??null,tools:n.tools,skills:n.skills,mcpServers:n.mcpServers,approvedTools:t});window.dispatchEvent(new CustomEvent(`pi-web-ui:device-bots-changed`)),v(r.bot?.id??null),g(`created`)}catch(e){m(jp(e,Fp(t)))}finally{f(!1)}},[d,o,n,s,w,E,t]),k=(0,Q.useCallback)(async()=>{if(d||h!==`pending`||!o)return;f(!0),m(``);let e=new AbortController;try{await wp(`bot-drafts/${encodeURIComponent(o)}/discard`,e.signal,{}),window.dispatchEvent(new CustomEvent(`pi-web-ui:device-bots-changed`)),g(`discarded`)}catch(e){m(jp(e,Fp(t)))}finally{f(!1)}},[d,o,h,t]),A=(0,Q.useCallback)(async()=>{let e=l.trim();if(d||h!==`pending`||!e||!o)return;f(!0),m(``);let n=new AbortController;try{await wp(`bot-drafts/${encodeURIComponent(o)}/revise`,n.signal,{feedback:e}),g(`revised`)}catch(e){m(jp(e,Fp(t)))}finally{f(!1)}},[d,o,l,h,t]);return h===`created`?(0,$.jsxs)(`div`,{className:`bot-draft-inline is-settled`,children:[(0,$.jsxs)(`div`,{className:`bot-draft-inline-head`,children:[(0,$.jsxs)(`div`,{className:`bot-draft-inline-title`,children:[(0,$.jsx)(`span`,{className:`bot-draft-inline-icon is-ok`,"aria-hidden":`true`,children:(0,$.jsx)(z,{size:13})}),(0,$.jsx)(`strong`,{children:n.name})]}),(0,$.jsx)(`span`,{className:`bot-draft-inline-status is-ok`,children:t(`agentBotsInlineCreated`)})]}),n.description&&(0,$.jsx)(`p`,{className:`bot-draft-inline-sub`,children:n.description}),_&&(0,$.jsx)(`div`,{className:`bot-draft-inline-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`lp-bot-draft-primary`,onClick:()=>cd(_),children:t(`agentBotsMenuChat`)})})]}):h===`revised`||h===`discarded`||h===`missing`?(0,$.jsxs)(`div`,{className:`bot-draft-inline is-settled`,children:[(0,$.jsxs)(`div`,{className:`bot-draft-inline-head`,children:[(0,$.jsxs)(`div`,{className:`bot-draft-inline-title`,children:[(0,$.jsx)(`span`,{className:`bot-draft-inline-icon`,"aria-hidden":`true`,children:(0,$.jsx)(fe,{size:13})}),(0,$.jsx)(`strong`,{children:n.name})]}),(0,$.jsx)(`span`,{className:`bot-draft-inline-status`,children:t(h===`revised`?`agentBotsInlineRevised`:h===`discarded`?`agentBotsInlineDiscarded`:`agentBotsInlineHandled`)})]}),h===`revised`&&(l.trim()||e.settledFeedback)&&(0,$.jsx)(`p`,{className:`bot-draft-inline-sub`,children:l.trim()||e.settledFeedback})]}):(0,$.jsxs)(`div`,{className:`bot-draft-inline`,children:[(0,$.jsxs)(`div`,{className:`bot-draft-inline-head`,children:[(0,$.jsxs)(`div`,{className:`bot-draft-inline-title`,children:[(0,$.jsx)(`span`,{className:`bot-draft-inline-icon`,"aria-hidden":`true`,children:(0,$.jsx)(fe,{size:13})}),(0,$.jsx)(`strong`,{children:t(`agentBotsInlineTitle`)})]}),(0,$.jsx)(`span`,{className:`lp-bot-draft-badge`,children:t(`agentBotsTriggerOnDemand`)})]}),e.rationale&&(0,$.jsx)(`p`,{className:`bot-draft-inline-sub`,children:e.rationale}),(0,$.jsx)(bf,{variant:`inline`,value:n,onChange:e=>{y.current=!0,r(e)},options:b,optionsLoading:x,optionsError:S,onReloadOptions:C,busy:d,baseCwd:b?.defaultCwd||n.cwd}),T.length>0&&(0,$.jsxs)(`div`,{className:`bot-draft-inline-grants`,children:[(0,$.jsx)(`span`,{className:`bot-draft-inline-hint`,children:t(`agentBotsDraftHint`)}),(0,$.jsx)(`div`,{className:`bot-draft-inline-grant-list`,children:T.map(e=>(0,$.jsxs)(`label`,{className:`bot-draft-inline-chip is-high`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:s.includes(e),disabled:d,onChange:t=>D(e,t.target.checked)}),(0,$.jsx)(`span`,{children:e})]},e))})]}),p&&(0,$.jsx)(`div`,{className:`lp-bot-drafts-error`,role:`alert`,children:(0,$.jsx)(`span`,{children:p})}),(0,$.jsxs)(`div`,{className:`bot-draft-inline-revise`,children:[(0,$.jsx)(`input`,{type:`text`,value:l,disabled:d,placeholder:t(`agentBotsRevisePlaceholder`),onChange:e=>u(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&l.trim()&&(e.preventDefault(),A())}}),(0,$.jsx)(`button`,{type:`button`,disabled:d||!l.trim(),onClick:()=>void A(),children:t(`agentBotsReviseBtn`)})]}),(0,$.jsxs)(`div`,{className:`bot-draft-inline-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-bot-draft-primary`,disabled:!E||d,onClick:()=>void O(),children:t(d?`agentBotsApproving`:`agentBotsApprove`)}),(0,$.jsx)(`button`,{type:`button`,disabled:d,onClick:()=>void k(),children:t(`agentBotsDiscard`)})]})]})}var Lp=new Set([`image`,`video`,`audio`,`markdown`,`html`,`pdf`,`text`,`binary`,`dir`,`missing`]);function Rp(e){let t=String(e??``).trim().replace(/\\/g,`/`);return t.length>1?t.replace(/\/+$/,``):t}function zp(e){let t=Rp(e).split(`/`);return(t[t.length-1]??``)||String(e??``)}function Bp(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function Vp(e){return typeof e==`string`&&e.trim()?e.trim():void 0}function Hp(e){if(!e)return null;let t;try{t=JSON.parse(e)}catch{return null}let n=Bp(t);if(!n)return null;let r=Array.isArray(n.items)?n.items:[],i=[];for(let e of r){if(typeof e==`string`){let t=e.trim();t&&i.push({path:t});continue}let t=Bp(e),n=t?Vp(t.path):void 0;if(!n)continue;let r={path:n},a=Vp(t?.caption);a&&(r.caption=a),t?.focus===!0&&(r.focus=!0),i.push(r)}if(i.length===0)return null;let a={items:i},o=Vp(n.title);o&&(a.title=o);let s=Vp(n.note);return s&&(a.note=s),a}function Up(e,t){let n=Bp(t),r=Array.isArray(n?.items)?n.items.map(Bp):[],i=new Map;for(let e of r){if(!e)continue;let t=Rp(String(e.path??e.abs??``));t&&!i.has(t)&&i.set(t,e)}return e.items.map((e,t)=>{let n=i.get(Rp(e.path))??r[t]??null,a=Vp(n?.kind),o={path:e.path,target:Vp(n?.abs)??e.path,name:zp(Vp(n?.name)??e.path),kind:a&&Lp.has(a)?a:`unknown`,focus:e.focus===!0};e.caption&&(o.caption=e.caption),typeof n?.size==`number`&&Number.isFinite(n.size)&&(o.size=n.size),typeof n?.mtime==`number`&&Number.isFinite(n.mtime)&&(o.mtime=n.mtime);let s=Vp(n?.excerpt);return s&&(o.excerpt=s),n?.excerptTruncated===!0&&(o.excerptTruncated=!0),o})}function Wp(e,t){return Vp(Bp(t)?.title)??e.title}function Gp(e,t){return Vp(Bp(t)?.note)??e.note}function Kp(e){return e===`image`||e===`video`||e===`audio`?e:null}function qp(e){return e!==`dir`&&e!==`missing`}function Jp(e){switch(e){case`image`:return`🖼`;case`video`:return`🎬`;case`audio`:return`🎵`;case`markdown`:return`📝`;case`html`:return`🌐`;case`pdf`:return`📕`;case`text`:return`📄`;case`dir`:return`📁`;case`missing`:return`⚠`;default:return`📦`}}function Yp(e){if(!(e===void 0||!Number.isFinite(e)||e<0))return e<1024?`${Math.round(e)} B`:e<1048576?`${(e/1024).toFixed(+(e<10240))} KB`:e<0x40000000?`${(e/1024/1024).toFixed(1)} MB`:`${(e/1024/1024/1024).toFixed(1)} GB`}function Xp(e){return e.find(e=>e.focus&&qp(e.kind))}function Zp(e){return Xp(e)??e.find(e=>qp(e.kind))}function Qp(e){if(!e.enabled||e.seen||typeof e.timestamp!=`number`||!Number.isFinite(e.timestamp))return!1;let t=e.now-e.timestamp;return t>=0&&t<=e.maxAgeMs}var $p=`pi-web-ui:present-auto-open`,em=3e4,tm=`pi-web-ui:present-auto-opened`;function nm(){try{return localStorage.getItem($p)===`1`}catch{return!1}}function rm(e){try{localStorage.setItem($p,e?`1`:`0`)}catch{}sm=e,am()}var im=new Set;function am(){for(let e of im)e()}function om(e){return im.add(e),()=>{im.delete(e)}}var sm=null;function cm(){return sm===null&&(sm=nm()),sm}function lm(){return(0,Q.useSyncExternalStore)(om,cm)}function um(){try{let e=sessionStorage.getItem(tm);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function dm(e){if(!e)return!1;let t=um();if(t.includes(e))return!1;let n=[...t,e].slice(-200);try{sessionStorage.setItem(tm,JSON.stringify(n))}catch{}return!0}function fm(e,t,n=Date.now()){let r=typeof t==`number`&&Number.isFinite(t)?t:n;return Qp({enabled:nm(),seen:!1,timestamp:r,now:n,maxAgeMs:em})?dm(e):!1}var pm=(0,Q.memo)(function({args:e,details:t,toolCallId:n,resultTimestamp:r}){let i=X(),a=lm(),o=(0,Q.useMemo)(()=>Up(e,t),[e,t]),s=Wp(e,t),c=Gp(e,t),l=(0,Q.useMemo)(()=>Zp(o),[o]),u=(0,Q.useMemo)(()=>o.filter(e=>qp(e.kind)).map(e=>({path:e.target,name:e.name})),[o]),d=(0,Q.useMemo)(()=>{if(!l)return 0;let e=u.findIndex(e=>e.path===l.target);return e>=0?e:0},[u,l]);(0,Q.useEffect)(()=>{a&&l&&u.length!==0&&n&&($t()||fm(n,r)&&Zt(u,d))},[a,l,u,d,n,r]);let[f,p]=(0,Q.useState)(null),m=f!==null&&f<o.length?f:-1,h=m>=0?[o[m]]:o;return o.length===0?(0,$.jsx)(`div`,{className:`present-empty`,children:i(`presentEmpty`)}):(0,$.jsxs)(`div`,{className:`present-card`,children:[(s||u.length>0||o.length>1)&&(0,$.jsxs)(`div`,{className:`present-head-bar`,children:[(0,$.jsxs)(`div`,{className:`present-head-left`,children:[s?(0,$.jsx)(`div`,{className:`present-title`,children:s}):null,o.length>1&&(0,$.jsx)(`span`,{className:`present-count-badge`,children:o.length})]}),u.length>0&&(0,$.jsx)(`button`,{type:`button`,className:`present-expand-btn`,title:i(`fullscreen`),"aria-label":i(`fullscreen`),onClick:()=>{let e=m>=0?o[m]:null,t=e?u.findIndex(t=>t.path===e.target):d;Zt(u,t>=0?t:d)},children:(0,$.jsx)(F,{size:13,"aria-hidden":`true`})})]}),o.length>1&&(0,$.jsxs)(`div`,{className:`present-tabs`,role:`tablist`,children:[(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":m===-1,className:`present-tab${m===-1?` active`:``}`,onClick:()=>p(null),children:[i(`allProviders`),` (`,o.length,`)`]}),o.map((e,t)=>(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":m===t,className:`present-tab${m===t?` active`:``}`,onClick:()=>p(t),children:e.name},`${e.target}\u0000${t}`))]}),c&&(0,$.jsx)(`div`,{className:`present-note`,children:(0,$.jsx)(nl,{text:c,rawHtml:!0})}),(0,$.jsx)(`div`,{className:`present-items`,children:h.map((e,t)=>(0,$.jsx)(hm,{item:e,previewList:u,previewIndex:(()=>{let n=u.findIndex(t=>t.path===e.target);return n>=0?n:t})()},`${e.target}\u0000${e.path}\u0000${t}`))})]})});function mm(e){return typeof e.mtime==`number`?`${e.path}\n${new Date(e.mtime).toLocaleString()}`:e.path}function hm({item:e,previewList:t,previewIndex:n}){let r=X(),{copied:a,copy:o}=Gn({duration:1200}),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(``),d=s?null:Kp(e.kind),f=Yp(e.size),p=e.kind===`missing`,m=!Uc(),h=Jc(e.target);return(0,$.jsxs)(`div`,{className:`present-item${p?` missing`:``}`,children:[(0,$.jsxs)(`div`,{className:`present-item-head`,children:[(0,$.jsx)(`span`,{className:`present-item-icon`,"aria-hidden":`true`,children:Jp(e.kind)}),(0,$.jsx)(`span`,{className:`present-item-name`,title:mm(e),children:e.name}),e.caption&&(0,$.jsx)(`span`,{className:`present-item-caption`,children:e.caption}),f&&!p&&(0,$.jsx)(`span`,{className:`present-item-meta`,children:f}),(0,$.jsx)(`span`,{className:`present-item-spacer`}),!p&&(0,$.jsxs)($.Fragment,{children:[qp(e.kind)&&(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:r(`previewFile`),"aria-label":r(`previewFile`),onClick:()=>Zt(t,n),children:(0,$.jsx)(ve,{})}),m?(0,$.jsxs)(`a`,{className:`present-btn labeled`,href:h,target:`_blank`,rel:`noreferrer noopener`,title:r(`openInNewTab`),children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{children:r(`openInNewTab`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`present-btn labeled`,title:r(`fileOpenDefault`),onClick:()=>Z({type:`file_open_default`,path:e.target}),children:[(0,$.jsx)(Be,{}),(0,$.jsx)(`span`,{children:r(`presentOpenLocal`)})]}),!m&&(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:r(`fileReveal`),"aria-label":r(`fileReveal`),onClick:()=>Z({type:`file_reveal`,path:e.target}),children:(0,$.jsx)(Ee,{})}),(0,$.jsx)(`button`,{type:`button`,className:`present-btn`,title:r(`downloadFile`),"aria-label":r(`downloadFile`),onClick:()=>{u(``),Ey(e.target,e.name).then(e=>{e.ok||e.cancelled||u(e.error===`FILE_NOT_FOUND`?r(`fileNotFoundShort`):e.error)})},children:(0,$.jsx)(ht,{})}),(0,$.jsx)(`button`,{type:`button`,className:`present-btn${a?` on`:``}`,title:r(`copyPath`),"aria-label":r(`copyPath`),onClick:()=>{o(e.path)},children:(0,$.jsx)(st,{})})]})]}),p&&(0,$.jsx)(`div`,{className:`present-item-warn`,children:r(`presentMissing`)}),l&&(0,$.jsx)(`div`,{className:`present-item-warn`,children:r(`downloadFailed`,{error:l})}),d===`image`&&(0,$.jsx)(`button`,{type:`button`,className:`present-media`,title:r(`previewFile`),onClick:()=>Zt(t,n),children:(0,$.jsx)(`img`,{crossOrigin:i(Ty(e.target,!1)),src:Ty(e.target,!1),alt:e.name,loading:`lazy`,onError:()=>c(!0)})}),d===`video`&&(0,$.jsx)(`video`,{className:`present-media-video`,crossOrigin:i(Ty(e.target,!1)),src:Ty(e.target,!1),controls:!0,preload:`metadata`,onError:()=>c(!0)}),d===`audio`&&(0,$.jsx)(`audio`,{className:`present-media-audio`,crossOrigin:i(Ty(e.target,!1)),src:Ty(e.target,!1),controls:!0,preload:`metadata`,onError:()=>c(!0)}),e.excerpt&&(0,$.jsxs)(`pre`,{className:`present-excerpt`,children:[e.excerpt,e.excerptTruncated?`…`:``]})]})}var gm=/^\s{0,3}(`{3,}|~{3,})/,_m=/^\s{0,3}(?:[-*+]|\d{1,9}[.)])\s/;function vm(e){return e.trim()===``}function ym(e){let t=gm.exec(e);return t?t[1]:null}function bm(e){let t=e.split(`
|
|
31
|
-
`),n=[],r=[],i=null;for(let e=0;e<t.length;e++){let a=t[e];if(i!==null){let e=ym(a);e&&e[0]===i[0]&&e.length>=i.length&&(i=null),r.push(a);continue}let o=ym(a);if(o&&!vm(a))i=o,r.push(a);else if(vm(a)){let i=e;for(;i<t.length&&vm(t[i]);)i++;if(!(i<t.length&&_m.test(t[i]))&&r.length>0){n.push(r.join(`
|
|
32
|
-
`)),r=[];continue}r.push(a)}else r.push(a)}return{frozen:n,active:r.join(`
|
|
33
|
-
`),inFence:i!==null}}function xm(e,t,n=!1){let r=e.length;if(t>=r)return r;t<0&&(t=0);let i=r-t,a;a=n?i<=16?Math.max(2,Math.ceil(i/6)):Math.ceil(i/8):i<=32?1:i<=90?2:Math.ceil(i<=240?i/28:i/18);let o=Math.min(r,t+a);if(o<r){let t=e.charCodeAt(o-1);t>=55296&&t<=56319&&(o=Math.min(r,o+1))}return o}var Sm=22,Cm=14,wm=()=>typeof document<`u`&&document.hidden;function Tm(e,t=!0,n=!1,r){let[i,a]=(0,Q.useState)(()=>!t||wm()||e.length>1500?e.length:0),o=(0,Q.useRef)(e);o.current=e;let s=(0,Q.useRef)(i);s.current=i;let c=(0,Q.useRef)(t);c.current=t;let l=(0,Q.useRef)(n);l.current=n;let u=(0,Q.useRef)(r);u.current=r;let d=(0,Q.useRef)(0),f=(0,Q.useRef)(0);return(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{document.hidden,d.current&&=(cancelAnimationFrame(d.current),0),s.current=o.current.length,a(o.current.length),(l.current||!c.current)&&u.current?.()};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),(0,Q.useEffect)(()=>{if(!t){d.current&&=(cancelAnimationFrame(d.current),0),s.current!==e.length&&(s.current=e.length,a(e.length));return}if(wm()){d.current&&=(cancelAnimationFrame(d.current),0),s.current!==e.length&&(s.current=e.length,a(e.length)),(n||s.current>=e.length)&&u.current?.();return}if(e.length<s.current){d.current&&=(cancelAnimationFrame(d.current),0),s.current=e.length,a(e.length),u.current?.();return}if(s.current>=e.length){d.current||u.current?.();return}if(d.current)return;let r=e=>{if(d.current=0,!c.current)return;let t=l.current?Cm:Sm;if(f.current>0&&e-f.current<t){d.current=requestAnimationFrame(r);return}f.current=e;let n=xm(o.current,s.current,l.current);n!==s.current&&(s.current=n,a(n)),n<o.current.length?d.current=requestAnimationFrame(r):u.current?.()};d.current=requestAnimationFrame(r)},[e,t,n]),(0,Q.useEffect)(()=>()=>{d.current&&=(cancelAnimationFrame(d.current),0)},[]),!t||i>=e.length?e:e.slice(0,i)}var Em=600,Dm=32,Om=(0,Q.memo)(function({text:e,active:t,inFence:n}){let r=t&&!n&&e.length>=Em,[i,a]=(0,Q.useState)(e),o=(0,Q.useRef)(0),s=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{if(!r)return;let t=Date.now()-o.current,n=()=>{o.current=Date.now(),a(e)};if(t>=Dm)n();else return s.current=setTimeout(n,Dm-t),()=>{s.current&&clearTimeout(s.current)}},[e,r]),t&&n?(0,$.jsx)(`div`,{className:`codeblock`,children:(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:e})})}):(0,$.jsx)(tl,{text:r?i:e})}),km=(0,Q.memo)(function({text:e,finishing:t=!1,onSettled:n}){let r=Tm(e,!0,t,n),{frozen:i,active:a,inFence:o}=(0,Q.useMemo)(()=>bm(r),[r]);return(0,$.jsx)(`div`,{className:`md`,children:[...i,...a.length>0?[a]:[]].map((e,t)=>(0,$.jsx)(Om,{text:e,active:t===i.length,inFence:t===i.length&&o},t))})});function Am({className:e,width:t=`1em`,height:n=`1em`,...r}){let i=[`half-ring-spin`,e].filter(Boolean).join(` `);return(0,$.jsx)(`svg`,{viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,width:t,height:n,className:i,"aria-hidden":`true`,...r,children:(0,$.jsx)(`path`,{d:`M 12 2 A 10 10 0 0 1 12 22`})})}function jm(e){if(e===void 0||e<0||!Number.isFinite(e))return``;if(e<1e3)return`${Math.round(e)}ms`;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${n}m ${String(r).padStart(2,`0`)}s`}function Mm(e){return String(e).padStart(2,`0`)}function Nm(e){if(e===void 0||!Number.isFinite(e)||e<=0)return``;let t=new Date(e),n=new Date,r=t.getFullYear()===n.getFullYear()&&t.getMonth()===n.getMonth()&&t.getDate()===n.getDate(),i=`${Mm(t.getHours())}:${Mm(t.getMinutes())}:${Mm(t.getSeconds())}`;return r?i:`${Mm(t.getMonth()+1)}-${Mm(t.getDate())} ${i}`}function Pm(e,t,n){let r=typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.round(t):typeof n==`number`&&Number.isFinite(n)&&n>=0?Math.round(n):void 0,i=typeof e==`number`&&Number.isFinite(e)?e:void 0;return{start:i!==void 0&&r!==void 0?i-r:void 0,end:i,durationMs:r}}function Fm(e,t){let n=typeof e==`number`&&Number.isFinite(e)?e:void 0,r=typeof t==`number`&&Number.isFinite(t)&&t>=0?Math.round(t):void 0;return{start:n,end:n!==void 0&&r!==void 0?n+r:void 0,durationMs:r}}var Im=300;function Lm(e){let t=e.split(`
|
|
34
|
-
`),n=0;for(;n<t.length;){let e=t[n].trim();if(!e){n++;continue}let r=e.replace(/^[#*>\s]+/,``).toLowerCase();if(r===`thinking`||r===`thinking:`||r===`thinking process`||r===`thinking process:`||r===`思考`||r===`思考过程`||r===`思考过程:`||r===`思路`||r===`思路:`)n++;else break}return t.slice(n).join(`
|
|
35
|
-
`)}function Rm(e){return!e||!e.includes(`[[`)?e:e.replace(/\[\[(?:conv|todo|action|suggest|notify|goal):[\s\S]*?\]\]/gu,``).replace(/\[\[(?:conv|todo|action|suggest|notify|goal):[^\]]*$/u,``)}function zm(e){let t=Rm(e).replace(/\r\n/g,`
|
|
36
|
-
`).replace(/[ \t]+\n/g,`
|
|
37
|
-
`),n=Lm(t).trim()||t.trim();return n?n.replace(/\n{3,}/g,`
|
|
38
|
-
|
|
39
|
-
`):``}function Bm(e){let t=Rm(e),n=Lm(t).trim()||t.trim();return n?n.split(/\n+/).map(e=>e.trim()).filter(Boolean).join(` `):``}function Vm(e,t){let n=Bm(e);return n?t?n.slice(-300):n.slice(0,Im):``}var Hm=(0,Q.memo)(function({thinking:e,streaming:t,wrap:n=!0,forceOpen:r=!1,startTimestamp:i,endTimestamp:a,durationMs:o,thinkingId:s}){let c=X(),[l,u]=(0,Q.useState)(null),d=l??n,f=d||r,p=!!t,m=(0,Q.useRef)(p);m.current=p;let g=()=>typeof document<`u`&&document.hidden,[_,v]=(0,Q.useState)(()=>p&&!g());(0,Q.useEffect)(()=>{p&&!g()?v(!0):!p&&g()&&v(!1)},[p]),(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{m.current||v(!1)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let y=(0,Q.useCallback)(()=>{m.current||v(!1)},[]),b=p||_,x=Tm(e,b,!p&&_,y),S=(0,Q.useMemo)(()=>zm(x),[x]),C=(0,Q.useMemo)(()=>Vm(x,b),[x,b]),{copied:w,copy:T}=Gn({duration:1200}),E=()=>{T(e)},D=f?c(`collapseMsg`):C?`${c(`expandMsg`)} · ${C}`:c(`expandMsg`),O=(0,Q.useRef)(null),k=Qt(O.current),A=Fm(i,o??(a!==void 0&&i!==void 0?a-i:void 0)),j=A.durationMs===void 0?``:jm(A.durationMs),[M,N]=(0,Q.useState)(()=>Date.now());(0,Q.useEffect)(()=>{if(!b||A.start===void 0)return;let e=window.setInterval(()=>N(Date.now()),1e3);return()=>window.clearInterval(e)},[b,A.start]);let P=b&&A.start!==void 0?Math.max(0,M-A.start):void 0,F=j?`${c(`done`)} (${j})`:c(`done`),I={status:b?c(`thinkingNow`):F,statusClass:b?`run`:`ok`,duration:j,durationMs:A.durationMs,startTimestamp:A.start,endTimestamp:A.end,output:S||e,thinking:x||e,streaming:b},L=(0,Q.useRef)(I);L.current=I;let R=(0,Q.useRef)(F);R.current=F;let B=(0,Q.useRef)(e);B.current=e;let V=(0,Q.useRef)(new Set);s&&V.current.add(s);let H=()=>{Bt({isThinking:!0,title:c(`toolInspectorThinkingTitle`),...I,toolCallId:s})};return(0,Q.useEffect)(()=>{if(!s)return;let t=Yt();if(!t||!t.isThinking)return;let n=t.toolCallId;if(n){if(n!==s){let r=zm(t.thinking||t.output||``),i=!!r&&(S||e).startsWith(r);if(!V.current.has(n)&&!i)return;Kt(n,s)}en(s,L.current,`thinking`)}},[s,x,S,e,b,j,A.start,A.end,A.durationMs,c]),(0,Q.useEffect)(()=>()=>{let e=Yt();if(!e||!e.isThinking||!e.streaming)return;let t=e.toolCallId;if(!t||!V.current.has(t))return;let n=zm(B.current);en(t,{...L.current,thinking:B.current||L.current.thinking,output:n||L.current.output,status:R.current,statusClass:`ok`,streaming:!1},`thinking`)},[]),k?(0,$.jsx)(`div`,{ref:O,className:`thinking ${b?`live run`:`ok`}`,"data-thinking":e,onClick:e=>{e.preventDefault(),e.stopPropagation(),H()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),H())},role:`button`,tabIndex:0,title:c(`toolInspectorThinkingTitle`),children:(0,$.jsxs)(`div`,{className:`thinking-head chead`,children:[(0,$.jsx)(`span`,{className:`thinking-icon chead-icon`,children:(0,$.jsx)(fe,{})}),(0,$.jsx)(`span`,{className:`thinking-name chead-title`,children:c(`thinking`)}),(0,$.jsx)(`span`,{className:`thinking-status toolcall-status`,title:c(b?`thinkingNow`:`done`),"aria-label":c(b?`thinkingNow`:`done`),children:b?(0,$.jsx)(Am,{className:`spin`}):(0,$.jsx)(z,{})})]})}):(0,$.jsxs)(`div`,{ref:O,className:`thinking ${f?`open`:``} ${b?`live`:``} ${b?`run`:`ok`}`,"data-thinking":e,onClick:e=>{Qt(O.current)&&(e.target?.closest(`.chead-copy, .toolcall-copy, .thinking-copy, a`)||(e.preventDefault(),e.stopPropagation(),H()))},children:[(0,$.jsx)(Pl,{open:!k&&f,headClassName:`thinking-head${b?` thinking-live`:``}`,toggleClassName:`thinking-toggle`,titleText:D,onToggle:()=>{Qt(O.current)?H():u(!d)},icon:(0,$.jsx)(fe,{}),iconClassName:`thinking-icon`,titleClassName:`thinking-label`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-status toolcall-status`,title:c(b?`thinkingNow`:`done`),"aria-label":c(b?`thinkingNow`:`done`),children:b?(0,$.jsx)(Am,{className:`spin`}):(0,$.jsx)(z,{})}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy thinking-copy${w?` copied`:``}`,title:c(w?`copied`:`copyMessage`),"aria-label":c(`copyMessage`),onClick:e=>{e.stopPropagation(),E()},children:w?(0,$.jsx)(h,{}):(0,$.jsx)(st,{})})]}),children:b&&f?(0,$.jsxs)(`span`,{className:`thinking-live-label`,children:[c(`thinkingNow`),(0,$.jsx)(`span`,{className:`dots`})]}):b?C?(0,$.jsx)(`span`,{className:`thinking-preview-live`,children:(0,$.jsx)(`span`,{className:`thinking-preview-viewport`,children:(0,$.jsxs)(`span`,{className:`thinking-preview-track`,children:[C,(0,$.jsx)(`span`,{className:`stream-cursor`})]})})}):(0,$.jsxs)(`span`,{className:`thinking-live-label`,children:[c(`thinkingNow`),(0,$.jsx)(`span`,{className:`dots`})]}):C?(0,$.jsx)(`span`,{className:`thinking-summary-text`,children:C}):null}),!k&&f&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`thinking-body`,children:[S,b&&(0,$.jsx)(`span`,{className:`stream-cursor`})]}),(0,$.jsxs)(`div`,{className:`toolcall-time-footer thinking-time-footer`,children:[(0,$.jsx)(re,{className:`toolcall-time-icon`}),(0,$.jsx)(`span`,{className:`toolcall-time-text`,children:A.start!==void 0&&A.end!==void 0&&A.durationMs!==void 0?c(`toolTimeRange`,{start:Nm(A.start),end:Nm(A.end),duration:jm(A.durationMs)}):b&&A.start!==void 0&&P!==void 0?c(`toolTimeRunning`,{start:Nm(A.start),duration:jm(P)}):A.start===void 0?``:Nm(A.start)})]})]})]})}),Um=262144,Wm=300,Gm=/"(path|file_path|filePath|filename|file)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,Km=/"agent"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/,qm=/"(?:name|skill)"\s*:\s*"((?:[^"\\\n]|\\.){0,4000})"/,Jm=/"(timeout|timeoutSeconds|timeout_seconds|timeoutSec|timeoutMs|timeout_ms|timeoutMilliseconds)"\s*:\s*(-?\d+(?:\.\d+)?)(?![0-9eE.])/,Ym=/"(query|q|search|pattern)"\s*:\s*"((?:[^"\\\n]|\\.){0,400})"/,Xm=1e9,Zm=new Set([`bash`,`exec_command`,`commandExecution`,`shell`,`shell_command`,`run_command`]);function Qm(e){return Zm.has(e)}function $m(e){let t=e.split(`
|
|
40
|
-
`),n=t[0].replace(/\s+/g,` `).trim();if(!n)return;let r=t.length-1,i=n.length>80?`${n.slice(0,80)}…`:n;return r>0?`${i} +${r}`:i}function eh(e){let{name:t,argumentsText:n,isCollapsed:r=!1}=e,i=e.hints??th(n);switch(t){case`bash`:case`exec_command`:case`commandExecution`:case`shell`:case`shell_command`:case`run_command`:if(i.command){if(!r)return null;let e=$m(i.command);return e?{text:e,title:i.command,prefix:`$ `,className:`toolcall-cmd`}:null}return i.path?{text:oh(i.path),title:i.path,className:`toolcall-path`}:i.title?{text:i.title,title:i.title,className:`toolcall-query`}:null;case`write_stdin`:{let e=fh(n);return e?{text:e,title:e,className:`toolcall-cmd`}:null}case`read`:case`write`:case`edit`:case`patch`:case`ls`:return i.path?{text:oh(i.path),title:i.path,className:`toolcall-path`}:null;case`skill`:return i.skillName?{text:i.skillName,title:i.skillName,className:`toolcall-skill`}:null;case`delegate_task`:return i.agent?{text:i.agent,title:i.agent,prefix:`◈ `,className:`toolcall-agent`}:null;case`codemode`:case`eval`:return i.codeLines?{text:`${i.codeLines}L`,title:`${i.codeLines} lines`,prefix:`λ `,className:`toolcall-timeout`}:null;case`tool_search`:case`grep`:return i.query?{text:i.query,title:i.query,className:`toolcall-query`}:null;case`ask_user_question`:return i.questionTitle?{text:i.questionTitle,title:i.questionTitle,className:`toolcall-query`}:null;case`bg_run`:{let e=xh(n);return e?{text:e,title:e,prefix:`◉ `,className:`toolcall-query`}:null}case`bg_status`:case`bg_logs`:case`bg_result`:case`bg_kill`:{let e=Sh(n);return e?{text:e,title:e,prefix:`◉ `,className:`toolcall-query`}:null}case`bg_task`:{let e=Ch(n);return e?{text:e,title:e,prefix:`◉ `,className:`toolcall-query`}:null}default:if(i.path)return{text:oh(i.path),title:i.path,className:`toolcall-path`};if(i.query)return{text:i.query,title:i.query,className:`toolcall-query`};if(i.command){let e=$m(i.command);if(e)return{text:e,title:i.command,prefix:`$ `,className:`toolcall-cmd`}}return i.title?{text:i.title,title:i.title,className:`toolcall-query`}:null}}function th(e){if(!e)return{};let t=e.length>Um?e.slice(0,Um):e;return{path:sh(t),timeout:ch(t),command:uh(e),agent:nh(t),skillName:rh(t),codeLines:hh(e),query:lh(t),questionTitle:_h(t),title:dh(e)}}function nh(e){let t=Km.exec(e);if(!t)return;let n=t[1].replace(/[\u0000-\u001f\u007f]/g,``).trim();if(n)return n.length>Wm?`${n.slice(0,Wm)}…`:n}function rh(e){let t=qm.exec(e);if(!t)return;let n=ph(t[1]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>Wm?`${n.slice(0,299)}…`:n}var ih=[`task`,`expected_outcome`,`required_tools`,`must_do`,`must_not_do`,`context`];function ah(e){if(!e||e.length>Um)return{};try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))return{};let n=t,r={};for(let e of[...ih,`agent`,`model`])typeof n[e]==`string`&&n[e].trim()&&(r[e]=n[e]);return r}catch{return{}}}function oh(e,t=56){if(e.length<=t)return e;let n=e.split(/[\\/]+/).filter(Boolean),r=n[n.length-1];if(!r||n.length<=1)return`…${e.slice(-(t-1))}`;let i=r;for(let e=n.length-2;e>=0;e--){let r=`${n[e]}/${i}`;if(r.length+2>t)break;i=r}return`…/${i}`}function sh(e){let t=Gm.exec(e);if(!t)return;let n=ph(t[2]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>Wm?`${n.slice(0,299)}…`:n}function ch(e){let t=Jm.exec(e);if(!t)return;let n=Number(t[2]);if(!Number.isFinite(n)||n<=0||n>Xm)return;let r=t[1].toLowerCase();return!r.endsWith(`ms`)&&!r.endsWith(`milliseconds`)?`${n}s`:n<1e3?`${n}ms`:`${Math.round(n/100)/10}s`}function lh(e){let t=Ym.exec(e);if(!t)return;let n=ph(t[2]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>60?`${n.slice(0,57)}…`:n}function uh(e){if(!(e.length>Um))try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?void 0:typeof t.command==`string`&&t.command.trim()?t.command:typeof t.cmd==`string`&&t.cmd.trim()?t.cmd:void 0}catch{return}}function dh(e){let t=yh(e);if(t)return bh(t.title,80)??void 0}function fh(e){let t=yh(e);if(!t)return null;let n=bh(t.chars,40);if(n)return n;let r=t.session_id??t.sessionId;return typeof r==`number`||typeof r==`string`?`#${r}`:null}function ph(e){try{let t=JSON.parse(`"${e}"`);return typeof t==`string`?t:e}catch{return e}}function mh(e){if(!e)return{};let t,n=e.trim();if(n.startsWith(`{`))try{let e=JSON.parse(n);typeof e?.code==`string`&&(t=e.code)}catch{let e=/"code"\s*:\s*"((?:[^"\\]|\\.)*)/.exec(n);e&&(t=ph(e[1]))}else n&&(t=e);if(!t)return{};let r=t.indexOf(`
|
|
41
|
-
`),i=r===-1?t.trim():t.slice(0,r).trim(),a;if(i.startsWith(`// @options:`))try{a=JSON.parse(i.slice(12).trim())}catch{}return{code:t,options:a}}function hh(e){let t=mh(e);if(!t.code)return;let n=t.code.split(`
|
|
42
|
-
`).length;return n>0?n:void 0}var gh=/"(?:header|question)"\s*:\s*"((?:[^"\\\n]|\\.){0,200})"/;function _h(e){let t=gh.exec(e);if(!t)return;let n=ph(t[1]).replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();if(n)return n.length>40?`${n.slice(0,38)}…`:n}function vh(e){if(!e||e.length>Um)return null;try{let t=JSON.parse(e);if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.questions;return Array.isArray(n)&&n.length>0?{questions:n}:null}catch{return null}}function yh(e){if(!e||e.length>Um)return null;try{let t=JSON.parse(e);return!t||typeof t!=`object`||Array.isArray(t)?null:t}catch{return null}}function bh(e,t=40){if(typeof e!=`string`)return null;let n=e.replace(/[\u0000-\u001f\u007f]/g,` `).replace(/\s+/g,` `).trim();return n?n.length>t?`${n.slice(0,t-1)}…`:n:null}function xh(e){let t=yh(e);return t?bh(t.name,40)??bh(t.command,40):null}function Sh(e){let t=yh(e);return t?bh(t.taskId,14)||bh(t.name,40):null}function Ch(e){let t=yh(e);if(!t)return null;let n=bh(t.action,12);if(!n)return null;let r=bh(t.jobId,14)??bh(t.taskId,14);return r?`${n} ${r}`:n}var wh={ts:`typescript`,tsx:`tsx`,js:`javascript`,jsx:`jsx`,mjs:`javascript`,cjs:`javascript`,json:`json`,html:`html`,htm:`html`,css:`css`,scss:`scss`,less:`less`,py:`python`,rs:`rust`,go:`go`,java:`java`,c:`c`,cpp:`cpp`,h:`c`,hpp:`cpp`,sh:`bash`,bash:`bash`,zsh:`bash`,yml:`yaml`,yaml:`yaml`,toml:`toml`,md:`markdown`,sql:`sql`,xml:`xml`,svg:`svg`};function Th(e){if(!e)return`plaintext`;let t=e.split(`.`).pop()?.toLowerCase();return t&&wh[t]||`plaintext`}var Eh=/\s+|[a-zA-Z0-9_$]+|[^\s\w]/g;function Dh(e){return e?e.replace(/\\([nrtbfv\\/"]|u[0-9a-fA-F]{4})/g,(e,t)=>{switch(t){case`n`:return`
|
|
43
|
-
`;case`r`:return`\r`;case`t`:return` `;case`b`:return`\b`;case`f`:return`\f`;case`v`:return`\v`;case`\\`:return`\\`;case`/`:return`/`;case`"`:return`"`;default:if(t.startsWith(`u`))try{return String.fromCharCode(parseInt(t.slice(1),16))}catch{return`\\${t}`}return`\\${t}`}}):``}function Oh(e,t){if(!e||!t||e.length>800||t.length>800)return{oldTokens:[{type:`del`,text:e}],newTokens:[{type:`add`,text:t}]};let n=e.match(Eh)||[e],r=t.match(Eh)||[t],i=n.length,a=r.length;if(i*a>4e3)return{oldTokens:[{type:`del`,text:e}],newTokens:[{type:`add`,text:t}]};let o=Array.from({length:i+1},()=>Array(a+1).fill(0));for(let e=1;e<=i;e++)for(let t=1;t<=a;t++)n[e-1]===r[t-1]?o[e][t]=o[e-1][t-1]+1:o[e][t]=Math.max(o[e-1][t],o[e][t-1]);let s=o[i][a],c=Math.max(i,a);if(c>0&&s/c<.25)return{oldTokens:[{type:`del`,text:e}],newTokens:[{type:`add`,text:t}]};let l=[],u=[],d=i,f=a,p=[],m=[];for(;d>0||f>0;)d>0&&f>0&&n[d-1]===r[f-1]?(p.push({type:`same`,text:n[d-1]}),m.push({type:`same`,text:r[f-1]}),d--,f--):f>0&&(d===0||o[d][f-1]>=o[d-1][f])?(m.push({type:`add`,text:r[f-1]}),f--):d>0&&(p.push({type:`del`,text:n[d-1]}),d--);p.reverse(),m.reverse();for(let e of p){let t=l[l.length-1];t&&t.type===e.type?t.text+=e.text:l.push({...e})}for(let e of m){let t=u[u.length-1];t&&t.type===e.type?t.text+=e.text:u.push({...e})}return{oldTokens:l,newTokens:u}}var kh=/^([+\- ])(\s*\d+)?\s(.*)$/;function Ah(e){let t=[],n=null,r=0,i=0,a=1,o=1,s=e.split(`
|
|
44
|
-
`),c=[],l=[],u=()=>{if(c.length===1&&l.length===1){let{oldTokens:e,newTokens:t}=Oh(c[0].content,l[0].content);c[0].tokens=e,l[0].tokens=t}c=[],l=[]},d=(e=`@@ Changes @@`)=>(n||(n={header:e,lines:[]},t.push(n)),n);for(let e of s){if(e.startsWith(`---`)||e.startsWith(`+++`)||e.startsWith(`===`)||e.startsWith(`Index:`))continue;if(e.startsWith(`@@`)){u();let r=/@@\s*-(\d+)(?:,\d+)?\s*\+(\d+)(?:,\d+)?\s*@@(.*)/.exec(e);r&&(a=parseInt(r[1],10),o=parseInt(r[2],10)),n={header:e.trim(),lines:[]},t.push(n);continue}if(/^\s+\.\.\.\s*$/.test(e)){u(),n={header:`@@ ... @@`,lines:[]},t.push(n);continue}let s=kh.exec(e);if(s){let e=s[1],t=s[2]?s[2].trim():void 0,n=t?parseInt(t,10):void 0,f=s[3],p=d();if(e===`+`){r++;let e={type:`add`,newLineNum:n??o++,content:f};p.lines.push(e),l.push(e)}else if(e===`-`){i++;let e={type:`del`,oldLineNum:n??a++,content:f};p.lines.push(e),c.push(e)}else{u();let e=n??a++;n||o++;let t={type:`context`,oldLineNum:e,newLineNum:e,content:f};p.lines.push(t)}}else if(e.length>0){let t=e[0],n=e.slice(1),s=d();if(t===`+`){r++;let e={type:`add`,newLineNum:o++,content:n};s.lines.push(e),l.push(e)}else if(t===`-`){i++;let e={type:`del`,oldLineNum:a++,content:n};s.lines.push(e),c.push(e)}else if(t===` `){u();let e={type:`context`,oldLineNum:a++,newLineNum:o++,content:n};s.lines.push(e)}}}return u(),{hunks:t,stats:{additions:r,deletions:i}}}function jh(e){let t=[],n=0,r=0;return e.forEach((e,i)=>{let a=typeof e.oldText==`string`?e.oldText:``,o=typeof e.newText==`string`?e.newText:``,s=a?a.split(`
|
|
45
|
-
`):[],c=o?o.split(`
|
|
46
|
-
`):[];r+=s.length,n+=c.length;let l=[];if(s.length===1&&c.length===1){let{oldTokens:e,newTokens:t}=Oh(s[0],c[0]);l.push({type:`del`,content:s[0],tokens:e}),l.push({type:`add`,content:c[0],tokens:t})}else{for(let e of s)l.push({type:`del`,content:e});for(let e of c)l.push({type:`add`,content:e})}t.push({header:`@@ Hunk #${i+1} (${s.length} lines -> ${c.length} lines) @@`,lines:l})}),{hunks:t,stats:{additions:n,deletions:r}}}function Mh(e,t,n,r){let i=e===`write`;if(!i&&e!==`edit`&&e!==`patch`)return null;let a=``,o=!1,s=null;if(t)try{s=JSON.parse(t),typeof s.path==`string`?a=s.path:typeof s.file_path==`string`&&(a=s.file_path)}catch{o=!0;let e=/"(?:path|file_path|filePath)"\s*:\s*"((?:[^"\\\n]|\\.){0,2000})"/.exec(t);if(e)try{a=JSON.parse(`"${e[1]}"`)}catch{a=e[1]}}if(!a&&r){let e=/(?:Successfully (?:wrote to|replaced \d+ block\(s\) in)|written to|Created)\s+([^\s\n\r"']+)/i.exec(r);e&&(a=e[1].trim())}let c=Th(a);if(i){let n=``;if(s&&typeof s.content==`string`)n=s.content;else if(t){let e=/"content"\s*:\s*"/i.exec(t);if(e){let r=e.index+e[0].length,i=t.slice(r),a=/",\s*"(?:path|file_path|filePath)"/i.exec(i);i=a?i.slice(0,a.index):i.replace(/\s*(?:\.\.\.\s*\[truncated\])?\s*"?\s*}?\s*$/,``),n=Dh(i)}else n=Dh(t)}let r=n?n.split(`
|
|
47
|
-
`).length:0;return{filePath:a,toolName:e,isWrite:!0,language:c,content:n,isStreamingPartial:o,stats:{additions:r,deletions:0,totalLines:r,isNewFile:!0},hunks:[]}}let l=n&&typeof n==`object`&&typeof n.patch==`string`?n.patch:void 0;if(l){let t=Ah(l);if(t.hunks.length>0&&t.hunks.some(e=>e.lines.length>0))return{filePath:a,toolName:e,isWrite:!1,language:c,stats:t.stats,hunks:t.hunks,isStreamingPartial:!1}}let u=n&&typeof n==`object`&&typeof n.diff==`string`?n.diff:void 0;if(u){let t=Ah(u);if(t.hunks.length>0&&t.hunks.some(e=>e.lines.length>0))return{filePath:a,toolName:e,isWrite:!1,language:c,stats:t.stats,hunks:t.hunks,isStreamingPartial:!1}}let d=[];if(s&&Array.isArray(s.edits)&&(d=s.edits),d.length>0){let{hunks:t,stats:n}=jh(d);return{filePath:a,toolName:e,isWrite:!1,language:c,stats:n,hunks:t,isStreamingPartial:o}}return{filePath:a,toolName:e,isWrite:!1,language:c,stats:{additions:0,deletions:0},hunks:[],isStreamingPartial:!0}}function Nh(e,t){let n=new Map,r=e?.answers;if(Array.isArray(r)){for(let e of r)e&&typeof e.id==`string`&&n.set(e.id,{id:e.id,selected:Array.isArray(e.selected)?e.selected:[],custom:typeof e.custom==`string`?e.custom:void 0});if(n.size>0)return n}if(t&&!t.includes(`User cancelled`)){let e=t.split(`
|
|
48
|
-
`).filter(e=>e.trim());for(let t of e){let e=t.indexOf(`:`);if(e===-1)continue;let r=t.slice(0,e).trim(),i=t.slice(e+1).trim(),a=[],o,s=/\s*\(wrote:\s*(.*?)\)$/i.exec(i),c=i;s&&(o=s[1],c=i.slice(0,s.index).trim()),c&&c!==`(no selection)`&&(a=c.split(`,`).map(e=>e.trim()).filter(Boolean)),n.set(r,{id:r,selected:a,custom:o})}}return n}function Ph(e){if(!e)return;let t=/(?:User note \/ 附言|附言)[::]\s*([^\n\r]+)/.exec(e);return t?t[1].trim():void 0}var Fh=(0,Q.memo)(function({questions:e,details:t,output:n,isError:r=!1,waiting:i=!1}){let a=X(),o=(0,Q.useMemo)(()=>Nh(t,n),[t,n]),s=(0,Q.useMemo)(()=>r?Ph(n):void 0,[r,n]);return(0,$.jsxs)(`div`,{className:`qcard-wrap`,children:[r&&(0,$.jsxs)(`div`,{className:`qcard-status qcard-status-cancelled`,children:[(0,$.jsx)(`span`,{className:`qcard-status-icon`,children:(0,$.jsx)(Ct,{})}),(0,$.jsx)(`span`,{className:`qcard-status-text`,children:a(`questionCardCancelled`)}),s&&(0,$.jsxs)(`div`,{className:`qcard-reject-reason`,children:[(0,$.jsx)(de,{className:`qcard-note-icon`}),(0,$.jsxs)(`span`,{children:[(0,$.jsxs)(`strong`,{children:[a(`questionCardRejectReason`),`:`]}),` `,s]})]})]}),i&&!r&&(0,$.jsxs)(`div`,{className:`qcard-status qcard-status-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),(0,$.jsx)(`span`,{className:`qcard-status-text`,children:a(`questionCardWaiting`)})]}),(0,$.jsx)(`div`,{className:`qcard-items`,children:e.map((e,t)=>{let n=o.get(e.id),r=new Set(n?.selected??[]),i=n!==void 0,s=e.options??[];return(0,$.jsxs)(`div`,{className:`qcard-item`,children:[(0,$.jsxs)(`div`,{className:`qcard-header`,children:[(0,$.jsx)(`span`,{className:`qcard-idx`,children:t+1}),(0,$.jsx)(`span`,{className:`qcard-title`,children:`${a(`modelQuestion`)} ${t+1}`})]}),(0,$.jsx)(`div`,{className:`qcard-question`,children:(0,$.jsx)(nl,{text:e.question,rawHtml:!0})}),s.length>0&&(0,$.jsx)(`div`,{className:`qcard-options`,children:s.map(t=>{let n=r.has(t.label);return(0,$.jsxs)(`div`,{className:`qcard-option${n?` selected`:``}${i&&!n?` dimmed`:``}`,children:[(0,$.jsx)(`span`,{className:`qcard-opt-mark`,children:e.multiSelect?n?(0,$.jsx)(z,{className:`qcard-check-icon`}):`☐`:n?`●`:`○`}),(0,$.jsx)(`div`,{className:`qcard-opt-content`,children:(0,$.jsx)(`div`,{className:`qcard-opt-label`,children:(0,$.jsx)(nl,{text:t.label,rawHtml:!0})})})]},t.label)})}),i&&r.size===0&&!n.custom&&(0,$.jsx)(`div`,{className:`qcard-empty-sel`,children:a(`questionCardNoSelection`)}),n?.custom&&(0,$.jsxs)(`div`,{className:`qcard-custom-note`,children:[(0,$.jsx)(C,{className:`qcard-note-icon`}),(0,$.jsxs)(`span`,{className:`qcard-custom-label`,children:[a(`questionCardUserCustom`),`:`]}),(0,$.jsx)(`span`,{className:`qcard-custom-text`,children:n.custom})]})]},e.id)})})]})}),Ih=(0,Q.memo)(function({toolName:e,argumentsText:t,details:n,output:r,isError:i,onOpenInspector:a}){let o=X(),[s,c]=(0,Q.useState)(`unified`),[l,u]=(0,Q.useState)(!1),d=Rt(l),{copied:f,copy:p}=Gn({duration:1200}),m=(0,Q.useMemo)(()=>Mh(e,t,n,r),[e,t,n,r]),h=(0,Q.useMemo)(()=>{if(!n||typeof n!=`object`)return``;try{return JSON.stringify(n,null,2)}catch{return``}},[n]);(0,Q.useEffect)(()=>{if(!l)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),u(!1))};return window.addEventListener(`keydown`,e,{capture:!0}),()=>window.removeEventListener(`keydown`,e,{capture:!0})},[l]);let g=e=>{e.stopPropagation(),m?.isWrite&&m.content?p(m.content):t&&p(t)},_=e=>{if(e.stopPropagation(),!m?.filePath)return;let t=m.filePath.split(`/`).pop()||m.filePath;Jt({path:m.filePath,name:t})},v=e=>{e.stopPropagation(),u(e=>!e),a?.()};if(!m||s===`raw`)return(0,$.jsxs)(`div`,{className:`file-diff-raw-wrap`,children:[(0,$.jsxs)(`div`,{className:`file-diff-toolbar`,children:[(0,$.jsx)(`span`,{className:`file-diff-path`,children:m?.filePath||e}),(0,$.jsxs)(`div`,{className:`file-diff-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`unified`)},children:o(`diffViewUnified`)}),!m?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`split`)},children:o(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`raw`)},children:o(`diffViewRaw`)}),a&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:o(`diffFullscreen`),"aria-label":o(`diffFullscreen`),onClick:v,children:(0,$.jsx)(F,{})})]})]}),(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,o(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:t||o(`toolInspectorNoArguments`)})]}),h&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,o(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[Object.keys(n).length,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:h})]})]})]});let y=()=>m.isWrite?(0,$.jsx)(Lh,{content:m.content||``}):s===`split`?(0,$.jsx)(Bh,{hunks:m.hunks,isStreaming:m.isStreamingPartial,fallbackText:t}):(0,$.jsx)(Rh,{hunks:m.hunks,isStreaming:m.isStreamingPartial,fallbackText:t});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`file-diff-card${i?` is-err`:``}`,children:[(0,$.jsxs)(`div`,{className:`file-diff-toolbar`,children:[(0,$.jsxs)(`div`,{className:`file-diff-info`,children:[(0,$.jsx)(vt,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:m.filePath,children:m.filePath||e}),m.language&&m.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:m.language}),m.isStreamingPartial&&(0,$.jsx)(`span`,{className:`file-diff-streaming-badge`,children:o(`diffStreaming`)}),m.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:o(`diffNewFile`)}):(m.stats.additions>0||m.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[m.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,m.stats.additions]}),m.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,m.stats.deletions]})]})]}),(0,$.jsxs)(`div`,{className:`file-diff-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`unified`)},children:o(`diffViewUnified`)}),!m.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`split`)},children:o(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`raw`)},children:o(`diffViewRaw`)})]}),m.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:o(`diffOpenFile`),"aria-label":o(`diffOpenFile`),onClick:_,children:(0,$.jsx)(Be,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:o(`diffFullscreen`),"aria-label":o(`diffFullscreen`),onClick:v,children:(0,$.jsx)(F,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${f?` copied`:``}`,title:m.isWrite?o(`diffCopyContent`):o(`diffCopyPatch`),"aria-label":m.isWrite?o(`diffCopyContent`):o(`diffCopyPatch`),onClick:g,children:f?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-body`,children:y()})]}),l&&(0,Er.createPortal)((0,$.jsx)(`div`,{className:`file-diff-fullscreen-backdrop`,style:{zIndex:d},role:`dialog`,"aria-modal":`true`,onClick:e=>{e.target===e.currentTarget&&u(!1)},children:(0,$.jsxs)(`div`,{className:`file-diff-fullscreen-dialog`,children:[(0,$.jsxs)(`div`,{className:`file-diff-fullscreen-header`,children:[(0,$.jsxs)(`div`,{className:`file-diff-info`,children:[(0,$.jsx)(vt,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:m.filePath,children:m.filePath||e}),m.language&&m.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:m.language}),m.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:o(`diffNewFile`)}):(m.stats.additions>0||m.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[m.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,m.stats.additions]}),m.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,m.stats.deletions]})]})]}),(0,$.jsxs)(`div`,{className:`file-diff-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`unified`)},children:o(`diffViewUnified`)}),!m.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`split`)},children:o(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${s===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),c(`raw`)},children:o(`diffViewRaw`)})]}),m.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:o(`diffOpenFile`),"aria-label":o(`diffOpenFile`),onClick:_,children:(0,$.jsx)(Be,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${f?` copied`:``}`,title:m.isWrite?o(`diffCopyContent`):o(`diffCopyPatch`),"aria-label":m.isWrite?o(`diffCopyContent`):o(`diffCopyPatch`),onClick:g,children:f?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${o(`diffRestoreScreen`)} (ESC)`,"aria-label":o(`diffRestoreScreen`),onClick:e=>{e.stopPropagation(),u(!1)},children:(0,$.jsx)(Mt,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${o(`close`)} (ESC)`,"aria-label":o(`close`),onClick:e=>{e.stopPropagation(),u(!1)},children:(0,$.jsx)(Ct,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-fullscreen-body`,children:y()})]})}),document.body)]})});function Lh({content:e,startLine:t=1}){let n=(0,Q.useMemo)(()=>e?e.split(`
|
|
49
|
-
`):[],[e]);return(0,$.jsx)(`div`,{className:`diff-code-table`,children:n.map((e,n)=>(0,$.jsxs)(`div`,{className:`diff-code-row`,children:[(0,$.jsx)(`span`,{className:`diff-line-num`,children:t+n}),(0,$.jsx)(`span`,{className:`diff-line-text`,children:e||` `})]},n))})}function Rh({hunks:e,isStreaming:t,fallbackText:n}){let r=X();return e.length===0?t?(0,$.jsxs)(`div`,{className:`diff-empty-tip`,children:[`⚡ `,r(`diffStreaming`)]}):n?(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:n}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:r(`diffEmptyHunks`)}):(0,$.jsx)(`div`,{className:`diff-unified-view`,children:e.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-hunk-section`,children:[(0,$.jsx)(`div`,{className:`diff-hunk-header`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.lines.map((e,t)=>(0,$.jsx)(zh,{line:e},t))]},t))})}function zh({line:e}){let t=e.type===`add`?`+`:e.type===`del`?`-`:` `,n=e.type===`del`?e.oldLineNum:e.newLineNum;return(0,$.jsxs)(`div`,{className:`diff-line-row ${e.type}`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:n??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:t}),(0,$.jsx)(`span`,{className:`diff-line-content`,children:e.tokens&&e.tokens.length>0?e.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`add`?`char-add`:e.type===`del`?`char-del`:void 0,children:e.text},t)):e.content||` `})]})}function Bh({hunks:e,isStreaming:t,fallbackText:n}){let r=X(),i=(0,Q.useRef)(null),a=(0,Q.useRef)(null),o=(0,Q.useRef)(null);if(e.length===0)return t?(0,$.jsxs)(`div`,{className:`diff-empty-tip`,children:[`⚡ `,r(`diffStreaming`)]}):n?(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:n}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:r(`diffEmptyHunks`)});let s=e=>{o.current!==`right`&&(o.current=`left`,a.current&&(a.current.scrollTop=e.currentTarget.scrollTop),requestAnimationFrame(()=>{o.current=null}))},c=e=>{o.current!==`left`&&(o.current=`right`,i.current&&(i.current.scrollTop=e.currentTarget.scrollTop),requestAnimationFrame(()=>{o.current=null}))},l=(0,Q.useMemo)(()=>e.map(e=>{let t=[],n=0;for(;n<e.lines.length;){let r=e.lines[n];if(r.type===`context`)t.push({left:r,right:r}),n++;else if(r.type===`del`){let i=e.lines[n+1];i&&i.type===`add`?(t.push({left:r,right:i}),n+=2):(t.push({left:r,right:void 0}),n++)}else r.type===`add`&&t.push({left:void 0,right:r}),n++}return{header:e.header,pairs:t}}),[e]);return(0,$.jsxs)(`div`,{className:`diff-split-container`,children:[(0,$.jsxs)(`div`,{ref:i,className:`diff-split-column left`,onScroll:s,children:[(0,$.jsx)(`div`,{className:`diff-split-pane-header`,children:(0,$.jsx)(`span`,{className:`diff-header-text`,children:`BEFORE (ORIGINAL)`})}),(0,$.jsx)(`div`,{className:`diff-split-lines`,children:l.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-hunk-group`,children:[(0,$.jsx)(`div`,{className:`diff-split-hunk-bar`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.pairs.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-line-box${e.left?` ${e.left.type}`:` empty`}`,children:[(0,$.jsxs)(`div`,{className:`diff-split-gutter`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:e.left?.oldLineNum??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:e.left?.type===`del`?`-`:` `})]}),(0,$.jsx)(`span`,{className:`diff-line-code`,children:e.left?.tokens&&e.left.tokens.length>0?e.left.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`del`?`char-del`:void 0,children:e.text},t)):e.left?.content||` `})]},t))]},t))})]}),(0,$.jsx)(`div`,{className:`diff-split-divider`}),(0,$.jsxs)(`div`,{ref:a,className:`diff-split-column right`,onScroll:c,children:[(0,$.jsx)(`div`,{className:`diff-split-pane-header`,children:(0,$.jsx)(`span`,{className:`diff-header-text`,children:`AFTER (MODIFIED)`})}),(0,$.jsx)(`div`,{className:`diff-split-lines`,children:l.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-hunk-group`,children:[(0,$.jsx)(`div`,{className:`diff-split-hunk-bar`,children:(0,$.jsx)(`span`,{className:`diff-hunk-text`,children:e.header})}),e.pairs.map((e,t)=>(0,$.jsxs)(`div`,{className:`diff-split-line-box${e.right?` ${e.right.type}`:` empty`}`,children:[(0,$.jsxs)(`div`,{className:`diff-split-gutter`,children:[(0,$.jsx)(`span`,{className:`diff-gutter-num`,children:e.right?.newLineNum??``}),(0,$.jsx)(`span`,{className:`diff-gutter-sym`,children:e.right?.type===`add`?`+`:` `})]}),(0,$.jsx)(`span`,{className:`diff-line-code`,children:e.right?.tokens&&e.right.tokens.length>0?e.right.tokens.map((e,t)=>(0,$.jsx)(`span`,{className:e.type===`add`?`char-add`:void 0,children:e.text},t)):e.right?.content||` `})]},t))]},t))})]})]})}var Vh=50,Hh=(0,Q.memo)(function({task:e}){let t=X(),n=e.exitCode!==void 0&&e.exitCode!==0?`exit=${e.exitCode}`:``,r=e.error||e.command||``,i=[`${e.id} ${t(Wt(e.status))}${e.exitCode===void 0?``:` exit=${e.exitCode}`}`,e.name?`— ${e.name}`:``,e.outputPath].filter(Boolean);return(0,$.jsxs)(`div`,{className:`bgc-row`,title:i.join(`
|
|
50
|
-
`),children:[(0,$.jsx)(`span`,{className:qt(e.status),"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`bgc-id`,children:e.id}),(0,$.jsx)(`span`,{className:`bgc-status`,children:t(Wt(e.status))}),n&&(0,$.jsx)(`span`,{className:`bgc-exit`,children:n}),r&&(0,$.jsx)(`span`,{className:`bgc-name`,children:e.name||r||e.outputPath})]})}),Uh=(0,Q.memo)(function({entries:e,rawOutput:t,isError:n=!1,running:r=!1}){let i=X(),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1);if(e.length===0)return null;let l=e.filter(e=>e.status===`running`).length,u=e.length,d=u>Vh,f=d?e.slice(0,Vh):e,p=d?`${f.length}/${u}`:String(u),m=l>0?i(`bgTasksRunning`,{count:p,running:l}):i(`bgTasksSummary`,{count:p});return(0,$.jsxs)(`div`,{className:`bgc`,children:[(0,$.jsxs)(`div`,{className:`bgc-head`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`bgc-toggle`,onClick:()=>o(e=>!e),"aria-expanded":a,title:i(`expandMsg`),children:[(0,$.jsx)(`span`,{className:`bgc-caret`,"aria-hidden":!0,children:a?`▾`:`▸`}),(0,$.jsxs)(`span`,{className:`bgc-title`,children:[`◉ `,i(`bgTasksTitle`)]}),(0,$.jsx)(`span`,{className:`bgc-count`,children:m})]}),(0,$.jsx)(`button`,{type:`button`,className:`bgc-raw-btn`,onClick:()=>c(e=>!e),"aria-pressed":s,children:i(s?`bgTasksHideRaw`:`bgTasksRaw`)})]}),a&&(0,$.jsx)(`div`,{className:`bgc-list`,role:`list`,children:f.map(e=>(0,$.jsx)(Hh,{task:e},e.id))}),s&&(0,$.jsxs)(`div`,{className:`toolcall-output bgc-raw`,children:[(0,$.jsxs)(`div`,{className:`toolcall-output-label`,children:[i(n?`errorOutput`:`output`),r&&(0,$.jsx)(`span`,{className:`cursor`})]}),(0,$.jsx)(`pre`,{children:t})]})]})});function Wh(e){let t=typeof e.name==`string`?e.name:``;if(e.unsupported===!0)return{name:t,status:`unsupported`};if(e.found!==!0)return{name:t,status:`missing`};let n={name:t,status:`ready`};return e.label&&(n.label=e.label),e.description&&(n.description=e.description),e.promptSnippet&&(n.promptSnippet=e.promptSnippet),Array.isArray(e.promptGuidelines)&&e.promptGuidelines.length>0&&(n.promptGuidelines=e.promptGuidelines),e.parameters!==void 0&&(n.parameters=e.parameters),e.parametersDropped===!0&&(n.parametersDropped=!0),(e.active===!0||e.active===!1)&&(n.active=e.active),e.source&&(n.source=e.source),e.scope&&(n.scope=e.scope),n}var Gh=null,Kh=new Set;function qh(){for(let e of Kh)e()}function Jh(e){let t=(e??``).trim();t&&(Gh={name:t,status:`loading`},qh(),Z({type:`get_tool_info`,name:t}))}function Yh(){Gh!==null&&(Gh=null,qh())}function Xh(e){Gh!==null&&Gh.name===e.name&&(Gh=Wh(e),qh())}function Zh(e){return Kh.add(e),()=>{Kh.delete(e)}}function Qh(){return Gh}function $h(){return(0,Q.useSyncExternalStore)(Zh,Qh,Qh)}var eg={projects:`host:lp-projects`,groups:`host:lp-groups`,convs:`host:lp-running`,sessions:`host:lp-history`},tg=[`projects`,`convs`,`sessions`],ng=new Map(Object.keys(eg).map(e=>[eg[e],e])),rg=`plugin:`;function ig(e){return e.startsWith(rg)&&e.length>7}function ag(e){let t=[],n=new Set;for(let r of e??[]){let e=null,i,a=ng.get(r.id);a?e=a:r.source?.startsWith(`plugin:`)&&r.kind===`view`&&(e=`${rg}${r.id}`,i=r),e&&!n.has(e)&&(n.add(e),t.push({key:e,shown:!r.hidden,...i?{entry:i}:{}}))}for(let e of tg)n.has(e)||t.push({key:e,shown:!0});return t}function og(e){if(e.some(e=>e.key===`groups`))return[...e];let t=[...e],n=t.findIndex(e=>e.key===`projects`&&e.shown);return t.splice(n+1,0,{key:`groups`,shown:!0}),t}function sg(e,t){let n=[];for(let r=0;r+1<e.length;r++){let i=e[r],a=e[r+1];!t(i)&&!t(a)&&n.push([i,a])}return n}function cg(e,t){let n={...t};if(!e)return n;try{let r=JSON.parse(e);if(!r||typeof r!=`object`||Array.isArray(r))return n;for(let[e,i]of Object.entries(r))(e in t||ig(e))&&typeof i==`number`&&Number.isFinite(i)&&i>0&&(n[e]=i)}catch{}return n}var lg=[`superagent`];function ug(e){return lg.some(t=>t===e)}function dg(e){return e.filter(e=>!ug(e.id))}var fg=new Set([`view`,`action`,`badge`,`menu`,`page`,`organizer`,`divider`,`toggle`,`input`,`progress`,`select`]),pg=new Set([`disabled`,`always`,`never`,`file.isDir`,`file.isFile`,`session.isRunning`,`message.hasSelection`,`search.isSession`,`search.isProject`,`search.isFile`,`search.isFolder`,`search.isPlugin`]),mg=`topbar.primary,topbar.overflow,notice.actions,leftpanel.sections,leftpanel.projects.actions,leftpanel.project,leftpanel.running.actions,leftpanel.running,leftpanel.history.actions,leftpanel.history,leftpanel.sessions,chat.header,chat.empty,message.actions,goalbar.actions,composer.leading,composer.actions,rightpanel.tabs,bottomdock.tabs,terminal.toolbar,scm.toolbar,bottombar,file.preview.toolbar,contextmenu.topbar,contextmenu.message,contextmenu.session,contextmenu.project,contextmenu.file,contextmenu.search,contextmenu.toolcall,contextmenu.bot,tool.card.footer,settings.pages,tasks.panel,modal.dialog,sidebar.left,sidebar.right,device.group.header,device.group.actions,device.group.workspace`.split(`,`),hg=mg.map(e=>({slot:e,cardinality:`list`}));function gg(e){return hg.find(t=>t.slot===e)?.cardinality??`list`}function _g(e,t){if(t===`list`)return{entries:[...e],conflicts:[]};let n=e.findIndex(e=>!e.hidden);if(n<0)return{entries:[...e],conflicts:[]};let r=e.filter((e,t)=>t!==n&&!e.hidden);return{entries:e.map((e,t)=>t===n||e.hidden?e:{...e,hidden:!0}),winner:e[n],conflicts:r}}var vg=[{id:`host:lp-projects`,slot:`leftpanel.sections`,labelKey:`recentProjects`,icon:`folder`,kind:`action`,order:10},{id:`host:lp-groups`,slot:`leftpanel.sections`,labelKey:`leftPanelGroups`,icon:`users`,kind:`action`,order:15},{id:`host:lp-running`,slot:`leftpanel.sections`,labelKey:`runningConversations`,icon:`activity`,kind:`action`,order:20},{id:`host:lp-history`,slot:`leftpanel.sections`,labelKey:`historySessions`,icon:`clock`,kind:`action`,order:30},{id:`host:brand`,slot:`topbar.primary`,labelKey:`brand`,kind:`badge`,order:1,group:`brand`},{id:`host:open-project`,slot:`topbar.primary`,labelKey:`openProject`,icon:`folder`,kind:`action`,order:3,group:`primary`},{id:`host:worktrees`,slot:`topbar.primary`,labelKey:`worktreeViewTitle`,icon:`folders`,kind:`action`,order:4,group:`primary`},{id:`host:history`,slot:`topbar.primary`,labelKey:`openHistory`,icon:`menu`,kind:`action`,order:0,group:`panels`},{id:`host:files`,slot:`topbar.primary`,labelKey:`openFiles`,icon:`folder`,kind:`action`,order:97,group:`panels`,align:`end`},{id:`host:new-chat`,slot:`topbar.primary`,labelKey:`newChat`,icon:`plus`,kind:`action`,order:96,group:`primary`,align:`end`,hidden:!0},{id:`host:new-cli`,slot:`topbar.primary`,labelKey:`nativeCliCreate`,icon:`command`,kind:`action`,order:96.2,group:`primary`,align:`end`,hidden:!0},{id:`host:new-ephemeral-chat`,slot:`topbar.primary`,labelKey:`newChatEphemeral`,icon:`chat`,kind:`action`,order:96.5,group:`primary`,align:`end`},{id:`host:new-sandbox`,slot:`topbar.primary`,labelKey:`newSandbox`,icon:`sandbox`,kind:`action`,order:96.6,group:`primary`,align:`end`},{id:`host:chat`,slot:`topbar.primary`,labelKey:`chat`,icon:`chat`,kind:`view`,view:`chat`,order:20,group:`views`,align:`end`},{id:`host:terminal`,slot:`topbar.primary`,labelKey:`terminal`,icon:`terminal`,kind:`view`,view:`terminal`,order:21,group:`views`,align:`end`},{id:`host:git`,slot:`topbar.primary`,labelKey:`scmTab`,icon:`git`,kind:`view`,view:`git`,order:22,group:`views`,align:`end`,hidden:!0},{id:`host:canvas`,slot:`topbar.primary`,labelKey:`canvasTab`,icon:`share`,kind:`view`,view:`canvas`,order:22.5,group:`views`,align:`end`},{id:`host:plugins`,slot:`topbar.primary`,labelKey:`pluginMenuTitle`,icon:`🧩`,kind:`action`,order:24,group:`views`,align:`end`},{id:`host:search`,slot:`topbar.primary`,labelKey:`searchGlobal`,icon:`search`,kind:`action`,order:40,group:`tools`,align:`end`},{id:`host:browser`,slot:`topbar.primary`,labelKey:`browserControl`,icon:`browser`,kind:`action`,order:41,group:`tools`,align:`end`,hidden:!0},{id:`host:tasks`,slot:`topbar.primary`,labelKey:`bgTasks`,icon:`layers`,kind:`action`,order:42,group:`tools`,align:`end`},{id:`host:zen-mode`,slot:`topbar.primary`,labelKey:`zenMode`,icon:`feather`,kind:`action`,order:43,group:`tools`,align:`end`},{id:`host:quiet-mode`,slot:`topbar.primary`,labelKey:`quietMode`,icon:`eye`,kind:`action`,order:44,group:`tools`,align:`end`},{id:`host:device-center`,slot:`topbar.primary`,labelKey:`deviceCenter`,icon:`globe`,kind:`view`,view:`devices`,order:59,group:`system`,align:`end`},{id:`host:settings`,slot:`topbar.primary`,labelKey:`settingsTitle`,icon:`settings`,kind:`action`,order:60,group:`system`,align:`end`},{id:`host:language`,slot:`topbar.primary`,labelKey:`language`,icon:`globe`,kind:`action`,order:80,group:`system`,hidden:!0,align:`end`},{id:`host:theme`,slot:`topbar.primary`,labelKey:`theme`,icon:`sun`,kind:`action`,order:82,group:`system`,hidden:!0,align:`end`},{id:`host:update`,slot:`topbar.primary`,labelKey:`update`,icon:`download`,kind:`action`,order:90,group:`system`,align:`end`,hidden:!0},{id:`host:github`,slot:`topbar.primary`,labelKey:`githubRepo`,icon:`github`,kind:`action`,order:200,group:`system`,align:`end`,hidden:!0},{id:`host:conn`,slot:`bottombar`,labelKey:`connected`,icon:`dot`,kind:`badge`,order:5,group:`status`},{id:`host:engine`,slot:`bottombar`,labelKey:`engineBadge`,icon:`aperture`,kind:`action`,order:6,group:`status`},{id:`host:ctx`,slot:`bottombar`,labelKey:`context`,icon:`gauge`,kind:`badge`,order:10,group:`usage`},{id:`host:cost`,slot:`bottombar`,labelKey:`cumulativeCost`,icon:`coins`,kind:`badge`,order:11,group:`usage`},{id:`host:cache`,slot:`bottombar`,labelKey:`cacheHit`,icon:`database`,kind:`badge`,order:12,group:`usage`},{id:`host:msg-count`,slot:`bottombar`,labelKey:`messages`,icon:`message`,kind:`badge`,order:13,group:`usage`},{id:`host:plugin-status`,slot:`bottombar`,labelKey:`pluginStatus`,icon:`activity`,kind:`badge`,order:14,group:`status`},{id:`host:working`,slot:`bottombar`,labelKey:`working`,icon:`activity`,kind:`badge`,order:15,group:`status`},{id:`host:status-delegate`,slot:`bottombar`,labelKey:`delegateModeBadge`,icon:`eye`,kind:`badge`,order:16,group:`status`},{id:`host:host-metrics`,slot:`bottombar`,labelKey:`hostResources`,icon:`cpu`,kind:`badge`,order:19,group:`host`,align:`end`},{id:`host:cwd`,slot:`bottombar`,labelKey:`cwdTip`,icon:`folder`,kind:`action`,order:20,group:`context`,align:`end`},{id:`host:msg-reask`,slot:`message.actions`,labelKey:`reaskDirectly`,icon:`refresh`,kind:`action`,order:9},{id:`host:msg-edit-reask`,slot:`message.actions`,labelKey:`editReask`,icon:`edit`,kind:`action`,order:10},{id:`host:msg-fork`,slot:`message.actions`,labelKey:`forkSession`,icon:`branch`,kind:`action`,order:15},{id:`host:msg-rollback`,slot:`message.actions`,labelKey:`rollbackSession`,icon:`undo`,kind:`action`,order:16},{id:`host:msg-copy`,slot:`message.actions`,labelKey:`copyMessage`,icon:`copy`,kind:`action`,order:20},{id:`host:msg-copy-text`,slot:`message.actions`,labelKey:`copyText`,icon:`text`,kind:`action`,order:21},{id:`host:msg-copy-markdown`,slot:`message.actions`,labelKey:`copyMarkdown`,icon:`markdown`,kind:`action`,order:22},{id:`host:msg-copy-image`,slot:`message.actions`,labelKey:`copyImage`,icon:`image`,kind:`action`,order:23},{id:`host:msg-speak`,slot:`message.actions`,labelKey:`speakMsg`,icon:`volume`,kind:`action`,order:24},{id:`host:msg-delete`,slot:`message.actions`,labelKey:`delete`,icon:`trash`,kind:`action`,order:30,hidden:!0},{id:`host:composer-upload`,slot:`composer.actions`,labelKey:`uploadFile`,icon:`upload`,kind:`action`,order:10,align:`start`},{id:`host:composer-screenshot`,slot:`composer.actions`,labelKey:`screenshotCapture`,icon:`cut`,kind:`action`,order:115,align:`start`},{id:`host:composer-templates`,slot:`composer.actions`,labelKey:`tpl.openPicker`,icon:`grid`,kind:`action`,order:110,align:`start`},{id:`host:composer-model`,slot:`composer.actions`,labelKey:`selectModel`,icon:`cpu`,kind:`action`,order:120,align:`start`},{id:`host:composer-thinking`,slot:`composer.actions`,labelKey:`thinkingLevel`,icon:`zap`,kind:`action`,order:130,align:`start`},{id:`host:composer-claude-perm`,slot:`composer.actions`,labelKey:`claudePermDefault`,icon:`lock`,kind:`action`,order:138,align:`start`},{id:`host:composer-dsh-perm`,slot:`composer.actions`,labelKey:`dshPerm`,icon:`lock`,kind:`action`,order:140,align:`start`},{id:`host:composer-dsh-preset`,slot:`composer.actions`,labelKey:`dshPreset`,icon:`layers`,kind:`action`,order:150,align:`start`},{id:`host:composer-send`,slot:`composer.actions`,labelKey:`sendTip`,icon:`send`,kind:`action`,order:200,align:`end`},{id:`host:fp-md`,slot:`file.preview.toolbar`,labelKey:`showMarkdownPreview`,icon:`eye`,kind:`action`,order:10},{id:`host:fp-toc`,slot:`file.preview.toolbar`,labelKey:`previewTocLabel`,icon:`list`,kind:`action`,order:15},{id:`host:fp-html`,slot:`file.preview.toolbar`,labelKey:`showHtmlPreview`,icon:`code`,kind:`action`,order:20},{id:`host:fp-external`,slot:`file.preview.toolbar`,labelKey:`openInNewTab`,icon:`open`,kind:`action`,order:25},{id:`host:fp-edit`,slot:`file.preview.toolbar`,labelKey:`editFile`,icon:`edit`,kind:`action`,order:30},{id:`host:fp-wrap`,slot:`file.preview.toolbar`,labelKey:`enableWrap`,icon:`wrap`,kind:`action`,order:40},{id:`host:fp-zoom`,slot:`file.preview.toolbar`,labelKey:`zoomIn`,icon:`zoom`,kind:`action`,order:50},{id:`host:fp-download`,slot:`file.preview.toolbar`,labelKey:`downloadFile`,icon:`download`,kind:`action`,order:60},{id:`host:fp-ref`,slot:`file.preview.toolbar`,labelKey:`referenceTip`,icon:`link`,kind:`action`,order:70},{id:`host:fp-full`,slot:`file.preview.toolbar`,labelKey:`fullscreen`,icon:`maximize`,kind:`action`,order:80},{id:`host:fp-close`,slot:`file.preview.toolbar`,labelKey:`close`,icon:`x`,kind:`action`,order:90},{id:`host:goal-pill`,slot:`goalbar.actions`,labelKey:`goalBarTitle`,icon:`target`,kind:`action`,order:5},{id:`host:goal-set`,slot:`goalbar.actions`,labelKey:`goalComposeEnter`,icon:`check`,kind:`action`,order:10},{id:`host:goal-wizard`,slot:`goalbar.actions`,labelKey:`goalWizardBtn`,icon:`search`,kind:`action`,order:20},{id:`host:goal-lock`,slot:`goalbar.actions`,labelKey:`goalBarLocked`,icon:`lock`,kind:`action`,order:30},{id:`host:goal-plan`,slot:`goalbar.actions`,labelKey:`planMode`,icon:`list`,kind:`action`,order:25},{id:`host:goal-collapse`,slot:`goalbar.actions`,labelKey:`collapsePanel`,icon:`chevron-up`,kind:`action`,order:40},{id:`host:goal-model`,slot:`goalbar.actions`,labelKey:`goalBarReviewModel`,icon:`cpu`,kind:`action`,order:50},{id:`host:goal-rounds`,slot:`goalbar.actions`,labelKey:`goalBarMaxRounds`,icon:`hash`,kind:`action`,order:60},{id:`host:goal-execmodel`,slot:`goalbar.actions`,labelKey:`goalBarExecModel`,icon:`cpu`,kind:`action`,order:55},{id:`host:goal-openrole`,slot:`goalbar.actions`,labelKey:`goalBarOpenExec`,icon:`search`,kind:`action`,order:65},{id:`host:goal-clear`,slot:`goalbar.actions`,labelKey:`goalBarClear`,icon:`x`,kind:`action`,order:70},{id:`host:scm-changes`,slot:`scm.toolbar`,labelKey:`scmChanges`,icon:`file`,kind:`action`,order:10},{id:`host:scm-history`,slot:`scm.toolbar`,labelKey:`scmHistory`,icon:`clock`,kind:`action`,order:20},{id:`host:scm-refresh`,slot:`scm.toolbar`,labelKey:`scmRefreshTip`,icon:`refresh`,kind:`action`,order:30},{id:`host:scm-branch`,slot:`scm.toolbar`,labelKey:`scmSwitchBranch`,icon:`git`,kind:`action`,order:40},{id:`host:scm-push`,slot:`scm.toolbar`,labelKey:`scmPush`,icon:`upload`,kind:`action`,order:60},{id:`host:scm-pull`,slot:`scm.toolbar`,labelKey:`scmPull`,icon:`download`,kind:`action`,order:70},{id:`host:scm-input`,slot:`scm.toolbar`,labelKey:`scmCommitPlaceholder`,icon:`edit`,kind:`action`,order:80},{id:`host:scm-genmsg`,slot:`scm.toolbar`,labelKey:`scmGenMsg`,icon:`cpu`,kind:`action`,order:85},{id:`host:scm-commit`,slot:`scm.toolbar`,labelKey:`scmCommit`,icon:`check`,kind:`action`,order:90},{id:`host:scm-commit-all`,slot:`scm.toolbar`,labelKey:`scmCommitAll`,icon:`check`,kind:`action`,order:100},{id:`host:scm-term`,slot:`scm.toolbar`,labelKey:`terminal`,icon:`terminal`,kind:`action`,order:110},{id:`host:term-cmd-refresh`,slot:`terminal.toolbar`,labelKey:`rerun`,icon:`refresh`,kind:`action`,order:10},{id:`host:term-cmd-new`,slot:`terminal.toolbar`,labelKey:`newCommand`,icon:`plus`,kind:`action`,order:20},{id:`host:term-tab-new`,slot:`terminal.toolbar`,labelKey:`newTerminal`,icon:`plus`,kind:`action`,order:30},{id:`host:right-files`,slot:`rightpanel.tabs`,labelKey:`openFiles`,icon:`folder`,kind:`view`,view:`files`,order:10},{id:`host:right-scm`,slot:`rightpanel.tabs`,labelKey:`scmTitle`,icon:`git`,kind:`view`,view:`scm`,order:20},{id:`host:bottom-terminal`,slot:`bottomdock.tabs`,labelKey:`terminal`,icon:`terminal`,kind:`view`,view:`terminal`,order:10},{id:`host:conv-rename`,slot:`contextmenu.session`,labelKey:`renameSession`,icon:`edit`,kind:`action`,context:`session`,order:1},{id:`host:conv-pin`,slot:`contextmenu.session`,labelKey:`pinConversation`,icon:`pin`,kind:`action`,context:`session`,order:2},{id:`host:conv-takeover`,slot:`contextmenu.session`,labelKey:`takeoverConversation`,icon:`chat`,kind:`action`,context:`session`,order:5},{id:`host:conv-dismiss-subagents`,slot:`contextmenu.session`,labelKey:`dismissFinishedSubagents`,icon:`x`,kind:`action`,context:`session`,order:10},{id:`host:conv-force-dismiss`,slot:`contextmenu.session`,labelKey:`forceDismissConversation`,icon:`x`,kind:`action`,context:`session`,order:20},{id:`host:conv-persist`,slot:`contextmenu.session`,labelKey:`persistSubagent`,icon:`save`,kind:`action`,context:`session`,order:25},{id:`host:conv-copy-id`,slot:`contextmenu.session`,labelKey:`copyConversationId`,icon:`copy`,kind:`action`,context:`session`,order:30},{id:`host:conv-copy-path`,slot:`contextmenu.session`,labelKey:`copyConversationPath`,icon:`copy`,kind:`action`,context:`session`,order:40},{id:`host:conv-copy-link`,slot:`contextmenu.session`,labelKey:`copyConversationLink`,icon:`link`,kind:`action`,context:`session`,order:45},{id:`host:conv-quote`,slot:`contextmenu.session`,labelKey:`quoteConversation`,icon:`chat`,kind:`action`,context:`session`,order:50},{id:`host:conv-quick-ask`,slot:`contextmenu.session`,labelKey:`quickAskReference`,icon:`chat`,kind:`action`,context:`session`,order:55},{id:`host:proj-new-chat`,slot:`contextmenu.project`,labelKey:`newChatAction`,icon:`plus`,kind:`action`,context:`project`,order:1},{id:`host:proj-rename`,slot:`contextmenu.project`,labelKey:`renameProject`,icon:`edit`,kind:`action`,context:`project`,order:2},{id:`host:proj-delete-all-sessions`,slot:`contextmenu.project`,labelKey:`deleteAllProjectSessions`,icon:`trash`,kind:`action`,context:`project`,order:3},{id:`host:search-open`,slot:`contextmenu.search`,labelKey:`gsOpen`,icon:`open`,kind:`action`,order:1,group:`open`},{id:`host:search-open-folder`,slot:`contextmenu.search`,labelKey:`searchMenuOpenInFiles`,icon:`folder`,kind:`action`,order:2,group:`open`},{id:`host:search-reveal`,slot:`contextmenu.search`,labelKey:`fileReveal`,icon:`folder`,kind:`action`,order:3,group:`open`},{id:`host:search-pin`,slot:`contextmenu.search`,labelKey:`pinConversation`,icon:`pin`,kind:`action`,order:10,group:`session`},{id:`host:search-quote`,slot:`contextmenu.search`,labelKey:`quoteConversation`,icon:`chat`,kind:`action`,order:20,group:`chat`},{id:`host:search-quick-ask`,slot:`contextmenu.search`,labelKey:`quickAskReference`,icon:`chat`,kind:`action`,order:21,group:`chat`},{id:`host:search-copy-name`,slot:`contextmenu.search`,labelKey:`copyName`,icon:`copy`,kind:`action`,order:40,group:`copy`},{id:`host:search-copy-rel`,slot:`contextmenu.search`,labelKey:`fileCopyRelPath`,icon:`copy`,kind:`action`,order:41,group:`copy`},{id:`host:search-copy-path`,slot:`contextmenu.search`,labelKey:`copyPath`,icon:`copy`,kind:`action`,order:42,group:`copy`},{id:`host:search-copy-id`,slot:`contextmenu.search`,labelKey:`copyConversationId`,icon:`copy`,kind:`action`,order:43,group:`copy`},{id:`host:file-open`,slot:`contextmenu.file`,labelKey:`fileOpenPreview`,icon:`open`,kind:`action`,context:`file`,order:11,group:`open`},{id:`host:file-open-in-editor`,slot:`contextmenu.file`,labelKey:`fileOpenInEditor`,icon:`open`,kind:`action`,context:`file`,order:12,group:`open`},{id:`host:file-enter`,slot:`contextmenu.file`,labelKey:`fileEnterDir`,icon:`folder`,kind:`action`,context:`file`,order:12,group:`open`},{id:`host:file-download`,slot:`contextmenu.file`,labelKey:`downloadFile`,icon:`download`,kind:`action`,context:`file`,order:13,group:`open`},{id:`host:file-compress`,slot:`contextmenu.file`,labelKey:`fileCompress`,icon:`file`,kind:`action`,context:`file`,order:16,group:`archive`},{id:`host:file-extract`,slot:`contextmenu.file`,labelKey:`fileExtract`,icon:`folder`,kind:`action`,context:`file`,order:17,group:`archive`},{id:`host:file-compress-download`,slot:`contextmenu.file`,labelKey:`fileCompressDownload`,icon:`download`,kind:`action`,context:`file`,order:18,group:`archive`},{id:`host:file-upload-folder`,slot:`contextmenu.file`,labelKey:`fileUploadFolder`,icon:`upload`,kind:`action`,context:`file`,order:25,group:`new`},{id:`host:file-open-project`,slot:`contextmenu.file`,labelKey:`openAsProject`,icon:`folder`,kind:`action`,context:`file`,order:14,group:`open`},{id:`host:file-add-root`,slot:`contextmenu.file`,labelKey:`addWorkspaceRoot`,icon:`folder`,kind:`action`,context:`file`,order:15,group:`open`},{id:`host:file-reveal`,slot:`contextmenu.file`,labelKey:`fileReveal`,icon:`folder`,kind:`action`,context:`file`,order:16,group:`open`},{id:`host:file-open-default`,slot:`contextmenu.file`,labelKey:`fileOpenDefault`,icon:`open`,kind:`action`,context:`file`,order:17,group:`open`},{id:`host:file-new-file`,slot:`contextmenu.file`,labelKey:`fileNewFile`,icon:`file`,kind:`action`,context:`file`,order:21,group:`new`},{id:`host:file-new-dir`,slot:`contextmenu.file`,labelKey:`fileNewDir`,icon:`folder`,kind:`action`,context:`file`,order:22,group:`new`},{id:`host:file-upload`,slot:`contextmenu.file`,labelKey:`uploadToFolder`,icon:`upload`,kind:`action`,context:`file`,order:23,group:`new`},{id:`host:file-paste`,slot:`contextmenu.file`,labelKey:`filePaste`,icon:`paste`,kind:`action`,context:`file`,order:24,group:`new`},{id:`host:file-attach-ref`,slot:`contextmenu.file`,labelKey:`referenceTip`,icon:`link`,kind:`action`,context:`file`,order:32,group:`chat`},{id:`host:file-attach-folder`,slot:`contextmenu.file`,labelKey:`linkFolderTip`,icon:`link`,kind:`action`,context:`file`,order:33,group:`chat`},{id:`host:file-quick-ask`,slot:`contextmenu.file`,labelKey:`quickAskReference`,icon:`chat`,kind:`action`,context:`file`,order:34,group:`chat`},{id:`host:file-rename`,slot:`contextmenu.file`,labelKey:`fileRename`,icon:`edit`,kind:`action`,context:`file`,order:41,group:`edit`},{id:`host:file-duplicate`,slot:`contextmenu.file`,labelKey:`fileDuplicate`,icon:`copy`,kind:`action`,context:`file`,order:42,group:`edit`},{id:`host:file-cut`,slot:`contextmenu.file`,labelKey:`fileCut`,icon:`cut`,kind:`action`,context:`file`,order:43,group:`edit`},{id:`host:file-copy`,slot:`contextmenu.file`,labelKey:`fileCopyEntry`,icon:`copy`,kind:`action`,context:`file`,order:44,group:`edit`},{id:`host:file-copy-name`,slot:`contextmenu.file`,labelKey:`copyName`,icon:`copy`,kind:`action`,context:`file`,order:51,group:`clipboard`},{id:`host:file-copy-path`,slot:`contextmenu.file`,labelKey:`copyPath`,icon:`copy`,kind:`action`,context:`file`,order:52,group:`clipboard`},{id:`host:file-copy-rel`,slot:`contextmenu.file`,labelKey:`fileCopyRelPath`,icon:`copy`,kind:`action`,context:`file`,order:53,group:`clipboard`},{id:`host:file-refresh`,slot:`contextmenu.file`,labelKey:`fileRefresh`,icon:`refresh`,kind:`action`,context:`file`,order:54,group:`clipboard`},{id:`host:file-delete`,slot:`contextmenu.file`,labelKey:`fileDelete`,icon:`trash`,kind:`action`,context:`file`,order:61,group:`danger`},{id:`host:msg-ctx-copy-markdown`,slot:`contextmenu.message`,labelKey:`copyMarkdown`,icon:`markdown`,kind:`action`,context:`message`,order:10,group:`copy`},{id:`host:msg-ctx-copy-text`,slot:`contextmenu.message`,labelKey:`copyText`,icon:`text`,kind:`action`,context:`message`,order:11,group:`copy`},{id:`host:msg-ctx-copy-image`,slot:`contextmenu.message`,labelKey:`copyImage`,icon:`image`,kind:`action`,context:`message`,order:12,group:`copy`},{id:`host:msg-ctx-copy-link`,slot:`contextmenu.message`,labelKey:`copyMessageLink`,icon:`link`,kind:`action`,context:`message`,order:13,group:`copy`},{id:`host:msg-ctx-reask`,slot:`contextmenu.message`,labelKey:`reaskDirectly`,icon:`refresh`,kind:`action`,context:`message`,order:19,group:`action`},{id:`host:msg-ctx-edit-reask`,slot:`contextmenu.message`,labelKey:`editReask`,icon:`edit`,kind:`action`,context:`message`,order:20,group:`action`},{id:`host:msg-ctx-fork`,slot:`contextmenu.message`,labelKey:`forkSession`,icon:`branch`,kind:`action`,context:`message`,order:21,group:`action`},{id:`host:msg-ctx-rollback`,slot:`contextmenu.message`,labelKey:`rollbackSession`,icon:`undo`,kind:`action`,context:`message`,order:22,group:`action`},{id:`host:msg-ctx-speak`,slot:`contextmenu.message`,labelKey:`speakMsg`,icon:`volume`,kind:`action`,context:`message`,order:23,group:`action`},{id:`host:msg-ctx-delete`,slot:`contextmenu.message`,labelKey:`delete`,icon:`trash`,kind:`action`,context:`message`,order:30,group:`danger`},{id:`host:tool-info`,slot:`contextmenu.toolcall`,labelKey:`toolInfoMenuLabel`,icon:`info`,kind:`action`,context:`toolcall`,order:10}],yg=`__view`,bg=new Set([`host:settings`,`host:history`,`host:files`]),xg=new Set([`host:history`,`host:files`,`host:lp-running`,`host:lp-history`]);function Sg(e){return`${e}:${yg}`}function Cg(e){return e.source.startsWith(`plugin:`)?e.id===Sg(e.source.slice(7)):!1}function wg(e,t,n){let r=Sg(t),i=(e?.hidden??[]).filter(e=>e!==r),a=(e?.shown??[]).filter(e=>e!==r);return n?a.push(r):i.push(r),{...e,hidden:i,shown:a}}function Tg(e,t){let n=t.map(Sg),r=new Set(n),i=(e?.order??[]).filter(e=>!r.has(e));return{...e,order:[...i,...n]}}var Eg=`host:composer-screenshot`;function Dg(e){let t=e.order??[];if(t.length===0||t.includes(Eg))return e;let n=[`host:composer-templates`,`host:composer-upload`].map(e=>t.indexOf(e)).find(e=>e>=0);if(n===void 0)return e;let r=[...t];return r.splice(n+1,0,Eg),{...e,order:r}}var Og=`host:brand`,kg=[`host:brand-logo`,`host:brand-name`];function Ag(e){if(!((e.hidden??[]).some(e=>kg.includes(e))||(e.shown??[]).some(e=>kg.includes(e))||(e.order??[]).some(e=>kg.includes(e))||kg.some(t=>e.align?.[t]!==void 0)||kg.some(t=>e.groups?.[t]!==void 0)||kg.some(t=>e.labels?.[t]!==void 0)||kg.some(t=>e.slots?.[t]!==void 0)))return e;let t=e=>{if(!e)return;let t=[];for(let n of e){let e=kg.includes(n)?Og:n;t.includes(e)||t.push(e)}return t},n=(e,t)=>{if(!e)return;let n={};for(let[t,r]of Object.entries(e))kg.includes(t)||(n[t]=r);if(n[Og]===void 0){let r=t?e[kg[0]]??e[kg[1]]:e[kg[1]]??e[kg[0]];r!==void 0&&(n[Og]=r)}return n},r=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))kg.includes(n)||(t[n]=r);if(t[Og]===void 0){let n=e[kg[0]]??e[kg[1]];n!==void 0&&(t[Og]=n)}return t},i=e=>{if(!e)return;let t={};for(let[n,r]of Object.entries(e))kg.includes(n)||(t[n]=r);if(t[Og]===void 0){let n=e[kg[0]]??e[kg[1]];n!==void 0&&(t[Og]=n)}return t};return{...e,...e.hidden?{hidden:t(e.hidden)}:{},...e.shown?{shown:t(e.shown)}:{},...e.order?{order:t(e.order)}:{},...e.groups?{groups:n(e.groups,!0)}:{},...e.labels?{labels:n(e.labels,!1)}:{},...e.align?{align:r(e.align)}:{},...e.slots?{slots:i(e.slots)}:{}}}function jg(e){return dg(e).map(e=>{if(e.view===!1)return e;let t=e.ui?.items??[];if(t.some(e=>e.id===`__view`))return e;let n={id:yg,slot:`topbar.primary`,label:e.name,...e.nameEn?{labelEn:e.nameEn}:{},...e.icon?{icon:e.icon}:{},...e.iconSvg?{iconSvg:e.iconSvg}:{},kind:`view`,view:`plugin:${e.id}`,order:23,align:`end`,hidden:!0};return{...e,ui:{items:[...t,n],arrange:e.ui?.arrange??[]}}})}function Mg(e){return{id:e.id,slot:e.slot,source:`host`,label:e.label,icon:e.icon,kind:e.kind??`action`,order:e.order??100,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[],when:e.when}}function Ng(e){return typeof e==`string`&&mg.includes(e)}function Pg(e,t){return t?e.label:e.labelEn??e.label}function Fg(e,t){return t?e.hint??e.hintEn:e.hintEn??e.hint}function Ig(e,t,n,r,i){let a=`${e}#${r.id}`,o=Lg(a,t,n,r.children,i),s=Fg(r,i),c=Rg(r.options,i),l=zg(r.progress);return{id:a,slot:t,source:n,label:Pg(r,i),labelExplicit:!0,...r.icon?{icon:r.icon}:{},...r.iconSvg?{iconSvg:r.iconSvg}:{},...s?{hint:s}:{},kind:r.kind??`action`,...r.action?{action:r.action}:{},...r.view?{view:r.view}:{},...r.group?{group:r.group}:{},order:r.order??100,align:`start`,hidden:r.hidden??!1,...r.badge?{badge:r.badge}:{},...typeof r.checked==`boolean`?{checked:r.checked}:{},...typeof r.value==`string`?{value:r.value}:{},...l===void 0?{}:{progress:l},...r.when?{when:r.when}:{},...c?{options:c}:{},...o.length>0?{children:o}:{},userOverrides:[],arrangedBy:[]}}function Lg(e,t,n,r,i){return r?.length?r.map((r,a)=>({entry:Ig(e,t,n,r,i),index:a})).sort((e,t)=>e.entry.order===t.entry.order?e.index-t.index:e.entry.order-t.entry.order).map(e=>e.entry):[]}function Rg(e,t){if(e?.length)return e.slice(0,32).map(e=>({value:e.value,label:t?e.label??e.labelEn??e.value:e.labelEn??e.label??e.value}))}function zg(e){if(e===void 0)return;let t=Number(e);return Number.isFinite(t)?Math.min(100,Math.max(0,t)):0}function Bg(e,t,n,r,i,a){let o=Lg(e,t,n,r.children,i),s=Fg(r,i),c=zg(r.progress),l=Rg(r.options,i);return{id:e,slot:t,source:n,label:Pg(r,i),labelExplicit:!0,...r.icon?{icon:r.icon}:{},...r.iconSvg?{iconSvg:r.iconSvg}:{},...s?{hint:s}:{},kind:r.kind??(t===`settings.pages`?`page`:`action`),...r.action?{action:r.action}:{},...r.view?{view:r.view}:{},...r.group?{group:r.group}:{},order:r.order??100,align:r.align??`start`,hidden:r.hidden??!1,...r.badge?{badge:r.badge}:{},...typeof r.checked==`boolean`?{checked:r.checked}:{},...typeof r.value==`string`?{value:r.value}:{},...c===void 0?{}:{progress:c},...l?{options:l}:{},...r.when?{when:r.when}:{},...o.length>0?{children:o}:{},userOverrides:[],arrangedBy:[],seq:a}}function Vg(e,t){return[...e].sort((e,n)=>{let r=t.get(e.id),i=t.get(n.id);return r!==void 0||i!==void 0?r!==void 0&&i!==void 0?r-i:r===void 0?1:-1:e.order===n.order?e.seq-n.seq:e.order-n.order})}function Hg(e,t){let n=e.filter(e=>Cg(e)&&!t.has(e.id));if(n.length===0)return e;let r=e.filter(e=>!Cg(e)||t.has(e.id)),i=[`host:git`,`host:terminal`,`host:chat`].map(e=>r.findIndex(t=>t.id===e)).find(e=>e>=0)??-1,a=r.findIndex(e=>e.id===`host:plugins`),o=i+1;return a>=o&&(o=a),o=Math.max(0,Math.min(o,r.length)),[...r.slice(0,o),...n,...r.slice(o)]}function Ug(e,t){let n=Ye(t.locale),r=new Set(t.disabledPlugins??[]),i=Dg(Ag(t.layout??{})),a=e=>{t.diagnostics?.push({level:e.level??`warn`,...e})},o=new Map,s=0;for(let e of vg)o.set(e.id,{id:e.id,slot:e.slot,source:`host`,label:t.t(e.labelKey),labelKey:e.labelKey,...e.icon?{icon:e.icon}:{},kind:e.kind,...e.view?{view:e.view}:{},...e.group?{group:e.group}:{},order:e.order??100,align:e.align??`start`,hidden:e.hidden??!1,userOverrides:[],arrangedBy:[],seq:s++});for(let t of e){if(r.has(t.id)){let e=t.ui?.items?.length??0,n=t.ui?.arrange?.length??0;(e>0||n>0)&&a({level:`info`,pluginId:t.id,message:`plugin "${t.id}" is disabled by the user — its ${e} UI item(s) are not rendered`});continue}if(t.error){a({level:`error`,pluginId:t.id,message:`plugin "${t.id}" failed to activate (${t.error}) — its UI items are not rendered`});continue}let e=`plugin:${t.id}`;for(let r of t.ui?.items??[]){if(!Ng(r.slot)){a({pluginId:t.id,entryId:r.id,message:`item "${t.id}:${r.id}" declares unknown slot "${String(r.slot)}" — dropped (valid slots: see docs/architecture-plugins.md)`});continue}if(r.slot===`leftpanel.sections`&&r.kind!==`view`){a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" targets leftpanel.sections: only kind="view" (a plugin section) is accepted — dropped`});continue}if(r.kind&&!fg.has(r.kind)&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" declares unknown kind "${r.kind}" — the render layer falls back to a plain button`}),Array.isArray(r.when))for(let e of r.when)pg.has(e)||a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" declares when:"${e}" which the host does not know — it is ignored (the item still renders)`});else r.when!==void 0&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item "${t.id}:${r.id}" has a non-array "when" — ignored`});let i=`${t.id}:${r.id}`,c=o.get(i);c&&a({pluginId:t.id,entryId:r.id,slot:r.slot,message:`item id "${r.id}" is declared more than once — the later declaration wins (order/visibility are inherited from the first)`}),o.set(i,Bg(i,r.slot,e,r,n,c?.seq??s++))}}for(let t of e)if(!(t.error||r.has(t.id)))for(let e of t.ui?.arrange??[]){let n=o.get(e.id);Gg(o,e,t.id),n||a({pluginId:t.id,entryId:e.id,message:`arrange target "${e.id}" does not exist — op ignored (is the providing plugin installed / not disabled?)`})}let c=new Map,l=(e,t)=>{let n=c.get(e)??[];n.includes(t)||n.push(t),c.set(e,n)};for(let e of i.hidden??[]){let t=o.get(e);t&&(t.hidden=!0,l(e,`hidden`))}for(let e of i.shown??[]){let t=o.get(e);t&&(t.hidden=!1,l(e,`hidden`))}for(let[e,t]of Object.entries(i.groups??{})){let n=o.get(e);n&&(n.group=t,l(e,`group`))}for(let[e,t]of Object.entries(i.align??{})){let n=o.get(e);!n||t!==`start`&&t!==`center`&&t!==`end`||(n.align=t,l(e,`align`))}for(let[e,t]of Object.entries(i.labels??{})){let n=o.get(e);n&&(n.label=t,n.labelExplicit=!0,l(e,`label`))}for(let[e,t]of Object.entries(i.slots??{})){let n=o.get(e);n&&Ng(t)&&n.slot!==t&&(n.movedFrom=n.movedFrom??n.slot,n.slot=t,l(e,`slot`))}for(let e of bg){let t=o.get(e);t&&(i.slots?.[e]||(t.slot=`topbar.primary`),t.hidden=!1)}let u=new Map;(i.order??[]).forEach((e,t)=>{o.has(e)&&(u.has(e)||u.set(e,t),l(e,`order`))});for(let e of Object.values(eg)){let t=o.get(e);t&&t.slot!==`leftpanel.sections`&&(a({entryId:e,slot:t.slot,message:`"${e}" must stay in leftpanel.sections — the move is ignored`}),t.slot=`leftpanel.sections`,delete t.movedFrom)}let d=new Map;for(let e of mg)d.set(e,[]);for(let e of o.values())d.get(e.slot)?.push(e);let f={};for(let e of mg){let t=Vg(d.get(e)??[],u),n=_g(e===`topbar.primary`?Hg(t,u):t,gg(e));if(n.winner&&n.conflicts.length>0)for(let t of n.conflicts)a({level:`error`,pluginId:t.source.startsWith(`plugin:`)?t.source.slice(7):void 0,entryId:t.id,slot:e,message:`slot "${e}" is single-cardinality; "${n.winner.id}" won and "${t.id}" was hidden`});f[e]=n.entries.map(e=>Wg(e,c.get(e.id)??[]))}return f}function Wg(e,t){let n={...e,userOverrides:t};return delete n.seq,n}function Gg(e,t,n){let r=e.get(t.id);if(!r)return;let i=!1;t.hide!==void 0&&(r.hidden=t.hide,i=!0),t.group!==void 0&&(r.group=t.group,i=!0),t.order!==void 0&&(r.order=t.order,i=!0),t.align!==void 0&&(r.align=t.align,i=!0),t.label!==void 0&&(r.label=t.label,r.labelExplicit=!0,i=!0),t.hint!==void 0&&(r.hint=t.hint,i=!0),t.icon!==void 0&&(r.icon=t.icon,i=!0),t.iconSvg!==void 0&&(r.iconSvg=t.iconSvg||void 0,i=!0),t.slot!==void 0&&Ng(t.slot)&&t.slot!==r.slot&&(r.movedFrom=r.movedFrom??r.slot,r.slot=t.slot,i=!0),i&&r.source!==`plugin:${n}`&&!r.arrangedBy.includes(n)&&r.arrangedBy.push(n)}function Kg(e){let t=[],n=[],r=[];for(let i of e)i.align===`end`?r.push(i):i.align===`center`?n.push(i):t.push(i);return{start:t,center:n,end:r}}function qg(e,t){let n=e??{},r={},i=t===Og?[t,...kg]:[t],a=(n.hidden??[]).filter(e=>!i.includes(e)),o=(n.shown??[]).filter(e=>!i.includes(e)),s=(n.order??[]).filter(e=>!i.includes(e));a.length>0&&(r.hidden=a),o.length>0&&(r.shown=o),s.length>0&&(r.order=s);let c=Yg(n.groups,t),l=Yg(n.labels,t),u=Yg(n.align,t),d=Yg(n.slots,t);if(t===Og)for(let e of kg)c=Yg(c,e),l=Yg(l,e),u=Yg(u,e),d=Yg(d,e);return c&&(r.groups=c),l&&(r.labels=l),u&&(r.align=u),d&&(r.slots=d),n.topbarText!==void 0&&(r.topbarText=n.topbarText),n.sideDockFloat!==void 0&&(r.sideDockFloat=n.sideDockFloat),r}function Jg(){return{}}function Yg(e,t){if(!e)return;let n={},r=!1;for(let[i,a]of Object.entries(e))i!==t&&(n[i]=a,r=!0);return r?n:void 0}function Xg(e){if(e===void 0||e<0||!Number.isFinite(e))return``;if(e<1e3)return`${Math.round(e)}ms`;let t=e/1e3;if(t<60)return`${t.toFixed(1)}s`;let n=Math.floor(t/60),r=Math.round(t%60);return`${n}m ${String(r).padStart(2,`0`)}s`}function Zg(e,t){let n=e.result?e.result.content.map(e=>e.type===`text`?e.text:``).join(``):e.liveOutput??``;return{rawOutput:n,output:n.replace(/…\[LIVE_OMIT:(\d+)\]…\n/,(e,n)=>t(`liveOutputOmitted`,{n}))}}function Qg(e){return(e?.content??[]).filter(e=>e.type===`image`&&typeof e.dataUrl==`string`&&(e.dataUrl.startsWith(`data:`)||e.dataUrl.startsWith(`/`)))}function $g(e){return Qg(e).map(e=>e.dataUrl)}function e_(e){if(!Array.isArray(e))return!1;for(let t of e)if(t.type===`text`&&typeof t.text==`string`){let e=t.text;if(/(?:```|#\s+|\|\s*[-:]+\s*\|)/m.test(e.slice(0,500)))return!0}return!1}function t_(e,t){let n=Hp(e);if(!n)return!1;let r=Up(n,t),i=r.filter(e=>qp(e.kind)).map(e=>({path:e.target,name:e.name}));if(i.length===0)return!1;let a=Zp(r),o=a?i.findIndex(e=>e.path===a.target):0;return Zt(i,o>=0?o:0)}function n_({view:e,t,persistedDurationMs:n}){let r=!e.result&&e.streaming&&!e.status,i=e.result!==void 0,a=!e.result&&!!e.status,o=e.result?.isError??e.status?.isError??!1,s=e.status?.durationMs,c=e.result?.durationMs,l=s??n,u=typeof c==`number`?c:l,d=Pm(e.result?.timestamp,c,l),f=o?`err`:i?`ok`:r||a?`run`:`idle`,p=t(o?`error`:i?`done`:r?`running`:a?`toolDoneWaitingModel`:`toolQueued`),m=(a||i)&&u!==void 0?jm(u):``;(a||i)&&m&&(p=`${p} · ${m}`);let h=a&&e.status?.exitCode!==void 0?`exit ${e.status.exitCode}`:``;return{running:r,done:i,waitingModel:a,isError:o,statusClass:f,statusLabel:p,duration:m,durationMs:u,timeRange:d,exitHint:h}}function r_({block:e,view:t,isPresent:n,isBash:r,inspectorTitle:i,hints:a,status:o,onKillBash:s,t:c}){let{rawOutput:l,output:u}=Zg(t,c),d=$g(t.result),f=n?Hp(e.argumentsText):null;Bt({isThinking:!1,name:e.name,title:i,status:o.statusLabel,statusClass:o.statusClass,duration:o.duration,durationMs:o.durationMs,startTimestamp:o.timeRange.start,endTimestamp:o.timeRange.end,exitHint:o.exitHint,hints:a,args:e.argumentsText||``,rawOutput:l,output:u,details:t.result?.details,images:d,isError:o.isError,toolCallId:t.result?.toolCallId??e.id,resultTimestamp:t.result?.timestamp,onKillBash:r?s:void 0,presentData:n&&f?{title:f.title,note:f.note,items:f.items}:null})}function i_({event:e,block:t,isBash:n,isBashRunning:r,onKillBash:i,uiContextToolCall:a,onUiAction:o,t:s}){let c=a??[],l=[];n&&i&&l.push(Mg({id:`host:kill-bash`,slot:`contextmenu.toolcall`,label:s(`toolInspectorStopBash`),icon:`■`,kind:`action`,order:-1,when:r?void 0:[`disabled`]})),l.push(...c),l.length!==0&&(e.preventDefault(),e.stopPropagation(),jf({x:e.clientX,y:e.clientY,slot:`contextmenu.toolcall`,target:{id:t.id,kind:`toolcall`,label:t.name},entries:l,onHostAction:e=>{e.id===`host:kill-bash`?i?.():e.id===`host:tool-info`?Jh(t.name):o?.(e)}}))}function a_({blockId:e,view:t,statusClass:n,statusLabel:r,duration:i,durationMs:a,startTimestamp:o,endTimestamp:s,exitHint:c,isError:l,isBash:u,onKillBash:d,t:f}){(0,Q.useEffect)(()=>{let p=Yt(),m=t.result?.toolCallId??e;if(!p||p.isThinking||p.toolCallId!==e&&p.toolCallId!==m)return;let{rawOutput:h,output:g}=Zg(t,f),_=$g(t.result);en(p.toolCallId,{status:r,statusClass:n,duration:i,durationMs:a,startTimestamp:o,endTimestamp:s,exitHint:c,rawOutput:h,output:g,details:t.result?.details,images:_,isError:l,resultTimestamp:t.result?.timestamp,onKillBash:u?d:void 0})},[e,t.liveOutput,t.result,t.status,n,r,i,a,o,s,c,l,u,d,f])}function o_({code:e,options:t,details:n,output:r}){let i=X(),a=n,o=Array.isArray(a?.calls)?a.calls:[],s=typeof a?.fullOutputPath==`string`?a.fullOutputPath:void 0,c=(0,Q.useMemo)(()=>{if(!r)return[];let e=/\[Image saved to (.*?) \((.*?)\)\]/g,t=[],n;for(;(n=e.exec(r))!==null;)t.push({path:n[1],info:n[2]});return t},[r]);return(0,$.jsxs)(`div`,{className:`codemode-card`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeScript`)}),t&&Object.keys(t).length>0&&(0,$.jsx)(`span`,{className:`codemode-options-badge`,children:JSON.stringify(t)})]}),(0,$.jsx)(`pre`,{className:`codemode-code`,children:(0,$.jsx)(`code`,{children:e})})]}),o.length>0&&(0,$.jsxs)(`div`,{className:`codemode-sec codemode-calls-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeNestedCalls`)}),(0,$.jsx)(`span`,{className:`codemode-count-badge`,children:o.length})]}),(0,$.jsx)(`div`,{className:`codemode-calls-list`,children:o.map((e,t)=>(0,$.jsxs)(`div`,{className:`codemode-call-item status-${e.status}`,children:[(0,$.jsx)(`span`,{className:`codemode-call-status`,children:e.status===`ok`?`✓`:e.status===`error`?`✗`:e.status===`running`?`…`:`⊘`}),(0,$.jsx)(`span`,{className:`codemode-call-name`,children:e.name}),e.args&&(0,$.jsx)(`span`,{className:`codemode-call-args`,children:e.args}),typeof e.durationMs==`number`&&(0,$.jsx)(`span`,{className:`codemode-call-duration`,children:Xg(e.durationMs)}),e.error&&(0,$.jsx)(`div`,{className:`codemode-call-error`,children:e.error})]},e.id||t))})]}),c.length>0&&(0,$.jsxs)(`div`,{className:`codemode-sec codemode-images-sec`,children:[(0,$.jsxs)(`div`,{className:`codemode-sec-head`,children:[(0,$.jsx)(`span`,{className:`codemode-sec-title`,children:i(`codemodeSavedImages`)}),(0,$.jsx)(`span`,{className:`codemode-count-badge`,children:c.length})]}),(0,$.jsx)(`div`,{className:`codemode-images-list`,children:c.map((e,t)=>(0,$.jsxs)(`div`,{className:`codemode-image-item`,children:[(0,$.jsx)(be,{className:`codemode-image-icon`}),(0,$.jsx)(`code`,{className:`codemode-image-path`,title:e.path,children:e.path}),(0,$.jsx)(`span`,{className:`codemode-image-info`,children:e.info}),(0,$.jsx)(`button`,{type:`button`,className:`btn-ghost codemode-image-copy`,title:i(`copy`),onClick:t=>{t.stopPropagation(),navigator.clipboard.writeText(e.path)},children:(0,$.jsx)(st,{})})]},t))})]}),s&&(0,$.jsxs)(`div`,{className:`codemode-full-output`,children:[(0,$.jsxs)(`span`,{className:`codemode-sec-title`,children:[i(`codemodeFullOutput`),`:`]}),(0,$.jsx)(`code`,{children:s})]})]})}function s_({command:e}){let t=X();return(0,$.jsxs)(`div`,{className:`termline`,children:[(0,$.jsx)(Xe,{className:`termline-icon`}),(0,$.jsx)(`code`,{children:sd(e,t)})]})}function c_({details:e}){let t=X(),n=Array.isArray(e?.loaded)?e.loaded:[];return n.length===0?null:(0,$.jsxs)(`div`,{className:`tool-search-loaded-box`,children:[(0,$.jsxs)(`span`,{className:`tool-search-loaded-label`,children:[t(`toolSearchLoaded`),`:`]}),(0,$.jsx)(`div`,{className:`tool-search-tags`,children:n.map(e=>(0,$.jsx)(`span`,{className:`tool-search-tag`,children:e},e))})]})}function l_({args:e}){let t=X(),n=[{field:`task`,label:t(`delegateSecTask`)},{field:`expected_outcome`,label:t(`delegateSecExpected`)},{field:`required_tools`,label:t(`delegateSecTools`)},{field:`must_do`,label:t(`delegateSecMustDo`)},{field:`must_not_do`,label:t(`delegateSecMustNotDo`)},{field:`context`,label:t(`delegateSecContext`)}].filter(({field:t})=>e[t]?.trim());return n.length===0?null:(0,$.jsx)(`div`,{className:`delegate-brief`,children:n.map(({field:t,label:n})=>(0,$.jsxs)(`div`,{className:`delegate-sec`,children:[(0,$.jsx)(`div`,{className:`delegate-sec-label`,children:n}),(0,$.jsx)(`div`,{className:`delegate-sec-text`,children:e[t]})]},t))})}function u_({block:e,view:t,output:n,status:r,isDelegate:i,delegateArgs:a,isCodemode:o,codemodeArgs:s,isQuestionnaire:c,questionnaireArgs:l,isFileChange:u,bashCommand:d,hasBgCluster:f,bgTaskEntries:p,hasBotDraftDetail:m,uiToolCardFooter:h,onUiAction:g,onOpenInspector:_}){let v=X(),y=(0,Q.useRef)(null),b=(0,Q.useRef)(!0),{running:x,waitingModel:S,isError:C,timeRange:w}=r;return(0,Q.useEffect)(()=>{(x||S)&&b.current&&y.current&&(y.current.scrollTop=y.current.scrollHeight)},[n,x,S]),(0,$.jsxs)(`div`,{className:`toolcall-body`,children:[i?(0,$.jsx)(l_,{args:a}):o&&s?.code?(0,$.jsx)(o_,{code:s.code,options:s.options,details:t.result?.details,output:n}):c&&l?(0,$.jsx)(Fh,{questions:l.questions,details:t.result?.details,output:n,isError:C,waiting:x||S}):u?(0,$.jsx)(Ih,{toolName:e.name,argumentsText:e.argumentsText,details:t.result?.details,output:n,isError:C,onOpenInspector:_}):e.argumentsText&&(0,$.jsx)(`div`,{className:`toolcall-args`,children:d?(0,$.jsx)(s_,{command:d}):(0,$.jsx)(`pre`,{children:e.argumentsText})}),e.name===`tool_search`&&(0,$.jsx)(c_,{details:t.result?.details}),f&&(0,$.jsx)(Uh,{entries:p,rawOutput:n,isError:C,running:x||S}),n.length>0&&!(c&&l)&&!m&&!f&&(0,$.jsxs)(`div`,{className:`toolcall-output`,children:[(0,$.jsxs)(`div`,{className:`toolcall-output-label`,children:[v(C?`errorOutput`:`output`),(x||S)&&(0,$.jsx)(`span`,{className:`cursor`})]}),(0,$.jsx)(`pre`,{ref:y,onWheel:e=>{if(e.deltaY<0)b.current=!1;else if(e.deltaY>0&&y.current){let e=y.current;e.scrollHeight-e.scrollTop-e.clientHeight<32&&(b.current=!0)}},onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<24&&(b.current=!0)},children:n})]}),x&&n.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,v(`waitingOutput`)]}),S&&n.length===0&&(0,$.jsxs)(`div`,{className:`toolcall-waiting`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,v(`waitingModel`)]}),(w.start!==void 0||w.end!==void 0)&&(0,$.jsxs)(`div`,{className:`toolcall-time-footer`,children:[(0,$.jsx)(re,{className:`toolcall-time-icon`}),(0,$.jsx)(`span`,{className:`toolcall-time-text`,children:w.start!==void 0&&w.end!==void 0&&w.durationMs!==void 0?v(`toolTimeRange`,{start:Nm(w.start),end:Nm(w.end),duration:jm(w.durationMs)}):w.end===void 0?w.start===void 0?``:Nm(w.start):Nm(w.end)})]}),h&&h.length>0&&(0,$.jsx)(`div`,{className:`toolcall-footer`,children:h.filter(e=>e&&e.hidden!==!0).map((e,t)=>{let n=e.label||e.id;return e.kind===`badge`?(0,$.jsx)(`span`,{className:`toolcall-footer-badge`,title:n,children:e.badge??n},`${e.id}#${t}`):(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-footer-item`,title:n,onClick:()=>g?.(e),children:[e.icon&&eu(e.icon),(0,$.jsx)(`span`,{children:n})]},`${e.id}#${t}`)})})]})}var d_=(0,Q.memo)(function({block:e,view:t,isPresent:n,icon:r,iconClassName:i,onKillBash:a,uiContextToolCall:o,onUiAction:c,rootRef:l}){let u=X(),d=e.name===`bash`,f=n_({view:t,t:u}),{running:p,done:m,waitingModel:h,isError:g,statusClass:_,statusLabel:v,duration:y,durationMs:b,timeRange:x,exitHint:S}=f,C=d&&(p||!t.result),w=th(e.argumentsText),T=eh({name:e.name,argumentsText:e.argumentsText,hints:w}),E=T?`${e.name}(${T.text})`:`${e.name}()`;a_({blockId:e.id,view:t,statusClass:_,statusLabel:v,duration:y,durationMs:b,startTimestamp:x.start,endTimestamp:x.end,exitHint:S,isError:g,isBash:d,onKillBash:a,t:u});let D=(0,Q.useMemo)(()=>{let e=t.result?.content;return Array.isArray(e)?e.some(e=>e.type===`image`):!1},[t.result?.content]),O=(0,Q.useMemo)(()=>e_(t.result?.content),[t.result?.content]),k=t=>{i_({event:t,block:e,isBash:d,isBashRunning:C,onKillBash:a,uiContextToolCall:o,onUiAction:c,t:u})},A=r=>{n&&!r?.altKey&&t_(e.argumentsText,t.result?.details)||r_({block:e,view:t,isPresent:n,isBash:d,inspectorTitle:E,hints:w,status:f,onKillBash:a,t:u})};return(0,$.jsx)(`div`,{ref:l,className:`toolcall ${_}`,onClick:e=>{e.preventDefault(),e.stopPropagation(),A(e)},onContextMenu:k,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),A(e))},role:`button`,tabIndex:0,title:`${e.name}(${T?T.text:``}) · ${v}`,children:(0,$.jsxs)(`div`,{className:`toolcall-head chead`,children:[(0,$.jsx)(`span`,{className:`toolcall-icon chead-icon ${i}`,children:r}),(0,$.jsx)(`span`,{className:`toolcall-name chead-title`,children:e.name}),(0,$.jsx)(`span`,{className:`toolcall-status`,title:S?`${v} · ${S}`:v,"aria-label":S?`${v} · ${S}`:v,children:g?(0,$.jsx)(Ct,{}):m?(0,$.jsx)(z,{}):p||h?(0,$.jsx)(Am,{}):(0,$.jsx)(s,{})}),D&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:u(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(be,{})}),O&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:u(`toolCallContainsMarkdown`),"aria-label":`markdown output`,children:(0,$.jsx)(vt,{})})]})})});function f_({images:e}){let t=X();return e.length===0?null:(0,$.jsx)(`div`,{className:`toolcall-images`,children:e.map((e,n)=>{let r=e.dataUrl.startsWith(`/`)?He(e.dataUrl):e.dataUrl;return(0,$.jsx)(`button`,{type:`button`,className:`toolcall-image`,title:t(`toolImageZoom`),"aria-label":t(`toolImageZoom`),onClick:e=>{e.stopPropagation(),Tn({src:r,alt:`tool result image ${n+1}`})},children:(0,$.jsx)(`img`,{crossOrigin:i(r),src:r,loading:`lazy`,decoding:`async`,alt:`tool result image ${n+1}`})},n)})})}var p_={bash:`toolcall-icon tc-tone-exec`,exec_command:`toolcall-icon tc-tone-exec`,write_stdin:`toolcall-icon tc-tone-exec`,commandExecution:`toolcall-icon tc-tone-exec`,shell:`toolcall-icon tc-tone-exec`,shell_command:`toolcall-icon tc-tone-exec`,run_command:`toolcall-icon tc-tone-exec`,bg_task:`toolcall-icon tc-tone-exec`,sftp:`toolcall-icon tc-tone-exec`,read:`toolcall-icon tc-tone-read`,ls:`toolcall-icon tc-tone-read`,view_image:`toolcall-icon tc-tone-read`,conversation_read:`toolcall-icon tc-tone-read`,obs_recall:`toolcall-icon tc-tone-read`,write:`toolcall-icon tc-tone-edit`,edit:`toolcall-icon tc-tone-edit`,patch:`toolcall-icon tc-tone-edit`,apply_patch:`toolcall-icon tc-tone-edit`,fileChange:`toolcall-icon tc-tone-edit`,claim_files:`toolcall-icon tc-tone-edit`,grep:`toolcall-icon tc-tone-search`,find:`toolcall-icon tc-tone-search`,tool_search:`toolcall-icon tc-tone-search`,load_tools:`toolcall-icon tc-tone-search`,web_search:`toolcall-icon tc-tone-search`,webSearch:`toolcall-icon tc-tone-search`,codemode:`toolcall-icon tc-tone-code`,eval:`toolcall-icon tc-tone-code`,lsp:`toolcall-icon tc-tone-code`,skill:`toolcall-icon tc-tone-code`,compact_context:`toolcall-icon tc-tone-code`,delegate_task:`toolcall-icon tc-tone-agent`,conversation:`toolcall-icon tc-tone-agent`,worktree:`toolcall-icon tc-tone-agent`,plan_update:`toolcall-icon tc-tone-agent`,schedule:`toolcall-icon tc-tone-agent`,agent_bot:`toolcall-icon tc-tone-agent`,ask_user_question:`toolcall-icon tc-tone-ui`,request_user_input:`toolcall-icon tc-tone-ui`,request_permissions:`toolcall-icon tc-tone-ui`,browser_page:`toolcall-icon tc-tone-ui`,mail:`toolcall-icon tc-tone-ui`,mcp_manage:`toolcall-icon tc-tone-ui`,sandbox:`toolcall-icon tc-tone-ui`},m_=`toolcall-icon tc-tone-default`;function h_(e){return p_[e]??m_}var g_={bash:(0,$.jsx)(Xe,{}),exec_command:(0,$.jsx)(Xe,{}),write_stdin:(0,$.jsx)(Xe,{}),commandExecution:(0,$.jsx)(Xe,{}),shell:(0,$.jsx)(Xe,{}),shell_command:(0,$.jsx)(Xe,{}),run_command:(0,$.jsx)(Xe,{}),bg_task:(0,$.jsx)(wt,{}),delegate_task:(0,$.jsx)(wt,{}),conversation:(0,$.jsx)(K,{}),read:(0,$.jsx)(vt,{}),write:(0,$.jsx)(dt,{}),edit:(0,$.jsx)(et,{}),patch:(0,$.jsx)(Je,{}),apply_patch:(0,$.jsx)(et,{}),fileChange:(0,$.jsx)(et,{}),grep:(0,$.jsx)(mt,{}),find:(0,$.jsx)(T,{}),ls:(0,$.jsx)(Ee,{}),codemode:(0,$.jsx)(ne,{}),eval:(0,$.jsx)(Y,{}),lsp:(0,$.jsx)(Y,{}),tool_search:(0,$.jsx)(mt,{}),load_tools:(0,$.jsx)(E,{}),ask_user_question:(0,$.jsx)(xt,{}),request_user_input:(0,$.jsx)(xt,{}),request_permissions:(0,$.jsx)(Ge,{}),[Du]:(0,$.jsx)(be,{}),view_image:(0,$.jsx)(be,{}),browser_page:(0,$.jsx)(Le,{}),web_search:(0,$.jsx)(Le,{}),webSearch:(0,$.jsx)(Le,{}),conversation_read:(0,$.jsx)(C,{}),claim_files:(0,$.jsx)(Ge,{}),plan_update:(0,$.jsx)(S,{}),skill:(0,$.jsx)(r,{}),schedule:(0,$.jsx)(re,{}),agent_bot:(0,$.jsx)(fe,{}),compact_context:(0,$.jsx)(ye,{}),mcp_manage:(0,$.jsx)(A,{}),sandbox:(0,$.jsx)(A,{}),worktree:(0,$.jsx)(ot,{}),sftp:(0,$.jsx)(ut,{}),mail:(0,$.jsx)(Ue,{}),obs_recall:(0,$.jsx)(t,{})},__=(0,$.jsx)(Ie,{});function v_(e){return g_[e]??__}var y_={conversation:`toolcall-icon tc-tone-agent`,[Du]:`toolcall-icon tc-tone-ui`};function b_(e){return y_[e]??h_(e)}var x_=(0,Q.memo)(function({block:e,view:t,onKillBash:n,wrap:r=!0,showImages:i=!0,forceOpen:a=!1,uiContextToolCall:o,uiToolCardFooter:c,onUiAction:l,rootRef:u}){let d=X(),[f,p]=(0,Q.useState)(null),m=e.name===Du,g=(0,Q.useMemo)(()=>e.name===`agent_bot`?Mp(t.result?.details):null,[e.name,t.result?.details]),_=f??(m||g?!0:r),v=_||a,{copied:y,copy:b}=Gn({duration:1200}),x=e.name===`bash`,S=(0,Q.useRef)(void 0),C=t.status?.durationMs,w=t.result?.durationMs;(0,Q.useEffect)(()=>{C!==void 0&&(S.current=C),typeof w==`number`&&(S.current=w)},[C,w]);let T=n_({view:t,t:d,persistedDurationMs:S.current}),{running:E,done:D,waitingModel:O,isError:k,statusClass:A,statusLabel:j,duration:M,durationMs:N,timeRange:P,exitHint:F}=T,I=x&&(E||!t.result),L=(0,Q.useMemo)(()=>v?Zg(t,d).output:``,[v,t,d]),R=(0,Q.useMemo)(()=>Xr({toolName:e.name,details:t.result?.details,text:L}),[e.name,t.result?.details,L]),B=R.length>0,V=(0,Q.useMemo)(()=>i?Qg(t.result):[],[i,t.result]),H=e.name===`delegate_task`,ee=(0,Q.useMemo)(()=>!H||!v?{}:ah(e.argumentsText),[H,v,e.argumentsText]),U=e.name===`codemode`,W=(0,Q.useMemo)(()=>U&&v?mh(e.argumentsText):null,[U,v,e.argumentsText]),G=e.name===`ask_user_question`,K=(0,Q.useMemo)(()=>G&&v?vh(e.argumentsText):null,[G,v,e.argumentsText]),q=e.name===`edit`||e.name===`write`||e.name===`patch`,te=(0,Q.useMemo)(()=>q?Mh(e.name,e.argumentsText,t.result?.details,L):null,[q,e.name,e.argumentsText,t.result?.details,L]),ne=V.length>0,re=(0,Q.useMemo)(()=>e_(t.result?.content),[t.result?.content]),J=H&&t.result&&typeof t.result.details==`object`&&t.result.details!==null?t.result.details.convId:void 0,ie=(0,Q.useMemo)(()=>{if(!H)return;if(J)return J;let e=t.result?.content?.[0];if(e&&typeof e==`object`&&`text`in e&&typeof e.text==`string`)return/sa-[0-9a-f]{8}/.exec(e.text)?.[0]},[H,J,t.result?.content]),ae=th(e.argumentsText),oe=Qm(e.name)?ae.command:void 0,se=eh({name:e.name,argumentsText:e.argumentsText,hints:ae,isCollapsed:!v}),Y=se?`${e.name}(${se.text})`:`${e.name}()`;a_({blockId:e.id,view:t,statusClass:A,statusLabel:j,duration:M,durationMs:N,startTimestamp:P.start,endTimestamp:P.end,exitHint:F,isError:k,isBash:x,onKillBash:n,t:d});let ce=()=>{e.argumentsText&&b(e.argumentsText)},le=t=>{let r=t.target;if(r instanceof Element&&r.closest(`pre, code, a, input, textarea, [contenteditable='true']`))return;let i=window.getSelection?.();i&&!i.isCollapsed&&i.toString().trim().length>0||i_({event:t,block:e,isBash:x,isBashRunning:I,onKillBash:n,uiContextToolCall:o,onUiAction:l,t:d})},ue=()=>{r_({block:e,view:t,isPresent:m,isBash:x,inspectorTitle:Y,hints:ae,status:T,onKillBash:n,t:d})},de=n=>{m&&!n?.altKey&&t_(e.argumentsText,t.result?.details)||ue()};return(0,$.jsxs)(`div`,{ref:u,className:`toolcall ${A}${V.length>0?` has-images`:``}`,onClick:e=>{Qt(u.current)&&(e.target?.closest(`button, a, .toolcall-kill, .toolcall-open, .toolcall-image, .file-diff-action-btn, .btn-tag`)||(e.preventDefault(),e.stopPropagation(),de(e)))},children:[(0,$.jsx)(Pl,{open:v,headClassName:`toolcall-head`,toggleClassName:`toolcall-toggle`,titleText:d(v?`collapseMsg`:`expandMsg`),onToggle:()=>{Qt(u.current)?de():p(!_)},onHeadContextMenu:le,icon:v_(e.name),iconClassName:b_(e.name),titleClassName:`toolcall-name`,after:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`toolcall-status`,title:F?`${j} · ${F}`:j,"aria-label":F?`${j} · ${F}`:j,children:k?(0,$.jsx)(Ct,{}):D?(0,$.jsx)(z,{}):E||O?(0,$.jsx)(Am,{}):(0,$.jsx)(s,{})}),ne&&(0,$.jsx)(`span`,{className:`toolcall-out-badge img`,title:d(`toolImageZoom`),"aria-label":`image output`,children:(0,$.jsx)(be,{})}),re&&(0,$.jsx)(`span`,{className:`toolcall-out-badge md`,title:d(`toolCallContainsMarkdown`),"aria-label":`markdown output`,children:(0,$.jsx)(vt,{})}),M&&(0,$.jsx)(`span`,{className:`toolcall-duration toolcall-timeout`,style:{marginLeft:-2,fontFamily:`var(--mono)`},title:F?`${j} · ${F}`:j,children:M}),se&&(0,$.jsxs)(`span`,{className:se.className,title:se.title??se.text,children:[se.prefix,se.text]}),te&&(te.stats.additions>0||te.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`toolcall-diff-badge`,title:`+${te.stats.additions} -${te.stats.deletions}`,children:[te.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,te.stats.additions]}),te.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,te.stats.deletions]})]}),ae.timeout&&(0,$.jsxs)(`span`,{className:`toolcall-timeout`,children:[`⏱ `,ae.timeout]}),(0,$.jsx)(`span`,{className:`toolcall-spacer`}),I&&n&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-kill`,title:d(`stopBashTip`),onClick:e=>{e.stopPropagation(),n?.()},children:[(0,$.jsx)(_t,{}),(0,$.jsx)(`span`,{children:d(`stopBash`)})]}),H&&D&&ie&&(0,$.jsxs)(`button`,{type:`button`,className:`toolcall-open`,title:d(`delegateOpenSubagent`),onClick:e=>{e.stopPropagation(),window.dispatchEvent(new CustomEvent(`pi-web-ui:switch-conversation`,{detail:ie}))},children:[(0,$.jsx)(St,{}),(0,$.jsx)(`span`,{children:d(`delegateOpenSubagent`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`chead-copy toolcall-copy${y?` copied`:``}`,title:d(`copyArgs`),"aria-label":d(`copyArgs`),onClick:e=>{e.stopPropagation(),ce()},children:y?(0,$.jsx)(h,{}):(0,$.jsx)(st,{})})]}),children:e.name}),(0,$.jsx)(f_,{images:V}),v&&(0,$.jsx)(u_,{block:e,view:t,output:L,status:T,isDelegate:H,delegateArgs:ee,isCodemode:U,codemodeArgs:W,isQuestionnaire:G,questionnaireArgs:K,isFileChange:q,bashCommand:oe,hasBgCluster:B,bgTaskEntries:R,hasBotDraftDetail:!!g,uiToolCardFooter:c,onUiAction:l,onOpenInspector:ue})]})}),S_=(0,Q.memo)(function(e){let t=(0,Q.useRef)(null);return Qt(t.current)?(0,$.jsx)(d_,{block:e.block,view:e.view,isPresent:e.block.name===Du,icon:v_(e.block.name),iconClassName:b_(e.block.name),onKillBash:e.onKillBash,uiContextToolCall:e.uiContextToolCall,onUiAction:e.onUiAction,rootRef:t}):(0,$.jsx)(x_,{...e,rootRef:t})});function C_({block:e,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:a,isLast:o,isTrailingBlock:s,onKillBash:c,thinkingWrap:l,toolsWrap:u,toolImages:d,searchActive:f,hideProcessBlocks:p,forceThinking:m,forceTools:g,role:_,showCopy:v,uiContextToolCall:y,uiToolCardFooter:b,onUiAction:x,parentTimestamp:S,parentDurationMs:C,parentId:w,blockIndex:T}){let E=X(),{copied:D,copy:O}=Gn({duration:1200}),k=s??!0,A=Gl(e),j=!!(A&&a&&o&&k),M=(0,Q.useRef)(j);M.current=j;let N=(0,Q.useRef)(j);j&&(N.current=!0);let P=()=>typeof document<`u`&&document.hidden,[F,I]=(0,Q.useState)(()=>j&&!P());(0,Q.useEffect)(()=>{j&&!P()?I(!0):!j&&P()&&I(!1)},[j]),(0,Q.useEffect)(()=>{if(typeof document>`u`)return;let e=()=>{M.current||I(!1)};return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]);let L=(0,Q.useCallback)(()=>{M.current||I(!1)},[]);if(A){let e=_===`user`?A.text:Wl(A.text,j);if(!e.trim())return null;let t=e===A.text?A:{...A,text:e},n=_===`user`?Xl(A.text):null,r=(_===`assistant`||_===`user`)&&v!==!1,i=r&&!t.text.includes(`
|
|
51
|
-
`)&&!t.truncated,a=n&&!n.isNotice?(0,$.jsxs)(`div`,{className:`collab-request-box`,children:[n.userText?(0,$.jsx)(nl,{text:n.userText,hardBreaks:!0}):null,n.questions&&n.questions.length>0&&(0,$.jsx)(`div`,{className:`collab-questions`,children:n.questions.map((e,t)=>(0,$.jsxs)(`div`,{className:`collab-q-item`,children:[(0,$.jsx)(`div`,{className:`collab-q-title`,children:(0,$.jsx)(`strong`,{children:e.question})}),e.options&&e.options.length>0&&(0,$.jsx)(`div`,{className:`collab-q-options`,children:e.options.map((e,t)=>(0,$.jsx)(`span`,{className:`collab-q-opt-tag`,children:e.label},t))})]},e.id||t))}),n.requestId&&(0,$.jsxs)(`div`,{className:`collab-req-id`,children:[`Request: `,(0,$.jsx)(`code`,{children:n.requestId})]})]}):_===`user`?(0,$.jsx)(nl,{text:t.text,hardBreaks:!0}):j||F||N.current?(0,$.jsx)(km,{text:t.text,finishing:!j&&F,onSettled:L}):(0,$.jsx)(nl,{text:t.text}),o=r?(0,$.jsx)(`button`,{type:`button`,className:`msg-text-copy${D?` copied`:``}`,title:E(D?`copied`:`copyMessage`),"aria-label":E(`copyMessage`),onClick:()=>{O(t.text)},children:D?(0,$.jsx)(h,{}):(0,$.jsx)(st,{})},`msg-text-copy`):null;return(0,$.jsx)(`div`,{className:`msg-text${i?` single`:``}`,children:i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`msg-text-main`,children:a}),o]}):(0,$.jsxs)($.Fragment,{children:[o,a,t.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:E(`truncated`)})]})})}let R=Kl(e);if(R)return p?null:(0,$.jsx)(Hm,{thinking:R.thinking,streaming:a&&o&&k,wrap:l,forceOpen:f||m,startTimestamp:S,endTimestamp:S!==void 0&&C!==void 0?S+C:void 0,durationMs:C,thinkingId:w===void 0?void 0:`${w}:thinking:${T??0}`});let z=ql(e);if(z){let e=t.get(z.id),i=n.get(z.id),o=z.name===`agent_bot`?Mp(e?.details)??Np(i?.text)??Pp(z.argumentsText):null,s=z.name===`present_files`?Hp(z.argumentsText):null,l=s?(0,$.jsx)(pm,{args:s,details:e?.details,toolCallId:e?.toolCallId??z.id,resultTimestamp:e?.timestamp}):null;if(p)return o?(0,$.jsx)(Ip,{draft:o},z.id):l;let m={result:e,liveOutput:i?.text,streaming:a,status:r.get(z.id)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(S_,{block:z,view:m,onKillBash:c,wrap:u,showImages:d??!0,forceOpen:f||g,uiContextToolCall:y,uiToolCardFooter:b,onUiAction:x}),o&&(0,$.jsx)(Ip,{draft:o},z.id),l]})}let B=Jl(e);if(B&&B.dataUrl){let e=B.dataUrl.startsWith(`/`)?He(B.dataUrl):B.dataUrl;return(0,$.jsx)(`div`,{className:`msg-image`,children:(0,$.jsx)(`img`,{crossOrigin:i(e),src:e,loading:`lazy`,decoding:`async`,alt:`attachment`,className:`msg-image-clickable`,title:E(`toolImageZoom`),onClick:()=>Tn({src:e,alt:`attachment`})})})}let V=Yl(e);return V?p?null:(0,$.jsxs)(`div`,{className:`bashblock`,children:[(0,$.jsxs)(`div`,{className:`bashblock-command`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:sd(V.command,E)}),V.exitCode!==void 0&&(0,$.jsx)(`span`,{className:`bashblock-exit ${V.exitCode===0?`ok`:`err`}`,children:E(`exitCode`,{code:V.exitCode})}),V.cancelled&&(0,$.jsx)(`span`,{className:`bashblock-exit err`,children:E(`cancelled`)})]}),V.output&&(0,$.jsx)(`pre`,{className:`bashblock-output`,children:V.output}),V.truncated&&(0,$.jsx)(`div`,{className:`trunc-note`,children:E(`outputTruncated`)})]}):null}function w_(e,t,n,r={}){let{align:i=`right`,side:a=`bottom`,gap:o=6,margin:s=8}=r,c=t.width,l=t.height,u=Math.max(0,n.width-c-s),d=Math.max(0,n.height-l-s),f=i===`left`?e.left:e.right-c;f=Math.max(s,Math.min(f,u));let p;return a===`top`?(p=e.top-l-o,p<s&&e.bottom+o+l<=n.height-s&&(p=e.bottom+o)):(p=e.bottom+o,p+l>n.height-s&&e.top-l-o>=s&&(p=e.top-l-o)),p>d&&(p=d),p<s&&(p=s),{x:Math.round(f),y:Math.round(p)}}function T_(e){let{open:t=!0,anchor:n,anchorEl:r,onClose:i,isInside:a,align:o=`right`,side:s=`bottom`,gap:c=6,margin:l=8}=e,u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(i);(0,Q.useLayoutEffect)(()=>{p.current=i});let m=()=>{if(!n)return null;if(`current`in n)return n.current?.getBoundingClientRect()??null;if(typeof n.getBoundingClientRect==`function`)return n.getBoundingClientRect();let e=n;return typeof e.left==`number`&&typeof e.right==`number`&&typeof e.top==`number`&&typeof e.bottom==`number`?e:null},h=()=>r||(n&&`current`in n?n.current:n&&typeof n.getBoundingClientRect==`function`?n:null),g=()=>{if(!t)return;let e=u.current;if(!e)return;let n=e.getBoundingClientRect();if(n.width===0&&n.height===0)return;let r=h(),i=r&&r.isConnected?r.getBoundingClientRect():m();if(!i)return;let a=w_(i,{width:n.width,height:n.height},{width:window.innerWidth,height:window.innerHeight},{align:o,side:s,gap:c,margin:l});f(e=>e?.x===a.x&&e?.y===a.y?e:a)};return(0,Q.useLayoutEffect)(()=>{t?g():f(null)},[t,n,r,o,s,c,l]),Lt(()=>{p.current()},t),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>e instanceof Node&&!!(u.current?.contains(e)||h()?.contains(e)||a?.(e)),n=t=>{e(t.target)||p.current()};return document.addEventListener(`mousedown`,n,!0),window.addEventListener(`resize`,g,!0),window.addEventListener(`scroll`,g,!0),()=>{document.removeEventListener(`mousedown`,n,!0),window.removeEventListener(`resize`,g,!0),window.removeEventListener(`scroll`,g,!0)}},[t,n,r]),{panelRef:u,pos:d,style:{position:`fixed`,left:d?.x??-9999,top:d?.y??-9999,visibility:d?`visible`:`hidden`},measure:g}}function E_({title:e,children:t,...n}){let r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(!1),o=(0,Q.useId)(),s=T_({open:i,anchor:r,side:`top`,onClose:()=>a(!1)});return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{...n,ref:r,"aria-label":n[`aria-label`]??e,"aria-describedby":i&&e?o:void 0,onMouseEnter:()=>a(!0),onMouseLeave:()=>a(!1),onFocus:()=>a(!0),onBlur:()=>a(!1),onClick:e=>{a(!1),n.onClick?.(e)},children:t}),i&&e&&(0,Er.createPortal)((0,$.jsx)(`div`,{ref:s.panelRef,id:o,role:`tooltip`,className:`msg-action-tooltip`,style:s.style,children:e}),document.body)]})}function D_(e){if(!e)return null;let t=e.startsWith(`#`)?e.slice(1):e;if(!t.trim())return null;let n=new URLSearchParams(t),r=n.get(`s`)?.trim()??``;if(!r)return null;let i=n.get(`m`)?.trim()||void 0;return i?{sessionId:r,messageId:i}:{sessionId:r}}function O_(e){let t=e?.sessionId?.trim()??``;if(!t)return``;let n=e?.messageId?.trim()??``,r=`#s=${encodeURIComponent(t)}`;return n?`${r}&m=${encodeURIComponent(n)}`:r}function k_(e,t){let n=O_(t);try{let t=new URL(e);return t.searchParams.delete(`token`),t.hash=n,t.toString()}catch{return`${e.split(`#`)[0]??e}${n}`}}function A_(e){if(!e)return null;let t=e.replace(/\\/g,`/`).replace(/\/+$/,``);if(!t)return null;let n=t.split(`/`),r=n[n.length-1]??``;if(!r)return null;if(r===`session.jsonl`)return(n[n.length-2]?.trim()??``)||null;let i=r.endsWith(`.jsonl`)?r.slice(0,-6):r;if(!i)return null;let a=i.lastIndexOf(`_`);return(a>=0?i.slice(a+1).trim():i.trim())||null}function j_(e,t){let n=t?.trim()??``;if(!n||e.length===0)return null;let r=e.find(e=>e.id===n);if(r)return r.id;let i=/^([a-z]+-\d+)-\d+$/.exec(n);if(i){let t=`${i[1]}-`,n=e.find(e=>e.id.startsWith(t));if(n)return n.id}return null}var M_=`pi-web-tts`,N_={enabled:!1,announce:!0,readReplies:!1,streamReplies:!0,rate:1,voiceURI:``,engine:`builtin`};function P_(){try{let e=localStorage.getItem(M_);if(!e)return{...N_};let{voiceCatalog:t,...n}=JSON.parse(e),r={...N_,...n};r.engine===`builtin`&&t!==`server`&&(r.voiceURI=``);for(let e of[`enabled`,`announce`,`readReplies`,`streamReplies`])typeof r[e]!=`boolean`&&(r[e]=N_[e]);return r.rate=typeof r.rate!=`number`||!Number.isFinite(r.rate)?N_.rate:Math.round(Math.max(.5,Math.min(2,r.rate))*10)/10,typeof r.voiceURI!=`string`&&(r.voiceURI=N_.voiceURI),typeof r.engine!=`string`&&(r.engine=N_.engine),r}catch{return{...N_}}}function F_(e){try{localStorage.setItem(M_,JSON.stringify({...e,voiceCatalog:`server`}))}catch{}}function I_(){return typeof Audio<`u`&&typeof fetch==`function`}function L_(e,t=600){let n=e??``;return n=n.replace(/```[\s\S]*?(?:```|$)/g,` `),n=n.replace(/`([^`]+)`/g,`$1`),n=n.replace(/!\[[^\]]*\]\([^)]*\)/g,` `),n=n.replace(/\[([^\]]+)\]\([^)]*\)/g,`$1`),n=n.replace(/^\s{0,3}#{1,6}\s+/gm,``),n=n.replace(/^\s{0,3}>\s?/gm,``),n=n.replace(/^\s*[-*+]\s+/gm,``),n=n.replace(/^\s*\|?[\s:|-]*\|[\s:|-]*$/gm,``),n=n.replace(/\|/g,` `),n=n.replace(/(\*\*\*|\*\*|__)(.*?)\1/g,`$2`),n=n.replace(/(\*|_)([^*_\n]+)\1/g,`$2`),n=n.replace(/<[^>]+>/g,` `),n=n.replace(/\r/g,``),n=n.replace(/[ \t]+/g,` `),n=n.replace(/\s*\n+\s*/g,` `),n=n.trim(),t>0&&n.length>t&&(n=`${n.slice(0,t).trimEnd()}…`),n}var R_=class{cursor=0;onSentence;constructor(e){this.onSentence=e}feed(e){if(e.length<=this.cursor)return;let t=e.slice(this.cursor),n=t.match(/(?:[。!?!?;;\n]|(?<=.{25,})[,,])/);if(n&&typeof n.index==`number`){let e=n.index+n[0].length,r=t.slice(0,e);this.cursor+=e;let i=L_(r,0);i&&this.onSentence(i)}}flush(e){if(e.length>this.cursor){let t=L_(e.slice(this.cursor),0);t&&this.onSentence(t),this.cursor=e.length}}reset(){this.cursor=0}};function z_(e){if(!Array.isArray(e))return``;for(let t=e.length-1;t>=0;t--){let n=e[t];if(n&&n.role===`assistant`)return L_((n.content??[]).filter(e=>e?.type===`text`&&typeof e.text==`string`).map(e=>e.text??``).join(`
|
|
52
|
-
`))}return``}var B_=!1,V_=null,H_=null,U_=null,W_=new Set;function G_(e,t=null){let n=!!e,r=n?t:null;if(B_!==n||V_!==r){B_=n,V_=r;for(let e of W_)try{e(n)}catch{}}}function K_(){return B_}function q_(){return B_?V_:null}function J_(e){return W_.add(e),()=>W_.delete(e)}function Y_(e,t=P_(),n){if(!e)return;X_();let r=(t.engine||`builtin`).trim(),i=Wn(r);if(i&&typeof i.play==`function`){let r=!1;G_(!0,n??null);try{let a=i.play({text:e,rate:t.rate,voiceURI:t.voiceURI,onStart:()=>{r||G_(!0,n??null)},onEnd:()=>{r||(r=!0,H_=null,G_(!1))},onError:()=>{r||(r=!0,H_=null,G_(!1))}});H_=()=>{r=!0;try{a?.()}catch{}}}catch{G_(!1)}}}function X_(){if(U_&&=(U_.stop(),null),H_){try{H_()}catch{}H_=null}G_(!1)}var Z_=class{queue=[];playing=!1;stopped=!1;stopCurrentAudio=null;settings;sourceId;finishedPushing=!1;constructor(e,t){this.settings=e,this.sourceId=t}push(e){if(this.stopped)return;let t=e.trim();t&&(this.queue.push(t),this.playing||this.playNext())}finish(){this.finishedPushing=!0,!this.playing&&this.queue.length===0&&this.stop()}async playNext(){if(this.stopped)return;if(this.queue.length===0){this.playing=!1,this.finishedPushing&&this.stop();return}this.playing=!0;let e=this.queue.shift();G_(!0,this.sourceId??null),await new Promise(t=>{let n=(this.settings.engine||`builtin`).trim(),r=Wn(n);if(r&&typeof r.play==`function`){let n=!1,i=r.play({text:e,rate:this.settings.rate,voiceURI:this.settings.voiceURI,onEnd:()=>{n||(n=!0,t())},onError:()=>{n||(n=!0,t())}});this.stopCurrentAudio=()=>{if(!n){n=!0;try{i?.()}catch{}t()}}}else t()}),this.stopCurrentAudio=null,this.stopped||this.playNext()}stop(){if(this.stopped=!0,this.queue=[],this.stopCurrentAudio){try{this.stopCurrentAudio()}catch{}this.stopCurrentAudio=null}this.playing=!1,U_===this&&(U_=null),G_(!1)}};function Q_(e=P_(),t){X_();let n=new Z_(e,t);return U_=n,n}function $_({message:e,streaming:t,readOnly:n,editing:r,canEdit:i,canDelete:a,canRollback:o,directReask:s,startEdit:c,rollbackEdit:u,deleteMessage:d,uiMessageActions:f,uiContextMessage:p,onUiAction:m}){let g=X(),[_,v]=(0,Q.useState)(null),y=(0,Q.useRef)(0),b=ml(e.content),x=(e.role===`assistant`||e.role===`user`)&&b.length>0,S=async t=>{try{let n=!1;if(t===`host:msg-copy-text`)n=await Kn(hl(e.content));else if(t===`host:msg-copy-markdown`)n=await Kn(b);else{kl(e.id);return}window.clearTimeout(y.current),v({id:t,ok:n}),y.current=window.setTimeout(()=>v(null),1600)}catch{window.clearTimeout(y.current),v({id:t,ok:!1}),y.current=window.setTimeout(()=>v(null),1600)}},C=tu(hl(e.content),40)||nu(e.role,g),[w,T]=(0,Q.useState)(K_());(0,Q.useEffect)(()=>J_(T),[]);let E=e.role===`assistant`&&hl(e.content).trim().length>0&&!t&&I_(),O=E&&q_()===e.id,k=()=>{O?X_():Y_(L_(hl(e.content),5e3),{...P_(),enabled:!0},e.id)},[A,j]=(0,Q.useState)(!1),M=(0,Q.useRef)(null),N=T_({open:A,anchor:M,onClose:()=>j(!1)}),P=e=>E?(0,$.jsxs)(E_,{type:`button`,className:`msg-action${O?` msg-action-speaking`:``}`,title:g(O?`stopSpeakingMsg`:`speakMsg`),"aria-label":g(O?`stopSpeakingMsg`:`speakMsg`),onClick:k,children:[O?(0,$.jsx)(_t,{}):(0,$.jsx)(l,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:g(O?`stopSpeakingMsg`:`speakMsg`)})]},e):null,F=()=>vg.filter(e=>e.slot===`contextmenu.message`).map(e=>({id:e.id,slot:e.slot,source:`host`,label:g(e.labelKey),labelKey:e.labelKey,icon:e.icon,kind:e.kind,group:e.group,order:e.order??100,align:e.align??`start`,hidden:e.hidden??!1,userOverrides:[],arrangedBy:[]})),I=l=>{let f=l.target;if(f instanceof Element&&f.closest(`a, input, textarea, [contenteditable='true']`))return;let h=window.getSelection?.();if(h&&!h.isCollapsed&&h.toString().trim().length>0)return;let _=(p&&p.length>0?p:F()).map(s=>{if(s.source!==`host`)return n?{...s,hidden:!0}:s;switch(s.id){case`host:msg-ctx-copy-markdown`:case`host:msg-ctx-copy-text`:case`host:msg-ctx-copy-image`:return x?s:{...s,hidden:!0};case`host:msg-ctx-copy-link`:{let r=D_(window.location.hash)?.sessionId;return!n&&!t&&r&&e.id?s:{...s,hidden:!0}}case`host:msg-ctx-reask`:case`host:msg-ctx-edit-reask`:return i?s:{...s,hidden:!0};case`host:msg-ctx-rollback`:return o?s:{...s,hidden:!0};case`host:msg-ctx-fork`:return!n&&!t&&!r?s:{...s,hidden:!0};case`host:msg-ctx-delete`:return a?s:{...s,hidden:!0};case`host:msg-ctx-speak`:return E?O?{...s,label:g(`stopSpeakingMsg`),icon:`square`}:s:{...s,hidden:!0};default:return s}});Hf(_).length!==0&&(l.preventDefault(),jf({x:l.clientX,y:l.clientY,slot:`contextmenu.message`,target:{id:e.id,kind:`message`,label:C},entries:_,onHostAction:t=>{switch(t.id){case`host:msg-ctx-copy-markdown`:S(`host:msg-copy-markdown`);return;case`host:msg-ctx-copy-text`:S(`host:msg-copy-text`);return;case`host:msg-ctx-copy-image`:S(`host:msg-copy-image`);return;case`host:msg-ctx-copy-link`:{let t=D_(window.location.hash)?.sessionId;if(t&&e.id){let n=k_(window.location.href,{sessionId:t,messageId:e.id});Kn(n)}return}case`host:msg-ctx-reask`:s();return;case`host:msg-ctx-edit-reask`:c();return;case`host:msg-ctx-fork`:Z({type:`fork_session`,messageId:e.id,position:`at`});return;case`host:msg-ctx-rollback`:u();return;case`host:msg-ctx-delete`:d();return;case`host:msg-ctx-speak`:k();return;default:m?.(t);return}}}))},L=(e,t)=>{if(!x)return null;let n=[{id:`host:msg-copy-markdown`,label:g(`copyMarkdown`),icon:(0,$.jsx)(Y,{})},{id:`host:msg-copy-text`,label:g(`copyText`),icon:(0,$.jsx)(vt,{})},{id:`host:msg-copy-image`,label:g(`copyImage`),icon:(0,$.jsx)(be,{})}].filter(e=>{if(!t)return!0;let n=t.find(t=>t.id===e.id);return!n||n.hidden!==!0});if(n.length===0)return null;let r=_!==null,i=_?.ok;return(0,$.jsxs)(`div`,{ref:M,className:`msg-copy-group${A?` has-open-dropdown`:``}`,children:[(0,$.jsxs)(E_,{type:`button`,className:`msg-action msg-copy-main-btn${i?` msg-copy-success`:``}`,title:g(i?`copied`:r&&!i?`copyFailed`:`copyMarkdown`),"aria-label":g(`copyMarkdown`),onClick:()=>void S(`host:msg-copy-markdown`),children:[i?(0,$.jsx)(h,{}):(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{className:`msg-action-label`,children:g(i?`copied`:`copy`)})]}),(0,$.jsx)(E_,{type:`button`,className:`msg-action msg-copy-caret-btn${A?` active`:``}`,title:g(`moreCopyOptions`),"aria-label":g(`moreCopyOptions`),"aria-expanded":A,onClick:e=>{e.stopPropagation(),j(e=>!e)},children:(0,$.jsx)(D,{className:`msg-copy-caret-icon${A?` open`:``}`})}),A&&(0,Er.createPortal)((0,$.jsx)(`div`,{ref:N.panelRef,style:N.style,className:`msg-copy-dropdown`,role:`menu`,children:n.map(e=>(0,$.jsxs)(E_,{type:`button`,className:`msg-copy-menu-item`,title:e.label,role:`menuitem`,onClick:()=>{j(!1),S(e.id)},children:[e.icon,(0,$.jsx)(`span`,{children:e.label})]},e.id))}),document.body)]},e)},R=()=>{if(!f){let e=L(`fb-copy`),t=P(`fb-speak`);if(!i&&!e&&!t)return null;let n=[];return i&&n.push((0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(E_,{type:`button`,className:`msg-action`,title:g(`reaskDirectlyTip`),"aria-label":g(`reaskDirectly`),onClick:s,children:[(0,$.jsx)(pe,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:g(`reaskDirectly`)})]}),(0,$.jsxs)(E_,{type:`button`,className:`msg-action`,title:g(`editReaskTip`),"aria-label":g(`editReask`),onClick:c,children:[(0,$.jsx)(dt,{}),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:g(`editReask`)})]})]},`fb-reask`)),e&&n.push(e),t&&n.push(t),n}let l=[],p=!1;return f.forEach((h,_)=>{if(!h||h.hidden===!0||h.id===`host:msg-copy`)return;let v=`${h.id}#${_}`,y=h.label||h.id;if(h.id===`host:msg-copy-text`||h.id===`host:msg-copy-markdown`||h.id===`host:msg-copy-image`){if(!p){p=!0;let e=L(`copy-dropdown`,f);e&&l.push(e)}}else if(h.id===`host:msg-speak`){let e=P(v);e&&l.push(e)}else if(h.id===`host:msg-delete`){if(!a)return;l.push((0,$.jsxs)(E_,{type:`button`,className:`msg-action`,title:y,"aria-label":y,onClick:d,children:[eu(h.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:y})]},v))}else if(h.id===`host:msg-reask`){if(!i)return;l.push((0,$.jsxs)(E_,{type:`button`,className:`msg-action`,title:g(`reaskDirectlyTip`),"aria-label":y,onClick:s,children:[eu(h.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:y})]},v))}else if(h.id===`host:msg-edit-reask`){if(!i)return;l.push((0,$.jsxs)(E_,{type:`button`,className:`msg-action`,title:g(`editReaskTip`),onClick:c,children:[eu(h.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:y})]},v))}else if(h.id===`host:msg-fork`){if(n||t||r)return;l.push((0,$.jsxs)(E_,{type:`button`,className:`msg-action`,title:g(`forkSessionTip`),"aria-label":y,onClick:()=>Z({type:`fork_session`,messageId:e.id,position:`at`}),children:[eu(h.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:y})]},v))}else if(h.id===`host:msg-rollback`){if(!o)return;l.push((0,$.jsxs)(E_,{type:`button`,className:`msg-action`,title:g(`rollbackSessionTip`),"aria-label":y,onClick:()=>{u()},children:[eu(h.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:y})]},v))}else n||(h.kind===`divider`?l.push((0,$.jsx)(`span`,{className:`msg-action-divider`,"aria-hidden":`true`},v)):h.kind===`badge`?l.push((0,$.jsx)(`span`,{className:`msg-action-badge`,title:y,children:h.badge??y},v)):h.kind===`select`&&h.options?.length?l.push((0,$.jsx)(`select`,{className:`msg-action msg-action-select`,title:y,"aria-label":y,value:h.options.some(e=>e.value===h.value)?h.value:h.options[0].value,onChange:e=>m?.(h,e.target.value),children:h.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},v)):l.push((0,$.jsxs)(E_,{type:`button`,className:`msg-action`,title:y,"aria-label":y,onClick:()=>m?.(h),children:[eu(h.icon),` `,(0,$.jsx)(`span`,{className:`msg-action-label`,children:y}),h.badge?(0,$.jsx)(`span`,{className:`msg-action-count`,children:h.badge}):null]},v)))}),l.length===0?null:l};return{canCopyWhole:x,onMsgContextMenu:I,renderMessageActions:()=>{let e=R();return e?(0,$.jsx)(`div`,{className:`msg-actions${A?` has-open-dropdown`:``}`,children:e}):null}}}function e1({message:e,streaming:t,isEmptyStreaming:n,readOnly:r,onEdit:i,onRollbackEdit:a,canRollbackEdit:o,questionAttachments:s,skillBlock:c,editRequest:l}){let u=X(),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)([]),[_,v]=(0,Q.useState)(!1),y=mn(`chatUploadMaxMb`),b=mn(`engine`),x=(0,Q.useRef)(0),[S,C]=(0,Q.useState)([]),w=e=>C(t=>t.filter(t=>t.id!==e)),[T,E]=(0,Q.useState)(null),D=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{D.current&&clearTimeout(D.current)},[]);let O=e=>{E(e),D.current&&clearTimeout(D.current),D.current=setTimeout(()=>E(t=>t===e?null:t),4e3)},k=!r&&e.role===`user`&&!t&&!n&&!!i,A=!r&&b===`pi`&&!t&&!d&&(e.role===`user`||e.role===`assistant`),j=()=>{A&&Z({type:`delete_message`,messageId:e.id})},M=async e=>{let t=[];for(let n of e){if(!ma(n.type))continue;if(n.size>y*1024*1024){O(u(`fileTooLarge`,{name:n.name,size:y}));continue}let e=++x.current;C(t=>[...t,{id:e,name:n.name,percent:null}]);try{let e=await ha(n);if(!e){O(u(`fileLoadFailed`,{name:n.name}));continue}t.push({path:``,imageData:e.data,mimeType:e.mimeType,name:e.name})}catch{O(u(`fileLoadFailed`,{name:n.name}))}finally{w(e)}}t.length>0&&g(e=>[...e,...t])},N=async e=>{if(e.size>y*1024*1024){O(u(`fileTooLarge`,{name:e.name,size:y}));return}let t=++x.current;C(n=>[...n,{id:t,name:e.name,percent:0}]);let n;try{n=(await new Promise((n,r)=>{let i=new FileReader;i.onload=()=>n(i.result),i.onerror=()=>r(i.error??Error(`read failed`)),i.onabort=()=>r(Error(`read aborted`)),i.onprogress=e=>{let n=e.lengthComputable&&e.total>0?Math.min(100,Math.round(e.loaded/e.total*100)):null;C(e=>e.map(e=>e.id===t?{...e,percent:n}:e))},i.readAsDataURL(e)})).replace(/^data:[^;]*;base64,/,``)}catch{O(u(`fileLoadFailed`,{name:e.name}));return}finally{w(t)}g(t=>[...t,{path:``,fileData:n,name:e.name,size:e.size,mimeType:e.type||void 0}])},P=async e=>{let t=[];for(let n of e)ma(n.type)?t.push(n):N(n);t.length>0&&await M(t)},[F,I]=(0,Q.useState)(!1),L=(0,Q.useRef)(!1),R=async(t,n)=>{if(!L.current){if(!n.some(e=>e.imageUrl))i?.(e.id,t,n.length?n:void 0),f(!1);else{L.current=!0,I(!0);try{let r=await Promise.all(n.map(async({imageUrl:e,...t})=>{if(!e)return t;let n=await fetch(He(e));if(!n.ok)throw Error(`Image load failed: ${n.status}`);let r=await n.blob(),i=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(String(n.result)),n.onerror=()=>t(n.error),n.readAsDataURL(r)});return{...t,imageData:i.slice(i.indexOf(`,`)+1),mimeType:r.type||t.mimeType}}));i?.(e.id,t,r.length?r:void 0),f(!1)}catch{f(!0),O(u(`fileLoadFailed`,{name:n.find(e=>e.imageUrl)?.name??`image`}))}finally{L.current=!1,I(!1)}}}},z=()=>{let t=(c?`/skill:`+c.name+(c.userMessage?` `+c.userMessage:``):e.content.map(e=>Gl(e)?.text??``).filter(Boolean).join(`
|
|
53
|
-
`)).trim(),n=!!(s&&s.length>0);(t||n)&&(m(t),g(s??[]),R(t,s??[]))},B=()=>{m(c?`/skill:${c.name}${c.userMessage?` ${c.userMessage}`:``}`:e.content.map(e=>Gl(e)?.text??``).filter(Boolean).join(`
|
|
54
|
-
`)),g(s??[]),f(!0)};return(0,Q.useEffect)(()=>{l&&k&&B()},[l]),{editing:d,setEditing:f,draft:p,setDraft:m,editAttachments:h,setEditAttachments:g,editDragOver:_,setEditDragOver:v,editReads:S,editNotice:T,resending:F,canEdit:k,canDelete:A,canRollback:!r&&!t&&!d&&(k||o),deleteMessage:j,addEditImageFiles:M,addEditDropFiles:P,directReask:z,startEdit:B,rollbackEdit:()=>{k?B():a?.(e.id)},submitEdit:()=>{let e=p.trim();(e||h.some(e=>e.mode===`quote`&&Sa(e.quote)))&&R(e,h)}}}var t1=(0,Q.memo)(function({message:e,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:o,isLast:s,onEdit:c,onKillBash:l,onRetry:u,onCollapse:d,questionAttachments:f,messageLabel:p,onRollbackEdit:m,canRollbackEdit:h=!1,editRequest:g,qnIndex:_,qnActive:v,onJump:y,thinkingWrap:b,toolsWrap:x,toolImages:S,searchActive:C,autoExpand:w,hideProcessBlocks:T=!1,uiMessageActions:E,uiContextMessage:D,uiContextToolCall:O,uiToolCardFooter:k,onUiAction:A,readOnly:j=!1}){let M=X(),N=o&&s&&e.role===`assistant`&&e.content.length===0,P=e.content.map(e=>Gl(e)?.text??``).filter(Boolean).join(`
|
|
55
|
-
`),F=e.role===`user`?fl(P):null,{editing:I,setEditing:L,draft:R,setDraft:z,editAttachments:B,setEditAttachments:V,editDragOver:H,setEditDragOver:ee,editReads:U,editNotice:W,resending:G,canEdit:K,canDelete:q,canRollback:te,deleteMessage:ne,addEditImageFiles:re,addEditDropFiles:J,directReask:ie,startEdit:ae,rollbackEdit:oe,submitEdit:se}=e1({message:e,streaming:o,isEmptyStreaming:N,readOnly:j,onEdit:c,onRollbackEdit:m,canRollbackEdit:h,questionAttachments:f,skillBlock:F,editRequest:g}),Y=Dl(),{canCopyWhole:ce,onMsgContextMenu:le,renderMessageActions:ue}=$_({message:e,streaming:o,readOnly:j,editing:I,canEdit:K,canDelete:q,canRollback:te,directReask:ie,startEdit:ae,rollbackEdit:oe,deleteMessage:ne,uiMessageActions:E,uiContextMessage:D,onUiAction:A}),de=!E||E.some(e=>e?.id===`host:msg-copy`&&e.hidden!==!0),fe=(0,Q.useRef)(null);if(e.role===`toolResult`||e.role===`system`)return null;if(e.role===`compactionSummary`)return(0,$.jsx)(su,{message:e,forceOpen:C,autoExpand:w,renderMessage:i1});let me=e.role===`custom`&&e.customType===`background-job-done`,he=me?e.details??null:null,ge=e.role===`custom`&&e.customType===`file`,_e=ge&&e.details?.mode===`quote`?Sa(e.details.quote):null,ve=e.details?.quotes,ye=e.role===`user`&&Array.isArray(ve)?ve.map(Sa).filter(e=>e!==null):[],xe=e.details?.attachments,Se=e.role===`user`&&Array.isArray(xe)?xe.filter(t=>t.type!==`image`||!e.content.some(e=>e.type===`image`)):[],Ce=F?F.userMessage??`skill:${F.name}`:P.split(`
|
|
56
|
-
`).join(` `).trim(),we=e.role===`custom`&&(e.customType===`goal-review`||e.customType===`goal-wizard`),Te=e.role===`custom`&&e.customType===`goal-wizard`,Ee=e.role===`custom`&&!!e.customType&&e.customType!==`file`&&!we&&Bc(e.customType),De=Ee?JSON.stringify({customType:e.customType,details:e.details??{}}):``,Oe=Y.open&&Y.selectedIds.includes(e.id),ke=Y.open&&ce,Ae=Oe&&Y.includeThinking,je=Oe&&Y.includeTools,Me=!I&&(e.role===`user`||ce),Ne=(0,Q.useMemo)(()=>{if(e.role!==`assistant`)return-1;for(let t=e.content.length-1;t>=0;t--)if(Gl(e.content[t]))return t;return-1},[e.role,e.content]),Pe=(0,Q.useMemo)(()=>e.role===`custom`&&e.customType===`background-task-notification`?Ur(P,e.details):null,[e.role,e.customType,e.details,P]),Fe=(0,Q.useMemo)(()=>{if(e.role!==`user`)return null;for(let t of e.content){let e=Gl(t);if(e){let t=Xl(e.text);if(t)return t}}return null},[e.role,e.content]);return(0,$.jsxs)(`div`,{ref:fe,className:`msg msg-${e.role}${Fe?Fe.isNotice?` msg-collab-notice`:` msg-collaboration`:``}${we?` msg-goal-review`:``}${Oe?` msg-export-selected`:``}${j?` msg-readonly`:``}${p&&e.id.startsWith(`group-`)?` msg-group`:``}`,"data-role":e.role,"data-msg-id":e.id,onContextMenu:le,children:[ke&&(0,$.jsx)(`input`,{type:`checkbox`,className:`msg-export-check`,checked:Oe,title:M(`copyImage`),"aria-label":M(`copyImage`),onClick:e=>e.stopPropagation(),onChange:()=>jl(e.id)}),(0,$.jsxs)(`div`,{className:`msg-meta`,children:[d&&(0,$.jsxs)(`button`,{type:`button`,className:`msg-collapse-btn`,title:M(`collapseMsg`),onClick:()=>d(e.id),children:[(0,$.jsx)(a,{}),` `,M(`collapseMsg`)]}),(0,$.jsx)(`span`,{className:`msg-role`,children:e.role===`custom`?Te?M(`goalWizardCard`):we?M(`goalBarTitle`):e.customType===`file`?M(`attachment`):e.customType===`background-job-done`?M(`bgTaskJobKind`):e.customType===`background-task-notification`?M(`bgTaskNotificationLabel`):`${M(`plugin`)} · ${e.customType??M(`unknown`)}`:Fe?Fe.isNotice?`${M(`subagentBadge`)} · ${M(`subagentCompletionNotice`)}`:`${M(`subagentBadge`)} · ${Fe.sourceTitle||Fe.sourceRole||M(`subagentBadge`)}`:nu(e.role,M)}),p&&(0,$.jsx)(`span`,{className:`msg-sender`,"data-initial":Array.from(p)[0],children:p}),e.model&&(0,$.jsx)(`span`,{className:`msg-model`,children:e.model}),e.timestamp&&(0,$.jsx)(`span`,{className:`msg-time`,children:ru(e.timestamp)}),_!==void 0&&y&&(0,$.jsxs)(`button`,{type:`button`,className:`qn-tag ${v?`active`:``}`,title:`${_+1}. ${Ce}`,"aria-label":`${_+1}. ${Ce}`,onClick:()=>y(e.id),children:[(0,$.jsx)(`span`,{className:`qn-tag-bar`}),(0,$.jsx)(`span`,{className:`qn-tag-idx`,children:_+1})]})]}),(0,$.jsx)(`div`,{className:`msg-body`,children:I?(0,$.jsxs)(`div`,{className:`msg-editor${H?` drag-over`:``}`,onDragOver:e=>{e.preventDefault(),e.stopPropagation(),ee(!0)},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||ee(!1)},onDrop:e=>{e.preventDefault(),e.stopPropagation(),ee(!1),J(Array.from(e.dataTransfer?.files??[]))},children:[B.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-images`,children:B.map((e,t)=>{if(e.mode===`quote`&&e.quote)return(0,$.jsx)(Ds,{quote:e.quote,onRemove:()=>V(e=>e.filter((e,n)=>n!==t))},`quote-${t}`);let n=Zl(e),r=e.imageUrl,a=r?He(r):`data:${e.mimeType??`image/png`};base64,${e.imageData}`;return(0,$.jsxs)(`span`,{className:`msg-editor-img ${n===`image`?``:`file-chip`}`,title:Ql(e,M),children:[n===`image`?(0,$.jsx)(`img`,{crossOrigin:i(a),src:a,alt:e.name,className:`msg-editor-img-clickable`,title:M(`toolImageZoom`),onClick:()=>Tn({src:a,alt:e.name})}):(0,$.jsxs)(`span`,{className:`msg-editor-file`,children:[(0,$.jsx)(`span`,{className:`msg-editor-file-icon`,children:n===`path`?e.mode===`page`?`🌐`:e.mode===`reference`?`🔗`:`📎`:`📄`}),(0,$.jsx)(`span`,{className:`msg-editor-file-name`,children:e.name??e.path?.split(`/`).pop()})]}),(0,$.jsx)(`button`,{type:`button`,className:`msg-editor-img-remove`,title:M(`removeAttachment`),onClick:()=>V(e=>e.filter((e,n)=>n!==t)),children:(0,$.jsx)(Ct,{})})]},`${e.name??e.path??`att`}-${t}`)})}),U.length>0&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,role:`status`,"aria-live":`polite`,"aria-atomic":`true`,children:U.map(({id:e,name:t,percent:n})=>(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:6,minWidth:0},children:[(0,$.jsx)(`progress`,{max:100,value:n??void 0,"aria-label":n===null?M(`uploadPreparing`,{name:t}):M(`uploadReading`,{name:t,percent:n}),style:{width:64,flexShrink:0}}),(0,$.jsx)(`span`,{style:{overflowWrap:`anywhere`,minWidth:0},children:n===null?M(`uploadPreparing`,{name:t}):M(`uploadReading`,{name:t,percent:n})})]},e))}),W&&(0,$.jsx)(`div`,{className:`msg-editor-notice`,children:W}),(0,$.jsx)(`textarea`,{className:`msg-editor-input`,value:R,autoFocus:!0,placeholder:M(`editPlaceholder`),rows:Math.max(2,Math.min(10,R.split(`
|
|
57
|
-
`).length+1)),onChange:e=>z(e.target.value),onPaste:e=>{let t=[];for(let n of e.clipboardData?.items??[])if(n.kind===`file`&&ma(n.type)){let e=n.getAsFile();e&&t.push(e)}t.length!==0&&(e.preventDefault(),re(t))},onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)?(e.preventDefault(),se()):e.key===`Escape`&&L(!1)}}),(0,$.jsxs)(`div`,{className:`msg-editor-actions`,children:[(0,$.jsxs)(`span`,{className:`msg-editor-hint`,children:[(0,$.jsx)(be,{}),` `,M(`editAttachmentHint`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn sm`,onClick:()=>L(!1),children:M(`cancel`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary sm`,disabled:G||!R.trim()&&!B.some(e=>e.mode===`quote`&&Sa(e.quote)),title:M(`reaskFromHere`),onClick:se,children:[(0,$.jsx)(dt,{}),` `,M(`reaskFromHere`)]})]})]}):(0,$.jsxs)($.Fragment,{children:[Nl(e)?(0,$.jsx)(`div`,{className:`msg-stopped`,role:`status`,children:M(`turnStopped`)}):e.errorMessage&&(0,$.jsxs)(`div`,{className:`msg-error`,children:[e.errorInfo?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`span`,{className:`msg-error-text`,children:[M(Ll[e.errorInfo.kind]??`modelError.unknown`),typeof e.errorInfo.status==`number`?` · HTTP ${e.errorInfo.status}`:``]}),e.errorInfo.summary&&(0,$.jsx)(`span`,{className:`msg-error-text`,style:{marginTop:4},children:e.errorInfo.summary}),e.errorInfo.retries&&e.errorInfo.retries.attempt>0&&(0,$.jsx)(`span`,{className:`msg-error-text`,style:{marginTop:4},children:M(`modelError.retried`,{attempt:e.errorInfo.retries.attempt,max:e.errorInfo.retries.maxAttempts||e.errorInfo.retries.attempt})}),e.errorMessage.trim()!==e.errorInfo.summary.trim()&&(0,$.jsxs)(`details`,{style:{marginTop:6,minWidth:0},children:[(0,$.jsx)(`summary`,{style:{cursor:`pointer`,minWidth:0,overflowWrap:`anywhere`},children:M(`modelError.rawResponse`)}),(0,$.jsx)(`pre`,{style:{margin:`6px 0 0`,maxHeight:260,overflow:`auto`,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,wordBreak:`break-word`,font:`inherit`,minWidth:0},children:e.errorMessage})]})]}):(0,$.jsx)(`span`,{className:`msg-error-text`,children:e.errorMessage}),s&&!o&&u&&(0,$.jsxs)(`button`,{type:`button`,className:`msg-retry-btn`,title:M(`retryLastTip`),onClick:u,children:[(0,$.jsx)(pe,{}),` `,M(`retryNow`)]})]}),ye.map((e,t)=>(0,$.jsx)(Ds,{quote:e,forceOpen:C},`quote-${t}`)),Se.length>0&&(0,$.jsx)(`div`,{className:`msg-queued-atts-bar`,children:Se.map((t,n)=>{let r;if(t.url)r=t.url.startsWith(`/`)?He(t.url):t.url;else if(t.type===`image`||t.type===`vision-bridge`){let n=f?.find(e=>e.name===t.name||e.imageData||e.imageUrl);if(n?.imageUrl)r=He(n.imageUrl);else if(n?.imageData)r=`data:${n.mimeType??`image/png`};base64,${n.imageData}`;else{let t=e.content.find(e=>e.type===`image`);t?.dataUrl&&(r=t.dataUrl.startsWith(`/`)?He(t.dataUrl):t.dataUrl)}}let i=!!(t.path&&t.type!==`page`&&t.type!==`conversation`&&t.type!==`canvas`),a=!!(r||i),o=()=>{r?Tn({src:r,alt:t.name}):i&&t.path&&Jt({path:t.path,name:t.name})};return(0,$.jsxs)(`span`,{className:`queued-att-chip${a?` previewable`:``}`,title:a?`${t.name} (${M(r?`toolImageZoom`:`fileOpenPreview`)})`:t.name,onClick:a?o:void 0,role:a?`button`:void 0,tabIndex:a?0:void 0,onKeyDown:a?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),o())}:void 0,children:[(0,$.jsx)(`span`,{className:`queued-att-icon`,children:t.type===`image`||t.type===`vision-bridge`?`🖼️`:t.type===`folder`?`📁`:t.type===`page`?`🌐`:t.type===`conversation`?`💬`:`📎`}),(0,$.jsx)(`span`,{className:`queued-att-name`,children:t.name})]},`qatt-${n}`)})}),_e?(0,$.jsx)(Ds,{quote:_e,forceOpen:C}):me&&he?.jobId?(0,$.jsx)(n1,{details:he}):Pe?(0,$.jsx)(ul,{task:Pe}):ge?(0,$.jsx)(au,{message:e,forceOpen:C}):F?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(cu,{block:F,forceOpen:C}),F.userMessage&&(0,$.jsx)(`div`,{className:`msg-text`,children:(0,$.jsx)(nl,{text:F.userMessage,hardBreaks:!0})}),e.content.map((i,a)=>i.type===`text`?null:(0,$.jsx)(C_,{block:i,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:o,isLast:s,isTrailingBlock:a===e.content.length-1,onKillBash:l,toolsWrap:x,toolImages:S,thinkingWrap:b,searchActive:C,forceThinking:Ae,forceTools:je,role:e.role,showCopy:de,uiContextToolCall:O,uiToolCardFooter:k,onUiAction:A,parentTimestamp:e.timestamp,parentDurationMs:e.durationMs,parentId:e.id,blockIndex:a},a))]}):Ee?(0,$.jsx)(ll,{type:e.customType??``,code:De,children:e.content.map((i,a)=>(0,$.jsx)(C_,{block:i,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:o,isLast:s,isTrailingBlock:a===e.content.length-1,onKillBash:l,toolsWrap:x,toolImages:S,thinkingWrap:b,searchActive:C,hideProcessBlocks:T,forceThinking:Ae,forceTools:je,role:e.role,showCopy:de,uiContextToolCall:O,uiToolCardFooter:k,onUiAction:A,parentTimestamp:e.timestamp,parentDurationMs:e.durationMs,parentId:e.id,blockIndex:a},a))}):e.content.map((i,a)=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsx)(C_,{block:i,toolResults:t,liveOutputs:n,toolStatuses:r,streaming:o,isLast:s,isTrailingBlock:a===e.content.length-1,onKillBash:l,toolsWrap:x,toolImages:S,thinkingWrap:b,searchActive:C,hideProcessBlocks:T,forceThinking:Ae,forceTools:je,role:e.role,showCopy:de,uiContextToolCall:O,uiToolCardFooter:k,onUiAction:A,parentTimestamp:e.timestamp,parentDurationMs:e.durationMs,parentId:e.id,blockIndex:a}),a===Ne&&Me&&ue()]},a)),N&&(0,$.jsx)(`div`,{className:`thinking-wait minimal`,title:M(`thinkingWait`),"aria-label":M(`thinkingWait`),role:`status`,children:(0,$.jsx)(`span`,{className:`dot`})})]})}),Me&&Ne<0&&ue()]})});function n1({details:e}){let t=X(),{locale:n}=_e(),r=e.ok??e.exitCode===0,i=n.startsWith(`zh`)?e.reasonText||e.reasonEn||e.reason:e.reasonEn||e.reasonText||e.reason;return(0,$.jsxs)(`div`,{className:`bashblock`,children:[(0,$.jsxs)(`div`,{className:`bashblock-command`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:e.command||e.jobId}),(0,$.jsx)(`span`,{className:`bashblock-exit ${r?`ok`:`err`}`,children:t(r?`done`:`error`)}),e.exitCode!==void 0&&e.exitCode!==null&&(0,$.jsx)(`span`,{className:`bashblock-exit ${r?`ok`:`err`}`,children:t(`exitCode`,{code:e.exitCode})})]}),i&&(0,$.jsx)(`div`,{className:`trunc-note`,children:i}),e.tail&&(0,$.jsx)(`pre`,{className:`bashblock-output`,children:e.tail}),e.logPath&&(0,$.jsx)(`div`,{className:`trunc-note mono`,children:e.logPath})]})}var r1=new Map;function i1(e,t){return(0,$.jsx)(t1,{message:e,toolResults:t,liveOutputs:r1,toolStatuses:r1,streaming:!1,isLast:!1,readOnly:!0},e.id)}function a1(e,t){let n=e.historyStart??0;return t.resyncRequired===!0||t.historyGeneration!==e.historyGeneration||t.historyStart+t.messages.length!==n||t.before!==void 0&&t.before!==n||t.historyGeneration!==void 0&&(t.before!==n||t.beforeId!==e.messages[0]?.id)}function o1(e,t){if(a1(e,t))return null;let n=e.historyStart??0,r=e.historyTotal??e.messages.length;return t.messages.length===0?t.historyStart===n&&t.historyTotal===r?null:{...e,historyStart:t.historyStart,historyTotal:t.historyTotal}:{...e,messages:[...t.messages,...e.messages],historyStart:t.historyStart,historyTotal:t.historyTotal}}function s1(e){let t=Math.max(0,e.historyStart??0);return e.isPagingActive?Math.max(0,e.totalMessages-Math.min(e.totalMessages,e.visibleCount))+t:t}var c1=`pi-web-sounds`,l1={enabled:!0,question:!0,done:!0,subagentDone:!0,start:!1,error:!0,approval:!0,volume:100};function u1(){try{let e=localStorage.getItem(c1);if(!e)return{...l1};let t=JSON.parse(e),n={...l1,...t};t.subagentDone===void 0&&typeof t.done==`boolean`&&(n.subagentDone=t.done);for(let e of[`enabled`,`question`,`done`,`subagentDone`,`start`,`error`,`approval`])typeof n[e]!=`boolean`&&(n[e]=l1[e]);return n.volume=typeof n.volume!=`number`||!Number.isFinite(n.volume)?l1.volume:Math.round(Math.max(0,Math.min(100,n.volume))/5)*5,n}catch{return{...l1}}}function d1(e){try{localStorage.setItem(c1,JSON.stringify(e))}catch{}J()&&typeof window<`u`&&window.dispatchEvent(new Event(`pi-web-ui:sound-settings`))}var f1=null;function p1(){try{if(!f1){let e=window.AudioContext??window.webkitAudioContext;if(!e)return null;f1=new e}return f1.state===`suspended`&&f1.resume(),f1}catch{return null}}var m1=[{type:`sine`,freq:587.33,start:0,dur:.13,peak:.5},{type:`sine`,freq:880,start:.11,dur:.24,peak:.5}],h1=[{type:`sine`,freq:880,start:0,dur:.15,peak:.35},{type:`sine`,freq:587.33,start:.15,dur:.32,peak:.35}],g1={question:m1,done:h1,subagentDone:h1,start:[{type:`triangle`,freq:660,start:0,dur:.08,peak:.22}],error:[{type:`square`,freq:220,start:0,dur:.16,peak:.18},{type:`square`,freq:174.61,start:.18,dur:.26,peak:.18}],approval:[{type:`sine`,freq:659.25,start:0,dur:.11,peak:.45},{type:`sine`,freq:659.25,start:.14,dur:.11,peak:.45},{type:`sine`,freq:880,start:.28,dur:.26,peak:.5}]};function _1(e,t,n){let r=e.createOscillator(),i=e.createGain();r.type=t.type,r.frequency.value=t.freq;let a=e.currentTime+t.start,o=Math.max(1e-4,t.peak*n);i.gain.setValueAtTime(1e-4,a),i.gain.exponentialRampToValueAtTime(o,a+.012),i.gain.exponentialRampToValueAtTime(1e-4,a+t.dur),r.connect(i),i.connect(e.destination),r.start(a),r.stop(a+t.dur+.05)}function v1(e,t=u1()){if(!t.enabled||!t[e])return;let n=p1();if(!n)return;let r=Math.max(0,Math.min(1,t.volume/100));for(let t of g1[e])_1(n,t,r)}var y1=`pi-web-ui:notification-click`;function b1(e){let t=t=>{let n=t instanceof CustomEvent?t.detail:t.data;if(n?.type===y1&&typeof n.url==`string`)try{let t=J()?new URL(n.url,window.location.href):new URL(n.url),r=new URL(We(),window.location.href);if(t.origin!==r.origin||!t.pathname.startsWith(r.pathname))return;J()&&t.searchParams.delete(`token`),e(t.href)}catch{}};return window.addEventListener(y1,t),J()||navigator.serviceWorker?.addEventListener(`message`,t),()=>{window.removeEventListener(y1,t),J()||navigator.serviceWorker?.removeEventListener(`message`,t)}}var x1=[`question`,`done`,`subagentDone`,`start`,`error`,`approval`];function S1(e,t,n){if(!t.enabled)return!1;let r=t.events?.[e];return r===`on`||r!==`off`&&n[e]}var C1=`pi-web-notify`,w1={enabled:!1};function T1(){let e=oe(),t=e?.pushAdapter?.getState(),n=e?t?.enabled??!1:void 0;if(t?.kinds)return{enabled:t.enabled,events:Object.fromEntries(x1.map(e=>[e,t.kinds.includes(e)?`on`:`off`]))};try{let e=localStorage.getItem(C1);if(!e)return{enabled:n??w1.enabled};let t=JSON.parse(e),r={};for(let e of x1){let n=t.events?.[e];(n===`follow`||n===`on`||n===`off`)&&(r[e]=n)}return{enabled:n??(typeof t.enabled==`boolean`?t.enabled:w1.enabled),events:r}}catch{return{enabled:n??w1.enabled}}}function E1(e){return oe()?.pushAdapter?.subscribe(e)??(()=>{})}async function D1(e=T1()){let t=oe()?.pushAdapter;if(!t?.setKinds)return;let n=u1(),r=x1.filter(t=>S1(t,{...e,enabled:!0},n));await t.setKinds(r)}async function O1(e){let t=e?await U1():H1(),n=e&&t===`granted`,r=oe();if(r){let e=r.pushAdapter;return e?(n&&await D1(),await e.setEnabled(n),e.getState().enabled):!1}return n}function k1(e){try{localStorage.setItem(C1,JSON.stringify(e))}catch{}D1(e).catch(e=>console.warn(`Push event settings failed:`,e))}function A1(){return J()?oe()?.pushAdapter?.getState().supported??!1:typeof window<`u`&&`Notification`in window}function j1(){return A1()?null:J()?`unsupported`:typeof window<`u`&&window.isSecureContext===!1?`insecure`:`unsupported`}function M1(e){let{screenX:t,screenY:n,outerWidth:r,outerHeight:i}=e;return Number.isFinite(t)&&N1(t)||Number.isFinite(n)&&N1(n)?!0:r>0&&r<=400&&i>0&&i<=40}function N1(e){return e<=-1e4}function P1(e){return!(e.visibility!==`visible`||e.minimized||!e.hasFocus||e.windows&&e.idleMs>12e4)}var F1=Date.now(),I1=!1;function L1(){F1=Date.now()}function R1(){return Math.max(0,Date.now()-F1)}function z1(){if(I1||typeof window>`u`)return;I1=!0;let e={passive:!0,capture:!0};for(let t of[`pointerdown`,`pointermove`,`keydown`,`wheel`,`touchstart`,`focus`,`scroll`])window.addEventListener(t,L1,e);typeof document<`u`&&document.addEventListener(`visibilitychange`,L1,e)}function B1(){return typeof navigator>`u`?!1:/windows/i.test(navigator.userAgent??``)}function V1(){return z1(),typeof window>`u`||typeof document>`u`?{hasFocus:!0,visibility:`visible`,minimized:!1,idleMs:0,windows:!1}:{hasFocus:typeof document.hasFocus!=`function`||document.hasFocus(),visibility:document.visibilityState??``,minimized:M1({screenX:window.screenX,screenY:window.screenY,outerWidth:window.outerWidth,outerHeight:window.outerHeight}),idleMs:R1(),windows:B1()}}function H1(){return J()?oe()?.pushAdapter?.getState().permission??`denied`:A1()?Notification.permission:`denied`}async function U1(){if(J())return oe()?.pushAdapter?.requestPermission()??`denied`;if(!A1())return`denied`;try{return await Notification.requestPermission()}catch{return`denied`}}function W1(e){return e instanceof Error?`${e.name}: ${e.message}`:String(e)}function G1(e,t=!1,n){let r=typeof location<`u`?location.href:We();try{let e=new URL(r);e.searchParams.delete(`token`),e.searchParams.delete(`view`),n&&(e.hash=O_({sessionId:n})),r=e.href}catch{}return{body:e,requireInteraction:t,icon:g(`/icons/icon-192.png`,We()),badge:g(`/icons/icon-192.png`,We()),data:{url:r}}}async function K1(e,t,n=!1,r){if(J())return{path:`none`,error:`native push`};if(!A1())return{path:`none`,error:`unsupported`};if(Notification.permission!==`granted`)return{path:`none`,error:`permission: ${Notification.permission}`};let i=G1(t,n,r),a;try{let t=await navigator.serviceWorker?.getRegistration();if(t?.active&&typeof t.showNotification==`function`)return await t.showNotification(e,i),{path:`sw`};a=t?`service worker not active`:`no service worker registration`}catch(e){a=W1(e)}try{let t=new Notification(e,i);return t.onclick=()=>{t.close(),window.focus(),window.dispatchEvent(new CustomEvent(y1,{detail:{type:y1,url:i.data.url}}))},{path:`page`,error:a}}catch(e){return{path:`none`,error:`${a}; page: ${W1(e)}`}}}async function q1(e,t,n=`done`,r){!J()&&A1()&&(P1(V1())||S1(n,T1(),u1())&&await K1(e,t,!1,r))}var J1=new Map;function Y1(e,t,n={}){return new Promise(r=>{if(n.signal?.aborted){r({ok:!1,reason:`cancelled`});return}let i=or(),a=e=>{J1.delete(i)&&(clearTimeout(s),n.signal?.removeEventListener(`abort`,o),r(e))},o=()=>a({ok:!1,reason:`cancelled`}),s=setTimeout(()=>a({ok:!1,reason:`timeout`}),n.timeoutMs??(t.action===`reconnect`?12e4:t.action===`stop`?6e4:15e3));J1.set(i,{...t,finish:a}),n.signal?.addEventListener(`abort`,o,{once:!0});try{e({type:`terminal_cli_control`,requestId:i,ownerKind:`conversation`,...t})||a({ok:!1,reason:`unavailable`})}catch{a({ok:!1,reason:`unavailable`})}})}function X1(e){let t=J1.get(e.requestId);return!t||t.terminalId!==e.terminalId||t.conversationId!==e.conversationId?!1:(t.finish({ok:e.ok,error:e.error}),!0)}var Z1=new Set,Q1=512,$1={done:[`nativeCliSession.doneTitle`,`nativeCliSession.doneBody`],error:[`nativeCliSession.errorTitle`,`nativeCliSession.errorBody`],question:[`nativeCliSession.questionTitle`,`nativeCliSession.questionBody`],approval:[`nativeCliSession.approvalTitle`,`nativeCliSession.approvalBody`]};function e0(e){if(!e.eventId?.trim()||!e.conversationId?.trim()||!e.sessionId?.trim()||!Number.isFinite(e.occurredAt)||!Object.hasOwn($1,e.kind))return;let t=JSON.stringify([e.conversationId,e.eventId]);if(Z1.has(t))return;Z1.add(t),Z1.size>Q1&&Z1.delete(Z1.values().next().value);let n=Ye(it())?we:gt,[r,i]=$1[e.kind];v1(e.kind),q1(n[r],n[i],e.kind,e.sessionId)}function t0(){let e=globalThis.__piPhoneHost;return typeof e?.phoneCall==`function`?e.phoneCall.bind(e):void 0}var n0=new Map,r0=new Set,i0=new Map;function a0(){i0=new Map(n0);for(let e of r0)try{e()}catch{}}function o0(e,t){let n=String(e??``).trim();if(!n)return!1;let r=n0.get(n);if(t===null)return r?(n0.delete(n),a0(),!0):!1;let i=String(t.text??``).trim();if(!i)return r?(n0.delete(n),a0(),!0):!1;let a={text:i,...t.tip?{tip:t.tip}:{},...t.pluginId?{pluginId:t.pluginId}:{},...t.action?{action:t.action}:{},...typeof t.content?.render==`function`?{content:t.content}:{}};return r&&r.text===a.text&&r.tip===a.tip&&r.action===a.action&&r.content?.render===a.content?.render?!1:(n0.set(n,a),a0(),!0)}function s0(e){let t=!1;for(let[n,r]of n0)r.pluginId===e&&(n0.delete(n),t=!0);t&&a0()}function c0(e){return r0.add(e),()=>r0.delete(e)}function l0(){return(0,Q.useSyncExternalStore)(c0,()=>i0,()=>i0)}function u0(e){let t=l0();if(e)return t.get(e)??null;for(let e of t.values())return e;return null}function d0(e,t){if(!t?.isolated)return{container:e,isShadow:!1,cleanup:()=>{e.replaceChildren()}};let n=e.shadowRoot;if(!n)try{n=e.attachShadow({mode:`open`})}catch{n=e.shadowRoot}if(!n)return{container:e,isShadow:!1,cleanup:()=>{e.replaceChildren()}};n.replaceChildren();let r=document.createElement(`style`);r.textContent=`
|
|
58
|
-
:host {
|
|
59
|
-
display: block;
|
|
60
|
-
width: 100%;
|
|
61
|
-
height: 100%;
|
|
62
|
-
box-sizing: border-box;
|
|
63
|
-
color: var(--text, inherit);
|
|
64
|
-
font-family: inherit;
|
|
65
|
-
font-size: var(--text-base, 13.5px);
|
|
66
|
-
line-height: 1.5;
|
|
67
|
-
}
|
|
68
|
-
*, *::before, *::after {
|
|
69
|
-
box-sizing: inherit;
|
|
70
|
-
}
|
|
71
|
-
`,n.appendChild(r);let i=document.createElement(`div`);return i.className=`plugin-isolated-root`,i.style.cssText=`width:100%;height:100%;display:flex;flex-direction:column;`,n.appendChild(i),{container:i,isShadow:!0,cleanup:()=>{i.replaceChildren(),n?.replaceChildren()}}}var f0=`pi-web-ui:plugin-data`;function p0(e,t){window.dispatchEvent(new CustomEvent(f0,{detail:{pluginId:e,payload:t}}))}function m0(e){let t=t=>{let n=t.detail;e(n.pluginId,n.payload)};return window.addEventListener(f0,t),()=>window.removeEventListener(f0,t)}var h0=new Map,g0=new Map;function _0(e){let t=g0.get(e);g0.delete(e);try{t?.()}catch(t){console.error(`[plugin:${e}] preload cleanup failed:`,t)}}var v0=new Set,y0=new Set,b0=new Set,x0=-1,S0=null;function C0(){return[...h0.values()]}function w0(){let e=C0();for(let t of v0)t(e)}function T0(){let e=[...y0];for(let t of b0)t(e)}function E0(e){return b0.add(e),e([...y0]),()=>b0.delete(e)}async function D0(e,t){y0.delete(e.id),k0.set(e.id,(k0.get(e.id)??0)+1),T0();let n=await P0(e,t);return w0(),n}function O0(e){return v0.add(e),e(C0()),()=>v0.delete(e)}var k0=new Map;function A0(e,t){let n=k0.get(e)??0;return j(`/plugins/${encodeURIComponent(e)}/client/entry.mjs?e=${t}${n>0?`&r=${n}`:``}`)}function j0(e){let t=Promise.resolve();return(n,r)=>{if(J())return Promise.reject(Error(`Remote plugin clients are unavailable in the native app`));let i=t.then(()=>zn(n,()=>e(r)));return t=i.then(()=>void 0,()=>void 0),i}}var M0=j0(e=>import(e));async function N0(e,t,n){if(J()||!e.hasClient||e.error)return null;n?.retry&&k0.set(e.id,(k0.get(e.id)??0)+1);try{let n=await M0(e.id,A0(e.id,t)),r=n.default??n;return{...r,fileHandlers:r.fileHandlers??n.fileHandlers}}catch(t){return console.error(`[plugin:${e.id}] 客户端 bundle 加载失败:`,t),null}}async function P0(e,t){if(J())return!1;try{let n=await M0(e.id,A0(e.id,t));if(x0!==-1&&t!==x0||S0&&!S0.has(e.id)){try{n.default?.dispose?.()}catch(t){console.error(`[plugin:${e.id}] stale bundle cleanup failed:`,t)}return Un(e.id),!1}let r=n.default;return r&&typeof r.mount==`function`?(h0.set(e.id,{info:e,module:r}),!0):e.preload?(g0.set(e.id,typeof r?.dispose==`function`?()=>r.dispose?.():void 0),!0):(Un(e.id),y0.add(e.id),T0(),console.error(`[plugin:${e.id}] entry.mjs 缺少 default.mount`),!1)}catch(t){return Un(e.id),y0.add(e.id),T0(),console.error(`[plugin:${e.id}] 客户端加载失败:`,t),!1}}async function F0(e,t){if(J())return!1;if(h0.has(e.id)||g0.has(e.id))return!0;if(y0.has(e.id)||!e.hasClient)return!1;let n=await P0(e,t);return w0(),n}async function I0(e,t){if(J())return;let n=new Set(e.filter(e=>!e.error).map(e=>e.id));if(S0)for(let e of S0)n.has(e)||s0(e);if(S0=n,Cn(S0),t!==x0){x0=t,Un(),h0.clear();for(let e of[...g0.keys()])_0(e);y0.clear(),k0.clear(),T0()}let r=new Set(e.map(e=>e.id));for(let t of[...h0.keys()])(!r.has(t)||e.find(e=>e.id===t)?.error)&&(Un(t),h0.delete(t),k0.set(t,(k0.get(t)??0)+1));for(let t of[...g0.keys()])(!r.has(t)||e.find(e=>e.id===t)?.error)&&(Un(t),_0(t),k0.set(t,(k0.get(t)??0)+1));for(let e of[...y0])r.has(e)||y0.delete(e);T0(),await Promise.all(e.filter(e=>e.hasClient&&(e.view!==!1||e.preload)&&!e.error&&!h0.has(e.id)&&!g0.has(e.id)&&!y0.has(e.id)).map(e=>P0(e,t))),w0()}function L0(e,t,n){let r=n?.page;return{pluginId:e,...r?{page:r}:{},send:n=>t({type:`plugin_message`,pluginId:e,payload:n}),onData:t=>m0((n,r)=>{n===e&&t(r)})}}var R0=[`debug`,`info`,`warn`,`error`];function z0(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`get`}}}function B0(e){return{type:`plugin_message`,pluginId:e,payload:{__host:`logs`,op:`clear`}}}function V0(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.__host!==`logs`||!Array.isArray(t.logs)?!1:t.logs.every(e=>!!e&&typeof e==`object`&&typeof e.ts==`number`&&typeof e.text==`string`&&R0.includes(String(e.level)))}var H0=new Map,U0=new Set;function W0(){for(let e of[...U0])try{e()}catch{}}function G0(e){return U0.add(e),()=>U0.delete(e)}function K0(e){return(H0.get(e)??[]).map(e=>({...e}))}function q0(e,t){return V0(t)?(H0.set(e,t.logs.map(e=>({ts:e.ts,level:e.level,text:e.text}))),W0(),!0):!1}var J0=/(?:\x1b\[(?:[>=]?0?c|\??6n|5n|\??\d+\$p|1[4-9]t|>0?q)|\x1b\](?:1[0-2]|4;\d+);\?(?:\x07|\x1b\\))+/g;function Y0(e){return e.replace(J0,``)}function X0(e){return e.type===`terminal_list`||(e.type===`terminal_output`||e.type===`terminal_exit`)&&e.ownerKind===`client`}function Z0(){let e=new Map,t=new Map,n=(e,t,n)=>JSON.stringify([n??`legacy`,n===`client`?``:e,t]),r=(e,t)=>[...e].filter(e=>{let[n,,r]=JSON.parse(e);return n===`legacy`&&r===t}),i=(e,t,n)=>{try{if(n){if(!e.reset)return;e.reset(),e.write(Y0(t));return}e.write(t)}catch{}};return{write(a,o,s,c=!1,l){let u=n(a,o,l),d=l||e.get(u)?.size?[u]:r(e.keys(),o);for(let t of d)for(let n of e.get(t)??[])i(n,s,c);let f=t.get(u)??(l?void 0:t.get(r(t.keys(),o)[0]));if(!l)for(let e of r(t.keys(),o))t.delete(e);t.set(u,{data:(c?s:(f?.data??``)+s).slice(-2e6),reset:c||(f?.reset??!1)})},register(a,o,s,c){let l=n(a,o,c),u=e.get(l);u||e.set(l,u=new Set),u.add(s);let d=t.get(l)??(c?void 0:t.get(r(t.keys(),o)[0]));return d&&i(s,d.data,d.reset),()=>{let t=e.get(l);t?.delete(s),t?.size||e.delete(l)}},reconcile(e,r,i){let a=new Set(r.map(t=>n(e,t.id,t.ownerKind??`client`)));for(let n of t.keys()){let[r,o]=JSON.parse(n);i===`client`?r===`client`&&!a.has(n)&&t.delete(n):i===`conversation`?r===`conversation`&&o===e&&!a.has(n)&&t.delete(n):r!==`client`&&o!==e||a.has(n)||t.delete(n)}},clear(e){if(!e)t.clear();else for(let n of t.keys()){let[r]=JSON.parse(n);(e===`client`?r===`client`:r!==`client`)&&t.delete(n)}}}}function Q0(e){let t=typeof e.name==`string`?e.name:``;if(e.unsupported===!0)return{name:t,status:`unsupported`};if(e.found!==!0)return{name:t,status:`missing`};let n={name:t,status:`ready`};return e.defaultDescription&&(n.defaultDescription=e.defaultDescription),e.defaultPromptSnippet&&(n.defaultPromptSnippet=e.defaultPromptSnippet),Array.isArray(e.defaultPromptGuidelines)&&e.defaultPromptGuidelines.length>0&&(n.defaultPromptGuidelines=e.defaultPromptGuidelines),e.override&&(n.override=e.override),n}var $0={},ev=new Set;function tv(){for(let e of ev)e()}function nv(e){let t=(e??``).trim();t&&($0[t]&&$0[t].status!==`loading`||($0={...$0,[t]:{name:t,status:`loading`}},tv(),Z({type:`get_tool_prompt`,name:t})))}function rv(e){let t=typeof e.name==`string`?e.name:``;t&&$0[t]&&($0={...$0,[t]:Q0(e)},tv())}function iv(e){if(!$0[e])return;let t={...$0};delete t[e],$0=t,tv()}function av(e){return ev.add(e),()=>ev.delete(e)}function ov(e){return(0,Q.useSyncExternalStore)(av,()=>e?$0[e]??null:null)}var sv=new Set,cv=1048576,lv=null,uv=[],dv=0;function fv(e=null){lv=e,uv=[],dv=0}function pv(e){if(sv.add(e),lv!==null&&uv.length){let t=lv,n=uv;uv=[],dv=0;for(let r of n)e(t,r)}return()=>{sv.delete(e)}}function mv(e,t){if(e===lv){if(!sv.size)dv+t.length>cv&&(uv=[],dv=0),t.length<=cv&&(uv.push(t),dv+=t.length);else for(let n of sv)try{n(e,t)}catch(e){console.error(`[tui-overlay-bridge] listener error:`,e)}}}var hv=typeof WebSocket<`u`&&WebSocket.CLOSING!==void 0?WebSocket.CLOSING:2,gv=typeof WebSocket<`u`&&WebSocket.CLOSED!==void 0?WebSocket.CLOSED:3,_v=new Set([`snapshot_delta`,`message_delta`,`tool_delta`,`earlier_messages`,`terminal_output`,`terminal_exit`,`terminal_list`]);function vv(e){let{t,wsRef:n,bridgeRef:r,retryRef:i,timerRef:a,aliveRef:o,lastBeatRef:s,noticeId:c,lastDeltaSeqRef:l,pendingCwdRef:u,pendingNewChatPromoteRef:d,answeredQuestionsRef:f,questionSourceRef:p,serverRunIdRef:m,chatApi:h,dispatch:g,send:_,requestState:v,scheduleResync:y,noteDeltaSeq:b,syncPendingQuestion:x,reconnect:S}=e;if(!o.current)return;g({type:`status`,status:`connecting`});let C=new WebSocket(Xo());n.current=C;let w=0,T=h.current.chat.activeConversationId||h.current.chat.state?.conversationId,E=T,D=()=>{let e=h.current.chat.activeConversationId||h.current.chat.state?.conversationId;return e!==T&&(T=e,E=e),E};C.onopen=()=>{n.current===C&&(g({type:`status`,status:`open`}),s.current=Date.now(),w=performance.now(),C.send(JSON.stringify({type:`hello`,clientId:Po(),locale:it()})))},C.onmessage=e=>{if(n.current!==C)return;s.current=Date.now();let a;try{a=JSON.parse(e.data)}catch{return}if(`conversationId`in a&&typeof a.conversationId==`string`&&_v.has(a.type)&&!X0(a)){let e=D();if(e&&a.conversationId!==e)return}switch(a.type){case`ready`:{E=void 0,T=h.current.chat.activeConversationId||h.current.chat.state?.conversationId,i.current=0;let e=h.current.chat.settings?.autoReload??!0;if(!J()&&e&&a.buildId&&a.buildId!==`20261202T08014`){let e=`pi-web-ui-reloaded-${a.buildId}`;try{if(!sessionStorage.getItem(e)){sessionStorage.setItem(e,`1`),location.reload();return}}catch{}}let t=h.current.chat.engine;t&&a.engine&&t!==a.engine&&r.current.clear(`conversation`),gn({engine:a.engine??`pi`,managed:!!a.managed,tabs:a.tabs,appVersion:a.appVersion,serverVersion:a.serverVersion,service:a.service,...a.engineCapabilities?{engineCapabilities:a.engineCapabilities}:{},...a.engines?{engines:a.engines}:{}});let n=w>0?Math.max(0,Math.round(performance.now()-w)):null;g({type:`ready`,serverVersion:a.serverVersion,protocolVersion:a.protocolVersion,engine:a.engine,appVersion:a.appVersion,managed:a.managed,tabs:a.tabs,service:a.service,latencyMs:n,engines:a.engines}),a.runId!==void 0&&a.runId!==m.current||a.runId===void 0?(m.current=a.runId??null,f.current.clear(),uo(),g({type:`question`,question:null})):(g({type:`question`,question:null}),lo()),v(C),C.send(JSON.stringify({type:`list_files`})),C.send(JSON.stringify({type:`list_models`})),C.send(JSON.stringify({type:`list_commands`})),C.send(JSON.stringify({type:`get_commands`})),a.managed||(C.send(JSON.stringify({type:`check_update`})),C.send(JSON.stringify({type:`check_updates_all`})));break}case`snapshot`:if(E=a.state.conversationId,l.current=new Map,u.current=So(u.current,{kind:`snapshot`,cwd:a.state.cwd}),g({type:`snapshot`,state:a.state}),d.current&&a.state.messages.length===0){d.current=null;let e=h.current.chat;go({...a.state,engine:e.engine},e.conversations,`new-chat:${a.state.conversationId}`)}x(a.state.pendingQuestion,a.state.conversationId);break;case`snapshot_delta`:{let e=h.current.chat.state;e?(e.conversationId!==a.conversationId||e.rev!==a.baseRev)&&y():v(n.current);let t=D();if(t&&a.conversationId!==t)break;g({type:`snapshot_delta`,msg:a}),x(a.state.pendingQuestion,t||a.conversationId);break}case`earlier_messages`:{let e=h.current.chat.state;if(e?.conversationId!==a.conversationId)break;if(a1(e,a)){y();break}g({type:`earlier_messages`,msg:a});break}case`tool_delta`:b(a.conversationId,a.seq),g({type:`tool_delta`,toolCallId:a.toolCallId,toolName:a.toolName,delta:a.delta,...a.mode?{mode:a.mode}:{}});break;case`tool_status`:g({type:`tool_status`,status:a});break;case`message_delta`:b(a.conversationId,a.seq),g({type:`message_delta`,msg:a});break;case`subagent_handoff`:break;case`notice`:{let e=++c.current;(a.level===`error`||a.level===`warning`)&&g({type:`transition_clear`}),g({type:`notice`,notice:{id:e,level:a.level,text:a.text,textEn:a.textEn}});break}case`prompt_queued`:g({type:`prompt_queued`,conversationId:a.conversationId,text:a.text});break;case`transition_progress`:u.current=So(u.current,{kind:`transition`,transitionKind:a.kind,phase:a.phase,target:a.target}),g({type:`transition_progress`,msg:a});break;case`engines_status`:gn({engines:a.engines}),g({type:`engines_status`,engines:a.engines});break;case`sessions`:g({type:`sessions`,sessions:a.sessions,cwd:a.cwd,hasMore:a.hasMore});break;case`native_cli_prompt_submitted`:{let e=h.current.chat,t=e.conversations.find(e=>e.id===a.conversationId||e.sessionId===a.sessionId);t&&go({engine:e.engine,cwd:t.cwd,conversationId:t.id,sessionId:a.sessionId,sessionFile:t.sessionFile},e.conversations,a.eventId);break}case`conversations`:a.activeId&&(E=a.activeId),g({type:`conversations`,conversations:a.conversations,activeId:a.activeId,elsewhere:a.elsewhere});break;case`projects`:as(a.projects),g({type:`projects`,projects:a.projects});break;case`sandbox_diff`:g({type:`sandbox_diff`,diff:a.diff});break;case`files`:g({type:`files`,files:a});break;case`canvas_list_result`:window.dispatchEvent(new CustomEvent(fs,{detail:a}));break;case`file_upload_result`:window.dispatchEvent(new CustomEvent(`pi:file-upload-result`,{detail:a}));break;case`file_write_result`:window.dispatchEvent(new CustomEvent(`pi:file-write-result`,{detail:a}));break;case`file_changed`:g({type:`file_changed`,path:a.path});break;case`file_content`:g({type:`file_content`,content:a});break;case`models`:g({type:`models`,models:a.models,loading:!1});break;case`models_config`:g({type:`models_config`,providers:a.providers});break;case`providers_status`:g({type:`providers_status`,providers:a.providers});break;case`provider_keys`:g({type:`provider_keys`,keys:a.keys});break;case`default_model`:g({type:`default_model`,modelId:a.modelId});break;case`provider_oauth_started`:case`provider_oauth_flows`:case`provider_oauth_prompt`:case`provider_oauth_event`:case`provider_oauth_result`:case`provider_oauth_logout_result`:g({type:`provider_oauth`,message:a});break;case`fetch_models_result`:g({type:`fetch_models_result`,result:{reqId:a.reqId,ok:a.ok,models:a.models,error:a.error}});break;case`test_model_connection_result`:g({type:`test_model_connection_result`,result:{reqId:a.reqId,ok:a.ok,latencyMs:a.latencyMs,error:a.error}});break;case`enrich_models_progress`:g({type:`enrich_models_progress`,progress:{reqId:a.reqId,phase:a.phase,current:a.current,total:a.total,message:a.message}});break;case`enrich_models_result`:g({type:`enrich_models_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results,error:a.error}});break;case`refresh_provider_result`:g({type:`refresh_provider_result`,result:{reqId:a.reqId,ok:a.ok,added:a.added,total:a.total,error:a.error}});break;case`refresh_builtin_result`:g({type:`refresh_builtin_result`,result:{reqId:a.reqId,ok:a.ok,error:a.error}});break;case`append_builtin_result`:g({type:`append_builtin_result`,result:{reqId:a.reqId,ok:a.ok,error:a.error}});break;case`clone_provider_result`:g({type:`clone_provider_result`,result:{reqId:a.reqId,ok:a.ok,config:a.config,configs:a.configs,error:a.error}});break;case`scm_data`:g({type:`scm_data`,data:a});break;case`search_files_result`:g({type:`file_search_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results,truncated:a.truncated}});break;case`session_search_results`:g({type:`session_search_result`,result:{reqId:a.reqId,ok:a.ok,results:a.results}});break;case`scm_changed`:g({type:`scm_changed`});break;case`extension_inventory_changed`:g({type:`extension_inventory_changed`});break;case`tool_info`:Xh(a);break;case`tool_prompt`:rv(a);break;case`compacted_messages_result`:Cs(a);break;case`heartbeat`:(a.hostMetrics||typeof a.latencyMs==`number`)&&g({type:`host_metrics`,metrics:a.hostMetrics,latencyMs:typeof a.latencyMs==`number`?a.latencyMs:void 0});break;case`install_result`:g({type:`install_result`,result:a});break;case`path_completions`:g({type:`path_completions`,completions:a.completions});break;case`update_status`:g({type:`update_status`,status:a});break;case`update_status_all`:g({type:`update_status_all`,items:a.items,piSdk:a.piSdk});break;case`widgets`:g({type:`widgets`,widgets:a.widgets});break;case`statuses`:g({type:`statuses`,statuses:a.statuses});break;case`dialog`:g({type:`dialog`,dialog:{id:a.id,kind:a.kind,title:a.title,args:a.args,code:a.code}});break;case`dialog_closed`:g({type:`dialog`,dialog:null});break;case`tui_overlay_open`:fv(a.id),g({type:`tui_overlay`,overlay:{id:a.id,title:a.title,cols:a.cols,rows:a.rows,initialAnsi:a.initialAnsi}});break;case`tui_overlay_render`:mv(a.id,a.ansi);break;case`tui_overlay_close`:fv(),g({type:`tui_overlay`,overlay:null});break;case`global_interactions`:g(a);break;case`question_pending`:if(a.global){g({type:`global_question`,id:a.id,owner:a.owner,question:a});break}p.current=`live`,g({type:`question`,question:{id:a.id,...a.deadline===void 0?{}:{deadline:a.deadline},questions:a.questions,...a.conversationId===void 0?{}:{conversationId:a.conversationId},...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle}}});break;case`tool_approval_pending`:if(a.global){g({type:`global_approval`,id:a.id,owner:a.owner,approval:a});break}g({type:`tool_approval`,approval:{id:a.id,toolCallId:a.toolCallId,toolName:a.toolName,params:a.params,reason:a.reason,reasonEn:a.reasonEn,...a.category?{category:a.category}:{},...a.hits?{hits:a.hits}:{},...a.parentTool?{parentTool:a.parentTool}:{},...a.conversationId===void 0?{}:{conversationId:a.conversationId},...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle},...a.scopeless?{scopeless:!0}:{}}});break;case`tool_approval_resolved`:if(a.global){g({type:`global_approval`,id:a.id,owner:a.owner});break}g({type:`tool_approval`,approval:null,resolvedId:a.id});break;case`question_retracted`:{if(so(a.id,a.owner),g({type:`question_queue_answered`,id:a.id,owner:a.owner}),a.global){g({type:`global_question`,id:a.id,owner:a.owner});break}h.current.chat.remoteQuestion?.id===a.id&&g({type:`remote_question`,question:null});let e=h.current.chat.question;if(e&&e.id===a.id){if(f.current.add(a.id),f.current.size>64){let e=f.current.values().next().value;e!==void 0&&f.current.delete(e)}p.current=`live`,g({type:`question`,question:null})}break}case`question_queue`:g({type:`question_queue`,questions:a.questions});break;case`elsewhere_question`:g({type:`remote_question`,question:{owner:a.owner,convId:a.convId,id:a.id,questions:a.questions,...a.conversationTitle===void 0?{}:{conversationTitle:a.conversationTitle}}});break;case`page_request`:(async()=>{let e=window.__piWebUiHost,n;if(!e?.pageCall)n={ok:!1,error:t(`pageBridgeUnavailable`)};else try{n=await e.pageCall({op:a.op,...a.args===void 0?{}:{args:a.args},...a.target?{target:a.target}:{},timeoutMs:a.timeoutMs})}catch(e){n={ok:!1,error:e instanceof Error?e.message:String(e)}}_({type:`page_response`,id:a.id,ok:n.ok===!0,...n.ok===!0?n.result===void 0?{}:{result:n.result}:{error:n.error??t(`pageActionFailed`)}})})();break;case`phone_request`:(async()=>{let e=t0(),n;if(!e)n={ok:!1,error:t(`phoneBridgeUnavailable`)};else try{n=await e({op:a.op,...a.args===void 0?{}:{args:a.args},timeoutMs:a.timeoutMs})}catch(e){n={ok:!1,error:e instanceof Error?e.message:String(e)}}_({type:`phone_response`,id:a.id,ok:n.ok===!0,...n.ok===!0?n.result===void 0?{}:{result:n.result}:{error:n.error??t(`phoneActionFailed`)}})})();break;case`native_cli_event`:e0(a);break;case`terminal_cli_control_result`:X1(a);break;case`terminal_cli_paste_result`:g({type:`terminal_cli_paste_result`,result:a});break;case`terminal_output`:r.current.write(a.conversationId??``,a.terminalId,a.data,a.reset,a.ownerKind??`client`);break;case`terminal_exit`:g({type:`terminal_exit`,conversationId:a.conversationId,ownerKind:a.ownerKind,terminalId:a.terminalId,exitCode:a.exitCode});break;case`terminal_list`:r.current.reconcile(a.conversationId??h.current.chat.activeConversationId,a.terminals,a.scope),g({type:`terminal_list`,conversationId:a.conversationId,scope:a.scope,terminals:a.terminals});break;case`commands`:g({type:`commands`,commands:a.commands,path:a.path});break;case`slash_commands`:g({type:`slash_commands`,commands:a.commands});break;case`goal_status`:g({type:`goal_status`,status:a.status});break;case`plan_updated`:g({type:`plan_updated`,conversationId:a.conversationId,plan:a.plan});break;case`settings_state`:a.settings?.markers&&Ul(a.settings.markers.map(e=>e.name)),g({type:`settings`,settings:a.settings});break;case`mcp_servers`:g({type:`mcp_servers`,servers:a.servers,globalConfigPath:a.globalConfigPath,projectConfigPath:a.projectConfigPath});break;case`mcp_oauth_result`:g({type:`mcp_oauth_result`,result:a});break;case`mcp_market_result`:g({type:`mcp_market_result`,result:a});break;case`skill_market_result`:g({type:`skill_market_result`,result:a});break;case`skill_content_result`:g({type:`skill_content_result`,result:a});break;case`bg_servers`:g({type:`bg_servers`,servers:a.servers});break;case`project_scripts`:g({type:`project_scripts`,cwd:a.cwd,scripts:a.scripts,...a.packageManager?{packageManager:a.packageManager}:{},...a.extraCommands?{extraCommands:a.extraCommands}:{}});break;case`scheduler_tasks`:g({type:`scheduler_tasks`,tasks:a.tasks});break;case`plugin_panel_items`:g({type:`plugin_panel_items`,groups:a.groups});break;case`plugins`:g({type:`plugins`,plugins:a.plugins,epoch:a.epoch});break;case`extension_inventory_data`:g({type:`extension_inventory`,entries:a.entries??[]});break;case`plugin_updates`:g({type:`plugin_updates`,updates:a.updates});break;case`plugin_catalog`:g({type:`plugin_catalog`,entries:a.entries,epoch:a.epoch});break;case`plugin_grants`:g({type:`plugin_grants`,grants:a.grants});break;case`plugin_permissions`:g({type:`plugin_permissions`,grants:a.grants});break;case`plugin_permission_request`:g({type:`plugin_permission_request`,req:{id:a.id,pluginId:a.pluginId,family:a.family,...a.hosts?{hosts:a.hosts}:{},...a.models?{models:a.models}:{},...a.reason?{reason:a.reason}:{}}});break;case`plugin_permission_resolved`:g({type:`plugin_permission_resolved`,id:a.id});break;case`plugin_path_request`:g({type:`plugin_path_request`,req:{id:a.id,pluginId:a.pluginId,path:a.path,...a.reason?{reason:a.reason}:{}}});break;case`plugin_dom_consent_request`:a.from===Po()&&C.send(JSON.stringify({type:`plugin_dom_consent_response`,id:a.id,ok:!0}));break;case`plugin_job`:g({type:`plugin_job`,job:{jobId:a.jobId,action:a.action,pluginId:a.pluginId,phase:a.phase,...a.ok===void 0?{}:{ok:a.ok},...a.error?{error:a.error}:{},...a.output?{output:a.output}:{}},...a.line?{line:a.line}:{}});break;case`plugin_install_inspect_result`:g({type:`plugin_install_inspect_result`,result:{requestId:String(a.requestId??``),source:String(a.source??``),kind:a.kind,suggestedId:String(a.suggestedId??``),installed:a.installed===!0,...a.problem?{problem:a.problem}:{},...a.detail?{detail:a.detail}:{},...a.manifest?{manifest:a.manifest}:{}}});break;case`new_chat_result`:Hn(a),a.ok||g({type:`transition_clear`});break;case`plugin_catalog_sync_result`:An(a),g({type:`plugin_catalog_sync_result`,result:{requestId:String(a.requestId??``),ok:a.ok===!0,...a.error?{error:a.error}:{},...a.entries?{entryCount:a.entries.length}:{},...a.installed?{installed:a.installed}:{}}});break;case`preset_export_result`:g({type:`preset_export_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,...a.name?{name:a.name}:{},...a.fileName?{fileName:a.fileName}:{},...a.json?{json:a.json}:{},...a.error?{error:a.error}:{}}});break;case`preset_import_result`:{let e=String(a.requestId??``),t=e.startsWith(`url:`)?`url`:e.startsWith(`file:`)?`file`:`paste`;g({type:`preset_import_result`,source:t,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,dryRun:a.dryRun===!0,...a.preview?{preview:a.preview}:{},...a.applied===void 0?{}:{applied:a.applied},...a.applyError?{applyError:a.applyError}:{},...a.applyDeferred?{applyDeferred:!0}:{},...a.error?{error:a.error}:{}}});break}case`preset_catalog_result`:g({type:`preset_catalog_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,entries:a.entries??[],source:a.source??``,cached:a.cached===!0,fetchedAt:a.fetchedAt??0,...a.error?{error:a.error}:{}}});break;case`preset_share_result`:g({type:`preset_share_result`,result:{...a.requestId?{requestId:a.requestId}:{},ok:a.ok===!0,...a.method?{method:a.method}:{},...a.url?{url:a.url}:{},...a.name?{name:a.name}:{},...a.json?{json:a.json}:{},...a.error?{error:a.error}:{}}});break;case`dsh_presets`:g({type:`dsh_presets`,presets:a.presets,defaultPreset:a.defaultPreset});break;case`dsh_permission`:g({type:`dsh_permission`,options:a.options,defaultPreset:a.defaultPreset});break;case`claude_permission`:g({type:`claude_permission`,modes:a.modes,current:a.current});break;case`plugin_data`:q0(a.pluginId,a.payload)||p0(a.pluginId,a.payload);break;case`remote_ssh_probe_result`:case`remote_ssh_list_dir_result`:case`remote_ssh_install_result`:case`remote_ssh_profiles_result`:Pi(a);break;default:Ao(a.type)}},C.onclose=()=>{if(n.current!==C||(n.current=null,r.current.clear(),!o.current))return;g({type:`status`,status:`closed`});let e=Math.min(1e3*2**i.current,1e4);i.current+=1,a.current=setTimeout(()=>{a.current=null,S()},e)},C.onerror=()=>{}}function yv(e,t,n,r,i){return e.find(e=>t(e)===n)??e.find(e=>!r.has(t(e))&&i(e))}function bv(e,t,n){return n!==`queue`||!t?e:e.filter(e=>!e.conversationId||e.conversationId===t||e.rootConversationId===t)}function xv(e,t,n){if(n)return e.filter(e=>e.id!==n);if(!t)return e;let r=e.findIndex(e=>e.id===t.id);return r<0?[...e,t]:e.map((e,n)=>n===r?t:e)}var Sv=2e5,Cv=`LIVE_OMIT`,wv={conversationId:null,goal:null,reviewModel:null,maxRounds:3,locked:!0,reviewing:!1,round:0,status:``,verdict:`pending`,wizard:{active:!1,draft:``,model:null,step:0,maxSteps:6,status:``}};function Tv(e,t){let n=new Set;for(let e of t.messages)e.role===`toolResult`&&e.toolCallId&&n.add(e.toolCallId),e.role===`bashExecution`&&n.add(`bash-${e.id}`);let r=null;for(let t of e.keys())n.has(t)&&(r||=new Map(e),r.delete(t));return r??e}function Ev(e,t){if(e.size===0)return e;let n=new Set;for(let e of t.messages)e.role===`toolResult`&&e.toolCallId&&n.add(e.toolCallId);let r=null;for(let t of e.keys())n.has(t)&&(r||=new Map(e),r.delete(t));return r??e}function Dv(e,t,n,r){let i=e.filter(e=>e.id!==t||e.owner!==n);return r&&i.push(r),i}function Ov(e,t){switch(t.type){case`tool_approval`:return{...e,approval:t.approval,approvals:xv(e.approvals,t.approval,t.resolvedId)};case`widgets`:return{...e,widgets:t.widgets};case`statuses`:return{...e,statuses:t.statuses};case`dialog`:return{...e,dialog:t.dialog};case`tui_overlay`:return{...e,tuiOverlay:t.overlay};case`global_interactions`:return{...e,globalQuestions:t.questions,globalApprovals:t.approvals};case`global_question`:return{...e,globalQuestions:Dv(e.globalQuestions,t.id,t.owner,t.question)};case`global_approval`:return{...e,globalApprovals:Dv(e.globalApprovals,t.id,t.owner,t.approval)};case`question`:return{...e,question:t.question};case`remote_question`:return{...e,remoteQuestion:e.questionQueue===null?t.question:null};case`question_queue`:return{...e,questionQueue:t.questions,remoteQuestion:null};case`question_queue_answered`:return{...e,questionQueue:e.questionQueue?.filter(e=>e.id!==t.id)??null};default:return}}function kv(e,t){let n=t.assistantMessageEvent,r=e.stats.tokens,i=t.usage===null?r:{...r,...t.usage},a=i===r?e.stats:{...e.stats,tokens:i};if(n.type!==`text_delta`&&n.type!==`thinking_delta`)return a===e.stats?e:{...e,stats:a};let o=n.delta??``;if(!o)return a===e.stats?e:{...e,stats:a};let s=e.streamingMessage??null,c=s&&s.id===t.messageId?{...s,role:s.role??`assistant`}:{id:t.messageId,role:`assistant`,content:[]},l=[...c.content],u=n.type===`thinking_delta`?`thinking`:`text`,d=n.contentIndex??l.length-1;return d>=0&&d<l.length&&l[d].type===u?l[d]=u===`thinking`?{type:`thinking`,thinking:(l[d].thinking??``)+o}:{type:`text`,text:(l[d].text??``)+o}:l.push(u===`thinking`?{type:`thinking`,thinking:o}:{type:`text`,text:o}),{...e,stats:a,streamingMessage:{...c,id:t.messageId,role:`assistant`,content:l}}}function Av(e){switch(e){case`error`:return 6500;case`warning`:return 4200;default:return 2400}}var jv=[/^(已在工作目录|正在切换到工作目录|已切换到工作目录)[::]/,/^(Already in directory|Switching to directory|Switched to directory):/i,/该项目最近的对话.*(为你停在了空白新对话|为你停在了新对话)/,/The most recent conversation .* landed on a (blank|new) chat/i,/^分层上下文预算裁剪生效/,/^Tiered context budget pruning/i,/^发现 \d+ 个内置插件有更新可用/,/^\d+ built-in plugin\(s\) have updates available/i,/^已(创建文件|创建文件夹|重命名|删除|移动|复制)[::]/,/^(Created file|Created folder|Renamed|Deleted|Moved|Copied):/i,/^已重命名当前会话为/,/^Renamed current session to/i,/的消息正在投递,已为你保留该对话$/,/is still sending your message — kept in the running list$/i,/^(计划模式已开启|计划模式已关闭|已进入计划模式|已退出计划模式|审查者模式已开启|审查者模式已关闭)/,/^(Plan mode (enabled|disabled)|Entered plan mode|Exited plan mode|Delegate mode (enabled|disabled))/i,/^已切换(智能体预设|权限预设)/,/^Switched (agent|permission) preset/i];function Mv(e){if(e.level!==`info`)return!1;let t=(e.text??``).trim(),n=(e.textEn??``).trim();return jv.some(e=>t&&e.test(t)||n&&e.test(n))}function Nv(e,t,n=2){if(Mv(t))return e;let r=`${t.level}:${(t.text??``).trim()}`,i=[...e.filter(e=>`${e.level}:${(e.text??``).trim()}`!==r),t];for(;i.length>n;){let e=i.findIndex(e=>e.level!==`error`);e>=0?i.splice(e,1):i.shift()}return i}function Pv(e,t){switch(t.type){case`optimistic_queue_add`:{let n=e.goal.reviewing&&!!(e.state?.conversationId&&e.goal.conversationId===e.state.conversationId),r=Ya(e.optimisticQueue,e.state,{text:t.text,attachments:t.attachments,queue:t.queue,engine:e.engine,goalReviewing:n});return r.tracker===e.optimisticQueue&&r.state===e.state?e:{...e,optimisticQueue:r.tracker,state:r.state}}case`optimistic_queue_remove`:{let n=Xa(e.optimisticQueue,e.state,{kind:t.kind,text:t.text,index:t.index});return n.tracker===e.optimisticQueue&&n.state===e.state?e:{...e,optimisticQueue:n.tracker,state:n.state}}case`optimistic_prompt_echo`:{let n=Ha(e.optimisticQueue,e.state,{text:t.text,attachments:t.attachments});return n.tracker===e.optimisticQueue&&n.state===e.state?e:{...e,optimisticQueue:n.tracker,state:n.state}}case`prompt_queued`:{let n=Ga(e.optimisticQueue,t.conversationId,t.text);return n===e.optimisticQueue?e:{...e,optimisticQueue:n}}case`tool_delta`:{let n=e.liveOutputs.get(t.toolCallId)?.text??``,r;r=t.mode===`replace`||n.length>0&&t.delta.startsWith(n)?t.delta:n+t.delta;let i=r.length>2e5?`…[${Cv}:${r.length-Sv}]…\n`+r.slice(r.length-Sv):r,a=new Map(e.liveOutputs);return a.set(t.toolCallId,{toolName:t.toolName,text:i}),{...e,liveOutputs:a}}case`message_delta`:{let n=e.state;return!n||n.conversationId!==t.msg.conversationId?e:{...e,state:kv(n,t.msg)}}case`tool_status`:return{...e,toolStatuses:new Map(e.toolStatuses).set(t.status.toolCallId,t.status)};case`reask_start`:return{...e,reaskConversationId:t.conversationId};case`notice`:{let n=Nv(e.notices,t.notice),r=t.notice.level===`error`||t.notice.level===`warning`,i=r&&(e.optimisticQueue.adds.length>0||e.optimisticQueue.echoes.length>0)?Qa(e.optimisticQueue,e.state):{tracker:e.optimisticQueue,state:e.state},a=r?null:e.reaskConversationId;return n===e.notices&&i.tracker===e.optimisticQueue&&a===e.reaskConversationId?e:{...e,notices:n,reaskConversationId:a,optimisticQueue:i.tracker,state:i.state}}case`dismiss_notice`:return{...e,notices:e.notices.filter(e=>e.id!==t.id)};default:return}}function Fv(e,t){switch(t.type){case`install_result`:return{...e,installResult:t.result};case`extension_inventory_changed`:return{...e,extensionInventoryDirty:e.extensionInventoryDirty+1};case`plugin_panel_items`:return{...e,pluginPanelGroups:t.groups};case`plugins`:return{...e,plugins:t.plugins,pluginsEpoch:t.epoch};case`extension_inventory`:return{...e,extensionInventory:t.entries};case`plugin_updates_check_started`:return{...e,checkingPluginUpdates:!0};case`plugin_updates`:{let n={};for(let e of t.updates)n[e.id]=e;return{...e,pluginUpdates:n,checkingPluginUpdates:!1}}case`plugin_catalog`:return{...e,pluginCatalog:t.entries,pluginCatalogEpoch:t.epoch};case`plugin_grants`:return{...e,pluginGrants:t.grants};case`plugin_permissions`:return{...e,pluginPermissions:t.grants};case`plugin_path_request`:return{...e,pathRequests:[...e.pathRequests.filter(e=>e.id!==t.req.id),t.req]};case`plugin_path_resolved`:return{...e,pathRequests:e.pathRequests.filter(e=>e.id!==t.id)};case`plugin_permission_request`:return{...e,permRequests:[...e.permRequests.filter(e=>e.id!==t.req.id),t.req]};case`plugin_permission_resolved`:return{...e,permRequests:e.permRequests.filter(e=>e.id!==t.id)};case`plugin_job`:{let{pluginId:n,phase:r,ok:i,action:a}=t.job,o=e.pluginUpdates;a===`update`&&r===`done`&&i&&e.pluginUpdates?.[n]&&(o={...e.pluginUpdates,[n]:{...e.pluginUpdates[n],updatable:!1}});let s=e.pluginJobs[t.job.jobId],c=t.line?[...s?.lines??[],t.line].slice(-40):s?.lines??[],l={...s,...t.job,lines:c,startedAt:s?.startedAt??Date.now()};return{...e,pluginUpdates:o,pluginJobs:{...e.pluginJobs,[t.job.jobId]:l}}}case`plugin_catalog_sync_result`:return{...e,catalogSync:{...t.result,receivedAt:Date.now()}};case`preset_export_result`:return{...e,presetExport:{...t.result,receivedAt:Date.now()}};case`preset_import_result`:return{...e,presetImport:{...t.result,source:t.source,receivedAt:Date.now()}};case`preset_catalog_result`:return{...e,presetCatalog:{...t.result,receivedAt:Date.now()}};case`preset_share_result`:return{...e,presetShare:{...t.result,receivedAt:Date.now()}};case`plugin_install_inspect_result`:return{...e,installInspect:t.result};case`dsh_presets`:{let n={presets:t.presets,defaultPreset:t.defaultPreset};return{...e,dshPresets:n}}case`claude_permission`:return{...e,claudePermission:{modes:t.modes,current:t.current}};case`dsh_permission`:{let n={options:t.options,defaultPreset:t.defaultPreset};return{...e,dshPermission:n}}default:return}}function Iv(e,t){switch(t.type){case`sync_cached_sessions`:return{...e,sessions:t.sessions};case`optimistic_delete_session`:{let n=Co(t.path);if(!n)return e;Ko(t.path,e.state?.cwd,`all`);let r=e.sessions.filter(e=>Co(e.path)!==n),i=e.projectSessions;if(e.projectSessions){let r=!1,a={};for(let[i,o]of Object.entries(e.projectSessions)){let e=o.filter(e=>Co(e.path)!==n);e.length!==o.length&&(r=!0,Ko(t.path,i,`all`)),a[i]=e}r&&(i=a)}return{...e,sessions:r,projectSessions:i}}case`optimistic_delete_project_sessions`:{let n=Co(t.cwd);if(!n)return e;qo(t.cwd);let r=Co(e.state?.cwd)===n;return{...e,...r?{sessions:[]}:{},projectSessions:{...e.projectSessions,[n]:[]}}}case`sessions`:{let n=t.cwd??t.targetCwd,r=!n||Co(n)===Co(e.state?.cwd),i=n=>{let r=e.projectSessionsHasMore??{};if(!!r[n]==!!t.hasMore)return e.projectSessionsHasMore;let i={...r};return t.hasMore?i[n]=!0:delete i[n],i};if(r){Go(e.state?.cwd,t.sessions,`all`);let n=Co(e.state?.cwd);return{...e,sessions:t.sessions,projectSessions:n?{...e.projectSessions,[n]:t.sessions}:e.projectSessions,projectSessionsHasMore:n?i(n):e.projectSessionsHasMore}}Go(n,t.sessions,`all`);let a=Co(n);return{...e,projectSessions:{...e.projectSessions,[a]:t.sessions},projectSessionsHasMore:i(a)}}case`conversations`:return Yo({conversations:t.conversations,elsewhere:t.elsewhere??[],activeConversationId:t.activeId}),{...e,conversations:t.conversations,elsewhere:t.elsewhere??[],activeConversationId:t.activeId};case`projects`:return ss(t.projects),{...e,projects:t.projects};case`session_search_result`:return{...e,sessionSearch:t.result};default:return}}function Lv(e,t){switch(t.type){case`models`:return{...e,models:t.models,modelsLoading:t.loading};case`models_config`:return{...e,modelsConfig:t.providers};case`providers_status`:return{...e,providers:t.providers};case`provider_keys`:return{...e,providerKeys:t.keys};case`default_model`:return{...e,defaultModel:t.modelId};case`provider_oauth`:{let n=ro({flows:e.providerOAuthFlows,results:e.providerOAuthResults},t.message);return{...e,providerOAuthFlows:n.flows,providerOAuthResults:n.results}}case`fetch_models_result`:return{...e,fetchModelsResult:t.result};case`test_model_connection_result`:return{...e,testModelConnectionResult:t.result};case`enrich_models_progress`:return{...e,enrichModelsProgress:t.progress};case`enrich_models_result`:return{...e,enrichModelsResult:t.result,enrichModelsProgress:null};case`refresh_provider_result`:return{...e,refreshProviderResult:t.result};case`refresh_builtin_result`:return{...e,refreshBuiltinResult:t.result};case`append_builtin_result`:return{...e,appendBuiltinResult:t.result};case`clone_provider_result`:return{...e,cloneProviderResult:t.result};case`commands`:return{...e,commands:t.commands,commandsPath:t.path};case`slash_commands`:return{...e,slashCommands:t.commands};case`goal_status`:return{...e,goal:t.status};case`plan_updated`:{let n=e.state;if(!n)return e;let r=e.activeConversationId||n.conversationId;if(!t.conversationId||t.conversationId!==r)return e;let i={...n,plan:t.plan};return{...e,state:i}}case`settings`:return{...e,settings:t.settings};case`mcp_servers`:return e.settings?{...e,settings:{...e.settings,mcpServers:t.servers,mcpGlobalConfigPath:t.globalConfigPath??e.settings.mcpGlobalConfigPath,mcpProjectConfigPath:t.projectConfigPath??e.settings.mcpProjectConfigPath}}:e;case`mcp_oauth_result`:return{...e,mcpOAuthResult:e.mcpOAuthResult?.reqId===t.result.reqId?{...e.mcpOAuthResult,...t.result,error:t.result.error}:t.result};case`mcp_market_result`:return{...e,mcpMarketResult:t.result};case`skill_market_result`:return{...e,skillMarketResult:t.result};case`skill_content_result`:return{...e,skillContentResult:t.result};default:return}}function Rv(e,t){return!e||t.conversationId!==e||t.messages.length>0||t.streamingMessage||t.isStreaming?null:e}function zv(e,t){switch(t.type){case`status`:return{...e,status:t.status,ready:t.status===`open`&&e.ready,terminals:t.status===`closed`?[]:e.terminals,hostMetrics:t.status===`closed`?null:e.hostMetrics,latencyMs:t.status===`open`?e.latencyMs:null};case`host_metrics`:return{...e,...t.metrics===void 0?{}:{hostMetrics:t.metrics},...t.latencyMs===void 0?{}:{latencyMs:t.latencyMs}};case`ready`:{let n=!!(e.engine&&t.engine&&e.engine!==t.engine);return{...e,connectionEpoch:(e.connectionEpoch??0)+1,serverVersion:t.serverVersion,engine:t.engine,appVersion:t.appVersion,managed:t.managed===!0,tabs:t.tabs,ready:!0,...t.engines?{engines:t.engines}:{},...n?{models:[],defaultModel:null,dshPresets:null,dshPermission:null,claudePermission:null}:{},...typeof t.latencyMs==`number`&&e.latencyMs==null?{latencyMs:t.latencyMs}:{},protocolMismatch:t.protocolVersion!==void 0&&t.protocolVersion!==65}}case`engines_status`:return{...e,engines:t.engines};case`snapshot`:{let n=e.state?.cwd,r=e.state?.conversationId,i=t.state.cwd,a=i&&i!==n?[]:e.sessions,o=e=>(e??``).trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase(),s=e.transition;if(s){let e=o(s.target),n=o(t.state.sessionFile),i=o(t.state.conversationId),a=o(t.state.sessionId);s.phase===`done`||s.phase===`error`||s.kind===`cwd`&&o(t.state.cwd)===e||s.kind===`session`&&(n===e||a===e||i===e||a&&(a.includes(e)||e.includes(a))||n&&(n.includes(e)||n.endsWith(`/`+e)||e.endsWith(`/`+n)))||s.kind===`conversation`&&i===e?s=null:s.kind!==`new_chat`||r&&t.state.conversationId===r&&t.state.messages.length!==0||(s=null)}let c=$a(e.optimisticQueue,t.state),l=Za(c.tracker,c.state);return{...e,ready:!0,state:l.state,optimisticQueue:l.tracker,transition:s,reaskConversationId:Rv(e.reaskConversationId,l.state),sessions:a,approval:l.state.pendingApproval??null,approvals:l.state.pendingApprovals??(l.state.pendingApproval?[l.state.pendingApproval]:[]),activeConversationId:l.state.conversationId,liveOutputs:Tv(e.liveOutputs,l.state),toolStatuses:Ev(e.toolStatuses,l.state)}}case`earlier_messages`:{let n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId)return e;let i=o1(n,r);return i?{...e,state:i}:e}case`snapshot_delta`:{let n=e.state,r=t.msg;if(!n||n.conversationId!==r.conversationId||n.rev!==r.baseRev)return e;let i={...n,...r.state,messages:r.appended.length>0?[...n.messages,...r.appended]:n.messages},a=$a(e.optimisticQueue,i),o=Za(a.tracker,a.state),s=o.state;return{...e,ready:!0,state:s,reaskConversationId:Rv(e.reaskConversationId,s),optimisticQueue:o.tracker,approval:s.pendingApproval===void 0?e.approval:s.pendingApproval??null,approvals:s.pendingApprovals??e.approvals,activeConversationId:s.conversationId,liveOutputs:Tv(e.liveOutputs,s),toolStatuses:Ev(e.toolStatuses,s)}}default:return}}function Bv(e,t){switch(t.type){case`sandbox_diff`:return{...e,sandboxDiff:t.diff};case`files`:return{...e,files:t.files};case`file_changed`:return{...e,fileChanged:{path:t.path}};case`file_content`:return{...e,fileContent:t.content};case`scm_data`:return{...e,scmData:t.data};case`file_search_result`:return{...e,fileSearch:t.result};case`scm_changed`:return{...e,scmDirty:e.scmDirty+1};case`path_completions`:return{...e,pathCompletions:t.completions};case`bg_servers`:return{...e,bgServers:t.servers};case`project_scripts`:return{...e,projectScripts:{cwd:t.cwd,scripts:t.scripts,...t.packageManager?{packageManager:t.packageManager}:{},...t.extraCommands?{extraCommands:t.extraCommands}:{}}};case`scheduler_tasks`:return{...e,schedulerTasks:t.tasks};case`update_status`:return{...e,update:t.status};case`update_status_all`:return{...e,updatesAll:t.items,updatesSdk:t.piSdk??null};case`updates_check_started`:return{...e,updatesAll:null};case`terminal_cli_paste_result`:return{...e,nativeCliPasteResult:t.result};case`terminal_add`:return{...e,terminals:[...e.terminals,t.meta]};case`terminal_remove`:return{...e,terminals:e.terminals.filter(e=>e.id!==t.id||(e.ownerKind??`client`)!==(t.ownerKind??`client`)||(e.ownerKind??`client`)!==`client`&&e.conversationId!==t.conversationId)};case`terminal_exit`:return{...e,terminals:e.terminals.map(e=>e.id===t.terminalId&&(e.ownerKind??`client`)===(t.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||e.conversationId===t.conversationId)?{...e,running:!1,exitCode:t.exitCode}:e)};case`terminal_restart`:return{...e,terminals:e.terminals.map(e=>e.id===t.terminalId&&(e.ownerKind??`client`)===(t.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||e.conversationId===t.conversationId)?{...e,running:!0,exitCode:null}:e)};case`terminal_list`:{let n=e.activeConversationId||e.state?.conversationId||``,r=t.conversationId??n;if(t.scope===`client`){let n=t.terminals.map(e=>({...e,ownerKind:`client`,conversationId:``})),r=e.terminals.filter(e=>e.ownerKind===`conversation`);return{...e,terminals:[...n,...r]}}if(t.scope===`conversation`){let i=t.terminals.map(e=>({...e,ownerKind:`conversation`,conversationId:r})),a=e.terminals.filter(e=>(e.ownerKind??`client`)===`client`||r!==n&&e.ownerKind===`conversation`&&e.conversationId===n);return{...e,terminals:[...a,...i]}}let i=t.terminals.map(e=>({...e,ownerKind:e.ownerKind??`client`,conversationId:r}));return r!==n&&i.push(...e.terminals.filter(e=>e.ownerKind===`conversation`&&e.conversationId===n)),{...e,terminals:i}}case`terminal_active`:return{...e,terminalActiveId:t.id};case`transition_start`:{let n=t.kind===`cwd`?Vo(t.target,`all`):null;return{...e,reaskConversationId:null,...n&&n.length>0?{sessions:n}:{},transition:{kind:t.kind,target:t.target,phase:`start`,progress:t.progress,text:``,textEn:``,textKey:t.textKey,...t.textVars?{textVars:t.textVars}:{},startedAt:Date.now()}}}case`transition_progress`:{let n=t.msg;if(n.phase===`done`||n.phase===`error`)return{...e,transition:e.transition?{...e.transition,phase:n.phase,progress:100,text:n.text,textEn:n.textEn}:null};let r=e.transition;return{...e,transition:{kind:n.kind,target:n.target,phase:n.phase,progress:Math.max(r?.target===n.target?r.progress:0,n.progress),text:n.text,textEn:n.textEn,totalMessages:n.totalMessages??r?.totalMessages,previewMessages:n.previewMessages??r?.previewMessages,previewConversationId:n.conversationId??(r?.target===n.target?r.previewConversationId:void 0),previewSessionFile:n.sessionFile??(r?.target===n.target?r.previewSessionFile:void 0),startedAt:r?.startedAt??Date.now()}}}case`transition_tick`:{let t=e.transition;if(!t||t.phase===`done`||t.phase===`error`)return e;let n=t.phase===`start`?26:t.phase===`fs`?56:92;if(t.progress>=n)return e;let r=Math.max(1,Math.round((n-t.progress)*.16));return{...e,transition:{...t,progress:Math.min(n,t.progress+r)}}}case`transition_clear`:return e.transition?{...e,transition:null}:e;default:return}}var Vv=[zv,Pv,Iv,Lv,Ov,Fv,Bv];function Hv(e,t){for(let n of Vv){let r=n(e,t);if(r!==void 0)return r}return e}var Uv=[`cost`,`input`,`output`,`cacheRead`,`cacheWrite`,`contextTokens`];function Wv(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:0}function Gv(e,t,n){return{t:n,engine:e||`pi`,cost:Wv(t.cost),input:Wv(t.tokens?.input),output:Wv(t.tokens?.output),cacheRead:Wv(t.tokens?.cacheRead),cacheWrite:Wv(t.tokens?.cacheWrite),contextTokens:Wv(t.contextUsage?.tokens)}}function Kv(e,t){return e.engine===t.engine&&e.cost===t.cost&&e.input===t.input&&e.output===t.output&&e.cacheRead===t.cacheRead&&e.cacheWrite===t.cacheWrite&&e.contextTokens===t.contextTokens}function qv(e,t,n=240){let r=e[e.length-1];if(r&&Kv(r,t))return e;let i=[...e,t];return i.length>n?i.slice(i.length-n):i}function Jv(e,t){return e.engine===t.engine&&e.cost===t.cost&&e.input===t.input&&e.output===t.output&&e.cacheRead===t.cacheRead&&e.cacheWrite===t.cacheWrite&&e.contextTokens!==t.contextTokens}function Yv(e,t){return t.t-e.t>=2e3&&Math.abs(t.contextTokens-e.contextTokens)>=256}function Xv(e,t){let n=new Map;return e.map(e=>{let r=n.get(e.engine);n.set(e.engine,e);let i={};for(let n of Uv)i[n]=n===`contextTokens`||t===`total`?e[n]:r?Math.max(0,e[n]-r[n]):0;return{t:e.t,engine:e.engine,values:i}})}function Zv(e,t){let n=t.engines&&t.engines.length>0?new Set(t.engines):null,r=Xv(n?e.filter(e=>n.has(e.engine)):[...e],t.mode),i=(t.metrics&&t.metrics.length>0?t.metrics:Uv).map(e=>({metric:e,values:[]})),a=new Map;for(let e of r){t.mode===`total`&&a.set(e.engine,e.values);for(let n of i){let{metric:r}=n;if(r===`contextTokens`||t.mode===`delta`){n.values.push(e.values[r]);continue}let i=0;for(let e of a.values())i+=e[r];n.values.push(i)}}return{count:r.length,times:r.map(e=>e.t),series:i}}function Qv(e,t){let n=Xv(e,t),r=new Map;for(let e of n){let n=r.get(e.engine);n||(n={engine:e.engine,samples:0,cost:0,input:0,output:0,cacheRead:0,cacheWrite:0,contextTokens:0},r.set(e.engine,n)),n.samples+=1,t===`total`?(n.cost=e.values.cost,n.input=e.values.input,n.output=e.values.output,n.cacheRead=e.values.cacheRead,n.cacheWrite=e.values.cacheWrite):(n.cost+=e.values.cost,n.input+=e.values.input,n.output+=e.values.output,n.cacheRead+=e.values.cacheRead,n.cacheWrite+=e.values.cacheWrite),n.contextTokens=e.values.contextTokens}return[...r.values()]}function $v(e){let t=0;for(let n of e)n>t&&(t=n);return t}var ey=`pi-web-ui:usage-history:v1`,ty=8,ny=800,ry=[],iy=new Map,ay=new Set,oy=!1,sy=null;function cy(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.t==`number`&&typeof t.engine==`string`&&[`cost`,`input`,`output`,`cacheRead`,`cacheWrite`,`contextTokens`].every(e=>typeof t[e]==`number`)}function ly(){if(!oy){oy=!0;try{let e=globalThis.localStorage?.getItem(ey);if(!e)return;let t=JSON.parse(e);if(!t||typeof t!=`object`)return;for(let[e,n]of Object.entries(t)){if(!e||!Array.isArray(n))continue;let t=n.filter(cy);t.length>0&&iy.set(e,t)}}catch{}}}function uy(){if(iy.size<=ty)return;let e=[...iy.entries()].map(([e,t])=>({conversationId:e,t:t[t.length-1]?.t??0})).sort((e,t)=>t.t-e.t);for(let{conversationId:t}of e.slice(ty))iy.delete(t)}function dy(){sy===null&&(sy=setTimeout(()=>{sy=null,uy();try{globalThis.localStorage?.setItem(ey,JSON.stringify(Object.fromEntries(iy)))}catch{}},ny))}function fy(){for(let e of[...ay])try{e()}catch{}}function py(e){let{conversationId:t,engine:n,stats:r}=e;if(!t||!r)return;ly();let i=iy.get(t)??ry,a=Gv(n,r,e.now??Date.now()),o=i[i.length-1];o&&(Kv(o,a)||Jv(o,a)&&!Yv(o,a))||(iy.set(t,qv(i,a)),dy(),fy())}function my(e){return ay.add(e),()=>ay.delete(e)}function hy(e){return ly(),iy.get(e)??ry}function gy(e){return(0,Q.useSyncExternalStore)(my,()=>hy(e),()=>ry)}function _y(){return it()}function vy(){let e=X(),[t,n]=(0,Q.useReducer)(Hv,{status:`connecting`,ready:!1,state:null,hostMetrics:null,latencyMs:null,liveOutputs:new Map,toolStatuses:new Map,notices:[],sessions:[],projectSessions:{},projectSessionsHasMore:{},conversations:[],elsewhere:[],activeConversationId:``,projects:[],files:null,fileChanged:null,fileContent:null,models:[],modelsLoading:!1,modelsConfig:[],providers:[],providerKeys:{},defaultModel:null,providerOAuthFlows:[],providerOAuthResults:to().results,installResult:null,pathCompletions:[],update:null,updatesAll:null,updatesSdk:null,widgets:[],statuses:[],dialog:null,tuiOverlay:null,approval:null,approvals:[],globalQuestions:[],globalApprovals:[],question:null,questionQueue:null,remoteQuestion:null,commands:[],commandsPath:``,slashCommands:[],terminals:[],terminalActiveId:null,goal:wv,bgServers:[],projectScripts:null,schedulerTasks:[],pluginPanelGroups:[],settings:null,fetchModelsResult:null,testModelConnectionResult:null,enrichModelsResult:null,enrichModelsProgress:null,refreshProviderResult:null,refreshBuiltinResult:null,appendBuiltinResult:null,cloneProviderResult:null,scmData:null,fileSearch:null,sessionSearch:null,scmDirty:0,extensionInventoryDirty:0,plugins:[],pluginsEpoch:0,extensionInventory:null,pluginUpdates:null,checkingPluginUpdates:!1,pluginCatalog:[],pluginCatalogEpoch:0,pluginJobs:{},catalogSync:null,presetExport:null,presetImport:null,presetCatalog:null,presetShare:null,installInspect:null,pluginGrants:[],pluginPermissions:[],pathRequests:[],permRequests:[],mcpOAuthResult:null,mcpMarketResult:null,skillMarketResult:null,skillContentResult:null,dshPresets:null,dshPermission:null,claudePermission:null,protocolMismatch:!1,transition:null,reaskConversationId:null,sandboxDiff:null,optimisticQueue:Na()}),r=(0,Q.useRef)(null),i=(0,Q.useRef)(Z0()),a=(0,Q.useRef)(0),o=(0,Q.useRef)(null),s=(0,Q.useRef)(!0),c=(0,Q.useRef)(0),l=(0,Q.useRef)(0),u=(0,Q.useRef)(new Map),d=(0,Q.useRef)(null),f=(0,Q.useRef)(!1),p=(0,Q.useRef)(null),m=(0,Q.useRef)(new Set),h=(0,Q.useRef)(`live`),g=(0,Q.useRef)(null),_=e=>{if(!us(e))return;let t=M.current.chat.state?.rev;e.send(JSON.stringify({type:`get_state`,...t===void 0?{}:{rev:t}}))},v=()=>{d.current||=setTimeout(()=>{d.current=null,_(r.current)},300)},y=(e,t)=>{let n=u.current,r=n.get(e);if(r!==void 0&&t!==r+1){let t=M.current.chat;e===(t.activeConversationId||t.state?.conversationId)&&v()}n.set(e,t)},b=(0,Q.useCallback)((e,t)=>{let r=++l.current;n({type:`notice`,notice:{id:r,level:e,text:t}})},[]);(0,Q.useEffect)(()=>{if(!t.transition)return;if(t.transition.phase===`done`||t.transition.phase===`error`){let e=setTimeout(()=>n({type:`transition_clear`}),180);return()=>clearTimeout(e)}let e=t.state;if(e&&t.ready&&t.transition.kind!==`cwd`){let r=(t.transition.target??``).trim().replace(/\\/g,`/`).toLowerCase(),i=(e.sessionId??``).trim().replace(/\\/g,`/`).toLowerCase(),a=(e.sessionFile??``).trim().replace(/\\/g,`/`).toLowerCase(),o=(e.conversationId??``).trim().replace(/\\/g,`/`).toLowerCase();if(r&&(i===r||a===r||o===r||i&&(i.includes(r)||r.includes(i))||a&&(a.includes(r)||r.includes(a)))){n({type:`transition_clear`});return}}let r=setInterval(()=>{Date.now()-(t.transition?.startedAt??0)>2e4?n({type:`transition_clear`}):n({type:`transition_tick`})},160);return()=>clearInterval(r)},[t.transition,t.state,t.ready]);let x=(0,Q.useRef)(null),S=(0,Q.useRef)(null),C=(0,Q.useCallback)((e,t)=>ds({wsRef:r,chatApi:M,pendingCwdRef:x,pendingNewChatPromoteRef:S,answeredQuestionsRef:m,questionSourceRef:h,dispatch:n},e,t),[]),w=(0,Q.useCallback)((e,t)=>{let r=eo({current:M.current.chat.question,source:h.current,snapshot:e,answered:m.current,activeConversationId:t,pendingDelivery:co});r.changed&&(h.current=r.source,n({type:`question`,question:r.question}))},[]);vn(C);let T=(0,Q.useCallback)(()=>{vv({t:e,wsRef:r,bridgeRef:i,retryRef:a,timerRef:o,aliveRef:s,lastBeatRef:c,noticeId:l,lastDeltaSeqRef:u,pendingCwdRef:x,pendingNewChatPromoteRef:S,answeredQuestionsRef:m,questionSourceRef:h,serverRunIdRef:g,chatApi:M,dispatch:n,send:C,requestState:_,scheduleResync:v,noteDeltaSeq:y,syncPendingQuestion:w,reconnect:T})},[]);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail??_y();t&&C({type:`set_locale`,locale:t})};return window.addEventListener(ke,e),()=>window.removeEventListener(ke,e)},[C]),(0,Q.useEffect)(()=>{let e=e=>{let r=t.state?.cwd;r&&e.key&&(e.key===Bo(r,`all`)||e.key===Bo(r,t.engine))&&n({type:`sync_cached_sessions`,sessions:Vo(r,`all`)})};return window.addEventListener(`storage`,e),()=>window.removeEventListener(`storage`,e)},[t.state?.cwd,t.engine]),(0,Q.useEffect)(()=>{s.current=!0,T();let e=setInterval(()=>{if(!s.current)return;let e=r.current;us(e)&&Date.now()-c.current>3e4&&e.close()},5e3),t=()=>{if(!s.current||typeof document<`u`&&document.visibilityState===`hidden`)return;let e=r.current;!e||e.readyState===gv||e.readyState===hv?(o.current&&=(clearTimeout(o.current),null),T()):us(e)&&(Date.now()-c.current>15e3||!M.current.chat.state)&&_(e)};return typeof document<`u`&&document.addEventListener(`visibilitychange`,t),typeof window<`u`&&(window.addEventListener(`pageshow`,t),window.addEventListener(`online`,t)),()=>{s.current=!1,clearInterval(e),o.current&&=(clearTimeout(o.current),null),typeof document<`u`&&document.removeEventListener(`visibilitychange`,t),typeof window<`u`&&(window.removeEventListener(`pageshow`,t),window.removeEventListener(`online`,t)),r.current?.close(),r.current=null,i.current.clear()}},[T]),(0,Q.useEffect)(()=>{let e=t.state?.cwd;if(e){if(!f.current){f.current=!0;let t=Io();if(t&&t!==e){C({type:`set_cwd`,path:t});return}}if(p.current!==e&&(p.current=e,Lo(e),e&&e!==`@root`&&e!==`machine-root`)){let t=os(),n=Co(e);ss([{path:e,lastUsed:0},...t.filter(e=>Co(e.path)!==n)])}}},[t.state?.cwd,C]),(0,Q.useEffect)(()=>{gn({ready:t.ready,status:t.status,cwd:t.state?.cwd??``,projects:t.projects,workspaceRoots:t.state?.workspaceRoots??[],pathCompletions:t.pathCompletions,homeDir:t.state?.homeDir??``,desktopDir:t.state?.desktopDir??``,chatUploadMaxMb:t.settings?.chatUploadMaxMb??20,workspaceUploadMaxMb:t.settings?.workspaceUploadMaxMb??100,folderUploadMaxMb:t.settings?.folderUploadMaxMb??32,...t.state?.engineCapabilities?{engineCapabilities:t.state.engineCapabilities}:{}})},[t.ready,t.status,t.state?.cwd,t.projects,t.state?.workspaceRoots,t.pathCompletions,t.state?.homeDir,t.state?.desktopDir,t.settings?.chatUploadMaxMb,t.settings?.workspaceUploadMaxMb,t.settings?.folderUploadMaxMb,t.state?.engineCapabilities]),(0,Q.useEffect)(()=>{let e=t.state;e&&py({conversationId:e.conversationId,engine:t.engine??`pi`,stats:e.stats})},[t.state,t.engine]);let E=(0,Q.useCallback)(e=>n({type:`dismiss_notice`,id:e}),[]),D=(0,Q.useCallback)(e=>{let t=M.current.chat;if(!t.ready||t.terminals.some(t=>t.id===e.id&&(t.ownerKind??`client`)===(e.ownerKind??`client`)&&((e.ownerKind??`client`)===`client`||t.conversationId===e.conversationId)))return;let r=e.ownerKind??`client`,i={terminalId:e.id,conversationId:e.conversationId,ownerKind:r,cols:e.cols,rows:e.rows};(e.command?C({type:`run_command`,...i,command:e.command}):C({type:`terminal_create`,...i,ownerKind:`client`,title:e.title,cwd:e.cwd,agentBash:e.agentBash,nativeCli:e.nativeCli,locale:_y()}))&&n({type:`terminal_add`,meta:{...e,ownerKind:r}})},[C]),O=(0,Q.useCallback)((e,t=`client`,r)=>n({type:`terminal_remove`,id:e,ownerKind:t,conversationId:r}),[]),k=(0,Q.useCallback)((e,t=`client`,r)=>n({type:`terminal_restart`,terminalId:e,ownerKind:t,conversationId:r}),[]),A=(0,Q.useCallback)(e=>n({type:`terminal_active`,id:e}),[]),j=(0,Q.useCallback)((e,t,n,r=`client`)=>i.current.register(e,t,n,r),[]),M=(0,Q.useRef)({chat:t,send:C,pushNotice:b,dismissNotice:E,terminal:{create:D,close:O,register:j,restart:k,select:A}});return M.current={chat:t,send:C,pushNotice:b,dismissNotice:E,terminal:{create:D,close:O,register:j,restart:k,select:A}},M.current}var yy=0xc800000,by=/windows/i.test(navigator.userAgent),xy=/[<>:"/\\|?*\u0000-\u001f]/g,Sy=/[. ]+$/,Cy=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\..*)?$/i;function wy(e){let t=e.replace(xy,`_`).replace(Sy,``);return t?Cy.test(t)?`_${t}`:t:`_`}function Ty(e,t=!0){let n=new URLSearchParams({clientId:Po(),path:e,...t?{download:`1`}:{}});return W(j(`/api/file?${n}`))}async function Ey(e,t){let n=by?wy(t):t;try{let t=await fetch(Ty(e));if(!t.ok)return{ok:!1,cancelled:!1,error:await t.text().catch(()=>``)||(t.status===404?`FILE_NOT_FOUND`:`HTTP ${t.status}`)};if(Number(t.headers.get(`content-length`)??`0`)>yy)return window.location.assign(Ty(e)),{ok:!0};let r=await t.blob();return window.showSaveFilePicker&&window.isSecureContext?Oy(r,n):ky(r,n)}catch(e){return{ok:!1,cancelled:!1,error:e instanceof Error?e.message:String(e)}}}async function Dy(e,t){let n=by?wy(t):t;return window.showSaveFilePicker&&window.isSecureContext?Oy(e,n):ky(e,n)}async function Oy(e,t){let n,r=window.showSaveFilePicker;if(!r)return ky(e,t);try{n=await r({suggestedName:t})}catch(n){return n instanceof DOMException&&n.name===`AbortError`?{ok:!1,cancelled:!0}:ky(e,t)}try{let t=await n.createWritable();return await t.write(e),await t.close(),{ok:!0}}catch(e){return{ok:!1,cancelled:!1,error:e instanceof Error?e.message:String(e)}}}function ky(e,t){let n=URL.createObjectURL(e),r=document.createElement(`a`);return r.href=n,r.download=t,document.body.appendChild(r),r.click(),r.remove(),setTimeout(()=>URL.revokeObjectURL(n),1e4),{ok:!0}}var Ay={"image/png":`png`,"image/jpeg":`jpg`,"image/gif":`gif`,"image/webp":`webp`,"image/avif":`avif`,"image/bmp":`bmp`,"image/svg+xml":`svg`,"image/tiff":`tiff`,"image/x-icon":`ico`},jy=/\.(?:png|jpe?g|gif|webp|avif|bmp|svg|tiff?|ico|heic|heif)$/i;function My(e,t){let n=(e?.split(/[\\/]/).pop()||`image`).replace(/[\u0000-\u001f<>:"|?*]/g,`_`).trim(),r=Ay[t];return r?n.toLowerCase().endsWith(`.${r}`)||r===`jpg`&&/\.jpeg$/i.test(n)?n:`${n.replace(jy,``).slice(0,180)||`image`}.${r}`:n||`image`}async function Ny(e,t,n){let r=await fetch(e,{credentials:`same-origin`,signal:n});if(!r.ok)throw Error(`HTTP ${r.status}`);let i=await r.blob();if(n?.throwIfAborted(),!i.size)throw Error(`Empty image`);let a=i.type;if(!a.startsWith(`image/`)){let e=new Uint8Array(await i.slice(0,12).arrayBuffer()),t=String.fromCharCode(...e);a=e[0]===137&&t.slice(1,4)===`PNG`?`image/png`:e[0]===255&&e[1]===216&&e[2]===255?`image/jpeg`:t.startsWith(`GIF8`)?`image/gif`:t.startsWith(`RIFF`)&&t.slice(8)===`WEBP`?`image/webp`:`image/unknown`}return n?.throwIfAborted(),new File([i],My(t,a),{type:a})}async function Py(e,t){let n=await Ny(e,void 0,t);if(n.type===`image/png`)return n;let r=URL.createObjectURL(n);try{let e=new Image;e.src=r,await e.decode(),t?.throwIfAborted();let n=document.createElement(`canvas`);n.width=e.naturalWidth,n.height=e.naturalHeight;let i=n.getContext(`2d`);if(!i)throw Error(`Image conversion is unavailable`);i.drawImage(e,0,0);let a=await new Promise((e,t)=>{n.toBlob(n=>n?e(n):t(Error(`Image conversion failed`)),`image/png`)});return t?.throwIfAborted(),a}finally{URL.revokeObjectURL(r)}}async function Fy(e,t){if(!navigator.clipboard?.write||typeof ClipboardItem>`u`)throw new DOMException(`Image clipboard is unavailable`,`NotSupportedError`);let n=Py(e,t);n.catch(()=>{}),await navigator.clipboard.write([new ClipboardItem({"image/png":n})])}async function Iy(e,t,n){let r=await Ny(e,t,n),i=await Dy(r,r.name);if(i.ok)return!0;if(i.cancelled)return!1;throw Error(i.error)}function Ly({tip:e,label:t,disabled:n,onClick:r,className:i,buttonRef:a,children:o}){return(0,$.jsx)(`button`,{ref:a,type:`button`,className:i?`img-lightbox-btn ${i}`:`img-lightbox-btn`,"data-tip":e,"aria-label":t??e,disabled:n,onClick:r,children:o})}function Ry({src:e,alt:t,onClose:n,onSaveAnnotation:r,actions:a,composerSessionId:o}){let s=X(),c=Rt(),l=Ye(tt()),u=o,f=(0,Q.useRef)(u);f.current=u;let[m,h]=(0,Q.useState)(null),g=m?.original===e?m.src:e,_=g===e?t:My(t,`image/png`),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(``),[w,T]=(0,Q.useState)(null),E=!!r||w?.sessionId===u&&w?.src===g,D=(0,Q.useRef)(null),O=(0,Q.useRef)(null),[k,A]=(0,Q.useState)(null),j=k?.src===g?k:{width:0,height:0},[N,P]=(0,Q.useState)(null),[I,L]=(0,Q.useState)(!1),R=(0,Q.useRef)(!1);R.current=I;let B=(0,Q.useSyncExternalStore)(wn,En),V=(0,Q.useSyncExternalStore)(la,ca),[H,U]=(0,Q.useState)(``),W=B.find(e=>e.id===H)??B[0],K=!W&&V.busy,q=!W&&V.error,[te,ne]=(0,Q.useState)(!1),[re,J]=(0,Q.useState)(0),[ie,ae]=(0,Q.useState)(null),[oe,se]=(0,Q.useState)(``),[Y,ce]=(0,Q.useState)(null),le=Y===g,[ue,de]=(0,Q.useState)(!1),fe=(0,Q.useRef)(null),pe=(0,Q.useRef)(null),me=(0,Q.useRef)(null),he=(0,Q.useRef)(n);he.current=n;let ge=(0,Q.useRef)({src:g,onSaveAnnotation:r});ge.current={src:g,onSaveAnnotation:r};let _e=(0,Q.useRef)(ue);_e.current=ue;let{copied:ve,copy:ye,reset:be}=Gn();(0,Q.useEffect)(()=>(fe.current?.abort(),fe.current=null,ne(!1),J(0),ae(null),se(``),be(),()=>{fe.current?.abort(),fe.current=null}),[g,W,be]),(0,Q.useEffect)(()=>h(null),[e]),(0,Q.useEffect)(()=>(D.current?.abort(),D.current=null,y(null),x(``),C(``),de(!1),P(null),L(!1),()=>{D.current?.abort(),D.current=null}),[g]),(0,Q.useEffect)(()=>{let e=document.activeElement;me.current?.focus({focusVisible:!1});let t=e=>{if(!document.querySelector(`.approval-modal, .perm-modal-backdrop`)){if(e.key===`Escape`){if(e.stopImmediatePropagation(),_e.current){e.preventDefault(),de(!1);return}if(R.current){e.preventDefault(),L(!1);return}e.preventDefault(),he.current()}else if(e.key===`Tab`){let t=pe.current?.querySelectorAll(`button:not(:disabled), select:not(:disabled), textarea:not(:disabled), input:not(:disabled)`);if(!t?.length)return;let n=t[0],r=t[t.length-1];e.shiftKey&&(document.activeElement===n||!pe.current?.contains(document.activeElement))?(e.preventDefault(),r.focus()):e.shiftKey||document.activeElement!==r&&pe.current?.contains(document.activeElement)||(e.preventDefault(),n.focus())}else if((e.key===`f`||e.key===`F`)&&!e.metaKey&&!e.ctrlKey&&!e.altKey){let t=e.target instanceof HTMLElement?e.target:null;if(e.repeat||t&&(t.isContentEditable||/^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName)))return;e.preventDefault(),L(!R.current)}}};return window.addEventListener(`keydown`,t,!0),()=>{window.removeEventListener(`keydown`,t,!0),e instanceof HTMLElement&&e.isConnected&&e.focus()}},[]);let xe=async()=>{if(!W||fe.current||le)return;let e=new AbortController;fe.current=e,ne(!0),se(``),ae(null),J(0),be();try{let t=await W.recognize({src:g,signal:e.signal,onProgress:t=>{fe.current===e&&Number.isFinite(t)&&J(Math.max(0,Math.min(1,t)))}});fe.current===e&&!e.signal.aborted&&ae(String(t.text??``).trim())}catch(t){fe.current===e&&!e.signal.aborted&&se(t instanceof Error?t.message:s(`imageOcrFailed`))}finally{fe.current===e&&(fe.current=null,ne(!1))}},Se=async e=>{if(D.current||le||ue)return;let t=new AbortController;D.current=t,y(e),x(``),C(``);try{if(e===`copy`)await Fy(g,t.signal);else if(e===`download`){if(!await Iy(g,_,t.signal))return}else{if(!u)throw Error(s(`imageAttachFailed`));let e=await ha(await Ny(g,_,t.signal));if(t.signal.throwIfAborted(),!e||e.size>2097152||f.current!==u||!ir({attachments:[{path:``,name:My(e.name,e.mimeType),imageData:e.data,mimeType:e.mimeType,size:e.size,key:crypto.randomUUID()}]}))throw Error(s(`imageAttachFailed`));D.current===t&&T({sessionId:u,src:g})}D.current===t&&C(s(e===`attach`?`imageAttached`:e===`copy`?`imageCopied`:`imageDownloaded`))}catch(n){if(D.current===t&&!t.signal.aborted){let t=n instanceof Error?n.message:String(n),r=s(e===`attach`?`imageAttachFailed`:`copyFailed`);x(n instanceof Error&&n.name===`NotSupportedError`?s(`imageCopyUnavailable`):e===`download`?s(`downloadFailed`,{error:t}):t===r?r:`${r}: ${t}`)}}finally{D.current===t&&(D.current=null,y(null))}},Ce=e=>{let t=N??Math.min((O.current?.clientWidth||j.width)/j.width,(O.current?.clientHeight||j.height)/j.height);P(Math.max(.1,Math.min(4,t*e)))},we=!!v||ue||le;return(0,Er.createPortal)((0,$.jsx)(`div`,{ref:pe,className:`img-lightbox`,"data-fullscreen":I?`true`:void 0,style:{zIndex:c},role:`dialog`,"aria-modal":`true`,"aria-label":t||s(`toolImageZoom`),onClick:e=>{e.target===e.currentTarget&&n()},children:(0,$.jsxs)(`div`,{className:`img-lightbox-panel`,children:[(0,$.jsxs)(`div`,{className:`img-lightbox-toolbar`,children:[(0,$.jsx)(`span`,{className:`img-lightbox-name`,title:_,children:_}),(0,$.jsxs)(`div`,{className:`img-lightbox-actions`,children:[(0,$.jsx)(Ly,{tip:s(E?`imageAttached`:`imageAttach`),disabled:we||!u||E,onClick:()=>void Se(`attach`),children:E?(0,$.jsx)(z,{}):(0,$.jsx)(ct,{})}),(0,$.jsx)(Ly,{tip:s(`imageCopy`),disabled:we,onClick:()=>void Se(`copy`),children:(0,$.jsx)(st,{})}),(0,$.jsx)(Ly,{tip:s(`downloadFile`),disabled:we,onClick:()=>void Se(`download`),children:(0,$.jsx)(ht,{})}),a?.filter(e=>e.id!==`download`).map(e=>(0,$.jsx)(`button`,{type:`button`,className:`img-lightbox-btn img-lightbox-btn-text`,disabled:!!v||ue,onClick:()=>{try{let t=e.onSelect();e.closeOnSelect&&n(),Promise.resolve(t).catch(e=>{pe.current&&se(e instanceof Error?e.message:String(e))})}catch(e){se(e instanceof Error?e.message:String(e))}},children:e.label},e.id)),B.length>1&&(0,$.jsx)(`select`,{className:`img-lightbox-select`,"aria-label":s(`imageOcrProvider`),value:W?.id??``,disabled:te,onChange:e=>U(e.target.value),children:B.map(e=>(0,$.jsx)(`option`,{value:e.id,children:l?e.label:e.labelEn||e.label},e.id))}),(0,$.jsx)(Ly,{tip:s(`imageAnnotate`),disabled:te||we,onClick:()=>{L(!0),de(!0)},children:(0,$.jsx)(dt,{})}),g!==e&&(0,$.jsx)(Ly,{tip:s(`imageRestoreOriginal`),disabled:te||we,onClick:()=>h(null),children:(0,$.jsx)(ee,{})}),(0,$.jsx)(Ly,{tip:s(W?`imageOcr`:`imageOcrInstall`),label:s(K?`imageOcrInstalling`:`imageOcr`),disabled:te||K||we,onClick:()=>W?void xe():da(),children:(0,$.jsx)(vt,{})}),(0,$.jsx)(Ly,{tip:s(I?`exitFullscreen`:`fullscreen`),onClick:()=>L(!I),children:I?(0,$.jsx)(Mt,{}):(0,$.jsx)(F,{})}),(0,$.jsx)(Ly,{tip:s(`close`),className:`img-lightbox-close`,buttonRef:me,onClick:n,children:(0,$.jsx)(Ct,{})})]})]}),(v||S||b)&&(0,$.jsx)(`div`,{className:`img-lightbox-notice${b?` img-lightbox-notice-error`:``}`,role:b?`alert`:`status`,children:b||(v?s(`running`):S)}),ue?(0,$.jsx)(ra,{src:g,saveLabel:s(r?`imageAnnotateSave`:`imageAnnotApply`),onCancel:()=>de(!1),onSave:async t=>{r&&await r(t),pe.current?.isConnected&&ge.current.src===g&&ge.current.onSaveAnnotation===r&&(r?n():(h({original:e,src:t}),de(!1)))}},g):(0,$.jsxs)(`div`,{className:`img-lightbox-content`,children:[(0,$.jsxs)(`div`,{className:`img-lightbox-viewer`,children:[(0,$.jsxs)(`div`,{className:`img-lightbox-image${N===null?``:` img-lightbox-image-zoomed`}`,"data-pending":j.width>0||le?void 0:`true`,children:[(0,$.jsx)(`img`,{crossOrigin:i(g),ref:O,src:g,alt:t??`image preview`,style:N===null||!j.width?void 0:{width:j.width*N,height:j.height*N},onLoad:e=>{A({src:g,width:e.currentTarget.naturalWidth,height:e.currentTarget.naturalHeight}),ce(null)},onDoubleClick:()=>L(!I),onError:()=>ce(g)},g),le&&(0,$.jsx)(`p`,{role:`alert`,children:s(`imagePreviewFailed`)})]}),(0,$.jsxs)(`div`,{className:`img-lightbox-view-controls`,children:[j.width>0&&(0,$.jsxs)(`span`,{className:`img-lightbox-dims`,children:[j.width,` × `,j.height]}),(0,$.jsx)(Ly,{tip:s(`imageZoomOut`),disabled:!j.width||N!==null&&N<=.1,onClick:()=>Ce(.8),children:(0,$.jsx)(d,{})}),(0,$.jsx)(Ly,{tip:s(`imageActualSize`),disabled:!j.width,onClick:()=>P(1),children:(0,$.jsx)(M,{})}),N!==null&&(0,$.jsxs)(`span`,{className:`img-lightbox-zoom`,children:[Math.round(N*100),`%`]}),(0,$.jsx)(Ly,{tip:s(`imageZoomIn`),disabled:!j.width||N!==null&&N>=4,onClick:()=>Ce(1.25),children:(0,$.jsx)(p,{})}),(0,$.jsx)(Ly,{tip:s(`imageFit`),disabled:N===null,onClick:()=>P(null),children:(0,$.jsx)(G,{})})]})]}),(te||ie!==null||oe||K||q)&&(0,$.jsxs)(`section`,{className:`img-lightbox-ocr`,"aria-label":s(`imageOcrResult`),children:[(0,$.jsxs)(`div`,{className:`img-lightbox-ocr-head`,children:[(0,$.jsx)(`strong`,{children:s(`imageOcrResult`)}),te?(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{fe.current?.abort(),fe.current=null,ne(!1)},children:s(`cancel`)}):ie?(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:async()=>{await ye(ie)||se(s(`copyFailed`))},children:[ve?(0,$.jsx)(z,{}):(0,$.jsx)(st,{}),s(ve?`copied`:`copyText`)]}):null]}),te&&(0,$.jsxs)(`div`,{role:`status`,children:[(0,$.jsxs)(`p`,{children:[s(`imageOcrWorking`),` `,Math.round(re*100),`%`]}),(0,$.jsx)(`progress`,{max:1,value:re}),(0,$.jsx)(`p`,{className:`img-lightbox-hint`,children:s(`imageOcrDownload`)})]}),K&&(0,$.jsx)(`p`,{role:`status`,children:s(`imageOcrInstalling`)}),q&&(0,$.jsx)(`p`,{role:`alert`,children:q}),oe&&(0,$.jsx)(`p`,{role:`alert`,children:oe}),ie!==null&&(ie?(0,$.jsx)(`textarea`,{"aria-label":s(`imageOcrResult`),value:ie,readOnly:!0,spellCheck:!1}):(0,$.jsx)(`p`,{role:`status`,children:s(`imageOcrEmpty`)}))]})]})]})}),document.body)}var zy=(0,Q.memo)(function({open:e=!0,currentModelId:t,models:n,modelsLoading:r=!1,providerKeys:i={},providers:a,defaultModel:o,onManageModels:s,onSelect:c,onClose:l,title:u}){let d=X();return(0,Q.useEffect)(()=>{if(!e)return;let t=e=>{e.key===`Escape`&&(e.preventDefault(),l())};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,l]),e?(0,$.jsx)(`div`,{className:`modal-backdrop`,style:{zIndex:1200,display:`flex`,alignItems:`center`,justifyContent:`center`},onClick:e=>{e.target===e.currentTarget&&l()},children:(0,$.jsxs)(`div`,{className:`modal dd-menu dd-menu-model`,style:{position:`relative`,top:`auto`,bottom:`auto`,left:`auto`,right:`auto`,transform:`none`,width:`min(92vw, 680px)`,maxWidth:`680px`,height:`min(84vh, 640px)`,maxHeight:`86vh`,padding:0,gap:0,display:`flex`,flexDirection:`column`,overflow:`hidden`,boxShadow:`0 24px 64px rgba(0, 0, 0, 0.55)`,background:`var(--bg-elev2, #1b1b24)`,borderRadius:`12px`,border:`1px solid var(--border)`},children:[(0,$.jsxs)(`div`,{className:`dd-header dd-header-flex`,style:{padding:`10px 14px`,borderBottom:`1px solid var(--border, #333)`},children:[(0,$.jsx)(`span`,{className:`dd-header-title`,style:{fontWeight:600},children:u||d(`availableModels`)}),(0,$.jsx)(`div`,{className:`dd-header-actions`,style:{marginLeft:`auto`},children:(0,$.jsx)(`button`,{type:`button`,className:`ghost dd-header-btn`,style:{border:0,cursor:`pointer`,fontSize:16},onClick:l,title:d(`close`),children:(0,$.jsx)(Ct,{})})})]}),(0,$.jsx)(df,{models:n,modelsLoading:r,providerKeys:i,providers:a,defaultModel:o,currentModelId:t,active:e,onEnsureModels:()=>{n.length===0&&!r&&Z({type:`list_models`})},onRefresh:()=>Z({type:`list_models`}),onManageModels:s,onToggleDefault:lf,onPickModel:e=>{c(e.id,e),l()},isRowActive:e=>sf(e,t),autoFocusSearch:!0,hideTitle:!0,bodyStyle:{flex:1,minHeight:0},scrollStyle:{flex:`1 1 auto`,minHeight:0,minWidth:0,maxHeight:`none`,overflowY:`auto`}})]})}):null});function By(e){return typeof e==`string`?e.trim():``}function Vy(e,t){let n=By(e.name)||e.id;return Ye(t)?n:By(e.nameEn)||n}function Hy(e,t){let n=By(e.description),r=By(e.descriptionEn);return Ye(t)?n||r||void 0:r||n||void 0}var Uy=new Map,Wy=-1;function Gy(e){let t=e.trim().toLowerCase();return t.startsWith(`.`)?t:`.${t}`}function Ky(e){let t=e.replace(/\\/g,`/`).split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(n).toLowerCase():``}function qy(e,t){Wy!==t&&(Wy=t);let n=new Map;for(let t of e){let e=t;if(!e.error&&e.hasClient&&Array.isArray(e.fileHandlers)){for(let t of e.fileHandlers)if(t&&t.id&&Array.isArray(t.extensions))for(let r of t.extensions){if(typeof r!=`string`)continue;let i=Gy(r);if(!/^\.[a-z0-9][a-z0-9._-]*$/.test(i))continue;let a=n.get(i)??[];a.push({plugin:e,declaration:t}),n.set(i,a)}}}for(let e of n.values())e.sort((e,t)=>t.declaration.priority-e.declaration.priority||e.plugin.id.localeCompare(t.plugin.id));Uy=n}function Jy(e){return Uy.get(Ky(e))?.[0]??null}async function Yy(e){let t=await N0(e.plugin,Wy);if(!t)return null;let n=t.fileHandlers,r;if(Array.isArray(n))r=n.find(t=>t&&t.id===e.declaration.id),!r&&n.length===1&&typeof n[0]?.mount==`function`&&(r=n[0]);else if(n&&typeof n==`object`){r=n[e.declaration.id];let t=Object.values(n);!r&&t.length===1&&typeof t[0]?.mount==`function`&&(r=t[0])}return!r||typeof r.mount!=`function`?null:{handler:r,pluginId:e.plugin.id}}function Xy({file:e,plugin:t,declaration:n,epoch:r,send:i,onClose:a,onFallback:o}){let{t:s,locale:c}=_e(),l=(0,Q.useRef)(null),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(!1),m=(0,Q.useRef)(o);m.current=o;let h=(Ye(c)?n.label:n.labelEn??n.label)??Vy(t,c);(0,Q.useEffect)(()=>{let r=l.current;if(!r)return;let a=!1,o;return d(null),p(!1),(async()=>{try{let c=await Yy({plugin:t,declaration:n});if(a)return;if(!c)throw Error(s(`pluginFilePreviewNoViewer`));let l=`/plugins-api/${encodeURIComponent(t.id)}`,u={...L0(t.id,i),file:e,apiUrl:(e,t)=>{let n=String(e??``).startsWith(`/`)?String(e):`/${String(e??``)}`,r=new URLSearchParams;for(let[e,n]of Object.entries(t??{}))n!==void 0&&r.set(e,String(n));r.set(`clientId`,Po());let i=r.toString();return W(j(`${l}${n}${i?`?${i}`:``}`))}};o=c.handler.mount(r,e,u),a||p(!0)}catch(e){a||(console.error(`[plugin:${t.id}] file handler failed:`,e),m.current())}})(),()=>{if(a=!0,typeof o==`function`)try{o()}catch(e){console.error(`[plugin:${t.id}] file handler cleanup failed:`,e)}r.textContent=``}},[e,t,n,r,i]);let g=(0,$.jsxs)(`div`,{className:`plugin-file-preview-title-row`,children:[(0,$.jsx)(`span`,{className:`plugin-file-preview-name`,title:e.path,children:e.name||e.path}),h?(0,$.jsx)(`span`,{className:`plugin-file-preview-badge`,children:h}):null]});return(0,$.jsx)(jr,{className:`plugin-file-preview`,title:g,icon:t.icon,allowFullscreen:!0,onClose:a,children:(0,$.jsxs)(`div`,{className:`modal-body plugin-file-preview-body`,children:[u?(0,$.jsx)(`div`,{className:`plugin-file-preview-error`,children:u}):null,!u&&!f?(0,$.jsx)(`div`,{className:`plugin-file-preview-loading`,children:s(`loading`)}):null,(0,$.jsx)(`div`,{ref:l,className:`plugin-file-preview-host`})]})})}function Zy({entry:e}){let t=(0,Q.useRef)(null),{t:n,locale:r}=_e();return(0,Q.useEffect)(()=>{let i=t.current;if(!i)return;let{container:a,cleanup:o}=d0(i,{isolated:!!(e.info.isolated||e.module.isolated||e.module.shadow)}),s;try{s=e.module.mount(a,L0(e.info.id,e=>Z(e)))}catch(t){console.error(`[plugin:${e.info.id}] mount failed:`,t),a.textContent=n(`pluginMountFailed`,{name:Vy(e.info,r)})}return()=>{if(typeof s==`function`)try{s()}catch(t){console.error(`[plugin:${e.info.id}] cleanup failed:`,t)}o()}},[e]),(0,$.jsx)(`div`,{className:`plugin-view`,ref:t})}function Qy({entry:e,pluginView:t,onUiAction:n,onClose:r}){let i=X(),a=e.label||e.id,o=e.kind===`view`;return(0,$.jsx)(jr,{className:`plugin-modal`,title:a,icon:e.icon,onClose:r,children:(0,$.jsx)(`div`,{className:`modal-body plugin-modal-body`,children:o?t?(0,$.jsx)(Zy,{entry:t}):(0,$.jsx)(`div`,{className:`plugin-modal-loading`,children:i(`loading`)}):e.kind===`divider`?(0,$.jsx)(`hr`,{className:`plugin-modal-divider`}):(0,$.jsx)(`button`,{type:`button`,className:`btn primary plugin-modal-action`,onClick:()=>n?.(e),children:e.badge??a})})})}function $y(e){let t=(0,Q.useRef)(null),n=(0,Q.useRef)(null),r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(!1),l=(0,Q.useCallback)(e=>{let r=t.current;if(!r)return;let{width:i,height:o}=r.getBoundingClientRect(),s={x:Math.max(8,Math.min(e.x,window.innerWidth-i-8)),y:Math.max(8,Math.min(e.y,window.innerHeight-o-8))};n.current=s,a(e=>e?.x===s.x&&e.y===s.y?e:s)},[]);(0,Q.useLayoutEffect)(()=>{if(!e){r.current=null,s(!1);return}let i=t.current;if(!i)return;let a=()=>{n.current&&l(n.current)};a();let o=new ResizeObserver(a);return o.observe(i),window.addEventListener(`resize`,a),()=>{o.disconnect(),window.removeEventListener(`resize`,a)}},[e,l]);let u=e=>{let n=e.target instanceof Element?e.target.closest(`button, select, input, textarea, a, [role='button'], [contenteditable='true']`):null;if(e.button!==0||!e.isPrimary||n&&n!==e.currentTarget)return!1;let i=t.current;if(!i)return!1;let a=i.getBoundingClientRect();return r.current={pointerId:e.pointerId,start:{x:e.clientX,y:e.clientY},origin:{x:a.left,y:a.top},moved:!1},c.current=!1,n!==e.currentTarget&&e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),!0},d=e=>{let t=r.current;if(!t||t.pointerId!==e.pointerId)return;let n=e.clientX-t.start.x,i=e.clientY-t.start.y;!t.moved&&Math.hypot(n,i)<3||(t.moved=!0,c.current=!0,s(!0),l({x:t.origin.x+n,y:t.origin.y+i}))},f=e=>{r.current?.pointerId===e.pointerId&&(r.current=null,s(!1),e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))};return{panelRef:t,style:i?{left:i.x,top:i.y,right:`auto`,bottom:`auto`}:void 0,dragging:o,onPointerDown:u,onPointerMove:d,onPointerUp:f,onPointerCancel:f,onLostPointerCapture:f,onClickCapture:e=>{c.current&&e.detail!==0&&(e.preventDefault(),e.stopPropagation()),c.current=!1}}}var e2=`pi:quick-ask-open`;function t2(e={}){window.dispatchEvent(new CustomEvent(e2,{detail:e}))}function n2(e,t){return(e?.trim()||`解释下: {{input}}`).replaceAll(`{{input}}`,()=>t)}var r2={zh:`Simplified Chinese`,"zh-CN":`Simplified Chinese`,"zh-TW":`Traditional Chinese`,"zh-HK":`Traditional Chinese`,"zh-Hant":`Traditional Chinese`,en:`English`,ja:`Japanese`,ko:`Korean`,de:`German`,fr:`French`,es:`Spanish`,ru:`Russian`,pt:`Portuguese`,it:`Italian`,tr:`Turkish`},i2={auto:`Auto`,"zh-CN":`简体中文`,"zh-TW":`繁體中文`,en:`English`,ja:`日本語`,ko:`한국어`,de:`Deutsch`,fr:`Français`,es:`Español`,ru:`Русский`,pt:`Português`,it:`Italiano`,tr:`Türkçe`};function a2(e,t,n,r=e?.quickAskTranslateTarget||`auto`){let i=r===`auto`?n:r,a=r2[i]||r2[i.split(`-`)[0]]||`English`,o=e?.quickAskTranslatePrompt?.trim()||`将以下文字翻译成{{targetLanguage}},只输出译文,保留代码与专有名词。
|
|
72
|
-
{{input}}`,s={natural:`Use natural, fluent phrasing while preserving the original meaning.`,literal:`Translate faithfully and stay close to the original wording.`,technical:`Use precise technical terminology and preserve code and identifiers.`}[e?.quickAskTranslateStyle||`natural`];return o.replace(/\{\{(input|targetLanguage)\}\}/g,(e,n)=>n===`input`?t:a)+`\n\nTranslation style: ${s}`}async function o2(e,t){if(!e.ok||!e.headers.get(`content-type`)?.includes(`application/x-ndjson`)){let n=await e.json();if(!e.ok)throw Error(n.error||`HTTP ${e.status}`);if(!n.text?.trim())throw Error(`Model returned no answer`);t({type:`done`,text:n.text,model:n.model??``});return}if(!e.body)throw Error(`Model response has no body`);let n=e.body.getReader(),r=new TextDecoder,i=``,a=!1,o=e=>{if(!e.trim())return;let n=JSON.parse(e);if(!n||typeof n!=`object`)throw Error(`Invalid quick ask stream event`);switch(n.type){case`start`:if(typeof n.model!=`string`)throw Error(`Invalid model in stream`);break;case`delta`:if(typeof n.text!=`string`)throw Error(`Invalid text in stream`);break;case`done`:if(typeof n.text!=`string`||!n.text.trim()||typeof n.model!=`string`)throw Error(`Model returned no answer`);a=!0;break;case`error`:throw Error(typeof n.error==`string`?n.error:`Quick ask failed`);default:throw Error(`Invalid quick ask stream event`)}t(n)};try{for(;!a;){let{done:e,value:t}=await n.read();i+=e?r.decode():r.decode(t,{stream:!0});let s;for(;!a&&(s=i.indexOf(`
|
|
73
|
-
`))!==-1;)o(i.slice(0,s)),i=i.slice(s+1);if(i.length>1048576)throw Error(`Quick ask stream frame is too large`);if(e){a||o(i);break}}if(!a)throw Error(`Model stream ended before completion`)}finally{await n.cancel().catch(()=>{}),n.releaseLock()}}function s2(e,t,n=[]){let r=e.at(-1)?.role===`user`?e.slice(0,-1):e,i=n.filter(e=>!r.some(t=>t.attachments?.some(t=>l2(t,e))));return[...r,{role:`user`,content:t,...i.length?{attachments:i}:{}}]}function c2(e,t){if(!t)return e;let n=!1,r=e.map(e=>{if(!e.attachments?.some(e=>e.id===t))return e;n=!0;let r=e.attachments.filter(e=>e.id!==t);return r.length?{...e,attachments:r}:{role:e.role,content:e.content}});return n?r:e}function l2(e,t){return e.id===t.id&&e.content===t.content&&e.image?.data===t.image?.data&&e.image?.mimeType===t.image?.mimeType}var u2=class extends Error{code;constructor(e){super(e),this.code=e}};function d2(e){let t=0,n=0,r=0;for(let i of e){n+=i.content.length;for(let e of i.attachments||[]){t++,n+=e.content.length+e.name.length+(e.path?.length||0)+128;let i=e.image?.data;i&&(r+=i.length*3/4-(i.endsWith(`==`)?2:+!!i.endsWith(`=`)))}}return t>8?`quickAskTooManyReferences`:r>6291456?`quickAskImagesTooLarge`:n>65536?`quickAskContextTooLarge`:null}async function f2(e,t){let n=new AbortController,r=()=>n.abort(t.signal.reason);t.signal.aborted?r():t.signal.addEventListener(`abort`,r,{once:!0});let i=setTimeout(()=>n.abort(Error(`Loading reference timed out`)),45e3);try{let r=await fetch(j(`/api/quick-ask/context`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({source:e,scope:t.scope,clientId:t.clientId}),signal:n.signal}),i=await r.json();if(!r.ok)throw r.status===415||/unsupported|binary file/i.test(i.error||``)?new u2(`quickAskUnsupportedFile`):Error(i.error||`HTTP ${r.status}`);let a=i.attachment;if(!a||typeof a.id!=`string`||typeof a.name!=`string`||typeof a.content!=`string`||![`file`,`directory`,`conversation`].includes(a.kind))throw Error(`Invalid reference response`);return a}finally{clearTimeout(i),t.signal.removeEventListener(`abort`,r)}}async function p2(e,t){if(e.size>2097152)throw new u2(`quickAskFileTooLarge`);t.signal.throwIfAborted();let n=new Uint8Array(await e.arrayBuffer());t.signal.throwIfAborted();let r=``;for(let e=0;e<n.length;e+=8192)r+=String.fromCharCode(...n.subarray(e,e+8192));return f2({kind:`upload`,name:e.name,data:btoa(r),mimeType:e.type},t)}async function m2(e,t){t.signal.throwIfAborted();let n=e[0]?.webkitRelativePath.split(`/`)[0]||`folder`,r=e.slice(0,64),i=r.map(e=>e.webkitRelativePath||e.name).join(`
|
|
74
|
-
`).slice(0,16e3);if(e.length>r.length&&(i+=`\n[Listing truncated: ${e.length-r.length} more files]`),t.scope===`content`){let e=r.filter(e=>e.type.startsWith(`text/`)||/\.(?:txt|md|mdx|json|jsonc|ya?ml|toml|xml|csv|ts|tsx|js|jsx|mjs|cjs|py|go|rs|java|c|cpp|h|css|html|sh|sql|log|ini|conf)$/i.test(e.name));for(let n of e.slice(0,8)){let e=await p2(n,t);if(i+=`\n\n--- ${n.webkitRelativePath||n.name} ---\n${e.content}`,i.length>3e4){i=i.slice(0,3e4)+`
|
|
75
|
-
[Content truncated]`;break}}e.length>8&&(i+=`
|
|
76
|
-
[Additional text files omitted]`)}return{id:`upload-directory:${n}`,kind:`directory`,name:`${n}/`,content:i}}function h2({attachments:e,onRemove:t}){let n=X(),[r,i]=(0,Q.useState)(!1);return e.length?(0,$.jsxs)(`div`,{className:`quick-ask-references${r?` is-expanded`:``}`,"aria-label":n(`quickAskReferences`),children:[(0,$.jsx)(`div`,{className:`quick-ask-reference-tags`,children:(r?e:e.slice(0,2)).map(e=>{let r=e.kind===`conversation`?_:e.kind===`directory`?Ee:vt;return(0,$.jsxs)(`span`,{className:`quick-ask-reference-tag`,title:e.path||e.name,children:[(0,$.jsx)(r,{size:10,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:e.name}),t&&(0,$.jsx)(`button`,{type:`button`,"aria-label":`${n(`quickAskRemoveReference`)}: ${e.name}`,onClick:()=>t(e.id),children:(0,$.jsx)(Ct,{size:10})})]},e.id)})}),e.length>2&&(0,$.jsx)(`button`,{type:`button`,className:`quick-ask-reference-count`,"aria-expanded":r,"aria-label":n(r?`quickAskCollapseReferences`:`quickAskExpandReferences`),onClick:()=>i(!r),children:r?`−`:`+${e.length-2}`})]}):null}function g2({currentConversation:e,disabled:t,onReference:n,onFiles:r,onFolder:i}){let a=X(),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(null),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(!1),f=T_({open:o,anchor:c,side:`top`,align:`left`,onClose:()=>s(!1)});return(0,Q.useEffect)(()=>{u.current?.setAttribute(`webkitdirectory`,``)},[]),(0,Q.useLayoutEffect)(()=>{o||(d.current=!1),o&&f.pos&&!d.current&&(d.current=!0,f.panelRef.current?.querySelector(`button:not(:disabled)`)?.focus({preventScroll:!0}))},[o,f.pos,f.panelRef]),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:c,type:`button`,className:`quick-ask-attach`,title:a(`quickAskAttach`),"aria-label":a(`quickAskAttach`),"aria-expanded":o,"aria-haspopup":`dialog`,"aria-controls":`quick-ask-attachment-menu`,disabled:t,onClick:()=>s(!o),children:(0,$.jsx)(ct,{size:14})}),(0,$.jsx)(`input`,{ref:l,type:`file`,multiple:!0,hidden:!0,"aria-label":a(`quickAskAttachFiles`),onChange:e=>{let t=Array.from(e.target.files||[]);e.target.value=``,t.length&&r(t)}}),(0,$.jsx)(`input`,{ref:u,type:`file`,multiple:!0,hidden:!0,"aria-label":a(`quickAskAttachFolder`),onChange:e=>{let t=Array.from(e.target.files||[]);e.target.value=``,t.length&&i(t)}}),o&&(0,Er.createPortal)((0,$.jsxs)(`div`,{ref:f.panelRef,style:f.style,id:`quick-ask-attachment-menu`,className:`quick-ask-menu quick-ask-attachment-menu`,role:`dialog`,"aria-label":a(`quickAskAttach`),children:[(0,$.jsxs)(`button`,{type:`button`,disabled:!e,onClick:()=>{let t=e;s(!1),t&&n(t)},children:[(0,$.jsx)(_,{size:13}),a(`quickAskAttachCurrent`)]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>{s(!1),l.current?.click()},children:[(0,$.jsx)(vt,{size:13}),a(`quickAskAttachFiles`)]}),(0,$.jsxs)(`button`,{type:`button`,onClick:()=>{s(!1),u.current?.click()},children:[(0,$.jsx)(Ee,{size:13}),a(`quickAskAttachFolder`)]})]}),document.body)]})}function _2({settings:e,fallbackModel:t,currentConversation:n,clientId:r}){let i=X(),{locale:a}=_e(),[o,s]=(0,Q.useState)(!1),c=$y(o),l=$y(!o&&e?.quickAskEnabled!==!1),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(!1),[g,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(``),[S,C]=(0,Q.useState)(!1),[w,T]=(0,Q.useState)(null),[E,D]=(0,Q.useState)(!1),[O,k]=(0,Q.useState)(!1),[A,M]=(0,Q.useState)(``),[N,P]=(0,Q.useState)(`ask`),[F,I]=(0,Q.useState)(e?.quickAskTranslateTarget||`auto`),[L,R]=(0,Q.useState)([]),z=(0,Q.useRef)([]),B=(0,Q.useRef)(0),V=(0,Q.useRef)(new Set),[H,ee]=(0,Q.useState)(0),[U,W]=(0,Q.useState)(!1),[G,K]=(0,Q.useState)(null),q=(0,Q.useRef)(null),re=(0,Q.useRef)(null),J=(0,Q.useRef)(null),ie=(0,Q.useRef)(null),ae=(0,Q.useRef)(null),oe=l.panelRef,se=(0,Q.useRef)(null),Y=(0,Q.useRef)(null),ce=(0,Q.useRef)(null),le=(0,Q.useRef)(!0),de=(0,Q.useRef)(0),fe=(0,Q.useRef)(o),pe=(0,Q.useRef)(!1),me=(0,Q.useRef)(new Set),he=(0,Q.useRef)(0),ge=(0,Q.useRef)(n?.kind===`conversation`?n.conversationId:void 0),ve=(0,Q.useRef)(!1),ye=()=>{ce.current&&(de.current=ce.current.scrollTop),v(!1),s(!1)};Lt(ye,o);let be=T_({open:o&&g,anchor:Y,onClose:()=>v(!1)}),xe=()=>{J.current?.(),J.current=null,q.current?.abort(),q.current=null,C(!1)},Se=()=>{B.current++;for(let e of V.current)e.abort();V.current.clear(),z.current=[],R([]),ee(0),K(null)},Ce=e=>{z.current=e,R(e)},we=e?.quickAskConversationScope||`recent`,Te=async(e,t)=>{let n=B.current,r=new AbortController;V.current.add(r),s(!0),k(!1),v(!1),ee(e=>e+1),K(null);try{let t=await e(r.signal);if(n!==B.current||r.signal.aborted)return;let i=[...z.current];for(let e of t){let t=i.findIndex(t=>t.id===e.id);t<0?i.push(e):i[t]=e}if(i.length>8)throw new u2(`quickAskTooManyReferences`);return Ce(i),h(!0),t}catch(e){n===B.current&&!r.signal.aborted&&K(t?.(e)??(e instanceof u2?i(e.code):e instanceof Error?e.message:String(e)));return}finally{V.current.delete(r),n===B.current&&ee(e=>Math.max(0,e-1))}},Ee=t=>{let n=t.kind===`conversation`?we:t.kind===`directory`?e?.quickAskFolderScope||`listing`:void 0;return Te(async e=>[await f2(t,{scope:n,clientId:r,signal:e})])},De=async()=>{if(!n)return;let e=(await Te(async e=>[await f2(n,{scope:we,clientId:r,signal:e})],e=>/no user\/assistant text/i.test(e instanceof Error?e.message:String(e))?i(`quickAskContextEmpty`):void 0))?.find(e=>e.kind===`conversation`);if(e){me.current.add(e.id);let t=[...me.current].filter(t=>t!==e.id);t.length&&Ce(z.current.filter(e=>!t.includes(e.id)))}return e},Oe=async()=>{pe.current?(pe.current=!1,W(!1),Ce(z.current.filter(e=>!me.current.has(e.id))),me.current.clear()):n&&(pe.current=!0,W(!0),h(!0),await De())},ke=()=>{xe(),Se(),he.current++,P(`ask`),re.current=null,d([]),p(``),h(!0),v(!1),b(``),T(null),D(!1),k(!1),M(``),le.current=!0,de.current=0,ae.current?.focus({preventScroll:!0}),pe.current&&De()},Ae=async e=>{xe();let n=new AbortController;q.current=n,re.current=e,d(e),C(!0),T(null),D(!1),k(!1),le.current=!0;let r=``,a=()=>q.current===n&&!n.signal.aborted,o=()=>{ie.current!==null&&cancelAnimationFrame(ie.current),ie.current=null,a()&&r&&d([...e,{role:`assistant`,content:r}])};J.current=o;try{await o2(await fetch(j(`/api/quick-ask`),{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/x-ndjson`},body:JSON.stringify({messages:e,fallbackModel:t}),signal:n.signal}),e=>{a()&&(e.type===`start`&&M(e.model),e.type===`delta`&&(r+=e.text,ie.current===null&&(ie.current=requestAnimationFrame(o))),e.type===`done`&&(r=e.text,M(e.model),o(),fe.current||k(!0)))})}catch(e){if(a()){let t=e instanceof Error?e.message:String(e);T(e instanceof TypeError||/failed to fetch|networkerror|load failed/i.test(t)?i(`quickAskNetworkError`):t===`Model returned no answer`?i(`quickAskEmptyAnswer`):t)}}finally{q.current===n&&(o(),J.current=null,q.current=null,C(!1))}},je=async(e=y.trim())=>{if(!e||q.current||ve.current||V.current.size)return;let t=he.current;ve.current=!0,P(`ask`),h(!0),b(``);try{if(pe.current&&await De(),t!==he.current||q.current)return;let n=s2([...me.current].reduce((e,t)=>c2(e,t),u),e,z.current),r=d2(n);if(r){K(i(r)),b(t=>t||e);return}Ae(n)}finally{ve.current=!1}},Me=e=>Te(async t=>{if(e.length>8)throw new u2(`quickAskTooManyReferences`);let n=[];for(let i of e)n.push(await p2(i,{signal:t,clientId:r}));return n}),Ne=t=>{let n=e?.quickAskFolderScope||`listing`;return Te(async e=>[await m2(t,{scope:n,clientId:r,signal:e})])},Pe=(t,n,r=e?.quickAskTranslateTarget||`auto`)=>{(n!==`translate`||e?.quickAskTranslateEnabled!==!1)&&(t.trim()?(Se(),he.current++,s(!0),P(n),I(r),p(t),h(!1),v(!1),b(``),M(``),de.current=0,Ae([{role:`user`,content:n===`translate`?a2(e,t,a,r):n2(e?.quickAskExplainPrompt,t)}])):K(i(`quickAskEmptySelection`)))},Fe=n?.kind===`conversation`?n.conversationId:void 0;(0,Q.useEffect)(()=>{ge.current!==Fe&&(ge.current=Fe,pe.current&&De())},[Fe]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;s(!0),k(!1),t.reference?Ee(t.reference):t.selection!==void 0&&Pe(t.selection,t.action||`explain`)};return window.addEventListener(e2,e),()=>window.removeEventListener(e2,e)},[e?.quickAskExplainPrompt,e?.quickAskTranslatePrompt,e?.quickAskTranslateTarget,e?.quickAskTranslateStyle,e?.quickAskTranslateEnabled,e?.quickAskConversationScope,e?.quickAskFolderScope,t,r,a,i]),(0,Q.useEffect)(()=>()=>{B.current++;for(let e of V.current)e.abort();V.current.clear();let e=q.current;q.current=null,J.current=null,e?.abort(),ie.current!==null&&cancelAnimationFrame(ie.current),ie.current=null},[]),(0,Q.useLayoutEffect)(()=>{fe.current=o,o?(k(!1),(ae.current||se.current)?.focus({preventScroll:!0}),ce.current&&(ce.current.scrollTop=de.current)):document.activeElement===document.body&&oe.current?.focus({preventScroll:!0})},[o]),(0,Q.useLayoutEffect)(()=>{o&&m&&ae.current?.focus({preventScroll:!0})},[o,m]),(0,Q.useLayoutEffect)(()=>{g&&be.panelRef.current?.querySelector(`button`)?.focus({preventScroll:!0})},[g,be.panelRef]),(0,Q.useLayoutEffect)(()=>{o&&le.current&&ce.current&&(ce.current.scrollTop=ce.current.scrollHeight)},[o,u,S,w,E]);let Ie=A||e?.quickAskModel||t||i(`quickAskFollowModel`),Re=u.findLast(e=>e.role===`assistant`),ze=u.at(-1)?.role===`assistant`,Be=m||u.length===0;return(0,Er.createPortal)((0,$.jsxs)($.Fragment,{children:[!o&&e?.quickAskEnabled!==!1&&(0,$.jsxs)(`button`,{ref:oe,type:`button`,className:`quick-ask-launcher${S?` is-loading`:``}${O?` has-answer`:``}${l.dragging?` is-dragging`:``}`,style:l.style,title:i(O?`quickAskReady`:S?`quickAskLoading`:`quickAskOpen`),"aria-label":i(`quickAskOpen`),onPointerDown:l.onPointerDown,onPointerMove:l.onPointerMove,onPointerUp:l.onPointerUp,onPointerCancel:l.onPointerCancel,onLostPointerCapture:l.onLostPointerCapture,onClickCapture:l.onClickCapture,onClick:()=>s(!0),children:[(0,$.jsx)(_,{size:20}),(S||O)&&(0,$.jsx)(`span`,{className:`quick-ask-launcher-dot`,"aria-hidden":`true`}),O&&(0,$.jsx)(`span`,{className:`quick-ask-launcher-status`,role:`status`,children:i(`quickAskReady`)})]}),o&&(0,$.jsxs)(`div`,{ref:c.panelRef,style:c.style,className:`quick-ask-popover${c.dragging?` is-dragging`:``}`,role:`dialog`,"aria-modal":`false`,"aria-label":i(`quickAskTitle`),children:[(0,$.jsxs)(`div`,{className:`quick-ask-header`,onPointerDown:e=>{c.onPointerDown(e)&&v(!1)},onPointerMove:c.onPointerMove,onPointerUp:c.onPointerUp,onPointerCancel:c.onPointerCancel,onLostPointerCapture:c.onLostPointerCapture,children:[N===`translate`?(0,$.jsx)(Le,{className:`quick-ask-symbol`,size:14,"aria-hidden":`true`}):(0,$.jsx)(ne,{className:`quick-ask-symbol`,size:14,"aria-hidden":`true`}),(0,$.jsx)(`strong`,{className:`quick-ask-heading`,children:i(N===`translate`?`quickAskTranslation`:`quickAskTitle`)}),N===`translate`&&(0,$.jsx)(`select`,{className:`quick-ask-target`,value:F,"aria-label":i(`quickAskTargetLanguage`),disabled:e?.quickAskTranslateEnabled===!1,onChange:e=>Pe(f,`translate`,e.target.value),children:Object.entries(i2).map(([e,t])=>(0,$.jsx)(`option`,{value:e,children:e===`auto`?i(`quickAskTargetAuto`):t},e))}),(0,$.jsxs)(`div`,{className:`quick-ask-header-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-icon`,title:i(`quickAskNewTopic`),"aria-label":i(`quickAskNewTopic`),onClick:ke,children:(0,$.jsx)(ue,{size:15,"aria-hidden":`true`})}),(0,$.jsx)(`button`,{ref:Y,type:`button`,className:`btn-icon`,title:i(`quickAskMore`),"aria-label":i(`quickAskMore`),"aria-expanded":g,"aria-haspopup":`dialog`,"aria-controls":`quick-ask-menu`,onClick:()=>v(!g),children:(0,$.jsx)(x,{size:15})}),(0,$.jsx)(`button`,{ref:se,type:`button`,className:`btn-icon`,title:i(`quickAskClose`),"aria-label":i(`quickAskClose`),onClick:ye,children:(0,$.jsx)(Ct,{size:14})})]})]}),(0,$.jsx)(h2,{attachments:L,onRemove:e=>{me.current.has(e)&&(pe.current=!1,W(!1),me.current.clear()),Ce(z.current.filter(t=>t.id!==e))}}),(0,$.jsxs)(`div`,{ref:ce,id:`quick-ask-answer`,className:`quick-ask-body`,"aria-busy":S,onScroll:()=>{let e=ce.current;e&&(le.current=e.scrollHeight-e.scrollTop-e.clientHeight<36,de.current=e.scrollTop)},children:[u.length===0&&L.length>0&&(0,$.jsx)(`p`,{className:`quick-ask-reference-empty`,children:i(`quickAskReferenceEmpty`)}),u.length===0&&L.length===0&&(0,$.jsxs)(`div`,{className:`quick-ask-empty`,children:[(0,$.jsx)(`strong`,{children:i(`quickAskEmptyTitle`)}),(0,$.jsx)(`p`,{children:i(`quickAskEmpty`)})]}),u.map((e,t)=>(0,$.jsx)(`div`,{className:`quick-ask-message quick-ask-${e.role}`,children:e.role===`assistant`?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`quick-ask-answer${S&&t===u.length-1?` is-streaming`:``}`,children:(0,$.jsx)(nl,{text:e.content})}),(!S||t<u.length-1)&&(0,$.jsx)(dc,{text:e.content})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(h2,{attachments:e.attachments||[]}),(0,$.jsx)(`div`,{className:t===0&&f?`quick-ask-selection`:void 0,children:t===0&&f?f:e.content})]})},t)),H>0&&(0,$.jsx)(`p`,{role:`status`,className:`quick-ask-reference-status`,children:i(`quickAskReferenceLoading`)}),G&&(0,$.jsxs)(`p`,{role:`alert`,className:`quick-ask-reference-error`,children:[i(`quickAskReferenceError`),`: `,G]}),S&&(0,$.jsxs)(`p`,{role:`status`,className:`quick-ask-stream-status`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`}),i(`quickAskLoading`)]}),w&&(0,$.jsxs)(`div`,{role:`alert`,className:`quick-ask-error`,children:[(0,$.jsx)(`strong`,{children:i(`quickAskError`)}),(0,$.jsx)(`p`,{children:w})]}),E&&(0,$.jsx)(`p`,{role:`status`,className:`quick-ask-stopped`,children:i(`quickAskStopped`)}),(w||E)&&re.current&&(0,$.jsx)(`button`,{type:`button`,className:`quick-ask-chip`,onClick:()=>void Ae(re.current),children:i(`quickAskRetry`)}),!S&&!w&&!E&&ze&&(0,$.jsxs)(`div`,{className:`quick-ask-suggestions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`quick-ask-chip`,onClick:()=>void je(i(`quickAskExample`)),children:i(`quickAskExample`)}),(0,$.jsx)(`button`,{type:`button`,className:`quick-ask-chip`,onClick:()=>void je(i(`quickAskSummarize`)),children:i(`quickAskSummarize`)})]})]}),(0,$.jsxs)(`div`,{className:`quick-ask-actions`,children:[(0,$.jsx)(g2,{currentConversation:n,disabled:H>0,onReference:e=>void Ee(e),onFiles:e=>void Me(e),onFolder:e=>void Ne(e)}),(0,$.jsxs)(`button`,{type:`button`,className:`quick-ask-context${U?` is-active`:``}`,"aria-pressed":U,"aria-label":i(`quickAskContextCurrent`),disabled:!n||H>0,title:n?U?i(`quickAskContextOnHint`):i(`quickAskContextOffHint`,{scope:i(we===`full`?`quickAskConversationFull`:`quickAskConversationRecent`)}):i(`quickAskContextUnavailable`),onClick:()=>void Oe(),children:[(0,$.jsx)(_,{size:12,"aria-hidden":`true`}),i(`quickAskContextCurrent`)]}),u.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`quick-ask-ask`,"aria-expanded":Be,"aria-controls":`quick-ask-composer`,onClick:()=>h(!Be),children:[(0,$.jsx)(_,{size:12,"aria-hidden":`true`}),i(Be?`quickAskHideInput`:`quickAskAsk`)]}),S&&(0,$.jsxs)(`button`,{type:`button`,className:`quick-ask-stop`,title:i(`quickAskStop`),"aria-label":i(`quickAskStop`),onClick:()=>{xe(),D(!0)},children:[(0,$.jsx)(_t,{size:10,"aria-hidden":`true`}),i(`quickAskStop`)]})]})]}),Be&&(0,$.jsx)(`form`,{id:`quick-ask-composer`,className:`quick-ask-composer`,onSubmit:e=>{e.preventDefault(),je()},children:(0,$.jsxs)(`div`,{className:`quick-ask-input-wrap`,children:[(0,$.jsx)(`textarea`,{ref:ae,value:y,onChange:e=>b(e.target.value),placeholder:i(ze?`quickAskFollowUp`:`quickAskPlaceholder`),"aria-label":i(`quickAskInputLabel`),rows:y.includes(`
|
|
77
|
-
`)?2:1,onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.nativeEvent.keyCode!==229&&(e.preventDefault(),je())}}),(0,$.jsx)(`button`,{type:`submit`,className:`quick-ask-send`,disabled:S||H>0||!y.trim(),title:i(`quickAskSend`),"aria-label":i(`quickAskSend`),children:(0,$.jsx)(te,{size:14})})]})})]}),o&&g&&(0,$.jsxs)(`div`,{ref:be.panelRef,id:`quick-ask-menu`,className:`quick-ask-menu`,style:be.style,role:`dialog`,"aria-label":i(`quickAskMore`),children:[Re&&(0,$.jsxs)(`div`,{className:`quick-ask-menu-row`,children:[(0,$.jsx)(`span`,{children:i(`copy`)}),(0,$.jsx)(dc,{text:Re.content})]}),(0,$.jsxs)(`div`,{className:`quick-ask-model`,title:Ie,children:[(0,$.jsx)(ne,{size:11,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:Ie})]}),(0,$.jsxs)(`div`,{className:`quick-ask-scope`,children:[(0,$.jsx)(Ge,{size:10,"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:i(`quickAskScope`)})]})]})]}),document.body)}var v2=null,y2=new Set;function b2(){for(let e of y2)e()}function x2(e){v2=e,b2()}function S2(){v2=null,b2()}function C2(e){v2&&(Z({type:`rollback_session`,messageId:v2.messageId,conversationId:v2.conversationId,restoreWorkspace:e}),v2=null,b2())}function w2(){return(0,Q.useSyncExternalStore)(e=>(y2.add(e),()=>y2.delete(e)),()=>v2)}function T2(){let e=X(),t=w2(),[n,r]=(0,Q.useState)(!0),i=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{t&&r(!0)},[t]),Lt(()=>{t&&S2()},!!t),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>{if(e.key!==`Enter`||e.shiftKey||e.ctrlKey||e.metaKey)return;let t=e.target;(!t||t===document.body||i.current?.contains(t))&&(e.preventDefault(),C2(n))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[t,n]),t?(0,Er.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:S2,children:(0,$.jsxs)(`div`,{ref:i,className:`tool-info-modal rollback-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":e(`rollbackSession`),onClick:e=>e.stopPropagation(),style:{maxWidth:520},children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,style:{color:`var(--amber, #f59e0b)`},children:[(0,$.jsx)(me,{}),e(`rollbackSession`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`cancel`),onClick:S2,children:(0,$.jsx)(Ct,{})})]}),(0,$.jsxs)(`div`,{className:`tool-info-body`,style:{padding:`16px 20px`},children:[(0,$.jsx)(`p`,{style:{margin:`0 0 16px 0`,fontSize:14,lineHeight:1.6},children:e(`rollbackConfirm`)}),(0,$.jsxs)(`label`,{style:{display:`flex`,alignItems:`flex-start`,gap:10,padding:`12px 14px`,borderRadius:8,backgroundColor:`var(--bg-elev, rgba(255, 255, 255, 0.04))`,border:`1px solid var(--border-subtle, rgba(255, 255, 255, 0.1))`,cursor:`pointer`,marginBottom:20},title:e(`rollbackRestoreWorkspaceTip`),children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:n,onChange:e=>r(e.target.checked),style:{marginTop:3,cursor:`pointer`}}),(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`div`,{style:{fontWeight:600,fontSize:13,color:`var(--text, #e2e8f0)`},children:e(`rollbackRestoreWorkspace`)}),(0,$.jsx)(`div`,{style:{fontSize:12,color:`var(--text-dim, #9aa1b4)`,marginTop:2},children:e(`rollbackRestoreWorkspaceTip`)})]})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:10},children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:S2,children:e(`cancel`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,style:{display:`inline-flex`,alignItems:`center`,gap:6,backgroundColor:`var(--amber, #f59e0b)`,borderColor:`var(--amber, #f59e0b)`,color:`#000`,fontWeight:600},onClick:()=>C2(n),children:[(0,$.jsx)(z,{}),e(`confirm`)]})]})]})]})}),document.body):null}function E2(e){return e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()||e}function D2(e,t,n){return!!(n&&t&&e&&n.path===t.path&&e.path===t.path&&(e.sandboxId===t.id||e.error&&e.sandboxId===``)&&e.requestId===n.requestId)}function O2(e){return!!(e&&!e.error&&e.expectedRevision&&e.added.length+e.modified.length+e.deleted.length>0)}function k2({mode:e,currentCwd:t,currentSandbox:n,sandboxDiff:r,projects:i,send:a,onClose:o}){let s=X(),c=n?.sourcePath||(!n&&t?t:i.find(e=>!e.sandbox)?.path||t||``),[l,u]=(0,Q.useState)(c?`import`:`blank`),[d,f]=(0,Q.useState)(c),[p,m]=(0,Q.useState)(!0),[h,g]=(0,Q.useState)(``),_=n?.sourcePath?`${n.sourcePath}-exp`:`~/projects/${(n?.name||`sandbox-app`).replace(/[^a-zA-Z0-9_-]+/g,`-`).replace(/^-|-$/g,``)||`sandbox-app`}`,[v,y]=(0,Q.useState)(_),[b,x]=(0,Q.useState)(!0),[S,C]=(0,Q.useState)(null),w=()=>{if(!n)return;let e={requestId:or(),path:n.path};C(e),a({type:`diff_sandbox`,...e})};(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]),(0,Q.useEffect)(()=>{if(C(null),e===`apply`&&n?.path){let e={requestId:or(),path:n.path};C(e),a({type:`diff_sandbox`,...e})}},[e,n?.path,a]);let T=i.filter(e=>!e.sandbox),D=e=>{e.preventDefault();let t=l===`import`?d.trim():void 0;(l!==`import`||t)&&(a({type:`create_sandbox`,name:h.trim()||void 0,sourcePath:t,ephemeral:p}),o())},O=e=>{e.preventDefault();let t=v.trim();t&&(a({type:`promote_sandbox`,path:n?.path,targetPath:t,switchToTarget:b}),o())},k=e=>{e.preventDefault(),n?.path&&A&&O2(r)&&r.expectedRevision&&(C(null),a({type:`apply_sandbox_to_source`,path:n.path,expectedRevision:r.expectedRevision}),o())},A=e===`apply`&&D2(r,n,S),j=A?r.added.length+r.modified.length+r.deleted.length:0,M=s(e===`create`?`sandboxModalTitle`:e===`promote`?`sandboxPromoteTitle`:`sandboxApplyTitle`);return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:o,children:(0,$.jsxs)(`div`,{className:`modal sandbox-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,onClick:o,title:s(`close`),"aria-label":s(`close`),children:(0,$.jsx)(Ct,{})}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(`span`,{className:`modal-head-icon`,"aria-hidden":!0,children:(0,$.jsx)(rp,{})}),(0,$.jsx)(`h2`,{children:M})]}),e===`create`?(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:D,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxModalSubtitle`)}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxModeLabel`)}),(0,$.jsxs)(`div`,{className:`sandbox-choice-grid`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${l===`import`?`active`:``}`,onClick:()=>u(`import`),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(E,{"aria-hidden":!0}),` `,s(`sandboxModeImport`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxModeImportDesc`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${l===`blank`?`active`:``}`,onClick:()=>u(`blank`),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(Je,{"aria-hidden":!0}),` `,s(`sandboxModeBlank`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxModeBlankDesc`)})]})]})]}),l===`import`&&(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxSourceLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:d,onChange:e=>f(e.target.value),placeholder:s(`sandboxSourcePlaceholder`),required:!0}),T.length>0&&(0,$.jsx)(`div`,{className:`sandbox-source-chips`,children:T.slice(0,6).map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-source-chip ${d===e.path?`active`:``}`,onClick:()=>f(e.path),title:e.path,children:[(0,$.jsx)(Ee,{"aria-hidden":!0,style:{marginRight:4,verticalAlign:`-1px`}}),E2(e.path)]},e.path))})]}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxLifecycleLabel`)}),(0,$.jsxs)(`div`,{className:`sandbox-choice-grid`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${p?`active`:``}`,onClick:()=>m(!0),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(re,{"aria-hidden":!0}),` `,s(`sandboxLifecycleEphemeral`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxLifecycleEphemeralDesc`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-choice-card ${p?``:`active`}`,onClick:()=>m(!1),children:[(0,$.jsxs)(`div`,{className:`sandbox-choice-title`,children:[(0,$.jsx)(Ve,{"aria-hidden":!0}),` `,s(`sandboxLifecyclePermanent`)]}),(0,$.jsx)(`div`,{className:`sandbox-choice-desc`,children:s(`sandboxLifecyclePermanentDesc`)})]})]})]}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxNameLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:h,onChange:e=>g(e.target.value),placeholder:l===`import`&&d.trim()?`${E2(d.trim())} (Sandbox)`:s(`sandboxNamePlaceholder`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:l===`import`&&!d.trim(),children:[(0,$.jsx)(rp,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxCreateSubmit`)]})]})]}):e===`promote`?(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:O,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxPromoteSubtitle`,{name:n?.name||``})}),(0,$.jsxs)(`div`,{className:`sandbox-field-group`,children:[(0,$.jsx)(`label`,{className:`sandbox-field-label`,children:s(`sandboxPromoteTargetLabel`)}),(0,$.jsx)(`input`,{type:`text`,className:`sandbox-text-input`,value:v,onChange:e=>y(e.target.value),placeholder:s(`sandboxPromoteTargetPlaceholder`),autoFocus:!0,required:!0})]}),(0,$.jsxs)(`label`,{className:`sandbox-checkbox-row`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:b,onChange:e=>x(e.target.checked)}),(0,$.jsx)(`span`,{children:s(`sandboxPromoteSwitchLabel`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:!v.trim(),children:[(0,$.jsx)(Ot,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxPromoteSubmit`)]})]})]}):(0,$.jsxs)(`form`,{className:`modal-body sandbox-modal-body`,onSubmit:k,children:[(0,$.jsx)(`p`,{className:`sandbox-modal-subtitle`,children:s(`sandboxActionApplyConfirm`,{name:n?.name||``,source:n?.sourcePath||``})}),A?r.error?(0,$.jsx)(`div`,{className:`sandbox-diff-empty`,children:r.error}):(0,$.jsxs)(`div`,{className:`sandbox-diff-box`,children:[(0,$.jsx)(`div`,{className:`sandbox-diff-stats`,children:s(`sandboxDiffStats`,{added:r.added.length,modified:r.modified.length,deleted:r.deleted.length,unchanged:r.unchangedCount})}),r.added.length+r.modified.length+r.deleted.length===0?(0,$.jsx)(`div`,{className:`sandbox-diff-empty`,children:s(`sandboxDiffEmpty`)}):(0,$.jsxs)(`div`,{className:`sandbox-diff-list`,children:[r.added.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item added`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag added`,children:`+`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`a:${e}`)),r.modified.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item modified`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag modified`,children:`~`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`m:${e}`)),r.deleted.map(e=>(0,$.jsxs)(`div`,{className:`sandbox-diff-item deleted`,children:[(0,$.jsx)(`span`,{className:`sandbox-diff-tag deleted`,children:`-`}),(0,$.jsx)(`span`,{className:`sandbox-diff-path`,children:e})]},`d:${e}`))]}),(0,$.jsx)(`div`,{className:`sandbox-diff-note`,children:s(`sandboxDiffDeletedNote`)})]}):(0,$.jsx)(`div`,{className:`sandbox-diff-loading`,children:s(`loading`)}),(0,$.jsxs)(`div`,{className:`sandbox-modal-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:o,children:s(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:w,children:s(`sandboxDiffRefresh`)}),(0,$.jsxs)(`button`,{type:`submit`,className:`btn primary`,disabled:!A||!O2(r),children:[(0,$.jsx)(z,{"aria-hidden":!0,style:{marginRight:5,verticalAlign:`-2px`}}),s(`sandboxApplySubmit`,{count:j})]})]})]})]})})}var A2=3,j2=200;function M2(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function N2(e){return typeof e==`string`&&e.trim()||void 0}function P2(e,t){let n=[];for(let r of e){let e=I2(r,t);if(n.includes(e)||n.push(e),n.length>=4){n.push(`…`);break}}return n.join(` | `)||`any`}function F2(e){let t=e.slice(0,6).map(e=>typeof e==`string`?e:JSON.stringify(e)??String(e));if(t.length!==0)return`enum: ${t.join(` | `)}${e.length>t.length?` | …`:``}`}function I2(e,t=0){if(t>6||!M2(e))return`any`;if(N2(e.$ref))return`ref`;let n=N2(e.type);if(n===`array`){let n=e.items;return`array<${n===void 0?`any`:I2(n,t+1)}>`}if(n)return n;for(let n of[`anyOf`,`oneOf`,`allOf`]){let r=e[n];if(Array.isArray(r)&&r.length>0)return P2(r,t+1)}return M2(e.properties)?`object`:M2(e.additionalProperties)?`record<${I2(e.additionalProperties,t+1)}>`:`any`}function L2(e){let t=[],n=e.enum;if(Array.isArray(n)&&n.length>0){let e=F2(n);e&&t.push(e)}return e.const!==void 0&&t.push(`const: ${JSON.stringify(e.const)}`),e.default!==void 0&&t.push(`default: ${JSON.stringify(e.default)}`),t.length>0?t.join(` · `):void 0}function R2(e,t={}){let n=t.maxDepth??A2,r=t.maxRows??j2,i=e;if(!M2(i))return[];let a=i.properties;if(!M2(a))return[];let o=[],s=new Set((Array.isArray(i.required)?i.required:[]).filter(e=>typeof e==`string`)),c=(e,t,i,a)=>{if(!(o.length>=r))for(let[s,l]of Object.entries(e)){if(o.length>=r)return;let e=M2(l)?l:{},u=t?`${t}.${s}`:s,d={name:u,type:I2(e,i),required:a.has(s),depth:i},f=N2(e.description);f&&(d.description=f);let p=L2(e);if(p&&(d.hint=p),o.push(d),i+1<n&&M2(e.properties)){let t=new Set((Array.isArray(e.required)?e.required:[]).filter(e=>typeof e==`string`));c(e.properties,u,i+1,t)}}};return c(a,``,0,s),o}function z2(){let e=X(),t=$h();return Lt(()=>{Yh()},!!t),t?(0,Er.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:Yh,children:(0,$.jsxs)(`div`,{className:`tool-info-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":e(`toolInfoTitle`),onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,children:[(0,$.jsx)(q,{}),e(`toolInfoTitle`)]}),(0,$.jsx)(`code`,{className:`tool-info-name`,children:t.name}),t.label&&t.label!==t.name&&(0,$.jsx)(`span`,{className:`tool-info-label`,children:t.label}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`close`),onClick:Yh,children:(0,$.jsx)(Ct,{})})]}),(0,$.jsx)(`div`,{className:`tool-info-body`,children:(0,$.jsx)(B2,{info:t})})]})}),document.body):null}function B2({info:e}){let t=X();if(e.status===`loading`)return(0,$.jsxs)(`div`,{className:`tool-info-state`,role:`status`,children:[(0,$.jsx)(`span`,{className:`cursor`}),` `,t(`toolInfoLoading`)]});if(e.status===`unsupported`)return(0,$.jsx)(`div`,{className:`tool-info-state`,children:t(`toolInfoUnsupported`)});if(e.status===`missing`)return(0,$.jsx)(`div`,{className:`tool-info-state`,children:t(`toolInfoMissing`)});let n=e.parameters===void 0?[]:R2(e.parameters),r=e.parameters===void 0?``:H2(e.parameters);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`tool-info-badges`,children:[e.active!==void 0&&(0,$.jsx)(`span`,{className:`tool-info-badge ${e.active?`on`:`off`}`,children:e.active?t(`toolInfoActive`):t(`toolInfoInactive`)}),e.source&&(0,$.jsxs)(`span`,{className:`tool-info-badge`,children:[t(`toolInfoSource`),`: `,e.source,e.scope?` · ${e.scope}`:``]})]}),(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoDescription`)}),(0,$.jsx)(`div`,{className:`tool-info-text`,children:e.description||t(`toolInfoNoDescription`)})]}),e.promptSnippet&&(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoPromptSnippet`)}),(0,$.jsx)(`div`,{className:`tool-info-text dim`,children:e.promptSnippet})]}),e.promptGuidelines&&e.promptGuidelines.length>0&&(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoGuidelines`)}),(0,$.jsx)(`ul`,{className:`tool-info-list`,children:e.promptGuidelines.map((e,t)=>(0,$.jsx)(`li`,{children:e},t))})]}),(0,$.jsxs)(`section`,{className:`tool-info-sec`,children:[(0,$.jsx)(`div`,{className:`tool-info-sec-label`,children:t(`toolInfoParams`)}),n.length>0?(0,$.jsx)(V2,{rows:n}):(0,$.jsx)(`div`,{className:`tool-info-text dim`,children:t(`toolInfoParamsNone`)}),e.parametersDropped&&(0,$.jsx)(`div`,{className:`tool-info-text warn`,children:t(`toolInfoSchemaDropped`)}),r&&(0,$.jsxs)(`details`,{className:`tool-info-raw`,children:[(0,$.jsxs)(`summary`,{children:[t(`toolInfoRawSchema`),(0,$.jsx)(dc,{text:r})]}),(0,$.jsx)(`pre`,{children:r})]})]}),(0,$.jsx)(`div`,{className:`tool-info-foot`,children:t(`toolInfoFootnote`)})]})}function V2({rows:e}){let t=X();return(0,$.jsx)(`div`,{className:`tool-schema-table`,role:`table`,children:e.map(e=>(0,$.jsxs)(`div`,{className:`tool-schema-row`,role:`row`,style:{paddingLeft:8+e.depth*14},children:[(0,$.jsxs)(`div`,{className:`tool-schema-name`,children:[(0,$.jsx)(`code`,{children:e.name}),e.required&&(0,$.jsx)(`span`,{className:`tool-schema-req`,children:t(`toolInfoRequired`)})]}),(0,$.jsxs)(`div`,{className:`tool-schema-type`,children:[e.type,e.hint&&(0,$.jsx)(`span`,{className:`tool-schema-hint`,children:e.hint})]}),e.description&&(0,$.jsx)(`div`,{className:`tool-schema-desc`,children:e.description})]},e.name))})}function H2(e){try{return JSON.stringify(e,null,2)??``}catch{return``}}function U2({state:e}){let t=X(),n=e.startTimestamp??(e.resultTimestamp!==void 0&&e.durationMs!==void 0?e.resultTimestamp-e.durationMs:void 0),r=e.endTimestamp??e.resultTimestamp,i=e.durationMs,a=``;if(n!==void 0&&r!==void 0&&i!==void 0)try{a=t(`toolTimeRange`,{start:Nm(n),end:Nm(r),duration:jm(i)})}catch{a=``}else r===void 0?n!==void 0&&(a=Nm(n)):a=Nm(r);return a?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`inspector-time`,title:a,children:a}),(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`})]}):null}function W2(e,t){let n=e.isError??!1,r=e.statusClass===`run`&&!n,i=n?`err`:r?`run`:`ok`,a=n?`✕`:r?`⟳`:`✓`,o;o=n?e.duration?`${t(`error`)} (${e.duration})`:t(`error`):r?e.status||t(`running`):e.duration?`${t(`done`)} (${e.duration})`:e.status||t(`done`);let s;return s=n?e.exitHint||t(`toolInspectorExecutionFailed`):r?e.exitHint||t(`running`):e.exitHint||t(`toolInspectorExecutionDone`),{isRunning:r,badgeClass:i,statusIcon:a,badgeText:o,footerText:s}}function G2(e){let t=e&&typeof e==`object`?Object.keys(e).length:0;return{formattedDetails:(0,Q.useMemo)(()=>{if(!e||typeof e!=`object`)return``;try{return JSON.stringify(e,null,2)}catch{return``}},[e]),detailsKeysCount:t}}function K2({args:e,formattedDetails:t,detailsKeysCount:n}){let r=X();return(0,$.jsxs)(`div`,{className:`file-diff-raw-body`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[`⚡ `,r(`toolInspectorArgs`)]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:e||r(`toolInspectorNoArgs`)})]}),t&&(0,$.jsxs)(`div`,{className:`file-diff-raw-section`,children:[(0,$.jsxs)(`div`,{className:`file-diff-raw-title`,children:[(0,$.jsxs)(`span`,{children:[`⚙ `,r(`toolInspectorDetails`)]}),(0,$.jsxs)(`span`,{className:`file-diff-raw-count`,children:[n,` keys`]})]}),(0,$.jsx)(`pre`,{className:`file-diff-pre`,children:t})]})]})}function q2({state:e,isMaximized:t,onToggleMaximize:n}){let r=X(),{copy:i,copied:a}=Gn({duration:1200}),o=e.thinking||e.output||``,s=o.length,c=o?o.split(`
|
|
78
|
-
`).length:0,l=(0,Q.useRef)(null),u=(0,Q.useRef)(!0);return(0,Q.useEffect)(()=>{u.current=!0},[e.toolCallId]),(0,Q.useEffect)(()=>{if(!e.streaming)return;let t=l.current;t&&u.current&&(t.scrollTop=t.scrollHeight)},[o,e.streaming]),(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&zt()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(fe,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,children:r(`toolInspectorThinkingSection`).replace(/^💭\s*/,``)}),(0,$.jsx)(`span`,{className:`file-diff-lang`,children:r(`toolInspectorStats`,{chars:s,lines:c})}),(0,$.jsx)(`span`,{className:`file-diff-status-pill ${e.streaming?`run`:`ok`}`,children:e.streaming?r(`toolInspectorThinkingStatusRunning`):r(`toolInspectorThinkingStatusDone`)})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${a?` copied`:``}`,title:r(a?`toolInspectorCopied`:`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),i(o)},children:a?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(Mt,{}):(0,$.jsx)(F,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),zt()},children:(0,$.jsx)(Ct,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,ref:l,onWheel:e=>{if(e.deltaY<0)u.current=!1;else if(e.deltaY>0&&l.current){let e=l.current;e.scrollHeight-e.scrollTop-e.clientHeight<32&&(u.current=!0)}},onScroll:e=>{let t=e.currentTarget;t.scrollHeight-t.scrollTop-t.clientHeight<24&&(u.current=!0)},children:(0,$.jsx)(`div`,{className:`thinking-inspector-content`,children:o?(0,$.jsxs)(`div`,{className:`markdown thinking-markdown`,children:[(0,$.jsx)(nl,{text:o}),e.streaming&&(0,$.jsx)(`span`,{className:`stream-cursor`})]}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:r(`toolInspectorEmptyThinking`)})})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon`,children:`💭`}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:e.streaming?r(`toolInspectorThinkingFooterRunning`):r(`toolInspectorThinkingFooterLines`,{lines:c})})]}),(0,$.jsx)(`div`,{className:`file-diff-footer-meta`,children:(0,$.jsx)(U2,{state:e})})]})]})})}function J2({state:e,isMaximized:t,onToggleMaximize:n}){let r=X(),[i,a]=(0,Q.useState)(`preview`),o=Gn({duration:1200}),s=Gn({duration:1200}),{args:c=``,output:l=``,details:u,exitHint:d}=e,f=(e.hints||th(c)).command||(c&&!c.startsWith(`{`)?c:``),{formattedDetails:p,detailsKeysCount:m}=G2(u),h=W2(e,r),g=l?l.split(`
|
|
79
|
-
`).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&zt()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(Xe,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:f||`bash`,children:f?`$ ${f}`:`bash`}),d&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:d}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${h.badgeClass}`,children:[h.statusIcon,` `,h.badgeText]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[h.isRunning&&e.onKillBash&&(0,$.jsxs)(`button`,{type:`button`,className:`file-diff-action-btn kill-btn`,title:r(`toolInspectorStopBashTitle`),onClick:t=>{t.stopPropagation(),e.onKillBash?.()},children:[(0,$.jsx)(_t,{}),(0,$.jsx)(`span`,{className:`kill-btn-label`,children:r(`toolInspectorStop`)})]}),(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${i===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),a(`preview`)},children:r(`toolInspectorTabTerminal`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${i===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),a(`raw`)},children:r(`diffViewRaw`)})]}),f&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${o.copied?` copied`:``}`,title:o.copied?r(`toolInspectorCopied`):r(`toolInspectorCopyArgs`),onClick:e=>{e.stopPropagation(),o.copy(f)},children:o.copied?(0,$.jsx)(z,{}):(0,$.jsx)(Y,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${s.copied?` copied`:``}`,title:s.copied?r(`toolInspectorCopied`):r(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),s.copy(l)},children:s.copied?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(Mt,{}):(0,$.jsx)(F,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),zt()},children:(0,$.jsx)(Ct,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:i===`raw`?(0,$.jsx)(K2,{args:c,formattedDetails:p,detailsKeysCount:m}):(0,$.jsxs)(`div`,{className:`bash-terminal-viewport`,onContextMenu:t=>{let n=window.getSelection?.()?.toString();if(n&&n.trim().length>0)return;t.preventDefault(),t.stopPropagation();let i=[];e.onKillBash&&i.push(Mg({id:`host:kill-bash`,slot:`contextmenu.toolcall`,label:r(`toolInspectorStopBash`),icon:`■`,kind:`action`,order:-1,when:h.isRunning?void 0:[`disabled`]})),f&&i.push(Mg({id:`host:copy-command`,slot:`contextmenu.toolcall`,label:r(`toolInspectorCopyCommand`),icon:`copy`,kind:`action`,order:1})),l&&i.push(Mg({id:`host:copy-output`,slot:`contextmenu.toolcall`,label:r(`toolInspectorCopyTerminalOutput`),icon:`copy`,kind:`action`,order:2})),i.push(Mg({id:`host:tool-info`,slot:`contextmenu.toolcall`,label:r(`toolInfoTitle`),icon:`info`,kind:`action`,order:3})),jf({x:t.clientX,y:t.clientY,slot:`contextmenu.toolcall`,target:{id:e.toolCallId||`bash`,kind:`toolcall`,label:`bash`},entries:i,onHostAction:t=>{t.id===`host:kill-bash`?e.onKillBash?.():t.id===`host:copy-command`?o.copy(f):t.id===`host:copy-output`?s.copy(l):t.id===`host:tool-info`&&Jh(`bash`)}})},children:[f&&(0,$.jsx)(s_,{command:f}),(0,$.jsx)(`pre`,{className:`bash-output-pre`,children:l||(e.statusClass===`run`?r(`toolInspectorRunningOutput`):r(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${h.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${h.isRunning?` spin`:``}`,children:h.statusIcon}),(0,$.jsxs)(`span`,{className:`file-diff-status-text`,children:[h.footerText,` · `,r(`toolInspectorOutputStats`,{lines:g,chars:l.length})]})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[(0,$.jsx)(U2,{state:e}),m>0&&(0,$.jsxs)(`span`,{children:[`details: `,m,` keys`]}),m>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),a(i===`raw`?`preview`:`raw`)},children:r(i===`raw`?`toolInspectorBackToTerminal`:`toolInspectorViewRawLogsDetails`)})]})]})]})})}function Y2({state:e,isMaximized:t,onToggleMaximize:n,toolIcon:r}){let a=X(),[o,s]=(0,Q.useState)(`preview`),c=Gn({duration:1200}),{name:l=`read`,args:u=``,output:d=``,details:f,images:p}=e,m=e.hints||th(u),h=m.path||``,g=m.query||``,_=g?h?`${g} (${h})`:g:h||l,v=(0,Q.useMemo)(()=>{if(p&&p.length>0)return!0;if(h){let e=h.split(`.`).pop()?.toLowerCase();return e&&[`png`,`jpg`,`jpeg`,`gif`,`webp`,`svg`,`ico`,`bmp`].includes(e)}return!1},[p,h]),y=(0,Q.useMemo)(()=>{if(!u)return 1;try{let e=JSON.parse(u);if(typeof e?.offset==`number`&&e.offset>0)return e.offset;if(typeof e?.startLine==`number`&&e.startLine>0)return e.startLine}catch{let e=/"(?:offset|startLine|start)"\s*:\s*(\d+)/.exec(u);if(e){let t=parseInt(e[1],10);if(t>0)return t}}return 1},[u]),{formattedDetails:b,detailsKeysCount:x}=G2(f),S=W2(e,a),C=d?d.split(`
|
|
80
|
-
`).length:0;return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&zt()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(`span`,{className:`file-diff-file-icon`,children:r}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:_,children:_}),g&&(0,$.jsx)(`span`,{className:`file-diff-pattern`,title:a(`toolInspectorPatternTitle`,{query:g}),children:l===`grep`?`REGEX`:`QUERY`}),h&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:h.split(`.`).pop()?.toUpperCase()||`FILE`}),y>1&&(0,$.jsxs)(`span`,{className:`file-diff-lang`,title:a(`toolInspectorStartOffsetTitle`,{line:y}),children:[`L`,y,`~L`,y+C-1]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${S.badgeClass}`,children:[S.statusIcon,` `,S.badgeText]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${o===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`preview`)},children:a(`toolInspectorTabContent`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${o===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`raw`)},children:a(`diffViewRaw`)})]}),h&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!h)return;let t=h.split(`/`).pop()||h;Jt({path:h,name:t})},children:(0,$.jsx)(Ee,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${c.copied?` copied`:``}`,title:c.copied?a(`toolInspectorCopied`):a(`toolInspectorCopyOutput`),onClick:e=>{e.stopPropagation(),c.copy(d)},children:c.copied?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(Mt,{}):(0,$.jsx)(F,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${a(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),zt()},children:(0,$.jsx)(Ct,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:o===`raw`?(0,$.jsx)(K2,{args:u,formattedDetails:b,detailsKeysCount:x}):(0,$.jsxs)(`div`,{className:`read-inspector-viewport`,children:[l===`tool_search`&&(0,$.jsx)(c_,{details:f}),v&&p&&p.length>0?(0,$.jsxs)(`div`,{className:`read-image-viewport`,children:[p.map((e,t)=>{let n=e.startsWith(`/`)?He(e):e;return(0,$.jsx)(`div`,{className:`read-image-container`,children:(0,$.jsx)(`button`,{type:`button`,className:`image-preview-trigger`,title:a(`toolImageZoom`),onClick:()=>Tn({src:n,alt:h||`Image ${t+1}`}),children:(0,$.jsx)(`img`,{crossOrigin:i(n),src:n,alt:h||`Image ${t+1}`,className:`read-image-item`})})},t)}),d&&(0,$.jsx)(`div`,{className:`read-image-caption`,children:d})]}):d?(0,$.jsx)(Lh,{content:d,startLine:y}):(0,$.jsx)(`div`,{className:`diff-empty-tip`,children:e.statusClass===`run`?a(`toolInspectorRunningOutput`):a(`toolInspectorEmptyOutput`)})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${S.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${S.isRunning?` spin`:``}`,children:S.statusIcon}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:S.isRunning?S.footerText:a(`toolInspectorStats`,{chars:d.length,lines:C})})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[(0,$.jsx)(U2,{state:e}),x>0&&(0,$.jsxs)(`span`,{children:[`details: `,x,` keys`]}),x>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),s(o===`raw`?`preview`:`raw`)},children:a(o===`raw`?`toolInspectorBackToContent`:`toolInspectorViewRawArgs`)})]})]})]})})}function X2({state:e,isMaximized:t,onToggleMaximize:n}){let r=X(),[i,a]=(0,Q.useState)(`unified`),{copied:o,copy:s}=Gn({duration:1200}),{name:c=`edit`,args:l=``,details:u,output:d=``}=e,f=c===`edit`||c===`patch`,p=(0,Q.useMemo)(()=>Mh(c,l,u,d),[c,l,u,d]),{formattedDetails:m,detailsKeysCount:h}=G2(u),g=W2(e,r);return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&zt()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(vt,{className:`file-diff-file-icon`}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:p?.filePath||c,children:p?.filePath||c}),p?.language&&p.language!==`plaintext`&&(0,$.jsx)(`span`,{className:`file-diff-lang`,children:p.language}),p?.stats.isNewFile?(0,$.jsx)(`span`,{className:`file-diff-stat-new`,children:r(`diffNewFile`)}):p?.stats.additions!==void 0&&(p.stats.additions>0||p.stats.deletions>0)&&(0,$.jsxs)(`span`,{className:`file-diff-stat-badge`,children:[p.stats.additions>0&&(0,$.jsxs)(`span`,{className:`add`,children:[`+`,p.stats.additions]}),p.stats.deletions>0&&(0,$.jsxs)(`span`,{className:`del`,children:[`-`,p.stats.deletions]})]}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${g.badgeClass}`,children:[g.statusIcon,` `,g.badgeText]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${i===`unified`?` active`:``}`,onClick:e=>{e.stopPropagation(),a(`unified`)},children:r(`diffViewUnified`)}),!p?.isWrite&&(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${i===`split`?` active`:``}`,onClick:e=>{e.stopPropagation(),a(`split`)},children:r(`diffViewSplit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${i===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),a(`raw`)},children:r(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${o?` copied`:``}`,title:p?.isWrite?r(`diffCopyContent`):r(`diffCopyPatch`),"aria-label":p?.isWrite?r(`diffCopyContent`):r(`diffCopyPatch`),onClick:e=>{e.stopPropagation(),p?.isWrite&&p.content?s(p.content):l&&s(l)},children:o?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}),p?.filePath&&(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(`diffOpenFile`),"aria-label":r(`diffOpenFile`),onClick:e=>{if(e.stopPropagation(),!p?.filePath)return;let t=p.filePath.split(`/`).pop()||p.filePath;Jt({path:p.filePath,name:t})},children:(0,$.jsx)(Ee,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:r(t?`diffRestoreScreen`:`diffFullscreen`),"aria-label":r(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(Mt,{}):(0,$.jsx)(F,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${r(`close`)} (ESC)`,"aria-label":r(`close`),onClick:e=>{e.stopPropagation(),zt()},children:(0,$.jsx)(Ct,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:i===`raw`?(0,$.jsx)(K2,{args:l,formattedDetails:m,detailsKeysCount:h}):p?.isWrite?(0,$.jsx)(Lh,{content:p.content||``}):i===`split`?(0,$.jsx)(Bh,{hunks:p?.hunks||[],isStreaming:p?.isStreamingPartial,fallbackText:l}):(0,$.jsx)(Rh,{hunks:p?.hunks||[],isStreaming:p?.isStreamingPartial,fallbackText:l})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${g.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${g.isRunning?` spin`:``}`,children:g.statusIcon}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:g.isRunning?g.footerText:d||r(f?`toolInspectorPatchApplied`:`toolInspectorFileWritten`)})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[(0,$.jsx)(U2,{state:e}),h>0&&(0,$.jsxs)(`span`,{children:[`details: `,h,` keys`]}),h>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),a(i===`raw`?`unified`:`raw`)},children:r(i===`raw`?`toolInspectorBackToDiff`:`toolInspectorViewRawLogs`)})]})]})]})})}function Z2(e,t,n){let r={action:`spawn`};if(e)try{let t=JSON.parse(e);t&&typeof t==`object`&&(typeof t.action==`string`&&(r.action=t.action.trim().toLowerCase()),typeof t.prompt==`string`&&(r.prompt=t.prompt),typeof t.type==`string`&&(r.type=t.type),typeof t.template==`string`&&(r.template=t.template),typeof t.model==`string`&&(r.model=t.model),typeof t.thinking==`string`&&(r.thinking=t.thinking),typeof t.isolation==`string`&&(r.isolation=t.isolation),typeof t.cwd==`string`&&(r.cwd=t.cwd),typeof t.runId==`string`&&(r.runId=t.runId),typeof t.message==`string`&&(r.message=t.message),typeof t.summary==`string`&&(r.summary=t.summary),(typeof t.notifyOnDone==`boolean`||t.notifyOnDone===`manual`)&&(r.notifyOnDone=t.notifyOnDone))}catch{}if(t&&typeof t==`object`){let e=t;if(typeof e.convId==`string`&&(r.convId=e.convId),typeof e.executionId==`string`&&(r.executionId=e.executionId),typeof e.type==`string`&&!r.type&&(r.type=e.type),typeof e.model==`string`&&!r.model&&(r.model=e.model),typeof e.thinkingLevel==`string`&&!r.thinking&&(r.thinking=e.thinkingLevel),typeof e.state==`string`&&(r.state=e.state),typeof e.streaming==`boolean`&&(r.streaming=e.streaming),typeof e.messageCount==`number`&&(r.messageCount=e.messageCount),typeof e.prompt==`string`&&!r.prompt&&(r.prompt=e.prompt),typeof e.output==`string`&&(r.output=e.output),e.worktree&&typeof e.worktree==`object`){let t=e.worktree;r.worktree={branch:typeof t.branch==`string`?t.branch:void 0,path:typeof t.path==`string`?t.path:void 0,uncommittedCount:typeof t.uncommittedCount==`number`?t.uncommittedCount:void 0,aheadCount:typeof t.aheadCount==`number`?t.aheadCount:void 0,isDirty:typeof t.isDirty==`boolean`?t.isDirty:void 0,error:typeof t.error==`string`?t.error:void 0}}Array.isArray(e.requests)&&(r.consultRequests=e.requests)}if(!r.convId){if(r.runId&&/^sa-[0-9a-f]{8}/.test(r.runId))r.convId=r.runId;else if(n){let e=/sa-[0-9a-f]{8}/.exec(n);e&&(r.convId=e[0])}}return r}function Q2(e,t){switch((e||``).toLowerCase()){case`review`:return{icon:`⚖️`,label:t(`subagentInspector.roleReviewLabel`),desc:t(`subagentInspector.roleReviewDesc`)};case`implement`:return{icon:`🛠️`,label:t(`subagentInspector.roleImplementLabel`),desc:t(`subagentInspector.roleImplementDesc`)};case`explore`:return{icon:`🔍`,label:t(`subagentInspector.roleExploreLabel`),desc:t(`subagentInspector.roleExploreDesc`)};case`test`:return{icon:`🧪`,label:t(`subagentInspector.roleTestLabel`),desc:t(`subagentInspector.roleTestDesc`)};default:return{icon:`👥`,label:t(`subagentInspector.roleGeneralLabel`),desc:t(`subagentInspector.roleGeneralDesc`)}}}function $2({args:e,details:t,output:n,duration:r,statusClass:i,isError:a}){let o=X(),s=(0,Q.useMemo)(()=>Z2(e,t,n),[e,t,n]),c=Gn({duration:1200}),l=Gn({duration:1200}),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!0),m=s.action===`spawn`,[h,g]=(0,Q.useState)(m?`spawn`:`result`),_=Q2(s.type,o),v=s.output||n||``,y=s.convId||(s.runId&&/^sa-[0-9a-f]{8}/.test(s.runId)?s.runId:void 0);return(0,$.jsxs)(`div`,{className:`subagent-inspector-container`,children:[(0,$.jsx)(`style`,{children:`
|
|
81
|
-
.subagent-inspector-container {
|
|
82
|
-
display: flex;
|
|
83
|
-
flex-direction: column;
|
|
84
|
-
gap: 12px;
|
|
85
|
-
padding: 16px;
|
|
86
|
-
width: 100%;
|
|
87
|
-
box-sizing: border-box;
|
|
88
|
-
background: var(--bg);
|
|
89
|
-
color: var(--text);
|
|
90
|
-
font-family: var(--sans);
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
/* 顶部形态切换条 */
|
|
94
|
-
.subagent-mode-switcher {
|
|
95
|
-
display: flex;
|
|
96
|
-
align-items: center;
|
|
97
|
-
justify-content: space-between;
|
|
98
|
-
background: var(--bg-elev);
|
|
99
|
-
border: 1px solid var(--border);
|
|
100
|
-
border-radius: 8px;
|
|
101
|
-
padding: 6px 12px;
|
|
102
|
-
gap: 12px;
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
.subagent-mode-tabs {
|
|
106
|
-
display: flex;
|
|
107
|
-
background: var(--bg-elev2);
|
|
108
|
-
border: 1px solid var(--border-soft);
|
|
109
|
-
border-radius: 6px;
|
|
110
|
-
padding: 2px;
|
|
111
|
-
gap: 2px;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
.subagent-mode-btn {
|
|
115
|
-
background: transparent;
|
|
116
|
-
border: none;
|
|
117
|
-
color: var(--text-dim);
|
|
118
|
-
font-size: 12px;
|
|
119
|
-
font-weight: 500;
|
|
120
|
-
padding: 4px 10px;
|
|
121
|
-
border-radius: 4px;
|
|
122
|
-
cursor: pointer;
|
|
123
|
-
transition: all 0.15s ease;
|
|
124
|
-
white-space: nowrap;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
.subagent-mode-btn:hover {
|
|
128
|
-
color: var(--text);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
.subagent-mode-btn.active {
|
|
132
|
-
background: var(--bg-elev);
|
|
133
|
-
color: var(--accent);
|
|
134
|
-
font-weight: 600;
|
|
135
|
-
box-shadow: 0 1px 3px rgba(0,0,0,0.15);
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
.subagent-conv-badge {
|
|
139
|
-
font-family: var(--mono);
|
|
140
|
-
font-size: 11.5px;
|
|
141
|
-
color: var(--text-dim);
|
|
142
|
-
display: flex;
|
|
143
|
-
align-items: center;
|
|
144
|
-
gap: 6px;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
.subagent-conv-badge strong {
|
|
148
|
-
color: var(--accent);
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/* HUD 核心指标网格 */
|
|
152
|
-
.subagent-hud-grid {
|
|
153
|
-
display: grid;
|
|
154
|
-
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
|
155
|
-
gap: 10px;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
.subagent-hud-card {
|
|
159
|
-
background: var(--bg-elev);
|
|
160
|
-
border: 1px solid var(--border-soft);
|
|
161
|
-
border-radius: 6px;
|
|
162
|
-
padding: 10px 12px;
|
|
163
|
-
display: flex;
|
|
164
|
-
flex-direction: column;
|
|
165
|
-
gap: 4px;
|
|
166
|
-
position: relative;
|
|
167
|
-
overflow: hidden;
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
.subagent-hud-card::before {
|
|
171
|
-
content: "";
|
|
172
|
-
position: absolute;
|
|
173
|
-
top: 0;
|
|
174
|
-
left: 0;
|
|
175
|
-
bottom: 0;
|
|
176
|
-
width: 3px;
|
|
177
|
-
background: var(--border);
|
|
178
|
-
}
|
|
179
|
-
|
|
180
|
-
.subagent-hud-card.accent::before { background: var(--accent); }
|
|
181
|
-
.subagent-hud-card.green::before { background: var(--green); }
|
|
182
|
-
.subagent-hud-card.blue::before { background: var(--blue); }
|
|
183
|
-
.subagent-hud-card.amber::before { background: var(--amber); }
|
|
184
|
-
|
|
185
|
-
.subagent-hud-label {
|
|
186
|
-
font-size: 10.5px;
|
|
187
|
-
color: var(--text-faint);
|
|
188
|
-
text-transform: uppercase;
|
|
189
|
-
letter-spacing: 0.5px;
|
|
190
|
-
font-weight: 600;
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
.subagent-hud-val {
|
|
194
|
-
font-size: 13px;
|
|
195
|
-
font-weight: 600;
|
|
196
|
-
color: var(--text);
|
|
197
|
-
display: flex;
|
|
198
|
-
align-items: center;
|
|
199
|
-
gap: 6px;
|
|
200
|
-
white-space: nowrap;
|
|
201
|
-
overflow: hidden;
|
|
202
|
-
text-overflow: ellipsis;
|
|
203
|
-
}
|
|
204
|
-
|
|
205
|
-
.subagent-hud-sub {
|
|
206
|
-
font-size: 11px;
|
|
207
|
-
color: var(--text-dim);
|
|
208
|
-
font-family: var(--mono);
|
|
209
|
-
white-space: nowrap;
|
|
210
|
-
overflow: hidden;
|
|
211
|
-
text-overflow: ellipsis;
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
/* 结构化卡片共通 */
|
|
215
|
-
.subagent-section-card {
|
|
216
|
-
background: var(--bg-elev);
|
|
217
|
-
border: 1px solid var(--border);
|
|
218
|
-
border-radius: 8px;
|
|
219
|
-
overflow: hidden;
|
|
220
|
-
display: flex;
|
|
221
|
-
flex-direction: column;
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
.subagent-section-header {
|
|
225
|
-
background: var(--bg-elev2);
|
|
226
|
-
border-bottom: 1px solid var(--border-soft);
|
|
227
|
-
padding: 8px 12px;
|
|
228
|
-
display: flex;
|
|
229
|
-
align-items: center;
|
|
230
|
-
justify-content: space-between;
|
|
231
|
-
gap: 8px;
|
|
232
|
-
font-size: 12.5px;
|
|
233
|
-
font-weight: 600;
|
|
234
|
-
color: var(--text);
|
|
235
|
-
}
|
|
236
|
-
|
|
237
|
-
.subagent-section-header.clickable {
|
|
238
|
-
cursor: pointer;
|
|
239
|
-
user-select: none;
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
.subagent-section-header.clickable:hover {
|
|
243
|
-
background: var(--bg-elev);
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
.subagent-section-title {
|
|
247
|
-
display: flex;
|
|
248
|
-
align-items: center;
|
|
249
|
-
gap: 6px;
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
.subagent-section-body {
|
|
253
|
-
padding: 12px;
|
|
254
|
-
display: flex;
|
|
255
|
-
flex-direction: column;
|
|
256
|
-
gap: 8px;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
.subagent-prompt-box {
|
|
260
|
-
font-size: 13px;
|
|
261
|
-
line-height: 1.6;
|
|
262
|
-
color: var(--text);
|
|
263
|
-
background: var(--bg);
|
|
264
|
-
border: 1px solid var(--border-soft);
|
|
265
|
-
border-radius: 6px;
|
|
266
|
-
padding: 10px 12px;
|
|
267
|
-
white-space: pre-wrap;
|
|
268
|
-
word-break: break-word;
|
|
269
|
-
max-height: 320px;
|
|
270
|
-
overflow-y: auto;
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
.subagent-output-box {
|
|
274
|
-
font-size: 12.5px;
|
|
275
|
-
line-height: 1.6;
|
|
276
|
-
color: var(--text);
|
|
277
|
-
background: var(--bg);
|
|
278
|
-
border: 1px solid var(--border-soft);
|
|
279
|
-
border-radius: 6px;
|
|
280
|
-
padding: 12px;
|
|
281
|
-
white-space: pre-wrap;
|
|
282
|
-
word-break: break-word;
|
|
283
|
-
font-family: var(--mono);
|
|
284
|
-
max-height: 380px;
|
|
285
|
-
overflow-y: auto;
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/* 环境与参数清单表格 */
|
|
289
|
-
.subagent-spec-table {
|
|
290
|
-
width: 100%;
|
|
291
|
-
border-collapse: collapse;
|
|
292
|
-
font-size: 12px;
|
|
293
|
-
}
|
|
294
|
-
|
|
295
|
-
.subagent-spec-table tr {
|
|
296
|
-
border-bottom: 1px solid var(--border-soft);
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
.subagent-spec-table tr:last-child {
|
|
300
|
-
border-bottom: none;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
.subagent-spec-table td {
|
|
304
|
-
padding: 6px 8px;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
.subagent-spec-table td.label {
|
|
308
|
-
width: 120px;
|
|
309
|
-
color: var(--text-faint);
|
|
310
|
-
font-weight: 500;
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
.subagent-spec-table td.val {
|
|
314
|
-
color: var(--text);
|
|
315
|
-
font-family: var(--mono);
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
/* 底部快捷操作条 */
|
|
319
|
-
.subagent-action-dock {
|
|
320
|
-
display: flex;
|
|
321
|
-
align-items: center;
|
|
322
|
-
justify-content: space-between;
|
|
323
|
-
gap: 12px;
|
|
324
|
-
background: var(--bg-elev);
|
|
325
|
-
border: 1px solid var(--border);
|
|
326
|
-
border-radius: 8px;
|
|
327
|
-
padding: 10px 14px;
|
|
328
|
-
flex-wrap: wrap;
|
|
329
|
-
}
|
|
330
|
-
|
|
331
|
-
.subagent-dock-tip {
|
|
332
|
-
font-size: 12px;
|
|
333
|
-
color: var(--text-dim);
|
|
334
|
-
display: flex;
|
|
335
|
-
align-items: center;
|
|
336
|
-
gap: 6px;
|
|
337
|
-
flex: 1;
|
|
338
|
-
min-width: 220px;
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
.subagent-dock-btns {
|
|
342
|
-
display: flex;
|
|
343
|
-
align-items: center;
|
|
344
|
-
gap: 8px;
|
|
345
|
-
flex-wrap: wrap;
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
.subagent-btn {
|
|
349
|
-
background: var(--bg-elev2);
|
|
350
|
-
border: 1px solid var(--border);
|
|
351
|
-
color: var(--text);
|
|
352
|
-
font-size: 12px;
|
|
353
|
-
font-weight: 500;
|
|
354
|
-
padding: 5px 10px;
|
|
355
|
-
border-radius: 6px;
|
|
356
|
-
cursor: pointer;
|
|
357
|
-
display: inline-flex;
|
|
358
|
-
align-items: center;
|
|
359
|
-
gap: 6px;
|
|
360
|
-
transition: all 0.15s;
|
|
361
|
-
white-space: nowrap;
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
.subagent-btn:hover {
|
|
365
|
-
border-color: var(--text-faint);
|
|
366
|
-
color: var(--text);
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
.subagent-btn.primary {
|
|
370
|
-
background: var(--accent);
|
|
371
|
-
border-color: var(--accent);
|
|
372
|
-
color: var(--accent-contrast);
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
.subagent-btn.primary:hover {
|
|
376
|
-
opacity: 0.92;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
.subagent-btn.copied {
|
|
380
|
-
color: var(--green);
|
|
381
|
-
border-color: var(--green);
|
|
382
|
-
}
|
|
383
|
-
`}),(0,$.jsxs)(`div`,{className:`subagent-mode-switcher`,children:[(0,$.jsxs)(`div`,{className:`subagent-mode-tabs`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`subagent-mode-btn${h===`spawn`?` active`:``}`,onClick:()=>g(`spawn`),children:[`🚀 `,o(`subagentInspector.tabMission`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`subagent-mode-btn${h===`result`?` active`:``}`,onClick:()=>g(`result`),children:[`📋 `,o(`subagentInspector.tabResult`)]})]}),(0,$.jsxs)(`div`,{className:`subagent-conv-badge`,children:[(0,$.jsxs)(`span`,{children:[o(`subagentInspector.subagentLabel`),`:`]}),(0,$.jsx)(`strong`,{children:y||o(`subagentInspector.unbound`)})]})]}),(0,$.jsxs)(`div`,{className:`subagent-hud-grid`,children:[(0,$.jsxs)(`div`,{className:`subagent-hud-card accent`,children:[(0,$.jsx)(`span`,{className:`subagent-hud-label`,children:o(`subagentInspector.roleTypeLabel`)}),(0,$.jsxs)(`span`,{className:`subagent-hud-val`,children:[(0,$.jsx)(`span`,{children:_.icon}),(0,$.jsx)(`span`,{children:s.type||`general`})]}),(0,$.jsx)(`span`,{className:`subagent-hud-sub`,children:s.template?o(`subagentInspector.templatePrefix`,{template:s.template}):_.desc})]}),(0,$.jsxs)(`div`,{className:`subagent-hud-card green`,children:[(0,$.jsx)(`span`,{className:`subagent-hud-label`,children:o(`subagentInspector.modelLabel`)}),(0,$.jsx)(`span`,{className:`subagent-hud-val`,children:s.model||o(`subagentInspector.modelInherit`)}),(0,$.jsx)(`span`,{className:`subagent-hud-sub`,children:s.thinking?o(`subagentInspector.thinkingValue`,{thinking:s.thinking}):o(`subagentInspector.thinkingDefault`)})]}),(0,$.jsxs)(`div`,{className:`subagent-hud-card blue`,children:[(0,$.jsx)(`span`,{className:`subagent-hud-label`,children:o(`subagentInspector.isolationLabel`)}),(0,$.jsxs)(`span`,{className:`subagent-hud-val`,children:[(0,$.jsx)(ot,{}),(0,$.jsx)(`span`,{children:s.worktree?.branch?s.worktree.branch.replace(/^agent\//,``):s.isolation===`worktree`?o(`subagentInspector.isolationWorktree`):o(`subagentInspector.isolationShared`)})]}),(0,$.jsx)(`span`,{className:`subagent-hud-sub`,children:s.worktree?.uncommittedCount===void 0?s.isolation===`worktree`?o(`subagentInspector.worktreeDedicated`):o(`subagentInspector.noGitBranch`):o(`subagentInspector.filesCount`,{count:s.worktree.uncommittedCount})})]}),(0,$.jsxs)(`div`,{className:`subagent-hud-card amber`,children:[(0,$.jsx)(`span`,{className:`subagent-hud-label`,children:o(`subagentInspector.metricsLabel`)}),(0,$.jsx)(`span`,{className:`subagent-hud-val`,children:i===`run`?o(`subagentInspector.running`):r||o(`subagentInspector.completed`)}),(0,$.jsx)(`span`,{className:`subagent-hud-sub`,children:s.messageCount===void 0?`action: ${s.action}`:o(`subagentInspector.turnsCount`,{count:s.messageCount})})]})]}),h===`spawn`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`subagent-section-card`,children:[(0,$.jsxs)(`div`,{className:`subagent-section-header`,children:[(0,$.jsxs)(`span`,{className:`subagent-section-title`,children:[(0,$.jsx)(ne,{style:{color:`var(--accent)`}}),(0,$.jsx)(`span`,{children:o(`subagentInspector.missionHeader`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`subagent-btn${c.copied?` copied`:``}`,onClick:()=>void c.copy(s.prompt||``),children:[c.copied?(0,$.jsx)(z,{}):(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{children:c.copied?o(`copied`):o(`subagentInspector.copyPrompt`)})]})]}),(0,$.jsx)(`div`,{className:`subagent-section-body`,children:(0,$.jsx)(`div`,{className:`subagent-prompt-box`,children:s.prompt||o(`subagentInspector.promptEmpty`)})})]}),(0,$.jsxs)(`div`,{className:`subagent-section-card`,children:[(0,$.jsxs)(`div`,{className:`subagent-section-header clickable`,onClick:()=>d(e=>!e),children:[(0,$.jsxs)(`span`,{className:`subagent-section-title`,children:[(0,$.jsx)(wt,{style:{color:`var(--blue)`}}),(0,$.jsx)(`span`,{children:o(`subagentInspector.envHeader`)})]}),(0,$.jsx)(`span`,{style:{fontSize:11,color:`var(--text-dim)`},children:o(u?`subagentInspector.collapse`:`subagentInspector.expand`)})]}),u&&(0,$.jsx)(`div`,{className:`subagent-section-body`,children:(0,$.jsx)(`table`,{className:`subagent-spec-table`,children:(0,$.jsxs)(`tbody`,{children:[(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`label`,children:o(`subagentInspector.cwdLabel`)}),(0,$.jsx)(`td`,{className:`val`,children:s.cwd||o(`subagentInspector.cwdInherited`)})]}),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`label`,children:o(`subagentInspector.isolationStrategyLabel`)}),(0,$.jsx)(`td`,{className:`val`,children:s.isolation===`worktree`?o(`subagentInspector.worktreeIsolationValue`):o(`subagentInspector.isolationShared`)})]}),s.worktree?.path&&(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`label`,children:o(`subagentInspector.worktreePathLabel`)}),(0,$.jsx)(`td`,{className:`val`,children:s.worktree.path})]}),(0,$.jsxs)(`tr`,{children:[(0,$.jsx)(`td`,{className:`label`,children:o(`subagentInspector.notifyLabel`)}),(0,$.jsx)(`td`,{className:`val`,children:s.notifyOnDone===!1?o(`subagentInspector.notifyDisabled`):o(`subagentInspector.notifyAuto`)})]})]})})})]})]}),h===`result`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`subagent-section-card`,children:[(0,$.jsxs)(`div`,{className:`subagent-section-header`,children:[(0,$.jsxs)(`span`,{className:`subagent-section-title`,children:[(0,$.jsx)(Xe,{style:{color:`var(--green)`}}),(0,$.jsx)(`span`,{children:o(`subagentInspector.resultHeader`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`subagent-btn${l.copied?` copied`:``}`,onClick:()=>void l.copy(v),children:[l.copied?(0,$.jsx)(z,{}):(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{children:l.copied?o(`copied`):o(`subagentInspector.copyOutput`)})]})]}),(0,$.jsx)(`div`,{className:`subagent-section-body`,children:(0,$.jsx)(`div`,{className:`subagent-output-box`,children:v||o(i===`run`?`subagentInspector.outputRunning`:`subagentInspector.outputEmpty`)})})]}),s.prompt&&(0,$.jsxs)(`div`,{className:`subagent-section-card`,children:[(0,$.jsxs)(`div`,{className:`subagent-section-header clickable`,onClick:()=>p(e=>!e),children:[(0,$.jsxs)(`span`,{className:`subagent-section-title`,children:[(0,$.jsx)(ne,{style:{color:`var(--text-dim)`}}),(0,$.jsx)(`span`,{children:o(`subagentInspector.associatedPromptHeader`)})]}),(0,$.jsx)(`span`,{style:{fontSize:11,color:`var(--text-dim)`},children:o(f?`subagentInspector.collapse`:`subagentInspector.expand`)})]}),f&&(0,$.jsx)(`div`,{className:`subagent-section-body`,children:(0,$.jsx)(`div`,{className:`subagent-prompt-box`,style:{maxHeight:180},children:s.prompt})})]})]}),(0,$.jsxs)(`div`,{className:`subagent-action-dock`,children:[(0,$.jsxs)(`div`,{className:`subagent-dock-tip`,children:[(0,$.jsx)(`span`,{children:`💡`}),(0,$.jsx)(`span`,{children:o(y?`subagentInspector.dockTipBound`:`subagentInspector.dockTipUnbound`)})]}),(0,$.jsx)(`div`,{className:`subagent-dock-btns`,children:y&&(0,$.jsxs)(`button`,{type:`button`,className:`subagent-btn primary`,onClick:()=>{y&&(zt(),window.dispatchEvent(new CustomEvent(`pi-web-ui:switch-conversation`,{detail:y})))},children:[(0,$.jsx)(K,{}),(0,$.jsx)(`span`,{children:o(`subagentInspector.switchConversation`)})]})})]})]})}function e4({state:e,isMaximized:t,onToggleMaximize:n,toolIcon:r}){let a=X(),[o,s]=(0,Q.useState)(`preview`),c=Gn({duration:1200}),{name:l=`tool`,args:u=``,details:d,output:f=``,isError:p=!1,duration:m,images:h}=e,g=eh({name:l,argumentsText:u,hints:e.hints||th(u)}),_=g?`${l}(${g.text})`:l?`${l}()`:a(`toolInspectorTitle`),{formattedDetails:v,detailsKeysCount:y}=G2(d),b=W2(e,a),x=l===`present_files`,S=(0,Q.useMemo)(()=>x&&u?Hp(u):null,[x,u]),C=l===`delegate_task`,w=(0,Q.useMemo)(()=>C&&u?ah(u):{},[C,u]),T=l===`codemode`,E=(0,Q.useMemo)(()=>T&&u?mh(u):null,[T,u]),D=l===`ask_user_question`,O=(0,Q.useMemo)(()=>D&&u?vh(u):null,[D,u]),k=l===`conversation`,A=!!(x&&S||C&&Object.keys(w).length>0||T&&E?.code||D&&O||k);return(0,$.jsx)(`div`,{className:`tool-inspector-backdrop pi-we-inspector-backdrop open${t?` is-maximized`:``}`,onClick:e=>{e.target===e.currentTarget&&zt()},children:(0,$.jsxs)(`div`,{className:`tool-inspector-dialog pi-we-inspector-dialog is-file-diff${t?` is-maximized`:``}`,role:`dialog`,"aria-modal":`true`,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-header`,onDoubleClick:n,children:[(0,$.jsxs)(`div`,{className:`file-diff-inspector-title-group`,children:[(0,$.jsx)(`span`,{className:`file-diff-file-icon`,children:r}),(0,$.jsx)(`span`,{className:`file-diff-path`,title:_,children:_}),(0,$.jsxs)(`span`,{className:`file-diff-status-pill ${b.badgeClass}`,children:[b.statusIcon,` `,b.badgeText]})]}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-actions`,children:[A&&(0,$.jsxs)(`div`,{className:`btn-group-diff`,role:`group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${o===`preview`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`preview`)},children:a(`toolInspectorTabView`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn-tag${o===`raw`?` active`:``}`,onClick:e=>{e.stopPropagation(),s(`raw`)},children:a(`diffViewRaw`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn${c.copied?` copied`:``}`,title:c.copied?a(`toolInspectorCopied`):a(`toolInspectorCopyAll`),onClick:e=>{e.stopPropagation(),c.copy(`[Arguments]\n${u}\n\n[Output]\n${f}`)},children:c.copied?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:a(t?`diffRestoreScreen`:`diffFullscreen`),onClick:e=>{e.stopPropagation(),n()},children:t?(0,$.jsx)(Mt,{}):(0,$.jsx)(F,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-action-btn`,title:`${a(`close`)} (ESC)`,onClick:e=>{e.stopPropagation(),zt()},children:(0,$.jsx)(Ct,{})})]})]}),(0,$.jsx)(`div`,{className:`file-diff-inspector-body`,children:o===`raw`?(0,$.jsx)(K2,{args:u,formattedDetails:v,detailsKeysCount:y}):(0,$.jsxs)(`div`,{className:`generic-inspector-viewport`,children:[x&&S&&(0,$.jsx)(pm,{args:S,details:d,toolCallId:e.toolCallId??``,resultTimestamp:e.resultTimestamp}),C&&(0,$.jsx)(l_,{args:w}),T&&E?.code&&(0,$.jsx)(o_,{code:E.code,options:E.options,details:d,output:f}),D&&O&&(0,$.jsx)(Fh,{questions:O.questions,details:d,output:f,isError:p,waiting:e.statusClass===`run`}),k&&(0,$.jsx)($2,{name:l,args:u,details:d,output:f,duration:m,statusClass:e.statusClass,isError:p}),h&&h.length>0&&(0,$.jsxs)(`div`,{className:`tool-inspector-section pi-we-inspector-section`,style:{padding:`8px 14px`},children:[(0,$.jsx)(`div`,{className:`tool-inspector-label-row`,children:(0,$.jsxs)(`span`,{className:`tool-inspector-label pi-we-inspector-label`,children:[a(`toolInspectorImages`),` (`,h.length,`)`]})}),(0,$.jsx)(`div`,{className:`tool-inspector-images`,children:h.map((e,t)=>{let n=e.startsWith(`/`)?He(e):e;return(0,$.jsx)(`button`,{type:`button`,className:`image-preview-trigger`,title:a(`toolImageZoom`),onClick:()=>Tn({src:n,alt:`output image ${t+1}`}),children:(0,$.jsx)(`img`,{crossOrigin:i(n),src:n,alt:`output image ${t+1}`,loading:`lazy`})},t)})})]}),!A&&(0,$.jsx)(`pre`,{className:`generic-output-pre`,children:f||(e.statusClass===`run`?a(`toolInspectorRunningOutput`):a(`toolInspectorEmptyOutput`))})]})}),(0,$.jsxs)(`div`,{className:`file-diff-inspector-footer`,children:[(0,$.jsxs)(`div`,{className:`file-diff-footer-status ${b.badgeClass}`,children:[(0,$.jsx)(`span`,{className:`file-diff-status-icon${b.isRunning?` spin`:``}`,children:b.statusIcon}),(0,$.jsx)(`span`,{className:`file-diff-status-text`,children:b.isRunning?b.footerText:f?a(`toolInspectorOutputStats`,{lines:f.split(`
|
|
384
|
-
`).length,chars:f.length}):b.footerText})]}),(0,$.jsxs)(`div`,{className:`file-diff-footer-meta`,children:[(0,$.jsx)(U2,{state:e}),y>0&&(0,$.jsxs)(`span`,{children:[`details: `,y,` keys`]}),y>0&&(0,$.jsx)(`span`,{className:`meta-sep`,children:`|`}),(0,$.jsx)(`button`,{type:`button`,className:`file-diff-footer-link`,onClick:e=>{e.stopPropagation(),s(o===`raw`?`preview`:`raw`)},children:a(o===`raw`?`toolInspectorBackToView`:`toolInspectorViewRawArgsDetails`)})]})]})]})})}var t4={bash:(0,$.jsx)(Xe,{}),skill:(0,$.jsx)(r,{}),read:(0,$.jsx)(vt,{}),write:(0,$.jsx)(dt,{}),edit:(0,$.jsx)(et,{}),grep:(0,$.jsx)(mt,{}),find:(0,$.jsx)(T,{}),codemode:(0,$.jsx)(ne,{}),eval:(0,$.jsx)(Y,{}),lsp:(0,$.jsx)(Y,{}),tool_search:(0,$.jsx)(mt,{}),conversation:(0,$.jsx)(K,{}),delegate_task:(0,$.jsx)(wt,{}),present_files:(0,$.jsx)(E,{}),browser_search:(0,$.jsx)(mt,{}),browser_use:(0,$.jsx)(Le,{}),ask_user_question:(0,$.jsx)(xt,{}),conversation_read:(0,$.jsx)(C,{})};function n4(){let e=Vt();return!e||typeof document>`u`?null:(0,$.jsx)(r4,{state:e})}function r4({state:e}){let t=Rt();return(0,Er.createPortal)((0,$.jsx)(`div`,{className:`overlay-layer`,style:{zIndex:t},children:(0,$.jsx)(i4,{state:e})}),document.body)}function i4({state:e}){let[t,n]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&(e.stopPropagation(),zt())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let r=()=>n(e=>!e);if(e.isThinking)return(0,$.jsx)(q2,{state:e,isMaximized:t,onToggleMaximize:r});let i=e.name||``;return i===`edit`||i===`write`||i===`patch`?(0,$.jsx)(X2,{state:e,isMaximized:t,onToggleMaximize:r}):Qm(i)?(0,$.jsx)(J2,{state:e,isMaximized:t,onToggleMaximize:r}):i===`read`||i===`ls`||i===`grep`||i===`find`||i===`tool_search`?(0,$.jsx)(Y2,{state:e,isMaximized:t,onToggleMaximize:r,toolIcon:t4[i]??(0,$.jsx)(vt,{})}):(0,$.jsx)(e4,{state:e,isMaximized:t,onToggleMaximize:r,toolIcon:t4[i]??(0,$.jsx)(E,{})})}var a4=`files`,o4=`host:bottom-terminal`,s4=e=>e===`right`?780:520,c4=e=>`pi-web-ui:${e}-panel-width`;function l4(e){try{let t=Number(localStorage.getItem(c4(e)));return Number.isFinite(t)&&t>=180&&t<=s4(e)?t:240}catch{return 240}}var u4=e=>`pi-web-ui:${e}-panel-collapsed`;function d4(e,t){try{localStorage.setItem(u4(e),t?`1`:`0`)}catch{}}function f4(e){try{return localStorage.getItem(u4(e))===`1`}catch{return!1}}function p4(){try{return localStorage.getItem(`pi-web-ui:rightpanel:tab`)??`files`}catch{return a4}}function m4(e,t,n){return e.textKey?n(e.textKey,e.textVars):!Ye(t)&&e.textEn?e.textEn:e.text}var h4=`pi-web-ui:plugin-path-grants`,g4=e=>e?`${h4}:${e}`:h4;function _4(e){if(e===null)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}catch{return[]}}function v4(e){try{let t=g4(e);if(localStorage.getItem(t)!==null)return _4(localStorage.getItem(t));if(!e)return[];let n=_4(localStorage.getItem(h4));return localStorage.setItem(t,JSON.stringify(n)),n}catch{return[]}}function y4(e,t){try{let n=[...new Set([...v4(t),e])];localStorage.setItem(g4(t),JSON.stringify(n))}catch{}}var b4=(0,Q.lazy)(()=>Rs(()=>import(`./FilePreview-0IDddE5F.js`).then(e=>({default:e.FilePreview})),__vite__mapDeps([6,2,3,7,8,9]),import.meta.url)),x4=(0,Q.lazy)(()=>Rs(()=>import(`./PiSetupModal-Dd0w2Koi.js`).then(e=>({default:e.PiSetupModal})),__vite__mapDeps([10,2,3,7,9,11,12,13,14]),import.meta.url)),S4=(0,Q.lazy)(()=>Rs(()=>import(`./ModelConfigModal-i3m9glTy.js`).then(e=>({default:e.ModelConfigModal})),__vite__mapDeps([15,2,7,3,9,14]),import.meta.url)),C4=(0,Q.lazy)(()=>Rs(()=>import(`./SettingsModal-6jgsnLF0.js`).then(e=>e.t).then(e=>({default:e.SettingsModal})),__vite__mapDeps([16,2,3,7,9,11,12,13,17,18,19,20]),import.meta.url)),w4=(0,Q.lazy)(()=>Rs(()=>import(`./ThemeMarketModal-CGaoF3NZ.js`).then(e=>({default:e.ThemeMarketModal})),__vite__mapDeps([21,7,2,3,8,22,12,13,9,16,11,17,18,19,20,23]),import.meta.url)),T4=(0,Q.lazy)(()=>Rs(()=>import(`./BgTasksModal-wL4p27CE.js`).then(e=>({default:e.BgTasksModal})),__vite__mapDeps([24,2,3,7,25,13,9]),import.meta.url)),E4=(0,Q.lazy)(()=>Rs(()=>import(`./TuiOverlayModal-Bj6jyAvr.js`).then(e=>({default:e.TuiOverlayModal})),__vite__mapDeps([26,2,3,27,28,7,9,12,13]),import.meta.url)),D4=(0,Q.lazy)(()=>Rs(()=>import(`./GlobalSearchModal-BaXs1zRG.js`).then(e=>({default:e.GlobalSearchModal})),__vite__mapDeps([29,2,3,7,30,13,31,11,12,9,18,32]),import.meta.url)),O4=(0,Q.lazy)(()=>Rs(()=>import(`./DeviceGroups-DUq2YZ8O.js`).then(e=>({default:e.DeviceGroupCreateDialog})),__vite__mapDeps([33,2,3,17,7,34,13]),import.meta.url));function k4({chat:e,send:t,terminal:n,sharedReadOnly:r,isNativeCliConversation:i,setupDismissed:a,dismissSetup:o,manageModelsOpen:s,setManageModelsOpen:c,settingsOpen:l,setSettingsOpen:u,settingsInitialSection:d,setSettingsInitialSection:f,onOpenIconEdit:p,onOpenManageModels:m,openTerminalDrawer:h,themeMarketOpen:g,setThemeMarketOpen:_,bgTasksOpen:v,setBgTasksOpen:y,globalSearchOpen:b,setGlobalSearchOpen:x,setSearchJump:S,deviceGroupCreateOpen:C,setDeviceGroupCreateOpen:w,sandboxModalMode:T,setSandboxModalMode:E,previewFile:D,previewFiles:O,previewIndex:k,setPreviewIndex:A,setPreviewFiles:j,pluginFile:M,setPluginFile:N,lightboxImage:P,setLightboxImage:F,openFile:I,attach:L,uiSlots:R,uiFilePreviewToolbar:z,onUiAction:B,openModalEntry:V,openModalPluginId:H,pluginViews:ee,setOpenModalId:U,pluginDirPicker:W,setPluginDirPicker:G,pluginModelPicker:K,setPluginModelPicker:q,pendingPermRequest:te,answerPermRequest:ne,pendingPathRequest:re,answerPathRequest:J,pluginPathConfirm:ie,pluginPathConfirmRef:ae,setPluginPathConfirm:oe,permOverlayZIndex:se,setRightCollapsed:Y,setDrawer:ce,sound:le,setSound:ue,tts:de,setTts:fe,themes:me,theme:he,switchTheme:ge,reloadThemes:_e}){let ve=X(),ye=mi(e.state?.messages,e.state?.conversationId);return(0,$.jsxs)($.Fragment,{children:[D&&O&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(b4,{file:D,files:O,activeIndex:k,onSelectFile:A,composerSessionId:e.state?.sessionId,content:e.fileContent,onAddLines:(e,t,n,r)=>L(e,t,`lines`,!1,{start:n,end:r}),onAttach:(e,t,n)=>L(e,t,n),onClose:()=>j(null),uiFilePreviewToolbar:z,onUiAction:B})}),M&&(0,$.jsx)(Xy,{file:M.file,plugin:M.plugin,declaration:M.declaration,epoch:e.pluginsEpoch,send:t,onClose:()=>N(null),onFallback:()=>{N(null),j([M.file]),A(0)}}),P&&(0,$.jsx)(Ry,{...P,composerSessionId:e.state?.sessionId,onClose:()=>F(null)}),e.ready&&e.state&&e.state.piConfigured===!1&&!i&&!a&&!s&&!an()&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(x4,{piConfigured:e.state.piConfigured,piAgentInstalled:e.state.piAgentInstalled,providers:e.providers,providerOAuthFlows:e.providerOAuthFlows,providerOAuthResults:e.providerOAuthResults,installResult:e.installResult,onClose:o})}),s&&!r&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(S4,{providers:e.modelsConfig,providerStatus:e.providers,providerKeys:e.providerKeys,providerOAuthFlows:e.providerOAuthFlows,providerOAuthResults:e.providerOAuthResults,fetchModelsResult:e.fetchModelsResult,testModelConnectionResult:e.testModelConnectionResult,enrichModelsResult:e.enrichModelsResult,enrichModelsProgress:e.enrichModelsProgress,refreshBuiltinResult:e.refreshBuiltinResult,refreshProviderResult:e.refreshProviderResult,appendBuiltinResult:e.appendBuiltinResult,cloneProviderResult:e.cloneProviderResult,defaultModel:e.defaultModel,onClose:()=>c(!1)})}),l&&!r&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(C4,{chat:e,terminal:n,initialSection:d,onSwitchToTerminal:()=>{u(!1),h()},onClose:()=>u(!1),onOpenIconEdit:p,onOpenManageModels:m,sound:le,onSoundChange:ue,tts:de,onTtsChange:fe,themes:me,currentTheme:he,onThemeChange:ge,onReloadThemes:_e})}),g&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(w4,{themes:me,currentTheme:he,onThemeChange:ge,onReloadThemes:_e,onClose:()=>_(!1)})}),v&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(T4,{servers:e.bgServers,tasks:ye.tasks,onClearFinished:ye.clearFinished,onClearTask:ye.clearTask,plugins:e.plugins,epoch:e.pluginsEpoch,send:t,onUiAction:B,autoCleanupMin:e.settings?.bgAutoCleanupMin??0,onClose:()=>y(!1)})}),(0,$.jsx)(z2,{}),(0,$.jsx)(n4,{}),(0,$.jsx)(T2,{}),e.tuiOverlay&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(E4,{overlay:e.tuiOverlay})}),V&&(0,$.jsx)(Qy,{entry:V,pluginView:H?ee.find(e=>e.info.id===H):void 0,onUiAction:(e,t)=>{B(e,t),U(null)},onClose:()=>U(null)}),(0,$.jsx)(Ai,{active:b,children:(0,$.jsx)(D4,{open:b,projects:e.projects,fileSearch:e.fileSearch,sessionSearch:e.sessionSearch,uiContextSearch:R[`contextmenu.search`],quickAskReferenceMenus:e.settings?.quickAskReferenceMenus!==!1,onClose:()=>x(!1),onSwitchSession:(e,n)=>{t({type:`switch_session`,path:e});let r=n&&n[0];S(r?{path:e,role:r.role,timestamp:r.timestamp}:null)},onSwitchProject:e=>{t({type:`set_cwd`,path:e})},onPreviewFile:(e,t)=>{I(e,t)},onOpenFolder:e=>{x(!1),Y(e=>{if(e)try{localStorage.setItem(u4(`right`),`0`)}catch{}return!1}),ce(null),window.setTimeout(()=>{window.dispatchEvent(new CustomEvent(`pi:open-folder`,{detail:{path:e}}))},0)}})}),W&&(0,$.jsx)(ea,{currentCwd:W.initialPath||e.state?.cwd||``,onClose:()=>{W.resolve({ok:!1,canceled:!0}),G(null)},onSelectDirectory:e=>{W.resolve({ok:!0,path:e}),G(null)},onCreateProject:e=>{t({type:`make_dir`,path:e}),W.resolve({ok:!0,path:e}),G(null)},mode:`project`,className:`project-picker`,backdropClassName:`project-picker-backdrop`,role:`dialog`,ariaLabel:ve(`projectPickerTitle`)}),K&&(0,$.jsx)(zy,{currentModelId:K.currentModelId,models:e.models,modelsLoading:e.modelsLoading,providerKeys:e.providerKeys,providers:e.providers,onManageModels:()=>c(!0),defaultModel:e.defaultModel,onClose:()=>{K.resolve({ok:!1,canceled:!0}),q(null)},onSelect:(e,t)=>{K.resolve({ok:!0,modelId:e,name:t?.name,provider:t?.provider}),q(null)}}),C&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(O4,{onClose:()=>w(!1)})}),(te||re||ie)&&(0,Er.createPortal)((0,$.jsxs)(`div`,{className:`modal-backdrop perm-modal-backdrop`,style:{zIndex:se},children:[te&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:ve(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:ve(`pluginPermTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:ve(`cancel`),onClick:()=>ne(te.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[te.family===`net`?ve(`pluginPermBodyNet`).replace(`{plugin}`,te.pluginId).replace(`{hosts}`,(te.hosts??[]).join(`, `)):ve(`pluginPermBodyLlm`).replace(`{plugin}`,te.pluginId).replace(`{models}`,(te.models??[]).length>0?` ${(te.models??[]).join(`, `)}`:``),te.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:te.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>ne(te.id,!1),children:ve(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>ne(te.id,!0),children:ve(`pluginPermOnce`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>ne(te.id,!0,!0),children:ve(`pluginPermAlways`)})]})]})]}),re&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:ve(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:ve(`pluginGrantRequestTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:ve(`cancel`),onClick:()=>J(re.id,!1),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[ve(`pluginGrantRequestBody`).replace(`{plugin}`,re.pluginId).replace(`{path}`,re.path),re.reason&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:re.reason}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>J(re.id,!1),children:ve(`pluginGrantDeny`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>J(re.id,!0),children:ve(`pluginGrantAllow`)})]})]})]}),ie&&(0,$.jsxs)(`div`,{className:`dialog-inline perm-dialog-card`,"data-dialog-kind":`confirm`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:ve(`pluginRequest`)}),(0,$.jsx)(`span`,{className:`dialog-title`,children:ve(`pluginSessionGrantTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:ve(`cancel`),onClick:()=>{ae.current=null,ie.resolve(!1),oe(null)},children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-body`,children:[ve(`pluginSessionGrantBody`).replace(`{path}`,ie.path),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{ae.current=null,ie.resolve(!1),oe(null)},children:ve(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{ae.current=null,ie.resolve(!0),oe(null)},children:ve(`ok`)})]})]})]})]}),document.body),!l&&Object.values(e.pluginJobs??{}).some(e=>e.phase!==`done`)&&(0,$.jsxs)(`div`,{className:`active-plugin-jobs-bar`,onClick:()=>{f(`plugins`),u(!0)},title:ve(`pluginJobRunning`),children:[(0,$.jsx)(pe,{className:`spin`}),(0,$.jsxs)(`span`,{className:`active-plugin-jobs-title`,children:[ve(`pluginJobRunning`),`:`,` `,Object.values(e.pluginJobs??{}).filter(e=>e.phase!==`done`).map(e=>e.pluginId).join(`, `)]}),(()=>{let t=Object.values(e.pluginJobs??{}).find(e=>e.phase!==`done`),n=t?.lines[t.lines.length-1];return n?(0,$.jsx)(`span`,{className:`active-plugin-jobs-line`,children:n}):null})()]}),T&&(0,$.jsx)(k2,{mode:T,currentCwd:e.state?.cwd,currentSandbox:e.state?.sandbox,sandboxDiff:e.sandboxDiff,projects:e.projects,send:t,onClose:()=>E(null)}),(0,$.jsx)(_2,{settings:e.settings,clientId:Po(),currentConversation:e.activeConversationId||e.state?.conversationId?{kind:`conversation`,conversationId:e.activeConversationId||e.state.conversationId}:void 0,fallbackModel:e.state?.model?`${e.state.model.provider}/${e.state.model.id}`:void 0}),(0,$.jsx)(ji,{}),(0,$.jsx)(ki,{})]})}function A4(e,t){return t?e.trim()?`${e.replace(/\s+$/,``)}\n${t}`:t:e}function j4(e,t,n){let r=null;return e&&e.text&&e.ts>0&&(r={text:e.text,ts:e.ts}),t&&t.text&&t.ts>(r?.ts??0)&&(r=t),!r||r.ts<=n?null:r}function M4(e){return e.mode===`quote`&&e.quote?`quote:${JSON.stringify([e.quote.sessionId??``,e.quote.messageId,e.quote.role,e.quote.text])}`:e.mode===`terminal`&&e.terminalId?`terminal:${e.terminalId}`:e.key?`key:${e.key}`:e.mode===`conversation`?e.conversationId?`conv:id:${e.conversationId}`:e.sessionPath?`conv:path:${e.sessionPath}`:null:e.path?`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`:null}function N4(e,t){return t?e?{key:t,clear:e!==t}:{key:t,clear:!1}:{key:e,clear:!1}}function P4(e,t){if(t.length===0)return e;if(e.length===0)return[...t];let n=new Set(e.map(M4).filter(e=>e!==null)),r=[...e];for(let e of t){let t=M4(e);if(t!==null){if(n.has(t))continue;n.add(t)}r.push(e)}return r}function F4(e,t,n,r,i=!1){return!e||!e.trim()?!1:!!(t||i)}function I4(e,t){if(!t||!t.trim())return!1;let n=e.trim();return!(!n||n===t.trim())}function L4(e,t,n){switch(n){case`cancel`:return null;case`append`:return A4(e,t);case`overwrite`:return t}}var R4={text:``,attachmentSummary:``},z4=null,B4=null,V4=new Set,H4=new Set;function U4(){for(let e of V4)e()}function W4(e){(R4.text!==e.text||R4.attachmentSummary!==e.attachmentSummary)&&(R4=e,U4())}function G4(e){z4=e}function K4(e){B4=e,U4();for(let e of H4)e()}function q4(){return B4!==null}function J4(e){return H4.add(e),()=>H4.delete(e)}function Y4(){return[R4.text.trim(),R4.attachmentSummary.trim()].filter(Boolean).join(`
|
|
385
|
-
`)}function X4(){z4?.()}function Z4(){return B4!==null}function Q4(){return B4?B4():!1}function $4(e){return V4.add(e),()=>V4.delete(e)}function e3(e){return e?typeof e==`string`?`:${e}`:`:${e.start}-${e.end}`:``}function t3(e,t,n,r){W4(e?{text:``,attachmentSummary:``}:{text:t,attachmentSummary:n.map(e=>e.mode===`quote`?`> ${typeof e.quote==`string`?e.quote:JSON.stringify(e.quote)}`:e.path?`[${r}: ${e.path}${e3(e.lines)}]`:e.name?`[${r}: ${e.name}]`:``).filter(Boolean).join(`
|
|
386
|
-
`)})}function n3(e,t){let{groupDevices:n,text:r,attachments:i,attachmentLabel:a,setText:o,clearDraftAfterConsume:s,onSent:c}=t;e(()=>{t3(n,r,i,a)},[n,r,i,a]),e(()=>{if(!n)return G4(()=>{o(``),s(),c()}),()=>G4(null)},[n,o,s,c])}function r3(e){return/^[@@]/.test(e)}function i3(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function a3(e,t){let n=String(t??``).trim();return!n||!r3(n)?!1:RegExp(`(^|[\\s(("'“‘[【])`+i3(n)+`(?=[\\s,.;:!?,。!?)\\]】」)]|$)`).test(String(e??``))}var o3=new Set;function s3(){for(let e of[...o3])e()}function c3(e){return o3.add(e),()=>{o3.delete(e)}}function l3(e,t){try{let n=localStorage.getItem(e);return n===null?t:n===`1`}catch{return t}}function u3(e,t){try{localStorage.setItem(e,t?`1`:`0`)}catch{}}var d3=`pi-web-ui:goal-refine`,f3=`pi-web-ui:goal-plan`,p3=!1,m3=!1,h3=l3(d3,!1),g3=l3(f3,!1);function _3(){return p3}function v3(){return m3}function y3(){return h3}function b3(){return g3}function x3(e){p3!==e&&(p3=e,s3())}function S3(e){m3!==e&&(m3=e,s3())}function C3(e){h3!==e&&(h3=e,u3(d3,e),s3())}function w3(e){g3!==e&&(g3=e,u3(f3,e),s3())}function T3(){return(0,Q.useSyncExternalStore)(c3,_3,_3)}function E3(){return(0,Q.useSyncExternalStore)(c3,v3,v3)}function D3(){return(0,Q.useSyncExternalStore)(c3,y3,y3)}function O3(){return(0,Q.useSyncExternalStore)(c3,b3,b3)}function k3(e){let t=Number.parseFloat(getComputedStyle(e).lineHeight)||0;return t>0?Math.max(2,t/2):2}var A3=``;function j3(e,t,n=1){return{first:e<=n,last:Math.abs(t-e)<=n}}function M3(e,t){return{first:!e.slice(0,t).includes(`
|
|
387
|
-
`),last:!e.slice(t).includes(`
|
|
388
|
-
`)}}var N3=null;function P3(){if(N3?.isConnected)return N3;let e=document.createElement(`div`);e.setAttribute(`aria-hidden`,`true`),e.setAttribute(`data-caret-mirror`,``);let t=e.style;return t.position=`fixed`,t.top=`0`,t.left=`-99999px`,t.visibility=`hidden`,t.pointerEvents=`none`,t.margin=`0`,t.padding=`0`,t.border=`0`,t.boxSizing=`border-box`,t.overflow=`visible`,document.body.appendChild(e),N3=e,e}function F3(e,t){let n=getComputedStyle(e),r=t.style;r.fontFamily=n.fontFamily,r.fontSize=n.fontSize,r.fontStyle=n.fontStyle,r.fontWeight=n.fontWeight,r.fontVariant=n.fontVariant,r.fontStretch=n.fontStretch,r.lineHeight=n.lineHeight,r.letterSpacing=n.letterSpacing,r.wordSpacing=n.wordSpacing,r.textTransform=n.textTransform,r.textIndent=n.textIndent,r.tabSize=n.tabSize,r.whiteSpace=n.whiteSpace||`pre-wrap`,r.overflowWrap=n.overflowWrap||`break-word`,r.wordBreak=n.wordBreak||`normal`,r.direction=n.direction,r.writingMode=n.writingMode,r.paddingLeft=n.paddingLeft,r.paddingRight=n.paddingRight;let i=e.clientWidth;return i>0?(r.width=`${i}px`,i):0}function I3(e,t){e.textContent=t;let n=document.createElement(`span`);return n.textContent=A3,e.appendChild(n),n.offsetTop}function L3(e){let t=e.value,n=e.selectionStart;if(n!==e.selectionEnd)return{first:!1,last:!1};let r=M3(t,n);if(!r.first&&!r.last||typeof document>`u`||typeof getComputedStyle!=`function`)return r;let i=P3();if(F3(e,i)<=0)return r;let a=I3(i,t.slice(0,n)),o=I3(i,t),s=i.offsetHeight>0;return i.textContent=``,!s&&t!==``?r:j3(a,o,k3(e))}function R3(e,t){let n=[],r=e?.length??0;for(let t=0;t<r;t++){let r=e?.[t];if(!r||r.kind!==`file`)continue;let i=r.getAsFile();i&&n.push(i)}if(n.length===0&&t)for(let e=0;e<t.length;e++){let r=t[e];r&&n.push(r)}return n}var z3=`pi-web-ui:prompt-history`,B3=`pi-web-ui:prompt-history-settings`,V3={maxEntries:100,charLimitEnabled:!1,charLimit:2e3};function H3(e){let t=V3;if(!e||typeof e!=`object`)return{...t};let n=e,r=typeof n.maxEntries==`number`?Math.floor(n.maxEntries):t.maxEntries;(!Number.isFinite(r)||r<1)&&(r=1),r>500&&(r=500);let i=typeof n.charLimit==`number`?Math.floor(n.charLimit):t.charLimit;(!Number.isFinite(i)||i<100)&&(i=100),i>2e4&&(i=2e4);let a=typeof n.charLimitEnabled==`boolean`?n.charLimitEnabled:t.charLimitEnabled;return{maxEntries:r,charLimitEnabled:a,charLimit:i}}function U3(){try{let e=localStorage.getItem(B3);return e?H3(JSON.parse(e)):{...V3}}catch{return{...V3}}}function W3(e){let t=H3(e);try{localStorage.setItem(B3,JSON.stringify(t))}catch{}try{let e=q3();t.charLimitEnabled&&(e=e.map(e=>e.length>t.charLimit?e.slice(0,t.charLimit):e)),e.length>t.maxEntries&&(e=e.slice(e.length-t.maxEntries)),J3(e)}catch{}}function G3(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`string`)continue;let e=n.trim();e&&t.push(e)}return t}function K3(e,t,n=100){let r=t.trim();if(!r||e.length>0&&e[e.length-1]===r)return e;let i=[...e,r];return i.length>n?i.slice(i.length-n):i}function q3(){try{let e=localStorage.getItem(z3);return e?G3(JSON.parse(e)):[]}catch{return[]}}function J3(e){let t=e;for(;t;)try{localStorage.setItem(z3,JSON.stringify(t));return}catch(e){if(!(e instanceof DOMException&&(e.name===`QuotaExceededError`||e.code===22))||t.length<=1)return;t=t.slice(Math.ceil(t.length/2))}}function Y3(e){let t=e.trim();if(!t)return;let n=U3();n.charLimitEnabled&&t.length>n.charLimit&&(t=t.slice(0,n.charLimit));let r=q3(),i=K3(r,t,n.maxEntries);i!==r&&J3(i)}function X3(){try{localStorage.removeItem(z3)}catch{}}function Z3(e){let t=e.query;if(!t||!t(`(pointer: coarse)`)||!t(`(hover: none)`))return!1;let n=e.userAgent??``;return!(/Windows|CrOS/i.test(n)||/Linux/i.test(n)&&!/Android/i.test(n)||/Macintosh/i.test(n)&&(e.maxTouchPoints??0)<=1)}function Q3(){return typeof window>`u`||typeof navigator>`u`||typeof window.matchMedia!=`function`?!1:Z3({query:e=>window.matchMedia(e).matches,userAgent:navigator.userAgent,maxTouchPoints:navigator.maxTouchPoints})}var $3=`pi-web-send-key`;function e6(e,t){return e===`enter`||e===`mod-enter`?e:t?`mod-enter`:`enter`}function t6(e){return e.key===`Enter`?e6(e.pref,!!e.isTouch)===`enter`?e.shiftKey?`newline`:`send`:(e.ctrlKey||e.metaKey)&&!e.shiftKey?`send`:`newline`:`ignore`}function n6(){try{let e=localStorage.getItem($3);return e===`enter`||e===`mod-enter`?e:null}catch{return null}}function r6(e){try{localStorage.setItem($3,e)}catch{}i6=e;for(let e of a6)e()}var i6=null,a6=new Set;function o6(e){return a6.add(e),()=>{a6.delete(e)}}function s6(){return i6===null&&(i6=n6()),i6}function c6(){return(0,Q.useSyncExternalStore)(o6,s6)}function l6(e=Q3()){return e6(c6(),e)}function u6(e,t,n){if(t<=0||!e)return null;let r=null;for(let t of n){let n=[t.mode===`page`||t.mode===`conversation`?t.name:t.path,t.name].filter(e=>typeof e==`string`&&e.trim().length>0);for(let i of n){let n=`@`+i,a=e.endsWith(n+` `);if(a||e.endsWith(n)){let e=n.length;(!r||e>r.tokenLen)&&(r={attachment:t,tokenLen:e,withSpace:a})}}}let i=-1,a=r?.attachment;if(r){let n=t-(r.withSpace?r.tokenLen+1:r.tokenLen);n>0&&/[\w.\-/]/.test(e[n-1])?(i=-1,a=void 0):i=n}if(i<0){let r=/(^|[\s(("'"“‘[【])(@[^\s@,.;:!?,。!?)\]】」]+)(\s?)$/.exec(e);if(r){i=t-r[2].length-r[3].length;let o=e.slice(i,t).trim().replace(/^@/,``),s=o.split(`/`).pop()??o;a=n.find(e=>e.path&&e.path===o)??n.find(e=>e.name&&e.name===o)??n.find(e=>e.mode!==`page`&&e.mode!==`conversation`&&e.name===s)}}return i>=0&&i<t?{tokenStart:i,...a?{attachment:a}:{}}:null}var d6=`pi-web-ui:project-title`,f6={projectName:!0};function p6(e){if(!e||typeof e!=`object`)return{...f6};let t=e;return{projectName:typeof t.projectName==`boolean`?t.projectName:f6.projectName}}function m6(e){return e?e.replace(/[\\/]+$/,``).split(/[\\/]/).pop()??``:``}function h6(e,t){if(!e)return``;if(t?.length){let n=Co(e),r=t.find(e=>Co(e.path)===n)?.name?.trim();if(r)return r}return m6(e)}function g6(){try{let e=localStorage.getItem(d6);return e?p6(JSON.parse(e)):{...f6}}catch{return{...f6}}}function _6(e){let t=p6(e);try{localStorage.setItem(d6,JSON.stringify(t))}catch{}v6=t;for(let e of y6)e()}var v6=null,y6=new Set;function b6(e){return y6.add(e),()=>{y6.delete(e)}}function x6(){return v6||=g6(),v6.projectName}function S6(){return(0,Q.useSyncExternalStore)(b6,x6)}function C6(e,t=0,n=Date.now()){return!!(e.isComposing||e.keyCode===229||t>0&&n-t<50)}function w6(){let e=(0,Q.useRef)(0);return{onCompositionEnd:()=>{e.current=Date.now()},isImeKey:t=>C6(t,e.current)}}var T6=[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],E6={off:0,minimal:1024,low:2048,medium:8192,high:16384,xhigh:32e3,max:64e3},D6=[{value:``,labelKey:`thinkingFormat.auto`},{value:`openai`,labelKey:`thinkingFormat.openai`},{value:`qwen`,labelKey:`thinkingFormat.qwen`},{value:`deepseek`,labelKey:`thinkingFormat.deepseek`},{value:`openrouter`,labelKey:`thinkingFormat.openrouter`},{value:`zai`,labelKey:`thinkingFormat.zai`},{value:`chat-template`,labelKey:`thinkingFormat.chatTemplate`}],O6=[{id:`claude-budget`,nameKey:`thinkingPreset.claudeBudget.name`,descKey:`thinkingPreset.claudeBudget.desc`,type:`budget`,map:{off:`off`,minimal:`1024`,low:`2048`,medium:`8192`,high:`16384`,xhigh:`32000`,max:`64000`}},{id:`openai-effort`,nameKey:`thinkingPreset.openaiEffort.name`,descKey:`thinkingPreset.openaiEffort.desc`,type:`effort`,thinkingFormat:`openai`,map:{off:null,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:null,max:null}},{id:`qwen-thinking`,nameKey:`thinkingPreset.qwenThinking.name`,descKey:`thinkingPreset.qwenThinking.desc`,type:`effort`,thinkingFormat:`qwen`,map:{off:`off`,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:null,max:null}},{id:`deepseek-compat`,nameKey:`thinkingPreset.deepseekCompat.name`,descKey:`thinkingPreset.deepseekCompat.desc`,type:`effort`,thinkingFormat:`deepseek`,map:{off:null,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:null,max:null}},{id:`openrouter-effort`,nameKey:`thinkingPreset.openrouterEffort.name`,descKey:`thinkingPreset.openrouterEffort.desc`,type:`effort`,thinkingFormat:`openrouter`,map:{off:`none`,minimal:null,low:`low`,medium:`medium`,high:`high`,xhigh:null,max:null}},{id:`gemma4-chat-template`,nameKey:`thinkingPreset.gemma4ChatTemplate.name`,descKey:`thinkingPreset.gemma4ChatTemplate.desc`,type:`effort`,thinkingFormat:`chat-template`,chatTemplateKwargs:{enable_thinking:{$var:`thinking.enabled`},reasoning_effort:{$var:`thinking.effort`,omitWhenOff:!0},preserve_thinking:!0},customExtraBody:JSON.stringify({temperature:.8,top_k:64,top_p:.95},null,2),map:{off:`none`,low:`low`,medium:`medium`,high:`high`}},{id:`gemini-budget`,nameKey:`thinkingPreset.geminiBudget.name`,descKey:`thinkingPreset.geminiBudget.desc`,type:`budget`,map:{off:`0`,minimal:`1024`,low:`2048`,medium:`8192`,high:`16384`,xhigh:`24576`,max:`32768`}},{id:`full-open`,nameKey:`thinkingPreset.fullOpen.name`,descKey:`thinkingPreset.fullOpen.desc`,type:`full`,map:{off:`off`,minimal:`minimal`,low:`low`,medium:`medium`,high:`high`,xhigh:`xhigh`,max:`max`}},{id:`fixed-deepseek`,nameKey:`thinkingPreset.fixedDeepseek.name`,descKey:`thinkingPreset.fixedDeepseek.desc`,type:`fixed`,map:{off:null,minimal:null,low:null,medium:null,high:null,xhigh:null,max:null}}];function k6(e,t,n,r){if(e===`off`)return t;if(n&&/^\d+$/.test(String(n).trim())){let e=Number(n);return`${t} (${e>=1024?`${Math.round(e/1024)}K`:`${e}`} tokens)`}if(r&&e in E6){let n=E6[e];if(n&&n>0)return`${t} (${n>=1024?`${Math.round(n/1024)}K`:`${n}`} tokens)`}return t}var A6=(0,Q.memo)(function({state:e,models:t,modelsLoading:n,onManageModels:r,providerKeys:i={},providers:a,defaultModel:o,compact:s=!1,only:c,onSelectModel:l,onSelectThinking:u,direction:d=`up`}){let f=X(),p=e?.model,m=p?p.id.startsWith(`${p.provider}/`)?p.id:`${p.provider}/${p.id}`:null,[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(!1),y=(0,Q.useRef)(null),b=(0,Q.useRef)(null),[x,S]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!h){S(null);return}if(t.length===0)return;let e=requestAnimationFrame(()=>{let e=b.current;e&&S(e.offsetWidth)});return()=>cancelAnimationFrame(e)},[h,t.length]);let[C,w]=(0,Q.useState)(!1),T=(p?.id??``).toLowerCase(),E=T.includes(`claude`)||T.includes(`gemini`)||T.includes(`sonnet`)||p?.provider===`anthropic`||p?.provider===`google`,D=T.includes(`r1`)||T.includes(`reasoner`)||T.includes(`qwq`),O=e?.availableThinkingLevels&&e.availableThinkingLevels.length>0?new Set(e.availableThinkingLevels):null,k=T6.map(e=>({value:e,label:k6(e,f(`thinking.${e}`),void 0,E),supported:!O||O.has(e)})),[A,j]=(0,Q.useState)(``),[M,N]=(0,Q.useState)(null),P=()=>{let e=parseInt(A.trim(),10);if(!Number.isFinite(e)||e<=0)return;N(e);let t=[{lvl:`minimal`,budget:1024},{lvl:`low`,budget:2048},{lvl:`medium`,budget:8192},{lvl:`high`,budget:16384},{lvl:`xhigh`,budget:32e3},{lvl:`max`,budget:64e3}].filter(e=>!O||O.has(e.lvl)),n=t[0]?.lvl??`medium`,r=1/0;for(let i of t){let t=Math.abs(i.budget-e);t<r&&(r=t,n=i.lvl)}u?u(n):Z({type:`set_thinking`,level:n}),v(!1)},F=e=>M&&e!==`off`?`${f(`thinkingCustomized`)} (${M.toLocaleString()} tokens)`:k.find(t=>t.value===e)?.label??e,I=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{h||(I.current=!1)},[h]),(0,Q.useEffect)(()=>{w(!1)},[t]),(0,Q.useEffect)(()=>{h&&(y.current?.querySelector(`.dd-item.active`))?.scrollIntoView({block:`nearest`})},[h,m,t.length]);let L=(0,$.jsx)(df,{models:t,modelsLoading:n,providerKeys:i,providers:a,defaultModel:o,currentModelId:m,active:h,onEnsureModels:()=>{I.current||t.length>0||n||(I.current=!0,w(!0),Z({type:`list_models`})||w(!1))},loading:C,onRefresh:()=>{w(!0),Z({type:`list_models`,refresh:!0})},onManageModels:r?()=>{g(!1),r()}:void 0,onPickModel:(e,t)=>{l?(l(e),g(!1)):(t&&!t.active&&Z({type:`activate_provider_key`,provider:e.provider,keyName:t.name}),m!==e.id&&p?.id!==e.id&&Z({type:`set_model`,modelId:e.id}),g(!1))},onToggleDefault:(e,t)=>{lf(e,t)},isRowActive:(e,t)=>(m===e.id||p?.id===e.id||`${e.provider}/${e.id}`===m)&&(!t||t.active),listRef:y}),R=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:f(`thinkingLevel`)}),D&&(0,$.jsxs)(`div`,{className:`dd-item-notice`,style:{padding:`4px 10px`,fontSize:`11px`,opacity:.7},children:[`🧠 `,f(`thinkingFixedNotice`)]}),k.filter(e=>e.supported).map(t=>(0,$.jsx)(Qd,{active:e?.thinkingLevel===t.value&&!M,onClick:()=>{N(null),u?(u(t.value),v(!1)):(e?.thinkingLevel!==t.value&&Z({type:`set_thinking`,level:t.value}),v(!1))},children:t.label},t.value)),!D&&(0,$.jsxs)(`div`,{className:`dd-custom-token-row`,children:[(0,$.jsx)(`div`,{className:`dd-custom-token-label`,children:(0,$.jsx)(`span`,{children:f(`thinkingCustomBudgetTitle`)})}),(0,$.jsxs)(`div`,{className:`dd-custom-token-group`,children:[(0,$.jsx)(`input`,{type:`number`,className:`dd-custom-token-input`,placeholder:f(`thinkingCustomBudgetPlaceholder`),value:A,onChange:e=>j(e.target.value),onKeyDown:e=>{e.key===`Enter`&&P()}}),(0,$.jsx)(`button`,{type:`button`,className:`dd-custom-token-btn`,onClick:P,children:f(`thinkingCustomBudgetBtn`)})]})]})]}),z=(0,$.jsx)(Zd,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(fe,{}),(0,$.jsx)(`span`,{className:`chip-model`,children:p?p.name:f(`selectModel`)}),!s&&p?.vision&&(0,$.jsx)(`span`,{className:`chip-vision`,title:f(`vision`),children:`🖼`}),!s&&p&&(0,$.jsx)(`span`,{className:`chip-sub`,children:p.provider})]}),open:h,onOpenChange:g,align:`left`,portal:!0,menuClassName:`dd-menu-model`,menuRef:b,menuStyle:x==null?void 0:{width:x},direction:d,children:L}),B=(0,$.jsx)(Zd,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(ne,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:f(`thinkingChip`,{level:e?F(e.thinkingLevel):`—`})})]}),tip:f(`thinkingLevel`),open:_,onOpenChange:v,align:`left`,portal:!0,direction:d,children:R});if(c===`model`)return z;if(c===`thinking`)return B;let V=e?.thinkingLevel&&e.thinkingLevel!==`off`;return(0,$.jsxs)(`div`,{className:`model-thinking-capsule`,children:[(0,$.jsx)(Zd,{className:`capsule-dropdown capsule-model-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(fe,{}),(0,$.jsx)(`span`,{className:`capsule-model-name`,children:p?p.name:f(`selectModel`)}),!s&&p?.vision&&(0,$.jsx)(`span`,{className:`chip-vision`,title:f(`vision`),children:`🖼`})]}),triggerClassName:`capsule-segment capsule-model`,open:h,onOpenChange:g,align:`left`,portal:!0,menuClassName:`dd-menu-model`,menuRef:b,menuStyle:x==null?void 0:{width:x},direction:d,children:L}),(0,$.jsx)(`div`,{className:`capsule-divider`}),(0,$.jsx)(Zd,{className:`capsule-dropdown capsule-thinking-dropdown`,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`thinking-pulse-dot ${V?`on`:``}`}),(0,$.jsx)(`span`,{className:`capsule-thinking-text`,children:e?F(e.thinkingLevel):`—`})]}),triggerClassName:`capsule-segment capsule-thinking`,open:_,onOpenChange:v,align:`left`,portal:!0,direction:d,children:R})]})});function j6({onNotice:e}){let t=X(),{locale:n}=_e(),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(!1),l=(0,Q.useRef)(null),u=(0,Q.useRef)(!1),d=(0,Q.useRef)(null),{panelRef:f,style:p}=T_({open:s,anchor:l,side:`top`,align:`left`,onClose:()=>c(!1)});(0,Q.useEffect)(()=>{let e=new AbortController;return fetch(j(`/api/system-screenshot`),{signal:e.signal}).then(async t=>{if(t.ok){let n=await t.json();e.signal.aborted||i(n.available===!0)}}).catch(()=>{}),()=>e.abort()},[]);let m=()=>{d.current!==null&&(clearTimeout(d.current),d.current=null)};(0,Q.useEffect)(()=>m,[]);let h=()=>{!r||a||u.current||(m(),c(!0))},g=()=>{m(),d.current=setTimeout(()=>{d.current=null,c(!1)},180)},_=async i=>{if(!r||u.current)return;u.current=!0,m(),c(!1),o(!0);let a=Array.from(crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``),s=document.title;i&&(document.title=`${s} [${a}]`);try{let e=await fetch(j(`/api/system-screenshot`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({token:a,locale:Ye(n)?`zh`:`en`,hideWindow:i})}),r=await e.json();if(!e.ok)throw r.error===`window-not-focused`?Error(t(`screenshotFocus`)):r.error===`busy`?Error(t(`screenshotBusy`)):r.error===`local-only`||r.error===`unsupported`?Error(t(`screenshotUnavailable`)):Error(t(`screenshotFailed`));if(r.cancelled)return;if(!r.dataUrl?.startsWith(`data:image/png;base64,`)||!Tn({src:r.dataUrl,alt:`${t(`screenshotName`)}.png`}))throw Error(t(`screenshotFailed`))}catch(n){e(`error`,n instanceof Error?n.message:t(`screenshotFailed`))}finally{i&&document.title.endsWith(`[${a}]`)&&(document.title=s),u.current=!1,o(!1)}};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:l,type:`button`,className:`btn attach-img`,title:t(r?a?`screenshotBusy`:`screenshotKeepWindow`:`screenshotUnavailable`),"aria-label":t(`screenshotCapture`),"aria-busy":a,"aria-expanded":s,disabled:!r||a,onClick:()=>void _(!1),onMouseEnter:h,onMouseMove:h,onMouseLeave:g,children:(0,$.jsx)(De,{})}),s&&(0,Er.createPortal)((0,$.jsx)(`div`,{ref:f,className:`ctx-menu`,style:p,role:`menu`,"aria-label":t(`screenshotCapture`),onMouseEnter:m,onMouseLeave:g,children:(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:`ctx-item`,onClick:()=>void _(!0),children:t(`screenshotHideWindow`)})}),document.body)]})}var M6=`pi-web:composer-mention`;function N6(e){e?.botId&&e.name&&window.dispatchEvent(new CustomEvent(M6,{detail:e}))}function P6(e){let t=t=>{let n=t.detail;n&&typeof n.botId==`string`&&typeof n.name==`string`&&e(n)};return window.addEventListener(M6,t),()=>window.removeEventListener(M6,t)}var F6=`Design and draft an AI agent (Bot) for the following request:
|
|
389
|
-
{{request}}
|
|
390
|
-
|
|
391
|
-
Call the agent_bot tool (op="draft") to generate the agent draft.`;function I6(e,t,n){let r=n.trim(),i=e.trim()||t.trim()||F6;return i.includes(`{{request}}`)||i.includes(`{{input}}`)?i.replaceAll(`{{request}}`,r).replaceAll(`{{input}}`,r):r?`${i}\n\n${r}`:i}async function L6(e,t){let n=e.trim();if(!n)throw new yp(400,`DRAFT_REQUEST_EMPTY`,`Describe the Bot in one sentence first`);if(n.length>2e3)throw new yp(400,`DRAFT_REQUEST_TOO_LONG`,`Describe the Bot in 2000 characters or less`);let r=t?.send??Z,i=await Dn(r,8e3,t?.cwd??void 0);if(!i)throw new yp(502,`DRAFT_FAILED`,`Failed to start a new conversation`);if(!r({type:`prompt`,text:I6(t?.promptTemplate??``,t?.defaultTemplate??``,n),targetConversationId:i}))throw new yp(502,`DRAFT_FAILED`,`Failed to send prompt`);return i}var R6=`pi-web-ui:bot-create`;function z6(){window.dispatchEvent(new Event(R6))}function B6(e){return window.addEventListener(R6,e),()=>window.removeEventListener(R6,e)}var V6=`pi-web-ui:bot-ai-draft`;function H6(){window.dispatchEvent(new CustomEvent(V6))}function U6(e){let t=()=>e();return window.addEventListener(V6,t),()=>window.removeEventListener(V6,t)}var W6=[`standard`,`ptc`,`minimal`,`cordis`],G6={standard:`preset.standard`,minimal:`preset.minimal`,code:`preset.code`,reader:`preset.reader`,ask:`preset.ask`},K6={standard:`preset.standardDesc`,minimal:`preset.minimalDesc`,code:`preset.codeDesc`,reader:`preset.readerDesc`,ask:`preset.askDesc`};function q6(e){return G6[e]??null}function J6(e){return K6[e]??null}function Y6(e,t,n){let r=Ye(t),i=q6(e.id),a=J6(e.id);return i&&a?{name:n(i),description:n(a)}:{name:r?e.name??e.id:e.nameEn??e.name??e.id,description:r?e.description:e.descriptionEn??e.description}}function X6(e){return[...e].sort((e,t)=>{let n=Number.isSafeInteger(e.order)?e.order:W6.indexOf(e.id),r=Number.isSafeInteger(t.order)?t.order:W6.indexOf(t.id),i=n>=0?n:1e3,a=r>=0?r:1e3;return i===a?e.id.localeCompare(t.id):i-a})}var Z6=(0,Q.memo)(function({preset:e,presets:t,defaultPreset:n,blank:r,conversationId:i,compact:a=!1}){let o=X(),{locale:s}=_e(),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(e?.id??n);if((0,Q.useEffect)(()=>{d(e?.id??n)},[i,e?.id,n]),t.length===0)return null;let f=e?.locked||!r,p=X6(t),m=p.find(t=>t.id===e?.id),h=p.find(e=>e.id===u)??m,g=e=>Y6(e,s,o),_=m?g(m):void 0,v=t=>{d(t),l(!1),r&&t!==e?.id&&Z({type:`dsh_preset_select`,preset:t})};if(a){let t=_?.description??m?.id??o(`dshPreset`);return(0,$.jsx)(Zd,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(qe,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:f?`${t}(${o(`dshPresetLocked`)})`:t,children:[_?.name??m?.id??e?.name??o(`dshPreset`),f&&(0,$.jsx)(Ge,{style:{marginLeft:3}})]})]}),open:c&&!f,onOpenChange:l,direction:`up`,align:`left`,children:p.map(t=>{let r=g(t);return(0,$.jsxs)(Qd,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>v(t.id),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[r.name,t.trust===`user`&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetUser`)}),t.id===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetDefaultTag`)}),t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:o(`dshPresetBroken`)})]}),r.description&&!t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:r.description})]},t.id)})})}return(0,$.jsxs)(`div`,{className:`dsh-presetbar`,"data-testid":`dsh-presetbar`,children:[(0,$.jsxs)(`span`,{className:`dsh-preset-label`,children:[(0,$.jsx)(qe,{}),o(`dshPreset`)]}),(0,$.jsx)(Zd,{trigger:(0,$.jsxs)(`span`,{title:_?.description??m?.id??``,children:[_?.name??m?.id??e?.name??`…`,f&&(0,$.jsxs)(`span`,{className:`dsh-preset-lock`,title:o(`dshPresetBlankOnly`),children:[(0,$.jsx)(Ge,{}),` `,o(`dshPresetLocked`)]})]}),open:c&&!f,onOpenChange:l,children:p.map(t=>{let r=g(t);return(0,$.jsxs)(Qd,{active:t.id===e?.id,disabled:!!t.broken,title:t.broken??r.description??t.id,onClick:()=>v(t.id),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[r.name,t.trust===`user`&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetUser`)}),t.id===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:o(`dshPresetDefaultTag`)}),t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:o(`dshPresetBroken`)})]}),r.description&&!t.broken&&(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:r.description})]},t.id)})}),!f&&(0,$.jsx)(`span`,{className:`dsh-preset-hint`,title:o(`dshPresetBlankOnly`),children:o(`dshPresetBlankOnly`)}),h?.id===`minimal`&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:o(`dshPresetMinimalNote`)}),(0,$.jsxs)(`button`,{type:`button`,className:`chip`,title:o(`dshPresetNewChat`),onClick:()=>{Z({type:`new_chat`,preset:h?.id??u}),er()},children:[(0,$.jsx)(ue,{}),` `,o(`dshPresetNewChat`)]})]})}),Q6=new Set([`bypassPermissions`]),$6=(0,Q.memo)(function({current:e,modes:t,compact:n=!1}){let r=X(),[i,a]=(0,Q.useState)(!1);if(!e||t.length===0)return null;let o=t=>{a(!1),t!==e&&Z({type:`claude_permission_mode`,mode:t})},s=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(nt,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:r(`claudePermDefaultDesc`),children:[e,Q6.has(e)&&(0,$.jsx)(me,{style:{marginLeft:3}})]})]});return n?(0,$.jsx)(Zd,{trigger:s,open:i,onOpenChange:a,direction:`up`,align:`left`,children:t.map(t=>(0,$.jsx)(Qd,{active:t===e,onClick:()=>o(t),children:(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[t,Q6.has(t)&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:r(`claudePermBypassTag`)})]})},t))}):(0,$.jsx)(`div`,{className:`dsh-presetbar`,children:(0,$.jsx)(Zd,{trigger:s,open:i,onOpenChange:a,direction:`down`,align:`left`,children:t.map(t=>(0,$.jsx)(Qd,{active:t===e,onClick:()=>o(t),children:t},t))})})}),eb=[`read-only`,`workspace-write-never`,`danger-full-access`],tb=[`read-only`,`workspace-write-never`,`danger-full-access`];function nb(e){return e===`read-only`?`dshPermReadOnly`:e===`danger-full-access`?`dshPermFullAccess`:`dshPermWorkspaceWrite`}function rb(e){return e===`read-only`?`dshPermReadOnlyDesc`:e===`danger-full-access`?`dshPermFullAccessDesc`:`dshPermWorkspaceWriteDesc`}var ib=(0,Q.memo)(function({current:e,options:t,defaultPreset:n,conversationId:r,compact:i=!1}){let a=X(),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{l(!1),s(!1)},[r]);let u=eb.filter(e=>t.some(t=>t.value===e));if(u.length===0)return null;let d=e??n,f=!!e&&!u.includes(e),p=e=>{e===`danger-full-access`&&e!==d&&!c?l(!0):(l(!1),s(!1),e!==d&&Z({type:`dsh_permission_set`,preset:e}))};if(i){let t=a(f?`dshPermCustom`:nb(d)),r=f?e??t:a(rb(d));return(0,$.jsxs)(Zd,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(nt,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,title:r,children:[t,d===`danger-full-access`&&(0,$.jsx)(me,{style:{marginLeft:3}})]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},direction:`up`,align:`left`,children:[u.map(e=>(0,$.jsxs)(Qd,{active:e===d,title:a(rb(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a(nb(e)),e===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:a(`dshPresetDefaultTag`)}),e===`danger-full-access`&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:a(`dshPermFullAccessTag`)})]}),(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:a(rb(e))})]},e)),c&&(0,$.jsx)(`div`,{className:`dd-note warn`,children:a(`dshPermConfirmFull`)})]})}return(0,$.jsxs)(`div`,{className:`dsh-presetbar`,"data-testid":`dsh-permissionbar`,children:[(0,$.jsxs)(`span`,{className:`dsh-preset-label`,children:[(0,$.jsx)(nt,{}),a(`dshPerm`)]}),(0,$.jsx)(Zd,{trigger:(0,$.jsxs)(`span`,{title:f?e:a(rb(d)),children:[a(f?`dshPermCustom`:nb(d)),d===`danger-full-access`&&(0,$.jsxs)(`span`,{className:`dd-preset-tag warn`,children:[(0,$.jsx)(me,{}),` `,a(`dshPermFullAccessTag`)]})]}),open:o,onOpenChange:e=>{s(e),e||l(!1)},children:u.map(e=>(0,$.jsxs)(Qd,{active:e===d,title:a(rb(e)),onClick:()=>p(e),children:[(0,$.jsxs)(`span`,{className:`dd-preset-name`,children:[a(nb(e)),e===n&&(0,$.jsx)(`span`,{className:`dd-preset-tag`,children:a(`dshPresetDefaultTag`)}),e===`danger-full-access`&&(0,$.jsx)(`span`,{className:`dd-preset-tag warn`,children:a(`dshPermFullAccessTag`)})]}),(0,$.jsx)(`span`,{className:`dd-preset-desc`,children:a(rb(e))})]},e))}),c&&(0,$.jsx)(`span`,{className:`dsh-preset-hint warn`,children:a(`dshPermConfirmFull`)})]})}),ab=[{key:`{{input}}`,labelKey:`tpl.vars.inputLabel`,descKey:`tpl.vars.inputDesc`},{key:`{{clipboard}}`,labelKey:`tpl.vars.clipboardLabel`,descKey:`tpl.vars.clipboardDesc`},{key:`{{date}}`,labelKey:`tpl.vars.dateLabel`,descKey:`tpl.vars.dateDesc`},{key:`{{time}}`,labelKey:`tpl.vars.timeLabel`,descKey:`tpl.vars.timeDesc`},{key:`{{datetime}}`,labelKey:`tpl.vars.datetimeLabel`,descKey:`tpl.vars.datetimeDesc`},{key:`{{selection}}`,labelKey:`tpl.vars.selectionLabel`,descKey:`tpl.vars.selectionDesc`}];function ob(e,t=new Date){if(!e.includes(`{{`))return e;let n=e=>String(e).padStart(2,`0`),r=t.getFullYear(),i=n(t.getMonth()+1),a=n(t.getDate()),o=n(t.getHours()),s=n(t.getMinutes()),c=n(t.getSeconds()),l=`${r}-${i}-${a}`,u=`${o}:${s}:${c}`,d=`${l} ${u}`;return e.replaceAll(`{{date}}`,l).replaceAll(`{{time}}`,u).replaceAll(`{{datetime}}`,d).replaceAll(`{{year}}`,String(r))}function sb(e){return e.trim().replace(/^\//,``).toLowerCase()}function cb(e){return/^[a-z][a-z0-9_-]*$/.test(e)}function lb(e,t){let n=new Set([`help`,`copy`,...t.map(e=>e.name.toLowerCase())]);return e.filter(e=>{let t=sb(e.command??``);return!cb(t)||n.has(t)?!1:(n.add(t),!0)})}function ub(e,t,n=new Date){let r=e.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);if(!r)return e;let i=t.find(e=>sb(e.command??``)===r[1].toLowerCase());if(!i)return e;let a=r[2]??``;return ob(i.prompt.includes(`{{input}}`)?i.prompt.replaceAll(`{{input}}`,()=>a):[i.prompt,a].filter(Boolean).join(`
|
|
392
|
-
|
|
393
|
-
`),n)}var db=[{id:`clarify`,command:`clarify`,icon:`🎯`,titleKey:`tpl.sk.clarify`,descKey:`tpl.sk.clarify.desc`,promptKey:`tpl.sk.clarify.prompt`},{id:`to-plan`,command:`plan`,icon:`📋`,titleKey:`tpl.sk.toplan`,descKey:`tpl.sk.toplan.desc`,promptKey:`tpl.sk.toplan.prompt`},{id:`implement`,command:`tdd`,icon:`🧪`,titleKey:`tpl.sk.implement`,descKey:`tpl.sk.implement.desc`,promptKey:`tpl.sk.implement.prompt`},{id:`code-review`,command:`review`,icon:`🧹`,titleKey:`tpl.sk.codeview`,descKey:`tpl.sk.codeview.desc`,promptKey:`tpl.sk.codeview.prompt`},{id:`pr-review`,command:`pr-review`,icon:`🔍`,titleKey:`tpl.sk.prreview`,descKey:`tpl.sk.prreview.desc`,promptKey:`tpl.sk.prreview.prompt`},{id:`diagnosing-bugs`,command:`debug`,icon:`🐛`,titleKey:`tpl.sk.debug`,descKey:`tpl.sk.debug.desc`,promptKey:`tpl.sk.debug.prompt`},{id:`resolving-merge-conflicts`,command:`merge`,icon:`🔀`,titleKey:`tpl.sk.merge`,descKey:`tpl.sk.merge.desc`,promptKey:`tpl.sk.merge.prompt`},{id:`prototype`,command:`spike`,icon:`🔬`,titleKey:`tpl.sk.prototype`,descKey:`tpl.sk.prototype.desc`,promptKey:`tpl.sk.prototype.prompt`},{id:`research`,command:`research`,icon:`📚`,titleKey:`tpl.sk.research`,descKey:`tpl.sk.research.desc`,promptKey:`tpl.sk.research.prompt`}],fb=`pi-web-ui:prompt-templates`;function pb(){try{let e=localStorage.getItem(fb);if(!e)return[];let t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>!!e&&typeof e==`object`&&typeof e.id==`string`):[]}catch{return[]}}function mb(e){return db.some(t=>t.id===e)}function hb(e){return typeof e.title==`string`}async function gb(e){if(typeof e.text==`function`){let t=await e.text();if(!t)return{};try{return JSON.parse(t)}catch{return{}}}if(typeof e.json==`function`)try{return await e.json()??{}}catch{return{}}return{}}async function _b(e){let t=``;if(typeof e.text==`function`)try{t=(await e.text()).trim()}catch{}else if(typeof e.json==`function`)try{let t=await e.json();if(t&&typeof t.error==`string`&&t.error)return t.error}catch{}if(t)try{let e=JSON.parse(t);if(e&&typeof e.error==`string`&&e.error)return e.error}catch{}let n=t?`: ${t.slice(0,120)}`:``;return`HTTP ${e.status}${n}`}async function vb(e){if(!e.ok)throw Error(await _b(e));let t=await gb(e);if(!Array.isArray(t.templates))throw Error(`Invalid prompt templates response`);return t.templates}var yb=(0,Q.createContext)(null);function bb(){let e=(0,Q.useContext)(yb);if(!e)throw Error(`useTemplates must be used within TemplateProvider`);return e}function xb({children:e,currentModelId:t}){let n=X(),r=mn(`status`),[i,a]=(0,Q.useState)([]),[o,s]=(0,Q.useState)(``),c=(0,Q.useRef)(!1),l=(0,Q.useRef)(0),u=(0,Q.useCallback)(async e=>{if(c.current)return!1;c.current=!0,l.current++;try{let t=await vb(await un(`/api/prompt-templates`,{body:e}));return a(t),s(``),!0}catch(e){return s(String(e)),!1}finally{c.current=!1}},[]),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(r!==`open`)return;let e=!1,t=async()=>{if(c.current)return;let t=++l.current;try{let n=await vb(await un(`/api/prompt-templates`));!e&&!c.current&&t===l.current&&(a(n),s(``))}catch(n){!e&&!c.current&&t===l.current&&s(String(n))}};return(async()=>{let e=pb();if(e.length&&await u({action:`migrate`,templates:e}))try{localStorage.removeItem(fb)}catch{}await t()})(),window.addEventListener(`focus`,t),window.addEventListener(`online`,t),()=>{e=!0,window.removeEventListener(`focus`,t),window.removeEventListener(`online`,t)}},[u,r]);let x=(0,Q.useMemo)(()=>{let e=new Map,t=new Set;for(let n of i)n.hidden?t.add(n.id):(hb(n)&&!mb(n.id)||hb(n))&&e.set(n.id,n);let r=db.filter(e=>!t.has(e.id)).map(t=>{let r=e.get(t.id);return{id:t.id,icon:r?.icon??t.icon,title:r?.title??n(t.titleKey),desc:r?.desc??n(t.descKey),command:typeof r?.command==`string`?r.command:t.command??``,prompt:r?.prompt??n(t.promptKey),builtin:!0}}),a=i.filter(e=>hb(e)&&!mb(e.id)).map(e=>({id:e.id,icon:e.icon??`📌`,title:e.title??``,desc:e.desc??``,command:typeof e.command==`string`?e.command:``,prompt:e.prompt??``}));return[...r,...a]},[i,n]),S=(0,Q.useCallback)(()=>f(!0),[]),C=(0,Q.useCallback)(e=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:e}))},[]),w=(0,Q.useCallback)((e,t=!1)=>{b(t),e?(g(!1),m({...e})):(g(!0),m({id:or(),icon:`📌`,title:``,desc:``,prompt:``}))},[]),T=(0,Q.useCallback)(()=>{f(!1),m(null),b(!1)},[]),E=(0,Q.useCallback)(()=>{_?(u({action:`reset`}),v(!1)):v(!0)},[_,u]);(0,Q.useEffect)(()=>{if(!_)return;let e=setTimeout(()=>v(!1),5e3);return()=>clearTimeout(e)},[_]);let D=(0,Q.useCallback)(e=>{f(!1),C(e.prompt)},[C]),O=(0,Q.useCallback)(e=>{f(!1),w(e,!0)},[w]),k=(0,Q.useCallback)(()=>{f(!1),w(void 0,!0)},[w]),A=(0,Q.useCallback)(async e=>{await u({action:`upsert`,template:e})&&(m(null),y&&(f(!0),b(!1)))},[y]),j=(0,Q.useCallback)(async e=>{await u(e.builtin?{action:`upsert`,template:{id:e.id,hidden:!0}}:{action:`remove`,id:e.id})&&(m(null),y&&(f(!0),b(!1)))},[y]),M=(0,Q.useCallback)(async e=>{await u({action:`remove`,id:e.id})&&(m(null),y&&(f(!0),b(!1)))},[y]),N=(0,Q.useMemo)(()=>({templates:x,fill:C,openPicker:S,openEdit:w,resetConfirm:_,toggleReset:E}),[x,C,S,w,_,E]),P=p?i.some(e=>e.id===p.id&&!e.hidden&&hb(e)):!1;return(0,$.jsxs)(yb.Provider,{value:N,children:[e,o&&(0,$.jsxs)(`div`,{className:`template-error`,role:`alert`,children:[n(`tpl.storageError`),`: `,o]}),d&&(0,$.jsx)(wb,{templates:x,resetConfirm:_,onFill:D,onEditTpl:O,onNew:k,onResetToggle:E,onClose:T}),p&&(0,$.jsx)(Eb,{editing:p,isNew:h,hasOverride:P,storageError:o,templates:x,onDraft:m,onSave:A,onRestore:()=>M(p),onRemove:()=>j(p),onFill:()=>{window.dispatchEvent(new CustomEvent(`pi-web:fill`,{detail:p.prompt})),T()},onSend:()=>{let e=ob(p.prompt.trim());e&&Z({type:`prompt`,text:e,queue:!1})&&(t&&of(t),T())},onClose:T})]})}function Sb(){let e=X(),{templates:t,fill:n,openEdit:r,toggleReset:i,resetConfirm:a}=bb();return(0,$.jsxs)(`div`,{className:`empty-templates`,children:[(0,$.jsxs)(`div`,{className:`empty-templates-head`,children:[(0,$.jsx)(`span`,{className:`empty-templates-title`,children:e(`tpl.title`)}),(0,$.jsx)(`span`,{className:`empty-templates-hint`,children:e(`tpl.hint`)})]}),(0,$.jsxs)(`div`,{className:`empty-templates-grid`,children:[t.map(t=>(0,$.jsx)(Cb,{tpl:t,title:e(`tpl.clickCard`),onFill:()=>n(t.prompt),onEdit:()=>r(t),editTitle:e(`tpl.editTpl`)},t.id)),(0,$.jsxs)(`button`,{type:`button`,className:`empty-template add`,onClick:()=>r(),title:e(`tpl.add`),children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:(0,$.jsx)(ue,{})}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:e(`tpl.add`)}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:e(`tpl.addDesc`)})]})]})]}),(0,$.jsx)(`div`,{className:`empty-templates-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`empty-templates-reset`,onClick:i,children:[(0,$.jsx)(ee,{}),e(a?`tpl.resetConfirm`:`tpl.reset`)]})})]})}function Cb({tpl:e,title:t,onFill:n,onEdit:r,editTitle:i}){let a=X();return(0,$.jsxs)(`button`,{type:`button`,className:`empty-template`,title:t,onClick:n,children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:e.icon}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:e.title}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:e.desc})]}),(0,$.jsx)(`span`,{className:`template-card-ops`,role:`button`,title:i??a(`tpl.editTpl`),onClick:e=>{e.stopPropagation(),r()},children:(0,$.jsx)(et,{})})]})}function wb({templates:e,resetConfirm:t,onFill:n,onEditTpl:r,onNew:i,onResetToggle:a,onClose:o}){let s=X();return(0,Q.useEffect)(()=>{let e=e=>{e.key===`Escape`&&o()};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[o]),(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:o,children:(0,$.jsxs)(`div`,{className:`modal template-picker`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`template-picker-top`,children:[(0,$.jsxs)(`div`,{className:`template-picker-head`,children:[(0,$.jsx)(`span`,{className:`template-picker-title`,children:s(`tpl.pickerTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:s(`close`),onClick:o,children:(0,$.jsx)(Ct,{})})]}),(0,$.jsx)(`div`,{className:`template-picker-hint`,children:s(`tpl.pickerHint`)})]}),(0,$.jsx)(`div`,{className:`template-picker-scroll`,children:(0,$.jsxs)(`div`,{className:`template-picker-grid`,children:[e.map(e=>(0,$.jsx)(Cb,{tpl:e,title:s(`tpl.clickCard`),onFill:()=>n(e),onEdit:()=>r(e),editTitle:s(`tpl.editTpl`)},e.id)),(0,$.jsxs)(`button`,{type:`button`,className:`empty-template add`,onClick:i,title:s(`tpl.add`),children:[(0,$.jsx)(`span`,{className:`empty-template-icon`,children:(0,$.jsx)(ue,{})}),(0,$.jsxs)(`span`,{className:`empty-template-main`,children:[(0,$.jsx)(`span`,{className:`empty-template-title`,children:s(`tpl.add`)}),(0,$.jsx)(`span`,{className:`empty-template-desc`,children:s(`tpl.addDesc`)})]})]})]})}),(0,$.jsx)(`div`,{className:`template-picker-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`empty-templates-reset`,onClick:a,children:[(0,$.jsx)(ee,{}),s(t?`tpl.resetConfirm`:`tpl.reset`)]})})]})})}var Tb=[`📌`,`🚀`,`⚡`,`📝`,`🔍`,`🛠️`,`🎯`,`💡`,`🤖`,`🌐`,`📦`,`🎨`,`🐛`,`🧪`,`✨`];function Eb({storageError:e,templates:t,editing:n,isNew:r,hasOverride:i,onDraft:a,onSave:o,onRestore:s,onRemove:c,onFill:l,onSend:u,onClose:d}){let f=X(),p=(0,Q.useRef)(null),m=(0,Q.useRef)(null),[h,g]=(0,Q.useState)(!1),_=(0,Q.useCallback)(()=>{let e=n.title.trim(),r=n.prompt.trim();if(!e||!r){a({...n,error:f(`tpl.required`)});return}let i=sb(n.command??``);i&&!cb(i)?a({...n,error:f(`tpl.commandInvalid`)}):i&&t.some(e=>e.id!==n.id&&sb(e.command??``)===i)?a({...n,error:f(`tpl.commandDuplicate`)}):o({id:n.id,command:i,icon:n.icon.trim()||`📌`,title:e,desc:n.desc.trim(),prompt:r})},[n,a,o,f,t]);(0,Q.useEffect)(()=>{let e=e=>{if(e.key===`Escape`){if(h){g(!1),e.stopPropagation();return}d()}else(e.ctrlKey||e.metaKey)&&e.key===`Enter`&&(e.preventDefault(),_())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[d,h,_]),(0,Q.useEffect)(()=>{if(!h)return;let e=e=>{m.current&&!m.current.contains(e.target)&&g(!1)};return window.addEventListener(`mousedown`,e),()=>window.removeEventListener(`mousedown`,e)},[h]),(0,Q.useEffect)(()=>{let e=p.current;if(!e)return;e.style.height=`auto`;let t=e.scrollHeight>340;e.style.height=`${Math.min(e.scrollHeight,340)}px`,e.style.overflowY=t?`auto`:`hidden`},[n.prompt]);let v=e=>{let t=p.current;if(!t){a({...n,prompt:n.prompt+e});return}let r=t.selectionStart??n.prompt.length,i=t.selectionEnd??n.prompt.length,o=n.prompt,s=o.slice(0,r)+e+o.slice(i);a({...n,prompt:s}),requestAnimationFrame(()=>{t.focus();let n=r+e.length;t.setSelectionRange(n,n)})},y=!!n.builtin&&!r;return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:d,children:(0,$.jsxs)(`div`,{className:`modal template-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`template-modal-head`,children:[(0,$.jsxs)(`div`,{className:`template-head-left`,ref:m,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn template-icon-btn`,title:f(`tpl.fieldIcon`),onClick:()=>g(e=>!e),children:(0,$.jsx)(`span`,{className:`template-modal-icon`,children:n.icon||`📌`})}),h&&(0,$.jsxs)(`div`,{className:`template-icon-dropdown`,children:[(0,$.jsx)(`div`,{className:`template-icon-grid`,children:Tb.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`template-icon-opt ${n.icon===e?`active`:``}`,onClick:()=>{a({...n,icon:e}),g(!1)},children:e},e))}),(0,$.jsx)(`div`,{className:`template-icon-custom`,children:(0,$.jsx)(`input`,{className:`template-icon-custom-input`,value:n.icon,maxLength:4,placeholder:`Emoji`,onChange:e=>a({...n,icon:e.target.value})})})]}),(0,$.jsx)(`input`,{className:`template-head-title-input`,value:n.title,placeholder:f(`tpl.fieldTitlePh`),onChange:e=>a({...n,title:e.target.value})}),(0,$.jsx)(`span`,{className:`template-modal-badge`,children:f(y?`tpl.builtin`:`tpl.custom`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-modal-close`,title:f(`close`),onClick:d,children:(0,$.jsx)(Ct,{})})]}),(0,$.jsxs)(`div`,{className:`template-modal-body`,children:[(0,$.jsxs)(`div`,{className:`template-grid-2col`,children:[(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`div`,{className:`template-field-label-row`,children:(0,$.jsx)(`span`,{className:`template-field-label`,children:f(`tpl.fieldCommand`)})}),(0,$.jsxs)(`div`,{className:`template-cmd-input-wrap`,children:[(0,$.jsx)(`span`,{className:`template-cmd-prefix`,children:`/`}),(0,$.jsx)(`input`,{className:`template-field-input template-cmd-input`,value:n.command?n.command.replace(/^\//,``):``,placeholder:`pr`,onChange:e=>a({...n,command:e.target.value.replace(/^\//,``),error:void 0})})]})]}),(0,$.jsxs)(`label`,{className:`template-field`,children:[(0,$.jsx)(`div`,{className:`template-field-label-row`,children:(0,$.jsx)(`span`,{className:`template-field-label`,children:f(`tpl.fieldDesc`)})}),(0,$.jsx)(`input`,{className:`template-field-input`,value:n.desc,placeholder:f(`tpl.fieldDescPh`),onChange:e=>a({...n,desc:e.target.value})})]})]}),(0,$.jsxs)(`div`,{className:`template-field template-prompt-field`,children:[(0,$.jsxs)(`div`,{className:`template-field-label-row`,children:[(0,$.jsx)(`span`,{className:`template-field-label`,children:f(`tpl.fieldPrompt`)}),(0,$.jsxs)(`span`,{className:`template-field-subhint`,children:[n.prompt.length,` 字符`]})]}),(0,$.jsxs)(`div`,{className:`template-prompt-container`,children:[(0,$.jsxs)(`div`,{className:`template-prompt-toolbar`,children:[(0,$.jsx)(`span`,{className:`template-vars-label`,children:`插入变量:`}),(0,$.jsx)(`div`,{className:`template-vars-chips`,children:ab.map(e=>(0,$.jsxs)(`button`,{type:`button`,className:`template-var-chip`,title:f(e.descKey),onClick:()=>v(e.key),children:[`+ `,f(e.labelKey,{token:e.key})]},e.key))})]}),(0,$.jsx)(`textarea`,{ref:p,className:`template-field-prompt`,value:n.prompt,placeholder:f(`tpl.fieldPromptPh`),onChange:e=>a({...n,prompt:e.target.value})})]}),(0,$.jsx)(`span`,{className:`template-picker-hint`,children:f(`tpl.commandHint`)})]})]}),(n.error||e)&&(0,$.jsx)(`div`,{className:`template-error`,role:`alert`,children:n.error||`${f(`tpl.storageError`)}: ${e}`}),(0,$.jsxs)(`div`,{className:`template-modal-actions`,children:[(0,$.jsxs)(`div`,{className:`template-modal-actions-left`,children:[!r&&y&&i&&(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn ghost`,title:f(`tpl.restoreTip`),onClick:s,children:f(`tpl.restore`)}),!r&&y&&(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn ghost danger`,title:f(`tpl.removeTip`),onClick:c,children:[(0,$.jsx)(Ne,{}),` `,f(`tpl.remove`)]}),!r&&!y&&(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn ghost danger`,title:f(`tpl.deleteTip`),onClick:c,children:[(0,$.jsx)(Ne,{}),` `,f(`tpl.delete`)]})]}),(0,$.jsxs)(`div`,{className:`template-modal-actions-right`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn`,onClick:_,children:f(`tpl.save`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn template-btn fill`,onClick:l,title:f(`tpl.fillTip`),children:f(`tpl.fill`)}),(0,$.jsxs)(`button`,{type:`button`,className:`btn template-btn send`,onClick:u,title:f(`tpl.sendTip`),children:[(0,$.jsx)($e,{}),` `,f(`tpl.sendNow`)]})]})]})]})})}function Db({attachRowRef:e,attachments:t,botDraftMode:n,onCancelBotDraft:r,onRemoveAttachment:a,onAnnotateImage:o}){let s=X();return t.length===0&&!n?null:(0,$.jsxs)(`div`,{className:`attach-row`,ref:e,children:[n&&(0,$.jsxs)(`span`,{className:`attach-chip is-bot-draft`,children:[(0,$.jsx)(fe,{size:12,className:`attach-bot-icon`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`attach-label`,children:s(`agentBotsComposerBadge`)}),(0,$.jsx)(`button`,{type:`button`,className:`attach-remove`,title:s(`agentBotsCreateCancel`),"aria-label":s(`agentBotsCreateCancel`),onClick:r,children:`×`})]}),t.map(e=>{if(e.mode===`quote`&&e.quote)return(0,$.jsx)(Ds,{quote:e.quote,onRemove:()=>a(_a(e))},e.key);let t=!!(e.imageData||e.path&&/\.(png|jpe?g|gif|webp|bmp|svg)$/i.test(e.path)),n=!(!e.path||e.isDir||e.mode===`conversation`||e.mode===`page`||e.mode===`canvas`),r=!!(e.imageData||n),c=e.imageData?e.imageData.startsWith(`data:`)?e.imageData:`data:${e.mimeType??`image/png`};base64,${e.imageData}`:t&&e.path?Jc(e.path):void 0,l=()=>{c?Tn({src:c,alt:e.name,onSaveAnnotation:o?t=>o(e,t):void 0}):n&&e.path&&Jt({path:e.path,name:e.name})},u=e.imageData?s(`attachImage`,{name:e.name}):e.fileData?s(`attachFile`,{name:e.name}):e.isDir?s(`folderRef`,{path:e.path}):e.mode===`page`?s(`attachPage`,{name:e.name}):e.mode===`canvas`?`${s(`canvasTab`)} · ${e.name}`:e.mode===`terminal`?s(`attachTerminal`,{name:e.name}):e.mode===`conversation`?s(`attachConversation`,{name:e.name}):e.mode===`reference`?s(`refOnly`,{path:e.path}):e.mode===`lines`&&e.lines?s(`attachLines`,{path:e.path,start:e.lines.start,end:e.lines.end}):s(`attachContent`,{path:e.path});return(0,$.jsxs)(`span`,{className:`attach-chip ${e.imageData?`image`:e.fileData?`file`:e.mode}${r?` previewable`:``}`,title:u+(r?` (${s(t?`toolImageZoom`:`fileOpenPreview`)})`:``),onClick:r?l:void 0,role:r?`button`:void 0,tabIndex:r?0:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),l())}:void 0,children:[c?(0,$.jsx)(`img`,{crossOrigin:i(c),src:c,alt:e.name,className:`attach-thumb`}):e.fileData?`📄`:e.isDir?`📁`:e.mode===`page`?`🌐`:e.mode===`canvas`?`◇`:e.mode===`terminal`?`🖥`:e.mode===`conversation`?`💬`:e.mode===`reference`?`🔗`:`📎`,(0,$.jsx)(`span`,{className:`attach-label`,title:e.name,children:e.name}),e.mode===`lines`&&e.lines&&(0,$.jsxs)(`span`,{className:`attach-range`,children:[`L`,e.lines.start,`-`,e.lines.end]}),(0,$.jsx)(`button`,{type:`button`,className:`attach-remove`,title:s(`removeAttachment`),onClick:t=>{t.stopPropagation(),a(_a(e))},children:`×`})]},e.key??(e.mode===`conversation`?`conv|${e.conversationId??``}|${e.sessionPath??``}`:`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`))})]})}var Ob=2e4,kb=2e3;function Ab(e){try{let t=localStorage.getItem(e);if(!t)return null;let n=JSON.parse(t);return typeof n.text!=`string`||!n.text||typeof n.ts!=`number`?null:{text:n.text.slice(0,Ob),ts:n.ts}}catch{return null}}function jb({sessionId:e,conversationId:t,sessionDraft:n,connected:r,ready:i,isTouch:a,messagesLength:o,hasGroupDevices:s,preserveDraftAcrossConversations:c,taRef:l,historyIndexRef:u,setText:d,clearMenu:f,refreshMenus:p,onGroupTextEdit:m}){let h=e?`${t??``}${e}`:null,g=h&&e?`pi-web-ui:composer-draft:${e}`:null,_=(0,Q.useRef)(``),v=(0,Q.useRef)(0),y=(0,Q.useRef)(!1),b=(0,Q.useRef)(0),x=(0,Q.useRef)(null),S=(0,Q.useRef)(null),C=(0,Q.useRef)(null),w=(0,Q.useRef)(c);w.current=c;let T=(e,t,n,r)=>{let i=n.slice(0,Ob);try{i.trim()?localStorage.setItem(t,JSON.stringify({text:i,ts:r})):localStorage.removeItem(t)}catch{}s||Z({type:`draft_update`,sessionId:e,text:i,ts:r})},E=()=>{x.current&&=(clearTimeout(x.current),null),y.current&&h&&g&&e&&r&&T(e,g,_.current,v.current)},D=t=>{if(m?.(t),_.current=t,y.current=!0,v.current=Date.now(),g){let e=t.slice(0,Ob);try{e.trim()?localStorage.setItem(g,JSON.stringify({text:e,ts:v.current})):localStorage.removeItem(g)}catch{}}if(h&&e&&r){x.current&&clearTimeout(x.current);let t=e,n=g,r=v.current,i=h;x.current=setTimeout(()=>{x.current=null,i===S.current&&n&&T(t,n,_.current,r)},kb)}},O=()=>{if(g)try{localStorage.removeItem(g)}catch{}x.current&&=(clearTimeout(x.current),null),y.current=!1,b.current=Date.now(),_.current=``,v.current=0};(0,Q.useEffect)(()=>{let t=h,n=e,r=g;return()=>{x.current&&=(clearTimeout(x.current),null);let e=_.current;if(y.current&&e.trim()){t&&n&&r&&T(n,r,e,v.current);let i=Qn(),a=t===null||i>0&&v.current>i;C.current={text:e,userEditedAfterSwitch:a}}else C.current=null}},[h]),(0,Q.useEffect)(()=>{S.current=h;let t=C.current;C.current=null;let r=t?.text??null,i=t?.userEditedAfterSwitch??!1,a=g?Ab(g):null,s=!!(n&&n.text?.trim()&&n.ts>0||a&&a.text?.trim());F4(r,i,o,s,w.current)&&r!==null&&g&&e?(y.current=!0,b.current=Date.now(),_.current=r,v.current=b.current,d(r),s||T(e,g,r,v.current)):(y.current=!1,b.current=0,_.current=``,v.current=0,d(``)),f(),u.current=-1},[h]);let k=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let e=o===0,t=k.current!==null&&k.current!==h,n=k.current===null&&e;k.current=h,i&&!a&&(t||n)&&requestAnimationFrame(()=>{l.current?.focus()})},[h,o,i]),(0,Q.useEffect)(()=>{if(!h||!g||y.current||_.current!==``)return;let e=j4(n&&n.text?{text:n.text.slice(0,Ob),ts:n.ts}:null,Ab(g),b.current);e&&(b.current=e.ts,_.current=e.text,v.current=e.ts,d(e.text),p(e.text,null))}),{textMirrorRef:_,lastEditTsRef:v,touchedRef:y,flushComposerDraft:E,noteComposerEdit:D,clearDraftAfterConsume:O}}var Mb=`skill:`,Nb=/[\s\-_./:]/;function Pb(e,t){let n=e.toLowerCase();return t===`skill`&&n.startsWith(`skill:`)?[n,n.slice(6)]:[n]}function Fb(e,t){let n=0;for(;n<t.length;){let r=t.indexOf(e,n);if(r===-1)return-1;if(r>0&&Nb.test(t[r-1]))return r;n=r+1}return-1}function Ib(e,t){let n=e.toLowerCase(),r=t.toLowerCase();if(!n)return{tier:0,score:0};if(n.length>r.length)return null;let i=3,a=-1;if(r===n)i=0,a=0;else if(r.startsWith(n))i=1,a=0;else{let e=Fb(n,r);e!==-1&&(i=2,a=e)}if(a!==-1){let e=0,t=0;for(let i=0;i<n.length;i++){let n=a+i,o=n===0||Nb.test(r[n-1]);i>0&&(t++,e-=t*5),o&&(e-=10),e+=n*.1}return i===0&&(e-=100),{tier:i,score:e}}let o=0,s=0,c=-1,l=0;for(;o<n.length;){let e=r.indexOf(n[o],c+1);if(e===-1)return null;let t=e===0||Nb.test(r[e-1]);c===e-1?(l++,s-=l*5):(l=0,c>=0&&(s+=(e-c-1)*2)),t&&(s-=10),s+=e*.1,c=e,o++}return{tier:3,score:s}}function Lb(e,t){let n=t.toLowerCase();if(!n)return[...e];let r=[];for(let t=0;t<e.length;t++){let i=e[t],a=Pb(i.name,i.source),o=null;for(let e of a){let t=Ib(n,e);t&&(!o||t.tier<o.tier||t.tier===o.tier&&t.score<o.score)&&(o=t)}o&&r.push({cmd:i,tier:o.tier,score:o.score,index:t})}return r.sort((e,t)=>e.tier===t.tier?e.tier<3?e.index-t.index:Math.abs(e.score-t.score)>1e-6?e.score-t.score:e.index-t.index:e.tier-t.tier),r.map(e=>e.cmd)}var Rb=new Set([`p`,`page`,`pages`,`web`,`网页`,`页面`]);function zb(e,t,n,r=10){if(!Array.isArray(t))return[];let i=String(n??``).toLowerCase(),a=i===``||Rb.has(i),o=[];for(let n of t){if(!n||typeof n.origin!=`string`||!n.origin||n.open!==!0)continue;let t=typeof n.title==`string`&&n.title.trim()?n.title.trim():n.origin;if(!a&&!t.toLowerCase().includes(i)&&!n.origin.toLowerCase().includes(i))continue;let s=t.indexOf(` · `),c=s===-1?`page · ${t}`:`page · ${t.slice(s+3)}`;if(o.push({providerId:`host:pages`,providerLabel:e,title:c,hint:n.origin,text:t,attachments:[{path:n.tabId??n.origin,name:t,mode:`page`}]}),o.length>=Math.max(0,r))break}return o}function Bb(e,t,n=10){if(!Array.isArray(t))return[];let r=[];for(let i of t.slice(0,Math.max(0,n))){if(!i||typeof i!=`object`)continue;let t=i;typeof t.path==`string`&&t.path&&typeof t.name==`string`&&t.name&&r.push({providerId:`host:files`,providerLabel:e,title:t.name,hint:t.path,text:`@${t.path}`,attachments:[{path:t.path,name:t.name,mode:`reference`,...t.type===`dir`?{isDir:!0}:{}}]})}return r}function Vb(e,t,n,r=10){if(!Array.isArray(n))return[];let i=[];for(let a of n.slice(0,Math.max(0,r))){if(!a||typeof a!=`object`)continue;let n=a;if(typeof n.title!=`string`||!n.title.trim())continue;let r=Array.isArray(n.attachments)?n.attachments.filter(e=>!!e&&typeof e==`object`&&typeof e.path==`string`).slice(0,4).map(e=>{let t=e.mode;return{path:e.path,...typeof e.name==`string`?{name:e.name}:{},...t===`inline`||t===`reference`||t===`lines`||t===`page`?{mode:t}:{},...typeof e.isDir==`boolean`?{isDir:e.isDir}:{}}}):void 0;i.push({providerId:e,providerLabel:t,title:n.title.trim(),...typeof n.hint==`string`&&n.hint?{hint:n.hint}:{},...typeof n.text==`string`&&n.text?{text:n.text}:{},...r?.length?{attachments:r}:{}})}return i}function Hb(e,t,n,r=15,i){if(!Array.isArray(t)||r<=0)return[];let a=String(n??``).toLowerCase(),o=a.startsWith(Mb),s=o?a.slice(Mb.length):a,c=[],l=[],u=o||s.length>=3;for(let n of t){if(n.source!==`skill`)continue;let t=n.name.startsWith(`skill:`)?n.name.slice(Mb.length):n.name,r=t.toLowerCase(),a=i?i(n):n.description??``,o=a.toLowerCase(),d=(n.descriptionEn??``).toLowerCase(),f={providerId:`host:skills`,providerLabel:e,title:t,hint:a||`Skill ${t}`,text:`@skill:${t}`};s?r.includes(s)?c.push(f):u&&(o.includes(s)||d.includes(s))&&l.push(f):c.push(f)}return[...c,...l].slice(0,Math.max(0,r))}function Ub(e,t,n=30){let r=String(t??``).toLowerCase(),i=e.pages??[],a=e.canvases??[],o=e.skills??[],s=e.files??[],c=e.plugins??[],l;return l=r.startsWith(`skill:`)?[...o,...a,...i,...s,...c]:[...a,...i,...o,...s,...c],l.slice(0,Math.max(0,n))}function Wb(e){return e===void 0||!(e===`@`||/[A-Za-z0-9_]/.test(e))}function Gb(e,t){let n=typeof e==`string`?e:``,r=Math.max(0,Math.min(typeof t==`number`&&Number.isFinite(t)?Math.floor(t):0,n.length)),i=n.slice(0,r),a=i.lastIndexOf(`@`);if(a===-1||!Wb(a>0?i[a-1]:void 0))return null;let o=i.slice(a+1);return/[\s@]/.test(o)?null:{start:a,query:o}}function Kb(){let e=window.__piBrowser;return e?.version===1&&typeof e.pageCall==`function`?e:void 0}var qb=()=>{let e=Kb();if(e)return t=>e.pageCall({...t,timeoutMs:t.timeoutMs??3e4});let t=window.__piWebUiHost;return t?.pageCall?.bind(t)},Jb=null,Yb=0;function Xb(){return Jb?.available===!0?Jb.pages??[]:[]}function Zb(e){Date.now()-Yb<5e3||Qb(e).catch(()=>{})}async function Qb(e){if(an()&&!Kb())return{available:!1,pages:[],desktop:!0,error:e(`browserControlNoDesktopBridge`)};let t=qb();if(!t)return{available:!1,pages:[],error:e(`browserControlNoHostBridge`)};try{let n=await t({op:`status`,timeoutMs:5e3});if(!n.ok)return{available:!1,pages:[],error:n.error??e(`browserControlNoExtensionStatus`)};let r=n.result??{},i={available:r.installed===!0,...Kb()?{native:!0}:{},aiControl:r.aiControl===!0,allowEval:r.allowEval===!0,...typeof r.activeTabId==`string`?{activeTabId:r.activeTabId}:{},...typeof r.activeOrigin==`string`?{activeOrigin:r.activeOrigin}:{},pages:Array.isArray(r.pages)?r.pages:[]};return i.available&&(Jb=i,Yb=Date.now()),i}catch(e){return{available:!1,pages:[],error:e instanceof Error?e.message:String(e)}}}function $b(e){let t=e.tabId??e.origin;return{path:t,name:e.title?.trim()||e.origin,mode:`page`,key:`page:${t}`}}async function e8(){let e=qb();if(!e)return!1;try{return(await e({op:`openOptions`,timeoutMs:5e3})).ok===!0}catch{return!1}}function t8(e=45e3){let t=X(),[n,r]=(0,Q.useState)(null),i=(0,Q.useRef)(!0),a=(0,Q.useCallback)(async e=>{let n=await Qb(t);i.current&&(r(n),e&&!n.available&&setTimeout(()=>{i.current&&a(!1)},1500))},[t]);return(0,Q.useEffect)(()=>{i.current=!0,a(!0);let t=setInterval(()=>void a(!1),Math.max(5e3,e));return()=>{i.current=!1,clearInterval(t)}},[a,e]),{status:n,refresh:()=>void a(!0)}}var n8=1;function r8(){return++n8}function i8({ready:e,text:t,setText:n,taRef:r,allSlashCommands:i,slashCommands:a,slashDesc:o,slashHint:s,capabilities:c,fileSearch:l,onSearchFiles:u,onAddPathAttachment:d,groupDevices:f,groupConversations:p,selectedGroupDevices:m,groupReferences:h,noteComposerEdit:g}){let _=X(),[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(0),S=(0,Q.useRef)(0),C=(0,Q.useRef)(new Map),w=(0,Q.useRef)(``),T=(0,Q.useRef)(null),E={builtin:_(`slashBuiltin`),extension:_(`slashExtension`),prompt:_(`slashPrompt`),skill:_(`slashSkill`),plugin:_(`slashPlugin`)},D=e=>{if(typeof u!=`function`)return Promise.resolve([]);let t=r8();return new Promise(n=>{C.current.set(t,n);try{u(t,e)}catch{C.current.delete(t),n([]);return}setTimeout(()=>{C.current.get(t)===n&&(C.current.delete(t),n([]))},3e3)})};(0,Q.useEffect)(()=>{if(!l||!l.ok)return;let e=C.current.get(l.reqId);e&&(C.current.delete(l.reqId),e(l.results??[]))},[l]),(0,Q.useEffect)(()=>{(T.current?.querySelector(`.slash-item.active`))?.scrollIntoView({block:`nearest`})},[b,v]);let O=(t,n)=>{w.current=t;let r=t.match(/^\/([^\s]*)$/);if(r&&e&&!f){let e=Lb(i,r[1].toLowerCase());y(e.length>0?{kind:`slash`,items:e}:null),x(0);return}if(n===null||!e){y(null);return}let s=Gb(t,n);if(!s){y(null);return}if(f){let e=ud(f,p,s.query,_);y(e.length?{kind:`at`,start:s.start,end:n,items:e}:null),x(0);return}let l=[];try{l=Fn()}catch{l=[]}let d=++S.current,m=t,h=s.start,g=s.query,v=h+1+g.length,b=l.map(e=>({id:e.id,label:e.label,run:()=>{let t;try{t=Rn(e.id)?.search}catch{t=void 0}return typeof t==`function`?t(g):Promise.resolve([])}}));b.push({id:`host:canvases`,label:_(`canvasTab`),run:async()=>ms(await hs(()=>Z({type:`canvas_list`})),g,_(`canvasTab`))}),g&&typeof u==`function`&&b.push({id:`host:files`,label:_(`openFiles`),run:()=>D(g)});let C=[];if(c.pageRef&&(Zb(_),C=zb(_(`browserControl`),Xb(),g),b.push({id:`host:pages`,label:_(`browserControl`),run:()=>Promise.resolve(C)})),b.length===0){y(null);return}let T=Hb(_(`slashSkill`),a,g,15,o),E=Ub({pages:C,skills:T},g,30),O=!1;E.length>0&&(O=!0,y({kind:`at`,start:h,end:v,items:E}),x(0)),Promise.allSettled(b.map(e=>Promise.race([e.run(),new Promise((e,t)=>setTimeout(()=>t(Error(`at-mention timeout`)),2e3))]))).then(e=>{if(S.current!==d||w.current!==m)return;let t=[],n=[],r=[],i=[];e.forEach((e,a)=>{e.status===`fulfilled`&&(b[a].id===`host:pages`&&Array.isArray(e.value)?n.push(...e.value):b[a].id===`host:canvases`&&Array.isArray(e.value)?t.push(...e.value):b[a].id===`host:files`?r.push(...Bb(b[a].label,e.value)):i.push(...Vb(b[a].id,b[a].label,e.value)))});let a=Ub({canvases:t,pages:n,skills:T,files:r,plugins:i},g,30);y(a.length>0?{kind:`at`,start:h,end:v,items:a}:null),!O&&a.length>0&&x(0)})},k=e=>O(e,null),A=e=>{let i=v?.kind===`slash`?v.items:[],a=e??i[b%Math.max(i.length,1)];if(!a){y(null);return}let o=t.match(/^\/([^\s]*)([\s\S]*)$/),s=o?o[2]:``,c=`/${a.name} ${s}`;w.current=c,n(c),g(c),y(null),r.current?.focus()},j=(e,i)=>{let a=v?.kind===`at`?v:null,o=a?.items??[],s=e??o[b%Math.max(o.length,1)],c=i??a?.start;if(!s||c===void 0){y(null);return}let l=r.current,u=l?l.selectionStart??t.length:t.length,_=a?.end!==void 0&&a.end>=c?a.end:u,x=s.attachments??[],S=s.providerId===`host:group-conversations`?p.find(e=>e.id===s.hint):void 0,C=f?.find(e=>s.providerId===`host:group-devices`?e.id===s.hint:e.id===S?.botId),T=s.text??(C?`@${C.name}`:s.title);f&&s.providerId===`host:group-devices`&&s.hint&&m.current.add(s.hint);let E=x.length>0&&!T.startsWith(`@`)?`@${T} `:`${T} `,D=`${t.slice(0,c)}${E}${t.slice(_)}`;w.current=D,n(D),g(D),C&&h.current.push({start:c,end:c+T.length,member:C,conversationId:S?.id}),y(null);for(let e of x)try{d?.({path:e.path,name:e.name??e.path.split(`/`).pop()??e.path,...e.mode?{mode:e.mode}:{mode:`reference`},...typeof e.isDir==`boolean`?{isDir:e.isDir}:{},...e.lines?{lines:e.lines}:{},silent:!0})}catch{}requestAnimationFrame(()=>{let e=r.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=c+E.length)})},M=e=>{v&&(v.kind===`slash`?A(e):j(e,v.start))};return{menu:v,setMenu:y,menuIndex:b,setMenuIndex:x,menuTextRef:w,menuRef:T,refreshMenus:O,updateCompletions:k,acceptSlash:A,acceptAt:j,acceptMenu:M,renderSlashRows:()=>v?.kind===`slash`?v.items.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${t===b?` active`:``}`,onMouseEnter:()=>x(t),onClick:()=>M(e),children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`/`,e.name]}),(0,$.jsx)(`span`,{className:`slash-source ${e.source}`,children:E[e.source]}),(0,$.jsxs)(`span`,{className:`slash-desc`,children:[o(e),e.argumentHint&&(0,$.jsx)(`span`,{className:`slash-hint`,children:s(e)})]})]},e.name)):null,renderAtRows:()=>v?.kind===`at`?v.items.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`slash-item${t===b?` active`:``}`,onMouseEnter:()=>x(t),onClick:()=>M(e),title:f?e.title:e.hint??e.title,children:[(0,$.jsxs)(`span`,{className:`slash-name`,children:[`@`,e.title]}),(0,$.jsx)(`span`,{className:`slash-source ${e.providerId===`host:skills`?`skill`:`plugin`}`,children:e.providerLabel}),e.hint&&!f&&(0,$.jsx)(`span`,{className:`slash-desc`,children:e.hint})]},`${e.providerId}:${e.title}:${t}`)):null}}var a8=`pi-web-ui:composer-height`;function o8(e){return typeof window>`u`?e:Math.max(160,Math.min(e,Math.floor(window.innerHeight*.42)))}function s8({maxH:e,text:t,attachmentsCount:n,quickPhrasesEnabled:r,quickPhrasesCount:i,taRef:a,composerRef:o,attachRowRef:s,quickRowRef:c}){let[l,u]=(0,Q.useState)(()=>{try{let t=Number(localStorage.getItem(a8));if(Number.isFinite(t)&&t>44)return Math.min(t,e)}catch{}return null}),d=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{let t=a.current,n=o.current;if(!t||!n)return;let r=t.closest(`main`)?.querySelector(`.messages`),i=n.getBoundingClientRect().height,s=r?.scrollTop??0,c=o8(e);t.style.maxHeight=`${c}px`;let u=l!=null&&l>44,d;t.style.height=`auto`;let f=t.scrollHeight;d=Math.min(u?l:Math.max(f,40),c),t.style.height=`${d}px`,t.style.overflowY=f>d?`auto`:`hidden`,r&&(r.scrollTop=s+(n.getBoundingClientRect().height-i))},[t,l,e]),(0,Q.useEffect)(()=>{let e=[s.current,c.current].filter(e=>e!==null),t=document.documentElement;if(e.length===0){t.style.removeProperty(`--quick-row-h`);return}let n=()=>{let n=e.reduce((e,t)=>e+t.offsetHeight,0)+Math.max(0,e.length-1)*6;t.style.setProperty(`--quick-row-h`,`${n}px`)};n();let r=new ResizeObserver(n);for(let t of e)r.observe(t);return()=>{r.disconnect(),t.style.removeProperty(`--quick-row-h`)}},[n,r,i]),{composerH:l,setComposerH:u,dragResizeRef:d}}function c8({text:e,setText:t,attachments:n,connected:r,sessionReady:i,isTouch:a,goalMode:o,goalRefine:s,goalPlan:c,goal:l,capabilities:u,groupDevices:d,groupPlanOnly:f,onGroupSend:p,selectedGroupDevices:m,groupReferences:h,groupReferenceText:g,textMirrorRef:_,historyIndexRef:v,draftRef:y,taRef:b,clearDraftAfterConsume:x,flushComposerDraft:S,onNotice:C,onSent:w,setHelpWidth:T,setShowHelp:E,copyLastAssistant:D,botDraftMode:O,setBotDraftMode:k,activeBotId:A,botDraftPrompt:j,botDraftDefaultPrompt:M,cwd:N,conversationId:P,commandTemplates:F,model:I}){let L=X(),R=(0,Q.useRef)(!1),z=()=>n.map(e=>e.mode===`quote`?{path:``,mode:`quote`,quote:e.quote}:e.imageData?{path:``,imageData:e.imageData,mimeType:e.mimeType,name:e.name}:e.fileData?{path:``,fileData:e.fileData,mimeType:e.mimeType,name:e.name,size:e.size}:{path:e.path,mode:e.mode,...e.lines?{lines:e.lines}:{},...e.mode===`page`||e.mode===`canvas`||e.mode===`terminal`?{name:e.name}:{},...e.mode===`terminal`&&e.terminalId?{terminalId:e.terminalId}:{},...e.mode===`conversation`?{name:e.name,...e.conversationId?{conversationId:e.conversationId}:{},...e.sessionPath?{sessionPath:e.sessionPath}:{}}:{}}),B=()=>{let e=ya(z());return e.unusable.length>0&&C(`warning`,L(`goalMaterialUnaddressable`,{names:e.unusable.join(`、`)})),e};return{submit:(a=!1)=>{let S=e.trim(),V=n.length>0;if(!S&&(o||!V)||!d&&!o&&!a&&Z4()&&Q4())return;if(!r){C(`error`,L(`netDisconnected`));return}if(!i){C(`warning`,L(`sessionInitializingNotice`));return}if(d){if(!p||R.current)return;let n;try{n=vd(h.current)}catch(e){C(`error`,e.message);return}R.current=!0;let r=bd(e,h.current);p(r.text.trim(),[...new Set([...r.targets,...hd(S,d).filter(e=>m.current.has(e))])],n,{planOnly:f}).then(e=>{e&&_.current.trim()===S&&(t(``),m.current.clear(),h.current=[],g.current=``,x(),w())}).catch(e=>C(`error`,String(e))).finally(()=>{R.current=!1});return}let H=va({attachments:n,conversationRefSupported:!!u.conversationRef});if(H)C(H.level,L(H.key));else if(o){let e=l?.locked??!0,n=l?.maxRounds??0,r=(l?.reviewModel??``).trim()?l?.reviewModel:``,{materials:i,blobs:a}=B(),o=!1;o=Z(s?{type:`start_goal_wizard`,text:S,...r?{wizardModel:r}:{},maxRounds:n,locked:e,...i.length>0?{materials:i}:{},...a.length>0?{materialBlobs:a}:{}}:{type:`set_goal`,goal:S,...r?{reviewModel:r}:{},maxRounds:n,locked:e,...i.length>0?{materials:i}:{},...a.length>0?{materialBlobs:a}:{}}),c&&(Z({type:`set_plan_mode`,enabled:!0}),w3(!1)),o?(S&&Y3(S),v.current=-1,y.current=``,t(``),x(),x3(!1),w(),b.current?.focus()):C(`error`,L(`netDisconnected`))}else if(S===`/help`)T(b.current?.closest(`.inputbox`)?.getBoundingClientRect()?.width),E(!0),t(``),x(),b.current?.focus();else if(S===`/copy`)t(``),x(),b.current?.focus(),D();else if(O){if(!S)return;if(A){L6(S,{promptTemplate:j,defaultTemplate:M,cwd:N}).catch(e=>{C(`error`,e instanceof Error?e.message:String(e))}),Y3(S),v.current=-1,y.current=``,t(``),x(),k(!1),w(),b.current?.focus();return}let e=I6(j??``,M??``,S);Z({type:`prompt`,text:e,queue:a,attachments:z(),...P?{targetConversationId:P}:{}})?(Y3(S),v.current=-1,y.current=``,t(``),x(),k(!1),w(),I&&of(`${I.provider}/${I.id}`),b.current?.focus()):C(`error`,L(`netDisconnected`))}else Z({type:`prompt`,text:ub(S,F),queue:a,attachments:z(),...P?{targetConversationId:P}:{}})?(S&&Y3(S),v.current=-1,y.current=``,t(``),x(),w(),I&&of(`${I.provider}/${I.id}`),b.current?.focus()):C(`error`,L(`netDisconnected`))},sendPhrase:(e,t=!1)=>{if(d)return;let n=e.trim();n&&(r?i?Z({type:`prompt`,text:n,queue:t,attachments:z(),...P?{targetConversationId:P}:{}})?(n&&Y3(n),v.current=-1,y.current=``,S(),w(),I&&of(`${I.provider}/${I.id}`),a||b.current?.focus()):C(`error`,L(`netDisconnected`)):C(`warning`,L(`sessionInitializingNotice`)):C(`error`,L(`netDisconnected`)))}}}var l8=Q3(),u8=320,d8=(0,Q.memo)(function({groupDevices:e,groupReady:t,groupPrimaryBotName:n,groupConversationError:i,groupConversations:a=[],onGroupSend:o,onAbort:s,streaming:c,planMode:l,messages:u,slashCommands:d,modelState:p,models:m,modelsLoading:h,attachments:g,onRemoveAttachment:_,onAnnotateImage:v,onAddImageFiles:y,onAddLocalFiles:b,onAddPathAttachment:x,fileSearch:S,onSearchFiles:C,onNotice:w,onSent:T,onManageModels:E,providerKeys:D,providers:O,defaultModel:A,quickPhrases:j,quickPhrasesEnabled:M,recallDrafts:P,composerLeading:F,composerActions:I,onUiAction:L,dshPermCurrent:R,claudePermCurrent:z,claudePermModes:B,dshPermOptions:V,dshPermDefault:H,dshPreset:ee,dshPresets:U,dshPresetDefault:W,dshBlank:G,conversationId:K,sessionDraft:q,sessionId:ne,preserveDraftAcrossConversations:re=!1,goal:J,goalModeEnabled:ie=!0,botDraftPrompt:ae,botDraftDefaultPrompt:oe,activeBotId:se}){let Y=X(),ce=mn(`ready`),le=e?!!t:ce,ue=_n(),de=!!(l&&ue.planMode),[fe,pe]=(0,Q.useState)(!1),me=T3(),he=D3(),ge=O3(),ve=!!J?.goal||!!J?.wizard?.active,ye=ie&&!e&&me&&!ve;(0,Q.useEffect)(()=>{(ve||!ie)&&(x3(!1),S3(!1))},[ve,ie]),(0,Q.useEffect)(()=>{x3(!1),S3(!1)},[K]);let{locale:be}=_e(),xe=l6(l8),Se=xe===`mod-enter`,Ce=mn(`cwd`),we=mn(`projects`),Te=h6(Ce||``,we)||`pi`,{openPicker:Ee,templates:De}=bb(),Oe=lb(De,d),ke=[...d,...Oe.map(e=>({name:sb(e.command??``),description:e.desc||e.title,source:`prompt`}))],Ae=e=>!Ye(be)&&e.descriptionEn?e.descriptionEn:e.description??``,je=e=>!Ye(be)&&e.argumentHintEn?e.argumentHintEn:e.argumentHint??``,[Me,Ne]=(0,Q.useState)(``),Pe=le,[Fe,Ie]=(0,Q.useState)(!1),[Le,Re]=(0,Q.useState)(void 0),ze=(0,Q.useRef)(null),Be=(0,Q.useRef)(null),Ve=(0,Q.useRef)(null),He=(0,Q.useRef)(null),Ue=(0,Q.useRef)(null),We=(0,Q.useRef)(-1),Ge=(0,Q.useRef)(``),[Ke,qe]=(0,Q.useState)(!1),Je=(0,Q.useRef)(0),Xe=(0,Q.useRef)(new Set),Ze=(0,Q.useRef)([]),Qe=(0,Q.useRef)(``),$e=w6(),et=(0,Q.useSyncExternalStore)(J4,q4,q4),{composerH:tt,setComposerH:nt,dragResizeRef:rt}=s8({maxH:u8,text:Me,attachmentsCount:g.length,quickPhrasesEnabled:M,quickPhrasesCount:j.length,taRef:ze,composerRef:Be,attachRowRef:Ve,quickRowRef:He}),it=(0,Q.useRef)(()=>{}),ot=(0,Q.useRef)(()=>{}),{textMirrorRef:st,lastEditTsRef:lt,touchedRef:ut,flushComposerDraft:dt,noteComposerEdit:ft,clearDraftAfterConsume:pt}=jb({sessionId:ne,conversationId:K,sessionDraft:q,connected:Pe,ready:le,isTouch:l8,messagesLength:u.length,hasGroupDevices:!!e,preserveDraftAcrossConversations:re,taRef:ze,historyIndexRef:We,setText:Ne,clearMenu:()=>it.current(),refreshMenus:(e,t)=>ot.current(e,t),onGroupTextEdit:e?t=>{Ze.current=yd(Qe.current,t,Ze.current),Qe.current=t;let n=new Set(hd(t,e));for(let e of Xe.current)n.has(e)||Xe.current.delete(e)}:void 0}),{menu:mt,setMenu:ht,setMenuIndex:gt,menuTextRef:vt,menuRef:yt,refreshMenus:bt,updateCompletions:xt,acceptMenu:St,renderSlashRows:Ct,renderAtRows:wt}=i8({ready:le,text:Me,setText:Ne,taRef:ze,allSlashCommands:ke,slashCommands:d,slashDesc:Ae,slashHint:je,capabilities:ue,fileSearch:S,onSearchFiles:C,onAddPathAttachment:x,groupDevices:e,groupConversations:a,selectedGroupDevices:Xe,groupReferences:Ze,noteComposerEdit:ft});it.current=()=>ht(null),ot.current=bt,(0,Q.useEffect)(()=>{if(!P||P.length===0)return;let e=P.filter(e=>e.text&&e.seq>Je.current);if(e.length===0)return;Je.current=e[e.length-1].seq,ht(null);let t=e.reduce((e,t)=>A4(e,t.text),Nt.current);vt.current=t,Ne(t),ft(t),We.current=-1,Ge.current=``,requestAnimationFrame(()=>{let e=ze.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)})},[P]),(0,Q.useEffect)(()=>{if(!e)return ar(e=>{ht(null);let t=A4(Nt.current,e);vt.current=t,Ne(t),ft(t),We.current=-1,Ge.current=``,requestAnimationFrame(()=>{let e=ze.current;e&&(e.focus(),e.selectionStart=e.selectionEnd=e.value.length)})}),()=>ar(null)},[]),(0,Q.useEffect)(()=>(Yn(()=>{l8||requestAnimationFrame(()=>{ze.current?.focus()})}),()=>Yn(null)),[]);let Tt=(0,Q.useRef)(``);Tt.current=Me,(0,Q.useEffect)(()=>{if(!e)return Xn(e=>{if(a3(Tt.current,e))return;let t=ze.current,n=Tt.current,r=e=>{Tt.current=e,st.current=e,vt.current=e,ut.current=!0,lt.current=Date.now(),Ne(e)};if(!t){r(n+(n&&!n.endsWith(` `)?` `:``)+e);return}let i=t.selectionStart??n.length,a=t.selectionEnd??n.length,o=(i>0&&!/[\s([{]$/.test(n.slice(0,i))?` `:``)+e;r(n.slice(0,i)+o+n.slice(a));let s=i+o.length;requestAnimationFrame(()=>{t.focus(),t.selectionStart=t.selectionEnd=s})}),()=>Xn(null)},[]),(0,Q.useEffect)(()=>{if(!e)return tr(e=>{Ne(t=>{let n=new Set([`.`,`*`,`+`,`?`,`^`,`$`,`{`,`}`,`(`,`)`,`|`,`[`,`]`,`\\`]),r=e.split(``).map(e=>n.has(e)?`\\`+e:e).join(``),i=RegExp(`(^|\\s)`+r+`(?:\\s|$)`,`g`),a=t.replace(i,(e,t)=>t===` `?` `:``);return a=a.replace(/ {2,}/g,` `).trim(),vt.current=a,a})}),()=>tr(null)},[]),(0,Q.useEffect)(()=>{if(Ze.current=[],Qe.current=Tt.current,e&&ne?.startsWith(`device-group:`))return Td(ne.slice(13),e=>{if(Ze.current.find(t=>t.member.id===e.id)){ze.current?.focus();return}let t=ze.current,n=Ed(Tt.current,t?.selectionStart??Tt.current.length,e);Ze.current=yd(Tt.current,n.text,Ze.current),Ze.current.push({start:n.cursor-e.name.length-2,end:n.cursor-1,member:e}),Qe.current=n.text,st.current=n.text,Tt.current=n.text,vt.current=n.text,Ne(n.text),requestAnimationFrame(()=>{ze.current?.focus(),ze.current?.setSelectionRange(n.cursor,n.cursor)})})},[ne,!!e]),(0,Q.useEffect)(()=>U6(()=>{pe(!0),window.setTimeout(()=>ze.current?.focus(),0)}),[]),(0,Q.useEffect)(()=>P6(t=>{let n=e?.find(e=>e.id===t.botId||e.name===t.name),r=ze.current,i=Tt.current,a=r?.selectionStart??i.length,o=r?.selectionEnd??i.length,s=n?Ed(i,a,n):void 0,c=`@${t.name}`,l=a>0&&!/[\s([{]$/.test(i.slice(0,a))?` `:``,u=s?s.text.slice(a,s.cursor):`${l}${c} `,d=s??{text:i.slice(0,a)+u+i.slice(o),cursor:a+u.length};n&&(Ze.current=[...Ze.current,{start:d.cursor-n.name.length-2,end:d.cursor-1,member:n}],Qe.current=d.text),st.current=d.text,Tt.current=d.text,vt.current=d.text,Ne(d.text),requestAnimationFrame(()=>{ze.current?.focus(),ze.current?.setSelectionRange(d.cursor,d.cursor)})}),[e]);let Et=(e,t)=>{We.current=-1,Ne(e),bt(e,t),ft(e)},Dt={builtin:Y(`slashBuiltin`),extension:Y(`slashExtension`),prompt:Y(`slashPrompt`),skill:Y(`slashSkill`),plugin:Y(`slashPlugin`)},Ot=async()=>{let e=[...u].reverse().find(e=>e.role===`assistant`&&e.content.some(e=>e.type===`text`&&e.text))?.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
394
|
-
`);e?await Kn(e)?w(`info`,Y(`slashCopied`)):w(`error`,Y(`slashCopyFailed`)):w(`warning`,Y(`slashCopyEmpty`))},kt=t=>{if(e)return;if(!t||t.length===0){w(`warning`,Y(`foldersNotSupported`));return}let n=Array.from(t).filter(e=>ma(e.type)),r=Array.from(t).filter(e=>!ma(e.type)),i=jt();n.length>0&&i?w(`warning`,i):n.length>0&&y(n),r.length>0&&b(r)},At=e=>{let t=R3(e.clipboardData?.items,e.clipboardData?.files);t.length!==0&&(e.preventDefault(),kt(t))},jt=()=>{let e=p?.model;if(!e?.id)return null;let t=m.find(t=>t.id===e.id);return t&&t.vision===!1?Y(`modelNoVision`,{name:t.name}):null},Mt=le&&!!ne,Nt=(0,Q.useRef)(Me);(0,Q.useEffect)(()=>{Nt.current=Me},[Me]),(0,Q.useEffect)(()=>{!e&&/^\/[^\s]*$/.test(Nt.current)&&xt(Nt.current)},[d]);let[Pt,Ft]=(0,Q.useState)(null),It=e=>{let t=Pt;if(Ft(null),t===null)return;let n=L4(Nt.current,t,e);n!==null&&(ht(null),vt.current=n,Ne(n)),requestAnimationFrame(()=>ze.current?.focus())};(0,Q.useEffect)(()=>{if(e)return;let t=e=>{let t=e.detail;typeof t==`string`&&(I4(Nt.current,t)?Ft(t):(ht(null),vt.current=t,Ne(t),ft(t),ze.current?.focus()))};return window.addEventListener(`pi-web:fill`,t),()=>window.removeEventListener(`pi-web:fill`,t)},[]),(0,Q.useEffect)(()=>{if(!Fe&&Pt===null)return;let e=e=>{e.key===`Escape`&&(Pt===null?Ie(!1):(Ft(null),requestAnimationFrame(()=>ze.current?.focus())))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[Fe,Pt]);let{submit:Lt,sendPhrase:Rt}=c8({text:Me,setText:Ne,attachments:g,connected:Pe,sessionReady:Mt,isTouch:l8,goalMode:ye,goalRefine:he,goalPlan:ge,goal:J,capabilities:ue,groupDevices:e,groupPlanOnly:Ke,onGroupSend:o,selectedGroupDevices:Xe,groupReferences:Ze,groupReferenceText:Qe,textMirrorRef:st,historyIndexRef:We,draftRef:Ge,taRef:ze,clearDraftAfterConsume:pt,flushComposerDraft:dt,onNotice:w,onSent:T,setHelpWidth:Re,setShowHelp:Ie,copyLastAssistant:Ot,botDraftMode:fe,setBotDraftMode:pe,activeBotId:se,botDraftPrompt:ae,botDraftDefaultPrompt:oe,cwd:Ce,conversationId:K,commandTemplates:Oe,model:p?.model});n3(Q.useEffect,{groupDevices:!!e,text:Me,attachments:g,attachmentLabel:Y(`attachment`),setText:Ne,clearDraftAfterConsume:pt,onSent:T});let zt=t=>{if(!$e.isImeKey(t.nativeEvent)){if(mt&&mt.items.length>0){let e=mt.items.length;switch(t.key){case`ArrowDown`:t.preventDefault(),gt(t=>(t+1)%e);return;case`ArrowUp`:t.preventDefault(),gt(t=>(t-1+e)%e);return;case`Tab`:case`Enter`:t.preventDefault(),St();return;case`Escape`:t.preventDefault(),ht(null);return}}if(e&&(t.key===`Backspace`||t.key===`Delete`)&&!t.nativeEvent.isComposing){let e=ze.current;if(e){let n=xd(Me,e.selectionStart,e.selectionEnd,t.key,Ze.current);if(n){t.preventDefault();let r=Me.slice(0,n.start)+Me.slice(n.end);ft(r),Ne(r),Tt.current=r,requestAnimationFrame(()=>e.setSelectionRange(n.start,n.start));return}}}if(t.key===`Backspace`&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=ze.current;if(e&&e.selectionStart===e.selectionEnd&&e.selectionStart>0){let n=e.selectionStart,r=u6(Me.slice(0,n),n,g);if(r&&r.tokenStart>=0&&r.tokenStart<n){t.preventDefault();let e=r.tokenStart,i=Me.slice(0,e)+Me.slice(n);vt.current=i,Ne(i),requestAnimationFrame(()=>{ze.current&&(ze.current.selectionStart=ze.current.selectionEnd=e)});let a=r.attachment;a&&_(a.key??(a.mode===`conversation`?`conv|${a.conversationId??``}|${a.sessionPath??``}`:a.path));return}}}if(!e&&(t.key===`ArrowUp`||t.key===`ArrowDown`)){if(t.ctrlKey||t.metaKey||t.altKey)return;let e=ze.current;if(!e)return;let n=t.key===`ArrowUp`,r=L3(e);if(n&&!r.first||!n&&!r.last||!n&&We.current===-1)return;let i=q3();if(i.length===0)return;if(t.preventDefault(),n){if(We.current===-1){Ge.current=Me;let e=i.length-1;We.current=e;let t=i[e];Ne(t),xt(t),requestAnimationFrame(()=>{let e=ze.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else if(We.current>0){let e=We.current-1;We.current=e;let t=i[e];Ne(t),xt(t),requestAnimationFrame(()=>{let e=ze.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}}else{let e=We.current+1;if(e<i.length){We.current=e;let t=i[e];Ne(t),xt(t),requestAnimationFrame(()=>{let e=ze.current;e&&(e.selectionStart=e.selectionEnd=t.length)})}else{We.current=-1;let e=Ge.current;Ne(e),xt(e),requestAnimationFrame(()=>{let t=ze.current;t&&(t.selectionStart=t.selectionEnd=e.length)})}}}else if(t.key===`Escape`&&We.current!==-1){t.preventDefault();let e=Ge.current;We.current=-1,Ne(e),xt(e),requestAnimationFrame(()=>{let t=ze.current;t&&(t.selectionStart=t.selectionEnd=e.length)})}else t6({key:t.key,shiftKey:t.shiftKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,isTouch:l8,pref:xe})===`send`&&(t.preventDefault(),Lt())}},Bt=va({attachments:g,conversationRefSupported:!!ue.conversationRef}),Vt=Mt&&!Bt&&ga(Me,g)&&!(ye&&!Me.trim()),Ht=(0,Q.useMemo)(()=>Kg((I??[]).filter(e=>e.source!==`host`&&!e.hidden)),[I]),Ut=(0,Q.useMemo)(()=>(F??[]).filter(e=>e.source!==`host`&&!e.hidden),[F]),Wt=I!==void 0,Gt=(0,Q.useMemo)(()=>Kg((I??[]).filter(e=>!e.hidden)),[I]),Kt=e=>{if(e.kind===`select`&&e.options?.length){let t=e.options.some(t=>t.value===e.value)?e.value:e.options[0].value;return(0,$.jsx)(`select`,{className:`composer-plugin-select`,title:e.hint||e.label,"aria-label":e.label,value:t,onChange:t=>L?.(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id)}let t=e.icon===`mic`?(0,$.jsx)(k,{}):e.icon===`camera`?(0,$.jsx)(N,{}):e.icon||e.label;return(0,$.jsx)(`button`,{type:`button`,className:`btn composer-plugin-action`,"data-action":e.action,"data-plugin-slot-id":e.id,title:e.hint||e.label,"aria-label":e.label,onClick:()=>L?.(e),children:t},e.id)},qt=ue.steer!==!1,Jt=ie&&!e&&!ve?(0,$.jsx)(`button`,{type:`button`,className:`btn goal-toggle`,title:Y(ye?`goalSendTip`:`goalComposeEnter`),"aria-label":Y(`goalComposeEnter`),"aria-pressed":ye,disabled:!Pe,onClick:()=>{let e=!me;x3(e),S3(e),requestAnimationFrame(()=>ze.current?.focus())},children:(0,$.jsx)(at,{})}):null,Yt=()=>(0,$.jsx)(`div`,{className:`inputbox-actions`,children:c&&!ye?Vt?(0,$.jsxs)(`div`,{className:`split-send${qt?``:` single`}`,children:[(0,$.jsx)(`button`,{type:`button`,className:`split-queue`,title:Y(`supplementTip`),"aria-label":Y(`queueFollowTag`),onClick:()=>Lt(!0),children:(0,$.jsx)(f,{})}),qt&&(0,$.jsx)(`button`,{type:`button`,className:`split-steer`,title:Y(Se?`steerTipMod`:`steerTip`),"aria-label":Y(`queueSteerTag`),onClick:()=>Lt(),children:(0,$.jsx)(te,{})})]}):(0,$.jsx)(`button`,{type:`button`,className:`btn stop`,title:Y(`stopAgent`),onClick:()=>s?s():Z({type:`abort`}),children:(0,$.jsx)(_t,{})}):(0,$.jsx)(`button`,{type:`button`,className:`btn send${ye?` goal`:``}`,title:Y(Bt?Bt.key:ye?`goalSendTip`:Pe?Mt?Se?`sendTipMod`:`sendTip`:`sessionInitializingNotice`:`netDisconnected`),disabled:!Vt,onClick:()=>Lt(),children:ye?(0,$.jsx)(at,{}):(0,$.jsx)(te,{})})}),Xt={"host:composer-upload":(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:Y(`uploadFile`),disabled:!Pe,onClick:()=>Ue.current?.click(),children:(0,$.jsx)(ct,{})}),"host:composer-screenshot":(0,$.jsx)(j6,{onNotice:w}),"host:composer-templates":(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:Y(`tpl.openPicker`),onClick:Ee,children:(0,$.jsx)(r,{})}),"host:composer-model":(0,$.jsx)(A6,{only:`model`,state:p,models:m,modelsLoading:h,onManageModels:E,providerKeys:D,providers:O,defaultModel:A,compact:!0}),"host:composer-thinking":(0,$.jsx)(A6,{only:`thinking`,state:p,models:m,modelsLoading:h,onManageModels:E,providerKeys:D,compact:!0}),"host:composer-claude-perm":B&&B.length>0&&z?(0,$.jsx)($6,{compact:!0,current:z,modes:B}):null,"host:composer-dsh-perm":V&&V.length>0&&H!==void 0?(0,$.jsx)(ib,{compact:!0,current:R??null,options:V,defaultPreset:H,conversationId:K??``}):null,"host:composer-dsh-preset":U&&U.length>0&&W!==void 0?(0,$.jsx)(Z6,{compact:!0,preset:ee??null,presets:U,defaultPreset:W,blank:G??!1,conversationId:K??``}):null,"host:composer-send":Yt()},Zt=e=>e.source===`host`?(0,$.jsx)(Q.Fragment,{children:Xt[e.id]??null},e.id):Kt(e);return(0,$.jsxs)(`div`,{ref:Be,className:`inputbar`,onDragOver:e=>{e.preventDefault()},onDrop:e=>{e.preventDefault(),e.stopPropagation(),kt(e.dataTransfer?.files??null)},children:[(0,$.jsx)(Db,{attachRowRef:Ve,attachments:g,botDraftMode:fe,onCancelBotDraft:()=>pe(!1),onRemoveAttachment:_,onAnnotateImage:v}),mt&&mt.items.length>0&&(0,$.jsxs)(`div`,{className:`slash-menu`,role:`listbox`,ref:yt,"aria-label":mt.kind===`slash`?Y(`slashCommands`):Y(`atMentions`),"data-menu-kind":mt.kind,children:[(0,$.jsxs)(`div`,{className:`slash-menu-hint`,children:[(0,$.jsx)(`span`,{children:mt.kind===`slash`?Y(`slashMenuHint`):Y(`atMenuHint`)}),(0,$.jsx)(`span`,{className:`slash-menu-close`,onClick:()=>ht(null),children:`Esc`})]}),mt.kind===`slash`?Ct():wt(),e&&mt.kind===`at`&&i&&(0,$.jsx)(`div`,{className:`slash-desc`,role:`status`,children:i})]}),Pt!==null&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>It(`cancel`),children:(0,$.jsxs)(`div`,{className:`slash-help`,role:`dialog`,"aria-modal":`true`,"aria-label":Y(`tpl.confirmFillTitle`),style:{maxWidth:420},onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`div`,{className:`slash-help-head`,children:(0,$.jsx)(`span`,{children:Y(`tpl.confirmFillTitle`)})}),(0,$.jsxs)(`div`,{className:`slash-help-body`,style:{padding:`12px 16px`},children:[(0,$.jsx)(`p`,{style:{margin:`0 0 14px`,lineHeight:1.5},children:Y(`tpl.confirmFillDesc`)}),(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`flex-end`,gap:8,flexWrap:`wrap`},children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,autoFocus:!0,onClick:()=>It(`cancel`),children:Y(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>It(`append`),children:Y(`tpl.confirmFillAppend`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>It(`overwrite`),children:Y(`tpl.confirmFillOverwrite`)})]})]})]})}),Fe&&(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>Ie(!1),children:(0,$.jsxs)(`div`,{className:`slash-help`,style:Le?{width:Le}:void 0,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`slash-help-head`,children:[(0,$.jsxs)(`span`,{children:[`⚡ `,Y(`slashHelpTitle`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>Ie(!1),children:Y(`close`)})]}),(0,$.jsx)(`div`,{className:`slash-help-body`,children:ke.length===0?(0,$.jsx)(`div`,{className:`slash-help-empty`,children:Y(`slashLoading`)}):ke.map(e=>(0,$.jsxs)(`div`,{className:`slash-help-row`,children:[(0,$.jsxs)(`span`,{className:`slash-help-cmd`,children:[`/`,e.name]}),(0,$.jsx)(`span`,{className:`slash-source ${e.source}`,children:Dt[e.source]}),(0,$.jsxs)(`span`,{className:`slash-help-desc`,children:[Ae(e),e.argumentHint&&(0,$.jsx)(`span`,{className:`slash-hint`,children:je(e)})]})]},e.name))})]})}),M&&j.length>0&&(0,$.jsx)(`div`,{className:`quick-row`,"aria-label":Y(`quickPhrases`),ref:He,children:j.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`quick-chip`,title:`${Y(`quickPhrasesTip`,{text:e})}(${Y(`quickPhrasesSendTip`)})`,disabled:!Pe,onClick:()=>Rt(e),onContextMenu:t=>{t.preventDefault(),t.stopPropagation(),Rt(e,!0)},children:e},e))}),(0,$.jsxs)(`div`,{className:`inputbox`,"data-pi-anchor":`composer`,children:[(0,$.jsx)(`div`,{className:`composer-resize${tt!=null&&tt>44?` is-manual`:``}`,"aria-label":Y(tt!=null&&tt>44?`composerResizeFixed`:`composerResize`),role:`separator`,"aria-orientation":`horizontal`,"aria-valuenow":Math.round(tt??40),"aria-valuemin":40,"aria-valuemax":u8,onPointerDown:e=>{e.currentTarget.setPointerCapture?.(e.pointerId);let t=ze.current?.getBoundingClientRect().height;rt.current={startY:e.clientY,startH:typeof t==`number`&&Number.isFinite(t)?t:tt??40,next:null}},onPointerMove:e=>{let t=rt.current;if(!t)return;let n=o8(u8),r=Math.min(n,Math.max(40,t.startH+(t.startY-e.clientY)));t.next=r,nt(r<=44?null:r)},onPointerUp:()=>{let e=rt.current?.next;if(rt.current=null,e!=null)try{if(e<=44)nt(null),localStorage.removeItem(a8);else{let t=Math.round(e);nt(t),localStorage.setItem(a8,String(t))}}catch{}},onPointerCancel:()=>{rt.current=null},onDoubleClick:()=>{nt(null);try{localStorage.removeItem(a8)}catch{}},children:(0,$.jsx)(`span`,{className:`composer-resize-tip`,children:Y(tt!=null&&tt>44?`composerResizeFixed`:`composerResize`)})}),(0,$.jsx)(`input`,{ref:Ue,type:`file`,multiple:!0,hidden:!0,onChange:e=>{kt(e.target.files),e.target.value=``}}),(0,$.jsx)(`textarea`,{ref:ze,value:Me,rows:1,placeholder:e?n?Y(`chatInputGroupPlaceholderWithBot`,{name:n}):Y(`chatInputGroupPlaceholder`):Pe?et&&!ye?Y(`placeholderQuestionSupplement`):c?Y(`placeholderStreaming`):fe?Y(`agentBotsCreatePlaceholder`):ye?Y(`goalBarPlaceholder`):de?Y(`placeholderPlanMode`):Y(Se?`placeholderIdleMod`:`placeholderIdle`,{name:Te}):Y(`placeholderConnecting`),disabled:!Pe,onChange:e=>{Et(e.target.value,e.target.selectionStart??e.target.value.length)},onSelect:e=>{if(mt?.kind===`at`){let t=e.target.selectionStart;(t<mt.start||t>mt.end)&&ht(null)}},onCompositionEnd:$e.onCompositionEnd,onBlur:dt,onKeyDown:zt,onPaste:At}),de&&(0,$.jsxs)(`button`,{type:`button`,style:{display:`inline-flex`,alignItems:`center`,gap:4,fontSize:11,color:`var(--accent, #38bdf8)`,background:`var(--accent-soft, rgba(56, 189, 248, 0.1))`,padding:`2px 8px`,borderRadius:12,position:`absolute`,right:12,top:8,cursor:`pointer`,border:`1px solid var(--border, rgba(255, 255, 255, 0.1))`,zIndex:2},onClick:()=>Z({type:`set_plan_mode`,enabled:!1}),title:Y(`planModeTip`),children:[`📋 `,Y(`planModeBadge`),` `,(0,$.jsx)(`span`,{style:{marginLeft:2,opacity:.7},children:`✕`})]}),e&&Ke&&(0,$.jsxs)(`button`,{type:`button`,style:{display:`inline-flex`,alignItems:`center`,gap:4,fontSize:11,color:`var(--accent, #38bdf8)`,background:`var(--accent-soft, rgba(56, 189, 248, 0.1))`,padding:`2px 8px`,borderRadius:12,position:`absolute`,right:12,top:8,cursor:`pointer`,border:`1px solid var(--border, rgba(255, 255, 255, 0.1))`,zIndex:2},onClick:()=>qe(!1),title:Y(`chatInputGroupPlanModeTip`),children:[`📋 `,Y(`chatInputGroupPlanMode`),` `,(0,$.jsx)(`span`,{style:{marginLeft:2,opacity:.7},children:`✕`})]}),(0,$.jsx)(`div`,{className:`composer-tools`,children:e?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn group-at-btn`,title:Y(`chatInputGroupMentionTip`),onClick:()=>{let e=ze.current,t=e?e.selectionStart:Me.length,n=Me.slice(0,t)+`@`+Me.slice(t);Et(n,t+1),e?.focus()},children:`@`}),(0,$.jsxs)(`button`,{type:`button`,className:`btn group-plan-toggle ${Ke?`active`:``}`,title:Y(`chatInputGroupTaskPlanModeTip`),onClick:()=>qe(e=>!e),children:[(0,$.jsx)(`span`,{className:`group-plan-icon`,children:`📋`}),(0,$.jsx)(`span`,{className:`group-plan-label`,children:Y(`chatInputGroupPlanOnly`)})]})]}),(0,$.jsx)(`div`,{className:`composer-tools-right`,children:Yt()})]}):Wt?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Jt,Ut.map(Kt),Gt.start.map(Zt)]}),Gt.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:Gt.center.map(Zt)}),(0,$.jsx)(`div`,{className:`composer-tools-right`,children:Gt.end.map(Zt)})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`composer-tools-left`,children:[Jt,Ut.map(Kt),(0,$.jsx)(`button`,{type:`button`,className:`btn attach-img`,title:Y(`uploadFile`),disabled:!Pe,onClick:()=>Ue.current?.click(),children:(0,$.jsx)(ct,{})}),Ht.start.map(Kt),(0,$.jsx)(`button`,{type:`button`,className:`btn tpl-open`,title:Y(`tpl.openPicker`),onClick:Ee,children:(0,$.jsx)(r,{})}),(0,$.jsx)(A6,{state:p,models:m,modelsLoading:h,onManageModels:E,providerKeys:D,providers:O,defaultModel:A,compact:!0}),V&&V.length>0&&H!==void 0&&(0,$.jsx)(ib,{compact:!0,current:R??null,options:V,defaultPreset:H,conversationId:K??``}),U&&U.length>0&&W!==void 0&&(0,$.jsx)(Z6,{compact:!0,preset:ee??null,presets:U,defaultPreset:W,blank:G??!1,conversationId:K??``})]}),Ht.center.length>0&&(0,$.jsx)(`div`,{className:`composer-tools-center`,children:Ht.center.map(Kt)}),(0,$.jsxs)(`div`,{className:`composer-tools-right`,children:[Ht.end.map(Kt),Yt()]})]})})]})]})});function f8({onAction:e}){let t=Ff(),n=Rt(!!t),r=(0,Q.useMemo)(()=>t?Hf(t.entries):[],[t]),{items:i,selectParents:a}=(0,Q.useMemo)(()=>Vf(r),[r]),o=(0,Q.useMemo)(()=>Uf(i),[i]),s=(0,Q.useMemo)(()=>typeof window>`u`?!1:o.length>14&&window.innerWidth>=640,[o.length]),c=(0,Q.useMemo)(()=>t?Rf(t.slot,t.target):void 0,[t,t?.slot,t?.target.kind]),l=(0,Q.useRef)(null),u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(-1),[h,g]=(0,Q.useState)(-1),[_,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(0),x=(0,Q.useRef)(-1),S=e=>{x.current=e,m(e)},C=(0,Q.useMemo)(()=>h>=0?Hf(i[h]?.children??[]):[],[i,h]),w=(0,Q.useMemo)(()=>Uf(C),[C]),T=e=>{let n=i[e];t&&n&&!Bf(n,c)&&(n.children?.length?g(e):E(n,t)||Mf())},E=(t,n,r)=>t.source===`host`&&n.onHostAction?n.onHostAction(t,n.target)===!0:(e(t,n.target,r),!1),D=(0,Q.useRef)(T);if((0,Q.useLayoutEffect)(()=>{D.current=T}),(0,Q.useEffect)(()=>{if(!t){x.current=-1,m(-1),g(-1);return}let e=Gf(i,-1,1,c);x.current=e,m(e),g(-1),l.current?.focus()},[t,i,c]),(0,Q.useLayoutEffect)(()=>{if(!t){f(null);return}let e=l.current;if(!e)return;let n=e.getBoundingClientRect();f(Lf(t.x,t.y,n.width,n.height,window.innerWidth,window.innerHeight))},[t,i]),(0,Q.useLayoutEffect)(()=>{let e=u.current,t=l.current;if(h<0||!e||!t){v(!1),b(0);return}let n=e.getBoundingClientRect(),r=t.getBoundingClientRect(),i=window.innerWidth-r.right,a=r.left;v(i<n.width+8&&a>i);let o=n.bottom-(window.innerHeight-8);b(o>0?-Math.min(o,Math.max(0,n.top-8)):0)},[h,i]),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>l.current&&e instanceof Node&&l.current.contains(e),n=t=>{e(t.target)||Mf()},r=t=>{e(t.target)||Mf()},i=()=>Mf();return document.addEventListener(`mousedown`,n,!0),window.addEventListener(`wheel`,r,!0),window.addEventListener(`resize`,i),()=>{document.removeEventListener(`mousedown`,n,!0),window.removeEventListener(`wheel`,r,!0),window.removeEventListener(`resize`,i)}},[t]),(0,Q.useEffect)(()=>{if(!t)return;let e=e=>{let t=Gf(i,x.current,e,c);x.current=t,m(t)},n=t=>{switch(t.key){case`Escape`:t.preventDefault(),Mf();return;case`Tab`:Mf();return;case`ArrowDown`:t.preventDefault(),e(1);return;case`ArrowUp`:t.preventDefault(),e(-1);return;case`ArrowRight`:i[x.current]?.children?.length&&(t.preventDefault(),g(x.current));return;case`ArrowLeft`:h>=0&&(t.preventDefault(),g(-1));return;case`Enter`:case` `:t.preventDefault(),D.current(x.current);return;default:return}};return document.addEventListener(`keydown`,n),()=>document.removeEventListener(`keydown`,n)},[t,i,h,c]),(0,Q.useEffect)(()=>{p<0||l.current?.querySelector(`[data-ctx-active="true"]`)?.scrollIntoView?.({block:`nearest`})},[p]),!t)return null;let O=e=>{let n=a.get(e.id);if(n){if(Bf(n.parent,c))return;t&&!E(n.parent,t,n.value)&&Mf()}else Bf(e,c)||E(e,t)||Mf()},k=(e,t,n)=>{let r=Bf(e,c),i=!!e.children?.length,a=qf(e.icon),o=n&&p===t;return(0,$.jsxs)(`div`,{className:`ctx-menu-itemwrap`,role:`none`,children:[(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`ctx-menu-item${r?` disabled`:``}${o?` active`:``}${i?` has-sub`:``}`,"aria-label":e.label,title:e.hint,"aria-disabled":r||void 0,"aria-haspopup":i?`menu`:void 0,"aria-expanded":i?h===t:void 0,"data-ctx-active":o?`true`:void 0,onMouseEnter:n?()=>{S(t),i&&!r&&g(t)}:void 0,onClick:()=>n?T(t):O(e),children:[a?(0,$.jsx)(`span`,{className:`ctx-menu-icon`,"aria-hidden":`true`,children:a}):null,(0,$.jsx)(`span`,{className:`ctx-menu-label`,children:e.label}),e.badge?(0,$.jsx)(`span`,{className:`ctx-menu-badge`,children:e.badge}):null,i?(0,$.jsx)(`span`,{className:`ctx-menu-caret`,"aria-hidden":`true`,children:`▸`}):null]}),n&&i&&h===t?(0,$.jsx)(`div`,{ref:u,className:`ctx-menu-sub${_?` left`:``}`,role:`menu`,"aria-label":e.label,style:y?{marginTop:y}:void 0,children:w.map(e=>e.kind===`sep`?(0,$.jsx)(`div`,{className:`ctx-menu-sep`,role:`separator`},e.key):k(e.entry,e.index,!1))}):null]},`${e.id}#${t}`)};return(0,Er.createPortal)((0,$.jsx)(`div`,{ref:l,className:`ctx-menu${s?` is-multi-col`:``}`,role:`menu`,"aria-label":t.target.label?`${t.slot}: ${t.target.label}`:t.slot,tabIndex:-1,style:{left:d?.x??t.x,top:d?.y??t.y,zIndex:n,visibility:d?`visible`:`hidden`},onContextMenu:e=>{e.preventDefault(),e.stopPropagation()},children:o.map(e=>e.kind===`sep`?(0,$.jsx)(`div`,{className:`ctx-menu-sep`,role:`separator`},e.key):k(e.entry,e.index,!0))}),document.body)}function p8(e){let t=e.trim().toLowerCase();return/^(yes|allow|approve|confirm|ok|是|允许|同意|确认|放行)/i.test(t)}function m8(e){let t=e.trim().toLowerCase();return/^(no|deny|reject|cancel|block|否|拒绝|取消|阻止)/i.test(t)}function h8(e){if(!e)return{hasRisk:!1,intro:``,command:null,outro:``};let t=/⚠️|danger|warning|高危|危险/i.test(e)||/\b(rm\s+-[a-zA-Z]*r[a-zA-Z]*f|chmod\s+(-R\s+)?777|mkfs|dd\s+if=|chown\s+-R|> \/dev\/|sudo\s+rm|drop\s+database|truncate\s+table)\b/i.test(e),n=e.match(/([\s\S]*?)```(?:[a-zA-Z0-9_-]*)\n([\s\S]*?)```([\s\S]*)/);if(n)return{hasRisk:t,intro:n[1].trim(),command:n[2].trim(),outro:n[3].trim()};let r=e.split(`
|
|
395
|
-
`),i=-1,a=-1;for(let e=0;e<r.length;e++){let t=r[e],n=t.trim();if(/^(printf|rm|npm|npx|git|pnpm|yarn|docker|curl|cat|sh|bash|sudo|cp|mv|find|kill|echo|node|python|cargo|make|set|export|source|env|touch|mkdir|chmod|chown)\b/i.test(n)||/^[A-Za-z_][A-Za-z0-9_]*=/.test(n)||t.startsWith(` `)&&n.length>0||t.startsWith(`$ `))i===-1&&(i=e),a=e;else if(i!==-1&&n.length>0)break}if(i!==-1&&(a>i||/command|命令/i.test(e))){let e=r.slice(0,i).join(`
|
|
396
|
-
`).trim(),n=r.slice(i,a+1).map(e=>e.startsWith(`$ `)?e.slice(2):e.startsWith(` `)?e.trimStart():e).join(`
|
|
397
|
-
`).trim(),o=r.slice(a+1).join(`
|
|
398
|
-
`).trim();if(n.length>0)return{hasRisk:t,intro:e,command:n,outro:o}}return{hasRisk:t,intro:e,command:null,outro:``}}function g8({command:e,hasRisk:t}){let n=X(),{copied:r,copy:i}=Gn({duration:2e3}),[o,s]=(0,Q.useState)(!1),c=(0,Q.useMemo)(()=>e.split(`
|
|
399
|
-
`),[e]),l=c.length>8;return(0,$.jsxs)(`div`,{className:`dialog-cmd-box ${t?`has-risk`:``}`,children:[t&&(0,$.jsxs)(`div`,{className:`dialog-cmd-risk`,children:[(0,$.jsx)(me,{}),(0,$.jsx)(`span`,{children:n(`cmdInspectorRisk`)})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-head`,children:[(0,$.jsxs)(`div`,{className:`dialog-cmd-tag`,children:[(0,$.jsx)(Xe,{}),(0,$.jsx)(`span`,{children:n(`cmdInspectorTitle`)}),(0,$.jsx)(`span`,{className:`dialog-cmd-badge`,children:n(`cmdInspectorLines`,{n:c.length})})]}),(0,$.jsxs)(`div`,{className:`dialog-cmd-actions`,children:[l&&(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>s(e=>!e),title:n(o?`cmdInspectorCollapse`:`cmdInspectorExpand`),children:[o?(0,$.jsx)(a,{}):(0,$.jsx)(D,{}),(0,$.jsx)(`span`,{children:n(o?`cmdInspectorCollapse`:`cmdInspectorExpand`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`cmd-btn-text`,onClick:()=>{i(e)},title:n(`copy`),children:[r?(0,$.jsx)(z,{}):(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{children:n(r?`cmdCopied`:`copy`)})]})]})]}),(0,$.jsx)(`div`,{className:`dialog-cmd-code ${o?`expanded`:``}`,children:(0,$.jsx)(`pre`,{children:(0,$.jsx)(`code`,{children:c.map((e,t)=>(0,$.jsxs)(`div`,{className:`dialog-cmd-line`,children:[(0,$.jsx)(`span`,{className:`cmd-line-num`,children:t+1}),(0,$.jsx)(`span`,{className:`cmd-line-text`,children:e})]},t))})})})]})}function _8({text:e,structuredCode:t}){let n=(0,Q.useMemo)(()=>t?{hasRisk:t.hasRisk??!1,intro:e,command:t.content,outro:``}:h8(e),[e,t]);return n.command?(0,$.jsxs)(`div`,{className:`dialog-prompt dialog-body`,children:[n.intro&&(0,$.jsx)(nl,{text:n.intro,rawHtml:!0,disableMath:!0}),(0,$.jsx)(g8,{command:n.command,hasRisk:n.hasRisk}),n.outro&&(0,$.jsx)(nl,{text:n.outro,rawHtml:!0,disableMath:!0})]}):(0,$.jsx)(`div`,{className:`dialog-prompt dialog-body`,children:(0,$.jsx)(nl,{text:e,rawHtml:!0,disableMath:!0})})}function v8({dialog:e}){let t=X(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(0),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(``),u=t=>{Z({type:`dialog_response`,id:e.id,value:t})};(0,Q.useEffect)(()=>{r(``),a(0),s(!1),l(``)},[e.id]),Lt(()=>u(null));let d=Array.isArray(e.args[0])?e.args[0]:[],f=typeof e.args[0]==`string`?e.args[0]:``,p=e.title&&e.title!==t(`pluginRequest`)?e.title:``,m=p?p.split(`
|
|
400
|
-
`)[0].trim():``,h=d.some(m8),g=d.find(m8)??d[d.length-1]??`No`,_=()=>{let e=c.trim();e&&(ir({text:`${t(`rejectFeedbackPrefix`)}${e}\n`}),er()),u(g)};return(0,Q.useEffect)(()=>{let t=t=>{let n=t.target?.tagName;if(n!==`INPUT`&&n!==`TEXTAREA`){if(e.kind===`select`){if(d.length===0)return;if(t.key===`ArrowDown`)t.preventDefault(),a(e=>(e+1)%d.length);else if(t.key===`ArrowUp`)t.preventDefault(),a(e=>(e-1+d.length)%d.length);else if(t.key===`Enter`&&!t.isComposing)t.preventDefault(),d[i]!==void 0&&u(d[i]);else if((t.key===`y`||t.key===`Y`)&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=d.findIndex(p8);e>=0&&(t.preventDefault(),u(d[e]))}else if((t.key===`n`||t.key===`N`)&&!t.ctrlKey&&!t.metaKey&&!t.altKey){let e=d.findIndex(m8);e>=0&&(t.preventDefault(),u(d[e]))}}else e.kind===`confirm`&&((t.key===`y`||t.key===`Y`||t.key===`Enter`)&&!t.ctrlKey&&!t.metaKey&&!t.altKey?(t.preventDefault(),u(!0)):t.key!==`n`&&t.key!==`N`||t.ctrlKey||t.metaKey||t.altKey||(t.preventDefault(),u(!1)))}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e.kind,e.id,d,i]),(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":e.kind,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:t(`pluginRequest`)}),m&&(0,$.jsx)(`span`,{className:`dialog-title`,title:p,children:m}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:t(`cancel`),onClick:()=>u(null),children:`✕`})]}),(0,$.jsxs)(`div`,{className:`dialog-scroll-body`,children:[e.kind===`select`&&(0,$.jsx)(_8,{text:p,structuredCode:e.code}),e.kind===`confirm`&&(0,$.jsxs)($.Fragment,{children:[p&&(p.includes(`
|
|
401
|
-
`)||p.length>50||!f||e.code)&&(0,$.jsx)(_8,{text:p,structuredCode:e.code}),f&&(0,$.jsx)(`div`,{className:`dialog-prompt dialog-body`,children:(0,$.jsx)(nl,{text:f,rawHtml:!0,disableMath:!0})})]}),e.kind===`input`&&(0,$.jsxs)($.Fragment,{children:[p&&(0,$.jsx)(_8,{text:p,structuredCode:e.code}),(0,$.jsx)(`input`,{className:`dialog-input`,value:n,placeholder:f||t(`inputPlaceholder`),autoFocus:!0,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing&&u(n)}})]})]}),(0,$.jsxs)(`div`,{className:`dialog-footer`,children:[e.kind===`select`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`dialog-options`,children:[d.map((e,t)=>{let n=p8(e),r=m8(e),o=n?`Y`:r?`N`:void 0;return(0,$.jsxs)(`button`,{type:`button`,className:`dialog-option ${t===i?`sel`:``} ${n?`opt-affirmative`:``} ${r?`opt-negative`:``}`,onMouseEnter:()=>a(t),onClick:()=>u(e),children:[(0,$.jsx)(`span`,{className:`dialog-option-text`,children:(0,$.jsx)(nl,{text:e,rawHtml:!0,disableMath:!0})}),o&&(0,$.jsx)(`kbd`,{className:`dialog-opt-badge`,children:o})]},t)}),d.length===0&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:t(`noOptions`)})]}),h&&(0,$.jsx)(`div`,{className:`dialog-reject-box`,children:o?(0,$.jsxs)(`div`,{className:`dialog-reject-input-row`,children:[(0,$.jsx)(`input`,{className:`dialog-input dialog-reject-input`,value:c,placeholder:t(`rejectNotePlaceholder`),autoFocus:!0,onChange:e=>l(e.target.value),onKeyDown:e=>{e.key===`Enter`&&!e.nativeEvent.isComposing?_():e.key===`Escape`&&s(!1)}}),(0,$.jsx)(`button`,{type:`button`,className:`btn btn-sm`,onClick:_,children:t(`rejectWithNoteSubmit`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn btn-sm ghost-btn`,title:t(`cancel`),onClick:()=>s(!1),children:`✕`})]}):(0,$.jsxs)(`button`,{type:`button`,className:`dialog-reject-toggle`,onClick:()=>s(!0),children:[(0,$.jsx)(de,{}),(0,$.jsx)(`span`,{children:t(`rejectWithNote`)})]})})]}),e.kind===`confirm`&&(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:()=>u(!1),children:[t(`cancel`),` `,(0,$.jsx)(`kbd`,{className:`dialog-opt-badge`,children:`N`})]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary`,onClick:()=>u(!0),children:[t(`ok`),` `,(0,$.jsx)(`kbd`,{className:`dialog-opt-badge`,children:`Y`})]})]}),e.kind===`input`&&(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>u(null),children:t(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>u(n),children:t(`ok`)})]})]})]})}function y8(e,t,n){return{id:e,slot:`contextmenu.topbar`,source:`host`,label:t,kind:`action`,order:n,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}}function b8({event:e,entry:t,bar:n,layout:r,uiContextEntries:i,t:a}){e.preventDefault(),e.stopPropagation();let o=e=>{let n={...r?.slots,[t.id]:e},i={...r?.align};e!==`sidebar.left`&&e!==`sidebar.right`||i[t.id]||(i[t.id]=`center`),Z({type:`set_settings`,uiLayout:{...r,slots:n,...i[t.id]?{align:i}:{}}})},s=()=>{let e=new Set(r?.hidden??[]);e.add(t.id);let n=(r?.shown??[]).filter(e=>e!==t.id);Z({type:`set_settings`,uiLayout:{...r,hidden:[...e],shown:n}})},c=()=>{Z({type:`set_settings`,uiLayout:qg(r,t.id)})},l=[];n!==`top`&&l.push(y8(`host:move-top`,a(`moveToTop`),10)),n!==`bottom`&&l.push(y8(`host:move-bottom`,a(`moveToBottom`),20)),n!==`left`&&l.push(y8(`host:move-left`,a(`moveToLeft`),30)),n!==`right`&&l.push(y8(`host:move-right`,a(`moveToRight`),40)),bg.has(t.id)||l.push(y8(`host:hide-item`,a(`uiLayoutHide`),50)),(t.userOverrides&&t.userOverrides.length>0||r?.slots?.[t.id]||r?.labels?.[t.id]||r?.align?.[t.id]||r?.order?.includes(t.id))&&l.push(y8(`host:restore-item`,a(`uiLayoutRestore`),60)),i&&i.length>0&&l.push(...i),jf({x:e.clientX,y:e.clientY,slot:`contextmenu.topbar`,target:{id:t.id,label:t.label},entries:l,onHostAction:e=>{e.id===`host:move-top`?o(`topbar.primary`):e.id===`host:move-bottom`?o(`bottombar`):e.id===`host:move-left`?o(`sidebar.left`):e.id===`host:move-right`?o(`sidebar.right`):e.id===`host:hide-item`?s():e.id===`host:restore-item`&&c()}})}function x8(e){let{entry:t,bar:n,chat:r,view:i,plugins:a,onViewChange:o,onUiAction:s}=e;if(t.kind===`view`){let e=t.view??``,n=i===e,s=(a??r.plugins??[]).find(e=>`plugin:${e.id}`===t.source),c=!!s?.error,l=t.iconSvg||s?.iconSvg,u=t.icon||s?.icon;return{iconNode:l?(0,$.jsx)(pp,{icon:u,iconSvg:l,className:`bar-item-icon plugin-icon-svg`}):u?(0,$.jsx)(`span`,{className:`bar-item-icon bar-item-glyph`,children:u}):null,labelText:t.label,badgeNode:null,isActive:n,isTab:!0,extraClasses:`plugin-tab${c?` broken`:``}`,tipOverride:s?.error?`${t.label}: ${s.error}`:void 0,onClick:()=>o?.(e)}}let c=t.iconSvg,l=t.icon;return{iconNode:c?(0,$.jsx)(pp,{icon:l,iconSvg:c,className:`bar-item-icon plugin-icon-svg`}):l?(0,$.jsx)(`span`,{className:`bar-item-icon bar-item-glyph`,children:l}):null,labelText:t.label,badgeNode:t.badge?(0,$.jsx)(`span`,{className:`bar-item-badge`,children:t.badge}):null,isActive:!1,isTab:!1,extraClasses:n===`bottom`?`status-item status-action chip`:`chip`,onClick:()=>s?.(t)}}function S8(e){return e===`zh-TW`?`TW`:e.startsWith(`zh`)?`ZH`:e.startsWith(`ja`)?`JA`:e.startsWith(`ko`)?`KO`:e.startsWith(`fr`)?`FR`:e.startsWith(`de`)?`DE`:e.startsWith(`es`)?`ES`:e.startsWith(`ru`)?`RU`:e.startsWith(`pt`)?`PT`:e.startsWith(`it`)?`IT`:`EN`}function C8({id:e,bar:t,direction:n,named:r,withName:i,onContextMenu:a,dropdownProps:o}){let s=X(),{locale:c,packs:l,setLocale:u}=_e(),[d,f]=(0,Q.useState)(!1);return(0,$.jsxs)(Zd,{direction:n,align:t===`right`?`right`:`left`,portal:!0,open:d,onOpenChange:f,tip:r(s(`language`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:a,dataBarItem:e,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Qf,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:i(S8(c))})]}),children:[(0,$.jsx)(`div`,{className:`dd-header`,children:s(`language`)}),l.map(e=>(0,$.jsx)(Qd,{active:c===e.code,onClick:()=>{u(e.code),f(!1)},children:e.nativeName},e.code)),o?.onLocaleModalOpen?(0,$.jsxs)(Qd,{onClick:()=>{f(!1),o.onLocaleModalOpen?.()},children:[(0,$.jsx)(ht,{}),` `,s(`localeGetMore`)]}):null]})}function w8({id:e,bar:t,direction:n,named:r,onContextMenu:i,dropdownProps:a}){let o=X(),{locale:s}=_e(),[c,l]=(0,Q.useState)(!1),u=a?.themes??[],d=a?.theme??null,f=u.filter(e=>e.group===`classic`),p=u.filter(e=>e.group!==`classic`),m=e=>{let t=Ye(s)?e.name:e.nameEn??e.name,n=e.scheme===`light`?o(`themeLight`):e.scheme===`dark`?o(`themeDark`):``;return n?(Ye(s),`${t} (${n})`):t};return(0,$.jsxs)(Zd,{direction:n,align:t===`right`?`right`:`left`,portal:!0,open:c,onOpenChange:e=>{l(e),e&&u.length===0&&a?.reloadThemes?.()},tip:r(o(`theme`)),caret:!1,triggerClassName:`bar-item chip`,onContextMenu:i,dataBarItem:e,trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Te,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:r(o(`theme`))})]}),children:[f.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:o(`themeGroupClassics`)}),f.map(e=>(0,$.jsx)(Qd,{active:d===e.id,onClick:()=>{a?.onThemeChange?.(e.id),l(!1)},children:m(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:f.length>0?o(`themeGroupBuiltin`):o(`theme`)}),(0,$.jsx)(Qd,{active:d===null,onClick:()=>{a?.onThemeChange?.(null),l(!1)},children:o(`themeDefault`)}),p.map(e=>(0,$.jsx)(Qd,{active:d===e.id,onClick:()=>{a?.onThemeChange?.(e.id),l(!1)},children:m(e)},e.id)),a?.onThemeModalOpen?(0,$.jsxs)(Qd,{onClick:()=>{l(!1),a.onThemeModalOpen?.()},children:[(0,$.jsx)(ht,{}),` `,o(`themeGetMore`)]}):null]})}function T8({id:e,chat:t,named:n,withName:r,onContextMenu:i,dropdownProps:a}){let o=X(),s=a?.updatesCount??0;return a?.managed?(0,$.jsxs)(`span`,{className:`bar-item chip`,title:o(`updatesManaged`),"data-tip":o(`updatesManaged`),onContextMenu:i,"data-bar-item":e,children:[(0,$.jsx)(ht,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:r(`v${a?.appVersion??t.update?.current??`…`}`)})]}):(0,$.jsx)(`div`,{className:`dropdown right fit`,children:(0,$.jsxs)(`button`,{type:`button`,className:`bar-item chip`,onClick:()=>a?.onOpenUpdateCenter?.(),onContextMenu:i,"data-bar-item":e,title:n(o(`update`)),"data-tip":n(o(`update`)),"aria-haspopup":`dialog`,children:[(0,$.jsx)(ht,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`chip-sub bar-item-text`,children:r(`v${a?.updateVersion??t.update?.current??`…`}`)}),a?.updatePending?(0,$.jsx)(`span`,{className:`update-dot`,title:o(`updateAvailable`,{version:a?.updateTargetVersion??``})}):null,s>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:s})]})})}function E8(e){let t=Math.max(0,e.input??0),n=Math.max(0,e.cacheRead??0),r=Math.max(0,e.cacheWrite??0),i=t+n+r;return{totalInput:i,miss:t,read:n,write:r,hitRate:i>0?Math.min(n/i,1):0,writeRate:i>0?Math.min(r/i,1):0}}var D8=2e3;function O8(e,t,n=D8){return e.filter(e=>t-e.t<=n)}function k8(e,t=D8){if(e.length<2)return 0;let n=e[e.length-1],r=e.find(e=>e.t>=n.t-t)??e[0],i=(n.t-r.t)/1e3;return i<=0?0:Math.max(0,(n.out-r.out)/i)}function A8(e){if(!e)return 0;let t=0;for(let n=0;n<e.length;n++){let r=e.charCodeAt(n);(r>=12352&&r<=12543||r>=13312&&r<=19903||r>=19968&&r<=40959||r>=63744&&r<=64255||r>=65280&&r<=65519||r===12288)&&t++}let n=e.length-t;return Math.round(t+n/4)}function j8(e){let t=0;for(let n of e)n.type===`text`&&typeof n.text==`string`&&n.text?t+=A8(n.text):n.type===`thinking`&&typeof n.thinking==`string`&&n.thinking&&(t+=A8(n.thinking));return t}function M8(e){return e>=1e6?`${(e/1e6).toFixed(1).replace(/\.0$/,``)}M`:e>=1e3?`${(e/1e3).toFixed(1).replace(/\.0$/,``)}K`:String(e)}var N8={systemPrompt:`settingsSystemPrompt`,memoryFiles:`contextMemoryFiles`,tools:`contextTools`,skills:`contextSkills`,toolResults:`contextToolResults`,messages:`messages`,other:`contextOther`};function P8({context:e,bar:t,title:n,onContextMenu:r,children:i}){let a=X(),o=(0,Q.useId)(),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(!1),{panelRef:u,style:d,measure:f}=T_({open:c,anchor:s,side:t===`bottom`?`top`:`bottom`,align:t===`left`?`left`:`right`,onClose:()=>l(!1)}),p=e?.contextWindow??0,m=e?.softCap??0,h=m>0&&m<p?m:p,g=typeof e?.tokens==`number`&&Number.isFinite(e.tokens),_=g&&h>0,v=g?Math.max(0,e.tokens):0,y=e?.contextWindowSource,b=Math.min(100,Math.round(v/(h||1)*100)),x=Math.max(0,h-v),S=e?.categories?.filter(e=>e.tokens>0&&e.category in N8)??[],C=S.length>0,w=S.map(e=>({...e,label:a(N8[e.category])}));return!C&&v>0&&w.push({category:`other`,tokens:v,label:a(`contextUsed`)}),(0,Q.useLayoutEffect)(()=>{c&&f()}),(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:s,type:`button`,className:`bar-item status-item status-ctx bar-item-ctx`,title:c?void 0:n,"data-tip":c?void 0:n,"data-bar-item":`host:ctx`,"aria-label":n,"aria-haspopup":`dialog`,"aria-expanded":c,"aria-controls":c?o:void 0,onContextMenu:r,onClick:()=>l(e=>!e),children:i}),c&&(0,Er.createPortal)((0,$.jsxs)(`div`,{ref:u,id:o,style:d,className:`context-usage-panel`,role:`dialog`,"aria-labelledby":`${o}-title`,children:[(0,$.jsxs)(`header`,{className:`context-usage-header`,children:[(0,$.jsx)(`h3`,{id:`${o}-title`,children:a(`context`)}),(0,$.jsx)(`span`,{children:_?a(`contextPercent`,{percent:b}):`—`})]}),_?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`context-usage-bar`,role:`meter`,"aria-label":a(`contextUsage`),"aria-valuemin":0,"aria-valuemax":h,"aria-valuenow":Math.min(v,h),"aria-valuetext":`${M8(v)} / ${M8(h)}`,children:[w.map(e=>(0,$.jsx)(`span`,{"data-category":e.category,style:{flexGrow:e.tokens}},e.category)),(0,$.jsx)(`span`,{"data-category":`free`,style:{flexGrow:x}})]}),(0,$.jsx)(`p`,{className:`context-usage-tokens`,children:a(C||e?.estimated?`contextTokensEstimated`:`contextTokens`,{used:M8(v),total:M8(h)})}),(0,$.jsxs)(`ul`,{className:`context-usage-categories`,"aria-label":a(`contextUsage`),children:[w.map(e=>(0,$.jsxs)(`li`,{"data-category":e.category,children:[(0,$.jsx)(`span`,{className:`context-usage-dot`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`context-usage-label`,children:e.label}),(0,$.jsx)(`span`,{className:`context-usage-value`,title:e.tokens.toLocaleString(),children:M8(e.tokens)})]},e.category)),(0,$.jsxs)(`li`,{"data-category":`free`,children:[(0,$.jsx)(`span`,{className:`context-usage-dot`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`context-usage-label`,children:a(`contextFree`)}),(0,$.jsx)(`span`,{className:`context-usage-value`,title:x.toLocaleString(),children:M8(x)})]})]}),(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(C?`contextBreakdownEstimate`:`contextBreakdownUnavailable`)}),m>0&&(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(`contextSoftCap`,{cap:M8(m),max:M8(p)})}),y&&(0,$.jsxs)(`p`,{className:`context-usage-note`,children:[a(`contextWindowLabel`),`:`,` `,y===`discovered`?`CLI`:a(y===`override`?`settings`:`unknown`)]})]}):g?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{className:`context-usage-tokens`,children:`${M8(v)} / ${a(`unknown`)}`}),(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(`contextUsageUnavailable`)})]}):(0,$.jsx)(`p`,{className:`context-usage-note`,children:a(`contextUsageUnavailable`)})]}),document.body)]})}function F8({anchor:e,content:t,onClose:n}){let r=(0,Q.useRef)(null),{panelRef:i,style:a,measure:o}=T_({anchor:e,side:`top`,align:`right`,gap:6,onClose:n});return(0,Q.useLayoutEffect)(()=>{let e=r.current;if(!e)return;let n=t.render(e);return o(),()=>{typeof n==`function`&&n(),e.innerHTML=``}},[t]),(0,Q.useEffect)(()=>{let e=i.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>o());return t.observe(e),()=>t.disconnect()},[]),(0,Q.useEffect)(()=>{let t=i.current;return(t?.querySelector(`button`)??t)?.focus({preventScroll:!0}),()=>{e?.isConnected&&e.focus({preventScroll:!0})}},[e,i]),(0,Er.createPortal)((0,$.jsx)(`div`,{ref:i,className:`footer-slot-popover`,style:a,role:`dialog`,"aria-modal":`false`,tabIndex:-1,"data-pi-popover":`footer-slot`,children:(0,$.jsx)(`div`,{ref:r,className:`footer-slot-popover-body`})}),document.body)}var I8={cost:`usageMetricCost`,input:`usageMetricInput`,output:`usageMetricOutput`,cacheRead:`usageMetricCacheRead`,cacheWrite:`usageMetricCacheWrite`,contextTokens:`usageMetricContext`},L8=[`cost`,`input`,`output`,`contextTokens`];function R8(e,t){if(e===`cost`){let e=In(t);return`${e.symbol}${e.value}`}return M8(t)}function z8({samples:e,anchor:t,onClose:n}){let r=X(),i=(0,Q.useId)(),a=Rt(),{panelRef:o,style:s,measure:c}=T_({anchor:t,side:`top`,align:`right`,onClose:n}),[l,u]=(0,Q.useState)(`total`),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(L8);(0,Q.useLayoutEffect)(()=>{c()});let h=(0,Q.useMemo)(()=>Qv(e,l),[e,l]),g=h.map(e=>e.engine),_=(0,Q.useMemo)(()=>Zv(e,{mode:l,engines:d?[d]:void 0,metrics:p}),[e,l,d,p]),v=e.length>0?e[e.length-1].cost:0,y=Nn(v),b=e=>m(t=>t.includes(e)?t.length>1?t.filter(t=>t!==e):t:[...t,e]);return(0,Er.createPortal)((0,$.jsxs)(`div`,{ref:o,id:i,style:{...s,zIndex:a},className:`usage-panel`,role:`dialog`,"aria-labelledby":`${i}-title`,children:[(0,$.jsxs)(`header`,{className:`usage-panel-header`,children:[(0,$.jsx)(`h3`,{id:`${i}-title`,children:r(`usagePanelTitle`)}),(0,$.jsxs)(`span`,{className:`usage-panel-total`,title:r(`cumulativeCost`),children:[y.symbol,y.value]})]}),(0,$.jsxs)(`div`,{className:`usage-panel-modes`,role:`group`,"aria-label":r(`usagePanelMode`),children:[(0,$.jsx)(`button`,{type:`button`,"aria-pressed":l===`total`,onClick:()=>u(`total`),children:r(`usageModeTotal`)}),(0,$.jsx)(`button`,{type:`button`,"aria-pressed":l===`delta`,onClick:()=>u(`delta`),children:r(`usageModeDelta`)})]}),g.length>1?(0,$.jsxs)(`div`,{className:`usage-panel-engines`,role:`group`,"aria-label":r(`usagePanelEngine`),children:[(0,$.jsx)(`button`,{type:`button`,"aria-pressed":d===``,onClick:()=>f(``),children:r(`usagePanelAllEngines`)}),g.map(e=>(0,$.jsx)(`button`,{type:`button`,"aria-pressed":d===e,onClick:()=>f(e),children:e},e))]}):null,e.length===0?(0,$.jsx)(`p`,{className:`usage-panel-empty`,children:r(`usagePanelEmpty`)}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`ul`,{className:`usage-panel-rows`,"aria-label":r(`usagePanelByEngine`),children:h.map(e=>(0,$.jsxs)(`li`,{"data-engine":e.engine,children:[(0,$.jsx)(`span`,{className:`usage-row-engine`,children:e.engine}),(0,$.jsx)(`span`,{className:`usage-row-cost`,children:R8(`cost`,e.cost)}),(0,$.jsx)(`span`,{className:`usage-row-detail`,children:`${r(`usageMetricInput`)} ${M8(e.input)} · ${r(`usageMetricOutput`)} ${M8(e.output)} · ${r(`usageMetricCacheRead`)} ${M8(e.cacheRead)} · ${r(`usageMetricContext`)} ${M8(e.contextTokens)}`}),(0,$.jsx)(`span`,{className:`usage-row-samples`,children:r(`usageSamplesCount`,{count:e.samples})})]},e.engine))}),(0,$.jsx)(`div`,{className:`usage-panel-metrics`,role:`group`,"aria-label":r(`usagePanelMetrics`),children:Uv.map(e=>(0,$.jsxs)(`button`,{type:`button`,"data-metric":e,"aria-pressed":p.includes(e),onClick:()=>b(e),children:[(0,$.jsx)(`span`,{className:`usage-metric-dot`,"aria-hidden":`true`}),r(I8[e])]},e))}),(0,$.jsx)(U8,{chart:_}),(0,$.jsx)(`p`,{className:`usage-panel-note`,children:r(`usagePanelNormalized`)})]})]}),document.body)}var B8=300,V8=96,H8=6;function U8({chart:e}){let t=X(),[n,r]=(0,Q.useState)(null),i=e.count,a=new Map(e.series.map(e=>[e.metric,$v(e.values)])),o=e=>i<=1?B8/2:e/(i-1)*B8,s=(e,t)=>84-(t>0?e/t*78:0),c=n!==null&&n>=0&&n<i?n:null;return(0,$.jsxs)(`div`,{className:`usage-chart`,children:[(0,$.jsxs)(`svg`,{viewBox:`0 0 ${B8} ${V8}`,role:`img`,"aria-label":t(`usagePanelChart`),onMouseMove:e=>{let t=e.currentTarget.getBoundingClientRect();if(t.width<=0||i<=0)return;let n=Math.min(1,Math.max(0,(e.clientX-t.left)/t.width));r(Math.round(n*(i-1)))},onMouseLeave:()=>r(null),children:[(0,$.jsx)(`line`,{className:`usage-chart-axis`,x1:0,y1:84,x2:B8,y2:84}),e.series.map(e=>{let t=a.get(e.metric)??0;if(i===1)return(0,$.jsx)(`circle`,{"data-metric":e.metric,cx:o(0),cy:s(e.values[0]??0,t),r:2},e.metric);let n=e.values.map((e,n)=>`${o(n)},${s(e,t)}`).join(` `);return(0,$.jsx)(`polyline`,{"data-metric":e.metric,points:n},e.metric)}),c===null?null:(0,$.jsx)(`line`,{className:`usage-chart-hover`,x1:o(c),y1:H8,x2:o(c),y2:84})]}),c===null?null:(0,$.jsxs)(`div`,{className:`usage-chart-tip`,style:{left:`${Math.min(92,Math.max(8,o(c)/B8*100))}%`},children:[(0,$.jsx)(`span`,{className:`usage-chart-tip-time`,children:(e=>new Date(e).toLocaleTimeString())(e.times[c])}),e.series.map(e=>(0,$.jsxs)(`span`,{"data-metric":e.metric,children:[t(I8[e.metric]),` `,R8(e.metric,e.values[c]??0)]},e.metric))]})]})}function W8({id:e,chat:t,withName:n,onContextMenu:r}){let i=X(),a=t.ready?`ok`:t.status===`closed`?`error`:`busy`,o=t.ready?i(`connected`):t.status===`closed`?i(`reconnecting`):i(`connecting`),s=t.ready&&typeof t.latencyMs==`number`&&Number.isFinite(t.latencyMs)&&t.latencyMs>=0?Math.round(t.latencyMs):null,c=s===null?null:`${s}ms`,l=s===null?``:s<100?`ok`:s<300?`mid`:`warn`,u=c?`${o} · ${i(`networkLatency`)}: ${c}`:o;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-conn ${a} bar-item-conn`,title:u,"data-tip":u,onContextMenu:r,"data-bar-item":e,children:[(0,$.jsx)(`span`,{className:`status-dot ${a}`}),(0,$.jsx)(`span`,{className:`status-conn-label bar-item-text`,children:n(o)}),c&&(0,$.jsx)(`span`,{className:`status-latency ${l}`,children:c})]})}function G8({bar:e,chat:t,custom:n,onContextMenu:r}){let i=X(),a=t.state,o=a?.stats?.contextUsage,s=o?.softCap??null,c=s!==null&&s>0&&s<(o?.contextWindow??0),l=c?s:o?.contextWindow??0,u=o?.tokens!==null&&o?.tokens!==void 0&&l>0?Math.min(100,Math.round(o.tokens/l*100)):null,d=o?.tokens!==null&&o?.tokens!==void 0?M8(o.tokens):null,f=l>0?M8(l):null,p=o?.contextWindowSource,m=d!==null&&f!==null&&u!==null?`${d} / ${f}`:d!==null&&l<=0?`${d} / ${i(`unknown`)}`:`—`,h=u===null?``:u>=80?`warn`:u>=50?`mid`:`ok`,g=p===`discovered`?`CLI`:p===`override`?i(`settings`):p===`unknown`?i(`unknown`):``,_=c?`${i(`contextUsage`)}: ${M8(o?.tokens??0)} / ${M8(s)} (${i(`softCapMarker`)}, max ${M8(o?.contextWindow??0)})`:s!==null&&s>0?`${i(`contextUsage`)}: ${m} · ${i(`softCapMarker`)}: ${M8(s)}`:`${i(`contextUsage`)}: ${m}${g?` (${g})`:``}`,v=u!==null&&u>0?+(31.42*(1-Math.min(u,100)/100)).toFixed(2):31.42;return(0,$.jsxs)(P8,{context:o,bar:e,title:_,onContextMenu:r,children:[(0,$.jsxs)(`svg`,{className:`ctx-ring ${h}`,viewBox:`0 0 14 14`,width:`13`,height:`13`,"aria-hidden":`true`,children:[(0,$.jsx)(`circle`,{className:`ctx-ring-bg`,cx:`7`,cy:`7`,r:`5`}),u!==null&&u>0&&(0,$.jsx)(`circle`,{className:`ctx-ring-fill`,cx:`7`,cy:`7`,r:`5`,strokeDasharray:31.42,strokeDashoffset:v,"data-percent":u})]}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[n?`${n} `:``,d!==null&&f!==null?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`ctx-val`,children:d}),(0,$.jsx)(`span`,{className:`status-sep`,children:`/`}),(0,$.jsx)(`span`,{className:`ctx-max`,children:f})]}):m]})]},`${t.engine}:${a?.conversationId??a?.sessionId??``}`)}function K8({id:e,chat:n,custom:r,onContextMenu:i}){let a=X(),o=E8(n.state?.stats?.tokens??{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}),s=o.hitRate*100,c=o.totalInput===0?``:o.hitRate>=.7?`ok`:o.hitRate>=.4?`mid`:`warn`,l=o.totalInput>0?`${s.toFixed(1)}%`:`—`,u=a(`cacheHitTip`,{read:M8(o.read),write:M8(o.write),miss:M8(o.miss),input:M8(o.totalInput)}),d=o.totalInput>0?`${a(`cacheHit`)}: ${l} · ${u}`:a(`cacheHit`),f=o.totalInput===0;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-cache bar-item-cache${f?` is-zero`:``}`,title:d,"data-tip":d,onContextMenu:i,"data-bar-item":e,children:[(0,$.jsx)(t,{className:`bar-item-icon`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[r?`${r} `:``,(0,$.jsx)(`b`,{className:`cache-pct ${c}`,children:l})]})]})}function q8({id:e,entry:t,chat:n,custom:r,onUiAction:i,onContextMenu:a}){let o=X(),s=n.state?.stats?.cost??0,c=Nn(s),l=u0(),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null),p=l?.content??null,[m,h]=(0,Q.useState)(!1),g=(0,Q.useRef)(null),_=gy(n.state?.conversationId??``);(0,Q.useEffect)(()=>{p||d(!1)},[p]);let v=c.tooltip||o(`cumulativeCost`),y=s<=0,b=l,x=!!b?.text&&!!(b?.content||b?.action),S=()=>{h(!1),b?.content?d(e=>!e):b?.action&&i?.({...t,action:b.action,source:`plugin:${b.pluginId??``}`})};return(0,$.jsxs)(`span`,{className:`bar-item status-item status-cost bar-item-cost${y?` is-zero`:``}${r?` has-name`:``}`,title:v,"data-tip":v,onContextMenu:a,"data-bar-item":e,children:[r?(0,$.jsx)(`span`,{className:`bar-item-text`,children:r}):null,(0,$.jsxs)(`button`,{ref:g,type:`button`,className:`bar-item-cost-btn`,"aria-label":o(`usagePanelOpen`),"aria-haspopup":`dialog`,"aria-expanded":m,onClick:()=>{d(!1),h(e=>!e)},children:[c.symbol?(0,$.jsx)(`span`,{className:`bar-item-char`,children:c.symbol}):null,(0,$.jsx)(`span`,{className:`bar-item-text`,children:c.value})]}),b?(0,$.jsxs)(`span`,{ref:f,className:`cost-quota${x?` is-clickable`:``}`,"data-bar-item":`host:cost-quota`,"data-plugin":b.pluginId??``,title:b.tip||b.text,"data-tip":b.tip||b.text,role:x?`button`:void 0,tabIndex:x?0:void 0,"aria-haspopup":b?.content?`dialog`:void 0,"aria-expanded":b?.content?u:void 0,onClick:x?S:void 0,onKeyDown:x?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),S())}:void 0,children:[(0,$.jsx)(`span`,{className:`bar-item-char`,children:`/`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:b.text})]}):null,b?.content&&u?(0,$.jsx)(F8,{anchor:f.current,content:b.content,onClose:()=>d(!1)}):null,m?(0,$.jsx)(z8,{samples:_,anchor:g,onClose:()=>h(!1)}):null]})}function J8({id:e,chat:t,withName:n,onContextMenu:r}){let i=X(),a=t.state?.stats?.totalMessages??0,o=`${i(`sessionMessages`)}: ${a}`;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-msg-count bar-item-msg-count${a===0?` is-zero`:``}`,title:o,"data-tip":o,onContextMenu:r,"data-bar-item":e,children:[(0,$.jsx)(Xf,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:n(String(a))})]})}function Y8({id:e,chat:t,named:n,onContextMenu:r}){let i=X(),a=t.state,o=a?.isStreaming??!1,s=a?.turnTiming,c=!!s&&s.finishedAt===void 0,[l,u]=(0,Q.useState)(Date.now);(0,Q.useEffect)(()=>{if(!c)return;u(Date.now());let e=window.setInterval(()=>u(Date.now()),1e3);return()=>window.clearInterval(e)},[c,s?.startedAt]);let d=(0,Q.useRef)([]),f=a?.streamingMessage?j8(a.streamingMessage.content):0;(0,Q.useEffect)(()=>{if(!o){d.current=[];return}let e=Date.now(),t=d.current,n=t[t.length-1];n&&e-n.t<250||(d.current=O8([...t,{t:e,out:f}],e))},[o,f]);let p=o?k8(d.current):0;if(!o&&!s)return null;let m=o||c,h=i(m?`working`:`done`),g=s?Math.max(0,Math.floor(((s.finishedAt??l)-s.startedAt)/1e3)):0,_=g<3600?`${Math.floor(g/60)}:${String(g%60).padStart(2,`0`)}`:`${Math.floor(g/3600)}:${String(Math.floor(g/60)%60).padStart(2,`0`)}:${String(g%60).padStart(2,`0`)}`,v=(a?.queue?.steering?.length??0)+(a?.queue?.followUp?.length??0);return(0,$.jsxs)(`span`,{className:`bar-item status-item bar-item-working${m?` working`:``}`,title:`${h}${s?` · ${_}`:``}`,"data-tip":`${h}${s?` · ${_}`:``}`,onContextMenu:r,"data-bar-item":e,children:[m&&(0,$.jsx)(`span`,{className:`working-spin`}),(0,$.jsxs)(`span`,{className:`bar-item-text`,children:[n(h),v>0&&` ⏳ ${v}`]}),s&&(0,$.jsx)(`span`,{className:`bar-item-duration`,children:_}),m&&p>0&&(0,$.jsx)(`span`,{className:`status-rate bar-item-rate`,title:i(`rateTip`),children:`${Math.round(p)}${i(`tps`)}`})]})}function X8({id:e,chat:t,named:n,onContextMenu:r}){let i=X(),a=t.state;return a?.delegateMode?(0,$.jsxs)(`span`,{className:`bar-item status-item delegate-badge bar-item-delegate`,title:a.delegateConvId?i(`delegateModeOpenTip`):i(`delegateModeBadgeTip`),"data-tip":a.delegateConvId?i(`delegateModeOpenTip`):i(`delegateModeBadgeTip`),onContextMenu:r,"data-bar-item":e,children:[(0,$.jsx)(`span`,{className:`bar-item-icon`,children:`🔎`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:n(i(`delegateModeBadge`))}),a.delegateConvId?(0,$.jsx)(`button`,{type:`button`,className:`delegate-badge-open`,title:i(`delegateModeOpenTip`),onClick:()=>Z({type:`switch_conversation`,id:a.delegateConvId}),children:`↗`}):null]}):null}function Z8({id:e,chat:t,withName:n,onContextMenu:r}){let i=X(),a=t.hostMetrics;if(!a)return null;let o=a.cpuPercent===null||!Number.isFinite(a.cpuPercent)?`—`:`${Math.round(a.cpuPercent)}%`,s=Number.isFinite(a.memoryPercent)?`${Math.round(a.memoryPercent)}%`:`—`;return(0,$.jsxs)(`span`,{className:`bar-item status-item status-host-metrics bar-item-host-metrics`,title:`${i(`hostResourcesTip`)}\n${i(`hostProcessor`)}: ${o} · ${i(`hostMemory`)}: ${s}`,"data-tip":`${i(`hostResourcesTip`)}\n${i(`hostProcessor`)}: ${o} · ${i(`hostMemory`)}: ${s}`,onContextMenu:r,"data-bar-item":e,children:[(0,$.jsx)(fe,{className:`bar-item-icon`}),(0,$.jsx)(`span`,{className:`bar-item-text`,children:n(`${o} · ${s}`)})]})}var Q8=`pi-web-ui:quiet-mode`,$8={enabled:!1,style:`fold`};function ex(e){if(!e||typeof e!=`object`)return{...$8};let t=e;return{enabled:typeof t.enabled==`boolean`?t.enabled:$8.enabled,style:t.style===`zero`?`zero`:$8.style}}function tx(){try{let e=localStorage.getItem(Q8);return e?ex(JSON.parse(e)):{...$8}}catch{return{...$8}}}var nx=null,rx=new Set;function ix(e){let t=ex(e);try{localStorage.setItem(Q8,JSON.stringify(t))}catch{}nx=t;for(let e of rx)e()}function ax(e){return rx.add(e),()=>{rx.delete(e)}}function ox(){return nx||=tx(),nx}function sx(){return(0,Q.useSyncExternalStore)(ax,ox)}var cx=`(max-width: 640px), (pointer: coarse)`;function lx(){return typeof window>`u`||typeof window.matchMedia!=`function`?!1:window.matchMedia(cx).matches}function ux(){let[e,t]=(0,Q.useState)(lx);return(0,Q.useEffect)(()=>{if(typeof window>`u`||typeof window.matchMedia!=`function`)return;let e=window.matchMedia(cx),n=()=>t(e.matches);return n(),e.addEventListener(`change`,n),()=>e.removeEventListener(`change`,n)},[]),e}var dx=84,fx=56,px=480;function mx(e){return e.remark?.trim()?e.remark.trim():e.name}function hx(e){return e.length>12?e.slice(0,8):e}async function gx(e){try{if(navigator.clipboard?.writeText)return await navigator.clipboard.writeText(e),!0}catch{}try{let t=document.createElement(`textarea`);t.value=e,t.setAttribute(`readonly`,``),t.style.position=`fixed`,t.style.opacity=`0`,document.body.append(t),t.select();let n=document.execCommand(`copy`);return t.remove(),n}catch{return!1}}function _x({devices:e,error:t,currentDeviceId:n,targetOf:r,onOpen:i,onRemark:a,onRefresh:o,mobile:s}){let c=X(),[l,u]=(0,Q.useState)(null),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(!1),[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)(null),[y,b]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(0),[w,T]=(0,Q.useState)(!1),[E,D]=(0,Q.useState)(``),O=(0,Q.useRef)(null),k=(0,Q.useRef)(null),A=(0,Q.useRef)(null),j=(0,Q.useRef)(null),M=(0,Q.useRef)(0),N=(0,Q.useRef)(o),P=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{N.current=o},[o]);function F(){b(!0),N.current(),window.setTimeout(()=>b(!1),900)}let I=Rt(!!h),L=T_({open:!!h,anchor:h?.anchor??null,align:`right`,gap:4,onClose:()=>g(null)});Lt(()=>(u(null),!0),!!l),(0,Q.useEffect)(()=>{if(!l)return;let e=k.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length))},[l]),(0,Q.useEffect)(()=>{let e=O.current;if(!e||!s)return;let t=0,n=!1,r=r=>{e.scrollTop>0||r.touches.length!==1||(t=r.touches[0].clientY,n=!0,P.current=0)},i=r=>{if(!n)return;let i=r.touches[0].clientY-t;i<=0?(P.current=0,C(0),T(!1)):e.scrollTop>0?(n=!1,P.current=0,C(0),T(!1)):(P.current=i,C(Math.min(fx,i*.5)),T(i>=dx),i>8&&r.cancelable&&r.preventDefault())},a=()=>{if(!n)return;n=!1;let e=P.current>=dx;P.current=0,C(0),T(!1),e&&F()};return e.addEventListener(`touchstart`,r,{passive:!0}),e.addEventListener(`touchmove`,i,{passive:!1}),e.addEventListener(`touchend`,a),e.addEventListener(`touchcancel`,a),()=>{e.removeEventListener(`touchstart`,r),e.removeEventListener(`touchmove`,i),e.removeEventListener(`touchend`,a),e.removeEventListener(`touchcancel`,a)}},[s]);function R(){A.current&&=(clearTimeout(A.current),null),j.current=null}function B(e){g(null),D(``),u(e.id),f(e.remark??``)}async function V(e,t){if(p)return;m(!0);let n=await a(e.id,t.trim());m(!1),n?(u(null),f(``)):k.current?.focus()}function H(e,t){s&&(e.target instanceof Element&&e.target.closest(`button`)||(R(),j.current={x:e.clientX,y:e.clientY},A.current=setTimeout(()=>{A.current=null,M.current=Date.now()+900,navigator.vibrate?.(8),B(t)},px)))}function ee(e){let t=j.current;t&&Math.abs(e.clientX-t.x)+Math.abs(e.clientY-t.y)>10&&R()}let U=l?e.find(e=>e.id===l):void 0,W=E||t;return(0,$.jsxs)(`div`,{className:`dp-panel${s?` is-mobile`:``}`,children:[(0,$.jsxs)(`div`,{className:`dp-head`,children:[(0,$.jsx)(`span`,{className:`dp-title`,children:c(`devicePanel.title`)}),(0,$.jsx)(`span`,{className:`dp-count`,children:e.length}),(0,$.jsx)(`span`,{className:`dp-spacer`}),(0,$.jsx)(`button`,{type:`button`,className:`dp-icon dp-refresh${y?` is-spinning`:``}`,"aria-label":c(`deviceDirectory.refresh`),title:c(`devicePanel.refreshHint`),onClick:F,children:(0,$.jsx)(pe,{"aria-hidden":!0})})]}),W&&(0,$.jsx)(`p`,{className:`dp-notice`,role:`alert`,children:W}),(0,$.jsxs)(`div`,{className:`dp-scroll`,ref:O,children:[(0,$.jsx)(`div`,{className:`dp-pull`,style:{height:S},"aria-hidden":S===0,children:S>0&&(0,$.jsx)(`span`,{className:`dp-pull-text`,children:c(w?`devicePanel.releaseToRefresh`:`devicePanel.pullToRefresh`)})}),(0,$.jsxs)(`ul`,{className:`dp-list`,children:[e.length===0&&(0,$.jsx)(`li`,{className:`dp-empty`,children:c(`devicePanel.empty`)}),e.map(e=>{let t=e.remark?.trim()?e.remark.trim():e.name,a=e.id===n,o=l===e.id,m=h?.device.id===e.id,_=a?void 0:r(e.id),y=[hx(e.id),e.online?``:c(`deviceHubOffline`)].filter(Boolean).join(` · `);return(0,$.jsxs)(`li`,{className:`dp-row${e.online?``:` is-off`}${o?` is-editing`:``}`,onPointerDown:t=>H(t,e),onPointerMove:ee,onPointerUp:R,onPointerCancel:R,onPointerLeave:R,children:[(0,$.jsx)(`span`,{className:`dp-dot${e.online?` is-on`:``}`,"aria-hidden":!0}),_&&(0,$.jsx)(`a`,{className:`dp-hit`,href:_,target:`_blank`,rel:`noopener noreferrer`,"aria-label":e.online?c(`devicePanel.openDevice`,{name:t}):c(`devicePanel.openDeviceOffline`,{name:t}),title:`${t} · ${e.id}`,onClick:t=>{Date.now()<M.current?t.preventDefault():i(t,e.id)}}),(0,$.jsxs)(`span`,{className:`dp-main`,children:[(0,$.jsxs)(`span`,{className:`dp-name`,children:[(0,$.jsx)(`strong`,{title:t,children:t}),a&&(0,$.jsx)(`em`,{className:`dp-tag`,children:c(`deviceDirectory.thisDevice`)})]}),o&&!s?(0,$.jsx)(`input`,{ref:k,className:`dp-input`,type:`text`,maxLength:80,value:d,disabled:p,placeholder:c(`devicePanel.remarkPlaceholder`),onChange:e=>f(e.target.value),onKeyDown:t=>{t.key===`Enter`&&(t.preventDefault(),V(e,d)),t.key===`Escape`&&(t.preventDefault(),u(null))},onBlur:()=>u(null)}):(0,$.jsx)(`span`,{className:`dp-sub`,title:e.id,children:y})]}),(0,$.jsx)(`span`,{className:`dp-actions`,children:o&&!s?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{type:`button`,className:`dp-icon`,"aria-label":c(`devicePanel.saveRemark`),disabled:p,onMouseDown:e=>e.preventDefault(),onClick:()=>void V(e,d),children:(0,$.jsx)(z,{"aria-hidden":!0})}),(0,$.jsx)(`button`,{type:`button`,className:`dp-icon`,"aria-label":c(`cancel`),disabled:p,onMouseDown:e=>e.preventDefault(),onClick:()=>u(null),children:(0,$.jsx)(Ct,{"aria-hidden":!0})})]}):(0,$.jsxs)($.Fragment,{children:[!a&&(0,$.jsx)(`button`,{type:`button`,className:`dp-icon`,"aria-label":c(`deviceDirectory.remoteDesktop`),title:c(`deviceDirectory.remoteDesktop`),onClick:t=>{R(),i(t,e.id,!0)},children:(0,$.jsx)(se,{"aria-hidden":!0})}),(0,$.jsx)(`button`,{type:`button`,className:`dp-icon`,"aria-label":c(`devicePanel.moreActions`),"aria-haspopup":`menu`,"aria-expanded":m,onClick:t=>{R(),D(``),v(null);let n=t.currentTarget;g(t=>t?.device.id===e.id?null:{device:e,anchor:n})},children:(0,$.jsx)(x,{"aria-hidden":!0})})]})}),_?(0,$.jsx)(At,{className:`dp-chev`,"aria-hidden":!0}):(0,$.jsx)(`span`,{className:`dp-chev`,"aria-hidden":!0})]},e.id)})]})]}),h&&(0,Er.createPortal)((0,$.jsxs)(`div`,{ref:L.panelRef,style:{...L.style,zIndex:I},className:`dp-menu`,role:`menu`,"aria-label":mx(h.device),children:[(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{B(h.device)},children:[(0,$.jsx)(et,{"aria-hidden":!0}),h.device.remark?.trim()?c(`deviceDirectory.editRemark`):c(`deviceDirectory.setRemark`)]}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{let{device:e}=h;gx(e.id).then(t=>{t?(v(e.id),setTimeout(()=>{v(t=>t===e.id?null:t),g(null)},900)):(D(c(`devicePanel.copyFailed`)),g(null))})},children:[_===h.device.id?(0,$.jsx)(z,{"aria-hidden":!0}):(0,$.jsx)(st,{"aria-hidden":!0}),_===h.device.id?c(`copied`):c(`devicePanel.copyDeviceId`)]})]}),document.body),U&&s&&(0,$.jsxs)(`form`,{className:`dp-editbar`,onSubmit:e=>{e.preventDefault(),V(U,d)},children:[(0,$.jsx)(`input`,{ref:k,className:`dp-editbar-input`,type:`text`,maxLength:80,value:d,disabled:p,"aria-label":c(`devicePanel.remarkAria`),placeholder:c(`devicePanel.remarkPlaceholderNamed`,{name:U.remark?.trim()||U.name}),onChange:e=>f(e.target.value),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),u(null))}}),(0,$.jsx)(`button`,{type:`submit`,className:`dp-save`,disabled:p,children:c(p?`saving`:`save`)}),(0,$.jsx)(`button`,{type:`button`,className:`dp-icon dp-cancel`,"aria-label":c(`cancel`),disabled:p,onClick:()=>u(null),children:(0,$.jsx)(Ct,{"aria-hidden":!0})})]})]})}function vx(e,t){try{let n=new URL(e);return![`http:`,`https:`].includes(n.protocol)||n.username||n.password?void 0:new URL(`/device/${encodeURIComponent(t)}`,n).href}catch{return}}function yx({hubUrl:e,currentDeviceId:t,onRemarkUpdated:n,onAfterOpen:r,variant:i=`page`,mobile:a=!1}){let o=X(),[s,c]=(0,Q.useState)([]),[l,u]=(0,Q.useState)(``),[d,f]=(0,Q.useState)(0),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(``),[_,v]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=await fetch(W(j(`/api/device-center/devices`)),{signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)]),credentials:`same-origin`});if(!n.ok)throw Error(n.status===409?o(`deviceDirectory.pairAgain`):o(`deviceDirectory.loadFailed`));let r=await n.json();if(!Array.isArray(r.devices))throw Error(o(`deviceDirectory.invalidList`));e||(c(r.devices),u(``))}catch(t){e||(c([]),u(t instanceof Error?t.message:String(t)))}finally{e||(n=setTimeout(r,5e3))}}return r(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[e,t,d,o]);async function y(t,n,i=!1){t.preventDefault();try{await Hd(n,e,i,o,!1,s.find(e=>e.id===n)?.name),u(``),r?.()}catch(e){u(e instanceof Error?e.message:String(e))}}async function b(e,t){v(e);let r=t.trim();try{return await ln(`/api/device-center/devices/${encodeURIComponent(e)}/remark`,{body:{remark:r},errorFor:e=>Error(e.serverError||o(`deviceDirectory.saveRemarkFailed`))}),c(t=>t.map(t=>t.id===e?{...t,remark:r||void 0}:t)),m(null),u(``),n?.(e,r),window.dispatchEvent(new CustomEvent(`pi-web-ui:device-remark-updated`,{detail:{deviceId:e,remark:r||void 0}})),!0}catch(e){return u(e instanceof Error?e.message:String(e)),!1}finally{v(null)}}return i===`panel`?(0,$.jsx)(_x,{devices:s,error:l,currentDeviceId:t,targetOf:t=>vx(e,t),onOpen:y,onRemark:b,onRefresh:()=>f(e=>e+1),mobile:a}):(0,$.jsxs)(`section`,{className:`dc-card`,"aria-label":o(`deviceDirectory.allDevices`),children:[(0,$.jsxs)(`div`,{className:`dc-card-header`,children:[(0,$.jsx)(`span`,{className:`dc-icon`,children:(0,$.jsx)(se,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`h2`,{children:[o(`deviceDirectory.allDevices`),` · `,s.length]}),(0,$.jsx)(`p`,{children:o(`deviceDirectory.intro`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`dc-icon-button`,"aria-label":o(`deviceDirectory.refresh`),onClick:()=>f(e=>e+1),children:(0,$.jsx)(pe,{})})]}),l&&(0,$.jsx)(`p`,{className:`dc-notice is-error`,role:`alert`,children:l}),(0,$.jsx)(`div`,{className:`dd-list`,children:s.map(n=>{let r=!!n.remark?.trim(),i=r?n.remark.trim():n.name,a=p===n.id;return(0,$.jsxs)(`div`,{className:`dd-device`,style:a?{flexWrap:`wrap`}:void 0,children:[(0,$.jsx)(`span`,{className:`dc-device-icon`,children:(0,$.jsx)(se,{"aria-hidden":!0})}),(0,$.jsxs)(`div`,{className:`dd-identity`,children:[(0,$.jsx)(`strong`,{children:i}),(0,$.jsxs)(`span`,{children:[r?`${n.name} · `:``,n.id===t?o(`deviceDirectory.thisDevice`):n.id]})]}),(0,$.jsx)(`span`,{className:`dc-status ${n.online?`is-online`:`is-offline`}`,children:n.online?o(`deviceHubOnline`):o(`deviceHubOffline`)}),(0,$.jsxs)(`div`,{className:`dc-actions`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,title:o(r?`deviceDirectory.editRemark`:`deviceDirectory.setRemark`),onClick:()=>{a?m(null):(m(n.id),g(n.remark??``))},children:[(0,$.jsx)(et,{"aria-hidden":!0}),o(r?`deviceDirectory.editRemark`:`deviceDirectory.setRemark`)]}),vx(e,n.id)&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`a`,{className:`dc-button`,href:vx(e,n.id),target:`_blank`,rel:`noopener noreferrer`,onClick:e=>void y(e,n.id),children:[(0,$.jsx)(Be,{"aria-hidden":!0}),o(`deviceDirectory.openDevice`)]}),(0,$.jsxs)(`a`,{className:`dc-button`,href:`${vx(e,n.id)}/desktop`,target:`_blank`,rel:`noopener noreferrer`,onClick:e=>void y(e,n.id,!0),children:[(0,$.jsx)(se,{"aria-hidden":!0}),o(`deviceDirectory.remoteDesktop`)]})]})]}),a&&(0,$.jsxs)(`form`,{className:`dd-remark-form`,style:{display:`flex`,alignItems:`center`,gap:`8px`,width:`100%`,paddingTop:`8px`,paddingBottom:`4px`},onSubmit:e=>{e.preventDefault(),b(n.id,h)},children:[(0,$.jsx)(`input`,{type:`text`,maxLength:80,autoFocus:!0,disabled:_===n.id,placeholder:o(`deviceDirectory.remarkPlaceholder`),value:h,onChange:e=>g(e.target.value),style:{flex:1,minWidth:`180px`,background:`var(--bg)`,border:`1px solid var(--border)`,borderRadius:`6px`,padding:`6px 10px`,color:`var(--text)`,fontSize:`12px`}}),(0,$.jsxs)(`button`,{type:`submit`,className:`dc-button is-primary`,disabled:_===n.id,children:[(0,$.jsx)(z,{"aria-hidden":!0}),_===n.id?o(`saving`):o(`save`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`dc-button`,disabled:_===n.id,onClick:()=>m(null),children:[(0,$.jsx)(Ct,{"aria-hidden":!0}),o(`cancel`)]})]})]},n.id)})})]})}var bx=80;function xx({label:e=`pi-web-ui`,barItem:t=!1,onContextMenu:n}){let r=X(),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(!1),c=(0,Q.useRef)(null),l=ux(),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(0),[p,m]=(0,Q.useState)(0),h=Rt(o&&l),g=(0,Q.useCallback)(()=>{s(!1),m(0),f.current=0},[]),{panelRef:_,style:v}=T_({open:o&&!!i&&!l,anchor:c,align:`left`,onClose:g});(0,Q.useEffect)(()=>{let e=!1,t,n;async function r(){t=new AbortController;try{let n=await fetch(W(j(`/api/device-center/chat-status`)),{credentials:`same-origin`,signal:AbortSignal.any([t.signal,AbortSignal.timeout(15e3)])});if(!n.ok)return;let r=await n.json();if(!e){let e=r.local!==!0&&typeof r.hubUrl==`string`&&!!r.hubUrl&&typeof r.deviceId==`string`&&!!r.deviceId;a(e?{hubUrl:r.hubUrl,deviceId:r.deviceId}:null),e||s(!1)}}catch{}finally{e||(n=setTimeout(r,15e3))}}return r(),()=>{e=!0,t?.abort(),clearTimeout(n)}},[]),Lt(g,o&&l),(0,Q.useEffect)(()=>{o&&l&&u.current?.focus()},[o,l]),(0,Q.useEffect)(()=>{if(!o||!l)return;let e=e=>{if(d.current===null)return;let t=Math.max(0,e.clientY-d.current);f.current=t,m(t)},t=()=>{d.current!==null&&(d.current=null,f.current>bx?g():m(0),f.current=0)};return window.addEventListener(`pointermove`,e),window.addEventListener(`pointerup`,t),window.addEventListener(`pointercancel`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t),window.removeEventListener(`pointercancel`,t)}},[o,l,g]);let y=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`img`,{className:t?`brand-logo bar-item-brand-logo bar-item-icon`:`brand-logo`,src:`${We()}icons/icon-192.png`,alt:`keel`,width:26,height:26,draggable:!1}),(0,$.jsx)(`span`,{className:t?`brand-name bar-item-text`:`brand-name`,children:e})]}),b=t?`bar-item brand bar-item-brand`:`brand`;return i?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:c,"data-bar-item":t?`host:brand`:void 0,onContextMenu:n,type:`button`,className:`${b} brand-device-trigger`,title:r(`brandDeviceList`),"aria-label":r(`brandDeviceList`),"aria-haspopup":`dialog`,"aria-expanded":o,onClick:()=>s(e=>!e),children:y}),o&&i&&(0,Er.createPortal)(l?(0,$.jsxs)(`div`,{className:`dp-sheet-layer`,style:{zIndex:h},children:[(0,$.jsx)(`div`,{className:`dp-sheet-scrim`,onClick:g,"aria-hidden":!0}),(0,$.jsxs)(`div`,{ref:u,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":r(`brandDeviceList`),className:`dp-sheet${p>0?` is-dragging`:``}`,style:p>0?{transform:`translateY(${p}px)`}:void 0,children:[(0,$.jsx)(`div`,{className:`dp-sheet-grab`,role:`presentation`,onPointerDown:e=>{d.current=e.clientY,f.current=0},children:(0,$.jsx)(`span`,{className:`dp-grab`})}),(0,$.jsx)(yx,{hubUrl:i.hubUrl,currentDeviceId:i.deviceId,variant:`panel`,mobile:!0,onAfterOpen:g})]})]}):(0,$.jsx)(`div`,{ref:_,style:v,className:`brand-device-panel`,role:`dialog`,"aria-label":r(`brandDeviceList`),children:(0,$.jsx)(yx,{hubUrl:i.hubUrl,currentDeviceId:i.deviceId,variant:`panel`,onAfterOpen:g})}),document.body)]}):(0,$.jsx)(`span`,{className:b,"data-bar-item":t?`host:brand`:void 0,onContextMenu:n,children:y})}function Sx(){return typeof window<`u`?window.piDesktop?.browser:void 0}function Cx(e){let[t,n]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(!e)return;e.getState().then(e=>{e&&typeof e==`object`&&n(e)});let t=e.onState(e=>{e&&typeof e==`object`&&n(e)});return()=>{t?.()}},[e]),t}function wx({onActivate:e,onOpenPanel:t}){let n=X(),{status:r}=t8(),i=Sx(),a=Cx(i),o=()=>{e?.(),t?.()};if(i){let t=a?.mode===`split`,r=a?.mode===`browser`,s=()=>{let n=t||r?`agent`:`split`;i.setMode(n),e?.()},c=n(t?`browserControlSplitCloseTip`:`browserControlSplitOpenTip`);return(0,$.jsx)(`span`,{className:`bc-anchor`,children:(0,$.jsxs)(`button`,{type:`button`,className:`chip browser-control${t?` active`:``}`,"data-tip":c,title:c,onClick:s,onContextMenu:e=>{e.preventDefault(),e.stopPropagation(),o()},children:[(0,$.jsx)(ip,{size:14,"aria-hidden":!0}),(0,$.jsx)(`span`,{children:n(`browserControl`)})]})})}let s=r?.pages??[],c=r?.available===!0&&(s.length===0||r.aiControl===!1);return(0,$.jsx)(`span`,{className:`bc-anchor`,children:(0,$.jsxs)(`button`,{type:`button`,className:`chip browser-control${c?` attention`:``}`,"data-tip":r?.error??n(c?`browserControlEmpty`:`browserControlTip`),title:r?.error??n(c?`browserControlEmpty`:`browserControlTip`),onClick:o,children:[(0,$.jsx)(ip,{size:14,"aria-hidden":!0}),(0,$.jsxs)(`span`,{children:[n(`browserControl`),s.length>0?` · ${s.length}`:``]})]})})}function Tx({onClose:e}){let t=X(),{status:n,refresh:r}=t8(),i=Sx(),a=Cx(i),[o,s]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{if(o===null)return;let e=window.setTimeout(()=>s(null),2600);return()=>window.clearTimeout(e)},[o]),(0,$.jsx)(Ex,{status:n,desktop:i,desktopState:a,onRefresh:r,onCite:e=>{let n=ir({attachments:[$b(e)]});s(t(n?`browserControlCited`:`browserControlCiteFailed`))},onClose:e,flash:o})}function Ex({status:e,desktop:t,desktopState:n,onRefresh:r,onCite:i,onClose:a,flash:o}){let s=X(),[c,l]=(0,Q.useState)(!1),u=e?.pages??[],d=async()=>{l(!0);try{await e8()||r()}finally{l(!1)}},f=async e=>{t&&(await t.setMode(e),a())},p=async()=>{t&&(await t.createTab(),a())};return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:a,children:(0,$.jsxs)(`div`,{className:`modal browser-control-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsx)(`button`,{type:`button`,className:`modal-close`,"aria-label":s(`close`),onClick:a,children:`✕`}),(0,$.jsxs)(`div`,{className:`modal-head`,children:[(0,$.jsx)(ip,{size:16,"aria-hidden":!0}),(0,$.jsx)(`h2`,{children:s(`browserControl`)})]}),(0,$.jsx)(`div`,{className:`modal-desc`,children:s(t?`browserControlDesktopReady`:e?.native?`browserControlNativeLead`:`browserControlTip`)}),o&&(0,$.jsx)(`div`,{className:`bc-note`,children:o}),t&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:s(`browserControlViewMode`)}),(0,$.jsxs)(`div`,{className:`bc-actions`,style:{marginTop:0,marginBottom:12},children:[(0,$.jsxs)(`button`,{type:`button`,className:n?.mode===`split`?`primary`:``,onClick:()=>void f(`split`),children:[(0,$.jsx)(Se,{size:14,style:{marginRight:6}}),s(`browserControlModeSplit`)]}),(0,$.jsxs)(`button`,{type:`button`,className:n?.mode===`browser`?`primary`:``,onClick:()=>void f(`browser`),children:[(0,$.jsx)(F,{size:14,style:{marginRight:6}}),s(`browserControlModeBrowser`)]}),(0,$.jsxs)(`button`,{type:`button`,className:n?.mode===`agent`?`primary`:``,onClick:()=>void f(`agent`),children:[(0,$.jsx)(Et,{size:14,style:{marginRight:6}}),s(`browserControlModeAgent`)]})]}),(0,$.jsx)(`div`,{className:`bc-actions`,style:{marginTop:0,marginBottom:12},children:(0,$.jsxs)(`button`,{type:`button`,onClick:()=>void p(),children:[(0,$.jsx)(ue,{size:14,style:{marginRight:6}}),s(`browserControlNewTab`)]})})]}),t&&n?.tabs&&n.tabs.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:s(`browserControlOpenTabs`)}),(0,$.jsx)(`ul`,{className:`bc-pages`,children:n.tabs.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`span`,{className:`bc-title`,title:e.title||e.url,children:e.title||s(`browserControlNewTabTitle`)}),(0,$.jsx)(`span`,{className:`bc-origin`,title:e.url,children:e.url}),e.id===n.activeTabId&&(0,$.jsx)(`span`,{className:`bc-open current`,children:s(`current`)}),(0,$.jsx)(`button`,{type:`button`,className:`bc-cite`,onClick:()=>{f(`split`)},children:s(`browserControlOpenTab`)})]},e.id))})]}),!t&&e===null&&(0,$.jsx)(`div`,{className:`bc-note`,children:s(`browserControlChecking`)}),!t&&e?.available===!1&&!e.desktop&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:s(`browserControlOffline`)}),!t&&e?.desktop===!0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-note warn`,children:s(`browserControlDesktop`)}),(0,$.jsx)(`div`,{className:`bc-note`,children:s(`browserControlDesktopLead`)}),(0,$.jsx)(`div`,{className:`bc-actions`,style:{marginTop:0},children:(0,$.jsx)(`a`,{className:`btn primary`,href:window.location.href,target:`_blank`,rel:`noreferrer noopener`,children:s(`browserControlOpenInBrowser`)})})]}),!t&&e?.available===!1&&!e.desktop&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:s(`browserControlInstall`)}),(0,$.jsx)(`div`,{className:`bc-note`,children:s(`browserControlInstallLead`)}),(0,$.jsx)(`div`,{className:`bc-actions`,style:{marginTop:0},children:(0,$.jsx)(`a`,{className:`btn primary`,href:`https://github.com/xing-shuyin/keel/releases/latest/download/page-picker-extension.zip`,target:`_blank`,rel:`noreferrer noopener`,children:s(`browserControlInstallDownload`)})}),(0,$.jsxs)(`ol`,{className:`bc-steps`,children:[(0,$.jsx)(`li`,{children:s(`browserControlInstallStep1`)}),(0,$.jsx)(`li`,{children:s(`browserControlInstallStep2`)}),(0,$.jsx)(`li`,{children:s(`browserControlInstallStep3`)}),(0,$.jsx)(`li`,{children:s(`browserControlInstallStep4`)})]})]}),e?.available===!0&&e.aiControl===!1&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:s(e.native?`browserControlNativeDisabled`:`browserControlDisabled`)}),e?.available===!0&&u.length===0&&!t&&(0,$.jsx)(`div`,{className:`bc-note warn`,children:s(e.native?`browserControlNativeEmpty`:`browserControlEmpty`)}),u.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`bc-section`,children:s(`browserControlPages`)}),(0,$.jsx)(`ul`,{className:`bc-pages`,children:u.map(e=>(0,$.jsxs)(`li`,{children:[(0,$.jsx)(`span`,{className:`bc-title`,title:e.title,children:e.title}),(0,$.jsx)(`span`,{className:`bc-origin`,title:e.origin,children:e.origin}),(0,$.jsx)(`span`,{className:`bc-open${e.open?` on`:``}`,children:e.open?s(`browserControlPageOpen`):s(`browserControlPageClosed`)}),e.active===!0&&(0,$.jsx)(`span`,{className:`bc-open current`,children:s(`current`)}),(0,$.jsx)(`button`,{type:`button`,className:`bc-cite`,title:s(`browserControlCiteTip`,{name:e.title||e.origin}),onClick:()=>i(e),children:s(`browserControlCite`)})]},e.tabId??e.origin))}),(0,$.jsx)(`div`,{className:`bc-note`,children:s(`browserControlCiteNote`)})]}),(0,$.jsxs)(`div`,{className:`bc-actions`,children:[!t&&e?.desktop!==!0&&(0,$.jsx)(`button`,{type:`button`,className:`primary`,disabled:c,onClick:()=>void d(),children:s(e?.native?`settings`:`browserControlOpenOptions`)}),(0,$.jsx)(`button`,{type:`button`,onClick:r,children:s(`browserControlRefresh`)})]})]})})}var Dx={pi:{id:`pi`,name:`Pi`,packageName:`@earendil-works/pi-coding-agent`,cliPackageName:null,acpPackageName:null,installCommand:`npm i -g @earendil-works/pi-coding-agent`,cliCommand:`pi`,cliModelArgs:`provider-model`,cliRequiresArgs:!1},claude:{id:`claude`,name:`Claude Code`,packageName:`@anthropic-ai/claude-code`,cliPackageName:null,acpPackageName:`@agentclientprotocol/claude-agent-acp`,installCommand:`npm i -g @anthropic-ai/claude-code`,cliCommand:`claude`,cliModelArgs:`model`,cliRequiresArgs:!1},codex:{id:`codex`,name:`Codex`,packageName:`@openai/codex`,cliPackageName:null,acpPackageName:`@agentclientprotocol/codex-acp`,installCommand:`npm i -g @openai/codex`,cliCommand:`codex`,cliModelArgs:`model`,cliRequiresArgs:!1},agy:{id:`agy`,name:`Antigravity`,packageName:null,cliPackageName:null,acpPackageName:null,installCommand:`https://antigravity.google/docs/getting-started?tab=cli`,cliCommand:`agy`,cliModelArgs:`model`,cliRequiresArgs:!1},opencode:{id:`opencode`,name:`OpenCode`,packageName:`opencode-ai`,cliPackageName:null,acpPackageName:null,installCommand:`npm i -g opencode-ai`,cliCommand:`opencode`,cliModelArgs:`model`,cliRequiresArgs:!1},dsh:{id:`dsh`,name:`DSH`,packageName:`@deepseek-ai/dsh`,cliPackageName:null,acpPackageName:null,installCommand:`npm i -g @deepseek-ai/dsh`,cliCommand:`dsh`,cliModelArgs:null,cliRequiresArgs:!1},durable:{id:`durable`,name:`Pi Durable`,packageName:`@earendil-works/pi-durable`,cliPackageName:null,acpPackageName:null,installCommand:`npm i -g @earendil-works/pi-durable`,cliCommand:null,cliModelArgs:null,cliRequiresArgs:!1}},Ox=[{id:`pi`,titleKey:`settingsEnginePiTitle`,badge:`PI`,tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-pi`},{id:`claude`,titleKey:`settingsEngineClaudeTitle`,badge:`CLAUDE`,tagKey:`engineTagUniversal`,descKey:`settingsEngineClaudeDesc`,colorClass:`engine-claude`},{id:`codex`,titleKey:`settingsEngineCodexTitle`,badge:`CODEX`,tagKey:`engineTagUniversal`,descKey:`settingsEngineCodexDesc`,colorClass:`engine-codex`},{id:`agy`,titleKey:`settingsEngineAgyTitle`,badge:`AGY`,tagKey:`engineTagUniversal`,descKey:`settingsEngineAgyDesc`,colorClass:`engine-agy`},{id:`opencode`,titleKey:`settingsEngineOpencodeTitle`,badge:`OPENCODE`,tagKey:`engineTagUniversal`,descKey:`settingsEngineOpencodeDesc`,colorClass:`engine-opencode`},{id:`dsh`,titleKey:`settingsEngineDshTitle`,badge:`DSH`,tagKey:`engineTagUniversal`,descKey:`settingsEngineDshDesc`,colorClass:`engine-dsh`},{id:`durable`,titleKey:`settingsEngineDurableTitle`,badge:`DURABLE`,tagKey:`engineTagDurable`,descKey:`settingsEngineDurableDesc`,colorClass:`engine-durable`}].map(e=>{let t=Dx[e.id];return{...e,...t.packageName?{packageName:t.packageName}:{},...t.packageName&&t.installCommand?{installCommand:t.installCommand}:{}}});function kx({direction:e,align:t,className:n,label:r,caret:i=!1,bar:a,portal:o}){let{engine:s}=fn(),c=yn(),{t:l}=_e(),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(null),m=(0,Q.useRef)(null),h=e??(a===`left`?`right`:a===`right`?`left`:a===`bottom`?`up`:`down`),g=o??(a===`left`||a===`right`||a===`bottom`),_=e=>{e?Z({type:`check_engines`}):p(null),d(e)},v=Ox.find(e=>e.id===s)??{id:s,titleKey:`settingsEnginePiTitle`,badge:s.toUpperCase(),tagKey:`engineTagFull`,descKey:`settingsEnginePiDesc`,colorClass:`engine-${s}`},y=l(v.titleKey),b=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Dt,{className:`bar-item-icon engine-picker-icon`}),r?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`chip-sub bar-item-text engine-picker-name`,children:r}),(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${v.colorClass}`,children:v.badge})]}):(0,$.jsx)(`span`,{className:`engine-badge bar-item-text ${v.colorClass}`,children:v.badge})]});return(0,$.jsx)(`div`,{ref:m,className:`engine-picker-wrap ${v.colorClass} ${n??``}`,"data-bar-item":`host:engine`,children:(0,$.jsxs)(Zd,{trigger:b,open:u,onOpenChange:_,direction:h,align:t??(a===`right`?`right`:`left`),fit:!0,caret:i,portal:g,triggerClassName:`bar-item chip engine-picker-btn ${v.colorClass}`,menuClassName:`engine-picker-menu`,tip:`${l(`engineBadge`)}: ${r??y} — ${l(`engineSwitchTip`)}`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-header`,children:[(0,$.jsxs)(`div`,{className:`engine-picker-title`,children:[(0,$.jsx)(Dt,{}),(0,$.jsx)(`span`,{children:l(`settingsEngineSection`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-subtitle`,children:l(`enginePickerDesc`)})]}),(0,$.jsx)(`div`,{className:`engine-picker-list`,role:`menu`,children:Ox.map(e=>{let t=e.id===s,n=c.find(t=>t.id===e.id),r=e.id===`pi`||(n?n.installed:!1),i=!!n?.updating,a=!!n?.uninstalling,o=!!(r&&n?.hasUpdate&&n?.latestVersion),u=o||i,m=e.id!==`pi`&&r,h=t=>{t.stopPropagation(),d(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:l(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}}))},g=t=>{t.stopPropagation(),i||a||(d(!1),Z({type:`update_engine`,engineId:e.id}))},_=n=>{n.stopPropagation(),a||i||t||(f===e.id?(p(null),Z({type:`uninstall_engine`,engineId:e.id})):p(e.id))},v=()=>{r?(d(!1),t||Z({type:`switch_engine`,engine:e.id})):(d(!1),e.installCommand&&window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:l(`installEngineTabTitle`,{name:e.badge}),command:e.installCommand}})))};return(0,$.jsxs)(`div`,{role:`menuitem`,tabIndex:0,title:r?void 0:l(`engineInstallTip`),className:`engine-picker-item ${e.colorClass}${t?` active`:``}${r?``:` uninstalled`}`,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),v())},onClick:v,children:[(0,$.jsxs)(`div`,{className:`engine-picker-item-head`,children:[(0,$.jsx)(Dt,{className:`engine-picker-item-icon`}),(0,$.jsx)(`span`,{className:`engine-badge ${e.colorClass}`,children:e.badge}),l(e.titleKey)!==e.badge&&(0,$.jsx)(`span`,{className:`engine-picker-item-name`,children:l(e.titleKey)}),(0,$.jsx)(`span`,{className:`engine-picker-item-tag${r?a?` uninstalling`:i||o?` update-available`:``:` uninstalled`}`,title:o?l(`engineUpdateTip`,{current:n?.version??``,latest:n?.latestVersion??``}):void 0,children:l(r?a?`engineUninstalling`:i?`engineUpdating`:o?`engineUpdateAvailable`:e.tagKey:`engineNotInstalled`)}),!r&&e.installCommand&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-install-btn`,title:l(`engineInstallTip`),onClick:h,children:[(0,$.jsx)(ht,{className:`engine-install-icon`}),(0,$.jsx)(`span`,{children:l(`engineInstall`)})]}),u&&(0,$.jsxs)(`button`,{type:`button`,className:`engine-picker-update-btn`,disabled:i||a,title:i?l(`engineUpdating`):l(`engineUpdateTip`,{current:n?.version??``,latest:n?.latestVersion??``}),onClick:g,children:[(0,$.jsx)(pe,{className:`engine-update-icon${i?` spinning`:``}`}),(0,$.jsx)(`span`,{children:l(i?`engineUpdating`:`engineUpdate`)})]}),m&&(0,$.jsxs)(`button`,{type:`button`,"data-testid":`engine-uninstall-${e.id}`,className:`engine-picker-uninstall-btn${f===e.id?` confirm`:``}`,disabled:a||i||t,title:t?l(`engineActiveNoUninstall`):a?l(`engineUninstalling`):f===e.id?l(`engineUninstallConfirm`):l(`engineUninstallTip`),onClick:_,children:[(0,$.jsx)(Ne,{className:`engine-uninstall-icon`}),(0,$.jsx)(`span`,{children:a?l(`engineUninstalling`):f===e.id?l(`engineUninstallConfirm`):l(`engineUninstall`)})]}),t&&(0,$.jsx)(z,{className:`engine-picker-check`})]}),(0,$.jsx)(`div`,{className:`engine-picker-item-desc`,children:l(e.descKey)})]},e.id)})})]})})}function Ax({entry:e,bar:t,chat:n,view:r,termOpen:i,gitOpen:a,worktreesOpen:o,plugins:s,onViewChange:c,onOpenPanel:l,onOpenSettings:u,onOpenGlobalSearch:d,onOpenBgTasks:f,onOpenProjectPicker:p,onOpenPluginMenu:m,isPluginMenuOpen:h,isProjectPickerOpen:g,onUiAction:_,uiContextEntries:y,dropdownProps:b,zenMode:x,onToggleZenMode:S,onOpenSandboxModal:w,onCreateCli:T}){let E=X(),{tabs:D}=fn(),O=sx(),k=mi(n.state?.messages,n.state?.conversationId),j=n.settings?.uiLayout,M=n.state,N=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{N.current!==null&&window.clearTimeout(N.current)},[]);let P=n=>{b8({event:n,entry:e,bar:t,layout:j,uiContextEntries:y,t:E})},F=e.id,I=e.labelExplicit?e.label:``,L=e=>I||e,R=e=>I?`${I} ${e}`:e;if(e.kind===`select`&&e.options?.length){let t=e.options.some(t=>t.value===e.value)?e.value:e.options[0].value;return(0,$.jsx)(`select`,{className:`bar-item bar-item-select`,title:e.hint??e.label,"data-tip":e.hint??e.label,"aria-label":e.label,value:t,onChange:t=>_?.(e,t.target.value),onContextMenu:P,"data-bar-item":F,children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})}if(F===`host:brand`)return(0,$.jsx)(xx,{label:L(`pi-web-ui`),barItem:!0,onContextMenu:P});if(F===`host:conn`)return(0,$.jsx)(W8,{id:F,chat:n,custom:I,withName:R,onContextMenu:P});if(F===`host:engine`)return(0,$.jsx)(`span`,{onContextMenu:P,"data-bar-item":F,className:`bar-item-engine-wrap`,style:{display:`inline-flex`,alignItems:`center`},children:(0,$.jsx)(kx,{direction:t===`bottom`?`up`:t===`left`?`right`:t===`right`?`left`:`down`,align:e.align===`end`||t===`right`?`right`:`left`,caret:!1,bar:t,portal:!0,label:e.labelExplicit?e.label:void 0})});if(F===`host:ctx`)return(0,$.jsx)(G8,{bar:t,chat:n,custom:I,onContextMenu:P});if(F===`host:cache`)return(0,$.jsx)(K8,{id:F,chat:n,custom:I,onContextMenu:P});if(F===`host:cost`)return(0,$.jsx)(q8,{id:F,entry:e,chat:n,custom:I,onUiAction:_,onContextMenu:P});if(F===`host:msg-count`)return(0,$.jsx)(J8,{id:F,chat:n,custom:I,withName:R,onContextMenu:P});if(F===`host:working`)return(0,$.jsx)(Y8,{id:F,chat:n,named:L,onContextMenu:P});if(F===`host:status-delegate`)return(0,$.jsx)(X8,{id:F,chat:n,named:L,onContextMenu:P});if(F===`host:host-metrics`)return(0,$.jsx)(Z8,{id:F,chat:n,withName:R,onContextMenu:P});if(F===`host:browser`)return!an()&&n.settings?.disabledAgentTools?.includes(`browser_page`)?null:(0,$.jsx)(`span`,{className:`bar-item-wrap`,onContextMenu:P,"data-bar-item":F,children:(0,$.jsx)(wx,{})});let z=t===`bottom`?`up`:t===`left`?`right`:t===`right`?`left`:`down`;if(F===`host:language`)return(0,$.jsx)(C8,{id:F,bar:t,direction:z,named:L,withName:R,onContextMenu:P,dropdownProps:b});if(F===`host:theme`)return(0,$.jsx)(w8,{id:F,bar:t,direction:z,named:L,withName:R,onContextMenu:P,dropdownProps:b});if(F===`host:update`)return(0,$.jsx)(T8,{id:F,chat:n,named:L,withName:R,onContextMenu:P,dropdownProps:b});let B=null,H=e.label,ee=null,U=!1,W=!1,G=``,K,q,te;switch(F){case`host:chat`:if(!r||r===`chat`||r===`native-cli`||r===`terminal`||r===`git`)return null;B=(0,$.jsx)(C,{className:`bar-item-icon`}),H=L(E(`chat`)),W=!0,q=()=>c?.(`chat`);break;case`host:native-cli`:return null;case`host:terminal`:B=(0,$.jsx)(Xe,{className:`bar-item-icon`}),H=L(E(`terminal`)),U=i??r===`terminal`,W=!0,q=()=>c?.(`terminal`);break;case`host:worktrees`:{let e=n.state?.worktree;if(!e)return null;let t=new Set(e.linkedWorktrees.map(e=>e.path));e.isLinkedWorktree&&t.add(e.currentPath),B=(0,$.jsx)($f,{className:`bar-item-icon`}),H=L(E(`worktreeViewTitle`)),G=`chip worktree-entry`,U=r===`worktrees`||o===!0,W=!0,K=E(`worktreeEntryTip`,{count:t.size}),ee=(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`worktree-count bar-item-badge`,children:t.size}),e.linkedWorktrees.some(e=>e.isDirty)&&(0,$.jsx)(`span`,{className:`worktree-dirty-dot`,"aria-label":E(`worktreeHasChanges`)})]}),q=()=>c?.(`worktrees`);break}case`host:git`:B=(0,$.jsx)(ot,{className:`bar-item-icon`}),H=L(E(`scmTab`)),U=a??r===`git`,W=!0,q=()=>c?.(`git`);break;case`host:canvas`:B=(0,$.jsx)(Jf,{className:`bar-item-icon`}),H=L(E(`canvasTab`)),U=r===`canvas`,W=!0,q=()=>c?.(`canvas`);break;case`host:new-chat`:B=(0,$.jsx)(ue,{className:`bar-item-icon`}),H=L(E(`newChat`)),G=`chip newchat`,q=()=>{c?.(`chat`),Z({type:`new_chat`}),er()};break;case`host:new-cli`:if(!T||D&&!D.includes(`terminal`))return null;B=(0,$.jsx)(v,{className:`bar-item-icon`}),H=L(E(`nativeCli`)),G=`chip native-cli-inline-button`,K=E(`nativeCliCreate`),q=()=>T();break;case`host:new-ephemeral-chat`:B=(0,$.jsx)(Zf,{className:`bar-item-icon`}),H=L(E(`newChatEphemeral`)),G=`chip newchat ephemeral-chat-btn`,q=()=>{c?.(`chat`),Z({type:`new_chat`,ephemeral:!0}),er()};break;case`host:new-sandbox`:B=(0,$.jsx)(rp,{className:`bar-item-icon`}),H=L(E(`newSandbox`)),G=`chip newchat sandbox-chip`,q=()=>w?.();break;case`host:history`:if(r&&r!==`chat`)return null;B=(0,$.jsx)(V,{className:`bar-item-icon`}),H=L(E(`openHistory`)),G=`panel-toggle`,q=()=>l?.(`left`);break;case`host:files`:if(r&&r!==`chat`)return null;B=(0,$.jsx)(tp,{className:`bar-item-icon`}),H=L(E(`openFiles`)),G=`panel-toggle has-label`,q=()=>l?.(`right`);break;case`host:open-project`:B=(0,$.jsx)(je,{className:`bar-item-icon`}),H=L(E(`openProject`)),G=`chip open-project`,U=!!g,q=()=>p?.();break;case`host:search`:B=(0,$.jsx)(mt,{className:`bar-item-icon`}),H=L(E(`searchGlobal`)),G=`chip`,q=()=>d?.();break;case`host:tasks`:{B=(0,$.jsx)(wt,{className:`bar-item-icon`}),H=L(E(`bgTasks`)),G=`chip bg-task-chip`;let e=n.bgServers.length+k.counts.running+k.counts.finished;e>0&&(ee=(0,$.jsx)(`span`,{className:`bg-task-badge bar-item-badge`,children:e})),q=()=>f?.();break}case`host:zen-mode`:B=(0,$.jsx)(ft,{className:`bar-item-icon`}),H=L(E(`zenMode`)),G=`chip chip-zen`,U=!!x,K=E(`zenModeTip`),q=()=>S?.();break;case`host:quiet-mode`:B=(0,$.jsx)(ve,{className:`bar-item-icon`}),H=L(E(`quietMode`)),G=`chip`,U=O.enabled,K=E(`quietMode`),q=()=>ix({...O,enabled:!O.enabled});break;case`host:device-center`:B=(0,$.jsx)(Yf,{className:`bar-item-icon`}),H=L(E(`deviceCenter`)),G=`chip`,K=E(`deviceCenterTip`),W=!0,U=r===`devices`,q=()=>c?.(`devices`);break;case`host:settings`:B=(0,$.jsx)(ze,{className:`bar-item-icon`}),H=L(E(`settings`)),G=`chip`,q=()=>u?.();break;case`host:plugins`:B=(0,$.jsx)(A,{className:`bar-item-icon`}),H=L(E(`pluginMenuTitle`)),G=`chip`,q=e=>{m?m(e.currentTarget):u?.(`plugins`)};break;case`host:github`:B=(0,$.jsx)(Ze,{className:`bar-item-icon`}),H=L(`GitHub`),G=`chip github`,q=()=>window.open(`https://github.com/xing-shuyin/keel`,`_blank`,`noreferrer,noopener`);break;case`host:cwd`:B=(0,$.jsx)(Ee,{className:`bar-item-icon`}),H=R(M?.cwd?h6(M.cwd,n.projects)||M.cwd:E(`openProject`)),G=`status-item status-cwd`,U=!!g,q=()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null),N.current=window.setTimeout(()=>{p?.(),N.current=null},220)},te=e=>{e.preventDefault(),e.stopPropagation(),N.current!==null&&(window.clearTimeout(N.current),N.current=null),Z({type:`new_chat`}),er()};break;case`host:plugin-status`:if(n.statuses.length===0)return null;B=(0,$.jsx)(Fe,{className:`bar-item-icon`}),H=R(n.statuses.map(e=>e.text).join(` · `)),G=`status-item ext-status`;break;default:{let i=x8({entry:e,bar:t,chat:n,view:r,plugins:s,onViewChange:c,onUiAction:_});B=i.iconNode,H=i.labelText,ee=i.badgeNode,U=i.isActive,W=i.isTab,G=i.extraClasses,K=i.tipOverride,q=i.onClick;break}}let ne=K??e.hint??H,re=[`bar-item`,W?`tb-tab${U?` active`:``}`:``,G,U&&!W?`active`:``].filter(Boolean).join(` `);return(0,$.jsxs)(`button`,{type:`button`,role:W?`tab`:void 0,"aria-selected":W?U:void 0,"aria-haspopup":F===`host:plugins`?`menu`:void 0,"aria-expanded":F===`host:plugins`?!!h:void 0,className:re,title:ne,"data-tip":ne,"aria-label":H,onClick:q,onDoubleClick:te,onContextMenu:P,"data-bar-item":F,children:[B,!(F===`host:worktrees`&&t===`top`&&!e.labelExplicit||F===`host:github`&&t===`bottom`&&!e.labelExplicit)&&(0,$.jsx)(`span`,{className:`bar-item-text`,children:H}),ee]})}var jx=[{id:`host:conn`,align:`start`},{id:`host:engine`,align:`start`},{id:`host:ctx`,align:`start`},{id:`host:cost`,align:`start`},{id:`host:cache`,align:`start`},{id:`host:msg-count`,align:`start`},{id:`host:plugin-status`,align:`start`},{id:`host:status-delegate`,align:`start`},{id:`host:working`,align:`start`},{id:`host:host-metrics`,align:`end`},{id:`host:cwd`,align:`end`}];function Mx({chat:e,bottombarItems:t,onUiAction:n,onOpenSettings:r,onViewChange:i,onCreateCli:a,onOpenGlobalSearch:o,onOpenBgTasks:s,worktreesOpen:c=!1}){let l=mn(`workspaceRoots`),u=e.state,[d,f]=(0,Q.useState)(!1);if(!u)return null;let p=t?t.map(e=>({id:e.id,entry:e,fallbackAlign:`start`})):jx.map(({id:e,align:t})=>({id:e,entry:null,fallbackAlign:t})),m=[],h=[],g=[];for(let{id:t,entry:l,fallbackAlign:u}of p){if(l?.hidden)continue;let p=l??{id:t,slot:`bottombar`,source:`host`,label:t.slice(5),kind:`action`,order:100,align:u,hidden:!1,userOverrides:[],arrangedBy:[]},_=(0,$.jsx)(Ax,{entry:p,bar:`bottom`,chat:e,view:void 0,worktreesOpen:c,onViewChange:i,onCreateCli:a,onOpenSettings:r,onOpenGlobalSearch:o,onOpenBgTasks:s,onOpenProjectPicker:()=>f(!0),isProjectPickerOpen:d,onUiAction:n});if(!_)continue;let v=p.align??u;v===`end`?g.push({key:t,node:_}):v===`center`?h.push({key:t,node:_}):m.push({key:t,node:_})}let _=e=>e.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.key));return(0,$.jsxs)(`footer`,{className:`statusbar`,children:[(0,$.jsx)(`div`,{className:`statusbar-left`,children:_(m)}),h.length>0&&(0,$.jsx)(`div`,{className:`statusbar-center`,children:_(h)}),(0,$.jsx)(`div`,{className:`statusbar-right`,children:_(g)}),d&&(0,$.jsx)(qd,{open:!0,currentCwd:u.cwd,pathCompletions:e.pathCompletions,workspaceRoots:l,onClose:()=>f(!1),onSelectDirectory:e=>{e&&e!==u.cwd&&Z({type:`set_cwd`,path:e}),f(!1)},mode:`folder`})]})}var Nx=class extends Q.Component{state={message:null};static getDerivedStateFromError(e){return{message:e instanceof Error?e.message:String(e)}}componentDidCatch(e,t){console.error(`[ui-slot] entry "${this.props.entryId??this.props.label}" in slot "${this.props.slot??`?`}" crashed:`,e,t.componentStack)}render(){if(this.state.message===null)return this.props.children;let e=`slot=${this.props.slot??`?`} entry=${this.props.entryId??this.props.label}: ${this.state.message}`;return(0,$.jsxs)(`button`,{type:`button`,className:`slot-error`,title:e,"aria-label":this.props.label,onClick:()=>console.error(`[ui-slot] ${e}`),children:[(0,$.jsx)(`span`,{"aria-hidden":!0,children:`⚠`}),(0,$.jsx)(`span`,{children:this.props.label})]})}};function Px(e,t){return!e||e.length===0?null:(0,$.jsx)(`span`,{className:`slot-toolbar`,children:e.map((e,n)=>(0,$.jsx)(Nx,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:Fx(e,n,t)},`${e.id}#${n}`))})}function Fx(e,t,n){let r=`${e.id}#${t}`,i=e.label||e.id,a=e.hint||i;return e.kind===`divider`?(0,$.jsx)(`span`,{className:`slot-divider`,"aria-hidden":`true`},r):e.kind===`badge`?(0,$.jsx)(`span`,{className:`slot-badge`,title:a,children:e.badge??i},r):e.kind===`toggle`?(0,$.jsxs)(`button`,{type:`button`,className:`slot-btn${e.checked?` on`:``}`,title:a,"aria-label":i,"aria-pressed":!!e.checked,onClick:()=>n?.(e),children:[e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):null,(0,$.jsx)(`span`,{children:i})]},r):e.kind===`progress`?(0,$.jsx)(`span`,{className:`slot-progress`,title:`${a} ${e.progress??0}%`,children:(0,$.jsx)(`progress`,{value:e.progress??0,max:100})},r):e.kind===`input`?(0,$.jsx)(`input`,{className:`slot-input`,defaultValue:e.value??``,placeholder:i,title:a,"aria-label":i,onKeyDown:t=>{t.key===`Enter`&&!t.nativeEvent.isComposing&&n?.(e,t.target.value)}},`${r}:${e.value??``}`):e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`slot-select`,title:a,"aria-label":i,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>n?.(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},r):(0,$.jsxs)(`button`,{type:`button`,className:`slot-btn`,title:a,"aria-label":i,onClick:()=>n?.(e),children:[e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):null,(0,$.jsx)(`span`,{children:i})]},r)}function Ix(e,t,n){let r=[],i=[],a=!1,o=e=>{i.length!==0&&(a=!0,r.push((0,$.jsx)(`span`,{className:`slot-toolbar`,children:i.map((e,t)=>(0,$.jsx)(Nx,{label:e.label||e.id,slot:e.slot,entryId:e.id,children:Fx(e,t,n)},`${e.id}#${t}`))},e)),i=[])};return e.forEach((e,n)=>{if(e.source===`host`){o(`gap${n}`);let i=t[e.id]??null;i&&(a=!0),r.push((0,$.jsx)(Q.Fragment,{children:i},e.id))}else i.push(e)}),o(`tail`),a?(0,$.jsx)($.Fragment,{children:r}):null}var Lx=(0,Q.memo)(function({goal:e,models:t,modelsLoading:n,activeConversationId:r,uiGoalbarActions:i,onUiAction:o}){let s=X(),{locale:c}=_e(),l=!Ye(c)&&e.statusEn?e.statusEn:e.status||``,d=!Ye(c)&&e.wizard?.statusEn?e.wizard.statusEn:e.wizard?.status||``,f=_n(),p=!e.conversationId||e.conversationId===r,m=e.goal!==null&&p,h=p?e.roles?.executor:void 0,g=h?.convId,_=h?.activity?!Ye(c)&&h.activityEn?h.activityEn:h.activity:h?.streaming?`…`:void 0,v=e.locked&&e.maxRounds>0?e.maxRounds:0,y=v>0?Ye(c)?s(`goalBarRound`,{n:`${e.round}/${v}`}):`Round ${e.round}/${v}`:`${s(`goalBarRound`,{n:e.round})}${e.locked?` · ${s(`goalBarUnlimitedShort`)}`:``}`,b=(e.usage?.inputTokens??0)+(e.usage?.outputTokens??0),x=e=>e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${(e/1e3).toFixed(1)}k`:`${e}`,S=e.execModel===void 0,[C,w]=(0,Q.useState)(e.reviewModel??``),[T,E]=(0,Q.useState)(e.maxRounds),[D,O]=(0,Q.useState)(e.locked),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(!1),N=T3(),P=D3(),F=O3(),[I,L]=(0,Q.useState)(!1),R=!E3();(0,Q.useEffect)(()=>{w(e.reviewModel??``),E(e.maxRounds||0),O(e.locked)},[e.goal,e.reviewModel,e.maxRounds,e.locked]),(0,Q.useEffect)(()=>{k&&t.length===0&&!I&&!n&&(L(!0),Z({type:`list_models`}))},[k,t.length,I,n]),(0,Q.useEffect)(()=>{t.length>0&&L(!1)},[t.length]);let z=()=>C?t.find(e=>e.id===C)?.name??C:s(`goalBarMainModelShort`),B=()=>{x3(!0),S3(!0),er()},V=i===void 0?[`host:goal-pill`,`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`,`host:goal-model`,`host:goal-rounds`,`host:goal-openrole`,`host:goal-clear`].map(e=>({id:e,source:`host`})):i.filter(e=>!e.hidden),H=e=>{let t=new Set(e);return V.filter(e=>t.has(e.id)||e.source!==`host`)},ee=(e,t)=>{let n=V.find(t=>t.id===e);return n?.labelExplicit?n.label:t},U={"host:goal-pill":(0,$.jsxs)(`button`,{type:`button`,className:`goalbar-hint`,title:s(`goalBarHelp`),onClick:B,children:[(0,$.jsx)(at,{}),` `,(0,$.jsx)(`span`,{children:ee(`host:goal-pill`,s(`goalBarTitle`))})]}),"host:goal-set":(0,$.jsx)(bn,{tip:s(`goalBarHelp`),className:`goalbar-btn mode`,"aria-pressed":N,onClick:()=>{N?x3(!1):B()},children:ee(`host:goal-set`,s(`goalComposeEnter`))}),"host:goal-wizard":(0,$.jsx)(bn,{tip:s(`goalWizardTip`),className:`goalbar-btn action wizard`,"aria-pressed":P,onClick:()=>C3(!P),children:ee(`host:goal-wizard`,s(`goalWizardBtn`))}),"host:goal-plan":f.planMode?(0,$.jsx)(bn,{tip:s(`planActionTip`),className:`goalbar-btn action plan`,"aria-pressed":F,onClick:()=>w3(!F),children:ee(`host:goal-plan`,s(`planActionBtn`))}):null,"host:goal-lock":(0,$.jsx)(bn,{tip:s(D?`goalBarLocked`:`goalBarUnlocked`),className:`goalbar-icon-btn${D?` on`:``}`,"aria-pressed":D,onClick:()=>O(e=>(Z({type:`set_goal_prefs`,locked:!e}),!e)),children:D?(0,$.jsx)(Ge,{}):(0,$.jsx)(bt,{})}),"host:goal-collapse":(0,$.jsx)(bn,{tip:s(`goalBarCollapse`),className:`goalbar-icon-btn`,onClick:()=>{S3(!1),x3(!1)},children:(0,$.jsx)(a,{})}),"host:goal-model":(0,$.jsx)(Zd,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,title:`${s(`goalBarReviewModel`)}: ${z()}`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:ee(`host:goal-model`,s(`goalBarReviewShort`))}),(0,$.jsx)(`b`,{children:z()})]}),open:k,onOpenChange:A,direction:`up`,children:(0,$.jsx)(df,{models:t,modelsLoading:n,currentModelId:C||null,active:k,onEnsureModels:()=>{t.length===0&&!n&&!I&&(L(!0),Z({type:`list_models`}))},loading:I,onRefresh:()=>Z({type:`list_models`}),onPickModel:e=>{w(e.id),A(!1),Z({type:`set_goal_prefs`,reviewModel:e.id})},isRowActive:e=>sf(e,C),extraTopRow:(0,$.jsx)(Qd,{active:C===``,onClick:()=>{w(``),A(!1),Z({type:`set_goal_prefs`,reviewModel:``})},children:s(`goalBarUseMainModel`)})})}),"host:goal-rounds":(0,$.jsxs)(`label`,{className:`goalbar-round`,title:s(`goalBarMaxRoundsTip`),children:[(0,$.jsx)(`input`,{type:`number`,min:0,step:1,value:T,placeholder:s(`goalBarUnlimitedShort`),onChange:e=>{let t=parseInt(e.target.value,10);E(Number.isNaN(t)||t<0?0:t)},onBlur:()=>Z({type:`set_goal_prefs`,maxRounds:T}),onKeyDown:e=>{e.key===`Enter`&&(Z({type:`set_goal_prefs`,maxRounds:T}),e.target.blur())}}),(0,$.jsx)(`span`,{children:ee(`host:goal-rounds`,s(`goalBarRoundsUnit`))})]})},W=(e.wizard?.active??!1)&&p;return W?(0,$.jsx)(`div`,{className:`goalbar goalbar-active ${W?`wizard`:``}`,children:(0,$.jsxs)(`div`,{className:`goalbar-active-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:(0,$.jsx)(`span`,{className:`goalbar-spin`,children:`🔍`})}),(0,$.jsxs)(`span`,{className:`goalbar-text`,title:e.wizard?.draft??``,children:[s(`goalWizardRunning`),`: `,e.wizard?.draft]}),(0,$.jsxs)(`span`,{className:`goalbar-chip reviewing`,children:[s(`goalBarRound`,{n:(e.wizard?.step??0)+1}),` / `,e.wizard?.maxSteps??6]}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:d||s(`goalBarReviewing`)}),Ix(H([`host:goal-clear`]),{...U,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x`,title:s(`goalBarClear`),onClick:()=>{Z({type:`clear_goal`}),S3(!1)},children:(0,$.jsx)(Ct,{})})},o)]})}):m?(0,$.jsx)(`div`,{className:`goalbar goalbar-active ${e.reviewing?`reviewing`:``}`,children:(0,$.jsxs)(`div`,{className:`goalbar-active-row`,children:[(0,$.jsx)(`span`,{className:`goalbar-icon`,children:e.reviewing?(0,$.jsx)(`span`,{className:`goalbar-spin`,children:`◌`}):`🎯`}),(0,$.jsx)(`span`,{className:`goalbar-text`,title:e.goal??``,children:e.goal}),e.reviewing?(0,$.jsxs)(`span`,{className:`goalbar-chip reviewing`,children:[e.phase===`executing`?s(`goalBarExecuting`):s(`goalBarReviewing`),` `,y]}):(0,$.jsx)(`span`,{className:`goalbar-chip ${e.verdict===`pass`?`pass`:e.verdict===`fail`?`fail`:e.verdict===`blocked`?`blocked`:``}`,children:e.verdict===`pass`?s(`goalBarPassed`):e.verdict===`fail`?s(`goalBarFailed`):e.verdict===`blocked`?s(`goalBarBlocked`):`${s(`goalBarRound`,{n:e.round||1})} · ${e.locked?s(`goalBarLocked`):s(`goalBarUnlocked`)}`}),(0,$.jsx)(`span`,{className:`goalbar-detail`,children:l}),_&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:h?.convId,children:[`· `,_]}),b>0&&(0,$.jsxs)(`span`,{className:`goalbar-detail`,title:`${e.usage?.inputTokens??0} in / ${e.usage?.outputTokens??0} out`,children:[`· `,x(b),` tokens`]}),S&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:s(`goalBarStaleBackend`)}),Ix(H([`host:goal-openrole`,`host:goal-clear`]),{...U,"host:goal-openrole":g?(0,$.jsx)(`button`,{type:`button`,className:`goalbar-icon-btn`,title:s(`goalBarOpenExecTip`),onClick:()=>Z({type:`switch_conversation`,id:g}),children:(0,$.jsx)(u,{})}):null,"host:goal-clear":(0,$.jsx)(`button`,{type:`button`,className:`goalbar-x${e.reviewing?` stopping`:``}`,title:ee(`host:goal-clear`,e.reviewing?s(`goalBarStop`):s(`goalBarClear`)),onClick:()=>{e.goal&&ir({text:e.goal}),Z({type:`clear_goal`}),x3(!0),S3(!0),er()},children:e.reviewing?(0,$.jsx)(_t,{}):(0,$.jsx)(Ct,{})})},o)]})}):R?null:(0,$.jsx)(`div`,{className:`goalbar`,children:(0,$.jsxs)(`div`,{className:`goalbar-row`,children:[(0,$.jsxs)(`span`,{className:`goalbar-lead`,children:[(0,$.jsx)(at,{}),(0,$.jsx)(`span`,{children:ee(`host:goal-pill`,s(`goalBarTitle`))})]}),Ix(H([`host:goal-set`,`host:goal-wizard`,`host:goal-plan`,`host:goal-lock`,`host:goal-collapse`]),U,o),(0,$.jsx)(`span`,{className:`goalbar-sep`}),H([`host:goal-model`,`host:goal-rounds`]).filter(e=>e.source===`host`).map(e=>(0,$.jsx)(Q.Fragment,{children:U[e.id]},e.id)),e.history&&e.history.length>0&&(0,$.jsxs)(Zd,{trigger:(0,$.jsxs)(`span`,{className:`goalbar-opt`,children:[(0,$.jsx)(`span`,{className:`goalbar-opt-label`,children:s(`goalHistory`)}),(0,$.jsx)(`b`,{children:e.history.length})]}),open:j,onOpenChange:M,direction:`up`,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:s(`goalHistory`)}),e.history.map((e,t)=>(0,$.jsx)(Qd,{onClick:()=>{ir({text:e.goal}),x3(!0),M(!1),er()},children:(0,$.jsxs)(`span`,{className:`dd-model-cell`,title:e.goal,children:[(0,$.jsxs)(`span`,{className:`dd-model-name`,children:[e.verdict===`pass`?`✅ `:e.verdict===`fail`?`❌ `:`⚠️ `,e.goal.length>42?`${e.goal.slice(0,42)}…`:e.goal]}),(0,$.jsx)(`span`,{className:`dd-model-meta`,children:(0,$.jsxs)(`span`,{className:`dd-model-id`,children:[s(`goalBarRound`,{n:e.rounds}),` · `,new Date(e.finishedAt).toLocaleString()]})})]})},`${e.finishedAt}-${t}`))]}),S&&(0,$.jsx)(`span`,{className:`goalbar-stale`,children:s(`goalBarStaleBackend`)}),(0,$.jsx)(bn,{tip:s(`goalBarHelp`),className:`goalbar-icon-btn`,onClick:()=>er(),children:`?`})]})})}),Rx=[{slot:`topbar.primary`,labelKey:`uiLayoutTopbar`,alignable:!0,vertical:!1},{slot:`bottombar`,labelKey:`uiLayoutBottombar`,alignable:!0,vertical:!1},{slot:`sidebar.left`,labelKey:`uiLayoutSidebarLeft`,alignable:!0,vertical:!0},{slot:`sidebar.right`,labelKey:`uiLayoutSidebarRight`,alignable:!0,vertical:!0}],zx=`__tray`,Bx=[`start`,`center`,`end`];function Vx(e,t,n){return e(t===`center`?`uiLayoutAlignMiddle`:n?t===`start`?`uiLayoutAlignTop`:`uiLayoutAlignBottom`:t===`start`?`uiLayoutAlignLeft`:`uiLayoutAlignRight`)}function Hx(e,t=new Set){let n={},r=[],i=new Set;for(let a of Rx){let o=(e[a.slot]??[]).filter(e=>!t.has(e.id));n[a.slot]=o;for(let e of o)e.hidden&&(r.push(e),i.add(e.id))}for(let n of e[`topbar.overflow`]??[])t.has(n.id)||i.has(n.id)||(r.push(n),i.add(n.id));return{zones:n,tray:r}}function Ux(e,t){for(let n of Object.values(e.zones)){let e=n.find(e=>e.id===t);if(e)return e}return e.tray.find(e=>e.id===t)}function Wx(e){return(e??[]).filter(e=>!e.hidden)}function Gx(e,t){let n=Wx(e);return t===void 0?n:n.filter(e=>(e.align??`start`)===t)}function Kx(e){return[...new Set(e)]}function qx(e,t,n){let r=e??{},i=Ux(t,n.id);if(!i)return r;let a={...r};i.hidden&&(a.hidden=(r.hidden??[]).filter(e=>e!==n.id),a.shown=Kx([...r.shown??[],n.id])),i.slot!==n.slot&&(a.slots={...r.slots,[n.id]:n.slot});let o=n.align;o!==void 0&&(i.align??`start`)!==o&&(a.align={...r.align,[n.id]:o});let s=t.zones[n.slot]??[],c=Wx(s),l=e=>o===void 0||(e.align??`start`)===o,u=c.filter(e=>e.id!==n.id&&l(e)).map(e=>e.id),d=Math.max(0,Math.min(Math.trunc(n.index)||0,u.length));u.splice(d,0,n.id);let f=o===void 0?[]:c.filter(e=>e.id!==n.id&&!l(e)).map(e=>e.id),p=new Set(s.map(e=>e.id));return a.order=Kx([...(r.order??[]).filter(e=>!p.has(e)&&e!==n.id),...u,...f]),a}function Jx(e,t){let n=e??{};return{...n,hidden:Kx([...n.hidden??[],t]),shown:(n.shown??[]).filter(e=>e!==t)}}function Yx({slots:e,layout:t,exclude:n,onClose:r}){let i=X(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(null),l=(0,Q.useMemo)(()=>Hx(e,n),[e,n]),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(l),p=(0,Q.useRef)(t),m=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{f.current=l,p.current=t}),(0,Q.useEffect)(()=>{m.current=null},[t]);let h=(e,t)=>{let n=document.elementFromPoint(e,t)?.closest(`[data-drop-slot]`);if(!n)return null;let r=n.dataset.dropSlot;if(!r)return null;let i=n.dataset.dropAlign,a=u.current,o=Array.from(n.querySelectorAll(`[data-chip]`)).filter(e=>e.dataset.chip!==a),s=o.length;for(let n=0;n<o.length;n++){let r=o[n].getBoundingClientRect();if(t<r.top||t<=r.bottom+4&&e<r.left+r.width/2){s=n;break}}return{slot:r,align:i,index:s}},g=e=>{m.current=e,Z({type:`set_settings`,uiLayout:e})},_=()=>{let e=u.current,t=d.current;if(u.current=null,d.current=null,o(null),c(null),!e||!t)return;let n=m.current??p.current;g(t.slot===`__tray`?Jx(n,e):qx(n,f.current,{id:e,slot:t.slot,...t.align===void 0?{}:{align:t.align},index:t.index}))},v=e=>{u.current||g(Jx(m.current??p.current,e))};(0,Q.useEffect)(()=>{if(!a)return;let e=e=>{e.preventDefault();let t=h(e.clientX,e.clientY);d.current=t,c(t)},t=()=>_();return window.addEventListener(`pointermove`,e,{passive:!1}),window.addEventListener(`pointerup`,t),window.addEventListener(`pointercancel`,t),()=>{window.removeEventListener(`pointermove`,e),window.removeEventListener(`pointerup`,t),window.removeEventListener(`pointercancel`,t)}},[a]),Lt(()=>{u.current||r()});let y=(e,t)=>{(e.pointerType!==`mouse`||e.button===0)&&(e.preventDefault(),u.current=t,d.current=null,o(t),c(null))},b=(e,t)=>{let n=!t&&!bg.has(e.id);return(0,$.jsxs)(`span`,{className:`icon-editor-chip-wrap${a===e.id?` dragging`:``}`,children:[(0,$.jsxs)(`button`,{type:`button`,"data-chip":e.id,className:`icon-editor-chip`,title:e.label,onPointerDown:t=>y(t,e.id),children:[(0,$.jsx)(`span`,{className:`icon-editor-chip-icon`,children:hp(e)}),(0,$.jsx)(`span`,{className:`icon-editor-chip-label`,children:e.label})]}),n&&(0,$.jsx)(`button`,{type:`button`,className:`icon-editor-chip-hide`,title:i(`uiLayoutHide`),"aria-label":`${i(`uiLayoutHide`)} ${e.label}`,onPointerDown:e=>e.stopPropagation(),onClick:t=>{t.stopPropagation(),v(e.id)},children:(0,$.jsx)(Ct,{})})]},e.id)},x=(e,t,n,r)=>{let o=s?.slot===e&&(s.align??null)===(t??null),c=e===zx,l=r.map(e=>b(e,c));return o&&s&&l.splice(Math.max(0,Math.min(s.index,l.length)),0,(0,$.jsx)(`span`,{className:`icon-editor-caret`,"aria-hidden":`true`},`__caret`)),(0,$.jsxs)(`div`,{className:`icon-editor-strip${o?` drop-over`:``}${a?` dragging-active`:``}`,"data-drop-slot":e,...t===void 0?{}:{"data-drop-align":t},children:[n!==null&&(0,$.jsx)(`span`,{className:`icon-editor-strip-label`,children:n}),l,r.length===0&&(0,$.jsx)(`span`,{className:`icon-editor-empty`,children:i(`uiIconEditDropHere`)})]},t??`__all`)};return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`icon-editor-backdrop`,onClick:r}),(0,$.jsxs)(`div`,{className:`icon-editor`,role:`dialog`,"aria-modal":`true`,"aria-label":i(`uiIconEditTitle`),children:[(0,$.jsxs)(`div`,{className:`icon-editor-head`,children:[(0,$.jsx)(`span`,{className:`icon-editor-title`,children:i(`uiIconEditTitle`)}),(0,$.jsx)(`span`,{className:`icon-editor-hint`,children:i(`uiIconEditHint`)}),(0,$.jsx)(`button`,{type:`button`,className:`icon-editor-close`,onClick:r,"aria-label":i(`close`),title:i(`close`),children:(0,$.jsx)(Ct,{})})]}),(0,$.jsx)(`div`,{className:`icon-editor-body`,children:Rx.map(e=>{let t=l.zones[e.slot]??[],n=Wx(t);return(0,$.jsxs)(`div`,{className:`icon-editor-zone`,children:[(0,$.jsxs)(`div`,{className:`icon-editor-zone-title`,children:[i(e.labelKey),a&&(0,$.jsx)(`span`,{className:`icon-editor-zone-count`,children:n.length})]}),e.alignable?Bx.map(n=>x(e.slot,n,Vx(i,n,e.vertical),Gx(t,n))):x(e.slot,void 0,null,n)]},e.slot)})}),(0,$.jsxs)(`div`,{className:`icon-editor-tray`,children:[(0,$.jsxs)(`div`,{className:`icon-editor-tray-head`,children:[(0,$.jsxs)(`span`,{className:`icon-editor-zone-title`,children:[i(`uiIconEditTray`),(0,$.jsx)(`span`,{className:`icon-editor-zone-count`,children:l.tray.length})]}),(0,$.jsx)(`span`,{className:`icon-editor-tray-hint`,children:i(`uiIconEditTrayHint`)})]}),x(zx,void 0,null,l.tray)]})]})]})}function Xx(e,t,n){let r=new Map(e.map(e=>[e.id,e])),i=new Map,a=e=>{let t=[],n=new Map,a=e,o;for(;;){let e=i.get(a.id);if(e!==void 0){o=e;break}let s=n.get(a.id);if(s!==void 0){o=t.slice(s).reduce((e,t)=>e.id<t.id?e:t).cwd;break}n.set(a.id,t.length),t.push(a);let c=a.parentId?r.get(a.parentId):void 0;if(!c){o=a.cwd;break}a=c}for(let e of t)i.set(e.id,o);return o},o=e.find(e=>e.id===n),s=o?a(o):t,c=Co(s),l=new Map;for(let t of e){let e=a(t),n=Co(e)||e,r=l.get(n);r?r.convs.push(t):l.set(n,{cwd:e,convs:[t]})}let u=[...l.entries()].map(([e,{cwd:t,convs:n}])=>({cwd:t,isCurrent:c?e===c:t===s,convs:n}));return u.sort((e,t)=>e.isCurrent?-1:t.isCurrent?1:e.cwd<t.cwd?-1:+(e.cwd>t.cwd)),u}function Zx(e,t=new Set){let n=new Map(e.map(e=>[e.id,e])),r=new Map,i=[];for(let t of e)if(t.parentId&&n.has(t.parentId)){let e=r.get(t.parentId)??[];e.push(t),r.set(t.parentId,e)}else i.push(t);let a=e=>{let t=[],n=[...r.get(e)??[]],i=new Set;for(;n.length>0;){let e=n.shift();if(i.has(e.id))continue;i.add(e.id),t.push(e);let a=r.get(e.id);a&&n.push(...a)}return t},o=[],s=new Set,c=new Set,l=(e,n)=>{if(s.has(e.id)||c.has(e.id))return;s.add(e.id);let i=r.get(e.id)??[],u=i.length>0,d=u&&t.has(e.id),f=0,p=!1,m=!1,h=!1;if(u){let t=a(e.id);if(f=t.length,p=t.some(e=>e.isStreaming),m=t.some(e=>!!e.error),h=t.some(e=>!!e.hasQuestion),d)for(let e of t)c.add(e.id)}if(o.push({c:e,depth:n,hasKids:u,isCollapsed:d,descendantCount:f,hasStreaming:p,hasError:m,hasQuestion:h}),!d)for(let e of i)l(e,n+1)};for(let e of i)l(e,0);for(let t of e)l(t,0);return o}var Qx=`pi-web-ui:project-order-manual`,$x=`pi-web-ui:lp-project-order`,e5=400,t5=new Set;function n5(){for(let e of t5)e()}function r5(e){return t5.add(e),()=>{t5.delete(e)}}function i5(){try{let e=localStorage.getItem($x);if(e){let t=JSON.parse(e),n=Array.isArray(t.order)?t.order.filter(e=>typeof e==`string`&&e.length>0):[],r={},i=t.firstSeen;if(i&&typeof i==`object`)for(let[e,t]of Object.entries(i))typeof t==`number`&&Number.isFinite(t)&&t>0&&(r[e]=t);return{order:n,firstSeen:r}}}catch{}return{order:[],firstSeen:{}}}function a5(e){try{localStorage.setItem($x,JSON.stringify(e))}catch{}}function o5(){return(0,Q.useSyncExternalStore)(r5,s5)}function s5(){try{return localStorage.getItem(Qx)===`1`}catch{return!1}}function c5(e){try{localStorage.setItem(Qx,e?`1`:`0`)}catch{}n5()}function l5(){return i5().order}function u5(e){let t=i5();t.order.length===e.length&&t.order.every((t,n)=>t===e[n])||a5({...t,firstSeen:t.firstSeen,order:[...e]})}function d5(e){let t=i5(),n=new Map(Object.entries(t.firstSeen)),r=Date.now(),i=!1;for(let t of e)n.has(t)||(n.set(t,r),i=!0);if(!i)return n;let a=[...n.entries()].sort((e,t)=>t[1]-e[1]).slice(0,e5);return a5({...t,firstSeen:Object.fromEntries(a)}),new Map(a)}function f5({send:e,ready:t,status:n,engine:r,connectionEpoch:i,cwd:a,sessions:o,projectSessions:s}){let c=(0,Q.useRef)(new Map),l=`${t}:${n}:${r??``}:${i??0}`,u=(0,Q.useRef)(l),[d,f]=(0,Q.useState)(()=>new Set),[p,m]=(0,Q.useState)(()=>new Set),h=(0,Q.useRef)({cwd:a,sessions:o,projectSessions:s});h.current={cwd:a,sessions:o,projectSessions:s};let g=(e,t)=>{if(!e.has(t))return e;let n=new Set(e);return n.delete(t),n},_=(0,Q.useCallback)(e=>{let t=c.current.get(e);t&&(t.timedOut=!0),f(t=>g(t,e)),m(t=>new Set(t).add(e))},[]);return(0,Q.useEffect)(()=>{u.current!==l&&(c.current.clear(),f(new Set),m(new Set),u.current=l);for(let[e,t]of c.current)t.timedOut||(t.timer=setTimeout(()=>_(e),Math.max(0,t.deadline-Date.now())));return()=>{for(let e of c.current.values())clearTimeout(e.timer)}},[l,_]),(0,Q.useEffect)(()=>{for(let[e,t]of c.current){let n=s?.[e]??(e===Co(a)?o:void 0);n!==void 0&&n!==t.baseline&&(clearTimeout(t.timer),c.current.delete(e),f(t=>g(t,e)),m(t=>g(t,e)))}},[s,o,a]),{request:(0,Q.useCallback)(r=>{if(!t||n!==`open`)return!1;let i=h.current,a=Co(r.path??i.cwd),o=c.current.get(a);if(o&&!o.timedOut)return!0;if(o&&clearTimeout(o.timer),!e(r))return!1;let s=i.projectSessions?.[a]??(a===Co(i.cwd)?i.sessions:void 0),l=setTimeout(()=>_(a),2e4);return c.current.set(a,{baseline:s,timer:l,deadline:Date.now()+2e4}),f(e=>new Set(e).add(a)),m(e=>g(e,a)),!0},[e,t,n,_]),pending:d,failed:p}}var p5=/^\[(微信|feishu|飞书|dingtalk|钉钉|wechat|qq|telegram)[^\]]*\]\s*(.*)$/i;function m5(e,t,n){let r=e.match(p5);if(r){let t=r[1].toLowerCase(),i=t.includes(`微信`)||t===`wechat`?n(`lpChannelWechat`):t.includes(`飞书`)||t===`feishu`?n(`lpChannelFeishu`):t.includes(`钉钉`)||t===`dingtalk`?n(`lpChannelDingtalk`):t.toUpperCase();return{cleanTitle:r[2]?.trim()||e,categoryTag:{key:`wechat`,label:i}}}return t.fork?{cleanTitle:e,categoryTag:{key:`fork`,label:n(`lpBadgeFork`)}}:t.scheduler?{cleanTitle:e,categoryTag:{key:`scheduler`,label:n(`lpBadgeScheduler`)}}:t.tui?{cleanTitle:e,categoryTag:{key:`tui`,label:`TUI`}}:{cleanTitle:e,categoryTag:null}}function h5(e){let t=new Date(e),n=new Date;return t.toDateString()===n.toDateString()?`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`:`${t.getMonth()+1}/${t.getDate()}`}function g5(e,t){return e&&t.kind===`session`&&!!t.target.pinned}function _5(e,t){if(!e||e.size===0)return!1;for(let n of[t.id,t.sessionId,t.sessionFile,t.path])if(n&&(e.has(n)||e.has(n.trim().toLowerCase())))return!0;return!1}function v5(e){let t=e instanceof HTMLElement?e:null;if(!t)return!1;let n=t.tagName;return n===`INPUT`||n===`TEXTAREA`||n===`SELECT`||t.isContentEditable}try{typeof localStorage<`u`&&localStorage.removeItem(`pi-web-ui:lp-visible-counts`)}catch{}var y5=`pi-web-ui:projects-order`;try{typeof localStorage<`u`&&localStorage.removeItem(y5)}catch{}var b5=`pi-web-ui:lp-sizes`,x5={projects:1,groups:1,convs:1,sessions:1},S5={running:`pluginRunStatusRunning`,done:`pluginRunStatusDone`,error:`pluginRunStatusError`};function C5(){try{return cg(localStorage.getItem(b5),x5)}catch{return{...x5}}}typeof process<`u`&&{}.VITEST;function w5({projects:e,currentCwd:t,conversations:n,elsewhere:r,activeConversationId:i,removedProjectsVersion:a,panelSend:o,ready:s,status:c,engine:l,connectionEpoch:u,sessions:d,projectSessions:f}){let p=(0,Q.useMemo)(()=>{let a=es(),o=new Set,s=[];for(let t of e){let e=Co(t.path);o.has(e)||is(t.path)||a.has(e)||(o.add(e),s.push(t))}if(t&&t!==`@root`&&t!==`machine-root`){let e=Co(t);!o.has(e)&&!a.has(e)&&(o.add(e),s.push({path:t,lastUsed:0}))}for(let e of Xx(n,t,i)){if(!e.cwd)continue;let t=Co(e.cwd);!o.has(t)&&!a.has(t)&&(o.add(t),s.push({path:e.cwd,lastUsed:0}))}for(let e of r){if(!e.cwd)continue;let t=Co(e.cwd);!o.has(t)&&!a.has(t)&&(o.add(t),s.push({path:e.cwd,lastUsed:0}))}return s},[e,t,n,r,i,a]),m=o5(),[h,g]=(0,Q.useState)(0),_=(0,Q.useMemo)(()=>{let e=e=>Co(e.path),t=d5(p.map(e)),n=n=>n.lastUsed>0?n.lastUsed:t.get(e(n))??0,r;if(m){let t=new Map(p.map(t=>[e(t),t])),n=[];for(let e of l5()){let r=t.get(e);r&&(n.push(r),t.delete(e))}r=[...t.values(),...n]}else r=[...p].sort((t,r)=>n(r)-n(t)||e(t).localeCompare(e(r)));return u5(r.map(e)),r},[p,m,h]),v=(0,Q.useCallback)((e,t,n)=>{let r=Co(e),i=Co(t);if(r===i)return;let a=_.map(e=>Co(e.path)).filter(e=>e!==r),o=a.indexOf(i);o<0||(a.splice(n?o+1:o,0,r),u5(a),s5()||c5(!0),g(e=>e+1))},[_]),[y,b]=(0,Q.useState)(null),[x,S]=(0,Q.useState)(null),C=_,w=(0,Q.useRef)(null),[T,E]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(`pi-web-ui:lp-expanded-projects`);if(e){let t=JSON.parse(e);if(Array.isArray(t))return w.current=new Set(t),w.current}}catch{}return new Set});(0,Q.useEffect)(()=>{try{localStorage.setItem(`pi-web-ui:lp-expanded-projects`,JSON.stringify([...T]))}catch{}},[T]);let[D,O]=(0,Q.useState)(()=>{try{let e=sessionStorage.getItem(`pi-web-ui:lp-visible-counts`);if(e){let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return t}}catch{}return{}});(0,Q.useEffect)(()=>{try{sessionStorage.setItem(`pi-web-ui:lp-visible-counts`,JSON.stringify(D))}catch{}},[D]);let k=(0,Q.useCallback)(e=>{let t=D[Co(e)]??5;return Math.max(20,t+10)},[D]),{request:A,pending:j,failed:M}=f5({send:o,ready:s,status:c,engine:l,connectionEpoch:u,cwd:t,sessions:d,projectSessions:f}),N=j,P=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=Co(t);if(e){if(!P.current&&(P.current=!0,w.current))return;E(t=>{if(t.has(e))return t;let n=new Set(t);return n.add(e),n})}},[t]);let F=(0,Q.useRef)(new Set),I=(0,Q.useRef)(l),L=(0,Q.useRef)(u??0);(0,Q.useEffect)(()=>{I.current!==l&&F.current.clear(),I.current=l,L.current!==(u??0)&&(L.current=u??0,F.current.clear())},[l,u]);let R=(0,Q.useCallback)(e=>{let t=Co(e),n=!T.has(t);if(E(e=>{let r=new Set(e);return n?r.add(t):r.delete(t),r}),n){let n=k(e);A({type:`list_sessions`,path:e,limit:n})&&F.current.add(t)}},[A,T,k]);return(0,Q.useEffect)(()=>{if(!s||c!==`open`){F.current.clear();return}if(C.length===0)return;let e=Co(t);for(let t of C){let n=Co(t.path);if(n!==e&&T.has(n)&&!F.current.has(n)){let e=k(t.path);A({type:`list_sessions`,path:t.path,limit:e})&&F.current.add(n)}}},[C,T,t,A,k,s,c,l]),{effectiveProjects:C,moveProject:v,dragProject:y,setDragProject:b,dropHint:x,setDropHint:S,expandedProjects:T,setExpandedProjects:E,projectVisibleCounts:D,setProjectVisibleCounts:O,serverListLimit:k,requestSessions:A,loadingProjects:j,failedProjects:M,loadingMore:N,toggleProjectExpand:R}}function T5({uiContextSession:e,quickAskReferenceMenus:t,conversations:n,sessions:r,elsewhere:i,finishedSubagentCount:a,conversationRefCapability:o,panelSend:s,setConfirmDel:c,setRenameDraft:l,setRenaming:u,onUiAction:d}){let f=X(),p=(0,Q.useRef)(null),m=(0,Q.useRef)(null),h=(0,Q.useRef)(()=>{}),g=Hf((e??[]).filter(e=>t||e.id!==`host:conv-quick-ask`)).length>0,_=(0,Q.useCallback)((s,c,l)=>{p.current={x:s,y:c,target:l};let u=l.kind===`running`?l.id:void 0,d=l.kind===`elsewhere`,g=u??(d&&l.id||void 0),_=u?{kind:`conversation`,conversationId:u}:l.kind===`history`&&l.id?{kind:`conversation`,sessionFile:l.id}:d&&g&&l.owner&&i.some(e=>e.owner===l.owner&&e.convId===g)?{kind:`conversation`,conversationId:g,owner:l.owner}:void 0,v=u??(d?g:void 0),y=a(n,u),b=y===0?f(`noFinishedSubagents`):f(u?`dismissFinishedSubagentsScoped`:`dismissFinishedSubagents`,{n:y}),x=!!v&&m.current===v,S=(e??[]).map(e=>{if(e.source!==`host`)return e;if(e.id===`host:conv-quick-ask`)return t&&_?e:{...e,hidden:!0};if(e.id===`host:conv-rename`)return l.kind===`running`||l.kind===`history`?e:{...e,hidden:!0};if(e.id===`host:conv-takeover`){let t=!!(l.pseudo&&l.owner?.startsWith(`scheduler:`)),n=i.some(e=>e.owner===l.owner&&e.convId===g&&e.independent===!1);return d&&g&&l.owner&&!t&&!n?e:{...e,hidden:!0}}if(d&&e.id===`host:conv-dismiss-subagents`)return{...e,hidden:!0};if(e.id===`host:conv-dismiss-subagents`)return{...e,label:b,...y===0?{when:[...e.when??[],`disabled`]}:{}};if(e.id===`host:conv-force-dismiss`)return v?{...e,...x?{label:f(`forceDismissConfirm`)}:{}}:{...e,hidden:!0};if(e.id===`host:conv-pin`){if(l.kind===`history`)return l.pinned??r.find(e=>e.path===l.id)?.pinned?{...e,label:f(`unpinConversation`)}:e;if(!u)return{...e,hidden:!0};let t=n.find(e=>e.id===u);return!t||t.isSubagent?{...e,hidden:!0}:t.pinned?{...e,label:f(`unpinConversation`)}:e}if(e.id===`host:conv-persist`){if(!u)return{...e,hidden:!0};let t=n.find(e=>e.id===u);return!t||!t.isSubagent&&t.sessionFile?{...e,hidden:!0}:t?.isEphemeral?{...e,label:f(`saveEphemeral`)}:e}if(e.id===`host:conv-copy-id`)return g?e:{...e,hidden:!0};if(e.id===`host:conv-copy-path`)return l.kind===`history`?e:u?n.some(e=>e.id===u&&e.sessionFile)?e:{...e,when:[...e.when??[],`disabled`]}:{...e,hidden:!0};if(e.id===`host:conv-copy-link`){if(l.kind===`history`)return r.find(e=>e.path===l.id)?.sessionId||A_(l.id)?e:{...e,hidden:!0};if(!u)return{...e,hidden:!0};let t=n.find(e=>e.id===u);return t?.sessionId||A_(t?.sessionFile)?e:{...e,when:[...e.when??[],`disabled`]}}return e.id===`host:conv-quote`?o&&(g||l.kind===`history`)?e:{...e,hidden:!0}:e});return Hf(S).length!==0&&(jf({x:s,y:c,slot:`contextmenu.session`,target:l,entries:S,onHostAction:(e,t)=>{if(e.id===`host:conv-quick-ask`)_&&t2({reference:_});else return h.current(e,t)}}),!0)},[e,t,n,r,i,a,f,o]);return h.current=(0,Q.useCallback)((e,t)=>{let i=t.kind===`running`?t.id:void 0,a=i??(t.kind===`elsewhere`&&t.id||void 0);if(e.id===`host:conv-takeover`)t.kind===`elsewhere`&&a&&t.owner&&s({type:`take_over_conversation`,owner:t.owner,id:a});else if(e.id===`host:conv-dismiss-subagents`)s(i?{type:`dismiss_finished_subagents`,parentId:i}:{type:`dismiss_finished_subagents`});else if(e.id===`host:conv-force-dismiss`){let e=p.current,n=i??(t.kind===`elsewhere`?a:void 0);if(!n||!e)return;if(m.current!==n)return m.current=n,_(e.x,e.y,e.target),!0;m.current=null,s({type:`dismiss_conversation`,id:n,force:!0,...t.kind===`elsewhere`&&t.owner?{owner:t.owner}:{}})}else if(e.id===`host:conv-persist`)i&&s({type:`persist_conversation`,id:i});else if(e.id===`host:conv-pin`){if(t.kind===`history`){let e=p.current?.target.pinned??r.find(e=>e.path===t.id)?.pinned;s({type:`pin_session`,path:t.id,pinned:!e});return}i&&s({type:`pin_conversation`,id:i,pinned:!n.find(e=>e.id===i)?.pinned})}else if(e.id===`host:conv-copy-id`&&a)navigator.clipboard?.writeText(a).catch(()=>{});else if(e.id===`host:conv-copy-path`){let e=t.kind===`history`?t.id:i&&n.find(e=>e.id===i)?.sessionFile||void 0;e&&navigator.clipboard?.writeText(e).catch(()=>{})}else if(e.id===`host:conv-copy-link`){let e=t.kind===`history`?r.find(e=>e.path===t.id)?.sessionId||A_(t.id):i?n.find(e=>e.id===i)?.sessionId||A_(n.find(e=>e.id===i)?.sessionFile):null;if(e){let t=k_(window.location.href,{sessionId:e});navigator.clipboard?.writeText(t).catch(()=>{})}}else e.id===`host:conv-quote`?t.kind===`history`&&t.id?ir({attachments:[{path:``,key:`conv||${t.id}`,name:t.label||t.id,mode:`conversation`,sessionPath:t.id}]}):a&&ir({attachments:[{path:``,key:`conv|${a}|`,name:t.label||a,mode:`conversation`,conversationId:a}]}):e.id===`host:conv-rename`&&(c(null),i?(l(n.find(e=>e.id===i)?.title??t.label??``),u(`conv:${i}`)):t.kind===`history`&&t.id&&(l(r.find(e=>e.path===t.id)?.name??t.label??``),u(t.id)))},[s,_,n,r,c,l,u]),{forceArmedRef:m,sessionMenuAvailable:g,showSessionMenu:_,renderInlineEntries:(e,t,n)=>!e||e.length===0?null:(0,$.jsx)(`span`,{className:t,children:e.map((e,t)=>{let r=`${e.id}#${t}`,i=e.label||e.id,a=e.hint||i;return e.kind===`divider`?(0,$.jsx)(`span`,{className:`lp-slot-divider`,"aria-hidden":`true`},r):e.kind===`badge`?(0,$.jsx)(`span`,{className:`lp-slot-badge`,title:a,children:e.badge??i},r):e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`lp-slot-select`,title:a,"aria-label":i,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onClick:e=>e.stopPropagation(),onChange:t=>{t.stopPropagation(),d?.(e,t.target.value)},children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},r):(0,$.jsx)(`button`,{type:`button`,className:`lp-slot-btn`,title:a,"aria-label":i,onClick:t=>{t.stopPropagation(),n?d?.(e,void 0,n):d?.(e)},children:e.icon?(0,$.jsx)(`span`,{"aria-hidden":!0,children:e.icon}):(0,$.jsx)(`span`,{children:i})},r)})}),openSessionMenu:(0,Q.useCallback)((e,t)=>{v5(e.target)||g&&(m.current=null,_(e.clientX,e.clientY,t)&&(e.preventDefault(),e.stopPropagation()))},[g,_])}}function E5(e,t=!0){let n=(0,Q.useRef)(new Map),r=(0,Q.useRef)(!1);(0,Q.useLayoutEffect)(()=>{let i=e.current;if(!i)return;let a=i.querySelectorAll(`.lp-row[data-session-key]`),o=new Map,s=n.current;if(a.forEach(e=>{let t=e.getAttribute(`data-session-key`);if(!t)return;let n=!e.closest(`.lp-history-collapsible`),r=e.getBoundingClientRect();o.set(t,{top:r.top,isRunning:n,el:e})}),!t||!r.current){t&&(r.current=!0);let e=new Map;for(let[t,n]of o.entries())e.set(t,{top:n.top,isRunning:n.isRunning});n.current=e;return}let c=null,l=0;for(let[e,t]of o.entries()){let n=s.get(e);if(n&&!n.isRunning&&t.isRunning){let r=n.top-t.top;if(r>4){c=e,l=r;break}}}if(c){let e=o.get(c);if(e){let t=e.el;t.style.transform=`translateY(${l}px)`,t.style.transition=`none`,t.style.zIndex=`10`,t.style.willChange=`transform`,t.classList.add(`session-row-promoting`),t.offsetHeight,requestAnimationFrame(()=>{t.style.transition=`transform 0.38s cubic-bezier(0.16, 1, 0.3, 1)`,t.style.transform=`translateY(0)`;let e=()=>{t.style.transform=``,t.style.transition=``,t.style.zIndex=``,t.style.willChange=``,t.classList.remove(`session-row-promoting`),t.removeEventListener(`transitionend`,e)};t.addEventListener(`transitionend`,e,{once:!0}),setTimeout(e,420)})}for(let[e,t]of o.entries()){if(e===c)continue;let n=s.get(e);if(n&&!n.isRunning&&!t.isRunning){let e=n.top-t.top;if(e>4&&e<80){let n=t.el;n.style.transform=`translateY(${e}px)`,n.style.transition=`none`,n.offsetHeight,requestAnimationFrame(()=>{n.style.transition=`transform 0.32s cubic-bezier(0.16, 1, 0.3, 1)`,n.style.transform=`translateY(0)`;let e=()=>{n.style.transform=``,n.style.transition=``};n.addEventListener(`transitionend`,e,{once:!0}),setTimeout(e,360)})}}else if(n&&n.isRunning&&t.isRunning){let e=n.top-t.top;if(Math.abs(e)>4&&Math.abs(e)<120){let n=t.el;n.style.transform=`translateY(${e}px)`,n.style.transition=`none`,n.offsetHeight,requestAnimationFrame(()=>{n.style.transition=`transform 0.32s cubic-bezier(0.16, 1, 0.3, 1)`,n.style.transform=`translateY(0)`;let e=()=>{n.style.transform=``,n.style.transition=``};n.addEventListener(`transitionend`,e,{once:!0}),setTimeout(e,360)})}}}}let u=new Map;for(let[e,t]of o.entries())u.set(e,{top:t.top,isRunning:t.isRunning});n.current=u})}function D5({effectiveProjects:e,expandedProjects:t,moveProject:n,toggleProjectExpand:r,renameOverrides:i,uiContextProject:o,panelSend:s,confirmDel:c,setConfirmDel:l,setRenameDraft:u,setRenaming:d}){let f=X(),p=e=>{let t=e.displayName||e.name||e.firstMessage?.trim();return t&&t.length>0?t:f(`emptyChat`)},m=e=>e.split(/[\\/]/).pop()||e,h=e=>{if(e.sandbox)return e.sandbox.name;let t=i[`proj:${e.path}`];return t===void 0?e.name?.trim()||m(e.path):t||m(e.path)},g=t=>{let n=Co(t),r=e.find(e=>Co(e.path)===n);return r?h(r):m(t)},_=(e,t)=>{let n=t.match(/^[^_]+_((?:\d{1,3}\.){3}\d{1,3}|[a-zA-Z0-9.-]+)_\d+_(.*)$/);if(n){let e=n[1],t=n[2]?.replace(/^_+/,``);return{label:t?`${e}/${t}`:e,isRemote:!0,envTag:`SSH`}}return/^(?:ssh|remote):\/\//i.test(e)||/[\\/]\.pi-web[\\/]ssh[\\/]/i.test(e)?{label:t,isRemote:!0,envTag:`SSH`}:{label:t,isRemote:!1}},v=e=>{let t=e.closest(`[role="tree"]`);return t?[...t.querySelectorAll(`[data-lp-nav]`)].filter(e=>!e.closest(`.lp-history-collapsible.collapsed`)&&!e.disabled):[]},y=(e,t)=>{let n=v(e);if(n.length===0)return;let r=n.indexOf(e);n[t===`first`?0:t===`last`?n.length-1:r<0?t>0?0:n.length-1:Math.min(n.length-1,Math.max(0,r+t))]?.focus()},b=i=>{let a=i.target;if(!a.hasAttribute(`data-lp-nav`))return;let o=a.getAttribute(`data-project-path`);switch(i.key){case`ArrowDown`:case`ArrowUp`:if(i.preventDefault(),i.altKey&&o){let t=e.map(e=>e.path),r=t.indexOf(o),s=i.key===`ArrowDown`?r+1:r-1;if(r<0||s<0||s>=t.length)return;n(o,t[s],i.key===`ArrowDown`),requestAnimationFrame(()=>{let e=a.closest(`[role="tree"]`)??document;for(let t of e.querySelectorAll(`[data-project-path]`))t.getAttribute(`data-project-path`)===o&&t.focus()});return}y(a,i.key===`ArrowDown`?1:-1);return;case`Home`:case`End`:i.preventDefault(),y(a,i.key===`Home`?`first`:`last`);return;case`ArrowRight`:o&&!t.has(Co(o))&&(i.preventDefault(),r(o));return;case`ArrowLeft`:i.preventDefault(),o?t.has(Co(o))&&r(o):a.closest(`.lp-project-node`)?.querySelector(`[data-project-path]`)?.focus();return}},x=(0,Q.useRef)(null),S=Hf(o??[]).length>0,C=(0,Q.useCallback)((e,t,n)=>{let r=!!n.sandbox,i=x.current===n.path,a=(o??[]).map(e=>e.source===`host`?e.id===`host:proj-rename`&&r?{...e,hidden:!0}:e.id===`host:proj-delete-all-sessions`&&i?{...e,label:f(`deleteAllProjectSessionsConfirm`)}:e:e);Hf(a).length!==0&&jf({x:e,y:t,slot:`contextmenu.project`,target:{id:n.path,kind:`project`,label:h(n)},entries:a,onHostAction:(r,i)=>{if(r.id===`host:proj-new-chat`)x.current=null,s({type:`new_chat`,cwd:i.id}),er();else if(r.id===`host:proj-rename`)x.current=null,l(null),u(n.name??``),d(`proj:${i.id}`);else if(r.id===`host:proj-delete-all-sessions`){if(x.current!==i.id)return x.current=i.id,C(e,t,n),!0;x.current=null,s({type:`delete_project_sessions`,path:i.id})}}})},[o,s,f,l,u,d]);return{displayName:p,projectDisplayName:h,lookupProjectName:g,parseProjectEnv:_,focusTreeItem:y,handleTreeKeyDown:b,openProjectMenu:(0,Q.useCallback)((e,t)=>{v5(e.target)||S&&(x.current=null,e.preventDefault(),e.stopPropagation(),C(e.clientX,e.clientY,t))},[S,C]),delButton:(e,t,n,r,i,a=!0)=>{let o=c===e;return(0,$.jsx)(`button`,{type:`button`,className:`lp-del ${o?`confirm`:``}`,title:o?n:t,onClick:t=>{t.stopPropagation(),!a||o?(l(null),r()):l(e)},children:o?(0,$.jsx)(z,{}):i??(0,$.jsx)(Ne,{})})},sectionHeader:(e,t,n,r,i,o)=>(0,$.jsxs)(`div`,{className:`lp-section-header`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-section-title panel-section-title`,onClick:n,title:f(t?`expandSection`:`collapseSection`),children:[(0,$.jsxs)(`span`,{className:`lp-section-title-text`,children:[e,r===void 0?``:` (${r})`]}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,children:t?(0,$.jsx)(D,{}):(0,$.jsx)(a,{})})]}),i||o?(0,$.jsxs)(`div`,{className:`lp-section-actions`,children:[i,o]}):null]}),handleBlankDoubleClick:(0,Q.useCallback)(e=>{let t=e.target;t&&(t.closest(`.lp-row`)||t.closest(`button, input, select, textarea, a`)||(s({type:`new_chat`}),er()))},[s])}}function O5(e,t){let n={...t};if(!e)return n;try{let r=JSON.parse(e);if(r&&typeof r==`object`&&!Array.isArray(r))for(let e of Object.keys(t)){let t=r[e];typeof t==`number`&&Number.isFinite(t)&&t>0&&(n[e]=t)}}catch{}return n}function k5(e){let t=e.start.above+e.start.below,n=Math.max(1,e.availablePx)/(e.totalWeight>0?e.totalWeight:1),r=e.minAbovePx/n,i=e.minBelowPx/n;if(r+i>=t){let n=e.minAbovePx+e.minBelowPx||1,r=t*e.minAbovePx/n;return{above:r,below:t-r}}let a=Math.min(t-i,Math.max(r,e.start.above+e.deltaPx/n));return{above:a,below:t-a}}var A5=`pi-web-ui:lp-collapse-projects`,j5=`pi-web-ui:lp-collapse-convs`,M5=`pi-web-ui:lp-collapse-sessions`,N5=`pi-web-ui:lp-collapse-subagents`,P5=`pi-web-ui:lp-collapse-plugin-sections`;function F5(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(N5);if(e)return new Set(JSON.parse(e))}catch{}return new Set});return[e,(0,Q.useCallback)(e=>{t(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(N5,JSON.stringify([...n]))}catch{}return n})},[])]}function I5(e,t=!1){let[n,r]=(0,Q.useState)(()=>{try{let t=localStorage.getItem(e);if(t===`1`)return!0;if(t===`0`)return!1}catch{}return t});return[n,(0,Q.useCallback)(()=>{r(t=>{let n=!t;try{localStorage.setItem(e,n?`1`:`0`)}catch{}return n})},[e])]}function L5(){let[e,t]=(0,Q.useState)(()=>{try{let e=localStorage.getItem(P5),t=e?JSON.parse(e):[];return new Set(Array.isArray(t)?t.filter(e=>typeof e==`string`):[])}catch{return new Set}});return[e,(0,Q.useCallback)(e=>{t(t=>{let n=new Set(t);n.has(e)?n.delete(e):n.add(e);try{localStorage.setItem(P5,JSON.stringify([...n]))}catch{}return n})},[])]}function R5({panelRef:e,uiSections:t,uiPluginRunning:n,onPluginRunningAction:r,renderPluginSectionBody:i,sessions:a,projectSessions:o,conversations:s,projects:c,panelSend:l}){let u=X(),[d,f]=(0,Q.useState)(null),[p,m]=(0,Q.useState)(``),[h,g]=(0,Q.useState)({}),_=(0,Q.useRef)(null);_.current=d;let v=()=>{_.current=null,f(null)},y=(e,t,n,r)=>{if(_.current!==e)return;_.current=null,f(null);let i=p.trim();if(t.type!==`rename_project`){if(!i||i===r)return}else if(i===r)return;l({...t,name:i}),g(e=>({...e,[n]:i})),setTimeout(()=>{g(e=>{if(e[n]!==i)return e;let t={...e};return delete t[n],t})},1e4)};(0,Q.useEffect)(()=>{g(e=>{let t=Object.keys(e);if(t.length===0)return e;let n={...e},r=!1,i=e=>(a.find(t=>t.path===e)??Object.values(o??{}).flat().find(t=>t.path===e))?.name;for(let a of t){let t=s.find(e=>e.id===a),o=c.find(e=>`proj:${e.path}`===a);(t&&t.title===e[a]||i(a)===e[a]||o&&(o.name??``)===e[a])&&(delete n[a],r=!0)}return r?n:e})},[a,o,s,c]);let[b]=I5(A5,!1),[x]=I5(j5,!1),[S]=I5(M5,!1),[C,w]=L5(),[T,E]=(0,Q.useState)(!1),[D,O]=(0,Q.useState)(()=>C5());(0,Q.useEffect)(()=>{try{localStorage.setItem(b5,JSON.stringify(D))}catch{}},[D]);let k=og(ag(t)).filter(e=>e.shown),A=k.some(e=>e.key===`groups`),j=(0,Q.useMemo)(()=>k.filter(e=>!(e.key===`convs`||e.key===`sessions`||e.key===`groups`&&k.some(e=>e.key===`projects`))),[k]),M=(0,Q.useCallback)(e=>e===`projects`?b:e===`convs`?x:e===`sessions`?S:e===`groups`?T:C.has(e),[b,x,S,T,C]),N=(0,Q.useMemo)(()=>j.filter(e=>e.key!==`convs`&&e.key!==`sessions`).map(e=>e.key),[j]),P=(0,Q.useCallback)((t,n)=>r=>{r.preventDefault();let i=r.currentTarget,a=r.clientY,o={...D},s=e.current;if(!s)return;let c=N.filter(e=>M(e)).length,l=N.filter(e=>!M(e)).reduce((e,t)=>e+(o[t]??1),0)||1,u=Math.max(120,s.clientHeight-c*32);i.classList.add(`dragging`),document.body.classList.add(`lp-resizing`);let d=e=>{let{above:r,below:i}=k5({start:{above:o[t]??1,below:o[n]??1},deltaPx:e.clientY-a,availablePx:u,totalWeight:l,minAbovePx:72,minBelowPx:72});O(e=>({...e,[t]:r,[n]:i}))},f=()=>{window.removeEventListener(`pointermove`,d),window.removeEventListener(`pointerup`,f),i.classList.remove(`dragging`),document.body.classList.remove(`lp-resizing`)};window.addEventListener(`pointermove`,d),window.addEventListener(`pointerup`,f)},[D,N,M,e]),F=N.filter(e=>!M(e)),I=F.reduce((e,t)=>e+(D[t]??1),0)||1,L=e=>F.length<=1?1:(D[e]??1)/I*F.length,R=new Map(sg(N,M).map(([e,t])=>[e,(0,$.jsx)(`div`,{className:`lp-sash`,role:`separator`,"aria-orientation":`horizontal`,onPointerDown:P(e,t),onDoubleClick:()=>O({...x5}),title:u(`dragToResize`)},`sash-${e}`)])),z=()=>{let e=n??[];return e.length===0?null:e.map(e=>(0,$.jsxs)(`div`,{className:`panel-conv-group lp-plugin-group`,children:[(0,$.jsxs)(`div`,{className:`panel-conv-group-title`,title:e.pluginId,children:[u(`leftPanelPluginGroup`),` · `,e.pluginName]}),e.items.map(t=>(0,$.jsx)(`div`,{className:`lp-row lp-plugin-row`,children:(0,$.jsxs)(`button`,{type:`button`,className:`session-item lp-plugin-item${t.action?``:` is-static`}`,title:t.hint?`${t.title} — ${t.hint}`:t.title,onClick:()=>r?.(e,t),children:[(0,$.jsx)(`span`,{className:`lp-plugin-dot st-${t.status}`,title:u(S5[t.status])}),t.icon?(0,$.jsx)(`span`,{className:`lp-plugin-icon`,"aria-hidden":!0,children:t.icon}):null,(0,$.jsxs)(`span`,{className:`session-info`,children:[(0,$.jsx)(`span`,{className:`session-title`,children:t.title}),t.hint?(0,$.jsx)(`span`,{className:`session-sub`,children:t.hint}):null]})]})},t.id))]},`plugin:${e.pluginId}`))},B=(e,t)=>{let n=k.find(t=>t.key===e)?.entry;if(!n)return null;let r=M(e);return(0,$.jsxs)(`div`,{className:`lp-section lp-section-plugin ${r?`collapsed`:``}`,style:r?void 0:{flex:`${L(e)} 1 0px`},children:[t(n.label,r,()=>w(e)),!r&&(0,$.jsx)(`div`,{className:`lp-section-body lp-plugin-section-body`,children:i?.(n)??null})]})},V=yn(),[H,ee]=(0,Q.useState)(!1),U=(0,Q.useRef)(null);return{renaming:d,setRenaming:f,renameDraft:p,setRenameDraft:m,renameOverrides:h,cancelRename:v,commitRename:y,collapseProjects:b,setCollapseGroups:E,hasGroupsSection:A,effectivePlan:j,effFlex:L,sashAfter:R,renderPluginRunning:z,renderPluginSection:B,newChatEngineOpen:H,setNewChatEngineOpen:ee,newChatSplitRef:U,newChatEngineMenu:T_({open:H,anchor:U,align:`left`,onClose:()=>ee(!1)}),isEngineInstalled:(0,Q.useCallback)(e=>{if(e===`pi`)return!0;let t=V.find(t=>t.id===e);return t?t.installed:!1},[V]),triggerInstallEngine:(0,Q.useCallback)((e,t)=>{t&&(/^https?:\/\//i.test(t)?window.open(t,`_blank`,`noopener,noreferrer`):window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:u(`installEngineTabTitle`,{name:e}),command:t}})))},[u])}}function z5(e){return/^ssh:\/\//i.test(e.trim())}function B5(e){return e.split(/\r?\n/).filter(e=>e.length>0)}function V5(e,t){let n=e?.status,r=n?.phase;if(!r)return e&&!t?`busy`:`ended`;if(r===`exited`||r===`disconnected`||r===`error`)return`ended`;if(r===`starting`)return`busy`;if(r===`waiting_input`||r===`waiting_approval`)return`waiting`;let i=n?.activity;return i===`idle`?`idle`:i===`waiting_input`||i===`waiting_approval`?`waiting`:i===`working`||r===`working`||n?.nativeEvents===!1?`busy`:`idle`}var H5=`pi.unread_conversations`,U5=6048e5;function W5(){if(typeof window>`u`||!window.sessionStorage)return[];try{let e=window.sessionStorage.getItem(H5);if(!e)return[];let t=JSON.parse(e);if(!Array.isArray(t))return[];let n=Date.now();return t.filter(e=>e&&typeof e.id==`string`&&n-(e.finishedAt||0)<U5)}catch{return[]}}function G5(e){if(typeof window<`u`&&window.sessionStorage)try{let t=Array.from(e);t.length===0?window.sessionStorage.removeItem(H5):window.sessionStorage.setItem(H5,JSON.stringify(t))}catch{}}var K5=new class{entries=new Map;keyToPrimaryId=new Map;cachedKeySet=new Set;listeners=new Set;constructor(){let e=W5();if(e.length>0){for(let t of e)this.addEntryInternal(t);this.updateCachedKeySet()}}normalizeKey(e){if(!e)return null;let t=e.trim();return t?t.toLowerCase():null}addEntryInternal(e){this.entries.set(e.id,e);let t=this.normalizeKey(e.id);t&&this.keyToPrimaryId.set(t,e.id);let n=this.normalizeKey(e.sessionId);n&&this.keyToPrimaryId.set(n,e.id);let r=this.normalizeKey(e.sessionFile);r&&this.keyToPrimaryId.set(r,e.id);let i=this.normalizeKey(e.path);i&&this.keyToPrimaryId.set(i,e.id)}updateCachedKeySet(){let e=new Set;for(let[t]of this.keyToPrimaryId.entries())e.add(t);for(let t of this.entries.values())t.id&&e.add(t.id),t.sessionId&&e.add(t.sessionId),t.sessionFile&&e.add(t.sessionFile),t.path&&e.add(t.path);this.cachedKeySet=e}notify(){this.updateCachedKeySet(),G5(this.entries.values());for(let e of this.listeners)try{e()}catch{}}subscribe=e=>(this.listeners.add(e),()=>this.listeners.delete(e));getSnapshot=()=>this.cachedKeySet;markUnread(e){let t=!1,n=Date.now();for(let r of e){if(!r.id)continue;let e=this.entries.get(r.id),i={id:r.id,sessionId:r.sessionId||e?.sessionId,sessionFile:r.sessionFile||e?.sessionFile,path:r.path||e?.path,finishedAt:n};this.addEntryInternal(i),t=!0}t&&this.notify()}clearUnread(e){if(!e)return;let t=this.normalizeKey(e);if(!t)return;let n=this.keyToPrimaryId.get(t)??(this.entries.has(e)?e:null);if(!n){this.entries.delete(e)&&(this.rebuildKeyMap(),this.notify());return}let r=this.entries.get(n);if(this.entries.delete(n),r){let e=this.normalizeKey(r.id);e&&this.keyToPrimaryId.delete(e);let t=this.normalizeKey(r.sessionId);t&&this.keyToPrimaryId.delete(t);let n=this.normalizeKey(r.sessionFile);n&&this.keyToPrimaryId.delete(n);let i=this.normalizeKey(r.path);i&&this.keyToPrimaryId.delete(i)}this.keyToPrimaryId.delete(t),this.notify()}rebuildKeyMap(){this.keyToPrimaryId.clear();for(let e of this.entries.values())this.addEntryInternal(e)}clearAll(){(this.entries.size!==0||this.keyToPrimaryId.size!==0)&&(this.entries.clear(),this.keyToPrimaryId.clear(),this.notify())}isUnread(e){return!!(e.id&&(this.cachedKeySet.has(e.id)||this.cachedKeySet.has(e.id.trim().toLowerCase()))||e.sessionId&&(this.cachedKeySet.has(e.sessionId)||this.cachedKeySet.has(e.sessionId.trim().toLowerCase()))||e.sessionFile&&(this.cachedKeySet.has(e.sessionFile)||this.cachedKeySet.has(e.sessionFile.trim().toLowerCase()))||e.path&&(this.cachedKeySet.has(e.path)||this.cachedKeySet.has(e.path.trim().toLowerCase())))}};function q5(e){K5.markUnread(e)}function J5(e){K5.clearUnread(e)}function Y5(){return(0,Q.useSyncExternalStore)(K5.subscribe,K5.getSnapshot,K5.getSnapshot)}function X5({editing:e,children:t,className:n,title:r,...i}){return e?(0,$.jsx)(`div`,{className:`${n??``} renaming`,title:r,children:t}):(0,$.jsx)(`button`,{type:`button`,className:n,title:r,...i,children:t})}function Z5({count:e,isCollapsed:t,hasStreaming:n,hasQuestion:r,hasError:i,onToggle:a}){let o=X(),s=o(t?`expandSubagents`:`collapseSubagents`),c=`${e} ${o(`subagentBadge`)} · ${s}`;return(0,$.jsxs)(`span`,{role:`button`,tabIndex:0,className:`subagents-toggle-badge${t?` is-collapsed`:``}${n?` has-streaming`:r?` has-question`:i?` has-error`:``}`,title:c,"aria-label":c,"aria-expanded":!t,onClick:e=>{e.stopPropagation(),a()},onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),e.stopPropagation(),a())},children:[n?(0,$.jsx)(`span`,{className:`subagent-dot streaming`,"aria-hidden":`true`}):r?(0,$.jsx)(`span`,{className:`subagent-dot question`,"aria-hidden":`true`,children:`?`}):i?(0,$.jsx)(`span`,{className:`subagent-dot error`,"aria-hidden":`true`}):null,(0,$.jsx)(`span`,{className:`subagents-count-text`,children:e})]})}function Q5({engine:e,className:t,title:n,ariaLabel:r}){let i=(e??`pi`).toLowerCase(),a=n??i.toUpperCase(),o=t?`lp-engine-glyph ${t}`:`lp-engine-glyph`,s=!r||void 0;return i===`claude`?(0,$.jsx)(`span`,{className:o,"data-engine":`claude`,title:a,"aria-label":r,"aria-hidden":s,children:(0,$.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`currentColor`,fillRule:`evenodd`,children:(0,$.jsx)(`path`,{d:`M4.709 15.955l4.72-2.647.08-.23-.08-.128H9.2l-.79-.048-2.698-.073-2.339-.097-2.266-.122-.571-.121L0 11.784l.055-.352.48-.321.686.06 1.52.103 2.278.158 1.652.097 2.449.255h.389l.055-.157-.134-.098-.103-.097-2.358-1.596-2.552-1.688-1.336-.972-.724-.491-.364-.462-.158-1.008.656-.722.881.06.225.061.893.686 1.908 1.476 2.491 1.833.365.304.145-.103.019-.073-.164-.274-1.355-2.446-1.446-2.49-.644-1.032-.17-.619a2.97 2.97 0 01-.104-.729L6.283.134 6.696 0l.996.134.42.364.62 1.414 1.002 2.229 1.555 3.03.456.898.243.832.091.255h.158V9.01l.128-1.706.237-2.095.23-2.695.08-.76.376-.91.747-.492.584.28.48.685-.067.444-.286 1.851-.559 2.903-.364 1.942h.212l.243-.242.985-1.306 1.652-2.064.73-.82.85-.904.547-.431h1.033l.76 1.129-.34 1.166-1.064 1.347-.881 1.142-1.264 1.7-.79 1.36.073.11.188-.02 2.856-.606 1.543-.28 1.841-.315.833.388.091.395-.328.807-1.969.486-2.309.462-3.439.813-.042.03.049.061 1.549.146.662.036h1.622l3.02.225.79.522.474.638-.079.485-1.215.62-1.64-.389-3.829-.91-1.312-.329h-.182v.11l1.093 1.068 2.006 1.81 2.509 2.33.127.578-.322.455-.34-.049-2.205-1.657-.851-.747-1.926-1.62h-.128v.17l.444.649 2.345 3.521.122 1.08-.17.353-.608.213-.668-.122-1.374-1.925-1.415-2.167-1.143-1.943-.14.08-.674 7.254-.316.37-.729.28-.607-.461-.322-.747.322-1.476.389-1.924.315-1.53.286-1.9.17-.632-.012-.042-.14.018-1.434 1.967-2.18 2.945-1.726 1.845-.414.164-.717-.37.067-.662.401-.589 2.388-3.036 1.44-1.882.93-1.086-.006-.158h-.055L4.132 18.56l-1.13.146-.487-.456.061-.746.231-.243 1.908-1.312-.006.006z`})})}):i===`codex`?(0,$.jsx)(`span`,{className:o,"data-engine":`codex`,title:a,"aria-label":r,"aria-hidden":s,children:(0,$.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`currentColor`,fillRule:`evenodd`,children:(0,$.jsx)(`path`,{d:`M9.205 8.658v-2.26c0-.19.072-.333.238-.428l4.543-2.616c.619-.357 1.356-.523 2.117-.523 2.854 0 4.662 2.212 4.662 4.566 0 .167 0 .357-.024.547l-4.71-2.759a.797.797 0 00-.856 0l-5.97 3.473zm10.609 8.8V12.06c0-.333-.143-.57-.429-.737l-5.97-3.473 1.95-1.118a.433.433 0 01.476 0l4.543 2.617c1.309.76 2.189 2.378 2.189 3.948 0 1.808-1.07 3.473-2.76 4.163zM7.802 12.703l-1.95-1.142c-.167-.095-.239-.238-.239-.428V5.899c0-2.545 1.95-4.472 4.591-4.472 1 0 1.927.333 2.712.928L8.23 5.067c-.285.166-.428.404-.428.737v6.898zM12 15.128l-2.795-1.57v-3.33L12 8.658l2.795 1.57v3.33L12 15.128zm1.796 7.23c-1 0-1.927-.332-2.712-.927l4.686-2.712c.285-.166.428-.404.428-.737v-6.898l1.974 1.142c.167.095.238.238.238.428v5.233c0 2.545-1.974 4.472-4.614 4.472zm-5.637-5.303l-4.544-2.617c-1.308-.761-2.188-2.378-2.188-3.948A4.482 4.482 0 014.21 6.327v5.423c0 .333.143.571.428.738l5.947 3.449-1.95 1.118a.432.432 0 01-.476 0zm-.262 3.9c-2.688 0-4.662-2.021-4.662-4.519 0-.19.024-.38.047-.57l4.686 2.71c.286.167.571.167.856 0l5.97-3.448v2.26c0 .19-.07.333-.237.428l-4.543 2.616c-.619.357-1.356.523-2.117.523zm5.899 2.83a5.947 5.947 0 005.827-4.756C22.287 18.339 24 15.84 24 13.296c0-1.665-.713-3.282-1.998-4.448.119-.5.19-.999.19-1.498 0-3.401-2.759-5.947-5.946-5.947-.642 0-1.26.095-1.88.31A5.962 5.962 0 0010.205 0a5.947 5.947 0 00-5.827 4.757C1.713 5.447 0 7.945 0 10.49c0 1.666.713 3.283 1.998 4.448-.119.5-.19 1-.19 1.499 0 3.401 2.759 5.946 5.946 5.946.642 0 1.26-.095 1.88-.309a5.96 5.96 0 004.162 1.713z`})})}):i===`agy`?(0,$.jsx)(`span`,{className:o,"data-engine":`agy`,title:a,"aria-label":r,"aria-hidden":s,children:(0,$.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`currentColor`,fillRule:`evenodd`,children:(0,$.jsx)(`path`,{d:`M21.751 22.607c1.34 1.005 3.35.335 1.508-1.508C17.73 15.74 18.904 1 12.037 1 5.17 1 6.342 15.74.815 21.1c-2.01 2.009.167 2.511 1.507 1.506 5.192-3.517 4.857-9.714 9.715-9.714 4.857 0 4.522 6.197 9.714 9.715z`})})}):i===`opencode`?(0,$.jsx)(`span`,{className:o,"data-engine":`opencode`,title:a,"aria-label":r,"aria-hidden":s,children:(0,$.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`rect`,{x:`4`,y:`4`,width:`16`,height:`16`,rx:`3`}),(0,$.jsx)(`path`,{d:`M9 9h6v6H9z`})]})}):i===`dsh`?(0,$.jsx)(`span`,{className:o,"data-engine":`dsh`,title:a,"aria-label":r,"aria-hidden":s,children:(0,$.jsx)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`currentColor`,fillRule:`evenodd`,children:(0,$.jsx)(`path`,{d:`M23.748 4.482c-.254-.124-.364.113-.512.234-.051.039-.094.09-.137.136-.372.397-.806.657-1.373.626-.829-.046-1.537.214-2.163.848-.133-.782-.575-1.248-1.247-1.548-.352-.156-.708-.311-.955-.65-.172-.241-.219-.51-.305-.774-.055-.16-.11-.323-.293-.35-.2-.031-.278.136-.356.276-.313.572-.434 1.202-.422 1.84.027 1.436.633 2.58 1.838 3.393.137.093.172.187.129.323-.082.28-.18.552-.266.833-.055.179-.137.217-.329.14a5.526 5.526 0 01-1.736-1.18c-.857-.828-1.631-1.742-2.597-2.458a11.365 11.365 0 00-.689-.471c-.985-.957.13-1.743.388-1.836.27-.098.093-.432-.779-.428-.872.004-1.67.295-2.687.684a3.055 3.055 0 01-.465.137 9.597 9.597 0 00-2.883-.102c-1.885.21-3.39 1.102-4.497 2.623C.082 8.606-.231 10.684.152 12.85c.403 2.284 1.569 4.175 3.36 5.653 1.858 1.533 3.997 2.284 6.438 2.14 1.482-.085 3.133-.284 4.994-1.86.47.234.962.327 1.78.397.63.059 1.236-.03 1.705-.128.735-.156.684-.837.419-.961-2.155-1.004-1.682-.595-2.113-.926 1.096-1.296 2.746-2.642 3.392-7.003.05-.347.007-.565 0-.845-.004-.17.035-.237.23-.256a4.173 4.173 0 001.545-.475c1.396-.763 1.96-2.015 2.093-3.517.02-.23-.004-.467-.247-.588zM11.581 18c-2.089-1.642-3.102-2.183-3.52-2.16-.392.024-.321.471-.235.763.09.288.207.486.371.739.114.167.192.416-.113.603-.673.416-1.842-.14-1.897-.167-1.361-.802-2.5-1.86-3.301-3.307-.774-1.393-1.224-2.887-1.298-4.482-.02-.386.093-.522.477-.592a4.696 4.696 0 011.529-.039c2.132.312 3.946 1.265 5.468 2.774.868.86 1.525 1.887 2.202 2.891.72 1.066 1.494 2.082 2.48 2.914.348.292.625.514.891.677-.802.09-2.14.11-3.054-.614zm1-6.44a.306.306 0 01.415-.287.302.302 0 01.2.288.306.306 0 01-.31.307.303.303 0 01-.304-.308zm3.11 1.596c-.2.081-.399.151-.59.16a1.245 1.245 0 01-.798-.254c-.274-.23-.47-.358-.552-.758a1.73 1.73 0 01.016-.588c.07-.327-.008-.537-.239-.727-.187-.156-.426-.199-.688-.199a.559.559 0 01-.254-.078c-.11-.054-.2-.19-.114-.358.028-.054.16-.186.192-.21.356-.202.767-.136 1.146.016.352.144.618.408 1.001.782.391.451.462.576.685.914.176.265.336.537.445.848.067.195-.019.354-.25.452z`})})}):i===`durable`?(0,$.jsx)(`span`,{className:o,"data-engine":`durable`,title:a,"aria-label":r,"aria-hidden":s,children:(0,$.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`1.8`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`path`,{d:`M12 3 5 6v6c0 4.5 3 7.8 7 9 4-1.2 7-4.5 7-9V6l-7-3Z`}),(0,$.jsx)(`path`,{d:`m9.5 12 1.8 1.8 3.4-3.6`})]})}):(0,$.jsx)(`span`,{className:o,"data-engine":i,title:a,"aria-label":r,"aria-hidden":s,children:(0,$.jsxs)(`svg`,{width:`14`,height:`14`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[(0,$.jsx)(`path`,{d:`M4.5 7.5c2.2-1 4.5-1 7.5-1h7.5`}),(0,$.jsx)(`path`,{d:`M9.5 6.8v10.7c0 .8-.4 1.5-1 1.8`}),(0,$.jsx)(`path`,{d:`M15.5 6.8v8.4c0 1.9.9 3.3 2.5 3.3.7 0 1.3-.3 1.7-.8`})]})})}function $5(e,t){let n=e.subagentVerdict;if(!n||n===`pass`)return null;let r=n===`blocked`?{kind:`blocked`,label:t(`subagentVerdictBlocked`)}:n===`partial`?{kind:`partial`,label:t(`subagentVerdictPartial`)}:{kind:`unverified`,label:t(`subagentVerdictUnverified`)};return(0,$.jsx)(`span`,{className:`category-badge-pill evidence-${r.kind}`,title:t(`subagentVerdictHint`),children:r.label})}function e7({children:e,time:t}){return e?(0,$.jsx)(`span`,{className:`conv-indicator-slot`,children:e}):t?(0,$.jsx)(`span`,{className:`conv-time`,children:t}):null}function t7({item:{c:e,depth:t,hasKids:n,isCollapsed:r,descendantCount:i,hasStreaming:a,hasError:o,hasQuestion:s},projectPath:c,currentCwd:l,sessions:u,projectSessions:d,conversations:f,sharedConversationOwner:p,activeConversationId:m,checkUnread:h,confirmTakeover:g,setConfirmTakeover:_,confirmDel:v,setConfirmDel:y,openSessionMenu:b,showSessionMenu:x,sessionMenuAvailable:S,forceArmedRef:C,panelSend:w,toggleSubagents:T,presetNames:E,delButton:D,renameOverrides:O,renaming:k,setRenaming:A,renameDraft:j,setRenameDraft:M,commitRename:N,cancelRename:P,finishedSubagentCount:F,countRunningSubagentDescendants:I,countScopeSubagents:L,renderInlineEntries:R,runningRowEntries:B}){let V=X(),H=Co(e.sessionFile||e.sessionId||e.id),ee=c?(d?.[Co(c)]??(Co(c)===Co(l)?u:void 0))?.find(t=>!!(e.sessionFile&&Co(t.path)===Co(e.sessionFile)||e.sessionId&&t.sessionId&&t.sessionId.trim().toLowerCase()===e.sessionId.trim().toLowerCase())):void 0,U=e.nativeCli?.status?.lastActivityAt??e.nativeCli?.status?.updatedAt,W=Math.max(e.modified??0,ee?.modified??0,U??0)||void 0;if(e.elsewhere){let c=e.owner,l=e.convId,u=!!e.pseudo,d=!!e.ownerOffline&&!u,f=!!(typeof c==`string`&&c.startsWith(`scheduler:`)),O=e.independent===!1,k=!!e.isSubagent,A=!!(c&&l)&&(O||f||k),j=A||!!(c&&l)&&!f&&!O&&!k,M=p===c&&m===l,N=!!(e.isStreaming||a||e.completionPending),P=!M&&!N&&h({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile}),F=!O&&!f&&!k&&g===e.id,I=k?`${V(`subagentBadge`)}\n${e.cwd}`:O?e.cwd:f?`${V(`schedulerViewTip`)}\n${e.cwd}`:F?V(`takeoverConfirm`):u?`${V(`lpOpenOnDesktopTip`)}\n${e.cwd}`:`${V(d?`elsewhereOfflineTip`:`elsewhereTip`)}\n${e.cwd}`,{cleanTitle:L,categoryTag:R}=m5(e.title,{fork:!!(e.forkFrom||e.forked),scheduler:f},V);return(0,$.jsxs)(`div`,{className:`lp-row${t>0?` lp-sub`:``}${n?` lp-has-kids`:``}`,"data-session-key":H,style:t>0?{"--depth":Math.min(t,4)}:void 0,onMouseLeave:()=>{_(t=>t===e.id?null:t),y(t=>t===`else:${e.id}`?null:t)},onContextMenu:t=>b(t,{id:l??e.id,kind:`elsewhere`,label:e.title,...c?{owner:c}:{},...u?{pseudo:!0}:{}}),children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-item lp-tree-session-item elsewhere-item${M?` active`:``}${j?``:` elsewhere-static`}${F?` confirm`:``}${N?` is-running`:``}${P?` is-unread`:``}`,title:I,tabIndex:j?0:-1,onClick:j?()=>{A?w({type:`open_shared_conversation`,owner:c,id:l,...k?{readOnly:!0}:{}}):u?w({type:`take_over_conversation`,owner:c,id:l}):F?(_(null),w({type:`take_over_conversation`,owner:c,id:l})):_(e.id)}:void 0,children:[M&&(0,$.jsx)(`span`,{className:`conv-current-badge`,children:V(`current`)}),(0,$.jsx)(`span`,{className:`conv-title-text`,title:e.title,children:F?V(`takeoverConfirm`):L}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[n&&(0,$.jsx)(Z5,{count:i,isCollapsed:r,hasStreaming:a,hasQuestion:s,hasError:o,onToggle:()=>T(e.id)}),e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:V(`pinnedConversation`),children:`📌`}),e.isEphemeral&&(0,$.jsx)(`span`,{className:`ephemeral-badge`,title:V(`newChatEphemeralTip`),children:V(`newChatEphemeral`)}),R&&(0,$.jsx)(`span`,{className:`category-badge-pill ${R.key}`,children:R.label}),e.engine&&e.engine!==`pi`&&(0,$.jsx)(`span`,{className:`category-badge-pill engine`,children:e.engine.toUpperCase()}),f?(0,$.jsx)(`span`,{className:`category-badge-pill scheduler`,children:V(`scheduledTaskBadge`)}):O?null:(0,$.jsx)(`span`,{className:`category-badge-pill elsewhere`,children:V(u?`elsewherePseudoBadge`:`elsewhereBadge`)}),d&&(0,$.jsx)(`span`,{className:`category-badge-pill elsewhere offline`,title:V(`elsewhereOfflineTip`),children:V(`elsewhereOfflineBadge`)}),k&&(0,$.jsx)(`span`,{className:`category-badge-pill subagent`,title:e.title,children:V(`subagentBadge`)}),e.agentPreset&&e.agentPreset!==`standard`&&(0,$.jsx)(`span`,{className:`category-badge-pill subagent`,title:e.agentPreset,children:E?.[e.agentPreset]??e.agentPreset}),$5(e,V),(0,$.jsx)(e7,{time:W?h5(W):void 0,children:e.hasQuestion?(0,$.jsx)(`span`,{className:`status-question-right${c&&l&&!u?` clickable`:``}`,style:c&&l&&!u?{cursor:`pointer`}:void 0,title:V(`takeoverHasQuestion`),onClick:c&&l&&!u?e=>{e.stopPropagation(),w({type:`peek_elsewhere_question`,owner:c,id:l})}:void 0,children:`?`}):N?(0,$.jsx)(`div`,{className:`status-spinner-right`,title:V(`streaming`)}):e.error?(0,$.jsx)(`span`,{className:`status-error-right`,title:e.error,children:`!`}):P?(0,$.jsx)(`span`,{className:`status-unread-right`,title:V(`completedUnreadTooltip`),children:(0,$.jsx)(z,{size:13,strokeWidth:3,"aria-hidden":`true`})}):null})]})]}),S&&v!==`else:${e.id}`&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-elsewhere-act`,style:{right:32},title:V(`elsewhereActions`),onClick:t=>{t.stopPropagation(),C.current=null;let n=t.currentTarget.getBoundingClientRect();x(n.left,n.bottom+4,{id:l??e.id,kind:`elsewhere`,label:e.title,...c?{owner:c}:{},...u?{pseudo:!0}:{}})},children:(0,$.jsx)(ie,{})}),D(`else:${e.id}`,V(`dismissConversation`),V(`dismissConversationConfirm`),()=>w({type:`dismiss_conversation`,id:l??e.id,force:!0,...c?{owner:c}:{}}),(0,$.jsx)(Ct,{}))]})}let G=!p&&m===e.id,K=!!e.nativeCli,q=e.nativeCli?.status?.phase,te=K?V5(e.nativeCli,e.error):void 0,ne=te===`busy`,re=te===`waiting`,J=te===`ended`,ae=!!(e.isStreaming||a||e.completionPending||ne),oe=!G&&!ae&&h({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile}),se=`conv:${e.id}`,Y=v===se,{cleanTitle:ce,categoryTag:le}=m5(O[e.id]??e.title,{fork:!!(e.forkFrom||e.forked||ee?.parentSessionPath),scheduler:!!(e.elsewhere&&e.owner?.startsWith(`scheduler:`))},V);return(0,$.jsxs)(`div`,{className:`lp-row${t>0?` lp-sub`:``}${n?` lp-has-kids`:``}`,"data-session-key":H,style:t>0?{"--depth":Math.min(t,4)}:void 0,onMouseLeave:()=>y(e=>e===se?null:e),onContextMenu:t=>b(t,{id:e.id,kind:`running`,label:e.title}),children:[(0,$.jsx)(X5,{editing:k===`conv:${e.id}`,className:`session-item lp-tree-session-item ${G?`active`:``}${ae?` is-running`:``}${oe?` is-unread`:``}`,title:`${e.title}${c?``:` — ${e.cwd}`}`,"aria-current":G?`true`:void 0,"data-lp-nav":``,onClick:()=>{J5(e.id),e.sessionId&&J5(e.sessionId),e.sessionFile&&J5(e.sessionFile),G||w({type:`switch_conversation`,id:e.id,...e.engine?{engine:e.engine}:{}})},children:(0,$.jsxs)(`div`,{className:`conv-main-col`,children:[(0,$.jsxs)(`div`,{className:`conv-title-row`,children:[e.nativeCli?(0,$.jsx)(Q5,{engine:e.nativeCli.config?.preset??e.engine,className:`native-cli-conversation-icon${ne?` is-running`:re?` is-waiting`:J?` is-exited`:``}`,title:q?`${V(`nativeCli`)} (${V(`nativeCliSession.${q===`waiting_input`?`waitingInput`:q===`waiting_approval`?`waitingApproval`:q}`)||q})`:V(`nativeCli`),ariaLabel:V(`nativeCli`)}):(0,$.jsx)(Q5,{engine:e.engine}),G&&(0,$.jsx)(`span`,{className:`conv-current-badge`,children:V(`current`)}),k===`conv:${e.id}`?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:j,placeholder:V(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>M(e.target.value),onKeyDown:t=>{t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing?N(`conv:${e.id}`,{type:`rename_conversation`,id:e.id},e.id,e.title):t.key===`Escape`&&P()},onBlur:()=>N(`conv:${e.id}`,{type:`rename_conversation`,id:e.id},e.id,e.title)}):(0,$.jsx)(`span`,{className:`conv-title-text`,title:e.title,children:ce}),e.nativeCli&&(0,$.jsx)(`span`,{className:`lp-cli-badge`,children:`CLI`}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[n&&(0,$.jsx)(Z5,{count:i,isCollapsed:r,hasStreaming:a,hasQuestion:s,hasError:o,onToggle:()=>T(e.id)}),(0,$.jsx)(e7,{time:W?h5(W):void 0,children:s||e.hasQuestion||re?(0,$.jsx)(`span`,{className:`status-question-right`,title:q===`waiting_approval`?V(`nativeCliSession.waitingApproval`):V(`nativeCliSession.waitingInput`)||V(`waitingQuestionBadge`),children:`?`}):ae?(0,$.jsx)(`div`,{className:`status-spinner-right`,title:V(`streaming`)}):e.error||q===`error`?(0,$.jsx)(`span`,{className:`status-error-right`,title:e.error||e.nativeCli?.status?.error||V(`nativeCliSession.error`),children:`!`}):oe?(0,$.jsx)(`span`,{className:`status-unread-right`,title:V(`completedUnreadTooltip`),children:(0,$.jsx)(z,{size:13,strokeWidth:3,"aria-hidden":`true`})}):null})]})]}),(()=>{let t=$5(e,V);return e.pinned||e.isEphemeral||le||e.agentPreset&&e.agentPreset!==`standard`||t?(0,$.jsxs)(`div`,{className:`conv-tags-row`,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:V(`pinnedConversation`),children:`📌`}),e.isEphemeral&&(0,$.jsx)(`span`,{className:`ephemeral-badge`,title:V(`newChatEphemeralTip`),children:V(`newChatEphemeral`)}),le&&(0,$.jsx)(`span`,{className:`category-badge-pill ${le.key}`,children:le.label}),e.agentPreset&&e.agentPreset!==`standard`&&(0,$.jsx)(`span`,{className:`category-badge-pill subagent`,title:e.agentPreset,children:E?.[e.agentPreset]??e.agentPreset}),t]}):null})()]})}),!Y&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:V(`renameSession`),onClick:t=>{t.stopPropagation(),y(null),M(e.title),A(se)},children:(0,$.jsx)(et,{})}),(()=>{let t=se,n=Y,r=F(f,e.id),i=I(f,e.id),a=L(f,e.id);return a===0&&!e.isStreaming?e.hasUserTerminals?D(t,V(`dismissConversation`),V(`dismissTerminalsConfirm`),()=>w({type:`dismiss_conversation`,id:e.id,force:!0}),(0,$.jsx)(Ct,{})):D(t,V(`dismissConversation`),V(`dismissConversationConfirm`),()=>w({type:`dismiss_conversation`,id:e.id}),(0,$.jsx)(Ct,{}),!e.nativeCli):a===0?D(t,V(`dismissConversation`),V(`dismissStreamingConfirm`),()=>w({type:`dismiss_conversation`,id:e.id,force:!0}),(0,$.jsx)(Ct,{})):n?(0,$.jsxs)(`span`,{className:`lp-del-group`,children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-del-opt danger`,title:V(`forceDismissTitle`,{n:a,m:i}),onClick:t=>{t.stopPropagation(),y(null),w({type:`dismiss_conversation`,id:e.id,force:!0})},children:V(`dismissForceAll`)}),(0,$.jsx)(`button`,{type:`button`,className:`lp-del confirm`,title:i>0&&r>0?V(`dismissFinishedSubagentsScoped`,{n:r}):V(`dismissConversationConfirm`),onClick:t=>{t.stopPropagation(),y(null),w({type:`dismiss_conversation`,id:e.id,withFinishedSubagents:!0})},children:(0,$.jsx)(z,{})})]}):(0,$.jsx)(`button`,{type:`button`,className:`lp-del`,title:V(`dismissConversation`),onClick:e=>{e.stopPropagation(),y(t)},children:(0,$.jsx)(Ct,{})})})(),R(B,`lp-slot-sessions`)]})}function n7({session:e,currentFile:t,sharedConversationOwner:n,activeConversationId:r,transition:i,getHistoryRunningInfo:a,checkUnread:o,renameOverrides:s,renaming:c,setRenaming:l,renameDraft:u,setRenameDraft:d,commitRename:f,cancelRename:p,confirmDel:m,setConfirmDel:h,openSessionMenu:g,panelSend:_,delButton:v,renderInlineEntries:y,historyRowEntries:b}){let x=X(),S=e.displayName||e.name||e.firstMessage?.trim(),C=S&&S.length>0?S:x(`emptyChat`),w=Co(t),T=Co(e.path),E=a(e),D=!!(!n&&r&&E?.conv?.id===r||w&&w===T&&(!E?.conv?.id||!r||E.conv.id===r)),O=i?.kind===`session`&&Co(i.target)===T,k=!!E?.isStreaming,A=!!E?.hasQuestion,j=!!(E?.hasError||E?.error),M=!!(e.nativeCli||E?.conv?.nativeCli),N=E?.conv?.nativeCli?.status?.phase,P=M?V5(E?.conv?.nativeCli,E?.conv?.error):void 0,F=P===`busy`,I=P===`waiting`,L=P===`ended`,R=!!(k||A||E?.conv?.completionPending||E?.conv?.isStreaming||F),B=!D&&!R&&o({id:E?.conv?.id,sessionId:e.sessionId,sessionFile:e.path,path:e.path}),V=s[e.path]??C,{cleanTitle:H,categoryTag:ee}=m5(V,{fork:!!(e.parentSessionPath||E?.conv?.forkFrom||E?.conv?.forked),scheduler:!!(E?.conv?.elsewhere&&E.conv.owner?.startsWith(`scheduler:`)),tui:e.source===`tui`},x),U=T||Co(e.sessionId)||e.path;return(0,$.jsxs)(`div`,{className:`lp-row`,"data-session-key":U,onMouseLeave:()=>h(t=>t===`sess:${e.path}`?null:t),onContextMenu:t=>g(t,{id:e.path,kind:`history`,label:V,pinned:e.pinned}),children:[(0,$.jsx)(X5,{editing:c===e.path,className:`session-item lp-tree-session-item ${D?`active`:``} ${O?`switching`:``}${R?` is-running`:``}${B?` is-unread`:``}`,title:e.path,disabled:O,"aria-current":D?`true`:void 0,"data-lp-nav":``,onClick:()=>{c||O||(J5(e.path),e.sessionId&&J5(e.sessionId),E?.conv?.id&&J5(E.conv.id),E?.conv?.id&&!E.conv.elsewhere?D||_({type:`switch_conversation`,id:E.conv.id,...E.conv.engine?{engine:E.conv.engine}:{}}):D||_({type:`switch_session`,path:e.path,...e.engine?{engine:e.engine}:{}}))},children:(0,$.jsxs)(`div`,{className:`conv-main-col`,children:[(0,$.jsxs)(`div`,{className:`conv-title-row`,children:[D&&(0,$.jsx)(`span`,{className:`conv-current-badge`,children:x(`current`)}),M?(0,$.jsx)(Q5,{engine:e.nativeCli?.preset??E?.conv?.nativeCli?.config?.preset??e.engine,className:`native-cli-conversation-icon${F?` is-running`:I?` is-waiting`:L?` is-exited`:``}`,title:N?`${x(`nativeCli`)} (${x(`nativeCliSession.${N===`waiting_input`?`waitingInput`:N===`waiting_approval`?`waitingApproval`:N}`)||N})`:x(`nativeCli`),ariaLabel:x(`nativeCli`)}):(0,$.jsx)(Q5,{engine:e.engine}),c===e.path?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:u,placeholder:x(`renameSessionPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>d(e.target.value),onKeyDown:t=>{t.stopPropagation(),t.key===`Enter`&&!t.nativeEvent.isComposing?f(e.path,{type:`rename_session`,path:e.path},e.path,V):t.key===`Escape`&&p()},onBlur:()=>f(e.path,{type:`rename_session`,path:e.path},e.path,V)}):(0,$.jsx)(`span`,{className:`conv-title-text`,title:V,children:H}),M&&(0,$.jsx)(`span`,{className:`lp-cli-badge`,children:`CLI`}),(0,$.jsx)(`span`,{className:`conv-meta-zone`,children:(0,$.jsx)(e7,{time:h5(e.modified),children:O?(0,$.jsx)(Am,{className:`status-spinner-right`}):A||I?(0,$.jsx)(`span`,{className:`status-question-right`,title:N===`waiting_approval`?x(`nativeCliSession.waitingApproval`):x(`nativeCliSession.waitingInput`)||x(`waitingQuestionBadge`),children:`?`}):k||F?(0,$.jsx)(`div`,{className:`status-spinner-right`,title:x(`streaming`)}):j||N===`error`?(0,$.jsx)(`span`,{className:`status-error-right`,title:E?.error||E?.conv?.nativeCli?.status?.error||x(`nativeCliSession.error`),children:`!`}):R?(0,$.jsx)(`span`,{className:`status-pulse-right`,title:x(`tabRunning`)}):B?(0,$.jsx)(`span`,{className:`status-unread-right`,title:x(`completedUnreadTooltip`),children:(0,$.jsx)(z,{size:13,strokeWidth:3,"aria-hidden":`true`})}):null})})]}),(e.pinned||E?.conv?.isEphemeral||ee)&&(0,$.jsxs)(`div`,{className:`conv-tags-row`,children:[e.pinned&&(0,$.jsx)(`span`,{className:`pin-badge`,title:x(`pinnedConversation`),children:`📌`}),E?.conv?.isEphemeral&&(0,$.jsx)(`span`,{className:`ephemeral-badge`,title:x(`newChatEphemeralTip`),children:x(`newChatEphemeral`)}),ee&&(0,$.jsx)(`span`,{className:`category-badge-pill ${ee.key}`,children:ee.label})]})]})}),m!==`sess:${e.path}`&&(0,$.jsx)(`button`,{type:`button`,className:`lp-del lp-rename`,title:x(`renameSession`),onClick:t=>{t.stopPropagation(),h(null),d(e.name??``),l(e.path)},children:(0,$.jsx)(et,{})}),!k&&v(`sess:${e.path}`,x(`deleteSession`),x(`deleteSessionConfirm`),()=>{_({type:`delete_session`,path:e.path,...e.engine?{engine:e.engine}:{}})}),y(b,`lp-slot-sessions`)]})}async function r7(e,t){return ln(`/api/device-center/local-bots/${e}`,{body:t,signal:AbortSignal.timeout(2e4),errorFor:e=>Error(e.serverError||e.code||e.error)})}function i7(e,t){return!t||[e.scope,e.summary,e.text].some(e=>e.toLowerCase().includes(t))}function a7(e){if(!Number.isFinite(e)||e<=0)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleDateString()}function o7(e){return e.source===`bot`&&e.hits<2}function s7({botId:e,botName:t,onClose:n}){let r=X(),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(``),m=Rt();Lt(n);let h=(0,Q.useCallback)(async()=>{try{a(await r7(`${encodeURIComponent(e)}/memory`)),s(``)}catch(e){s(e instanceof Error?e.message:String(e))}},[e]);(0,Q.useEffect)(()=>{h()},[h]);let g=(0,Q.useMemo)(()=>{let e=f.trim().toLowerCase();return(i?.entries??[]).filter(t=>i7(t,e))},[i,f]),_=(0,Q.useCallback)(async(e,t)=>{d(!0),l(``);try{await t(),l(e),await h()}catch(e){s(e instanceof Error?e.message:String(e))}finally{d(!1)}},[h]),v=(0,Q.useCallback)(t=>_(r(`botMemory.promoted`),()=>r7(`${encodeURIComponent(e)}/memory/promote`,t.confidence===`confirmed`?{id:t.id}:{id:t.id,confirm:!0})),[_,e,r]),y=(0,Q.useCallback)(async()=>{d(!0);try{let n=await r7(`${encodeURIComponent(e)}/home`),i=new Blob([JSON.stringify(n.bundle,null,2)],{type:`application/json;charset=utf-8`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=`${t.replace(/[^\w.-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`bot`}-home.json`,o.click(),URL.revokeObjectURL(a),l(r(`botMemory.exportedBundle`))}catch(e){s(e instanceof Error?e.message:String(e))}finally{d(!1)}},[e,t,r]),b=(0,Q.useCallback)(async()=>{d(!0);try{let n=await r7(`${encodeURIComponent(e)}/memory/export`),i=new Blob([n.markdown],{type:`text/markdown;charset=utf-8`}),a=URL.createObjectURL(i),o=document.createElement(`a`);o.href=a,o.download=`${t.replace(/[^\w.-]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,40)||`bot`}-memory.md`,o.click(),URL.revokeObjectURL(a),l(r(`botMemory.exportedMarkdown`))}catch(e){s(e instanceof Error?e.message:String(e))}finally{d(!1)}},[e,t,r]);return(0,$.jsx)(`div`,{className:`lp-memory-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":r(`botMemory.titleNamed`,{name:t}),style:{zIndex:m},children:(0,$.jsxs)(`div`,{className:`lp-memory-dialog`,children:[(0,$.jsxs)(`header`,{className:`lp-memory-head`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{children:r(`botMemory.titleNamed`,{name:t})}),(0,$.jsx)(`p`,{className:`lp-memory-sub`,children:r(`botMemory.subtitle`)})]}),(0,$.jsxs)(`div`,{className:`lp-memory-head-actions`,children:[(0,$.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>void _(r(`botMemory.compacted`),()=>r7(`${encodeURIComponent(e)}/memory/compact`,{})),children:r(`botMemory.compact`)}),(0,$.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>void b(),children:r(`botMemory.export`)}),(0,$.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>void y(),children:r(`botMemory.bundle`)}),(0,$.jsx)(`button`,{type:`button`,onClick:n,children:r(`botMemory.close`)})]})]}),c&&(0,$.jsx)(`p`,{className:`lp-memory-notice`,children:c}),o&&(0,$.jsx)(`p`,{className:`lp-memory-error`,role:`alert`,children:o}),i&&i.scopes.length>0&&(0,$.jsx)(`p`,{className:`lp-memory-scopes`,children:i.scopes.map(e=>(0,$.jsxs)(`span`,{className:`lp-memory-scope`,children:[e.scope,` · `,e.entries,e.resident?` (${r(`botMemory.residentCount`,{count:e.resident})})`:``]},e.scope))}),(0,$.jsx)(`input`,{type:`search`,className:`lp-memory-search`,value:f,placeholder:r(`botMemory.search`),"aria-label":r(`botMemory.search`),onChange:e=>p(e.target.value)}),(0,$.jsxs)(`div`,{className:`lp-memory-list`,children:[i&&i.entries.length===0&&(0,$.jsx)(`p`,{className:`lp-memory-empty`,children:r(`botMemory.empty`)}),i&&i.entries.length>0&&g.length===0&&(0,$.jsx)(`p`,{className:`lp-memory-empty`,children:r(`botMemory.searchEmpty`,{query:f.trim()})}),g.map(t=>{let n=a7(t.createdAt),i=o7(t);return(0,$.jsxs)(`article`,{className:`lp-memory-entry`,children:[(0,$.jsxs)(`div`,{className:`lp-memory-entry-head`,children:[(0,$.jsx)(`span`,{className:`lp-memory-scope`,children:t.scope}),(0,$.jsx)(`span`,{className:`lp-memory-badge`,title:r(`botMemory.confidenceTip`,{value:t.confidence}),children:t.confidence}),t.resident&&(0,$.jsx)(`span`,{className:`lp-memory-badge is-resident`,children:r(`botMemory.resident`)}),n&&(0,$.jsx)(`span`,{className:`lp-memory-meta`,children:r(`botMemory.created`,{date:n})}),(0,$.jsxs)(`span`,{className:`lp-memory-meta`,title:`${t.source}:${t.sourceId}`,children:[t.source,`:`,t.sourceId,` · `,r(`botMemory.hits`,{count:t.hits})]})]}),(0,$.jsx)(`p`,{className:`lp-memory-text`,children:t.text}),(0,$.jsxs)(`div`,{className:`lp-memory-entry-actions`,children:[!t.resident&&(0,$.jsx)(`button`,{type:`button`,disabled:u||i,title:i?r(`botMemory.promoteBlocked`):void 0,onClick:()=>void v(t),children:t.confidence===`confirmed`?r(`botMemory.promote`):r(`botMemory.promoteConfirm`)}),(0,$.jsx)(`button`,{type:`button`,disabled:u,onClick:()=>void _(r(`botMemory.forgotten`),()=>r7(`${encodeURIComponent(e)}/memory/forget`,{id:t.id})),children:r(`botMemory.forget`)})]})]},t.id)})]})]})})}async function c7(e){return(await ln(`/api/device-center/local-bots/${encodeURIComponent(e)}/sessions`,{signal:AbortSignal.timeout(2e4)})).sessions??[]}function l7(e){if(!Number.isFinite(e)||e<=0)return``;let t=new Date(e);return Number.isNaN(t.getTime())?``:t.toLocaleString()}function u7({botId:e,botName:t,onClose:n}){let r=X(),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``),c=Rt();Lt(n);let l=(0,Q.useCallback)(async()=>{try{a(await c7(e)),s(``)}catch(e){s(e instanceof Error?e.message:String(e))}},[e]);(0,Q.useEffect)(()=>{l()},[l]);let u=e=>{Z({type:`switch_session`,path:e.path}),n()};return(0,$.jsx)(`div`,{className:`lp-memory-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":r(`agentBotsHistoryTitle`,{name:t}),style:{zIndex:c},children:(0,$.jsxs)(`div`,{className:`lp-memory-dialog lp-bot-history`,children:[(0,$.jsxs)(`header`,{className:`lp-memory-head`,children:[(0,$.jsx)(`strong`,{children:r(`agentBotsHistoryTitle`,{name:t})}),(0,$.jsx)(`button`,{type:`button`,onClick:n,children:r(`agentBotsHistoryClose`)})]}),o&&(0,$.jsxs)(`p`,{className:`lp-memory-error`,role:`alert`,children:[r(`agentBotsHistoryFailed`),`:`,o]}),i===null&&!o&&(0,$.jsx)(`p`,{className:`lp-memory-empty`,children:r(`agentBotsLoading`)}),i&&i.length===0&&(0,$.jsx)(`p`,{className:`lp-memory-empty`,children:r(`agentBotsHistoryEmpty`)}),i&&i.length>0&&(0,$.jsx)(`ul`,{className:`lp-bot-history-list`,children:i.map(e=>(0,$.jsxs)(`li`,{className:`lp-bot-history-row`,children:[(0,$.jsxs)(`div`,{className:`lp-bot-history-text`,children:[(0,$.jsx)(`span`,{className:`lp-bot-history-title`,children:e.title?.trim()||r(`agentBotsHistoryUntitled`)}),(0,$.jsx)(`span`,{className:`lp-bot-history-meta`,children:r(`agentBotsHistoryUpdated`,{date:l7(e.updatedAt)})})]}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>u(e),children:r(`agentBotsHistoryOpen`)})]},e.path))})]})})}function d7({onClose:e,cwd:t}){return(0,Er.createPortal)((0,$.jsx)(Cf,{createOnly:!0,initialCwd:t??void 0,onCancel:e,onCreated:t=>{e(),t?.id&&cd(t.id)}}),document.body)}async function f7(e,t){let n=await ln(`/api/device-center/local-bots/${encodeURIComponent(e)}`,{signal:t});if(!n.bot)throw Error(`Bot not found`);return n.bot}function p7({botId:e,onClose:t}){let n=X(),r=Rt(),[i,a]=(0,Q.useState)(null),[o,s]=(0,Q.useState)(``);return Lt(t,!i),(0,Q.useEffect)(()=>{let t=new AbortController;return a(null),s(``),f7(e,t.signal).then(e=>{t.signal.aborted||a(e)}).catch(e=>{t.signal.aborted||s(e instanceof Error?e.message:String(e))}),()=>t.abort()},[e]),i?(0,Er.createPortal)((0,$.jsx)(Cf,{editBot:i,onCancel:t,onFinished:t}),document.body):(0,Er.createPortal)((0,$.jsx)(`div`,{className:`lp-memory-backdrop`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`agentBotsMenuEdit`),style:{zIndex:r},children:(0,$.jsxs)(`div`,{className:`lp-memory-dialog`,children:[(0,$.jsxs)(`header`,{className:`lp-memory-head`,children:[(0,$.jsx)(`strong`,{children:n(`agentBotsMenuEdit`)}),(0,$.jsx)(`button`,{type:`button`,onClick:t,children:n(`agentBotsMemoryClose`)})]}),o?(0,$.jsxs)(`p`,{className:`lp-memory-error`,role:`alert`,children:[n(`agentBotsFailed`),`:`,o]}):(0,$.jsx)(`p`,{className:`lp-memory-empty`,children:n(`agentBotsLoading`)})]})}),document.body)}function m7(e,t=36){let n=e.replace(/[\\/]+$/,``);return n.length<=t?n:`…${n.slice(1-t)}`}function h7(e,t){let n=[t(`agentBotsOpen`,{name:e.name})];return e.busy===!0&&n.push(t(`agentBotsBusyTip`)),e.cwd&&n.push(`${t(`agentBotsWorkspace`)}: ${m7(e.cwd)}`),n.join(`
|
|
402
|
-
`)}function g7(){window.dispatchEvent(new CustomEvent(`pi-web-ui:device-group-open`,{detail:{create:!0}}))}function _7({active:e=!0,activeBotId:t,cwd:n,botDraftPrompt:r,botDraftDefaultPrompt:i}){let o=X(),s=_n(),[c,l]=(0,Q.useState)(null),[u,d]=(0,Q.useState)(null),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(``),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(!1),S=(0,Q.useRef)(null),C=T_({open:b,anchor:S,onClose:()=>x(!1),side:`top`,align:`right`}),[w,T]=(0,Q.useState)(``),[E,O]=(0,Q.useState)(!1),[k,A]=(0,Q.useState)(null),j=(0,Q.useRef)(0),M=(0,Q.useCallback)(async()=>{let e=++j.current,t=new AbortController;try{let n=await wp(`bot-panel`,t.signal);if(e!==j.current)return;l((n.bots??[]).filter(e=>e.enabled).sort((e,t)=>e.name.localeCompare(t.name))),T(``)}catch(t){if(e!==j.current)return;T(t instanceof Error?t.message:String(t))}},[]);(0,Q.useEffect)(()=>{if(!e)return;M();let t=()=>void M();return window.addEventListener(gp,t),window.addEventListener(`pi-web-ui:device-bots-changed`,t),()=>{window.removeEventListener(gp,t),window.removeEventListener(`pi-web-ui:device-bots-changed`,t)}},[e,M]),(0,Q.useEffect)(()=>B6(()=>y(!0)),[]);let N=(0,Q.useCallback)((e,t)=>{A(e.id),cd(e.id,t),window.setTimeout(()=>A(null),400)},[]),P=(0,Q.useCallback)((e,t)=>{e.preventDefault(),e.stopPropagation();let n=[{action:`chat`,label:o(`agentBotsMenuChat`),hint:void 0},{action:`new-chat`,label:o(`agentBotsMenuNewChat`),hint:o(`agentBotsMenuNewChatTip`)},{action:`reference`,label:o(`agentBotsMenuReference`),hint:o(`agentBotsMenuReferenceTip`)},{action:`history`,label:o(`agentBotsMenuHistory`),hint:o(`agentBotsMenuHistoryTip`)},{action:`edit`,label:o(`agentBotsMenuEdit`),hint:void 0},{action:`manage`,label:o(`agentBotsMenuManage`),hint:void 0},{action:`memory`,label:o(`agentBotsMenuMemory`),hint:void 0},{action:`copy-id`,label:o(`agentBotsMenuCopyId`),hint:void 0}].map((e,t)=>({id:`host:bot-${e.action}`,slot:`contextmenu.bot`,source:`host`,label:e.label,...e.hint?{hint:e.hint}:{},kind:`action`,action:e.action,order:(t+1)*10,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}));jf({x:e.clientX,y:e.clientY,slot:`contextmenu.bot`,target:{id:t.id,kind:`agent-bot`,label:t.name},entries:n,onHostAction:e=>{e.action===`chat`?N(t):e.action===`new-chat`?N(t,{fresh:!0}):e.action===`reference`?N6({botId:t.id,name:t.name}):e.action===`edit`?h(t.id):e.action===`manage`?ld():e.action===`memory`?d(t):e.action===`history`?p(t):e.action===`copy-id`&&Kn(t.id)}})},[N,o]);return(0,$.jsxs)(`section`,{className:`lp-bots-section`,"aria-label":o(`agentBotsTitle`),"aria-busy":!c&&!w,children:[(0,$.jsxs)(`div`,{className:`lp-bots-header`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-bots-toggle`,"aria-expanded":!E,"aria-label":o(E?`agentBotsExpand`:`agentBotsCollapse`),onClick:()=>O(e=>!e),children:[(0,$.jsx)(fe,{"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`lp-bots-title`,children:o(`agentBotsTitle`)}),v7(c)>0&&(0,$.jsx)(`span`,{className:`lp-bots-count`,children:v7(c)}),(0,$.jsx)(`span`,{className:`lp-section-chevron`,"aria-hidden":`true`,children:E?(0,$.jsx)(D,{}):(0,$.jsx)(a,{})})]}),(0,$.jsxs)(`div`,{className:`lp-bots-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`lp-bots-group`,title:o(`createGroup`),"aria-label":o(`createGroup`),onClick:g7,children:(0,$.jsx)(K,{"aria-hidden":`true`})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-bots-manage`,title:o(`agentBotsManageTip`),"aria-label":o(`agentBotsManage`),onClick:ld,children:(0,$.jsx)(ze,{"aria-hidden":`true`})}),(0,$.jsxs)(`div`,{className:`lp-bots-create-wrap`,children:[(0,$.jsx)(`button`,{type:`button`,ref:S,className:`lp-bots-import`,title:o(`agentBotsCreateTitle`),"aria-label":o(`agentBotsCreateTitle`),"aria-expanded":b,"aria-haspopup":`menu`,onClick:()=>x(e=>!e),children:`+`}),b&&(0,Er.createPortal)((0,$.jsxs)(`div`,{ref:C.panelRef,className:`lp-bots-create-menu`,style:C.style,role:`menu`,children:[(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{x(!1);let e=s.ephemeralChat!==!1;Z(e?{type:`new_chat`,ephemeral:!0}:{type:`new_chat`}),H6(),er()},children:o(`agentBotsCreateAi`)}),(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,onClick:()=>{x(!1),z6()},children:o(`agentBotsCreateManual`)})]}),document.body)]})]})]}),(0,$.jsx)(`div`,{className:`lp-bots-scroll`,children:!E&&(0,$.jsxs)(`div`,{className:`lp-bots-body`,children:[g&&(0,$.jsx)(`p`,{className:`lp-bots-notice`,children:g}),w&&(0,$.jsxs)(`div`,{className:`lp-bots-error`,children:[(0,$.jsx)(`span`,{children:o(`agentBotsFailed`)}),(0,$.jsx)(`button`,{type:`button`,onClick:()=>void M(),children:o(`agentBotsRetry`)})]}),!w&&!c&&(0,$.jsx)(`p`,{className:`lp-bots-empty`,children:o(`agentBotsLoading`)}),!w&&c&&c.length===0&&(0,$.jsx)(`p`,{className:`lp-bots-empty`,children:o(`agentBotsEmpty`)}),(c??[]).map(e=>{let n=t===e.id;return(0,$.jsxs)(`div`,{className:`lp-bot-item`,onContextMenu:t=>P(t,e),children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-bot-row${n?` is-active`:``}`,title:h7(e,o),"aria-pressed":n,disabled:k!==null,onClick:()=>void N(e),children:[(0,$.jsx)(`span`,{className:`lp-bot-avatar${e.online?` is-online`:``}`,"aria-hidden":`true`,children:e.name.slice(0,1).toUpperCase()}),(0,$.jsxs)(`span`,{className:`lp-bot-meta`,children:[(0,$.jsx)(`span`,{className:`lp-bot-name`,children:e.name}),(0,$.jsx)(`span`,{className:`lp-bot-sub`,children:k===e.id?o(`agentBotsStarting`):e.online===!1?o(`agentBotsOffline`):e.deviceName??`Bot`})]}),e.busy===!0&&(0,$.jsx)(`span`,{className:`lp-bot-busy`,title:o(`agentBotsBusyTip`),children:o(`agentBotsBusy`)})]}),(0,$.jsx)(`button`,{type:`button`,className:`lp-bot-memory`,title:o(`agentBotsMemoryTip`),"aria-label":o(`agentBotsMemory`),onClick:()=>d(e),children:`🧠`})]},e.id)})]})}),f&&(0,$.jsx)(u7,{botId:f.id,botName:f.name,onClose:()=>p(null)}),u&&(0,$.jsx)(s7,{botId:u.id,botName:u.name,onClose:()=>d(null)}),m&&(0,$.jsx)(p7,{botId:m,onClose:()=>h(null)}),v&&(0,$.jsx)(d7,{cwd:n,onClose:()=>y(!1)})]})}function v7(e){return e?.length??0}var y7=`pi-web-ui:project-click-switch`,b7=new Set;function x7(){for(let e of b7)e()}function S7(e){return b7.add(e),()=>{b7.delete(e)}}function C7(){try{let e=localStorage.getItem(y7);return e===null||e!==`0`}catch{return!0}}var w7=null;function T7(){return w7===null&&(w7=C7()),w7}function E7(e){try{localStorage.setItem(y7,e?`1`:`0`)}catch{}w7=e,x7()}function D7(){return(0,Q.useSyncExternalStore)(S7,T7)}function O7(){return T7()}function k7({hasGroupsSection:e,uiSections:t,active:n,activeGroupId:r,activeBotId:i,cwd:a,currentCwd:o,botDraftPrompt:s,botDraftDefaultPrompt:c,collapseProjects:l,effFlex:u,newChatSplitRef:d,panelSend:f,engine:p,newChatEngineOpen:m,setNewChatEngineOpen:h,isEngineInstalled:g,newChatEngineMenu:_,onCreateCli:v,triggerInstallEngine:y,searchOpen:b,setSearchOpen:x,filterText:S,setFilterText:w,filterInputRef:T,workspaceMenuAnchor:E,workspaceMenuOpen:O,setWorkspaceMenuOpen:k,workspaceMenu:A,uiProjectsActions:j,renderInlineEntries:M,collapsible:N,onToggleCollapse:P,tabs:F,setProjectPickerInitialTab:I,setProjectPickerOpen:L,onOpenSandboxModal:R,effectiveProjects:B,projectScrollRef:V,handleBlankDoubleClick:H,handleTreeKeyDown:ee,focusTreeItem:W,parseProjectEnv:G,projectDisplayName:K,envFilter:q,setEnvFilter:te,transition:ne,projectTreeModel:re,renameOverrides:J,displayName:ie,everExpandedRef:ae,dropHint:oe,setDropHint:se,dragProject:Y,setDragProject:ce,moveProject:le,setConfirmDel:de,confirmDel:fe,openProjectMenu:pe,setExpandedProjects:me,toggleProjectExpand:he,renaming:_e,setRenaming:ve,renameDraft:ye,setRenameDraft:be,commitRename:xe,cancelRename:Se,setRemovedProjectsVersion:Ce,uiLeftProject:we,renderSingleConvRow:Te,renderHistorySessionRow:De,failedProjects:Oe,ready:ke,status:Ae,requestSessions:je,serverListLimit:Me,loadingMore:Pe,setProjectVisibleCounts:Fe,renderPluginRunning:Ie}){let Le=X();return(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`lp-section panel-projects ${l?`collapsed`:``}`,style:l?void 0:{flex:`${u} 1 0px`},children:[(0,$.jsxs)(`div`,{className:`lp-c-top-header`,children:[(0,$.jsxs)(`div`,{className:`lp-new-chat-split`,ref:d,children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-new-chat-primary`,title:Le(`newChatInCurrentProjectTip`),onClick:()=>{f({type:`new_chat`}),er()},children:[(0,$.jsx)(ue,{"aria-hidden":`true`}),(0,$.jsx)(`span`,{children:Le(`newChatAction`)}),(0,$.jsx)(Q5,{engine:p,className:`lp-new-chat-engine-glyph`})]}),(0,$.jsx)(`button`,{type:`button`,className:`lp-new-chat-engine-btn`,"aria-haspopup":`menu`,"aria-expanded":m,title:Le(`settingsEngineSection`),onClick:()=>h(e=>{let t=!e;return t&&Ox.some(e=>!g(e.id))&&Z({type:`check_engines`,force:!0}),t}),children:(0,$.jsx)(D,{"aria-hidden":`true`})}),m&&(0,Er.createPortal)((0,$.jsxs)(`div`,{ref:_.panelRef,className:`lp-new-chat-engine-menu`,style:_.style,role:`menu`,children:[(0,$.jsx)(`div`,{className:`lp-new-chat-engine-head`,children:Le(`settingsEngineSection`)}),Ox.map(e=>{let t=g(e.id),n=Dx[e.id],r=!!(v&&n?.cliCommand),i=e.installCommand??n?.installCommand,s=p===e.id,c=()=>{h(!1),t?(f({type:`new_chat`,engine:e.id,cwd:o}),er()):y(e.badge,i)};return(0,$.jsxs)(`div`,{role:`menuitem`,tabIndex:0,className:`lp-new-chat-engine-row${s?` active`:``}${t?``:` uninstalled`}`,title:Le(t?e.descKey:`engineInstallTip`),onClick:c,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),c())},children:[(0,$.jsx)(Q5,{engine:e.id}),(0,$.jsx)(`span`,{className:`lp-new-chat-engine-name`,children:Le(e.titleKey)}),t?(0,$.jsxs)(`span`,{className:`lp-new-chat-engine-actions`,children:[s&&(0,$.jsx)(z,{size:12,className:`lp-new-chat-engine-check`,"aria-hidden":`true`}),r&&(0,$.jsx)(`button`,{type:`button`,className:`lp-new-chat-cli-pill`,title:`${n.name} CLI`,onClick:t=>{t.stopPropagation(),h(!1),f({type:`new_cli_chat`,config:{preset:e.id},cwd:a})},children:`CLI`})]}):(0,$.jsx)(`span`,{className:`lp-new-chat-engine-install-pill`,children:Le(`engineInstall`)})]},e.id)}),v&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`lp-new-chat-engine-divider`,role:`separator`}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`lp-new-chat-engine-row lp-new-chat-engine-custom`,onClick:()=>{h(!1),v(a)},children:[(0,$.jsx)(Xe,{size:12,className:`lp-new-chat-custom-icon`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`lp-new-chat-engine-name`,children:[Le(`nativeCliCreate`),`…`]})]})]})]}),document.body)]}),(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-c-icon-btn${b||S?` active`:``}`,title:Le(`lpFilterPlaceholder`),"aria-label":Le(`lpFilterPlaceholder`),onClick:()=>{x(e=>{let t=!e;return t?setTimeout(()=>T.current?.focus(),0):w(``),t})},children:(0,$.jsx)(mt,{})}),(0,$.jsxs)(`div`,{className:`lp-section-actions`,children:[(0,$.jsx)(`button`,{type:`button`,ref:E,className:`lp-section-action lp-project-action lp-c-icon-btn ${O?`active`:``}`,title:O?void 0:Le(`openProject`),"aria-label":Le(`openProject`),"aria-expanded":O,onClick:e=>{e.stopPropagation(),k(e=>!e)},children:(0,$.jsx)(Ee,{})}),M(j,`lp-slot-section`)]}),N&&P&&(0,$.jsx)(`button`,{type:`button`,className:`lp-section-action lp-c-icon-btn`,title:Le(`collapsePanel`),"aria-label":Le(`collapsePanel`),onClick:P,children:(0,$.jsx)(U,{})}),O&&(0,Er.createPortal)((0,$.jsxs)(`div`,{ref:A.panelRef,className:`lp-workspace-menu`,style:A.style,role:`menu`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item lp-new-chat-btn`,title:Le(`newChatInCurrentProjectTip`),onClick:()=>{k(!1),f({type:`new_chat`}),er()},children:[(0,$.jsx)(C,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:Le(`newChatAction`)})]}),v&&(!F||F.includes(`terminal`))&&(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item lp-new-cli-btn`,onClick:()=>{k(!1),v(a)},children:[(0,$.jsx)(Xe,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:Le(`nativeCliCreate`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item lp-manage-projects-btn`,onClick:()=>{k(!1),I(`local`),L(!0)},children:[(0,$.jsx)(ge,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:Le(`openLocalProject`)})]}),(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item lp-manage-projects-btn`,onClick:()=>{k(!1),I(`remote`),L(!0)},children:[(0,$.jsx)(ut,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:Le(`openRemoteProject`)})]}),R&&(0,$.jsxs)(`button`,{type:`button`,className:`lp-workspace-menu-item`,onClick:()=>{k(!1),R()},children:[(0,$.jsx)(rp,{style:{fontSize:`13px`}}),(0,$.jsx)(`span`,{children:Le(`sandboxNewShort`)})]})]}),document.body)]}),!l&&B.length>0&&(0,$.jsxs)(`div`,{className:`lp-section-body projects-scroll`,ref:V,onDoubleClick:H,role:`tree`,"aria-label":Le(`lpProjectsTree`),onKeyDown:ee,children:[(b||S)&&(0,$.jsxs)(`div`,{className:`lp-filter`,children:[(0,$.jsx)(mt,{"aria-hidden":`true`}),(0,$.jsx)(`input`,{ref:T,type:`search`,value:S,placeholder:Le(`lpFilterPlaceholder`),"aria-label":Le(`lpFilterPlaceholder`),onChange:e=>w(e.target.value),onKeyDown:e=>{e.key===`Escape`?(e.stopPropagation(),S?w(``):x(!1)):e.key===`ArrowDown`&&(e.preventDefault(),W(e.currentTarget,1))}}),S&&(0,$.jsx)(`button`,{type:`button`,className:`lp-filter-clear`,title:Le(`lpFilterClear`),"aria-label":Le(`lpFilterClear`),onClick:()=>w(``),children:(0,$.jsx)(Ct,{})})]}),B.some(e=>G(e.path,K(e)).isRemote)&&(0,$.jsx)(`div`,{className:`lp-env-pills`,role:`tablist`,"aria-label":Le(`lpProjectsTree`),children:[`all`,`local`,`remote`].map(e=>(0,$.jsx)(`button`,{type:`button`,role:`tab`,"aria-selected":q===e,className:`lp-env-pill${q===e?` active`:``}`,onClick:()=>te(e),children:Le(e===`all`?`lpEnvAll`:e===`local`?`lpEnvLocal`:`lpEnvRemote`)},e))}),(()=>{let e=ne?.kind===`cwd`?Co(ne.target):null,t=S.trim().toLowerCase(),n=re.map(e=>{let n=K(e.p),r=G(e.p.path,n);if(q===`local`&&r.isRemote||q===`remote`&&!r.isRemote)return null;let i=new Set([...e.idleSessions.slice(0,e.maxVisible),...e.idleSessions.filter(e=>e.pinned)]),a={...e,orderedBlocks:e.orderedBlocks.filter(e=>e.kind===`conversation`||i.has(e.target))};if(!t||n.toLowerCase().includes(t)||r.label.toLowerCase().includes(t)||e.p.path.toLowerCase().includes(t))return a;let o=e.pRunningRows.filter(e=>(e.c.title??``).toLowerCase().includes(t)),s=e.idleSessions.filter(e=>(J[e.path]??ie(e)).toLowerCase().includes(t));if(o.length===0&&s.length===0)return null;let c=new Set(o.map(e=>e.c.id)),l=new Set(s.slice(0,50)),u=e.orderedBlocks.map(e=>{if(e.kind===`session`)return l.has(e.target)?e:null;let t=e.rows.filter(e=>c.has(e.c.id));return t.length>0?{...e,rows:t}:null}).filter(e=>e!==null);return{...e,isCollapsed:!1,pRunningRows:o,idleSessions:s,orderedBlocks:u,maxVisible:50,hasMore:!1}});return t&&n.every(e=>e===null)?(0,$.jsx)(`div`,{className:`lp-filter-empty`,children:Le(`lpFilterNoMatch`)}):n.map(t=>{if(!t)return null;let{p:n,pNorm:r,active:i,isCollapsed:a,isLoadingSessions:o,pRunningRows:s,idleSessions:c,orderedBlocks:l,maxVisible:u,hasMore:d,actuallyRunningCount:p,unreadCount:m,serverHasMore:h}=t,g=e!==null&&e===r,_=n.sandbox,v=K(n),y=_?{label:v,isRemote:!1,envTag:void 0}:G(n.path,v),b=p>0,x=c.length>0,S=m>0;a||ae.current.add(r);let C=c.some(e=>e.pinned),w=!a||s.length>0||S||i||C||ae.current.has(r),T=oe?.path===n.path&&Y&&Y!==n.path?oe.after?` drop-after`:` drop-before`:``;return(0,$.jsxs)(`div`,{className:`lp-project-node${Y===n.path?` dragging`:``}${T}`,role:`treeitem`,"aria-expanded":!a,"aria-selected":i,onDragOver:e=>{if(!Y||Y===n.path)return;e.preventDefault(),e.dataTransfer.dropEffect=`move`;let t=e.currentTarget.getBoundingClientRect(),r=e.clientY>t.top+Math.min(t.height,32)/2;(oe?.path!==n.path||oe.after!==r)&&se({path:n.path,after:r})},onDrop:e=>{if(!Y)return;e.preventDefault();let t=e.currentTarget.getBoundingClientRect();le(Y,n.path,e.clientY>t.top+Math.min(t.height,32)/2),ce(null),se(null)},children:[(0,$.jsxs)(`div`,{className:`lp-row lp-project-head-row${i?` active`:``}${g?` switching`:``}${a?` is-collapsed`:` is-expanded`}${b?` has-running`:``}${S?` has-unread`:``}`,draggable:!g,onDragStart:e=>{e.dataTransfer.effectAllowed=`move`,e.dataTransfer.setData(`text/plain`,n.path),ce(n.path)},onDragEnd:()=>{ce(null),se(null)},onMouseLeave:()=>de(e=>e===`proj:${n.path}`?null:e),onContextMenu:e=>pe(e,n),children:[(0,$.jsxs)(`button`,{type:`button`,className:`lp-project-header-item project-item ${i?`active`:``} ${g?`switching`:``}${b?` has-running`:``}${S?` has-unread`:``}`,title:`${_?.sourcePath?`${v}\n${Le(`sandboxSourceLabel`)}: ${_.sourcePath}\n${n.path}`:n.path}\n${Le(`lpDragToReorder`)}`,disabled:g,"data-lp-nav":``,"data-project-path":n.path,"aria-current":i?`true`:void 0,"aria-keyshortcuts":`Alt+ArrowUp Alt+ArrowDown`,onClick:()=>{g||(!i&&O7()?(f({type:`set_cwd`,path:n.path}),me(e=>{let t=Co(n.path);if(e.has(t))return e;let r=new Set(e);return r.add(t),r})):he(n.path))},onDoubleClick:e=>{e.stopPropagation(),g||(f({type:`new_chat`,cwd:n.path}),er())},children:[(0,$.jsx)(`span`,{className:`lp-project-chevron`,"aria-hidden":`true`,onClick:e=>{e.stopPropagation(),he(n.path)},title:Le(a?`expandSection`:`collapseSection`),children:a?(0,$.jsx)(ep,{size:14}):(0,$.jsx)(np,{size:14})}),_&&(0,$.jsx)(rp,{className:`project-icon sandbox-icon`}),_e===`proj:${n.path}`?(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:ye,placeholder:Le(`renameProjectPlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>be(e.target.value),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`&&!e.nativeEvent.isComposing?xe(`proj:${n.path}`,{type:`rename_project`,path:n.path},`proj:${n.path}`,n.name??``):e.key===`Escape`&&Se()},onBlur:()=>xe(`proj:${n.path}`,{type:`rename_project`,path:n.path},`proj:${n.path}`,n.name??``)}):(0,$.jsx)(`span`,{className:`lp-project-name`,title:n.path,children:y.label}),(0,$.jsx)(`span`,{className:`lp-env-tag`,children:y.envTag??`LOCAL`}),_&&(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${_.ephemeral?`ephemeral`:`permanent`}`,children:_.ephemeral?Le(`sandboxBadgeEphemeral`):Le(`sandboxBadgePermanent`)}),(0,$.jsxs)(`span`,{className:`conv-meta-zone`,children:[g&&(0,$.jsx)(Am,{className:`status-spinner-right`}),b&&(0,$.jsxs)(`span`,{className:`lp-project-running-badge`,title:Le(`tabRunning`),children:[(0,$.jsx)(`span`,{className:`lp-project-running-dot`}),(0,$.jsx)(`span`,{children:p})]}),S&&(0,$.jsxs)(`span`,{className:`lp-project-unread-badge`,title:Le(`completedUnreadBadge`),children:[(0,$.jsx)(`span`,{className:`lp-project-unread-dot`}),(0,$.jsx)(`span`,{children:m})]}),(0,$.jsx)(`span`,{className:`project-time ${g?`switching-pct`:``}`,children:g?`${ne?.progress??0}%`:n.lastUsed>0?h5(n.lastUsed):``})]})]}),(0,$.jsxs)(`div`,{className:`lp-project-actions`,children:[!_&&fe!==`proj:${n.path}`&&(0,$.jsx)(`button`,{type:`button`,className:`lp-project-btn lp-project-rename-btn`,title:Le(`renameProject`),onClick:e=>{e.stopPropagation(),de(null),be(n.name??``),ve(`proj:${n.path}`)},children:(0,$.jsx)(et,{})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-project-btn lp-project-new-chat-btn`,title:Le(`newChat`),onClick:e=>{e.stopPropagation(),f({type:`new_chat`,cwd:n.path}),er()},children:(0,$.jsx)(ue,{})}),(0,$.jsx)(`button`,{type:`button`,className:`lp-project-btn lp-project-del-btn ${fe===`proj:${n.path}`?`confirm danger`:``}`,title:fe===`proj:${n.path}`?Le(_?`sandboxActionDestroy`:`deleteProjectConfirm`):Le(_?`sandboxActionDestroyTip`:`deleteProject`),onClick:e=>{e.stopPropagation(),fe===`proj:${n.path}`?(de(null),Ro(n.path),cs(n.path),ns(n.path),Ce(e=>e+1),f(_?{type:`destroy_sandbox`,path:n.path}:{type:`remove_project`,path:n.path})):de(`proj:${n.path}`)},children:fe===`proj:${n.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(Ne,{})}),M(we,`lp-slot-project`,{id:n.path,kind:`project`,label:v})]})]}),w&&(0,$.jsxs)(`div`,{className:`lp-project-tree-children${a?` is-collapsed`:` is-expanded`}${s.length>0?` has-running-rows`:``}`,children:[l.map(e=>{let t=g5(a,e);return(0,$.jsx)(Q.Fragment,{children:e.kind===`conversation`?e.rows.map(e=>Te(e,n.path)):(0,$.jsx)(`div`,{className:`lp-history-collapsible${a&&!t?` collapsed`:` expanded`}${t?` is-pinned-visible`:``}`,children:(0,$.jsx)(`div`,{className:`lp-history-collapsible-inner`,children:De(e.target,n.path)})})},e.key)}),(0,$.jsx)(`div`,{className:`lp-history-collapsible${a?` collapsed`:` expanded`}`,children:(0,$.jsxs)(`div`,{className:`lp-history-collapsible-inner`,children:[s.length===0&&c.length===0&&!Oe.has(r)&&(0,$.jsx)(`div`,{className:`lp-project-empty-tip`,children:o?(0,$.jsx)(`span`,{children:Le(`loadingSessions`)}):(0,$.jsx)(`span`,{children:Le(`noSessionsYet`)})}),Oe.has(r)&&(0,$.jsx)(`button`,{type:`button`,className:`lp-show-more-row lp-retry-chip`,disabled:!ke||Ae!==`open`,onClick:()=>je({type:`list_sessions`,path:n.path,limit:Me(n.path)}),children:Le(`sessionsLoadFailed`)}),d&&(0,$.jsx)(`button`,{type:`button`,className:`lp-show-more-row`,"data-lp-nav":``,disabled:Pe.has(r),onClick:e=>{e.stopPropagation();let t=u+10;if(Fe(e=>({...e,[r]:t})),h&&t>=c.length){let e=Math.max(20,t+10);je({type:`list_sessions`,path:n.path,limit:e})}},children:(0,$.jsx)(`span`,{children:Pe.has(r)?Le(`loadingSessions`):Le(`lpShowMore`,{n:c.length>u?`${c.length-u}${h?`+`:``}`:`…`})})})]})}),a&&x&&(s.length>0||S)&&(0,$.jsxs)(`button`,{type:`button`,className:`lp-collapsed-history-tip`,"data-lp-nav":``,onClick:e=>{e.stopPropagation(),he(n.path)},title:Le(`expandSection`),children:[(0,$.jsx)(`span`,{children:Le(`lpCollapsedHistory`,{n:c.length})}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`›`})]})]})]},n.path)})})(),Ie()]})]}),(0,$.jsx)(_7,{active:n,activeBotId:i,cwd:a,botDraftPrompt:s,botDraftDefaultPrompt:c}),e&&(0,$.jsx)(Op,{entry:t?.find(e=>e.id===`host:lp-groups`),active:n,selectedRoomId:r,hideWhenEmpty:!0,autoHeight:!0})]})}var A7=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,j7=e=>e?e.trim().replace(/\\/g,`/`).replace(/\/+$/,``).toLowerCase():``,M7=e=>e.endsWith(`.jsonl`);function N7(e){if(!M7(e))return null;let t=A_(e)?.trim()??``;return A7.test(t)?t.toLowerCase():null}function P7(e){let t=[],n=e.id?.trim();n&&t.push(`conv:${n.replace(/\\/g,`/`).toLowerCase()}`);let r=e.sessionId?.trim();r&&t.push(`sid:${r.toLowerCase()}`);let i=j7(e.sessionFile||e.path);if(i){t.push(`file:${i}`);let e=N7(i);e?t.push(`sid:${e}`):i.includes(`/`)||t.push(`conv:${i}`)}return[...new Set(t)]}var F7=/^(?:events|session|transcript|history|messages)(?:\.v\d+)?\.jsonl(?:\.zstd)?$/;function I7(e){let t=P7(e),n=j7(e.sessionFile||e.path).split(`/`).pop();return n&&!F7.test(n)?[...t,`fn:${n}`]:t}var L7=class{items=new Map;add(e,t,n=P7(e)){for(let e of n)this.items.set(e,t);return t}get(e,t=P7(e)){for(let e of t){let t=this.items.get(e);if(t!==void 0)return t}}has(e){return this.get(e)!==void 0}get size(){return this.items.size}};function R7(e,t,n,r){if(t.id===n)return r&&(e.get(n)?.isSubagent??!1);let i=t,a=new Set;for(;i?.parentId;){if(i.parentId===n)return!0;if(a.has(i.parentId)||(a.add(i.parentId),i=e.get(i.parentId),!i))return!1}return!1}function z7(e,t,n){if(!n)return e.filter(e=>e.isSubagent&&!e.isStreaming&&e.id!==t).length;let r=new Map(e.map(e=>[e.id,e]));return e.filter(e=>e.isSubagent&&!e.isStreaming&&e.id!==t&&R7(r,e,n,!0)).length}function B7(e,t){if(!t)return e.filter(e=>e.isSubagent).length;let n=new Map(e.map(e=>[e.id,e]));return e.filter(e=>e.isSubagent&&R7(n,e,t,!0)).length}function V7(e,t){if(!t)return 0;let n=new Map(e.map(e=>[e.id,e]));return e.filter(e=>e.isSubagent&&e.isStreaming&&R7(n,e,t,!1)).length}function H7(e,t){let n=new Set,r=new Set;for(let t of e)t.sessionFile&&n.add(t.sessionFile),r.add(`${t.cwd}\0${t.title}`);let i=[],a=new Set;for(let e of t){if(!e.convId&&e.independent!==!1&&(e.sessionFile&&n.has(e.sessionFile)||r.has(`${e.cwd}\0${e.title}`)))continue;let t=e.convId?`conv:${e.owner}:${e.convId}`:e.sessionFile?`file:${e.sessionFile}`:`title:${e.cwd}\0${e.title}`;if(a.has(t))continue;a.add(t);let o=e.convId&&e.owner?`elsewhere:${e.owner}:${e.convId}`:e.sessionFile?`elsewhere:${e.owner}:${e.cwd}:${e.sessionFile}`:`elsewhere:${e.cwd}:${e.title}${e.owner?`:${e.owner}`:``}`,s=e.isSubagent&&e.owner&&e.parentId?`elsewhere:${e.owner}:${e.parentId}`:void 0;i.push({id:o,title:e.title,cwd:e.cwd,messageCount:0,isStreaming:e.isStreaming,isSubagent:!!e.isSubagent,...s?{parentId:s}:{},elsewhere:!0,pseudo:!!e.pseudo,independent:e.independent,...e.forked?{forked:!0}:{},ownerOffline:!!e.ownerOffline,sessionFile:e.sessionFile,...e.owner&&e.convId?{owner:e.owner,convId:e.convId}:{},...e.hasQuestion?{hasQuestion:!0}:{}})}let o=new Set(e.map(e=>e.id));for(let e of i)o.add(e.id);let s=i.filter(e=>!e.isSubagent||!!(e.parentId&&o.has(e.parentId)));return[...e,...s]}function U7(e){let t=new Map,n=new Map;for(let n of e)t.set(n.id,n);for(let r of e)if(r.parentId&&t.has(r.parentId)){let e=n.get(r.parentId)??[];e.push(r),n.set(r.parentId,e)}let r=e=>{let t=[],r=[...n.get(e)??[]],i=new Set;for(;r.length>0;){let e=r.shift();if(i.has(e.id))continue;i.add(e.id),t.push(e);let a=n.get(e.id);a&&r.push(...a)}return t},i=new L7;for(let t of e){let e=r(t.id),n=e.some(e=>e.isStreaming||e.completionPending),a=e.some(e=>!!e.hasQuestion),o=e.some(e=>!!e.error),s={conv:t,isStreaming:!!(t.isStreaming||t.completionPending||n),hasQuestion:!!(t.hasQuestion||a),hasError:!!(t.error||o),error:t.errorInfo?.summary??t.error};i.add(t,s,I7(t))}return i}function W7({effectiveProjects:e,currentCwd:t,runningAll:n,expandedProjects:r,projectSessions:i,sessions:a,loadingProjects:o,activeConversationId:s,collapsedSubagents:c,checkUnread:l,projectVisibleCounts:u,projectSessionsHasMore:d,ready:f}){let p=Co(t),m=new Map,h=new Set;for(let e of Xx(n,t,s)){let t=Co(e.cwd),n=m.get(t);m.set(t,n?[...n,...e.convs]:e.convs)}for(let e of n)e.parentId&&h.add(e.parentId);let g=new L7;return e.map(e=>{let t=Co(e.path),n=t===p,s=!r.has(t),_=m.get(t)??[],v=i?.[t],y=a&&a.length>0&&Wo(a[0],e.path)?a:v??(n?a:[]),b=!n&&v===void 0&&o.has(t)&&y.length===0,x=null,S=()=>{if(x)return x;let e=new L7;for(let t of y)e.add(t,!0);return x=e,e},C=e=>e.isStreaming||e.completionPending||e.hasQuestion||e.isSubagent||e.parentId||h.has(e.id)||e.pinned||e.nativeCli?!0:!e.sessionFile&&!S().has(e),w=mo(`all`,e.path);ho.observe(w,[..._,...y],!!(f&&(!i||t in i)));let T=ho.sort(w,_,e=>e,!1),E=_.some(e=>e.rowKind!==void 0),D=T.filter(e=>e.elsewhere?!0:E?e.rowKind!==`history`:C(e)),O=Zx(D,c);for(let e of D)g.add(e,!0);let k=ho.sort(w,y.filter(t=>!Wo(t,e.path)||g.has(t)?!1:(g.add(t,!0),!0)),e=>e,!1),A=O.filter(e=>e.c.isStreaming||e.hasStreaming||e.c.hasQuestion||e.hasQuestion||e.c.completionPending||!!(e.c.nativeCli&&V5(e.c.nativeCli,e.c.error)===`busy`)).length,j=D.filter(e=>!e.isStreaming&&!e.completionPending&&l({id:e.id,sessionId:e.sessionId,sessionFile:e.sessionFile})).length,M=k.filter(e=>l({sessionId:e.sessionId,sessionFile:e.path,path:e.path})).length,N=u[t]??5,P=[];for(let e of O){let t=P.at(-1);e.depth>0&&t?.kind===`conversation`?t.rows.push(e):P.push({kind:`conversation`,target:e.c,rows:[e]})}for(let e of k)P.push({kind:`session`,target:e});let F=ho.sort(w,P,e=>e.target,!1).map(e=>({...e,key:ho.key(w,e.target)})),I=!!d?.[t];return{serverHasMore:I,p:e,pNorm:t,active:n,isCollapsed:s,isLoadingSessions:b,pRunningRows:O,idleSessions:k,orderedBlocks:F,maxVisible:N,hasMore:!s&&(k.length>N||I),actuallyRunningCount:A,unreadCount:j+M}})}var G7=(0,Q.memo)(function({sessionFile:e,conversations:t,elsewhere:n,sessions:r,projects:i,activeConversationId:a,sharedConversationOwner:o,activeGroupId:s,activeBotId:c,projectSessions:l,projectSessionsHasMore:u,engine:d,connectionEpoch:f,unreadConvKeys:p,panelSend:m,active:h,collapsible:g,onToggleCollapse:_,pathCompletions:v,uiContextSession:y,quickAskReferenceMenus:b=!0,botDraftPrompt:x,botDraftDefaultPrompt:S,uiLeftSessions:C,uiContextProject:w,uiProjectsActions:T,uiLeftProject:E,uiRunningActions:D,uiHistoryActions:O,uiSections:k,renderPluginSectionBody:A,uiPluginRunning:j,onPluginRunningAction:M,uiLeftRunning:N,uiLeftHistory:P,onUiAction:F,presetNames:I,transition:L,onOpenSandboxModal:R,onCreateCli:z}){let B=_n(),V=Y5(),H=p??V,ee=(0,Q.useCallback)(e=>_5(H,e),[H]),U=e,W=mn(`ready`),G=mn(`tabs`),K=mn(`status`),q=mn(`cwd`),te=mn(`workspaceRoots`),ne=q,re=_o(),[J,ie]=(0,Q.useState)(!1),[ae,oe]=(0,Q.useState)(void 0),[se,Y]=(0,Q.useState)(null),[ce,le]=(0,Q.useState)(0),[ue,de]=(0,Q.useState)(null),[fe,pe]=(0,Q.useState)(``),[me,he]=(0,Q.useState)(!1),[ge,_e]=(0,Q.useState)(`all`),ve=(0,Q.useRef)(null),ye=(0,Q.useRef)(null),{renaming:be,setRenaming:xe,renameDraft:Se,setRenameDraft:Ce,renameOverrides:we,cancelRename:Te,commitRename:Ee,collapseProjects:De,setCollapseGroups:Oe,hasGroupsSection:ke,effectivePlan:Ae,effFlex:je,sashAfter:Me,renderPluginRunning:Ne,renderPluginSection:Pe,newChatEngineOpen:Fe,setNewChatEngineOpen:Ie,newChatSplitRef:Le,newChatEngineMenu:Re,isEngineInstalled:ze,triggerInstallEngine:Be}=R5({panelRef:ye,uiSections:k,uiPluginRunning:j,onPluginRunningAction:M,renderPluginSectionBody:A,sessions:r,projectSessions:l,conversations:t,projects:i,panelSend:m}),[Ve,He]=F5(),[Ue,We]=(0,Q.useState)(!1),Ge=(0,Q.useRef)(null),Ke=T_({open:Ue,anchor:Ge,onClose:()=>We(!1),side:`bottom`,align:`right`}),qe=(0,Q.useRef)(null),Je=(0,Q.useRef)(new Set);E5(qe,W);let{effectiveProjects:Ye,moveProject:Xe,dragProject:Ze,setDragProject:Qe,dropHint:$e,setDropHint:et,expandedProjects:tt,setExpandedProjects:nt,projectVisibleCounts:rt,setProjectVisibleCounts:it,serverListLimit:at,requestSessions:ot,loadingProjects:st,failedProjects:ct,loadingMore:lt,toggleProjectExpand:ut}=w5({projects:i,currentCwd:ne,conversations:t,elsewhere:n,activeConversationId:a,removedProjectsVersion:ce,panelSend:m,ready:W,status:K,engine:d,connectionEpoch:f,sessions:r,projectSessions:l}),dt=(0,Q.useCallback)((e,t)=>z7(e,a,t),[a]),{forceArmedRef:X,sessionMenuAvailable:ft,showSessionMenu:pt,renderInlineEntries:mt,openSessionMenu:ht}=T5({uiContextSession:y,quickAskReferenceMenus:b,conversations:t,sessions:r,elsewhere:n,finishedSubagentCount:dt,conversationRefCapability:B.conversationRef,panelSend:m,setConfirmDel:Y,setRenameDraft:Ce,setRenaming:xe,onUiAction:F}),gt=(0,Q.useMemo)(()=>H7(t,n),[t,n]),_t=(0,Q.useMemo)(()=>U7(gt),[gt]),vt=(0,Q.useCallback)(e=>e.path.startsWith(`conv:`)&&_t.has({id:e.path})?_t.get({id:e.path}):_t.get(e,I7(e)),[_t]),yt=(0,Q.useMemo)(()=>W7({effectiveProjects:Ye,currentCwd:ne,runningAll:gt,expandedProjects:tt,projectSessions:l,sessions:r,loadingProjects:st,activeConversationId:a,collapsedSubagents:Ve,checkUnread:ee,projectVisibleCounts:rt,projectSessionsHasMore:u,ready:W}),[Ye,ne,gt,tt,l,r,st,a,Ve,ee,rt,u,W,re]),bt=(0,Q.useMemo)(()=>[...C??[],...N??[]],[C,N]),xt=(0,Q.useMemo)(()=>[...C??[],...P??[]],[C,P]);(0,Q.useEffect)(()=>{h&&W&&K===`open`&&q&&(m({type:`list_sessions`,limit:at(q)}),m({type:`list_projects`}))},[h,W,K,q,m]);let{displayName:St,projectDisplayName:Ct,parseProjectEnv:wt,focusTreeItem:Tt,handleTreeKeyDown:Et,openProjectMenu:Dt,delButton:Ot,sectionHeader:kt,handleBlankDoubleClick:At}=D5({effectiveProjects:Ye,expandedProjects:tt,moveProject:Xe,toggleProjectExpand:ut,renameOverrides:we,uiContextProject:w,panelSend:m,confirmDel:se,setConfirmDel:Y,setRenameDraft:Ce,setRenaming:xe}),jt={currentFile:U,sharedConversationOwner:o,activeConversationId:a,transition:L,getHistoryRunningInfo:vt,checkUnread:ee,renameOverrides:we,renaming:be,setRenaming:xe,renameDraft:Se,setRenameDraft:Ce,commitRename:Ee,cancelRename:Te,confirmDel:se,setConfirmDel:Y,openSessionMenu:ht,panelSend:m,delButton:Ot,renderInlineEntries:mt,historyRowEntries:xt},Mt={projects:(0,$.jsx)(k7,{hasGroupsSection:ke,uiSections:k,active:h,activeGroupId:s,activeBotId:c,cwd:q,currentCwd:ne,botDraftPrompt:x,botDraftDefaultPrompt:S,collapseProjects:De,effFlex:je(`projects`),newChatSplitRef:Le,panelSend:m,engine:d,newChatEngineOpen:Fe,setNewChatEngineOpen:Ie,isEngineInstalled:ze,newChatEngineMenu:Re,onCreateCli:z,triggerInstallEngine:Be,searchOpen:me,setSearchOpen:he,filterText:fe,setFilterText:pe,filterInputRef:ve,workspaceMenuAnchor:Ge,workspaceMenuOpen:Ue,setWorkspaceMenuOpen:We,workspaceMenu:Ke,uiProjectsActions:T,renderInlineEntries:mt,collapsible:g,onToggleCollapse:_,tabs:G,setProjectPickerInitialTab:oe,setProjectPickerOpen:ie,onOpenSandboxModal:R,effectiveProjects:Ye,projectScrollRef:qe,handleBlankDoubleClick:At,handleTreeKeyDown:Et,focusTreeItem:Tt,parseProjectEnv:wt,projectDisplayName:Ct,envFilter:ge,setEnvFilter:_e,transition:L,projectTreeModel:yt,renameOverrides:we,displayName:St,everExpandedRef:Je,dropHint:$e,setDropHint:et,dragProject:Ze,setDragProject:Qe,moveProject:Xe,setConfirmDel:Y,confirmDel:se,openProjectMenu:Dt,setExpandedProjects:nt,toggleProjectExpand:ut,renaming:be,setRenaming:xe,renameDraft:Se,setRenameDraft:Ce,commitRename:Ee,cancelRename:Te,setRemovedProjectsVersion:le,uiLeftProject:E,renderSingleConvRow:(e,n)=>(0,$.jsx)(t7,{item:e,projectPath:n,currentCwd:ne,sessions:r,projectSessions:l,conversations:t,sharedConversationOwner:o,activeConversationId:a,checkUnread:ee,confirmTakeover:ue,setConfirmTakeover:de,confirmDel:se,setConfirmDel:Y,openSessionMenu:ht,showSessionMenu:pt,sessionMenuAvailable:ft,forceArmedRef:X,panelSend:m,toggleSubagents:He,presetNames:I,delButton:Ot,renameOverrides:we,renaming:be,setRenaming:xe,renameDraft:Se,setRenameDraft:Ce,commitRename:Ee,cancelRename:Te,finishedSubagentCount:dt,countRunningSubagentDescendants:V7,countScopeSubagents:B7,renderInlineEntries:mt,runningRowEntries:bt},e.c.id),renderHistorySessionRow:(e,t)=>(0,$.jsx)(n7,{session:e,...jt},e.path),failedProjects:ct,ready:W,status:K,requestSessions:ot,serverListLimit:at,loadingMore:lt,setProjectVisibleCounts:it,renderPluginRunning:Ne}),convs:null,sessions:null},Nt=e=>e===`groups`?(0,$.jsx)(Op,{entry:k?.find(e=>e.id===`host:lp-groups`),active:h,selectedRoomId:s,flex:je(`groups`),onCollapsedChange:Oe}):e===`projects`||e===`convs`||e===`sessions`?Mt[e]:Pe(e,kt);return(0,$.jsxs)(`aside`,{ref:ye,className:`panel panel-left lp-panel`,children:[Ae.map(({key:e})=>(0,$.jsxs)(Q.Fragment,{children:[Nt(e),Me.get(e)??null]},e)),(0,$.jsx)(qd,{open:J,initialTab:ae,currentCwd:ne,pathCompletions:v??[],workspaceRoots:te,onClose:()=>ie(!1),onSelectDirectory:(e,t)=>m({type:`set_cwd`,path:e,...t?{name:t}:{}}),onCreateProject:(e,t)=>m({type:`make_dir`,path:e,setAsCwd:!0,...t?{name:t}:{}})})]})});function K7(e,t,n){let r=!1;for(let i of t){let t=i;if(t.type!==`image`||typeof t.dataUrl!=`string`)continue;if(/^\/api\/attachment\/[a-f0-9]{64}$/.test(t.dataUrl)){r=!0,e.push({path:``,imageUrl:t.dataUrl,mimeType:t.mimeType,name:n??`image`});continue}if(!t.dataUrl.startsWith(`data:`))continue;let a=t.dataUrl.match(/^data:([^;]*);base64,(.+)$/);a&&(r=!0,e.push({path:``,imageData:a[2],mimeType:a[1]||`image/png`,name:n??`image.${(a[1]||`image/png`).split(`/`)[1]??`png`}`}))}return r}function q7(e){let t=e.details??{};if(t.mode===`quote`){let e=Sa(t.quote);return e?{path:``,mode:`quote`,quote:e}:null}let n=[];if(K7(n,e.content,t.name))return n[0]??null;if(t.upload&&t.path)return{path:``,uploadPath:t.path,name:t.name??t.path,size:t.size};if((t.mode===`page`||t.mode===`canvas`)&&t.path)return{path:t.path,mode:t.mode,name:t.name??t.path};if(t.mode===`conversation`){let e=t,n=typeof e.conversationId==`string`&&e.conversationId?e.conversationId:void 0,r=typeof e.sessionPath==`string`&&e.sessionPath?e.sessionPath:void 0;return n||r?{path:``,mode:`conversation`,name:t.name??n??r,...n?{conversationId:n}:{},...r?{sessionPath:r}:{}}:null}if(t.path&&t.mode){let e=t.mode===`lines`?`lines`:`reference`,n={path:t.path,mode:e};return t.mode===`lines`&&typeof t.startLine==`number`&&typeof t.endLine==`number`&&(n.lines={start:t.startLine,end:t.endLine}),n}return null}function J7(e){if(e.mode===`quote`&&e.quote)return`quote:${e.quote.messageId??``}:${e.quote.text}`;if(e.mode===`conversation`)return`conv:${e.conversationId??``}:${e.sessionPath??``}:${e.name??``}`;if(e.mode===`page`)return`page:${e.path}`;if(e.imageUrl)return`image-url:${e.imageUrl}`;if(e.imageData)return`img:${e.name??``}:${e.imageData.length}:${e.imageData.slice(0,64)}`;if(e.uploadPath)return`upload:${e.uploadPath}`;if(e.path){let t=e.lines?`${e.lines.start}-${e.lines.end}`:``;return`path:${e.mode??`ref`}:${e.path}:${t}`}return`unknown:${JSON.stringify(e)}`}function Y7(e){let t=new Set,n=[];for(let r of e){let e=J7(r);t.has(e)||(t.add(e),n.push(r))}return n}function X7(e){let t=new Map;for(let n=0;n<e.length;n++){let r=e[n];if(r.role!==`user`||!r.id)continue;let i=[];K7(i,r.content);let a=r.details?.quotes;for(let e of Array.isArray(a)?a:[]){let t=Sa(e);t&&i.push({path:``,mode:`quote`,quote:t})}let o=[];for(let t=n-1;t>=0&&e[t].role===`custom`&&e[t].customType===`file`;t--){let n=q7(e[t]);n&&o.unshift(n)}i.push(...o);for(let t=n+1;t<e.length&&e[t].role===`custom`&&e[t].customType===`file`;t++){let n=q7(e[t]);n&&i.push(n)}let s=Y7(i);s.length>0&&t.set(r.id,s)}return t}function Z7(e,t,n){let r=Math.max(0,t),i=Math.floor((r+4)/7),a=Math.min(e,i),o=Array.from({length:a},(t,r)=>{let i=Math.floor(r*e/a),o=Math.floor((r+1)*e/a)-1;return n>=i&&n<=o?n:r===a-1?o:i}),s=a>1?Math.min(27,(r-a*3)/(a-1)):0;return{indices:o,gap:s,many:e>a||a>1&&s<20}}var Q7=`pi-web-ui:wide-chat`,$7={wide:!1};function e9(e){if(!e||typeof e!=`object`)return{...$7};let t=e;return{wide:typeof t.wide==`boolean`?t.wide:$7.wide}}function t9(){try{let e=localStorage.getItem(Q7);return e?e9(JSON.parse(e)):{...$7}}catch{return{...$7}}}function n9(e){let t=e9(e);try{localStorage.setItem(Q7,JSON.stringify(t))}catch{}r9=t;for(let e of i9)e()}var r9=null,i9=new Set;function a9(e){return i9.add(e),()=>{i9.delete(e)}}function o9(){return r9||=t9(),r9.wide}function s9(){return(0,Q.useSyncExternalStore)(a9,o9)}var c9=`pi-web-ui:hide-model-row`,l9={hide:!1};function u9(e){if(!e||typeof e!=`object`)return{...l9};let t=e;return{hide:typeof t.hide==`boolean`?t.hide:l9.hide}}function d9(){try{let e=localStorage.getItem(c9);return e?u9(JSON.parse(e)):{...l9}}catch{return{...l9}}}function f9(e){let t=u9(e);try{localStorage.setItem(c9,JSON.stringify(t))}catch{}p9=t;for(let e of m9)e()}var p9=null,m9=new Set;function h9(e){return m9.add(e),()=>{m9.delete(e)}}function g9(){return p9||=d9(),p9.hide}function _9(){return(0,Q.useSyncExternalStore)(h9,g9)}var v9=`pi-web-ui:hide-question-nav`,y9={hide:!1};function b9(e){if(!e||typeof e!=`object`)return{...y9};let t=e;return{hide:typeof t.hide==`boolean`?t.hide:y9.hide}}function x9(){try{let e=localStorage.getItem(v9);return e?b9(JSON.parse(e)):{...y9}}catch{return{...y9}}}function S9(e){let t=b9(e);try{localStorage.setItem(v9,JSON.stringify(t))}catch{}C9=t;for(let e of w9)e()}var C9=null,w9=new Set;function T9(e){return w9.add(e),()=>{w9.delete(e)}}function E9(){return C9||=x9(),C9.hide}function D9(){return(0,Q.useSyncExternalStore)(T9,E9)}var O9=(0,Q.memo)(function({message:e,onExpand:t,summary:n}){let r=X(),i=Dl(),a=Sl(e),o=i.open&&i.selectedIds.includes(e.id),s=i.open&&a,c=n??``;if(!c)for(let t of e.content){let e=Gl(t);if(e&&e.text.trim()){let t=fl(e.text);c=t?`skill:${t.name}`+(t.userMessage?` · ${t.userMessage.replace(/\s+/g,` `).trim()}`:``):e.text.replace(/\s+/g,` `).trim();break}}if(!c&&e.role===`custom`&&e.customType===`file`){let t=e.details??{};c=t.name??t.path??``}c.length>90&&(c=`${c.slice(0,90)}…`);let l=0,u=0,d=0,f=0;for(let t of e.content)Kl(t)?l++:ql(t)?u++:Yl(t)?d++:Jl(t)&&f++;let p=[];return l&&p.push(`${r(`thinking`)} ${l}`),u&&p.push(`${r(`toolCalls`)} ${u}`),d&&p.push(`${r(`bashRuns`)} ${d}`),f&&p.push(`${r(`images`)} ${f}`),(0,$.jsxs)(`div`,{role:`button`,tabIndex:0,className:`msg-collapsed${o?` msg-export-selected`:``}`,"data-msg-id":e.id,title:`${r(`expandMsg`)} · ${c||p.join(` · `)||e.role}`,onClick:()=>t(e.id),onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(e.id))},children:[s&&(0,$.jsx)(`input`,{type:`checkbox`,className:`msg-export-check`,checked:o,title:r(`copyImage`),"aria-label":r(`copyImage`),onClick:e=>e.stopPropagation(),onChange:()=>jl(e.id)}),(0,$.jsx)(`span`,{className:`msg-collapsed-role role-${e.role}`,children:e.role===`custom`&&e.customType===`file`?r(`attachment`):nu(e.role,r)}),(0,$.jsxs)(`span`,{className:`msg-collapsed-body`,children:[c&&(0,$.jsx)(`span`,{className:`msg-collapsed-preview`,children:c}),p.length>0&&(0,$.jsx)(`span`,{className:`msg-collapsed-chips`,children:p.map((e,t)=>(0,$.jsx)(`span`,{className:`msg-collapsed-chip`,children:e},t))})]}),e.timestamp?(0,$.jsx)(`span`,{className:`msg-collapsed-time`,children:k9(e.timestamp)}):null,(0,$.jsx)(`span`,{className:`msg-collapsed-action`,children:r(`expandMsg`)})]})});function k9(e){let t=new Date(e);return`${String(t.getHours()).padStart(2,`0`)}:${String(t.getMinutes()).padStart(2,`0`)}`}var A9=`[goal-review]`;function j9(e){for(let t of e.content??[]){let e=Gl(t);if(e&&e.text.trim())return e.text}return``}function M9(e){if(e.role!==`assistant`)return;let t=j9(e).trim();if(!t.startsWith(`{`)||!t.endsWith(`}`))return;try{let e=JSON.parse(t);if(e&&typeof e==`object`&&(e.verdict===`pass`||e.verdict===`fail`))return e.verdict}catch{}let n=t.match(/^\{\s*"verdict"\s*:\s*"(pass|fail)"[^}]*\}$/);return n?n[1]:void 0}function N9(e){if(e.role===`user`&&j9(e).includes(A9))return{kind:`prompt`};let t=M9(e);if(t)return{kind:`verdict`,verdict:t}}var P9=`--flow-inline-stream`;function F9(){if(typeof window>`u`||typeof document>`u`)return!1;let e=getComputedStyle(document.documentElement).getPropertyValue(P9).trim();return e===`1`||e===`true`}function I9(){let[e,t]=(0,Q.useState)(F9);return(0,Q.useEffect)(()=>{let e=()=>t(F9());return e(),window.addEventListener(yr,e),()=>window.removeEventListener(yr,e)},[]),e}function L9(e){if(!Array.isArray(e.content))return``;for(let t of e.content){let e=Gl(t);if(e&&e.text.trim().length>0)return e.text}return``}function R9(e){return L9(e)!==``}function z9(e){if(e.role!==`user`)return null;let t=L9(e);return t?Xl(t):null}function B9(e){return z9(e)?.isNotice===!0}function V9(e){return e.role===`assistant`||!e.role}function H9(e){return e.customType||e.role!==`user`?!1:!z9(e)}function U9(e,t){if(!Array.isArray(e.content))return!1;for(let n of e.content){let e=ql(n);if(e){if(e.name===`present_files`&&Hp(e.argumentsText))return!0;if(e.name===`agent_bot`){if(Pp(e.argumentsText))return!0;if(t){let n=t.get(e.id);if(n&&Mp(n.details))return!0}}}}return!1}function W9(e,t){let n=new Set,r=-1;for(let t=e.length-1;t>=0;t--){let n=e[t];if(V9(n)&&R9(n)){r=t;break}}for(let i=0;i<e.length;i++){let a=e[i];B9(a)||(V9(a)?(i===r&&n.add(a),a.errorMessage&&n.add(a),t.streamingId&&a.id===t.streamingId&&n.add(a),t.keepIds?.has(a.id)&&n.add(a),U9(a,t.toolResults)&&n.add(a)):n.add(a))}return n}function G9(e,t,n){let r=[];for(let e of t)e.type===`single`?r.push(e.message):r.push(...e.messages);if(r.length===0)return;let i=W9(r,n),a=e.length,o=!1,s=[],c=-1,l=()=>{s.length!==0&&(e.push({type:`quiet_fold`,id:`quiet-${s[0].id}`,messages:s}),c=e.length-1,s=[])};for(let n of t){if(n.type===`single`){i.has(n.message)?(l(),e.push(n),!o&&H9(n.message)&&(a=e.length,o=!0)):s.push(n.message);continue}let t=n.messages.filter(e=>i.has(e));s.push(...n.messages.filter(e=>!i.has(e))),t.length!==0&&(l(),e.push(t.length===n.messages.length?n:{type:`tool_cluster`,id:`quiet-cluster-${t[0].id}`,messages:t}))}if(s.length>0){let t=c>=0?e[c]:null;t&&t.type===`quiet_fold`?t.messages.push(...s):e.splice(a,0,{type:`quiet_fold`,id:`quiet-${s[0].id}`,messages:s}),s=[]}}function K9(e,t={}){let n=[],r=[];for(let i of e)i.type===`single`&&r.length>0&&H9(i.message)&&(G9(n,r,t),r=[]),r.push(i);return G9(n,r,t),n}function q9(e){let t={total:e.length,thinking:0,tools:0,bash:0,collab:0,other:0};for(let n of e){if(B9(n)){t.collab++;continue}let e=!1;for(let r of n.content??[])Kl(r)?(t.thinking++,e=!0):ql(r)?(t.tools++,e=!0):Yl(r)&&(t.bash++,e=!0);e||t.other++}return t}function J9(e){let t=new Set,n=[];for(let r of e)for(let e of r.content??[]){let r=ql(e);r?.name&&!t.has(r.name)?(t.add(r.name),n.push(r.name)):Yl(e)&&!t.has(`bash`)&&(t.add(`bash`),n.push(`bash`))}return n}var Y9=(0,Q.memo)(function({id:e,show:t,height:n,containerRef:r,onMeasured:i,lazyRef:a,children:o}){let s=(0,Q.useRef)(null);return(0,Q.useLayoutEffect)(()=>{if(!t)return;let n=s.current;if(!n)return;let r=n.offsetHeight;r>0&&i?.(e,r)},[t,e,i]),t?(0,$.jsx)(`div`,{ref:a,"data-lazy-id":e,children:(0,$.jsx)(`div`,{ref:s,children:o})}):(0,$.jsx)(`div`,{ref:a,className:`msg-lazy-ph`,"data-msg-id":e,"data-lazy-id":e,style:{height:n},"aria-hidden":`true`})});function X9(e,t,n){if(t.length===0&&n.length===0)return e;let r=!1,i=new Set(e);for(let e of t)i.delete(e)&&(r=!0);for(let e of n)i.has(e)||(i.add(e),r=!0);return r?i:e}function Z9(e,t,n){let r=new Set,i=0;for(let a=e.length-1;a>=0&&!(a<e.length-1&&i>=n);a--){let n=e[a];r.add(n.id),i+=t.get(n.id)??Q9(n.role,n.customType)}return r}function Q9(e,t){switch(e){case`user`:return 72;case`assistant`:return 280;case`toolResult`:return 8;case`custom`:return t===`file`?96:72;default:return 60}}var $9=[`text`,`thinking`,`argumentsText`,`output`,`command`];function eS(e){let t=0;for(let n of e.content){n.type===`image`&&(t+=1);for(let e of $9){let r=n[e];typeof r==`string`&&(t+=r.length)}}return t}function tS(e,t,n,r){let i=n.get(e);return i&&i.len===t?i.h:r}function nS(e){let t=[];for(let n of e.content)n.type===`text`&&typeof n.text==`string`&&t.push(n.text);return t.join(`
|
|
403
|
-
`)}function rS(e,t){let n=[];for(let r of e.content)if(r.type===`text`&&typeof r.text==`string`)n.push(r.text);else if(r.type===`thinking`&&typeof r.thinking==`string`)n.push(r.thinking);else if(r.type===`toolCall`){if(typeof r.name==`string`&&n.push(r.name),typeof r.argumentsText==`string`&&n.push(r.argumentsText),typeof r.id==`string`){let e=t.get(r.id);if(e){let t=nS(e);t&&n.push(t)}}}else r.type===`bash`&&(typeof r.command==`string`&&n.push(r.command),typeof r.output==`string`&&n.push(r.output));return n.join(`
|
|
404
|
-
`)}function iS(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n}function aS(e,t,n,r){let i=new Map,a=n.toLowerCase();if(!a)return i;for(let n of e){if(!t.has(n.id))continue;let e=iS(rS(n,r).toLowerCase(),a);e>0&&i.set(n.id,e)}return i}function oS(e,t){let n=[],r=t.toLowerCase();if(!r)return n;let i=document.createTreeWalker(e,NodeFilter.SHOW_TEXT,{acceptNode(e){let t=e.parentElement;return!t||t.closest(`.search-bar`)||t.closest(`.msg-collapsed`)?NodeFilter.FILTER_REJECT:(e.textContent??``).toLowerCase().includes(r)?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(let e=i.nextNode();e;e=i.nextNode()){let t=(e.textContent??``).toLowerCase();if(!e.parentElement?.closest(`[data-msg-id]`))continue;let i=t.indexOf(r);for(;i!==-1;){let a=document.createRange();a.setStart(e,i),a.setEnd(e,i+r.length),n.push(a),i=t.indexOf(r,i+r.length)}}return n}function sS(e,t,n,r,i){let a=aS(n,r,t,i),o=new Map;for(let n of oS(e,t)){let e=n.startContainer.parentElement?.closest(`[data-msg-id]`);if(!e?.dataset.msgId)continue;let t=o.get(e.dataset.msgId);t?t.push(n):o.set(e.dataset.msgId,[n])}let s=[];for(let e of n){let t=o.get(e.id);if(t)for(let n=0;n<t.length;n++)s.push({kind:`dom`,range:t[n],msgId:e.id,k:n});let n=a.get(e.id);if(n)for(let t=0;t<n;t++)s.push({kind:`folded`,msgId:e.id,k:t})}return s}function cS(e,t){return e.findIndex(e=>e.msgId===t.msgId&&e.k===t.k)}function lS(e,t){let n=CSS;if(!n.highlights)return;if(t.length===0){n.highlights.delete(e);return}let r=window.Highlight;r&&n.highlights.set(e,new r(...t))}function uS(e,t){let n=[],r=e;for(;r&&r!==t;){let e=getComputedStyle(r);/(auto|scroll|hidden)/.test(e.overflowY+e.overflowX)&&(r.scrollHeight>r.clientHeight||r.scrollWidth>r.clientWidth)&&n.push(r),r=r.parentElement}return n}function dS(e,t){let n=t.startContainer.parentElement;for(let r of uS(n,e)){let e=t.getBoundingClientRect(),n=r.getBoundingClientRect();if(e.height<=0||e.width<=0)return;e.top>=n.top+4&&e.bottom<=n.bottom-4||(r.scrollTop+=e.top-n.top-(r.clientHeight-e.height)/2),e.left>=n.left+4&&e.right<=n.right-4||(r.scrollLeft+=e.left-n.left-(r.clientWidth-e.width)/2)}let r=t.getBoundingClientRect(),i=e.getBoundingClientRect();if(r.height<=0||r.width<=0)return;let a=r.top>=i.top+6&&r.bottom<=i.bottom-6,o=r.left>=i.left+6&&r.right<=i.right-6;a&&o||(a||(e.scrollTop+=r.top-i.top-(i.height-r.height)/2),o||(e.scrollLeft+=r.left-i.left-(i.width-r.width)/2))}function fS({containerRef:e,messages:t,collapsedIds:n,toolResults:r,onExpand:i,onProgrammaticScroll:o,open:s,onClose:c}){let l=X(),u=(0,Q.useRef)(null),[d,f]=(0,Q.useState)(``),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(0),[,_]=(0,Q.useState)(0),v=(0,Q.useDeferredValue)(d),y=s?v.trim():``,b=(0,Q.useRef)(null);b.current=p;let x=(0,Q.useRef)([]),S=(0,Q.useRef)({key:null}),C=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{s&&(m(null),requestAnimationFrame(()=>u.current?.select()))},[s]),(0,Q.useEffect)(()=>{if(!s)return;let e=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),c())};return window.addEventListener(`keydown`,e,!0),()=>window.removeEventListener(`keydown`,e,!0)},[s,c]),(0,Q.useEffect)(()=>(s||(lS(`msg-search`,[]),lS(`msg-search-active`,[])),()=>{lS(`msg-search`,[]),lS(`msg-search-active`,[])}),[s]),(0,Q.useLayoutEffect)(()=>{let a=()=>{g(0),m(null),_(0),x.current=[],lS(`msg-search`,[]),lS(`msg-search-active`,[]),S.current={key:null},C.current=``};if(!s||!y){a();return}let c=e.current;if(!c)return;let l=!1,u=0;return u=requestAnimationFrame(()=>{if(l)return;let e=sS(c,y,t,n,r);x.current=e;let a=e.length;if(g(a),a===0){m(null),_(0),lS(`msg-search`,[]),lS(`msg-search-active`,[]),S.current={key:null},C.current=y;return}let s=b.current,u;if(s){if(u=cS(e,s),u===-1){let t=[];for(let n=0;n<e.length;n++)e[n].msgId===s.msgId&&t.push(n);u=t.length>0?t[Math.min(s.k,t.length-1)]:0}}else u=0;u<0&&(u=0),u>=a&&(u=a-1),s&&s.msgId===e[u].msgId&&s.k===e[u].k||m({msgId:e[u].msgId,k:e[u].k}),_(u);let d=e[u],f=S.current,p=f.key?.msgId!==d.msgId||f.key?.k!==d.k||f.kind===`folded`&&d.kind===`dom`||y!==C.current;S.current={key:{msgId:d.msgId,k:d.k},kind:d.kind},C.current=y,lS(`msg-search`,e.filter(e=>e.kind===`dom`).map(e=>e.range)),d.kind===`folded`?(lS(`msg-search-active`,[]),p&&i(d.msgId)):(lS(`msg-search-active`,[d.range]),p&&(o?.(),dS(c,d.range)))}),()=>{l=!0,cancelAnimationFrame(u)}},[s,y,t,e,p,n,r,i,o]);let w=(0,Q.useCallback)(e=>{let t=x.current,n=t.length;if(n===0)return;let r=b.current,i=t[((r?cS(t,r):0)+e+n)%n];m(i.kind===`dom`||i.kind===`folded`?{msgId:i.msgId,k:i.k}:null)},[]);if(!s)return null;let T=p?(()=>{let e=cS(x.current,p);return e===-1?0:e})():0;return(0,$.jsxs)(`div`,{className:`search-bar`,role:`search`,children:[(0,$.jsx)(`input`,{ref:u,className:`search-input`,type:`text`,value:d,placeholder:l(`searchPlaceholder`),onChange:e=>{f(e.target.value)},onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),w(e.shiftKey?-1:1))}}),(0,$.jsx)(`span`,{className:`search-count ${h===0?`empty`:``}`,children:h===0?l(`searchNoResults`):`${Math.min(T+1,h)}/${h}`}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchPrev`),disabled:h===0,onClick:()=>w(-1),children:(0,$.jsx)(a,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchNext`),disabled:h===0,onClick:()=>w(1),children:(0,$.jsx)(D,{})}),(0,$.jsx)(`button`,{type:`button`,className:`search-btn`,title:l(`searchClose`),onClick:c,children:(0,$.jsx)(Ct,{})})]})}function pS(e){let{dSt:t,dSh:n,escaped:r,graceActive:i,stuck:a}=e;return i||t>=-4||t<=-500?{flipEscape:!1,reassert:!1}:n<0?{flipEscape:!1,reassert:a&&!r}:{flipEscape:!0,reassert:!1}}function mS(e){let{decisionFlipEscape:t,hasUserUpwardIntent:n,stuck:r,escaped:i}=e;return t?n?{shouldEscape:!0,shouldReassert:!1}:{shouldEscape:!1,shouldReassert:r&&!i}:{shouldEscape:!1,shouldReassert:!1}}function hS(e){let{wasStreaming:t,isStreaming:n,escaped:r,hasJumpTarget:i}=e;return i?!1:!t&&n?!r:!1}function gS(e){let{convChanged:t,lastQuestionId:n,prevLastQuestionId:r,escaped:i,hasJumpTarget:a}=e;return a?{shouldScroll:!1,reason:`none`}:t?{shouldScroll:!0,reason:`conv_changed`}:n!==null&&r!==null&&n!==r?{shouldScroll:!i,reason:`question_added`}:r===null&&n!==null?{shouldScroll:!i,reason:`initial_load`}:{shouldScroll:!1,reason:`none`}}function _S(e){let{now:t,holdUntil:n,stuck:r,escaped:i}=e;return t<n?!1:r&&!i}function vS(e){let{scrollTop:t,scrollHeight:n,clientHeight:r,hasEarlier:i,isMovingUp:a}=e;return!i||!a?!1:t<=Math.max(r*2,n*.5,800)}function yS(e){let{messages:t,isStreaming:n,liveOutputs:r,toolStatuses:i,queue:a,conversationId:o,sessionFile:s,questions:c,jumpTarget:l,urlJumpMessageId:u,hasEarlier:d,loadEarlier:f,userPromptNonce:p}=e,m=(0,Q.useRef)(null),h=e.scrollRef??m,g=(0,Q.useRef)(null),[_,v]=(0,Q.useState)(!0),y=(0,Q.useRef)(!0),b=e.stickRef??y,x=(0,Q.useRef)(!1),S=e.escapedRef??x,C=(0,Q.useRef)(0),w=(0,Q.useRef)(0),T=(0,Q.useRef)(0),E=(0,Q.useRef)(0),D=(0,Q.useRef)(0),O=(0,Q.useRef)(!1),k=(0,Q.useRef)(!1),A=(0,Q.useRef)(0),j=(0,Q.useRef)([]),M=(0,Q.useCallback)(()=>{for(let e of j.current)clearTimeout(e);j.current=[]},[]),N=(0,Q.useCallback)(()=>{M(),S.current=!0,b.current=!1,v(!1)},[M]),P=(0,Q.useCallback)((e=900)=>{T.current=Math.max(T.current,Date.now()+Math.max(0,e))},[]),F=(0,Q.useCallback)(()=>{M(),D.current=Date.now(),E.current=0,S.current=!0,b.current=!1,v(!1)},[M]),I=(0,Q.useCallback)(()=>{let e=h.current;e&&(S.current||!b.current||Date.now()-D.current<500||(E.current=Date.now()+250,e.scrollTop=e.scrollHeight,C.current=e.scrollTop,w.current=e.scrollHeight))},[h]),L=(0,Q.useCallback)(()=>{h.current&&(M(),D.current=0,b.current=!0,S.current=!1,v(!0),I(),requestAnimationFrame(()=>requestAnimationFrame(I)),j.current.push(setTimeout(I,120)),j.current.push(setTimeout(I,300)),j.current.push(setTimeout(I,600)))},[I,M,h]),R=(0,Q.useRef)(d);R.current=d;let z=(0,Q.useRef)(f);z.current=f;let B=(0,Q.useCallback)(e=>{let t=h.current;t&&vS({scrollTop:t.scrollTop,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,hasEarlier:R.current,isMovingUp:e})&&z.current()},[h]),V=(0,Q.useCallback)(e=>{if(e.deltaY<0){let t=(e.target instanceof Element?e.target:null)?.closest(`.toolcall-output pre, .toolcall-args pre, .codemode-code, .compaction-summary`);if(t&&t.scrollHeight>t.clientHeight&&t.scrollTop>0)return;D.current=Date.now(),F(),B(!0)}else if(e.deltaY>0){D.current=0;let e=h.current;e&&e.scrollHeight-e.scrollTop-e.clientHeight<96&&(S.current=!1,b.current=!0,v(!0))}},[F,B,h]),H=(0,Q.useCallback)(e=>{e.touches.length>0&&(A.current=e.touches[0].clientY)},[]),ee=(0,Q.useCallback)(e=>{if(e.touches.length>0){let t=e.touches[0].clientY-A.current;if(t>8)F(),B(!0);else if(t<-8){D.current=0;let e=h.current;e&&e.scrollHeight-e.scrollTop-e.clientHeight<96&&(S.current=!1,b.current=!0,v(!0))}}},[F,B,h]),U=(0,Q.useCallback)(e=>{if(e.target instanceof Element&&e.target.closest(`[data-disclosure]`)&&P(),e.button===1){D.current=Date.now(),F();return}if(e.button!==0)return;let t=e.currentTarget;e.target===t&&e.clientX>=t.getBoundingClientRect().left+t.clientWidth&&(O.current=!0)},[F,P]);(0,Q.useEffect)(()=>{let e=e=>{O.current=!1,e&&e.button!==1||(k.current=!1)},t=e=>{e.button===1&&(k.current=!0,D.current=Date.now(),F())},n=e=>{let t=e.target;(!t||t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&!t.isContentEditable)&&((e.key===`Enter`||e.key===` `)&&t?.closest?.(`[data-disclosure]`)?P():e.key===`PageUp`||e.key===`ArrowUp`||e.key===`Home`?F():e.key===`End`&&(D.current=0))};return window.addEventListener(`pointerup`,e),window.addEventListener(`pointercancel`,e),window.addEventListener(`pointerdown`,t,{capture:!0}),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`pointerup`,e),window.removeEventListener(`pointercancel`,e),window.removeEventListener(`pointerdown`,t,{capture:!0}),window.removeEventListener(`keydown`,n)}},[F,P]);let W=(0,Q.useCallback)(()=>{let e=h.current;if(!e)return;let t=e.scrollTop-C.current,n=e.scrollHeight-w.current;C.current=e.scrollTop,w.current=e.scrollHeight;let r=e.scrollHeight-e.scrollTop-e.clientHeight<36,i=Date.now()<E.current;k.current&&t<0&&(D.current=Date.now(),F());let a=Date.now()-D.current<800||O.current&&t<0||k.current,o=pS({dSt:t,dSh:n,escaped:S.current,graceActive:i,stuck:b.current});o.reassert&&!a&&I();let{shouldEscape:s,shouldReassert:c}=mS({decisionFlipEscape:o.flipEscape,hasUserUpwardIntent:a,stuck:b.current,escaped:S.current});s?(S.current=!0,b.current=!1):c&&I(),i||a||t<0||r&&(t>0||!S.current)&&(b.current=!0,S.current=!1);let l=t<0||Date.now()-D.current<800;B(l),v(e=>e===b.current?e:b.current)},[I,F,B,h]),G=(0,Q.useRef)(!!n);(0,Q.useEffect)(()=>{let e=G.current;if(G.current=!!n,hS({wasStreaming:e,isStreaming:!!n,escaped:S.current,hasJumpTarget:!!(l||u)}))L();else if(e&&!n&&!S.current){let e=()=>{h.current&&!S.current&&(b.current=!0,v(!0),I())};requestAnimationFrame(()=>requestAnimationFrame(e))}},[n,l,u,L,I,h]);let K=c.length>0?c[c.length-1].id:null,q=(0,Q.useRef)(`${o??``}:${s??``}`),te=(0,Q.useRef)(K);(0,Q.useEffect)(()=>{let e=`${o??``}:${s??``}`,t=e!==q.current,n=h.current,r=!n||n.scrollHeight-n.scrollTop-n.clientHeight<36,i=!!(K&&Ma(K)),{shouldScroll:a}=gS({convChanged:t,lastQuestionId:K,prevLastQuestionId:te.current,escaped:S.current,nearBottom:r,hasJumpTarget:!!(l||u)});q.current=e,te.current=K,(a||i)&&L()},[o,s,K,l,u,L]);let ne=(0,Q.useRef)(p??0);(0,Q.useEffect)(()=>{let e=p??0;e>ne.current&&(ne.current=e,L())},[p,L]),(0,Q.useLayoutEffect)(()=>{h.current&&b.current&&!S.current&&I()},[t,n,r,i,I,h]);let re=a?a.steering.join(`\0`)+``+a.followUp.join(`\0`):``,J=a?a.steering.length+a.followUp.length:0,ie=(0,Q.useRef)(J);return(0,Q.useLayoutEffect)(()=>{let e=J>ie.current;ie.current=J,e?L():h.current&&b.current&&!S.current&&I()},[re,J,L,I,h]),(0,Q.useEffect)(()=>{let e=h.current;if(!e||typeof ResizeObserver>`u`)return;let t=e.clientHeight,n=new ResizeObserver(()=>{let n=e.clientHeight,r=n-t;t=n,r>0&&(e.scrollTop=Math.min(e.scrollTop,e.scrollHeight-e.clientHeight))});return n.observe(e),()=>n.disconnect()},[h]),(0,Q.useEffect)(()=>{let e=h.current;if(!e||typeof MutationObserver>`u`)return;let t=!1,n=new MutationObserver(()=>{t||(t=!0,requestAnimationFrame(()=>{t=!1,h.current&&_S({now:Date.now(),holdUntil:T.current,stuck:b.current,escaped:S.current})&&(I(),v(!0))}))});return n.observe(e,{childList:!0,subtree:!0}),()=>n.disconnect()},[I,h]),(0,Q.useEffect)(()=>{let e=g.current,t=h.current;if(!e||!t)return;let n=n=>{n.preventDefault();let r=e.querySelector(`.qn-list`);r&&r.contains(n.target)&&r.scrollHeight>r.clientHeight?r.scrollTop+=n.deltaY:(n.deltaY<0?F():n.deltaY>0&&(D.current=0,t.scrollHeight-t.scrollTop-t.clientHeight<96&&(S.current=!1,b.current=!0,v(!0))),t.scrollTop+=n.deltaY)};return e.addEventListener(`wheel`,n,{passive:!1}),()=>e.removeEventListener(`wheel`,n)},[F,h]),(0,Q.useEffect)(()=>()=>M(),[M]),{scrollRef:h,railRef:g,stickBottom:_,escapedRef:S,stickRef:b,scrollToBottom:L,pinToBottom:I,disengageStick:F,pauseForSelection:N,suppressAutoPin:P,handleWheel:V,handleTouchStart:H,handleTouchMove:ee,handlePointerDown:U,onScroll:W}}var bS=`#ffffff`,xS=`#1e1e1e`,SS=`.msg-actions, .msg-text-copy, .chead-copy, .stream-cursor, .msg-editor, .msg-collapse-btn, .msg-export-check, .toolcall-kill, .toolcall-open`,CS=16384;function wS(e,t=800,n=2){let r=Math.max(e,t,1);return r*n<=CS?n:+(r<=CS)}function TS(e){let t=e.trim().toLowerCase();if(!t)return null;if(t===`transparent`)return{r:0,g:0,b:0,a:0};if(t.startsWith(`#`)){let e=t.slice(1);if(e.length===3||e.length===4){let t=Number.parseInt(e[0]+e[0],16),n=Number.parseInt(e[1]+e[1],16),r=Number.parseInt(e[2]+e[2],16),i=e.length===4?Number.parseInt(e[3]+e[3],16)/255:1;return[t,n,r,i].some(e=>Number.isNaN(e))?null:{r:t,g:n,b:r,a:i}}if(e.length===6||e.length===8){let t=Number.parseInt(e.slice(0,2),16),n=Number.parseInt(e.slice(2,4),16),r=Number.parseInt(e.slice(4,6),16),i=e.length===8?Number.parseInt(e.slice(6,8),16)/255:1;return[t,n,r,i].some(e=>Number.isNaN(e))?null:{r:t,g:n,b:r,a:i}}return null}let n=t.match(/^rgba?\(\s*([\s\S]+)\)$/);if(!n)return null;let r=n[1].trim(),i,a=1;if(r.includes(`/`)){let[e,t]=r.split(`/`);i=e.trim().split(/[\s,]+/).filter(Boolean),a=DS(t.trim())}else if(r.includes(`,`)){let e=r.split(`,`).map(e=>e.trim());e.length===4&&(a=DS(e.pop())),i=e}else i=r.split(/\s+/).filter(Boolean),i.length===4&&(a=DS(i.pop()));if(i.length!==3)return null;let o=ES(i[0]),s=ES(i[1]),c=ES(i[2]);return[o,s,c,a].some(e=>Number.isNaN(e))?null:{r:o,g:s,b:c,a}}function ES(e){return e.endsWith(`%`)?Math.round(OS(Number.parseFloat(e),0,100)*2.55):Math.round(OS(Number.parseFloat(e),0,255))}function DS(e){return e.endsWith(`%`)?OS(Number.parseFloat(e)/100,0,1):OS(Number.parseFloat(e),0,1)}function OS(e,t,n){return Math.min(n,Math.max(t,e))}function kS(e){let t=OS(Math.round(e.r),0,255),n=OS(Math.round(e.g),0,255),r=OS(Math.round(e.b),0,255);return e.a<.996?`rgba(${t}, ${n}, ${r}, ${Math.round(OS(e.a,0,1)*1e3)/1e3})`:`rgb(${t}, ${n}, ${r})`}function AS(e,t){let n=OS(e.a,0,1);return n<=0?{r:t.r,g:t.g,b:t.b,a:t.a}:n>=1?{r:e.r,g:e.g,b:e.b,a:1}:{r:e.r*n+t.r*(1-n),g:e.g*n+t.g*(1-n),b:e.b*n+t.b*(1-n),a:1}}function jS(e,t){let n=TS(t)??{r:255,g:255,b:255,a:1},r=TS(e);return!r||r.a<=.004?kS({...n,a:1}):kS(AS(r,{...n,a:1}))}function MS(e){let t=e=>{let t=e/255;return t<=.03928?t/12.92:((t+.055)/1.055)**2.4};return .2126*t(e.r)+.7152*t(e.g)+.0722*t(e.b)}function NS(e){return MS(e)>.45}function PS(e){let t=document.createElement(`div`);t.style.cssText=`position:fixed;left:-99999px;top:0;width:8px;height:8px;pointer-events:none;background:${e}`,document.body.appendChild(t);let n=getComputedStyle(t).backgroundColor;return t.remove(),n}function FS(){return getComputedStyle(document.documentElement).colorScheme.split(/\s+/).includes(`light`)?bS:xS}function IS(e){let t=FS(),n=t;try{n=jS(PS(`var(--bg)`),t)}catch{n=t}try{let e=jS(PS(`var(--card-bg, var(--msgs-bg, var(--bg)))`),n),t=TS(e);if(t&&MS(t)+t.a>0)return e}catch{}let r=e??null;for(;r;){let e=getComputedStyle(r).backgroundColor;if(e&&e!==`transparent`&&e!==`rgba(0, 0, 0, 0)`){let t=jS(e,n),r=TS(e);if(r&&r.a>.04)return t}r=r.parentElement}return n}function LS(e){return e instanceof HTMLElement||e instanceof SVGElement?e.style:null}function RS(e,t){let n=TS(e);return n?n.a<=.004?`transparent`:n.a>=.996?kS({...n,a:1}):kS(AS(n,{...TS(t)??{r:255,g:255,b:255,a:1},a:1})):null}function zS(e,t,n){let r=getComputedStyle(e),i=LS(t),a=n;if(i){let e=RS(r.backgroundColor,n);e===`transparent`?i.backgroundColor=`transparent`:e&&(i.backgroundColor=e,a=e);let t=RS(r.color,a);t&&t!==`transparent`&&(i.color=t);for(let[e]of[[`borderTopColor`,`border-top-color`],[`borderRightColor`,`border-right-color`],[`borderBottomColor`,`border-bottom-color`],[`borderLeftColor`,`border-left-color`],[`outlineColor`,`outline-color`],[`textDecorationColor`,`text-decoration-color`]]){let t=RS(r[e],a);t&&t!==`transparent`&&(i[e]=t)}let o=RS(r.fill,a);o&&o!==`transparent`&&r.fill!==`none`&&(i.fill=o);let s=RS(r.stroke,a);s&&s!==`transparent`&&r.stroke!==`none`&&(i.stroke=s),i.backdropFilter=`none`,i.setProperty(`-webkit-backdrop-filter`,`none`),r.mixBlendMode&&r.mixBlendMode!==`normal`&&(i.mixBlendMode=`normal`),i.caretColor=`transparent`}let o=Array.from(e.children),s=Array.from(t.children),c=Math.min(o.length,s.length);for(let e=0;e<c;e++)zS(o[e],s[e],a)}function BS(e){e.querySelectorAll(SS).forEach(e=>e.remove())}function VS(e,t={}){t.includeThinking||e.querySelectorAll(`.thinking`).forEach(e=>e.remove()),t.includeTools||e.querySelectorAll(`.toolcall`).forEach(e=>e.remove())}function HS(e,t,n={}){let r=e.cloneNode(!0);return zS(e,r,t),VS(r,n),BS(r),r.classList.remove(`msg-export-selected`),r.style.margin=`0`,r.style.paddingLeft=``,r.removeAttribute(`id`),r.querySelectorAll(`[id]`).forEach(e=>e.removeAttribute(`id`)),r}async function US(e,t={}){let{toBlob:n}=await Rs(async()=>{let{toBlob:e}=await import(`./es-C5BHljgM.js`);return{toBlob:e}},[],import.meta.url),r=t.backgroundColor??IS(e),i=TS(r),a=await n(e,{pixelRatio:t.pixelRatio??2,backgroundColor:r,cacheBust:!1,style:{colorScheme:i&&!NS(i)?`dark`:`light`}});if(!a)throw Error(`toBlob returned null`);return a}function WS(e){return typeof CSS<`u`&&typeof CSS.escape==`function`?CSS.escape(e):e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}function GS(e){return document.querySelector(`.msg[data-msg-id="${WS(e)}"]`)??document.querySelector(`[data-msg-id="${WS(e)}"]`)}function KS(){let e=X(),t=Dl(),[n,r]=(0,Q.useState)(``),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)(!1),[c,l]=(0,Q.useState)(`pi-web-ui`),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!1),[m,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(``),y=(0,Q.useRef)(null),b=(0,Q.useRef)(null),x=(0,Q.useRef)(`#ffffff`);if((0,Q.useEffect)(()=>{t.open&&(d(!1),g(!1),v(``))},[t.open]),Lt(()=>{Ol()},t.open),(0,Q.useLayoutEffect)(()=>{if(!t.open)return;let e=!1,n=0;p(!0);let r=()=>{if(e||!b.current)return;let i=[],a=!1;for(let e of t.selectedIds){let t=GS(e);t?i.push(t):a=!0}let o=t.includeThinking&&i.some(e=>e.querySelector(`.thinking`)&&!e.querySelector(`.thinking-body`))||t.includeTools&&i.some(e=>e.querySelector(`.toolcall`)&&!e.querySelector(`.toolcall-body`));if((a||o)&&n<12){n+=1,requestAnimationFrame(r);return}let s=i[0],c=IS(s??void 0);x.current=c;let l=document.createDocumentFragment();for(let e of i)l.appendChild(HS(e,c,{includeThinking:t.includeThinking,includeTools:t.includeTools}));b.current.replaceChildren(l);let u=y.current;if(u){u.style.backgroundColor=c;let e=TS(c);if(u.style.colorScheme=e&&!NS(e)?`dark`:`light`,s){let e=getComputedStyle(s).color;e&&(u.style.color=e)}}p(!1)},i=requestAnimationFrame(()=>requestAnimationFrame(r));return()=>{e=!0,cancelAnimationFrame(i),b.current?.replaceChildren()}},[t.open,t.selectedIds,t.includeThinking,t.includeTools]),!t.open)return null;let S=async()=>{let n=y.current;if(n&&!u&&t.selectedIds.length!==0){d(!0),v(``);try{let t=wS(n.scrollHeight,n.scrollWidth);if(t===0){v(e(`exportTooLong`));return}let r=await US(n,{backgroundColor:x.current,pixelRatio:t});await navigator.clipboard.write([new ClipboardItem({"image/png":r})]),g(!0),window.setTimeout(()=>g(!1),1500)}catch(t){let n=t instanceof Error?t.message:String(t);v(`${e(`copyFailed`)}: ${n}`)}finally{d(!1)}}};return(0,$.jsxs)(`aside`,{className:`saveimg-dock`,role:`dialog`,"aria-label":e(`saveAsImage`),children:[(0,$.jsxs)(`div`,{className:`saveimg-head`,children:[(0,$.jsx)(`span`,{className:`saveimg-title`,children:e(`saveAsImage`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:e(`close`),"aria-label":e(`close`),onClick:()=>Ol(),children:(0,$.jsx)(Ct,{})})]}),(0,$.jsx)(`p`,{className:`saveimg-hint`,children:e(`exportSelectHint`)}),(0,$.jsxs)(`div`,{className:`saveimg-body`,children:[(0,$.jsx)(`div`,{className:`saveimg-preview`,children:(0,$.jsxs)(`div`,{ref:y,className:`saveimg-card${i?` saveimg-card--border`:``}`,children:[n.trim()?(0,$.jsx)(`div`,{className:`saveimg-card-title`,children:n.trim()}):null,(0,$.jsx)(`div`,{ref:b,className:`saveimg-card-md`}),o&&c.trim()?(0,$.jsx)(`div`,{className:`saveimg-card-wm`,children:c.trim()}):null]})}),(0,$.jsxs)(`div`,{className:`saveimg-options`,children:[(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t.includeTools,onChange:e=>Al({includeTools:e.target.checked})}),(0,$.jsx)(`span`,{children:e(`exportIncludeTools`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:t.includeThinking,onChange:e=>Al({includeThinking:e.target.checked})}),(0,$.jsx)(`span`,{children:e(`exportIncludeThinking`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt`,children:[(0,$.jsx)(`span`,{children:e(`imageTitle`)}),(0,$.jsx)(`input`,{type:`text`,className:`dialog-input saveimg-input`,value:n,onChange:e=>r(e.target.value),placeholder:e(`imageTitlePlaceholder`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:i,onChange:e=>a(e.target.checked)}),(0,$.jsx)(`span`,{children:e(`imageBorder`)})]}),(0,$.jsxs)(`label`,{className:`saveimg-opt saveimg-opt--toggle`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:o,onChange:e=>s(e.target.checked)}),(0,$.jsx)(`span`,{children:e(`imageWatermark`)})]}),(0,$.jsx)(`input`,{type:`text`,className:`dialog-input saveimg-input`,value:c,disabled:!o,onChange:e=>l(e.target.value),placeholder:e(`imageWatermarkPlaceholder`)}),(0,$.jsxs)(`div`,{className:`saveimg-copy-row`,children:[(0,$.jsx)(`span`,{className:`saveimg-count`,children:e(`exportSelectedCount`,{n:t.selectedIds.length})}),(0,$.jsxs)(`button`,{type:`button`,className:`btn primary saveimg-copy`,onClick:()=>void S(),disabled:u||f||t.selectedIds.length===0,title:e(`copyImageBtn`),children:[u||f?(0,$.jsx)(Am,{className:`saveimg-spin`}):m?(0,$.jsx)(h,{}):(0,$.jsx)(st,{}),(0,$.jsx)(`span`,{children:e(u||f?`savingImage`:m?`copied`:`copyImageBtn`)})]})]})]}),_?(0,$.jsx)(`div`,{className:`saveimg-error`,children:_}):null]})]})}var qS=`.msg-text, .attachcard-content, .toolcall-output pre, .bashblock-output, .quote-content`,JS=`button, input, textarea, [contenteditable], .msg-meta, .msg-actions, .chead, .toolcall-output-label`;function YS(e){return e.nodeType===1?e:e.parentElement}function XS(e,t,n){if(!t||t.isCollapsed||t.rangeCount!==1)return null;let r=t.getRangeAt(0),i=YS(r.startContainer),a=YS(r.endContainer);if(!i||!a||!e.contains(i)||!e.contains(a)||!i.closest(qS)||!a.closest(qS)||i.closest(JS)||a.closest(JS))return null;let o=i.closest(`.msg[data-msg-id]`);if(!o||o!==a.closest(`.msg[data-msg-id]`))return null;for(let e of o.querySelectorAll(JS))if(r.intersectsNode(e))return null;let s=t.toString(),c=o.dataset.msgId,l=o.dataset.role;return!s.trim()||!c||!l?null:{text:s,messageId:c,role:l,...n?{sessionId:n}:{}}}function ZS({rootRef:e,sessionId:t,enabled:n=!0,translateEnabled:r=!0,onSelect:i}){let a=X(),[o,s]=(0,Q.useState)(null);return(0,Q.useEffect)(()=>{s(null);let a=e.current;if(!a||!n)return;let o=!1,c=0,l=()=>{cancelAnimationFrame(c),s(null)},u=()=>{cancelAnimationFrame(c),c=requestAnimationFrame(()=>{let e=window.getSelection(),n=XS(a,e,t);if(!n||!e){s(null);return}let o=e.getRangeAt(0).getBoundingClientRect();!o.width&&!o.height?s(null):(i?.(),s({quote:n,left:Math.max(8,Math.min(o.right-(r?240:176),window.innerWidth-(r?248:184))),top:Math.max(8,Math.min(o.top>=44?o.top-40:o.bottom+8,window.innerHeight-42))}))})},d=e=>{e.target?.closest?.(`.quote-selection-toolbar, .quick-ask-popover`)||(o=e.button===0&&a.contains(e.target),l())},f=e=>{o=!1,e.button===0&&u()},p=()=>{o||u()},m=e=>{e.key===`Escape`&&l()};return document.addEventListener(`mousedown`,d),document.addEventListener(`mouseup`,f),document.addEventListener(`selectionchange`,p),document.addEventListener(`keydown`,m),window.addEventListener(`scroll`,l,!0),window.addEventListener(`resize`,l),window.addEventListener(`blur`,l),()=>{cancelAnimationFrame(c),document.removeEventListener(`mousedown`,d),document.removeEventListener(`mouseup`,f),document.removeEventListener(`selectionchange`,p),document.removeEventListener(`keydown`,m),window.removeEventListener(`scroll`,l,!0),window.removeEventListener(`resize`,l),window.removeEventListener(`blur`,l)}},[e,t,n,r,i]),!n||!o||o.quote.sessionId!==t?null:(0,Er.createPortal)((0,$.jsxs)(`div`,{className:`quote-selection-toolbar`,role:`group`,style:{left:o.left,top:o.top},onMouseDown:e=>e.preventDefault(),children:[(0,$.jsxs)(`button`,{type:`button`,className:`quote-selection-button`,onClick:()=>{ir({attachments:[{path:``,name:a(`quoteText`),mode:`quote`,quote:o.quote,key:or()}]})&&(s(null),window.getSelection()?.removeAllRanges(),er())},children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`↪`}),` `,a(`quoteSelection`)]}),(0,$.jsx)(`button`,{type:`button`,className:`quote-selection-button selection-explain-trigger`,onClick:e=>{let t=e.currentTarget.parentElement.getBoundingClientRect();t2({selection:o.quote.text,action:`explain`,anchor:{left:t.left,right:t.right,top:t.top,bottom:t.bottom}}),s(null),window.getSelection()?.removeAllRanges()},children:a(`explainSelection`)}),r&&(0,$.jsx)(`button`,{type:`button`,className:`quote-selection-button selection-translate-trigger`,onClick:e=>{let t=e.currentTarget.parentElement.getBoundingClientRect();t2({selection:o.quote.text,action:`translate`,anchor:{left:t.left,right:t.right,top:t.top,bottom:t.bottom}}),s(null),window.getSelection()?.removeAllRanges()},children:a(`quickAskTranslate`)})]}),document.body)}function QS({kind:e,text:t,parsed:n,index:r,id:i,onRemoveQueued:a,onRecallQueued:o}){let s=X();return(0,$.jsxs)(`div`,{className:`msg msg-user msg-queued`,"data-role":`user`,children:[(0,$.jsxs)(`div`,{className:`msg-meta`,children:[(0,$.jsx)(`span`,{className:`msg-role`,children:s(`role.user`)}),(0,$.jsx)(`span`,{className:`queued-tag ${e===`steer`?`steer`:`follow`}`,children:s(e===`steer`?`queueSteerTag`:`queueFollowTag`)}),(0,$.jsxs)(`div`,{className:`msg-queued-actions`,children:[o&&(0,$.jsx)(`button`,{type:`button`,className:`msg-queued-recall`,title:s(`queueRecallTip`),"aria-label":s(`queueRecallTip`),onClick:()=>o(e,t,r,i),children:`↩`}),a&&(0,$.jsx)(`button`,{type:`button`,className:`msg-queued-remove`,title:s(`queueRemoveTip`),"aria-label":s(`queueRemoveTip`),onClick:()=>a(e,t,r,i),children:`✕`})]})]}),(0,$.jsx)(`div`,{className:`msg-body`,children:(0,$.jsxs)(`div`,{className:`msg-text`,children:[n.quotes.map((e,t)=>(0,$.jsx)(Ds,{quote:e},`quote-${t}`)),n.attachments&&n.attachments.length>0&&(0,$.jsx)(`div`,{className:`queued-attachments`,children:n.attachments.map((e,t)=>{let n=!!(e.path&&e.type!==`page`&&e.type!==`conversation`&&e.type!==`canvas`),r=!!(e.url||n),i=()=>{e.url?Tn({src:e.url.startsWith(`/`)?He(e.url):e.url,alt:e.name}):n&&e.path&&Jt({path:e.path,name:e.name})};return(0,$.jsxs)(`span`,{className:`queued-att-chip${r?` previewable`:``}`,title:r?`${e.name} (${e.url?s(`toolImageZoom`):s(`fileOpenPreview`)})`:e.name,onClick:r?i:void 0,role:r?`button`:void 0,tabIndex:r?0:void 0,onKeyDown:r?e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),i())}:void 0,children:[(0,$.jsx)(`span`,{className:`queued-att-icon`,children:e.type===`image`||e.type===`vision-bridge`?`🖼️`:e.type===`folder`?`📁`:e.type===`page`?`🌐`:e.type===`conversation`?`💬`:`📎`}),(0,$.jsx)(`span`,{className:`queued-att-name`,children:e.name})]},`att-${t}`)})}),n.text?(0,$.jsx)(nl,{text:n.text,hardBreaks:!0}):null]})})]})}function $S({compaction:e}){let t=X(),[,n]=(0,Q.useState)(0);(0,Q.useEffect)(()=>{let e=setInterval(()=>n(e=>e+1),1e3);return()=>clearInterval(e)},[]);let r=Math.max(0,Math.floor((Date.now()-e.startedAt)/1e3)),i=e.reason===`manual`?t(`compactingReasonManual`):e.reason===`overflow`?t(`compactingReasonOverflow`):t(`compactingReasonThreshold`);return(0,$.jsxs)(`div`,{className:`compact-notice`,role:`status`,children:[(0,$.jsx)(`span`,{className:`compact-pulse`}),(0,$.jsxs)(`span`,{className:`compact-text`,children:[t(`compactingContext`),` · `,r,`s`]}),(0,$.jsx)(`span`,{className:`compact-reason`,children:i})]})}function eC(e,t,n,r,i){if(e.convKey!==t&&(e.convKey=t,e.pending=null,e.finalizedMap.clear()),e.pending&&r?.id!==e.pending.streamKey){let{index:t,streamKey:r}=e.pending;for(let a=Math.max(0,t);a<n.length;a++){let t=n[a];if(t.role===`assistant`&&!e.finalizedMap.has(t.id)){e.finalizedMap.set(t.id,r),i?.(r,t.id);break}}e.pending=null}return r&&e.pending?.streamKey!==r.id&&(e.pending={index:n.length,streamKey:r.id}),e.finalizedMap}function tC(e){return Array.isArray(e.content)?e.content.some(e=>{let t=Gl(e);return t&&t.text.trim().length>0}):!1}function nC(e){return e.role&&e.role!==`assistant`||e.customType||!Array.isArray(e.content)||e.content.length===0||tC(e)?!1:e.content.some(e=>e.type===`toolCall`||e.type===`thinking`)}function rC(e){return e.customType?!1:e.role===`assistant`||!e.role}function iC(e,t){let n=!!t?.mergeTurns,r=[],i=null;for(let t=0;t<e.length;t++){let a=e[t];if(a.role===`system`||a.role===`toolResult`)continue;let o=N9(a),s=rC(a),c=nC(a),l=!c&&!!i&&s&&!o&&t===e.length-1&&!tC(a);!o&&(n?s:c||l)?i?i.messages.push(a):(i={type:`tool_cluster`,id:`cluster-${a.id}`,messages:[a]},r.push(i)):(i=null,r.push({type:`single`,message:a}))}return r}function aC(e,t=!1){return t?Math.max(48,Math.ceil(e.length/4)*30):Math.max(48,e.length*52)}var oC=new Set,sC=new Map,cC=1200,lC=2400,uC=1600;function dC({scrollRef:e,convKey:t,previewHandoff:n,messages:r,stateMessages:i,clusteredItems:a,clusterOptions:o,keepRecentCount:s,reversePagination:c,searchOpen:l,quietActive:u,expanded:d}){let[f,p]=(0,Q.useState)(()=>{if(c||i.length<=30)return new Set;let e=Z9(i,new Map,Math.max(uC,s*120)),t=new Set;for(let n of i)e.has(n.id)||t.add(n.id);for(let n of iC(i,o))n.type===`tool_cluster`&&n.messages.every(t=>!e.has(t.id))&&t.add(n.id);return t}),m=(0,Q.useRef)(new Map),h=(0,Q.useRef)(new Map),g=(0,Q.useRef)(new Map),_=!c&&i.length>30&&!l&&!u,v=(0,Q.useRef)(_);v.current=_;let y=(0,Q.useMemo)(()=>_?Z9(r,m.current,Math.max(uC,s*120)):oC,[_,r,s]),b=(0,Q.useMemo)(()=>{let e=new Set(y);for(let t of a)t.type===`tool_cluster`&&t.messages.some(e=>y.has(e.id))&&e.add(t.id);return e},[y,a]),x=(0,Q.useRef)(b);x.current=b;let S=(0,Q.useMemo)(()=>{if(!_)return sC;let e=new Map;for(let t of i)e.set(t.id,eS(t));for(let t of a)if(t.type===`tool_cluster`){let n=0;for(let r of t.messages)n+=e.get(r.id)??0;e.set(t.id,n)}return e},[_,i,a]),C=(0,Q.useRef)(S);C.current=S;let w=(0,Q.useRef)(f),T=f,E=(0,Q.useRef)(t);if(E.current!==t||n){E.current=t;let e=new Set(i.map(e=>e.id));for(let t of iC(i,o))t.type===`tool_cluster`&&e.add(t.id);for(let t of g.current.keys())e.has(t)||g.current.delete(t);if(!c&&i.length>30){let e=Z9(i,m.current,Math.max(uC,s*120)),t=n?new Set(g.current.keys()):null,r=new Set;for(let n of i)!e.has(n.id)&&!t?.has(n.id)&&r.add(n.id);for(let n of iC(i,o))n.type===`tool_cluster`&&!t?.has(n.id)&&n.messages.every(n=>!e.has(n.id)&&!t?.has(n.id))&&r.add(n.id);T=r,p(r),w.current=r}else if(f.size>0){let e=new Set;T=e,p(e),w.current=e}}w.current=T;let D=(0,Q.useCallback)((e,t,n)=>{n!==void 0&&(h.current.set(e,{h:t,len:n}),m.current.set(e,t))},[]),O=(0,Q.useCallback)((e,t)=>{D(e,t,C.current.get(e))},[D]),k=(0,Q.useRef)(null),A=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!_){p(e=>e.size?new Set:e);return}let t=e.current;if(!t||typeof IntersectionObserver>`u`)return;let n=new IntersectionObserver(e=>{if(!v.current)return;let t=[];for(let n of e){if(!n.isIntersecting)continue;let e=n.target.dataset.lazyId;e&&w.current.has(e)&&t.push(e)}t.length>0&&p(e=>X9(e,t,[]))},{root:t,rootMargin:`${cC}px 0px ${cC}px 0px`,threshold:0}),r=new IntersectionObserver(e=>{if(!v.current)return;let t=[];for(let n of e){if(n.isIntersecting)continue;let e=n.target.dataset.lazyId;e&&!x.current.has(e)&&!w.current.has(e)&&t.push(e)}t.length>0&&p(e=>X9(e,[],t))},{root:t,rootMargin:`${lC}px 0px ${lC}px 0px`,threshold:0});k.current=n,A.current=r;for(let e of g.current.values())n.observe(e),r.observe(e);return()=>{n.disconnect(),r.disconnect(),k.current=null,A.current=null}},[_,e,t]);let j=(0,Q.useCallback)(e=>{if(!e)return;let t=e.dataset.lazyId??``;if(!t)return;let n=g.current.get(t);n!==e&&(n&&(k.current?.unobserve(n),A.current?.unobserve(n)),g.current.set(t,e),k.current?.observe(e),A.current?.observe(e))},[]);return(0,Q.useEffect)(()=>{let e=new Set(i.map(e=>e.id));for(let t of a)t.type===`tool_cluster`&&e.add(t.id);for(let[t,n]of g.current)e.has(t)||(k.current?.unobserve(n),A.current?.unobserve(n),g.current.delete(t),m.current.delete(t),h.current.delete(t));p(t=>{let n=!1,r=new Set;for(let i of t)e.has(i)?r.add(i):n=!0;return n?r:t})},[i,a,d]),{virtualOn:_,effectiveHidden:T,alwaysSet:b,fingerprints:S,heightsRef:m,heightMetaRef:h,elsRef:g,attachEl:j,storeHeight:O}}function fC({state:e,messages:t,preview:n,readOnly:r,reversePagination:i,flowStream:a,keepRecentCount:o,exportOpen:s,searchOpen:c,scrollRef:l}){let u=Math.max(a?240:60,o*2),d=a?120:30,f=Math.min(u,10),[p,m]=(0,Q.useState)(()=>f),h=`${e.conversationId??``}:${e.sessionFile??``}`,[g,_]=(0,Q.useState)(n),v=g&&!n;g!==n&&_(n);let y=(0,Q.useRef)(h),b=(0,Q.useRef)(t.length),x=(0,Q.useRef)(t[0]?.id),S=(0,Q.useRef)(null),C=(0,Q.useRef)(null),w=(0,Q.useRef)(!1),[T,E]=(0,Q.useState)(!1),D=(0,Q.useRef)(!1),O=(0,Q.useCallback)(e=>{D.current=e,E(e)},[]),k=(0,Q.useRef)(0),A=(0,Q.useRef)(null),j=(0,Q.useCallback)(()=>{let e=l.current;if(!e)return null;let t=e.getBoundingClientRect().top,n=e.querySelectorAll(`[data-lazy-id]`);for(let e=0;e<n.length;e++){let r=n[e],i=r.getBoundingClientRect();if(i.bottom>t+2)return{id:r.dataset.lazyId??null,top:i.top-t}}return null},[l]),M=(0,Q.useCallback)(()=>{k.current&&=(cancelAnimationFrame(k.current),0),A.current=null},[]),N=(0,Q.useCallback)(()=>{let e=l.current,n=j();C.current={sh:e?e.scrollHeight:0,st:e?e.scrollTop:0,id:n?.id??null,top:n?.top??0,msgLen:t.length,firstId:t[0]?.id}},[j,t,l]),P=(0,Q.useCallback)(e=>{let t=l.current;if(t){if(e.id){let n=null;try{n=t.querySelector(`[data-lazy-id="`+CSS.escape(e.id)+`"]`)}catch{n=null}if(n){let r=n.getBoundingClientRect().top-t.getBoundingClientRect().top-e.top;r!==0&&(t.scrollTop+=r);return}}t.scrollTop=e.st+(t.scrollHeight-e.sh)}},[l]),F=(0,Q.useCallback)(()=>{let e=C.current,t=l.current;if(!t||!e)return;M(),O(!0),P(e);let n=j();A.current={id:n?.id??null,top:n?.top??0,sh:t.scrollHeight,st:t.scrollTop};let r=0,i=0,a=()=>{k.current=0;let e=l.current,t=A.current;if(!e||!t)O(!1);else{if(Math.abs(e.scrollTop-t.st)>2){let t=j();A.current={id:t?.id??null,top:t?.top??0,sh:e.scrollHeight,st:e.scrollTop},i=0}else{let n=0,r=!1;if(t.id){let i=null;try{i=e.querySelector(`[data-lazy-id="`+CSS.escape(t.id)+`"]`)}catch{i=null}i&&(r=!0,n=i.getBoundingClientRect().top-e.getBoundingClientRect().top-t.top)}if(r)n!==0&&(e.scrollTop+=n),A.current={...t,sh:e.scrollHeight,st:e.scrollTop};else{n=e.scrollHeight-t.sh;let r=j();n!==0&&(e.scrollTop+=n),A.current={id:r?.id??null,top:r?.top??0,sh:e.scrollHeight,st:e.scrollTop}}i=n===0?i+1:0}r++,i>=3&&r>=4||r>=30?(A.current=null,O(!1)):k.current=requestAnimationFrame(a)}};k.current=requestAnimationFrame(a)},[M,j,P,l,O]);(y.current!==h||v)&&(y.current=h,S.current=null,m(v?Math.max(f,Math.min(p,b.current)):f),b.current=t.length,x.current=t[0]?.id,C.current=null,M(),D.current&&O(!1),w.current=!1),(0,Q.useLayoutEffect)(()=>{let e=t.length-b.current;b.current=t.length;let n=t[0]?.id,r=n!==x.current;x.current=n,e<=0||(m(t=>t+e),r&&(w.current=!1))},[t.length,t]),(0,Q.useLayoutEffect)(()=>{let e=C.current;if(!e)return;let n=t[0]?.id!==e.firstId,r=t.length===e.msgLen&&!n;(n||r)&&(w.current&&r?(F(),N()):(C.current=null,F()))},[p,t,N,F]);let I=!!i&&!s&&!c;(0,Q.useEffect)(()=>{if(!I||p>=u)return;let e=0,t=requestAnimationFrame(()=>{e=requestAnimationFrame(()=>{(0,Q.startTransition)(()=>m(e=>e<u?u:e))})});return()=>{cancelAnimationFrame(t),cancelAnimationFrame(e)}},[I,p,u,h]);let L=I?Math.min(t.length,p):t.length;(0,Q.useEffect)(()=>{w.current=!1},[e.historyStart,e.historyTotal]);let R=Math.max(0,e.historyStart??0),z=(0,Q.useRef)(R);z.current=R;let B=s1({isPagingActive:I,totalMessages:t.length,visibleCount:p,historyStart:R}),V=!n&&!s&&!c&&B>0,H=I&&L<t.length?t.slice(-L):t,ee=(0,Q.useCallback)(i=>{if(n||r||w.current)return;w.current=!0,M(),N();let a=t[0]?.id,o=z.current;Z(i.all?{type:`load_earlier_messages`,all:!0,conversationId:e.conversationId??void 0,beforeId:a,before:o}:{type:`load_earlier_messages`,count:i.count??d,conversationId:e.conversationId??void 0,beforeId:a,before:o}),setTimeout(()=>{w.current=!1},3e3)},[n,r,t,d,M,N,e.conversationId]),U=(0,Q.useCallback)(e=>{if(n)return;let r=e??d;M(),I&&t.length-p>=r?(N(),m(e=>Math.min(t.length,e+r))):(I&&t.length>p&&(N(),m(t.length)),z.current>0&&ee({count:r}))},[n,I,t,p,ee,d,M,N]),W=(0,Q.useRef)(V);W.current=V;let G=(0,Q.useRef)(U);G.current=U,(0,Q.useEffect)(()=>{let t=e.conversationId;if(!t||S.current===t||!V||n)return;let r=setTimeout(()=>{S.current!==t&&(S.current=t,W.current&&U())},150);return()=>clearTimeout(r)},[e.conversationId,V,n,U]);let K=!n&&(c||s);return(0,Q.useEffect)(()=>{K&&z.current>0&&ee({all:!0})},[K,ee]),{convKey:h,previewHandoff:v,anchorLock:T,anchorLockRef:D,visibleCount:p,setVisibleCount:m,isPagingActive:I,hasEarlier:V,earlierCount:B,visibleMessages:H,hasEarlierRef:W,loadEarlier:U,loadEarlierRef:G,cancelSettle:M}}function pC({messages:e,visibleCount:t,setVisibleCount:n,isPagingActive:r,scrollRef:i,stickRef:a,escapedRef:o,elsRef:s,expand:c,setPinned:l}){let u=(0,Q.useMemo)(()=>{let t=[];for(let n of e){if(n.role!==`user`)continue;let e=n.content.map(e=>Gl(e)?.text??``).filter(Boolean).join(` `),r=fl(e),i=r?r.userMessage??`skill:${r.name}`:e.trim();i&&t.push({id:n.id,text:i})}return t},[e]),d=(0,Q.useMemo)(()=>{let e=new Map;return u.forEach((t,n)=>e.set(t.id,n)),e},[u]),[f,p]=(0,Q.useState)(-1),m=(0,Q.useRef)(-1),h=(0,Q.useRef)(u);return(0,Q.useEffect)(()=>{h.current=u},[u]),(0,Q.useEffect)(()=>{let e=i.current;if(!e||u.length===0){m.current!==-1&&(m.current=-1,p(-1));return}if(a.current&&!o.current){let e=u.length-1;e!==m.current&&(m.current=e,p(e))}if(typeof IntersectionObserver>`u`)return;let t=new WeakMap,n=new Set,r=new Map,c=0,l=()=>{if(a.current&&!o.current){let e=h.current.length-1;e!==m.current&&(m.current=e,p(e));return}let e=c+140,t=-1;for(let i of n){let n=r.get(i);n!==void 0&&n<=e&&i>t&&(t=i)}if(t===-1){let i=1/0;for(let e of n)e<i&&(i=e);if(i!==1/0)t=i-1;else for(let[n,i]of r)i<=e&&n>t&&(t=n)}t!==m.current&&(m.current=t,p(t))},d=new IntersectionObserver(e=>{for(let i of e){let e=t.get(i.target);e!==void 0&&(i.rootBounds&&(c=i.rootBounds.top),r.set(e,i.boundingClientRect.top),i.isIntersecting?n.add(e):n.delete(e))}l()},{root:e,rootMargin:`0px`,threshold:0});for(let n=0;n<u.length;n++){let r=s.current.get(u[n].id)??e.querySelector(`[data-msg-id="${u[n].id}"]`);r&&(t.set(r,n),d.observe(r))}return()=>d.disconnect()},[s,o,u,i,a]),{questions:u,qnIndex:d,activeIdx:f,jumpTo:(0,Q.useCallback)(s=>{if(r){let r=e.findIndex(e=>e.id===s);r!==-1&&r<e.length-t&&(0,Er.flushSync)(()=>{n(e.length-r+5)})}(0,Er.flushSync)(()=>{c(s),l(e=>e.has(s)?e:new Set(e).add(s))});let u=h.current.findIndex(e=>e.id===s);m.current=u,p(u),requestAnimationFrame(()=>{let e=i.current?.querySelector(`[data-msg-id="${s}"]`);e&&(i.current?.querySelectorAll(`.msg-flash`).forEach(e=>e.classList.remove(`msg-flash`)),e.scrollIntoView({block:`start`}),e.classList.remove(`msg-flash`),e.offsetWidth,e.classList.add(`msg-flash`),e!==i.current?.lastElementChild&&(o.current=!0,a.current=!1))})},[c,o,r,e,i,l,n,a,t])}}var mC=new Map,hC=new Map,gC=15,_C=5,vC=100;function yC(e,t){if(t.size===0)return!1;for(let n of e.content)if(n.type===`toolCall`&&typeof n.id==`string`&&t.has(n.id))return!0;return!1}var bC=(0,Q.memo)(function({id:e,show:t,placeholderHeight:n,attachEl:r,onMeasured:i,variant:a=`trail`,children:o}){let s=(0,Q.useRef)(null);return(0,Q.useLayoutEffect)(()=>{if(!t)return;let n=s.current;if(!n)return;let r=Array.from(n.children,e=>e.getBoundingClientRect()),o=a===`contents`&&r.length?Math.max(...r.map(e=>e.bottom))-Math.min(...r.map(e=>e.top)):n.offsetHeight;o>0&&i?.(e,o)},[t,e,i,a]),t?(0,$.jsx)(`div`,{ref:e=>{s.current=e,r(e)},className:a===`flow`?`flow-turn`:a===`trail`?`turn-tools-trail`:void 0,style:a===`contents`?{display:`contents`}:void 0,"data-cluster-id":e,"data-lazy-id":e,children:o}):(0,$.jsx)(`div`,{ref:r,className:`msg-lazy-ph msg-lazy-ph-cluster`,"data-cluster-id":e,"data-lazy-id":e,style:{height:n},"aria-hidden":`true`})}),xC=(0,Q.memo)(function({state:e,liveOutputs:t,toolStatuses:n,onEdit:r,onKillBash:i,onRetry:a,onRemoveQueued:o,onRecallQueued:s,thinkingWrap:c,quickAskTranslateEnabled:l=!0,toolsWrap:u,toolImages:d,keepRecent:f,reversePagination:p=!1,minimalNewChat:m=!1,reasking:h=!1,jumpTarget:g,onJumpDone:_,urlJumpMessageId:v,onUrlJumpDone:y,preview:b=!1,userPromptNonce:x,messageLabels:S,readOnly:C=!1,uiMessageActions:w,uiContextMessage:T,uiContextToolCall:E,uiToolCardFooter:D,uiChatEmpty:O,onUiAction:k}){let A=X(),j=Dl(),M=(0,Q.useRef)(null),N=(0,Q.useRef)(!0),P=(0,Q.useRef)(!1),[F,I]=(0,Q.useState)(()=>new Set),[L,R]=(0,Q.useState)(!1),z=(0,Q.useMemo)(()=>e.streamingMessage?[...e.messages,e.streamingMessage]:e.messages,[e.messages,e.streamingMessage]),B=(0,Q.useMemo)(()=>{let t=new Map;for(let n of e.messages)n.role===`toolResult`&&n.toolCallId&&t.set(n.toolCallId,n);return t},[e.messages]),V=(0,Q.useMemo)(()=>X7(e.messages),[e.messages]),H=(0,Q.useMemo)(()=>{let t=new Map,n;for(let r of e.messages)r.role===`user`&&(n=r.id),n&&t.set(r.id,n);return t},[e.messages]),[ee,U]=(0,Q.useState)(null),W=(0,Q.useMemo)(()=>{for(let e=z.length-1;e>=0;e--)if(z[e].role!==`system`)return z[e].id;return null},[z]),G=Math.min(vC,Math.max(_C,Math.floor(Number(f)||gC))),K=(0,Q.useMemo)(()=>{let t=new Set;for(let n of e.messages)n.role!==`toolResult`&&N9(n)&&!F.has(n.id)&&t.add(n.id);return t},[e.messages,F]),q=I9(),te=sx(),ne=te.enabled&&!L&&!j.open,[re,J]=(0,Q.useState)(()=>new Set),ie=(0,Q.useCallback)(e=>{J(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ae=(0,Q.useMemo)(()=>({mergeTurns:!0}),[]),[oe,se]=(0,Q.useState)(()=>new Set),{convKey:Y,previewHandoff:ce,anchorLock:le,visibleCount:ue,setVisibleCount:de,isPagingActive:fe,hasEarlier:pe,visibleMessages:me,loadEarlier:he,cancelSettle:ge}=fC({state:e,messages:z,preview:b,readOnly:C,reversePagination:p,flowStream:q,keepRecentCount:G,exportOpen:j.open,searchOpen:L,scrollRef:M}),_e=(0,Q.useMemo)(()=>{let e=iC(me,ae);return ne?K9(e,{toolResults:B}):e},[me,ae,ne,B]);(0,Q.useEffect)(()=>{if(C||b||e.messages.length===0||_e.length>0||!pe)return;let t=setTimeout(()=>he(),150);return()=>clearTimeout(t)},[C,b,e.messages.length,e.historyStart,_e.length,pe,he]);let{virtualOn:ve,effectiveHidden:ye,alwaysSet:be,fingerprints:xe,heightsRef:Se,heightMetaRef:Ce,elsRef:we,attachEl:Te,storeHeight:Ee}=dC({scrollRef:M,convKey:Y,previewHandoff:ce,messages:z,stateMessages:e.messages,clusteredItems:_e,clusterOptions:ae,keepRecentCount:G,reversePagination:p,searchOpen:L,quietActive:ne,expanded:F}),De=eC((0,Q.useRef)({convKey:Y,pending:null,finalizedMap:new Map}).current,Y,e.messages,e.streamingMessage,(e,t)=>{let n=Se.current.get(e);n!==void 0&&!Se.current.has(t)&&Se.current.set(t,n)});(0,Q.useEffect)(()=>()=>{ge()},[]);let Oe=(0,Q.useCallback)(e=>{I(t=>t.has(e)?t:new Set(t).add(e))},[]),{questions:ke,qnIndex:Ae,activeIdx:je,jumpTo:Me}=pC({messages:e.messages,visibleCount:ue,setVisibleCount:de,isPagingActive:fe,scrollRef:M,stickRef:N,escapedRef:P,elsRef:we,expand:Oe,setPinned:se});(0,Q.useLayoutEffect)(()=>{wl(e.messages.filter(Sl).map(e=>({id:e.id,role:e.role,content:e.content})))},[e.messages]),(0,Q.useEffect)(()=>{if(j.open){for(let e of j.selectedIds)Oe(e);se(e=>{let t=!1,n=new Set(e);for(let e of j.selectedIds)n.has(e)||(n.add(e),t=!0);return t?n:e})}},[j.open,j.selectedIds,Oe]),(0,Q.useEffect)(()=>{let e=e=>{if(!(e.ctrlKey||e.metaKey)||e.key.toLowerCase()!==`f`)return;let t=e.target;(!t||t.tagName!==`INPUT`&&t.tagName!==`TEXTAREA`&&!t.isContentEditable)&&(e.preventDefault(),R(!0))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[]);let Ne=(0,Q.useCallback)(e=>{I(t=>{if(!t.has(e))return t;let n=new Set(t);return n.delete(e),n})},[]),Pe=(0,Q.useCallback)(t=>{let n=H.get(t);n&&r&&(Me(n),U({id:n,session:e.sessionFile}))},[H,r,Me,e.sessionFile]),[Fe,Ie]=(0,Q.useState)(null),Le=(0,Q.useRef)(null),Re=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let t=Le.current;if(!t||t.convId!==e.conversationId)Le.current={convId:e.conversationId,ids:new Set(e.messages.filter(e=>e.role===`compactionSummary`).map(e=>e.id))},Re.current=null,Ie(null);else for(let n of e.messages)if(n.role===`compactionSummary`&&!t.ids.has(n.id)){t.ids.add(n.id),Ie(n.id);break}},[e.messages,e.conversationId]),(0,Q.useEffect)(()=>{Fe&&Re.current!==Fe&&(Re.current=Fe,Me(Fe))},[Fe,Me]);let ze=(0,Q.useMemo)(()=>g?e.messages.find(e=>e.role===g.role&&e.timestamp===g.timestamp)?.id??null:null,[e.messages,g]);(0,Q.useEffect)(()=>{g&&(ze?(Me(ze),_?.()):e.sessionFile===g.path&&e.messages.length>0&&_?.())},[ze,Me,_,g,e.sessionFile,e.messages.length]),(0,Q.useEffect)(()=>{if(!v)return;let t=j_(e.messages,v);t?(Me(t),y?.()):e.messages.length>0&&y?.()},[v,e.messages,Me,y]);let{railRef:Be,stickBottom:Ve,scrollToBottom:He,pauseForSelection:Ue,handleWheel:We,handleTouchStart:Ge,handleTouchMove:Ke,handlePointerDown:qe,onScroll:Je}=yS({scrollRef:M,stickRef:N,escapedRef:P,messages:z,isStreaming:e.isStreaming,liveOutputs:t,toolStatuses:n,queue:e.queue,conversationId:e.conversationId,sessionFile:e.sessionFile,questions:ke,jumpTarget:g,urlJumpMessageId:v,hasEarlier:pe,loadEarlier:he,userPromptNonce:x}),Ye=D9(),[Xe,Ze]=(0,Q.useState)(0),Qe=ke.length>0&&!Ye;(0,Q.useLayoutEffect)(()=>{let e=Be.current;if(!e)return;let t=()=>Ze(e.clientHeight);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[Qe,Be]);let{indices:$e,gap:et,many:tt}=(0,Q.useMemo)(()=>Z7(ke.length,Xe,je),[ke.length,Xe,je]),nt=(o,s=!1,l=!1)=>{let f=(e.streamingMessage?o.id===e.streamingMessage.id:e.isStreaming&&o.id===W)&&(o.role===`assistant`||!o.role),p=De.get(o.id)??o.id,m=s?f?u:!1:u;return(0,$.jsx)(t1,{uiMessageActions:w,uiContextMessage:T,uiContextToolCall:E,uiToolCardFooter:D,onUiAction:C?void 0:k,message:o,toolResults:B,liveOutputs:yC(o,t)?t:mC,toolStatuses:yC(o,n)?n:hC,streaming:f,onKillBash:C?void 0:i,onRetry:!C&&o.id===W?a:void 0,toolsWrap:m,toolImages:d,thinkingWrap:c,isLast:o.id===W,onEdit:C?void 0:r,readOnly:C,messageLabel:S?.get(o.id),onRollbackEdit:Pe,canRollbackEdit:!C&&!!r&&H.has(o.id),questionAttachments:V.get(o.id),editRequest:ee&&ee.session===e.sessionFile&&ee.id===o.id?ee:void 0,searchActive:L,hideProcessBlocks:ne&&!l},p)};return(0,$.jsxs)(`div`,{className:`messages-wrap${j.open?` messages-exporting`:``}`,children:[(0,$.jsx)(ZS,{rootRef:M,sessionId:e.sessionId,enabled:!j.open,translateEnabled:l,onSelect:Ue}),(0,$.jsxs)(`div`,{className:`messages${L||le||Ve&&!P.current?``:` anchor-live`}`,"data-chat-transcript":``,ref:M,onScroll:Je,onWheel:We,onTouchStart:Ge,onTouchMove:Ke,onPointerDown:qe,children:[e.messages.length===0&&!e.streamingMessage&&!e.isStreaming&&!m&&!h&&(0,$.jsxs)(`div`,{className:`empty-state`,children:[(0,$.jsx)(Sb,{}),!C&&O&&O.length>0&&(0,$.jsx)(`div`,{className:`chat-empty-slots`,children:Px(O,k)})]}),_e.map(o=>{if(o.type===`quiet_fold`){let e=re.has(o.id),t=q9(o.messages),n=A(`quietHidden`,{count:t.total}),r=J9(o.messages),i=r.length>0?r.length<=3?r.join(`, `):`${r.slice(0,3).join(`, `)} +${r.length-3}`:t.thinking>0?A(`thinking`):``,a=i?`${n} · ${i}`:n,s=[];t.thinking&&s.push(`${A(`thinking`)} ${t.thinking}`),t.tools&&s.push(`${A(`toolCalls`)} ${t.tools}`),t.bash&&s.push(`${A(`bashRuns`)} ${t.bash}`),t.collab&&s.push(`${A(`subagentBadge`)} ${t.collab}`);let c=()=>ie(o.id);return(0,$.jsxs)(Q.Fragment,{children:[te.style===`zero`?(0,$.jsx)(`div`,{className:`quiet-gap`,role:`button`,tabIndex:0,"aria-expanded":e,title:a,"aria-label":a,onClick:c,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),c())}}):(0,$.jsxs)(`button`,{type:`button`,className:`quiet-fold-toggle${e?` is-open`:``}`,"aria-expanded":e,title:s.length>0?`${a} (${s.join(` · `)})`:a,onClick:c,children:[(0,$.jsx)(`span`,{children:a}),(0,$.jsx)(At,{className:`quiet-fold-chevron`,"aria-hidden":`true`})]}),e&&(0,$.jsx)(`div`,{className:`turn-tools-trail`,children:o.messages.map(e=>nt(e,!1,!0))})]},o.id)}if(o.type===`tool_cluster`){let t=e.streamingMessage?.id,n=(t?o.messages.some(e=>e.id===t):!1)||e.isStreaming&&o.messages.some(e=>e.id===W),r=o.messages.some(e=>oe.has(e.id)),i=o.messages.some(e=>be.has(e.id)),a=ye.has(o.id),s=!q&&!o.messages.every(nC),c=!ve||n||r||i||!a,l=o.messages.filter(nC).length>=4;return(0,$.jsx)(bC,{id:o.id,show:c,placeholderHeight:tS(o.id,xe.get(o.id)??-1,Ce.current,aC(o.messages,q)),attachEl:Te,onMeasured:Ee,variant:q?`flow`:s?`contents`:`trail`,children:o.messages.map(e=>nt(e,l))},`cluster-${De.get(o.messages[0].id)??o.messages[0].id}`)}let s=o.message,l=N9(s);if(l&&!F.has(s.id))return(0,$.jsx)(O9,{message:s,onExpand:Oe,summary:l.kind===`prompt`?A(`goalBarReviewing`):l.verdict===`pass`?A(`goalBarPassed`):A(`goalBarFailed`)},s.id);let f=s.role===`user`?Ae.get(s.id):void 0,p=!ve||be.has(s.id)||oe.has(s.id)||!ye.has(s.id),m=(e.streamingMessage?s.id===e.streamingMessage.id:e.isStreaming&&s.id===W)&&(s.role===`assistant`||!s.role),h=De.get(s.id)??s.id;return(0,$.jsx)(Y9,{id:s.id,show:p,height:tS(s.id,xe.get(s.id)??-1,Ce.current,Q9(s.role,s.customType)),containerRef:M,onMeasured:Ee,lazyRef:Te,children:(0,$.jsx)(t1,{uiMessageActions:w,uiContextMessage:T,uiContextToolCall:E,uiToolCardFooter:D,onUiAction:C?void 0:k,message:s,qnIndex:f,qnActive:f===void 0?void 0:f===je,onJump:Me,toolResults:B,liveOutputs:yC(s,t)?t:mC,toolStatuses:yC(s,n)?n:hC,streaming:m,onKillBash:C?void 0:i,onRetry:!C&&s.id===W?a:void 0,toolsWrap:u,toolImages:d,thinkingWrap:c,isLast:s.id===W,onEdit:C?void 0:r,readOnly:C,messageLabel:S?.get(s.id),onRollbackEdit:Pe,canRollbackEdit:!C&&!!r&&H.has(s.id),editRequest:ee&&ee.session===e.sessionFile&&ee.id===s.id?ee:void 0,questionAttachments:V.get(s.id),onCollapse:l?Ne:void 0,searchActive:L,autoExpand:s.id===Fe},h)},h)}),e.retry&&e.isStreaming&&(0,$.jsxs)(`div`,{className:`retry-notice`,role:`status`,title:e.retry.errorMessage||void 0,children:[(0,$.jsx)(`span`,{className:`retry-pulse`}),(0,$.jsx)(`span`,{className:`retry-text`,children:e.retry.maxAttempts>0?A(`retryingApi`,{attempt:Math.max(1,e.retry.attempt),max:e.retry.maxAttempts,error:e.retry.errorMessage}):A(`retryingApiSoon`,{error:e.retry.errorMessage})})]}),e.compaction&&(0,$.jsx)($S,{compaction:e.compaction}),(e.isStreaming||h)&&z.length===0&&(0,$.jsx)(`div`,{className:`streaming-wait`,children:A(`waitingResponse`)}),(e.queue.entries?.steering??e.queue.steering).map((e,t)=>{let n=typeof e!=`string`,r=n?e.text:e,i=n?e.id:void 0;return(0,$.jsx)(QS,{kind:`steer`,text:r,parsed:Da(r),index:t,id:i,onRemoveQueued:C?void 0:o,onRecallQueued:C?void 0:s},i||`q-steer-${t}`)}),(e.queue.entries?.followUp??e.queue.followUp).map((e,t)=>{let n=typeof e!=`string`,r=n?e.text:e,i=n?e.id:void 0;return(0,$.jsx)(QS,{kind:`followUp`,text:r,parsed:Da(r),index:t,id:i,onRemoveQueued:C?void 0:o,onRecallQueued:C?void 0:s},i||`q-fu-${t}`)}),!C&&e.actionSuggestions&&e.actionSuggestions.length>0&&(0,$.jsx)(`div`,{className:`action-suggestions`,"aria-label":A(`actionSuggestions`),children:(0,$.jsx)(`div`,{className:`action-suggestions-list`,children:e.actionSuggestions.map(t=>(0,$.jsxs)(`button`,{type:`button`,className:`action-suggestion-chip`,title:t.prompt===t.label?t.label:A(`actionSuggestionsTip`,{prompt:t.prompt}),disabled:e.isStreaming,onClick:()=>{He(),Z({type:`prompt`,text:t.prompt})},children:[(0,$.jsx)(`span`,{className:`action-suggestion-label`,children:t.label}),(0,$.jsx)(`span`,{className:`action-suggestion-icon`,"aria-hidden":`true`,children:`↵`})]},t.id))})})]}),!Ve&&(0,$.jsxs)(`button`,{type:`button`,className:`scroll-bottom`,title:A(`backToBottom`),"aria-label":A(`backToBottom`),onClick:He,children:[(0,$.jsx)(Tt,{}),(0,$.jsx)(`span`,{className:`scroll-bottom-label`,children:A(`backToBottom`)})]}),(0,$.jsx)(fS,{containerRef:M,messages:z,collapsedIds:K,toolResults:B,onExpand:Oe,onProgrammaticScroll:()=>{Ue()},open:L,onClose:()=>R(!1)}),ke.length>0&&!Ye&&(0,$.jsxs)(`div`,{className:`qn-rail ${tt?`many`:``}`,ref:Be,"aria-label":A(`questionNavTitle`),style:{"--rail-gap":`${et}px`},children:[$e.map(e=>{let t=ke[e];return(0,$.jsx)(`button`,{type:`button`,className:`qn-bar ${e===je?`active`:``}`,"aria-label":`${e+1}. ${t.text}`,onClick:()=>Me(t.id),children:(0,$.jsxs)(`span`,{className:`qn-bar-text`,children:[e+1,`. `,t.text]})},t.id)}),tt&&(0,$.jsx)(`div`,{className:`qn-list`,children:ke.map((e,t)=>(0,$.jsxs)(`button`,{type:`button`,className:`qn-list-item ${t===je?`active`:``}`,"aria-label":`${t+1}. ${e.text}`,onClick:()=>Me(e.id),children:[(0,$.jsx)(`span`,{className:`qn-list-idx`,children:t+1}),(0,$.jsx)(`span`,{className:`qn-list-text`,children:e.text})]},e.id))})]}),(0,$.jsx)(KS,{})]})}),SC=30,CC=56,wC=e=>/[^\x00-\x7f]/.test(e)?Math.round(SC/2):SC;function TC(e){return(0,$.jsx)(EC,{...e},e.cwd??``)}function EC({cwd:e,onClose:t,onCreate:n,disabled:r=!1}){let i=X(),a=(0,Q.useId)(),[o,s]=(0,Q.useState)(null),[c,l]=(0,Q.useState)(``),[u,d]=(0,Q.useState)({}),f=z5(e??``),p=f?Li(e??``):null,[m,h]=(0,Q.useState)(null),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(0),[b,x]=(0,Q.useState)(!1),S=f&&m?.persistence?.available===!0,C=e=>b&&S?{...e,keepAlive:!0}:e,w=(0,Q.useRef)(null),T=!!e&&!m&&g===null;(0,Q.useEffect)(()=>{if(!e)return;let t=new AbortController;return w.current=t,(async()=>{try{let n=await fetch(j(`/api/native-cli/discovery?cwd=${encodeURIComponent(e)}`),{signal:t.signal}),r=await n.json();if(t.signal.aborted)return;if(!n.ok)throw Error(r.error||``);if(r.cwd!==e||r.target!==(f?`ssh`:`local`)||!Array.isArray(r.clis))throw Error();h(r)}catch(e){t.signal.aborted||_(e instanceof Error?e.message:``)}})(),()=>t.abort()},[e,f,v]);let E=()=>{w.current?.abort(),t()},D=e=>e===`custom`?void 0:m?.clis.find(t=>t.preset===e),O=e=>{if(r||e===`custom`)return r;let t=D(e);return f?!t?.available:t?.available===!1},k=e=>{let t=D(e.id),n=e.cliCommand??e.name;if(t?.available){let e=t.executable??n;return{text:oh(e,wC(e)),full:e}}return f?{text:t?.error??i(T?`nativeCliRemoteDetecting`:`nativeCliRemoteUnavailable`)}:t?{text:i(`nativeCliNotInstalled`)}:T?{text:i(`nativeCliDetecting`)}:{text:e.cliRequiresArgs?i(`nativeCliConfigureArgs`):n}},A=(e,t)=>{window.dispatchEvent(new CustomEvent(`pi-web-ui:plugin-run-command`,{detail:{title:i(`installEngineTabTitle`,{name:e}),command:t}})),E()},M=Object.values(Dx).filter(e=>e.cliCommand),N=[`claude`,`codex`,`pi`];M.sort((e,t)=>{let n=e=>N.includes(e)?N.indexOf(e):N.length;return n(e.id)-n(t.id)});let P=o?u[o]??``:``,F=B5(P),I=o!==null&&o!==`custom`&&Dx[o].cliRequiresArgs,L=o!==null&&!O(o)&&(o!==`custom`||!!c.trim())&&(!I||!!F[0]?.trim()),R=e=>{let t=e.installCommand;return t?/^https?:\/\//i.test(t)?`docs`:`terminal`:null},z=e=>{O(e)||(e===`custom`||Dx[e].cliRequiresArgs?s(e):n(C({preset:e})))};return(0,$.jsx)(jr,{title:i(`nativeCliCreate`),icon:(0,$.jsx)(Xe,{size:18}),onClose:E,className:`native-cli-create-modal`,closeOnBackdropClick:!r,closeOnEscape:!r,showCloseButton:!r,children:(0,$.jsxs)(`div`,{className:`native-cli-create-body`,"aria-busy":r||T,children:[(0,$.jsx)(`p`,{className:`native-cli-create-hint`,children:i(`nativeCliChooseEngine`)}),e&&(0,$.jsx)(`div`,{className:`native-cli-create-cwd`,title:e,children:p?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{children:i(`nativeCliRemoteLocation`,{host:`${p.username}@${p.host}:${p.port}`})}),(0,$.jsx)(`div`,{children:i(`nativeCliRemotePath`,{path:oh(p.remotePath,CC)})})]}):oh(e,CC)}),T&&(0,$.jsx)(`p`,{className:`native-cli-create-hint`,role:`status`,children:i(f?`nativeCliRemoteDetecting`:`nativeCliDetecting`)}),g!==null&&(0,$.jsxs)(`div`,{role:`alert`,className:`native-cli-create-hint`,children:[(0,$.jsx)(`p`,{children:g||i(f?`nativeCliRemoteDiscoveryFailed`:`nativeCliDiscoveryFailed`)}),f&&(0,$.jsx)(`p`,{children:i(`nativeCliRemoteConnectHint`)})]}),e&&(0,$.jsx)(`div`,{children:(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:r||T,onClick:()=>{w.current?.abort(),h(null),x(!1),_(null),y(e=>e+1)},children:i(`nativeCliRemoteRetry`)})}),f&&(0,$.jsxs)(`div`,{className:`native-cli-persistence`,children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:b&&S,disabled:r||!S,onChange:e=>x(e.target.checked),"aria-describedby":`${a}-persistence-hint`}),i(`nativeCliSession.keepAlive`)]}),(0,$.jsx)(`p`,{id:`${a}-persistence-hint`,className:`native-cli-create-hint`,children:S?i(`nativeCliSession.keepAliveHint`):m?.persistence?.error||i(`nativeCliSession.persistenceUnavailable`)})]}),(0,$.jsxs)(`div`,{className:`native-cli-create-options`,children:[M.map(e=>{let t=D(e.id),n=k(e),s=!f&&t?.available===!1?R(e):null,c=e.installCommand??``;return(0,$.jsxs)(`div`,{className:`native-cli-create-item`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`native-cli-create-option`,disabled:O(e.id),"aria-expanded":e.cliRequiresArgs?o===e.id:void 0,"aria-controls":e.cliRequiresArgs?`${a}-config`:void 0,onClick:()=>z(e.id),children:[(0,$.jsx)(Xe,{size:18}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`small`,{className:n.full?`native-cli-create-path`:void 0,title:n.full,children:n.text})]}),(0,$.jsx)(At,{size:16})]}),s===`terminal`&&(0,$.jsxs)(`button`,{type:`button`,className:`native-cli-create-install`,disabled:r,title:c,onClick:()=>A(e.name,c),children:[(0,$.jsx)(ht,{size:13}),i(`nativeCliInstall`)]}),s===`docs`&&(0,$.jsxs)(`a`,{className:`native-cli-create-install`,href:c,target:`_blank`,rel:`noreferrer`,children:[(0,$.jsx)(ht,{size:13}),i(`nativeCliInstallDocs`)]})]},e.id)}),(0,$.jsx)(`div`,{className:`native-cli-create-item`,children:(0,$.jsxs)(`button`,{type:`button`,className:`native-cli-create-option`,disabled:r,"aria-expanded":o===`custom`,"aria-controls":`${a}-config`,onClick:()=>z(`custom`),children:[(0,$.jsx)(Xe,{size:18}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:i(`nativeCliCustom`)}),(0,$.jsx)(`small`,{children:i(`nativeCliExecutable`)})]}),(0,$.jsx)(At,{size:16})]})})]}),o&&(0,$.jsxs)(`form`,{id:`${a}-config`,className:`native-cli-create-config`,onSubmit:e=>{e.preventDefault(),L&&n(C(o===`custom`?{preset:`custom`,executable:c.trim(),args:F}:{preset:o,args:F}))},children:[(0,$.jsx)(`strong`,{children:o===`custom`?i(`nativeCliCustom`):Dx[o].name}),o===`custom`&&(0,$.jsxs)(`label`,{htmlFor:`${a}-executable`,children:[i(f?`nativeCliRemoteExecutable`:`nativeCliExecutable`),(0,$.jsx)(`input`,{id:`${a}-executable`,value:c,onChange:e=>l(e.target.value),disabled:r,required:!0,autoFocus:!0,autoComplete:`off`})]}),f&&o===`custom`&&(0,$.jsx)(`p`,{className:`native-cli-create-hint`,children:i(`nativeCliRemoteExecutableHint`)}),(0,$.jsxs)(`label`,{htmlFor:`${a}-args`,children:[i(`nativeCliArgs`),(0,$.jsx)(`textarea`,{id:`${a}-args`,value:P,onChange:e=>d(t=>({...t,[o]:e.target.value})),disabled:r,rows:4,required:!!I,"aria-describedby":`${a}-args-hint`})]}),(0,$.jsx)(`p`,{id:`${a}-args-hint`,className:`native-cli-create-hint`,children:i(`nativeCliArgsHint`)}),(0,$.jsx)(`div`,{className:`native-cli-create-actions`,children:(0,$.jsx)(`button`,{type:`submit`,className:`btn primary`,disabled:!L,children:i(`nativeCliStart`)})})]})]})})}var DC={pending:`in_progress`,in_progress:`done`,done:`failed`,failed:`pending`};function OC(e){switch(e){case`done`:return(0,$.jsx)(h,{});case`in_progress`:return(0,$.jsx)(R,{});case`failed`:return(0,$.jsx)(Me,{});default:return(0,$.jsx)(ae,{})}}function kC({plan:e}){let t=X(),[n,r]=(0,Q.useState)(!1),[i,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(``),l=e?.steps??[],u=e?.markdown?.trim()??``;if(l.length===0&&!u)return null;let d=l.filter(e=>e.status===`done`).length,f=!!u&&l.length===0,p=l.find(t=>t.id===e?.activeStepId)??l.find(e=>e.status===`in_progress`)??l.find(e=>e.status===`pending`)??l[l.length-1],m=u.split(/\r?\n/).map(e=>e.replace(/^#{1,6}\s+/,``).trim()).find(Boolean),h=e=>{switch(e){case`done`:return t(`planBoardCompleted`);case`in_progress`:return t(`planBoardInProgress`);case`failed`:return t(`planBoardFailed`);default:return t(`planBoardPending`)}},g=e=>{o(e.id),c(e.content)},_=()=>{o(null),c(``)},v=e=>{let t=s.trim();t&&(Z({type:`plan_step_update`,stepId:e,patch:{content:t}}),o(null))},y=e=>{let t=l.find(t=>t.id===e);t&&Z({type:`plan_step_update`,stepId:e,patch:{status:DC[t.status]}})};return(0,$.jsx)(`div`,{className:`plan-board${n?` plan-board-collapsed`:``}`,children:n?(0,$.jsxs)(`div`,{className:`plan-board-mini`,onClick:()=>r(!1),children:[p?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`plan-board-mini-status status-${p.status}`,children:OC(p.status)}),(0,$.jsx)(`span`,{className:`plan-board-mini-text`,title:p.content,children:p.content}),(0,$.jsxs)(`span`,{className:`plan-board-mini-count`,children:[d,`/`,l.length]})]}):(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`plan-board-mini-status`,children:(0,$.jsx)(vt,{})}),(0,$.jsx)(`span`,{className:`plan-board-mini-text`,title:m??``,children:m??``})]}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn plan-board-mini-expand`,title:t(`expandSection`),"aria-label":t(`expandSection`),children:(0,$.jsx)(D,{size:13})})]}):(0,$.jsxs)($.Fragment,{children:[l.length===0&&(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn plan-board-collapse-fab`,title:t(`collapseSection`),"aria-label":t(`collapseSection`),onClick:()=>r(!0),children:(0,$.jsx)(a,{size:13})}),f&&(0,$.jsx)(`div`,{className:`plan-board-markdown`,children:(0,$.jsx)(nl,{text:u})}),l.length>0&&(0,$.jsx)(`div`,{className:`plan-board-steps`,children:l.map((n,o)=>{let l=n.id===e?.activeStepId||n.status===`in_progress`;return i===n.id?(0,$.jsxs)(`div`,{className:`plan-board-edit`,children:[(0,$.jsx)(`input`,{type:`text`,className:`plan-board-edit-input`,value:s,onChange:e=>c(e.target.value),placeholder:t(`planBoardStepTitlePlaceholder`),autoFocus:!0,onKeyDown:e=>{e.key===`Enter`&&!e.shiftKey?(e.preventDefault(),v(n.id)):e.key===`Escape`&&_()}}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`confirm`),onClick:()=>v(n.id),children:(0,$.jsx)(z,{size:13})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`cancel`),onClick:_,children:(0,$.jsx)(Ct,{size:13})}),o===0&&(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn plan-board-collapse-inline`,title:t(`collapseSection`),"aria-label":t(`collapseSection`),onClick:()=>r(!0),children:(0,$.jsx)(a,{size:13})})]},n.id||o):(0,$.jsxs)(`div`,{className:`plan-board-row${l?` active`:``}${n.status===`done`?` done`:``}`,children:[(0,$.jsx)(`button`,{type:`button`,className:`plan-board-status status-${n.status}`,title:`${h(n.status)} · ${t(`planBoardToggleStatusTip`)}`,"aria-label":h(n.status),onClick:()=>y(n.id),children:OC(n.status)}),(0,$.jsxs)(`div`,{className:`plan-board-row-body`,onDoubleClick:()=>g(n),children:[(0,$.jsxs)(`span`,{className:`plan-board-row-idx`,children:[o+1,`.`]}),(0,$.jsx)(`span`,{className:`plan-board-row-text`,children:n.content})]}),(0,$.jsxs)(`div`,{className:`plan-board-row-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardEditStep`),onClick:()=>g(n),children:(0,$.jsx)(et,{size:12})}),(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn`,title:t(`planBoardDeleteStep`),onClick:()=>Z({type:`plan_step_delete`,stepId:n.id}),children:(0,$.jsx)(Ne,{size:12})})]}),o===0&&(0,$.jsx)(`button`,{type:`button`,className:`plan-board-iconbtn plan-board-collapse-inline`,title:t(`collapseSection`),"aria-label":t(`collapseSection`),onClick:()=>r(!0),children:(0,$.jsx)(a,{size:13})})]},n.id||o)})})]})})}function AC({pluginId:e,info:t,epoch:n,failed:r}){let i=X(),[a,o]=(0,Q.useState)(!1),s=t?.name||e;return r?(0,$.jsx)(`div`,{className:`view-pane`,children:(0,$.jsxs)(`div`,{className:`plugin-view-fallback`,role:`alert`,children:[(0,$.jsxs)(`div`,{className:`plugin-view-fallback-title`,children:[i(`pluginViewLoadFailed`),`:`,s]}),(0,$.jsx)(`div`,{className:`plugin-view-fallback-hint`,children:i(`pluginViewLoadFailedHint`)}),t&&(0,$.jsx)(`button`,{type:`button`,className:`plugin-view-fallback-retry`,onClick:()=>{t&&!a&&(o(!0),D0(t,n).finally(()=>o(!1)))},disabled:a,children:i(a?`pluginViewLoading`:`pluginViewRetry`)})]})}):(0,$.jsx)(`div`,{className:`view-pane`,children:(0,$.jsx)(`div`,{className:`plugin-view-fallback`,role:`status`,children:i(`pluginViewLoading`)})})}function jC({open:e,pathCompletions:t,onClose:n}){let r=mn(`cwd`),i=mn(`workspaceRoots`);return e?(0,$.jsx)(qd,{open:!0,currentCwd:r,pathCompletions:t,workspaceRoots:i,onClose:n,onSelectDirectory:(e,t)=>Z({type:`set_cwd`,path:e,...t?{name:t}:{}}),onCreateProject:(e,t)=>Z({type:`make_dir`,path:e,setAsCwd:!0,...t?{name:t}:{}})}):null}function MC(e){if(e.global&&e.owner&&e.conversationId)return{type:`open_shared_conversation`,owner:e.owner,id:e.conversationId};if(e.owner)return{type:`navigate_question`,id:e.id};let t=e.conversationId??e.rootConversationId;return t?{type:`switch_conversation`,id:t}:void 0}function NC(e,t){if(!Number.isFinite(e)||e<=0)return;let n=t>1e12&&e>1e9&&e<1e11?e*1e3:e,r=Math.max(0,t-n);if(r>2592e6)return;let i=Math.floor(r/1e3),a=Math.floor(i/60),o=String(i%60).padStart(2,`0`);return a<60?`${a}:${o}`:`${Math.floor(a/60)}:${String(a%60).padStart(2,`0`)}:${o}`}function PC(e,t,n,r=[],i){let a=r.map(e=>({...e,global:!0,audience:`user`,createdAt:e.createdAt??0})),o=e=>FC(e,a,i);if(e!==null)return o(e.filter(e=>e.audience===`user`));let s=[];for(let e of[t&&{...t,createdAt:0,audience:`user`},n&&{...n,conversationId:n.convId,createdAt:0,audience:`user`}])e&&(s.some(t=>t.id===e.id&&(`owner`in e?t.owner===e.owner:!e.conversationId||t.conversationId===e.conversationId))||s.push(e));return o(s)}function FC(e,t,n){let r=new Map;for(let i of[...e.map(e=>n&&!e.owner?{...e,owner:n,global:!0}:e),...t])r.set(JSON.stringify([i.owner??``,i.id]),i);return[...r.values()]}function IC(e){return JSON.stringify([e.owner??``,e.conversationId??``,e.id])}function LC(e,t){let n=e=>{let t=e.replace(/[\\/]+$/,``);return/^[a-zA-Z]:/.test(t)?t.toLowerCase():t},r=e.cwd?n(e.cwd):``,i=t?n(t):``;if(r&&i&&r!==i)return r.split(/[\\/]/).filter(Boolean).pop()??r}function RC(e,t){return!!t&&(e.conversationId===t||e.rootConversationId===t)}var zC=`pi_web_qdraft_`,BC=864e5,VC=new Map;function HC(e){return`${zC}${e}`}function UC(e){if(!e)return null;try{if(typeof window<`u`&&window.sessionStorage){let t=window.sessionStorage.getItem(HC(e));if(t){let n=JSON.parse(t);if(n&&typeof n==`object`&&n.selections&&typeof n.selections==`object`&&n.customs&&typeof n.customs==`object`&&typeof n.step==`number`)return n.updatedAt&&Date.now()-n.updatedAt>BC?(GC(e),null):n}}}catch{}let t=VC.get(e);return t?t.updatedAt&&Date.now()-t.updatedAt>BC?(VC.delete(e),null):t:null}function WC(e,t){if(!e)return;let n=Object.values(t.selections).some(e=>e&&e.length>0),r=Object.values(t.customs).some(e=>e&&e.trim().length>0),i=t.step>0;if(!n&&!r&&!i){GC(e);return}let a={selections:{...t.selections},customs:{...t.customs},step:t.step,updatedAt:Date.now()};VC.set(e,a);try{typeof window<`u`&&window.sessionStorage&&window.sessionStorage.setItem(HC(e),JSON.stringify(a))}catch{}}function GC(e){if(e){VC.delete(e);try{typeof window<`u`&&window.sessionStorage&&window.sessionStorage.removeItem(HC(e))}catch{}}}function KC({question:e,owner:t,conversationTitle:n,project:r,onDefer:i,onNavigate:o}){let s=X(),l=e.global?JSON.stringify([t,e.id]):e.id,u=e.conversationTitle||n,[d,f]=(0,Q.useState)(()=>UC(l)?.selections??{}),[p,m]=(0,Q.useState)(()=>UC(l)?.customs??{}),[h,g]=(0,Q.useState)(!1),[_,v]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi-web:question-auto-submit-last`)===`1`}catch{return!1}}),y=w6(),[b,x]=(0,Q.useState)(()=>UC(l)?.step??0),[S,C]=(0,Q.useState)(()=>e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1),[T,E]=(0,Q.useState)(Date.now),O=(0,Q.useRef)(!1),[k,A]=(0,Q.useState)(!1),j=(0,Q.useSyncExternalStore)($4,Y4,Y4);(0,Q.useEffect)(()=>{O.current=!1;let t=UC(l);t?(f(t.selections),m(t.customs),x(t.step)):(f({}),m({}),x(0)),g(!1);let n=e.deadline?Math.max(0,Math.ceil((e.deadline-Date.now())/1e3)):-1;C(n),E(Date.now())},[e.id,e.deadline,e.createdAt,t]),(0,Q.useEffect)(()=>{O.current||WC(l,{selections:d,customs:p,step:b})},[e.id,d,p,b]),(0,Q.useEffect)(()=>{if(!e.deadline&&!e.createdAt)return;E(Date.now());let t=setInterval(()=>{let t=Date.now();E(t),e.deadline&&C(Math.max(0,Math.ceil((e.deadline-t)/1e3)))},1e3);return()=>clearInterval(t)},[e.id,e.deadline,e.createdAt]);let M=(0,Q.useCallback)(n=>{O.current=!0,GC(l),oo({type:`question_answer`,id:e.id,answers:[],cancelled:!0,...e.global?{global:!0}:{},...n?.trim()?{cancelReason:n.trim()}:{},...t?{owner:t}:{}})},[e.id,t]);Lt(()=>{i?i():M()},!h);let N=e.questions,P=N.length,F=Math.min(b,Math.max(0,P-1)),I=N[F];if(!I)return(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":`select`,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:s(`modelQuestion`)}),r&&(0,$.jsx)(`span`,{className:`question-conv-title`,children:r}),u&&(0,$.jsx)(`span`,{className:`question-conv-title`,title:u,children:u}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:s(i?`questionQueueDefer`:`cancel`),onClick:()=>i?i():M(),children:`✕`})]}),(0,$.jsx)(`div`,{className:`set-section`,children:(0,$.jsx)(`div`,{className:`set-hint`,children:s(`questionNoneAvailable`)})})]});let L=I.options??[],R=(n,r)=>{let i=r??p;O.current=!0,GC(l);let a=e.questions.map(e=>{let t=n[e.id]??[],r=(i[e.id]??``).trim();return{id:e.id,selected:t,...r?{custom:r}:{}}});oo({type:`question_answer`,id:e.id,answers:a,...e.global?{global:!0}:{},...t?{owner:t}:{}})||A(!0)},z=()=>{let e={...d,[I.id]:[]},t={...p,[I.id]:``};f(e),m(t),j&&X4(),F<P-1?x(F+1):R(e,t)},B=(e,t)=>{f(n=>{let r=n[e]??[];return{...n,[e]:r.includes(t)?r.filter(e=>e!==t):[...r,t]}})},V=e=>{let t=j.trim();return t?{...e,[I.id]:t}:e},H=(t,n,r)=>{if(r){B(t,n);return}let i=(d[t]??[]).includes(n),a={...d,[t]:i?[]:[n]};if(f(a),i)return;let o=e.questions.findIndex(e=>e.id===t)+1;if(o<e.questions.length){let e=V(p);j.trim()&&(m(e),X4()),x(o)}else if(_){let e=V(p);j.trim()&&X4(),R(a,e)}},ee=()=>{let e=V(p);j.trim()&&(m(e),X4()),F>=P-1?R(d,e):x(F+1)},U=t=>{let n=e.questions.find(e=>e.id===t);if(L.length===0&&(n?.options?.length??0)===0)return!0;let r=t===I.id&&j.trim()||(p[t]??``).trim();return(d[t]?.length??0)>0||r!==``},W=I.question.replace(/\s+/g,` `).trim(),G=j.trim()||(p[I.id]??``).trim(),K=Object.values(p).map(e=>e?.trim()).filter(Boolean).join(`;
|
|
405
|
-
`),q=G.length>0||K.length>0,te=G||K,ne=(0,Q.useRef)(()=>!1);ne.current=()=>U(I.id)?(ee(),!0):!1,(0,Q.useEffect)(()=>{if(h)K4(null);else return K4(()=>ne.current()),()=>K4(null)},[h]),(0,Q.useEffect)(()=>{if(h)return;let e=e=>{let t=e.target;if(!(t?.tagName===`INPUT`||t?.tagName===`TEXTAREA`||t?.isContentEditable||y.isImeKey(e))&&!(e.key===`Enter`&&t?.closest?.(`button, select, label`))){if(e.key>=`1`&&e.key<=`9`){let t=parseInt(e.key,10)-1;if(t<L.length){e.preventDefault(),H(I.id,L[t].label,!!I.multiSelect);return}}e.key===`ArrowLeft`&&F>0?(e.preventDefault(),x(F-1)):e.key===`ArrowRight`&&F<P-1&&U(I.id)?(e.preventDefault(),x(F+1)):e.key===`Enter`&&U(I.id)&&(e.preventDefault(),ee())}};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[h,L,I.id,I.multiSelect,F,P,U,ee,H]);let re=NC(e.createdAt??0,T),J=!!(r||u||k||S>=0||re);return(0,$.jsxs)(`div`,{className:`dialog-inline${h?` collapsed`:``}`,"data-dialog-kind":`select`,children:[(0,$.jsxs)(`div`,{className:`dialog-head question-dialog-head`,onClick:h?()=>g(!1):void 0,children:[(0,$.jsxs)(`div`,{className:`question-head-main`,children:[(0,$.jsxs)(`span`,{className:`question-head-icon`,"aria-hidden":`true`,children:[(0,$.jsx)(xt,{}),(0,$.jsx)(`span`,{className:`question-head-dot`})]}),h?(0,$.jsx)(`span`,{className:`question-collapsed-preview`,title:W,children:W}):(0,$.jsxs)(`div`,{className:`question-head`,children:[I.header&&(0,$.jsx)(`span`,{className:`question-header-tag`,children:I.header}),(0,$.jsx)(nl,{text:I.question,rawHtml:!0}),I.detail&&(0,$.jsx)(nl,{text:I.detail,rawHtml:!0})]}),(0,$.jsxs)(`div`,{className:`dialog-head-actions`,children:[P>1&&!h&&(0,$.jsxs)(`div`,{className:`question-stepper`,children:[(0,$.jsx)(`button`,{type:`button`,className:`question-step-arrow dialog-prev`,disabled:F===0,title:s(`previous`),onClick:e=>{e.stopPropagation(),x(F-1)},children:(0,$.jsx)(c,{})}),(0,$.jsx)(`span`,{className:`question-progress`,children:`${F+1} / ${P}`}),(0,$.jsx)(`button`,{type:`button`,className:`question-step-arrow`,disabled:F>=P-1,title:s(`next`),onClick:e=>{e.stopPropagation(),x(F+1)},children:(0,$.jsx)(St,{})})]}),o&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:e=>{e.stopPropagation(),o()},children:s(`questionQueueNavigate`)}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-toggle-collapse`,title:s(h?`expandSection`:`collapseSection`),onClick:e=>{e.stopPropagation(),g(e=>!e)},children:h?(0,$.jsx)(a,{}):(0,$.jsx)(D,{})}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:s(i?`questionQueueDefer`:q?`modelQuestionRejectWithNoteTip`:`cancel`),onClick:e=>{e.stopPropagation(),i?i():M(q?te:void 0)},children:`✕`})]})]}),!h&&J&&(0,$.jsxs)(`div`,{className:`question-meta-row`,children:[r&&(0,$.jsx)(`span`,{className:`question-conv-title`,children:r}),u&&(0,$.jsx)(`span`,{className:`question-conv-title`,title:u,children:u}),k&&(0,$.jsx)(`span`,{className:`question-timer`,title:`connection lost`,children:s(`questionQueuedOffline`)}),S>=0?(0,$.jsx)(`span`,{className:`question-timer`,children:S>0?s(`questionTimeout`,{s:S}):s(`questionTimeoutExpired`)}):re?(0,$.jsxs)(`span`,{className:`question-timer question-queue-wait`,children:[`⏱ `,re]}):null]})]}),!h&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`set-section`,children:(0,$.jsx)(`div`,{className:`set-list`,children:L.map((e,t)=>{let n=(d[I.id]??[]).includes(e.label),r=t<9?t+1:void 0;return(0,$.jsx)(qC,{label:e.label,description:e.description,preview:e.preview,multiSelect:!!I.multiSelect,active:n,keyNumber:r,onPick:()=>H(I.id,e.label,!!I.multiSelect)},e.label)})})},I.id),(0,$.jsxs)(`div`,{className:`dialog-nav question-sub-bar`,children:[(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss-inline${q?` reject-note`:``}`,onClick:()=>{let e=q?te:void 0;j.trim()&&X4(),M(e)},title:s(q?`modelQuestionRejectWithNoteTip`:`cancel`),children:s(q?`modelQuestionRejectWithNote`:`cancel`)}),(0,$.jsxs)(`label`,{className:`question-auto-submit`,children:[(0,$.jsx)(`input`,{type:`checkbox`,checked:_,onChange:e=>{let t=e.target.checked;v(t);try{localStorage.setItem(`pi-web:question-auto-submit-last`,t?`1`:`0`)}catch{}}}),(0,$.jsx)(`span`,{children:s(`questionAutoSubmitLast`)}),_&&F===P-1&&!I.multiSelect&&L.length>0&&(0,$.jsx)(`span`,{className:`question-auto-submit-hint`,children:s(`questionPickSubmits`)})]}),(0,$.jsxs)(`div`,{className:`question-other-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`question-skip`,onClick:z,children:s(`skip`)}),(0,$.jsxs)(`button`,{type:`button`,className:`dialog-submit`,disabled:!U(I.id),onClick:ee,children:[(0,$.jsx)(`span`,{children:F===P-1?s(`modelQuestionSubmitShort`):s(`next`)}),(0,$.jsx)(w,{className:`question-submit-enter`,"aria-hidden":`true`})]})]})]})]})]})}function qC({label:e,description:t,preview:n,multiSelect:r,active:i,keyNumber:a,onPick:o}){let s=X();return(0,$.jsxs)(`button`,{type:`button`,className:`set-row question-option${i?` active`:``}`,onClick:o,children:[a!==void 0&&(0,$.jsx)(`span`,{className:`question-key-badge`,title:s(`keyShortcutTip`,{key:a}),children:a}),(0,$.jsxs)(`div`,{className:`question-option-body`,children:[(0,$.jsx)(`div`,{className:`set-row-name`,children:(0,$.jsx)(nl,{text:e,rawHtml:!0})}),t&&(0,$.jsx)(`div`,{className:`set-row-desc`,children:t})]}),i&&n&&(0,$.jsx)(`div`,{className:`question-preview`,children:(0,$.jsx)(`div`,{className:`question-preview-body`,children:(0,$.jsx)(nl,{text:n,rawHtml:!0})})}),r&&(0,$.jsx)(`span`,{className:`question-select-mark${i?` active`:``}`,"aria-hidden":`true`,children:i?(0,$.jsx)(z,{}):null})]})}function JC({items:e,itemKey:t,title:n,summary:r,canAutoOpen:i,createdAt:a,onNavigate:o,canNavigate:s,children:c}){let l=X(),[u,d]=(0,Q.useState)(()=>new Set),[f,p]=(0,Q.useState)(null),[m,h]=(0,Q.useState)(Date.now),g=yv(e,t,f,u,i),_=g?t(g):null;(0,Q.useEffect)(()=>{p(_)},[_]);let v=e.some(e=>a(e)>0);if((0,Q.useEffect)(()=>{if(!v)return;h(Date.now());let e=setInterval(()=>h(Date.now()),1e3);return()=>clearInterval(e)},[v]),!e.length)return null;let y=e.filter(e=>e!==g);return(0,$.jsxs)(`section`,{className:`question-queue`,"aria-label":n,children:[y.length>0&&(0,$.jsxs)(`div`,{className:`question-queue-list`,children:[(0,$.jsxs)(`div`,{children:[n,` · `,e.length]}),y.map(e=>(0,$.jsxs)(`div`,{className:`question-queue-item`,children:[(0,$.jsx)(`div`,{className:`question-queue-summary`,children:r(e)}),NC(a(e),m)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,children:[`⏱ `,NC(a(e),m)]}),(0,$.jsxs)(`div`,{className:`question-queue-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>p(t(e)),children:l(`questionQueueOpen`)}),o&&s?.(e)&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>o(e),children:l(`questionQueueNavigate`)})]})]},t(e)))]}),g&&(0,$.jsx)(`div`,{className:`question-queue-dialog`,children:c(g,()=>{d(e=>new Set(e).add(t(g))),p(null)})},_)]})}function YC({questions:e,activeConversationId:t,currentCwd:n,mode:r}){let i=X(),a=e=>LC(e,n),o=e=>{let t=MC(e);t&&Z(t)},s=e=>!!(e.rootConversationId||e.conversationId)&&(!!e.owner||(e.conversationId?e.conversationId!==t:!RC(e,t)));return(0,$.jsx)(JC,{items:bv(e.filter(e=>e.audience===`user`),t,r),itemKey:IC,title:i(`questionQueueTitle`),summary:e=>(0,$.jsxs)($.Fragment,{children:[a(e)&&(0,$.jsx)(`span`,{className:`question-conv-title`,children:a(e)}),e.conversationTitle&&(0,$.jsxs)(`strong`,{children:[e.conversationTitle,` · `]}),e.questions[0]?.question||i(`modelQuestion`)]}),createdAt:e=>e.createdAt,canAutoOpen:e=>r!==`manual`&&(e.global||r===`all`||e.conversationId===t||!e.conversationId),onNavigate:o,canNavigate:s,children:(e,t)=>{let n=s(e)||a(e)?e:{...e,conversationTitle:void 0};return(0,$.jsx)(KC,{question:n,owner:e.owner,project:a(e),onDefer:t,onNavigate:s(e)?()=>o(e):void 0},IC(e))}})}function XC(e){let t=X(),[n,r]=(0,Q.useState)(),[i,a]=(0,Q.useState)(``),[o,s]=(0,Q.useState)(0);return(0,Q.useEffect)(()=>{let n=new AbortController;return r(void 0),a(``),Vd(e.id,e.hubUrl,!0,t,e.mode===`preview`,n.signal,e.local).then(e=>{n.signal.aborted||r(e)}).catch(e=>{n.signal.aborted||a(e instanceof Error?e.message:String(e))}),()=>n.abort()},[e.revision,e.mode,e.id,e.hubUrl,e.local,o,t]),{target:n,error:i,retry:()=>s(e=>e+1)}}var ZC=[`--bg`,`--bg-elev`,`--bg-elev2`,`--border`,`--text`,`--text-dim`,`--accent`,`--accent-contrast`,`--green`,`--red`];function QC(e,t,n=!1){(0,Q.useEffect)(()=>{let r=()=>{let t=getComputedStyle(document.documentElement),n=Object.fromEntries(ZC.map(e=>[e,t.getPropertyValue(e).trim()]));e.current?.contentWindow?.postMessage({type:`desktop-theme`,theme:n,scheme:t.colorScheme},`*`)},i=i=>{i.source===e.current?.contentWindow&&i.origin===(n&&t?new URL(t).origin:`null`)&&i.data?.type===`desktop-theme-request`&&r()};return window.addEventListener(`message`,i),window.addEventListener(yr,r),r(),()=>{window.removeEventListener(`message`,i),window.removeEventListener(yr,r)}},[e,t,n])}function $C(e){let t=`pi-web-ui:desktop-preferences:`+encodeURIComponent(e);function n(e){if(!e||typeof e!=`object`||Array.isArray(e))return{};let t=e,n={};[`auto`,`smooth`,`balanced`,`sharp`].includes(t.quality)&&(n.quality=t.quality),[0,960,1280,1920,2560].includes(t.edge)&&(n.edge=t.edge),[0,10,15,30,60,120,240].includes(t.fps)&&(n.fps=t.fps),([`window`,`native`,`custom`].includes(t.resolution??``)||typeof t.resolution==`string`&&/^\d{3,4}x\d{3,4}$/.test(t.resolution)&&t.resolution.split(`x`).every(e=>Number(e)>=320&&Number(e)<=4096))&&(n.resolution=t.resolution);for(let e of[`width`,`height`])Number.isInteger(t[e])&&t[e]>=320&&t[e]<=4096&&(n[e]=t[e]);return[`limited`,`full`].includes(t.colorRange??``)&&(n.colorRange=t.colorRange),typeof t.diagnostics==`boolean`&&(n.diagnostics=t.diagnostics),typeof t.mapShortcuts==`boolean`&&(n.mapShortcuts=t.mapShortcuts),(t.cursor===`local`||t.cursor===`remote`)&&(n.cursor=t.cursor),typeof t.scale==`boolean`&&(n.scale=t.scale),typeof t.viewOnly==`boolean`&&(n.viewOnly=t.viewOnly),[`off`,`send`,`receive`,`both`].includes(t.clipboard)&&(n.clipboard=t.clipboard),n}let r={};function i(){try{return n(JSON.parse(localStorage.getItem(t)??`{}`))}catch{return r}}return{clean:n,read:i,write(e){let a={...i(),...n(e)};r=a;try{localStorage.setItem(t,JSON.stringify(a))}catch{}return a}}}function ew(e,t,n,r=!1){(0,Q.useEffect)(()=>{let i=$C(JSON.stringify([t.hubUrl,t.id])),a=a=>{let o=a.data;if(o&&[`desktop-preferences-read`,`desktop-preferences-write`,`desktop-preferences-value`].includes(o.type)){if(Ad()&&a.source===parent&&parent!==window&&o.type===`desktop-preferences-value`&&o.target===t.id)e.current?.contentWindow?.postMessage(o,`*`);else if(a.source===e.current?.contentWindow&&a.origin===(r&&n?new URL(n).origin:`null`)&&o.type!==`desktop-preferences-value`){if(Ad()&&parent!==window)parent.postMessage({...o,target:t.id},`*`);else if(o.type===`desktop-preferences-write`){let e=i.clean(o.value);delete e.clipboard,i.write(e)}else e.current?.contentWindow?.postMessage({type:`desktop-preferences-value`,value:i.read()},`*`)}}};return window.addEventListener(`message`,a),()=>window.removeEventListener(`message`,a)},[e,t.id,t.hubUrl,n,r])}function tw(e){let t,n=``,r=`off`,i=!1,a=!1,o,s,c,l=!1,u=e=>{!l&&t&&(l=!0,t.send(JSON.stringify({type:`start`,read:r!==`receive`,write:r!==`send`,...e?.streamFiles===!0&&c?.streamFiles===!0?{streamFiles:!0,maxBytes:Math.min(Number(e.maxFileBytes)||33554432,0x400000000)}:{}})))},d=t=>t.type===`clipboard-preparing`||t.type===`clipboard-idle`?(e.state(t.type===`clipboard-preparing`?`clipboard-preparing`:`clipboard-ready`),!0):t.type===`clipboard-error`?(t.recoverable===!0?e.state(`warning:`+String(t.code)):m(String(t.code)),!0):t.type===`clipboard-progress`?(Number.isSafeInteger(t.bytes)&&Number.isSafeInteger(t.total)&&Number(t.bytes)>=0&&Number(t.bytes)<=Number(t.total)&&e.state(`clipboard-progress:${t.direction===`send`?`send`:`receive`}:${t.bytes}:${t.total}`),!0):t.type===`clipboard-complete`&&(e.state(`clipboard-complete`),!0),f=t=>e.post({type:`desktop-clipboard`,channel:n,payload:t}),p=()=>{n&&f({type:`bridge-stop`}),n=``,r=`off`,i=a=!1,s=void 0,c=void 0,l=!1,clearTimeout(o),t&&=(t.onmessage=t.onerror=t.onclose=null,t.close(),void 0)},m=t=>{p(),e.state(t)};return{receive(c){if(!c||typeof c!=`object`)return;let l=c;if(l.type!==`desktop-clipboard`||!n||l.channel!==n)return;let p=l.payload;if(!p||typeof p!=`object`||d(p))return;if(p.type===`clipboard-capabilities`){u(p);return}if(p.type===`clipboard-stopped`){m(`clipboard-stopped`);return}if(p.type===`clipboard-ready`){i=!0,u(),a&&(clearTimeout(o),e.state(`clipboard-ready`)),s&&=(f(s),void 0);return}if(!i||!a||t?.readyState!==1||![`offer`,`chunk`,`commit`,`ack`,`abort`].includes(String(p.type)))return;if(p.type!==`abort`&&(p.type===`ack`&&r===`receive`||p.type!==`ack`&&r===`send`))return m(`clipboard-direction`);let h=JSON.stringify(p);if(h.length>49152||t.bufferedAmount>1671168)return m(`clipboard-size`);t.send(h)},set(l){if(p(),l===`off`){e.state(`clipboard-off`);return}r=l,n=e.id(),e.state(`clipboard-connecting`);let u;try{u=e.open()}catch{m(`clipboard-unavailable`);return}t=u,o=setTimeout(()=>m(`clipboard-timeout`),15e3),u.onmessage=n=>{if(!(u!==t||typeof n.data!=`string`||n.data.length>49152))try{let t=JSON.parse(n.data);if(d(t))return;if(t.type===`clipboard-capabilities`){c=t,f({type:`bridge-start`,mode:r,capabilities:{streamFiles:t.streamFiles===!0,maxFileBytes:t.maxFileBytes}});return}if(t.type===`clipboard-ready`){a=!0,i&&(clearTimeout(o),e.state(`clipboard-ready`));return}[`offer`,`chunk`,`commit`,`ack`,`abort`].includes(t.type)&&(i?f(t):s?m(`clipboard-protocol`):s=t)}catch{m(`clipboard-protocol`)}},u.onclose=u.onerror=()=>{u===t&&m(`clipboard-unavailable`)}},close:p}}function nw(e){let t=tw({open:()=>new WebSocket(e.localUrl),id:()=>crypto.randomUUID(),post:t=>e.frame()?.postMessage(t,`*`),state:e.state}),n=n=>{n.source===e.frame()&&n.origin===e.origin&&t.receive(n.data)};return window.addEventListener(`message`,n),{set:t.set,close(){t.close(),window.removeEventListener(`message`,n)}}}function rw(e){let t=Reflect.get(globalThis,`document`),n=Reflect.get(globalThis,`navigator`),{host:r,post:i,zh:a}=e,o=t.createElement(`details`);o.className=`browser-clipboard`,o.hidden=!e.alwaysVisible;let s=t.createElement(`summary`);s.textContent=a?`剪贴板 · 浏览器文本传递`:`Clipboard · browser text transfer`;let c=t.createElement(`textarea`);c.setAttribute(`aria-label`,a?`剪贴板文本`:`Clipboard text`),c.placeholder=a?`在这里粘贴文本,再发送到远程剪贴板`:`Paste text here, then send to the remote clipboard`,c.maxLength=16384;let l=t.createElement(`div`),u=t.createElement(`p`),d=t.createElement(`span`);d.setAttribute(`role`,`status`),u.textContent=a?`浏览器模式需手动发送/接收文本(最多 16 KiB)。文本、图片、文件自动同步请从本机 localhost 的 pi-web-ui 打开设备。`:`Manually send/receive text (up to 16 KiB). For automatic text, image and file sync, open the device from your local pi-web-ui.`;let f=(e,n)=>{let r=t.createElement(`button`);return r.type=`button`,r.textContent=e,r.onclick=n,l.append(r),r},p=``,m=!1,h=!1,g=!0,_,v,y=e=>i({type:`desktop-clipboard`,channel:p,payload:e}),b=()=>{w.disabled=m||!h||g,T.disabled=m||!h},x=()=>{clearTimeout(v),p&&y({type:`bridge-stop`}),p=``,m=!1,_=void 0,b()},S=()=>{x(),d.textContent=a?`传递失败,请检查连接并更新被控端。`:`Transfer failed. Check the connection and update the remote device.`},C=e=>{!m&&h&&(JSON.stringify(e).length>48e3?d.textContent=a?`文本编码后超过传递限制。`:`Encoded text exceeds the transfer limit.`:(x(),m=!0,b(),_=e,p=`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(Number(e)^crypto.getRandomValues(new Uint8Array(1))[0]&15>>Number(e)/4).toString(16)),d.textContent=a?`正在传递…`:`Transferring…`,y({type:`bridge-text-start`,mode:g?`receive`:`both`}),v=setTimeout(S,15e3)))},w=f(a?`发送到远程`:`Send to remote`,()=>{new TextEncoder().encode(c.value).length>16384?d.textContent=a?`文本超过 16 KiB。`:`Text exceeds 16 KiB.`:C({type:`text-write`,text:c.value})}),T=f(a?`读取远程文本`:`Read remote text`,()=>C({type:`text-read`}));return f(a?`复制到本机`:`Copy locally`,()=>{c.focus(),c.select(),n.clipboard?.writeText?n.clipboard.writeText(c.value).then(()=>{d.textContent=a?`已复制到本机。`:`Copied locally.`}).catch(()=>{d.textContent=a?`请按 Ctrl/Cmd+C 复制选中的文本。`:`Press Ctrl/Cmd+C to copy the selected text.`}):d.textContent=a?`请按 Ctrl/Cmd+C 复制选中的文本。`:`Press Ctrl/Cmd+C to copy the selected text.`}),o.append(s,c,l,d,u),r.append(o),b(),o.addEventListener(`toggle`,()=>{o.open||x()}),{cancel:x,open(){o.hidden=!1,o.open=!0,h||(d.textContent=a?`桌面尚未连接,请先连接远程桌面。`:`Connect the remote desktop first.`),c.focus()},receive(t){if(t?.type===`desktop-clipboard-available`){h=t.connected===!0,g=t.viewOnly!==!1,o.hidden=!h&&!e.alwaysVisible,h||(x(),c.value=``,d.textContent=``),b();return}if(t?.type!==`desktop-clipboard`||!p||t.channel!==p)return;let n=t.payload;if(n?.type===`clipboard-ready`&&_){let e=_;_=void 0,y(e)}else n?.type===`text-result`?(typeof n.text==`string`&&new TextEncoder().encode(n.text).length<=16384&&(c.value=n.text),x(),d.textContent=n.error?a?`当前内容不是文本、超过限制或无法读取。图片和文件请使用本机客户端同步。`:`Not text, too large, or unavailable. Use the local client for images and files.`:n.written?a?`已写入远程剪贴板,可在远程粘贴。`:`Written to remote clipboard. Paste on the remote computer.`:a?`已读取,可选中复制或点击复制到本机。`:`Received. Select and copy, or click Copy locally.`):(n?.type===`clipboard-error`||n?.type===`clipboard-stopped`)&&S()},close(){x(),o.remove()}}}var iw=`.browser-clipboard{flex:none;padding:6px 10px;background:var(--bg-elev,#17181c);color:var(--text,#eee);font:12px system-ui;max-height:38vh;overflow:auto}.browser-clipboard[hidden]{display:none}.browser-clipboard summary{cursor:pointer}.browser-clipboard textarea{box-sizing:border-box;display:block;width:100%;height:70px;margin:8px 0;background:var(--bg,#17181c);color:inherit;border:1px solid var(--border,#555);border-radius:6px;resize:vertical}.browser-clipboard button{margin:0 6px 6px 0;padding:5px 8px;font:inherit;background:var(--bg,#303137);color:inherit;border:1px solid var(--border,#555);border-radius:6px}.browser-clipboard p{margin:6px 0;max-width:none;overflow-wrap:anywhere}.browser-clipboard button:disabled{opacity:.5}`;function aw(e,t){let n=Reflect.get(globalThis,`document`),r=n.createElement(`dialog`);r.className=`desktop-clipboard-dialog`,r.setAttribute(`aria-label`,e?`剪贴板`:`Clipboard`);let i=n.createElement(`header`),a=n.createElement(`strong`),o=n.createElement(`button`);a.textContent=e?`剪贴板`:`Clipboard`,o.type=`button`,o.textContent=e?`关闭`:`Close`,o.onclick=()=>r.close(),r.addEventListener(`close`,()=>t?.()),i.append(a,o);let s=n.createElement(`div`);return r.append(i,s),n.body.append(r),{host:s,open(){r.open||r.showModal()},hide(){r.close()},remove(){r.remove()}}}var ow=`.desktop-clipboard-dialog{box-sizing:border-box;width:min(560px,calc(100vw - 24px));max-width:100%;max-height:calc(100dvh - 24px);padding:16px;border:1px solid var(--border,#555);border-radius:12px;background:var(--bg-elev,#17181c);color:var(--text,#eee);font:13px system-ui;overflow:auto;overscroll-behavior:contain;box-shadow:0 12px 40px #0005}.desktop-clipboard-dialog::backdrop{background:#0006}.desktop-clipboard-dialog>header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:10px}.desktop-clipboard-dialog button{font:inherit;color:inherit;background:var(--bg-elev2,#303137);border:1px solid var(--border,#555);border-radius:6px;padding:5px 10px;cursor:pointer}.desktop-clipboard-dialog .browser-clipboard{max-height:none;padding:0}.desktop-clipboard-dialog .browser-clipboard textarea{height:130px;max-height:40vh}.desktop-clipboard-dialog #clipboard-bar{flex-wrap:wrap;padding:0}.desktop-clipboard-dialog p{color:var(--text-dim,#aaa)}`;function sw(e,t){if(e===`clipboard-preparing`)return t?`正在读取并校验本次复制的内容;完成前请勿粘贴,剪贴板仍可能是旧文件。`:`Reading and checking this copy. Wait before pasting; the clipboard may still contain old files.`;if(e===`clipboard-complete`)return t?`本次复制已同步完成,可以粘贴。`:`This copy has finished syncing. Ready to paste.`;if(e.startsWith(`clipboard-progress:`)){let[,,n,r]=e.split(`:`),i=Number(n),a=Number(r);if(!Number.isFinite(i)||!Number.isFinite(a)||a<=0)return;let o=e=>e>=0x40000000?(e/0x40000000).toFixed(2)+` GiB`:(e/1048576).toFixed(1)+` MiB`;return`${t?`正在传输`:`Transferring`} ${o(i)} / ${o(a)} · ${Math.floor(i/a*100)}%`}if(e.startsWith(`warning:`))return({"clipboard-folder":[`文件夹没有同步,剪贴板仍是原来的内容。请点击“文件传输”选择文件夹发送。`,`Folder not synced; the previous clipboard is unchanged. Use File transfer → Send folder.`],"clipboard-size":[`本次内容超出对端支持的大小。大文件需要两端都更新;同步方向已保留,请重新复制。`,`Content exceeds the peer's limit. Update both endpoints for large files. Direction is retained; copy again.`],"clipboard-space":[`接收端磁盘空间或临时文件配额不足。清理空间后重新复制;同步仍开启。`,`The receiver has insufficient disk space or temporary quota. Free space and copy again; sync remains enabled.`],"clipboard-changed":[`文件在传输时发生变化。请等待文件写入完成后重新复制;同步仍开启。`,`The source file changed. Wait until writing finishes, then copy again; sync remains enabled.`],"clipboard-timeout":[`本次传输超时,请检查连接后重新复制;同步方向已保留。`,`This transfer timed out. Check the connection and copy again; direction is retained.`]}[e.slice(8)]??[`本次复制失败,剪贴板仍是原来的内容。请重新复制,或使用“文件传输”;同步仍开启。`,`This copy failed; the previous clipboard is unchanged. Copy again or use File transfer; sync remains enabled.`])[+!t]}function cw({frame:e,url:t,local:n,scope:r}){let i=X(),a=Ye(_e().locale),[o,s]=(0,Q.useState)(`off`),[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(!0),[f,p]=(0,Q.useState)(`clipboard-off`),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(null),v=(0,Q.useRef)(void 0),y=(0,Q.useRef)(void 0),b=(0,Q.useRef)(null),x=!!Ad(),S=!x&&[`localhost`,`127.0.0.1`,`[::1]`].includes(location.hostname)&&!n;if((0,Q.useEffect)(()=>{let i=$C(r),o=!1,c=!0,u=n&&t?new URL(t).origin:`null`;l(!1),s(i.read().clipboard??`off`),p(`clipboard-off`),h(!1);let f=x?void 0:aw(a,()=>m?.cancel());v.current=f,_(f?.host??null);let m=f&&!S?rw({host:f.host,post:t=>e.current?.contentWindow?.postMessage(t,`*`),zh:a,alwaysVisible:!0}):void 0,g=t=>{if(x&&t.source===parent&&parent!==window&&[`desktop-clipboard`,`desktop-clipboard-status`].includes(t.data?.type))e.current?.contentWindow?.postMessage(t.data,`*`);else if(t.source===e.current?.contentWindow&&t.origin===u){if(x&&[`desktop-clipboard`,`desktop-clipboard-available`,`desktop-clipboard-show`].includes(t.data?.type))parent.postMessage(t.data,`*`);else if(t.data?.type===`desktop-clipboard-show`)f?.open(),m?.open(),b.current?.focus();else if(m?.receive(t.data),t.data?.type===`desktop-clipboard-available`){if(h(t.data.toolbar===!0),l(t.data.connected===!0),d(t.data.viewOnly!==!1),!t.data.connected)f?.hide(),y.current?.set(`off`),o=!1;else if(!o||c!==(t.data.viewOnly!==!1)){let e=i.read().clipboard??`off`,n=t.data.viewOnly===!1?e:e===`both`?`receive`:e===`send`?`off`:e;s(n),y.current?.set(n),o=!0}c=t.data.viewOnly!==!1}}};return window.addEventListener(`message`,g),S&&(y.current=nw({frame:()=>e.current?.contentWindow??null,origin:u,localUrl:W(P(`/api/device-desktop/local/clipboard-ws`)),state:t=>{p(t),e.current?.contentWindow?.postMessage({type:`desktop-clipboard-status`,code:t},`*`)}})),()=>{window.removeEventListener(`message`,g),y.current?.close(),m?.close(),f?.remove(),v.current=void 0,y.current=void 0,x&&parent.postMessage({type:`desktop-clipboard-available`,connected:!1,viewOnly:!0},`*`)}},[e,t,n,x,S,a,r]),x)return null;let C=i(`desktop.clipboard`),w=S?f===`clipboard-ready`?i(`desktop.clipboardReady`):f===`clipboard-connecting`?i(`desktop.connecting`):f===`clipboard-off`?i(`desktop.clipboardHint`):sw(f,a)??i(`desktopClipboardUnavailable`):i(`desktop.clipboardLocal`);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`style`,{children:iw+ow}),c&&!m&&(0,$.jsx)(`button`,{className:`btn desktop-clipboard-launcher`,type:`button`,"aria-haspopup":`dialog`,onClick:()=>v.current?.open(),children:C}),S&&g&&(0,Er.createPortal)((0,$.jsxs)(`label`,{className:`desktop-clipboard-control`,title:w,children:[(0,$.jsx)(`span`,{children:C}),(0,$.jsxs)(`select`,{ref:b,"aria-label":C,value:o,disabled:!S||!c,onChange:e=>{let t=e.target.value;s(t),$C(r).write({clipboard:t}),y.current?.set(t)},children:[(0,$.jsx)(`option`,{value:`off`,children:i(`desktop.clipboardOff`)}),(0,$.jsx)(`option`,{value:`send`,disabled:u,children:i(`desktop.clipboardSend`)}),(0,$.jsx)(`option`,{value:`receive`,children:i(`desktop.clipboardReceive`)}),(0,$.jsx)(`option`,{value:`both`,disabled:u,children:i(`desktop.clipboardBoth`)})]}),![`clipboard-off`,`clipboard-ready`].includes(f)&&(0,$.jsx)(`span`,{role:`status`,children:w}),c&&o!==`off`&&f.startsWith(`clipboard-`)&&![`clipboard-off`,`clipboard-ready`,`clipboard-connecting`].includes(f)&&!f.startsWith(`clipboard-progress:`)&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>y.current?.set(o),children:i(`retryNow`)})]}),g)]})}function lw(e){let t=Reflect.get(globalThis,`document`),n=Reflect.get(globalThis,`window`),r=(n.navigator.language||`en`).startsWith(`zh`),i=(e,t)=>r?e:t,a=(e,n=``,r=``)=>{let i=t.createElement(e);return i.textContent=n,i.className=r,i},o=e=>e<1024?e+` B`:e<1024**2?(e/1024).toFixed(1)+` KB`:e<1024**3?(e/1024**2).toFixed(1)+` MB`:(e/1024**3).toFixed(2)+` GB`,s=()=>Array.from(n.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``),c=a(`style`);c.nonce=t.querySelector(`script[nonce]`)?.nonce||``,c.textContent=`
|
|
406
|
-
.pi-files{--fm-bg:var(--bg-elev,var(--bg,#171c23));--fm-line:var(--border,#46505d);box-sizing:border-box;color:var(--text,#e6edf3);background:var(--fm-bg);border:1px solid var(--fm-line);border-radius:12px;width:min(1120px,96vw);height:min(760px,91dvh);max-height:94dvh;padding:0;font:13px system-ui;overflow:hidden;box-shadow:0 20px 70px #0005}
|
|
407
|
-
.pi-files::backdrop{background:#0005}.pi-files *{box-sizing:border-box}.pi-files .fm-shell{height:100%;display:flex;flex-direction:column;min-width:0}.pi-files button,.pi-files input,.pi-files select{font:inherit;color:inherit;background:var(--bg,#171c23);border:1px solid var(--fm-line);border-radius:6px;padding:6px 9px;min-width:0;max-width:100%;line-height:1.4}.pi-files button{cursor:pointer;white-space:nowrap;display:inline-flex;align-items:center;justify-content:center;gap:5px}.pi-files button:disabled{opacity:.45;cursor:default}.pi-files button:hover:not(:disabled){border-color:var(--accent,#8ab4f8)}.pi-files button:focus-visible,.pi-files input:focus-visible,.pi-files select:focus-visible{outline:2px solid var(--accent,#8ab4f8);outline-offset:2px}.pi-files input[type=checkbox]{width:14px;height:14px;accent-color:var(--accent,#8ab4f8)}.pi-files .fm-head{display:flex;justify-content:space-between;align-items:center;padding:14px 18px;border-bottom:1px solid var(--fm-line)}.pi-files .fm-head strong{font-size:16px}.pi-files .fm-muted{color:var(--text-dim,var(--text,#b3bac5));font-size:12px}.pi-files .fm-panes{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:16px;padding:16px 18px 10px;min-height:180px;flex:1.4;overflow:hidden}.pi-files .fm-pane{min-width:0;display:flex;flex-direction:column;overflow:hidden}.pi-files .fm-device{display:flex;align-items:center;gap:8px;margin-bottom:10px;min-width:0}.pi-files .fm-device strong{font-size:15px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pi-files .fm-badge{font-size:11px;padding:2px 6px;border:1px solid var(--fm-line);border-radius:4px;flex:none}.pi-files .fm-device button{margin-left:auto}.pi-files .fm-nav{display:flex;gap:5px;margin-bottom:6px;min-width:0}.pi-files .fm-path{flex:1;width:0}.pi-files .fm-roots{width:100%;margin-bottom:6px}.pi-files .fm-grid{overflow:auto;min-height:80px;border:1px solid var(--fm-line);border-radius:7px;flex:1;overscroll-behavior:contain}.pi-files table{color:inherit;width:100%;border-collapse:collapse;text-align:left;font-size:12px;table-layout:fixed}.pi-files .fm-sort{width:100%;justify-content:flex-start;padding:2px 0;border:0;background:transparent;color:inherit}.pi-files [aria-sort=ascending] .fm-sort::after{content:"↑"}.pi-files [aria-sort=descending] .fm-sort::after{content:"↓"}.pi-files th{font-weight:500;color:var(--text-dim,var(--text,#b3bac5));position:sticky;top:0;background:var(--fm-bg);z-index:1}.pi-files td,.pi-files th{padding:7px 8px;border-bottom:1px solid var(--fm-line);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.pi-files th:first-child,.pi-files td:first-child{width:30px}.pi-files .fm-name{width:43%}.pi-files .fm-date{width:27%}.pi-files tr[aria-selected=true]{background:color-mix(in srgb,var(--accent,#8ab4f8) 15%,transparent)}.pi-files tbody tr:hover{background:color-mix(in srgb,var(--accent,#8ab4f8) 9%,transparent)}.pi-files .fm-empty{text-align:center;padding:24px;white-space:normal;color:var(--text-dim,var(--text,#b3bac5))}.pi-files .fm-foot{padding:7px 2px;font-size:12px;min-height:30px;overflow-wrap:anywhere;word-break:break-word}.pi-files .fm-actions{display:flex;gap:8px;flex-wrap:wrap}.pi-files .fm-queue{display:flex;flex-direction:column;min-height:140px;flex:1;padding:4px 18px 16px;overflow:hidden}.pi-files .fm-queue-head{display:flex;align-items:center;justify-content:space-between;gap:8px;margin:4px 0 8px;flex-wrap:wrap}.pi-files .fm-tasks th:first-child,.pi-files .fm-tasks td:first-child{width:19%}.pi-files .fm-tasks th:nth-child(2){width:24%}.pi-files .fm-tasks th:nth-child(3){width:10%}.pi-files .fm-tasks th:last-child{width:16%}.pi-files .fm-tasks td{white-space:normal;overflow-wrap:anywhere;word-break:break-word;vertical-align:top}.pi-files progress{display:block;width:100%;height:5px;margin-top:7px;accent-color:var(--accent,#8ab4f8)}.pi-files .fm-note{padding:0 18px 8px;overflow-wrap:anywhere;word-break:break-word;min-height:22px}.pi-files .fm-note[role=alert]{color:var(--red,#ff9a9a)}.pi-files .fm-task-actions{display:flex;gap:4px;flex-wrap:wrap}.pi-files .fm-task-actions button{font-size:11px;padding:3px 6px}.pi-files [hidden]{display:none!important}@media(max-width:700px){.pi-files .fm-panes{gap:8px;padding:10px;}.pi-files .fm-pane table{min-width:320px}.pi-files .fm-nav{flex-wrap:wrap}.pi-files .fm-path{flex-basis:100%;width:100%;order:2}.pi-files .fm-device{flex-wrap:wrap}.pi-files .fm-device strong{max-width:100%;font-size:12px}.pi-files .fm-queue{padding:4px 10px 10px}.pi-files .fm-tasks th:nth-child(4),.pi-files .fm-tasks td:nth-child(4),.pi-files .fm-tasks th:nth-child(5),.pi-files .fm-tasks td:nth-child(5){display:none}.pi-files .fm-tasks th:last-child{width:24%}.pi-files .fm-device button{margin-left:0}}
|
|
408
|
-
`,t.head.append(c);let l=a(`dialog`,``,`pi-files`);l.id=`file-transfer-dialog`;let u=a(`div`,``,`fm-shell`),d=a(`div`,``,`fm-head`),f=a(`button`,i(`收起`,`Hide`));d.append(a(`strong`,i(`文件传输`,`File transfer`)),f),f.onclick=()=>l.close();let p=a(`div`,``,`fm-panes`),m=a(`div`,``,`fm-note fm-muted`),h=a(`div`,``,`fm-queue`),g=a(`div`,``,`fm-queue-head`),_=a(`div`,``,`fm-actions`);g.append(a(`strong`,i(`传输列表`,`Transfers`)),_);let v=a(`div`,``,`fm-grid`),y=a(`table`,``,`fm-tasks`),b=a(`tbody`),x=a(`tr`);for(let e of[i(`名称 / 方向`,`Name / direction`),i(`状态 / 进度`,`Status / progress`),i(`大小`,`Size`),i(`发送路径`,`Source`),i(`接收路径`,`Destination`),i(`操作`,`Actions`)])x.append(a(`th`,e));let S=a(`thead`);S.append(x),y.append(S,b),v.append(y),h.append(g,v),u.append(d,p,m,h),l.append(u),t.body.append(l);let C=e.local?void 0:e.browser(),w=!1,T=!1,E=!1,D=[],O=(e,t=!1)=>{m.textContent=e,m.setAttribute(`role`,t?`alert`:`status`)},k=i(`双击文件夹打开;选中文件后按箭头传输。同名文件自动重命名,保留两份。`,`Double-click folders to open. Select files, then send. Existing files are kept; duplicates are renamed.`);O(k);let A=[],j=new Intl.Collator(n.navigator.language,{numeric:!0});function M(e,r){let s=a(`section`,``,`fm-pane`),c=a(`div`,``,`fm-device`),u=a(`strong`,e?i(`远程设备`,`Remote device`):i(`我的设备`,`My device`)),d=a(`button`,e?i(`← 接收`,`← Receive`):i(`发送 →`,`Send →`)),f=a(`span`,e?i(`远程`,`Remote`):i(`本机`,`Local`),`fm-badge`);c.append(u,f,d);let m=a(`div`,``,`fm-nav`),h=a(`button`,`←`),g=a(`button`,`↑`),_=a(`button`,`↻`),v=a(`button`,`+`),y=a(`input`,``,`fm-path`),b=a(`select`,``,`fm-roots`),x=a(`div`,``,`fm-grid`),S=a(`table`),T=a(`thead`),E=a(`tbody`),D=a(`tr`),M=a(`input`),N=a(`th`),P=a(`div`,``,`fm-foot fm-muted`);h.title=i(`后退`,`Back`),g.title=i(`上一级`,`Parent folder`),_.title=i(`刷新`,`Refresh`),v.title=i(`新建文件夹`,`New folder`),y.setAttribute(`aria-label`,e?i(`远程路径`,`Remote path`):i(`本机路径`,`Local path`)),M.type=`checkbox`,M.setAttribute(`aria-label`,i(`全选`,`Select all`)),N.append(M),D.append(N);let I=`name`,L=1,R=new Map;for(let[e,t,n]of[[`name`,i(`名称`,`Name`),`fm-name`],[`modified`,i(`修改日期`,`Modified`),`fm-date`],[`size`,i(`大小`,`Size`),``]]){let r=a(`th`,``,n),i=a(`button`,t,`fm-sort`);r.scope=`col`,R.set(e,r),i.onclick=()=>{L=I===e?-L:e===`name`?1:-1,I=e,V()},r.append(i),D.append(r)}T.append(D),S.append(T,E),x.append(S),m.append(h,g,_,v,y),s.append(c,m,b,x,P),p.append(s);let z={request:r,index:e,path:``,parent:``,entries:[],selected:new Set,history:[],name:``,info:null,revision:0,loading:!1};function B(){let t=e===0&&A[1]?.info?.readOnly===!0;d.disabled=z.loading||!z.selected.size||t,d.title=t?i(`只读模式不能发送文件`,`Sending is disabled in view-only mode`):``,e===1&&(v.disabled=z.info?.readOnly===!0),M.checked=z.entries.length>0&&z.selected.size===z.entries.length,M.indeterminate=z.selected.size>0&&!M.checked,h.disabled=!z.history.length,g.disabled=!z.parent||z.parent===z.path,P.textContent=`${z.entries.length} ${i(`项`,`items`)} · ${i(`已选择`,`Selected`)} ${z.selected.size}`}z.update=B;function V(e){for(let[e,t]of R)e===I?t.setAttribute(`aria-sort`,L===1?`ascending`:`descending`):t.removeAttribute(`aria-sort`);z.entries.sort((e,t)=>{if(e.directory!==t.directory)return e.directory?-1:1;if(I===`name`)return L*j.compare(e.name,t.name);let n=e[I],r=t[I];return n==null==(r==null)?(I===`size`&&e.directory?0:L*((n??0)-(r??0)))||j.compare(e.name,t.name):n==null?1:-1}),E.replaceChildren();for(let t of z.entries){let n=a(`tr`),r=a(`input`),s=a(`td`),c=a(`td`,(t.directory?`📁 `:`▤ `)+t.name),l=a(`td`,t.modified==null?`—`:new Date(t.modified).toLocaleString(),`fm-date`);r.type=`checkbox`,r.checked=z.selected.has(t.path),r.setAttribute(`aria-label`,t.name),n.setAttribute(`aria-selected`,String(r.checked)),s.append(r),c.title=t.name,n.append(s,c,l,a(`td`,t.directory?i(`文件夹`,`Folder`):o(t.size))),r.onchange=()=>{r.checked?z.selected.add(t.path):z.selected.delete(t.path),n.setAttribute(`aria-selected`,String(r.checked)),B()},n.onclick=e=>{e.target!==r&&(r.checked=!r.checked,r.onchange())},n.ondblclick=()=>{t.directory&&z.load(t.path)},E.append(n),t.path===e&&n.scrollIntoView?.({block:`nearest`})}if(!z.entries.length){let e=a(`tr`),t=a(`td`,i(`此文件夹为空`,`This folder is empty`),`fm-empty`);t.colSpan=4,e.append(t),E.append(e)}B()}if(z.load=async(e,t=!0)=>{let n=++z.revision;z.loading=!0,d.disabled=!0;try{let a=e=>r(`list?path=`+encodeURIComponent(e)),o;try{o=await a(e)}catch(t){if(!/\bENOTDIR\b/.test(t.message)||w||n!==z.revision)throw t;let r=/^[A-Za-z]:[\\/]/.test(e)?Math.max(e.lastIndexOf(`\\`),e.lastIndexOf(`/`)):e.lastIndexOf(`/`);if(r<0||r===e.length-1)throw t;let i=await a(e.slice(0,r+1)),s=i.entries.find(t=>!t.directory&&t.name===e.slice(r+1));if(!s)throw t;o={...i,selected:s.path}}if(w||n!==z.revision)return;if(o.selected&&!o.entries.some(e=>e.path===o.selected&&!e.directory))throw Error(i(`文件已移动或不可读。`,`The file was moved or is no longer readable.`));t&&z.path&&z.path!==o.path&&z.history.push(z.path),z.path=o.path,z.parent=o.parent,z.entries=o.entries,z.selected.clear(),o.selected&&z.selected.add(o.selected),y.value=z.path,b.value=z.path,b.selectedIndex<0&&(b.value=``),V(o.selected),t&&O(k),o.truncated&&O(i(`目录只显示前 2000 项,请进入子目录。`,`Only the first 2000 entries are shown; open a subfolder.`))}catch(e){if(w||n!==z.revision)return;O(e.message,!0),y.value=z.path}finally{n===z.revision&&(z.loading=!1,B())}},z.init=async()=>{if(z.info=await r(`info`),e===1&&!n.getComputedStyle(t.documentElement).getPropertyValue(`--bg`).trim())for(let e of[`--bg`,`--bg-elev`,`--border`,`--text`,`--text-dim`,`--accent`,`--red`]){let t=z.info.theme?.[e];typeof t==`string`&&t.length<=128&&n.CSS.supports(`color`,t)&&l.style.setProperty(e,t)}z.name=z.info.device,u.textContent=z.name,u.title=z.name,b.replaceChildren();let o=a(`option`,i(`快速访问…`,`Quick access…`));o.value=``,o.disabled=!0,b.append(o);for(let e of z.info.roots||[]){let t=a(`option`,{Home:i(`主目录`,`Home`),Desktop:i(`桌面`,`Desktop`),Downloads:i(`下载`,`Downloads`),Documents:i(`文档`,`Documents`)}[e.name]||e.name);t.value=e.path,b.append(t)}await z.load(z.info.home,!1);for(let e of A)e.update()},b.onchange=()=>void z.load(b.value),y.onkeydown=e=>{if(e.key!==`Enter`||e.isComposing)return;let t=y.value.replace(/^"(.*)"$/,`$1`),n=/^[A-Za-z]:[\\/]/.test(z.path);t&&!t.startsWith(`/`)&&!(n&&/^(?:[A-Za-z]:|\\)/.test(t))&&(t=z.path+(/[\\/]$/.test(z.path)?``:n?`\\`:`/`)+t),z.selected.size&&(z.selected.clear(),V()),z.load(t||z.info.home)},_.onclick=()=>void z.load(z.path,!1),g.onclick=()=>void z.load(z.parent),h.onclick=()=>void z.load(z.history.pop()||z.path,!1),v.onclick=async()=>{let e=n.prompt(i(`新文件夹名称`,`New folder name`));if(e)try{await r(`mkdir`,`POST`,{path:z.path,name:e}),await z.load(z.path,!1)}catch(e){O(e.message,!0)}},M.onchange=()=>{z.selected=M.checked?new Set(z.entries.map(e=>e.path)):new Set,V()},d.onclick=()=>void F(z),e===0&&C){let e=a(`div`,``,`fm-actions`),t=a(`button`,i(`选择本机目录`,`Choose local folder`)),n=a(`button`,i(`选择文件`,`Choose files`)),r=a(`button`,i(`选择文件夹`,`Choose folder`));e.style.marginBottom=`6px`,e.append(t,n,r),s.insertBefore(e,m),t.hidden=!C.canChoose,t.onclick=async()=>{try{await C.choose(),await z.init()}catch(e){e.name!==`AbortError`&&O(e.message,!0)}},n.onclick=()=>C.pick(!1,()=>void z.init()),r.onclick=()=>C.pick(!0,()=>void z.init()),v.disabled=!C.canChoose}return B(),z}A=[M(0,e.local??C.request),M(1,e.remote)];function N(){if(b.replaceChildren(),!D.length){let e=a(`tr`),t=a(`td`,i(`选择文件和接收目录后,传输任务会显示在这里。`,`Choose files and a destination. Transfers will appear here.`),`fm-empty`);t.colSpan=6,e.append(t),b.append(e)}else for(let e of D){let t=a(`tr`),n=a(`td`,e.name+`
|
|
409
|
-
`+(e.from.index?`←`:`→`)),r=a(`td`),s=a(`progress`),c=a(`td`,e.source),l=a(`td`,e.destination),u=a(`div`,``,`fm-task-actions`),d=a(`td`);if(r.append(a(`span`,e.message||{queued:i(`等待中`,`Queued`),running:i(`正在传输`,`Transferring`),paused:i(`已暂停`,`Paused`),complete:i(`已完成`,`Completed`),cancelled:i(`已取消`,`Cancelled`),error:i(`传输失败`,`Failed`)}[e.status])),s.max=e.total||1,s.value=e.done||0,r.append(s),c.title=e.source,l.title=e.saved?.join(`
|
|
410
|
-
`)||e.destination,![`complete`,`cancelled`].includes(e.status)){let t=a(`button`,[`paused`,`error`].includes(e.status)?i(`继续`,`Resume`):i(`暂停`,`Pause`)),n=a(`button`,i(`取消`,`Cancel`));t.onclick=()=>{e.message=``,e.status=[`paused`,`error`].includes(e.status)?`queued`:`paused`,N(),L()},n.onclick=()=>{e.status=`cancelled`,e.message=``,e.active||P(e),N()},u.append(t,n)}d.append(u),t.append(n,r,a(`td`,o(e.total||0)),c,l,d),b.append(t)}}async function P(e){e.job&&await e.to.request(`jobs/`+e.job.id,`DELETE`).catch(()=>{}),e.export&&await e.from.request(`exports/`+e.export.id,`DELETE`).catch(()=>{})}async function F(e){let t=A[1-e.index];if(!t.info||!t.path){O(i(`请先选择接收目录。`,`Choose a destination folder first.`),!0);return}let n=e.entries.filter(t=>e.selected.has(t.path));if(!n.length)return;if(e.index===0&&t.info.readOnly){O(i(`只读模式不能发送文件,请先切换到可控制模式。`,`Sending files requires control mode.`),!0);return}if(e.index===1&&C&&!C.writable){try{for(let r of n)await e.request(`download`,`POST`,{path:r.path}),D.push({name:r.name,from:e,to:t,source:r.path,destination:i(`浏览器下载位置`,`Browser download location`),total:r.size,done:0,status:`complete`,message:i(`已交给浏览器下载,请在浏览器查看进度`,`Download handed to browser; check its download progress`)});O(i(`保存位置由浏览器下载设置决定;如需直接选择目录,请先点击“选择本机目录”,或从本机 pi-web-ui 打开。`,`Your browser chooses the download location. To choose a destination here, grant a local folder or open this from your local pi-web-ui.`)),N()}catch(e){O(e.message,!0)}return}let r={key:s(),name:n.length===1?n[0].name:`${n.length} ${i(`项`,`items`)}`,from:e,to:t,paths:n.map(e=>e.path),source:e.path,destination:t.path,status:`queued`,done:0,total:n.reduce((e,t)=>e+(t.directory?0:t.size),0)};D.push(r),O(k),N(),L()}async function I(e){let t;for(let r=0;r<3;r++)try{return await e()}catch(e){if(t=e,w)break;await new Promise(e=>n.setTimeout(e,300*(r+1)))}throw t}async function L(){if(!(E||w)){E=!0;try{for(;;){let t=D.find(e=>e.status===`queued`);if(!t||w)break;t.active=!0,t.status=`running`,N();try{t.export||=await t.from.request(`exports`,`POST`,{paths:t.paths});let r=t.export.entries;if(!Array.isArray(r)||r.length>1e4)throw Error(i(`无效文件清单`,`Invalid file list`));if(t.total=r.reduce((e,t)=>e+t.size,0),!Number.isSafeInteger(t.total)||t.total<0||t.total>16*1024**3)throw Error(i(`单次传输最多 16 GB`,`Transfer limit: 16 GiB`));t.job=await I(()=>t.to.request(`jobs`,`POST`,{key:t.key,entries:r,destination:t.destination})),t.done=t.job.entries.reduce((e,t)=>e+t.offset,0);for(let a=0;a<r.length;a++){let o=r[a],s=t.job.entries[a];for(;s.offset<o.size&&!(t.status!==`running`||w);){let r=await I(()=>t.from.request(`exports/${t.export.id}/chunk?entry=${a}&offset=${s.offset}`));if(typeof r.data!=`string`||r.data.length>1398104)throw Error(`Invalid file chunk`);let o=Uint8Array.from(n.atob(r.data),e=>e.charCodeAt(0));if(o.length!==r.length||e.crc(o)!==r.crc)throw Error(i(`文件校验失败`,`File checksum mismatch`));let c=e.crc(o,s.crc),l=await I(()=>t.to.request(`jobs/${t.job.id}/chunk?entry=${a}&offset=${s.offset}&crc=${r.crc}`,`PUT`,{data:r.data}));if(l.offset!==s.offset+o.length||l.crc!==c)throw Error(i(`文件校验失败`,`File checksum mismatch`));t.done+=o.length,s.offset=l.offset,s.crc=l.crc,t.message=`${i(`正在传输`,`Transferring`)} ${t.total?Math.round(t.done/t.total*100):100}%`,N()}if(t.status!==`running`||w)break}t.status===`running`&&!w&&(t.saved=(await I(()=>t.to.request(`jobs/${t.job.id}/finish`,`POST`,{checksums:t.job.entries.map(e=>e.crc)}))).saved,t.status=`complete`,t.message=i(`已完成 · 文件已校验`,`Completed · verified`),await P(t),t.to.path===t.destination&&await t.to.load(t.destination,!1))}catch(e){t.status!==`cancelled`&&(t.status=`error`,t.message=e.message,O(e.message,!0))}finally{t.active=!1,(t.status===`cancelled`||w)&&await P(t),t.status===`paused`&&(t.message=``),N()}}}finally{E=!1}}}for(let[e,t]of[[i(`全部继续`,`Resume all`),()=>{for(let e of D)[`paused`,`error`].includes(e.status)&&(e.status=`queued`,e.message=``);L()}],[i(`全部暂停`,`Pause all`),()=>{for(let e of D)[`queued`,`running`].includes(e.status)&&(e.status=`paused`)}],[i(`清除已完成`,`Clear finished`),()=>{for(let e=D.length-1;e>=0;e--)[`complete`,`cancelled`].includes(D[e].status)&&D.splice(e,1)}]]){let n=a(`button`,e);n.onclick=()=>{t(),N()},_.append(n)}return N(),{async open(){if(!w){if(l.open||l.showModal(),!T)T=!0,await Promise.all(A.map(async e=>{try{await e.init()}catch(e){T=!1,O(e.message,!0)}}));else try{A[1].info=await e.remote(`info`);for(let e of A)e.update()}catch(e){O(e.message,!0)}}},close(){w=!0;for(let e of D)[`complete`,`cancelled`].includes(e.status)||(e.status=`cancelled`,e.active||P(e));C?.close(),l.remove(),c.remove()}}}function uw(e){let t=Reflect.get(globalThis,`window`),n=t.document,r,i=new Map,a=0,o=new Map,s=new Map,c=()=>String(++a),l=e=>{let t=e.replace(/^\//,``).split(`/`).filter(Boolean);if(t.some(e=>e===`.`||e===`..`||/[\\:\x00-\x1f]/.test(e)))throw Error(`Invalid file path`);return t},u=()=>{if(o.size||s.size)throw Error(`Finish or cancel transfers before choosing another local folder`)},d=e=>{let n=``;for(let t=0;t<e.length;t+=16384)n+=String.fromCharCode(...e.subarray(t,t+16384));return t.btoa(n)};async function f(e){if(!r)throw Error(`Choose a local folder first`);let t=r;for(let n of l(e))t=await t.getDirectoryHandle(n);return t}async function p(e){let t=[];if(r)for await(let[n,r]of(await f(e)).entries()){let i=r.kind===`file`?await r.getFile():null;if(t.push({name:n,path:(e===`/`?``:e)+`/`+n,directory:r.kind===`directory`,size:i?.size||0,modified:i?.lastModified}),t.length>1e4)throw Error(`Folder exceeds 10000 entries`)}else{let n=e===`/`?``:e;for(let[e,r]of i)e.slice(0,e.lastIndexOf(`/`))===n&&t.push({name:e.slice(e.lastIndexOf(`/`)+1),path:e,directory:!r.file,size:r.file?.size||0,modified:r.file?.lastModified})}return t}async function m(e){if(!r){let t=i.get(e)?.file;if(!t)throw Error(`File is no longer selected`);return t}let t=l(e),n=t.pop();return(await(await f(`/`+t.join(`/`))).getFileHandle(n)).getFile()}return{request:async(n,a=`GET`,u)=>{let h=new URL(n,`https://files.invalid/`),g=h.pathname.slice(1),_=g.split(`/`);if(g===`info`)return{device:r?.name||`Browser / 浏览器`,home:`/`,roots:[{name:r?.name||`Selected files / 已选择的文件`,path:`/`}]};if(g===`list`){let e=`/`+l(h.searchParams.get(`path`)||`/`).join(`/`),t=e=>e.slice(0,e.lastIndexOf(`/`))||`/`;if(e!==`/`&&!r&&!i.has(e))throw Error(`File or folder not found`);if(!i.get(e)?.file)try{return{path:e,parent:t(e),entries:await p(e)}}catch(e){if(!r||e.name!==`TypeMismatchError`)throw e}let n=t(e),a=await p(n);if(!a.some(t=>t.path===e&&!t.directory))throw Error(`File not found`);return{path:n,parent:t(n),entries:a,selected:e}}if(g===`mkdir`){let e=l(u.name);if(e.length!==1)throw Error(`Invalid folder name`);return await(await f(u.path)).getDirectoryHandle(e[0],{create:!0}),{}}if(g===`exports`){let e=[],t=0;async function n(a,o){let s=r?null:i.get(a),c=!!s&&!s.file;if(r){let e=l(a),t=e.pop();try{await(await f(`/`+e.join(`/`))).getDirectoryHandle(t),c=!0}catch{c=!1}}let u=c?null:await m(a);if(e.push({path:o,source:a,directory:c,size:u?.size||0,modified:u?.lastModified}),t+=u?.size||0,e.length>1e4||t>16*1024**3)throw Error(`Transfer exceeds 10000 entries or 16 GiB`);if(c)for(let e of await p(a))await n(e.path,o+`/`+e.name)}for(let e of u.paths)await n(e,l(e).at(-1));let a=c();return o.set(a,e),{id:a,total:t,entries:e.map(({path:e,size:t,directory:n})=>({path:e,size:t,directory:n}))}}if(_[0]===`exports`){let t=o.get(_[1]);if(a===`DELETE`)return o.delete(_[1]),null;if(!t)throw Error(`Source selection expired`);let n=t[Number(h.searchParams.get(`entry`))],r=Number(h.searchParams.get(`offset`));if(!n||n.directory||!Number.isSafeInteger(r)||r<0||r>=n.size)throw Error(`Invalid file offset`);let i=await m(n.source);if(i.size!==n.size||i.lastModified!==n.modified)throw Error(`Source file changed; select again`);let s=new Uint8Array(await i.slice(r,r+1024**2).arrayBuffer());return{data:d(s),length:s.length,crc:e(s)}}if(g===`jobs`){let e=[...s.values()].find(e=>e.key===u.key);if(e)return e.snapshot();let t=await f(u.destination),n=u.entries,r=new Map,i=new Set;for(let e of n){let t=l(e.path);if(!t.length||t.join(`/`)!==e.path||i.has(e.path.toLowerCase())||!Number.isSafeInteger(e.size)||e.size<0)throw Error(`Invalid file list`);i.add(e.path.toLowerCase())}async function a(e,t,n){let r=n?-1:t.lastIndexOf(`.`);for(let i=0;i<1e4;i++){let a=i?r>0?t.slice(0,r)+` (${i+1})`+t.slice(r):t+` (${i+1})`:t,o=!1;for await(let[t]of e.entries())if(t.toLowerCase()===a.toLowerCase()){o=!0;break}if(!o)return{handle:await(n?e.getDirectoryHandle(a,{create:!0}):e.getFileHandle(a,{create:!0})),name:a}}throw Error(`Too many duplicate names`)}let o=new Map;for(let e of n){let t=l(e.path);o.set(t[0],t.length>1||e.directory||o.get(t[0])===!0)}for(let[e,n]of o){let i=await a(t,e,n);r.set(e,i.handle)}for(let e of[...n].sort((e,t)=>l(e.path).length-l(t.path).length)){let t=l(e.path),n=r.get(t[0]);for(let i=1;i<t.length;i++){let a=t.slice(0,i+1).join(`/`);r.has(a)||r.set(a,await(i<t.length-1||e.directory?n.getDirectoryHandle(t[i],{create:!0}):n.getFileHandle(t[i],{create:!0}))),n=r.get(a)}}let d=c(),p={id:d,key:u.key,entries:n.map(()=>({offset:0,crc:0})),manifest:n,handles:r,writers:new Map,complete:!1,destination:u.destination};return p.snapshot=()=>({id:d,entries:p.entries.map(({offset:e,crc:t})=>({offset:e,crc:t})),complete:p.complete,destination:p.destination}),s.set(d,p),p.snapshot()}if(_[0]===`jobs`){let n=s.get(_[1]);if(!n)throw Error(`Transfer expired`);if(a===`DELETE`){for(let e of n.writers.values())await e.abort().catch(()=>{});return s.delete(n.id),null}if(_[2]===`finish`){if(n.entries.some((e,t)=>e.offset!==n.manifest[t].size||e.crc!==u.checksums[t]))throw Error(`File checksum mismatch`);for(let e of n.writers.values())await e.close();return n.writers.clear(),n.complete=!0,n.snapshot()}let r=Number(h.searchParams.get(`entry`)),i=Number(h.searchParams.get(`offset`)),o=n.entries[r],c=n.manifest[r],l=Uint8Array.from(t.atob(u.data),e=>e.charCodeAt(0));if(e(l)!==Number(h.searchParams.get(`crc`)))throw Error(`File checksum mismatch`);if(o?.last===i&&o.lastCrc===e(l)&&o.lastSize===l.length)return{offset:o.offset,crc:o.crc};if(!o||o.offset!==i||i+l.length>c.size)throw Error(`Invalid file offset`);let d=n.writers.get(r);return d||(d=await n.handles.get(c.path).createWritable(),n.writers.set(r,d)),await d.write({type:`write`,position:i,data:l}),i+l.length===c.size&&(await d.close(),n.writers.delete(r)),o.offset+=l.length,o.crc=e(l,o.crc),o.last=i,o.lastCrc=e(l),o.lastSize=l.length,{offset:o.offset,crc:o.crc}}throw Error(`Unsupported file operation`)},get writable(){return!!r},canChoose:typeof t.showDirectoryPicker==`function`,async choose(){u(),r=await t.showDirectoryPicker({mode:`readwrite`}),i.clear()},pick(e,a){try{u()}catch(e){t.alert(e.message);return}let o=n.createElement(`input`);o.type=`file`,o.multiple=!0,e&&o.setAttribute(`webkitdirectory`,``),o.onchange=()=>{r=void 0,i=new Map;for(let e of o.files){let t=`/`+(e.webkitRelativePath||e.name),n=l(t);for(let e=1;e<n.length;e++)i.set(`/`+n.slice(0,e).join(`/`),{});i.set(t,{file:e})}a()},o.click()},close(){for(let e of s.values())for(let t of e.writers.values())t.abort().catch(()=>{});s.clear(),o.clear()}}}Object.freeze({bytes:16*1024**3,entries:1e4,chunk:1024**2,jobs:4,idleMs:18e5});function dw(e,t=0){let n=new Uint32Array(256);for(let e=0;e<256;e++){let t=e;for(let e=0;e<8;e++)t=t>>>1^0xedb88320&-(t&1);n[e]=t}let r=t^-1;for(let t of e)r=r>>>8^n[(r^t)&255];return(r^-1)>>>0}function fw(e,t=!1,n){return async(r,i=`GET`,a)=>{let o=await fetch(e(r),{method:i,credentials:`same-origin`,cache:`no-store`,headers:{...a===void 0?{}:{"content-type":`application/json`},...t?{"x-pi-local-files":`1`}:{},...n?{"x-pi-desktop-file-session":n()}:{}},...a===void 0?{}:{body:JSON.stringify(a)}});if(o.status===204)return null;let s=await o.json();if(!o.ok)throw Error(s.error||`HTTP ${o.status}`);return s}}function pw(e){let t=Reflect.get(globalThis,`window`),n=0,r=!1,i,a=``,o=0,s=Array.from(t.crypto.getRandomValues(new Uint8Array(16)),e=>e.toString(16).padStart(2,`0`)).join(``),c=new Map,l=(i,a=`GET`,o)=>new Promise((l,u)=>{if(r)return u(Error(`File transfer closed`));let d=++n,f=t.setTimeout(()=>{c.delete(d),u(Error(`File request timed out; resume to retry`))},12e4);c.set(d,{resolve:l,reject:u,timer:f}),e.frame()?.postMessage({type:`desktop-files-call`,channel:s,id:d,path:i,method:a,body:o},`*`)}),u=n=>{let r=n.data;if(!r||typeof r.type!=`string`)return;if(e.nested&&n.source===t.parent&&t.parent!==t&&r.type===`desktop-files-call`){e.frame()?.postMessage(r,`*`);return}if(n.source!==e.frame()||n.origin!==e.origin||![`desktop-files-show`,`desktop-files-result`,`desktop-files-target`].includes(r.type))return;if(e.nested){t.parent.postMessage(r,`*`);return}if([`desktop-files-target`,`desktop-files-show`].includes(r.type)){if(typeof r.target!=`string`||!/^[a-f0-9]{32}$/.test(r.target))return;if(a!==r.target){a=r.target,o++,i?.close(),i=void 0;for(let e of c.values())t.clearTimeout(e.timer),e.reject(Error(`Remote device changed`));c.clear()}if(r.type===`desktop-files-target`)return}if(r.type===`desktop-files-show`){let t=o;i??=e.manager((...e)=>t===o?l(...e):Promise.reject(Error(`Remote device changed; reopen file transfer`))),i.open();return}if(r.channel!==s||!Number.isSafeInteger(r.id))return;let u=c.get(r.id);u&&(c.delete(r.id),t.clearTimeout(u.timer),typeof r.error==`string`?u.reject(Error(r.error)):u.resolve(r.value))};return t.addEventListener(`message`,u),{close(){r=!0,t.removeEventListener(`message`,u),i?.close();for(let e of c.values())t.clearTimeout(e.timer),e.reject(Error(`Remote device changed; reopen file transfer`));c.clear()}}}function mw({frame:e,url:t,local:n}){return(0,Q.useEffect)(()=>{let r=!!Ad(),i=!r&&[`localhost`,`127.0.0.1`,`[::1]`].includes(location.hostname),a=pw({frame:()=>e.current?.contentWindow,origin:n&&t?new URL(t).origin:`null`,nested:r,manager:e=>lw({remote:e,local:i?fw(e=>W(j(`/api/device-desktop/local/files/`+e)),!0):void 0,crc:dw,browser:()=>uw(dw)})});return()=>a.close()},[e,t,n]),null}function hw({access:e,visible:t}){let n=X(),r=(0,Q.useRef)(null),[i,a]=(0,Q.useState)(!1),[o,s]=(0,Q.useState)([]),[c,l]=(0,Q.useState)(!0),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(0),m=i&&t,h=Rt(m),{panelRef:g,style:_,measure:v}=T_({open:m,anchor:r,onClose:()=>{a(!1),r.current?.focus()}});(0,Q.useEffect)(()=>{t||a(!1)},[t]),(0,Q.useEffect)(()=>{if(!m)return;let e=new AbortController;return l(!0),d(!1),s([]),(async()=>{try{let t=AbortSignal.any([e.signal,AbortSignal.timeout(15e3)]),n=()=>fetch(W(j(Ad()?`/__desktop_devices`:`/api/device-center/devices`)),{credentials:`same-origin`,signal:t}),r=await n();for(let e=0;e<2&&[502,503,504].includes(r.status);e++)await r.body?.cancel(),await new Promise((n,r)=>{let i=()=>{clearTimeout(a),t.removeEventListener(`abort`,i),r(t.reason)},a=setTimeout(()=>{t.removeEventListener(`abort`,i),n()},750*(e+1));t.addEventListener(`abort`,i,{once:!0}),t.aborted&&i()}),r=await n();if(!r.ok)throw Error(`Device list unavailable`);let i=await r.json();if(!Array.isArray(i.devices))throw Error(`Invalid device list`);let a=i.devices.filter(e=>e&&typeof e.id==`string`&&typeof e.name==`string`&&typeof e.online==`boolean`&&(e.remark==null||typeof e.remark==`string`));e.signal.aborted||s(a)}catch{e.signal.aborted||d(!0)}finally{e.signal.aborted||l(!1)}})(),()=>e.abort()},[m,e.hubUrl,f]),(0,Q.useLayoutEffect)(()=>{v()},[o,c,u,v]),(0,Q.useEffect)(()=>{m&&!c&&(g.current?.querySelector(`button[aria-pressed="true"]:not(:disabled)`)||g.current?.querySelector(`button:not(:disabled)`))?.focus()},[m,c,o,u,g]);async function y(t){if(t.online){if(t.id===e.id)a(!1),r.current?.focus();else try{await Hd(t.id,e.hubUrl,!0,n,!1,t.remark?.trim()||t.name,{mode:e.mode}),a(!1)}catch{d(!0)}}}return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`button`,{ref:r,type:`button`,className:`btn`,"aria-label":n(`desktop.choose`),"aria-haspopup":`dialog`,"aria-expanded":m,onClick:()=>a(!i),children:n(`desktop.choose`)}),m&&(0,Er.createPortal)((0,$.jsx)(`div`,{ref:g,className:`desktop-device-picker`,style:{..._,zIndex:h},role:`dialog`,"aria-label":n(`desktop.choose`),"aria-busy":c,children:c?(0,$.jsx)(`p`,{role:`status`,children:n(`loading`)}):u?(0,$.jsxs)(`div`,{role:`alert`,children:[(0,$.jsx)(`p`,{children:n(`desktop.devicesUnavailable`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>p(e=>e+1),children:n(`desktop.retry`)})]}):o.length?o.map(t=>(0,$.jsxs)(`button`,{type:`button`,className:`desktop-device-option`,disabled:!t.online,"aria-pressed":t.id===e.id,onClick:()=>void y(t),children:[(0,$.jsx)(se,{"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`desktop-device-name`,children:t.remark?.trim()||t.name}),(0,$.jsx)(`span`,{className:`desktop-device-status`,children:n(t.online?`deviceHubOnline`:`deviceHubOffline`)}),t.id===e.id&&(0,$.jsx)(z,{"aria-hidden":!0})]},t.id)):(0,$.jsx)(`p`,{role:`status`,children:n(`desktop.noDevices`)})}),document.body)]})}var gw=new Map,_w=`pi-web-ui:desktop-display:`,vw=e=>_w+encodeURIComponent(JSON.stringify([e.hubUrl,e.id])),yw=`pi:desktop-display-change`,bw=e=>{try{let t=localStorage.getItem(vw(e));if(t&&t.length<=128&&!/[\x00-\x1f]/.test(t))return t}catch{}return gw.get(vw(e))??``};function xw(e,t){if(!(t.length>128||/[\x00-\x1f]/.test(t)||bw(e)===t)){gw.set(vw(e),t);try{localStorage.setItem(vw(e),t)}catch{}window.dispatchEvent(new Event(yw))}}typeof window<`u`&&window.addEventListener(`storage`,e=>{e.key?.startsWith(_w)&&window.dispatchEvent(new Event(yw))});function Sw(){let e=(0,Q.useSyncExternalStore)(Ld,Rd);return e?.mode===`live`?(0,$.jsx)(Cw,{access:e},e.revision):null}function Cw({access:e}){let t=X(),n=Rt(),{target:r,error:i,retry:a}=XC(e),o=(0,Q.useRef)(null),s=Md(e);QC(o,r?.url,s),ew(o,e,r?.url,s),(0,Q.useEffect)(()=>{let t=bw(e),n=!0,i=!1,a=a=>{if(Ad()&&parent!==window&&a.source===parent&&a.data?.type===`desktop-select-display`){o.current?.contentWindow?.postMessage(a.data,`*`);return}if(a.source!==o.current?.contentWindow||a.origin!==(s&&r?new URL(r.url).origin:`null`)||a.data?.type!==`desktop-displays`)return;let{displays:c,selected:l}=a.data;!Array.isArray(c)||c.length>32||typeof l!=`string`||!c.some(e=>e?.id===l)||(Ad()&&parent!==window&&parent.postMessage(a.data,`*`),n&&t&&l!==t&&c.some(e=>e?.id===t)?i||(i=!0,o.current?.contentWindow?.postMessage({type:`desktop-select-display`,display:t},`*`)):(n=!1,xw(e,l)))};return window.addEventListener(`message`,a),()=>window.removeEventListener(`message`,a)},[e.id,e.hubUrl,s,r]);let[c,l]=(0,Q.useState)();(0,Q.useEffect)(()=>{l(r?.transport)},[r]),(0,Q.useEffect)(()=>{let e=e=>{if(e.source!==o.current?.contentWindow||e.origin!==`null`||e.data?.type!==`device-access-transport`)return;let t=Od(e.data);t&&l(t)};return window.addEventListener(`message`,e),()=>window.removeEventListener(`message`,e)},[]);let[u,d]=(0,Q.useState)({x:24,y:64,width:Math.min(960,window.innerWidth-32),height:Math.min(640,window.innerHeight-88)}),[f,p]=(0,Q.useState)(()=>window.innerWidth<=768),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(!1),[v,y]=(0,Q.useState)(``);(0,Q.useEffect)(()=>{let e=()=>d(e=>({...e,x:Math.max(0,Math.min(e.x,window.innerWidth-Math.min(e.width,window.innerWidth))),y:Math.max(0,Math.min(e.y,window.innerHeight-Math.min(e.height,window.innerHeight))),width:Math.min(e.width,window.innerWidth),height:Math.min(e.height,window.innerHeight)}));return window.addEventListener(`resize`,e),()=>window.removeEventListener(`resize`,e)},[]);function b(e,t){if(f||e.button!==0||e.target.closest(`button,select,input,label`))return;e.preventDefault();let n=e.currentTarget;n.setPointerCapture(e.pointerId),_(!0);let r={...u,px:e.clientX,py:e.clientY},i=e=>{let n=e.clientX-r.px,i=e.clientY-r.py;d(t?{...u,width:Math.max(Math.min(320,window.innerWidth),Math.min(window.innerWidth-u.x,r.width+n)),height:Math.max(Math.min(200,window.innerHeight),Math.min(window.innerHeight-u.y,r.height+i))}:{...u,x:Math.max(0,Math.min(window.innerWidth-Math.min(u.width,240),r.x+n)),y:Math.max(0,Math.min(window.innerHeight-40,r.y+i))})},a=()=>{_(!1),n.removeEventListener(`pointermove`,i),n.removeEventListener(`pointerup`,a),n.removeEventListener(`pointercancel`,a),n.removeEventListener(`lostpointercapture`,a),n.hasPointerCapture(e.pointerId)&&n.releasePointerCapture(e.pointerId)};n.addEventListener(`pointermove`,i),n.addEventListener(`pointerup`,a),n.addEventListener(`pointercancel`,a),n.addEventListener(`lostpointercapture`,a)}async function x(){h(!0),y(``);try{await Hd(e.id,e.hubUrl,!0,t,!0,e.name,{local:e.local}),Bd(e,`preview`)}catch(e){y(e instanceof Error?e.message:String(e))}finally{h(!1)}}let S=t(`desktop.title`),C=!!window.piDesktop?.openHub;return(0,Er.createPortal)((0,$.jsxs)(`div`,{className:`remote-desktop-window${f?` is-fullscreen`:``}${g?` is-dragging`:``}`,role:`dialog`,"aria-label":S,style:f?{zIndex:n}:{zIndex:n,left:u.x,top:u.y,width:u.width,height:u.height},children:[(0,$.jsxs)(`div`,{className:`remote-desktop-titlebar`,onPointerDown:e=>b(e,!1),children:[(0,$.jsxs)(`strong`,{children:[S,` · `,e.name||e.id,` · `,kd(c,t)]}),(0,$.jsx)(hw,{access:e,visible:!0}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:m,onClick:()=>void x(),children:t(C?`desktop.window`:`desktop.tab`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":t(`desktop.back`),onClick:()=>Bd(e,`preview`),children:t(`desktop.back`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":t(f?`desktop.exitFullscreen`:`desktop.fullscreen`),onClick:()=>{p(!f)},children:f?`⤡`:`⤢`}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":t(`desktop.back`),title:t(`desktop.back`),onClick:()=>Bd(e,`preview`),children:`×`})]}),(0,$.jsx)(mw,{frame:o,url:r?.url,local:s}),(0,$.jsx)(cw,{frame:o,url:r?.url,local:s,scope:JSON.stringify([e.hubUrl,e.id])}),(v||i)&&(0,$.jsxs)(`div`,{role:`alert`,className:`remote-desktop-error`,children:[v||i,(0,$.jsx)(`button`,{className:`btn`,onClick:a,children:t(`desktop.retry`)})]}),!r&&!i&&(0,$.jsx)(`div`,{role:`status`,className:`remote-desktop-loading`,children:t(`desktop.connecting`)}),r&&(0,$.jsx)(`iframe`,{ref:o,title:S,src:r.url,sandbox:s?`allow-scripts allow-forms allow-pointer-lock allow-same-origin allow-downloads`:`allow-scripts allow-forms allow-pointer-lock allow-downloads`,allow:`fullscreen; local-network-access *; local-network *; loopback-network *`,allowFullScreen:!0}),!f&&(0,$.jsx)(`div`,{className:`remote-desktop-resize`,onPointerDown:e=>b(e,!0),"aria-hidden":`true`})]}),document.body)}var ww=e=>/\.(zip|tar|tar\.gz|tgz|gz)$/i.test(e);function Tw(e,t={}){let n={archive:j(`/api/file-transfer/archive`),upload:j(`/api/file-transfer/upload`)},r=new URL(W(`${n[e]}?${new URLSearchParams({clientId:Po(),...t})}`),window.location.href),i=new URL(n[e],window.location.href);if(r.origin!==i.origin||r.pathname!==i.pathname)throw Error(`File transfers must use an allowlisted service endpoint`);return r}async function Ew(e,t,n){let r=await fetch(Tw(`archive`),{method:`POST`,headers:{"Content-Type":`application/json`,"X-File-Operation":`1`},body:JSON.stringify({action:e,path:t,...n})});if(!r.ok)throw Error(await r.text());if(e===`download`){let e=r.headers.get(`content-disposition`)??``,t=/filename\*=UTF-8''([^;]+)/i.exec(e)?.[1],n=/filename="([^"]+)"/i.exec(e)?.[1],i=t?decodeURIComponent(t):n??`archive.tar.gz`,a=await Dy(await r.blob(),i);if(!a.ok&&!a.cancelled)throw Error(a.error)}}async function Dw(){let e=window.showDirectoryPicker;if(!e)return null;let t=await e.call(window),n=[];async function r(e,t){if(n.length>=2e4)throw Error(`Folder exceeds 20,000 entries`);if(n.push(e.kind===`file`?{path:t,file:await e.getFile()}:{path:t}),e.kind===`directory`)for await(let n of e.values())await r(n,`${t}/${n.name}`)}return await r(t,t.name),n}async function Ow(e,t,n,r=32){if(t.length>2e4)throw Error(`Folder exceeds 20,000 entries`);for(let e of t)if(e.file&&e.file.size>r*1024*1024)throw Error(`File exceeds ${r} MiB: ${e.path}`);let i=t.reduce((e,t)=>e+(t.file?.size??0),0),a=0,o=0;for(let r of t){let t=Tw(`upload`,{dir:e,name:r.path,kind:r.file?`file`:`directory`}),s=r.file??new Blob;await new Promise((e,c)=>{let l=new XMLHttpRequest,u=0,d=e=>n?.({done:a,uploadedBytes:o+u,totalBytes:i,path:r.path,phase:e});l.open(`POST`,t.href),l.setRequestHeader(`Content-Type`,`application/octet-stream`),l.setRequestHeader(`X-File-Operation`,`1`),l.upload.onprogress=e=>{u=Math.min(e.loaded,s.size),d(u===s.size?`waiting`:`uploading`)},l.upload.onload=()=>{u=s.size,d(`waiting`)},l.onload=()=>{l.status<200||l.status>=300?c(Error(`${r.path}: ${l.responseText||`HTTP ${l.status}`}`)):(a++,o+=s.size,u=0,d(`confirmed`),e())},l.onerror=()=>c(Error(`${r.path}: Network error`)),l.onabort=()=>c(Error(`${r.path}: Upload aborted`)),l.ontimeout=()=>c(Error(`${r.path}: Upload timed out`)),d(s.size===0?`waiting`:`uploading`),l.send(s)})}}function kw({request:e,onClose:t,onComplete:n}){let r=X(),i=mn(`folderUploadMaxMb`),[a,o]=(0,Q.useState)(e.dir),[s,c]=(0,Q.useState)(`skip`),[l,u]=(0,Q.useState)([]),[d,f]=(0,Q.useState)(null),p=(0,Q.useRef)(null),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(``),v=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{v.current?.showModal()},[]);let y=r(e.action===`upload`?`fileUploadFolder`:e.action===`extract`?`fileExtract`:e.action===`download`?`fileCompressDownload`:`fileCompress`);async function b(){try{let e=await Dw();e?(u(e),f(null)):p.current?.click()}catch(e){e instanceof DOMException&&e.name===`AbortError`||_(String(e))}}async function x(){f(null),h(!0),_(``);try{e.action===`upload`?await Ow(e.dir,l,f,i):await Ew(e.action,e.path,{destination:a,policy:s}),n(),t()}catch(e){_(e instanceof Error?e.message:String(e)),n()}finally{h(!1)}}return(0,Er.createPortal)((0,$.jsx)(`dialog`,{ref:v,className:`file-transfer-dialog`,"aria-labelledby":`file-transfer-title`,onCancel:e=>{e.preventDefault(),m||t()},children:(0,$.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),x()},children:[(0,$.jsxs)(`div`,{className:`file-transfer-head`,children:[(0,$.jsx)(`h3`,{id:`file-transfer-title`,children:y}),(0,$.jsx)(`button`,{type:`button`,className:`file-transfer-close`,title:r(`close`),"aria-label":r(`close`),disabled:m,onClick:t,children:(0,$.jsx)(Ct,{})})]}),(0,$.jsx)(`p`,{className:`file-transfer-path`,children:(e.action===`upload`?e.dir:e.path)||`.`}),(0,$.jsx)(`p`,{children:r(`fileArchiveLimits`)}),e.action===`extract`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[r(`fileExtractDestination`),(0,$.jsx)(`input`,{value:a,disabled:m,onChange:e=>o(e.target.value)})]}),(0,$.jsxs)(`label`,{children:[r(`fileConflictPolicy`),(0,$.jsxs)(`select`,{value:s,disabled:m,onChange:e=>c(e.target.value),children:[(0,$.jsx)(`option`,{value:`skip`,children:r(`fileConflictSkip`)}),(0,$.jsx)(`option`,{value:`overwrite`,children:r(`fileConflictOverwrite`)}),(0,$.jsx)(`option`,{value:`error`,children:r(`fileConflictError`)})]})]})]}),e.action===`upload`&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`p`,{children:r(`fileFolderUploadHint`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:m,onClick:()=>void b(),children:r(`fileChooseFolder`)}),(0,$.jsx)(`input`,{type:`file`,"aria-label":y,multiple:!0,hidden:!0,disabled:m,ref:e=>{p.current=e,e?.setAttribute(`webkitdirectory`,``)},onChange:e=>{u(Array.from(e.target.files??[],e=>({path:e.webkitRelativePath||e.name,file:e}))),f(null)}}),(0,$.jsxs)(`p`,{"aria-live":`polite`,children:[d?.done??0,` / `,l.length]}),d&&(0,$.jsxs)($.Fragment,{children:[d.totalBytes>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`progress`,{"aria-label":y,value:d.uploadedBytes,max:d.totalBytes}),(0,$.jsxs)(`p`,{children:[d.uploadedBytes.toLocaleString(),` / `,d.totalBytes.toLocaleString(),` B`]})]}),m&&d.phase!==`confirmed`&&(0,$.jsx)(`p`,{className:`file-transfer-path`,role:`status`,children:d.phase===`waiting`?r(`folderUploadWaiting`,{name:d.path}):r(`folderUploadSending`,{name:d.path,percent:Math.floor(d.uploadedBytes/d.totalBytes*100)})})]})]}),g&&(0,$.jsx)(`p`,{role:`alert`,children:r(`fileTransferFailed`,{error:g})}),(0,$.jsxs)(`div`,{className:`file-transfer-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,disabled:m,onClick:t,children:r(`cancel`)}),(0,$.jsx)(`button`,{type:`submit`,className:`btn primary`,disabled:m||e.action===`upload`&&l.length===0,children:m?r(`fileTransferBusy`):y})]})]})}),document.body)}function Aw(e){return e.startsWith(`.`)&&e!==`..`}function jw(e,t){return t?e:e.filter(e=>!Aw(e.name))}function Mw(e){return e instanceof Error?e.message:String(e)}function Nw(e,t,n){switch(e.kind){case`no-client`:return n(`pluginPageNoClient`,{name:t});case`load`:return n(`pluginPageLoadFailed`,{name:t,detail:e.detail});case`mount`:return n(`pluginPageMountFailed`,{name:t,detail:e.detail})}}function Pw({plugin:e,epoch:t,send:n,pageId:r,className:i}){let a=(0,Q.useRef)(null),{locale:o}=_e(),s=X(),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(n);(0,Q.useEffect)(()=>{u.current=n},[n]),(0,Q.useEffect)(()=>{let n=a.current;if(!n)return;let i=!1,o,s=!1;if(l(null),!e.hasClient)l({kind:`no-client`});else return(async()=>{try{if(await F0(e,t),i)return;let a=await zn(e.id,()=>import(A0(e.id,t)));if(i)return;let c=a.default;if(!c||typeof c.mount!=`function`)throw Error(`client/entry.mjs 没有导出 default.mount()`);s=!0;let l=!!(e.isolated||c.isolated||c.shadow),{container:d}=d0(n,{isolated:l});o=c.mount(d,L0(e.id,e=>u.current(e),r?{page:r}:void 0))}catch(t){if(i)return;console.error(`[plugin:${e.id}] 页面${s?`挂载`:`加载`}失败:`,t),l({kind:s?`mount`:`load`,detail:Mw(t)})}})(),()=>{if(i=!0,typeof o==`function`)try{o()}catch(t){console.error(`[plugin:${e.id}] cleanup 失败:`,t)}n.replaceChildren()}},[e.id,e.hasClient,t,r]);let d=i?`plugin-page ${i}`:`plugin-page`;return(0,$.jsxs)(`div`,{className:d,children:[(0,$.jsx)(`div`,{className:`plugin-page-host`,ref:a}),c&&(0,$.jsx)(`div`,{className:`plugin-page-error`,role:`alert`,children:Nw(c,Vy(e,o),s)})]})}function Fw(e){return`pi-web-ui:${e}:tab`}function Iw(e,t){try{let n=localStorage.getItem(Fw(e));return n&&t.some(e=>e.id===n)?n:null}catch{return null}}function Lw(e,t){try{localStorage.setItem(Fw(e),t)}catch{}}function Rw(e){return e.length>0&&!/[a-z]/i.test(e)}function zw(e){if(e.label)return e.label;let t=e.pluginPage;return t?.entry.label||t?.plugin.name||e.id}function Bw({storageKey:e,tabs:t,epoch:n,send:r,extra:i,className:a,onActiveChange:o}){let s=(0,Q.useId)(),[c,l]=(0,Q.useState)(()=>Iw(e,t)??t[0]?.id??``),u=(0,Q.useRef)([]),d=(0,Q.useRef)(``),f=(0,Q.useRef)(``),p=t.findIndex(e=>e.id===c),m=p>=0?t[p]:t[0],h=m?t.indexOf(m):-1;(0,Q.useEffect)(()=>{if(!m)return;c!==m.id&&l(m.id);let t=`${e}:${m.id}`;d.current!==t&&(d.current=t,Lw(e,m.id)),f.current!==m.id&&(f.current=m.id,o?.(m.id))},[m,c,e,o]),(0,Q.useEffect)(()=>{let n=n=>{let r=n.detail;r&&r.group===e&&typeof r.id==`string`&&t.some(e=>e.id===r.id)&&(l(r.id),d.current=`${e}:${r.id}`,Lw(e,r.id))};return window.addEventListener(`pi:select-slot-tab`,n),()=>window.removeEventListener(`pi:select-slot-tab`,n)},[e,t]);let g=t=>{l(t.id),d.current=`${e}:${t.id}`,Lw(e,t.id)},_=(e,n)=>{let r=t.length,i=-1;if(e.key===`ArrowRight`)i=(n+1)%r;else if(e.key===`ArrowLeft`)i=(n-1+r)%r;else if(e.key===`Home`)i=0;else if(e.key===`End`)i=r-1;else return;let a=t[i];a&&(e.preventDefault(),g(a),u.current[i]?.focus())};if(!m)return null;let v=`${s}-panel-${h}`,y=a?`slot-tabs ${a}`:`slot-tabs`,b=t.length>1||i!=null;return(0,$.jsxs)(`div`,{className:y,children:[b?(0,$.jsxs)(`div`,{className:`slot-tabs-bar`,role:`tablist`,children:[t.map((e,t)=>{let n=t===h,r=zw(e);return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,id:`${s}-tab-${t}`,className:`slot-tab${n?` active`:``}${e.iconOnly?` slot-tab-icon-only`:``}`,title:e.hint??r,"aria-label":e.iconOnly?r:void 0,"aria-selected":n,"aria-controls":`${s}-panel-${t}`,tabIndex:n?0:-1,ref:e=>{u.current[t]=e},onClick:()=>g(e),onKeyDown:e=>_(e,t),children:[e.iconNode?(0,$.jsx)(`span`,{className:`slot-tab-icon`,"aria-hidden":`true`,children:e.iconNode}):e.iconSvg?(0,$.jsx)(pp,{iconSvg:e.iconSvg,className:`slot-tab-icon`}):e.icon&&Rw(e.icon)?(0,$.jsx)(`span`,{className:`slot-tab-icon`,children:e.icon}):null,!e.iconOnly&&(0,$.jsx)(`span`,{className:`slot-tab-label`,children:r})]},e.id)}),i?(0,$.jsx)(`div`,{className:`slot-tabs-extra`,children:i}):null]}):null,(0,$.jsx)(`div`,{className:`slot-tabs-body`,id:v,role:`tabpanel`,"aria-labelledby":`${s}-tab-${h}`,children:m.pluginPage?(0,$.jsx)(Pw,{plugin:m.pluginPage.plugin,epoch:n,send:r}):m.element??null})]})}function Vw({access:e,active:t,collapsed:n,height:r,onOpen:i,label:a}){let o=X(),{target:s,error:c,retry:l}=XC(e),u=(0,Q.useRef)(null),d=Md(e);QC(u,s?.url,d);let[f,p]=(0,Q.useState)(),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(0),[v,y]=(0,Q.useState)(Date.now),b=(0,Q.useRef)(t);b.current=t;function x(){u.current?.contentWindow?.postMessage({type:`desktop-preview-active`,active:b.current&&!document.hidden,display:bw(e)},`*`)}return(0,Q.useEffect)(()=>(x(),document.addEventListener(`visibilitychange`,x),window.addEventListener(yw,x),()=>{document.removeEventListener(`visibilitychange`,x),window.removeEventListener(yw,x)}),[t,s]),(0,Q.useEffect)(()=>{if(p(s?.transport),_(0),h(``),!s)return;let e=setTimeout(()=>h(o(`desktop.previewUnavailable`)),2e4),t=t=>{if(t.source!==u.current?.contentWindow||t.origin!==(d?new URL(s.url).origin:`null`))return;let n=t.data;if(n?.type===`device-access-transport`){let e=Od(n);e&&p(e)}n?.type===`desktop-preview-state`&&(clearTimeout(e),n.ready===!0&&x(),typeof n.error==`string`&&h(n.unsupported?o(`desktop.previewUnavailable`):n.error.slice(0,2048)),typeof n.updatedAt==`number`&&Number.isFinite(n.updatedAt)&&(_(Date.now()),y(Date.now()),h(``)))};return window.addEventListener(`message`,t),()=>{clearTimeout(e),window.removeEventListener(`message`,t)}},[s,o,d]),(0,Q.useEffect)(()=>{if(!t)return;let e=setInterval(()=>y(Date.now()),1e3);return()=>clearInterval(e)},[t]),(0,$.jsxs)(`div`,{hidden:n,children:[(0,$.jsxs)(`div`,{className:`desktop-preview-screen`,style:{height:r},children:[s&&(0,$.jsx)(`iframe`,{ref:u,src:s.url,title:a||o(`desktop.preview`),sandbox:d?`allow-scripts allow-forms allow-same-origin`:`allow-scripts allow-forms`,onLoad:x,tabIndex:-1}),(0,$.jsx)(`button`,{className:`desktop-preview-open`,onClick:i??(()=>Bd(e,`live`)),"aria-label":a?o(`desktop.groupOpen`,{name:a}):o(`desktop.open`),children:(0,$.jsx)(`span`,{children:o(`desktop.open`)})})]}),(0,$.jsxs)(`div`,{className:`desktop-preview-status`,children:[(0,$.jsx)(`span`,{children:kd(f,o)}),(0,$.jsx)(`span`,{children:t?m||c?o(`desktop.previewUnavailable`):g?o(`desktop.updated`,{seconds:Math.max(0,Math.floor((v-g)/1e3))}):o(`desktop.waiting`):o(`desktop.paused`)})]}),(m||c)&&(0,$.jsxs)(`div`,{className:`remote-desktop-error`,role:`status`,children:[m||c,(0,$.jsx)(`button`,{className:`btn`,onClick:l,children:o(`desktop.retry`)})]})]})}var Hw=null,Uw=new Set;function Ww(){for(let e of Uw)e()}function Gw(e){if(!e){Hw!==null&&(Hw=null,Ww());return}let t=!!(Hw&&Hw.roomId===e.roomId),n=t&&Hw?Hw.activeRightTab:e.attentionCount>0?`deliveries`:`files`;Hw&&t&&Hw.detail===e.detail&&Hw.devices===e.devices&&Hw.members===e.members&&Hw.conversations===e.conversations&&Hw.attentionCount===e.attentionCount&&Hw.disabled===e.disabled&&Hw.conversationError===e.conversationError&&Hw.activeRightTab===n||(Hw={...Hw,...e,activeRightTab:n},Ww())}function Kw(){return Hw}function qw(){return(0,Q.useSyncExternalStore)(e=>(Uw.add(e),()=>Uw.delete(e)),Kw,Kw)}function Jw(e,t){let n=new Map;for(let r of e?.bots??[]){if(!e?.room.botIds.includes(r.id)||!r.deviceId)continue;let i=n.get(r.deviceId);if(!i){let e=t.find(e=>e.id===r.deviceId);i={id:r.deviceId,name:Dd(e?.name,e?.remark,r.deviceName||r.deviceId),online:e?.online===!0,members:[]},n.set(i.id,i)}i.members.push(r)}return[...n.values()]}function Yw({group:e,visible:t}){let n=X(),r=(0,Q.useSyncExternalStore)(Ld,Rd),i=(0,Q.useRef)(r?.revision),[a,o]=(0,Q.useState)(),[s,c]=(0,Q.useState)(!1),[l,u]=(0,Q.useState)(0),[d,f]=(0,Q.useState)(!1),[p,m]=(0,Q.useState)(null),[h,g]=(0,Q.useState)(!document.hidden),_=t&&h&&!d&&!e.disabled,v=(e.detail?.bots??[]).filter(t=>e.detail?.room.botIds.includes(t.id)),y=Jw(e.detail,a?.devices??[]),b=p?y.filter(e=>e.members.some(e=>e.id===p)):y;(0,Q.useEffect)(()=>{let e=()=>g(!document.hidden);return document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[]),(0,Q.useEffect)(()=>{if(!_)return;let e=new AbortController,t;async function n(){try{let t=async t=>{let n=await fetch(W(j(`/api/device-center/${t}`)),{credentials:`same-origin`,signal:AbortSignal.any([e.signal,AbortSignal.timeout(15e3)])});if(!n.ok)throw Error(`Group desktop directory unavailable`);return n.json()},[n,r]=await Promise.all([t(`chat-status`),t(`devices`)]);if(typeof n.hubUrl!=`string`||!Array.isArray(r.devices))throw Error(`Invalid directory`);let i=r.devices.filter(e=>e&&typeof e.id==`string`&&typeof e.name==`string`&&typeof e.online==`boolean`&&(e.remark==null||typeof e.remark==`string`));e.signal.aborted||(o({hubUrl:n.hubUrl,deviceId:n.deviceId,devices:i}),c(!1))}catch{e.signal.aborted||c(!0)}finally{e.signal.aborted||(t=setTimeout(n,15e3))}}return n(),()=>{e.abort(),clearTimeout(t)}},[_,l]),(0,Q.useEffect)(()=>{if(!r||r.revision===i.current||!e.detail||(i.current=r.revision,r.groupId))return;let t=v.filter(e=>e.deviceId===r.id),n=t.find(e=>e.name===r.name)??t[0];n&&m(n.id)},[r,e.detail,v]),(0,Q.useEffect)(()=>{p&&!v.some(e=>e.id===p&&e.deviceId)&&m(null),r?.groupId===e.roomId&&!y.some(e=>e.id===r.id)&&zd(r)},[p,v,y,r,e.roomId]),(0,Q.useEffect)(()=>()=>{let t=Rd();t?.groupId===e.roomId&&zd(t)},[e.roomId]);function x(t){m(t),r?.groupId===e.roomId&&r.mode===`live`&&Bd(r,`preview`)}async function S(t){if(a&&t.online&&!e.disabled)try{await Hd(t.id,a.hubUrl,!0,n,!1,t.name,{mode:`live`,local:t.id===a.deviceId,groupId:e.roomId})}catch{c(!0)}}return(0,$.jsxs)(`section`,{className:`desktop-preview group-desktop`,"aria-label":n(`desktop.groupTitle`),children:[(0,$.jsxs)(`div`,{className:`desktop-preview-heading`,children:[(0,$.jsx)(`strong`,{title:e.detail?.room.name,children:n(`desktop.groupTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":n(d?`desktop.expand`:`desktop.collapse`),onClick:()=>f(!d),children:d?`+`:`−`})]}),!d&&(0,$.jsxs)($.Fragment,{children:[s&&(0,$.jsxs)(`div`,{className:`remote-desktop-error`,role:`status`,children:[n(`desktop.devicesUnavailable`),` `,(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>u(e=>e+1),children:n(`desktop.retry`)})]}),!a&&!s&&(0,$.jsx)(`p`,{className:`group-desktop-empty`,role:`status`,children:n(`loading`)}),a&&(0,$.jsxs)(`div`,{className:`group-desktop-grid${p||y.length===1?` is-single`:``}`,children:[b.map(e=>(0,$.jsx)(Xw,{target:e,active:_,directory:a,selected:p,access:r,onOpen:()=>void S(e)},e.id)),!b.length&&(0,$.jsx)(`p`,{className:`group-desktop-empty`,children:n(`desktop.noDevices`)})]}),(0,$.jsxs)(`div`,{className:`group-desktop-members`,role:`group`,"aria-label":n(`desktop.groupMembers`),children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-pressed":p===null,onClick:()=>x(null),children:n(`desktop.groupAll`)}),v.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-pressed":p===e.id,disabled:!e.deviceId,title:e.deviceId?e.name:n(`desktop.groupNoDevice`),"aria-label":n(`desktop.groupSelect`,{name:e.name}),onClick:()=>x(e.id),children:e.name},e.id))]})]})]})}function Xw({target:e,active:t,directory:n,selected:r,access:i,onOpen:a}){let o=X(),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(!s.current)return;let e=new IntersectionObserver(([e])=>l(e.isIntersecting),{threshold:.01});return e.observe(s.current),()=>e.disconnect()},[]);let u=i?.id===e.id&&i.mode===`live`,d=e.members.filter(e=>!r||e.id===r).map(e=>e.name).join(` · `),f={id:e.id,hubUrl:n.hubUrl,name:e.name,revision:0,mode:`preview`,local:n.deviceId===e.id};return(0,$.jsxs)(`article`,{className:`group-desktop-card`,ref:s,"aria-label":e.name,children:[(0,$.jsxs)(`div`,{className:`group-desktop-card-heading`,children:[(0,$.jsx)(`strong`,{title:d,children:d}),(0,$.jsx)(`span`,{title:e.name,children:e.name})]}),u?(0,$.jsxs)(`div`,{className:`group-desktop-placeholder`,children:[(0,$.jsx)(`span`,{children:o(`desktop.operating`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>Bd(i,`preview`),children:o(`desktop.back`)})]}):e.online?t&&c?(0,$.jsx)(Vw,{access:f,active:!0,collapsed:!1,height:r?220:120,onOpen:a,label:d}):(0,$.jsxs)(`div`,{className:`group-desktop-placeholder`,children:[(0,$.jsx)(se,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:o(`desktop.paused`)})]}):(0,$.jsxs)(`div`,{className:`group-desktop-placeholder`,children:[(0,$.jsx)(se,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:o(`deviceHubOffline`)})]})]})}function Zw({visible:e}){let t=(0,Q.useSyncExternalStore)(Ld,Rd),n=X(),[r,i]=(0,Q.useState)(!1),a=qw();return a?(0,$.jsx)(Yw,{group:a,visible:e},a.roomId):t?(0,$.jsx)(Qw,{access:t,visible:e},`${t.revision}:${t.mode}`):Ad()?(0,$.jsxs)(`section`,{className:`desktop-preview`,children:[(0,$.jsx)(`button`,{className:`btn`,onClick:()=>{i(!1),jd(n,n(`desktop.currentDevice`)).catch(()=>i(!0))},children:n(`desktop.showCurrent`)}),r&&(0,$.jsx)(`p`,{role:`alert`,children:n(`desktop.devicesUnavailable`)})]}):null}function Qw({access:e,visible:t}){let n=X(),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(200),s=(0,Q.useRef)(null);function c(e){e.button===0&&(s.current={y:e.clientY,height:a},e.currentTarget.setPointerCapture(e.pointerId),e.preventDefault())}return(0,$.jsxs)(`section`,{className:`desktop-preview`,"aria-label":n(`desktop.title`),children:[(0,$.jsxs)(`div`,{className:`desktop-preview-heading`,children:[(0,$.jsxs)(`strong`,{title:e.name||e.id,children:[n(`desktop.title`),` · `,e.name||e.id]}),(0,$.jsx)(hw,{access:e,visible:t}),(0,$.jsx)(`button`,{className:`btn`,"aria-label":n(r?`desktop.expand`:`desktop.collapse`),onClick:()=>i(!r),children:r?`+`:`−`}),(0,$.jsx)(`button`,{className:`btn`,"aria-label":n(`desktop.close`),onClick:()=>zd(e),children:`×`})]}),e.mode===`preview`?(0,$.jsx)(Vw,{access:e,active:t&&!r,collapsed:r,height:a}):(0,$.jsxs)(`div`,{className:`desktop-preview-live`,children:[(0,$.jsx)(`span`,{children:n(`desktop.operating`)}),(0,$.jsx)(`button`,{className:`btn`,onClick:()=>Bd(e,`preview`),children:n(`desktop.back`)})]}),!r&&e.mode===`preview`&&(0,$.jsx)(`div`,{className:`desktop-preview-sash`,role:`separator`,"aria-label":n(`desktop.resize`),"aria-orientation":`horizontal`,"aria-valuemin":120,"aria-valuemax":400,"aria-valuenow":a,tabIndex:0,onPointerDown:c,onPointerMove:e=>{s.current&&o(Math.max(120,Math.min(400,s.current.height+e.clientY-s.current.y)))},onLostPointerCapture:()=>{s.current=null},onKeyDown:e=>{(e.key===`ArrowUp`||e.key===`ArrowDown`)&&(e.preventDefault(),o(t=>Math.max(120,Math.min(400,t+(e.key===`ArrowUp`?-20:20)))))}})]})}var $w=`@root`;function eT(e){let t=e.endsWith(`/`)&&e!==`/`?e.slice(0,-1):e,n=t.lastIndexOf(`/`);return n<0?``:n===0?`/`:t.slice(0,n)}function tT(e){return e===`@root`||e===`/`||/^[A-Za-z]:$/.test(e)}function nT(e){return e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)}function rT({nodes:e,depth:t,collapsed:n,onToggle:r,onOpenDir:i,onOpenFile:a}){return(0,$.jsx)($.Fragment,{children:e.map(e=>(0,$.jsxs)(Q.Fragment,{children:[e.type===`dir`?(0,$.jsxs)(`div`,{className:`file-item dir`,style:{paddingLeft:4+t*12},children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,style:{padding:2,flex:`none`},onClick:()=>r(e.path),"aria-label":e.path,children:n.includes(e.path)?(0,$.jsx)(At,{"aria-hidden":`true`}):(0,$.jsx)(D,{"aria-hidden":`true`})}),(0,$.jsxs)(`button`,{type:`button`,className:`file-dir-main`,onClick:()=>i(e.path),title:e.path,children:[(0,$.jsx)(Ee,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,style:e.matched?void 0:{opacity:.65},children:e.name})]})]}):(0,$.jsxs)(`button`,{type:`button`,className:`file-item`,style:{paddingLeft:8+t*12},onClick:()=>a(e.path,e.name),title:e.path,children:[(0,$.jsx)(Ce,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:e.name})]}),e.type===`dir`&&!n.includes(e.path)&&(0,$.jsx)(rT,{nodes:e.children,depth:t+1,collapsed:n,onToggle:r,onOpenDir:i,onOpenFile:a})]},e.path||e.name))})}function iT({currentPath:e,files:t,fileSearch:n,showHiddenFiles:r,panelSend:i}){let[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(!1),l=(0,Q.useRef)(0),[u,d]=(0,Q.useState)([]),f=a.trim();(0,Q.useEffect)(()=>{if(f===``)return;let t=setTimeout(()=>{l.current+=1,i({type:`search_files`,reqId:l.current,query:f,scope:e})},300);return()=>clearTimeout(t)},[f,e,i]);let p=(f!==``&&n&&n.reqId===l.current?n.results:[]).filter(t=>t.path!==e&&(e===``||e===`@root`||t.path===e||(e===`/`?t.path.startsWith(`/`):t.path.startsWith(`${e}/`))));return(0,Q.useEffect)(()=>{d([])},[f,e]),{fileFilter:a,setFileFilter:o,pathSearching:s,setPathSearching:c,collapsedSearchDirs:u,fileFilterQuery:f,searchTree:(0,Q.useMemo)(()=>{if(f===``)return[];let n={name:``,path:``,type:`dir`,matched:!1,children:[]},i=e!==``&&e!==`@root`?e===`/`?`/`:`${e}/`:``,a=f.toLowerCase(),o=(e,t)=>{let r=(i!==``&&e.startsWith(i)?e.slice(i.length):e).split(`/`).filter(Boolean);if(r.length===0)return;let a=n,o=i===``||i===`/`?``:i.slice(0,-1);r.forEach((e,n)=>{let s=n===r.length-1;o=o===``?i===`/`?`/${e}`:e:`${o}/${e}`;let c=a.children.find(t=>t.name===e);c?s&&t===`dir`&&(c.type=`dir`):(c={name:e,path:o,type:s?t:`dir`,matched:!1,children:[]},a.children.push(c)),s&&(c.matched=!0),a=c})};if(t&&t.path===e)for(let e of jw(t.entries,r))e.type===`file`&&e.name.toLowerCase().includes(a)&&o(e.path,e.type);for(let e of p)o(e.path,e.type);let s=e=>{e.children.sort((e,t)=>e.type===t.type?e.name.localeCompare(t.name):e.type===`dir`?-1:1),e.children.forEach(s)};return s(n),n.children},[p,e,t,r,f]),toggleSearchDir:(0,Q.useCallback)(e=>{d(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e])},[])}}function aT({panelSend:e,onNotice:t}){let n=X(),r=mn(`workspaceUploadMaxMb`)*1024*1024,[i,a]=(0,Q.useState)([]),o=mn(`status`);(0,Q.useEffect)(()=>{o!==`open`&&a(e=>e.some(e=>e.phase===`waiting`)?e.map(e=>e.phase===`waiting`?{...e,phase:`unknown`}:e):e)},[o]);let s=(0,Q.useRef)(new Map);return(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;if(!t||typeof t!=`object`)return;let{uploadId:n,ok:r,error:i}=t;typeof n==`string`&&typeof r==`boolean`&&a(e=>e.map(e=>e.id===n&&(e.phase===`waiting`||e.phase===`unknown`)?{...e,phase:r?`success`:`error`,error:typeof i==`string`?i:void 0}:e))};window.addEventListener(`pi:file-upload-result`,e);let t=s.current;return()=>{window.removeEventListener(`pi:file-upload-result`,e);for(let e of t.values())e.onload=e.onprogress=e.onerror=e.onabort=null,e.abort();t.clear()}},[]),{fileUploads:i,setFileUploads:a,uploadFilesTo:(0,Q.useCallback)((i,o)=>{for(let c of o){if(c.size>r){t(`warning`,n(`fileTooLarge`,{name:c.name,size:r/1024/1024}));continue}let o=crypto.randomUUID(),l=e=>a(t=>t.map(t=>t.id===o?{...t,...e}:t));a(e=>[...e,{id:o,name:c.name,dir:i,phase:`reading`,percent:0}]);let u=new FileReader;s.current.set(o,u);let d=()=>{s.current.delete(o),l({phase:`error`,error:n(`fileUploadReadFailed`,{name:c.name})})};u.onprogress=e=>{e.lengthComputable&&e.total>0&&l({percent:Math.min(100,Math.floor(e.loaded/e.total*100))})},u.onerror=d,u.onabort=d,u.onload=()=>{if(s.current.delete(o),typeof u.result!=`string`||!u.result.includes(`,`)){d();return}let t=u.result.slice(u.result.indexOf(`,`)+1);l({phase:`waiting`,percent:100});try{if(e({type:`upload_file`,dirPath:i,name:c.name,data:t,uploadId:o}))return}catch{}l({phase:`error`,error:n(`fileUploadSendFailed`,{name:c.name})})};try{u.readAsDataURL(c)}catch{d()}}},[e,t,n,r])}}function oT(e){if(!e||typeof e!=`string`)return!1;let t=e.trim();return!(!t||t===`@root`||t===`/`||t===`.`||t===`..`||t.startsWith(`/`)||t.startsWith(`\\`)||/^[A-Za-z]:($|[\\/])/.test(t)||t.split(/[\\/]/).some(e=>e===`..`))}function sT({currentPath:e,cwd:t,workspaceRoots:n,uiContextFile:r,quickAskReferenceMenus:i,panelSend:a,onNotice:o,onPreview:s,onAttach:c,onOpenInEditor:l,openDir:u,copyText:d,absPathOf:f,transferAbsPathOf:p,toProjectPath:m,uploadFilesTo:h}){let g=X(),_=(0,Q.useRef)(null),[v,y]=(0,Q.useState)(null),b=(0,Q.useRef)(null),x=(0,Q.useCallback)(()=>{let e=_.current?.project;e&&a({type:`set_cwd`,path:e.path})},[a]),S=(0,Q.useCallback)(()=>{b.current&&(b.current.value=``),b.current?.click()},[]),[C,w]=(0,Q.useState)(null),[T,E]=(0,Q.useState)(null),[D,O]=(0,Q.useState)(``),[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(``),N=(0,Q.useCallback)((e,t)=>{Ey(e,t).then(e=>{e.ok||e.cancelled||o(`error`,g(`downloadFailed`,{error:e.error===`FILE_NOT_FOUND`?g(`fileNotFoundShort`):e.error}))})},[o,g]),P=(0,Q.useCallback)(()=>{let e=_.current?.target;e&&e.kind!==`list`&&!tT(e.id)&&(A(null),O(e.label),E(e.id))},[]),F=(0,Q.useCallback)(()=>{if(!T)return;let e=D.trim();E(null),e&&a({type:`file_rename`,path:T,newName:e})},[T,D,a]),I=(0,Q.useCallback)(t=>{let n=_.current?.dir??e;E(null),M(``),A({dir:n,kind:t})},[e]),L=(0,Q.useCallback)(()=>{if(!k)return;let e=j.trim();A(null),e&&a({type:`file_create`,dir:k.dir,name:e,kind:k.kind})},[k,j,a]),R=(0,Q.useCallback)(()=>{let e=_.current?.target;e&&e.kind!==`list`&&!tT(e.id)&&window.confirm(g(`fileDeleteConfirm`,{name:e.label}))&&(C?.src===e.id&&w(null),T===e.id&&E(null),a({type:`file_delete`,path:e.id}))},[a,g,C,T]),z=(0,Q.useCallback)(()=>{let e=_.current?.target;e&&e.kind!==`list`&&!tT(e.id)&&a({type:`file_copy`,src:e.id,destDir:eT(e.id)})},[a]),B=(0,Q.useCallback)(e=>{let t=_.current?.target;t&&t.kind!==`list`&&!tT(t.id)&&w({src:t.id,cut:e})},[]),V=(0,Q.useCallback)(()=>{if(!C)return;let t=_.current?.dir??e;C.cut?(a({type:`file_copy`,src:C.src,destDir:t,move:!0}),w(null)):a({type:`file_copy`,src:C.src,destDir:t})},[C,a,e]),H=(0,Q.useCallback)(()=>{a({type:`list_files`,path:e===``?void 0:e})},[a,e]),ee=(0,Q.useCallback)(e=>{a({type:`set_workspace_roots`,roots:e})},[a]),U=(0,Q.useCallback)(()=>{let e=_.current?.target;if(!e||e.kind!==`dir`)return;let t=m(e.id);t&&!n.includes(t)&&ee([...n,t])},[n,m,ee]),W=(0,Q.useCallback)(t=>{h(_.current?.dir??e,Array.from(t.target.files??[]))},[h,e]),G=(0,Q.useCallback)(t=>{let n=_.current?.target;switch(t.id){case`host:file-compress`:case`host:file-extract`:case`host:file-compress-download`:case`host:file-upload-folder`:{if(!n)break;let r=t.id===`host:file-compress`?`compress`:t.id===`host:file-extract`?`extract`:t.id===`host:file-compress-download`?`download`:`upload`;y({action:r,path:p(n.id),dir:p(r===`upload`?_.current?.dir??e:eT(n.id))});break}case`host:file-open-project`:x();break;case`host:file-upload`:S();break;case`host:file-add-root`:U();break;case`host:file-open`:n?.kind===`file`&&s(n.id,n.label);break;case`host:file-open-in-editor`:n?.kind===`file`&&oT(n.id)&&l?.(n.id);break;case`host:file-enter`:n?.kind===`dir`&&u(n.id);break;case`host:file-download`:n?.kind===`file`&&N(n.id,n.label);break;case`host:file-reveal`:n&&a({type:`file_reveal`,path:n.id});break;case`host:file-open-default`:n?.kind===`file`&&a({type:`file_open_default`,path:n.id});break;case`host:file-attach-ref`:n?.kind===`file`&&c(n.id,n.label,`reference`);break;case`host:file-attach-folder`:n?.kind===`dir`&&c(n.id,n.label,`reference`,!0);break;case`host:file-new-file`:I(`file`);break;case`host:file-new-dir`:I(`dir`);break;case`host:file-paste`:V();break;case`host:file-rename`:P();break;case`host:file-duplicate`:z();break;case`host:file-cut`:B(!0);break;case`host:file-copy`:B(!1);break;case`host:file-copy-name`:n&&n.kind!==`list`&&d(n.label,`name:${n.id}`);break;case`host:file-copy-path`:n&&n.kind!==`list`&&d(f(n.id),`path:${n.id}`);break;case`host:file-copy-rel`:n&&n.kind!==`list`&&d(n.id,`rel:${n.id}`);break;case`host:file-refresh`:H();break;case`host:file-delete`:R()}},[x,e,S,U,s,l,u,c,d,f,p,N,a,I,V,P,z,B,H,R]);return{transfer:v,setTransfer:y,fileInput:b,clipboard:C,renamingPath:T,setRenamingPath:E,renameDraft:D,setRenameDraft:O,creating:k,setCreating:A,createDraft:j,setCreateDraft:M,downloadEntry:N,submitRename:F,submitCreate:L,refreshList:H,setRoots:ee,uploadPicked:W,openFileMenu:(0,Q.useCallback)((a,o)=>{let s=o.kind===`dir`?m(o.id):null,c={target:o,dir:o.kind===`dir`?o.id:e,project:s?{path:s,name:o.label}:null},u=o.kind,d=u===`file`,p=u===`dir`,h=u===`list`,v=!h&&tT(o.id),y=!h&&nT(o.id),b=e===$w,x=!h&&o.id!==`@root`&&(t||y)?{kind:p?`directory`:`file`,path:f(o.id),cwd:t}:void 0,S=(r??[]).map(r=>{if(r.source!==`host`)return r;switch(r.id){case`host:file-quick-ask`:return i&&x?r:{...r,hidden:!0};case`host:file-upload-folder`:return b?{...r,hidden:!0}:r;case`host:file-compress`:case`host:file-compress-download`:return!h&&!v?r:{...r,hidden:!0};case`host:file-extract`:return d&&ww(o.label)?r:{...r,hidden:!0};case`host:file-upload`:return b?{...r,hidden:!0}:{...r,label:c.dir===e?g(`uploadToCurrentDir`):g(`uploadToFolder`)};case`host:file-open-project`:return s?r:{...r,hidden:!0};case`host:file-add-root`:return s&&s!==t&&!n.includes(s)?r:{...r,hidden:!0};case`host:file-open`:case`host:file-download`:case`host:file-open-default`:case`host:file-attach-ref`:return d?r:{...r,hidden:!0};case`host:file-open-in-editor`:return d&&l&&oT(o.id)?r:{...r,hidden:!0};case`host:file-reveal`:return!b&&o.id!==`@root`?r:{...r,hidden:!0};case`host:file-enter`:case`host:file-attach-folder`:return p?r:{...r,hidden:!0};case`host:file-new-file`:case`host:file-new-dir`:return!d&&!b?r:{...r,hidden:!0};case`host:file-paste`:return!d&&!b&&C?r:{...r,hidden:!0};case`host:file-rename`:case`host:file-duplicate`:case`host:file-cut`:case`host:file-copy`:case`host:file-delete`:return!h&&!v?r:{...r,hidden:!0};case`host:file-copy-name`:case`host:file-copy-path`:return h?{...r,hidden:!0}:r;case`host:file-copy-rel`:return!h&&!y?r:{...r,hidden:!0};case`host:file-refresh`:return h?r:{...r,hidden:!0};default:return r}});Hf(S).length!==0&&(a.preventDefault(),a.stopPropagation(),_.current=c,jf({x:a.clientX,y:a.clientY,slot:`contextmenu.file`,target:o,entries:S,onHostAction:e=>{e.id===`host:file-quick-ask`?x&&t2({reference:x}):G(e)}}))},[r,i,e,m,f,g,G,t,n,C,l])}}var cT=`pi-web-ui:rp-sizes`,lT=`pi-web-ui:files-show-hidden`,uT={files:4,widgets:1},dT=120,fT=56;function pT(e,t){return t?Math.max(0,t.getBoundingClientRect().top-e.getBoundingClientRect().top):32}var mT=`files`,hT=`scm`,gT=[],_T=()=>{},vT=(0,Q.memo)(function({desktopVisible:e=!0,files:t,fileSearch:n,fileChanged:r,widgets:i,panelSend:a,onAttach:o,onPreview:s,onNotice:c,collapsible:l,onToggleCollapse:u,uiRightPanelTabs:d,uiContextFile:f,scmTab:p,onActiveTabChange:h,quickAskReferenceMenus:g=!0,plugins:_,pluginsEpoch:v,send:b,onOpenInEditor:x}){let S=X(),C=_??gT,w=mn(`cwd`),T=mn(`workspaceRoots`),E=mn(`homeDir`),D=mn(`desktopDir`),[O,k]=(0,Q.useState)(``),[A,j]=(0,Q.useState)(null),[M,N]=(0,Q.useState)(!1),P=(0,Q.useRef)(null),I=(0,Q.useRef)(null),[L,R]=(0,Q.useState)(()=>{try{return O5(localStorage.getItem(cT),uT)}catch{return{...uT}}});(0,Q.useEffect)(()=>{try{localStorage.setItem(cT,JSON.stringify(L))}catch{}},[L]);let[B,V]=(0,Q.useState)(()=>{try{return localStorage.getItem(lT)===`1`}catch{return!1}}),{fileFilter:H,setFileFilter:ee,pathSearching:U,setPathSearching:W,collapsedSearchDirs:G,fileFilterQuery:K,searchTree:q,toggleSearchDir:te}=iT({currentPath:O,files:t,fileSearch:n,showHiddenFiles:B,panelSend:a});(0,Q.useEffect)(()=>{try{localStorage.setItem(lT,B?`1`:`0`)}catch{}},[B]);let ne=i.some(e=>e.lines.length>0),re=(0,Q.useCallback)(e=>{e.preventDefault();let t=P.current;if(!t)return;let n=e.currentTarget,r=e.clientY,i={above:L.files,below:L.widgets},a=Math.max(120,t.clientHeight-pT(t,I.current));n.classList.add(`dragging`),document.body.classList.add(`rp-resizing`);let o=e=>{let{above:t,below:n}=k5({start:i,deltaPx:e.clientY-r,availablePx:a,totalWeight:i.above+i.below,minAbovePx:dT,minBelowPx:fT});R({files:t,widgets:n})},s=()=>{window.removeEventListener(`pointermove`,o),window.removeEventListener(`pointerup`,s),n.classList.remove(`dragging`),document.body.classList.remove(`rp-resizing`)};window.addEventListener(`pointermove`,o),window.addEventListener(`pointerup`,s)},[L.files,L.widgets]),J=(0,Q.useRef)(null),ie=(0,Q.useRef)(0),ae=(0,Q.useCallback)(e=>{J.current=e,e&&(e.scrollTop=ie.current)},[]),[oe,Y]=(0,Q.useState)(null),ce=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{ce.current&&clearTimeout(ce.current)},[]);let le=(0,Q.useCallback)(e=>{Y(e),ce.current&&clearTimeout(ce.current),ce.current=setTimeout(()=>Y(null),1200)},[]),ue=(0,Q.useCallback)((e,t)=>{e&&Kn(e).then(e=>{e?le(t):c(`error`,S(`slashCopyFailed`))})},[le,c,S]),de=(0,Q.useCallback)(e=>{if(!e)return w;if(/^[A-Za-z]:$/.test(e))return`${e}/`;if(e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e))return e;let t=w.replace(/\\/g,`/`).replace(/\/+$/,``);return t?`${t}/${e}`:e},[w]),fe=(0,Q.useCallback)(e=>{if(Ii(w)){let t=Li(w),n=t?t.remotePath:`/`;if(!e)return n;if(e.startsWith(`/`))return e;let r=n.replace(/\/+$/,``)||`/`;return r===`/`?`/${e}`:`${r}/${e}`}return de(e)},[w,de]),pe=(0,Q.useCallback)(e=>!e||e===`@root`?null:e.startsWith(`/`)||/^[A-Za-z]:([/]|$)/.test(e)?e:`${w.replace(/\\/g,`/`).replace(/\/+$/,``)}/${e}`,[w]),{fileUploads:me,setFileUploads:he,uploadFilesTo:_e}=aT({panelSend:a,onNotice:c}),ye=(0,Q.useRef)(()=>{}),{transfer:be,setTransfer:xe,fileInput:Se,clipboard:we,renamingPath:Te,setRenamingPath:De,renameDraft:Oe,setRenameDraft:ke,creating:Ae,setCreating:je,createDraft:Me,setCreateDraft:Ne,downloadEntry:Pe,submitRename:Fe,submitCreate:Ie,refreshList:Le,setRoots:Re,uploadPicked:ze,openFileMenu:Be}=sT({currentPath:O,cwd:w,workspaceRoots:T,uiContextFile:f,quickAskReferenceMenus:g,panelSend:a,onNotice:c,onPreview:s,onAttach:o,onOpenInEditor:x,openDir:e=>ye.current(e),copyText:ue,absPathOf:de,transferAbsPathOf:fe,toProjectPath:pe,uploadFilesTo:_e}),Ve=(e,t,n,r)=>(0,$.jsx)(`input`,{autoFocus:!0,className:`session-rename-input`,value:e,placeholder:S(`fileNamePlaceholder`),onClick:e=>e.stopPropagation(),onChange:e=>t(e.target.value),onKeyDown:e=>{e.stopPropagation(),e.key===`Enter`&&!e.nativeEvent.isComposing?n():e.key===`Escape`&&r()},onBlur:r}),[He,Ue]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(!He)return;let e=e=>{e.target?.closest(`.root-picker`)||Ue(!1)},t=e=>{e.key===`Escape`&&Ue(!1)};return window.addEventListener(`mousedown`,e,!0),window.addEventListener(`keydown`,t),()=>{window.removeEventListener(`mousedown`,e,!0),window.removeEventListener(`keydown`,t)}},[He]);let We=e=>Array.from(e.dataTransfer?.types??[]).includes(`Files`),Ge=(0,Q.useCallback)(()=>{J.current?.querySelectorAll(`.file-item.drop-target`).forEach(e=>e.classList.remove(`drop-target`)),J.current?.classList.remove(`drop-root`)},[]),Ke=(0,Q.useCallback)(e=>{if(Ge(),e==null)return;let t=J.current?.querySelector(`.file-item[data-path="${CSS.escape(e)}"]`);t?t.classList.add(`drop-target`):J.current?.classList.add(`drop-root`)},[Ge]),qe=e=>{let t=e instanceof Element?e.closest(`.file-item`):null;return t?.dataset.type===`dir`?t.dataset.path??O:O},Je=(0,Q.useCallback)(()=>{let e=document.querySelector(`.app`);e&&e.dispatchEvent(new DragEvent(`dragleave`,{bubbles:!0}))},[]),Ye=(0,Q.useRef)(0),Xe=(0,Q.useRef)(void 0),Ze=(0,Q.useCallback)((e,t)=>{let n=++Ye.current;k(e),t?.silent||N(!0),a({type:`list_files`,path:e===``?void 0:e})||Ye.current===n&&N(!1)},[a]),Qe=(0,Q.useCallback)(e=>{let t=T.filter(t=>t!==e);Re(t),(O===e||O.startsWith(`${e}/`))&&Ze(``)},[T,Re,O,Ze]);(0,Q.useEffect)(()=>{t&&t.path===O&&N(!1)},[t,O]),(0,Q.useEffect)(()=>{if(!w){Xe.current=w,N(!1);return}if(w!==Xe.current){let e=Xe.current===void 0;Xe.current=w,e?Ze(``,{silent:!0}):k(``)}let e=setInterval(()=>{document.visibilityState!==`hidden`&&Ze(O,{silent:!0})},1e4);return()=>clearInterval(e)},[w,O,Ze]),(0,Q.useEffect)(()=>{r&&r.path===O&&Ze(O,{silent:!0})},[r,O,Ze]);let $e=e=>Ze(e);ye.current=$e,(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;t&&typeof t.path==`string`&&(window.dispatchEvent(new CustomEvent(`pi:select-slot-tab`,{detail:{group:`rightpanel`,id:mT}})),Ze(t.path))};return window.addEventListener(`pi:open-folder`,e),()=>window.removeEventListener(`pi:open-folder`,e)},[Ze]);let et=()=>{t?.parent!==null&&t?.parent!==void 0&&Ze(t.parent)},tt=(()=>{if(O===``||O===`@root`)return[];let e=O.split(`/`).filter(e=>!!e&&e!==`@root`);return O.startsWith(`/`)?[{label:`/`,path:`/`},...e.map((t,n)=>({label:t,path:`/`+e.slice(0,n+1).join(`/`)}))]:e.map((t,n)=>({label:e[n],path:e.slice(0,n+1).join(`/`)}))})(),nt=O.startsWith(`/`)||O===`@root`?tt:[{label:S(`rootDir`),path:``},...tt],it=O===``?w||S(`rootDir`):O,at=[];for(let e of d??[]){if(e.source===`host`||e.hidden||e.kind===`divider`)continue;let t=C.find(t=>t.id===e.source.slice(7));t&&at.push({id:e.id,label:e.label,icon:e.icon,...e.iconSvg?{iconSvg:e.iconSvg}:{},hint:e.hint,pluginPage:{plugin:t,entry:e}})}let ct=(d??[]).some(e=>e.id===`host:right-files`&&e.hidden),lt=(d??[]).some(e=>e.id===`host:right-scm`&&e.hidden);return(0,$.jsxs)(`aside`,{className:`panel panel-right`,ref:P,children:[l&&u&&(0,$.jsx)(`button`,{type:`button`,className:`panel-collapse-btn`,title:S(`collapsePanel`),onClick:u,children:(0,$.jsx)(At,{})}),(0,$.jsx)(Zw,{visible:e}),(0,$.jsx)(`div`,{ref:I,style:{display:`flex`,flexDirection:`column`,flex:ne?`${L.files} 1 0`:`1 1 0`,minHeight:ne?dT:0},children:(0,$.jsx)(Bw,{storageKey:`rightpanel`,epoch:v??0,send:b??_T,onActiveChange:h,tabs:(e=>{let t=(d??[]).filter(e=>!e.hidden);if(t.length===0)return e;let n=new Map(t.map((e,t)=>[e.id,t])),r={[mT]:`host:right-files`,[hT]:`host:right-scm`},i=e=>n.get(r[e]??e)??1e9;return[...e].sort((e,t)=>i(e.id)-i(t.id))})([...ct?[]:[{id:mT,label:S(`openFiles`),iconNode:(0,$.jsx)(tp,{}),iconOnly:!0,element:(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{className:`panel-crumbs files-toolbar`,children:[(0,$.jsx)(bn,{className:`crumb ${O===`@root`?`active`:``}`,tip:S(`computer`),onClick:()=>Ze($w),children:(0,$.jsx)(ge,{})}),E!==``&&(0,$.jsx)(bn,{className:`crumb ${O===E||O.startsWith(`${E}/`)?`active`:``}`,tip:S(`homeDir`),onClick:()=>Ze(E),children:(0,$.jsx)(kt,{})}),D!==``&&(0,$.jsx)(bn,{className:`crumb ${O===D||O.startsWith(`${D}/`)?`active`:``}`,tip:S(`desktopDir`),onClick:()=>Ze(D),children:(0,$.jsx)(se,{})}),(0,$.jsx)(bn,{className:`crumb ${B?`active`:``}`,tip:S(B?`filesHideHidden`:`filesShowHidden`),"aria-pressed":B,onClick:()=>V(e=>!e),children:B?(0,$.jsx)(ve,{}):(0,$.jsx)(rt,{})}),(0,$.jsx)(bn,{className:`crumb ${U?`active`:``}`,tip:S(`filesFilterPlaceholder`),"aria-pressed":U,onClick:()=>{U&&ee(``),W(e=>!e)},children:(0,$.jsx)(mt,{})}),(0,$.jsx)(xn,{text:S(`filesHelp`)}),T.length>0&&(0,$.jsxs)(`div`,{className:`root-picker`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`crumb root-picker-trigger`,"aria-haspopup":`menu`,"aria-expanded":He,title:S(`workspaceRoots`),onClick:()=>Ue(e=>!e),children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`span`,{className:`root-picker-label`,children:S(`workspaceRoots`)}),(0,$.jsx)(`span`,{className:`set-count`,children:T.length+1}),`▾`]}),He&&(0,$.jsxs)(`div`,{className:`root-picker-menu`,role:`menu`,children:[(0,$.jsx)(`div`,{className:`root-picker-row`,children:(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:O===``?`root-picker-item active`:`root-picker-item`,title:w,onClick:()=>{Ue(!1),Ze(``)},children:[S(`rootDir`),(0,$.jsx)(`span`,{className:`root-picker-path`,children:w})]})}),T.map(e=>(0,$.jsxs)(`div`,{className:`root-picker-row`,children:[(0,$.jsx)(`button`,{type:`button`,role:`menuitem`,className:O===e?`root-picker-item active`:`root-picker-item`,title:e,onClick:()=>{Ue(!1),Ze(e)},children:(0,$.jsx)(`span`,{className:`root-picker-path`,children:e})}),(0,$.jsx)(`button`,{type:`button`,className:`root-picker-remove`,title:S(`removeWorkspaceRoot`),"aria-label":S(`removeWorkspaceRoot`),onClick:()=>Qe(e),children:(0,$.jsx)(Ct,{})})]},e)),(0,$.jsx)(`div`,{className:`root-picker-hint`,children:S(`workspaceRootsHint`)})]})]})]}),(0,$.jsx)(`div`,{className:`panel-crumbs files-pathrow`,style:{flexWrap:`nowrap`},children:U?(0,$.jsxs)(`span`,{className:`crumb file-filter-wrap`,style:{flex:1,display:`inline-flex`,alignItems:`center`,gap:6},children:[(0,$.jsx)(mt,{"aria-hidden":`true`}),(0,$.jsx)(`input`,{className:`file-filter-input`,autoFocus:!0,value:H,onChange:e=>ee(e.target.value),placeholder:S(`filesFilterPlaceholder`),"aria-label":S(`filesFilterPlaceholder`),onKeyDown:e=>{e.key===`Escape`&&(ee(``),W(!1))},style:{flex:1,minWidth:0,background:`transparent`,border:`none`,outline:`none`,color:`inherit`}}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,style:{padding:2},onClick:()=>{H===``?W(!1):ee(``)},"aria-label":S(`close`),title:S(`close`),children:(0,$.jsx)(Ct,{"aria-hidden":`true`})})]}):(0,$.jsx)($.Fragment,{children:(0,$.jsx)(`span`,{className:`file-path-text`,title:it,style:{flex:1,minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:nt.map((e,t)=>e===null?(0,$.jsxs)(`span`,{className:`crumb-seg`,style:{margin:`0 2px`},children:[`…`,(0,$.jsx)(At,{"aria-hidden":`true`})]},`ellipsis`):(0,$.jsxs)(`span`,{className:`crumb-seg`,children:[t>0&&(0,$.jsx)(At,{"aria-hidden":`true`}),(0,$.jsx)(`button`,{type:`button`,className:`crumb ${e.path===O?`active`:``}`,onClick:()=>Ze(e.path),title:e.path||it,children:e.label})]},e.path||`root`))})})}),(0,$.jsxs)(`div`,{ref:ae,className:`panel-body`,onScroll:e=>{ie.current=e.currentTarget.scrollTop},onContextMenu:e=>Be(e,{id:O,kind:`list`,label:O===``?S(`rootDir`):O===`@root`?S(`computer`):O}),onDragOver:e=>{We(e)&&(e.preventDefault(),e.stopPropagation(),e.dataTransfer.dropEffect=`copy`,Je(),Ke(qe(e.target)))},onDragLeave:e=>{e.relatedTarget&&e.currentTarget.contains(e.relatedTarget)||Ge()},onDrop:e=>{if(Ge(),!We(e))return;e.preventDefault(),e.stopPropagation(),Je();let t=Array.from(e.dataTransfer?.files??[]);t.length===0?c(`warning`,S(`foldersNotSupported`)):_e(qe(e.target),t)},onDragEnd:Ge,children:[(0,$.jsx)(`input`,{ref:Se,type:`file`,multiple:!0,hidden:!0,onChange:ze}),me.length>0&&(0,$.jsx)(`div`,{style:{minWidth:0,maxWidth:`100%`,padding:`4px 8px`},children:me.map(e=>{let t=e.phase===`reading`?S(`fileUploadReading`,{name:e.name,percent:e.percent}):e.phase===`waiting`?S(`fileUploadWaiting`,{name:e.name}):e.phase===`success`?S(`fileUploadConfirmed`):e.phase===`unknown`?S(`fileUploadOutcomeUnknown`):S(`fileUploadFailed`,{error:e.error||e.name});return(0,$.jsxs)(`div`,{style:{minWidth:0,maxWidth:`100%`,padding:`3px 0`,fontSize:12},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,gap:4,minWidth:0,maxWidth:`100%`},children:[(0,$.jsx)(`span`,{title:`${e.dir}/${e.name}`,style:{minWidth:0,overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`,flex:1},children:e.name}),e.phase!==`reading`&&(0,$.jsx)(`button`,{type:`button`,className:`btn`,"aria-label":`${S(`fileUploadDismiss`)}: ${e.name}`,title:S(`fileUploadDismiss`),onClick:()=>he(t=>t.filter(t=>t.id!==e.id)),style:{flex:`none`,padding:2},children:(0,$.jsx)(Ct,{"aria-hidden":`true`})})]}),e.phase===`reading`&&(0,$.jsx)(`progress`,{max:100,value:e.percent,"aria-label":S(`fileUploadReading`,{name:e.name,percent:e.percent}),style:{width:`100%`,height:4,display:`block`}}),(0,$.jsx)(`div`,{role:`status`,"aria-live":`polite`,"aria-atomic":`true`,style:{overflowWrap:`anywhere`,wordBreak:`break-word`,color:e.phase===`error`?`var(--err-text)`:`var(--text-dim)`},children:t})]},e.id)})}),be&&(0,$.jsx)(kw,{request:be,onClose:()=>xe(null),onComplete:Le}),Ae&&(0,$.jsxs)(`div`,{className:`file-item dir`,children:[Ae.kind===`dir`?(0,$.jsx)(Ee,{className:`file-icon`}):(0,$.jsx)(Ce,{className:`file-icon`}),Ve(Me,Ne,Ie,()=>je(null))]}),M&&(0,$.jsx)(`div`,{className:`panel-empty`,children:S(`loading`)}),!M&&t&&t.path===O&&(0,$.jsxs)($.Fragment,{children:[K===``&&t.parent!=null&&(0,$.jsxs)(`button`,{type:`button`,className:`file-item dir`,onClick:et,children:[(0,$.jsx)(Ee,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:`..`})]}),jw(t.entries,B).filter(e=>K===``&&(H.trim()===``||e.name.toLowerCase().includes(H.trim().toLowerCase()))).map(e=>e.type===`dir`?(0,$.jsxs)(`div`,{className:`file-item dir${we?.cut&&we.src===e.path?` cut`:``}`,"data-type":`dir`,"data-path":e.path,onClick:t=>{Te!==e.path&&(t.target.closest(`.file-attach`)||$e(e.path))},onContextMenu:t=>Be(t,{id:e.path,kind:`dir`,label:e.name}),children:[Te===e.path?Ve(Oe,ke,Fe,()=>De(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-dir-main`,onClick:t=>{t.stopPropagation(),$e(e.path)},children:[(0,$.jsx)(Ee,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":S(`linkFolderTip`),"aria-label":S(`linkFolderTip`),onClick:t=>{t.stopPropagation(),o(e.path,e.name,`reference`,!0)},children:(0,$.jsx)(m,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`name:${e.path}`?` copied`:``}`,"data-tip":S(`copyName`),"aria-label":S(`copyName`),onClick:t=>{t.stopPropagation(),ue(e.name,`name:${e.path}`)},children:oe===`name:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`path:${e.path}`?` copied`:``}`,"data-tip":S(`copyPath`),"aria-label":S(`copyPath`),onClick:t=>{t.stopPropagation(),ue(de(e.path),`path:${e.path}`)},children:oe===`path:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(y,{})})]},e.path):(0,$.jsxs)(`div`,{className:`file-item file${we?.cut&&we.src===e.path?` cut`:``}`,"data-type":`file`,"data-path":e.path,onClick:t=>{Te!==e.path&&(t.target.closest(`.file-attach`)||s(e.path,e.name))},onContextMenu:t=>Be(t,{id:e.path,kind:`file`,label:e.name}),children:[Te===e.path?Ve(Oe,ke,Fe,()=>De(null)):(0,$.jsxs)(`button`,{type:`button`,className:`file-name`,title:`${e.path} — ${S(`previewFile`)}`,onClick:t=>{t.stopPropagation(),s(e.path,e.name)},children:[(0,$.jsx)(Ce,{className:`file-icon`}),(0,$.jsx)(`span`,{className:`file-name-text`,children:e.name})]}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach download`,"data-tip":S(`downloadFile`),onClick:t=>{t.stopPropagation(),Pe(e.path,e.name)},children:(0,$.jsx)(ht,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach ref`,"data-tip":S(`referenceTip`),"aria-label":S(`referenceTip`),onClick:t=>{t.stopPropagation(),o(e.path,e.name,`reference`)},children:(0,$.jsx)(m,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`name:${e.path}`?` copied`:``}`,"data-tip":S(`copyName`),"aria-label":S(`copyName`),onClick:t=>{t.stopPropagation(),ue(e.name,`name:${e.path}`)},children:oe===`name:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(st,{})}),(0,$.jsx)(`button`,{type:`button`,className:`file-attach copy${oe===`path:${e.path}`?` copied`:``}`,"data-tip":S(`copyPath`),"aria-label":S(`copyPath`),onClick:t=>{t.stopPropagation(),ue(de(e.path),`path:${e.path}`)},children:oe===`path:${e.path}`?(0,$.jsx)(z,{}):(0,$.jsx)(y,{})})]},e.path)),K!==``&&(q.length>0?(0,$.jsx)(rT,{nodes:q,depth:0,collapsed:G,onToggle:te,onOpenDir:$e,onOpenFile:s}):(0,$.jsx)(`div`,{className:`panel-empty`,children:S(`searchNoResults`)})),K===``&&t.truncated&&(0,$.jsx)(`div`,{className:`panel-empty files-truncated`,children:S(`filesTruncated`)})]}),!M&&!t&&(0,$.jsx)(`div`,{className:`panel-empty`,children:S(`noFiles`)})]})]})}],...p&&!lt?[{id:hT,label:S(`scmTitle`),iconNode:(0,$.jsx)(ot,{}),iconOnly:!0,element:p}]:[],...at])})}),ne&&(0,$.jsx)(`div`,{className:`rp-sash`,onPointerDown:re,onDoubleClick:()=>R({...uT}),title:S(`dragToResize`)}),ne&&(0,$.jsx)(`div`,{className:`panel-widgets`,style:{flexGrow:L.widgets,minHeight:fT},children:i.filter(e=>e.lines.length>0).map(e=>(0,$.jsxs)(`div`,{className:`widget`,children:[(0,$.jsxs)(`button`,{type:`button`,className:`widget-title widget-title-btn`,title:S(`widgetExpand`),onClick:()=>j(e.key),children:[(0,$.jsx)(`span`,{children:e.key}),(0,$.jsx)(F,{})]}),(0,$.jsx)(`pre`,{className:`widget-lines`,children:e.lines.join(`
|
|
411
|
-
`)})]},e.key))}),A&&(()=>{let e=i.find(e=>e.key===A);return e?(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:()=>j(null),children:(0,$.jsxs)(`div`,{className:`widget-expand`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`widget-expand-head`,children:[(0,$.jsx)(`span`,{className:`widget-expand-title`,children:e.key}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:S(`close`),onClick:()=>j(null),children:(0,$.jsx)(Ct,{})})]}),(0,$.jsx)(`pre`,{className:`widget-expand-lines`,children:e.lines.join(`
|
|
412
|
-
`)})]})}):null})()]})}),yT=220;function bT({side:e,items:t,barProps:n}){let{t:r}=_e(),i=n.chat,[a,o]=(0,Q.useState)(!1),s=(0,Q.useRef)(null),[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=Rt(c!==null),p=ux(),m=i.settings?.uiLayout?.sideDockFloat===!0,h=m?` side-dock-float`:``,g=t.filter(e=>!e.hidden),_=m&&a,v=()=>{u.current!==null&&(window.clearTimeout(u.current),u.current=null),d.current=null,l(null)},y=t=>{if(p||d.current===t)return;let n=t.getAttribute(`data-tip`);n&&(d.current=t,u.current!==null&&window.clearTimeout(u.current),u.current=window.setTimeout(()=>{u.current=null;let r=t.getBoundingClientRect();if(r.width===0&&r.height===0)return;let i=Math.min(Math.max(r.top+r.height/2,24),window.innerHeight-24);l({label:n,x:e===`left`?r.right+8:r.left-8,y:i})},yT))};if((0,Q.useEffect)(()=>{p||s.current?.querySelectorAll(`[title]`).forEach(e=>e.removeAttribute(`title`))}),(0,Q.useEffect)(()=>()=>{u.current!==null&&window.clearTimeout(u.current)},[]),(0,Q.useEffect)(()=>{if(!c)return;let e=()=>l(null);return window.addEventListener(`scroll`,e,!0),window.addEventListener(`resize`,e),()=>{window.removeEventListener(`scroll`,e,!0),window.removeEventListener(`resize`,e)}},[c]),g.length===0)return null;let b=Kg(g),x=t=>(0,$.jsx)(Ax,{entry:t,bar:e,...n},t.id);return(0,$.jsxs)(`div`,{ref:s,className:`side-dock side-dock-${e}${_?` side-dock-collapsed`:``}${h}`,onPointerOver:e=>{let t=e.target.closest?.(`[data-tip]`);t instanceof HTMLElement&&y(t)},onPointerOut:e=>{let t=e.target.closest?.(`[data-tip]`);if(!t)return;let n=e.relatedTarget;n instanceof Node&&t.contains(n)||v()},onPointerDown:v,onScrollCapture:v,onFocusCapture:e=>{let t=e.target;t.hasAttribute?.(`data-tip`)&&y(t)},onBlurCapture:v,children:[_?(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-toggle-btn`,"data-tip":`${r(`sideDockExpand`)} (${g.length})`,onClick:()=>o(!1),"aria-label":r(`sideDockExpand`),children:e===`left`?(0,$.jsx)(At,{}):(0,$.jsx)(U,{})}):(0,$.jsxs)($.Fragment,{children:[m&&(0,$.jsx)(`button`,{type:`button`,className:`side-dock-btn side-dock-collapse-btn`,"data-tip":r(`sideDockCollapse`),onClick:()=>o(!0),"aria-label":r(`sideDockCollapse`),children:e===`left`?(0,$.jsx)(U,{}):(0,$.jsx)(At,{})}),Bx.map(e=>(0,$.jsx)(`div`,{className:`side-dock-slot side-dock-slot-${e}`,children:b[e].length>0&&(0,$.jsx)(`div`,{className:`side-dock-seg`,children:b[e].map(x)})},e))]}),c&&(0,$.jsx)(`div`,{className:`rail-tip`,role:`tooltip`,style:{left:c.x,top:c.y,zIndex:f,transform:e===`right`?`translate(-100%, -50%)`:`translate(0, -50%)`},children:c.label})]})}function xT({approvals:e,activeConversationId:t,mode:n=`all`}){let r=X();return(0,$.jsx)(JC,{items:bv(e,t,n),itemKey:e=>`${e.owner??`local`}:${e.id}`,title:r(`toolApprovalTitle`),summary:e=>(0,$.jsxs)($.Fragment,{children:[e.conversationTitle&&(0,$.jsxs)(`strong`,{children:[e.conversationTitle,` · `]}),e.toolName]}),createdAt:e=>e.createdAt??0,canAutoOpen:e=>n!==`manual`&&(e.global||n===`all`||e.conversationId===t||!e.conversationId),onNavigate:e=>{e.conversationId&&Z(e.global&&e.owner?{type:`open_shared_conversation`,owner:e.owner,id:e.conversationId}:{type:`switch_conversation`,id:e.conversationId})},canNavigate:e=>!!e.conversationId,children:(e,t)=>(0,$.jsx)(ST,{approval:e,onDefer:t},`${e.owner??`local`}:${e.id}`)})}function ST({approval:e,onDefer:t}){let n=X(),{locale:r}=_e(),i=Rt(!!e),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(null),[l,u]=(0,Q.useState)(Date.now);if((0,Q.useEffect)(()=>{if(!e?.createdAt)return;u(Date.now());let t=setInterval(()=>u(Date.now()),1e3);return()=>clearInterval(t)},[e?.id,e?.createdAt]),(0,Q.useEffect)(()=>{if(e){let t=e.params;o(typeof t==`object`&&t?JSON.stringify(t,null,2):t==null?`{}`:String(t)),c(null)}},[e?.id]),!e)return null;let d=t=>{Z({type:`tool_approval_response`,id:e.id,...e.owner?{owner:e.owner}:{},...e.global?{global:!0}:{},decision:`approve`,...t&&t!==`once`?{scope:t}:{}})},f=()=>{Z({type:`tool_approval_response`,id:e.id,...e.owner?{owner:e.owner}:{},...e.global?{global:!0}:{},decision:`deny`,reason:`Operation rejected by user`})};return(0,Er.createPortal)((0,$.jsx)(`div`,{className:`modal-backdrop`,style:{zIndex:i},children:(0,$.jsxs)(`div`,{className:`tool-info-modal approval-modal`,role:`dialog`,"aria-modal":`true`,"aria-label":n(`toolApprovalTitle`),style:{maxWidth:640,borderTop:`4px solid var(--amber, #f59e0b)`},onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`tool-info-head`,children:[(0,$.jsxs)(`span`,{className:`tool-info-title`,style:{color:`var(--amber, #f59e0b)`},children:[(0,$.jsx)(me,{}),n(`toolApprovalTitle`)]}),(0,$.jsx)(`code`,{className:`tool-info-name`,style:{fontWeight:700},children:e.toolName}),e.parentTool===`codemode`&&(0,$.jsxs)(`span`,{className:`tool-info-label`,style:{backgroundColor:`rgba(245, 158, 11, 0.15)`,color:`var(--amber, #f59e0b)`,border:`1px solid rgba(245, 158, 11, 0.35)`,fontWeight:600},children:[`⚡ `,n(`codemodeNestedApprovalBadge`)]}),e.conversationTitle&&(0,$.jsx)(`span`,{className:`tool-info-label`,children:e.conversationTitle}),e.createdAt&&NC(e.createdAt,l)&&(0,$.jsxs)(`span`,{className:`question-queue-wait`,style:{marginLeft:`auto`},children:[`⏱ `,NC(e.createdAt,l)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:t,children:n(`pendingQueueDefer`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalDeny`),onClick:f,children:(0,$.jsx)(Ct,{})})]}),(0,$.jsxs)(`div`,{className:`tool-info-body`,style:{padding:`16px 20px`},children:[e.parentTool===`codemode`&&(0,$.jsxs)(`div`,{style:{padding:`8px 12px`,borderRadius:6,backgroundColor:`rgba(99, 102, 241, 0.12)`,border:`1px solid rgba(99, 102, 241, 0.25)`,marginBottom:12,color:`var(--text, #e2e8f0)`,fontSize:12.5,display:`flex`,alignItems:`center`,gap:6},children:[(0,$.jsx)(`span`,{style:{fontSize:14},children:`⚡`}),(0,$.jsx)(`span`,{children:n(`codemodeNestedApprovalDesc`)})]}),(e.reason||e.reasonEn)&&(0,$.jsxs)(`div`,{style:{padding:`10px 14px`,borderRadius:6,backgroundColor:`rgba(245, 158, 11, 0.12)`,border:`1px solid rgba(245, 158, 11, 0.3)`,marginBottom:16,color:`var(--amber, #f59e0b)`,fontSize:13,lineHeight:1.5,fontWeight:500},children:[(0,$.jsxs)(`div`,{style:{fontWeight:600,marginBottom:2},children:[n(`toolApprovalRiskAlert`),`:`]}),(0,$.jsx)(`div`,{children:Ye(r)?e.reason||e.reasonEn:e.reasonEn||e.reason}),e.category&&(0,$.jsxs)(`div`,{style:{marginTop:6,fontSize:12,opacity:.85},children:[n(`toolApprovalCategory`),`:`,Ye(r)?e.category.label:e.category.labelEn]}),e.hits&&e.hits.length>0&&(0,$.jsxs)(`div`,{className:`approval-hits-panel`,children:[(0,$.jsxs)(`div`,{className:`approval-hits-title`,children:[n(`toolApprovalHitsTitle`),` (`,e.hits.length,`)`]}),(0,$.jsx)(`div`,{className:`approval-hits-list`,children:e.hits.map((e,t)=>(0,$.jsxs)(`div`,{className:`approval-hit-item`,children:[(0,$.jsxs)(`div`,{className:`approval-hit-header`,children:[(0,$.jsx)(`span`,{className:`approval-hit-badge`,children:Ye(r)?e.label:e.labelEn||e.label}),(0,$.jsx)(`span`,{className:`approval-hit-field`,children:e.field}),(0,$.jsx)(`span`,{className:`approval-hit-pos`,children:n(`approvalHitPos`,{index:e.index+1,length:e.length})})]}),(0,$.jsx)(`div`,{className:`approval-hit-text`,children:(0,$.jsx)(`mark`,{className:`approval-danger-hit`,children:e.text})})]},t))})]})]}),Qm(e.toolName)&&typeof(e.params?.command??e.params?.cmd)==`string`&&(0,$.jsxs)(`div`,{className:`approval-cmd-preview`,children:[(0,$.jsxs)(`div`,{className:`approval-cmd-preview-label`,children:[n(`approvalCommandPreview`),`:`]}),(0,$.jsxs)(`div`,{className:`approval-cmd-preview-box`,children:[(0,$.jsx)(`span`,{className:`bashblock-prompt`,children:`$`}),(0,$.jsx)(`code`,{children:sd(e.params.command??e.params.cmd,n,e.hits)})]})]}),(0,$.jsxs)(`div`,{style:{marginBottom:16},children:[(0,$.jsxs)(`div`,{style:{display:`flex`,justifyContent:`space-between`,alignItems:`center`,marginBottom:6},children:[(0,$.jsx)(`span`,{style:{fontSize:13,fontWeight:600,color:`var(--text, #e2e8f0)`},children:n(`toolApprovalParams`)}),(0,$.jsx)(`span`,{style:{fontSize:11,color:`var(--text-dim, #9aa1b4)`},children:n(`toolApprovalEditPlaceholder`)})]}),(0,$.jsx)(`textarea`,{rows:8,value:a,onChange:e=>{o(e.target.value),s&&c(null)},style:{width:`100%`,fontFamily:`var(--mono, monospace)`,fontSize:12,lineHeight:1.5,padding:10,borderRadius:6,backgroundColor:`var(--bg-elev, #111827)`,color:`var(--text, #f8fafc)`,border:s?`1px solid var(--red, #ef4444)`:`1px solid var(--border-subtle, rgba(255,255,255,0.1))`,boxSizing:`border-box`,resize:`vertical`}}),s&&(0,$.jsx)(`div`,{style:{color:`var(--red, #ef4444)`,fontSize:12,marginTop:4},children:s})]}),(0,$.jsxs)(`div`,{style:{display:`flex`,flexWrap:`wrap`,justifyContent:`flex-end`,gap:10},children:[e.category&&(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalAllowCategoryHint`),onClick:()=>d(`category`),children:[(0,$.jsx)(wt,{}),n(`toolApprovalAllowCategory`)]}),!e.scopeless&&(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:n(`toolApprovalAllowConversationHint`),onClick:()=>d(`all`),children:[(0,$.jsx)(h,{}),n(`toolApprovalAllowConversation`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,style:{color:`var(--red, #ef4444)`},onClick:f,children:[(0,$.jsx)(Ct,{}),n(`toolApprovalDeny`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn`,onClick:()=>d(),style:{fontWeight:500},children:[(0,$.jsx)(z,{}),n(`toolApprovalApprove`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-primary`,style:{display:`inline-flex`,alignItems:`center`,gap:6,backgroundColor:`var(--amber, #f59e0b)`,borderColor:`var(--amber, #f59e0b)`,color:`#000`,fontWeight:600},onClick:()=>{try{let t=e.params,n;n=typeof t==`object`&&t||t==null?JSON.parse(a):a,c(null),Z({type:`tool_approval_response`,id:e.id,...e.owner?{owner:e.owner}:{},...e.global?{global:!0}:{},decision:`edit`,editedParams:n})}catch(e){c(n(`toolApprovalJsonError`,{message:e.message}))}},children:[(0,$.jsx)(dt,{}),n(`toolApprovalEditAndRun`)]})]})]})]})}),document.body)}function CT(e){return L({tag:`svg`,attr:{viewBox:`0 0 24 24`},child:[{tag:`path`,attr:{d:`M11.646 15.146 5.854 9.354a.5.5 0 0 1 .353-.854h11.586a.5.5 0 0 1 .353.854l-5.793 5.792a.5.5 0 0 1-.707 0Z`},child:[]}]})(e)}var wT=new Set([`host:files`]);function TT(e,t){let n=e=>e===`center`?1:e===`end`?2:0;return[...e].sort((e,r)=>n(e.align)-n(r.align)||t(e.id)-t(r.id))}function ET(e,t,n,r,i=new Set){let a=new Set;if(!Number.isFinite(t)||t<=0)return a;let o=e.filter(e=>i.has(e.id)&&e.width>0).reduce((e,t)=>e+t.width+n,0),s=Math.max(0,t-Math.max(0,r)-o),c=0,l=!1;for(let t of e){if(!(t.width>0)||i.has(t.id))continue;let e=t.width+n;l||c+e>s?(l=!0,a.add(t.id)):c+=e}return a}function DT(e){return L({tag:`svg`,attr:{viewBox:`0 0 256 256`,fill:`currentColor`},child:[{tag:`path`,attr:{d:`M53.92,34.62A8,8,0,1,0,42.08,45.38L67.37,73.2A69.82,69.82,0,0,0,38,87.63a16,16,0,0,0-1.29,23.78L85,159.71,42.34,202.34a8,8,0,0,0,11.32,11.32L96.29,171l48.29,48.29A16,16,0,0,0,155.9,224c.38,0,.75,0,1.13,0a15.93,15.93,0,0,0,11.64-6.33,89.75,89.75,0,0,0,11.58-20.27l21.84,24a8,8,0,1,0,11.84-10.76ZM155.9,208,48,100.08C58.23,91.83,69.2,87.72,80.66,87.81l87.16,95.88C165.59,193.56,160.24,202.23,155.9,208Zm79.42-104-44.64,44.79a8,8,0,1,1-11.33-11.3L224,92.7,163.32,32,122.1,73.35a8,8,0,0,1-11.33-11.29L152,20.7a16,16,0,0,1,22.63,0l60.69,60.68A16,16,0,0,1,235.32,104Z`},child:[]}]})(e)}function OT(e){return L({tag:`svg`,attr:{viewBox:`0 0 256 256`,fill:`currentColor`},child:[{tag:`path`,attr:{d:`M235.33,104l-53.47,53.65c4.56,12.67,6.45,33.89-13.19,60A15.93,15.93,0,0,1,157,224c-.38,0-.75,0-1.13,0a16,16,0,0,1-11.32-4.69L96.29,171,53.66,213.66a8,8,0,0,1-11.32-11.32L85,159.71l-48.3-48.3A16,16,0,0,1,38,87.63c25.42-20.51,49.75-16.48,60.4-13.14L152,20.7a16,16,0,0,1,22.63,0l60.69,60.68A16,16,0,0,1,235.33,104Z`},child:[]}]})(e)}function kT({anchorRect:e,anchorEl:t,plugins:n,pinnedIds:r,orderedPluginIds:i,onTogglePin:a,onReorder:o,onOpenView:s,onManagePlugins:c,onClose:l}){let{t:u}=_e(),{panelRef:d,style:f,measure:p}=T_({anchor:e,anchorEl:t,onClose:l}),[,m]=(0,Q.useState)(null),h=(0,Q.useRef)(null),[g,_]=(0,Q.useState)(null),v=(0,Q.useMemo)(()=>{let e=new Map((i??[]).map((e,t)=>[e,t]));return dg(n).map((e,t)=>({plugin:e,index:t})).sort((t,n)=>(e.get(t.plugin.id)??1e6+t.index)-(e.get(n.plugin.id)??1e6+n.index)).map(({plugin:e})=>e)},[n,i]),{viewPlugins:y,extPlugins:b}=(0,Q.useMemo)(()=>{let e=[],t=[];for(let n of v)n.view!==!1&&!n.error?e.push(n):t.push(n);return{viewPlugins:e,extPlugins:t}},[v]);(0,Q.useLayoutEffect)(()=>{p()},[v,p]);let x=(e,t)=>{let n=v.filter(e=>e.view!==!1&&!e.error).map(e=>e.id),r=n.indexOf(e),i=r+t;if(r<0||i<0||i>=n.length)return;let[a]=n.splice(r,1);a&&(n.splice(i,0,a),o(n))},S=(e,t)=>{if(!e||e===t)return;let n=v.filter(e=>e.view!==!1&&!e.error).map(e=>e.id),r=n.indexOf(e),i=n.indexOf(t);if(r<0||i<0)return;let[a]=n.splice(r,1);a&&(n.splice(i,0,a),o(n))},C=(e,t)=>{let n=e.view===!1||!!e.error,i=!n&&r.has(e.id),o=e.iconSvg?void 0:e.icon&&!/[a-z]/i.test(e.icon)?e.icon:void 0;return(0,$.jsxs)(`div`,{className:`pm-row${g===e.id?` drop-target`:``}${t?` pm-row-ext`:``}`,role:`none`,onDragOver:t=>{!n&&h.current&&(t.preventDefault(),_(e.id))},onDrop:t=>{t.preventDefault(),S(t.dataTransfer.getData(`text/plain`)||h.current,e.id),h.current=null,m(null),_(null)},children:[n?(0,$.jsx)(`span`,{className:`pm-drag-placeholder`,"aria-hidden":!0}):(0,$.jsx)(`button`,{type:`button`,className:`pm-drag`,draggable:!0,"aria-label":u(`pluginMenuReorder`),title:u(`pluginMenuReorderHint`),onDragStart:t=>{m(e.id),h.current=e.id,t.dataTransfer.effectAllowed=`move`,t.dataTransfer.setData(`text/plain`,e.id);let n=document.createElement(`div`);n.style.cssText=`position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0`,document.body.appendChild(n),t.dataTransfer.setDragImage(n,0,0),requestAnimationFrame(()=>n.remove())},onDragEnd:()=>{h.current=null,m(null),_(null)},onKeyDown:t=>{(t.key===`ArrowUp`||t.key===`ArrowDown`)&&(t.preventDefault(),x(e.id,t.key===`ArrowUp`?-1:1))},children:(0,$.jsx)(V,{"aria-hidden":!0})}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-row-main`,disabled:n,title:e.error??(n?u(`pluginMenuNoView`):e.name),onClick:()=>s(e.id),children:[o||e.iconSvg?(0,$.jsx)(pp,{icon:o,iconSvg:e.iconSvg,className:`pm-icon`}):(0,$.jsx)(A,{className:`pm-icon`,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`pm-name`,children:e.name}),e.error?(0,$.jsx)(`span`,{className:`pm-err-tag`,title:e.error,children:u(`pluginPhaseFailed`)}):t?(0,$.jsx)(`span`,{className:`pm-ext-tag`,title:u(`pluginMenuNoView`),children:u(`pluginBadgeBg`)}):null]}),(0,$.jsx)(`div`,{className:`pm-row-actions`,children:!n&&(0,$.jsx)(`button`,{type:`button`,role:`menuitemcheckbox`,"aria-checked":i,"aria-label":u(i?`pluginMenuUnpin`:`pluginMenuPin`),title:u(i?`pluginMenuUnpin`:`pluginMenuPin`),className:`pm-pin${i?` on`:``}`,onClick:()=>a(e.id,!i),children:i?(0,$.jsx)(OT,{"aria-hidden":!0}):(0,$.jsx)(DT,{"aria-hidden":!0})})})]},e.id)};return(0,Er.createPortal)((0,$.jsxs)(`div`,{ref:d,className:`pm-panel`,role:`menu`,"aria-label":u(`pluginMenuTitle`),style:f,children:[(0,$.jsx)(`div`,{className:`pm-head`,"aria-hidden":`true`,children:(0,$.jsxs)(`div`,{className:`pm-head-left`,children:[(0,$.jsx)(A,{className:`pm-head-icon`,"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`pm-head-title`,children:u(`pluginMenuTitle`)}),(0,$.jsx)(`span`,{className:`pm-head-count`,children:v.length})]})}),(0,$.jsx)(`div`,{className:`pm-list`,children:v.length===0?(0,$.jsx)(`div`,{className:`pm-empty`,children:u(`pluginMenuEmpty`)}):(0,$.jsxs)($.Fragment,{children:[y.length>0&&(0,$.jsxs)(`div`,{className:`pm-group`,children:[b.length>0&&(0,$.jsxs)(`div`,{className:`pm-section-title`,children:[(0,$.jsx)(`span`,{children:u(`pluginGroupViews`)}),(0,$.jsx)(`span`,{className:`pm-section-count`,children:y.length})]}),y.map(e=>C(e,!1))]}),b.length>0&&(0,$.jsxs)(`div`,{className:`pm-group`,children:[y.length>0&&(0,$.jsxs)(`div`,{className:`pm-section-title`,children:[(0,$.jsx)(`span`,{children:u(`pluginGroupExtensions`)}),(0,$.jsx)(`span`,{className:`pm-section-count`,children:b.length})]}),b.map(e=>C(e,!0))]})]})}),(0,$.jsx)(`div`,{className:`pm-footer`,children:(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`pm-footer-btn pm-manage`,onClick:()=>{l(),c()},children:[(0,$.jsx)(E,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:u(`pluginMenuManage`)})]})})]}),document.body)}function AT({onClose:e}){let t=X(),{locale:n,setLocale:r,reloadPacks:i}=_e(),[a,o]=(0,Q.useState)(null),[s,c]=(0,Q.useState)(``),[l,u]=(0,Q.useState)(``);async function d(){try{let e=await fetch(W(j(`/api/locales`)));if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();o(t.packs??[]),c(``)}catch(e){c(t(`localeListFailed`,{error:e instanceof Error?e.message:String(e)}))}}(0,Q.useEffect)(()=>{d()},[]);async function f(e){u(e),c(``);try{let t=await fetch(W(j(`/api/locales/${e}/install`)),{method:`POST`});if(!t.ok){let e=`HTTP ${t.status}`;try{e=(await t.json()).error??e}catch{}throw Error(e)}await i(),await d()}catch(e){c(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{u(``)}}async function p(e){u(e),c(``);try{let t=await fetch(W(j(`/api/locales/${e}`)),{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);Re(e),n===e&&r(`zh`),await i(),await d()}catch(e){c(t(`localeInstallFailed`,{error:e instanceof Error?e.message:String(e)}))}finally{u(``)}}return(0,$.jsx)(`div`,{className:`modal-backdrop`,onClick:e,children:(0,$.jsxs)(`div`,{className:`bg-task-modal`,onClick:e=>e.stopPropagation(),children:[(0,$.jsxs)(`div`,{className:`bg-task-head`,children:[(0,$.jsxs)(`span`,{className:`bg-task-title`,children:[(0,$.jsx)(Le,{}),` `,t(`localePacks`)]}),(0,$.jsx)(`button`,{type:`button`,className:`btn`,title:t(`close`),onClick:e,children:(0,$.jsx)(Ct,{})})]}),s&&(0,$.jsx)(`div`,{className:`bg-task-empty`,children:s}),a===null&&!s?(0,$.jsx)(`div`,{className:`bg-task-empty`,children:t(`loading`)}):(0,$.jsx)(`ul`,{className:`bg-task-list`,children:(a??[]).map(e=>{let n=l===e.code;return(0,$.jsxs)(`li`,{className:`bg-task-item`,children:[(0,$.jsxs)(`div`,{className:`bg-task-info`,children:[(0,$.jsxs)(`div`,{className:`bg-task-line1`,children:[(0,$.jsx)(`span`,{className:`bg-task-port`,children:e.nativeName}),e.installed&&e.version&&(0,$.jsxs)(`span`,{className:`bg-task-name`,children:[`v`,e.version]})]}),(0,$.jsxs)(`div`,{className:`bg-task-line2`,children:[(0,$.jsx)(`span`,{children:e.code}),e.installed?(0,$.jsxs)(`span`,{children:[t(`localeInstalled`),` · `,t(`localeRemoveHint`)]}):(0,$.jsx)(`span`,{children:t(`localeGetMore`)})]})]}),e.installed?(0,$.jsxs)(`button`,{type:`button`,className:`btn bg-task-stop`,disabled:n,title:t(`localeRemove`),onClick:()=>void p(e.code),children:[(0,$.jsx)(Ne,{}),(0,$.jsx)(`span`,{children:t(n?`localeRemoving`:`localeRemove`)})]}):(0,$.jsxs)(`button`,{type:`button`,className:`btn`,disabled:n,title:t(`localeInstall`),onClick:()=>void f(e.code),children:[(0,$.jsx)(ht,{}),(0,$.jsx)(`span`,{children:t(n?`localeDownloading`:`localeInstall`)})]})]},e.code)})}),(0,$.jsx)(`div`,{className:`bg-task-foot`,children:(0,$.jsxs)(`button`,{type:`button`,className:`btn`,title:t(`bgTaskRefresh`),onClick:()=>void d(),children:[(0,$.jsx)(pe,{}),(0,$.jsx)(`span`,{children:t(`bgTaskRefresh`)})]})})]})})}var jT=`xing-shuyin/keel`;function MT(e){if(!e||typeof e!=`object`)return{ok:!1,error:`bad-response`};let t=e;return t.ok===!0?{ok:!0}:{ok:!1,cancelled:t.cancelled===!0||void 0,error:typeof t.error==`string`?t.error:`unknown error`}}var NT=new Set([`idle`,`checking`,`available`,`downloading`,`downloaded`,`up-to-date`,`error`]),PT=new Set([`disabled`,`idle`,`checking`,`available`,`downloading`,`staged`,`applying`,`done`,`up-to-date`,`error`]),FT=new Set([`network`,`feed`,`permission`,`disk`,`signature`,`unknown`]),IT=new Set([`ready`,`dev`,`portable`,`no-feed`,`forced`]);function LT(e){return typeof e==`string`&&e.trim()?e.trim().replace(/^v/i,``):null}function RT(e){return typeof e==`number`&&Number.isFinite(e)?e:0}function zT(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;typeof e.markdown==`string`&&e.markdown.trim()&&t.push({version:typeof e.version==`string`?e.version.replace(/^v/i,``):``,markdown:e.markdown})}return t}function BT(e){if(!e||typeof e!=`object`)return null;let t=e,n=typeof t.phase==`string`&&PT.has(t.phase)?t.phase:null;return n?{enabled:t.enabled===!0,phase:n,currentVersion:LT(t.currentVersion),targetVersion:LT(t.targetVersion),percent:Math.max(0,Math.min(100,Math.round(RT(t.percent)))),transferred:RT(t.transferred),total:RT(t.total),errorCode:typeof t.errorCode==`string`?t.errorCode:null,error:typeof t.error==`string`?t.error:null,checkedAt:typeof t.checkedAt==`number`&&Number.isFinite(t.checkedAt)?t.checkedAt:null}:null}function VT(e){if(!e||typeof e!=`object`)return null;let t=e,n=typeof t.phase==`string`&&NT.has(t.phase)?t.phase:null,r=LT(t.currentVersion);if(!n||!r)return null;let i=t.mode===`manual`?`manual`:`auto`,a=typeof t.modeReason==`string`&&IT.has(t.modeReason)?t.modeReason:`ready`,o=typeof t.errorCode==`string`&&FT.has(t.errorCode)?t.errorCode:null;return{mode:i,modeReason:a,phase:n,currentVersion:r,targetVersion:LT(t.targetVersion),releasesBehind:RT(t.releasesBehind),notes:zT(t.notes),notesCut:t.notesCut===!0,percent:Math.max(0,Math.min(100,Math.round(RT(t.percent)))),transferred:RT(t.transferred),total:RT(t.total),bytesPerSecond:RT(t.bytesPerSecond),skippedVersion:LT(t.skippedVersion),errorCode:o,error:typeof t.error==`string`?t.error:null,checkedAt:typeof t.checkedAt==`number`&&Number.isFinite(t.checkedAt)?t.checkedAt:null,releasesUrl:typeof t.releasesUrl==`string`?t.releasesUrl:WT(null),runtime:BT(t.runtime)??void 0}}function HT(e){if(!e||typeof e!=`object`)return null;let t=e;switch(t.state){case`checking`:return{phase:`checking`,error:null,errorCode:null};case`available`:return{phase:`available`,targetVersion:LT(t.version),percent:0,error:null,errorCode:null,releasesUrl:WT(LT(t.version))};case`up-to-date`:return{phase:`up-to-date`,percent:0,error:null,errorCode:null};case`downloading`:return{phase:`downloading`,percent:Math.max(0,Math.min(100,Math.round(RT(t.percent))))};case`downloaded`:return{phase:`downloaded`,percent:100,error:null,errorCode:null};case`error`:return{phase:`error`,percent:0,error:t.message??`unknown error`,errorCode:`unknown`};default:return null}}function UT(e){if(!an(e))return null;let t=(e??(typeof window>`u`?void 0:window))?.piDesktop?.updater;return!t||typeof t.check!=`function`||typeof t.download!=`function`?null:t}function WT(e){let t=LT(e??null)??``;return t?`https://github.com/${jT}/releases/tag/v${t}`:`https://github.com/${jT}/releases/latest`}function GT(){let[e]=(0,Q.useState)(()=>UT()),[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(null),a=(0,Q.useRef)(!0);(0,Q.useEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let o=(0,Q.useCallback)(()=>{e?.getState&&e.getState().then(e=>{let t=VT(e);t&&a.current&&n(e=>e??t)}).catch(()=>{})},[e]);(0,Q.useEffect)(()=>{if(e)return o(),e.onEvent(e=>{let t=VT(e);if(t){i(null),n(t);return}let r=HT(e);r&&n(e=>e?{...e,...r}:null)})},[e,o]);let s=(0,Q.useCallback)(t=>{if(!e)return;i(null);let n=t(e);n&&typeof n.catch==`function`&&n.catch(e=>{a.current&&i(e instanceof Error?e.message:String(e))})},[e]);return{state:t,bridge:e,actionError:r,check:(0,Q.useCallback)((e={})=>s(t=>t.check(e)),[s]),download:(0,Q.useCallback)((e=`shell`)=>s(t=>t.download(e)),[s]),cancel:(0,Q.useCallback)((e=`shell`)=>s(t=>t.cancel?.(e)??Promise.resolve(!1)),[s]),skip:(0,Q.useCallback)(e=>s(t=>t.skip?.(e)??Promise.resolve(!1)),[s]),quitAndInstall:(0,Q.useCallback)(()=>s(e=>e.quitAndInstall()),[s]),applyRuntime:(0,Q.useCallback)(()=>s(e=>e.applyRuntime?.()??Promise.resolve(!1)),[s]),installLocalMsi:(0,Q.useCallback)(async()=>{if(!e?.installLocalMsi)return{ok:!1,error:`no-bridge`};try{return MT(await e.installLocalMsi())}catch(e){return{ok:!1,error:e instanceof Error?e.message:String(e)}}},[e]),refresh:o}}var KT=new Set([`webui`,`pi-core`]);function qT(e){return!KT.has(e.kind)}function JT(e){return!e.error&&!e.upToDate&&!!e.latest}function YT(e){switch(e){case`available`:case`downloading`:case`ready`:case`applying`:return`warn`;case`error`:return`err`;case`manual`:case`bundled`:case`disabled`:case`idle`:case`checking`:return`muted`;default:return`ok`}}function XT(e){if(!e)return null;let t={id:`shell`,labelKey:`updatesAxisShell`,noteKey:`updatesAxisShellNote`,current:e.currentVersion||null,target:e.targetVersion,percent:e.percent,transferred:e.transferred,total:e.total,bytesPerSecond:e.bytesPerSecond,errorCode:e.errorCode,error:e.error,checkedAt:e.checkedAt};if(e.mode===`manual`){let n=`manual`;return{...t,target:e.targetVersion,state:n,tone:YT(n),action:`manual`}}switch(e.phase){case`checking`:return{...t,state:`checking`,tone:YT(`checking`),action:null};case`available`:{let n=e.targetVersion!==null&&e.targetVersion===e.skippedVersion;return{...t,state:`available`,tone:YT(`available`),action:n?`check`:`download`,skipped:n}}case`downloading`:return{...t,state:`downloading`,tone:YT(`downloading`),action:`cancel`};case`downloaded`:return{...t,state:`ready`,tone:YT(`ready`),action:`install`};case`up-to-date`:return{...t,target:null,state:`latest`,tone:YT(`latest`),action:`check`};case`error`:return{...t,state:`error`,tone:YT(`error`),action:`check`};default:return{...t,state:`idle`,tone:YT(`idle`),action:`check`}}}function ZT(e,t){if(!e)return null;let n={id:`runtime`,labelKey:`updateDesktopRuntimeTitle`,noteKey:`updatesAxisRuntimeNote`,current:e.currentVersion,target:e.targetVersion,percent:e.percent,transferred:e.transferred,total:e.total,bytesPerSecond:0,errorCode:e.errorCode,error:e.error,checkedAt:e.checkedAt};if(!e.enabled){let e=QT(t);return e?{...e,id:`runtime`,labelKey:`updateDesktopRuntimeTitle`}:{...n,target:null,state:`bundled`,tone:YT(`bundled`),action:null}}switch(e.phase){case`checking`:return{...n,state:`checking`,tone:YT(`checking`),action:null};case`available`:return{...n,state:`available`,tone:YT(`available`),action:`download-runtime`};case`downloading`:return{...n,state:`downloading`,tone:YT(`downloading`),action:`cancel-runtime`};case`staged`:return{...n,state:`ready`,tone:YT(`ready`),action:`install-runtime`};case`applying`:return{...n,state:`applying`,tone:YT(`applying`),action:null};case`done`:case`up-to-date`:return{...n,target:null,state:`latest`,tone:YT(`latest`),action:`check-runtime`};case`error`:return{...n,state:`error`,tone:YT(`error`),action:`check-runtime`};case`disabled`:return{...n,target:null,state:`disabled`,tone:YT(`disabled`),action:null};default:return{...n,target:null,state:`idle`,tone:YT(`idle`),action:`check-runtime`}}}function QT(e){let t=e.update,n=e.updatesAll?.find(e=>e.kind===`webui`),r=t?.current??n?.current??null;if(!r)return null;let i={id:`webui`,labelKey:`updatesAxisWebui`,noteKey:`updatesAxisWebuiNote`,current:r,target:t?.latest??n?.latest??null,percent:0,transferred:0,total:0,bytesPerSecond:0,errorCode:null,error:t?.error??n?.error??null,checkedAt:null};return i.error?{...i,state:`error`,tone:YT(`error`),action:`check`}:t===null&&!n?{...i,state:`checking`,tone:YT(`checking`),action:null}:t&&!t.upToDate&&t.latest?{...i,state:`available`,tone:YT(`available`),action:`npm`}:{...i,target:null,state:`latest`,tone:YT(`latest`),action:`check`}}function $T(e){let t=e.updatesAll?.find(e=>e.kind===`pi-core`),n=e.updatesSdk,r=n?.newerInstalled??null,i=!t&&n?.bundledInUse===!0;if(!t&&!r&&!i)return null;let a=t?.current??n?.running??null,o=t&&!t.error&&!t.upToDate?t.latest:null,s={id:`core`,labelKey:`updatesAxisCore`,noteKey:`updatesAxisCoreNote`,current:a,target:o,percent:0,transferred:0,total:0,bytesPerSecond:0,errorCode:null,error:t?.error??null,checkedAt:null};if(t?.error)return{...s,state:`error`,tone:YT(`error`),action:null};if(o)return{...s,state:`available`,tone:YT(`available`),action:`npm`};let c=!t&&n?.bundledInUse?`npm`:null;return{...s,target:null,state:`latest`,tone:r?`warn`:YT(`latest`),action:c}}function eE(e){let t=[],n=e.inDesktopShell?XT(e.desktop):null;if(n&&t.push(n),e.inDesktopShell){let n=ZT(e.desktop?.runtime,e);n&&t.push(n)}else{let n=QT(e);n&&t.push(n)}let r=$T(e);r&&t.push(r);let i=(e.updatesAll??[]).filter(qT),a=i.filter(JT).length,o=t.filter(e=>!e.skipped&&(e.state===`available`||e.state===`downloading`||e.state===`ready`||e.state===`applying`)).length+a,s=t[0]??null,c=s?.state===`error`,l=s?.state===`manual`,u=`ok`,d=`updatesVerdictLatest`,f=`updatesVerdictLatestSub`,p,m={n:t.length+i.length},h=null;if(l)u=`muted`,d=`updatesVerdictManual`,f=a>0?`updatesVerdictManualComponentsSub`:`updatesVerdictManualSub`,h=a>0?{key:`updatesActionUpdateComponents`,action:`npm`}:{key:`updateDesktopManual`,action:`manual`};else if(c)u=`err`,d=`updatesVerdictError`,f=`updatesVerdictErrorSub`,h={key:`updateDesktopRetry`,action:`check`};else if(t.some(e=>e.state===`downloading`||e.state===`applying`)){u=`warn`;let e=t.find(e=>e.state===`downloading`||e.state===`applying`);d=`updatesVerdictWorking`,p={percent:e.percent},f=`updatesVerdictWorkingSub`,h={key:`cancel`,action:e.action??`cancel`,axisId:e.id}}else if(o>0){u=`warn`,d=`updatesVerdictAvailable`,p={n:o},f=e.inDesktopShell?`updatesVerdictAvailableSubShell`:`updatesVerdictAvailableSubWeb`,m=e.inDesktopShell?void 0:{n:a};let n=t.find(e=>!e.skipped&&(e.state===`available`||e.state===`ready`||e.state===`downloading`||e.state===`applying`))??null;h=n?{key:n.action===`install`?`updateDesktopInstall`:n.action===`install-runtime`?`updatesActionInstallRuntime`:n.action===`npm`||n.action===`download-runtime`||n.action===`download`?`updateBtn`:n.action===`cancel`||n.action===`cancel-runtime`?`cancel`:`updateBtn`,action:n.action,axisId:n.id}:a>0?{key:`updatesActionUpdateComponents`,action:`npm`}:null}else t.some(e=>e.state===`checking`)&&(u=`muted`,d=`updatesVerdictChecking`,f=`updatesVerdictCheckingSub`);return{tone:u,titleKey:d,titleVars:p,subKey:f,subVars:m,primary:h,axes:t,components:i,pendingCount:o,hasPending:o>0}}var tE={network:`updateDesktopErrNetwork`,feed:`updateDesktopErrFeed`,permission:`updateDesktopErrPermission`,disk:`updateDesktopErrDisk`,signature:`updateDesktopErrSignature`,unknown:`updateDesktopErrUnknown`},nE={network:`updateDesktopErrNetwork`,feed:`updateDesktopErrFeed`,permission:`updateDesktopErrPermission`,disk:`updateDesktopErrDisk`,signature:`updateDesktopErrSignature`,manifest:`updateDesktopRuntimeErrManifest`,unsupported:`updateDesktopRuntimeErrUnsupported`,corrupt:`updateDesktopRuntimeErrCorrupt`,busy:`updateDesktopRuntimeErrBusy`,health:`updateDesktopRuntimeErrHealth`,unknown:`updateDesktopErrUnknown`};function rE(e){return tE[e??`unknown`]??`updateDesktopErrUnknown`}function iE(e){return nE[e??`unknown`]??`updateDesktopErrUnknown`}var aE=`@earendil-works/pi-coding-agent`,oE={idle:`updatesStateIdle`,checking:`updatesStateChecking`,available:`updatesStateAvailable`,downloading:`updatesStateDownloading`,ready:`updatesStateReady`,applying:`updatesStateApplying`,latest:`updatesStateLatest`,error:`updatesStateError`,manual:`updatesStateManual`,bundled:`updateDesktopRuntimeBundled`,disabled:`updatesStateDisabled`},sE={check:`updateDesktopCheck`,"check-runtime":`updateDesktopRuntimeCheck`,download:`updateDesktopDownload`,"download-runtime":`updateDesktopRuntimeDownload`,cancel:`updateDesktopCancel`,"cancel-runtime":`updateDesktopCancel`,install:`updateDesktopInstall`,"install-runtime":`updateDesktopRuntimeRestart`,manual:`updateDesktopManual`,npm:`updateBtn`},cE={webui:`kindWebUi`,"pi-core":`kindPiCore`,engine:`kindEngine`,package:`kindPackage`,"git-extension":`kindGitExtension`,plugin:`kindPlugin`};function lE(e){return(e??``).replace(/ \([0-9a-f]{7}\)$/,``)}function uE(e){return e.kind===`git-extension`&&e.source?e.source:e.name}function dE(e,t=Date.now()){if(!e)return{key:`updatesAgoJustNow`};let n=Math.max(0,Math.round((t-e)/6e4));if(n<1)return{key:`updatesAgoJustNow`};if(n<60)return{key:`updatesAgoMinutes`,vars:{n}};let r=Math.round(n/60);return r<24?{key:`updatesAgoHours`,vars:{n:r}}:{key:`updatesAgoDays`,vars:{n:Math.round(r/24)}}}var fE={warn:`↓`,ok:`✓`,err:`!`,muted:`↓`};function pE({axis:e,desktop:t,updater:n,inDesktopShell:r,msiLeaving:i,setMsiLeaving:a,setMsiError:o,msiError:s}){let c=X();if(!r)return null;let l=t?.targetVersion!==null&&t?.targetVersion===t?.skippedVersion,u=e.state===`available`&&!!t?.targetVersion,d=on()===`win32`&&typeof n.installLocalMsi==`function`;return!u&&!d&&!l?null:(0,$.jsxs)(`details`,{className:`uc-fold`,children:[(0,$.jsx)(`summary`,{children:c(`updatesMoreOptions`)}),(0,$.jsxs)(`div`,{className:`uc-rows`,children:[l&&t?.targetVersion?(0,$.jsxs)(`div`,{className:`uc-row`,children:[(0,$.jsx)(`span`,{className:`uc-row-name`,children:c(`updateDesktopSkipped`,{version:t.targetVersion})}),(0,$.jsx)(`button`,{type:`button`,className:`uc-btn sm`,onClick:()=>n.skip(null),children:c(`updateDesktopUnskip`)})]}):null,u&&e.target?(0,$.jsxs)(`div`,{className:`uc-row`,children:[(0,$.jsx)(`span`,{className:`uc-row-name`,children:c(`updateDesktopSkip`)}),(0,$.jsx)(`button`,{type:`button`,className:`uc-btn sm`,onClick:()=>n.skip(e.target),children:c(`updateDesktopSkip`)})]}):null,d?(0,$.jsxs)(`div`,{className:`uc-row`,children:[(0,$.jsx)(`span`,{className:`uc-row-name`,children:c(`msiQuitInstallButton`)}),(0,$.jsx)(`button`,{type:`button`,className:`uc-btn sm`,disabled:i,onClick:async()=>{if(!window.confirm(c(`msiQuitInstallConfirm`)))return;o(null);let e=await n.installLocalMsi();e.cancelled||(e.ok?a(!0):o(e.error??`unknown error`))},children:c(`msiQuitInstallButton`)})]}):null,i?(0,$.jsx)(`div`,{className:`uc-hint`,children:c(`msiQuitInstallRunning`)}):null,s?(0,$.jsx)(`div`,{className:`uc-error`,children:c(`msiQuitInstallFailed`,{error:s})}):null]})]})}function mE({open:e,onClose:t,center:n,inDesktopShell:r,updater:i,updatesAll:a,busy:o,serviceName:s,restarting:c,onRestartService:l,onRunNpmUpdate:u,onCheckNpm:d,onCheckAll:f,latestPublishedAt:p=null,updatesSdk:m=null}){let h=X(),g=Rt(e),[_,v]=(0,Q.useState)(!1),[y,b]=(0,Q.useState)(null);if(Lt(t,e),(0,Q.useEffect)(()=>{e&&r&&i.state?.mode===`auto`&&i.state.phase===`idle`&&i.check({manual:!1})},[e,r,i.state?.mode,i.state?.phase]),!e)return null;let x=i.state,S=dE(n.axes.find(e=>e.checkedAt)?.checkedAt??null),C=x?.notes??[],w=()=>a?.find(e=>e.kind===`pi-core`)??{name:aE,kind:`pi-core`,current:``,latest:null,upToDate:!1},T=(e,t)=>{switch(e){case`check`:r&&t?.id!==`runtime`?i.check({manual:!0}):d();return;case`check-runtime`:i.check({manual:!0,channel:`runtime`});return;case`download`:i.download();return;case`download-runtime`:i.download(`runtime`);return;case`cancel`:i.cancel();return;case`cancel-runtime`:i.cancel(`runtime`);return;case`install`:i.quitAndInstall();return;case`install-runtime`:i.applyRuntime();return;case`manual`:window.open(WT(x?.targetVersion??null),`_blank`,`noopener,noreferrer`);return;case`npm`:{if(t?.id===`core`){let e=w(),t=a?.some(e=>e.kind===`pi-core`)??!1;u([e],t?`updatePkgTabTitle`:`installGlobalEngineTabTitle`,{name:e.name});return}if(t?.id===`webui`||t?.id===`runtime`){u([a?.find(e=>e.kind===`webui`)??{name:`keel-agent`,kind:`webui`,current:t.current??``,latest:t.target,upToDate:!1}],`updateTabTitle`);return}let e=n.components.filter(JT);e.length>0&&u(e,`updateAllTabTitle`);return}}},E=(e,t)=>t===`check`&&e.state===`error`?`updateDesktopRetry`:t===`npm`&&e.id===`core`&&!a?.some(e=>e.kind===`pi-core`)?`installGlobalEngineBtn`:sE[t],D=n.primary,O=e=>{if(e.id===`shell`){if(e.state===`checking`)return h(`updateDesktopChecking`);if(e.state===`available`)return[h(`updateDesktopAvailable`,{version:e.target??``}),x&&x.releasesBehind>1?h(`updateDesktopBehind`,{n:x.releasesBehind}):null].filter(Boolean).join(` · `);if(e.state===`ready`)return`${h(`updateDesktopDownloaded`)} ${h(`updateDesktopAutoInstall`)}`;if(e.state===`latest`)return h(`updateDesktopUpToDate`,{version:e.current??``});if(e.state===`manual`){let e=x?.modeReason;return h(e===`dev`?`updateDesktopReasonDev`:e===`portable`?`updateDesktopReasonPortable`:e===`no-feed`?`updateDesktopReasonNoFeed`:e===`forced`?`updateDesktopReasonForced`:`updateDesktopReasonNoFeed`)}return null}if(e.id===`runtime`)return e.state===`bundled`||e.state===`disabled`?h(`updateDesktopRuntimeDisabled`):e.state===`checking`?h(`updateDesktopRuntimeChecking`):e.state===`available`?h(`updateDesktopRuntimeAvailable`,{version:e.target??``}):e.state===`ready`?h(`updateDesktopRuntimeStaged`,{version:e.target??``}):e.state===`applying`?h(`updateDesktopRuntimeApplying`):e.state===`latest`?x?.runtime?.phase===`done`?h(`updateDesktopRuntimeDone`,{version:e.current??``}):h(`updateDesktopRuntimeUpToDate`):null;if(e.id===`webui`&&e.state===`available`)return[p&&Date.now()-new Date(p).getTime()<18e5?h(`updateJustPublished`,{version:e.target??``}):null,h(`updateTerminalHint`)].filter(Boolean).join(` · `);if(e.id===`core`&&e.error)return h(`piCoreUndetected`);if(e.id===`core`){let e=m?.newerInstalled==null?null:`${h(`piCoreSplitRun`,{running:m.running})} · ${h(`piSdkSplitNote`,{running:m.running,installed:m.newerInstalled})}`,t=a?.find(e=>e.kind===`pi-core`);return[e,m?.bundledInUse&&(!t||!t.upToDate)?h(`piSdkBundledNote`,{running:m.running}):null].filter(Boolean).join(` · `)||null}return null},k=e=>{let t=e.state===`downloading`,n=e.state===`error`?h(e.id===`runtime`?iE(e.errorCode):rE(e.errorCode),{error:e.error??``}):null,a=oE[e.state],s=e.tone===`muted`?`muted`:e.tone,c=e.action;return(0,$.jsxs)(`li`,{className:`uc-axis tone-${e.tone}`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`uc-axis-head`,children:[(0,$.jsx)(`span`,{className:`uc-axis-name`,children:h(e.labelKey)}),(0,$.jsx)(`span`,{className:`uc-pill tone-${s}`,children:h(a)})]}),(0,$.jsx)(`div`,{className:`uc-axis-note`,children:h(e.noteKey)}),O(e)?(0,$.jsx)(`div`,{className:`uc-hint`,children:O(e)}):null]}),(0,$.jsxs)(`div`,{className:`uc-axis-act`,children:[(0,$.jsxs)(`span`,{className:`uc-vers`,children:[e.current?e.target?`${e.current} → `:e.current:`—`,e.target?(0,$.jsx)(`span`,{className:`uc-vers-target`,children:e.target}):null]}),c?(0,$.jsx)(`button`,{type:`button`,className:`uc-btn sm${c===`download`||c===`download-runtime`||c===`install`||c===`install-runtime`||c===`npm`?` primary`:``}`,onClick:()=>T(c,e),children:h(E(e,c))}):null]}),t?(0,$.jsxs)(`div`,{className:`uc-axis-progress`,children:[(0,$.jsx)(`div`,{className:`uc-bar`,role:`progressbar`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":e.percent,children:(0,$.jsx)(`i`,{style:{width:`${e.percent}%`}})}),(0,$.jsxs)(`div`,{className:`uc-bar-meta`,children:[(0,$.jsx)(`span`,{children:h(`updateDesktopDownloadProgress`,{percent:e.percent,done:Fl(e.transferred),total:e.total>0?Fl(e.total):`—`})}),e.bytesPerSecond>0?(0,$.jsx)(`span`,{children:h(`updateDesktopSpeed`,{rate:Fl(e.bytesPerSecond)})}):null]})]}):null,n?(0,$.jsx)(`div`,{className:`uc-error`,children:n}):null,e.id===`shell`&&e.state===`ready`&&o?(0,$.jsx)(`div`,{className:`uc-hint`,children:h(`updateDesktopBusy`)}):null,e.id===`shell`?(0,$.jsx)(pE,{axis:e,desktop:x,updater:i,inDesktopShell:r,msiLeaving:_,setMsiLeaving:v,setMsiError:b,msiError:y}):null]},e.id)};return(0,Er.createPortal)((0,$.jsx)(`div`,{className:`uc-backdrop`,style:{zIndex:g},onMouseDown:e=>{e.target===e.currentTarget&&t()},children:(0,$.jsxs)(`div`,{className:`uc-sheet`,role:`dialog`,"aria-modal":`true`,"aria-label":h(`update`),children:[(0,$.jsx)(`div`,{className:`uc-grab`}),(0,$.jsxs)(`header`,{className:`uc-head`,children:[(0,$.jsxs)(`div`,{className:`uc-head-main`,children:[(0,$.jsx)(`h2`,{className:`uc-title`,children:h(`update`)}),(0,$.jsxs)(`p`,{className:`uc-sub`,children:[h(`updateDesktopCurrent`),` v`,n.axes[0]?.current??`—`,` ·`,` `,h(`updatesCheckedAgo`,{ago:h(S.key,S.vars)}),n.axes[0]?.target?` · ${h(`updateDesktopLatest`)} v${n.axes[0].target}`:``]})]}),(0,$.jsx)(`button`,{type:`button`,className:`uc-icon-btn`,"aria-label":h(`close`),onClick:t,children:`✕`})]}),(0,$.jsxs)(`div`,{className:`uc-body`,children:[r&&!i.bridge?(0,$.jsx)(`div`,{className:`uc-hint`,children:h(`updateDesktopNoBridge`)}):null,(0,$.jsxs)(`div`,{className:`uc-verdict tone-${n.tone}`,children:[(0,$.jsx)(`div`,{className:`uc-verdict-ico`,"aria-hidden":`true`,children:fE[n.tone]}),(0,$.jsxs)(`div`,{className:`uc-verdict-text`,children:[(0,$.jsx)(`strong`,{className:`uc-verdict-title`,children:h(n.titleKey,n.titleVars)}),(0,$.jsx)(`span`,{className:`uc-verdict-detail`,children:h(n.subKey,{...n.subVars,ago:h(S.key,S.vars)})})]}),(0,$.jsxs)(`div`,{className:`uc-verdict-actions`,children:[D?.action===`cancel`||D?.action===`cancel-runtime`?null:(0,$.jsx)(`button`,{type:`button`,className:`uc-btn ghost`,onClick:t,children:h(`close`)}),D?(0,$.jsx)(`button`,{type:`button`,className:`uc-btn primary`,onClick:()=>T(D.action,n.axes.find(e=>e.id===D.axisId)),children:h(D.key,D.vars)}):null]})]}),(0,$.jsx)(`ul`,{className:`uc-axes`,children:n.axes.map(k)}),(0,$.jsxs)(`details`,{className:`uc-fold`,open:n.pendingCount>0,children:[(0,$.jsx)(`summary`,{children:n.components.length===0?h(`updatesComponentsTitle`):n.components.some(JT)?`${h(`updatesAllTitle`)} · ${h(`updatesComponentsCount`,{n:n.components.filter(JT).length})}`:h(`updatesComponentsLatest`)}),(0,$.jsxs)(`div`,{className:`uc-rows`,children:[n.components.length===0?(0,$.jsx)(`div`,{className:`uc-empty`,children:h(`updatesNoComponents`)}):n.components.map(e=>{let t=JT(e);return(0,$.jsxs)(`div`,{className:`uc-row`,children:[(0,$.jsx)(`span`,{className:`uc-row-name`,title:e.name,children:uE(e)}),(0,$.jsx)(`span`,{className:`uc-pill plain`,children:h(cE[e.kind])}),(0,$.jsx)(`span`,{className:`uc-row-vers`,children:e.error?h(`updateCheckFailed`):e.upToDate||!e.latest?lE(e.current):`${lE(e.current)} → ${lE(e.latest)}`}),t?(0,$.jsx)(`button`,{type:`button`,className:`uc-btn sm`,onClick:()=>u([e],`updatePkgTabTitle`,{name:uE(e)}),children:h(`updateBtn`)}):(0,$.jsx)(`span`,{className:`uc-pill tone-${e.error?`err`:e.upToDate?`ok`:`muted`}`,children:e.error?h(`updatesStateError`):e.upToDate?h(`updatesStateLatest`):h(`updatesStateChecking`)})]},`${e.kind}:${e.name}`)}),n.components.filter(JT).length>1?(0,$.jsxs)(`div`,{className:`uc-row`,children:[(0,$.jsx)(`span`,{className:`uc-row-name`,children:h(`updatesAllTitle`)}),(0,$.jsx)(`button`,{type:`button`,className:`uc-btn sm primary`,onClick:()=>u(n.components.filter(JT),`updateAllTabTitle`),children:h(`updateAllBtn`)})]}):null]})]}),C.length>0?(0,$.jsxs)(`details`,{className:`uc-fold`,children:[(0,$.jsx)(`summary`,{children:h(`updateDesktopNotes`,{n:C.length})}),(0,$.jsxs)(`div`,{className:`uc-notes-body`,children:[C.map(e=>(0,$.jsxs)(`section`,{children:[e.version?(0,$.jsxs)(`h4`,{children:[`v`,e.version]}):null,(0,$.jsx)(nl,{text:e.markdown,disableMath:!0})]},`${e.version}:${e.markdown.slice(0,32)}`)),x?.notesCut?(0,$.jsx)(`div`,{className:`uc-hint`,children:h(`updateDesktopNotesCut`)}):null]})]}):null]}),(0,$.jsxs)(`footer`,{className:`uc-foot`,children:[(0,$.jsx)(`span`,{className:`uc-foot-spacer`}),(0,$.jsx)(`button`,{type:`button`,className:`uc-link`,onClick:f,children:h(`updatesAllRefresh`)}),s?(0,$.jsx)(`button`,{type:`button`,className:`uc-btn sm`,disabled:c,title:h(`restartServiceTip`,{name:s}),onClick:l,children:h(c?`restartingService`:`restartService`)}):null]})]})}),document.body)}function hE(){let e=X(),[t,n]=(0,Q.useState)(!1),[r,i]=(0,Q.useState)(()=>typeof window<`u`),[a,o]=(0,Q.useState)(null);if((0,Q.useEffect)(()=>{i(!0);let e=tn();if(!e)return;e.isMaximized().then(n);let t=e.onMaximizedChange(e=>{n(e)});return()=>t()},[]),(0,Q.useEffect)(()=>{let e=window.piDesktop?.browser;if(!e)return;e.getState?.().then(e=>{e&&typeof e==`object`&&`mode`in e&&typeof e.mode==`string`&&o(e.mode)});let t=e.onState?.(e=>{e&&typeof e==`object`&&`mode`in e&&typeof e.mode==`string`&&o(e.mode)});return()=>t?.()},[]),!r||!an()||a===`split`||on()===`darwin`)return null;let s=tn();return s?(0,$.jsxs)(`div`,{className:`window-controls`,"aria-label":e(`windowControls`),children:[(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn`,onClick:()=>void s.minimize(),title:e(`windowMinimize`),"aria-label":e(`windowMinimize`),children:(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M1.5 5.5H9.5`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`})})}),(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn`,onClick:()=>void s.toggleMaximize(),title:e(t?`windowRestore`:`windowMaximize`),"aria-label":e(t?`windowRestore`:`windowMaximize`),children:t?(0,$.jsxs)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:[(0,$.jsx)(`path`,{d:`M3 3V1.5C3 1.22 3.22 1 3.5 1H9.5C9.78 1 10 1.22 10 1.5V7.5C10 7.78 9.78 8 9.5 8H8`,stroke:`currentColor`,strokeWidth:`1.1`}),(0,$.jsx)(`rect`,{x:`1`,y:`3`,width:`7`,height:`7`,rx:`0.5`,stroke:`currentColor`,strokeWidth:`1.1`})]}):(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`rect`,{x:`1.5`,y:`1.5`,width:`8`,height:`8`,rx:`0.5`,stroke:`currentColor`,strokeWidth:`1.1`})})}),(0,$.jsx)(`button`,{type:`button`,className:`win-ctrl-btn win-ctrl-close`,onClick:()=>void s.close(),title:e(`close`),"aria-label":e(`close`),children:(0,$.jsx)(`svg`,{width:`11`,height:`11`,viewBox:`0 0 11 11`,fill:`none`,children:(0,$.jsx)(`path`,{d:`M2 2L9 9M9 2L2 9`,stroke:`currentColor`,strokeWidth:`1.2`,strokeLinecap:`round`})})})]}):null}function gE({anchorRef:e,open:t,onClose:n,children:r}){let{panelRef:i,style:a,measure:o}=T_({open:t,anchor:e,onClose:n});return(0,Q.useLayoutEffect)(()=>{t&&o()},[t,r,o]),t?(0,Er.createPortal)((0,$.jsx)(`div`,{ref:i,className:`plugin-topbar-menu portal`,role:`menu`,style:a,children:r}),document.body):null}function _E(){let[e,t]=(0,Q.useState)(()=>typeof window<`u`&&window.matchMedia!==void 0&&window.matchMedia(`(max-width: 768px)`).matches);return(0,Q.useEffect)(()=>{if(typeof window>`u`||window.matchMedia===void 0)return;let e=window.matchMedia(`(max-width: 768px)`),n=e=>t(e.matches);return typeof e.addEventListener==`function`?e.addEventListener(`change`,n):e.addListener(n),()=>{typeof e.removeEventListener==`function`?e.removeEventListener(`change`,n):e.removeListener(n)}},[]),e}function vE({chat:e,uiContextTopbar:t}){let{t:n}=_e();return(0,Q.useCallback)((r,i,a)=>{r.preventDefault(),r.stopPropagation();let o=e.settings?.uiLayout,s=e=>{let t={...o?.slots,[i]:e},n={...o?.align};e!==`sidebar.left`&&e!==`sidebar.right`||n[i]||(n[i]=`center`),Z({type:`set_settings`,uiLayout:{...o,slots:t,...n[i]?{align:n}:{}}})},c=()=>{let e=new Set(o?.hidden??[]);e.add(i);let t=(o?.shown??[]).filter(e=>e!==i);Z({type:`set_settings`,uiLayout:{...o,hidden:[...e],shown:t}})},l=()=>{Z({type:`set_settings`,uiLayout:qg(o,i)})},u=[{id:`host:move-bottom`,slot:`contextmenu.topbar`,source:`host`,label:n(`moveToBottom`),kind:`action`,order:10,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]},{id:`host:move-left`,slot:`contextmenu.topbar`,source:`host`,label:n(`moveToLeft`),kind:`action`,order:20,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]},{id:`host:move-right`,slot:`contextmenu.topbar`,source:`host`,label:n(`moveToRight`),kind:`action`,order:30,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}];bg.has(i)||u.push({id:`host:hide-item`,slot:`contextmenu.topbar`,source:`host`,label:n(`uiLayoutHide`),kind:`action`,order:40,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),(o?.slots?.[i]||o?.labels?.[i]||o?.align?.[i]||o?.order?.includes(i))&&u.push({id:`host:restore-item`,slot:`contextmenu.topbar`,source:`host`,label:n(`uiLayoutRestore`),kind:`action`,order:50,align:`start`,hidden:!1,userOverrides:[],arrangedBy:[]}),t&&t.length>0&&u.push(...t),jf({x:r.clientX,y:r.clientY,slot:`contextmenu.topbar`,target:{id:i,label:a},entries:u,onHostAction:e=>{e.id===`host:move-bottom`?s(`bottombar`):e.id===`host:move-left`?s(`sidebar.left`):e.id===`host:move-right`?s(`sidebar.right`):e.id===`host:hide-item`?c():e.id===`host:restore-item`&&l()}})},[e.settings?.uiLayout,n,t])}function yE(e){return e.map(e=>e.kind===`package`?`pi update npm:${e.name}`:e.kind===`git-extension`?`pi update ${bE(e.source??e.name)}`:e.kind===`plugin`?`keel install ${e.source??e.name} --name ${e.pluginId??e.name} --force`:`npm i -g ${e.name}@latest`).join(`; `)}function bE(e){return e.startsWith(`git:`)?e:`git:${e}`}function xE({chat:e,terminal:t,onViewChange:n}){let{appVersion:r}=fn(),i=pn(),a=hn(),[o,s]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{o&&e.status===`open`&&s(!1)},[o,e.status]);let[c,l]=(0,Q.useState)(!1),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(!1),m=an(),h=GT(),[g,_]=(0,Q.useState)(!1),v=(0,Q.useMemo)(()=>eE({inDesktopShell:m,desktop:h.state,desktopActionError:h.actionError,update:e.update,updatesAll:e.updatesAll,updatesSdk:e.updatesSdk}),[m,h.state,h.actionError,e.update,e.updatesAll,e.updatesSdk]),y=m?h.state?.currentVersion??e.update?.current:e.update?.current,b=v.hasPending,x=m?h.state?.targetVersion??null:e.update?.latest??null,S=v.pendingCount,C=(0,Q.useRef)(new Set);return(0,Q.useEffect)(()=>{if(C.current.size===0)return;let t=!1;for(let n of Array.from(C.current)){let r=e.terminals.find(e=>e.id===n);r&&!r.running&&(C.current.delete(n),t=!0)}t&&e.ready&&(Z({type:`check_update`}),Z({type:`check_updates_all`,force:!0}))},[e.terminals,e.ready]),{appVersion:r,managed:i,service:a,restarting:o,setRestarting:s,langOpen:c,setLangOpen:l,themeOpen:u,setThemeOpen:d,updateOpen:f,setUpdateOpen:p,inDesktopShell:m,desktopUpdater:h,localeModalOpen:g,setLocaleModalOpen:_,updateCenter:v,shownVersion:y,updateWaiting:b,waitingVersion:x,updatesCount:S,runPkgUpdate:(r,i)=>{if(!e.ready||r.length===0)return;let a={name:i,command:yE(r),cwd:"${pwd}"},o=e.terminals.find(e=>e.title===i),s=o?o.id:or();o?(C.current.add(o.id),t.restart(o.id),Z({type:`run_command`,terminalId:o.id,conversationId:o.conversationId,command:a,cols:80,rows:24})):(C.current.add(s),t.create({id:s,conversationId:e.activeConversationId||e.state?.conversationId||``,title:i,cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:a})),p(!1),t.select?.(s),n(`terminal`,{skipAutoCreate:!0})},openUpdateCenter:()=>{p(!0),m?h.refresh():Z({type:`check_update`}),Z({type:`check_updates_all`})}}}var SE=e=>e.entry?.align??`start`;function CE({flowItems:e,isMobile:t,view:n,tabs:r}){let[i,a]=(0,Q.useState)(()=>new Set),o=(0,Q.useRef)(null),s=(0,Q.useRef)(new Map),c=e.filter(e=>!i.has(e.id)),l=t?c.filter(e=>wT.has(e.id)):[],u=t?c.filter(e=>!wT.has(e.id)):c,d=t?e.filter(e=>!wT.has(e.id)):e,f=[...d.filter(e=>SE(e)===`start`),...d.filter(e=>SE(e)===`center`),...d.filter(e=>SE(e)===`end`)],p=f.filter(e=>!i.has(e.id)),m=p.map(e=>e.id).join(`,`),h=(0,Q.useRef)(f),g=(0,Q.useRef)(p);(0,Q.useLayoutEffect)(()=>{h.current=f,g.current=p});let _=()=>{let e=o.current;if(!e||typeof ResizeObserver>`u`)return;let t=Array.from(e.children).filter(e=>!e.classList.contains(`tb-spacer`)),n=g.current;t.length===n.length&&n.forEach((e,n)=>s.current.set(e.id,t[n].offsetWidth));for(let n of t){let t=n;t.offsetWidth>0&&e.clientWidth>0&&t.offsetLeft+t.offsetWidth/2<Math.min(220,e.clientWidth/2)?t.setAttribute(`data-tip-align`,`right`):t.removeAttribute(`data-tip-align`)}let r=Number.parseFloat(getComputedStyle(e).columnGap)||0,i=ET(h.current.map(e=>({id:e.id,width:e.entry?s.current.get(e.id)??0:0})),e.clientWidth,r,0,new Set([...bg,`host:worktrees`,...an()?[`host:browser`]:[]]));a(e=>e.size===i.size&&[...i].every(t=>e.has(t))?e:i)},v=`${c.map(e=>`${e.id}:${e.entry?.label??``}`).join(`|`)}|${n}|${(r??[]).join(`,`)}|${t?`m`:`d`}`;return(0,Q.useLayoutEffect)(_,[v]),(0,Q.useEffect)(()=>{let e=o.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(()=>_());return t.observe(e),()=>t.disconnect()},[v]),{flowRef:o,droppedIds:i,mobileAsideItems:l,segStart:u.filter(e=>SE(e)===`start`),segCenter:u.filter(e=>SE(e)===`center`),segEnd:u.filter(e=>SE(e)===`end`),keptVisualRef:g,dragTagKey:m}}var wE=e=>Array.from(e.children).filter(e=>!e.classList.contains(`tb-spacer`));function TE({chat:e,uiPrimary:t,flowRef:n,keptVisualRef:r,dragTagKey:i}){let a=(0,Q.useRef)(null),o=(0,Q.useRef)(null),s=(0,Q.useRef)(null),c=(0,Q.useRef)(0),[l,u]=(0,Q.useState)(null),d=e=>{let t=n.current;if(!t||!(e instanceof Element))return null;let i=e;for(;i&&i.parentElement!==t;)i=i.parentElement;if(!i||i.classList.contains(`tb-spacer`))return null;let a=wE(t).indexOf(i),o=r.current[a]?.entry;return o?{el:i,entry:o}:null},f=()=>{let e=n.current;if(e)for(let t of e.querySelectorAll(`.tb-dragging, .tb-drop-before, .tb-drop-after`))t.classList.remove(`tb-dragging`,`tb-drop-before`,`tb-drop-after`)},p=(n,r,i)=>{let a=t??[],o=a.find(e=>e.id===n);if(!o||n===r)return;let s=o.align??`start`,c=a.find(e=>e.id===r);if(!c||(c.align??`start`)!==s)return;let l=a.filter(e=>!e.hidden&&(e.align??`start`)===s&&e.id!==n).map(e=>e.id).indexOf(r);if(l<0)return;let u=i?l:l+1,d=qx(e.settings?.uiLayout,{zones:{"topbar.primary":a},tray:[]},{id:n,slot:`topbar.primary`,align:s,index:u});Z({type:`set_settings`,uiLayout:d})},m=(e,r)=>{let i=a.current;if(!i)return;let s=d(document.elementFromPoint(e,r));if(!s||s.entry.id===i)return;let c=(t??[]).find(e=>e.id===i);if(!c||(s.entry.align??`start`)!==(c.align??`start`))return;let l=s.el.getBoundingClientRect(),u=r<l.top+l.height*.25?!0:r>l.bottom-l.height*.25?!1:e<l.left+l.width/2,f=o.current;if(f?.id!==s.entry.id||f.before!==u){o.current={id:s.entry.id,before:u};for(let e of Array.from(n.current?.querySelectorAll(`.tb-drop-before, .tb-drop-after`)??[]))e.classList.remove(`tb-drop-before`,`tb-drop-after`);s.el.classList.add(u?`tb-drop-before`:`tb-drop-after`)}};return(0,Q.useEffect)(()=>{let e=n.current;if(!e)return;let t=wE(e),i=r.current;for(let[e,n]of t.entries()){let t=i[e]?.entry;t&&(n.dataset.uiId=t.id)}return()=>{for(let e of t)delete e.dataset.uiId}},[i,n,r]),{draggingId:l,beginTopbarDrag:e=>{if(e.button!==0||s.current||e.target.closest?.(`input, select, textarea, [contenteditable='true']`))return;let t=d(e.target);if(!t)return;let n={id:t.entry.id,el:t.el,pointerId:e.pointerId,startX:e.clientX,startY:e.clientY,touch:e.pointerType===`touch`,active:!1,moved:!1,timer:0};s.current=n;let r=()=>{n.timer&&=(window.clearTimeout(n.timer),0),window.removeEventListener(`pointermove`,l),window.removeEventListener(`pointerup`,g),window.removeEventListener(`pointercancel`,_)},i=()=>{n.active||(n.active=!0,a.current=n.id,u(n.id),n.el.classList.add(`tb-dragging`))},l=e=>{if(e.pointerId===n.pointerId){if(!n.active){if(Math.hypot(e.clientX-n.startX,e.clientY-n.startY)<6)return;if(n.touch){r(),s.current=null;return}i()}n.moved=!0,e.preventDefault(),m(e.clientX,e.clientY)}},h=e=>{let t=o.current;r(),s.current=null,a.current=null,o.current=null,u(null),f(),e&&n.active&&(c.current=Date.now(),window.setTimeout(()=>{c.current=0},50),n.moved&&t&&p(n.id,t.id,t.before))},g=e=>{e.pointerId===n.pointerId&&h(!0)},_=e=>{e.pointerId===n.pointerId&&h(!1)};window.addEventListener(`pointermove`,l,{passive:!1}),window.addEventListener(`pointerup`,g),window.addEventListener(`pointercancel`,_),n.touch&&(n.timer=window.setTimeout(()=>{n.timer=0,i()},420))},suppressTopbarClick:e=>{c.current&&(c.current=0,e.preventDefault(),e.stopPropagation())}}}function EE({chat:e,terminal:t,view:n,termOpen:r=!1,gitOpen:i=!1,worktreesOpen:a=!1,plugins:o,uiPrimary:s,uiOverflow:c,uiContextTopbar:l,onUiAction:u,onViewChange:d,onOpenPanel:f,onOpenSettings:p,onManagePlugins:m,onOpenBgTasks:h,onOpenGlobalSearch:g,themes:_,theme:y,onThemeChange:b,reloadThemes:x,onOpenThemeMarket:S,onOpenIconEdit:w,zenMode:T,onToggleZenMode:E,onOpenSandboxModal:D,onOpenProjectPicker:O,isProjectPickerOpen:k=!1,onCreateCli:j}){let{locale:M,setLocale:N,t:P,packs:F}=_e(),I=sx(),L=mi(e.state?.messages,e.state?.conversationId),[R,z]=(0,Q.useState)(!1),[B,H]=(0,Q.useState)(!1),[ee,U]=(0,Q.useState)(null),W=_n().ephemeralChat!==!1,G=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>{G.current!==null&&window.clearTimeout(G.current)},[]);let K=(0,Q.useRef)(null),q=t=>!e.tabs||t===`chat`||e.tabs.includes(t),te=n!==`chat`&&n!==`native-cli`&&n!==`terminal`&&n!==`git`,ne=[...c??[]].filter(e=>(e.source!==`host`||e.id!==`host:brand`)&&!Cg(e)),re=o.map(e=>({...e,name:Vy(e,M)})),J=new Set([...s??[],...c??[]].filter(e=>Cg(e)&&!e.hidden).map(e=>e.source.slice(7))),ie=new Map((e.settings?.uiLayout?.order??[]).map((e,t)=>[e,t])),ae=o.map((e,t)=>({id:e.id,index:t})).sort((e,t)=>(ie.get(`${e.id}:__view`)??1e6+e.index)-(ie.get(`${t.id}:__view`)??1e6+t.index)).map(e=>e.id),oe=s===void 0?`host:history.host:brand.host:worktrees.host:engine.host:open-project.host:chat.host:terminal.host:git.host:canvas.host:plugins.host:search.host:browser.host:tasks.host:quiet-mode.host:zen-mode.host:device-center.host:settings.host:language.host:theme.host:update.host:github.host:new-chat.host:new-cli.host:new-ephemeral-chat.host:new-sandbox.host:files`.split(`.`).map(e=>({id:e,entry:null})):s.map(e=>({id:e.id,entry:e})),se=(q(`plugins`)?o:[]).filter(e=>e.view!==!1&&e.error&&!oe.some(t=>t.id===`${e.id}:__view`)).map(e=>({id:`${e.id}:__view`,slot:`topbar.primary`,source:`plugin:${e.id}`,label:Vy(e,M),kind:`view`,view:`plugin:${e.id}`,order:23,align:`end`,hidden:!1,userOverrides:[],arrangedBy:[]})),Y=e=>{if(e.source!==`host`)return!1;switch(e.id){case`host:history`:return f(`left`),!0;case`host:files`:return f(`right`),!0;case`host:new-chat`:return d(`chat`),Z({type:`new_chat`}),er(),!0;case`host:new-cli`:return j?.(),!0;case`host:new-ephemeral-chat`:return d(`chat`),Z({type:`new_chat`,ephemeral:!0}),er(),!0;case`host:new-sandbox`:return D?.(),!0;case`host:open-project`:return O(),!0;case`host:search`:return g(),!0;case`host:tasks`:return h(),!0;case`host:zen-mode`:return E?.(),!0;case`host:quiet-mode`:return ix({...I,enabled:!I.enabled}),!0;case`host:worktrees`:return d(`worktrees`),!0;case`host:device-center`:return d(`devices`),!0;case`host:settings`:return p(),!0;case`host:plugins`:return U(K.current?{rect:K.current.getBoundingClientRect(),el:K.current}:null),!0;default:return!1}},ce=vE({chat:e,uiContextTopbar:l}),{appVersion:le,managed:de,service:fe,restarting:pe,setRestarting:me,langOpen:he,setLangOpen:ge,themeOpen:ye,setThemeOpen:be,updateOpen:xe,setUpdateOpen:Se,inDesktopShell:Ce,desktopUpdater:we,localeModalOpen:De,setLocaleModalOpen:Oe,updateCenter:ke,shownVersion:Ae,updateWaiting:Me,waitingVersion:Ne,updatesCount:Pe,runPkgUpdate:Fe,openUpdateCenter:Ie}=xE({chat:e,terminal:t,onViewChange:d}),Le=_E(),Re={"host:brand":(0,$.jsx)(xx,{}),"host:worktrees":e.state?.worktree?(0,$.jsxs)(`button`,{type:`button`,className:`tb-tab${n===`worktrees`||a?` active`:``}`,title:P(`worktreeViewTitle`),onClick:()=>d(`worktrees`),children:[(0,$.jsx)($f,{}),(0,$.jsx)(`span`,{children:P(`worktreeViewTitle`)})]}):null,"host:open-project":(0,$.jsxs)(`button`,{type:`button`,className:`chip open-project`,"data-tip":P(`openProject`),onClick:O,children:[(0,$.jsx)(je,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`openProject`)})]}),"host:history":n===`chat`&&q(`history`)?(0,$.jsx)(`button`,{type:`button`,className:`panel-toggle`,"data-tip":P(`openHistory`),"aria-label":P(`openHistory`),onClick:()=>f(`left`),children:(0,$.jsx)(V,{})}):null,"host:files":n===`chat`&&q(`files`)?(0,$.jsxs)(`button`,{type:`button`,className:`panel-toggle has-label`,"data-tip":P(`openFiles`),"aria-label":P(`openFiles`),onClick:()=>f(`right`),children:[(0,$.jsx)(tp,{}),(0,$.jsx)(`span`,{children:P(`openFiles`)})]}):null,"host:new-chat":q(`new-chat`)?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat`,"data-tip":P(`newChatTip`),onClick:()=>{d(`chat`),Z({type:`new_chat`}),er()},children:[(0,$.jsx)(ue,{}),(0,$.jsx)(`span`,{children:P(`newChat`)})]}):null,"host:new-cli":j&&q(`terminal`)?(0,$.jsxs)(`button`,{type:`button`,className:`chip native-cli-inline-button`,"data-tip":P(`nativeCliCreate`),"aria-label":P(`nativeCliCreate`),onClick:()=>j(),children:[(0,$.jsx)(v,{}),(0,$.jsx)(`span`,{children:P(`nativeCli`)})]}):null,"host:new-ephemeral-chat":W?(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat ephemeral-chat-btn`,"data-tip":P(`newChatEphemeralTip`),onClick:()=>{d(`chat`),Z({type:`new_chat`,ephemeral:!0}),er()},children:[(0,$.jsx)(Zf,{}),(0,$.jsx)(`span`,{children:P(`newChatEphemeral`)})]}):null,"host:new-sandbox":(0,$.jsxs)(`button`,{type:`button`,className:`chip newchat sandbox-chip`,"data-tip":P(`newSandboxTip`),"aria-label":P(`newSandboxTip`),onClick:()=>D?.(),children:[(0,$.jsx)(rp,{}),(0,$.jsx)(`span`,{children:P(`newSandbox`)})]}),"host:chat":te?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":!1,className:`tb-tab`,"data-tip":P(`chat`),onClick:()=>d(`chat`),children:[(0,$.jsx)(C,{}),(0,$.jsx)(`span`,{children:P(`chat`)})]}):null,"host:native-cli":null,"host:terminal":q(`terminal`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":r,className:`tb-tab${r?` active`:``}`,"data-tip":P(`terminal`),onClick:()=>d(`terminal`),children:[(0,$.jsx)(Xe,{}),(0,$.jsx)(`span`,{children:P(`terminal`)})]}):null,"host:git":q(`git`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":i,className:`tb-tab${i?` active`:``}`,"data-tip":P(`scmTab`),onClick:()=>d(`git`),children:[(0,$.jsx)(ot,{}),(0,$.jsx)(`span`,{children:P(`scmTab`)})]}):null,"host:canvas":q(`canvas`)?(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===`canvas`,className:`tb-tab${n===`canvas`?` active`:``}`,"data-tip":P(`canvasTab`),onClick:()=>d(`canvas`),children:[(0,$.jsx)(Jf,{}),(0,$.jsx)(`span`,{children:P(`canvasTab`)})]}):null,"host:plugins":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":P(`pluginMenuTitle`),"aria-haspopup":`menu`,"aria-expanded":ee!==null,onClick:e=>{let t=e.currentTarget;U(e=>e?.el===t?null:{rect:t.getBoundingClientRect(),el:t})},children:[(0,$.jsx)(A,{"aria-hidden":!0}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`pluginMenuTitle`)})]}),"host:search":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":P(`searchGlobalTip`),onClick:g,children:[(0,$.jsx)(mt,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`searchGlobal`)})]}),"host:browser":an()||!(e.settings?.disabledAgentTools?.includes(`browser_page`)??!1)?(0,$.jsx)(wx,{onActivate:()=>z(!1),onOpenPanel:()=>H(!0)}):null,"host:tasks":(0,$.jsxs)(`button`,{type:`button`,className:`chip bg-task-chip`,"data-tip":P(`bgTasksTip`),onClick:h,children:[(0,$.jsx)(wt,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`bgTasks`)}),e.bgServers.length+L.counts.running+L.counts.finished>0&&(0,$.jsx)(`span`,{className:`bg-task-badge`,children:e.bgServers.length+L.counts.running+L.counts.finished})]}),"host:quiet-mode":(0,$.jsxs)(`button`,{type:`button`,className:`chip${I.enabled?` active`:``}`,"data-tip":P(`quietMode`),onClick:()=>ix({...I,enabled:!I.enabled}),"aria-label":P(`quietMode`),"aria-pressed":I.enabled,children:[(0,$.jsx)(ve,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`quietMode`)})]}),"host:zen-mode":(0,$.jsxs)(`button`,{type:`button`,className:`chip chip-zen${T?` active`:``}`,"data-tip":P(`zenModeTip`),onClick:E,"aria-label":P(`zenMode`),"aria-pressed":T,children:[(0,$.jsx)(ft,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`zenMode`)})]}),"host:device-center":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":P(`deviceCenterTip`),onClick:()=>d(`devices`),"aria-pressed":n===`devices`,children:[(0,$.jsx)(Yf,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`deviceCenter`)})]}),"host:settings":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":P(`settingsTitle`),onClick:p,children:[(0,$.jsx)(ze,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`settings`)})]}),"host:language":(0,$.jsxs)(Zd,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Qf,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:lt(M)})]}),tip:P(`language`),open:he,onOpenChange:ge,caret:!1,children:[(0,$.jsx)(`div`,{className:`dd-header`,children:P(`language`)}),F.map(e=>(0,$.jsx)(Qd,{active:M===e.code,onClick:()=>{N(e.code),ge(!1)},children:e.nativeName},e.code)),(0,$.jsxs)(Qd,{onClick:()=>{ge(!1),Oe(!0)},children:[(0,$.jsx)(ht,{}),` `,P(`localeGetMore`)]})]}),"host:theme":(0,$.jsx)(Zd,{trigger:(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(Te,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:P(`theme`)})]}),tip:P(`theme`),open:ye,caret:!1,onOpenChange:e=>{be(e),e&&_.length===0&&x()},children:(()=>{let e=_.filter(e=>e.group===`classic`),t=_.filter(e=>e.group!==`classic`),n=e=>{let t=Ye(M)?e.name:e.nameEn??e.name,n=e.scheme===`light`?P(`themeLight`):e.scheme===`dark`?P(`themeDark`):``;return n?Ye(M)?`${t}(${n})`:`${t} (${n})`:t};return(0,$.jsxs)($.Fragment,{children:[e.length>0&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{className:`dd-header`,children:P(`themeGroupClassics`)}),e.map(e=>(0,$.jsx)(Qd,{active:y===e.id,onClick:()=>{b(e.id),be(!1)},children:n(e)},e.id))]}),(0,$.jsx)(`div`,{className:`dd-header`,children:e.length>0?P(`themeGroupBuiltin`):P(`theme`)}),(0,$.jsx)(Qd,{active:y===null,onClick:()=>{b(null),be(!1)},children:P(`themeDefault`)}),t.map(e=>(0,$.jsx)(Qd,{active:y===e.id,onClick:()=>{b(e.id),be(!1)},children:n(e)},e.id)),S?(0,$.jsxs)(Qd,{onClick:()=>{be(!1),S()},children:[(0,$.jsx)(ht,{}),` `,P(`themeGetMore`)]}):null]})})()}),"host:update":de?(0,$.jsxs)(`span`,{className:`chip`,"data-tip":P(`updatesManaged`),children:[(0,$.jsx)(ht,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,children:[`v`,le??e.update?.current??`…`]})]}):(0,$.jsx)(`div`,{className:`dropdown right fit`,children:(0,$.jsxs)(`button`,{type:`button`,className:`chip`,onClick:Ie,"aria-haspopup":`dialog`,"aria-expanded":xe,"data-tip":P(`update`),children:[(0,$.jsx)(ht,{}),(0,$.jsxs)(`span`,{className:`chip-sub`,children:[`v`,Ae??`…`]}),Me&&(0,$.jsx)(`span`,{className:`update-dot`,title:P(`updateAvailable`,{version:Ne??``})}),Pe>0&&(0,$.jsx)(`span`,{className:`update-badge`,children:P(`updatesAllBadge`,{n:Pe})})]})}),"host:github":(0,$.jsx)(`a`,{className:`chip github`,href:`https://github.com/xing-shuyin/keel`,target:`_blank`,rel:`noreferrer noopener`,"data-tip":P(`githubRepo`),children:(0,$.jsx)(Ze,{})}),"host:conn":(0,$.jsxs)(`span`,{className:`chip`,"data-tip":e.status,children:[(0,$.jsx)(`span`,{className:`status-dot ${e.status===`open`?`ok`:`busy`}`}),(0,$.jsx)(`span`,{className:`chip-sub`,children:e.status})]}),"host:engine":(0,$.jsx)(kx,{direction:`down`,align:`left`,caret:!1,bar:`top`}),"host:ctx":(0,$.jsx)(`span`,{className:`chip`,"data-tip":P(`contextUsage`),children:(0,$.jsx)(`span`,{className:`chip-sub`,children:(e.state?.stats?.contextUsage?.tokens??0)>0?`${e.state?.stats?.contextUsage?.tokens}`:P(`contextUsage`)})}),"host:cost":(()=>{let t=In(e.state?.stats?.cost??0,{fixedDigits:4});return(0,$.jsx)(`span`,{className:`chip`,"data-tip":t.tooltip||P(`cumulativeCost`),children:(0,$.jsxs)(`span`,{className:`chip-sub`,children:[t.symbol,t.value]})})})(),"host:cwd":(0,$.jsxs)(`button`,{type:`button`,className:`chip`,"data-tip":e.state?.cwd??``,onClick:()=>{G.current!==null&&(window.clearTimeout(G.current),G.current=null),G.current=window.setTimeout(()=>{O(),G.current=null},220)},onDoubleClick:e=>{e.preventDefault(),e.stopPropagation(),G.current!==null&&(window.clearTimeout(G.current),G.current=null),Z({type:`new_chat`}),er()},children:[(0,$.jsx)(Ee,{}),(0,$.jsx)(`span`,{className:`chip-sub`,children:e.state?.cwd?.split(/[/\\]/).pop()||e.state?.cwd})]})},Be=new Set([`host:search`,`host:tasks`,`host:settings`,`host:plugins`]),Ve=new Set([`host:language`,`host:theme`,`host:update`,`host:browser`,`host:engine`]),He=e=>Be.has(e)&&!q(e.slice(5)),Ue=e=>{if(e.kind===`view`){if(!q(`plugins`))return null;let t=e.view??``,r=o.find(t=>`plugin:${t.id}`===e.source),i=r?.error?`${e.label}: ${r.error}`:e.hint??e.label;return(0,$.jsxs)(`button`,{type:`button`,role:`tab`,"aria-selected":n===t,className:`tb-tab plugin-tab${n===t?` active`:``}${r?.error?` broken`:``}`,"data-tip":i,onClick:()=>d(t),onContextMenu:t=>ce(t,e.id,e.label),children:[(0,$.jsx)(pp,{icon:e.icon,iconSvg:e.iconSvg}),(0,$.jsx)(`span`,{children:e.label})]},e.id)}return e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`plugin-topbar-item plugin-topbar-select`,title:e.hint??e.label,"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>u?.(e,t.target.value),onContextMenu:t=>ce(t,e.id,e.label),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id):(0,$.jsxs)(`button`,{type:`button`,className:`plugin-topbar-item`,"data-tip":e.hint??e.label,onClick:()=>u?.(e),onContextMenu:t=>ce(t,e.id,e.label),children:[(0,$.jsx)(pp,{icon:e.icon,iconSvg:e.iconSvg}),(0,$.jsx)(`span`,{children:e.label})]},e.id)},We=[];for(let t of oe){if(t.id===`host:native-cli`||t.id===`host:chat`&&!te||!(t.id===`host:browser`&&an())&&t.entry?.hidden||He(t.id)||t.id===`host:worktrees`&&!e.state?.worktree)continue;let s=null;t.entry?s=(0,$.jsx)(Ax,{entry:t.entry,bar:`top`,chat:e,view:n,termOpen:r,gitOpen:i,worktreesOpen:a,plugins:o,onViewChange:d,onOpenPanel:f,onOpenSettings:p,onOpenGlobalSearch:g,onOpenBgTasks:h,onOpenProjectPicker:O,isProjectPickerOpen:k,onOpenPluginMenu:e=>U(t=>t?.el===e?null:{rect:e.getBoundingClientRect(),el:e}),isPluginMenuOpen:ee!==null,onUiAction:u,uiContextEntries:l,zenMode:T,onToggleZenMode:E,onOpenSandboxModal:D,onCreateCli:j,dropdownProps:{theme:y,themes:_,onThemeChange:b,reloadThemes:x,onLocaleModalOpen:()=>Oe(!0),onThemeModalOpen:S,onOpenUpdateCenter:Ie,updateVersion:Ae??null,updatePending:Me,updateTargetVersion:Ne,updatesCount:Pe,managed:de,appVersion:le}},t.id):t.id.startsWith(`host:`)&&Re[t.id]&&(s=Re[t.id]),s&&We.push({id:t.id,entry:t.entry,node:s})}for(let t of se){let a=(0,$.jsx)(Ax,{entry:t,bar:`top`,chat:e,view:n,termOpen:r,gitOpen:i,plugins:o,onViewChange:d,onUiAction:u,uiContextEntries:l},t.id);a&&We.push({id:t.id,entry:t,node:a})}let{flowRef:Ge,droppedIds:Ke,mobileAsideItems:qe,segStart:Je,segCenter:Qe,segEnd:$e,keptVisualRef:tt,dragTagKey:nt}=CE({flowItems:We,isMobile:Le,view:n,tabs:e.tabs}),{draggingId:rt,beginTopbarDrag:it,suppressTopbarClick:at}=TE({chat:e,uiPrimary:s,flowRef:Ge,keptVisualRef:tt,dragTagKey:nt}),st=We.filter(e=>Ke.has(e.id)&&e.entry).map(e=>e.entry),ct=new Map;[...s??[],...c??[]].forEach((e,t)=>{ct.has(e.id)||ct.set(e.id,t)});let ut=TT([...ne,...st],e=>ct.get(e)??999999),dt=e=>e.icon&&!/[a-z]/i.test(e.icon)?e.icon:null,X=e.settings?.uiLayout?.topbarText===!1;return(0,$.jsxs)(`header`,{className:`topbar${X?` no-labels`:``}`,"data-pi-anchor":`topbar`,children:[(0,$.jsxs)(`div`,{className:`topbar-flow${rt?` tb-reordering`:``}`,ref:Ge,role:`toolbar`,"aria-label":P(`viewSwitch`),onPointerDown:it,onClickCapture:at,children:[Je.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(Qe.length>0||$e.length>0)&&(0,$.jsx)(`span`,{className:`tb-spacer${Qe.length===0&&$e.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),Qe.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),Qe.length>0&&(0,$.jsx)(`span`,{className:`tb-spacer${$e.length>0?` tb-spacer-end`:``}`,"aria-hidden":`true`}),$e.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id))]}),(ut.length>0||We.length>0)&&(0,$.jsxs)(`div`,{className:`plugin-topbar-more`,children:[(0,$.jsx)(`button`,{ref:K,type:`button`,className:`plugin-topbar-item`,"aria-haspopup":`menu`,"aria-expanded":R,"aria-label":P(`pluginTopbarMore`),"data-tip":P(`pluginTopbarMore`),onClick:()=>z(e=>!e),children:(0,$.jsx)(CT,{})}),(0,$.jsxs)(gE,{anchorRef:K,open:R,onClose:()=>z(!1),children:[ut.map(e=>{let t=e.source===`host`&&Ve.has(e.id)?Re[e.id]:void 0;if(t!==void 0)return(0,$.jsx)(Q.Fragment,{children:t},e.id);if(e.source===`host`&&e.id===`host:github`)return(0,$.jsxs)(`a`,{role:`menuitem`,className:`chip github`,href:`https://github.com/xing-shuyin/keel`,target:`_blank`,rel:`noreferrer noopener`,title:P(`githubRepo`),onClick:()=>z(!1),children:[(0,$.jsx)(Ze,{}),(0,$.jsx)(`span`,{children:`GitHub`})]},e.id);if(e.source===`host`){let t=Re[e.id];if(t)return(0,$.jsx)(`div`,{className:`plugin-topbar-menu-keep`,onClick:()=>z(!1),children:t},e.id)}else{let t=Ue(e);if(t)return(0,$.jsx)(`div`,{className:`plugin-topbar-menu-keep`,onClick:()=>z(!1),children:t},e.id)}return e.kind===`select`&&e.options?.length?(0,$.jsxs)(`label`,{className:`plugin-topbar-overflow-select tb-row`,title:e.hint??e.label,children:[dt(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:dt(e)}):null,(0,$.jsx)(`span`,{className:`tb-row-text`,children:e.label}),(0,$.jsx)(`select`,{"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>{z(!1),Y(e)||u?.(e,t.target.value)},children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))})]},e.id):(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`tb-row`,title:e.hint??e.label,onClick:()=>{z(!1),Y(e)||u?.(e)},children:[dt(e)?(0,$.jsx)(`span`,{className:`plugin-icon-glyph`,children:dt(e)}):null,(0,$.jsx)(`span`,{className:`tb-row-text`,children:e.label})]},e.id)}),(0,$.jsx)(`div`,{className:`tb-menu-divider`,"aria-hidden":`true`}),(0,$.jsxs)(`button`,{type:`button`,role:`menuitem`,className:`tb-row`,onClick:()=>{z(!1),w()},children:[(0,$.jsx)(et,{}),(0,$.jsx)(`span`,{className:`tb-row-text`,children:P(`uiIconEdit`)})]})]})]}),qe.map(e=>(0,$.jsx)(Q.Fragment,{children:e.node},e.id)),(0,$.jsx)(hE,{}),De&&(0,$.jsx)(AT,{onClose:()=>Oe(!1)}),!de&&(0,$.jsx)(mE,{open:xe,onClose:()=>Se(!1),center:ke,inDesktopShell:Ce,updater:we,updatesAll:e.updatesAll,updatesSdk:e.updatesSdk,latestPublishedAt:e.update?.latestPublishedAt??null,busy:e.status===`open`,serviceName:fe?.name??null,restarting:pe,onRestartService:()=>{pe||(me(!0),Z({type:`restart_service`}))},onRunNpmUpdate:(e,t,n)=>{Fe(e,P(t,n)),Se(!1)},onCheckNpm:()=>Z({type:`check_update`}),onCheckAll:()=>{Z({type:`check_updates_all`,force:!0}),Ce&&we.state?.mode===`auto`&&we.check({manual:!0})}}),B&&(0,Er.createPortal)((0,$.jsx)(Tx,{onClose:()=>H(!1)}),document.body),ee&&(0,$.jsx)(kT,{anchorRect:ee.rect,anchorEl:ee.el,plugins:re,pinnedIds:J,orderedPluginIds:ae,onTogglePin:(t,n)=>Z({type:`set_settings`,uiLayout:wg(e.settings?.uiLayout,t,n)}),onReorder:t=>Z({type:`set_settings`,uiLayout:Tg(e.settings?.uiLayout,t)}),onOpenView:e=>{U(null),d(`plugin:${e}`)},onManagePlugins:m,onClose:()=>U(null)})]})}var DE=`pi-web-ui:terminal-dock:v1`,OE=[`pi-web-ui:bottom-dock-h`,`pi-web-ui:term-drawer-h`],kE=180,AE=318,jE=240,ME=360,NE={version:1,side:`bottom`,open:!1,collapsed:!1,sizes:{bottom:AE,left:ME,right:ME},activeTab:`host:bottom-terminal`,terminalTabOrder:[]};function PE(e,t,n){let r=e===`bottom`?kE:jE;return typeof t!=`number`||!Number.isFinite(t)||t<r?n:Math.round(Math.min(1200,Math.max(r,t)))}function FE(){try{for(let e of OE){let t=localStorage.getItem(e);if(t===null)continue;let n=Number(t);if(Number.isFinite(n)&&n>=kE)return Math.round(n)}}catch{}return null}function IE(e){let t=e&&typeof e==`object`?e:{},n=t.side===`left`||t.side===`right`?t.side:`bottom`,r=t.sizes&&typeof t.sizes==`object`?t.sizes:{},i=FE();return{version:1,side:n,open:typeof t.open==`boolean`?t.open:NE.open,collapsed:typeof t.collapsed==`boolean`?t.collapsed:NE.collapsed,sizes:{bottom:PE(`bottom`,r.bottom,i??AE),left:PE(`left`,r.left,ME),right:PE(`right`,r.right,ME)},activeTab:typeof t.activeTab==`string`&&t.activeTab.length>0?t.activeTab:NE.activeTab,terminalTabOrder:Array.isArray(t.terminalTabOrder)?[...new Set(t.terminalTabOrder.filter(e=>typeof e==`string`&&e.length>0))].slice(0,200):[],activeTerminal:typeof t.activeTerminal==`string`&&t.activeTerminal.length>0?t.activeTerminal:void 0}}function LE(){try{let e=localStorage.getItem(DE);return IE(e?JSON.parse(e):null)}catch{return IE(null)}}var RE=null,zE=new Set;function BE(){return RE||=LE(),RE}function VE(e){let t=BE(),n=IE({...t,...e,sizes:e.sizes?{...t.sizes,...e.sizes}:t.sizes});n.terminalTabOrder.length===t.terminalTabOrder.length&&n.terminalTabOrder.every((e,n)=>e===t.terminalTabOrder[n])&&(n.terminalTabOrder=t.terminalTabOrder);try{localStorage.setItem(DE,JSON.stringify(n))}catch{}RE=n;for(let e of zE)e();return n}function HE(e){return zE.add(e),()=>zE.delete(e)}function UE(){return BE()}function WE(){return(0,Q.useSyncExternalStore)(HE,UE,UE)}function GE(e){return e.isComposing||e.repeat||e.altKey||!e.ctrlKey&&!e.metaKey?null:e.code===`Backquote`||e.key==="`"||e.key===`~`?e.shiftKey?`new`:`toggle`:e.key.toLowerCase()===`j`&&!e.shiftKey?`toggle`:e.key===`PageUp`&&!e.shiftKey?`previous`:e.key===`PageDown`&&!e.shiftKey?`next`:e.key.toLowerCase()===`w`&&!e.shiftKey?`close`:null}function KE(e,t,n){return e<n.left||e>n.left+n.width||t<n.top||t>n.top+n.height?null:e<n.left+n.width*.25?`left`:e>n.left+n.width*.75?`right`:t>n.top+n.height*.6?`bottom`:null}function qE({notice:e,onDismiss:t}){let n=X(),{locale:r}=_e(),i=!Ye(r)&&e.textEn?e.textEn:e.text,[a,o]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{if(a)return;let n=setTimeout(()=>t(e.id),Av(e.level));return()=>clearTimeout(n)},[a,e.id,e.level,t]);let s=e.level===`error`?Me:e.level===`warning`?me:q;return(0,$.jsxs)(`div`,{className:`notice notice-${e.level}${a?` paused`:``}`,role:`status`,onMouseEnter:()=>o(!0),onMouseLeave:()=>o(!1),onClick:()=>{window.getSelection?.()?.toString()||t(e.id)},children:[(0,$.jsx)(s,{className:`notice-icon`}),(0,$.jsx)(`span`,{className:`notice-text`,children:i}),(0,$.jsx)(`button`,{type:`button`,className:`notice-close`,title:n(`close`),onClick:n=>{n.stopPropagation(),t(e.id)},children:(0,$.jsx)(Ct,{})})]})}function JE({side:e,width:t,onResize:n}){let r=X(),i=(0,Q.useCallback)(r=>{r.preventDefault();let i=r.clientX,a=t,o=a,s=t=>{let r=e===`left`?t.clientX-i:i-t.clientX;o=Math.min(s4(e),Math.max(180,Math.round(a+r))),n(o)},c=()=>{window.removeEventListener(`pointermove`,s),window.removeEventListener(`pointerup`,c),document.body.classList.remove(`panel-resizing`);try{localStorage.setItem(c4(e),String(o))}catch{}};window.addEventListener(`pointermove`,s),window.addEventListener(`pointerup`,c),document.body.classList.add(`panel-resizing`)},[e,t,n]);return(0,$.jsx)(`div`,{className:`resize-handle resize-${e}`,title:r(`dragToResize`),onPointerDown:i,onDoubleClick:()=>n(240)})}function YE({side:e,onClick:t}){let n=X();return(0,$.jsx)(`button`,{type:`button`,className:`panel-rail panel-rail-${e}`,title:n(`expandPanel`),onClick:t,children:e===`left`?(0,$.jsx)(At,{}):(0,$.jsx)(U,{})})}var XE=(0,Q.lazy)(()=>Rs(()=>import(`./BottomDock-CUnQsIDW.js`).then(e=>({default:e.BottomDock})),__vite__mapDeps([35,2,3,7,36,8]),import.meta.url)),ZE=(0,Q.lazy)(()=>Rs(()=>import(`./NativeCliPanel-DotHqKv_.js`).then(e=>({default:e.NativeCliPanel})),__vite__mapDeps([37,2,3,7,31,18,38,27,28,12,13,9]),import.meta.url)),QE=(0,Q.lazy)(()=>Rs(()=>import(`./DeviceCenter-BWKRVpWt.js`).then(e=>({default:e.DeviceCenter})),__vite__mapDeps([39,2,3,7,13,40,41]),import.meta.url)),$E=(0,Q.lazy)(()=>Rs(()=>import(`./CanvasStudio-KZ0MmCL7.js`).then(e=>({default:e.CanvasStudio})),__vite__mapDeps([42,2,7,3,43,18,31,32,8,44,9,17,45,19]),import.meta.url)),eD=(0,Q.lazy)(()=>Rs(()=>import(`./GroupConversation-EaMawnF-.js`).then(e=>({default:e.GroupConversation})),__vite__mapDeps([46,2,3,13,7,18,34,44,9,32,41,8,47]),import.meta.url)),tD=[];function nD({chat:e,terminal:t,send:n,pushNotice:r,dismissNotice:i,panelSend:a,locale:o,view:s,setView:c,worktreeOpen:l,setWorktreeOpen:u,handleViewChange:d,zenMode:f,toggleZenMode:p,appDragOver:m,setAppDragOver:h,nativeCliViewRef:g,addNativeCliFiles:_,addImageFiles:v,addLocalFiles:y,termDrawerOpen:b,gitDrawerOpen:x,termCollapsed:S,setTermCollapsed:C,enabledPlugins:w,uiSlots:T,uiPrimary:E,uiOverflow:D,uiNoticeActions:O,uiSidebarLeft:k,uiSidebarRight:A,uiLeftSessions:j,uiLeftProjectsActions:M,uiLeftProject:N,uiLeftRunningActions:P,uiLeftHistoryActions:F,uiLeftSections:I,uiLeftRunning:L,uiLeftHistory:R,uiChatHeader:B,uiChatEmpty:V,uiGoalbarActions:H,sidebarBarProps:ee,onUiAction:U,renderLeftPluginSectionBody:W,onPluginRunningAction:G,openNativeCliCreate:K,nativeCliCreateCwd:q,nativeCliCreating:te,setNativeCliCreateCwd:ne,createNativeCliConversation:re,drawer:J,setDrawer:ie,closeDrawer:ae,setSettingsInitialSection:oe,setSettingsOpen:se,setBgTasksOpen:Y,setGlobalSearchOpen:ce,iconEditOpen:le,setIconEditOpen:ue,setSandboxModalMode:de,openSandboxCreateModal:me,openProjectPicker:he,projectPickerOpen:ge,setProjectPickerOpen:_e,themes:ve,theme:ye,switchTheme:be,reloadThemes:xe,setThemeMarketOpen:Se,pluginNotify:Ce,pluginNotifyRef:we,setPluginNotify:Te,pluginDialog:Ee,pluginDialogRef:De,setPluginDialog:Oe,pluginDialogSel:ke,setPluginDialogSel:Ae,pluginDialogInput:je,setPluginDialogInput:Me,model:Pe,layoutRef:Fe,leftWidth:Ie,rightWidth:Le,isMobile:Re,leftCollapsed:ze,rightCollapsed:Be,toggleLeft:He,toggleRight:Ue,resizeLeft:We,resizeRight:Ge,wide:Ke,hideModelRow:qe,isMinimalEmpty:Je,unreadConvKeys:Ye,activeGroupId:Xe,setActiveGroupId:Ze,presetNames:Qe,leftPanelTransition:$e,cachedNativeClis:et,isNativeCliConversation:tt,chatPaneVisible:nt,sharedReadOnly:rt,activeConvId:it,onEditMessage:at,onRemoveQueued:ot,onRecallQueued:st,searchJump:ct,setSearchJump:lt,urlJump:ut,setUrlJump:dt,userPromptNonce:pt,attachmentProgress:mt,handleAbort:ht,modelState:gt,attachments:_t,removeAttachmentCb:vt,annotateImageCb:yt,addImageFilesCb:bt,addLocalFilesCb:xt,addPathAttachmentCb:St,searchFilesCb:wt,openManageModels:Tt,handleSent:Et,recallDrafts:Dt,attach:kt,openFile:At,openInVscodeEditor:jt,scmTab:Mt,setRightTab:Nt,refreshWorktrees:Pt,pendingWorktreeSwitch:Ft,pluginViews:It,failedPluginViews:Lt,bottomDockTabs:Rt,bottomTab:zt,setBottomTab:Bt,children:Vt}){let Ht=X(),Ut=WE(),Wt=Re?`bottom`:Ut.side,Gt=(0,Q.useCallback)(()=>{let t=e.state?.conversationId;t&&!e.transition&&n({type:`abort_bash`,conversationId:t})},[e.state?.conversationId,e.transition,n]),Kt=(0,Q.useCallback)(()=>{if(n({type:`retry_last`})){let t=e.state?.model;t&&of(`${t.provider}/${t.id}`)}},[e.state?.model,n]),qt=(0,Q.useCallback)(()=>lt(null),[lt]),Jt=(0,Q.useCallback)(()=>dt(null),[dt]);return(0,$.jsxs)(`div`,{className:`app${f?` zen-mode`:``}`,"data-pi-anchor":`app`,onDragOver:e=>{Array.from(e.dataTransfer?.types??[]).includes(`Files`)&&(e.preventDefault(),h(!0))},onDragLeave:e=>{e.currentTarget.contains(e.relatedTarget)||h(!1)},onDrop:e=>{if(h(!1),!Array.from(e.dataTransfer?.types??[]).includes(`Files`))return;e.preventDefault();let t=Array.from(e.dataTransfer?.files??[]);if(t.length===0){r(`warning`,Ht(`foldersNotSupported`));return}if(g.current){_(t);return}let n=t.filter(e=>ma(e.type)),i=t.filter(e=>!ma(e.type));n.length>0&&v(n),i.length>0&&y(i)},children:[(0,$.jsx)(Sw,{}),f&&(0,$.jsxs)(`button`,{type:`button`,className:`zen-exit-pill`,onClick:p,title:Ht(`zenModeExitTip`),"aria-label":Ht(`zenModeExit`),children:[(0,$.jsx)(ft,{}),(0,$.jsx)(`span`,{children:Ht(`zenModeExit`)})]}),m&&(0,$.jsx)(`div`,{className:`app-drop-overlay`,"aria-hidden":!0,children:(0,$.jsxs)(`span`,{children:[`📎 `,Ht(`dropHereToAttach`)]})}),(0,$.jsx)(EE,{chat:e,terminal:t,view:s,termOpen:b&&!rt,gitOpen:x,worktreesOpen:l,plugins:w,uiPrimary:E,uiOverflow:D,uiContextTopbar:T[`contextmenu.topbar`],onCreateCli:K,onUiAction:U,zenMode:f,onToggleZenMode:p,onViewChange:d,onOpenPanel:ie,onOpenSettings:()=>{oe(void 0),se(!0)},onManagePlugins:()=>{oe(`plugins`),se(!0)},onOpenBgTasks:()=>Y(!0),onOpenGlobalSearch:()=>ce(!0),onOpenIconEdit:()=>ue(!0),onOpenSandboxModal:()=>de(`create`),onOpenProjectPicker:he,isProjectPickerOpen:ge,themes:ve,theme:ye,onThemeChange:be,reloadThemes:xe,onOpenThemeMarket:()=>Se(!0)}),q!==null&&(0,$.jsx)(TC,{cwd:q,disabled:te,onClose:()=>{te||ne(null)},onCreate:re}),(0,$.jsx)(jC,{open:ge,onClose:()=>_e(!1)}),le&&(0,$.jsx)(Yx,{slots:T,layout:e.settings?.uiLayout,exclude:xg,onClose:()=>ue(!1)}),e.protocolMismatch&&(0,$.jsxs)(`div`,{className:`protocol-banner`,children:[`⚠ `,Ht(`protocolMismatch`)]}),(0,$.jsxs)(`div`,{className:`notices`,children:[e.notices.map(e=>(0,$.jsx)(qE,{notice:e,onDismiss:i},e.id)),Ce&&(0,$.jsxs)(`div`,{className:`notice notice-info`,role:`status`,children:[(0,$.jsx)(`span`,{className:`notice-text`,children:Ce.text}),Ce.actions.map(e=>(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let t=we.current;we.current=null,Te(null);try{t?.resolve(e.id)}catch{}},children:e.label},e.id)),(0,$.jsx)(`button`,{type:`button`,className:`notice-close`,title:Ht(`close`),onClick:()=>{let e=we.current;we.current=null,Te(null);try{e?.resolve(null)}catch{}},children:(0,$.jsx)(Ct,{})})]}),O.length>0&&(0,$.jsx)(`div`,{className:`notice-actions`,role:`toolbar`,children:O.map(e=>e.kind===`select`&&e.options?.length?(0,$.jsx)(`select`,{className:`btn btn-slot notice-select`,title:e.hint??e.label,"aria-label":e.label,value:e.options.some(t=>t.value===e.value)?e.value:e.options[0].value,onChange:t=>U(e,t.target.value),children:e.options.map(e=>(0,$.jsx)(`option`,{value:e.value,children:e.label},e.value))},e.id):(0,$.jsxs)(`button`,{type:`button`,className:`btn btn-slot`,title:e.hint??e.label,onClick:()=>U(e),children:[e.icon?`${e.icon} `:``,e.badge??e.label]},e.id))})]}),(0,$.jsxs)(xb,{currentModelId:Pe?`${Pe.provider}/${Pe.id}`:null,children:[(0,$.jsx)(f8,{onAction:(e,t,n)=>U(e,n,t)}),(0,$.jsxs)(`div`,{className:`terminal-workspace terminal-workspace-${Wt}`,children:[(0,$.jsxs)(`div`,{ref:Fe,className:`layout`,style:{"--left-w":`${Ie}px`,"--right-w":`${Le}px`},children:[Re?(0,$.jsx)(`div`,{className:`drawer-backdrop persistent${J?` on`:``}`,onClick:()=>ie(null)}):J&&(0,$.jsx)(`div`,{className:`drawer-backdrop`,onClick:()=>ie(null)}),(0,$.jsx)(bT,{side:`left`,items:k,barProps:ee}),(0,$.jsxs)(`div`,{className:`view-pane ${s===`chat`||s===`terminal`||s===`git`?``:`hidden`}`,children:[!Re&&ze&&(0,$.jsx)(YE,{side:`left`,onClick:He}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-left ${J===`left`?`open`:``}${Re?``:ze?` hidden`:``}`,children:(0,$.jsx)(G7,{quickAskReferenceMenus:e.settings?.quickAskReferenceMenus!==!1,botDraftPrompt:e.settings?.botDraftPrompt,botDraftDefaultPrompt:e.settings?.botDraftDefaultPrompt,collapsible:!Re,onToggleCollapse:He,panelSend:a,onCreateCli:K,active:!Re||J===`left`,unreadConvKeys:Ye,sessionFile:Xe||e.activeConversationId&&e.state?.conversationId!==e.activeConversationId?null:e.state?.sessionFile??null,conversations:e.conversations,elsewhere:e.elsewhere,sessions:e.sessions,projects:e.projects,projectSessions:e.projectSessions,projectSessionsHasMore:e.projectSessionsHasMore,engine:e.engine,connectionEpoch:e.connectionEpoch,pathCompletions:e.pathCompletions,activeConversationId:Xe?``:e.activeConversationId,sharedConversationOwner:e.state?.sharedConversation?.owner,activeGroupId:Xe,activeBotId:Xe?null:e.state?.bot?.id??null,uiContextSession:T[`contextmenu.session`],uiLeftSessions:j,uiContextProject:T[`contextmenu.project`],uiProjectsActions:M,uiLeftProject:N,uiRunningActions:P,uiHistoryActions:F,uiSections:I,renderPluginSectionBody:W,uiLeftRunning:L,uiLeftHistory:R,uiPluginRunning:e.pluginPanelGroups,onPluginRunningAction:G,onUiAction:U,presetNames:Qe,transition:$e,onOpenSandboxModal:me})}),!Re&&!ze&&(0,$.jsx)(JE,{side:`left`,width:Ie,onResize:We}),(0,$.jsxs)(`main`,{className:`${Ke?`main wide-chat`:`main`}${qe?` hide-model-row`:``}${e.transition&&!e.transition.previewMessages?.length?` main-transitioning`:``}${Je?` main-minimal-empty`:``}`,children:[Object.entries(et).map(([i,a])=>{let o=tt&&e.state?.conversationId===i,s=o&&nt&&!e.transition;return(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(`div`,{className:`native-cli-main ${o?``:`hidden`}`,children:(0,$.jsx)(ZE,{chat:e,terminal:t,send:n,conversationId:i,nativeCli:o&&e.state?.nativeCli?e.state.nativeCli:a.nativeCli,active:s,cwd:a.cwd,onAddFiles:_,pushNotice:r})})},i)}),tt&&e.state?.nativeCli&&!et[e.state.conversationId]&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(`div`,{className:`native-cli-main`,children:(0,$.jsx)(ZE,{chat:e,terminal:t,send:n,conversationId:e.state.conversationId,nativeCli:e.state.nativeCli,active:nt&&!e.transition,cwd:e.state.cwd,onAddFiles:_,pushNotice:r})})}),!tt&&(0,$.jsx)(`div`,{className:`native-cli-chat-content`,children:Xe?(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(eD,{roomId:Xe,active:nt,onBack:()=>Ze(null)},Xe)}):(0,$.jsxs)($.Fragment,{children:[e.transition&&(0,$.jsxs)(`div`,{className:`workspace-transition-bar phase-${e.transition.phase}`,role:`status`,"aria-live":`polite`,children:[(0,$.jsx)(`div`,{className:`workspace-transition-track`,children:(0,$.jsx)(`div`,{className:`workspace-transition-fill`,style:{width:`${Math.min(100,Math.max(8,e.transition.progress))}%`}})}),(0,$.jsxs)(`div`,{className:`workspace-transition-pill`,children:[(0,$.jsx)(`span`,{className:`workspace-transition-spinner`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`workspace-transition-text`,children:m4(e.transition,o,Ht)}),(0,$.jsxs)(`span`,{className:`workspace-transition-pct`,children:[e.transition.progress,`%`]})]})]}),B.length>0&&(0,$.jsx)(`div`,{className:`chat-header`,role:`toolbar`,children:Px(B,U)}),e.state?(0,$.jsxs)($.Fragment,{children:[!rt&&e.state.bot&&(0,$.jsxs)(`div`,{className:`bot-chat-bar`,role:`status`,children:[(0,$.jsx)(fe,{"aria-hidden":!0}),(0,$.jsx)(`span`,{children:Ht(`botChatWith`,{name:e.state.bot.name})})]}),!rt&&e.state.sandbox&&(0,$.jsxs)(`div`,{className:`sandbox-banner`,role:`region`,"aria-label":e.state.sandbox.name,children:[(0,$.jsxs)(`div`,{className:`sandbox-banner-info`,children:[(0,$.jsxs)(`span`,{className:`sandbox-banner-title`,children:[(0,$.jsx)(rp,{className:`sandbox-banner-icon`,"aria-hidden":!0}),Ht(`sandboxBannerTitle`,{name:e.state.sandbox.name}),(0,$.jsx)(`span`,{className:`lp-sandbox-badge ${e.state.sandbox.ephemeral?`ephemeral`:`permanent`}`,children:e.state.sandbox.ephemeral?Ht(`sandboxBadgeEphemeral`):Ht(`sandboxBadgePermanent`)})]}),(0,$.jsx)(`span`,{className:`sandbox-banner-desc`,children:e.state.sandbox.sourcePath?Ht(`sandboxBannerSourceDesc`,{source:e.state.sandbox.sourcePath}):Ht(`sandboxBannerBlankDesc`)})]}),(0,$.jsxs)(`div`,{className:`sandbox-banner-actions`,children:[e.state.sandbox.ephemeral&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:Ht(`sandboxActionPersistTip`),onClick:()=>n({type:`persist_sandbox`,path:e.state?.sandbox?.path}),children:[(0,$.jsx)(Ve,{"aria-hidden":!0}),` `,Ht(`sandboxActionPersist`)]}),e.state.sandbox.sourcePath&&(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn primary`,title:Ht(`sandboxActionApplySourceTip`),onClick:()=>de(`apply`),children:[(0,$.jsx)(z,{"aria-hidden":!0}),` `,Ht(`sandboxActionApplySource`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:Ht(`sandboxActionPromoteTip`),onClick:()=>de(`promote`),children:[(0,$.jsx)(Ot,{"aria-hidden":!0}),` `,Ht(`sandboxActionPromote`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn`,title:Ht(`sandboxActionResetTip`),onClick:()=>{let t=e.state?.sandbox;t&&window.confirm(Ht(`sandboxActionResetConfirm`,{name:t.name}))&&n({type:`reset_sandbox`,path:t.path})},children:[(0,$.jsx)(pe,{"aria-hidden":!0}),` `,Ht(`sandboxActionReset`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`sandbox-banner-btn danger`,title:Ht(`sandboxActionDestroyTip`),onClick:()=>{let t=e.state?.sandbox;t&&window.confirm(Ht(`sandboxActionDestroyConfirm`,{name:t.name}))&&n({type:`destroy_sandbox`,path:t.path})},children:[(0,$.jsx)(Ne,{"aria-hidden":!0}),` `,Ht(`sandboxActionDestroy`)]})]})]}),e.state.isEphemeral&&(0,$.jsxs)(`div`,{className:`ephemeral-banner`,children:[(0,$.jsxs)(`span`,{children:[`🎭 `,Ht(`ephemeralBannerText`)]}),(0,$.jsxs)(`button`,{type:`button`,className:`ephemeral-save`,onClick:()=>n({type:`persist_conversation`,id:it}),children:[`💾 `,Ht(`saveEphemeral`)]})]}),(0,$.jsx)(xC,{quickAskTranslateEnabled:e.settings?.quickAskTranslateEnabled!==!1,uiMessageActions:T[`message.actions`],uiContextMessage:T[`contextmenu.message`],uiContextToolCall:T[`contextmenu.toolcall`],uiToolCardFooter:T[`tool.card.footer`],uiChatEmpty:V,onUiAction:U,preview:!!e.transition?.previewMessages?.length,state:e.transition?.previewMessages?.length?{...e.state,conversationId:e.transition.previewConversationId??e.transition.target,sessionFile:e.transition.previewSessionFile,historyStart:0,historyTotal:e.transition.previewMessages.length,messages:e.transition.previewMessages,streamingMessage:null,isStreaming:!1,pendingQuestion:null,pendingApproval:null}:e.state,liveOutputs:e.liveOutputs,toolStatuses:e.toolStatuses,onEdit:at,onKillBash:Gt,onRetry:Kt,onRemoveQueued:ot,onRecallQueued:st,thinkingWrap:e.settings?.thinkingWrap??!0,toolsWrap:e.settings?.toolsWrap??!0,toolImages:e.settings?.toolImagesEnabled??!0,keepRecent:e.settings?.keepRecentMessages,reversePagination:e.settings?.reversePagination??!1,minimalNewChat:e.settings?.minimalNewChat??!1,reasking:!!e.reaskConversationId&&e.reaskConversationId===e.state?.conversationId,jumpTarget:ct,onJumpDone:qt,urlJumpMessageId:ut&&ut.sessionId===e.state.sessionId?ut.messageId:null,onUrlJumpDone:Jt,userPromptNonce:pt},e.transition?.previewMessages?.length?e.transition.previewConversationId??e.transition.target:e.state.conversationId??`boot`)]}):(0,$.jsx)(`div`,{className:`boot-wait`,children:e.ready?Ht(`loadingSession`):Ht(`connectingServer`)}),e.settings?.goalModeEnabled!==!1&&(0,$.jsx)(`div`,{className:`goalbar-slot`,children:(0,$.jsx)(Lx,{goal:e.goal,models:e.models,modelsLoading:e.modelsLoading,activeConversationId:e.activeConversationId,uiGoalbarActions:H,onUiAction:U})}),e.dialog&&(0,$.jsx)(v8,{dialog:e.dialog}),Ee&&(0,$.jsxs)(`div`,{className:`dialog-inline`,"data-dialog-kind":Ee.kind,children:[(0,$.jsxs)(`div`,{className:`dialog-head`,children:[(0,$.jsx)(`span`,{className:`dialog-badge`,children:Ht(`pluginRequest`)}),Ee.title&&(0,$.jsx)(`span`,{className:`dialog-title`,children:Ee.title}),(0,$.jsx)(`button`,{type:`button`,className:`dialog-dismiss`,title:Ht(`cancel`),onClick:()=>{let e=De.current;De.current=null,Oe(null);try{e?.kind===`confirm`?e.resolve(!1):e?.resolve({ok:!1})}catch{}},children:`✕`})]}),Ee.kind===`select`&&(0,$.jsxs)(`div`,{className:`dialog-options`,children:[(Ee.options??[]).map((e,t)=>{let n=Ee.multi?ke.includes(t):!1;return(0,$.jsxs)(`button`,{type:`button`,className:`dialog-option ${n?`sel`:``}`,title:e.description,onClick:()=>{if(Ee.multi){Ae(e=>e.includes(t)?e.filter(e=>e!==t):[...e,t]);return}let n=De.current;De.current=null,Oe(null);try{n?.resolve({ok:!0,selected:[e.label]})}catch{}},children:[e.label,e.description&&(0,$.jsx)(`span`,{className:`dialog-hint`,children:e.description})]},t)}),(Ee.options??[]).length===0&&(0,$.jsx)(`div`,{className:`dialog-hint`,children:Ht(`noOptions`)}),Ee.multi&&(0,$.jsx)(`div`,{className:`dialog-actions`,children:(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=De.current,t=(e?.options??[]).filter((e,t)=>ke.includes(t)).map(e=>e.label);De.current=null,Oe(null);try{e?.resolve({ok:!0,selected:t})}catch{}},children:Ht(`ok`)})})]}),Ee.kind===`confirm`&&(0,$.jsx)(`div`,{className:`dialog-body`,children:(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let e=De.current;De.current=null,Oe(null);try{e?.resolve(!1)}catch{}},children:Ht(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=De.current;De.current=null,Oe(null);try{e?.resolve(!0)}catch{}},children:Ht(`ok`)})]})}),Ee.kind===`input`&&(0,$.jsxs)(`div`,{className:`dialog-body`,children:[(0,$.jsx)(`input`,{className:`dialog-input`,value:je,placeholder:Ee.placeholder||Ht(`inputPlaceholder`),autoFocus:!0,onChange:e=>Me(e.target.value),onKeyDown:e=>{if(e.key===`Enter`&&!e.nativeEvent.isComposing){let e=De.current;De.current=null,Oe(null);try{e?.resolve({ok:!0,value:je})}catch{}}}}),(0,$.jsxs)(`div`,{className:`dialog-actions`,children:[(0,$.jsx)(`button`,{type:`button`,className:`btn`,onClick:()=>{let e=De.current;De.current=null,Oe(null);try{e?.resolve({ok:!1})}catch{}},children:Ht(`cancel`)}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,onClick:()=>{let e=De.current;De.current=null,Oe(null);try{e?.resolve({ok:!0,value:je})}catch{}},children:Ht(`ok`)})]})]})]}),(0,$.jsx)(YC,{questions:PC(e.questionQueue,e.question,e.remoteQuestion,e.globalQuestions,e.state?.sharedConversation?.owner),activeConversationId:it,currentCwd:e.state?.cwd,mode:e.settings?.questionPresentation??`queue`}),(0,$.jsx)(xT,{approvals:FC(e.approvals,e.globalApprovals,e.state?.sharedConversation?.owner),activeConversationId:it,mode:e.settings?.toolApprovalPresentation??`all`}),(0,$.jsx)(kC,{plan:e.activeConversationId&&e.state?.conversationId!==e.activeConversationId?null:e.state?.plan}),Object.entries(mt).map(([e,t])=>(0,$.jsxs)(`div`,{role:`status`,children:[t.percent===void 0?Ht(`uploadPreparing`,{name:t.name}):Ht(`uploadReading`,{name:t.name,percent:t.percent}),(0,$.jsx)(`progress`,{max:100,value:t.percent,"aria-label":t.name})]},e)),rt?(0,$.jsx)(`div`,{className:`sound-hint`,role:`status`,children:`Read-only conversation. Questions and approvals remain available above.`}):e.state&&!e.state.cwd?(0,$.jsx)(`div`,{className:`inputbar`,style:{flexShrink:0},role:`status`,children:(0,$.jsxs)(`div`,{style:{display:`flex`,alignItems:`center`,justifyContent:`space-between`,gap:`12px`,padding:`12px 16px`,borderRadius:`16px`,border:`1px solid var(--border)`,background:`var(--bg-elev2)`,color:`var(--text-muted)`,fontSize:`13px`},children:[(0,$.jsx)(`span`,{children:`请先打开一个项目再开始对话`}),(0,$.jsx)(`button`,{type:`button`,className:`btn primary`,style:{whiteSpace:`nowrap`,flexShrink:0},onClick:he,children:Ht(`openProject`)})]})}):(0,$.jsx)(d8,{composerLeading:T[`composer.leading`],composerActions:T[`composer.actions`],onUiAction:U,streaming:e.state?.isStreaming??!1,onAbort:ht,planMode:e.state?.planMode??!1,messages:e.state?.messages??tD,slashCommands:e.slashCommands,modelState:gt,models:e.models,modelsLoading:e.modelsLoading,providerKeys:e.providerKeys,providers:e.providers,defaultModel:e.defaultModel,attachments:_t,onRemoveAttachment:vt,onAnnotateImage:yt,onAddImageFiles:bt,onAddLocalFiles:xt,onAddPathAttachment:St,fileSearch:e.fileSearch,onSearchFiles:wt,onNotice:r,onManageModels:Tt,onSent:Et,quickPhrases:e.settings?.quickPhrases??[],quickPhrasesEnabled:!f&&(e.settings?.quickPhrasesEnabled??!0)&&(!e.settings?.minimalNewChat||(e.state?.messages?.length??0)>0||!!e.state?.streamingMessage||!!e.state?.isStreaming||!!e.reaskConversationId&&e.reaskConversationId===e.state?.conversationId),recallDrafts:Dt,dshPermCurrent:e.state?.permission??null,claudePermCurrent:e.claudePermission?.current??null,claudePermModes:e.claudePermission?.modes,dshPermOptions:e.dshPermission?.options??void 0,dshPermDefault:e.dshPermission?.defaultPreset,dshPreset:e.state?.agentPreset??null,dshPresets:e.dshPresets?.presets??void 0,dshPresetDefault:e.dshPresets?.defaultPreset,dshBlank:(e.state?.messages?.length??0)===0,conversationId:e.activeConversationId||e.state?.conversationId||``,sessionDraft:e.state?.draft??null,sessionId:e.state?.sessionId??``,preserveDraftAcrossConversations:e.settings?.preserveDraftAcrossConversations??!1,botDraftPrompt:e.settings?.botDraftPrompt,botDraftDefaultPrompt:e.settings?.botDraftDefaultPrompt,activeBotId:e.state?.bot?.id??null,goal:e.goal,goalModeEnabled:e.settings?.goalModeEnabled!==!1})]})})]}),!Re&&!Be&&(0,$.jsx)(JE,{side:`right`,width:Le,onResize:Ge}),(0,$.jsx)(`div`,{className:`panel-drawer drawer-right ${J===`right`?`open`:``}${Re?``:Be?` hidden`:``}`,children:(0,$.jsx)(vT,{desktopVisible:nt&&(Re?J===`right`:!Be),quickAskReferenceMenus:e.settings?.quickAskReferenceMenus!==!1,collapsible:!Re,onToggleCollapse:Ue,panelSend:a,files:e.files,fileSearch:e.fileSearch,fileChanged:e.fileChanged,widgets:e.widgets,onAttach:(e,t,n,r)=>{ie(null),kt(e,t,n,r)},onPreview:(e,t)=>{ie(null),At(e,t)},onOpenInEditor:w.some(e=>e.id===`vscode-editor`)?e=>{ie(null),jt(e)}:void 0,onNotice:(e,t)=>r(e,t),uiRightPanelTabs:T[`rightpanel.tabs`],uiContextFile:T[`contextmenu.file`],plugins:w,pluginsEpoch:e.pluginsEpoch,send:n,scmTab:Mt,onActiveTabChange:e=>{Nt(e),Be||c(t=>e===`scm`?t===`terminal`?t:`git`:t===`git`?b?`terminal`:`chat`:t)}})}),!Re&&Be&&(0,$.jsx)(YE,{side:`right`,onClick:Ue})]}),(0,$.jsx)(`div`,{className:`view-pane ${s===`canvas`?``:`hidden`}`,children:(0,$.jsx)(Ai,{active:s===`canvas`,children:(0,$.jsx)($E,{send:n,active:s===`canvas`,models:e.models,defaultModel:e.defaultModel,installedSkills:e.settings?.skills,projects:e.projects,workspaceRoots:e.state?.workspaceRoots??[],pathCompletions:e.pathCompletions,currentCwd:e.state?.cwd||`.`})})}),(0,$.jsx)(Nr,{open:l,worktree:e.state?.worktree,onRefresh:Pt,onSwitch:t=>{Ft.current={source:e.state?.cwd??``,target:t},n({type:`switch_worktree`,path:t})},onRemove:e=>n({type:`remove_worktree`,path:e}),onClose:()=>u(!1)}),(0,$.jsx)(`div`,{className:`view-pane ${s===`devices`?``:`hidden`}`,children:(0,$.jsx)(Ai,{active:s===`devices`,children:(0,$.jsx)(QE,{pathCompletions:e.pathCompletions,plugins:e.plugins,pluginsEpoch:e.pluginsEpoch})})}),It.map(e=>{let t=`plugin:${e.info.id}`;return(0,$.jsx)(`div`,{className:`view-pane ${s===t?``:`hidden`}`,children:(0,$.jsx)(Zy,{entry:e})},e.info.id)}),s.startsWith(`plugin:`)&&!It.some(e=>`plugin:${e.info.id}`===s)&&(0,$.jsx)(AC,{pluginId:s.slice(7),info:e.plugins.find(e=>`plugin:${e.id}`===s),epoch:e.pluginsEpoch,failed:Lt.includes(s.slice(7))}),(0,$.jsx)(bT,{side:`right`,items:A,barProps:ee})]}),(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(XE,{open:b&&!rt,collapsed:S,onToggleCollapse:()=>C(e=>!e),onHide:()=>ae(`terminal`),tabs:rt?[]:Rt,activeId:zt,onSelectTab:Bt,side:Wt,onSideChange:e=>VE({side:e})})})]})]}),(0,$.jsx)(Mx,{onCreateCli:K,chat:e,bottombarItems:T.bottombar,onUiAction:U,onOpenSettings:()=>{oe(void 0),se(!0)},onViewChange:d,worktreesOpen:l,onOpenGlobalSearch:()=>ce(!0),onOpenBgTasks:()=>Y(!0)}),Vt]})}function rD(e,t,n,r,i,a=!1){let o=new Map;for(let e of r)o.set(e.id,!!e.isStreaming||!!e.completionPending);if(t&&o.set(t,n||a),e===null)return{startCue:!1,finishedConvs:[],nextMap:o};let s=!1;t&&(i===void 0||i===t)&&e.get(t)===!1&&n===!0&&(s=!0);let c=[];for(let[n,i]of e.entries())if(i&&o.has(n)&&!o.get(n)){let e=r.find(e=>e.id===n);if(e?.canceled||e?.error)continue;c.push({id:n,title:e?.title,isActive:n===t,isSubagent:!!e?.isSubagent})}return{startCue:s,finishedConvs:c,nextMap:o}}function iD({chat:e,activeSessionId:t,sound:n,tts:r,send:i,pushNotice:a}){let o=X(),s=(0,Q.useRef)(null),c=(0,Q.useRef)(null),l=(0,Q.useRef)(e.state?.messages);l.current=e.state?.messages;let u=(0,Q.useRef)(new Set),d=(0,Q.useRef)(new Set),f=(0,Q.useRef)(new Set),p=(0,Q.useRef)(0),m=(0,Q.useRef)(e.terminals);(0,Q.useEffect)(()=>{d1(n)},[n]),(0,Q.useEffect)(()=>{F_(r)},[r]),(0,Q.useEffect)(()=>{let t=m.current;m.current=e.terminals;for(let n of e.terminals){let e=n.command?.command??``;t.find(e=>e.id===n.id)?.running&&!n.running&&(e.startsWith(`pi remove `)?i({type:`extensions_reload`}):e.startsWith(`pi-web-ui install `)||e.startsWith(`pi-web-ui uninstall `)?i({type:`plugins_reload`}):e.startsWith(`npm i -g `)&&(i({type:`extensions_reload`}),i({type:`plugins_reload`}),i({type:`check_updates_all`,force:!0}),i({type:`check_engines`,force:!0})))}},[e.terminals,i]),(0,Q.useEffect)(()=>{let i=e.state?.conversationId??null,a=rD(s.current,i,e.state?.isStreaming??!1,e.conversations,c.current,!!e.state?.completionPending||!!e.state?.queue?.steering.length||!!e.state?.queue?.followUp.length);s.current=a.nextMap,c.current=i;for(let[e,t]of a.nextMap.entries())t&&J5(e);if(a.startCue&&(v1(`start`,n),q1(o(`notifyStartTitle`),o(`notifyStartBody`),`start`,t)),a.finishedConvs.length>0){let i=typeof document<`u`&&document.hasFocus?document.hasFocus():!0,s=[];for(let t of a.finishedConvs)if(!t.isActive||!i){let n=e.conversations.find(e=>e.id===t.id);s.push({id:t.id,sessionId:n?.sessionId,sessionFile:n?.sessionFile})}s.length>0&&q5(s),a.finishedConvs.some(e=>!e.isSubagent&&n.done)?v1(`done`,n):a.finishedConvs.some(e=>e.isSubagent)&&v1(`subagentDone`,n);let c=a.finishedConvs.find(e=>e.isActive);if(c&&(q1(o(`notifyDoneTitle`),o(`notifyDoneBody`),c.isSubagent?`subagentDone`:`done`,t),r.enabled)){if(r.readReplies){if(!r.streamReplies){let e=z_(l.current);e?Y_(e,r):r.announce&&!P1(V1())&&Y_(o(`ttsAnnounceDone`),r)}}else r.announce&&!P1(V1())&&Y_(o(`ttsAnnounceDone`),r)}for(let t of a.finishedConvs.filter(e=>!e.isActive)){let n=t.title?`${t.title}:${o(`notifyDoneBody`)}`:o(`notifyDoneBody`),r=e.conversations.find(e=>e.id===t.id)?.sessionId;q1(o(`notifyDoneTitle`),n,t.isSubagent?`subagentDone`:`done`,r)}!c&&r.enabled&&r.announce&&!P1(V1())&&Y_(o(`ttsAnnounceDone`),r)}},[e.state?.conversationId,t,e.state?.isStreaming,e.state?.completionPending,e.state?.queue,e.conversations,n,r,o]),(0,Q.useEffect)(()=>{let t=e.state?.conversationId??null;t&&(J5(t),e.state?.sessionId&&J5(e.state.sessionId),e.state?.sessionFile&&J5(e.state.sessionFile))},[e.state?.conversationId,e.state?.sessionId,e.state?.sessionFile]),(0,Q.useEffect)(()=>{let t=()=>{let t=e.state?.conversationId;t&&(J5(t),e.state?.sessionId&&J5(e.state.sessionId),e.state?.sessionFile&&J5(e.state.sessionFile))};return window.addEventListener(`focus`,t),()=>window.removeEventListener(`focus`,t)},[e.state?.conversationId,e.state?.sessionId,e.state?.sessionFile]);let h=(0,Q.useRef)(null),g=(0,Q.useRef)(null),_=(0,Q.useRef)(0);(0,Q.useEffect)(()=>{let t=e.state?.isStreaming??!1,n=e.state?.conversationId;if(!(r.enabled&&r.readReplies&&r.streamReplies)||!t){if(h.current){let e=l.current,t=Array.isArray(e)&&e.length>0?e[e.length-1]:null;if(t&&t.role===`assistant`&&g.current){let e=(t.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
|
|
413
|
-
`);g.current.flush(e)}h.current.finish(),h.current=null,g.current=null,_.current=0}return}let i=e.state?.messages,a=Array.isArray(i)&&i.length>0?i[i.length-1]:null;if(!a||a.role!==`assistant`)return;let o=Date.now();if(o-_.current<150)return;if(_.current=o,!h.current){let e=Q_(r,n);h.current=e,g.current=new R_(t=>{e.push(t)})}let s=(a.content??[]).filter(e=>e.type===`text`).map(e=>e.text??``).join(`
|
|
414
|
-
`);g.current?.feed(s)},[e.state?.messages,e.state?.isStreaming,e.state?.conversationId,r]),(0,Q.useEffect)(()=>{let t=e.dialog?.id??null;if(t!==null&&!u.current.has(t)){if(u.current.add(t),u.current.size>64){let e=u.current.values().next().value;e!==void 0&&u.current.delete(e)}v1(`question`,n),q1(o(`notifyQuestionTitle`),o(`notifyQuestionBody`),`question`),r.enabled&&r.announce&&!P1(V1())&&Y_(o(`ttsAnnounceQuestion`),r)}},[e.dialog,n,r,o]),(0,Q.useEffect)(()=>{let i=e.question?.id??null,a=e.remoteQuestion?`${e.remoteQuestion.owner}:${e.remoteQuestion.id}`:null,s=new Set;i!==null&&!d.current.has(i)&&(d.current.add(i),s.add(t)),a!==null&&!d.current.has(a)&&(d.current.add(a),s.add(void 0));for(let t of e.conversations){if(!t.hasQuestion)continue;let e=t.questionId?`q:${t.questionId}`:`conv-q:${t.id}`;d.current.has(e)||(d.current.add(e),t.questionId&&d.current.add(t.questionId),i!==t.questionId&&s.add(t.sessionId))}if(d.current.size>64){let e=d.current.values().next().value;e!==void 0&&d.current.delete(e)}if(s.size>0){v1(`question`,n);for(let e of s)q1(o(`notifyQuestionTitle`),o(`notifyQuestionBody`),`question`,e);r.enabled&&r.announce&&!P1(V1())&&Y_(o(`ttsAnnounceQuestion`),r)}},[e.question,e.remoteQuestion,e.conversations,t,n,r,o]),(0,Q.useEffect)(()=>{let t=e.approval,i=t?.id??null;if(i!==null&&!f.current.has(i)){if(f.current.add(i),f.current.size>64){let e=f.current.values().next().value;e!==void 0&&f.current.delete(e)}v1(`approval`,n);let e=typeof t?.toolName==`string`?t.toolName:``;q1(o(`notifyApprovalTitle`),e?o(`notifyApprovalBodyTool`,{tool:e}):o(`notifyApprovalBody`),`approval`),r.enabled&&r.announce&&!P1(V1())&&Y_(o(`ttsAnnounceApproval`),r)}},[e.approval,n,r,o]),(0,Q.useEffect)(()=>{let t=[...e.notices].reverse().find(e=>e.level===`error`);t&&t.id!==p.current&&(p.current=t.id,v1(`error`,n),q1(o(`notifyErrorTitle`),o(`notifyErrorBody`),`error`),r.enabled&&r.announce&&!P1(V1())&&Y_(o(`ttsAnnounceError`),r))},[e.notices,n,r,o]);let v=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{let t=e.state?.messages??[];for(let e of t){if(e.toolName!==`live_preview`||v.current.has(e.id))continue;v.current.add(e.id);let t=``;for(let n of e.content??[]){if(n.type!==`text`)continue;let e=/🔗 已自动在浏览器打开\]\((\/(?!\/)[^)\s]+)\)/.exec(n.text??``);if(e?.[1]){t=e[1];break}}if(!t)continue;let n=null;try{let e=new URL(j(t),window.location.href);e.origin===window.location.origin&&document.hasFocus()&&(n=window.open(e.href,`_blank`,`noopener`))}catch{n=null}n||a(`info`,t)}},[e.state?.messages,a])}var aD=`decorate`,oD=`pi-deco-`,sD=[`color`,`backgroundColor`,`fontWeight`],cD={color:`color`,backgroundColor:`background-color`,fontWeight:`font-weight`};function lD(e,t){return(typeof e==`string`?e.trim().slice(0,32):``).replace(/[^A-Za-z0-9_-]/g,`-`).replace(/-+/g,`-`).replace(/^[-_]+|[-_]+$/g,``)||`r${t+1}`}function uD(e){let t=``;if(typeof e==`string`)for(let n of e)`gimsu`.includes(n)&&!t.includes(n)&&(t+=n);return t.includes(`g`)||(t+=`g`),t}function dD(e,t){if(typeof t!=`string`)return null;let n=t.trim();return!n||n.length>64||/[{}<>;\\"'`]/.test(n)||/url\s*\(/i.test(n)?null:e===`fontWeight`?/^(?:normal|bold|bolder|lighter|[1-9]00)$/.test(n)?n:null:/^[#A-Za-z0-9(),.%\s\-/+]+$/.test(n)?n:null}function fD(e,t,n,r,i){if(typeof t==`string`)return dD(e,t);let a=typeof t?.setting==`string`?t.setting.trim().slice(0,64):``;if(!a)return i.push(`[${n.pluginId}] ${r}.${e}: 非法设置引用(缺少 setting)`),null;let o=n.settingsSchema?.find(e=>e.key===a);if(!o)return i.push(`[${n.pluginId}] ${r}.${e}: settingsSchema 里没有 "${a}"`),null;if(o.type!==`text`&&o.type!==`select`&&o.type!==`number`)return i.push(`[${n.pluginId}] ${r}.${e}: 设置 "${a}" 的类型 ${o.type} 不能用于样式`),null;let s=n.settingsValues?.[a]??o.default;return s==null||s===``?(i.push(`[${n.pluginId}] ${r}.${e}: 设置 "${a}" 没有值`),null):dD(e,String(s))||(i.push(`[${n.pluginId}] ${r}.${e}: 设置 "${a}" 的值不是合法 CSS`),null)}function pD(e,t,n,r){let i=[];for(let a of sD){let o=e.style?.[a];if(o===void 0)continue;let s=fD(a,o,t,n,r);s&&i.push(`${cD[a]}:${s}`)}return i.length?`${i.join(`;`)};`:null}function mD(e){return e?e.some(e=>String(e).split(`:`)[0]?.trim()===aD):!1}function hD(e){let t=e?.setting;return typeof t==`string`?t.trim().slice(0,64):``}function gD(e,t){return e.settingsSchema?.find(e=>e.key===t)}function _D(e){return e===`assistant`||e===`user`?e:`all`}function vD(e,t,n,r){let i=e.enabledBy;if(i===void 0)return!0;let a=(Array.isArray(i)?i:[i]).map(e=>String(e).trim()).filter(Boolean);if(a.length===0)return r.push(`[${t.pluginId}] ${n}: enabledBy 为空,规则被丢弃`),!1;for(let e of a){let i=gD(t,e);if(!i)return r.push(`[${t.pluginId}] ${n}: enabledBy 引用的设置 "${e}" 不存在`),!1;if(i.type!==`boolean`)return r.push(`[${t.pluginId}] ${n}: 设置 "${e}" 不是 boolean,不能当开关`),!1;if((t.settingsValues?.[e]??i.default)!==!0)return!1}return!0}function yD(e,t,n,r){if(typeof e.pattern==`string`){let i=e.pattern.trim();return i?i.length>200?(r.push(`[${t.pluginId}] ${n}: pattern 超过 200 字符`),null):i:(r.push(`[${t.pluginId}] ${n}: pattern 为空`),null)}let i=hD(e.pattern);if(!i)return r.push(`[${t.pluginId}] ${n}: 非法 pattern 引用(缺少 setting)`),null;let a=gD(t,i);if(!a)return r.push(`[${t.pluginId}] ${n}: pattern 引用的设置 "${i}" 不存在`),null;if(a.type!==`text`&&a.type!==`select`)return r.push(`[${t.pluginId}] ${n}: 设置 "${i}" 的类型 ${a.type} 不能当 pattern`),null;let o=t.settingsValues?.[i]??a.default,s=typeof o==`string`?o.trim():``;return s?s.length>200?(r.push(`[${t.pluginId}] ${n}: 设置 "${i}" 的 pattern 超过 200 字符`),null):s:null}function bD(e){let t=[],n=[],r=new Set,i=!1;for(let a of e){let e=a.decorations??[];e.length!==0&&(mD(a.permissions)?(e.length>12&&n.push(`[${a.pluginId}] 只应用前 12 条 chatDecorations(声明了 ${e.length} 条)`),e.slice(0,12).forEach((e,o)=>{if(t.length>=48){i||(i=!0,n.push(`装饰规则总数上限 48:超出的插件/规则被丢弃`));return}let s=lD(e.id,o);if(!vD(e,a,s,n))return;let c=`${oD}${a.pluginId}-${s}`;if(r.has(c)){n.push(`[${a.pluginId}] 重复的规则 id "${s}":后者被丢弃`);return}let l=yD(e,a,s,n);if(!l)return;let u=pD(e,a,s,n);if(!u){n.push(`[${a.pluginId}] ${s}: 没有任何可用的样式,规则被丢弃`);return}let d;try{d=new RegExp(l,uD(e.flags))}catch(e){n.push(`[${a.pluginId}] ${s}: 正则非法(${e.message})`);return}r.add(c),t.push({name:c,pluginId:a.pluginId,ruleId:s,regex:d,declarations:u,scope:_D(e.scope)})})):n.push(`[${a.pluginId}] chatDecorations 已忽略:manifest.permissions 未声明 "${aD}"`))}return{rules:t,diagnostics:n}}function xD(e,t,n=200){let r=[];if(!e)return r;t.lastIndex=0;try{let i;for(;i=t.exec(e);)if(i[0].length===0)t.lastIndex=i.index+1;else if(r.push([i.index,i.index+i[0].length]),r.length>=n)break}finally{t.lastIndex=0}return r}function SD(e,t){let n=[];if(e.length===0||t.length===0)return n;let r=Array(e.length),i=0;for(let t=0;t<e.length;t++)r[t]=i,i+=e[t];let a=(t,n)=>{for(let i=e.length-1;i>=0;i--){let a=r[i],o=e[i];if(!(o<=0)&&(n?t>a&&t<=a+o:t>=a&&t<a+o))return{node:i,offset:t-a}}return null};for(let[e,r]of t){let t=a(e,!1),i=a(r,!0);t&&i&&n.push({fromNode:t.node,fromOffset:t.offset,toNode:i.node,toOffset:i.offset})}return n}var CD=`data-chat-transcript`,wD=`pre, code, kbd, samp, script, style, textarea, .codeblock`,TD=`p, li, blockquote, td, th, h1, h2, h3, h4, h5, h6`,ED=`data-pi-chat-decorations`,DD=6,OD=2e4;function kD(){if(typeof window>`u`||typeof CSS>`u`)return null;let e=globalThis.Highlight,t=CSS.highlights;return typeof e!=`function`||!t?null:{ctor:e,registry:t}}function AD(e){let t=e.querySelectorAll(TD);if(t.length===0)return[e];let n=[];for(let e of t)e.closest(wD)||e.querySelector(TD)&&e.tagName!==`BLOCKQUOTE`||n.push(e);return n}function jD(e,t){let n=t.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,{acceptNode(e){return e.nodeType===Node.ELEMENT_NODE?e.matches(wD)?NodeFilter.FILTER_REJECT:NodeFilter.FILTER_SKIP:NodeFilter.FILTER_ACCEPT}}),r=[];for(let e=n.nextNode();e;e=n.nextNode())r.push(e);return r}function MD(e,t={}){let n=t.doc??(typeof document>`u`?null:document),r=kD();if(!n||e.length===0||!r)return{flush(){},dispose(){}};let i=n.createElement(`style`);i.setAttribute(ED,``),i.textContent=e.map(e=>`::highlight(${e.name}){${e.declarations}}`).join(`
|
|
415
|
-
`),n.head.appendChild(i);let a=new Map;for(let t of e){let e=new r.ctor;r.registry.set(t.name,e),a.set(t.name,e)}let o=new Map,s=new Set,c=0,l=!1,u=e=>{let t=e.nodeType===Node.ELEMENT_NODE?e:e.parentElement;if(!t)return[];let n=t.closest(`[${CD}]`);return n?[n]:t.querySelectorAll?[...t.querySelectorAll(`[${CD}]`)]:[]},d=e=>{if(e.nodeType!==Node.ELEMENT_NODE)return[];let t=e,n=t.matches(`[data-chat-transcript]`)?[t]:[];for(let e of t.querySelectorAll(`[${CD}]`))n.push(e);return n},f=e=>{let t=o.get(e);if(t){for(let e of a.values())for(let n of t)e.delete(n);o.delete(e)}},p=t=>{if(f(t),!t.isConnected)return;let r=[],i=t.querySelectorAll(`.md`),s=i.length>0?[...i]:[];for(let t of s){let i=t.closest(`[data-role]`)?.getAttribute(`data-role`)??``,o=e.filter(e=>e.scope===`all`||e.scope===i);if(o.length!==0)for(let e of AD(t)){if(r.length>OD)break;let t=jD(e,n);if(t.length===0)continue;let i=``,s=[];for(let e of t)s.push(e.data.length),i+=e.data;for(let e of o){let o=a.get(e.name);if(o)for(let a of SD(s,xD(i,e.regex))){let e=t[a.fromNode],i=t[a.toNode];if(!e||!i)continue;let s=n.createRange();s.setStart(e,a.fromOffset),s.setEnd(i,a.toOffset),o.add(s),r.push(s)}}}}o.set(t,r)},m=()=>{let e=s.values().next();return e.done?null:(s.delete(e.value),e.value)},h=()=>{if(c=0,l)return;let e=Date.now();for(;s.size>0;){if(Date.now()-e>DD){g();return}let t=m();if(!t)return;p(t)}},g=()=>{l||c||(c=requestAnimationFrame(h))},_=e=>{l||(s.add(e),g())},v=new MutationObserver(e=>{for(let t of e){for(let e of u(t.target))_(e);for(let e of t.addedNodes)for(let t of u(e))_(t);for(let e of t.removedNodes)for(let t of d(e))f(t)}});v.observe(n.body,{childList:!0,characterData:!0,subtree:!0});for(let e of n.querySelectorAll(`[${CD}]`))_(e);return{flush(){if(!l){for(c&&=(cancelAnimationFrame(c),0);s.size>0;){let e=m();if(!e)return;p(e)}for(let e of Array.from(o.keys()))p(e)}},dispose(){if(!l){l=!0,v.disconnect(),c&&cancelAnimationFrame(c),c=0,s.clear();for(let e of a.keys())r.registry.delete(e);a.clear(),o.clear(),i.remove()}}}}function ND(e){return{pluginId:e.id,permissions:e.permissions,decorations:e.chatDecorations,settingsSchema:e.settingsSchema,settingsValues:e.settingsValues}}function PD(e){let t=(0,Q.useMemo)(()=>bD((e??[]).map(ND)),[e]);(0,Q.useEffect)(()=>{for(let e of t.diagnostics)console.warn(`[chat-decorations]`,e)},[t]),(0,Q.useEffect)(()=>{if(t.rules.length===0)return;let e=MD(t.rules);return()=>e.dispose()},[t])}function FD(e,t){let n=X(),r=(0,Q.useMemo)(()=>e.plugins.filter(t=>!e.settings?.disabledPlugins?.includes(t.id)),[e.plugins,e.settings?.disabledPlugins]);PD(r);let[i,a]=(0,Q.useMemo)(()=>{let r=[];return[Ug(jg(e.plugins),{locale:t,t:e=>n(e),disabledPlugins:e.settings?.disabledPlugins??[],layout:e.settings?.uiLayout,diagnostics:r}),r]},[e.plugins,e.settings?.disabledPlugins,e.settings?.uiLayout,t,n]),o=(0,Q.useRef)(``);return(0,Q.useEffect)(()=>{let e=a.map(e=>`${e.level}:${e.pluginId??``}:${e.entryId??``}:${e.message}`).join(`
|
|
416
|
-
`);if(e!==o.current){o.current=e;for(let e of a){let t=`[ui-slot] ${e.pluginId?`[${e.pluginId}] `:``}`;e.level===`error`?console.error(`${t}${e.message}`):e.level===`warn`?console.warn(`${t}${e.message}`):console.debug(`${t}${e.message}`)}}},[a]),{enabledPlugins:r,uiSlots:i,uiPrimary:(0,Q.useMemo)(()=>i[`topbar.primary`].filter(e=>!e.hidden),[i]),uiOverflow:(0,Q.useMemo)(()=>[...i[`topbar.primary`].filter(e=>e.hidden),...i[`topbar.overflow`]],[i]),uiLeftSessions:(0,Q.useMemo)(()=>i[`leftpanel.sessions`].filter(e=>!e.hidden),[i]),uiLeftProjectsActions:(0,Q.useMemo)(()=>i[`leftpanel.projects.actions`].filter(e=>!e.hidden),[i]),uiLeftProject:(0,Q.useMemo)(()=>i[`leftpanel.project`].filter(e=>!e.hidden),[i]),uiLeftRunningActions:(0,Q.useMemo)(()=>i[`leftpanel.running.actions`].filter(e=>!e.hidden),[i]),uiLeftHistoryActions:(0,Q.useMemo)(()=>i[`leftpanel.history.actions`].filter(e=>!e.hidden),[i]),uiLeftSections:i[`leftpanel.sections`],uiLeftRunning:(0,Q.useMemo)(()=>i[`leftpanel.running`].filter(e=>!e.hidden),[i]),uiLeftHistory:(0,Q.useMemo)(()=>i[`leftpanel.history`].filter(e=>!e.hidden),[i]),uiTerminalToolbar:(0,Q.useMemo)(()=>i[`terminal.toolbar`].filter(e=>!e.hidden),[i]),uiScmToolbar:(0,Q.useMemo)(()=>i[`scm.toolbar`].filter(e=>!e.hidden),[i]),uiGoalbarActions:(0,Q.useMemo)(()=>i[`goalbar.actions`].filter(e=>!e.hidden),[i]),uiChatHeader:(0,Q.useMemo)(()=>i[`chat.header`].filter(e=>!e.hidden),[i]),uiChatEmpty:(0,Q.useMemo)(()=>i[`chat.empty`].filter(e=>!e.hidden),[i]),uiFilePreviewToolbar:(0,Q.useMemo)(()=>i[`file.preview.toolbar`].filter(e=>!e.hidden),[i]),presetNames:(0,Q.useMemo)(()=>Object.fromEntries((e.dshPresets?.presets??[]).map(e=>[e.id,Y6(e,t,n).name])),[e.dshPresets,t]),uiNoticeActions:(0,Q.useMemo)(()=>i[`notice.actions`].filter(e=>!e.hidden),[i]),uiSidebarLeft:(0,Q.useMemo)(()=>i[`sidebar.left`]??[],[i]),uiSidebarRight:(0,Q.useMemo)(()=>i[`sidebar.right`]??[],[i])}}function ID(e,t){let n=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{let r=N4(n.current,e);n.current=r.key,r.clear&&t()},[e,t])}function LD(e,t){let n=Da(e);if(n.quotes?.length&&t(e=>P4(e,n.quotes.map(e=>({path:``,name:``,mode:`quote`,quote:e,key:or()})))),n.attachments?.length){let e=n.attachments.filter(e=>e.type!==`vision-bridge`).map(e=>({path:e.path||e.url||``,name:e.name,mode:e.type===`page`?`page`:e.type===`canvas`?`canvas`:e.type===`conversation`?`conversation`:e.lines?`lines`:`reference`,lines:e.lines,key:or()}));e.length&&t(t=>P4(t,e))}return n.text}function RD({chat:e,send:t,pushNotice:n,setAttachments:r,nativeCliViewRef:i}){let a=X(),o=(e,t,o,s=!1,c,l=!1)=>{if(i.current){ir({attachments:[{path:e,name:t,mode:o,isDir:s,...c?{lines:c}:{}}]})||n(`warning`,a(`nativeCliDisconnected`));return}let u=`${e}|${o}|${c?`${c.start}-${c.end}`:``}`;r(n=>n.some(e=>`${e.path}|${e.mode}|${e.lines?`${e.lines.start}-${e.lines.end}`:``}`===u)?n:[...n,{path:e,name:t,mode:o,isDir:s,...c?{lines:c}:{}}]);let d=o===`page`||o===`canvas`?t:e;!l&&d&&!i.current&&qn(`@${d} `)},s=e=>{let t=``;r(n=>n.filter(n=>{let r=n.key?n.key===e:n.mode===`conversation`?`conv|${n.conversationId??``}|${n.sessionPath??``}`===e:n.path===e;return r&&!t&&(t=n.mode===`page`||n.mode===`conversation`||n.mode===`canvas`?n.name:n.path),!r})),t&&Zn(`@${t}`)},c=mn(`chatUploadMaxMb`),[l,u]=(0,Q.useState)({}),d=(0,Q.useRef)(0),f=(0,Q.useRef)(0),p=(0,Q.useRef)(0),m=(0,Q.useCallback)(t=>{let i=Date.now();e.state?.model&&!e.state.model.vision&&i-p.current>1e4&&(p.current=i,n(`warning`,a(`imageNotSupported`)));let o=`paste-${++f.current}`;r(e=>[...e,{path:``,key:o,name:t.name,imageData:t.data,mimeType:t.mimeType}])},[e.state?.model,n,r,a]),h=(0,Q.useCallback)(async e=>{for(let t of e){if(t.size>c*1024*1024){n(`warning`,a(`fileTooLarge`,{name:t.name,size:c}));continue}let e=String(++d.current);u(n=>({...n,[e]:{name:t.name}}));try{let e=await ha(t);e?m(e):n(`error`,a(`imageLoadFailed`,{name:t.name}))}catch{n(`error`,a(`imageLoadFailed`,{name:t.name}))}finally{u(t=>{let n={...t};return delete n[e],n})}}},[m,n,a,c]),g=c*1024*1024,_=(0,Q.useRef)(0),v=(0,Q.useCallback)(async e=>{if(e.size>g){n(`warning`,a(`fileTooLarge`,{name:e.name,size:g/1024/1024}));return}let t=String(++d.current);u(n=>({...n,[t]:{name:e.name,percent:0}}));let i;try{i=(await new Promise((n,r)=>{let i=new FileReader;i.onprogress=n=>{n.lengthComputable&&u(r=>({...r,[t]:{name:e.name,percent:Math.round(n.loaded/n.total*100)}}))},i.onload=()=>n(i.result),i.onerror=()=>r(i.error??Error(`read failed`)),i.onabort=()=>r(Error(`read aborted`)),i.readAsDataURL(e)})).replace(/^data:[^;]*;base64,/,``)}catch{n(`error`,a(`fileLoadFailed`,{name:e.name}));return}finally{u(e=>{let n={...e};return delete n[t],n})}let o=`upload-${++_.current}`;r(t=>[...t,{path:``,key:o,name:e.name,fileData:i,size:e.size,mimeType:e.type||void 0}])},[g,n,r,a]),y=(0,Q.useCallback)(async e=>{for(let t of e)ma(t.type)?await h([t]):await v(t)},[h,v]),b=(0,Q.useCallback)(async e=>{let t=nr();if(!t)n(`warning`,a(`nativeCliDisconnected`));else for(let r of e)if(r.size>g)n(`warning`,a(`fileTooLarge`,{name:r.name,size:c}));else try{let e=await new Promise((e,t)=>{let n=new FileReader;n.onload=()=>e(String(n.result).replace(/^data:[^;]*;base64,/,``)),n.onerror=()=>t(n.error),n.onabort=()=>t(Error(`read aborted`)),n.readAsDataURL(r)});t.compose({attachments:[{path:``,name:r.name,fileData:e,size:r.size,mimeType:r.type||void 0}]})||n(`error`,a(`fileLoadFailed`,{name:r.name}))}catch{n(`error`,a(`fileLoadFailed`,{name:r.name}))}},[g,c,n,a]);(0,Q.useEffect)(()=>{let t=e.nativeCliPasteResult;t&&!t.ok&&n(`error`,a(`nativeCliPasteFailed`,{error:t.error??``}))},[e.nativeCliPasteResult,n,a]);let x=(0,Q.useCallback)((e,n,r)=>{t({type:`edit_message`,messageId:e,text:n,attachments:r})},[t]),S=(0,Q.useCallback)((e,n,r,i)=>{t({type:`queue_remove`,kind:e,text:n,index:r,id:i})},[t]),[C,w]=(0,Q.useState)([]),T=(0,Q.useRef)(0),E=(0,Q.useCallback)((e,n,i,a)=>{t({type:`queue_remove`,kind:e,text:n,index:i,id:a}),T.current+=1;let o=LD(n,r);w(e=>[...e.slice(-9),{text:o,seq:T.current}])},[t,r]),D=(0,Q.useCallback)(()=>r([]),[r]),[O,k]=(0,Q.useState)(0),A=(0,Q.useCallback)(()=>{D(),k(e=>e+1)},[D]),j=(0,Q.useCallback)(()=>{let n=e.state?.queue?.steering??[],i=e.state?.queue?.followUp??[];for(let e of[...n,...i]){T.current+=1;let t=LD(e,r);w(e=>[...e.slice(-9),{text:t,seq:T.current}])}t({type:`abort`})},[e.state?.queue?.steering,e.state?.queue?.followUp,t,r]);return ID(e.state?.sessionId??``,D),{attach:o,removeAttachment:s,attachmentProgress:l,addImageFiles:h,addLocalFiles:y,addNativeCliFiles:b,onEditMessage:x,onRemoveQueued:S,recallDrafts:C,onRecallQueued:E,userPromptNonce:O,handleSent:A,handleAbort:j,removeAttachmentCb:(0,Q.useCallback)(s,[]),annotateImageCb:(0,Q.useCallback)(async(e,t)=>{if(!t.startsWith(`data:image/png;base64,`))throw Error(`Invalid annotated image`);let n=await(await fetch(t)).blob(),i=`${e.name.replace(/\.[^.]+$/,``).replace(/-annotated$/,``)}-annotated`,a=await ha(new File([n],`${i}.png`,{type:`image/png`}));if(!a||a.size>2097152)throw Error(`Annotated image exceeds the attachment limit`);let o={path:``,name:`${i}.${a.mimeType===`image/jpeg`?`jpg`:a.mimeType===`image/webp`?`webp`:`png`}`,key:e.key||or(),imageData:a.data,mimeType:a.mimeType,size:a.size};r(t=>t.map(t=>t===e?o:t))},[r]),addImageFilesCb:h,addLocalFilesCb:y,searchFilesCb:(0,Q.useCallback)((e,n)=>t({type:`search_files`,reqId:e,query:n}),[t]),addPathAttachmentCb:(0,Q.useCallback)(e=>o(e.path,e.name,e.mode??`reference`,e.isDir??!1,e.lines,e.silent??!1),[])}}function zD({ready:e,activeSessionId:t,notices:n,send:r,pushNotice:i,setView:a,setActiveGroupId:s}){let[c,l]=(0,Q.useState)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=(0,Q.useRef)(t);f.current=t;let p=(0,Q.useRef)(e);p.current=e,(0,Q.useEffect)(()=>{let e=()=>{if(b())return;let e=D_(window.location.hash);e&&(e.messageId?l({sessionId:e.sessionId,messageId:e.messageId}):l(null),!p.current||!f.current?u.current=e.sessionId:f.current===e.sessionId||f.current&&e.sessionId&&(f.current.includes(e.sessionId)||e.sessionId.includes(f.current))||(d.current=e.sessionId,a(`chat`),r({type:`switch_session`,path:``,sessionId:e.sessionId})))};e(),window.addEventListener(`hashchange`,e),window.addEventListener(`popstate`,e);let t=b1(t=>{window.history.replaceState(null,``,t),s(null),a(`chat`),e()});return()=>{window.removeEventListener(`hashchange`,e),window.removeEventListener(`popstate`,e),t()}},[r,s,a]);let m=(0,Q.useRef)(null);return(0,Q.useEffect)(()=>{if(!J()||!e)return;let t=e=>{let t=o()??e?.detail;if(!t||t.eventId&&t.eventId===m.current)return;let n=ce(t,Po());if(!n){i(`warning`,`The notification no longer identifies an open conversation.`);return}m.current=t.eventId,u.current=null,d.current=null,l(null),s(null),a(`chat`);let c=new URL(window.location.href);c.searchParams.delete(`token`),c.searchParams.delete(`view`),c.hash=``,window.history.replaceState(null,``,c.href),r(n)};return window.addEventListener(jt,t),t(),()=>window.removeEventListener(jt,t)},[e,i,r,s,a]),(0,Q.useEffect)(()=>{let e=d.current;if(e&&n.some(t=>t.text.includes(e)&&(t.text.includes(`未找到会话`)||t.text.includes(`Session not found`)))&&(d.current=null,l(null),t)){let e=O_({sessionId:t});window.location.hash!==e&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${e}`)}},[n,t]),(0,Q.useEffect)(()=>{if(!e||!t)return;if(u.current){let e=u.current;u.current=null;let n=e===t||e&&t&&(e.includes(t)||t.includes(e));if(s(null),a(`chat`),!n){d.current=e,r({type:`switch_session`,path:``,sessionId:e});return}}if(d.current){if(t===d.current||t&&d.current&&(t.includes(d.current)||d.current.includes(t)))d.current=null;else return}let n=D_(window.location.hash),i=n?.sessionId===t?n.messageId:void 0,o=O_({sessionId:t,...i?{messageId:i}:{}});window.location.hash!==o&&window.history.replaceState(null,``,`${window.location.pathname}${window.location.search}${o}`)},[e,t,r,s,a]),{urlJump:c,setUrlJump:l}}var BD=.4,VD=1.05;function HD(e){return Math.min(300,e*.86)}function UD(e,t,n){return n||(t<=144?null:e<=72?`left`:t-e<=72?`right`:null)}function WD(e,t){let n=Math.abs(e),r=Math.abs(t);return n<12&&r<12?`none`:n>r*1.2?`horizontal`:`vertical`}function GD(e,t){return e===`left`?t:-t}function KD(e,t){return Math.max(-e,Math.min(0,-e+t))}function qD(e,t,n){let r=n?e+t:t;return Math.max(0,Math.min(1,r/e))}function JD(e){let{wasOpen:t,pull:n,width:r,durationMs:i}=e;return i<=320&&Math.abs(n)>=48?n>0:qD(r*VD,n,t)>=BD}var YD=new Set([`auto`,`scroll`,`overlay`]);function XD(e,t){let n=e instanceof Element?e:null;for(;n;){if(n instanceof HTMLElement&&n.scrollWidth>n.clientWidth+4&&YD.has(getComputedStyle(n).overflowX))return!0;if(n===t)break;n=n.parentElement}return!1}function ZD(){let e=e=>{e.stopPropagation(),e.preventDefault()};window.addEventListener(`click`,e,{capture:!0,once:!0}),setTimeout(()=>window.removeEventListener(`click`,e,{capture:!0}),400)}function QD(e){let{enabled:t,open:n,onOpenChange:r,container:i}=e,{panelSelector:a,backdropSelector:o}=e;(0,Q.useEffect)(()=>{let e=i.current;if(!t||!e)return;let s=null,c=`none`,l=0,u=0,d=0,f=0,p=!1,m=0,h=0,g=null,_=null,v=()=>{g&&(g.classList.remove(`drawer-dragging`),g.style.transform=``),_&&(_.style.opacity=``),s=null,c=`none`,g=null,_=null,f=0,p=!1},y=t=>{if(v(),t.touches.length!==1)return;let r=t.touches[0],i=UD(r.clientX,window.innerWidth,n);i&&!XD(t.target,e)&&(s=i,l=r.clientX,u=r.clientY,d=Date.now())},b=t=>{let r=s;if(!r||t.touches.length!==1)return;let i=t.touches[0],d=i.clientX-l,v=i.clientY-u;if(c===`none`){let t=WD(d,v);if(t===`none`)return;if(t===`vertical`){s=null;return}c=`horizontal`,p=n===r,m=HD(window.innerWidth),h=m*VD;let i=e.querySelector(a?a(r):`.panel-drawer.drawer-${r}`);if(!i){s=null;return}g=i,_=o===null?null:e.querySelector(o??`.drawer-backdrop`),i.classList.add(`drawer-dragging`)}let y=g;if(!y)return;f=GD(r,d);let b=KD(h,f);y.style.transform=`translateX(${r===`left`?b:-b}px)`,_&&(_.style.opacity=String(qD(h,f,p))),t.preventDefault()},x=()=>{let e=s,t=c===`horizontal`&&e!==null&&g!==null,i=f,a=Date.now()-d,o=t?JD({wasOpen:p,pull:i,width:m,durationMs:a}):!1;v(),t&&e&&o!==(n===e)&&(ZD(),r(o?e:null))},S=()=>v();return e.addEventListener(`touchstart`,y,{passive:!0}),e.addEventListener(`touchmove`,b,{passive:!1}),e.addEventListener(`touchend`,x),e.addEventListener(`touchcancel`,S),()=>{v(),e.removeEventListener(`touchstart`,y),e.removeEventListener(`touchmove`,b),e.removeEventListener(`touchend`,x),e.removeEventListener(`touchcancel`,S)}},[t,n,r,i,a,o])}function $D(e,t){let n=X(),r=BE(),[i,a]=(0,Q.useState)(r.open),[o,s]=(0,Q.useState)(r.collapsed),[c,l]=(0,Q.useState)(r.activeTab??`host:bottom-terminal`),[u,d]=(0,Q.useState)(p4);(0,Q.useEffect)(()=>{VE({open:i})},[i]),(0,Q.useEffect)(()=>{VE({collapsed:o})},[o]),(0,Q.useEffect)(()=>{VE({activeTab:c})},[c]);let[f,p]=(0,Q.useState)(()=>l4(`left`)),[m,h]=(0,Q.useState)(()=>l4(`right`)),g=(0,Q.useCallback)(e=>p(e),[]),_=(0,Q.useCallback)(e=>h(e),[]),[v,y]=(0,Q.useState)(()=>f4(`left`)),[b,x]=(0,Q.useState)(()=>f4(`right`)),S=!b&&u===`scm`,C=(0,Q.useCallback)(()=>{y(e=>{try{localStorage.setItem(u4(`left`),e?`0`:`1`)}catch{}return!e})},[]),w=(0,Q.useCallback)(()=>{x(e=>(d4(`right`,!e),!e))},[]);(0,Q.useEffect)(()=>{b&&e===`git`&&t(i?`terminal`:`chat`)},[b,e,i,t]);let[T,E]=(0,Q.useState)(null),D=(0,Q.useRef)(null),[O,k]=(0,Q.useState)(()=>window.matchMedia(`(max-width: 768px)`).matches);return(0,Q.useEffect)(()=>{let e=()=>{t(`chat`),x(!1),O&&E(`right`)};return window.addEventListener(`pi:desktop-open`,e),()=>window.removeEventListener(`pi:desktop-open`,e)},[O,t]),(0,Q.useEffect)(()=>{if(!Ad())return;let e=new AbortController;return jd(n,n(`desktop.currentDevice`),e.signal).catch(()=>{}),()=>e.abort()},[n]),(0,Q.useEffect)(()=>{let e=window.matchMedia(`(max-width: 768px)`),t=e=>k(e.matches);return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[]),QD({enabled:O&&e===`chat`,open:T,onOpenChange:E,container:D,backdropSelector:`.drawer-backdrop.persistent`}),{termDrawerOpen:i,setTermDrawerOpen:a,termCollapsed:o,setTermCollapsed:s,bottomTab:c,setBottomTab:l,rightTab:u,setRightTab:d,leftWidth:f,rightWidth:m,setRightWidth:h,resizeLeft:g,resizeRight:_,leftCollapsed:v,setLeftCollapsed:y,rightCollapsed:b,setRightCollapsed:x,gitDrawerOpen:S,toggleLeft:C,toggleRight:w,drawer:T,setDrawer:E,layoutRef:D,isMobile:O}}function eO({chat:e,enabledPlugins:t,uiSlots:n,send:r,pushNotice:i,setView:a,openInVscodeEditor:o}){let s=X(),{locale:c}=_e(),l=(0,Q.useRef)(e);l.current=e;let u=(0,Q.useRef)(null),d=(0,Q.useRef)(a);d.current=a;let f=(0,Q.useRef)(c);f.current=c;let p=(0,Q.useRef)(n);p.current=n;let[m,h]=(0,Q.useState)([]);(0,Q.useEffect)(()=>O0(h),[]);let[g,_]=(0,Q.useState)([]);(0,Q.useEffect)(()=>E0(_),[]);let[v,y]=(0,Q.useState)(null),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(null),[w,T]=(0,Q.useState)(null),E=(0,Q.useRef)(null),[D,O]=(0,Q.useState)(null),k=(0,Q.useRef)(null),[A,j]=(0,Q.useState)([]),[M,N]=(0,Q.useState)(``),[P,F]=(0,Q.useState)(null),I=(0,Q.useRef)(null),L=v?n[`modal.dialog`].find(e=>e.id===v&&!e.hidden):void 0,R=(0,Q.useMemo)(()=>{if(!L||L.kind!==`view`)return``;let e=L.view??``;return e.startsWith(`plugin:`)?e.slice(7):L.source.startsWith(`plugin:`)?L.source.slice(7):``},[L]);(0,Q.useEffect)(()=>{if(!L||!R||m.some(e=>e.info.id===R))return;let e=l.current.plugins.find(e=>e.id===R);e&&F0(e,l.current.pluginsEpoch)},[L,R,m,e.pluginsEpoch]),(0,Q.useEffect)(()=>{jc(r),Mc(t,e.pluginsEpoch),zc(t,e.pluginsEpoch),qy(t,e.pluginsEpoch),I0(t,e.pluginsEpoch)},[t,e.pluginsEpoch,r]),(0,Q.useEffect)(()=>{ua(()=>{let e=l.current;if(!e.ready)throw Error(s(`imageOcrInstallFailed`));let t=e.plugins.find(e=>e.id===`image-ocr`);if(t?.error)throw Error(t.error);u.current=null;let n=e.settings?.disabledPlugins??[],i=n.includes(`image-ocr`);if(i&&r({type:`set_settings`,disabledPlugins:n.filter(e=>e!==`image-ocr`)}),t)i||r({type:`plugins_reload`});else{let t=Object.values(e.pluginJobs).find(e=>e.pluginId===`image-ocr`&&e.phase!==`done`),n=t?.jobId??or();u.current=n,t||r({type:`plugin_job`,jobId:n,action:`install`,id:`image-ocr`,source:`xing-shuyin/keel/plugins/image-ocr`})}});let e=wn(()=>{En().length&&sa(!1)}),t=E0(e=>{e.includes(`image-ocr`)&&sa(!1,s(`imageOcrInstallFailed`))});return()=>{ua(null),e(),t()}},[r,s]),(0,Q.useEffect)(()=>{if(!e.ready){sa(!1);return}let t=u.current?e.pluginJobs[u.current]:void 0;t&&sa(t.phase!==`done`,t.phase===`done`&&!t.ok?t.error||s(`imageOcrInstallFailed`):``)},[e.pluginJobs,e.ready,s]),(0,Q.useEffect)(()=>{if(!D)return;let e=e=>{if(e.key!==`Escape`)return;let t=k.current;k.current=null,O(null);try{if(!t)return;t.kind===`confirm`?t.resolve(!1):t.resolve({ok:!1})}catch{}};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[D]),(0,Q.useEffect)(()=>{if(!P)return;let e=setTimeout(()=>{let e=I.current;I.current=null,F(null);try{e?.resolve(null)}catch{}},8e3);return()=>clearTimeout(e)},[P]);let z=(0,Q.useCallback)((e,t,n)=>{if(e.id===`host:msg-fork`){n?.id&&r({type:`fork_session`,messageId:n.id,position:`before`});return}if(e.id===`host:msg-rollback`){n?.id&&x2({messageId:n.id});return}let o=(e.action??``).trim();if(e.kind===`view`||(!o||o===`view`)&&e.source!==`host`){a(e.view??`plugin:${e.source.startsWith(`plugin:`)?e.source.slice(7):``}`);return}if(!o)return;let c=e.source.startsWith(`plugin:`)?e.source.slice(7):``;jn(c,o,e.id,{...t===void 0?{}:{value:t},...n===void 0?{}:{target:n},loadBundle:async e=>{let t=l.current.plugins.find(t=>t.id===e);return t?F0(t,l.current.pluginsEpoch):!1}}).then(e=>{e||i(`info`,s(`pluginUiNoHandler`))})},[s,i,r,a]),B=(0,Q.useCallback)(t=>{let n=e.plugins.find(e=>e.id===t.source.slice(7));return n?(0,$.jsx)(Pw,{plugin:n,epoch:e.pluginsEpoch,send:r,className:`lp-plugin-page`}):null},[e.plugins,e.pluginsEpoch,r]),V=(0,Q.useCallback)((e,t)=>{t.action&&jn(e.pluginId,t.action,t.id,{target:{id:t.id,kind:`plugin-running`,label:t.title},loadBundle:async e=>{let t=l.current.plugins.find(t=>t.id===e);return t?F0(t,l.current.pluginsEpoch):!1}}).then(e=>{e||i(`info`,s(`pluginUiNoHandler`))})},[s,i]);return(0,Q.useEffect)(()=>(kn(Vn({send:r,isReady:()=>!!l.current.state,setView:e=>d.current(e),getCwd:()=>l.current.state?.cwd??``,getWorkspaceRoots:()=>l.current.state?.workspaceRoots??[],listSessions:()=>{let e=l.current,t=e.state?.cwd??``;return[...e.conversations.map(e=>({id:e.id,title:e.title,cwd:e.cwd||t,kind:`running`,isStreaming:e.isStreaming})),...(e.elsewhere??[]).filter(e=>!!(e.convId&&e.owner)).map(e=>({id:JSON.stringify([e.owner,e.convId]),conversationId:e.convId,title:e.title,cwd:e.cwd||t,kind:`elsewhere`,owner:e.owner,independent:e.independent,isStreaming:e.isStreaming})),...e.sessions.map(e=>({id:e.path,title:e.displayName||e.name||e.firstMessage?.trim()||e.path,cwd:t,kind:`history`}))]},getConversationId:()=>l.current.state?.conversationId??null,getLocale:()=>f.current,getConversationOwner:()=>l.current.state?.sharedConversation?.owner??null,isConversationBlank:()=>(l.current.state?.messages.length??0)===0,listModels:()=>l.current.models.map(e=>({id:e.id,provider:e.provider,name:e.name,vision:e.vision,reasoning:e.reasoning})),getCurrentModelId:()=>{let e=l.current.state?.model;return e?`${e.provider}/${e.id}`:null},listProjects:()=>l.current.projects.map(e=>e.path),grantedPaths:v4,grantPath:y4,confirm:e=>new Promise(t=>{if(E.current){t(!1);return}let n={path:e.path,resolve:t};E.current=n,T(n)}),openModal:e=>{let t=String(e??``).trim();if(!t)return!1;let n=p.current[`modal.dialog`].find(e=>e.id===t);return!n||n.hidden?!1:(y(t),!0)},closeModal:()=>y(null),setFooterStatus:(e,t)=>o0(e,t?{...t}:null),pickDirectory:e=>new Promise(t=>{x({initialPath:e?.initialPath,resolve:t})}),pickModel:e=>new Promise(t=>{C({currentModelId:e?.currentModelId,resolve:t})}),dialogConfirm:e=>new Promise(t=>{if(k.current){t(!1);return}let n={kind:`confirm`,title:e.title,resolve:t};k.current=n,O(n)}),select:e=>new Promise(t=>{if(k.current){t({ok:!1,error:`busy`});return}let n={kind:`select`,title:e.title,options:e.options,...e.multi?{multi:!0}:{},resolve:t};k.current=n,j([]),O(n)}),input:e=>new Promise(t=>{if(k.current){t({ok:!1,error:`busy`});return}let n={kind:`input`,title:e.title,...typeof e.placeholder==`string`?{placeholder:e.placeholder}:{},...typeof e.initial==`string`?{initial:e.initial}:{},resolve:t};k.current=n,N(e.initial??``),O(n)}),notifyAction:e=>new Promise(t=>{try{let n=I.current;I.current=null,F(null);try{n?.resolve(null)}catch{}let r={text:e.text,actions:e.actions,resolve:t};I.current=r,F(r)}catch{t(null)}}),loadPluginBundle:e=>{let t=l.current.plugins.find(t=>t.id===e);return t?F0(t,l.current.pluginsEpoch):Promise.resolve(!1)},openFileContextMenu:e=>{let n=String(e.path??``).replace(/\\/g,`/`).replace(/^\/+|\/+$/g,``),a=!n,c=e.kind??(e.path.endsWith(`/`)||a?`dir`:`file`),u=e.label??(n?n.split(`/`).pop()??n:`workspace`),d={id:n,kind:c,label:u},f=c===`file`,m=c===`dir`||a,h=c===`list`,g=l.current.state?.cwd??``,_=String(e.path??``).replace(/\\/g,`/`),v=/^[A-Za-z]:$/.test(_)?`${_}/`:_.startsWith(`/`)||/^[A-Za-z]:\//.test(_)||!g?_:`${g.replace(/\\/g,`/`).replace(/\/+$/,``)}/${_}`,y=!h&&v&&(g||v.startsWith(`/`)||/^[A-Za-z]:\//.test(v))?{kind:m?`directory`:`file`,path:v,cwd:g||void 0}:void 0,b=(p.current[`contextmenu.file`]??[]).map(e=>{if(e.source!==`host`)return m&&e.when?.includes(`file.isFile`)||f&&e.when?.includes(`file.isDir`)?{...e,hidden:!0}:e;switch(e.id){case`host:file-quick-ask`:return l.current.settings?.quickAskReferenceMenus!==!1&&y?e:{...e,hidden:!0};case`host:file-compress`:case`host:file-compress-download`:return h?{...e,hidden:!0}:e;case`host:file-extract`:return f&&ww(u)?e:{...e,hidden:!0};case`host:file-upload`:return m||h?{...e,label:s(`uploadToFolder`)}:{...e,hidden:!0};case`host:file-upload-folder`:return m||h?e:{...e,hidden:!0};case`host:file-open`:case`host:file-download`:case`host:file-open-default`:return f?e:{...e,hidden:!0};case`host:file-open-in-editor`:return f&&oT(d.id)&&t.some(e=>e.id===`vscode-editor`)?e:{...e,hidden:!0};case`host:file-attach-ref`:return f?e:{...e,hidden:!0};case`host:file-attach-folder`:return m?e:{...e,hidden:!0};case`host:file-reveal`:return h?{...e,hidden:!0}:e;case`host:file-enter`:case`host:file-open-project`:case`host:file-add-root`:return{...e,hidden:!0};case`host:file-new-file`:case`host:file-new-dir`:case`host:file-paste`:return m||h?e:{...e,hidden:!0};case`host:file-rename`:case`host:file-duplicate`:case`host:file-cut`:case`host:file-copy`:case`host:file-delete`:return!h&&!a?e:{...e,hidden:!0};case`host:file-copy-name`:case`host:file-copy-path`:case`host:file-copy-rel`:return h?{...e,hidden:!0}:e;case`host:file-refresh`:return h?e:{...e,hidden:!0};default:return e}});Hf(b).length!==0&&jf({x:e.x,y:e.y,slot:`contextmenu.file`,target:d,entries:b,onHostAction:(t,n)=>{if(t.id===`host:file-quick-ask`)y&&t2({reference:y});else{if(e.onHostAction){let r=e.onHostAction(t.id,n);if(r!==void 0)return r}switch(t.id){case`host:file-reveal`:r({type:`file_reveal`,path:n.id});break;case`host:file-open-default`:n.kind===`file`&&r({type:`file_open_default`,path:n.id});break;case`host:file-open-in-editor`:n.kind===`file`&&o(n.id);break;case`host:file-copy-name`:navigator.clipboard?.writeText(n.label??n.id),i(`info`,s(`copied`));break;case`host:file-copy-rel`:navigator.clipboard?.writeText(n.id),i(`info`,s(`copied`));break;case`host:file-copy-path`:{let e=l.current.state?.cwd??``,t=e?`${e.replace(/\\/g,`/`).replace(/\/+$/,``)}/${n.id}`:n.id;navigator.clipboard?.writeText(t),i(`info`,s(`copied`));break}}}}})}})),()=>kn(null)),[r,t,o,i,s]),(0,Q.useEffect)(()=>{if(!D)return;let e=e=>{if(e.key!==`Escape`)return;let t=k.current;k.current=null,O(null);try{if(!t)return;t.kind===`confirm`?t.resolve(!1):t.resolve({ok:!1})}catch{}};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[D]),(0,Q.useEffect)(()=>{if(!P)return;let e=setTimeout(()=>{let e=I.current;I.current=null,F(null);try{e?.resolve(null)}catch{}},8e3);return()=>clearTimeout(e)},[P]),{pluginViews:m,failedPluginViews:g,openModalId:v,setOpenModalId:y,openModalEntry:L,openModalPluginId:R,pluginDirPicker:b,setPluginDirPicker:x,pluginModelPicker:S,setPluginModelPicker:C,pluginPathConfirm:w,setPluginPathConfirm:T,pluginPathConfirmRef:E,pluginDialog:D,setPluginDialog:O,pluginDialogRef:k,pluginDialogSel:A,setPluginDialogSel:j,pluginDialogInput:M,setPluginDialogInput:N,pluginNotify:P,setPluginNotify:F,pluginNotifyRef:I,onUiAction:z,renderLeftPluginSectionBody:B,onPluginRunningAction:V}}function tO(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(0),a=t?t[r]??t[0]??null:null,[o,s]=(0,Q.useState)(null),c=(0,Q.useRef)(!1),l=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{c.current=t!==null,l.current=o},[t,o]);let u=(0,Q.useCallback)(t=>{oT(t)&&(window.__piVscodeEditorPendingOpen=t,e(`plugin:vscode-editor`),window.dispatchEvent(new CustomEvent(`pi:open-in-vscode-editor`,{detail:{path:t}})))},[e]),d=(0,Q.useCallback)((e,t)=>{let r=Jy(t);r?(n(null),s({file:{path:e,name:t},plugin:r.plugin,declaration:r.declaration})):(s(null),n([{path:e,name:t}]),i(0))},[]),f=(0,Q.useCallback)((e,t=0)=>{let r=(Array.isArray(e)?e:[]).filter(e=>e&&typeof e.path==`string`&&e.path);if(r.length===0)return;let a=Math.min(Math.max(0,t|0),r.length-1),o=r[a]??r[0],c=r.length===1&&o?Jy(o.name):null;c&&o?(n(null),s({file:{path:o.path,name:o.name},plugin:c.plugin,declaration:c.declaration})):(s(null),n(r.map(e=>({path:e.path,name:e.name}))),i(a))},[]);(0,Q.useEffect)(()=>(Gt({open:e=>d(e.path,e.name),openList:(e,t)=>f(e,t??0),isOpen:()=>c.current||l.current!==null}),()=>Gt(null)),[d,f]),(0,Q.useEffect)(()=>{let e=rn();if(e)return e(({files:e})=>{for(let t of e){let e=t.replace(/\\/g,`/`).split(`/`).pop()||t;d(t,e)}})},[d]);let[p,m]=(0,Q.useState)(null),h=(0,Q.useRef)(!1);return(0,Q.useEffect)(()=>{h.current=p!==null},[p]),(0,Q.useEffect)(()=>(Sn({open:e=>m(e),close:()=>m(null),isOpen:()=>h.current}),()=>Sn(null)),[]),{previewFiles:t,setPreviewFiles:n,previewIndex:r,setPreviewIndex:i,previewFile:a,pluginFile:o,setPluginFile:s,lightboxImage:p,setLightboxImage:m,openFile:d,openFileList:f,openInVscodeEditor:u}}function nO(e){return JSON.stringify([e.ownerKind??`client`,e.ownerKind===`conversation`?e.conversationId??``:``,e.id])}function rO(e,t){let n=t.map(e=>e.key),r=new Set(n),i=[],a=new Set;for(let t of e)typeof t==`string`&&r.has(t)&&!a.has(t)&&(a.add(t),i.push(t));for(let e of n)a.has(e)||(a.add(e),i.push(e));return i}function iO(e,t){let n=new Map(e.map(e=>[e.key,e]));return rO(t,e).map(e=>n.get(e)).filter(e=>e!==void 0)}function aO(e){return[...e.filter(e=>!e.agentBash),...e.filter(e=>e.agentBash)]}function oO(e,t,n,r=!1){let i=[...e],a=i.indexOf(t),o=i.indexOf(n);if(a<0||o<0||a===o)return i;i.splice(a,1);let s=i.indexOf(n)+ +!!r;return i.splice(s,0,t),i}function sO(e,t,n){if(e.length===0)return;let r=t?e.indexOf(t):-1;return r<0?n===`next`?e[0]:e[e.length-1]:e[(r+(n===`next`?1:-1)+e.length)%e.length]}var cO=(0,Q.lazy)(()=>Rs(()=>import(`./TerminalPanel-D2Bpt0f_.js`).then(e=>({default:e.TerminalPanel})),__vite__mapDeps([48,2,3,18,7,38,27,28,12,13,9,8,49,17,31,36]),import.meta.url)),lO=(0,Q.lazy)(()=>Rs(()=>import(`./SCMPanel-CfOxsL8H.js`).then(e=>({default:e.ScmPanel})),__vite__mapDeps([50,2,3,7,9,17,8,18,51]),import.meta.url));function uO({chat:e,terminal:t,send:n,pushNotice:r,cwd:i,sharedReadOnly:a,view:o,setView:s,worktreeOpen:c,setWorktreeOpen:l,isMobile:u,drawer:d,setDrawer:f,termDrawerOpen:p,setTermDrawerOpen:m,gitDrawerOpen:h,termCollapsed:g,setTermCollapsed:_,setBottomTab:v,rightCollapsed:y,setRightCollapsed:b,setRightTab:x,setRightWidth:S,enabledPlugins:C,uiSlots:w,uiTerminalToolbar:T,uiScmToolbar:E,onUiAction:D,setGlobalSearchOpen:O,setSettingsInitialSection:k,setSettingsOpen:A,setBgTasksOpen:j,openSandboxCreateModal:M,openProjectPicker:N,projectPickerOpen:P,nativeCliCreateCwd:F,setNativeCliCreateCwd:I,nativeCliCreating:L,setNativeCliCreating:R,theme:z,themes:B,switchTheme:V,reloadThemes:H,setThemeMarketOpen:ee}){let U=X(),W=(0,Q.useRef)(!1),G=WE(),K=e.terminals.filter(t=>!t.nativeCli&&((t.ownerKind??`client`)===`client`||t.conversationId===(e.activeConversationId||e.state?.conversationId||``))).length,q=(0,Q.useCallback)((n=!1)=>{if(!e.ready||a||!n&&K!==0)return null;let r=or(),i=e.activeConversationId||e.state?.conversationId||``;t.create({id:r,conversationId:i,title:U(`terminalTitle`,{n:K+1}),cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null});let o=nO({id:r,ownerKind:`client`,conversationId:i});return VE({activeTerminal:o}),t.select(r),o},[e.activeConversationId,e.ready,e.state?.conversationId,e.state?.cwd,a,K,U,t]);(0,Q.useEffect)(()=>{W.current&&(o!==`terminal`||K!==0||q())&&(W.current=!1)},[K,q,o]),(0,Q.useEffect)(()=>{let r=r=>{let i=r.detail,o=i?.title||U(`pluginCommandFallback`),c=i?.command;if(!c||!e.ready||a)return;let l={name:o,command:c,cwd:"${pwd}"},u=e.terminals.find(e=>e.title===o),d=e.activeConversationId||e.state?.conversationId||``,f,p;u?(t.restart(u.id),n({type:`run_command`,terminalId:u.id,conversationId:u.conversationId,command:l,cols:80,rows:24}),f=u.id,p=nO(u)):(f=or(),t.create({id:f,conversationId:d,title:o,cwd:e.state?.cwd??``,cols:80,rows:24,running:!0,exitCode:null,command:l}),p=nO({id:f,ownerKind:`client`,conversationId:d})),t.select(f),VE({activeTerminal:p}),m(!0),_(!1),v(o4),s(`terminal`)};window.addEventListener(`pi-web-ui:plugin-run-command`,r),window.addEventListener(`pi-web-ui:run-command`,r);let i=e=>{let t=e.detail;typeof t==`string`&&t&&(s(e=>e===`chat`?e:`chat`),n({type:`switch_conversation`,id:t}),er())};return window.addEventListener(`pi-web-ui:switch-conversation`,i),()=>{window.removeEventListener(`pi-web-ui:plugin-run-command`,r),window.removeEventListener(`pi-web-ui:run-command`,r),window.removeEventListener(`pi-web-ui:switch-conversation`,i)}},[e,t,n,a,m,_,v,s,U]);let te=(0,Q.useCallback)(()=>{a||(m(!0),_(!1),v(o4),s(`terminal`),f(null))},[a,m,_,v,s,f]),ne=(0,Q.useCallback)(()=>{W.current=K===0,q()&&(W.current=!1),te()},[K,q,te]),re=(0,Q.useCallback)(()=>{u&&f(`right`),x(`scm`),b(!1),d4(`right`,!1),S(e=>e<560?560:e),window.dispatchEvent(new CustomEvent(`pi:select-slot-tab`,{detail:{group:`rightpanel`,id:`scm`}})),s(`git`),f(null)},[u,f,x,b,S,s]),J=(0,Q.useCallback)(e=>{e===`terminal`?m(!1):(b(!0),d4(`right`,!0)),s(t=>e===`terminal`&&t===`terminal`?h?`git`:`chat`:e===`git`&&t===`git`?p?`terminal`:`chat`:t)},[p,h,m,b,s]),ie=(0,Q.useCallback)((e,t)=>{if(a&&e!==`chat`&&e!==`devices`)r(`info`,`This conversation is open in read-only mode.`);else if(e===`native-cli`)I(i);else if(e===`worktrees`)l(e=>!e),f(null);else if(e===`terminal`||e===`git`){let n=e===`terminal`?p:h,r=e===`terminal`&&t?.skipAutoCreate;if(n&&!r){J(e),f(null);return}e===`terminal`?(t?.skipAutoCreate?(W.current=!1,m(!0),_(!1),v(o4),s(`terminal`)):ne(),f(null)):(re(),f(u?`right`:null))}else e===`chat`&&(u||G.side===`bottom`)&&m(!1),s(e),f(null)},[a,r,i,ne,re,p,h,J,u,G.side,I,f,m,_,v,s,l]);(0,Q.useEffect)(()=>{let e=e=>{(e.ctrlKey||e.metaKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),O(e=>!e))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[O]);let[ae,oe]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_zen_mode`)===`1`}catch{return!1}});(0,Q.useEffect)(()=>{try{ae?localStorage.setItem(`pi_zen_mode`,`1`):localStorage.removeItem(`pi_zen_mode`)}catch{}},[ae]);let se=(0,Q.useCallback)(()=>{oe(e=>{let t=!e;return t&&o!==`chat`&&s(`chat`),t})},[o,s]);Lt(()=>ae?(oe(!1),!0):!1,ae),Lt(()=>d?(f(null),!0):!1,d!==null),(0,Q.useEffect)(()=>{let r=r=>{let i=r.altKey&&!r.ctrlKey&&!r.metaKey&&r.key.toLowerCase()===`z`,o=(r.ctrlKey||r.metaKey)&&r.shiftKey&&r.key.toLowerCase()===`f`;if(i||o){r.preventDefault(),se();return}let s=GE(r);if(s){let i=r.target;if(i instanceof Element&&i.closest(`input, textarea, [contenteditable='true'], .xterm-helper-textarea`))return;if(r.preventDefault(),s===`toggle`){p?J(`terminal`):ne();return}if(s===`new`){if(a)return;let e=q(!0);W.current=!e,te();return}let o=e.terminals.filter(t=>!t.nativeCli&&((t.ownerKind??`client`)===`client`||t.conversationId===(e.activeConversationId||e.state?.conversationId||``))),c=aO(iO(o.map(e=>({...e,key:nO(e)})),G.terminalTabOrder)).map(e=>e.key);if(s===`previous`||s===`next`){let e=sO(c,G.activeTerminal,s),n=o.find(t=>nO(t)===e);if(!n)return;VE({activeTerminal:e}),t.select(n.id),te();return}let l=G.activeTerminal,u=o.find(e=>nO(e)===l);if(!u||a||u.running&&!window.confirm(U(`termCloseRunningConfirm`,{name:u.title})))return;n({type:`terminal_kill`,terminalId:u.id,conversationId:u.conversationId,ownerKind:u.ownerKind??`client`}),t.close(u.id,u.ownerKind??`client`,u.conversationId);let d=c.filter(e=>e!==l),f=l?c.indexOf(l):0,m=d[Math.min(f,d.length-1)];VE({activeTerminal:m});let h=o.find(e=>nO(e)===m);h&&t.select(h.id)}else(r.ctrlKey||r.metaKey)&&r.shiftKey&&!r.altKey&&r.key.toLowerCase()===`g`&&(r.preventDefault(),h?J(`git`):re())};return window.addEventListener(`keydown`,r),()=>window.removeEventListener(`keydown`,r)},[se,p,h,ne,re,J,q,te,a,e.terminals,e.activeConversationId,e.state?.conversationId,G.activeTerminal,G.terminalTabOrder,t,n,U]);let Y=(0,Q.useCallback)(e=>{a||(I(e??i),f(null))},[i,a,I,f]),ce={"host:bottom-terminal":{label:U(`terminal`),element:(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(cO,{chat:e,terminal:t,uiTerminalToolbar:T,onUiAction:D,collapsed:g,onToggleCollapse:()=>_(e=>!e),onHide:()=>J(`terminal`),dockSide:u?`bottom`:G.side,onDockSideChange:e=>VE({side:e})})})}},le=[];for(let t of w[`bottomdock.tabs`]??[]){if(t.hidden||t.kind===`divider`)continue;if(t.source===`host`){let e=ce[t.id];e&&le.push({id:t.id,label:t.labelExplicit?t.label:e.label,element:e.element});continue}let r=C.find(e=>e.id===t.source.slice(7));r&&le.push({id:t.id,label:t.label||r.name,hint:t.hint||t.label||r.name,element:(0,$.jsx)(Pw,{plugin:r,epoch:e.pluginsEpoch,send:n})})}return{openTerminalDrawer:ne,closeDrawer:J,handleViewChange:ie,zenMode:ae,toggleZenMode:se,openNativeCliCreate:Y,bottomDockTabs:le,scmTab:(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(lO,{chat:e,terminal:t,active:u?d===`right`:!y,onSwitchToTerminal:ne,uiScmToolbar:E,onUiAction:D})}),createNativeCliConversation:async e=>{if(L||F===null)return;R(!0);let t=await Mn(n,e,F);R(!1),t?I(null):r(`error`,U(`nativeCliCreateFailed`))},sidebarBarProps:{chat:e,view:o,worktreesOpen:c,termOpen:p,gitOpen:h,plugins:C,onViewChange:ie,onOpenPanel:f,onOpenSettings:e=>{k(e),A(!0)},onOpenGlobalSearch:()=>O(!0),onOpenBgTasks:()=>j(!0),onOpenSandboxModal:M,onOpenProjectPicker:N,isProjectPickerOpen:P,onCreateCli:Y,onUiAction:D,uiContextEntries:w[`contextmenu.topbar`],zenMode:ae,onToggleZenMode:se,dropdownProps:{theme:z,themes:B,onThemeChange:V,reloadThemes:H,onThemeModalOpen:()=>ee(!0)}}}}function dO(e,t){let n=typeof document<`u`?document.documentElement.lang:`zh`;return Qe((Ye(n)?Ke:xe)[e]??Ke[e],t)}var fO=6e3;function pO(e){return/^https?:\/\//i.test(e)?e:``}function mO(e,t){let n=e.replace(/\s+/g,` `).trim();return n&&n!==t?n:``}function hO(e,t=10){let n=String(e??``).trim();return t<=0||n.length<=t?n:`${n.slice(0,t).replace(/[\s,;:,。;:、·-]+$/,``)}…`}function gO(e,t=fO){let n=String(e??``).replace(/\r\n?/g,`
|
|
417
|
-
`).split(`
|
|
418
|
-
`).map(e=>e.replace(/\s+$/,``));for(;n.length&&!n[0];)n.shift();for(;n.length&&!n[n.length-1];)n.pop();if(!n.length)return``;let r=n.join(`
|
|
419
|
-
`);if(t>0&&r.length>t){r=r.slice(0,t);let e=r.lastIndexOf(`
|
|
420
|
-
`);e>0&&(r=r.slice(0,e)),r+=dO(`browserRefTruncated`)}return r}function _O(e){let t=pO(String(e.url??``).trim());if(!t)return[];let n=hO(mO(String(e.title??``),t)),r=$b({origin:t,...n?{title:n}:{},...e.tabId?{tabId:e.tabId}:{}}),i=gO(e.text??``);if(!i)return[r];let a=Sa({text:i,messageId:`page:${e.tabId||t}`,role:`page`});return a?[r,{path:``,name:n||hO(t),mode:`quote`,quote:a,key:or()}]:[r]}var vO={revision:0},yO=new Set;function bO(e){vO={...e,revision:vO.revision+1};for(let e of yO)e()}var xO=[`quickPhrase.continue`,`quickPhrase.publish`,`quickPhrase.uploadGitHub`,`quickPhrase.handlePr`,`quickPhrase.handleIssue`,`quickPhrase.betterWay`,`quickPhrase.closeIssue`];function SO(e){return xO.map(t=>e(t))}var CO=`pi-web-ui:favicon-settings`,wO=[{id:`violet`,hex:`#8b5cf6`,nameKey:`colorViolet`},{id:`blue`,hex:`#3b82f6`,nameKey:`colorBlue`},{id:`cyan`,hex:`#06b6d4`,nameKey:`colorCyan`},{id:`emerald`,hex:`#10b981`,nameKey:`colorEmerald`},{id:`amber`,hex:`#f59e0b`,nameKey:`colorAmber`},{id:`rose`,hex:`#ef4444`,nameKey:`colorRose`},{id:`pink`,hex:`#ec4899`,nameKey:`colorPink`},{id:`indigo`,hex:`#6366f1`,nameKey:`colorIndigo`},{id:`slate`,hex:`#64748b`,nameKey:`colorSlate`}],TO=`#8b5cf6`,EO={color:`default`,customHex:``,instanceName:``};function DO(e){if(!e)return null;let t=e.trim(),n=/^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(t);if(!n)return null;let r=n[1];return r.length===3?`#${r[0]}${r[0]}${r[1]}${r[1]}${r[2]}${r[2]}`.toLowerCase():`#${r.toLowerCase()}`}function OO(e){if(!e||typeof e!=`object`)return{...EO};let t=e;return{color:typeof t.color==`string`&&t.color.trim()?t.color.trim():EO.color,customHex:typeof t.customHex==`string`?t.customHex.trim():``,instanceName:typeof t.instanceName==`string`?t.instanceName.trim():``}}function kO(e,t=wO){if(!e||t.length===0)return TO;let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t[Math.abs(n)%t.length].hex}function AO(e){let t=e.replace(`#`,``).trim();if(t.length!==3&&t.length!==6)return!1;let n=0,r=0,i=0;return t.length===3?(n=parseInt(t[0]+t[0],16),r=parseInt(t[1]+t[1],16),i=parseInt(t[2]+t[2],16)):(n=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),i=parseInt(t.slice(4,6),16)),Number.isNaN(n)||Number.isNaN(r)||Number.isNaN(i)?!1:.2126*n+.7152*r+.0722*i>180}function jO(e){return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="${e}"/><path d="M18 15h7v14.5L39.5 15h8.5L32.5 31.5 48.5 49H39.8L25 32.5V49h-7V15z" fill="${AO(e)?`#1e1e2e`:`#ffffff`}"/></svg>`}var MO={};function NO(e){MO={...MO,...e},zO();for(let e of HO)e()}async function PO(){if(typeof window<`u`&&typeof fetch<`u`)try{let e=await fetch(j(`/api/health`));if(!e.ok)return;let t=await e.json();t&&(t.instanceName||t.faviconColor)&&NO({instanceName:t.instanceName,faviconColor:t.faviconColor})}catch{}}function FO(e,t=typeof window<`u`?window.location.host:``,n=MO.faviconColor){if(e.color===`custom`&&e.customHex){let t=DO(e.customHex);if(t)return t}if(e.color===`auto`)return kO(t||`localhost`);let r=wO.find(t=>t.id===e.color);if(r)return r.hex;let i=DO(e.color);if(i)return i;if(e.color==="default"&&n){let e=wO.find(e=>e.id===n.toLowerCase());if(e)return e.hex;let t=DO(n);if(t)return t}return TO}function IO(e,t=MO.instanceName){return e.instanceName&&e.instanceName.trim()?e.instanceName.trim():t&&t.trim()?t.trim():``}function LO(e){if(typeof document>`u`)return;let t=document.querySelector(`link[rel~='icon']`);t||(t=document.createElement(`link`),t.rel=`icon`,document.head.appendChild(t)),t.type=`image/svg+xml`;let n=jO(e);t.href=`data:image/svg+xml;utf8,${encodeURIComponent(n)}`}function RO(){try{let e=localStorage.getItem(CO);return e?OO(JSON.parse(e)):{...EO}}catch{return{...EO}}}function zO(){LO(FO(VO??RO(),typeof window<`u`?window.location.host:``))}function BO(e){let t=OO(e);try{localStorage.setItem(CO,JSON.stringify(t))}catch{}VO=t,zO();for(let e of HO)e()}var VO=null,HO=new Set;function UO(e){return HO.add(e),()=>{HO.delete(e)}}function WO(){return VO||=RO(),VO}function GO(){return(0,Q.useSyncExternalStore)(UO,WO)}var KO=`pi-web-ui:wallpaper`,qO=`has-wallpaper`,JO={url:``,dim:78,blur:0},YO=2e3,XO=28e5;function ZO(e){if(typeof e!=`string`)return``;let t=e.trim();if(!t)return``;let n=t.toLowerCase().startsWith(`data:image/`)?XO:YO;return t.length>n?``:/^https?:\/\//i.test(t)||/^blob:/i.test(t)||/^data:image\//i.test(t)||t.startsWith(`/`)&&!t.startsWith(`//`)?t:``}var QO=(e,t,n,r)=>typeof e!=`number`||!Number.isFinite(e)?r:Math.min(n,Math.max(t,Math.round(e)));function $O(e){if(!e||typeof e!=`object`)return{...JO};let t=e;return{url:ZO(t.url),dim:QO(t.dim,0,95,JO.dim),blur:QO(t.blur,0,24,JO.blur)}}function ek(){try{let e=localStorage.getItem(KO);return e?$O(JSON.parse(e)):{...JO}}catch{return{...JO}}}function tk(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\r\n]/g,``)}async function nk(e){let t=await ha(e);return t?`data:${t.mimeType};base64,${t.data}`:null}function rk(){let e=ak??ek(),t=document.documentElement;e.url?(t.style.setProperty(`--bg-image`,`url("${tk(e.url)}")`),t.style.setProperty(`--bg-image-dim`,String(e.dim/100)),t.style.setProperty(`--bg-image-blur`,`${e.blur}px`)):(t.style.removeProperty(`--bg-image`),t.style.removeProperty(`--bg-image-dim`),t.style.removeProperty(`--bg-image-blur`));let n=getComputedStyle(t).getPropertyValue(`--bg-image`).trim();document.body.classList.toggle(qO,e.url!==``||n!==``&&n!==`none`)}function ik(e){let t=$O(e);ak=t;try{localStorage.setItem(KO,JSON.stringify(t))}catch{}for(let e of ok)e();rk()}var ak=null,ok=new Set;function sk(e){return ok.add(e),()=>{ok.delete(e)}}function ck(){return ak||=ek(),ak}function lk(){return(0,Q.useSyncExternalStore)(sk,ck)}function uk(){let e=lk();(0,Q.useEffect)(()=>{rk()},[e]),(0,Q.useEffect)(()=>{let e=()=>rk();return window.addEventListener(yr,e),rk(),()=>window.removeEventListener(yr,e)},[])}function dk(){let e=X(),{locale:t}=_e(),{chat:n,send:r,dismissNotice:i,pushNotice:a,terminal:o}=vy(),s=n.state?.sharedConversation?.readOnly===!0||n.state?.readOnly===!0,c=(0,Q.useRef)(!1);(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail,n=typeof t?.text==`string`?t.text.trim():``;if(!n)return;let r=t?.level===`warning`||t?.level===`error`?t.level:`info`;a(r,n)};return window.addEventListener(`pi-web-ui:toast`,e),()=>window.removeEventListener(`pi-web-ui:toast`,e)},[a]),(0,Q.useEffect)(()=>{n.ready&&n.settings&&(c.current||n.settings.quickPhrasesSeeded||(c.current=!0,n.settings.quickPhrases.length===0&&r({type:`set_settings`,quickPhrases:SO(e),quickPhrasesSeeded:!0})))},[n.ready,n.settings,r,e]);let l=n.state?.cwd??``,u=S6(),d=IO(GO());(0,Q.useEffect)(()=>{PO()},[]),(0,Q.useEffect)(()=>{let t=u?h6(l,n.projects):``,r=t?`${t} — keel`:e(`docTitle`);document.title=d?`[${d}] ${r}`:r},[l,n.projects,u,d,e]);let[f,p]=(0,Q.useState)([]);(0,Q.useEffect)(()=>(Jn(e=>p(t=>P4(t,e))),()=>Jn(null)),[]);let[m,h]=(0,Q.useState)(()=>new URLSearchParams(window.location.search).get(`view`)===`devices`?`devices`:`chat`),{previewFiles:g,setPreviewFiles:_,previewIndex:v,setPreviewIndex:y,previewFile:b,pluginFile:x,setPluginFile:S,lightboxImage:C,setLightboxImage:w,openFile:T,openInVscodeEditor:E}=tO(h);(0,Q.useEffect)(()=>{let e=cn();if(e)return sn(),e(e=>{let t=_O(e);if(!t.length)return;let n=3,r=()=>{ir({attachments:t})||--n>0&&window.setTimeout(r,400)};r()})},[]);let[D,O]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{let e=()=>O(!1);return window.addEventListener(`drop`,e,!0),()=>window.removeEventListener(`drop`,e,!0)},[]);let[k,A]=(0,Q.useState)(null),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(null),[F,I]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>($n(()=>{P(null),h(`chat`)}),()=>$n(null)),[]),(0,Q.useEffect)(()=>{let e=e=>{let t=e.detail;t&&typeof t==`object`&&(t.create===!0?I(!0):(bO({roomId:typeof t.roomId==`string`?t.roomId:void 0,create:t.create===!0,manage:t.manage===!0}),typeof t.roomId==`string`&&!t.manage&&!t.create?(P(t.roomId),h(`chat`)):(P(null),h(`devices`))))};return window.addEventListener(`pi-web-ui:device-group-open`,e),()=>window.removeEventListener(`pi-web-ui:device-group-open`,e)},[]);let L=(e=>!n.tabs||e===`chat`||e===`devices`||e===`worktrees`||n.tabs.includes(e))(m.startsWith(`plugin:`)?`plugins`:m)&&m!==`native-cli`&&(!s||m===`chat`||m===`devices`)?m:`chat`,R=!!n.state?.nativeCli&&!N&&!s,z=L===`chat`||L===`terminal`||L===`git`,[B,V]=(0,Q.useState)({});(0,Q.useEffect)(()=>{if(R&&n.state?.nativeCli&&n.state.conversationId){let e=n.state.conversationId,t=n.state.nativeCli,r=n.state.cwd;V(n=>{let i=n[e];return i&&i.nativeCli===t&&i.cwd===r?n:{...n,[e]:{nativeCli:t,cwd:r}}})}},[R,n.state?.nativeCli,n.state?.conversationId,n.state?.cwd]),(0,Q.useEffect)(()=>{let e=new Set(n.conversations.map(e=>e.id));V(t=>{let n=!1,r={};for(let[i,a]of Object.entries(t))e.has(i)?r[i]=a:n=!0;return n?r:t})},[n.conversations]);let H=(0,Q.useRef)(!1);H.current=L===`chat`&&R;let ee=(0,Q.useCallback)(()=>r({type:`refresh_worktrees`}),[r]);Mr(n.state?.worktree?.mainPath,ee);let[U,W]=(0,Q.useState)(!1),G=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{let e=G.current;e&&n.state?.cwd&&(U?n.state.cwd===e.target||n.state.worktree?.currentPath===e.target?(G.current=null,W(!1),er()):n.state.cwd!==e.source&&(G.current=null):G.current=null)},[n.state?.cwd,n.state?.worktree?.currentPath,U]);let{enabledPlugins:K,uiSlots:q,uiPrimary:te,uiOverflow:ne,uiLeftSessions:re,uiLeftProjectsActions:J,uiLeftProject:ie,uiLeftRunningActions:ae,uiLeftHistoryActions:oe,uiLeftSections:se,uiLeftRunning:Y,uiLeftHistory:ce,uiTerminalToolbar:le,uiScmToolbar:ue,uiGoalbarActions:de,uiChatHeader:fe,uiChatEmpty:pe,uiFilePreviewToolbar:me,presetNames:he,uiNoticeActions:ge,uiSidebarLeft:ve,uiSidebarRight:ye}=FD(n,t),{pluginViews:be,failedPluginViews:xe,setOpenModalId:Se,openModalEntry:Ce,openModalPluginId:we,pluginDirPicker:Te,setPluginDirPicker:Ee,pluginModelPicker:De,setPluginModelPicker:Oe,pluginPathConfirm:ke,setPluginPathConfirm:Ae,pluginPathConfirmRef:je,pluginDialog:Me,setPluginDialog:Ne,pluginDialogRef:Pe,pluginDialogSel:Fe,setPluginDialogSel:Ie,pluginDialogInput:Le,setPluginDialogInput:Re,pluginNotify:ze,setPluginNotify:Be,pluginNotifyRef:Ve,onUiAction:He,renderLeftPluginSectionBody:Ue,onPluginRunningAction:We}=eO({chat:n,enabledPlugins:K,uiSlots:q,send:r,pushNotice:a,setView:h,openInVscodeEditor:E}),{termDrawerOpen:Ge,setTermDrawerOpen:Ke,termCollapsed:qe,setTermCollapsed:Je,bottomTab:Ye,setBottomTab:Xe,setRightTab:Ze,leftWidth:Qe,rightWidth:$e,setRightWidth:et,resizeLeft:tt,resizeRight:nt,leftCollapsed:rt,rightCollapsed:it,setRightCollapsed:at,gitDrawerOpen:ot,toggleLeft:st,toggleRight:ct,drawer:lt,setDrawer:ut,layoutRef:dt,isMobile:ft}=$D(L,h),pt=Y5(),[mt,ht]=(0,Q.useState)(()=>{try{return localStorage.getItem(`pi_web_setup_dismissed`)===`1`}catch{return!1}}),gt=()=>{ht(!0);try{localStorage.setItem(`pi_web_setup_dismissed`,`1`)}catch{}},[_t,vt]=(0,Q.useState)(!1),[yt,bt]=(0,Q.useState)(!1),[xt,St]=(0,Q.useState)(),[Ct,wt]=(0,Q.useState)(null),Tt=(0,Q.useCallback)(()=>wt(`create`),[]),[Et,Dt]=(0,Q.useState)(!1),Ot=(0,Q.useCallback)(()=>Dt(!0),[]),kt=n.transition?.kind,At=n.transition?.target,jt=n.transition?.progress,Mt=(0,Q.useMemo)(()=>kt&&At!==void 0?{kind:kt,target:At,progress:jt??0}:null,[kt,At,jt]),[Nt,Pt]=(0,Q.useState)(()=>new Set),Ft=(e,t)=>{r({type:`plugin_path_response`,id:e,ok:t}),Pt(t=>new Set(t).add(e))},It=n.pathRequests.find(e=>!Nt.has(e.id))??null,[Lt,zt]=(0,Q.useState)(()=>new Set),Bt=(e,t,n=!1)=>{r({type:`plugin_permission_response`,id:e,ok:t,...n?{remember:!0}:{}}),zt(t=>new Set(t).add(e))},Vt=n.permRequests.find(e=>!Lt.has(e.id))??null,Ht=Rt(!!(Vt||It||ke)),Ut=s9(),Wt=_9(),Gt=!!n.reaskConversationId&&n.reaskConversationId===n.state?.conversationId,Kt=!R&&!!n.settings?.minimalNewChat&&(n.state?.messages?.length??0)===0&&!n.state?.streamingMessage&&!n.state?.isStreaming&&!Gt,[qt,Jt]=(0,Q.useState)(!1),[Yt,Xt]=(0,Q.useState)(!1),[Zt,Qt]=(0,Q.useState)(!1),[$t,en]=(0,Q.useState)(null);(0,Q.useEffect)(()=>{if(!$t)return;let e=setTimeout(()=>en(null),15e3);return()=>clearTimeout(e)},[$t]);let tn=n.state?.sessionId??``,{urlJump:nn,setUrlJump:rn}=zD({ready:n.ready,activeSessionId:tn,notices:n.notices,send:r,pushNotice:a,setView:h,setActiveGroupId:P}),[an,on]=(0,Q.useState)(u1),[ln,un]=(0,Q.useState)(P_),{themes:dn,theme:fn,switchTheme:pn,reloadThemes:mn}=gr(),[hn,gn]=(0,Q.useState)(!1);uk(),(0,Q.useEffect)(()=>{try{typeof Pn==`function`&&Pn(fn??``)}catch{}},[fn]),(0,Q.useEffect)(()=>{try{typeof Ln==`function`&&Ln(t)}catch{}},[t]),(0,Q.useEffect)(()=>{try{typeof On==`function`&&On(L)}catch{}},[L]),(0,Q.useEffect)(()=>{try{let e=n.state?.model,t=e?`${e.provider}/${e.id}`:null;typeof Bn==`function`&&Bn(t)}catch{}},[n.state?.model?.provider,n.state?.model?.id]),iD({chat:n,activeSessionId:tn,sound:an,tts:ln,send:r,pushNotice:a});let _n=(0,Q.useCallback)(e=>(!e.type.startsWith(`list_`)&&!e.type.startsWith(`get_`)&&ut(null),r(e)),[r]),vn=(0,Q.useRef)(new Set),yn=n.activeConversationId||n.state?.conversationId||``;(0,Q.useEffect)(()=>{let t=n.conversations.filter(e=>e.hasQuestion),r=new Set(t.map(e=>e.id)),i=new Set(t.map(e=>e.questionId).filter(Boolean));for(let e of vn.current)i.has(e)||vn.current.delete(e);for(let n of t){let t=`question-${n.id}`;n.id===yn?Si(t,{silent:!0}):n.questionId&&vn.current.has(n.questionId)||xi({id:t,type:`question`,title:n.title||e(`chat`),message:n.questionTitle||e(`waitingQuestionBadge`),persistent:!0,dismissible:!0,data:{conversationId:n.id,questionId:n.questionId},onClose:()=>{n.questionId&&vn.current.add(n.questionId)},onClick:()=>{_n({type:`switch_conversation`,id:n.id}),Si(t,{silent:!0})}})}Ci(e=>{let t=e.data?.conversationId;return t?!r.has(t)||t===yn:!1},{silent:!0})},[n.conversations,yn,_n,e]);let Z=(0,Q.useCallback)(()=>vt(!0),[]),{attach:bn,attachmentProgress:xn,addImageFiles:Sn,addLocalFiles:Cn,addNativeCliFiles:wn,onEditMessage:Tn,onRemoveQueued:En,recallDrafts:Dn,onRecallQueued:kn,userPromptNonce:An,handleSent:jn,handleAbort:Mn,removeAttachmentCb:Nn,annotateImageCb:Fn,addImageFilesCb:In,addLocalFilesCb:Rn,searchFilesCb:zn,addPathAttachmentCb:Vn}=RD({chat:n,send:r,pushNotice:a,setAttachments:p,nativeCliViewRef:H}),Hn=n.state?.model,Un=n.state?.thinkingLevel,Wn=n.state?.availableThinkingLevels,Gn=(0,Q.useMemo)(()=>Hn?{model:Hn,thinkingLevel:Un??`off`,availableThinkingLevels:Wn??[]}:null,[Hn,Un,Wn]),{openTerminalDrawer:Kn,closeDrawer:qn,handleViewChange:Yn,zenMode:Xn,toggleZenMode:Zn,openNativeCliCreate:Qn,bottomDockTabs:tr,scmTab:nr,createNativeCliConversation:rr,sidebarBarProps:ar}=uO({chat:n,terminal:o,send:r,pushNotice:a,cwd:l,sharedReadOnly:s,view:L,setView:h,worktreeOpen:U,setWorktreeOpen:W,isMobile:ft,drawer:lt,setDrawer:ut,termDrawerOpen:Ge,setTermDrawerOpen:Ke,gitDrawerOpen:ot,termCollapsed:qe,setTermCollapsed:Je,setBottomTab:Xe,rightCollapsed:it,setRightCollapsed:at,setRightTab:Ze,setRightWidth:et,enabledPlugins:K,uiSlots:q,uiTerminalToolbar:le,uiScmToolbar:ue,onUiAction:He,setGlobalSearchOpen:Xt,setSettingsInitialSection:St,setSettingsOpen:bt,setBgTasksOpen:Jt,openSandboxCreateModal:Tt,openProjectPicker:Ot,projectPickerOpen:Et,nativeCliCreateCwd:k,setNativeCliCreateCwd:A,nativeCliCreating:j,setNativeCliCreating:M,theme:fn,themes:dn,switchTheme:pn,reloadThemes:mn,setThemeMarketOpen:gn});return(0,$.jsx)(nD,{chat:n,terminal:o,send:r,pushNotice:a,dismissNotice:i,panelSend:_n,locale:t,view:L,setView:h,worktreeOpen:U,setWorktreeOpen:W,handleViewChange:Yn,zenMode:Xn,toggleZenMode:Zn,appDragOver:D,setAppDragOver:O,nativeCliViewRef:H,addNativeCliFiles:wn,addImageFiles:Sn,addLocalFiles:Cn,termDrawerOpen:Ge,gitDrawerOpen:ot,termCollapsed:qe,setTermCollapsed:Je,enabledPlugins:K,uiSlots:q,uiPrimary:te,uiOverflow:ne,uiNoticeActions:ge,uiSidebarLeft:ve,uiSidebarRight:ye,uiLeftSessions:re,uiLeftProjectsActions:J,uiLeftProject:ie,uiLeftRunningActions:ae,uiLeftHistoryActions:oe,uiLeftSections:se,uiLeftRunning:Y,uiLeftHistory:ce,uiChatHeader:fe,uiChatEmpty:pe,uiGoalbarActions:de,sidebarBarProps:ar,onUiAction:He,renderLeftPluginSectionBody:Ue,onPluginRunningAction:We,openNativeCliCreate:Qn,nativeCliCreateCwd:k,nativeCliCreating:j,setNativeCliCreateCwd:A,createNativeCliConversation:rr,drawer:lt,setDrawer:ut,closeDrawer:qn,setSettingsInitialSection:St,setSettingsOpen:bt,setBgTasksOpen:Jt,setGlobalSearchOpen:Xt,iconEditOpen:Zt,setIconEditOpen:Qt,setSandboxModalMode:wt,openSandboxCreateModal:Tt,openProjectPicker:Ot,projectPickerOpen:Et,setProjectPickerOpen:Dt,themes:dn,theme:fn,switchTheme:pn,reloadThemes:mn,setThemeMarketOpen:gn,pluginNotify:ze,pluginNotifyRef:Ve,setPluginNotify:Be,pluginDialog:Me,pluginDialogRef:Pe,setPluginDialog:Ne,pluginDialogSel:Fe,setPluginDialogSel:Ie,pluginDialogInput:Le,setPluginDialogInput:Re,model:Hn,layoutRef:dt,leftWidth:Qe,rightWidth:$e,isMobile:ft,leftCollapsed:rt,rightCollapsed:it,toggleLeft:st,toggleRight:ct,resizeLeft:tt,resizeRight:nt,wide:Ut,hideModelRow:Wt,isMinimalEmpty:Kt,unreadConvKeys:pt,activeGroupId:N,setActiveGroupId:P,presetNames:he,leftPanelTransition:Mt,cachedNativeClis:B,isNativeCliConversation:R,chatPaneVisible:z,sharedReadOnly:s,activeConvId:yn,onEditMessage:Tn,onRemoveQueued:En,onRecallQueued:kn,searchJump:$t,setSearchJump:en,urlJump:nn,setUrlJump:rn,userPromptNonce:An,attachmentProgress:xn,handleAbort:Mn,modelState:Gn,attachments:f,removeAttachmentCb:Nn,annotateImageCb:Fn,addImageFilesCb:In,addLocalFilesCb:Rn,addPathAttachmentCb:Vn,searchFilesCb:zn,openManageModels:Z,handleSent:jn,recallDrafts:Dn,attach:bn,openFile:T,openInVscodeEditor:E,scmTab:nr,setRightTab:Ze,refreshWorktrees:ee,pendingWorktreeSwitch:G,pluginViews:be,failedPluginViews:xe,bottomDockTabs:tr,bottomTab:Ye,setBottomTab:Xe,children:(0,$.jsx)(k4,{chat:n,send:r,terminal:o,sharedReadOnly:s,isNativeCliConversation:R,setupDismissed:mt,dismissSetup:gt,manageModelsOpen:_t,setManageModelsOpen:vt,settingsOpen:yt,setSettingsOpen:bt,settingsInitialSection:xt,setSettingsInitialSection:St,onOpenIconEdit:()=>Qt(!0),onOpenManageModels:()=>{bt(!1),vt(!0)},openTerminalDrawer:Kn,themeMarketOpen:hn,setThemeMarketOpen:gn,bgTasksOpen:qt,setBgTasksOpen:Jt,globalSearchOpen:Yt,setGlobalSearchOpen:Xt,setSearchJump:en,deviceGroupCreateOpen:F,setDeviceGroupCreateOpen:I,sandboxModalMode:Ct,setSandboxModalMode:wt,previewFile:b,previewFiles:g,previewIndex:v,setPreviewIndex:y,setPreviewFiles:_,pluginFile:x,setPluginFile:S,lightboxImage:C,setLightboxImage:w,openFile:T,attach:bn,uiSlots:q,uiFilePreviewToolbar:me,onUiAction:He,openModalEntry:Ce,openModalPluginId:we,pluginViews:be,setOpenModalId:Se,pluginDirPicker:Te,setPluginDirPicker:Ee,pluginModelPicker:De,setPluginModelPicker:Oe,pendingPermRequest:Vt,answerPermRequest:Bt,pendingPathRequest:It,answerPathRequest:Ft,pluginPathConfirm:ke,pluginPathConfirmRef:je,setPluginPathConfirm:Ae,permOverlayZIndex:Ht,setRightCollapsed:at,setDrawer:ut,sound:an,setSound:on,tts:ln,setTts:un,themes:dn,theme:fn,switchTheme:pn,reloadThemes:mn})})}function fk(){typeof document<`u`&&(pk(mk()),gk())}function pk(e){!Number.isFinite(e)||e<0||document.documentElement.style.setProperty(`--msgs-gutter`,`${Math.round(e*100)/100}px`)}function mk(){let e=document.createElement(`div`);e.style.cssText=`position:fixed;top:-9999px;left:0;width:100px;height:100px;overflow-y:auto;scrollbar-gutter:stable both-edges;visibility:hidden;pointer-events:none;`,document.body.appendChild(e);let t=(e.offsetWidth-e.clientWidth)/2;return e.remove(),t}function hk(e){let t=document.createElement(`div`);t.style.cssText=`width:0;height:0;pointer-events:none;`,e.appendChild(t);let n=getComputedStyle(e),r=e.getBoundingClientRect(),i=t.getBoundingClientRect(),a=Number.parseFloat(n.borderLeftWidth)||0,o=Number.parseFloat(n.paddingLeft)||0,s=i.left-(r.left+a+o);return t.remove(),s}function gk(){let e=()=>{let e=document.querySelector(`.messages`);return e?(pk(hk(e)),!0):!1},t=0;if(window.addEventListener(`resize`,()=>{t||=window.requestAnimationFrame(()=>{t=0,e()})}),e())return;let n=new MutationObserver(()=>{e()&&n.disconnect()});n.observe(document.documentElement,{childList:!0,subtree:!0}),window.setTimeout(()=>n.disconnect(),6e4)}function _k(e){let t=typeof e==`object`&&e&&`message`in e?String(e.message):String(e);return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|Unable to preload CSS for|Loading (?:CSS )?chunk .+ failed/i.test(t)}function vk(e,t){let n=!1;return r=>{if(!_k(r))return!1;if(n)return!0;try{let n=`pi-web:chunk-recovery`,r=t.storage.getItem(n),i=r?JSON.parse(r):null,a=t.now();if(i&&(i.buildId===e||a-i.time<6e4))return!1;t.storage.setItem(n,JSON.stringify({buildId:e,time:a}))}catch{return!1}return n=!0,t.reload(),!0}}function yk(e){let t=vk(e,{storage:{getItem:e=>window.sessionStorage.getItem(e),setItem:(e,t)=>window.sessionStorage.setItem(e,t)},reload:()=>window.location.reload(),now:Date.now});return window.addEventListener(`vite:preloadError`,e=>{t(e.payload)&&e.preventDefault()}),t}var bk=J()?()=>!1:yk(`20261202T08014`),xk=class extends Q.Component{state={error:null};static getDerivedStateFromError(e){return{error:e}}componentDidCatch(e,t){bk(e)||console.error(`RootErrorBoundary caught error:`,e,t)}render(){return this.state.error?(0,$.jsxs)(`div`,{style:{minHeight:`100vh`,display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`,padding:`24px`,background:`var(--bg, rgb(13, 14, 18))`,color:`var(--text, #e2e8f0)`,fontFamily:`system-ui, -apple-system, sans-serif`,textAlign:`center`},children:[(0,$.jsx)(`h2`,{style:{fontSize:`18px`,marginBottom:`12px`,color:`var(--red, #f43f5e)`},children:`页面加载出现异常 / App Failed to Render`}),(0,$.jsx)(`pre`,{style:{maxWidth:`600px`,overflow:`auto`,padding:`12px 16px`,background:`rgba(0, 0, 0, 0.4)`,borderRadius:`8px`,fontSize:`12px`,lineHeight:`1.5`,marginBottom:`20px`,whiteSpace:`pre-wrap`,wordBreak:`break-word`,color:`#94a3b8`},children:this.state.error.message||String(this.state.error)}),(0,$.jsx)(`button`,{type:`button`,style:{padding:`8px 20px`,background:`var(--accent, #38bdf8)`,color:`#0f172a`,border:`none`,borderRadius:`6px`,fontWeight:600,cursor:`pointer`,fontSize:`13px`},onClick:()=>window.location.reload(),children:`刷新重试 / Reload`})]}):this.props.children}};if(O(),J()){let e=()=>{D1().catch(e=>console.warn(`Push event settings failed:`,e))};e(),window.addEventListener(`pi-web-ui:sound-settings`,e)}function Sk(){_r(vr()),(0,Tr.createRoot)(document.getElementById(`root`)).render((0,$.jsx)(Q.StrictMode,{children:(0,$.jsx)(xk,{children:(0,$.jsx)(pt,{children:(0,$.jsx)(dk,{})})})}))}zO(),nn(),fk(),wr?Cr(window).then(Sk):Sk(),!J()&&!wr&&`serviceWorker`in navigator&&window.addEventListener(`load`,()=>{let e=We();navigator.serviceWorker.register(`${e}sw.js`,{scope:e}).catch(e=>{console.warn(`Service worker registration failed:`,e)})});export{_6 as $,Hf as $t,z5 as A,j1 as At,ix as B,bg as Bt,f9 as C,hs as Cn,G0 as Ct,s9 as D,B1 as Dt,D9 as E,jr as En,x1 as Et,Ix as F,t1 as Ft,nb as G,dg as Gt,d8 as H,Jg as Ht,Px as I,I_ as It,A6 as J,lm as Jt,Y6 as K,ug as Kt,Ox as L,Y_ as Lt,o5 as M,O1 as Mt,Bx as N,E1 as Nt,E7 as O,T1 as Ot,Vx as P,v1 as Pt,T6 as Q,Mf as Qt,Dx as R,T_ as Rt,n9 as S,Rs as Sn,z0 as St,_9 as T,Sa as Tn,Y1 as Tt,r8 as U,qg as Ut,sx as V,Ug as Vt,tb as W,jg as Wt,D6 as X,pp as Xt,E6 as Y,wp as Yt,O6 as Z,Lf as Zt,KE as _,Bu as _n,nv as _t,TO as a,fd as an,U3 as at,Pw as b,Uc as bn,K0 as bt,BO as c,_d as cn,t2 as ct,aO as d,Wu as dn,Vy as dt,Pf as en,S6 as et,oO as f,$u as fn,Ry as ft,VE as g,Vu as gn,iv as gt,nO as h,Xu as hn,pv as ht,lk as i,Jd as in,q3 as it,c5 as j,k1 as jt,D7 as k,H1 as kt,GO as l,cd as ln,Zy as lt,iO as m,ed as mn,Dy as mt,ZO as n,Cf as nn,l6 as nt,wO as o,pd as on,W3 as ot,rO as p,qu as pn,Ey as pt,X6 as q,rm as qt,ik as r,Zd as rn,X3 as rt,DO as s,gd as sn,R3 as st,nk as t,jf as tn,r6 as tt,SO as u,Hu as un,Hy as ut,WE as v,Fl as vn,ov as vt,S9 as w,Po as wn,N0 as wt,xC as x,dc as xn,B0 as xt,Gw as y,nl as yn,R0 as yt,yx as z,xg as zt};
|