pisper 0.6.44 → 0.6.45
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/package.json +6 -6
- package/web/.vite/manifest.json +691 -691
- package/web/assets/{AppDialog-BmhtqPq6.js → AppDialog-DNRcFofn.js} +1 -1
- package/web/assets/{AppOverlays-cyz0mMc9.js → AppOverlays-D1G4bRJ_.js} +1 -1
- package/web/assets/{AssetsPage-a_DNQXQF.js → AssetsPage-BxfXloqY.js} +1 -1
- package/web/assets/{AttachmentTray-Fx0RVdj2.js → AttachmentTray-ChMs2_F_.js} +1 -1
- package/web/assets/{BoardPage-CQF_701M.js → BoardPage-BWPe3aOh.js} +3 -3
- package/web/assets/{ChannelsPage-C4sSuXef.js → ChannelsPage-DIqDgADZ.js} +1 -1
- package/web/assets/{ChatAppearancePage-BA77E4RG.js → ChatAppearancePage-RMfIitpr.js} +1 -1
- package/web/assets/{ChatHistoryPage-Bo932avi.js → ChatHistoryPage-Dv2EeHAV.js} +1 -1
- package/web/assets/{ChatMessage-DyRMVDmJ.js → ChatMessage-CzJ7vm4B.js} +5 -5
- package/web/assets/{ChatPage-Bh2srQ5Q.js → ChatPage-Bz2V_NZ9.js} +5 -5
- package/web/assets/{ConfigPage-CRMPpPxz.js → ConfigPage-DXTFhwnY.js} +2 -2
- package/web/assets/{DesktopWindowControls-QTt7BkHB.js → DesktopWindowControls-iivqpiQx.js} +1 -1
- package/web/assets/{FeaturePage-DEjUrI25.js → FeaturePage-BOq1shgs.js} +1 -1
- package/web/assets/{FileAttachmentPreview-CU3DVCec.js → FileAttachmentPreview-DV6eqgRK.js} +1 -1
- package/web/assets/{FloatingWidgets-DsEUT3hG.js → FloatingWidgets-VZ-Qb-wN.js} +1 -1
- package/web/assets/FocusRuntimeControls-C8oD9nnP.js +2 -0
- package/web/assets/{GitDiffViewer-BFdi1mxr.js → GitDiffViewer-CAklMpA4.js} +1 -1
- package/web/assets/{ManageProjectsDialog-BpsBTKv5.js → ManageProjectsDialog-Cfv6AU2u.js} +1 -1
- package/web/assets/{MarkdownMessage-B9Bb9VQU.js → MarkdownMessage-C47P3anj.js} +1 -1
- package/web/assets/{McpPage-D1onf9RA.js → McpPage-CnBIWy5m.js} +1 -1
- package/web/assets/{MemoryEvolution-D4d8ELda.js → MemoryEvolution-BdhNE7KR.js} +1 -1
- package/web/assets/{MemoryPage-BxeQ1cdR.js → MemoryPage-Cs9Gw3yR.js} +2 -2
- package/web/assets/{MobileNavigation-DQcTpoYc.js → MobileNavigation-C-CAVhMP.js} +1 -1
- package/web/assets/{MorePage-DqfRiueD.js → MorePage-CLEkoAvi.js} +1 -1
- package/web/assets/{NewFolderDialog-dNstknkT.js → NewFolderDialog-GIqRGkVE.js} +1 -1
- package/web/assets/{PageHeader-Bn_vZ-th.js → PageHeader-DRXzRG34.js} +1 -1
- package/web/assets/{PhoneDrawer-BnWXS2P1.js → PhoneDrawer-WHEiWgs5.js} +1 -1
- package/web/assets/{PhoneMenuButton-Coocnsrf.js → PhoneMenuButton-BQSaB_4t.js} +1 -1
- package/web/assets/{PhoneTopBar-DUJ9aeM3.js → PhoneTopBar-BCRq9xao.js} +1 -1
- package/web/assets/{PluginsPage-Z7Fx-eAU.js → PluginsPage-xVXkgNsr.js} +1 -1
- package/web/assets/{SafeModePrompt-DaxOzv7_.js → SafeModePrompt-CV0e__Tp.js} +1 -1
- package/web/assets/{SchedulesPage-ZGP3g3Vt.js → SchedulesPage-Bsl7a3lS.js} +1 -1
- package/web/assets/{SessionBrowserPane-DeOqkbLQ.js → SessionBrowserPane-feS4xeee.js} +2 -2
- package/web/assets/{SessionContextPanel-Co419auw.js → SessionContextPanel-aH8brkyg.js} +2 -2
- package/web/assets/{SessionHome-3GRisRUv.js → SessionHome-DLPkN0jf.js} +1 -1
- package/web/assets/{SessionInspector-KjdRXk-P.js → SessionInspector-2ar9Ti-b.js} +1 -1
- package/web/assets/{SessionShell-DrMljmEy.js → SessionShell-FCFBi5iD.js} +1 -1
- package/web/assets/{SettingsSidebar-Bfgryx3X.js → SettingsSidebar-JH87Nmo2.js} +1 -1
- package/web/assets/{ShortcutHelpDialog-BEv4kDZo.js → ShortcutHelpDialog-BQlkmhTE.js} +1 -1
- package/web/assets/{ShortcutKeys-CFnZogMX.js → ShortcutKeys-CJB8XFeA.js} +1 -1
- package/web/assets/{SidebarUpdateStatus-BaQLz9Ha.js → SidebarUpdateStatus-DsInXdr3.js} +1 -1
- package/web/assets/{SkillsPage-DiBdvo55.js → SkillsPage-wekYWAdT.js} +1 -1
- package/web/assets/{TaskProcessesPane-CgzN0Oqf.js → TaskProcessesPane-nhAVkTPK.js} +1 -1
- package/web/assets/{TaskTerminalView-E0ZkafSN.js → TaskTerminalView-QMAxGYqP.js} +1 -1
- package/web/assets/{TerminalPanel-KwRTV-hb.js → TerminalPanel-CtwjsJfa.js} +1 -1
- package/web/assets/{WebDesktopPet-CGpI6-UL.js → WebDesktopPet-CA-YJQxv.js} +1 -1
- package/web/assets/{WorkflowsPage-BCfAr_BN.js → WorkflowsPage-Cd86btwf.js} +1 -1
- package/web/assets/{WorkspacePicker-DyL_8DP0.js → WorkspacePicker-BMvjJqVo.js} +1 -1
- package/web/assets/{api-D1flkoh7.js → api-DvJkDxm2.js} +1 -1
- package/web/assets/{app-update-DWy3AK8N.js → app-update-A3wZafCD.js} +1 -1
- package/web/assets/{approval-confirm-CDGLUuxy.js → approval-confirm-CryF68cs.js} +1 -1
- package/web/assets/{assets-api-BGMZsyC4.js → assets-api-CPakJhYf.js} +1 -1
- package/web/assets/{board-projects-DjGBcX8k.js → board-projects-jIIRo-OH.js} +1 -1
- package/web/assets/{bots-store-Ck_jncK7.js → bots-store-Dc07jUzl.js} +1 -1
- package/web/assets/{chat-api-BqA8nXly.js → chat-api-DrjHZunL.js} +1 -1
- package/web/assets/{client-store-e4OXhDNK.js → client-store-vgpSLnwK.js} +1 -1
- package/web/assets/command-Cf3AX_Nt.js +1 -0
- package/web/assets/{config-search-a0xjM1yz.js → config-search-DLwaZPQ0.js} +1 -1
- package/web/assets/{desktop-hosts-DsTa6yr4.js → desktop-hosts-0e3KPpOY.js} +1 -1
- package/web/assets/{dialog-DldLiTwf.js → dialog-Cfk77z7g.js} +1 -1
- package/web/assets/{event-stream-DRv0u06j.js → event-stream-Viv-Ob7U.js} +1 -1
- package/web/assets/{events-C8OUQmIW.js → events-Wogs03GD.js} +1 -1
- package/web/assets/{folder-paths-CfRbR0Ik.js → folder-paths-JS7ynXVP.js} +1 -1
- package/web/assets/{hosts-DbXwJrWt.js → hosts-BOC6FyGx.js} +1 -1
- package/web/assets/{http-response-DEs9jkgT.js → http-response-CSCIVa2S.js} +1 -1
- package/web/assets/{http-B-XVZUum.js → http-zidLhKOq.js} +1 -1
- package/web/assets/i18n-DojWxWRu.js +1 -0
- package/web/assets/{index-j6s460ui.css → index-CrtNFCj_.css} +1 -1
- package/web/assets/{index-CiyAfWLi.js → index-DfZr_SBB.js} +2 -2
- package/web/assets/{machine-messages-CKHf8pyL.js → machine-messages-BJSM1X90.js} +1 -1
- package/web/assets/{machines-api-BeimiMiu.js → machines-api-C_Mtpsx-.js} +1 -1
- package/web/assets/{memory-api-Cu3MEsQE.js → memory-api-Bgy-5-wQ.js} +1 -1
- package/web/assets/{mount-app-ISo-f47e.js → mount-app-G6kgCLuV.js} +2 -2
- package/web/assets/{permission-rules-api-bHINce43.js → permission-rules-api-B_E6IQKz.js} +1 -1
- package/web/assets/{pick-system-directory-D1GGkOTf.js → pick-system-directory-LTM6ma78.js} +1 -1
- package/web/assets/{placements-9_rV4h0k.js → placements-C9ibKMbf.js} +2 -2
- package/web/assets/{popover-DGWRnOht.js → popover-CJZagMlP.js} +1 -1
- package/web/assets/{public-B7wKOz_X.js → public-BoVk_M9e.js} +2 -2
- package/web/assets/{public-lAWjPSYc.js → public-DAyGFlph.js} +1 -1
- package/web/assets/{public-DRF_OfnY.js → public-EyctVdZl.js} +1 -1
- package/web/assets/{public-Dr8_scp5.js → public-RXIeJTl_.js} +2 -2
- package/web/assets/{public-components-by-7di2-.js → public-components-DUyD_N-P.js} +1 -1
- package/web/assets/public-diff-BHHFwd2h.js +1 -0
- package/web/assets/public-events-CF9LX0aU.js +1 -0
- package/web/assets/{public-flags-DHN44K2T.js → public-flags-DRJJOuZP.js} +1 -1
- package/web/assets/{public-folder-dialog-Gkbm4LRI.js → public-folder-dialog-BCVCXKem.js} +1 -1
- package/web/assets/{public-greeting-Bdpk4piS.js → public-greeting-BWAXeejh.js} +1 -1
- package/web/assets/{public-session-CtusCiv8.js → public-session-DS7Ggm0I.js} +1 -1
- package/web/assets/{public-sidebar-DmWVSBL3.js → public-sidebar-BscZFI63.js} +1 -1
- package/web/assets/{runtime-capabilities-store-MtXRlSIi.js → runtime-capabilities-store-Pf6H3F8g.js} +1 -1
- package/web/assets/{safe-mode-instance-CpOBP8Nz.js → safe-mode-instance-DW1In7Kt.js} +1 -1
- package/web/assets/safe-mode-sentinel-Dj3En0LX.js +1 -0
- package/web/assets/{session-change-summary-api-CAkw4_-l.js → session-change-summary-api-ytql-8Mb.js} +1 -1
- package/web/assets/{session-home-CJcIlNWK.js → session-home-CYMA_6K8.js} +1 -1
- package/web/assets/{session-inspector-store-C3BluNoW.js → session-inspector-store-C8XTJKcv.js} +1 -1
- package/web/assets/{session-questions-BPKyVhzp.js → session-questions-DODg4dBd.js} +1 -1
- package/web/assets/{session-scope-ddZfvpZE.js → session-scope-UGYN3ar9.js} +1 -1
- package/web/assets/{session-tree-actions-_YCQsWye.js → session-tree-actions-EtL6Nf5T.js} +1 -1
- package/web/assets/{session-tree-summary-BLsTrwUq.js → session-tree-summary-JM5v4ugd.js} +1 -1
- package/web/assets/{session-web-preview-DZOVkeBU.js → session-web-preview-BsCgxxv4.js} +1 -1
- package/web/assets/{shortcuts-C6ddcUau.js → shortcuts-DDY3WKNk.js} +1 -1
- package/web/assets/{side-chat-context-C7vwSBGo.js → side-chat-context-C2I0EzIE.js} +4 -4
- package/web/assets/{sidebar-B7HP3-3A.js → sidebar-BTaR7jH_.js} +1 -1
- package/web/assets/{sidebar-store-Bv_D4lVD.js → sidebar-store-Bmpse81N.js} +1 -1
- package/web/assets/{speech-session-DI3T3jpW.js → speech-session-DOQkdJHS.js} +1 -1
- package/web/assets/{startup-queries-B2k6wlnS.js → startup-queries-D3JCr4DY.js} +1 -1
- package/web/assets/{use-i18n-CsOCclo6.js → use-i18n-D7gqe3X9.js} +1 -1
- package/web/assets/{use-open-bot-BPSaOfrG.js → use-open-bot-CKhA9NsG.js} +1 -1
- package/web/assets/{use-studio-actions-Cvz4jiDa.js → use-studio-actions-CvFfWXni.js} +1 -1
- package/web/assets/{useCatalogProjects-D3mDdYej.js → useCatalogProjects-D4S7sSAX.js} +1 -1
- package/web/assets/{useMachines-BwvKcPVd.js → useMachines-CGhATQIK.js} +1 -1
- package/web/assets/{useNewProjectPicker-DfE1or_O.js → useNewProjectPicker-BhuGTAp2.js} +2 -2
- package/web/assets/{useNow-CuwOIh4H.js → useNow-BHuHuBZk.js} +1 -1
- package/web/assets/{usePhoneShell-e-CScTJH.js → usePhoneShell-O2Livo2-.js} +1 -1
- package/web/assets/{useSessionRowActions-DUufel_k.js → useSessionRowActions-a38hlfs2.js} +1 -1
- package/web/assets/{useSidebarModel-CShQi_Fw.js → useSidebarModel-CQwUXEO7.js} +1 -1
- package/web/assets/{workspace-folders-Dq7V_wOF.js → workspace-folders-BrFjAGZo.js} +1 -1
- package/web/assets/{workspace-order-store-PI98x5sR.js → workspace-order-store-DLX9fhcf.js} +1 -1
- package/web/index.html +2 -2
- package/web/assets/FocusRuntimeControls-CoxLbl8K.js +0 -2
- package/web/assets/command-LVPgEdXI.js +0 -1
- package/web/assets/i18n-DyMZgkZI.js +0 -1
- package/web/assets/public-diff-pNrf0LGG.js +0 -1
- package/web/assets/public-events-DmLE1dVC.js +0 -1
- package/web/assets/safe-mode-sentinel-BGslsjrl.js +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SessionContextPanel-
|
|
2
|
-
import{a as e}from"./rolldown-runtime-B0Z9INg1.js";import{h as t,n,u as r}from"./vendor-router-CSN_DGvx.js";import{t as i}from"./index-CiyAfWLi.js";import{i as a,n as o,r as s}from"./vendor-react-DwNgTV1j.js";import{p as c}from"./routes-BYsK6aeM.js";import{t as l}from"./use-i18n-CsOCclo6.js";import{a as u,i as d,o as f}from"./vendor-state-GkUciC5H.js";import{t as p}from"./storage-DtvZ_lEu.js";import{u as m}from"./query-DFQayLF5.js";import{r as h,t as g}from"./useQuery-DfOU-27z.js";import{t as _}from"./startup-queries-B2k6wlnS.js";import{n as v,r as y,t as b}from"./abort-signal-f4JsiYKX.js";import{a as x,i as S,t as C}from"./http-response-DEs9jkgT.js";import{i as w,n as T}from"./http-B-XVZUum.js";import{n as E,t as D}from"./api-D1flkoh7.js";import{i as O}from"./runtime-capabilities-ChJVNwRz.js";import{t as k}from"./runtime-capabilities-store-MtXRlSIi.js";import{n as A}from"./use-mobile-C2tPBAza.js";import{n as j,t as M}from"./client-store-e4OXhDNK.js";import{t as N}from"./createLucideIcon-Cd-3GVxJ.js";import{t as P}from"./activity-BCxvXCG3.js";import{t as F}from"./archive-ojKJT7Fp.js";import{t as I}from"./book-open-BuHHD9os.js";import{t as L}from"./bot-B3TaBp_T.js";import{t as R}from"./braces-DQcXLGFF.js";import{t as z}from"./check-2vYc6QaP.js";import{t as B}from"./chevron-down-CxtxIjiP.js";import{t as V}from"./chevron-left-BAtyp3_6.js";import{t as H}from"./chevron-right-C3t2Rckj.js";import{t as U}from"./circle-check-iEdCm3Pw.js";import{n as W,t as ee}from"./image-plus-D7bzZog0.js";import{t as te}from"./corner-down-right--hxi-Ihy.js";import{t as ne}from"./download-BCfIiuaL.js";import{o as re}from"./GitDiffViewer-BFdi1mxr.js";import{C as ie,T as ae,_ as oe,a as se,b as ce,c as G,d as le,f as ue,g as de,h as fe,i as pe,l as me,m as K,n as he,o as q,p as ge,r as _e,s as ve,t as ye,u as be,v as xe,w as Se}from"./FocusRuntimeControls-CoxLbl8K.js";import{_ as Ce,a as we,b as Te,c as Ee,d as De,f as Oe,g as ke,h as Ae,i as je,l as Me,m as Ne,n as Pe,o as Fe,p as Ie,s as Le,t as Re,u as ze,v as Be,y as Ve}from"./side-chat-context-C7vwSBGo.js";import{t as He}from"./WorkspacePicker-DyL_8DP0.js";import{t as Ue}from"./folder-open-FIShC5Qk.js";import{t as We}from"./git-branch-N7LGjtzt.js";import{_ as Ge,a as Ke,b as qe,d as Je,i as Ye,m as Xe,r as Ze,u as Qe,v as $e,x as et,y as tt}from"./ChatMessage-DyRMVDmJ.js";import{t as nt}from"./link-2-mgasYn21.js";import{t as rt}from"./list-todo-hpikYm6Q.js";import{t as it}from"./loader-circle-BOwQzHB-.js";import{t as at}from"./message-square-SKjZyY3v.js";import{t as ot}from"./panel-right-BSUtqUd8.js";import{t as st}from"./paperclip-BCXrwYpb.js";import{t as ct}from"./pencil-U08v_vV9.js";import{t as lt}from"./play-DNDjDNGn.js";import{t as ut}from"./plus-fQbSqB1n.js";import{t as dt}from"./refresh-cw-TbWxTY4K.js";import{t as ft}from"./search-D0mqDaf_.js";import{t as pt}from"./settings-QX0oWnVK.js";import{t as mt}from"./shield-alert-oZqX6MNu.js";import{t as ht}from"./square-pen-hYbjKh6A.js";import{t as J}from"./square-terminal-BVG6cUT1.js";import{t as gt}from"./square-bHHVTT3G.js";import{t as _t}from"./tag-CqkeJlBf.js";import{i as vt,n as yt,r as bt,t as xt}from"./AttachmentTray-Fx0RVdj2.js";import{t as St}from"./trash-2-CNrPOoPR.js";import{t as Ct}from"./triangle-alert-CE1q54ci.js";import{t as wt}from"./users-CCtFZzwl.js";import{t as Tt}from"./workflow-Bg94dy8I.js";import{t as Et}from"./wrench-6pg6_bqI.js";import{t as Dt}from"./x-07u4-129.js";import{t as Ot}from"./brand-DIEc3fK8.js";import{t as kt}from"./checkbox-BrEHgFV0.js";import{c as At,i as jt,l as Mt,p as Nt,r as Pt,t as Ft}from"./dropdown-menu-Ds0gD8S8.js";import{a as It,i as Lt,r as Rt,t as zt}from"./popover-DGWRnOht.js";import{t as Bt}from"./progress-5odAz3B9.js";import{t as Vt}from"./switch-D_G8wFhs.js";import{i as Ht,r as Ut,t as Wt}from"./tabs-DsgBuvJv.js";import{n as Gt,t as Kt}from"./segmented-control-xkrEOP_d.js";import{i as qt,n as Jt,t as Yt}from"./tooltip-D4MFbqcG.js";import{t as Xt}from"./utils-C8uzG5AZ.js";import{n as Zt,t as Y}from"./button-CCcCN8tE.js";import{n as Qt,t as $t}from"./kbd-CAufZTkl.js";import{C as en,S as tn,b as nn,c as rn,f as an,i as on,o as sn,p as cn,r as ln,s as un,u as dn,w as fn,x as pn,y as mn}from"./events-C8OUQmIW.js";import{a as hn,c as gn,i as _n,n as vn,r as yn,s as bn,t as xn}from"./shortcuts-C6ddcUau.js";import{n as Sn,o as Cn,r as wn,t as Tn}from"./sheet-BTaIEX4w.js";import{t as X}from"./chat-api-BqA8nXly.js";import{a as En,l as Dn,n as On,s as kn,t as An}from"./session-questions-BPKyVhzp.js";import{r as jn}from"./session-workspaces-Brm-8lHh.js";import{o as Mn,r as Nn,t as Pn}from"./format-DMJQzoZ7.js";import{t as Fn}from"./StatusGlyph-1KgitlUg.js";import{_ as In,b as Ln,d as Rn,f as zn,g as Bn,m as Vn,p as Hn,y as Un}from"./command-LVPgEdXI.js";import{a as Wn,i as Gn,l as Kn,s as qn,t as Jn}from"./dialog-DldLiTwf.js";import{t as Yn}from"./input-CPw-zkYh.js";import{i as Xn,n as Zn,t as Qn}from"./input-group-h8z63MzW.js";import{t as $n}from"./model-display-kDwvtxrW.js";import{t as er}from"./session-change-summary-api-CAkw4_-l.js";import{t as tr}from"./pick-system-directory-D1GGkOTf.js";import{n as nr,r as rr,t as ir}from"./PageState-Cz6vFMXv.js";import{t as ar}from"./back-navigation-CK7X_5Bc.js";import{t as or}from"./MarkdownMessage-B9Bb9VQU.js";import{t as sr}from"./esm-DCV8yILT.js";import{t as cr}from"./motion-DTR4ZVle.js";import{t as lr}from"./shortcut-aria-jHRmld9z.js";import{t as ur}from"./BrandLogo-k3CvJjd4.js";import{i as dr,n as fr,o as Z,s as pr,t as mr}from"./session-tree-summary-BLsTrwUq.js";import{d as hr,f as gr,l as _r,m as vr,n as yr,p as br,r as xr}from"./session-web-preview-DZOVkeBU.js";import{t as Sr}from"./app-primitives-BskZ4ZJj.js";import{i as Cr,n as wr,o as Tr,r as Er,s as Dr,t as Or}from"./session-list-BRMu9JWa.js";import"./public-lAWjPSYc.js";import{n as kr,r as Ar}from"./terminal-context-aIsIJPn8.js";import{n as jr,r as Mr,t as Nr}from"./session-inspector-store-C3BluNoW.js";import{t as Pr}from"./subagent-view-store-BUvI8piR.js";import{a as Fr,i as Ir}from"./tool-labels-D-3gybP7.js";import{fileRewindConfirmOptions as Lr,fileRewindNotice as Rr,notifyTreeNavigation as zr}from"./session-tree-actions-_YCQsWye.js";import{a as Br,c as Vr,i as Hr,l as Ur,n as Wr,o as Gr,s as Kr,t as qr,u as Jr}from"./speech-session-DI3T3jpW.js";import{n as Yr,t as Xr}from"./web-preview-events-D7F0Z-Hy.js";var Zr=N(`audio-lines`,[[`path`,{d:`M2 10v3`,key:`1fnikh`}],[`path`,{d:`M6 6v11`,key:`11sgs0`}],[`path`,{d:`M10 3v18`,key:`yhl04a`}],[`path`,{d:`M14 8v7`,key:`3a1oy3`}],[`path`,{d:`M18 5v13`,key:`123xd1`}],[`path`,{d:`M22 10v3`,key:`154ddg`}]]),Qr=N(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),$r=N(`bookmark`,[[`path`,{d:`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`,key:`oz39mx`}]]),ei=N(`file-check-corner`,[[`path`,{d:`M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6`,key:`g5mvt7`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m14 20 2 2 4-4`,key:`15kota`}]]),ti=N(`file-down`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M12 18v-6`,key:`17g6i2`}],[`path`,{d:`m9 15 3 3 3-3`,key:`1npd3o`}]]),ni=N(`message-circle-question-mark`,[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),ri=N(`mic-off`,[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`,key:`1gzdoj`}],[`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`,key:`cqa7eg`}],[`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`,key:`16hl24`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`,key:`r2i35w`}]]),ii=N(`mic`,[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`,key:`1vc78b`}],[`rect`,{x:`9`,y:`2`,width:`6`,height:`13`,rx:`3`,key:`s6n7sd`}]]),ai=N(`shield`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}]]),oi=N(`shrink`,[[`path`,{d:`m15 15 6 6m-6-6v4.8m0-4.8h4.8`,key:`17vawe`}],[`path`,{d:`M9 19.8V15m0 0H4.2M9 15l-6 6`,key:`chjx8e`}],[`path`,{d:`M15 4.2V9m0 0h4.8M15 9l6-6`,key:`lav6yq`}],[`path`,{d:`M9 4.2V9m0 0H4.2M9 9 3 3`,key:`1pxi2q`}]]),Q=e(a(),1),si=d(()=>({getItem:e=>{try{return i.getItem(e)}catch{return null}},setItem:(e,t)=>{try{i.setItem(e,t)}catch{}},removeItem:e=>{try{i.removeItem(e)}catch{}}})),ci=f()(u((e,t)=>({width:360,open:!1,setWidth:n=>{let r=gr(n);t().width!==r&&e({width:r})},setOpen:n=>{t().open!==n&&e({open:n})}}),{name:`pisper-session-context-layout`,version:2,storage:si,migrate:e=>{let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{width:gr(`width`in t?t.width:void 0),open:`open`in t&&t.open===!0}},partialize:({width:e,open:t})=>({width:e,open:t}),merge:(e,t)=>({...t,width:gr(e&&typeof e==`object`&&!Array.isArray(e)&&`width`in e?e.width:void 0),open:!!(e&&typeof e==`object`&&!Array.isArray(e)&&`open`in e&&e.open===!0)})}));function li(e,t,n){let r=(0,Q.useRef)(n);r.current=n,(0,Q.useLayoutEffect)(()=>e?ar.register(t,()=>r.current()):void 0,[e,t])}var $=s();function ui({preferredWidth:e,onWidthChange:t,availableWidth:n,presentation:r,children:i,context:a,side:o=`right`,layoutId:s=`chat`,conversationHeaderInset:c=0}){let{t:u}=l(),d=(0,Q.useRef)(()=>{});(0,Q.useEffect)(()=>()=>d.current(),[]);let f=r===`aside`,p=r===`content`,m=br(e,n),h=br(720,n),g=e=>t(Math.max(280,Math.min(h,e))),_=n=>{if(n.button!==0)return;d.current(),n.preventDefault(),n.currentTarget.focus(),n.currentTarget.setPointerCapture(n.pointerId);let r=n.clientX,i=e=>g(m+(e.clientX-r)*(o===`left`?1:-1)),a=()=>{window.removeEventListener(`pointermove`,i),window.removeEventListener(`pointerup`,a),window.removeEventListener(`pointercancel`,s),window.removeEventListener(`keydown`,c)},s=()=>{t(e),a()},c=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),s())};d.current=a,window.addEventListener(`pointermove`,i),window.addEventListener(`pointerup`,a,{once:!0}),window.addEventListener(`pointercancel`,s,{once:!0}),window.addEventListener(`keydown`,c)},v=(0,$.jsx)(`div`,{id:`${s}-conversation`,"data-workspace-conversation":!0,inert:p,className:p?`hidden`:`min-h-0 min-w-0 flex-1 overflow-hidden`,style:f&&c?{paddingTop:c}:void 0,children:i},`conversation`),y=f?(0,$.jsx)(`div`,{role:`separator`,tabIndex:0,"aria-orientation":`vertical`,"aria-label":u(`chat:sessionContext.resize`),title:u(`chat:sessionContext.resizeHint`),"aria-controls":`${s}-conversation ${s}-content`,"aria-valuemin":280,"aria-valuemax":h,"aria-valuenow":m,onPointerDown:_,onDoubleClick:()=>t(360),onKeyDown:e=>{if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`,`Enter`].includes(e.key))return;if(e.preventDefault(),e.key===`Enter`){t(360);return}let n=e.shiftKey?64:16;g(e.key===`Home`?280:e.key===`End`?h:m+(e.key===`ArrowRight`?n:-n)*(o===`left`?1:-1))},className:`relative w-2 shrink-0 cursor-col-resize touch-none select-none outline-none after:absolute after:top-1/2 after:left-1/2 after:h-9 after:w-[3px] after:-translate-1/2 after:rounded-full after:bg-stroke-strong after:transition-colors after:duration-[var(--d-fast)] hover:after:bg-focus active:after:bg-focus focus-visible:after:bg-focus focus-visible:after:ring-3 focus-visible:after:ring-focus-ring`},`separator`):null,b=(0,$.jsx)(`div`,{id:`${s}-content`,className:f?`h-full min-h-0 shrink-0 overflow-hidden`:p?`h-full min-h-0 min-w-0 flex-1 overflow-hidden`:`hidden`,style:f?{width:m}:void 0,children:(f||p)&&a},`resource`);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{id:`${s}-context-layout`,"data-workspace-layout":!0,className:`flex h-full min-h-0 min-w-0 flex-1 overflow-hidden`,children:o===`left`?[b,y,v]:[v,y,b]}),r===`sheet`&&a]})}function di({sessionId:e,streaming:t,completed:n,runStartedAt:r,enabled:i,open:a,onReveal:o}){let s=(0,Q.useRef)(null),c=(0,Q.useRef)(o);(0,Q.useLayoutEffect)(()=>{c.current=o},[o]),(0,Q.useEffect)(()=>{let o=s.current,l={sessionId:e,streaming:t,completed:n,runStartedAt:r};if(s.current=l,!i||a||!hr(o,l))return;let u=new AbortController,d=!0;return X.getSessionFileChanges(e,{signal:u.signal}).then(({files:e})=>{d&&vr(o,l,e)&&c.current()}).catch(()=>{}),()=>{d=!1,u.abort()}},[n,i,a,r,e,t])}var fi=`pisper:task-content-requested`,pi=[`changes`,`terminal`,`processes`,`sources`,`browser`];function mi(e){return!e||typeof e!=`object`||!(`kind`in e)?null:pi.find(t=>t===e.kind)||null}function hi({sessionId:e,cwd:t,taskName:n,sources:r,mobile:i,streaming:a}){let{t:o}=l(),s=Ar(e),c=kr(),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null),p=(0,Q.useRef)(!1),m=k(e=>e.capabilities),h=O(m,`vcs`),_=g({enabled:h,queryKey:[`task-project-changes`,e,t,a],queryFn:({signal:t})=>X.getVcsChanges(e,{signal:t})}),v=(0,Q.useMemo)(()=>Le(_.data?.diff||``,_.data?.files.map(e=>e.path)||[],_.data?.diffTruncated),[_.data]),y=()=>xr.getState().update(e,`new`,{type:`workspace`,summaryOpen:!1}),b=()=>document.getElementById(`task-${e}-summary-toggle`)?.focus();(0,Q.useEffect)(()=>{i||f.current?.focus()},[i]);let x=(t,n=``)=>{let r=xr.getState();if(r.update(e,t,{type:`open`,kind:t})===`limit`){d(!0);return}p.current=!0;let i=xr.getState().sessions[e]?.activeId;n&&i&&r.update(e,t,{type:`view`,id:i,patch:t===`sources`?{selectedSourceId:n,query:``,filter:``}:{expandedProcesses:[n],filter:``}})};li(!i,300,()=>{y(),b()});let S=`w-full justify-start gap-2 px-2 font-normal text-content`,C=`ml-auto shrink-0 text-xs text-content-muted tabular-nums`,w=(0,$.jsxs)($.Fragment,{children:[u&&(0,$.jsx)(`p`,{role:`alert`,className:`px-2 pb-1 text-xs text-danger`,children:o(`chat:sessionContext.pageLimit`)}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2 border-b border-stroke-soft px-2 pt-1 pb-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`truncate font-mono text-xs text-content-muted`,title:t,children:t.split(/[\\/]/).filter(Boolean).at(-1)||t}),(0,$.jsx)(`p`,{className:`mt-0.5 truncate text-sm font-medium text-content`,children:n})]}),(0,$.jsx)(Y,{variant:`ghost`,size:`icon`,className:`max-[650px]:size-11`,"aria-label":o(`chat:workbench.closeSummary`),onClick:()=>{y(),b()},children:(0,$.jsx)(Dt,{size:16})})]}),(0,$.jsxs)(`section`,{className:`border-b border-stroke-soft py-1`,children:[(0,$.jsxs)(Y,{variant:`ghost`,className:`${S} h-auto min-h-8 whitespace-normal text-left`,disabled:!h,onClick:()=>x(`changes`),children:[(0,$.jsx)(re,{size:16,className:`text-content-muted`}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:o(`chat:workbench.projectChanges`)}),(0,$.jsx)(`span`,{className:C,children:h?_.isPending?`…`:_.isError||_.data?.error?o(`chat:workbench.unavailable`):_.data?.isRepo?_.data.files.length:`—`:o(`chat:workbench.unavailable`)})]}),(_.isError||_.data?.error)&&(0,$.jsx)(`p`,{role:`alert`,className:`px-2 py-1 text-xs text-danger`,children:o(`chat:workbench.changesFailed`)}),_.data?.isRepo&&!_.isError&&!_.data.error&&(0,$.jsxs)(`p`,{className:`px-2 pb-1 pl-8 font-mono text-xs tabular-nums text-content-muted`,children:[v.partial?`${o(`chat:workbench.partialCounts`)} `:``,(0,$.jsxs)(`span`,{className:`text-success`,children:[`+`,v.added]}),` `,(0,$.jsxs)(`span`,{className:`text-danger`,children:[`−`,v.removed]})]}),(0,$.jsxs)(Y,{variant:`ghost`,className:S,onClick:()=>x(`files`),children:[(0,$.jsx)(Te,{size:16,className:`text-content-muted`}),o(`chat:workbench.taskSnapshots`)]})]}),(0,$.jsxs)(`section`,{className:`border-b border-stroke-soft py-1`,children:[(0,$.jsxs)(Y,{variant:`ghost`,className:S,onClick:()=>x(`processes`),children:[(0,$.jsx)(`span`,{children:o(`terminal:workspace.processes`)}),(0,$.jsx)(`span`,{className:C,children:s.length})]}),!c&&(0,$.jsx)(`p`,{className:`px-2 pb-1 text-xs text-content-muted`,children:o(`terminal:workspace.nativeOnly`)}),s.slice(0,3).map(e=>(0,$.jsxs)(Y,{variant:`ghost`,className:`${S} min-w-0`,onClick:()=>x(`processes`,e.id),children:[e.status===`running`?(0,$.jsx)(Zt,{className:`size-3.5`}):(0,$.jsx)(P,{size:15,className:`text-content-muted`}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-left font-mono text-xs`,children:e.profileId}),(0,$.jsx)(`span`,{className:C,children:e.status===`running`?o(`terminal:workspace.running`):e.status===`exited`?o(`terminal:workspace.exited`):o(`chat:workbench.otherState`)})]},e.id))]}),(0,$.jsxs)(`section`,{className:`pt-1`,children:[(0,$.jsxs)(Y,{variant:`ghost`,className:S,onClick:()=>x(`sources`),children:[(0,$.jsx)(`span`,{children:o(`chat:workbench.sources`)}),(0,$.jsx)(`span`,{className:C,children:r.length})]}),r.slice(0,3).map(e=>(0,$.jsxs)(Y,{variant:`ghost`,className:`${S} min-w-0`,onClick:()=>x(`sources`,e.id),children:[(0,$.jsx)(nt,{size:15,className:`text-content-muted`}),(0,$.jsx)(`span`,{className:`truncate font-mono text-xs`,children:e.name||o(`chat:chatMessage.fileAttachment`)})]},e.id)),(0,$.jsx)(Y,{variant:`ghost`,className:`${S} text-content-muted`,onClick:()=>x(`sources`),children:o(`chat:workbench.viewAll`)})]})]});return i?(0,$.jsx)(Tn,{open:!0,onOpenChange:e=>{e||y()},children:(0,$.jsxs)(Sn,{side:`bottom`,showCloseButton:!1,"aria-describedby":void 0,className:`max-h-[80dvh] overflow-y-auto rounded-t-2xl p-3 pb-[max(16px,var(--pisper-safe-area-bottom))] [&_button]:min-h-11`,style:{left:`calc(44px + var(--pisper-safe-area-left, 0px))`,right:`var(--pisper-safe-area-right, 0px)`},onCloseAutoFocus:e=>{e.preventDefault(),p.current||b()},children:[(0,$.jsx)(Cn,{className:`sr-only`,children:o(`chat:workbench.summary`)}),w]})}):(0,$.jsx)(`div`,{ref:f,tabIndex:-1,id:`task-${e}-summary`,role:`region`,"aria-label":o(`chat:workbench.summary`),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),y(),b())},className:`absolute top-[52px] right-2 z-20 max-h-[calc(100%-64px)] w-80 max-w-[calc(100%-16px)] overflow-y-auto rounded-md bg-popover p-1 text-sm text-popover-foreground shadow-float`,children:w})}function gi(e){if(typeof e!=`string`||Array.from(e).some(e=>e.charCodeAt(0)<32))return``;let t=e.replace(/\\/g,`/`);return!t.startsWith(`/`)&&!/^[a-z]:\//i.test(t)?``:t.replace(/\/\.\//g,`/`).replace(/\/$/,``)||`/`}function _i(e){let t=[],n=new Set;for(let r of e)if(Array.isArray(r.attachments))for(let[e,i]of r.attachments.entries()){if(!i||typeof i!=`object`||Array.isArray(i))continue;let a=typeof i.id==`string`&&!i.id.startsWith(`path:`)&&i.id.length<=512&&!Array.from(i.id).some(e=>e.charCodeAt(0)<32)?i.id:``,o=gi(i.path),s=a?`asset`:o?`path`:`unresolved`,c=a?`asset:${a}`:o?`path:${o}`:`unresolved:${r.id}:${e}`;if(n.has(c))continue;n.add(c);let l=typeof i.name==`string`?i.name:o.split(`/`).pop()||a,u=typeof i.mimeType==`string`?i.mimeType:``,d={...a?{id:a,downloadUrl:`/api/assets/${encodeURIComponent(a)}/download`}:{},...o?{id:a||`path:${o}`,path:o}:{},name:l,mimeType:u,...typeof i.size==`number`&&Number.isFinite(i.size)&&i.size>=0?{size:i.size}:{},...typeof i.text==`string`?{text:i.text.slice(0,4e5)}:{}};t.push({id:c,name:l,method:s,messageId:r.id,attachment:d,available:s!==`unresolved`||typeof i.text==`string`,kind:u.startsWith(`image/`)?`image`:u.startsWith(`text/`)?`text`:`file`})}return t}function vi({width:e,mobile:t,contentOpen:n}){return n?t||e<660?`content`:`split`:`conversation`}var yi=(0,Q.lazy)(()=>t(()=>import(`./SessionContextPanel-Co419auw.js`).then(e=>({default:e.SessionContextPanel})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128])));function bi({sessionId:e,messages:t,taskName:n,cwd:r,panelId:i,active:a,mobile:o,plan:s,streaming:c,completed:u,runStartedAt:d,plansAvailable:f,requestConfirm:p,children:m}){let{t:h}=l(),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(null),b=(0,Q.useMemo)(()=>({headerHost:g,sourceActionHost:v,setSourceActionHost:y}),[g,v]),x=(0,Q.useMemo)(()=>_i(t),[t]),S=(0,Q.useRef)(ci.getState().width).current,C=(0,Q.useRef)(null),[w,T]=(0,Q.useState)(0),E=(0,Q.useMemo)(()=>_r(),[]),D=xr(t=>t.sessions[e])||E,O=xr(e=>e.update);(0,Q.useLayoutEffect)(()=>{D.contentWidth??O(e,`new`,{type:`workspace`,contentWidth:S})},[D.contentWidth,e,S,O]),(0,Q.useLayoutEffect)(()=>{let e=C.current;if(!e)return;let t=()=>T(e.clientWidth);t();let n=null,r=new ResizeObserver(()=>{n!==null&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{n=null,t()})});return r.observe(e),()=>{r.disconnect(),n!==null&&cancelAnimationFrame(n)}},[]);let k=vi({width:w,mobile:o,contentOpen:D.contentOpen&&D.pages.length>0});di({sessionId:e,streaming:c,completed:u,runStartedAt:d,enabled:!0,open:D.contentOpen,onReveal:()=>O(e,`files`,{type:`open`,kind:`files`})}),(0,Q.useEffect)(()=>{if(!a)return;let t=t=>{let n=mi(t.detail);n&&O(e,n,{type:`open`,kind:n})};return window.addEventListener(fi,t),()=>window.removeEventListener(fi,t)},[a,e,O]);let A=()=>{window.dispatchEvent(new Event(un)),O(e,`files`,{type:`workspace`,contentOpen:!1}),requestAnimationFrame(()=>(document.getElementById(`task-${e}-new-content-tab`)||document.getElementById(`task-${e}-more`))?.focus())};li(a&&k===`content`,100,A);let j=D.contentOpen&&D.pages.length>0&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{role:`status`,className:`p-4 text-sm text-content-muted`,children:h(`chat:focusSession.gitLoading`)}),children:(0,$.jsx)(yi,{panelId:`${i}-context`,compact:!1,embedded:!0,active:a,sessionId:e,cwd:r,sources:x,tab:D.pages.find(e=>e.id===D.activeId)?.kind||`files`,plan:s,streaming:c,plansAvailable:f,requestConfirm:p,onTabChange:()=>{},onClose:A,onBack:A})});return(0,$.jsx)(Ee.Provider,{value:b,children:(0,$.jsxs)(`div`,{ref:C,id:`task-${e}-workspace`,tabIndex:-1,"data-task-workspace":e,"data-active":a,className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-panel`,children:[(0,$.jsx)(`div`,{ref:_,className:k===`split`?`@container absolute left-0 top-0 z-10`:`@container shrink-0`,style:k===`split`?{width:`calc(100% - ${br(D.contentWidth??S,w)+8}px)`}:void 0,"data-task-header":!0}),(0,$.jsx)(ui,{preferredWidth:D.contentWidth??S,onWidthChange:t=>{O(e,`new`,{type:`workspace`,contentWidth:t}),ci.getState().setWidth(t)},layoutId:i,availableWidth:w,conversationHeaderInset:48,presentation:k===`split`?`aside`:k===`content`?`content`:`closed`,context:j,children:m}),a&&D.summaryOpen&&(0,$.jsx)(hi,{sessionId:e,cwd:r,taskName:n,sources:x,mobile:o,streaming:c})]})})}function xi(e,t){return e.open===t?e:{open:t,leaving:!t}}function Si(e){return e.leaving?{open:e.open,leaving:!1}:e}function Ci(e){return e.open||e.leaving}function wi(e,t=400){let[n,r]=(0,Q.useState)(()=>({open:e,leaving:!1})),i=n;n.open!==e&&(i=xi(n,e),r(i));let a=i.leaving,o=(0,Q.useCallback)(()=>r(Si),[]);return(0,Q.useLayoutEffect)(()=>{if(!a)return;if(cr()){o();return}let e=window.setTimeout(o,t);return()=>window.clearTimeout(e)},[t,o,a]),{mounted:Ci(i),leaving:a,finish:o}}function Ti(e){return[`running`,`waiting_approval`].includes(String(e.status||``))}function Ei(e,t){return t(e===`running`?`chat:workflowRun.running`:e===`waiting_approval`?`chat:workflowRun.waitingApproval`:e===`completed`?`chat:workflowRun.completed`:e===`failed`?`chat:workflowRun.failed`:e===`cancelled`?`chat:workflowRun.stopped`:`chat:workflowRun.interrupted`)}function Di({sessionId:e,empty:t=null}){let{t:n}=l(),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(``),s=(0,Q.useCallback)(async()=>{try{let t=await X.getSessionWorkflowRuns(e);i(t.runs||[])}catch{}},[e]);if((0,Q.useEffect)(()=>{s();let e=window.setInterval(s,1500);return()=>window.clearInterval(e)},[s]),!r.length)return t;let c=`session-workflow-context grid min-w-0 gap-1 border-b border-stroke-soft pb-1.5 [&_strong]:text-xs [&_strong]:font-medium [&_strong]:text-content-muted [&_p]:max-h-[84px] [&_p]:overflow-auto [&_p]:text-xs [&_p]:leading-relaxed [&_p]:whitespace-pre-wrap [&_p]:text-content-secondary [&_p]:[overflow-wrap:anywhere] [&_pre]:max-h-[84px] [&_pre]:overflow-auto [&_pre]:rounded-xs [&_pre]:bg-code [&_pre]:px-1.5 [&_pre]:py-1 [&_pre]:font-mono [&_pre]:text-xs [&_pre]:leading-relaxed [&_pre]:whitespace-pre-wrap [&_pre]:text-content-secondary [&_pre]:[overflow-wrap:anywhere]`;return(0,$.jsx)(`div`,{className:`flex max-h-[210px] flex-col overflow-auto rounded-md border border-stroke bg-panel`,children:[...r].sort((e,t)=>Date.parse(t.startedAt)-Date.parse(e.startedAt)).slice(0,5).map(e=>{let t=a===e.id,r=Math.round((Number(e.completedNodes)||0)/Math.max(1,Number(e.totalNodes)||1)*100);return(0,$.jsxs)(`div`,{className:`session-workflow-run border-b border-stroke-soft last:border-b-0 ${e.status}`,children:[(0,$.jsxs)(`button`,{className:`session-workflow-summary grid w-full cursor-pointer grid-cols-[20px_minmax(120px,1fr)_minmax(80px,160px)_14px] items-center gap-2.5 border-0 px-3 py-2 text-left text-content transition-colors duration-(--d-fast) hover:bg-surface-subtle focus-visible:-outline-offset-2 max-[650px]:min-h-11 max-[650px]:grid-cols-[20px_minmax(0,1fr)_14px] max-[650px]:[&_[data-slot='progress']]:col-[2/4] [&_[data-slot='progress']]:h-1 [&_>_span:nth-child(2)]:flex [&_>_span:nth-child(2)]:min-w-0 [&_>_span:nth-child(2)]:flex-col [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_small]:tabular-nums [&_strong]:truncate [&_strong]:text-sm [&_strong]:font-medium ${t?`bg-surface-subtle`:`bg-transparent`}`,"aria-expanded":t,onClick:()=>o(t?``:e.id),children:[(0,$.jsx)(`span`,{className:`grid size-5 place-items-center rounded-xs ${e.status===`completed`?`bg-success-soft text-success`:e.status===`failed`?`bg-danger-soft text-danger`:e.status===`waiting_approval`?`bg-warning-soft text-warning-strong`:`bg-surface-muted text-content-muted`}`,children:e.status===`running`?(0,$.jsx)(Zt,{className:`size-3.5`}):e.status===`completed`?(0,$.jsx)(z,{size:12}):e.status===`failed`?(0,$.jsx)(Dt,{size:12}):(0,$.jsx)(Tt,{size:12})}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.workflowName}),(0,$.jsxs)(`small`,{children:[Ei(e.status,n),` · v`,e.workflowRevision||1]})]}),(0,$.jsx)(Bt,{value:e.status===`completed`?100:r}),(0,$.jsx)(H,{size:14,className:`text-content-muted transition-transform duration-(--d-fast) ${t?`rotate-90`:``}`})]}),t&&(0,$.jsxs)(`div`,{className:`session-workflow-detail flex flex-col gap-1.5 border-t border-stroke-soft bg-surface-subtle py-2 pr-3 pl-[42px] max-[650px]:pl-3 [&_>_p]:text-xs [&_>_p]:text-content-muted`,children:[e.sourceMessage&&(0,$.jsxs)(`div`,{className:c,children:[(0,$.jsx)(`strong`,{children:n(`chat:workflowRun.request`)}),(0,$.jsx)(`p`,{children:e.sourceMessage})]}),e.inputs&&Object.keys(e.inputs).length>0&&(0,$.jsxs)(`div`,{className:c,children:[(0,$.jsx)(`strong`,{children:n(`chat:workflowRun.inputs`)}),(0,$.jsx)(`pre`,{children:JSON.stringify(e.inputs,null,2)})]}),(e.nodes||[]).map(t=>(0,$.jsxs)(`div`,{className:`session-workflow-node grid min-h-6 grid-cols-[15px_minmax(0,1fr)_auto] items-center gap-1.5 text-content-muted [&.completed]:text-success [&.failed]:text-danger [&_>_div]:flex [&_>_div]:gap-1 [&_>_span]:flex [&_>_span]:min-w-0 [&_>_span]:flex-col [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_strong]:text-xs [&_strong]:font-medium [&_strong]:text-content ${t.status}`,children:[t.status===`completed`?(0,$.jsx)(z,{size:13}):t.status===`failed`?(0,$.jsx)(W,{size:13}):t.status===`running`?(0,$.jsx)(Zt,{className:`size-3.5`}):(0,$.jsx)(gt,{size:11}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:t.label}),(t.error||t.summary)&&(0,$.jsx)(`small`,{children:t.error||t.summary})]}),t.status===`waiting_approval`&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(Y,{size:`xs`,onClick:async()=>{await X.resolveWorkflowApproval(e.id,t.id,!0),await s()},children:n(`chat:workflowRun.approve`)}),(0,$.jsx)(Y,{size:`xs`,variant:`destructive`,onClick:async()=>{await X.resolveWorkflowApproval(e.id,t.id,!1),await s()},children:n(`chat:workflowRun.reject`)})]})]},t.id)),(e.error||e.summary)&&(0,$.jsx)(`p`,{children:e.error||e.summary}),Ti(e)&&(0,$.jsxs)(Y,{size:`xs`,variant:`destructive`,className:`self-start`,onClick:async()=>{await X.stopWorkflowRun(e.id),await s()},children:[(0,$.jsx)(gt,{"data-icon":`inline-start`}),n(`chat:workflowRun.stop`)]})]})]},e.id)})})}function Oi(e,t){let[n,r]=(0,Q.useState)(()=>Date.now());(0,Q.useEffect)(()=>{if(!t)return;r(Date.now());let e=setInterval(()=>r(Date.now()),1e3);return()=>clearInterval(e)},[t]);let i=e?Date.parse(e):NaN;return t&&Number.isFinite(i)?Math.max(0,n-i):null}function ki(e,t){xr.getState().update(e,`side-chat`,{type:`open`,kind:`side-chat`}),t?.show(`side-chat`)}function Ai(e,t){let{t:n,language:i}=l(),a=(0,Q.useContext)(Ye),[o,s]=(0,Q.useState)(!1),[c,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(!1),p=k(e=>e.capabilities.features.sessionExport===!0),m=e.name||n(`navigation:pageHeader.newChat`),{notify:h}=t,g=r(),_=e.botId,v=async()=>{if(!c){u(!0);try{await Dn(e.id,{archived:!0}),h(n(`board:action.archived`,{title:m})),a?.onArchived?.(e.id)}catch{h(n(`board:action.failed`),`error`)}finally{u(!1)}}},y=async()=>{if(!d){f(!0);try{let t=await X.exportSessionMarkdown(e.id,i),r=URL.createObjectURL(t),a=document.createElement(`a`);a.href=r,a.download=`${m.replace(/[\\/:*?"<>|\p{Cc}]/gu,`-`).slice(0,80)||`session`}.md`,a.click(),window.setTimeout(()=>URL.revokeObjectURL(r),1e3),h(n(`chat:sessionMenu.exported`,{title:m}))}catch{h(n(`chat:sessionMenu.exportFailed`),`error`)}finally{f(!1)}}},b=typeof t.contextPercent==`number`&&Number.isFinite(t.contextPercent)?Math.round(Math.min(100,Math.max(0,t.contextPercent))):null,x=[..._?[]:[{key:`rename`,icon:ct,label:n(`chat:sessionMenu.rename`),onSelect:t.onRename}],...t.onSideChat?[{key:`side-chat`,icon:at,label:n(`board:inspector.sideChat`),onSelect:t.onSideChat,marker:`session-side-chat`}]:[],...p?[{key:`export`,icon:ti,label:n(`chat:sessionMenu.exportMarkdown`),onSelect:()=>void y(),disabled:d,marker:`session-export`}]:[],...e.machine||_?[]:[{key:`workspace`,icon:Ue,label:n(`board:session.moveWorkspace`),onSelect:t.onWorkspace,disabled:t.workspaceDisabled,separator:!0}],{key:`compact`,icon:oi,label:n(`chat:sessionMenu.compactContext`),onSelect:()=>t.onCompact?.(),disabled:t.compactDisabled||!t.onCompact,trailing:b===null?void 0:`${b}%`,trailingTitle:b===null?void 0:n(`board:session.contextUsage`,{percent:b})},...t.workflowsAvailable?[{key:`workflows`,icon:Tt,label:n(`chat:sessionMenu.workflowRuns`),onSelect:()=>s(!0)}]:[],{key:`voice`,icon:Zr,label:n(`chat:sessionMenu.voiceMode`),onSelect:t.onVoiceMode},_?{key:`delete-bot`,icon:St,label:n(`chat:sessionMenu.deleteBot`),onSelect:()=>g(`/bots/${encodeURIComponent(_)}?action=delete`),separator:!0,marker:`session-delete-bot`}:{key:`archive`,icon:F,label:n(`board:card.archive`),onSelect:()=>void v(),disabled:c,separator:!0}];return{entries:x,items:(0,$.jsxs)($.Fragment,{children:[x.map(e=>{let t=e.icon,n=e.marker?{[`data-${e.marker}`]:!0}:{},r=(0,$.jsxs)(jt,{disabled:e.disabled,onSelect:e.onSelect,...n,children:[(0,$.jsx)(t,{}),e.label,e.trailing&&(0,$.jsx)(Mt,{className:`font-mono tabular-nums`,title:e.trailingTitle,"data-session-context-usage":!0,children:e.trailing})]});return(0,$.jsxs)(Q.Fragment,{children:[e.separator&&(0,$.jsx)(At,{}),r]},e.key)}),t.extraItems&&(0,$.jsx)(At,{}),t.extraItems]}),dialog:(0,$.jsx)(Jn,{open:o,onOpenChange:s,children:(0,$.jsxs)(Gn,{className:`max-w-lg`,children:[(0,$.jsxs)(qn,{children:[(0,$.jsx)(Kn,{children:n(`board:session.workflowRuns`)}),(0,$.jsx)(Wn,{children:m})]}),o&&(0,$.jsx)(Di,{sessionId:e.id,empty:(0,$.jsx)(`p`,{className:`py-6 text-center text-sm text-content-muted`,children:n(`board:session.workflowRunsEmpty`)})})]})})}}var ji=(0,Q.lazy)(()=>t(()=>import(`./SessionInspector-KjdRXk-P.js`).then(e=>({default:e.SessionInspector})),__vite__mapDeps([129,1,3,4,5,2,6,7,8,9,23,24,10,11,12,13,14,15,16,18,130,20,22,19,25,26,27,21,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,17,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,131,122,123,124,132,126,127,128,133,134]))),Mi=[];function Ni(e){switch(e){case`changes`:return{tab:`changes`,changesView:`workspace`};case`files`:return{tab:`changes`,changesView:`session`};case`terminal`:case`processes`:return{tab:`terminal`,terminalView:e};case`sources`:return{tab:`files`};case`browser`:return{tab:`preview`};case`plan`:return{tab:`plan`};case`side-chat`:return{tab:`side-chat`};default:return null}}function Pi(e){if(!(e instanceof HTMLElement)||e===document.body||e.closest(`[data-inspector-sheet]`))return null;let t=e.closest(`[role="menu"]`);if(!t)return e;let n=t.getAttribute(`aria-labelledby`);return n?document.getElementById(n):null}var Fi=`a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), iframe, [tabindex]:not([tabindex="-1"])`;function Ii(e){if(e.key!==`Tab`||e.altKey||e.ctrlKey||e.metaKey)return;let t=[...e.currentTarget.querySelectorAll(Fi)].filter(e=>e.getClientRects().length>0);if(!t.length)return;let n=t[0],r=t[t.length-1],i=document.activeElement;(e.shiftKey?i===n:i===r)&&(e.preventDefault(),(e.shiftKey?r:n).focus())}function Li(e){let t=e?.items??[];return t.length?{done:t.filter(e=>e.status===`completed`).length,total:t.length}:null}function Ri({sessionId:e,messages:t,cwd:n,active:r,plan:i,goal:a=null,team:o=null,activity:s=Mi,planTab:c,streaming:u,completed:d,runStartedAt:f,requestConfirm:p,remoteMachine:m=!1,children:h}){let{t:g}=l(),_=(0,Q.useContext)(Ye),v=!!(_?.phone??null),y=v||!!(_?.compact||_?.overlayOnly),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(null),w=(0,Q.useMemo)(()=>({headerHost:b,sourceActionHost:S,setSourceActionHost:C}),[b,S]),T=(0,Q.useMemo)(()=>_i(t),[t]),E=Mr(e=>e.open),D=Mr(e=>e.pinned),O=Mr(e=>e.setOpen),k=Mr(e=>e.widthPercent),A=Mr(e=>e.width),j=Mr(e=>e.setWidth),M=Mr(e=>e.resetWidth),[N,P]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{y||P(!1)},[y]);let F=y?N:E,I=wi(v&&F),L=v&&I.leaving,R=(0,Q.useRef)(null),z=`session-${e}-inspector`,B=(0,Q.useRef)(null),[V,H]=(0,Q.useState)(0);(0,Q.useLayoutEffect)(()=>{let e=B.current;if(!e)return;let t=()=>H(e.clientWidth);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let U=jr({widthPercent:k,width:A},V||window.innerWidth),[W,ee]=(0,Q.useState)(0);(0,Q.useLayoutEffect)(()=>{if(!b)return;let e=()=>ee(b.offsetHeight);e();let t=new ResizeObserver(e);return t.observe(b),()=>t.disconnect()},[b]);let te=(0,Q.useRef)(null),[ne,re]=(0,Q.useState)(!1),[ie,ae]=(0,Q.useState)(!1),oe=(0,Q.useCallback)((e,t=!1)=>{if(window.dispatchEvent(new Event(un)),v&&e){let e=Pi(document.activeElement);e&&(R.current=e)}re(e),ae(e&&t),y?P(e):O(e)},[y,O,v]),ce=(0,Q.useCallback)((e,t)=>{Mr.getState().setTab(e),oe(!0,t)},[oe]),G=(0,Q.useCallback)(e=>ce(e,!0),[ce]),le=(0,Q.useCallback)(()=>{let e=document.activeElement,t=!!(e&&te.current?.contains(e))||y&&!v&&(!e||e===document.body);oe(!1),t&&requestAnimationFrame(()=>document.querySelector(`[aria-controls="${CSS.escape(z)}"][data-inspector-toggle]`)?.focus())},[y,z,oe,v]),ue=(0,Q.useCallback)(()=>F?le():oe(!0,!0),[le,F,oe]),de=(0,Q.useCallback)(t=>{t.preventDefault();let n=R.current;R.current=null,((n?.isConnected?n:null)??document.querySelector(`[data-session-changes][aria-controls="${CSS.escape(z)}"]`)??document.getElementById(`task-${e}-more`))?.focus({preventScroll:!0})},[z,e]),fe=v?`sheet`:y?`overlay`:`aside`,pe=(0,Q.useMemo)(()=>({open:F,mode:fe,panelId:z,toggle:ue,show:G}),[F,fe,z,G,ue]),me=(0,Q.useCallback)(e=>{let t=Ni(e);if(!t)return;let n=Mr.getState();t.terminalView&&n.setTerminalView(t.terminalView),t.changesView&&n.setChangesView(t.changesView),ce(t.tab,!1)},[ce]);(0,Q.useEffect)(()=>xr.subscribe((t,n)=>{let r=t.sessions[e],i=n.sessions[e];if(!r||r===i||!r.contentOpen)return;let a=r.pages.find(e=>e.id===r.activeId);if(!a)return;let o=i?.pages.find(e=>e.id===i.activeId);(r.activeId!==i?.activeId||!i?.contentOpen||a.kind===`browser`&&a.url!==o?.url)&&me(a.kind)}),[me,e]),(0,Q.useEffect)(()=>{if(!r)return;let t=t=>{let n=mi(t.detail);n&&xr.getState().update(e,n,{type:`open`,kind:n})};return window.addEventListener(fi,t),()=>window.removeEventListener(fi,t)},[r,e]),(0,Q.useEffect)(()=>{if(!r)return;let t=t=>{let n=t.detail;n===`side-chat`?ki(e,pe):n===`tree`&&B.current?.querySelector(`[data-session-branches]`)?.click()};return window.addEventListener(on,t),()=>window.removeEventListener(on,t)},[r,pe,e]),di({sessionId:e,streaming:u,completed:d,runStartedAt:f,enabled:!y,open:F,onReveal:()=>me(`files`)});let K=gn(e=>e.bindings.toggleInspector);(0,Q.useEffect)(()=>{if(!r)return;let e=e=>{!yn(e,K)||hn(e)||_n(e)&&e.key.length===1||(e.preventDefault(),ue())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,K,ue]),li(r&&y&&N,100,le),li(r&&!y&&E&&!D,100,le);let he=(0,Q.useRef)(()=>{});(0,Q.useEffect)(()=>()=>he.current(),[]);let q=e=>{if(e.button!==0)return;he.current(),e.preventDefault(),e.currentTarget.focus(),e.currentTarget.setPointerCapture(e.pointerId);let t=e.clientX,n=U,r=e=>j(Nr(n-(e.clientX-t),V),V),i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),window.removeEventListener(`pointercancel`,i)};he.current=i,window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i,{once:!0}),window.addEventListener(`pointercancel`,i,{once:!0})},ge=u?Li(i):null,_e=ne&&F&&!y,ve=y&&!v&&F&&V-420>=480?420:0,ye=(F||L)&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,className:`p-4 text-sm text-content-muted`,children:g(`chat:focusSession.gitLoading`)}),children:(0,$.jsx)(ji,{panelId:z,sessionId:e,cwd:n,streaming:u,plan:i,goal:a,team:o,activity:s,planTab:c,sources:T,mode:fe,requestConfirm:p,onClose:le,onOpenComponents:_?.onOpenComponents,componentTabs:_?.componentTabs,autoFocus:fe===`overlay`&&ie,remoteMachine:m})});return(0,$.jsx)(Ee.Provider,{value:w,children:(0,$.jsx)(Ze.Provider,{value:pe,children:(0,$.jsxs)(`div`,{ref:B,id:`task-${e}-workspace`,tabIndex:-1,"data-task-workspace":e,"data-session-workspace":fe,"data-active":r,className:Xt(`relative flex h-full min-h-0 min-w-0 overflow-hidden bg-panel`,v&&`pb-[var(--pisper-safe-area-bottom)] [[data-mobile-keyboard='open']_&]:pb-0`),children:[(0,$.jsxs)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col`,"data-session-conversation":!0,children:[(0,$.jsx)(`div`,{ref:x,className:`@container shrink-0`,"data-task-header":!0}),ge&&(0,$.jsxs)(`div`,{className:`relative z-10 h-0.5 shrink-0 bg-surface-muted`,"data-plan-progress":!0,children:[(0,$.jsx)(`span`,{role:`progressbar`,"aria-label":g(`board:session.planLabel`,ge),"aria-valuemin":0,"aria-valuemax":ge.total,"aria-valuenow":ge.done,className:`absolute inset-0 origin-left bg-st-run transition-transform duration-(--d-base)`,style:{transform:`scaleX(${ge.done/ge.total})`}}),c&&(0,$.jsx)(`button`,{type:`button`,className:`absolute top-1.5 right-3 inline-flex h-6 items-center rounded-sm bg-panel px-2 font-mono text-xs text-content-secondary tabular-nums shadow-edge hover:bg-surface-hover hover:text-content focus-visible:outline-2 focus-visible:outline-focus pointer-coarse:h-11`,"aria-label":g(`board:session.planOpen`,{plan:g(`board:session.plan`,ge)}),"aria-controls":z,"data-plan-progress-open":!0,onClick:()=>G(`plan`),children:g(`board:session.plan`,ge)})]}),(0,$.jsx)(`div`,{className:Xt(`min-h-0 min-w-0 flex-1 overflow-hidden`,_e&&`animate-in duration-[220ms] ease-(--ease)`),"data-overlay-inset":ve||void 0,style:ve?{paddingRight:ve}:_e?{"--tw-enter-translate-x":`${U/2}px`}:void 0,children:h})]}),!y&&F&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{role:`separator`,tabIndex:0,"aria-orientation":`vertical`,"aria-label":g(`chat:sessionContext.resize`),title:g(`chat:sessionContext.resizeHint`),"aria-controls":z,"aria-valuemin":360,"aria-valuemax":Nr(1/0,V),"aria-valuenow":U,onPointerDown:q,onDoubleClick:M,onKeyDown:e=>{if(![`ArrowLeft`,`ArrowRight`,`Enter`].includes(e.key))return;if(e.preventDefault(),e.key===`Enter`){M();return}let t=e.shiftKey?64:16;j(Nr(U+(e.key===`ArrowLeft`?t:-t),V),V)},className:`relative -mr-1 w-2 shrink-0 cursor-col-resize touch-none select-none outline-none after:absolute after:inset-y-0 after:left-1/2 after:w-px after:bg-stroke-soft after:transition-colors after:duration-(--d-fast) hover:after:w-[3px] hover:after:-translate-x-px hover:after:bg-focus focus-visible:after:w-[3px] focus-visible:after:bg-focus`}),(0,$.jsxs)(`aside`,{ref:te,className:Xt(`flex h-full min-h-0 shrink-0 flex-col overflow-hidden border-l border-stroke-soft`,ne&&`animate-in slide-in-from-right duration-[220ms] ease-(--ease)`),style:{width:U},"data-inspector-aside":!0,"data-inspector-pinned":D||void 0,children:[(0,$.jsx)(`div`,{"aria-hidden":`true`,"data-window-drag-region":!0,"data-inspector-titlebar-gap":!0,className:`hidden h-[52px] shrink-0 [[data-custom-titlebar]_&]:block`}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1`,children:ye})]})]}),y&&(F||L)&&(0,$.jsx)($.Fragment,{children:v?(0,$.jsx)(Tn,{open:F,onOpenChange:e=>!e&&le(),children:(0,$.jsxs)(Sn,{side:`bottom`,showCloseButton:!1,"data-inspector-sheet":!0,"data-sheet-leaving":L||void 0,onAnimationEnd:e=>{e.target===e.currentTarget&&!F&&I.finish()},onCloseAutoFocus:de,className:`gap-0 data-[side=bottom]:h-[min(86dvh,calc(100dvh-var(--pisper-safe-area-top)-48px))] overflow-hidden rounded-t-(--r-sheet) bg-panel p-0 pb-[var(--pisper-safe-area-bottom)]`,children:[(0,$.jsx)(Cn,{className:`sr-only`,children:g(`board:inspector.label`)}),(0,$.jsx)(wn,{className:`sr-only`,children:g(`board:phone.inspectorDescription`)}),(0,$.jsx)(se,{onDismiss:le}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col [&_[data-slot=segmented-control]]:h-11 [&_[data-slot=segmented-control-item]]:h-10 [&_[data-slot=segmented-control-item]]:px-3`,children:ye})]})}):(0,$.jsx)(`aside`,{ref:te,"data-inspector-overlay":!0,onKeyDown:Ii,className:Xt(`absolute right-0 bottom-0 z-30 max-w-[calc(100%-24px)] overflow-hidden border-l border-stroke bg-panel shadow-float`,`animate-in slide-in-from-right duration-[220ms] ease-(--ease)`),style:{width:420,top:W},children:ye})})]})})})}var zi=e(o(),1),Bi=(0,Q.createContext)(null),Vi=new Set([`queued`,`starting`,`running`]),Hi=new Set([`starting`,`running`,`stopping`]);function Ui(e){return typeof e==`string`?e.trim():``}function Wi(e,t,n){let r=new Map;for(let i of e){if(i?.type!==t)continue;let e=n(i);e&&r.set(String(e.id||r.size),e)}return[...r.values()]}function Gi({startedAt:e}){let[t,n]=(0,Q.useState)(()=>Date.now());(0,Q.useEffect)(()=>{let e=window.setInterval(()=>n(Date.now()),1e3);return()=>window.clearInterval(e)},[]);let r=Hn(e,null,t);return r?(0,$.jsx)(`span`,{className:`flex-none font-mono text-xs text-content-muted tabular-nums`,children:ge(r)}):null}function Ki(e,t,n){let{t:r}=l(),i=Ar(e);return[...t?Wi(n,`tool`,e=>e).filter(e=>e.status===`running`).map(e=>{let t=e.args||{};return{key:`tool:${String(e.id)}`,kind:`tool`,icon:(0,$.jsx)(Et,{size:14,"aria-hidden":`true`}),name:Ui(e.name)||r(`board:inspector.runningTool`),detail:Ui(t.command)||Ui(t.path)||Ui(t.file_path),startedAt:Ui(e.startedAt),status:r(`board:inspector.runningStatus`)}}):[],...Wi(n,`agent`,e=>e.agent&&typeof e.agent==`object`?e.agent:null).filter(e=>Vi.has(String(e.status))).map(e=>({key:`agent:${String(e.id)}`,kind:`agent`,agentId:Ui(e.id),icon:(0,$.jsx)(L,{size:14,"aria-hidden":`true`}),name:Ui(e.title)||Ui(e.taskName)||r(`board:inspector.runningAgent`),detail:Ui(e.message),startedAt:Ui(e.startedAt),status:e.status===`queued`?r(`board:inspector.runningQueued`):r(`board:inspector.runningStatus`)})),...i.filter(e=>Hi.has(e.status)).map(e=>({key:`terminal:${e.id}`,kind:`terminal`,icon:(0,$.jsx)(J,{size:14,"aria-hidden":`true`}),name:e.profileId||r(`board:inspector.terminal`),detail:e.cwd||``,status:e.status===`stopping`?r(`terminal:workspace.stopping`):r(`board:inspector.runningStatus`)}))]}function qi({row:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`mt-0.5 text-content-secondary`,children:e.icon}),(0,$.jsxs)(`span`,{className:`grid min-w-0 gap-0.5`,children:[(0,$.jsx)(`strong`,{className:`truncate text-[13px] font-medium text-content`,children:e.name}),e.detail&&(0,$.jsx)(`span`,{className:`min-w-0 truncate font-mono text-content-muted`,title:e.detail,children:e.detail})]}),(0,$.jsxs)(`span`,{className:`flex flex-none items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-content-muted`,children:e.status}),(0,$.jsx)(Gi,{startedAt:e.startedAt})]})]})}var Ji=`grid min-h-9 w-full min-w-0 grid-cols-[14px_minmax(0,1fr)_auto] items-start gap-2 rounded-sm px-2 py-1.5 text-left text-xs pointer-coarse:min-h-11`;function Yi({sessionId:e,streaming:t,activity:n,phoneButtonClass:r}){let{t:i}=l(),a=(0,Q.useContext)(Ze),[o,s]=(0,Q.useState)(!1),c=Ki(e,t,n),u=k(e=>e.capabilities.features.agentTranscripts);if(!c.length)return null;let d=i(`board:inspector.runningCount`,{count:c.length}),f=()=>{s(!1),Mr.getState().setTerminalView(`processes`),a?.show(`terminal`)},p=t=>{s(!1),Pr.getState().select(e,t),a?.show(`subagent`)};return(0,$.jsxs)(zt,{open:o,onOpenChange:s,children:[(0,$.jsx)(It,{asChild:!0,children:r?(0,$.jsxs)(`button`,{type:`button`,className:r,"aria-label":d,"data-session-running":c.length,children:[(0,$.jsx)(Fn,{status:`run`,className:`size-5`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`absolute top-1.5 right-1 grid h-4 min-w-4 place-items-center rounded-full bg-content px-1 text-[10px] leading-none font-semibold text-panel tabular-nums`,children:c.length>99?`99+`:c.length})]}):(0,$.jsxs)(Y,{type:`button`,variant:`ghost`,className:Xt(`h-8 flex-none gap-1.5 px-2 text-[13px] font-normal text-content-secondary tabular-nums hover:text-content pointer-coarse:h-11`,o&&`bg-surface-hover text-content`),"aria-label":d,title:d,"data-session-running":c.length,children:[(0,$.jsx)(Fn,{status:`run`,className:`size-3.5`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:d})]})}),(0,$.jsxs)(Rt,{align:`end`,className:`w-[380px] gap-1.5 p-1.5`,"aria-label":i(`board:inspector.running`),"data-session-running-list":!0,children:[(0,$.jsx)(Lt,{className:`px-2 pt-1 text-xs font-medium text-content-muted`,children:i(`board:inspector.running`)}),(0,$.jsx)(`ul`,{className:`m-0 flex list-none flex-col gap-px p-0`,children:c.map(e=>(0,$.jsx)(`li`,{"data-running-item":e.kind,children:e.kind===`agent`&&e.agentId&&u&&a?(0,$.jsx)(`button`,{type:`button`,className:Xt(Ji,`group cursor-pointer hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus`),"aria-label":i(`board:subagent.open`,{name:e.name}),onClick:()=>p(e.agentId??``),children:(0,$.jsx)(qi,{row:e})}):e.kind===`terminal`&&a?(0,$.jsx)(`button`,{type:`button`,className:Xt(Ji,`group cursor-pointer hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus`),"aria-label":i(`board:inspector.runningOpenProcess`,{name:e.name}),onClick:f,children:(0,$.jsx)(qi,{row:e})}):(0,$.jsx)(`div`,{className:Ji,children:(0,$.jsx)(qi,{row:e})})},e.key))}),c.some(e=>e.kind===`terminal`)&&a&&(0,$.jsxs)(`button`,{type:`button`,className:`flex h-8 w-full cursor-pointer items-center justify-between rounded-sm px-2 text-[13px] text-content-secondary hover:bg-surface-hover hover:text-content pointer-coarse:h-11`,onClick:f,children:[i(`board:inspector.runningAllProcesses`),(0,$.jsx)(H,{size:14,"aria-hidden":`true`})]}),(0,$.jsx)(`p`,{className:`m-0 border-t border-stroke-soft px-2 pt-2 pb-1 text-xs leading-relaxed text-content-faint`,children:i(`board:inspector.runningHint`)})]})]})}var Xi=(0,Q.lazy)(()=>t(()=>import(`./public-session-CtusCiv8.js`),__vite__mapDeps([135,1,2,3,4,5,6,7,8,9,136,18,35,34,36,33,137,105,138,76,24,77,12,13,14,15,16,139,140,10,11,37,127])));function Zi({session:e,cwd:t,streaming:r,treeAvailable:i,branches:a,onOpenTree:o,runningActivity:s=[],...u}){let d=e.machine?`${e.machine.name}:${e.machine.cwd}`:t,{t:f,language:p}=l(),m=(0,Q.useContext)(Ze),h=Ai(e,{...u,onSideChat:()=>ki(e.id,m)}),_=e.name||f(`navigation:pageHeader.newChat`),v=Mn(e.projectless?``:d,p),y=e.machine?jn(e.machine):v,b=g({queryKey:[`session-change-summary`,e.id,r],queryFn:()=>er(e.id),staleTime:1e4}),x=b.data?.status===`known`?b.data:null,S=x?.changedFiles??0,C=gn(e=>e.bindings.toggleInspector),w=gn(e=>e.bindings.sessionTree),T=xn(C),E=xn(w),D=S>0?f(`board:session.changes`,{count:S,added:x?.added??0,removed:x?.removed??0}):null,O=D?`${f(`board:inspector.label`)} · ${D}`:f(`board:inspector.label`),k=T?f(`board:session.withShortcut`,{label:O,shortcut:T}):O,A=a>0?f(`board:session.treeBranches`,{count:a}):f(`board:session.tree`),j=E?f(`board:session.withShortcut`,{label:A,shortcut:E}):A;return(0,$.jsxs)(`header`,{"data-session-header":!0,"data-focus-region":`header`,"data-window-drag-region":!0,className:`flex h-[52px] min-w-0 shrink-0 items-center gap-2 pr-3 pl-4 [[data-custom-titlebar]_&]:pr-[144px]`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1.5`,"data-window-drag-region":!0,children:[e.roomId&&(0,$.jsx)(Y,{asChild:!0,variant:`ghost`,size:`icon-sm`,className:`-ml-1`,children:(0,$.jsx)(n,{to:c(e.roomId),"data-session-back-room":!0,"aria-label":f(`board:session.backToRoom`),title:f(`board:session.backToRoom`),children:(0,$.jsx)(V,{})})}),e.botId&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Xi,{botId:e.botId,part:`avatar`})}),(0,$.jsxs)(Ft,{children:[(0,$.jsx)(Nt,{asChild:!0,children:(0,$.jsxs)(`button`,{type:`button`,id:`task-${e.id}-more`,"data-session-menu":!0,className:Xt(`group inline-flex h-8 min-w-0 shrink items-center gap-1 rounded-sm px-2 text-[15px] leading-6 font-medium text-content hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus data-[state=open]:bg-surface-hover pointer-coarse:h-11`,Gt),"aria-label":f(`board:session.titleMenu`,{title:_}),children:[(0,$.jsx)(`span`,{className:`truncate`,"data-session-title":!0,children:_}),(0,$.jsx)(B,{className:`size-3.5 flex-none text-content-muted`,"aria-hidden":`true`})]})}),(0,$.jsx)(Pt,{align:`start`,className:`min-w-60`,children:h.items})]}),(0,$.jsx)(`span`,{className:`min-w-0 max-w-[160px] flex-none truncate font-mono text-xs text-content-muted @max-[560px]:hidden`,title:d,"data-session-project":!0,children:y}),e.botId&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Xi,{botId:e.botId,part:`settings`})}),i&&(0,$.jsxs)(Y,{type:`button`,variant:`ghost`,className:Xt(`h-7 min-w-7 flex-none gap-1 px-1.5 font-mono text-xs font-normal text-content-muted tabular-nums hover:text-content pointer-coarse:h-11 pointer-coarse:min-w-11`),"aria-haspopup":`dialog`,"aria-label":j,title:j,"aria-keyshortcuts":lr(w),"data-session-branches":a,onClick:e=>o(`branches`,e.currentTarget),children:[(0,$.jsx)(et,{className:`size-3.5`,"aria-hidden":`true`}),a>0&&(0,$.jsx)(`span`,{"aria-hidden":`true`,children:a})]})]}),(0,$.jsx)(Yi,{sessionId:e.id,streaming:r,activity:s}),m&&(0,$.jsx)(Y,{type:`button`,variant:`ghost`,className:Xt(`h-8 flex-none gap-1.5 px-2 text-[13px] font-normal text-content-secondary hover:text-content pointer-coarse:h-11`,D?``:`w-8 px-0 pointer-coarse:w-11`,m.open&&`bg-surface-hover text-content ring-1 ring-stroke ring-inset`),"data-inspector-toggle":!0,"data-session-changes":S,"aria-controls":m.panelId,"aria-expanded":m.open,"aria-label":k,title:k,"aria-keyshortcuts":lr(C),onClick:m.toggle,children:D&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(re,{className:`size-3.5`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:f(`board:session.changedFiles`,{count:S})}),(0,$.jsxs)(`span`,{className:`font-mono text-xs text-success tabular-nums`,"aria-hidden":`true`,children:[`+`,x.added??0]}),(0,$.jsxs)(`span`,{className:`font-mono text-xs text-danger tabular-nums`,"aria-hidden":`true`,children:[`−`,x.removed??0]})]}):(0,$.jsx)(ot,{"aria-hidden":`true`})}),h.dialog]})}var Qi=`outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus`,$i={1:`grid-cols-1`,2:`grid-cols-2`,3:`grid-cols-3`};function ea({count:e,children:t}){return(0,$.jsx)(`div`,{className:Xt(`grid gap-2 px-1 pb-2`,$i[e]??`grid-cols-3`),children:t})}function ta({icon:e,label:t,className:n,...r}){return(0,$.jsxs)(`button`,{type:`button`,className:Xt(`flex h-[68px] min-w-0 cursor-pointer flex-col items-center justify-center gap-1.5 rounded-[var(--r-md)] bg-surface-muted px-1 text-[13px] text-content active:bg-surface-hover disabled:cursor-default disabled:text-content-faint`,Qi,n),...r,children:[(0,$.jsx)(e,{className:`size-5 text-content-secondary`,strokeWidth:1.75,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`max-w-full truncate`,children:t})]})}function na({icon:e,label:t,hint:n,trailing:r,className:i,...a}){return(0,$.jsxs)(`button`,{type:`button`,className:Xt(`flex min-h-11 w-full min-w-0 cursor-pointer items-center gap-3 rounded-[var(--r-md)] px-3 text-left text-[15px] text-content active:bg-surface-hover disabled:cursor-default disabled:text-content-faint`,Qi,i),...a,children:[(0,$.jsx)(e,{className:`size-[18px] flex-none text-content-secondary`,strokeWidth:1.75,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:t}),n&&(0,$.jsx)(`span`,{className:`truncate text-xs text-content-muted`,children:n})]}),r]})}var ra=`relative grid size-11 flex-none place-items-center rounded-full bg-surface-muted text-content focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus active:bg-surface-hover dark:bg-surface-active`;function ia({leading:e,session:t,cwd:n,streaming:r,runStartedAt:i,approvals:a,failed:o,stopped:s,treeAvailable:c,branches:u,onOpenTree:d,runningActivity:f=[],...p}){let m=t.machine?`${t.machine.name}:${t.machine.cwd}`:n,{t:h,language:_}=l(),v=(0,Q.useContext)(Ze),y=(0,Q.useContext)(Ye),b=Oi(i,r),x=Ai(t,p),[S,C]=(0,Q.useState)(!1),w=(0,Q.useId)(),T=t.name||h(`navigation:pageHeader.newChat`),E=Mn(t.projectless?``:m,_),D=t.machine?jn(t.machine):E,O=g({queryKey:[`session-change-summary`,t.id,r],queryFn:()=>er(t.id),staleTime:1e4}),k=O.data?.status===`known`?O.data.changedFiles??0:0,A=a>0?{kind:`approval`,label:h(`board:status.approval`)}:r?{kind:`running`,label:b===null?h(`board:status.running`):h(`board:phone.running`,{elapsed:Pn(b)})}:o?{kind:`failed`,label:h(`board:status.failed`)}:s?{kind:`stopped`,label:h(`board:status.stopped`)}:null,j=()=>v?.show(`changes`),M=[...c?[{key:`tree`,icon:et,label:u>0?h(`board:session.treeBranches`,{count:u}):h(`board:session.tree`),shortLabel:h(`board:session.tree`),onSelect:()=>d(`branches`),marker:`session-tree`}]:[],{key:`side-chat`,icon:at,label:h(`board:inspector.sideChat`),onSelect:()=>ki(t.id,v),marker:`session-side-chat`},...v?[{key:`inspector`,icon:re,label:h(`board:phone.openInspector`),shortLabel:h(`board:phone.openInspectorShort`),onSelect:j,marker:`inspector-toggle`}]:[]];return(0,$.jsxs)(`header`,{"data-session-header":`phone`,className:`grid h-14 min-w-0 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center bg-panel px-3`,children:[(0,$.jsx)(`div`,{className:`flex min-w-0 items-center`,children:e}),(0,$.jsxs)(`button`,{type:`button`,"data-session-menu-trigger":!0,"aria-haspopup":`dialog`,"aria-expanded":S,"aria-controls":S?w:void 0,"aria-label":h(`board:session.titleMenu`,{title:T}),className:`flex h-11 max-w-[min(58vw,260px)] min-w-0 flex-col items-center justify-center rounded-[var(--r-md)] px-2 outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus active:bg-surface-hover`,onClick:()=>C(!0),children:[(0,$.jsxs)(`span`,{className:`flex max-w-full min-w-0 items-center gap-0.5 text-base leading-5 font-semibold text-content`,children:[(0,$.jsx)(`span`,{className:`truncate`,"data-session-title":!0,children:T}),(0,$.jsx)(B,{className:`size-4 flex-none text-content-muted`,"aria-hidden":`true`})]}),(0,$.jsxs)(`span`,{className:`flex max-w-full min-w-0 items-center gap-1 text-xs leading-4 text-content-muted`,children:[(0,$.jsx)(`span`,{className:`min-w-0 truncate font-mono`,title:m,"data-session-project":!0,children:D}),A&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,$.jsxs)(`span`,{className:Xt(`flex flex-none items-center gap-1`,(A.kind===`approval`||A.kind===`failed`)&&`font-medium text-warning-strong`),"data-session-status":A.kind,children:[(0,$.jsx)(Fn,{status:A.kind===`running`?`run`:A.kind===`stopped`?`stopped`:`attention`,className:`size-3`}),(0,$.jsx)(`span`,{className:`tabular-nums`,children:A.label})]})]})]})]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center justify-end gap-2`,children:[(0,$.jsx)(Yi,{sessionId:t.id,streaming:r,activity:f,phoneButtonClass:ra}),k>0&&v?(0,$.jsxs)(`button`,{type:`button`,"data-session-changes":k,"aria-haspopup":`dialog`,"aria-controls":v.panelId,"aria-label":h(`board:phone.changesLabel`,{count:k}),className:ra,onClick:j,children:[(0,$.jsx)(re,{className:`size-5`,strokeWidth:1.75,"aria-hidden":`true`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`absolute top-1.5 right-1 grid h-4 min-w-4 place-items-center rounded-full bg-content px-1 text-[10px] leading-none font-semibold text-panel tabular-nums`,children:k>99?`99+`:k})]}):y?.phone?(0,$.jsx)(`button`,{type:`button`,"data-phone-new-task":!0,"aria-label":h(`navigation:shell.newTask`),className:ra,onClick:y.phone.onNewTask,children:(0,$.jsx)(ht,{className:`size-5`,strokeWidth:1.75,"aria-hidden":`true`})}):null]}),(0,$.jsx)(Tn,{open:S,onOpenChange:C,children:(0,$.jsxs)(Sn,{id:w,side:`bottom`,showCloseButton:!1,"data-session-menu-sheet":!0,className:`max-h-[85dvh] gap-0 rounded-t-(--r-sheet) px-2 pt-1 pb-[calc(8px+var(--pisper-safe-area-bottom))]`,children:[(0,$.jsx)(se,{onDismiss:()=>C(!1)}),(0,$.jsx)(Cn,{className:`truncate px-3 pt-1 pb-0.5 text-base font-semibold`,children:T}),(0,$.jsx)(wn,{className:`truncate px-3 pb-2 font-mono text-xs text-content-muted`,children:E}),(0,$.jsx)(ea,{count:M.length,children:M.map(e=>{let t=e.marker?{[`data-${e.marker}`]:!0}:{};return(0,$.jsx)(ta,{icon:e.icon,label:e.shortLabel||e.label,"aria-label":e.label,onClick:()=>{C(!1),e.onSelect()},...t},e.key)})}),(0,$.jsx)(`div`,{className:`min-h-0 overflow-y-auto`,role:`list`,children:x.entries.map(e=>{let t=e.marker?{[`data-${e.marker}`]:!0}:{};return(0,$.jsxs)(`div`,{role:`listitem`,children:[e.separator&&(0,$.jsx)(`div`,{"aria-hidden":`true`,className:`mx-3 my-1 h-px bg-stroke-soft`}),(0,$.jsx)(na,{icon:e.icon,label:e.label,disabled:e.disabled,trailing:e.trailing&&(0,$.jsx)(`span`,{className:`flex-none font-mono text-sm text-content-muted tabular-nums`,title:e.trailingTitle,"data-session-context-usage":!0,children:e.trailing}),onClick:()=>{C(!1),e.onSelect()},...t})]},e.key)})})]})}),x.dialog]})}function aa({open:e,sessionId:t,cwd:n=``,onClose:r,onSelect:i,onCommandSelect:a}){let{t:o}=l(),s=k(e=>e.capabilities),c=O(s,`workflows`),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)(`all`),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)({}),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(``);(0,Q.useEffect)(()=>{if(!e)return;let r=!0;return p(`all`),h(``),_(null),y({}),x(!0),C(``),Promise.all([t?X.getSessionCommands(t):X.getWorkspaceCommands(n),c?D(`/api/workflows`):Promise.resolve({workflows:[]}),D(`/api/plugins?sessionId=${encodeURIComponent(t)}`)]).then(([e,t,n])=>{if(!r)return;let i=new Set(n.callableToolNames||[]);d([...(e.commands||[]).map(e=>({kind:e.source,id:e.name,name:e.name,description:e.description||``,inputs:[],argumentHint:e.argumentHint,invocation:e.invocation})),...(t.workflows||[]).filter(e=>e.status===`published`).map(e=>({kind:`workflow`,id:e.id,name:e.name,description:e.description||``,inputs:e.inputs||[]})),...(n.plugins||[]).flatMap(e=>(e.capabilities||[]).filter(e=>i.has(e.name)).map(t=>({kind:`tool`,id:t.name,name:t.id?Fr(t,o):String(t.label||t.name),description:t.id?Ir(t,o):t.description,inputs:[],sourceName:e.name})))])}).catch(e=>{r&&(d([]),C(e instanceof Error?e.message:String(e)))}).finally(()=>r&&x(!1)),()=>{r=!1}},[n,e,t,o,c]);let w=(0,Q.useMemo)(()=>({all:u.length,prompt:u.filter(e=>e.kind===`prompt`).length,skill:u.filter(e=>e.kind===`skill`).length,tool:u.filter(e=>e.kind===`tool`).length,workflow:u.filter(e=>e.kind===`workflow`).length}),[u]),T=(0,Q.useMemo)(()=>{let e=m.trim().toLowerCase();return u.filter(t=>(f===`all`||t.kind===f)&&(!e||`${t.name} ${t.id} ${t.description} ${t.kind===`tool`?t.sourceName:``}`.toLowerCase().includes(e)))},[f,m,u]),E=e=>{let t=e;p(t),g&&t!==`all`&&g.kind!==t&&_(null)},A=e=>{_(e),y(Object.fromEntries(e.inputs.map(e=>[e.name,e.defaultValue??``])))};return(0,$.jsx)(Jn,{open:e,onOpenChange:e=>!e&&r(),children:(0,$.jsxs)(Gn,{className:`chat-resource-dialog w-[min(820px,calc(100vw_-_32px))] h-[min(600px,calc(100dvh_-_32px))] max-w-[820px] sm:max-w-[820px] grid-rows-[auto_minmax(0,1fr)] overflow-hidden max-[650px]:w-[calc(100vw_-_16px)] max-[650px]:h-[calc(100dvh_-_16px)] z-[220] gap-0 p-0 ring-0`,overlayClassName:`z-[220]`,showCloseButton:!1,children:[(0,$.jsxs)(`div`,{className:`chat-resource-head flex items-start justify-between gap-4 border-b border-stroke-soft px-[18px] pt-4 pb-3.5 max-[650px]:p-3.5 [&_[data-slot='dialog-description']]:mt-0.5 [&_[data-slot='dialog-description']]:text-xs [&_[data-slot='dialog-description']]:text-content-muted [&_[data-slot='dialog-title']]:text-base [&_[data-slot='dialog-title']]:font-semibold`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(Kn,{children:o(`chat:resourcePicker.title`)}),(0,$.jsx)(Wn,{children:o(`chat:resourcePicker.description`)})]}),(0,$.jsx)(Y,{size:`icon-sm`,variant:`ghost`,"aria-label":o(`chat:resourcePicker.close`),onClick:r,children:(0,$.jsx)(Dt,{})})]}),(0,$.jsxs)(`div`,{className:`chat-resource-body grid min-h-0 grid-cols-[minmax(0,1.1fr)_minmax(260px,.9fr)] overflow-hidden max-[650px]:grid-cols-[1fr] max-[650px]:grid-rows-[minmax(0,1fr)_minmax(190px,auto)] max-[650px]:overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`chat-resource-browser flex min-h-0 min-w-0 flex-col border-r border-stroke-soft p-3 max-[650px]:min-h-0 max-[650px]:border-r-0 max-[650px]:border-b`,children:[(0,$.jsx)(Wt,{value:f,onValueChange:E,className:`chat-resource-tabs w-full [&_[data-slot='tabs-list']]:grid [&_[data-slot='tabs-list']]:h-9 [&_[data-slot='tabs-list']]:w-full [&_[data-slot='tabs-list']]:rounded-sm [&_[data-slot='tabs-list']]:border [&_[data-slot='tabs-list']]:border-stroke [&_[data-slot='tabs-list']]:bg-surface-muted [&_[data-slot='tabs-list']]:p-0.5 [&_[data-slot='tabs-trigger']]:min-w-0 [&_[data-slot='tabs-trigger']]:gap-1 [&_[data-slot='tabs-trigger']]:rounded-xs [&_[data-slot='tabs-trigger']]:px-1.5 [&_[data-slot='tabs-trigger']]:text-xs [&_[data-slot='tabs-trigger']]:text-content-secondary [&_[data-slot='tabs-trigger'][data-state='active']]:bg-key [&_[data-slot='tabs-trigger'][data-state='active']]:text-content [&_[data-slot='tabs-trigger'][data-state='active']]:shadow-key [&_[data-slot='tabs-trigger']_small]:text-xs [&_[data-slot='tabs-trigger']_small]:font-normal [&_[data-slot='tabs-trigger']_small]:text-content-muted [&_[data-slot='tabs-trigger']_small]:tabular-nums ${c?`[&_[data-slot='tabs-list']]:grid-cols-[repeat(5,minmax(0,1fr))]`:`[&_[data-slot='tabs-list']]:grid-cols-[repeat(4,minmax(0,1fr))]`}`,children:(0,$.jsxs)(Ut,{"aria-label":o(`chat:resourcePicker.categories`),children:[(0,$.jsxs)(Ht,{value:`all`,children:[o(`chat:resourcePicker.all`),(0,$.jsx)(`small`,{children:w.all})]}),(0,$.jsxs)(Ht,{value:`prompt`,children:[o(`chat:resourcePicker.prompt`),(0,$.jsx)(`small`,{children:w.prompt})]}),(0,$.jsxs)(Ht,{value:`skill`,children:[o(`chat:resourcePicker.skill`),(0,$.jsx)(`small`,{children:w.skill})]}),(0,$.jsxs)(Ht,{value:`tool`,children:[o(`chat:resourcePicker.tool`),(0,$.jsx)(`small`,{children:w.tool})]}),c&&(0,$.jsxs)(Ht,{value:`workflow`,children:[o(`chat:resourcePicker.workflow`),(0,$.jsx)(`small`,{children:w.workflow})]})]})}),(0,$.jsxs)(Qn,{className:`chat-resource-search mt-2`,children:[(0,$.jsx)(Zn,{children:(0,$.jsx)(ft,{"aria-hidden":`true`})}),(0,$.jsx)(Xn,{autoFocus:!0,value:m,"aria-label":o(`chat:resourcePicker.search`),onChange:e=>h(e.target.value),placeholder:o(`chat:resourcePicker.search`)})]}),(0,$.jsxs)(`div`,{className:`chat-resource-list mt-2 flex min-h-0 [flex:1_1_0] flex-col gap-px overflow-y-auto [overscroll-behavior:contain] [scrollbar-gutter:stable] [touch-action:pan-y] [&_>_button]:relative [&_>_button]:grid [&_>_button]:w-full [&_>_button]:cursor-pointer [&_>_button]:grid-cols-[28px_minmax(0,1fr)_auto] [&_>_button]:items-center [&_>_button]:gap-2 [&_>_button]:rounded-sm [&_>_button]:px-2 [&_>_button]:py-1.5 [&_>_button]:text-left [&_>_button]:text-content [&_>_button:hover]:bg-surface-hover [&_>_button.active]:bg-surface-hover [&_>_button.active]:before:absolute [&_>_button.active]:before:inset-y-1.5 [&_>_button.active]:before:left-0 [&_>_button.active]:before:w-[3px] [&_>_button.active]:before:rounded-full [&_>_button.active]:before:bg-star max-[650px]:[&_>_button]:min-h-11 [&_button_>_span:nth-child(2)]:flex [&_button_>_span:nth-child(2)]:min-w-0 [&_button_>_span:nth-child(2)]:flex-col [&_strong]:truncate [&_strong]:text-[13px] [&_strong]:font-medium [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_em]:text-xs [&_em]:whitespace-nowrap [&_em]:text-content-muted [&_em]:not-italic [&_>_p]:m-auto [&_>_p]:text-xs [&_>_p]:text-content-muted`,children:[T.map(e=>{let t=e.kind===`prompt`?ae:e.kind===`skill`?R:e.kind===`tool`?Et:Tt;return(0,$.jsxs)(`button`,{type:`button`,className:g?.kind===e.kind&&g.id===e.id?`active`:``,onClick:()=>A(e),children:[(0,$.jsx)(`span`,{className:`list-icon grid size-7 place-items-center rounded-sm bg-surface-muted text-content-secondary`,children:(0,$.jsx)(t,{size:15})}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`small`,{children:e.description})]}),(0,$.jsx)(`em`,{children:e.kind===`prompt`?o(`chat:resourcePicker.prompt`):e.kind===`skill`?`Skill`:e.kind===`tool`?o(`chat:resourcePicker.tool`):o(`chat:resourcePicker.workflow`)})]},`${e.kind}:${e.id}`)}),!T.length&&(0,$.jsx)(`p`,{children:b?o(`chat:resourcePicker.loading`):S||o(`chat:resourcePicker.empty`)})]})]}),(0,$.jsx)(`div`,{className:`chat-resource-config flex min-h-0 min-w-0 flex-col gap-4 overflow-y-auto overscroll-contain p-[18px] max-[650px]:max-h-[230px] max-[650px]:min-h-0 [&_>_div:first-child]:flex [&_>_div:first-child]:flex-col [&_>_div:first-child]:gap-1 [&_>_p]:m-auto [&_>_p]:text-xs [&_>_p]:text-content-muted [&_p]:text-xs [&_p]:text-content-muted [&_strong]:text-[15px] [&_strong]:font-medium`,children:g?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{children:g.name}),(0,$.jsx)(`p`,{children:g.description||o(`chat:resourcePicker.noDescription`)})]}),g.kind===`workflow`&&g.inputs.length>0&&(0,$.jsx)(`div`,{className:`chat-resource-inputs flex flex-col gap-3 [&_label]:grid [&_label]:gap-1.5 [&_label]:text-xs [&_label]:font-medium [&_label]:text-content-secondary`,children:g.inputs.map(e=>(0,$.jsxs)(`label`,{children:[(0,$.jsxs)(`span`,{children:[e.label,e.required?` *`:``]}),e.type===`boolean`?(0,$.jsx)(kt,{checked:!!v[e.name],onCheckedChange:t=>y(n=>({...n,[e.name]:t===!0}))}):(0,$.jsx)(Yn,{type:e.type===`number`?`number`:`text`,required:e.required,value:String(v[e.name]??``),onChange:t=>y(n=>({...n,[e.name]:t.target.value}))})]},e.id))}),g.kind===`prompt`&&g.argumentHint&&(0,$.jsx)(`code`,{className:`w-fit max-w-full rounded-xs bg-inline-code px-1.5 py-1 font-mono text-xs [overflow-wrap:anywhere] text-content-secondary`,children:g.argumentHint}),(0,$.jsx)(Y,{className:`chat-resource-confirm min-h-8 min-w-[112px] self-start bg-star text-[var(--on-accent)] hover:bg-star-hover max-[650px]:min-h-11`,onClick:()=>{if(g){if(g.kind===`prompt`){a(g.invocation||`/${g.name}`),r();return}i({kind:g.kind,resourceId:g.id,resourceName:g.name,arguments:g.kind===`workflow`?v:void 0,behavior:g.kind===`workflow`?`background`:`foreground`}),r()}},children:g.kind===`prompt`?o(`chat:resourcePicker.insertPrompt`):o(`chat:resourcePicker.useResource`)})]}):(0,$.jsx)(`p`,{children:o(`chat:resourcePicker.chooseResource`)})})]})]})})}function oa(e){if(e.style.height=`auto`,!e.scrollHeight){e.style.height=``;return}e.style.height=`${Math.min(e.scrollHeight,220)}px`}function sa(e){let t=e.getHours();return t>=5&&t<11?`morning`:t>=11&&t<13?`noon`:t>=13&&t<18?`afternoon`:t>=18&&t<23?`evening`:`lateNight`}function ca(e){let t=new Date(e);return t.setHours(e.getHours()+1,0,0,0),Math.max(1e3,t.getTime()-e.getTime())}function la(){let{t:e}=l(),[t,n]=(0,Q.useState)(()=>new Date);(0,Q.useEffect)(()=>{let e=window.setTimeout(()=>n(new Date),ca(t));return()=>window.clearTimeout(e)},[t]);let r=sa(t),i=e(r===`morning`?`chat:newTask.greetingMorning`:r===`noon`?`chat:newTask.greetingNoon`:r===`afternoon`?`chat:newTask.greetingAfternoon`:r===`evening`?`chat:newTask.greetingEvening`:`chat:newTask.greetingLateNight`);return(0,$.jsxs)(`div`,{className:`grid min-h-full content-center justify-items-center gap-2 text-center max-[650px]:gap-3`,"data-new-task-greeting":!0,children:[(0,$.jsx)(ur,{size:32}),(0,$.jsx)(`h2`,{className:`text-2xl! font-semibold tracking-[-.01em] text-balance text-content max-[650px]:text-xl!`,children:i}),(0,$.jsx)(`p`,{className:`max-w-[46ch] text-sm leading-6 text-content-muted max-[650px]:hidden`,children:e(`board:home.draftHint`)})]})}function ua({phone:e,leading:t,project:n}){let{t:r}=l();return e?(0,$.jsxs)(`header`,{"data-session-header":`draft`,"data-focus-region":`header`,className:`grid h-14 min-w-0 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center bg-panel px-3`,children:[(0,$.jsx)(`div`,{className:`flex min-w-0 items-center`,children:t}),(0,$.jsxs)(`div`,{className:`flex max-w-[min(58vw,260px)] min-w-0 flex-col items-center justify-center`,children:[(0,$.jsx)(`h1`,{className:`max-w-full truncate px-1.5 text-base leading-5 font-semibold text-content`,children:r(`board:home.draftTitle`)}),n]}),(0,$.jsx)(`span`,{"aria-hidden":`true`})]}):(0,$.jsxs)(`header`,{"data-session-header":`draft`,"data-focus-region":`header`,"data-window-drag-region":!0,className:`flex h-[52px] min-w-0 shrink-0 items-center gap-2 border-b border-stroke-soft pr-2 pl-4 [[data-custom-titlebar]_&]:pr-[144px]`,children:[t,(0,$.jsx)(`h1`,{className:`flex-none text-[15px] leading-6 font-semibold text-content`,children:r(`board:home.draftTitle`)}),(0,$.jsx)(`span`,{className:`min-w-0 truncate text-xs text-content-muted`,children:r(`board:home.draftSubtitle`)})]})}var da=1e3;function fa({option:e,selected:t,disabled:n,onSelect:r}){let i=e.icon;return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":t,disabled:n,className:`grid min-h-12 w-full cursor-pointer grid-cols-[16px_minmax(0,1fr)_16px] items-center gap-2.5 rounded-sm px-2 py-1.5 text-left text-content hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus disabled:cursor-default disabled:opacity-50 disabled:hover:bg-transparent max-[650px]:min-h-14`,"data-mode-option":e.value,onClick:()=>r(e.value),children:[(0,$.jsx)(i,{size:16,strokeWidth:1.75,className:`text-content-secondary`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-px`,children:[(0,$.jsx)(`span`,{className:Xt(`text-[13px] max-[650px]:text-[15px]`,t&&`font-medium`),children:e.label}),(0,$.jsx)(`small`,{className:`text-xs leading-normal text-content-muted max-[650px]:text-[13px]`,children:e.description})]}),t?(0,$.jsx)(z,{size:15,strokeWidth:2.25,"aria-hidden":`true`}):(0,$.jsx)(`span`,{})]})}function pa({approvalMode:e,onApprovalModeChange:t,approvalDisabled:n=!1,runMode:r,onRunModeChange:i,runModeDisabled:a=!1,goalsAvailable:o,teamAvailable:s,goal:c,tokenBudget:u,onTokenBudgetChange:d,onSaveTokenBudget:f,sheet:p=!1,collapse:m=!1,open:h,onOpenChange:g}){let{t:_}=l(),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(!1),S=h??b,C=e=>{h===void 0&&x(e),g?.(e)},w=[{value:`approval-required`,label:_(`chat:focusSession.approvalRequired`),description:_(`chat:focusSession.approvalRequiredShowsADiffBeforeWriting`),icon:ei},{value:`workspace-write`,label:_(`chat:focusSession.workspaceWrite`),description:_(`chat:focusSession.workspaceWriteRunsCommandsWithAutomaticApproval`),icon:Qr},{value:`full-access`,label:_(`chat:focusSession.fullAccess`),description:_(`chat:focusSession.fullAccessRunsShellWithoutPerCommandApproval`),icon:mt}],T=[{value:`plan`,label:_(`board:composer.planShort`),description:_(`chat:focusSession.planModeDescription`),icon:rt},...o?[{value:`goal`,label:_(`board:composer.goalShort`),description:_(`chat:focusSession.goalModeDescription`),icon:vt}]:[],...o&&s?[{value:`team`,label:_(`board:composer.teamShort`),description:_(`chat:focusSession.teamModeDescription`),icon:wt}]:[]],E=w.find(t=>t.value===e)||w[0],D=c?.status===`active`?c?.mode===`team`&&s?`team`:`goal`:r,O=T.find(e=>e.value===D)||T[0],k=O.value!==`plan`,A=E.value===`full-access`?mt:ai,j=O.value===`team`?_(`board:composer.teamShort`):O.value===`goal`?_(`board:composer.goalShort`):``,M=j?`${j} · ${E.label}`:E.label,N=O.value===`plan`&&E.value===`approval-required`,P=!!c?.id,F=D===`team`?c?.teamTokenBudget:c?.tokenBudget,I=F==null?null:Number(F)>0?Number(F):null,L=u!==I,R=P?I==null?_(`chat:focusSession.usedUnlimitedGoalTokens`,{used:Nn(c?.tokensUsed)}):_(`chat:focusSession.usedBudgetTokensUsed`,{used:c?.tokensUsed||0,budget:I||0}):``,V=`${_(`board:composer.modeChip`)} · ${M}`,H=_(D===`team`?`chat:focusSession.teamTokenBudget`:`chat:focusSession.goalTokenBudget`),U=async()=>{if(!(v||!L||!P||!f)){y(!0);try{await f(u)}finally{y(!1)}}};return(0,$.jsxs)(pe,{sheet:p,title:_(`board:composer.modeChip`),open:S,onOpenChange:C,align:`start`,side:`top`,className:`composer-mode-popover w-[300px] max-w-[calc(100vw_-_24px)] gap-1 p-1`,trigger:(0,$.jsxs)(`button`,{type:`button`,className:Xt(q,`composer-mode-chip max-w-[220px] max-[650px]:min-w-9 max-[650px]:justify-center max-[650px]:gap-1`,k?`max-[650px]:px-2.5`:`max-[650px]:px-0`),"aria-label":V,title:V,hidden:m&&!k&&E.value!==`full-access`,"data-composer-mode":`${O.value}:${E.value}`,children:[k&&(0,$.jsx)(O.icon,{size:16,className:`hidden shrink-0 max-[650px]:block`,"aria-hidden":`true`}),(0,$.jsx)(A,{size:14,className:`shrink-0 max-[650px]:size-4`,"aria-hidden":`true`}),!N&&(0,$.jsx)(`span`,{className:`min-w-0 truncate max-[650px]:hidden`,children:M}),(0,$.jsx)(B,{size:14,className:`shrink-0 opacity-70 max-[650px]:hidden`,"aria-hidden":`true`})]}),children:[(0,$.jsxs)(`div`,{role:`radiogroup`,"aria-label":_(`chat:focusSession.approvalMode`),className:`flex flex-col gap-0.5`,children:[(0,$.jsx)(`div`,{className:`px-2 pt-1.5 pb-1 text-xs font-medium text-content-muted`,children:_(`chat:focusSession.approvalMode`)}),w.map(e=>(0,$.jsx)(fa,{option:e,selected:e.value===E.value,disabled:n,onSelect:e=>{C(!1),t(e)}},e.value))]}),T.length>1&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{role:`separator`,className:`mx-1 h-px bg-stroke-soft`}),(0,$.jsxs)(`div`,{className:`grid gap-1.5 px-2 pt-1.5 pb-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex min-h-7 items-center justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-1.5 text-xs font-medium text-content-muted`,children:[_(`chat:focusSession.executionMode`),(0,$.jsx)($t,{className:`font-normal max-[650px]:hidden pointer-coarse:hidden`,children:`⇧Tab`})]}),(0,$.jsx)(Kt,{size:`sm`,"aria-label":_(`chat:focusSession.executionMode`),value:D,disabled:a,options:T.map(({value:e,label:t})=>({value:e,label:t})),onValueChange:i})]}),(0,$.jsx)(`p`,{className:`text-xs leading-normal text-content-muted max-[650px]:text-[13px]`,children:O.description})]}),(k||P)&&(0,$.jsxs)(`div`,{className:`grid gap-1 px-2 pt-1 pb-1.5 text-xs`,children:[R&&(0,$.jsx)(`p`,{className:`text-content-muted tabular-nums`,children:R}),(0,$.jsxs)(`div`,{className:`grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1.5`,children:[(0,$.jsx)(`label`,{htmlFor:`goal-token-budget-input`,className:`font-medium text-content-secondary`,children:H}),(0,$.jsx)(Yn,{id:`goal-token-budget-input`,type:`number`,min:da,step:1e3,value:u??``,placeholder:_(`chat:focusSession.goalTokenBudgetUnlimited`),"aria-label":H,disabled:v,className:`text-[13px] tabular-nums`,onChange:e=>{let t=e.target.value.trim();if(!t){d(null);return}let n=Number(t);Number.isFinite(n)&&d(Math.max(da,Math.round(n)))}}),P&&L?(0,$.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v,onClick:()=>void U(),children:[v?(0,$.jsx)(dt,{className:`animate-spin`,size:12}):(0,$.jsx)(z,{size:12}),_(`chat:focusSession.goalBudgetSave`)]}):(0,$.jsx)(`span`,{})]}),(0,$.jsx)(`small`,{className:`text-content-muted`,children:_(D===`team`?`chat:focusSession.teamTokenBudgetHint`:P?`chat:focusSession.goalTokenBudgetUpdateHint`:`chat:focusSession.goalTokenBudgetHint`)})]})]})]})}function ma({trigger:e,open:t,onOpenChange:n,onAttachment:r,onResource:i,onVisual:a,steer:o,mode:s}){let{t:c}=l(),u=e=>{n(!1),window.setTimeout(e,0)};return(0,$.jsxs)(pe,{sheet:!0,title:c(`board:composer.plusSheetTitle`),open:t,onOpenChange:n,trigger:e,sheetClassName:`px-2`,children:[(0,$.jsxs)(ea,{count:a?3:2,children:[(0,$.jsx)(ta,{icon:st,label:c(`board:composer.attachmentShort`),"data-composer-plus-item":`attachment`,onClick:()=>{n(!1),r()}}),(0,$.jsx)(ta,{icon:R,label:c(`chat:resourcePicker.open`),"data-composer-plus-item":`resource`,onClick:()=>u(i)}),a&&(0,$.jsx)(ta,{icon:ee,label:c(`chat:focusSession.generateImage`),"data-composer-plus-item":`visual`,onClick:()=>u(a)})]}),o&&(0,$.jsx)(na,{icon:te,label:c(`board:composer.steerNow`),hint:c(`board:composer.steerHint`),disabled:o.disabled,"data-composer-steer":!0,onClick:()=>u(o.onSelect)}),s&&(0,$.jsx)(na,{icon:ai,label:c(`board:composer.modeChip`),"data-composer-plus-item":`mode`,trailing:(0,$.jsxs)(`span`,{className:`flex flex-none items-center gap-1 text-sm text-content-muted`,children:[s.valueLabel,(0,$.jsx)(H,{className:`size-4`,"aria-hidden":`true`})]}),onClick:()=>u(s.onOpen)})]})}function ha(e,t){let n=[`plan`];return t.goalsAvailable&&n.push(`goal`),t.goalsAvailable&&t.teamAvailable&&n.push(`team`),n.length<2?null:n[(n.indexOf(e)+1)%n.length]??`plan`}function ga({state:e,cwd:t,onDismiss:n}){let{t:r}=l(),i=e.status===`streaming`;return(0,$.jsxs)(`section`,{"aria-label":r(`chat:sideQuestion.label`),"aria-busy":i,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),n())},className:`flex max-h-[min(45vh,420px)] min-w-0 flex-col rounded-lg border border-stroke bg-panel shadow-float`,children:[(0,$.jsxs)(`header`,{className:`flex min-w-0 items-start gap-2 border-b border-stroke-soft px-3 py-2`,children:[(0,$.jsx)(ni,{size:15,"aria-hidden":`true`,className:`mt-0.5 shrink-0 text-content-muted`}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,$.jsx)(`span`,{className:`text-xs text-content-muted`,children:r(`chat:sideQuestion.label`)}),(0,$.jsx)(`p`,{className:`m-0 line-clamp-2 text-[13px] text-content`,title:e.question,children:e.question})]}),(0,$.jsx)(Y,{variant:`ghost`,size:`icon-xs`,className:`shrink-0 pointer-coarse:size-11`,"aria-label":r(`chat:sideQuestion.close`),title:r(`chat:sideQuestion.close`),onClick:n,children:(0,$.jsx)(Dt,{})})]}),(0,$.jsxs)(`div`,{className:`min-h-0 overflow-y-auto overscroll-contain px-3 py-2 text-[13px]`,children:[e.answer?(0,$.jsx)(or,{cwd:t,streaming:i,children:e.answer}):i?(0,$.jsxs)(`p`,{role:`status`,className:`m-0 flex items-center gap-2 text-content-muted`,children:[(0,$.jsx)(Zt,{className:`size-4`}),r(`chat:sideQuestion.answering`)]}):e.status===`done`?(0,$.jsx)(`p`,{className:`m-0 text-content-muted`,children:e.toolCallIgnored?r(`chat:sideQuestion.toolIgnored`):r(`chat:sideQuestion.empty`)}):null,e.status===`error`&&(0,$.jsx)(`p`,{role:`alert`,className:`m-0 mt-1 text-[var(--danger)]`,children:r(`chat:sideQuestion.failed`,{error:e.error})})]}),(0,$.jsx)(`footer`,{className:`border-t border-stroke-soft px-3 py-1.5 text-xs text-content-muted`,children:r(`chat:sideQuestion.note`)})]})}function _a(e){let[t,n]=(0,Q.useState)(null),r=(0,Q.useRef)(null),i=(0,Q.useCallback)(()=>{r.current?.abort(),r.current=null},[]),a=(0,Q.useCallback)(()=>{i(),n(null)},[i]);return(0,Q.useEffect)(()=>a,[e,a]),{state:t,ask:(0,Q.useCallback)(t=>{i();let a=new AbortController;r.current=a;let o=()=>r.current===a;n({question:t,answer:``,status:`streaming`,error:``,toolCallIgnored:!1}),X.askSideQuestion(e,t,{signal:a.signal,onDelta:e=>{o()&&n(t=>t&&{...t,answer:t.answer+e})}}).then(e=>{o()&&(r.current=null,n(t=>t&&{...t,answer:e.text||t.answer,status:`done`,toolCallIgnored:e.toolCallIgnored}))}).catch(e=>{o()&&(r.current=null,n(t=>t&&{...t,status:`error`,error:e instanceof Error?e.message:String(e)}))})},[i,e]),dismiss:a}}var va=new Set([`user`,`assistant`,`summary`,`compaction`,`position`]);function ya(e,t,n){return t===`labeled`?!!e.label:t===`branches`?n||va.has(e.kind):!1}var ba=new Set([`tool`,`tool-call`]);function xa(e){let t=[],n=new Map;for(let r of e){let e=r.parentId?n.get(r.parentId):void 0,i={...r,children:[]};n.set(r.id,i),e?e.children.push(i):t.push(i)}return t}function Sa(e){let t=[],n=[...e].reverse();for(;n.length>0;){let e=n.pop();if(e){t.push(e);for(let t=e.children.length-1;t>=0;--t)n.push(e.children[t])}}return t}function Ca(e,t){let n=[],r=new Map;for(let i of Sa(e)){let e=i.parentId&&r.get(i.parentId)||null;if(!t(i)){r.set(i.id,e);continue}let a={...i,children:[]};r.set(i.id,a),e?e.children.push(a):n.push(a)}return n}function wa(e){let t=[e],n=e;for(;n.children.length===1;)n=n.children[0],t.push(n);let r={id:e.id,nodes:t,children:[],active:t.some(e=>e.active)},i=[{segment:r,children:n.children}];for(;i.length>0;){let e=i.pop();if(e)for(let t of e.children){let n=[t],r=t;for(;r.children.length===1;)r=r.children[0],n.push(r);let a={id:t.id,nodes:n,children:[],active:n.some(e=>e.active)};e.segment.children.push(a),i.push({segment:a,children:r.children})}}return r}function Ta(e){return e.kind===`user`?Ve:e.kind===`assistant`?L:e.kind===`tool`||e.kind===`tool-call`?Et:e.kind===`settings`?pt:e.kind===`label`?_t:e.kind===`summary`||e.kind===`compaction`?ae:e.kind===`position`?We:e.label?$r:at}function Ea({nodes:e,viewportRef:t,selectedId:n,typeLabel:r,stateLabel:i,onSelect:a}){let o=sr({count:e.length,getScrollElement:()=>t.current,estimateSize:()=>64,getItemKey:t=>e[t]?.id??`mobile-tree-node-${t}`,overscan:12,useAnimationFrameWithResizeObserver:!0});return(0,Q.useEffect)(()=>{if(!n)return;let t=e.findIndex(e=>e.id===n);t>=0&&o.scrollToIndex(t,{align:`center`})},[e,n,o]),(0,$.jsx)(`div`,{className:`relative w-full`,style:{height:`${o.getTotalSize()}px`},children:o.getVirtualItems().map(t=>{let o=e[t.index],s=Ta(o);return(0,$.jsx)(`div`,{className:`absolute top-0 left-0 w-full px-3 py-1`,style:{transform:`translateY(${t.start}px)`},children:(0,$.jsxs)(`button`,{type:`button`,className:`session-tree-node relative grid items-center gap-2 rounded-sm border border-stroke bg-panel text-left text-content transition-colors duration-(--d-fast) hover:bg-surface-subtle [&.selected]:border-key-border [&.selected]:bg-key [&.selected]:shadow-key [&.selected]:before:absolute [&.selected]:before:inset-y-2 [&.selected]:before:-left-px [&.selected]:before:w-[3px] [&.selected]:before:rounded-r-[3px] [&.selected]:before:bg-star min-h-14 w-full grid-cols-[34px_minmax(0,1fr)_auto] py-2 pr-2.5 pl-1 ${o.id===n?` selected`:``}${o.active?` active`:``}${o.leaf?` leaf`:``}`,"data-kind":o.kind,"data-pisper-tree-entry":o.id,onClick:()=>a(o.id),children:[(0,$.jsx)(`span`,{className:`session-tree-marker relative z-[2] grid size-6 place-items-center justify-self-center rounded-sm bg-surface-muted text-content-secondary [.session-tree-node[data-kind='tool']_&]:bg-warning-soft [.session-tree-node[data-kind='tool']_&]:text-warning-strong [.session-tree-node.leaf_&]:bg-star [.session-tree-node.leaf_&]:text-on-accent [.session-tree-mark.active_&]:bg-star-soft [.session-tree-mark.active_&]:text-star-strong`,children:(0,$.jsx)(s,{size:14})}),(0,$.jsxs)(`span`,{className:`session-tree-node-copy flex min-w-0 flex-col gap-0.5 [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_strong]:truncate [&_strong]:text-sm [&_strong]:font-medium`,children:[(0,$.jsx)(`strong`,{children:o.label||o.text||r(o)}),(0,$.jsx)(`small`,{children:o.label&&o.text?o.text:r(o)})]}),(0,$.jsxs)(`span`,{className:`session-tree-node-state inline-flex min-w-0 shrink-0 items-center gap-1 text-xs text-content-muted [.session-tree-node.leaf_&]:text-accent-fg`,children:[o.label&&(0,$.jsx)($r,{size:12}),i(o)]})]})},t.key)})})}function Da({segment:e,viewportRef:t,selectedId:n,typeLabel:r,stateLabel:i,onSelect:a}){let{nodes:o,children:s}=e,c=o.length>120,l=sr({count:o.length,getScrollElement:()=>t.current,estimateSize:()=>56,getItemKey:e=>o[e]?.id??`tree-node-${e}`,overscan:12,scrollMargin:26,enabled:c,useAnimationFrameWithResizeObserver:!0}),u=e=>{let t=Ta(e);return(0,$.jsxs)(`button`,{type:`button`,className:`session-tree-node relative grid items-center gap-2 rounded-sm border border-stroke bg-panel text-left text-content transition-colors duration-(--d-fast) hover:bg-surface-subtle [&.selected]:border-key-border [&.selected]:bg-key [&.selected]:shadow-key [&.selected]:before:absolute [&.selected]:before:inset-y-2 [&.selected]:before:-left-px [&.selected]:before:w-[3px] [&.selected]:before:rounded-r-[3px] [&.selected]:before:bg-star z-[1] min-h-12 w-[220px] cursor-pointer grid-cols-[30px_minmax(0,1fr)_auto] py-1.5 pr-2 pl-0.5 ${e.id===n?` selected`:``}${e.active?` active`:``}${e.leaf?` leaf`:``}`,"data-kind":e.kind,"data-pisper-tree-entry":e.id,onClick:()=>a(e.id),children:[(0,$.jsx)(`span`,{className:`session-tree-marker relative z-[2] grid size-6 place-items-center justify-self-center rounded-sm bg-surface-muted text-content-secondary [.session-tree-node[data-kind='tool']_&]:bg-warning-soft [.session-tree-node[data-kind='tool']_&]:text-warning-strong [.session-tree-node.leaf_&]:bg-star [.session-tree-node.leaf_&]:text-on-accent [.session-tree-mark.active_&]:bg-star-soft [.session-tree-mark.active_&]:text-star-strong`,children:(0,$.jsx)(t,{size:14})}),(0,$.jsxs)(`span`,{className:`session-tree-node-copy flex min-w-0 flex-col gap-0.5 [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_strong]:truncate [&_strong]:text-sm [&_strong]:font-medium`,children:[(0,$.jsx)(`strong`,{children:e.label||e.text||r(e)}),(0,$.jsx)(`small`,{children:e.label&&e.text?e.text:r(e)})]}),(0,$.jsxs)(`span`,{className:`session-tree-node-state inline-flex min-w-0 shrink-0 items-center gap-1 text-xs text-content-muted [.session-tree-node.leaf_&]:text-accent-fg`,children:[e.label&&(0,$.jsx)($r,{size:12}),i(e)]})]},e.id)};return(0,Q.useEffect)(()=>{if(!c||!n)return;let e=o.findIndex(e=>e.id===n);e<0||l.scrollToIndex(e,{align:`center`})},[n,o,c,l]),(0,$.jsxs)(`div`,{className:`session-tree-segment relative flex min-w-[220px] flex-col items-center ${e.active?` active`:``}`,children:[(0,$.jsx)(`div`,{className:`session-tree-track relative z-[1] grid w-[220px] gap-2 before:absolute before:top-[22px] before:bottom-[22px] before:left-1/2 before:z-0 before:w-px before:bg-stroke-strong [.session-tree-segment.active_>_&::before]:bg-control`,children:c?(0,$.jsx)(`div`,{className:`relative w-[220px]`,style:{height:`${l.getTotalSize()}px`},children:l.getVirtualItems().map(e=>(0,$.jsx)(`div`,{className:`absolute top-0 left-0 w-[220px]`,style:{top:`${e.start-26}px`},children:u(o[e.index])},e.key))}):o.map(u)}),s.length>0&&(0,$.jsx)(`div`,{className:`session-tree-children relative flex items-start justify-center pt-7 before:absolute before:top-0 before:left-1/2 before:h-3.5 before:w-px before:bg-stroke-strong [.session-tree-segment.active_>_&::before]:bg-control`,children:s.map(e=>(0,$.jsx)(`div`,{className:`session-tree-child relative flex px-3 pt-3.5 before:absolute before:top-0 before:right-1/2 before:h-3.5 before:w-1/2 before:border-t before:border-stroke-strong after:absolute after:top-0 after:left-1/2 after:h-3.5 after:w-1/2 after:border-t after:border-l after:border-stroke-strong [&:first-child::before]:border-t-transparent [&:last-child::after]:border-t-transparent [&.active]:before:border-control [&.active]:after:border-control [&.active:first-child::before]:border-t-transparent [&.active:last-child::after]:border-t-transparent${e.active?` active`:``}`,children:(0,$.jsx)(Da,{segment:e,viewportRef:t,selectedId:n,typeLabel:r,stateLabel:i,onSelect:a})},e.id))})]})}function Oa({view:e,onViewChange:t,showAllEntries:n,onShowAllEntriesChange:r,query:i,onQueryChange:a,loading:o,error:s,mobileLayout:c,viewportRef:u,segments:d,visibleNodes:f,selectedId:p,typeLabel:m,stateLabel:h,onSelect:g,visibleMarks:_,marksLoading:v,openingMark:y,onOpenMark:b,confirmingMark:x,onConfirmMark:S,onCancelMark:C}){let{t:w,language:T}=l(),E=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{x&&E.current?.focus()},[x]);let D=e=>{let t=Date.parse(e);return Number.isFinite(t)?new Intl.DateTimeFormat(T,{dateStyle:`medium`,timeStyle:`short`}).format(t):w(`navigation:appOverlays.unknownTime`)};return(0,$.jsxs)(`div`,{className:`chat-resource-browser flex min-h-0 min-w-0 flex-col bg-transparent session-tree-browser`,children:[(0,$.jsx)(Wt,{className:`chat-resource-tabs session-tree-tabs px-3 pt-3`,value:e,onValueChange:e=>t(e),children:(0,$.jsxs)(Ut,{children:[(0,$.jsx)(Ht,{value:`branches`,children:w(`chat:sessionTree.branches`)}),(0,$.jsx)(Ht,{value:`labeled`,children:w(`chat:sessionTree.labeled`)}),(0,$.jsx)(Ht,{value:`marks`,children:w(`chat:sessionTree.allMarks`)})]})}),(0,$.jsxs)(Qn,{className:`chat-resource-search mx-3 mt-2 w-auto flex-none`,children:[(0,$.jsx)(Zn,{children:(0,$.jsx)(ft,{"aria-hidden":`true`})}),(0,$.jsx)(Xn,{value:i,disabled:!!y,"aria-label":w(`chat:sessionTree.searchPlaceholder`),onChange:e=>a(e.target.value),placeholder:w(`chat:sessionTree.searchPlaceholder`)})]}),e===`branches`&&(0,$.jsxs)(`label`,{className:`mx-3 mt-2 flex min-h-6 flex-none cursor-pointer items-center gap-2 text-xs text-content-secondary max-[650px]:min-h-11`,children:[(0,$.jsx)(kt,{checked:n,onCheckedChange:e=>r(e===!0),"data-session-tree-all-entries":!0}),w(`chat:sessionTree.showAllEntries`)]}),e===`marks`?(0,$.jsxs)(`div`,{className:`flex min-h-0 min-w-0 flex-1 basis-0 flex-col gap-2 overflow-auto overscroll-contain px-3.5 py-3`,"data-testid":`session-tree-marks-list`,children:[s&&(0,$.jsx)(`p`,{role:`alert`,className:`mx-0.5 text-xs text-danger`,children:s}),v?(0,$.jsx)(`p`,{className:`grid min-h-[180px] place-items-center text-xs text-content-muted`,children:w(`chat:sessionTree.loadingMarks`)}):_.length?_.map(e=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-tree-mark grid cursor-pointer grid-cols-[30px_minmax(0,1fr)_auto] items-center gap-2 rounded-sm border border-stroke bg-panel py-2 pr-2.5 pl-1 text-left text-content transition-colors duration-(--d-fast) hover:bg-surface-subtle [&.active]:border-star-border [&_>_em]:rounded-xs [&_>_em]:bg-star-soft [&_>_em]:px-1.5 [&_>_em]:py-0.5 [&_>_em]:text-xs [&_>_em]:text-star-strong [&_>_em]:not-italic ${e.active?` active`:``}`,"aria-expanded":e.active?void 0:x===e,"data-session-tree-mark":e.active?`active`:`other-branch`,disabled:!!y,"aria-busy":y===e,onClick:()=>b(e),children:[(0,$.jsx)(`span`,{className:`session-tree-marker relative z-[2] grid size-6 place-items-center justify-self-center rounded-sm bg-surface-muted text-content-secondary [.session-tree-node[data-kind='tool']_&]:bg-warning-soft [.session-tree-node[data-kind='tool']_&]:text-warning-strong [.session-tree-node.leaf_&]:bg-star [.session-tree-node.leaf_&]:text-on-accent [.session-tree-mark.active_&]:bg-star-soft [.session-tree-mark.active_&]:text-star-strong`,children:y===e?(0,$.jsx)(Zt,{className:`size-3.5`}):(0,$.jsx)(_t,{size:14})}),(0,$.jsxs)(`span`,{className:`session-tree-node-copy flex min-w-0 flex-col gap-0.5 [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_strong]:truncate [&_strong]:text-sm [&_strong]:font-medium`,children:[(0,$.jsx)(`strong`,{children:e.label}),(0,$.jsx)(`small`,{children:e.sessionName||w(`navigation:appOverlays.untitledChat`)}),(0,$.jsx)(`small`,{children:w(`chat:sessionTree.markTimes`,{sessionTime:D(e.sessionModified),nodeTime:D(e.nodeTimestamp)})})]}),y===e?(0,$.jsx)(`em`,{children:w(`chat:sessionTree.navigating`)}):e.active&&(0,$.jsx)(`em`,{children:w(`chat:sessionTree.markActive`)})]}),x===e&&(0,$.jsxs)(`div`,{role:`group`,"aria-label":w(`chat:sessionTree.otherBranchTitle`),className:`-mt-1 grid gap-2 rounded-sm border border-stroke bg-surface-subtle p-2.5 text-xs text-content-secondary`,"data-session-tree-mark-confirm":!0,children:[(0,$.jsxs)(`p`,{className:`flex items-start gap-1.5 text-content`,children:[(0,$.jsx)(et,{size:13,className:`mt-0.5 flex-none`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{className:`font-medium`,children:w(`chat:sessionTree.otherBranchTitle`)}),(0,$.jsx)(`span`,{className:`block text-content-muted`,children:w(`chat:sessionTree.otherBranchMessage`)})]})]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,className:`max-[650px]:h-11`,onClick:C,children:w(`common:ui.cancel`)}),(0,$.jsx)(Y,{ref:E,type:`button`,size:`sm`,className:`max-[650px]:h-11`,onClick:()=>S(e),children:w(`chat:sessionTree.switchBranch`)})]})]})]},`${e.sessionId}:${e.entryId}`)):(0,$.jsx)(`p`,{className:`grid min-h-[180px] place-items-center text-xs text-content-muted`,children:w(`chat:sessionTree.noMarksYet`)})]}):(0,$.jsx)(`div`,{className:`min-h-0 min-w-0 flex-1 basis-0 overflow-auto overscroll-contain [scrollbar-gutter:stable]`,"data-testid":`session-tree-list`,ref:u,children:d.length>0?c?(0,$.jsx)(Ea,{nodes:f,viewportRef:u,selectedId:p,typeLabel:m,stateLabel:h,onSelect:g}):(0,$.jsx)(`div`,{className:`session-tree-canvas flex w-max min-w-full items-start justify-center gap-9 px-7 pt-6.5 pb-12`,children:d.map(e=>(0,$.jsx)(Da,{segment:e,viewportRef:u,selectedId:p,typeLabel:m,stateLabel:h,onSelect:g},e.id))}):(0,$.jsx)(`p`,{className:`grid min-h-[180px] place-items-center text-xs text-content-muted`,children:o?w(`chat:sessionTree.loading`):s||w(`chat:sessionTree.empty`)})})]})}function ka({label:e,onClick:t}){return(0,$.jsxs)(Y,{variant:`secondary`,className:`w-full min-w-0`,title:e,onClick:t,children:[(0,$.jsx)(at,{size:13}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:e})]})}function Aa({mobileLayout:e,selected:t,loading:n,error:r,streaming:i,dataStreaming:a,parentSession:o,parentEntryId:s,childSessions:c,canLabel:u,canDerive:d,label:f,summarize:p,savingLabel:m,creatingChild:h,navigating:g,typeLabel:_,stateLabel:v,onBackToList:y,onLabelChange:b,onSummarizeChange:x,onSaveLabel:S,onRemoveLabel:C,onCreateChild:w,onNavigate:T,onRefresh:E,onOpenRelated:D}){let{t:O,language:k}=l();return(0,$.jsxs)(`div`,{className:`chat-resource-config session-tree-inspector flex min-h-0 min-w-0 flex-col gap-4 overflow-y-auto overscroll-contain bg-panel p-[18px] [&_>_p]:m-auto [&_>_p]:text-xs [&_>_p]:text-content-muted [&_p]:text-xs [&_p]:text-content-muted [&_strong]:text-[15px] [&_strong]:font-medium ${e?``:`border-l border-stroke-soft`}`,children:[e&&(0,$.jsx)(`div`,{className:`sticky top-0 z-[2] -mx-1.5 -mt-2 flex border-b border-stroke-soft bg-panel px-0.5 pb-2`,children:(0,$.jsxs)(Y,{variant:`ghost`,className:`min-h-11 justify-start px-2`,onClick:y,children:[(0,$.jsx)(V,{size:17}),O(`chat:sessionTree.backToNodes`)]})}),t?(0,$.jsxs)($.Fragment,{children:[(o||c.length>0)&&(0,$.jsxs)(`div`,{className:`session-tree-lineage flex flex-col gap-1.5 border-b border-stroke-soft pb-3 [&_>_strong]:text-xs [&_>_strong]:font-medium [&_>_strong]:text-content-muted [&_button]:justify-start [&_button]:text-left [&_button]:text-xs`,children:[(0,$.jsx)(`strong`,{children:O(`chat:sessionTree.conversationLineage`)}),o&&(0,$.jsx)(ka,{label:O(`chat:sessionTree.returnToOriginalChat`,{name:o.name||O(`chat:chatPage.newChat`)}),onClick:()=>D(o,s)}),c.map(e=>(0,$.jsx)(ka,{label:O(`chat:sessionTree.openSeparateChat`,{name:e.name||O(`chat:chatPage.newChat`)}),onClick:()=>D(e)},e.id))]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`span`,{className:`session-tree-selection-kind mb-1 flex items-center justify-between gap-2 text-xs text-content-muted [&_em]:rounded-xs [&_em]:border [&_em]:border-star-border [&_em]:bg-star-soft [&_em]:px-1.5 [&_em]:py-0.5 [&_em]:font-medium [&_em]:text-star-strong [&_em]:not-italic`,children:[_(t),v(t)&&(0,$.jsx)(`em`,{children:v(t)})]}),(0,$.jsx)(`strong`,{children:t.label||_(t)}),(0,$.jsx)(`p`,{children:t.text||O(`chat:sessionTree.noPreview`)})]}),(0,$.jsxs)(`div`,{className:`chat-resource-inputs flex flex-col gap-3 [&_label]:grid [&_label]:gap-1.5 [&_label]:text-xs [&_label]:font-medium [&_label]:text-content-secondary`,children:[u&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`span`,{children:O(`chat:sessionTree.nodeLabel`)}),(0,$.jsx)(Yn,{value:f,maxLength:80,placeholder:O(`chat:sessionTree.labelPlaceholder`),onChange:e=>b(e.target.value)})]}),(0,$.jsxs)(Y,{variant:`secondary`,disabled:m||i||a,onClick:S,children:[(0,$.jsx)(_t,{size:14}),O(m?`chat:sessionTree.savingLabel`:`chat:sessionTree.saveLabel`)]}),!!t.label&&(0,$.jsxs)(Y,{variant:`secondary`,disabled:m||i||a,onClick:C,children:[(0,$.jsx)(St,{size:14}),O(`chat:sessionTree.removeLabel`)]})]}),u&&(0,$.jsxs)(Y,{variant:`secondary`,disabled:h||i||a,onClick:w,children:[(0,$.jsx)(qe,{size:14}),O(h?`chat:sessionTree.creatingChildChat`:`chat:sessionTree.createChildChat`)]}),d&&(0,$.jsxs)(`label`,{className:`session-tree-summary-option cursor-pointer grid-cols-[minmax(0,1fr)_auto] items-center [&_small]:col-span-full [&_small]:leading-relaxed [&_small]:font-normal [&_small]:text-content-muted`,children:[(0,$.jsx)(`span`,{children:O(`chat:sessionTree.abandonedBranchSummary`)}),(0,$.jsx)(Vt,{checked:p,disabled:t.leaf||i||a,onCheckedChange:x,"data-session-tree-summary":!0}),(0,$.jsx)(`small`,{children:O(`chat:sessionTree.abandonedBranchSummaryHint`)})]})]}),d&&(0,$.jsx)(`p`,{children:O(`chat:sessionTree.sideEffectsRemain`)}),t.timestamp&&(0,$.jsx)(`p`,{children:new Intl.DateTimeFormat(k,{dateStyle:`medium`,timeStyle:`short`}).format(new Date(t.timestamp))}),r&&(0,$.jsx)(`p`,{role:`alert`,className:`text-danger!`,children:r}),d&&(0,$.jsxs)(Y,{className:`chat-resource-confirm self-start`,disabled:g||t.leaf||i||a,onClick:T,children:[(0,$.jsx)(We,{size:15}),g?O(`chat:sessionTree.navigating`):t.leaf?O(`chat:sessionTree.currentPosition`):O(`chat:sessionTree.continueFromNode`)]})]}):(0,$.jsx)(`p`,{children:n?O(`chat:sessionTree.loading`):r||O(`chat:sessionTree.chooseNode`)}),r&&!t&&(0,$.jsx)(Y,{variant:`secondary`,onClick:E,children:O(`chat:sessionTree.retry`)})]})}function ja({open:e,sessionId:t,streaming:n,onClose:r,onNavigated:i,onCreateChildSession:a,initialView:o=`branches`,returnFocusRef:s,notify:c}){let{t:u,language:d}=l(),f=j(),p=A(),m=f||p,[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(`branches`),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(`list`),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(``),[k,M]=(0,Q.useState)(``),[N,P]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(!1),[z,B]=(0,Q.useState)(null),[V,H]=(0,Q.useState)(null),[U,W]=(0,Q.useState)(!1),[ee,te]=(0,Q.useState)(!1),[ne,re]=(0,Q.useState)(!1),[ie,ae]=(0,Q.useState)(!1),[oe,se]=(0,Q.useState)(!1),[ce,G]=(0,Q.useState)(``),le=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!e||!t)return;let n=!1;return b(o),w(`list`),E(``),te(!0),G(``),Promise.all([X.getSessionTree(t),X.listSessions()]).then(([e,t])=>{n||(g(e),v(t.sessions||[]),O(e.leafId||e.nodes[0]?.id||``))}).catch(e=>{n||G(Z(e))}).finally(()=>{n||te(!1)}),()=>{n=!0}},[e,t]),(0,Q.useEffect)(()=>{e||(g(null),v([]),O(``),w(`list`),M(``),B(null),H(null),W(!1),G(``))},[e]),(0,Q.useEffect)(()=>{if(!e||y!==`marks`||F)return;let t=!0;return R(!0),G(``),X.listSessionTreeLabels(500).then(e=>{t&&(P(e.labels||[]),I(!0))}).catch(e=>t&&G(Z(e))).finally(()=>t&&R(!1)),()=>{t=!1}},[e,y,F]);let ue=(0,Q.useMemo)(()=>{let e=T.trim().toLocaleLowerCase(d);return e?N.filter(t=>`${t.label} ${t.sessionName}`.toLocaleLowerCase(d).includes(e)):N},[N,d,T]),de=async(e,t=!1)=>{if(!z){if(!e.active&&!t){H(e);return}H(null),B(e),G(``);try{let t=null;if(!e.active){if(t=await X.navigateSessionTreeTarget(e.sessionId,e.entryId),t.cancelled){B(null);return}fr(e.sessionId)}mn(e.sessionId,`open`,e.entryId),r(),t&&c&&zr(e.sessionId,t,u(`chat:sessionTree.switchedBranch`),{notify:c,t:u})}catch(e){G(Z(e)),B(null)}}},fe=(0,Q.useMemo)(()=>xa(h?.nodes||[]),[h]),pe=(0,Q.useCallback)(e=>({user:u(`chat:sessionTree.userMessage`),assistant:u(`chat:sessionTree.agentMessage`),tool:u(`chat:sessionTree.toolResult`),"tool-call":u(`chat:sessionTree.toolCall`),summary:u(`chat:sessionTree.branchSummary`),compaction:u(`chat:sessionTree.compactionSummary`),settings:u(`chat:sessionTree.settingsChange`),label:u(`chat:sessionTree.labelChange`),position:u(`chat:sessionTree.branchPosition`),extension:u(`chat:sessionTree.extensionEntry`),metadata:u(`chat:sessionTree.metadataEntry`),message:u(`chat:sessionTree.message`)})[e.kind]||e.type,[u]),me=(0,Q.useMemo)(()=>{let e=T.trim().toLocaleLowerCase(d);return Ca(fe,t=>ya(t,y,x)?!e||`${t.label} ${t.text} ${pe(t)}`.toLocaleLowerCase(d).includes(e):!1)},[fe,d,T,x,pe,y]),K=(0,Q.useMemo)(()=>me.map(wa),[me]),he=(0,Q.useMemo)(()=>Sa(me),[me]),q=(0,Q.useMemo)(()=>Sa(fe),[fe]).find(e=>e.id===D)||null,ge=h?.lineage?.parentSessionId?_.find(e=>e.id===h.lineage?.parentSessionId):null,_e=(h?.lineage?.childSessionIds||[]).map(e=>_.find(t=>t.id===e)).filter(e=>!!e),ve=q?.kind===`assistant`&&q.status===`completed`,ye=ve,be=q?!ba.has(q.kind):!1;(0,Q.useEffect)(()=>{M(q?.label||``),W(!1)},[q?.id,q?.label]),(0,Q.useEffect)(()=>{if(D&&he.some(e=>e.id===D))return;let e=[...he].reverse().find(e=>e.active);O(e?.id||he[0]?.id||``)},[D,he]),(0,Q.useEffect)(()=>{if(!e||!D)return;let t=requestAnimationFrame(()=>{document.querySelector(`[data-testid="session-tree-list"] .session-tree-node.selected`)?.scrollIntoView({block:`center`})});return()=>cancelAnimationFrame(t)},[e,T,D,y,he.length]);let xe=async()=>{te(!0),G(``);try{let e=await X.getSessionTree(t);g(e),O(e.leafId||e.nodes[0]?.id||``)}catch(e){G(Z(e))}finally{te(!1)}},Se=async()=>{if(!(!q||ne)){re(!0),G(``);try{let e=await X.setSessionTreeLabel(t,q.id,k);g(e),mr(t,e)}catch(e){G(Z(e))}finally{re(!1)}}},Ce=async()=>{if(!(!q||ne)){re(!0),G(``);try{let e=await X.setSessionTreeLabel(t,q.id,``);g(e),mr(t,e)}catch(e){G(Z(e))}finally{re(!1)}}},we=async()=>{if(!(!q||!ye||oe)){se(!0),G(``);try{await a(q.id),r()}catch(e){G(Z(e))}finally{se(!1)}}},Te=(e,t=``)=>{e.id&&(mn(e.id,`open`,t),r())},Ee=async()=>{if(!(!q||ie||q.leaf||n||h?.streaming)){ae(!0),G(``);try{let e=await X.navigateSessionTree(t,q.id,U);g(e),e.cancelled||(mr(t,e),await i(e.editorText),r(),c&&zr(t,e,u(`chat:chatPage.branchedFromNode`),{notify:c,t:u}))}catch(e){G(Z(e))}finally{ae(!1)}}},De=e=>e.leaf?u(`chat:sessionTree.current`):e.branchPoint?u(`chat:sessionTree.fork`):e.active?u(`chat:sessionTree.active`):``;return(0,$.jsx)(Jn,{open:e,onOpenChange:e=>!e&&r(),children:(0,$.jsxs)(Gn,{onCloseAutoFocus:e=>{let n=s?.current,r=n?.isConnected?n:document.getElementById(`task-${t}-more`);r?.closest(`[data-task-workspace]`)?.getAttribute(`data-active`)===`true`&&(e.preventDefault(),r.focus())},className:`chat-resource-dialog session-tree-dialog grid-rows-[auto_minmax(0,1fr)] gap-0 overflow-hidden border border-stroke bg-solid p-0 ${m?`!h-[calc(100dvh_-_16px)] !w-[calc(100vw_-_16px)] !max-w-none`:`!h-[min(760px,calc(100dvh_-_32px))] !w-[min(1120px,calc(100vw_-_32px))] !max-w-[1120px]`}`,showCloseButton:!1,children:[(0,$.jsxs)(`div`,{className:`chat-resource-head flex items-start justify-between gap-4 border-b border-stroke-soft px-[18px] pt-4 pb-3.5 max-[650px]:p-3.5 [&_[data-slot='dialog-description']]:mt-0.5 [&_[data-slot='dialog-description']]:text-xs [&_[data-slot='dialog-description']]:text-content-muted [&_[data-slot='dialog-title']]:text-base [&_[data-slot='dialog-title']]:font-semibold`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`session-tree-title flex items-center gap-2`,children:[(0,$.jsx)(et,{className:`size-4 text-content-muted`,strokeWidth:1.75,"aria-hidden":`true`}),(0,$.jsx)(Kn,{children:u(`chat:sessionTree.title`)})]}),(0,$.jsx)(Wn,{children:u(`chat:sessionTree.description`,{nodes:h?.nodeCount||0,branches:h?.branchCount||0})})]}),(0,$.jsx)(Y,{type:`button`,variant:`ghost`,size:`icon`,className:`max-[650px]:size-11`,"aria-label":u(`common:ui.closeDialog`),title:u(`common:ui.closeDialog`),onClick:r,children:(0,$.jsx)(Dt,{size:16})})]}),(0,$.jsxs)(`div`,{className:`chat-resource-body session-tree-layout grid min-h-0 overflow-hidden bg-background ${m?`grid-cols-1 grid-rows-[minmax(0,1fr)]`:`!grid-cols-[minmax(0,1fr)_292px]`}`,children:[(!m||C===`list`)&&(0,$.jsx)(Oa,{view:y,onViewChange:e=>{b(e),H(null),w(`list`)},showAllEntries:x,onShowAllEntriesChange:S,query:T,onQueryChange:E,loading:ee,error:ce,mobileLayout:m,viewportRef:le,segments:K,visibleNodes:he,selectedId:D,typeLabel:pe,stateLabel:De,onSelect:e=>{O(e),m&&w(`detail`)},visibleMarks:ue,marksLoading:L,openingMark:z,onOpenMark:e=>void de(e),confirmingMark:V,onConfirmMark:e=>void de(e,!0),onCancelMark:()=>H(null)}),y!==`marks`&&(!m||C===`detail`)&&(0,$.jsx)(Aa,{mobileLayout:m,selected:q,loading:ee,error:ce,streaming:n,dataStreaming:!!h?.streaming,parentSession:ge??null,parentEntryId:h?.lineage?.sourceEntryId||``,childSessions:_e,canLabel:ve,canDerive:be,label:k,summarize:U,savingLabel:ne,creatingChild:oe,navigating:ie,typeLabel:pe,stateLabel:De,onBackToList:()=>w(`list`),onLabelChange:M,onSummarizeChange:W,onSaveLabel:()=>void Se(),onRemoveLabel:()=>void Ce(),onCreateChild:()=>void we(),onNavigate:()=>void Ee(),onRefresh:()=>void xe(),onOpenRelated:(e,t)=>Te(e,t??``)})]})]})})}function Ma({visible:e,open:t,sessionId:n,streaming:r,revision:i,pulseToken:a,onOpenChange:o,onNavigated:s,onCreateChildSession:c,notify:u,children:d}){let{t:f}=l(),p=dr(n,{enabled:e,streaming:r,revision:i})?.branchCount??0,[m,h]=(0,Q.useState)(`branches`),[g,_]=(0,Q.useState)(!1),v=(0,Q.useRef)(0),y=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>cancelAnimationFrame(v.current),[]),(0,Q.useEffect)(()=>{if(!a)return;_(!0);let e=window.setTimeout(()=>_(!1),1800);return()=>window.clearTimeout(e)},[a]);let b=p>0&&(0,$.jsx)(`i`,{"aria-hidden":`true`,className:`ml-auto size-1.5 rounded-full bg-star`}),x=e?(0,$.jsxs)(jt,{"aria-label":f(`chat:sessionTree.menu`),"aria-haspopup":`dialog`,"data-pisper-recall-pulse":g||void 0,onSelect:()=>{y.current=null,h(`branches`),cancelAnimationFrame(v.current),v.current=requestAnimationFrame(()=>o(!0))},children:[(0,$.jsx)(et,{className:g?`motion-reduce:animate-none [animation:session-tree-new-node-pulse_1.8s_var(--ease-out)]`:void 0}),f(`chat:sessionTree.menu`),b]}):null;return(0,$.jsxs)($.Fragment,{children:[d(x,{branches:p,open:(e=`branches`,t=null)=>{y.current=t,h(e),cancelAnimationFrame(v.current),v.current=requestAnimationFrame(()=>o(!0))}}),e&&(0,$.jsx)(ja,{open:t,initialView:m,returnFocusRef:y,sessionId:n,streaming:r,onClose:()=>o(!1),onNavigated:s,onCreateChildSession:c,notify:u})]})}function Na({question:e,more:t,collapsed:n,onAnswer:r}){let{t:i}=l(),[a,o]=(0,Q.useState)(()=>e.questions.map(()=>({selected:[]}))),[s,c]=(0,Q.useState)(()=>e.questions.map(()=>!1)),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(``),m=e.questions.length===1&&!e.questions[0].multiSelect,h=On(e,a);if(n)return(0,$.jsxs)(`p`,{"data-question-more":!0,className:`flex min-h-8 min-w-0 items-center gap-2 rounded-(--r-md) border border-st-attn-border px-3 text-xs text-st-attn`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`size-2 flex-none rounded-full bg-st-attn-fill`}),i(`board:question.waiting`,{count:t+1})]});let g=async t=>{if(!u){d(!0),p(``);try{await r(e.id,t)}catch{p(i(`board:question.failed`)),d(!1)}}},_=e=>e.map((e,t)=>{let n=s[t]?e.other?.trim():``;return n?{selected:e.selected,other:n}:{selected:e.selected}}),v=(t,n)=>{let r=e.questions[t],i=a.map((e,i)=>{if(i!==t)return e;if(!r.multiSelect)return{...e,selected:[n]};let a=e.selected.includes(n)?e.selected.filter(e=>e!==n):[...e.selected,n];return{...e,selected:a}});o(i),m&&g({answers:_(i)})};return(0,$.jsxs)(`div`,{"data-question-card":e.id,role:`group`,"aria-label":i(`board:question.label`),"aria-busy":u||void 0,onKeyDown:t=>{if(t.altKey||t.metaKey||t.ctrlKey)return;let n=t.target;if(n.closest(`textarea, input`))return;let r=a.findIndex(e=>!e.selected.length&&!e.other?.trim()),i=r<0?e.questions.length-1:r,o=Number(t.key);if(Number.isInteger(o)&&o>=1&&o<=6){let n=e.questions[i]?.options[o-1];if(!n)return;t.preventDefault(),v(i,n.label)}else t.key===`Enter`&&!n.closest(`button`)&&h&&(t.preventDefault(),g({answers:_(a)}))},className:`flex max-h-[min(60vh,560px)] min-w-0 flex-col gap-3 overflow-y-auto rounded-(--r-lg) border border-st-attn-border bg-st-attn-soft px-3.5 py-3 text-foreground`,children:[(0,$.jsxs)(`p`,{className:`flex items-center gap-2 text-xs font-medium text-warning-strong`,children:[(0,$.jsx)(ni,{className:`size-4 flex-none`,"aria-hidden":`true`}),i(`board:question.title`),t>0&&(0,$.jsx)(`span`,{className:`font-normal text-content-muted`,children:i(`board:question.moreAfter`,{count:t})})]}),e.questions.map((t,n)=>{let r=a[n],l=t.header?`${t.header}:${t.question}`:t.question;return(0,$.jsxs)(`fieldset`,{"data-question-item":n,className:`flex min-w-0 flex-col gap-1.5`,children:[(0,$.jsxs)(`legend`,{className:`mb-1.5 flex min-w-0 flex-col gap-0.5`,children:[t.header&&(0,$.jsx)(`span`,{className:`text-xs font-medium text-content-muted`,children:t.header}),(0,$.jsx)(`span`,{className:`text-sm leading-5 text-content`,children:t.question})]}),(0,$.jsxs)(`div`,{role:t.multiSelect?`group`:`radiogroup`,"aria-label":l,className:`flex flex-wrap gap-1.5`,children:[t.options.map((e,i)=>{let a=r.selected.includes(e.label);return(0,$.jsxs)(`button`,{type:`button`,role:t.multiSelect?`checkbox`:`radio`,"aria-checked":a,disabled:u,"data-question-option":e.label,title:e.description||void 0,className:Xt(`flex min-h-9 max-w-full min-w-0 items-center gap-1.5 rounded-(--r-md) border px-2.5 py-1 text-left text-[13px] transition-colors duration-(--d-fast) focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-focus disabled:opacity-60 pointer-coarse:min-h-11`,a?`border-content bg-content text-panel`:`border-stroke-strong bg-panel text-content hover:bg-surface-hover`),onClick:()=>v(n,e.label),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`font-mono text-[11px] opacity-60 pointer-coarse:hidden`,children:i+1}),(0,$.jsxs)(`span`,{className:`flex min-w-0 flex-col`,children:[(0,$.jsx)(`span`,{className:`break-words`,children:e.label}),e.description&&(0,$.jsx)(`span`,{className:Xt(`text-xs break-words`,a?`opacity-80`:`text-content-muted`),children:e.description})]}),a&&t.multiSelect&&(0,$.jsx)(z,{className:`size-3.5 flex-none`,"aria-hidden":`true`})]},e.label)}),(0,$.jsx)(`button`,{type:`button`,"aria-expanded":s[n],disabled:u,"data-question-other":n,className:Xt(`flex min-h-9 items-center rounded-(--r-md) border border-dashed border-stroke-strong px-2.5 text-[13px] text-content-secondary hover:bg-surface-hover focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-focus pointer-coarse:min-h-11`,s[n]&&`border-solid bg-panel`),onClick:()=>c(e=>e.map((e,t)=>t===n?!e:e)),children:i(`board:question.other`)})]}),s[n]&&(0,$.jsx)(`textarea`,{"aria-label":i(`board:question.otherLabel`,{question:t.question}),maxLength:An.other,rows:2,disabled:u,value:r.other??``,placeholder:i(`board:question.otherPlaceholder`),className:`min-h-16 w-full resize-y rounded-(--r-md) border border-control bg-panel px-2.5 py-1.5 text-sm text-content outline-none focus:border-focus focus:ring-3 focus:ring-focus-ring max-[650px]:text-[16px]`,onChange:e=>{let t=e.target.value;o(e=>e.map((e,r)=>r===n?{...e,other:t}:e))},onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&h&&(e.preventDefault(),g({answers:_(a)}))}})]},`${e.id}-${n}`)}),f&&(0,$.jsx)(`p`,{role:`alert`,className:`text-xs text-[var(--danger)]`,children:f}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[(0,$.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,disabled:u,"data-question-skip":!0,className:`pointer-coarse:min-h-11`,onClick:()=>void g({skip:!0}),children:i(`board:question.skip`)}),(!m||s[0])&&(0,$.jsx)(Y,{type:`button`,size:`sm`,disabled:u||!h,loading:u,"data-question-submit":!0,className:`pointer-coarse:min-h-11`,onClick:()=>void g({answers:_(a)}),children:i(`board:question.submit`)})]})]})}async function Pa({templatePrompt:e,configureHint:t,notify:n,onOpenModelSettings:r,onInsertPrompt:i}){try{let a=await D(`/api/visual/models`);a.image||a.video?i(e):(n?.(t),r?.())}catch{i(e)}}function Fa(e){return(e.target instanceof Element?e.target:null)?.closest(`[data-shortcut-recorder], [role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], .xterm, .terminal-xterm, .terminal-panel, [data-terminal]`)?!0:Array.from(document.querySelectorAll(`[role="dialog"], [role="alertdialog"], dialog[open]`)).some(e=>e.getClientRects().length>0)}function Ia(e){let t=(0,Q.useRef)(e);t.current=e;let{enabled:n,binding:r}=e;(0,Q.useEffect)(()=>{if(!n||!r)return;let e=null,i=null,a=()=>{e=null,i&&(i=null,t.current.onCancel())},o=n=>{if(i&&n.key===`Escape`&&!n.isComposing){a(),n.preventDefault();return}!t.current.enabled||n.defaultPrevented||n.isComposing||n.keyCode===229||n.repeat||e||document.visibilityState===`hidden`||Fa(n)||!yn(n,r)||(e=n.code,t.current.onStart()&&(i={code:n.code,ctrl:n.ctrlKey,meta:n.metaKey,alt:n.altKey,shift:n.shiftKey},n.preventDefault()))},s=n=>{n.code===e&&(e=null),i&&(n.code===i.code||i.ctrl&&(!n.ctrlKey||n.code.startsWith(`Control`))||i.meta&&(!n.metaKey||n.code.startsWith(`Meta`))||i.alt&&(!n.altKey||n.code.startsWith(`Alt`))||i.shift&&(!n.shiftKey||n.code.startsWith(`Shift`)))&&(i=null,t.current.onRelease())},c=()=>{document.visibilityState===`hidden`&&a()};return window.addEventListener(`keydown`,o),window.addEventListener(`keyup`,s,!0),window.addEventListener(`blur`,a),document.addEventListener(`visibilitychange`,c),()=>{window.removeEventListener(`keydown`,o),window.removeEventListener(`keyup`,s,!0),window.removeEventListener(`blur`,a),document.removeEventListener(`visibilitychange`,c),a()}},[n,r])}function La(e){if(!e.length)return 0;let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];let n=Math.sqrt(t/e.length);return n<.0056?0:Math.min(1,Math.sqrt(n)*2.6)}function Ra(e=.35){let t=0;return{push(n){return t=t*(1-e)+n*e,t},reset(){t=0}}}function za(e,t=140){let n=e.trim();return n.length>t?`${n.slice(0,t-1)}…`:n}var Ba=16e3,Va=20,Ha=Ba*Va/1e3;function Ua(e,{onsetMs:t=80,minVoicedMs:n=160,silenceMs:r=900}={}){for(let e of[t,n,r])if(!Number.isFinite(e)||e<=0)throw Error(`Invalid VAD endpoint duration`);let i=e(),a=new Int16Array(Ha),o=0,s=0,c=0,l=0,u=!1,d=!1,f=!1,p=()=>u&&c*Va>=n;return{get hasSpeech(){return p()},acceptPcm(e){if(f||d)return!1;for(let n=0;n<e.length;n+=1){let f=Number.isFinite(e[n])?Math.max(-1,Math.min(1,e[n])):0;if(a[o++]=f*(f<0?32768:32767),o!==Ha)continue;o=0;let m=i.processFrame(a);if(m<0)throw Error(`VAD frame processing failed`);if(m===1)s+=1,c+=1,l=0,s*Va>=t&&(u=!0);else if(s=0,l+=1,u||(c=0),l*Va>=r){if(p())return d=!0,!0;u=!1,c=0}}return!1},reset(){f||(i.destroy(),i=e(),o=s=c=l=0,u=d=!1,a.fill(0))},dispose(){f||(f=!0,o=0,i.destroy())}}}async function Wa(e={}){let{default:n,VADMode:r}=await t(async()=>{let{default:e,VADMode:t}=await import(`./embedded-D2rqyswH.js`);return{default:e,VADMode:t}},[]),i=await n();return Ua(()=>new i(e.mode??r.AGGRESSIVE,Ba),e)}var Ga=()=>new DOMException(`Speech setup cancelled.`,`AbortError`);function Ka(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(``),l=(0,Q.useRef)(null),u=(0,Q.useRef)(!1),d=(0,Q.useRef)(0),f=(0,Q.useRef)(0),p=(0,Q.useRef)(0),m=(0,Q.useRef)(e);m.current=e;let h=(0,Q.useCallback)(e=>{d.current++,f.current++;let t=l.current;l.current=null,t&&(t.signal.removeEventListener(`abort`,t.abort),e?t.reject(e):t.resolve()),u.current&&(i(!1),o(!1))},[]),g=(0,Q.useCallback)(e=>{u.current&&(n(e),c(``),l.current&&Jr(e,m.current).every(e=>e.status===`installed`)&&h())},[h]),_=(0,Q.useCallback)(async e=>{let t=d.current,n=++f.current,r=()=>u.current&&t===d.current&&n===f.current&&!e?.aborted;try{let t=await Vr(e);r()&&g(t)}catch(e){if(r())throw e}},[g]);(0,Q.useEffect)(()=>(u.current=!0,_().catch(()=>{}),()=>{u.current=!1,h(Ga())}),[h,_]),(0,Q.useEffect)(()=>{if(!r)return;let e=new AbortController,t,n=async()=>{try{await _(e.signal)}catch(t){e.signal.aborted||c(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||(t=setTimeout(()=>void n(),750))}};return n(),()=>{e.abort(),clearTimeout(t)}},[r,_]);let v=(0,Q.useCallback)(async e=>{if(y(e),!u.current)throw Ga();h(Ga());let t=++f.current;return new Promise((n,r)=>{let a=()=>{l.current===o&&h(e.reason||Ga())},o={signal:e,abort:a,resolve:n,reject:r};if(l.current=o,e.addEventListener(`abort`,a,{once:!0}),e.aborted){a();return}Vr(e).then(n=>{!u.current||l.current!==o||e.aborted||(t===f.current&&g(n),l.current===o&&i(!0))},e=>{l.current===o&&h(e)})})},[g,h]),b=(0,Q.useCallback)(async e=>{let t=d.current,n=++p.current,r=()=>u.current&&t===d.current&&n===p.current;o(!0),c(``);try{await e(),r()&&await _()}catch(e){r()&&c(e instanceof Error?e.message:String(e))}finally{r()&&o(!1)}},[_]);return{catalog:t,open:r,loading:a,error:s,selectedVoice:t?.defaults.voice||``,ensureReady:v,models:t?Jr(t,e):[],show:()=>{h(Ga()),i(!0),c(``)},close:()=>h(Ga()),download:e=>b(()=>Kr(e)),cancelDownload:e=>b(()=>Gr(e)),downloadAll:()=>b(async()=>{if(t)for(let e of Jr(t,m.current))[`installed`,`downloading`,`verifying`].includes(e.status)||await Kr(e.id)})}}var qa=8388608;function Ja(e,t){return y(t),new Promise((n,r)=>{let i=()=>r(b(t));t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}var Ya=10,Xa=500;async function Za(e,t,n,r){for(let i=0;;i+=1){let a=await fetch(`/api/speech/synthesize`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({text:e,voiceId:t,requestId:n}),signal:r});if(a.status!==409||i>=Ya)return a;let o=await a.json().catch(()=>({}));if(!o.error||!/busy/i.test(o.error))return a;await Ja(new Promise(e=>setTimeout(e,Xa)),r)}}async function Qa(e){if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error||`Speech synthesis failed (${e.status}).`)}if(!e.headers.get(`content-type`)?.startsWith(`audio/wav`)||!e.body)throw Error(`Invalid speech audio response.`);let t=e.body.getReader(),n=[],r=0;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;if(r+=i.byteLength,r>qa)throw Error(`Speech audio exceeds the supported limit.`);n.push(i)}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}if(r<44)throw Error(`Speech audio is empty.`);let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i.buffer}async function $a(e,t,n,r){y(n);let i=v(n);try{await eo(e,t,i,r)}finally{i.abort(new DOMException(`Speech playback ended.`,`AbortError`)),i.dispose()}}async function eo(e,n,r,i){let{signal:a}=r,{speechSegments:o}=await Ja(t(()=>import(`./speech-text-BTwYi9Sb.js`),__vite__mapDeps([141,91,1,2,3,88,89,90,34])),a);y(a);let s=(typeof e==`string`?(async function*(){yield*o(e)})():(await Ja(t(()=>import(`./speech-stream-text-DF6aAUVb.js`),__vite__mapDeps([142,91,1,2,3,88,89,90,34,13,141])),a)).streamingSpeechSegments(e,a))[Symbol.asyncIterator](),c=!!window.__PISPER_MOBILE_APP__,l=new Set,u,d,f,p=e=>{(c?Ur(`mobile_cancel_speech`,{requestId:e}):D(`/api/speech/cancel`,{method:`POST`,body:{requestId:e},timeout:3e3})).catch(()=>{})},m=()=>{for(let e of l)p(e);try{d?.stop()}catch{}f?.(a.reason||new DOMException(`Speech playback cancelled.`,`AbortError`))};a.addEventListener(`abort`,m,{once:!0});let h=e=>{y(a);let t=crypto.randomUUID();l.add(t);let r=(async()=>{if(c){let r=await Ur(`mobile_synthesize_speech`,{text:e,voiceId:n,requestId:t});if(a.aborted&&(p(t),y(a)),!r||typeof r.audioId!=`string`||!r.audioId.trim()||r.audioId.length>128||!Number.isInteger(r.sampleRate)||r.sampleRate<8e3||r.sampleRate>48e3||!Number.isFinite(r.durationMs)||r.durationMs<=0||r.durationMs>45e3)throw Error(`Invalid native speech audio.`);return{requestId:t,native:r}}let r=v(a,6e4);try{let i=await Za(e,n,t,r.signal);return{requestId:t,wav:await Qa(i)}}finally{r.dispose()}})();return r.catch(()=>{}),r};try{if(!c){u=new AudioContext({sampleRate:24e3});let e;try{await Ja(Promise.race([u.resume(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`Audio playback is unavailable.`)),5e3)})]),a)}finally{clearTimeout(e)}}let e=async()=>{let e=await Ja(s.next(),a);return e.done?void 0:h(e.value)},t=e(),n=!1;for(;;){let r=await Ja(t,a);if(y(a),!r)break;if(t=e(),t.catch(()=>{}),n=!0,i?.(),r.native){if((await Ja(Ur(`mobile_play_speech`,{audioId:r.native.audioId,requestId:r.requestId}),a))?.completed!==!0)throw Error(`Speech playback was interrupted.`)}else{let e=await Ja(u.decodeAudioData(r.wav),a);if(y(a),e.numberOfChannels!==1||!Number.isFinite(e.duration)||e.duration<=0||e.duration>45)throw Error(`Invalid speech audio duration.`);let t=u.createBufferSource();d=t,t.buffer=e,t.connect(u.destination);try{await new Promise((e,n)=>{f=n,t.onended=()=>e(),t.start()})}finally{f=void 0,t.onended=null,t.disconnect(),d=void 0}}l.delete(r.requestId),y(a)}if(!n)throw Error(`The reply has no speakable text.`)}finally{a.removeEventListener(`abort`,m),r.abort(new DOMException(`Speech playback ended.`,`AbortError`)),s.return?.(void 0).catch(()=>{});for(let e of l)p(e);try{d?.stop()}catch{}await u?.close().catch(()=>{})}}var to={schemaVersion:1,scope:`Offline license texts and provenance notices for the catalogued speech resources and local derivatives. This document is not legal advice, commercial-use clearance, a complete training-data rights audit, or approval for redistribution or formal release. Packaging this small notice file does not package the large models or resolve pending obligations. Native sherpa binaries and their compiled or embedded dependencies require a separate license/linkage and source-delivery audit; switching TTS models does not prove the binaries contain no GPL components or satisfy their obligations.`,licenseIdsMeaning:`References identify retained license documents applicable to the described components or their stated source projects. Multiple references are not alternative dual-license choices and are not a complete SPDX expression. A repository declaration does not relicense unrelated bundled data.`,statusDefinitions:{confirmed:`The specific content or source match described in summary was verified; this is not a whole-chain rights guarantee.`,declared:`An upstream license declaration supports the classification, without a complete reproducible provenance proof.`,pending:`The listed provenance, rights, or distribution obligations remain unresolved even where a license declaration exists.`},pathScopes:{model:`Paths are relative to the original downloaded model root. A terminal /** matches every descendant; all other paths are exact.`,shared:`Paths are relative to the application's shared resource root.`},licenses:[{id:`apache-2.0`,name:`Apache License 2.0 (X-ASR source text)`,text:` Apache License
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SessionContextPanel-aH8brkyg.js","assets/rolldown-runtime-B0Z9INg1.js","assets/vendor-router-CSN_DGvx.js","assets/vendor-react-DwNgTV1j.js","assets/use-i18n-D7gqe3X9.js","assets/i18n-DojWxWRu.js","assets/index-DfZr_SBB.js","assets/index-CrtNFCj_.css","assets/storage-DtvZ_lEu.js","assets/vendor-state-GkUciC5H.js","assets/runtime-capabilities-ChJVNwRz.js","assets/runtime-capabilities-store-Pf6H3F8g.js","assets/api-DvJkDxm2.js","assets/abort-signal-f4JsiYKX.js","assets/http-response-CSCIVa2S.js","assets/event-stream-Viv-Ob7U.js","assets/http-zidLhKOq.js","assets/activity-BCxvXCG3.js","assets/createLucideIcon-Cd-3GVxJ.js","assets/arrow-left-B8oVrQ2S.js","assets/check-2vYc6QaP.js","assets/chevron-right-C3t2Rckj.js","assets/SessionBrowserPane-feS4xeee.js","assets/useQuery-DfOU-27z.js","assets/query-DFQayLF5.js","assets/arrow-right-DqLOhpA2.js","assets/arrow-up-DST6-qVQ.js","assets/chevron-down-CxtxIjiP.js","assets/download-BCfIiuaL.js","assets/earth-Ddy13fHh.js","assets/external-link-CEQqPcqc.js","assets/GitDiffViewer-CAklMpA4.js","assets/x-07u4-129.js","assets/utils-C8uzG5AZ.js","assets/vendor-ui-DvrYggeS.js","assets/button-CCcCN8tE.js","assets/dist-41X0pdUs.js","assets/events-Wogs03GD.js","assets/esm-DCV8yILT.js","assets/file-Bllajneu.js","assets/side-chat-context-C2I0EzIE.js","assets/routes-BYsK6aeM.js","assets/session-board-status-D_Tz3HJm.js","assets/usePhoneShell-O2Livo2-.js","assets/use-mobile-C2tPBAza.js","assets/client-store-vgpSLnwK.js","assets/arrow-down-CDGua-ue.js","assets/ChatMessage-CzJ7vm4B.js","assets/chevron-left-BAtyp3_6.js","assets/chevron-up-D_ZcXjqr.js","assets/copy-DHmIFc52.js","assets/ellipsis-CfGKfbq6.js","assets/eye-uWAPXNzJ.js","assets/folder-open-FIShC5Qk.js","assets/info-DATxy0fb.js","assets/undo-2-ChaURM4t.js","assets/loader-circle-BOwQzHB-.js","assets/message-square-text-C5MJw0FL.js","assets/rotate-ccw-clock-CO6Bw-sF.js","assets/rotate-ccw-C0v8V77_.js","assets/tag-CqkeJlBf.js","assets/trash-2-CNrPOoPR.js","assets/collapsible-B-fc7n0u.js","assets/dist-BsRXXcSL.js","assets/dropdown-menu-Ds0gD8S8.js","assets/dist-DzGQ7sLi.js","assets/es2015-DTZdOI9P.js","assets/dist-BRjj4UeB.js","assets/dist-OB2r6Xsr.js","assets/dist-BaBySQmo.js","assets/popover-CJZagMlP.js","assets/dialog-Cfk77z7g.js","assets/dist-BHkR6BLP.js","assets/tooltip-D4MFbqcG.js","assets/dist-BiRPwy4W.js","assets/chat-api-DrjHZunL.js","assets/startup-queries-D3JCr4DY.js","assets/mutation-b4pPvB7p.js","assets/format-DMJQzoZ7.js","assets/StatusGlyph-1KgitlUg.js","assets/command-Cf3AX_Nt.js","assets/search-D0mqDaf_.js","assets/input-group-h8z63MzW.js","assets/input-CPw-zkYh.js","assets/textarea-DmATpOqT.js","assets/alert-DRIrgNI4.js","assets/vendor-motion-DSW3wzXK.js","assets/MarkdownMessage-C47P3anj.js","assets/vendor-markdown-plugins-CT5L3KA9.js","assets/vendor-shiki-runtime-DM7fm4Bl.js","assets/vendor-markdown-plugins-DEcVZfaU.css","assets/vendor-markdown-CT6Z4fh8.js","assets/route-context-DvWDul4T.js","assets/BrandLogo-k3CvJjd4.js","assets/card-C3A0b5KR.js","assets/session-tree-summary-JM5v4ugd.js","assets/session-web-preview-BsCgxxv4.js","assets/FileAttachmentPreview-DV6eqgRK.js","assets/refresh-cw-TbWxTY4K.js","assets/tabs-DsgBuvJv.js","assets/shield-alert-oZqX6MNu.js","assets/shield-check-Gvek4RJ7.js","assets/square-bHHVTT3G.js","assets/shortcuts-DDY3WKNk.js","assets/PageState-Cz6vFMXv.js","assets/motion-DTR4ZVle.js","assets/HoldToConfirmButton-BxdJ7icc.js","assets/permission-rules-api-B_E6IQKz.js","assets/git-branch-N7LGjtzt.js","assets/image-BY_c3FYU.js","assets/link-2-mgasYn21.js","assets/message-square-SKjZyY3v.js","assets/pause-CYWpPg1R.js","assets/triangle-alert-CE1q54ci.js","assets/alert-dialog-DiUitBB0.js","assets/session-change-summary-api-ytql-8Mb.js","assets/AppSelect-B15Hpk2W.js","assets/select-DyBoNnz-.js","assets/chevrons-up-down-C2sEPdAh.js","assets/dist-BS3ekNDj.js","assets/web-preview-C7DdG9JP.js","assets/useNativeBrowser-CF8AHTRL.js","assets/list-todo-hpikYm6Q.js","assets/plus-fQbSqB1n.js","assets/square-terminal-BVG6cUT1.js","assets/sheet-BTaIEX4w.js","assets/public-DAyGFlph.js","assets/public-events-CF9LX0aU.js","assets/terminal-context-aIsIJPn8.js","assets/SessionInspector-2ar9Ti-b.js","assets/bot-B3TaBp_T.js","assets/corner-down-left-DalpwXuX.js","assets/segmented-control-xkrEOP_d.js","assets/session-inspector-store-C8XTJKcv.js","assets/subagent-view-store-BUvI8piR.js","assets/public-session-DS7Ggm0I.js","assets/settings-2-CXJjXJS9.js","assets/BotAvatar-SFQi6bVG.js","assets/bots-store-Dc07jUzl.js","assets/workspace-folders-BrFjAGZo.js","assets/public-flags-DRJJOuZP.js","assets/speech-text-BTwYi9Sb.js","assets/speech-stream-text-DF6aAUVb.js","assets/speech-session-DOQkdJHS.js","assets/mobile-remote-fallback-LLMZWoIu.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{a as e}from"./rolldown-runtime-B0Z9INg1.js";import{h as t,n,u as r}from"./vendor-router-CSN_DGvx.js";import{t as i}from"./index-DfZr_SBB.js";import{i as a,n as o,r as s}from"./vendor-react-DwNgTV1j.js";import{p as c}from"./routes-BYsK6aeM.js";import{t as l}from"./use-i18n-D7gqe3X9.js";import{a as u,i as d,o as f}from"./vendor-state-GkUciC5H.js";import{t as p}from"./storage-DtvZ_lEu.js";import{u as m}from"./query-DFQayLF5.js";import{r as h,t as g}from"./useQuery-DfOU-27z.js";import{t as _}from"./startup-queries-D3JCr4DY.js";import{n as v,r as y,t as b}from"./abort-signal-f4JsiYKX.js";import{a as x,i as S,t as C}from"./http-response-CSCIVa2S.js";import{i as w,n as T}from"./http-zidLhKOq.js";import{n as E,t as D}from"./api-DvJkDxm2.js";import{i as O}from"./runtime-capabilities-ChJVNwRz.js";import{t as k}from"./runtime-capabilities-store-Pf6H3F8g.js";import{n as A}from"./use-mobile-C2tPBAza.js";import{n as j,t as M}from"./client-store-vgpSLnwK.js";import{t as N}from"./createLucideIcon-Cd-3GVxJ.js";import{t as P}from"./activity-BCxvXCG3.js";import{t as F}from"./archive-ojKJT7Fp.js";import{t as I}from"./book-open-BuHHD9os.js";import{t as L}from"./bot-B3TaBp_T.js";import{t as R}from"./braces-DQcXLGFF.js";import{t as z}from"./check-2vYc6QaP.js";import{t as B}from"./chevron-down-CxtxIjiP.js";import{t as V}from"./chevron-left-BAtyp3_6.js";import{t as H}from"./chevron-right-C3t2Rckj.js";import{t as U}from"./circle-check-iEdCm3Pw.js";import{n as W,t as ee}from"./image-plus-D7bzZog0.js";import{t as te}from"./corner-down-right--hxi-Ihy.js";import{t as ne}from"./download-BCfIiuaL.js";import{o as re}from"./GitDiffViewer-CAklMpA4.js";import{C as ie,T as ae,_ as oe,a as se,b as ce,c as G,d as le,f as ue,g as de,h as fe,i as pe,l as me,m as K,n as he,o as q,p as ge,r as _e,s as ve,t as ye,u as be,v as xe,w as Se}from"./FocusRuntimeControls-C8oD9nnP.js";import{_ as Ce,a as we,b as Te,c as Ee,d as De,f as Oe,g as ke,h as Ae,i as je,l as Me,m as Ne,n as Pe,o as Fe,p as Ie,s as Le,t as Re,u as ze,v as Be,y as Ve}from"./side-chat-context-C2I0EzIE.js";import{t as He}from"./WorkspacePicker-BMvjJqVo.js";import{t as Ue}from"./folder-open-FIShC5Qk.js";import{t as We}from"./git-branch-N7LGjtzt.js";import{_ as Ge,a as Ke,b as qe,d as Je,i as Ye,m as Xe,r as Ze,u as Qe,v as $e,x as et,y as tt}from"./ChatMessage-CzJ7vm4B.js";import{t as nt}from"./link-2-mgasYn21.js";import{t as rt}from"./list-todo-hpikYm6Q.js";import{t as it}from"./loader-circle-BOwQzHB-.js";import{t as at}from"./message-square-SKjZyY3v.js";import{t as ot}from"./panel-right-BSUtqUd8.js";import{t as st}from"./paperclip-BCXrwYpb.js";import{t as ct}from"./pencil-U08v_vV9.js";import{t as lt}from"./play-DNDjDNGn.js";import{t as ut}from"./plus-fQbSqB1n.js";import{t as dt}from"./refresh-cw-TbWxTY4K.js";import{t as ft}from"./search-D0mqDaf_.js";import{t as pt}from"./settings-QX0oWnVK.js";import{t as mt}from"./shield-alert-oZqX6MNu.js";import{t as ht}from"./square-pen-hYbjKh6A.js";import{t as J}from"./square-terminal-BVG6cUT1.js";import{t as gt}from"./square-bHHVTT3G.js";import{t as _t}from"./tag-CqkeJlBf.js";import{i as vt,n as yt,r as bt,t as xt}from"./AttachmentTray-ChMs2_F_.js";import{t as St}from"./trash-2-CNrPOoPR.js";import{t as Ct}from"./triangle-alert-CE1q54ci.js";import{t as wt}from"./users-CCtFZzwl.js";import{t as Tt}from"./workflow-Bg94dy8I.js";import{t as Et}from"./wrench-6pg6_bqI.js";import{t as Dt}from"./x-07u4-129.js";import{t as Ot}from"./brand-DIEc3fK8.js";import{t as kt}from"./checkbox-BrEHgFV0.js";import{c as At,i as jt,l as Mt,p as Nt,r as Pt,t as Ft}from"./dropdown-menu-Ds0gD8S8.js";import{a as It,i as Lt,r as Rt,t as zt}from"./popover-CJZagMlP.js";import{t as Bt}from"./progress-5odAz3B9.js";import{t as Vt}from"./switch-D_G8wFhs.js";import{i as Ht,r as Ut,t as Wt}from"./tabs-DsgBuvJv.js";import{n as Gt,t as Kt}from"./segmented-control-xkrEOP_d.js";import{i as qt,n as Jt,t as Yt}from"./tooltip-D4MFbqcG.js";import{t as Xt}from"./utils-C8uzG5AZ.js";import{n as Zt,t as Y}from"./button-CCcCN8tE.js";import{n as Qt,t as $t}from"./kbd-CAufZTkl.js";import{C as en,S as tn,b as nn,c as rn,f as an,i as on,o as sn,p as cn,r as ln,s as un,u as dn,w as fn,x as pn,y as mn}from"./events-Wogs03GD.js";import{a as hn,c as gn,i as _n,n as vn,r as yn,s as bn,t as xn}from"./shortcuts-DDY3WKNk.js";import{n as Sn,o as Cn,r as wn,t as Tn}from"./sheet-BTaIEX4w.js";import{t as X}from"./chat-api-DrjHZunL.js";import{a as En,l as Dn,n as On,s as kn,t as An}from"./session-questions-DODg4dBd.js";import{r as jn}from"./session-workspaces-Brm-8lHh.js";import{o as Mn,r as Nn,t as Pn}from"./format-DMJQzoZ7.js";import{t as Fn}from"./StatusGlyph-1KgitlUg.js";import{C as In,S as Ln,_ as Rn,b as zn,g as Bn,h as Vn,m as Hn,y as Un}from"./command-Cf3AX_Nt.js";import{a as Wn,i as Gn,l as Kn,s as qn,t as Jn}from"./dialog-Cfk77z7g.js";import{t as Yn}from"./input-CPw-zkYh.js";import{i as Xn,n as Zn,t as Qn}from"./input-group-h8z63MzW.js";import{t as $n}from"./model-display-kDwvtxrW.js";import{t as er}from"./session-change-summary-api-ytql-8Mb.js";import{t as tr}from"./pick-system-directory-LTM6ma78.js";import{n as nr,r as rr,t as ir}from"./PageState-Cz6vFMXv.js";import{t as ar}from"./back-navigation-CK7X_5Bc.js";import{t as or}from"./MarkdownMessage-C47P3anj.js";import{t as sr}from"./esm-DCV8yILT.js";import{t as cr}from"./motion-DTR4ZVle.js";import{t as lr}from"./shortcut-aria-jHRmld9z.js";import{t as ur}from"./BrandLogo-k3CvJjd4.js";import{i as dr,n as fr,o as Z,s as pr,t as mr}from"./session-tree-summary-JM5v4ugd.js";import{d as hr,f as gr,l as _r,m as vr,n as yr,p as br,r as xr}from"./session-web-preview-BsCgxxv4.js";import{t as Sr}from"./app-primitives-BskZ4ZJj.js";import{i as Cr,n as wr,o as Tr,r as Er,s as Dr,t as Or}from"./session-list-BRMu9JWa.js";import"./public-DAyGFlph.js";import{n as kr,r as Ar}from"./terminal-context-aIsIJPn8.js";import{n as jr,r as Mr,t as Nr}from"./session-inspector-store-C8XTJKcv.js";import{t as Pr}from"./subagent-view-store-BUvI8piR.js";import{a as Fr,i as Ir}from"./tool-labels-D-3gybP7.js";import{fileRewindConfirmOptions as Lr,fileRewindNotice as Rr,notifyTreeNavigation as zr}from"./session-tree-actions-EtL6Nf5T.js";import{a as Br,c as Vr,i as Hr,l as Ur,n as Wr,o as Gr,s as Kr,t as qr,u as Jr}from"./speech-session-DOQkdJHS.js";import{n as Yr,t as Xr}from"./web-preview-events-D7F0Z-Hy.js";var Zr=N(`audio-lines`,[[`path`,{d:`M2 10v3`,key:`1fnikh`}],[`path`,{d:`M6 6v11`,key:`11sgs0`}],[`path`,{d:`M10 3v18`,key:`yhl04a`}],[`path`,{d:`M14 8v7`,key:`3a1oy3`}],[`path`,{d:`M18 5v13`,key:`123xd1`}],[`path`,{d:`M22 10v3`,key:`154ddg`}]]),Qr=N(`badge-check`,[[`path`,{d:`M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z`,key:`3c2336`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),$r=N(`bookmark`,[[`path`,{d:`M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z`,key:`oz39mx`}]]),ei=N(`file-check-corner`,[[`path`,{d:`M10.5 22H6a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.706.706l3.588 3.588A2.4 2.4 0 0 1 20 8v6`,key:`g5mvt7`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`m14 20 2 2 4-4`,key:`15kota`}]]),ti=N(`file-down`,[[`path`,{d:`M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z`,key:`1oefj6`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M12 18v-6`,key:`17g6i2`}],[`path`,{d:`m9 15 3 3 3-3`,key:`1npd3o`}]]),ni=N(`message-circle-question-mark`,[[`path`,{d:`M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719`,key:`1sd12s`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),ri=N(`mic-off`,[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M15 9.34V5a3 3 0 0 0-5.68-1.33`,key:`1gzdoj`}],[`path`,{d:`M16.95 16.95A7 7 0 0 1 5 12v-2`,key:`cqa7eg`}],[`path`,{d:`M18.89 13.23A7 7 0 0 0 19 12v-2`,key:`16hl24`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M9 9v3a3 3 0 0 0 5.12 2.12`,key:`r2i35w`}]]),ii=N(`mic`,[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`,key:`1vc78b`}],[`rect`,{x:`9`,y:`2`,width:`6`,height:`13`,rx:`3`,key:`s6n7sd`}]]),ai=N(`shield`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}]]),oi=N(`shrink`,[[`path`,{d:`m15 15 6 6m-6-6v4.8m0-4.8h4.8`,key:`17vawe`}],[`path`,{d:`M9 19.8V15m0 0H4.2M9 15l-6 6`,key:`chjx8e`}],[`path`,{d:`M15 4.2V9m0 0h4.8M15 9l6-6`,key:`lav6yq`}],[`path`,{d:`M9 4.2V9m0 0H4.2M9 9 3 3`,key:`1pxi2q`}]]),Q=e(a(),1),si=d(()=>({getItem:e=>{try{return i.getItem(e)}catch{return null}},setItem:(e,t)=>{try{i.setItem(e,t)}catch{}},removeItem:e=>{try{i.removeItem(e)}catch{}}})),ci=f()(u((e,t)=>({width:360,open:!1,setWidth:n=>{let r=gr(n);t().width!==r&&e({width:r})},setOpen:n=>{t().open!==n&&e({open:n})}}),{name:`pisper-session-context-layout`,version:2,storage:si,migrate:e=>{let t=e&&typeof e==`object`&&!Array.isArray(e)?e:{};return{width:gr(`width`in t?t.width:void 0),open:`open`in t&&t.open===!0}},partialize:({width:e,open:t})=>({width:e,open:t}),merge:(e,t)=>({...t,width:gr(e&&typeof e==`object`&&!Array.isArray(e)&&`width`in e?e.width:void 0),open:!!(e&&typeof e==`object`&&!Array.isArray(e)&&`open`in e&&e.open===!0)})}));function li(e,t,n){let r=(0,Q.useRef)(n);r.current=n,(0,Q.useLayoutEffect)(()=>e?ar.register(t,()=>r.current()):void 0,[e,t])}var $=s();function ui({preferredWidth:e,onWidthChange:t,availableWidth:n,presentation:r,children:i,context:a,side:o=`right`,layoutId:s=`chat`,conversationHeaderInset:c=0}){let{t:u}=l(),d=(0,Q.useRef)(()=>{});(0,Q.useEffect)(()=>()=>d.current(),[]);let f=r===`aside`,p=r===`content`,m=br(e,n),h=br(720,n),g=e=>t(Math.max(280,Math.min(h,e))),_=n=>{if(n.button!==0)return;d.current(),n.preventDefault(),n.currentTarget.focus(),n.currentTarget.setPointerCapture(n.pointerId);let r=n.clientX,i=e=>g(m+(e.clientX-r)*(o===`left`?1:-1)),a=()=>{window.removeEventListener(`pointermove`,i),window.removeEventListener(`pointerup`,a),window.removeEventListener(`pointercancel`,s),window.removeEventListener(`keydown`,c)},s=()=>{t(e),a()},c=e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),s())};d.current=a,window.addEventListener(`pointermove`,i),window.addEventListener(`pointerup`,a,{once:!0}),window.addEventListener(`pointercancel`,s,{once:!0}),window.addEventListener(`keydown`,c)},v=(0,$.jsx)(`div`,{id:`${s}-conversation`,"data-workspace-conversation":!0,inert:p,className:p?`hidden`:`min-h-0 min-w-0 flex-1 overflow-hidden`,style:f&&c?{paddingTop:c}:void 0,children:i},`conversation`),y=f?(0,$.jsx)(`div`,{role:`separator`,tabIndex:0,"aria-orientation":`vertical`,"aria-label":u(`chat:sessionContext.resize`),title:u(`chat:sessionContext.resizeHint`),"aria-controls":`${s}-conversation ${s}-content`,"aria-valuemin":280,"aria-valuemax":h,"aria-valuenow":m,onPointerDown:_,onDoubleClick:()=>t(360),onKeyDown:e=>{if(![`ArrowLeft`,`ArrowRight`,`Home`,`End`,`Enter`].includes(e.key))return;if(e.preventDefault(),e.key===`Enter`){t(360);return}let n=e.shiftKey?64:16;g(e.key===`Home`?280:e.key===`End`?h:m+(e.key===`ArrowRight`?n:-n)*(o===`left`?1:-1))},className:`relative w-2 shrink-0 cursor-col-resize touch-none select-none outline-none after:absolute after:top-1/2 after:left-1/2 after:h-9 after:w-[3px] after:-translate-1/2 after:rounded-full after:bg-stroke-strong after:transition-colors after:duration-[var(--d-fast)] hover:after:bg-focus active:after:bg-focus focus-visible:after:bg-focus focus-visible:after:ring-3 focus-visible:after:ring-focus-ring`},`separator`):null,b=(0,$.jsx)(`div`,{id:`${s}-content`,className:f?`h-full min-h-0 shrink-0 overflow-hidden`:p?`h-full min-h-0 min-w-0 flex-1 overflow-hidden`:`hidden`,style:f?{width:m}:void 0,children:(f||p)&&a},`resource`);return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{id:`${s}-context-layout`,"data-workspace-layout":!0,className:`flex h-full min-h-0 min-w-0 flex-1 overflow-hidden`,children:o===`left`?[b,y,v]:[v,y,b]}),r===`sheet`&&a]})}function di({sessionId:e,streaming:t,completed:n,runStartedAt:r,enabled:i,open:a,onReveal:o}){let s=(0,Q.useRef)(null),c=(0,Q.useRef)(o);(0,Q.useLayoutEffect)(()=>{c.current=o},[o]),(0,Q.useEffect)(()=>{let o=s.current,l={sessionId:e,streaming:t,completed:n,runStartedAt:r};if(s.current=l,!i||a||!hr(o,l))return;let u=new AbortController,d=!0;return X.getSessionFileChanges(e,{signal:u.signal}).then(({files:e})=>{d&&vr(o,l,e)&&c.current()}).catch(()=>{}),()=>{d=!1,u.abort()}},[n,i,a,r,e,t])}var fi=`pisper:task-content-requested`,pi=[`changes`,`terminal`,`processes`,`sources`,`browser`];function mi(e){return!e||typeof e!=`object`||!(`kind`in e)?null:pi.find(t=>t===e.kind)||null}function hi({sessionId:e,cwd:t,taskName:n,sources:r,mobile:i,streaming:a}){let{t:o}=l(),s=Ar(e),c=kr(),[u,d]=(0,Q.useState)(!1),f=(0,Q.useRef)(null),p=(0,Q.useRef)(!1),m=k(e=>e.capabilities),h=O(m,`vcs`),_=g({enabled:h,queryKey:[`task-project-changes`,e,t,a],queryFn:({signal:t})=>X.getVcsChanges(e,{signal:t})}),v=(0,Q.useMemo)(()=>Le(_.data?.diff||``,_.data?.files.map(e=>e.path)||[],_.data?.diffTruncated),[_.data]),y=()=>xr.getState().update(e,`new`,{type:`workspace`,summaryOpen:!1}),b=()=>document.getElementById(`task-${e}-summary-toggle`)?.focus();(0,Q.useEffect)(()=>{i||f.current?.focus()},[i]);let x=(t,n=``)=>{let r=xr.getState();if(r.update(e,t,{type:`open`,kind:t})===`limit`){d(!0);return}p.current=!0;let i=xr.getState().sessions[e]?.activeId;n&&i&&r.update(e,t,{type:`view`,id:i,patch:t===`sources`?{selectedSourceId:n,query:``,filter:``}:{expandedProcesses:[n],filter:``}})};li(!i,300,()=>{y(),b()});let S=`w-full justify-start gap-2 px-2 font-normal text-content`,C=`ml-auto shrink-0 text-xs text-content-muted tabular-nums`,w=(0,$.jsxs)($.Fragment,{children:[u&&(0,$.jsx)(`p`,{role:`alert`,className:`px-2 pb-1 text-xs text-danger`,children:o(`chat:sessionContext.pageLimit`)}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-start gap-2 border-b border-stroke-soft px-2 pt-1 pb-2`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`p`,{className:`truncate font-mono text-xs text-content-muted`,title:t,children:t.split(/[\\/]/).filter(Boolean).at(-1)||t}),(0,$.jsx)(`p`,{className:`mt-0.5 truncate text-sm font-medium text-content`,children:n})]}),(0,$.jsx)(Y,{variant:`ghost`,size:`icon`,className:`max-[650px]:size-11`,"aria-label":o(`chat:workbench.closeSummary`),onClick:()=>{y(),b()},children:(0,$.jsx)(Dt,{size:16})})]}),(0,$.jsxs)(`section`,{className:`border-b border-stroke-soft py-1`,children:[(0,$.jsxs)(Y,{variant:`ghost`,className:`${S} h-auto min-h-8 whitespace-normal text-left`,disabled:!h,onClick:()=>x(`changes`),children:[(0,$.jsx)(re,{size:16,className:`text-content-muted`}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1`,children:o(`chat:workbench.projectChanges`)}),(0,$.jsx)(`span`,{className:C,children:h?_.isPending?`…`:_.isError||_.data?.error?o(`chat:workbench.unavailable`):_.data?.isRepo?_.data.files.length:`—`:o(`chat:workbench.unavailable`)})]}),(_.isError||_.data?.error)&&(0,$.jsx)(`p`,{role:`alert`,className:`px-2 py-1 text-xs text-danger`,children:o(`chat:workbench.changesFailed`)}),_.data?.isRepo&&!_.isError&&!_.data.error&&(0,$.jsxs)(`p`,{className:`px-2 pb-1 pl-8 font-mono text-xs tabular-nums text-content-muted`,children:[v.partial?`${o(`chat:workbench.partialCounts`)} `:``,(0,$.jsxs)(`span`,{className:`text-success`,children:[`+`,v.added]}),` `,(0,$.jsxs)(`span`,{className:`text-danger`,children:[`−`,v.removed]})]}),(0,$.jsxs)(Y,{variant:`ghost`,className:S,onClick:()=>x(`files`),children:[(0,$.jsx)(Te,{size:16,className:`text-content-muted`}),o(`chat:workbench.taskSnapshots`)]})]}),(0,$.jsxs)(`section`,{className:`border-b border-stroke-soft py-1`,children:[(0,$.jsxs)(Y,{variant:`ghost`,className:S,onClick:()=>x(`processes`),children:[(0,$.jsx)(`span`,{children:o(`terminal:workspace.processes`)}),(0,$.jsx)(`span`,{className:C,children:s.length})]}),!c&&(0,$.jsx)(`p`,{className:`px-2 pb-1 text-xs text-content-muted`,children:o(`terminal:workspace.nativeOnly`)}),s.slice(0,3).map(e=>(0,$.jsxs)(Y,{variant:`ghost`,className:`${S} min-w-0`,onClick:()=>x(`processes`,e.id),children:[e.status===`running`?(0,$.jsx)(Zt,{className:`size-3.5`}):(0,$.jsx)(P,{size:15,className:`text-content-muted`}),(0,$.jsx)(`span`,{className:`min-w-0 flex-1 truncate text-left font-mono text-xs`,children:e.profileId}),(0,$.jsx)(`span`,{className:C,children:e.status===`running`?o(`terminal:workspace.running`):e.status===`exited`?o(`terminal:workspace.exited`):o(`chat:workbench.otherState`)})]},e.id))]}),(0,$.jsxs)(`section`,{className:`pt-1`,children:[(0,$.jsxs)(Y,{variant:`ghost`,className:S,onClick:()=>x(`sources`),children:[(0,$.jsx)(`span`,{children:o(`chat:workbench.sources`)}),(0,$.jsx)(`span`,{className:C,children:r.length})]}),r.slice(0,3).map(e=>(0,$.jsxs)(Y,{variant:`ghost`,className:`${S} min-w-0`,onClick:()=>x(`sources`,e.id),children:[(0,$.jsx)(nt,{size:15,className:`text-content-muted`}),(0,$.jsx)(`span`,{className:`truncate font-mono text-xs`,children:e.name||o(`chat:chatMessage.fileAttachment`)})]},e.id)),(0,$.jsx)(Y,{variant:`ghost`,className:`${S} text-content-muted`,onClick:()=>x(`sources`),children:o(`chat:workbench.viewAll`)})]})]});return i?(0,$.jsx)(Tn,{open:!0,onOpenChange:e=>{e||y()},children:(0,$.jsxs)(Sn,{side:`bottom`,showCloseButton:!1,"aria-describedby":void 0,className:`max-h-[80dvh] overflow-y-auto rounded-t-2xl p-3 pb-[max(16px,var(--pisper-safe-area-bottom))] [&_button]:min-h-11`,style:{left:`calc(44px + var(--pisper-safe-area-left, 0px))`,right:`var(--pisper-safe-area-right, 0px)`},onCloseAutoFocus:e=>{e.preventDefault(),p.current||b()},children:[(0,$.jsx)(Cn,{className:`sr-only`,children:o(`chat:workbench.summary`)}),w]})}):(0,$.jsx)(`div`,{ref:f,tabIndex:-1,id:`task-${e}-summary`,role:`region`,"aria-label":o(`chat:workbench.summary`),onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),y(),b())},className:`absolute top-[52px] right-2 z-20 max-h-[calc(100%-64px)] w-80 max-w-[calc(100%-16px)] overflow-y-auto rounded-md bg-popover p-1 text-sm text-popover-foreground shadow-float`,children:w})}function gi(e){if(typeof e!=`string`||Array.from(e).some(e=>e.charCodeAt(0)<32))return``;let t=e.replace(/\\/g,`/`);return!t.startsWith(`/`)&&!/^[a-z]:\//i.test(t)?``:t.replace(/\/\.\//g,`/`).replace(/\/$/,``)||`/`}function _i(e){let t=[],n=new Set;for(let r of e)if(Array.isArray(r.attachments))for(let[e,i]of r.attachments.entries()){if(!i||typeof i!=`object`||Array.isArray(i))continue;let a=typeof i.id==`string`&&!i.id.startsWith(`path:`)&&i.id.length<=512&&!Array.from(i.id).some(e=>e.charCodeAt(0)<32)?i.id:``,o=gi(i.path),s=a?`asset`:o?`path`:`unresolved`,c=a?`asset:${a}`:o?`path:${o}`:`unresolved:${r.id}:${e}`;if(n.has(c))continue;n.add(c);let l=typeof i.name==`string`?i.name:o.split(`/`).pop()||a,u=typeof i.mimeType==`string`?i.mimeType:``,d={...a?{id:a,downloadUrl:`/api/assets/${encodeURIComponent(a)}/download`}:{},...o?{id:a||`path:${o}`,path:o}:{},name:l,mimeType:u,...typeof i.size==`number`&&Number.isFinite(i.size)&&i.size>=0?{size:i.size}:{},...typeof i.text==`string`?{text:i.text.slice(0,4e5)}:{}};t.push({id:c,name:l,method:s,messageId:r.id,attachment:d,available:s!==`unresolved`||typeof i.text==`string`,kind:u.startsWith(`image/`)?`image`:u.startsWith(`text/`)?`text`:`file`})}return t}function vi({width:e,mobile:t,contentOpen:n}){return n?t||e<660?`content`:`split`:`conversation`}var yi=(0,Q.lazy)(()=>t(()=>import(`./SessionContextPanel-aH8brkyg.js`).then(e=>({default:e.SessionContextPanel})),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128])));function bi({sessionId:e,messages:t,taskName:n,cwd:r,panelId:i,active:a,mobile:o,plan:s,streaming:c,completed:u,runStartedAt:d,plansAvailable:f,requestConfirm:p,children:m}){let{t:h}=l(),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)(null),b=(0,Q.useMemo)(()=>({headerHost:g,sourceActionHost:v,setSourceActionHost:y}),[g,v]),x=(0,Q.useMemo)(()=>_i(t),[t]),S=(0,Q.useRef)(ci.getState().width).current,C=(0,Q.useRef)(null),[w,T]=(0,Q.useState)(0),E=(0,Q.useMemo)(()=>_r(),[]),D=xr(t=>t.sessions[e])||E,O=xr(e=>e.update);(0,Q.useLayoutEffect)(()=>{D.contentWidth??O(e,`new`,{type:`workspace`,contentWidth:S})},[D.contentWidth,e,S,O]),(0,Q.useLayoutEffect)(()=>{let e=C.current;if(!e)return;let t=()=>T(e.clientWidth);t();let n=null,r=new ResizeObserver(()=>{n!==null&&cancelAnimationFrame(n),n=requestAnimationFrame(()=>{n=null,t()})});return r.observe(e),()=>{r.disconnect(),n!==null&&cancelAnimationFrame(n)}},[]);let k=vi({width:w,mobile:o,contentOpen:D.contentOpen&&D.pages.length>0});di({sessionId:e,streaming:c,completed:u,runStartedAt:d,enabled:!0,open:D.contentOpen,onReveal:()=>O(e,`files`,{type:`open`,kind:`files`})}),(0,Q.useEffect)(()=>{if(!a)return;let t=t=>{let n=mi(t.detail);n&&O(e,n,{type:`open`,kind:n})};return window.addEventListener(fi,t),()=>window.removeEventListener(fi,t)},[a,e,O]);let A=()=>{window.dispatchEvent(new Event(un)),O(e,`files`,{type:`workspace`,contentOpen:!1}),requestAnimationFrame(()=>(document.getElementById(`task-${e}-new-content-tab`)||document.getElementById(`task-${e}-more`))?.focus())};li(a&&k===`content`,100,A);let j=D.contentOpen&&D.pages.length>0&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`div`,{role:`status`,className:`p-4 text-sm text-content-muted`,children:h(`chat:focusSession.gitLoading`)}),children:(0,$.jsx)(yi,{panelId:`${i}-context`,compact:!1,embedded:!0,active:a,sessionId:e,cwd:r,sources:x,tab:D.pages.find(e=>e.id===D.activeId)?.kind||`files`,plan:s,streaming:c,plansAvailable:f,requestConfirm:p,onTabChange:()=>{},onClose:A,onBack:A})});return(0,$.jsx)(Ee.Provider,{value:b,children:(0,$.jsxs)(`div`,{ref:C,id:`task-${e}-workspace`,tabIndex:-1,"data-task-workspace":e,"data-active":a,className:`relative flex h-full min-h-0 min-w-0 flex-col overflow-hidden bg-panel`,children:[(0,$.jsx)(`div`,{ref:_,className:k===`split`?`@container absolute left-0 top-0 z-10`:`@container shrink-0`,style:k===`split`?{width:`calc(100% - ${br(D.contentWidth??S,w)+8}px)`}:void 0,"data-task-header":!0}),(0,$.jsx)(ui,{preferredWidth:D.contentWidth??S,onWidthChange:t=>{O(e,`new`,{type:`workspace`,contentWidth:t}),ci.getState().setWidth(t)},layoutId:i,availableWidth:w,conversationHeaderInset:48,presentation:k===`split`?`aside`:k===`content`?`content`:`closed`,context:j,children:m}),a&&D.summaryOpen&&(0,$.jsx)(hi,{sessionId:e,cwd:r,taskName:n,sources:x,mobile:o,streaming:c})]})})}function xi(e,t){return e.open===t?e:{open:t,leaving:!t}}function Si(e){return e.leaving?{open:e.open,leaving:!1}:e}function Ci(e){return e.open||e.leaving}function wi(e,t=400){let[n,r]=(0,Q.useState)(()=>({open:e,leaving:!1})),i=n;n.open!==e&&(i=xi(n,e),r(i));let a=i.leaving,o=(0,Q.useCallback)(()=>r(Si),[]);return(0,Q.useLayoutEffect)(()=>{if(!a)return;if(cr()){o();return}let e=window.setTimeout(o,t);return()=>window.clearTimeout(e)},[t,o,a]),{mounted:Ci(i),leaving:a,finish:o}}function Ti(e){return[`running`,`waiting_approval`].includes(String(e.status||``))}function Ei(e,t){return t(e===`running`?`chat:workflowRun.running`:e===`waiting_approval`?`chat:workflowRun.waitingApproval`:e===`completed`?`chat:workflowRun.completed`:e===`failed`?`chat:workflowRun.failed`:e===`cancelled`?`chat:workflowRun.stopped`:`chat:workflowRun.interrupted`)}function Di({sessionId:e,empty:t=null}){let{t:n}=l(),[r,i]=(0,Q.useState)([]),[a,o]=(0,Q.useState)(``),s=(0,Q.useCallback)(async()=>{try{let t=await X.getSessionWorkflowRuns(e);i(t.runs||[])}catch{}},[e]);if((0,Q.useEffect)(()=>{s();let e=window.setInterval(s,1500);return()=>window.clearInterval(e)},[s]),!r.length)return t;let c=`session-workflow-context grid min-w-0 gap-1 border-b border-stroke-soft pb-1.5 [&_strong]:text-xs [&_strong]:font-medium [&_strong]:text-content-muted [&_p]:max-h-[84px] [&_p]:overflow-auto [&_p]:text-xs [&_p]:leading-relaxed [&_p]:whitespace-pre-wrap [&_p]:text-content-secondary [&_p]:[overflow-wrap:anywhere] [&_pre]:max-h-[84px] [&_pre]:overflow-auto [&_pre]:rounded-xs [&_pre]:bg-code [&_pre]:px-1.5 [&_pre]:py-1 [&_pre]:font-mono [&_pre]:text-xs [&_pre]:leading-relaxed [&_pre]:whitespace-pre-wrap [&_pre]:text-content-secondary [&_pre]:[overflow-wrap:anywhere]`;return(0,$.jsx)(`div`,{className:`flex max-h-[210px] flex-col overflow-auto rounded-md border border-stroke bg-panel`,children:[...r].sort((e,t)=>Date.parse(t.startedAt)-Date.parse(e.startedAt)).slice(0,5).map(e=>{let t=a===e.id,r=Math.round((Number(e.completedNodes)||0)/Math.max(1,Number(e.totalNodes)||1)*100);return(0,$.jsxs)(`div`,{className:`session-workflow-run border-b border-stroke-soft last:border-b-0 ${e.status}`,children:[(0,$.jsxs)(`button`,{className:`session-workflow-summary grid w-full cursor-pointer grid-cols-[20px_minmax(120px,1fr)_minmax(80px,160px)_14px] items-center gap-2.5 border-0 px-3 py-2 text-left text-content transition-colors duration-(--d-fast) hover:bg-surface-subtle focus-visible:-outline-offset-2 max-[650px]:min-h-11 max-[650px]:grid-cols-[20px_minmax(0,1fr)_14px] max-[650px]:[&_[data-slot='progress']]:col-[2/4] [&_[data-slot='progress']]:h-1 [&_>_span:nth-child(2)]:flex [&_>_span:nth-child(2)]:min-w-0 [&_>_span:nth-child(2)]:flex-col [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_small]:tabular-nums [&_strong]:truncate [&_strong]:text-sm [&_strong]:font-medium ${t?`bg-surface-subtle`:`bg-transparent`}`,"aria-expanded":t,onClick:()=>o(t?``:e.id),children:[(0,$.jsx)(`span`,{className:`grid size-5 place-items-center rounded-xs ${e.status===`completed`?`bg-success-soft text-success`:e.status===`failed`?`bg-danger-soft text-danger`:e.status===`waiting_approval`?`bg-warning-soft text-warning-strong`:`bg-surface-muted text-content-muted`}`,children:e.status===`running`?(0,$.jsx)(Zt,{className:`size-3.5`}):e.status===`completed`?(0,$.jsx)(z,{size:12}):e.status===`failed`?(0,$.jsx)(Dt,{size:12}):(0,$.jsx)(Tt,{size:12})}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.workflowName}),(0,$.jsxs)(`small`,{children:[Ei(e.status,n),` · v`,e.workflowRevision||1]})]}),(0,$.jsx)(Bt,{value:e.status===`completed`?100:r}),(0,$.jsx)(H,{size:14,className:`text-content-muted transition-transform duration-(--d-fast) ${t?`rotate-90`:``}`})]}),t&&(0,$.jsxs)(`div`,{className:`session-workflow-detail flex flex-col gap-1.5 border-t border-stroke-soft bg-surface-subtle py-2 pr-3 pl-[42px] max-[650px]:pl-3 [&_>_p]:text-xs [&_>_p]:text-content-muted`,children:[e.sourceMessage&&(0,$.jsxs)(`div`,{className:c,children:[(0,$.jsx)(`strong`,{children:n(`chat:workflowRun.request`)}),(0,$.jsx)(`p`,{children:e.sourceMessage})]}),e.inputs&&Object.keys(e.inputs).length>0&&(0,$.jsxs)(`div`,{className:c,children:[(0,$.jsx)(`strong`,{children:n(`chat:workflowRun.inputs`)}),(0,$.jsx)(`pre`,{children:JSON.stringify(e.inputs,null,2)})]}),(e.nodes||[]).map(t=>(0,$.jsxs)(`div`,{className:`session-workflow-node grid min-h-6 grid-cols-[15px_minmax(0,1fr)_auto] items-center gap-1.5 text-content-muted [&.completed]:text-success [&.failed]:text-danger [&_>_div]:flex [&_>_div]:gap-1 [&_>_span]:flex [&_>_span]:min-w-0 [&_>_span]:flex-col [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_strong]:text-xs [&_strong]:font-medium [&_strong]:text-content ${t.status}`,children:[t.status===`completed`?(0,$.jsx)(z,{size:13}):t.status===`failed`?(0,$.jsx)(W,{size:13}):t.status===`running`?(0,$.jsx)(Zt,{className:`size-3.5`}):(0,$.jsx)(gt,{size:11}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:t.label}),(t.error||t.summary)&&(0,$.jsx)(`small`,{children:t.error||t.summary})]}),t.status===`waiting_approval`&&(0,$.jsxs)(`div`,{children:[(0,$.jsx)(Y,{size:`xs`,onClick:async()=>{await X.resolveWorkflowApproval(e.id,t.id,!0),await s()},children:n(`chat:workflowRun.approve`)}),(0,$.jsx)(Y,{size:`xs`,variant:`destructive`,onClick:async()=>{await X.resolveWorkflowApproval(e.id,t.id,!1),await s()},children:n(`chat:workflowRun.reject`)})]})]},t.id)),(e.error||e.summary)&&(0,$.jsx)(`p`,{children:e.error||e.summary}),Ti(e)&&(0,$.jsxs)(Y,{size:`xs`,variant:`destructive`,className:`self-start`,onClick:async()=>{await X.stopWorkflowRun(e.id),await s()},children:[(0,$.jsx)(gt,{"data-icon":`inline-start`}),n(`chat:workflowRun.stop`)]})]})]},e.id)})})}function Oi(e,t){let[n,r]=(0,Q.useState)(()=>Date.now());(0,Q.useEffect)(()=>{if(!t)return;r(Date.now());let e=setInterval(()=>r(Date.now()),1e3);return()=>clearInterval(e)},[t]);let i=e?Date.parse(e):NaN;return t&&Number.isFinite(i)?Math.max(0,n-i):null}function ki(e,t){xr.getState().update(e,`side-chat`,{type:`open`,kind:`side-chat`}),t?.show(`side-chat`)}function Ai(e,t){let{t:n,language:i}=l(),a=(0,Q.useContext)(Ye),[o,s]=(0,Q.useState)(!1),[c,u]=(0,Q.useState)(!1),[d,f]=(0,Q.useState)(!1),p=k(e=>e.capabilities.features.sessionExport===!0),m=e.name||n(`navigation:pageHeader.newChat`),{notify:h}=t,g=r(),_=e.botId,v=async()=>{if(!c){u(!0);try{await Dn(e.id,{archived:!0}),h(n(`board:action.archived`,{title:m})),a?.onArchived?.(e.id)}catch{h(n(`board:action.failed`),`error`)}finally{u(!1)}}},y=async()=>{if(!d){f(!0);try{let t=await X.exportSessionMarkdown(e.id,i),r=URL.createObjectURL(t),a=document.createElement(`a`);a.href=r,a.download=`${m.replace(/[\\/:*?"<>|\p{Cc}]/gu,`-`).slice(0,80)||`session`}.md`,a.click(),window.setTimeout(()=>URL.revokeObjectURL(r),1e3),h(n(`chat:sessionMenu.exported`,{title:m}))}catch{h(n(`chat:sessionMenu.exportFailed`),`error`)}finally{f(!1)}}},b=typeof t.contextPercent==`number`&&Number.isFinite(t.contextPercent)?Math.round(Math.min(100,Math.max(0,t.contextPercent))):null,x=[..._?[]:[{key:`rename`,icon:ct,label:n(`chat:sessionMenu.rename`),onSelect:t.onRename}],...t.onSideChat?[{key:`side-chat`,icon:at,label:n(`board:inspector.sideChat`),onSelect:t.onSideChat,marker:`session-side-chat`}]:[],...p?[{key:`export`,icon:ti,label:n(`chat:sessionMenu.exportMarkdown`),onSelect:()=>void y(),disabled:d,marker:`session-export`}]:[],...e.machine||_?[]:[{key:`workspace`,icon:Ue,label:n(`board:session.moveWorkspace`),onSelect:t.onWorkspace,disabled:t.workspaceDisabled,separator:!0}],{key:`compact`,icon:oi,label:n(`chat:sessionMenu.compactContext`),onSelect:()=>t.onCompact?.(),disabled:t.compactDisabled||!t.onCompact,trailing:b===null?void 0:`${b}%`,trailingTitle:b===null?void 0:n(`board:session.contextUsage`,{percent:b})},...t.workflowsAvailable?[{key:`workflows`,icon:Tt,label:n(`chat:sessionMenu.workflowRuns`),onSelect:()=>s(!0)}]:[],{key:`voice`,icon:Zr,label:n(`chat:sessionMenu.voiceMode`),onSelect:t.onVoiceMode},_?{key:`delete-bot`,icon:St,label:n(`chat:sessionMenu.deleteBot`),onSelect:()=>g(`/bots/${encodeURIComponent(_)}?action=delete`),separator:!0,marker:`session-delete-bot`}:{key:`archive`,icon:F,label:n(`board:card.archive`),onSelect:()=>void v(),disabled:c,separator:!0}];return{entries:x,items:(0,$.jsxs)($.Fragment,{children:[x.map(e=>{let t=e.icon,n=e.marker?{[`data-${e.marker}`]:!0}:{},r=(0,$.jsxs)(jt,{disabled:e.disabled,onSelect:e.onSelect,...n,children:[(0,$.jsx)(t,{}),e.label,e.trailing&&(0,$.jsx)(Mt,{className:`font-mono tabular-nums`,title:e.trailingTitle,"data-session-context-usage":!0,children:e.trailing})]});return(0,$.jsxs)(Q.Fragment,{children:[e.separator&&(0,$.jsx)(At,{}),r]},e.key)}),t.extraItems&&(0,$.jsx)(At,{}),t.extraItems]}),dialog:(0,$.jsx)(Jn,{open:o,onOpenChange:s,children:(0,$.jsxs)(Gn,{className:`max-w-lg`,children:[(0,$.jsxs)(qn,{children:[(0,$.jsx)(Kn,{children:n(`board:session.workflowRuns`)}),(0,$.jsx)(Wn,{children:m})]}),o&&(0,$.jsx)(Di,{sessionId:e.id,empty:(0,$.jsx)(`p`,{className:`py-6 text-center text-sm text-content-muted`,children:n(`board:session.workflowRunsEmpty`)})})]})})}}var ji=(0,Q.lazy)(()=>t(()=>import(`./SessionInspector-2ar9Ti-b.js`).then(e=>({default:e.SessionInspector})),__vite__mapDeps([129,1,3,4,5,2,6,7,8,9,23,24,10,11,12,13,14,15,16,18,130,20,22,19,25,26,27,21,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,17,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,131,122,123,124,132,126,127,128,133,134]))),Mi=[];function Ni(e){switch(e){case`changes`:return{tab:`changes`,changesView:`workspace`};case`files`:return{tab:`changes`,changesView:`session`};case`terminal`:case`processes`:return{tab:`terminal`,terminalView:e};case`sources`:return{tab:`files`};case`browser`:return{tab:`preview`};case`plan`:return{tab:`plan`};case`side-chat`:return{tab:`side-chat`};default:return null}}function Pi(e){if(!(e instanceof HTMLElement)||e===document.body||e.closest(`[data-inspector-sheet]`))return null;let t=e.closest(`[role="menu"]`);if(!t)return e;let n=t.getAttribute(`aria-labelledby`);return n?document.getElementById(n):null}var Fi=`a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), iframe, [tabindex]:not([tabindex="-1"])`;function Ii(e){if(e.key!==`Tab`||e.altKey||e.ctrlKey||e.metaKey)return;let t=[...e.currentTarget.querySelectorAll(Fi)].filter(e=>e.getClientRects().length>0);if(!t.length)return;let n=t[0],r=t[t.length-1],i=document.activeElement;(e.shiftKey?i===n:i===r)&&(e.preventDefault(),(e.shiftKey?r:n).focus())}function Li(e){let t=e?.items??[];return t.length?{done:t.filter(e=>e.status===`completed`).length,total:t.length}:null}function Ri({sessionId:e,messages:t,cwd:n,active:r,plan:i,goal:a=null,team:o=null,activity:s=Mi,planTab:c,streaming:u,completed:d,runStartedAt:f,requestConfirm:p,remoteMachine:m=!1,children:h}){let{t:g}=l(),_=(0,Q.useContext)(Ye),v=!!(_?.phone??null),y=v||!!(_?.compact||_?.overlayOnly),[b,x]=(0,Q.useState)(null),[S,C]=(0,Q.useState)(null),w=(0,Q.useMemo)(()=>({headerHost:b,sourceActionHost:S,setSourceActionHost:C}),[b,S]),T=(0,Q.useMemo)(()=>_i(t),[t]),E=Mr(e=>e.open),D=Mr(e=>e.pinned),O=Mr(e=>e.setOpen),k=Mr(e=>e.widthPercent),A=Mr(e=>e.width),j=Mr(e=>e.setWidth),M=Mr(e=>e.resetWidth),[N,P]=(0,Q.useState)(!1);(0,Q.useEffect)(()=>{y||P(!1)},[y]);let F=y?N:E,I=wi(v&&F),L=v&&I.leaving,R=(0,Q.useRef)(null),z=`session-${e}-inspector`,B=(0,Q.useRef)(null),[V,H]=(0,Q.useState)(0);(0,Q.useLayoutEffect)(()=>{let e=B.current;if(!e)return;let t=()=>H(e.clientWidth);t();let n=new ResizeObserver(t);return n.observe(e),()=>n.disconnect()},[]);let U=jr({widthPercent:k,width:A},V||window.innerWidth),[W,ee]=(0,Q.useState)(0);(0,Q.useLayoutEffect)(()=>{if(!b)return;let e=()=>ee(b.offsetHeight);e();let t=new ResizeObserver(e);return t.observe(b),()=>t.disconnect()},[b]);let te=(0,Q.useRef)(null),[ne,re]=(0,Q.useState)(!1),[ie,ae]=(0,Q.useState)(!1),oe=(0,Q.useCallback)((e,t=!1)=>{if(window.dispatchEvent(new Event(un)),v&&e){let e=Pi(document.activeElement);e&&(R.current=e)}re(e),ae(e&&t),y?P(e):O(e)},[y,O,v]),ce=(0,Q.useCallback)((e,t)=>{Mr.getState().setTab(e),oe(!0,t)},[oe]),G=(0,Q.useCallback)(e=>ce(e,!0),[ce]),le=(0,Q.useCallback)(()=>{let e=document.activeElement,t=!!(e&&te.current?.contains(e))||y&&!v&&(!e||e===document.body);oe(!1),t&&requestAnimationFrame(()=>document.querySelector(`[aria-controls="${CSS.escape(z)}"][data-inspector-toggle]`)?.focus())},[y,z,oe,v]),ue=(0,Q.useCallback)(()=>F?le():oe(!0,!0),[le,F,oe]),de=(0,Q.useCallback)(t=>{t.preventDefault();let n=R.current;R.current=null,((n?.isConnected?n:null)??document.querySelector(`[data-session-changes][aria-controls="${CSS.escape(z)}"]`)??document.getElementById(`task-${e}-more`))?.focus({preventScroll:!0})},[z,e]),fe=v?`sheet`:y?`overlay`:`aside`,pe=(0,Q.useMemo)(()=>({open:F,mode:fe,panelId:z,toggle:ue,show:G}),[F,fe,z,G,ue]),me=(0,Q.useCallback)(e=>{let t=Ni(e);if(!t)return;let n=Mr.getState();t.terminalView&&n.setTerminalView(t.terminalView),t.changesView&&n.setChangesView(t.changesView),ce(t.tab,!1)},[ce]);(0,Q.useEffect)(()=>xr.subscribe((t,n)=>{let r=t.sessions[e],i=n.sessions[e];if(!r||r===i||!r.contentOpen)return;let a=r.pages.find(e=>e.id===r.activeId);if(!a)return;let o=i?.pages.find(e=>e.id===i.activeId);(r.activeId!==i?.activeId||!i?.contentOpen||a.kind===`browser`&&a.url!==o?.url)&&me(a.kind)}),[me,e]),(0,Q.useEffect)(()=>{if(!r)return;let t=t=>{let n=mi(t.detail);n&&xr.getState().update(e,n,{type:`open`,kind:n})};return window.addEventListener(fi,t),()=>window.removeEventListener(fi,t)},[r,e]),(0,Q.useEffect)(()=>{if(!r)return;let t=t=>{let n=t.detail;n===`side-chat`?ki(e,pe):n===`tree`&&B.current?.querySelector(`[data-session-branches]`)?.click()};return window.addEventListener(on,t),()=>window.removeEventListener(on,t)},[r,pe,e]),di({sessionId:e,streaming:u,completed:d,runStartedAt:f,enabled:!y,open:F,onReveal:()=>me(`files`)});let K=gn(e=>e.bindings.toggleInspector);(0,Q.useEffect)(()=>{if(!r)return;let e=e=>{!yn(e,K)||hn(e)||_n(e)&&e.key.length===1||(e.preventDefault(),ue())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,K,ue]),li(r&&y&&N,100,le),li(r&&!y&&E&&!D,100,le);let he=(0,Q.useRef)(()=>{});(0,Q.useEffect)(()=>()=>he.current(),[]);let q=e=>{if(e.button!==0)return;he.current(),e.preventDefault(),e.currentTarget.focus(),e.currentTarget.setPointerCapture(e.pointerId);let t=e.clientX,n=U,r=e=>j(Nr(n-(e.clientX-t),V),V),i=()=>{window.removeEventListener(`pointermove`,r),window.removeEventListener(`pointerup`,i),window.removeEventListener(`pointercancel`,i)};he.current=i,window.addEventListener(`pointermove`,r),window.addEventListener(`pointerup`,i,{once:!0}),window.addEventListener(`pointercancel`,i,{once:!0})},ge=u?Li(i):null,_e=ne&&F&&!y,ve=y&&!v&&F&&V-420>=480?420:0,ye=(F||L)&&(0,$.jsx)(Q.Suspense,{fallback:(0,$.jsx)(`p`,{role:`status`,className:`p-4 text-sm text-content-muted`,children:g(`chat:focusSession.gitLoading`)}),children:(0,$.jsx)(ji,{panelId:z,sessionId:e,cwd:n,streaming:u,plan:i,goal:a,team:o,activity:s,planTab:c,sources:T,mode:fe,requestConfirm:p,onClose:le,onOpenComponents:_?.onOpenComponents,componentTabs:_?.componentTabs,autoFocus:fe===`overlay`&&ie,remoteMachine:m})});return(0,$.jsx)(Ee.Provider,{value:w,children:(0,$.jsx)(Ze.Provider,{value:pe,children:(0,$.jsxs)(`div`,{ref:B,id:`task-${e}-workspace`,tabIndex:-1,"data-task-workspace":e,"data-session-workspace":fe,"data-active":r,className:Xt(`relative flex h-full min-h-0 min-w-0 overflow-hidden bg-panel`,v&&`pb-[var(--pisper-safe-area-bottom)] [[data-mobile-keyboard='open']_&]:pb-0`),children:[(0,$.jsxs)(`div`,{className:`flex min-h-0 min-w-0 flex-1 flex-col`,"data-session-conversation":!0,children:[(0,$.jsx)(`div`,{ref:x,className:`@container shrink-0`,"data-task-header":!0}),ge&&(0,$.jsxs)(`div`,{className:`relative z-10 h-0.5 shrink-0 bg-surface-muted`,"data-plan-progress":!0,children:[(0,$.jsx)(`span`,{role:`progressbar`,"aria-label":g(`board:session.planLabel`,ge),"aria-valuemin":0,"aria-valuemax":ge.total,"aria-valuenow":ge.done,className:`absolute inset-0 origin-left bg-st-run transition-transform duration-(--d-base)`,style:{transform:`scaleX(${ge.done/ge.total})`}}),c&&(0,$.jsx)(`button`,{type:`button`,className:`absolute top-1.5 right-3 inline-flex h-6 items-center rounded-sm bg-panel px-2 font-mono text-xs text-content-secondary tabular-nums shadow-edge hover:bg-surface-hover hover:text-content focus-visible:outline-2 focus-visible:outline-focus pointer-coarse:h-11`,"aria-label":g(`board:session.planOpen`,{plan:g(`board:session.plan`,ge)}),"aria-controls":z,"data-plan-progress-open":!0,onClick:()=>G(`plan`),children:g(`board:session.plan`,ge)})]}),(0,$.jsx)(`div`,{className:Xt(`min-h-0 min-w-0 flex-1 overflow-hidden`,_e&&`animate-in duration-[220ms] ease-(--ease)`),"data-overlay-inset":ve||void 0,style:ve?{paddingRight:ve}:_e?{"--tw-enter-translate-x":`${U/2}px`}:void 0,children:h})]}),!y&&F&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{role:`separator`,tabIndex:0,"aria-orientation":`vertical`,"aria-label":g(`chat:sessionContext.resize`),title:g(`chat:sessionContext.resizeHint`),"aria-controls":z,"aria-valuemin":360,"aria-valuemax":Nr(1/0,V),"aria-valuenow":U,onPointerDown:q,onDoubleClick:M,onKeyDown:e=>{if(![`ArrowLeft`,`ArrowRight`,`Enter`].includes(e.key))return;if(e.preventDefault(),e.key===`Enter`){M();return}let t=e.shiftKey?64:16;j(Nr(U+(e.key===`ArrowLeft`?t:-t),V),V)},className:`relative -mr-1 w-2 shrink-0 cursor-col-resize touch-none select-none outline-none after:absolute after:inset-y-0 after:left-1/2 after:w-px after:bg-stroke-soft after:transition-colors after:duration-(--d-fast) hover:after:w-[3px] hover:after:-translate-x-px hover:after:bg-focus focus-visible:after:w-[3px] focus-visible:after:bg-focus`}),(0,$.jsxs)(`aside`,{ref:te,className:Xt(`flex h-full min-h-0 shrink-0 flex-col overflow-hidden border-l border-stroke-soft`,ne&&`animate-in slide-in-from-right duration-[220ms] ease-(--ease)`),style:{width:U},"data-inspector-aside":!0,"data-inspector-pinned":D||void 0,children:[(0,$.jsx)(`div`,{"aria-hidden":`true`,"data-window-drag-region":!0,"data-inspector-titlebar-gap":!0,className:`hidden h-[52px] shrink-0 [[data-custom-titlebar]_&]:block`}),(0,$.jsx)(`div`,{className:`min-h-0 flex-1`,children:ye})]})]}),y&&(F||L)&&(0,$.jsx)($.Fragment,{children:v?(0,$.jsx)(Tn,{open:F,onOpenChange:e=>!e&&le(),children:(0,$.jsxs)(Sn,{side:`bottom`,showCloseButton:!1,"data-inspector-sheet":!0,"data-sheet-leaving":L||void 0,onAnimationEnd:e=>{e.target===e.currentTarget&&!F&&I.finish()},onCloseAutoFocus:de,className:`gap-0 data-[side=bottom]:h-[min(86dvh,calc(100dvh-var(--pisper-safe-area-top)-48px))] overflow-hidden rounded-t-(--r-sheet) bg-panel p-0 pb-[var(--pisper-safe-area-bottom)]`,children:[(0,$.jsx)(Cn,{className:`sr-only`,children:g(`board:inspector.label`)}),(0,$.jsx)(wn,{className:`sr-only`,children:g(`board:phone.inspectorDescription`)}),(0,$.jsx)(se,{onDismiss:le}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col [&_[data-slot=segmented-control]]:h-11 [&_[data-slot=segmented-control-item]]:h-10 [&_[data-slot=segmented-control-item]]:px-3`,children:ye})]})}):(0,$.jsx)(`aside`,{ref:te,"data-inspector-overlay":!0,onKeyDown:Ii,className:Xt(`absolute right-0 bottom-0 z-30 max-w-[calc(100%-24px)] overflow-hidden border-l border-stroke bg-panel shadow-float`,`animate-in slide-in-from-right duration-[220ms] ease-(--ease)`),style:{width:420,top:W},children:ye})})]})})})}var zi=e(o(),1),Bi=(0,Q.createContext)(null),Vi=new Set([`queued`,`starting`,`running`]),Hi=new Set([`starting`,`running`,`stopping`]);function Ui(e){return typeof e==`string`?e.trim():``}function Wi(e,t,n){let r=new Map;for(let i of e){if(i?.type!==t)continue;let e=n(i);e&&r.set(String(e.id||r.size),e)}return[...r.values()]}function Gi({startedAt:e}){let[t,n]=(0,Q.useState)(()=>Date.now());(0,Q.useEffect)(()=>{let e=window.setInterval(()=>n(Date.now()),1e3);return()=>window.clearInterval(e)},[]);let r=Bn(e,null,t);return r?(0,$.jsx)(`span`,{className:`flex-none font-mono text-xs text-content-muted tabular-nums`,children:ge(r)}):null}function Ki(e,t,n){let{t:r}=l(),i=Ar(e);return[...t?Wi(n,`tool`,e=>e).filter(e=>e.status===`running`).map(e=>{let t=e.args||{};return{key:`tool:${String(e.id)}`,kind:`tool`,icon:(0,$.jsx)(Et,{size:14,"aria-hidden":`true`}),name:Ui(e.name)||r(`board:inspector.runningTool`),detail:Ui(t.command)||Ui(t.path)||Ui(t.file_path),startedAt:Ui(e.startedAt),status:r(`board:inspector.runningStatus`)}}):[],...Wi(n,`agent`,e=>e.agent&&typeof e.agent==`object`?e.agent:null).filter(e=>Vi.has(String(e.status))).map(e=>({key:`agent:${String(e.id)}`,kind:`agent`,agentId:Ui(e.id),icon:(0,$.jsx)(L,{size:14,"aria-hidden":`true`}),name:Ui(e.title)||Ui(e.taskName)||r(`board:inspector.runningAgent`),detail:Ui(e.message),startedAt:Ui(e.startedAt),status:e.status===`queued`?r(`board:inspector.runningQueued`):r(`board:inspector.runningStatus`)})),...i.filter(e=>Hi.has(e.status)).map(e=>({key:`terminal:${e.id}`,kind:`terminal`,icon:(0,$.jsx)(J,{size:14,"aria-hidden":`true`}),name:e.profileId||r(`board:inspector.terminal`),detail:e.cwd||``,status:e.status===`stopping`?r(`terminal:workspace.stopping`):r(`board:inspector.runningStatus`)}))]}function qi({row:e}){return(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{className:`mt-0.5 text-content-secondary`,children:e.icon}),(0,$.jsxs)(`span`,{className:`grid min-w-0 gap-0.5`,children:[(0,$.jsx)(`strong`,{className:`truncate text-[13px] font-medium text-content`,children:e.name}),e.detail&&(0,$.jsx)(`span`,{className:`min-w-0 truncate font-mono text-content-muted`,title:e.detail,children:e.detail})]}),(0,$.jsxs)(`span`,{className:`flex flex-none items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`text-content-muted`,children:e.status}),(0,$.jsx)(Gi,{startedAt:e.startedAt})]})]})}var Ji=`grid min-h-9 w-full min-w-0 grid-cols-[14px_minmax(0,1fr)_auto] items-start gap-2 rounded-sm px-2 py-1.5 text-left text-xs pointer-coarse:min-h-11`;function Yi({sessionId:e,streaming:t,activity:n,phoneButtonClass:r}){let{t:i}=l(),a=(0,Q.useContext)(Ze),[o,s]=(0,Q.useState)(!1),c=Ki(e,t,n),u=k(e=>e.capabilities.features.agentTranscripts);if(!c.length)return null;let d=i(`board:inspector.runningCount`,{count:c.length}),f=()=>{s(!1),Mr.getState().setTerminalView(`processes`),a?.show(`terminal`)},p=t=>{s(!1),Pr.getState().select(e,t),a?.show(`subagent`)};return(0,$.jsxs)(zt,{open:o,onOpenChange:s,children:[(0,$.jsx)(It,{asChild:!0,children:r?(0,$.jsxs)(`button`,{type:`button`,className:r,"aria-label":d,"data-session-running":c.length,children:[(0,$.jsx)(Fn,{status:`run`,className:`size-5`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`absolute top-1.5 right-1 grid h-4 min-w-4 place-items-center rounded-full bg-content px-1 text-[10px] leading-none font-semibold text-panel tabular-nums`,children:c.length>99?`99+`:c.length})]}):(0,$.jsxs)(Y,{type:`button`,variant:`ghost`,className:Xt(`h-8 flex-none gap-1.5 px-2 text-[13px] font-normal text-content-secondary tabular-nums hover:text-content pointer-coarse:h-11`,o&&`bg-surface-hover text-content`),"aria-label":d,title:d,"data-session-running":c.length,children:[(0,$.jsx)(Fn,{status:`run`,className:`size-3.5`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:d})]})}),(0,$.jsxs)(Rt,{align:`end`,className:`w-[380px] gap-1.5 p-1.5`,"aria-label":i(`board:inspector.running`),"data-session-running-list":!0,children:[(0,$.jsx)(Lt,{className:`px-2 pt-1 text-xs font-medium text-content-muted`,children:i(`board:inspector.running`)}),(0,$.jsx)(`ul`,{className:`m-0 flex list-none flex-col gap-px p-0`,children:c.map(e=>(0,$.jsx)(`li`,{"data-running-item":e.kind,children:e.kind===`agent`&&e.agentId&&u&&a?(0,$.jsx)(`button`,{type:`button`,className:Xt(Ji,`group cursor-pointer hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus`),"aria-label":i(`board:subagent.open`,{name:e.name}),onClick:()=>p(e.agentId??``),children:(0,$.jsx)(qi,{row:e})}):e.kind===`terminal`&&a?(0,$.jsx)(`button`,{type:`button`,className:Xt(Ji,`group cursor-pointer hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus`),"aria-label":i(`board:inspector.runningOpenProcess`,{name:e.name}),onClick:f,children:(0,$.jsx)(qi,{row:e})}):(0,$.jsx)(`div`,{className:Ji,children:(0,$.jsx)(qi,{row:e})})},e.key))}),c.some(e=>e.kind===`terminal`)&&a&&(0,$.jsxs)(`button`,{type:`button`,className:`flex h-8 w-full cursor-pointer items-center justify-between rounded-sm px-2 text-[13px] text-content-secondary hover:bg-surface-hover hover:text-content pointer-coarse:h-11`,onClick:f,children:[i(`board:inspector.runningAllProcesses`),(0,$.jsx)(H,{size:14,"aria-hidden":`true`})]}),(0,$.jsx)(`p`,{className:`m-0 border-t border-stroke-soft px-2 pt-2 pb-1 text-xs leading-relaxed text-content-faint`,children:i(`board:inspector.runningHint`)})]})]})}var Xi=(0,Q.lazy)(()=>t(()=>import(`./public-session-DS7Ggm0I.js`),__vite__mapDeps([135,1,2,3,4,5,6,7,8,9,136,18,35,34,36,33,137,105,138,76,24,77,12,13,14,15,16,139,140,10,11,37,127])));function Zi({session:e,cwd:t,streaming:r,treeAvailable:i,branches:a,onOpenTree:o,runningActivity:s=[],...u}){let d=e.machine?`${e.machine.name}:${e.machine.cwd}`:t,{t:f,language:p}=l(),m=(0,Q.useContext)(Ze),h=Ai(e,{...u,onSideChat:()=>ki(e.id,m)}),_=e.name||f(`navigation:pageHeader.newChat`),v=Mn(e.projectless?``:d,p),y=e.machine?jn(e.machine):v,b=g({queryKey:[`session-change-summary`,e.id,r],queryFn:()=>er(e.id),staleTime:1e4}),x=b.data?.status===`known`?b.data:null,S=x?.changedFiles??0,C=gn(e=>e.bindings.toggleInspector),w=gn(e=>e.bindings.sessionTree),T=xn(C),E=xn(w),D=S>0?f(`board:session.changes`,{count:S,added:x?.added??0,removed:x?.removed??0}):null,O=D?`${f(`board:inspector.label`)} · ${D}`:f(`board:inspector.label`),k=T?f(`board:session.withShortcut`,{label:O,shortcut:T}):O,A=a>0?f(`board:session.treeBranches`,{count:a}):f(`board:session.tree`),j=E?f(`board:session.withShortcut`,{label:A,shortcut:E}):A;return(0,$.jsxs)(`header`,{"data-session-header":!0,"data-focus-region":`header`,"data-window-drag-region":!0,className:`flex h-[52px] min-w-0 shrink-0 items-center gap-2 pr-3 pl-4 [[data-custom-titlebar]_&]:pr-[144px]`,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-1 items-center gap-1.5`,"data-window-drag-region":!0,children:[e.roomId&&(0,$.jsx)(Y,{asChild:!0,variant:`ghost`,size:`icon-sm`,className:`-ml-1`,children:(0,$.jsx)(n,{to:c(e.roomId),"data-session-back-room":!0,"aria-label":f(`board:session.backToRoom`),title:f(`board:session.backToRoom`),children:(0,$.jsx)(V,{})})}),e.botId&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Xi,{botId:e.botId,part:`avatar`})}),(0,$.jsxs)(Ft,{children:[(0,$.jsx)(Nt,{asChild:!0,children:(0,$.jsxs)(`button`,{type:`button`,id:`task-${e.id}-more`,"data-session-menu":!0,className:Xt(`group inline-flex h-8 min-w-0 shrink items-center gap-1 rounded-sm px-2 text-[15px] leading-6 font-medium text-content hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus data-[state=open]:bg-surface-hover pointer-coarse:h-11`,Gt),"aria-label":f(`board:session.titleMenu`,{title:_}),children:[(0,$.jsx)(`span`,{className:`truncate`,"data-session-title":!0,children:_}),(0,$.jsx)(B,{className:`size-3.5 flex-none text-content-muted`,"aria-hidden":`true`})]})}),(0,$.jsx)(Pt,{align:`start`,className:`min-w-60`,children:h.items})]}),(0,$.jsx)(`span`,{className:`min-w-0 max-w-[160px] flex-none truncate font-mono text-xs text-content-muted @max-[560px]:hidden`,title:d,"data-session-project":!0,children:y}),e.botId&&(0,$.jsx)(Q.Suspense,{fallback:null,children:(0,$.jsx)(Xi,{botId:e.botId,part:`settings`})}),i&&(0,$.jsxs)(Y,{type:`button`,variant:`ghost`,className:Xt(`h-7 min-w-7 flex-none gap-1 px-1.5 font-mono text-xs font-normal text-content-muted tabular-nums hover:text-content pointer-coarse:h-11 pointer-coarse:min-w-11`),"aria-haspopup":`dialog`,"aria-label":j,title:j,"aria-keyshortcuts":lr(w),"data-session-branches":a,onClick:e=>o(`branches`,e.currentTarget),children:[(0,$.jsx)(et,{className:`size-3.5`,"aria-hidden":`true`}),a>0&&(0,$.jsx)(`span`,{"aria-hidden":`true`,children:a})]})]}),(0,$.jsx)(Yi,{sessionId:e.id,streaming:r,activity:s}),m&&(0,$.jsx)(Y,{type:`button`,variant:`ghost`,className:Xt(`h-8 flex-none gap-1.5 px-2 text-[13px] font-normal text-content-secondary hover:text-content pointer-coarse:h-11`,D?``:`w-8 px-0 pointer-coarse:w-11`,m.open&&`bg-surface-hover text-content ring-1 ring-stroke ring-inset`),"data-inspector-toggle":!0,"data-session-changes":S,"aria-controls":m.panelId,"aria-expanded":m.open,"aria-label":k,title:k,"aria-keyshortcuts":lr(C),onClick:m.toggle,children:D&&x?(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(re,{className:`size-3.5`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,children:f(`board:session.changedFiles`,{count:S})}),(0,$.jsxs)(`span`,{className:`font-mono text-xs text-success tabular-nums`,"aria-hidden":`true`,children:[`+`,x.added??0]}),(0,$.jsxs)(`span`,{className:`font-mono text-xs text-danger tabular-nums`,"aria-hidden":`true`,children:[`−`,x.removed??0]})]}):(0,$.jsx)(ot,{"aria-hidden":`true`})}),h.dialog]})}var Qi=`outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus`,$i={1:`grid-cols-1`,2:`grid-cols-2`,3:`grid-cols-3`};function ea({count:e,children:t}){return(0,$.jsx)(`div`,{className:Xt(`grid gap-2 px-1 pb-2`,$i[e]??`grid-cols-3`),children:t})}function ta({icon:e,label:t,className:n,...r}){return(0,$.jsxs)(`button`,{type:`button`,className:Xt(`flex h-[68px] min-w-0 cursor-pointer flex-col items-center justify-center gap-1.5 rounded-[var(--r-md)] bg-surface-muted px-1 text-[13px] text-content active:bg-surface-hover disabled:cursor-default disabled:text-content-faint`,Qi,n),...r,children:[(0,$.jsx)(e,{className:`size-5 text-content-secondary`,strokeWidth:1.75,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`max-w-full truncate`,children:t})]})}function na({icon:e,label:t,hint:n,trailing:r,className:i,...a}){return(0,$.jsxs)(`button`,{type:`button`,className:Xt(`flex min-h-11 w-full min-w-0 cursor-pointer items-center gap-3 rounded-[var(--r-md)] px-3 text-left text-[15px] text-content active:bg-surface-hover disabled:cursor-default disabled:text-content-faint`,Qi,i),...a,children:[(0,$.jsx)(e,{className:`size-[18px] flex-none text-content-secondary`,strokeWidth:1.75,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,$.jsx)(`span`,{className:`truncate`,children:t}),n&&(0,$.jsx)(`span`,{className:`truncate text-xs text-content-muted`,children:n})]}),r]})}var ra=`relative grid size-11 flex-none place-items-center rounded-full bg-surface-muted text-content focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus active:bg-surface-hover dark:bg-surface-active`;function ia({leading:e,session:t,cwd:n,streaming:r,runStartedAt:i,approvals:a,failed:o,stopped:s,treeAvailable:c,branches:u,onOpenTree:d,runningActivity:f=[],...p}){let m=t.machine?`${t.machine.name}:${t.machine.cwd}`:n,{t:h,language:_}=l(),v=(0,Q.useContext)(Ze),y=(0,Q.useContext)(Ye),b=Oi(i,r),x=Ai(t,p),[S,C]=(0,Q.useState)(!1),w=(0,Q.useId)(),T=t.name||h(`navigation:pageHeader.newChat`),E=Mn(t.projectless?``:m,_),D=t.machine?jn(t.machine):E,O=g({queryKey:[`session-change-summary`,t.id,r],queryFn:()=>er(t.id),staleTime:1e4}),k=O.data?.status===`known`?O.data.changedFiles??0:0,A=a>0?{kind:`approval`,label:h(`board:status.approval`)}:r?{kind:`running`,label:b===null?h(`board:status.running`):h(`board:phone.running`,{elapsed:Pn(b)})}:o?{kind:`failed`,label:h(`board:status.failed`)}:s?{kind:`stopped`,label:h(`board:status.stopped`)}:null,j=()=>v?.show(`changes`),M=[...c?[{key:`tree`,icon:et,label:u>0?h(`board:session.treeBranches`,{count:u}):h(`board:session.tree`),shortLabel:h(`board:session.tree`),onSelect:()=>d(`branches`),marker:`session-tree`}]:[],{key:`side-chat`,icon:at,label:h(`board:inspector.sideChat`),onSelect:()=>ki(t.id,v),marker:`session-side-chat`},...v?[{key:`inspector`,icon:re,label:h(`board:phone.openInspector`),shortLabel:h(`board:phone.openInspectorShort`),onSelect:j,marker:`inspector-toggle`}]:[]];return(0,$.jsxs)(`header`,{"data-session-header":`phone`,className:`grid h-14 min-w-0 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center bg-panel px-3`,children:[(0,$.jsx)(`div`,{className:`flex min-w-0 items-center`,children:e}),(0,$.jsxs)(`button`,{type:`button`,"data-session-menu-trigger":!0,"aria-haspopup":`dialog`,"aria-expanded":S,"aria-controls":S?w:void 0,"aria-label":h(`board:session.titleMenu`,{title:T}),className:`flex h-11 max-w-[min(58vw,260px)] min-w-0 flex-col items-center justify-center rounded-[var(--r-md)] px-2 outline-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus active:bg-surface-hover`,onClick:()=>C(!0),children:[(0,$.jsxs)(`span`,{className:`flex max-w-full min-w-0 items-center gap-0.5 text-base leading-5 font-semibold text-content`,children:[(0,$.jsx)(`span`,{className:`truncate`,"data-session-title":!0,children:T}),(0,$.jsx)(B,{className:`size-4 flex-none text-content-muted`,"aria-hidden":`true`})]}),(0,$.jsxs)(`span`,{className:`flex max-w-full min-w-0 items-center gap-1 text-xs leading-4 text-content-muted`,children:[(0,$.jsx)(`span`,{className:`min-w-0 truncate font-mono`,title:m,"data-session-project":!0,children:D}),A&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,children:`·`}),(0,$.jsxs)(`span`,{className:Xt(`flex flex-none items-center gap-1`,(A.kind===`approval`||A.kind===`failed`)&&`font-medium text-warning-strong`),"data-session-status":A.kind,children:[(0,$.jsx)(Fn,{status:A.kind===`running`?`run`:A.kind===`stopped`?`stopped`:`attention`,className:`size-3`}),(0,$.jsx)(`span`,{className:`tabular-nums`,children:A.label})]})]})]})]}),(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center justify-end gap-2`,children:[(0,$.jsx)(Yi,{sessionId:t.id,streaming:r,activity:f,phoneButtonClass:ra}),k>0&&v?(0,$.jsxs)(`button`,{type:`button`,"data-session-changes":k,"aria-haspopup":`dialog`,"aria-controls":v.panelId,"aria-label":h(`board:phone.changesLabel`,{count:k}),className:ra,onClick:j,children:[(0,$.jsx)(re,{className:`size-5`,strokeWidth:1.75,"aria-hidden":`true`}),(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`absolute top-1.5 right-1 grid h-4 min-w-4 place-items-center rounded-full bg-content px-1 text-[10px] leading-none font-semibold text-panel tabular-nums`,children:k>99?`99+`:k})]}):y?.phone?(0,$.jsx)(`button`,{type:`button`,"data-phone-new-task":!0,"aria-label":h(`navigation:shell.newTask`),className:ra,onClick:y.phone.onNewTask,children:(0,$.jsx)(ht,{className:`size-5`,strokeWidth:1.75,"aria-hidden":`true`})}):null]}),(0,$.jsx)(Tn,{open:S,onOpenChange:C,children:(0,$.jsxs)(Sn,{id:w,side:`bottom`,showCloseButton:!1,"data-session-menu-sheet":!0,className:`max-h-[85dvh] gap-0 rounded-t-(--r-sheet) px-2 pt-1 pb-[calc(8px+var(--pisper-safe-area-bottom))]`,children:[(0,$.jsx)(se,{onDismiss:()=>C(!1)}),(0,$.jsx)(Cn,{className:`truncate px-3 pt-1 pb-0.5 text-base font-semibold`,children:T}),(0,$.jsx)(wn,{className:`truncate px-3 pb-2 font-mono text-xs text-content-muted`,children:E}),(0,$.jsx)(ea,{count:M.length,children:M.map(e=>{let t=e.marker?{[`data-${e.marker}`]:!0}:{};return(0,$.jsx)(ta,{icon:e.icon,label:e.shortLabel||e.label,"aria-label":e.label,onClick:()=>{C(!1),e.onSelect()},...t},e.key)})}),(0,$.jsx)(`div`,{className:`min-h-0 overflow-y-auto`,role:`list`,children:x.entries.map(e=>{let t=e.marker?{[`data-${e.marker}`]:!0}:{};return(0,$.jsxs)(`div`,{role:`listitem`,children:[e.separator&&(0,$.jsx)(`div`,{"aria-hidden":`true`,className:`mx-3 my-1 h-px bg-stroke-soft`}),(0,$.jsx)(na,{icon:e.icon,label:e.label,disabled:e.disabled,trailing:e.trailing&&(0,$.jsx)(`span`,{className:`flex-none font-mono text-sm text-content-muted tabular-nums`,title:e.trailingTitle,"data-session-context-usage":!0,children:e.trailing}),onClick:()=>{C(!1),e.onSelect()},...t})]},e.key)})})]})}),x.dialog]})}function aa({open:e,sessionId:t,cwd:n=``,onClose:r,onSelect:i,onCommandSelect:a}){let{t:o}=l(),s=k(e=>e.capabilities),c=O(s,`workflows`),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)(`all`),[m,h]=(0,Q.useState)(``),[g,_]=(0,Q.useState)(null),[v,y]=(0,Q.useState)({}),[b,x]=(0,Q.useState)(!1),[S,C]=(0,Q.useState)(``);(0,Q.useEffect)(()=>{if(!e)return;let r=!0;return p(`all`),h(``),_(null),y({}),x(!0),C(``),Promise.all([t?X.getSessionCommands(t):X.getWorkspaceCommands(n),c?D(`/api/workflows`):Promise.resolve({workflows:[]}),D(`/api/plugins?sessionId=${encodeURIComponent(t)}`)]).then(([e,t,n])=>{if(!r)return;let i=new Set(n.callableToolNames||[]);d([...(e.commands||[]).map(e=>({kind:e.source,id:e.name,name:e.name,description:e.description||``,inputs:[],argumentHint:e.argumentHint,invocation:e.invocation})),...(t.workflows||[]).filter(e=>e.status===`published`).map(e=>({kind:`workflow`,id:e.id,name:e.name,description:e.description||``,inputs:e.inputs||[]})),...(n.plugins||[]).flatMap(e=>(e.capabilities||[]).filter(e=>i.has(e.name)).map(t=>({kind:`tool`,id:t.name,name:t.id?Fr(t,o):String(t.label||t.name),description:t.id?Ir(t,o):t.description,inputs:[],sourceName:e.name})))])}).catch(e=>{r&&(d([]),C(e instanceof Error?e.message:String(e)))}).finally(()=>r&&x(!1)),()=>{r=!1}},[n,e,t,o,c]);let w=(0,Q.useMemo)(()=>({all:u.length,prompt:u.filter(e=>e.kind===`prompt`).length,skill:u.filter(e=>e.kind===`skill`).length,tool:u.filter(e=>e.kind===`tool`).length,workflow:u.filter(e=>e.kind===`workflow`).length}),[u]),T=(0,Q.useMemo)(()=>{let e=m.trim().toLowerCase();return u.filter(t=>(f===`all`||t.kind===f)&&(!e||`${t.name} ${t.id} ${t.description} ${t.kind===`tool`?t.sourceName:``}`.toLowerCase().includes(e)))},[f,m,u]),E=e=>{let t=e;p(t),g&&t!==`all`&&g.kind!==t&&_(null)},A=e=>{_(e),y(Object.fromEntries(e.inputs.map(e=>[e.name,e.defaultValue??``])))};return(0,$.jsx)(Jn,{open:e,onOpenChange:e=>!e&&r(),children:(0,$.jsxs)(Gn,{className:`chat-resource-dialog w-[min(820px,calc(100vw_-_32px))] h-[min(600px,calc(100dvh_-_32px))] max-w-[820px] sm:max-w-[820px] grid-rows-[auto_minmax(0,1fr)] overflow-hidden max-[650px]:w-[calc(100vw_-_16px)] max-[650px]:h-[calc(100dvh_-_16px)] z-[220] gap-0 p-0 ring-0`,overlayClassName:`z-[220]`,showCloseButton:!1,children:[(0,$.jsxs)(`div`,{className:`chat-resource-head flex items-start justify-between gap-4 border-b border-stroke-soft px-[18px] pt-4 pb-3.5 max-[650px]:p-3.5 [&_[data-slot='dialog-description']]:mt-0.5 [&_[data-slot='dialog-description']]:text-xs [&_[data-slot='dialog-description']]:text-content-muted [&_[data-slot='dialog-title']]:text-base [&_[data-slot='dialog-title']]:font-semibold`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(Kn,{children:o(`chat:resourcePicker.title`)}),(0,$.jsx)(Wn,{children:o(`chat:resourcePicker.description`)})]}),(0,$.jsx)(Y,{size:`icon-sm`,variant:`ghost`,"aria-label":o(`chat:resourcePicker.close`),onClick:r,children:(0,$.jsx)(Dt,{})})]}),(0,$.jsxs)(`div`,{className:`chat-resource-body grid min-h-0 grid-cols-[minmax(0,1.1fr)_minmax(260px,.9fr)] overflow-hidden max-[650px]:grid-cols-[1fr] max-[650px]:grid-rows-[minmax(0,1fr)_minmax(190px,auto)] max-[650px]:overflow-hidden`,children:[(0,$.jsxs)(`div`,{className:`chat-resource-browser flex min-h-0 min-w-0 flex-col border-r border-stroke-soft p-3 max-[650px]:min-h-0 max-[650px]:border-r-0 max-[650px]:border-b`,children:[(0,$.jsx)(Wt,{value:f,onValueChange:E,className:`chat-resource-tabs w-full [&_[data-slot='tabs-list']]:grid [&_[data-slot='tabs-list']]:h-9 [&_[data-slot='tabs-list']]:w-full [&_[data-slot='tabs-list']]:rounded-sm [&_[data-slot='tabs-list']]:border [&_[data-slot='tabs-list']]:border-stroke [&_[data-slot='tabs-list']]:bg-surface-muted [&_[data-slot='tabs-list']]:p-0.5 [&_[data-slot='tabs-trigger']]:min-w-0 [&_[data-slot='tabs-trigger']]:gap-1 [&_[data-slot='tabs-trigger']]:rounded-xs [&_[data-slot='tabs-trigger']]:px-1.5 [&_[data-slot='tabs-trigger']]:text-xs [&_[data-slot='tabs-trigger']]:text-content-secondary [&_[data-slot='tabs-trigger'][data-state='active']]:bg-key [&_[data-slot='tabs-trigger'][data-state='active']]:text-content [&_[data-slot='tabs-trigger'][data-state='active']]:shadow-key [&_[data-slot='tabs-trigger']_small]:text-xs [&_[data-slot='tabs-trigger']_small]:font-normal [&_[data-slot='tabs-trigger']_small]:text-content-muted [&_[data-slot='tabs-trigger']_small]:tabular-nums ${c?`[&_[data-slot='tabs-list']]:grid-cols-[repeat(5,minmax(0,1fr))]`:`[&_[data-slot='tabs-list']]:grid-cols-[repeat(4,minmax(0,1fr))]`}`,children:(0,$.jsxs)(Ut,{"aria-label":o(`chat:resourcePicker.categories`),children:[(0,$.jsxs)(Ht,{value:`all`,children:[o(`chat:resourcePicker.all`),(0,$.jsx)(`small`,{children:w.all})]}),(0,$.jsxs)(Ht,{value:`prompt`,children:[o(`chat:resourcePicker.prompt`),(0,$.jsx)(`small`,{children:w.prompt})]}),(0,$.jsxs)(Ht,{value:`skill`,children:[o(`chat:resourcePicker.skill`),(0,$.jsx)(`small`,{children:w.skill})]}),(0,$.jsxs)(Ht,{value:`tool`,children:[o(`chat:resourcePicker.tool`),(0,$.jsx)(`small`,{children:w.tool})]}),c&&(0,$.jsxs)(Ht,{value:`workflow`,children:[o(`chat:resourcePicker.workflow`),(0,$.jsx)(`small`,{children:w.workflow})]})]})}),(0,$.jsxs)(Qn,{className:`chat-resource-search mt-2`,children:[(0,$.jsx)(Zn,{children:(0,$.jsx)(ft,{"aria-hidden":`true`})}),(0,$.jsx)(Xn,{autoFocus:!0,value:m,"aria-label":o(`chat:resourcePicker.search`),onChange:e=>h(e.target.value),placeholder:o(`chat:resourcePicker.search`)})]}),(0,$.jsxs)(`div`,{className:`chat-resource-list mt-2 flex min-h-0 [flex:1_1_0] flex-col gap-px overflow-y-auto [overscroll-behavior:contain] [scrollbar-gutter:stable] [touch-action:pan-y] [&_>_button]:relative [&_>_button]:grid [&_>_button]:w-full [&_>_button]:cursor-pointer [&_>_button]:grid-cols-[28px_minmax(0,1fr)_auto] [&_>_button]:items-center [&_>_button]:gap-2 [&_>_button]:rounded-sm [&_>_button]:px-2 [&_>_button]:py-1.5 [&_>_button]:text-left [&_>_button]:text-content [&_>_button:hover]:bg-surface-hover [&_>_button.active]:bg-surface-hover [&_>_button.active]:before:absolute [&_>_button.active]:before:inset-y-1.5 [&_>_button.active]:before:left-0 [&_>_button.active]:before:w-[3px] [&_>_button.active]:before:rounded-full [&_>_button.active]:before:bg-star max-[650px]:[&_>_button]:min-h-11 [&_button_>_span:nth-child(2)]:flex [&_button_>_span:nth-child(2)]:min-w-0 [&_button_>_span:nth-child(2)]:flex-col [&_strong]:truncate [&_strong]:text-[13px] [&_strong]:font-medium [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_em]:text-xs [&_em]:whitespace-nowrap [&_em]:text-content-muted [&_em]:not-italic [&_>_p]:m-auto [&_>_p]:text-xs [&_>_p]:text-content-muted`,children:[T.map(e=>{let t=e.kind===`prompt`?ae:e.kind===`skill`?R:e.kind===`tool`?Et:Tt;return(0,$.jsxs)(`button`,{type:`button`,className:g?.kind===e.kind&&g.id===e.id?`active`:``,onClick:()=>A(e),children:[(0,$.jsx)(`span`,{className:`list-icon grid size-7 place-items-center rounded-sm bg-surface-muted text-content-secondary`,children:(0,$.jsx)(t,{size:15})}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{children:e.name}),(0,$.jsx)(`small`,{children:e.description})]}),(0,$.jsx)(`em`,{children:e.kind===`prompt`?o(`chat:resourcePicker.prompt`):e.kind===`skill`?`Skill`:e.kind===`tool`?o(`chat:resourcePicker.tool`):o(`chat:resourcePicker.workflow`)})]},`${e.kind}:${e.id}`)}),!T.length&&(0,$.jsx)(`p`,{children:b?o(`chat:resourcePicker.loading`):S||o(`chat:resourcePicker.empty`)})]})]}),(0,$.jsx)(`div`,{className:`chat-resource-config flex min-h-0 min-w-0 flex-col gap-4 overflow-y-auto overscroll-contain p-[18px] max-[650px]:max-h-[230px] max-[650px]:min-h-0 [&_>_div:first-child]:flex [&_>_div:first-child]:flex-col [&_>_div:first-child]:gap-1 [&_>_p]:m-auto [&_>_p]:text-xs [&_>_p]:text-content-muted [&_p]:text-xs [&_p]:text-content-muted [&_strong]:text-[15px] [&_strong]:font-medium`,children:g?(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`div`,{children:[(0,$.jsx)(`strong`,{children:g.name}),(0,$.jsx)(`p`,{children:g.description||o(`chat:resourcePicker.noDescription`)})]}),g.kind===`workflow`&&g.inputs.length>0&&(0,$.jsx)(`div`,{className:`chat-resource-inputs flex flex-col gap-3 [&_label]:grid [&_label]:gap-1.5 [&_label]:text-xs [&_label]:font-medium [&_label]:text-content-secondary`,children:g.inputs.map(e=>(0,$.jsxs)(`label`,{children:[(0,$.jsxs)(`span`,{children:[e.label,e.required?` *`:``]}),e.type===`boolean`?(0,$.jsx)(kt,{checked:!!v[e.name],onCheckedChange:t=>y(n=>({...n,[e.name]:t===!0}))}):(0,$.jsx)(Yn,{type:e.type===`number`?`number`:`text`,required:e.required,value:String(v[e.name]??``),onChange:t=>y(n=>({...n,[e.name]:t.target.value}))})]},e.id))}),g.kind===`prompt`&&g.argumentHint&&(0,$.jsx)(`code`,{className:`w-fit max-w-full rounded-xs bg-inline-code px-1.5 py-1 font-mono text-xs [overflow-wrap:anywhere] text-content-secondary`,children:g.argumentHint}),(0,$.jsx)(Y,{className:`chat-resource-confirm min-h-8 min-w-[112px] self-start bg-star text-[var(--on-accent)] hover:bg-star-hover max-[650px]:min-h-11`,onClick:()=>{if(g){if(g.kind===`prompt`){a(g.invocation||`/${g.name}`),r();return}i({kind:g.kind,resourceId:g.id,resourceName:g.name,arguments:g.kind===`workflow`?v:void 0,behavior:g.kind===`workflow`?`background`:`foreground`}),r()}},children:g.kind===`prompt`?o(`chat:resourcePicker.insertPrompt`):o(`chat:resourcePicker.useResource`)})]}):(0,$.jsx)(`p`,{children:o(`chat:resourcePicker.chooseResource`)})})]})]})})}function oa(e){if(e.style.height=`auto`,!e.scrollHeight){e.style.height=``;return}e.style.height=`${Math.min(e.scrollHeight,220)}px`}function sa(e){let t=e.getHours();return t>=5&&t<11?`morning`:t>=11&&t<13?`noon`:t>=13&&t<18?`afternoon`:t>=18&&t<23?`evening`:`lateNight`}function ca(e){let t=new Date(e);return t.setHours(e.getHours()+1,0,0,0),Math.max(1e3,t.getTime()-e.getTime())}function la(){let{t:e}=l(),[t,n]=(0,Q.useState)(()=>new Date);(0,Q.useEffect)(()=>{let e=window.setTimeout(()=>n(new Date),ca(t));return()=>window.clearTimeout(e)},[t]);let r=sa(t),i=e(r===`morning`?`chat:newTask.greetingMorning`:r===`noon`?`chat:newTask.greetingNoon`:r===`afternoon`?`chat:newTask.greetingAfternoon`:r===`evening`?`chat:newTask.greetingEvening`:`chat:newTask.greetingLateNight`);return(0,$.jsxs)(`div`,{className:`grid min-h-full content-center justify-items-center gap-2 text-center max-[650px]:gap-3`,"data-new-task-greeting":!0,children:[(0,$.jsx)(ur,{size:32}),(0,$.jsx)(`h2`,{className:`text-2xl! font-semibold tracking-[-.01em] text-balance text-content max-[650px]:text-xl!`,children:i}),(0,$.jsx)(`p`,{className:`max-w-[46ch] text-sm leading-6 text-content-muted max-[650px]:hidden`,children:e(`board:home.draftHint`)})]})}function ua({phone:e,leading:t,project:n}){let{t:r}=l();return e?(0,$.jsxs)(`header`,{"data-session-header":`draft`,"data-focus-region":`header`,className:`grid h-14 min-w-0 shrink-0 grid-cols-[minmax(0,1fr)_auto_minmax(0,1fr)] items-center bg-panel px-3`,children:[(0,$.jsx)(`div`,{className:`flex min-w-0 items-center`,children:t}),(0,$.jsxs)(`div`,{className:`flex max-w-[min(58vw,260px)] min-w-0 flex-col items-center justify-center`,children:[(0,$.jsx)(`h1`,{className:`max-w-full truncate px-1.5 text-base leading-5 font-semibold text-content`,children:r(`board:home.draftTitle`)}),n]}),(0,$.jsx)(`span`,{"aria-hidden":`true`})]}):(0,$.jsxs)(`header`,{"data-session-header":`draft`,"data-focus-region":`header`,"data-window-drag-region":!0,className:`flex h-[52px] min-w-0 shrink-0 items-center gap-2 border-b border-stroke-soft pr-2 pl-4 [[data-custom-titlebar]_&]:pr-[144px]`,children:[t,(0,$.jsx)(`h1`,{className:`flex-none text-[15px] leading-6 font-semibold text-content`,children:r(`board:home.draftTitle`)}),(0,$.jsx)(`span`,{className:`min-w-0 truncate text-xs text-content-muted`,children:r(`board:home.draftSubtitle`)})]})}var da=1e3;function fa({option:e,selected:t,disabled:n,onSelect:r}){let i=e.icon;return(0,$.jsxs)(`button`,{type:`button`,role:`radio`,"aria-checked":t,disabled:n,className:`grid min-h-12 w-full cursor-pointer grid-cols-[16px_minmax(0,1fr)_16px] items-center gap-2.5 rounded-sm px-2 py-1.5 text-left text-content hover:bg-surface-hover focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-focus disabled:cursor-default disabled:opacity-50 disabled:hover:bg-transparent max-[650px]:min-h-14`,"data-mode-option":e.value,onClick:()=>r(e.value),children:[(0,$.jsx)(i,{size:16,strokeWidth:1.75,className:`text-content-secondary`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{className:`flex min-w-0 flex-col gap-px`,children:[(0,$.jsx)(`span`,{className:Xt(`text-[13px] max-[650px]:text-[15px]`,t&&`font-medium`),children:e.label}),(0,$.jsx)(`small`,{className:`text-xs leading-normal text-content-muted max-[650px]:text-[13px]`,children:e.description})]}),t?(0,$.jsx)(z,{size:15,strokeWidth:2.25,"aria-hidden":`true`}):(0,$.jsx)(`span`,{})]})}function pa({approvalMode:e,onApprovalModeChange:t,approvalDisabled:n=!1,runMode:r,onRunModeChange:i,runModeDisabled:a=!1,goalsAvailable:o,teamAvailable:s,goal:c,tokenBudget:u,onTokenBudgetChange:d,onSaveTokenBudget:f,sheet:p=!1,collapse:m=!1,open:h,onOpenChange:g}){let{t:_}=l(),[v,y]=(0,Q.useState)(!1),[b,x]=(0,Q.useState)(!1),S=h??b,C=e=>{h===void 0&&x(e),g?.(e)},w=[{value:`approval-required`,label:_(`chat:focusSession.approvalRequired`),description:_(`chat:focusSession.approvalRequiredShowsADiffBeforeWriting`),icon:ei},{value:`workspace-write`,label:_(`chat:focusSession.workspaceWrite`),description:_(`chat:focusSession.workspaceWriteRunsCommandsWithAutomaticApproval`),icon:Qr},{value:`full-access`,label:_(`chat:focusSession.fullAccess`),description:_(`chat:focusSession.fullAccessRunsShellWithoutPerCommandApproval`),icon:mt}],T=[{value:`plan`,label:_(`board:composer.planShort`),description:_(`chat:focusSession.planModeDescription`),icon:rt},...o?[{value:`goal`,label:_(`board:composer.goalShort`),description:_(`chat:focusSession.goalModeDescription`),icon:vt}]:[],...o&&s?[{value:`team`,label:_(`board:composer.teamShort`),description:_(`chat:focusSession.teamModeDescription`),icon:wt}]:[]],E=w.find(t=>t.value===e)||w[0],D=c?.status===`active`?c?.mode===`team`&&s?`team`:`goal`:r,O=T.find(e=>e.value===D)||T[0],k=O.value!==`plan`,A=E.value===`full-access`?mt:ai,j=O.value===`team`?_(`board:composer.teamShort`):O.value===`goal`?_(`board:composer.goalShort`):``,M=j?`${j} · ${E.label}`:E.label,N=O.value===`plan`&&E.value===`approval-required`,P=!!c?.id,F=D===`team`?c?.teamTokenBudget:c?.tokenBudget,I=F==null?null:Number(F)>0?Number(F):null,L=u!==I,R=P?I==null?_(`chat:focusSession.usedUnlimitedGoalTokens`,{used:Nn(c?.tokensUsed)}):_(`chat:focusSession.usedBudgetTokensUsed`,{used:c?.tokensUsed||0,budget:I||0}):``,V=`${_(`board:composer.modeChip`)} · ${M}`,H=_(D===`team`?`chat:focusSession.teamTokenBudget`:`chat:focusSession.goalTokenBudget`),U=async()=>{if(!(v||!L||!P||!f)){y(!0);try{await f(u)}finally{y(!1)}}};return(0,$.jsxs)(pe,{sheet:p,title:_(`board:composer.modeChip`),open:S,onOpenChange:C,align:`start`,side:`top`,className:`composer-mode-popover w-[300px] max-w-[calc(100vw_-_24px)] gap-1 p-1`,trigger:(0,$.jsxs)(`button`,{type:`button`,className:Xt(q,`composer-mode-chip max-w-[220px] max-[650px]:min-w-9 max-[650px]:justify-center max-[650px]:gap-1`,k?`max-[650px]:px-2.5`:`max-[650px]:px-0`),"aria-label":V,title:V,hidden:m&&!k&&E.value!==`full-access`,"data-composer-mode":`${O.value}:${E.value}`,children:[k&&(0,$.jsx)(O.icon,{size:16,className:`hidden shrink-0 max-[650px]:block`,"aria-hidden":`true`}),(0,$.jsx)(A,{size:14,className:`shrink-0 max-[650px]:size-4`,"aria-hidden":`true`}),!N&&(0,$.jsx)(`span`,{className:`min-w-0 truncate max-[650px]:hidden`,children:M}),(0,$.jsx)(B,{size:14,className:`shrink-0 opacity-70 max-[650px]:hidden`,"aria-hidden":`true`})]}),children:[(0,$.jsxs)(`div`,{role:`radiogroup`,"aria-label":_(`chat:focusSession.approvalMode`),className:`flex flex-col gap-0.5`,children:[(0,$.jsx)(`div`,{className:`px-2 pt-1.5 pb-1 text-xs font-medium text-content-muted`,children:_(`chat:focusSession.approvalMode`)}),w.map(e=>(0,$.jsx)(fa,{option:e,selected:e.value===E.value,disabled:n,onSelect:e=>{C(!1),t(e)}},e.value))]}),T.length>1&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsx)(`div`,{role:`separator`,className:`mx-1 h-px bg-stroke-soft`}),(0,$.jsxs)(`div`,{className:`grid gap-1.5 px-2 pt-1.5 pb-1.5`,children:[(0,$.jsxs)(`div`,{className:`flex min-h-7 items-center justify-between gap-2`,children:[(0,$.jsxs)(`span`,{className:`flex items-center gap-1.5 text-xs font-medium text-content-muted`,children:[_(`chat:focusSession.executionMode`),(0,$.jsx)($t,{className:`font-normal max-[650px]:hidden pointer-coarse:hidden`,children:`⇧Tab`})]}),(0,$.jsx)(Kt,{size:`sm`,"aria-label":_(`chat:focusSession.executionMode`),value:D,disabled:a,options:T.map(({value:e,label:t})=>({value:e,label:t})),onValueChange:i})]}),(0,$.jsx)(`p`,{className:`text-xs leading-normal text-content-muted max-[650px]:text-[13px]`,children:O.description})]}),(k||P)&&(0,$.jsxs)(`div`,{className:`grid gap-1 px-2 pt-1 pb-1.5 text-xs`,children:[R&&(0,$.jsx)(`p`,{className:`text-content-muted tabular-nums`,children:R}),(0,$.jsxs)(`div`,{className:`grid grid-cols-[auto_minmax(0,1fr)_auto] items-center gap-1.5`,children:[(0,$.jsx)(`label`,{htmlFor:`goal-token-budget-input`,className:`font-medium text-content-secondary`,children:H}),(0,$.jsx)(Yn,{id:`goal-token-budget-input`,type:`number`,min:da,step:1e3,value:u??``,placeholder:_(`chat:focusSession.goalTokenBudgetUnlimited`),"aria-label":H,disabled:v,className:`text-[13px] tabular-nums`,onChange:e=>{let t=e.target.value.trim();if(!t){d(null);return}let n=Number(t);Number.isFinite(n)&&d(Math.max(da,Math.round(n)))}}),P&&L?(0,$.jsxs)(Y,{type:`button`,variant:`outline`,size:`sm`,disabled:v,onClick:()=>void U(),children:[v?(0,$.jsx)(dt,{className:`animate-spin`,size:12}):(0,$.jsx)(z,{size:12}),_(`chat:focusSession.goalBudgetSave`)]}):(0,$.jsx)(`span`,{})]}),(0,$.jsx)(`small`,{className:`text-content-muted`,children:_(D===`team`?`chat:focusSession.teamTokenBudgetHint`:P?`chat:focusSession.goalTokenBudgetUpdateHint`:`chat:focusSession.goalTokenBudgetHint`)})]})]})]})}function ma({trigger:e,open:t,onOpenChange:n,onAttachment:r,onResource:i,onVisual:a,steer:o,mode:s}){let{t:c}=l(),u=e=>{n(!1),window.setTimeout(e,0)};return(0,$.jsxs)(pe,{sheet:!0,title:c(`board:composer.plusSheetTitle`),open:t,onOpenChange:n,trigger:e,sheetClassName:`px-2`,children:[(0,$.jsxs)(ea,{count:a?3:2,children:[(0,$.jsx)(ta,{icon:st,label:c(`board:composer.attachmentShort`),"data-composer-plus-item":`attachment`,onClick:()=>{n(!1),r()}}),(0,$.jsx)(ta,{icon:R,label:c(`chat:resourcePicker.open`),"data-composer-plus-item":`resource`,onClick:()=>u(i)}),a&&(0,$.jsx)(ta,{icon:ee,label:c(`chat:focusSession.generateImage`),"data-composer-plus-item":`visual`,onClick:()=>u(a)})]}),o&&(0,$.jsx)(na,{icon:te,label:c(`board:composer.steerNow`),hint:c(`board:composer.steerHint`),disabled:o.disabled,"data-composer-steer":!0,onClick:()=>u(o.onSelect)}),s&&(0,$.jsx)(na,{icon:ai,label:c(`board:composer.modeChip`),"data-composer-plus-item":`mode`,trailing:(0,$.jsxs)(`span`,{className:`flex flex-none items-center gap-1 text-sm text-content-muted`,children:[s.valueLabel,(0,$.jsx)(H,{className:`size-4`,"aria-hidden":`true`})]}),onClick:()=>u(s.onOpen)})]})}function ha(e,t){let n=[`plan`];return t.goalsAvailable&&n.push(`goal`),t.goalsAvailable&&t.teamAvailable&&n.push(`team`),n.length<2?null:n[(n.indexOf(e)+1)%n.length]??`plan`}function ga({state:e,cwd:t,onDismiss:n}){let{t:r}=l(),i=e.status===`streaming`;return(0,$.jsxs)(`section`,{"aria-label":r(`chat:sideQuestion.label`),"aria-busy":i,onKeyDown:e=>{e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),n())},className:`flex max-h-[min(45vh,420px)] min-w-0 flex-col rounded-lg border border-stroke bg-panel shadow-float`,children:[(0,$.jsxs)(`header`,{className:`flex min-w-0 items-start gap-2 border-b border-stroke-soft px-3 py-2`,children:[(0,$.jsx)(ni,{size:15,"aria-hidden":`true`,className:`mt-0.5 shrink-0 text-content-muted`}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-1 flex-col`,children:[(0,$.jsx)(`span`,{className:`text-xs text-content-muted`,children:r(`chat:sideQuestion.label`)}),(0,$.jsx)(`p`,{className:`m-0 line-clamp-2 text-[13px] text-content`,title:e.question,children:e.question})]}),(0,$.jsx)(Y,{variant:`ghost`,size:`icon-xs`,className:`shrink-0 pointer-coarse:size-11`,"aria-label":r(`chat:sideQuestion.close`),title:r(`chat:sideQuestion.close`),onClick:n,children:(0,$.jsx)(Dt,{})})]}),(0,$.jsxs)(`div`,{className:`min-h-0 overflow-y-auto overscroll-contain px-3 py-2 text-[13px]`,children:[e.answer?(0,$.jsx)(or,{cwd:t,streaming:i,children:e.answer}):i?(0,$.jsxs)(`p`,{role:`status`,className:`m-0 flex items-center gap-2 text-content-muted`,children:[(0,$.jsx)(Zt,{className:`size-4`}),r(`chat:sideQuestion.answering`)]}):e.status===`done`?(0,$.jsx)(`p`,{className:`m-0 text-content-muted`,children:e.toolCallIgnored?r(`chat:sideQuestion.toolIgnored`):r(`chat:sideQuestion.empty`)}):null,e.status===`error`&&(0,$.jsx)(`p`,{role:`alert`,className:`m-0 mt-1 text-[var(--danger)]`,children:r(`chat:sideQuestion.failed`,{error:e.error})})]}),(0,$.jsx)(`footer`,{className:`border-t border-stroke-soft px-3 py-1.5 text-xs text-content-muted`,children:r(`chat:sideQuestion.note`)})]})}function _a(e){let[t,n]=(0,Q.useState)(null),r=(0,Q.useRef)(null),i=(0,Q.useCallback)(()=>{r.current?.abort(),r.current=null},[]),a=(0,Q.useCallback)(()=>{i(),n(null)},[i]);return(0,Q.useEffect)(()=>a,[e,a]),{state:t,ask:(0,Q.useCallback)(t=>{i();let a=new AbortController;r.current=a;let o=()=>r.current===a;n({question:t,answer:``,status:`streaming`,error:``,toolCallIgnored:!1}),X.askSideQuestion(e,t,{signal:a.signal,onDelta:e=>{o()&&n(t=>t&&{...t,answer:t.answer+e})}}).then(e=>{o()&&(r.current=null,n(t=>t&&{...t,answer:e.text||t.answer,status:`done`,toolCallIgnored:e.toolCallIgnored}))}).catch(e=>{o()&&(r.current=null,n(t=>t&&{...t,status:`error`,error:e instanceof Error?e.message:String(e)}))})},[i,e]),dismiss:a}}var va=new Set([`user`,`assistant`,`summary`,`compaction`,`position`]);function ya(e,t,n){return t===`labeled`?!!e.label:t===`branches`?n||va.has(e.kind):!1}var ba=new Set([`tool`,`tool-call`]);function xa(e){let t=[],n=new Map;for(let r of e){let e=r.parentId?n.get(r.parentId):void 0,i={...r,children:[]};n.set(r.id,i),e?e.children.push(i):t.push(i)}return t}function Sa(e){let t=[],n=[...e].reverse();for(;n.length>0;){let e=n.pop();if(e){t.push(e);for(let t=e.children.length-1;t>=0;--t)n.push(e.children[t])}}return t}function Ca(e,t){let n=[],r=new Map;for(let i of Sa(e)){let e=i.parentId&&r.get(i.parentId)||null;if(!t(i)){r.set(i.id,e);continue}let a={...i,children:[]};r.set(i.id,a),e?e.children.push(a):n.push(a)}return n}function wa(e){let t=[e],n=e;for(;n.children.length===1;)n=n.children[0],t.push(n);let r={id:e.id,nodes:t,children:[],active:t.some(e=>e.active)},i=[{segment:r,children:n.children}];for(;i.length>0;){let e=i.pop();if(e)for(let t of e.children){let n=[t],r=t;for(;r.children.length===1;)r=r.children[0],n.push(r);let a={id:t.id,nodes:n,children:[],active:n.some(e=>e.active)};e.segment.children.push(a),i.push({segment:a,children:r.children})}}return r}function Ta(e){return e.kind===`user`?Ve:e.kind===`assistant`?L:e.kind===`tool`||e.kind===`tool-call`?Et:e.kind===`settings`?pt:e.kind===`label`?_t:e.kind===`summary`||e.kind===`compaction`?ae:e.kind===`position`?We:e.label?$r:at}function Ea({nodes:e,viewportRef:t,selectedId:n,typeLabel:r,stateLabel:i,onSelect:a}){let o=sr({count:e.length,getScrollElement:()=>t.current,estimateSize:()=>64,getItemKey:t=>e[t]?.id??`mobile-tree-node-${t}`,overscan:12,useAnimationFrameWithResizeObserver:!0});return(0,Q.useEffect)(()=>{if(!n)return;let t=e.findIndex(e=>e.id===n);t>=0&&o.scrollToIndex(t,{align:`center`})},[e,n,o]),(0,$.jsx)(`div`,{className:`relative w-full`,style:{height:`${o.getTotalSize()}px`},children:o.getVirtualItems().map(t=>{let o=e[t.index],s=Ta(o);return(0,$.jsx)(`div`,{className:`absolute top-0 left-0 w-full px-3 py-1`,style:{transform:`translateY(${t.start}px)`},children:(0,$.jsxs)(`button`,{type:`button`,className:`session-tree-node relative grid items-center gap-2 rounded-sm border border-stroke bg-panel text-left text-content transition-colors duration-(--d-fast) hover:bg-surface-subtle [&.selected]:border-key-border [&.selected]:bg-key [&.selected]:shadow-key [&.selected]:before:absolute [&.selected]:before:inset-y-2 [&.selected]:before:-left-px [&.selected]:before:w-[3px] [&.selected]:before:rounded-r-[3px] [&.selected]:before:bg-star min-h-14 w-full grid-cols-[34px_minmax(0,1fr)_auto] py-2 pr-2.5 pl-1 ${o.id===n?` selected`:``}${o.active?` active`:``}${o.leaf?` leaf`:``}`,"data-kind":o.kind,"data-pisper-tree-entry":o.id,onClick:()=>a(o.id),children:[(0,$.jsx)(`span`,{className:`session-tree-marker relative z-[2] grid size-6 place-items-center justify-self-center rounded-sm bg-surface-muted text-content-secondary [.session-tree-node[data-kind='tool']_&]:bg-warning-soft [.session-tree-node[data-kind='tool']_&]:text-warning-strong [.session-tree-node.leaf_&]:bg-star [.session-tree-node.leaf_&]:text-on-accent [.session-tree-mark.active_&]:bg-star-soft [.session-tree-mark.active_&]:text-star-strong`,children:(0,$.jsx)(s,{size:14})}),(0,$.jsxs)(`span`,{className:`session-tree-node-copy flex min-w-0 flex-col gap-0.5 [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_strong]:truncate [&_strong]:text-sm [&_strong]:font-medium`,children:[(0,$.jsx)(`strong`,{children:o.label||o.text||r(o)}),(0,$.jsx)(`small`,{children:o.label&&o.text?o.text:r(o)})]}),(0,$.jsxs)(`span`,{className:`session-tree-node-state inline-flex min-w-0 shrink-0 items-center gap-1 text-xs text-content-muted [.session-tree-node.leaf_&]:text-accent-fg`,children:[o.label&&(0,$.jsx)($r,{size:12}),i(o)]})]})},t.key)})})}function Da({segment:e,viewportRef:t,selectedId:n,typeLabel:r,stateLabel:i,onSelect:a}){let{nodes:o,children:s}=e,c=o.length>120,l=sr({count:o.length,getScrollElement:()=>t.current,estimateSize:()=>56,getItemKey:e=>o[e]?.id??`tree-node-${e}`,overscan:12,scrollMargin:26,enabled:c,useAnimationFrameWithResizeObserver:!0}),u=e=>{let t=Ta(e);return(0,$.jsxs)(`button`,{type:`button`,className:`session-tree-node relative grid items-center gap-2 rounded-sm border border-stroke bg-panel text-left text-content transition-colors duration-(--d-fast) hover:bg-surface-subtle [&.selected]:border-key-border [&.selected]:bg-key [&.selected]:shadow-key [&.selected]:before:absolute [&.selected]:before:inset-y-2 [&.selected]:before:-left-px [&.selected]:before:w-[3px] [&.selected]:before:rounded-r-[3px] [&.selected]:before:bg-star z-[1] min-h-12 w-[220px] cursor-pointer grid-cols-[30px_minmax(0,1fr)_auto] py-1.5 pr-2 pl-0.5 ${e.id===n?` selected`:``}${e.active?` active`:``}${e.leaf?` leaf`:``}`,"data-kind":e.kind,"data-pisper-tree-entry":e.id,onClick:()=>a(e.id),children:[(0,$.jsx)(`span`,{className:`session-tree-marker relative z-[2] grid size-6 place-items-center justify-self-center rounded-sm bg-surface-muted text-content-secondary [.session-tree-node[data-kind='tool']_&]:bg-warning-soft [.session-tree-node[data-kind='tool']_&]:text-warning-strong [.session-tree-node.leaf_&]:bg-star [.session-tree-node.leaf_&]:text-on-accent [.session-tree-mark.active_&]:bg-star-soft [.session-tree-mark.active_&]:text-star-strong`,children:(0,$.jsx)(t,{size:14})}),(0,$.jsxs)(`span`,{className:`session-tree-node-copy flex min-w-0 flex-col gap-0.5 [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_strong]:truncate [&_strong]:text-sm [&_strong]:font-medium`,children:[(0,$.jsx)(`strong`,{children:e.label||e.text||r(e)}),(0,$.jsx)(`small`,{children:e.label&&e.text?e.text:r(e)})]}),(0,$.jsxs)(`span`,{className:`session-tree-node-state inline-flex min-w-0 shrink-0 items-center gap-1 text-xs text-content-muted [.session-tree-node.leaf_&]:text-accent-fg`,children:[e.label&&(0,$.jsx)($r,{size:12}),i(e)]})]},e.id)};return(0,Q.useEffect)(()=>{if(!c||!n)return;let e=o.findIndex(e=>e.id===n);e<0||l.scrollToIndex(e,{align:`center`})},[n,o,c,l]),(0,$.jsxs)(`div`,{className:`session-tree-segment relative flex min-w-[220px] flex-col items-center ${e.active?` active`:``}`,children:[(0,$.jsx)(`div`,{className:`session-tree-track relative z-[1] grid w-[220px] gap-2 before:absolute before:top-[22px] before:bottom-[22px] before:left-1/2 before:z-0 before:w-px before:bg-stroke-strong [.session-tree-segment.active_>_&::before]:bg-control`,children:c?(0,$.jsx)(`div`,{className:`relative w-[220px]`,style:{height:`${l.getTotalSize()}px`},children:l.getVirtualItems().map(e=>(0,$.jsx)(`div`,{className:`absolute top-0 left-0 w-[220px]`,style:{top:`${e.start-26}px`},children:u(o[e.index])},e.key))}):o.map(u)}),s.length>0&&(0,$.jsx)(`div`,{className:`session-tree-children relative flex items-start justify-center pt-7 before:absolute before:top-0 before:left-1/2 before:h-3.5 before:w-px before:bg-stroke-strong [.session-tree-segment.active_>_&::before]:bg-control`,children:s.map(e=>(0,$.jsx)(`div`,{className:`session-tree-child relative flex px-3 pt-3.5 before:absolute before:top-0 before:right-1/2 before:h-3.5 before:w-1/2 before:border-t before:border-stroke-strong after:absolute after:top-0 after:left-1/2 after:h-3.5 after:w-1/2 after:border-t after:border-l after:border-stroke-strong [&:first-child::before]:border-t-transparent [&:last-child::after]:border-t-transparent [&.active]:before:border-control [&.active]:after:border-control [&.active:first-child::before]:border-t-transparent [&.active:last-child::after]:border-t-transparent${e.active?` active`:``}`,children:(0,$.jsx)(Da,{segment:e,viewportRef:t,selectedId:n,typeLabel:r,stateLabel:i,onSelect:a})},e.id))})]})}function Oa({view:e,onViewChange:t,showAllEntries:n,onShowAllEntriesChange:r,query:i,onQueryChange:a,loading:o,error:s,mobileLayout:c,viewportRef:u,segments:d,visibleNodes:f,selectedId:p,typeLabel:m,stateLabel:h,onSelect:g,visibleMarks:_,marksLoading:v,openingMark:y,onOpenMark:b,confirmingMark:x,onConfirmMark:S,onCancelMark:C}){let{t:w,language:T}=l(),E=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{x&&E.current?.focus()},[x]);let D=e=>{let t=Date.parse(e);return Number.isFinite(t)?new Intl.DateTimeFormat(T,{dateStyle:`medium`,timeStyle:`short`}).format(t):w(`navigation:appOverlays.unknownTime`)};return(0,$.jsxs)(`div`,{className:`chat-resource-browser flex min-h-0 min-w-0 flex-col bg-transparent session-tree-browser`,children:[(0,$.jsx)(Wt,{className:`chat-resource-tabs session-tree-tabs px-3 pt-3`,value:e,onValueChange:e=>t(e),children:(0,$.jsxs)(Ut,{children:[(0,$.jsx)(Ht,{value:`branches`,children:w(`chat:sessionTree.branches`)}),(0,$.jsx)(Ht,{value:`labeled`,children:w(`chat:sessionTree.labeled`)}),(0,$.jsx)(Ht,{value:`marks`,children:w(`chat:sessionTree.allMarks`)})]})}),(0,$.jsxs)(Qn,{className:`chat-resource-search mx-3 mt-2 w-auto flex-none`,children:[(0,$.jsx)(Zn,{children:(0,$.jsx)(ft,{"aria-hidden":`true`})}),(0,$.jsx)(Xn,{value:i,disabled:!!y,"aria-label":w(`chat:sessionTree.searchPlaceholder`),onChange:e=>a(e.target.value),placeholder:w(`chat:sessionTree.searchPlaceholder`)})]}),e===`branches`&&(0,$.jsxs)(`label`,{className:`mx-3 mt-2 flex min-h-6 flex-none cursor-pointer items-center gap-2 text-xs text-content-secondary max-[650px]:min-h-11`,children:[(0,$.jsx)(kt,{checked:n,onCheckedChange:e=>r(e===!0),"data-session-tree-all-entries":!0}),w(`chat:sessionTree.showAllEntries`)]}),e===`marks`?(0,$.jsxs)(`div`,{className:`flex min-h-0 min-w-0 flex-1 basis-0 flex-col gap-2 overflow-auto overscroll-contain px-3.5 py-3`,"data-testid":`session-tree-marks-list`,children:[s&&(0,$.jsx)(`p`,{role:`alert`,className:`mx-0.5 text-xs text-danger`,children:s}),v?(0,$.jsx)(`p`,{className:`grid min-h-[180px] place-items-center text-xs text-content-muted`,children:w(`chat:sessionTree.loadingMarks`)}):_.length?_.map(e=>(0,$.jsxs)(Q.Fragment,{children:[(0,$.jsxs)(`button`,{type:`button`,className:`session-tree-mark grid cursor-pointer grid-cols-[30px_minmax(0,1fr)_auto] items-center gap-2 rounded-sm border border-stroke bg-panel py-2 pr-2.5 pl-1 text-left text-content transition-colors duration-(--d-fast) hover:bg-surface-subtle [&.active]:border-star-border [&_>_em]:rounded-xs [&_>_em]:bg-star-soft [&_>_em]:px-1.5 [&_>_em]:py-0.5 [&_>_em]:text-xs [&_>_em]:text-star-strong [&_>_em]:not-italic ${e.active?` active`:``}`,"aria-expanded":e.active?void 0:x===e,"data-session-tree-mark":e.active?`active`:`other-branch`,disabled:!!y,"aria-busy":y===e,onClick:()=>b(e),children:[(0,$.jsx)(`span`,{className:`session-tree-marker relative z-[2] grid size-6 place-items-center justify-self-center rounded-sm bg-surface-muted text-content-secondary [.session-tree-node[data-kind='tool']_&]:bg-warning-soft [.session-tree-node[data-kind='tool']_&]:text-warning-strong [.session-tree-node.leaf_&]:bg-star [.session-tree-node.leaf_&]:text-on-accent [.session-tree-mark.active_&]:bg-star-soft [.session-tree-mark.active_&]:text-star-strong`,children:y===e?(0,$.jsx)(Zt,{className:`size-3.5`}):(0,$.jsx)(_t,{size:14})}),(0,$.jsxs)(`span`,{className:`session-tree-node-copy flex min-w-0 flex-col gap-0.5 [&_small]:truncate [&_small]:text-xs [&_small]:text-content-muted [&_strong]:truncate [&_strong]:text-sm [&_strong]:font-medium`,children:[(0,$.jsx)(`strong`,{children:e.label}),(0,$.jsx)(`small`,{children:e.sessionName||w(`navigation:appOverlays.untitledChat`)}),(0,$.jsx)(`small`,{children:w(`chat:sessionTree.markTimes`,{sessionTime:D(e.sessionModified),nodeTime:D(e.nodeTimestamp)})})]}),y===e?(0,$.jsx)(`em`,{children:w(`chat:sessionTree.navigating`)}):e.active&&(0,$.jsx)(`em`,{children:w(`chat:sessionTree.markActive`)})]}),x===e&&(0,$.jsxs)(`div`,{role:`group`,"aria-label":w(`chat:sessionTree.otherBranchTitle`),className:`-mt-1 grid gap-2 rounded-sm border border-stroke bg-surface-subtle p-2.5 text-xs text-content-secondary`,"data-session-tree-mark-confirm":!0,children:[(0,$.jsxs)(`p`,{className:`flex items-start gap-1.5 text-content`,children:[(0,$.jsx)(et,{size:13,className:`mt-0.5 flex-none`,"aria-hidden":`true`}),(0,$.jsxs)(`span`,{children:[(0,$.jsx)(`strong`,{className:`font-medium`,children:w(`chat:sessionTree.otherBranchTitle`)}),(0,$.jsx)(`span`,{className:`block text-content-muted`,children:w(`chat:sessionTree.otherBranchMessage`)})]})]}),(0,$.jsxs)(`div`,{className:`flex justify-end gap-2`,children:[(0,$.jsx)(Y,{type:`button`,size:`sm`,variant:`ghost`,className:`max-[650px]:h-11`,onClick:C,children:w(`common:ui.cancel`)}),(0,$.jsx)(Y,{ref:E,type:`button`,size:`sm`,className:`max-[650px]:h-11`,onClick:()=>S(e),children:w(`chat:sessionTree.switchBranch`)})]})]})]},`${e.sessionId}:${e.entryId}`)):(0,$.jsx)(`p`,{className:`grid min-h-[180px] place-items-center text-xs text-content-muted`,children:w(`chat:sessionTree.noMarksYet`)})]}):(0,$.jsx)(`div`,{className:`min-h-0 min-w-0 flex-1 basis-0 overflow-auto overscroll-contain [scrollbar-gutter:stable]`,"data-testid":`session-tree-list`,ref:u,children:d.length>0?c?(0,$.jsx)(Ea,{nodes:f,viewportRef:u,selectedId:p,typeLabel:m,stateLabel:h,onSelect:g}):(0,$.jsx)(`div`,{className:`session-tree-canvas flex w-max min-w-full items-start justify-center gap-9 px-7 pt-6.5 pb-12`,children:d.map(e=>(0,$.jsx)(Da,{segment:e,viewportRef:u,selectedId:p,typeLabel:m,stateLabel:h,onSelect:g},e.id))}):(0,$.jsx)(`p`,{className:`grid min-h-[180px] place-items-center text-xs text-content-muted`,children:o?w(`chat:sessionTree.loading`):s||w(`chat:sessionTree.empty`)})})]})}function ka({label:e,onClick:t}){return(0,$.jsxs)(Y,{variant:`secondary`,className:`w-full min-w-0`,title:e,onClick:t,children:[(0,$.jsx)(at,{size:13}),(0,$.jsx)(`span`,{className:`min-w-0 truncate`,children:e})]})}function Aa({mobileLayout:e,selected:t,loading:n,error:r,streaming:i,dataStreaming:a,parentSession:o,parentEntryId:s,childSessions:c,canLabel:u,canDerive:d,label:f,summarize:p,savingLabel:m,creatingChild:h,navigating:g,typeLabel:_,stateLabel:v,onBackToList:y,onLabelChange:b,onSummarizeChange:x,onSaveLabel:S,onRemoveLabel:C,onCreateChild:w,onNavigate:T,onRefresh:E,onOpenRelated:D}){let{t:O,language:k}=l();return(0,$.jsxs)(`div`,{className:`chat-resource-config session-tree-inspector flex min-h-0 min-w-0 flex-col gap-4 overflow-y-auto overscroll-contain bg-panel p-[18px] [&_>_p]:m-auto [&_>_p]:text-xs [&_>_p]:text-content-muted [&_p]:text-xs [&_p]:text-content-muted [&_strong]:text-[15px] [&_strong]:font-medium ${e?``:`border-l border-stroke-soft`}`,children:[e&&(0,$.jsx)(`div`,{className:`sticky top-0 z-[2] -mx-1.5 -mt-2 flex border-b border-stroke-soft bg-panel px-0.5 pb-2`,children:(0,$.jsxs)(Y,{variant:`ghost`,className:`min-h-11 justify-start px-2`,onClick:y,children:[(0,$.jsx)(V,{size:17}),O(`chat:sessionTree.backToNodes`)]})}),t?(0,$.jsxs)($.Fragment,{children:[(o||c.length>0)&&(0,$.jsxs)(`div`,{className:`session-tree-lineage flex flex-col gap-1.5 border-b border-stroke-soft pb-3 [&_>_strong]:text-xs [&_>_strong]:font-medium [&_>_strong]:text-content-muted [&_button]:justify-start [&_button]:text-left [&_button]:text-xs`,children:[(0,$.jsx)(`strong`,{children:O(`chat:sessionTree.conversationLineage`)}),o&&(0,$.jsx)(ka,{label:O(`chat:sessionTree.returnToOriginalChat`,{name:o.name||O(`chat:chatPage.newChat`)}),onClick:()=>D(o,s)}),c.map(e=>(0,$.jsx)(ka,{label:O(`chat:sessionTree.openSeparateChat`,{name:e.name||O(`chat:chatPage.newChat`)}),onClick:()=>D(e)},e.id))]}),(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`span`,{className:`session-tree-selection-kind mb-1 flex items-center justify-between gap-2 text-xs text-content-muted [&_em]:rounded-xs [&_em]:border [&_em]:border-star-border [&_em]:bg-star-soft [&_em]:px-1.5 [&_em]:py-0.5 [&_em]:font-medium [&_em]:text-star-strong [&_em]:not-italic`,children:[_(t),v(t)&&(0,$.jsx)(`em`,{children:v(t)})]}),(0,$.jsx)(`strong`,{children:t.label||_(t)}),(0,$.jsx)(`p`,{children:t.text||O(`chat:sessionTree.noPreview`)})]}),(0,$.jsxs)(`div`,{className:`chat-resource-inputs flex flex-col gap-3 [&_label]:grid [&_label]:gap-1.5 [&_label]:text-xs [&_label]:font-medium [&_label]:text-content-secondary`,children:[u&&(0,$.jsxs)($.Fragment,{children:[(0,$.jsxs)(`label`,{children:[(0,$.jsx)(`span`,{children:O(`chat:sessionTree.nodeLabel`)}),(0,$.jsx)(Yn,{value:f,maxLength:80,placeholder:O(`chat:sessionTree.labelPlaceholder`),onChange:e=>b(e.target.value)})]}),(0,$.jsxs)(Y,{variant:`secondary`,disabled:m||i||a,onClick:S,children:[(0,$.jsx)(_t,{size:14}),O(m?`chat:sessionTree.savingLabel`:`chat:sessionTree.saveLabel`)]}),!!t.label&&(0,$.jsxs)(Y,{variant:`secondary`,disabled:m||i||a,onClick:C,children:[(0,$.jsx)(St,{size:14}),O(`chat:sessionTree.removeLabel`)]})]}),u&&(0,$.jsxs)(Y,{variant:`secondary`,disabled:h||i||a,onClick:w,children:[(0,$.jsx)(qe,{size:14}),O(h?`chat:sessionTree.creatingChildChat`:`chat:sessionTree.createChildChat`)]}),d&&(0,$.jsxs)(`label`,{className:`session-tree-summary-option cursor-pointer grid-cols-[minmax(0,1fr)_auto] items-center [&_small]:col-span-full [&_small]:leading-relaxed [&_small]:font-normal [&_small]:text-content-muted`,children:[(0,$.jsx)(`span`,{children:O(`chat:sessionTree.abandonedBranchSummary`)}),(0,$.jsx)(Vt,{checked:p,disabled:t.leaf||i||a,onCheckedChange:x,"data-session-tree-summary":!0}),(0,$.jsx)(`small`,{children:O(`chat:sessionTree.abandonedBranchSummaryHint`)})]})]}),d&&(0,$.jsx)(`p`,{children:O(`chat:sessionTree.sideEffectsRemain`)}),t.timestamp&&(0,$.jsx)(`p`,{children:new Intl.DateTimeFormat(k,{dateStyle:`medium`,timeStyle:`short`}).format(new Date(t.timestamp))}),r&&(0,$.jsx)(`p`,{role:`alert`,className:`text-danger!`,children:r}),d&&(0,$.jsxs)(Y,{className:`chat-resource-confirm self-start`,disabled:g||t.leaf||i||a,onClick:T,children:[(0,$.jsx)(We,{size:15}),g?O(`chat:sessionTree.navigating`):t.leaf?O(`chat:sessionTree.currentPosition`):O(`chat:sessionTree.continueFromNode`)]})]}):(0,$.jsx)(`p`,{children:n?O(`chat:sessionTree.loading`):r||O(`chat:sessionTree.chooseNode`)}),r&&!t&&(0,$.jsx)(Y,{variant:`secondary`,onClick:E,children:O(`chat:sessionTree.retry`)})]})}function ja({open:e,sessionId:t,streaming:n,onClose:r,onNavigated:i,onCreateChildSession:a,initialView:o=`branches`,returnFocusRef:s,notify:c}){let{t:u,language:d}=l(),f=j(),p=A(),m=f||p,[h,g]=(0,Q.useState)(null),[_,v]=(0,Q.useState)([]),[y,b]=(0,Q.useState)(`branches`),[x,S]=(0,Q.useState)(!1),[C,w]=(0,Q.useState)(`list`),[T,E]=(0,Q.useState)(``),[D,O]=(0,Q.useState)(``),[k,M]=(0,Q.useState)(``),[N,P]=(0,Q.useState)([]),[F,I]=(0,Q.useState)(!1),[L,R]=(0,Q.useState)(!1),[z,B]=(0,Q.useState)(null),[V,H]=(0,Q.useState)(null),[U,W]=(0,Q.useState)(!1),[ee,te]=(0,Q.useState)(!1),[ne,re]=(0,Q.useState)(!1),[ie,ae]=(0,Q.useState)(!1),[oe,se]=(0,Q.useState)(!1),[ce,G]=(0,Q.useState)(``),le=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!e||!t)return;let n=!1;return b(o),w(`list`),E(``),te(!0),G(``),Promise.all([X.getSessionTree(t),X.listSessions()]).then(([e,t])=>{n||(g(e),v(t.sessions||[]),O(e.leafId||e.nodes[0]?.id||``))}).catch(e=>{n||G(Z(e))}).finally(()=>{n||te(!1)}),()=>{n=!0}},[e,t]),(0,Q.useEffect)(()=>{e||(g(null),v([]),O(``),w(`list`),M(``),B(null),H(null),W(!1),G(``))},[e]),(0,Q.useEffect)(()=>{if(!e||y!==`marks`||F)return;let t=!0;return R(!0),G(``),X.listSessionTreeLabels(500).then(e=>{t&&(P(e.labels||[]),I(!0))}).catch(e=>t&&G(Z(e))).finally(()=>t&&R(!1)),()=>{t=!1}},[e,y,F]);let ue=(0,Q.useMemo)(()=>{let e=T.trim().toLocaleLowerCase(d);return e?N.filter(t=>`${t.label} ${t.sessionName}`.toLocaleLowerCase(d).includes(e)):N},[N,d,T]),de=async(e,t=!1)=>{if(!z){if(!e.active&&!t){H(e);return}H(null),B(e),G(``);try{let t=null;if(!e.active){if(t=await X.navigateSessionTreeTarget(e.sessionId,e.entryId),t.cancelled){B(null);return}fr(e.sessionId)}mn(e.sessionId,`open`,e.entryId),r(),t&&c&&zr(e.sessionId,t,u(`chat:sessionTree.switchedBranch`),{notify:c,t:u})}catch(e){G(Z(e)),B(null)}}},fe=(0,Q.useMemo)(()=>xa(h?.nodes||[]),[h]),pe=(0,Q.useCallback)(e=>({user:u(`chat:sessionTree.userMessage`),assistant:u(`chat:sessionTree.agentMessage`),tool:u(`chat:sessionTree.toolResult`),"tool-call":u(`chat:sessionTree.toolCall`),summary:u(`chat:sessionTree.branchSummary`),compaction:u(`chat:sessionTree.compactionSummary`),settings:u(`chat:sessionTree.settingsChange`),label:u(`chat:sessionTree.labelChange`),position:u(`chat:sessionTree.branchPosition`),extension:u(`chat:sessionTree.extensionEntry`),metadata:u(`chat:sessionTree.metadataEntry`),message:u(`chat:sessionTree.message`)})[e.kind]||e.type,[u]),me=(0,Q.useMemo)(()=>{let e=T.trim().toLocaleLowerCase(d);return Ca(fe,t=>ya(t,y,x)?!e||`${t.label} ${t.text} ${pe(t)}`.toLocaleLowerCase(d).includes(e):!1)},[fe,d,T,x,pe,y]),K=(0,Q.useMemo)(()=>me.map(wa),[me]),he=(0,Q.useMemo)(()=>Sa(me),[me]),q=(0,Q.useMemo)(()=>Sa(fe),[fe]).find(e=>e.id===D)||null,ge=h?.lineage?.parentSessionId?_.find(e=>e.id===h.lineage?.parentSessionId):null,_e=(h?.lineage?.childSessionIds||[]).map(e=>_.find(t=>t.id===e)).filter(e=>!!e),ve=q?.kind===`assistant`&&q.status===`completed`,ye=ve,be=q?!ba.has(q.kind):!1;(0,Q.useEffect)(()=>{M(q?.label||``),W(!1)},[q?.id,q?.label]),(0,Q.useEffect)(()=>{if(D&&he.some(e=>e.id===D))return;let e=[...he].reverse().find(e=>e.active);O(e?.id||he[0]?.id||``)},[D,he]),(0,Q.useEffect)(()=>{if(!e||!D)return;let t=requestAnimationFrame(()=>{document.querySelector(`[data-testid="session-tree-list"] .session-tree-node.selected`)?.scrollIntoView({block:`center`})});return()=>cancelAnimationFrame(t)},[e,T,D,y,he.length]);let xe=async()=>{te(!0),G(``);try{let e=await X.getSessionTree(t);g(e),O(e.leafId||e.nodes[0]?.id||``)}catch(e){G(Z(e))}finally{te(!1)}},Se=async()=>{if(!(!q||ne)){re(!0),G(``);try{let e=await X.setSessionTreeLabel(t,q.id,k);g(e),mr(t,e)}catch(e){G(Z(e))}finally{re(!1)}}},Ce=async()=>{if(!(!q||ne)){re(!0),G(``);try{let e=await X.setSessionTreeLabel(t,q.id,``);g(e),mr(t,e)}catch(e){G(Z(e))}finally{re(!1)}}},we=async()=>{if(!(!q||!ye||oe)){se(!0),G(``);try{await a(q.id),r()}catch(e){G(Z(e))}finally{se(!1)}}},Te=(e,t=``)=>{e.id&&(mn(e.id,`open`,t),r())},Ee=async()=>{if(!(!q||ie||q.leaf||n||h?.streaming)){ae(!0),G(``);try{let e=await X.navigateSessionTree(t,q.id,U);g(e),e.cancelled||(mr(t,e),await i(e.editorText),r(),c&&zr(t,e,u(`chat:chatPage.branchedFromNode`),{notify:c,t:u}))}catch(e){G(Z(e))}finally{ae(!1)}}},De=e=>e.leaf?u(`chat:sessionTree.current`):e.branchPoint?u(`chat:sessionTree.fork`):e.active?u(`chat:sessionTree.active`):``;return(0,$.jsx)(Jn,{open:e,onOpenChange:e=>!e&&r(),children:(0,$.jsxs)(Gn,{onCloseAutoFocus:e=>{let n=s?.current,r=n?.isConnected?n:document.getElementById(`task-${t}-more`);r?.closest(`[data-task-workspace]`)?.getAttribute(`data-active`)===`true`&&(e.preventDefault(),r.focus())},className:`chat-resource-dialog session-tree-dialog grid-rows-[auto_minmax(0,1fr)] gap-0 overflow-hidden border border-stroke bg-solid p-0 ${m?`!h-[calc(100dvh_-_16px)] !w-[calc(100vw_-_16px)] !max-w-none`:`!h-[min(760px,calc(100dvh_-_32px))] !w-[min(1120px,calc(100vw_-_32px))] !max-w-[1120px]`}`,showCloseButton:!1,children:[(0,$.jsxs)(`div`,{className:`chat-resource-head flex items-start justify-between gap-4 border-b border-stroke-soft px-[18px] pt-4 pb-3.5 max-[650px]:p-3.5 [&_[data-slot='dialog-description']]:mt-0.5 [&_[data-slot='dialog-description']]:text-xs [&_[data-slot='dialog-description']]:text-content-muted [&_[data-slot='dialog-title']]:text-base [&_[data-slot='dialog-title']]:font-semibold`,children:[(0,$.jsxs)(`div`,{children:[(0,$.jsxs)(`div`,{className:`session-tree-title flex items-center gap-2`,children:[(0,$.jsx)(et,{className:`size-4 text-content-muted`,strokeWidth:1.75,"aria-hidden":`true`}),(0,$.jsx)(Kn,{children:u(`chat:sessionTree.title`)})]}),(0,$.jsx)(Wn,{children:u(`chat:sessionTree.description`,{nodes:h?.nodeCount||0,branches:h?.branchCount||0})})]}),(0,$.jsx)(Y,{type:`button`,variant:`ghost`,size:`icon`,className:`max-[650px]:size-11`,"aria-label":u(`common:ui.closeDialog`),title:u(`common:ui.closeDialog`),onClick:r,children:(0,$.jsx)(Dt,{size:16})})]}),(0,$.jsxs)(`div`,{className:`chat-resource-body session-tree-layout grid min-h-0 overflow-hidden bg-background ${m?`grid-cols-1 grid-rows-[minmax(0,1fr)]`:`!grid-cols-[minmax(0,1fr)_292px]`}`,children:[(!m||C===`list`)&&(0,$.jsx)(Oa,{view:y,onViewChange:e=>{b(e),H(null),w(`list`)},showAllEntries:x,onShowAllEntriesChange:S,query:T,onQueryChange:E,loading:ee,error:ce,mobileLayout:m,viewportRef:le,segments:K,visibleNodes:he,selectedId:D,typeLabel:pe,stateLabel:De,onSelect:e=>{O(e),m&&w(`detail`)},visibleMarks:ue,marksLoading:L,openingMark:z,onOpenMark:e=>void de(e),confirmingMark:V,onConfirmMark:e=>void de(e,!0),onCancelMark:()=>H(null)}),y!==`marks`&&(!m||C===`detail`)&&(0,$.jsx)(Aa,{mobileLayout:m,selected:q,loading:ee,error:ce,streaming:n,dataStreaming:!!h?.streaming,parentSession:ge??null,parentEntryId:h?.lineage?.sourceEntryId||``,childSessions:_e,canLabel:ve,canDerive:be,label:k,summarize:U,savingLabel:ne,creatingChild:oe,navigating:ie,typeLabel:pe,stateLabel:De,onBackToList:()=>w(`list`),onLabelChange:M,onSummarizeChange:W,onSaveLabel:()=>void Se(),onRemoveLabel:()=>void Ce(),onCreateChild:()=>void we(),onNavigate:()=>void Ee(),onRefresh:()=>void xe(),onOpenRelated:(e,t)=>Te(e,t??``)})]})]})})}function Ma({visible:e,open:t,sessionId:n,streaming:r,revision:i,pulseToken:a,onOpenChange:o,onNavigated:s,onCreateChildSession:c,notify:u,children:d}){let{t:f}=l(),p=dr(n,{enabled:e,streaming:r,revision:i})?.branchCount??0,[m,h]=(0,Q.useState)(`branches`),[g,_]=(0,Q.useState)(!1),v=(0,Q.useRef)(0),y=(0,Q.useRef)(null);(0,Q.useEffect)(()=>()=>cancelAnimationFrame(v.current),[]),(0,Q.useEffect)(()=>{if(!a)return;_(!0);let e=window.setTimeout(()=>_(!1),1800);return()=>window.clearTimeout(e)},[a]);let b=p>0&&(0,$.jsx)(`i`,{"aria-hidden":`true`,className:`ml-auto size-1.5 rounded-full bg-star`}),x=e?(0,$.jsxs)(jt,{"aria-label":f(`chat:sessionTree.menu`),"aria-haspopup":`dialog`,"data-pisper-recall-pulse":g||void 0,onSelect:()=>{y.current=null,h(`branches`),cancelAnimationFrame(v.current),v.current=requestAnimationFrame(()=>o(!0))},children:[(0,$.jsx)(et,{className:g?`motion-reduce:animate-none [animation:session-tree-new-node-pulse_1.8s_var(--ease-out)]`:void 0}),f(`chat:sessionTree.menu`),b]}):null;return(0,$.jsxs)($.Fragment,{children:[d(x,{branches:p,open:(e=`branches`,t=null)=>{y.current=t,h(e),cancelAnimationFrame(v.current),v.current=requestAnimationFrame(()=>o(!0))}}),e&&(0,$.jsx)(ja,{open:t,initialView:m,returnFocusRef:y,sessionId:n,streaming:r,onClose:()=>o(!1),onNavigated:s,onCreateChildSession:c,notify:u})]})}function Na({question:e,more:t,collapsed:n,onAnswer:r}){let{t:i}=l(),[a,o]=(0,Q.useState)(()=>e.questions.map(()=>({selected:[]}))),[s,c]=(0,Q.useState)(()=>e.questions.map(()=>!1)),[u,d]=(0,Q.useState)(!1),[f,p]=(0,Q.useState)(``),m=e.questions.length===1&&!e.questions[0].multiSelect,h=On(e,a);if(n)return(0,$.jsxs)(`p`,{"data-question-more":!0,className:`flex min-h-8 min-w-0 items-center gap-2 rounded-(--r-md) border border-st-attn-border px-3 text-xs text-st-attn`,children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`size-2 flex-none rounded-full bg-st-attn-fill`}),i(`board:question.waiting`,{count:t+1})]});let g=async t=>{if(!u){d(!0),p(``);try{await r(e.id,t)}catch{p(i(`board:question.failed`)),d(!1)}}},_=e=>e.map((e,t)=>{let n=s[t]?e.other?.trim():``;return n?{selected:e.selected,other:n}:{selected:e.selected}}),v=(t,n)=>{let r=e.questions[t],i=a.map((e,i)=>{if(i!==t)return e;if(!r.multiSelect)return{...e,selected:[n]};let a=e.selected.includes(n)?e.selected.filter(e=>e!==n):[...e.selected,n];return{...e,selected:a}});o(i),m&&g({answers:_(i)})};return(0,$.jsxs)(`div`,{"data-question-card":e.id,role:`group`,"aria-label":i(`board:question.label`),"aria-busy":u||void 0,onKeyDown:t=>{if(t.altKey||t.metaKey||t.ctrlKey)return;let n=t.target;if(n.closest(`textarea, input`))return;let r=a.findIndex(e=>!e.selected.length&&!e.other?.trim()),i=r<0?e.questions.length-1:r,o=Number(t.key);if(Number.isInteger(o)&&o>=1&&o<=6){let n=e.questions[i]?.options[o-1];if(!n)return;t.preventDefault(),v(i,n.label)}else t.key===`Enter`&&!n.closest(`button`)&&h&&(t.preventDefault(),g({answers:_(a)}))},className:`flex max-h-[min(60vh,560px)] min-w-0 flex-col gap-3 overflow-y-auto rounded-(--r-lg) border border-st-attn-border bg-st-attn-soft px-3.5 py-3 text-foreground`,children:[(0,$.jsxs)(`p`,{className:`flex items-center gap-2 text-xs font-medium text-warning-strong`,children:[(0,$.jsx)(ni,{className:`size-4 flex-none`,"aria-hidden":`true`}),i(`board:question.title`),t>0&&(0,$.jsx)(`span`,{className:`font-normal text-content-muted`,children:i(`board:question.moreAfter`,{count:t})})]}),e.questions.map((t,n)=>{let r=a[n],l=t.header?`${t.header}:${t.question}`:t.question;return(0,$.jsxs)(`fieldset`,{"data-question-item":n,className:`flex min-w-0 flex-col gap-1.5`,children:[(0,$.jsxs)(`legend`,{className:`mb-1.5 flex min-w-0 flex-col gap-0.5`,children:[t.header&&(0,$.jsx)(`span`,{className:`text-xs font-medium text-content-muted`,children:t.header}),(0,$.jsx)(`span`,{className:`text-sm leading-5 text-content`,children:t.question})]}),(0,$.jsxs)(`div`,{role:t.multiSelect?`group`:`radiogroup`,"aria-label":l,className:`flex flex-wrap gap-1.5`,children:[t.options.map((e,i)=>{let a=r.selected.includes(e.label);return(0,$.jsxs)(`button`,{type:`button`,role:t.multiSelect?`checkbox`:`radio`,"aria-checked":a,disabled:u,"data-question-option":e.label,title:e.description||void 0,className:Xt(`flex min-h-9 max-w-full min-w-0 items-center gap-1.5 rounded-(--r-md) border px-2.5 py-1 text-left text-[13px] transition-colors duration-(--d-fast) focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-focus disabled:opacity-60 pointer-coarse:min-h-11`,a?`border-content bg-content text-panel`:`border-stroke-strong bg-panel text-content hover:bg-surface-hover`),onClick:()=>v(n,e.label),children:[(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`font-mono text-[11px] opacity-60 pointer-coarse:hidden`,children:i+1}),(0,$.jsxs)(`span`,{className:`flex min-w-0 flex-col`,children:[(0,$.jsx)(`span`,{className:`break-words`,children:e.label}),e.description&&(0,$.jsx)(`span`,{className:Xt(`text-xs break-words`,a?`opacity-80`:`text-content-muted`),children:e.description})]}),a&&t.multiSelect&&(0,$.jsx)(z,{className:`size-3.5 flex-none`,"aria-hidden":`true`})]},e.label)}),(0,$.jsx)(`button`,{type:`button`,"aria-expanded":s[n],disabled:u,"data-question-other":n,className:Xt(`flex min-h-9 items-center rounded-(--r-md) border border-dashed border-stroke-strong px-2.5 text-[13px] text-content-secondary hover:bg-surface-hover focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-focus pointer-coarse:min-h-11`,s[n]&&`border-solid bg-panel`),onClick:()=>c(e=>e.map((e,t)=>t===n?!e:e)),children:i(`board:question.other`)})]}),s[n]&&(0,$.jsx)(`textarea`,{"aria-label":i(`board:question.otherLabel`,{question:t.question}),maxLength:An.other,rows:2,disabled:u,value:r.other??``,placeholder:i(`board:question.otherPlaceholder`),className:`min-h-16 w-full resize-y rounded-(--r-md) border border-control bg-panel px-2.5 py-1.5 text-sm text-content outline-none focus:border-focus focus:ring-3 focus:ring-focus-ring max-[650px]:text-[16px]`,onChange:e=>{let t=e.target.value;o(e=>e.map((e,r)=>r===n?{...e,other:t}:e))},onKeyDown:e=>{e.key===`Enter`&&(e.metaKey||e.ctrlKey)&&h&&(e.preventDefault(),g({answers:_(a)}))}})]},`${e.id}-${n}`)}),f&&(0,$.jsx)(`p`,{role:`alert`,className:`text-xs text-[var(--danger)]`,children:f}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-end gap-2`,children:[(0,$.jsx)(Y,{type:`button`,variant:`ghost`,size:`sm`,disabled:u,"data-question-skip":!0,className:`pointer-coarse:min-h-11`,onClick:()=>void g({skip:!0}),children:i(`board:question.skip`)}),(!m||s[0])&&(0,$.jsx)(Y,{type:`button`,size:`sm`,disabled:u||!h,loading:u,"data-question-submit":!0,className:`pointer-coarse:min-h-11`,onClick:()=>void g({answers:_(a)}),children:i(`board:question.submit`)})]})]})}async function Pa({templatePrompt:e,configureHint:t,notify:n,onOpenModelSettings:r,onInsertPrompt:i}){try{let a=await D(`/api/visual/models`);a.image||a.video?i(e):(n?.(t),r?.())}catch{i(e)}}function Fa(e){return(e.target instanceof Element?e.target:null)?.closest(`[data-shortcut-recorder], [role="dialog"], [role="alertdialog"], [role="menu"], [role="listbox"], .xterm, .terminal-xterm, .terminal-panel, [data-terminal]`)?!0:Array.from(document.querySelectorAll(`[role="dialog"], [role="alertdialog"], dialog[open]`)).some(e=>e.getClientRects().length>0)}function Ia(e){let t=(0,Q.useRef)(e);t.current=e;let{enabled:n,binding:r}=e;(0,Q.useEffect)(()=>{if(!n||!r)return;let e=null,i=null,a=()=>{e=null,i&&(i=null,t.current.onCancel())},o=n=>{if(i&&n.key===`Escape`&&!n.isComposing){a(),n.preventDefault();return}!t.current.enabled||n.defaultPrevented||n.isComposing||n.keyCode===229||n.repeat||e||document.visibilityState===`hidden`||Fa(n)||!yn(n,r)||(e=n.code,t.current.onStart()&&(i={code:n.code,ctrl:n.ctrlKey,meta:n.metaKey,alt:n.altKey,shift:n.shiftKey},n.preventDefault()))},s=n=>{n.code===e&&(e=null),i&&(n.code===i.code||i.ctrl&&(!n.ctrlKey||n.code.startsWith(`Control`))||i.meta&&(!n.metaKey||n.code.startsWith(`Meta`))||i.alt&&(!n.altKey||n.code.startsWith(`Alt`))||i.shift&&(!n.shiftKey||n.code.startsWith(`Shift`)))&&(i=null,t.current.onRelease())},c=()=>{document.visibilityState===`hidden`&&a()};return window.addEventListener(`keydown`,o),window.addEventListener(`keyup`,s,!0),window.addEventListener(`blur`,a),document.addEventListener(`visibilitychange`,c),()=>{window.removeEventListener(`keydown`,o),window.removeEventListener(`keyup`,s,!0),window.removeEventListener(`blur`,a),document.removeEventListener(`visibilitychange`,c),a()}},[n,r])}function La(e){if(!e.length)return 0;let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];let n=Math.sqrt(t/e.length);return n<.0056?0:Math.min(1,Math.sqrt(n)*2.6)}function Ra(e=.35){let t=0;return{push(n){return t=t*(1-e)+n*e,t},reset(){t=0}}}function za(e,t=140){let n=e.trim();return n.length>t?`${n.slice(0,t-1)}…`:n}var Ba=16e3,Va=20,Ha=Ba*Va/1e3;function Ua(e,{onsetMs:t=80,minVoicedMs:n=160,silenceMs:r=900}={}){for(let e of[t,n,r])if(!Number.isFinite(e)||e<=0)throw Error(`Invalid VAD endpoint duration`);let i=e(),a=new Int16Array(Ha),o=0,s=0,c=0,l=0,u=!1,d=!1,f=!1,p=()=>u&&c*Va>=n;return{get hasSpeech(){return p()},acceptPcm(e){if(f||d)return!1;for(let n=0;n<e.length;n+=1){let f=Number.isFinite(e[n])?Math.max(-1,Math.min(1,e[n])):0;if(a[o++]=f*(f<0?32768:32767),o!==Ha)continue;o=0;let m=i.processFrame(a);if(m<0)throw Error(`VAD frame processing failed`);if(m===1)s+=1,c+=1,l=0,s*Va>=t&&(u=!0);else if(s=0,l+=1,u||(c=0),l*Va>=r){if(p())return d=!0,!0;u=!1,c=0}}return!1},reset(){f||(i.destroy(),i=e(),o=s=c=l=0,u=d=!1,a.fill(0))},dispose(){f||(f=!0,o=0,i.destroy())}}}async function Wa(e={}){let{default:n,VADMode:r}=await t(async()=>{let{default:e,VADMode:t}=await import(`./embedded-D2rqyswH.js`);return{default:e,VADMode:t}},[]),i=await n();return Ua(()=>new i(e.mode??r.AGGRESSIVE,Ba),e)}var Ga=()=>new DOMException(`Speech setup cancelled.`,`AbortError`);function Ka(e){let[t,n]=(0,Q.useState)(null),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(!1),[s,c]=(0,Q.useState)(``),l=(0,Q.useRef)(null),u=(0,Q.useRef)(!1),d=(0,Q.useRef)(0),f=(0,Q.useRef)(0),p=(0,Q.useRef)(0),m=(0,Q.useRef)(e);m.current=e;let h=(0,Q.useCallback)(e=>{d.current++,f.current++;let t=l.current;l.current=null,t&&(t.signal.removeEventListener(`abort`,t.abort),e?t.reject(e):t.resolve()),u.current&&(i(!1),o(!1))},[]),g=(0,Q.useCallback)(e=>{u.current&&(n(e),c(``),l.current&&Jr(e,m.current).every(e=>e.status===`installed`)&&h())},[h]),_=(0,Q.useCallback)(async e=>{let t=d.current,n=++f.current,r=()=>u.current&&t===d.current&&n===f.current&&!e?.aborted;try{let t=await Vr(e);r()&&g(t)}catch(e){if(r())throw e}},[g]);(0,Q.useEffect)(()=>(u.current=!0,_().catch(()=>{}),()=>{u.current=!1,h(Ga())}),[h,_]),(0,Q.useEffect)(()=>{if(!r)return;let e=new AbortController,t,n=async()=>{try{await _(e.signal)}catch(t){e.signal.aborted||c(t instanceof Error?t.message:String(t))}finally{e.signal.aborted||(t=setTimeout(()=>void n(),750))}};return n(),()=>{e.abort(),clearTimeout(t)}},[r,_]);let v=(0,Q.useCallback)(async e=>{if(y(e),!u.current)throw Ga();h(Ga());let t=++f.current;return new Promise((n,r)=>{let a=()=>{l.current===o&&h(e.reason||Ga())},o={signal:e,abort:a,resolve:n,reject:r};if(l.current=o,e.addEventListener(`abort`,a,{once:!0}),e.aborted){a();return}Vr(e).then(n=>{!u.current||l.current!==o||e.aborted||(t===f.current&&g(n),l.current===o&&i(!0))},e=>{l.current===o&&h(e)})})},[g,h]),b=(0,Q.useCallback)(async e=>{let t=d.current,n=++p.current,r=()=>u.current&&t===d.current&&n===p.current;o(!0),c(``);try{await e(),r()&&await _()}catch(e){r()&&c(e instanceof Error?e.message:String(e))}finally{r()&&o(!1)}},[_]);return{catalog:t,open:r,loading:a,error:s,selectedVoice:t?.defaults.voice||``,ensureReady:v,models:t?Jr(t,e):[],show:()=>{h(Ga()),i(!0),c(``)},close:()=>h(Ga()),download:e=>b(()=>Kr(e)),cancelDownload:e=>b(()=>Gr(e)),downloadAll:()=>b(async()=>{if(t)for(let e of Jr(t,m.current))[`installed`,`downloading`,`verifying`].includes(e.status)||await Kr(e.id)})}}var qa=8388608;function Ja(e,t){return y(t),new Promise((n,r)=>{let i=()=>r(b(t));t.addEventListener(`abort`,i,{once:!0}),e.then(n,r).finally(()=>t.removeEventListener(`abort`,i))})}var Ya=10,Xa=500;async function Za(e,t,n,r){for(let i=0;;i+=1){let a=await fetch(`/api/speech/synthesize`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({text:e,voiceId:t,requestId:n}),signal:r});if(a.status!==409||i>=Ya)return a;let o=await a.json().catch(()=>({}));if(!o.error||!/busy/i.test(o.error))return a;await Ja(new Promise(e=>setTimeout(e,Xa)),r)}}async function Qa(e){if(!e.ok){let t=await e.json().catch(()=>({}));throw Error(t.error||`Speech synthesis failed (${e.status}).`)}if(!e.headers.get(`content-type`)?.startsWith(`audio/wav`)||!e.body)throw Error(`Invalid speech audio response.`);let t=e.body.getReader(),n=[],r=0;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;if(r+=i.byteLength,r>qa)throw Error(`Speech audio exceeds the supported limit.`);n.push(i)}}finally{await t.cancel().catch(()=>{}),t.releaseLock()}if(r<44)throw Error(`Speech audio is empty.`);let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i.buffer}async function $a(e,t,n,r){y(n);let i=v(n);try{await eo(e,t,i,r)}finally{i.abort(new DOMException(`Speech playback ended.`,`AbortError`)),i.dispose()}}async function eo(e,n,r,i){let{signal:a}=r,{speechSegments:o}=await Ja(t(()=>import(`./speech-text-BTwYi9Sb.js`),__vite__mapDeps([141,91,1,2,3,88,89,90,34])),a);y(a);let s=(typeof e==`string`?(async function*(){yield*o(e)})():(await Ja(t(()=>import(`./speech-stream-text-DF6aAUVb.js`),__vite__mapDeps([142,91,1,2,3,88,89,90,34,13,141])),a)).streamingSpeechSegments(e,a))[Symbol.asyncIterator](),c=!!window.__PISPER_MOBILE_APP__,l=new Set,u,d,f,p=e=>{(c?Ur(`mobile_cancel_speech`,{requestId:e}):D(`/api/speech/cancel`,{method:`POST`,body:{requestId:e},timeout:3e3})).catch(()=>{})},m=()=>{for(let e of l)p(e);try{d?.stop()}catch{}f?.(a.reason||new DOMException(`Speech playback cancelled.`,`AbortError`))};a.addEventListener(`abort`,m,{once:!0});let h=e=>{y(a);let t=crypto.randomUUID();l.add(t);let r=(async()=>{if(c){let r=await Ur(`mobile_synthesize_speech`,{text:e,voiceId:n,requestId:t});if(a.aborted&&(p(t),y(a)),!r||typeof r.audioId!=`string`||!r.audioId.trim()||r.audioId.length>128||!Number.isInteger(r.sampleRate)||r.sampleRate<8e3||r.sampleRate>48e3||!Number.isFinite(r.durationMs)||r.durationMs<=0||r.durationMs>45e3)throw Error(`Invalid native speech audio.`);return{requestId:t,native:r}}let r=v(a,6e4);try{let i=await Za(e,n,t,r.signal);return{requestId:t,wav:await Qa(i)}}finally{r.dispose()}})();return r.catch(()=>{}),r};try{if(!c){u=new AudioContext({sampleRate:24e3});let e;try{await Ja(Promise.race([u.resume(),new Promise((t,n)=>{e=setTimeout(()=>n(Error(`Audio playback is unavailable.`)),5e3)})]),a)}finally{clearTimeout(e)}}let e=async()=>{let e=await Ja(s.next(),a);return e.done?void 0:h(e.value)},t=e(),n=!1;for(;;){let r=await Ja(t,a);if(y(a),!r)break;if(t=e(),t.catch(()=>{}),n=!0,i?.(),r.native){if((await Ja(Ur(`mobile_play_speech`,{audioId:r.native.audioId,requestId:r.requestId}),a))?.completed!==!0)throw Error(`Speech playback was interrupted.`)}else{let e=await Ja(u.decodeAudioData(r.wav),a);if(y(a),e.numberOfChannels!==1||!Number.isFinite(e.duration)||e.duration<=0||e.duration>45)throw Error(`Invalid speech audio duration.`);let t=u.createBufferSource();d=t,t.buffer=e,t.connect(u.destination);try{await new Promise((e,n)=>{f=n,t.onended=()=>e(),t.start()})}finally{f=void 0,t.onended=null,t.disconnect(),d=void 0}}l.delete(r.requestId),y(a)}if(!n)throw Error(`The reply has no speakable text.`)}finally{a.removeEventListener(`abort`,m),r.abort(new DOMException(`Speech playback ended.`,`AbortError`)),s.return?.(void 0).catch(()=>{});for(let e of l)p(e);try{d?.stop()}catch{}await u?.close().catch(()=>{})}}var to={schemaVersion:1,scope:`Offline license texts and provenance notices for the catalogued speech resources and local derivatives. This document is not legal advice, commercial-use clearance, a complete training-data rights audit, or approval for redistribution or formal release. Packaging this small notice file does not package the large models or resolve pending obligations. Native sherpa binaries and their compiled or embedded dependencies require a separate license/linkage and source-delivery audit; switching TTS models does not prove the binaries contain no GPL components or satisfy their obligations.`,licenseIdsMeaning:`References identify retained license documents applicable to the described components or their stated source projects. Multiple references are not alternative dual-license choices and are not a complete SPDX expression. A repository declaration does not relicense unrelated bundled data.`,statusDefinitions:{confirmed:`The specific content or source match described in summary was verified; this is not a whole-chain rights guarantee.`,declared:`An upstream license declaration supports the classification, without a complete reproducible provenance proof.`,pending:`The listed provenance, rights, or distribution obligations remain unresolved even where a license declaration exists.`},pathScopes:{model:`Paths are relative to the original downloaded model root. A terminal /** matches every descendant; all other paths are exact.`,shared:`Paths are relative to the application's shared resource root.`},licenses:[{id:`apache-2.0`,name:`Apache License 2.0 (X-ASR source text)`,text:` Apache License
|
|
3
3
|
Version 2.0, January 2004
|
|
4
4
|
http://www.apache.org/licenses/
|
|
5
5
|
|
|
@@ -508,7 +508,7 @@ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
|
|
508
508
|
## Dictionary. Further addictions and improvements are planned
|
|
509
509
|
## for forthcoming releases.
|
|
510
510
|
##
|
|
511
|
-
`,sourceUrl:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/melo/text/cmudict.rep`,sha256:`08ee91f3c05c55160bdc599247ba53e5de8cc2597766fdb22b54a81cb24dd954`}],models:[{id:`x-asr-480ms-int8`,revision:`2026-06-05`,attribution:`X-ASR by Gilgamesh-J / GilgameshWind; trained using icefall and deployed with sherpa-onnx. The locked HF model card expressly covers model artifacts and declares Apache-2.0. The separately discovered GitHub license commit is not the locked HF revision. No root LICENSE or NOTICE was listed in the inspected HF tree; this is not proof that every historical distribution lacks NOTICE. Retain applicable upstream notices when found.`,archive:{url:`https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-x-asr-480ms-streaming-zipformer-transducer-zh-en-punct-int8-2026-06-05.tar.bz2`,sha256:`fa5f63d618e5a01526e275a358bb7772e403f84808a4769fba52cffd8160bf74`},groups:[{id:`xasr-weights`,pathScope:`model`,paths:[`encoder.int8.onnx`,`decoder.onnx`,`joiner.int8.onnx`],licenseIds:[`apache-2.0`],status:`pending`,summary:`Apache-2.0 is explicitly declared for X-ASR model artifacts. The sherpa export script describes icefall streaming ONNX export and INT8 quantization; installed file hashes match the catalog, but the 2026-06-05 archive-to-checkpoint/build identity is not established.`,pendingReasons:[`Exact checkpoint and source commits used to build the 2026-06-05 INT8 archive remain unverified; the export script downloads moving main URLs. Training-data rights are not fully audited.`],evidence:[{url:`https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/689ff18c584d29910da37b6fe904db0c1489c9d1/README.md`,sha256:`7acc6f439d3e39e46de4298ccf8a8f6a483fdc5f9f5d08e61422b63760ec37b1`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/v1.13.7/scripts/zipformer-transducer/x-asr/export-streaming.sh`,sha256:`63b018fe72a29e9a41c6d4e358085b5ad1614e021c0d9f3c05a2d11f1dff0d81`}]},{id:`xasr-tokens`,pathScope:`model`,paths:[`tokens.txt`],licenseIds:[`apache-2.0`],status:`pending`,summary:`X-ASR token resource, not the SentencePiece or sherpa software. The punctuation export block downloads X-ASR-zh-en/zipformer/data/lang_5000_with_punctuation/tokens.txt. Catalog content SHA256: b818a60878b9aae978cbb8ad594acbd403d76d1af2e31ef4197c84e2dbdba27c.`,pendingReasons:[`The historical source revision for the token file in the 2026-06-05 archive is not pinned by the export script.`],evidence:[{url:`https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/689ff18c584d29910da37b6fe904db0c1489c9d1/README.md`,sha256:`7acc6f439d3e39e46de4298ccf8a8f6a483fdc5f9f5d08e61422b63760ec37b1`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/v1.13.7/scripts/zipformer-transducer/x-asr/export-streaming.sh`,sha256:`63b018fe72a29e9a41c6d4e358085b5ad1614e021c0d9f3c05a2d11f1dff0d81`}]},{id:`xasr-bpe`,pathScope:`model`,paths:[`bpe.model`],licenseIds:[`apache-2.0`],status:`pending`,summary:`X-ASR BPE resource. The export script renames X-ASR-zh-en/zipformer/data/lang_5000_with_punctuation/bpe_punc.model to bpe.model. Its license classification comes from X-ASR, not from the software that reads the SentencePiece format.`,pendingReasons:[`The historical BPE source commit and exact archive build provenance remain unverified.`],evidence:[{url:`https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/689ff18c584d29910da37b6fe904db0c1489c9d1/README.md`,sha256:`7acc6f439d3e39e46de4298ccf8a8f6a483fdc5f9f5d08e61422b63760ec37b1`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/v1.13.7/scripts/zipformer-transducer/x-asr/export-streaming.sh`,sha256:`63b018fe72a29e9a41c6d4e358085b5ad1614e021c0d9f3c05a2d11f1dff0d81`}]},{id:`xasr-bpe-vocab`,pathScope:`shared`,paths:[`speech-resources/xasr-bpe.vocab`],licenseIds:[`apache-2.0`],status:`pending`,summary:`Modified by Pisper: extracted the ordered SentencePiece pieces and scores as UTF-8 piece<TAB>score<LF> lines. This local text derivative retains the source resource license classification; it is not newly licensed as Pisper-owned model data. Original and derived hashes and generator are bound by xasr-bpe-extraction below.`,pendingReasons:[`The source BPE historical provenance remains pending as described in xasr-bpe. A text extraction does not resolve upstream rights.`],evidence:[{url:`https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/689ff18c584d29910da37b6fe904db0c1489c9d1/README.md`,sha256:`7acc6f439d3e39e46de4298ccf8a8f6a483fdc5f9f5d08e61422b63760ec37b1`}]}],modifications:[{id:`xasr-bpe-extraction`,groupIds:[`xasr-bpe-vocab`],modifiedBy:`Pisper`,summary:`Local BPE text extraction, not retraining. The generator identity records the inspected repository implementation, not a claim about a historical upstream build date.`,source:{path:`bpe.model`,bytes:119265,sha256:`f87a38025a5fdd1e4e9591f6a44bb81295097ce0b80df6f4ab9f44e52c64ca5f`},derived:{path:`speech-resources/xasr-bpe.vocab`,bytes:61562,sha256:`01381aa0c3065832cb8d7462d529e3079a99be56c955ce93b4cb9b78e8aa34e5`},generator:{path:`scripts/speech-bpe.mjs`,sha256:`a1c85731aa3e0be89f04acc79830db784a9d43edb8af9f4fb723bb45bd725786`,method:`sentencePieceModelToVocab decodes ordered protobuf ModelProto.pieces and emits each piece, a tab, its finite score, and a newline without changing the BPE model.`}}]},{id:`vits-melo-tts-zh_en`,revision:`a0d5c6a264c0ef92d70d8661d8cc502d79627cd6`,archive:{url:`https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/vits-melo-tts-zh_en.tar.bz2`,bytes:167006755,sha256:`e58351ed7149f290a54534538badd4077cdbe6fddc964b24d0bee870415d1514`},attribution:`MeloTTS by MyShell.ai; sherpa-onnx ONNX conversion. The retained software license is Copyright (c) 2024 MyShell.ai, MIT. The neural-weight repository separately declares MIT; dictionary and FST resources have separate declarations and pending provenance. Pisper selects the original single female voice via public sid 0 and uses the same original FP32 ONNX, tokens, mixed-language lexicon, dictionary and normalization files on Desktop, Android and iOS. No retraining, quantization, graph/metadata patch or voice-subset derivative is made. The unused new_heteronym.fst and 133-byte model.int8.onnx Git LFS pointer in the transport archive are drained but not installed; retained model files are unchanged. These choices do not imply upstream/speaker endorsement, redistribution approval or completed native-platform acceptance.`,groups:[{id:`melo-weights`,pathScope:`model`,paths:[`model.onnx`],licenseIds:[`mit-melo`],status:`pending`,summary:`The myshell-ai/MeloTTS-Chinese model card at af5d207a364ea4208c6f589c89f57f88414bdd16 declares license: mit for the model repository; this is separate evidence from the MeloTTS software MIT license. The sherpa conversion package carries the exact MyShell.ai MIT text, and original ONNX metadata declares MIT license, melo-vits version 2, Chinese + English, n_speakers=1 and speaker_id=1. The conversion README explicitly describes a single female Chinese+English speaker. sherpa maps public sid 0 to the internal metadata speaker_id; Pisper does not change the graph, metadata or speaker embedding.`,pendingReasons:[`Exact historical checkpoint, training/conversion commits and reproducible archive build identity have not been established; the inspected conversion workflow uses moving upstream references. Training-data permissions, individual speaker consent and applicable personality/publicity rights are not fully audited. The discovered model card revision is evidence of a declaration, not proof of the historical conversion input.`],evidence:[{url:`https://hf-mirror.com/myshell-ai/MeloTTS-Chinese/resolve/af5d207a364ea4208c6f589c89f57f88414bdd16/README.md`,sha256:`40b5b860bacbb3947cbef838719e660d2fe4961eba5b484290b4bedc0253e208`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://hf-mirror.com/csukuangfj/vits-melo-tts-zh_en/resolve/a0d5c6a264c0ef92d70d8661d8cc502d79627cd6/README.md`,sha256:`ae6e44dead53dfdbd5b4a77106226f3118eb910222b46cb5533a3860773fc6c7`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/export-onnx.py`,sha256:`c0be7727d59ad6ceaf39e909b4560b57e704091c69ac3fab6f2f2abfd931c916`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/run.sh`,sha256:`e2afb98d9028eded2983f780468337fc019a8306db926f89e3bdeed18af867bb`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/sherpa-onnx/csrc/offline-tts-vits-model.cc`,sha256:`060907349036d63b60d035843defe7078b83c8099e0d4de323446c7db0d653d0`}]},{id:`melo-tokens`,pathScope:`model`,paths:[`tokens.txt`],licenseIds:[`mit-melo`,`apache-2.0-sherpa`],status:`declared`,summary:`The sherpa Melo export writes enumerated model.hps symbols to tokens.txt. The original 655-byte token file is retained unchanged. Melo software is MIT; sherpa conversion code is Apache-2.0. These code declarations do not independently establish all underlying training-data rights.`,pendingReasons:[],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/export-onnx.py`,sha256:`c0be7727d59ad6ceaf39e909b4560b57e704091c69ac3fab6f2f2abfd931c916`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/LICENSE`,sha256:`cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`}]},{id:`melo-cppjieba-dictionary`,pathScope:`model`,paths:[`dict/hmm_model.utf8`,`dict/idf.utf8`,`dict/jieba.dict.utf8`,`dict/pos_dict/char_state_tab.utf8`,`dict/pos_dict/prob_emit.utf8`,`dict/pos_dict/prob_start.utf8`,`dict/pos_dict/prob_trans.utf8`,`dict/README.md`,`dict/stop_words.utf8`],licenseIds:[`mit-cppjieba`],status:`confirmed`,summary:`Nine ordinary dictionary/README files are byte-identical to the separately HTTPS-downloaded CppJieba sherpa-onnx-2024-04-19 dict archive. The exact release source MIT license retains Copyright (c) 2013. This confirms the documented source-content match, not a whole-chain data-rights guarantee. The small Melo user.dict.utf8 is separately classified and is NOT the 829194-byte pypinyin-derived user dictionary from that source archive.`,pendingReasons:[],evidence:[{url:`https://ghfast.top/https://github.com/csukuangfj/cppjieba/releases/download/sherpa-onnx-2024-04-19/dict.tar.bz2`,sha256:`35c3877c9b9221a5b2d69bbf57d5dbf1ccbe5b7684c60eb42f93db6b2d494f26`},{url:`https://raw.githubusercontent.com/csukuangfj/cppjieba/f03dd931a00330c279c8590275850fd1f6749a18/LICENSE`,sha256:`ba898a14f729ba5e9965da34e3eecd5edd3795f2cc5d7c923b815ba79bb851b0`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/.github/workflows/export-melo-tts-to-onnx.yaml`,sha256:`fc90fc412fd6f3c8a7d593743372a077dd63b2c8ce0780ed9c3a7e05cc8b659e`}]},{id:`melo-user-dictionary`,pathScope:`model`,paths:[`dict/user.dict.utf8`],licenseIds:[`mit-cppjieba`,`mit-melo`],status:`pending`,summary:`Melo ships an unchanged 49-byte user dictionary containing four entries. It matches the locked Melo HF file but differs from the separately downloaded CppJieba release user dictionary. The package MIT text and CppJieba project MIT declaration are retained as source declarations, not proof that either automatically licenses every edit. This file is not attributed to the unrelated historical pypinyin-derived dictionary.`,pendingReasons:[`The exact historical source commit, modifier and license coverage for this 49-byte replacement have not been identified. Retain applicable modifier notices when established.`],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/.github/workflows/export-melo-tts-to-onnx.yaml`,sha256:`fc90fc412fd6f3c8a7d593743372a077dd63b2c8ce0780ed9c3a7e05cc8b659e`},{url:`https://raw.githubusercontent.com/csukuangfj/cppjieba/f03dd931a00330c279c8590275850fd1f6749a18/LICENSE`,sha256:`ba898a14f729ba5e9965da34e3eecd5edd3795f2cc5d7c923b815ba79bb851b0`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://huggingface.co/csukuangfj/vits-melo-tts-zh_en/resolve/a0d5c6a264c0ef92d70d8661d8cc502d79627cd6/dict/user.dict.utf8`,sha256:`495bbf49270408a1234690e1e6a97328f30a482a7a72aa769e8a12e8714b0c62`}]},{id:`melo-english-lexicon`,pathScope:`model`,paths:[`lexicon.txt`],licenseIds:[`cmudict-0.6-1998`,`mit-melo`,`apache-2.0-sherpa`],status:`pending`,summary:`The English portion is generated by the sherpa Melo export from melo.text.english.eng_dict and refine_syllables, lowercasing words and adding language tone offsets plus kaldi/SF entries. The inspected Melo source reads cmudict.rep or a cached pickle. cmudict.rep contains its own Copyright 1998 Carnegie Mellon University unrestricted research/commercial permission and attribution notice, retained verbatim in cmudict-0.6-1998. This is NOT a substitution of a modern CMUdict BSD license. The retained notice hash covers the complete original comment header; the evidence hash covers the complete 3969309-byte source file. No package script or pickle was executed.`,pendingReasons:[`The precise historical dictionary/cache inputs and all intervening modifications used for this lexicon have not been pinned or reproduced. Trace cached-data equivalence and retain applicable original and modifier notices.`],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/export-onnx.py`,sha256:`c0be7727d59ad6ceaf39e909b4560b57e704091c69ac3fab6f2f2abfd931c916`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/melo/text/english.py`,sha256:`28527f574511bfc13fe1f2f6bbb5bfe4072c06e1c7e9b69598138aef81b9905b`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/melo/text/cmudict.rep`,sha256:`d127b5ce8b8e695732701e8efde04b9b0fa11991218b1fb9d21bd0c9264636aa`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/LICENSE`,sha256:`cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`}]},{id:`melo-chinese-lexicon`,pathScope:`model`,paths:[`lexicon.txt`],licenseIds:[`mit-pypinyin`,`mit-melo`,`apache-2.0-sherpa`],status:`pending`,summary:`The Chinese portion is generated by the sherpa Melo export from pypinyin character/phrase dictionaries, lazy_pinyin and the Melo pinyin-to-symbol map. Melo code is MIT, sherpa conversion code Apache-2.0, and pypinyin declares MIT. Those software declarations do not relicense external dictionary inputs. The same 6837671-byte mixed-language lexicon is used unchanged on every platform.`,pendingReasons:[`Pin historical pypinyin versions, character/phrase JSON data and Melo phoneme mapping, reproduce the output and trace the actual underlying source-data terms. No particular Zdic, CC-CEDICT or Unihan license is asserted without proof of the actual input chain.`],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/export-onnx.py`,sha256:`c0be7727d59ad6ceaf39e909b4560b57e704091c69ac3fab6f2f2abfd931c916`},{url:`https://raw.githubusercontent.com/mozillazg/python-pinyin/8595294b1a97845e30f11ecfdb3caa4e61ac3988/pypinyin/pinyin_dict.py`,sha256:`245c1f70509432b289cde1f938157cd5ff1372d1d083b577d5fab72b4dfcda08`},{url:`https://raw.githubusercontent.com/mozillazg/python-pinyin/8595294b1a97845e30f11ecfdb3caa4e61ac3988/pypinyin/phrases_dict.py`,sha256:`3f6f39bbca68d8d1676ea463cd4620b934b03160cc5042fb9d9007b8f3a80b9e`},{url:`https://raw.githubusercontent.com/mozillazg/python-pinyin/8595294b1a97845e30f11ecfdb3caa4e61ac3988/LICENSE.txt`,sha256:`1e6c90014b4912815c296ee64bb6f6280af47e6d4c5d80e86232dfc5defe764c`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`}]},{id:`melo-normalization-fsts`,pathScope:`model`,paths:[`date.fst`,`number.fst`,`phone.fst`],licenseIds:[`apache-2.0-sherpa`],status:`pending`,summary:`All three FSTs are byte-identical to the separately downloaded data/date.fst, data/number.fst and data/phone.fst at csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06 revision 57345c004e13ed640e408c4c29ab56187b18f065, the source repository named by the Melo packaging workflow. That source model card declares Apache-2.0; the full Apache text is retained from sherpa. Neither the OpenFst software license nor the Melo neural-weight MIT declaration independently grants rights to these FST data.`,pendingReasons:[`Exact editable generation rules, compiler/source revisions, underlying data provenance and applicable author/modifier notices remain unverified. No standalone FST LICENSE/NOTICE or complete reproducible source chain was found in the inspected source tree.`],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/.github/workflows/export-melo-tts-to-onnx.yaml`,sha256:`fc90fc412fd6f3c8a7d593743372a077dd63b2c8ce0780ed9c3a7e05cc8b659e`},{url:`https://hf-mirror.com/csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06/resolve/57345c004e13ed640e408c4c29ab56187b18f065/README.md`,sha256:`98b45ea81164d1e1a1dd82255207053b15cd6c69d922a1c5cf3387ce604d4b74`},{url:`https://hf-mirror.com/csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06/resolve/57345c004e13ed640e408c4c29ab56187b18f065/data/date.fst`,sha256:`eb8aa079ae3cb81d8f4404992f39d61a0cb990947512b5b8d1e54d1f6980e718`},{url:`https://hf-mirror.com/csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06/resolve/57345c004e13ed640e408c4c29ab56187b18f065/data/number.fst`,sha256:`743f402181fcfebf76cc2f0546b71fa26476e626fbe4e460fb7b4c3a7a8bd5bd`},{url:`https://hf-mirror.com/csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06/resolve/57345c004e13ed640e408c4c29ab56187b18f065/data/phone.fst`,sha256:`1ac2b6fa56b1442320c4de7db08353bab8963a2b57f365eebcdd3a2d3562f8d7`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/LICENSE`,sha256:`cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`}]},{id:`melo-package-notices`,pathScope:`model`,paths:[`LICENSE`,`README.md`],licenseIds:[`mit-melo`],status:`confirmed`,summary:`LICENSE is byte-identical to the original MyShell.ai MIT text (Copyright (c) 2024 MyShell.ai), including its exact final newline behavior. README explicitly identifies the single female Chinese+English speaker. The package-level MIT file is not a blanket grant for every bundled dictionary or FST. No upstream NOTICE was listed in the inspected conversion and weight repository trees; this is not proof that none ever existed.`,pendingReasons:[],evidence:[{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://hf-mirror.com/csukuangfj/vits-melo-tts-zh_en/resolve/a0d5c6a264c0ef92d70d8661d8cc502d79627cd6/README.md`,sha256:`ae6e44dead53dfdbd5b4a77106226f3118eb910222b46cb5533a3860773fc6c7`}]}],modifications:[]}]},no=to,ro=e=>to.models.some(t=>t.id===e);function io({modelId:e,modelName:t,returnFocus:n,onClose:r}){let{t:i}=l(),a=no.models.find(t=>t.id===e);if(!a)return null;let o=new Set(a.groups.flatMap(e=>e.licenseIds)),s=no.licenses.filter(e=>o.has(e.id));return(0,$.jsx)(Jn,{open:!0,onOpenChange:e=>{e||r()},children:(0,$.jsxs)(Gn,{className:`z-[130] max-h-[85dvh] min-w-0 grid-cols-1 overflow-y-auto rounded-lg sm:max-w-2xl`,overlayClassName:`z-[129]`,onEscapeKeyDown:e=>e.stopPropagation(),onCloseAutoFocus:e=>{e.preventDefault(),n.current?.isConnected&&n.current.focus()},children:[(0,$.jsxs)(qn,{children:[(0,$.jsx)(Kn,{children:i(`chat:speechModels.notices`)}),(0,$.jsxs)(Wn,{className:`break-words`,children:[t,` (`,a.revision,`)`]})]}),(0,$.jsx)(`p`,{className:`break-words text-sm text-muted-foreground`,children:no.scope}),(0,$.jsx)(`p`,{className:`break-words text-sm text-muted-foreground`,children:no.licenseIdsMeaning}),(0,$.jsx)(`div`,{className:`min-w-0 divide-y divide-stroke-soft`,children:a.groups.map(e=>(0,$.jsxs)(`details`,{className:`min-w-0 py-3`,children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer break-words text-sm font-medium`,children:[e.id,e.status===`pending`&&(0,$.jsx)(`span`,{className:`ml-2 text-xs font-normal text-warning-strong`,children:i(`chat:speechModels.provenancePending`)})]}),(0,$.jsxs)(`div`,{className:`mt-3 min-w-0 space-y-3 text-sm`,children:[(0,$.jsx)(`p`,{className:`break-words`,children:e.summary}),e.pendingReasons.map(e=>(0,$.jsx)(`p`,{className:`break-words text-muted-foreground`,children:e},e)),(0,$.jsx)(`pre`,{className:`whitespace-pre-wrap break-all text-xs`,children:JSON.stringify({pathScope:e.pathScope,paths:e.paths,licenseIds:e.licenseIds,evidence:e.evidence},null,2)})]})]},e.id))}),(0,$.jsxs)(`details`,{className:`min-w-0 border-t pt-3`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:i(`chat:speechModels.modifications`)}),(0,$.jsx)(`pre`,{className:`mt-3 whitespace-pre-wrap break-all text-xs`,children:JSON.stringify(a.modifications,null,2)})]}),s.map(e=>(0,$.jsxs)(`details`,{className:`min-w-0 border-t pt-3`,children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer break-words text-sm font-medium`,children:[e.name,` (`,e.id,`)`]}),(0,$.jsx)(`pre`,{className:`mt-3 whitespace-pre-wrap break-words text-xs`,children:e.text})]},e.id)),(0,$.jsx)(`div`,{className:`flex justify-end border-t pt-3`,children:(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{size:`icon-sm`,variant:`outline`,onClick:()=>{let e=new Blob([JSON.stringify({...no,models:[a],licenses:s},null,2)],{type:`application/json;charset=utf-8`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`${a.id}-notices.json`,n.click(),window.setTimeout(()=>URL.revokeObjectURL(t),0)},"aria-label":i(`chat:speechModels.downloadNotices`),children:(0,$.jsx)(ne,{})})}),(0,$.jsx)(Jt,{children:i(`chat:speechModels.downloadNotices`)})]})})]})})}var ao=e=>`${new Intl.NumberFormat(void 0,{maximumFractionDigits:1}).format(e/1048576)} MiB`;function oo({manager:e,onClose:t}){let{t:n}=l(),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=()=>{u.current?.abort(),u.current=null,i(!1)};(0,Q.useEffect)(()=>(e.open||(u.current?.abort(),u.current=null,i(!1),c(null)),()=>{u.current?.abort(),u.current=null}),[e.open]);let p={"not-installed":n(`chat:speechModels.notInstalled`),downloading:n(`chat:speechModels.downloading`),verifying:n(`chat:speechModels.verifying`),installed:n(`chat:speechModels.installed`),cancelled:n(`chat:speechModels.cancelled`),error:n(`chat:speechModels.failed`)},m=e.models.flatMap(e=>e.voices||[]),h=m.find(t=>t.id===e.selectedVoice),g=e.models.some(e=>e.kind===`tts`&&e.status===`installed`),_=e.models.filter(e=>e.status!==`installed`),v=_.some(e=>[`downloading`,`verifying`].includes(e.status)),y=()=>{c(null),f(),e.close(),t()},b=async()=>{if(u.current){f();return}if(!h||!g||_.length)return;let e=new AbortController;u.current=e,i(!0),o(``);try{await $a(h.language===`en`?n(`chat:speechModels.previewEnglish`):n(`chat:speechModels.previewChinese`),h.id,e.signal)}catch(t){e.signal.aborted||o(t instanceof Error?t.message:String(t))}finally{u.current===e&&(u.current=null,i(!1))}};return(0,$.jsxs)(Jn,{open:e.open,onOpenChange:e=>{e||y()},children:[(0,$.jsxs)(Gn,{className:`z-[110] max-h-[85dvh] overflow-y-auto sm:max-w-md`,overlayClassName:`z-[109]`,onEscapeKeyDown:e=>e.stopPropagation(),children:[(0,$.jsxs)(qn,{children:[(0,$.jsx)(Kn,{children:n(`chat:speechModels.title`)}),(0,$.jsx)(Wn,{className:`sr-only`,children:n(`chat:speechModels.title`)})]}),!e.catalog&&!e.error&&(0,$.jsx)(it,{className:`mx-auto my-4 size-5 animate-spin`,"aria-label":n(`chat:speechModels.loading`)}),(0,$.jsx)(`div`,{className:`min-w-0 divide-y divide-stroke-soft`,children:e.models.map(t=>{let r=[`downloading`,`verifying`].includes(t.status),i=t.totalBytes?Math.min(100,Math.floor(t.downloadedBytes/t.totalBytes*100)):0,a=t.license?.url.startsWith(`https://`)?t.license.url:void 0;return(0,$.jsxs)(`section`,{className:`min-w-0 space-y-2 py-3 first:pt-0`,"aria-label":t.name,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:t.kind===`asr`?n(`chat:speechModels.recognition`):n(`chat:speechModels.synthesis`)}),(0,$.jsx)(`div`,{className:`break-words font-medium`,children:t.name})]}),t.status===`installed`?(0,$.jsx)(U,{className:`size-5 shrink-0 text-success`,"aria-label":p.installed}):(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{size:`icon-sm`,variant:`outline`,disabled:e.loading,onClick:()=>{r?e.cancelDownload(t.id):e.download(t.id)},"aria-label":n(r?`chat:speechModels.cancelDownload`:`chat:speechModels.download`),children:r?(0,$.jsx)(gt,{}):(0,$.jsx)(ne,{})})}),(0,$.jsx)(Jt,{children:n(r?`chat:speechModels.cancelDownload`:`chat:speechModels.download`)})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[(0,$.jsx)(`span`,{children:p[t.status]}),(0,$.jsx)(`span`,{className:`tabular-nums`,children:r?`${ao(t.downloadedBytes)} / ${ao(t.totalBytes)}`:ao(t.totalBytes)})]}),r&&(0,$.jsx)(Bt,{value:i,"aria-label":t.name,"aria-valuenow":i,"aria-valuemin":0,"aria-valuemax":100}),t.error&&(0,$.jsx)(`p`,{role:`alert`,className:`break-words text-xs text-destructive`,children:t.error}),t.license&&(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center justify-between gap-2`,children:[(0,$.jsx)(`a`,{href:a,target:`_blank`,rel:`noreferrer`,className:`block break-words text-xs text-muted-foreground underline underline-offset-2`,children:t.license.name}),ro(t.id)&&(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{size:`icon-sm`,variant:`ghost`,"aria-label":n(`chat:speechModels.notices`),onClick:e=>{d.current=e.currentTarget,f(),c(t)},children:(0,$.jsx)(I,{})})}),(0,$.jsx)(Jt,{children:n(`chat:speechModels.notices`)})]})]})]},t.id)})}),m.length>0&&(0,$.jsx)(`div`,{className:`space-y-2 border-t pt-3`,children:(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`min-w-0 flex-1 text-sm`,children:n(`chat:speechModels.voice`)}),(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{size:`icon`,variant:`outline`,disabled:!g||_.length>0,onClick:()=>void b(),"aria-label":n(r?`chat:speechModels.stopPreview`:`chat:speechModels.preview`),children:r?(0,$.jsx)(gt,{}):(0,$.jsx)(lt,{})})}),(0,$.jsx)(Jt,{children:n(r?`chat:speechModels.stopPreview`:`chat:speechModels.preview`)})]})]})}),(e.error||a)&&(0,$.jsx)(`p`,{role:`alert`,className:`break-words text-sm text-destructive`,children:e.error||a}),(0,$.jsx)(`div`,{className:`flex justify-end border-t pt-3`,children:_.length?(0,$.jsxs)(Y,{disabled:e.loading||v,onClick:()=>void e.downloadAll(),children:[(0,$.jsx)(ne,{}),n(`chat:speechModels.downloadAll`)]}):(0,$.jsx)(Y,{disabled:!e.catalog,onClick:y,children:n(`chat:speechModels.done`)})})]}),e.open&&s&&(0,$.jsx)(io,{modelId:s.id,modelName:s.name,returnFocus:d,onClose:()=>c(null)})]})}var so=16e3,co=so*60;function lo(e,t){let n=window.__TAURI__?.core?.invoke??window.__TAURI_INTERNALS__?.invoke;return n?n(e,t):Promise.reject(Error(`移动端原生桥不可用。`))}async function uo(){if(!(typeof window>`u`||!window.__PISPER_MOBILE_APP__)&&(await lo(`mobile_request_microphone_permission`)).state!==`granted`)throw Error(`microphone_permission_denied`)}async function fo(e){let t=await e.text().catch(()=>``);try{return JSON.parse(t).error||`语音转写失败 (${e.status})`}catch{return t||`语音转写失败 (${e.status})`}}function po(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var mo=class{chatSessionId;chunks=[];pending=[];listeners=new Set;controller=null;sessionId=``;nativeRequestId=``;legacy=!1;flushTimer=0;sendChain=Promise.resolve();finished=!1;retainedSamples=0;terms=[];initializing=null;constructor(e=``){this.chatSessionId=e}start(){return this.initializing=this.initialize().catch(async e=>{throw await this.cancel(),e}),this.initializing}async initialize(){this.chunks=[],this.pending=[],this.finished=!1,this.retainedSamples=0;let e=new AbortController;this.controller=e,await w(),y(e.signal);let{loadSpeechHotwords:n,prepareSpeechSession:r}=await t(async()=>{let{loadSpeechHotwords:e,prepareSpeechSession:t}=await import(`./speech-session-DI3T3jpW.js`).then(e=>e.r);return{loadSpeechHotwords:e,prepareSpeechSession:t}},__vite__mapDeps([143,1,2,3,13,15,14,5,6,7,8,12,16])),{terms:i,hotwords:a}=await n(this.chatSessionId,e.signal);this.terms=i;let o=await r({kinds:[`asr`],hotwords:a},e.signal);if(y(o.signal),o.signal.addEventListener(`abort`,()=>{this.controller===e&&!e.signal.aborted&&this.cancel()},{once:!0}),window.__PISPER_MOBILE_APP__)return;let s=v(e.signal,3e4);try{let t=await fetch(`/api/speech/stream/start`,{method:`POST`,headers:{"X-Pisper-Chat-Session":this.chatSessionId},signal:s.signal});if(!t.ok){if(t.status===404){this.legacy=!0;return}throw Error(await fo(t))}let n=await t.json();if(!n.id)throw Error(`语音识别会话创建失败。`);e.signal.aborted&&(await fetch(`/api/speech/stream/cancel`,{method:`POST`,headers:{"X-Pisper-Speech-Session":n.id}}).catch(()=>{}),y(e.signal)),this.sessionId=n.id,this.pending.push(...this.chunks.splice(0)),this.retainedSamples=0,this.flushTimer=window.setInterval(()=>void this.flushPending(),1e3)}finally{s.dispose()}}acceptPcm(e){if(!e.length||this.finished)return!1;if(window.__PISPER_MOBILE_APP__||!this.sessionId){let t=co-this.retainedSamples;if(t<=0)return!0;let n=e.slice(0,t);return this.chunks.push(n),this.retainedSamples+=n.length,this.retainedSamples>=co}let t=e.slice();return this.sessionId&&!this.legacy?this.pending.push(t):this.chunks.push(t),!1}onPartial(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emitPartial(e){if(e)for(let t of this.listeners)t(e)}flushPending(){return this.sendChain=this.sendChain.then(async()=>{if(!this.sessionId||this.legacy||this.finished||!this.pending.length)return;let e=po(this.pending.splice(0));try{let t=await fetch(`/api/speech/stream/chunk`,{method:`POST`,headers:{"Content-Type":`application/octet-stream`,"X-Pisper-Sample-Rate":String(so),"X-Pisper-Speech-Session":this.sessionId},body:e.buffer,signal:this.controller?.signal});if(!t.ok)return;let n=await t.json();typeof n.text==`string`&&this.emitPartial(n.text.trim())}catch{}}),this.sendChain}async finishStreaming(){window.clearInterval(this.flushTimer),this.flushTimer=0,await this.flushPending(),this.finished=!0;let e=await fetch(`/api/speech/stream/finish`,{method:`POST`,headers:{"X-Pisper-Speech-Session":this.sessionId},signal:this.controller?.signal});if(!e.ok)throw Error(await fo(e));let t=await e.json(),n=typeof t.text==`string`?t.text.trim():``;if(!n)throw Error(`未识别到语音内容。`);return this.emitPartial(n),n}async finishOneShot(e){if(window.__PISPER_MOBILE_APP__){let t=new Uint8Array(e.buffer),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));let i=this.controller;if(!i)throw new DOMException(`Speech recognition cancelled.`,`AbortError`);y(i.signal);let a=crypto.randomUUID();this.nativeRequestId=a;let o=await lo(`mobile_transcribe_pcm`,{pcmBase64:btoa(n),hotwords:Br(this.terms),requestId:a});if(y(i.signal),this.controller!==i)throw new DOMException(`Speech recognition cancelled.`,`AbortError`);let s=Hr(typeof o.text==`string`?o.text.trim():``,this.terms);if(!s)throw Error(`未识别到语音内容。`);return this.emitPartial(s),s}let t=await fetch(`/api/speech/transcribe`,{method:`POST`,headers:{"Content-Type":`application/octet-stream`,"X-Pisper-Sample-Rate":String(so),"X-Pisper-Chat-Session":this.chatSessionId},body:e.buffer,signal:this.controller?.signal});if(!t.ok)throw Error(await fo(t));let n=await t.json(),r=typeof n.text==`string`?n.text.trim():``;if(!r)throw Error(`未识别到语音内容。`);return this.emitPartial(r),r}async finish(){if(await this.initializing,!this.controller)throw Error(`语音识别尚未启动。`);if(this.sessionId&&!this.legacy)return this.finishStreaming();this.finished=!0;let e=po(this.chunks);if(!e.length)throw Error(`没有采集到语音。`);return this.finishOneShot(e)}async cancel(){if(this.finished=!0,window.clearInterval(this.flushTimer),this.flushTimer=0,this.controller?.abort(),this.controller=null,this.chunks=[],this.pending=[],this.retainedSamples=0,this.nativeRequestId){let e=this.nativeRequestId;this.nativeRequestId=``,await lo(`mobile_cancel_speech`,{requestId:e}).catch(()=>{})}if(this.sessionId&&!this.legacy){let e=this.sessionId;this.sessionId=``,await fetch(`/api/speech/stream/cancel`,{method:`POST`,headers:{"X-Pisper-Speech-Session":e}}).catch(()=>{})}}async dispose(){await this.cancel(),this.listeners.clear()}};function ho({chatSessionId:e=``}={}){return new mo(e)}var go=`
|
|
511
|
+
`,sourceUrl:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/melo/text/cmudict.rep`,sha256:`08ee91f3c05c55160bdc599247ba53e5de8cc2597766fdb22b54a81cb24dd954`}],models:[{id:`x-asr-480ms-int8`,revision:`2026-06-05`,attribution:`X-ASR by Gilgamesh-J / GilgameshWind; trained using icefall and deployed with sherpa-onnx. The locked HF model card expressly covers model artifacts and declares Apache-2.0. The separately discovered GitHub license commit is not the locked HF revision. No root LICENSE or NOTICE was listed in the inspected HF tree; this is not proof that every historical distribution lacks NOTICE. Retain applicable upstream notices when found.`,archive:{url:`https://github.com/k2-fsa/sherpa-onnx/releases/download/asr-models/sherpa-onnx-x-asr-480ms-streaming-zipformer-transducer-zh-en-punct-int8-2026-06-05.tar.bz2`,sha256:`fa5f63d618e5a01526e275a358bb7772e403f84808a4769fba52cffd8160bf74`},groups:[{id:`xasr-weights`,pathScope:`model`,paths:[`encoder.int8.onnx`,`decoder.onnx`,`joiner.int8.onnx`],licenseIds:[`apache-2.0`],status:`pending`,summary:`Apache-2.0 is explicitly declared for X-ASR model artifacts. The sherpa export script describes icefall streaming ONNX export and INT8 quantization; installed file hashes match the catalog, but the 2026-06-05 archive-to-checkpoint/build identity is not established.`,pendingReasons:[`Exact checkpoint and source commits used to build the 2026-06-05 INT8 archive remain unverified; the export script downloads moving main URLs. Training-data rights are not fully audited.`],evidence:[{url:`https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/689ff18c584d29910da37b6fe904db0c1489c9d1/README.md`,sha256:`7acc6f439d3e39e46de4298ccf8a8f6a483fdc5f9f5d08e61422b63760ec37b1`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/v1.13.7/scripts/zipformer-transducer/x-asr/export-streaming.sh`,sha256:`63b018fe72a29e9a41c6d4e358085b5ad1614e021c0d9f3c05a2d11f1dff0d81`}]},{id:`xasr-tokens`,pathScope:`model`,paths:[`tokens.txt`],licenseIds:[`apache-2.0`],status:`pending`,summary:`X-ASR token resource, not the SentencePiece or sherpa software. The punctuation export block downloads X-ASR-zh-en/zipformer/data/lang_5000_with_punctuation/tokens.txt. Catalog content SHA256: b818a60878b9aae978cbb8ad594acbd403d76d1af2e31ef4197c84e2dbdba27c.`,pendingReasons:[`The historical source revision for the token file in the 2026-06-05 archive is not pinned by the export script.`],evidence:[{url:`https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/689ff18c584d29910da37b6fe904db0c1489c9d1/README.md`,sha256:`7acc6f439d3e39e46de4298ccf8a8f6a483fdc5f9f5d08e61422b63760ec37b1`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/v1.13.7/scripts/zipformer-transducer/x-asr/export-streaming.sh`,sha256:`63b018fe72a29e9a41c6d4e358085b5ad1614e021c0d9f3c05a2d11f1dff0d81`}]},{id:`xasr-bpe`,pathScope:`model`,paths:[`bpe.model`],licenseIds:[`apache-2.0`],status:`pending`,summary:`X-ASR BPE resource. The export script renames X-ASR-zh-en/zipformer/data/lang_5000_with_punctuation/bpe_punc.model to bpe.model. Its license classification comes from X-ASR, not from the software that reads the SentencePiece format.`,pendingReasons:[`The historical BPE source commit and exact archive build provenance remain unverified.`],evidence:[{url:`https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/689ff18c584d29910da37b6fe904db0c1489c9d1/README.md`,sha256:`7acc6f439d3e39e46de4298ccf8a8f6a483fdc5f9f5d08e61422b63760ec37b1`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/v1.13.7/scripts/zipformer-transducer/x-asr/export-streaming.sh`,sha256:`63b018fe72a29e9a41c6d4e358085b5ad1614e021c0d9f3c05a2d11f1dff0d81`}]},{id:`xasr-bpe-vocab`,pathScope:`shared`,paths:[`speech-resources/xasr-bpe.vocab`],licenseIds:[`apache-2.0`],status:`pending`,summary:`Modified by Pisper: extracted the ordered SentencePiece pieces and scores as UTF-8 piece<TAB>score<LF> lines. This local text derivative retains the source resource license classification; it is not newly licensed as Pisper-owned model data. Original and derived hashes and generator are bound by xasr-bpe-extraction below.`,pendingReasons:[`The source BPE historical provenance remains pending as described in xasr-bpe. A text extraction does not resolve upstream rights.`],evidence:[{url:`https://hf-mirror.com/GilgameshWind/X-ASR-zh-en/resolve/689ff18c584d29910da37b6fe904db0c1489c9d1/README.md`,sha256:`7acc6f439d3e39e46de4298ccf8a8f6a483fdc5f9f5d08e61422b63760ec37b1`}]}],modifications:[{id:`xasr-bpe-extraction`,groupIds:[`xasr-bpe-vocab`],modifiedBy:`Pisper`,summary:`Local BPE text extraction, not retraining. The generator identity records the inspected repository implementation, not a claim about a historical upstream build date.`,source:{path:`bpe.model`,bytes:119265,sha256:`f87a38025a5fdd1e4e9591f6a44bb81295097ce0b80df6f4ab9f44e52c64ca5f`},derived:{path:`speech-resources/xasr-bpe.vocab`,bytes:61562,sha256:`01381aa0c3065832cb8d7462d529e3079a99be56c955ce93b4cb9b78e8aa34e5`},generator:{path:`scripts/speech-bpe.mjs`,sha256:`a1c85731aa3e0be89f04acc79830db784a9d43edb8af9f4fb723bb45bd725786`,method:`sentencePieceModelToVocab decodes ordered protobuf ModelProto.pieces and emits each piece, a tab, its finite score, and a newline without changing the BPE model.`}}]},{id:`vits-melo-tts-zh_en`,revision:`a0d5c6a264c0ef92d70d8661d8cc502d79627cd6`,archive:{url:`https://github.com/k2-fsa/sherpa-onnx/releases/download/tts-models/vits-melo-tts-zh_en.tar.bz2`,bytes:167006755,sha256:`e58351ed7149f290a54534538badd4077cdbe6fddc964b24d0bee870415d1514`},attribution:`MeloTTS by MyShell.ai; sherpa-onnx ONNX conversion. The retained software license is Copyright (c) 2024 MyShell.ai, MIT. The neural-weight repository separately declares MIT; dictionary and FST resources have separate declarations and pending provenance. Pisper selects the original single female voice via public sid 0 and uses the same original FP32 ONNX, tokens, mixed-language lexicon, dictionary and normalization files on Desktop, Android and iOS. No retraining, quantization, graph/metadata patch or voice-subset derivative is made. The unused new_heteronym.fst and 133-byte model.int8.onnx Git LFS pointer in the transport archive are drained but not installed; retained model files are unchanged. These choices do not imply upstream/speaker endorsement, redistribution approval or completed native-platform acceptance.`,groups:[{id:`melo-weights`,pathScope:`model`,paths:[`model.onnx`],licenseIds:[`mit-melo`],status:`pending`,summary:`The myshell-ai/MeloTTS-Chinese model card at af5d207a364ea4208c6f589c89f57f88414bdd16 declares license: mit for the model repository; this is separate evidence from the MeloTTS software MIT license. The sherpa conversion package carries the exact MyShell.ai MIT text, and original ONNX metadata declares MIT license, melo-vits version 2, Chinese + English, n_speakers=1 and speaker_id=1. The conversion README explicitly describes a single female Chinese+English speaker. sherpa maps public sid 0 to the internal metadata speaker_id; Pisper does not change the graph, metadata or speaker embedding.`,pendingReasons:[`Exact historical checkpoint, training/conversion commits and reproducible archive build identity have not been established; the inspected conversion workflow uses moving upstream references. Training-data permissions, individual speaker consent and applicable personality/publicity rights are not fully audited. The discovered model card revision is evidence of a declaration, not proof of the historical conversion input.`],evidence:[{url:`https://hf-mirror.com/myshell-ai/MeloTTS-Chinese/resolve/af5d207a364ea4208c6f589c89f57f88414bdd16/README.md`,sha256:`40b5b860bacbb3947cbef838719e660d2fe4961eba5b484290b4bedc0253e208`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://hf-mirror.com/csukuangfj/vits-melo-tts-zh_en/resolve/a0d5c6a264c0ef92d70d8661d8cc502d79627cd6/README.md`,sha256:`ae6e44dead53dfdbd5b4a77106226f3118eb910222b46cb5533a3860773fc6c7`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/export-onnx.py`,sha256:`c0be7727d59ad6ceaf39e909b4560b57e704091c69ac3fab6f2f2abfd931c916`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/run.sh`,sha256:`e2afb98d9028eded2983f780468337fc019a8306db926f89e3bdeed18af867bb`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/sherpa-onnx/csrc/offline-tts-vits-model.cc`,sha256:`060907349036d63b60d035843defe7078b83c8099e0d4de323446c7db0d653d0`}]},{id:`melo-tokens`,pathScope:`model`,paths:[`tokens.txt`],licenseIds:[`mit-melo`,`apache-2.0-sherpa`],status:`declared`,summary:`The sherpa Melo export writes enumerated model.hps symbols to tokens.txt. The original 655-byte token file is retained unchanged. Melo software is MIT; sherpa conversion code is Apache-2.0. These code declarations do not independently establish all underlying training-data rights.`,pendingReasons:[],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/export-onnx.py`,sha256:`c0be7727d59ad6ceaf39e909b4560b57e704091c69ac3fab6f2f2abfd931c916`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/LICENSE`,sha256:`cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`}]},{id:`melo-cppjieba-dictionary`,pathScope:`model`,paths:[`dict/hmm_model.utf8`,`dict/idf.utf8`,`dict/jieba.dict.utf8`,`dict/pos_dict/char_state_tab.utf8`,`dict/pos_dict/prob_emit.utf8`,`dict/pos_dict/prob_start.utf8`,`dict/pos_dict/prob_trans.utf8`,`dict/README.md`,`dict/stop_words.utf8`],licenseIds:[`mit-cppjieba`],status:`confirmed`,summary:`Nine ordinary dictionary/README files are byte-identical to the separately HTTPS-downloaded CppJieba sherpa-onnx-2024-04-19 dict archive. The exact release source MIT license retains Copyright (c) 2013. This confirms the documented source-content match, not a whole-chain data-rights guarantee. The small Melo user.dict.utf8 is separately classified and is NOT the 829194-byte pypinyin-derived user dictionary from that source archive.`,pendingReasons:[],evidence:[{url:`https://ghfast.top/https://github.com/csukuangfj/cppjieba/releases/download/sherpa-onnx-2024-04-19/dict.tar.bz2`,sha256:`35c3877c9b9221a5b2d69bbf57d5dbf1ccbe5b7684c60eb42f93db6b2d494f26`},{url:`https://raw.githubusercontent.com/csukuangfj/cppjieba/f03dd931a00330c279c8590275850fd1f6749a18/LICENSE`,sha256:`ba898a14f729ba5e9965da34e3eecd5edd3795f2cc5d7c923b815ba79bb851b0`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/.github/workflows/export-melo-tts-to-onnx.yaml`,sha256:`fc90fc412fd6f3c8a7d593743372a077dd63b2c8ce0780ed9c3a7e05cc8b659e`}]},{id:`melo-user-dictionary`,pathScope:`model`,paths:[`dict/user.dict.utf8`],licenseIds:[`mit-cppjieba`,`mit-melo`],status:`pending`,summary:`Melo ships an unchanged 49-byte user dictionary containing four entries. It matches the locked Melo HF file but differs from the separately downloaded CppJieba release user dictionary. The package MIT text and CppJieba project MIT declaration are retained as source declarations, not proof that either automatically licenses every edit. This file is not attributed to the unrelated historical pypinyin-derived dictionary.`,pendingReasons:[`The exact historical source commit, modifier and license coverage for this 49-byte replacement have not been identified. Retain applicable modifier notices when established.`],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/.github/workflows/export-melo-tts-to-onnx.yaml`,sha256:`fc90fc412fd6f3c8a7d593743372a077dd63b2c8ce0780ed9c3a7e05cc8b659e`},{url:`https://raw.githubusercontent.com/csukuangfj/cppjieba/f03dd931a00330c279c8590275850fd1f6749a18/LICENSE`,sha256:`ba898a14f729ba5e9965da34e3eecd5edd3795f2cc5d7c923b815ba79bb851b0`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://huggingface.co/csukuangfj/vits-melo-tts-zh_en/resolve/a0d5c6a264c0ef92d70d8661d8cc502d79627cd6/dict/user.dict.utf8`,sha256:`495bbf49270408a1234690e1e6a97328f30a482a7a72aa769e8a12e8714b0c62`}]},{id:`melo-english-lexicon`,pathScope:`model`,paths:[`lexicon.txt`],licenseIds:[`cmudict-0.6-1998`,`mit-melo`,`apache-2.0-sherpa`],status:`pending`,summary:`The English portion is generated by the sherpa Melo export from melo.text.english.eng_dict and refine_syllables, lowercasing words and adding language tone offsets plus kaldi/SF entries. The inspected Melo source reads cmudict.rep or a cached pickle. cmudict.rep contains its own Copyright 1998 Carnegie Mellon University unrestricted research/commercial permission and attribution notice, retained verbatim in cmudict-0.6-1998. This is NOT a substitution of a modern CMUdict BSD license. The retained notice hash covers the complete original comment header; the evidence hash covers the complete 3969309-byte source file. No package script or pickle was executed.`,pendingReasons:[`The precise historical dictionary/cache inputs and all intervening modifications used for this lexicon have not been pinned or reproduced. Trace cached-data equivalence and retain applicable original and modifier notices.`],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/export-onnx.py`,sha256:`c0be7727d59ad6ceaf39e909b4560b57e704091c69ac3fab6f2f2abfd931c916`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/melo/text/english.py`,sha256:`28527f574511bfc13fe1f2f6bbb5bfe4072c06e1c7e9b69598138aef81b9905b`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/melo/text/cmudict.rep`,sha256:`d127b5ce8b8e695732701e8efde04b9b0fa11991218b1fb9d21bd0c9264636aa`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/LICENSE`,sha256:`cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`}]},{id:`melo-chinese-lexicon`,pathScope:`model`,paths:[`lexicon.txt`],licenseIds:[`mit-pypinyin`,`mit-melo`,`apache-2.0-sherpa`],status:`pending`,summary:`The Chinese portion is generated by the sherpa Melo export from pypinyin character/phrase dictionaries, lazy_pinyin and the Melo pinyin-to-symbol map. Melo code is MIT, sherpa conversion code Apache-2.0, and pypinyin declares MIT. Those software declarations do not relicense external dictionary inputs. The same 6837671-byte mixed-language lexicon is used unchanged on every platform.`,pendingReasons:[`Pin historical pypinyin versions, character/phrase JSON data and Melo phoneme mapping, reproduce the output and trace the actual underlying source-data terms. No particular Zdic, CC-CEDICT or Unihan license is asserted without proof of the actual input chain.`],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/scripts/melo-tts/export-onnx.py`,sha256:`c0be7727d59ad6ceaf39e909b4560b57e704091c69ac3fab6f2f2abfd931c916`},{url:`https://raw.githubusercontent.com/mozillazg/python-pinyin/8595294b1a97845e30f11ecfdb3caa4e61ac3988/pypinyin/pinyin_dict.py`,sha256:`245c1f70509432b289cde1f938157cd5ff1372d1d083b577d5fab72b4dfcda08`},{url:`https://raw.githubusercontent.com/mozillazg/python-pinyin/8595294b1a97845e30f11ecfdb3caa4e61ac3988/pypinyin/phrases_dict.py`,sha256:`3f6f39bbca68d8d1676ea463cd4620b934b03160cc5042fb9d9007b8f3a80b9e`},{url:`https://raw.githubusercontent.com/mozillazg/python-pinyin/8595294b1a97845e30f11ecfdb3caa4e61ac3988/LICENSE.txt`,sha256:`1e6c90014b4912815c296ee64bb6f6280af47e6d4c5d80e86232dfc5defe764c`},{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`}]},{id:`melo-normalization-fsts`,pathScope:`model`,paths:[`date.fst`,`number.fst`,`phone.fst`],licenseIds:[`apache-2.0-sherpa`],status:`pending`,summary:`All three FSTs are byte-identical to the separately downloaded data/date.fst, data/number.fst and data/phone.fst at csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06 revision 57345c004e13ed640e408c4c29ab56187b18f065, the source repository named by the Melo packaging workflow. That source model card declares Apache-2.0; the full Apache text is retained from sherpa. Neither the OpenFst software license nor the Melo neural-weight MIT declaration independently grants rights to these FST data.`,pendingReasons:[`Exact editable generation rules, compiler/source revisions, underlying data provenance and applicable author/modifier notices remain unverified. No standalone FST LICENSE/NOTICE or complete reproducible source chain was found in the inspected source tree.`],evidence:[{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/.github/workflows/export-melo-tts-to-onnx.yaml`,sha256:`fc90fc412fd6f3c8a7d593743372a077dd63b2c8ce0780ed9c3a7e05cc8b659e`},{url:`https://hf-mirror.com/csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06/resolve/57345c004e13ed640e408c4c29ab56187b18f065/README.md`,sha256:`98b45ea81164d1e1a1dd82255207053b15cd6c69d922a1c5cf3387ce604d4b74`},{url:`https://hf-mirror.com/csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06/resolve/57345c004e13ed640e408c4c29ab56187b18f065/data/date.fst`,sha256:`eb8aa079ae3cb81d8f4404992f39d61a0cb990947512b5b8d1e54d1f6980e718`},{url:`https://hf-mirror.com/csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06/resolve/57345c004e13ed640e408c4c29ab56187b18f065/data/number.fst`,sha256:`743f402181fcfebf76cc2f0546b71fa26476e626fbe4e460fb7b4c3a7a8bd5bd`},{url:`https://hf-mirror.com/csukuangfj/icefall-tts-aishell3-vits-low-2024-04-06/resolve/57345c004e13ed640e408c4c29ab56187b18f065/data/phone.fst`,sha256:`1ac2b6fa56b1442320c4de7db08353bab8963a2b57f365eebcdd3a2d3562f8d7`},{url:`https://raw.githubusercontent.com/k2-fsa/sherpa-onnx/917bed95c8e5c7c18aa4d69fea42e9ef8ef0a60e/LICENSE`,sha256:`cfc7749b96f63bd31c3c42b5c471bf756814053e847c10f3eb003417bc523d30`}]},{id:`melo-package-notices`,pathScope:`model`,paths:[`LICENSE`,`README.md`],licenseIds:[`mit-melo`],status:`confirmed`,summary:`LICENSE is byte-identical to the original MyShell.ai MIT text (Copyright (c) 2024 MyShell.ai), including its exact final newline behavior. README explicitly identifies the single female Chinese+English speaker. The package-level MIT file is not a blanket grant for every bundled dictionary or FST. No upstream NOTICE was listed in the inspected conversion and weight repository trees; this is not proof that none ever existed.`,pendingReasons:[],evidence:[{url:`https://raw.githubusercontent.com/myshell-ai/MeloTTS/209145371cff8fc3bd60d7be902ea69cbdb7965a/LICENSE`,sha256:`88a50e5a02bbc2a5c2f084dc19da751aa97b1690f5fda76cd8005c8634d1ca70`},{url:`https://hf-mirror.com/csukuangfj/vits-melo-tts-zh_en/resolve/a0d5c6a264c0ef92d70d8661d8cc502d79627cd6/README.md`,sha256:`ae6e44dead53dfdbd5b4a77106226f3118eb910222b46cb5533a3860773fc6c7`}]}],modifications:[]}]},no=to,ro=e=>to.models.some(t=>t.id===e);function io({modelId:e,modelName:t,returnFocus:n,onClose:r}){let{t:i}=l(),a=no.models.find(t=>t.id===e);if(!a)return null;let o=new Set(a.groups.flatMap(e=>e.licenseIds)),s=no.licenses.filter(e=>o.has(e.id));return(0,$.jsx)(Jn,{open:!0,onOpenChange:e=>{e||r()},children:(0,$.jsxs)(Gn,{className:`z-[130] max-h-[85dvh] min-w-0 grid-cols-1 overflow-y-auto rounded-lg sm:max-w-2xl`,overlayClassName:`z-[129]`,onEscapeKeyDown:e=>e.stopPropagation(),onCloseAutoFocus:e=>{e.preventDefault(),n.current?.isConnected&&n.current.focus()},children:[(0,$.jsxs)(qn,{children:[(0,$.jsx)(Kn,{children:i(`chat:speechModels.notices`)}),(0,$.jsxs)(Wn,{className:`break-words`,children:[t,` (`,a.revision,`)`]})]}),(0,$.jsx)(`p`,{className:`break-words text-sm text-muted-foreground`,children:no.scope}),(0,$.jsx)(`p`,{className:`break-words text-sm text-muted-foreground`,children:no.licenseIdsMeaning}),(0,$.jsx)(`div`,{className:`min-w-0 divide-y divide-stroke-soft`,children:a.groups.map(e=>(0,$.jsxs)(`details`,{className:`min-w-0 py-3`,children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer break-words text-sm font-medium`,children:[e.id,e.status===`pending`&&(0,$.jsx)(`span`,{className:`ml-2 text-xs font-normal text-warning-strong`,children:i(`chat:speechModels.provenancePending`)})]}),(0,$.jsxs)(`div`,{className:`mt-3 min-w-0 space-y-3 text-sm`,children:[(0,$.jsx)(`p`,{className:`break-words`,children:e.summary}),e.pendingReasons.map(e=>(0,$.jsx)(`p`,{className:`break-words text-muted-foreground`,children:e},e)),(0,$.jsx)(`pre`,{className:`whitespace-pre-wrap break-all text-xs`,children:JSON.stringify({pathScope:e.pathScope,paths:e.paths,licenseIds:e.licenseIds,evidence:e.evidence},null,2)})]})]},e.id))}),(0,$.jsxs)(`details`,{className:`min-w-0 border-t pt-3`,children:[(0,$.jsx)(`summary`,{className:`cursor-pointer text-sm font-medium`,children:i(`chat:speechModels.modifications`)}),(0,$.jsx)(`pre`,{className:`mt-3 whitespace-pre-wrap break-all text-xs`,children:JSON.stringify(a.modifications,null,2)})]}),s.map(e=>(0,$.jsxs)(`details`,{className:`min-w-0 border-t pt-3`,children:[(0,$.jsxs)(`summary`,{className:`cursor-pointer break-words text-sm font-medium`,children:[e.name,` (`,e.id,`)`]}),(0,$.jsx)(`pre`,{className:`mt-3 whitespace-pre-wrap break-words text-xs`,children:e.text})]},e.id)),(0,$.jsx)(`div`,{className:`flex justify-end border-t pt-3`,children:(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{size:`icon-sm`,variant:`outline`,onClick:()=>{let e=new Blob([JSON.stringify({...no,models:[a],licenses:s},null,2)],{type:`application/json;charset=utf-8`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`${a.id}-notices.json`,n.click(),window.setTimeout(()=>URL.revokeObjectURL(t),0)},"aria-label":i(`chat:speechModels.downloadNotices`),children:(0,$.jsx)(ne,{})})}),(0,$.jsx)(Jt,{children:i(`chat:speechModels.downloadNotices`)})]})})]})})}var ao=e=>`${new Intl.NumberFormat(void 0,{maximumFractionDigits:1}).format(e/1048576)} MiB`;function oo({manager:e,onClose:t}){let{t:n}=l(),[r,i]=(0,Q.useState)(!1),[a,o]=(0,Q.useState)(``),[s,c]=(0,Q.useState)(null),u=(0,Q.useRef)(null),d=(0,Q.useRef)(null),f=()=>{u.current?.abort(),u.current=null,i(!1)};(0,Q.useEffect)(()=>(e.open||(u.current?.abort(),u.current=null,i(!1),c(null)),()=>{u.current?.abort(),u.current=null}),[e.open]);let p={"not-installed":n(`chat:speechModels.notInstalled`),downloading:n(`chat:speechModels.downloading`),verifying:n(`chat:speechModels.verifying`),installed:n(`chat:speechModels.installed`),cancelled:n(`chat:speechModels.cancelled`),error:n(`chat:speechModels.failed`)},m=e.models.flatMap(e=>e.voices||[]),h=m.find(t=>t.id===e.selectedVoice),g=e.models.some(e=>e.kind===`tts`&&e.status===`installed`),_=e.models.filter(e=>e.status!==`installed`),v=_.some(e=>[`downloading`,`verifying`].includes(e.status)),y=()=>{c(null),f(),e.close(),t()},b=async()=>{if(u.current){f();return}if(!h||!g||_.length)return;let e=new AbortController;u.current=e,i(!0),o(``);try{await $a(h.language===`en`?n(`chat:speechModels.previewEnglish`):n(`chat:speechModels.previewChinese`),h.id,e.signal)}catch(t){e.signal.aborted||o(t instanceof Error?t.message:String(t))}finally{u.current===e&&(u.current=null,i(!1))}};return(0,$.jsxs)(Jn,{open:e.open,onOpenChange:e=>{e||y()},children:[(0,$.jsxs)(Gn,{className:`z-[110] max-h-[85dvh] overflow-y-auto sm:max-w-md`,overlayClassName:`z-[109]`,onEscapeKeyDown:e=>e.stopPropagation(),children:[(0,$.jsxs)(qn,{children:[(0,$.jsx)(Kn,{children:n(`chat:speechModels.title`)}),(0,$.jsx)(Wn,{className:`sr-only`,children:n(`chat:speechModels.title`)})]}),!e.catalog&&!e.error&&(0,$.jsx)(it,{className:`mx-auto my-4 size-5 animate-spin`,"aria-label":n(`chat:speechModels.loading`)}),(0,$.jsx)(`div`,{className:`min-w-0 divide-y divide-stroke-soft`,children:e.models.map(t=>{let r=[`downloading`,`verifying`].includes(t.status),i=t.totalBytes?Math.min(100,Math.floor(t.downloadedBytes/t.totalBytes*100)):0,a=t.license?.url.startsWith(`https://`)?t.license.url:void 0;return(0,$.jsxs)(`section`,{className:`min-w-0 space-y-2 py-3 first:pt-0`,"aria-label":t.name,children:[(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-3`,children:[(0,$.jsxs)(`div`,{className:`min-w-0 flex-1`,children:[(0,$.jsx)(`div`,{className:`text-xs text-muted-foreground`,children:t.kind===`asr`?n(`chat:speechModels.recognition`):n(`chat:speechModels.synthesis`)}),(0,$.jsx)(`div`,{className:`break-words font-medium`,children:t.name})]}),t.status===`installed`?(0,$.jsx)(U,{className:`size-5 shrink-0 text-success`,"aria-label":p.installed}):(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{size:`icon-sm`,variant:`outline`,disabled:e.loading,onClick:()=>{r?e.cancelDownload(t.id):e.download(t.id)},"aria-label":n(r?`chat:speechModels.cancelDownload`:`chat:speechModels.download`),children:r?(0,$.jsx)(gt,{}):(0,$.jsx)(ne,{})})}),(0,$.jsx)(Jt,{children:n(r?`chat:speechModels.cancelDownload`:`chat:speechModels.download`)})]})]}),(0,$.jsxs)(`div`,{className:`flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-xs text-muted-foreground`,children:[(0,$.jsx)(`span`,{children:p[t.status]}),(0,$.jsx)(`span`,{className:`tabular-nums`,children:r?`${ao(t.downloadedBytes)} / ${ao(t.totalBytes)}`:ao(t.totalBytes)})]}),r&&(0,$.jsx)(Bt,{value:i,"aria-label":t.name,"aria-valuenow":i,"aria-valuemin":0,"aria-valuemax":100}),t.error&&(0,$.jsx)(`p`,{role:`alert`,className:`break-words text-xs text-destructive`,children:t.error}),t.license&&(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center justify-between gap-2`,children:[(0,$.jsx)(`a`,{href:a,target:`_blank`,rel:`noreferrer`,className:`block break-words text-xs text-muted-foreground underline underline-offset-2`,children:t.license.name}),ro(t.id)&&(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{size:`icon-sm`,variant:`ghost`,"aria-label":n(`chat:speechModels.notices`),onClick:e=>{d.current=e.currentTarget,f(),c(t)},children:(0,$.jsx)(I,{})})}),(0,$.jsx)(Jt,{children:n(`chat:speechModels.notices`)})]})]})]},t.id)})}),m.length>0&&(0,$.jsx)(`div`,{className:`space-y-2 border-t pt-3`,children:(0,$.jsxs)(`div`,{className:`flex min-w-0 items-center gap-2`,children:[(0,$.jsx)(`span`,{className:`min-w-0 flex-1 text-sm`,children:n(`chat:speechModels.voice`)}),(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{size:`icon`,variant:`outline`,disabled:!g||_.length>0,onClick:()=>void b(),"aria-label":n(r?`chat:speechModels.stopPreview`:`chat:speechModels.preview`),children:r?(0,$.jsx)(gt,{}):(0,$.jsx)(lt,{})})}),(0,$.jsx)(Jt,{children:n(r?`chat:speechModels.stopPreview`:`chat:speechModels.preview`)})]})]})}),(e.error||a)&&(0,$.jsx)(`p`,{role:`alert`,className:`break-words text-sm text-destructive`,children:e.error||a}),(0,$.jsx)(`div`,{className:`flex justify-end border-t pt-3`,children:_.length?(0,$.jsxs)(Y,{disabled:e.loading||v,onClick:()=>void e.downloadAll(),children:[(0,$.jsx)(ne,{}),n(`chat:speechModels.downloadAll`)]}):(0,$.jsx)(Y,{disabled:!e.catalog,onClick:y,children:n(`chat:speechModels.done`)})})]}),e.open&&s&&(0,$.jsx)(io,{modelId:s.id,modelName:s.name,returnFocus:d,onClose:()=>c(null)})]})}var so=16e3,co=so*60;function lo(e,t){let n=window.__TAURI__?.core?.invoke??window.__TAURI_INTERNALS__?.invoke;return n?n(e,t):Promise.reject(Error(`移动端原生桥不可用。`))}async function uo(){if(!(typeof window>`u`||!window.__PISPER_MOBILE_APP__)&&(await lo(`mobile_request_microphone_permission`)).state!==`granted`)throw Error(`microphone_permission_denied`)}async function fo(e){let t=await e.text().catch(()=>``);try{return JSON.parse(t).error||`语音转写失败 (${e.status})`}catch{return t||`语音转写失败 (${e.status})`}}function po(e){let t=e.reduce((e,t)=>e+t.length,0),n=new Float32Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var mo=class{chatSessionId;chunks=[];pending=[];listeners=new Set;controller=null;sessionId=``;nativeRequestId=``;legacy=!1;flushTimer=0;sendChain=Promise.resolve();finished=!1;retainedSamples=0;terms=[];initializing=null;constructor(e=``){this.chatSessionId=e}start(){return this.initializing=this.initialize().catch(async e=>{throw await this.cancel(),e}),this.initializing}async initialize(){this.chunks=[],this.pending=[],this.finished=!1,this.retainedSamples=0;let e=new AbortController;this.controller=e,await w(),y(e.signal);let{loadSpeechHotwords:n,prepareSpeechSession:r}=await t(async()=>{let{loadSpeechHotwords:e,prepareSpeechSession:t}=await import(`./speech-session-DOQkdJHS.js`).then(e=>e.r);return{loadSpeechHotwords:e,prepareSpeechSession:t}},__vite__mapDeps([143,1,2,3,13,15,14,5,6,7,8,12,16])),{terms:i,hotwords:a}=await n(this.chatSessionId,e.signal);this.terms=i;let o=await r({kinds:[`asr`],hotwords:a},e.signal);if(y(o.signal),o.signal.addEventListener(`abort`,()=>{this.controller===e&&!e.signal.aborted&&this.cancel()},{once:!0}),window.__PISPER_MOBILE_APP__)return;let s=v(e.signal,3e4);try{let t=await fetch(`/api/speech/stream/start`,{method:`POST`,headers:{"X-Pisper-Chat-Session":this.chatSessionId},signal:s.signal});if(!t.ok){if(t.status===404){this.legacy=!0;return}throw Error(await fo(t))}let n=await t.json();if(!n.id)throw Error(`语音识别会话创建失败。`);e.signal.aborted&&(await fetch(`/api/speech/stream/cancel`,{method:`POST`,headers:{"X-Pisper-Speech-Session":n.id}}).catch(()=>{}),y(e.signal)),this.sessionId=n.id,this.pending.push(...this.chunks.splice(0)),this.retainedSamples=0,this.flushTimer=window.setInterval(()=>void this.flushPending(),1e3)}finally{s.dispose()}}acceptPcm(e){if(!e.length||this.finished)return!1;if(window.__PISPER_MOBILE_APP__||!this.sessionId){let t=co-this.retainedSamples;if(t<=0)return!0;let n=e.slice(0,t);return this.chunks.push(n),this.retainedSamples+=n.length,this.retainedSamples>=co}let t=e.slice();return this.sessionId&&!this.legacy?this.pending.push(t):this.chunks.push(t),!1}onPartial(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emitPartial(e){if(e)for(let t of this.listeners)t(e)}flushPending(){return this.sendChain=this.sendChain.then(async()=>{if(!this.sessionId||this.legacy||this.finished||!this.pending.length)return;let e=po(this.pending.splice(0));try{let t=await fetch(`/api/speech/stream/chunk`,{method:`POST`,headers:{"Content-Type":`application/octet-stream`,"X-Pisper-Sample-Rate":String(so),"X-Pisper-Speech-Session":this.sessionId},body:e.buffer,signal:this.controller?.signal});if(!t.ok)return;let n=await t.json();typeof n.text==`string`&&this.emitPartial(n.text.trim())}catch{}}),this.sendChain}async finishStreaming(){window.clearInterval(this.flushTimer),this.flushTimer=0,await this.flushPending(),this.finished=!0;let e=await fetch(`/api/speech/stream/finish`,{method:`POST`,headers:{"X-Pisper-Speech-Session":this.sessionId},signal:this.controller?.signal});if(!e.ok)throw Error(await fo(e));let t=await e.json(),n=typeof t.text==`string`?t.text.trim():``;if(!n)throw Error(`未识别到语音内容。`);return this.emitPartial(n),n}async finishOneShot(e){if(window.__PISPER_MOBILE_APP__){let t=new Uint8Array(e.buffer),n=``,r=32768;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,e+r));let i=this.controller;if(!i)throw new DOMException(`Speech recognition cancelled.`,`AbortError`);y(i.signal);let a=crypto.randomUUID();this.nativeRequestId=a;let o=await lo(`mobile_transcribe_pcm`,{pcmBase64:btoa(n),hotwords:Br(this.terms),requestId:a});if(y(i.signal),this.controller!==i)throw new DOMException(`Speech recognition cancelled.`,`AbortError`);let s=Hr(typeof o.text==`string`?o.text.trim():``,this.terms);if(!s)throw Error(`未识别到语音内容。`);return this.emitPartial(s),s}let t=await fetch(`/api/speech/transcribe`,{method:`POST`,headers:{"Content-Type":`application/octet-stream`,"X-Pisper-Sample-Rate":String(so),"X-Pisper-Chat-Session":this.chatSessionId},body:e.buffer,signal:this.controller?.signal});if(!t.ok)throw Error(await fo(t));let n=await t.json(),r=typeof n.text==`string`?n.text.trim():``;if(!r)throw Error(`未识别到语音内容。`);return this.emitPartial(r),r}async finish(){if(await this.initializing,!this.controller)throw Error(`语音识别尚未启动。`);if(this.sessionId&&!this.legacy)return this.finishStreaming();this.finished=!0;let e=po(this.chunks);if(!e.length)throw Error(`没有采集到语音。`);return this.finishOneShot(e)}async cancel(){if(this.finished=!0,window.clearInterval(this.flushTimer),this.flushTimer=0,this.controller?.abort(),this.controller=null,this.chunks=[],this.pending=[],this.retainedSamples=0,this.nativeRequestId){let e=this.nativeRequestId;this.nativeRequestId=``,await lo(`mobile_cancel_speech`,{requestId:e}).catch(()=>{})}if(this.sessionId&&!this.legacy){let e=this.sessionId;this.sessionId=``,await fetch(`/api/speech/stream/cancel`,{method:`POST`,headers:{"X-Pisper-Speech-Session":e}}).catch(()=>{})}}async dispose(){await this.cancel(),this.listeners.clear()}};function ho({chatSessionId:e=``}={}){return new mo(e)}var go=`
|
|
512
512
|
class PisperVoiceInputProcessor extends AudioWorkletProcessor {
|
|
513
513
|
constructor(options) {
|
|
514
514
|
super()
|
|
@@ -548,6 +548,6 @@ class PisperVoiceInputProcessor extends AudioWorkletProcessor {
|
|
|
548
548
|
}
|
|
549
549
|
}
|
|
550
550
|
registerProcessor('pisper-voice-input', PisperVoiceInputProcessor)
|
|
551
|
-
`;async function _o(e){let t=new Blob([go],{type:`application/javascript`}),n=URL.createObjectURL(t);try{await e.audioWorklet.addModule(n)}finally{URL.revokeObjectURL(n)}}async function vo(e,t){if(y(t),!navigator.mediaDevices?.getUserMedia)throw Error(`当前环境不支持麦克风采集。`);if(!window.AudioContext&&!window.webkitAudioContext)throw Error(`当前环境不支持音频处理。`);let n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1}),r=null,i=null,a=null,o=null,s=!1,c=null,l=()=>{if(s)return c??Promise.resolve();s=!0,t?.removeEventListener(`abort`,u);for(let e of n.getTracks())e.removeEventListener?.(`ended`,d),e.removeEventListener?.(`mute`,d),e.stop();return c=r?.close().catch(()=>{})??Promise.resolve(),i&&(i.port.onmessage=null,i.port.close()),a?.disconnect(),i?.disconnect(),o?.disconnect(),c},u=()=>{l()},d=()=>{s||(l(),window.dispatchEvent(new Event(`pisper:speech-interrupted`)))},f=()=>{if(y(t),s)throw new DOMException(`Microphone capture was interrupted.`,`AbortError`)};t?.addEventListener(`abort`,u,{once:!0});for(let e of n.getTracks()){if(s)break;e.addEventListener?.(`ended`,d),e.addEventListener?.(`mute`,d),e.readyState===`ended`&&d()}try{f(),r=new(window.AudioContext||window.webkitAudioContext)({latencyHint:`interactive`}),await _o(r),f(),a=r.createMediaStreamSource(n),i=new AudioWorkletNode(r,`pisper-voice-input`,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{targetSampleRate:so}}),o=r.createGain(),o.gain.value=0,i.port.onmessage=n=>{!s&&!t?.aborted&&e(new Float32Array(n.data))},a.connect(i),i.connect(o),o.connect(r.destination),await r.resume(),f()}catch(e){throw await l(),e}return{stop:l}}var yo=32,bo=50;function xo(e,t){if(e instanceof DOMException&&e.name===`NotAllowedError`)return`permission`;let n=typeof e==`string`?e:e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):``;return n.includes(`microphone_permission_denied`)?`permission`:n||t}function So({onInsert:e,onLiveText:t,sessionId:n,disabled:r=!1,shortcutEnabled:i=!1,variant:a=`button`,controlRef:o}){let{t:s}=l(),c=Ka([`asr`]),u=gn(e=>e.bindings.voiceInput),[d,f]=(0,Q.useState)(`idle`),[p,m]=(0,Q.useState)(``),h=(0,Q.useRef)(`idle`),g=e=>{h.current=e,f(e)},_=(0,Q.useRef)(null),v=(0,Q.useRef)(null),y=(0,Q.useRef)(null),b=(0,Q.useRef)(null),x=(0,Q.useRef)(0),S=(0,Q.useRef)(0),C=(0,Q.useRef)(()=>{}),w=(0,Q.useRef)(!1),T=(0,Q.useRef)(null),E=(0,Q.useRef)(null),D=(0,Q.useRef)(()=>{}),O=(0,Q.useRef)(0),k=(0,Q.useRef)(Ra()),A=(0,Q.useRef)(0),[j,M]=(0,Q.useState)([]),N=(0,Q.useRef)([]),P=(0,Q.useRef)(null),F=(0,Q.useRef)(e),I=(0,Q.useRef)(t);F.current=e,I.current=t;let L=()=>{window.clearTimeout(S.current),S.current=0},R=async()=>{L();let e=y.current;y.current=null,e?.abort(),b.current?.(),b.current=null,P.current?.dispose(),P.current=null;let t=v.current;v.current=null;let n=_.current;_.current=null,await Promise.allSettled([t?.stop(),n?.dispose()])},z=e=>{console.warn(`[voice-input]`,e),m(e),g(`error`),window.clearTimeout(O.current),O.current=window.setTimeout(()=>{h.current===`error`&&(m(``),g(`idle`))},4e3)},B=()=>{L(),w.current=!1,g(`idle`),m(``)},V=()=>{T.current=null,E.current=null,x.current+=1,R(),I.current?.(null),B()};D.current=V,(0,Q.useEffect)(()=>{let e=()=>{(E.current!==x.current||T.current===x.current)&&D.current()},t=()=>{document.visibilityState===`hidden`&&e()},n=()=>D.current();return window.addEventListener(`blur`,e),window.addEventListener(`pisper:speech-interrupted`,n),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`blur`,e),window.removeEventListener(`pisper:speech-interrupted`,n),document.removeEventListener(`visibilitychange`,t),window.clearTimeout(O.current),e()}},[n,i,r]),(0,Q.useEffect)(()=>{if(d!==`recording`){M([]),N.current=[];return}let e=()=>{let e=performance.now()/1e3,t=A.current,n=N.current,r=[];for(let i=0;i<yo;i+=1){let a=i/31*2-1,o=Math.cos(a*Math.PI/2)**1.3,s=.1+.06*Math.sin(e*2.2+i*.55)+.04*Math.sin(e*3.7+i*.21),c=.75+.5*Math.abs(Math.sin(e*9+i*1.7)),l=Math.min(1,Math.max(.05,s+t*o*c*1.15)),u=n[i]??l,d=l>u?.55:.28;r.push(u+(l-u)*d)}N.current=r,M(r)};e();let t=window.setInterval(e,bo);return()=>window.clearInterval(t)},[d]);let H=()=>!r&&(h.current===`idle`||h.current===`error`),U=async()=>{if(!H())return;let e=++x.current,t=new AbortController;y.current=t,w.current=!1,g(`requesting`),m(``),k.current.reset();let r=ho({chatSessionId:n});_.current=r,b.current=r.onPartial(e=>{_.current===r&&I.current?.(e)});let i=null,a=async t=>{if(i?.dispose(),i=null,e!==x.current)return;if(t instanceof DOMException&&t.name===`AbortError`){let e=++x.current;if(await R(),e!==x.current)return;B();return}let n=++x.current;if(await R(),n!==x.current)return;let r=xo(t,s(`chat:voiceInput.failed`));z(r===`permission`?s(`chat:voiceInput.permissionDenied`):r)};try{window.__PISPER_MOBILE_APP__&&(E.current=e);try{await uo()}finally{E.current===e&&(E.current=null)}if(e!==x.current)return;if(window.__PISPER_MOBILE_APP__&&document.visibilityState===`hidden`){V();return}if(await c.ensureReady(t.signal),e!==x.current)return;if(r.start().then(()=>{},()=>a(Error(s(`chat:voiceInput.failed`)))),i=await Wa(),e!==x.current){i.dispose();return}P.current=i;let n=i,o=await vo(t=>{if(e!==x.current)return;A.current=k.current.push(La(t));let i=n.acceptPcm(t);(r.acceptPcm(t)||i)&&C.current()},t.signal);if(e!==x.current){await o.stop();return}v.current=o,g(`recording`),window.__PISPER_MOBILE_APP__&&(S.current=window.setTimeout(()=>C.current(),6e4))}catch(e){await a(e)}},W=async()=>{if(h.current!==`recording`||w.current)return;T.current=null,w.current=!0,L();let e=++x.current;g(`transcribing`);let t=y.current;y.current=null,t?.abort();let n=v.current;v.current=null;let r=P.current;P.current=null;let i=_.current;try{if(await n?.stop(),e!==x.current)return;if(r&&!r.hasSpeech){if(r.dispose(),I.current?.(null),await R(),e!==x.current)return;B();return}r?.dispose();let t=await i?.finish();if(e!==x.current)return;if(!t)throw Error(s(`chat:voiceInput.empty`));if(F.current(t),await R(),e!==x.current)return;B()}catch(t){if(e!==x.current||(await R(),e!==x.current))return;I.current?.(null);let n=xo(t,s(`chat:voiceInput.failed`));z(n===`permission`?s(`chat:voiceInput.permissionDenied`):n),w.current=!1}};C.current=()=>void W(),Ia({enabled:i&&!r,binding:u,onStart:()=>H()?(U(),T.current=x.current,!0):!1,onRelease:()=>{T.current===x.current&&(v.current?W():V())},onCancel:()=>{T.current===x.current&&V()}});let ee=d===`recording`?s(`chat:voiceInput.stop`):d===`requesting`?s(`chat:voiceInput.close`):d===`error`?p:s(`chat:voiceInput.open`),te=u&&d!==`error`?`${ee} (${xn(u)})`:ee,ne=d===`recording`?()=>void W():d===`requesting`?()=>V():()=>void U(),re=(0,Q.useRef)(ne);re.current=ne;let ie=!r&&d!==`transcribing`;(0,Q.useEffect)(()=>{if(o)return o.current=ie?()=>re.current():null,()=>{o.current=null}},[o,ie]);let ae=a===`menu`&&d===`idle`;return(0,$.jsxs)(`div`,{className:`relative flex flex-none items-center`,"data-voice-input":d,children:[d===`recording`&&(0,zi.createPortal)((0,$.jsx)(`div`,{"aria-hidden":`true`,className:`voice-capsule-pop pointer-events-none fixed bottom-4 left-1/2 z-[80] flex h-10 -translate-x-1/2 items-center gap-[3px] rounded-full bg-ink px-4 shadow-float`,children:j.map((e,t)=>(0,$.jsx)(`span`,{className:`w-[3px] rounded-full bg-on-ink`,style:{height:`${(3+e*19).toFixed(1)}px`,opacity:.55+e*.45,transition:`height 70ms linear`}},t))}),document.body),d===`error`&&(0,zi.createPortal)((0,$.jsxs)(`button`,{type:`button`,className:`voice-capsule-pop fixed bottom-4 left-1/2 z-[80] flex h-9 max-w-[min(480px,calc(100vw-32px))] -translate-x-1/2 cursor-pointer items-center gap-2 rounded-full border border-danger-border bg-solid px-4 text-xs text-danger shadow-float max-[650px]:h-11`,onClick:()=>{window.clearTimeout(O.current),m(``),g(`idle`)},children:[(0,$.jsx)(ri,{size:13,className:`flex-none`}),(0,$.jsx)(`span`,{className:`truncate`,children:p})]}),document.body),(0,$.jsxs)(`button`,{type:`button`,hidden:ae,className:`relative grid size-8 min-w-8 cursor-pointer place-items-center rounded-sm border transition-colors disabled:cursor-not-allowed disabled:opacity-45 max-[650px]:size-9 max-[650px]:min-w-9 min-[651px]:pointer-coarse:size-11 min-[651px]:pointer-coarse:min-w-11 ${me} ${d===`recording`?`border-danger bg-danger-soft text-danger`:d===`transcribing`||d===`requesting`?`border-transparent bg-star-soft text-accent-fg`:d===`error`?`border-transparent bg-danger-soft text-danger`:`border-transparent text-content-muted hover:bg-surface-hover hover:text-content`}`,title:te,"aria-label":s(d===`recording`?`chat:voiceInput.stop`:`chat:voiceInput.open`),"aria-pressed":d===`recording`,disabled:r||d===`transcribing`,onClick:ne,children:[d===`recording`&&(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-0 animate-ping rounded-sm bg-danger opacity-25`}),d===`recording`?(0,$.jsx)(ri,{size:17,className:G}):d===`transcribing`||d===`requesting`?(0,$.jsx)(it,{className:`animate-spin ${G}`,size:16}):d===`error`?(0,$.jsx)(ri,{size:17,className:G}):(0,$.jsx)(ii,{size:17,className:G})]}),(0,$.jsx)(oo,{manager:c,onClose:()=>{}})]})}var Co={idle:{amp:.14,freq:1.7,speed:.22,spike:0,rot:.22,dim:.8,behavior:`calm`},requesting:{amp:.08,freq:1.6,speed:.3,spike:0,rot:.4,dim:.5,behavior:`calm`},listening:{amp:.15,freq:2,speed:.55,spike:.55,rot:.4,dim:1,behavior:`reactive`},transcribing:{amp:.08,freq:1.8,speed:1,spike:0,rot:1.5,dim:.95,behavior:`converge`},thinking:{amp:.2,freq:2.3,speed:.8,spike:0,rot:.85,dim:1,behavior:`swirl`},speaking:{amp:.13,freq:1.9,speed:.5,spike:.1,rot:.35,dim:1,behavior:`beat`},error:{amp:.12,freq:2.2,speed:1.2,spike:0,rot:.1,dim:.9,behavior:`jitter`}},wo=64,To=96,Eo=2.6,Do=Math.PI*2,Oo={dark:{base:[223,233,255],cyan:[89,230,255],magenta:[255,95,210],haloInner:[70,110,170],haloMid:[50,80,140],haloAlpha:.1,composite:`lighter`,alphaBase:.1,alphaFront:.68},light:{base:[34,44,76],cyan:[6,132,180],magenta:[176,48,150],haloInner:[110,140,210],haloMid:[130,160,220],haloAlpha:.16,composite:`source-over`,alphaBase:.18,alphaFront:.85}};function ko(e,t,n){let r=Math.sin(e*127.1+t*311.7+n*74.7)*43758.5453123;return r-Math.floor(r)}function Ao(e){return e*e*(3-2*e)}function jo(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=Ao(e-r),s=Ao(t-i),c=Ao(n-a),l=0;for(let e=0;e<=1;e+=1)for(let t=0;t<=1;t+=1)for(let n=0;n<=1;n+=1)l+=(e?o:1-o)*(t?s:1-s)*(n?c:1-c)*ko(r+e,i+t,a+n);return l}function Mo(e){return 1+2.70158*(e-1)**3+1.70158*(e-1)**2}function No(e){let t=e*.9%1;return Math.exp(-(((t-.12)*9)**2))+.45*Math.exp(-(((t-.34)*9)**2))}function Po({stage:e,level:t,size:n=380,dark:r=!0}){let i=(0,Q.useRef)(null),a=(0,Q.useRef)(e),o=(0,Q.useRef)(t),s=(0,Q.useRef)(r);return a.current=e,o.current=t,s.current=r,(0,Q.useEffect)(()=>{let e=i.current;if(!e)return;let t=e.getContext(`2d`);if(!t)return;let r=Math.min(window.devicePixelRatio||1,2);e.width=n*r,e.height=n*r,t.scale(r,r);let c=new Float32Array(wo),l=new Float32Array(wo);for(let e=0;e<wo;e+=1){let t=-Math.PI/2+(e+.5)/wo*Math.PI;c[e]=Math.sin(t),l[e]=Math.cos(t)}let u=new Float32Array(To),d=new Float32Array(To);for(let e=0;e<To;e+=1){let t=e/To*Do;u[e]=Math.cos(t),d[e]=Math.sin(t)}let f=n/2,p=n*.31,m=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,h=0,g=performance.now(),_=g,v=0,y=0,b={...Co[a.current]},x=0,S=0,C=0,w=e=>{let r=Math.min((e-g)/1e3,.05);g=e;let i=Co[a.current],T=Math.min(1,r*5);b={...i,amp:b.amp+(i.amp-b.amp)*T,freq:b.freq+(i.freq-b.freq)*T,speed:b.speed+(i.speed-b.speed)*T,spike:b.spike+(i.spike-b.spike)*T,rot:b.rot+(i.rot-b.rot)*T,dim:b.dim+(i.dim-b.dim)*T};let E=m?.35:1;v+=r*E,y+=b.rot*r*E,x+=(o.current-x)*Math.min(1,r*14);let D=Math.max(0,x-S-.02);S=x,C=Math.min(.6,C*.02**r+D*2.4);let O=x;b.behavior===`beat`?O=Math.max(.08,.4+.28*Math.abs(Math.sin(v*5.2))*Math.sin(v*1.6)+.12*Math.sin(v*9.1)):b.behavior===`converge`?O=.18:b.behavior===`jitter`?O=.3+.2*Math.sin(v*17):b.behavior!==`reactive`&&(O=.1+.05*Math.sin(v*1.3));let k=Mo(Math.min(1,Math.max(0,(e-_)/900))),A=b.behavior===`beat`?O:No(v)*.5+O*.5,j=k*(1+A*.04+C*.1);b.behavior===`converge`&&(j*=.9+.1*Math.sin(v*4.2)),t.clearRect(0,0,n,n);let M=Oo[s.current?`dark`:`light`],N=t.createRadialGradient(f,f,0,f,f,p*1.7);N.addColorStop(0,`rgba(${M.haloInner[0]},${M.haloInner[1]},${M.haloInner[2]},${(M.haloAlpha*b.dim).toFixed(3)})`),N.addColorStop(.6,`rgba(${M.haloMid[0]},${M.haloMid[1]},${M.haloMid[2]},${(M.haloAlpha*.5*b.dim).toFixed(3)})`),N.addColorStop(1,`rgba(0,0,0,0)`),t.fillStyle=N,t.fillRect(0,0,n,n);let P=Math.sin(y),F=Math.cos(y),I=.38,L=Math.sin(I),R=Math.cos(I),z=v*b.speed,B=b.freq,V=b.amp*j,H=b.spike*(O+C),U=p*j,W=Math.floor(v*15),ee=b.dim*(.72+.5*A)+C*.3;t.globalCompositeOperation=M.composite;for(let e=0;e<wo;e+=1){let n=c[e],r=l[e];for(let i=0;i<To;i+=1){let a=r*u[i],o=n,s=r*d[i],c=jo(a*B+z,o*B+z*.7,s*B)-.5,l=1+c*2*V;b.behavior===`reactive`?l+=Math.max(c,0)**2*1.7*H:b.behavior===`swirl`?l+=.03*Math.sin(9*a+v*4.6):b.behavior===`jitter`&&(l+=.02*(ko(e*To+i,W,3)-.5));let p=a*l,m=o*l,h=s*l,g=p*F-h*P,_=p*P+h*F,y=m*R-_*L,x=m*L+_*R,S=Eo/(Eo-x),C=f+g*S*U,w=f+y*S*U,T=(x+1)/2,E=jo(a*1.25+31,o*1.25+z*.12,s*1.25-17),D=M.base;E>.62?D=M.magenta:E<.38&&(D=M.cyan);let O=(M.alphaBase+M.alphaFront*T*T)*ee;if(O<.015)continue;let k=(1+1.4*T+H*.4)*(.55+.45*S);t.fillStyle=`rgba(${D[0]},${D[1]},${D[2]},${O.toFixed(3)})`,t.fillRect(C,w,k,k)}}t.globalCompositeOperation=`source-over`,h=requestAnimationFrame(w)};return h=requestAnimationFrame(w),()=>cancelAnimationFrame(h)},[n]),(0,$.jsx)(`canvas`,{ref:i,className:`pointer-events-none block`,style:{width:n,height:n},"aria-hidden":`true`})}var Fo=new Map;function Io(e,t){let n=Fo.get(e)??new Set;return n.add(t),Fo.set(e,n),()=>{n.delete(t),n.size||Fo.delete(e)}}function Lo(e){for(let t of Fo.get(e.sessionId)??[])t(e)}function Ro(e,t){let n=t.messages.length-1;for(;n>=0&&t.messages[n].role!==`user`;)--n;let r=t.messages.slice(n+1).filter(e=>e.role===`agent`||e.role===`assistant`),i=r.find(e=>e.streaming)??r.at(-1);Lo({sessionId:e,messageId:i?.id??``,prompt:t.messages[n]?.text,startedAt:t.startedAt??void 0,source:`snapshot`,users:t.messages.filter(e=>e.role===`user`),text:i?.text??``,status:t.error||i?.error?`failed`:t.streaming?i?`streaming`:`started`:`completed`,error:t.error||i?.error})}function zo(e){let t=``,n=0,r=!1,i,a,o=()=>{a?.(),a=void 0},s=()=>{i=b(e),o()};return e.addEventListener(`abort`,s,{once:!0}),e.aborted&&s(),{get text(){return t},update(e){if(!(r||i)){if(e.length>32e3)throw Error(`Speech text exceeds the supported limit.`);if(!e.startsWith(t))throw Error(`The streamed speech response was rewritten.`);t=e,o()}},finish(e){r&&e===void 0||(r=!0,e!==void 0&&(i=e),o())},async*[Symbol.asyncIterator](){try{for(;;){if(y(e),i)throw i;if(n<t.length){let e=t.slice(n);n=t.length,yield e}else if(r)return;else await new Promise(e=>{a=e})}}finally{e.removeEventListener(`abort`,s),r=!0,o()}}}}function Bo(e){let{t}=l(),n=(0,Q.useRef)({...e,t});n.current={...e,t};let[r,i]=(0,Q.useState)(`idle`),[a,o]=(0,Q.useState)(0),[s,c]=(0,Q.useState)(``),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(0),v=(0,Q.useRef)(`idle`),b=(0,Q.useRef)(0),x=(0,Q.useRef)(null),S=(0,Q.useRef)(Promise.resolve()),C=(0,Q.useRef)(!1),w=(0,Q.useRef)(null),T=(0,Q.useRef)(!1),E=(0,Q.useRef)(!1),D=(0,Q.useRef)(!1),O=(0,Q.useRef)({start:async()=>{},commit:async()=>{},stop:()=>{}}),k=(0,Q.useCallback)(e=>{v.current=e,i(e)},[]),A=e=>T.current&&n.current.open&&e.sessionId===n.current.sessionId&&x.current===e&&b.current===e.generation&&!e.controller.signal.aborted,j=()=>!!(n.current.streaming||n.current.messages.some(e=>e.streaming));function M(){let e=w.current;w.current=null,e?.controller.abort()}function N(){if(w.current)return w.current.preparing;let e=new AbortController,t=n.current.sessionId,r=(async()=>{C.current||=(await n.current.ensureReady?.(e.signal),y(e.signal),!0);let{hotwords:r}=await qr(t,e.signal);await Wr({kinds:[`asr`,`tts`],hotwords:r},e.signal),y(e.signal)})().catch(t=>{throw w.current?.controller===e&&(w.current=null),e.abort(),t});return w.current={controller:e,preparing:r},r}function P(e){window.clearTimeout(e.limitTimer),e.limitTimer=void 0,e.microphone.abort(),e.endpoint?.dispose(),e.endpoint=void 0;let t=e.capture;return e.capture=void 0,t&&(e.captureStopping=t.stop()),e.captureStopping??Promise.resolve()}function F(e){if(e.cleanup)return e.cleanup;e.controller.abort(),e.unsubscribe?.(),e.unsubscribe=void 0,e.responseSubscription?.(),e.responseSubscription=void 0,e.checkOwnership=void 0;let t=P(e),n=e.recognizer;return e.recognizer=void 0,e.cleanup=Promise.allSettled([t,e.capturePending,e.recognizerDisposing,e.playback,n?.dispose()]).then(()=>{}),e.cleanup}function I(){b.current+=1;let e=x.current;if(x.current=null,!e)return;let t=Promise.resolve(),r=n.current.messages.filter(t=>t.role===`user`&&!e.baseline?.has(t.id)),i=n.current.sessionId===e.sessionId&&(r.length>1||r.length===1&&r[0].text?.trim()!==e.prompt);if(e.ownsRun&&!i){e.ownsRun=!1;try{t=Promise.resolve(e.abortRun?.()).catch(()=>{})}catch{}}S.current=Promise.allSettled([S.current,F(e),t]).then(()=>{})}function L(){D.current=!1,I(),k(`idle`),c(``),o(0),d(e=>e.filter(e=>!e.pending))}function R(e,t){if(!A(e))return;let r=t instanceof Error?t.message:typeof t==`string`?t:t&&typeof t==`object`&&`message`in t?t.message:void 0,i=typeof r==`string`&&r.trim()?r:n.current.t(`chat:voiceMode.failed`),a=t instanceof DOMException&&t.name===`NotAllowedError`||i.includes(`microphone_permission_denied`)?n.current.t(`chat:voiceInput.permissionDenied`):i;L(),p(a),k(`error`),n.current.notifyError?.(a)}function z(e){return new Promise(t=>{let n=e.controller.signal,r=()=>{window.clearTimeout(i),n.removeEventListener(`abort`,r),t()},i=window.setTimeout(r,50);n.addEventListener(`abort`,r,{once:!0}),n.aborted&&r()})}async function B(e,t,r){let i=e.controller.signal,a=zo(i),o,s,c,l=!1,u=!1,f=!1,p=!1,m=!1,h=1/0,g=n=>{let r=n.filter(e=>e.role===`user`&&!t.has(e.id));return r.length>1||r.length===1&&r[0].text?.trim()!==e.prompt};e.checkOwnership=()=>{A(e)&&g(n.current.messages)&&(e.ownsRun=!1,R(e,Error(n.current.t(`chat:voiceMode.failed`))))};let _=e=>{a.update(e),d(t=>t.map(t=>t.id===r?{...t,text:e,pending:!e.trim()}:t))};e.responseSubscription=Io(e.sessionId,r=>{if(!(!A(e)||r.source!==`snapshot`&&t.has(r.messageId)))try{let t=r.source===`snapshot`,i=!!(c&&r.startedAt===c);if(r.users&&g(r.users)||r.prompt!==void 0&&r.prompt.trim()!==e.prompt||s&&r.runId&&s!==r.runId||c&&r.startedAt&&c!==r.startedAt||t&&!i&&!(p&&!r.startedAt&&r.status===`completed`)||!t&&o&&o!==r.messageId)throw e.ownsRun=!1,Error(n.current.t(`chat:voiceMode.failed`));if(p&&t)return;if(s||=r.runId,c||=r.startedAt,r.messageId&&(o=r.messageId),r.status===`recovering`){l=!0;return}if(t&&(l=!0,u=r.status===`streaming`||r.status===`started`),r.status===`started`)return;if(f=!0,r.status===`failed`)throw e.ownsRun=!1,Error(r.error||n.current.t(`chat:voiceMode.failed`));_(r.text),r.status===`completed`&&(p=!0,e.ownsRun=!1,a.finish())}catch(t){a.finish(t),R(e,t)}});let v=Promise.resolve().then(()=>(y(i),n.current.sendPrompt(e.prompt,[],!1,!1,null))).catch(t=>{throw e.ownsRun=!1,a.finish(t),t}).finally(()=>{!f&&!s&&!c&&(e.ownsRun=!1),m=!0,h=Date.now()+15e3}),b=async()=>{for(;A(e);){if(await z(e),!A(e))return;let r=n.current.messages.filter(e=>!t.has(e.id)),i=r.filter(e=>e.role===`user`);if(i.length>1||i.length===1&&i[0].text?.trim()!==e.prompt)throw Error(n.current.t(`chat:voiceMode.failed`));let s=r.filter(e=>e.role===`assistant`||e.role===`agent`),c=s.find(e=>e.error);if(c)throw Error(String(c.error));if(p&&m&&!j())return;let d=s.at(-1);if(!l&&d?.text&&(!f||m&&!j())){if(o&&o!==d.id)throw Error(n.current.t(`chat:voiceMode.failed`));o=d.id,_(d.text)}if(!l&&m&&!j()&&d?.text?.trim()){e.ownsRun=!1,a.finish();return}if(m&&(j()||u)&&(h=Date.now()+15e3),Date.now()>=h)throw Error(n.current.t(`chat:voiceMode.emptyReply`))}};try{e.playback=Promise.resolve().then(()=>n.current.speakText(a,i,()=>{A(e)&&k(`speaking`)})),await Promise.all([v,b(),e.playback])}catch(e){throw a.finish(e),e}finally{e.responseSubscription?.(),e.responseSubscription=void 0,e.checkOwnership=void 0,a.finish()}}async function V(){let e=x.current;if(!e||!A(e)||e.committed||v.current!==`listening`)return;e.committed=!0;let t=e.endpoint?.hasSpeech;k(`transcribing`),o(0);try{if(await P(e),!A(e))return;if(!t){L();return}let r=(await e.recognizer?.finish())?.trim();if(!A(e))return;e.unsubscribe?.(),e.unsubscribe=void 0;let i=e.recognizer;if(e.recognizer=void 0,e.recognizerDisposing=i?.dispose(),await e.recognizerDisposing,!A(e))return;if(c(``),!r)throw Error(n.current.t(`chat:voiceMode.emptyReply`));if(j()){L();return}let a=new Set(n.current.messages.map(e=>e.id));e.baseline=a,e.prompt=r;let o=`voice-agent-${e.generation}`;if(d(t=>[...t.slice(-4),{id:`voice-user-${e.generation}`,role:`user`,text:r},{id:o,role:`agent`,text:``,pending:!0}]),k(`thinking`),e.abortRun=n.current.onAbort,e.ownsRun=!0,await B(e,a,o),!A(e))return;D.current&&!E.current?(k(`idle`),await O.current.start()):L()}catch(t){R(e,t)}}async function H(){if(!T.current||!n.current.open||E.current||document.hidden||![`idle`,`error`,`speaking`].includes(v.current))return;I();let e={generation:++b.current,sessionId:n.current.sessionId,controller:new AbortController,microphone:new AbortController,permissionPending:!1,committed:!1,commitRequested:!1,ownsRun:!1};x.current=e,D.current=!0,p(``),c(``),o(0),k(`requesting`);let t=Ra(),r=0;try{if(await S.current,!A(e)||(await N(),!A(e)))return;if(j()){L();return}e.permissionPending=!0;try{await uo()}finally{e.permissionPending=!1}if(!A(e))return;if(document.hidden||j()){L();return}let n=await Wa();if(!A(e)){n.dispose();return}e.endpoint=n;let i=ho({chatSessionId:e.sessionId});if(e.recognizer=i,e.unsubscribe=i.onPartial(t=>{A(e)&&c(t)}),await i.start(),!A(e)||(e.capturePending=vo(a=>{if(!(!A(e)||e.committed||e.microphone.signal.aborted))try{let s=t.push(La(a)),c=performance.now();c-r>=66&&(r=c,o(s));let l=i.acceptPcm(a),u=n.acceptPcm(a);(l||u)&&(e.commitRequested=!0,v.current===`listening`?O.current.commit():e.microphone.abort())}catch(t){R(e,t)}},e.microphone.signal).then(async t=>(!A(e)||e.microphone.signal.aborted?await t.stop():e.capture=t,t)),await e.capturePending,!A(e)))return;if(k(`listening`),e.commitRequested){await O.current.commit();return}e.limitTimer=window.setTimeout(()=>void O.current.commit(),6e4)}catch(t){A(e)&&e.commitRequested&&e.microphone.signal.aborted?(k(`listening`),await O.current.commit()):R(e,t)}}O.current={start:H,commit:V,stop:L};let U=(0,Q.useCallback)(()=>O.current.commit(),[]),W=(0,Q.useCallback)(()=>{O.current.stop();let e=b.current;S.current.then(()=>{b.current===e&&T.current&&O.current.start()})},[]),ee=(0,Q.useCallback)(()=>{v.current===`listening`?O.current.commit():v.current===`thinking`||v.current===`speaking`?W():(v.current===`idle`||v.current===`error`)&&(E.current=!1,h(!1),O.current.start())},[W]),te=(0,Q.useCallback)(()=>{let e=!E.current;E.current=e,h(e),e?O.current.stop():O.current.start()},[]),ne=(0,Q.useCallback)(()=>{M(),O.current.stop(),p(``),_(0)},[]);return(0,Q.useEffect)(()=>{if(!e.open)return;T.current=!0,C.current=!1,E.current=!1,h(!1),d([]),_(0),k(`idle`),O.current.start();let t=()=>{x.current?.permissionPending&&window.__PISPER_MOBILE_APP__||(M(),O.current.stop())},n=()=>{document.hidden&&t()},r=()=>{M(),O.current.stop()};return window.addEventListener(`blur`,t),window.addEventListener(`pisper:speech-interrupted`,r),document.addEventListener(`visibilitychange`,n),()=>{T.current=!1,M(),O.current.stop(),window.removeEventListener(`blur`,t),window.removeEventListener(`pisper:speech-interrupted`,r),document.removeEventListener(`visibilitychange`,n)}},[e.open,e.sessionId,k]),(0,Q.useEffect)(()=>{x.current?.checkOwnership?.()},[e.messages,e.streaming]),(0,Q.useEffect)(()=>{if(![`listening`,`transcribing`,`thinking`,`speaking`].includes(r))return;let e=window.setInterval(()=>_(e=>e+1),1e3);return()=>window.clearInterval(e)},[r]),{stage:r,level:a,partial:s,turns:u,error:f,muted:m,elapsed:g,toggleMain:ee,toggleMute:te,hangUp:ne,commitListening:U,interrupt:W}}function Vo(e){return{idle:e(`chat:voiceMode.idle`),requesting:e(`chat:voiceMode.requesting`),listening:e(`chat:voiceMode.listening`),transcribing:e(`chat:voiceMode.transcribing`),thinking:e(`chat:voiceMode.thinking`),speaking:e(`chat:voiceMode.speaking`),error:e(`chat:voiceMode.failed`)}}function Ho(e){let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`}function Uo(){let[e,t]=(0,Q.useState)(()=>document.documentElement.dataset.theme!==`light`);return(0,Q.useEffect)(()=>{let e=document.documentElement,n=()=>t(e.dataset.theme!==`light`);n();let r=new MutationObserver(n);return r.observe(e,{attributes:!0,attributeFilter:[`data-theme`]}),()=>r.disconnect()},[]),e}function Wo(e){let[t,n]=(0,Q.useState)(()=>typeof window>`u`?380:Math.max(48,Math.min(window.innerWidth*.52,window.innerHeight-304,460)));return(0,Q.useEffect)(()=>{if(!e)return;let t=()=>n(Math.max(48,Math.min(window.innerWidth*.52,window.innerHeight-304,460)));return t(),window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[e]),Math.floor(t)}function Go({open:e,sessionId:t,messages:n,streaming:r,sendPrompt:i,onAbort:a,onClose:o}){let{t:s}=l(),c=Uo(),u=Ka([`asr`,`tts`]),d=Bo({open:e,sessionId:t,messages:n,streaming:r,sendPrompt:i,onAbort:a,ensureReady:u.ensureReady,speakText:(e,t,n)=>$a(e,u.selectedVoice,t,n)}),{stage:f,level:p,partial:m,turns:h,error:g,elapsed:_}=d,v=Wo(e),y=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!e)return;let t=document.activeElement;return y.current?.focus({preventScroll:!0}),()=>{t instanceof HTMLElement&&t.isConnected&&t.focus({preventScroll:!0})}},[e]);let b=()=>{try{d.hangUp()}finally{u.close(),o()}},x=f===`listening`||f===`transcribing`||f===`thinking`||f===`speaking`||f===`requesting`;if((0,Q.useEffect)(()=>{if(!e)return;let t=e=>{if(!(u.open||e.defaultPrevented||e.isComposing)){if(e.key===`Escape`){e.preventDefault(),b();return}if(e.key===`Tab`){let t=[...y.current?.querySelectorAll(`button:not(:disabled)`)||[]],n=t[0],r=t[t.length-1];e.shiftKey&&(document.activeElement===n||document.activeElement===y.current)?(e.preventDefault(),r?.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n?.focus())}e.target instanceof Element&&e.target.closest(`input, textarea, select, button, [contenteditable="true"]`)||e.key===` `&&!e.repeat&&(e.preventDefault(),x?d.hangUp():d.toggleMain())}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,o,x,u.open]),!e)return null;let S=Vo(s),C=h[h.length-1],w=f===`listening`&&m?m:C?`${C.role,``}${za(C.text,120)}`:``,T=f===`error`?g||s(`chat:voiceMode.failed`):S[f];return(0,zi.createPortal)((0,$.jsxs)(`div`,{className:`fixed inset-0 z-[90] grid grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_100px_108px] overflow-hidden bg-chrome pt-[env(safe-area-inset-top)] pr-[env(safe-area-inset-right)] pb-[env(safe-area-inset-bottom)] pl-[env(safe-area-inset-left)] text-content select-none`,ref:y,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":s(`chat:voiceMode.title`),children:[(0,$.jsxs)(`header`,{className:`pointer-events-none absolute left-[calc(env(safe-area-inset-left)_+_28px)] top-[calc(env(safe-area-inset-top)_+_24px)] flex items-center gap-3`,children:[(0,$.jsx)(`span`,{className:`inline-block size-2 rounded-full ${x?`animate-pulse bg-star`:`bg-content-faint`}`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`text-[13px] font-semibold tracking-[0.3em] text-content`,children:`PISPER`})]}),(0,$.jsxs)(`div`,{className:`absolute top-[calc(env(safe-area-inset-top)_+_16px)] right-[calc(env(safe-area-inset-right)_+_16px)] z-10 flex items-center gap-1`,children:[(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{variant:`ghost`,size:`icon-sm`,"aria-label":s(`chat:speechModels.title`),onClick:()=>{d.hangUp(),u.show()},children:(0,$.jsx)(Zr,{})})}),(0,$.jsx)(Jt,{children:s(`chat:speechModels.title`)})]}),(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{variant:`ghost`,size:`icon-sm`,className:`size-11 flex-none`,"aria-label":s(`chat:speechModels.close`),onClick:b,children:(0,$.jsx)(Dt,{})})}),(0,$.jsx)(Jt,{children:s(`chat:speechModels.close`)})]})]}),(0,$.jsx)(oo,{manager:u,onClose:()=>d.hangUp()}),(0,$.jsx)(`div`,{className:`flex min-h-0 items-center justify-center pt-16 pb-6`,children:(0,$.jsx)(Po,{stage:f,level:p,size:v,dark:c})}),(0,$.jsxs)(`div`,{className:`flex min-h-0 min-w-0 flex-col items-center justify-center gap-2 px-6 text-center`,children:[(0,$.jsx)(`div`,{className:`max-w-full text-xs font-medium tracking-normal ${f===`error`?`max-h-full overflow-y-auto break-words text-danger`:`line-clamp-2 text-content-muted`}`,role:`status`,"aria-live":`polite`,children:T}),(0,$.jsx)(`p`,{className:`m-0 line-clamp-2 min-h-[22px] max-w-[640px] text-[15px] leading-[1.6] text-content`,children:w})]}),(0,$.jsx)(`div`,{className:`relative flex justify-center pt-3 sm:items-center sm:pt-0`,children:(0,$.jsx)(`button`,{type:`button`,className:`h-11 cursor-pointer rounded-full border px-8 text-sm font-medium transition-colors ${x?`border-control bg-key text-content shadow-key hover:bg-surface-hover`:`border-transparent bg-star text-on-accent shadow-primary hover:bg-star-hover`}`,onClick:()=>x?d.hangUp():d.toggleMain(),children:s(x?`chat:voiceMode.endConversation`:`chat:voiceMode.startConversation`)})}),(0,$.jsxs)(`div`,{className:`pointer-events-none absolute bottom-[calc(env(safe-area-inset-bottom)_+_12px)] right-[calc(env(safe-area-inset-right)_+_20px)] flex items-center gap-2.5 sm:bottom-[calc(env(safe-area-inset-bottom)_+_36px)] sm:right-[calc(env(safe-area-inset-right)_+_28px)]`,children:[(0,$.jsx)(`span`,{className:`hidden size-9 place-items-center rounded-full border border-key-border bg-key text-xs text-accent-fg shadow-key sm:grid`,"aria-hidden":`true`,children:x?`●`:`○`}),(0,$.jsx)(`span`,{className:`font-mono text-[13px] tracking-[0.08em] text-content-muted tabular-nums`,children:Ho(_)})]}),(0,$.jsx)(`div`,{className:`absolute bottom-[env(safe-area-inset-bottom)] left-[calc(env(safe-area-inset-left)_+_20px)] sm:bottom-[calc(env(safe-area-inset-bottom)_+_36px)] sm:left-[calc(env(safe-area-inset-left)_+_28px)]`,children:(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{variant:`ghost`,size:`icon`,className:`size-11 flex-none`,disabled:!x&&!d.muted,"aria-label":f===`speaking`||f===`thinking`?s(`chat:voiceMode.interrupt`):d.muted?s(`chat:voiceMode.unmute`):s(`chat:voiceMode.mute`),onClick:()=>f===`speaking`||f===`thinking`?d.interrupt():d.toggleMute(),children:f===`speaking`||f===`thinking`?(0,$.jsx)(gt,{}):d.muted?(0,$.jsx)(ri,{}):(0,$.jsx)(ii,{})})}),(0,$.jsx)(Jt,{children:f===`speaking`||f===`thinking`?s(`chat:voiceMode.interrupt`):d.muted?s(`chat:voiceMode.unmute`):s(`chat:voiceMode.mute`)})]})})]}),document.body)}var Ko=[`plan`,`goal`,`team`];function qo(e){return Ko.includes(e)?e:`plan`}function Jo({sessionId:e,runMode:t,goalsAvailable:n,teamAvailable:r,workflowsAvailable:i,goal:a,streaming:o,compaction:s,value:c,selection:l,clearDraft:u,captureSubmission:d,promptRef:f,onCompact:p,onGoalPause:m,onSend:h,onQueue:g,onAbort:_,requestTranscriptBottom:v}){let[y,b]=(0,Q.useState)(()=>qo(t)),x=(0,Q.useRef)(t);x.current=t;let[S,C]=(0,Q.useState)(null),[w,T]=(0,Q.useState)(null),E=(0,Q.useRef)(null),[D,O]=(0,Q.useState)(!1),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(``),F=(0,Q.useRef)(null),I=(0,Q.useRef)(e);I.current=e;let[L,R]=(0,Q.useState)(!1),[z,B]=(0,Q.useState)(null),V=(0,Q.useRef)(z);return V.current=z,(0,Q.useEffect)(()=>{b(qo(x.current)),E.current=null,C(null),T(null),F.current=null,A(!1),M(!1),P(``),O(!1),R(!1),B(null)},[e]),(0,Q.useEffect)(()=>{b(qo(t))},[e,t]),(0,Q.useEffect)(()=>{n||b(`plan`),!r&&y===`team`&&b(`goal`),!i&&z?.kind===`workflow`&&B(null)},[y,n,z?.kind,r,i]),(0,Q.useEffect)(()=>{a?.status===`active`&&b(a.mode===`team`&&r?`team`:`goal`)},[a?.id,a?.mode,a?.status,r]),(0,Q.useEffect)(()=>{if(!a?.id){C(null);return}let e=a.mode===`team`?a.teamTokenBudget:a.tokenBudget,t=e==null?null:Number(e),n=t!==null&&Number.isFinite(t)&&t>0?t:null;a.mode===`team`?T(n):C(n)},[a?.id,a?.mode,a?.teamTokenBudget,a?.tokenBudget]),{composerExecutionMode:y,setComposerExecutionMode:b,goalTokenBudget:S,setGoalTokenBudget:C,teamTokenBudget:w,setTeamTokenBudget:T,queueing:D,submitting:k,stopping:j,submitError:N,stop:async()=>{if(j||!_)return!1;let t=e;M(!0);try{return await _(),!0}catch(e){return I.current===t&&P(e instanceof Error?e.message:String(e)),!1}finally{I.current===t&&M(!1)}},compactingManually:L,invocation:z,setInvocation:B,requestGoalPause:()=>{if(E.current)return E.current;let e=Promise.resolve().then(()=>m?.());return E.current=e,e.catch(()=>{}),e},compactContext:async()=>{if(!(!p||o||L||s?.active)){R(!0);try{await p()}finally{R(!1)}}},submit:async(t,n=`steer`)=>{if(t.preventDefault(),F.current||j||l.preparingAttachments?.length||!c.trim()&&!l.attachments.length&&!z||o&&(!c.trim()&&!l.attachments.length||!g))return;let r={},i=e;F.current=r;let s=()=>I.current===i&&F.current===r,p=d?.(),_=!1,x=()=>{_||(_=!0,p?p.accept():u(),s()&&(A(!1),O(!1),b(`plan`),V.current===z&&B(null),v(),f.current&&(f.current.style.height=`auto`),F.current=null))};P(``),o?O(!0):A(!0);try{if(o){await g?.(c,l.attachments,n,x)&&x();return}let e=E.current;if(e?(await e,E.current=null):a?.status===`active`&&(y===`plan`||y!==a.mode)&&await m?.(),!s())return;let t=await h(c,l.attachments,y===`goal`||y===`team`,y===`team`,y===`team`?w:y===`goal`?S:null,z,x);!_&&t!==!1&&x()}catch(e){s()&&(E.current=null,P(e instanceof Error?e.message:String(e)))}finally{s()&&(F.current=null,A(!1),O(!1))}}}}var Yo=[`[role="dialog"]`,`[role="alertdialog"]`,`[role="menu"]`,`[role="listbox"]`,`.anchored-popup-menu`,`.voice-input-popup`,`.git-diff-dialog-backdrop`,`[data-slot='popover-content']`,`[data-slot='dropdown-menu-content']`,`[data-slot='select-content']`,`[data-slot='sheet-content']`].join(`, `);function Xo(){return[...document.querySelectorAll(Yo)].some(e=>e.dataset.state!==`closed`&&e.getAttribute(`aria-hidden`)!==`true`&&e.getClientRects().length>0)}var Zo=(0,Q.memo)(function({session:e,draft:t,emptyState:n,shortcutEnabled:r=!1,messages:i,transcriptLoadState:a=`ready`,messageStart:o,hasNewer:s,hasOlder:c,loadingOlder:u,olderError:d,model:f,thinkingLevel:p,availableThinkingLevels:m,thinkingStatus:h,thinkingMessage:g,executionMode:_,goal:v,team:y,currentActivity:b,activityFeed:x,tools:S,thinkingText:C,queuedInputs:w,workspace:T,withdrawingInputIds:E,compaction:D,contextUsage:M,sessionUsage:N,sessionTreeRevision:P,sessionTreePulse:F,cwd:I,availableModels:L,pendingRuntimeSelection:z,switchingModel:B,switchingThinking:V,switchingCwd:H,switchingPermission:U,streaming:W,runStartedAt:te,lastActivityAt:ne,runFinishedAt:re,runStopped:ae,runNotice:se,approvals:de,questions:pe,error:me,pendingAsset:q,notify:ge,onOpenModelSettings:Ce,onAssetConsumed:Te,onLoadOlder:De,onLoadLatest:Oe,onModelChange:ke,onThinkingLevelChange:je,onExecutionModeChange:Me,onRunModeChange:Ne,onCompact:Pe,onCompactionThresholdChange:Le,onGoalPause:Re,onGoalBudgetChange:ze,onApproval:Be,onAnswerQuestion:Ve,onWorkspace:He,onRename:Ue,onBranchFromHere:We,onCreateChildSession:qe,onRetryLastTurn:et,onTreeNavigated:nt,onSend:rt,onQueue:it,onWithdrawQueuedInput:at,onSendQueuedInputNow:ot,onDeliverSessionMessages:ct,onDismissSessionMessages:lt,onAbort:dt}){let ft=(0,Q.useContext)(Ee),pt=(0,Q.useContext)(Bi),mt=(0,Q.useContext)(Ye),ht=!!mt?.phone,{t:J}=l(),gt=gn(e=>e.bindings),_t=j(),vt=A(),St=_t||vt,Ct=k(e=>e.capabilities),wt=O(Ct,`goals`),Tt=O(Ct,`multiAgent`),Et=O(Ct,`workflows`),Dt=O(Ct,`visualGeneration`),Ot=O(Ct,`inputInterrupt`),kt=Ot?`interrupt`:`steer`,{value:It,updateValue:Lt,selection:Rt,clearDraft:zt,restoreDraft:Bt,captureSubmission:Vt}=xe(t?fe:e.id),[Ht,Ut]=(0,Q.useState)(!1),[Wt,Gt]=(0,Q.useState)(!1),[Kt,qt]=(0,Q.useState)(!1),Jt=(0,Q.useRef)(null),[Yt,Zt]=(0,Q.useState)(!1),[Y,Qt]=(0,Q.useState)(!1),[$t,en]=(0,Q.useState)(``),[tn,nn]=(0,Q.useState)(!1),[rn,on]=(0,Q.useState)(0),sn=Rt.addAttachments,cn=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{cn.current&&oa(cn.current)},[It]);let un=(0,Q.useRef)(null),dn=(0,Q.useRef)(`steer`),fn=gt.steerMessage,pn=()=>{dn.current=kt,cn.current?.form?.requestSubmit()},mn=bn(`sendMessage`),_n=bn(`voiceInput`),Sn=(0,Q.useRef)(null),Cn=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!r)return;let e=e=>{!hn(e)&&yn(e,gt.focusComposer)&&(e.preventDefault(),cn.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,gt.focusComposer]);let wn=!!t;(0,Q.useEffect)(()=>{if(!wn)return;let e=()=>{let e=cn.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.scrollTop=e.scrollHeight,an())};return(an()||!St)&&e(),window.addEventListener(ln,e),()=>window.removeEventListener(ln,e)},[wn,St]);let Tn=(0,Q.useRef)(!1),Dn=a!==`ready`||i.length>0,On=W?St?J(`board:composer.placeholderRunningTouch`):fn?J(`board:composer.placeholderRunning`,{queue:mn,steer:xn(fn)}):J(`board:composer.placeholderRunningQueueOnly`,{queue:mn}):J(t?`chat:newTask.placeholder`:`board:composer.placeholder`),kn=()=>on(e=>e+1),An=e=>{Lt(e)},{composerExecutionMode:jn,setComposerExecutionMode:Mn,goalTokenBudget:Nn,setGoalTokenBudget:Pn,teamTokenBudget:Fn,setTeamTokenBudget:In,queueing:Ln,submitting:Rn,stopping:zn,submitError:Bn,stop:Vn,compactingManually:Hn,invocation:Un,setInvocation:Wn,requestGoalPause:Gn,compactContext:Kn,submit:qn}=Jo({sessionId:e.id,runMode:e.runMode,goalsAvailable:wt,teamAvailable:Tt,workflowsAvailable:Et,goal:v,streaming:W,compaction:D,value:It,selection:Rt,clearDraft:zt,captureSubmission:Vt,promptRef:cn,onCompact:Pe,onGoalPause:Re,onSend:rt,onQueue:it,onAbort:dt,requestTranscriptBottom:kn}),Jn=async()=>{let e=w||[];if(await Vn())for(let t of e)Bt({text:String(t.text||``),attachments:Array.isArray(t.attachments)?t.attachments:[]})},Yn=(0,Q.useRef)(Jn);Yn.current=Jn,(0,Q.useEffect)(()=>{if(!mt||!r||!W)return;let e=new WeakSet,t=t=>{t.key===`Escape`&&Xo()&&e.add(t)},n=t=>{if(t.key!==`Escape`||!t.isTrusted||t.defaultPrevented||t.isComposing||t.keyCode===229||e.has(t))return;let n=t.target,r=un.current,i=n===document.body||n===document.documentElement||n instanceof Element&&!!n.closest(`[data-session-conversation]`)&&!n.closest(`.terminal-panel, .xterm`);!r||!i||vn(n)&&n!==cn.current||(t.preventDefault(),Yn.current())};return window.addEventListener(`keydown`,t,!0),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`keydown`,t,!0),window.removeEventListener(`keydown`,n)}},[mt,r,W]);let Xn=e=>{v?.status===`active`&&(e===`plan`||e!==v.mode)&&Gn().catch(()=>{}),Mn(e),Ne(e)},Zn=(0,Q.useContext)(Ze),Qn=mt?.onNewTask||mt?.phone?.onNewTask,er=t?t.cwd:null,tr=(0,Q.useCallback)(()=>er===null?X.getSessionCommands(e.id):X.getWorkspaceCommands(er),[er,e.id]),nr=_a(e.id),rr=[...Qn&&!t?[{invocation:`/new`,description:J(`chat:commands.builtin.new`),run:Qn}]:[],...ie({t:J,models:L,model:z?.model||f,onModel:e=>ke(e),thinkingLevels:z?.model?[]:m||[],thinkingLevel:z?.thinkingLevel||p||``,thinkingLabel:e=>_e(J,e),onThinking:e=>je(e),executionModes:[`approval-required`,`workspace-write`,`full-access`],executionMode:_,executionLabel:e=>J(e===`full-access`?`chat:focusSession.fullAccess`:e===`workspace-write`?`chat:focusSession.workspaceWrite`:`chat:focusSession.approvalRequired`),onExecutionMode:e=>Me(e),runModes:W?[]:[`plan`,...wt?[`goal`]:[],...wt&&Tt?[`team`]:[]],runMode:jn,runModeLabel:e=>J(e===`team`?`chat:focusSession.teamMode`:e===`goal`?`chat:focusSession.goalMode`:`chat:focusSession.planMode`),onRunMode:e=>Xn(e)}),...t?[]:[{invocation:`/btw`,description:J(`chat:commands.builtin.btw`)}],...Pe?[{invocation:`/compact`,description:J(`chat:commands.builtin.compact`),run:()=>Kn()}]:[],...Zn&&!t?[{invocation:`/changes`,description:J(`chat:commands.builtin.changes`),run:()=>Zn.show(`changes`)}]:[]],ir=z?.model||f||``,ar=$n(L.find(e=>e.key===ir)?.label||ir.split(`/`).at(-1)||``,L.map(e=>e.label)),or=e?.botId,sr=(0,Q.useMemo)(()=>mt?{model:ar,...or?{botId:or}:{}}:null,[or,ar,mt]),cr=(0,Q.useRef)([]);(0,Q.useEffect)(()=>()=>{for(let e of cr.current)window.clearTimeout(e);cr.current=[]},[e.id]);let lr=!!(Ct.features.agentTranscripts&&Zn&&!t),ur=(0,Q.useMemo)(()=>lr&&Xe(i,x.length?x:S),[x,i,lr,S]),dr=(0,Q.useRef)(!!s);dr.current=!!s;let fr=Ge(e.id,!!or||ur,()=>{if(or)for(let e of[1500,4e3,9e3])cr.current.push(window.setTimeout(()=>{dr.current||Oe?.()},e))}),Z=(0,Q.useRef)(W),pr=fr.reload;(0,Q.useEffect)(()=>{let e=Z.current&&!W;if(Z.current=W,!or||!e)return;let t=[1500,4e3].map(e=>window.setTimeout(pr,e));return()=>{for(let e of t)window.clearTimeout(e)}},[or,pr,W]);let mr=(0,Q.useMemo)(()=>or?{sessionId:e.id,agents:new Map(fr.agents.map(e=>[e.id,e])),links:new Map(fr.links.map(e=>[e.id,e])),reload:fr.reload}:null,[or,e.id,fr.agents,fr.links,fr.reload]),hr=Pr(e=>e.select),gr=Zn?.show,_r=(0,Q.useMemo)(()=>lr&&gr?{sessionId:e.id,agents:fr.agents,open:t=>{hr(e.id,t),gr(`subagent`)}}:null,[hr,e.id,fr.agents,gr,lr]),vr=(0,Q.useMemo)(()=>{let e=ht?i:i.filter(e=>!Ie(e));return or?$e(e,fr.agents,fr.links):e},[or,i,ht,fr.agents,fr.links]),yr=Number(M?.percent),br=M?.percent!=null&&Number.isFinite(yr)?yr:null,xr=i[Ae(i)],Cr=xr?.role===`agent`?xr:null,wr=Bn||me||(W?``:String(Cr?.error||``)),Tr=!s&&!Bn&&!W&&i.some(e=>e.role===`user`);(0,Q.useEffect)(()=>{Ut(!1),Zt(!1)},[e.id]),(0,Q.useEffect)(()=>{q&&(sn([q]),Te?.())},[q,Te,sn]);let Er=async e=>{let t=await at?.(e);if(!t||!Bt(t))return;let n=cn.current;requestAnimationFrame(()=>{!n||cn.current!==n||!n.isConnected||n.focus()})},Dr=async e=>{await at?.(e)},Or=e=>{Lt(e),requestAnimationFrame(()=>{let e=cn.current;e&&e.focus()})},kr=bt({cwd:I,selection:Rt}),Ar=(0,$.jsx)(So,{sessionId:e.id,shortcutEnabled:r,variant:ht?`button`:`menu`,controlRef:Cn,onLiveText:e=>{if(e===null){Sn.current!==null&&(An(Sn.current),Sn.current=null);return}Sn.current===null&&(Sn.current=(cn.current?.value??It).trimEnd());let t=Sn.current;An(t&&e?`${t}\n${e}`:t||e)},onInsert:e=>{let t=Sn.current??(cn.current?.value??It).trimEnd();Sn.current=null,An(t?`${t}\n${e}`:e),requestAnimationFrame(()=>cn.current?.focus())}}),jr=J(`board:composer.plusMenu`),Mr=()=>void Pa({templatePrompt:J(`chat:focusSession.visualPromptTemplate`),configureHint:J(`chat:focusSession.configureVisualModelFirst`),notify:ge,onOpenModelSettings:Ce,onInsertPrompt:Or}),Nr=(0,$.jsxs)(`button`,{type:`button`,className:Xt(ve,`composer-plus-trigger aria-expanded:bg-surface-hover aria-expanded:text-content max-[650px]:rounded-full max-[650px]:bg-surface-muted max-[650px]:dark:bg-surface-active max-[650px]:text-content`),ref:Jt,title:jr,"aria-label":jr,"data-composer-plus":!0,children:[(0,$.jsx)(ut,{size:18,className:G,"aria-hidden":`true`}),Rt.attachments.length>0&&(0,$.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 grid h-4 min-w-4 place-items-center rounded-full border-2 border-panel bg-star px-0.5 text-[10px] leading-none font-medium text-on-accent tabular-nums`,children:Rt.attachments.length})]}),Fr=ht?(0,$.jsx)(ma,{trigger:Nr,open:Kt,onOpenChange:qt,onAttachment:()=>void kr.choose(),onResource:()=>Ut(!0),onVisual:Dt?Mr:void 0,steer:W?{disabled:!It.trim()&&!Rt.attachments.length&&!Un,onSelect:pn}:void 0,mode:or?void 0:{valueLabel:J(_===`full-access`?`chat:focusSession.fullAccessShort`:_===`workspace-write`?`chat:focusSession.workspaceWriteShort`:`chat:focusSession.approvalRequiredShort`),onOpen:()=>Gt(!0)}}):(0,$.jsxs)(Ft,{children:[(0,$.jsx)(Nt,{asChild:!0,children:Nr}),(0,$.jsxs)(Pt,{align:`start`,side:`top`,className:`w-60 p-1 max-[650px]:[&_[role=menuitem]]:min-h-11`,"data-composer-plus-menu":!0,children:[(0,$.jsxs)(jt,{"data-composer-plus-item":`attachment`,onSelect:()=>void kr.choose(),children:[(0,$.jsx)(st,{"aria-hidden":`true`}),J(`chat:focusSession.addAttachment`)]}),(0,$.jsxs)(jt,{"data-composer-plus-item":`resource`,onSelect:()=>Ut(!0),children:[(0,$.jsx)(R,{"aria-hidden":`true`}),J(`chat:resourcePicker.open`)]}),(0,$.jsx)(At,{}),Dt&&(0,$.jsxs)(jt,{"data-composer-plus-item":`visual`,onSelect:Mr,children:[(0,$.jsx)(ee,{"aria-hidden":`true`}),J(`chat:focusSession.generateImage`)]}),(0,$.jsxs)(jt,{"data-composer-plus-item":`voice`,onSelect:()=>Cn.current?.(),children:[(0,$.jsx)(ii,{"aria-hidden":`true`}),J(`board:composer.voiceInput`),_n&&(0,$.jsx)(Mt,{children:_n})]})]})]}),Ir=(0,$.jsx)(pa,{sheet:ht,collapse:ht,open:Wt,onOpenChange:e=>{Gt(e),!e&&ht&&window.setTimeout(()=>Jt.current?.focus(),0)},approvalMode:_,onApprovalModeChange:Me,approvalDisabled:U,runMode:jn,onRunModeChange:Xn,runModeDisabled:!!W,goalsAvailable:wt,teamAvailable:Tt,goal:v,tokenBudget:jn===`team`?Fn:Nn,onTokenBudgetChange:jn===`team`?In:Pn,onSaveTokenBudget:e=>ze?.(e)}),Lr=(0,$.jsx)(he,{sheet:ht,model:z?.model||f,models:L,onModelChange:ke,thinkingLevel:z?.thinkingLevel||p||`medium`,levels:z?.model?[]:m||[],status:h,message:g,onThinkingChange:je,modelDisabled:B||V,thinkingDisabled:V||B,deferred:W,pendingModel:!!z?.model,usage:(0,$.jsx)(ye,{sessionId:e.id,usage:M,sessionUsage:N,model:f,availableModels:L,onThresholdChange:Le})}),Rr=(0,$.jsx)(`div`,{className:Xt(`flex items-center`,ht?`shrink-0`:`min-w-0 shrink [&_.model-effort-pill]:max-w-full @max-[300px]/composer-footer:[&_.model-effort-pill>span:nth-child(n+2)]:hidden`),children:Lr}),zr=(0,Q.useMemo)(()=>En(pe),[pe]),Br={session:e,cwd:I||``,streaming:!!W,treeAvailable:i.length>0,onRename:Ue,onWorkspace:He,workspaceDisabled:!!(W||H),onCompact:Pe?()=>void Kn():void 0,compactDisabled:!!(W||Hn||D?.active||i.length===0),workflowsAvailable:Et,onVoiceMode:()=>Qt(!0),notify:ge??(()=>void 0)},Vr=x.length?x:S,Hr=mt&&(0,$.jsx)(Ma,{visible:i.length>0,open:Yt,sessionId:e.id,streaming:!!W,revision:P,pulseToken:F,onOpenChange:Zt,onNavigated:async e=>{e!==null&&Or(e),await nt?.(),kn()},onCreateChildSession:e=>qe(e),notify:ge,children:(e,t)=>ht?(0,$.jsx)(ia,{...Br,runStartedAt:te,approvals:de.length,failed:!!(!W&&(me||Cr?.error)),stopped:!!(!W&&ae),contextPercent:br,leading:pt,branches:t.branches,onOpenTree:t.open,runningActivity:Vr}):(0,$.jsx)(Zi,{...Br,contextPercent:br,branches:t.branches,onOpenTree:t.open,runningActivity:Vr})}),Ur=t?(0,$.jsx)(ua,{phone:ht,leading:pt,project:ht?t.renderProjectControl(`header`):void 0}):Hr,Wr=(0,$.jsx)(Fe,{emptyState:t?(0,$.jsx)(la,{}):n,botId:e?.roomId?void 0:or,layoutMeasurementKey:`fixed`,sessionId:e.id,messages:vr,transcriptLoadState:a,messageStart:o,hasNewer:s,onLoadLatest:Oe,hasOlder:c,loadingOlder:u,olderError:d,currentActivity:b,team:y,activityFeed:x,tools:S,thinkingText:C,compaction:D,streaming:W,runStartedAt:te,lastActivityAt:ne,runFinishedAt:re,runStopped:ae,runNotice:se,error:me,scrollRequest:rn,cwd:I,lineage:e.lineage,switchingCwd:H,onLoadOlder:De,onBranchFromHere:We,onCreateChildSession:qe,onRetryLastTurn:et,onPromptSelect:Or,onWorkspace:He,collapseEarlierTurns:ht},`transcript`),Gr=e=>ce(e.dataTransfer)?(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),nn(!0),!0):!1,Kr=(0,$.jsxs)(`form`,{className:Xt(`focus-composer-shell relative z-20 mx-auto flex w-[min(768px,calc(100%_-_48px))] shrink-0 flex-col gap-2 pt-2 pb-3 @max-[700px]:w-[calc(100%_-_24px)] max-[650px]:pb-2.5`,Dn&&`before:pointer-events-none before:absolute before:inset-x-0 before:-top-9 before:h-9 before:bg-linear-to-b before:from-transparent before:to-panel`),onSubmit:e=>{let t=dn.current;dn.current=`steer`;let n=Se(It);if(n!==null){e.preventDefault(),n&&(nr.ask(n),Lt(``));return}if(!W&&(z||B||V)){e.preventDefault();return}qn(e,mt?t:`steer`)},children:[nr.state&&(0,$.jsx)(ga,{state:nr.state,cwd:I||void 0,onDismiss:()=>{nr.dismiss(),cn.current?.focus()}}),(0,$.jsx)(we,{approvals:de,onResolve:Be,sessionTitle:e.name||e.id,cwd:I||``}),zr[0]&&Ve&&(0,$.jsx)(Na,{question:zr[0],more:zr.length-1,collapsed:de.length>0,onAnswer:Ve},zr[0].id),Et&&!t&&(0,$.jsx)(Di,{sessionId:e.id}),Un&&(0,$.jsx)(be,{invocation:Un,onRemove:()=>Wn(null)}),Rt.attachmentError&&(0,$.jsx)(`span`,{className:`text-[var(--danger)] text-[13px]`,children:Rt.attachmentError}),wr&&(0,$.jsx)(tt,{error:wr,onRetry:Tr?et:void 0,className:`w-full`}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-col`,children:[(0,$.jsx)(ue,{streaming:W,compaction:D,startedAt:te,stopping:zn,onStop:()=>void Jn(),runRow:!ht,queuedInputs:w,withdrawingInputIds:E,onEdit:at?Er:void 0,onCancel:at?Dr:void 0,onSendNow:Ot&&ot?e=>void ot(e):void 0,queueList:!ht,workspace:t?null:T,onDeliverSessionMessages:ct,onDismissSessionMessages:lt}),(0,$.jsxs)(`div`,{className:Xt(`focus-composer relative flex min-w-0 flex-col rounded-[var(--composer-radius,22px)] [corner-shape:var(--composer-corner-shape,round)] border border-control bg-solid shadow-composer transition-[border-color,box-shadow] duration-(--d-fast) ease-(--ease) has-[textarea:focus]:border-focus has-[textarea:focus]:ring-3 has-[textarea:focus]:ring-focus-ring max-[650px]:rounded-[28px] max-[650px]:border-stroke-strong max-[650px]:shadow-none max-[650px]:has-[textarea:focus]:border-control max-[650px]:has-[textarea:focus]:ring-0 [&>.attachment-tray]:px-3 [&>.attachment-tray]:pt-3 [&_textarea]:w-full [&_textarea]:min-w-0 [&_textarea]:min-h-11 [&_textarea]:max-h-[220px] [&_textarea]:resize-none [&_textarea]:overflow-y-auto [&_textarea]:border-0 [&_textarea]:[outline:0]! [&_textarea]:bg-transparent [&_textarea]:px-4 [&_textarea]:pt-3 [&_textarea]:pb-1 [&_textarea]:text-[length:calc(var(--app-message-font-size)*.9375)] max-[650px]:[&_textarea]:px-3.5 max-[650px]:[&_textarea]:text-[length:var(--app-message-font-size)] [&_textarea]:[font-family:var(--font-content-family)] [&_textarea]:font-[400] [&_textarea]:leading-5 [&_textarea]:text-content [&_textarea]:placeholder:text-content-muted`,tn&&`border-focus ring-3 ring-focus-ring`),onDragEnter:Gr,onDragOver:Gr,onDragLeave:e=>{let t=e.relatedTarget;t instanceof Node&&e.currentTarget.contains(t)||nn(!1)},onDrop:e=>{nn(!1),Rt.dropFiles(e)},children:[tn&&(0,$.jsx)(`div`,{role:`status`,className:`pointer-events-none absolute inset-0 z-10 grid place-items-center rounded-[inherit] border border-dashed border-focus bg-panel px-4 text-center text-sm text-content`,children:J(`chat:focusSession.dropAttachment`)}),(0,$.jsx)(xt,{attachments:Rt.attachments,preparing:Rt.preparingAttachments,onRemove:Rt.removeAttachment}),(0,$.jsx)(K,{placement:`top`,resourceKey:e.id,loadCommands:tr,builtinCommands:rr,value:It,onChange:Lt,inputRef:cn}),(0,$.jsx)(`textarea`,{ref:cn,rows:1,"aria-label":J(`chat:focusSession.taskDescription`),value:It,onChange:e=>{Lt(e.target.value)},onPaste:Rt.pasteFiles,onCompositionStart:()=>Tn.current=!0,onCompositionEnd:()=>window.setTimeout(()=>Tn.current=!1,0),onKeyDown:e=>{let t=e.nativeEvent.isComposing||Tn.current;if(mt&&W&&!t&&fn&&yn(e.nativeEvent,fn)){e.preventDefault(),dn.current=kt,e.currentTarget.form?.requestSubmit();return}if(e.key===`Tab`&&e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!t&&!W){let t=ha(jn,{goalsAvailable:wt,teamAvailable:Tt});if(t){e.preventDefault(),Xn(t),en(J(t===`team`?`chat:focusSession.teamMode`:t===`goal`?`chat:focusSession.goalMode`:`chat:focusSession.planMode`));return}}!t&&yn(e.nativeEvent,gt.sendMessage)&&(e.preventDefault(),e.currentTarget.form?.requestSubmit()),!mt&&W&&!t&&e.key===`Escape`&&!e.defaultPrevented&&(e.preventDefault(),Jn())},"data-mobile-composer-input":St||void 0,enterKeyHint:St&>.sendMessage===`Enter`?`send`:`enter`,placeholder:On}),(0,$.jsx)(`span`,{role:`status`,className:`sr-only`,children:$t}),(0,$.jsxs)(`div`,{className:`focus-composer-footer @container/composer-footer flex min-w-0 items-center gap-1 px-2 pt-1 pb-2 max-[650px]:gap-2 max-[650px]:pt-2 max-[650px]:pb-3`,"data-composer-toolbar":!0,children:[Fr,kr.input,ht&&!or&&Rr,!ht&&t?.renderProjectControl(`chip`),!or&&Ir,(0,$.jsx)(`span`,{className:`min-w-0 flex-1`}),Ar,!ht&&!or&&Rr,(0,$.jsx)(le,{streaming:W,queueing:Ln,submitting:Rn,stopping:zn,preparing:Rt.preparingAttachments.length>0,hasDraft:!!(It.trim()||Rt.attachments.length||Un),canQueue:!!it,blockedReason:!W&&(z||B||V)?J(`chat:focusSession.waitingForModel`):void 0,disabled:!W&&(!!z||B||V||Ln||!It.trim()&&!Rt.attachments.length&&!Un),onLongPress:ht&&W?pn:void 0,longPressHint:J(`board:composer.longPressSteer`),onStop:ht?()=>void Jn():void 0})]})]})]})]},`composer`);return(0,$.jsxs)(Sr,{className:Xt(`focus-session [--chat-content-width:768px] [.session-dock-panel_&]:overflow-hidden [.session-dock-panel_&]:min-h-0 [.session-dock-panel_&]:border-0 [.session-dock-panel_&]:rounded-[0] [.session-dock-panel_&]:bg-[var(--panel)] [.session-dock-panel_&]:p-0 [.session-dock-panel_&]:shadow-[none] [[data-theme='dark']_.session-dock-panel_&]:bg-[var(--main-surface-bg)] min-[651px]:[[data-density='compact']_.app-card:not(&)]:p-[10px] max-[650px]:min-h-[460px] max-[650px]:[.session-dock-panel_&]:min-h-0 relative flex h-full min-h-0 flex-col ${Dn?`has-conversation`:`is-empty`}`,t&&`min-[651px]:[&_[data-chat-region=messages]]:!flex-none min-[651px]:[&_[data-chat-region=messages]]:mt-[max(48px,calc((100dvh-520px)/2))] min-[651px]:[&_[data-chat-region=messages]]:!overflow-visible min-[651px]:[&_.transcript]:!overflow-visible min-[651px]:[&_.transcript]:!p-0 min-[651px]:[&_.transcript]:!pb-6`),"data-chat-message-style":`bubble`,children:[(0,$.jsxs)(`div`,{ref:un,className:`flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,$.jsx)(`div`,{className:`shrink-0`,"data-chat-region":`header`,children:ft?.headerHost?(0,zi.createPortal)(Ur,ft.headerHost):ft?null:Ur}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,"data-chat-region":`messages`,"data-focus-region":`content`,children:(0,$.jsx)(Qe.Provider,{value:mr,children:(0,$.jsx)(Je.Provider,{value:_r,children:sr?(0,$.jsx)(Ke.Provider,{value:sr,children:Wr}):Wr})})}),(0,$.jsx)(`div`,{className:`shrink-0`,"data-chat-region":`composer`,"data-focus-region":`composer`,children:Kr})]}),ft?.sourceActionHost&&(0,zi.createPortal)((0,$.jsx)(yt,{cwd:I,selection:Rt}),ft.sourceActionHost),(0,$.jsx)(aa,{open:Ht,sessionId:e.id,cwd:I||``,onClose:()=>Ut(!1),onSelect:Wn,onCommandSelect:e=>Or(oe(e,It))}),(0,$.jsx)(Go,{open:Y,sessionId:e.id,sessionName:e.name||e.id,messages:i,streaming:W,sendPrompt:async(...e)=>{await rt(...e)},onAbort:dt,onClose:()=>Qt(!1)})]})}),Qo=(0,Q.createContext)(null),$o=40,es=[],ts=()=>void 0;function ns(e){let t=e?.queue;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.startAfter;return typeof n==`string`?n:``}function rs({draft:e}){let t=(0,Q.useContext)(Qo),{t:n}=l(),r=n(`board:home.draftTitle`),i=(0,Q.useMemo)(()=>({id:``,name:r,cwd:e.cwd,runMode:e.runMode}),[e.cwd,e.runMode,r]);if(!t)return null;let a=t.pendingAsset?.asset&&!t.pendingAsset.targetSessionId?t.pendingAsset.asset:null;return(0,$.jsx)(`div`,{className:`session-dock-panel h-full w-full min-w-0 min-h-0 overflow-hidden [container-type:inline-size] bg-panel`,"data-new-task-draft":!0,children:(0,$.jsx)(Zo,{session:i,shortcutEnabled:!0,draft:e,messages:es,transcriptLoadState:`ready`,model:e.model||t.defaultModel,thinkingLevel:e.thinkingLevel,availableThinkingLevels:e.availableThinkingLevels,executionMode:e.executionMode,runMode:e.runMode,activityFeed:es,tools:es,queuedInputs:es,approvals:es,cwd:e.cwd,availableModels:t.availableModels,pendingAsset:a,onAssetConsumed:t.onAssetConsumed,notify:t.notify,onOpenModelSettings:t.openModelSettings,onModelChange:e.onModelChange,onThinkingLevelChange:e.onThinkingLevelChange,onExecutionModeChange:e.onExecutionModeChange,onRunModeChange:e.onRunModeChange,onApproval:ts,onWorkspace:ts,onRename:ts,onBranchFromHere:ts,onCreateChildSession:ts,onRetryLastTurn:ts,onAbort:ts,onSend:(n,r,i,a,o,s,c)=>t.sendNewTask(e,n,r,i,a,o,s,{onAccepted:c})})})}function is({sessionId:e,onCreateSession:t}){let n=(0,Q.useContext)(Qo),r=e??(n?.activeId||``);return r?(0,$.jsx)(as,{sessionId:r,panelId:`single-${r}`,shortcutEnabled:!0},r):(0,$.jsx)(os,{onNewSession:t})}function as({sessionId:e,panelId:t,shortcutEnabled:n,onFocusCapture:r}){let i=(0,Q.useContext)(Qo),{t:a}=l(),o=(0,Q.useContext)(Ye),s=k(e=>e.capabilities),c=i?.subscribeSessionState,u=i?.getSessionState,d=(0,Q.useMemo)(()=>t=>c?.(e,t)??(()=>{}),[c,e]),f=(0,Q.useMemo)(()=>()=>u?.(e),[u,e]),p=(0,Q.useSyncExternalStore)(d,f),m=i?.sessions.find(t=>t.id===e),h=p||Me,g=je(h,m),_=ns(m),v=Ce(p,m),y=p&&Object.hasOwn(p,`team`)?p.team:m?.team??null,b=Ne(v,{streaming:g})?v:null,x=i?.sessionTreePulseSessionId===e?i.sessionTreePulseToken:0,S=i?.loadSessionMessages,C=i?.loadSessionThinkingLevel,w=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{e&&S?.(e,{limit:$o})},[S,e]),(0,Q.useEffect)(()=>{!e||!m||!C||h.thinkingStatus||(h.availableThinkingLevels||[]).length||w.current!==e&&(w.current=e,C(e))},[C,m,e,h.availableThinkingLevels,h.thinkingStatus,g]);let T=(0,Q.useMemo)(()=>({onLoadLatest:()=>i?.loadSessionMessages(e,{force:!0}),onLoadOlder:()=>i?.loadOlderMessages(e)??!1,onModelChange:t=>i?.switchSessionModel(e,t),onThinkingLevelChange:t=>i?.switchSessionThinkingLevel(e,t),onExecutionModeChange:t=>i?.switchSessionExecutionMode(e,t)??!1,onRunModeChange:t=>i?.switchSessionRunMode(e,t)??!1,onGoalPause:()=>i?.pauseGoal(e),onGoalBudgetChange:t=>i?.setGoalBudget(e,t),onCompact:()=>i?.compactSession(e),onApproval:(t,n)=>i?.resolveToolApproval(e,t,n),onAnswerQuestion:async(t,n)=>{await i?.answerQuestion(e,t,n)},onWorkspace:()=>{m&&i?.selectSessionWorkspace(m)},onRename:()=>{m&&i?.renameSession(m)},onBranchFromHere:(e,t)=>{if(m)return i?.branchFromEntry(m,e,t)},onCreateChildSession:e=>{if(m)return i?.createChildSession(m,e)},onRetryLastTurn:()=>i?.retryLastTurn(e),onTreeNavigated:()=>i?.reloadSessionBranch(e),onSend:(t,n,r,a,o,s,c)=>i?.sendPrompt(t,e,n,r,a,o,s,{onAccepted:c}),onQueue:(t,n,r,a)=>i?.queuePrompt(t,e,n,r,a)??!1,onWithdrawQueuedInput:t=>i?.withdrawQueuedInput(e,t)??Promise.resolve(null),onSendQueuedInputNow:t=>i?.sendQueuedInputNow(e,t)??Promise.resolve(!1),onDeliverSessionMessages:()=>i?.deliverSessionMessages(e)??Promise.resolve(),onDismissSessionMessages:()=>i?.dismissSessionMessages(e)??Promise.resolve(),onAbort:()=>i?.abort(e)}),[i,e,m]);if(!i||!m)return(0,$.jsxs)(`div`,{className:`session-dock-missing flex h-full min-h-[180px] items-center justify-center gap-2 text-sm text-content-secondary`,children:[(0,$.jsx)(Ct,{size:16}),i?`Session unavailable`:`Loading session`]});let E=i.pendingAsset?.asset&&(!i.pendingAsset.targetSessionId||i.pendingAsset.targetSessionId===e)?i.pendingAsset.asset:null,D=h.historyWindow?.messages||h.messages||es,A=h.loaded?`ready`:h.loading||!h.error?`loading`:`error`,j=!!(h.recovering&&!D.length&&!h.error),M=h.lifecycle?.phase===`completed`&&!h.error&&!h.runStopped,N=typeof h.runStartedAt==`string`?h.runStartedAt:null,P=h.goal??m.goal??null,F=_&&i.sessions.find(e=>e.id===_)?.name||``,I=_!==null&&!g&&!D.length?(0,$.jsx)(ir,{compact:!0,className:`min-h-full`,title:a(`chat:focusSession.queuedTitle`),description:F?a(`chat:focusSession.queuedAfter`,{title:F}):a(`chat:focusSession.queuedAfterUnknown`),action:(0,$.jsx)(Y,{variant:`secondary`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>void X.startQueuedSession(e).then(()=>i.loadSessionMessages(e,{force:!0})).catch(e=>i.notify(Z(e),`error`)),children:a(`chat:focusSession.startQueuedNow`)})}):void 0,L=(0,$.jsx)(Zo,{session:m,emptyState:I,shortcutEnabled:n,messages:D,transcriptLoadState:j?`loading`:A,hasNewer:!!h.historyWindow,messageStart:h.historyWindow?.messageStart??h.messageStart,hasOlder:h.historyWindow?.hasOlder??h.hasOlder,loadingOlder:h.loadingOlder,olderError:h.olderError,model:h.model||m.model||i.defaultModel,thinkingLevel:h.thinkingLevel||m.thinkingLevel||`medium`,availableThinkingLevels:h.availableThinkingLevels||es,thinkingStatus:h.thinkingStatus||``,thinkingMessage:h.thinkingMessage||``,executionMode:h.executionMode||m.executionMode||`approval-required`,runMode:h.runMode||m.runMode||`plan`,goal:P,team:y,plan:b,currentActivity:h.currentActivity,activityFeed:h.activityFeed||es,tools:h.tools||es,thinkingText:h.thinkingText||``,queuedInputs:h.queuedInputs||es,workspace:h.workspace||null,withdrawingInputIds:h.withdrawingInputIds||es,compaction:h.compaction,contextUsage:h.contextUsage,sessionUsage:h.sessionUsage,sessionTreeRevision:h.sessionTreeRevision,sessionTreePulse:x,cwd:h.cwd||m.cwd,availableModels:i.availableModels,pendingRuntimeSelection:h.pendingRuntimeSelection,switchingModel:h.switchingModel,switchingThinking:h.switchingThinking,switchingCwd:h.switchingCwd,switchingPermission:h.switchingPermission,streaming:g,runStartedAt:h.runStartedAt,lastActivityAt:h.lastActivityAt,runFinishedAt:h.runFinishedAt,runStopped:h.runStopped,runNotice:h.runNotice,approvals:h.approvals||es,questions:h.questions||es,error:h.error||(i.activeId===e?i.globalError:``),pendingAsset:E,onAssetConsumed:i.onAssetConsumed,notify:i.notify,onOpenModelSettings:i.openModelSettings,onCompactionThresholdChange:i.setCompactionThreshold,...T});return(0,$.jsx)(`div`,{className:Xt(`session-dock-panel w-full h-full min-w-0 min-h-0 overflow-hidden [container-type:inline-size] bg-panel`,o&&`animate-[fade-in_var(--d-fast)_var(--ease-enter)]`),onFocusCapture:r,"data-session-panel":e,children:o?(0,$.jsx)(Ri,{sessionId:e,messages:D,cwd:h.cwd||m.cwd||``,remoteMachine:!!m.machine,active:n,plan:b,goal:P,team:y,activity:h.activityFeed?.length?h.activityFeed:h.tools||es,planTab:!!(b?.items?.length||P||y),streaming:g,completed:M,runStartedAt:N,requestConfirm:i.requestConfirm,children:L},e):(0,$.jsx)(bi,{messages:D,taskName:m.name||e,cwd:h.cwd||m.cwd||``,sessionId:e,panelId:t||`mobile-${e}`,active:n,mobile:i.mobileLayout,plan:b,streaming:g,completed:M,runStartedAt:N,plansAvailable:O(s,`plans`),requestConfirm:i.requestConfirm,children:L},e)})}function os({onNewSession:e,newSessionShortcut:t}){let{t:n}=l();return(0,$.jsxs)(`div`,{className:`flex h-full min-h-[180px] flex-col items-center justify-center gap-1.5 px-6 text-center`,children:[(0,$.jsx)(rr,{className:`mb-1.5`}),(0,$.jsx)(`strong`,{className:`text-sm font-medium text-content`,children:n(`chat:chatDock.openAChatToBegin`)}),(0,$.jsx)(`span`,{className:`max-w-[320px] text-xs leading-relaxed text-content-muted`,children:n(`chat:chatDock.openAChatFromTheSessionListOrSplitItInAnyDirection`)}),e?(0,$.jsxs)(Y,{variant:`secondary`,className:`mt-3`,onClick:()=>void e(),children:[(0,$.jsx)(ut,{"aria-hidden":`true`}),n(`chat:chatDock.newChat`),t?(0,$.jsx)(Qt,{"aria-hidden":`true`,className:`ml-1.5 pointer-coarse:hidden`,children:t.split(/\+(?=.)/).map(e=>(0,$.jsx)($t,{children:e},e))}):null]}):null]})}var ss=1e4;function cs(e,t){return{defaultModel:e.model?`${e.provider}/${e.model}`:t(`chat:chatPage.noModelConfigured`),availableModels:e.providers.flatMap(e=>e.configured&&e.enabled?e.models.filter(e=>e.kind===`chat`).map(t=>({key:`${e.id}/${t.id}`,provider:e.id,modelId:t.id,label:t.name||t.id,providerName:e.name||e.id})):[])}}function ls(e){let t=e.getQueryData(_)?.sessions,n=e.getQueryData([`config`]);return Array.isArray(t)&&t.length&&n?{sessions:t,config:n}:null}function us({notify:e}){let{t:n}=l(),r=h(),[a]=(0,Q.useState)(()=>ls(r)),[o,s]=(0,Q.useState)(()=>a?.sessions??[]),[c,u]=(0,Q.useState)(()=>i.getItem(p.activeSession)||``),[d,f]=(0,Q.useState)({}),[g,v]=(0,Q.useState)(!a),[y,b]=(0,Q.useState)(``),[x,S]=(0,Q.useState)(()=>a?cs(a.config,n).defaultModel:n(`chat:chatPage.waitingForConfiguration`)),[C,w]=(0,Q.useState)(()=>a?cs(a.config,n).availableModels:[]),T=(0,Q.useRef)(o),E=(0,Q.useRef)(d),D=(0,Q.useRef)(new Map),O=(0,Q.useRef)(null),k=(0,Q.useRef)(new Map),A=(0,Q.useRef)(new Set),j=(0,Q.useRef)(0),M=(0,Q.useRef)(0),[N]=(0,Q.useState)(Er),P=(0,Q.useCallback)(e=>{let t=T.current,n=typeof e==`function`?e(t):e;if(n===t)return n;let i=r.setQueryData(_,e=>e?{...e,sessions:n}:void 0)?.sessions??n;return i!==T.current&&(T.current=i,s(i)),i},[r]),F=(0,Q.useCallback)(()=>{if(j.current)return;let e=r.getQueryData(_)?.sessions;if(!(!Array.isArray(e)||e===T.current)){if(e.length)M.current=0;else if(T.current.length&&Date.now()<M.current)return;T.current=e,s(e)}},[r]);(0,Q.useEffect)(()=>{F();let e=m(_);return r.getQueryCache().subscribe(t=>{t.type===`updated`&&t.query.queryHash===e&&F()})},[r,F]),(0,Q.useEffect)(()=>fn(window,e=>{N.record(e),P(t=>wr(t,e))}),[N,P]),(0,Q.useEffect)(()=>en(window,e=>{P(t=>Or(t,e))}),[P]);let I=(0,Q.useCallback)(e=>{let t=A.current.size?Object.fromEntries(Object.entries(e).filter(([e])=>!A.current.has(e))):e,n=E.current;E.current=t,f(t);let i=Object.keys(t).filter(e=>t[e].streaming!==n[e]?.streaming);if(i.length){let e=new Set(i);r.setQueryData(_,n=>n&&{...n,sessions:n.sessions.map(n=>e.has(n.id)?{...n,streaming:t[n.id].streaming}:n)})}let a=new Set([...Object.keys(n),...Object.keys(t)]);for(let e of a){if(n[e]===t[e])continue;let r=D.current.get(e);if(r)for(let e of[...r])e()}},[r]);(0,Q.useEffect)(()=>tn(window,({deletedIds:e})=>{N.remove(e);let t=new Set(e),n=P(e=>e.filter(e=>!t.has(e.id)));u(e=>t.has(e)?n[0]?.id||``:e);let r=E.current;e.some(e=>e in r)&&I(Object.fromEntries(Object.entries(r).filter(([e])=>!t.has(e))))}),[I,N,P]);let L=(0,Q.useCallback)((e,t)=>{let n=D.current.get(e)||new Set;return n.add(t),D.current.set(e,n),()=>{n.delete(t),n.size||D.current.delete(e)}},[]),R=(0,Q.useCallback)(e=>E.current[e]||Me,[]),z=(0,Q.useCallback)((e,t)=>{if(!e||A.current.has(e))return;let n=E.current,r=n[e]||Me,i=ze(r,t);i!==r&&I({...n,[e]:i})},[I]);(0,Q.useEffect)(()=>pn(window,({id:e,cwd:t})=>{P(n=>n.map(n=>n.id===e?{...n,cwd:t}:n)),E.current[e]&&z(e,{cwd:t})}),[z,P]);let B=(0,Q.useCallback)((e,{panelOpen:t=!1,localStreamOwned:n=!1}={})=>{if(!e||t||n||k.current.has(e))return!1;let r=E.current,i=r[e];if(!i||Be(i))return!1;let a={...r};return delete a[e],I(a),!0},[I]),V=(0,Q.useCallback)(e=>{if(!e)return;A.current.add(e);let t={...E.current};delete t[e],I(t)},[I]),H=(0,Q.useCallback)(e=>{if(A.current.has(e))return()=>{};let t=k.current;t.set(e,(t.get(e)??0)+1);let n=!1;return()=>{if(n)return;n=!0;let r=t.get(e)??0;r>1?t.set(e,r-1):(t.delete(e),B(e))}},[B]),U=(0,Q.useCallback)(async(e,{preserveExistingOnEmpty:t=!1}={})=>{let n=N.getRevision();t&&(j.current+=1);let r;try{let e=await X.listSessions(),i=!!(t&&!e.sessions.length&&T.current.length);i&&(M.current=Date.now()+ss),r=i?T.current:N.reconcile(e.sessions,n)}finally{t&&(--j.current,F())}return P(r),u(e||(e=>r.some(t=>t.id===e)?e:r[0]?.id||``)),dn(),r},[F,N,P]),W=(0,Q.useCallback)(e=>{u(e.id),P(t=>Cr(t,[e])),z(e.id,{messages:[],tools:[],approvals:[],queuedInputs:[],permissionMode:e.permissionMode||`ask`,executionMode:e.executionMode||`approval-required`,runMode:e.runMode||`plan`,goal:e.goal||null,plan:Ln(e,null),contextUsage:e.contextUsage||null,sessionUsage:e.sessionUsage||null,compaction:null,streaming:!1,error:``,loaded:!0,pageSize:40,messageStart:0,hasOlder:!1,olderCursor:null,runStartedAt:null,lastActivityAt:null,runFinishedAt:null,runStopped:!1,runNotice:``})},[z,P]),ee=(0,Q.useCallback)((t=``,{inheritRecentCwd:r=!0}={})=>{if(O.current)return O.current;let i=(async()=>{try{b(``);let i=await X.createSession(n(`chat:chatPage.newChat`),Tr(t,T.current,r));W(i);try{await U(i.id)}catch(e){b(n(`chat:chatPage.theChatWasCreatedButTheListCouldNotBeRefreshedError`,{error:Z(e)}))}return e(n(`chat:chatPage.newChatCreated`)),i.id}catch(e){return b(Z(e)),``}})();return O.current=i,i.finally(()=>{O.current===i&&(O.current=null)}),i},[W,e,U,n]);(0,Q.useEffect)(()=>{let r=!0,o=N.getRevision();return(a?Promise.resolve([{sessions:a.sessions},a.config]):Promise.all([X.listSessions({refresh:!1}),X.getConfig()])).then(async([a,s])=>{if(!r)return;let c=cs(s,n);S(c.defaultModel),w(c.availableModels);let l=a.sessions;if(!l.length&&(O.current||Object.keys(E.current).length)){if(await O.current,!r)return;o=N.getRevision(),l=(await X.listSessions()).sessions}if(!r)return;l=N.reconcile(l,o),P(e=>Cr(e,l));for(let e of l)z(e.id,{team:e.team||null,agents:e.agents||[],plan:Ln(e,null),...e.streaming?{streaming:!0,recovering:!0,loaded:!1,error:``}:{}});let d=i.getItem(p.activeSession),f=new Set([...l.map(e=>e.id),...Object.keys(E.current)]);if(u(e=>f.has(e)?e:d&&f.has(d)?d:l[0]?.id||``),typeof window<`u`&&window.__PISPER_MOBILE_APP__)try{let{consumeRemoteFallbackNotice:r}=await t(async()=>{let{consumeRemoteFallbackNotice:e}=await import(`./mobile-remote-fallback-LLMZWoIu.js`);return{consumeRemoteFallbackNotice:e}},__vite__mapDeps([144,8]));r()&&e(n(`chat:chatPage.remoteUnavailableSwitchedToLocal`))}catch{}}).catch(async e=>{if(r){if(typeof window<`u`&&window.__PISPER_MOBILE_APP__)try{let{fallbackRemoteToLocalAfterFailure:n}=await t(async()=>{let{fallbackRemoteToLocalAfterFailure:e}=await import(`./mobile-remote-fallback-LLMZWoIu.js`);return{fallbackRemoteToLocalAfterFailure:e}},__vite__mapDeps([144,8]));if(await n(e))return}catch{}r&&b(Z(e))}}).finally(()=>r&&v(!1)),()=>{r=!1}},[e,a,n,N,z,P]),(0,Q.useEffect)(()=>{c?i.setItem(p.activeSession,c):i.removeItem(p.activeSession)},[c]);let te=o.find(e=>e.id===c),ne=(d[c]||Me).model||te?.model||``;return(0,Q.useEffect)(()=>{rn(c,ne)},[c,ne]),(0,Q.useEffect)(()=>(document.title=te?.name?`${te.name} · ${Ot}`:Ot,()=>{document.title=Ot}),[te?.name]),{sessions:o,sessionsRef:T,activeId:c,setActiveId:u,sessionStates:d,sessionStatesRef:E,loading:g,globalError:y,setGlobalError:b,defaultModel:x,availableModels:C,updateSessions:P,replaceSessionStates:I,updateSessionState:z,releaseSessionState:B,retainSessionState:H,discardSessionState:V,subscribeSessionState:L,getSessionState:R,refreshSessions:U,adoptCreatedSession:W,createSessionRecord:ee}}function ds({setActiveId:e,loadSessionMessages:t,openRoutedSession:n}){let r=(0,Q.useRef)(n);r.current=n;let i=(0,Q.useCallback)(t=>(t&&r.current?r.current(t):e(t),!0),[e]);return(0,Q.useEffect)(()=>{let e=e=>{let n=e.detail,r=n?.sessionId||n?.id;r&&(localStorage.removeItem(p.sessionOpenRequest),i(r),n?.targetEntryId&&t(r,{force:!0,limit:40}))};return window.addEventListener(sn,e),()=>window.removeEventListener(sn,e)},[t,i]),(0,Q.useEffect)(()=>tn(window,({deletedIds:e})=>{for(let t of e)xr.getState().forget(t),de(t)}),[]),{openSession:i}}function fs(e){return!!e?.agents?.some(e=>[`queued`,`starting`,`running`].includes(String(e.status)))}function ps(e,{localStreamOwned:t=!1}={}){return!e||t?!1:!!(e.recovering||e.streaming||e.approvals?.length||fs(e))}function ms(e){return e?.recovering||e?.streaming?1:3}function hs({mobile:e,reason:t,lastEventAt:n,now:r=Date.now()}){return e||t!==`visible`?!0:!n||r-n>=1e4}function gs(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function _s(e,t){return typeof e==`string`?e.slice(0,t):``}function vs(e){let t=gs(e),n=_s(t?.id,200);return n?{id:n,title:_s(t?.title,80)}:null}function ys(e){let t=gs(e);if(!t)return null;let n=(Array.isArray(t.neighbours)?t.neighbours:[]).map(gs).filter(e=>!!(e&&_s(e.id,200))).slice(0,5).map(e=>({id:_s(e.id,200),title:_s(e.title,80),running:e.running===!0,fileCount:Number.isSafeInteger(e.fileCount)?Number(e.fileCount):0,files:(Array.isArray(e.files)?e.files:[]).map(e=>_s(e,500)).filter(Boolean).slice(0,5),lastChangedAt:_s(e.lastChangedAt,40)})),r=(Array.isArray(t.messages)?t.messages:[]).map(gs).flatMap(e=>{let t=vs(e?.from),n=_s(e?.id,200);return e&&t&&n?[{id:n,from:t,text:_s(e.text,4e3),at:_s(e.at,40)}]:[]}).slice(0,20);return n.length||r.length?{neighbours:n,messages:r}:null}function bs(e,t){return Object.hasOwn(e,`team`)?e.team??null:t??null}var xs=new WeakMap;function Ss(e){let t=xs.get(e);return t===void 0&&(t=JSON.stringify(e),xs.set(e,t)),t}function Cs(e,t){let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>{let t=n.get(e.id);return t&&Ss(t)===Ss(e)?t:e})}function ws(e,t){let n=Number(t.pageInfo?.start)||0,r=Number.isInteger(e.messageStart)?e.messageStart:null,i=r!=null&&r<=n,a=i?Math.max(0,n-r):0,o=i?r:n,s=i?[...e.messages.slice(0,a),...Cs(e.messages,t.messages)]:Cs(e.messages,t.messages),c=Math.max(0,s.length-200);return c&&(s=s.slice(c),o+=c),{messages:s,messageStart:o,hasNewer:!1,hasOlder:o>0,olderCursor:o>0?String(o):null}}function Ts(e,t){let n=new Set(e.messages.map(e=>e.id)),r=[...t.messages.filter(e=>!n.has(e.id)),...e.messages],i=r.slice(0,200);return{messages:i,messageStart:t.pageInfo.start,hasOlder:t.pageInfo.hasMore,olderCursor:t.pageInfo.nextCursor,hasNewer:!!(e.hasNewer||r.length>i.length)}}function Es(e,t){let n=Ts(e.historyWindow?{...e,...e.historyWindow}:e,t);return e.historyWindow||n.hasNewer?{...e,historyWindow:n}:{...e,...n}}function Ds(e){return{...e,historyWindow:null}}function Os(e,t,n){if(t.streaming||!e.error&&!t.error)return{page:n,error:t.error||``};let r=e.messages.at(-2),i=e.messages.at(-1);if(r?.role!==`user`||!/^user-\d+$/.test(r.id)||i?.role!==`agent`||!/^agent-\d+$/.test(i.id))return{page:n,error:t.error||``};let a=Date.parse(e.runStartedAt||``),o=n.messages.findIndex(e=>{if(e.id===r.id)return!0;if(e.role!==`user`||!Number.isFinite(a))return!1;let t=new Date(e.timestamp).getTime();return Number.isFinite(t)&&t>=a});if(o>=0&&n.messages.slice(o+1).some(e=>e.role===`agent`))return{page:n,error:t.error||``};let s=[...n.messages,...o<0?[r]:[],{...i,streaming:!1,error:t.error||e.error||i.error}],c=Math.max(0,s.length-200),l=n.messageStart+c;return{page:{...n,messages:c?s.slice(c):s,messageStart:l,hasOlder:l>0,olderCursor:l>0?String(l):null},error:t.error||e.error||``}}function ks(e,t,n=new Date().toISOString(),r=e.runtimeSelectionRevision||0){let i=r!==(e.runtimeSelectionRevision||0),a=!!(e.switchingModel||e.switchingThinking||i),o=t.finishedAt||e.runFinishedAt||n,s=Os(e,t,ws(e,t));return{...ke({...e,...s.page},t),tools:t.streaming?t.tools||[]:Vn(t.tools||[],{finishedAt:o,error:t.error||``}),streaming:t.streaming,recovering:t.streaming,runStartedAt:t.startedAt||e.runStartedAt||null,lastActivityAt:t.lastActivityAt||e.lastActivityAt||t.startedAt||null,runFinishedAt:t.streaming?null:o,runNotice:t.streaming&&e.runNotice||``,loaded:!0,loading:!1,error:a?e.error:s.error,model:a?e.model:t.model||e.model,cwd:t.cwd||e.cwd,permissionMode:t.permissionMode||e.permissionMode,executionMode:t.executionMode||e.executionMode,runMode:t.runMode||e.runMode,goal:t.goal??e.goal??null,team:bs(t,e.team),plan:Ln(t,e.plan??null),contextUsage:a?e.contextUsage:t.contextUsage??e.contextUsage??null,sessionUsage:t.sessionUsage??e.sessionUsage??null,compaction:t.compaction??e.compaction??null,approvals:t.approvals||[],questions:Array.isArray(t.questions)?t.questions:e.questions||[],workspace:ys(t.workspace),agents:t.agents||[],currentActivity:t.streaming?t.currentActivity||e.currentActivity||null:t.currentActivity?.type===`agent`?t.currentActivity:null,lifecycle:t.lifecycle??e.lifecycle??null,sessionTreeRevision:Number(t.sessionTreeRevision??e.sessionTreeRevision??0),activityFeed:t.streaming?t.activityFeed||e.activityFeed||[]:(t.activityFeed||[]).filter(e=>e.type===`agent`),thinkingText:t.streaming?t.thinkingText??e.thinkingText??``:``,...t.streaming?{}:{hadQueuedInput:!1}}}function As(e,{catalogStreaming:t,localStreamOwned:n}){return!e?.loaded||e.loading||e.streaming||e.recovering||n?!1:t||!e.messages?.length}function js({sessionStates:e,sessionStatesRef:t,localStreamSessionsRef:n,streamGenerationRef:r,updateSessionState:i,updateSessions:a,pollOnly:o}){let s=(0,Q.useRef)(new Set),c=(0,Q.useRef)(new Map),l=(0,Q.useRef)({timer:null,tick:0,activeSessions:new Set}),u=(0,Q.useRef)({timer:null,ids:new Set}),d=(0,Q.useCallback)(async(e,{force:o=!1}={})=>{if(!e||!o&&(n.current.has(e)||s.current.has(e)))return;let l=(c.current.get(e)||0)+1;c.current.set(e,l);let u=()=>c.current.get(e)!==l;s.current.add(e);let d=t.current[e]?.runtimeSelectionRevision||0;try{let s=await X.getLiveSession(e);if(u()||!o&&n.current.has(e))return;if(o&&n.current.has(e)){let t=r.current.get(e)||0;r.current.set(e,t+1),n.current.delete(e)}Ro(e,s),i(e,e=>ks(e,s,void 0,d)),a(n=>n.map(n=>n.id===e?{...n,streaming:s.streaming,model:t.current[e]?.model||s.model||n.model,cwd:s.cwd||n.cwd,permissionMode:s.permissionMode||n.permissionMode,executionMode:s.executionMode||n.executionMode,runMode:s.runMode||n.runMode,goal:s.goal??n.goal??null,team:bs(s,n.team),plan:Ln(s,n.plan??null)}:n))}catch(t){!u()&&!n.current.has(e)&&i(e,{recovering:!1,loading:!1,error:Z(t)})}finally{u()||s.current.delete(e)}},[n,t,r,i,a]),f=(0,Q.useCallback)(async(e,{force:r=!1,limit:o=40}={})=>{if(!e)return;let s=t.current[e];if(r&&s?.historyWindow){if(i(e,Ds),n.current.has(e))return;if(s.streaming||s.recovering){await d(e,{force:r});return}}if(s?.recovering){await d(e,{force:r});return}if(!(!r&&(s?.loading||s?.streaming||s?.loaded&&s.messages?.length&&(s.pageSize||0)>=o))){i(e,{loading:!0});try{let r=await X.getMessages(e,{limit:o}),s=r.streaming===!0&&!n.current.has(e),c=!1;i(e,t=>t.streaming&&!t.loaded&&!t.messages?.length&&!n.current.has(e)?(c=!0,{...t,loading:!1,pageSize:Math.max(t.pageSize||0,o)}):t.streaming?{...t,loaded:!0,loading:!1,pageSize:Math.max(t.pageSize||0,o)}:(s&&(c=!0),{...t,...ws(t,r),...s?{streaming:!0,recovering:!0}:{},model:t.model||r.model||void 0,contextUsage:r.contextUsage??t.contextUsage??null,sessionUsage:r.sessionUsage??t.sessionUsage??null,workspace:ys(r.workspace),loaded:!0,loading:!1,pageSize:Math.max(t.pageSize||0,o),error:``,olderError:``})),c&&d(e);let l=t.current[e]?.model||(typeof r.model==`string`?r.model:``);l&&a(t=>t.map(t=>t.id===e&&t.model!==l?{...t,model:l}:t))}catch(t){i(e,{loading:!1,error:Z(t)})}}},[n,t,d,i,a]),p=(0,Q.useCallback)(async e=>{let n=t.current[e],r=n?.historyWindow?{...n,...n.historyWindow}:n;if(!e||!r?.hasOlder||!r.olderCursor||n.loadingOlder)return!1;let a=n.historyWindow??null;i(e,{loadingOlder:!0,olderError:``});try{let t=await X.getMessages(e,{limit:40,before:r.olderCursor});return i(e,e=>{let n=e.historyWindow||e;return(e.historyWindow??null)!==a||n.olderCursor!==r.olderCursor?{...e,loadingOlder:!1}:{...Es(e,t),loadingOlder:!1,olderError:``}}),t.messages.length>0}catch(t){return i(e,{loadingOlder:!1,olderError:Z(t)}),!1}},[t,i]),m=(0,Q.useCallback)(()=>{l.current.timer&&window.clearInterval(l.current.timer),l.current.timer=null,l.current.activeSessions.clear()},[]),h=(0,Q.useCallback)(()=>{l.current.timer||!l.current.activeSessions.size||(l.current.timer=window.setInterval(()=>{if(typeof document<`u`&&document.hidden)return;l.current.tick+=1;let e=l.current.tick,r=Array.from(l.current.activeSessions).map(async r=>{let i=t.current[r];if(!ps(i,{localStreamOwned:n.current.has(r)})){l.current.activeSessions.delete(r);return}e%ms(i)===0&&await d(r)});Promise.allSettled(r).then(()=>{l.current.activeSessions.size||m()})},2e3))},[n,t,m,d]);return(0,Q.useEffect)(()=>{let t=new Set(Object.keys(e));for(let e of l.current.activeSessions)t.has(e)||l.current.activeSessions.delete(e);let r=[];for(let[t,i]of Object.entries(e)){let e=(o===void 0||t===o)&&ps(i,{localStreamOwned:n.current.has(t)});e&&!l.current.activeSessions.has(t)&&r.push(t),e?l.current.activeSessions.add(t):l.current.activeSessions.delete(t)}if(l.current.activeSessions.size?h():m(),!r.length)return;let i=u.current;for(let e of r)i.ids.add(e);i.timer===null&&(i.timer=window.setTimeout(()=>{i.timer=null;let e=Array.from(i.ids);if(i.ids.clear(),!(typeof document<`u`&&document.hidden))for(let t of e)l.current.activeSessions.has(t)&&d(t)},0))},[h,n,o,e,m,d]),(0,Q.useEffect)(()=>{let e=u.current;return()=>{m(),e.timer!==null&&window.clearTimeout(e.timer),e.timer=null,e.ids.clear()}},[m]),{syncLiveSession:d,loadSessionMessages:f,loadOlderMessages:p,liveSyncInFlightRef:s}}function Ms(e,t){let n=null,r=!1,i=typeof document<`u`,a=()=>!i||document.visibilityState===`visible`,o=()=>{r&&=(document.removeEventListener(`visibilitychange`,c),!1)},s=()=>{n=setTimeout(()=>{n=null,e()},t)},c=()=>{!a()||n!=null||(o(),s())},l=()=>{!i||r||(document.addEventListener(`visibilitychange`,c),r=!0)};return{schedule(){n!=null||r||(a()?s():l())},flushNow(){n!=null&&(clearTimeout(n),n=null),o(),e()},cancel(){n!=null&&clearTimeout(n),n=null,o()},get active(){return n!=null||r}}}function Ns(e,{intervalMs:t=48}={}){let n=null,r=null,i=Ms(()=>{if(n==null)return;let t=n,i=r;n=null,r=null,e(t,i)},t);return{push(e,t=new Date().toISOString()){n=e,r=t,i.schedule()},flush(){i.flushNow()},cancel(){i.cancel(),n=null,r=null}}}function Ps(e,{intervalMs:t=80}={}){let n=new Map,r=null,i=Ms(()=>{if(!n.size)return;let t=n,i=r;n=new Map,r=null,e(t,i)},t);return{push(e,t,a=new Date().toISOString()){e&&(n.set(e,{...n.get(e)||{},...t}),r=a,i.schedule())},flush(){i.flushNow()},cancel(){i.cancel(),n=new Map,r=null}}}function Fs(e){return e>=55296&&e<=56319}function Is(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e.charCodeAt(r)===t.charCodeAt(r);)r+=1;return r>0&&Fs(e.charCodeAt(r-1))?r-1:r}var Ls=50;function Rs(e,{minCharsPerSecond:t=36,maxCharsPerSecond:n=1200,catchUpRemaining:r=160,requestFrame:i,cancelFrame:a,isCurrent:o=()=>!0,now:s=()=>typeof performance<`u`&&performance.now?performance.now():Date.now()}={}){let c=!i&&typeof globalThis.requestAnimationFrame==`function`&&typeof globalThis.cancelAnimationFrame==`function`,l=i||(c?globalThis.requestAnimationFrame.bind(globalThis):e=>setTimeout(()=>e(s()),Math.ceil(Ls))),u=a||(c?globalThis.cancelAnimationFrame.bind(globalThis):clearTimeout),d=typeof document<`u`?document:null,f=()=>!d||d.visibilityState===`visible`,p=``,m=``,h=null,g=null,_=0,v=null,y=0,b=!1,x=new Set,S=e=>{let t=[...x];x.clear();for(let n of t)n(e)},C=()=>{m.length,e(m,h)},w=()=>{b=!0,g!=null&&u(g),d?.removeEventListener(`visibilitychange`,O),g=null,y=0,S(!1)},T=()=>{if(!b){if(!o()){w();return}g!=null&&u(g),g=null,y=0,m=p,v=s(),C(),m===p&&S(!0)}},E=e=>{if(g=null,b)return;if(!o()){w();return}if(!f()){x.size&&T();return}if(p===m){S(!0);return}let i=e-_;if(i+.001<Ls||v!=null&&e-v+.001<Ls){g=l(E);return}_=e;let a=m;p.startsWith(m)||(m=p.slice(0,Is(m,p)),y=0);let s=p.length-m.length;if(s>=480)m=p,y=0;else{let e=Math.max(0,Math.min(n,t+s*(s>=r?10:4))),a=y+e*Math.min(.08,Math.max(0,i/1e3)),o=Math.floor(a+1e-9);y=Math.max(0,a-o);let c=m.length;for(let e=0;e<o&&c<p.length;e+=1){let e=p.codePointAt(c)??0;if(Fs(e)&&c+1===p.length&&!x.size)break;c+=e>65535?2:1}m=p.slice(0,c)}m!==a&&(v=e,C()),m===p&&S(!0);let c=!x.size&&m.length+1===p.length&&Fs(p.charCodeAt(m.length));!b&&g==null&&m!==p&&!c&&f()?g=l(E):g??(y=0)},D=()=>{b||g!=null||!f()||p===m||(_=s(),g=l(E))},O=()=>{f()?D():x.size?T():(g!=null&&u(g),g=null,y=0)};return d?.addEventListener(`visibilitychange`,O),{setTarget(e,t=new Date().toISOString()){b||(p=String(e||``),h=t,D())},drain(){return b||!o()?(w(),Promise.resolve(!1)):m===p?Promise.resolve(!0):new Promise(e=>{x.add(e),f()?D():T()})},flush:T,cancel:w,getShown:()=>m,getTarget:()=>p}}var zs=new Set(`contacts.search,camera.capture,location.current,device.info,device.capabilities,device.battery,device.storage,device.memory,device.network,device.display,device.locale,device.status,device.clipboard.get,device.clipboard.set,device.vibrate,device.flashlight,device.notify,photos.list,photos.create_album,photos.add_to_album,photos.delete,apps.open_url,apps.open_map,apps.open_system_settings,apps.open_dialer,apps.compose_sms,apps.open_app,apps.share_text`.split(`,`)),Bs=new Map,Vs=[];function Hs(e,t){let n=window.__TAURI__?.core?.invoke??window.__TAURI_INTERNALS__?.invoke;return n?n(e,t):Promise.reject(Error(`native bridge unavailable`))}async function Us(e,t){let n=String(t.id||``),r=String(t.operation||``);if(!n||!zs.has(r))return;let i=Date.parse(String(t.expiresAt||``));if(Number.isFinite(i)&&i<=Date.now()){await X.resolveMobileOperation(e,n,{ok:!1,error:`移动设备操作请求已过期。`});return}try{let i=await Hs(`mobile_execute_device_operation`,{request:{id:n,operation:r,parameters:t.parameters&&typeof t.parameters==`object`?t.parameters:void 0}});await X.resolveMobileOperation(e,n,{ok:!0,result:i})}catch(t){await X.resolveMobileOperation(e,n,{ok:!1,error:t instanceof Error?t.message:String(t)})}finally{Vs.push(n),Vs.length>128&&Vs.splice(0,Vs.length-128)}}function Ws(e){let t=String(e.id||``);!t||Vs.includes(t)||(Vs.push(t),Vs.length>128&&Vs.splice(0,Vs.length-128))}function Gs(e,t){let n=String(t.id||``);if(!n||Vs.includes(n)||Bs.has(n))return;let r=Us(e,t).catch(()=>{}).finally(()=>Bs.delete(n));Bs.set(n,r)}function Ks(e){let t=String(e.path||``).trim().replaceAll(`\\`,`/`).toLowerCase();return t?`path:${t}`:`id:${e.id}`}function qs(e,t){return Object.hasOwn(e,`team`)?e.team??null:t??null}function Js(e,{agentId:t,responseText:n,data:r,finishedAt:i,error:a,preserveDisplayedText:o}){let s=!!a,c=r.lifecycle||e.lifecycle||{},l=ke(e,r);return{...l,streaming:!1,runFinishedAt:i,lastActivityAt:i,...s?{}:{runNotice:``},currentActivity:r.currentActivity?.type===`agent`?r.currentActivity:null,lifecycle:{...c,phase:s?`failed`:`completed`,event:s?`runtime_error`:`runtime_done`,updatedAt:i},sessionTreeRevision:Number(r.sessionTreeRevision??e.sessionTreeRevision??0),activityFeed:(r.activityFeed||[]).filter(e=>e.type===`agent`),goal:s?e.goal:r.goal??e.goal??null,plan:s?e.plan:Ln(r,e.plan),team:qs(r,e.team),agents:r.agents||e.agents||[],contextUsage:r.contextUsage??e.contextUsage??null,sessionUsage:r.sessionUsage??e.sessionUsage??null,compaction:r.compaction??e.compaction??null,approvals:s?[]:r.approvals||[],tools:Vn(r.tools||e.tools,{finishedAt:i,...a?{error:a}:{}}),messages:l.messages.map(e=>e.id===t?{...e,text:o?e.text:typeof r.text==`string`?r.text:n||e.text,streaming:o?e.text!==n:!1,...s?{}:r.turnBoundaryEntryId?{turnBoundaryEntryId:String(r.turnBoundaryEntryId)}:{},...s?{}:r.assets?.length?{attachments:r.assets}:{}}:e)}}function Ys({sessionId:e,agentId:t,sessionStatesRef:n,updateSessionState:r,updateSessions:i,typewriter:a,thinkingScheduler:o,toolScheduler:s,t:c}){let l={responseText:``,responseRenderingStreaming:!0,thinkingText:``,thinkingPrefix:``,queuedDuringRun:!1,pendingInputIds:[]},u=e=>(Array.isArray(e)?e:[]).map(e=>typeof e?.id==`string`?e.id:``).filter(Boolean),d=(i,o)=>{let s=u(i.queuedInputs),c=new Set([...n.current[e]?.withdrawnInputIds||[],...typeof i.removedInputId==`string`?[i.removedInputId]:[]]),d=l.pendingInputIds.filter(e=>!s.includes(e)&&!c.has(e));if(l.pendingInputIds=s,!d.length)return;let f=new Set(u((i.sendNowInputIds||[]).map(e=>({id:e})))),p=l.responseText;l.responseText=``,r(e,e=>De(e,{agentId:t,deliveredIds:d,frozenText:p,interrupted:d.some(e=>f.has(e))})),p&&(a.setTarget(``,o),a.flush())},f=t=>{i(n=>n.map(n=>n.id===e?t(n):n))},p=(r,i)=>{let a=n.current[e]?.messages??[],o=a.findIndex(e=>e.id===t),s=a.slice(0,Math.max(0,o)).filter(e=>e.role===`user`).at(-1)?.text;Lo({sessionId:e,messageId:t,prompt:s,text:l.responseText,runId:l.runId,startedAt:l.startedAt,status:r,error:i})};return{dispatch:(i,m)=>{let h=new Date().toISOString();if(i===`run`)l.runId=typeof m.runId==`string`?m.runId:void 0,p(`started`);else if(i===`resync_required`)p(`recovering`);else if(i===`meta`)l.startedAt=typeof m.startedAt==`string`?m.startedAt:void 0,Array.isArray(m.queuedInputs)&&(l.pendingInputIds=u(m.queuedInputs)),p(`started`),r(e,e=>({...ke(e,m),model:m.model||e.model,thinkingLevel:m.thinkingLevel||e.thinkingLevel,cwd:m.cwd,permissionMode:m.permissionMode,executionMode:m.executionMode,runMode:m.runMode||e.runMode,goal:m.goal??null,plan:Ln(m,e.plan),team:qs(m,e.team),agents:m.agents||e.agents||[],currentActivity:m.currentActivity||e.currentActivity||null,activityFeed:m.activityFeed||e.activityFeed||[],lifecycle:m.lifecycle??e.lifecycle??null,sessionTreeRevision:Number(m.sessionTreeRevision??e.sessionTreeRevision??0),thinkingText:m.thinkingText??e.thinkingText??``,contextUsage:m.contextUsage??e.contextUsage??null,sessionUsage:m.sessionUsage??e.sessionUsage??null,runStartedAt:m.startedAt||e.runStartedAt,lastActivityAt:m.lastActivityAt||h})),(m.model||m.thinkingLevel||m.cwd||m.permissionMode||m.executionMode||m.goal!==void 0||m.team!==void 0||Un(m)!==void 0)&&f(e=>({...e,model:m.model||e.model,thinkingLevel:m.thinkingLevel||e.thinkingLevel,cwd:m.cwd||e.cwd,permissionMode:m.permissionMode||e.permissionMode,executionMode:m.executionMode||e.executionMode,runMode:m.runMode||e.runMode,goal:m.goal??e.goal??null,team:qs(m,e.team),plan:Ln(m,e.plan??null)}));else if(i===`queue_update`)m.queuedInputs?.length&&(l.queuedDuringRun=!0),r(e,e=>ke(e,{...m,queuedInputs:m.queuedInputs||[]})),d(m,h);else if(i===`agent_update`)r(e,e=>{let t=m.currentActivity||(m.agent?{type:`agent`,agent:m.agent,updatedAt:m.agent.lastActivityAt||h}:null);return{...e,team:qs(m,e.team),agents:m.agents||[],currentActivity:e.currentActivity?.type===`tool`?e.currentActivity:t||e.currentActivity,activityFeed:t?zn(e.activityFeed,t):e.activityFeed,lastActivityAt:m.agent?.lastActivityAt||h}}),Object.hasOwn(m,`team`)&&f(e=>({...e,team:qs(m,e.team)}));else if(i===`agent_lifecycle`)r(e,e=>{let t=m.lifecycle||e.lifecycle,n=t?.event===`auto_retry_end`,r=t?.event===`turn_start`&&(e.lifecycle?.phase===`retrying`||e.currentActivity?.type===`retry`);return{...e,lifecycle:t,currentActivity:m.currentActivity||e.currentActivity,lastActivityAt:t?.updatedAt||h,runNotice:n&&t?.retry?.success?``:n&&t?.retry?.message?t.retry.message:r?``:e.runNotice}});else if(i===`session_tree_changed`)r(e,{sessionTreeRevision:Number(m.revision||0),lastActivityAt:h});else if(i===`thinking_level_changed`)r(e,{thinkingLevel:m.level,lastActivityAt:h}),f(e=>({...e,thinkingLevel:m.level}));else if(i===`context_usage`)r(e,{contextUsage:m});else if(i===`session_usage`)r(e,{sessionUsage:m});else if(i===`compaction_start`)s.flush(),r(e,e=>{let t={type:`compaction`,compaction:m,updatedAt:m.startedAt||h};return{...e,compaction:m,currentActivity:t,activityFeed:zn(e.activityFeed,t),lastActivityAt:m.startedAt||h}});else if(i===`compaction_end`)r(e,e=>{let t={type:`model`,stage:`processing_result`,updatedAt:m.finishedAt||h};return{...e,compaction:m,currentActivity:t,activityFeed:zn(e.activityFeed,t),lastActivityAt:m.finishedAt||h}});else if(i===`text_patch`)l.responseRenderingStreaming=!0,l.responseText=E(l.responseText,m),p(`streaming`),a.setTarget(l.responseText,h);else if(i===`text_delta`)l.responseText.length,l.responseRenderingStreaming=!0,l.responseText+=m.delta||``,p(`streaming`),a.setTarget(l.responseText,h);else if(i===`text_end`)l.responseText.length,typeof m.text==`string`&&(l.responseText=m.text),l.responseRenderingStreaming=!1,p(`streaming`),a.setTarget(l.responseText,m.updatedAt||h),r(e,e=>({...e,messages:e.messages.map(e=>e.id===t?{...e,streaming:e.text!==l.responseText}:e)}));else if(i===`thinking_reset`)l.thinkingText=``,l.thinkingPrefix=String(m.thinkingText||``).slice(-6e3),o.cancel(),r(e,{thinkingText:l.thinkingPrefix,currentActivity:{type:`model`,stage:`thinking`,updatedAt:m.updatedAt||h},lastActivityAt:m.updatedAt||h});else if(i===`thinking_patch`){l.thinkingText=E(l.thinkingText,m).slice(-6e3);let e=[l.thinkingPrefix,l.thinkingText].filter(Boolean).join(`
|
|
551
|
+
`;async function _o(e){let t=new Blob([go],{type:`application/javascript`}),n=URL.createObjectURL(t);try{await e.audioWorklet.addModule(n)}finally{URL.revokeObjectURL(n)}}async function vo(e,t){if(y(t),!navigator.mediaDevices?.getUserMedia)throw Error(`当前环境不支持麦克风采集。`);if(!window.AudioContext&&!window.webkitAudioContext)throw Error(`当前环境不支持音频处理。`);let n=await navigator.mediaDevices.getUserMedia({audio:{channelCount:1,echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0},video:!1}),r=null,i=null,a=null,o=null,s=!1,c=null,l=()=>{if(s)return c??Promise.resolve();s=!0,t?.removeEventListener(`abort`,u);for(let e of n.getTracks())e.removeEventListener?.(`ended`,d),e.removeEventListener?.(`mute`,d),e.stop();return c=r?.close().catch(()=>{})??Promise.resolve(),i&&(i.port.onmessage=null,i.port.close()),a?.disconnect(),i?.disconnect(),o?.disconnect(),c},u=()=>{l()},d=()=>{s||(l(),window.dispatchEvent(new Event(`pisper:speech-interrupted`)))},f=()=>{if(y(t),s)throw new DOMException(`Microphone capture was interrupted.`,`AbortError`)};t?.addEventListener(`abort`,u,{once:!0});for(let e of n.getTracks()){if(s)break;e.addEventListener?.(`ended`,d),e.addEventListener?.(`mute`,d),e.readyState===`ended`&&d()}try{f(),r=new(window.AudioContext||window.webkitAudioContext)({latencyHint:`interactive`}),await _o(r),f(),a=r.createMediaStreamSource(n),i=new AudioWorkletNode(r,`pisper-voice-input`,{numberOfInputs:1,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{targetSampleRate:so}}),o=r.createGain(),o.gain.value=0,i.port.onmessage=n=>{!s&&!t?.aborted&&e(new Float32Array(n.data))},a.connect(i),i.connect(o),o.connect(r.destination),await r.resume(),f()}catch(e){throw await l(),e}return{stop:l}}var yo=32,bo=50;function xo(e,t){if(e instanceof DOMException&&e.name===`NotAllowedError`)return`permission`;let n=typeof e==`string`?e:e instanceof Error?e.message:typeof e==`object`&&e&&`message`in e?String(e.message):``;return n.includes(`microphone_permission_denied`)?`permission`:n||t}function So({onInsert:e,onLiveText:t,sessionId:n,disabled:r=!1,shortcutEnabled:i=!1,variant:a=`button`,controlRef:o}){let{t:s}=l(),c=Ka([`asr`]),u=gn(e=>e.bindings.voiceInput),[d,f]=(0,Q.useState)(`idle`),[p,m]=(0,Q.useState)(``),h=(0,Q.useRef)(`idle`),g=e=>{h.current=e,f(e)},_=(0,Q.useRef)(null),v=(0,Q.useRef)(null),y=(0,Q.useRef)(null),b=(0,Q.useRef)(null),x=(0,Q.useRef)(0),S=(0,Q.useRef)(0),C=(0,Q.useRef)(()=>{}),w=(0,Q.useRef)(!1),T=(0,Q.useRef)(null),E=(0,Q.useRef)(null),D=(0,Q.useRef)(()=>{}),O=(0,Q.useRef)(0),k=(0,Q.useRef)(Ra()),A=(0,Q.useRef)(0),[j,M]=(0,Q.useState)([]),N=(0,Q.useRef)([]),P=(0,Q.useRef)(null),F=(0,Q.useRef)(e),I=(0,Q.useRef)(t);F.current=e,I.current=t;let L=()=>{window.clearTimeout(S.current),S.current=0},R=async()=>{L();let e=y.current;y.current=null,e?.abort(),b.current?.(),b.current=null,P.current?.dispose(),P.current=null;let t=v.current;v.current=null;let n=_.current;_.current=null,await Promise.allSettled([t?.stop(),n?.dispose()])},z=e=>{console.warn(`[voice-input]`,e),m(e),g(`error`),window.clearTimeout(O.current),O.current=window.setTimeout(()=>{h.current===`error`&&(m(``),g(`idle`))},4e3)},B=()=>{L(),w.current=!1,g(`idle`),m(``)},V=()=>{T.current=null,E.current=null,x.current+=1,R(),I.current?.(null),B()};D.current=V,(0,Q.useEffect)(()=>{let e=()=>{(E.current!==x.current||T.current===x.current)&&D.current()},t=()=>{document.visibilityState===`hidden`&&e()},n=()=>D.current();return window.addEventListener(`blur`,e),window.addEventListener(`pisper:speech-interrupted`,n),document.addEventListener(`visibilitychange`,t),()=>{window.removeEventListener(`blur`,e),window.removeEventListener(`pisper:speech-interrupted`,n),document.removeEventListener(`visibilitychange`,t),window.clearTimeout(O.current),e()}},[n,i,r]),(0,Q.useEffect)(()=>{if(d!==`recording`){M([]),N.current=[];return}let e=()=>{let e=performance.now()/1e3,t=A.current,n=N.current,r=[];for(let i=0;i<yo;i+=1){let a=i/31*2-1,o=Math.cos(a*Math.PI/2)**1.3,s=.1+.06*Math.sin(e*2.2+i*.55)+.04*Math.sin(e*3.7+i*.21),c=.75+.5*Math.abs(Math.sin(e*9+i*1.7)),l=Math.min(1,Math.max(.05,s+t*o*c*1.15)),u=n[i]??l,d=l>u?.55:.28;r.push(u+(l-u)*d)}N.current=r,M(r)};e();let t=window.setInterval(e,bo);return()=>window.clearInterval(t)},[d]);let H=()=>!r&&(h.current===`idle`||h.current===`error`),U=async()=>{if(!H())return;let e=++x.current,t=new AbortController;y.current=t,w.current=!1,g(`requesting`),m(``),k.current.reset();let r=ho({chatSessionId:n});_.current=r,b.current=r.onPartial(e=>{_.current===r&&I.current?.(e)});let i=null,a=async t=>{if(i?.dispose(),i=null,e!==x.current)return;if(t instanceof DOMException&&t.name===`AbortError`){let e=++x.current;if(await R(),e!==x.current)return;B();return}let n=++x.current;if(await R(),n!==x.current)return;let r=xo(t,s(`chat:voiceInput.failed`));z(r===`permission`?s(`chat:voiceInput.permissionDenied`):r)};try{window.__PISPER_MOBILE_APP__&&(E.current=e);try{await uo()}finally{E.current===e&&(E.current=null)}if(e!==x.current)return;if(window.__PISPER_MOBILE_APP__&&document.visibilityState===`hidden`){V();return}if(await c.ensureReady(t.signal),e!==x.current)return;if(r.start().then(()=>{},()=>a(Error(s(`chat:voiceInput.failed`)))),i=await Wa(),e!==x.current){i.dispose();return}P.current=i;let n=i,o=await vo(t=>{if(e!==x.current)return;A.current=k.current.push(La(t));let i=n.acceptPcm(t);(r.acceptPcm(t)||i)&&C.current()},t.signal);if(e!==x.current){await o.stop();return}v.current=o,g(`recording`),window.__PISPER_MOBILE_APP__&&(S.current=window.setTimeout(()=>C.current(),6e4))}catch(e){await a(e)}},W=async()=>{if(h.current!==`recording`||w.current)return;T.current=null,w.current=!0,L();let e=++x.current;g(`transcribing`);let t=y.current;y.current=null,t?.abort();let n=v.current;v.current=null;let r=P.current;P.current=null;let i=_.current;try{if(await n?.stop(),e!==x.current)return;if(r&&!r.hasSpeech){if(r.dispose(),I.current?.(null),await R(),e!==x.current)return;B();return}r?.dispose();let t=await i?.finish();if(e!==x.current)return;if(!t)throw Error(s(`chat:voiceInput.empty`));if(F.current(t),await R(),e!==x.current)return;B()}catch(t){if(e!==x.current||(await R(),e!==x.current))return;I.current?.(null);let n=xo(t,s(`chat:voiceInput.failed`));z(n===`permission`?s(`chat:voiceInput.permissionDenied`):n),w.current=!1}};C.current=()=>void W(),Ia({enabled:i&&!r,binding:u,onStart:()=>H()?(U(),T.current=x.current,!0):!1,onRelease:()=>{T.current===x.current&&(v.current?W():V())},onCancel:()=>{T.current===x.current&&V()}});let ee=d===`recording`?s(`chat:voiceInput.stop`):d===`requesting`?s(`chat:voiceInput.close`):d===`error`?p:s(`chat:voiceInput.open`),te=u&&d!==`error`?`${ee} (${xn(u)})`:ee,ne=d===`recording`?()=>void W():d===`requesting`?()=>V():()=>void U(),re=(0,Q.useRef)(ne);re.current=ne;let ie=!r&&d!==`transcribing`;(0,Q.useEffect)(()=>{if(o)return o.current=ie?()=>re.current():null,()=>{o.current=null}},[o,ie]);let ae=a===`menu`&&d===`idle`;return(0,$.jsxs)(`div`,{className:`relative flex flex-none items-center`,"data-voice-input":d,children:[d===`recording`&&(0,zi.createPortal)((0,$.jsx)(`div`,{"aria-hidden":`true`,className:`voice-capsule-pop pointer-events-none fixed bottom-4 left-1/2 z-[80] flex h-10 -translate-x-1/2 items-center gap-[3px] rounded-full bg-ink px-4 shadow-float`,children:j.map((e,t)=>(0,$.jsx)(`span`,{className:`w-[3px] rounded-full bg-on-ink`,style:{height:`${(3+e*19).toFixed(1)}px`,opacity:.55+e*.45,transition:`height 70ms linear`}},t))}),document.body),d===`error`&&(0,zi.createPortal)((0,$.jsxs)(`button`,{type:`button`,className:`voice-capsule-pop fixed bottom-4 left-1/2 z-[80] flex h-9 max-w-[min(480px,calc(100vw-32px))] -translate-x-1/2 cursor-pointer items-center gap-2 rounded-full border border-danger-border bg-solid px-4 text-xs text-danger shadow-float max-[650px]:h-11`,onClick:()=>{window.clearTimeout(O.current),m(``),g(`idle`)},children:[(0,$.jsx)(ri,{size:13,className:`flex-none`}),(0,$.jsx)(`span`,{className:`truncate`,children:p})]}),document.body),(0,$.jsxs)(`button`,{type:`button`,hidden:ae,className:`relative grid size-8 min-w-8 cursor-pointer place-items-center rounded-sm border transition-colors disabled:cursor-not-allowed disabled:opacity-45 max-[650px]:size-9 max-[650px]:min-w-9 min-[651px]:pointer-coarse:size-11 min-[651px]:pointer-coarse:min-w-11 ${me} ${d===`recording`?`border-danger bg-danger-soft text-danger`:d===`transcribing`||d===`requesting`?`border-transparent bg-star-soft text-accent-fg`:d===`error`?`border-transparent bg-danger-soft text-danger`:`border-transparent text-content-muted hover:bg-surface-hover hover:text-content`}`,title:te,"aria-label":s(d===`recording`?`chat:voiceInput.stop`:`chat:voiceInput.open`),"aria-pressed":d===`recording`,disabled:r||d===`transcribing`,onClick:ne,children:[d===`recording`&&(0,$.jsx)(`span`,{"aria-hidden":`true`,className:`absolute inset-0 animate-ping rounded-sm bg-danger opacity-25`}),d===`recording`?(0,$.jsx)(ri,{size:17,className:G}):d===`transcribing`||d===`requesting`?(0,$.jsx)(it,{className:`animate-spin ${G}`,size:16}):d===`error`?(0,$.jsx)(ri,{size:17,className:G}):(0,$.jsx)(ii,{size:17,className:G})]}),(0,$.jsx)(oo,{manager:c,onClose:()=>{}})]})}var Co={idle:{amp:.14,freq:1.7,speed:.22,spike:0,rot:.22,dim:.8,behavior:`calm`},requesting:{amp:.08,freq:1.6,speed:.3,spike:0,rot:.4,dim:.5,behavior:`calm`},listening:{amp:.15,freq:2,speed:.55,spike:.55,rot:.4,dim:1,behavior:`reactive`},transcribing:{amp:.08,freq:1.8,speed:1,spike:0,rot:1.5,dim:.95,behavior:`converge`},thinking:{amp:.2,freq:2.3,speed:.8,spike:0,rot:.85,dim:1,behavior:`swirl`},speaking:{amp:.13,freq:1.9,speed:.5,spike:.1,rot:.35,dim:1,behavior:`beat`},error:{amp:.12,freq:2.2,speed:1.2,spike:0,rot:.1,dim:.9,behavior:`jitter`}},wo=64,To=96,Eo=2.6,Do=Math.PI*2,Oo={dark:{base:[223,233,255],cyan:[89,230,255],magenta:[255,95,210],haloInner:[70,110,170],haloMid:[50,80,140],haloAlpha:.1,composite:`lighter`,alphaBase:.1,alphaFront:.68},light:{base:[34,44,76],cyan:[6,132,180],magenta:[176,48,150],haloInner:[110,140,210],haloMid:[130,160,220],haloAlpha:.16,composite:`source-over`,alphaBase:.18,alphaFront:.85}};function ko(e,t,n){let r=Math.sin(e*127.1+t*311.7+n*74.7)*43758.5453123;return r-Math.floor(r)}function Ao(e){return e*e*(3-2*e)}function jo(e,t,n){let r=Math.floor(e),i=Math.floor(t),a=Math.floor(n),o=Ao(e-r),s=Ao(t-i),c=Ao(n-a),l=0;for(let e=0;e<=1;e+=1)for(let t=0;t<=1;t+=1)for(let n=0;n<=1;n+=1)l+=(e?o:1-o)*(t?s:1-s)*(n?c:1-c)*ko(r+e,i+t,a+n);return l}function Mo(e){return 1+2.70158*(e-1)**3+1.70158*(e-1)**2}function No(e){let t=e*.9%1;return Math.exp(-(((t-.12)*9)**2))+.45*Math.exp(-(((t-.34)*9)**2))}function Po({stage:e,level:t,size:n=380,dark:r=!0}){let i=(0,Q.useRef)(null),a=(0,Q.useRef)(e),o=(0,Q.useRef)(t),s=(0,Q.useRef)(r);return a.current=e,o.current=t,s.current=r,(0,Q.useEffect)(()=>{let e=i.current;if(!e)return;let t=e.getContext(`2d`);if(!t)return;let r=Math.min(window.devicePixelRatio||1,2);e.width=n*r,e.height=n*r,t.scale(r,r);let c=new Float32Array(wo),l=new Float32Array(wo);for(let e=0;e<wo;e+=1){let t=-Math.PI/2+(e+.5)/wo*Math.PI;c[e]=Math.sin(t),l[e]=Math.cos(t)}let u=new Float32Array(To),d=new Float32Array(To);for(let e=0;e<To;e+=1){let t=e/To*Do;u[e]=Math.cos(t),d[e]=Math.sin(t)}let f=n/2,p=n*.31,m=window.matchMedia(`(prefers-reduced-motion: reduce)`).matches,h=0,g=performance.now(),_=g,v=0,y=0,b={...Co[a.current]},x=0,S=0,C=0,w=e=>{let r=Math.min((e-g)/1e3,.05);g=e;let i=Co[a.current],T=Math.min(1,r*5);b={...i,amp:b.amp+(i.amp-b.amp)*T,freq:b.freq+(i.freq-b.freq)*T,speed:b.speed+(i.speed-b.speed)*T,spike:b.spike+(i.spike-b.spike)*T,rot:b.rot+(i.rot-b.rot)*T,dim:b.dim+(i.dim-b.dim)*T};let E=m?.35:1;v+=r*E,y+=b.rot*r*E,x+=(o.current-x)*Math.min(1,r*14);let D=Math.max(0,x-S-.02);S=x,C=Math.min(.6,C*.02**r+D*2.4);let O=x;b.behavior===`beat`?O=Math.max(.08,.4+.28*Math.abs(Math.sin(v*5.2))*Math.sin(v*1.6)+.12*Math.sin(v*9.1)):b.behavior===`converge`?O=.18:b.behavior===`jitter`?O=.3+.2*Math.sin(v*17):b.behavior!==`reactive`&&(O=.1+.05*Math.sin(v*1.3));let k=Mo(Math.min(1,Math.max(0,(e-_)/900))),A=b.behavior===`beat`?O:No(v)*.5+O*.5,j=k*(1+A*.04+C*.1);b.behavior===`converge`&&(j*=.9+.1*Math.sin(v*4.2)),t.clearRect(0,0,n,n);let M=Oo[s.current?`dark`:`light`],N=t.createRadialGradient(f,f,0,f,f,p*1.7);N.addColorStop(0,`rgba(${M.haloInner[0]},${M.haloInner[1]},${M.haloInner[2]},${(M.haloAlpha*b.dim).toFixed(3)})`),N.addColorStop(.6,`rgba(${M.haloMid[0]},${M.haloMid[1]},${M.haloMid[2]},${(M.haloAlpha*.5*b.dim).toFixed(3)})`),N.addColorStop(1,`rgba(0,0,0,0)`),t.fillStyle=N,t.fillRect(0,0,n,n);let P=Math.sin(y),F=Math.cos(y),I=.38,L=Math.sin(I),R=Math.cos(I),z=v*b.speed,B=b.freq,V=b.amp*j,H=b.spike*(O+C),U=p*j,W=Math.floor(v*15),ee=b.dim*(.72+.5*A)+C*.3;t.globalCompositeOperation=M.composite;for(let e=0;e<wo;e+=1){let n=c[e],r=l[e];for(let i=0;i<To;i+=1){let a=r*u[i],o=n,s=r*d[i],c=jo(a*B+z,o*B+z*.7,s*B)-.5,l=1+c*2*V;b.behavior===`reactive`?l+=Math.max(c,0)**2*1.7*H:b.behavior===`swirl`?l+=.03*Math.sin(9*a+v*4.6):b.behavior===`jitter`&&(l+=.02*(ko(e*To+i,W,3)-.5));let p=a*l,m=o*l,h=s*l,g=p*F-h*P,_=p*P+h*F,y=m*R-_*L,x=m*L+_*R,S=Eo/(Eo-x),C=f+g*S*U,w=f+y*S*U,T=(x+1)/2,E=jo(a*1.25+31,o*1.25+z*.12,s*1.25-17),D=M.base;E>.62?D=M.magenta:E<.38&&(D=M.cyan);let O=(M.alphaBase+M.alphaFront*T*T)*ee;if(O<.015)continue;let k=(1+1.4*T+H*.4)*(.55+.45*S);t.fillStyle=`rgba(${D[0]},${D[1]},${D[2]},${O.toFixed(3)})`,t.fillRect(C,w,k,k)}}t.globalCompositeOperation=`source-over`,h=requestAnimationFrame(w)};return h=requestAnimationFrame(w),()=>cancelAnimationFrame(h)},[n]),(0,$.jsx)(`canvas`,{ref:i,className:`pointer-events-none block`,style:{width:n,height:n},"aria-hidden":`true`})}var Fo=new Map;function Io(e,t){let n=Fo.get(e)??new Set;return n.add(t),Fo.set(e,n),()=>{n.delete(t),n.size||Fo.delete(e)}}function Lo(e){for(let t of Fo.get(e.sessionId)??[])t(e)}function Ro(e,t){let n=t.messages.length-1;for(;n>=0&&t.messages[n].role!==`user`;)--n;let r=t.messages.slice(n+1).filter(e=>e.role===`agent`||e.role===`assistant`),i=r.find(e=>e.streaming)??r.at(-1);Lo({sessionId:e,messageId:i?.id??``,prompt:t.messages[n]?.text,startedAt:t.startedAt??void 0,source:`snapshot`,users:t.messages.filter(e=>e.role===`user`),text:i?.text??``,status:t.error||i?.error?`failed`:t.streaming?i?`streaming`:`started`:`completed`,error:t.error||i?.error})}function zo(e){let t=``,n=0,r=!1,i,a,o=()=>{a?.(),a=void 0},s=()=>{i=b(e),o()};return e.addEventListener(`abort`,s,{once:!0}),e.aborted&&s(),{get text(){return t},update(e){if(!(r||i)){if(e.length>32e3)throw Error(`Speech text exceeds the supported limit.`);if(!e.startsWith(t))throw Error(`The streamed speech response was rewritten.`);t=e,o()}},finish(e){r&&e===void 0||(r=!0,e!==void 0&&(i=e),o())},async*[Symbol.asyncIterator](){try{for(;;){if(y(e),i)throw i;if(n<t.length){let e=t.slice(n);n=t.length,yield e}else if(r)return;else await new Promise(e=>{a=e})}}finally{e.removeEventListener(`abort`,s),r=!0,o()}}}}function Bo(e){let{t}=l(),n=(0,Q.useRef)({...e,t});n.current={...e,t};let[r,i]=(0,Q.useState)(`idle`),[a,o]=(0,Q.useState)(0),[s,c]=(0,Q.useState)(``),[u,d]=(0,Q.useState)([]),[f,p]=(0,Q.useState)(``),[m,h]=(0,Q.useState)(!1),[g,_]=(0,Q.useState)(0),v=(0,Q.useRef)(`idle`),b=(0,Q.useRef)(0),x=(0,Q.useRef)(null),S=(0,Q.useRef)(Promise.resolve()),C=(0,Q.useRef)(!1),w=(0,Q.useRef)(null),T=(0,Q.useRef)(!1),E=(0,Q.useRef)(!1),D=(0,Q.useRef)(!1),O=(0,Q.useRef)({start:async()=>{},commit:async()=>{},stop:()=>{}}),k=(0,Q.useCallback)(e=>{v.current=e,i(e)},[]),A=e=>T.current&&n.current.open&&e.sessionId===n.current.sessionId&&x.current===e&&b.current===e.generation&&!e.controller.signal.aborted,j=()=>!!(n.current.streaming||n.current.messages.some(e=>e.streaming));function M(){let e=w.current;w.current=null,e?.controller.abort()}function N(){if(w.current)return w.current.preparing;let e=new AbortController,t=n.current.sessionId,r=(async()=>{C.current||=(await n.current.ensureReady?.(e.signal),y(e.signal),!0);let{hotwords:r}=await qr(t,e.signal);await Wr({kinds:[`asr`,`tts`],hotwords:r},e.signal),y(e.signal)})().catch(t=>{throw w.current?.controller===e&&(w.current=null),e.abort(),t});return w.current={controller:e,preparing:r},r}function P(e){window.clearTimeout(e.limitTimer),e.limitTimer=void 0,e.microphone.abort(),e.endpoint?.dispose(),e.endpoint=void 0;let t=e.capture;return e.capture=void 0,t&&(e.captureStopping=t.stop()),e.captureStopping??Promise.resolve()}function F(e){if(e.cleanup)return e.cleanup;e.controller.abort(),e.unsubscribe?.(),e.unsubscribe=void 0,e.responseSubscription?.(),e.responseSubscription=void 0,e.checkOwnership=void 0;let t=P(e),n=e.recognizer;return e.recognizer=void 0,e.cleanup=Promise.allSettled([t,e.capturePending,e.recognizerDisposing,e.playback,n?.dispose()]).then(()=>{}),e.cleanup}function I(){b.current+=1;let e=x.current;if(x.current=null,!e)return;let t=Promise.resolve(),r=n.current.messages.filter(t=>t.role===`user`&&!e.baseline?.has(t.id)),i=n.current.sessionId===e.sessionId&&(r.length>1||r.length===1&&r[0].text?.trim()!==e.prompt);if(e.ownsRun&&!i){e.ownsRun=!1;try{t=Promise.resolve(e.abortRun?.()).catch(()=>{})}catch{}}S.current=Promise.allSettled([S.current,F(e),t]).then(()=>{})}function L(){D.current=!1,I(),k(`idle`),c(``),o(0),d(e=>e.filter(e=>!e.pending))}function R(e,t){if(!A(e))return;let r=t instanceof Error?t.message:typeof t==`string`?t:t&&typeof t==`object`&&`message`in t?t.message:void 0,i=typeof r==`string`&&r.trim()?r:n.current.t(`chat:voiceMode.failed`),a=t instanceof DOMException&&t.name===`NotAllowedError`||i.includes(`microphone_permission_denied`)?n.current.t(`chat:voiceInput.permissionDenied`):i;L(),p(a),k(`error`),n.current.notifyError?.(a)}function z(e){return new Promise(t=>{let n=e.controller.signal,r=()=>{window.clearTimeout(i),n.removeEventListener(`abort`,r),t()},i=window.setTimeout(r,50);n.addEventListener(`abort`,r,{once:!0}),n.aborted&&r()})}async function B(e,t,r){let i=e.controller.signal,a=zo(i),o,s,c,l=!1,u=!1,f=!1,p=!1,m=!1,h=1/0,g=n=>{let r=n.filter(e=>e.role===`user`&&!t.has(e.id));return r.length>1||r.length===1&&r[0].text?.trim()!==e.prompt};e.checkOwnership=()=>{A(e)&&g(n.current.messages)&&(e.ownsRun=!1,R(e,Error(n.current.t(`chat:voiceMode.failed`))))};let _=e=>{a.update(e),d(t=>t.map(t=>t.id===r?{...t,text:e,pending:!e.trim()}:t))};e.responseSubscription=Io(e.sessionId,r=>{if(!(!A(e)||r.source!==`snapshot`&&t.has(r.messageId)))try{let t=r.source===`snapshot`,i=!!(c&&r.startedAt===c);if(r.users&&g(r.users)||r.prompt!==void 0&&r.prompt.trim()!==e.prompt||s&&r.runId&&s!==r.runId||c&&r.startedAt&&c!==r.startedAt||t&&!i&&!(p&&!r.startedAt&&r.status===`completed`)||!t&&o&&o!==r.messageId)throw e.ownsRun=!1,Error(n.current.t(`chat:voiceMode.failed`));if(p&&t)return;if(s||=r.runId,c||=r.startedAt,r.messageId&&(o=r.messageId),r.status===`recovering`){l=!0;return}if(t&&(l=!0,u=r.status===`streaming`||r.status===`started`),r.status===`started`)return;if(f=!0,r.status===`failed`)throw e.ownsRun=!1,Error(r.error||n.current.t(`chat:voiceMode.failed`));_(r.text),r.status===`completed`&&(p=!0,e.ownsRun=!1,a.finish())}catch(t){a.finish(t),R(e,t)}});let v=Promise.resolve().then(()=>(y(i),n.current.sendPrompt(e.prompt,[],!1,!1,null))).catch(t=>{throw e.ownsRun=!1,a.finish(t),t}).finally(()=>{!f&&!s&&!c&&(e.ownsRun=!1),m=!0,h=Date.now()+15e3}),b=async()=>{for(;A(e);){if(await z(e),!A(e))return;let r=n.current.messages.filter(e=>!t.has(e.id)),i=r.filter(e=>e.role===`user`);if(i.length>1||i.length===1&&i[0].text?.trim()!==e.prompt)throw Error(n.current.t(`chat:voiceMode.failed`));let s=r.filter(e=>e.role===`assistant`||e.role===`agent`),c=s.find(e=>e.error);if(c)throw Error(String(c.error));if(p&&m&&!j())return;let d=s.at(-1);if(!l&&d?.text&&(!f||m&&!j())){if(o&&o!==d.id)throw Error(n.current.t(`chat:voiceMode.failed`));o=d.id,_(d.text)}if(!l&&m&&!j()&&d?.text?.trim()){e.ownsRun=!1,a.finish();return}if(m&&(j()||u)&&(h=Date.now()+15e3),Date.now()>=h)throw Error(n.current.t(`chat:voiceMode.emptyReply`))}};try{e.playback=Promise.resolve().then(()=>n.current.speakText(a,i,()=>{A(e)&&k(`speaking`)})),await Promise.all([v,b(),e.playback])}catch(e){throw a.finish(e),e}finally{e.responseSubscription?.(),e.responseSubscription=void 0,e.checkOwnership=void 0,a.finish()}}async function V(){let e=x.current;if(!e||!A(e)||e.committed||v.current!==`listening`)return;e.committed=!0;let t=e.endpoint?.hasSpeech;k(`transcribing`),o(0);try{if(await P(e),!A(e))return;if(!t){L();return}let r=(await e.recognizer?.finish())?.trim();if(!A(e))return;e.unsubscribe?.(),e.unsubscribe=void 0;let i=e.recognizer;if(e.recognizer=void 0,e.recognizerDisposing=i?.dispose(),await e.recognizerDisposing,!A(e))return;if(c(``),!r)throw Error(n.current.t(`chat:voiceMode.emptyReply`));if(j()){L();return}let a=new Set(n.current.messages.map(e=>e.id));e.baseline=a,e.prompt=r;let o=`voice-agent-${e.generation}`;if(d(t=>[...t.slice(-4),{id:`voice-user-${e.generation}`,role:`user`,text:r},{id:o,role:`agent`,text:``,pending:!0}]),k(`thinking`),e.abortRun=n.current.onAbort,e.ownsRun=!0,await B(e,a,o),!A(e))return;D.current&&!E.current?(k(`idle`),await O.current.start()):L()}catch(t){R(e,t)}}async function H(){if(!T.current||!n.current.open||E.current||document.hidden||![`idle`,`error`,`speaking`].includes(v.current))return;I();let e={generation:++b.current,sessionId:n.current.sessionId,controller:new AbortController,microphone:new AbortController,permissionPending:!1,committed:!1,commitRequested:!1,ownsRun:!1};x.current=e,D.current=!0,p(``),c(``),o(0),k(`requesting`);let t=Ra(),r=0;try{if(await S.current,!A(e)||(await N(),!A(e)))return;if(j()){L();return}e.permissionPending=!0;try{await uo()}finally{e.permissionPending=!1}if(!A(e))return;if(document.hidden||j()){L();return}let n=await Wa();if(!A(e)){n.dispose();return}e.endpoint=n;let i=ho({chatSessionId:e.sessionId});if(e.recognizer=i,e.unsubscribe=i.onPartial(t=>{A(e)&&c(t)}),await i.start(),!A(e)||(e.capturePending=vo(a=>{if(!(!A(e)||e.committed||e.microphone.signal.aborted))try{let s=t.push(La(a)),c=performance.now();c-r>=66&&(r=c,o(s));let l=i.acceptPcm(a),u=n.acceptPcm(a);(l||u)&&(e.commitRequested=!0,v.current===`listening`?O.current.commit():e.microphone.abort())}catch(t){R(e,t)}},e.microphone.signal).then(async t=>(!A(e)||e.microphone.signal.aborted?await t.stop():e.capture=t,t)),await e.capturePending,!A(e)))return;if(k(`listening`),e.commitRequested){await O.current.commit();return}e.limitTimer=window.setTimeout(()=>void O.current.commit(),6e4)}catch(t){A(e)&&e.commitRequested&&e.microphone.signal.aborted?(k(`listening`),await O.current.commit()):R(e,t)}}O.current={start:H,commit:V,stop:L};let U=(0,Q.useCallback)(()=>O.current.commit(),[]),W=(0,Q.useCallback)(()=>{O.current.stop();let e=b.current;S.current.then(()=>{b.current===e&&T.current&&O.current.start()})},[]),ee=(0,Q.useCallback)(()=>{v.current===`listening`?O.current.commit():v.current===`thinking`||v.current===`speaking`?W():(v.current===`idle`||v.current===`error`)&&(E.current=!1,h(!1),O.current.start())},[W]),te=(0,Q.useCallback)(()=>{let e=!E.current;E.current=e,h(e),e?O.current.stop():O.current.start()},[]),ne=(0,Q.useCallback)(()=>{M(),O.current.stop(),p(``),_(0)},[]);return(0,Q.useEffect)(()=>{if(!e.open)return;T.current=!0,C.current=!1,E.current=!1,h(!1),d([]),_(0),k(`idle`),O.current.start();let t=()=>{x.current?.permissionPending&&window.__PISPER_MOBILE_APP__||(M(),O.current.stop())},n=()=>{document.hidden&&t()},r=()=>{M(),O.current.stop()};return window.addEventListener(`blur`,t),window.addEventListener(`pisper:speech-interrupted`,r),document.addEventListener(`visibilitychange`,n),()=>{T.current=!1,M(),O.current.stop(),window.removeEventListener(`blur`,t),window.removeEventListener(`pisper:speech-interrupted`,r),document.removeEventListener(`visibilitychange`,n)}},[e.open,e.sessionId,k]),(0,Q.useEffect)(()=>{x.current?.checkOwnership?.()},[e.messages,e.streaming]),(0,Q.useEffect)(()=>{if(![`listening`,`transcribing`,`thinking`,`speaking`].includes(r))return;let e=window.setInterval(()=>_(e=>e+1),1e3);return()=>window.clearInterval(e)},[r]),{stage:r,level:a,partial:s,turns:u,error:f,muted:m,elapsed:g,toggleMain:ee,toggleMute:te,hangUp:ne,commitListening:U,interrupt:W}}function Vo(e){return{idle:e(`chat:voiceMode.idle`),requesting:e(`chat:voiceMode.requesting`),listening:e(`chat:voiceMode.listening`),transcribing:e(`chat:voiceMode.transcribing`),thinking:e(`chat:voiceMode.thinking`),speaking:e(`chat:voiceMode.speaking`),error:e(`chat:voiceMode.failed`)}}function Ho(e){let t=Math.floor(e/60),n=e%60;return`${t.toString().padStart(2,`0`)}:${n.toString().padStart(2,`0`)}`}function Uo(){let[e,t]=(0,Q.useState)(()=>document.documentElement.dataset.theme!==`light`);return(0,Q.useEffect)(()=>{let e=document.documentElement,n=()=>t(e.dataset.theme!==`light`);n();let r=new MutationObserver(n);return r.observe(e,{attributes:!0,attributeFilter:[`data-theme`]}),()=>r.disconnect()},[]),e}function Wo(e){let[t,n]=(0,Q.useState)(()=>typeof window>`u`?380:Math.max(48,Math.min(window.innerWidth*.52,window.innerHeight-304,460)));return(0,Q.useEffect)(()=>{if(!e)return;let t=()=>n(Math.max(48,Math.min(window.innerWidth*.52,window.innerHeight-304,460)));return t(),window.addEventListener(`resize`,t),()=>window.removeEventListener(`resize`,t)},[e]),Math.floor(t)}function Go({open:e,sessionId:t,messages:n,streaming:r,sendPrompt:i,onAbort:a,onClose:o}){let{t:s}=l(),c=Uo(),u=Ka([`asr`,`tts`]),d=Bo({open:e,sessionId:t,messages:n,streaming:r,sendPrompt:i,onAbort:a,ensureReady:u.ensureReady,speakText:(e,t,n)=>$a(e,u.selectedVoice,t,n)}),{stage:f,level:p,partial:m,turns:h,error:g,elapsed:_}=d,v=Wo(e),y=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!e)return;let t=document.activeElement;return y.current?.focus({preventScroll:!0}),()=>{t instanceof HTMLElement&&t.isConnected&&t.focus({preventScroll:!0})}},[e]);let b=()=>{try{d.hangUp()}finally{u.close(),o()}},x=f===`listening`||f===`transcribing`||f===`thinking`||f===`speaking`||f===`requesting`;if((0,Q.useEffect)(()=>{if(!e)return;let t=e=>{if(!(u.open||e.defaultPrevented||e.isComposing)){if(e.key===`Escape`){e.preventDefault(),b();return}if(e.key===`Tab`){let t=[...y.current?.querySelectorAll(`button:not(:disabled)`)||[]],n=t[0],r=t[t.length-1];e.shiftKey&&(document.activeElement===n||document.activeElement===y.current)?(e.preventDefault(),r?.focus()):!e.shiftKey&&document.activeElement===r&&(e.preventDefault(),n?.focus())}e.target instanceof Element&&e.target.closest(`input, textarea, select, button, [contenteditable="true"]`)||e.key===` `&&!e.repeat&&(e.preventDefault(),x?d.hangUp():d.toggleMain())}};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e,o,x,u.open]),!e)return null;let S=Vo(s),C=h[h.length-1],w=f===`listening`&&m?m:C?`${C.role,``}${za(C.text,120)}`:``,T=f===`error`?g||s(`chat:voiceMode.failed`):S[f];return(0,zi.createPortal)((0,$.jsxs)(`div`,{className:`fixed inset-0 z-[90] grid grid-cols-[minmax(0,1fr)] grid-rows-[minmax(0,1fr)_100px_108px] overflow-hidden bg-chrome pt-[env(safe-area-inset-top)] pr-[env(safe-area-inset-right)] pb-[env(safe-area-inset-bottom)] pl-[env(safe-area-inset-left)] text-content select-none`,ref:y,tabIndex:-1,role:`dialog`,"aria-modal":`true`,"aria-label":s(`chat:voiceMode.title`),children:[(0,$.jsxs)(`header`,{className:`pointer-events-none absolute left-[calc(env(safe-area-inset-left)_+_28px)] top-[calc(env(safe-area-inset-top)_+_24px)] flex items-center gap-3`,children:[(0,$.jsx)(`span`,{className:`inline-block size-2 rounded-full ${x?`animate-pulse bg-star`:`bg-content-faint`}`,"aria-hidden":`true`}),(0,$.jsx)(`span`,{className:`text-[13px] font-semibold tracking-[0.3em] text-content`,children:`PISPER`})]}),(0,$.jsxs)(`div`,{className:`absolute top-[calc(env(safe-area-inset-top)_+_16px)] right-[calc(env(safe-area-inset-right)_+_16px)] z-10 flex items-center gap-1`,children:[(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{variant:`ghost`,size:`icon-sm`,"aria-label":s(`chat:speechModels.title`),onClick:()=>{d.hangUp(),u.show()},children:(0,$.jsx)(Zr,{})})}),(0,$.jsx)(Jt,{children:s(`chat:speechModels.title`)})]}),(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{variant:`ghost`,size:`icon-sm`,className:`size-11 flex-none`,"aria-label":s(`chat:speechModels.close`),onClick:b,children:(0,$.jsx)(Dt,{})})}),(0,$.jsx)(Jt,{children:s(`chat:speechModels.close`)})]})]}),(0,$.jsx)(oo,{manager:u,onClose:()=>d.hangUp()}),(0,$.jsx)(`div`,{className:`flex min-h-0 items-center justify-center pt-16 pb-6`,children:(0,$.jsx)(Po,{stage:f,level:p,size:v,dark:c})}),(0,$.jsxs)(`div`,{className:`flex min-h-0 min-w-0 flex-col items-center justify-center gap-2 px-6 text-center`,children:[(0,$.jsx)(`div`,{className:`max-w-full text-xs font-medium tracking-normal ${f===`error`?`max-h-full overflow-y-auto break-words text-danger`:`line-clamp-2 text-content-muted`}`,role:`status`,"aria-live":`polite`,children:T}),(0,$.jsx)(`p`,{className:`m-0 line-clamp-2 min-h-[22px] max-w-[640px] text-[15px] leading-[1.6] text-content`,children:w})]}),(0,$.jsx)(`div`,{className:`relative flex justify-center pt-3 sm:items-center sm:pt-0`,children:(0,$.jsx)(`button`,{type:`button`,className:`h-11 cursor-pointer rounded-full border px-8 text-sm font-medium transition-colors ${x?`border-control bg-key text-content shadow-key hover:bg-surface-hover`:`border-transparent bg-star text-on-accent shadow-primary hover:bg-star-hover`}`,onClick:()=>x?d.hangUp():d.toggleMain(),children:s(x?`chat:voiceMode.endConversation`:`chat:voiceMode.startConversation`)})}),(0,$.jsxs)(`div`,{className:`pointer-events-none absolute bottom-[calc(env(safe-area-inset-bottom)_+_12px)] right-[calc(env(safe-area-inset-right)_+_20px)] flex items-center gap-2.5 sm:bottom-[calc(env(safe-area-inset-bottom)_+_36px)] sm:right-[calc(env(safe-area-inset-right)_+_28px)]`,children:[(0,$.jsx)(`span`,{className:`hidden size-9 place-items-center rounded-full border border-key-border bg-key text-xs text-accent-fg shadow-key sm:grid`,"aria-hidden":`true`,children:x?`●`:`○`}),(0,$.jsx)(`span`,{className:`font-mono text-[13px] tracking-[0.08em] text-content-muted tabular-nums`,children:Ho(_)})]}),(0,$.jsx)(`div`,{className:`absolute bottom-[env(safe-area-inset-bottom)] left-[calc(env(safe-area-inset-left)_+_20px)] sm:bottom-[calc(env(safe-area-inset-bottom)_+_36px)] sm:left-[calc(env(safe-area-inset-left)_+_28px)]`,children:(0,$.jsxs)(Yt,{children:[(0,$.jsx)(qt,{asChild:!0,children:(0,$.jsx)(Y,{variant:`ghost`,size:`icon`,className:`size-11 flex-none`,disabled:!x&&!d.muted,"aria-label":f===`speaking`||f===`thinking`?s(`chat:voiceMode.interrupt`):d.muted?s(`chat:voiceMode.unmute`):s(`chat:voiceMode.mute`),onClick:()=>f===`speaking`||f===`thinking`?d.interrupt():d.toggleMute(),children:f===`speaking`||f===`thinking`?(0,$.jsx)(gt,{}):d.muted?(0,$.jsx)(ri,{}):(0,$.jsx)(ii,{})})}),(0,$.jsx)(Jt,{children:f===`speaking`||f===`thinking`?s(`chat:voiceMode.interrupt`):d.muted?s(`chat:voiceMode.unmute`):s(`chat:voiceMode.mute`)})]})})]}),document.body)}var Ko=[`plan`,`goal`,`team`];function qo(e){return Ko.includes(e)?e:`plan`}function Jo({sessionId:e,runMode:t,goalsAvailable:n,teamAvailable:r,workflowsAvailable:i,goal:a,streaming:o,compaction:s,value:c,selection:l,clearDraft:u,captureSubmission:d,promptRef:f,onCompact:p,onGoalPause:m,onSend:h,onQueue:g,onAbort:_,requestTranscriptBottom:v}){let[y,b]=(0,Q.useState)(()=>qo(t)),x=(0,Q.useRef)(t);x.current=t;let[S,C]=(0,Q.useState)(null),[w,T]=(0,Q.useState)(null),E=(0,Q.useRef)(null),[D,O]=(0,Q.useState)(!1),[k,A]=(0,Q.useState)(!1),[j,M]=(0,Q.useState)(!1),[N,P]=(0,Q.useState)(``),F=(0,Q.useRef)(null),I=(0,Q.useRef)(e);I.current=e;let[L,R]=(0,Q.useState)(!1),[z,B]=(0,Q.useState)(null),V=(0,Q.useRef)(z);return V.current=z,(0,Q.useEffect)(()=>{b(qo(x.current)),E.current=null,C(null),T(null),F.current=null,A(!1),M(!1),P(``),O(!1),R(!1),B(null)},[e]),(0,Q.useEffect)(()=>{b(qo(t))},[e,t]),(0,Q.useEffect)(()=>{n||b(`plan`),!r&&y===`team`&&b(`goal`),!i&&z?.kind===`workflow`&&B(null)},[y,n,z?.kind,r,i]),(0,Q.useEffect)(()=>{a?.status===`active`&&b(a.mode===`team`&&r?`team`:`goal`)},[a?.id,a?.mode,a?.status,r]),(0,Q.useEffect)(()=>{if(!a?.id){C(null);return}let e=a.mode===`team`?a.teamTokenBudget:a.tokenBudget,t=e==null?null:Number(e),n=t!==null&&Number.isFinite(t)&&t>0?t:null;a.mode===`team`?T(n):C(n)},[a?.id,a?.mode,a?.teamTokenBudget,a?.tokenBudget]),{composerExecutionMode:y,setComposerExecutionMode:b,goalTokenBudget:S,setGoalTokenBudget:C,teamTokenBudget:w,setTeamTokenBudget:T,queueing:D,submitting:k,stopping:j,submitError:N,stop:async()=>{if(j||!_)return!1;let t=e;M(!0);try{return await _(),!0}catch(e){return I.current===t&&P(e instanceof Error?e.message:String(e)),!1}finally{I.current===t&&M(!1)}},compactingManually:L,invocation:z,setInvocation:B,requestGoalPause:()=>{if(E.current)return E.current;let e=Promise.resolve().then(()=>m?.());return E.current=e,e.catch(()=>{}),e},compactContext:async()=>{if(!(!p||o||L||s?.active)){R(!0);try{await p()}finally{R(!1)}}},submit:async(t,n=`steer`)=>{if(t.preventDefault(),F.current||j||l.preparingAttachments?.length||!c.trim()&&!l.attachments.length&&!z||o&&(!c.trim()&&!l.attachments.length||!g))return;let r={},i=e;F.current=r;let s=()=>I.current===i&&F.current===r,p=d?.(),_=!1,x=()=>{_||(_=!0,p?p.accept():u(),s()&&(A(!1),O(!1),b(`plan`),V.current===z&&B(null),v(),f.current&&(f.current.style.height=`auto`),F.current=null))};P(``),o?O(!0):A(!0);try{if(o){await g?.(c,l.attachments,n,x)&&x();return}let e=E.current;if(e?(await e,E.current=null):a?.status===`active`&&(y===`plan`||y!==a.mode)&&await m?.(),!s())return;let t=await h(c,l.attachments,y===`goal`||y===`team`,y===`team`,y===`team`?w:y===`goal`?S:null,z,x);!_&&t!==!1&&x()}catch(e){s()&&(E.current=null,P(e instanceof Error?e.message:String(e)))}finally{s()&&(F.current=null,A(!1),O(!1))}}}}var Yo=[`[role="dialog"]`,`[role="alertdialog"]`,`[role="menu"]`,`[role="listbox"]`,`.anchored-popup-menu`,`.voice-input-popup`,`.git-diff-dialog-backdrop`,`[data-slot='popover-content']`,`[data-slot='dropdown-menu-content']`,`[data-slot='select-content']`,`[data-slot='sheet-content']`].join(`, `);function Xo(){return[...document.querySelectorAll(Yo)].some(e=>e.dataset.state!==`closed`&&e.getAttribute(`aria-hidden`)!==`true`&&e.getClientRects().length>0)}var Zo=(0,Q.memo)(function({session:e,draft:t,emptyState:n,shortcutEnabled:r=!1,messages:i,transcriptLoadState:a=`ready`,messageStart:o,hasNewer:s,hasOlder:c,loadingOlder:u,olderError:d,model:f,thinkingLevel:p,availableThinkingLevels:m,thinkingStatus:h,thinkingMessage:g,executionMode:_,goal:v,team:y,currentActivity:b,activityFeed:x,tools:S,thinkingText:C,queuedInputs:w,workspace:T,withdrawingInputIds:E,compaction:D,contextUsage:M,sessionUsage:N,sessionTreeRevision:P,sessionTreePulse:F,cwd:I,availableModels:L,pendingRuntimeSelection:z,switchingModel:B,switchingThinking:V,switchingCwd:H,switchingPermission:U,streaming:W,runStartedAt:te,lastActivityAt:ne,runFinishedAt:re,runStopped:ae,runNotice:se,approvals:de,questions:pe,error:me,pendingAsset:q,notify:ge,onOpenModelSettings:Ce,onAssetConsumed:Te,onLoadOlder:De,onLoadLatest:Oe,onModelChange:ke,onThinkingLevelChange:je,onExecutionModeChange:Me,onRunModeChange:Ne,onCompact:Pe,onCompactionThresholdChange:Le,onGoalPause:Re,onGoalBudgetChange:ze,onApproval:Be,onAnswerQuestion:Ve,onWorkspace:He,onRename:Ue,onBranchFromHere:We,onCreateChildSession:qe,onRetryLastTurn:et,onTreeNavigated:nt,onSend:rt,onQueue:it,onWithdrawQueuedInput:at,onSendQueuedInputNow:ot,onDeliverSessionMessages:ct,onDismissSessionMessages:lt,onAbort:dt}){let ft=(0,Q.useContext)(Ee),pt=(0,Q.useContext)(Bi),mt=(0,Q.useContext)(Ye),ht=!!mt?.phone,{t:J}=l(),gt=gn(e=>e.bindings),_t=j(),vt=A(),St=_t||vt,Ct=k(e=>e.capabilities),wt=O(Ct,`goals`),Tt=O(Ct,`multiAgent`),Et=O(Ct,`workflows`),Dt=O(Ct,`visualGeneration`),Ot=O(Ct,`inputInterrupt`),kt=Ot?`interrupt`:`steer`,{value:It,updateValue:Lt,selection:Rt,clearDraft:zt,restoreDraft:Bt,captureSubmission:Vt}=xe(t?fe:e.id),[Ht,Ut]=(0,Q.useState)(!1),[Wt,Gt]=(0,Q.useState)(!1),[Kt,qt]=(0,Q.useState)(!1),Jt=(0,Q.useRef)(null),[Yt,Zt]=(0,Q.useState)(!1),[Y,Qt]=(0,Q.useState)(!1),[$t,en]=(0,Q.useState)(``),[tn,nn]=(0,Q.useState)(!1),[rn,on]=(0,Q.useState)(0),sn=Rt.addAttachments,cn=(0,Q.useRef)(null);(0,Q.useLayoutEffect)(()=>{cn.current&&oa(cn.current)},[It]);let un=(0,Q.useRef)(null),dn=(0,Q.useRef)(`steer`),fn=gt.steerMessage,pn=()=>{dn.current=kt,cn.current?.form?.requestSubmit()},mn=bn(`sendMessage`),_n=bn(`voiceInput`),Sn=(0,Q.useRef)(null),Cn=(0,Q.useRef)(null);(0,Q.useEffect)(()=>{if(!r)return;let e=e=>{!hn(e)&&yn(e,gt.focusComposer)&&(e.preventDefault(),cn.current?.focus())};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)},[r,gt.focusComposer]);let wn=!!t;(0,Q.useEffect)(()=>{if(!wn)return;let e=()=>{let e=cn.current;e&&(e.focus(),e.setSelectionRange(e.value.length,e.value.length),e.scrollTop=e.scrollHeight,an())};return(an()||!St)&&e(),window.addEventListener(ln,e),()=>window.removeEventListener(ln,e)},[wn,St]);let Tn=(0,Q.useRef)(!1),Dn=a!==`ready`||i.length>0,On=W?St?J(`board:composer.placeholderRunningTouch`):fn?J(`board:composer.placeholderRunning`,{queue:mn,steer:xn(fn)}):J(`board:composer.placeholderRunningQueueOnly`,{queue:mn}):J(t?`chat:newTask.placeholder`:`board:composer.placeholder`),kn=()=>on(e=>e+1),An=e=>{Lt(e)},{composerExecutionMode:jn,setComposerExecutionMode:Mn,goalTokenBudget:Nn,setGoalTokenBudget:Pn,teamTokenBudget:Fn,setTeamTokenBudget:In,queueing:Ln,submitting:Rn,stopping:zn,submitError:Bn,stop:Vn,compactingManually:Hn,invocation:Un,setInvocation:Wn,requestGoalPause:Gn,compactContext:Kn,submit:qn}=Jo({sessionId:e.id,runMode:e.runMode,goalsAvailable:wt,teamAvailable:Tt,workflowsAvailable:Et,goal:v,streaming:W,compaction:D,value:It,selection:Rt,clearDraft:zt,captureSubmission:Vt,promptRef:cn,onCompact:Pe,onGoalPause:Re,onSend:rt,onQueue:it,onAbort:dt,requestTranscriptBottom:kn}),Jn=async()=>{let e=w||[];if(await Vn())for(let t of e)Bt({text:String(t.text||``),attachments:Array.isArray(t.attachments)?t.attachments:[]})},Yn=(0,Q.useRef)(Jn);Yn.current=Jn,(0,Q.useEffect)(()=>{if(!mt||!r||!W)return;let e=new WeakSet,t=t=>{t.key===`Escape`&&Xo()&&e.add(t)},n=t=>{if(t.key!==`Escape`||!t.isTrusted||t.defaultPrevented||t.isComposing||t.keyCode===229||e.has(t))return;let n=t.target,r=un.current,i=n===document.body||n===document.documentElement||n instanceof Element&&!!n.closest(`[data-session-conversation]`)&&!n.closest(`.terminal-panel, .xterm`);!r||!i||vn(n)&&n!==cn.current||(t.preventDefault(),Yn.current())};return window.addEventListener(`keydown`,t,!0),window.addEventListener(`keydown`,n),()=>{window.removeEventListener(`keydown`,t,!0),window.removeEventListener(`keydown`,n)}},[mt,r,W]);let Xn=e=>{v?.status===`active`&&(e===`plan`||e!==v.mode)&&Gn().catch(()=>{}),Mn(e),Ne(e)},Zn=(0,Q.useContext)(Ze),Qn=mt?.onNewTask||mt?.phone?.onNewTask,er=t?t.cwd:null,tr=(0,Q.useCallback)(()=>er===null?X.getSessionCommands(e.id):X.getWorkspaceCommands(er),[er,e.id]),nr=_a(e.id),rr=[...Qn&&!t?[{invocation:`/new`,description:J(`chat:commands.builtin.new`),run:Qn}]:[],...ie({t:J,models:L,model:z?.model||f,onModel:e=>ke(e),thinkingLevels:z?.model?[]:m||[],thinkingLevel:z?.thinkingLevel||p||``,thinkingLabel:e=>_e(J,e),onThinking:e=>je(e),executionModes:[`approval-required`,`workspace-write`,`full-access`],executionMode:_,executionLabel:e=>J(e===`full-access`?`chat:focusSession.fullAccess`:e===`workspace-write`?`chat:focusSession.workspaceWrite`:`chat:focusSession.approvalRequired`),onExecutionMode:e=>Me(e),runModes:W?[]:[`plan`,...wt?[`goal`]:[],...wt&&Tt?[`team`]:[]],runMode:jn,runModeLabel:e=>J(e===`team`?`chat:focusSession.teamMode`:e===`goal`?`chat:focusSession.goalMode`:`chat:focusSession.planMode`),onRunMode:e=>Xn(e)}),...t?[]:[{invocation:`/btw`,description:J(`chat:commands.builtin.btw`)}],...Pe?[{invocation:`/compact`,description:J(`chat:commands.builtin.compact`),run:()=>Kn()}]:[],...Zn&&!t?[{invocation:`/changes`,description:J(`chat:commands.builtin.changes`),run:()=>Zn.show(`changes`)}]:[]],ir=z?.model||f||``,ar=$n(L.find(e=>e.key===ir)?.label||ir.split(`/`).at(-1)||``,L.map(e=>e.label)),or=e?.botId,sr=(0,Q.useMemo)(()=>mt?{model:ar,...or?{botId:or}:{}}:null,[or,ar,mt]),cr=(0,Q.useRef)([]);(0,Q.useEffect)(()=>()=>{for(let e of cr.current)window.clearTimeout(e);cr.current=[]},[e.id]);let lr=!!(Ct.features.agentTranscripts&&Zn&&!t),ur=(0,Q.useMemo)(()=>lr&&Xe(i,x.length?x:S),[x,i,lr,S]),dr=(0,Q.useRef)(!!s);dr.current=!!s;let fr=Ge(e.id,!!or||ur,()=>{if(or)for(let e of[1500,4e3,9e3])cr.current.push(window.setTimeout(()=>{dr.current||Oe?.()},e))}),Z=(0,Q.useRef)(W),pr=fr.reload;(0,Q.useEffect)(()=>{let e=Z.current&&!W;if(Z.current=W,!or||!e)return;let t=[1500,4e3].map(e=>window.setTimeout(pr,e));return()=>{for(let e of t)window.clearTimeout(e)}},[or,pr,W]);let mr=(0,Q.useMemo)(()=>or?{sessionId:e.id,agents:new Map(fr.agents.map(e=>[e.id,e])),links:new Map(fr.links.map(e=>[e.id,e])),reload:fr.reload}:null,[or,e.id,fr.agents,fr.links,fr.reload]),hr=Pr(e=>e.select),gr=Zn?.show,_r=(0,Q.useMemo)(()=>lr&&gr?{sessionId:e.id,agents:fr.agents,open:t=>{hr(e.id,t),gr(`subagent`)}}:null,[hr,e.id,fr.agents,gr,lr]),vr=(0,Q.useMemo)(()=>{let e=ht?i:i.filter(e=>!Ie(e));return or?$e(e,fr.agents,fr.links):e},[or,i,ht,fr.agents,fr.links]),yr=Number(M?.percent),br=M?.percent!=null&&Number.isFinite(yr)?yr:null,xr=i[Ae(i)],Cr=xr?.role===`agent`?xr:null,wr=Bn||me||(W?``:String(Cr?.error||``)),Tr=!s&&!Bn&&!W&&i.some(e=>e.role===`user`);(0,Q.useEffect)(()=>{Ut(!1),Zt(!1)},[e.id]),(0,Q.useEffect)(()=>{q&&(sn([q]),Te?.())},[q,Te,sn]);let Er=async e=>{let t=await at?.(e);if(!t||!Bt(t))return;let n=cn.current;requestAnimationFrame(()=>{!n||cn.current!==n||!n.isConnected||n.focus()})},Dr=async e=>{await at?.(e)},Or=e=>{Lt(e),requestAnimationFrame(()=>{let e=cn.current;e&&e.focus()})},kr=bt({cwd:I,selection:Rt}),Ar=(0,$.jsx)(So,{sessionId:e.id,shortcutEnabled:r,variant:ht?`button`:`menu`,controlRef:Cn,onLiveText:e=>{if(e===null){Sn.current!==null&&(An(Sn.current),Sn.current=null);return}Sn.current===null&&(Sn.current=(cn.current?.value??It).trimEnd());let t=Sn.current;An(t&&e?`${t}\n${e}`:t||e)},onInsert:e=>{let t=Sn.current??(cn.current?.value??It).trimEnd();Sn.current=null,An(t?`${t}\n${e}`:e),requestAnimationFrame(()=>cn.current?.focus())}}),jr=J(`board:composer.plusMenu`),Mr=()=>void Pa({templatePrompt:J(`chat:focusSession.visualPromptTemplate`),configureHint:J(`chat:focusSession.configureVisualModelFirst`),notify:ge,onOpenModelSettings:Ce,onInsertPrompt:Or}),Nr=(0,$.jsxs)(`button`,{type:`button`,className:Xt(ve,`composer-plus-trigger aria-expanded:bg-surface-hover aria-expanded:text-content max-[650px]:rounded-full max-[650px]:bg-surface-muted max-[650px]:dark:bg-surface-active max-[650px]:text-content`),ref:Jt,title:jr,"aria-label":jr,"data-composer-plus":!0,children:[(0,$.jsx)(ut,{size:18,className:G,"aria-hidden":`true`}),Rt.attachments.length>0&&(0,$.jsx)(`span`,{className:`absolute -top-0.5 -right-0.5 grid h-4 min-w-4 place-items-center rounded-full border-2 border-panel bg-star px-0.5 text-[10px] leading-none font-medium text-on-accent tabular-nums`,children:Rt.attachments.length})]}),Fr=ht?(0,$.jsx)(ma,{trigger:Nr,open:Kt,onOpenChange:qt,onAttachment:()=>void kr.choose(),onResource:()=>Ut(!0),onVisual:Dt?Mr:void 0,steer:W?{disabled:!It.trim()&&!Rt.attachments.length&&!Un,onSelect:pn}:void 0,mode:or?void 0:{valueLabel:J(_===`full-access`?`chat:focusSession.fullAccessShort`:_===`workspace-write`?`chat:focusSession.workspaceWriteShort`:`chat:focusSession.approvalRequiredShort`),onOpen:()=>Gt(!0)}}):(0,$.jsxs)(Ft,{children:[(0,$.jsx)(Nt,{asChild:!0,children:Nr}),(0,$.jsxs)(Pt,{align:`start`,side:`top`,className:`w-60 p-1 max-[650px]:[&_[role=menuitem]]:min-h-11`,"data-composer-plus-menu":!0,children:[(0,$.jsxs)(jt,{"data-composer-plus-item":`attachment`,onSelect:()=>void kr.choose(),children:[(0,$.jsx)(st,{"aria-hidden":`true`}),J(`chat:focusSession.addAttachment`)]}),(0,$.jsxs)(jt,{"data-composer-plus-item":`resource`,onSelect:()=>Ut(!0),children:[(0,$.jsx)(R,{"aria-hidden":`true`}),J(`chat:resourcePicker.open`)]}),(0,$.jsx)(At,{}),Dt&&(0,$.jsxs)(jt,{"data-composer-plus-item":`visual`,onSelect:Mr,children:[(0,$.jsx)(ee,{"aria-hidden":`true`}),J(`chat:focusSession.generateImage`)]}),(0,$.jsxs)(jt,{"data-composer-plus-item":`voice`,onSelect:()=>Cn.current?.(),children:[(0,$.jsx)(ii,{"aria-hidden":`true`}),J(`board:composer.voiceInput`),_n&&(0,$.jsx)(Mt,{children:_n})]})]})]}),Ir=(0,$.jsx)(pa,{sheet:ht,collapse:ht,open:Wt,onOpenChange:e=>{Gt(e),!e&&ht&&window.setTimeout(()=>Jt.current?.focus(),0)},approvalMode:_,onApprovalModeChange:Me,approvalDisabled:U,runMode:jn,onRunModeChange:Xn,runModeDisabled:!!W,goalsAvailable:wt,teamAvailable:Tt,goal:v,tokenBudget:jn===`team`?Fn:Nn,onTokenBudgetChange:jn===`team`?In:Pn,onSaveTokenBudget:e=>ze?.(e)}),Lr=(0,$.jsx)(he,{sheet:ht,model:z?.model||f,models:L,onModelChange:ke,thinkingLevel:z?.thinkingLevel||p||`medium`,levels:z?.model?[]:m||[],status:h,message:g,onThinkingChange:je,modelDisabled:B||V,thinkingDisabled:V||B,deferred:W,pendingModel:!!z?.model,usage:(0,$.jsx)(ye,{sessionId:e.id,usage:M,sessionUsage:N,model:f,availableModels:L,onThresholdChange:Le})}),Rr=(0,$.jsx)(`div`,{className:Xt(`flex items-center`,ht?`shrink-0`:`min-w-0 shrink [&_.model-effort-pill]:max-w-full @max-[300px]/composer-footer:[&_.model-effort-pill>span:nth-child(n+2)]:hidden`),children:Lr}),zr=(0,Q.useMemo)(()=>En(pe),[pe]),Br={session:e,cwd:I||``,streaming:!!W,treeAvailable:i.length>0,onRename:Ue,onWorkspace:He,workspaceDisabled:!!(W||H),onCompact:Pe?()=>void Kn():void 0,compactDisabled:!!(W||Hn||D?.active||i.length===0),workflowsAvailable:Et,onVoiceMode:()=>Qt(!0),notify:ge??(()=>void 0)},Vr=x.length?x:S,Hr=mt&&(0,$.jsx)(Ma,{visible:i.length>0,open:Yt,sessionId:e.id,streaming:!!W,revision:P,pulseToken:F,onOpenChange:Zt,onNavigated:async e=>{e!==null&&Or(e),await nt?.(),kn()},onCreateChildSession:e=>qe(e),notify:ge,children:(e,t)=>ht?(0,$.jsx)(ia,{...Br,runStartedAt:te,approvals:de.length,failed:!!(!W&&(me||Cr?.error)),stopped:!!(!W&&ae),contextPercent:br,leading:pt,branches:t.branches,onOpenTree:t.open,runningActivity:Vr}):(0,$.jsx)(Zi,{...Br,contextPercent:br,branches:t.branches,onOpenTree:t.open,runningActivity:Vr})}),Ur=t?(0,$.jsx)(ua,{phone:ht,leading:pt,project:ht?t.renderProjectControl(`header`):void 0}):Hr,Wr=(0,$.jsx)(Fe,{emptyState:t?(0,$.jsx)(la,{}):n,botId:e?.roomId?void 0:or,layoutMeasurementKey:`fixed`,sessionId:e.id,messages:vr,transcriptLoadState:a,messageStart:o,hasNewer:s,onLoadLatest:Oe,hasOlder:c,loadingOlder:u,olderError:d,currentActivity:b,team:y,activityFeed:x,tools:S,thinkingText:C,compaction:D,streaming:W,runStartedAt:te,lastActivityAt:ne,runFinishedAt:re,runStopped:ae,runNotice:se,error:me,scrollRequest:rn,cwd:I,lineage:e.lineage,switchingCwd:H,onLoadOlder:De,onBranchFromHere:We,onCreateChildSession:qe,onRetryLastTurn:et,onPromptSelect:Or,onWorkspace:He,collapseEarlierTurns:ht},`transcript`),Gr=e=>ce(e.dataTransfer)?(e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`),nn(!0),!0):!1,Kr=(0,$.jsxs)(`form`,{className:Xt(`focus-composer-shell relative z-20 mx-auto flex w-[min(768px,calc(100%_-_48px))] shrink-0 flex-col gap-2 pt-2 pb-3 @max-[700px]:w-[calc(100%_-_24px)] max-[650px]:pb-2.5`,Dn&&`before:pointer-events-none before:absolute before:inset-x-0 before:-top-9 before:h-9 before:bg-linear-to-b before:from-transparent before:to-panel`),onSubmit:e=>{let t=dn.current;dn.current=`steer`;let n=Se(It);if(n!==null){e.preventDefault(),n&&(nr.ask(n),Lt(``));return}if(!W&&(z||B||V)){e.preventDefault();return}qn(e,mt?t:`steer`)},children:[nr.state&&(0,$.jsx)(ga,{state:nr.state,cwd:I||void 0,onDismiss:()=>{nr.dismiss(),cn.current?.focus()}}),(0,$.jsx)(we,{approvals:de,onResolve:Be,sessionTitle:e.name||e.id,cwd:I||``}),zr[0]&&Ve&&(0,$.jsx)(Na,{question:zr[0],more:zr.length-1,collapsed:de.length>0,onAnswer:Ve},zr[0].id),Et&&!t&&(0,$.jsx)(Di,{sessionId:e.id}),Un&&(0,$.jsx)(be,{invocation:Un,onRemove:()=>Wn(null)}),Rt.attachmentError&&(0,$.jsx)(`span`,{className:`text-[var(--danger)] text-[13px]`,children:Rt.attachmentError}),wr&&(0,$.jsx)(tt,{error:wr,onRetry:Tr?et:void 0,className:`w-full`}),(0,$.jsxs)(`div`,{className:`flex min-w-0 flex-col`,children:[(0,$.jsx)(ue,{streaming:W,compaction:D,startedAt:te,lastActivityAt:ne,stopping:zn,onStop:()=>void Jn(),runRow:!ht,queuedInputs:w,withdrawingInputIds:E,onEdit:at?Er:void 0,onCancel:at?Dr:void 0,onSendNow:Ot&&ot?e=>void ot(e):void 0,queueList:!ht,workspace:t?null:T,onDeliverSessionMessages:ct,onDismissSessionMessages:lt}),(0,$.jsxs)(`div`,{className:Xt(`focus-composer relative flex min-w-0 flex-col rounded-[var(--composer-radius,22px)] [corner-shape:var(--composer-corner-shape,round)] border border-control bg-solid shadow-composer transition-[border-color,box-shadow] duration-(--d-fast) ease-(--ease) has-[textarea:focus]:border-focus has-[textarea:focus]:ring-3 has-[textarea:focus]:ring-focus-ring max-[650px]:rounded-[28px] max-[650px]:border-stroke-strong max-[650px]:shadow-none max-[650px]:has-[textarea:focus]:border-control max-[650px]:has-[textarea:focus]:ring-0 [&>.attachment-tray]:px-3 [&>.attachment-tray]:pt-3 [&_textarea]:w-full [&_textarea]:min-w-0 [&_textarea]:min-h-11 [&_textarea]:max-h-[220px] [&_textarea]:resize-none [&_textarea]:overflow-y-auto [&_textarea]:border-0 [&_textarea]:[outline:0]! [&_textarea]:bg-transparent [&_textarea]:px-4 [&_textarea]:pt-3 [&_textarea]:pb-1 [&_textarea]:text-[length:calc(var(--app-message-font-size)*.9375)] max-[650px]:[&_textarea]:px-3.5 max-[650px]:[&_textarea]:text-[length:var(--app-message-font-size)] [&_textarea]:[font-family:var(--font-content-family)] [&_textarea]:font-[400] [&_textarea]:leading-5 [&_textarea]:text-content [&_textarea]:placeholder:text-content-muted`,tn&&`border-focus ring-3 ring-focus-ring`),onDragEnter:Gr,onDragOver:Gr,onDragLeave:e=>{let t=e.relatedTarget;t instanceof Node&&e.currentTarget.contains(t)||nn(!1)},onDrop:e=>{nn(!1),Rt.dropFiles(e)},children:[tn&&(0,$.jsx)(`div`,{role:`status`,className:`pointer-events-none absolute inset-0 z-10 grid place-items-center rounded-[inherit] border border-dashed border-focus bg-panel px-4 text-center text-sm text-content`,children:J(`chat:focusSession.dropAttachment`)}),(0,$.jsx)(xt,{attachments:Rt.attachments,preparing:Rt.preparingAttachments,onRemove:Rt.removeAttachment}),(0,$.jsx)(K,{placement:`top`,resourceKey:e.id,loadCommands:tr,builtinCommands:rr,value:It,onChange:Lt,inputRef:cn}),(0,$.jsx)(`textarea`,{ref:cn,rows:1,"aria-label":J(`chat:focusSession.taskDescription`),value:It,onChange:e=>{Lt(e.target.value)},onPaste:Rt.pasteFiles,onCompositionStart:()=>Tn.current=!0,onCompositionEnd:()=>window.setTimeout(()=>Tn.current=!1,0),onKeyDown:e=>{let t=e.nativeEvent.isComposing||Tn.current;if(mt&&W&&!t&&fn&&yn(e.nativeEvent,fn)){e.preventDefault(),dn.current=kt,e.currentTarget.form?.requestSubmit();return}if(e.key===`Tab`&&e.shiftKey&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!t&&!W){let t=ha(jn,{goalsAvailable:wt,teamAvailable:Tt});if(t){e.preventDefault(),Xn(t),en(J(t===`team`?`chat:focusSession.teamMode`:t===`goal`?`chat:focusSession.goalMode`:`chat:focusSession.planMode`));return}}!t&&yn(e.nativeEvent,gt.sendMessage)&&(e.preventDefault(),e.currentTarget.form?.requestSubmit()),!mt&&W&&!t&&e.key===`Escape`&&!e.defaultPrevented&&(e.preventDefault(),Jn())},"data-mobile-composer-input":St||void 0,enterKeyHint:St&>.sendMessage===`Enter`?`send`:`enter`,placeholder:On}),(0,$.jsx)(`span`,{role:`status`,className:`sr-only`,children:$t}),(0,$.jsxs)(`div`,{className:`focus-composer-footer @container/composer-footer flex min-w-0 items-center gap-1 px-2 pt-1 pb-2 max-[650px]:gap-2 max-[650px]:pt-2 max-[650px]:pb-3`,"data-composer-toolbar":!0,children:[Fr,kr.input,ht&&!or&&Rr,!ht&&t?.renderProjectControl(`chip`),!or&&Ir,(0,$.jsx)(`span`,{className:`min-w-0 flex-1`}),Ar,!ht&&!or&&Rr,(0,$.jsx)(le,{streaming:W,startedAt:te,lastActivityAt:ne,queueing:Ln,submitting:Rn,stopping:zn,preparing:Rt.preparingAttachments.length>0,hasDraft:!!(It.trim()||Rt.attachments.length||Un),canQueue:!!it,blockedReason:!W&&(z||B||V)?J(`chat:focusSession.waitingForModel`):void 0,disabled:!W&&(!!z||B||V||Ln||!It.trim()&&!Rt.attachments.length&&!Un),onLongPress:ht&&W?pn:void 0,longPressHint:J(`board:composer.longPressSteer`),onStop:ht?()=>void Jn():void 0})]})]})]})]},`composer`);return(0,$.jsxs)(Sr,{className:Xt(`focus-session [--chat-content-width:768px] [.session-dock-panel_&]:overflow-hidden [.session-dock-panel_&]:min-h-0 [.session-dock-panel_&]:border-0 [.session-dock-panel_&]:rounded-[0] [.session-dock-panel_&]:bg-[var(--panel)] [.session-dock-panel_&]:p-0 [.session-dock-panel_&]:shadow-[none] [[data-theme='dark']_.session-dock-panel_&]:bg-[var(--main-surface-bg)] min-[651px]:[[data-density='compact']_.app-card:not(&)]:p-[10px] max-[650px]:min-h-[460px] max-[650px]:[.session-dock-panel_&]:min-h-0 relative flex h-full min-h-0 flex-col ${Dn?`has-conversation`:`is-empty`}`,t&&`min-[651px]:[&_[data-chat-region=messages]]:!flex-none min-[651px]:[&_[data-chat-region=messages]]:mt-[max(48px,calc((100dvh-520px)/2))] min-[651px]:[&_[data-chat-region=messages]]:!overflow-visible min-[651px]:[&_.transcript]:!overflow-visible min-[651px]:[&_.transcript]:!p-0 min-[651px]:[&_.transcript]:!pb-6`),"data-chat-message-style":`bubble`,children:[(0,$.jsxs)(`div`,{ref:un,className:`flex h-full min-h-0 min-w-0 flex-1 flex-col overflow-hidden`,children:[(0,$.jsx)(`div`,{className:`shrink-0`,"data-chat-region":`header`,children:ft?.headerHost?(0,zi.createPortal)(Ur,ft.headerHost):ft?null:Ur}),(0,$.jsx)(`div`,{className:`flex min-h-0 flex-1 flex-col overflow-hidden`,"data-chat-region":`messages`,"data-focus-region":`content`,children:(0,$.jsx)(Qe.Provider,{value:mr,children:(0,$.jsx)(Je.Provider,{value:_r,children:sr?(0,$.jsx)(Ke.Provider,{value:sr,children:Wr}):Wr})})}),(0,$.jsx)(`div`,{className:`shrink-0`,"data-chat-region":`composer`,"data-focus-region":`composer`,children:Kr})]}),ft?.sourceActionHost&&(0,zi.createPortal)((0,$.jsx)(yt,{cwd:I,selection:Rt}),ft.sourceActionHost),(0,$.jsx)(aa,{open:Ht,sessionId:e.id,cwd:I||``,onClose:()=>Ut(!1),onSelect:Wn,onCommandSelect:e=>Or(oe(e,It))}),(0,$.jsx)(Go,{open:Y,sessionId:e.id,sessionName:e.name||e.id,messages:i,streaming:W,sendPrompt:async(...e)=>{await rt(...e)},onAbort:dt,onClose:()=>Qt(!1)})]})}),Qo=(0,Q.createContext)(null),$o=40,es=[],ts=()=>void 0;function ns(e){let t=e?.queue;if(!t||typeof t!=`object`||Array.isArray(t))return null;let n=t.startAfter;return typeof n==`string`?n:``}function rs({draft:e}){let t=(0,Q.useContext)(Qo),{t:n}=l(),r=n(`board:home.draftTitle`),i=(0,Q.useMemo)(()=>({id:``,name:r,cwd:e.cwd,runMode:e.runMode}),[e.cwd,e.runMode,r]);if(!t)return null;let a=t.pendingAsset?.asset&&!t.pendingAsset.targetSessionId?t.pendingAsset.asset:null;return(0,$.jsx)(`div`,{className:`session-dock-panel h-full w-full min-w-0 min-h-0 overflow-hidden [container-type:inline-size] bg-panel`,"data-new-task-draft":!0,children:(0,$.jsx)(Zo,{session:i,shortcutEnabled:!0,draft:e,messages:es,transcriptLoadState:`ready`,model:e.model||t.defaultModel,thinkingLevel:e.thinkingLevel,availableThinkingLevels:e.availableThinkingLevels,executionMode:e.executionMode,runMode:e.runMode,activityFeed:es,tools:es,queuedInputs:es,approvals:es,cwd:e.cwd,availableModels:t.availableModels,pendingAsset:a,onAssetConsumed:t.onAssetConsumed,notify:t.notify,onOpenModelSettings:t.openModelSettings,onModelChange:e.onModelChange,onThinkingLevelChange:e.onThinkingLevelChange,onExecutionModeChange:e.onExecutionModeChange,onRunModeChange:e.onRunModeChange,onApproval:ts,onWorkspace:ts,onRename:ts,onBranchFromHere:ts,onCreateChildSession:ts,onRetryLastTurn:ts,onAbort:ts,onSend:(n,r,i,a,o,s,c)=>t.sendNewTask(e,n,r,i,a,o,s,{onAccepted:c})})})}function is({sessionId:e,onCreateSession:t}){let n=(0,Q.useContext)(Qo),r=e??(n?.activeId||``);return r?(0,$.jsx)(as,{sessionId:r,panelId:`single-${r}`,shortcutEnabled:!0},r):(0,$.jsx)(os,{onNewSession:t})}function as({sessionId:e,panelId:t,shortcutEnabled:n,onFocusCapture:r}){let i=(0,Q.useContext)(Qo),{t:a}=l(),o=(0,Q.useContext)(Ye),s=k(e=>e.capabilities),c=i?.subscribeSessionState,u=i?.getSessionState,d=(0,Q.useMemo)(()=>t=>c?.(e,t)??(()=>{}),[c,e]),f=(0,Q.useMemo)(()=>()=>u?.(e),[u,e]),p=(0,Q.useSyncExternalStore)(d,f),m=i?.sessions.find(t=>t.id===e),h=p||Me,g=je(h,m),_=ns(m),v=Ce(p,m),y=p&&Object.hasOwn(p,`team`)?p.team:m?.team??null,b=Ne(v,{streaming:g})?v:null,x=i?.sessionTreePulseSessionId===e?i.sessionTreePulseToken:0,S=i?.loadSessionMessages,C=i?.loadSessionThinkingLevel,w=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{e&&S?.(e,{limit:$o})},[S,e]),(0,Q.useEffect)(()=>{!e||!m||!C||h.thinkingStatus||(h.availableThinkingLevels||[]).length||w.current!==e&&(w.current=e,C(e))},[C,m,e,h.availableThinkingLevels,h.thinkingStatus,g]);let T=(0,Q.useMemo)(()=>({onLoadLatest:()=>i?.loadSessionMessages(e,{force:!0}),onLoadOlder:()=>i?.loadOlderMessages(e)??!1,onModelChange:t=>i?.switchSessionModel(e,t),onThinkingLevelChange:t=>i?.switchSessionThinkingLevel(e,t),onExecutionModeChange:t=>i?.switchSessionExecutionMode(e,t)??!1,onRunModeChange:t=>i?.switchSessionRunMode(e,t)??!1,onGoalPause:()=>i?.pauseGoal(e),onGoalBudgetChange:t=>i?.setGoalBudget(e,t),onCompact:()=>i?.compactSession(e),onApproval:(t,n)=>i?.resolveToolApproval(e,t,n),onAnswerQuestion:async(t,n)=>{await i?.answerQuestion(e,t,n)},onWorkspace:()=>{m&&i?.selectSessionWorkspace(m)},onRename:()=>{m&&i?.renameSession(m)},onBranchFromHere:(e,t)=>{if(m)return i?.branchFromEntry(m,e,t)},onCreateChildSession:e=>{if(m)return i?.createChildSession(m,e)},onRetryLastTurn:()=>i?.retryLastTurn(e),onTreeNavigated:()=>i?.reloadSessionBranch(e),onSend:(t,n,r,a,o,s,c)=>i?.sendPrompt(t,e,n,r,a,o,s,{onAccepted:c}),onQueue:(t,n,r,a)=>i?.queuePrompt(t,e,n,r,a)??!1,onWithdrawQueuedInput:t=>i?.withdrawQueuedInput(e,t)??Promise.resolve(null),onSendQueuedInputNow:t=>i?.sendQueuedInputNow(e,t)??Promise.resolve(!1),onDeliverSessionMessages:()=>i?.deliverSessionMessages(e)??Promise.resolve(),onDismissSessionMessages:()=>i?.dismissSessionMessages(e)??Promise.resolve(),onAbort:()=>i?.abort(e)}),[i,e,m]);if(!i||!m)return(0,$.jsxs)(`div`,{className:`session-dock-missing flex h-full min-h-[180px] items-center justify-center gap-2 text-sm text-content-secondary`,children:[(0,$.jsx)(Ct,{size:16}),i?`Session unavailable`:`Loading session`]});let E=i.pendingAsset?.asset&&(!i.pendingAsset.targetSessionId||i.pendingAsset.targetSessionId===e)?i.pendingAsset.asset:null,D=h.historyWindow?.messages||h.messages||es,A=h.loaded?`ready`:h.loading||!h.error?`loading`:`error`,j=!!(h.recovering&&!D.length&&!h.error),M=h.lifecycle?.phase===`completed`&&!h.error&&!h.runStopped,N=typeof h.runStartedAt==`string`?h.runStartedAt:null,P=h.goal??m.goal??null,F=_&&i.sessions.find(e=>e.id===_)?.name||``,I=_!==null&&!g&&!D.length?(0,$.jsx)(ir,{compact:!0,className:`min-h-full`,title:a(`chat:focusSession.queuedTitle`),description:F?a(`chat:focusSession.queuedAfter`,{title:F}):a(`chat:focusSession.queuedAfterUnknown`),action:(0,$.jsx)(Y,{variant:`secondary`,size:`sm`,className:`pointer-coarse:min-h-11`,onClick:()=>void X.startQueuedSession(e).then(()=>i.loadSessionMessages(e,{force:!0})).catch(e=>i.notify(Z(e),`error`)),children:a(`chat:focusSession.startQueuedNow`)})}):void 0,L=(0,$.jsx)(Zo,{session:m,emptyState:I,shortcutEnabled:n,messages:D,transcriptLoadState:j?`loading`:A,hasNewer:!!h.historyWindow,messageStart:h.historyWindow?.messageStart??h.messageStart,hasOlder:h.historyWindow?.hasOlder??h.hasOlder,loadingOlder:h.loadingOlder,olderError:h.olderError,model:h.model||m.model||i.defaultModel,thinkingLevel:h.thinkingLevel||m.thinkingLevel||`medium`,availableThinkingLevels:h.availableThinkingLevels||es,thinkingStatus:h.thinkingStatus||``,thinkingMessage:h.thinkingMessage||``,executionMode:h.executionMode||m.executionMode||`approval-required`,runMode:h.runMode||m.runMode||`plan`,goal:P,team:y,plan:b,currentActivity:h.currentActivity,activityFeed:h.activityFeed||es,tools:h.tools||es,thinkingText:h.thinkingText||``,queuedInputs:h.queuedInputs||es,workspace:h.workspace||null,withdrawingInputIds:h.withdrawingInputIds||es,compaction:h.compaction,contextUsage:h.contextUsage,sessionUsage:h.sessionUsage,sessionTreeRevision:h.sessionTreeRevision,sessionTreePulse:x,cwd:h.cwd||m.cwd,availableModels:i.availableModels,pendingRuntimeSelection:h.pendingRuntimeSelection,switchingModel:h.switchingModel,switchingThinking:h.switchingThinking,switchingCwd:h.switchingCwd,switchingPermission:h.switchingPermission,streaming:g,runStartedAt:h.runStartedAt,lastActivityAt:h.lastActivityAt,runFinishedAt:h.runFinishedAt,runStopped:h.runStopped,runNotice:h.runNotice,approvals:h.approvals||es,questions:h.questions||es,error:h.error||(i.activeId===e?i.globalError:``),pendingAsset:E,onAssetConsumed:i.onAssetConsumed,notify:i.notify,onOpenModelSettings:i.openModelSettings,onCompactionThresholdChange:i.setCompactionThreshold,...T});return(0,$.jsx)(`div`,{className:Xt(`session-dock-panel w-full h-full min-w-0 min-h-0 overflow-hidden [container-type:inline-size] bg-panel`,o&&`animate-[fade-in_var(--d-fast)_var(--ease-enter)]`),onFocusCapture:r,"data-session-panel":e,children:o?(0,$.jsx)(Ri,{sessionId:e,messages:D,cwd:h.cwd||m.cwd||``,remoteMachine:!!m.machine,active:n,plan:b,goal:P,team:y,activity:h.activityFeed?.length?h.activityFeed:h.tools||es,planTab:!!(b?.items?.length||P||y),streaming:g,completed:M,runStartedAt:N,requestConfirm:i.requestConfirm,children:L},e):(0,$.jsx)(bi,{messages:D,taskName:m.name||e,cwd:h.cwd||m.cwd||``,sessionId:e,panelId:t||`mobile-${e}`,active:n,mobile:i.mobileLayout,plan:b,streaming:g,completed:M,runStartedAt:N,plansAvailable:O(s,`plans`),requestConfirm:i.requestConfirm,children:L},e)})}function os({onNewSession:e,newSessionShortcut:t}){let{t:n}=l();return(0,$.jsxs)(`div`,{className:`flex h-full min-h-[180px] flex-col items-center justify-center gap-1.5 px-6 text-center`,children:[(0,$.jsx)(rr,{className:`mb-1.5`}),(0,$.jsx)(`strong`,{className:`text-sm font-medium text-content`,children:n(`chat:chatDock.openAChatToBegin`)}),(0,$.jsx)(`span`,{className:`max-w-[320px] text-xs leading-relaxed text-content-muted`,children:n(`chat:chatDock.openAChatFromTheSessionListOrSplitItInAnyDirection`)}),e?(0,$.jsxs)(Y,{variant:`secondary`,className:`mt-3`,onClick:()=>void e(),children:[(0,$.jsx)(ut,{"aria-hidden":`true`}),n(`chat:chatDock.newChat`),t?(0,$.jsx)(Qt,{"aria-hidden":`true`,className:`ml-1.5 pointer-coarse:hidden`,children:t.split(/\+(?=.)/).map(e=>(0,$.jsx)($t,{children:e},e))}):null]}):null]})}var ss=1e4;function cs(e,t){return{defaultModel:e.model?`${e.provider}/${e.model}`:t(`chat:chatPage.noModelConfigured`),availableModels:e.providers.flatMap(e=>e.configured&&e.enabled?e.models.filter(e=>e.kind===`chat`).map(t=>({key:`${e.id}/${t.id}`,provider:e.id,modelId:t.id,label:t.name||t.id,providerName:e.name||e.id})):[])}}function ls(e){let t=e.getQueryData(_)?.sessions,n=e.getQueryData([`config`]);return Array.isArray(t)&&t.length&&n?{sessions:t,config:n}:null}function us({notify:e}){let{t:n}=l(),r=h(),[a]=(0,Q.useState)(()=>ls(r)),[o,s]=(0,Q.useState)(()=>a?.sessions??[]),[c,u]=(0,Q.useState)(()=>i.getItem(p.activeSession)||``),[d,f]=(0,Q.useState)({}),[g,v]=(0,Q.useState)(!a),[y,b]=(0,Q.useState)(``),[x,S]=(0,Q.useState)(()=>a?cs(a.config,n).defaultModel:n(`chat:chatPage.waitingForConfiguration`)),[C,w]=(0,Q.useState)(()=>a?cs(a.config,n).availableModels:[]),T=(0,Q.useRef)(o),E=(0,Q.useRef)(d),D=(0,Q.useRef)(new Map),O=(0,Q.useRef)(null),k=(0,Q.useRef)(new Map),A=(0,Q.useRef)(new Set),j=(0,Q.useRef)(0),M=(0,Q.useRef)(0),[N]=(0,Q.useState)(Er),P=(0,Q.useCallback)(e=>{let t=T.current,n=typeof e==`function`?e(t):e;if(n===t)return n;let i=r.setQueryData(_,e=>e?{...e,sessions:n}:void 0)?.sessions??n;return i!==T.current&&(T.current=i,s(i)),i},[r]),F=(0,Q.useCallback)(()=>{if(j.current)return;let e=r.getQueryData(_)?.sessions;if(!(!Array.isArray(e)||e===T.current)){if(e.length)M.current=0;else if(T.current.length&&Date.now()<M.current)return;T.current=e,s(e)}},[r]);(0,Q.useEffect)(()=>{F();let e=m(_);return r.getQueryCache().subscribe(t=>{t.type===`updated`&&t.query.queryHash===e&&F()})},[r,F]),(0,Q.useEffect)(()=>fn(window,e=>{N.record(e),P(t=>wr(t,e))}),[N,P]),(0,Q.useEffect)(()=>en(window,e=>{P(t=>Or(t,e))}),[P]);let I=(0,Q.useCallback)(e=>{let t=A.current.size?Object.fromEntries(Object.entries(e).filter(([e])=>!A.current.has(e))):e,n=E.current;E.current=t,f(t);let i=Object.keys(t).filter(e=>t[e].streaming!==n[e]?.streaming);if(i.length){let e=new Set(i);r.setQueryData(_,n=>n&&{...n,sessions:n.sessions.map(n=>e.has(n.id)?{...n,streaming:t[n.id].streaming}:n)})}let a=new Set([...Object.keys(n),...Object.keys(t)]);for(let e of a){if(n[e]===t[e])continue;let r=D.current.get(e);if(r)for(let e of[...r])e()}},[r]);(0,Q.useEffect)(()=>tn(window,({deletedIds:e})=>{N.remove(e);let t=new Set(e),n=P(e=>e.filter(e=>!t.has(e.id)));u(e=>t.has(e)?n[0]?.id||``:e);let r=E.current;e.some(e=>e in r)&&I(Object.fromEntries(Object.entries(r).filter(([e])=>!t.has(e))))}),[I,N,P]);let L=(0,Q.useCallback)((e,t)=>{let n=D.current.get(e)||new Set;return n.add(t),D.current.set(e,n),()=>{n.delete(t),n.size||D.current.delete(e)}},[]),R=(0,Q.useCallback)(e=>E.current[e]||Me,[]),z=(0,Q.useCallback)((e,t)=>{if(!e||A.current.has(e))return;let n=E.current,r=n[e]||Me,i=ze(r,t);i!==r&&I({...n,[e]:i})},[I]);(0,Q.useEffect)(()=>pn(window,({id:e,cwd:t})=>{P(n=>n.map(n=>n.id===e?{...n,cwd:t}:n)),E.current[e]&&z(e,{cwd:t})}),[z,P]);let B=(0,Q.useCallback)((e,{panelOpen:t=!1,localStreamOwned:n=!1}={})=>{if(!e||t||n||k.current.has(e))return!1;let r=E.current,i=r[e];if(!i||Be(i))return!1;let a={...r};return delete a[e],I(a),!0},[I]),V=(0,Q.useCallback)(e=>{if(!e)return;A.current.add(e);let t={...E.current};delete t[e],I(t)},[I]),H=(0,Q.useCallback)(e=>{if(A.current.has(e))return()=>{};let t=k.current;t.set(e,(t.get(e)??0)+1);let n=!1;return()=>{if(n)return;n=!0;let r=t.get(e)??0;r>1?t.set(e,r-1):(t.delete(e),B(e))}},[B]),U=(0,Q.useCallback)(async(e,{preserveExistingOnEmpty:t=!1}={})=>{let n=N.getRevision();t&&(j.current+=1);let r;try{let e=await X.listSessions(),i=!!(t&&!e.sessions.length&&T.current.length);i&&(M.current=Date.now()+ss),r=i?T.current:N.reconcile(e.sessions,n)}finally{t&&(--j.current,F())}return P(r),u(e||(e=>r.some(t=>t.id===e)?e:r[0]?.id||``)),dn(),r},[F,N,P]),W=(0,Q.useCallback)(e=>{u(e.id),P(t=>Cr(t,[e])),z(e.id,{messages:[],tools:[],approvals:[],queuedInputs:[],permissionMode:e.permissionMode||`ask`,executionMode:e.executionMode||`approval-required`,runMode:e.runMode||`plan`,goal:e.goal||null,plan:In(e,null),contextUsage:e.contextUsage||null,sessionUsage:e.sessionUsage||null,compaction:null,streaming:!1,error:``,loaded:!0,pageSize:40,messageStart:0,hasOlder:!1,olderCursor:null,runStartedAt:null,lastActivityAt:null,runFinishedAt:null,runStopped:!1,runNotice:``})},[z,P]),ee=(0,Q.useCallback)((t=``,{inheritRecentCwd:r=!0}={})=>{if(O.current)return O.current;let i=(async()=>{try{b(``);let i=await X.createSession(n(`chat:chatPage.newChat`),Tr(t,T.current,r));W(i);try{await U(i.id)}catch(e){b(n(`chat:chatPage.theChatWasCreatedButTheListCouldNotBeRefreshedError`,{error:Z(e)}))}return e(n(`chat:chatPage.newChatCreated`)),i.id}catch(e){return b(Z(e)),``}})();return O.current=i,i.finally(()=>{O.current===i&&(O.current=null)}),i},[W,e,U,n]);(0,Q.useEffect)(()=>{let r=!0,o=N.getRevision();return(a?Promise.resolve([{sessions:a.sessions},a.config]):Promise.all([X.listSessions({refresh:!1}),X.getConfig()])).then(async([a,s])=>{if(!r)return;let c=cs(s,n);S(c.defaultModel),w(c.availableModels);let l=a.sessions;if(!l.length&&(O.current||Object.keys(E.current).length)){if(await O.current,!r)return;o=N.getRevision(),l=(await X.listSessions()).sessions}if(!r)return;l=N.reconcile(l,o),P(e=>Cr(e,l));for(let e of l)z(e.id,{team:e.team||null,agents:e.agents||[],plan:In(e,null),...e.streaming?{streaming:!0,recovering:!0,loaded:!1,error:``}:{}});let d=i.getItem(p.activeSession),f=new Set([...l.map(e=>e.id),...Object.keys(E.current)]);if(u(e=>f.has(e)?e:d&&f.has(d)?d:l[0]?.id||``),typeof window<`u`&&window.__PISPER_MOBILE_APP__)try{let{consumeRemoteFallbackNotice:r}=await t(async()=>{let{consumeRemoteFallbackNotice:e}=await import(`./mobile-remote-fallback-LLMZWoIu.js`);return{consumeRemoteFallbackNotice:e}},__vite__mapDeps([144,8]));r()&&e(n(`chat:chatPage.remoteUnavailableSwitchedToLocal`))}catch{}}).catch(async e=>{if(r){if(typeof window<`u`&&window.__PISPER_MOBILE_APP__)try{let{fallbackRemoteToLocalAfterFailure:n}=await t(async()=>{let{fallbackRemoteToLocalAfterFailure:e}=await import(`./mobile-remote-fallback-LLMZWoIu.js`);return{fallbackRemoteToLocalAfterFailure:e}},__vite__mapDeps([144,8]));if(await n(e))return}catch{}r&&b(Z(e))}}).finally(()=>r&&v(!1)),()=>{r=!1}},[e,a,n,N,z,P]),(0,Q.useEffect)(()=>{c?i.setItem(p.activeSession,c):i.removeItem(p.activeSession)},[c]);let te=o.find(e=>e.id===c),ne=(d[c]||Me).model||te?.model||``;return(0,Q.useEffect)(()=>{rn(c,ne)},[c,ne]),(0,Q.useEffect)(()=>(document.title=te?.name?`${te.name} · ${Ot}`:Ot,()=>{document.title=Ot}),[te?.name]),{sessions:o,sessionsRef:T,activeId:c,setActiveId:u,sessionStates:d,sessionStatesRef:E,loading:g,globalError:y,setGlobalError:b,defaultModel:x,availableModels:C,updateSessions:P,replaceSessionStates:I,updateSessionState:z,releaseSessionState:B,retainSessionState:H,discardSessionState:V,subscribeSessionState:L,getSessionState:R,refreshSessions:U,adoptCreatedSession:W,createSessionRecord:ee}}function ds({setActiveId:e,loadSessionMessages:t,openRoutedSession:n}){let r=(0,Q.useRef)(n);r.current=n;let i=(0,Q.useCallback)(t=>(t&&r.current?r.current(t):e(t),!0),[e]);return(0,Q.useEffect)(()=>{let e=e=>{let n=e.detail,r=n?.sessionId||n?.id;r&&(localStorage.removeItem(p.sessionOpenRequest),i(r),n?.targetEntryId&&t(r,{force:!0,limit:40}))};return window.addEventListener(sn,e),()=>window.removeEventListener(sn,e)},[t,i]),(0,Q.useEffect)(()=>tn(window,({deletedIds:e})=>{for(let t of e)xr.getState().forget(t),de(t)}),[]),{openSession:i}}function fs(e){return!!e?.agents?.some(e=>[`queued`,`starting`,`running`].includes(String(e.status)))}function ps(e,{localStreamOwned:t=!1}={}){return!e||t?!1:!!(e.recovering||e.streaming||e.approvals?.length||fs(e))}function ms(e){return e?.recovering||e?.streaming?1:3}function hs({mobile:e,reason:t,lastEventAt:n,now:r=Date.now()}){return e||t!==`visible`?!0:!n||r-n>=1e4}function gs(e){return e&&typeof e==`object`&&!Array.isArray(e)?e:null}function _s(e,t){return typeof e==`string`?e.slice(0,t):``}function vs(e){let t=gs(e),n=_s(t?.id,200);return n?{id:n,title:_s(t?.title,80)}:null}function ys(e){let t=gs(e);if(!t)return null;let n=(Array.isArray(t.neighbours)?t.neighbours:[]).map(gs).filter(e=>!!(e&&_s(e.id,200))).slice(0,5).map(e=>({id:_s(e.id,200),title:_s(e.title,80),running:e.running===!0,fileCount:Number.isSafeInteger(e.fileCount)?Number(e.fileCount):0,files:(Array.isArray(e.files)?e.files:[]).map(e=>_s(e,500)).filter(Boolean).slice(0,5),lastChangedAt:_s(e.lastChangedAt,40)})),r=(Array.isArray(t.messages)?t.messages:[]).map(gs).flatMap(e=>{let t=vs(e?.from),n=_s(e?.id,200);return e&&t&&n?[{id:n,from:t,text:_s(e.text,4e3),at:_s(e.at,40)}]:[]}).slice(0,20);return n.length||r.length?{neighbours:n,messages:r}:null}function bs(e,t){return Object.hasOwn(e,`team`)?e.team??null:t??null}var xs=new WeakMap;function Ss(e){let t=xs.get(e);return t===void 0&&(t=JSON.stringify(e),xs.set(e,t)),t}function Cs(e,t){let n=new Map(e.map(e=>[e.id,e]));return t.map(e=>{let t=n.get(e.id);return t&&Ss(t)===Ss(e)?t:e})}function ws(e,t){let n=Number(t.pageInfo?.start)||0,r=Number.isInteger(e.messageStart)?e.messageStart:null,i=r!=null&&r<=n,a=i?Math.max(0,n-r):0,o=i?r:n,s=i?[...e.messages.slice(0,a),...Cs(e.messages,t.messages)]:Cs(e.messages,t.messages),c=Math.max(0,s.length-200);return c&&(s=s.slice(c),o+=c),{messages:s,messageStart:o,hasNewer:!1,hasOlder:o>0,olderCursor:o>0?String(o):null}}function Ts(e,t){let n=new Set(e.messages.map(e=>e.id)),r=[...t.messages.filter(e=>!n.has(e.id)),...e.messages],i=r.slice(0,200);return{messages:i,messageStart:t.pageInfo.start,hasOlder:t.pageInfo.hasMore,olderCursor:t.pageInfo.nextCursor,hasNewer:!!(e.hasNewer||r.length>i.length)}}function Es(e,t){let n=Ts(e.historyWindow?{...e,...e.historyWindow}:e,t);return e.historyWindow||n.hasNewer?{...e,historyWindow:n}:{...e,...n}}function Ds(e){return{...e,historyWindow:null}}function Os(e,t,n){if(t.streaming||!e.error&&!t.error)return{page:n,error:t.error||``};let r=e.messages.at(-2),i=e.messages.at(-1);if(r?.role!==`user`||!/^user-\d+$/.test(r.id)||i?.role!==`agent`||!/^agent-\d+$/.test(i.id))return{page:n,error:t.error||``};let a=Date.parse(e.runStartedAt||``),o=n.messages.findIndex(e=>{if(e.id===r.id)return!0;if(e.role!==`user`||!Number.isFinite(a))return!1;let t=new Date(e.timestamp).getTime();return Number.isFinite(t)&&t>=a});if(o>=0&&n.messages.slice(o+1).some(e=>e.role===`agent`))return{page:n,error:t.error||``};let s=[...n.messages,...o<0?[r]:[],{...i,streaming:!1,error:t.error||e.error||i.error}],c=Math.max(0,s.length-200),l=n.messageStart+c;return{page:{...n,messages:c?s.slice(c):s,messageStart:l,hasOlder:l>0,olderCursor:l>0?String(l):null},error:t.error||e.error||``}}function ks(e,t,n=new Date().toISOString(),r=e.runtimeSelectionRevision||0){let i=r!==(e.runtimeSelectionRevision||0),a=!!(e.switchingModel||e.switchingThinking||i),o=t.finishedAt||e.runFinishedAt||n,s=Os(e,t,ws(e,t));return{...ke({...e,...s.page},t),tools:t.streaming?t.tools||[]:Rn(t.tools||[],{finishedAt:o,error:t.error||``}),streaming:t.streaming,recovering:t.streaming,runStartedAt:t.startedAt||e.runStartedAt||null,lastActivityAt:t.lastActivityAt||e.lastActivityAt||t.startedAt||null,runFinishedAt:t.streaming?null:o,runNotice:t.streaming&&e.runNotice||``,loaded:!0,loading:!1,error:a?e.error:s.error,model:a?e.model:t.model||e.model,cwd:t.cwd||e.cwd,permissionMode:t.permissionMode||e.permissionMode,executionMode:t.executionMode||e.executionMode,runMode:t.runMode||e.runMode,goal:t.goal??e.goal??null,team:bs(t,e.team),plan:In(t,e.plan??null),contextUsage:a?e.contextUsage:t.contextUsage??e.contextUsage??null,sessionUsage:t.sessionUsage??e.sessionUsage??null,compaction:t.compaction??e.compaction??null,approvals:t.approvals||[],questions:Array.isArray(t.questions)?t.questions:e.questions||[],workspace:ys(t.workspace),agents:t.agents||[],currentActivity:t.streaming?t.currentActivity||e.currentActivity||null:t.currentActivity?.type===`agent`?t.currentActivity:null,lifecycle:t.lifecycle??e.lifecycle??null,sessionTreeRevision:Number(t.sessionTreeRevision??e.sessionTreeRevision??0),activityFeed:t.streaming?t.activityFeed||e.activityFeed||[]:(t.activityFeed||[]).filter(e=>e.type===`agent`),thinkingText:t.streaming?t.thinkingText??e.thinkingText??``:``,...t.streaming?{}:{hadQueuedInput:!1}}}function As(e,{catalogStreaming:t,localStreamOwned:n}){return!e?.loaded||e.loading||e.streaming||e.recovering||n?!1:t||!e.messages?.length}function js({sessionStates:e,sessionStatesRef:t,localStreamSessionsRef:n,streamGenerationRef:r,updateSessionState:i,updateSessions:a,pollOnly:o}){let s=(0,Q.useRef)(new Set),c=(0,Q.useRef)(new Map),l=(0,Q.useRef)({timer:null,tick:0,activeSessions:new Set}),u=(0,Q.useRef)({timer:null,ids:new Set}),d=(0,Q.useCallback)(async(e,{force:o=!1}={})=>{if(!e||!o&&(n.current.has(e)||s.current.has(e)))return;let l=(c.current.get(e)||0)+1;c.current.set(e,l);let u=()=>c.current.get(e)!==l;s.current.add(e);let d=t.current[e]?.runtimeSelectionRevision||0;try{let s=await X.getLiveSession(e);if(u()||!o&&n.current.has(e))return;if(o&&n.current.has(e)){let t=r.current.get(e)||0;r.current.set(e,t+1),n.current.delete(e)}Ro(e,s),i(e,e=>ks(e,s,void 0,d)),a(n=>n.map(n=>n.id===e?{...n,streaming:s.streaming,model:t.current[e]?.model||s.model||n.model,cwd:s.cwd||n.cwd,permissionMode:s.permissionMode||n.permissionMode,executionMode:s.executionMode||n.executionMode,runMode:s.runMode||n.runMode,goal:s.goal??n.goal??null,team:bs(s,n.team),plan:In(s,n.plan??null)}:n))}catch(t){!u()&&!n.current.has(e)&&i(e,{recovering:!1,loading:!1,error:Z(t)})}finally{u()||s.current.delete(e)}},[n,t,r,i,a]),f=(0,Q.useCallback)(async(e,{force:r=!1,limit:o=40}={})=>{if(!e)return;let s=t.current[e];if(r&&s?.historyWindow){if(i(e,Ds),n.current.has(e))return;if(s.streaming||s.recovering){await d(e,{force:r});return}}if(s?.recovering){await d(e,{force:r});return}if(!(!r&&(s?.loading||s?.streaming||s?.loaded&&s.messages?.length&&(s.pageSize||0)>=o))){i(e,{loading:!0});try{let r=await X.getMessages(e,{limit:o}),s=r.streaming===!0&&!n.current.has(e),c=!1;i(e,t=>t.streaming&&!t.loaded&&!t.messages?.length&&!n.current.has(e)?(c=!0,{...t,loading:!1,pageSize:Math.max(t.pageSize||0,o)}):t.streaming?{...t,loaded:!0,loading:!1,pageSize:Math.max(t.pageSize||0,o)}:(s&&(c=!0),{...t,...ws(t,r),...s?{streaming:!0,recovering:!0}:{},model:t.model||r.model||void 0,contextUsage:r.contextUsage??t.contextUsage??null,sessionUsage:r.sessionUsage??t.sessionUsage??null,workspace:ys(r.workspace),loaded:!0,loading:!1,pageSize:Math.max(t.pageSize||0,o),error:``,olderError:``})),c&&d(e);let l=t.current[e]?.model||(typeof r.model==`string`?r.model:``);l&&a(t=>t.map(t=>t.id===e&&t.model!==l?{...t,model:l}:t))}catch(t){i(e,{loading:!1,error:Z(t)})}}},[n,t,d,i,a]),p=(0,Q.useCallback)(async e=>{let n=t.current[e],r=n?.historyWindow?{...n,...n.historyWindow}:n;if(!e||!r?.hasOlder||!r.olderCursor||n.loadingOlder)return!1;let a=n.historyWindow??null;i(e,{loadingOlder:!0,olderError:``});try{let t=await X.getMessages(e,{limit:40,before:r.olderCursor});return i(e,e=>{let n=e.historyWindow||e;return(e.historyWindow??null)!==a||n.olderCursor!==r.olderCursor?{...e,loadingOlder:!1}:{...Es(e,t),loadingOlder:!1,olderError:``}}),t.messages.length>0}catch(t){return i(e,{loadingOlder:!1,olderError:Z(t)}),!1}},[t,i]),m=(0,Q.useCallback)(()=>{l.current.timer&&window.clearInterval(l.current.timer),l.current.timer=null,l.current.activeSessions.clear()},[]),h=(0,Q.useCallback)(()=>{l.current.timer||!l.current.activeSessions.size||(l.current.timer=window.setInterval(()=>{if(typeof document<`u`&&document.hidden)return;l.current.tick+=1;let e=l.current.tick,r=Array.from(l.current.activeSessions).map(async r=>{let i=t.current[r];if(!ps(i,{localStreamOwned:n.current.has(r)})){l.current.activeSessions.delete(r);return}e%ms(i)===0&&await d(r)});Promise.allSettled(r).then(()=>{l.current.activeSessions.size||m()})},2e3))},[n,t,m,d]);return(0,Q.useEffect)(()=>{let t=new Set(Object.keys(e));for(let e of l.current.activeSessions)t.has(e)||l.current.activeSessions.delete(e);let r=[];for(let[t,i]of Object.entries(e)){let e=(o===void 0||t===o)&&ps(i,{localStreamOwned:n.current.has(t)});e&&!l.current.activeSessions.has(t)&&r.push(t),e?l.current.activeSessions.add(t):l.current.activeSessions.delete(t)}if(l.current.activeSessions.size?h():m(),!r.length)return;let i=u.current;for(let e of r)i.ids.add(e);i.timer===null&&(i.timer=window.setTimeout(()=>{i.timer=null;let e=Array.from(i.ids);if(i.ids.clear(),!(typeof document<`u`&&document.hidden))for(let t of e)l.current.activeSessions.has(t)&&d(t)},0))},[h,n,o,e,m,d]),(0,Q.useEffect)(()=>{let e=u.current;return()=>{m(),e.timer!==null&&window.clearTimeout(e.timer),e.timer=null,e.ids.clear()}},[m]),{syncLiveSession:d,loadSessionMessages:f,loadOlderMessages:p,liveSyncInFlightRef:s}}function Ms(e,t){let n=null,r=!1,i=typeof document<`u`,a=()=>!i||document.visibilityState===`visible`,o=()=>{r&&=(document.removeEventListener(`visibilitychange`,c),!1)},s=()=>{n=setTimeout(()=>{n=null,e()},t)},c=()=>{!a()||n!=null||(o(),s())},l=()=>{!i||r||(document.addEventListener(`visibilitychange`,c),r=!0)};return{schedule(){n!=null||r||(a()?s():l())},flushNow(){n!=null&&(clearTimeout(n),n=null),o(),e()},cancel(){n!=null&&clearTimeout(n),n=null,o()},get active(){return n!=null||r}}}function Ns(e,{intervalMs:t=48}={}){let n=null,r=null,i=Ms(()=>{if(n==null)return;let t=n,i=r;n=null,r=null,e(t,i)},t);return{push(e,t=new Date().toISOString()){n=e,r=t,i.schedule()},flush(){i.flushNow()},cancel(){i.cancel(),n=null,r=null}}}function Ps(e,{intervalMs:t=80}={}){let n=new Map,r=null,i=Ms(()=>{if(!n.size)return;let t=n,i=r;n=new Map,r=null,e(t,i)},t);return{push(e,t,a=new Date().toISOString()){e&&(n.set(e,{...n.get(e)||{},...t}),r=a,i.schedule())},flush(){i.flushNow()},cancel(){i.cancel(),n=new Map,r=null}}}function Fs(e){return e>=55296&&e<=56319}function Is(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&e.charCodeAt(r)===t.charCodeAt(r);)r+=1;return r>0&&Fs(e.charCodeAt(r-1))?r-1:r}var Ls=50;function Rs(e,{minCharsPerSecond:t=36,maxCharsPerSecond:n=1200,catchUpRemaining:r=160,requestFrame:i,cancelFrame:a,isCurrent:o=()=>!0,now:s=()=>typeof performance<`u`&&performance.now?performance.now():Date.now()}={}){let c=!i&&typeof globalThis.requestAnimationFrame==`function`&&typeof globalThis.cancelAnimationFrame==`function`,l=i||(c?globalThis.requestAnimationFrame.bind(globalThis):e=>setTimeout(()=>e(s()),Math.ceil(Ls))),u=a||(c?globalThis.cancelAnimationFrame.bind(globalThis):clearTimeout),d=typeof document<`u`?document:null,f=()=>!d||d.visibilityState===`visible`,p=``,m=``,h=null,g=null,_=0,v=null,y=0,b=!1,x=new Set,S=e=>{let t=[...x];x.clear();for(let n of t)n(e)},C=()=>{m.length,e(m,h)},w=()=>{b=!0,g!=null&&u(g),d?.removeEventListener(`visibilitychange`,O),g=null,y=0,S(!1)},T=()=>{if(!b){if(!o()){w();return}g!=null&&u(g),g=null,y=0,m=p,v=s(),C(),m===p&&S(!0)}},E=e=>{if(g=null,b)return;if(!o()){w();return}if(!f()){x.size&&T();return}if(p===m){S(!0);return}let i=e-_;if(i+.001<Ls||v!=null&&e-v+.001<Ls){g=l(E);return}_=e;let a=m;p.startsWith(m)||(m=p.slice(0,Is(m,p)),y=0);let s=p.length-m.length;if(s>=480)m=p,y=0;else{let e=Math.max(0,Math.min(n,t+s*(s>=r?10:4))),a=y+e*Math.min(.08,Math.max(0,i/1e3)),o=Math.floor(a+1e-9);y=Math.max(0,a-o);let c=m.length;for(let e=0;e<o&&c<p.length;e+=1){let e=p.codePointAt(c)??0;if(Fs(e)&&c+1===p.length&&!x.size)break;c+=e>65535?2:1}m=p.slice(0,c)}m!==a&&(v=e,C()),m===p&&S(!0);let c=!x.size&&m.length+1===p.length&&Fs(p.charCodeAt(m.length));!b&&g==null&&m!==p&&!c&&f()?g=l(E):g??(y=0)},D=()=>{b||g!=null||!f()||p===m||(_=s(),g=l(E))},O=()=>{f()?D():x.size?T():(g!=null&&u(g),g=null,y=0)};return d?.addEventListener(`visibilitychange`,O),{setTarget(e,t=new Date().toISOString()){b||(p=String(e||``),h=t,D())},drain(){return b||!o()?(w(),Promise.resolve(!1)):m===p?Promise.resolve(!0):new Promise(e=>{x.add(e),f()?D():T()})},flush:T,cancel:w,getShown:()=>m,getTarget:()=>p}}var zs=new Set(`contacts.search,camera.capture,location.current,device.info,device.capabilities,device.battery,device.storage,device.memory,device.network,device.display,device.locale,device.status,device.clipboard.get,device.clipboard.set,device.vibrate,device.flashlight,device.notify,photos.list,photos.create_album,photos.add_to_album,photos.delete,apps.open_url,apps.open_map,apps.open_system_settings,apps.open_dialer,apps.compose_sms,apps.open_app,apps.share_text`.split(`,`)),Bs=new Map,Vs=[];function Hs(e,t){let n=window.__TAURI__?.core?.invoke??window.__TAURI_INTERNALS__?.invoke;return n?n(e,t):Promise.reject(Error(`native bridge unavailable`))}async function Us(e,t){let n=String(t.id||``),r=String(t.operation||``);if(!n||!zs.has(r))return;let i=Date.parse(String(t.expiresAt||``));if(Number.isFinite(i)&&i<=Date.now()){await X.resolveMobileOperation(e,n,{ok:!1,error:`移动设备操作请求已过期。`});return}try{let i=await Hs(`mobile_execute_device_operation`,{request:{id:n,operation:r,parameters:t.parameters&&typeof t.parameters==`object`?t.parameters:void 0}});await X.resolveMobileOperation(e,n,{ok:!0,result:i})}catch(t){await X.resolveMobileOperation(e,n,{ok:!1,error:t instanceof Error?t.message:String(t)})}finally{Vs.push(n),Vs.length>128&&Vs.splice(0,Vs.length-128)}}function Ws(e){let t=String(e.id||``);!t||Vs.includes(t)||(Vs.push(t),Vs.length>128&&Vs.splice(0,Vs.length-128))}function Gs(e,t){let n=String(t.id||``);if(!n||Vs.includes(n)||Bs.has(n))return;let r=Us(e,t).catch(()=>{}).finally(()=>Bs.delete(n));Bs.set(n,r)}function Ks(e){let t=String(e.path||``).trim().replaceAll(`\\`,`/`).toLowerCase();return t?`path:${t}`:`id:${e.id}`}function qs(e,t){return Object.hasOwn(e,`team`)?e.team??null:t??null}function Js(e,{agentId:t,responseText:n,data:r,finishedAt:i,error:a,preserveDisplayedText:o}){let s=!!a,c=r.lifecycle||e.lifecycle||{},l=ke(e,r);return{...l,streaming:!1,runFinishedAt:i,lastActivityAt:i,...s?{}:{runNotice:``},currentActivity:r.currentActivity?.type===`agent`?r.currentActivity:null,lifecycle:{...c,phase:s?`failed`:`completed`,event:s?`runtime_error`:`runtime_done`,updatedAt:i},sessionTreeRevision:Number(r.sessionTreeRevision??e.sessionTreeRevision??0),activityFeed:(r.activityFeed||[]).filter(e=>e.type===`agent`),goal:s?e.goal:r.goal??e.goal??null,plan:s?e.plan:In(r,e.plan),team:qs(r,e.team),agents:r.agents||e.agents||[],contextUsage:r.contextUsage??e.contextUsage??null,sessionUsage:r.sessionUsage??e.sessionUsage??null,compaction:r.compaction??e.compaction??null,approvals:s?[]:r.approvals||[],tools:Rn(r.tools||e.tools,{finishedAt:i,...a?{error:a}:{}}),messages:l.messages.map(e=>e.id===t?{...e,text:o?e.text:typeof r.text==`string`?r.text:n||e.text,streaming:o?e.text!==n:!1,...s?{}:r.turnBoundaryEntryId?{turnBoundaryEntryId:String(r.turnBoundaryEntryId)}:{},...s?{}:r.assets?.length?{attachments:r.assets}:{}}:e)}}function Ys({sessionId:e,agentId:t,sessionStatesRef:n,updateSessionState:r,updateSessions:i,typewriter:a,thinkingScheduler:o,toolScheduler:s,t:c}){let l={responseText:``,responseRenderingStreaming:!0,thinkingText:``,thinkingPrefix:``,queuedDuringRun:!1,pendingInputIds:[]},u=e=>(Array.isArray(e)?e:[]).map(e=>typeof e?.id==`string`?e.id:``).filter(Boolean),d=(i,o)=>{let s=u(i.queuedInputs),c=new Set([...n.current[e]?.withdrawnInputIds||[],...typeof i.removedInputId==`string`?[i.removedInputId]:[]]),d=l.pendingInputIds.filter(e=>!s.includes(e)&&!c.has(e));if(l.pendingInputIds=s,!d.length)return;let f=new Set(u((i.sendNowInputIds||[]).map(e=>({id:e})))),p=l.responseText;l.responseText=``,r(e,e=>De(e,{agentId:t,deliveredIds:d,frozenText:p,interrupted:d.some(e=>f.has(e))})),p&&(a.setTarget(``,o),a.flush())},f=t=>{i(n=>n.map(n=>n.id===e?t(n):n))},p=(r,i)=>{let a=n.current[e]?.messages??[],o=a.findIndex(e=>e.id===t),s=a.slice(0,Math.max(0,o)).filter(e=>e.role===`user`).at(-1)?.text;Lo({sessionId:e,messageId:t,prompt:s,text:l.responseText,runId:l.runId,startedAt:l.startedAt,status:r,error:i})};return{dispatch:(i,m)=>{let h=new Date().toISOString();if(i===`run`)l.runId=typeof m.runId==`string`?m.runId:void 0,p(`started`);else if(i===`resync_required`)p(`recovering`);else if(i===`meta`)l.startedAt=typeof m.startedAt==`string`?m.startedAt:void 0,Array.isArray(m.queuedInputs)&&(l.pendingInputIds=u(m.queuedInputs)),p(`started`),r(e,e=>({...ke(e,m),model:m.model||e.model,thinkingLevel:m.thinkingLevel||e.thinkingLevel,cwd:m.cwd,permissionMode:m.permissionMode,executionMode:m.executionMode,runMode:m.runMode||e.runMode,goal:m.goal??null,plan:In(m,e.plan),team:qs(m,e.team),agents:m.agents||e.agents||[],currentActivity:m.currentActivity||e.currentActivity||null,activityFeed:m.activityFeed||e.activityFeed||[],lifecycle:m.lifecycle??e.lifecycle??null,sessionTreeRevision:Number(m.sessionTreeRevision??e.sessionTreeRevision??0),thinkingText:m.thinkingText??e.thinkingText??``,contextUsage:m.contextUsage??e.contextUsage??null,sessionUsage:m.sessionUsage??e.sessionUsage??null,runStartedAt:m.startedAt||e.runStartedAt,lastActivityAt:m.lastActivityAt||h})),(m.model||m.thinkingLevel||m.cwd||m.permissionMode||m.executionMode||m.goal!==void 0||m.team!==void 0||Ln(m)!==void 0)&&f(e=>({...e,model:m.model||e.model,thinkingLevel:m.thinkingLevel||e.thinkingLevel,cwd:m.cwd||e.cwd,permissionMode:m.permissionMode||e.permissionMode,executionMode:m.executionMode||e.executionMode,runMode:m.runMode||e.runMode,goal:m.goal??e.goal??null,team:qs(m,e.team),plan:In(m,e.plan??null)}));else if(i===`queue_update`)m.queuedInputs?.length&&(l.queuedDuringRun=!0),r(e,e=>ke(e,{...m,queuedInputs:m.queuedInputs||[]})),d(m,h);else if(i===`agent_update`)r(e,e=>{let t=m.currentActivity||(m.agent?{type:`agent`,agent:m.agent,updatedAt:m.agent.lastActivityAt||h}:null);return{...e,team:qs(m,e.team),agents:m.agents||[],currentActivity:e.currentActivity?.type===`tool`?e.currentActivity:t||e.currentActivity,activityFeed:t?Vn(e.activityFeed,t):e.activityFeed,lastActivityAt:m.agent?.lastActivityAt||h}}),Object.hasOwn(m,`team`)&&f(e=>({...e,team:qs(m,e.team)}));else if(i===`agent_lifecycle`)r(e,e=>{let t=m.lifecycle||e.lifecycle,n=t?.event===`auto_retry_end`,r=t?.event===`turn_start`&&(e.lifecycle?.phase===`retrying`||e.currentActivity?.type===`retry`);return{...e,lifecycle:t,currentActivity:m.currentActivity||e.currentActivity,lastActivityAt:t?.updatedAt||h,runNotice:n&&t?.retry?.success?``:n&&t?.retry?.message?t.retry.message:r?``:e.runNotice}});else if(i===`session_tree_changed`)r(e,{sessionTreeRevision:Number(m.revision||0),lastActivityAt:h});else if(i===`thinking_level_changed`)r(e,{thinkingLevel:m.level,lastActivityAt:h}),f(e=>({...e,thinkingLevel:m.level}));else if(i===`context_usage`)r(e,{contextUsage:m});else if(i===`session_usage`)r(e,{sessionUsage:m});else if(i===`compaction_start`)s.flush(),r(e,e=>{let t={type:`compaction`,compaction:m,updatedAt:m.startedAt||h};return{...e,compaction:m,currentActivity:t,activityFeed:Vn(e.activityFeed,t),lastActivityAt:m.startedAt||h}});else if(i===`compaction_end`)r(e,e=>{let t={type:`model`,stage:`processing_result`,updatedAt:m.finishedAt||h};return{...e,compaction:m,currentActivity:t,activityFeed:Vn(e.activityFeed,t),lastActivityAt:m.finishedAt||h}});else if(i===`text_patch`)l.responseRenderingStreaming=!0,l.responseText=E(l.responseText,m),p(`streaming`),a.setTarget(l.responseText,h);else if(i===`text_delta`)l.responseText.length,l.responseRenderingStreaming=!0,l.responseText+=m.delta||``,p(`streaming`),a.setTarget(l.responseText,h);else if(i===`text_end`)l.responseText.length,typeof m.text==`string`&&(l.responseText=m.text),l.responseRenderingStreaming=!1,p(`streaming`),a.setTarget(l.responseText,m.updatedAt||h),r(e,e=>({...e,messages:e.messages.map(e=>e.id===t?{...e,streaming:e.text!==l.responseText}:e)}));else if(i===`thinking_reset`)l.thinkingText=``,l.thinkingPrefix=String(m.thinkingText||``).slice(-6e3),o.cancel(),r(e,{thinkingText:l.thinkingPrefix,currentActivity:{type:`model`,stage:`thinking`,updatedAt:m.updatedAt||h},lastActivityAt:m.updatedAt||h});else if(i===`thinking_patch`){l.thinkingText=E(l.thinkingText,m).slice(-6e3);let e=[l.thinkingPrefix,l.thinkingText].filter(Boolean).join(`
|
|
552
552
|
|
|
553
|
-
`);o.push(e.slice(-6e3),h)}else if(i===`tool_start`)o.flush(),s.flush(),r(e,e=>{let t={type:`tool`,id:m.id,name:m.name,args:m.args,status:`running`,startedAt:m.startedAt||h,updatedAt:h,...m.output===void 0?{}:{output:m.output}};return{...e,lastActivityAt:h,runNotice:``,tools:zn(e.tools,t),currentActivity:t,activityFeed:zn(e.activityFeed,t)}});else if(i===`tool_update`)s.push(m.id,{message:m.message||``,updatedAt:m.updatedAt||h,...m.output===void 0?{}:{output:m.output},...m.agent?{agent:m.agent}:{},...m.previewImage?{previewImage:m.previewImage}:{}},m.updatedAt||h);else if(i===`tool_end`)s.flush(),r(e,e=>{let t=e.tools.find(e=>e.id===m.id),n=m.finishedAt||h,r=String(t?.name||``),i=(In(r)||[`spawn_agent`,`list_agents`,`send_message`,`followup_task`,`wait_agent`,`interrupt_agent`].includes(r))&&[`plan`,`agent`].includes(e.currentActivity?.type),a={...t||{},type:`tool`,status:m.error?`error`:`done`,message:m.message||t?.message||``,updatedAt:n,finishedAt:n,...m.output===void 0?{}:{output:m.output},...m.previewImage?{previewImage:m.previewImage}:{},...m.target?{target:m.target}:{}},o=m.agent?{type:`agent`,agent:m.agent,updatedAt:m.agent.lastActivityAt||n}:null,s=e.activityFeed||[];return(m.error||!i&&!o)&&(s=zn(s,a)),o&&(s=zn(s,o)),{...e,lastActivityAt:n,tools:e.tools.map(e=>e.id===m.id?{...e,status:m.error?`error`:`done`,message:m.message||``,updatedAt:n,finishedAt:n,...m.output===void 0?{}:{output:m.output},...m.previewImage?{previewImage:m.previewImage}:{},...m.target?{target:m.target}:{}}:e),currentActivity:m.error?a:o||(i?e.currentActivity:a),activityFeed:s}});else if(i===`mobile_operation_request`)Gs(e,m);else if(i===`mobile_operation_cancel`)Ws(m);else if(i===`permission_request`)s.flush(),r(e,e=>({...e,lastActivityAt:h,approvals:[...(e.approvals||[]).filter(e=>e.id!==m.id),m]}));else if(i===`permission_resolved`)r(e,e=>({...e,lastActivityAt:h,approvals:(e.approvals||[]).filter(e=>e.id!==m.id)}));else if(i===`question_request`){s.flush();let t=typeof m.id==`string`?m.id:m.questionId;r(e,e=>({...e,lastActivityAt:h,questions:[...(e.questions||[]).filter(e=>(e.id??e.questionId)!==t),m]}))}else if(i===`question_resolved`){let t=typeof m.questionId==`string`?m.questionId:m.id;r(e,e=>({...e,lastActivityAt:h,questions:(e.questions||[]).filter(e=>(e.id??e.questionId)!==t)}))}else if(i===`generated_asset`)r(e,e=>({...e,lastActivityAt:h,messages:e.messages.map(e=>e.id===t?{...e,attachments:[...(e.attachments||[]).filter(e=>Ks(e)!==Ks(m)),m]}:e)}));else if(i===`goal_update`)r(e,e=>({...e,goal:m.goal??null,team:qs(m,e.team)})),f(e=>({...e,goal:m.goal??null,team:qs(m,e.team)}));else if(Bn(i))s.flush(),r(e,e=>{let t=Ln(m,e.plan),n=m.currentActivity||{type:`plan`,plan:t,changes:Rn(e.plan,t),updatedAt:t?.updatedAt||h};return{...e,lastActivityAt:h,plan:t,currentActivity:n,activityFeed:zn(e.activityFeed,n)}}),f(e=>({...e,plan:Ln(m,e.plan??null)}));else if(i===`session_title`)f(e=>({...e,name:m.name}));else if(i===`model_fallback`){let t=typeof m.model==`string`?m.model:``;if(!t)return;let n=c(`chat:requestNotice.modelFallback`,{model:typeof m.modelId==`string`&&m.modelId?m.modelId:t});r(e,e=>{let r={type:`retry`,message:m.message,summary:n,updatedAt:h};return{...e,model:t,...typeof m.thinkingLevel==`string`?{thinkingLevel:m.thinkingLevel}:{},runNotice:n,currentActivity:r,activityFeed:zn(e.activityFeed,r),lastActivityAt:h}}),f(e=>({...e,model:t,...typeof m.thinkingLevel==`string`?{thinkingLevel:m.thinkingLevel}:{}}))}else if(i===`retry`){let t=c(`chat:requestNotice.retryingAttempt`,{attempt:m.attempt,maxAttempts:m.maxAttempts});r(e,e=>{let n={type:`retry`,message:m.message,summary:t,updatedAt:h};return{...e,runNotice:t,currentActivity:n,activityFeed:zn(e.activityFeed,n),lastActivityAt:h}})}else if(i===`done`||i===`error`){l.queuedDuringRun||=!!(n.current[e]?.hadQueuedInput||n.current[e]?.queuedInputs?.length);let c=m.finishedAt||h;typeof m.text==`string`&&(l.responseText=m.text),l.responseRenderingStreaming=!1,l.terminal=!0;let u=i===`error`?S(m,String(m.message||``)):``;if(p(i===`done`?`completed`:`failed`,i===`error`?u||`Speech response failed.`:void 0),a.setTarget(l.responseText,c),i===`error`&&a.flush(),o.flush(),s.cancel(),r(e,e=>Js(e,{agentId:t,responseText:l.responseText,data:m,finishedAt:c,preserveDisplayedText:i===`done`,...i===`error`?{error:u}:{}})),i===`done`)return f(e=>({...e,streaming:!1,goal:m.goal??e.goal??null,team:qs(m,e.team),plan:Ln(m,e.plan??null)})),!1;throw Error(m.message)}},state:l}}var Xs=`pisper:usage-updated`;function Zs({browserNotify:e,notify:t,defaultModel:n,localStreamSessionsRef:r,streamGenerationRef:i,streamActivityRef:a,sessionStatesRef:o,setActiveId:s,setGlobalError:c,updateSessionState:u,updateSessions:d,createSession:f,loadSessionMessages:p,refreshSessions:m,syncLiveSession:h}){let{t:g}=l(),_=(0,Q.useRef)(new Map),v=(0,Q.useRef)(new Set),y=(0,Q.useRef)(new Map),b=(0,Q.useCallback)(async(t,l,v=[],y=!1,b=!1,x=null,S=null,C={})=>{let w=C.retryFromIndex,T=w==null?t.trim()||(v.length?g(`chat:chatPage.pleaseAnalyzeTheseAttachments`):``)||(S?S.resourceName:``):t;if(!T&&!S)return!1;let E=l;if(E||=await f(),!E||o.current[E]?.streaming)return!1;o.current[E]?.historyWindow&&await p(E,{force:!0});let D=o.current[E];if(D?.streaming)return!1;if(w!=null){let e=-1;for(let t=(D?.messages.length||0)-1;t>=0;--t)if(D.messages[t]?.role===`user`){e=t;break}let t=D?.messages[e];if(!t||C.retryUserMessageId&&t.id!==C.retryUserMessageId)return!1;w=e,T=t.text||``,v=t.attachments||[]}let O=o.current[E];if(O?.pendingRuntimeSelection||O?.switchingModel||O?.switchingThinking)return!1;let k=(i.current.get(E)||0)+1;i.current.set(E,k);let A=!1,j=()=>!A&&i.current.get(E)===k,M=()=>{},N=new Promise(e=>{M=e});_.current.set(E,{promise:N,resolve:M}),C.activate!==!1&&(s(E),c(``));let P={id:`user-${Date.now()}`,role:`user`,text:T,invocation:S,attachments:v.map(({id:e,kind:t,name:n,mimeType:r,size:i,data:a})=>({id:e,kind:t,name:n,mimeType:r,size:i,data:t===`image`?a:void 0}))},F=`agent-${Date.now()}`,I=new Date().toISOString(),L={responseText:``,responseRenderingStreaming:!0,thinkingText:``,thinkingPrefix:``,queuedDuringRun:!1,pendingInputIds:[]},R=Ns((e,t)=>{j()&&u(E,n=>j()?{...n,thinkingText:e,lastActivityAt:t||n.lastActivityAt,currentActivity:{type:`model`,stage:`thinking`,updatedAt:t||n.lastActivityAt}}:n)},{intervalMs:80}),z=Rs((e,t)=>{j()&&u(E,n=>{if(!j())return n;let r=n.messages.map(t=>t.id===F?{...t,text:e,streaming:L.responseRenderingStreaming||e!==L.responseText}:t);if(L.terminal||!L.responseRenderingStreaming||n.currentActivity&&n.currentActivity.type!==`model`)return{...n,messages:r};let i={type:`model`,stage:`responding`,updatedAt:t||n.lastActivityAt};return{...n,lastActivityAt:t||n.lastActivityAt,runNotice:``,currentActivity:i,activityFeed:zn(n.activityFeed,i),messages:r}})},{isCurrent:j}),B=Ps((e,t)=>{j()&&u(E,n=>{if(!j())return n;let r=n.activityFeed||[];for(let[n,i]of e){let e=r.find(e=>e.type===`tool`&&e.id===n);e&&(r=zn(r,{...e,...i,updatedAt:t||e.updatedAt}))}let i=n.currentActivity?.type===`tool`&&e.has(n.currentActivity.id)?{...n.currentActivity,...e.get(n.currentActivity.id),updatedAt:t||n.currentActivity.updatedAt}:n.currentActivity;return{...n,lastActivityAt:t||n.lastActivityAt,tools:n.tools.map(t=>{let n=e.get(String(t.id||``));return n?{...t,...n}:t}),currentActivity:i,activityFeed:r}})}),V=Ys({sessionId:E,agentId:F,sessionStatesRef:o,updateSessionState:u,updateSessions:d,typewriter:z,thinkingScheduler:R,toolScheduler:B,t:g}),H=!1,U=(e,t)=>j()?(a?.current.set(E,Date.now()),!H&&(e===`run`||e===`meta`)&&(H=!0,C.onAccepted?.()),e===`resync_required`?(V.dispatch(e,t),A=!0,i.current.delete(E),r.current.delete(E),h(E),!1):V.dispatch(e,t)):!1;L=V.state,u(E,e=>{let t=y||b||e.goal?.status===`active`;return{...e,messages:[...w==null?e.messages:e.messages.slice(0,w),P,{id:F,role:`agent`,text:``,streaming:!0}],tools:[],approvals:[],error:``,streaming:!0,loaded:!0,runStartedAt:I,lastActivityAt:I,runFinishedAt:null,runStopped:!1,runNotice:``,currentActivity:{type:`model`,stage:`thinking`,updatedAt:I},activityFeed:[],lifecycle:{phase:`starting`,event:`prompt_submitted`,turn:0,updatedAt:I},thinkingText:``,hadQueuedInput:!1,withdrawnInputIds:[],queuedInputRunId:F,compaction:null,plan:t?e.plan:null}}),!y&&!b&&d(e=>e.map(e=>e.id!==E||e.goal?.status===`active`?e:{...e,plan:null})),r.current.add(E),a?.current.set(E,Date.now());let W=!1;try{if(w==null?await X.openStream({sessionId:E,message:T,attachments:v,goalMode:y,teamMode:b,goalTokenBudget:x,invocation:S},U):await X.retryLastTurn(E,U),!j())return H;L.responseRenderingStreaming=!1,L.terminal=!0,z.setTarget(L.responseText),R.flush(),B.flush();let t=new Date().toISOString();if(o.current[E]?.streaming&&u(E,e=>{let n=e.runFinishedAt||t;return{...e,streaming:!1,runFinishedAt:n,lastActivityAt:n,runNotice:``,currentActivity:null,activityFeed:[],approvals:[],tools:Vn(e.tools,{finishedAt:n}),messages:e.messages.map(e=>e.id===F?{...e,streaming:e.text!==L.responseText}:e)}}),!await z.drain()||!j()||(u(E,e=>({...e,messages:e.messages.map(e=>e.id===F?{...e,text:L.responseText,streaming:!1}:e)})),!j()))return H;let r=!!(L.queuedDuringRun||o.current[E]?.hadQueuedInput);(y||b||r||o.current[E]?.goal||o.current[E]?.queuedInputs?.length)&&u(E,{queuedInputs:[],hadQueuedInput:!1});let i;try{i=(await m()).find(e=>e.id===E)}catch{h(E)}if(!j()||(r&&await p(E,{force:!0}).catch(()=>void 0),!j()))return H;C.activate!==!1&&e?.(`chat.completed`,{chat:{title:i?.name||g(`chat:chatPage.appChat`,{app:`Pisper`}),summary:L.responseText.trim().slice(0,260)||g(`chat:chatPage.theAgentHasFinishedResponding`),model:o.current[E]?.model||n}})}catch(e){if(!j())return H;if((L.runId||L.startedAt)&&!L.terminal)return V.dispatch(`resync_required`,{}),A=!0,i.current.delete(E),r.current.delete(E),h(E),H;W=!0,z.cancel(),R.flush(),B.cancel();let t=new Date().toISOString(),n=Z(e);if(u(E,e=>({...e,streaming:!1,error:n,runFinishedAt:t,lastActivityAt:t,runNotice:``,currentActivity:null,activityFeed:[],approvals:[],tools:Vn(e.tools,{finishedAt:t,error:n}),messages:e.messages.map(e=>e.id===F?{...e,streaming:!1,error:n,text:e.text||L.responseText}:e)})),L.queuedDuringRun||o.current[E]?.hadQueuedInput||o.current[E]?.queuedInputs?.length){try{await p(E,{force:!0})}catch{}u(E,{queuedInputs:[],hadQueuedInput:!1})}d(e=>e.map(e=>e.id===E?{...e,streaming:!1}:e))}finally{let e=j();if(A=!0,e&&(r.current.delete(E),i.current.delete(E),u(E,{streaming:!1,hadQueuedInput:!1}),_.current.get(E)?.promise===N&&_.current.delete(E)),z.cancel(),R.cancel(),B.cancel(),M(),window.dispatchEvent(new Event(Xs)),W&&e)h(E);else if(e){let e=o.current[E];(e?.recovering||e&&!e.loaded)&&h(E)}}return H},[e,f,n,p,r,m,i,a,o,s,c,h,g,u,d]),x=(0,Q.useCallback)(async(e,n,r=[],i=`steer`,a)=>{let s=String(e||``).trim()||(r.length?g(`chat:chatPage.pleaseAnalyzeTheseAttachments`):``);if(!n||!s)return!1;o.current[n]?.historyWindow&&await p(n,{force:!0});let c=o.current[n]?.queuedInputRunId;try{let e=await X.queueInput(n,s,r,i),t=new Date().toISOString(),a={id:`interactive-user-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,role:`user`,text:s,queuedAt:t,queuedInputId:e.inputId||void 0,streamingBehavior:e.behavior||i,attachments:r.map(({id:e,kind:t,name:n,mimeType:r,size:i,data:a})=>({id:e,kind:t,name:n,mimeType:r,size:i,data:t===`image`?a:void 0}))};return u(n,n=>{let r=ke(n,e),i=!r.withdrawnInputIds?.includes(e.inputId)&&n.queuedInputRunId===c,o=!!(e.inputId&&r.deliveredInputIds?.includes(e.inputId));return{...r,messages:i?Oe(r.messages,{...a,queuedPending:!!e.inputId&&!o}):r.messages,hadQueuedInput:!0,lastActivityAt:t}}),!0}catch(e){if(pr(e)){let e=_.current.get(n);return e?await e.promise:await h(n),u(n,{streaming:!1,recovering:!1,queuedInputs:[],hadQueuedInput:!1}),await p(n,{force:!0}),await b(s,n,r,!1,!1,null,null,{onAccepted:a})??!1}return t(Z(e),`error`),!1}},[p,t,b,o,h,g,u]),S=(0,Q.useCallback)(e=>{if(!e)return Promise.resolve();let n=o.current[e],r=y.current.get(e);if(r?.matchesRun(n))return r.promise;let i=n?.runStartedAt,a=n?.queuedInputRunId,s=!!n?.runStopped,c=e=>!!(e&&(a?e.queuedInputRunId===a:!e.queuedInputRunId&&e.runStartedAt===i));u(e,{runStopped:!0});let l=(async()=>{let n;try{n=await X.abort(e)}catch(t){let n=o.current[e];throw c(n)&&n?.runStopped&&u(e,{runStopped:s}),t}if(!c(o.current[e])||(await h(e,{force:!0}),!c(o.current[e])))return;let r=new Date().toISOString();u(e,e=>({...e,streaming:!1,queuedInputs:[],hadQueuedInput:!1,goal:n.goal??null,team:Object.hasOwn(n,`team`)?n.team??null:e.team,compaction:e.compaction?.active?{...e.compaction,active:!1,status:`aborted`,aborted:!0,finishedAt:r}:e.compaction,runFinishedAt:r,lastActivityAt:r,runStopped:!0,runNotice:``,approvals:[],tools:Vn(e.tools,{finishedAt:r,error:g(`chat:chatPage.stopped`)}),messages:e.messages.map(e=>e.streaming?{...e,streaming:!1}:e)})),d(t=>t.map(t=>t.id===e?{...t,streaming:!1,goal:n.goal??t.goal??null,team:Object.hasOwn(n,`team`)?n.team??null:t.team}:t)),t(g(`chat:chatPage.currentRunStopped`),`info`)})().finally(()=>{y.current.get(e)?.promise===l&&y.current.delete(e)});return y.current.set(e,{matchesRun:c,promise:l}),l},[t,o,h,g,u,d]),C=(0,Q.useCallback)(async(e,n)=>{let r=`${e}/${n}`;if(!e||!n||v.current.has(r))return null;v.current.add(r),u(e,e=>({...e,withdrawingInputIds:[...e.withdrawingInputIds||[],n]}));try{let r=await X.withdrawQueuedInput(e,n);return u(e,e=>ke(e,{...r,removedInputId:r.removed?n:void 0})),r.removed?r.withdrawnInput||null:(t(g(`chat:focusSession.queuedInputAlreadyConsumed`),`info`),null)}catch(e){return t(Z(e),`error`),null}finally{v.current.delete(r),u(e,e=>({...e,withdrawingInputIds:(e.withdrawingInputIds||[]).filter(e=>e!==n)}))}},[t,g,u]),w=(0,Q.useCallback)(async(e,n)=>{let r=`${e}/${n}`;if(!e||!n||v.current.has(r))return!1;v.current.add(r),u(e,e=>({...e,withdrawingInputIds:[...e.withdrawingInputIds||[],n]}));try{let r=await X.sendQueuedInputNow(e,n);return u(e,e=>ke(e,r)),r.sent||t(g(`chat:focusSession.queuedInputAlreadyConsumed`),`info`),r.sent}catch(e){return t(Z(e),`error`),!1}finally{v.current.delete(r),u(e,e=>({...e,withdrawingInputIds:(e.withdrawingInputIds||[]).filter(e=>e!==n)}))}},[t,g,u]);return{sendPrompt:b,retryLastTurn:(0,Q.useCallback)(async(e,t={})=>{let n=o.current[e];if(!n||n.streaming)return;if(n.historyWindow){try{await p(e,{force:!0})}catch{return}if(n=o.current[e],!n||n.streaming||n.historyWindow||n.loading||n.error)return}let r=n.messages||[],i=-1;for(let e=r.length-1;e>=0;--e)if(r[e]?.role===`user`){i=e;break}if(i<0)return;let a=r[i];await b(a.text||``,e,a.attachments||[],!1,!1,null,null,{retryFromIndex:i,retryUserMessageId:a.id,...t})},[p,b,o]),queuePrompt:x,withdrawQueuedInput:C,sendQueuedInputNow:w,abort:S}}function Qs(e,t){return new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r,{once:!0}),t.aborted&&r()})}function $s({isStreaming:e,apply:t,intervalMs:n=750}){let r=new Map,i=new Map,a=new Set,o=e=>{let t=r.get(e);for(let n of a)n(e,t);a.size&&r.get(e)===t&&(t?.status===`success`||t?.status===`error`)&&r.delete(e)},s=e=>{i.get(e)?.controller.abort(),i.delete(e),r.delete(e),o(e)};return{select:(a,c)=>{if(r.get(a)?.status===`applying`)return!1;if(!c)return s(a),!0;if(r.set(a,{selection:c,status:`pending`}),o(a),i.has(a))return!0;let l=new AbortController,{signal:u}=l,d={controller:l,promise:Promise.resolve()};return i.set(a,d),d.promise=(async()=>{try{for(;!u.aborted;){let s=await e(a,u);if(u.aborted)return;if(s){await Qs(n,u);continue}let c=r.get(a);if(!c)return;r.set(a,{...c,status:`applying`}),o(a);let l=await t(a,c.selection);u.aborted||(i.get(a)===d&&i.delete(a),r.set(a,{...c,status:`success`,result:l}),o(a));return}}catch(e){let t=r.get(a);!u.aborted&&t&&(i.get(a)===d&&i.delete(a),r.set(a,{...t,status:`error`,error:e}),o(a))}finally{i.get(a)===d&&i.delete(a)}})(),!0},subscribe(e){a.add(e);for(let[t,n]of r)e(t,n),r.get(t)===n&&(n.status===`success`||n.status===`error`)&&r.delete(t);return()=>{a.delete(e)}},async dispose(){let e=[...i.values()];a.clear();for(let e of i.keys())s(e);r.clear(),await Promise.all(e.map(e=>e.promise))}}}var ec=$s({isStreaming:async(e,t)=>{let n=await X.getLiveSession(e,{signal:t});return!!(n.configurationBusy??n.streaming)},apply:(e,t)=>t.model?X.updateModel(e,t.model.provider,t.model.modelId):X.setThinkingLevel(e,t.thinkingLevel)});function tc({notify:e,requestText:t,requestConfirm:n,availableModels:r,sessionStatesRef:i,updateSessionState:a,updateSessions:o,replaceSessionStates:s,setGlobalError:c,syncLiveSession:u}){let{t:d,language:f}=l(),[p,m]=(0,Q.useState)(null),h=(0,Q.useCallback)(e=>{a(e,e=>({...e,runtimeSelectionRevision:(e.runtimeSelectionRevision||0)+1}))},[a]),g=(0,Q.useCallback)((e,t)=>{o(n=>n.map(n=>n.id===e?t(n):n))},[o]),_=(0,Q.useCallback)(async t=>{if(t)try{let n=await X.pauseGoal(t);a(t,{goal:n.goal||null}),g(t,e=>({...e,goal:n.goal||null})),e(d(`chat:chatPage.goalPaused`),`info`)}catch(e){a(t,{error:Z(e)})}},[e,d,a,g]),v=(0,Q.useCallback)(async(t,n)=>{if(t)try{let r=await X.setGoalBudget(t,n);a(t,{goal:r.goal||null}),g(t,e=>({...e,goal:r.goal||null})),e(d(`chat:chatPage.goalTokenBudgetUpdated`),`info`)}catch(e){a(t,{error:Z(e)})}},[e,d,a,g]),y=(0,Q.useCallback)(async t=>{let n=i.current[t];if(!(!t||n?.streaming||n?.compaction?.active)){a(t,{compaction:{...n?.compaction||{},active:!0,status:`running`,reason:`manual`},error:``});try{let n=await X.compactSession(t);a(t,{compaction:n.compaction||null,contextUsage:n.contextUsage||null}),e(d(`chat:chatPage.contextCompacted`))}catch(e){await u(t).catch(()=>{}),a(t,{error:Z(e)})}}},[e,i,u,d,a]),b=(0,Q.useCallback)(async e=>{let t=await X.updateCompactionPreference(e);s(Object.fromEntries(Object.entries(i.current).map(([e,n])=>{let r=Number(n.contextUsage?.contextWindow)||0;return r?[e,{...n,contextUsage:{...n.contextUsage,compactAtPercent:t.thresholdPercent,compactAtTokens:Math.floor(r*t.thresholdPercent/100)}}]:[e,n]})))},[s,i]),S=(0,Q.useCallback)((e,t={})=>{let n=String(t.model||``),r=String(i.current[e]?.model||``);if(n&&r&&n!==r)return;let o=Array.isArray(t.availableThinkingLevels)?t.availableThinkingLevels.map(e=>String(e)):Array.isArray(t.availableLevels)?t.availableLevels.map(e=>String(e)):[],s=String(t.thinkingLevel||``);a(e,{thinkingLevel:s||void 0,availableThinkingLevels:o,thinkingStatus:String(t.thinkingStatus||t.status||``),thinkingMessage:String(t.thinkingMessage||t.message||``),switchingThinking:!1}),s&&g(e,e=>({...e,thinkingLevel:s}))},[i,a,g]),C=(0,Q.useCallback)(async e=>{if(!e)return;let t=i.current[e]?.runtimeSelectionRevision,n=i.current[e];if(!(n?.switchingModel||n?.switchingThinking))try{let n=await X.getThinkingLevel(e);if(i.current[e]?.runtimeSelectionRevision!==t)return;S(e,n)}catch{if(i.current[e]?.runtimeSelectionRevision!==t)return;a(e,{thinkingStatus:`error`,thinkingMessage:d(`chat:focusSession.thinkingLevelsLoadFailed`)})}},[S,i,d,a]),w=(0,Q.useCallback)(async(t,o)=>{let s=r.find(e=>e.key===o);if(!t||!s)return;let c=i.current[t];if(c?.switchingModel||c?.switchingThinking)return;if(c?.streaming||c?.pendingRuntimeSelection){ec.select(t,s.key===c.model?void 0:{model:s});return}h(t);let l=c?.model||``,u=!!c?.messages?.length&&!c?.compaction?.active;a(t,{switchingModel:!0,model:s.key,error:``}),g(t,e=>({...e,model:s.key}));try{let r=await X.updateModel(t,s.provider,s.modelId);h(t),a(t,{model:r.model||s.key,contextUsage:r.contextUsage??null,switchingModel:!1}),g(t,e=>({...e,model:r.model||s.key})),S(t,r),e(d(`chat:chatPage.switchedToModel`,{model:s.label})),u&&await n({title:d(`chat:chatPage.compactAfterModelSwitch`),message:d(`chat:chatPage.compactAfterModelSwitchDescription`),confirmLabel:d(`chat:chatPage.compactNow`),tone:`primary`})&&await y(t)}catch(e){h(t),a(t,{switchingModel:!1,model:l||void 0,error:Z(e)}),l&&g(t,e=>({...e,model:l}))}},[S,r,y,h,e,n,i,d,a,g]),T=(0,Q.useCallback)(async(t,n)=>{let r=String(n||``).trim();if(!t||!r)return;let o=i.current[t]||{};if(o.switchingModel||o.switchingThinking)return;if(o.streaming||o.pendingRuntimeSelection){if(o.pendingRuntimeSelection?.model)return;ec.select(t,r===o.thinkingLevel?void 0:{thinkingLevel:r});return}h(t);let s=String(o.thinkingLevel||``);a(t,{switchingThinking:!0,thinkingLevel:r,error:``}),g(t,e=>({...e,thinkingLevel:r}));try{let n=await X.setThinkingLevel(t,r);h(t),S(t,n),e(d(`chat:chatPage.switchedToThinkingLevel`,{level:String(n.thinkingLevel||r)}))}catch(e){h(t),a(t,{switchingThinking:!1,thinkingLevel:s||void 0,error:Z(e)}),s&&g(t,e=>({...e,thinkingLevel:s}))}},[S,h,e,i,d,a,g]);(0,Q.useEffect)(()=>ec.subscribe((t,n)=>{if(!n){a(t,{pendingRuntimeSelection:void 0});return}let{selection:r,status:i}=n;if(i===`pending`||i===`applying`){h(t),a(t,{pendingRuntimeSelection:{model:r.model?.key,thinkingLevel:r.thinkingLevel},switchingModel:i===`applying`&&!!r.model,switchingThinking:i===`applying`&&!!r.thinkingLevel,error:``});return}if(h(t),a(t,{pendingRuntimeSelection:void 0,switchingModel:!1,switchingThinking:!1,...n.error?{error:Z(n.error)}:{}}),i===`error`)return;let o=n.result||{};if(r.model){let e=String(o.model||r.model.key);a(t,{model:e,contextUsage:o.contextUsage??null}),g(t,t=>({...t,model:e}))}S(t,o),e(r.model?d(`chat:chatPage.switchedToModel`,{model:r.model.label}):d(`chat:chatPage.switchedToThinkingLevel`,{level:String(o.thinkingLevel||r.thinkingLevel)}))}),[S,h,e,d,a,g]);let E=(0,Q.useCallback)(async(t,r)=>{if(!t)return!1;a(t,{switchingPermission:!0,error:``});try{if(r===`full-access`&&!await n({title:d(`chat:chatPage.enableFullAccess`),message:d(`chat:chatPage.fullAccessAllowsTheAgentToUseFilesAndNetworkServicesOutsideTheWorkspaceAndShellCommandsWillNoLon`),confirmLabel:d(`chat:chatPage.enableFullAccess`)}))return a(t,{switchingPermission:!1}),!1;let i=await X.updateExecutionMode(t,r);return a(t,{executionMode:i.executionMode,permissionMode:i.permissionMode,switchingPermission:!1}),g(t,e=>({...e,executionMode:i.executionMode,permissionMode:i.permissionMode})),e(d(`chat:chatPage.executionModeChangedToMode`,{mode:i.executionMode===`approval-required`?d(`chat:chatPage.approvalRequired`):i.executionMode===`workspace-write`?d(`chat:focusSession.workspaceWrite`):d(`chat:chatPage.fullAccess`)})),!0}catch(e){return a(t,{switchingPermission:!1,error:Z(e)}),!1}},[e,n,d,a,g]),D=(0,Q.useCallback)(async(e,t)=>{if(!e)return!1;try{let n=await X.updateRunMode(e,t),r=String(n.runMode||t);return a(e,{runMode:r}),g(e,e=>({...e,runMode:r})),!0}catch(t){return a(e,{error:Z(t)}),!1}},[a,g]),O=(0,Q.useCallback)(async(t,n,r)=>{a(t,{error:``});try{let e=await X.resolveApproval(t,n,r);a(t,e=>({...e,approvals:(e.approvals||[]).filter(e=>e.id!==n)})),e.alreadyResolved&&u(t,{force:!0})}catch(n){if(await u(t,{force:!0}),n instanceof x&&n.status===404){e(d(`chat:chatPage.approvalStatusUpdated`),`info`);return}throw a(t,{error:Z(n)}),n}},[e,u,d,a]),k=(0,Q.useCallback)(async(t,n,r)=>{let i=()=>a(t,e=>({...e,questions:(e.questions||[]).filter(e=>(e.id??e.questionId)!==n)}));try{await X.answerQuestion(t,n,r),i()}catch(n){if(await u(t,{force:!0}),n instanceof x&&(n.status===404||n.status===409)){i(),e(d(`board:question.closed`),`info`);return}throw n}},[e,u,d,a]),A=(0,Q.useCallback)(async t=>{try{await X.deliverSessionMessages(t)}catch(t){e(Z(t),`error`)}await u(t,{force:!0})},[e,u]),j=(0,Q.useCallback)(async t=>{try{await X.dismissSessionMessages(t),a(t,e=>({...e,workspace:e.workspace?.neighbours.length?{...e.workspace,messages:[]}:null}))}catch(n){e(Z(n),`error`),await u(t,{force:!0})}},[e,u,a]),M=(0,Q.useCallback)(async(t,n)=>{if(!(!t?.id||i.current[t.id]?.streaming)){a(t.id,{switchingCwd:!0,error:``});try{let r=await X.updateCwd(t.id,n);a(t.id,{cwd:r.cwd,switchingCwd:!1}),g(t.id,e=>({...e,cwd:r.cwd})),m(null),e(d(`chat:chatPage.workingDirectoryChangedToWorkspace`,{workspace:Mn(r.cwd,f)}))}catch(e){throw a(t.id,{switchingCwd:!1,error:Z(e)}),e}}},[f,e,i,d,a,g]);return{workspaceSession:p,setWorkspaceSession:m,switchSessionCwd:M,selectSessionWorkspace:(0,Q.useCallback)(async t=>{if(t?.id){if(i.current[t.id]?.streaming){e(d(`chat:chatPage.stopTheActiveRunBeforeChangingTheWorkspace`),`info`);return}try{let e=await tr(t.cwd,d(`common:workspacePicker.setWorkingDirectory`));e.status===`picked`?await M(t,e.path):e.status===`unavailable`&&m(t)}catch(e){a(t.id,{switchingCwd:!1,error:Z(e)})}}},[e,i,M,d,a]),renameSession:(0,Q.useCallback)(async n=>{if(!n?.id)return;if(i.current[n.id]?.streaming){e(d(`chat:chatPage.stopTheActiveRunBeforeRenamingTheChat`),`info`);return}let r=await t({title:d(`chat:chatPage.renameChat`),inputLabel:d(`chat:chatPage.chatTitle`),value:n.name,confirmLabel:d(`chat:chatPage.save`)});if(r!==null&&r!==n.name)try{let t=await X.renameSession(n.id,r);g(n.id,e=>({...e,name:t.name})),dn({id:n.id,name:t.name}),e(d(`chat:chatPage.chatTitleUpdated`))}catch(e){c(Z(e))}},[e,t,i,c,d,g]),pauseGoal:_,setGoalBudget:v,compactSession:y,setCompactionThreshold:b,loadSessionThinkingLevel:C,switchSessionModel:w,switchSessionThinkingLevel:T,switchSessionExecutionMode:E,switchSessionRunMode:D,resolveToolApproval:O,answerQuestion:k,deliverSessionMessages:A,dismissSessionMessages:j}}function nc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rc(e){if(!nc(e)||typeof e.created!=`boolean`)throw C();if(e.session===null){if(e.expiresAt!==null||e.created)throw C();return{session:null,expiresAt:null,created:!1}}let t=e.session;if(!nc(t)||typeof t.id!=`string`||!t.id||typeof e.expiresAt!=`string`||!Number.isFinite(Date.parse(e.expiresAt)))throw C();let n={id:t.id};for(let e of[`name`,`cwd`,`model`,`thinkingLevel`,`executionMode`,`permissionMode`,`runMode`]){let r=t[e];if(r!=null&&typeof r!=`string`)throw C();typeof r==`string`&&(n[e]=r)}if(t.streaming!==void 0&&typeof t.streaming!=`boolean`)throw C();return typeof t.streaming==`boolean`&&(n.streaming=t.streaming),{session:n,expiresAt:e.expiresAt,created:e.created}}async function ic(e,t){return rc(await T(`/api/sessions/${encodeURIComponent(e)}/side-chat`,{signal:t}))}async function ac(e,t){let n=rc(await T(`/api/sessions/${encodeURIComponent(e)}/side-chat`,{method:`POST`,signal:t}));if(!n.session)throw C();return n}function oc({runtime:e,children:t}){let[n,r]=(0,Q.useState)({}),i=(0,Q.useRef)(n),a=(0,Q.useRef)(!0),o=(0,Q.useRef)(e),s=(0,Q.useRef)(new Map),c=(0,Q.useRef)(new Map);(0,Q.useLayoutEffect)(()=>{o.current=e},[e]),(0,Q.useLayoutEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let l=(0,Q.useCallback)((e,t)=>{let n={...i.current,[e]:{...i.current[e]??Re,...t}};i.current=n,r(n)},[]),u=(0,Q.useCallback)(async(e,t=!1)=>{if(!a.current)return null;let n=c.current.get(e);if(n){let r=await n.promise;return!t||n.create?r:u(e,!0)}let r=new AbortController;l(e,{loading:!0,error:``});let d=(async()=>{try{let n=await(t?ac:ic)(e,r.signal);if(r.signal.aborted)return null;let a=i.current[e]?.session?.id;if(a&&a!==n.session?.id&&(o.current.discard(a),s.current.get(a)?.(),s.current.delete(a),de(a)),l(e,{...n,expired:!n.session&&!!(a||i.current[e]?.expired)}),n.session){if(s.current.has(n.session.id)||s.current.set(n.session.id,o.current.retainSessionState(n.session.id)),await o.current.syncLiveSession(n.session.id),r.signal.aborted)return null;await o.current.loadSessionMessages(n.session.id)}return r.signal.aborted?null:n}catch(t){return r.signal.aborted||l(e,{error:Z(t)}),null}finally{r.signal.aborted||l(e,{loading:!1}),c.current.get(e)?.controller===r&&c.current.delete(e)}})();return c.current.set(e,{create:t,controller:r,promise:d}),d},[l]);(0,Q.useEffect)(()=>{a.current=!0;let e=c.current,t=s.current,n=()=>{for(let[e,t]of Object.entries(i.current))t.expiresAt&&Date.parse(t.expiresAt)<=Date.now()&&!c.current.has(e)&&u(e)},r=window.setInterval(n,6e4),o=()=>{document.visibilityState===`visible`&&n()};return document.addEventListener(`visibilitychange`,o),()=>{a.current=!1,window.clearInterval(r),document.removeEventListener(`visibilitychange`,o);for(let t of e.values())t.controller.abort();e.clear();for(let e of t.values())e();t.clear()}},[u]);let d=(0,Q.useCallback)((e,t)=>l(e,{draft:t}),[l]),f=(0,Q.useMemo)(()=>({entries:n,runtime:e,load:u,setDraft:d}),[n,e,u,d]);return(0,$.jsx)(Pe.Provider,{value:f,children:t})}var sc=`new`,cc=40;function lc(e){let t=window.__TAURI__?.core?.invoke??window.__TAURI_INTERNALS__?.invoke;return t?t(e):Promise.reject(Error(`native bridge unavailable`))}function uc({notify:e,navigate:t,browserNotify:n,pendingAsset:r,onAssetConsumed:i,requestText:a,requestConfirm:o,routeSessionId:s,onRouteSessionChange:c,routeLeading:u,pageChrome:d}){let{t:f}=l(),p=s!==void 0,m=p&&s!==sc?s:``,h=M(e=>e.client===`mobile-app`),g=M(e=>e.loaded),_=A(),v=h||_,y=(0,Q.useRef)(null),b=(0,Q.useRef)(new Set),x=(0,Q.useRef)(new Map),S=(0,Q.useRef)(new Map),C=(0,Q.useRef)(null),T=us({notify:e}),E=(0,Q.useRef)(new Set),D=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{for(let e of D.current)T.sessions.some(t=>t.id===e&&t.unread)||D.current.delete(e);let e=e=>{let t=T.activeId;!t||document.visibilityState!==`visible`||!T.sessions.some(e=>e.id===t&&e.unread)||E.current.has(t)||!e&&D.current.has(t)||(E.current.add(t),D.current.add(t),Dn(t,{read:!0}).catch(()=>void 0).finally(()=>E.current.delete(t)))};return e(),document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[T.activeId,T.sessions]);let O=k(e=>e.capabilities.features.sessionActivityOrder===!0),j=T.activeId,N=!!j&&T.sessions.some(e=>e.id===j);(0,Q.useEffect)(()=>{!O||!j||!N||Dn(j,{opened:!0}).catch(()=>void 0)},[O,j,N]);let P=k(e=>e.capabilities.features[`board.events`]===!0),F=js({sessionStates:T.sessionStates,sessionStatesRef:T.sessionStatesRef,localStreamSessionsRef:b,streamGenerationRef:x,updateSessionState:T.updateSessionState,updateSessions:T.updateSessions,pollOnly:P?T.activeId||null:void 0}),I=ds({setActiveId:T.setActiveId,loadSessionMessages:F.loadSessionMessages,openRoutedSession:p?c:void 0}),L=T.createSessionRecord,R=F.loadSessionMessages,z=T.refreshSessions,B=T.sessionStatesRef,V=F.syncLiveSession,H=T.setGlobalError,U=I.openSession,[W,ee]=(0,Q.useState)({sessionId:``,token:0}),te=(0,Q.useCallback)(async(e=``)=>{let t=null;h&&(t=await lc(`mobile_state`).catch(()=>null));let n=Dr(h,t),r=await L(e,{inheritRecentCwd:n});return r?(U(r),r):``},[L,h,U]),ne=T.setActiveId,re=!!(m&&T.sessions.some(e=>e.id===m));(0,Q.useEffect)(()=>{!m||T.activeId===m||!re&&!T.loading||ne(m)},[T.activeId,T.loading,re,m,ne]);let ie=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{if(!m||ie.current===m)return;ie.current=m;let e=cn();e?.sessionId===m&&e.targetEntryId&&R(m,{force:!0,limit:cc})},[R,m]);let ae=T.activeId,oe=T.sessions.some(e=>e.id===ae&&e.streaming===!0),se=T.sessions.find(e=>e.id===ae)?.botId;(0,Q.useEffect)(()=>{ae&&se&&V(ae)},[se,oe,ae,V]);let ce=(0,Q.useRef)({id:``,streaming:!1});(0,Q.useEffect)(()=>{let e=ce.current;ce.current={id:ae,streaming:oe},ae&&(e.id===ae?e.streaming!==oe:oe)&&As(B.current[ae],{catalogStreaming:oe,localStreamOwned:b.current.has(ae)})&&R(ae,{force:!0})},[oe,ae,R,B]),(0,Q.useEffect)(()=>kn(e=>{let t=e===`*`?ae?[ae]:[]:[e];for(let e of t){let t=B.current[e];!t?.loaded||t.streaming||b.current.has(e)||V(e)}}),[ae,B,V]),(0,Q.useEffect)(()=>{if(!m||!re)return;let e=Yr();e&&yr(m,e.url);let t=e=>{let t=e.detail?.url;t&&yr(m,t)};return window.addEventListener(Xr,t),()=>window.removeEventListener(Xr,t)},[re,m]);let G=Zs({browserNotify:n,notify:e,defaultModel:T.defaultModel,localStreamSessionsRef:b,streamGenerationRef:x,streamActivityRef:S,sessionStatesRef:T.sessionStatesRef,setActiveId:T.setActiveId,setGlobalError:T.setGlobalError,updateSessionState:T.updateSessionState,updateSessions:T.updateSessions,createSession:te,loadSessionMessages:F.loadSessionMessages,refreshSessions:T.refreshSessions,syncLiveSession:F.syncLiveSession}),{sendPrompt:le,retryLastTurn:ue}=G,pe=T.adoptCreatedSession,me=(0,Q.useCallback)(async(t,n,r=[],i=!1,a=!1,o=null,s=null,c={})=>{let l=n.trim()||(r.length?f(`chat:chatPage.pleaseAnalyzeTheseAttachments`):``)||(s?s.resourceName:``);if(!l)return!1;let u;try{u=await t.prepare(l)}catch(t){return e(Z(t),`error`),!1}return pe(u.session),t.onSent(),de(fe),U(u.session.id),le(n,u.session.id,r,i,a,o,s,{onAccepted:c.onAccepted})},[pe,e,U,le,f]),K=tc({notify:e,requestText:a,requestConfirm:o,availableModels:T.availableModels,sessionStatesRef:T.sessionStatesRef,updateSessionState:T.updateSessionState,updateSessions:T.updateSessions,replaceSessionStates:T.replaceSessionStates,setGlobalError:T.setGlobalError,syncLiveSession:F.syncLiveSession}),he=(0,Q.useCallback)(e=>{if(document.visibilityState!==`visible`||C.current)return;let t=h||typeof window.matchMedia==`function`&&window.matchMedia(`(pointer: coarse)`).matches,n=(async()=>{h&&await w().catch(()=>void 0);let n=[];try{n=await z(void 0,{preserveExistingOnEmpty:!0})}catch{}let r=new Set([...Object.keys(B.current),...T.activeId?[T.activeId]:[],...n.filter(e=>e.streaming).map(e=>e.id)]);await Promise.allSettled(Array.from(r).map(n=>b.current.has(n)&&!hs({mobile:t,reason:e,lastEventAt:S.current.get(n)??0})?void 0:V(n,{force:!0})))})().finally(()=>{C.current=null});C.current=n},[T.activeId,h,z,B,V]);(0,Q.useEffect)(()=>{let e=e=>he(e.type===`online`?`online`:e.type===`pageshow`&&e.persisted?`restored`:`visible`);return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pageshow`,e),window.addEventListener(`online`,e),()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pageshow`,e),window.removeEventListener(`online`,e)}},[he]);let q=(0,Q.useCallback)(async e=>{await R(e,{force:!0}),await z(e)},[R,z]),ge=(0,Q.useCallback)(async(t,n,r)=>{if(!(!t?.id||!n))try{H(``);let i=null;if(r?.rewindFiles){let e=await X.previewFileRewind(t.id,n);if(!await o(Lr(e,f)))return;i=await X.rewindFiles(t.id,n)}let a=await X.navigateSessionTree(t.id,n,!1);if(a.cancelled)return;mr(t.id,a),await q(t.id),ee(e=>({sessionId:t.id,token:e.token+1})),i?e(Rr(i,f)):zr(t.id,a,f(`chat:chatPage.branchedFromNode`),{notify:e,t:f})}catch(e){H(e instanceof Error?e.message:String(e))}},[e,q,o,H,f]);(0,Q.useEffect)(()=>nn(e=>{B.current[e]&&q(e).catch(()=>void 0)}),[q,B]);let _e=(0,Q.useCallback)(async(t,n)=>{if(!t?.id||!n)return;let r=await a({title:f(`chat:chatPage.createChildChat`),inputLabel:f(`chat:chatPage.chatTitle`),value:`${f(`chat:chatPage.separateChatSuffix`)} · ${t.name||f(`chat:chatPage.newChat`)}`,confirmLabel:f(`chat:chatPage.create`)});if(r!==null)try{H(``);let i=await X.deriveSession(t.id,n,r);await z(),U(i.id),ee(e=>({sessionId:i.id,token:e.token+1})),e(f(`chat:chatPage.childChatCreated`))}catch(e){H(e instanceof Error?e.message:String(e))}},[e,U,z,a,H,f]),ve=(0,Q.useCallback)(()=>t(`config`),[t]),ye=(0,Q.useMemo)(()=>({sessions:T.sessions,subscribeSessionState:T.subscribeSessionState,getSessionState:T.getSessionState,defaultModel:T.defaultModel,availableModels:T.availableModels,globalError:T.globalError,activeId:T.activeId,mobileLayout:v,requestConfirm:o,sessionTreePulseSessionId:W.sessionId,sessionTreePulseToken:W.token,pendingAsset:r,onAssetConsumed:i,notify:e,openModelSettings:ve,loadSessionMessages:F.loadSessionMessages,loadOlderMessages:F.loadOlderMessages,sendPrompt:G.sendPrompt,sendNewTask:me,retryLastTurn:G.retryLastTurn,queuePrompt:G.queuePrompt,withdrawQueuedInput:G.withdrawQueuedInput,sendQueuedInputNow:G.sendQueuedInputNow,abort:G.abort,pauseGoal:K.pauseGoal,setGoalBudget:K.setGoalBudget,compactSession:K.compactSession,setCompactionThreshold:K.setCompactionThreshold,switchSessionModel:K.switchSessionModel,loadSessionThinkingLevel:K.loadSessionThinkingLevel,switchSessionThinkingLevel:K.switchSessionThinkingLevel,switchSessionExecutionMode:K.switchSessionExecutionMode,switchSessionRunMode:K.switchSessionRunMode,resolveToolApproval:K.resolveToolApproval,answerQuestion:K.answerQuestion,deliverSessionMessages:K.deliverSessionMessages,dismissSessionMessages:K.dismissSessionMessages,selectSessionWorkspace:K.selectSessionWorkspace,renameSession:K.renameSession,branchFromEntry:ge,createChildSession:_e,reloadSessionBranch:q}),[T.sessions,T.subscribeSessionState,T.getSessionState,T.defaultModel,T.availableModels,T.globalError,T.activeId,v,o,W.sessionId,W.token,r,i,e,ve,F.loadSessionMessages,F.loadOlderMessages,G.sendPrompt,me,G.retryLastTurn,G.queuePrompt,G.withdrawQueuedInput,G.sendQueuedInputNow,G.abort,K.pauseGoal,K.setGoalBudget,K.compactSession,K.setCompactionThreshold,K.switchSessionModel,K.loadSessionThinkingLevel,K.switchSessionThinkingLevel,K.switchSessionExecutionMode,K.switchSessionRunMode,K.resolveToolApproval,K.deliverSessionMessages,K.dismissSessionMessages,K.selectSessionWorkspace,K.renameSession,ge,_e,q]),be=T.discardSessionState,xe=(0,Q.useMemo)(()=>({subscribeSessionState:T.subscribeSessionState,getSessionState:T.getSessionState,retainSessionState:T.retainSessionState,discard:e=>{x.current.set(e,(x.current.get(e)??0)+1),b.current.delete(e),be(e)},loadSessionMessages:F.loadSessionMessages,loadOlderMessages:F.loadOlderMessages,syncLiveSession:F.syncLiveSession,send:async(e,t)=>{await le(t,e,[],!1,!1,null,null,{activate:!1})},retry:e=>ue(e,{activate:!1}),abort:G.abort,approve:K.resolveToolApproval}),[T.subscribeSessionState,T.getSessionState,T.retainSessionState,be,F.loadSessionMessages,F.loadOlderMessages,F.syncLiveSession,le,ue,G.abort,K.resolveToolApproval]);return(0,$.jsxs)(oc,{runtime:xe,children:[(0,$.jsx)(`div`,{ref:y,className:`chat-layout dock-layout relative flex w-full min-w-0 min-h-0 flex-1`,children:T.loading?(0,$.jsx)(nr,{kind:`loading`,title:f(`chat:chatPage.wakingTheAgent`),description:f(`chat:chatPage.modelsSessionsAndContextAreSettlingIntoPlace`)}):(0,$.jsx)(`div`,{className:`chat-dock-workspace relative h-full w-full min-w-0 min-h-0 flex-1 [isolation:isolate] overflow-hidden border-0 rounded-none bg-panel`,children:(0,$.jsx)(Qo.Provider,{value:ye,children:(0,$.jsx)(Ye.Provider,{value:p?d??null:null,children:(0,$.jsx)(Bi.Provider,{value:p?u??null:null,children:g&&(p?m&&!re?(0,$.jsx)(nr,{kind:`empty`,title:f(`navigation:shell.sessionNotFound`),description:f(`navigation:shell.sessionNotFoundHint`),action:d?.onHome?(0,$.jsx)(Y,{variant:`secondary`,onClick:d.onHome,children:f(`board:home.goHome`)}):(0,$.jsx)(Y,{variant:`secondary`,onClick:()=>t(`board`),children:f(`navigation:shell.backToBoardLabel`)})}):s===sc&&d?.newTaskDraft?(0,$.jsx)(rs,{draft:d.newTaskDraft}):m?(0,$.jsx)(is,{sessionId:m,onCreateSession:te}):T.globalError?(0,$.jsx)(nr,{kind:`error`,title:f(`navigation:shell.createSessionFailed`),description:T.globalError,action:(0,$.jsx)(Y,{variant:`secondary`,onClick:()=>void te(),children:f(`navigation:more.retry`)})}):(0,$.jsx)(nr,{kind:`loading`,title:f(`chat:chatPage.wakingTheAgent`)}):(0,$.jsx)(is,{onCreateSession:te}))})})})})}),K.workspaceSession&&(0,$.jsx)(He,{open:!0,initialPath:K.workspaceSession.cwd,description:f(`common:workspacePicker.selectWorkspaceForChat`,{name:K.workspaceSession.name}),onOpenChange:e=>!e&&K.setWorkspaceSession(null),onSelect:e=>K.switchSessionCwd(K.workspaceSession,e)})]})}export{uc as ChatPage};
|
|
553
|
+
`);o.push(e.slice(-6e3),h)}else if(i===`tool_start`)o.flush(),s.flush(),r(e,e=>{let t={type:`tool`,id:m.id,name:m.name,args:m.args,status:`running`,startedAt:m.startedAt||h,updatedAt:h,...m.output===void 0?{}:{output:m.output}};return{...e,lastActivityAt:h,runNotice:``,tools:Vn(e.tools,t),currentActivity:t,activityFeed:Vn(e.activityFeed,t)}});else if(i===`tool_update`)s.push(m.id,{message:m.message||``,updatedAt:m.updatedAt||h,...m.output===void 0?{}:{output:m.output},...m.agent?{agent:m.agent}:{},...m.previewImage?{previewImage:m.previewImage}:{}},m.updatedAt||h);else if(i===`tool_end`)s.flush(),r(e,e=>{let t=e.tools.find(e=>e.id===m.id),n=m.finishedAt||h,r=String(t?.name||``),i=(zn(r)||[`spawn_agent`,`list_agents`,`send_message`,`followup_task`,`wait_agent`,`interrupt_agent`].includes(r))&&[`plan`,`agent`].includes(e.currentActivity?.type),a={...t||{},type:`tool`,status:m.error?`error`:`done`,message:m.message||t?.message||``,updatedAt:n,finishedAt:n,...m.output===void 0?{}:{output:m.output},...m.previewImage?{previewImage:m.previewImage}:{},...m.target?{target:m.target}:{}},o=m.agent?{type:`agent`,agent:m.agent,updatedAt:m.agent.lastActivityAt||n}:null,s=e.activityFeed||[];return(m.error||!i&&!o)&&(s=Vn(s,a)),o&&(s=Vn(s,o)),{...e,lastActivityAt:n,tools:e.tools.map(e=>e.id===m.id?{...e,status:m.error?`error`:`done`,message:m.message||``,updatedAt:n,finishedAt:n,...m.output===void 0?{}:{output:m.output},...m.previewImage?{previewImage:m.previewImage}:{},...m.target?{target:m.target}:{}}:e),currentActivity:m.error?a:o||(i?e.currentActivity:a),activityFeed:s}});else if(i===`mobile_operation_request`)Gs(e,m);else if(i===`mobile_operation_cancel`)Ws(m);else if(i===`permission_request`)s.flush(),r(e,e=>({...e,lastActivityAt:h,approvals:[...(e.approvals||[]).filter(e=>e.id!==m.id),m]}));else if(i===`permission_resolved`)r(e,e=>({...e,lastActivityAt:h,approvals:(e.approvals||[]).filter(e=>e.id!==m.id)}));else if(i===`question_request`){s.flush();let t=typeof m.id==`string`?m.id:m.questionId;r(e,e=>({...e,lastActivityAt:h,questions:[...(e.questions||[]).filter(e=>(e.id??e.questionId)!==t),m]}))}else if(i===`question_resolved`){let t=typeof m.questionId==`string`?m.questionId:m.id;r(e,e=>({...e,lastActivityAt:h,questions:(e.questions||[]).filter(e=>(e.id??e.questionId)!==t)}))}else if(i===`generated_asset`)r(e,e=>({...e,lastActivityAt:h,messages:e.messages.map(e=>e.id===t?{...e,attachments:[...(e.attachments||[]).filter(e=>Ks(e)!==Ks(m)),m]}:e)}));else if(i===`goal_update`)r(e,e=>({...e,goal:m.goal??null,team:qs(m,e.team)})),f(e=>({...e,goal:m.goal??null,team:qs(m,e.team)}));else if(Un(i))s.flush(),r(e,e=>{let t=In(m,e.plan),n=m.currentActivity||{type:`plan`,plan:t,changes:Hn(e.plan,t),updatedAt:t?.updatedAt||h};return{...e,lastActivityAt:h,plan:t,currentActivity:n,activityFeed:Vn(e.activityFeed,n)}}),f(e=>({...e,plan:In(m,e.plan??null)}));else if(i===`session_title`)f(e=>({...e,name:m.name}));else if(i===`model_fallback`){let t=typeof m.model==`string`?m.model:``;if(!t)return;let n=c(`chat:requestNotice.modelFallback`,{model:typeof m.modelId==`string`&&m.modelId?m.modelId:t});r(e,e=>{let r={type:`retry`,message:m.message,summary:n,updatedAt:h};return{...e,model:t,...typeof m.thinkingLevel==`string`?{thinkingLevel:m.thinkingLevel}:{},runNotice:n,currentActivity:r,activityFeed:Vn(e.activityFeed,r),lastActivityAt:h}}),f(e=>({...e,model:t,...typeof m.thinkingLevel==`string`?{thinkingLevel:m.thinkingLevel}:{}}))}else if(i===`retry`){let t=c(`chat:requestNotice.retryingAttempt`,{attempt:m.attempt,maxAttempts:m.maxAttempts});r(e,e=>{let n={type:`retry`,message:m.message,summary:t,updatedAt:h};return{...e,runNotice:t,currentActivity:n,activityFeed:Vn(e.activityFeed,n),lastActivityAt:h}})}else if(i===`done`||i===`error`){l.queuedDuringRun||=!!(n.current[e]?.hadQueuedInput||n.current[e]?.queuedInputs?.length);let c=m.finishedAt||h;typeof m.text==`string`&&(l.responseText=m.text),l.responseRenderingStreaming=!1,l.terminal=!0;let u=i===`error`?S(m,String(m.message||``)):``;if(p(i===`done`?`completed`:`failed`,i===`error`?u||`Speech response failed.`:void 0),a.setTarget(l.responseText,c),i===`error`&&a.flush(),o.flush(),s.cancel(),r(e,e=>Js(e,{agentId:t,responseText:l.responseText,data:m,finishedAt:c,preserveDisplayedText:i===`done`,...i===`error`?{error:u}:{}})),i===`done`)return f(e=>({...e,streaming:!1,goal:m.goal??e.goal??null,team:qs(m,e.team),plan:In(m,e.plan??null)})),!1;throw Error(m.message)}},state:l}}var Xs=`pisper:usage-updated`;function Zs({browserNotify:e,notify:t,defaultModel:n,localStreamSessionsRef:r,streamGenerationRef:i,streamActivityRef:a,sessionStatesRef:o,setActiveId:s,setGlobalError:c,updateSessionState:u,updateSessions:d,createSession:f,loadSessionMessages:p,refreshSessions:m,syncLiveSession:h}){let{t:g}=l(),_=(0,Q.useRef)(new Map),v=(0,Q.useRef)(new Set),y=(0,Q.useRef)(new Map),b=(0,Q.useCallback)(async(t,l,v=[],y=!1,b=!1,x=null,S=null,C={})=>{let w=C.retryFromIndex,T=w==null?t.trim()||(v.length?g(`chat:chatPage.pleaseAnalyzeTheseAttachments`):``)||(S?S.resourceName:``):t;if(!T&&!S)return!1;let E=l;if(E||=await f(),!E||o.current[E]?.streaming)return!1;o.current[E]?.historyWindow&&await p(E,{force:!0});let D=o.current[E];if(D?.streaming)return!1;if(w!=null){let e=-1;for(let t=(D?.messages.length||0)-1;t>=0;--t)if(D.messages[t]?.role===`user`){e=t;break}let t=D?.messages[e];if(!t||C.retryUserMessageId&&t.id!==C.retryUserMessageId)return!1;w=e,T=t.text||``,v=t.attachments||[]}let O=o.current[E];if(O?.pendingRuntimeSelection||O?.switchingModel||O?.switchingThinking)return!1;let k=(i.current.get(E)||0)+1;i.current.set(E,k);let A=!1,j=()=>!A&&i.current.get(E)===k,M=()=>{},N=new Promise(e=>{M=e});_.current.set(E,{promise:N,resolve:M}),C.activate!==!1&&(s(E),c(``));let P={id:`user-${Date.now()}`,role:`user`,text:T,invocation:S,attachments:v.map(({id:e,kind:t,name:n,mimeType:r,size:i,data:a})=>({id:e,kind:t,name:n,mimeType:r,size:i,data:t===`image`?a:void 0}))},F=`agent-${Date.now()}`,I=new Date().toISOString(),L={responseText:``,responseRenderingStreaming:!0,thinkingText:``,thinkingPrefix:``,queuedDuringRun:!1,pendingInputIds:[]},R=Ns((e,t)=>{j()&&u(E,n=>j()?{...n,thinkingText:e,lastActivityAt:t||n.lastActivityAt,currentActivity:{type:`model`,stage:`thinking`,updatedAt:t||n.lastActivityAt}}:n)},{intervalMs:80}),z=Rs((e,t)=>{j()&&u(E,n=>{if(!j())return n;let r=n.messages.map(t=>t.id===F?{...t,text:e,streaming:L.responseRenderingStreaming||e!==L.responseText}:t);if(L.terminal||!L.responseRenderingStreaming||n.currentActivity&&n.currentActivity.type!==`model`)return{...n,messages:r};let i={type:`model`,stage:`responding`,updatedAt:t||n.lastActivityAt};return{...n,lastActivityAt:t||n.lastActivityAt,runNotice:``,currentActivity:i,activityFeed:Vn(n.activityFeed,i),messages:r}})},{isCurrent:j}),B=Ps((e,t)=>{j()&&u(E,n=>{if(!j())return n;let r=n.activityFeed||[];for(let[n,i]of e){let e=r.find(e=>e.type===`tool`&&e.id===n);e&&(r=Vn(r,{...e,...i,updatedAt:t||e.updatedAt}))}let i=n.currentActivity?.type===`tool`&&e.has(n.currentActivity.id)?{...n.currentActivity,...e.get(n.currentActivity.id),updatedAt:t||n.currentActivity.updatedAt}:n.currentActivity;return{...n,lastActivityAt:t||n.lastActivityAt,tools:n.tools.map(t=>{let n=e.get(String(t.id||``));return n?{...t,...n}:t}),currentActivity:i,activityFeed:r}})}),V=Ys({sessionId:E,agentId:F,sessionStatesRef:o,updateSessionState:u,updateSessions:d,typewriter:z,thinkingScheduler:R,toolScheduler:B,t:g}),H=!1,U=(e,t)=>j()?(a?.current.set(E,Date.now()),!H&&(e===`run`||e===`meta`)&&(H=!0,C.onAccepted?.()),e===`resync_required`?(V.dispatch(e,t),A=!0,i.current.delete(E),r.current.delete(E),h(E),!1):V.dispatch(e,t)):!1;L=V.state,u(E,e=>{let t=y||b||e.goal?.status===`active`;return{...e,messages:[...w==null?e.messages:e.messages.slice(0,w),P,{id:F,role:`agent`,text:``,streaming:!0}],tools:[],approvals:[],error:``,streaming:!0,loaded:!0,runStartedAt:I,lastActivityAt:I,runFinishedAt:null,runStopped:!1,runNotice:``,currentActivity:{type:`model`,stage:`thinking`,updatedAt:I},activityFeed:[],lifecycle:{phase:`starting`,event:`prompt_submitted`,turn:0,updatedAt:I},thinkingText:``,hadQueuedInput:!1,withdrawnInputIds:[],queuedInputRunId:F,compaction:null,plan:t?e.plan:null}}),!y&&!b&&d(e=>e.map(e=>e.id!==E||e.goal?.status===`active`?e:{...e,plan:null})),r.current.add(E),a?.current.set(E,Date.now());let W=!1;try{if(w==null?await X.openStream({sessionId:E,message:T,attachments:v,goalMode:y,teamMode:b,goalTokenBudget:x,invocation:S},U):await X.retryLastTurn(E,U),!j())return H;L.responseRenderingStreaming=!1,L.terminal=!0,z.setTarget(L.responseText),R.flush(),B.flush();let t=new Date().toISOString();if(o.current[E]?.streaming&&u(E,e=>{let n=e.runFinishedAt||t;return{...e,streaming:!1,runFinishedAt:n,lastActivityAt:n,runNotice:``,currentActivity:null,activityFeed:[],approvals:[],tools:Rn(e.tools,{finishedAt:n}),messages:e.messages.map(e=>e.id===F?{...e,streaming:e.text!==L.responseText}:e)}}),!await z.drain()||!j()||(u(E,e=>({...e,messages:e.messages.map(e=>e.id===F?{...e,text:L.responseText,streaming:!1}:e)})),!j()))return H;let r=!!(L.queuedDuringRun||o.current[E]?.hadQueuedInput);(y||b||r||o.current[E]?.goal||o.current[E]?.queuedInputs?.length)&&u(E,{queuedInputs:[],hadQueuedInput:!1});let i;try{i=(await m()).find(e=>e.id===E)}catch{h(E)}if(!j()||(r&&await p(E,{force:!0}).catch(()=>void 0),!j()))return H;C.activate!==!1&&e?.(`chat.completed`,{chat:{title:i?.name||g(`chat:chatPage.appChat`,{app:`Pisper`}),summary:L.responseText.trim().slice(0,260)||g(`chat:chatPage.theAgentHasFinishedResponding`),model:o.current[E]?.model||n}})}catch(e){if(!j())return H;if((L.runId||L.startedAt)&&!L.terminal)return V.dispatch(`resync_required`,{}),A=!0,i.current.delete(E),r.current.delete(E),h(E),H;W=!0,z.cancel(),R.flush(),B.cancel();let t=new Date().toISOString(),n=Z(e);if(u(E,e=>({...e,streaming:!1,error:n,runFinishedAt:t,lastActivityAt:t,runNotice:``,currentActivity:null,activityFeed:[],approvals:[],tools:Rn(e.tools,{finishedAt:t,error:n}),messages:e.messages.map(e=>e.id===F?{...e,streaming:!1,error:n,text:e.text||L.responseText}:e)})),L.queuedDuringRun||o.current[E]?.hadQueuedInput||o.current[E]?.queuedInputs?.length){try{await p(E,{force:!0})}catch{}u(E,{queuedInputs:[],hadQueuedInput:!1})}d(e=>e.map(e=>e.id===E?{...e,streaming:!1}:e))}finally{let e=j();if(A=!0,e&&(r.current.delete(E),i.current.delete(E),u(E,{streaming:!1,hadQueuedInput:!1}),_.current.get(E)?.promise===N&&_.current.delete(E)),z.cancel(),R.cancel(),B.cancel(),M(),window.dispatchEvent(new Event(Xs)),W&&e)h(E);else if(e){let e=o.current[E];(e?.recovering||e&&!e.loaded)&&h(E)}}return H},[e,f,n,p,r,m,i,a,o,s,c,h,g,u,d]),x=(0,Q.useCallback)(async(e,n,r=[],i=`steer`,a)=>{let s=String(e||``).trim()||(r.length?g(`chat:chatPage.pleaseAnalyzeTheseAttachments`):``);if(!n||!s)return!1;o.current[n]?.historyWindow&&await p(n,{force:!0});let c=o.current[n]?.queuedInputRunId;try{let e=await X.queueInput(n,s,r,i),t=new Date().toISOString(),a={id:`interactive-user-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,role:`user`,text:s,queuedAt:t,queuedInputId:e.inputId||void 0,streamingBehavior:e.behavior||i,attachments:r.map(({id:e,kind:t,name:n,mimeType:r,size:i,data:a})=>({id:e,kind:t,name:n,mimeType:r,size:i,data:t===`image`?a:void 0}))};return u(n,n=>{let r=ke(n,e),i=!r.withdrawnInputIds?.includes(e.inputId)&&n.queuedInputRunId===c,o=!!(e.inputId&&r.deliveredInputIds?.includes(e.inputId));return{...r,messages:i?Oe(r.messages,{...a,queuedPending:!!e.inputId&&!o}):r.messages,hadQueuedInput:!0,lastActivityAt:t}}),!0}catch(e){if(pr(e)){let e=_.current.get(n);return e?await e.promise:await h(n),u(n,{streaming:!1,recovering:!1,queuedInputs:[],hadQueuedInput:!1}),await p(n,{force:!0}),await b(s,n,r,!1,!1,null,null,{onAccepted:a})??!1}return t(Z(e),`error`),!1}},[p,t,b,o,h,g,u]),S=(0,Q.useCallback)(e=>{if(!e)return Promise.resolve();let n=o.current[e],r=y.current.get(e);if(r?.matchesRun(n))return r.promise;let i=n?.runStartedAt,a=n?.queuedInputRunId,s=!!n?.runStopped,c=e=>!!(e&&(a?e.queuedInputRunId===a:!e.queuedInputRunId&&e.runStartedAt===i));u(e,{runStopped:!0});let l=(async()=>{let n;try{n=await X.abort(e)}catch(t){let n=o.current[e];throw c(n)&&n?.runStopped&&u(e,{runStopped:s}),t}if(!c(o.current[e])||(await h(e,{force:!0}),!c(o.current[e])))return;let r=new Date().toISOString();u(e,e=>({...e,streaming:!1,queuedInputs:[],hadQueuedInput:!1,goal:n.goal??null,team:Object.hasOwn(n,`team`)?n.team??null:e.team,compaction:e.compaction?.active?{...e.compaction,active:!1,status:`aborted`,aborted:!0,finishedAt:r}:e.compaction,runFinishedAt:r,lastActivityAt:r,runStopped:!0,runNotice:``,approvals:[],tools:Rn(e.tools,{finishedAt:r,error:g(`chat:chatPage.stopped`)}),messages:e.messages.map(e=>e.streaming?{...e,streaming:!1}:e)})),d(t=>t.map(t=>t.id===e?{...t,streaming:!1,goal:n.goal??t.goal??null,team:Object.hasOwn(n,`team`)?n.team??null:t.team}:t)),t(g(`chat:chatPage.currentRunStopped`),`info`)})().finally(()=>{y.current.get(e)?.promise===l&&y.current.delete(e)});return y.current.set(e,{matchesRun:c,promise:l}),l},[t,o,h,g,u,d]),C=(0,Q.useCallback)(async(e,n)=>{let r=`${e}/${n}`;if(!e||!n||v.current.has(r))return null;v.current.add(r),u(e,e=>({...e,withdrawingInputIds:[...e.withdrawingInputIds||[],n]}));try{let r=await X.withdrawQueuedInput(e,n);return u(e,e=>ke(e,{...r,removedInputId:r.removed?n:void 0})),r.removed?r.withdrawnInput||null:(t(g(`chat:focusSession.queuedInputAlreadyConsumed`),`info`),null)}catch(e){return t(Z(e),`error`),null}finally{v.current.delete(r),u(e,e=>({...e,withdrawingInputIds:(e.withdrawingInputIds||[]).filter(e=>e!==n)}))}},[t,g,u]),w=(0,Q.useCallback)(async(e,n)=>{let r=`${e}/${n}`;if(!e||!n||v.current.has(r))return!1;v.current.add(r),u(e,e=>({...e,withdrawingInputIds:[...e.withdrawingInputIds||[],n]}));try{let r=await X.sendQueuedInputNow(e,n);return u(e,e=>ke(e,r)),r.sent||t(g(`chat:focusSession.queuedInputAlreadyConsumed`),`info`),r.sent}catch(e){return t(Z(e),`error`),!1}finally{v.current.delete(r),u(e,e=>({...e,withdrawingInputIds:(e.withdrawingInputIds||[]).filter(e=>e!==n)}))}},[t,g,u]);return{sendPrompt:b,retryLastTurn:(0,Q.useCallback)(async(e,t={})=>{let n=o.current[e];if(!n||n.streaming)return;if(n.historyWindow){try{await p(e,{force:!0})}catch{return}if(n=o.current[e],!n||n.streaming||n.historyWindow||n.loading||n.error)return}let r=n.messages||[],i=-1;for(let e=r.length-1;e>=0;--e)if(r[e]?.role===`user`){i=e;break}if(i<0)return;let a=r[i];await b(a.text||``,e,a.attachments||[],!1,!1,null,null,{retryFromIndex:i,retryUserMessageId:a.id,...t})},[p,b,o]),queuePrompt:x,withdrawQueuedInput:C,sendQueuedInputNow:w,abort:S}}function Qs(e,t){return new Promise(n=>{let r=()=>{clearTimeout(i),t.removeEventListener(`abort`,r),n()},i=setTimeout(r,e);t.addEventListener(`abort`,r,{once:!0}),t.aborted&&r()})}function $s({isStreaming:e,apply:t,intervalMs:n=750}){let r=new Map,i=new Map,a=new Set,o=e=>{let t=r.get(e);for(let n of a)n(e,t);a.size&&r.get(e)===t&&(t?.status===`success`||t?.status===`error`)&&r.delete(e)},s=e=>{i.get(e)?.controller.abort(),i.delete(e),r.delete(e),o(e)};return{select:(a,c)=>{if(r.get(a)?.status===`applying`)return!1;if(!c)return s(a),!0;if(r.set(a,{selection:c,status:`pending`}),o(a),i.has(a))return!0;let l=new AbortController,{signal:u}=l,d={controller:l,promise:Promise.resolve()};return i.set(a,d),d.promise=(async()=>{try{for(;!u.aborted;){let s=await e(a,u);if(u.aborted)return;if(s){await Qs(n,u);continue}let c=r.get(a);if(!c)return;r.set(a,{...c,status:`applying`}),o(a);let l=await t(a,c.selection);u.aborted||(i.get(a)===d&&i.delete(a),r.set(a,{...c,status:`success`,result:l}),o(a));return}}catch(e){let t=r.get(a);!u.aborted&&t&&(i.get(a)===d&&i.delete(a),r.set(a,{...t,status:`error`,error:e}),o(a))}finally{i.get(a)===d&&i.delete(a)}})(),!0},subscribe(e){a.add(e);for(let[t,n]of r)e(t,n),r.get(t)===n&&(n.status===`success`||n.status===`error`)&&r.delete(t);return()=>{a.delete(e)}},async dispose(){let e=[...i.values()];a.clear();for(let e of i.keys())s(e);r.clear(),await Promise.all(e.map(e=>e.promise))}}}var ec=$s({isStreaming:async(e,t)=>{let n=await X.getLiveSession(e,{signal:t});return!!(n.configurationBusy??n.streaming)},apply:(e,t)=>t.model?X.updateModel(e,t.model.provider,t.model.modelId):X.setThinkingLevel(e,t.thinkingLevel)});function tc({notify:e,requestText:t,requestConfirm:n,availableModels:r,sessionStatesRef:i,updateSessionState:a,updateSessions:o,replaceSessionStates:s,setGlobalError:c,syncLiveSession:u}){let{t:d,language:f}=l(),[p,m]=(0,Q.useState)(null),h=(0,Q.useCallback)(e=>{a(e,e=>({...e,runtimeSelectionRevision:(e.runtimeSelectionRevision||0)+1}))},[a]),g=(0,Q.useCallback)((e,t)=>{o(n=>n.map(n=>n.id===e?t(n):n))},[o]),_=(0,Q.useCallback)(async t=>{if(t)try{let n=await X.pauseGoal(t);a(t,{goal:n.goal||null}),g(t,e=>({...e,goal:n.goal||null})),e(d(`chat:chatPage.goalPaused`),`info`)}catch(e){a(t,{error:Z(e)})}},[e,d,a,g]),v=(0,Q.useCallback)(async(t,n)=>{if(t)try{let r=await X.setGoalBudget(t,n);a(t,{goal:r.goal||null}),g(t,e=>({...e,goal:r.goal||null})),e(d(`chat:chatPage.goalTokenBudgetUpdated`),`info`)}catch(e){a(t,{error:Z(e)})}},[e,d,a,g]),y=(0,Q.useCallback)(async t=>{let n=i.current[t];if(!(!t||n?.streaming||n?.compaction?.active)){a(t,{compaction:{...n?.compaction||{},active:!0,status:`running`,reason:`manual`},error:``});try{let n=await X.compactSession(t);a(t,{compaction:n.compaction||null,contextUsage:n.contextUsage||null}),e(d(`chat:chatPage.contextCompacted`))}catch(e){await u(t).catch(()=>{}),a(t,{error:Z(e)})}}},[e,i,u,d,a]),b=(0,Q.useCallback)(async e=>{let t=await X.updateCompactionPreference(e);s(Object.fromEntries(Object.entries(i.current).map(([e,n])=>{let r=Number(n.contextUsage?.contextWindow)||0;return r?[e,{...n,contextUsage:{...n.contextUsage,compactAtPercent:t.thresholdPercent,compactAtTokens:Math.floor(r*t.thresholdPercent/100)}}]:[e,n]})))},[s,i]),S=(0,Q.useCallback)((e,t={})=>{let n=String(t.model||``),r=String(i.current[e]?.model||``);if(n&&r&&n!==r)return;let o=Array.isArray(t.availableThinkingLevels)?t.availableThinkingLevels.map(e=>String(e)):Array.isArray(t.availableLevels)?t.availableLevels.map(e=>String(e)):[],s=String(t.thinkingLevel||``);a(e,{thinkingLevel:s||void 0,availableThinkingLevels:o,thinkingStatus:String(t.thinkingStatus||t.status||``),thinkingMessage:String(t.thinkingMessage||t.message||``),switchingThinking:!1}),s&&g(e,e=>({...e,thinkingLevel:s}))},[i,a,g]),C=(0,Q.useCallback)(async e=>{if(!e)return;let t=i.current[e]?.runtimeSelectionRevision,n=i.current[e];if(!(n?.switchingModel||n?.switchingThinking))try{let n=await X.getThinkingLevel(e);if(i.current[e]?.runtimeSelectionRevision!==t)return;S(e,n)}catch{if(i.current[e]?.runtimeSelectionRevision!==t)return;a(e,{thinkingStatus:`error`,thinkingMessage:d(`chat:focusSession.thinkingLevelsLoadFailed`)})}},[S,i,d,a]),w=(0,Q.useCallback)(async(t,o)=>{let s=r.find(e=>e.key===o);if(!t||!s)return;let c=i.current[t];if(c?.switchingModel||c?.switchingThinking)return;if(c?.streaming||c?.pendingRuntimeSelection){ec.select(t,s.key===c.model?void 0:{model:s});return}h(t);let l=c?.model||``,u=!!c?.messages?.length&&!c?.compaction?.active;a(t,{switchingModel:!0,model:s.key,error:``}),g(t,e=>({...e,model:s.key}));try{let r=await X.updateModel(t,s.provider,s.modelId);h(t),a(t,{model:r.model||s.key,contextUsage:r.contextUsage??null,switchingModel:!1}),g(t,e=>({...e,model:r.model||s.key})),S(t,r),e(d(`chat:chatPage.switchedToModel`,{model:s.label})),u&&await n({title:d(`chat:chatPage.compactAfterModelSwitch`),message:d(`chat:chatPage.compactAfterModelSwitchDescription`),confirmLabel:d(`chat:chatPage.compactNow`),tone:`primary`})&&await y(t)}catch(e){h(t),a(t,{switchingModel:!1,model:l||void 0,error:Z(e)}),l&&g(t,e=>({...e,model:l}))}},[S,r,y,h,e,n,i,d,a,g]),T=(0,Q.useCallback)(async(t,n)=>{let r=String(n||``).trim();if(!t||!r)return;let o=i.current[t]||{};if(o.switchingModel||o.switchingThinking)return;if(o.streaming||o.pendingRuntimeSelection){if(o.pendingRuntimeSelection?.model)return;ec.select(t,r===o.thinkingLevel?void 0:{thinkingLevel:r});return}h(t);let s=String(o.thinkingLevel||``);a(t,{switchingThinking:!0,thinkingLevel:r,error:``}),g(t,e=>({...e,thinkingLevel:r}));try{let n=await X.setThinkingLevel(t,r);h(t),S(t,n),e(d(`chat:chatPage.switchedToThinkingLevel`,{level:String(n.thinkingLevel||r)}))}catch(e){h(t),a(t,{switchingThinking:!1,thinkingLevel:s||void 0,error:Z(e)}),s&&g(t,e=>({...e,thinkingLevel:s}))}},[S,h,e,i,d,a,g]);(0,Q.useEffect)(()=>ec.subscribe((t,n)=>{if(!n){a(t,{pendingRuntimeSelection:void 0});return}let{selection:r,status:i}=n;if(i===`pending`||i===`applying`){h(t),a(t,{pendingRuntimeSelection:{model:r.model?.key,thinkingLevel:r.thinkingLevel},switchingModel:i===`applying`&&!!r.model,switchingThinking:i===`applying`&&!!r.thinkingLevel,error:``});return}if(h(t),a(t,{pendingRuntimeSelection:void 0,switchingModel:!1,switchingThinking:!1,...n.error?{error:Z(n.error)}:{}}),i===`error`)return;let o=n.result||{};if(r.model){let e=String(o.model||r.model.key);a(t,{model:e,contextUsage:o.contextUsage??null}),g(t,t=>({...t,model:e}))}S(t,o),e(r.model?d(`chat:chatPage.switchedToModel`,{model:r.model.label}):d(`chat:chatPage.switchedToThinkingLevel`,{level:String(o.thinkingLevel||r.thinkingLevel)}))}),[S,h,e,d,a,g]);let E=(0,Q.useCallback)(async(t,r)=>{if(!t)return!1;a(t,{switchingPermission:!0,error:``});try{if(r===`full-access`&&!await n({title:d(`chat:chatPage.enableFullAccess`),message:d(`chat:chatPage.fullAccessAllowsTheAgentToUseFilesAndNetworkServicesOutsideTheWorkspaceAndShellCommandsWillNoLon`),confirmLabel:d(`chat:chatPage.enableFullAccess`)}))return a(t,{switchingPermission:!1}),!1;let i=await X.updateExecutionMode(t,r);return a(t,{executionMode:i.executionMode,permissionMode:i.permissionMode,switchingPermission:!1}),g(t,e=>({...e,executionMode:i.executionMode,permissionMode:i.permissionMode})),e(d(`chat:chatPage.executionModeChangedToMode`,{mode:i.executionMode===`approval-required`?d(`chat:chatPage.approvalRequired`):i.executionMode===`workspace-write`?d(`chat:focusSession.workspaceWrite`):d(`chat:chatPage.fullAccess`)})),!0}catch(e){return a(t,{switchingPermission:!1,error:Z(e)}),!1}},[e,n,d,a,g]),D=(0,Q.useCallback)(async(e,t)=>{if(!e)return!1;try{let n=await X.updateRunMode(e,t),r=String(n.runMode||t);return a(e,{runMode:r}),g(e,e=>({...e,runMode:r})),!0}catch(t){return a(e,{error:Z(t)}),!1}},[a,g]),O=(0,Q.useCallback)(async(t,n,r)=>{a(t,{error:``});try{let e=await X.resolveApproval(t,n,r);a(t,e=>({...e,approvals:(e.approvals||[]).filter(e=>e.id!==n)})),e.alreadyResolved&&u(t,{force:!0})}catch(n){if(await u(t,{force:!0}),n instanceof x&&n.status===404){e(d(`chat:chatPage.approvalStatusUpdated`),`info`);return}throw a(t,{error:Z(n)}),n}},[e,u,d,a]),k=(0,Q.useCallback)(async(t,n,r)=>{let i=()=>a(t,e=>({...e,questions:(e.questions||[]).filter(e=>(e.id??e.questionId)!==n)}));try{await X.answerQuestion(t,n,r),i()}catch(n){if(await u(t,{force:!0}),n instanceof x&&(n.status===404||n.status===409)){i(),e(d(`board:question.closed`),`info`);return}throw n}},[e,u,d,a]),A=(0,Q.useCallback)(async t=>{try{await X.deliverSessionMessages(t)}catch(t){e(Z(t),`error`)}await u(t,{force:!0})},[e,u]),j=(0,Q.useCallback)(async t=>{try{await X.dismissSessionMessages(t),a(t,e=>({...e,workspace:e.workspace?.neighbours.length?{...e.workspace,messages:[]}:null}))}catch(n){e(Z(n),`error`),await u(t,{force:!0})}},[e,u,a]),M=(0,Q.useCallback)(async(t,n)=>{if(!(!t?.id||i.current[t.id]?.streaming)){a(t.id,{switchingCwd:!0,error:``});try{let r=await X.updateCwd(t.id,n);a(t.id,{cwd:r.cwd,switchingCwd:!1}),g(t.id,e=>({...e,cwd:r.cwd})),m(null),e(d(`chat:chatPage.workingDirectoryChangedToWorkspace`,{workspace:Mn(r.cwd,f)}))}catch(e){throw a(t.id,{switchingCwd:!1,error:Z(e)}),e}}},[f,e,i,d,a,g]);return{workspaceSession:p,setWorkspaceSession:m,switchSessionCwd:M,selectSessionWorkspace:(0,Q.useCallback)(async t=>{if(t?.id){if(i.current[t.id]?.streaming){e(d(`chat:chatPage.stopTheActiveRunBeforeChangingTheWorkspace`),`info`);return}try{let e=await tr(t.cwd,d(`common:workspacePicker.setWorkingDirectory`));e.status===`picked`?await M(t,e.path):e.status===`unavailable`&&m(t)}catch(e){a(t.id,{switchingCwd:!1,error:Z(e)})}}},[e,i,M,d,a]),renameSession:(0,Q.useCallback)(async n=>{if(!n?.id)return;if(i.current[n.id]?.streaming){e(d(`chat:chatPage.stopTheActiveRunBeforeRenamingTheChat`),`info`);return}let r=await t({title:d(`chat:chatPage.renameChat`),inputLabel:d(`chat:chatPage.chatTitle`),value:n.name,confirmLabel:d(`chat:chatPage.save`)});if(r!==null&&r!==n.name)try{let t=await X.renameSession(n.id,r);g(n.id,e=>({...e,name:t.name})),dn({id:n.id,name:t.name}),e(d(`chat:chatPage.chatTitleUpdated`))}catch(e){c(Z(e))}},[e,t,i,c,d,g]),pauseGoal:_,setGoalBudget:v,compactSession:y,setCompactionThreshold:b,loadSessionThinkingLevel:C,switchSessionModel:w,switchSessionThinkingLevel:T,switchSessionExecutionMode:E,switchSessionRunMode:D,resolveToolApproval:O,answerQuestion:k,deliverSessionMessages:A,dismissSessionMessages:j}}function nc(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rc(e){if(!nc(e)||typeof e.created!=`boolean`)throw C();if(e.session===null){if(e.expiresAt!==null||e.created)throw C();return{session:null,expiresAt:null,created:!1}}let t=e.session;if(!nc(t)||typeof t.id!=`string`||!t.id||typeof e.expiresAt!=`string`||!Number.isFinite(Date.parse(e.expiresAt)))throw C();let n={id:t.id};for(let e of[`name`,`cwd`,`model`,`thinkingLevel`,`executionMode`,`permissionMode`,`runMode`]){let r=t[e];if(r!=null&&typeof r!=`string`)throw C();typeof r==`string`&&(n[e]=r)}if(t.streaming!==void 0&&typeof t.streaming!=`boolean`)throw C();return typeof t.streaming==`boolean`&&(n.streaming=t.streaming),{session:n,expiresAt:e.expiresAt,created:e.created}}async function ic(e,t){return rc(await T(`/api/sessions/${encodeURIComponent(e)}/side-chat`,{signal:t}))}async function ac(e,t){let n=rc(await T(`/api/sessions/${encodeURIComponent(e)}/side-chat`,{method:`POST`,signal:t}));if(!n.session)throw C();return n}function oc({runtime:e,children:t}){let[n,r]=(0,Q.useState)({}),i=(0,Q.useRef)(n),a=(0,Q.useRef)(!0),o=(0,Q.useRef)(e),s=(0,Q.useRef)(new Map),c=(0,Q.useRef)(new Map);(0,Q.useLayoutEffect)(()=>{o.current=e},[e]),(0,Q.useLayoutEffect)(()=>(a.current=!0,()=>{a.current=!1}),[]);let l=(0,Q.useCallback)((e,t)=>{let n={...i.current,[e]:{...i.current[e]??Re,...t}};i.current=n,r(n)},[]),u=(0,Q.useCallback)(async(e,t=!1)=>{if(!a.current)return null;let n=c.current.get(e);if(n){let r=await n.promise;return!t||n.create?r:u(e,!0)}let r=new AbortController;l(e,{loading:!0,error:``});let d=(async()=>{try{let n=await(t?ac:ic)(e,r.signal);if(r.signal.aborted)return null;let a=i.current[e]?.session?.id;if(a&&a!==n.session?.id&&(o.current.discard(a),s.current.get(a)?.(),s.current.delete(a),de(a)),l(e,{...n,expired:!n.session&&!!(a||i.current[e]?.expired)}),n.session){if(s.current.has(n.session.id)||s.current.set(n.session.id,o.current.retainSessionState(n.session.id)),await o.current.syncLiveSession(n.session.id),r.signal.aborted)return null;await o.current.loadSessionMessages(n.session.id)}return r.signal.aborted?null:n}catch(t){return r.signal.aborted||l(e,{error:Z(t)}),null}finally{r.signal.aborted||l(e,{loading:!1}),c.current.get(e)?.controller===r&&c.current.delete(e)}})();return c.current.set(e,{create:t,controller:r,promise:d}),d},[l]);(0,Q.useEffect)(()=>{a.current=!0;let e=c.current,t=s.current,n=()=>{for(let[e,t]of Object.entries(i.current))t.expiresAt&&Date.parse(t.expiresAt)<=Date.now()&&!c.current.has(e)&&u(e)},r=window.setInterval(n,6e4),o=()=>{document.visibilityState===`visible`&&n()};return document.addEventListener(`visibilitychange`,o),()=>{a.current=!1,window.clearInterval(r),document.removeEventListener(`visibilitychange`,o);for(let t of e.values())t.controller.abort();e.clear();for(let e of t.values())e();t.clear()}},[u]);let d=(0,Q.useCallback)((e,t)=>l(e,{draft:t}),[l]),f=(0,Q.useMemo)(()=>({entries:n,runtime:e,load:u,setDraft:d}),[n,e,u,d]);return(0,$.jsx)(Pe.Provider,{value:f,children:t})}var sc=`new`,cc=40;function lc(e){let t=window.__TAURI__?.core?.invoke??window.__TAURI_INTERNALS__?.invoke;return t?t(e):Promise.reject(Error(`native bridge unavailable`))}function uc({notify:e,navigate:t,browserNotify:n,pendingAsset:r,onAssetConsumed:i,requestText:a,requestConfirm:o,routeSessionId:s,onRouteSessionChange:c,routeLeading:u,pageChrome:d}){let{t:f}=l(),p=s!==void 0,m=p&&s!==sc?s:``,h=M(e=>e.client===`mobile-app`),g=M(e=>e.loaded),_=A(),v=h||_,y=(0,Q.useRef)(null),b=(0,Q.useRef)(new Set),x=(0,Q.useRef)(new Map),S=(0,Q.useRef)(new Map),C=(0,Q.useRef)(null),T=us({notify:e}),E=(0,Q.useRef)(new Set),D=(0,Q.useRef)(new Set);(0,Q.useEffect)(()=>{for(let e of D.current)T.sessions.some(t=>t.id===e&&t.unread)||D.current.delete(e);let e=e=>{let t=T.activeId;!t||document.visibilityState!==`visible`||!T.sessions.some(e=>e.id===t&&e.unread)||E.current.has(t)||!e&&D.current.has(t)||(E.current.add(t),D.current.add(t),Dn(t,{read:!0}).catch(()=>void 0).finally(()=>E.current.delete(t)))};return e(),document.addEventListener(`visibilitychange`,e),()=>document.removeEventListener(`visibilitychange`,e)},[T.activeId,T.sessions]);let O=k(e=>e.capabilities.features.sessionActivityOrder===!0),j=T.activeId,N=!!j&&T.sessions.some(e=>e.id===j);(0,Q.useEffect)(()=>{!O||!j||!N||Dn(j,{opened:!0}).catch(()=>void 0)},[O,j,N]);let P=k(e=>e.capabilities.features[`board.events`]===!0),F=js({sessionStates:T.sessionStates,sessionStatesRef:T.sessionStatesRef,localStreamSessionsRef:b,streamGenerationRef:x,updateSessionState:T.updateSessionState,updateSessions:T.updateSessions,pollOnly:P?T.activeId||null:void 0}),I=ds({setActiveId:T.setActiveId,loadSessionMessages:F.loadSessionMessages,openRoutedSession:p?c:void 0}),L=T.createSessionRecord,R=F.loadSessionMessages,z=T.refreshSessions,B=T.sessionStatesRef,V=F.syncLiveSession,H=T.setGlobalError,U=I.openSession,[W,ee]=(0,Q.useState)({sessionId:``,token:0}),te=(0,Q.useCallback)(async(e=``)=>{let t=null;h&&(t=await lc(`mobile_state`).catch(()=>null));let n=Dr(h,t),r=await L(e,{inheritRecentCwd:n});return r?(U(r),r):``},[L,h,U]),ne=T.setActiveId,re=!!(m&&T.sessions.some(e=>e.id===m));(0,Q.useEffect)(()=>{!m||T.activeId===m||!re&&!T.loading||ne(m)},[T.activeId,T.loading,re,m,ne]);let ie=(0,Q.useRef)(``);(0,Q.useEffect)(()=>{if(!m||ie.current===m)return;ie.current=m;let e=cn();e?.sessionId===m&&e.targetEntryId&&R(m,{force:!0,limit:cc})},[R,m]);let ae=T.activeId,oe=T.sessions.some(e=>e.id===ae&&e.streaming===!0),se=T.sessions.find(e=>e.id===ae)?.botId;(0,Q.useEffect)(()=>{ae&&se&&V(ae)},[se,oe,ae,V]);let ce=(0,Q.useRef)({id:``,streaming:!1});(0,Q.useEffect)(()=>{let e=ce.current;ce.current={id:ae,streaming:oe},ae&&(e.id===ae?e.streaming!==oe:oe)&&As(B.current[ae],{catalogStreaming:oe,localStreamOwned:b.current.has(ae)})&&R(ae,{force:!0})},[oe,ae,R,B]),(0,Q.useEffect)(()=>kn(e=>{let t=e===`*`?ae?[ae]:[]:[e];for(let e of t){let t=B.current[e];!t?.loaded||t.streaming||b.current.has(e)||V(e)}}),[ae,B,V]),(0,Q.useEffect)(()=>{if(!m||!re)return;let e=Yr();e&&yr(m,e.url);let t=e=>{let t=e.detail?.url;t&&yr(m,t)};return window.addEventListener(Xr,t),()=>window.removeEventListener(Xr,t)},[re,m]);let G=Zs({browserNotify:n,notify:e,defaultModel:T.defaultModel,localStreamSessionsRef:b,streamGenerationRef:x,streamActivityRef:S,sessionStatesRef:T.sessionStatesRef,setActiveId:T.setActiveId,setGlobalError:T.setGlobalError,updateSessionState:T.updateSessionState,updateSessions:T.updateSessions,createSession:te,loadSessionMessages:F.loadSessionMessages,refreshSessions:T.refreshSessions,syncLiveSession:F.syncLiveSession}),{sendPrompt:le,retryLastTurn:ue}=G,pe=T.adoptCreatedSession,me=(0,Q.useCallback)(async(t,n,r=[],i=!1,a=!1,o=null,s=null,c={})=>{let l=n.trim()||(r.length?f(`chat:chatPage.pleaseAnalyzeTheseAttachments`):``)||(s?s.resourceName:``);if(!l)return!1;let u;try{u=await t.prepare(l)}catch(t){return e(Z(t),`error`),!1}return pe(u.session),t.onSent(),de(fe),U(u.session.id),le(n,u.session.id,r,i,a,o,s,{onAccepted:c.onAccepted})},[pe,e,U,le,f]),K=tc({notify:e,requestText:a,requestConfirm:o,availableModels:T.availableModels,sessionStatesRef:T.sessionStatesRef,updateSessionState:T.updateSessionState,updateSessions:T.updateSessions,replaceSessionStates:T.replaceSessionStates,setGlobalError:T.setGlobalError,syncLiveSession:F.syncLiveSession}),he=(0,Q.useCallback)(e=>{if(document.visibilityState!==`visible`||C.current)return;let t=h||typeof window.matchMedia==`function`&&window.matchMedia(`(pointer: coarse)`).matches,n=(async()=>{h&&await w().catch(()=>void 0);let n=[];try{n=await z(void 0,{preserveExistingOnEmpty:!0})}catch{}let r=new Set([...Object.keys(B.current),...T.activeId?[T.activeId]:[],...n.filter(e=>e.streaming).map(e=>e.id)]);await Promise.allSettled(Array.from(r).map(n=>b.current.has(n)&&!hs({mobile:t,reason:e,lastEventAt:S.current.get(n)??0})?void 0:V(n,{force:!0})))})().finally(()=>{C.current=null});C.current=n},[T.activeId,h,z,B,V]);(0,Q.useEffect)(()=>{let e=e=>he(e.type===`online`?`online`:e.type===`pageshow`&&e.persisted?`restored`:`visible`);return document.addEventListener(`visibilitychange`,e),window.addEventListener(`pageshow`,e),window.addEventListener(`online`,e),()=>{document.removeEventListener(`visibilitychange`,e),window.removeEventListener(`pageshow`,e),window.removeEventListener(`online`,e)}},[he]);let q=(0,Q.useCallback)(async e=>{await R(e,{force:!0}),await z(e)},[R,z]),ge=(0,Q.useCallback)(async(t,n,r)=>{if(!(!t?.id||!n))try{H(``);let i=null;if(r?.rewindFiles){let e=await X.previewFileRewind(t.id,n);if(!await o(Lr(e,f)))return;i=await X.rewindFiles(t.id,n)}let a=await X.navigateSessionTree(t.id,n,!1);if(a.cancelled)return;mr(t.id,a),await q(t.id),ee(e=>({sessionId:t.id,token:e.token+1})),i?e(Rr(i,f)):zr(t.id,a,f(`chat:chatPage.branchedFromNode`),{notify:e,t:f})}catch(e){H(e instanceof Error?e.message:String(e))}},[e,q,o,H,f]);(0,Q.useEffect)(()=>nn(e=>{B.current[e]&&q(e).catch(()=>void 0)}),[q,B]);let _e=(0,Q.useCallback)(async(t,n)=>{if(!t?.id||!n)return;let r=await a({title:f(`chat:chatPage.createChildChat`),inputLabel:f(`chat:chatPage.chatTitle`),value:`${f(`chat:chatPage.separateChatSuffix`)} · ${t.name||f(`chat:chatPage.newChat`)}`,confirmLabel:f(`chat:chatPage.create`)});if(r!==null)try{H(``);let i=await X.deriveSession(t.id,n,r);await z(),U(i.id),ee(e=>({sessionId:i.id,token:e.token+1})),e(f(`chat:chatPage.childChatCreated`))}catch(e){H(e instanceof Error?e.message:String(e))}},[e,U,z,a,H,f]),ve=(0,Q.useCallback)(()=>t(`config`),[t]),ye=(0,Q.useMemo)(()=>({sessions:T.sessions,subscribeSessionState:T.subscribeSessionState,getSessionState:T.getSessionState,defaultModel:T.defaultModel,availableModels:T.availableModels,globalError:T.globalError,activeId:T.activeId,mobileLayout:v,requestConfirm:o,sessionTreePulseSessionId:W.sessionId,sessionTreePulseToken:W.token,pendingAsset:r,onAssetConsumed:i,notify:e,openModelSettings:ve,loadSessionMessages:F.loadSessionMessages,loadOlderMessages:F.loadOlderMessages,sendPrompt:G.sendPrompt,sendNewTask:me,retryLastTurn:G.retryLastTurn,queuePrompt:G.queuePrompt,withdrawQueuedInput:G.withdrawQueuedInput,sendQueuedInputNow:G.sendQueuedInputNow,abort:G.abort,pauseGoal:K.pauseGoal,setGoalBudget:K.setGoalBudget,compactSession:K.compactSession,setCompactionThreshold:K.setCompactionThreshold,switchSessionModel:K.switchSessionModel,loadSessionThinkingLevel:K.loadSessionThinkingLevel,switchSessionThinkingLevel:K.switchSessionThinkingLevel,switchSessionExecutionMode:K.switchSessionExecutionMode,switchSessionRunMode:K.switchSessionRunMode,resolveToolApproval:K.resolveToolApproval,answerQuestion:K.answerQuestion,deliverSessionMessages:K.deliverSessionMessages,dismissSessionMessages:K.dismissSessionMessages,selectSessionWorkspace:K.selectSessionWorkspace,renameSession:K.renameSession,branchFromEntry:ge,createChildSession:_e,reloadSessionBranch:q}),[T.sessions,T.subscribeSessionState,T.getSessionState,T.defaultModel,T.availableModels,T.globalError,T.activeId,v,o,W.sessionId,W.token,r,i,e,ve,F.loadSessionMessages,F.loadOlderMessages,G.sendPrompt,me,G.retryLastTurn,G.queuePrompt,G.withdrawQueuedInput,G.sendQueuedInputNow,G.abort,K.pauseGoal,K.setGoalBudget,K.compactSession,K.setCompactionThreshold,K.switchSessionModel,K.loadSessionThinkingLevel,K.switchSessionThinkingLevel,K.switchSessionExecutionMode,K.switchSessionRunMode,K.resolveToolApproval,K.deliverSessionMessages,K.dismissSessionMessages,K.selectSessionWorkspace,K.renameSession,ge,_e,q]),be=T.discardSessionState,xe=(0,Q.useMemo)(()=>({subscribeSessionState:T.subscribeSessionState,getSessionState:T.getSessionState,retainSessionState:T.retainSessionState,discard:e=>{x.current.set(e,(x.current.get(e)??0)+1),b.current.delete(e),be(e)},loadSessionMessages:F.loadSessionMessages,loadOlderMessages:F.loadOlderMessages,syncLiveSession:F.syncLiveSession,send:async(e,t)=>{await le(t,e,[],!1,!1,null,null,{activate:!1})},retry:e=>ue(e,{activate:!1}),abort:G.abort,approve:K.resolveToolApproval}),[T.subscribeSessionState,T.getSessionState,T.retainSessionState,be,F.loadSessionMessages,F.loadOlderMessages,F.syncLiveSession,le,ue,G.abort,K.resolveToolApproval]);return(0,$.jsxs)(oc,{runtime:xe,children:[(0,$.jsx)(`div`,{ref:y,className:`chat-layout dock-layout relative flex w-full min-w-0 min-h-0 flex-1`,children:T.loading?(0,$.jsx)(nr,{kind:`loading`,title:f(`chat:chatPage.wakingTheAgent`),description:f(`chat:chatPage.modelsSessionsAndContextAreSettlingIntoPlace`)}):(0,$.jsx)(`div`,{className:`chat-dock-workspace relative h-full w-full min-w-0 min-h-0 flex-1 [isolation:isolate] overflow-hidden border-0 rounded-none bg-panel`,children:(0,$.jsx)(Qo.Provider,{value:ye,children:(0,$.jsx)(Ye.Provider,{value:p?d??null:null,children:(0,$.jsx)(Bi.Provider,{value:p?u??null:null,children:g&&(p?m&&!re?(0,$.jsx)(nr,{kind:`empty`,title:f(`navigation:shell.sessionNotFound`),description:f(`navigation:shell.sessionNotFoundHint`),action:d?.onHome?(0,$.jsx)(Y,{variant:`secondary`,onClick:d.onHome,children:f(`board:home.goHome`)}):(0,$.jsx)(Y,{variant:`secondary`,onClick:()=>t(`board`),children:f(`navigation:shell.backToBoardLabel`)})}):s===sc&&d?.newTaskDraft?(0,$.jsx)(rs,{draft:d.newTaskDraft}):m?(0,$.jsx)(is,{sessionId:m,onCreateSession:te}):T.globalError?(0,$.jsx)(nr,{kind:`error`,title:f(`navigation:shell.createSessionFailed`),description:T.globalError,action:(0,$.jsx)(Y,{variant:`secondary`,onClick:()=>void te(),children:f(`navigation:more.retry`)})}):(0,$.jsx)(nr,{kind:`loading`,title:f(`chat:chatPage.wakingTheAgent`)}):(0,$.jsx)(is,{onCreateSession:te}))})})})})}),K.workspaceSession&&(0,$.jsx)(He,{open:!0,initialPath:K.workspaceSession.cwd,description:f(`common:workspacePicker.selectWorkspaceForChat`,{name:K.workspaceSession.name}),onOpenChange:e=>!e&&K.setWorkspaceSession(null),onSelect:e=>K.switchSessionCwd(K.workspaceSession,e)})]})}export{uc as ChatPage};
|