@jingyi0605/codingns 0.7.2 → 0.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/public/assets/{AdaptiveButlerPage-174Mg-9X.js → AdaptiveButlerPage-CgBX49t-.js} +3 -3
  2. package/dist/public/assets/{App-BRupl2Ul.js → App-tXOqoHNl.js} +3 -3
  3. package/dist/public/assets/{BootstrapPage-BKzDRWtn.js → BootstrapPage-DoRMz87R.js} +1 -1
  4. package/dist/public/assets/ConversationPage-DXR6Hp4O.js +9 -0
  5. package/dist/public/assets/{DesktopDetachPreviewPage-DtHzSQOX.js → DesktopDetachPreviewPage-Cyk-ZYCk.js} +1 -1
  6. package/dist/public/assets/{DesktopWindowPage-ppc3h5sO.js → DesktopWindowPage-DNVNK3hs.js} +1 -1
  7. package/dist/public/assets/{FileContextPanel-h0kvRbSR.js → FileContextPanel-xGTYDclT.js} +1 -1
  8. package/dist/public/assets/{GitSidebar-TlaPNhxG.js → GitSidebar-Cr3Z9OUI.js} +1 -1
  9. package/dist/public/assets/{MobileCreateSessionSheet-Bp4xOKdt.js → MobileCreateSessionSheet-DMW0V6GJ.js} +1 -1
  10. package/dist/public/assets/{MobileTopHeaderFrame-BawK1vUE.js → MobileTopHeaderFrame-CkdnZ_MU.js} +1 -1
  11. package/dist/public/assets/{MobileWorkspaceSwitcherHeader-CWPXAMoX.js → MobileWorkspaceSwitcherHeader-KIbqBYJN.js} +1 -1
  12. package/dist/public/assets/{RelayConnectEntryPage-B0-OBZXu.js → RelayConnectEntryPage-DIRBH3hw.js} +1 -1
  13. package/dist/public/assets/{ServerSettingsModal-P_pcDvyR.js → ServerSettingsModal-C-9RxdWP.js} +1 -1
  14. package/dist/public/assets/{SessionIndexPage-r8AZ0pJv.js → SessionIndexPage-bRlIydRA.js} +1 -1
  15. package/dist/public/assets/{SettingsPage-B-uNuML1.js → SettingsPage-CMEt4ua9.js} +1 -1
  16. package/dist/public/assets/{TerminalManagerPanel-Bkgr9ZNV.js → TerminalManagerPanel-2bi9wVhT.js} +1 -1
  17. package/dist/public/assets/{TerminalPage-BpFpA3My.js → TerminalPage-DayZz2Tf.js} +1 -1
  18. package/dist/public/assets/{TerminalRuntimeFallbackModal-D_BUt6HD.js → TerminalRuntimeFallbackModal-DgwYcp-Y.js} +1 -1
  19. package/dist/public/assets/{ToolFilesPage-BE9-iHL0.js → ToolFilesPage-YvnP_FXW.js} +1 -1
  20. package/dist/public/assets/{ToolGitPage-ChUkwKgK.js → ToolGitPage-GMcQKtV9.js} +1 -1
  21. package/dist/public/assets/{ToolProcessesPage-C4dli_mi.js → ToolProcessesPage-DFIQ7BCd.js} +1 -1
  22. package/dist/public/assets/{ToolsHomePage-ZmcEotg4.js → ToolsHomePage-CSilFzXR.js} +1 -1
  23. package/dist/public/assets/{WorkbenchLandingPage-DZzbQZHt.js → WorkbenchLandingPage-1VtToSz9.js} +1 -1
  24. package/dist/public/assets/WorkbenchLayout-DScHaza9.js +244 -0
  25. package/dist/public/assets/{WorkbenchModal-CAj_TqWW.js → WorkbenchModal-BWXYSXmC.js} +1 -1
  26. package/dist/public/assets/WorkbenchShellRoute-DN6LdrqC.js +1 -0
  27. package/dist/public/assets/{WorkspaceDebugDetailPage-qku5AzZQ.js → WorkspaceDebugDetailPage-Ux8_Q7la.js} +1 -1
  28. package/dist/public/assets/{WorkspaceDetailPage-BtrSsZVP.js → WorkspaceDetailPage-B402p99m.js} +1 -1
  29. package/dist/public/assets/{WorkspaceHomePage-BhekFDSu.js → WorkspaceHomePage-D2pob6HI.js} +1 -1
  30. package/dist/public/assets/{client-runtime-manager-CgogHxt0.js → client-runtime-manager-C5D76ewj.js} +1 -1
  31. package/dist/public/assets/{file-tree-icon-CLfk31E7.js → file-tree-icon-lfU9Ag77.js} +1 -1
  32. package/dist/public/assets/index-CFYXCsyx.css +1 -0
  33. package/dist/public/assets/{index-DvkfRpBe.js → index-NGxWr8Ix.js} +3 -3
  34. package/dist/public/assets/{login-direct-candidate-resolver-DvJnjQCi.js → login-direct-candidate-resolver-wXSaB0i7.js} +1 -1
  35. package/dist/public/assets/{model-switch-api-Dps4yN2t.js → model-switch-api-CPtou49j.js} +1 -1
  36. package/dist/public/assets/{preferences-service-ohVuseA-.js → preferences-service-CdaK7zA8.js} +1 -1
  37. package/dist/public/assets/{realtime-client-CIci6rCd.js → realtime-client-BjQazYsK.js} +1 -1
  38. package/dist/public/assets/{relay-entry-WiotM2TL.js → relay-entry-BwE5nw0l.js} +1 -1
  39. package/dist/public/assets/{terminal-runtime-meta-C3Mr0zW5.js → terminal-runtime-meta-C-Lbyx2i.js} +1 -1
  40. package/dist/public/assets/{useRegisteredDebugTemplates-DVQBPV-V.js → useRegisteredDebugTemplates-BM7-c-gx.js} +1 -1
  41. package/dist/public/index.html +2 -2
  42. package/dist/server/config/env.js +36 -29
  43. package/dist/server/config/env.js.map +1 -1
  44. package/dist/server/modules/sessions/session-history-service.d.ts +3 -1
  45. package/dist/server/modules/sessions/session-history-service.js +55 -2
  46. package/dist/server/modules/sessions/session-history-service.js.map +1 -1
  47. package/dist/server/modules/sessions/session-provider-error-mapper.js +2 -2
  48. package/dist/server/modules/sessions/session-provider-error-mapper.js.map +1 -1
  49. package/dist/server/server/release-manifest-sync.d.ts +7 -0
  50. package/dist/server/server/release-manifest-sync.js +96 -0
  51. package/dist/server/server/release-manifest-sync.js.map +1 -0
  52. package/dist/server/server/start-host.js +2 -0
  53. package/dist/server/server/start-host.js.map +1 -1
  54. package/dist/server/ws/ws-server.js +1 -1
  55. package/dist/server/ws/ws-server.js.map +1 -1
  56. package/node_modules/@codingns/session-sync-core/package.json +1 -1
  57. package/package.json +3 -2
  58. package/scripts/postinstall.mjs +167 -22
  59. package/dist/public/assets/ConversationPage-BLQXBsBc.js +0 -6
  60. package/dist/public/assets/WorkbenchLayout-Cht6Un5X.js +0 -244
  61. package/dist/public/assets/WorkbenchShellRoute-DzbO05cD.js +0 -1
  62. package/dist/public/assets/index-CkkzIvxs.css +0 -1
@@ -1,3 +1,3 @@
1
- var Zi=Object.defineProperty;var Xi=(e,n,l)=>n in e?Zi(e,n,{enumerable:!0,configurable:!0,writable:!0,value:l}):e[n]=l;var re=(e,n,l)=>Xi(e,typeof n!="symbol"?n+"":n,l);import{j as t,t as s,b as u}from"./index-DvkfRpBe.js";import{h as wl,aL as Gi,aM as Gs,Z as Qi,aN as Ji,aO as er,aP as tr,ac as U,aQ as nr,aR as sr,aS as Il,j as ss,aT as lr,r as ir,u as ms,aU as In,aV as Qs,aW as rr,a0 as Tl,a1 as Nl,aX as ar,aY as or,c as An,aZ as Tn,a_ as Nn,a$ as Rl,b0 as ur,b1 as cr,b2 as dr,b3 as mr,B as Rn,b4 as hs,at as kl,k as El,l as ls,b5 as Ll,b6 as is,b7 as rs,b8 as Pl,q as as,aC as hr}from"./WorkbenchLayout-Cht6Un5X.js";import{e as br,c as Ml,u as Fl,f as Dl,h as fr}from"./App-BRupl2Ul.js";import{E as gr,F as pr,H as Js,I as xr,K as vr,s as Sr,A as yr,R as Ol,i as os,j as Ul,M as Ar}from"./model-switch-api-Dps4yN2t.js";import{R as jr,P as Hl,C as $l}from"./realtime-client-CIci6rCd.js";import{FileContextPanel as Cr}from"./FileContextPanel-h0kvRbSR.js";import{W as Ve}from"./WorkbenchModal-CAj_TqWW.js";import{s as Bl}from"./butler-records-events-DgWCG364.js";import{M as wr}from"./MobileWorkspaceSwitcherHeader-CWPXAMoX.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./relay-entry-WiotM2TL.js";import"./file-tree-icon-CLfk31E7.js";import"./MobileTopHeaderFrame-BawK1vUE.js";function _l(){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 Yn=60,Ir=400,Vl="butler-diagnostic://",Tr=15e3;class ql{constructor(n){re(this,"state");re(this,"listeners",new Set);re(this,"realtimeClient",null);re(this,"realtimeSessionId",null);re(this,"selectedControlSessionId",null);re(this,"controlSessionReloadInFlight",!1);re(this,"terminalSyncTimer",null);re(this,"terminalSyncArmed",!1);re(this,"terminalSyncCompletedControlSessionId",null);re(this,"pendingRunControlSession",null);re(this,"subscribe",n=>(this.listeners.add(n),()=>{this.listeners.delete(n)}));re(this,"getState",()=>this.state);this.workspaceId=n,this.state={loading:!0,sending:!1,switchingProvider:!1,initialized:!1,profile:null,activeProvider:"codex",controlSession:null,capabilities:Ct("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 wl();if(!n.initialized||!n.profile){this.clearPendingRun(),this.patch({loading:!1,initialized:!1,profile:null,activeProvider:"codex",capabilities:Ct("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:Ct(l.providerId)}),await this.reloadForProvider(l.providerId),this.patch({loading:!1})}catch(n){this.patch({loading:!1,error:pe(n)})}}async initializeProfile(n){this.patch({loading:!0,error:null});try{const l=await Gi(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:Ct(l.profile.providerId)}),await this.reloadForProvider(l.profile.providerId)}catch(l){throw this.patch({error:pe(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:Ct(n)});try{const i=await Gs({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:pe(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 Gs(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:pe(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)??Qi();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 er({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 Ji({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:pe(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 gr(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 pr(i,n,l);this.patch({permissionRequests:Zn(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 tr()}catch(l){throw this.patch({historyState:"error",error:pe(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 v=await Js(l,this.state.olderCursor,Yn,"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 x=el(this.state.messages,l,v.messages);this.patch({messages:Xn(x,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:v.nextCursor,hasOlderMessages:!!v.nextCursor})}catch(v){this.patch({loadingOlderMessages:!1,error:pe(v)})}}}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 v=(n?await nr(n):await sr()).controlSession;if(!v){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=v.id;const[x,A,H]=await Promise.all([Js(v.session.sessionId,null,Yn,"backward"),xr(v.session.sessionId),vr(v.session.sessionId)]),P=this.resolvePendingRunControlSession(v,A),R=this.resolvePendingRunRuntimeState(P,A),$=A.hasActiveRun||A.canInterrupt||Te(A.runningState)||qe(A.runningState);((f=this.state.controlSession)==null?void 0:f.id)!==v.id&&(this.terminalSyncCompletedControlSessionId=null),this.terminalSyncArmed=R.hasActiveRun||P.status==="running",$?(this.clearPendingRun(v.id),this.terminalSyncCompletedControlSessionId=null):this.terminalSyncArmed||(this.terminalSyncCompletedControlSessionId=v.id);const W=x.messages.map(Y=>Il(v.session.sessionId,Y));this.ensureRealtimeSubscription(v.session.sessionId,x.cursor),this.patch({controlSession:P,messages:Xn(W,P,{runningState:A.runningState,runtimeHasActiveRun:R.hasActiveRun,runtimeCanInterrupt:R.canInterrupt,detail:A.detail,errorDetail:A.errorDetail,updatedAt:A.updatedAt}),historyState:"ready",loadingOlderMessages:!1,olderCursor:x.nextCursor,hasOlderMessages:!!x.nextCursor,runtimeHasActiveRun:R.hasActiveRun,runtimeCanInterrupt:R.canInterrupt,contextUsage:A.contextUsage,permissionRequests:H.items}),U("butler.runtime.reload_control_session.end",{workspaceId:this.workspaceId,controlSessionId:v.id,sessionId:v.session.sessionId,messages:W.length,historyState:"ready",hasActiveRun:R.hasActiveRun,canInterrupt:R.canInterrupt,terminalSyncArmed:this.terminalSyncArmed,terminalSyncCompletedControlSessionId:this.terminalSyncCompletedControlSessionId})}catch(h){this.patch({historyState:"error",error:pe(h)}),U("butler.runtime.reload_control_session.error",{workspaceId:this.workspaceId,requestedControlSessionId:n??null,message:pe(h)})}}async refreshCapabilities(n){try{const l=await Sr(n,this.workspaceId);this.patch({capabilities:l})}catch{this.patch({capabilities:Ct(n)})}}async refreshOverview(){try{const n=await ss();this.patch({overview:n.overview})}catch(n){this.patch({error:pe(n)})}}async refreshEvents(){try{const n=await lr();this.patch({events:n.items})}catch(n){this.patch({error:pe(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 jr({sessionId:n,cursor:l,limit:Yn,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})})},Ir)}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=el(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:Zn(this.state.permissionRequests,n.request)})}handlePermissionRequestResolved(n){this.isActiveControlSession(n.sessionId)&&this.patch({permissionRequests:Zn(this.state.permissionRequests,n.request)})}patchActiveControlSessionRuntimeState(n){var v;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&&!qe(n.runningState)&&!qe(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?((v=this.state.capabilities)==null?void 0:v.supportsInterrupt)??this.state.runtimeCanInterrupt??n.canInterrupt:n.canInterrupt;r||this.clearPendingRun(l.id);const h=n.status??kr(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:Er(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()+Tr})}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)||qe(l.runningState)||Te(n.session.runningState)||qe(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||qe(l.runningState)||qe(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)||qe(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 k(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 Ct(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 el(e,n,l){const i=new Map;for(const r of e.filter(c=>!zl(c)))i.set(tl(r),r);for(const r of l){const c=Il(n,r);i.set(tl(c),c)}return[...i.values()].sort((r,c)=>r.sequence!==c.sequence?r.sequence-c.sequence:r.timestamp.localeCompare(c.timestamp))}function tl(e){return e.id||e.rawRef}function Zn(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=>!zl(c));if(i.length>0||!n)return i;const r=Nr(n,l);return r?[...i,Rr(n,r,l.updatedAt)]:i}function Nr(e,n){var f,h,v;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())||((v=n.detail)==null?void 0:v.trim())||null,d=[i?"本轮助手会话已结束,但没有收到可展示的助手消息。":"本轮助手会话已结束,但 provider 没有返回可展示的助手消息。"];return c&&(d.push(""),d.push(`诊断信息:${c}`)),d.join(`
2
- `)}function Rr(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:`${Vl}${e.id}`,deliveryState:"sent",clientRequestId:null}}function zl(e){return e.rawRef.startsWith(Vl)}function pe(e){return e instanceof Error?e.message:String(e)}function kr(e,n,l){return l||n==="starting"||n==="running"||n==="reconnecting"?"running":n==="failed"?"failed":e==="closed"?"closed":"idle"}function Er(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 qe(e){return e==="completed"||e==="failed"||e==="interrupted"}const us={"risk-first":["risk","blocker","verification"],"blocker-first":["blocker","risk","verification"],"verification-first":["verification","risk","blocker"],"progress-first":["progress","risk","blocker"]},Wl=300,Lr=1500,Pr=1500,Mr=480*60*1e3,cs=["codex","claude-code"],Fr={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:Wl},Dr=[{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"}],Ne={builder:["🧠","🤖","🦾","🛠️","⚙️","🧩","🚀","🛰️","🔧","💡"],analyst:["🦉","🧭","🔍","📚","🧪","📐","🗂️","📝","🧮","📊"],direct:["🦅","🛡️","⚡","🎯","🪓","🧱","🔨","📌","🧰","🏹"],steady:["🐢","🐘","🦬","🦫","🌲","⛰️","🪨","🧺","🧷","🕰️"],friendly:["🐼","🦊","🐻","🐶","🐱","🐹","🐰","🦄","🌼","🍀"],default:["🧠","🤖","🦉","🧩","📚","💡","🛠️","🚀","🌟","🪄","🧭","🔮"]};function Or(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 Ur(e){var n;if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText))try{await navigator.clipboard.writeText(e);return}catch{}if(!Or(e))throw new Error(s("conversation.copyContentFailed"))}function Hr(){var _s,Vs,qs,zs,Ws,Ks,Ys,Zs,Xs;const e=br(),n=ir(e),{workspaceId:l=""}=Ml(),i=Fl(),{showToast:r}=Dl(),{navigationGroups:c,requestNavigationRefresh:d,setAuxiliaryPanel:f}=ms(),h=u.useRef(null),v=u.useRef(null),[x,A]=u.useState(Fr),[H,P]=u.useState(!1),[R,$]=u.useState(Gn),[W,Y]=u.useState(!1),[te,Z]=u.useState(0),[B,oe]=u.useState([]),[q,We]=u.useState([]),[As,ke]=u.useState([]),[qt,he]=u.useState([]),[rt,Ee]=u.useState([]),[ne,_]=u.useState([]),[be,Le]=u.useState([]),[Pe,at]=u.useState(!1),[zt,ot]=u.useState(!1),[Wt,Kt]=u.useState(!1),[ut,Yt]=u.useState(!1),[fe,ct]=u.useState(null),[Me,se]=u.useState(null),[dt,xe]=u.useState(null),[Zt,y]=u.useState(null),[F,Xt]=u.useState(!1),[E,It]=u.useState(""),[ve,X]=u.useState(null),[ue,I]=u.useState(null),[Tt,Nt]=u.useState(!1),[Ln,mt]=u.useState(!1),[Pn,Ke]=u.useState(null),[Se,ht]=u.useState(null),[Mn,Ye]=u.useState(!1),[Fn,bt]=u.useState(null),[ge,ce]=u.useState([]),[ye,V]=u.useState([]),[Rt,kt]=u.useState(!1),[Ze,Gt]=u.useState(!1),[Ae,Fe]=u.useState(null),[Qt,De]=u.useState(null),[Et,de]=u.useState(null),[Lt,Jt]=u.useState(null),[Pt,en]=u.useState(null),[Dn,Xe]=u.useState(null),[On,tn]=u.useState(null),[Un,ft]=u.useState(null),[le,Mt]=u.useState(()=>Date.now()),{items:Ft}=yr(!0),Ge=u.useRef(null),nn=u.useRef(null),gt=u.useRef(null),sn=u.useId(),[Dt,pt]=u.useState({itemId:null,kind:null});(!h.current||v.current!==l)&&(h.current=new ql(l),v.current=l);const j=h.current,je=k(j,a=>a.loading),me=k(j,a=>a.sending),Ie=k(j,a=>a.switchingProvider),K=k(j,a=>a.initialized),N=k(j,a=>a.profile),z=k(j,a=>a.activeProvider),g=k(j,a=>a.controlSession),Hn=k(j,a=>a.capabilities),D=k(j,a=>a.overview),Ot=k(j,a=>a.events),Oe=k(j,a=>a.messages),Qe=k(j,a=>a.historyState),$n=k(j,a=>a.loadingOlderMessages),Bn=k(j,a=>a.hasOlderMessages),Je=k(j,a=>a.runtimeHasActiveRun),Ue=k(j,a=>a.runtimeCanInterrupt),_n=k(j,a=>a.contextUsage),Ut=k(j,a=>a.permissionRequests),He=k(j,a=>a.error),ln=u.useRef(null),Ht=u.useRef(null),xt=u.useRef(!1),vt=u.useRef(new Set),Ce=((_s=N==null?void 0:N.displayName)==null?void 0:_s.trim())||x.displayName.trim()||s("shell.butlerEntry"),St=u.useMemo(()=>_a({displayName:Ce,providerId:(N==null?void 0:N.providerId)??x.providerId,tone:(N==null?void 0:N.persona.tone)??x.personaTone}),[Ce,x.personaTone,x.providerId,N==null?void 0:N.persona.tone,N==null?void 0:N.providerId]),$t=u.useMemo(()=>q.filter(a=>ds(a.status)).slice(0,3),[q]),rn=u.useMemo(()=>ta(g,Je),[g,Je]),et=ea((g==null?void 0:g.session.sessionId)??null,rn),an=et||me,on=et||me,un=Ue===!0||me?!0:Ue??!1,o=u.useMemo(()=>{if(!g||et)return null;const a=rt.filter(T=>T.status==="active"&&T.controlSessionId===g.id).map(T=>({kind:"timer",timer:T})),m=new Set(rt.filter(T=>T.status==="active"&&T.controlSessionId===g.id).map(T=>T.id)),p=ne.filter(T=>T.status==="active"&&T.controlSessionId===g.id&&!!T.nextRunAt&&!m.has(T.id)).map(T=>({kind:"automation",automation:T}));return[...a,...p].sort((T,O)=>w(Vt(T))-w(Vt(O)))[0]??null},[ne,g,rt,et]),b=Jr(o),S=u.useMemo(()=>((D==null?void 0:D.projects)??[]).map(a=>a.id).sort(),[D==null?void 0:D.projects]),C=((Vs=c.find(a=>a.workspace.id===l))==null?void 0:Vs.workspace.name)??null,G=u.useMemo(()=>new Map(((D==null?void 0:D.projects)??[]).map(a=>[a.id,a.name])),[D==null?void 0:D.projects]),$e=u.useMemo(()=>new Map(c.map(a=>[a.workspace.id,a.workspace.name])),[c]),Q=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]),L=u.useMemo(()=>fe?ne.find(a=>a.id===fe)??null:null,[ne,fe]),yt=u.useMemo(()=>fe?be.filter(a=>a.automationId===fe).sort((a,m)=>w(m.createdAt)-w(a.createdAt)).slice(0,8):[],[be,fe]);u.useEffect(()=>{fe&&!L&&(ct(null),se(null))},[L,fe]);const ie=u.useMemo(()=>new Map(c.flatMap(a=>a.sessions.map(m=>[m.sessionId,a.workspace.id]))),[c]),Vn=u.useMemo(()=>ge.find(a=>a.id===Ae)??ye.find(a=>a.id===Ae)??null,[ye,ge,Ae]);u.useEffect(()=>{var p,T;if(!Ae)return;const a=ge.some(O=>O.id===Ae),m=ye.some(O=>O.id===Ae);a||m||Fe(((p=ge[0])==null?void 0:p.id)??((T=ye[0])==null?void 0:T.id)??null)},[ye,ge,Ae]),u.useEffect(()=>{if(Mt(Date.now()),!b)return;const a=window.setInterval(()=>{Mt(Date.now())},1e3);return()=>{window.clearInterval(a)}},[b]);const At=u.useCallback(async()=>{if(!K){he([]);return}try{const a=await In();he(a.items)}catch(a){r({title:s("shell.butlerSidebarLoadFailed"),description:a instanceof Error?a.message:void 0,tone:"error"})}},[K,r]),tt=u.useCallback(async()=>{if(!K){ce([]),Fe(null);return}if(!(g!=null&&g.id)){ce([]),Fe(null);return}kt(!0);try{const a=await Qs({controlSessionId:(g==null?void 0:g.id)??null});ce(a.payload.items),Fe(m=>{var p;return a.payload.items.length?a.payload.items.some(T=>T.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{kt(!1)}},[g==null?void 0:g.id,K,r]),Bt=u.useCallback(async()=>{if(!K){V([]);return}Gt(!0);try{const a=await Qs();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{Gt(!1)}},[K,r]),cn=u.useCallback(()=>{ot(!0)},[]),dn=u.useCallback(()=>{Kt(!0)},[]),J=u.useCallback(()=>{Yt(!0)},[]),Ai=u.useCallback(()=>{F||At(),Xt(a=>!a)},[F,At]),Be=u.useCallback(()=>{Xt(!1),It("")},[]),ji=u.useCallback(async()=>{if(!(!ve||ue)){I(ve.id);try{await Ol(ve.session.sessionId),ve.id===(g==null?void 0:g.id)&&await j.openControlSession(""),Be(),X(null),await At(),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,ve,ue,Be,At,d,r,j]),js=u.useCallback(()=>{Nt(!0),tt()},[tt]),Ci=u.useCallback(()=>{mt(!0),Bt()},[Bt]);u.useEffect(()=>{if(!F){It("");return}const a=window.requestAnimationFrame(()=>{var m,p;(m=gt.current)==null||m.focus(),(p=gt.current)==null||p.select()});return()=>{window.cancelAnimationFrame(a)}},[F]),u.useEffect(()=>{if(!F)return;const a=p=>{var O,nt;const T=p.target;(O=Ge.current)!=null&&O.contains(T)||(nt=nn.current)!=null&&nt.contains(T)||Be()},m=p=>{p.key==="Escape"&&(p.preventDefault(),Be())};return document.addEventListener("pointerdown",a),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",a),document.removeEventListener("keydown",m)}},[F,Be]),u.useEffect(()=>{Tt&&tt()},[g==null?void 0:g.id,tt,Tt]);const Cs=u.useCallback(a=>{$(m=>({...m,...a}))},[]),qn=u.useCallback(async a=>{ot(!1),Ke(a),ht(null),bt(null),Ye(!0);try{const m=await rr(a);ht(m.task)}catch(m){bt(m instanceof Error?m.message:s("shell.butlerAutomationRoundLoadFailed"))}finally{Ye(!1)}},[]),zn=u.useCallback(async a=>{de(a.id);try{const m=await Tl(a.id);We(p=>ll(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{de(null)}},[d,r,j]),Wn=u.useCallback(async a=>{Jt(a.id);try{await Nl(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{Jt(null)}},[d,r,j]),ws=u.useCallback(async a=>{pt({itemId:a.id,kind:"analyze"});try{const m=await ar(a.id);oe(p=>sl(p,m.item)),he(p=>pa(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{pt({itemId:null,kind:null})}},[r]),Is=u.useCallback(async a=>{pt({itemId:a.id,kind:"start"});try{const m=await or(a.id);oe(p=>sl(p,m.item)),m.followUpTask&&We(p=>ll(p,m.followUpTask)),d(),r({title:s("shell.butlerTodoStartSessionSucceeded"),tone:"success"}),i(An(m.item.workspaceId,m.session.sessionId))}catch(m){r({title:s("shell.butlerTodoStartSessionFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{pt({itemId:null,kind:null})}},[i,d,r]),Ts=u.useCallback(a=>{var p;const m=(p=a.assistantState.linkedSessionId)==null?void 0:p.trim();m&&i(An(a.workspaceId,m))},[i]),Ns=u.useCallback(async a=>{var p;const m=(p=a.assistantState.generatedPrompt)==null?void 0:p.trim();if(m)try{await Ur(m),r({title:s("shell.butlerTodoCopyPromptSucceeded"),tone:"success"})}catch(T){r({title:T instanceof Error?T.message:s("conversation.copyContentFailed"),tone:"error"})}},[r]),mn=u.useCallback(async a=>{tn(a);try{const m=await Tn(a);Ee(p=>il(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{tn(null)}},[r]),hn=u.useCallback(async a=>{en(a);try{const m=await Nn(a);_(p=>xn(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{en(null)}},[r]),Rs=u.useCallback(a=>{const m=ne.find(p=>p.id===a);m&&(ct(a),se(ol(m)))},[ne]),wi=u.useCallback(async()=>{if(!L||!Me)return;let a;try{a=Ba(L,Me)}catch(m){r({title:s("shell.butlerAutomationSaveFailed"),description:m instanceof Error?m.message:void 0,tone:"error"});return}xe(L.id);try{const m=await Rl(L.id,a);_(p=>xn(p,m.payload.automation)),ct(m.payload.automation.id),se(ol(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{xe(null)}},[Me,L,r]),Ii=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 Tn(a.id);Ee(T=>il(T,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]),ks=u.useCallback(async a=>{Xe(a);try{const m=await ur(a);_(p=>xn(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{Xe(null)}},[r]),Ti=u.useCallback(async a=>{if(a.kind==="timer"){await mn(a.timer.id);return}await hn(a.automation.id)},[hn,mn]),Ni=u.useCallback(async a=>{if(a.kind==="timer"){await mn(a.timer.id);return}await ks(a.automation.id)},[mn,ks]),Ri=u.useCallback(async a=>{if(a.kind==="timer"){await Ii(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 Nn(a.automation.id),_(p=>xn(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]),ki=u.useCallback(a=>{const m=kn(a),p=(m?ie.get(m):null)||bs(a)||l;!m||!p||i(An(p,m))},[i,ie,l]),Ei=u.useCallback(async a=>{De(a);try{const m=await cr({sandboxId:a,mode:"project",defaultProvider:z});ce(p=>wt(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>wt(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{De(null)}},[z,g==null?void 0:g.id,d,r]),Li=u.useCallback(async a=>{De(a);try{const m=await dr(a);ce(p=>wt(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>wt(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{De(null)}},[g==null?void 0:g.id,r]),Es=u.useCallback(async a=>{De(a);try{const m=await mr(a);ce(p=>wt(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>wt(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{De(null)}},[g==null?void 0:g.id,d,r]),Ls=u.useCallback(async()=>{if(N){if(!R.displayName.trim()){r({title:s("shell.butlerInitNameRequired"),tone:"warning"});return}Y(!0);try{await j.updateProfile({displayName:R.displayName.trim(),agentsMode:R.agentsMode,agentsFilePath:R.agentsMode==="file"?R.agentsFilePath:null,agentsContent:R.agentsContent,persona:{tone:R.personaTone,language:R.personaLanguage,summaryStyle:R.personaSummaryStyle},focus:{...N.focus,riskPreference:R.focusRiskPreference,reportPriority:us[R.reportPriorityPreset],summaryDebounceSeconds:R.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{Y(!1)}}},[N,R,r,j]);u.useEffect(()=>{j.initialize()},[j]),u.useEffect(()=>{var m,p;const a=JSON.stringify({workspaceId:l,activeProvider:z,controlSessionId:(g==null?void 0:g.id)??null,sessionId:((m=g==null?void 0:g.session)==null?void 0:m.sessionId)??null,messages:Oe.length,historyState:Qe,runtimeHasActiveRun:Je,runtimeCanInterrupt:Ue,loading:je,sending:me,switchingProvider:Ie,error:He});ln.current!==a&&(ln.current=a,U("butler.page.timeline_state",{workspaceId:l,activeProvider:z,controlSessionId:(g==null?void 0:g.id)??null,sessionId:((p=g==null?void 0:g.session)==null?void 0:p.sessionId)??null,messages:Oe.length,historyState:Qe,runtimeHasActiveRun:Je,runtimeCanInterrupt:Ue,loading:je,sending:me,switchingProvider:Ie,error:He??null}))},[l,z,g==null?void 0:g.id,(qs=g==null?void 0:g.session)==null?void 0:qs.sessionId,Oe.length,Qe,Je,Ue,je,me,Ie,He]),u.useEffect(()=>{He&&r({title:s("shell.butlerLoadFailed"),description:He,tone:"error"})},[He,r]),u.useEffect(()=>{var T;const a=((T=g==null?void 0:g.session)==null?void 0:T.sessionId)??null;if(Ht.current!==a&&(Ht.current=a,xt.current=!1,vt.current=new Set),!a)return;const m=Ut.filter(O=>O.status==="pending"),p=new Set(m.map(O=>O.id));xt.current&&m.forEach(O=>{var nt,bn,fn;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())||((fn=(bn=g==null?void 0:g.session)==null?void 0:bn.title)==null?void 0:fn.trim())||Ce,requestTitle:O.title}),tone:"warning",durationMs:8e3})}),vt.current=p,xt.current=!0},[Ce,(zs=g==null?void 0:g.session)==null?void 0:zs.sessionId,(Ws=g==null?void 0:g.session)==null?void 0:Ws.title,g==null?void 0:g.title,Ut,r]),u.useEffect(()=>{if(!N){$(Gn);return}$({displayName:N.displayName,agentsMode:N.agentsMode,agentsFilePath:Da(N),agentsContent:N.agentsContent,personaTone:N.persona.tone,personaLanguage:N.persona.language,personaSummaryStyle:N.persona.summaryStyle,focusRiskPreference:N.focus.riskPreference,reportPriorityPreset:Fa(N.focus.reportPriority),summaryDebounceSeconds:N.focus.summaryDebounceSeconds??Gn.summaryDebounceSeconds})},[N]),u.useEffect(()=>{if(!K){oe([]),We([]),ke([]),he([]),Ee([]),_([]),Le([]),ce([]);return}let a=!1;async function m(){try{const[O,nt,bn,fn,Wi,Ki,Yi]=await Promise.all([El(),ls(),In(),Ll(),is({limit:100}),rs({limit:100}),Promise.all(S.map(Kn=>Pl(Kn)))]);a||(oe(O.items),We(nt.items),he(bn.items),Ee(fn.items),_(Wi.payload.items),Le(Ki.payload.items),ke(Yi.flatMap(Kn=>Kn.items)))}catch(O){if(a)return;oe([]),We([]),ke([]),he([]),Ee([]),_([]),Le([]),ce([]),r({title:s("shell.butlerSidebarLoadFailed"),description:O instanceof Error?O.message:void 0,tone:"error"})}}m();function p(){m()}const T=window.setInterval(()=>{m()},15e3);return window.addEventListener(Rn,p),()=>{a=!0,window.clearInterval(T),window.removeEventListener(Rn,p)}},[K,S,r]),u.useEffect(()=>Bl(()=>{j.reloadEventsAndOverview()}),[j]);const _e=u.useMemo(()=>qa(Ft,[x.providerId,(N==null?void 0:N.providerId)??null,z]),[z,x.providerId,N==null?void 0:N.providerId,Ft]),jt=u.useMemo(()=>_e.filter(a=>a.enabled),[_e]),Pi=((Ks=_e.find(a=>a.value===z))==null?void 0:Ks.enabled)??!0,Mi=_e.some(a=>a.enabled&&a.value!==z);u.useEffect(()=>{K||jt.length===0||jt.some(a=>a.value===x.providerId)||A(a=>{var m;return{...a,providerId:((m=jt[0])==null?void 0:m.value)??a.providerId}})},[jt,x.providerId,K]);const Ps=u.useMemo(()=>[{value:"inline",label:s("shell.butlerAgentsModeInline")},{value:"file",label:s("shell.butlerAgentsModeFile")}],[]),Ms=u.useMemo(()=>[{value:"direct",label:s("shell.butlerToneDirect")},{value:"steady",label:s("shell.butlerToneSteady")},{value:"friendly",label:s("shell.butlerToneFriendly")}],[]),Fs=u.useMemo(()=>[{value:"zh-CN",label:s("shell.butlerLanguageZhCn")},{value:"en-US",label:s("shell.butlerLanguageEnUs")},{value:"bilingual",label:s("shell.butlerLanguageBilingual")}],[]),Ds=u.useMemo(()=>[{value:"brief",label:s("shell.butlerSummaryBrief")},{value:"structured",label:s("shell.butlerSummaryStructured")},{value:"thorough",label:s("shell.butlerSummaryThorough")}],[]),Os=u.useMemo(()=>[{value:"conservative",label:s("shell.butlerRiskConservative")},{value:"balanced",label:s("shell.butlerRiskBalanced")},{value:"proactive",label:s("shell.butlerRiskProactive")}],[]),Us=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")}],[]),Fi=ze(_e,x.providerId),Hs=ze(Ps,x.agentsMode),Di=ze(Ms,x.personaTone),Oi=ze(Fs,x.personaLanguage),Ui=ze(Ds,x.personaSummaryStyle),Hi=ze(Os,x.focusRiskPreference),$i=ze(Us,x.reportPriorityPreset),Bi=x.agentsMode==="inline"?s("shell.butlerAgentsModeInlineDescription"):s("shell.butlerAgentsModeFileDescription"),_i=[Hs,Oi,Hi],$s=u.useMemo(()=>t.jsx($r,{overview:D,events:Ot,inboxItems:B,followUpTasks:q,assistantAutomations:ne,assistantAutomationRuns:be,cancellingFollowUpTaskId:Et,cancellingVerificationId:Lt,cancellingAutomationId:Pt,controlSession:g,sandboxes:ge,settingsForm:R,savingSettings:W,onOpenSandboxManager:js,onOpenFollowUpHistory:cn,onOpenVerificationHistory:dn,onOpenAutomationHistory:J,onOpenAutomationDetail:Rs,onOpenFollowUpDetail:qn,onCancelFollowUpTask:zn,onCancelVerificationRun:Wn,onCancelAutomation:hn,onAnalyzeTodo:ws,onStartTodoSession:Is,onOpenTodoSession:Ts,onCopyTodoPrompt:Ns,todoActionState:Dt,onSettingsFormChange:Cs,onSaveSettings:()=>{Ls()}}),[Ot,ws,hn,js,Ns,J,Rs,cn,dn,q,qn,Ts,Ls,Cs,Is,ne,be,ge,B,Pt,Et,Lt,g,D,zn,Wn,W,R,Dt]);u.useEffect(()=>{if(!K){f(null);return}return f($s),()=>{f(null)}},[K,f,$s]);async function Vi(a){a.preventDefault();const m=x.displayName.trim();if(!m){r({title:s("shell.butlerInitNameRequired"),tone:"warning"});return}const p={displayName:m,providerId:x.providerId,agentsMode:x.agentsMode,persona:{tone:x.personaTone,language:x.personaLanguage,summaryStyle:x.personaSummaryStyle},focus:{projectIds:[],riskPreference:x.focusRiskPreference,reportPriority:us[x.reportPriorityPreset],summaryDebounceSeconds:Wl}};P(!0);try{await j.initializeProfile(p),r({title:s("shell.butlerInitSuccess"),tone:"success"})}catch(T){r({title:s("shell.butlerInitFailed"),description:T instanceof Error?T.message:void 0,tone:"error"})}finally{P(!1)}}async function qi(a){if(a!==z)try{await j.switchProvider(a),Bs(a),r({title:s("shell.butlerProviderSwitched"),description:s("shell.butlerProviderSwitchedDescription",{provider:ze(_e,a)}),tone:"success"})}catch(m){r({title:s("shell.butlerProviderSwitchFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}}async function zi(){try{Bs(z),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 Bs(a){Z(m=>m+1),i(as(l),{replace:!0}),a&&d()}return je&&!K&&!H?t.jsx("main",{className:"workbench-page butler-page-shell butler-loading-shell",children:t.jsx(_l,{})}):K?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:Ce})}),Pe?t.jsxs("div",{className:"butler-header-analysis-popover",role:"status","aria-live":"polite",children:[t.jsx("strong",{children:s("conversation.butlerAnalysisTitle")}),$t.length>0?$t.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"),":",gs(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:z,disabled:!Mi||Ie||me,onChange:a=>{qi(a.target.value)},children:_e.map(a=>t.jsx("option",{value:a.value,disabled:!a.enabled,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:je||me||Ie||!Pi,onClick:()=>{zi()},children:t.jsx("span",{className:"terminal-toolbar-icon","aria-hidden":"true",children:t.jsx(Wa,{})})}),t.jsxs("div",{className:"butler-session-history-anchor",ref:Ge,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:je||me||Ie,onClick:()=>{Ai()},children:t.jsx("span",{className:"terminal-toolbar-icon butler-history-toolbar-icon","aria-hidden":"true",children:t.jsx(Ka,{})})}),t.jsx(hs,{open:F,id:"butler-control-history-popover",className:"butler-session-history-popover",anchorRef:Ge,popoverRef:nn,labelledBy:sn,maxWidth:420,gap:10,viewportPadding:14,children:t.jsx(zr,{sessions:qt,activeControlSessionId:(g==null?void 0:g.id)??null,labelId:sn,query:E,searchInputRef:gt,onQueryChange:It,deletingSessionId:ue,onSelectSession:async a=>{if(a.id===(g==null?void 0:g.id)){Be();return}await j.openControlSession(a.id),Be()},onDeleteSession:a=>{Be(),X(a)}})})]})]})]}),t.jsx("section",{className:"butler-main-column",children:t.jsxs("div",{className:"butler-conversation-shell",children:[t.jsx(Hl,{requests:Ut,replyingRequestId:Zt,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(kl,{sessionId:(Ys=g==null?void 0:g.session)==null?void 0:Ys.sessionId,messages:Oe,historyState:Qe,loadingOlderMessages:$n,hasOlderMessages:Bn,provider:z,assistantAvatar:t.jsx("span",{className:"butler-message-avatar","aria-hidden":"true",children:St}),onLoadOlderMessages:()=>{j.loadOlderMessages()},onRetryMessage:a=>{const m=Oe.find(p=>p.clientRequestId===a);if(m!=null&&m.content.trim()){j.sendMessage(m.content);return}j.retryMessage(a)}}),b?t.jsx(Qr,{schedule:b,currentWorkspaceId:l,currentWorkspaceName:C,projectNameById:G,workspaceNameById:$e,sessionTitleById:Q,sessionWorkspaceIdById:ie,countdownNow:le,cancelling:b.kind==="timer"?On===b.timer.id:Pt===b.automation.id,skippingWait:b.kind==="automation"&&Dn===b.automation.id,executingNow:Un===aa(b),onCancel:()=>{Ti(b)},onSkipWait:()=>{Ni(b)},onExecuteNow:()=>{Ri(b)},onOpenSession:()=>{ki(b)}}):null,t.jsx("div",{className:"butler-composer-shell",children:t.jsx($l,{capabilities:Hn,draftStorageId:`butler:${z}:${te}`,placeholder:s("shell.butlerComposerPlaceholder",{displayName:Ce}),hasActiveRun:an,canInterrupt:un,contextUsage:_n,isSubmitting:me||Ie,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:${z}:${te}`)})]}),t.jsxs(Ve,{open:ve!==null,title:s("shell.deleteSessionConfirmTitle"),description:s("shell.deleteSessionConfirmDescription"),onClose:()=>{ue||X(null)},children:[t.jsx("p",{className:"workbench-section-empty",children:ve?Yl(ve):""}),t.jsxs("div",{className:"workbench-modal-actions",children:[t.jsx("button",{type:"button",className:"secondary-button",disabled:!!ue,onClick:()=>X(null),children:s("common.cancel")}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!ue,onClick:()=>{ji()},children:ue?s("common.loading"):s("shell.deleteSessionAction")})]})]}),t.jsx(Ve,{open:zt,title:s("shell.butlerFollowUpHistoryTitle"),description:s("shell.butlerFollowUpHistoryDescription"),onClose:()=>{ot(!1)},children:t.jsx(Gr,{tasks:q.filter(a=>!ds(a.status)),cancellingTaskId:Et,onOpenFollowUpDetail:qn,onCancelFollowUpTask:zn,onClose:()=>{ot(!1)}})}),t.jsx(Ve,{open:Wt,title:s("shell.butlerVerificationHistoryTitle"),description:s("shell.butlerVerificationHistoryDescription"),onClose:()=>{Kt(!1)},children:t.jsx(fa,{items:Ql((D==null?void 0:D.verifications)??[],"history"),cancellingVerificationId:Lt,onCancelVerificationRun:Wn})}),t.jsx(Ve,{open:ut,title:s("shell.butlerAutomationHistoryTitle"),description:s("shell.butlerAutomationHistoryDescription"),onClose:()=>{Yt(!1)},children:t.jsx(ga,{taskItems:Xl(ne,D,"history"),runItems:Gl(ne,be,D,"history")})}),t.jsx(Ve,{open:L!==null,title:s("shell.butlerAutomationDetailTitle"),description:((Zs=L==null?void 0:L.title)==null?void 0:Zs.trim())||(L==null?void 0:L.actionConfig.content.trim())||s("shell.butlerAutomationDetailDescription"),className:"butler-automation-detail-modal",onClose:()=>{ct(null),se(null),xe(null)},children:L&&Me?t.jsx(la,{automation:L,editorState:Me,saving:dt===L.id,projectName:ps(L,G),targetSessionTitle:$a(L,Q),recentRuns:yt,onEditorChange:a=>{se(m=>m&&{...m,...a})},onSave:()=>{wi()}}):null}),t.jsx(Ve,{open:Tt,title:s("shell.butlerSandboxManagerTitle"),description:s("shell.butlerSandboxManagerDescription"),headerActions:t.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{Ci()},children:s("shell.butlerSandboxBrowseAllAction")}),onClose:()=>{mt(!1),Nt(!1)},children:t.jsx(Yr,{items:ge,selectedSandbox:Vn,loading:Rt,actionSandboxId:Qt,onSelectSandbox:Fe,onReload:tt,onPromoteSandboxToProject:Ei,onExpireSandbox:Li,onRemoveSandbox:Es})}),t.jsx(Ve,{open:Ln,title:s("shell.butlerSandboxLibraryTitle"),description:s("shell.butlerSandboxLibraryDescription"),layout:"list",headerActions:t.jsx("button",{type:"button",className:"secondary-button",disabled:Ze,onClick:()=>{Bt()},children:s("shell.butlerRefreshAction")}),onClose:()=>{mt(!1)},children:t.jsx(Zr,{items:ye,loading:Ze,actionSandboxId:Qt,selectedSandboxId:Ae,onViewSandbox:a=>{Fe(a),mt(!1)},onRemoveSandbox:Es})}),t.jsx(Ve,{open:Pn!==null,title:s("shell.butlerAutomationRoundDetailsTitle"),description:((Xs=Se==null?void 0:Se.sessionTitle)==null?void 0:Xs.trim())||(Se==null?void 0:Se.projectName)||s("shell.butlerAutomationRoundDetailsDescription"),onClose:()=>{Ke(null),ht(null),bt(null),Ye(!1)},children:t.jsx(ba,{task:Se,loading:Mn,error:Fn})})]}):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:Ce})]}),t.jsx("span",{className:"butler-init-preview-provider",children:Fi})]}),t.jsx("div",{className:"butler-init-chip-list",children:_i.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:Di})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerInitPreviewRuleLabel")}),t.jsx("strong",{children:Hs})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerPersonaSummaryStyleLabel")}),t.jsx("strong",{children:Ui})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerReportPriorityPresetLabel")}),t.jsx("strong",{children:$i})]})]})]})]}),t.jsxs("form",{className:"butler-init-form",onSubmit:Vi,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:x.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:x.providerId,disabled:jt.length<=1,onChange:a=>A(m=>({...m,providerId:a.target.value})),children:_e.map(a=>t.jsx("option",{value:a.value,disabled:!a.enabled,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:x.agentsMode,onChange:a=>A(m=>({...m,agentsMode:a.target.value})),children:Ps.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))}),t.jsx("small",{children:Bi})]})]})]}),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:x.personaTone,onChange:a=>A(m=>({...m,personaTone: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.butlerPersonaLanguageLabel")}),t.jsx("select",{className:"butler-form-control",value:x.personaLanguage,onChange:a=>A(m=>({...m,personaLanguage:a.target.value})),children:Fs.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:x.personaSummaryStyle,onChange:a=>A(m=>({...m,personaSummaryStyle:a.target.value})),children:Ds.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:x.focusRiskPreference,onChange:a=>A(m=>({...m,focusRiskPreference:a.target.value})),children:Os.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:x.reportPriorityPreset,onChange:a=>A(m=>({...m,reportPriorityPreset:a.target.value})),children:Us.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:je||H||jt.length===0,children:je||H?s("shell.butlerInitSubmitting"):s("shell.butlerInitSubmit")})})]})]})]})}function $r(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(Br,{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(Vr,{overview:e.overview,automations:e.assistantAutomations,runs:e.assistantAutomationRuns,cancellingAutomationId:e.cancellingAutomationId,onOpenAutomationHistory:e.onOpenAutomationHistory,onOpenAutomationDetail:e.onOpenAutomationDetail,onCancelAutomation:e.onCancelAutomation}):t.jsx(ra,{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 Br(e){var r;const n=u.useMemo(()=>e.followUpTasks.filter(c=>ds(c.status)),[e.followUpTasks]),l=u.useMemo(()=>{var c;return Ql(((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(_r,{sandboxes:e.sandboxes,onOpenSandboxManager:e.onOpenSandboxManager}),t.jsx(Xr,{tasks:n,cancellingTaskId:e.cancellingFollowUpTaskId,onOpenFollowUpHistory:e.onOpenFollowUpHistory,onOpenFollowUpDetail:e.onOpenFollowUpDetail,onCancelFollowUpTask:e.onCancelFollowUpTask}),t.jsx(Kl,{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(qr,{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 _r(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 Vr(e){const n=u.useMemo(()=>Xl(e.automations,e.overview,"active"),[e.automations,e.overview]),l=u.useMemo(()=>Gl(e.automations,e.runs,e.overview,"active"),[e.automations,e.overview,e.runs]);return t.jsxs(t.Fragment,{children:[t.jsx(na,{items:n,cancellingAutomationId:e.cancellingAutomationId,onCancelAutomation:e.onCancelAutomation,onOpenAutomationDetail:e.onOpenAutomationDetail,emptyText:s("shell.butlerAutomationTasksEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:e.onOpenAutomationHistory}),t.jsx(sa,{items:l,emptyText:s("shell.butlerAutomationRunsEmpty"),onOpenAutomationDetail:e.onOpenAutomationDetail})]})}function Kl(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?Ra(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||!Ta(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 qr(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:Oa(n.status)}),t.jsx("span",{className:"butler-inline-badge",children:ka(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 zr(e){const n=u.useDeferredValue(e.query),l=u.useMemo(()=>{const d=n.trim().toLowerCase();return e.sessions.map(f=>{const h=Yl(f),v=Wr(f,h),x=w(f.updatedAt),A=[h,v,f.sessionId].join(`
3
- `).toLowerCase();return{session:f,title:h,preview:v,updatedAtMs:x,active:x>0&&Date.now()-x<=Mr,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(Kr,{})}),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(os,{compact:!0,className:"butler-session-history-section-list",role:"list",children:i.map(d=>t.jsx(nl,{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(os,{compact:!0,className:"butler-session-history-section-list",role:"list",children:r.map(d=>t.jsx(nl,{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 nl(e){return t.jsx(Ul,{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:fs(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 Yl(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 Wr(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 Kr(){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 Yr(e){var f,h,v;const n=u.useMemo(()=>[...e.items].sort((x,A)=>w(A.updatedAt)-w(x.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":oi(l.status),children:ai(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:ui(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:ci(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:fs(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:((v=e.selectedSandbox.workspace)==null?void 0:v.path)??s("shell.butlerSandboxWorkspaceMissing")})]})]}),e.selectedSandbox.workspace?t.jsx(Cr,{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 Zr(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(os,{className:"butler-sandbox-browser-list",compact:!0,children:n.map(l=>{var r;const i=e.actionSandboxId===l.id;return t.jsx(Ul,{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":oi(l.status),children:ai(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:ui(l.sourceKind)}),t.jsx("span",{children:ci(l.visibility)}),t.jsx("span",{children:fs(l.updatedAt)})]})},l.id)})})}function Xr(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 Gr(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:gs(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:ae(it(n))}),t.jsxs("div",{className:"butler-inline-actions",children:[e.onCancelFollowUpTask&&Ia(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=da(e.schedule,e.countdownNow),h=ua(e.schedule,e.countdownNow),v=ca(e.schedule,e.countdownNow),x=ya(e.schedule,e.projectNameById,e.workspaceNameById,e.currentWorkspaceId,e.currentWorkspaceName),A=ja(e.schedule,e.sessionTitleById),H=ma(e.schedule),P=!!(kn(e.schedule)&&(e.sessionWorkspaceIdById.has(kn(e.schedule))||bs(e.schedule))),R=oa(e.schedule),$=ha(e.schedule),W=R?e.executingNow?s("shell.butlerControlTimerExecutingNow"):s("shell.butlerControlTimerExecuteNowAction"):e.skippingWait?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerCancelAction"),Y=R?e.cancelling?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerStopAction"):e.cancelling?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerCancelOperationAction");return u.useEffect(()=>{if(!c)return;const te=B=>{var oe,q;(oe=i.current)!=null&&oe.contains(B.target)||(q=r.current)!=null&&q.contains(B.target)||d(!1)},Z=B=>{B.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",te),document.addEventListener("keydown",Z),()=>{document.removeEventListener("pointerdown",te),document.removeEventListener("keydown",Z)}},[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:$})]}),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:v})]}),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:x,children:x})]}),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(te=>!te)},children:t.jsx("span",{className:"butler-control-timer-banner-detail-icon","aria-hidden":"true",children:t.jsx(Ca,{})})}),t.jsx(hs,{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:R?e.onExecuteNow:e.onSkipWait,children:W}),t.jsx("button",{type:"button",className:"secondary-button butler-control-timer-banner-action",disabled:e.cancelling||e.executingNow||e.skippingWait,onClick:e.onCancel,children:Y})]}),R?t.jsx("p",{className:"butler-control-timer-banner-note",children:s("shell.butlerControlTimerActionNote")}):null]})})}function Jr(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)},Lr))},[e,n]),u.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),e??n}function ea(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)},Pr))},[n,l]),u.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),l}function ta(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 na(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")," · ",ae(n.nextRunAt)]}),t.jsxs("span",{className:"butler-automation-overview-inline-meta",children:[s("shell.butlerAutomationTaskLastRunLabel")," · ",ae(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 sa(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")," · ",ae(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 la(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:ti(e.automation.triggerType)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationStatusLabel")}),t.jsx("strong",{children:li(e.automation.status)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskNextRunLabel")}),t.jsx("strong",{children:ae(e.automation.nextRunAt)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskLastRunLabel")}),t.jsx("strong",{children:ae(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(ia,{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":si(n.status),children:ii(n.status)})]}),t.jsxs("div",{className:"butler-automation-detail-run-meta",children:[t.jsx("span",{children:ni(n.triggerType)}),t.jsx("span",{children:ae(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 ia(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 ra(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:Dr.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 ae(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 aa(e){return e.kind==="timer"?e.timer.id:e.automation.id}function Vt(e){return e.kind==="timer"?e.timer.dueAt:e.automation.nextRunAt}function bs(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 kn(e){var n,l,i,r,c,d,f,h,v,x,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())||((v=(h=(f=e.automation.controlSession)==null?void 0:f.session)==null?void 0:h.sessionId)==null?void 0:v.trim())||((A=(x=e.automation.controlSession)==null?void 0:x.sessionId)==null?void 0:A.trim())||null}function oa(e){return e.kind==="timer"||e.automation.triggerType==="once"}function ua(e,n){const l=w(Vt(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueLead"):s("shell.butlerControlTimerCountdownLead")}function ca(e,n){const l=w(Vt(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueTail"):s("shell.butlerControlTimerCountdownTail")}function da(e,n){const l=w(Vt(e));return!l||l<=n?"00:00":wa(l-n)}function ma(e){return e.kind==="timer"?va(e.timer):e.automation.actionConfig.content.trim()||s("conversation.butlerAnalysisEmpty")}function ha(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 Xl(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:ri(c),projectName:ps(c,i),status:Ha(c.status),taskTypeLabel:ti(c.triggerType),statusLabel:li(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 Gl(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 v=d.get(h.automationId);return{run:h,automation:v,normalizedStatus:si(h.status)}}).filter(({automation:h})=>!!h).filter(({normalizedStatus:h})=>i==="history"?!r(h):r(h)).map(({run:h,automation:v,normalizedStatus:x})=>{var A,H;return{id:`assistant-automation-run:${h.id}`,automationId:h.automationId,kind:"assistant_automation_run",title:ri(v),projectName:ps(v,c),status:x,sourceLabel:ni(h.triggerType),statusLabel:ii(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,v)=>w(v.createdAt)-w(h.createdAt)).slice(0,12)}function ba(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:Ua(l.kind)})]}),t.jsx("span",{children:ae(l.createdAt)})]}),t.jsxs("div",{className:"butler-follow-up-round-body",children:[t.jsxs("p",{children:[s("shell.butlerAutomationRoundProcessedAtLabel"),":",ae(l.createdAt)]}),t.jsxs("p",{children:[s("shell.butlerAutomationRoundStatusLabel"),":",gs(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 fa(e){return e.items.length===0?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerVerificationHistoryEmpty")}):t.jsx(Kl,{title:s("shell.butlerInfoVerificationRecordsTitle"),items:e.items,emptyText:s("shell.butlerVerificationHistoryEmpty"),cancellingVerificationId:e.cancellingVerificationId,onCancelVerificationRun:e.onCancelVerificationRun})}function ga(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:ae(n.lastRunAt)})]})]}),t.jsxs("footer",{className:"butler-automation-card-footer",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskNextRunLabel")}),t.jsx("strong",{children:ae(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:ae(n.createdAt)})]})]},n.id))]})}function Ql(e,n){return[...e].filter(l=>n==="history"?!al(l.status):al(l.status)).sort((l,i)=>w(Qn(i))-w(Qn(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:Na(l.status),content:((r=l.summary)==null?void 0:r.trim())||s("shell.butlerInfoVerificationFallback",{status:l.status}),meta:ae(Qn(l)),verification:l}})}function sl(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(r.updatedAt)-w(i.updatedAt))}function ll(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(it(r))-w(it(i)))}function pa(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(r.updatedAt)-w(i.updatedAt))}function il(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(rl(r))-w(rl(i)))}function ds(e){return e==="active"||e==="waiting_user"}function rl(e){return e.dueAt||e.triggeredAt||e.cancelledAt||e.updatedAt||e.createdAt}function xa(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 va(e){return e.content.trim()||xa(e)}function Sa(e,n,l,i,r){var f,h,v,x;const c=(f=e.projectId)==null?void 0:f.trim();if(c&&n.has(c))return n.get(c);const d=((x=(v=(h=e.controlSession)==null?void 0:h.session)==null?void 0:v.workspaceId)==null?void 0:x.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 ya(e,n,l,i,r){var f;if(e.kind==="timer")return Sa(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=bs(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 Aa(e,n){var r,c,d,f,h,v,x;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=((x=(v=(h=e.controlSession)==null?void 0:h.session)==null?void 0:v.sessionId)==null?void 0:x.trim())||e.sessionId.trim();return i&&n.has(i)?n.get(i):s("shell.butlerControlTimerUnknownSession")}function ja(e,n){var i,r,c;if(e.kind==="timer")return Aa(e.timer,n);const l=kn(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 Ca(){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 wa(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 al(e){return e==="queued"||e==="running"}function Ia(e){return e.status==="active"||e.status==="waiting_user"}function Ta(e){return e.status==="queued"||e.status==="running"}function Na(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 Ra(e){return e==="failed"?"failed":e==="cancelled"?"cancelled":e==="passed"||e==="skipped"?"completed":"active"}function ka(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 Qn(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 Ea(e){const n=e.trim();return n||null}function gn(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 jn(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 La(e,n){const l=jn(e,n);if(!l)throw new Error(`${n}${s("shell.butlerAutomationRequiredSuffix")}`);return l}function Jl(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 ei(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 pn(e,n){const l=ei(e,n);if(l===null)return null;if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Pa(e,n){const l=Jl(e,n);if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Ma(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 fs(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 Fa(e){for(const[n,l]of Object.entries(us))if(l.length===e.length&&l.every((i,r)=>i===e[r]))return n;return"risk-first"}function Da(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 Oa(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 gs(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 Ua(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 ti(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 ni(e){return e==="interval"||e==="cron"?s("shell.butlerAutomationRunSourcePatrol"):e==="once"?s("shell.butlerAutomationRunSourceControlTimer"):s("shell.butlerAutomationRunSourceFollowUp")}function si(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 Ha(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 li(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 ii(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 ri(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 ps(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 $a(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 ol(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=gn(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=gn(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=gn(e.triggerConfig.stopAt)):(n.pollIntervalSeconds=st(e.triggerConfig.pollIntervalSeconds),n.expiresAt=gn(e.triggerConfig.expiresAt),n.maxChecks=st(e.triggerConfig.maxChecks)),n}function Ba(e,n){const l={title:Ea(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:La(n.dueAt,s("shell.butlerAutomationDueAtLabel"))}:e.triggerConfig.type==="interval"?{...l,everySeconds:pn(n.everySeconds,s("shell.butlerAutomationEverySecondsLabel")),everyMinutes:pn(n.everyMinutes,s("shell.butlerAutomationEveryMinutesLabel")),everyHours:pn(n.everyHours,s("shell.butlerAutomationEveryHoursLabel")),stopAt:jn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:e.triggerConfig.type==="cron"?{...l,cronMinute:Jl(n.cronMinute,s("shell.butlerAutomationCronMinuteLabel")),cronHour:ei(n.cronHour,s("shell.butlerAutomationCronHourLabel")),cronDaysOfWeek:Ma(n.cronDaysOfWeek),stopAt:jn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:{...l,pollIntervalSeconds:Pa(n.pollIntervalSeconds,s("shell.butlerAutomationPollIntervalLabel")),expiresAt:jn(n.expiresAt,s("shell.butlerAutomationExpiresAtLabel")),maxChecks:pn(n.maxChecks,s("shell.butlerAutomationMaxChecksLabel"))}}function ai(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 oi(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 ui(e){return e==="clone"?s("shell.butlerSandboxSourceClone"):s("shell.butlerSandboxSourceBlank")}function ci(e){return e==="pinned"?s("shell.butlerSandboxVisibilityPinned"):s("shell.butlerSandboxVisibilityAssistantOnly")}function wt(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 xn(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(ul(r))-w(ul(i)))}function ul(e){return e.updatedAt||e.lastRunAt||e.nextRunAt||e.createdAt}function _a(e){const l=`${e.displayName.trim()}:${e.providerId}:${e.tone}`,i=Va(e);if(!l)return Ne.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 Va(e){const n=e.displayName.trim().toLowerCase();return/(bot|ai|智能|助手|助理|管家|buddy|helper)/.test(n)?Ne.builder:/(书|学|知|研|析|查|review|audit|scan)/.test(n)?Ne.analyst:e.tone==="friendly"?Ne.friendly:e.tone==="steady"?Ne.steady:e.tone==="direct"?e.providerId==="claude-code"?Ne.analyst:Ne.direct:e.providerId==="claude-code"?Ne.analyst:Ne.default}function Jn(e){switch(e){case"claude-code":return"Claude Code";case"codex":default:return"Codex"}}function qa(e,n){const l=(e==null?void 0:e.flatMap(r=>{if(!za(r.provider))return[];const c=r.provider,d=r.displayName||Jn(c);return[{value:c,label:r.enabled?d:`${d} (${s("settings.skillTargetDisabledTag")})`,enabled:r.enabled}]}))??cs.map(r=>({value:r,label:Jn(r),enabled:!0})),i=new Map(l.map(r=>[r.value,r]));for(const r of n)!r||i.has(r)||i.set(r,{value:r,label:`${Jn(r)} (${s("settings.skillTargetDisabledTag")})`,enabled:!1});return cs.map(r=>i.get(r)).filter(r=>!!r)}function za(e){return cs.includes(e)}function ze(e,n){var l;return((l=e.find(i=>i.value===n))==null?void 0:l.label)??n}function Wa(){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 Ka(){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 di="mobile.butler.active-tab",Cn=["info","automation","settings"],Ya=15e3,xs=56,vs=1.2,cl=360,Za=1500,Xa=1500;function Ga(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)},Za))},[e,n]),u.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),e??n}function Qa(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)},Xa))},[n,l]),u.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),l}function Ja(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 eo(){if(typeof window>"u")return"info";try{const e=window.localStorage.getItem(di);return e==="automation"||e==="settings"?e:"info"}catch{return"info"}}function to(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 no(e,n){return e==="settings"?"settings":e==="automation"?"automation":e==="info"?"info":n}function so(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)<xs)return{closeSidebar:!1,nextTab:e};if(Math.abs(i)<Math.abs(r)*vs)return{closeSidebar:!1,nextTab:e};const c=Cn.indexOf(e);if(i>0&&c===0)return{closeSidebar:!0,nextTab:e};const d=i<0?Math.min(Cn.length-1,c+1):Math.max(0,c-1);return{closeSidebar:!1,nextTab:Cn[d]??e}}function lo(e,n){if(!e)return null;const l=n.x-e.x,i=n.y-e.y;return Math.abs(l)<xs||Math.abs(l)<Math.abs(i)*vs?null:l>0?"list":"sidebar"}function es(e){return e instanceof Element?!!e.closest("input, textarea, select, option, label, button, a, [contenteditable='true'], [data-mobile-butler-gesture='ignore']"):!1}function io(){var Ht,xt,vt,Ce,St,$t,rn,et,an,on,un;const{workspaceId:e=""}=Ml(),n=fr(),l=Fl(),{showToast:i}=Dl(),{navigationGroups:r,requestNavigationRefresh:c,selectWorkspace:d}=ms(),f=((Ht=r.find(o=>o.workspace.id===e))==null?void 0:Ht.workspace)??null,h=u.useMemo(()=>new Map(r.map(o=>[o.workspace.id,o.workspace.name])),[r]),v=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]),x=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(eo()),P=no(A,H.current),R=u.useRef(null),$=u.useRef(null),W=u.useRef(null),Y=u.useRef(null),te=u.useRef(null),[Z,B]=u.useState(null),[oe,q]=u.useState(null),[We,As]=u.useState(null),[ke,qt]=u.useState(null),[he,rt]=u.useState(null),[Ee,ne]=u.useState(null),[_,be]=u.useState(null),[Le,Pe]=u.useState(null),[at,zt]=u.useState(null),[ot,Wt]=u.useState(null),[Kt,ut]=u.useState(null),[Yt,fe]=u.useState(null),[ct,Me]=u.useState(()=>Date.now()),[se,dt]=u.useState(null),[xe,Zt]=u.useState(null),[y,F]=u.useState({loading:!0,initialized:!1,profile:null,overview:null,followUpTasks:[],inboxItems:[],patrolPlans:[],controlSessions:[],controlTimers:[],assistantAutomations:[],assistantAutomationRuns:[]}),Xt=u.useMemo(()=>{var o;return new Map((((o=y.overview)==null?void 0:o.projects)??[]).map(b=>[b.id,b.name]))},[(xt=y.overview)==null?void 0:xt.projects]);(!Y.current||te.current!==e)&&(Y.current=new ql(e),te.current=e);const E=Y.current,It=k(E,o=>o.loading),ve=k(E,o=>o.initialized),X=k(E,o=>o.profile),ue=k(E,o=>o.activeProvider),I=k(E,o=>o.controlSession),Tt=k(E,o=>o.capabilities),Nt=k(E,o=>o.messages),Ln=k(E,o=>o.historyState),mt=k(E,o=>o.loadingOlderMessages),Pn=k(E,o=>o.hasOlderMessages),Ke=k(E,o=>o.sending),Se=k(E,o=>o.runtimeHasActiveRun),ht=k(E,o=>o.runtimeCanInterrupt),Mn=k(E,o=>o.contextUsage),Ye=k(E,o=>o.permissionRequests),{composerPortalTarget:Fn}=hr(),bt=u.useRef(null),ge=u.useRef(null),ce=u.useRef(!1),ye=u.useRef(new Set);u.useEffect(()=>{if(H.current=P,!(typeof window>"u"))try{window.localStorage.setItem(di,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&&E.initialize()},[E,e]),u.useEffect(()=>{var G,$e,Q,L,yt;const o=((G=I==null?void 0:I.session)==null?void 0:G.sessionId)??null;if(ge.current!==o&&(ge.current=o,ce.current=!1,ye.current=new Set),!o)return;const b=Ye.filter(ie=>ie.status==="pending"),S=new Set(b.map(ie=>ie.id)),C=(($e=I==null?void 0:I.title)==null?void 0:$e.trim())||((L=(Q=I==null?void 0:I.session)==null?void 0:Q.title)==null?void 0:L.trim())||((yt=X==null?void 0:X.displayName)==null?void 0:yt.trim())||s("shell.butlerEntry");ce.current&&b.forEach(ie=>{ye.current.has(ie.id)||i({id:`mobile-butler-permission-request-${ie.id}`,title:s("conversation.permissionRequestToastTitle"),description:s("conversation.backgroundPermissionToastDescription",{title:C,requestTitle:ie.title}),tone:"warning",durationMs:8e3})}),ye.current=S,ce.current=!0},[(vt=I==null?void 0:I.session)==null?void 0:vt.sessionId,(Ce=I==null?void 0:I.session)==null?void 0:Ce.title,I==null?void 0:I.title,Ye,X==null?void 0:X.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($e){F(Q=>({...Q,loading:!0}));try{const Q=await wl();if(!Q.initialized||!Q.profile){o||F({loading:!1,initialized:!1,profile:null,overview:null,followUpTasks:[],inboxItems:[],patrolPlans:[],controlSessions:[],controlTimers:[],assistantAutomations:[],assistantAutomationRuns:[]});return}const[L,yt,ie,Vn,At,tt,Bt]=await Promise.all([ss(),ls(),El({workspaceId:e}),In(),Ll(),is({limit:100}),rs({limit:100})]),cn=L.overview.projects.filter(J=>J.workspaceId===e).map(J=>J.id),dn=await Promise.all(cn.map(J=>Pl(J)));if(o)return;F({loading:!1,initialized:!0,profile:Q.profile,overview:L.overview,followUpTasks:yt.items.filter(J=>J.workspaceId===e),inboxItems:ie.items.filter(J=>J.status!=="closed"),patrolPlans:dn.flatMap(J=>J.items),controlSessions:Vn.items,controlTimers:At.items,assistantAutomations:tt.payload.items,assistantAutomationRuns:Bt.payload.items})}catch(Q){if(o)return;F(L=>({...L,loading:!1})),$e&&i({title:s("shell.butlerLoadFailed"),description:Q instanceof Error?Q.message:void 0,tone:"error"})}}b(!0);const S=window.setInterval(()=>{b(!1)},Ya),C=Bl(()=>{b(!1)}),G=()=>{b(!1)};return window.addEventListener(Rn,G),()=>{o=!0,window.clearInterval(S),C(),window.removeEventListener(Rn,G)}},[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))},[(St=y.overview)==null?void 0:St.projects,e]),Rt=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]),kt=u.useMemo(()=>y.followUpTasks.filter(o=>bl(o.status)),[y.followUpTasks]),Ze=u.useMemo(()=>{var o;return(((o=y.overview)==null?void 0:o.verifications)??[]).filter(b=>b.projectId?V.has(b.projectId):!1)},[($t=y.overview)==null?void 0:$t.verifications,V]),Gt=u.useMemo(()=>[...kt].sort((o,b)=>M(we(b))-M(we(o))).slice(0,4),[kt]),Ae=u.useMemo(()=>ml(Ze,"active"),[Ze]),Fe=u.useMemo(()=>ml(Ze,"history"),[Ze]),Qt=u.useMemo(()=>fo(y.inboxItems.filter(o=>o.status!=="closed")).slice(0,4),[y.inboxItems]),De=u.useMemo(()=>xl(y.assistantAutomations,y.overview,V,"active"),[y.assistantAutomations,y.overview,V]),Et=u.useMemo(()=>vl(y.assistantAutomations,y.assistantAutomationRuns,y.overview,V,"active"),[y.assistantAutomations,y.assistantAutomationRuns,y.overview,V]),de=u.useMemo(()=>_?y.assistantAutomations.find(o=>o.id===_)??null:null,[_,y.assistantAutomations]),Lt=u.useMemo(()=>_?y.assistantAutomationRuns.filter(o=>o.automationId===_).sort((o,b)=>M(b.createdAt)-M(o.createdAt)).slice(0,6):[],[_,y.assistantAutomationRuns]);u.useEffect(()=>{_&&!de&&(be(null),Pe(null))},[de,_]);const Jt=u.useMemo(()=>[...y.followUpTasks].filter(o=>!bl(o.status)).sort((o,b)=>M(we(b))-M(we(o))).slice(0,8),[y.followUpTasks]),Pt=u.useMemo(()=>xl(y.assistantAutomations,y.overview,V,"history"),[y.assistantAutomations,y.overview,V]),en=u.useMemo(()=>vl(y.assistantAutomations,y.assistantAutomationRuns,y.overview,V,"history"),[y.assistantAutomations,y.assistantAutomationRuns,y.overview,V]),Dn=u.useMemo(()=>Ja(I,Se),[I,Se]),Xe=Qa((I==null?void 0:I.session.sessionId)??null,Dn),On=Xe||Ke,tn=Xe||Ke,Un=ht===!0||Ke?!0:ht??!1,ft=u.useMemo(()=>{if(!I||Xe)return null;const o=Rt.filter(C=>C.status==="active"&&C.controlSessionId===I.id).map(C=>({kind:"timer",timer:C})),b=new Set(Rt.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,G)=>M(En(C))-M(En(G)))[0]??null},[I,Xe,y.assistantAutomations,Rt]),le=Ga(ft),Mt=y.loading||It,Ft=!Mt&&(!y.initialized||!ve||!y.profile),Ge=((rn=X==null?void 0:X.displayName)==null?void 0:rn.trim())||((an=(et=y.profile)==null?void 0:et.displayName)==null?void 0:an.trim())||s("shell.butlerEntry"),nn=!I&&Nt.length===0,gt=!Ft&&Z===null;u.useEffect(()=>{if(Me(Date.now()),!le)return;const o=window.setInterval(()=>{Me(Date.now())},1e3);return()=>{window.clearInterval(o)}},[le]),u.useEffect(()=>{Z!=="sidebar"&&q(null)},[Z]);const sn=oe==="follow_up"?t.jsx(dl,{title:s("shell.butlerFollowUpHistoryTitle"),description:s("shell.butlerFollowUpHistoryDescription"),emptyText:s("shell.butlerInfoFollowUpRecordsEmpty"),onClose:()=>q(null),items:Jt.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:Sl(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:ee(we(o))}),meta:ee(we(o)),actionLabel:vn(o.status)?ke===o.id?s("conversation.butlerFollowUpStopping"):s("conversation.butlerStopFollowUpAction"):null,actionDisabled:ke===o.id,onAction:vn(o.status)?()=>{Oe(o)}:void 0}})}):oe==="verification"?t.jsx(dl,{title:s("shell.butlerVerificationHistoryTitle"),description:s("shell.butlerVerificationHistoryDescription"),emptyText:s("shell.butlerVerificationHistoryEmpty"),onClose:()=>q(null),items:Fe.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&&gl(o.verification.status)?he===o.verification.id?s("conversation.butlerVerificationStopping"):s("conversation.butlerStopVerificationAction"):null,actionDisabled:o.verification?he===o.verification.id:!1,onAction:o.verification?()=>{Qe(o.verification)}:void 0}))}):oe==="automation"?t.jsx(mo,{taskItems:Pt,runItems:en,onClose:()=>q(null)}):P==="info"?t.jsxs(t.Fragment,{children:[t.jsx(_t,{title:s("shell.butlerInfoFollowUpRecordsTitle"),emptyText:s("shell.butlerInfoFollowUpRecordsEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("follow_up"),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:Sl(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:ee(we(o))}),meta:ee(we(o)),actionLabel:vn(o.status)?ke===o.id?s("conversation.butlerFollowUpStopping"):s("conversation.butlerStopFollowUpAction"):null,actionDisabled:ke===o.id,onAction:vn(o.status)?()=>{Oe(o)}:void 0}})}),t.jsx(_t,{title:s("shell.butlerInfoVerificationRecordsTitle"),emptyText:s("shell.butlerInfoVerificationRecordsEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("verification"),items:Ae.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&&gl(o.verification.status)?he===o.verification.id?s("conversation.butlerVerificationStopping"):s("conversation.butlerStopVerificationAction"):null,actionDisabled:o.verification?he===o.verification.id:!1,onAction:o.verification?()=>{Qe(o.verification)}:void 0}))}),t.jsx(co,{title:s("shell.butlerInfoTodoRecordsTitle"),emptyText:s("shell.butlerInfoTodoRecordsEmpty"),items:Qt.map((o,b)=>({id:`${o.title}:${b}`,title:o.title,content:o.content}))})]}):P==="automation"?t.jsxs(t.Fragment,{children:[t.jsx(ao,{items:De,emptyText:s("shell.butlerAutomationTasksEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("automation"),selectedAutomationId:_,cancellingAutomationId:Ee,onSelectAutomation:Bn,onCancelAutomation:o=>{Ue(o)}}),de&&Le?t.jsx(oo,{automation:de,editorState:Le,saving:at===de.id,recentRuns:Lt,workspaceNameById:h,sessionTitleById:v,onClose:()=>{be(null),Pe(null)},onEditorChange:o=>{Pe(b=>b&&{...b,...o})},onSave:()=>{Je()}}):null,t.jsx(_t,{title:s("shell.butlerAutomationRunsTitle"),emptyText:s("shell.butlerAutomationRunsEmpty"),items:Et.map(o=>({id:o.id,title:o.title,subtitle:o.projectName,status:o.statusLabel,content:`${o.sourceLabel} · ${o.summary}`,meta:ee(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(Re,{label:s("shell.butlerDisplayNameLabel"),value:Ge}),t.jsx(Re,{label:s("shell.butlerProviderLabel"),value:Cl(ue)}),t.jsx(Re,{label:s("shell.mobileButlerAssistantWorkspaceLabel"),value:((on=y.profile)==null?void 0:on.workspacePath)??(f==null?void 0:f.path)??"-"})]})]});bo(bt,We,gt,`${e}:${Z??"none"}`);function Dt(o){o!==P&&(q(null),l(as(e,o),{replace:!0}))}function pt(o){if(o.changedTouches.length!==1){R.current=null;return}if(es(o.target)){R.current=null;return}const b=o.changedTouches[0];R.current={x:b.clientX,y:b.clientY}}function j(o){if(o.changedTouches.length!==1)return;const b=R.current;R.current=null;const S=o.changedTouches[0],C=lo(b,{x:S.clientX,y:S.clientY});C&&B(C)}function je(o){if(o.changedTouches.length!==1){$.current=null;return}if(es(o.target)){$.current=null;return}const b=o.changedTouches[0];$.current={x:b.clientX,y:b.clientY}}function me(o){const b=$.current;if($.current=null,!b||o.changedTouches.length!==1)return;const S=o.changedTouches[0],C=S.clientX-b.x,G=S.clientY-b.y;C>-xs||Math.abs(C)<Math.abs(G)*vs||B(null)}function Ie(o){if(o.changedTouches.length!==1){W.current=null;return}if(es(o.target)){W.current=null;return}const b=o.changedTouches[0];W.current={x:b.clientX,y:b.clientY}}function K(o){const b=W.current;if(W.current=null,o.changedTouches.length!==1)return;const S=o.changedTouches[0],C=so(P,b,{x:S.clientX,y:S.clientY});if(C.closeSidebar){B(null);return}C.nextTab!==P&&Dt(C.nextTab)}async function N(o){await E.openControlSession(o),B(null)}async function z(){const o=await In();F(b=>({...b,controlSessions:o.items}))}async function g(){if(!(!se||xe)){Zt(se.id);try{await Ol(se.session.sessionId),se.id===(I==null?void 0:I.id)&&await E.openControlSession(""),dt(null),await z(),c(),B(null),i({title:s("shell.deleteSessionSuccess"),tone:"success"})}catch(o){i({title:o instanceof Error?o.message:s("shell.deleteSessionFailed"),tone:"error"})}finally{Zt(null)}}}async function Hn(){await E.startFreshSession(),B(null),c()}async function D(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 E.sendMessage(o,{model:(b==null?void 0:b.model)??null,reasoningLevel:(b==null?void 0:b.reasoningLevel)??null,permissionMode:null}),c()}async function Ot(){const[o,b,S,C]=await Promise.all([ss(),ls(),is({limit:100}),rs({limit:100})]);await E.reloadEventsAndOverview(),F(G=>({...G,overview:o.overview,followUpTasks:b.items.filter($e=>$e.workspaceId===e),assistantAutomations:S.payload.items,assistantAutomationRuns:C.payload.items}))}async function Oe(o){qt(o.id);try{const b=await Tl(o.id);F(S=>({...S,followUpTasks:go(S.followUpTasks,b.task)})),await Ot(),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{qt(null)}}async function Qe(o){rt(o.id);try{await Nl(o.projectId,o.id),await Ot(),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){Wt(o);try{const b=await Tn(o);F(S=>({...S,controlTimers:hl(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{Wt(null)}}function Bn(o){if(_===o){be(null),Pe(null);return}const b=y.assistantAutomations.find(S=>S.id===o);b&&(be(o),Pe(yl(b)))}async function Je(){if(!de||!Le)return;let o;try{o=Mo(de,Le)}catch(b){i({title:s("shell.butlerAutomationSaveFailed"),description:b instanceof Error?b.message:void 0,tone:"error"});return}zt(de.id);try{const b=await Rl(de.id,o);F(S=>({...S,assistantAutomations:ts(S.assistantAutomations,b.payload.automation)})),be(b.payload.automation.id),Pe(yl(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{zt(null)}}async function Ue(o){ne(o);try{const b=await Nn(o);F(S=>({...S,assistantAutomations:ts(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{ne(null)}}async function _n(o){const b=o.content.trim();if(!b){i({title:s("shell.butlerControlTimerExecuteNowFailed"),tone:"error"});return}ut(o.id);try{const S=await Tn(o.id);F(C=>({...C,controlTimers:hl(C.controlTimers,S.timer)})),await E.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 Ut(o){if(o.kind==="timer"){await $n(o.timer.id);return}await Ue(o.automation.id)}async function He(o){if(o.kind==="timer"){await _n(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 Nn(o.automation.id),F(S=>({...S,assistantAutomations:ts(S.assistantAutomations,{...o.automation,status:"cancelled",nextRunAt:null,cancelledAt:new Date().toISOString(),updatedAt:new Date().toISOString()})})),await E.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=ys(o),S=(b?x.get(b):null)||Ss(o)||e;!b||!S||(B(null),l(An(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":Z??"none",children:[t.jsx(wr,{currentWorkspace:f,workspaces:r.map(o=>o.workspace),heading:s("shell.mobileButlerEntry"),triggerLabel:f.name,onSelectWorkspace:o=>{d(o),l(as(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:Ge}),t.jsx("span",{children:Cl(ue)})]})]}),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:()=>B("list"),children:"≡"}),t.jsx("button",{type:"button",className:"mobile-butler-toolbar-button","aria-label":s("shell.butlerSidebarTabsLabel"),title:s("shell.butlerSidebarTabsLabel"),onClick:()=>B("sidebar"),children:"ⓘ"})]})]})}),t.jsxs("div",{className:"mobile-butler-stage-shell",children:[Z?t.jsx("button",{type:"button",className:"mobile-butler-drawer-scrim","aria-label":s("common.close"),onClick:()=>B(null)}):null,t.jsxs("aside",{className:"mobile-butler-drawer mobile-butler-drawer-list",style:{width:`min(88vw, ${cl}px)`},onTouchStart:je,onTouchEnd:me,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:()=>{Hn()},children:"+"})]}),t.jsx("div",{className:"mobile-butler-list-body",children:t.jsx(ho,{activeControlSessionId:(I==null?void 0:I.id)??null,deletingSessionId:xe,sessions:y.controlSessions,onSelectSession:o=>{N(o)},onDeleteSession:o=>{dt(o)}})})]}),t.jsx("div",{className:"mobile-butler-main-stage",onTouchStart:pt,onTouchEnd:j,children:Mt?t.jsx("section",{className:"mobile-butler-loading-shell",children:t.jsx(_l,{})}):Ft?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(Hl,{requests:Ye,replyingRequestId:Yt,onReply:async(o,b)=>{fe(o);try{await E.replyPermissionRequest(o,b)}catch(S){i({title:s("conversation.permissionRequestReplyFailed"),description:S instanceof Error?S.message:void 0,tone:"error"})}finally{fe(null)}}}),nn?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(kl,{sessionId:(un=I==null?void 0:I.session)==null?void 0:un.sessionId,messages:Nt,historyState:Ln,loadingOlderMessages:mt,hasOlderMessages:Pn,provider:ue,onLoadOlderMessages:()=>{E.loadOlderMessages()},onRetryMessage:o=>{E.retryMessage(o)}})})]}),le?t.jsx(ro,{schedule:le,currentWorkspaceId:e,currentWorkspaceName:(f==null?void 0:f.name)??null,projectNameById:Xt,workspaceNameById:h,sessionTitleById:v,sessionWorkspaceIdById:x,countdownNow:ct,cancelling:le.kind==="timer"?ot===le.timer.id:Ee===le.automation.id,executingNow:Kt===Io(le),onCancel:()=>{Ut(le)},onExecuteNow:()=>{He(le)},onOpenSession:()=>{ln(le)}}):null,gt?t.jsx("div",{className:"mobile-butler-chat-composer","data-mobile-butler-gesture":"ignore",children:t.jsx($l,{capabilities:Tt,draftStorageId:`mobile-butler:${e}:${ue}`,panelRef:As,portalContainer:Fn,placeholder:s("shell.butlerComposerPlaceholder",{displayName:Ge}),hasActiveRun:On,canInterrupt:Un,contextUsage:Mn,isSubmitting:Ke,isRunning:tn,onInterrupt:async()=>{await E.interrupt(),c()},onSend:async(o,b)=>{await D(o,b)}})}):null]})}),t.jsx("aside",{className:"mobile-butler-drawer mobile-butler-drawer-sidebar",style:{width:`min(88vw, ${cl}px)`},onTouchStart:Ie,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:Cn.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:()=>{Dt(o)},children:S},o)})})}),t.jsx("div",{className:"mobile-page-top-body mobile-butler-body mobile-butler-sidebar-body",children:sn})]})})]}),t.jsx(Ar,{open:se!==null,title:s("shell.deleteSessionConfirmTitle"),description:s("shell.deleteSessionConfirmDescription"),height:"auto",onClose:()=>{xe||dt(null)},footer:t.jsxs("div",{className:"workbench-modal-actions",children:[t.jsx("button",{type:"button",className:"secondary-button",disabled:!!xe,onClick:()=>dt(null),children:s("common.cancel")}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!xe,onClick:()=>{g()},children:xe?s("common.loading"):s("shell.deleteSessionAction")})]}),children:t.jsx("p",{className:"mobile-butler-empty-text",children:se?to(se):""})})]}):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 ro(e){const n=u.useId(),l=u.useId(),i=u.useRef(null),r=u.useRef(null),[c,d]=u.useState(!1),f=No(e.schedule,e.countdownNow),h=Ro(e.schedule,e.countdownNow),v=yo(e.schedule,e.projectNameById,e.workspaceNameById,e.currentWorkspaceId,e.currentWorkspaceName),x=jo(e.schedule,e.sessionTitleById),A=ko(e.schedule),H=ys(e.schedule),P=!!(H&&(e.sessionWorkspaceIdById.has(H)||Ss(e.schedule))),R=To(e.schedule);return u.useEffect(()=>{if(!c)return;const $=Y=>{var te,Z;(te=i.current)!=null&&te.contains(Y.target)||(Z=r.current)!=null&&Z.contains(Y.target)||d(!1)},W=Y=>{Y.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",$),document.addEventListener("keydown",W),()=>{document.removeEventListener("pointerdown",$),document.removeEventListener("keydown",W)}},[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:v,children:v})]}),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:x,"aria-label":`${s("shell.butlerControlTimerSessionLabel")}:${x}`,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:x}):t.jsx("strong",{title:x,children:x})]})]}),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($=>!$)},children:t.jsx("span",{className:"mobile-butler-timer-detail-icon","aria-hidden":"true",children:t.jsx(Co,{})})}),t.jsx(hs,{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})]})})]}),R?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")})]}),R?t.jsx("p",{className:"mobile-butler-timer-note",children:s("shell.butlerControlTimerActionNote")}):null]})}function Re({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 ao(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:ee(n.nextRunAt)})]}),t.jsxs("div",{className:"mobile-butler-automation-metric",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskLastRunLabel")}),t.jsx("strong",{children:ee(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 oo(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=xi(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(Re,{label:s("shell.butlerAutomationTaskTypeLabel"),value:mi(e.automation.triggerType)}),t.jsx(Re,{label:s("shell.butlerAutomationStatusLabel"),value:bi(e.automation.status)}),t.jsx(Re,{label:s("shell.butlerAutomationTaskNextRunLabel"),value:ee(e.automation.nextRunAt)}),t.jsx(Re,{label:s("shell.butlerAutomationTaskLastRunLabel"),value:ee(e.automation.lastRunAt||e.automation.updatedAt)}),n?t.jsx(Re,{label:s("shell.mobileButlerAssistantWorkspaceLabel"),value:n}):null,l?t.jsx(Re,{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(uo,{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:hi(d.triggerType)})]}),t.jsx("span",{className:"mobile-butler-record-badge",children:fi(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:ee(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 uo(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 _t(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 co(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 dl(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 mo(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(_t,{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")} · ${ee(n.lastRunAt)}`}))}):null,e.runItems.length>0?t.jsx(_t,{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:ee(n.createdAt)}))}):null]})}function ho(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:ee(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 bo(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 ml(e,n){return[...e].filter(l=>n==="history"?!fl(l.status):fl(l.status)).sort((l,i)=>M(ns(i))-M(ns(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:po(l.status),content:((r=l.summary)==null?void 0:r.trim())||s("shell.butlerInfoVerificationFallback",{status:l.status}),meta:ee(ns(l)),verification:{id:l.id,projectId:l.projectId,status:l.status}}})}function fo(e){return e.map(n=>({title:n.title,content:`${n.projectName} · ${wo(n.status)}`}))}function hl(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(pl(r))-M(pl(i)))}function ts(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(Al(r))-M(Al(i)))}function go(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(we(r))-M(we(i)))}function bl(e){return e==="active"||e==="waiting_user"}function vn(e){return e==="active"||e==="waiting_user"}function fl(e){return e==="queued"||e==="running"}function gl(e){return e==="queued"||e==="running"}function po(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 pl(e){return e.dueAt||e.triggeredAt||e.cancelledAt||e.updatedAt||e.createdAt}function xo(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 vo(e){return e.content.trim()||xo(e)}function So(e,n,l,i,r){var f,h,v,x;const c=(f=e.projectId)==null?void 0:f.trim();if(c&&n.has(c))return n.get(c);const d=((x=(v=(h=e.controlSession)==null?void 0:h.session)==null?void 0:v.workspaceId)==null?void 0:x.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 yo(e,n,l,i,r){var f;if(e.kind==="timer")return So(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=Ss(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 Ao(e,n){var r,c,d,f,h,v,x;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=((x=(v=(h=e.controlSession)==null?void 0:h.session)==null?void 0:v.sessionId)==null?void 0:x.trim())||e.sessionId.trim();return i&&n.has(i)?n.get(i):s("shell.butlerControlTimerUnknownSession")}function jo(e,n){var i,r,c;if(e.kind==="timer")return Ao(e.timer,n);const l=ys(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 Co(){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 xl(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=>vi(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:gi(d),projectName:pi(d,r),status:Lo(d.status),taskTypeLabel:mi(d.triggerType),statusLabel:bi(d.status),nextRunAt:d.nextRunAt,lastRunAt:d.lastRunAt||d.updatedAt,promptPreview:Po(d.actionConfig.content),lastResultSummary:((f=d.lastRunSummary)==null?void 0:f.trim())||((h=d.lastError)==null?void 0:h.trim())||null,targetSessionTitle:xi(d)}}).sort((d,f)=>{const h=M(d.nextRunAt),v=M(f.nextRunAt);return h!==v?h===0?1:v===0?-1:h-v:M(f.lastRunAt)-M(d.lastRunAt)}).slice(0,8)}function vl(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=>vi(h,i,l)).map(h=>[h.id,h]));return n.map(h=>({run:h,automation:d.get(h.automationId),normalizedStatus:Eo(h.status)})).filter(({automation:h})=>!!h).filter(({normalizedStatus:h})=>r==="history"?!jl(h):jl(h)).map(({run:h,automation:v,normalizedStatus:x})=>{var A,H;return{id:`assistant-automation-run:${h.id}`,kind:"assistant_automation_run",title:gi(v),projectName:pi(v,c),status:x,sourceLabel:hi(h.triggerType),statusLabel:fi(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,v)=>M(v.createdAt)-M(h.createdAt)).slice(0,10)}function wo(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 we(e){return e.updatedAt||e.lastAutomationAt||e.lastCheckedAt||e.createdAt}function Io(e){return e.kind==="timer"?e.timer.id:e.automation.id}function En(e){return e.kind==="timer"?e.timer.dueAt:e.automation.nextRunAt}function Ss(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 ys(e){var n,l,i,r,c,d,f,h,v,x,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())||((v=(h=(f=e.automation.controlSession)==null?void 0:f.session)==null?void 0:h.sessionId)==null?void 0:v.trim())||((A=(x=e.automation.controlSession)==null?void 0:x.sessionId)==null?void 0:A.trim())||null}function To(e){return e.kind==="timer"||e.automation.triggerType==="once"}function No(e,n){const l=M(En(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueNow"):s("shell.butlerControlTimerCountdownActive",{duration:Ho(l-n)})}function Ro(e,n){const l=M(En(e));return!l||l<=n?"00:00":$o(l-n)}function ko(e){return e.kind==="timer"?vo(e.timer):e.automation.actionConfig.content.trim()||s("conversation.butlerAnalysisEmpty")}function Sl(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 mi(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 hi(e){return e==="interval"||e==="cron"?s("shell.butlerAutomationRunSourcePatrol"):e==="once"?s("shell.butlerAutomationRunSourceControlTimer"):s("shell.butlerAutomationRunSourceFollowUp")}function Eo(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 Lo(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 bi(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 fi(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 gi(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 pi(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 xi(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 Po(e){const n=e.replace(/\s+/g," ").trim();return n?n.length<=72?n:`${n.slice(0,72)}...`:s("conversation.butlerAnalysisEmpty")}function yl(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=Sn(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=Sn(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=Sn(e.triggerConfig.stopAt)):(n.pollIntervalSeconds=lt(e.triggerConfig.pollIntervalSeconds),n.expiresAt=Sn(e.triggerConfig.expiresAt),n.maxChecks=lt(e.triggerConfig.maxChecks)),n}function Mo(e,n){const l={title:Fo(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:Do(n.dueAt,s("shell.butlerAutomationDueAtLabel"))}:e.triggerConfig.type==="interval"?{...l,everySeconds:yn(n.everySeconds,s("shell.butlerAutomationEverySecondsLabel")),everyMinutes:yn(n.everyMinutes,s("shell.butlerAutomationEveryMinutesLabel")),everyHours:yn(n.everyHours,s("shell.butlerAutomationEveryHoursLabel")),stopAt:wn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:e.triggerConfig.type==="cron"?{...l,cronMinute:Si(n.cronMinute,s("shell.butlerAutomationCronMinuteLabel")),cronHour:yi(n.cronHour,s("shell.butlerAutomationCronHourLabel")),cronDaysOfWeek:Uo(n.cronDaysOfWeek),stopAt:wn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:{...l,pollIntervalSeconds:Oo(n.pollIntervalSeconds,s("shell.butlerAutomationPollIntervalLabel")),expiresAt:wn(n.expiresAt,s("shell.butlerAutomationExpiresAtLabel")),maxChecks:yn(n.maxChecks,s("shell.butlerAutomationMaxChecksLabel"))}}function Al(e){return e.updatedAt||e.lastRunAt||e.nextRunAt||e.createdAt}function vi(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 jl(e){return e==="active"||e==="waiting_user"}function ns(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 Fo(e){const n=e.trim();return n||null}function Sn(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 Do(e,n){const l=wn(e,n);if(!l)throw new Error(`${n}${s("shell.butlerAutomationRequiredSuffix")}`);return l}function Si(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 yi(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 yn(e,n){const l=yi(e,n);if(l===null)return null;if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Oo(e,n){const l=Si(e,n);if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Uo(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 ee(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 Ho(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 $o(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 Cl(e){switch(e){case"claude-code":return"Claude Code";case"codex":default:return"Codex"}}function nu(){const{shellMode:e}=ms();return e==="mobile"?t.jsx(io,{}):t.jsx(Hr,{})}export{nu as AdaptiveButlerPage};
1
+ var Xi=Object.defineProperty;var Gi=(e,n,l)=>n in e?Xi(e,n,{enumerable:!0,configurable:!0,writable:!0,value:l}):e[n]=l;var re=(e,n,l)=>Gi(e,typeof n!="symbol"?n+"":n,l);import{j as t,t as s,b as u}from"./index-NGxWr8Ix.js";import{h as wl,aQ as Qi,aR as Gs,Z as Ji,aS as er,aT as tr,aU as nr,a7 as U,aV as sr,aW as lr,a9 as Il,j as ss,aX as ir,r as rr,u as ms,aY as In,aZ as Qs,a_ as ar,a0 as Tl,a1 as Nl,a$ as or,b0 as ur,c as An,b1 as Tn,b2 as Nn,b3 as Rl,b4 as cr,b5 as dr,b6 as mr,b7 as hr,B as Rn,b8 as hs,ay as kl,af as El,k as Ll,l as ls,b9 as Pl,ba as is,bb as rs,bc as Ml,q as as,aH as br}from"./WorkbenchLayout-DScHaza9.js";import{e as fr,c as Fl,u as Dl,f as Ol,h as gr}from"./App-tXOqoHNl.js";import{E as pr,F as xr,H as Js,I as vr,K as Sr,s as yr,A as Ar,R as Ul,i as os,j as Hl,M as jr}from"./model-switch-api-CPtou49j.js";import{R as Cr,P as $l,C as Bl}from"./realtime-client-BjQazYsK.js";import{FileContextPanel as wr}from"./FileContextPanel-xGTYDclT.js";import{W as Ve}from"./WorkbenchModal-BWXYSXmC.js";import{s as _l}from"./butler-records-events-DgWCG364.js";import{M as Ir}from"./MobileWorkspaceSwitcherHeader-KIbqBYJN.js";import"./window-BVUB8gMK.js";import"./event-DvH9tcej.js";import"./relay-entry-BwE5nw0l.js";import"./file-tree-icon-lfU9Ag77.js";import"./MobileTopHeaderFrame-CkdnZ_MU.js";function Vl(){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 Yn=60,Tr=400,ql="butler-diagnostic://",Nr=15e3;class zl{constructor(n){re(this,"state");re(this,"listeners",new Set);re(this,"realtimeClient",null);re(this,"realtimeSessionId",null);re(this,"selectedControlSessionId",null);re(this,"controlSessionReloadInFlight",!1);re(this,"terminalSyncTimer",null);re(this,"terminalSyncArmed",!1);re(this,"terminalSyncCompletedControlSessionId",null);re(this,"pendingRunControlSession",null);re(this,"subscribe",n=>(this.listeners.add(n),()=>{this.listeners.delete(n)}));re(this,"getState",()=>this.state);this.workspaceId=n,this.state={loading:!0,sending:!1,switchingProvider:!1,initialized:!1,profile:null,activeProvider:"codex",controlSession:null,capabilities:Ct("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 wl();if(!n.initialized||!n.profile){this.clearPendingRun(),this.patch({loading:!1,initialized:!1,profile:null,activeProvider:"codex",capabilities:Ct("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:Ct(l.providerId)}),await this.reloadForProvider(l.providerId),this.patch({loading:!1})}catch(n){this.patch({loading:!1,error:pe(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:Ct(l.profile.providerId)}),await this.reloadForProvider(l.profile.providerId)}catch(l){throw this.patch({error:pe(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:Ct(n)});try{const i=await Gs({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:pe(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 Gs(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:pe(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)??Ji();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 tr({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 er({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:pe(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 pr(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 xr(i,n,l);this.patch({permissionRequests:Zn(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 nr()}catch(l){throw this.patch({historyState:"error",error:pe(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 v=await Js(l,this.state.olderCursor,Yn,"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 x=el(this.state.messages,l,v.messages);this.patch({messages:Xn(x,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:v.nextCursor,hasOlderMessages:!!v.nextCursor})}catch(v){this.patch({loadingOlderMessages:!1,error:pe(v)})}}}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 v=(n?await sr(n):await lr()).controlSession;if(!v){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=v.id;const[x,A,H]=await Promise.all([Js(v.session.sessionId,null,Yn,"backward"),vr(v.session.sessionId),Sr(v.session.sessionId)]),P=this.resolvePendingRunControlSession(v,A),R=this.resolvePendingRunRuntimeState(P,A),$=A.hasActiveRun||A.canInterrupt||Te(A.runningState)||qe(A.runningState);((f=this.state.controlSession)==null?void 0:f.id)!==v.id&&(this.terminalSyncCompletedControlSessionId=null),this.terminalSyncArmed=R.hasActiveRun||P.status==="running",$?(this.clearPendingRun(v.id),this.terminalSyncCompletedControlSessionId=null):this.terminalSyncArmed||(this.terminalSyncCompletedControlSessionId=v.id);const W=x.messages.map(Y=>Il(v.session.sessionId,Y));this.ensureRealtimeSubscription(v.session.sessionId,x.cursor),this.patch({controlSession:P,messages:Xn(W,P,{runningState:A.runningState,runtimeHasActiveRun:R.hasActiveRun,runtimeCanInterrupt:R.canInterrupt,detail:A.detail,errorDetail:A.errorDetail,updatedAt:A.updatedAt}),historyState:"ready",loadingOlderMessages:!1,olderCursor:x.nextCursor,hasOlderMessages:!!x.nextCursor,runtimeHasActiveRun:R.hasActiveRun,runtimeCanInterrupt:R.canInterrupt,contextUsage:A.contextUsage,permissionRequests:H.items}),U("butler.runtime.reload_control_session.end",{workspaceId:this.workspaceId,controlSessionId:v.id,sessionId:v.session.sessionId,messages:W.length,historyState:"ready",hasActiveRun:R.hasActiveRun,canInterrupt:R.canInterrupt,terminalSyncArmed:this.terminalSyncArmed,terminalSyncCompletedControlSessionId:this.terminalSyncCompletedControlSessionId})}catch(h){this.patch({historyState:"error",error:pe(h)}),U("butler.runtime.reload_control_session.error",{workspaceId:this.workspaceId,requestedControlSessionId:n??null,message:pe(h)})}}async refreshCapabilities(n){try{const l=await yr(n,this.workspaceId);this.patch({capabilities:l})}catch{this.patch({capabilities:Ct(n)})}}async refreshOverview(){try{const n=await ss();this.patch({overview:n.overview})}catch(n){this.patch({error:pe(n)})}}async refreshEvents(){try{const n=await ir();this.patch({events:n.items})}catch(n){this.patch({error:pe(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 Cr({sessionId:n,cursor:l,limit:Yn,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})})},Tr)}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=el(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:Zn(this.state.permissionRequests,n.request)})}handlePermissionRequestResolved(n){this.isActiveControlSession(n.sessionId)&&this.patch({permissionRequests:Zn(this.state.permissionRequests,n.request)})}patchActiveControlSessionRuntimeState(n){var v;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&&!qe(n.runningState)&&!qe(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?((v=this.state.capabilities)==null?void 0:v.supportsInterrupt)??this.state.runtimeCanInterrupt??n.canInterrupt:n.canInterrupt;r||this.clearPendingRun(l.id);const h=n.status??Er(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:Lr(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()+Nr})}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)||qe(l.runningState)||Te(n.session.runningState)||qe(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||qe(l.runningState)||qe(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)||qe(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 k(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 Ct(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 el(e,n,l){const i=new Map;for(const r of e.filter(c=>!Wl(c)))i.set(tl(r),r);for(const r of l){const c=Il(n,r);i.set(tl(c),c)}return[...i.values()].sort((r,c)=>r.sequence!==c.sequence?r.sequence-c.sequence:r.timestamp.localeCompare(c.timestamp))}function tl(e){return e.id||e.rawRef}function Zn(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=>!Wl(c));if(i.length>0||!n)return i;const r=Rr(n,l);return r?[...i,kr(n,r,l.updatedAt)]:i}function Rr(e,n){var f,h,v;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())||((v=n.detail)==null?void 0:v.trim())||null,d=[i?"本轮助手会话已结束,但没有收到可展示的助手消息。":"本轮助手会话已结束,但 provider 没有返回可展示的助手消息。"];return c&&(d.push(""),d.push(`诊断信息:${c}`)),d.join(`
2
+ `)}function kr(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:`${ql}${e.id}`,deliveryState:"sent",clientRequestId:null}}function Wl(e){return e.rawRef.startsWith(ql)}function pe(e){return e instanceof Error?e.message:String(e)}function Er(e,n,l){return l||n==="starting"||n==="running"||n==="reconnecting"?"running":n==="failed"?"failed":e==="closed"?"closed":"idle"}function Lr(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 qe(e){return e==="completed"||e==="failed"||e==="interrupted"}const us={"risk-first":["risk","blocker","verification"],"blocker-first":["blocker","risk","verification"],"verification-first":["verification","risk","blocker"],"progress-first":["progress","risk","blocker"]},Kl=300,Pr=1500,Mr=1500,Fr=480*60*1e3,cs=["codex","claude-code"],Dr={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:Kl},Or=[{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"}],Ne={builder:["🧠","🤖","🦾","🛠️","⚙️","🧩","🚀","🛰️","🔧","💡"],analyst:["🦉","🧭","🔍","📚","🧪","📐","🗂️","📝","🧮","📊"],direct:["🦅","🛡️","⚡","🎯","🪓","🧱","🔨","📌","🧰","🏹"],steady:["🐢","🐘","🦬","🦫","🌲","⛰️","🪨","🧺","🧷","🕰️"],friendly:["🐼","🦊","🐻","🐶","🐱","🐹","🐰","🦄","🌼","🍀"],default:["🧠","🤖","🦉","🧩","📚","💡","🛠️","🚀","🌟","🪄","🧭","🔮"]};function Ur(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 Hr(e){var n;if(typeof navigator<"u"&&((n=navigator.clipboard)!=null&&n.writeText))try{await navigator.clipboard.writeText(e);return}catch{}if(!Ur(e))throw new Error(s("conversation.copyContentFailed"))}function $r(){var _s,Vs,qs,zs,Ws,Ks,Ys,Zs,Xs;const e=fr(),n=rr(e),{workspaceId:l=""}=Fl(),i=Dl(),{showToast:r}=Ol(),{navigationGroups:c,requestNavigationRefresh:d,setAuxiliaryPanel:f}=ms(),h=u.useRef(null),v=u.useRef(null),[x,A]=u.useState(Dr),[H,P]=u.useState(!1),[R,$]=u.useState(Gn),[W,Y]=u.useState(!1),[te,Z]=u.useState(0),[B,oe]=u.useState([]),[q,We]=u.useState([]),[As,ke]=u.useState([]),[qt,he]=u.useState([]),[rt,Ee]=u.useState([]),[ne,_]=u.useState([]),[be,Le]=u.useState([]),[Pe,at]=u.useState(!1),[zt,ot]=u.useState(!1),[Wt,Kt]=u.useState(!1),[ut,Yt]=u.useState(!1),[fe,ct]=u.useState(null),[Me,se]=u.useState(null),[dt,xe]=u.useState(null),[Zt,y]=u.useState(null),[F,Xt]=u.useState(!1),[E,It]=u.useState(""),[ve,X]=u.useState(null),[ue,I]=u.useState(null),[Tt,Nt]=u.useState(!1),[Ln,mt]=u.useState(!1),[Pn,Ke]=u.useState(null),[Se,ht]=u.useState(null),[Mn,Ye]=u.useState(!1),[Fn,bt]=u.useState(null),[ge,ce]=u.useState([]),[ye,V]=u.useState([]),[Rt,kt]=u.useState(!1),[Ze,Gt]=u.useState(!1),[Ae,Fe]=u.useState(null),[Qt,De]=u.useState(null),[Et,de]=u.useState(null),[Lt,Jt]=u.useState(null),[Pt,en]=u.useState(null),[Dn,Xe]=u.useState(null),[On,tn]=u.useState(null),[Un,ft]=u.useState(null),[le,Mt]=u.useState(()=>Date.now()),{items:Ft}=Ar(!0),Ge=u.useRef(null),nn=u.useRef(null),gt=u.useRef(null),sn=u.useId(),[Dt,pt]=u.useState({itemId:null,kind:null});(!h.current||v.current!==l)&&(h.current=new zl(l),v.current=l);const j=h.current,je=k(j,a=>a.loading),me=k(j,a=>a.sending),Ie=k(j,a=>a.switchingProvider),K=k(j,a=>a.initialized),N=k(j,a=>a.profile),z=k(j,a=>a.activeProvider),g=k(j,a=>a.controlSession),Hn=k(j,a=>a.capabilities),D=k(j,a=>a.overview),Ot=k(j,a=>a.events),Oe=k(j,a=>a.messages),Qe=k(j,a=>a.historyState),$n=k(j,a=>a.loadingOlderMessages),Bn=k(j,a=>a.hasOlderMessages),Je=k(j,a=>a.runtimeHasActiveRun),Ue=k(j,a=>a.runtimeCanInterrupt),_n=k(j,a=>a.contextUsage),Ut=k(j,a=>a.permissionRequests),He=k(j,a=>a.error),ln=u.useRef(null),Ht=u.useRef(null),xt=u.useRef(!1),vt=u.useRef(new Set),Ce=((_s=N==null?void 0:N.displayName)==null?void 0:_s.trim())||x.displayName.trim()||s("shell.butlerEntry"),St=u.useMemo(()=>Va({displayName:Ce,providerId:(N==null?void 0:N.providerId)??x.providerId,tone:(N==null?void 0:N.persona.tone)??x.personaTone}),[Ce,x.personaTone,x.providerId,N==null?void 0:N.persona.tone,N==null?void 0:N.providerId]),$t=u.useMemo(()=>q.filter(a=>ds(a.status)).slice(0,3),[q]),rn=u.useMemo(()=>na(g,Je),[g,Je]),et=ta((g==null?void 0:g.session.sessionId)??null,rn),an=et||me,on=et||me,un=Ue===!0||me?!0:Ue??!1,o=u.useMemo(()=>{if(!g||et)return null;const a=rt.filter(T=>T.status==="active"&&T.controlSessionId===g.id).map(T=>({kind:"timer",timer:T})),m=new Set(rt.filter(T=>T.status==="active"&&T.controlSessionId===g.id).map(T=>T.id)),p=ne.filter(T=>T.status==="active"&&T.controlSessionId===g.id&&!!T.nextRunAt&&!m.has(T.id)).map(T=>({kind:"automation",automation:T}));return[...a,...p].sort((T,O)=>w(Vt(T))-w(Vt(O)))[0]??null},[ne,g,rt,et]),b=ea(o),S=u.useMemo(()=>((D==null?void 0:D.projects)??[]).map(a=>a.id).sort(),[D==null?void 0:D.projects]),C=((Vs=c.find(a=>a.workspace.id===l))==null?void 0:Vs.workspace.name)??null,G=u.useMemo(()=>new Map(((D==null?void 0:D.projects)??[]).map(a=>[a.id,a.name])),[D==null?void 0:D.projects]),$e=u.useMemo(()=>new Map(c.map(a=>[a.workspace.id,a.workspace.name])),[c]),Q=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]),L=u.useMemo(()=>fe?ne.find(a=>a.id===fe)??null:null,[ne,fe]),yt=u.useMemo(()=>fe?be.filter(a=>a.automationId===fe).sort((a,m)=>w(m.createdAt)-w(a.createdAt)).slice(0,8):[],[be,fe]);u.useEffect(()=>{fe&&!L&&(ct(null),se(null))},[L,fe]);const ie=u.useMemo(()=>new Map(c.flatMap(a=>a.sessions.map(m=>[m.sessionId,a.workspace.id]))),[c]),Vn=u.useMemo(()=>ge.find(a=>a.id===Ae)??ye.find(a=>a.id===Ae)??null,[ye,ge,Ae]);u.useEffect(()=>{var p,T;if(!Ae)return;const a=ge.some(O=>O.id===Ae),m=ye.some(O=>O.id===Ae);a||m||Fe(((p=ge[0])==null?void 0:p.id)??((T=ye[0])==null?void 0:T.id)??null)},[ye,ge,Ae]),u.useEffect(()=>{if(Mt(Date.now()),!b)return;const a=window.setInterval(()=>{Mt(Date.now())},1e3);return()=>{window.clearInterval(a)}},[b]);const At=u.useCallback(async()=>{if(!K){he([]);return}try{const a=await In();he(a.items)}catch(a){r({title:s("shell.butlerSidebarLoadFailed"),description:a instanceof Error?a.message:void 0,tone:"error"})}},[K,r]),tt=u.useCallback(async()=>{if(!K){ce([]),Fe(null);return}if(!(g!=null&&g.id)){ce([]),Fe(null);return}kt(!0);try{const a=await Qs({controlSessionId:(g==null?void 0:g.id)??null});ce(a.payload.items),Fe(m=>{var p;return a.payload.items.length?a.payload.items.some(T=>T.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{kt(!1)}},[g==null?void 0:g.id,K,r]),Bt=u.useCallback(async()=>{if(!K){V([]);return}Gt(!0);try{const a=await Qs();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{Gt(!1)}},[K,r]),cn=u.useCallback(()=>{ot(!0)},[]),dn=u.useCallback(()=>{Kt(!0)},[]),J=u.useCallback(()=>{Yt(!0)},[]),ji=u.useCallback(()=>{F||At(),Xt(a=>!a)},[F,At]),Be=u.useCallback(()=>{Xt(!1),It("")},[]),Ci=u.useCallback(async()=>{if(!(!ve||ue)){I(ve.id);try{await Ul(ve.session.sessionId),ve.id===(g==null?void 0:g.id)&&await j.openControlSession(""),Be(),X(null),await At(),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,ve,ue,Be,At,d,r,j]),js=u.useCallback(()=>{Nt(!0),tt()},[tt]),wi=u.useCallback(()=>{mt(!0),Bt()},[Bt]);u.useEffect(()=>{if(!F){It("");return}const a=window.requestAnimationFrame(()=>{var m,p;(m=gt.current)==null||m.focus(),(p=gt.current)==null||p.select()});return()=>{window.cancelAnimationFrame(a)}},[F]),u.useEffect(()=>{if(!F)return;const a=p=>{var O,nt;const T=p.target;(O=Ge.current)!=null&&O.contains(T)||(nt=nn.current)!=null&&nt.contains(T)||Be()},m=p=>{p.key==="Escape"&&(p.preventDefault(),Be())};return document.addEventListener("pointerdown",a),document.addEventListener("keydown",m),()=>{document.removeEventListener("pointerdown",a),document.removeEventListener("keydown",m)}},[F,Be]),u.useEffect(()=>{Tt&&tt()},[g==null?void 0:g.id,tt,Tt]);const Cs=u.useCallback(a=>{$(m=>({...m,...a}))},[]),qn=u.useCallback(async a=>{ot(!1),Ke(a),ht(null),bt(null),Ye(!0);try{const m=await ar(a);ht(m.task)}catch(m){bt(m instanceof Error?m.message:s("shell.butlerAutomationRoundLoadFailed"))}finally{Ye(!1)}},[]),zn=u.useCallback(async a=>{de(a.id);try{const m=await Tl(a.id);We(p=>ll(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{de(null)}},[d,r,j]),Wn=u.useCallback(async a=>{Jt(a.id);try{await Nl(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{Jt(null)}},[d,r,j]),ws=u.useCallback(async a=>{pt({itemId:a.id,kind:"analyze"});try{const m=await or(a.id);oe(p=>sl(p,m.item)),he(p=>xa(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{pt({itemId:null,kind:null})}},[r]),Is=u.useCallback(async a=>{pt({itemId:a.id,kind:"start"});try{const m=await ur(a.id);oe(p=>sl(p,m.item)),m.followUpTask&&We(p=>ll(p,m.followUpTask)),d(),r({title:s("shell.butlerTodoStartSessionSucceeded"),tone:"success"}),i(An(m.item.workspaceId,m.session.sessionId))}catch(m){r({title:s("shell.butlerTodoStartSessionFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}finally{pt({itemId:null,kind:null})}},[i,d,r]),Ts=u.useCallback(a=>{var p;const m=(p=a.assistantState.linkedSessionId)==null?void 0:p.trim();m&&i(An(a.workspaceId,m))},[i]),Ns=u.useCallback(async a=>{var p;const m=(p=a.assistantState.generatedPrompt)==null?void 0:p.trim();if(m)try{await Hr(m),r({title:s("shell.butlerTodoCopyPromptSucceeded"),tone:"success"})}catch(T){r({title:T instanceof Error?T.message:s("conversation.copyContentFailed"),tone:"error"})}},[r]),mn=u.useCallback(async a=>{tn(a);try{const m=await Tn(a);Ee(p=>il(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{tn(null)}},[r]),hn=u.useCallback(async a=>{en(a);try{const m=await Nn(a);_(p=>xn(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{en(null)}},[r]),Rs=u.useCallback(a=>{const m=ne.find(p=>p.id===a);m&&(ct(a),se(ol(m)))},[ne]),Ii=u.useCallback(async()=>{if(!L||!Me)return;let a;try{a=_a(L,Me)}catch(m){r({title:s("shell.butlerAutomationSaveFailed"),description:m instanceof Error?m.message:void 0,tone:"error"});return}xe(L.id);try{const m=await Rl(L.id,a);_(p=>xn(p,m.payload.automation)),ct(m.payload.automation.id),se(ol(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{xe(null)}},[Me,L,r]),Ti=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 Tn(a.id);Ee(T=>il(T,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]),ks=u.useCallback(async a=>{Xe(a);try{const m=await cr(a);_(p=>xn(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{Xe(null)}},[r]),Ni=u.useCallback(async a=>{if(a.kind==="timer"){await mn(a.timer.id);return}await hn(a.automation.id)},[hn,mn]),Ri=u.useCallback(async a=>{if(a.kind==="timer"){await mn(a.timer.id);return}await ks(a.automation.id)},[mn,ks]),ki=u.useCallback(async a=>{if(a.kind==="timer"){await Ti(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 Nn(a.automation.id),_(p=>xn(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]),Ei=u.useCallback(a=>{const m=kn(a),p=(m?ie.get(m):null)||bs(a)||l;!m||!p||i(An(p,m))},[i,ie,l]),Li=u.useCallback(async a=>{De(a);try{const m=await dr({sandboxId:a,mode:"project",defaultProvider:z});ce(p=>wt(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>wt(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{De(null)}},[z,g==null?void 0:g.id,d,r]),Pi=u.useCallback(async a=>{De(a);try{const m=await mr(a);ce(p=>wt(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>wt(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{De(null)}},[g==null?void 0:g.id,r]),Es=u.useCallback(async a=>{De(a);try{const m=await hr(a);ce(p=>wt(p,m.payload.sandbox,(g==null?void 0:g.id)??null)),V(p=>wt(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{De(null)}},[g==null?void 0:g.id,d,r]),Ls=u.useCallback(async()=>{if(N){if(!R.displayName.trim()){r({title:s("shell.butlerInitNameRequired"),tone:"warning"});return}Y(!0);try{await j.updateProfile({displayName:R.displayName.trim(),agentsMode:R.agentsMode,agentsFilePath:R.agentsMode==="file"?R.agentsFilePath:null,agentsContent:R.agentsContent,persona:{tone:R.personaTone,language:R.personaLanguage,summaryStyle:R.personaSummaryStyle},focus:{...N.focus,riskPreference:R.focusRiskPreference,reportPriority:us[R.reportPriorityPreset],summaryDebounceSeconds:R.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{Y(!1)}}},[N,R,r,j]);u.useEffect(()=>{j.initialize()},[j]),u.useEffect(()=>{var m,p;const a=JSON.stringify({workspaceId:l,activeProvider:z,controlSessionId:(g==null?void 0:g.id)??null,sessionId:((m=g==null?void 0:g.session)==null?void 0:m.sessionId)??null,messages:Oe.length,historyState:Qe,runtimeHasActiveRun:Je,runtimeCanInterrupt:Ue,loading:je,sending:me,switchingProvider:Ie,error:He});ln.current!==a&&(ln.current=a,U("butler.page.timeline_state",{workspaceId:l,activeProvider:z,controlSessionId:(g==null?void 0:g.id)??null,sessionId:((p=g==null?void 0:g.session)==null?void 0:p.sessionId)??null,messages:Oe.length,historyState:Qe,runtimeHasActiveRun:Je,runtimeCanInterrupt:Ue,loading:je,sending:me,switchingProvider:Ie,error:He??null}))},[l,z,g==null?void 0:g.id,(qs=g==null?void 0:g.session)==null?void 0:qs.sessionId,Oe.length,Qe,Je,Ue,je,me,Ie,He]),u.useEffect(()=>{He&&r({title:s("shell.butlerLoadFailed"),description:He,tone:"error"})},[He,r]),u.useEffect(()=>{var T;const a=((T=g==null?void 0:g.session)==null?void 0:T.sessionId)??null;if(Ht.current!==a&&(Ht.current=a,xt.current=!1,vt.current=new Set),!a)return;const m=Ut.filter(O=>O.status==="pending"),p=new Set(m.map(O=>O.id));xt.current&&m.forEach(O=>{var nt,bn,fn;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())||((fn=(bn=g==null?void 0:g.session)==null?void 0:bn.title)==null?void 0:fn.trim())||Ce,requestTitle:O.title}),tone:"warning",durationMs:8e3})}),vt.current=p,xt.current=!0},[Ce,(zs=g==null?void 0:g.session)==null?void 0:zs.sessionId,(Ws=g==null?void 0:g.session)==null?void 0:Ws.title,g==null?void 0:g.title,Ut,r]),u.useEffect(()=>{if(!N){$(Gn);return}$({displayName:N.displayName,agentsMode:N.agentsMode,agentsFilePath:Oa(N),agentsContent:N.agentsContent,personaTone:N.persona.tone,personaLanguage:N.persona.language,personaSummaryStyle:N.persona.summaryStyle,focusRiskPreference:N.focus.riskPreference,reportPriorityPreset:Da(N.focus.reportPriority),summaryDebounceSeconds:N.focus.summaryDebounceSeconds??Gn.summaryDebounceSeconds})},[N]),u.useEffect(()=>{if(!K){oe([]),We([]),ke([]),he([]),Ee([]),_([]),Le([]),ce([]);return}let a=!1;async function m(){try{const[O,nt,bn,fn,Ki,Yi,Zi]=await Promise.all([Ll(),ls(),In(),Pl(),is({limit:100}),rs({limit:100}),Promise.all(S.map(Kn=>Ml(Kn)))]);a||(oe(O.items),We(nt.items),he(bn.items),Ee(fn.items),_(Ki.payload.items),Le(Yi.payload.items),ke(Zi.flatMap(Kn=>Kn.items)))}catch(O){if(a)return;oe([]),We([]),ke([]),he([]),Ee([]),_([]),Le([]),ce([]),r({title:s("shell.butlerSidebarLoadFailed"),description:O instanceof Error?O.message:void 0,tone:"error"})}}m();function p(){m()}const T=window.setInterval(()=>{m()},15e3);return window.addEventListener(Rn,p),()=>{a=!0,window.clearInterval(T),window.removeEventListener(Rn,p)}},[K,S,r]),u.useEffect(()=>_l(()=>{j.reloadEventsAndOverview()}),[j]);const _e=u.useMemo(()=>za(Ft,[x.providerId,(N==null?void 0:N.providerId)??null,z]),[z,x.providerId,N==null?void 0:N.providerId,Ft]),jt=u.useMemo(()=>_e.filter(a=>a.enabled),[_e]),Mi=((Ks=_e.find(a=>a.value===z))==null?void 0:Ks.enabled)??!0,Fi=_e.some(a=>a.enabled&&a.value!==z);u.useEffect(()=>{K||jt.length===0||jt.some(a=>a.value===x.providerId)||A(a=>{var m;return{...a,providerId:((m=jt[0])==null?void 0:m.value)??a.providerId}})},[jt,x.providerId,K]);const Ps=u.useMemo(()=>[{value:"inline",label:s("shell.butlerAgentsModeInline")},{value:"file",label:s("shell.butlerAgentsModeFile")}],[]),Ms=u.useMemo(()=>[{value:"direct",label:s("shell.butlerToneDirect")},{value:"steady",label:s("shell.butlerToneSteady")},{value:"friendly",label:s("shell.butlerToneFriendly")}],[]),Fs=u.useMemo(()=>[{value:"zh-CN",label:s("shell.butlerLanguageZhCn")},{value:"en-US",label:s("shell.butlerLanguageEnUs")},{value:"bilingual",label:s("shell.butlerLanguageBilingual")}],[]),Ds=u.useMemo(()=>[{value:"brief",label:s("shell.butlerSummaryBrief")},{value:"structured",label:s("shell.butlerSummaryStructured")},{value:"thorough",label:s("shell.butlerSummaryThorough")}],[]),Os=u.useMemo(()=>[{value:"conservative",label:s("shell.butlerRiskConservative")},{value:"balanced",label:s("shell.butlerRiskBalanced")},{value:"proactive",label:s("shell.butlerRiskProactive")}],[]),Us=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")}],[]),Di=ze(_e,x.providerId),Hs=ze(Ps,x.agentsMode),Oi=ze(Ms,x.personaTone),Ui=ze(Fs,x.personaLanguage),Hi=ze(Ds,x.personaSummaryStyle),$i=ze(Os,x.focusRiskPreference),Bi=ze(Us,x.reportPriorityPreset),_i=x.agentsMode==="inline"?s("shell.butlerAgentsModeInlineDescription"):s("shell.butlerAgentsModeFileDescription"),Vi=[Hs,Ui,$i],$s=u.useMemo(()=>t.jsx(Br,{overview:D,events:Ot,inboxItems:B,followUpTasks:q,assistantAutomations:ne,assistantAutomationRuns:be,cancellingFollowUpTaskId:Et,cancellingVerificationId:Lt,cancellingAutomationId:Pt,controlSession:g,sandboxes:ge,settingsForm:R,savingSettings:W,onOpenSandboxManager:js,onOpenFollowUpHistory:cn,onOpenVerificationHistory:dn,onOpenAutomationHistory:J,onOpenAutomationDetail:Rs,onOpenFollowUpDetail:qn,onCancelFollowUpTask:zn,onCancelVerificationRun:Wn,onCancelAutomation:hn,onAnalyzeTodo:ws,onStartTodoSession:Is,onOpenTodoSession:Ts,onCopyTodoPrompt:Ns,todoActionState:Dt,onSettingsFormChange:Cs,onSaveSettings:()=>{Ls()}}),[Ot,ws,hn,js,Ns,J,Rs,cn,dn,q,qn,Ts,Ls,Cs,Is,ne,be,ge,B,Pt,Et,Lt,g,D,zn,Wn,W,R,Dt]);u.useEffect(()=>{if(!K){f(null);return}return f($s),()=>{f(null)}},[K,f,$s]);async function qi(a){a.preventDefault();const m=x.displayName.trim();if(!m){r({title:s("shell.butlerInitNameRequired"),tone:"warning"});return}const p={displayName:m,providerId:x.providerId,agentsMode:x.agentsMode,persona:{tone:x.personaTone,language:x.personaLanguage,summaryStyle:x.personaSummaryStyle},focus:{projectIds:[],riskPreference:x.focusRiskPreference,reportPriority:us[x.reportPriorityPreset],summaryDebounceSeconds:Kl}};P(!0);try{await j.initializeProfile(p),r({title:s("shell.butlerInitSuccess"),tone:"success"})}catch(T){r({title:s("shell.butlerInitFailed"),description:T instanceof Error?T.message:void 0,tone:"error"})}finally{P(!1)}}async function zi(a){if(a!==z)try{await j.switchProvider(a),Bs(a),r({title:s("shell.butlerProviderSwitched"),description:s("shell.butlerProviderSwitchedDescription",{provider:ze(_e,a)}),tone:"success"})}catch(m){r({title:s("shell.butlerProviderSwitchFailed"),description:m instanceof Error?m.message:void 0,tone:"error"})}}async function Wi(){try{Bs(z),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 Bs(a){Z(m=>m+1),i(as(l),{replace:!0}),a&&d()}return je&&!K&&!H?t.jsx("main",{className:"workbench-page butler-page-shell butler-loading-shell",children:t.jsx(Vl,{})}):K?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:Ce})}),Pe?t.jsxs("div",{className:"butler-header-analysis-popover",role:"status","aria-live":"polite",children:[t.jsx("strong",{children:s("conversation.butlerAnalysisTitle")}),$t.length>0?$t.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"),":",gs(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:z,disabled:!Fi||Ie||me,onChange:a=>{zi(a.target.value)},children:_e.map(a=>t.jsx("option",{value:a.value,disabled:!a.enabled,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:je||me||Ie||!Mi,onClick:()=>{Wi()},children:t.jsx("span",{className:"terminal-toolbar-icon","aria-hidden":"true",children:t.jsx(Ka,{})})}),t.jsxs("div",{className:"butler-session-history-anchor",ref:Ge,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:je||me||Ie,onClick:()=>{ji()},children:t.jsx("span",{className:"terminal-toolbar-icon butler-history-toolbar-icon","aria-hidden":"true",children:t.jsx(Ya,{})})}),t.jsx(hs,{open:F,id:"butler-control-history-popover",className:"butler-session-history-popover",anchorRef:Ge,popoverRef:nn,labelledBy:sn,maxWidth:420,gap:10,viewportPadding:14,children:t.jsx(Wr,{sessions:qt,activeControlSessionId:(g==null?void 0:g.id)??null,labelId:sn,query:E,searchInputRef:gt,onQueryChange:It,deletingSessionId:ue,onSelectSession:async a=>{if(a.id===(g==null?void 0:g.id)){Be();return}await j.openControlSession(a.id),Be()},onDeleteSession:a=>{Be(),X(a)}})})]})]})]}),t.jsx("section",{className:"butler-main-column",children:t.jsxs("div",{className:"butler-conversation-shell",children:[t.jsx($l,{requests:Ut,replyingRequestId:Zt,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(kl,{sessionId:(Ys=g==null?void 0:g.session)==null?void 0:Ys.sessionId,items:El({messages:Oe}),historyState:Qe,loadingOlderMessages:$n,hasOlderMessages:Bn,provider:z,assistantAvatar:t.jsx("span",{className:"butler-message-avatar","aria-hidden":"true",children:St}),onLoadOlderMessages:()=>{j.loadOlderMessages()},onRetryMessage:a=>{const m=Oe.find(p=>p.clientRequestId===a);if(m!=null&&m.content.trim()){j.sendMessage(m.content);return}j.retryMessage(a)}}),b?t.jsx(Jr,{schedule:b,currentWorkspaceId:l,currentWorkspaceName:C,projectNameById:G,workspaceNameById:$e,sessionTitleById:Q,sessionWorkspaceIdById:ie,countdownNow:le,cancelling:b.kind==="timer"?On===b.timer.id:Pt===b.automation.id,skippingWait:b.kind==="automation"&&Dn===b.automation.id,executingNow:Un===oa(b),onCancel:()=>{Ni(b)},onSkipWait:()=>{Ri(b)},onExecuteNow:()=>{ki(b)},onOpenSession:()=>{Ei(b)}}):null,t.jsx("div",{className:"butler-composer-shell",children:t.jsx(Bl,{capabilities:Hn,draftStorageId:`butler:${z}:${te}`,placeholder:s("shell.butlerComposerPlaceholder",{displayName:Ce}),hasActiveRun:an,canInterrupt:un,contextUsage:_n,isSubmitting:me||Ie,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:${z}:${te}`)})]}),t.jsxs(Ve,{open:ve!==null,title:s("shell.deleteSessionConfirmTitle"),description:s("shell.deleteSessionConfirmDescription"),onClose:()=>{ue||X(null)},children:[t.jsx("p",{className:"workbench-section-empty",children:ve?Zl(ve):""}),t.jsxs("div",{className:"workbench-modal-actions",children:[t.jsx("button",{type:"button",className:"secondary-button",disabled:!!ue,onClick:()=>X(null),children:s("common.cancel")}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!ue,onClick:()=>{Ci()},children:ue?s("common.loading"):s("shell.deleteSessionAction")})]})]}),t.jsx(Ve,{open:zt,title:s("shell.butlerFollowUpHistoryTitle"),description:s("shell.butlerFollowUpHistoryDescription"),onClose:()=>{ot(!1)},children:t.jsx(Qr,{tasks:q.filter(a=>!ds(a.status)),cancellingTaskId:Et,onOpenFollowUpDetail:qn,onCancelFollowUpTask:zn,onClose:()=>{ot(!1)}})}),t.jsx(Ve,{open:Wt,title:s("shell.butlerVerificationHistoryTitle"),description:s("shell.butlerVerificationHistoryDescription"),onClose:()=>{Kt(!1)},children:t.jsx(ga,{items:Jl((D==null?void 0:D.verifications)??[],"history"),cancellingVerificationId:Lt,onCancelVerificationRun:Wn})}),t.jsx(Ve,{open:ut,title:s("shell.butlerAutomationHistoryTitle"),description:s("shell.butlerAutomationHistoryDescription"),onClose:()=>{Yt(!1)},children:t.jsx(pa,{taskItems:Gl(ne,D,"history"),runItems:Ql(ne,be,D,"history")})}),t.jsx(Ve,{open:L!==null,title:s("shell.butlerAutomationDetailTitle"),description:((Zs=L==null?void 0:L.title)==null?void 0:Zs.trim())||(L==null?void 0:L.actionConfig.content.trim())||s("shell.butlerAutomationDetailDescription"),className:"butler-automation-detail-modal",onClose:()=>{ct(null),se(null),xe(null)},children:L&&Me?t.jsx(ia,{automation:L,editorState:Me,saving:dt===L.id,projectName:ps(L,G),targetSessionTitle:Ba(L,Q),recentRuns:yt,onEditorChange:a=>{se(m=>m&&{...m,...a})},onSave:()=>{Ii()}}):null}),t.jsx(Ve,{open:Tt,title:s("shell.butlerSandboxManagerTitle"),description:s("shell.butlerSandboxManagerDescription"),headerActions:t.jsx("button",{type:"button",className:"secondary-button",onClick:()=>{wi()},children:s("shell.butlerSandboxBrowseAllAction")}),onClose:()=>{mt(!1),Nt(!1)},children:t.jsx(Zr,{items:ge,selectedSandbox:Vn,loading:Rt,actionSandboxId:Qt,onSelectSandbox:Fe,onReload:tt,onPromoteSandboxToProject:Li,onExpireSandbox:Pi,onRemoveSandbox:Es})}),t.jsx(Ve,{open:Ln,title:s("shell.butlerSandboxLibraryTitle"),description:s("shell.butlerSandboxLibraryDescription"),layout:"list",headerActions:t.jsx("button",{type:"button",className:"secondary-button",disabled:Ze,onClick:()=>{Bt()},children:s("shell.butlerRefreshAction")}),onClose:()=>{mt(!1)},children:t.jsx(Xr,{items:ye,loading:Ze,actionSandboxId:Qt,selectedSandboxId:Ae,onViewSandbox:a=>{Fe(a),mt(!1)},onRemoveSandbox:Es})}),t.jsx(Ve,{open:Pn!==null,title:s("shell.butlerAutomationRoundDetailsTitle"),description:((Xs=Se==null?void 0:Se.sessionTitle)==null?void 0:Xs.trim())||(Se==null?void 0:Se.projectName)||s("shell.butlerAutomationRoundDetailsDescription"),onClose:()=>{Ke(null),ht(null),bt(null),Ye(!1)},children:t.jsx(fa,{task:Se,loading:Mn,error:Fn})})]}):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:Ce})]}),t.jsx("span",{className:"butler-init-preview-provider",children:Di})]}),t.jsx("div",{className:"butler-init-chip-list",children:Vi.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:Oi})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerInitPreviewRuleLabel")}),t.jsx("strong",{children:Hs})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerPersonaSummaryStyleLabel")}),t.jsx("strong",{children:Hi})]}),t.jsxs("div",{className:"butler-init-preview-row",children:[t.jsx("span",{children:s("shell.butlerReportPriorityPresetLabel")}),t.jsx("strong",{children:Bi})]})]})]})]}),t.jsxs("form",{className:"butler-init-form",onSubmit:qi,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:x.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:x.providerId,disabled:jt.length<=1,onChange:a=>A(m=>({...m,providerId:a.target.value})),children:_e.map(a=>t.jsx("option",{value:a.value,disabled:!a.enabled,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:x.agentsMode,onChange:a=>A(m=>({...m,agentsMode:a.target.value})),children:Ps.map(a=>t.jsx("option",{value:a.value,children:a.label},a.value))}),t.jsx("small",{children:_i})]})]})]}),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:x.personaTone,onChange:a=>A(m=>({...m,personaTone: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.butlerPersonaLanguageLabel")}),t.jsx("select",{className:"butler-form-control",value:x.personaLanguage,onChange:a=>A(m=>({...m,personaLanguage:a.target.value})),children:Fs.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:x.personaSummaryStyle,onChange:a=>A(m=>({...m,personaSummaryStyle:a.target.value})),children:Ds.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:x.focusRiskPreference,onChange:a=>A(m=>({...m,focusRiskPreference:a.target.value})),children:Os.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:x.reportPriorityPreset,onChange:a=>A(m=>({...m,reportPriorityPreset:a.target.value})),children:Us.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:je||H||jt.length===0,children:je||H?s("shell.butlerInitSubmitting"):s("shell.butlerInitSubmit")})})]})]})]})}function Br(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(_r,{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(qr,{overview:e.overview,automations:e.assistantAutomations,runs:e.assistantAutomationRuns,cancellingAutomationId:e.cancellingAutomationId,onOpenAutomationHistory:e.onOpenAutomationHistory,onOpenAutomationDetail:e.onOpenAutomationDetail,onCancelAutomation:e.onCancelAutomation}):t.jsx(aa,{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 _r(e){var r;const n=u.useMemo(()=>e.followUpTasks.filter(c=>ds(c.status)),[e.followUpTasks]),l=u.useMemo(()=>{var c;return Jl(((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(Vr,{sandboxes:e.sandboxes,onOpenSandboxManager:e.onOpenSandboxManager}),t.jsx(Gr,{tasks:n,cancellingTaskId:e.cancellingFollowUpTaskId,onOpenFollowUpHistory:e.onOpenFollowUpHistory,onOpenFollowUpDetail:e.onOpenFollowUpDetail,onCancelFollowUpTask:e.onCancelFollowUpTask}),t.jsx(Yl,{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(zr,{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 Vr(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 qr(e){const n=u.useMemo(()=>Gl(e.automations,e.overview,"active"),[e.automations,e.overview]),l=u.useMemo(()=>Ql(e.automations,e.runs,e.overview,"active"),[e.automations,e.overview,e.runs]);return t.jsxs(t.Fragment,{children:[t.jsx(sa,{items:n,cancellingAutomationId:e.cancellingAutomationId,onCancelAutomation:e.onCancelAutomation,onOpenAutomationDetail:e.onOpenAutomationDetail,emptyText:s("shell.butlerAutomationTasksEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:e.onOpenAutomationHistory}),t.jsx(la,{items:l,emptyText:s("shell.butlerAutomationRunsEmpty"),onOpenAutomationDetail:e.onOpenAutomationDetail})]})}function Yl(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?ka(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||!Na(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 zr(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:Ua(n.status)}),t.jsx("span",{className:"butler-inline-badge",children:Ea(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 Wr(e){const n=u.useDeferredValue(e.query),l=u.useMemo(()=>{const d=n.trim().toLowerCase();return e.sessions.map(f=>{const h=Zl(f),v=Kr(f,h),x=w(f.updatedAt),A=[h,v,f.sessionId].join(`
3
+ `).toLowerCase();return{session:f,title:h,preview:v,updatedAtMs:x,active:x>0&&Date.now()-x<=Fr,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(Yr,{})}),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(os,{compact:!0,className:"butler-session-history-section-list",role:"list",children:i.map(d=>t.jsx(nl,{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(os,{compact:!0,className:"butler-session-history-section-list",role:"list",children:r.map(d=>t.jsx(nl,{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 nl(e){return t.jsx(Hl,{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:fs(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 Zl(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 Kr(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 Yr(){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 Zr(e){var f,h,v;const n=u.useMemo(()=>[...e.items].sort((x,A)=>w(A.updatedAt)-w(x.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":ui(l.status),children:oi(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:ci(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:di(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:fs(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:((v=e.selectedSandbox.workspace)==null?void 0:v.path)??s("shell.butlerSandboxWorkspaceMissing")})]})]}),e.selectedSandbox.workspace?t.jsx(wr,{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 Xr(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(os,{className:"butler-sandbox-browser-list",compact:!0,children:n.map(l=>{var r;const i=e.actionSandboxId===l.id;return t.jsx(Hl,{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":ui(l.status),children:oi(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:ci(l.sourceKind)}),t.jsx("span",{children:di(l.visibility)}),t.jsx("span",{children:fs(l.updatedAt)})]})},l.id)})})}function Gr(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(Xl,{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 Qr(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(Xl,{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 Xl(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:gs(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:ae(it(n))}),t.jsxs("div",{className:"butler-inline-actions",children:[e.onCancelFollowUpTask&&Ta(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 Jr(e){const n=u.useId(),l=u.useId(),i=u.useRef(null),r=u.useRef(null),[c,d]=u.useState(!1),f=ma(e.schedule,e.countdownNow),h=ca(e.schedule,e.countdownNow),v=da(e.schedule,e.countdownNow),x=Aa(e.schedule,e.projectNameById,e.workspaceNameById,e.currentWorkspaceId,e.currentWorkspaceName),A=Ca(e.schedule,e.sessionTitleById),H=ha(e.schedule),P=!!(kn(e.schedule)&&(e.sessionWorkspaceIdById.has(kn(e.schedule))||bs(e.schedule))),R=ua(e.schedule),$=ba(e.schedule),W=R?e.executingNow?s("shell.butlerControlTimerExecutingNow"):s("shell.butlerControlTimerExecuteNowAction"):e.skippingWait?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerCancelAction"),Y=R?e.cancelling?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerStopAction"):e.cancelling?s("shell.butlerControlTimerCancelling"):s("shell.butlerControlTimerCancelOperationAction");return u.useEffect(()=>{if(!c)return;const te=B=>{var oe,q;(oe=i.current)!=null&&oe.contains(B.target)||(q=r.current)!=null&&q.contains(B.target)||d(!1)},Z=B=>{B.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",te),document.addEventListener("keydown",Z),()=>{document.removeEventListener("pointerdown",te),document.removeEventListener("keydown",Z)}},[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:$})]}),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:v})]}),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:x,children:x})]}),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(te=>!te)},children:t.jsx("span",{className:"butler-control-timer-banner-detail-icon","aria-hidden":"true",children:t.jsx(wa,{})})}),t.jsx(hs,{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:R?e.onExecuteNow:e.onSkipWait,children:W}),t.jsx("button",{type:"button",className:"secondary-button butler-control-timer-banner-action",disabled:e.cancelling||e.executingNow||e.skippingWait,onClick:e.onCancel,children:Y})]}),R?t.jsx("p",{className:"butler-control-timer-banner-note",children:s("shell.butlerControlTimerActionNote")}):null]})})}function ea(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)},Pr))},[e,n]),u.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),e??n}function ta(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)},Mr))},[n,l]),u.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),l}function na(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 sa(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")," · ",ae(n.nextRunAt)]}),t.jsxs("span",{className:"butler-automation-overview-inline-meta",children:[s("shell.butlerAutomationTaskLastRunLabel")," · ",ae(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 la(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")," · ",ae(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 ia(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:ni(e.automation.triggerType)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationStatusLabel")}),t.jsx("strong",{children:ii(e.automation.status)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskNextRunLabel")}),t.jsx("strong",{children:ae(e.automation.nextRunAt)})]}),t.jsxs("div",{className:"butler-automation-detail-summary-card",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskLastRunLabel")}),t.jsx("strong",{children:ae(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(ra,{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":li(n.status),children:ri(n.status)})]}),t.jsxs("div",{className:"butler-automation-detail-run-meta",children:[t.jsx("span",{children:si(n.triggerType)}),t.jsx("span",{children:ae(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 ra(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 aa(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:Or.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 ae(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 oa(e){return e.kind==="timer"?e.timer.id:e.automation.id}function Vt(e){return e.kind==="timer"?e.timer.dueAt:e.automation.nextRunAt}function bs(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 kn(e){var n,l,i,r,c,d,f,h,v,x,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())||((v=(h=(f=e.automation.controlSession)==null?void 0:f.session)==null?void 0:h.sessionId)==null?void 0:v.trim())||((A=(x=e.automation.controlSession)==null?void 0:x.sessionId)==null?void 0:A.trim())||null}function ua(e){return e.kind==="timer"||e.automation.triggerType==="once"}function ca(e,n){const l=w(Vt(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueLead"):s("shell.butlerControlTimerCountdownLead")}function da(e,n){const l=w(Vt(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueTail"):s("shell.butlerControlTimerCountdownTail")}function ma(e,n){const l=w(Vt(e));return!l||l<=n?"00:00":Ia(l-n)}function ha(e){return e.kind==="timer"?Sa(e.timer):e.automation.actionConfig.content.trim()||s("conversation.butlerAnalysisEmpty")}function ba(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 Gl(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:ai(c),projectName:ps(c,i),status:$a(c.status),taskTypeLabel:ni(c.triggerType),statusLabel:ii(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 Ql(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 v=d.get(h.automationId);return{run:h,automation:v,normalizedStatus:li(h.status)}}).filter(({automation:h})=>!!h).filter(({normalizedStatus:h})=>i==="history"?!r(h):r(h)).map(({run:h,automation:v,normalizedStatus:x})=>{var A,H;return{id:`assistant-automation-run:${h.id}`,automationId:h.automationId,kind:"assistant_automation_run",title:ai(v),projectName:ps(v,c),status:x,sourceLabel:si(h.triggerType),statusLabel:ri(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,v)=>w(v.createdAt)-w(h.createdAt)).slice(0,12)}function fa(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:Ha(l.kind)})]}),t.jsx("span",{children:ae(l.createdAt)})]}),t.jsxs("div",{className:"butler-follow-up-round-body",children:[t.jsxs("p",{children:[s("shell.butlerAutomationRoundProcessedAtLabel"),":",ae(l.createdAt)]}),t.jsxs("p",{children:[s("shell.butlerAutomationRoundStatusLabel"),":",gs(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 ga(e){return e.items.length===0?t.jsx("p",{className:"butler-secondary-text",children:s("shell.butlerVerificationHistoryEmpty")}):t.jsx(Yl,{title:s("shell.butlerInfoVerificationRecordsTitle"),items:e.items,emptyText:s("shell.butlerVerificationHistoryEmpty"),cancellingVerificationId:e.cancellingVerificationId,onCancelVerificationRun:e.onCancelVerificationRun})}function pa(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:ae(n.lastRunAt)})]})]}),t.jsxs("footer",{className:"butler-automation-card-footer",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskNextRunLabel")}),t.jsx("strong",{children:ae(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:ae(n.createdAt)})]})]},n.id))]})}function Jl(e,n){return[...e].filter(l=>n==="history"?!al(l.status):al(l.status)).sort((l,i)=>w(Qn(i))-w(Qn(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:Ra(l.status),content:((r=l.summary)==null?void 0:r.trim())||s("shell.butlerInfoVerificationFallback",{status:l.status}),meta:ae(Qn(l)),verification:l}})}function sl(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(r.updatedAt)-w(i.updatedAt))}function ll(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(it(r))-w(it(i)))}function xa(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(r.updatedAt)-w(i.updatedAt))}function il(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(rl(r))-w(rl(i)))}function ds(e){return e==="active"||e==="waiting_user"}function rl(e){return e.dueAt||e.triggeredAt||e.cancelledAt||e.updatedAt||e.createdAt}function va(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 Sa(e){return e.content.trim()||va(e)}function ya(e,n,l,i,r){var f,h,v,x;const c=(f=e.projectId)==null?void 0:f.trim();if(c&&n.has(c))return n.get(c);const d=((x=(v=(h=e.controlSession)==null?void 0:h.session)==null?void 0:v.workspaceId)==null?void 0:x.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 Aa(e,n,l,i,r){var f;if(e.kind==="timer")return ya(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=bs(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 ja(e,n){var r,c,d,f,h,v,x;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=((x=(v=(h=e.controlSession)==null?void 0:h.session)==null?void 0:v.sessionId)==null?void 0:x.trim())||e.sessionId.trim();return i&&n.has(i)?n.get(i):s("shell.butlerControlTimerUnknownSession")}function Ca(e,n){var i,r,c;if(e.kind==="timer")return ja(e.timer,n);const l=kn(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 wa(){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 Ia(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 al(e){return e==="queued"||e==="running"}function Ta(e){return e.status==="active"||e.status==="waiting_user"}function Na(e){return e.status==="queued"||e.status==="running"}function Ra(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 ka(e){return e==="failed"?"failed":e==="cancelled"?"cancelled":e==="passed"||e==="skipped"?"completed":"active"}function Ea(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 Qn(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 La(e){const n=e.trim();return n||null}function gn(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 jn(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 Pa(e,n){const l=jn(e,n);if(!l)throw new Error(`${n}${s("shell.butlerAutomationRequiredSuffix")}`);return l}function ei(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 ti(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 pn(e,n){const l=ti(e,n);if(l===null)return null;if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Ma(e,n){const l=ei(e,n);if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Fa(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 fs(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 Da(e){for(const[n,l]of Object.entries(us))if(l.length===e.length&&l.every((i,r)=>i===e[r]))return n;return"risk-first"}function Oa(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 Ua(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 gs(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 Ha(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 ni(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 si(e){return e==="interval"||e==="cron"?s("shell.butlerAutomationRunSourcePatrol"):e==="once"?s("shell.butlerAutomationRunSourceControlTimer"):s("shell.butlerAutomationRunSourceFollowUp")}function li(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 $a(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 ii(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 ri(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 ai(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 ps(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 Ba(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 ol(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=gn(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=gn(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=gn(e.triggerConfig.stopAt)):(n.pollIntervalSeconds=st(e.triggerConfig.pollIntervalSeconds),n.expiresAt=gn(e.triggerConfig.expiresAt),n.maxChecks=st(e.triggerConfig.maxChecks)),n}function _a(e,n){const l={title:La(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:Pa(n.dueAt,s("shell.butlerAutomationDueAtLabel"))}:e.triggerConfig.type==="interval"?{...l,everySeconds:pn(n.everySeconds,s("shell.butlerAutomationEverySecondsLabel")),everyMinutes:pn(n.everyMinutes,s("shell.butlerAutomationEveryMinutesLabel")),everyHours:pn(n.everyHours,s("shell.butlerAutomationEveryHoursLabel")),stopAt:jn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:e.triggerConfig.type==="cron"?{...l,cronMinute:ei(n.cronMinute,s("shell.butlerAutomationCronMinuteLabel")),cronHour:ti(n.cronHour,s("shell.butlerAutomationCronHourLabel")),cronDaysOfWeek:Fa(n.cronDaysOfWeek),stopAt:jn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:{...l,pollIntervalSeconds:Ma(n.pollIntervalSeconds,s("shell.butlerAutomationPollIntervalLabel")),expiresAt:jn(n.expiresAt,s("shell.butlerAutomationExpiresAtLabel")),maxChecks:pn(n.maxChecks,s("shell.butlerAutomationMaxChecksLabel"))}}function oi(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 ui(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 ci(e){return e==="clone"?s("shell.butlerSandboxSourceClone"):s("shell.butlerSandboxSourceBlank")}function di(e){return e==="pinned"?s("shell.butlerSandboxVisibilityPinned"):s("shell.butlerSandboxVisibilityAssistantOnly")}function wt(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 xn(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>w(ul(r))-w(ul(i)))}function ul(e){return e.updatedAt||e.lastRunAt||e.nextRunAt||e.createdAt}function Va(e){const l=`${e.displayName.trim()}:${e.providerId}:${e.tone}`,i=qa(e);if(!l)return Ne.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 qa(e){const n=e.displayName.trim().toLowerCase();return/(bot|ai|智能|助手|助理|管家|buddy|helper)/.test(n)?Ne.builder:/(书|学|知|研|析|查|review|audit|scan)/.test(n)?Ne.analyst:e.tone==="friendly"?Ne.friendly:e.tone==="steady"?Ne.steady:e.tone==="direct"?e.providerId==="claude-code"?Ne.analyst:Ne.direct:e.providerId==="claude-code"?Ne.analyst:Ne.default}function Jn(e){switch(e){case"claude-code":return"Claude Code";case"codex":default:return"Codex"}}function za(e,n){const l=(e==null?void 0:e.flatMap(r=>{if(!Wa(r.provider))return[];const c=r.provider,d=r.displayName||Jn(c);return[{value:c,label:r.enabled?d:`${d} (${s("settings.skillTargetDisabledTag")})`,enabled:r.enabled}]}))??cs.map(r=>({value:r,label:Jn(r),enabled:!0})),i=new Map(l.map(r=>[r.value,r]));for(const r of n)!r||i.has(r)||i.set(r,{value:r,label:`${Jn(r)} (${s("settings.skillTargetDisabledTag")})`,enabled:!1});return cs.map(r=>i.get(r)).filter(r=>!!r)}function Wa(e){return cs.includes(e)}function ze(e,n){var l;return((l=e.find(i=>i.value===n))==null?void 0:l.label)??n}function Ka(){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 Ya(){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 mi="mobile.butler.active-tab",Cn=["info","automation","settings"],Za=15e3,xs=56,vs=1.2,cl=360,Xa=1500,Ga=1500;function Qa(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)},Xa))},[e,n]),u.useEffect(()=>()=>{i.current!==null&&window.clearTimeout(i.current)},[]),e??n}function Ja(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)},Ga))},[n,l]),u.useEffect(()=>()=>{r.current!==null&&window.clearTimeout(r.current)},[]),l}function eo(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 to(){if(typeof window>"u")return"info";try{const e=window.localStorage.getItem(mi);return e==="automation"||e==="settings"?e:"info"}catch{return"info"}}function no(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 so(e,n){return e==="settings"?"settings":e==="automation"?"automation":e==="info"?"info":n}function lo(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)<xs)return{closeSidebar:!1,nextTab:e};if(Math.abs(i)<Math.abs(r)*vs)return{closeSidebar:!1,nextTab:e};const c=Cn.indexOf(e);if(i>0&&c===0)return{closeSidebar:!0,nextTab:e};const d=i<0?Math.min(Cn.length-1,c+1):Math.max(0,c-1);return{closeSidebar:!1,nextTab:Cn[d]??e}}function io(e,n){if(!e)return null;const l=n.x-e.x,i=n.y-e.y;return Math.abs(l)<xs||Math.abs(l)<Math.abs(i)*vs?null:l>0?"list":"sidebar"}function es(e){return e instanceof Element?!!e.closest("input, textarea, select, option, label, button, a, [contenteditable='true'], [data-mobile-butler-gesture='ignore']"):!1}function ro(){var Ht,xt,vt,Ce,St,$t,rn,et,an,on,un;const{workspaceId:e=""}=Fl(),n=gr(),l=Dl(),{showToast:i}=Ol(),{navigationGroups:r,requestNavigationRefresh:c,selectWorkspace:d}=ms(),f=((Ht=r.find(o=>o.workspace.id===e))==null?void 0:Ht.workspace)??null,h=u.useMemo(()=>new Map(r.map(o=>[o.workspace.id,o.workspace.name])),[r]),v=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]),x=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(to()),P=so(A,H.current),R=u.useRef(null),$=u.useRef(null),W=u.useRef(null),Y=u.useRef(null),te=u.useRef(null),[Z,B]=u.useState(null),[oe,q]=u.useState(null),[We,As]=u.useState(null),[ke,qt]=u.useState(null),[he,rt]=u.useState(null),[Ee,ne]=u.useState(null),[_,be]=u.useState(null),[Le,Pe]=u.useState(null),[at,zt]=u.useState(null),[ot,Wt]=u.useState(null),[Kt,ut]=u.useState(null),[Yt,fe]=u.useState(null),[ct,Me]=u.useState(()=>Date.now()),[se,dt]=u.useState(null),[xe,Zt]=u.useState(null),[y,F]=u.useState({loading:!0,initialized:!1,profile:null,overview:null,followUpTasks:[],inboxItems:[],patrolPlans:[],controlSessions:[],controlTimers:[],assistantAutomations:[],assistantAutomationRuns:[]}),Xt=u.useMemo(()=>{var o;return new Map((((o=y.overview)==null?void 0:o.projects)??[]).map(b=>[b.id,b.name]))},[(xt=y.overview)==null?void 0:xt.projects]);(!Y.current||te.current!==e)&&(Y.current=new zl(e),te.current=e);const E=Y.current,It=k(E,o=>o.loading),ve=k(E,o=>o.initialized),X=k(E,o=>o.profile),ue=k(E,o=>o.activeProvider),I=k(E,o=>o.controlSession),Tt=k(E,o=>o.capabilities),Nt=k(E,o=>o.messages),Ln=k(E,o=>o.historyState),mt=k(E,o=>o.loadingOlderMessages),Pn=k(E,o=>o.hasOlderMessages),Ke=k(E,o=>o.sending),Se=k(E,o=>o.runtimeHasActiveRun),ht=k(E,o=>o.runtimeCanInterrupt),Mn=k(E,o=>o.contextUsage),Ye=k(E,o=>o.permissionRequests),{composerPortalTarget:Fn}=br(),bt=u.useRef(null),ge=u.useRef(null),ce=u.useRef(!1),ye=u.useRef(new Set);u.useEffect(()=>{if(H.current=P,!(typeof window>"u"))try{window.localStorage.setItem(mi,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&&E.initialize()},[E,e]),u.useEffect(()=>{var G,$e,Q,L,yt;const o=((G=I==null?void 0:I.session)==null?void 0:G.sessionId)??null;if(ge.current!==o&&(ge.current=o,ce.current=!1,ye.current=new Set),!o)return;const b=Ye.filter(ie=>ie.status==="pending"),S=new Set(b.map(ie=>ie.id)),C=(($e=I==null?void 0:I.title)==null?void 0:$e.trim())||((L=(Q=I==null?void 0:I.session)==null?void 0:Q.title)==null?void 0:L.trim())||((yt=X==null?void 0:X.displayName)==null?void 0:yt.trim())||s("shell.butlerEntry");ce.current&&b.forEach(ie=>{ye.current.has(ie.id)||i({id:`mobile-butler-permission-request-${ie.id}`,title:s("conversation.permissionRequestToastTitle"),description:s("conversation.backgroundPermissionToastDescription",{title:C,requestTitle:ie.title}),tone:"warning",durationMs:8e3})}),ye.current=S,ce.current=!0},[(vt=I==null?void 0:I.session)==null?void 0:vt.sessionId,(Ce=I==null?void 0:I.session)==null?void 0:Ce.title,I==null?void 0:I.title,Ye,X==null?void 0:X.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($e){F(Q=>({...Q,loading:!0}));try{const Q=await wl();if(!Q.initialized||!Q.profile){o||F({loading:!1,initialized:!1,profile:null,overview:null,followUpTasks:[],inboxItems:[],patrolPlans:[],controlSessions:[],controlTimers:[],assistantAutomations:[],assistantAutomationRuns:[]});return}const[L,yt,ie,Vn,At,tt,Bt]=await Promise.all([ss(),ls(),Ll({workspaceId:e}),In(),Pl(),is({limit:100}),rs({limit:100})]),cn=L.overview.projects.filter(J=>J.workspaceId===e).map(J=>J.id),dn=await Promise.all(cn.map(J=>Ml(J)));if(o)return;F({loading:!1,initialized:!0,profile:Q.profile,overview:L.overview,followUpTasks:yt.items.filter(J=>J.workspaceId===e),inboxItems:ie.items.filter(J=>J.status!=="closed"),patrolPlans:dn.flatMap(J=>J.items),controlSessions:Vn.items,controlTimers:At.items,assistantAutomations:tt.payload.items,assistantAutomationRuns:Bt.payload.items})}catch(Q){if(o)return;F(L=>({...L,loading:!1})),$e&&i({title:s("shell.butlerLoadFailed"),description:Q instanceof Error?Q.message:void 0,tone:"error"})}}b(!0);const S=window.setInterval(()=>{b(!1)},Za),C=_l(()=>{b(!1)}),G=()=>{b(!1)};return window.addEventListener(Rn,G),()=>{o=!0,window.clearInterval(S),C(),window.removeEventListener(Rn,G)}},[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))},[(St=y.overview)==null?void 0:St.projects,e]),Rt=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]),kt=u.useMemo(()=>y.followUpTasks.filter(o=>bl(o.status)),[y.followUpTasks]),Ze=u.useMemo(()=>{var o;return(((o=y.overview)==null?void 0:o.verifications)??[]).filter(b=>b.projectId?V.has(b.projectId):!1)},[($t=y.overview)==null?void 0:$t.verifications,V]),Gt=u.useMemo(()=>[...kt].sort((o,b)=>M(we(b))-M(we(o))).slice(0,4),[kt]),Ae=u.useMemo(()=>ml(Ze,"active"),[Ze]),Fe=u.useMemo(()=>ml(Ze,"history"),[Ze]),Qt=u.useMemo(()=>go(y.inboxItems.filter(o=>o.status!=="closed")).slice(0,4),[y.inboxItems]),De=u.useMemo(()=>xl(y.assistantAutomations,y.overview,V,"active"),[y.assistantAutomations,y.overview,V]),Et=u.useMemo(()=>vl(y.assistantAutomations,y.assistantAutomationRuns,y.overview,V,"active"),[y.assistantAutomations,y.assistantAutomationRuns,y.overview,V]),de=u.useMemo(()=>_?y.assistantAutomations.find(o=>o.id===_)??null:null,[_,y.assistantAutomations]),Lt=u.useMemo(()=>_?y.assistantAutomationRuns.filter(o=>o.automationId===_).sort((o,b)=>M(b.createdAt)-M(o.createdAt)).slice(0,6):[],[_,y.assistantAutomationRuns]);u.useEffect(()=>{_&&!de&&(be(null),Pe(null))},[de,_]);const Jt=u.useMemo(()=>[...y.followUpTasks].filter(o=>!bl(o.status)).sort((o,b)=>M(we(b))-M(we(o))).slice(0,8),[y.followUpTasks]),Pt=u.useMemo(()=>xl(y.assistantAutomations,y.overview,V,"history"),[y.assistantAutomations,y.overview,V]),en=u.useMemo(()=>vl(y.assistantAutomations,y.assistantAutomationRuns,y.overview,V,"history"),[y.assistantAutomations,y.assistantAutomationRuns,y.overview,V]),Dn=u.useMemo(()=>eo(I,Se),[I,Se]),Xe=Ja((I==null?void 0:I.session.sessionId)??null,Dn),On=Xe||Ke,tn=Xe||Ke,Un=ht===!0||Ke?!0:ht??!1,ft=u.useMemo(()=>{if(!I||Xe)return null;const o=Rt.filter(C=>C.status==="active"&&C.controlSessionId===I.id).map(C=>({kind:"timer",timer:C})),b=new Set(Rt.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,G)=>M(En(C))-M(En(G)))[0]??null},[I,Xe,y.assistantAutomations,Rt]),le=Qa(ft),Mt=y.loading||It,Ft=!Mt&&(!y.initialized||!ve||!y.profile),Ge=((rn=X==null?void 0:X.displayName)==null?void 0:rn.trim())||((an=(et=y.profile)==null?void 0:et.displayName)==null?void 0:an.trim())||s("shell.butlerEntry"),nn=!I&&Nt.length===0,gt=!Ft&&Z===null;u.useEffect(()=>{if(Me(Date.now()),!le)return;const o=window.setInterval(()=>{Me(Date.now())},1e3);return()=>{window.clearInterval(o)}},[le]),u.useEffect(()=>{Z!=="sidebar"&&q(null)},[Z]);const sn=oe==="follow_up"?t.jsx(dl,{title:s("shell.butlerFollowUpHistoryTitle"),description:s("shell.butlerFollowUpHistoryDescription"),emptyText:s("shell.butlerInfoFollowUpRecordsEmpty"),onClose:()=>q(null),items:Jt.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:Sl(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:ee(we(o))}),meta:ee(we(o)),actionLabel:vn(o.status)?ke===o.id?s("conversation.butlerFollowUpStopping"):s("conversation.butlerStopFollowUpAction"):null,actionDisabled:ke===o.id,onAction:vn(o.status)?()=>{Oe(o)}:void 0}})}):oe==="verification"?t.jsx(dl,{title:s("shell.butlerVerificationHistoryTitle"),description:s("shell.butlerVerificationHistoryDescription"),emptyText:s("shell.butlerVerificationHistoryEmpty"),onClose:()=>q(null),items:Fe.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&&gl(o.verification.status)?he===o.verification.id?s("conversation.butlerVerificationStopping"):s("conversation.butlerStopVerificationAction"):null,actionDisabled:o.verification?he===o.verification.id:!1,onAction:o.verification?()=>{Qe(o.verification)}:void 0}))}):oe==="automation"?t.jsx(ho,{taskItems:Pt,runItems:en,onClose:()=>q(null)}):P==="info"?t.jsxs(t.Fragment,{children:[t.jsx(_t,{title:s("shell.butlerInfoFollowUpRecordsTitle"),emptyText:s("shell.butlerInfoFollowUpRecordsEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("follow_up"),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:Sl(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:ee(we(o))}),meta:ee(we(o)),actionLabel:vn(o.status)?ke===o.id?s("conversation.butlerFollowUpStopping"):s("conversation.butlerStopFollowUpAction"):null,actionDisabled:ke===o.id,onAction:vn(o.status)?()=>{Oe(o)}:void 0}})}),t.jsx(_t,{title:s("shell.butlerInfoVerificationRecordsTitle"),emptyText:s("shell.butlerInfoVerificationRecordsEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("verification"),items:Ae.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&&gl(o.verification.status)?he===o.verification.id?s("conversation.butlerVerificationStopping"):s("conversation.butlerStopVerificationAction"):null,actionDisabled:o.verification?he===o.verification.id:!1,onAction:o.verification?()=>{Qe(o.verification)}:void 0}))}),t.jsx(mo,{title:s("shell.butlerInfoTodoRecordsTitle"),emptyText:s("shell.butlerInfoTodoRecordsEmpty"),items:Qt.map((o,b)=>({id:`${o.title}:${b}`,title:o.title,content:o.content}))})]}):P==="automation"?t.jsxs(t.Fragment,{children:[t.jsx(oo,{items:De,emptyText:s("shell.butlerAutomationTasksEmpty"),actionLabel:s("shell.butlerFollowUpHistoryAction"),onAction:()=>q("automation"),selectedAutomationId:_,cancellingAutomationId:Ee,onSelectAutomation:Bn,onCancelAutomation:o=>{Ue(o)}}),de&&Le?t.jsx(uo,{automation:de,editorState:Le,saving:at===de.id,recentRuns:Lt,workspaceNameById:h,sessionTitleById:v,onClose:()=>{be(null),Pe(null)},onEditorChange:o=>{Pe(b=>b&&{...b,...o})},onSave:()=>{Je()}}):null,t.jsx(_t,{title:s("shell.butlerAutomationRunsTitle"),emptyText:s("shell.butlerAutomationRunsEmpty"),items:Et.map(o=>({id:o.id,title:o.title,subtitle:o.projectName,status:o.statusLabel,content:`${o.sourceLabel} · ${o.summary}`,meta:ee(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(Re,{label:s("shell.butlerDisplayNameLabel"),value:Ge}),t.jsx(Re,{label:s("shell.butlerProviderLabel"),value:Cl(ue)}),t.jsx(Re,{label:s("shell.mobileButlerAssistantWorkspaceLabel"),value:((on=y.profile)==null?void 0:on.workspacePath)??(f==null?void 0:f.path)??"-"})]})]});fo(bt,We,gt,`${e}:${Z??"none"}`);function Dt(o){o!==P&&(q(null),l(as(e,o),{replace:!0}))}function pt(o){if(o.changedTouches.length!==1){R.current=null;return}if(es(o.target)){R.current=null;return}const b=o.changedTouches[0];R.current={x:b.clientX,y:b.clientY}}function j(o){if(o.changedTouches.length!==1)return;const b=R.current;R.current=null;const S=o.changedTouches[0],C=io(b,{x:S.clientX,y:S.clientY});C&&B(C)}function je(o){if(o.changedTouches.length!==1){$.current=null;return}if(es(o.target)){$.current=null;return}const b=o.changedTouches[0];$.current={x:b.clientX,y:b.clientY}}function me(o){const b=$.current;if($.current=null,!b||o.changedTouches.length!==1)return;const S=o.changedTouches[0],C=S.clientX-b.x,G=S.clientY-b.y;C>-xs||Math.abs(C)<Math.abs(G)*vs||B(null)}function Ie(o){if(o.changedTouches.length!==1){W.current=null;return}if(es(o.target)){W.current=null;return}const b=o.changedTouches[0];W.current={x:b.clientX,y:b.clientY}}function K(o){const b=W.current;if(W.current=null,o.changedTouches.length!==1)return;const S=o.changedTouches[0],C=lo(P,b,{x:S.clientX,y:S.clientY});if(C.closeSidebar){B(null);return}C.nextTab!==P&&Dt(C.nextTab)}async function N(o){await E.openControlSession(o),B(null)}async function z(){const o=await In();F(b=>({...b,controlSessions:o.items}))}async function g(){if(!(!se||xe)){Zt(se.id);try{await Ul(se.session.sessionId),se.id===(I==null?void 0:I.id)&&await E.openControlSession(""),dt(null),await z(),c(),B(null),i({title:s("shell.deleteSessionSuccess"),tone:"success"})}catch(o){i({title:o instanceof Error?o.message:s("shell.deleteSessionFailed"),tone:"error"})}finally{Zt(null)}}}async function Hn(){await E.startFreshSession(),B(null),c()}async function D(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 E.sendMessage(o,{model:(b==null?void 0:b.model)??null,reasoningLevel:(b==null?void 0:b.reasoningLevel)??null,permissionMode:null}),c()}async function Ot(){const[o,b,S,C]=await Promise.all([ss(),ls(),is({limit:100}),rs({limit:100})]);await E.reloadEventsAndOverview(),F(G=>({...G,overview:o.overview,followUpTasks:b.items.filter($e=>$e.workspaceId===e),assistantAutomations:S.payload.items,assistantAutomationRuns:C.payload.items}))}async function Oe(o){qt(o.id);try{const b=await Tl(o.id);F(S=>({...S,followUpTasks:po(S.followUpTasks,b.task)})),await Ot(),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{qt(null)}}async function Qe(o){rt(o.id);try{await Nl(o.projectId,o.id),await Ot(),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){Wt(o);try{const b=await Tn(o);F(S=>({...S,controlTimers:hl(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{Wt(null)}}function Bn(o){if(_===o){be(null),Pe(null);return}const b=y.assistantAutomations.find(S=>S.id===o);b&&(be(o),Pe(yl(b)))}async function Je(){if(!de||!Le)return;let o;try{o=Fo(de,Le)}catch(b){i({title:s("shell.butlerAutomationSaveFailed"),description:b instanceof Error?b.message:void 0,tone:"error"});return}zt(de.id);try{const b=await Rl(de.id,o);F(S=>({...S,assistantAutomations:ts(S.assistantAutomations,b.payload.automation)})),be(b.payload.automation.id),Pe(yl(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{zt(null)}}async function Ue(o){ne(o);try{const b=await Nn(o);F(S=>({...S,assistantAutomations:ts(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{ne(null)}}async function _n(o){const b=o.content.trim();if(!b){i({title:s("shell.butlerControlTimerExecuteNowFailed"),tone:"error"});return}ut(o.id);try{const S=await Tn(o.id);F(C=>({...C,controlTimers:hl(C.controlTimers,S.timer)})),await E.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 Ut(o){if(o.kind==="timer"){await $n(o.timer.id);return}await Ue(o.automation.id)}async function He(o){if(o.kind==="timer"){await _n(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 Nn(o.automation.id),F(S=>({...S,assistantAutomations:ts(S.assistantAutomations,{...o.automation,status:"cancelled",nextRunAt:null,cancelledAt:new Date().toISOString(),updatedAt:new Date().toISOString()})})),await E.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=ys(o),S=(b?x.get(b):null)||Ss(o)||e;!b||!S||(B(null),l(An(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":Z??"none",children:[t.jsx(Ir,{currentWorkspace:f,workspaces:r.map(o=>o.workspace),heading:s("shell.mobileButlerEntry"),triggerLabel:f.name,onSelectWorkspace:o=>{d(o),l(as(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:Ge}),t.jsx("span",{children:Cl(ue)})]})]}),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:()=>B("list"),children:"≡"}),t.jsx("button",{type:"button",className:"mobile-butler-toolbar-button","aria-label":s("shell.butlerSidebarTabsLabel"),title:s("shell.butlerSidebarTabsLabel"),onClick:()=>B("sidebar"),children:"ⓘ"})]})]})}),t.jsxs("div",{className:"mobile-butler-stage-shell",children:[Z?t.jsx("button",{type:"button",className:"mobile-butler-drawer-scrim","aria-label":s("common.close"),onClick:()=>B(null)}):null,t.jsxs("aside",{className:"mobile-butler-drawer mobile-butler-drawer-list",style:{width:`min(88vw, ${cl}px)`},onTouchStart:je,onTouchEnd:me,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:()=>{Hn()},children:"+"})]}),t.jsx("div",{className:"mobile-butler-list-body",children:t.jsx(bo,{activeControlSessionId:(I==null?void 0:I.id)??null,deletingSessionId:xe,sessions:y.controlSessions,onSelectSession:o=>{N(o)},onDeleteSession:o=>{dt(o)}})})]}),t.jsx("div",{className:"mobile-butler-main-stage",onTouchStart:pt,onTouchEnd:j,children:Mt?t.jsx("section",{className:"mobile-butler-loading-shell",children:t.jsx(Vl,{})}):Ft?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($l,{requests:Ye,replyingRequestId:Yt,onReply:async(o,b)=>{fe(o);try{await E.replyPermissionRequest(o,b)}catch(S){i({title:s("conversation.permissionRequestReplyFailed"),description:S instanceof Error?S.message:void 0,tone:"error"})}finally{fe(null)}}}),nn?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(kl,{sessionId:(un=I==null?void 0:I.session)==null?void 0:un.sessionId,items:El({messages:Nt}),historyState:Ln,loadingOlderMessages:mt,hasOlderMessages:Pn,provider:ue,onLoadOlderMessages:()=>{E.loadOlderMessages()},onRetryMessage:o=>{E.retryMessage(o)}})})]}),le?t.jsx(ao,{schedule:le,currentWorkspaceId:e,currentWorkspaceName:(f==null?void 0:f.name)??null,projectNameById:Xt,workspaceNameById:h,sessionTitleById:v,sessionWorkspaceIdById:x,countdownNow:ct,cancelling:le.kind==="timer"?ot===le.timer.id:Ee===le.automation.id,executingNow:Kt===To(le),onCancel:()=>{Ut(le)},onExecuteNow:()=>{He(le)},onOpenSession:()=>{ln(le)}}):null,gt?t.jsx("div",{className:"mobile-butler-chat-composer","data-mobile-butler-gesture":"ignore",children:t.jsx(Bl,{capabilities:Tt,draftStorageId:`mobile-butler:${e}:${ue}`,panelRef:As,portalContainer:Fn,placeholder:s("shell.butlerComposerPlaceholder",{displayName:Ge}),hasActiveRun:On,canInterrupt:Un,contextUsage:Mn,isSubmitting:Ke,isRunning:tn,onInterrupt:async()=>{await E.interrupt(),c()},onSend:async(o,b)=>{await D(o,b)}})}):null]})}),t.jsx("aside",{className:"mobile-butler-drawer mobile-butler-drawer-sidebar",style:{width:`min(88vw, ${cl}px)`},onTouchStart:Ie,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:Cn.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:()=>{Dt(o)},children:S},o)})})}),t.jsx("div",{className:"mobile-page-top-body mobile-butler-body mobile-butler-sidebar-body",children:sn})]})})]}),t.jsx(jr,{open:se!==null,title:s("shell.deleteSessionConfirmTitle"),description:s("shell.deleteSessionConfirmDescription"),height:"auto",onClose:()=>{xe||dt(null)},footer:t.jsxs("div",{className:"workbench-modal-actions",children:[t.jsx("button",{type:"button",className:"secondary-button",disabled:!!xe,onClick:()=>dt(null),children:s("common.cancel")}),t.jsx("button",{type:"button",className:"secondary-button workbench-danger-button",disabled:!!xe,onClick:()=>{g()},children:xe?s("common.loading"):s("shell.deleteSessionAction")})]}),children:t.jsx("p",{className:"mobile-butler-empty-text",children:se?no(se):""})})]}):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 ao(e){const n=u.useId(),l=u.useId(),i=u.useRef(null),r=u.useRef(null),[c,d]=u.useState(!1),f=Ro(e.schedule,e.countdownNow),h=ko(e.schedule,e.countdownNow),v=Ao(e.schedule,e.projectNameById,e.workspaceNameById,e.currentWorkspaceId,e.currentWorkspaceName),x=Co(e.schedule,e.sessionTitleById),A=Eo(e.schedule),H=ys(e.schedule),P=!!(H&&(e.sessionWorkspaceIdById.has(H)||Ss(e.schedule))),R=No(e.schedule);return u.useEffect(()=>{if(!c)return;const $=Y=>{var te,Z;(te=i.current)!=null&&te.contains(Y.target)||(Z=r.current)!=null&&Z.contains(Y.target)||d(!1)},W=Y=>{Y.key==="Escape"&&d(!1)};return document.addEventListener("pointerdown",$),document.addEventListener("keydown",W),()=>{document.removeEventListener("pointerdown",$),document.removeEventListener("keydown",W)}},[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:v,children:v})]}),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:x,"aria-label":`${s("shell.butlerControlTimerSessionLabel")}:${x}`,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:x}):t.jsx("strong",{title:x,children:x})]})]}),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($=>!$)},children:t.jsx("span",{className:"mobile-butler-timer-detail-icon","aria-hidden":"true",children:t.jsx(wo,{})})}),t.jsx(hs,{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})]})})]}),R?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")})]}),R?t.jsx("p",{className:"mobile-butler-timer-note",children:s("shell.butlerControlTimerActionNote")}):null]})}function Re({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 oo(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:ee(n.nextRunAt)})]}),t.jsxs("div",{className:"mobile-butler-automation-metric",children:[t.jsx("span",{children:s("shell.butlerAutomationTaskLastRunLabel")}),t.jsx("strong",{children:ee(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 uo(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=vi(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(Re,{label:s("shell.butlerAutomationTaskTypeLabel"),value:hi(e.automation.triggerType)}),t.jsx(Re,{label:s("shell.butlerAutomationStatusLabel"),value:fi(e.automation.status)}),t.jsx(Re,{label:s("shell.butlerAutomationTaskNextRunLabel"),value:ee(e.automation.nextRunAt)}),t.jsx(Re,{label:s("shell.butlerAutomationTaskLastRunLabel"),value:ee(e.automation.lastRunAt||e.automation.updatedAt)}),n?t.jsx(Re,{label:s("shell.mobileButlerAssistantWorkspaceLabel"),value:n}):null,l?t.jsx(Re,{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(co,{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:bi(d.triggerType)})]}),t.jsx("span",{className:"mobile-butler-record-badge",children:gi(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:ee(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 co(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 _t(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 mo(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 dl(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 ho(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(_t,{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")} · ${ee(n.lastRunAt)}`}))}):null,e.runItems.length>0?t.jsx(_t,{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:ee(n.createdAt)}))}):null]})}function bo(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:ee(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 fo(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 ml(e,n){return[...e].filter(l=>n==="history"?!fl(l.status):fl(l.status)).sort((l,i)=>M(ns(i))-M(ns(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:xo(l.status),content:((r=l.summary)==null?void 0:r.trim())||s("shell.butlerInfoVerificationFallback",{status:l.status}),meta:ee(ns(l)),verification:{id:l.id,projectId:l.projectId,status:l.status}}})}function go(e){return e.map(n=>({title:n.title,content:`${n.projectName} · ${Io(n.status)}`}))}function hl(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(pl(r))-M(pl(i)))}function ts(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(Al(r))-M(Al(i)))}function po(e,n){const l=e.filter(i=>i.id!==n.id);return[n,...l].sort((i,r)=>M(we(r))-M(we(i)))}function bl(e){return e==="active"||e==="waiting_user"}function vn(e){return e==="active"||e==="waiting_user"}function fl(e){return e==="queued"||e==="running"}function gl(e){return e==="queued"||e==="running"}function xo(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 pl(e){return e.dueAt||e.triggeredAt||e.cancelledAt||e.updatedAt||e.createdAt}function vo(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 So(e){return e.content.trim()||vo(e)}function yo(e,n,l,i,r){var f,h,v,x;const c=(f=e.projectId)==null?void 0:f.trim();if(c&&n.has(c))return n.get(c);const d=((x=(v=(h=e.controlSession)==null?void 0:h.session)==null?void 0:v.workspaceId)==null?void 0:x.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 Ao(e,n,l,i,r){var f;if(e.kind==="timer")return yo(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=Ss(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 jo(e,n){var r,c,d,f,h,v,x;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=((x=(v=(h=e.controlSession)==null?void 0:h.session)==null?void 0:v.sessionId)==null?void 0:x.trim())||e.sessionId.trim();return i&&n.has(i)?n.get(i):s("shell.butlerControlTimerUnknownSession")}function Co(e,n){var i,r,c;if(e.kind==="timer")return jo(e.timer,n);const l=ys(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 wo(){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 xl(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=>Si(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:pi(d),projectName:xi(d,r),status:Po(d.status),taskTypeLabel:hi(d.triggerType),statusLabel:fi(d.status),nextRunAt:d.nextRunAt,lastRunAt:d.lastRunAt||d.updatedAt,promptPreview:Mo(d.actionConfig.content),lastResultSummary:((f=d.lastRunSummary)==null?void 0:f.trim())||((h=d.lastError)==null?void 0:h.trim())||null,targetSessionTitle:vi(d)}}).sort((d,f)=>{const h=M(d.nextRunAt),v=M(f.nextRunAt);return h!==v?h===0?1:v===0?-1:h-v:M(f.lastRunAt)-M(d.lastRunAt)}).slice(0,8)}function vl(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=>Si(h,i,l)).map(h=>[h.id,h]));return n.map(h=>({run:h,automation:d.get(h.automationId),normalizedStatus:Lo(h.status)})).filter(({automation:h})=>!!h).filter(({normalizedStatus:h})=>r==="history"?!jl(h):jl(h)).map(({run:h,automation:v,normalizedStatus:x})=>{var A,H;return{id:`assistant-automation-run:${h.id}`,kind:"assistant_automation_run",title:pi(v),projectName:xi(v,c),status:x,sourceLabel:bi(h.triggerType),statusLabel:gi(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,v)=>M(v.createdAt)-M(h.createdAt)).slice(0,10)}function Io(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 we(e){return e.updatedAt||e.lastAutomationAt||e.lastCheckedAt||e.createdAt}function To(e){return e.kind==="timer"?e.timer.id:e.automation.id}function En(e){return e.kind==="timer"?e.timer.dueAt:e.automation.nextRunAt}function Ss(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 ys(e){var n,l,i,r,c,d,f,h,v,x,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())||((v=(h=(f=e.automation.controlSession)==null?void 0:f.session)==null?void 0:h.sessionId)==null?void 0:v.trim())||((A=(x=e.automation.controlSession)==null?void 0:x.sessionId)==null?void 0:A.trim())||null}function No(e){return e.kind==="timer"||e.automation.triggerType==="once"}function Ro(e,n){const l=M(En(e));return!l||l<=n?s("shell.butlerControlTimerCountdownDueNow"):s("shell.butlerControlTimerCountdownActive",{duration:$o(l-n)})}function ko(e,n){const l=M(En(e));return!l||l<=n?"00:00":Bo(l-n)}function Eo(e){return e.kind==="timer"?So(e.timer):e.automation.actionConfig.content.trim()||s("conversation.butlerAnalysisEmpty")}function Sl(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 hi(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 bi(e){return e==="interval"||e==="cron"?s("shell.butlerAutomationRunSourcePatrol"):e==="once"?s("shell.butlerAutomationRunSourceControlTimer"):s("shell.butlerAutomationRunSourceFollowUp")}function Lo(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 Po(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 fi(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 gi(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 pi(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 xi(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 vi(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 Mo(e){const n=e.replace(/\s+/g," ").trim();return n?n.length<=72?n:`${n.slice(0,72)}...`:s("conversation.butlerAnalysisEmpty")}function yl(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=Sn(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=Sn(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=Sn(e.triggerConfig.stopAt)):(n.pollIntervalSeconds=lt(e.triggerConfig.pollIntervalSeconds),n.expiresAt=Sn(e.triggerConfig.expiresAt),n.maxChecks=lt(e.triggerConfig.maxChecks)),n}function Fo(e,n){const l={title:Do(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:Oo(n.dueAt,s("shell.butlerAutomationDueAtLabel"))}:e.triggerConfig.type==="interval"?{...l,everySeconds:yn(n.everySeconds,s("shell.butlerAutomationEverySecondsLabel")),everyMinutes:yn(n.everyMinutes,s("shell.butlerAutomationEveryMinutesLabel")),everyHours:yn(n.everyHours,s("shell.butlerAutomationEveryHoursLabel")),stopAt:wn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:e.triggerConfig.type==="cron"?{...l,cronMinute:yi(n.cronMinute,s("shell.butlerAutomationCronMinuteLabel")),cronHour:Ai(n.cronHour,s("shell.butlerAutomationCronHourLabel")),cronDaysOfWeek:Ho(n.cronDaysOfWeek),stopAt:wn(n.stopAt,s("shell.butlerAutomationStopAtLabel"))}:{...l,pollIntervalSeconds:Uo(n.pollIntervalSeconds,s("shell.butlerAutomationPollIntervalLabel")),expiresAt:wn(n.expiresAt,s("shell.butlerAutomationExpiresAtLabel")),maxChecks:yn(n.maxChecks,s("shell.butlerAutomationMaxChecksLabel"))}}function Al(e){return e.updatedAt||e.lastRunAt||e.nextRunAt||e.createdAt}function Si(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 jl(e){return e==="active"||e==="waiting_user"}function ns(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 Do(e){const n=e.trim();return n||null}function Sn(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 Oo(e,n){const l=wn(e,n);if(!l)throw new Error(`${n}${s("shell.butlerAutomationRequiredSuffix")}`);return l}function yi(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 Ai(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 yn(e,n){const l=Ai(e,n);if(l===null)return null;if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Uo(e,n){const l=yi(e,n);if(l<=0)throw new Error(`${n}${s("shell.butlerAutomationInvalidPositiveNumberSuffix")}`);return l}function Ho(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 ee(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 $o(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 Bo(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 Cl(e){switch(e){case"claude-code":return"Claude Code";case"codex":default:return"Codex"}}function su(){const{shellMode:e}=ms();return e==="mobile"?t.jsx(ro,{}):t.jsx($r,{})}export{su as AdaptiveButlerPage};