@piagent/platform 1.49.0 → 1.49.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/docs/command-reference-vietnamese.md +2 -2
  3. package/docs/distribution-standard.md +6 -6
  4. package/docs/harness-conformance.md +3 -3
  5. package/docs/operator-manual-vietnamese.md +7 -7
  6. package/docs/publishing-for-teams.md +1 -0
  7. package/docs/release-install-policy.md +2 -2
  8. package/docs/team-onboarding.md +2 -2
  9. package/docs-site/architecture.html +1 -1
  10. package/docs-site/assets/search-en.json +1 -1
  11. package/docs-site/assets/search-vi.json +1 -1
  12. package/docs-site/benchmark.html +1 -1
  13. package/docs-site/commands.html +1 -1
  14. package/docs-site/context-engine.html +1 -1
  15. package/docs-site/ecosystem.html +1 -1
  16. package/docs-site/en/architecture.html +1 -1
  17. package/docs-site/en/benchmark.html +1 -1
  18. package/docs-site/en/commands.html +1 -1
  19. package/docs-site/en/context-engine.html +1 -1
  20. package/docs-site/en/ecosystem.html +1 -1
  21. package/docs-site/en/index.html +9 -9
  22. package/docs-site/en/mcp-approval.html +1 -1
  23. package/docs-site/en/mcp-auth.html +1 -1
  24. package/docs-site/en/mcp-servers.html +1 -1
  25. package/docs-site/en/mcp.html +1 -1
  26. package/docs-site/en/permissions.html +1 -1
  27. package/docs-site/en/profiles.html +1 -1
  28. package/docs-site/en/quickstart.html +1 -1
  29. package/docs-site/en/runtime.html +1 -1
  30. package/docs-site/en/scope.html +1 -1
  31. package/docs-site/en/security.html +1 -1
  32. package/docs-site/en/team.html +1 -1
  33. package/docs-site/en/update.html +3 -3
  34. package/docs-site/en/whats-new.html +30 -16
  35. package/docs-site/en/windows.html +1 -1
  36. package/docs-site/en/workflows.html +1 -1
  37. package/docs-site/index.html +9 -9
  38. package/docs-site/mcp-approval.html +1 -1
  39. package/docs-site/mcp-auth.html +1 -1
  40. package/docs-site/mcp-servers.html +1 -1
  41. package/docs-site/mcp.html +1 -1
  42. package/docs-site/permissions.html +1 -1
  43. package/docs-site/profiles.html +1 -1
  44. package/docs-site/quickstart.html +1 -1
  45. package/docs-site/releases.json +46 -0
  46. package/docs-site/runtime.html +1 -1
  47. package/docs-site/scope.html +1 -1
  48. package/docs-site/security.html +1 -1
  49. package/docs-site/team.html +1 -1
  50. package/docs-site/update.html +3 -3
  51. package/docs-site/whats-new.html +30 -16
  52. package/docs-site/windows.html +1 -1
  53. package/docs-site/workflows.html +1 -1
  54. package/evals/private-holdout-v1/public-exposure.v2.json +2 -2
  55. package/package.json +1 -1
  56. package/packages/piagent-core/managed/fast-mode.mjs +19 -16
  57. package/packages/piagent-core/managed/helper-run.mjs +19 -2
  58. package/packages/piagent-core/managed/request-stream.mjs +2 -2
  59. package/packages/piagent-core/managed/session.mjs +2 -2
  60. package/packages/piagent-core/managed/workflow.mjs +3 -0
  61. package/packages/piagent-core/package.json +1 -1
  62. package/packages/piagent-webui/dist/client/assets/ActivityPanel-CmjxPmNT.js +1 -0
  63. package/packages/piagent-webui/dist/client/assets/{App-CU-wndsb.js → App-JrRb7jgn.js} +1 -1
  64. package/packages/piagent-webui/dist/client/assets/GatewayApp-BmkqeXih.js +63 -0
  65. package/packages/piagent-webui/dist/client/assets/{InspectionApp-Bfvr2S8S.js → InspectionApp-9jBsgkVJ.js} +1 -1
  66. package/packages/piagent-webui/dist/client/assets/{SessionAgentWorkspace-0Xowe-sG.js → SessionAgentWorkspace-RQ0N65d9.js} +1 -1
  67. package/packages/piagent-webui/dist/client/assets/{SessionInspectorDrawer-72Z5908P.js → SessionInspectorDrawer-BWyEN4bf.js} +2 -2
  68. package/packages/piagent-webui/dist/client/assets/{SettingsNavigation-Bu1A7x4F.js → SettingsNavigation-Wx-q5QQk.js} +1 -1
  69. package/packages/piagent-webui/dist/client/assets/{SettingsPage-DxGxE0AF.js → SettingsPage-xAt6kSyZ.js} +1 -1
  70. package/packages/piagent-webui/dist/client/assets/{TerminalPanel-BKgx9SjR.js → TerminalPanel-DzHdSjpN.js} +1 -1
  71. package/packages/piagent-webui/dist/client/assets/{WorkspaceCodeEditor-DFrh3qs2.js → WorkspaceCodeEditor-CEuPTTBd.js} +1 -1
  72. package/packages/piagent-webui/dist/client/assets/{WorkspaceExplorer-D6ufO-eP.js → WorkspaceExplorer-B_NwYf4S.js} +3 -3
  73. package/packages/piagent-webui/dist/client/assets/{index-CjM70M7D.css → index-De7bIeMc.css} +1 -1
  74. package/packages/piagent-webui/dist/client/assets/{index-C3CJv1wM.js → index-fUpioGMZ.js} +2 -2
  75. package/packages/piagent-webui/dist/client/index.html +2 -2
  76. package/packages/piagent-webui/gateway/gateway-session-stream.ts +28 -0
  77. package/packages/piagent-webui/gateway/managed-projection.ts +8 -1
  78. package/packages/piagent-webui/gateway/session-catalog.ts +2 -2
  79. package/packages/piagent-webui/server/tool-call-summary.ts +13 -0
  80. package/packages/piagent-webui/server/transcript-projection.ts +11 -4
  81. package/schemas/piagent-webui/gateway-protocol-v1.schema.json +2 -0
  82. package/schemas/piagent-webui/session-catalog-v1.schema.json +1 -1
  83. package/schemas/piagent-webui/transcript-v1.schema.json +17 -1
  84. package/scripts/company-terminal.mjs +2 -2
  85. package/packages/piagent-webui/dist/client/assets/ActivityPanel-Bv-jc1s3.js +0 -1
  86. package/packages/piagent-webui/dist/client/assets/GatewayApp-MIvgr7kn.js +0 -63
@@ -0,0 +1,63 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/WorkspaceQuickOpen-Bi-kTEEU.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-DNZbaWhT.js","assets/ui-preferences-OfS30-ZV.js","assets/workspace-api-CFBR73lU.js","assets/bootstrap-CedkNtRG.js","assets/TerminalPanel-DzHdSjpN.js","assets/index-fUpioGMZ.js","assets/index-De7bIeMc.css","assets/terminal-transport-Dk5pYNX5.js","assets/tab-close-BwkkhMH7.js","assets/WorkspaceExplorer-B_NwYf4S.js","assets/api-BQS4Dtrr.js","assets/workspace-navigation-DW8zhH6U.js","assets/composer-drafts-BtMaVw8W.js","assets/LineReview-CB3mQe7m.js","assets/WorkspaceFilePreview-CvIBYige.js","assets/MarkdownMessage-zw5RxDmZ.js","assets/AttachmentImage-eZKqLYZ2.js","assets/SettingsPage-xAt6kSyZ.js","assets/view-model-CWNiS4JN.js","assets/SettingsNavigation-Wx-q5QQk.js","assets/SessionInspectorDrawer-BWyEN4bf.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{$t as t,A as n,An as r,At as i,B as a,Bt as o,D as s,Dt as c,E as l,En as u,Et as d,F as f,Ft as p,G as m,Gt as h,Ht as g,I as _,It as v,Jt as y,K as b,Kt as x,L as S,Lt as C,M as w,Mn as T,Mt as E,N as D,Nn as O,Nt as k,O as A,Ot as j,P as M,Pt as N,Qt as P,R as F,Rn as I,Rt as L,St as ee,Tn as te,Tt as R,Ut as z,Vt as ne,W as B,Wt as V,Xt as H,Yt as U,_n as W,_t as re,an as G,at as K,bt as ie,cn as q,ct as ae,dn as J,dt as oe,en as se,fn as ce,hn as le,ht as ue,in as de,it as Y,j as fe,jt as pe,k as me,kt as he,ln as ge,mt as _e,nn as ve,nt as ye,on as be,qt as xe,rn as Se,rt as Ce,sn as we,vt as Te,wn as Ee,xn as De,yt as Oe,z as ke}from"./vendor-DNZbaWhT.js";import{i as Ae,n as X,o as je,s as Me}from"./ui-preferences-OfS30-ZV.js";import{n as Ne,t as Pe}from"./index-fUpioGMZ.js";import{a as Fe,i as Ie,n as Le,o as Re,r as ze,s as Be,t as Ve}from"./bootstrap-CedkNtRG.js";import{E as He,F as Ue,I as We,K as Ge,N as Ke,R as qe,U as Je,V as Ye,ft as Xe,n as Ze,o as Qe,p as $e,r as et,u as tt,w as Z,z as nt}from"./api-BQS4Dtrr.js";import{r as rt}from"./view-model-CWNiS4JN.js";import{A as it,B as at,C as ot,D as st,E as ct,F as lt,H as ut,M as dt,N as ft,O as pt,P as mt,R as ht,S as gt,T as _t,V as vt,_ as yt,a as bt,b as xt,c as St,d as Ct,f as wt,g as Tt,h as Et,i as Dt,j as Ot,k as kt,l as At,m as jt,o as Mt,p as Nt,r as Pt,s as Ft,u as It,v as Lt,w as Rt,y as zt,z as Bt}from"./SettingsNavigation-Wx-q5QQk.js";import{a as Vt,i as Ht,n as Ut,t as Wt}from"./workspace-navigation-DW8zhH6U.js";import{a as Gt,r as Kt,t as qt}from"./AttachmentImage-eZKqLYZ2.js";import{S as Jt,_ as Yt,a as Xt,b as Zt,c as Qt,d as $t,g as en,h as tn,i as nn,m as rn,o as an,p as on,r as sn,s as cn,t as ln,u as un,v as dn,x as fn,y as pn}from"./transcript-view-model-acWtHGyE.js";import{a as mn,i as hn,n as gn,o as _n,r as vn,s as yn,t as bn}from"./composer-drafts-BtMaVw8W.js";import{t as xn}from"./latest-request-DXcYQW86.js";import{t as Sn}from"./terminal-transport-Dk5pYNX5.js";var Q=r();function Cn({value:e,onChange:t}){let{locale:n}=Ae();return(0,Q.jsxs)(ne,{value:e,onChange:(e,n)=>t(n),variant:`fullWidth`,"aria-label":X(n,`Thanh bên`,`Sidebar`),children:[(0,Q.jsx)(g,{value:`sessions`,label:X(n,`Phiên`,`Sessions`)}),(0,Q.jsx)(g,{value:`files`,label:X(n,`Tệp`,`Files`)}),(0,Q.jsx)(g,{value:`search`,label:X(n,`Tìm kiếm`,`Search`)})]})}var $=e(I(),1),wn=(0,$.lazy)(()=>Pe(()=>import(`./WorkspaceQuickOpen-Bi-kTEEU.js`),__vite__mapDeps([0,1,2,3,4,5]))),Tn=(0,$.lazy)(()=>Pe(()=>import(`./TerminalPanel-DzHdSjpN.js`),__vite__mapDeps([6,1,2,3,7,8,9,5,10]))),En=(0,$.lazy)(()=>Pe(()=>import(`./WorkspaceExplorer-B_NwYf4S.js`),__vite__mapDeps([11,1,2,3,7,8,5,12,13,14,15,4,16,10]))),Dn=52,On=36,kn=25,An=75,jn=`piagent-webui-editor-width`;function Mn(){try{let e=Number(window.localStorage.getItem(jn));return e>=kn&&e<=An?e:55}catch{return 55}}var Nn=e=>({color:e?`text.primary`:`text.secondary`,bgcolor:e?`action.selected`:`transparent`,"& .MuiButton-startIcon svg":{fontSize:16,color:e?`primary.main`:`inherit`}});function Pn({title:e,close:t,onClose:n}){return(0,Q.jsxs)(V,{sx:{display:`flex`,alignItems:`center`,gap:1,px:2,minHeight:48,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(o,{sx:{fontWeight:600,flex:1},children:e}),(0,Q.jsx)(x,{size:`small`,"aria-label":t,onClick:n,children:(0,Q.jsx)(L,{fontSize:`small`})})]})}function Fn({sessionRef:e,children:t,navigationHost:n,sidebarMode:r,onSection:i}){let{locale:a}=Ae(),s=ce(),c=k(s.breakpoints.up(`lg`)),[l,u]=(0,$.useState)(!1),[d,f]=(0,$.useState)(!1),[p,m]=(0,$.useState)(!1),[h,g]=(0,$.useState)(),_=(0,$.useRef)(null),[y,b]=(0,$.useState)(Mn),x=e=>{let t=Math.min(An,Math.max(kn,e));b(t);try{window.localStorage.setItem(jn,String(Math.round(t)))}catch{}},S=e=>{let t=_.current?.getBoundingClientRect();if(!t)return;e.preventDefault(),document.body.style.cursor=`col-resize`,document.body.style.userSelect=`none`;let n=e=>x((e.clientX-t.left)/t.width*100),r=()=>{window.removeEventListener(`pointermove`,n),window.removeEventListener(`pointerup`,r),document.body.style.cursor=``,document.body.style.userSelect=``};window.addEventListener(`pointermove`,n),window.addEventListener(`pointerup`,r)};(0,$.useEffect)(()=>{let t=e=>{(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&e.key.toLowerCase()===`p`&&(e.preventDefault(),f(!0))},n=t=>{let n=t.detail;n?.sessionRef===e&&(g({path:n.path,line:n.line}),u(!0),i(`files`))};return window.addEventListener(`keydown`,t),window.addEventListener(Wt,n),()=>{window.removeEventListener(`keydown`,t),window.removeEventListener(Wt,n)}},[e]),(0,$.useEffect)(()=>{r!==`sessions`&&u(!0)},[r]);let w=(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(xe,{size:24}),children:(0,Q.jsx)(En,{sessionRef:e,target:h,navigationHost:c?n:null,sidebarMode:r,onHide:()=>{u(!1),i(`sessions`)},fill:c})}),T=(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(xe,{size:24}),children:(0,Q.jsx)(Tn,{sessionRef:e,onHide:()=>m(!1)})});return(0,Q.jsxs)(Q.Fragment,{children:[d&&(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(xe,{size:20}),children:(0,Q.jsx)(wn,{sessionRef:e,onClose:()=>f(!1),onOpen:e=>{f(!1),u(!0),i(`files`),g({path:e})}})}),(0,Q.jsxs)(V,{sx:{position:`sticky`,top:Dn,zIndex:2,height:On,display:`flex`,alignItems:`center`,gap:.5,px:1,bgcolor:`background.default`,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(z,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(C,{}),"aria-expanded":l,onClick:()=>{u(e=>!e),i(l?`sessions`:`files`)},sx:Nn(l),children:X(a,`Tệp`,`Files`)}),(0,Q.jsx)(z,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(v,{}),"aria-expanded":p,onClick:()=>m(e=>!e),sx:Nn(p),children:`Terminal`}),(0,Q.jsx)(V,{sx:{flex:1}}),c&&(0,Q.jsx)(o,{variant:`caption`,color:`text.disabled`,sx:{pr:.5,display:{xs:`none`,xl:`block`}},children:X(a,`⌘P mở file`,`⌘P to open a file`)})]}),(0,Q.jsxs)(V,{ref:_,sx:{display:`flex`,minWidth:0},children:[c&&(l||p)&&(0,Q.jsxs)(V,{component:`section`,"aria-label":X(a,`Editor và terminal`,`Editor and terminal`),sx:{position:`sticky`,top:88,alignSelf:`flex-start`,flexShrink:0,minWidth:0,width:`clamp(320px, ${y}%, calc(100% - 360px))`,height:`calc(100vh - 88px - var(--piagent-status-bar, 0px))`,display:`flex`,flexDirection:`column`,bgcolor:`background.default`,zIndex:1},children:[l&&(0,Q.jsx)(V,{sx:{flex:1,minHeight:0,overflow:`hidden`},children:w}),p&&(0,Q.jsx)(V,{sx:{flexShrink:0,maxHeight:l?`60%`:`100%`,overflow:`auto`,...l?{}:{flex:1}},children:T}),(0,Q.jsx)(V,{role:`separator`,"aria-orientation":`vertical`,"aria-label":X(a,`Kéo để đổi độ rộng editor`,`Drag to resize the editor`),"aria-valuenow":Math.round(y),"aria-valuemin":kn,"aria-valuemax":An,tabIndex:0,onPointerDown:S,onKeyDown:e=>{(e.key===`ArrowLeft`||e.key===`ArrowRight`)&&(e.preventDefault(),x(y+(e.key===`ArrowLeft`?-2:2)))},sx:{position:`absolute`,top:0,right:-3,bottom:0,width:6,cursor:`col-resize`,zIndex:2,borderRight:1,borderColor:`divider`,"&:hover, &:focus-visible":{borderColor:`primary.main`,outline:`none`}}})]}),(0,Q.jsx)(V,{sx:{flex:1,minWidth:0},children:t})]}),!c&&(0,Q.jsxs)(N,{anchor:`bottom`,open:p,onClose:()=>m(!1),children:[(0,Q.jsx)(Pn,{title:`Terminal`,close:X(a,`Ẩn terminal`,`Hide terminal`),onClose:()=>m(!1)}),p&&T]}),!c&&(0,Q.jsxs)(N,{anchor:`left`,open:l,onClose:()=>u(!1),slotProps:{paper:{sx:{width:`min(96vw, 800px)`}}},children:[(0,Q.jsx)(Pn,{title:X(a,`Tệp`,`Files`),close:X(a,`Đóng`,`Close`),onClose:()=>u(!1)}),l&&w]})]})}var In=e=>e.name??e.repo;function Ln(e,t,n){let r=n===`vi`,i=t?` ${t}`:``,a=r?` Admin Studio đã được báo.`:` Studio administrators were told.`,o=t=>e.filter(e=>e.kind===t).map(In).join(`, `),s=[],c=o(`other_team`),l=o(`unlisted`),u=o(`unregistered`),d=o(`no_repository`);return c&&s.push(r?`${c} thuộc team khác, không phải team${i} của key này.`:`${c} belongs to another team, not this key's team${i}.`),l&&s.push(r?`${l} chưa có trong danh sách project của team${i}.`:`${l} is not in the project list of team${i}.`),u&&s.push(r?`${u} chưa được đăng ký cho team${i}.`:`${u} is not registered to team${i}.`),d&&s.push(r?`Không xác định được project của thư mục ${d}.`:`The project of folder ${d} could not be identified.`),s.join(` `)+a}function Rn({session:e,locale:t}){let n=e.managedProjectWarning;return n?(0,Q.jsx)(h,{severity:`warning`,role:`status`,sx:{maxWidth:820,mx:`auto`,mb:1,py:0},children:Ln(n.warnings,n.team,t)}):null}var zn=H((0,Q.jsx)(`path`,{d:`M16.5 6.75v10.58c0 2.09-1.53 3.95-3.61 4.15-2.39.23-4.39-1.64-4.39-3.98V5.14c0-1.31.94-2.5 2.24-2.63 1.5-.15 2.76 1.02 2.76 2.49v10.5c0 .55-.45 1-1 1s-1-.45-1-1V6.75c0-.41-.34-.75-.75-.75s-.75.34-.75.75v8.61c0 1.31.94 2.5 2.24 2.63 1.5.15 2.76-1.02 2.76-2.49V5.17c0-2.09-1.53-3.95-3.61-4.15C9.01.79 7 2.66 7 5v12.27c0 2.87 2.1 5.44 4.96 5.71 3.29.3 6.04-2.26 6.04-5.48V6.75c0-.41-.34-.75-.75-.75s-.75.34-.75.75`}),`AttachFileRounded`),Bn=H((0,Q.jsx)(`path`,{d:`M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2m4.3 14.3c-.39.39-1.02.39-1.41 0L12 13.41 9.11 16.3c-.39.39-1.02.39-1.41 0a.996.996 0 0 1 0-1.41L10.59 12 7.7 9.11a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0L12 10.59l2.89-2.89c.39-.39 1.02-.39 1.41 0s.39 1.02 0 1.41L13.41 12l2.89 2.89c.38.38.38 1.02 0 1.41`}),`CancelRounded`),Vn=H((0,Q.jsx)(`path`,{d:`M13 19V7.83l4.88 4.88c.39.39 1.03.39 1.42 0s.39-1.02 0-1.41l-6.59-6.59a.996.996 0 0 0-1.41 0l-6.6 6.58c-.39.39-.39 1.02 0 1.41s1.02.39 1.41 0L11 7.83V19c0 .55.45 1 1 1s1-.45 1-1`}),`ArrowUpwardRounded`),Hn=H((0,Q.jsx)(`path`,{d:`M2 4v16h20V4zm18 4.67h-2.5V6H20zm-2.5 2H20v2.67h-2.5zM4 6h11.5v12H4zm13.5 12v-2.67H20V18z`}),`ViewSidebarOutlined`),Un=H((0,Q.jsx)(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m3 14H9c-.55 0-1-.45-1-1V9c0-.55.45-1 1-1h6c.55 0 1 .45 1 1v6c0 .55-.45 1-1 1`}),`StopCircleRounded`);function Wn(e){return te(`MuiCollapse`,e)}Ee(`MuiCollapse`,[`root`,`horizontal`,`vertical`,`entered`,`hidden`,`wrapper`,`wrapperInner`]);var Gn={},Kn=e=>{let{orientation:t,classes:n}=e;return W({root:[`root`,t],entered:[`entered`],hidden:[`hidden`],wrapper:[`wrapper`,t],wrapperInner:[`wrapperInner`,t]},Wn,n)},qn=J(`div`,{name:`MuiCollapse`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[n.orientation],n.state===`entered`&&t.entered,n.state===`exited`&&!n.in&&n.collapsedSize===`0px`&&t.hidden]}})(q(({theme:e})=>({height:0,overflow:`hidden`,transition:e.transitions.create(`height`),variants:[{props:{orientation:`horizontal`},style:{height:`auto`,width:0,transition:e.transitions.create(`width`)}},{props:{state:`entered`},style:{height:`auto`,overflow:`visible`}},{props:{state:`entered`,orientation:`horizontal`},style:{width:`auto`}},{props:({ownerState:e})=>e.state===`exited`&&!e.in&&e.collapsedSize===`0px`,style:{visibility:`hidden`}}]}))),Jn=J(`div`,{name:`MuiCollapse`,slot:`Wrapper`})({display:`flex`,width:`100%`,variants:[{props:{orientation:`horizontal`},style:{width:`auto`,height:`100%`}}]}),Yn=J(`div`,{name:`MuiCollapse`,slot:`WrapperInner`})({width:`100%`,variants:[{props:{orientation:`horizontal`},style:{width:`auto`,height:`100%`}}]}),Xn=$.forwardRef(function(e,t){let n=ge({props:e,name:`MuiCollapse`}),{addEndListener:r,children:i,className:a,collapsedSize:o=`0px`,component:s,disablePrefersReducedMotion:c=!1,easing:l,in:d,onEnter:f,onEntered:m,onEntering:h,onExit:g,onExited:_,onExiting:v,orientation:y=`vertical`,slots:b=Gn,slotProps:x=Gn,style:S,timeout:C=le.standard,TransitionComponent:w=p,...T}=n,E={...n,orientation:y,collapsedSize:o},D=Kn(E),O=ce(),k=$.useRef(null),A=$.useRef(null),j=typeof o==`number`?`${o}px`:o,M=y===`horizontal`,N=M?`width`:`height`,P=U(O.motion.reducedMotion,c),F=$.useRef(null),I=be(t,F),L=()=>k.current?k.current[M?`clientWidth`:`clientHeight`]:0,ee=G(F,(e,t)=>{k.current&&M&&(k.current.style.position=`absolute`),e.style[N]=j,f&&f(e,t)}),te=G(F,(e,t)=>{let n=L();k.current&&M&&(k.current.style.position=``);let{duration:r,easing:i}=Se({style:S,timeout:C,easing:l},{mode:`enter`});if(C===`auto`&&!P.shouldReduceMotion){let e=O.transitions.getAutoHeightDuration(n);A.current=e}else A.current=null;let a=P.getTransitionTiming({duration:A.current??r,delay:void 0});e.style.transitionDuration=typeof a.duration==`string`?a.duration:`${a.duration}ms`,e.style[N]=`${n}px`,e.style.transitionTimingFunction=i,h&&h(e,t)}),R=G(F,(e,t)=>{e.style[N]=`auto`,m&&m(e,t)}),z=G(F,e=>{e.style[N]=`${L()}px`,g&&g(e)}),ne=G(F,_),B=G(F,e=>{let t=L(),{duration:n,easing:r}=Se({style:S,timeout:C,easing:l},{mode:`exit`});if(C===`auto`&&!P.shouldReduceMotion){let e=O.transitions.getAutoHeightDuration(t);A.current=e}else A.current=null;let i=P.getTransitionTiming({duration:A.current??n,delay:void 0});e.style.transitionDuration=typeof i.duration==`string`?i.duration:`${i.duration}ms`,e.style[N]=j,e.style.transitionTimingFunction=r,v&&v(e)}),V=r?e=>{r(F.current,e)}:void 0,H={slots:b,slotProps:x,component:s},[W,re]=se(`root`,{ref:I,className:u(D.root,a),elementType:qn,externalForwardedProps:H,ownerState:E,additionalProps:{style:{[M?`minWidth`:`minHeight`]:j,...S}}}),[K,ie]=se(`wrapper`,{ref:k,className:D.wrapper,elementType:Jn,externalForwardedProps:H,ownerState:E}),[q,ae]=se(`wrapperInner`,{className:D.wrapperInner,elementType:Yn,externalForwardedProps:H,ownerState:E});return(0,Q.jsx)(w,{in:d,onEnter:ee,onEntered:R,onEntering:te,onExit:z,onExited:ne,onExiting:B,addEndListener:V,getAutoTimeout:C===`auto`?()=>A.current:void 0,reduceMotion:P.shouldReduceMotion,nodeRef:F,timeout:C===`auto`?null:C,...T,children:(e,{ownerState:t,...n})=>{let r={...E,state:e};return(0,Q.jsx)(W,{...re,className:u(re.className,{entered:D.entered,exited:!d&&j===`0px`&&D.hidden}[e]),ownerState:r,...n,children:(0,Q.jsx)(K,{...ie,ownerState:r,children:(0,Q.jsx)(q,{...ae,ownerState:r,children:i})})})}})});Xn&&(Xn.muiSupportAuto=!0);function Zn(e,t,n){return at(e,t,n)}var Qn=new Set([`company-quota`,`company-provider-limit`,`company-account`,`company-busy`,`company-trial-limit`,`company-key`,`company-policy`,`company-rejected`,`company-unreachable`,`company-service`,`company-config-changed`,`company-failed`]);function $n(e){return Qn.has(e)||!e.startsWith(`company-`)}function er(e,t){return vt(e,t)}var tr=Bt,nr={"session-revision-stale":[`Danh sách cuộc trò chuyện vừa thay đổi. Gửi lại tin nhắn.`,`The conversation list just changed. Send the message again.`],"catalog-unavailable":[`Danh sách cuộc trò chuyện chưa tải xong. Thử lại sau vài giây.`,`The conversation list has not loaded yet. Try again in a few seconds.`],"session-model-mismatch":[`Cuộc trò chuyện đã tạo nhưng đang dùng model khác model đã chọn, nên tin nhắn chưa được gửi.`,`The conversation was created with a different model than the one chosen, so the message was not sent.`],"gateway-command-response-timeout":[`Piagent chưa xác nhận được cuộc trò chuyện mới sau 2 phút; nó có thể đã được tạo và đang chạy. Xem danh sách cuộc trò chuyện bên trái trước khi gửi lại.`,`Piagent could not confirm the new conversation within 2 minutes; it may have been created and be running. Check the conversation list before sending again.`],"session-command-expired":[`Yêu cầu chờ quá lâu nên đã hết hạn. Gửi lại tin nhắn.`,`The request waited too long and expired. Send the message again.`]};function rr(e,t){let n=e.startsWith(`company-`)?Zn(e,null,t):null;if(n)return`${n.title}: ${n.text}`;let r=nr[e]??tr[e];return r?X(t,...r):`${X(t,`Chưa tạo được cuộc trò chuyện`,`The conversation could not be created`)} (${e}).`}function ir(e,t){let n=tr[e?.reasonCode??``];return n?X(t,...n):null}var ar=(e,t)=>e?.state===`connecting`?X(t,`Đang kết nối phiên công ty…`,`Connecting the company runtime…`):ir(e,t)??X(t,`Chưa kết nối phiên công ty. Bấm để kết nối.`,`The company runtime is not connected. Select to connect.`);function or({locale:e,onConnected:t}){let[n,r]=(0,$.useState)(),[i,a]=(0,$.useState)(!1),o=(0,$.useRef)(!1),s=()=>{o.current&&(o.current=!1,t())};if((0,$.useEffect)(()=>{let e=!0,t=()=>void $e().then(t=>{e&&(r(t),t?.state===`ready`?s():t&&(o.current=!0))}).catch(()=>void 0);t();let n=window.setInterval(t,5e3);return()=>{e=!1,window.clearInterval(n)}},[]),!n||n.state===`ready`||n.state===`unconfigured`)return null;let c=async()=>{a(!0);try{let e=await Qe();r(e),e.state===`ready`&&s()}catch{r(await $e().catch(()=>null)??n)}finally{a(!1)}},l=ir(n,e),u=i||n.state===`connecting`;return(0,Q.jsxs)(h,{severity:`warning`,role:`status`,sx:{mb:2},action:(0,Q.jsx)(z,{color:`inherit`,size:`small`,disabled:u,onClick:()=>void c(),sx:{whiteSpace:`nowrap`},children:u?X(e,`Đang kết nối…`,`Connecting…`):X(e,`Kết nối lại`,`Reconnect`)}),children:[X(e,`Chế độ công ty đang tắt nên chưa đọc hay gửi tiếp được cuộc trò chuyện này. Bấm Kết nối lại; macOS có thể hỏi quyền đọc key một lần.`,`Company mode is not running, so this conversation cannot be read or continued yet. Select Reconnect; macOS may ask once to read the key.`),l&&(0,Q.jsxs)(Q.Fragment,{children:[` `,l]})]})}function sr(e){return e.key===`Enter`&&!e.shiftKey&&!e.nativeEvent.isComposing&&e.keyCode!==229}var cr=H((0,Q.jsx)(`path`,{d:`M12 7V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zM6 19H4v-2h2zm0-4H4v-2h2zm0-4H4V9h2zm0-4H4V5h2zm4 12H8v-2h2zm0-4H8v-2h2zm0-4H8V9h2zm0-4H8V5h2zm9 12h-7v-2h2v-2h-2v-2h2v-2h-2V9h7c.55 0 1 .45 1 1v8c0 .55-.45 1-1 1m-1-8h-2v2h2zm0 4h-2v2h2z`}),`BusinessRounded`),lr=H((0,Q.jsx)(`path`,{d:`m19 9 1.25-2.75L23 5l-2.75-1.25L19 1l-1.25 2.75L15 5l2.75 1.25zm0 6-1.25 2.75L15 19l2.75 1.25L19 23l1.25-2.75L23 19l-2.75-1.25zm-7.5-5.5L9 4 6.5 9.5 1 12l5.5 2.5L9 20l2.5-5.5L17 12zm-1.51 3.49L9 15.17l-.99-2.18L5.83 12l2.18-.99L9 8.83l.99 2.18 2.18.99z`}),`AutoAwesomeOutlined`);function ur(e,t){let n=e.slice(0,t),r=/(^|[\s(])@"([^"\n]*)$/.exec(n);if(r)return{start:r.index+r[1].length,end:e[t]===`"`?t+1:t,query:r[2],quoted:!0};let i=/(^|[\s(])@([^\s"]*)$/.exec(n);return i?{start:i.index+i[1].length,end:t+(/^[^\s"]*/.exec(e.slice(t))?.[0].length??0),query:i[2],quoted:!1}:null}function dr(e,t,n){let r=t.quoted||/\s/.test(n.value),i=r?`@"${n.value}"`:`@${n.value}`,a=n.kind===`directory`,o=e.slice(t.end),s=a||/^\s/.test(o)?``:` `;return{text:e.slice(0,t.start)+i+s+o,caret:t.start+i.length+s.length-(a&&r?1:0)}}function fr(e,t){let n=e.slice(0,t);return/^\/[^\s/]*$/.test(n)?{start:0,end:t+(/^[^\s]*/.exec(e.slice(t))?.[0].length??0),query:n.slice(1),quoted:!1}:null}function pr(e,t,n){let r=n.kind===`skill`?`/skill:${n.name}`:`/${n.name}`,i=e.slice(t.end);return{text:r+(/^\s/.test(i)?``:` `)+i,caret:r.length+1}}var mr=20,hr=e=>e.normalize(`NFD`).replace(/\p{M}/gu,``).toLowerCase();function gr(e,t,n){let r=hr(t.replace(/^skill:/,``)),i=e=>hr(e.name).startsWith(r)?0:hr(e.name).includes(r)?1:hr(e.description).includes(r)?2:3,a=e=>e.origin===`piagent`?`Piagent`:e.plugin?`${e.plugin} · ${e.origin===`claude`?`Claude`:`Codex`} plugin`:`${e.scope===`user`?`~/`:``}.${e.origin===`pi`?`pi`:e.origin}`;return e.filter(e=>i(e)<3&&(!t.startsWith(`skill:`)||e.kind===`skill`)).sort((e,t)=>i(e)-i(t)||e.name.localeCompare(t.name)).slice(0,mr).map(e=>({key:`${e.kind}:${e.name}`,icon:e.kind,label:e.kind===`skill`?`/skill:${e.name}`:`/${e.name}`,hint:e.argumentHint,detail:`${e.description}${e.description?` · `:``}${e.kind===`skill`?`skill`:X(n,`lệnh`,`command`)} ${a(e)}`,apply:(t,n)=>pr(t,n,e)}))}function _r({projectRef:e,value:t,onChange:n,locale:r,builtIns:i=[]}){let a=(0,$.useRef)(null),s=(0,$.useId)(),[c,l]=(0,$.useState)(null),[u,d]=(0,$.useState)(!1),[f,p]=(0,$.useState)(null),[m,h]=(0,$.useState)(0),[g,_]=(0,$.useState)(null),[y,b]=(0,$.useState)(null),x=e&&c!==null&&c<=t.length?c:null,S=x===null?null:fr(t,x),w=x===null||S?null:ur(t,x),T=S??w,E=S?`command`:`path`,D=T&&`${E}:${T.start}`!==f?T:null,O=D&&E===`path`?D.query:null;(0,$.useEffect)(()=>{if(O===null||!e){_(null);return}let t=new AbortController,n=setTimeout(()=>{Z(e,O,t.signal).then(e=>{_({query:O,items:e.suggestions.map(e=>({key:e.value,label:e.label,hint:null,icon:e.kind,detail:e.detail.slice(0,Math.max(0,e.detail.length-e.label.replace(/\/$/,``).length)),apply:(t,n)=>dr(t,n,e)}))}),h(0)}).catch(()=>{t.signal.aborted||_({query:O,items:[]})})},90);return()=>{clearTimeout(n),t.abort()}},[e,O]);let k=!!(D&&E===`command`&&e&&y?.projectRef!==e);(0,$.useEffect)(()=>{if(!k||!e)return;let t=new AbortController;return He(e,t.signal).then(t=>b({projectRef:e,list:t.commands})).catch(()=>{t.signal.aborted||b({projectRef:e,list:[]})}),()=>t.abort()},[k,e]);let A=D?E===`path`?g?.items??null:y&&y.projectRef===e?gr([...i,...y.list.filter(e=>!i.some(t=>t.name===e.name))],D.query,r):null:null;(0,$.useEffect)(()=>{h(0)},[E,D?.query]);let j=!!(u&&D&&A&&a.current),N=j?A:[];(0,$.useEffect)(()=>{j&&document.getElementById(`${s}-${m}`)?.scrollIntoView({block:`nearest`})},[j,m,s]);let F=(0,$.useRef)(null);(0,$.useLayoutEffect)(()=>{let e=F.current,n=a.current;!e||!n||e.text!==t||(F.current=null,n.focus(),n.setSelectionRange(e.caret,e.caret),l(e.caret))},[t]);let I=e=>{if(!D)return;let r=e.apply(t,D);F.current=r,n(r.text),l(r.caret)},L=e=>!j||e.nativeEvent.isComposing||e.keyCode===229?!1:e.key===`Escape`?(e.preventDefault(),p(`${E}:${D.start}`),!0):N.length?e.key===`ArrowDown`||e.key===`ArrowUp`?(e.preventDefault(),h(t=>(t+(e.key===`ArrowDown`?1:N.length-1))%N.length),!0):(e.key===`Enter`||e.key===`Tab`)&&!e.shiftKey&&!e.altKey&&!e.metaKey&&!e.ctrlKey&&(e.preventDefault(),I(N[Math.min(m,N.length-1)]),!0):!1,ee=e=>e===`directory`?(0,Q.jsx)(C,{fontSize:`small`,color:`primary`}):e===`file`?(0,Q.jsx)(M,{fontSize:`small`,color:`action`}):e===`skill`?(0,Q.jsx)(lr,{fontSize:`small`,color:`secondary`}):(0,Q.jsx)(v,{fontSize:`small`,color:`primary`}),te=E===`command`?X(r,`Lệnh và skill`,`Commands and skills`):X(r,`File và folder`,`Files and folders`),R=a.current,z=(0,Q.jsx)(Te,{open:j,anchorEl:R,placement:`top-start`,disablePortal:!0,sx:{zIndex:1350,width:Math.min(640,R?.clientWidth??640)},modifiers:[{name:`offset`,options:{offset:[0,10]}}],children:(0,Q.jsxs)(P,{elevation:8,sx:{borderRadius:1,overflow:`hidden`,display:`flex`,flexDirection:`column`,maxHeight:340},children:[(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,sx:{px:1.5,pt:1,pb:.5},children:E===`command`?X(r,`Lệnh và skill của project và trên máy này · Tab để chọn`,`Commands and skills of the project and on this computer · Tab to pick`):X(r,`File và folder · gõ ~/ hoặc / để chọn folder khác trên máy · Tab để chọn`,`Files and folders · type ~/ or / for other folders on this computer · Tab to pick`)}),N.length?(0,Q.jsx)(V,{component:`ul`,role:`listbox`,id:s,"aria-label":te,sx:{listStyle:`none`,m:0,p:.5,pt:0,overflowY:`auto`},children:N.map((e,t)=>(0,Q.jsxs)(V,{component:`li`,id:`${s}-${t}`,role:`option`,"aria-selected":t===m,onMouseDown:e=>e.preventDefault(),onMouseEnter:()=>h(t),onClick:()=>I(e),sx:{display:`flex`,alignItems:`center`,gap:1,minWidth:0,px:1,py:.55,borderRadius:1,cursor:`pointer`,bgcolor:t===m?`action.selected`:`transparent`},children:[ee(e.icon),(0,Q.jsx)(o,{noWrap:!0,sx:{flexShrink:0,maxWidth:`55%`,fontSize:14,fontWeight:600},children:e.label}),e.hint&&(0,Q.jsx)(o,{noWrap:!0,variant:`caption`,sx:{flexShrink:0,maxWidth:`25%`,fontFamily:`monospace`},children:e.hint}),(0,Q.jsx)(o,{noWrap:!0,variant:`caption`,color:`text.secondary`,sx:{minWidth:0},children:e.detail})]},e.key))}):(0,Q.jsx)(o,{variant:`body2`,color:`text.secondary`,sx:{px:1.5,pb:1.25},children:E===`command`?X(r,`Không có lệnh hoặc skill khớp`,`No matching command or skill`):X(r,`Không có file hoặc folder khớp`,`No matching file or folder`)})]})}),ne=e=>l(e.target.selectionStart??null);return{inputRef:a,menu:z,onKeyDown:L,track:ne,inputProps:{onFocus:()=>d(!0),onBlur:()=>d(!1)},htmlInput:{onSelect:ne,"aria-autocomplete":`list`,"aria-controls":j&&N.length?s:void 0,"aria-activedescendant":j&&N.length?`${s}-${m}`:void 0}}}var vr=`agent_watch_managed`;function yr({file:e,locale:t,onRemove:n}){let[r,i]=(0,$.useState)(null);return(0,$.useEffect)(()=>{if(!e.type.startsWith(`image/`))return;let t=new FileReader;return t.onload=()=>{typeof t.result==`string`&&i(t.result)},t.readAsDataURL(e),()=>t.abort()},[e]),r?(0,Q.jsx)(Kt,{url:r,name:e.name,detail:Zt(e.size),locale:t,onRemove:n}):(0,Q.jsx)(c,{size:`small`,variant:`outlined`,label:`${e.name} · ${Zt(e.size)}`,onDelete:n,deleteIcon:(0,Q.jsx)(Bn,{"aria-label":`${X(t,`Bỏ`,`Remove`)} ${e.name}`,role:`button`})})}function br(e,t,n){return e===`native-project-picker-unavailable`||e===`project-import-picker-failed`?X(n,`Không mở được hộp chọn thư mục của máy. Thử lại; nếu vẫn lỗi, mở cuộc trò chuyện từ Terminal trong thư mục đó (pi hoặc piagent studio).`,`The folder picker could not open. Try again; if it still fails, start a conversation from a Terminal in that folder (pi or piagent studio).`):e===`project-import-folder-invalid`?X(n,`Không dùng được thư mục này: thư mục gốc của ổ đĩa hoặc một liên kết (symlink). Chọn thư mục thật của project.`,`This folder cannot be used: a drive's root or a symbolic link. Choose the project's real folder.`):t===429?X(n,`Thao tác quá nhanh. Đợi vài giây rồi thử lại.`,`Too many attempts. Wait a few seconds and try again.`):X(n,`Không thể thêm thư mục. Thử lại; nếu vẫn lỗi, chạy piagent dashboard doctor.`,`Could not add this folder. Try again; if it still fails, run piagent dashboard doctor.`)}var xr=[[`Đọc project này (chỉ đọc) và ghi lại project context.`,`Read this project (read-only) and record the project context.`],[`Review diff hiện tại. Chỉ đọc.`,`Review the current diff. Read-only.`],[`Chạy test của project và giải thích lỗi nếu có.`,`Run the project's tests and explain any failure.`],[`Lập plan cho việc sau, chưa sửa code: `,`Plan this change before editing any code: `]];function Sr({active:e,defaultProjectRef:t,busy:n,error:r,onCancel:i,onCreate:s}){let{locale:l}=Ae(),[u,d]=(0,$.useState)(),[p,m]=(0,$.useState)(void 0),[h,g]=(0,$.useState)(!1),v=p===null&&u?.models.length===1&&u.models[0].provider===`agent_watch_managed`,[y,b]=(0,$.useState)(!1),[C,w]=(0,$.useState)(``),[T,D]=(0,$.useState)(``),[O,k]=(0,$.useState)(`high`),[A,j]=(0,$.useState)(!1),[M,N]=(0,$.useState)(!1),[P,I]=(0,$.useState)(null),[L,te]=(0,$.useState)(()=>mn(gn)),ne=e=>{te(e),yn(gn,e)},[B,H]=(0,$.useState)(null),[U,W]=(0,$.useState)(()=>hn(`new-chat`)??[]),[G,q]=(0,$.useState)(null);(0,$.useEffect)(()=>{_n(gn,U.length?U:null)},[U]);let[J,se]=(0,$.useState)(!1),ce=(0,$.useRef)(0),[le,ue]=(0,$.useState)(null),[de,fe]=(0,$.useState)(null),[pe,me]=(0,$.useState)(!1),[he,ge]=(0,$.useState)(null);(0,$.useEffect)(()=>{if(!e)return;let n=new AbortController;return d(void 0),b(!1),ge(null),q(null),se(!1),j(!1),ce.current=0,We(n.signal).then(e=>{n.signal.aborted||(d(e),w(e.projects.some(e=>e.projectRef===t)?t:e.projects[0]?.projectRef??``),D(e.defaultModelRef??``),k(e.defaultThinkingLevel??`high`),I(null),N(!1))}).catch(()=>{n.signal.aborted||b(!0)}),m(void 0),$e(n.signal).then(e=>{n.signal.aborted||m(e)}).catch(()=>{n.signal.aborted||m(null)}),()=>n.abort()},[e,t]),(0,$.useEffect)(()=>{if(!e)return;let t=e=>{pn(e.dataTransfer)&&e.preventDefault()};return window.addEventListener(`dragover`,t),window.addEventListener(`drop`,t),()=>{window.removeEventListener(`dragover`,t),window.removeEventListener(`drop`,t)}},[e]);let ve=u?.projects.find(e=>e.projectRef===C),ye=_r({projectRef:ve?.projectRef,value:L,onChange:ne,locale:l}),be=u?.models.find(e=>e.modelRef===T),Se=!v&&be?.provider===vr,we=v?[]:u?.models.filter(e=>e.provider===vr)??[],Te=(v||Se)&&be?.managedFast===!0,Ee=v?u?.models??[]:u?.models.filter(e=>e.provider!==vr)??[],De=async()=>{g(!0);try{let e=await Qe().catch(()=>null),t=await We();d(t),m(e??await $e().catch(()=>null));let n=t.models.find(e=>e.provider===vr);n&&(D(n.modelRef),Ne())}catch{b(!0)}finally{g(!1)}},Oe=u?.models.find(e=>e.modelRef===u.defaultModelRef),je=(0,$.useMemo)(()=>be?.thinkingLevels??[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`],[be]);(0,$.useEffect)(()=>{je.includes(O)||k(je.includes(`high`)?`high`:je[0]??`off`)},[T,je]);let Me=e=>t=>{ue(e),fe(t.currentTarget)},Ne=()=>{ue(null),fe(null)},Pe=async()=>{me(!0),ge(null);try{let e=await tt(),t=e.projects?.length?e.projects:[e.project];d(e=>e&&{...e,projects:[...e.projects.filter(e=>!t.some(t=>t.projectRef===e.projectRef)),...t]}),w(e.project.projectRef),Ne()}catch(e){e instanceof Ze&&e.status===409?ge(null):ge(br(e instanceof Ze?e.code:null,e instanceof Ze?e.status:0,l))}finally{me(!1)}},Fe=e=>{if(!e?.length)return;let t=[...U],n=!1,r=null;for(let i of[...e]){if(t.some(e=>e.name===i.name&&e.size===i.size&&e.lastModified===i.lastModified))continue;let e=Yt(i.name);if(`refused`in e){r=`${i.name}: ${fn(e.refused,l)}`;continue}if(t.length===4){n=!0;continue}t.push(i)}W(t),q(r??(n?X(l,`Mỗi tin nhắn nhận tối đa 4 file.`,`Each message accepts at most 4 files.`):null))},Ie=!n&&!y&&U.length<4,Le=(0,$.useRef)(!1),Re=()=>{Le.current||n||!ve||!L.trim()||(Le.current=!0,Promise.resolve(s({projectRef:C,placeRef:ve.placeRef,modelRef:T||null,thinkingLevel:O,permissionMode:P,...Te&&M?{fast:!0}:{},message:L,files:U})).finally(()=>{Le.current=!1}))};return(0,Q.jsxs)(V,{sx:{minHeight:`calc(100vh - 68px)`,display:`flex`,flexDirection:`column`},children:[(0,Q.jsx)(V,{sx:{p:{xs:1.5,sm:2}},children:(0,Q.jsx)(x,{"aria-label":X(l,`Quay lại`,`Back`),onClick:i,children:(0,Q.jsx)(a,{})})}),(0,Q.jsxs)(R,{sx:{flex:1,alignItems:`center`,justifyContent:`center`,px:2,pb:{xs:5,md:12}},spacing:4,children:[(0,Q.jsxs)(R,{spacing:1.75,sx:{alignItems:`center`},children:[(0,Q.jsx)(ut,{size:44}),(0,Q.jsx)(o,{component:`h1`,sx:{fontSize:{xs:`1.9rem`,md:`2.3rem`},fontWeight:650,letterSpacing:`-.04em`,textAlign:`center`},children:X(l,`Hôm nay làm gì?`,`What should we work on?`)}),(0,Q.jsx)(o,{color:`text.secondary`,sx:{textAlign:`center`,maxWidth:520,fontSize:14.5},children:X(l,`Nói việc bằng lời thường. Guard kiểm tra mọi tool call; việc rủi ro chờ bạn duyệt.`,`Say what you need in plain language. The guard checks every tool call; risky actions wait for you.`)})]}),(0,Q.jsxs)(V,{sx:{position:`relative`,width:`100%`,maxWidth:820,border:1,borderColor:J?`primary.main`:`divider`,borderStyle:J?`dashed`:`solid`,borderRadius:2.5,bgcolor:`background.paper`,p:1.5,boxShadow:`0 24px 60px -24px rgba(0,0,0,.55)`,transition:`border-color .16s, box-shadow .16s`,"&:focus-within":{borderColor:`rgba(var(--piagent-palette-primary-mainChannel) / .55)`,boxShadow:`0 0 0 4px rgba(var(--piagent-palette-primary-mainChannel) / .12), 0 24px 60px -24px rgba(0,0,0,.55)`}},onDragEnter:e=>{pn(e.dataTransfer)&&(ce.current+=1,se(!0))},onDragOver:e=>{pn(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect=Ie?`copy`:`none`)},onDragLeave:e=>{pn(e.dataTransfer)&&(--ce.current,ce.current<=0&&(ce.current=0,se(!1)))},onDrop:e=>{pn(e.dataTransfer)&&(e.preventDefault(),ce.current=0,se(!1),Ie&&Fe(e.dataTransfer.files))},children:[J&&(0,Q.jsxs)(V,{role:`status`,sx:{position:`absolute`,inset:0,zIndex:3,display:`grid`,alignContent:`center`,justifyItems:`center`,gap:.5,borderRadius:1,bgcolor:`background.paper`,opacity:.96,pointerEvents:`none`,textAlign:`center`},children:[(0,Q.jsx)(o,{sx:{fontWeight:650},children:Ie?X(l,`Thả tài liệu vào đây`,`Drop documents here`):U.length>=4?X(l,`Đã đủ 4 file cho tin nhắn đầu tiên`,`The first message already holds 4 files`):X(l,`Chưa nhận file lúc này`,`Files cannot be attached right now`)}),Ie&&(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,children:en(l)})]}),!u&&!y?(0,Q.jsxs)(R,{direction:`row`,spacing:1.5,sx:{minHeight:126,alignItems:`center`,justifyContent:`center`},children:[(0,Q.jsx)(xe,{size:20}),(0,Q.jsx)(o,{color:`text.secondary`,children:X(l,`Đang mở…`,`Opening…`)})]}):(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(ie,{autoFocus:!0,fullWidth:!0,multiline:!0,minRows:3,maxRows:8,value:L,disabled:n||y,inputRef:ye.inputRef,...ye.inputProps,onChange:e=>{ne(e.target.value),ye.track(e)},onKeyDown:e=>{ye.onKeyDown(e)||sr(e)&&(e.preventDefault(),Re())},onPaste:e=>{e.clipboardData?.files.length&&(e.preventDefault(),Ie&&Fe(e.clipboardData.files))},placeholder:X(l,`Nhắn cho Piagent… (@ để chọn file, folder)`,`Message Piagent… (@ for files and folders)`),variant:`standard`,slotProps:{input:{disableUnderline:!0},htmlInput:{maxLength:32768,...ye.htmlInput}},sx:{px:.5}}),ye.menu,U.length>0&&(0,Q.jsx)(R,{direction:`row`,sx:{flexWrap:`wrap`,gap:.75,px:.5,pt:.75},"aria-label":X(l,`File sẽ gửi cùng tin nhắn đầu tiên`,`Files for the first message`),children:U.map(e=>(0,Q.jsx)(yr,{file:e,locale:l,onRemove:n?void 0:()=>{W(t=>t.filter(t=>t!==e)),q(null)}},`${e.name}:${e.size}:${e.lastModified}`))}),(0,Q.jsx)(Xn,{in:A,id:`piagent-new-session-options`,children:(0,Q.jsxs)(V,{sx:{mx:.35,mt:1,px:1.1,py:1,borderRadius:1,bgcolor:`action.hover`},children:[(0,Q.jsx)(o,{variant:`caption`,sx:{display:`block`,mb:.75,fontWeight:650},children:X(l,`Tùy chọn cho tin nhắn đầu tiên`,`Options for the first message`)}),(0,Q.jsxs)(R,{direction:`row`,sx:{alignItems:`center`,gap:.75,flexWrap:`wrap`},children:[(0,Q.jsx)(z,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(_,{}),endIcon:(0,Q.jsx)(ke,{}),onClick:Me(`thinking`),children:rt(O,l)}),(0,Q.jsx)(z,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(S,{}),endIcon:(0,Q.jsx)(ke,{}),onClick:Me(`permission`),children:v||Se?pt(P,l):P?rt(P,l):X(l,`Quyền theo profile`,`Profile access`)}),(0,Q.jsxs)(z,{component:`label`,size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(zn,{}),disabled:!Ie,"aria-label":`${X(l,`Thêm file`,`Add files`)} (${U.length}/4)`,children:[X(l,`Đính kèm`,`Attach`),(0,Q.jsx)(`input`,{type:`file`,hidden:!0,multiple:!0,disabled:!Ie,accept:``,onChange:e=>{Fe(e.target.files),e.currentTarget.value=``}})]})]}),Se&&(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,sx:{display:`block`,mt:.75},children:X(l,`Model và quyền theo Harness công ty; thinking chọn ở đây.`,`Models and access follow the company Harness; choose thinking here.`)})]})}),(0,Q.jsxs)(R,{direction:`row`,sx:{mt:1,alignItems:`center`,gap:.65,flexWrap:`nowrap`,minWidth:0},children:[(0,Q.jsx)(re,{title:A?X(l,`Ẩn tùy chọn`,`Hide options`):X(l,`Thêm tùy chọn`,`More options`),children:(0,Q.jsx)(x,{size:`small`,"aria-label":A?X(l,`Ẩn tùy chọn`,`Hide options`):X(l,`Thêm tùy chọn`,`More options`),"aria-expanded":A,"aria-controls":`piagent-new-session-options`,onClick:()=>j(e=>!e),sx:{flex:`0 0 auto`,bgcolor:A?`action.selected`:`transparent`},children:(0,Q.jsx)(E,{fontSize:`small`,sx:{transition:`transform .16s ease`,transform:A?`rotate(45deg)`:`none`}})})}),(0,Q.jsx)(z,{size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(F,{}),endIcon:(0,Q.jsx)(ke,{}),onClick:Me(`project`),"aria-label":`${X(l,`Project`,`Project`)}: ${ve?.label??X(l,`Chọn project`,`Choose project`)}`,sx:{minWidth:0,maxWidth:{xs:118,sm:250},px:{xs:.75,sm:1},"& .MuiButton-startIcon":{display:{xs:`none`,sm:`inherit`}}},children:(0,Q.jsx)(V,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:ve?.label??X(l,`Chọn project`,`Choose project`)})}),(0,Q.jsx)(z,{size:`small`,color:`inherit`,startIcon:Se?(0,Q.jsx)(cr,{}):(0,Q.jsx)(oe,{}),endIcon:(0,Q.jsx)(ke,{}),onClick:Me(`model`),"aria-label":`${X(l,`Model`,`Model`)}: ${Se?X(l,`Công ty · agent-watch-auto`,`Company · agent-watch-auto`):be?.displayName??Oe?.displayName??X(l,`Mặc định của Pi`,`Pi default`)}`,sx:{minWidth:0,maxWidth:{xs:142,sm:250},px:{xs:.75,sm:1},"& .MuiButton-startIcon":{display:{xs:`none`,sm:`inherit`}}},children:(0,Q.jsx)(V,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,whiteSpace:`nowrap`},children:Se?X(l,`Công ty · agent-watch-auto`,`Company · agent-watch-auto`):be?`${be.displayName}${be.modelRef===u?.defaultModelRef?X(l,` · mặc định`,` · default`):``}`:Oe?.displayName??X(l,`Mặc định của Pi`,`Pi default`)})}),Te&&(0,Q.jsx)(re,{title:Ot(l),arrow:!0,children:(0,Q.jsx)(z,{size:`small`,color:`inherit`,variant:`outlined`,startIcon:(0,Q.jsx)(_e,{}),"aria-pressed":M,"aria-label":`${dt(M,l)}. ${Ot(l)}`,onClick:()=>N(e=>!e),sx:{flex:`0 0 auto`,minWidth:0,px:{xs:.75,sm:1},borderRadius:1,borderColor:`divider`,color:`text.secondary`,"& .MuiButton-startIcon":{mr:{xs:0,sm:.65},ml:0},...M?ft:{}},children:(0,Q.jsx)(V,{component:`span`,sx:{display:{xs:`none`,sm:`inline`},whiteSpace:`nowrap`},children:dt(M,l)})})}),(0,Q.jsx)(V,{sx:{flex:1,minWidth:0}}),(0,Q.jsx)(x,{"aria-label":X(l,`Gửi`,`Send`),disabled:n||y||!ve||!L.trim(),onClick:Re,sx:{flex:`0 0 auto`,width:34,height:34,borderRadius:999,transition:`transform .12s`,bgcolor:`primary.main`,color:`primary.contrastText`,"&:hover":{bgcolor:`primary.main`,color:`primary.contrastText`,transform:`translateY(-1px)`},"&.Mui-disabled":{bgcolor:`action.disabledBackground`}},children:(0,Q.jsx)(Vn,{fontSize:`small`})})]}),Te&&M&&(0,Q.jsx)(o,{variant:`caption`,sx:{display:`block`,px:.5,pt:.75,color:`warning.main`},children:Ot(l)})]}),(G||he||r||y)&&(0,Q.jsx)(o,{role:`status`,color:`error`,variant:`caption`,sx:{display:`block`,px:.5,pt:1},children:G??he??r??X(l,`Không tải được lựa chọn`,`Could not load choices`)})]}),u&&!L&&(0,Q.jsx)(R,{direction:`row`,role:`group`,"aria-label":X(l,`Việc mẫu`,`Starter tasks`),sx:{flexWrap:`wrap`,justifyContent:`center`,gap:1,maxWidth:820,mt:`16px !important`},children:xr.map(([e,t])=>(0,Q.jsx)(c,{variant:`outlined`,clickable:!0,label:X(l,e,t),onClick:()=>{ne(X(l,e,t)),requestAnimationFrame(()=>ye.inputRef.current?.focus())},sx:{height:30,color:`text.secondary`,"&:hover":{color:`text.primary`}}},t))})]}),(0,Q.jsxs)(ee,{anchorEl:de,open:le===`project`,onClose:Ne,slotProps:{paper:{sx:{width:310,maxHeight:380}}},children:[(u?.projects??[]).map(e=>(0,Q.jsxs)(Ce,{selected:C===e.projectRef,onClick:()=>{w(e.projectRef),Ne()},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(ht,{name:`folder`,size:26})}),(0,Q.jsx)(Y,{primary:e.label,secondary:e.hint,slotProps:{secondary:{noWrap:!0,title:e.hint}}})]},e.projectRef)),(0,Q.jsx)(ae,{}),(0,Q.jsxs)(Ce,{disabled:pe||u?.projectImport?.status!==`available`,onClick:()=>void Pe(),children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(E,{})}),(0,Q.jsx)(Y,{primary:pe?X(l,`Đang chọn…`,`Choosing…`):X(l,`Thêm một hoặc nhiều folder`,`Add one or more folders`)})]})]}),(0,Q.jsxs)(ee,{anchorEl:de,open:le===`model`,onClose:Ne,slotProps:{paper:{sx:{width:360,maxHeight:440}}},children:[!v&&(we.length>0||p?.available)&&[(0,Q.jsx)(f,{children:X(l,`Công ty`,`Company`)},`company-heading`),...we.length?we.map(e=>(0,Q.jsxs)(Ce,{selected:T===e.modelRef,onClick:()=>{D(e.modelRef),Ne()},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(cr,{})}),(0,Q.jsx)(Y,{primary:`agent-watch-auto`,secondary:X(l,`Harness công ty · Studio quản lý model`,`Company Harness · models managed by Studio`)})]},e.modelRef)):[(0,Q.jsxs)(Ce,{disabled:h,onClick:()=>void De(),children:[(0,Q.jsx)(K,{children:h?(0,Q.jsx)(xe,{size:20}):(0,Q.jsx)(cr,{})}),(0,Q.jsx)(Y,{primary:`agent-watch-auto`,secondary:h?X(l,`Đang kết nối…`,`Connecting…`):ar(p,l),slotProps:{secondary:{sx:{whiteSpace:`normal`}}}})]},`company-connect`)],(0,Q.jsx)(f,{children:X(l,`Cá nhân`,`Personal`)},`personal-heading`)],!u?.defaultModelRef&&(0,Q.jsxs)(Ce,{selected:!T,onClick:()=>{D(``),Ne()},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(oe,{})}),(0,Q.jsx)(Y,{primary:X(l,`Model mặc định của Pi`,`Pi default model`)})]}),Ee.map(e=>(0,Q.jsxs)(Ce,{selected:T===e.modelRef,onClick:()=>{D(e.modelRef),Ne()},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(ht,{name:e.provider,size:26})}),(0,Q.jsx)(Y,{primary:e.displayName,secondary:e.modelRef===u?.defaultModelRef?X(l,`Mặc định · ${e.provider} · High`,`Default · ${e.provider} · High`):e.provider})]},e.modelRef))]}),(0,Q.jsx)(ee,{anchorEl:de,open:le===`thinking`,onClose:Ne,slotProps:{paper:{sx:{width:250,maxHeight:400}}},children:je.map(e=>(0,Q.jsxs)(Ce,{value:e,selected:O===e,onClick:()=>{k(e),Ne()},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(_,{})}),(0,Q.jsx)(Y,{primary:rt(e,l)})]},e))}),(0,Q.jsx)(ee,{anchorEl:de,open:le===`permission`,onClose:Ne,slotProps:{paper:{sx:{width:310}}},children:v||Se?[(0,Q.jsxs)(Ce,{selected:P!==`trusted-full-access`&&P!==`bypass`,onClick:()=>{I(null),Ne()},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(S,{})}),(0,Q.jsx)(Y,{primary:pt(null,l),secondary:X(l,`Hỏi trước mỗi lệnh cần internet`,`Asks before each command that needs the internet`)})]},`ask`),(0,Q.jsxs)(Ce,{selected:P===`trusted-full-access`,onClick:()=>{Ne(),H(`trusted-full-access`)},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(S,{color:`warning`})}),(0,Q.jsx)(Y,{primary:pt(`trusted-full-access`,l),secondary:X(l,`Chỉ hỏi việc bắt buộc phải xác nhận`,`Asks only what must be confirmed`)})]},`full`),...be?.managedBypass?[(0,Q.jsxs)(Ce,{selected:P===`bypass`,onClick:()=>{Ne(),H(`bypass`)},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(S,{color:`error`})}),(0,Q.jsx)(Y,{primary:`Bypass`,secondary:X(l,`Không hỏi gì; admin Studio có thể tắt`,`Asks nothing; a Studio administrator can turn it off`)})]},`bypass`)]:[]]:(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(Ce,{selected:P===null,onClick:()=>{I(null),Ne()},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(S,{})}),(0,Q.jsx)(Y,{primary:X(l,`Theo profile project`,`Project profile default`)})]}),[`read-only`,`workspace-write`,`trusted-full-access`,`bypass`].map(e=>(0,Q.jsxs)(Ce,{selected:P===e,onClick:()=>{Ne(),e===`trusted-full-access`||e===`bypass`?H(e):I(e)},children:[(0,Q.jsx)(K,{children:(0,Q.jsx)(S,{color:e===`bypass`?`error`:e===`trusted-full-access`?`warning`:void 0})}),(0,Q.jsx)(Y,{primary:rt(e,l)})]},e))]})}),(0,Q.jsx)(lt,{open:B!==null,title:B===`bypass`?X(l,`Tạo cuộc trò chuyện với Bypass?`,`Create with Bypass?`):X(l,`Tạo session với toàn quyền?`,`Create with full access?`),description:B===`bypass`?v||Se?kt(l):mt(l):v||Se?it(l):X(l,`Session mới được phép đọc, sửa file và chạy command trong runtime. Xóa dữ liệu và gửi ra ngoài vẫn cần xác nhận riêng.`,`The new session may read and edit files and run commands. Deletion and external transfer still require separate approval.`),cancelLabel:X(l,`Hủy`,`Cancel`),confirmLabel:B===`bypass`?X(l,`Dùng Bypass`,`Use Bypass`):X(l,`Dùng toàn quyền`,`Use full access`),onCancel:()=>H(null),onConfirm:()=>{let e=B;H(null),e&&I(e)}})]})}var Cr=(e,t,n)=>e===`vi`?t:n,wr=[[`⌘K`,`Mở bảng lệnh`,`Open the command palette`],[`⌘⇧O`,`Cuộc trò chuyện mới`,`New chat`],[`⌘,`,`Cài đặt`,`Settings`],[`⌘/`,`Phím tắt và lệnh /`,`Shortcuts and / commands`],[`Esc`,`Dừng lượt đang chạy (trong ô nhập)`,`Stop the running turn (in the composer)`]];function Tr(e,t){let n=/^\/([a-z][a-z-]*)(?:\s+([\s\S]*))?$/.exec(e.trim()),r=n?t.find(e=>e.name===n[1]):void 0;return r?{command:r,argument:(n[2]??``).trim()}:null}var Er=(e,t,n,r)=>({tone:`error`,text:t instanceof Error&&t.message===`session-runtime-busy`?Cr(e,`${n}: lượt này đang chạy, thử lại khi xong.`,`${r}: this turn is running; try again when it ends.`):Cr(e,`${n}. Thử lại.`,`${r}. Try again.`)});async function Dr(e,t,n,r,i){try{return await t(),n}catch(t){return Er(e,t,r,i)}}function Or(e){let{locale:t,actions:n}=e,r=(e,n)=>Cr(t,e,n),i=(e,t)=>({tone:`success`,text:r(e,t)}),a=(e,t)=>({tone:`warning`,text:r(e,t)}),o=[],s=(e,t,n,i,a)=>o.push({name:e,argumentHint:t,description:r(n,i),run:a});return s(`help`,null,`Danh sách lệnh / và phím tắt`,`The / commands and keyboard shortcuts`,async()=>({tone:`info`,text:[...o.map(e=>`/${e.name}${e.argumentHint?` ${e.argumentHint}`:``} — ${e.description}`),...wr.map(([e,t,n])=>`${e} — ${r(t,n)}`)].join(`
3
+ `)})),s(`new`,null,`Cuộc trò chuyện mới`,`New chat`,async()=>(n.newChat(),i(`Đã mở cuộc trò chuyện mới.`,`Opened a new chat.`))),s(`stop`,null,`Dừng lượt đang chạy`,`Stop the running turn`,async()=>e.running?Dr(t,n.stop,i(`Đã dừng lượt đang chạy.`,`Stopped the running turn.`),`Chưa dừng được`,`Could not stop`):{tone:`info`,text:r(`Không có lượt nào đang chạy.`,`No turn is running.`)}),s(`name`,`<tên>`,`Đổi tên cuộc trò chuyện`,`Rename the conversation`,async e=>e?Dr(t,()=>n.rename(e.slice(0,200)),i(`Đã đổi tên thành “${e.slice(0,200)}”.`,`Renamed to “${e.slice(0,200)}”.`),`Chưa đổi được tên`,`Could not rename`):a(`Cách dùng: /name <tên mới>`,`Usage: /name <new name>`)),s(`fork`,null,`Tạo cuộc trò chuyện mới từ cuộc này`,`Fork this conversation`,async()=>Dr(t,n.fork,i(`Đã tạo bản sao của cuộc trò chuyện.`,`Forked the conversation.`),`Chưa tạo được bản sao`,`Could not fork`)),s(`pin`,null,e.pinned?`Bỏ ghim cuộc trò chuyện`:`Ghim cuộc trò chuyện`,e.pinned?`Unpin the conversation`:`Pin the conversation`,async()=>Dr(t,()=>n.pin(!e.pinned),e.pinned?i(`Đã bỏ ghim.`,`Unpinned.`):i(`Đã ghim.`,`Pinned.`),`Chưa đổi được ghim`,`Could not change the pin`)),s(`archive`,null,`Lưu trữ cuộc trò chuyện`,`Archive the conversation`,async()=>Dr(t,n.archive,i(`Đã lưu trữ cuộc trò chuyện.`,`Archived the conversation.`),`Chưa lưu trữ được`,`Could not archive`)),e.thinkingLevels.length&&s(`thinking`,`<${e.thinkingLevels.join(`|`)}>`,`Đổi mức suy luận`,`Change the thinking level`,async r=>e.thinkingLevels.includes(r)?Dr(t,()=>n.setThinking(r),i(`Đã đổi thinking sang ${r}.`,`Thinking is now ${r}.`),`Chưa đổi được thinking`,`Could not change thinking`):a(`Cách dùng: /thinking ${e.thinkingLevels.join(`|`)}`,`Usage: /thinking ${e.thinkingLevels.join(`|`)}`)),e.company?(s(`undo`,null,`Hoàn tác file mà lượt trước của agent đã sửa`,`Undo the files the agent's last turn changed`,async()=>({send:!0})),e.fast&&s(`fast`,`[on|off]`,`Bật/tắt Fast (Harness cho phép)`,`Turn Fast on or off (where the Harness allows it)`,async r=>{let o=r===`on`?!0:r===`off`?!1:r?null:e.fast!==`on`;return o===null?a(`Cách dùng: /fast on|off`,`Usage: /fast on|off`):Dr(t,()=>n.setFast(o),o?i(`Đã bật Fast.`,`Fast is on.`):i(`Đã tắt Fast.`,`Fast is off.`),`Chưa đổi được Fast`,`Could not change Fast`)}),s(`bypass`,`<on|full|off>`,`Bypass (chỉ hỏi việc bàn giao), Toàn quyền (hỏi việc bàn giao và việc phá huỷ) hoặc Hỏi trước`,`Bypass (asks only about the handoff), Full access (asks about the handoff and destructive steps) or Ask first`,async o=>o===`off`?Dr(t,()=>n.setPermission(`workspace-write`),i(`Đã chuyển sang Hỏi trước.`,`Switched to Ask first.`),`Chưa đổi được quyền`,`Access not changed`):o===`full`?{confirm:{title:r(`Bật Toàn quyền?`,`Turn on Full access?`),confirmLabel:r(`Bật Toàn quyền`,`Turn on Full access`),description:r(`Lệnh cần internet hoặc Docker chạy không hỏi; push, PR, publish, deploy, migration, xoá không rõ đích và lệnh trên máy vẫn hỏi.`,`Commands that need the internet or Docker run without asking; pushes, pull requests, publish, deploys, migrations, unknown-target deletes and commands on this machine still ask.`),run:()=>Dr(t,()=>n.setPermission(`trusted-full-access`),i(`Đã bật Toàn quyền.`,`Full access is on.`),`Chưa đổi được quyền`,`Access not changed`)}}:o===`on`?e.bypass?{confirm:{title:r(`Bật Bypass?`,`Turn on Bypass?`),confirmLabel:r(`Bật Bypass`,`Turn on Bypass`),description:r(`Việc làm chạy luôn (internet, Docker, lệnh trên máy, migration); việc bàn giao vẫn hỏi: push, PR, publish, deploy, upload, MCP ghi ra ngoài. Lệnh thường vẫn trong sandbox; /undo vẫn dùng được.`,`The work runs (internet, Docker, commands on this machine, migrations); the handoff is still asked: pushes, pull requests, publish, deploys, uploads, MCP writes. Plain commands stay in the sandbox; /undo still works.`),run:()=>Dr(t,()=>n.setPermission(`bypass`),i(`Đã bật Bypass.`,`Bypass is on.`),`Chưa đổi được quyền`,`Access not changed`)}}:a(`Harness của team đã tắt Bypass (admin Studio). Dùng /bypass full cho Toàn quyền.`,`The team's Harness has Bypass off (Studio administrator). Use /bypass full for Full access.`):a(`Cách dùng: /bypass on|full|off`,`Usage: /bypass on|full|off`))):(s(`model`,`<tên model>`,`Đổi model`,`Change the model`,async r=>{let o=await e.loadModels().catch(()=>[]),s=r.toLowerCase(),c=s?o.filter(e=>e.label.toLowerCase()===s||e.modelRef.toLowerCase()===s):[],l=c.length?c:s?o.filter(e=>e.label.toLowerCase().includes(s)||e.modelRef.toLowerCase().includes(s)):[];return l.length===1?Dr(t,()=>n.setModel(l[0].modelRef),i(`Đã đổi model sang ${l[0].label}.`,`The model is now ${l[0].label}.`),`Chưa đổi được model`,`Could not change the model`):a(`Cách dùng: /model <tên>. Có: ${o.map(e=>e.label).slice(0,12).join(`, `)||`—`}`,`Usage: /model <name>. Available: ${o.map(e=>e.label).slice(0,12).join(`, `)||`—`}`)}),s(`permission`,`<read-only|ask|full|bypass>`,`Đổi quyền của cuộc trò chuyện`,`Change the conversation's access`,async e=>{let o=e===`read-only`?`read-only`:e===`ask`?`workspace-write`:e===`full`?`trusted-full-access`:e===`bypass`?`bypass`:null;if(!o)return a(`Cách dùng: /permission read-only|ask|full|bypass`,`Usage: /permission read-only|ask|full|bypass`);let s=()=>Dr(t,()=>n.setPermission(o),i(`Đã đổi quyền sang ${e}.`,`Access is now ${e}.`),`Chưa đổi được quyền`,`Access not changed`);return o===`bypass`?{confirm:{title:r(`Bật Bypass?`,`Turn on Bypass?`),confirmLabel:r(`Bật Bypass`,`Turn on Bypass`),description:r(`Không hỏi, không chặn gì trong cuộc trò chuyện này (xoá, push, file được bảo vệ đều chạy luôn). Output vẫn che secret, /undo vẫn hoàn tác được.`,`Nothing is asked or blocked in this conversation (deletes, pushes and protected files all run). Output is still redacted and /undo still works.`),run:s}}:o===`trusted-full-access`?{confirm:{title:r(`Bật toàn quyền?`,`Enable full access?`),confirmLabel:r(`Bật toàn quyền`,`Enable full access`),description:r(`Session được đọc, sửa file và chạy command trong phạm vi runtime; xoá hoặc gửi dữ liệu ra ngoài vẫn cần xác nhận riêng.`,`The session may read and edit files and run commands within the runtime; destructive actions and external transfers still ask.`),run:s}}:s()})),s(`changes`,null,`Mở Source Changes`,`Open Source Changes`,async()=>(n.openChanges(),i(`Đã mở Source Changes.`,`Opened Source Changes.`))),s(`settings`,null,`Mở Cài đặt`,`Open Settings`,async()=>(n.openSettings(),i(`Đã mở Cài đặt.`,`Opened Settings.`))),o}var kr=`piagent dashboard`;function Ar(){return(0,$.useSyncExternalStore)(Be,ze,ze)}function jr({locale:e}){let[t,n]=(0,$.useState)(!1);return(0,Q.jsxs)(R,{role:`alert`,spacing:2,sx:{minHeight:`100vh`,alignItems:`center`,justifyContent:`center`,px:2,textAlign:`center`},children:[(0,Q.jsx)(o,{variant:`h6`,component:`h1`,children:X(e,`Tab này đã hết phiên đăng nhập`,`This tab is no longer signed in`)}),(0,Q.jsx)(o,{color:`text.secondary`,sx:{maxWidth:520},children:X(e,`Piagent vừa khởi động lại, tab không được dùng quá 8 giờ, hoặc tab được mở từ một link cũ. Các cuộc trò chuyện vẫn còn nguyên — mở lại Piagent để vào tiếp.`,`Piagent restarted, this tab was unused for over 8 hours, or this tab came from an old link. Your conversations are kept — open Piagent again to continue.`)}),(0,Q.jsxs)(V,{sx:{display:`flex`,gap:1,alignItems:`center`,flexWrap:`wrap`,justifyContent:`center`},children:[(0,Q.jsx)(V,{component:`code`,sx:{px:1.5,py:.75,borderRadius:1,bgcolor:`action.hover`,fontSize:`.9rem`},children:kr}),(0,Q.jsx)(z,{size:`small`,variant:`outlined`,onClick:()=>{navigator.clipboard?.writeText(kr).then(()=>n(!0),()=>n(!1))},children:t?X(e,`Đã chép`,`Copied`):X(e,`Chép lệnh`,`Copy command`)})]}),(0,Q.jsx)(o,{variant:`body2`,color:`text.secondary`,children:X(e,`Chạy lệnh trên trong terminal, hoặc bấm WebUI trong Agent Watch. Sau đó có thể đóng tab này.`,`Run it in a terminal, or choose WebUI in Agent Watch. You can close this tab afterwards.`)})]})}var Mr=`piagent-update-snooze`,Nr=`piagent-update-job-seen`,Pr=36e5;function Fr(e){try{return window.localStorage.getItem(e)}catch{return null}}function Ir(e,t){try{window.localStorage.setItem(e,t)}catch{}}function Lr(e,t){try{let n=JSON.parse(Fr(Mr)??`null`);return n?.version===e&&typeof n.until==`number`&&t<n.until}catch{return!1}}function Rr({locale:e,onDetails:t}){let{status:n,applying:r,error:i,apply:a}=ct(),[s,c]=(0,$.useState)(()=>Date.now()),[l,u]=(0,$.useState)(null),[f,p]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=window.setInterval(()=>c(Date.now()),6e4);return()=>window.clearInterval(e)},[]);let g=n?.piagent.latest??null,_=n?.job??null;(0,$.useEffect)(()=>{!_||_.state!==`succeeded`||Fr(Nr)===_.startedAt||(Ir(Nr,_.startedAt),p(X(e,`Đã cập nhật Piagent ${_.from} → ${_.installed??_.to}.`,`Piagent updated ${_.from} → ${_.installed??_.to}.`)))},[_,e]);let v=!!(n?.installable&&n.updateAvailable&&g&&!_t(n))&&l!==g&&!Lr(g,s),y=()=>{g&&(Ir(Mr,JSON.stringify({version:g,until:Date.now()+Pr})),u(g))},x=(n?.runningConversations??0)>0;return(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsxs)(d,{open:v,onClose:y,fullWidth:!0,maxWidth:`xs`,"aria-labelledby":`piagent-update-offer`,children:[(0,Q.jsxs)(B,{id:`piagent-update-offer`,sx:{display:`flex`,alignItems:`center`,gap:1},children:[(0,Q.jsx)(D,{color:`primary`}),X(e,`Có bản Piagent mới: ${g}`,`Piagent ${g} is available`)]}),(0,Q.jsxs)(m,{sx:{display:`grid`,gap:1.5},children:[(0,Q.jsx)(V,{component:`ul`,sx:{m:0,pl:2.5,display:`grid`,gap:.75},children:n&&ot(e,n).map(e=>(0,Q.jsx)(o,{component:`li`,variant:`body2`,children:e},e))}),x&&(0,Q.jsx)(h,{severity:`info`,children:X(e,`${n?.runningConversations} cuộc trò chuyện đang chạy. Cập nhật khi chúng xong — dialog này sẽ nhắc lại.`,`${n?.runningConversations} conversation(s) running. Update once they finish — this will ask again.`)}),i&&(0,Q.jsx)(h,{severity:`error`,children:gt(e,i)})]}),(0,Q.jsxs)(b,{sx:{flexWrap:`wrap`,gap:1},children:[(0,Q.jsx)(z,{onClick:y,children:X(e,`Để sau (nhắc lại sau 1 giờ)`,`Later (ask again in an hour)`)}),(0,Q.jsx)(z,{onClick:()=>{u(g),t()},children:X(e,`Xem chi tiết`,`Details`)}),(0,Q.jsx)(z,{variant:`contained`,disabled:x||r,onClick:()=>{u(g),a().then(t)},children:X(e,`Cập nhật ngay`,`Update now`)})]})]}),(0,Q.jsx)(ye,{open:f!==null,autoHideDuration:8e3,onClose:()=>p(null),anchorOrigin:{vertical:`top`,horizontal:`center`},children:(0,Q.jsx)(h,{severity:`success`,variant:`filled`,onClose:()=>p(null),children:f})})]})}var zr=e=>Array.from({length:e},()=>({selected:[],other:``,otherOn:!1})),Br=e=>e.selected.length>0||e.otherOn&&e.other.trim().length>0,Vr=(e,t)=>!e||e===`main`?X(t,`Main agent`,`Main agent`):X(t,`Subagent ${e}`,`Subagent ${e}`);function Hr({sessionRef:e,pending:t,locale:n,onDone:r}){let[i,a]=(0,$.useState)(()=>zr(t.questions.length)),[o,s]=(0,$.useState)(null),[c,l]=(0,$.useState)(``),u=(0,$.useRef)([]),d=(0,$.useRef)(null),f=(0,$.useRef)([]),[p,m]=(0,$.useState)(0);(0,$.useEffect)(()=>{d.current?.focus({preventScroll:!0})},[]);let h=(e,t)=>a(n=>n.map((n,r)=>r===e?t(n):n)),g=(e,n)=>h(e,r=>t.questions[e].multiSelect?{...r,selected:r.selected.includes(n)?r.selected.filter(e=>e!==n):[...r.selected,n]}:{selected:[n],other:r.other,otherOn:!1}),_=(e,n=!0)=>{h(e,r=>t.questions[e].multiSelect?{...r,otherOn:n}:{selected:[],other:r.other,otherOn:n}),n&&setTimeout(()=>u.current[e]?.focus(),0)},v=i.every(Br),y=e=>{if(e.target.tagName===`INPUT`&&e.target.type===`text`)return;if(e.key===`Enter`){v&&(e.preventDefault(),x());return}let n=Number(e.target.closest(`fieldset`)?.getAttribute(`data-question`)??NaN),r=Number.isInteger(n)?n:p,a=Number(e.key),o=t.questions[r],s=o.options.length;if(!(!Number.isInteger(a)||a<1||a>s+1)){if(e.preventDefault(),a===s+1){_(r,!o.multiSelect||!i[r].otherOn);return}g(r,a-1),!o.multiSelect&&r+1<t.questions.length&&(m(r+1),f.current[r+1]?.focus({preventScroll:!1}))}},b=async(i,a)=>{s(a),l(``);try{await et(e,t.questionRef,i),r()}catch(e){s(null),l(e.status===409?X(n,`Câu hỏi này đã được trả lời hoặc lượt làm việc đã dừng.`,`This question was already answered or the turn stopped.`):X(n,`Chưa gửi được câu trả lời. Thử lại.`,`The answer could not be sent. Try again.`))}},x=()=>{!v||o||b({answers:i.map(e=>({selected:[...e.selected].sort((e,t)=>e-t),...e.otherOn&&e.other.trim()?{other:e.other.trim()}:{}}))},`answer`)},S=t.questions.length;return(0,Q.jsxs)(`article`,{className:`question-card`,ref:d,tabIndex:-1,onKeyDown:y,"aria-labelledby":`question-${t.questionRef}`,children:[(0,Q.jsxs)(`header`,{children:[(0,Q.jsxs)(`div`,{children:[(0,Q.jsx)(`p`,{className:`section-kicker`,children:X(n,`${Vr(t.role,n)} cần bạn quyết định`,`${Vr(t.role,n)} needs your decision`)}),(0,Q.jsx)(`h2`,{id:`question-${t.questionRef}`,children:S>1?X(n,`${S} câu hỏi`,`${S} questions`):X(n,`1 câu hỏi`,`1 question`)})]}),(0,Q.jsx)(`span`,{className:`question-hint`,children:X(n,`Bấm số để chọn · Enter để gửi`,`Press a number to choose · Enter to send`)})]}),t.questions.map((e,r)=>{let a=i[r],o=`${t.questionRef}-${r}`,s=e.multiSelect?`checkbox`:`radio`;return(0,Q.jsxs)(`fieldset`,{className:r===p?`question-block active`:`question-block`,"data-question":r,tabIndex:-1,ref:e=>{f.current[r]=e},onFocus:()=>m(r),children:[(0,Q.jsxs)(`legend`,{children:[S>1&&(0,Q.jsxs)(`span`,{className:`question-number`,children:[r+1,`.`]}),e.header&&(0,Q.jsx)(`span`,{className:`question-chip`,children:e.header}),(0,Q.jsx)(`span`,{className:`question-text`,children:e.question})]}),e.multiSelect&&(0,Q.jsx)(`p`,{className:`question-multi`,children:X(n,`Có thể chọn nhiều đáp án.`,`You can choose more than one.`)}),(0,Q.jsxs)(`ol`,{className:`question-options`,children:[e.options.map((e,t)=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`label`,{className:a.selected.includes(t)?`selected`:void 0,children:[(0,Q.jsx)(`input`,{type:s,name:o,checked:a.selected.includes(t),onChange:()=>g(r,t)}),(0,Q.jsx)(`span`,{className:`option-number`,"aria-hidden":`true`,children:t+1}),(0,Q.jsxs)(`span`,{className:`option-body`,children:[(0,Q.jsx)(`strong`,{children:e.label}),e.description&&(0,Q.jsx)(`small`,{children:e.description})]})]})},t)),(0,Q.jsxs)(`li`,{className:`question-other`,children:[(0,Q.jsxs)(`label`,{className:a.otherOn?`selected`:void 0,children:[(0,Q.jsx)(`input`,{type:s,name:o,checked:a.otherOn,onChange:()=>_(r,!e.multiSelect||!a.otherOn)}),(0,Q.jsx)(`span`,{className:`option-number`,"aria-hidden":`true`,children:e.options.length+1}),(0,Q.jsx)(`span`,{className:`option-body`,children:(0,Q.jsx)(`strong`,{children:X(n,`Khác`,`Other`)})})]}),a.otherOn&&(0,Q.jsx)(`input`,{type:`text`,ref:e=>{u.current[r]=e},maxLength:1e3,value:a.other,"aria-label":X(n,`Câu trả lời khác cho câu ${r+1}`,`Other answer to question ${r+1}`),placeholder:X(n,`Nhập câu trả lời của bạn`,`Type your answer`),onChange:e=>h(r,t=>({...t,other:e.target.value})),onKeyDown:e=>{e.key===`Enter`&&(e.preventDefault(),x())}})]})]})]},o)}),c&&(0,Q.jsx)(`p`,{className:`form-error`,role:`alert`,children:c}),(0,Q.jsxs)(`footer`,{children:[(0,Q.jsx)(`button`,{type:`button`,className:`secondary-action`,disabled:!!o,onClick:()=>void b({skipped:!0},`skip`),children:o===`skip`?X(n,`Đang gửi…`,`Sending…`):X(n,`Để agent tự quyết`,`Let the agent decide`)}),(0,Q.jsx)(`button`,{type:`button`,className:`primary-action`,disabled:!v||!!o,onClick:x,children:o===`answer`?X(n,`Đang gửi…`,`Sending…`):X(n,`Gửi câu trả lời`,`Send answer`)})]})]})}function Ur(e,t,n=!1){let[r,i]=(0,$.useState)([]),[a,o]=(0,$.useState)(0);return(0,$.useEffect)(()=>{let t=new AbortController;return Ye(e,t.signal).then(e=>i(e.questions??[]),()=>void 0),()=>t.abort()},[e,t,a]),(0,$.useEffect)(()=>{if(!t&&!n&&!r.length)return;let e=setInterval(()=>o(e=>e+1),t&&!r.length?1500:4e3);return()=>clearInterval(e)},[t,n,r.length]),{pending:r,done:e=>i(t=>t.filter(t=>t.questionRef!==e))}}function Wr({sessionRef:e,waiting:t,running:n,approvalRefs:r}){let{locale:i}=Ae(),a=Ur(e,t,n),o=on(r,e,i),[s,c]=(0,$.useState)(null),l=Lt([...a.pending.map(e=>({key:e.questionRef,kind:`question`,role:e.role??`main`,askedAt:e.askedAt,label:e.questions[0]?.header||e.questions[0]?.question||X(i,`Câu hỏi`,`Question`)})),...o.refs.map(e=>{let t=o.states[e]?.request;return{key:e,kind:`approval`,role:`main`,askedAt:t?.requestedAt??new Date(864e13).toISOString(),expiresAt:t?.expiresAt??null,label:t?t.action.commandPreview?.split(`
4
+ `)[0]||t.action.toolName:X(i,`Yêu cầu duyệt`,`Approval`)}})]),u=l.find(e=>e.key===s)??l[0];(0,$.useEffect)(()=>{s&&!l.some(e=>e.key===s)&&c(null)},[s,l.map(e=>e.key).join(`\0`)]);let d=u?.key??null;if((0,$.useLayoutEffect)(()=>{if(!d)return;let e=requestAnimationFrame(()=>window.scrollTo({top:document.documentElement.scrollHeight-window.innerHeight,behavior:`smooth`}));return()=>cancelAnimationFrame(e)},[d]),!u)return null;let f=l.indexOf(u);return(0,Q.jsxs)(`section`,{className:`decision-queue`,"aria-label":X(i,`Việc đang chờ bạn quyết định`,`Decisions waiting for you`),"aria-live":`polite`,children:[l.length>1&&(0,Q.jsxs)(`nav`,{className:`decision-steps`,"aria-label":X(i,`Các việc đang chờ`,`Waiting decisions`),children:[(0,Q.jsx)(`strong`,{children:X(i,`Việc cần bạn quyết · ${f+1}/${l.length}`,`Needs your decision · ${f+1}/${l.length}`)}),(0,Q.jsx)(`ol`,{children:l.map((e,t)=>(0,Q.jsx)(`li`,{children:(0,Q.jsxs)(`button`,{type:`button`,"aria-current":e===u?`step`:void 0,className:e===u?`decision-step current`:`decision-step`,onClick:()=>c(e.key),title:`${Vr(e.role,i)} · ${e.label}`,children:[(0,Q.jsx)(`span`,{className:`decision-step-number`,children:t+1}),(0,Q.jsx)(`span`,{className:`decision-step-kind`,children:e.kind===`question`?X(i,`Hỏi`,`Ask`):X(i,`Duyệt`,`Approve`)}),(0,Q.jsx)(`span`,{className:`decision-step-role`,children:Vr(e.role,i)}),(0,Q.jsx)(`span`,{className:`decision-step-label`,children:e.label})]})},e.key))})]}),u.kind===`question`?(0,Q.jsx)(Hr,{sessionRef:e,locale:i,onDone:()=>a.done(u.key),pending:a.pending.find(e=>e.questionRef===u.key)},u.key):(0,Q.jsx)($t,{state:o.states[u.key]??{},locale:i,asker:Vr(u.role,i),setState:e=>o.set(u.key,e)},u.key)]})}function Gr(e,t,n){let r=typeof t==`string`?t:e?.assistantMessageRef??null,i=e?.assistant??``;return{assistant:`${i}${i&&r!==(e?.assistantMessageRef??null)&&!/\n\n$/.test(i)?i.endsWith(`
5
+ `)?`
6
+ `:`
7
+
8
+ `:``}${n}`,assistantMessageRef:r}}function Kr(e,t){return e?.state===`ready`&&e.gatewayInstanceRef===t&&Number.isSafeInteger(e.eventSequence)&&e.eventSequence>=0&&Array.isArray(e.operations)&&Array.isArray(e.settlements)?e.eventSequence:null}function qr(e,t){return e&&!t?`connected`:`reconnecting`}var Jr=100,Yr=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/,Xr=/^[a-z0-9][a-z0-9.-]{0,95}$/,Zr=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;function Qr(e,t){return typeof t==`string`&&Xr.test(t)?t:e===`aborted`?`operation-aborted`:e===`blocked`?`operation-blocked`:e===`error`?`operation-failed`:`operation-settlement-unknown`}function $r(e){if(e.settlement===`completed`||typeof e.operationRef!=`string`||!Yr.test(e.operationRef)||typeof e.settledAt!=`string`||!Zr.test(e.settledAt)||!Number.isSafeInteger(e.sequence)||Number(e.sequence)<1)return null;let t=[`blocked`,`aborted`,`error`,`unknown`].includes(String(e.settlement))?e.settlement:`unknown`,n=t===`error`?`failed`:t;return{activityRef:e.operationRef,operationRef:e.operationRef,settlement:t,state:n,reasonCode:Qr(t,e.reasonCode),settledAt:e.settledAt,sequence:Number(e.sequence)}}function ei(e,t){let n=new Map;for(let r of[...e,...t])n.has(r.operationRef)||n.set(r.operationRef,r);return[...n.values()].sort((e,t)=>t.sequence-e.sequence).slice(0,Jr)}function ti(e){if(e.state!==`ready`)return{};let t={};for(let n of e.settlements??[]){let e=$r(n);e&&(t[n.sessionRef]=ei(t[n.sessionRef]??[],[e]))}return t}function ni(e,t){let n=[`completed`,`blocked`,`aborted`,`error`].includes(String(t.settlement))?t.settlement:`unknown`;return{...e,operationRef:t.operationRef,abortable:!1,complete:!0,settlement:n,activities:[],delivery:e.user?`admitted`:e.delivery,assistant:n===`completed`?e.assistant:``,error:n===`completed`?null:String(t.reasonCode??`operation-settlement-unknown`)}}function ri(e,t){return{...e??{assistant:``,activities:[],operationRef:null,complete:!0,error:null},user:t.message,assistant:``,attachments:t.attachments,activities:[],operationRef:null,abortable:!1,complete:!1,settlement:null,error:null,messageRequestId:t.messageRequestId,delivery:`submitting`,startedAt:t.submittedAt,lastEventAt:t.submittedAt}}function ii(e,t,n,r){let i=t===`admitted`&&!!n&&e.operationRef===n&&e.complete;return{...e,delivery:t,operationRef:n??e.operationRef,abortable:t===`admitted`&&!i&&!!(n??e.operationRef),complete:t===`admitted`?i:e.complete,error:null,lastEventAt:r??e.lastEventAt}}function ai(e,t,n){return!e||e.messageRequestId!==n||e.delivery===`admitted`?e:t}function oi(e,t){if(t.state!==`ready`)return{...e};let n=new Map(t.operations.map(e=>[e.sessionRef,e])),r={...e};for(let[i,a]of Object.entries(e))n.has(i)||a.complete||a.delivery!==`submitting`&&(r[i]={...a,assistant:``,activities:[],operationRef:null,abortable:!1,complete:!0,settlement:`unknown`,error:`operation-settlement-unavailable`,lastEventAt:t.generatedAt});for(let n of t.operations){let i=e[n.sessionRef],a=!(n.messageRequestId&&i?.messageRequestId&&n.messageRequestId!==i.messageRequestId)&&(i?.operationRef===n.operationRef||!!(i?.user&&[`submitting`,`unconfirmed`].includes(String(i.delivery))));r[n.sessionRef]=a?{...i,operationRef:n.operationRef,abortable:n.abortable,complete:!1,settlement:null,messageRequestId:n.messageRequestId??i?.messageRequestId,delivery:i?.user?`admitted`:i?.delivery,error:null,lastEventAt:t.generatedAt}:{user:``,assistant:``,attachments:[],activities:[],operationRef:n.operationRef,messageRequestId:n.messageRequestId??null,abortable:n.abortable,complete:!1,settlement:null,error:null,runtimeRecovery:null,startedAt:t.generatedAt,lastEventAt:t.generatedAt}}return r}function si(e,t){let n=e.toLowerCase();return n===`compaction`?t===`vi`?`tóm tắt phần cũ của cuộc trò chuyện`:`summarising the older part of the conversation`:n===`capacity-wait`?t===`vi`?`chờ tài khoản công ty rảnh`:`waiting for a free company account`:n===`ask_user`?t===`vi`?`chờ bạn trả lời câu hỏi`:`waiting for your answer`:/(subagent|scout|delegate|agent)/.test(n)?t===`vi`?`phối hợp agent hỗ trợ`:`coordinating a helper agent`:/(bash|exec|shell|command|terminal)/.test(n)?t===`vi`?`chạy lệnh`:`running a command`:/(read|grep|find|list|glob|search_file)/.test(n)?t===`vi`?`đọc mã nguồn`:`reading source`:/(edit|write|patch|apply)/.test(n)?t===`vi`?`cập nhật file`:`updating files`:/(test|verify|check|lint)/.test(n)?t===`vi`?`kiểm tra kết quả`:`verifying results`:/(web|search|browser|fetch)/.test(n)?t===`vi`?`tìm kiếm thông tin`:`searching`:t===`vi`?`chạy công cụ`:`running a tool`}var ci=/(?:sk-(?:proj|live|test|svcacct)-[A-Za-z0-9_-]{8,}|as_(?:live|device|run)_[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}_|(?:api[_-]?key|password|secret|token)=)/i;function li(e){if(typeof e!=`string`)return null;let t=(e.replace(/\\/g,`/`).split(`/`).at(-1)??``).trim();return!t||t===`.`||t===`..`||t.length>160||/[\u0000-\u001f\u007f/\\]/.test(t)||ci.test(t)||t.includes(`[REDACTED`)?null:t}function ui(e,t){let n=[...e.filter(e=>e.toolCallRef!==t.toolCallRef),t],r=n.filter(e=>!e.agent).slice(-16);return[...n.filter(e=>e.agent).slice(-200),...r]}function di(e,t){return e?.includes(`review`)?t===`vi`?`nhờ reviewer độc lập kiểm tra lại thay đổi`:`having an independent reviewer check the change`:e?.includes(`verify`)?t===`vi`?`nhờ agent hỗ trợ kiểm chứng kết quả`:`having a helper verify the results`:si(`subagent`,t)}function fi(e,t){let n=Math.floor(Math.max(0,e)/6e4);return n<1?t===`vi`?`Vừa bắt đầu`:`Just started`:t===`vi`?`Đã chạy ${n} phút`:`Running for ${n}m`}function pi(e){return e?.active?(e.roles?.length?e.roles:[`helper`]).map(t=>({toolCallRef:`helper-${t}`,toolLabel:`subagent ${t}`,state:`running`,startedAt:e.since})):[]}function mi(e,t=`vi`,n=Date.now(),r){let i=[...e.activities].reverse().find(e=>e.state===`running`&&!e.agent);if(!i&&r?.active){let i=Date.parse(r.since??``),a=Number.isFinite(i)?fi(n-i,t):t===`vi`?`Đang chạy`:`Running`,o=e.assistant||r.roles?.includes(`review`)?t===`vi`?` · Câu trả lời trên có thể còn được bổ sung`:` · The answer above may still change`:``,s=[...e.activities].reverse().find(e=>e.agent&&e.state===`running`),c=s?` · ${s.agent}: ${s.toolLabel}${s.detail?` ${s.detail}`:``}`:``;return{label:t===`vi`?`Piagent đang ${di(r.roles,t)}…`:`Piagent is ${di(r.roles,t)}…`,detail:`${a}${o}${c}`}}let a=i?si(i.toolLabel,t):e.activities.length?t===`vi`?`tổng hợp bước tiếp theo`:`preparing the next step`:t===`vi`?`phân tích yêu cầu`:`analyzing the request`,o=Date.parse(e.lastEventAt??i?.startedAt??e.startedAt??``),s=Number.isFinite(o)?Math.max(0,Math.floor((n-o)/1e3)):null,c=s===null?t===`vi`?`Đang chờ cập nhật tiến trình đầu tiên`:`Waiting for the first progress update`:s<10?t===`vi`?`Tiến trình vừa cập nhật`:`Progress updated just now`:s<60?t===`vi`?`Cập nhật ${s} giây trước`:`Updated ${s}s ago`:t===`vi`?`Cập nhật ${Math.floor(s/60)} phút trước`:`Updated ${Math.floor(s/60)}m ago`,l=li(i?.fileLabel),u=l?`${l} · ${c}`:c;return{label:t===`vi`?`Piagent đang ${a}…`:`Piagent is ${a}…`,detail:u}}function hi(e,t,n,r){if(e?.state!==`ready`||e.gatewayInstanceRef!==t)return!1;let i=e.operations.find(e=>e.sessionRef===n);return i?.operationRef===r&&i.abortable===!0}function gi(e){let t=e.lastIndexOf(`
9
+
10
+ `);return(e.slice(0,t<0?0:t).match(/^```/gm)??[]).length%2==1&&(t=e.lastIndexOf("\n```",t)),t>0?[e.slice(0,t).replace(/\n+$/,``),e.slice(t).replace(/^\n+/,``)]:[``,e]}function _i(e,t){return{key:t,user:e,steps:[],answer:null,failure:null,failureDetail:null,requests:0,tokens:0,model:null,process:null,reviewing:!1,end:null,startedAt:e.recordedAt,endedAt:null,outputTokens:0,generationMs:0}}var vi=new Set([`objection`,`rejudge`,`dispute`]);function yi(e){let t=[],n=null,r=NaN;for(let i of e){let e=Date.parse(i.recordedAt),a=r;if(i.role!==`custom`&&(r=e),i.role===`user`){n=_i(i,i.messageRef),t.push(n);continue}if(!n||i.helperRun||i.role===`tool-result`)continue;if(n.endedAt=i.recordedAt,i.role===`custom`&&i.turnEnd){n.end=i.turnEnd;continue}if(i.role===`custom`&&i.process){if(n.process&&(n.answer&&(n.steps.push({kind:`note`,key:`${i.messageRef}:round-answer`,text:n.answer,draft:!0}),n.answer=null),n.steps.push({kind:`process`,key:`${i.messageRef}:round`,process:n.process}),n.process=null),i.process.phase===`reviewing`){n.reviewing=!0;continue}if(i.process.phase===`final`){n.process=i.process,n.reviewing=!1;continue}if(n.answer&&!vi.has(i.process.phase)){let e=n.reviewing||i.process.phase===`review`;n.steps.push({kind:`note`,key:`${i.messageRef}:answer`,text:n.answer,draft:!0,...e?{beforeReview:!0}:{}}),n.answer=null,n.reviewing=!1}n.steps.push({kind:`process`,key:i.messageRef,process:i.process});continue}i.role===`assistant`&&i.usage?.outputTokens&&e>a&&(n.outputTokens+=i.usage.outputTokens,n.generationMs+=e-a),i.role===`assistant`&&(i.failure?.local||(n.requests+=1),n.tokens+=i.usage?.totalTokens??0,n.model=i.model??n.model);let o=ln(i);if(o){n.answer||(n.failure=o,n.failureDetail=i.failure??null);continue}for(let e of i.toolCalls)n.steps.push({kind:`tool`,key:`${i.messageRef}:${e.toolCallRef}`,tool:e});if(i.toolCalls.length)continue;let s=i.role===`assistant`?Qt(i.content.text??``):i.content.text;if(s){if(i.role===`custom`){n.steps.push({kind:`note`,key:i.messageRef,text:s});continue}n.answer&&n.answer.trim()!==s.trim()&&n.steps.push({kind:`note`,key:`${i.messageRef}:previous`,text:n.answer}),n.answer=s,n.failure=null,n.failureDetail=null}}for(let e of t){let t=new Set(e.answer?[e.answer.trim()]:[]);e.steps=e.steps.reduceRight((e,n)=>{if(n.kind===`note`&&n.draft){let r=n.text.trim();if(t.has(r))return e;t.add(r)}return[n,...e]},[])}return t}function bi(e){let t=Date.parse(e.startedAt??``),n=Date.parse(e.endedAt??``);return Number.isFinite(t)&&Number.isFinite(n)&&n>=t?Math.round((n-t)/1e3):null}function xi(e){if(e.outputTokens<50||e.generationMs<250)return null;let t=e.outputTokens/(e.generationMs/1e3);return t>=10?Math.round(t):Math.round(t*10)/10}function Si(e,t){return e<40||t<1e3?null:Math.round(e/4/(t/1e3))}function Ci(e){return e<1e3?String(e):e<1e6?`${(e/1e3).toFixed(+(e<1e4))}k`:`${(e/1e6).toFixed(1)}M`}var wi=e=>`/api/v1/sessions/${encodeURIComponent(e)}/checkpoints`,Ti=`piagent-webui-checkpoint-v1`;function Ei(e){return Array.isArray(e)?`[${e.map(Ei).join(`,`)}]`:e&&typeof e==`object`?`{${Object.entries(e).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${JSON.stringify(e)}:${Ei(t)}`).join(`,`)}}`:JSON.stringify(e)}async function Di(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return`sha256:${[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,`0`)).join(``)}`}var Oi=e=>typeof e==`string`&&/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(e),ki=e=>typeof e==`string`&&/^[a-f0-9]{64}$/.test(e),Ai=(e,t)=>typeof e==`string`&&e.length>0&&e.length<=t,ji=e=>Array.isArray(e)&&e.length<=1e4&&e.every(e=>Ai(e,4096)),Mi=e=>typeof e==`string`&&/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/.test(e)&&Number.isFinite(Date.parse(e));function Ni(e){return e&&[`projectRef`,`runtimeInstanceId`,`sessionRef`].every(t=>typeof e[t]==`string`&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e[t]))&&[`taskId`,`taskRunId`,`agentOperationId`,`toolCallId`].every(t=>e[t]===null||typeof e[t]==`string`&&/^[A-Za-z0-9][A-Za-z0-9._:@~-]{0,159}$/.test(e[t]))}function Pi(e){return Oi(e.targetId)&&[`ready`,`conflict`,`busy`,`none`,`unavailable`].includes(e.result)&&(e.previewDigest===null||ki(e.previewDigest))&&(e.tree===null||typeof e.tree==`string`&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(e.tree))&&Array.isArray(e.steps)&&e.steps.length<=64&&e.steps.every(e=>e&&Oi(e.id)&&Ai(e.turnRef,256)&&ji(e.restore)&&ji(e.remove))&&ji(e.files)&&ji(e.conflicts)&&(e.stoppedAt===null||Oi(e.stoppedAt))}async function Fi(e,t,n){let r=await fetch(wi(e)+(t?`/${encodeURIComponent(t)}`:``),{credentials:`same-origin`,signal:n,headers:{Accept:`application/json`}});if(r.status===401&&Re(),!r.ok)throw Error(`checkpoint-unavailable`);let i=await r.json();if(!i||i.schemaVersion!==1||i.version!==Ti||i.identity?.sessionRef!==e||!Ni(i.identity)||i.messageType!==(t?`preview`:`state`)||!/^[a-f0-9]{64}$/.test(i.revisions?.checkpointRevision??``)||i.messageType===`state`&&(typeof i.available!=`boolean`||typeof i.agentRunning!=`boolean`||!Array.isArray(i.points)||i.points.length>64||!i.points.every(e=>e&&Oi(e.id)&&Ai(e.turnRef,256)&&Number.isSafeInteger(e.at)&&e.at>=0))||i.messageType===`preview`&&(i.targetId!==t||!Pi(i)))throw Error(`checkpoint-response-invalid`);return i}var Ii=(e,t)=>Fi(e,null,t),Li=(e,t,n)=>Fi(e,t,n);async function Ri(e){if(!Pi(e)||!Ni(e.identity)||!ki(e.revisions?.checkpointRevision)||!e.previewDigest||!e.tree||!e.steps.length||![`ready`,`conflict`].includes(e.result))throw Error(`checkpoint-preview-unavailable`);let t=Date.now(),n=`checkpoint.restore`,r={...e.identity},i={...e.revisions},a={targetId:e.targetId,previewDigest:e.previewDigest,expectedTree:e.tree,confirmed:!0};return{schemaVersion:1,version:Ti,messageType:`command`,action:n,identity:r,expectedRevisions:i,payload:a,commandId:crypto.randomUUID(),idempotencyKey:crypto.randomUUID(),requestedAt:new Date(t).toISOString(),expiresAt:new Date(t+6e4).toISOString(),actionDigest:await Di(Ei({action:n,identity:r,expectedRevisions:i,payload:a}))}}async function zi(e,t){let{action:n,identity:r,expectedRevisions:i,payload:a}=e;return e.schemaVersion===1&&e.version===Ti&&e.messageType===`command`&&n===`checkpoint.restore`&&Ni(r)&&r.sessionRef===t&&ki(i?.checkpointRevision)&&a?.confirmed===!0&&Oi(a.targetId)&&ki(a.previewDigest)&&typeof a.expectedTree==`string`&&/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(a.expectedTree)&&typeof e.commandId==`string`&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e.commandId)&&typeof e.idempotencyKey==`string`&&/^[A-Za-z0-9._~-]{32,128}$/.test(e.idempotencyKey)&&Mi(e.requestedAt)&&Mi(e.expiresAt)&&e.actionDigest===await Di(Ei({action:n,identity:r,expectedRevisions:i,payload:a}))}async function Bi(e,t){if(!await zi(t,e))throw Error(`checkpoint-command-invalid`);let n=Le();if(!n)throw Error(`checkpoint-unavailable`);let r=await Ie(wi(e),{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Piagent-CSRF":n},body:JSON.stringify(t)});if(r.status===401&&Re(),!r.ok)throw Error(`checkpoint-unavailable`);let i=await r.json();if(!i||i.schemaVersion!==1||i.version!==Ti||i.messageType!==`receipt`||i.commandId!==t.commandId||i.actionDigest!==t.actionDigest||i.action!==t.action||i.targetId!==t.payload.targetId||i.idempotencyKeyDigest!==await Di(t.idempotencyKey)||Ei(i.identity)!==Ei(t.identity)||![`settled`,`rejected`,`uncertain`].includes(i.phase)||![`restored`,`conflict`,`stale-revision`,`identity-mismatch`,`read-only`,`busy`,`unavailable`,`expired`,`idempotency-payload-mismatch`,`effect-unknown`].includes(i.resultCode)||i.requestedAt!==t.requestedAt||!Mi(i.settledAt)||typeof i.deduplicated!=`boolean`||!ki(i.observedRevisionsBefore?.checkpointRevision)||!ki(i.observedRevisionsAfter?.checkpointRevision)||!Array.isArray(i.completed)||i.completed.length>64||!i.completed.every(Oi)||!ji(i.files)||!ji(i.conflicts)||!(i.stoppedAt===null||Oi(i.stoppedAt))||i.phase===`uncertain`!=(i.resultCode===`effect-unknown`)||i.resultCode===`restored`&&i.phase!==`settled`)throw Error(`checkpoint-receipt-invalid`);return i}var Vi=`piagent.checkpoint.pending.v1`,Hi=64;function Ui(e){let t=e.getItem(Vi);if(t===null)return Object.create(null);if(t.length>262144)throw Error(`checkpoint-pending-invalid`);let n=JSON.parse(t);if(!Array.isArray(n)||n.length>Hi)throw Error(`checkpoint-pending-invalid`);let r=Object.create(null);for(let e of n){if(!Array.isArray(e)||e.length!==2)throw Error(`checkpoint-pending-invalid`);let[t,n]=e;if(typeof t!=`string`||!/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(t)||r[t]||!n||n.schemaVersion!==1||n.version!==`piagent-webui-checkpoint-v1`||n.messageType!==`command`||n.action!==`checkpoint.restore`||n.identity?.sessionRef!==t||n.payload?.confirmed!==!0||typeof n.payload.targetId!=`string`||typeof n.commandId!=`string`||typeof n.idempotencyKey!=`string`)throw Error(`checkpoint-pending-invalid`);r[t]=n}return r}function Wi(e,t=window.sessionStorage){return Ui(t)[e]}function Gi(e,t,n=window.sessionStorage){let r=Ui(n),i=r[e];if(i&&JSON.stringify(i)!==JSON.stringify(t))throw Error(`checkpoint-pending-exists`);if(!i&&Object.keys(r).length>=Hi)throw Error(`checkpoint-pending-capacity`);if(t.identity.sessionRef!==e)throw Error(`checkpoint-pending-session`);r[e]=t;let a=JSON.stringify(Object.entries(r));if(a.length>262144)throw Error(`checkpoint-pending-capacity`);if(n.setItem(Vi,a),n.getItem(Vi)!==a)throw Error(`checkpoint-pending-write-failed`)}function Ki(e,t,n=window.sessionStorage){let r=Ui(n);if(r[e]){if(JSON.stringify(r[e])!==JSON.stringify(t))throw Error(`checkpoint-pending-replaced`);delete r[e],n.setItem(Vi,JSON.stringify(Object.entries(r)))}}var qi=(0,$.createContext)(null);function Ji({turnRef:e}){let t=(0,$.useContext)(qi),n=t?.state?.points.find(t=>t.turnRef===e);return!t||!n?null:(0,Q.jsx)(z,{size:`small`,disabled:t.busy||t.state?.agentRunning,onClick:()=>t.open(n.id),sx:{alignSelf:`flex-start`},children:X(t.locale,`Khôi phục về trước lượt này`,`Restore before this turn`)})}function Yi({sessionRef:e,refresh:t,running:n,locale:r,children:i}){let[a,s]=(0,$.useState)(),[c,l]=(0,$.useState)(0),[u,f]=(0,$.useState)(!1),[p,g]=(0,$.useState)(!1),[_,v]=(0,$.useState)(!1),[y,x]=(0,$.useState)(),[S,C]=(0,$.useState)(),[w,T]=(0,$.useState)(!1),[E]=(0,$.useState)(()=>{try{return{command:Wi(e),failed:!1}}catch{return{command:void 0,failed:!0}}}),[D,O]=(0,$.useState)(E.command),[k,A]=(0,$.useState)(E.failed),j=(0,$.useRef)(null),M=(0,$.useRef)(!1),N=(0,$.useRef)(!0);(0,$.useEffect)(()=>(N.current=!0,()=>{N.current=!1,j.current?.abort()}),[]),(0,$.useEffect)(()=>{let t=new AbortController;return Ii(e,t.signal).then(e=>{t.signal.aborted||s(e)}).catch(()=>{}),()=>t.abort()},[e,t,c]);let P=t=>{if(f(!0),C(void 0),T(!1),D)return;j.current?.abort();let n=new AbortController;j.current=n,x(void 0),g(!0),Li(e,t,n.signal).then(e=>{n.signal.aborted||x(e)}).catch(()=>{n.signal.aborted||T(!0)}).finally(()=>{n.signal.aborted||g(!1)})},F=async()=>{if(!(k||M.current||!D&&(!y||n||a?.agentRunning||![`ready`,`conflict`].includes(y.result)))){M.current=!0,v(!0),T(!1);try{let t=D??await Ri(y);try{Gi(e,t)}catch{A(!0);return}O(t);let n=await Bi(e,t);if(n.phase!==`uncertain`&&Ki(e,t),!N.current)return;C(n),n.phase!==`uncertain`&&O(void 0),l(e=>e+1)}catch{N.current&&T(!0)}finally{window.dispatchEvent(new CustomEvent(`piagent-workspace-changed`,{detail:{sessionRef:e}})),M.current=!1,N.current&&v(!1)}}},I=()=>{M.current||(j.current?.abort(),f(!1),g(!1))},L=S?.conflicts??y?.conflicts??[],ee=S?.phase===`uncertain`||w&&!!D;return(0,Q.jsxs)(qi.Provider,{value:{state:a,busy:n||_||k,open:P,locale:r},children:[a&&!a.available&&(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,children:X(r,`Project không dùng Git nên không có checkpoint để khôi phục.`,`This project has no Git repository, so checkpoints are unavailable.`)}),D&&!u&&(0,Q.jsx)(h,{severity:`warning`,action:(0,Q.jsx)(z,{color:`inherit`,onClick:()=>P(D.payload.targetId),children:X(r,`Xem kết quả`,`Check result`)}),children:X(r,`Một lần khôi phục chưa có kết quả xác nhận.`,`A restore is awaiting a confirmed result.`)}),k&&!u&&(0,Q.jsx)(h,{severity:`error`,children:X(r,`Không đọc hoặc lưu được yêu cầu khôi phục đang chờ trong trình duyệt. Chưa gửi yêu cầu mới; hãy kiểm tra file trước khi tiếp tục.`,`The browser could not read or save the pending restore. No new request was sent; inspect your files before continuing.`)}),i,(0,Q.jsxs)(d,{open:u,onClose:I,fullWidth:!0,maxWidth:`sm`,"aria-labelledby":`checkpoint-dialog-title`,children:[(0,Q.jsx)(B,{id:`checkpoint-dialog-title`,children:X(r,`Khôi phục về trước lượt này`,`Restore before this turn`)}),(0,Q.jsx)(m,{children:(0,Q.jsxs)(R,{spacing:2,children:[k&&(0,Q.jsx)(h,{severity:`error`,children:X(r,`Không đọc hoặc lưu được yêu cầu khôi phục đang chờ trong trình duyệt. Chưa gửi yêu cầu mới; hãy kiểm tra file trước khi tiếp tục.`,`The browser could not read or save the pending restore. No new request was sent; inspect your files before continuing.`)}),p&&(0,Q.jsx)(o,{children:X(r,`Đang xem trước…`,`Loading preview…`)}),y&&!S&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(o,{children:X(r,`Sẽ hoàn tác ${y.steps.length} lượt từ mới nhất về lượt đã chọn. Commit và vùng stage được giữ nguyên.`,`Undo ${y.steps.length} turns from newest to the selected turn. Commits and staged changes are preserved.`)}),(0,Q.jsx)(o,{variant:`body2`,sx:{whiteSpace:`pre-wrap`,maxHeight:240,overflow:`auto`},children:y.files.join(`
11
+ `)}),![`ready`,`conflict`].includes(y.result)&&(0,Q.jsx)(h,{severity:`info`,children:X(r,`Checkpoint hiện không thể khôi phục. Đóng hộp thoại rồi xem trước lại khi lượt chạy kết thúc.`,`This checkpoint cannot be restored now. Close this dialog and preview again after the running turn ends.`)})]}),L.length>0&&(0,Q.jsxs)(h,{severity:`warning`,children:[X(r,`Sẽ dừng trước file đã thay đổi sau lượt: `,`Stop before files changed after the turn: `),L.join(`, `)]}),S&&!ee&&(0,Q.jsx)(h,{severity:S.resultCode===`restored`?`success`:`warning`,children:S.resultCode===`restored`?X(r,`Đã khôi phục ${S.completed.length} lượt.`,`Restored ${S.completed.length} turns.`):S.resultCode===`conflict`?X(r,`Đã khôi phục ${S.completed.length} lượt và dừng để giữ thay đổi của bạn.`,`Restored ${S.completed.length} turns and stopped to preserve your changes.`):X(r,`Chưa khôi phục: trạng thái hoặc quyền đã thay đổi. Đóng hộp thoại và xem trước lại.`,`Not restored: state or permissions changed. Close this dialog and preview again.`)}),ee&&(0,Q.jsx)(h,{severity:`warning`,children:X(r,`Chưa xác nhận được kết quả; một số file có thể đã thay đổi. Kiểm tra file trước khi tiếp tục. Nút bên dưới chỉ kiểm tra lại cùng yêu cầu.`,`The result is unconfirmed; some files may have changed. Inspect them before continuing. The button below checks the same request.`)}),w&&!D&&(0,Q.jsx)(h,{severity:`error`,children:X(r,`Không tải được preview. Đóng hộp thoại và thử lại.`,`Could not load the preview. Close this dialog and try again.`)})]})}),(0,Q.jsxs)(b,{children:[(0,Q.jsx)(z,{disabled:_,onClick:I,children:X(r,`Đóng`,`Close`)}),(!S||ee)&&(0,Q.jsx)(z,{variant:`contained`,disabled:k||_||p||!D&&(n||a?.agentRunning||!y?.steps.length||![`ready`,`conflict`].includes(y?.result??``)),onClick:()=>void F(),children:D?X(r,`Kiểm tra lại kết quả`,`Check result again`):X(r,`Xác nhận khôi phục`,`Confirm restore`)})]})]})]})}var Xi=H((0,Q.jsx)(`path`,{d:`M19 5v14H5V5zm0-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-4.86 8.86-3 3.87L9 13.14 6 17h12z`}),`ImageOutlined`),Zi=H((0,Q.jsx)(`path`,{d:`M22 11V3h-7v3H9V3H2v8h7V8h2v10h4v3h7v-8h-7v3h-2V8h2v3zM7 9H4V5h3zm10 6h3v4h-3zm0-10h3v4h-3z`}),`AccountTreeOutlined`),Qi=H((0,Q.jsx)(`path`,{d:`m22.61 18.99-9.08-9.08c.93-2.34.45-5.1-1.44-7C9.79.61 6.21.4 3.66 2.26L7.5 6.11 6.08 7.52 2.25 3.69C.39 6.23.6 9.82 2.9 12.11c1.86 1.86 4.57 2.35 6.89 1.48l9.11 9.11c.39.39 1.02.39 1.41 0l2.3-2.3c.4-.38.4-1.01 0-1.41m-3 1.6-9.46-9.46c-.61.45-1.29.72-2 .82-1.36.2-2.79-.21-3.83-1.25C3.37 9.76 2.93 8.5 3 7.26l3.09 3.09 4.24-4.24-3.09-3.09c1.24-.07 2.49.37 3.44 1.31 1.08 1.08 1.49 2.57 1.24 3.96-.12.71-.42 1.37-.88 1.96l9.45 9.45z`}),`BuildOutlined`),$i=H((0,Q.jsx)(`path`,{d:`M22 8c0-.55-.45-1-1-1h-7c-.55 0-1 .45-1 1s.45 1 1 1h7c.55 0 1-.45 1-1m-9 8c0 .55.45 1 1 1h7c.55 0 1-.45 1-1s-.45-1-1-1h-7c-.55 0-1 .45-1 1M10.47 4.63c.39.39.39 1.02 0 1.41l-4.23 4.25c-.39.39-1.02.39-1.42 0L2.7 8.16a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0l1.42 1.42 3.54-3.54c.38-.38 1.02-.38 1.4 0m.01 8.01c.39.39.39 1.02 0 1.41L6.25 18.3c-.39.39-1.02.39-1.42 0L2.7 16.16c-.39-.39-.39-1.02 0-1.41s1.02-.39 1.41 0l1.42 1.42 3.54-3.54c.38-.38 1.02-.38 1.41.01`}),`ChecklistRounded`),ea=H((0,Q.jsx)(`path`,{d:`m14.85 4.85 1.44 1.44-2.88 2.88 1.42 1.42 2.88-2.88 1.44 1.44c.31.31.85.09.85-.36V4.5c0-.28-.22-.5-.5-.5h-4.29c-.45 0-.67.54-.36.85M8.79 4H4.5c-.28 0-.5.22-.5.5v4.29c0 .45.54.67.85.35L6.29 7.7 11 12.4V19c0 .55.45 1 1 1s1-.45 1-1v-7c0-.26-.11-.52-.29-.71l-5-5.01 1.44-1.44c.31-.3.09-.84-.36-.84`}),`CallSplitRounded`),ta=H((0,Q.jsx)(`path`,{d:`m14.06 9.02.92.92L5.92 19H5v-.92zM17.66 3c-.25 0-.51.1-.7.29l-1.83 1.83 3.75 3.75 1.83-1.83c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.2-.2-.45-.29-.71-.29m-3.6 3.19L3 17.25V21h3.75L17.81 9.94z`}),`EditOutlined`),na=H((0,Q.jsx)(`path`,{d:`M8 2c-1.1 0-2 .9-2 2v3.17c0 .53.21 1.04.59 1.42L10 12l-3.42 3.42c-.37.38-.58.89-.58 1.42V20c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2v-3.16c0-.53-.21-1.04-.58-1.41L14 12l3.41-3.4c.38-.38.59-.89.59-1.42V4c0-1.1-.9-2-2-2zm8 14.5V19c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1v-2.5l4-4zm-4-5-4-4V5c0-.55.45-1 1-1h6c.55 0 1 .45 1 1v2.5z`}),`HourglassEmptyRounded`),ra=H((0,Q.jsx)(`path`,{d:`M13 11h-2v3H8v2h3v3h2v-3h3v-2h-3zm1-9H6c-1.1 0-2 .9-2 2v16c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8zm4 18H6V4h7v5h5z`}),`NoteAddOutlined`),ia=H((0,Q.jsx)(`path`,{d:`M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m-1 17.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L9 15v1c0 1.1.9 2 2 2zm6.9-2.54c-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H8v-2h2c.55 0 1-.45 1-1V7h2c1.1 0 2-.9 2-2v-.41c2.93 1.19 5 4.06 5 7.41 0 2.08-.8 3.97-2.1 5.39`}),`PublicRounded`),aa=H((0,Q.jsx)(`path`,{d:`M2 6c.55 0 1-.45 1-1V4c0-.55.45-1 1-1h1c.55 0 1-.45 1-1s-.45-1-1-1H4C2.34 1 1 2.34 1 4v1c0 .55.45 1 1 1m3 15H4c-.55 0-1-.45-1-1v-1c0-.55-.45-1-1-1s-1 .45-1 1v1c0 1.66 1.34 3 3 3h1c.55 0 1-.45 1-1s-.45-1-1-1M20 1h-1c-.55 0-1 .45-1 1s.45 1 1 1h1c.55 0 1 .45 1 1v1c0 .55.45 1 1 1s1-.45 1-1V4c0-1.66-1.34-3-3-3m2 17c-.55 0-1 .45-1 1v1c0 .55-.45 1-1 1h-1c-.55 0-1 .45-1 1s.45 1 1 1h1c1.66 0 3-1.34 3-3v-1c0-.55-.45-1-1-1m-3-3.13V9.13c0-.72-.38-1.38-1-1.73l-5-2.88c-.31-.18-.65-.27-1-.27s-.69.09-1 .27L6 7.39c-.62.36-1 1.02-1 1.74v5.74c0 .72.38 1.38 1 1.73l5 2.88c.31.18.65.27 1 .27s.69-.09 1-.27l5-2.88c.62-.35 1-1.01 1-1.73m-8 2.3-4-2.3v-4.63l4 2.33zm1-6.33L8.04 8.53 12 6.25l3.96 2.28zm5 4.03-4 2.3v-4.6l4-2.33z`}),`ViewInArRounded`),oa=`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,sa={read:M,write:ra,edit:ta,command:v,search:s,list:F,"web-search":l,"web-fetch":A,subagent:Zi,network:ia,docker:aa,git:ea,plan:$i,other:Qi},ca={read:[`Đọc`,`Read`],write:[`Tạo`,`Write`],edit:[`Sửa`,`Edit`],command:[`Chạy`,`Run`],search:[`Tìm`,`Search`],list:[`Xem thư mục`,`List`],"web-search":[`Tìm web`,`Web search`],"web-fetch":[`Đọc trang`,`Fetch page`],subagent:[`Subagent`,`Subagent`],network:[`Chạy có mạng`,`Run with network`],docker:[`Chạy với Docker`,`Run with Docker`],git:[`Git`,`Git`],plan:[`Plan`,`Plan`],other:[`Công cụ`,`Tool`]},la={read:`read`,write:`write`,edit:`edit`,apply_patch:`edit`,bash:`command`,run_experiment:`command`,grep:`search`,find:`search`,ls:`list`,web_search:`web-search`,web_fetch:`web-fetch`,delegate:`subagent`,subagent:`subagent`,run_with_network:`network`,run_with_docker:`docker`,fetch_origin:`git`,update_plan:`plan`};function ua(e){return la[e.toLowerCase()]??`other`}function da({preview:e}){return(0,Q.jsx)(V,{component:`pre`,sx:{m:0,fontFamily:oa,fontSize:12,lineHeight:1.55,overflowX:`auto`},children:e.split(`
12
+ `).map((e,t)=>{let n=e[0],r=n===`+`?`success`:n===`-`?`error`:null;return(0,Q.jsx)(V,{component:`div`,sx:{px:1,whiteSpace:`pre`,...r?Et(r):{color:e===`@@`?`text.disabled`:`text.secondary`},bgcolor:r?`rgba(var(--piagent-palette-${r}-mainChannel) / .12)`:`transparent`},children:e===`@@`?`⋯`:e||` `},t)})})}function fa({tool:e,locale:t,live:n,waiting:r}){let i=e.summary??{kind:`other`,target:null,detail:null},a=`change`in e?e.change:void 0,s=`result`in e?e.result:void 0,c=e.state===`failed`||s?.isError===!0,l=`failure`in e&&e.failure?{detail:e.failure,copy:Zn(e.failure.reasonCode,e.failure.code,t)}:null,u=n?e.state===`running`:e.state===`requested`,[d,f]=(0,$.useState)(()=>c||(i.kind===`edit`||i.kind===`write`)&&!!a?.preview),p=!!(a?.preview||s?.text||l?.copy||i.detail&&i.kind!==`read`),m=r?na:sa[i.kind],h=ca[i.kind][t===`vi`?0:1],g=i.kind===`other`?e.toolName:h;return(0,Q.jsxs)(V,{sx:{border:1,borderColor:c?`error.main`:`divider`,borderRadius:1,bgcolor:`background.paper`,overflow:`hidden`},children:[(0,Q.jsxs)(y,{component:`div`,disabled:!p,onClick:()=>f(e=>!e),"aria-expanded":p?d:void 0,sx:{width:`100%`,display:`flex`,alignItems:`center`,gap:1,px:1.25,py:.85,textAlign:`left`,justifyContent:`flex-start`},children:[(0,Q.jsx)(m,{sx:{fontSize:17,color:c?`error.main`:`text.secondary`,flexShrink:0}}),(0,Q.jsx)(o,{variant:`body2`,sx:{fontWeight:600,flexShrink:0},children:g}),i.target&&(0,Q.jsx)(o,{variant:`body2`,noWrap:!0,title:i.target,sx:{fontFamily:oa,fontSize:12.5,color:`text.secondary`,minWidth:0,flex:1},children:i.target}),!i.target&&(0,Q.jsx)(V,{sx:{flex:1}}),i.kind===`read`&&i.detail&&(0,Q.jsx)(o,{variant:`caption`,color:`text.disabled`,sx:{flexShrink:0},children:X(t,`dòng ${i.detail}`,`lines ${i.detail}`)}),a&&(a.added>0||a.removed>0)&&(0,Q.jsxs)(o,{variant:`caption`,sx:{fontFamily:oa,flexShrink:0},children:[a.added>0&&(0,Q.jsxs)(V,{component:`span`,sx:Et(`success`),children:[`+`,a.added,` `]}),a.removed>0&&(0,Q.jsxs)(V,{component:`span`,sx:Et(`error`),children:[`−`,a.removed]})]}),c&&!u&&(0,Q.jsx)(o,{variant:`caption`,sx:{flexShrink:0,fontWeight:600,...Et(`error`)},children:X(t,`Lỗi`,`Failed`)}),u?(0,Q.jsx)(xe,{size:14,thickness:5,"aria-label":X(t,`Đang chạy`,`Running`)}):c?(0,Q.jsx)(L,{sx:{fontSize:16,color:`error.main`},"aria-hidden":`true`}):(0,Q.jsx)(me,{sx:{fontSize:16,color:`success.main`},"aria-label":X(t,`Xong`,`Done`)}),p&&(0,Q.jsx)(ke,{sx:{fontSize:18,color:`text.disabled`,transition:`transform .15s`,transform:d?`rotate(180deg)`:`none`}})]}),i.target&&[`read`,`write`,`edit`].includes(i.kind)&&(0,Q.jsx)(Ut,{path:i.target,line:Number.parseInt(i.detail??`1`,10)||1}),(0,Q.jsx)(Xn,{in:d&&p,unmountOnExit:!0,children:(0,Q.jsxs)(V,{sx:{borderTop:1,borderColor:`divider`,bgcolor:`action.hover`,maxHeight:360,overflow:`auto`},children:[i.detail&&i.kind!==`read`&&(0,Q.jsx)(o,{variant:`body2`,color:`text.secondary`,sx:{px:1.25,py:.75,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,...i.kind===`command`?{fontFamily:oa,fontSize:12}:{}},children:i.detail}),l?.copy&&(0,Q.jsxs)(V,{sx:{px:1.25,py:.75},children:[(0,Q.jsxs)(o,{variant:`body2`,sx:{fontWeight:650,...Et(`error`)},children:[er(l.detail.role,t),` `,X(t,`lỗi`,`failed`),` · `,l.copy.title]}),(0,Q.jsx)(o,{variant:`body2`,color:`text.secondary`,children:l.copy.text}),(0,Q.jsxs)(o,{variant:`caption`,color:`text.secondary`,sx:{fontFamily:oa,overflowWrap:`anywhere`},title:l.detail.requestRef??void 0,children:[X(t,`Mã`,`Code`),`: `,l.detail.code,l.detail.requestRef?` · request ${l.detail.requestRef.slice(0,8)}`:``]})]}),a?.preview&&(0,Q.jsx)(V,{sx:{py:.5},children:(0,Q.jsx)(da,{preview:a.preview})}),s?.text&&!l?.copy&&(0,Q.jsx)(V,{component:`pre`,sx:{m:0,px:1.25,py:.75,fontFamily:oa,fontSize:12,lineHeight:1.55,whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,color:s.isError?`error.main`:`text.secondary`},children:s.text}),(a?.truncated||s?.truncated)&&(0,Q.jsx)(o,{variant:`caption`,color:`text.disabled`,sx:{display:`block`,px:1.25,pb:.75},children:X(t,`Đã rút gọn`,`Truncated`)})]})})]})}var pa=null,ma=null,ha=()=>pa??=Pe(()=>import(`./MarkdownMessage-zw5RxDmZ.js`).then(e=>(ma=e.MarkdownMessage,e)),__vite__mapDeps([17,1,2,3,13,12,5,18,4,16])),ga=(0,$.lazy)(async()=>({default:(await ha()).MarkdownMessage}));function _a({children:e}){let t=ma;return t?(0,Q.jsx)(t,{children:e}):(0,Q.jsx)($.Suspense,{fallback:(0,Q.jsx)(o,{sx:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,lineHeight:1.75},children:e}),children:(0,Q.jsx)(ga,{children:e})})}var va=(0,$.memo)(function({text:e}){return(0,Q.jsx)(_a,{children:e})});function ya({text:e}){let[t,n]=gi(e);return(0,Q.jsxs)(Q.Fragment,{children:[t&&(0,Q.jsx)(va,{text:t}),n&&(0,Q.jsx)(_a,{children:n})]})}function ba({attachments:e,images:t,locale:n}){if(!e.length)return null;let r=0;return(0,Q.jsx)(R,{spacing:.75,sx:{mb:1},"aria-label":X(n,`File đã gửi`,`Sent files`),children:e.map((e,i)=>{let a=`sourceBytes`in e,s=a?tn(e,n):`${e.kind===`document`?X(n,`Tài liệu`,`Document`):e.kind===`image`?X(n,`Ảnh`,`Image`):`File`}${e.truncated?` · ${X(n,`đã cắt bớt`,`truncated`)}`:``}`,c=(0,Q.jsxs)(P,{variant:`outlined`,sx:{display:`flex`,alignItems:`center`,gap:1.1,minWidth:220,maxWidth:440,px:1.2,py:1,borderRadius:1,bgcolor:`background.paper`},children:[e.kind===`image`?(0,Q.jsx)(Xi,{color:`action`}):(0,Q.jsx)(M,{color:`action`}),(0,Q.jsxs)(V,{sx:{minWidth:0},children:[(0,Q.jsx)(o,{variant:`body2`,noWrap:!0,sx:{fontWeight:650},children:e.displayName}),(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,children:s})]})]},`${e.displayName}:${i}`);if(e.kind!==`image`)return c;let l=a?{staged:e.attachmentRef}:t?{...t,index:r}:null;return r+=1,(0,Q.jsx)(qt,{name:e.displayName,source:l,locale:n,fallback:c},`${e.displayName}:${i}`)})})}var xa=new Set([`assistant-response-failed`,`operation-failed`]);function Sa(e,t){switch(e){case`provider-auth-expired`:return X(t,`Phiên đăng nhập model đã hết hạn. Mở Cài đặt → Nhà cung cấp & model để kết nối lại.`,`The model sign-in expired. Open Settings → Providers & models to reconnect.`);case`provider-auth-required`:return X(t,`Model cần đăng nhập lại. Mở Cài đặt → Nhà cung cấp & model.`,`The model needs to sign in again. Open Settings → Providers & models.`);case`provider-rate-limited`:return X(t,`Model đang bị giới hạn lượt gọi hoặc đã hết hạn mức. Thử lại sau.`,`The model is rate limited or out of quota. Try again later.`);case`provider-unavailable`:return X(t,`Model hoặc máy chủ trung gian đang không phục vụ yêu cầu này. Thử lại; nếu lỗi lặp lại, kiểm tra model đang dùng.`,`The model or its gateway did not serve this request. Retry; if it repeats, check the model in use.`);case`assistant-output-incomplete`:return X(t,`Câu trả lời dừng giữa chừng vì chạm giới hạn độ dài. Gửi “tiếp tục” để model viết tiếp.`,`The answer stopped at the length limit. Send “continue” to resume.`);default:return X(t,`Model trả lỗi và chưa có câu trả lời. Gửi lại; nếu lỗi lặp lại, kiểm tra model đang dùng.`,`The model returned an error without an answer. Send again; if it repeats, check the model in use.`)}}function Ca({code:e,detail:t,locale:r,onContinue:i}){let a=Zn(e,t?.code??null,r),s=i&&$n(e)?(0,Q.jsx)(z,{color:`inherit`,size:`small`,onClick:i,children:X(r,`Tiếp tục`,`Continue`)}):void 0;return a?(0,Q.jsxs)(h,{severity:`error`,variant:`outlined`,icon:(0,Q.jsx)(w,{}),action:s,sx:{alignSelf:`stretch`},children:[(0,Q.jsxs)(n,{sx:{fontSize:`inherit`,fontWeight:650,mb:.25},children:[er(t?.role??`main`,r),` `,X(r,`lỗi`,`failed`),` · `,a.title]}),a.text,t&&(0,Q.jsxs)(o,{variant:`caption`,component:`div`,color:`text.secondary`,sx:{mt:.5,fontFamily:`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,overflowWrap:`anywhere`},title:t.requestRef??void 0,children:[X(r,`Mã`,`Code`),`: `,t.code,t.requestRef?` · request ${t.requestRef.slice(0,8)}`:``]})]}):(0,Q.jsx)(h,{severity:`error`,variant:`outlined`,icon:(0,Q.jsx)(w,{}),action:s,sx:{alignSelf:`stretch`},children:Sa(e,r)})}function wa({text:e,attachments:t,images:n,note:r,locale:i}){return(0,Q.jsxs)(V,{sx:{alignSelf:`flex-end`,maxWidth:`82%`,bgcolor:`action.selected`,borderRadius:1,px:2,py:1.4},children:[(0,Q.jsx)(ba,{attachments:t,images:n,locale:i}),e&&(0,Q.jsx)(o,{sx:{whiteSpace:`pre-wrap`,overflowWrap:`anywhere`,lineHeight:1.7},children:(0,Q.jsx)(Ht,{children:e})}),r&&(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,children:r})]})}function Ta({children:e}){return(0,Q.jsxs)(V,{sx:{display:`flex`,gap:1.5,alignItems:`flex-start`},children:[(0,Q.jsx)(ut,{size:26}),(0,Q.jsxs)(R,{spacing:1,sx:{minWidth:0,flex:1},children:[(0,Q.jsx)(o,{sx:{fontWeight:600},children:`Piagent`}),e]})]})}function Ea(e,t){return e.content.redacted?X(t,`Đã ẩn dữ liệu nhạy cảm`,`Sensitive data hidden`):e.content.truncated?X(t,`Nội dung đã rút gọn`,`Content truncated`):null}function Da({turn:e,locale:t}){let n=bi(e),r=[`${e.requests} request`];e.tokens&&r.push(`${Ci(e.tokens)} token`),n!==null&&n>0&&r.push(n<60?`${n}s`:`${Math.floor(n/60)}m ${n%60}s`);let i=xi(e);return i!==null&&r.push(`${i} tok/s`),e.model&&r.push(e.model),(0,Q.jsx)(o,{variant:`caption`,color:`text.disabled`,title:X(t,`Request model, token, thời gian và tốc độ sinh token (token đầu ra mỗi giây, tính cả thời gian chờ) của lượt này`,`Model requests, tokens, time and output speed (output tokens per second, waiting included) of this turn`),children:r.join(` · `)})}var Oa=(0,$.memo)(function({turn:e,sessionRef:t,locale:n,onContinue:r}){let i=!!r&&!e.answer&&!e.failure&&!e.end,a=e.reviewing&&!e.end,s=[...e.steps].reverse().find(e=>e.kind===`note`&&e.draft),c=e.steps.length>0||e.answer||e.failure||i||e.process||e.end;return(0,Q.jsxs)(R,{spacing:1.5,children:[(0,Q.jsx)(wa,{text:e.user.content.text,attachments:e.user.attachments??[],note:Ea(e.user,n),locale:n,images:t?{sessionRef:t,messageRef:e.user.messageRef}:void 0}),c&&(0,Q.jsxs)(Ta,{children:[e.steps.map(t=>t.kind===`tool`?(0,Q.jsx)(fa,{tool:t.tool,locale:n},t.key):t.kind===`process`?(0,Q.jsx)(wt,{process:t.process,locale:n},t.key):(0,Q.jsx)(V,{sx:{color:`text.secondary`,fontSize:`.875rem`,"& .MuiTypography-root":{fontSize:`inherit`},...t.draft?{borderLeft:2,borderColor:`divider`,pl:1.5}:{}},children:t.draft?(0,Q.jsxs)(`details`,{open:!e.answer&&t===s,children:[(0,Q.jsx)(`summary`,{style:{cursor:`pointer`},children:(0,Q.jsx)(o,{variant:`caption`,component:`span`,color:`text.disabled`,sx:{fontWeight:600},children:t.beforeReview?X(n,`Bản trước review · chưa phải kết quả cuối`,`Before review · not the final result`):X(n,`Trả lời giữa chừng · harness yêu cầu làm tiếp`,`Interim answer · the harness asked for more`)})}),(0,Q.jsx)(_a,{children:t.text})]}):(0,Q.jsx)(_a,{children:t.text})},t.key)),e.failure&&(0,Q.jsx)(Ca,{code:e.failure,detail:e.failureDetail,locale:n,onContinue:r}),i&&(0,Q.jsx)(h,{severity:`info`,variant:`outlined`,sx:{alignSelf:`stretch`},action:(0,Q.jsx)(z,{color:`inherit`,size:`small`,onClick:r,children:X(n,`Tiếp tục`,`Continue`)}),children:X(n,`Lượt này chưa có câu trả lời: nó đã bị dừng, hoặc ứng dụng hay máy tắt khi đang chạy. Các bước đã làm vẫn được giữ; bấm Tiếp tục để làm tiếp.`,`This turn has no answer: it was stopped, or the app or the machine went down while it ran. Its steps are kept; press Continue to go on.`)}),e.answer&&(0,Q.jsxs)(V,{children:[(a||s)&&(0,Q.jsx)(o,{variant:`caption`,component:`div`,color:`text.disabled`,sx:{mb:.5,fontWeight:600},children:a?X(n,`Bản nháp · reviewer đang kiểm tra, kết quả có thể còn thay đổi`,`Draft · the reviewer is checking it, the result may still change`):e.process?.reviewed?X(n,`Kết quả cuối · đã qua review`,`Final result · reviewed`):X(n,`Kết quả cuối`,`Final result`)}),(0,Q.jsx)(_a,{children:e.answer})]}),e.process&&(0,Q.jsx)(wt,{process:e.process,locale:n}),e.end&&(0,Q.jsx)(Ct,{end:e.end,locale:n,onContinue:e.failure?void 0:r}),e.requests>0&&(0,Q.jsx)(Da,{turn:e,locale:n})]}),(0,Q.jsx)(Ji,{turnRef:e.user.messageRef})]})});function ka(e,t){return e===`compaction`?X(t,`Tóm tắt phần cũ của cuộc trò chuyện`,`Summarise the older part of the conversation`):e===`capacity-wait`?X(t,`Chờ tài khoản công ty rảnh (Studio đang bận, sẽ tự gửi lại)`,`Wait for a free company account (Studio is busy; it is sent again by itself)`):e}function Aa({user:e,attachments:t,activities:n,assistant:r,running:i,failure:a,status:o,locale:s}){return(0,Q.jsxs)(R,{spacing:1.5,children:[e&&(0,Q.jsx)(wa,{text:e,attachments:t,locale:s}),(0,Q.jsxs)(Ta,{children:[n.map(e=>(0,Q.jsx)(fa,{live:!0,locale:s,waiting:e.toolLabel===`capacity-wait`,tool:{toolName:ka(e.toolLabel,s),state:e.state,summary:{kind:ua(e.toolLabel),target:e.fileLabel??null,detail:null}}},e.toolCallRef)),a&&(0,Q.jsx)(Ca,{code:a,locale:s}),r&&(0,Q.jsx)(V,{className:i?`streaming-answer`:void 0,children:i?(0,Q.jsx)(ya,{text:r}):(0,Q.jsx)(_a,{children:r})}),i&&o]})]})}function ja(e){let t=(0,$.useRef)(null),[n,r]=(0,$.useState)(null);return(0,$.useEffect)(()=>{if(!e){t.current=null,r(null);return}t.current??={at:Date.now(),from:e.length},r(Si(e.length-t.current.from,Date.now()-t.current.at))},[e]),n}function Ma({live:e,locale:t,helpers:n,onOpenActivity:r}){let[i,a]=(0,$.useState)(()=>Date.now());(0,$.useEffect)(()=>{let e=window.setInterval(()=>a(Date.now()),1e4);return()=>window.clearInterval(e)},[]);let s=mi(e,t,i,n),c=ja(e.assistant??``),l=e.activities.some(e=>e.state===`running`&&!e.agent)||!!e.assistant;return(0,Q.jsxs)(R,{direction:`row`,spacing:1.25,role:`status`,"aria-live":`polite`,sx:{alignItems:`center`,color:`text.secondary`,py:.5,minHeight:36},children:[(0,Q.jsx)(V,{sx:{width:18,display:`grid`,placeItems:`center`,flexShrink:0},children:l?(0,Q.jsx)(V,{sx:{width:6,height:6,borderRadius:`50%`,bgcolor:`primary.main`,opacity:.7}}):(0,Q.jsx)(xe,{size:16,thickness:4.5})}),(0,Q.jsxs)(V,{sx:{minWidth:0},children:[(0,Q.jsx)(o,{variant:`body2`,sx:{fontWeight:600},children:s.label}),(0,Q.jsxs)(o,{variant:`caption`,color:`text.disabled`,children:[s.detail,c!==null&&` · ≈ ${c} tok/s`]})]}),r&&(0,Q.jsx)(z,{size:`small`,variant:`text`,onClick:r,sx:{ml:`auto !important`},children:X(t,`Xem Activity`,`View Activity`)})]})}var Na=new Map,Pa=96,Fa=()=>document.documentElement.scrollHeight-window.innerHeight,Ia=()=>Fa()-window.scrollY<=Pa,La=1500,Ra=110;function za(e,t){let n=(0,$.useRef)(null),r=(0,$.useRef)(!1),i=(0,$.useRef)(!0),a=(0,$.useRef)(null),o=(0,$.useRef)(!1),s=()=>{a.current=null,n.current&&(n.current.style.overflowAnchor=``)},c=()=>{let e=a.current;if(!e)return;if(Date.now()>e.until){s();return}let t=n.current?.querySelector(`[data-turn="${CSS.escape(e.key)}"]`);if(!t)return;let r=t.getBoundingClientRect().top-e.top;Math.abs(r)>=1&&window.scrollBy(0,r)};return(0,$.useLayoutEffect)(()=>{if(!t||r.current)return;r.current=!0;let n=Na.get(e)??`end`;i.current=n===`end`,window.scrollTo(0,n===`end`?Fa():Math.min(n,Fa()))},[t,e]),(0,$.useEffect)(()=>{let t=window.scrollY,s=()=>{if(!r.current)return;window.scrollY<t-2&&(o.current=!0),t=window.scrollY;let s=a.current;if(s){let e=n.current?.querySelector(`[data-turn="${CSS.escape(s.key)}"]`);e&&(s.top=e.getBoundingClientRect().top)}i.current=Ia(),Na.set(e,i.current?`end`:window.scrollY)};window.addEventListener(`scroll`,s,{passive:!0});let l=n.current,u=typeof ResizeObserver>`u`||!l?null:new ResizeObserver(()=>{r.current&&(a.current?c():i.current&&window.scrollTo(0,Fa()))});return l&&u?.observe(l),()=>{window.removeEventListener(`scroll`,s),u?.disconnect()}},[e]),{content:n,hold:()=>{if(window.setTimeout(c,1550),a.current){a.current.until=Date.now()+La;return}let e=[...n.current?.querySelectorAll(`[data-turn]`)??[]],t=e.find(e=>e.getBoundingClientRect().bottom>Ra)??e[0];!t?.dataset.turn||!n.current||(n.current.style.overflowAnchor=`none`,a.current={key:t.dataset.turn,top:t.getBoundingClientRect().top,until:Date.now()+La})},reapply:c,scrolledUp:o,follow:()=>{s(),i.current=!0,o.current=!1}}}function Ba({turns:e=2,label:t}){return(0,Q.jsx)(R,{spacing:3,role:`status`,"aria-label":t,sx:{py:1},children:Array.from({length:e},(e,t)=>(0,Q.jsxs)(R,{spacing:1.5,children:[(0,Q.jsx)(ue,{variant:`rounded`,animation:`wave`,sx:{alignSelf:`flex-end`,width:`46%`,height:44,borderRadius:2}}),(0,Q.jsxs)(R,{direction:`row`,spacing:1.5,children:[(0,Q.jsx)(ue,{variant:`rounded`,width:26,height:26}),(0,Q.jsxs)(R,{spacing:1,sx:{flex:1},children:[(0,Q.jsx)(ue,{width:`30%`}),(0,Q.jsx)(ue,{width:`92%`}),(0,Q.jsx)(ue,{width:`78%`})]})]})]},t))})}function Va({sessionRef:e,sessionRevision:t,live:n,helpers:r,approvals:i,locale:a,onOpenActivity:s,onContinue:c,reload:l=0}){let[u,d]=(0,$.useState)(),[f,p]=(0,$.useState)(!0),[m,g]=(0,$.useState)(!1),[_,v]=(0,$.useState)(0),[y,b]=(0,$.useState)(!1),[x,S]=(0,$.useState)(!1),[C,T]=(0,$.useState)(!1),[E,D]=(0,$.useState)(null);(0,$.useEffect)(()=>{ha()},[]);let O=sn(e,t,n),{completionKey:k,user:A,assistant:j,operationRef:M,messageRequestId:N,startedAt:P}=O;(0,$.useEffect)(()=>{let t=new AbortController;p(!0),S(!1),D(null);let n=window.setTimeout(()=>{Promise.all([Ge(e,null,50,t.signal),ha().catch(()=>void 0)]).then(([e])=>{d(e),b(!1),k&&Xt(e.items,A,j,{operationRef:M,messageRequestId:N,startedAt:P})&&D(k)}).catch(()=>{t.signal.aborted||S(!0)}).finally(()=>{t.signal.aborted||p(!1)})},k?100:0);return()=>{window.clearTimeout(n),t.abort()}},[O.key,l,_]);let F=u?.state===`ready`?u.items:[],I=(0,$.useMemo)(()=>yi(F),[F]),L=(0,$.useMemo)(()=>!!(n?.user&&nn(F,n.user,{operationRef:n.operationRef,messageRequestId:n.messageRequestId,startedAt:n.startedAt})),[F,n?.user,n?.operationRef,n?.messageRequestId,n?.startedAt]),ee=!!(n&&!L&&(!n.complete||E!==k)),te=!!(n&&L&&!n.complete&&!n.error),ne=(0,$.useMemo)(()=>!!(n?.user&&an(F,n.user,{operationRef:n.operationRef,messageRequestId:n.messageRequestId,startedAt:n.startedAt})),[F,n?.user,n?.operationRef,n?.messageRequestId,n?.startedAt]),{content:B,hold:H,reapply:U,scrolledUp:W,follow:re}=za(e,!!u||x),G=(0,$.useRef)(!1),K=(0,$.useRef)(u);K.current=u;let ie=async()=>{let t=K.current,n=t?.page.nextBeforeCursor;if(!(!t?.page.hasOlder||!n||G.current)){W.current=!1,G.current=!0,H(),g(!0),T(!1);try{let r=await Ge(e,n,t.page.limit);H();let i=K.current;if(!i){K.current=r,d(r);return}let a=un(i.items,r.items);new Set([...i.items,...r.items].map(e=>e.messageRef)).size>a.length&&b(!0);let o={...i,items:a,page:r.page};K.current=o,d(o)}catch{T(!0)}finally{G.current=!1,g(!1)}}};(0,$.useLayoutEffect)(()=>{U()},[F.length,m]);let q=(0,$.useRef)(null),ae=(0,$.useRef)(()=>{}),J=!!u?.page.hasOlder;ae.current=()=>{if(!W.current||C||G.current)return;let e=q.current?.getBoundingClientRect();e&&e.bottom>=-900&&e.top<=window.innerHeight&&ie()},(0,$.useEffect)(()=>{let e=q.current;if(!e||!J)return;let t=0,n=()=>{t||=window.requestAnimationFrame(()=>{t=0,ae.current()})},r=typeof IntersectionObserver>`u`?null:new IntersectionObserver(e=>{e.some(e=>e.isIntersecting)&&n()},{rootMargin:`900px 0px 0px 0px`});return r?.observe(e),window.addEventListener(`scroll`,n,{passive:!0}),()=>{r?.disconnect(),window.removeEventListener(`scroll`,n),window.cancelAnimationFrame(t)}},[e,J]);let oe=n?Qt(n.assistant||``):null;return(0,Q.jsx)(Yi,{sessionRef:e,refresh:`${O.key}:${l}`,running:!!n&&!n.complete&&!n.error,locale:a,children:(0,Q.jsxs)(R,{ref:B,spacing:3,children:[u?.page.hasOlder&&(0,Q.jsx)(V,{ref:q,"data-history-sentinel":!0,children:m?(0,Q.jsx)(Ba,{label:X(a,`Đang tải tin cũ hơn`,`Loading older messages`)}):(0,Q.jsx)(V,{sx:{textAlign:`center`},children:(0,Q.jsx)(z,{size:`small`,variant:`text`,color:`inherit`,startIcon:(0,Q.jsx)(fe,{}),onClick:()=>void ie(),sx:{color:C?`warning.main`:`text.secondary`},children:C?X(a,`Chưa tải được tin cũ · thử lại`,`Older messages did not load · retry`):X(a,`Tải tin cũ hơn`,`Load older messages`)})})}),u?.state===`ready`&&!u.page.hasOlder&&I.length>3&&(0,Q.jsx)(o,{variant:`caption`,color:`text.disabled`,sx:{textAlign:`center`,display:`block`},children:X(a,`Đầu cuộc trò chuyện`,`Start of the conversation`)}),f&&!u&&(0,Q.jsx)(Ba,{turns:3,label:X(a,`Đang tải cuộc trò chuyện`,`Loading the conversation`)}),x&&!u&&(0,Q.jsx)(h,{severity:`warning`,icon:(0,Q.jsx)(w,{}),children:X(a,`Chưa tải được lịch sử cuộc trò chuyện. Thử lại bằng nút làm mới.`,`Session history could not be loaded. You can retry with Refresh.`)}),I.map((t,n)=>(0,Q.jsx)(V,{"data-turn":t.key,children:(0,Q.jsx)(Oa,{turn:t,sessionRef:e,locale:a,onContinue:n===I.length-1&&!ee&&!te&&!i?.pending.length?c:void 0})},t.key)),y&&(0,Q.jsx)(V,{sx:{textAlign:`center`},children:(0,Q.jsx)(z,{size:`small`,variant:`outlined`,onClick:()=>{re(),v(e=>e+1)},children:X(a,`Tin mới hơn đã ẩn · về tin mới nhất`,`Newer messages are hidden · back to the newest`)})}),ee&&n&&(0,Q.jsx)(Aa,{user:n.user&&!ne?n.user:null,attachments:n.attachments,activities:n.activities.filter(e=>!e.agent),assistant:n.error?null:oe,running:!n.complete&&!n.error,failure:n.complete&&n.error&&xa.has(n.error)?n.error:null,locale:a,status:(0,Q.jsx)(Ma,{live:n,locale:a,helpers:r,onOpenActivity:s})}),te&&n&&(0,Q.jsx)(Ta,{children:(0,Q.jsx)(Ma,{live:n,locale:a,helpers:r,onOpenActivity:s})}),(0,Q.jsx)(Wr,{sessionRef:e,waiting:xt(n),running:!!n&&!n.complete,approvalRefs:i?.pending.map(e=>e.approvalRef)??[]})]})})}var Ha=9e3,Ua=4,Wa={done:[`Xong`,`Done`,`Agent đã trả lời xong.`,`The agent finished its answer.`],failed:[`Lượt bị lỗi`,`Turn failed`,`Mở để xem lỗi và gửi “tiếp tục”.`,`Open it to see the error and continue.`],stopped:[`Đã dừng`,`Stopped`,`Lượt làm việc đã dừng giữa chừng.`,`The turn stopped midway.`],question:[`Cần bạn trả lời`,`Needs your answer`,`Main agent đang chờ bạn chọn phương án.`,`The main agent is waiting for your choice.`],approval:[`Cần bạn duyệt`,`Needs your approval`,`Main agent xin chạy một lệnh và đang chờ bạn duyệt.`,`The main agent asked to run a command and is waiting.`]},Ga={done:`success`,failed:`error`,stopped:`neutral`,question:`warning`,approval:`warning`};function Ka({sessions:e,live:t,selectedRef:n,onOpen:r,locale:i}){let a=(0,$.useRef)(null),[o,s]=(0,$.useState)([]),[c,l]=(0,$.useState)(()=>new Set);(0,$.useEffect)(()=>{let r=yt(e,t);if(a.current){let i=document.visibilityState===`visible`,o=Tt(a.current,r,e,t).filter(e=>!(i&&e.sessionRef===n));if(o.length){s(e=>[...o,...e.filter(e=>!o.some(t=>t.sessionRef===e.sessionRef))].slice(0,12));let e=o.filter(e=>[`done`,`failed`,`stopped`].includes(e.kind)).map(e=>e.sessionRef);e.length&&l(t=>new Set([...t,...e]))}}a.current=r,s(e=>{let t=e.filter(e=>![`question`,`approval`].includes(e.kind)||r[e.sessionRef]?.need===e.kind);return t.length===e.length?e:t})},[e,t,n]),(0,$.useEffect)(()=>{n&&(l(e=>{if(!e.has(n))return e;let t=new Set(e);return t.delete(n),t}),s(e=>e.filter(e=>e.sessionRef!==n)))},[n]);let u=e.filter(e=>!e.archived&&zt(e,t[e.sessionRef])).length;(0,$.useEffect)(()=>{let e=document.title.replace(/^\(\d+\) /,``);document.title=u?`(${u}) ${e}`:e},[u]);let d=e=>s(t=>t.filter(t=>t.id!==e));return{unseen:c,view:(0,Q.jsx)(qa,{toasts:o.slice(0,Ua),more:Math.max(0,o.length-Ua),locale:i,onClose:d,onOpen:e=>{d(e.id),r(e.sessionRef)}})}}function qa({toasts:e,more:t,locale:n,onClose:r,onOpen:i}){return(0,Q.jsxs)(`section`,{className:`attention-toasts`,"aria-label":X(n,`Thông báo cuộc trò chuyện`,`Chat notifications`),"aria-live":`polite`,children:[e.map(e=>(0,Q.jsx)(Ja,{event:e,locale:n,onClose:()=>r(e.id),onOpen:()=>i(e)},e.id)),t>0&&(0,Q.jsx)(`p`,{className:`attention-more`,children:X(n,`và ${t} thông báo khác`,`and ${t} more`)})]})}function Ja({event:e,locale:t,onClose:n,onOpen:r}){let i=e.kind===`question`||e.kind===`approval`,[a,o,s,c]=Wa[e.kind];return(0,$.useEffect)(()=>{if(i)return;let e=window.setTimeout(n,Ha);return()=>window.clearTimeout(e)},[i]),(0,Q.jsxs)(`article`,{className:`attention-toast tone-${Ga[e.kind]}`,role:i?`alert`:`status`,children:[(0,Q.jsx)(`span`,{className:`attention-toast-mark`,"aria-hidden":`true`}),(0,Q.jsxs)(`div`,{className:`attention-toast-body`,children:[(0,Q.jsxs)(`strong`,{children:[X(t,a,o),` · `,(0,Q.jsx)(`span`,{className:`attention-toast-title`,children:e.title})]}),(0,Q.jsx)(`small`,{children:X(t,s,c)})]}),(0,Q.jsxs)(`div`,{className:`attention-toast-actions`,children:[(0,Q.jsx)(`button`,{type:`button`,className:`attention-open`,onClick:r,children:X(t,`Mở`,`Open`)}),(0,Q.jsx)(`button`,{type:`button`,className:`attention-close`,"aria-label":X(t,`Đóng thông báo`,`Close notification`),onClick:n,children:`×`})]})]})}var Ya=H((0,Q.jsx)(`path`,{d:`M18 19H6c-.55 0-1-.45-1-1V6c0-.55.45-1 1-1h12c.55 0 1 .45 1 1v12c0 .55-.45 1-1 1m1-16H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2`}),`CheckBoxOutlineBlankRounded`),Xa=H((0,Q.jsx)(`path`,{d:`M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2m-8.29 13.29c-.39.39-1.02.39-1.41 0L5.71 12.7a.996.996 0 0 1 0-1.41c.39-.39 1.02-.39 1.41 0L10 14.17l6.88-6.88c.39-.39 1.02-.39 1.41 0s.39 1.02 0 1.41z`}),`CheckBoxRounded`),Za=H((0,Q.jsx)(`path`,{d:`m10.8 15.9 4.67-3.5c.27-.2.27-.6 0-.8L10.8 8.1c-.33-.25-.8-.01-.8.4v7c0 .41.47.65.8.4M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8`}),`PlayCircleOutlineRounded`),Qa=H((0,Q.jsx)(`path`,{d:`M7 12c0 .55.45 1 1 1h8c.55 0 1-.45 1-1s-.45-1-1-1H8c-.55 0-1 .45-1 1m5-10C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2m0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8`}),`RemoveCircleOutlineRounded`);function $a(e){return te(`MuiLinearProgress`,e)}Ee(`MuiLinearProgress`,[`root`,`colorPrimary`,`colorSecondary`,`determinate`,`indeterminate`,`buffer`,`query`,`dashed`,`bar`,`bar1`,`bar2`]);var eo=4,to={},no=O`
13
+ 0% {
14
+ left: -35%;
15
+ right: 100%;
16
+ }
17
+
18
+ 60% {
19
+ left: 100%;
20
+ right: -90%;
21
+ }
22
+
23
+ 100% {
24
+ left: 100%;
25
+ right: -90%;
26
+ }
27
+ `,ro=typeof no==`string`?null:T`
28
+ animation: ${no} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite;
29
+ `,io=O`
30
+ 0% {
31
+ left: -200%;
32
+ right: 100%;
33
+ }
34
+
35
+ 60% {
36
+ left: 107%;
37
+ right: -8%;
38
+ }
39
+
40
+ 100% {
41
+ left: 107%;
42
+ right: -8%;
43
+ }
44
+ `,ao=typeof io==`string`?null:T`
45
+ animation: ${io} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite;
46
+ `,oo=O`
47
+ 0% {
48
+ opacity: 1;
49
+ background-position: 0 -23px;
50
+ }
51
+
52
+ 60% {
53
+ opacity: 0;
54
+ background-position: 0 -23px;
55
+ }
56
+
57
+ 100% {
58
+ opacity: 1;
59
+ background-position: -200px -23px;
60
+ }
61
+ `,so=typeof oo==`string`?null:T`
62
+ animation: ${oo} 3s infinite linear;
63
+ `,co=e=>{let{classes:t,variant:n,color:r}=e,i={root:[`root`,`color${we(r)}`,n],dashed:[`dashed`],bar1:[`bar`,`bar1`],bar2:[`bar`,`bar2`,n===`buffer`&&`color${we(r)}`]};return W(i,$a,t)},lo=(e,t)=>e.vars?e.vars.palette.LinearProgress[`${t}Bg`]:e.palette.mode===`light`?e.lighten(e.palette[t].main,.62):e.darken(e.palette[t].main,.5),uo=J(`span`,{name:`MuiLinearProgress`,slot:`Root`,overridesResolver:(e,t)=>{let{ownerState:n}=e;return[t.root,t[`color${we(n.color)}`],t[n.variant]]}})(q(({theme:e})=>({position:`relative`,overflow:`hidden`,display:`block`,height:4,zIndex:0,"@media print":{colorAdjust:`exact`},variants:[...Object.entries(e.palette).filter(t()).map(([t])=>({props:{color:t},style:{backgroundColor:lo(e,t)}})),{props:({ownerState:e})=>e.color===`inherit`&&e.variant!==`buffer`,style:{"&::before":{content:`""`,position:`absolute`,left:0,top:0,right:0,bottom:0,backgroundColor:`currentColor`,opacity:.3}}},{props:{variant:`buffer`},style:{backgroundColor:`transparent`}},{props:{variant:`query`},style:{transform:`rotate(180deg)`}}]}))),fo=J(`span`,{name:`MuiLinearProgress`,slot:`Dashed`})(q(({theme:e})=>({position:`absolute`,marginTop:0,height:`100%`,width:`100%`,backgroundSize:`10px 10px`,backgroundPosition:`0 -23px`,variants:[{props:{color:`inherit`},style:{opacity:.3,backgroundImage:`radial-gradient(currentColor 0%, currentColor 16%, transparent 42%)`}},...Object.entries(e.palette).filter(t()).map(([t])=>{let n=lo(e,t);return{props:{color:t},style:{backgroundImage:`radial-gradient(${n} 0%, ${n} 16%, transparent 42%)`}}})]})),so||{animation:`${oo} 3s infinite linear`},q(({theme:e})=>ve(e,{animation:`none`})||to)),po=J(`span`,{name:`MuiLinearProgress`,slot:`Bar1`,overridesResolver:(e,t)=>[t.bar,t.bar1]})(q(({theme:e})=>{let n=ve(e,{animation:`none`,left:`30%`,right:`auto`,width:`40%`});return{width:`100%`,position:`absolute`,left:0,bottom:0,top:0,...de(e,`transform`,{duration:`0.2s`,easing:`linear`}),transformOrigin:`left`,variants:[{props:{color:`inherit`},style:{backgroundColor:`currentColor`}},...Object.entries(e.palette).filter(t()).map(([t])=>({props:{color:t},style:{backgroundColor:(e.vars||e).palette[t].main}})),{props:{variant:`determinate`},style:{...de(e,`transform`,{duration:`.${eo}s`,easing:`linear`})}},{props:{variant:`buffer`},style:{zIndex:1,...de(e,`transform`,{duration:`.${eo}s`,easing:`linear`})}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:ro||{animation:`${no} 2.1s cubic-bezier(0.65, 0.815, 0.735, 0.395) infinite`}},...n?[{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:n}]:[]]}})),mo=J(`span`,{name:`MuiLinearProgress`,slot:`Bar2`,overridesResolver:(e,t)=>[t.bar,t.bar2]})(q(({theme:e})=>{let n=ve(e,{animation:`none`,display:`none`});return{width:`100%`,position:`absolute`,left:0,bottom:0,top:0,...de(e,`transform`,{duration:`0.2s`,easing:`linear`}),transformOrigin:`left`,variants:[...Object.entries(e.palette).filter(t()).map(([t])=>({props:{color:t},style:{"--LinearProgressBar2-barColor":(e.vars||e).palette[t].main}})),{props:({ownerState:e})=>e.variant!==`buffer`&&e.color!==`inherit`,style:{backgroundColor:`var(--LinearProgressBar2-barColor, currentColor)`}},{props:({ownerState:e})=>e.variant!==`buffer`&&e.color===`inherit`,style:{backgroundColor:`currentColor`}},{props:{color:`inherit`},style:{opacity:.3}},...Object.entries(e.palette).filter(t()).map(([t])=>({props:{color:t,variant:`buffer`},style:{backgroundColor:lo(e,t),...de(e,`transform`,{duration:`.${eo}s`,easing:`linear`})}})),{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:{width:`auto`}},{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:ao||{animation:`${io} 2.1s cubic-bezier(0.165, 0.84, 0.44, 1) 1.15s infinite`}},...n?[{props:({ownerState:e})=>e.variant===`indeterminate`||e.variant===`query`,style:n}]:[]]}})),ho=$.forwardRef(function(e,t){let n=ge({props:e,name:`MuiLinearProgress`}),{className:r,color:i=`primary`,max:a,min:o,value:s,valueBuffer:c,variant:l=`indeterminate`,...d}=n,f={...n,color:i,variant:l},p=o??0,m=a??100,h=co(f),g=De(),_={},v={bar1:{},bar2:{}};if((l===`determinate`||l===`buffer`)&&s!==void 0){let e=m-p,t=(s-p)/e*100-100;g&&(t=-t),v.bar1.transform=e>0?`translateX(${t}%)`:`translateX(-100%)`,_[`aria-valuenow`]=s,_[`aria-valuemin`]=p,_[`aria-valuemax`]=m}if(l===`buffer`&&c!==void 0){let e=m-p,t=(c-p)/e*100-100;g&&(t=-t),v.bar2.transform=e>0?`translateX(${t}%)`:`translateX(-100%)`}return(0,Q.jsxs)(uo,{className:u(h.root,r),ownerState:f,role:`progressbar`,..._,ref:t,...d,children:[l===`buffer`?(0,Q.jsx)(fo,{className:h.dashed,ownerState:f}):null,(0,Q.jsx)(po,{className:h.bar1,ownerState:f,style:v.bar1}),l===`determinate`?null:(0,Q.jsx)(mo,{className:h.bar2,ownerState:f,style:v.bar2})]})}),go=`ui-monospace, SFMono-Regular, Menlo, Consolas, monospace`,_o={A:`success`,M:`warning`,D:`error`,R:`info`,C:`info`,U:`success`};function vo({title:e,action:t,children:n}){return(0,Q.jsxs)(V,{component:`section`,sx:{px:2,py:1.75,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsxs)(R,{direction:`row`,sx:{alignItems:`center`,justifyContent:`space-between`,mb:1},children:[(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,sx:{fontWeight:650,textTransform:`uppercase`,letterSpacing:`.06em`},children:e}),t]}),n]})}var yo=3e3;function bo({session:e,snapshot:t,live:n,locale:r,onOpenReview:i,onClose:a}){let[s,c]=(0,$.useState)(),[l,u]=(0,$.useState)(!1),d=!!(n&&!n.complete);(0,$.useEffect)(()=>{let t=new AbortController;u(!1);let n,r=()=>void Je(e.sessionRef,`working-tree`,t.signal).then(e=>{t.signal.aborted||(c(e),u(!1))}).catch(()=>{!t.signal.aborted&&!d&&u(!0)}).finally(()=>{d&&!t.signal.aborted&&(n=window.setTimeout(r,yo))});return n=window.setTimeout(r,250),()=>{window.clearTimeout(n),t.abort()}},[e.sessionRef,e.sessionRevision,d]),(0,$.useEffect)(()=>{c(void 0)},[e.sessionRef]);let f=s?.files??[],p=f.reduce((e,t)=>e+(t.stats?.additions??0),0),m=f.reduce((e,t)=>e+(t.stats?.deletions??0),0),h=t?.usage.context,g=h?.state===`known`,_=g?h.percent:e.contextUsage.ratio===null?null:e.contextUsage.ratio*100,v=g?h.contextWindow:e.contextUsage.contextWindow,y=g?h.tokens:e.contextUsage.usedTokens,b=e.managedHelpers?.maximum===0?void 0:e.managedHelpers,S=e.managedPlan,C=e.managedProcess,w=S?.steps.filter(e=>e.status===`completed`).length??0,T=(n?.activities??[]).filter(e=>ua(e.toolLabel)===`subagent`);return(0,Q.jsxs)(V,{role:`region`,sx:{height:`100%`,overflowY:`auto`,bgcolor:`background.paper`},"aria-label":X(r,`Thay đổi và ngữ cảnh`,`Changes and context`),children:[(0,Q.jsxs)(R,{direction:`row`,sx:{alignItems:`center`,gap:1,px:2,minHeight:52,borderBottom:1,borderColor:`divider`},children:[(0,Q.jsx)(o,{sx:{fontWeight:600,flex:1},children:X(r,`Workspace`,`Workspace`)}),a&&(0,Q.jsx)(x,{size:`small`,"aria-label":X(r,`Đóng khung bên`,`Close side panel`),onClick:a,children:(0,Q.jsx)(L,{fontSize:`small`})})]}),(0,Q.jsxs)(vo,{title:s?X(r,`Thay đổi · ${f.length} file`,`Changes · ${f.length} files`):X(r,`Thay đổi`,`Changes`),action:f.length>0?(0,Q.jsx)(re,{title:X(r,`Xem diff đầy đủ, stage hoặc hoàn tác`,`Full diff, stage or revert`),children:(0,Q.jsx)(z,{size:`small`,startIcon:(0,Q.jsx)(pe,{fontSize:`small`}),onClick:i,children:X(r,`Review`,`Review`)})}):void 0,children:[(p>0||m>0)&&(0,Q.jsxs)(R,{direction:`row`,sx:{alignItems:`center`,gap:.75,mb:1,color:`text.secondary`},children:[(0,Q.jsx)(ea,{sx:{fontSize:15}}),(0,Q.jsx)(o,{variant:`caption`,children:X(r,`Chưa commit`,`Uncommitted`)}),(0,Q.jsxs)(o,{variant:`caption`,sx:{fontFamily:go,ml:`auto`},children:[(0,Q.jsxs)(V,{component:`span`,sx:Et(`success`),children:[`+`,p]}),` `,(0,Q.jsxs)(V,{component:`span`,sx:Et(`error`),children:[`−`,m]})]})]}),d&&(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,role:`status`,sx:{display:`block`,mb:.75},children:X(r,`Agent đang chạy · cập nhật trực tiếp. Thấy sai thì bấm Dừng.`,`The agent is running · updating live. Stop it if it goes wrong.`)}),s===void 0&&!l&&(0,Q.jsx)(ho,{sx:{borderRadius:1}}),(l||s?.availability.state===`unavailable`)&&(0,Q.jsx)(o,{variant:`body2`,color:`text.secondary`,children:X(r,`Chưa đọc được thay đổi (thư mục có thể không phải git repo).`,`Changes are unavailable (the folder may not be a git repository).`)}),s&&s.availability.state!==`unavailable`&&f.length===0&&(0,Q.jsx)(o,{variant:`body2`,color:`text.secondary`,children:X(r,`Chưa có thay đổi nào chưa commit.`,`No uncommitted changes.`)}),(0,Q.jsx)(R,{spacing:.25,children:f.slice(0,200).map(e=>(0,Q.jsxs)(R,{direction:`row`,sx:{alignItems:`center`,gap:1,py:.4},children:[(0,Q.jsx)(o,{variant:`caption`,sx:{fontFamily:go,fontWeight:650,width:12,..._o[e.status]?Et(_o[e.status]):{color:`text.secondary`}},children:e.status}),(0,Q.jsx)(o,{variant:`body2`,noWrap:!0,title:e.path,sx:{fontFamily:go,fontSize:12.5,flex:1,minWidth:0},children:e.path}),(0,Q.jsxs)(o,{variant:`caption`,sx:{fontFamily:go,flexShrink:0},children:[(e.stats?.additions??0)>0&&(0,Q.jsxs)(V,{component:`span`,sx:Et(`success`),children:[`+`,e.stats.additions,` `]}),(e.stats?.deletions??0)>0&&(0,Q.jsxs)(V,{component:`span`,sx:Et(`error`),children:[`−`,e.stats.deletions]})]})]},e.fileRef))})]}),(S||C)&&(0,Q.jsxs)(vo,{title:S?X(r,`Plan · ${w}/${S.steps.length}`,`Plan · ${w}/${S.steps.length}`):X(r,`Tiến trình`,`Process`),children:[S&&(0,Q.jsx)(R,{component:`ol`,spacing:.25,sx:{m:0,p:0,listStyle:`none`},"aria-label":X(r,`Plan của agent`,`Agent plan`),children:S.steps.map((e,t)=>{let n=e.status===`completed`?Xa:e.status===`in_progress`?Za:e.status===`deferred`?Qa:Ya;return(0,Q.jsxs)(R,{component:`li`,direction:`row`,sx:{alignItems:`flex-start`,gap:.75,py:.25},"aria-label":`${e.step}: ${e.status===`completed`?X(r,`xong`,`done`):e.status===`in_progress`?X(r,`đang làm`,`in progress`):e.status===`deferred`?X(r,`để sau`,`left for later`):X(r,`chưa làm`,`pending`)}`,children:[(0,Q.jsx)(n,{sx:{fontSize:16,mt:.2,color:e.status===`in_progress`?`primary.main`:`text.secondary`}}),(0,Q.jsx)(o,{variant:`body2`,sx:{flex:1,minWidth:0,overflowWrap:`anywhere`,...e.status===`completed`?{color:`text.secondary`,textDecoration:`line-through`}:e.status===`deferred`?{color:`text.disabled`,fontStyle:`italic`}:{},...e.status===`in_progress`?{fontWeight:600}:{}},children:e.step})]},t)})}),C&&C.outcome!==`no_change`&&(0,Q.jsxs)(o,{variant:`body2`,role:`status`,sx:{mt:+!!S,...Et(jt(C))},children:[X(r,`Lượt sửa code gần nhất: `,`Last code-changing turn: `),Nt(C,r)]})]}),(0,Q.jsxs)(vo,{title:X(r,`Ngữ cảnh`,`Context`),children:[(0,Q.jsxs)(R,{direction:`row`,sx:{justifyContent:`space-between`,mb:.75},children:[(0,Q.jsx)(o,{variant:`body2`,children:_==null?`—`:`${Math.round(_)}%`}),(0,Q.jsxs)(o,{variant:`caption`,color:`text.secondary`,children:[y?Ci(y):`—`,v?` / ${Ci(v)}`:``]})]}),(0,Q.jsx)(ho,{variant:`determinate`,value:Math.min(100,Math.max(0,_??0)),sx:{height:6,borderRadius:1},color:(_??0)>85?`warning`:`primary`,"aria-label":X(r,`Mức dùng ngữ cảnh`,`Context usage`)})]}),(b||T.length>0)&&(0,Q.jsxs)(vo,{title:`Subagent`,children:[b&&(0,Q.jsx)(o,{variant:`body2`,color:`text.secondary`,sx:{mb:T.length?.75:0},children:X(r,`${b.active??0}/${b.maximum} đang chạy`,`${b.active??0}/${b.maximum} running`)}),T.map(e=>(0,Q.jsxs)(R,{direction:`row`,sx:{alignItems:`center`,gap:.75,py:.25},children:[(0,Q.jsx)(Zi,{sx:{fontSize:15,color:`text.secondary`}}),(0,Q.jsx)(o,{variant:`body2`,sx:{flex:1},children:e.fileLabel??`subagent`}),(0,Q.jsx)(o,{variant:`caption`,color:e.state===`failed`?`error`:`text.secondary`,children:e.state===`running`?X(r,`đang chạy`,`running`):e.state===`failed`?X(r,`lỗi`,`failed`):X(r,`xong`,`done`)})]},e.toolCallRef))]})]})}function xo(e){let{locale:t,actions:n}=e,r=X(t,`Lệnh`,`Commands`),i=At(),a=[];e.canCreate&&a.push({id:`new-chat`,group:r,label:X(t,`Cuộc trò chuyện mới`,`New chat`),hint:`${i} ⇧ O`,keywords:`new create tạo`,run:n.newChat}),e.update.available&&e.update.latest&&a.push({id:`update-now`,group:r,label:X(t,`Cập nhật Piagent ${e.update.latest}`,`Update Piagent ${e.update.latest}`),keywords:`update upgrade nâng cấp phiên bản version`,run:()=>n.settings(`updates`)}),a.push({id:`check-updates`,group:r,label:X(t,`Kiểm tra cập nhật`,`Check for updates`),keywords:`update version phiên bản pi piagent`,run:n.checkUpdates}),e.hasSelection&&a.push({id:`toggle-panel`,group:r,label:X(t,`Bật/tắt khung Workspace`,`Toggle the Workspace panel`),keywords:`panel sidebar changes plan context`,run:n.togglePanel},{id:`open-changes`,group:r,label:X(t,`Mở Source Changes`,`Open Source Changes`),keywords:`diff review thay đổi git`,run:n.openChanges}),a.push({id:`theme`,group:r,label:e.colorMode===`dark`?X(t,`Chuyển sang chủ đề sáng`,`Switch to the light theme`):X(t,`Chuyển sang chủ đề tối`,`Switch to the dark theme`),keywords:`theme chủ đề dark light sáng tối`,run:()=>n.setColorMode(e.colorMode===`dark`?`light`:`dark`)},{id:`language`,group:r,label:t===`vi`?`Switch the interface to English`:`Chuyển giao diện sang tiếng Việt`,keywords:`language ngôn ngữ english tiếng việt`,run:()=>n.setLocale(t===`vi`?`en`:`vi`)},{id:`refresh`,group:r,label:X(t,`Làm mới`,`Refresh`),keywords:`reload tải lại`,run:n.refresh});let o=n.setTheme,s=X(t,`Chủ đề màu`,`Color theme`);if(o)for(let t of je)a.push({id:`theme-${t.id}`,group:s,label:`${s}: ${t.label}`,hint:t.id===e.themeId?`✓`:void 0,keywords:`theme chủ đề màu color ${t.mode}`,run:()=>o(t.id)});let c=X(t,`Cài đặt`,`Settings`);for(let e of Pt(t))a.push({id:`settings-${e.id}`,group:c,label:`${c}: ${e.label}`,hint:e.id===`general`?`${i} ,`:void 0,keywords:e.keywords,run:()=>n.settings(e.id)});let l=X(t,`Cuộc trò chuyện`,`Conversations`);for(let t of e.sessions)a.push({id:`session-${t.sessionRef}`,group:l,label:t.title,hint:t.projectLabel,keywords:t.projectLabel,run:()=>n.openSession(t.sessionRef)});return a}var So=`piagent-gateway-event-cursor-v1`,Co=3e4,wo=12e4,To=4001,Eo=class extends Error{reasonCode;constructor(e){super(e),this.name=`SessionSendRejectedError`,this.reasonCode=e}};function Do(e,t){if(!e)return null;try{let n=JSON.parse(e);return n.gatewayInstanceRef===t&&Number.isSafeInteger(n.sequence)&&Number(n.sequence)>=0?Number(n.sequence):null}catch{return null}}function Oo(e,t){if(t!==null)try{window.sessionStorage.setItem(So,JSON.stringify({gatewayInstanceRef:e,sequence:t}))}catch{}}function ko(e){return`${e}_${crypto.randomUUID().replaceAll(`-`,``)}`}function Ao(e){return e.phase===`rejected`&&e.resultCode===`stale-revision`&&e.error?.code===`session-revision-stale`}var jo=(0,$.lazy)(()=>Pe(()=>import(`./SettingsPage-xAt6kSyZ.js`).then(e=>({default:e.SettingsPage})),__vite__mapDeps([19,1,2,3,12,5,20,21]))),Mo=(0,$.lazy)(()=>Pe(()=>import(`./SessionInspectorDrawer-BWyEN4bf.js`).then(e=>({default:e.SessionInspectorDrawer})),__vite__mapDeps([22,1,2,3,7,8]))),No=272,Po=52,Fo=320,Io=`min(44vw, 860px)`,Lo=`piagent-webui-workspace-panel`;function Ro({session:e,live:t,locale:n}){let r=Ft(e,t),[i,a]=r===`running`?[X(n,`Đang chạy`,`Running`),`primary`]:r===`elsewhere`?[X(n,`Đang chạy ở nơi khác`,`Running elsewhere`),`info`]:r===`attention`?zt(e,t)===`question`?[X(n,`Cần bạn trả lời`,`Needs your answer`),`warning`]:[X(n,`Cần duyệt`,`Needs approval`),`warning`]:r===`recovery`?[X(n,`Cần khôi phục`,`Recovery needed`),`error`]:r===`failed`?[X(n,`Lượt cuối lỗi`,`Last turn failed`),`error`]:[X(n,`Sẵn sàng`,`Ready`),`default`],o=a==="default"?`text.disabled`:a===`info`?`info.main`:`${a}.main`;return(0,Q.jsxs)(V,{role:`status`,sx:{display:`inline-flex`,alignItems:`center`,gap:.75,height:28,px:1.1,borderRadius:999,whiteSpace:`nowrap`,fontSize:12.5,fontWeight:550,color:a==="default"?`text.secondary`:o,bgcolor:`action.hover`},children:[(0,Q.jsx)(V,{component:`span`,"aria-hidden":`true`,sx:{width:7,height:7,borderRadius:`50%`,bgcolor:o}}),i]})}function zo({session:e,snapshot:t,locale:n,live:r,canSend:i,canCompose:a,canRestart:s,send:l,abort:u,restart:d,onInspector:f,commandActions:p}){let m=e.sessionRef,g=hn(m),[_,v]=(0,$.useState)(()=>mn(m)),[y,b]=(0,$.useState)(!1),[S,C]=(0,$.useState)(),w=e=>{v(e),yn(m,e)},T=e.modelLabel===`agent-watch-auto`,D=!!(r&&!r.complete),O=Or({locale:n,company:T,running:D,pinned:e.pinned,bypass:e.managedBypass===!0,fast:e.managedFast===`on`||e.managedFast===`off`?e.managedFast:null,thinkingLevels:e.managedThinkingLevels??(T?[]:[`off`,`minimal`,`low`,`medium`,`high`,`xhigh`,`max`]),loadModels:()=>We().then(e=>e.models.map(e=>({modelRef:e.modelRef,label:e.displayName}))),actions:{...p,stop:u}}),k=O.map(e=>({kind:`command`,name:e.name,argumentHint:e.argumentHint,origin:`piagent`,scope:`project`,description:e.description})),[A,j]=(0,$.useState)(null),[M,N]=(0,$.useState)(null);(0,$.useEffect)(()=>{let e=e=>{e.isComposing||M||(e.key===`Escape`&&D&&!e.metaKey&&!e.ctrlKey?(e.preventDefault(),u()):e.key===`/`&&(e.metaKey||e.ctrlKey)&&!e.altKey&&!e.shiftKey&&i&&(e.preventDefault(),w(`/`),requestAnimationFrame(()=>{let e=P.inputRef.current;e?.focus(),e?.setSelectionRange(1,1)})))};return window.addEventListener(`keydown`,e),()=>window.removeEventListener(`keydown`,e)});let P=_r({projectRef:e.projectRef,value:_,locale:n,builtIns:k,onChange:e=>{w(e),K(null)}});(0,$.useEffect)(()=>{let e=e=>{e.detail===m&&(v(mn(m)),requestAnimationFrame(()=>P.inputRef.current?.focus()))};return window.addEventListener(bn,e),()=>window.removeEventListener(bn,e)},[m]);let[F,I]=(0,$.useState)(()=>g?.attachments??[]),[L,ee]=(0,$.useState)(!1),[te,ne]=(0,$.useState)(()=>g?.messageRequestId??`message-request.${crypto.randomUUID()}`),[B,H]=(0,$.useState)(!1),[U,W]=(0,$.useState)(null),[G,K]=(0,$.useState)(null),[q,ae]=(0,$.useState)(()=>g?.sendUnconfirmed??!1);(0,$.useEffect)(()=>{_n(m,F.length||q?{attachments:F,messageRequestId:te,sendUnconfirmed:q}:null)},[m,F,te,q]),(0,$.useEffect)(()=>{if(!q)return;let e=window.setTimeout(()=>{ae(!1),K({tone:`error`,text:X(n,`Tin nhắn chưa được gửi: phiên chưa nhận nó trong 2 phút nên nó sẽ không chạy nữa. Nội dung vẫn còn; bấm Gửi để thử lại.`,`The message was not sent: the session did not take it within 2 minutes, so it will not run. Your message is kept; send it again.`)})},wo+15e3);return()=>window.clearTimeout(e)},[q,n]);let[J,oe]=(0,$.useState)(!1),[se,ce]=(0,$.useState)(null),[le,ue]=(0,$.useState)(!1),[de,Y]=(0,$.useState)(0),fe=(0,$.useRef)(0);(0,$.useEffect)(()=>{let e=e=>{pn(e.dataTransfer)&&e.preventDefault()};return window.addEventListener(`dragover`,e),window.addEventListener(`drop`,e),()=>{window.removeEventListener(`dragover`,e),window.removeEventListener(`drop`,e)}},[]);let pe=t?.capabilities.capabilities.attachments,me=(0,$.useMemo)(()=>new Set(pe?.status===`available`?pe.mimeTypes:[]),[pe]),he=(0,$.useMemo)(()=>rn(me),[me]),ge=!!t&&pe?.status===`available`&&i&&!y&&!q&&!B&&F.length<4,_e=async r=>{if(!(!r?.length||!t||pe?.status!==`available`||B)){H(!0),W(null);try{let i=await Jt({files:r,snapshot:t,messageRequestId:te,existing:F,allowed:me,locale:n,stage:t=>Xe(e.sessionRef,t)});I(i.attachments),W(i.status)}catch{W(X(n,`Không thể đính kèm; file không được gửi vào Pi.`,`Unable to attach the file; it was not sent to Pi.`))}finally{H(!1)}}},ve=async r=>{if(!(!t||y||B)){H(!0),W(null);try{let i=await dn({snapshot:t,messageRequestId:te,attachmentRef:r,locale:n,stage:t=>Xe(e.sessionRef,t)});i.discarded?I(e=>e.filter(e=>e.attachmentRef!==r)):W(i.status)}catch{W(X(n,`Không thể bỏ file; trạng thái session có thể đã thay đổi.`,`Unable to remove the file; session state may have changed.`))}finally{H(!1)}}};(0,$.useEffect)(()=>{let t=new AbortController;return C(void 0),Ue(e.sessionRef,t.signal).then(C).catch(()=>void 0),()=>t.abort()},[e.sessionRef,e.sessionRevision]);let ye=(0,$.useRef)(!1),be=async()=>{let e=_;if(!e.trim()||y||q||ye.current)return;let t=F.length===0?Tr(e,O):null;if(t){K(null),j(null);let e=await t.command.run(t.argument);if(`confirm`in e){N(e.confirm),w(``);return}if(!(`send`in e)){j(e),e.tone!==`warning`&&w(``);return}}ye.current=!0,b(!0),K(null);let r=F.map(e=>e.attachmentRef);try{if((await l(e,r.length>0?{messageRequestId:te,attachmentRefs:r,attachments:F}:void 0)).state===`unconfirmed`){_n(m,{attachments:F,messageRequestId:te,sendUnconfirmed:!0}),ae(!0),K({tone:`warning`,text:X(n,`Piagent đang xác nhận lần gửi này. Nội dung và file vẫn được giữ; đừng gửi lại để tránh chạy trùng.`,`Piagent is confirming this send. Your message and files remain preserved; do not resend, to avoid a duplicate run.`)});return}w(``),I([]),W(null),ne(`message-request.${crypto.randomUUID()}`),_n(m,null)}catch{K({tone:`error`,text:X(n,`Tin nhắn chưa được gửi. Nội dung và file vẫn được giữ; có thể thử lại khi session sẵn sàng.`,`The message was not sent. Your message and files are preserved; retry when the session is ready.`)})}finally{ye.current=!1,b(!1)}},[xe,Se]=(0,$.useState)(!1);(0,$.useEffect)(()=>{!xe||!i||(Se(!1),r?.error||r?.settlement&&r.settlement!==`completed`?K({tone:`warning`,text:X(n,`Lượt vừa rồi không xong nên tin chưa gửi. Nội dung vẫn còn; Enter để gửi.`,`The last turn did not finish, so your message was not sent. It is kept; press Enter to send.`)}):be())},[xe,i]),(0,$.useEffect)(()=>{!q||r?.messageRequestId!==te||r.delivery!==`admitted`||(w(``),I([]),W(null),K(null),ae(!1),ne(`message-request.${crypto.randomUUID()}`))},[r?.delivery,r?.messageRequestId,te,q]);let Ce=async()=>{if(!(y||q)){b(!0),K(null);try{await l(X(n,`tiếp tục`,`continue`))}catch{K({tone:`error`,text:X(n,`Chưa gửi được. Thử lại khi session sẵn sàng.`,`Not sent. Retry when the session is ready.`)})}finally{b(!1)}}},we=async t=>{if(t){C(t);return}C(await Ue(e.sessionRef).catch(()=>S))},Te=async()=>{if(!J){oe(!0),ce(null);try{await d()}catch(e){ce(e instanceof Error?e.message:null)}finally{oe(!1)}}},Ee=r?.runtimeRecovery??(e.state===`recovery-required`?`stale`:null);return(0,Q.jsxs)(V,{sx:{minHeight:`calc(100vh - 88px - var(--piagent-status-bar, 0px))`,display:`flex`,flexDirection:`column`},children:[(0,Q.jsxs)(V,{sx:{flex:1,width:`100%`,maxWidth:860,mx:`auto`,px:{xs:2,sm:4},py:{xs:3,md:4},display:`flex`,flexDirection:`column`,justifyContent:`flex-end`},children:[!i&&e.modelLabel===`agent-watch-auto`&&(0,Q.jsx)(or,{locale:n,onConnected:()=>Y(e=>e+1)},e.sessionRef),(0,Q.jsx)(V,{sx:{width:`100%`},children:(0,Q.jsx)(Va,{reload:de,sessionRef:e.sessionRef,sessionRevision:e.sessionRevision,live:r,helpers:e.managedHelpers??void 0,approvals:t?.approvals,locale:n,onOpenActivity:()=>f(`activity`),onContinue:i&&!y&&!q&&e.liveState!==`running`&&(!r||r.complete)?()=>void Ce():void 0},e.sessionRef)})]}),(0,Q.jsxs)(V,{sx:{position:`sticky`,bottom:`var(--piagent-status-bar, 0px)`,px:{xs:1.5,sm:2.5},pb:2.5,background:`linear-gradient(transparent, var(--piagent-palette-background-default) 25%)`},children:[(0,Q.jsx)(Rn,{session:e,locale:n}),e.state===`terminal-owned`&&(0,Q.jsx)(h,{severity:`info`,role:`status`,sx:{maxWidth:820,mx:`auto`,mb:1},children:X(n,`Cuộc trò chuyện này đang chạy trong Terminal hoặc một tiến trình Piagent khác. Trang này tự cập nhật để bạn theo dõi; gửi tin nhắn khi nó chạy xong.`,`This conversation is running in Terminal or another Piagent process. This page follows it; send a message when it has finished.`)}),Ee&&(0,Q.jsx)(h,{severity:Ee===`recovered`?`success`:Ee===`failed`?`error`:`warning`,action:(Ee===`failed`||Ee===`required`||Ee===`stale`)&&s&&e.liveState!==`running`?(0,Q.jsx)(z,{color:`inherit`,size:`small`,disabled:J,onClick:()=>void Te(),children:J?X(n,`Đang khởi động…`,`Restarting…`):X(n,`Khởi động lại phiên`,`Restart session`)}):void 0,sx:{maxWidth:860,mx:`auto`,mb:1},children:Ee===`recovered`?X(n,`Runtime mới đã được xác minh; lịch sử và context của session được giữ nguyên.`,`The new runtime is verified; session history and context were preserved.`):Ee===`failed`?se?.startsWith(`company-`)&&Zn(se,null,n)?`${Zn(se,null,n).title}: ${Zn(se,null,n).text}`:X(n,`Runtime đã đổi nhưng chưa khởi động lại được. Hãy dùng nút bên cạnh hoặc restart Dashboard.`,`The runtime changed but could not restart. Use the action here or restart the Dashboard.`):Ee===`stale`&&[`session-runtime-open-failed`,`session-runtime-dispose-failed`].includes(e.reasonCode??``)?X(n,`Runtime của phiên này chưa mở được (thường do key, Harness hoặc Agent Watch lúc đó). Bấm Khởi động lại phiên để thử lại, hoặc lưu trữ phiên; lịch sử được giữ nguyên.`,`This session's runtime did not open (usually the key, the Harness or Agent Watch at the time). Restart the session to try again, or archive it; its history is kept.`):Ee===`stale`?X(n,`Phiên này chưa được đóng đúng cách và có thể đang mở ở cửa sổ Terminal khác. Đóng cửa sổ đó (nếu có) rồi bấm Khởi động lại phiên để làm tiếp; lịch sử được giữ nguyên.`,`This session was not closed cleanly and may still be open in a Terminal window. Close it (if any), then restart the session to go on; its history is kept.`):Ee===`restarting`?X(n,`Runtime vừa được cập nhật. Piagent đang khởi động lại session an toàn sau lượt hiện tại.`,`The runtime was updated. Piagent is safely restarting the session after the current turn.`):X(n,`Phát hiện runtime mới. Piagent sẽ giữ câu trả lời hiện tại rồi tự khởi động lại session.`,`A new runtime was detected. Piagent will preserve the current response and restart the session automatically.`)}),(0,Q.jsxs)(V,{sx:{position:`relative`,maxWidth:860,mx:`auto`,border:1,borderColor:le?`primary.main`:`divider`,borderStyle:le?`dashed`:`solid`,borderRadius:2,bgcolor:`background.paper`,px:1.5,pt:1.25,pb:1,boxShadow:`0 12px 40px -18px rgba(0,0,0,.5)`,transition:`border-color .16s, box-shadow .16s`,"&:focus-within":{borderColor:`rgba(var(--piagent-palette-primary-mainChannel) / .55)`,boxShadow:`0 0 0 3px rgba(var(--piagent-palette-primary-mainChannel) / .14), 0 12px 40px -18px rgba(0,0,0,.5)`}},onDragEnter:e=>{pn(e.dataTransfer)&&(fe.current+=1,ue(!0))},onDragOver:e=>{pn(e.dataTransfer)&&(e.preventDefault(),e.dataTransfer.dropEffect=ge?`copy`:`none`)},onDragLeave:e=>{pn(e.dataTransfer)&&(--fe.current,fe.current<=0&&(fe.current=0,ue(!1)))},onDrop:e=>{pn(e.dataTransfer)&&(e.preventDefault(),fe.current=0,ue(!1),ge&&_e(e.dataTransfer.files))},children:[le&&(0,Q.jsxs)(V,{role:`status`,sx:{position:`absolute`,inset:0,zIndex:3,display:`grid`,alignContent:`center`,justifyItems:`center`,gap:.5,borderRadius:1,bgcolor:`background.paper`,opacity:.96,pointerEvents:`none`,textAlign:`center`},children:[(0,Q.jsx)(o,{sx:{fontWeight:650},children:ge?X(n,`Thả tài liệu vào đây`,`Drop documents here`):F.length>=4?X(n,`Đã đủ 4 file cho tin nhắn này`,`This message already holds 4 files`):X(n,`Chưa nhận file lúc này`,`Files cannot be attached right now`)}),ge&&(0,Q.jsx)(o,{variant:`caption`,color:`text.secondary`,children:en(n)})]}),F.length>0&&(0,Q.jsx)(R,{direction:`row`,sx:{flexWrap:`wrap`,gap:.75,px:.5,pb:.75},"aria-label":X(n,`File sẽ gửi cùng tin nhắn`,`Files to send with the message`),children:F.map(e=>{let t=y||q||B?void 0:()=>void ve(e.attachmentRef),r=e.kind===`image`?Gt(e.attachmentRef):null;return r?(0,Q.jsx)(Kt,{url:r,name:e.displayName,detail:tn(e,n),locale:n,onRemove:t},e.attachmentRef):(0,Q.jsx)(c,{size:`small`,variant:`outlined`,color:e.kind===`document`?`success`:`default`,label:`${e.displayName} · ${tn(e,n)}`,onDelete:t,deleteIcon:(0,Q.jsx)(Bn,{"aria-label":`${X(n,`Bỏ`,`Remove`)} ${e.displayName}`,role:`button`})},e.attachmentRef)})}),A&&(0,Q.jsx)(h,{severity:A.tone,onClose:()=>j(null),sx:{mb:.75,whiteSpace:`pre-line`},children:A.text}),(0,Q.jsx)(ie,{fullWidth:!0,multiline:!0,minRows:2,disabled:!a||y||q,value:_,inputRef:P.inputRef,...P.inputProps,onChange:e=>{w(e.target.value),K(null),Se(!1),P.track(e)},onKeyDown:e=>{P.onKeyDown(e)||sr(e)&&(e.preventDefault(),i?be():a&&_.trim()&&Se(!0))},onPaste:e=>{e.clipboardData?.files.length&&(e.preventDefault(),ge&&_e(e.clipboardData.files))},placeholder:X(n,`Nhắn cho Piagent… (@ để chọn file, folder)`,`Message Piagent… (@ for files and folders)`),variant:`standard`,slotProps:{input:{disableUnderline:!0},htmlInput:P.htmlInput}}),P.menu,(0,Q.jsx)(lt,{open:M!==null,title:M?.title??``,description:M?.description??``,confirmLabel:M?.confirmLabel??``,cancelLabel:X(n,`Huỷ`,`Cancel`),onCancel:()=>N(null),onConfirm:()=>{let e=M;N(null),e&&e.run().then(j)}}),(0,Q.jsx)(Xn,{in:L,id:`piagent-message-options`,children:(0,Q.jsxs)(V,{sx:{mt:.65,p:.85,borderRadius:1,bgcolor:`action.hover`},children:[(0,Q.jsx)(st,{session:e,snapshot:t,connections:S,locale:n,onOpenChanges:()=>f(`source`),onConnectionsChanged:we}),(0,Q.jsx)(R,{direction:`row`,sx:{minWidth:0,alignItems:`center`,gap:.75,flexWrap:`wrap`},children:pe?.status===`available`&&(0,Q.jsx)(re,{title:X(n,`Chọn file, hoặc kéo thả / dán thẳng vào khung chat`,`Pick a file, or drag and drop / paste straight into the chat`),children:(0,Q.jsxs)(z,{component:`label`,size:`small`,color:`inherit`,startIcon:(0,Q.jsx)(zn,{}),disabled:!ge,"aria-label":`${X(n,`Đính kèm`,`Attach`)} (${F.length}/4)`,children:[X(n,`Đính kèm`,`Attach`),(0,Q.jsx)(`input`,{type:`file`,multiple:!0,hidden:!0,disabled:!ge,accept:he||void 0,onChange:e=>{_e(e.target.files),e.currentTarget.value=``}})]})})})]})}),(0,Q.jsxs)(R,{direction:`row`,sx:{justifyContent:`space-between`,alignItems:`center`,mt:.5,gap:1},children:[(0,Q.jsxs)(R,{direction:`row`,sx:{minWidth:0,alignItems:`center`,gap:1},children:[(0,Q.jsx)(re,{title:L?X(n,`Ẩn tùy chọn`,`Hide options`):X(n,`File và công cụ`,`Files and tools`),children:(0,Q.jsx)(x,{size:`small`,"aria-label":L?X(n,`Ẩn tùy chọn`,`Hide options`):X(n,`Thêm tùy chọn`,`More options`),"aria-expanded":L,"aria-controls":`piagent-message-options`,onClick:()=>ee(e=>!e),sx:{bgcolor:L?`action.selected`:`transparent`},children:(0,Q.jsx)(E,{fontSize:`small`,sx:{transition:`transform .16s ease`,transform:L?`rotate(45deg)`:`none`}})})}),(0,Q.jsx)(o,{variant:`caption`,color:U||G?.tone===`error`?`error`:G?`warning.main`:`text.disabled`,noWrap:!G,sx:{display:{xs:U||G||B?`block`:`none`,sm:`block`}},children:G?.text??U??(B?X(n,`Đang đọc tài liệu…`,`Reading documents…`):xe?X(n,`Tin sẽ gửi khi lượt này xong · sửa nội dung để hủy`,`Sends when this turn ends · edit it to cancel`):r&&!r.complete?X(n,`Esc để dừng · Enter để gửi khi lượt này xong`,`Esc to stop · Enter to send when this turn ends`):i?X(n,`Enter để gửi · Shift+Enter xuống dòng`,`Enter to send · Shift+Enter for a new line`):X(n,`Session hiện chỉ đọc`,`Session is currently read only`))})]}),r?.operationRef&&!r.complete&&r.abortable!==!1?(0,Q.jsx)(z,{color:`error`,variant:`outlined`,size:`small`,startIcon:(0,Q.jsx)(Un,{}),onClick:()=>void u(),sx:{borderRadius:999},children:X(n,`Dừng`,`Stop`)}):(0,Q.jsx)(x,{"aria-label":X(n,`Gửi`,`Send`),disabled:!i||y||q||!_.trim(),color:`primary`,onClick:()=>void be(),sx:{width:32,height:32,borderRadius:999,bgcolor:`primary.main`,color:`primary.contrastText`,transition:`transform .12s, background-color .16s`,"&:hover":{bgcolor:`primary.main`,color:`primary.contrastText`,transform:`translateY(-1px)`},"&.Mui-disabled":{bgcolor:`action.disabledBackground`}},children:(0,Q.jsx)(Vn,{fontSize:`small`})})]})]})]})]})}function Bo({locale:e,canCreate:t,onNew:n}){return(0,Q.jsxs)(R,{sx:{minHeight:`calc(100vh - ${Po}px - var(--piagent-status-bar, 0px))`,alignItems:`center`,justifyContent:`center`,px:3,textAlign:`center`},spacing:1.5,children:[(0,Q.jsx)(ut,{size:48}),(0,Q.jsx)(o,{variant:`h1`,children:X(e,`Bắt đầu với Piagent`,`Start with Piagent`)}),(0,Q.jsx)(o,{color:`text.secondary`,sx:{maxWidth:520},children:X(e,`Tạo cuộc trò chuyện mới, chọn project và model; session sẽ được lưu để tiếp tục sau khi đóng Gateway.`,`Create a new chat, choose a project and model, and the session will remain available after the Gateway closes.`)}),(0,Q.jsx)(z,{disabled:!t,variant:`contained`,startIcon:(0,Q.jsx)(E,{}),onClick:n,children:X(e,`Cuộc trò chuyện mới`,`New chat`)})]})}function Vo({catalog:e,capabilities:t,connection:n,live:r,terminalActivities:a,refresh:s,create:c,send:l,abort:u,restart:f,setModel:p,setThinking:m,setPermission:h,setFast:g,rename:_,pin:v,archive:y,unarchive:b,fork:S}){let{locale:C,colorMode:w,themeId:T,setLocale:E,setColorMode:D,setThemeId:O}=Ae(),A=Ar(),M=ct(),[P,F]=(0,$.useState)(!1),[I,L]=(0,$.useState)(`sessions`),ee=k(ce().breakpoints.up(`lg`)),[te,ne]=(0,$.useState)(null),[B,H]=(0,$.useState)(``),[U,W]=(0,$.useState)(),[G,K]=(0,$.useState)(!1),[q,ae]=(0,$.useState)(!1),[J,oe]=(0,$.useState)(`chat`),[se,le]=(0,$.useState)(!1),[ue,de]=(0,$.useState)(`general`),[Y,fe]=(0,$.useState)(!1),[me,ge]=(0,$.useState)(`task`),_e=!ee,[ve,ye]=(0,$.useState)(()=>{try{let e=window.localStorage.getItem(Lo);if(e)return e===`open`}catch{}return window.innerWidth>=1200}),[be,Se]=(0,$.useState)(!1),Ce=()=>_e?Se(e=>!e):ye(e=>{try{window.localStorage.setItem(Lo,e?`closed`:`open`)}catch{}return!e}),we=(0,$.useRef)(!1);Y&&(we.current=!0);let Te=(0,$.useRef)(!1);Te.current=Y&&(me===`activity`||me===`source`);let[Ee,De]=(0,$.useState)(),ke=(0,$.useRef)(null),[je,Me]=(0,$.useState)(`idle`),Pe=(0,$.useRef)(null),Ie=(0,$.useRef)(null);Ie.current??=new xn;let[Le,Re]=(0,$.useState)(!1),[ze,Be]=(0,$.useState)(null),[Ve,He]=(0,$.useState)(null),[Ue,We]=(0,$.useState)(``),[Ge,Ke]=(0,$.useState)(!1),[Je,Ye]=(0,$.useState)(null),[Ze,Qe]=(0,$.useState)(null);(0,$.useEffect)(()=>{J===`chat`&&U||(window.scrollTo(0,0),document.documentElement.scrollTop=0,document.body.scrollTop=0)},[J,U]);let $e=(0,$.useMemo)(()=>(e?.sessions??[]).filter(e=>e.archived===q&&`${e.title} ${e.projectLabel} ${e.preview}`.toLowerCase().includes(B.trim().toLowerCase())),[e,B,q]),et=(0,$.useMemo)(()=>{let e=new Map;for(let t of $e){let n=e.get(t.projectRef)??{label:t.projectLabel,gitBranch:t.gitBranch,sessions:[]};n.gitBranch??=t.gitBranch,n.gitRepositories??=t.gitRepositories,n.sessions.push(t),e.set(t.projectRef,n)}return[...e.entries()].map(([e,t])=>({projectRef:e,...t,sessions:t.sessions.sort((e,t)=>Number(t.pinned)-Number(e.pinned)||Date.parse(t.updatedAt)-Date.parse(e.updatedAt))})).sort((e,t)=>Date.parse(t.sessions[0]?.updatedAt??``)-Date.parse(e.sessions[0]?.updatedAt??``))},[$e]),tt=e?.sessions.filter(e=>e.archived).length??0;(0,$.useEffect)(()=>{(!U||!(e?.sessions??[]).some(e=>e.sessionRef===U))&&W((e?.sessions??[]).find(e=>!e.archived)?.sessionRef)},[U,e]);let Z=(e?.sessions??[]).find(e=>e.sessionRef===U),nt=Z?.sessionRef,rt=Z?.state===`terminal-owned`,it=(e?.sessions??[]).some(e=>e.state===`terminal-owned`);(0,$.useEffect)(()=>{let e=rt?3e3:it?1e4:3e4,t=window.setInterval(()=>{document.visibilityState===`visible`&&s()},e);return()=>window.clearInterval(t)},[rt,it,s]);let at=(0,$.useRef)(nt);at.current=nt;let ot=ke.current&&ke.current.sessionRef===nt&&ke.current.snapshot===Ee?Ee:void 0,lt=Pe.current===nt?je:nt?`loading`:`idle`,ut=Z?r[Z.sessionRef]:void 0,dt=!!(ut&&!ut.complete),ft=n===`connected`&&!!Z&&(Z?.composerAvailable||dt)&&t?.capabilities.sessionActions.send.status===`available`&&![`required`,`restarting`,`failed`].includes(String(ut?.runtimeRecovery)),[pt,mt]=(0,$.useState)(null),ht=(0,$.useRef)(!1);(0,$.useEffect)(()=>{if(!e||ht.current)return;ht.current=!0;let t=Fe();t&&(mt(t),oe(`new`))},[e]);let gt=e=>{mt(null),W(e),oe(`chat`),K(!1)},vt=Ka({sessions:(0,$.useMemo)(()=>e?.sessions??[],[e]),live:r,selectedRef:J===`chat`?nt:void 0,onOpen:gt,locale:C}),yt=e=>{de(e),le(!0)};bt({palette:()=>F(!0),settings:()=>yt(`general`),newChat:()=>{wt&&(Be(null),oe(`new`))}});let xt=e=>{ge(e),fe(!0)},Ct=async()=>{let e=at.current;if(!e)return;ke.current?.sessionRef!==e&&(Pe.current=e,Me(`loading`));let t=await Ie.current.run(()=>qe(e),t=>{at.current===e&&(ke.current={sessionRef:e,snapshot:t},Pe.current=e,De(t),Me(`ready`))},()=>{at.current===e&&(Pe.current=e,Me(ke.current?.sessionRef===e?`ready`:`error`))});return at.current===e?t:void 0};(0,$.useEffect)(()=>{if(!nt){Ie.current.invalidate(),ke.current=null,Pe.current=null,De(void 0),Me(`idle`);return}let e=nt,t=new AbortController;return Pe.current=e,ke.current?.sessionRef!==e&&(ke.current=null,De(void 0),Me(`loading`)),Ie.current.run(()=>qe(e,t.signal),n=>{t.signal.aborted||at.current!==e||(ke.current={sessionRef:e,snapshot:n},Pe.current=e,De(n),Me(`ready`))},()=>{t.signal.aborted||at.current!==e||(Pe.current=e,Me(ke.current?.sessionRef===e?`ready`:`error`))}),()=>t.abort()},[nt,Z?.sessionRevision]),(0,$.useEffect)(()=>{if(!Y||me!==`activity`&&me!==`source`||!nt||!ot||!ut?.operationRef||ut.complete)return;let e=nt,t=!1,n,r=async()=>{await Ie.current.run(()=>qe(e),n=>{t||!Te.current||at.current!==e||(ke.current={sessionRef:e,snapshot:n},Pe.current=e,De(n),Me(`ready`))},()=>void 0),t||(n=window.setTimeout(()=>void r(),2e3))};return n=window.setTimeout(()=>void r(),2e3),()=>{t=!0,n!==void 0&&window.clearTimeout(n)}},[Y,me,nt,!!ot,ut?.operationRef,ut?.complete]);let wt=n===`connected`&&t?.capabilities.sessionActions.create.status===`available`,Tt=async e=>{Re(!0),Be(null);let t=null;try{let n=`message-request.${crypto.randomUUID()}`,r=e.files.length>0,i=await c({projectRef:e.projectRef,placeRef:e.placeRef,modelRef:e.modelRef,thinkingLevel:e.thinkingLevel,workflow:e.workflow,permissionMode:e.permissionMode,fast:e.fast,message:e.message,messageRequestId:n,deferInitialMessage:r});if(t=i.sessionRef,!t)throw Error(`session-create-result-invalid`);if(yn(gn,``),_n(gn,null),i.phase!==`settled`){W(t),oe(`chat`),Qe({title:X(C,`Session đã được tạo`,`The session was created`),message:X(C,`Pi đã nhận yêu cầu và session đang tự đồng bộ. Không gửi lại để tránh chạy trùng.`,`Pi received the request and the session is resyncing. Do not resend it, to avoid a duplicate run.`)});return}if(r){let r=(await s())?.sessions.find(e=>e.sessionRef===t);if(!r)throw Error(`session-catalog-refresh-failed`);let i=await qe(t),a=i.capabilities.capabilities.attachments;if(a.status!==`available`)throw Error(a.reason?.code??`session-attachment-unavailable`);let o=await Jt({files:e.files,snapshot:i,messageRequestId:n,existing:[],allowed:new Set(a.mimeTypes),locale:C,stage:e=>Xe(t,e)});if(o.status||o.attachments.length!==e.files.length)throw await Promise.all(o.attachments.map(async e=>{try{await dn({snapshot:i,messageRequestId:n,attachmentRef:e.attachmentRef,locale:C,stage:e=>Xe(t,e)})}catch{}})),Error(o.status??`session-attachment-incomplete`);await l(r,e.message,{messageRequestId:n,attachmentRefs:o.attachments.map(e=>e.attachmentRef),attachments:o.attachments,workflow:e.workflow})}W(t),oe(`chat`)}catch(n){let r=n instanceof Error?n.message:`session-create-failed`;t?(e.files.length>0&&yn(t,e.message),W(t),oe(`chat`),Qe({title:X(C,`Session đã tạo nhưng file chưa được gửi`,`The session was created, but the files were not sent`),message:r})):Be(rr(r,C))}finally{Re(!1)}},Et=(e,t)=>{if(t===`pin`){v(e,!e.pinned).catch(e=>Qe({title:X(C,`Không thể đổi trạng thái ghim`,`Could not change pin state`),message:e instanceof Error?e.message:`session-pin-failed`}));return}if(t===`unarchive`){b(e).then(()=>ae(!1)).catch(e=>Qe({title:X(C,`Không thể khôi phục cuộc trò chuyện`,`Could not restore chat`),message:e instanceof Error?e.message:`session-unarchive-failed`}));return}Ye(null),We(t===`rename`?e.title:t===`fork`?`${e.title} · ${X(C,`nhánh`,`fork`)}`:``),He({kind:t,session:e})},Ot=async()=>{if(!(!Ve||Ge)){Ke(!0),Ye(null);try{if(Ve.kind===`rename`)await _(Ve.session,Ue.trim());else if(Ve.kind===`archive`)await y(Ve.session);else{let e=await S(Ve.session,Ue.trim()||null);e.sessionRef&&(W(e.sessionRef),oe(`chat`))}He(null)}catch(e){Ye(Wo(Ve.kind,e instanceof Error?e.message:`session-action-failed`,C))}finally{Ke(!1)}}},kt=(0,Q.jsx)(Mt,{locale:C,canCreate:wt,query:B,onQuery:H,groups:et,count:$e.length,selectedRef:J===`chat`?Z?.sessionRef:void 0,showArchived:q,archivedCount:tt,settingsOpen:se,connection:n,live:r,unseen:vt.unseen,onSelect:gt,onAction:Et,onNew:()=>{Be(null),oe(`new`),K(!1)},onToggleArchived:()=>{ae(e=>!e),K(!1)},updateDot:!!(M.status?.updateAvailable&&M.status.installable),onSettings:()=>{yt(M.status?.updateAvailable&&M.status.installable?`updates`:`general`),K(!1)}}),At=J===`chat`&&Z?(0,Q.jsx)(bo,{session:Z,snapshot:ot,live:ut,locale:C,onOpenReview:()=>xt(`source`),onClose:()=>_e?Se(!1):ye(!1)}):null,jt=!!At&&(_e?be:ve)&&!Y;if(A)return(0,Q.jsx)(jr,{locale:C});if(!e&&n!==`failed`)return(0,Q.jsxs)(R,{sx:{minHeight:`100vh`,alignItems:`center`,justifyContent:`center`},spacing:2,children:[(0,Q.jsx)(xe,{size:24}),(0,Q.jsx)(o,{children:X(C,`Đang mở Piagent…`,`Opening Piagent…`)})]});let Nt=J===`new`?X(C,`Cuộc trò chuyện mới`,`New chat`):Z?.title??`Piagent`,Pt=xo({locale:C,colorMode:w,themeId:T,canCreate:wt,hasSelection:J===`chat`&&!!Z,sessions:(e?.sessions??[]).filter(e=>!e.archived),update:{available:!!(M.status?.updateAvailable&&M.status.installable&&!_t(M.status)),latest:M.status?.piagent.latest??null},actions:{newChat:()=>{Be(null),oe(`new`)},togglePanel:Ce,openChanges:()=>xt(`source`),refresh:()=>void s(),settings:yt,checkUpdates:()=>{yt(`updates`),M.check()},setColorMode:D,setTheme:O,setLocale:E,openSession:gt}}),Ft=Object.values(r).filter(e=>e&&!e.complete).length;return(0,Q.jsx)(Vt,{sessionRef:J===`chat`?nt:void 0,onOpen:()=>fe(!1),children:(0,Q.jsxs)(V,{sx:{minHeight:`100vh`,bgcolor:`background.default`,"--piagent-status-bar":{xs:`0px`,md:`28px`}},children:[(0,Q.jsx)(j,{position:`fixed`,color:`transparent`,elevation:0,sx:{left:{md:`${No}px`},right:{lg:jt?`${Fo}px`:0,xl:Y?Io:jt?`${Fo}px`:0},width:{xs:`100%`,md:`auto`},borderBottom:1,transition:`right .2s ease`,borderColor:`divider`,bgcolor:`rgba(var(--piagent-palette-background-defaultChannel) / .9)`,backdropFilter:`blur(18px)`},children:(0,Q.jsxs)(Oe,{sx:{minHeight:`${Po}px !important`,gap:1,px:{xs:1.5,sm:2.5}},children:[(0,Q.jsx)(x,{"aria-label":X(C,`Mở điều hướng`,`Open navigation`),onClick:()=>K(!0),sx:{display:{md:`none`}},children:(0,Q.jsx)(i,{})}),(0,Q.jsxs)(V,{sx:{flex:1,minWidth:0},children:[(0,Q.jsx)(o,{component:`h1`,noWrap:!0,sx:{fontWeight:600,fontSize:14.5,letterSpacing:`-0.01em`,lineHeight:1.3},children:Nt}),J===`chat`&&Z&&(0,Q.jsxs)(o,{variant:`caption`,color:`text.secondary`,noWrap:!0,component:`div`,sx:{display:`flex`,alignItems:`center`,gap:.75,minWidth:0},children:[(0,Q.jsx)(V,{component:`span`,sx:{overflow:`hidden`,textOverflow:`ellipsis`,flexShrink:3,minWidth:24},children:Z.projectLabel}),(Z.gitBranch||!!Z.gitRepositories?.length)&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(V,{component:`span`,"aria-hidden":!0,sx:{color:`text.disabled`},children:`·`}),(0,Q.jsx)(It,{projectRef:Z.projectRef,projectLabel:Z.projectLabel,branch:Z.gitBranch,repositories:Z.gitRepositories,locale:C,maxWidth:`45%`,onSwitched:()=>void s()})]})]})]}),J===`chat`&&Z&&(0,Q.jsxs)(Q.Fragment,{children:[(0,Q.jsx)(st,{placement:`header`,compact:Y,session:Z,snapshot:ot,locale:C,onOpenChanges:()=>xt(`source`),canSetModel:n===`connected`&&t?.capabilities.sessionActions.setModel.status===`available`,canSetThinking:n===`connected`&&t?.capabilities.sessionActions.setThinking.status===`available`,canSetPermission:n===`connected`&&t?.capabilities.sessionActions.setPermission.status===`available`,onSetModel:e=>p(Z,e),onSetThinking:e=>m(Z,e),onSetPermission:e=>h(Z,e),onSetFast:e=>g(Z,e)}),(0,Q.jsx)(V,{sx:{display:{xs:`none`,sm:Y?`none`:`block`}},children:(0,Q.jsx)(Ro,{session:Z,live:ut,locale:C})}),(0,Q.jsx)(V,{"aria-hidden":`true`,sx:{width:`1px`,height:20,bgcolor:`divider`,mx:.5,display:{xs:`none`,sm:`block`}}}),(0,Q.jsx)(re,{title:`Source Changes`,children:(0,Q.jsx)(x,{"aria-label":X(C,`Mở Source Changes Inspector`,`Open Source Changes Inspector`),onClick:()=>xt(`source`),children:(0,Q.jsx)(pe,{fontSize:`small`})})}),(0,Q.jsx)(re,{title:X(C,`Khung Workspace: thay đổi, ngữ cảnh, subagent`,`Workspace panel: changes, context, subagents`),children:(0,Q.jsx)(x,{"aria-label":X(C,`Khung Workspace`,`Workspace panel`),"aria-pressed":jt,onClick:()=>Ce(),color:jt?`primary`:`default`,children:(0,Q.jsx)(Hn,{fontSize:`small`,sx:{transform:`scaleX(-1)`}})})})]}),(0,Q.jsx)(re,{title:X(C,`Làm mới`,`Refresh`),children:(0,Q.jsx)(x,{"aria-label":X(C,`Làm mới`,`Refresh`),onClick:()=>void s(),children:(0,Q.jsx)(he,{fontSize:`small`})})})]})}),(0,Q.jsxs)(V,{component:`nav`,sx:{width:{md:No}},children:[(0,Q.jsx)(N,{variant:`temporary`,open:G,onClose:()=>K(!1),sx:{display:{xs:`block`,md:`none`},"& .MuiDrawer-paper":{width:No}},children:kt}),(0,Q.jsxs)(N,{variant:`permanent`,sx:{display:{xs:`none`,md:`block`},"& .MuiDrawer-paper":{width:No,borderRight:1,borderColor:`divider`,height:`calc(100% - var(--piagent-status-bar, 0px))`}},children:[ee&&Z&&J===`chat`&&(0,Q.jsx)(Cn,{value:I,onChange:L}),!ee||I===`sessions`||!Z||J!==`chat`?kt:(0,Q.jsx)(V,{ref:ne,sx:{overflow:`auto`,flex:1}})]})]}),(0,Q.jsx)(V,{component:`main`,sx:{ml:{md:`${No}px`},mr:{lg:jt?`${Fo}px`:0,xl:Y?Io:jt?`${Fo}px`:0},pt:`${Po}px`,transition:`margin-right .2s ease`},children:J===`new`?(0,Q.jsx)(Sr,{active:!0,defaultProjectRef:pt??Z?.projectRef,busy:Le,error:ze,onCancel:()=>oe(`chat`),onCreate:e=>Tt(e)}):Z?(0,Q.jsx)(Fn,{sessionRef:Z.sessionRef,navigationHost:te,sidebarMode:I,onSection:L,children:(0,Q.jsx)(zo,{session:Z,snapshot:ot,locale:C,live:r[Z.sessionRef],commandActions:{setModel:e=>p(Z,e),setThinking:e=>m(Z,e),setFast:e=>g(Z,e),setPermission:e=>h(Z,e),rename:e=>_(Z,e),fork:()=>S(Z,null),pin:e=>v(Z,e),archive:()=>y(Z),newChat:()=>{Be(null),oe(`new`)},openChanges:()=>xt(`source`),openSettings:()=>yt(`general`)},canSend:ft&&!dt&&Z.composerAvailable,canCompose:ft,canRestart:n===`connected`&&t?.capabilities.sessionActions.release.status===`available`&&t?.capabilities.sessionActions.acquire.status===`available`,send:(e,t)=>l(Z,e,t),abort:()=>u(Z).catch(e=>Qe({title:X(C,`Chưa dừng được lượt này`,`This turn could not be stopped`),message:e instanceof Error&&e.message===`operation-unavailable`?X(C,`Lượt đã kết thúc hoặc đang chuyển bước. Nếu vẫn còn chạy, bấm Dừng lần nữa.`,`The turn already ended or is between steps. If it is still running, press Stop again.`):e instanceof Error?e.message:`session-abort-failed`})),restart:()=>f(Z),onInspector:xt},Z.sessionRef)},Z.sessionRef):(0,Q.jsx)(Bo,{locale:C,canCreate:wt,onNew:()=>oe(`new`)})}),At&&jt&&!_e&&(0,Q.jsx)(V,{component:`aside`,sx:{display:{xs:`none`,lg:`block`},position:`fixed`,top:0,right:0,bottom:`var(--piagent-status-bar, 0px)`,width:Fo,borderLeft:1,borderColor:`divider`,zIndex:e=>e.zIndex.appBar-1},children:At}),At&&(0,Q.jsx)(N,{anchor:`right`,variant:`temporary`,open:be&&!Y&&_e,onClose:()=>Se(!1),sx:{display:{xs:`block`,lg:`none`},"& .MuiDrawer-paper":{width:`min(${Fo}px, 88vw)`}},children:At}),we.current&&(0,Q.jsx)($.Suspense,{fallback:null,children:(0,Q.jsx)(Mo,{open:Y,active:me,snapshot:ot,state:lt,sessionRef:nt,terminalActivities:Z?a[Z.sessionRef]:void 0,liveActivities:dt&&ut?[...ut.activities,...ut.activities.some(e=>e.agent&&e.state===`running`)?[]:pi(Z?.managedHelpers)]:void 0,onClose:()=>fe(!1),onActive:ge,refresh:Ct,findings:Z?.managedReview?.findings,onSendComments:Z&&Z.composerAvailable?e=>{vn(Z.sessionRef,e),fe(!1)}:void 0})}),(0,Q.jsx)(Rr,{locale:C,onDetails:()=>yt(`updates`)}),vt.view,(0,Q.jsx)(St,{locale:C,connection:n,running:Ft,session:J===`chat`?Z:void 0,onBranchSwitched:()=>void s(),onUpdates:()=>yt(`updates`),onPalette:()=>F(!0)}),(0,Q.jsx)(Dt,{open:P,onClose:()=>F(!1),commands:Pt,locale:C}),(0,Q.jsx)(d,{open:se,onClose:()=>le(!1),fullWidth:!0,maxWidth:`lg`,"aria-labelledby":`piagent-settings-title`,slotProps:{paper:{sx:{m:{xs:0,sm:2},width:{xs:`100%`,sm:`calc(100% - 32px)`},height:{xs:`100%`,sm:`min(86vh, 840px)`},maxHeight:{xs:`100%`,sm:`86vh`},borderRadius:{xs:0,sm:2.5},overflow:`hidden`}}},children:se&&(0,Q.jsx)(Ne,{locale:C,children:(0,Q.jsx)(jo,{section:ue,onSection:de,onBack:()=>le(!1),session:Z,snapshot:ot,capabilities:t,connection:n,onSetModel:Z?e=>p(Z,e):void 0,onSetThinking:Z?e=>m(Z,e):void 0,onSetPermission:Z?e=>h(Z,e):void 0,onRuntimeChanged:async()=>{await s(),await Ct()}})})}),(0,Q.jsx)(d,{open:!!Ve,onClose:()=>!Ge&&He(null),fullWidth:!0,maxWidth:`xs`,children:(0,Q.jsxs)(R,{spacing:2,sx:{p:3},children:[(0,Q.jsx)(o,{variant:`h2`,children:Ve?.kind===`rename`?X(C,`Đổi tên cuộc trò chuyện`,`Rename chat`):Ve?.kind===`fork`?X(C,`Tạo nhánh cuộc trò chuyện`,`Fork chat`):X(C,`Lưu trữ cuộc trò chuyện`,`Archive chat`)}),Ve?.kind===`archive`?(0,Q.jsx)(o,{color:`text.secondary`,children:X(C,`Cuộc trò chuyện vẫn được lưu và có thể khôi phục từ mục Đã lưu trữ.`,`The chat remains saved and can be restored from Archived.`)}):(0,Q.jsx)(ie,{autoFocus:!0,label:X(C,`Tên`,`Title`),value:Ue,onChange:e=>We(e.target.value),slotProps:{htmlInput:{maxLength:500}}}),Je&&(0,Q.jsx)(o,{color:`error`,children:Je}),(0,Q.jsxs)(R,{direction:`row`,spacing:1,sx:{justifyContent:`flex-end`},children:[(0,Q.jsx)(z,{disabled:Ge,onClick:()=>He(null),children:X(C,`Hủy`,`Cancel`)}),(0,Q.jsx)(z,{variant:`contained`,disabled:Ge||Ve?.kind!==`archive`&&!Ue.trim(),onClick:()=>void Ot(),children:X(C,`Xác nhận`,`Confirm`)})]})]})}),(0,Q.jsx)(d,{open:!!Ze,onClose:()=>Qe(null),fullWidth:!0,maxWidth:`xs`,"aria-labelledby":`piagent-session-notice-title`,children:(0,Q.jsxs)(R,{spacing:2,sx:{p:3},children:[(0,Q.jsx)(o,{id:`piagent-session-notice-title`,variant:`h2`,children:Ze?.title}),(0,Q.jsx)(o,{color:`text.secondary`,children:Ze?.message}),(0,Q.jsx)(R,{direction:`row`,sx:{justifyContent:`flex-end`},children:(0,Q.jsx)(z,{variant:`contained`,onClick:()=>Qe(null),children:X(C,`Đóng`,`Close`)})})]})})]})})}var Ho={"session-revision-stale":[`Cuộc trò chuyện vừa thay đổi trong lúc gửi. Bấm Xác nhận lần nữa.`,`The chat changed while this was sent. Select Confirm again.`],"session-runtime-busy":[`Cuộc trò chuyện đang bận. Thử lại khi lượt này xong.`,`The chat is busy. Try again when this turn ends.`],"session-runtime-unavailable":[`Cuộc trò chuyện chưa mở được. Mở lại cuộc trò chuyện rồi thử lại.`,`The chat is not open. Open it again and retry.`],"session-unavailable":[`Không còn thấy cuộc trò chuyện này trong danh sách. Tải lại trang rồi thử lại.`,`This chat is no longer in the list. Reload the page and retry.`],"session-archived":[`Cuộc trò chuyện đã được lưu trữ. Bỏ lưu trữ trước.`,`The chat is archived. Unarchive it first.`],"session-command-expired":[`Yêu cầu chờ quá lâu nên đã hết hạn. Thử lại.`,`The request waited too long and expired. Try again.`],"gateway-command-response-timeout":[`Piagent chưa trả lời. Xem lại danh sách trước khi thử lại.`,`Piagent did not answer. Check the list before trying again.`]},Uo={rename:[`Chưa đổi được tên`,`Could not rename`],fork:[`Chưa tạo được nhánh`,`Could not fork`],archive:[`Chưa lưu trữ được`,`Could not archive`]};function Wo(e,t,n){let r=Ho[t];return`${X(n,...Uo[e])}: ${r?X(n,...r):X(n,`thử lại.`,`try again.`)} (${t})`}function Go(e,t=150){let n,r=!1,i=!1,a=!1,o=()=>{if(!a){if(r||n!==void 0){i=r;return}n=setTimeout(()=>{n=void 0,r=!0,e().catch(()=>void 0).finally(()=>{r=!1,i&&(i=!1,o())})},t)}};return{request:o,stop:()=>{a=!0,n!==void 0&&clearTimeout(n),n=void 0}}}var Ko=class extends Error{effectMayHaveOccurred;constructor(e,t){super(e),this.name=`GatewayCommandTransportError`,this.effectMayHaveOccurred=t}};async function qo(e,t,n=4){for(let r=1;;r+=1)try{return await e(t)}catch(e){if(r>=n||!(e instanceof Ko)||e.message!==`gateway-command-response-timeout`)throw e}}function Jo(e,t){return e instanceof Ko?e.effectMayHaveOccurred:t}function Yo(e,t,n=null,r=null){return!e||e.serial<=t||e.operationRef===n||r&&e.messageRequestId&&e.messageRequestId!==r?null:e}function Xo(e,t,n=null){return e&&e.operationRef!==t&&!(n&&e.messageRequestId&&e.messageRequestId!==n)?{operationRef:e.operationRef,complete:!1}:null}function Zo(e,t){return t?`observed`:e?.phase===`settled`||e?.phase===`accepted`?`confirmed`:e?.phase===`rejected`?`rejected`:`unconfirmed`}function Qo(e,t){let n=new AbortController,r=()=>void 0,i=new Promise(e=>{r=e}),a=setTimeout(()=>{n.abort(),r(null)},t);return{promise:Promise.race([e(n.signal).catch(()=>null),i]).finally(()=>clearTimeout(a)),cancel(){n.abort(),r(null),clearTimeout(a)}}}function $o(e,t,n,r,i){let a=e[t];if(!a||a.messageRequestId!==n||i===`unconfirmed`&&(a.delivery===`admitted`||a.operationRef))return e;let o=ii(a,i,r.operationRef,new Date().toISOString()),s=i===`unconfirmed`||r.complete||!!(r.operationRef&&a.operationRef===r.operationRef&&a.complete);return{...e,[t]:{...o,complete:s,abortable:i===`admitted`&&!s&&!!r.operationRef}}}async function es(e,t={}){let n=()=>{let t=Yo(e.readLocalObservation?.()??e.localObservation,e.afterSerial,e.priorOperationRef,e.messageRequestId);return t?{operationRef:t.operationRef,complete:t.complete}:null},r=n();if(r)return r;let i=t.timeoutMs??5e3,a=t.readLiveState??nt,o=t.readTranscript??Ge,s=[Qo(async t=>{let n=await a(t);return Xo(n?.state===`ready`?n.operations.find(t=>t.sessionRef===e.sessionRef):void 0,e.priorOperationRef,e.messageRequestId)},i),Qo(async t=>{let n=await o(e.sessionRef,null,50,t);if(n?.state!==`ready`)return null;let r=[...n.items].reverse().find(t=>t.role===`user`&&t.messageRequestId===e.messageRequestId);if(r)return{operationRef:r.agentOperationId,complete:nn(n.items,e.message,{operationRef:r.agentOperationId,messageRequestId:e.messageRequestId,startedAt:null})};let i=Date.parse(e.requestedAt),a=[...n.items].reverse().find(t=>t.role===`user`&&!t.messageRequestId&&cn(t.content.text,e.message)&&Date.parse(t.recordedAt)>=i);return a?{operationRef:a.agentOperationId,complete:nn(n.items,e.message,{operationRef:a.agentOperationId,messageRequestId:null,startedAt:e.requestedAt})}:null},i)],c=new Map(s.map((e,t)=>[t,e.promise.then(e=>({evidence:e,index:t}))]));try{for(;c.size>0;){let e=await Promise.race(c.values());if(c.delete(e.index),e.evidence)return e.evidence;let t=n();if(t)return t}return n()}finally{for(let e of s)e.cancel()}}function ts(e){return(0,$.useMemo)(()=>{let t=[],n=0,r=()=>{if(n&&cancelAnimationFrame(n),n=0,t.length===0)return;let r=t;t=[],e(e=>r.reduce((e,t)=>t(e),e))};return{now:t=>{r(),e(t)},later:e=>{t.push(e),n||=requestAnimationFrame(r)}}},[e])}function ns(e,t){if(e===t)return!0;try{return e!==void 0&&JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function rs(){let[e,t]=(0,$.useState)(),[n,r]=(0,$.useState)(),[i,a]=(0,$.useState)(`connecting`),[o,s]=(0,$.useState)({}),{now:c,later:l}=ts(s),[u,d]=(0,$.useState)({}),f=(0,$.useRef)(void 0),p=(0,$.useRef)(null),m=(0,$.useRef)(null),h=(0,$.useRef)({});h.current=o;let g=(0,$.useRef)(0),_=(0,$.useRef)(new Map),v=(0,$.useRef)(null),y=(0,$.useRef)(!0),b=(0,$.useRef)(0),x=(0,$.useRef)(0),S=(0,$.useRef)(new Map),C=(0,$.useCallback)(Oo,[]),w=(0,$.useCallback)(async(e={})=>{let n=++b.current;try{let[r,i]=await Promise.all([Ke(),nt().catch(()=>void 0)]),o=Kr(i,r.gatewayInstanceRef),s=!1;if(n>=x.current){x.current=n,f.current=r,t(e=>ns(e,r)?e:r);let l=v.current;l!==null&&l!==r.gatewayInstanceRef&&(y.current=!0),v.current=r.gatewayInstanceRef;let u=e.requireLiveState||y.current,h=p.current?.readyState===WebSocket.OPEN;if(a(qr(h,u)),!h&&i&&o!==null)m.current=o,C(r.gatewayInstanceRef,o),c(e=>oi(e,i)),d(ti(i)),y.current=!1,s=!0;else if(l!==r.gatewayInstanceRef){if(d({}),u)m.current=null;else{let e=null;try{e=window.sessionStorage.getItem(So)}catch{}m.current=Do(e,r.gatewayInstanceRef)}}}return e.requireLiveState&&!s?void 0:f.current??r}catch{a(`reconnecting`);return}},[C]),T=(0,$.useCallback)(e=>{let t=p.current;if(!t||t.readyState!==WebSocket.OPEN)return Promise.reject(new Ko(`gateway-not-connected`,!1));let n=ko(`request`);return new Promise((r,i)=>{let a=window.setTimeout(()=>{S.current.delete(n)&&i(new Ko(`gateway-command-response-timeout`,!0))},Co);S.current.set(n,{resolve:r,reject:i,timeout:a});try{t.send(JSON.stringify({schemaVersion:1,version:`piagent-gateway-protocol-v1`,messageType:`request`,requestId:n,method:`sessions.command`,params:{command:e}}))}catch(e){window.clearTimeout(a),S.current.delete(n),i(new Ko(e instanceof Error?e.message:`gateway-request-failed`,!1))}})},[]),E=(0,$.useCallback)((e,t,n,r,i,a)=>es({sessionRef:e,message:t,requestedAt:n,afterSerial:r,priorOperationRef:i,messageRequestId:a,readLocalObservation:()=>_.current.get(e)}),[]),D=(0,$.useCallback)(async e=>{let t=f.current,n=e.message.trim(),r=e.messageRequestId??ko(`message`);if(!t?.catalogRevision)throw Error(`catalog-unavailable`);if(!n)throw Error(`message-empty`);let i=t=>{if(!t.catalogRevision)throw Error(`catalog-unavailable`);let i=new Date;return qo(T,{schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:ko(`command`),idempotencyKey:ko(`idempotency`),action:`session.create`,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:null,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:null,payload:{projectRef:e.projectRef,placeRef:e.placeRef,modelRef:e.modelRef,thinkingLevel:e.thinkingLevel,workflow:e.workflow,message:n,messageRequestId:r,...e.permissionMode?{permissionMode:e.permissionMode}:{},...e.fast?{fast:!0}:{},...e.deferInitialMessage?{deferInitialMessage:!0}:{}}})},a=await i(t);if(Ao(a)){let e=await w();e?.catalogRevision&&(a=await i(e))}if(!(a.phase===`uncertain`&&a.sessionRef)&&a.phase!==`settled`||!a.sessionRef)throw Error(a.error?.code??a.resultCode);let o=a.settledAt??a.requestedAt;return a.phase===`settled`&&!e.deferInitialMessage&&c(e=>{let t=e[a.sessionRef];return{...e,[a.sessionRef]:{...t??{assistant:``,attachments:[],activities:[],complete:!1,error:null},user:n,operationRef:a.operationRef,messageRequestId:r,abortable:!t?.complete&&!!a.operationRef,startedAt:t?.startedAt??o,lastEventAt:t?.lastEventAt??o}}}),await w(),a},[w,T]),O=(0,$.useCallback)(async(e,t,n)=>{let r=f.current;if(!r?.catalogRevision)throw Error(`catalog-unavailable`);let i=t.trim();if(!i)throw Error(`message-empty`);let a=n?.messageRequestId??ko(`message`),o=n?.attachmentRefs??[],s=h.current[e.sessionRef],l=g.current,u=_.current.get(e.sessionRef)?.operationRef??s?.operationRef??null,d=new Date().toISOString();c(t=>({...t,[e.sessionRef]:ri(t[e.sessionRef],{message:i,attachments:n?.attachments??[],messageRequestId:a,submittedAt:d})}));let p=()=>c(t=>{let n=t[e.sessionRef],r=ai(n,s,a);if(r===n)return t;let i={...t};return r?i[e.sessionRef]=r:delete i[e.sessionRef],i}),m=(t,n)=>c(r=>$o(r,e.sessionRef,a,t,n)),v=d,y=!1;try{let t=t=>{let r=t.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t.catalogRevision||!r)throw Error(`session-unavailable`);let s=new Date;return v=s.toISOString(),{schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:ko(`command`),idempotencyKey:ko(`idempotency`),action:`session.send`,requestedAt:s.toISOString(),expiresAt:new Date(s.getTime()+wo).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{delivery:`new-operation`,message:i,messageRequestId:a,expectedOperationRef:null,attachmentRefs:o,...n?.workflow?{workflow:n.workflow}:{}}}},s=t(r);y=!0;let c=await T(s);if(Ao(c)){let e=await w();e?.catalogRevision&&(s=t(e),c=await T(s))}if(Zo(c,null)===`confirmed`)return m({operationRef:c.operationRef,complete:!1},`admitted`),w(),{state:`confirmed`,receipt:c};let d=await E(e.sessionRef,i,v,l,u,a),f=Zo(c,d);if(f===`observed`&&d)return m(d,`admitted`),w(),{state:`observed`,receipt:c};if(f===`unconfirmed`)return m({operationRef:null,complete:!0},`unconfirmed`),w(),{state:`unconfirmed`,receipt:c};throw p(),new Eo(c.error?.code??c.resultCode)}catch(t){if(t instanceof Eo)throw t;if(Jo(t,y)){let t=await E(e.sessionRef,i,v,l,u,a);return Zo(null,t)===`observed`&&t?(m(t,`admitted`),w(),{state:`observed`,receipt:null}):(m({operationRef:null,complete:!0},`unconfirmed`),w(),{state:`unconfirmed`,receipt:null})}throw p(),t}},[E,w,T]),k=(0,$.useCallback)(async e=>{let t=f.current,n=o[e.sessionRef]?.operationRef,r=t?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t?.catalogRevision||!r||!n||o[e.sessionRef]?.abortable===!1)throw Error(`operation-unavailable`);let i=t=>{let r=t.sessions.find(t=>t.sessionRef===e.sessionRef);if(!t.catalogRevision||!r)throw Error(`operation-unavailable`);let i=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:ko(`command`),idempotencyKey:ko(`idempotency`),action:`session.abort`,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:t.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{operationRef:n,clearQueued:!0}})},a=await i(t);if(Ao(a)){let[t,r]=await Promise.all([w(),nt().catch(()=>void 0)]);if(!t||!hi(r,t.gatewayInstanceRef,e.sessionRef,n))throw Error(`operation-unavailable`);a=await i(t)}if(a.phase!==`settled`)throw Error(a.error?.code??a.resultCode);return w(),a},[o,w,T]),A=(0,$.useCallback)(async e=>{let t=async t=>{let n=await w(),r=n?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!n?.catalogRevision||!r)throw Error(`session-unavailable`);let i=new Date,a=await T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:ko(`command`),idempotencyKey:ko(`idempotency`),action:t,requestedAt:i.toISOString(),expiresAt:new Date(i.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:n.catalogRevision,expectedSessionRevision:r.sessionRevision,payload:{}});if(a.phase!==`settled`)throw Error(a.error?.code??a.resultCode);return a};c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`restarting`}}));try{let n=(await w())?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!n)throw Error(`session-unavailable`);n.state===`gateway-owned`&&await t(`session.release`);let r=await t(`session.acquire`);return c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`recovered`}})),await w(),r}catch(t){throw c(t=>({...t,[e.sessionRef]:{...t[e.sessionRef]??{user:``,assistant:``,attachments:[],activities:[],operationRef:null,complete:!0,error:null},runtimeRecovery:`failed`}})),t}},[w,T]),j=(0,$.useCallback)(async(e,t,n)=>{let r=r=>{let i=r?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!r?.catalogRevision||!i)throw Error(`session-unavailable`);let a=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:ko(`command`),idempotencyKey:ko(`idempotency`),action:t,requestedAt:a.toISOString(),expiresAt:new Date(a.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:r.catalogRevision,expectedSessionRevision:i.sessionRevision,payload:n})},i=await r(f.current);for(let e=0;[`session.set-permission`,`session.set-fast`].includes(t)&&Ao(i)&&e<2;e++)i=await r(await w());if(i.phase!==`settled`)throw Error(i.error?.code??i.resultCode);return await w(),i},[w,T]),M=(0,$.useCallback)((e,t)=>j(e,`session.set-model`,{modelRef:t}),[j]),N=(0,$.useCallback)((e,t)=>j(e,`session.set-thinking`,{thinkingLevel:t}),[j]),P=(0,$.useCallback)((e,t)=>j(e,`session.set-permission`,{permissionMode:t}),[j]),F=(0,$.useCallback)((e,t)=>j(e,`session.set-fast`,{fast:t}),[j]),I=(0,$.useCallback)(async(e,t,n)=>{let r=r=>{let i=r?.sessions.find(t=>t.sessionRef===e.sessionRef);if(!r?.catalogRevision||!i)throw Error(`session-unavailable`);let a=new Date;return T({schemaVersion:1,version:`piagent-session-command-v1`,messageType:`command`,commandId:ko(`command`),idempotencyKey:ko(`idempotency`),action:t,requestedAt:a.toISOString(),expiresAt:new Date(a.getTime()+3e5).toISOString(),sessionRef:e.sessionRef,expectedCatalogRevision:r.catalogRevision,expectedSessionRevision:i.sessionRevision,payload:n})},i=await r(f.current);for(let e=0;t===`session.rename`&&Ao(i)&&e<2;e++)i=await r(await w());if(i.phase!==`settled`)throw Error(i.error?.code??i.resultCode);return await w(),i},[w,T]),L=(0,$.useCallback)((e,t)=>I(e,`session.rename`,{title:t}),[I]),ee=(0,$.useCallback)((e,t)=>I(e,`session.pin`,{pinned:t}),[I]),te=(0,$.useCallback)(e=>I(e,`session.archive`,{}),[I]),R=(0,$.useCallback)(e=>I(e,`session.unarchive`,{}),[I]),z=(0,$.useCallback)((e,t)=>I(e,`session.fork`,{entryRef:null,title:t}),[I]);return(0,$.useEffect)(()=>{let e=!1,t,n=0,i=!1,o=Go(()=>w()),s=o.request,u=(()=>{try{let e=window.localStorage.getItem(`piagent-gateway-client-ref`);if(e&&/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/.test(e))return e;let t=ko(`client`);return window.localStorage.setItem(`piagent-gateway-client-ref`,t),t}catch{return ko(`client`)}})(),h=()=>{if(e||ze())return;a(n===0?`connecting`:`reconnecting`);let o=window.location.protocol===`https:`?`wss:`:`ws:`,x=new WebSocket(`${o}//${window.location.host}/api/v1/gateway`,`piagent.gateway.v1`);p.current=x,Sn.attach(x);let w=window.setTimeout(()=>x.close(1008,`hello-timeout`),5e3);x.addEventListener(`open`,()=>x.send(JSON.stringify({schemaVersion:1,version:`piagent-gateway-protocol-v1`,messageType:`connect`,clientRef:u,minimumProtocol:1,maximumProtocol:1,lastEventSequence:m.current,catalogRevision:f.current?.catalogRevision??null}))),x.addEventListener(`message`,e=>{let t;try{t=JSON.parse(String(e.data))}catch{x.close(1007,`invalid-json`);return}if(!t||typeof t!=`object`){x.close(1008,`invalid-frame`);return}let o=t;if(o.messageType===`hello`){window.clearTimeout(w);let e=typeof o.capabilities?.gatewayInstanceRef==`string`?o.capabilities.gatewayInstanceRef:null;if(!e||v.current&&e!==v.current){m.current=null,y.current=!0,i=!0,x.close(To,`gateway-epoch-changed`);return}v.current=e,n=0,r(o.capabilities),a(`connected`);return}if(o.messageType===`response`){let e=S.current.get(String(o.requestId));if(!e)return;S.current.delete(String(o.requestId)),window.clearTimeout(e.timeout),o.ok===!0&&o.result?e.resolve(o.result):e.reject(new Ko(String(o.error?.code??`gateway-request-failed`),!1));return}if(o.messageType!==`event`||!Number.isSafeInteger(o.sequence))return;let u=o.payload,f=typeof o.generatedAt==`string`?o.generatedAt:new Date().toISOString(),p=typeof u.messageRequestId==`string`?u.messageRequestId:null,h=e=>e&&p&&e.messageRequestId&&e.messageRequestId!==p?void 0:e;if(o.kind===`resync.required`){y.current=!0,i=!0,x.close(To,`canonical-resync-required`);return}let b=Number(o.sequence),T=m.current;if(!(T!==null&&b<=T)){if(T!==null&&b!==T+1){y.current=!0,i=!0,x.close(To,`gateway-event-sequence-gap`);return}if(m.current=b,v.current&&C(v.current,b),typeof u?.sessionRef==`string`&&typeof u.operationRef==`string`&&[`runtime.changed`,`message.delta`,`tool.started`,`tool.completed`,`message.completed`,`operation.settled`].includes(String(o.kind))&&(g.current+=1,_.current.set(u.sessionRef,{serial:g.current,operationRef:u.operationRef,messageRequestId:p,complete:[`message.completed`,`operation.settled`].includes(String(o.kind))})),o.kind===`message.delta`&&typeof u?.sessionRef==`string`&&typeof u.delta==`string`&&l(e=>{let t=h(e[u.sessionRef]);return{...e,[u.sessionRef]:{...t??{user:``,assistant:``,attachments:[],activities:[],complete:!1,error:null},operationRef:u.operationRef,messageRequestId:p??t?.messageRequestId,abortable:!0,complete:!1,delivery:t?.user?`admitted`:t?.delivery,...Gr(t,u.messageRef,u.delta),startedAt:t?.startedAt??f,lastEventAt:f}}}),[`tool.started`,`tool.completed`].includes(String(o.kind))&&typeof u?.sessionRef==`string`&&typeof u.toolCallRef==`string`&&typeof u.toolLabel==`string`&&c(e=>{let t=h(e[u.sessionRef])??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef??null,abortable:!0,complete:!1,error:null,runtimeRecovery:null},n=o.kind===`tool.started`?`running`:u.isError===!0?`failed`:`completed`,r=t.activities.find(e=>e.toolCallRef===u.toolCallRef),i=ui(t.activities,{toolCallRef:u.toolCallRef,toolLabel:u.toolLabel,...typeof u.agent==`string`?{agent:u.agent}:{},...typeof u.detail==`string`?{detail:u.detail}:{},fileLabel:typeof u.fileLabel==`string`?u.fileLabel:r?.fileLabel??null,state:n,reasonCode:u.reasonCode??null,startedAt:r?.startedAt??f,finishedAt:n===`running`?null:f}),a=u.reasonCode===`runtime-restart-required`?`required`:t.runtimeRecovery;return{...e,[u.sessionRef]:{...t,operationRef:u.operationRef??t.operationRef,messageRequestId:p??t.messageRequestId,activities:i,complete:!1,delivery:t.user?`admitted`:t.delivery,runtimeRecovery:a,startedAt:t.startedAt??f,lastEventAt:f}}}),o.kind===`runtime.changed`&&typeof u?.sessionRef==`string`&&c(e=>{let t=[`running`,`paused`,`waiting-approval`].includes(String(u.liveState)),n=h(e[u.sessionRef])??(t&&typeof u.operationRef==`string`?{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,messageRequestId:p,abortable:!0,complete:!1,settlement:null,error:null,runtimeRecovery:null}:null);if(!n)return e;let r=u.reasonCode===`runtime-restart-required`?`restarting`:u.reasonCode===`runtime-restart-failed`?`failed`:[`required`,`restarting`].includes(String(n.runtimeRecovery))&&u.liveState===`idle`?`recovered`:n.runtimeRecovery;return t?{...e,[u.sessionRef]:{...n,operationRef:u.operationRef??n.operationRef,messageRequestId:p??n.messageRequestId,abortable:!0,complete:!1,settlement:null,delivery:n.user?`admitted`:n.delivery,runtimeRecovery:r,startedAt:n.startedAt??f,lastEventAt:f}}:!n.complete&&u.operationRef===null?{...e,[u.sessionRef]:{...n,assistant:``,activities:[],abortable:!1,complete:!0,settlement:`unknown`,messageRequestId:p??n.messageRequestId,error:u.reasonCode??`operation-settlement-unknown`,runtimeRecovery:r,lastEventAt:f}}:r===n.runtimeRecovery?e:{...e,[u.sessionRef]:{...n,runtimeRecovery:r}}}),o.kind===`message.completed`&&typeof u?.sessionRef==`string`&&c(e=>{let t=h(e[u.sessionRef]);return{...e,[u.sessionRef]:{...t??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,error:null},operationRef:u.operationRef,messageRequestId:p??t?.messageRequestId,abortable:!1,complete:!0,settlement:`completed`,delivery:t?.user?`admitted`:t?.delivery,error:null,lastEventAt:f}}}),o.kind===`operation.settled`&&typeof u?.sessionRef==`string`&&typeof u.operationRef==`string`){c(e=>{let t=h(e[u.sessionRef])??{user:``,assistant:``,attachments:[],activities:[],operationRef:u.operationRef,complete:!1,error:null,runtimeRecovery:null};return t.operationRef&&t.operationRef!==u.operationRef?e:{...e,[u.sessionRef]:{...ni(t,{operationRef:u.operationRef,settlement:u.settlement,reasonCode:u.reasonCode}),messageRequestId:p??t.messageRequestId,lastEventAt:f}}});let e=$r({operationRef:u.operationRef,settlement:u.settlement,reasonCode:u.reasonCode,settledAt:o.generatedAt,sequence:b});e&&d(t=>({...t,[u.sessionRef]:ei(t[u.sessionRef]??[],[e])}))}[`catalog.changed`,`session.changed`,`runtime.changed`,`message.completed`,`operation.settled`].includes(String(o.kind))&&s(),[`session.changed`,`tool.completed`,`operation.settled`].includes(String(o.kind))&&typeof u?.sessionRef==`string`&&window.dispatchEvent(new CustomEvent(`piagent-workspace-changed`,{detail:{sessionRef:u.sessionRef}}))}}),x.addEventListener(`close`,()=>{window.clearTimeout(w);for(let e of S.current.values())window.clearTimeout(e.timeout),e.reject(new Ko(`gateway-connection-lost`,!0));if(S.current.clear(),!e){if(a(`reconnecting`),i){i=!1,b();return}n+=1,t=window.setTimeout(h,Math.min(5e3,250*2**Math.min(n,5))*(.5+Math.random()))}}),x.addEventListener(`error`,()=>{})},b=async()=>{if(e||ze())return;let r=await w({requireLiveState:!0});if(!e){if(r){n=0,h();return}a(`reconnecting`),n+=1,t=window.setTimeout(()=>void b(),Math.min(5e3,250*2**Math.min(n,5))*(.5+Math.random()))}};(async()=>{let t=await Ve();if(!e){if(t===`failed`){a(`failed`);return}await b()}})();let x=()=>{!e&&document.visibilityState===`visible`&&w()};return document.addEventListener(`visibilitychange`,x),()=>{e=!0,t&&window.clearTimeout(t),o.stop();for(let e of S.current.values())window.clearTimeout(e.timeout),e.reject(new Ko(`gateway-client-unmounted`,!0));S.current.clear(),p.current?.close(1e3,`client-unmount`),document.removeEventListener(`visibilitychange`,x)}},[C,w]),{catalog:e,capabilities:n,connection:i,live:o,terminalActivities:u,refresh:w,create:D,send:O,abort:k,restart:A,setModel:M,setThinking:N,setPermission:P,setFast:F,rename:L,pin:ee,archive:te,unarchive:R,fork:z}}async function is(){let e=await fetch(`/api/v1/preferences`,{credentials:`same-origin`,headers:{Accept:`application/json`}});return e.ok?await e.json():null}async function as(e){let t=Le();t&&await Ie(`/api/v1/preferences`,{method:`POST`,credentials:`same-origin`,headers:{Accept:`application/json`,"Content-Type":`application/json`,"X-Piagent-CSRF":t},body:JSON.stringify(e)})}function os(e,t,n){let r=(0,$.useRef)(!1),i=(0,$.useRef)(t);i.current=t,(0,$.useEffect)(()=>{if(!e||r.current)return;let t=!1;return is().then(e=>{t||!e||(r.current=!0,e.locale&&n.setLocale(e.locale),e.themeId&&Me(e.themeId)&&n.setThemeId(e.themeId),(!e.locale||!e.themeId)&&as({...i.current,...e}).catch(()=>{}))}).catch(()=>{}),()=>{t=!0}},[e]),(0,$.useEffect)(()=>{r.current&&as(t).catch(()=>{})},[t.locale,t.themeId])}function ss(){let e=rs(),{locale:t,themeId:n,setLocale:r,setThemeId:i}=Ae();return os(!!e.catalog,{locale:t,themeId:n},{setLocale:r,setThemeId:i}),(0,Q.jsx)(Rt,{children:(0,Q.jsx)(Vo,{...e})})}export{ss as default};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Rn as n}from"./vendor-DNZbaWhT.js";import{t as r}from"./bootstrap-CedkNtRG.js";import{n as i,q as a}from"./api-BQS4Dtrr.js";import{n as o}from"./latest-request-DXcYQW86.js";import{t as s}from"./App-CU-wndsb.js";var c=e(n(),1),l=250,u=4e3,d=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;function f(e){return Math.min(l*2**Math.min(Math.max(0,e),16),u)}function p(e){return e instanceof i?e.status===408||e.status===409||e.status===423||e.status===425||e.status===429||e.status>=500?`retryable`:`terminal`:typeof DOMException<`u`&&e instanceof DOMException&&e.name===`AbortError`?`terminal`:e instanceof TypeError?`retryable`:`terminal`}function m(e,...t){for(let e of t)if(typeof e==`string`&&d.test(e))return e;return e}function h(e){if(!e||typeof e!=`object`)throw Error(`invalid-inspection-snapshot`);let t=e;if(t.schemaVersion!==1||t.version!==`piagent-webui-snapshot-v1`||typeof t.generatedAt!=`string`||[`identity`,`revision`,`capabilities`,`session`,`sourceChanges`,`activity`,`approvals`,`verification`,`usage`,`continuation`,`health`].some(e=>!t[e]||typeof t[e]!=`object`))throw Error(`invalid-inspection-snapshot`);let n=t.revision;if(typeof n.eventCursor!=`string`||!d.test(n.eventCursor))throw Error(`invalid-inspection-snapshot-cursor`);return e}function g(e=0){return{state:`cancelled`,readSequence:e}}async function _(e){let t=0;for(;!e.stopped();){let n=await e.read();if(e.stopped())return g(n.readSequence);if(n.state!==`retryable-error`)return n;await e.wait(f(t)),t=Math.min(t+1,16)}return g()}function v(){let[e,t]=(0,c.useState)(),[n,i]=(0,c.useState)(`connecting`),[s,l]=(0,c.useState)([]),u=(0,c.useRef)(()=>Promise.resolve(g())),d=(0,c.useRef)(()=>void 0),v=(0,c.useCallback)(async()=>{let e=await u.current();if(e.state===`committed`)return d.current(e.value),e.value},[]);return(0,c.useEffect)(()=>{let e=new AbortController,n,s,c,v,y,b=0,x=0,S=0,C=0,w=null,T=!1,E=!1,D=!1,O=!1,k=!1,A=!1,j=!1,M=!1,N=()=>{window.clearTimeout(s),s=void 0},P=()=>{window.clearTimeout(c),c=void 0},F=()=>{window.clearTimeout(v),v=void 0;let e=y;y=void 0,e?.()},I=e=>new Promise(t=>{let n=()=>{y===n&&(y=void 0,v=void 0),t()};y=n,v=window.setTimeout(n,e)}),L=()=>{b+=1,F()},R,z=()=>{M||j||(j=!0,L(),N(),P(),e.abort(),R.invalidate(),n?.close(),n=void 0,O=!1,i(`failed`))};R=new o({read:async()=>{let t=C;return{snapshot:h(await a(e.signal)),eventGenerationAtStart:t}},commit:({snapshot:e,eventGenerationAtStart:n})=>{M||j||(E=!0,D=!0,C===n&&(w=m(null,e.revision.eventCursor)),t(e),O&&i(`connected`))},classify:p});let B=async()=>{let e=await R.request();return e.state===`committed`?{...e,value:e.value.snapshot}:(e.state===`terminal-error`&&z(),e)};u.current=B;let V=()=>void 0,H=()=>void 0,U=()=>{if(M||j||!T||!E||n)return;L();let e=w?`?after=${encodeURIComponent(w)}`:``,t;try{t=new EventSource(`/api/v1/events${e}`,{withCredentials:!0})}catch{x=Math.min(x+1,16),i(`reconnecting`),V(f(x-1));return}n=t,O=!1,i(e=>e===`connecting`?`connecting`:`reconnecting`),t.onopen=()=>{M||j||n!==t||(O=!0,x=0,i(D?`connected`:`reconnecting`))},t.addEventListener(`runtime-event`,e=>{if(!(M||j||n!==t))try{let t=e,n=JSON.parse(t.data);if(!n||typeof n.kind!=`string`)return;let r=m(w,t.lastEventId,n.eventCursor);r!==w&&(w=r,C+=1),l(e=>[...e,n].slice(-500)),[`message.text-delta`,`message.thinking-state`,`activity.progress`].includes(String(n.kind))||H()}catch{}}),t.addEventListener(`resync-required`,()=>{M||j||n!==t||(t.close(),n=void 0,O=!1,N(),P(),A=!1,l([]),i(`reconnecting`),V(0,!0))}),t.onerror=()=>{M||j||n!==t||(t.close(),n=void 0,O=!1,D=!1,x=Math.min(x+1,16),i(`reconnecting`),V(f(x-1)))}};V=(e=0,t=!1)=>{if(M||j)return;let r=++b;F(),t&&l([]),i(E?`reconnecting`:`connecting`),(async()=>{if(e>0&&await I(e),M||j||b!==r||n)return;let t=await _({read:B,wait:I,stopped:()=>M||j||b!==r||!!n});M||j||b!==r||n||t.state===`committed`&&U()})()};let W=()=>{if(M||j||!n||c!==void 0)return;let e=f(S);S=Math.min(S+1,16),c=window.setTimeout(()=>{c=void 0,A=!0,G()},e)},G=async()=>{if(!(M||j||!n)){if(k){A=!0;return}k=!0;try{do{A=!1;let e=await B();if(M||j||!n||e.state===`cancelled`||e.state===`terminal-error`)return;if(e.state===`retryable-error`){D=!1,i(`reconnecting`),A=!0,W();return}S=0}while(A&&!M&&!j&&n)}finally{k=!1,A&&c===void 0&&s===void 0&&n&&!j&&!M&&(s=window.setTimeout(()=>{s=void 0,G()},80))}}};H=()=>{A=!0,!(M||j||k||c!==void 0||s!==void 0)&&(s=window.setTimeout(()=>{s=void 0,G()},80))};let K=e=>{!M&&!j&&T&&!n&&U()};return d.current=K,(async()=>{let e;try{e=await r()}catch{!M&&!j&&z();return}if(!(M||j)){if(e===`failed`){z();return}T=!0,V()}})(),()=>{M=!0,L(),e.abort(),R.invalidate(),n?.close(),N(),P(),d.current===K&&(d.current=()=>void 0),u.current===B&&(u.current=()=>Promise.resolve(g()))}},[]),{snapshot:e,connection:n,events:s,refreshSnapshot:v}}var y=t();function b(){let e=v();return(0,y.jsx)(s,{...e})}export{b as default};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Rn as n}from"./vendor-DNZbaWhT.js";import{t as r}from"./bootstrap-CedkNtRG.js";import{n as i,q as a}from"./api-BQS4Dtrr.js";import{n as o}from"./latest-request-DXcYQW86.js";import{t as s}from"./App-JrRb7jgn.js";var c=e(n(),1),l=250,u=4e3,d=/^[A-Za-z0-9][A-Za-z0-9._~-]{0,159}$/;function f(e){return Math.min(l*2**Math.min(Math.max(0,e),16),u)}function p(e){return e instanceof i?e.status===408||e.status===409||e.status===423||e.status===425||e.status===429||e.status>=500?`retryable`:`terminal`:typeof DOMException<`u`&&e instanceof DOMException&&e.name===`AbortError`?`terminal`:e instanceof TypeError?`retryable`:`terminal`}function m(e,...t){for(let e of t)if(typeof e==`string`&&d.test(e))return e;return e}function h(e){if(!e||typeof e!=`object`)throw Error(`invalid-inspection-snapshot`);let t=e;if(t.schemaVersion!==1||t.version!==`piagent-webui-snapshot-v1`||typeof t.generatedAt!=`string`||[`identity`,`revision`,`capabilities`,`session`,`sourceChanges`,`activity`,`approvals`,`verification`,`usage`,`continuation`,`health`].some(e=>!t[e]||typeof t[e]!=`object`))throw Error(`invalid-inspection-snapshot`);let n=t.revision;if(typeof n.eventCursor!=`string`||!d.test(n.eventCursor))throw Error(`invalid-inspection-snapshot-cursor`);return e}function g(e=0){return{state:`cancelled`,readSequence:e}}async function _(e){let t=0;for(;!e.stopped();){let n=await e.read();if(e.stopped())return g(n.readSequence);if(n.state!==`retryable-error`)return n;await e.wait(f(t)),t=Math.min(t+1,16)}return g()}function v(){let[e,t]=(0,c.useState)(),[n,i]=(0,c.useState)(`connecting`),[s,l]=(0,c.useState)([]),u=(0,c.useRef)(()=>Promise.resolve(g())),d=(0,c.useRef)(()=>void 0),v=(0,c.useCallback)(async()=>{let e=await u.current();if(e.state===`committed`)return d.current(e.value),e.value},[]);return(0,c.useEffect)(()=>{let e=new AbortController,n,s,c,v,y,b=0,x=0,S=0,C=0,w=null,T=!1,E=!1,D=!1,O=!1,k=!1,A=!1,j=!1,M=!1,N=()=>{window.clearTimeout(s),s=void 0},P=()=>{window.clearTimeout(c),c=void 0},F=()=>{window.clearTimeout(v),v=void 0;let e=y;y=void 0,e?.()},I=e=>new Promise(t=>{let n=()=>{y===n&&(y=void 0,v=void 0),t()};y=n,v=window.setTimeout(n,e)}),L=()=>{b+=1,F()},R,z=()=>{M||j||(j=!0,L(),N(),P(),e.abort(),R.invalidate(),n?.close(),n=void 0,O=!1,i(`failed`))};R=new o({read:async()=>{let t=C;return{snapshot:h(await a(e.signal)),eventGenerationAtStart:t}},commit:({snapshot:e,eventGenerationAtStart:n})=>{M||j||(E=!0,D=!0,C===n&&(w=m(null,e.revision.eventCursor)),t(e),O&&i(`connected`))},classify:p});let B=async()=>{let e=await R.request();return e.state===`committed`?{...e,value:e.value.snapshot}:(e.state===`terminal-error`&&z(),e)};u.current=B;let V=()=>void 0,H=()=>void 0,U=()=>{if(M||j||!T||!E||n)return;L();let e=w?`?after=${encodeURIComponent(w)}`:``,t;try{t=new EventSource(`/api/v1/events${e}`,{withCredentials:!0})}catch{x=Math.min(x+1,16),i(`reconnecting`),V(f(x-1));return}n=t,O=!1,i(e=>e===`connecting`?`connecting`:`reconnecting`),t.onopen=()=>{M||j||n!==t||(O=!0,x=0,i(D?`connected`:`reconnecting`))},t.addEventListener(`runtime-event`,e=>{if(!(M||j||n!==t))try{let t=e,n=JSON.parse(t.data);if(!n||typeof n.kind!=`string`)return;let r=m(w,t.lastEventId,n.eventCursor);r!==w&&(w=r,C+=1),l(e=>[...e,n].slice(-500)),[`message.text-delta`,`message.thinking-state`,`activity.progress`].includes(String(n.kind))||H()}catch{}}),t.addEventListener(`resync-required`,()=>{M||j||n!==t||(t.close(),n=void 0,O=!1,N(),P(),A=!1,l([]),i(`reconnecting`),V(0,!0))}),t.onerror=()=>{M||j||n!==t||(t.close(),n=void 0,O=!1,D=!1,x=Math.min(x+1,16),i(`reconnecting`),V(f(x-1)))}};V=(e=0,t=!1)=>{if(M||j)return;let r=++b;F(),t&&l([]),i(E?`reconnecting`:`connecting`),(async()=>{if(e>0&&await I(e),M||j||b!==r||n)return;let t=await _({read:B,wait:I,stopped:()=>M||j||b!==r||!!n});M||j||b!==r||n||t.state===`committed`&&U()})()};let W=()=>{if(M||j||!n||c!==void 0)return;let e=f(S);S=Math.min(S+1,16),c=window.setTimeout(()=>{c=void 0,A=!0,G()},e)},G=async()=>{if(!(M||j||!n)){if(k){A=!0;return}k=!0;try{do{A=!1;let e=await B();if(M||j||!n||e.state===`cancelled`||e.state===`terminal-error`)return;if(e.state===`retryable-error`){D=!1,i(`reconnecting`),A=!0,W();return}S=0}while(A&&!M&&!j&&n)}finally{k=!1,A&&c===void 0&&s===void 0&&n&&!j&&!M&&(s=window.setTimeout(()=>{s=void 0,G()},80))}}};H=()=>{A=!0,!(M||j||k||c!==void 0||s!==void 0)&&(s=window.setTimeout(()=>{s=void 0,G()},80))};let K=e=>{!M&&!j&&T&&!n&&U()};return d.current=K,(async()=>{let e;try{e=await r()}catch{!M&&!j&&z();return}if(!(M||j)){if(e===`failed`){z();return}T=!0,V()}})(),()=>{M=!0,L(),e.abort(),R.invalidate(),n?.close(),N(),P(),d.current===K&&(d.current=()=>void 0),u.current===B&&(u.current=()=>Promise.resolve(g()))}},[]),{snapshot:e,connection:n,events:s,refreshSnapshot:v}}var y=t();function b(){let e=v();return(0,y.jsx)(s,{...e})}export{b as default};
@@ -1 +1 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Rn as n,Tt as r}from"./vendor-DNZbaWhT.js";import{i}from"./ui-preferences-OfS30-ZV.js";import{t as a}from"./ActivityPanel-Bv-jc1s3.js";import{a as o,i as s,n as c,o as l,r as u}from"./App-CU-wndsb.js";var d=e(n(),1),f=t();function p({active:e,snapshot:t,sessionRef:n,terminalActivities:p,liveActivities:m,refresh:h,findings:g,onSendComments:_}){let{locale:v}=i();return(0,d.useEffect)(()=>{let e=e=>{e.detail?.sessionRef===n&&h()};return window.addEventListener(`piagent-workspace-saved`,e),()=>window.removeEventListener(`piagent-workspace-saved`,e)},[n,h]),e===`source`?(0,f.jsx)(l,{snapshot:t,sessionRef:n,refreshSnapshot:h,findings:g,onSendComments:_}):e===`documents`?(0,f.jsx)(o,{sessionRef:n}):e===`activity`?(0,f.jsx)(a,{snapshot:t,sessionRef:n,terminalActivities:p,liveActivities:m}):(0,f.jsxs)(r,{spacing:2.25,children:[(0,f.jsx)(c,{snapshot:t,locale:v}),(0,f.jsx)(u,{snapshot:t,locale:v}),(0,f.jsx)(s,{snapshot:t})]})}export{p as SessionAgentWorkspace};
1
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Rn as n,Tt as r}from"./vendor-DNZbaWhT.js";import{i}from"./ui-preferences-OfS30-ZV.js";import{t as a}from"./ActivityPanel-CmjxPmNT.js";import{a as o,i as s,n as c,o as l,r as u}from"./App-JrRb7jgn.js";var d=e(n(),1),f=t();function p({active:e,snapshot:t,sessionRef:n,terminalActivities:p,liveActivities:m,refresh:h,findings:g,onSendComments:_}){let{locale:v}=i();return(0,d.useEffect)(()=>{let e=e=>{e.detail?.sessionRef===n&&h()};return window.addEventListener(`piagent-workspace-saved`,e),()=>window.removeEventListener(`piagent-workspace-saved`,e)},[n,h]),e===`source`?(0,f.jsx)(l,{snapshot:t,sessionRef:n,refreshSnapshot:h,findings:g,onSendComments:_}):e===`documents`?(0,f.jsx)(o,{sessionRef:n}):e===`activity`?(0,f.jsx)(a,{snapshot:t,sessionRef:n,terminalActivities:p,liveActivities:m}):(0,f.jsxs)(r,{spacing:2.25,children:[(0,f.jsx)(c,{snapshot:t,locale:v}),(0,f.jsx)(u,{snapshot:t,locale:v}),(0,f.jsx)(s,{snapshot:t})]})}export{p as SessionAgentWorkspace};
@@ -1,2 +1,2 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ActivityPanel-Bv-jc1s3.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-DNZbaWhT.js","assets/ui-preferences-OfS30-ZV.js","assets/api-BQS4Dtrr.js","assets/bootstrap-CedkNtRG.js","assets/view-model-CWNiS4JN.js","assets/SessionAgentWorkspace-0Xowe-sG.js","assets/App-CU-wndsb.js","assets/index-C3CJv1wM.js","assets/index-CjM70M7D.css","assets/workspace-navigation-DW8zhH6U.js","assets/AttachmentImage-eZKqLYZ2.js","assets/transcript-view-model-acWtHGyE.js","assets/LineReview-CB3mQe7m.js"])))=>i.map(i=>d[i]);
2
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Bt as n,Gt as r,Ht as i,It as a,Kt as o,Nt as s,Pt as c,Rn as l,Rt as u,Tt as d,Ut as f,Vt as p,Wt as m,_t as h,fn as g,jt as _,kt as v,l as y,qt as b,s as x}from"./vendor-DNZbaWhT.js";import{i as S,n as C}from"./ui-preferences-OfS30-ZV.js";import{n as w,t as T}from"./index-C3CJv1wM.js";var E=e(l(),1),D=t(),O=`min(44vw, 860px)`,k=(0,E.lazy)(async()=>({default:(await T(async()=>{let{ActivityPanel:e}=await import(`./ActivityPanel-Bv-jc1s3.js`).then(e=>e.n);return{ActivityPanel:e}},__vite__mapDeps([0,1,2,3,4,5,6]))).ActivityPanel})),A=(0,E.lazy)(async()=>({default:(await T(async()=>{let{SessionAgentWorkspace:e}=await import(`./SessionAgentWorkspace-0Xowe-sG.js`);return{SessionAgentWorkspace:e}},__vite__mapDeps([7,1,2,3,0,4,5,6,8,9,10,11,12,13,14]))).SessionAgentWorkspace}));function j({open:e,active:t,snapshot:l,state:T,sessionRef:E,terminalActivities:j,liveActivities:M,onClose:N,onActive:P,refresh:F,findings:I,onSendComments:L}){let{locale:R}=S(),z=g(),B=s(z.breakpoints.up(`xl`)),V=l?.sourceChanges.workingTree.counts.files??0,H=M===void 0?l?.activity.running.length??0:M.filter(e=>e.state===`running`).length;return(0,D.jsxs)(c,{anchor:`right`,variant:B?`persistent`:`temporary`,open:e,onClose:N,sx:{"& .MuiDrawer-paper":{width:{xs:`100%`,sm:`min(88vw, 980px)`,xl:O},bgcolor:`background.default`}},children:[(0,D.jsxs)(m,{sx:{position:`sticky`,top:0,zIndex:3,bgcolor:`background.paper`,borderBottom:1,borderColor:`divider`},children:[(0,D.jsxs)(d,{direction:`row`,sx:{minHeight:64,px:{xs:1.5,md:2},alignItems:`center`,gap:1},children:[(0,D.jsxs)(m,{sx:{flex:1,minWidth:0},children:[(0,D.jsx)(n,{sx:{fontWeight:650},children:C(R,`Agent Inspector`,`Agent Inspector`)}),(0,D.jsx)(n,{variant:`caption`,color:`text.secondary`,children:C(R,`Thay đổi trong Git · tài liệu · hoạt động của agent`,`Git changes · documents · agent activity`)})]}),(0,D.jsx)(h,{title:C(R,`Làm mới Inspector`,`Refresh Inspector`),children:(0,D.jsx)(o,{onClick:()=>void F(),children:(0,D.jsx)(v,{fontSize:`small`})})}),(0,D.jsx)(o,{"aria-label":C(R,`Đóng Inspector`,`Close Inspector`),onClick:N,children:(0,D.jsx)(u,{})})]}),(0,D.jsxs)(p,{value:t,onChange:(e,t)=>P(t),variant:`scrollable`,scrollButtons:`auto`,children:[(0,D.jsx)(i,{value:`task`,icon:(0,D.jsx)(y,{}),iconPosition:`start`,label:l?.task?`${C(R,`Task`,`Task`)} · ${l.task.progress.completed}/${l.task.progress.total}`:C(R,`Task`,`Task`)}),(0,D.jsx)(i,{value:`source`,icon:(0,D.jsx)(_,{}),iconPosition:`start`,label:`Source Changes${V?` · ${V}`:``}`}),(0,D.jsx)(i,{value:`documents`,icon:(0,D.jsx)(x,{}),iconPosition:`start`,label:C(R,`Tài liệu`,`Documents`)}),(0,D.jsx)(i,{value:`activity`,icon:(0,D.jsx)(a,{}),iconPosition:`start`,label:`${C(R,`Activity`,`Activity`)}${H?` · ${H}`:``}`})]})]}),(0,D.jsx)(w,{locale:R,children:T===`loading`?(0,D.jsxs)(d,{sx:{alignItems:`center`,py:12},spacing:1.5,children:[(0,D.jsx)(b,{size:25}),(0,D.jsx)(n,{color:`text.secondary`,children:C(R,`Đang dựng Inspector từ session và Git…`,`Building the Inspector from the session and Git…`)})]}):(T===`error`||!l)&&E&&t===`activity`&&j?.length?(0,D.jsx)(m,{sx:{p:{xs:1.5,sm:2.5,xl:3},maxWidth:1500,mx:`auto`,width:`100%`},children:(0,D.jsx)(k,{sessionRef:E,terminalActivities:j,liveActivities:M})}):T===`error`||!l||!E?(0,D.jsxs)(d,{sx:{p:3,maxWidth:720},spacing:2,children:[(0,D.jsx)(r,{severity:`warning`,children:C(R,`Không thể dựng Inspector cho session này. Chat vẫn an toàn; hãy kiểm tra project còn tồn tại và thử làm mới.`,`The Inspector could not be built for this session. Chat remains safe; check that the project still exists and refresh.`)}),(0,D.jsx)(f,{variant:`outlined`,onClick:()=>void F(),children:C(R,`Thử lại`,`Try again`)})]}):(0,D.jsx)(m,{sx:{p:t===`source`?{xs:1,md:1.5}:{xs:1.5,sm:2.5,xl:3},maxWidth:t===`source`?`none`:1500,mx:`auto`,width:`100%`},children:(0,D.jsx)(A,{active:t,snapshot:l,sessionRef:E,terminalActivities:j,liveActivities:M,refresh:F,findings:I,onSendComments:L})})},E)]})}export{j as SessionInspectorDrawer};
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/ActivityPanel-CmjxPmNT.js","assets/rolldown-runtime-hePW80VL.js","assets/vendor-DNZbaWhT.js","assets/ui-preferences-OfS30-ZV.js","assets/api-BQS4Dtrr.js","assets/bootstrap-CedkNtRG.js","assets/view-model-CWNiS4JN.js","assets/SessionAgentWorkspace-RQ0N65d9.js","assets/App-JrRb7jgn.js","assets/index-fUpioGMZ.js","assets/index-De7bIeMc.css","assets/workspace-navigation-DW8zhH6U.js","assets/AttachmentImage-eZKqLYZ2.js","assets/transcript-view-model-acWtHGyE.js","assets/LineReview-CB3mQe7m.js"])))=>i.map(i=>d[i]);
2
+ import{r as e}from"./rolldown-runtime-hePW80VL.js";import{An as t,Bt as n,Gt as r,Ht as i,It as a,Kt as o,Nt as s,Pt as c,Rn as l,Rt as u,Tt as d,Ut as f,Vt as p,Wt as m,_t as h,fn as g,jt as _,kt as v,l as y,qt as b,s as x}from"./vendor-DNZbaWhT.js";import{i as S,n as C}from"./ui-preferences-OfS30-ZV.js";import{n as w,t as T}from"./index-fUpioGMZ.js";var E=e(l(),1),D=t(),O=`min(44vw, 860px)`,k=(0,E.lazy)(async()=>({default:(await T(async()=>{let{ActivityPanel:e}=await import(`./ActivityPanel-CmjxPmNT.js`).then(e=>e.n);return{ActivityPanel:e}},__vite__mapDeps([0,1,2,3,4,5,6]))).ActivityPanel})),A=(0,E.lazy)(async()=>({default:(await T(async()=>{let{SessionAgentWorkspace:e}=await import(`./SessionAgentWorkspace-RQ0N65d9.js`);return{SessionAgentWorkspace:e}},__vite__mapDeps([7,1,2,3,0,4,5,6,8,9,10,11,12,13,14]))).SessionAgentWorkspace}));function j({open:e,active:t,snapshot:l,state:T,sessionRef:E,terminalActivities:j,liveActivities:M,onClose:N,onActive:P,refresh:F,findings:I,onSendComments:L}){let{locale:R}=S(),z=g(),B=s(z.breakpoints.up(`xl`)),V=l?.sourceChanges.workingTree.counts.files??0,H=M===void 0?l?.activity.running.length??0:M.filter(e=>e.state===`running`).length;return(0,D.jsxs)(c,{anchor:`right`,variant:B?`persistent`:`temporary`,open:e,onClose:N,sx:{"& .MuiDrawer-paper":{width:{xs:`100%`,sm:`min(88vw, 980px)`,xl:O},bgcolor:`background.default`}},children:[(0,D.jsxs)(m,{sx:{position:`sticky`,top:0,zIndex:3,bgcolor:`background.paper`,borderBottom:1,borderColor:`divider`},children:[(0,D.jsxs)(d,{direction:`row`,sx:{minHeight:64,px:{xs:1.5,md:2},alignItems:`center`,gap:1},children:[(0,D.jsxs)(m,{sx:{flex:1,minWidth:0},children:[(0,D.jsx)(n,{sx:{fontWeight:650},children:C(R,`Agent Inspector`,`Agent Inspector`)}),(0,D.jsx)(n,{variant:`caption`,color:`text.secondary`,children:C(R,`Thay đổi trong Git · tài liệu · hoạt động của agent`,`Git changes · documents · agent activity`)})]}),(0,D.jsx)(h,{title:C(R,`Làm mới Inspector`,`Refresh Inspector`),children:(0,D.jsx)(o,{onClick:()=>void F(),children:(0,D.jsx)(v,{fontSize:`small`})})}),(0,D.jsx)(o,{"aria-label":C(R,`Đóng Inspector`,`Close Inspector`),onClick:N,children:(0,D.jsx)(u,{})})]}),(0,D.jsxs)(p,{value:t,onChange:(e,t)=>P(t),variant:`scrollable`,scrollButtons:`auto`,children:[(0,D.jsx)(i,{value:`task`,icon:(0,D.jsx)(y,{}),iconPosition:`start`,label:l?.task?`${C(R,`Task`,`Task`)} · ${l.task.progress.completed}/${l.task.progress.total}`:C(R,`Task`,`Task`)}),(0,D.jsx)(i,{value:`source`,icon:(0,D.jsx)(_,{}),iconPosition:`start`,label:`Source Changes${V?` · ${V}`:``}`}),(0,D.jsx)(i,{value:`documents`,icon:(0,D.jsx)(x,{}),iconPosition:`start`,label:C(R,`Tài liệu`,`Documents`)}),(0,D.jsx)(i,{value:`activity`,icon:(0,D.jsx)(a,{}),iconPosition:`start`,label:`${C(R,`Activity`,`Activity`)}${H?` · ${H}`:``}`})]})]}),(0,D.jsx)(w,{locale:R,children:T===`loading`?(0,D.jsxs)(d,{sx:{alignItems:`center`,py:12},spacing:1.5,children:[(0,D.jsx)(b,{size:25}),(0,D.jsx)(n,{color:`text.secondary`,children:C(R,`Đang dựng Inspector từ session và Git…`,`Building the Inspector from the session and Git…`)})]}):(T===`error`||!l)&&E&&t===`activity`&&j?.length?(0,D.jsx)(m,{sx:{p:{xs:1.5,sm:2.5,xl:3},maxWidth:1500,mx:`auto`,width:`100%`},children:(0,D.jsx)(k,{sessionRef:E,terminalActivities:j,liveActivities:M})}):T===`error`||!l||!E?(0,D.jsxs)(d,{sx:{p:3,maxWidth:720},spacing:2,children:[(0,D.jsx)(r,{severity:`warning`,children:C(R,`Không thể dựng Inspector cho session này. Chat vẫn an toàn; hãy kiểm tra project còn tồn tại và thử làm mới.`,`The Inspector could not be built for this session. Chat remains safe; check that the project still exists and refresh.`)}),(0,D.jsx)(f,{variant:`outlined`,onClick:()=>void F(),children:C(R,`Thử lại`,`Try again`)})]}):(0,D.jsx)(m,{sx:{p:t===`source`?{xs:1,md:1.5}:{xs:1.5,sm:2.5,xl:3},maxWidth:t===`source`?`none`:1500,mx:`auto`,width:`100%`},children:(0,D.jsx)(A,{active:t,snapshot:l,sessionRef:E,terminalActivities:j,liveActivities:M,refresh:F,findings:I,onSendComments:L})})},E)]})}export{j as SessionInspectorDrawer};