@jingyi0605/codingns 0.5.0 → 0.5.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.
- package/dist/public/assets/AdaptiveButlerPage-SffCV4Vb.js +3 -0
- package/dist/public/assets/App-WOLwMld_.js +30 -0
- package/dist/public/assets/{BootstrapPage-Vu5oEJ8z.js → BootstrapPage--zExdgfM.js} +1 -1
- package/dist/public/assets/{ConversationPage-Cjpg6g0J.js → ConversationPage-D9pzRmOg.js} +2 -2
- package/dist/public/assets/{DesktopDetachPreviewPage-BgeEqbc5.js → DesktopDetachPreviewPage-DvI9CIKi.js} +1 -1
- package/dist/public/assets/{DesktopWindowPage-1WelvxdH.js → DesktopWindowPage-D8FpOSLE.js} +1 -1
- package/dist/public/assets/FileContextPanel-C8T7oqRN.js +1 -0
- package/dist/public/assets/GitSidebar-Bze7DNnc.js +6 -0
- package/dist/public/assets/{MobileCreateSessionSheet-DLq5qPkx.js → MobileCreateSessionSheet-CXSKMnYn.js} +1 -1
- package/dist/public/assets/MobileSheet-Gzc14EpR.js +1 -0
- package/dist/public/assets/{MobileTopHeaderFrame-DArgZI7L.js → MobileTopHeaderFrame-BWorAJ1C.js} +1 -1
- package/dist/public/assets/{MobileWorkspaceSwitcherHeader-0ywJKfBQ.js → MobileWorkspaceSwitcherHeader-DOr4pTUq.js} +1 -1
- package/dist/public/assets/{ServerSettingsModal-izoYMx9U.js → ServerSettingsModal-BYB0GvTl.js} +1 -1
- package/dist/public/assets/{SessionIndexPage-C5aG8FIv.js → SessionIndexPage-CR3IARXX.js} +1 -1
- package/dist/public/assets/SettingsPage-B_BQtnwE.js +1 -0
- package/dist/public/assets/TerminalManagerPanel-PQ-EM64j.js +1 -0
- package/dist/public/assets/{TerminalPage-CtKXIU0h.js → TerminalPage-CvnHXBhw.js} +12 -12
- package/dist/public/assets/{TerminalRuntimeFallbackModal-CRhOQOsT.js → TerminalRuntimeFallbackModal-D7Aq186N.js} +1 -1
- package/dist/public/assets/{ToolFilesPage-DcYPsS-e.js → ToolFilesPage-Qzkc6K2I.js} +1 -1
- package/dist/public/assets/{ToolGitPage-CsPl89ty.js → ToolGitPage-BdNDN-cV.js} +1 -1
- package/dist/public/assets/{ToolProcessesPage-D0dvR8xK.js → ToolProcessesPage-EXJ9DHWI.js} +1 -1
- package/dist/public/assets/{ToolsHomePage-4fP-KRiv.js → ToolsHomePage-CjF3CWzR.js} +1 -1
- package/dist/public/assets/{WorkbenchLandingPage-kvlfyxRo.js → WorkbenchLandingPage-DZPk4SmX.js} +1 -1
- package/dist/public/assets/WorkbenchLayout-rwQib5In.js +3 -0
- package/dist/public/assets/{WorkbenchModal-Ctob14VR.js → WorkbenchModal-B09hC9b5.js} +1 -1
- package/dist/public/assets/WorkbenchShellRoute-Cerk5uK7.js +1 -0
- package/dist/public/assets/WorkbenchShellRoute-DsW4mBTX.css +1 -0
- package/dist/public/assets/{WorkspaceDebugDetailPage-Com5kEXJ.js → WorkspaceDebugDetailPage-Bcq8s-Ma.js} +1 -1
- package/dist/public/assets/WorkspaceDetailPage-DNAa8pKr.js +1 -0
- package/dist/public/assets/WorkspaceHomePage-BoiLuACV.js +1 -0
- package/dist/public/assets/client-runtime-manager-CRQ-F5d2.js +1 -0
- package/dist/public/assets/{default-session-permission-mode-CcGwR4Kk.js → default-session-permission-mode-D0wZ9Jek.js} +1 -1
- package/dist/public/assets/{file-tree-icon-UFVoVzhM.js → file-tree-icon-Dp_xhVfD.js} +14 -14
- package/dist/public/assets/index-C2G8Gmf1.js +42 -0
- package/dist/public/assets/{index-_52jxu4a.css → index-CpPTUeA3.css} +1 -1
- package/dist/public/assets/{preferences-service-KIYeE2gk.js → preferences-service-gOt2ZjKZ.js} +1 -1
- package/dist/public/assets/{session-runtime-machine-0KNSSPp5.js → session-runtime-machine-Dq3pW-UF.js} +8 -8
- package/dist/public/assets/{terminal-runtime-meta-AWXJpN4r.js → terminal-runtime-meta-BMT-rSEe.js} +1 -1
- package/dist/public/assets/{useRegisteredDebugTemplates-DBDRdptr.js → useRegisteredDebugTemplates-zMcEOGca.js} +1 -1
- package/dist/public/index.html +2 -2
- package/dist/server/modules/client/client-controller.js +1 -1
- package/dist/server/modules/client/client-controller.js.map +1 -1
- package/dist/server/modules/client/client-service.d.ts +16 -2
- package/dist/server/modules/client/client-service.js +21 -3
- package/dist/server/modules/client/client-service.js.map +1 -1
- package/dist/server/modules/relay-tunnel/relay-tunnel-service.d.ts +2 -1
- package/dist/server/modules/relay-tunnel/relay-tunnel-service.js +203 -8
- package/dist/server/modules/relay-tunnel/relay-tunnel-service.js.map +1 -1
- package/dist/server/modules/workbench/snapshot-revision.d.ts +4 -0
- package/dist/server/modules/workbench/snapshot-revision.js +13 -0
- package/dist/server/modules/workbench/snapshot-revision.js.map +1 -0
- package/dist/server/modules/workbench/workbench-service.d.ts +1 -0
- package/dist/server/modules/workbench/workbench-service.js +3 -2
- package/dist/server/modules/workbench/workbench-service.js.map +1 -1
- package/dist/server/modules/workbench/workspace-panel-snapshot-service.d.ts +6 -1
- package/dist/server/modules/workbench/workspace-panel-snapshot-service.js +10 -8
- package/dist/server/modules/workbench/workspace-panel-snapshot-service.js.map +1 -1
- package/dist/server/server/create-server.js +1 -1
- package/dist/server/server/create-server.js.map +1 -1
- package/dist/server/types/domain.d.ts +9 -0
- package/dist/server/ws/workbench-ws-hub.js +135 -33
- package/dist/server/ws/workbench-ws-hub.js.map +1 -1
- package/package.json +1 -1
- package/dist/public/assets/AdaptiveButlerPage-R-XZw7pd.js +0 -3
- package/dist/public/assets/App-DkvE5EyM.js +0 -30
- package/dist/public/assets/FileContextPanel-D_ghXJuW.js +0 -1
- package/dist/public/assets/GitSidebar-D9f9Jxwr.js +0 -6
- package/dist/public/assets/MobileSheet-DLg-gX1t.js +0 -1
- package/dist/public/assets/SettingsPage-HJIC-P-4.js +0 -1
- package/dist/public/assets/TerminalManagerPanel-DpyUTo9k.js +0 -1
- package/dist/public/assets/WorkbenchLayout-ByFw4eeu.js +0 -3
- package/dist/public/assets/WorkbenchShellRoute-BUITtdAg.css +0 -1
- package/dist/public/assets/WorkbenchShellRoute-Kw7JEZI3.js +0 -1
- package/dist/public/assets/WorkspaceDetailPage-D0Lrx4Uz.js +0 -1
- package/dist/public/assets/WorkspaceHomePage-wR8d3aP9.js +0 -1
- package/dist/public/assets/index-Byp9hJ0c.js +0 -42
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
var _i=Object.defineProperty;var Vi=(e,n,l)=>n in e?_i(e,n,{enumerable:!0,configurable:!0,writable:!0,value:l}):e[n]=l;var le=(e,n,l)=>Vi(e,typeof n!="symbol"?n+"":n,l);import{j as t,t as s,b as u}from"./index-C2G8Gmf1.js";import{g as yl,a3 as qi,a4 as Ks,a5 as zi,a6 as Wi,a7 as Ki,X as U,a8 as Yi,a9 as Xi,f as ts,aa as Gi,U as Zi,u as us,ab as Tn,ac as Ys,ad as Qi,M as Al,N as jl,ae as Ji,af as er,b as Cn,ag as Rn,ah as kn,ai as Cl,aj as tr,ak as nr,al as sr,am as lr,B as En,an as cs,h as wl,l as ns,ao as Il,ap as ss,aq as ls,ar as Nl,o as is,_ as ir}from"./WorkbenchLayout-rwQib5In.js";import{d as rr,c as Tl,u as Rl,e as kl,g as ar}from"./App-WOLwMld_.js";import{C as or,D as ur,y as Xs,F as cr,H as dr,o as mr,P as El,i as rs,j as Ll,M as hr}from"./MobileSheet-Gzc14EpR.js";import{t as Pl,R as br,P as Ml,d as Fl,C as Dl}from"./session-runtime-machine-Dq3pW-UF.js";import{FileContextPanel as fr}from"./FileContextPanel-C8T7oqRN.js";import{W as $e}from"./WorkbenchModal-B09hC9b5.js";import{s as Ol}from"./butler-records-events-DgWCG364.js";import{g as gr}from"./default-session-permission-mode-D0wZ9Jek.js";import{M as pr}from"./MobileWorkspaceSwitcherHeader-DOr4pTUq.js";import"./window-BWqRixxq.js";import"./event-DvH9tcej.js";import"./file-tree-icon-Dp_xhVfD.js";import"./MobileTopHeaderFrame-BWorAJ1C.js";function Ul(){return t.jsxs("section",{className:"butler-loading-panel",role:"status","aria-live":"polite",children:[t.jsxs("div",{className:"butler-loading-orb","aria-hidden":"true",children:[t.jsx("span",{className:"butler-loading-ring butler-loading-ring-primary"}),t.jsx("span",{className:"butler-loading-ring butler-loading-ring-secondary"}),t.jsx("span",{className:"butler-loading-core"})]}),t.jsxs("div",{className:"butler-loading-copy",children:[t.jsx("h1",{children:s("shell.butlerLoadingTitle")}),t.jsx("p",{children:s("shell.butlerLoadingDescription")})]})]})}const Kn=60,xr=400,Hl="butler-diagnostic://",vr=15e3;class Bl{constructor(n){le(this,"state");le(this,"listeners",new Set);le(this,"realtimeClient",null);le(this,"realtimeSessionId",null);le(this,"selectedControlSessionId",null);le(this,"controlSessionReloadInFlight",!1);le(this,"terminalSyncTimer",null);le(this,"terminalSyncArmed",!1);le(this,"terminalSyncCompletedControlSessionId",null);le(this,"pendingRunControlSession",null);le(this,"subscribe",n=>(this.listeners.add(n),()=>{this.listeners.delete(n)}));le(this,"getState",()=>this.state);this.workspaceId=n,this.state={loading:!0,sending:!1,switchingProvider:!1,initialized:!1,profile:null,activeProvider:"codex",controlSession:null,capabilities:jt("codex"),overview:null,events:[],messages:[],historyState:"idle",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,permissionRequests:[],error:null}}async initialize(){this.patch({loading:!0,error:null});try{const n=await yl();if(!n.initialized||!n.profile){this.clearPendingRun(),this.patch({loading:!1,initialized:!1,profile:null,activeProvider:"codex",capabilities:jt("codex"),controlSession:null,messages:[],historyState:"idle",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,overview:null,events:[],runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,permissionRequests:[]});return}const l=n.profile;this.patch({initialized:!0,profile:l,activeProvider:l.providerId,capabilities:jt(l.providerId)}),await this.reloadForProvider(l.providerId),this.patch({loading:!1})}catch(n){this.patch({loading:!1,error:ge(n)})}}async initializeProfile(n){this.patch({loading:!0,error:null});try{const l=await qi(n);if(!l.initialized||!l.profile)throw new Error("BUTLER_PROFILE_INIT_FAILED");this.patch({initialized:!0,profile:l.profile,activeProvider:l.profile.providerId,capabilities:jt(l.profile.providerId)}),await this.reloadForProvider(l.profile.providerId)}catch(l){throw this.patch({error:ge(l)}),l}finally{this.patch({loading:!1})}}async switchProvider(n){if(!this.state.initialized||!this.state.profile||this.state.activeProvider===n)return;const l={activeProvider:this.state.activeProvider,profile:this.state.profile,controlSession:this.state.controlSession,capabilities:this.state.capabilities,overview:this.state.overview,events:this.state.events,messages:this.state.messages,historyState:this.state.historyState,loadingOlderMessages:this.state.loadingOlderMessages,olderCursor:this.state.olderCursor,hasOlderMessages:this.state.hasOlderMessages,runtimeHasActiveRun:this.state.runtimeHasActiveRun,runtimeCanInterrupt:this.state.runtimeCanInterrupt,contextUsage:this.state.contextUsage};this.patch({switchingProvider:!0,error:null,activeProvider:n,controlSession:null,messages:[],historyState:"idle",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,overview:null,events:[],runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,capabilities:jt(n)});try{const i=await Ks({providerId:n});if(!i.initialized||!i.profile)throw new Error("BUTLER_PROFILE_UPDATE_FAILED");this.patch({initialized:!0,profile:i.profile,activeProvider:i.profile.providerId}),await Promise.all([this.refreshCapabilities(i.profile.providerId),this.refreshOverview(),this.refreshEvents()]),await this.startFreshSession({preserveSwitchingState:!0})}catch(i){throw this.patch({...l,error:ge(i)}),i}finally{this.patch({switchingProvider:!1})}}async updateProfile(n){if(!(!this.state.initialized||!this.state.profile)){this.patch({loading:!0,error:null});try{const l=await Ks(n);if(!l.initialized||!l.profile)throw new Error("BUTLER_PROFILE_UPDATE_FAILED");this.patch({initialized:!0,profile:l.profile,activeProvider:l.profile.providerId})}catch(l){throw this.patch({error:ge(l)}),l}finally{this.patch({loading:!1})}}}async sendMessage(n,l){var r;const i=n.trim();if(!(!i||!this.state.initialized)){this.patch({sending:!0,error:null});try{const c=this.state.controlSession,d=((r=this.state.capabilities)==null?void 0:r.supportsInterrupt)??!1,f=(l==null?void 0:l.permissionMode)??gr();if(c){const h=new Date().toISOString();this.patch({controlSession:{...c,status:"running",updatedAt:h,...c.session?{session:{...c.session,runningState:Te(c.session.runningState)?c.session.runningState:"starting",activitySource:"inferred",activityState:"running",lastEventAt:h,updatedAt:h}}:{}},runtimeHasActiveRun:!0,runtimeCanInterrupt:d})}if(c){const h=await Wi({controlSessionId:c.id,content:i,model:(l==null?void 0:l.model)??null,reasoningLevel:(l==null?void 0:l.reasoningLevel)??null,permissionMode:f});this.selectedControlSessionId=h.controlSession.id,this.patch({controlSession:h.controlSession,runtimeHasActiveRun:!0,runtimeCanInterrupt:d})}else{const h=await zi({content:i,model:(l==null?void 0:l.model)??null,reasoningLevel:(l==null?void 0:l.reasoningLevel)??null,permissionMode:f});this.selectedControlSessionId=h.controlSession.id,this.patch({controlSession:h.controlSession,runtimeHasActiveRun:!0,runtimeCanInterrupt:d})}this.markPendingRun(this.selectedControlSessionId),await this.reloadControlSession(this.selectedControlSessionId),await Promise.all([this.refreshOverview(),this.refreshEvents()])}catch(c){throw this.patch({error:ge(c)}),c}finally{this.patch({sending:!1})}}}async retryMessage(n){const l=this.state.messages.find(i=>i.clientRequestId===n);!l||!l.content.trim()||await this.sendMessage(l.content)}async interrupt(){var l,i;const n=((l=this.state.controlSession)==null?void 0:l.session.sessionId)??null;n&&(await or(n),this.clearPendingRun(((i=this.state.controlSession)==null?void 0:i.id)??null),this.patch({runtimeHasActiveRun:!1,runtimeCanInterrupt:!1}))}async replyPermissionRequest(n,l){var d;const i=((d=this.state.controlSession)==null?void 0:d.session.sessionId)??null;if(!i||!(this.state.permissionRequests.find(f=>f.id===n)??null))return;const c=await ur(i,n,l);this.patch({permissionRequests:Yn(this.state.permissionRequests,c)})}async startFreshSession(n){if(this.state.initialized){this.teardownRealtime(),this.selectedControlSessionId=null,this.clearPendingRun(),this.terminalSyncArmed=!1,this.terminalSyncCompletedControlSessionId=null,this.patch({sending:!1,error:null,controlSession:null,messages:[],historyState:"ready",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,permissionRequests:[]});try{await Ki()}catch(l){throw this.patch({historyState:"error",error:ge(l)}),l}this.patch({switchingProvider:n!=null&&n.preserveSwitchingState?this.state.switchingProvider:!1})}}async loadOlderMessages(){var i,r,c,d,f,h;const n=((i=this.state.controlSession)==null?void 0:i.id)??null,l=((r=this.state.controlSession)==null?void 0:r.session.sessionId)??null;if(!(!l||this.state.historyState!=="ready"||this.state.loadingOlderMessages||!this.state.olderCursor)){this.patch({loadingOlderMessages:!0,error:null});try{const x=await Xs(l,this.state.olderCursor,Kn,"backward");if(!n||((c=this.state.controlSession)==null?void 0:c.id)!==n||((d=this.state.controlSession)==null?void 0:d.session.sessionId)!==l){this.patch({loadingOlderMessages:!1});return}const v=Gs(this.state.messages,l,x.messages);this.patch({messages:Xn(v,this.state.controlSession,{runningState:((f=this.state.controlSession)==null?void 0:f.session.runningState)??"idle",runtimeHasActiveRun:this.state.runtimeHasActiveRun??!1,runtimeCanInterrupt:this.state.runtimeCanInterrupt??!1,detail:null,errorDetail:this.state.error,updatedAt:((h=this.state.controlSession)==null?void 0:h.updatedAt)??new Date().toISOString()}),historyState:"ready",loadingOlderMessages:!1,olderCursor:x.nextCursor,hasOlderMessages:!!x.nextCursor})}catch(x){this.patch({loadingOlderMessages:!1,error:ge(x)})}}}async refreshAll(){if(this.state.initialized){this.patch({loading:!0,error:null});try{await this.reloadForProvider(this.state.activeProvider)}finally{this.patch({loading:!1})}}}async reloadEventsAndOverview(){this.state.initialized&&await Promise.all([this.refreshOverview(),this.refreshEvents()])}async reloadForProvider(n){U("butler.runtime.reload_for_provider.start",{workspaceId:this.workspaceId,providerId:n,selectedControlSessionId:this.selectedControlSessionId}),await Promise.all([this.refreshCapabilities(n),this.refreshOverview(),this.refreshEvents()]),await this.reloadControlSession(this.selectedControlSessionId),U("butler.runtime.reload_for_provider.end",{workspaceId:this.workspaceId,providerId:n,selectedControlSessionId:this.selectedControlSessionId})}async openControlSession(n){this.selectedControlSessionId=n.trim()||null,await this.reloadControlSession(this.selectedControlSessionId)}async adoptControlSession(n){this.selectedControlSessionId=n.id,this.patch({controlSession:n}),await this.reloadControlSession(n.id)}async reloadControlSession(n){var r,c,d,f;const l=((r=this.state.controlSession)==null?void 0:r.id)??null,i=this.state.historyState==="ready"&&l!==null&&(n==null||n===l);U("butler.runtime.reload_control_session.start",{workspaceId:this.workspaceId,requestedControlSessionId:n??null,currentControlSessionId:l,currentSessionId:((d=(c=this.state.controlSession)==null?void 0:c.session)==null?void 0:d.sessionId)??null,currentMessages:this.state.messages.length,currentHistoryState:this.state.historyState,backgroundReload:i}),i||this.patch({historyState:"loading"});try{const x=(n?await Yi(n):await Xi()).controlSession;if(!x){this.selectedControlSessionId=null,this.clearPendingRun(),this.terminalSyncArmed=!1,this.terminalSyncCompletedControlSessionId=null,this.teardownRealtime(),this.patch({controlSession:null,messages:[],historyState:"ready",loadingOlderMessages:!1,olderCursor:null,hasOlderMessages:!1,runtimeHasActiveRun:null,runtimeCanInterrupt:null,contextUsage:null,permissionRequests:[]}),U("butler.runtime.reload_control_session.empty",{workspaceId:this.workspaceId,requestedControlSessionId:n??null});return}this.selectedControlSessionId=x.id;const[v,A,H]=await Promise.all([Xs(x.session.sessionId,null,Kn,"backward"),cr(x.session.sessionId),dr(x.session.sessionId)]),P=this.resolvePendingRunControlSession(x,A),T=this.resolvePendingRunRuntimeState(P,A),B=A.hasActiveRun||A.canInterrupt||Te(A.runningState)||_e(A.runningState);((f=this.state.controlSession)==null?void 0:f.id)!==x.id&&(this.terminalSyncCompletedControlSessionId=null),this.terminalSyncArmed=T.hasActiveRun||P.status==="running",B?(this.clearPendingRun(x.id),this.terminalSyncCompletedControlSessionId=null):this.terminalSyncArmed||(this.terminalSyncCompletedControlSessionId=x.id);const z=v.messages.map(W=>Pl(x.session.sessionId,W));this.ensureRealtimeSubscription(x.session.sessionId,v.cursor),this.patch({controlSession:P,messages:Xn(z,P,{runningState:A.runningState,runtimeHasActiveRun:T.hasActiveRun,runtimeCanInterrupt:T.canInterrupt,detail:A.detail,errorDetail:A.errorDetail,updatedAt:A.updatedAt}),historyState:"ready",loadingOlderMessages:!1,olderCursor:v.nextCursor,hasOlderMessages:!!v.nextCursor,runtimeHasActiveRun:T.hasActiveRun,runtimeCanInterrupt:T.canInterrupt,contextUsage:A.contextUsage,permissionRequests:H.items}),U("butler.runtime.reload_control_session.end",{workspaceId:this.workspaceId,controlSessionId:x.id,sessionId:x.session.sessionId,messages:z.length,historyState:"ready",hasActiveRun:T.hasActiveRun,canInterrupt:T.canInterrupt,terminalSyncArmed:this.terminalSyncArmed,terminalSyncCompletedControlSessionId:this.terminalSyncCompletedControlSessionId})}catch(h){this.patch({historyState:"error",error:ge(h)}),U("butler.runtime.reload_control_session.error",{workspaceId:this.workspaceId,requestedControlSessionId:n??null,message:ge(h)})}}async refreshCapabilities(n){try{const l=await mr(n,this.workspaceId);this.patch({capabilities:l})}catch{this.patch({capabilities:jt(n)})}}async refreshOverview(){try{const n=await ts();this.patch({overview:n.overview})}catch(n){this.patch({error:ge(n)})}}async refreshEvents(){try{const n=await Gi();this.patch({events:n.items})}catch(n){this.patch({error:ge(n)})}}patch(n){this.state={...this.state,...n},this.emit()}emit(){for(const n of this.listeners)n()}ensureRealtimeSubscription(n,l){if(this.realtimeClient&&this.realtimeSessionId===n){this.realtimeClient.updateCursor(l),U("butler.runtime.realtime.reuse",{workspaceId:this.workspaceId,sessionId:n,cursor:l});return}this.teardownRealtime(),this.realtimeSessionId=n,U("butler.runtime.realtime.subscribe",{workspaceId:this.workspaceId,sessionId:n,cursor:l}),this.realtimeClient=new br({sessionId:n,cursor:l,limit:Kn,onConnectionChange:()=>{},onSubscribed:()=>{},onEnvelope:i=>{this.handleRealtimeMessages(i.sessionId,i.messages)},onOlderHistory:i=>{this.handleRealtimeMessages(i.sessionId,i.messages)},onRuntimeMessage:i=>{this.handleRealtimeRuntimeMessage(i)},onActivity:i=>{this.handleRealtimeActivity(i)},onRuntimeStatus:i=>{this.handleRealtimeStatus(i)},onRuntimeError:i=>{this.handleRealtimeRuntimeError(i)},onInterrupted:i=>{this.handleRealtimeInterrupted(i)},onPermissionRequest:i=>{this.handlePermissionRequest(i)},onPermissionRequestResolved:i=>{this.handlePermissionRequestResolved(i)},onError:i=>{this.isActiveControlSession(i.sessionId??null)&&this.patch({error:i.detail})},onUnauthorized:()=>{this.patch({error:s("common.unauthorized")})}}),this.realtimeClient.start()}teardownRealtime(){var n;this.clearTerminalSyncTimer(),this.realtimeSessionId&&U("butler.runtime.realtime.teardown",{workspaceId:this.workspaceId,sessionId:this.realtimeSessionId}),(n=this.realtimeClient)==null||n.close(),this.realtimeClient=null,this.realtimeSessionId=null}clearTerminalSyncTimer(){this.terminalSyncTimer!==null&&(window.clearTimeout(this.terminalSyncTimer),this.terminalSyncTimer=null)}scheduleTerminalSessionSync(n,l){var i;this.clearTerminalSyncTimer(),U("butler.runtime.terminal_sync.scheduled",{workspaceId:this.workspaceId,controlSessionId:((i=this.state.controlSession)==null?void 0:i.id)??null,reason:n,...l}),this.terminalSyncTimer=window.setTimeout(()=>{var r,c,d;if(this.terminalSyncTimer=null,this.controlSessionReloadInFlight){U("butler.runtime.terminal_sync.skipped_inflight",{workspaceId:this.workspaceId,controlSessionId:((r=this.state.controlSession)==null?void 0:r.id)??null,reason:n,...l});return}this.controlSessionReloadInFlight=!0,this.terminalSyncCompletedControlSessionId=((c=this.state.controlSession)==null?void 0:c.id)??null,U("butler.runtime.terminal_sync.start",{workspaceId:this.workspaceId,controlSessionId:((d=this.state.controlSession)==null?void 0:d.id)??null,reason:n,...l}),this.reloadControlSession().finally(()=>{var f;this.controlSessionReloadInFlight=!1,U("butler.runtime.terminal_sync.end",{workspaceId:this.workspaceId,controlSessionId:((f=this.state.controlSession)==null?void 0:f.id)??null,reason:n,...l})})},xr)}handleRealtimeMessages(n,l){var r,c,d;if(!this.isActiveControlSession(n)){U("butler.runtime.realtime.messages.ignored",{workspaceId:this.workspaceId,sessionId:n,incoming:l.length,activeSessionId:((r=this.state.controlSession)==null?void 0:r.session.sessionId)??null});return}const i=Gs(this.state.messages,n,l);this.patch({messages:Xn(i,this.state.controlSession,{runningState:((c=this.state.controlSession)==null?void 0:c.session.runningState)??"idle",runtimeHasActiveRun:this.state.runtimeHasActiveRun??!1,runtimeCanInterrupt:this.state.runtimeCanInterrupt??!1,detail:null,errorDetail:this.state.error,updatedAt:((d=this.state.controlSession)==null?void 0:d.updatedAt)??new Date().toISOString()}),historyState:"ready"}),this.promotePendingRunFromMessages(n,l),U("butler.runtime.realtime.messages",{workspaceId:this.workspaceId,sessionId:n,incoming:l.length,messages:i.length})}handleRealtimeRuntimeMessage(n){this.handleRealtimeMessages(n.sessionId,[n.message])}handleRealtimeActivity(n){var r;if(!this.isActiveControlSession(n.sessionId))return;n.hasActiveRun&&(this.terminalSyncArmed=!0,this.terminalSyncCompletedControlSessionId=null);const l=((r=this.state.controlSession)==null?void 0:r.id)??null,i=!n.hasActiveRun&&this.terminalSyncArmed&&l!==null&&this.terminalSyncCompletedControlSessionId!==l;U("butler.runtime.realtime.activity",{workspaceId:this.workspaceId,sessionId:n.sessionId,hasActiveRun:n.hasActiveRun,canInterrupt:n.canInterrupt,updatedAt:n.updatedAt,shouldSyncTerminalState:i,terminalSyncArmed:this.terminalSyncArmed,terminalSyncCompletedControlSessionId:this.terminalSyncCompletedControlSessionId}),this.patchActiveControlSessionRuntimeState({runningState:n.runningState,hasActiveRun:n.hasActiveRun,canInterrupt:n.canInterrupt,updatedAt:n.updatedAt}),i&&this.scheduleTerminalSessionSync("activity_terminal",{sessionId:n.sessionId,updatedAt:n.updatedAt})}handleRealtimeStatus(n){var d;if(!this.isActiveControlSession(n.sessionId))return;const l=n.status==="starting"||n.status==="running";l&&(this.terminalSyncArmed=!0,this.terminalSyncCompletedControlSessionId=null);const i=n.status==="completed"||n.status==="failed"||n.status==="interrupted",r=((d=this.state.controlSession)==null?void 0:d.id)??null,c=i&&!l&&this.terminalSyncArmed&&r!==null&&this.terminalSyncCompletedControlSessionId!==r;U("butler.runtime.realtime.status",{workspaceId:this.workspaceId,sessionId:n.sessionId,status:n.status,timestamp:n.timestamp,shouldSyncTerminalState:c,terminalSyncArmed:this.terminalSyncArmed,terminalSyncCompletedControlSessionId:this.terminalSyncCompletedControlSessionId}),this.patchActiveControlSessionRuntimeState({runningState:n.status,hasActiveRun:l,canInterrupt:l,updatedAt:n.timestamp}),c&&this.scheduleTerminalSessionSync("status_terminal",{sessionId:n.sessionId,status:n.status,timestamp:n.timestamp})}handleRealtimeRuntimeError(n){this.isActiveControlSession(n.sessionId)&&(U("butler.runtime.realtime.error",{workspaceId:this.workspaceId,sessionId:n.sessionId,detail:n.detail,errorCode:n.error_code}),this.patchActiveControlSessionRuntimeState({runningState:"failed",hasActiveRun:!1,canInterrupt:!1,updatedAt:n.timestamp,status:"failed",error:n.detail}),this.reloadControlSession())}handleRealtimeInterrupted(n){this.isActiveControlSession(n.sessionId)&&(U("butler.runtime.realtime.interrupted",{workspaceId:this.workspaceId,sessionId:n.sessionId,detail:n.detail}),this.patchActiveControlSessionRuntimeState({runningState:"interrupted",hasActiveRun:!1,canInterrupt:!1,updatedAt:n.timestamp,error:n.detail}),this.reloadControlSession())}handlePermissionRequest(n){this.isActiveControlSession(n.sessionId)&&this.patch({permissionRequests:Yn(this.state.permissionRequests,n.request)})}handlePermissionRequestResolved(n){this.isActiveControlSession(n.sessionId)&&this.patch({permissionRequests:Yn(this.state.permissionRequests,n.request)})}patchActiveControlSessionRuntimeState(n){var x;const l=this.state.controlSession;if(!l){this.patch({runtimeHasActiveRun:n.hasActiveRun,runtimeCanInterrupt:n.canInterrupt,...n.error!==void 0?{error:n.error}:{}});return}const i=l.session,r=i&&this.hasPendingRun(l.id)&&!n.hasActiveRun&&!n.canInterrupt&&!_e(n.runningState)&&!_e(i.runningState)&&l.status!=="failed"&&l.status!=="closed",c=r?Te(n.runningState)?n.runningState:Te(i.runningState)?i.runningState:"starting":n.runningState,d=r?!0:n.hasActiveRun,f=r?((x=this.state.capabilities)==null?void 0:x.supportsInterrupt)??this.state.runtimeCanInterrupt??n.canInterrupt:n.canInterrupt;r||this.clearPendingRun(l.id);const h=n.status??Ar(l.status,c,d);if(!i){this.patch({controlSession:{...l,status:h,updatedAt:n.updatedAt},runtimeHasActiveRun:d,runtimeCanInterrupt:f,...n.error!==void 0?{error:n.error}:{}});return}this.patch({controlSession:{...l,status:h,updatedAt:n.updatedAt,session:{...i,runningState:c,activitySource:"runtime",activityState:jr(i.activityState,c,d),lastEventAt:n.updatedAt,updatedAt:n.updatedAt}},runtimeHasActiveRun:d,runtimeCanInterrupt:f,...n.error!==void 0?{error:n.error}:{}})}markPendingRun(n){n&&(this.pendingRunControlSession={controlSessionId:n,expiresAt:Date.now()+vr})}clearPendingRun(n){this.pendingRunControlSession&&(n==null||this.pendingRunControlSession.controlSessionId===n)&&(this.pendingRunControlSession=null)}hasPendingRun(n){return!n||!this.pendingRunControlSession||this.pendingRunControlSession.controlSessionId!==n?!1:this.pendingRunControlSession.expiresAt<=Date.now()?(this.pendingRunControlSession=null,!1):!0}resolvePendingRunControlSession(n,l){if(!this.hasPendingRun(n.id))return n;if(l.hasActiveRun||Te(l.runningState)||_e(l.runningState)||Te(n.session.runningState)||_e(n.session.runningState)||n.status==="failed"||n.status==="closed")return this.clearPendingRun(n.id),n;const i=l.updatedAt||n.updatedAt||new Date().toISOString();return{...n,status:"running",updatedAt:i,session:{...n.session,runningState:"starting",activitySource:"inferred",activityState:"running",lastEventAt:i,updatedAt:i}}}resolvePendingRunRuntimeState(n,l){var i;return this.hasPendingRun(n.id)?l.hasActiveRun||l.canInterrupt||_e(l.runningState)||_e(n.session.runningState)||n.status==="failed"||n.status==="closed"?{hasActiveRun:l.hasActiveRun,canInterrupt:l.canInterrupt}:Te(l.runningState)||Te(n.session.runningState)||n.status==="running"?{hasActiveRun:!0,canInterrupt:((i=this.state.capabilities)==null?void 0:i.supportsInterrupt)??l.canInterrupt}:{hasActiveRun:l.hasActiveRun,canInterrupt:l.canInterrupt}:{hasActiveRun:l.hasActiveRun,canInterrupt:l.canInterrupt}}promotePendingRunFromMessages(n,l){var c;const i=this.state.controlSession;if(!i||i.session.sessionId!==n||!this.hasPendingRun(i.id)||this.state.runtimeHasActiveRun===!0||Te(i.session.runningState)||_e(i.session.runningState)||l.length===0)return;const r=((c=l.at(-1))==null?void 0:c.timestamp)??new Date().toISOString();this.patch({controlSession:{...i,status:"running",updatedAt:r,session:{...i.session,runningState:"running",activitySource:"inferred",activityState:"running",lastEventAt:r,updatedAt:r}}})}isActiveControlSession(n){var l;return!!(n&&((l=this.state.controlSession)==null?void 0:l.session.sessionId)===n)}}function R(e,n){const[l,i]=u.useState(()=>n(e.getState()));return u.useEffect(()=>(i(n(e.getState())),e.subscribe(()=>{i(n(e.getState()))})),[n,e]),l}function jt(e){const n=[{id:"provider-default",name:s("conversation.modelUseCliDefault"),usesProviderDefault:!0}];return{provider:e,canStartSession:!0,canResumeSession:!0,canSendMessage:!0,inRunInputMode:e==="claude-code"?"streaming_guidance":"none",supportsSubagents:!1,supportsInterrupt:!0,supportsStructuredToolCalls:!0,supportsTokenUsage:!0,supportsAttachments:!1,supportsPermissionPrompt:!0,supportsCheckpoint:!1,supportsQueueWhileRunning:!1,supportsRunSteering:!1,supportsSlashMenu:!1,supportsReasoningSelector:!0,modelOptions:n,defaultReasoningLevel:null,limitations:[]}}function Gs(e,n,l){const i=new Map;for(const r of e.filter(c=>!$l(c)))i.set(Zs(r),r);for(const r of l){const c=Pl(n,r);i.set(Zs(c),c)}return[...i.values()].sort((r,c)=>r.sequence!==c.sequence?r.sequence-c.sequence:r.timestamp.localeCompare(c.timestamp))}function Zs(e){return e.id||e.rawRef}function Yn(e,n){const l=e.filter(i=>i.id!==n.id);return l.push(n),l.sort((i,r)=>i.status!==r.status?i.status==="pending"?-1:1:r.createdAt.localeCompare(i.createdAt)),l}function Xn(e,n,l){const i=e.filter(c=>!$l(c));if(i.length>0||!n)return i;const r=Sr(n,l);return r?[...i,yr(n,r,l.updatedAt)]:i}function Sr(e,n){var f,h,x;if(n.runtimeHasActiveRun)return null;const l=n.runningState,i=e.status==="failed"||l==="failed";if(!(i||l==="completed"||l==="interrupted"||l==="idle"&&e.status!=="running"))return null;const c=((f=e.lastSummary)==null?void 0:f.trim())||((h=n.errorDetail)==null?void 0:h.trim())||((x=n.detail)==null?void 0:x.trim())||null,d=[i?"本轮助手会话已结束,但没有收到可展示的助手消息。":"本轮助手会话已结束,但 provider 没有返回可展示的助手消息。"];return c&&(d.push(""),d.push(`诊断信息:${c}`)),d.join(`
|
|
2
|
+
`)}function yr(e,n,l){const i=Number.isFinite(e.session.messageCount)?e.session.messageCount:0;return{id:`butler-diagnostic-${e.id}`,sessionId:e.session.sessionId,role:"system",kind:"text",content:n,toolCall:null,attachments:[],attachmentPayloads:null,origin:"system",originRef:e.id,timestamp:l??e.updatedAt,sequence:i+1,rawRef:`${Hl}${e.id}`,deliveryState:"sent",clientRequestId:null}}function $l(e){return e.rawRef.startsWith(Hl)}function ge(e){return e instanceof Error?e.message:String(e)}function Ar(e,n,l){return l||n==="starting"||n==="running"||n==="reconnecting"?"running":n==="failed"?"failed":e==="closed"?"closed":"idle"}function jr(e,n,l){return l||n==="starting"||n==="running"||n==="reconnecting"?"running":n==="completed"||n==="interrupted"||n==="failed"?"completed_unread":e==="running"?"idle":e}function Te(e){return e==="starting"||e==="running"||e==="reconnecting"}function _e(e){return e==="completed"||e==="failed"||e==="interrupted"}const as={"risk-first":["risk","blocker","verification"],"blocker-first":["blocker","risk","verification"],"verification-first":["verification","risk","blocker"],"progress-first":["progress","risk","blocker"]},_l=300,Cr=1500,wr=1500,Ir=480*60*1e3,Nr={displayName:"",providerId:"codex",agentsMode:"inline",personaTone:"direct",personaLanguage:"zh-CN",personaSummaryStyle:"brief",focusRiskPreference:"conservative",reportPriorityPreset:"risk-first"},Gn={displayName:"",agentsMode:"inline",agentsFilePath:"",agentsContent:"",personaTone:"direct",personaLanguage:"zh-CN",personaSummaryStyle:"brief",focusRiskPreference:"conservative",reportPriorityPreset:"risk-first",summaryDebounceSeconds:_l},Tr=[{value:60,labelKey:"shell.butlerSummaryDebounceOption1Minute"},{value:180,labelKey:"shell.butlerSummaryDebounceOption3Minutes"},{value:300,labelKey:"shell.butlerSummaryDebounceOption5Minutes"},{value:600,labelKey:"shell.butlerSummaryDebounceOption10Minutes"},{value:900,labelKey:"shell.butlerSummaryDebounceOption15Minutes"},{value:1800,labelKey:"shell.butlerSummaryDebounceOption30Minutes"}],Re={builder:["🧠","🤖","🦾","🛠️","⚙️","🧩","🚀","🛰️","🔧","💡"],analyst:["🦉","🧭","🔍","📚","🧪","📐","🗂️","📝","🧮","📊"],direct:["🦅","🛡️","⚡","🎯","🪓","🧱","🔨","📌","🧰","🏹"],steady:["🐢","🐘","🦬","🦫","🌲","⛰️","🪨","🧺","🧷","🕰️"],friendly:["🐼","🦊","🐻","🐶","🐱","🐹","🐰","🦄","🌼","🍀"],default:["🧠","🤖","🦉","🧩","📚","💡","🛠️","🚀","🌟","🪄","🧭","🔮"]};function Rr(e){if(typeof document>"u")return!1;const n=document.createElement("textarea");n.value=e,n.setAttribute("readonly","true"),n.style.position="fixed",n.style.opacity="0",n.style.pointerEvents="none",document.body.appendChild(n),n.focus(),n.select();try{return document.execCommand("copy")}catch{return!1}finally{document.body.removeChild(n)}}async function kr(e){var n;if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText))try{await navigator.clipboard.writeText(e);return}catch{}if(!Rr(e))throw new Error(s("conversation.copyContentFailed"))}function Er(){var Hs,Bs,$s,_s,Vs,qs,zs,Ws;const e=rr(),n=Zi(e),{workspaceId:l=""}=Tl(),i=Rl(),{showToast:r}=kl(),{navigationGroups:c,requestNavigationRefresh:d,setAuxiliaryPanel:f}=us(),h=u.useRef(null),x=u.useRef(null),[v,A]=u.useState(Nr),[H,P]=u.useState(!1),[T,B]=u.useState(Gn),[z,W]=u.useState(!1),[Z,K]=u.useState(0),[$,re]=u.useState([]),[q,qe]=u.useState([]),[vs,Ee]=u.useState([]),[$t,de]=u.useState([]),[rt,Le]=u.useState([]),[Q,_]=u.useState([]),[me,Pe]=u.useState([]),[Me,at]=u.useState(!1),[_t,ot]=u.useState(!1),[Vt,qt]=u.useState(!1),[ut,zt]=u.useState(!1),[he,ct]=u.useState(null),[Fe,J]=u.useState(null),[dt,pe]=u.useState(null),[Wt,y]=u.useState(null),[F,Kt]=u.useState(!1),[L,wt]=u.useState(""),[xe,Y]=u.useState(null),[ae,I]=u.useState(null),[It,Nt]=u.useState(!1),[Mn,mt]=u.useState(!1),[Fn,ze]=u.useState(null),[ve,ht]=u.useState(null),[Dn,We]=u.useState(!1),[On,bt]=u.useState(null),[be,oe]=u.useState([]),[Se,V]=u.useState([]),[Tt,Rt]=u.useState(!1),[Ke,Yt]=u.useState(!1),[ye,De]=u.useState(null),[Xt,Oe]=u.useState(null),[kt,ue]=u.useState(null),[Et,Gt]=u.useState(null),[Lt,Zt]=u.useState(null),[Un,Ye]=u.useState(null),[Hn,Qt]=u.useState(null),[Bn,ft]=u.useState(null),[ee,Pt]=u.useState(()=>Date.now()),gt=u.useRef(null),pt=u.useRef(null),Mt=u.useRef(null),Ft=u.useId(),[Jt,Xe]=u.useState({itemId:null,kind:null});(!h.current||x.current!==l)&&(h.current=new Bl(l),x.current=l);const j=h.current,Ae=R(j,a=>a.loading),ce=R(j,a=>a.sending),we=R(j,a=>a.switchingProvider),X=R(j,a=>a.initialized),k=R(j,a=>a.profile),te=R(j,a=>a.activeProvider),g=R(j,a=>a.controlSession),$n=R(j,a=>a.capabilities),D=R(j,a=>a.overview),en=R(j,a=>a.events),Ue=R(j,a=>a.messages),Ge=R(j,a=>a.historyState),tn=R(j,a=>a.loadingOlderMessages),_n=R(j,a=>a.hasOlderMessages),Ze=R(j,a=>a.runtimeHasActiveRun),Qe=R(j,a=>a.runtimeCanInterrupt),nn=R(j,a=>a.contextUsage),Dt=R(j,a=>a.permissionRequests),He=R(j,a=>a.error),sn=u.useRef(null),ln=u.useRef(null),xt=u.useRef(!1),vt=u.useRef(new Set),je=((Hs=k==null?void 0:k.displayName)==null?void 0:Hs.trim())||v.displayName.trim()||s("shell.butlerEntry"),St=u.useMemo(()=>Ma({displayName:je,providerId:(k==null?void 0:k.providerId)??v.providerId,tone:(k==null?void 0:k.persona.tone)??v.personaTone}),[je,v.personaTone,v.providerId,k==null?void 0:k.persona.tone,k==null?void 0:k.providerId]),Ot=u.useMemo(()=>q.filter(a=>os(a.status)).slice(0,3),[q]),rn=u.useMemo(()=>Kr(g,Ze),[g,Ze]),Je=Wr((g==null?void 0:g.session.sessionId)??null,rn),an=Je||ce,on=Je||ce,un=Qe===!0||ce?!0:Qe??!1,cn=u.useMemo(()=>{if(!g||Je)return null;const a=rt.filter(N=>N.status==="active"&&N.controlSessionId===g.id).map(N=>({kind:"timer",timer:N})),m=new Set(rt.filter(N=>N.status==="active"&&N.controlSessionId===g.id).map(N=>N.id)),p=Q.filter(N=>N.status==="active"&&N.controlSessionId===g.id&&!!N.nextRunAt&&!m.has(N.id)).map(N=>({kind:"automation",automation:N}));return[...a,...p].sort((N,O)=>w(Bt(N))-w(Bt(O)))[0]??null},[Q,g,rt,Je]),o=zr(cn),b=u.useMemo(()=>((D==null?void 0:D.projects)??[]).map(a=>a.id).sort(),[D==null?void 0:D.projects]),S=((Bs=c.find(a=>a.workspace.id===l))==null?void 0:Bs.workspace.name)??null,C=u.useMemo(()=>new Map(((D==null?void 0:D.projects)??[]).map(a=>[a.id,a.name])),[D==null?void 0:D.projects]),ne=u.useMemo(()=>new Map(c.map(a=>[a.workspace.id,a.workspace.name])),[c]),Ie=u.useMemo(()=>new Map(c.flatMap(a=>a.sessions.map(m=>{var p;return[m.sessionId,((p=m.title)==null?void 0:p.trim())||s("common.unknown")]}))),[c]),E=u.useMemo(()=>he?Q.find(a=>a.id===he)??null:null,[Q,he]),Ne=u.useMemo(()=>he?me.filter(a=>a.automationId===he).sort((a,m)=>w(m.createdAt)-w(a.createdAt)).slice(0,8):[],[me,he]);u.useEffect(()=>{he&&!E&&(ct(null),J(null))},[E,he]);const Be=u.useMemo(()=>new Map(c.flatMap(a=>a.sessions.map(m=>[m.sessionId,a.workspace.id]))),[c]),fe=u.useMemo(()=>be.find(a=>a.id===ye)??Se.find(a=>a.id===ye)??null,[Se,be,ye]);u.useEffect(()=>{var p,N;if(!ye)return;const a=be.some(O=>O.id===ye),m=Se.some(O=>O.id===ye);a||m||De(((p=be[0])==null?void 0:p.id)??((N=Se[0])==null?void 0:N.id)??null)},[Se,be,ye]),u.useEffect(()=>{if(Pt(Date.now()),!o)return;const a=window.setInterval(()=>{Pt(Date.now())},1e3);return()=>{window.clearInterval(a)}},[o]);const yt=u.useCallback(async()=>{if(!X){de([]);return}try{const a=await Tn();de(a.items)}catch(a){r({title:s("shell.butlerSidebarLoadFailed"),description:a instanceof Error?a.message:void 0,tone:"error"})}},[X,r]),et=u.useCallback(async()=>{if(!X){oe([]),De(null);return}if(!(g!=null&&g.id)){oe([]),De(null);return}Rt(!0);try{const a=await Ys({controlSessionId:(g==null?void 0:g.id)??null});oe(a.payload.items),De(m=>{var p;return a.payload.items.length?a.payload.items.some(N=>N.id===m)?m:((p=a.payload.items[0])==null?void 0:p.id)??null:null})}catch(a){r({title:s("shell.butlerSandboxLoadFailed"),description:a instanceof Error?a.message:void 0,tone:"error"})}finally{Rt(!1)}},[g==null?void 0:g.id,X,r]),Ut=u.useCallback(async()=>{if(!X){V([]);return}Yt(!0);try{const a=await Ys();V(a.payload.items.filter(m=>m.status!=="deleted"))}catch(a){r({title:s("shell.butlerSandboxLoadFailed"),description:a instanceof Error?a.message:void 0,tone:"error"})}finally{Yt(!1)}},[X,r]),dn=u.useCallback(()=>{ot(!0)},[]),mn=u.useCallback(()=>{qt(!0)},[]),hn=u.useCallback(()=>{zt(!0)},[]),se=u.useCallback(()=>{F||yt(),Kt(a=>!a)},[F,yt]),tt=u.useCallback(()=>{Kt(!1),wt("")},[]),xi=u.useCallback(async()=>{if(!(!xe||ae)){I(xe.id);try{await El(xe.session.sessionId),xe.id===(g==null?void 0:g.id)&&await j.openControlSession(""),tt(),Y(null),await yt(),d(),r({title:s("shell.deleteSessionSuccess"),tone:"success"})}catch(a){r({title:a instanceof Error?a.message:s("shell.deleteSessionFailed"),tone:"error"})}finally{I(null)}}},[g==null?void 0:g.id,xe,ae,tt,yt,d,r,j]),Ss=u.useCallback(()=>{Nt(!0),et()},[et]),vi=u.useCallback(()=>{mt(!0),Ut()},[Ut]);u.useEffect(()=>{if(!F){wt("");return}const a=window.requestAnimationFrame(()=>{var m,p;(m=Mt.current)==null||m.focus(),(p=Mt.current)==null||p.select()});return()=>{window.cancelAnimationFrame(a)}},[F]),u.useEffect(()=>{if(!F)return;const a=p=>{var O,nt;const N=p.target;(O=gt.current)!=null&&O.contains(N)||(nt=pt.current)!=null&&nt.contains(N)||tt()},m=p=>{p.key==="Escape"&&(p.preventDefault(),tt())};return document.addEventListener("pointerdown",a),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",a),document.removeEventListener("keydown",m)}},[F,tt]),u.useEffect(()=>{It&&et()},[g==null?void 0:g.id,et,It]);const ys=u.useCallback(a=>{B(m=>({...m,...a}))},[]),Vn=u.useCallback(async a=>{ot(!1),ze(a),ht(null),bt(null),We(!0);try{const m=await Qi(a);ht(m.task)}catch(m){bt(m instanceof Error?m.message:s("shell.butlerAutomationRoundLoadFailed"))}finally{We(!1)}},[]),qn=u.useCallback(async a=>{ue(a.id);try{const m=await Al(a.id);qe(p=>el(p,m.task)),r({title:s("conversation.butlerFollowUpStopped"),description:s("conversation.butlerFollowUpStoppedDescription"),tone:"success"}),await j.reloadEventsAndOverview(),d()}catch(m){r({title:s("conversation.butlerFollowUpStopFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{ue(null)}},[d,r,j]),zn=u.useCallback(async a=>{Gt(a.id);try{await jl(a.projectId,a.id),r({title:s("conversation.butlerVerificationStopped"),description:s("conversation.butlerVerificationStoppedDescription"),tone:"success"}),await j.reloadEventsAndOverview(),d()}catch(m){r({title:s("conversation.butlerVerificationStopFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Gt(null)}},[d,r,j]),As=u.useCallback(async a=>{Xe({itemId:a.id,kind:"analyze"});try{const m=await Ji(a.id);re(p=>Js(p,m.item)),de(p=>ua(p,m.controlSession)),await j.adoptControlSession(m.controlSession),r({title:s("shell.butlerTodoAnalyzeQueued"),tone:"success"})}catch(m){r({title:s("shell.butlerTodoAnalyzeFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Xe({itemId:null,kind:null})}},[r]),js=u.useCallback(async a=>{Xe({itemId:a.id,kind:"start"});try{const m=await er(a.id);re(p=>Js(p,m.item)),m.followUpTask&&qe(p=>el(p,m.followUpTask)),d(),r({title:s("shell.butlerTodoStartSessionSucceeded"),tone:"success"}),i(Cn(m.item.workspaceId,m.session.sessionId))}catch(m){r({title:s("shell.butlerTodoStartSessionFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Xe({itemId:null,kind:null})}},[i,d,r]),Cs=u.useCallback(a=>{var p;const m=(p=a.assistantState.linkedSessionId)==null?void 0:p.trim();m&&i(Cn(a.workspaceId,m))},[i]),ws=u.useCallback(async a=>{var p;const m=(p=a.assistantState.generatedPrompt)==null?void 0:p.trim();if(m)try{await kr(m),r({title:s("shell.butlerTodoCopyPromptSucceeded"),tone:"success"})}catch(N){r({title:N instanceof Error?N.message:s("conversation.copyContentFailed"),tone:"error"})}},[r]),bn=u.useCallback(async a=>{Qt(a);try{const m=await Rn(a);Le(p=>tl(p,m.timer)),r({title:s("shell.butlerControlTimerCancelSucceeded"),tone:"success"})}catch(m){r({title:s("shell.butlerControlTimerCancelFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Qt(null)}},[r]),fn=u.useCallback(async a=>{Zt(a);try{const m=await kn(a);_(p=>Sn(p,m.payload.automation)),r({title:s("shell.butlerControlTimerCancelSucceeded"),tone:"success"})}catch(m){r({title:s("shell.butlerControlTimerCancelFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Zt(null)}},[r]),Is=u.useCallback(a=>{const m=Q.find(p=>p.id===a);m&&(ct(a),J(ll(m)))},[Q]),Si=u.useCallback(async()=>{if(!E||!Fe)return;let a;try{a=Pa(E,Fe)}catch(m){r({title:s("shell.butlerAutomationSaveFailed"),description:m instanceof Error?m.message:void 0,tone:"error"});return}pe(E.id);try{const m=await Cl(E.id,a);_(p=>Sn(p,m.payload.automation)),ct(m.payload.automation.id),J(ll(m.payload.automation)),r({title:s("shell.butlerAutomationSaveSucceeded"),tone:"success"})}catch(m){r({title:s("shell.butlerAutomationSaveFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{pe(null)}},[Fe,E,r]),yi=u.useCallback(async a=>{const m=a.content.trim();if(!m){r({title:s("shell.butlerControlTimerExecuteNowFailed"),tone:"error"});return}ft(a.id);try{const p=await Rn(a.id);Le(N=>tl(N,p.timer)),await j.sendMessage(m),d(),r({title:s("shell.butlerControlTimerExecuteNowSucceeded"),tone:"success"})}catch(p){r({title:s("shell.butlerControlTimerExecuteNowFailed"),description:p instanceof Error?p.message:void 0,tone:"error"})}finally{ft(null)}},[d,r,j]),Ns=u.useCallback(async a=>{Ye(a);try{const m=await tr(a);_(p=>Sn(p,m.payload.automation)),r({title:s("shell.butlerControlTimerCancelSucceeded"),tone:"success"})}catch(m){r({title:s("shell.butlerControlTimerCancelFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Ye(null)}},[r]),Ai=u.useCallback(async a=>{if(a.kind==="timer"){await bn(a.timer.id);return}await fn(a.automation.id)},[fn,bn]),ji=u.useCallback(async a=>{if(a.kind==="timer"){await bn(a.timer.id);return}await Ns(a.automation.id)},[bn,Ns]),Ci=u.useCallback(async a=>{if(a.kind==="timer"){await yi(a.timer);return}if(a.automation.triggerType!=="once")return;const m=a.automation.actionConfig.content.trim();if(!m){r({title:s("shell.butlerControlTimerExecuteNowFailed"),tone:"error"});return}ft(a.automation.id);try{await kn(a.automation.id),_(p=>Sn(p,{...a.automation,status:"cancelled",nextRunAt:null,cancelledAt:new Date().toISOString(),updatedAt:new Date().toISOString()})),await j.sendMessage(m),d(),r({title:s("shell.butlerControlTimerExecuteNowSucceeded"),tone:"success"})}catch(p){r({title:s("shell.butlerControlTimerExecuteNowFailed"),description:p instanceof Error?p.message:void 0,tone:"error"})}finally{ft(null)}},[d,r,j]),wi=u.useCallback(a=>{const m=Ln(a),p=(m?Be.get(m):null)||ds(a)||l;!m||!p||i(Cn(p,m))},[i,Be,l]),Ii=u.useCallback(async a=>{Oe(a);try{const m=await nr({sandboxId:a,mode:"project",defaultProvider:te});oe(p=>Ct(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>Ct(p,m.payload.sandbox)),d(),r({title:s("shell.butlerSandboxPromoteSucceeded"),tone:"success"})}catch(m){r({title:s("shell.butlerSandboxPromoteFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Oe(null)}},[te,g==null?void 0:g.id,d,r]),Ni=u.useCallback(async a=>{Oe(a);try{const m=await sr(a);oe(p=>Ct(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>Ct(p,m.payload.sandbox)),r({title:s("shell.butlerSandboxExpireSucceeded"),tone:"success"})}catch(m){r({title:s("shell.butlerSandboxExpireFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Oe(null)}},[g==null?void 0:g.id,r]),Ts=u.useCallback(async a=>{Oe(a);try{const m=await lr(a);oe(p=>Ct(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>Ct(p,m.payload.sandbox)),d(),r({title:s("shell.butlerSandboxRemoveSucceeded"),tone:"success"})}catch(m){r({title:s("shell.butlerSandboxRemoveFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{Oe(null)}},[g==null?void 0:g.id,d,r]),Rs=u.useCallback(async()=>{if(k){if(!T.displayName.trim()){r({title:s("shell.butlerInitNameRequired"),tone:"warning"});return}W(!0);try{await j.updateProfile({displayName:T.displayName.trim(),agentsMode:T.agentsMode,agentsFilePath:T.agentsMode==="file"?T.agentsFilePath:null,agentsContent:T.agentsContent,persona:{tone:T.personaTone,language:T.personaLanguage,summaryStyle:T.personaSummaryStyle},focus:{...k.focus,riskPreference:T.focusRiskPreference,reportPriority:as[T.reportPriorityPreset],summaryDebounceSeconds:T.summaryDebounceSeconds}}),r({title:s("shell.butlerSettingsSaved"),tone:"success"})}catch(a){r({title:s("shell.butlerSettingsSaveFailed"),description:a instanceof Error?a.message:void 0,tone:"error"})}finally{W(!1)}}},[k,T,r,j]);u.useEffect(()=>{j.initialize()},[j]),u.useEffect(()=>{var m,p;const a=JSON.stringify({workspaceId:l,activeProvider:te,controlSessionId:(g==null?void 0:g.id)??null,sessionId:((m=g==null?void 0:g.session)==null?void 0:m.sessionId)??null,messages:Ue.length,historyState:Ge,runtimeHasActiveRun:Ze,runtimeCanInterrupt:Qe,loading:Ae,sending:ce,switchingProvider:we,error:He});sn.current!==a&&(sn.current=a,U("butler.page.timeline_state",{workspaceId:l,activeProvider:te,controlSessionId:(g==null?void 0:g.id)??null,sessionId:((p=g==null?void 0:g.session)==null?void 0:p.sessionId)??null,messages:Ue.length,historyState:Ge,runtimeHasActiveRun:Ze,runtimeCanInterrupt:Qe,loading:Ae,sending:ce,switchingProvider:we,error:He??null}))},[l,te,g==null?void 0:g.id,($s=g==null?void 0:g.session)==null?void 0:$s.sessionId,Ue.length,Ge,Ze,Qe,Ae,ce,we,He]),u.useEffect(()=>{He&&r({title:s("shell.butlerLoadFailed"),description:He,tone:"error"})},[He,r]),u.useEffect(()=>{var N;const a=((N=g==null?void 0:g.session)==null?void 0:N.sessionId)??null;if(ln.current!==a&&(ln.current=a,xt.current=!1,vt.current=new Set),!a)return;const m=Dt.filter(O=>O.status==="pending"),p=new Set(m.map(O=>O.id));xt.current&&m.forEach(O=>{var nt,gn,pn;vt.current.has(O.id)||r({id:`butler-permission-request-${O.id}`,title:s("conversation.permissionRequestToastTitle"),description:s("conversation.backgroundPermissionToastDescription",{title:((nt=g==null?void 0:g.title)==null?void 0:nt.trim())||((pn=(gn=g==null?void 0:g.session)==null?void 0:gn.title)==null?void 0:pn.trim())||je,requestTitle:O.title}),tone:"warning",durationMs:8e3})}),vt.current=p,xt.current=!0},[je,(_s=g==null?void 0:g.session)==null?void 0:_s.sessionId,(Vs=g==null?void 0:g.session)==null?void 0:Vs.title,g==null?void 0:g.title,Dt,r]),u.useEffect(()=>{if(!k){B(Gn);return}B({displayName:k.displayName,agentsMode:k.agentsMode,agentsFilePath:Ta(k),agentsContent:k.agentsContent,personaTone:k.persona.tone,personaLanguage:k.persona.language,personaSummaryStyle:k.persona.summaryStyle,focusRiskPreference:k.focus.riskPreference,reportPriorityPreset:Na(k.focus.reportPriority),summaryDebounceSeconds:k.focus.summaryDebounceSeconds??Gn.summaryDebounceSeconds})},[k]),u.useEffect(()=>{if(!X){re([]),qe([]),Ee([]),de([]),Le([]),_([]),Pe([]),oe([]);return}let a=!1;async function m(){try{const[O,nt,gn,pn,Hi,Bi,$i]=await Promise.all([wl(),ns(),Tn(),Il(),ss({limit:100}),ls({limit:100}),Promise.all(b.map(Wn=>Nl(Wn)))]);a||(re(O.items),qe(nt.items),de(gn.items),Le(pn.items),_(Hi.payload.items),Pe(Bi.payload.items),Ee($i.flatMap(Wn=>Wn.items)))}catch(O){if(a)return;re([]),qe([]),Ee([]),de([]),Le([]),_([]),Pe([]),oe([]),r({title:s("shell.butlerSidebarLoadFailed"),description:O instanceof Error?O.message:void 0,tone:"error"})}}m();function p(){m()}const N=window.setInterval(()=>{m()},15e3);return window.addEventListener(En,p),()=>{a=!0,window.clearInterval(N),window.removeEventListener(En,p)}},[X,b,r]),u.useEffect(()=>Ol(()=>{j.reloadEventsAndOverview()}),[j]);const At=u.useMemo(()=>[{value:"codex",label:"Codex"},{value:"claude-code",label:"Claude Code"}],[]),ks=u.useMemo(()=>[{value:"inline",label:s("shell.butlerAgentsModeInline")},{value:"file",label:s("shell.butlerAgentsModeFile")}],[]),Es=u.useMemo(()=>[{value:"direct",label:s("shell.butlerToneDirect")},{value:"steady",label:s("shell.butlerToneSteady")},{value:"friendly",label:s("shell.butlerToneFriendly")}],[]),Ls=u.useMemo(()=>[{value:"zh-CN",label:s("shell.butlerLanguageZhCn")},{value:"en-US",label:s("shell.butlerLanguageEnUs")},{value:"bilingual",label:s("shell.butlerLanguageBilingual")}],[]),Ps=u.useMemo(()=>[{value:"brief",label:s("shell.butlerSummaryBrief")},{value:"structured",label:s("shell.butlerSummaryStructured")},{value:"thorough",label:s("shell.butlerSummaryThorough")}],[]),Ms=u.useMemo(()=>[{value:"conservative",label:s("shell.butlerRiskConservative")},{value:"balanced",label:s("shell.butlerRiskBalanced")},{value:"proactive",label:s("shell.butlerRiskProactive")}],[]),Fs=u.useMemo(()=>[{value:"risk-first",label:s("shell.butlerReportRiskFirst")},{value:"blocker-first",label:s("shell.butlerReportBlockerFirst")},{value:"verification-first",label:s("shell.butlerReportVerificationFirst")},{value:"progress-first",label:s("shell.butlerReportProgressFirst")}],[]),Ti=Ve(At,v.providerId),Ds=Ve(ks,v.agentsMode),Ri=Ve(Es,v.personaTone),ki=Ve(Ls,v.personaLanguage),Ei=Ve(Ps,v.personaSummaryStyle),Li=Ve(Ms,v.focusRiskPreference),Pi=Ve(Fs,v.reportPriorityPreset),Mi=v.agentsMode==="inline"?s("shell.butlerAgentsModeInlineDescription"):s("shell.butlerAgentsModeFileDescription"),Fi=[Ds,ki,Li],Os=u.useMemo(()=>t.jsx(Lr,{overview:D,events:en,inboxItems:$,followUpTasks:q,assistantAutomations:Q,assistantAutomationRuns:me,cancellingFollowUpTaskId:kt,cancellingVerificationId:Et,cancellingAutomationId:Lt,controlSession:g,sandboxes:be,settingsForm:T,savingSettings:z,onOpenSandboxManager:Ss,onOpenFollowUpHistory:dn,onOpenVerificationHistory:mn,onOpenAutomationHistory:hn,onOpenAutomationDetail:Is,onOpenFollowUpDetail:Vn,onCancelFollowUpTask:qn,onCancelVerificationRun:zn,onCancelAutomation:fn,onAnalyzeTodo:As,onStartTodoSession:js,onOpenTodoSession:Cs,onCopyTodoPrompt:ws,todoActionState:Jt,onSettingsFormChange:ys,onSaveSettings:()=>{Rs()}}),[en,As,fn,Ss,ws,hn,Is,dn,mn,q,Vn,Cs,Rs,ys,js,Q,me,be,$,Lt,kt,Et,g,D,qn,zn,z,T,Jt]);u.useEffect(()=>{if(!X){f(null);return}return f(Os),()=>{f(null)}},[X,f,Os]);async function Di(a){a.preventDefault();const m=v.displayName.trim();if(!m){r({title:s("shell.butlerInitNameRequired"),tone:"warning"});return}const p={displayName:m,providerId:v.providerId,agentsMode:v.agentsMode,persona:{tone:v.personaTone,language:v.personaLanguage,summaryStyle:v.personaSummaryStyle},focus:{projectIds:[],riskPreference:v.focusRiskPreference,reportPriority:as[v.reportPriorityPreset],summaryDebounceSeconds:_l}};P(!0);try{await j.initializeProfile(p),r({title:s("shell.butlerInitSuccess"),tone:"success"})}catch(N){r({title:s("shell.butlerInitFailed"),description:N instanceof Error?N.message:void 0,tone:"error"})}finally{P(!1)}}async function Oi(a){if(a!==te)try{await j.switchProvider(a),Us(a),r({title:s("shell.butlerProviderSwitched"),description:s("shell.butlerProviderSwitchedDescription",{provider:Ve(At,a)}),tone:"success"})}catch(m){r({title:s("shell.butlerProviderSwitchFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}}async function Ui(){try{Us(te),await j.startFreshSession(),r({title:s("shell.butlerNewSessionStarted"),tone:"success"})}catch(a){r({title:s("shell.butlerNewSessionFailed"),description:a instanceof Error?a.message:void 0,tone:"error"})}}function Us(a){K(m=>m+1),i(is(l),{replace:!0}),a&&d()}return Ae&&!X&&!H?t.jsx("main",{className:"workbench-page butler-page-shell butler-loading-shell",children:t.jsx(Ul,{})}):X?t.jsxs(t.Fragment,{children:[t.jsxs("main",{className:"workbench-page conversation-page-shell butler-page-shell butler-chat-workspace",children:[t.jsxs("header",{className:"workbench-auxiliary-header butler-main-header","data-window-drag-handle":"conversation-header","data-tauri-drag-region":n,children:[t.jsx("div",{className:"butler-header-main","data-tauri-drag-region":n,children:t.jsxs("div",{className:"butler-header-analysis-anchor",onMouseEnter:()=>{at(!0)},onMouseLeave:()=>{at(!1)},children:[t.jsx("div",{className:"butler-chat-avatar","aria-hidden":"true",children:t.jsx("span",{children:St})}),t.jsx("div",{className:"butler-main-heading",children:t.jsx("h1",{tabIndex:0,"data-tauri-drag-region":n,onFocus:()=>{at(!0)},onBlur:()=>{at(!1)},children:je})}),Me?t.jsxs("div",{className:"butler-header-analysis-popover",role:"status","aria-live":"polite",children:[t.jsx("strong",{children:s("conversation.butlerAnalysisTitle")}),Ot.length>0?Ot.map(a=>t.jsxs("div",{className:"butler-header-analysis-item",children:[t.jsxs("p",{children:[s("conversation.butlerAnalysisObjectiveLabel"),":",a.objective]}),t.jsxs("p",{children:[s("conversation.butlerAnalysisStatusLabel"),":",hs(a.status)]}),t.jsxs("p",{children:[s("conversation.butlerAnalysisSummaryLabel"),":",a.lastAutomationSummary||a.waitingReason||s("conversation.butlerAnalysisEmpty")]})]},a.id)):t.jsx("p",{children:s("conversation.butlerAnalysisEmpty")})]}):null]})}),t.jsxs("div",{className:"butler-toolbar-cluster",children:[t.jsx("div",{className:"butler-provider-switcher",children:t.jsx("select",{"aria-label":s("shell.butlerProviderLabel"),value:te,disabled:At.length<=1||we||ce,onChange:a=>{Oi(a.target.value)},children:At.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))})}),t.jsx("button",{type:"button",className:"terminal-tab-control butler-header-icon-button","aria-label":s("shell.butlerNewSessionAction"),title:s("shell.butlerNewSessionAction"),disabled:Ae||ce||we,onClick:()=>{Ui()},children:t.jsx("span",{className:"terminal-toolbar-icon","aria-hidden":"true",children:t.jsx(Da,{})})}),t.jsxs("div",{className:"butler-session-history-anchor",ref:gt,children:[t.jsx("button",{type:"button",className:"terminal-tab-control butler-header-icon-button","aria-label":s("shell.butlerHistoryAction"),"aria-haspopup":"dialog","aria-expanded":F,"aria-controls":F?"butler-control-history-popover":void 0,title:s("shell.butlerHistoryAction"),disabled:Ae||ce||we,onClick:()=>{se()},children:t.jsx("span",{className:"terminal-toolbar-icon butler-history-toolbar-icon","aria-hidden":"true",children:t.jsx(Oa,{})})}),t.jsx(cs,{open:F,id:"butler-control-history-popover",className:"butler-session-history-popover",anchorRef:gt,popoverRef:pt,labelledBy:Ft,maxWidth:420,gap:10,viewportPadding:14,children:t.jsx(Or,{sessions:$t,activeControlSessionId:(g==null?void 0:g.id)??null,labelId:Ft,query:L,searchInputRef:Mt,onQueryChange:wt,deletingSessionId:ae,onSelectSession:async a=>{if(a.id===(g==null?void 0:g.id)){tt();return}await j.openControlSession(a.id),tt()},onDeleteSession:a=>{Y(a)}})})]})]})]}),t.jsx("section",{className:"butler-main-column",children:t.jsxs("div",{className:"butler-conversation-shell",children:[t.jsx(Ml,{requests:Dt,replyingRequestId:Wt,onReply:async(a,m)=>{y(a);try{await j.replyPermissionRequest(a,m)}catch(p){r({title:s("conversation.permissionRequestReplyFailed"),description:p instanceof Error?p.message:void 0,tone:"error"})}finally{y(null)}}}),t.jsx(Fl,{sessionId:(qs=g==null?void 0:g.session)==null?void 0:qs.sessionId,messages:Ue,historyState:Ge,loadingOlderMessages:tn,hasOlderMessages:_n,provider:te,assistantAvatar:t.jsx("span",{className:"butler-message-avatar","aria-hidden":"true",children:St}),onLoadOlderMessages:()=>{j.loadOlderMessages()},onRetryMessage:a=>{const m=Ue.find(p=>p.clientRequestId===a);if(m!=null&&m.content.trim()){j.sendMessage(m.content);return}j.retryMessage(a)}}),o?t.jsx(qr,{schedule:o,currentWorkspaceId:l,currentWorkspaceName:S,projectNameById:C,workspaceNameById:ne,sessionTitleById:Ie,sessionWorkspaceIdById:Be,countdownNow:ee,cancelling:o.kind==="timer"?Hn===o.timer.id:Lt===o.automation.id,skippingWait:o.kind==="automation"&&Un===o.automation.id,executingNow:Bn===Jr(o),onCancel:()=>{Ai(o)},onSkipWait:()=>{ji(o)},onExecuteNow:()=>{Ci(o)},onOpenSession:()=>{wi(o)}}):null,t.jsx("div",{className:"butler-composer-shell",children:t.jsx(Dl,{capabilities:$n,draftStorageId:`butler:${te}:${Z}`,placeholder:s("shell.butlerComposerPlaceholder",{displayName:je}),hasActiveRun:an,canInterrupt:un,contextUsage:nn,isSubmitting:ce||we,isRunning:on,onInterrupt:async()=>{await j.interrupt(),d()},onSend:async(a,m)=>{var p;(((p=m==null?void 0:m.attachments)==null?void 0:p.length)??0)>0&&r({title:s("shell.butlerAttachmentUnsupported"),tone:"warning"}),await j.sendMessage(a,{model:(m==null?void 0:m.model)??null,reasoningLevel:(m==null?void 0:m.reasoningLevel)??null,permissionMode:null}),d()}})})]},`timeline:${te}:${Z}`)})]}),t.jsxs($e,{open:xe!==null,title:s("shell.deleteSessionConfirmTitle"),description:s("shell.deleteSessionConfirmDescription"),onClose:()=>{ae||Y(null)},children:[t.jsx("p",{className:"workbench-section-empty",children:xe?ql(xe):""}),t.jsxs("div",{className:"workbench-modal-actions",children:[t.jsx("button",{type:"button",className:"secondary-button",disabled:!!ae,onClick:()=>Y(null),children:s("common.cancel")}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!ae,onClick:()=>{xi()},children:ae?s("common.loading"):s("shell.deleteSessionAction")})]})]}),t.jsx($e,{open:_t,title:s("shell.butlerFollowUpHistoryTitle"),description:s("shell.butlerFollowUpHistoryDescription"),onClose:()=>{ot(!1)},children:t.jsx(Vr,{tasks:q.filter(a=>!os(a.status)),cancellingTaskId:kt,onOpenFollowUpDetail:Vn,onCancelFollowUpTask:qn,onClose:()=>{ot(!1)}})}),t.jsx($e,{open:Vt,title:s("shell.butlerVerificationHistoryTitle"),description:s("shell.butlerVerificationHistoryDescription"),onClose:()=>{qt(!1)},children:t.jsx(aa,{items:Yl((D==null?void 0:D.verifications)??[],"history"),cancellingVerificationId:Et,onCancelVerificationRun:zn})}),t.jsx($e,{open:ut,title:s("shell.butlerAutomationHistoryTitle"),description:s("shell.butlerAutomationHistoryDescription"),onClose:()=>{zt(!1)},children:t.jsx(oa,{taskItems:Wl(Q,D,"history"),runItems:Kl(Q,me,D,"history")})}),t.jsx($e,{open:E!==null,title:s("shell.butlerAutomationDetailTitle"),description:((zs=E==null?void 0:E.title)==null?void 0:zs.trim())||(E==null?void 0:E.actionConfig.content.trim())||s("shell.butlerAutomationDetailDescription"),className:"butler-automation-detail-modal",onClose:()=>{ct(null),J(null),pe(null)},children:E&&Fe?t.jsx(Gr,{automation:E,editorState:Fe,saving:dt===E.id,projectName:bs(E,C),targetSessionTitle:La(E,Ie),recentRuns:Ne,onEditorChange:a=>{J(m=>m&&{...m,...a})},onSave:()=>{Si()}}):null}),t.jsx($e,{open:It,title:s("shell.butlerSandboxManagerTitle"),description:s("shell.butlerSandboxManagerDescription"),headerActions:t.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{vi()},children:s("shell.butlerSandboxBrowseAllAction")}),onClose:()=>{mt(!1),Nt(!1)},children:t.jsx(Br,{items:be,selectedSandbox:fe,loading:Tt,actionSandboxId:Xt,onSelectSandbox:De,onReload:et,onPromoteSandboxToProject:Ii,onExpireSandbox:Ni,onRemoveSandbox:Ts})}),t.jsx($e,{open:Mn,title:s("shell.butlerSandboxLibraryTitle"),description:s("shell.butlerSandboxLibraryDescription"),layout:"list",headerActions:t.jsx("button",{type:"button",className:"secondary-button",disabled:Ke,onClick:()=>{Ut()},children:s("shell.butlerRefreshAction")}),onClose:()=>{mt(!1)},children:t.jsx($r,{items:Se,loading:Ke,actionSandboxId:Xt,selectedSandboxId:ye,onViewSandbox:a=>{De(a),mt(!1)},onRemoveSandbox:Ts})}),t.jsx($e,{open:Fn!==null,title:s("shell.butlerAutomationRoundDetailsTitle"),description:((Ws=ve==null?void 0:ve.sessionTitle)==null?void 0:Ws.trim())||(ve==null?void 0:ve.projectName)||s("shell.butlerAutomationRoundDetailsDescription"),onClose:()=>{ze(null),ht(null),bt(null),We(!1)},children:t.jsx(ra,{task:ve,loading:Dn,error:On})})]}):t.jsxs("main",{className:"workbench-page butler-page-shell butler-init-shell",children:[t.jsxs("div",{className:"butler-init-backdrop","aria-hidden":"true",children:[t.jsx("span",{className:"butler-init-glow butler-init-glow-primary"}),t.jsx("span",{className:"butler-init-glow butler-init-glow-secondary"})]}),t.jsxs("div",{className:"butler-init-layout",children:[t.jsxs("aside",{className:"butler-init-sidebar",children:[t.jsx("section",{className:"butler-init-hero-card",children:t.jsxs("div",{className:"butler-init-hero-copy",children:[t.jsx("h1",{children:s("shell.butlerInitTitle")}),t.jsx("p",{children:s("shell.butlerInitDescription")})]})}),t.jsxs("section",{className:"butler-init-preview-card",children:[t.jsx("header",{className:"butler-init-section-header",children:t.jsx("div",{children:t.jsx("h2",{children:s("shell.butlerInitPreviewTitle")})})}),t.jsxs("div",{className:"butler-init-preview-identity",children:[t.jsxs("div",{className:"butler-init-preview-nameplate",children:[t.jsx("div",{className:"butler-chat-avatar butler-init-preview-avatar",children:t.jsx("span",{children:St})}),t.jsx("strong",{children:je})]}),t.jsx("span",{className:"butler-init-preview-provider",children:Ti})]}),t.jsx("div",{className:"butler-init-chip-list",children:Fi.map(a=>t.jsx("span",{className:"butler-init-chip",children:a},a))}),t.jsxs("div",{className:"butler-init-preview-rows",children:[t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerPersonaToneLabel")}),t.jsx("strong",{children:Ri})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerInitPreviewRuleLabel")}),t.jsx("strong",{children:Ds})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerPersonaSummaryStyleLabel")}),t.jsx("strong",{children:Ei})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerReportPriorityPresetLabel")}),t.jsx("strong",{children:Pi})]})]})]})]}),t.jsxs("form",{className:"butler-init-form",onSubmit:Di,children:[t.jsxs("section",{className:"butler-init-form-section",children:[t.jsx("header",{className:"butler-init-section-header",children:t.jsx("div",{children:t.jsx("h2",{children:s("shell.butlerInitBasicsTitle")})})}),t.jsxs("div",{className:"butler-init-basic-grid",children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerDisplayNameLabel")}),t.jsx("input",{className:"butler-form-control",value:v.displayName,onChange:a=>A(m=>({...m,displayName:a.target.value})),placeholder:s("shell.butlerDisplayNamePlaceholder")}),t.jsx("small",{children:s("shell.butlerDisplayNameHint")})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerProviderLabel")}),t.jsx("select",{className:"butler-form-control",value:v.providerId,disabled:At.length<=1,onChange:a=>A(m=>({...m,providerId:a.target.value})),children:At.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))})]}),t.jsxs("label",{className:"butler-form-field butler-form-field-wide",children:[t.jsx("span",{children:s("shell.butlerAgentsModeLabel")}),t.jsx("select",{className:"butler-form-control",value:v.agentsMode,onChange:a=>A(m=>({...m,agentsMode:a.target.value})),children:ks.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))}),t.jsx("small",{children:Mi})]})]})]}),t.jsxs("section",{className:"butler-init-form-section",children:[t.jsx("header",{className:"butler-init-section-header",children:t.jsx("div",{children:t.jsx("h2",{children:s("shell.butlerInitPersonaTitle")})})}),t.jsxs("div",{className:"butler-init-persona-grid",children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerPersonaToneLabel")}),t.jsx("select",{className:"butler-form-control",value:v.personaTone,onChange:a=>A(m=>({...m,personaTone:a.target.value})),children:Es.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerPersonaLanguageLabel")}),t.jsx("select",{className:"butler-form-control",value:v.personaLanguage,onChange:a=>A(m=>({...m,personaLanguage:a.target.value})),children:Ls.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerPersonaSummaryStyleLabel")}),t.jsx("select",{className:"butler-form-control",value:v.personaSummaryStyle,onChange:a=>A(m=>({...m,personaSummaryStyle:a.target.value})),children:Ps.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))})]})]})]}),t.jsxs("section",{className:"butler-init-form-section",children:[t.jsx("header",{className:"butler-init-section-header",children:t.jsx("div",{children:t.jsx("h2",{children:s("shell.butlerInitPreferenceTitle")})})}),t.jsxs("div",{className:"butler-init-preferences-grid",children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerFocusRiskPreferenceLabel")}),t.jsx("select",{className:"butler-form-control",value:v.focusRiskPreference,onChange:a=>A(m=>({...m,focusRiskPreference:a.target.value})),children:Ms.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerReportPriorityPresetLabel")}),t.jsx("select",{className:"butler-form-control",value:v.reportPriorityPreset,onChange:a=>A(m=>({...m,reportPriorityPreset:a.target.value})),children:Fs.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))})]})]})]}),t.jsx("div",{className:"butler-init-actions",children:t.jsx("button",{className:"butler-init-submit",type:"submit",disabled:Ae||H,children:Ae||H?s("shell.butlerInitSubmitting"):s("shell.butlerInitSubmit")})})]})]})]})}function Lr(e){const[n,l]=u.useState("info"),i=[{id:"info",label:s("shell.butlerSidebarInfoTab")},{id:"automation",label:s("shell.butlerSidebarAutomationTab")},{id:"settings",label:s("shell.butlerSidebarSettingsTab")}],r=n==="info"?t.jsx(Pr,{overview:e.overview,inboxItems:e.inboxItems,followUpTasks:e.followUpTasks,sandboxes:e.sandboxes,onOpenSandboxManager:e.onOpenSandboxManager,cancellingFollowUpTaskId:e.cancellingFollowUpTaskId,cancellingVerificationId:e.cancellingVerificationId,onOpenFollowUpHistory:e.onOpenFollowUpHistory,onOpenVerificationHistory:e.onOpenVerificationHistory,onOpenFollowUpDetail:e.onOpenFollowUpDetail,onCancelFollowUpTask:e.onCancelFollowUpTask,onCancelVerificationRun:e.onCancelVerificationRun,onAnalyzeTodo:e.onAnalyzeTodo,onStartTodoSession:e.onStartTodoSession,onOpenTodoSession:e.onOpenTodoSession,onCopyTodoPrompt:e.onCopyTodoPrompt,todoActionState:e.todoActionState}):n==="automation"?t.jsx(Fr,{overview:e.overview,automations:e.assistantAutomations,runs:e.assistantAutomationRuns,cancellingAutomationId:e.cancellingAutomationId,onOpenAutomationHistory:e.onOpenAutomationHistory,onOpenAutomationDetail:e.onOpenAutomationDetail,onCancelAutomation:e.onCancelAutomation}):t.jsx(Qr,{settingsForm:e.settingsForm,savingSettings:e.savingSettings,onSettingsFormChange:e.onSettingsFormChange,onSaveSettings:e.onSaveSettings});return t.jsxs("div",{className:"butler-side-column",children:[t.jsx("div",{className:"workbench-auxiliary-header butler-side-header",children:t.jsx("div",{className:"workbench-info-tabs butler-side-tabs",role:"tablist","aria-label":s("shell.butlerSidebarTabsLabel"),children:i.map(c=>t.jsx("button",{type:"button",role:"tab","aria-selected":n===c.id,className:n===c.id?"workbench-info-tab active":"workbench-info-tab",onClick:()=>{l(c.id)},children:c.label},c.id))})}),t.jsx("div",{className:"butler-side-content",children:r})]})}function Pr(e){var r;const n=u.useMemo(()=>e.followUpTasks.filter(c=>os(c.status)),[e.followUpTasks]),l=u.useMemo(()=>{var c;return Yl(((c=e.overview)==null?void 0:c.verifications)??[],"active")},[(r=e.overview)==null?void 0:r.verifications]),i=u.useMemo(()=>e.inboxItems.filter(c=>c.status!=="closed"),[e.inboxItems]);return t.jsxs(t.Fragment,{children:[t.jsx(Mr,{sandboxes:e.sandboxes,onOpenSandboxManager:e.onOpenSandboxManager}),t.jsx(_r,{tasks:n,cancellingTaskId:e.cancellingFollowUpTaskId,onOpenFollowUpHistory:e.onOpenFollowUpHistory,onOpenFollowUpDetail:e.onOpenFollowUpDetail,onCancelFollowUpTask:e.onCancelFollowUpTask}),t.jsx(Vl,{title:s("shell.butlerInfoVerificationRecordsTitle"),items:l,emptyText:s("shell.butlerInfoVerificationRecordsEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:e.onOpenVerificationHistory,cancellingVerificationId:e.cancellingVerificationId,onCancelVerificationRun:e.onCancelVerificationRun}),t.jsx(Dr,{title:s("shell.butlerInfoTodoRecordsTitle"),items:i,emptyText:s("shell.butlerInfoTodoRecordsEmpty"),todoActionState:e.todoActionState,onAnalyzeTodo:e.onAnalyzeTodo,onStartTodoSession:e.onStartTodoSession,onOpenTodoSession:e.onOpenTodoSession,onCopyTodoPrompt:e.onCopyTodoPrompt})]})}function Mr(e){const n=e.sandboxes.filter(l=>l.status==="active").length;return t.jsx("section",{className:"butler-side-card butler-sandbox-entry-card",children:t.jsxs("header",{children:[t.jsxs("div",{children:[t.jsx("h2",{children:s("shell.butlerSandboxEntryTitle")}),t.jsx("p",{children:s("shell.butlerSandboxEntryDescription")}),n>0?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerSandboxEntrySessionSummary",{count:n})}):null]}),t.jsx("button",{type:"button",className:"secondary-button butler-side-header-action",onClick:e.onOpenSandboxManager,children:s("shell.butlerSandboxManageAction")})]})})}function Fr(e){const n=u.useMemo(()=>Wl(e.automations,e.overview,"active"),[e.automations,e.overview]),l=u.useMemo(()=>Kl(e.automations,e.runs,e.overview,"active"),[e.automations,e.overview,e.runs]);return t.jsxs(t.Fragment,{children:[t.jsx(Yr,{items:n,cancellingAutomationId:e.cancellingAutomationId,onCancelAutomation:e.onCancelAutomation,onOpenAutomationDetail:e.onOpenAutomationDetail,emptyText:s("shell.butlerAutomationTasksEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:e.onOpenAutomationHistory}),t.jsx(Xr,{items:l,emptyText:s("shell.butlerAutomationRunsEmpty"),onOpenAutomationDetail:e.onOpenAutomationDetail})]})}function Vl(e){return t.jsxs("section",{className:"butler-side-card",children:[t.jsxs("header",{children:[t.jsx("h2",{children:e.title}),e.actionLabel&&e.onAction?t.jsx("button",{type:"button",className:"secondary-button butler-side-header-action",onClick:e.onAction,children:e.actionLabel}):null]}),e.items.length>0?t.jsx("div",{className:"butler-record-list",children:e.items.map(n=>t.jsxs("article",{className:"butler-follow-up-status-card",children:[t.jsxs("header",{className:"butler-follow-up-status-header",children:[t.jsxs("div",{className:"butler-follow-up-status-title-group",children:[t.jsx("strong",{children:n.title}),n.subtitle?t.jsx("span",{children:n.subtitle}):null]}),n.status?t.jsx("span",{className:"butler-automation-status-badge","data-status":n.verification?ya(n.verification.status):"active",children:n.status}):null]}),t.jsx("div",{className:"butler-follow-up-status-body",children:t.jsx("p",{children:n.content})}),n.meta||e.onCancelVerificationRun&&n.verification?t.jsxs("footer",{className:"butler-follow-up-status-footer",children:[t.jsx("span",{children:n.meta??""}),n.verification&&e.onCancelVerificationRun?t.jsx("button",{type:"button",className:"secondary-button butler-follow-up-status-action",disabled:e.cancellingVerificationId===n.verification.id||!va(n.verification),onClick:()=>{var l;n.verification&&((l=e.onCancelVerificationRun)==null||l.call(e,n.verification))},children:e.cancellingVerificationId===n.verification.id?s("conversation.butlerVerificationStopping"):s("conversation.butlerStopVerificationAction")}):null]}):null]},n.id))}):t.jsx("p",{className:"butler-secondary-text",children:e.emptyText})]})}function Dr(e){return t.jsxs("section",{className:"butler-side-card",children:[t.jsx("header",{children:t.jsx("h2",{children:e.title})}),e.items.length>0?t.jsx("div",{className:"butler-record-list",children:e.items.map(n=>{var f,h;const l=e.todoActionState.itemId===n.id?e.todoActionState.kind:null,i=!!((f=n.assistantState.generatedPrompt)!=null&&f.trim()),r=!!((h=n.assistantState.linkedSessionId)!=null&&h.trim()),c=n.assistantState.lifecycleStage==="analyzing",d=r||i&&!c&&n.status!=="closed";return t.jsxs("article",{className:"butler-todo-card",children:[t.jsxs("header",{className:"butler-todo-card-header",children:[t.jsxs("div",{children:[t.jsx("strong",{children:n.title}),t.jsx("span",{children:n.projectName})]}),t.jsxs("div",{className:"butler-todo-card-badges",children:[t.jsx("span",{className:"butler-inline-badge",children:Ra(n.status)}),t.jsx("span",{className:"butler-inline-badge",children:Aa(n.assistantState.lifecycleStage)})]})]}),t.jsx("p",{children:n.content}),t.jsx("p",{className:"butler-secondary-text",children:n.assistantState.lastError||n.assistantState.analysisSummary||s("shell.butlerTodoLifecycleEmpty")}),i?t.jsx("div",{className:"butler-todo-prompt-preview",children:t.jsxs("details",{className:"butler-todo-prompt-preview-details",children:[t.jsx("summary",{children:s("shell.butlerTodoPromptPreviewAction")}),t.jsx("pre",{children:n.assistantState.generatedPrompt})]})}):null,t.jsxs("div",{className:"butler-todo-card-actions",children:[t.jsx("button",{type:"button",className:"secondary-button",disabled:l!==null||n.status==="closed"||c,onClick:()=>{e.onAnalyzeTodo(n)},children:l==="analyze"?s("shell.butlerTodoAnalyzeRunning"):c?s("shell.butlerTodoAnalyzeRunning"):i?s("shell.butlerTodoReanalyzeAction"):s("shell.butlerTodoAnalyzeAction")}),t.jsx("button",{type:"button",className:"secondary-button",disabled:l!==null||!d,onClick:()=>{if(r){e.onOpenTodoSession(n);return}e.onStartTodoSession(n)},children:l==="start"?s("shell.butlerTodoStartSessionRunning"):r?s("shell.butlerTodoOpenSessionAction"):c?s("shell.butlerTodoWaitForPromptAction"):i?s("shell.butlerTodoStartSessionAction"):s("shell.butlerTodoAnalyzeFirstAction")}),t.jsx("button",{type:"button",className:"secondary-button",disabled:!i,onClick:()=>{e.onCopyTodoPrompt(n)},children:s("shell.butlerTodoCopyPromptAction")})]})]},n.id)})}):t.jsx("p",{className:"butler-secondary-text",children:e.emptyText})]})}function Or(e){const n=u.useDeferredValue(e.query),l=u.useMemo(()=>{const d=n.trim().toLowerCase();return e.sessions.map(f=>{const h=ql(f),x=Ur(f,h),v=w(f.updatedAt),A=[h,x,f.sessionId].join(`
|
|
3
|
+
`).toLowerCase();return{session:f,title:h,preview:x,updatedAtMs:v,active:v>0&&Date.now()-v<=Ir,searchText:A}}).filter(f=>!d||f.searchText.includes(d)).sort((f,h)=>h.updatedAtMs-f.updatedAtMs)},[n,e.sessions]),i=l.filter(d=>d.active),r=l.filter(d=>!d.active),c=n.trim().length>0;return t.jsxs("div",{className:"butler-session-history-panel",children:[t.jsx("div",{className:"butler-session-history-header",children:t.jsxs("div",{className:"butler-card-header-copy",children:[t.jsx("strong",{id:e.labelId,children:s("shell.butlerHistoryTitle")}),t.jsx("p",{children:s("shell.butlerHistoryDescription")})]})}),t.jsxs("label",{className:"butler-session-history-search",children:[t.jsx("span",{className:"butler-session-history-search-icon","aria-hidden":"true",children:t.jsx(Hr,{})}),t.jsx("input",{ref:e.searchInputRef,type:"search","aria-label":s("shell.butlerHistorySearchLabel"),placeholder:s("shell.butlerHistorySearchPlaceholder"),value:e.query,onChange:d=>{e.onQueryChange(d.target.value)}})]}),l.length===0?t.jsx("p",{className:"butler-secondary-text",children:c?s("shell.butlerHistorySearchEmpty"):s("shell.butlerHistoryEmpty")}):t.jsxs("div",{className:"butler-session-history-list",children:[i.length>0?t.jsxs("div",{className:"butler-session-history-section",children:[t.jsx("div",{className:"butler-session-history-divider",children:t.jsx("span",{children:s("shell.butlerHistoryActiveSection")})}),t.jsx(rs,{compact:!0,className:"butler-session-history-section-list",role:"list",children:i.map(d=>t.jsx(Qs,{session:d.session,title:d.title,preview:d.preview,selected:d.session.id===e.activeControlSessionId,deleting:e.deletingSessionId===d.session.id,onSelectSession:e.onSelectSession,onDeleteSession:e.onDeleteSession},d.session.id))})]}):null,r.length>0?t.jsxs("div",{className:"butler-session-history-section",children:[t.jsx("div",{className:"butler-session-history-divider","data-muted":i.length>0,children:t.jsx("span",{children:s("shell.butlerHistoryInactiveSection")})}),t.jsx(rs,{compact:!0,className:"butler-session-history-section-list",role:"list",children:r.map(d=>t.jsx(Qs,{session:d.session,title:d.title,preview:d.preview,selected:d.session.id===e.activeControlSessionId,deleting:e.deletingSessionId===d.session.id,onSelectSession:e.onSelectSession,onDeleteSession:e.onDeleteSession},d.session.id))})]}):null]})]})}function Qs(e){return t.jsx(Ll,{as:"div",role:"listitem",className:"butler-session-history-item",selected:e.selected,tabIndex:0,style:{paddingTop:"13px",paddingRight:"0",paddingBottom:"12px",paddingLeft:"24px"},label:t.jsx("span",{className:"butler-session-history-item-title",title:e.title,children:e.title}),description:t.jsx("span",{className:"butler-session-history-item-preview",title:e.preview,children:e.preview}),trailing:t.jsxs("div",{className:"butler-session-history-item-trailing",children:[t.jsx("time",{className:"butler-session-history-item-time",dateTime:e.session.updatedAt,children:ms(e.session.updatedAt)}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button butler-session-history-delete-button",disabled:e.deleting,"aria-label":s("shell.butlerHistoryDeleteAction"),onClick:n=>{n.stopPropagation(),e.onDeleteSession(e.session)},children:e.deleting?s("common.loading"):s("shell.deleteSessionAction")})]}),"aria-current":e.selected?"true":void 0,onClick:()=>{e.onSelectSession(e.session)},onKeyDown:n=>{n.key!=="Enter"&&n.key!==" "||(n.preventDefault(),e.onSelectSession(e.session))}})}function ql(e){var n,l,i;return((n=e.title)==null?void 0:n.trim())||((l=e.session.title)==null?void 0:l.trim())||((i=e.lastSummary)==null?void 0:i.trim())||e.sessionId}function Ur(e,n){var r,c;const l=(r=e.lastSummary)==null?void 0:r.trim();if(l)return l;const i=(c=e.session.title)==null?void 0:c.trim();return i&&i!==n?i:e.sessionId}function Hr(){return t.jsx("svg",{viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",focusable:"false",children:t.jsx("path",{fill:"currentColor",d:"M6.75 1.75a5 5 0 1 0 3.16 8.875l3.61 3.608a.75.75 0 1 0 1.06-1.06l-3.608-3.61A5 5 0 0 0 6.75 1.75Zm-3.5 5a3.5 3.5 0 1 1 7 0 3.5 3.5 0 0 1-7 0Z"})})}function Br(e){var f,h,x;const n=u.useMemo(()=>[...e.items].sort((v,A)=>w(A.updatedAt)-w(v.updatedAt)),[e.items]),l=e.selectedSandbox??n[0]??null,i=e.actionSandboxId===(l==null?void 0:l.id),r=(l==null?void 0:l.status)==="active"&&l.visibility==="assistant_only",c=(l==null?void 0:l.status)==="active",d=(l==null?void 0:l.status)!=="deleted";return t.jsxs("div",{className:"butler-sandbox-panel",children:[t.jsxs("section",{className:"butler-side-card butler-sandbox-panel-card",children:[t.jsxs("header",{className:"butler-sandbox-current-header",children:[t.jsxs("div",{className:"butler-card-header-copy",children:[t.jsx("h2",{children:s("shell.butlerSandboxCurrentTitle")}),t.jsx("p",{children:s("shell.butlerSandboxCurrentPanelDescription")})]}),t.jsxs("div",{className:"butler-sandbox-header-actions",children:[l&&r?t.jsx("button",{type:"button",className:"secondary-button butler-automation-card-action",disabled:i,onClick:()=>{e.onPromoteSandboxToProject(l.id)},children:i?s("shell.butlerSandboxActionRunning"):s("shell.butlerSandboxPromoteAction")}):null,l&&c?t.jsx("button",{type:"button",className:"secondary-button butler-automation-card-action",disabled:i,onClick:()=>{e.onExpireSandbox(l.id)},children:i?s("shell.butlerSandboxActionRunning"):s("shell.butlerSandboxExpireAction")}):null,l&&d?t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button butler-automation-card-action",disabled:i,onClick:()=>{e.onRemoveSandbox(l.id)},children:i?s("shell.butlerSandboxActionRunning"):s("shell.butlerSandboxRemoveAction")}):null,t.jsx("button",{type:"button",className:"secondary-button",disabled:e.loading,onClick:()=>{e.onReload()},children:s("shell.butlerRefreshAction")})]})]}),e.loading?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerSandboxLoading")}):n.length===0?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerSandboxEmpty")}):l?t.jsxs("article",{className:"butler-automation-card butler-sandbox-record","data-selected":"true",children:[t.jsxs("div",{className:"butler-sandbox-record-top",children:[t.jsxs("div",{className:"butler-automation-card-title-group butler-sandbox-record-title",children:[t.jsx("strong",{children:l.title}),t.jsx("span",{children:((f=l.workspace)==null?void 0:f.path)??s("shell.butlerSandboxWorkspaceMissing")})]}),t.jsx("span",{className:"butler-automation-status-badge","data-status":li(l.status),children:si(l.status)})]}),t.jsxs("div",{className:"butler-automation-card-body butler-sandbox-record-body",children:[t.jsxs("div",{className:"butler-automation-row butler-sandbox-record-meta",children:[t.jsx("span",{children:s("shell.butlerSandboxSourceKindLabel")}),t.jsx("strong",{children:ii(l.sourceKind)})]}),t.jsxs("div",{className:"butler-automation-row butler-sandbox-record-meta",children:[t.jsx("span",{children:s("shell.butlerSandboxVisibilityLabel")}),t.jsx("strong",{children:ri(l.visibility)})]}),t.jsxs("div",{className:"butler-automation-row butler-sandbox-record-meta",children:[t.jsx("span",{children:s("shell.butlerSandboxUpdatedAtLabel")}),t.jsx("strong",{children:ms(l.updatedAt)})]}),t.jsxs("div",{className:"butler-automation-row butler-sandbox-record-meta",children:[t.jsx("span",{children:s("shell.butlerSandboxPurposeLabel")}),t.jsx("strong",{children:((h=l.purpose)==null?void 0:h.trim())||s("shell.butlerSandboxPurposeEmpty")})]})]})]}):null]}),t.jsxs("section",{className:"butler-side-card butler-sandbox-panel-card butler-sandbox-files-card",children:[t.jsx("header",{children:t.jsxs("div",{className:"butler-card-header-copy",children:[t.jsx("h2",{children:s("shell.butlerSandboxFilesTitle")}),t.jsx("p",{children:s("shell.butlerSandboxFilesDescription")})]})}),e.selectedSandbox?t.jsxs("div",{className:"butler-sandbox-files-shell",children:[t.jsxs("div",{className:"butler-sandbox-files-meta",children:[t.jsxs("div",{className:"butler-automation-row butler-sandbox-files-meta-item",children:[t.jsx("span",{children:s("shell.butlerSandboxTitleLabel")}),t.jsx("strong",{children:e.selectedSandbox.title})]}),t.jsxs("div",{className:"butler-automation-row butler-sandbox-files-meta-item",children:[t.jsx("span",{children:s("shell.butlerSandboxWorkspaceLabel")}),t.jsx("strong",{children:((x=e.selectedSandbox.workspace)==null?void 0:x.path)??s("shell.butlerSandboxWorkspaceMissing")})]})]}),e.selectedSandbox.workspace?t.jsx(fr,{className:"butler-sandbox-file-context-panel",hideHeading:!0,hideTabs:!0,sessionId:null,workspaceId:e.selectedSandbox.workspaceId}):t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerSandboxWorkspaceMissing")})]}):n.length>0?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerSandboxSelectHint")}):null]})]})}function $r(e){const n=u.useMemo(()=>[...e.items].sort((l,i)=>w(i.updatedAt)-w(l.updatedAt)),[e.items]);return e.loading?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerSandboxLoading")}):n.length===0?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerSandboxLibraryEmpty")}):t.jsx(rs,{className:"butler-sandbox-browser-list",compact:!0,children:n.map(l=>{var r;const i=e.actionSandboxId===l.id;return t.jsx(Ll,{className:"butler-sandbox-browser-item",selected:e.selectedSandboxId===l.id,label:l.title,description:((r=l.workspace)==null?void 0:r.path)??s("shell.butlerSandboxWorkspaceMissing"),trailing:t.jsxs("div",{className:"butler-sandbox-browser-actions",children:[t.jsx("span",{className:"butler-automation-status-badge","data-status":li(l.status),children:si(l.status)}),t.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{e.onViewSandbox(l.id)},children:s("shell.butlerSandboxOpenAction")}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:i,onClick:()=>{e.onRemoveSandbox(l.id)},children:i?s("shell.butlerSandboxActionRunning"):s("shell.butlerSandboxRemoveAction")})]}),children:t.jsxs("div",{className:"butler-sandbox-browser-meta",children:[t.jsx("span",{children:ii(l.sourceKind)}),t.jsx("span",{children:ri(l.visibility)}),t.jsx("span",{children:ms(l.updatedAt)})]})},l.id)})})}function _r(e){const n=u.useMemo(()=>[...e.tasks].sort((l,i)=>w(it(i))-w(it(l))).slice(0,5),[e.tasks]);return t.jsxs("section",{className:"butler-side-card",children:[t.jsxs("header",{children:[t.jsx("div",{className:"butler-card-header-copy",children:t.jsx("h2",{children:s("shell.butlerInfoFollowUpRecordsTitle")})}),t.jsx("button",{type:"button",className:"secondary-button butler-side-header-action",onClick:e.onOpenFollowUpHistory,children:s("shell.butlerFollowUpHistoryAction")})]}),n.length>0?t.jsx("div",{className:"butler-record-list",children:n.map(l=>t.jsx(zl,{task:l,cancelling:e.cancellingTaskId===l.id,onOpenFollowUpDetail:e.onOpenFollowUpDetail,onCancelFollowUpTask:e.onCancelFollowUpTask},l.id))}):t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerInfoFollowUpRecordsEmpty")})]})}function Vr(e){const n=u.useMemo(()=>[...e.tasks].sort((l,i)=>w(it(i))-w(it(l))),[e.tasks]);return t.jsx("div",{className:"butler-follow-up-history-panel",children:n.length>0?t.jsx("div",{className:"butler-record-list",children:n.map(l=>t.jsx(zl,{task:l,cancelling:e.cancellingTaskId===l.id,onOpenFollowUpDetail:async i=>{e.onClose(),await e.onOpenFollowUpDetail(i)},onCancelFollowUpTask:e.onCancelFollowUpTask},l.id))}):t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerInfoFollowUpRecordsEmpty")})})}function zl(e){var r,c,d;const{task:n}=e,l=((r=n.sessionTitle)==null?void 0:r.trim())||n.projectName,i=((c=n.waitingReason)==null?void 0:c.trim())||((d=n.lastAutomationSummary)==null?void 0:d.trim())||n.objective;return t.jsxs("article",{className:"butler-follow-up-status-card",children:[t.jsxs("header",{className:"butler-follow-up-status-header",children:[t.jsxs("div",{className:"butler-follow-up-status-title-group",children:[t.jsx("strong",{children:l}),t.jsx("span",{children:n.projectName})]}),t.jsx("span",{className:"butler-automation-status-badge","data-status":n.status,children:hs(n.status)})]}),t.jsx("div",{className:"butler-follow-up-status-body",children:t.jsx("p",{children:i})}),t.jsxs("footer",{className:"butler-follow-up-status-footer",children:[t.jsx("span",{children:ie(it(n))}),t.jsxs("div",{className:"butler-inline-actions",children:[e.onCancelFollowUpTask&&xa(n)?t.jsx("button",{type:"button",className:"secondary-button butler-follow-up-status-action",disabled:e.cancelling,onClick:()=>{e.onCancelFollowUpTask(n)},children:e.cancelling?s("conversation.butlerFollowUpStopping"):s("conversation.butlerStopFollowUpAction")}):null,t.jsx("button",{type:"button",className:"secondary-button butler-follow-up-status-action",onClick:()=>{e.onOpenFollowUpDetail(n.id)},children:s("shell.butlerAutomationViewRoundsAction")})]})]})]})}function qr(e){const n=u.useId(),l=u.useId(),i=u.useRef(null),r=u.useRef(null),[c,d]=u.useState(!1),f=sa(e.schedule,e.countdownNow),h=ta(e.schedule,e.countdownNow),x=na(e.schedule,e.countdownNow),v=ha(e.schedule,e.projectNameById,e.workspaceNameById,e.currentWorkspaceId,e.currentWorkspaceName),A=fa(e.schedule,e.sessionTitleById),H=la(e.schedule),P=!!(Ln(e.schedule)&&(e.sessionWorkspaceIdById.has(Ln(e.schedule))||ds(e.schedule))),T=ea(e.schedule),B=ia(e.schedule),z=T?e.executingNow?s("shell.butlerControlTimerExecutingNow"):s("shell.butlerControlTimerExecuteNowAction"):e.skippingWait?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerCancelAction"),W=T?e.cancelling?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerStopAction"):e.cancelling?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerCancelOperationAction");return u.useEffect(()=>{if(!c)return;const Z=$=>{var re,q;(re=i.current)!=null&&re.contains($.target)||(q=r.current)!=null&&q.contains($.target)||d(!1)},K=$=>{$.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",Z),document.addEventListener("keydown",K),()=>{document.removeEventListener("pointerdown",Z),document.removeEventListener("keydown",K)}},[c]),t.jsx("section",{className:"butler-control-timer-banner","aria-live":"polite",children:t.jsxs("div",{className:"butler-control-timer-banner-shell",children:[t.jsxs("div",{className:"butler-control-timer-banner-copy",children:[t.jsxs("div",{className:"butler-control-timer-banner-status",children:[t.jsx("span",{className:"butler-control-timer-pulse","aria-hidden":"true"}),t.jsx("span",{className:"butler-control-timer-banner-caption",children:B})]}),t.jsxs("div",{className:"butler-control-timer-display-panel",children:[t.jsx("p",{className:"butler-control-timer-banner-lead",children:h}),t.jsx("p",{className:"butler-control-timer-display-clock",children:f}),t.jsx("p",{className:"butler-control-timer-banner-tail",children:x})]}),t.jsxs("div",{className:"butler-control-timer-banner-meta",children:[t.jsxs("div",{className:"butler-control-timer-banner-meta-card","data-kind":"workspace",children:[t.jsx("span",{children:s("shell.butlerControlTimerWorkspaceLabel")}),t.jsx("strong",{title:v,children:v})]}),t.jsxs("div",{className:"butler-control-timer-banner-meta-card","data-kind":"session",children:[t.jsx("span",{children:s("shell.butlerControlTimerSessionLabel")}),P?t.jsx("button",{type:"button",className:"butler-control-timer-session-link",title:A,"aria-label":`${s("shell.butlerControlTimerSessionLabel")}:${A}`,onClick:e.onOpenSession,children:A}):t.jsx("strong",{title:A,children:A})]})]})]}),t.jsxs("div",{className:"butler-control-timer-banner-actions",children:[t.jsxs("div",{className:"butler-control-timer-banner-detail",ref:i,children:[t.jsx("button",{id:n,type:"button",className:"butler-control-timer-banner-detail-button","aria-label":s("shell.butlerControlTimerDetailAction"),"aria-haspopup":"dialog","aria-expanded":c,"aria-controls":c?l:void 0,title:s("shell.butlerControlTimerDetailAction"),onClick:()=>{d(Z=>!Z)},children:t.jsx("span",{className:"butler-control-timer-banner-detail-icon","aria-hidden":"true",children:t.jsx(ga,{})})}),t.jsx(cs,{open:c,id:l,className:"butler-control-timer-banner-detail-popover",anchorRef:i,popoverRef:r,labelledBy:n,children:t.jsxs("div",{children:[t.jsx("strong",{children:s("shell.butlerControlTimerPromptTitle")}),t.jsx("p",{children:H})]})})]}),t.jsx("button",{type:"button",className:"secondary-button butler-control-timer-banner-action",disabled:e.cancelling||e.executingNow||e.skippingWait,onClick:T?e.onExecuteNow:e.onSkipWait,children:z}),t.jsx("button",{type:"button",className:"secondary-button butler-control-timer-banner-action",disabled:e.cancelling||e.executingNow||e.skippingWait,onClick:e.onCancel,children:W})]}),T?t.jsx("p",{className:"butler-control-timer-banner-note",children:s("shell.butlerControlTimerActionNote")}):null]})})}function zr(e){const[n,l]=u.useState(e),i=u.useRef(null);return u.useEffect(()=>{if(e){i.current!==null&&(window.clearTimeout(i.current),i.current=null),l(e);return}!n||i.current!==null||(i.current=window.setTimeout(()=>{i.current=null,l(null)},Cr))},[e,n]),u.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),e??n}function Wr(e,n){const[l,i]=u.useState(n),r=u.useRef(null);return u.useEffect(()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null),i(n)},[e]),u.useEffect(()=>{if(n){r.current!==null&&(window.clearTimeout(r.current),r.current=null),i(!0);return}!l||r.current!==null||(r.current=window.setTimeout(()=>{r.current=null,i(!1)},wr))},[n,l]),u.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),l}function Kr(e,n){return n===!0?!0:e?e.session.activityState==="running"||e.session.runningState==="starting"||e.session.runningState==="running"||e.session.runningState==="reconnecting":!1}function Yr(e){return t.jsxs("section",{className:"butler-side-card",children:[t.jsxs("header",{children:[t.jsx("h2",{children:s("shell.butlerAutomationTasksTitle")}),e.actionLabel&&e.onAction?t.jsx("button",{type:"button",className:"secondary-button butler-side-header-action",onClick:e.onAction,children:e.actionLabel}):null]}),e.items.length>0?t.jsx("div",{className:"butler-automation-overview-list",children:e.items.map(n=>t.jsxs("article",{className:"butler-automation-card butler-automation-overview-card","data-kind":"task",children:[t.jsxs("header",{className:"butler-automation-card-header",children:[t.jsxs("div",{className:"butler-automation-card-title-group",children:[t.jsx("strong",{children:n.title}),t.jsx("span",{children:n.projectName})]}),t.jsx("span",{className:"butler-automation-status-badge","data-status":n.status,children:n.statusLabel})]}),t.jsxs("div",{className:"butler-automation-overview-inline",children:[t.jsx("span",{className:"butler-automation-overview-chip",children:n.taskTypeLabel}),t.jsxs("span",{className:"butler-automation-overview-inline-meta",children:[s("shell.butlerAutomationTaskNextRunLabel")," · ",ie(n.nextRunAt)]}),t.jsxs("span",{className:"butler-automation-overview-inline-meta",children:[s("shell.butlerAutomationTaskLastRunLabel")," · ",ie(n.lastRunAt)]})]}),t.jsxs("footer",{className:"butler-automation-card-footer",children:[n.automationId?t.jsx("button",{type:"button",className:"secondary-button butler-automation-card-action",onClick:()=>{e.onOpenAutomationDetail(n.automationId)},children:s("shell.butlerAutomationOpenDetailsAction")}):null,n.automationId&&n.status==="active"?t.jsx("button",{type:"button",className:"secondary-button butler-automation-card-action",disabled:e.cancellingAutomationId===n.automationId,onClick:()=>{e.onCancelAutomation(n.automationId)},children:e.cancellingAutomationId===n.automationId?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerStopAction")}):null]})]},n.id))}):t.jsx("p",{className:"butler-secondary-text",children:e.emptyText})]})}function Xr(e){return t.jsxs("section",{className:"butler-side-card",children:[t.jsx("header",{children:t.jsx("h2",{children:s("shell.butlerAutomationRunsTitle")})}),e.items.length>0?t.jsx("div",{className:"butler-automation-overview-list",children:e.items.map(n=>t.jsxs("article",{className:"butler-automation-card butler-automation-overview-card","data-kind":"run",children:[t.jsxs("header",{className:"butler-automation-card-header",children:[t.jsxs("div",{className:"butler-automation-card-title-group",children:[t.jsx("strong",{children:n.title}),t.jsx("span",{children:n.projectName})]}),t.jsx("span",{className:"butler-automation-status-badge","data-status":n.status,children:n.statusLabel})]}),t.jsxs("div",{className:"butler-automation-overview-inline",children:[t.jsx("span",{className:"butler-automation-overview-chip",children:n.sourceLabel}),t.jsxs("span",{className:"butler-automation-overview-inline-meta",children:[s("shell.butlerAutomationRunProcessedAtLabel")," · ",ie(n.createdAt)]})]}),t.jsx("footer",{className:"butler-automation-card-footer",children:t.jsx("button",{type:"button",className:"secondary-button butler-automation-card-action",onClick:()=>{e.onOpenAutomationDetail(n.automationId)},children:s("shell.butlerAutomationOpenDetailsAction")})})]},n.id))}):t.jsx("p",{className:"butler-secondary-text",children:e.emptyText})]})}function Gr(e){return t.jsxs("div",{className:"butler-automation-detail-shell",children:[t.jsxs("section",{className:"butler-automation-detail-summary-grid",children:[t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskTypeLabel")}),t.jsx("strong",{children:Zl(e.automation.triggerType)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationStatusLabel")}),t.jsx("strong",{children:ei(e.automation.status)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskNextRunLabel")}),t.jsx("strong",{children:ie(e.automation.nextRunAt)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskLastRunLabel")}),t.jsx("strong",{children:ie(e.automation.lastRunAt||e.automation.updatedAt)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerControlTimerWorkspaceLabel")}),t.jsx("strong",{children:e.projectName})]}),e.targetSessionTitle?t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationTargetSessionLabel")}),t.jsx("strong",{children:e.targetSessionTitle})]}):null]}),t.jsxs("section",{className:"butler-side-card butler-automation-detail-section",children:[t.jsx("header",{children:t.jsx("h2",{children:s("shell.butlerAutomationDetailTitle")})}),t.jsxs("div",{className:"butler-automation-detail-form-grid",children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationTitleLabel")}),t.jsx("input",{className:"butler-form-control",value:e.editorState.title,disabled:e.saving,onChange:n=>{e.onEditorChange({title:n.target.value})}})]}),t.jsxs("label",{className:"butler-form-field butler-form-field-wide",children:[t.jsx("span",{children:s("shell.butlerAutomationPromptLabel")}),t.jsx("textarea",{className:"butler-form-control butler-automation-detail-textarea",value:e.editorState.content,disabled:e.saving,onChange:n=>{e.onEditorChange({content:n.target.value})}})]}),t.jsxs("label",{className:"butler-automation-detail-toggle",children:[t.jsx("input",{type:"checkbox",checked:e.editorState.includeTriggerContext,disabled:e.saving,onChange:n=>{e.onEditorChange({includeTriggerContext:n.target.checked})}}),t.jsx("span",{children:s("shell.butlerAutomationIncludeTriggerContextLabel")})]}),t.jsx(Zr,{automation:e.automation,editorState:e.editorState,saving:e.saving,onEditorChange:e.onEditorChange})]}),t.jsx("div",{className:"butler-automation-detail-actions",children:t.jsx("button",{type:"button",className:"primary-button",disabled:e.saving,onClick:e.onSave,children:e.saving?s("shell.butlerAutomationSaving"):s("shell.butlerAutomationSaveAction")})})]}),t.jsxs("section",{className:"butler-side-card butler-automation-detail-section",children:[t.jsx("header",{children:t.jsx("h2",{children:s("shell.butlerAutomationRunsTitle")})}),e.recentRuns.length>0?t.jsx("div",{className:"butler-automation-detail-run-list",children:e.recentRuns.map(n=>{var l,i;return t.jsxs("article",{className:"butler-automation-detail-run-card",children:[t.jsxs("header",{children:[t.jsx("strong",{children:s("shell.butlerAutomationRoundLabel",{round:n.runSeq})}),t.jsx("span",{className:"butler-automation-status-badge","data-status":Jl(n.status),children:ti(n.status)})]}),t.jsxs("div",{className:"butler-automation-detail-run-meta",children:[t.jsx("span",{children:Ql(n.triggerType)}),t.jsx("span",{children:ie(n.finishedAt||n.startedAt||n.createdAt)})]}),t.jsx("p",{children:((l=n.summary)==null?void 0:l.trim())||((i=n.error)==null?void 0:i.trim())||s("shell.butlerAutomationRunEmptySummary")})]},n.id)})}):t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerAutomationRunsEmpty")})]})]})}function Zr(e){const{triggerConfig:n}=e.automation;return n.type==="once"?t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationDueAtLabel")}),t.jsx("input",{type:"datetime-local",className:"butler-form-control",value:e.editorState.dueAt,disabled:e.saving,onChange:l=>{e.onEditorChange({dueAt:l.target.value})}})]}):n.type==="interval"?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationEverySecondsLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.everySeconds,disabled:e.saving,onChange:l=>{e.onEditorChange({everySeconds:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationEveryMinutesLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.everyMinutes,disabled:e.saving,onChange:l=>{e.onEditorChange({everyMinutes:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationEveryHoursLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.everyHours,disabled:e.saving,onChange:l=>{e.onEditorChange({everyHours:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationStopAtLabel")}),t.jsx("input",{type:"datetime-local",className:"butler-form-control",value:e.editorState.stopAt,disabled:e.saving,onChange:l=>{e.onEditorChange({stopAt:l.target.value})}})]})]}):n.type==="cron"?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationCronMinuteLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.cronMinute,disabled:e.saving,onChange:l=>{e.onEditorChange({cronMinute:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationCronHourLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.cronHour,disabled:e.saving,onChange:l=>{e.onEditorChange({cronHour:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field butler-form-field-wide",children:[t.jsx("span",{children:s("shell.butlerAutomationCronDaysOfWeekLabel")}),t.jsx("input",{className:"butler-form-control",value:e.editorState.cronDaysOfWeek,disabled:e.saving,onChange:l=>{e.onEditorChange({cronDaysOfWeek:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationStopAtLabel")}),t.jsx("input",{type:"datetime-local",className:"butler-form-control",value:e.editorState.stopAt,disabled:e.saving,onChange:l=>{e.onEditorChange({stopAt:l.target.value})}})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationPollIntervalLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.pollIntervalSeconds,disabled:e.saving,onChange:l=>{e.onEditorChange({pollIntervalSeconds:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationMaxChecksLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.maxChecks,disabled:e.saving,onChange:l=>{e.onEditorChange({maxChecks:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationExpiresAtLabel")}),t.jsx("input",{type:"datetime-local",className:"butler-form-control",value:e.editorState.expiresAt,disabled:e.saving,onChange:l=>{e.onEditorChange({expiresAt:l.target.value})}})]})]})}function Qr(e){return t.jsxs("section",{className:"butler-side-card butler-settings-panel",children:[t.jsx("header",{children:t.jsx("h2",{children:s("shell.butlerSettingsTitle")})}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerDisplayNameLabel")}),t.jsx("input",{"aria-label":s("shell.butlerDisplayNameLabel"),className:"butler-form-control",value:e.settingsForm.displayName,disabled:e.savingSettings,onChange:n=>{e.onSettingsFormChange({displayName:n.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAgentsModeLabel")}),t.jsxs("select",{"aria-label":s("shell.butlerAgentsModeLabel"),className:"butler-form-control",value:e.settingsForm.agentsMode,disabled:e.savingSettings,onChange:n=>{e.onSettingsFormChange({agentsMode:n.target.value})},children:[t.jsx("option",{value:"inline",children:s("shell.butlerAgentsModeInline")}),t.jsx("option",{value:"file",children:s("shell.butlerAgentsModeFile")})]}),t.jsx("small",{children:e.settingsForm.agentsMode==="file"?s("shell.butlerAgentsModeFileDescription"):s("shell.butlerAgentsModeInlineDescription")})]}),e.settingsForm.agentsMode==="file"?t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAgentsFilePathLabel")}),t.jsx("input",{"aria-label":s("shell.butlerAgentsFilePathLabel"),className:"butler-form-control butler-settings-file-path",value:e.settingsForm.agentsFilePath,readOnly:!0,disabled:e.savingSettings})]}):null,t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAgentsContentLabel")}),t.jsx("textarea",{"aria-label":s("shell.butlerAgentsContentLabel"),className:"butler-form-control butler-settings-agents-editor",rows:10,value:e.settingsForm.agentsContent,disabled:e.savingSettings,placeholder:s("shell.butlerAgentsContentPlaceholder"),onChange:n=>{e.onSettingsFormChange({agentsContent:n.target.value})}}),t.jsx("small",{children:s("shell.butlerAgentsContentHint")})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerPersonaToneLabel")}),t.jsxs("select",{"aria-label":s("shell.butlerPersonaToneLabel"),className:"butler-form-control",value:e.settingsForm.personaTone,disabled:e.savingSettings,onChange:n=>{e.onSettingsFormChange({personaTone:n.target.value})},children:[t.jsx("option",{value:"direct",children:s("shell.butlerToneDirect")}),t.jsx("option",{value:"steady",children:s("shell.butlerToneSteady")}),t.jsx("option",{value:"friendly",children:s("shell.butlerToneFriendly")})]})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerPersonaLanguageLabel")}),t.jsxs("select",{"aria-label":s("shell.butlerPersonaLanguageLabel"),className:"butler-form-control",value:e.settingsForm.personaLanguage,disabled:e.savingSettings,onChange:n=>{e.onSettingsFormChange({personaLanguage:n.target.value})},children:[t.jsx("option",{value:"zh-CN",children:s("shell.butlerLanguageZhCn")}),t.jsx("option",{value:"en-US",children:s("shell.butlerLanguageEnUs")}),t.jsx("option",{value:"bilingual",children:s("shell.butlerLanguageBilingual")})]})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerPersonaSummaryStyleLabel")}),t.jsxs("select",{"aria-label":s("shell.butlerPersonaSummaryStyleLabel"),className:"butler-form-control",value:e.settingsForm.personaSummaryStyle,disabled:e.savingSettings,onChange:n=>{e.onSettingsFormChange({personaSummaryStyle:n.target.value})},children:[t.jsx("option",{value:"brief",children:s("shell.butlerSummaryBrief")}),t.jsx("option",{value:"structured",children:s("shell.butlerSummaryStructured")}),t.jsx("option",{value:"thorough",children:s("shell.butlerSummaryThorough")})]})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerFocusRiskPreferenceLabel")}),t.jsxs("select",{"aria-label":s("shell.butlerFocusRiskPreferenceLabel"),className:"butler-form-control",value:e.settingsForm.focusRiskPreference,disabled:e.savingSettings,onChange:n=>{e.onSettingsFormChange({focusRiskPreference:n.target.value})},children:[t.jsx("option",{value:"conservative",children:s("shell.butlerRiskConservative")}),t.jsx("option",{value:"balanced",children:s("shell.butlerRiskBalanced")}),t.jsx("option",{value:"proactive",children:s("shell.butlerRiskProactive")})]})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerReportPriorityPresetLabel")}),t.jsxs("select",{"aria-label":s("shell.butlerReportPriorityPresetLabel"),className:"butler-form-control",value:e.settingsForm.reportPriorityPreset,disabled:e.savingSettings,onChange:n=>{e.onSettingsFormChange({reportPriorityPreset:n.target.value})},children:[t.jsx("option",{value:"risk-first",children:s("shell.butlerReportRiskFirst")}),t.jsx("option",{value:"blocker-first",children:s("shell.butlerReportBlockerFirst")}),t.jsx("option",{value:"verification-first",children:s("shell.butlerReportVerificationFirst")}),t.jsx("option",{value:"progress-first",children:s("shell.butlerReportProgressFirst")})]})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerSummaryDebounceLabel")}),t.jsx("select",{"aria-label":s("shell.butlerSummaryDebounceLabel"),className:"butler-form-control",value:String(e.settingsForm.summaryDebounceSeconds),disabled:e.savingSettings,onChange:n=>{e.onSettingsFormChange({summaryDebounceSeconds:Number(n.target.value)})},children:Tr.map(n=>t.jsx("option",{value:n.value,children:s(n.labelKey)},n.value))})]}),t.jsx("div",{className:"butler-inline-actions",children:t.jsx("button",{type:"button",className:"primary-button",disabled:e.savingSettings,onClick:e.onSaveSettings,children:e.savingSettings?s("shell.butlerSettingsSaving"):s("shell.butlerSettingsSaveAction")})})]})}function ie(e){if(!e)return"-";const n=new Date(e);return Number.isNaN(n.getTime())?e:new Intl.DateTimeFormat(void 0,{year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(n)}function it(e){return e.updatedAt||e.lastAutomationAt||e.lastCheckedAt||e.createdAt}function Jr(e){return e.kind==="timer"?e.timer.id:e.automation.id}function Bt(e){return e.kind==="timer"?e.timer.dueAt:e.automation.nextRunAt}function ds(e){var n,l,i,r,c,d;return e.kind==="timer"?((i=(l=(n=e.timer.controlSession)==null?void 0:n.session)==null?void 0:l.workspaceId)==null?void 0:i.trim())||null:((d=(c=(r=e.automation.controlSession)==null?void 0:r.session)==null?void 0:c.workspaceId)==null?void 0:d.trim())||null}function Ln(e){var n,l,i,r,c,d,f,h,x,v,A;return e.kind==="timer"?((n=e.timer.targetSessionId)==null?void 0:n.trim())||((r=(i=(l=e.timer.controlSession)==null?void 0:l.session)==null?void 0:i.sessionId)==null?void 0:r.trim())||((c=e.timer.sessionId)==null?void 0:c.trim())||null:((d=e.automation.actionConfig.targetSessionId)==null?void 0:d.trim())||((x=(h=(f=e.automation.controlSession)==null?void 0:f.session)==null?void 0:h.sessionId)==null?void 0:x.trim())||((A=(v=e.automation.controlSession)==null?void 0:v.sessionId)==null?void 0:A.trim())||null}function ea(e){return e.kind==="timer"||e.automation.triggerType==="once"}function ta(e,n){const l=w(Bt(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueLead"):s("shell.butlerControlTimerCountdownLead")}function na(e,n){const l=w(Bt(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueTail"):s("shell.butlerControlTimerCountdownTail")}function sa(e,n){const l=w(Bt(e));return!l||l<=n?"00:00":pa(l-n)}function la(e){return e.kind==="timer"?da(e.timer):e.automation.actionConfig.content.trim()||s("conversation.butlerAnalysisEmpty")}function ia(e){if(e.kind==="timer")return s("shell.butlerControlTimerTypeOnce");switch(e.automation.triggerType){case"once":return s("shell.butlerControlTimerTypeOnce");case"interval":case"cron":return s("shell.butlerControlTimerTypeRepeat");case"condition":return s("shell.butlerControlTimerTypeConditional");default:return s("shell.butlerControlTimerTypeOther")}}function Wl(e,n,l="active"){const i=new Map(((n==null?void 0:n.projects)??[]).map(c=>[c.id,c.name]));return e.filter(c=>l==="history"?c.status!=="active":c.status==="active").map(c=>({id:`assistant-automation:${c.id}`,automationId:c.id,kind:"assistant_automation",title:ni(c),projectName:bs(c,i),status:Ea(c.status),taskTypeLabel:Zl(c.triggerType),statusLabel:ei(c.status),nextRunAt:c.nextRunAt,lastRunAt:c.lastRunAt||c.updatedAt})).sort((c,d)=>{const f=w(c.nextRunAt),h=w(d.nextRunAt);return f!==h?f===0?1:h===0?-1:f-h:w(d.lastRunAt)-w(c.lastRunAt)}).slice(0,10)}function Kl(e,n,l,i="active"){const r=h=>h==="active"||h==="waiting_user",c=new Map(((l==null?void 0:l.projects)??[]).map(h=>[h.id,h.name])),d=new Map(e.map(h=>[h.id,h]));return n.map(h=>{const x=d.get(h.automationId);return{run:h,automation:x,normalizedStatus:Jl(h.status)}}).filter(({automation:h})=>!!h).filter(({normalizedStatus:h})=>i==="history"?!r(h):r(h)).map(({run:h,automation:x,normalizedStatus:v})=>{var A,H;return{id:`assistant-automation-run:${h.id}`,automationId:h.automationId,kind:"assistant_automation_run",title:ni(x),projectName:bs(x,c),status:v,sourceLabel:Ql(h.triggerType),statusLabel:ti(h.status),summary:((A=h.summary)==null?void 0:A.trim())||((H=h.error)==null?void 0:H.trim())||s("shell.butlerAutomationRunEmptySummary"),createdAt:h.finishedAt||h.startedAt||h.createdAt}}).sort((h,x)=>w(x.createdAt)-w(h.createdAt)).slice(0,12)}function ra(e){if(e.loading)return t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerAutomationRoundLoading")});if(e.error)return t.jsx("p",{className:"butler-secondary-text",children:e.error});if(!e.task)return t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerAutomationRoundEmpty")});const n=[...e.task.rounds??[]].sort((l,i)=>w(i.createdAt)-w(l.createdAt));return t.jsxs("div",{className:"butler-follow-up-rounds",children:[t.jsxs("div",{className:"butler-follow-up-round-summary",children:[t.jsx("strong",{children:e.task.objective}),t.jsx("span",{children:s("conversation.butlerCurrentFollowUpProgress",{current:e.task.autoContinueCount,max:e.task.maxAutoContinueCount??5})})]}),n.length>0?t.jsx("div",{className:"butler-follow-up-round-list",children:n.map(l=>t.jsxs("article",{className:"butler-follow-up-round-card",children:[t.jsxs("header",{className:"butler-follow-up-round-header",children:[t.jsxs("div",{children:[t.jsx("strong",{children:s("shell.butlerAutomationRoundLabel",{round:l.roundNumber})}),t.jsx("span",{children:ka(l.kind)})]}),t.jsx("span",{children:ie(l.createdAt)})]}),t.jsxs("div",{className:"butler-follow-up-round-body",children:[t.jsxs("p",{children:[s("shell.butlerAutomationRoundProcessedAtLabel"),":",ie(l.createdAt)]}),t.jsxs("p",{children:[s("shell.butlerAutomationRoundStatusLabel"),":",hs(l.status)]}),l.observedRunningState?t.jsxs("p",{children:[s("shell.butlerAutomationRoundObservedStateLabel"),":",l.observedRunningState]}):null,t.jsxs("p",{children:[s("shell.butlerAutomationRoundSummaryLabel"),":",l.summary||s("conversation.butlerAnalysisEmpty")]}),l.waitingReason?t.jsxs("p",{children:[s("shell.butlerAutomationRoundWaitingReasonLabel"),":",l.waitingReason]}):null,l.continuePrompt?t.jsxs("p",{children:[s("shell.butlerAutomationRoundPromptLabel"),":",l.continuePrompt]}):null]})]},`${l.roundNumber}:${l.createdAt}`))}):t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerAutomationRoundEmpty")})]})}function aa(e){return e.items.length===0?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerVerificationHistoryEmpty")}):t.jsx(Vl,{title:s("shell.butlerInfoVerificationRecordsTitle"),items:e.items,emptyText:s("shell.butlerVerificationHistoryEmpty"),cancellingVerificationId:e.cancellingVerificationId,onCancelVerificationRun:e.onCancelVerificationRun})}function oa(e){return e.taskItems.length===0&&e.runItems.length===0?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerAutomationHistoryEmpty")}):t.jsxs("div",{className:"butler-record-list",children:[e.taskItems.map(n=>t.jsxs("article",{className:"butler-automation-card",children:[t.jsxs("header",{className:"butler-automation-card-header",children:[t.jsxs("div",{className:"butler-automation-card-title-group",children:[t.jsx("strong",{children:n.title}),t.jsx("span",{children:n.projectName})]}),t.jsx("span",{className:"butler-automation-status-badge","data-status":n.status,children:n.statusLabel})]}),t.jsxs("div",{className:"butler-automation-card-body",children:[t.jsxs("div",{className:"butler-automation-row",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskTypeLabel")}),t.jsx("strong",{children:n.taskTypeLabel})]}),t.jsxs("div",{className:"butler-automation-row",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskLastRunLabel")}),t.jsx("strong",{children:ie(n.lastRunAt)})]})]}),t.jsxs("footer",{className:"butler-automation-card-footer",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskNextRunLabel")}),t.jsx("strong",{children:ie(n.nextRunAt)})]})]},n.id)),e.runItems.map(n=>t.jsxs("article",{className:"butler-automation-card",children:[t.jsxs("header",{className:"butler-automation-card-header",children:[t.jsxs("div",{className:"butler-automation-card-title-group",children:[t.jsx("strong",{children:n.title}),t.jsx("span",{children:n.projectName})]}),t.jsx("span",{className:"butler-automation-status-badge","data-status":n.status,children:n.statusLabel})]}),t.jsxs("div",{className:"butler-automation-card-body",children:[t.jsxs("div",{className:"butler-automation-row",children:[t.jsx("span",{children:s("shell.butlerAutomationRunSourceLabel")}),t.jsx("strong",{children:n.sourceLabel})]}),t.jsxs("div",{className:"butler-automation-row",children:[t.jsx("span",{children:s("shell.butlerAutomationRunSummaryLabel")}),t.jsx("strong",{children:n.summary})]})]}),t.jsxs("footer",{className:"butler-automation-card-footer",children:[t.jsx("span",{children:s("shell.butlerAutomationRunProcessedAtLabel")}),t.jsx("strong",{children:ie(n.createdAt)})]})]},n.id))]})}function Yl(e,n){return[...e].filter(l=>n==="history"?!sl(l.status):sl(l.status)).sort((l,i)=>w(Zn(i))-w(Zn(l))).slice(0,5).map(l=>{var i,r;return{id:l.id,title:((i=l.targetRef)==null?void 0:i.trim())||l.verificationType,subtitle:l.verificationType,status:Sa(l.status),content:((r=l.summary)==null?void 0:r.trim())||s("shell.butlerInfoVerificationFallback",{status:l.status}),meta:ie(Zn(l)),verification:l}})}function Js(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(r.updatedAt)-w(i.updatedAt))}function el(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(it(r))-w(it(i)))}function ua(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(r.updatedAt)-w(i.updatedAt))}function tl(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(nl(r))-w(nl(i)))}function os(e){return e==="active"||e==="waiting_user"}function nl(e){return e.dueAt||e.triggeredAt||e.cancelledAt||e.updatedAt||e.createdAt}function ca(e){var n,l,i,r,c,d;return((n=e.title)==null?void 0:n.trim())||((i=(l=e.controlSession)==null?void 0:l.title)==null?void 0:i.trim())||((d=(c=(r=e.controlSession)==null?void 0:r.session)==null?void 0:c.title)==null?void 0:d.trim())||e.content.trim()}function da(e){return e.content.trim()||ca(e)}function ma(e,n,l,i,r){var f,h,x,v;const c=(f=e.projectId)==null?void 0:f.trim();if(c&&n.has(c))return n.get(c);const d=((v=(x=(h=e.controlSession)==null?void 0:h.session)==null?void 0:x.workspaceId)==null?void 0:v.trim())||i.trim();return d?l.has(d)?l.get(d):d===i.trim()&&(r!=null&&r.trim())?r.trim():s("shell.butlerControlTimerUnknownWorkspace"):s("shell.butlerControlTimerUnknownWorkspace")}function ha(e,n,l,i,r){var f;if(e.kind==="timer")return ma(e.timer,n,l,i,r);const c=(f=e.automation.projectId)==null?void 0:f.trim();if(c&&n.has(c))return n.get(c);const d=ds(e)||i.trim();return d?l.has(d)?l.get(d):d===i.trim()&&(r!=null&&r.trim())?r.trim():s("shell.butlerControlTimerUnknownWorkspace"):s("shell.butlerControlTimerUnknownWorkspace")}function ba(e,n){var r,c,d,f,h,x,v;const l=(r=e.targetSessionId)==null?void 0:r.trim();if(l&&n.has(l))return n.get(l);if((f=(d=(c=e.controlSession)==null?void 0:c.session)==null?void 0:d.title)!=null&&f.trim())return e.controlSession.session.title.trim();const i=((v=(x=(h=e.controlSession)==null?void 0:h.session)==null?void 0:x.sessionId)==null?void 0:v.trim())||e.sessionId.trim();return i&&n.has(i)?n.get(i):s("shell.butlerControlTimerUnknownSession")}function fa(e,n){var i,r,c;if(e.kind==="timer")return ba(e.timer,n);const l=Ln(e);return l&&n.has(l)?n.get(l):(c=(r=(i=e.automation.controlSession)==null?void 0:i.session)==null?void 0:r.title)!=null&&c.trim()?e.automation.controlSession.session.title.trim():s("shell.butlerControlTimerUnknownSession")}function ga(){return t.jsx("svg",{viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",focusable:"false",children:t.jsx("path",{fill:"currentColor",d:"M8 1.25a6.75 6.75 0 1 0 0 13.5A6.75 6.75 0 0 0 8 1.25Zm0 1.5a5.25 5.25 0 1 1 0 10.5A5.25 5.25 0 0 1 8 2.75Zm0 2.5a.875.875 0 1 0 0 1.75a.875.875 0 0 0 0-1.75Zm-.875 3.125a.625.625 0 1 0 0 1.25h.25v1.75h-.25a.625.625 0 1 0 0 1.25h1.75a.625.625 0 1 0 0-1.25h-.25V9a.625.625 0 0 0-.625-.625h-.875Z"})})}function pa(e){const n=Math.max(0,Math.ceil(e/1e3)),l=Math.floor(n/3600),i=Math.floor(n%3600/60),r=n%60;return l>0?`${String(l).padStart(2,"0")}:${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}`:`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function sl(e){return e==="queued"||e==="running"}function xa(e){return e.status==="active"||e.status==="waiting_user"}function va(e){return e.status==="queued"||e.status==="running"}function Sa(e){switch(e){case"queued":case"running":return s("shell.butlerAutomationStatusActive");case"passed":case"skipped":return s("shell.butlerAutomationStatusCompleted");case"failed":return s("shell.butlerAutomationStatusFailed");case"cancelled":return s("shell.butlerAutomationStatusCancelled");default:return e}}function ya(e){return e==="failed"?"failed":e==="cancelled"?"cancelled":e==="passed"||e==="skipped"?"completed":"active"}function Aa(e){switch(e){case"analyzing":return s("shell.butlerTodoLifecycleAnalyzing");case"analyzed":return s("shell.butlerTodoLifecycleAnalyzed");case"session_created":return s("shell.butlerTodoLifecycleSessionCreated");case"follow_up_active":return s("shell.butlerTodoLifecycleFollowUpActive");case"completed":return s("shell.butlerTodoLifecycleCompleted");case"failed":return s("shell.butlerTodoLifecycleFailed");case"pending":default:return s("shell.butlerTodoLifecyclePending")}}function Zn(e){return e.finishedAt||e.startedAt||e.createdAt}function w(e){if(!e)return 0;const n=new Date(e).getTime();return Number.isNaN(n)?0:n}function st(e){return typeof e=="number"&&Number.isFinite(e)?String(e):""}function ja(e){const n=e.trim();return n||null}function xn(e){if(!e)return"";const n=new Date(e);if(Number.isNaN(n.getTime()))return"";const l=n.getFullYear(),i=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0"),c=String(n.getHours()).padStart(2,"0"),d=String(n.getMinutes()).padStart(2,"0");return`${l}-${i}-${r}T${c}:${d}`}function wn(e,n){const l=e.trim();if(!l)return null;const i=Date.parse(l);if(Number.isNaN(i))throw new Error(`${n}${s("shell.butlerAutomationInvalidDateSuffix")}`);return new Date(i).toISOString()}function Ca(e,n){const l=wn(e,n);if(!l)throw new Error(`${n}${s("shell.butlerAutomationRequiredSuffix")}`);return l}function Xl(e,n){const l=e.trim();if(!l)throw new Error(`${n}${s("shell.butlerAutomationRequiredSuffix")}`);const i=Number.parseInt(l,10);if(!Number.isInteger(i))throw new Error(`${n}${s("shell.butlerAutomationInvalidNumberSuffix")}`);return i}function Gl(e,n){const l=e.trim();if(!l)return null;const i=Number.parseInt(l,10);if(!Number.isInteger(i))throw new Error(`${n}${s("shell.butlerAutomationInvalidNumberSuffix")}`);return i}function vn(e,n){const l=Gl(e,n);if(l===null)return null;if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function wa(e,n){const l=Xl(e,n);if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Ia(e){const n=e.trim();if(!n)return null;const l=n.split(",").map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isInteger(i));if(l.length===0||l.some(i=>i<0||i>6))throw new Error(s("shell.butlerAutomationCronDaysValidation"));return Array.from(new Set(l)).sort((i,r)=>i-r)}function ms(e){const n=w(e);return n<=0?"-":new Intl.DateTimeFormat("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(new Date(n))}function Na(e){for(const[n,l]of Object.entries(as))if(l.length===e.length&&l.every((i,r)=>i===e[r]))return n;return"risk-first"}function Ta(e){var i;if((i=e.agentsFilePath)!=null&&i.trim())return e.agentsFilePath.trim();const n=e.workspacePath.includes("\\")?"\\":"/";return`${e.workspacePath.replace(/[\\/]+$/,"")}${n}AGENTS.md`}function Ra(e){switch(e){case"pending":return s("shell.butlerInfoTodoPending");case"in_progress":return s("shell.butlerInfoTodoInProgress");case"closed":return s("shell.butlerInfoTodoClosed");default:return s("shell.butlerInfoTodoPending")}}function hs(e){switch(e){case"active":return s("shell.butlerAutomationStatusActive");case"waiting_user":return s("shell.butlerAutomationStatusWaitingUser");case"completed":return s("shell.butlerAutomationStatusCompleted");case"failed":return s("shell.butlerAutomationStatusFailed");case"cancelled":return s("shell.butlerAutomationStatusCancelled");default:return s("shell.butlerAutomationStatusActive")}}function ka(e){switch(e){case"started":return s("shell.butlerAutomationRoundKindStarted");case"continue":return s("shell.butlerAutomationRoundKindContinue");case"queued":return s("shell.butlerAutomationRoundKindQueued");case"waiting_user":return s("shell.butlerAutomationRoundKindWaitingUser");case"completed":return s("shell.butlerAutomationRoundKindCompleted");case"failed":return s("shell.butlerAutomationRoundKindFailed");case"cancelled":return s("shell.butlerAutomationRoundKindCancelled");case"limit_reached":return s("shell.butlerAutomationRoundKindLimitReached");default:return e}}function Zl(e){switch(e){case"once":return s("shell.butlerAutomationTaskTypeControlTimer");case"interval":return s("shell.butlerAutomationTaskTypeInterval");case"cron":return s("shell.butlerAutomationTaskTypeCron");case"condition":return s("shell.butlerAutomationTaskTypeFollowUp");default:return s("shell.butlerAutomationTaskTypeControlTimer")}}function Ql(e){return e==="interval"||e==="cron"?s("shell.butlerAutomationRunSourcePatrol"):e==="once"?s("shell.butlerAutomationRunSourceControlTimer"):s("shell.butlerAutomationRunSourceFollowUp")}function Jl(e){switch(e){case"failed":return"failed";case"cancelled":return"cancelled";case"completed":case"passed":case"succeeded":return"completed";case"waiting_user":return"waiting_user";case"active":case"queued":case"running":default:return"active"}}function Ea(e){switch(e){case"failed":return"failed";case"cancelled":return"cancelled";case"completed":return"completed";case"paused":return"waiting_user";case"active":default:return"active"}}function ei(e){switch(e){case"completed":return s("shell.butlerAutomationStatusCompleted");case"failed":return s("shell.butlerAutomationStatusFailed");case"cancelled":return s("shell.butlerAutomationStatusCancelled");case"paused":return s("shell.butlerAutomationStatusWaitingUser");case"active":default:return s("shell.butlerAutomationStatusActive")}}function ti(e){switch(e){case"succeeded":return s("shell.butlerAutomationStatusCompleted");case"failed":return s("shell.butlerAutomationStatusFailed");case"cancelled":case"skipped":return s("shell.butlerAutomationStatusCancelled");case"queued":case"running":default:return s("shell.butlerAutomationStatusActive")}}function ni(e){var n,l;return((n=e.title)==null?void 0:n.trim())||((l=e.actionConfig.targetSessionId)==null?void 0:l.trim())||e.actionConfig.content.trim()||e.id}function bs(e,n){var l,i;return e.projectId&&n.has(e.projectId)?n.get(e.projectId):((i=(l=e.controlSession)==null?void 0:l.session)==null?void 0:i.workspaceId)||s("shell.butlerControlTimerNoProject")}function La(e,n){var i,r,c;const l=(i=e.actionConfig.targetSessionId)==null?void 0:i.trim();return l&&n.has(l)?n.get(l):(c=(r=e.controlSession)==null?void 0:r.title)!=null&&c.trim()?e.controlSession.title.trim():l||null}function ll(e){var l;const n={title:((l=e.title)==null?void 0:l.trim())||"",content:e.actionConfig.content,includeTriggerContext:e.actionConfig.includeTriggerContext,dueAt:"",everySeconds:"",everyMinutes:"",everyHours:"",stopAt:"",cronMinute:"",cronHour:"",cronDaysOfWeek:"",pollIntervalSeconds:"",expiresAt:"",maxChecks:""};return e.triggerConfig.type==="once"?n.dueAt=xn(e.triggerConfig.dueAt):e.triggerConfig.type==="interval"?(n.everySeconds=st(e.triggerConfig.seconds),n.everyMinutes=st(e.triggerConfig.minutes),n.everyHours=st(e.triggerConfig.hours),n.stopAt=xn(e.triggerConfig.stopAt)):e.triggerConfig.type==="cron"?(n.cronMinute=st(e.triggerConfig.minute),n.cronHour=st(e.triggerConfig.hour),n.cronDaysOfWeek=(e.triggerConfig.daysOfWeek??[]).join(","),n.stopAt=xn(e.triggerConfig.stopAt)):(n.pollIntervalSeconds=st(e.triggerConfig.pollIntervalSeconds),n.expiresAt=xn(e.triggerConfig.expiresAt),n.maxChecks=st(e.triggerConfig.maxChecks)),n}function Pa(e,n){const l={title:ja(n.title),content:n.content.trim(),includeTriggerContext:n.includeTriggerContext};if(!l.content)throw new Error(s("shell.butlerAutomationPromptRequired"));return e.triggerConfig.type==="once"?{...l,dueAt:Ca(n.dueAt,s("shell.butlerAutomationDueAtLabel"))}:e.triggerConfig.type==="interval"?{...l,everySeconds:vn(n.everySeconds,s("shell.butlerAutomationEverySecondsLabel")),everyMinutes:vn(n.everyMinutes,s("shell.butlerAutomationEveryMinutesLabel")),everyHours:vn(n.everyHours,s("shell.butlerAutomationEveryHoursLabel")),stopAt:wn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:e.triggerConfig.type==="cron"?{...l,cronMinute:Xl(n.cronMinute,s("shell.butlerAutomationCronMinuteLabel")),cronHour:Gl(n.cronHour,s("shell.butlerAutomationCronHourLabel")),cronDaysOfWeek:Ia(n.cronDaysOfWeek),stopAt:wn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:{...l,pollIntervalSeconds:wa(n.pollIntervalSeconds,s("shell.butlerAutomationPollIntervalLabel")),expiresAt:wn(n.expiresAt,s("shell.butlerAutomationExpiresAtLabel")),maxChecks:vn(n.maxChecks,s("shell.butlerAutomationMaxChecksLabel"))}}function si(e){switch(e){case"archived":return s("shell.butlerAutomationStatusCompleted");case"expired":return s("shell.butlerAutomationStatusCancelled");case"orphaned":return s("shell.butlerSandboxStatusOrphaned");case"deleted":return s("shell.butlerAutomationStatusFailed");case"active":default:return s("shell.butlerAutomationStatusActive")}}function li(e){switch(e){case"archived":return"completed";case"expired":return"cancelled";case"orphaned":return"waiting_user";case"deleted":return"failed";case"active":default:return"active"}}function ii(e){return e==="clone"?s("shell.butlerSandboxSourceClone"):s("shell.butlerSandboxSourceBlank")}function ri(e){return e==="pinned"?s("shell.butlerSandboxVisibilityPinned"):s("shell.butlerSandboxVisibilityAssistantOnly")}function Ct(e,n,l){const i=e.filter(r=>r.id!==n.id);return n.status==="deleted"?i.sort((r,c)=>w(c.updatedAt)-w(r.updatedAt)):l&&n.controlSessionId!==l&&e.every(r=>r.id!==n.id)?i.sort((r,c)=>w(c.updatedAt)-w(r.updatedAt)):[n,...i].sort((r,c)=>w(c.updatedAt)-w(r.updatedAt))}function Sn(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(il(r))-w(il(i)))}function il(e){return e.updatedAt||e.lastRunAt||e.nextRunAt||e.createdAt}function Ma(e){const l=`${e.displayName.trim()}:${e.providerId}:${e.tone}`,i=Fa(e);if(!l)return Re.default[0];const r=Array.from(l).reduce((c,d)=>{const f=d.codePointAt(0)??0;return c+f},0);return i[r%i.length]}function Fa(e){const n=e.displayName.trim().toLowerCase();return/(bot|ai|智能|助手|助理|管家|buddy|helper)/.test(n)?Re.builder:/(书|学|知|研|析|查|review|audit|scan)/.test(n)?Re.analyst:e.tone==="friendly"?Re.friendly:e.tone==="steady"?Re.steady:e.tone==="direct"?e.providerId==="claude-code"?Re.analyst:Re.direct:e.providerId==="claude-code"?Re.analyst:Re.default}function Ve(e,n){var l;return((l=e.find(i=>i.value===n))==null?void 0:l.label)??n}function Da(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[t.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),t.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})}function Oa(){return t.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round",strokeLinejoin:"round",children:[t.jsx("circle",{cx:"12",cy:"12",r:"8.25",fill:"none"}),t.jsx("path",{d:"M12 8.4v4.1l2.75 1.9",fill:"none"})]})}const ai="mobile.butler.active-tab",In=["info","automation","settings"],Ua=15e3,fs=56,gs=1.2,rl=360,Ha=1500,Ba=1500;function $a(e){const[n,l]=u.useState(e),i=u.useRef(null);return u.useEffect(()=>{if(e){i.current!==null&&(window.clearTimeout(i.current),i.current=null),l(e);return}!n||i.current!==null||(i.current=window.setTimeout(()=>{i.current=null,l(null)},Ha))},[e,n]),u.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),e??n}function _a(e,n){const[l,i]=u.useState(n),r=u.useRef(null);return u.useEffect(()=>{r.current!==null&&(window.clearTimeout(r.current),r.current=null),i(n)},[e]),u.useEffect(()=>{if(n){r.current!==null&&(window.clearTimeout(r.current),r.current=null),i(!0);return}!l||r.current!==null||(r.current=window.setTimeout(()=>{r.current=null,i(!1)},Ba))},[n,l]),u.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),l}function Va(e,n){return n===!0?!0:e?e.session.activityState==="running"||e.session.runningState==="starting"||e.session.runningState==="running"||e.session.runningState==="reconnecting":!1}function qa(){if(typeof window>"u")return"info";try{const e=window.localStorage.getItem(ai);return e==="automation"||e==="settings"?e:"info"}catch{return"info"}}function za(e){var n,l,i;return((n=e.title)==null?void 0:n.trim())||((l=e.session.title)==null?void 0:l.trim())||((i=e.lastSummary)==null?void 0:i.trim())||e.sessionId}function Wa(e,n){return e==="settings"?"settings":e==="automation"?"automation":e==="info"?"info":n}function Ka(e,n,l){if(!n)return{closeSidebar:!1,nextTab:e};const i=l.x-n.x,r=l.y-n.y;if(Math.abs(i)<fs)return{closeSidebar:!1,nextTab:e};if(Math.abs(i)<Math.abs(r)*gs)return{closeSidebar:!1,nextTab:e};const c=In.indexOf(e);if(i>0&&c===0)return{closeSidebar:!0,nextTab:e};const d=i<0?Math.min(In.length-1,c+1):Math.max(0,c-1);return{closeSidebar:!1,nextTab:In[d]??e}}function Ya(e,n){if(!e)return null;const l=n.x-e.x,i=n.y-e.y;return Math.abs(l)<fs||Math.abs(l)<Math.abs(i)*gs?null:l>0?"list":"sidebar"}function Qn(e){return e instanceof Element?!!e.closest("input, textarea, select, option, label, button, a, [contenteditable='true'], [data-mobile-butler-gesture='ignore']"):!1}function Xa(){var xt,vt,je,St,Ot,rn,Je,an,on,un,cn;const{workspaceId:e=""}=Tl(),n=ar(),l=Rl(),{showToast:i}=kl(),{navigationGroups:r,requestNavigationRefresh:c,selectWorkspace:d}=us(),f=((xt=r.find(o=>o.workspace.id===e))==null?void 0:xt.workspace)??null,h=u.useMemo(()=>new Map(r.map(o=>[o.workspace.id,o.workspace.name])),[r]),x=u.useMemo(()=>new Map(r.flatMap(o=>o.sessions.map(b=>{var S;return[b.sessionId,((S=b.title)==null?void 0:S.trim())||s("common.unknown")]}))),[r]),v=u.useMemo(()=>new Map(r.flatMap(o=>o.sessions.map(b=>[b.sessionId,o.workspace.id]))),[r]),A=new URLSearchParams(n.search).get("tab"),H=u.useRef(qa()),P=Wa(A,H.current),T=u.useRef(null),B=u.useRef(null),z=u.useRef(null),W=u.useRef(null),Z=u.useRef(null),[K,$]=u.useState(null),[re,q]=u.useState(null),[qe,vs]=u.useState(null),[Ee,$t]=u.useState(null),[de,rt]=u.useState(null),[Le,Q]=u.useState(null),[_,me]=u.useState(null),[Pe,Me]=u.useState(null),[at,_t]=u.useState(null),[ot,Vt]=u.useState(null),[qt,ut]=u.useState(null),[zt,he]=u.useState(null),[ct,Fe]=u.useState(()=>Date.now()),[J,dt]=u.useState(null),[pe,Wt]=u.useState(null),[y,F]=u.useState({loading:!0,initialized:!1,profile:null,overview:null,followUpTasks:[],inboxItems:[],patrolPlans:[],controlSessions:[],controlTimers:[],assistantAutomations:[],assistantAutomationRuns:[]}),Kt=u.useMemo(()=>{var o;return new Map((((o=y.overview)==null?void 0:o.projects)??[]).map(b=>[b.id,b.name]))},[(vt=y.overview)==null?void 0:vt.projects]);(!W.current||Z.current!==e)&&(W.current=new Bl(e),Z.current=e);const L=W.current,wt=R(L,o=>o.loading),xe=R(L,o=>o.initialized),Y=R(L,o=>o.profile),ae=R(L,o=>o.activeProvider),I=R(L,o=>o.controlSession),It=R(L,o=>o.capabilities),Nt=R(L,o=>o.messages),Mn=R(L,o=>o.historyState),mt=R(L,o=>o.loadingOlderMessages),Fn=R(L,o=>o.hasOlderMessages),ze=R(L,o=>o.sending),ve=R(L,o=>o.runtimeHasActiveRun),ht=R(L,o=>o.runtimeCanInterrupt),Dn=R(L,o=>o.contextUsage),We=R(L,o=>o.permissionRequests),{composerPortalTarget:On}=ir(),bt=u.useRef(null),be=u.useRef(null),oe=u.useRef(!1),Se=u.useRef(new Set);u.useEffect(()=>{if(H.current=P,!(typeof window>"u"))try{window.localStorage.setItem(ai,P)}catch{}},[P]),u.useEffect(()=>{if(A===P)return;const o=new URLSearchParams(n.search);o.set("tab",P),l({pathname:n.pathname,search:`?${o.toString()}`},{replace:!0})},[P,n.pathname,n.search,l,A]),u.useEffect(()=>{e&&d(e)},[d,e]),u.useEffect(()=>{e&&L.initialize()},[L,e]),u.useEffect(()=>{var ne,Ie,E,Ne,Be;const o=((ne=I==null?void 0:I.session)==null?void 0:ne.sessionId)??null;if(be.current!==o&&(be.current=o,oe.current=!1,Se.current=new Set),!o)return;const b=We.filter(fe=>fe.status==="pending"),S=new Set(b.map(fe=>fe.id)),C=((Ie=I==null?void 0:I.title)==null?void 0:Ie.trim())||((Ne=(E=I==null?void 0:I.session)==null?void 0:E.title)==null?void 0:Ne.trim())||((Be=Y==null?void 0:Y.displayName)==null?void 0:Be.trim())||s("shell.butlerEntry");oe.current&&b.forEach(fe=>{Se.current.has(fe.id)||i({id:`mobile-butler-permission-request-${fe.id}`,title:s("conversation.permissionRequestToastTitle"),description:s("conversation.backgroundPermissionToastDescription",{title:C,requestTitle:fe.title}),tone:"warning",durationMs:8e3})}),Se.current=S,oe.current=!0},[(je=I==null?void 0:I.session)==null?void 0:je.sessionId,(St=I==null?void 0:I.session)==null?void 0:St.title,I==null?void 0:I.title,We,Y==null?void 0:Y.displayName,i]),u.useEffect(()=>{if(!e){F({loading:!1,initialized:!1,profile:null,overview:null,followUpTasks:[],inboxItems:[],patrolPlans:[],controlSessions:[],controlTimers:[],assistantAutomations:[],assistantAutomationRuns:[]});return}let o=!1;async function b(Ie){F(E=>({...E,loading:!0}));try{const E=await yl();if(!E.initialized||!E.profile){o||F({loading:!1,initialized:!1,profile:null,overview:null,followUpTasks:[],inboxItems:[],patrolPlans:[],controlSessions:[],controlTimers:[],assistantAutomations:[],assistantAutomationRuns:[]});return}const[Ne,Be,fe,yt,et,Ut,dn]=await Promise.all([ts(),ns(),wl({workspaceId:e}),Tn(),Il(),ss({limit:100}),ls({limit:100})]),mn=Ne.overview.projects.filter(se=>se.workspaceId===e).map(se=>se.id),hn=await Promise.all(mn.map(se=>Nl(se)));if(o)return;F({loading:!1,initialized:!0,profile:E.profile,overview:Ne.overview,followUpTasks:Be.items.filter(se=>se.workspaceId===e),inboxItems:fe.items.filter(se=>se.status!=="closed"),patrolPlans:hn.flatMap(se=>se.items),controlSessions:yt.items,controlTimers:et.items,assistantAutomations:Ut.payload.items,assistantAutomationRuns:dn.payload.items})}catch(E){if(o)return;F(Ne=>({...Ne,loading:!1})),Ie&&i({title:s("shell.butlerLoadFailed"),description:E instanceof Error?E.message:void 0,tone:"error"})}}b(!0);const S=window.setInterval(()=>{b(!1)},Ua),C=Ol(()=>{b(!1)}),ne=()=>{b(!1)};return window.addEventListener(En,ne),()=>{o=!0,window.clearInterval(S),C(),window.removeEventListener(En,ne)}},[i,e]);const V=u.useMemo(()=>{var o;return new Set((((o=y.overview)==null?void 0:o.projects)??[]).filter(b=>b.workspaceId===e).map(b=>b.id))},[(Ot=y.overview)==null?void 0:Ot.projects,e]),Tt=u.useMemo(()=>y.controlTimers.filter(o=>{var b,S;return o.projectId?V.has(o.projectId):((S=(b=o.controlSession)==null?void 0:b.session)==null?void 0:S.workspaceId)===e}),[y.controlTimers,e,V]),Rt=u.useMemo(()=>y.followUpTasks.filter(o=>cl(o.status)),[y.followUpTasks]),Ke=u.useMemo(()=>{var o;return(((o=y.overview)==null?void 0:o.verifications)??[]).filter(b=>b.projectId?V.has(b.projectId):!1)},[(rn=y.overview)==null?void 0:rn.verifications,V]),Yt=u.useMemo(()=>[...Rt].sort((o,b)=>M(Ce(b))-M(Ce(o))).slice(0,4),[Rt]),ye=u.useMemo(()=>ol(Ke,"active"),[Ke]),De=u.useMemo(()=>ol(Ke,"history"),[Ke]),Xt=u.useMemo(()=>lo(y.inboxItems.filter(o=>o.status!=="closed")).slice(0,4),[y.inboxItems]),Oe=u.useMemo(()=>bl(y.assistantAutomations,y.overview,V,"active"),[y.assistantAutomations,y.overview,V]),kt=u.useMemo(()=>fl(y.assistantAutomations,y.assistantAutomationRuns,y.overview,V,"active"),[y.assistantAutomations,y.assistantAutomationRuns,y.overview,V]),ue=u.useMemo(()=>_?y.assistantAutomations.find(o=>o.id===_)??null:null,[_,y.assistantAutomations]),Et=u.useMemo(()=>_?y.assistantAutomationRuns.filter(o=>o.automationId===_).sort((o,b)=>M(b.createdAt)-M(o.createdAt)).slice(0,6):[],[_,y.assistantAutomationRuns]);u.useEffect(()=>{_&&!ue&&(me(null),Me(null))},[ue,_]);const Gt=u.useMemo(()=>[...y.followUpTasks].filter(o=>!cl(o.status)).sort((o,b)=>M(Ce(b))-M(Ce(o))).slice(0,8),[y.followUpTasks]),Lt=u.useMemo(()=>bl(y.assistantAutomations,y.overview,V,"history"),[y.assistantAutomations,y.overview,V]),Zt=u.useMemo(()=>fl(y.assistantAutomations,y.assistantAutomationRuns,y.overview,V,"history"),[y.assistantAutomations,y.assistantAutomationRuns,y.overview,V]),Un=u.useMemo(()=>Va(I,ve),[I,ve]),Ye=_a((I==null?void 0:I.session.sessionId)??null,Un),Hn=Ye||ze,Qt=Ye||ze,Bn=ht===!0||ze?!0:ht??!1,ft=u.useMemo(()=>{if(!I||Ye)return null;const o=Tt.filter(C=>C.status==="active"&&C.controlSessionId===I.id).map(C=>({kind:"timer",timer:C})),b=new Set(Tt.filter(C=>C.status==="active"&&C.controlSessionId===I.id).map(C=>C.id)),S=y.assistantAutomations.filter(C=>C.status==="active"&&C.controlSessionId===I.id&&!!C.nextRunAt&&!b.has(C.id)).map(C=>({kind:"automation",automation:C}));return[...o,...S].sort((C,ne)=>M(Pn(C))-M(Pn(ne)))[0]??null},[I,Ye,y.assistantAutomations,Tt]),ee=$a(ft),Pt=y.loading||wt,gt=!Pt&&(!y.initialized||!xe||!y.profile),pt=((Je=Y==null?void 0:Y.displayName)==null?void 0:Je.trim())||((on=(an=y.profile)==null?void 0:an.displayName)==null?void 0:on.trim())||s("shell.butlerEntry"),Mt=!I&&Nt.length===0,Ft=!gt&&K===null;u.useEffect(()=>{if(Fe(Date.now()),!ee)return;const o=window.setInterval(()=>{Fe(Date.now())},1e3);return()=>{window.clearInterval(o)}},[ee]),u.useEffect(()=>{K!=="sidebar"&&q(null)},[K]);const Jt=re==="follow_up"?t.jsx(al,{title:s("shell.butlerFollowUpHistoryTitle"),description:s("shell.butlerFollowUpHistoryDescription"),emptyText:s("shell.butlerInfoFollowUpRecordsEmpty"),onClose:()=>q(null),items:Gt.map(o=>{var b,S,C;return{id:o.id,title:((b=o.sessionTitle)==null?void 0:b.trim())||o.projectName,subtitle:o.projectName,status:gl(o.status),content:((S=o.waitingReason)==null?void 0:S.trim())||((C=o.lastAutomationSummary)==null?void 0:C.trim())||o.objective||s("shell.butlerInfoFollowUpFallback",{updatedAt:G(Ce(o))}),meta:G(Ce(o)),actionLabel:yn(o.status)?Ee===o.id?s("conversation.butlerFollowUpStopping"):s("conversation.butlerStopFollowUpAction"):null,actionDisabled:Ee===o.id,onAction:yn(o.status)?()=>{Ge(o)}:void 0}})}):re==="verification"?t.jsx(al,{title:s("shell.butlerVerificationHistoryTitle"),description:s("shell.butlerVerificationHistoryDescription"),emptyText:s("shell.butlerVerificationHistoryEmpty"),onClose:()=>q(null),items:De.map((o,b)=>({id:`${o.title}:${b}`,title:o.title,subtitle:o.subtitle,status:o.status,content:o.content,meta:o.meta,actionLabel:o.verification&&ml(o.verification.status)?de===o.verification.id?s("conversation.butlerVerificationStopping"):s("conversation.butlerStopVerificationAction"):null,actionDisabled:o.verification?de===o.verification.id:!1,onAction:o.verification?()=>{tn(o.verification)}:void 0}))}):re==="automation"?t.jsx(to,{taskItems:Lt,runItems:Zt,onClose:()=>q(null)}):P==="info"?t.jsxs(t.Fragment,{children:[t.jsx(Ht,{title:s("shell.butlerInfoFollowUpRecordsTitle"),emptyText:s("shell.butlerInfoFollowUpRecordsEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("follow_up"),items:Yt.map(o=>{var b,S,C;return{id:o.id,title:((b=o.sessionTitle)==null?void 0:b.trim())||o.projectName,subtitle:o.projectName,status:gl(o.status),content:((S=o.waitingReason)==null?void 0:S.trim())||((C=o.lastAutomationSummary)==null?void 0:C.trim())||o.objective||s("shell.butlerInfoFollowUpFallback",{updatedAt:G(Ce(o))}),meta:G(Ce(o)),actionLabel:yn(o.status)?Ee===o.id?s("conversation.butlerFollowUpStopping"):s("conversation.butlerStopFollowUpAction"):null,actionDisabled:Ee===o.id,onAction:yn(o.status)?()=>{Ge(o)}:void 0}})}),t.jsx(Ht,{title:s("shell.butlerInfoVerificationRecordsTitle"),emptyText:s("shell.butlerInfoVerificationRecordsEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("verification"),items:ye.map((o,b)=>({id:`${o.title}:${b}`,title:o.title,subtitle:o.subtitle,status:o.status,content:o.content,meta:o.meta,actionLabel:o.verification&&ml(o.verification.status)?de===o.verification.id?s("conversation.butlerVerificationStopping"):s("conversation.butlerStopVerificationAction"):null,actionDisabled:o.verification?de===o.verification.id:!1,onAction:o.verification?()=>{tn(o.verification)}:void 0}))}),t.jsx(eo,{title:s("shell.butlerInfoTodoRecordsTitle"),emptyText:s("shell.butlerInfoTodoRecordsEmpty"),items:Xt.map((o,b)=>({id:`${o.title}:${b}`,title:o.title,content:o.content}))})]}):P==="automation"?t.jsxs(t.Fragment,{children:[t.jsx(Za,{items:Oe,emptyText:s("shell.butlerAutomationTasksEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("automation"),selectedAutomationId:_,cancellingAutomationId:Le,onSelectAutomation:Ze,onCancelAutomation:o=>{nn(o)}}),ue&&Pe?t.jsx(Qa,{automation:ue,editorState:Pe,saving:at===ue.id,recentRuns:Et,workspaceNameById:h,sessionTitleById:x,onClose:()=>{me(null),Me(null)},onEditorChange:o=>{Me(b=>b&&{...b,...o})},onSave:()=>{Qe()}}):null,t.jsx(Ht,{title:s("shell.butlerAutomationRunsTitle"),emptyText:s("shell.butlerAutomationRunsEmpty"),items:kt.map(o=>({id:o.id,title:o.title,subtitle:o.projectName,status:o.statusLabel,content:`${o.sourceLabel} · ${o.summary}`,meta:G(o.createdAt)}))})]}):t.jsxs("section",{className:"mobile-feature-panel surface-card mobile-butler-record-section",children:[t.jsx("div",{className:"mobile-feature-section-header",children:t.jsx("div",{children:t.jsx("h2",{children:s("shell.butlerSidebarSettingsTab")})})}),t.jsxs("div",{className:"mobile-butler-settings-summary",children:[t.jsx(ke,{label:s("shell.butlerDisplayNameLabel"),value:pt}),t.jsx(ke,{label:s("shell.butlerProviderLabel"),value:Sl(ae)}),t.jsx(ke,{label:s("shell.mobileButlerAssistantWorkspaceLabel"),value:((un=y.profile)==null?void 0:un.workspacePath)??(f==null?void 0:f.path)??"-"})]})]});so(bt,qe,Ft,`${e}:${K??"none"}`);function Xe(o){o!==P&&(q(null),l(is(e,o),{replace:!0}))}function j(o){if(o.changedTouches.length!==1){T.current=null;return}if(Qn(o.target)){T.current=null;return}const b=o.changedTouches[0];T.current={x:b.clientX,y:b.clientY}}function Ae(o){if(o.changedTouches.length!==1)return;const b=T.current;T.current=null;const S=o.changedTouches[0],C=Ya(b,{x:S.clientX,y:S.clientY});C&&$(C)}function ce(o){if(o.changedTouches.length!==1){B.current=null;return}if(Qn(o.target)){B.current=null;return}const b=o.changedTouches[0];B.current={x:b.clientX,y:b.clientY}}function we(o){const b=B.current;if(B.current=null,!b||o.changedTouches.length!==1)return;const S=o.changedTouches[0],C=S.clientX-b.x,ne=S.clientY-b.y;C>-fs||Math.abs(C)<Math.abs(ne)*gs||$(null)}function X(o){if(o.changedTouches.length!==1){z.current=null;return}if(Qn(o.target)){z.current=null;return}const b=o.changedTouches[0];z.current={x:b.clientX,y:b.clientY}}function k(o){const b=z.current;if(z.current=null,o.changedTouches.length!==1)return;const S=o.changedTouches[0],C=Ka(P,b,{x:S.clientX,y:S.clientY});if(C.closeSidebar){$(null);return}C.nextTab!==P&&Xe(C.nextTab)}async function te(o){await L.openControlSession(o),$(null)}async function g(){const o=await Tn();F(b=>({...b,controlSessions:o.items}))}async function $n(){if(!(!J||pe)){Wt(J.id);try{await El(J.session.sessionId),J.id===(I==null?void 0:I.id)&&await L.openControlSession(""),dt(null),await g(),c(),$(null),i({title:s("shell.deleteSessionSuccess"),tone:"success"})}catch(o){i({title:o instanceof Error?o.message:s("shell.deleteSessionFailed"),tone:"error"})}finally{Wt(null)}}}async function D(){await L.startFreshSession(),$(null),c()}async function en(o,b){var S;(((S=b==null?void 0:b.attachments)==null?void 0:S.length)??0)>0&&i({title:s("shell.butlerAttachmentUnsupported"),tone:"warning"}),await L.sendMessage(o,{model:(b==null?void 0:b.model)??null,reasoningLevel:(b==null?void 0:b.reasoningLevel)??null,permissionMode:null}),c()}async function Ue(){const[o,b,S,C]=await Promise.all([ts(),ns(),ss({limit:100}),ls({limit:100})]);await L.reloadEventsAndOverview(),F(ne=>({...ne,overview:o.overview,followUpTasks:b.items.filter(Ie=>Ie.workspaceId===e),assistantAutomations:S.payload.items,assistantAutomationRuns:C.payload.items}))}async function Ge(o){$t(o.id);try{const b=await Al(o.id);F(S=>({...S,followUpTasks:io(S.followUpTasks,b.task)})),await Ue(),c(),i({title:s("conversation.butlerFollowUpStopped"),description:s("conversation.butlerFollowUpStoppedDescription"),tone:"success"})}catch(b){i({title:s("conversation.butlerFollowUpStopFailed"),description:b instanceof Error?b.message:void 0,tone:"error"})}finally{$t(null)}}async function tn(o){rt(o.id);try{await jl(o.projectId,o.id),await Ue(),c(),i({title:s("conversation.butlerVerificationStopped"),description:s("conversation.butlerVerificationStoppedDescription"),tone:"success"})}catch(b){i({title:s("conversation.butlerVerificationStopFailed"),description:b instanceof Error?b.message:void 0,tone:"error"})}finally{rt(null)}}async function _n(o){Vt(o);try{const b=await Rn(o);F(S=>({...S,controlTimers:ul(S.controlTimers,b.timer)})),i({title:s("shell.butlerControlTimerCancelSucceeded"),tone:"success"})}catch(b){i({title:s("shell.butlerControlTimerCancelFailed"),description:b instanceof Error?b.message:void 0,tone:"error"})}finally{Vt(null)}}function Ze(o){if(_===o){me(null),Me(null);return}const b=y.assistantAutomations.find(S=>S.id===o);b&&(me(o),Me(pl(b)))}async function Qe(){if(!ue||!Pe)return;let o;try{o=Co(ue,Pe)}catch(b){i({title:s("shell.butlerAutomationSaveFailed"),description:b instanceof Error?b.message:void 0,tone:"error"});return}_t(ue.id);try{const b=await Cl(ue.id,o);F(S=>({...S,assistantAutomations:Jn(S.assistantAutomations,b.payload.automation)})),me(b.payload.automation.id),Me(pl(b.payload.automation)),i({title:s("shell.butlerAutomationSaveSucceeded"),tone:"success"})}catch(b){i({title:s("shell.butlerAutomationSaveFailed"),description:b instanceof Error?b.message:void 0,tone:"error"})}finally{_t(null)}}async function nn(o){Q(o);try{const b=await kn(o);F(S=>({...S,assistantAutomations:Jn(S.assistantAutomations,b.payload.automation)})),i({title:s("shell.butlerControlTimerCancelSucceeded"),tone:"success"})}catch(b){i({title:s("shell.butlerControlTimerCancelFailed"),description:b instanceof Error?b.message:void 0,tone:"error"})}finally{Q(null)}}async function Dt(o){const b=o.content.trim();if(!b){i({title:s("shell.butlerControlTimerExecuteNowFailed"),tone:"error"});return}ut(o.id);try{const S=await Rn(o.id);F(C=>({...C,controlTimers:ul(C.controlTimers,S.timer)})),await L.sendMessage(b),c(),i({title:s("shell.butlerControlTimerExecuteNowSucceeded"),tone:"success"})}catch(S){i({title:s("shell.butlerControlTimerExecuteNowFailed"),description:S instanceof Error?S.message:void 0,tone:"error"})}finally{ut(null)}}async function He(o){if(o.kind==="timer"){await _n(o.timer.id);return}await nn(o.automation.id)}async function sn(o){if(o.kind==="timer"){await Dt(o.timer);return}if(o.automation.triggerType!=="once")return;const b=o.automation.actionConfig.content.trim();if(!b){i({title:s("shell.butlerControlTimerExecuteNowFailed"),tone:"error"});return}ut(o.automation.id);try{await kn(o.automation.id),F(S=>({...S,assistantAutomations:Jn(S.assistantAutomations,{...o.automation,status:"cancelled",nextRunAt:null,cancelledAt:new Date().toISOString(),updatedAt:new Date().toISOString()})})),await L.sendMessage(b),c(),i({title:s("shell.butlerControlTimerExecuteNowSucceeded"),tone:"success"})}catch(S){i({title:s("shell.butlerControlTimerExecuteNowFailed"),description:S instanceof Error?S.message:void 0,tone:"error"})}finally{ut(null)}}function ln(o){const b=xs(o),S=(b?v.get(b):null)||ps(o)||e;!b||!S||($(null),l(Cn(S,b)))}return f?t.jsxs("main",{ref:bt,className:"mobile-feature-page mobile-page-fixed-root mobile-butler-page mobile-butler-page-shell","data-mobile-butler-drawer":K??"none",children:[t.jsx(pr,{currentWorkspace:f,workspaces:r.map(o=>o.workspace),heading:s("shell.mobileButlerEntry"),triggerLabel:f.name,onSelectWorkspace:o=>{d(o),l(is(o,P))},trailing:t.jsxs("div",{className:"mobile-butler-header-trailing","data-mobile-butler-gesture":"ignore",children:[t.jsxs("div",{className:"mobile-butler-hero-top mobile-butler-toolbar-identity",children:[t.jsx("div",{className:"mobile-butler-hero-badge",children:"AI"}),t.jsxs("div",{className:"mobile-butler-hero-copy",children:[t.jsx("strong",{children:pt}),t.jsx("span",{children:Sl(ae)})]})]}),t.jsxs("div",{className:"mobile-butler-toolbar-actions",children:[t.jsx("button",{type:"button",className:"mobile-butler-toolbar-button","aria-label":s("shell.butlerHistoryAction"),title:s("shell.butlerHistoryAction"),onClick:()=>$("list"),children:"≡"}),t.jsx("button",{type:"button",className:"mobile-butler-toolbar-button","aria-label":s("shell.butlerSidebarTabsLabel"),title:s("shell.butlerSidebarTabsLabel"),onClick:()=>$("sidebar"),children:"ⓘ"})]})]})}),t.jsxs("div",{className:"mobile-butler-stage-shell",children:[K?t.jsx("button",{type:"button",className:"mobile-butler-drawer-scrim","aria-label":s("common.close"),onClick:()=>$(null)}):null,t.jsxs("aside",{className:"mobile-butler-drawer mobile-butler-drawer-list",style:{width:`min(88vw, ${rl}px)`},onTouchStart:ce,onTouchEnd:we,children:[t.jsxs("div",{className:"mobile-butler-drawer-header",children:[t.jsxs("div",{children:[t.jsx("h2",{children:s("shell.butlerHistoryTitle")}),t.jsx("p",{children:s("shell.butlerHistoryDescription")})]}),t.jsx("button",{type:"button",className:"mobile-butler-toolbar-button","aria-label":s("shell.butlerNewSessionAction"),onClick:()=>{D()},children:"+"})]}),t.jsx("div",{className:"mobile-butler-list-body",children:t.jsx(no,{activeControlSessionId:(I==null?void 0:I.id)??null,deletingSessionId:pe,sessions:y.controlSessions,onSelectSession:o=>{te(o)},onDeleteSession:o=>{dt(o)}})})]}),t.jsx("div",{className:"mobile-butler-main-stage",onTouchStart:j,onTouchEnd:Ae,children:Pt?t.jsx("section",{className:"mobile-butler-loading-shell",children:t.jsx(Ul,{})}):gt?t.jsxs("section",{className:"mobile-butler-empty-panel",children:[t.jsx("h2",{children:s("shell.mobileButlerEmptyTitle")}),t.jsx("p",{children:s("shell.mobileButlerEmptyBody")})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mobile-butler-chat-body",children:[t.jsx(Ml,{requests:We,replyingRequestId:zt,onReply:async(o,b)=>{he(o);try{await L.replyPermissionRequest(o,b)}catch(S){i({title:s("conversation.permissionRequestReplyFailed"),description:S instanceof Error?S.message:void 0,tone:"error"})}finally{he(null)}}}),Mt?t.jsxs("section",{className:"mobile-butler-empty-panel",children:[t.jsx("h2",{children:s("shell.butlerConversationTitle")}),t.jsx("p",{children:s("shell.butlerProjectSyncEmptyState")})]}):t.jsx("div",{className:"conversation-timeline-shell mobile-butler-timeline-shell",children:t.jsx(Fl,{sessionId:(cn=I==null?void 0:I.session)==null?void 0:cn.sessionId,messages:Nt,historyState:Mn,loadingOlderMessages:mt,hasOlderMessages:Fn,provider:ae,onLoadOlderMessages:()=>{L.loadOlderMessages()},onRetryMessage:o=>{L.retryMessage(o)}})})]}),ee?t.jsx(Ga,{schedule:ee,currentWorkspaceId:e,currentWorkspaceName:(f==null?void 0:f.name)??null,projectNameById:Kt,workspaceNameById:h,sessionTitleById:x,sessionWorkspaceIdById:v,countdownNow:ct,cancelling:ee.kind==="timer"?ot===ee.timer.id:Le===ee.automation.id,executingNow:qt===go(ee),onCancel:()=>{He(ee)},onExecuteNow:()=>{sn(ee)},onOpenSession:()=>{ln(ee)}}):null,Ft?t.jsx("div",{className:"mobile-butler-chat-composer","data-mobile-butler-gesture":"ignore",children:t.jsx(Dl,{capabilities:It,draftStorageId:`mobile-butler:${e}:${ae}`,panelRef:vs,portalContainer:On,placeholder:s("shell.butlerComposerPlaceholder",{displayName:pt}),hasActiveRun:Hn,canInterrupt:Bn,contextUsage:Dn,isSubmitting:ze,isRunning:Qt,onInterrupt:async()=>{await L.interrupt(),c()},onSend:async(o,b)=>{await en(o,b)}})}):null]})}),t.jsx("aside",{className:"mobile-butler-drawer mobile-butler-drawer-sidebar",style:{width:`min(88vw, ${rl}px)`},onTouchStart:X,onTouchEnd:k,children:t.jsxs("div",{className:"mobile-butler-sidebar-shell",children:[t.jsx("div",{className:"mobile-butler-segmented-shell","data-mobile-butler-gesture":"ignore",children:t.jsx("div",{className:"mobile-butler-segmented-control",role:"tablist","aria-label":s("shell.butlerSidebarTabsLabel"),children:In.map(o=>{const b=P===o,S=o==="info"?s("shell.butlerSidebarInfoTab"):o==="automation"?s("shell.butlerSidebarAutomationTab"):s("shell.butlerSidebarSettingsTab");return t.jsx("button",{type:"button",role:"tab",className:"mobile-butler-segmented-button","aria-selected":b,onClick:()=>{Xe(o)},children:S},o)})})}),t.jsx("div",{className:"mobile-page-top-body mobile-butler-body mobile-butler-sidebar-body",children:Jt})]})})]}),t.jsx(hr,{open:J!==null,title:s("shell.deleteSessionConfirmTitle"),description:s("shell.deleteSessionConfirmDescription"),height:"auto",onClose:()=>{pe||dt(null)},footer:t.jsxs("div",{className:"workbench-modal-actions",children:[t.jsx("button",{type:"button",className:"secondary-button",disabled:!!pe,onClick:()=>dt(null),children:s("common.cancel")}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!pe,onClick:()=>{$n()},children:pe?s("common.loading"):s("shell.deleteSessionAction")})]}),children:t.jsx("p",{className:"mobile-butler-empty-text",children:J?za(J):""})})]}):t.jsx("main",{className:"mobile-feature-page mobile-page-scroll-root",children:t.jsxs("article",{className:"mobile-feature-empty surface-card",children:[t.jsx("h1",{children:s("shell.workspaceDetailMissingTitle")}),t.jsx("p",{children:s("shell.workspaceDetailMissingBody")})]})})}function Ga(e){const n=u.useId(),l=u.useId(),i=u.useRef(null),r=u.useRef(null),[c,d]=u.useState(!1),f=xo(e.schedule,e.countdownNow),h=vo(e.schedule,e.countdownNow),x=co(e.schedule,e.projectNameById,e.workspaceNameById,e.currentWorkspaceId,e.currentWorkspaceName),v=ho(e.schedule,e.sessionTitleById),A=So(e.schedule),H=xs(e.schedule),P=!!(H&&(e.sessionWorkspaceIdById.has(H)||ps(e.schedule))),T=po(e.schedule);return u.useEffect(()=>{if(!c)return;const B=W=>{var Z,K;(Z=i.current)!=null&&Z.contains(W.target)||(K=r.current)!=null&&K.contains(W.target)||d(!1)},z=W=>{W.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",B),document.addEventListener("keydown",z),()=>{document.removeEventListener("pointerdown",B),document.removeEventListener("keydown",z)}},[c]),t.jsxs("section",{className:"mobile-feature-panel surface-card mobile-butler-timer-banner","aria-live":"polite",children:[t.jsxs("div",{className:"mobile-butler-timer-status",children:[t.jsx("span",{className:"mobile-butler-timer-pulse","aria-hidden":"true"}),t.jsx("span",{className:"mobile-butler-timer-caption",children:s("shell.butlerControlTimerBannerTitle")})]}),t.jsxs("div",{className:"mobile-butler-timer-display-panel",children:[t.jsx("p",{className:"mobile-butler-timer-display-clock",children:h}),t.jsx("p",{className:"mobile-butler-timer-countdown",children:f})]}),t.jsxs("div",{className:"mobile-butler-timer-meta",children:[t.jsxs("div",{className:"mobile-butler-timer-meta-card",children:[t.jsx("span",{children:s("shell.butlerControlTimerWorkspaceLabel")}),t.jsx("strong",{title:x,children:x})]}),t.jsxs("div",{className:"mobile-butler-timer-meta-card",children:[t.jsx("span",{children:s("shell.butlerControlTimerSessionLabel")}),P?t.jsx("button",{type:"button",className:"mobile-butler-timer-session-link",title:v,"aria-label":`${s("shell.butlerControlTimerSessionLabel")}:${v}`,style:{padding:0,border:"none",background:"transparent",color:"inherit",font:"inherit",fontWeight:600,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",cursor:"pointer",textDecoration:"underline"},onClick:e.onOpenSession,children:v}):t.jsx("strong",{title:v,children:v})]})]}),t.jsxs("div",{className:"mobile-butler-timer-actions",children:[t.jsxs("div",{className:"mobile-butler-timer-detail",ref:i,children:[t.jsx("button",{id:n,type:"button",className:"mobile-butler-timer-detail-button","aria-label":s("shell.butlerControlTimerDetailAction"),"aria-haspopup":"dialog","aria-expanded":c,"aria-controls":c?l:void 0,title:s("shell.butlerControlTimerDetailAction"),onClick:()=>{d(B=>!B)},children:t.jsx("span",{className:"mobile-butler-timer-detail-icon","aria-hidden":"true",children:t.jsx(bo,{})})}),t.jsx(cs,{open:c,id:l,className:"mobile-butler-timer-detail-popover",anchorRef:i,popoverRef:r,labelledBy:n,maxWidth:288,gap:8,viewportPadding:12,children:t.jsxs("div",{children:[t.jsx("strong",{children:s("shell.butlerControlTimerPromptTitle")}),t.jsx("p",{children:A})]})})]}),T?t.jsx("button",{type:"button",className:"secondary-button mobile-butler-timer-action",disabled:e.cancelling||e.executingNow,onClick:e.onExecuteNow,children:e.executingNow?s("shell.butlerControlTimerExecutingNow"):s("shell.butlerControlTimerExecuteNowAction")}):null,t.jsx("button",{type:"button",className:"secondary-button mobile-butler-timer-action",disabled:e.cancelling||e.executingNow,onClick:e.onCancel,children:e.cancelling?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerStopAction")})]}),T?t.jsx("p",{className:"mobile-butler-timer-note",children:s("shell.butlerControlTimerActionNote")}):null]})}function ke({label:e,value:n}){return t.jsxs("div",{className:"mobile-butler-info-metric",children:[t.jsx("span",{children:e}),t.jsx("strong",{title:n,children:n})]})}function Za(e){return t.jsxs("section",{className:"mobile-feature-panel surface-card mobile-butler-record-section",children:[t.jsxs("div",{className:"mobile-feature-section-header",children:[t.jsxs("div",{children:[t.jsx("h2",{children:s("shell.butlerAutomationTasksTitle")}),t.jsx("p",{children:s("shell.butlerAutomationMobileOverviewDescription")})]}),t.jsxs("div",{className:"mobile-feature-section-actions",children:[e.actionLabel&&e.onAction?t.jsx("button",{type:"button",className:"mobile-butler-section-action",onClick:e.onAction,children:e.actionLabel}):null,t.jsx("span",{className:"mobile-feature-counter",children:e.items.length})]})]}),e.items.length>0?t.jsx("div",{className:"mobile-butler-automation-grid",children:e.items.map(n=>t.jsxs("article",{className:"mobile-butler-automation-card","data-selected":e.selectedAutomationId===n.automationId,children:[t.jsxs("header",{className:"mobile-butler-record-header",children:[t.jsxs("div",{className:"mobile-butler-record-copy",children:[t.jsx("strong",{children:n.title}),t.jsx("span",{children:n.projectName})]}),t.jsx("span",{className:"mobile-butler-record-badge",children:n.statusLabel})]}),t.jsxs("div",{className:"mobile-butler-automation-chip-row",children:[t.jsx("span",{className:"mobile-butler-automation-chip",children:n.taskTypeLabel}),n.targetSessionTitle?t.jsx("span",{className:"mobile-butler-automation-chip",children:n.targetSessionTitle}):null]}),t.jsxs("div",{className:"mobile-butler-automation-metric-grid",children:[t.jsxs("div",{className:"mobile-butler-automation-metric",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskNextRunLabel")}),t.jsx("strong",{children:G(n.nextRunAt)})]}),t.jsxs("div",{className:"mobile-butler-automation-metric",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskLastRunLabel")}),t.jsx("strong",{children:G(n.lastRunAt)})]})]}),t.jsx("p",{className:"mobile-butler-automation-summary",children:n.promptPreview}),n.lastResultSummary?t.jsx("p",{className:"mobile-butler-automation-footnote",children:n.lastResultSummary}):null,t.jsxs("footer",{className:"mobile-butler-record-footer",children:[t.jsx("button",{type:"button",className:"secondary-button mobile-butler-record-action",onClick:()=>{n.automationId&&e.onSelectAutomation(n.automationId)},children:e.selectedAutomationId===n.automationId?s("shell.butlerAutomationCollapseDetailsAction"):s("shell.butlerAutomationOpenDetailsAction")}),n.automationId&&n.status==="active"?t.jsx("button",{type:"button",className:"secondary-button mobile-butler-record-action",disabled:e.cancellingAutomationId===n.automationId,onClick:()=>{e.onCancelAutomation(n.automationId)},children:e.cancellingAutomationId===n.automationId?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerStopAction")}):null]})]},n.id))}):t.jsx("p",{className:"mobile-butler-empty-text",children:e.emptyText})]})}function Qa(e){var i,r,c;const n=(i=e.automation.projectId)!=null&&i.trim()?e.workspaceNameById.get(((c=(r=e.automation.controlSession)==null?void 0:r.session)==null?void 0:c.workspaceId)??""):null,l=bi(e.automation,e.sessionTitleById);return t.jsxs("section",{className:"mobile-feature-panel surface-card mobile-butler-record-section mobile-butler-automation-detail-panel",children:[t.jsxs("div",{className:"mobile-feature-section-header",children:[t.jsxs("div",{children:[t.jsx("h2",{children:s("shell.butlerAutomationDetailTitle")}),t.jsx("p",{children:s("shell.butlerAutomationDetailDescription")})]}),t.jsx("button",{type:"button",className:"mobile-butler-section-action",onClick:e.onClose,children:s("common.close")})]}),t.jsxs("div",{className:"mobile-butler-automation-detail-summary",children:[t.jsx(ke,{label:s("shell.butlerAutomationTaskTypeLabel"),value:oi(e.automation.triggerType)}),t.jsx(ke,{label:s("shell.butlerAutomationStatusLabel"),value:ci(e.automation.status)}),t.jsx(ke,{label:s("shell.butlerAutomationTaskNextRunLabel"),value:G(e.automation.nextRunAt)}),t.jsx(ke,{label:s("shell.butlerAutomationTaskLastRunLabel"),value:G(e.automation.lastRunAt||e.automation.updatedAt)}),n?t.jsx(ke,{label:s("shell.mobileButlerAssistantWorkspaceLabel"),value:n}):null,l?t.jsx(ke,{label:s("shell.butlerAutomationTargetSessionLabel"),value:l}):null]}),t.jsxs("div",{className:"mobile-butler-automation-form-grid",children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationTitleLabel")}),t.jsx("input",{className:"butler-form-control",value:e.editorState.title,disabled:e.saving,onChange:d=>{e.onEditorChange({title:d.target.value})}})]}),t.jsxs("label",{className:"butler-form-field butler-form-field-wide",children:[t.jsx("span",{children:s("shell.butlerAutomationPromptLabel")}),t.jsx("textarea",{className:"butler-form-control mobile-butler-automation-textarea",value:e.editorState.content,disabled:e.saving,onChange:d=>{e.onEditorChange({content:d.target.value})}})]}),t.jsxs("label",{className:"mobile-butler-automation-toggle",children:[t.jsx("input",{type:"checkbox",checked:e.editorState.includeTriggerContext,disabled:e.saving,onChange:d=>{e.onEditorChange({includeTriggerContext:d.target.checked})}}),t.jsx("span",{children:s("shell.butlerAutomationIncludeTriggerContextLabel")})]}),t.jsx(Ja,{automation:e.automation,editorState:e.editorState,saving:e.saving,onEditorChange:e.onEditorChange})]}),e.recentRuns.length>0?t.jsxs("div",{className:"mobile-butler-automation-detail-runs",children:[t.jsxs("div",{className:"mobile-feature-section-header",children:[t.jsx("div",{children:t.jsx("h2",{children:s("shell.butlerAutomationRunsTitle")})}),t.jsx("span",{className:"mobile-feature-counter",children:e.recentRuns.length})]}),t.jsx("div",{className:"mobile-butler-record-list",children:e.recentRuns.map(d=>{var f,h;return t.jsxs("article",{className:"mobile-butler-record-card",children:[t.jsxs("header",{className:"mobile-butler-record-header",children:[t.jsxs("div",{className:"mobile-butler-record-copy",children:[t.jsx("strong",{children:s("shell.butlerAutomationRoundLabel",{round:d.runSeq})}),t.jsx("span",{children:ui(d.triggerType)})]}),t.jsx("span",{className:"mobile-butler-record-badge",children:di(d.status)})]}),t.jsx("p",{children:((f=d.summary)==null?void 0:f.trim())||((h=d.error)==null?void 0:h.trim())||s("shell.butlerAutomationRunEmptySummary")}),t.jsx("footer",{className:"mobile-butler-record-footer",children:t.jsx("span",{children:G(d.createdAt)})})]},d.id)})})]}):null,t.jsxs("footer",{className:"mobile-butler-automation-detail-actions",children:[t.jsx("button",{type:"button",className:"secondary-button",disabled:e.saving,onClick:e.onClose,children:s("common.close")}),t.jsx("button",{type:"button",className:"primary-button",disabled:e.saving,onClick:e.onSave,children:e.saving?s("shell.butlerAutomationSaving"):s("shell.butlerAutomationSaveAction")})]})]})}function Ja(e){const{triggerConfig:n}=e.automation;return n.type==="once"?t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationDueAtLabel")}),t.jsx("input",{type:"datetime-local",className:"butler-form-control",value:e.editorState.dueAt,disabled:e.saving,onChange:l=>{e.onEditorChange({dueAt:l.target.value})}})]}):n.type==="interval"?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationEverySecondsLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.everySeconds,disabled:e.saving,onChange:l=>{e.onEditorChange({everySeconds:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationEveryMinutesLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.everyMinutes,disabled:e.saving,onChange:l=>{e.onEditorChange({everyMinutes:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationEveryHoursLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.everyHours,disabled:e.saving,onChange:l=>{e.onEditorChange({everyHours:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationStopAtLabel")}),t.jsx("input",{type:"datetime-local",className:"butler-form-control",value:e.editorState.stopAt,disabled:e.saving,onChange:l=>{e.onEditorChange({stopAt:l.target.value})}})]})]}):n.type==="cron"?t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationCronMinuteLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.cronMinute,disabled:e.saving,onChange:l=>{e.onEditorChange({cronMinute:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationCronHourLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.cronHour,disabled:e.saving,onChange:l=>{e.onEditorChange({cronHour:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field butler-form-field-wide",children:[t.jsx("span",{children:s("shell.butlerAutomationCronDaysOfWeekLabel")}),t.jsx("input",{className:"butler-form-control",value:e.editorState.cronDaysOfWeek,disabled:e.saving,onChange:l=>{e.onEditorChange({cronDaysOfWeek:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationStopAtLabel")}),t.jsx("input",{type:"datetime-local",className:"butler-form-control",value:e.editorState.stopAt,disabled:e.saving,onChange:l=>{e.onEditorChange({stopAt:l.target.value})}})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationPollIntervalLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.pollIntervalSeconds,disabled:e.saving,onChange:l=>{e.onEditorChange({pollIntervalSeconds:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationMaxChecksLabel")}),t.jsx("input",{inputMode:"numeric",className:"butler-form-control",value:e.editorState.maxChecks,disabled:e.saving,onChange:l=>{e.onEditorChange({maxChecks:l.target.value})}})]}),t.jsxs("label",{className:"butler-form-field",children:[t.jsx("span",{children:s("shell.butlerAutomationExpiresAtLabel")}),t.jsx("input",{type:"datetime-local",className:"butler-form-control",value:e.editorState.expiresAt,disabled:e.saving,onChange:l=>{e.onEditorChange({expiresAt:l.target.value})}})]})]})}function Ht(e){return t.jsxs("section",{className:"mobile-feature-panel surface-card mobile-butler-record-section",children:[t.jsxs("div",{className:"mobile-feature-section-header",children:[t.jsx("div",{children:t.jsx("h2",{children:e.title})}),t.jsxs("div",{className:"mobile-feature-section-actions",children:[e.actionLabel&&e.onAction?t.jsx("button",{type:"button",className:"mobile-butler-section-action",onClick:e.onAction,children:e.actionLabel}):null,t.jsx("span",{className:"mobile-feature-counter",children:e.items.length})]})]}),e.items.length>0?t.jsx("div",{className:"mobile-butler-record-list",children:e.items.map(n=>t.jsxs("article",{className:"mobile-butler-record-card",children:[t.jsxs("header",{className:"mobile-butler-record-header",children:[t.jsxs("div",{className:"mobile-butler-record-copy",children:[t.jsx("strong",{children:n.title}),n.subtitle?t.jsx("span",{children:n.subtitle}):null]}),n.status?t.jsx("span",{className:"mobile-butler-record-badge",children:n.status}):null]}),t.jsx("p",{children:n.content}),n.meta||n.actionLabel?t.jsxs("footer",{className:"mobile-butler-record-footer",children:[n.meta?t.jsx("span",{children:n.meta}):t.jsx("span",{}),n.actionLabel&&n.onAction?t.jsx("button",{type:"button",className:"secondary-button mobile-butler-record-action",disabled:n.actionDisabled,onClick:n.onAction,children:n.actionLabel}):null]}):null]},n.id))}):t.jsx("p",{className:"mobile-butler-empty-text",children:e.emptyText})]})}function eo(e){return t.jsxs("section",{className:"mobile-feature-panel surface-card mobile-butler-record-section mobile-butler-record-section-compact",children:[t.jsxs("div",{className:"mobile-feature-section-header",children:[t.jsx("div",{children:t.jsx("h2",{children:e.title})}),e.actionLabel&&e.onAction?t.jsx("button",{type:"button",className:"mobile-butler-section-action",onClick:e.onAction,children:e.actionLabel}):null]}),e.items.length>0?t.jsx("div",{className:"mobile-butler-record-list mobile-butler-record-list-compact",children:e.items.map(n=>t.jsxs("article",{className:"mobile-butler-compact-record",children:[t.jsx("span",{children:n.title}),t.jsx("strong",{children:n.content})]},n.id))}):t.jsx("p",{className:"mobile-butler-empty-text",children:e.emptyText})]})}function al(e){return t.jsxs("section",{className:"mobile-feature-panel surface-card mobile-butler-record-section",children:[t.jsxs("div",{className:"mobile-feature-section-header",children:[t.jsxs("div",{children:[t.jsx("h2",{children:e.title}),t.jsx("p",{children:e.description})]}),t.jsx("button",{type:"button",className:"mobile-butler-section-action",onClick:e.onClose,children:s("common.close")})]}),e.items.length>0?t.jsx("div",{className:"mobile-butler-record-list",children:e.items.map(n=>t.jsxs("article",{className:"mobile-butler-record-card",children:[t.jsxs("header",{className:"mobile-butler-record-header",children:[t.jsxs("div",{className:"mobile-butler-record-copy",children:[t.jsx("strong",{children:n.title}),n.subtitle?t.jsx("span",{children:n.subtitle}):null]}),n.status?t.jsx("span",{className:"mobile-butler-record-badge",children:n.status}):null]}),t.jsx("p",{children:n.content}),n.meta||n.actionLabel?t.jsxs("footer",{className:"mobile-butler-record-footer",children:[n.meta?t.jsx("span",{children:n.meta}):t.jsx("span",{}),n.actionLabel&&n.onAction?t.jsx("button",{type:"button",className:"secondary-button mobile-butler-record-action",disabled:n.actionDisabled,onClick:n.onAction,children:n.actionLabel}):null]}):null]},n.id))}):t.jsx("p",{className:"mobile-butler-empty-text",children:e.emptyText})]})}function to(e){return t.jsxs("div",{className:"mobile-butler-history-stack",children:[t.jsxs("section",{className:"mobile-feature-panel surface-card mobile-butler-record-section",children:[t.jsxs("div",{className:"mobile-feature-section-header",children:[t.jsxs("div",{children:[t.jsx("h2",{children:s("shell.butlerAutomationHistoryTitle")}),t.jsx("p",{children:s("shell.butlerAutomationHistoryDescription")})]}),t.jsx("button",{type:"button",className:"mobile-butler-section-action",onClick:e.onClose,children:s("common.close")})]}),e.taskItems.length===0&&e.runItems.length===0?t.jsx("p",{className:"mobile-butler-empty-text",children:s("shell.butlerAutomationHistoryEmpty")}):null]}),e.taskItems.length>0?t.jsx(Ht,{title:s("shell.butlerAutomationTasksTitle"),emptyText:s("shell.butlerAutomationHistoryEmpty"),items:e.taskItems.map(n=>({id:n.id,title:n.title,subtitle:n.projectName,status:n.statusLabel,content:`${s("shell.butlerAutomationTaskTypeLabel")} · ${n.taskTypeLabel}`,meta:`${s("shell.butlerAutomationTaskLastRunLabel")} · ${G(n.lastRunAt)}`}))}):null,e.runItems.length>0?t.jsx(Ht,{title:s("shell.butlerAutomationRunsTitle"),emptyText:s("shell.butlerAutomationHistoryEmpty"),items:e.runItems.map(n=>({id:n.id,title:n.title,subtitle:n.projectName,status:n.statusLabel,content:`${n.sourceLabel} · ${n.summary}`,meta:G(n.createdAt)}))}):null]})}function no(e){return e.sessions.length===0?t.jsx("p",{className:"mobile-butler-empty-text",children:s("shell.butlerHistoryEmpty")}):t.jsx("div",{className:"mobile-butler-record-list",children:e.sessions.map(n=>{var r,c,d,f,h;const l=n.id===e.activeControlSessionId,i=((r=n.title)==null?void 0:r.trim())||((c=n.session.title)==null?void 0:c.trim())||((d=n.lastSummary)==null?void 0:d.trim())||n.sessionId;return t.jsxs("article",{className:"mobile-butler-record-card mobile-butler-history-card","data-active":l,children:[t.jsxs("header",{className:"mobile-butler-record-header",children:[t.jsxs("div",{className:"mobile-butler-record-copy",children:[t.jsx("strong",{children:i}),t.jsx("span",{children:G(n.updatedAt)})]}),l?t.jsx("span",{className:"mobile-butler-record-badge",children:s("shell.butlerCurrentSessionBadge")}):null]}),t.jsx("p",{children:((f=n.lastSummary)==null?void 0:f.trim())||((h=n.session.title)==null?void 0:h.trim())||n.sessionId}),t.jsxs("footer",{className:"mobile-butler-record-footer",children:[t.jsx("button",{type:"button",className:"secondary-button mobile-butler-record-action",onClick:()=>{e.onSelectSession(n.id)},children:l?s("shell.butlerCurrentSessionBadge"):s("shell.butlerHistoryOpenAction")}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button mobile-butler-record-action",disabled:e.deletingSessionId===n.id,"aria-label":s("shell.butlerHistoryDeleteAction"),onClick:()=>{e.onDeleteSession(n)},children:e.deletingSessionId===n.id?s("common.loading"):s("shell.deleteSessionAction")})]})]},n.id)})})}function so(e,n,l,i){u.useEffect(()=>{const r=e.current;if(!l||!r){r&&r.style.removeProperty("--mobile-conversation-composer-height");return}if(!n){r.style.removeProperty("--mobile-conversation-composer-height");return}const c=r,d=n;function f(){!e.current||!d.isConnected||c.style.setProperty("--mobile-conversation-composer-height",`${d.offsetHeight}px`)}f();const h=typeof ResizeObserver<"u"?new ResizeObserver(f):null;return h==null||h.observe(d),window.addEventListener("resize",f),()=>{h==null||h.disconnect(),window.removeEventListener("resize",f),r.style.removeProperty("--mobile-conversation-composer-height")}},[n,l,i,e])}function ol(e,n){return[...e].filter(l=>n==="history"?!dl(l.status):dl(l.status)).sort((l,i)=>M(es(i))-M(es(l))).slice(0,4).map(l=>{var i,r;return{id:l.id,title:((i=l.targetRef)==null?void 0:i.trim())||l.verificationType,subtitle:l.verificationType,status:ro(l.status),content:((r=l.summary)==null?void 0:r.trim())||s("shell.butlerInfoVerificationFallback",{status:l.status}),meta:G(es(l)),verification:{id:l.id,projectId:l.projectId,status:l.status}}})}function lo(e){return e.map(n=>({title:n.title,content:`${n.projectName} · ${fo(n.status)}`}))}function ul(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(hl(r))-M(hl(i)))}function Jn(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(xl(r))-M(xl(i)))}function io(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(Ce(r))-M(Ce(i)))}function cl(e){return e==="active"||e==="waiting_user"}function yn(e){return e==="active"||e==="waiting_user"}function dl(e){return e==="queued"||e==="running"}function ml(e){return e==="queued"||e==="running"}function ro(e){switch(e){case"queued":case"running":return s("shell.butlerAutomationStatusActive");case"passed":case"skipped":return s("shell.butlerAutomationStatusCompleted");case"failed":return s("shell.butlerAutomationStatusFailed");case"cancelled":return s("shell.butlerAutomationStatusCancelled");default:return e}}function hl(e){return e.dueAt||e.triggeredAt||e.cancelledAt||e.updatedAt||e.createdAt}function ao(e){var n,l,i,r,c,d;return((n=e.title)==null?void 0:n.trim())||((i=(l=e.controlSession)==null?void 0:l.title)==null?void 0:i.trim())||((d=(c=(r=e.controlSession)==null?void 0:r.session)==null?void 0:c.title)==null?void 0:d.trim())||e.content.trim()}function oo(e){return e.content.trim()||ao(e)}function uo(e,n,l,i,r){var f,h,x,v;const c=(f=e.projectId)==null?void 0:f.trim();if(c&&n.has(c))return n.get(c);const d=((v=(x=(h=e.controlSession)==null?void 0:h.session)==null?void 0:x.workspaceId)==null?void 0:v.trim())||i.trim();return d?l.has(d)?l.get(d):d===i.trim()&&(r!=null&&r.trim())?r.trim():s("shell.butlerControlTimerUnknownWorkspace"):s("shell.butlerControlTimerUnknownWorkspace")}function co(e,n,l,i,r){var f;if(e.kind==="timer")return uo(e.timer,n,l,i,r);const c=(f=e.automation.projectId)==null?void 0:f.trim();if(c&&n.has(c))return n.get(c);const d=ps(e)||i.trim();return d?l.has(d)?l.get(d):d===i.trim()&&(r!=null&&r.trim())?r.trim():s("shell.butlerControlTimerUnknownWorkspace"):s("shell.butlerControlTimerUnknownWorkspace")}function mo(e,n){var r,c,d,f,h,x,v;const l=(r=e.targetSessionId)==null?void 0:r.trim();if(l&&n.has(l))return n.get(l);if((f=(d=(c=e.controlSession)==null?void 0:c.session)==null?void 0:d.title)!=null&&f.trim())return e.controlSession.session.title.trim();const i=((v=(x=(h=e.controlSession)==null?void 0:h.session)==null?void 0:x.sessionId)==null?void 0:v.trim())||e.sessionId.trim();return i&&n.has(i)?n.get(i):s("shell.butlerControlTimerUnknownSession")}function ho(e,n){var i,r,c;if(e.kind==="timer")return mo(e.timer,n);const l=xs(e);return l&&n.has(l)?n.get(l):(c=(r=(i=e.automation.controlSession)==null?void 0:i.session)==null?void 0:r.title)!=null&&c.trim()?e.automation.controlSession.session.title.trim():s("shell.butlerControlTimerUnknownSession")}function bo(){return t.jsx("svg",{viewBox:"0 0 16 16",fill:"none","aria-hidden":"true",focusable:"false",children:t.jsx("path",{fill:"currentColor",d:"M8 1.25a6.75 6.75 0 1 0 0 13.5A6.75 6.75 0 0 0 8 1.25Zm0 1.5a5.25 5.25 0 1 1 0 10.5A5.25 5.25 0 0 1 8 2.75Zm0 2.5a.875.875 0 1 0 0 1.75a.875.875 0 0 0 0-1.75Zm-.875 3.125a.625.625 0 1 0 0 1.25h.25v1.75h-.25a.625.625 0 1 0 0 1.25h1.75a.625.625 0 1 0 0-1.25h-.25V9a.625.625 0 0 0-.625-.625h-.875Z"})})}function bl(e,n,l,i="active"){const r=new Map(((n==null?void 0:n.projects)??[]).filter(d=>l.has(d.id)).map(d=>[d.id,d.name]));return e.filter(d=>fi(d,l,n)).filter(d=>i==="history"?d.status!=="active":d.status==="active").map(d=>{var f,h;return{id:`assistant-automation:${d.id}`,automationId:d.id,kind:"assistant_automation",title:mi(d),projectName:hi(d,r),status:Ao(d.status),taskTypeLabel:oi(d.triggerType),statusLabel:ci(d.status),nextRunAt:d.nextRunAt,lastRunAt:d.lastRunAt||d.updatedAt,promptPreview:jo(d.actionConfig.content),lastResultSummary:((f=d.lastRunSummary)==null?void 0:f.trim())||((h=d.lastError)==null?void 0:h.trim())||null,targetSessionTitle:bi(d)}}).sort((d,f)=>{const h=M(d.nextRunAt),x=M(f.nextRunAt);return h!==x?h===0?1:x===0?-1:h-x:M(f.lastRunAt)-M(d.lastRunAt)}).slice(0,8)}function fl(e,n,l,i,r="active"){const c=new Map(((l==null?void 0:l.projects)??[]).filter(h=>i.has(h.id)).map(h=>[h.id,h.name])),d=new Map(e.filter(h=>fi(h,i,l)).map(h=>[h.id,h]));return n.map(h=>({run:h,automation:d.get(h.automationId),normalizedStatus:yo(h.status)})).filter(({automation:h})=>!!h).filter(({normalizedStatus:h})=>r==="history"?!vl(h):vl(h)).map(({run:h,automation:x,normalizedStatus:v})=>{var A,H;return{id:`assistant-automation-run:${h.id}`,kind:"assistant_automation_run",title:mi(x),projectName:hi(x,c),status:v,sourceLabel:ui(h.triggerType),statusLabel:di(h.status),summary:((A=h.summary)==null?void 0:A.trim())||((H=h.error)==null?void 0:H.trim())||s("shell.butlerAutomationRunEmptySummary"),createdAt:h.finishedAt||h.startedAt||h.createdAt}}).sort((h,x)=>M(x.createdAt)-M(h.createdAt)).slice(0,10)}function fo(e){switch(e){case"pending":return s("shell.butlerInfoTodoPending");case"in_progress":return s("shell.butlerInfoTodoInProgress");case"closed":return s("shell.butlerInfoTodoClosed");default:return s("shell.butlerInfoTodoPending")}}function Ce(e){return e.updatedAt||e.lastAutomationAt||e.lastCheckedAt||e.createdAt}function go(e){return e.kind==="timer"?e.timer.id:e.automation.id}function Pn(e){return e.kind==="timer"?e.timer.dueAt:e.automation.nextRunAt}function ps(e){var n,l,i,r,c,d;return e.kind==="timer"?((i=(l=(n=e.timer.controlSession)==null?void 0:n.session)==null?void 0:l.workspaceId)==null?void 0:i.trim())||null:((d=(c=(r=e.automation.controlSession)==null?void 0:r.session)==null?void 0:c.workspaceId)==null?void 0:d.trim())||null}function xs(e){var n,l,i,r,c,d,f,h,x,v,A;return e.kind==="timer"?((n=e.timer.targetSessionId)==null?void 0:n.trim())||((r=(i=(l=e.timer.controlSession)==null?void 0:l.session)==null?void 0:i.sessionId)==null?void 0:r.trim())||((c=e.timer.sessionId)==null?void 0:c.trim())||null:((d=e.automation.actionConfig.targetSessionId)==null?void 0:d.trim())||((x=(h=(f=e.automation.controlSession)==null?void 0:f.session)==null?void 0:h.sessionId)==null?void 0:x.trim())||((A=(v=e.automation.controlSession)==null?void 0:v.sessionId)==null?void 0:A.trim())||null}function po(e){return e.kind==="timer"||e.automation.triggerType==="once"}function xo(e,n){const l=M(Pn(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueNow"):s("shell.butlerControlTimerCountdownActive",{duration:Ro(l-n)})}function vo(e,n){const l=M(Pn(e));return!l||l<=n?"00:00":ko(l-n)}function So(e){return e.kind==="timer"?oo(e.timer):e.automation.actionConfig.content.trim()||s("conversation.butlerAnalysisEmpty")}function gl(e){switch(e){case"active":return s("shell.butlerAutomationStatusActive");case"waiting_user":return s("shell.butlerAutomationStatusWaitingUser");case"completed":return s("shell.butlerAutomationStatusCompleted");case"failed":return s("shell.butlerAutomationStatusFailed");case"cancelled":return s("shell.butlerAutomationStatusCancelled");default:return s("shell.butlerAutomationStatusActive")}}function oi(e){switch(e){case"once":return s("shell.butlerAutomationTaskTypeControlTimer");case"interval":return s("shell.butlerAutomationTaskTypeInterval");case"cron":return s("shell.butlerAutomationTaskTypeCron");case"condition":return s("shell.butlerAutomationTaskTypeFollowUp");default:return s("shell.butlerAutomationTaskTypeControlTimer")}}function ui(e){return e==="interval"||e==="cron"?s("shell.butlerAutomationRunSourcePatrol"):e==="once"?s("shell.butlerAutomationRunSourceControlTimer"):s("shell.butlerAutomationRunSourceFollowUp")}function yo(e){switch(e){case"failed":return"failed";case"cancelled":return"cancelled";case"completed":case"passed":case"succeeded":return"completed";case"waiting_user":return"waiting_user";case"active":case"queued":case"running":default:return"active"}}function Ao(e){switch(e){case"failed":return"failed";case"cancelled":return"cancelled";case"completed":return"completed";case"paused":return"waiting_user";case"active":default:return"active"}}function ci(e){switch(e){case"completed":return s("shell.butlerAutomationStatusCompleted");case"failed":return s("shell.butlerAutomationStatusFailed");case"cancelled":return s("shell.butlerAutomationStatusCancelled");case"paused":return s("shell.butlerAutomationStatusWaitingUser");case"active":default:return s("shell.butlerAutomationStatusActive")}}function di(e){switch(e){case"succeeded":return s("shell.butlerAutomationStatusCompleted");case"failed":return s("shell.butlerAutomationStatusFailed");case"cancelled":case"skipped":return s("shell.butlerAutomationStatusCancelled");case"queued":case"running":default:return s("shell.butlerAutomationStatusActive")}}function mi(e){var n,l;return((n=e.title)==null?void 0:n.trim())||((l=e.actionConfig.targetSessionId)==null?void 0:l.trim())||e.actionConfig.content.trim()||e.id}function hi(e,n){var l,i;return e.projectId&&n.has(e.projectId)?n.get(e.projectId):((i=(l=e.controlSession)==null?void 0:l.session)==null?void 0:i.workspaceId)||s("shell.butlerControlTimerNoProject")}function bi(e,n=new Map){var i,r,c,d;const l=(i=e.actionConfig.targetSessionId)==null?void 0:i.trim();return l&&n.has(l)?n.get(l):(d=(c=(r=e.controlSession)==null?void 0:r.session)==null?void 0:c.title)!=null&&d.trim()?e.controlSession.session.title.trim():l||null}function jo(e){const n=e.replace(/\s+/g," ").trim();return n?n.length<=72?n:`${n.slice(0,72)}...`:s("conversation.butlerAnalysisEmpty")}function pl(e){var l;const n={title:((l=e.title)==null?void 0:l.trim())||"",content:e.actionConfig.content,includeTriggerContext:e.actionConfig.includeTriggerContext,dueAt:"",everySeconds:"",everyMinutes:"",everyHours:"",stopAt:"",cronMinute:"",cronHour:"",cronDaysOfWeek:"",pollIntervalSeconds:"",expiresAt:"",maxChecks:""};return e.triggerConfig.type==="once"?n.dueAt=An(e.triggerConfig.dueAt):e.triggerConfig.type==="interval"?(n.everySeconds=lt(e.triggerConfig.seconds),n.everyMinutes=lt(e.triggerConfig.minutes),n.everyHours=lt(e.triggerConfig.hours),n.stopAt=An(e.triggerConfig.stopAt)):e.triggerConfig.type==="cron"?(n.cronMinute=lt(e.triggerConfig.minute),n.cronHour=lt(e.triggerConfig.hour),n.cronDaysOfWeek=(e.triggerConfig.daysOfWeek??[]).join(","),n.stopAt=An(e.triggerConfig.stopAt)):(n.pollIntervalSeconds=lt(e.triggerConfig.pollIntervalSeconds),n.expiresAt=An(e.triggerConfig.expiresAt),n.maxChecks=lt(e.triggerConfig.maxChecks)),n}function Co(e,n){const l={title:wo(n.title),content:n.content.trim(),includeTriggerContext:n.includeTriggerContext};if(!l.content)throw new Error(s("shell.butlerAutomationPromptRequired"));return e.triggerConfig.type==="once"?{...l,dueAt:Io(n.dueAt,s("shell.butlerAutomationDueAtLabel"))}:e.triggerConfig.type==="interval"?{...l,everySeconds:jn(n.everySeconds,s("shell.butlerAutomationEverySecondsLabel")),everyMinutes:jn(n.everyMinutes,s("shell.butlerAutomationEveryMinutesLabel")),everyHours:jn(n.everyHours,s("shell.butlerAutomationEveryHoursLabel")),stopAt:Nn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:e.triggerConfig.type==="cron"?{...l,cronMinute:gi(n.cronMinute,s("shell.butlerAutomationCronMinuteLabel")),cronHour:pi(n.cronHour,s("shell.butlerAutomationCronHourLabel")),cronDaysOfWeek:To(n.cronDaysOfWeek),stopAt:Nn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:{...l,pollIntervalSeconds:No(n.pollIntervalSeconds,s("shell.butlerAutomationPollIntervalLabel")),expiresAt:Nn(n.expiresAt,s("shell.butlerAutomationExpiresAtLabel")),maxChecks:jn(n.maxChecks,s("shell.butlerAutomationMaxChecksLabel"))}}function xl(e){return e.updatedAt||e.lastRunAt||e.nextRunAt||e.createdAt}function fi(e,n,l){var r,c,d;if(e.projectId&&n.has(e.projectId))return!0;const i=(d=(c=(r=e.controlSession)==null?void 0:r.session)==null?void 0:c.workspaceId)==null?void 0:d.trim();return i?((l==null?void 0:l.projects)??[]).some(f=>f.workspaceId===i&&n.has(f.id)):!1}function vl(e){return e==="active"||e==="waiting_user"}function es(e){return e.finishedAt||e.startedAt||e.createdAt}function M(e){if(!e)return 0;const n=new Date(e).getTime();return Number.isNaN(n)?0:n}function lt(e){return typeof e=="number"&&Number.isFinite(e)?String(e):""}function wo(e){const n=e.trim();return n||null}function An(e){if(!e)return"";const n=new Date(e);if(Number.isNaN(n.getTime()))return"";const l=n.getFullYear(),i=String(n.getMonth()+1).padStart(2,"0"),r=String(n.getDate()).padStart(2,"0"),c=String(n.getHours()).padStart(2,"0"),d=String(n.getMinutes()).padStart(2,"0");return`${l}-${i}-${r}T${c}:${d}`}function Nn(e,n){const l=e.trim();if(!l)return null;const i=Date.parse(l);if(Number.isNaN(i))throw new Error(`${n}${s("shell.butlerAutomationInvalidDateSuffix")}`);return new Date(i).toISOString()}function Io(e,n){const l=Nn(e,n);if(!l)throw new Error(`${n}${s("shell.butlerAutomationRequiredSuffix")}`);return l}function gi(e,n){const l=e.trim();if(!l)throw new Error(`${n}${s("shell.butlerAutomationRequiredSuffix")}`);const i=Number.parseInt(l,10);if(!Number.isInteger(i))throw new Error(`${n}${s("shell.butlerAutomationInvalidNumberSuffix")}`);return i}function pi(e,n){const l=e.trim();if(!l)return null;const i=Number.parseInt(l,10);if(!Number.isInteger(i))throw new Error(`${n}${s("shell.butlerAutomationInvalidNumberSuffix")}`);return i}function jn(e,n){const l=pi(e,n);if(l===null)return null;if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function No(e,n){const l=gi(e,n);if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function To(e){const n=e.trim();if(!n)return null;const l=n.split(",").map(i=>Number.parseInt(i.trim(),10)).filter(i=>Number.isInteger(i));if(l.length===0||l.some(i=>i<0||i>6))throw new Error(s("shell.butlerAutomationCronDaysValidation"));return Array.from(new Set(l)).sort((i,r)=>i-r)}function G(e){if(!e)return"-";const n=new Date(e);return Number.isNaN(n.getTime())?e:new Intl.DateTimeFormat(void 0,{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}).format(n)}function Ro(e){const n=Math.max(1,Math.ceil(e/1e3)),l=Math.floor(n/3600),i=Math.floor(n%3600/60),r=n%60,c=(d,f)=>new Intl.NumberFormat(void 0,{style:"unit",unit:f,unitDisplay:"narrow"}).format(d);return l>0?[c(l,"hour"),c(Math.max(i,0),"minute")].join(" "):i>0?[c(i,"minute"),c(r,"second")].join(" "):c(r,"second")}function ko(e){const n=Math.max(0,Math.ceil(e/1e3)),l=Math.floor(n/3600),i=Math.floor(n%3600/60),r=n%60;return l>0?`${String(l).padStart(2,"0")}:${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}`:`${String(i).padStart(2,"0")}:${String(r).padStart(2,"0")}`}function Sl(e){switch(e){case"claude-code":return"Claude Code";case"codex":default:return"Codex"}}function Wo(){const{shellMode:e}=us();return e==="mobile"?t.jsx(Xa,{}):t.jsx(Er,{})}export{Wo as AdaptiveButlerPage};
|