@cats-inc/cats-platform 0.2.8 → 0.3.5

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 (205) hide show
  1. package/README.md +25 -1
  2. package/build/desktop/bootstrapPage.d.ts.map +1 -1
  3. package/build/desktop/bootstrapPage.js +26 -129
  4. package/build/desktop/bootstrapPage.js.map +1 -1
  5. package/build/desktop/cliInventoryProbe.d.ts +6 -0
  6. package/build/desktop/cliInventoryProbe.d.ts.map +1 -1
  7. package/build/desktop/cliInventoryProbe.js +6 -3
  8. package/build/desktop/cliInventoryProbe.js.map +1 -1
  9. package/build/desktop/contracts.d.ts +2 -0
  10. package/build/desktop/contracts.d.ts.map +1 -1
  11. package/build/desktop/contracts.js.map +1 -1
  12. package/build/desktop/main.js +95 -41
  13. package/build/desktop/main.js.map +1 -1
  14. package/build/desktop/preload.cjs +8 -6
  15. package/build/desktop/preload.cjs.map +1 -1
  16. package/build/desktop/providerManager.d.ts +46 -0
  17. package/build/desktop/providerManager.d.ts.map +1 -0
  18. package/build/desktop/providerManager.js +220 -0
  19. package/build/desktop/providerManager.js.map +1 -0
  20. package/build/desktop/providerSelection.d.ts +1 -0
  21. package/build/desktop/providerSelection.d.ts.map +1 -1
  22. package/build/desktop/providerSelection.js +7 -1
  23. package/build/desktop/providerSelection.js.map +1 -1
  24. package/build/desktop/setupAssets.d.ts.map +1 -1
  25. package/build/desktop/setupAssets.js +12 -0
  26. package/build/desktop/setupAssets.js.map +1 -1
  27. package/build/desktop/setupAudit.d.ts +3 -1
  28. package/build/desktop/setupAudit.d.ts.map +1 -1
  29. package/build/desktop/setupAudit.js +12 -8
  30. package/build/desktop/setupAudit.js.map +1 -1
  31. package/build/desktop/setupBridge.js +1 -1
  32. package/build/desktop/setupBridge.js.map +1 -1
  33. package/build/desktop/setupPrerequisites.d.ts +11 -0
  34. package/build/desktop/setupPrerequisites.d.ts.map +1 -0
  35. package/build/desktop/setupPrerequisites.js +47 -0
  36. package/build/desktop/setupPrerequisites.js.map +1 -0
  37. package/build/renderer/assets/ActiveSessionPermissionChip-BugyYoVY.js +1 -0
  38. package/build/renderer/assets/{App-BZA23O2J.js → App-1MFRMMld.js} +1 -1
  39. package/build/renderer/assets/{App-YqprEL2n.js → App-BWgnfutX.js} +1 -1
  40. package/build/renderer/assets/{App-rGw9J8PZ.js → App-Cm_tok6f.js} +1 -1
  41. package/build/renderer/assets/{WorkspaceAppRoutes-BCHCikmJ.js → WorkspaceAppRoutes-B8U5FWao.js} +1 -1
  42. package/build/renderer/assets/app-CqnsY5ed.css +1 -0
  43. package/build/renderer/assets/app-DTDTNtih.js +85 -0
  44. package/build/renderer/assets/{client-BdGHAUoK.js → client-DREGSZqQ.js} +1 -1
  45. package/build/renderer/assets/conversationSidebarRecentEntries-y_bEg3Cp.js +6 -0
  46. package/build/renderer/assets/{screenshotOverlay-DfBcolX-.js → screenshotOverlay-EF07cXvw.js} +1 -1
  47. package/build/renderer/assets/{useDraftSessionChips-D9BX6X92.js → useDraftSessionChips-BD6ZGG_y.js} +1 -1
  48. package/build/renderer/desktop/overlay/index.html +2 -2
  49. package/build/renderer/index.html +3 -3
  50. package/build/server/app/renderer/auth/api.d.ts.map +1 -1
  51. package/build/server/app/renderer/auth/api.js +4 -1
  52. package/build/server/app/renderer/auth/api.js.map +1 -1
  53. package/build/server/app/renderer/providerCatalogClient.d.ts.map +1 -1
  54. package/build/server/app/renderer/providerCatalogClient.js +19 -6
  55. package/build/server/app/renderer/providerCatalogClient.js.map +1 -1
  56. package/build/server/app/renderer/providerClientInvalidation.d.ts +6 -0
  57. package/build/server/app/renderer/providerClientInvalidation.d.ts.map +1 -0
  58. package/build/server/app/renderer/providerClientInvalidation.js +12 -0
  59. package/build/server/app/renderer/providerClientInvalidation.js.map +1 -0
  60. package/build/server/app/renderer/providerReadLoop.d.ts +5 -0
  61. package/build/server/app/renderer/providerReadLoop.d.ts.map +1 -0
  62. package/build/server/app/renderer/providerReadLoop.js +52 -0
  63. package/build/server/app/renderer/providerReadLoop.js.map +1 -0
  64. package/build/server/app/renderer/providerRegistryClient.d.ts +2 -1
  65. package/build/server/app/renderer/providerRegistryClient.d.ts.map +1 -1
  66. package/build/server/app/renderer/providerRegistryClient.js +33 -17
  67. package/build/server/app/renderer/providerRegistryClient.js.map +1 -1
  68. package/build/server/app/server/authGatePolicy.js +7 -0
  69. package/build/server/app/server/authGatePolicy.js.map +1 -1
  70. package/build/server/app/server/shutdown.d.ts.map +1 -1
  71. package/build/server/app/server/shutdown.js +3 -1
  72. package/build/server/app/server/shutdown.js.map +1 -1
  73. package/build/server/app/server/startup.d.ts +4 -3
  74. package/build/server/app/server/startup.d.ts.map +1 -1
  75. package/build/server/app/server/startup.js +8 -0
  76. package/build/server/app/server/startup.js.map +1 -1
  77. package/build/server/app/server/subscribeRoutes.d.ts.map +1 -1
  78. package/build/server/app/server/subscribeRoutes.js +5 -3
  79. package/build/server/app/server/subscribeRoutes.js.map +1 -1
  80. package/build/server/design/components/providerModelFieldsSupport.d.ts +2 -21
  81. package/build/server/design/components/providerModelFieldsSupport.d.ts.map +1 -1
  82. package/build/server/design/components/providerModelFieldsSupport.js +32 -36
  83. package/build/server/design/components/providerModelFieldsSupport.js.map +1 -1
  84. package/build/server/design/components/useProviderCatalogState.d.ts +1 -2
  85. package/build/server/design/components/useProviderCatalogState.d.ts.map +1 -1
  86. package/build/server/design/components/useProviderCatalogState.js +71 -152
  87. package/build/server/design/components/useProviderCatalogState.js.map +1 -1
  88. package/build/server/design/components/useProviderModelFieldActions.js +2 -2
  89. package/build/server/design/components/useProviderModelFieldActions.js.map +1 -1
  90. package/build/server/design/components/useProviderRegistryState.d.ts +1 -7
  91. package/build/server/design/components/useProviderRegistryState.d.ts.map +1 -1
  92. package/build/server/design/components/useProviderRegistryState.js +41 -91
  93. package/build/server/design/components/useProviderRegistryState.js.map +1 -1
  94. package/build/server/design/components/useProviderTargetReconciliation.d.ts +1 -0
  95. package/build/server/design/components/useProviderTargetReconciliation.d.ts.map +1 -1
  96. package/build/server/design/components/useProviderTargetReconciliation.js +1 -1
  97. package/build/server/design/components/useProviderTargetReconciliation.js.map +1 -1
  98. package/build/server/index.js +30 -0
  99. package/build/server/index.js.map +1 -1
  100. package/build/server/platform/orchestration/entitySubscriptions/channel.d.ts +2 -1
  101. package/build/server/platform/orchestration/entitySubscriptions/channel.d.ts.map +1 -1
  102. package/build/server/platform/orchestration/entitySubscriptions/channel.js +3 -18
  103. package/build/server/platform/orchestration/entitySubscriptions/channel.js.map +1 -1
  104. package/build/server/platform/orchestration/entitySubscriptions/index.d.ts +1 -0
  105. package/build/server/platform/orchestration/entitySubscriptions/index.d.ts.map +1 -1
  106. package/build/server/platform/orchestration/entitySubscriptions/index.js.map +1 -1
  107. package/build/server/products/chat/api/routeSupport.d.ts +9 -1
  108. package/build/server/products/chat/api/routeSupport.d.ts.map +1 -1
  109. package/build/server/products/chat/api/routeSupport.js +22 -0
  110. package/build/server/products/chat/api/routeSupport.js.map +1 -1
  111. package/build/server/products/chat/state/model/readModels.d.ts +1 -0
  112. package/build/server/products/chat/state/model/readModels.d.ts.map +1 -1
  113. package/build/server/products/chat/state/model/readModels.js +2 -1
  114. package/build/server/products/chat/state/model/readModels.js.map +1 -1
  115. package/build/server/products/shared/renderer/api/appShell.d.ts +1 -0
  116. package/build/server/products/shared/renderer/api/appShell.d.ts.map +1 -1
  117. package/build/server/products/shared/renderer/api/appShell.js +9 -0
  118. package/build/server/products/shared/renderer/api/appShell.js.map +1 -1
  119. package/build/server/runtime/client.d.ts.map +1 -1
  120. package/build/server/runtime/client.js +5 -1
  121. package/build/server/runtime/client.js.map +1 -1
  122. package/build/server/runtime/setup.d.ts +4 -0
  123. package/build/server/runtime/setup.d.ts.map +1 -1
  124. package/build/server/runtime/setup.js +3 -1
  125. package/build/server/runtime/setup.js.map +1 -1
  126. package/build/server/server/routes/providers.d.ts.map +1 -1
  127. package/build/server/server/routes/providers.js +21 -50
  128. package/build/server/server/routes/providers.js.map +1 -1
  129. package/build/server/shared/cliInteraction.d.ts +17 -0
  130. package/build/server/shared/cliInteraction.d.ts.map +1 -0
  131. package/build/server/shared/cliInteraction.js +102 -0
  132. package/build/server/shared/cliInteraction.js.map +1 -0
  133. package/build/server/shared/desktopRecoveryBridge.d.ts +2 -1
  134. package/build/server/shared/desktopRecoveryBridge.d.ts.map +1 -1
  135. package/build/server/shared/desktopRecoveryBridge.js.map +1 -1
  136. package/build/server/shared/providerCatalogData.d.ts +168 -96
  137. package/build/server/shared/providerCatalogData.d.ts.map +1 -1
  138. package/build/server/shared/providerCatalogData.js +68 -42
  139. package/build/server/shared/providerCatalogData.js.map +1 -1
  140. package/build/server/shared/providerRegistryWarnings.d.ts +4 -0
  141. package/build/server/shared/providerRegistryWarnings.d.ts.map +1 -1
  142. package/build/server/shared/providerRegistryWarnings.js +7 -0
  143. package/build/server/shared/providerRegistryWarnings.js.map +1 -1
  144. package/package.json +13 -6
  145. package/packages/provider-setup/manager.d.ts +79 -0
  146. package/packages/provider-setup/manager.js +441 -0
  147. package/scripts/README.md +23 -0
  148. package/scripts/build-desktop-installer.mjs +124 -16
  149. package/scripts/dev-server.mjs +4 -1
  150. package/scripts/linux/install-github-cli.sh +5 -0
  151. package/scripts/linux/install-node.sh +9 -3
  152. package/scripts/linux/node-cli-common.sh +87 -48
  153. package/scripts/linux/provider-cli-common.sh +80 -105
  154. package/scripts/linux/provider-version-common.sh +247 -0
  155. package/scripts/linux/test-linux-package-smoke.sh +2 -0
  156. package/scripts/linux/verified-npm-update.sh +20 -0
  157. package/scripts/macos/install-github-cli.sh +5 -0
  158. package/scripts/macos/install-node.sh +9 -3
  159. package/scripts/macos/node-cli-common.sh +87 -48
  160. package/scripts/macos/provider-cli-common.sh +80 -105
  161. package/scripts/macos/provider-version-common.sh +247 -0
  162. package/scripts/macos/test-macos-package-smoke.sh +2 -0
  163. package/scripts/macos/verified-npm-update.sh +20 -0
  164. package/scripts/testing/conversation-navigation-smoke-electron.cjs +134 -0
  165. package/scripts/testing/conversation-navigation-smoke-renderer.tsx +102 -0
  166. package/scripts/testing/conversation-navigation-smoke.mjs +67 -0
  167. package/scripts/validate-release-assets.mjs +4 -1
  168. package/scripts/windows/Install-Antigravity.ps1 +26 -3
  169. package/scripts/windows/Install-ClaudeCode.ps1 +25 -7
  170. package/scripts/windows/Install-CursorAgent.ps1 +45 -30
  171. package/scripts/windows/Install-Devin.ps1 +16 -47
  172. package/scripts/windows/Install-GitHubCli.ps1 +4 -0
  173. package/scripts/windows/Install-Goose.ps1 +18 -1
  174. package/scripts/windows/Install-Grok.ps1 +14 -1
  175. package/scripts/windows/Install-Junie.ps1 +32 -11
  176. package/scripts/windows/Install-KiroCli.ps1 +37 -13
  177. package/scripts/windows/Install-MetaCli.ps1 +8 -1
  178. package/scripts/windows/Install-Node.ps1 +6 -1
  179. package/scripts/windows/Setup-NodeGlobalPrefix.ps1 +10 -0
  180. package/scripts/windows/Test-WindowsInstallerSmoke.ps1 +2 -0
  181. package/scripts/windows/_HiddenProcess.ps1 +14 -3
  182. package/scripts/windows/_NativeInstallerSupport.ps1 +308 -0
  183. package/scripts/windows/_NpmCliInstaller.ps1 +35 -14
  184. package/scripts/windows/_PackagedUninstall.ps1 +9 -1
  185. package/scripts/windows/_VerifiedNpmUpdate.ps1 +25 -0
  186. package/build/renderer/assets/ActiveSessionPermissionChip-CAgN-tXv.js +0 -1
  187. package/build/renderer/assets/app-BV3UAQkR.css +0 -1
  188. package/build/renderer/assets/app-CVPqqfZo.js +0 -45
  189. package/build/renderer/assets/conversationSidebarRecentEntries-iqaLqA1n.js +0 -6
  190. package/build/server/app/renderer/settings/runtimeLifecycleHelpers.d.ts +0 -48
  191. package/build/server/app/renderer/settings/runtimeLifecycleHelpers.d.ts.map +0 -1
  192. package/build/server/app/renderer/settings/runtimeLifecycleHelpers.js +0 -535
  193. package/build/server/app/renderer/settings/runtimeLifecycleHelpers.js.map +0 -1
  194. package/build/server/design/components/useProviderRegistryAutoRecheck.d.ts +0 -13
  195. package/build/server/design/components/useProviderRegistryAutoRecheck.d.ts.map +0 -1
  196. package/build/server/design/components/useProviderRegistryAutoRecheck.js +0 -70
  197. package/build/server/design/components/useProviderRegistryAutoRecheck.js.map +0 -1
  198. package/build/server/products/shared/renderer/api/providerCatalogRefreshStore.d.ts +0 -19
  199. package/build/server/products/shared/renderer/api/providerCatalogRefreshStore.d.ts.map +0 -1
  200. package/build/server/products/shared/renderer/api/providerCatalogRefreshStore.js +0 -53
  201. package/build/server/products/shared/renderer/api/providerCatalogRefreshStore.js.map +0 -1
  202. package/build/server/products/shared/renderer/api/providers.d.ts +0 -17
  203. package/build/server/products/shared/renderer/api/providers.d.ts.map +0 -1
  204. package/build/server/products/shared/renderer/api/providers.js +0 -50
  205. package/build/server/products/shared/renderer/api/providers.js.map +0 -1
@@ -0,0 +1,6 @@
1
+ import{r as p,j as r}from"./client-DREGSZqQ.js";import{ay as zl,I as Cs,az as Ra,aA as Na,aB as aa,aC as Ro,aD as Yl,aE as wr,m as l,V as ia,u as Q,aF as Jl,aG as Ju,ae as Ql,aH as Qu,ah as Xl,aI as Xu,aJ as Zu,aK as ep,aL as tp,aM as fi,aN as Ms,aO as np,aP as mi,aQ as ap,aR as In,aS as rp,aT as Zl,aU as Fe,aV as ec,aW as gi,aX as sp,aY as op,aZ as ip,a_ as lp,a$ as cp,b0 as dp,b1 as Ci,b2 as up,b3 as tc,b4 as Yr,b5 as Jr,b6 as Qr,b7 as pp,b8 as vi,b9 as hp,ba as fp,bb as mp,bc as gp,bd as Cp,am as vp,be as No,bf as nc,ai as pr,bg as Ur,bh as Ip,bi as Xn,bj as To,bk as Sp,E as Xr,r as ao,ar as jo,C as hr,bl as yp,bm as bp,bn as xp,bo as wp,bp as kp,bq as Pp,br as Ap,bs as Ia,bt as Rp,bu as Es,bv as Np,bw as Tp,bx as ya,by as ac,bz as jp,bA as Lp,bB as Mp,bC as Ep,bD as Dp,bE as Bp,bF as Op,bG as Lo,bH as Ii,bI as Mo,bJ as vs,bK as _p,bL as Fp,bM as Wp,bN as Kp,bO as Up,bP as $p,bQ as rc,bR as Hp,bS as sc,bT as oc,bU as qp,bV as Si,bW as Gp,bX as Yn,bY as Jn,F as Vp,bZ as zp,b_ as Yp,b$ as Jp,c0 as Qp,c1 as Xp,c2 as Zp,c3 as eh,c4 as th,c5 as ic,c6 as yi,c7 as nh,c8 as ah,c9 as rh,ca as sh,cb as oh,cc as ih,aj as lh,cd as Eo,ce as bi,X as Ta,cf as ch,cg as lc,ch as dh,ci as Ds,H as uh,cj as ro,ax as Do,ck as Bs,cl as ph,cm as hh,cn as fh,co as mh,cp as gh,cq as Ch,cr as vh,cs as so,ct as Ih,cu as Lr,cv as Sh,cw as ra,au as oa,cx as yh,cy as bh,cz as xh,n as At,cA as wh,ag as kh,at as Ph,cB as Ah,cC as oo,aw as io,_ as Rh,cD as Nh,cE as Th,a3 as Is,cF as jh,cG as Lh,cH as Mh,cI as Eh,a9 as cc,cJ as Dh,an as Bh,cK as Oh,av as xi,as as _h,ak as Fh,b as Wh,ao as Kh,ap as Uh,aq as $h,$ as dc,c as Os,cL as Hh,cM as qh,cN as Gh,cO as Vh,cP as zh,cQ as uc,cR as Bo,cS as Oo,cT as Yh,cU as Jh,cV as Qh,cW as pc,cX as _s,cY as Xh,cZ as Zh,c_ as ef}from"./app-DTDTNtih.js";async function tf(e){const t=await fetch("/api/core",{headers:{Accept:"application/json"},signal:e});return Cs(t,`cats core state returned ${t.status}`)}async function nf(e){const t=await fetch("/api/core/approvals",{headers:{Accept:"application/json"},signal:e});return(await Cs(t,`cats core approvals returned ${t.status}`)).approvals}async function Ir(e){const[t,n]=await Promise.all([tf(e),nf(e)]);return{core:t,approvals:n}}async function af(e,t){const n=await fetch("/api/core/approvals",{method:"POST",headers:{"content-type":"application/json",Accept:"application/json"},body:JSON.stringify(e),signal:t});if(!n.ok)throw new Error(await zl(n,`cats core approval returned ${n.status}`));try{return await Ir(t)}catch{return Ir()}}async function rf(e,t){const n=await fetch("/api/core/operator-actions",{method:"POST",headers:{"content-type":"application/json",Accept:"application/json"},body:JSON.stringify(e),signal:t});if(!n.ok)throw new Error(await zl(n,`cats core operator action returned ${n.status}`));try{return await Ir(t)}catch{return Ir()}}async function wi(e,t){const n=e?`?path=${encodeURIComponent(e)}`:"",a=await fetch(`/api/shell/browse${n}`,{method:"GET",headers:{Accept:"application/json"},signal:t});return Cs(a,`directory browse returned ${a.status}`)}async function sf(e,t){const n=await fetch(`/api/shell/inspect-path?path=${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"},signal:t});return Cs(n,`inspect path returned ${n.status}`)}async function of(e){await fetch("/api/shell/open-folder",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:e})})}const hc=ia("en"),Fs=2;function Dn(e){return Ro(e)??e.trim()}function fc(e){const t=Dn(e.provider);return{provider:t,model:e.model===void 0?Ra(t)||void 0:e.model?.trim()||void 0,instance:e.instance===void 0?Na(t)||void 0:e.instance?.trim()||void 0,modelSelection:e.modelSelection??null}}function Zr(e){return wr({provider:e.provider,instance:e.instance??null,model:e.model??null})}function lf(e,t){return t(e==="strong_agent"?l.chatDraftParticipantCapabilityStrongAgent:l.chatDraftParticipantCapabilityConservativeAgent)}function cf(e,t){const n=[];return e.toolScope==="broad_write"&&n.push(t(l.chatDraftParticipantReviewReasonBroadWrite)),e.autonomy==="outcome_delegation"&&n.push(t(l.chatDraftParticipantReviewReasonOutcomeDelegation)),e.approvalThreshold==="high"&&n.push(t(l.chatDraftParticipantReviewReasonHighApproval)),n}function df(e,t){switch(e){case"none":return t(l.chatDraftParticipantAutonomyNone);case"single_step":return t(l.chatDraftParticipantAutonomySingleStep);case"milestone_plan":return t(l.chatDraftParticipantAutonomyMilestonePlan);case"outcome_delegation":return t(l.chatDraftParticipantAutonomyOutcomeDelegation)}}function uf(e,t){switch(e){case"none":return t(l.chatDraftParticipantToolScopeNone);case"read_only":return t(l.chatDraftParticipantToolScopeReadOnly);case"narrow_write":return t(l.chatDraftParticipantToolScopeNarrowWrite);case"broad_write":return t(l.chatDraftParticipantToolScopeBroadWrite)}}function pf(e,t){switch(e){case"low":return t(l.chatDraftParticipantApprovalThresholdLow);case"medium":return t(l.chatDraftParticipantApprovalThresholdMedium);case"high":return t(l.chatDraftParticipantApprovalThresholdHigh)}}function hf(e,t={},n=hc){const a=t.bootstrapTreatment==="strong_agent",s=lf(t.bootstrapTreatment,n),o={autonomy:t.autonomy??(a?"milestone_plan":"single_step"),toolScope:t.toolScope??"read_only",approvalThreshold:t.approvalThreshold??"low"},i=cf(o,n);return{capabilityLabel:s,executionLabel:Zr(e),policySummary:n(l.chatDraftParticipantPolicySummary,{autonomy:df(o.autonomy,n),approvalThreshold:pf(o.approvalThreshold,n)}),toolGrantSummary:n(l.chatDraftParticipantToolGrantSummary,{toolScope:uf(o.toolScope,n)}),requiresActivationReview:i.length>0,reviewReasons:i}}function ff(e,t={}){return{participantId:t.participantId?.trim()||t.randomUUID?.()||globalThis.crypto.randomUUID(),presetId:e.id,name:e.name,provider:e.executionTarget.provider,instance:e.executionTarget.instance??void 0,model:e.executionTarget.model??void 0,modelSelection:e.modelSelection??null,roleHint:e.roleHint??void 0}}function _o(e,t){const n=e.name?.trim();if(n)return n;const a=Yl(e.provider,e.instance??null,null).replace(/\s+\u00b7.*$/u,"").trim(),s=new Set((t??[]).map(i=>i.trim().toLowerCase()).filter(i=>i.length>0));if(!s.has(a.toLowerCase()))return a;let o=2;for(;s.has(`${a} ${o}`.toLowerCase());)o+=1;return`${a} ${o}`}function Mn(e){return{participantId:e.participantId?.trim()||e.randomUUID?.()||globalThis.crypto?.randomUUID?.()||`participant-${Date.now()}`,presetId:e.presetId?.trim()||void 0,name:_o({name:e.name,provider:e.provider,instance:e.instance},e.takenNames),provider:Dn(e.provider),instance:e.instance?.trim()||void 0,model:e.model?.trim()||void 0,modelSelection:e.modelSelection??null,roleHint:e.roleHint?.trim()||void 0}}function mf(e,t=Fs){const n=fc(e),a=Number.isFinite(t)?Math.max(0,t):Fs,s=Math.min(Fs,a),o=[n.provider,...aa.filter(d=>d!==n.provider)].slice(0,s),i=[];return o.map((d,c)=>{const u=Mn(c===0?{provider:n.provider,instance:n.instance,model:n.model,modelSelection:n.modelSelection,takenNames:i,randomUUID:()=>globalThis.crypto?.randomUUID?.()??`temp-${d}-${Date.now()}`}:{provider:d,instance:Na(d),model:Ra(d)||void 0,modelSelection:null,takenNames:i,randomUUID:()=>globalThis.crypto?.randomUUID?.()??`temp-${d}-${Date.now()}`});return i.push(u.name),u})}function gf(e){return e.participant.name===_o({provider:e.participant.provider,instance:e.participant.instance??null},e.siblingNames)}function ki(e){if(e.participants.length===0)return e.participants;const[t,...n]=e.participants;if(t.presetId)return e.participants;const a=fc(e.target),s=n.map(d=>d.name),o=gf({participant:t,siblingNames:s})?_o({provider:a.provider,instance:a.instance??null},s):t.name,i={...t,name:o,provider:a.provider,instance:a.instance,model:a.model,modelSelection:a.modelSelection};return i.name===t.name&&i.provider===t.provider&&(i.instance??null)===(t.instance??null)&&(i.model??null)===(t.model??null)&&JSON.stringify(i.modelSelection??null)===JSON.stringify(t.modelSelection??null)?e.participants:[i,...n]}function Ws(e){const t=Dn(e.baseProvider)||aa[0]||"claude",n=[t,...aa.filter(o=>o!==t)],a=new Map(n.map(o=>[o,0]));e.existingParticipants.forEach(o=>{const i=Dn(o.provider);a.set(i,(a.get(i)??0)+1)});const s=n.reduce((o,i)=>o?(a.get(i)??0)<(a.get(o)??0)?i:o:i,n[0]??aa[0]??t);return Mn({provider:s,instance:Na(s),model:Ra(s)||void 0,modelSelection:null,takenNames:e.takenNames??e.existingParticipants.map(o=>o.name),randomUUID:e.randomUUID})}function Pi(e,t,n,a={}){return e!=="group"?[]:a.autoSeedGroupParticipants===!1||t.length>0?t:n()}function Ai(e,t){if(!Number.isFinite(t))return[...e];const n=Math.max(1,Math.trunc(t??Number.POSITIVE_INFINITY));return e.slice(0,n)}function mc(e){const t=[...e.draftParticipantCatIds.map(o=>({key:`cat:${o}`,participantId:o})),...e.draftTemporaryParticipants.map(o=>({key:`temp:${o.participantId}`,participantId:o.participantId}))];if(!e.draftAudienceKeys)return Ai(t.map(o=>o.participantId),e.maxAudienceParticipants);const n=new Map(t.map(o=>[o.key,o.participantId])),a=new Set,s=e.draftAudienceKeys.map(o=>n.get(o)).filter(o=>!!o).filter(o=>a.has(o)?!1:(a.add(o),!0));return s.length>0?Ai(s,e.maxAudienceParticipants):t[0]?.participantId?[t[0].participantId]:[]}function Mr(e){const t=e.draftAudienceKeys??(Number.isFinite(e.maxAudienceParticipants)?e.previousParticipantKeys.slice(0,e.maxAudienceParticipants):e.previousParticipantKeys),n=new Set(e.previousParticipantKeys),a=new Set(e.nextParticipantKeys),o=t.filter((i,d,c)=>c.indexOf(i)===d&&n.has(i)).filter(i=>i!==e.removedParticipantKey&&a.has(i));return o.length===0?e.nextParticipantKeys[0]?[e.nextParticipantKeys[0]]:[]:o}function gc(e){const t=Dn(e);return{provider:t,model:Ra(t)||null,instance:Na(t),modelSelection:null}}function Ri(e,t={}){if(t.includeCompareTarget===!1)return[e];const n=Dn(e.provider),a=aa.find(s=>s!==n)??"codex";return[e,gc(a)]}function Cf(e,t){if(e.length===0)return e;const n=e[0];return n?.provider===t.provider&&(n.instance??null)===(t.instance??null)&&(n.model??null)===(t.model??null)&&JSON.stringify(n.modelSelection??null)===JSON.stringify(t.modelSelection??null)?e:[{provider:t.provider,model:t.model,instance:t.instance,modelSelection:t.modelSelection},...e.slice(1)]}function vf(e,t){const n=new Set(e.map(o=>Dn(o.provider))),a=Dn(t.provider),s=aa.find(o=>!n.has(o))??aa.find(o=>o!==a)??a;return s===a?{provider:a,model:t.model,instance:t.instance,modelSelection:t.modelSelection}:gc(s)}function If(e,t){return e.some(n=>n.presetId===t)}const Sf=[l.chatNewChatDraftDefaultGreeting,l.chatNewChatDraftGreetingNap,l.chatNewChatDraftGreetingKeyboard,l.chatNewChatDraftGreetingLetsGo,l.chatNewChatDraftGreetingStandby,l.chatNewChatDraftGreetingTaskReady,l.chatNewChatDraftGreetingOnDuty];function yf(e){return(e??[]).map(t=>t.trim()).filter(t=>t.length>0)}function bf(e={}){const t=yf(e.pool),n=Sf.map(o=>(e.t??hc)(o)),a=t.length>0?t:n,s=e.random??Math.random;return a[Math.floor(s()*a.length)]}const xf=["post","photo","video","music","file"],wf="v1",lo="cats:",Cc="companion";function Fo(e){const t=typeof e=="string"?e.trim():"";if(!t.toLowerCase().startsWith(`${lo}//`))return{status:"invalid",rawText:e,reason:"wrong_scheme"};const a=t.slice(`${lo}//`.length),s=a.indexOf("/");if((s>=0?a.slice(0,s):a).toLowerCase()!==Cc)return{status:"invalid",rawText:e,reason:"wrong_host"};const i=s>=0?a.slice(s+1):"",d=i.length===0?[]:i.split("/"),c=[];for(const S of d)try{c.push(decodeURIComponent(S))}catch{return{status:"invalid",rawText:e,reason:"malformed_percent_encoding"}}const u=c[0];if(typeof u=="string"&&u!==wf)return{status:"unsupported_version",rawText:e,version:u};if(c.length!==5)return{status:"invalid",rawText:e,reason:"bad_segment_count"};const[h,f,m,v,C]=c;return f.length===0||m.length===0||C.length===0?{status:"invalid",rawText:e,reason:"empty_path_segment"}:kf(v)?{status:"parsed",reference:{version:h,scopeId:f,catId:m,type:v,targetId:C,surface:"companion"}}:{status:"invalid",rawText:e,reason:"unknown_target_type"}}function kf(e){return xf.includes(e)}const Ni=1;function Pf(e){if(!Ti(e)||e.schemaVersion!==Ni)return null;const t=e.referenceText;if(typeof t!="string")return null;const n=Fo(t);if(n.status!=="parsed")return null;const a=n.reference,s=Us(e.title)??"",o=Us(e.capturedAt)??"";return o.length===0?null:{schemaVersion:Ni,referenceText:t,reference:a,title:s,subtitle:Ks(e.subtitle),description:Ks(e.description),thumbnailUrl:Ks(e.thumbnailUrl),catName:Us(e.catName)??"Companion",capturedAt:o,snapshot:Ti(e.snapshot)?e.snapshot:null}}function Ti(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ks(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Us(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const Af=`${lo}//${Cc}/`,Rf=/[\s<>'" ]/u;function Nf(e){if(typeof e!="string"||e.length===0)return[];const t=[],n=e.toLowerCase(),a=Af.toLowerCase();let s=0;for(;s<e.length;){const o=n.indexOf(a,s);if(o===-1)break;const i=Tf(e,o),d=e.slice(o,i),c=Fo(d);t.push({start:o,end:i,rawText:d,parseResult:c}),s=i}return t}function Tf(e,t){for(let n=t;n<e.length;n+=1){const a=e.charAt(n);if(Rf.test(a))return n}return e.length}function jf(e){return e.filter(t=>t.status==="active").length}function Lf(e){return e.roomMode==="direct_message"?"direct_message":"chat_channel"}function vc(e){const t=Lf({roomMode:e.roomMode,participants:e.participants});return e.channelKind==="direct_message"||t==="direct_message"?"direct_message":"chat_channel"}function Ic(e){return e.assignedParticipants&&e.assignedParticipants.length>0?e.assignedParticipants:e.assignedCats&&e.assignedCats.length>0?e.assignedCats:e.participantAssignments&&e.participantAssignments.length>0?e.participantAssignments:e.catAssignments??[]}function Mf(e){return jf(Ic(e))}function Wo(e){return Mf(e)>0}function Ef(e){return vc({channelKind:e.channelKind,roomMode:e.roomRouting?.mode==="direct_message"?"direct_message":"chat_channel",participants:Ic(e)})}function Ko(e){return Ef(e)==="direct_message"}function Sc(e){return!Ko(e)&&!Wo(e)&&!!e.pendingProvider?.trim()}function sa(e){return!Ko(e)&&!Wo(e)}function Df(e){return!Ko(e)&&Wo(e)}function co(e){return Df(e)}function Lw(e){return vc({channelKind:e.channelKind,roomMode:e.roomMode==="direct_message"?"direct_message":"chat_channel",participants:[]})==="direct_message"}const ji=250,Bf=4e3;let Of=1;function _f(){const[e,t]=p.useState([]),n=p.useRef(new Map),a=p.useCallback(i=>{t(c=>c.map(u=>u.id===i?{...u,fading:!0}:u));const d=setTimeout(()=>{t(c=>c.filter(u=>u.id!==i)),n.current.delete(i)},ji);n.current.set(i,d)},[]),s=p.useCallback(i=>{const d=Of++,c=i.level??"info";if(t(u=>[...u,{id:d,title:i.title,message:i.message,level:c,fading:!1}]),c!=="error"){const u=setTimeout(()=>a(d),Bf);n.current.set(d,u)}},[a]),o=p.useCallback(()=>{t(d=>d.map(c=>({...c,fading:!0})));const i=setTimeout(()=>{t([]),n.current.clear()},ji);n.current.set(-1,i)},[]);return p.useEffect(()=>()=>{for(const i of n.current.values())clearTimeout(i)},[]),{notifications:e,notify:s,dismiss:a,dismissAll:o}}const Ff={info:"notificationInfo",success:"notificationSuccess",warning:"notificationWarning",error:"notificationError"};function Wf({notifications:e,onDismiss:t}){const{t:n}=Q();return e.length===0?null:r.jsx("div",{className:"notificationContainer",children:e.map(a=>r.jsxs("div",{className:`notification ${Ff[a.level]}`+(a.fading?" notificationFading":""),children:[r.jsxs("div",{className:"notificationBody",children:[r.jsx("p",{className:"notificationTitle",children:a.title}),a.message?r.jsx("p",{className:"notificationMessage",children:a.message}):null]}),r.jsx("button",{className:"notificationDismiss",type:"button",onClick:()=>t(a.id),"aria-label":n(l.designNotificationDismissLabel),children:"✕"})]},a.id))})}function es(e){if(e.channelKind==="direct_message"||e.roomRouting?.mode==="direct_message")return"direct_message";const t=e.assignedCats.filter(n=>n.status==="active").length;return t===0?"default_chat":t>0?"participant_chat":"default_chat"}function ts(e){return e==="direct_message"}function yc(e){return e==="default_chat"}const Kf=ia("en");function Uf(e,t){return!e||!t?!1:ts(es(e))&&e.roomRouting.defaultRecipientId===t}function $f(e){const{draftDefaultRecipientCatId:t,routeChannelId:n,showingMyCatDirectLane:a,state:s}=e,o=s.status==="ready"?s.payload:null,i=s.status==="ready"?s.payload.chat:null,d=Jl(i?.selectedChannel??null),c=i?.selectedChannelId??null,u=d?.id??null,h=Ju(d),f=!!(n&&i?.channels.some(g=>g.id===n)),m=n?i?.channels.find(g=>g.id===n)?.title??null:null,v=a&&t&&i?Ql(i.channels,t):null,C=n&&d?.id===n?d:null,S=a&&t&&Uf(d,t)?d:null,y=i?[i.selectedChannelId,d?.id??"",d?.updatedAt??"",d?.messages.length??0,d?.roomRouting.workflow.activeTurn?.updatedAt??"",i.channels.length].join("|"):"";return{readyPayload:o,readyChat:i,readySelectedChannel:d,selectedChannelId:c,selectedChannelViewId:u,selectedChannelEntryLifecycle:h,routeChannelExists:f,routeChannelTitle:m,routeDirectLaneSummary:v,selectedChannel:C,selectedDirectLane:S,operatorRefreshKey:y}}function Hf(e){const{addCatOpen:t,draftCatIds:n,draftDefaultRecipientCatId:a,pathname:s,payload:o,routeDirectLaneSummary:i,selectedChannel:d,selectedDirectLane:c,showingMyCatDirectLane:u,showingNewChatDraft:h,t:f=Kf}=e,m=s.startsWith("/settings")?"settings":"chats",v=u?c:null,C=d??v,S=C?es(C):null,y=d?es(d):null,g=ts(S)?C?.roomRouting.defaultRecipientId??null:null,x=C?.assignedCats.filter(b=>b.status==="active")??[],I=new Set(C?.assignedCats.map(b=>b.catId)??[]),k=Qu(o)??f(l.sharedOrchestratorFallbackName),P=o.chat.cats.find(b=>b.id===o.chat.bossCatId)?.avatarColor??null,A=!!o.chat.bossCatId&&!yc(y)&&!ts(y)&&!x.some(b=>b.catId===o.chat.bossCatId),M=o.chat.cats.filter(b=>b.status==="active"&&b.id!==o.chat.bossCatId&&Xl(b)),D=M.length,N=new Set(n);return{surface:m,directLaneChannel:v,activeConversationMode:S,activeMyCatId:g,activeAssignedCats:x,assignedCatIds:I,bossCatName:k,bossCatAvatarColor:P,showBossCatAvatar:A,selectableCats:M,assignableCatCount:D,draftCatIdSet:N,showDirectLaneBoot:!!(i&&!v),showAddCatPanel:t&&(!!d||h&&!a)}}function qf({state:e,BootShell:t,unavailableTitle:n,renderReady:a}){const{t:s}=Q();return e.status==="loading"?r.jsx(t,{}):e.status==="error"?r.jsx("div",{className:"screen screenCentered",children:r.jsxs("div",{className:"errorPanel",children:[r.jsx("p",{className:"eyebrow",children:s(l.sharedProductRendererErrorEyebrow)}),r.jsx("h1",{children:n}),r.jsx("p",{children:e.message})]})}):r.jsx(r.Fragment,{children:a(e.payload)})}function Gf({sidebarOpen:e,sidebar:t,mainContent:n,confirmDialog:a,onConfirmClose:s}){return r.jsxs("div",{className:e?"screen claudeShell":"screen claudeShell claudeShellSidebarCollapsed",children:[t,r.jsx("main",{className:"canvas",children:n}),r.jsx(Xu,{dialog:a,onClose:s})]})}function Vf({payload:e,sidebarOpen:t,sidebar:n,settingsMode:a,busy:s,appContent:o,confirmDialog:i,onPayloadUpdate:d,onFeedback:c,onBusy:u,onResetSetup:h,onConfirmClose:f}){return r.jsx(Gf,{sidebarOpen:t,sidebar:n,mainContent:a?r.jsx(Zu,{payload:e,onPayloadUpdate:d,busy:s,onFeedback:c,onBusy:u,onResetSetup:h}):o,confirmDialog:i,onConfirmClose:f})}function zf(){const[e,t]=p.useState(!1),[n,a]=p.useState(()=>ep(typeof window>"u"?null:window.localStorage)),[s,o]=p.useState(null),[i,d]=p.useState(!1),[c,u]=p.useState(!1),[h,f]=p.useState(!1),m=p.useRef(null),v=p.useRef(null),C=p.useRef(null),S=p.useRef(null),y=p.useRef(null),g=p.useRef(null);p.useEffect(()=>{if(!s&&!i&&!h&&!c)return;function P(A){const M=A.target;if(s){const D=document.querySelector(".recentOverflowMenu")??document.querySelector(".myCatOverflowMenu"),N=A.target.closest?.(".recentOverflowButton, .myCatOverflowButton");!D?.contains(M)&&!N&&o(null)}i&&v.current&&!v.current.contains(M)&&d(!1),h&&y.current&&!y.current.contains(M)&&f(!1),c&&C.current&&!C.current.contains(M)&&u(!1)}return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[s,i,h,c]),p.useEffect(()=>{tp(typeof window>"u"?null:window.localStorage,n)},[n]);const x=p.useCallback(P=>{P.style.height="auto";const A=200;P.scrollHeight>A?(P.style.height=`${A}px`,P.style.overflowY="auto"):(P.style.height=`${P.scrollHeight}px`,P.style.overflowY="hidden")},[]);function I(){a(P=>(P&&t(!1),!P))}function k(P){if(n)return;const A=P.target;A.closest('button, a, input, textarea, select, [role="button"]')||A.closest(".accountMenu")||a(!0)}return{accountMenuOpen:e,setAccountMenuOpen:t,sidebarOpen:n,setSidebarOpen:a,overflowMenuOpenId:s,setOverflowMenuOpenId:o,plusMenuOpen:i,setPlusMenuOpen:d,addCatOpen:c,setAddCatOpen:u,channelPlusMenuOpen:h,setChannelPlusMenuOpen:f,accountMenuRef:m,plusMenuRef:v,addCatPanelRef:C,fileInputRef:S,channelPlusMenuRef:y,channelFileInputRef:g,autoResize:x,onToggleSidebar:I,onCollapsedSidebarClick:k}}const Yf=300;function Jf(e){return e.surface==="chat"&&e.directLaneCatId?`chat:${e.directLaneCatId}`:e.surface}function Qf(e){const{t}=Q(),{onSelectPath:n,surface:a,directLaneCatId:s=null}=e,[o,i]=p.useState(""),[d,c]=p.useState(""),[u,h]=p.useState(""),[f,m]=p.useState([]),[v,C]=p.useState(!1),[S,y]=p.useState(""),g=p.useRef(fi(e.initialPreferences)),x=p.useRef(new Map),I=p.useRef(new Map),k=p.useRef(null),P=p.useCallback(b=>{let T=b;for(const E of I.current.values())T=Ms(T,E.scope,E.path);for(const E of x.current.values())T=Ms(T,E.scope,E.path);return T},[]);p.useEffect(()=>{const b=fi(e.initialPreferences);g.current=P(b)},[e.initialPreferences,P]);const A=p.useCallback(()=>{for(const[b,T]of x.current)I.current.has(b)||(x.current.delete(b),I.current.set(b,T),np({surface:T.scope.surface,directLaneCatId:T.scope.directLaneCatId??null,path:T.path}).catch(()=>{}).finally(()=>{I.current.get(b)===T&&I.current.delete(b),x.current.has(b)&&A()}))},[]),M=p.useCallback(b=>{if(k.current&&(clearTimeout(k.current),k.current=null),b){A();return}k.current=setTimeout(()=>{k.current=null,A()},Yf)},[A]),D=p.useCallback((b,T=!1)=>{const E={surface:a,directLaneCatId:s},O=Jf(E),H=mi(g.current,E),U=x.current.has(O);H===b&&!U||(g.current=Ms(g.current,E,b),x.current.set(O,{scope:E,path:b}),M(T))},[s,M,a]);p.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),A()},[A]);const N=p.useCallback(async b=>{C(!0),y("");try{const T=await wi(b);c(T.current),h(T.parent),i(T.current),m(T.entries),y(T.error??""),T.error||D(T.current)}catch(T){y(T instanceof Error?T.message:t(l.sharedFolderBrowserLoadError)),m([]),b&&i(b)}finally{C(!1)}},[D,t]),R=p.useCallback(async b=>{const T=mi(g.current,{surface:a,directLaneCatId:s}),E=b?.trim()?b:T;C(!0),y(""),i(E??"");try{const O=await ap({browse:wi,requestedPath:b??null,rememberedPath:T});c(O.current),h(O.parent),i(O.current),m(O.entries),y(O.error??""),O.error||D(O.current)}catch(O){y(O instanceof Error?O.message:t(l.sharedFolderBrowserLoadError)),m([])}finally{C(!1)}},[s,D,a,t]),w=p.useCallback(()=>{!d||S||(D(d,!0),n(d))},[d,S,n,D]);return{browseFolder:N,folderBrowseCurrentPath:d,folderBrowseEntries:f,folderBrowseError:S,folderBrowseLoading:v,folderBrowseParentPath:u,folderBrowsePath:o,openFolderBrowser:R,selectCurrentFolder:w,setFolderBrowsePath:i}}const Xf="container-chat-root";function bc(e){return`conversation-channel-${e}`}function Zf(e){return Xf}function ns(e,t,n){return`lane-${e}-${t||n}`}function Li(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ir(e){return typeof e=="string"&&e.trim().length>0?e:null}function em(e){return e==="text"||e==="tool"||e==="status"?e:null}function tm(e){return e==="streaming"||e==="complete"||e==="error"?e:null}function uo(e){const t=Li(e.block);if(!t)return null;const n=ir(t.id),a=em(t.kind),s=tm(t.status),o=typeof t.index=="number"&&Number.isFinite(t.index)?t.index:null;return!n||!a||!s||o===null?null:{id:n,index:o,kind:a,status:s,title:ir(t.title),text:ir(t.text)??"",toolName:ir(t.toolName),toolId:ir(t.toolId),metadata:Li(t.metadata)}}function xc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function rn(e){return typeof e=="string"&&e.length>0?e:null}function Mi(e){return rn(e.toolName)??rn(e.name)}function Ei(e){return rn(e.toolId)??rn(e.toolUseId)??rn(e.tool_use_id)??rn(e.id)}function nm(e){const t=e.toolArgs??e.arguments??e.input;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function am(e){return Array.isArray(e)?rm(e).flatMap(t=>{if(typeof t=="string")return t.length>0?[t]:[];const n=xc(t);if(!n)return[];const a=rn(n.text)??rn(n.content)??"";return a.length>0?[a]:[]}).join(""):""}function $s(e){return rn(e.text)??rn(e.content)??am(e.content)??""}function rm(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n=="string"){t.push(n);continue}const a=xc(n);if(!a)continue;const s=a.content;if(Array.isArray(s)){t.push(...s);continue}t.push(a)}return t}function wc(e){if(typeof e=="string")return e.length>0?{kind:"text",text:e,toolName:null,toolId:null}:null;if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e,n=typeof t.kind=="string"?t.kind:typeof t.type=="string"?t.type:null,a=n==="output_text"?"text":n;if(a==="text"||!a&&(typeof t.text=="string"||typeof t.content=="string")){const s=$s(t);return s.length>0?{kind:"text",text:s,toolName:null,toolId:null}:null}if(a==="tool_use"){const s=nm(t);return{kind:"tool_use",text:$s(t),toolName:Mi(t),toolId:Ei(t),...s?{toolArgs:s}:{}}}return a==="tool_result"?{kind:"tool_result",text:$s(t),toolName:Mi(t),toolId:Ei(t),...typeof t.isError=="boolean"?{isError:t.isError}:{}}:null}const Di=200,Bi="__catsLiveTraceStore",sm="__catsLiveTrace",om="__catsLiveTraceEnabled";function im(e){const t=Uo();e&&!t.enabled&&(t.entries.length=0,t.seq=0,t.lastSignature=null),t.enabled=e,$o(t)}function kc(){return Uo().enabled}function Pc(e){const t=Uo();if(!t.enabled)return;const n=e.signature??um(e);n&&t.lastSignature===n||(t.lastSignature=n,t.seq+=1,t.entries.push(cm("browser",t.seq,e)),dm(t.entries),$o(t))}function Uo(){const e=globalThis,t=e[Bi];if(lm(t))return t;const n={enabled:!1,seq:0,entries:[],lastSignature:null};return e[Bi]=n,$o(n),n}function lm(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;const t=e;return Array.isArray(t.entries)&&typeof t.enabled=="boolean"&&typeof t.seq=="number"}function $o(e){const t=globalThis;t[sm]=e.entries,t[om]=e.enabled}function cm(e,t,n){return{seq:t,at:new Date().toISOString(),origin:e,event:n.event,channelId:n.channelId??null,containerId:n.containerId??null,conversationId:n.conversationId??null,turnId:n.turnId??null,laneId:n.laneId??null,sourceMessageId:n.sourceMessageId??null,targetStateId:n.targetStateId??null,sessionId:n.sessionId??null,participantId:n.participantId??null,catId:n.catId??null,speakerLabel:n.speakerLabel??null,activeTurnUpdatedAt:n.activeTurnUpdatedAt??null,visible:n.visible??null,reason:n.reason??null,details:n.details??null}}function dm(e){e.length<=Di||e.splice(0,e.length-Di)}function um(e){return[e.event,e.channelId??"",e.containerId??"",e.conversationId??"",e.turnId??"",e.laneId??"",e.sourceMessageId??"",e.targetStateId??"",e.sessionId??"",e.participantId??"",e.catId??"",e.speakerLabel??"",e.activeTurnUpdatedAt??"",e.visible==null?"":e.visible?"1":"0",e.reason??"",JSON.stringify(e.details??{})].join("::")}const Oi=8,_i=220,Ac=1200,ur={active:!1,phase:"idle",sourceMessageId:null,laneId:null,targetStateId:null,segmentIndex:0,sessionId:null,identityParticipantId:null,participantId:null,catId:null,activeCatIds:[],catName:null,speakerLabel:null,sessionStartedAt:null,requiresSessionStartConfirmation:!1,progressText:"",progressKind:null,tools:[],contentBlocks:[],events:[],segments:[],lastActivityAtMs:null,lastVisibleContentAtMs:null};function Ho(e){const t=ge(e.sourceMessageId)??"no-source",n=ge(e.laneId)??e.targetStateId??ge(e.sessionId)??e.identityParticipantId??e.participantId??e.catId??ge(e.speakerLabel)??"anonymous";return`${t}:${n}:segment:${e.segmentIndex}`}function Sn(e){const t=e.catId??null,n=e.segmentIndex??0,a=e.activeCatIds?.filter(s=>s.trim().length>0)??(t?[t]:[]);return{id:e.id?.trim()||Ho({sourceMessageId:e.sourceMessageId??null,laneId:e.laneId??null,targetStateId:e.targetStateId??null,sessionId:e.sessionId??null,identityParticipantId:e.identityParticipantId??e.participantId??null,participantId:e.participantId??null,catId:t,speakerLabel:e.speakerLabel??null,segmentIndex:n}),phase:e.phase,sourceMessageId:e.sourceMessageId??null,laneId:e.laneId??null,targetStateId:e.targetStateId??null,segmentIndex:n,sessionId:e.sessionId??null,identityParticipantId:e.identityParticipantId??e.participantId??null,participantId:e.participantId??null,catId:t,activeCatIds:a,catName:e.catName??null,speakerLabel:e.speakerLabel??null,sessionStartedAt:e.sessionStartedAt??null,requiresSessionStartConfirmation:e.requiresSessionStartConfirmation===!0,progressText:e.progressText??"",progressKind:e.progressKind??null,tools:e.tools??[],contentBlocks:e.contentBlocks??[],events:e.events??[],lastActivityAtMs:typeof e.lastActivityAtMs=="number"?e.lastActivityAtMs:null,lastVisibleContentAtMs:typeof e.lastVisibleContentAtMs=="number"?e.lastVisibleContentAtMs:null}}function Rc(e){if(e.length<=1)return[...e];const t=new Set,n=[];for(let a=e.length-1;a>=0;a-=1){const s=e[a];t.has(s.id)||(t.add(s.id),n.push(s))}return n.reverse()}function Ge(e){const t=Ve(e);return!e?.active||t.length===0?null:t.at(-1)??null}function Ve(e){return e?.active?e.segments.length>0?Rc(e.segments):e.phase==="idle"?[]:[Sn({phase:e.phase,targetStateId:e.targetStateId,sourceMessageId:e.sourceMessageId,laneId:e.laneId,segmentIndex:e.segmentIndex,sessionId:e.sessionId,identityParticipantId:e.identityParticipantId,participantId:e.participantId,catId:e.catId,activeCatIds:e.activeCatIds,catName:e.catName,speakerLabel:e.speakerLabel,sessionStartedAt:e.sessionStartedAt,requiresSessionStartConfirmation:e.requiresSessionStartConfirmation,progressText:e.progressText,progressKind:e.progressKind,tools:e.tools,contentBlocks:e.contentBlocks,events:e.events})]:[]}function Ze(e,t=e.length>0){const n=Rc(e),a=n.at(-1)??null;return!a||!t?ur:{active:!0,phase:a.phase,sourceMessageId:a.sourceMessageId,laneId:a.laneId,targetStateId:a.targetStateId,segmentIndex:a.segmentIndex,sessionId:a.sessionId,identityParticipantId:a.identityParticipantId,participantId:a.participantId,catId:a.catId,activeCatIds:a.activeCatIds,catName:a.catName,speakerLabel:a.speakerLabel,sessionStartedAt:a.sessionStartedAt,requiresSessionStartConfirmation:a.requiresSessionStartConfirmation,progressText:a.progressText,progressKind:a.progressKind,tools:a.tools,contentBlocks:a.contentBlocks,events:a.events,segments:n,lastActivityAtMs:a.lastActivityAtMs,lastVisibleContentAtMs:a.lastVisibleContentAtMs}}function pm(e,t){return!e.active||e.segments.length===0?Ze([t]):Ze([...e.segments.slice(0,-1),t])}function Nc(e,t){const n=Ge(e);if(!n)return Ze([t]);const a=n.phase==="sealed"?n:{...n,phase:"sealed"};return Ze([...e.segments.slice(0,-1),a,t])}function po(e){return e.identityParticipantId??e.participantId??null}function Tc(e,t){return e?Ss(e,t):!1}function Ss(e,t){const n=e.sourceMessageId??null,a=t.sourceMessageId??null,s=e.laneId??null,o=t.laneId??null,i=e.targetStateId??null,d=t.targetStateId??null,c=po(e),u=po(t),h=e.catId??null,f=t.catId??null,m=e.speakerLabel??null,v=t.speakerLabel??null;return s!==null&&o!==null?s===o:i!==null&&d!==null?i===d:n===a&&c===u&&h===f&&m===v}function hm(e){const t=[];for(const n of e){const a=[...n.contentBlocks].sort((d,c)=>d.index-c.index);if(a.length===0){t.push(n);continue}let s=[],o=0;const i=d=>{s.length!==0&&(t.push(Sn({...n,id:Ho({sourceMessageId:n.sourceMessageId,laneId:n.laneId,targetStateId:n.targetStateId,sessionId:n.sessionId,participantId:n.participantId,catId:n.catId,speakerLabel:n.speakerLabel,segmentIndex:n.segmentIndex+o}),phase:d,segmentIndex:n.segmentIndex+o,contentBlocks:s})),o+=1,s=[])};for(let d=0;d<a.length;d+=1){const c=a[d],u=s.some(h=>h.kind==="text");if(c.kind==="text"){if(s.length===0||!u){s.push(c);continue}i("sealed"),s.push(c);continue}if(s.length===0||!u){s.push(c);continue}i("sealed"),s.push(c)}i(n.phase)}return t}function fm(e,t){const n=Ge(e);return n?pm(e,t(n)):e}function jc(e,t,n){const a=Ve(e);return a[t]?Ze(a.map((o,i)=>i===t?n(o):o)):e}function mm(e,t,n){const a=Ve(e),s=a.findIndex(t);if(s<0)return e;const o=a.map((i,d)=>d===s?n(i):i);return Ze(o)}function Lc(e,t){const n=Ve(e);for(let a=n.length-1;a>=0;a-=1)if(Ss(n[a],t))return a;return-1}function qo(e,t){const n=Go(e,t),a=Lc(e,n);if(a>=0){const o=Ve(e);return{segmentIndex:a,segment:o[a]??null}}const s=Ge(e);return{segmentIndex:s?Ve(e).length-1:-1,segment:s}}function yn(e,t,n){const a=qo(e,t);return a.segmentIndex<0||!a.segment?e:jc(e,a.segmentIndex,n)}function gm(e,t,n){const a=Ve(e),s=a[t];if(!s)return Nc(e,n);const o=s.phase==="sealed"?s:{...s,phase:"sealed"};return Ze([...a.slice(0,t),o,n,...a.slice(t+1)])}function xa(e){return e.contentBlocks.some(t=>t.kind==="text"&&t.text.trim().length>0)}function Mc(e){return e.contentBlocks.some(t=>t.kind==="text"&&t.status==="streaming"&&t.text.trim().length>0)}function Cm(e,t){return e.phase==="streaming"&&Mc(e)&&e.lastVisibleContentAtMs!=null&&t-e.lastVisibleContentAtMs>=Ac}function vm(e,t=Date.now()){if(!e?.active)return null;const n=Ve(e).filter(a=>a.phase==="streaming"&&Mc(a)).map(a=>a.lastVisibleContentAtMs).filter(a=>typeof a=="number").map(a=>a+Ac).filter(a=>a>t);return n.length===0?null:Math.min(...n)}function Im(e,t){const n=e[t];if(!n||!xa(n))return null;let a=0;for(let s=0;s<e.length;s+=1){const o=e[s];if(!(!xa(o)||!Tc(o,n))){if(s===t)return a;a+=1}}return null}function Ec(e){return e.contentBlocks.length>0&&e.contentBlocks.every(t=>Oc(t))}function ho(e,t){return e.id===t.id||e.index===t.index&&e.kind===t.kind}function Hs(e){return e.contentBlocks.length>0||e.progressText.trim().length>0||e.events.length>0||e.tools.length>0}function Sm(e){return e.progressText.trim().length>0||e.events.length>0||e.tools.length>0?!0:e.contentBlocks.some(t=>t.kind==="text"?t.text.trim().length>0:t.kind==="tool"?!0:t.kind==="status"?t.text.trim().length>0:!1)}function Dc(e){return e.phase==="waiting"||e.contentBlocks.length>0||e.progressText.trim().length>0||e.progressKind!==null||e.events.length>0||e.tools.length>0}function Bc(e){const t=e.revealIdentity===!0;return Ze([Sn({phase:"waiting",sourceMessageId:e.sourceMessageId??null,laneId:e.laneId??null,targetStateId:e.targetStateId??null,segmentIndex:e.segmentIndex??0,sessionId:e.sessionId??null,identityParticipantId:e.participantId??null,participantId:t?e.participantId??null:null,catId:t?e.catId:null,speakerLabel:t?e.speakerLabel:null,sessionStartedAt:e.sessionStartedAt??null,requiresSessionStartConfirmation:e.requiresSessionStartConfirmation===!0})])}function Go(e,t){const n=Ge(e),a=n?.sourceMessageId??e.sourceMessageId,s=n?.laneId??e.laneId,o=n?.targetStateId??e.targetStateId,i=Object.prototype.hasOwnProperty.call(t,"sourceMessageId"),d=Object.prototype.hasOwnProperty.call(t,"laneId"),c=Object.prototype.hasOwnProperty.call(t,"identityParticipantId"),u=Object.prototype.hasOwnProperty.call(t,"participantId"),h=Object.prototype.hasOwnProperty.call(t,"catId"),f=Object.prototype.hasOwnProperty.call(t,"speakerLabel"),m=Object.prototype.hasOwnProperty.call(t,"targetStateId"),v=n?.identityParticipantId??e.identityParticipantId,C=u?nn(t.participantId):n?.participantId??e.participantId,S=c?nn(t.identityParticipantId):u?nn(t.participantId):v,y=h?nn(t.catId):n?.catId??e.catId,g=f?nn(t.speakerLabel):n?.speakerLabel??e.speakerLabel;return{sourceMessageId:i?nn(t.sourceMessageId)??a:a,laneId:d?nn(t.laneId)??s:s,targetStateId:m?nn(t.targetStateId)??o:o,identityParticipantId:S,participantId:C,catId:y,activeCatIds:y?[y]:[],speakerLabel:g}}function ym(e,t){const n=Ge(e),a=Object.prototype.hasOwnProperty.call(t,"sessionId"),s=Object.prototype.hasOwnProperty.call(t,"sessionStartedAt"),o=Object.prototype.hasOwnProperty.call(t,"requiresSessionStartConfirmation");return{sessionId:a?nn(t.sessionId):n?.sessionId??e.sessionId,sessionStartedAt:s?nn(t.sessionStartedAt):n?.sessionStartedAt??e.sessionStartedAt,requiresSessionStartConfirmation:o?t.requiresSessionStartConfirmation===!0:n?.requiresSessionStartConfirmation??e.requiresSessionStartConfirmation}}function bm(e,t,n,a=Date.now()){if(!e.active)return e;const s=wm(e,t,n);switch(t){case"progress":return Nm(s,n,a);case"text":return Tm(s,n,a);case"tool_use":return Lm(s,n,a);case"tool_result":return Mm(s,n,a);case"content_block":return Em(s,n,a);case"result":return Wi(s,n,a);case"session_closed":return qo(s,n).segment?.phase==="waiting"?s:Wi(s,n,a);case"error":return Dm(s,n,a);default:return s}}function xm(e,t,n,a){if(!e)return!1;const s=!Ss(e,t);if(e.phase==="sealed"){if(n==="content_block"){const o=uo(a);if(o&&e.contentBlocks.some(i=>ho(i,o)))return!1}return!0}if(s)return Hs(e);if(e.phase==="waiting"&&!Hs(e)||e.phase==="streaming"&&!Hs(e))return!1;switch(n){case"progress":case"tool_use":case"tool_result":case"error":return xa(e);case"content_block":{const o=uo(a);if(!o)return!1;if(o.kind==="text"){if(Ec(e))return!1;const i=e.contentBlocks.some(d=>d.id===o.id);return xa(e)&&!i}return xa(e)}default:return!1}}function Fi(e,t,n,a){const s=Tc(e,t);return Sn({phase:a,sourceMessageId:t.sourceMessageId,laneId:t.laneId,targetStateId:t.targetStateId,segmentIndex:s&&e?e.segmentIndex+1:0,sessionId:n.sessionId,identityParticipantId:t.identityParticipantId,participantId:t.participantId,catId:t.catId,activeCatIds:t.activeCatIds,speakerLabel:t.speakerLabel,sessionStartedAt:n.sessionStartedAt,requiresSessionStartConfirmation:n.requiresSessionStartConfirmation})}function wm(e,t,n){const a=Go(e,n),s=ym(e,n),o=Ve(e),i=Lc(e,a),d=i>=0?o[i]??null:Ge(e);if(xm(d,a,t,n)){const u=Fi(d,a,s,t==="session_closed"?"waiting":"streaming");return i>=0&&i<o.length-1?gm(e,i,u):Nc(e,u)}if(!d)return Ze([Fi(null,a,s,"waiting")]);const c=u=>({...u,...a,...s,id:Ho({sourceMessageId:a.sourceMessageId,laneId:a.laneId,targetStateId:a.targetStateId,sessionId:s.sessionId,identityParticipantId:a.identityParticipantId,participantId:a.participantId,catId:a.catId,speakerLabel:a.speakerLabel,segmentIndex:u.segmentIndex})});return i>=0?jc(e,i,c):fm(e,c)}function km(e){if(!e)return"";const t=Ve(e);return[e.active?"1":"0",t.map(n=>[n.id,n.phase,n.sourceMessageId??"",n.laneId??"",n.targetStateId??"",String(n.segmentIndex),n.sessionId??"",n.identityParticipantId??"",n.participantId??"",n.activeCatIds.join("|"),n.catId??"",n.speakerLabel??"",n.sessionStartedAt??"",n.requiresSessionStartConfirmation?"1":"0",n.progressText??"",n.tools.map(a=>`${a.toolId}:${a.toolName}:${a.done?"1":"0"}`).join("|"),n.contentBlocks.map(a=>[a.id,String(a.index),a.kind,a.status,a.title??"",a.text,a.toolId??""].join(":")).join("|"),n.events.map(a=>[a.eventType,a.label,a.text,a.tone,a.kind??"",a.toolId??""].join(":")).join("|")].join("~")).join("::")].join("::")}function Pm(e,t){return(e.phase==="waiting"||e.phase==="streaming")&&e.requiresSessionStartConfirmation&&!Fc(t,Ze([e]),e.sessionStartedAt)?Sn({...e,phase:"waiting",participantId:null,catId:null,activeCatIds:[],catName:null,speakerLabel:null,progressText:"",progressKind:null,tools:[],contentBlocks:[],events:[]}):e}function Am(e,t,n,a=t,s=Date.now()){if(!e?.active)return e??null;const o=Ve(e),i=hm(o),d=i.map(g=>Pm(g,a)),c=d.filter((g,x)=>{const I=d.slice(x+1).some(P=>!Ss(g,P)),k=Im(i,x)??g.segmentIndex;return!(qm(t,g,k)||g.phase==="sealed"&&I&&ge(g.sourceMessageId)&&xa(g)&&ys(t,g.sourceMessageId,Ze([g]))||g.phase==="sealed"&&I&&!Sm(g)||x>0&&!Dc(g))}),u=g=>{if(!n||g.events.some(A=>A.eventType==="result"||A.eventType==="error"))return null;const I=Date.parse(n);if(!Number.isFinite(I))return null;const k=Ze([g]);return(Sr(k)?Er(t,A=>fo(A,k)):Er(t))>I?null:Sn({phase:"waiting",sourceMessageId:g.sourceMessageId,laneId:g.laneId,targetStateId:g.targetStateId,segmentIndex:g.segmentIndex+1,sessionId:g.sessionId,identityParticipantId:g.identityParticipantId,participantId:g.participantId,catId:g.catId,activeCatIds:g.activeCatIds,catName:g.catName,speakerLabel:g.speakerLabel,sessionStartedAt:g.sessionStartedAt,requiresSessionStartConfirmation:g.requiresSessionStartConfirmation,lastActivityAtMs:g.lastActivityAtMs,lastVisibleContentAtMs:g.lastVisibleContentAtMs})};if(c.length===0){if(o.length>0){const g=u(o.at(-1));if(g)return Ze([g])}return null}const h=c.at(-1);if(h.phase==="streaming"&&Cm(h,s)){const g=Sn({...h,phase:"sealed"}),x=u(g);x&&(c[c.length-1]=g,c.push(x))}else if(h.phase==="sealed"){const g=u(h);g&&c.push(g)}const m=c.length===i.length&&i.length===o.length&&e.segments.length===0&&c.every((g,x)=>g===i[x])?e:Ze(c);if(!n)return m;const v=Date.parse(n);if(Number.isNaN(v))return m;const C=Ge(m);if((C?.laneId||C?.targetStateId)&&C.phase!=="sealed")return qs({liveIndicator:m,messages:t,activeTurnUpdatedAt:n,visible:!0,reason:"segment_timeline_visible",latestReplyTimestamp:Number.NEGATIVE_INFINITY}),m;if(Sr(m)){const g=Er(t,I=>fo(I,m)),x=g<v;return qs({liveIndicator:m,messages:t,activeTurnUpdatedAt:n,visible:x,reason:x?"speaker_still_streaming":"same_speaker_reply_visible",latestReplyTimestamp:g}),x?m:null}const S=Er(t),y=S<v;return qs({liveIndicator:m,messages:t,activeTurnUpdatedAt:n,visible:y,reason:y?"visible_before_identity":"reply_after_active_turn",latestReplyTimestamp:S}),y?m:null}function Rm(e,t,n,a=t,s=Date.now()){const o=Am(e,t,n,a,s),i=t.at(-1);return{visibleLiveIndicator:o,transcriptScrollKey:[t.length,i?.id??"",i?.createdAt??"",km(o)].join("::")}}function Nm(e,t,n){const a=kr(t.text),s=zt(t.metadata),o=typeof s?.kind=="string"?s.kind:null;return a?yn(e,t,i=>({...i,phase:"streaming",progressText:a,progressKind:o,events:ja(i.events,{eventType:"progress",label:Fm(o),text:a,tone:o==="reasoning"?"default":"active",kind:o,toolName:null,toolId:null}),lastActivityAtMs:n,lastVisibleContentAtMs:n})):yn(e,t,i=>({...i,phase:"streaming",...o?{progressKind:o}:{},lastActivityAtMs:n}))}function Tm(e,t,n){const a=typeof t.text=="string"?t.text:"",s=kr(t.text);return!a&&!s?yn(e,t,o=>({...o,phase:"streaming",lastActivityAtMs:n})):yn(e,t,o=>({...o,phase:"streaming",progressText:"",progressKind:null,contentBlocks:jm(o.contentBlocks,a),events:s?ja(o.events,{eventType:"text",label:"Text",text:s,tone:"default",kind:"text",toolName:null,toolId:null}):o.events,lastActivityAtMs:n,lastVisibleContentAtMs:n}))}function jm(e,t){if(!t||e.some(s=>!Oc(s)))return e;const n=e.at(-1);if(n?.kind==="text"&&n.status==="streaming")return e.map(s=>s.id===n.id?{...s,text:s.text+t}:s);const a=e.length>0?Math.max(...e.map(s=>s.index))+1:0;return[...e,{id:`text:${a}`,index:a,kind:"text",status:"streaming",title:null,text:t,toolName:null,toolId:null,metadata:{syntheticTextFallback:!0}}].slice(-12)}function Oc(e){return e.kind==="text"&&e.metadata?.syntheticTextFallback===!0}function Lm(e,t,n){const a=wc({type:"tool_use",...t}),s=(a?.kind==="tool_use"?a.toolName:ge(t.toolName))||"tool",o=a?.kind==="tool_use"?a.toolId:ge(t.toolId);return yn(e,t,i=>{const d=Bm(i.tools,{toolName:s,toolId:o||s});return{...i,phase:"streaming",tools:d,events:ja(i.events,{eventType:"tool_use",label:"Tool",text:`Started ${s}`,tone:"active",kind:"tool",toolName:s,toolId:o||s}),lastActivityAtMs:n}})}function Mm(e,t,n){const a=wc({type:"tool_result",...t}),s=a?.kind==="tool_result"?a.toolId:ge(t.toolId),o=qo(e,t).segment,i=(a?.kind==="tool_result"?a.toolName:ge(t.toolName))||_m(o?.tools??[],s)||"tool",d=kr(a?.kind==="tool_result"?a.text:t.text),c=t.isError===!0,u=d?`${c?"Failed":"Completed"} ${i}: ${d}`:`${c?"Failed":"Completed"} ${i}`;return yn(e,t,h=>({...h,phase:"streaming",tools:Om(h.tools,s,i),events:ja(h.events,{eventType:"tool_result",label:c?"Tool Error":"Tool",text:u,tone:c?"error":"success",kind:"tool",toolName:i,toolId:s||i}),lastActivityAtMs:n}))}function Wi(e,t={},n){return yn(e,t,a=>{const s=a.contentBlocks.some(i=>i.kind==="text"&&i.text.trim().length>0),o=s?"":a.progressText||"Finalizing...";return{...a,phase:"sealed",progressKind:s?null:"finalizing",progressText:o,events:ja(a.events,{eventType:"result",label:"Result",text:"Turn completed.",tone:"success",kind:"finalizing",toolName:null,toolId:null}),lastActivityAtMs:n,lastVisibleContentAtMs:s?a.lastVisibleContentAtMs:n}})}function Em(e,t,n){const a=uo(t);if(!a)return e;const s=i=>{const c=[...(a.kind==="text"&&Ec(i)?[]:i.contentBlocks).filter(u=>!ho(u,a)),a].sort((u,h)=>u.index-h.index).slice(-12);return{...i,phase:i.phase==="sealed"?"sealed":"streaming",contentBlocks:c,lastActivityAtMs:n,lastVisibleContentAtMs:n}},o=mm(e,i=>i.contentBlocks.some(d=>ho(d,a)),s);return o!==e?o:yn(e,t,s)}function Dm(e,t,n){const a=kr(t.text)||"Finishing...";return yn(e,t,s=>({...s,phase:"sealed",progressKind:"error",progressText:a,events:ja(s.events,{eventType:"error",label:"Error",text:a,tone:"error",kind:"error",toolName:null,toolId:null}),lastActivityAtMs:n,lastVisibleContentAtMs:n}))}function Bm(e,t){return e.some(n=>n.toolId===t.toolId&&!n.done)?e:[...e,{...t,done:!1}]}function Om(e,t,n){let a=!1;const s=e.map(o=>t&&o.toolId===t||!t&&!a&&o.toolName===n&&!o.done?(a=!0,{...o,done:!0}):o);return a?s:[...s,{toolName:n,toolId:t||n,done:!0}]}function _m(e,t){return t?e.find(n=>n.toolId===t)?.toolName??null:null}function ja(e,t){if(!t.text)return e;const n=e.at(-1);if(n&&n.eventType===t.eventType&&n.text===t.text&&n.toolId===t.toolId)return e;if(n&&n.eventType==="text"&&t.eventType==="text"){const a=kr(`${n.text} ${t.text}`),s={...n,text:a};return Ki([...e.slice(0,-1),s])}return Ki([...e,t])}function Ki(e){return e.length<=Oi?e:e.slice(e.length-Oi)}function Fm(e){switch(e){case"tool":return"Tool";case"reasoning":return"Reasoning";case"plan":return"Plan";case"command":return"Command";case"files":return"Files";case"model_state":return"Model";case"session":return"Session";default:return"Progress"}}function kr(e){if(typeof e!="string")return"";const t=e.replace(/\s+/g," ").trim();return t?t.length>_i?`${t.slice(0,_i-1)}…`:t:""}function _c(e,t){const n=e.findIndex(a=>a.id===t);return n===-1?!1:e.slice(n+1).some(a=>a.senderKind==="agent"||a.senderKind==="orchestrator")}function ys(e,t,n){const a=e.findIndex(s=>s.id===t);return a===-1?!1:e.slice(a+1).some(s=>fr(s)&&fo(s,n))}function Er(e,t){return e.reduce((n,a)=>{if(!fr(a)||t&&!t(a))return n;const s=Date.parse(a.createdAt);return Number.isNaN(s)?n:Math.max(n,s)},Number.NEGATIVE_INFINITY)}function fr(e){return e.senderKind!=="user"&&e.senderKind!=="system"}function Sr(e){return e?.active?!!(ge(e.participantId)||ge(e.speakerLabel)||e.catId||e.activeCatIds.some(t=>t.trim().length>0)):!1}function fo(e,t){const n=ge(t.laneId);if(n&&zo(e,{laneId:n,sourceMessageId:t.sourceMessageId}))return!0;const a=ge(t.targetStateId);if(a)return Uc(e,{targetStateId:a,sessionId:t.sessionId,sourceMessageId:t.sourceMessageId});const s=Vo(e),o=ge(t.identityParticipantId)??ge(t.participantId)??t.catId??t.activeCatIds.find(d=>d.trim().length>0)??null;if(s&&o&&s===o)return!0;if(o)return!1;const i=ge(t.speakerLabel);return i?ge(e.senderName)===i||$m(e)===i:!1}function Fc(e,t,n){const a=ge(t.laneId),s=ge(t.targetStateId),o=ge(t.sessionId),i=!!(a||s),d=(()=>{if(!n)return null;const c=Date.parse(n);return Number.isNaN(c)?null:c})();return e.some(c=>{if($r(c)!=="session_started")return!1;const u=Date.parse(c.createdAt);if(Number.isNaN(u)||d!=null&&u<d)return!1;let h=!1;if(a&&(h=zo(c,{laneId:a,sourceMessageId:t.sourceMessageId})),!h&&s&&(h=Uc(c,{targetStateId:s,sessionId:o})),!h&&o){const m=Wc(c);h=!!(m&&m===o)}const f=ge(t.identityParticipantId)??ge(t.participantId);if(f){if(f==="orchestrator")return Ui(c)==="orchestrator";const m=Vo(c);return m?m!==f?!1:i?h:!0:h}return h?!0:Ui(c)==="orchestrator"})}function Wm(e,t){return Fc(t,Ze([e]),e.sessionStartedAt)}function qs(e){if(!kc())return;const t=e.messages.at(-1),n=t?.channelId??null;Pc({event:"visibility_decision",channelId:n,conversationId:n?bc(n):null,turnId:Um(t??null),laneId:e.liveIndicator.laneId,sourceMessageId:e.liveIndicator.sourceMessageId,targetStateId:e.liveIndicator.targetStateId,sessionId:e.liveIndicator.sessionId,speakerLabel:e.liveIndicator.speakerLabel,participantId:e.liveIndicator.participantId,catId:e.liveIndicator.catId,activeTurnUpdatedAt:e.activeTurnUpdatedAt,visible:e.visible,reason:e.reason,details:{phase:e.liveIndicator.phase,lastMessageId:t?.id??null,latestReplyAt:Number.isFinite(e.latestReplyTimestamp)&&e.latestReplyTimestamp>Number.NEGATIVE_INFINITY?new Date(e.latestReplyTimestamp).toISOString():null},signature:[e.liveIndicator.phase,e.liveIndicator.laneId??"",e.liveIndicator.targetStateId??"",e.liveIndicator.sourceMessageId??"",e.liveIndicator.sessionId??"",e.liveIndicator.identityParticipantId??"",e.liveIndicator.participantId??"",e.liveIndicator.speakerLabel??"",e.liveIndicator.catId??"",e.activeTurnUpdatedAt,e.visible?"1":"0",e.reason,t?.id??""].join("::")})}function zt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Vo(e){const t=zt(e.metadata);return ge(t?.targetId)||ge(t?.sourceRefId)||ge(t?.participantId)}function Wc(e){const t=zt(e.metadata);return ge(t?.sessionId)}function Km(e){const t=zt(e.metadata);return ge(t?.laneId)}function Kc(e){const t=zt(e.metadata);return ge(t?.targetStateId)}function Ui(e){const t=zt(e.metadata);return ge(t?.targetKind)}function $r(e){const t=zt(e.metadata);return ge(t?.event)}function as(e){const t=zt(e.metadata);return ge(t?.sourceMessageId)}function Um(e){if(!e)return null;const t=zt(e.metadata);return ge(t?.turnId)}function Gs(e){const t=zt(e.metadata);return typeof t?.segmentIndex=="number"&&Number.isFinite(t.segmentIndex)?t.segmentIndex:null}function $m(e){const t=zt(e.metadata);return ge(t?.executionLabelSnapshot)}function Uc(e,t){const n=ge(t.targetStateId),a=ge(t.sourceMessageId);if(n){const s=Kc(e);if(s&&s===n){if(!a)return!0;const o=as(e);return!o||o===a}}return Hm(e,{sessionId:t.sessionId,sourceMessageId:a})}function zo(e,t){const n=ge(t.laneId);if(!n)return!1;const a=Km(e);return!(!a||a!==n)}function Hm(e,t){const n=ge(t.sessionId);if(!n)return!1;const a=Wc(e);if(!a||a!==n)return!1;const s=ge(t.sourceMessageId);if(!s)return!0;const o=as(e);return!o||o===s}function qm(e,t,n){const a=ge(t.sourceMessageId);if(t.laneId||t.targetStateId)return e.some(i=>fr(i)&&$r(i)==="assistant_turn_segment"&&(zo(i,{laneId:t.laneId})||t.targetStateId&&(!a||as(i)===a)&&Kc(i)===t.targetStateId)&&Gs(i)===n);const s=po(t);if(t.phase==="sealed"&&s&&a)return e.some(i=>fr(i)&&$r(i)==="assistant_turn_segment"&&as(i)===a&&Gs(i)===n&&Vo(i)===s);let o=-1;for(let i=e.length-1;i>=0;i-=1)if(e[i].senderKind==="user"){o=i;break}return e.some((i,d)=>d>o&&fr(i)&&$r(i)==="assistant_turn_segment"&&Gs(i)===n)}function ge(e){return typeof e!="string"?null:e.trim()||null}function nn(e){return e==null?null:ge(e)}function Gm(e){return e.key==="Enter"&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.isComposing}function $c(e){return e?.kind==="composer"&&e.phase==="send"||In(e,"dispatch")}function Vm(e){return e?.kind==="composer"&&e.phase==="stop"||In(e,"stop")}function zm(e){return e?.kind==="composer"&&e.phase==="send"&&e.scope.kind==="channel"?e.scope.channelId:null}function Hc(e,t){return e?.kind==="composer"&&(e.phase==="prepare"||e.phase==="ack")&&e.scope.kind==="channel"&&e.scope.channelId===t}function Ym(e,t){return e?.kind==="composer"&&e.phase==="send"&&e.scope.kind==="channel"&&e.scope.channelId===t}function Jm(e,t){return e?.kind==="composer"&&e.phase==="stop"&&e.scope.kind==="channel"&&e.scope.channelId===t}function qc(e){return e?.kind==="composer"&&(e.phase==="prepare"||e.phase==="ack")&&e.scope.kind==="draft"}function Qm(e){return qc(e)}function Xm(e,t){return!!t&&(Hc(e,t)||Jm(e,t))}function Gc(e,t){return{containerId:Zf(),conversationId:bc(t)}}const Zm=150,eg=8;function tg(e,t,n){return!$c(t)||!e?!1:!Zl(e)}function ng(e){const t=e?.pendingProvider?.trim()||null;return!e||e.roomRouting.defaultRecipientId||!t||!Sc(e)?null:Yl(t,e.pendingInstance,null)}function ag(e,t){const n=te(e?.conversationId);return n||(t?Gc(null,t).conversationId:null)}function yr(e,t,n,a=null){const s=a?.trim()||null;if(s)return s;const o=e?.trim()||null,i=t?.trim()||null,d=n?.trim()||null;return o&&i&&d?ns(o,i,d):null}function rg(e){const t=e?.roomRouting.workflow.activeTurn??null,a=(t?.targetStatuses?.filter(i=>i.status==="running"||i.status==="pending")??[])[0];if(!a)return{sourceMessageId:t?.sourceMessageId?.trim()||null,laneId:null,targetStateId:null,participantId:null,catId:null,speakerLabel:null,revealIdentity:!1};const s=t?.sourceMessageId?_c(e?.messages??[],t.sourceMessageId):!1,o=t?.workflowShape==="concurrent"||s;return{sourceMessageId:t?.sourceMessageId?.trim()||null,laneId:yr(t?.id??null,a.id??null,a.participant.participantId,a.laneId??null),targetStateId:a.id?.trim()||null,participantId:a.participant.participantId,catId:null,speakerLabel:a.participant.participantName?.trim()||null,revealIdentity:o}}function sg(e){const t=e?.roomRouting.workflow.activeTurn??null;if(t?.workflowShape!=="concurrent")return[];const n=t.targetStatuses?.filter(a=>a.status==="running"||a.status==="pending")??[];return n.length<=1?[]:n.map(a=>{const s=t.sourceMessageId?.trim()||null,o=yr(t.id??null,a.id??null,a.participant.participantId,a.laneId??null),i=Vc(e,a.participant.participantId,a.id?.trim()||null,o);return Sn({phase:"waiting",sourceMessageId:s,laneId:o,targetStateId:a.id?.trim()||null,participantId:a.participant.participantId,identityParticipantId:a.participant.participantId,speakerLabel:a.participant.participantName?.trim()||null,sessionStartedAt:i.sessionStartedAt,requiresSessionStartConfirmation:i.requiresSessionStartConfirmation})})}function $i(e){return e==="ready"||e==="initializing"}function og(e,t,n=null){if(!e||!t)return null;if(t==="orchestrator"){const i=te(e.orchestratorLease?.status),d=te(e.orchestratorLease?.laneId);return i&&!$i(i)?{sessionId:null,startedAt:null}:n&&d&&d!==n?{sessionId:null,startedAt:null}:{sessionId:te(e.orchestratorLease?.sessionId),startedAt:te(e.orchestratorLease?.startedAt)}}const a=e.assignedParticipants?.find(i=>i.participantId===t)?.execution?.lease??null,s=te(a?.status),o=te(a?.laneId);return s&&!$i(s)?{sessionId:null,startedAt:null}:n&&o&&o!==n?{sessionId:null,startedAt:null}:{sessionId:te(a?.sessionId),startedAt:te(a?.startedAt)}}function Vc(e,t,n=null,a=null){const s=te(e?.roomRouting.workflow.activeTurn?.id),o=te(e?.roomRouting.workflow.activeTurn?.startedAt),i=e?.roomRouting.workflow.activeTurn?.targetStatuses?.find(v=>{const C=yr(s,v.id??null,v.participant.participantId,v.laneId??null);return a&&C===a||n&&v.id?.trim()===n?!0:t!==null&&v.participant.participantId===t})??null,d=te(i?.startedAt)??te(i?.queuedAt)??o;if(!t||!d)return{sessionStartedAt:null,requiresSessionStartConfirmation:!1};const c=og(e,t,a),u=c?.sessionId??null,h=c?.startedAt??null;if(!u||!h)return{sessionStartedAt:d,requiresSessionStartConfirmation:!0};const f=Date.parse(d),m=Date.parse(h);return Number.isNaN(f)||Number.isNaN(m)?{sessionStartedAt:h,requiresSessionStartConfirmation:!1}:{sessionStartedAt:h,requiresSessionStartConfirmation:m>=f}}function zc(e){return e.contentBlocks.length>0||e.progressText.trim().length>0||e.events.length>0}function rs(e,t){if(!e.active||e.phase==="waiting"||!zc(e))return!1;const n=t?.roomRouting.workflow.activeTurn?.sourceMessageId??null;return n?Sr(e)||e.laneId||e.targetStateId?!ys(t?.messages??[],n,e):!_c(t?.messages??[],n):!1}function ig(e){return e.previousChannelId!==e.channelId||!e.previous.active?e.waitingState:rs(e.previous,e.selectedChannel)?e.previous:e.previous.phase==="streaming"?Zn(e.previous,e.waitingState):e.previous.phase==="waiting"&&!zc(e.previous)?Zc(e.previous,e.waitingState):e.previous.phase==="sealed"?xs(e.previous,e.waitingState)&&!Yo(e.selectedChannel)?e.previous:Zn(e.previous,e.waitingState):e.previous}function bs(e,t){return e.segmentIndex===t.segmentIndex&&Pa(e,t)}function Pa(e,t){const n=e.sourceMessageId??null,a=t.sourceMessageId??null,s=e.laneId??null,o=t.laneId??null,i=e.targetStateId??null,d=t.targetStateId??null,c=Bn(e),u=Bn(t),h=e.catId??null,f=t.catId??null,m=e.speakerLabel??null,v=t.speakerLabel??null;return s!==null&&o!==null?s===o:i!==null&&d!==null?i===d:n===a&&c===u&&h===f&&m===v}function xs(e,t){const n=Ge(e),a=Ge(t);return n!=null&&a!=null&&Pa(n,a)||Pa(e,t)}function Yc(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function Jc(e,t){return e.length===t.length&&e.every((n,a)=>{const s=t[a];return s!=null&&n.id===s.id&&n.kind===s.kind&&n.index===s.index&&n.status===s.status&&n.text===s.text&&n.title===s.title&&n.toolName===s.toolName})}function Qc(e,t){return e.length===t.length&&e.every((n,a)=>{const s=t[a];return s!=null&&n.toolName===s.toolName&&n.toolId===s.toolId&&n.done===s.done})}function Xc(e,t){return e.length===t.length&&e.every((n,a)=>{const s=t[a];return s!=null&&n.eventType===s.eventType&&n.label===s.label&&n.text===s.text&&n.tone===s.tone&&n.kind===s.kind&&n.toolName===s.toolName&&n.toolId===s.toolId})}function lg(e,t){return e.id===t.id&&e.phase===t.phase&&e.sourceMessageId===t.sourceMessageId&&e.laneId===t.laneId&&e.targetStateId===t.targetStateId&&e.segmentIndex===t.segmentIndex&&e.sessionId===t.sessionId&&e.identityParticipantId===t.identityParticipantId&&e.participantId===t.participantId&&e.catId===t.catId&&e.catName===t.catName&&e.speakerLabel===t.speakerLabel&&e.sessionStartedAt===t.sessionStartedAt&&e.requiresSessionStartConfirmation===t.requiresSessionStartConfirmation&&e.lastActivityAtMs===t.lastActivityAtMs&&e.lastVisibleContentAtMs===t.lastVisibleContentAtMs&&e.progressText===t.progressText&&e.progressKind===t.progressKind&&Yc(e.activeCatIds,t.activeCatIds)&&Qc(e.tools,t.tools)&&Jc(e.contentBlocks,t.contentBlocks)&&Xc(e.events,t.events)}function cg(e,t){if(e===t)return!0;if(e.active!==t.active||e.phase!==t.phase||e.sourceMessageId!==t.sourceMessageId||e.laneId!==t.laneId||e.targetStateId!==t.targetStateId||e.segmentIndex!==t.segmentIndex||e.sessionId!==t.sessionId||e.identityParticipantId!==t.identityParticipantId||e.participantId!==t.participantId||e.catId!==t.catId||e.catName!==t.catName||e.speakerLabel!==t.speakerLabel||e.sessionStartedAt!==t.sessionStartedAt||e.requiresSessionStartConfirmation!==t.requiresSessionStartConfirmation||e.lastActivityAtMs!==t.lastActivityAtMs||e.lastVisibleContentAtMs!==t.lastVisibleContentAtMs||e.progressText!==t.progressText||e.progressKind!==t.progressKind||!Yc(e.activeCatIds,t.activeCatIds)||!Qc(e.tools,t.tools)||!Jc(e.contentBlocks,t.contentBlocks)||!Xc(e.events,t.events))return!1;const n=Ve(e),a=Ve(t);return n.length===a.length&&n.every((s,o)=>{const i=a[o];return i!=null&&lg(s,i)})}function Bn(e){return e.identityParticipantId??e.participantId??null}function Yo(e){return e?Sc(e):!1}function dg(e,t){if(!e||!t)return!1;if(e.laneId&&t.laneId)return e.laneId===t.laneId;if(e.targetStateId&&t.targetStateId)return e.targetStateId===t.targetStateId;if(!e.sourceMessageId||!t.sourceMessageId||e.sourceMessageId!==t.sourceMessageId)return!1;const n=Bn(e),a=Bn(t);return n&&a?n===a:e.catId&&t.catId?e.catId===t.catId:n!=null||a!=null||e.catId!=null||t.catId!=null?!1:e.speakerLabel!=null&&t.speakerLabel!=null&&e.speakerLabel===t.speakerLabel}function Hi(e){if(!e||typeof e!="object")return null;const t=e;return{participantId:typeof t.participantId=="string"&&t.participantId.trim()||null,participantName:typeof t.participantName=="string"&&t.participantName.trim()||null}}function ug(e,t){const a=(e.events?.find(s=>s.kind==="turn_started")??null)?.targets?.map(s=>Hi(s)).filter(s=>s!==null)??[];return a.length>0?a:!t||t.turnId!==e.id?[]:t.resolvedTargets?.map(s=>Hi(s)).filter(s=>s!==null)??[]}function pg(e,t){const n=Bn(t);if(n){const a=e.findIndex(s=>s.participantId===n);return a>=0?a:-1}if(t.speakerLabel){const a=e.map((s,o)=>s.participantName===t.speakerLabel?o:-1).filter(s=>s>=0);return a.length===1?a[0]:-1}return-1}function qi(e,t){if(!t)throw new Error("reindexWaitingSegment requires a waiting segment");return dg(e,t)?Ge(Bc({sourceMessageId:t.sourceMessageId,laneId:t.laneId,targetStateId:t.targetStateId,participantId:Bn(t),catId:t.catId,speakerLabel:t.speakerLabel,revealIdentity:!0,segmentIndex:e.segmentIndex+1}))??t:t}function Zn(e,t){const n=Ge(t);if(!n)return e;const a=Ge(e);if(!e.active||!a)return t;if(a.phase==="waiting"){if(bs(e,t))return e;const i=qi(a,n);return Ze([...e.segments.slice(0,-1),i])}const s=a.phase==="sealed"?a:{...a,phase:"sealed"},o=qi(s,n);return Ze([...e.segments.slice(0,-1),s,o])}function Zc(e,t){const n=Ge(t);if(!n)return e;const a=Ge(e);return!e.active||!a?t:a.phase!=="waiting"||bs(e,t)||xs(e,t)?e:Ze([...e.segments.slice(0,-1),n])}function hg(e,t,n){if(!e.active||e.phase!=="streaming"||!t.active||t.phase!=="waiting"||!Sr(t)||bs(e,t)||xs(e,t)&&!Yo(n))return!1;const a=n?.roomRouting.workflow.activeTurn?.sourceMessageId??null;return a?ys(n?.messages??[],a,e):!1}function fg(e,t,n){if(!e.active||e.phase!=="sealed"||!t.active||t.phase!=="waiting"||!Sr(t)||bs(e,t)||xs(e,t)&&!Yo(n))return!1;const a=n?.roomRouting.workflow.activeTurn?.sourceMessageId??null;return a?ys(n?.messages??[],a,e):!1}function mg(e,t){return!(Ge(e)?.phase==="sealed"||rs(e,t))}function Gi(e,t){const n=Ge(e),a=t?.roomRouting.workflow.activeTurn??null,s=a?.sourceMessageId?.trim()||null,o=n?.sourceMessageId??e.sourceMessageId;if(n?.phase!=="sealed"||!a||a.status!=="running"&&a.status!=="pending"||!s||!o||o!==s)return!1;const i=a.targetStatuses?.filter(m=>m.status==="running"||m.status==="pending")??[];if(i.length>0){if(i.some(S=>{const y=yr(a.id??null,S.id??null,S.participant.participantId,S.laneId??null);if(n.laneId&&y)return y!==n.laneId;const g=S.id?.trim()||null;if(n.targetStateId&&g)return g!==n.targetStateId;const x=Bn(n),I=S.participant.participantId?.trim()||null;return x&&I?I!==x:(S.participant.participantName?.trim()||null)!==(n.speakerLabel??null)}))return!0;if(n.laneId||n.targetStateId||Bn(n))return!1;const v=n.speakerLabel?.trim()||null;return v?(a.targetStatuses??i).filter(S=>(S.participant.participantName?.trim()||null)===v).length>1:i.length>0}if(a.workflowShape!=="sequential")return!0;const d=t?.roomRouting.lastOutcome??null,c=ug(a,d);if(c.length>0){const m=pg(c,n);if(m>=0)return m<c.length-1}const h=(a.events?.find(m=>m.kind==="turn_started")??null)?.targets?.length??(d?.turnId===a.id?d?.resolvedTargets?.length:null)??null;if(!h)return!0;const f=new Set(a.targetStatuses?.map(m=>yr(a.id??null,m.id??null,m.participant.participantId,m.laneId??null)??m.id?.trim()??null).filter(m=>!!m)??[]);return(n.laneId||n.targetStateId)&&f.add(n.laneId??n.targetStateId),f.size<h}function gg(e,t){return Ge(e)?.phase!=="sealed"?!1:!mo(e,t)}function mo(e,t){const n=Ge(e),a=Ge(t);return a?n?a.laneId&&n.laneId?a.laneId!==n.laneId:a.targetStateId&&n.targetStateId?a.targetStateId!==n.targetStateId:!Pa(n,a):!0:!1}function Cg(e){return $c(e.busy)&&!!e.channelId}function vg(e){return tg(e.channelId,e.busy,e.routingStatus)}function Ig(e,t){const n=te(t.sessionId),a=te(t.laneId),s=te(t.targetStateId),o=te(t.sourceMessageId),i=typeof t.streamSeq=="number"&&Number.isFinite(t.streamSeq)?t.streamSeq:null,d=typeof t.streamSeqIndex=="number"&&Number.isFinite(t.streamSeqIndex)?t.streamSeqIndex:null;return!n||i===null||d===null?{accept:!0,cursor:e}:e&&e.sessionId===n&&e.sourceMessageId===o&&Sg(e,{laneId:a,targetStateId:s})&&(i<e.streamSeq||i===e.streamSeq&&d<=e.streamSeqIndex)?{accept:!1,cursor:e}:{accept:!0,cursor:{sessionId:n,laneId:a,targetStateId:s,sourceMessageId:o,streamSeq:i,streamSeqIndex:d}}}function Sg(e,t){return e.laneId&&t.laneId?e.laneId===t.laneId:(e.targetStateId&&t.targetStateId||e.laneId===t.laneId)&&e.targetStateId===t.targetStateId}function yg(e){return e.phase!=="waiting"||e.contentBlocks.length>0||e.progressText.trim().length>0||e.events.length>0||e.tools.length>0}function Dr(e,t){const n=Ve(t);if(n.length<=1)return Zn(e,t);const a=Ve(e);if(a.length===0)return t;const s=new Set,o=new Set,i=[];for(let c=0;c<a.length;c+=1){if(s.has(c))continue;const u=a[c],h=n.findIndex(v=>Pa(u,v));if(h<0){i.push(u);continue}o.add(h);const f=n[h],m=[];for(let v=c;v<a.length;v+=1){if(s.has(v))continue;const C=a[v];Pa(C,f)&&(s.add(v),m.push(C))}if(m.some(yg)){i.push(...m);continue}i.push(f)}n.forEach((c,u)=>{o.has(u)||i.push(c)});const d=Ze(i);return cg(e,d)?e:d}function bg(e){const{channelId:t,busy:n,selectedChannel:a,debugTraceEnabled:s=!1,resolveRoutingStatus:o,shouldShowWaitingIndicator:i=Cg,shouldConnectStream:d=vg}=e,[c,u]=p.useState(ur),h=p.useRef(null),f=p.useRef(ur),m=p.useRef(a),v=p.useRef(null),C=p.useRef(null),S=a?.roomRouting.defaultRecipientId??null,y=o?.(a)??null,g=a?.roomRouting.workflow.activeTurn??null,x=S?null:ng(a),I=p.useMemo(()=>rg(a),[g,a?.messages]),k=p.useMemo(()=>Vc(a,I.participantId,I.targetStateId,I.laneId),[a,I.participantId,I.targetStateId,I.laneId]),P=p.useMemo(()=>({sourceMessageId:I.sourceMessageId,laneId:I.laneId,targetStateId:I.targetStateId,participantId:I.participantId,catId:I.catId,speakerLabel:I.speakerLabel,revealIdentity:I.revealIdentity,defaultRecipientCatId:S,fallbackSpeakerLabel:x,sessionStartedAt:k.sessionStartedAt,requiresSessionStartConfirmation:k.requiresSessionStartConfirmation}),[I.sourceMessageId,I.laneId,S,x,I.catId,I.targetStateId,I.participantId,I.revealIdentity,I.speakerLabel,k.sessionStartedAt,k.requiresSessionStartConfirmation]),A=p.useRef(P);function M(){const R=sg(m.current);if(R.length>1)return Ze(R);const w=A.current;return Bc({sourceMessageId:w.sourceMessageId,laneId:w.laneId,targetStateId:w.targetStateId,participantId:w.participantId,catId:w.revealIdentity?w.catId:w.defaultRecipientCatId,speakerLabel:w.revealIdentity?w.speakerLabel:w.fallbackSpeakerLabel,revealIdentity:w.revealIdentity,sessionStartedAt:w.sessionStartedAt,requiresSessionStartConfirmation:w.requiresSessionStartConfirmation})}function D(R,w={}){if(!s)return;const b=te(m.current?.roomRouting.workflow.activeTurn?.id),T=Ge(f.current);Pc({event:R,channelId:t,containerId:te(w.containerId)??te(m.current?.containerId),conversationId:ag(m.current,t),turnId:te(w.turnId)??b,laneId:te(w.laneId)??T?.laneId??f.current.laneId,sourceMessageId:te(w.sourceMessageId)??T?.sourceMessageId??f.current.sourceMessageId,targetStateId:te(w.targetStateId)??T?.targetStateId??f.current.targetStateId,sessionId:te(w.sessionId),participantId:te(w.participantId),catId:te(w.catId),speakerLabel:te(w.speakerLabel),reason:te(w.reason),details:w.details??null,signature:w.signature??null})}p.useEffect(()=>{f.current=c},[c]),p.useEffect(()=>{m.current=a},[a]),p.useEffect(()=>{A.current=P},[P]),p.useEffect(()=>{const R=i({channelId:t,busy:n,routingStatus:y}),w=v.current;v.current=t;let b=!1,T=null,E=0;function O(z){u(B=>{const ae=z(B);return f.current=ae,ae})}function H(){T&&(clearTimeout(T),T=null)}function U(){h.current&&(h.current.close(),h.current=null)}function L(){b||E>=eg||!d({channelId:t,busy:n,routingStatus:y})||(E+=1,U(),H(),T=setTimeout(()=>{T=null,b||X()},Zm))}function $(z){let B;try{B=JSON.parse(z.data)}catch{return}const ae=Ig(C.current,B);if(!ae.accept){D("stream_event_deduped",{turnId:te(B.turnId),laneId:te(B.laneId),sourceMessageId:te(B.sourceMessageId),targetStateId:te(B.targetStateId),sessionId:te(B.sessionId),participantId:te(B.participantId),catId:te(B.catId),speakerLabel:te(B.speakerLabel),reason:"stale_replayed_event",details:{eventType:B.type??z.type,streamSeq:typeof B.streamSeq=="number"?B.streamSeq:null,streamSeqIndex:typeof B.streamSeqIndex=="number"?B.streamSeqIndex:null}});return}C.current=ae.cursor,E=0;const he=B.type??z.type,Y=M(),G=he==="session_closed"&&d({channelId:t,busy:n,routingStatus:y});Ge(f.current);const W=G&&mo(f.current,Y),ue=G&&Gi(f.current,m.current),pe=G&&rs(f.current,m.current),We=G&&gg(f.current,Y)&&!ue;D("stream_event",{turnId:te(B.turnId),laneId:te(B.laneId),sourceMessageId:te(B.sourceMessageId),targetStateId:te(B.targetStateId),sessionId:te(B.sessionId),participantId:te(B.participantId),catId:te(B.catId),speakerLabel:te(B.speakerLabel),reason:G?"session_close_reconnect":null,details:{eventType:he,busy:n,routingStatus:y}}),O(Z=>{if(!Z.active)return Z;if(G){if(We)return D("stream_session_close_ignored",{turnId:te(B.turnId),laneId:Z.laneId,sourceMessageId:Z.sourceMessageId,targetStateId:Z.targetStateId,participantId:Z.participantId,catId:Z.catId,speakerLabel:Z.speakerLabel,reason:"sealed_segment_already_completed"}),Z;if(pe)return D("stream_reply_commit_pending",{turnId:te(B.turnId),laneId:Z.laneId,sourceMessageId:Z.sourceMessageId,targetStateId:Z.targetStateId,participantId:Z.participantId,catId:Z.catId,speakerLabel:Z.speakerLabel,reason:"pin_until_persisted_reply"}),Z;if(!W&&!ue)return D("stream_session_close_no_followup",{turnId:te(B.turnId),laneId:Z.laneId,sourceMessageId:Z.sourceMessageId,targetStateId:Z.targetStateId,participantId:Z.participantId,catId:Z.catId,speakerLabel:Z.speakerLabel,reason:"no_distinct_followup_target"}),Z;if(!W)return D("stream_session_close_reconnect",{turnId:te(B.turnId),laneId:Z.laneId,sourceMessageId:Z.sourceMessageId,targetStateId:Z.targetStateId,participantId:Z.participantId,catId:Z.catId,speakerLabel:Z.speakerLabel,reason:"ongoing_workflow_boundary"}),Z;const Ke=Go(Y,B);return D("stream_waiting_restart",{turnId:te(B.turnId),laneId:Ke.laneId,sourceMessageId:Ke.sourceMessageId,targetStateId:Ke.targetStateId,participantId:te(B.participantId),catId:Ke.catId,speakerLabel:Ke.speakerLabel,reason:"session_close_reconnect"}),Ve(Y).length>1?Dr(Z,Y):Zn(Z,Y)}return bm(Z,he,B,Date.now())}),G&&!We&&(W||ue)&&L()}function X(){if(b||!d({channelId:t,busy:n,routingStatus:y}))return;U();const z=new EventSource(`/api/channels/${t}/stream`);h.current=z,D("stream_connect",{turnId:g?.id??null,laneId:A.current.laneId,sourceMessageId:A.current.sourceMessageId,targetStateId:A.current.targetStateId,reason:"open_source",details:{busy:n,routingStatus:y}}),z.addEventListener("progress",$),z.addEventListener("text",$),z.addEventListener("tool_use",$),z.addEventListener("tool_result",$),z.addEventListener("content_block",$),z.addEventListener("result",$),z.addEventListener("error",$),z.addEventListener("session_closed",$),z.onerror=()=>{if(b||z!==h.current)return;const B=M(),ae=mo(f.current,B),he=Gi(f.current,m.current);if(!(ae||he||mg(f.current,m.current))){D("stream_source_error_ignored",{turnId:m.current?.roomRouting.workflow.activeTurn?.id??null,laneId:f.current.laneId,sourceMessageId:f.current.sourceMessageId,targetStateId:f.current.targetStateId,participantId:f.current.participantId,catId:f.current.catId,speakerLabel:f.current.speakerLabel,reason:"reply_commit_or_sealed_segment",details:{phase:Ge(f.current)?.phase??null}}),U();return}ae&&O(G=>Ve(B).length>1?Dr(G,B):Zn(G,B)),D("stream_source_error",{turnId:m.current?.roomRouting.workflow.activeTurn?.id??null,laneId:ae?A.current.laneId:f.current.laneId,sourceMessageId:ae?A.current.sourceMessageId:f.current.sourceMessageId,targetStateId:ae?A.current.targetStateId:f.current.targetStateId,reason:ae?"eventsource_terminated_followup_handoff":he?"eventsource_terminated_running_workflow":"eventsource_terminated",details:{busy:n,routingStatus:y}}),U(),L()}}if(!R){if(H(),U(),rs(f.current,m.current)){D("indicator_pin_pending_reply",{turnId:m.current?.roomRouting.workflow.activeTurn?.id??null,laneId:f.current.laneId,sourceMessageId:f.current.sourceMessageId,targetStateId:f.current.targetStateId,participantId:f.current.participantId,catId:f.current.catId,speakerLabel:f.current.speakerLabel,reason:"waiting_not_needed_but_reply_not_persisted",details:{phase:Ge(f.current)?.phase??null}});return}D("indicator_reset",{turnId:g?.id??null,laneId:A.current.laneId,sourceMessageId:A.current.sourceMessageId,targetStateId:A.current.targetStateId,reason:"waiting_not_needed",details:{busy:n,routingStatus:y},signature:`indicator_reset::${t??""}::${rp(n)}::${y??""}`}),f.current=ur,u(ur);return}const ke=M();if(w!==t&&(C.current=null),u(z=>{const B=Ve(ke).length>1?Dr(z,ke):ig({previous:z,waitingState:ke,selectedChannel:m.current,previousChannelId:w,channelId:t});return f.current=B,B}),D("waiting_started",{turnId:g?.id??null,laneId:P.laneId,sourceMessageId:P.sourceMessageId,targetStateId:P.targetStateId,participantId:P.revealIdentity?P.participantId:null,catId:P.revealIdentity?P.catId:P.defaultRecipientCatId,speakerLabel:P.revealIdentity?P.speakerLabel:P.fallbackSpeakerLabel,reason:d({channelId:t,busy:n,routingStatus:y})?"awaiting_stream_attach":"waiting_without_stream",details:{busy:n,routingStatus:y}}),!d({channelId:t,busy:n,routingStatus:y})){H(),U();return}return X(),()=>{b=!0,H(),U()}},[n,t,s,y,d,i]),p.useEffect(()=>{if(!i({channelId:t,busy:n,routingStatus:y}))return;const w=M();u(b=>{if(Ve(w).length>1){const E=Dr(b,w);return f.current=E,E}if(hg(b,w,m.current)){const E=Zn(b,w);return f.current=E,E}if(fg(b,w,m.current)){const E=Zn(b,w);return f.current=E,E}if(!b.active||b.phase!=="waiting")return b;const T=Zc(b,w);return f.current=T,T})},[n,t,y,a,i,P]);const N=p.useMemo(()=>vm(c,Date.now()),[c]);return p.useEffect(()=>{if(N==null)return;const R=Math.max(N-Date.now(),0),w=globalThis.setTimeout(()=>{u(b=>{if(!b.active)return b;const T={...b};return f.current=T,T})},R);return()=>{globalThis.clearTimeout(w)}},[N]),c}function te(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function xg(){const[e,t]=p.useState([]),[n,a]=p.useState(null),[s,o]=p.useState(new Map),i=p.useCallback(u=>{t(h=>{const f=h.includes(u),m=f?h.filter(v=>v!==u):[...h,u];return f?(a(v=>v===u?m.length>0?m[0]:null:v),o(v=>{const C=new Map(v);return C.delete(u),C})):a(u),m})},[]),d=p.useCallback((u,h)=>{o(f=>{const m=new Map(f);return m.set(u,h),m})},[]),c=p.useCallback(()=>{t([]),a(null),o(new Map)},[]);return{draftCatIds:e,setDraftCatIds:t,draftHighlightedCatId:n,setDraftHighlightedCatId:a,draftCatExecutionTargetOverrides:s,setDraftCatExecutionTargetOverrides:o,onToggleDraftCat:i,onDraftCatExecutionTargetOverride:d,resetDraftCats:c}}function Vi(e){const t=e?.trim();return t||null}function ed(e){const t=Vi(e.draftDefaultRecipientCatId),n=[],a=new Set;for(const o of e.draftCatIds){const i=Vi(o);!i||a.has(i)||(a.add(i),n.push(i))}const s=t?[t,...n.filter(o=>o!==t)]:n;return{participantCatIds:s,effectiveDefaultRecipientCatId:s[0]??null}}function wg(e){const{state:t,draftDefaultRecipientCatId:n,draftCatIds:a,maxDraftGroupParticipants:s}=e,[o,i]=p.useState([]),d=p.useMemo(()=>ed({draftDefaultRecipientCatId:n,draftCatIds:a}),[a,n]),c=p.useCallback(f=>{i(m=>{if(d.participantCatIds.length+m.length>=s)return m;const v=[...d.participantCatIds.map(C=>(t.status==="ready"?t.payload.chat.cats.find(S=>S.id===C)?.name:null)??""),...m.map(C=>C.name)].filter(C=>C.trim().length>0);return[...m,Mn({...f,takenNames:v,randomUUID:()=>window.crypto.randomUUID()})]})},[d.participantCatIds,s,t]),u=p.useCallback(f=>{i(m=>m.filter(v=>v.participantId!==f))},[]),h=p.useCallback((f,m)=>{i(v=>v.map(C=>C.participantId===f?{...C,...m.name!==void 0?{name:m.name?.trim()||C.name}:{},...m.roleHint!==void 0?{roleHint:m.roleHint?.trim()||void 0}:{}}:C))},[]);return{draftTemporaryParticipants:o,setDraftTemporaryParticipants:i,draftParticipants:d,onAddDraftTemporaryParticipant:c,onRemoveDraftTemporaryParticipant:u,onUpdateDraftTemporaryParticipant:h}}function kg(e){const[t,n]=p.useState(e.initialState),[a,s]=p.useState(""),[o,i]=p.useState(e.createEmptyCatForm),[d,c]=p.useState(Fe()),[u,h]=p.useState(""),[f,m]=p.useState("existing"),[v]=p.useState(e.pickGreeting),[C,S]=p.useState(null),[y,g]=p.useState([]),[x,I]=p.useState([]);return{state:t,setState:n,composerDraft:a,setComposerDraft:s,catForm:o,setCatForm:i,busy:d,setBusy:c,feedback:u,setFeedback:h,addCatTab:f,setAddCatTab:m,greeting:v,draftCwd:C,setDraftCwd:S,draftFiles:y,setDraftFiles:g,channelFiles:x,setChannelFiles:I}}function Pg(e){const t=ec(),n=gi(`${e}/chats/:channelId`),a=gi(`${e}/dm/:catId`),s=n?.params.channelId??null,o=a?.params.catId??null,i=sp(e,t.pathname),d=i?op(t.search):"default",c=o??ip(t.search);return{location:t,settingsMode:lp(t.pathname),routeChannelId:s,routeMyCatId:o,showingNewChatDraft:i,newChatPreset:d,draftDefaultRecipientCatId:c,showingMyCatDirectLane:!!o}}function Ag(e){return e.replace(/\s*\((?:default|recommended)\)\s*/giu," ").trim()}function Rg(e){const t=e.model?.trim();if(!t)return"default";const n=dp(e.provider,t)??t,s=Ci(e.provider,t)??Ci(e.provider,n)??up(e.provider).find(o=>o.value===n)?.label;return Ag(s??n)}function Jo(e,t,n){const a=wr({provider:e.provider,instance:e.instance,model:e.model,modelSelection:e.modelSelection??null,executionLabel:e.executionLabel??null,catalogControls:n});return t?`${t} · ${a}`:a}function Ng(e,t){return{label:Jo(e,null,t),providerLabel:cp(e.provider),instanceLabel:e.instance?.trim()||null,modelLabel:Rg(e)}}function wa(e){return{provider:e.provider,model:e.model||null,instance:e.instance||null,modelSelection:e.modelSelection??null,executionLabel:e.executionLabel??null}}const Tg=[/^cats new chat defaults update returned \d+$/u,/^cats channel update returned \d+$/u];function zi(e,t,n){if(!(e instanceof Error))return t;const a=tc(e.message,n);return a||(Tg.some(s=>s.test(e.message))?t:e.message)}const td=5e3;let Br=null,lr=null;const Yi=new Map,Vs=new Map;function Ji(e,t){typeof console>"u"||typeof console.warn!="function"||console.warn(`[cats-platform] ${e}`,t instanceof Error?t.stack??t.message:t)}function jg(e){const t=No(e);if(!t)return"null";const n=t.controls?Object.fromEntries(Object.keys(t.controls).sort().map(a=>[a,t.controls?.[a]])):void 0;return JSON.stringify({...t.entryId?{entryId:t.entryId}:{},entryMode:t.entryMode,...t.presetId?{presetId:t.presetId}:{},...n?{controls:n}:{}})}function zs(e){return JSON.stringify({provider:e.provider.trim(),instance:e.instance??null,model:e.model??null,modelSelection:jg(e.modelSelection)})}function Lg(e){return(e.fetchProviderRegistryFn??Yr)===Yr&&(e.fetchProviderModelsFn??Jr)===Jr&&(e.fetchAdvancedProviderModelsFn??Qr)===Qr}async function Mg(e){const t=Date.now();return Br&&Br.expiresAt>t?Br.value:lr||(lr=e().then(n=>(Br={value:n,expiresAt:Date.now()+td},n)).finally(()=>{lr=null}),lr)}async function Eg(e){const t=`${e.provider}\0${e.instance??""}`,n=Date.now(),a=Yi.get(t);if(a&&a.expiresAt>n)return a.value;const s=Vs.get(t);if(s)return s;const o=Promise.allSettled([e.fetchProviderModelsFn(e.provider,e.instance),e.fetchAdvancedProviderModelsFn(e.provider,e.instance)]).then(([i,d])=>{if(i.status!=="fulfilled")throw i.reason;const c=i.value,u=nc({provider:e.provider,instance:e.instance,catalog:c,advancedCatalogResult:d,modelsResult:i}),h={effectiveCatalog:c,effectiveAdvancedCatalog:u};return Yi.set(t,{value:h,expiresAt:Date.now()+td}),h}).finally(()=>{Vs.delete(t)});return Vs.set(t,o),o}async function Dg(e){const[t,n]=await Promise.allSettled([e.fetchProviderModelsFn(e.provider,e.instance),e.fetchAdvancedProviderModelsFn(e.provider,e.instance)]);if(t.status!=="fulfilled")throw t.reason;return{effectiveCatalog:t.value,effectiveAdvancedCatalog:nc({provider:e.provider,instance:e.instance,catalog:t.value,advancedCatalogResult:n,modelsResult:t})}}function Bg(e){return{provider:e,model:Ra(e)||null,instance:Na(e),modelSelection:null,executionLabel:null}}function Hr(){return Bg("claude")}function Qi(e){if(!e)return Hr();const t=e.provider?.trim()||"claude",n=e.model===void 0?(e.modelSelection?.entryId??Ra(t))||null:e.model??e.modelSelection?.entryId??null;return{provider:t,model:n,instance:e.instance??Na(t),modelSelection:e.modelSelection??null,executionLabel:null}}function mr(e,t){return e.provider===t.provider&&(e.instance??null)===(t.instance??null)&&(e.model??null)===(t.model??null)&&vp(e.modelSelection,t.modelSelection)}function nd(e,t){return mr(e,t)&&(e.executionLabel??null)===(t.executionLabel??null)}function Ys(e,t){if(!mr(e,t))return t;const n=t.executionLabel===null?null:t.executionLabel??e.executionLabel??null;return(e.executionLabel??null)===n?e:{...e,executionLabel:n}}function Og(e){return{provider:e.provider,instance:e.instance??"",model:e.model??"",modelSelection:e.modelSelection??null,executionLabel:e.executionLabel??null}}async function Xi(e){const t=e.target.provider.trim();if(!t)return e.target;const n=e.fetchProviderRegistryFn??Yr,a=e.fetchProviderModelsFn??Jr,s=e.fetchAdvancedProviderModelsFn??Qr,o=Lg(e),d=(o?await Mg(n):await n()).providers.find(S=>S.id===t);if(!d)return e.target;const c=pp(d,e.target.instance??"");let u,h;try{const S=o?await Eg({provider:t,instance:c||null,fetchProviderModelsFn:a,fetchAdvancedProviderModelsFn:s}):await Dg({provider:t,instance:c||null,fetchProviderModelsFn:a,fetchAdvancedProviderModelsFn:s});u=S.effectiveCatalog,h=S.effectiveAdvancedCatalog}catch{const S={...e.target,instance:c||null,...vi(t,e.target.model)?{model:null,modelSelection:null,executionLabel:null}:{}};return nd(e.target,S)?e.target:S}let f=Og({...e.target,provider:t,instance:c||null});const m=vi(t,f.model);if(!(!m&&hp({catalogSource:u.source,advancedCatalogSource:h.source,model:f.model,modelSelection:f.modelSelection}))&&u.models.length>0){const S=!!f.modelSelection||fp({catalog:u,model:f.model,modelSelection:f.modelSelection});f=mp({target:gp({target:f,catalog:u,advancedCatalog:h,preserveCurrentModel:S,preserveCurrentSelection:S}),controls:h.controls})}else m&&(f={...f,model:"",modelSelection:null,modelResolution:null,executionLabel:null});const C=f.model?Cp({target:f,effectiveCatalog:u,effectiveAdvancedCatalog:h}):{...f,executionLabel:null};return wa(C)}function Zi(e,t){return!e||!t||!sa(t)?null:t.pendingProvider?{provider:t.pendingProvider,model:t.pendingModel??null,instance:t.pendingInstance??null,modelSelection:t.pendingModelSelection??null,executionLabel:null}:{provider:e.globalOrchestrator.executionTarget.provider,model:e.globalOrchestrator.executionTarget.model??null,instance:e.globalOrchestrator.executionTarget.instance??null,modelSelection:e.globalOrchestrator.executionModelSelection??null,executionLabel:null}}function _g({state:e,readyChat:t,readySelectedChannel:n,setState:a,setFeedback:s,updateNewChatDefaultsPreference:o,updateChannelPendingExecutionTarget:i,debounceMs:d=150}){const{t:c}=Q(),[u,h]=p.useState(Hr),f=Zi(t,n),m=f?n?.id??null:null,v=f?zs(f):null,[C,S]=p.useState(()=>({channelId:m,persistedSignature:v,target:f??Hr()}));(C.channelId!==m||C.persistedSignature!==v)&&S({channelId:m,persistedSignature:v,target:f??Hr()});const y=C.target,g=p.useCallback(R=>{S(w=>{if(!m||w.channelId!==m)return w;const b=typeof R=="function"?R(w.target):R;return nd(w.target,b)?w:{...w,target:b}})},[m]),x=p.useRef(0),I=p.useRef(null),k=p.useRef(null),P=p.useRef(0),A=p.useRef(null),M=p.useRef(null),D=zs(u),N=zs(y);return p.useEffect(()=>{if(!t)return;const R=Qi(t.newChatDefaults);h(w=>Ys(w,R))},[t?.newChatDefaults?.instance,t?.newChatDefaults?.model,t?.newChatDefaults?.modelSelection,t?.newChatDefaults?.provider]),p.useEffect(()=>()=>{I.current&&(clearTimeout(I.current),I.current=null),k.current?.abort(),k.current=null,A.current&&(clearTimeout(A.current),A.current=null),M.current?.abort(),M.current=null},[]),p.useEffect(()=>{if(e.status!=="ready")return;let R=!1;return Xi({target:u}).then(w=>{R||h(b=>Ys(b,w))}).catch(w=>{Ji(`failed to reconcile draft execution target for ${u.provider}:${u.model??"default"}`,w)}),()=>{R=!0}},[D,e.status]),p.useEffect(()=>{if(e.status!=="ready"||!n||!sa(n))return;let R=!1;return Xi({target:y}).then(w=>{R||g(b=>mr(b,y)?Ys(b,w):b)}).catch(w=>{Ji(`failed to reconcile default chat execution target for ${y.provider}:${y.model??"default"}`,w)}),()=>{R=!0}},[n?.id,n?.channelKind,n?.roomRouting?.mode,N,g,e.status]),p.useEffect(()=>{if(e.status!=="ready")return;const R=Qi(e.payload.chat.newChatDefaults);if(mr(u,R))return;I.current&&(clearTimeout(I.current),I.current=null),k.current?.abort();const w=x.current+1;x.current=w;const b=new AbortController;k.current=b;const T={provider:u.provider,instance:u.instance,model:u.model,modelSelection:u.modelSelection};return I.current=setTimeout(()=>{I.current=null,o(T,b.signal).then(E=>{b.signal.aborted||x.current!==w||(k.current=null,p.startTransition(()=>a({status:"ready",payload:E})))}).catch(E=>{b.signal.aborted||x.current!==w||(k.current=null,s(zi(E,c(l.sharedExecutionTargetSaveNewChatDefaultsError),c)))})},d),()=>{I.current&&(clearTimeout(I.current),I.current=null),b.abort()}},[d,u.instance,u.model,u.modelSelection,u.provider,s,a,c,e.status,e.status==="ready"?e.payload.chat.newChatDefaults?.instance??null:null,e.status==="ready"?e.payload.chat.newChatDefaults?.model??null:null,e.status==="ready"?e.payload.chat.newChatDefaults?.modelSelection??null:null,e.status==="ready"?e.payload.chat.newChatDefaults?.provider??null:null,o]),p.useEffect(()=>{if(e.status!=="ready")return;const R=Zi(t,n);if(!n||!R||mr(y,R))return;A.current&&(clearTimeout(A.current),A.current=null),M.current?.abort();const w=n.id,b=P.current+1;P.current=b;const T=new AbortController;M.current=T;const E={pendingProvider:y.provider,pendingModel:y.model,pendingInstance:y.instance,pendingModelSelection:y.modelSelection};return A.current=setTimeout(()=>{A.current=null,i(w,E,T.signal).then(O=>{T.signal.aborted||P.current!==b||(M.current=null,p.startTransition(()=>a({status:"ready",payload:O})))}).catch(O=>{T.signal.aborted||P.current!==b||(M.current=null,s(zi(O,c(l.sharedExecutionTargetSaveChatReplySettingsError),c)))})},d),()=>{A.current&&(clearTimeout(A.current),A.current=null),T.abort()}},[d,t?.globalOrchestrator.executionTarget.provider,t?.globalOrchestrator.executionTarget.model,t?.globalOrchestrator.executionTarget.instance,t?.globalOrchestrator.executionModelSelection,n?.id,n?.channelKind,n?.roomRouting?.mode,n?.pendingProvider,n?.pendingModel,n?.pendingInstance,n?.pendingModelSelection,s,a,c,y.instance,y.model,y.modelSelection,y.provider,e.status,i]),{draftExecutionTarget:u,setDraftExecutionTarget:h,defaultChannelExecutionTarget:y,setDefaultChannelExecutionTarget:g}}function Fg(e,t,n="__generic__"){const a=p.useRef(null);p.useEffect(()=>{const s=e?n:null,o=s!=null&&a.current!==s;a.current=s,o&&t()},[n,e,t])}function ws(e){return!Array.isArray(e)||e.length===0?[]:e.filter((t,n,a)=>typeof t=="string"&&t.trim().length>0&&a.indexOf(t)===n)}function ad(e,t,n){return{...e,audienceKeys:[...t],workflowShape:n}}function el(e,t){return{...e,audienceKeys:ws(t.audienceKeys),workflowShape:t.workflowShape??"sequential",...t.cwd===void 0?{}:{cwd:t.cwd},...t.runtimeSessionPolicy===void 0?{}:{runtimeSessionPolicy:t.runtimeSessionPolicy},...t.promptOverride===void 0?{}:{promptOverride:t.promptOverride},...t.attachmentsOverride===void 0?{}:{attachmentsOverride:t.attachmentsOverride}}}function Wg(e){const t=ws(e.audienceKeys),n=e.workflowShape??"sequential";return ad(e,t,n)}function tl(e,t={}){const n=ws(t.seedAudienceKeys),a=t.seedWorkflowShape??"sequential";return e.map(s=>rd(s,{audienceKeys:n,workflowShape:a}))}function rd(e,t={}){const n=ws(t.audienceKeys),a=t.workflowShape??"sequential";return ad(e,n,a)}function ba(e,t,n){return e.map((a,s)=>s===t?Wg(n(a)):a)}function Kg(e,t,n){return ba(e,t,a=>({...a,cwd:n}))}function Ug(e,t,n){return ba(e,t,a=>({...a,runtimeSessionPolicy:n}))}function $g(e){const{draftExecutionTarget:t,maxParallelChats:n,seedCompareTarget:a=!0}=e,[s,o]=p.useState(()=>tl(Ri({provider:t.provider,model:t.model,instance:t.instance,modelSelection:t.modelSelection},{includeCompareTarget:a}))),i=p.useCallback(C=>{o(tl(Ri(t,{includeCompareTarget:C?.includeCompareTarget??a}),{seedAudienceKeys:C?.seedAudienceKeys,seedWorkflowShape:C?.seedWorkflowShape}))},[t,a]);p.useEffect(()=>{o(C=>ba(C,0,S=>el(Cf([S],t)[0]??t,S)))},[t]);const d=p.useCallback((C,S)=>{o(y=>ba(y,C,g=>el(S,g)))},[]),c=p.useCallback(C=>{o(S=>{if(S.length>=n)return S;const y=S[0]??null,g=C?.seedAudienceKeys??y?.audienceKeys??[],x=C?.seedWorkflowShape??y?.workflowShape??"sequential";return[...S,rd(vf(S,t),{audienceKeys:g,workflowShape:x})]})},[t,n]),u=p.useCallback(C=>{o(S=>S.length<=1?S:S.filter((y,g)=>g!==C))},[]),h=p.useCallback((C,S)=>{o(y=>ba(y,C,g=>({...g,audienceKeys:[...S]})))},[]),f=p.useCallback((C,S)=>{o(y=>Kg(y,C,S))},[]),m=p.useCallback((C,S)=>{o(y=>Ug(y,C,S))},[]),v=p.useCallback(C=>{o(S=>ba(S,C,y=>({...y,workflowShape:y.workflowShape==="concurrent"?"sequential":"concurrent"})))},[]);return{draftParallelChatTargets:s,resetDraftParallelChatTargets:i,onDraftParallelChatTargetChange:d,onAddDraftParallelChatTarget:c,onRemoveDraftParallelChatTarget:u,onSetDraftParallelBranchAudienceKeys:h,onSetDraftParallelBranchCwd:f,onSetDraftParallelBranchRuntimeSessionPolicy:m,onToggleDraftParallelBranchWorkflowShape:v}}function Hg(e,t){const{t:n}=Q();p.useEffect(()=>{document.title=t?`${pr(t,n)} - ${e}`:e},[e,t,n])}const qg=[/^cats core state returned \d+$/u,/^cats core approvals returned \d+$/u,/^cats core approval returned \d+$/u,/^cats core operator action returned \d+$/u,/^cats channel messaging returned \d+$/u,/^cats channel cancel returned \d+$/u,/^cats channel participant update returned \d+$/u,/^cats channel continuity reset returned \d+$/u,/^channel message retry returned \d+$/u,/^parallel chat relay returned \d+$/u,/^parallel chat cancel returned \d+$/u];function Gg(e,t){const n=tc(e,t);return n||(e==="The active chat is not part of this Parallel chat group."?t(l.chatComposerErrorActiveChatNotInParallelGroup):e==="The source chat is not part of this Parallel chat group."?t(l.chatComposerErrorSourceChatNotInParallelGroup):e==="One or more parallel branch inputs target a chat outside this Parallel chat group."?t(l.chatComposerErrorParallelBranchOutsideGroup):e==="No parallel chat targets were selected for this relay."?t(l.chatComposerErrorNoParallelRelayTargets):e==="Message not found."||e.startsWith("Channel message not found:")?t(l.chatComposerErrorMessageNotFound):e==="At least one participant field must be updated."?t(l.chatParticipantsErrorNoFields):e.startsWith("Channel participant assignment not found:")||e.startsWith("Temporary participant assignment not found:")?t(l.chatParticipantsErrorNotFound):e==="Only temporary participants can be renamed here."?t(l.chatParticipantsErrorTemporaryOnly):e==="Temporary participant name is required"?t(l.chatParticipantsErrorNameRequired):e==="Only user messages can be retried."?t(l.chatComposerErrorRetryInvalidSender):e==="Cannot retry while this room already has an active turn."?t(l.chatComposerErrorRetryInProgress):e==="Only the latest acknowledged user message can be retried."?t(l.chatComposerErrorRetryNotLatest):e==="Retry is only available for the latest failed acknowledged user message."?t(l.chatComposerErrorRetryNotAvailable):null)}function Gt(e,t,n){if(!(e instanceof Error))return t;const a=Gg(e.message,n);return a||(qg.some(s=>s.test(e.message))?t:e.message)}const Vg=5e3;function zg(e,t){const{t:n}=Q(),[a,s]=p.useState({status:"idle",snapshot:null,message:""}),o=p.useRef(0),i=p.useCallback((d={})=>{if(!e?.setupCompleteAt)return o.current+=1,s({status:"idle",snapshot:null,message:""}),()=>{};const c=new AbortController,u=o.current+1;return o.current=u,d.background||s(h=>({status:"loading",snapshot:h.snapshot,message:""})),Ir(c.signal).then(h=>{c.signal.aborted||u!==o.current||p.startTransition(()=>{s({status:"ready",snapshot:h,message:""})})}).catch(h=>{c.signal.aborted||u!==o.current||s(f=>d.background&&f.snapshot?f:{status:"error",snapshot:f.snapshot,message:Gt(h,n(l.sharedOperatorLoopLoadError),n)})}),()=>c.abort()},[e?.setupCompleteAt,n]);return p.useEffect(()=>i(),[t,i]),p.useEffect(()=>{if(!e?.setupCompleteAt||typeof window>"u"||typeof document>"u")return;const d=()=>{document.visibilityState!=="hidden"&&i({background:!0})},c=window.setInterval(d,Vg),u=()=>{d()},h=()=>{document.visibilityState==="visible"&&d()};return window.addEventListener("focus",u),document.addEventListener("visibilitychange",h),()=>{window.clearInterval(c),window.removeEventListener("focus",u),document.removeEventListener("visibilitychange",h)}},[e?.setupCompleteAt,i]),{operatorState:a,refreshOperatorSnapshot:i,setOperatorState:s}}function Yg({updateCatProfile:e,publishReadyPayload:t,onError:n}){return p.useCallback(async(a,s)=>{try{const o=await e(a,{provider:s.provider,instance:s.instance,model:s.model,modelSelection:s.modelSelection});return p.startTransition(()=>t(o)),!0}catch(o){return n?.(o),!1}},[n,t,e])}function Jg({resetChannelContinuity:e,publishReadyPayload:t,setBusy:n,setFeedback:a}){const{t:s}=Q();return p.useCallback(async o=>{n(Ur("reset")),a("");try{const i=await e(o);p.startTransition(()=>t(i))}catch(i){a(Gt(i,s(l.sharedChannelContinuityStartFreshError),s))}finally{n(Fe())}},[t,e,n,a,s])}function Qg(e){const{updateChannelParticipantApi:t,setBusy:n,setFeedback:a,setState:s}=e,{t:o}=Q();return p.useCallback(async(i,d,c)=>{n(Ip(d));try{const u=await t(i,d,c);p.startTransition(()=>{s({status:"ready",payload:u}),a("")})}catch(u){a(Gt(u,o(l.chatParticipantsErrorUpdateParticipant),o))}finally{n(Fe())}},[n,a,s,o,t])}function Xg(e){const{selectedChannel:t,selectedParallelChatGroup:n,relayParallelChatMessage:a,setBusy:s,setFeedback:o,setState:i}=e,{locale:d,t:c}=Q();return p.useCallback(async(u,h)=>{if(!(!t||!n)){s(Xn("relay")),o("");try{const f=await a(n.id,{activeChannelId:t.id,sourceChannelId:t.id,sourceMessageId:u,command:h,targetPolicy:"all_others",locale:d});p.startTransition(()=>i({status:"ready",payload:f.appShell}));const m=f.results.filter(v=>v.status==="error");m.length>0&&o(m.map(v=>v.error||c(l.chatComposerErrorRelayFailedForChannel,{channelId:v.channelId})).join(" "))}catch(f){o(Gt(f,c(l.chatComposerErrorRelayCompareFailed),c))}finally{s(Fe())}}},[a,t,n,s,o,i,d,c])}function nl(e){if(typeof e!="object"||e===null)return null;const t=e.metadata;if(typeof t!="object"||t===null)return null;const n=t.generatedAt;if(typeof n!="string")return null;const a=Date.parse(n);return Number.isNaN(a)?null:a}function Zg(e,t){const n=nl(e),a=nl(t);return n===null||a===null?!0:a>=n}function eC(e){return p.useCallback(t=>{p.startTransition(()=>e(n=>n.status==="ready"&&!Zg(n.payload,t)?n:{status:"ready",payload:t}))},[e])}function tC(e){const{addCatOpen:t,channelPlusMenuOpen:n,plusMenuOpen:a,draftCwd:s,draftDefaultRecipientCatId:o,navigate:i,chatPrefix:d,emptyCatForm:c,resolveDraftDefaultRecipientPath:u,setAddCatOpen:h,setAddCatTab:f,setFeedback:m,setCatForm:v,setPlusMenuOpen:C,setChannelPlusMenuOpen:S,channelFileInputRef:y,fileInputRef:g,openFolderBrowser:x,onDraftScreenshotCapture:I,onChannelScreenshotCapture:k}=e;function P(){h(!t),f("existing"),m(""),v(c())}function A(){S(!n)}function M(){y.current?.click(),S(!1)}function D(){k?.(),S(!1)}function N(){C(!a)}function R(){g.current?.click(),C(!1)}function w(){I?.(),C(!1)}function b(){x(s),C(!1)}function T(){C(!1),h(!0),f("existing"),v(c()),m("")}function E(O){O!==o&&i(u?.(O)??To(d,O),{replace:!0})}return{toggleAddCatPanel:P,toggleChannelPlusMenu:A,openChannelFilePicker:M,captureAndAttachChannelScreenshot:D,toggleDraftPlusMenu:N,openDraftFilePicker:R,captureAndAttachDraftScreenshot:w,openDraftFolderPicker:b,openDraftAddCatPanel:T,changeDraftDefaultRecipient:E}}function al(e,t){return Xr(ao(e),t)}function nC(e){switch(e.entityKind){case"channel":case"conversation":return al(e.surface,e.entityId);case"parallel-group":{const t=e.activeChannelId?.trim();if(!t)throw new Error("Parallel group handoff requires an active channel route target.");return al(e.surface,t)}default:throw new Error(`No cross-surface navigation path builder is registered for ${e.entityKind}.`)}}function aC(e){return{surface:e.surface,path:nC(e)}}function rC(e){return typeof e=="string"?e:e.surface}function sC(e){return Sp(rC(e))}const oC=6e4,iC="__catsCrossSurfaceNavigationHandoffTelemetry",Be={counters:{stage:0,hit:0,miss:{missing:0,stale:0,invalid:0}},activeStagedTargets:[],latestStage:null,latestHit:null,latestMiss:null};function Qo(e){return{sourceSurface:e.sourceSurface,targetSurface:e.targetSurface,entityKind:e.destination.entityKind,entityId:e.destination.entityId,route:{surface:e.destination.route.surface,path:e.destination.route.path}}}function Pr(){Be.activeStagedTargets=[...br.values()].map(Qo),uC()}function lC(e){Be.counters.stage+=1,Be.latestStage=Qo(e),Pr()}function cC(e,t){Be.counters.hit+=1,Be.latestHit={...Qo(t),match:{surface:e.surface,path:La(e.path)}},Pr()}function Js(e,t){Be.counters.miss[t]+=1,Be.latestMiss={match:{surface:e.surface,path:La(e.path)},reason:t},Pr()}function dC(){return{counters:{stage:Be.counters.stage,hit:Be.counters.hit,miss:{missing:Be.counters.miss.missing,stale:Be.counters.miss.stale,invalid:Be.counters.miss.invalid}},activeStagedTargets:Be.activeStagedTargets.map(e=>({...e,route:{surface:e.route.surface,path:e.route.path}})),latestStage:Be.latestStage?{...Be.latestStage,route:{surface:Be.latestStage.route.surface,path:Be.latestStage.route.path}}:null,latestHit:Be.latestHit?{...Be.latestHit,route:{surface:Be.latestHit.route.surface,path:Be.latestHit.route.path},match:{surface:Be.latestHit.match.surface,path:Be.latestHit.match.path}}:null,latestMiss:Be.latestMiss?{reason:Be.latestMiss.reason,match:{surface:Be.latestMiss.match.surface,path:Be.latestMiss.match.path}}:null}}function uC(){const e=globalThis;e[iC]=dC()}const br=new Map,sd=new Set;function pC(e,t){br.set(e,t),sd.clear(),Pr()}function Qs(e){const t=br.delete(e);return t&&(sd.clear(),Pr()),t}function rl(e,t){return e<t?-1:e>t?1:0}function La(e){const t=e.trim();if(!t)return"";try{const n=new URL(t.startsWith("/")?t:`/${t}`,"https://cats.local"),a=n.pathname,s=[...n.searchParams.entries()].sort(([i,d],[c,u])=>i===c?rl(d,u):rl(i,c)),o=s.length>0?`?${new URLSearchParams(s).toString()}`:"";return`${a}${o}`}catch{return t}}function hC(e,t=""){return La(`${e}${t}`)}function od(e){return`${e.surface}:${La(e.path)}`}function fC(e){const t=Date.parse(e.createdAt);return Number.isNaN(t)?!1:Date.now()-t<=oC}function id(e,t){const n=t?.consume===!0,a=od(e),s=br.get(a)??null;return s?vC(s,e)?fC(s)?(n&&(Qs(a),cC(e,s)),s):(n&&(Qs(a),Js(e,"stale")),null):(n&&(Qs(a),Js(e,"invalid")),null):(n&&br.size>0&&Js(e,"missing"),null)}function mC(e){const t={...e,destination:{...e.destination,route:{...e.destination.route,path:La(e.destination.route.path)}}};pC(od(t.destination.route),t),lC(t)}function ld(e){return id(e)}function gC(e){return ld(e)?.snapshot?.appShellPayload??null}function CC(e){return IC(e)?.snapshot?.appShellPayload??null}function vC(e,t){return e.targetSurface===t.surface&&e.destination.route.surface===t.surface&&e.destination.route.path===La(t.path)}function IC(e){return id(e,{consume:!0})}function SC(e){const t=e.channelId.trim();if(!t||e.sourceSurface===e.targetSurface)return null;const n=aC({surface:e.targetSurface,entityKind:"conversation",entityId:t});return mC({kind:"navigate-conversation",sourceSurface:e.sourceSurface,targetSurface:e.targetSurface,destination:{entityKind:"conversation",entityId:t,route:n},createdAt:new Date().toISOString(),snapshot:e.snapshotPayload?{appShellPayload:e.snapshotPayload}:void 0,optimisticState:{pendingExecution:!1,selectedChannelId:t}}),n}function qr({setDraftCwd:e,setDraftCatIds:t,setDraftHighlightedCatId:n,setDraftCatExecutionTargetOverrides:a,resetDraftSurface:s,setDraftRuntimeSessionPolicy:o,setDraftFiles:i,setDraftTemporaryParticipants:d,setChannelFiles:c,resetDraftParallelChatTargets:u,setDraftWorkflowShape:h,setDraftAudienceKeys:f}){e(null),t([]),d?.([]),n(null),a(new Map),s?.(),o?.(jo()),i([]),c?.([]),u?.(),h?.("sequential"),f?.(null)}const yC={deleteChatChannel:Ap,deleteGlobalCat:Pp,deleteParallelChatGroup:kp,renameChatChannel:yp,renameParallelChatGroup:wp,resetSetup:xp,ungroupParallelChatGroup:bp};function go(e){return!!(e&&typeof e=="object"&&"payload"in e&&"runtimeCleanup"in e)}function bC(e,t){if(!go(e)||e.runtimeCleanup.retainedSessionCount===0)return"";const n=e.runtimeCleanup.retainedSessionCount;return t(n===1?l.sharedWorkspaceNavigationDeleteChannelRuntimeCleanupFeedbackOne:l.sharedWorkspaceNavigationDeleteChannelRuntimeCleanupFeedbackMany,{count:n})}function xC(e){const{state:t,setState:n,navigate:a,platformShellSurface:s,setBusy:o,setFeedback:i,setComposerDraft:d,resetDraftComposer:c,navigationSnapshot:u,setAccountMenuOpen:h,setAddCatOpen:f,setPlusMenuOpen:m,setChannelPlusMenuOpen:v,setDraftCwd:C,setDraftCatIds:S,setDraftTemporaryParticipants:y,setDraftHighlightedCatId:g,setDraftCatExecutionTargetOverrides:x,setDraftSurface:I,setDraftRuntimeSessionPolicy:k,setDraftWorkflowShape:P,setDraftAudienceKeys:A,resetDraftParallelChatTargets:M,createInitialGroupParticipants:D,seedInitialGroupParticipants:N=!0,setDraftFiles:R,setChannelFiles:w,navigationApi:b,confirm:T}=e,{t:E}=Q(),O=ao(s),H=b??yC,U=p.useCallback(V=>{f(!1),m(!1),qr({setDraftCwd:C,setDraftCatIds:S,setDraftTemporaryParticipants:y,setDraftHighlightedCatId:g,setDraftCatExecutionTargetOverrides:x,resetDraftSurface:()=>I?.(s),setDraftRuntimeSessionPolicy:k,setDraftWorkflowShape:P,setDraftAudienceKeys:A,resetDraftParallelChatTargets:()=>{M?.({includeCompareTarget:V?.includeCompareTarget??!1})},setDraftFiles:R,setChannelFiles:c?void 0:w}),v(!1)},[f,m,C,S,y,g,x,I,s,k,P,A,M,R,w,v,c]),L=p.useCallback(()=>{t.status==="ready"&&(a(hr(O,t.payload.chat.channels,t.payload.chat.selectedChannelId,s)),i(""),f(!1))},[O,a,s,f,i,t]),$=p.useCallback(V=>{const ne=(t.status==="ready"?t.payload.chat.channels.find(tt=>tt.id===V)??null:null)?.originSurface??s,Oe=SC({sourceSurface:s,targetSurface:ne,channelId:V,snapshotPayload:u});Oe&&sC(ne),a(Oe?.path??Xr(ao(ne),V)),i(""),f(!1),v(!1)},[a,s,u,f,w,v,i,t]),X=p.useCallback(async(V,re)=>{o(Ur("rename",V));try{const ne=await H.renameChatChannel(V,re);p.startTransition(()=>{n({status:"ready",payload:ne}),i("")})}catch(ne){i(Ia(ne,E(l.sharedWorkspaceNavigationRenameChatError),E))}finally{o(Fe())}},[H,o,i,n,E]),ke=p.useCallback(async(V,re)=>{o(Ur("delete",re));try{const ne=await H.deleteChatChannel(re),Oe=go(ne)?ne.payload:ne;p.startTransition(()=>{n({status:"ready",payload:Oe}),f(!1),i("")}),a(Rp(O,V))}catch(ne){i(Ia(ne,E(l.sharedWorkspaceNavigationDeleteChatError),E))}finally{o(Fe())}},[O,a,H,f,o,i,n,E]),z=p.useCallback(async V=>{o(Ur("delete",V));try{const re=await H.deleteChatChannel(V),ne=go(re)?re.payload:re,Oe=bC(re,E);p.startTransition(()=>{n({status:"ready",payload:ne}),f(!1),i(Oe)}),a(hr(O,ne.chat.channels,ne.chat.selectedChannelId,s))}catch(re){i(Ia(re,E(l.sharedWorkspaceNavigationDeleteChatError),E))}finally{o(Fe())}},[O,a,H,s,f,o,i,n,E]),B=p.useCallback(async(V,re)=>{o(Es("rename",V));try{const ne=await H.renameParallelChatGroup(V,{title:re});p.startTransition(()=>{n({status:"ready",payload:ne}),i("")})}catch(ne){i(Ia(ne,E(l.sharedWorkspaceNavigationRenameParallelChatError),E))}finally{o(Fe())}},[H,o,i,n,E]),ae=p.useCallback(async V=>{o(Es("ungroup",V));try{const re=await H.ungroupParallelChatGroup(V);p.startTransition(()=>{n({status:"ready",payload:re}),i("")})}catch(re){i(Ia(re,E(l.sharedWorkspaceNavigationUngroupParallelChatError),E))}finally{o(Fe())}},[H,o,i,n,E]),he=p.useCallback(async V=>{const re=E(l.sharedWorkspaceNavigationParallelChatFallbackName),ne=t.status==="ready"?t.payload.chat.parallelChatGroups?.find(tt=>tt.id===V)?.title??re:re;if(!T||await T(Np(ne,E))){o(Es("delete",V));try{const tt=await H.deleteParallelChatGroup(V);p.startTransition(()=>{n({status:"ready",payload:tt}),f(!1),i("")}),a(hr(O,tt.chat.channels,tt.chat.selectedChannelId,s))}catch(tt){i(Ia(tt,E(l.sharedWorkspaceNavigationDeleteParallelChatGroupError),E))}finally{o(Fe())}}},[O,T,a,H,s,f,o,i,n,t,E]),Y=p.useCallback(async V=>{const re=t.status==="ready"?t.payload.chat.cats?.find(Oe=>Oe.id===V)?.name??null:null;if(!T||await T(Tp(re,E))){o(ya("delete",V));try{const Oe=await H.deleteGlobalCat(V);p.startTransition(()=>n({status:"ready",payload:Oe}))}catch(Oe){i(ac(Oe,E(l.sharedSettingsCatsDeleteError),E))}finally{o(Fe())}}},[T,H,o,i,n,t,E]),G=p.useCallback(()=>{a("/settings/general",{state:{platformShellSurface:s}}),h(!1),f(!1),i("")},[a,s,h,f,i]),W=p.useCallback(()=>{a("/settings/runtime",{state:{platformShellSurface:s}}),h(!1),f(!1),i("")},[a,s,h,f,i]),ue=p.useCallback(()=>{a("/settings/cats/new",{state:{platformShellSurface:s}}),h(!1),f(!1),i("")},[a,s,h,f,i]),pe=p.useCallback(async V=>{if(t.status!=="ready")return;const re=jp(O,t.payload.chat.channels.slice(),V);i(""),U(),a(re.path)},[O,U,a,i,t]),We=p.useCallback(async()=>{if(!T||await T({title:E(l.settingsDataResetAllDataTitle),message:E(l.settingsDataResetAllDataDescription),confirmLabel:E(l.settingsDataResetButtonLabel)})){o(Lp());try{const re=await H.resetSetup();Mp(),await Ep({bootstrapAttemptId:re.bootstrapAttemptId??null,setupCompleteAt:re.setupCompleteAt??null,products:Array.isArray(re.products)?[...re.products]:[]}),window.location.href="/"}catch(re){throw o(Fe()),re}}},[T,H,o,E]),Z=p.useCallback(async()=>{const V=To(O,null);a(V),c?c(V):d(""),U({includeCompareTarget:!1}),i("")},[O,U,a,d,c,i]),Ke=p.useCallback(async()=>{const V=Dp(O);a(V),c?c(V):d(""),U({includeCompareTarget:!1}),i(""),N&&y?.(D?.()??[])},[O,U,a,d,c,y,D,N,i]),et=p.useCallback(async()=>{const V=Bp(O);a(V),c?c(V):d(""),U({includeCompareTarget:!0}),i("")},[O,U,a,d,c,i]);return{onOpenChatsOverview:L,onSelect:$,onRenameChannel:X,onDeleteChannel:z,onClearDirectLane:ke,onRenameParallelChatGroup:B,onUngroupParallelChatGroup:ae,onDeleteParallelChatGroup:he,onDeleteCat:Y,onNavigateSettings:G,onNavigateRuntime:W,onCreateNewCat:ue,onDirectChatCat:pe,onResetSetup:We,onStartNewChat:Z,onStartNewGroupChat:Ke,onStartNewParallelChat:et}}class wC{constructor(t=Op){this.write=t}wanted=null;controller=null;retryTimer=null;failures=0;scope=null;savedId=null;select(t,n){this.scope!==null&&this.scope!==t&&this.clear(),this.scope=t,!(this.wanted?.id===n||!this.wanted&&this.savedId===n)&&(this.wanted={scope:t,id:n},this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=null,this.flush())}clear(){this.wanted=null,this.controller?.abort(),this.retryTimer&&clearTimeout(this.retryTimer),this.retryTimer=null,this.failures=0,this.scope=null,this.savedId=null}async flush(){if(this.controller||!this.wanted)return;const t=this.wanted,n=new AbortController;this.controller=n;const a=setTimeout(()=>n.abort(),15e3);let s=!1;try{if(await this.write(t.id,n.signal),n.signal.aborted)throw new Error("Selection persistence reset");this.savedId=t.id,this.wanted===t&&(this.wanted=null),this.failures=0}catch{s=!0}finally{clearTimeout(a),this.controller=null}if(!this.wanted)return;if(!s||this.wanted!==t){this.flush();return}const o=Math.min(250*2**this.failures++,1e4);this.retryTimer=setTimeout(()=>{this.retryTimer=null,this.flush()},o)}}const Co=new wC;Lo(()=>Co.clear());const kC=5e3;function sl(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function PC(e){return!sl(e)||!sl(e.chat)?!1:Array.isArray(e.chat.channels)&&Array.isArray(e.chat.cats)&&(typeof e.chat.selectedChannelId=="string"||e.chat.selectedChannelId===null)}function AC(e){return PC(e)}function RC(e){const t=CC(e);return AC(t)?t:null}function NC(e){const t=e.consumeWarmPayload?.(e.match)??RC(e.match);return e.initialHadReadyState?null:t}async function TC(e){const t=NC({initialHadReadyState:e.initialHadReadyState,match:e.match,consumeWarmPayload:e.consumeWarmPayload});t&&e.onReady(t);try{const n=await e.fetchAppShell(e.signal);if(e.signal.aborted)return;e.onReady(n)}catch(n){!e.signal.aborted&&!t&&!e.initialHadReadyState&&e.onError(jC(n,e.unknownRendererErrorMessage))}}function jC(e,t){return e instanceof Error?/^cats app shell returned \d+$/u.test(e.message)?t:e.message:t}function LC(e,t){const n=Date.parse(e.metadata.generatedAt),a=Date.parse(t.metadata.generatedAt);return Number.isNaN(n)||Number.isNaN(a)?!0:a>=n}function MC(e,t){return{...e,runtime:t.runtime,runtimeSetup:t.runtimeSetup,metadata:t.metadata,bootstrapAttemptId:t.bootstrapAttemptId}}function EC(e,t){return e.status!=="ready"||!LC(e.payload,t)?e:{status:"ready",payload:MC(e.payload,t)}}function DC(e){const{state:t,setState:n,navigate:a,busy:s,surface:o,currentPath:i,chatPrefix:d,routeChannelId:c,routeChannelExists:u,selectedChannelId:h,draftDefaultRecipientCatId:f,showingMyCatDirectLane:m,routeDirectLaneSummary:v,unknownRendererErrorMessage:C,fetchAppShell:S=Mo,isRouteSelectionBlocked:y=Xm,resolveMissingDraftDefaultRecipientPath:g}=e,x=t.status==="ready"?t.payload:null,I=x?hr(d,x.chat.channels,h,o):Ii(d),k=x&&f?g?.({channels:x.chat.channels,selectedChannelId:x.chat.selectedChannelId,draftDefaultRecipientCatId:f,showingMyCatDirectLane:m})??(m?hr(d,x.chat.channels,x.chat.selectedChannelId,o):Ii(d)):null,P=f?x?.chat.cats.some(N=>N.id===f&&N.status==="active"):!1,A=v?.id??null,M=p.useRef({surface:o,path:i}),D=p.useRef(t.status==="ready");p.useEffect(()=>{const N=new AbortController;return TC({initialHadReadyState:D.current,match:{surface:M.current.surface,path:M.current.path},fetchAppShell:S,signal:N.signal,unknownRendererErrorMessage:C,onReady:R=>{p.startTransition(()=>{n({status:"ready",payload:R})})},onError:R=>{n({status:"error",message:R})}}),()=>N.abort()},[S,n]),p.useEffect(()=>{if(t.status!=="ready"||typeof window>"u"||typeof document>"u")return;let N=null;const R=()=>{if(document.visibilityState==="hidden"||N)return;const E=new AbortController;N=E,S(E.signal).then(O=>{E.signal.aborted||p.startTransition(()=>{n(H=>EC(H,O))})}).catch(()=>{}).finally(()=>{N===E&&(N=null)})},w=window.setInterval(R,kC),b=()=>{R()},T=()=>{document.visibilityState==="visible"&&R()};return window.addEventListener("focus",b),document.addEventListener("visibilitychange",T),()=>{N&&N.abort(),window.clearInterval(w),window.removeEventListener("focus",b),document.removeEventListener("visibilitychange",T)}},[S,n,t.status]),p.useEffect(()=>{if(!(!x||!c)&&!y(s,c)&&!Zl(c)){if(!u){a(I,{replace:!0});return}Co.select(x.scopeId??"",c)}},[s,d,a,u,c,I,x?.scopeId,t.status]),p.useEffect(()=>{!x||!f||!P&&k&&a(k,{replace:!0})},[f,P,k,a,x]),p.useEffect(()=>{!x||!m||!f||!A||Co.select(x.scopeId??"",A)},[f,x?.scopeId,t.status,A,m])}function ol(e,t,n=""){return JSON.stringify([n,e,t])}class BC{entries=new Map;canOpen;createEventSource;constructor(t){this.canOpen=t!==void 0||typeof EventSource<"u",this.createEventSource=t??(n=>new EventSource(n))}subscribe(t){if(t.enabled===!1||!t.id)return()=>{};const n=ol(t.kind,t.id,t.scopeKey);let a=this.entries.get(n);a||(a={kind:t.kind,id:t.id,scopeKey:t.scopeKey,callbacks:new Set,source:null,retryCount:0,retryTimer:null,closed:!1},this.entries.set(n,a),this.open(a));const s={onSnapshot:t.onSnapshot,onPatch:t.onPatch,onClose:t.onClose};return a.callbacks.add(s),()=>{const o=this.entries.get(n);o&&(o.callbacks.delete(s),o.callbacks.size===0&&this.closeEntry(n,o))}}getActiveSubscribedIds(t){return[...this.entries.values()].filter(n=>n.kind===t&&n.callbacks.size>0).map(n=>n.id)}open(t){if(t.closed||!this.canOpen)return;const n=`/api/subscribe?kind=${encodeURIComponent(t.kind)}&id=${encodeURIComponent(t.id)}`,a=this.createEventSource(n);t.source=a,a.addEventListener("open",()=>{t.closed||t.source!==a||(t.retryCount=0)}),a.addEventListener("snapshot",s=>{if(t.closed||t.source!==a)return;const o=JSON.parse(s.data);if(!(o.kind!==t.kind||o.id!==t.id))for(const i of t.callbacks)i.onSnapshot(o)}),a.addEventListener("patch",s=>{if(t.closed||t.source!==a)return;const o=JSON.parse(s.data);if(!(o.kind!==t.kind||o.id!==t.id))for(const i of t.callbacks)i.onPatch(o)}),a.addEventListener("close",s=>{if(t.closed||t.source!==a)return;const o=JSON.parse(s.data);for(const i of t.callbacks)i.onClose?.(o);if(o.retryable){a.close(),t.source=null,this.scheduleReconnect(t);return}this.closeEntry(ol(t.kind,t.id,t.scopeKey),t)}),a.onerror=()=>{t.closed||t.source!==a||(a.close(),t.source===a&&(t.source=null),this.scheduleReconnect(t))}}scheduleReconnect(t){if(t.closed||t.callbacks.size===0||t.retryTimer)return;const n=Math.min(250*2**t.retryCount,1e4);t.retryCount+=1,t.retryTimer=setTimeout(()=>{t.retryTimer=null,this.open(t)},n)}closeEntry(t,n){n.closed=!0,n.retryTimer&&(clearTimeout(n.retryTimer),n.retryTimer=null),n.source?.close(),n.source=null,this.entries.delete(t)}}const cd=new BC;function dd(e,t=cd){const n=p.useRef(e.scopeKey);n.current=e.scopeKey;const a=p.useRef({onSnapshot:e.onSnapshot,onPatch:e.onPatch,onClose:e.onClose});a.current={onSnapshot:e.onSnapshot,onPatch:e.onPatch,onClose:e.onClose},p.useEffect(()=>t.subscribe({kind:e.kind,id:e.id,enabled:e.enabled,scopeKey:e.scopeKey,onSnapshot:s=>{n.current===e.scopeKey&&a.current.onSnapshot(s)},onPatch:s=>{n.current===e.scopeKey&&a.current.onPatch(s)},onClose:s=>{n.current===e.scopeKey&&a.current.onClose?.(s)}}),[t,e.enabled,e.id,e.kind,e.scopeKey])}function ud(e){return new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))}function il(e,t,n){const a=[...e];return a.splice(Math.max(0,Math.min(t,a.length)),0,n),a}function OC(e,t,n){let a=[...t.memberChannelIds],s=[...t.members];for(const o of n){const i=e.memberChannelIds.includes(o),d=t.memberChannelIds.includes(o);if(i&&!d){const c=e.memberChannelIds.indexOf(o);a=il(a,c,o);const u=e.members.find(h=>h.channelId===o);u&&!s.some(h=>h.channelId===o)&&(s=il(s,c,u));continue}!i&&d&&(a=a.filter(c=>c!==o),s=s.filter(c=>c.channelId!==o))}return{...t,memberChannelIds:a,members:s,memberCount:a.length}}function pd(e,t,n){const a=ud(n);if(a.size===0)return t;const s=new Map(e.map(c=>[c.id,c])),o=new Map(t.map(c=>[c.id,c])),i=[...t.map(c=>c.id),...e.map(c=>c.id).filter(c=>!o.has(c))],d=[];for(const c of i){const u=s.get(c)??null,h=o.get(c)??null;if(u&&h){d.push(OC(u,h,a));continue}if(h){d.push(h);continue}u&&u.memberChannelIds.some(f=>a.has(f))&&d.push(u)}return d}function _C(e){const t=e.assignedParticipants;return Array.isArray(t)&&t.length>0?t:e.assignedCats}function FC(e){const t=vs(e.roomRouting),n=_C(e),a=e.assignedCats??[],s=t.defaultRecipientId?a.find(o=>o.catId===t.defaultRecipientId):null;return{participantCount:n.length,activeParticipantCount:n.filter(o=>o.status==="active").length,catCount:a.length,activeCatCount:a.filter(o=>o.status==="active").length,defaultRecipientCatId:s?.catId??null,defaultRecipientLeaseStatus:s?.execution.lease.status??null}}function WC(e){const t=vs(e.roomRouting),n=t.workflow.activeTurn?.status??t.workflow.lastOutcomeEvent?.status??null;switch(n){case"pending":return"running";case"failed":return"error";case"idle":case"running":case"completed":case"blocked":return n;default:return t.lastOutcome?.status??"idle"}}function KC(e){const t=vs(e.roomRouting);return t.workflow.activeTurn?.updatedAt??t.workflow.lastOutcomeEvent?.createdAt??t.lastOutcome?.completedAt??t.lastCheckpoint?.createdAt??null}function hd(e,t){const n=vs(t.roomRouting),a=FC(t);return{...e,id:t.id,containerId:t.containerId,conversationId:t.conversationId,title:t.title,topic:t.topic,originSurface:t.originSurface??e?.originSurface,channelKind:t.channelKind??e?.channelKind,status:t.status,unreadCount:t.unreadCount,...a,repoPath:t.repoPath,chatCwd:t.chatCwd,runtimeWorkspaceKind:t.runtimeWorkspaceKind??null,runtimeWorkspaceAccess:t.runtimeWorkspaceAccess??null,runtimePermissionMode:t.runtimePermissionMode??null,lastMessageAt:t.lastMessageAt,lastActivatedAt:t.lastActivatedAt,pendingProvider:t.pendingProvider??e?.pendingProvider,pendingModel:t.pendingModel??e?.pendingModel,pendingModelSelection:t.pendingModelSelection??e?.pendingModelSelection??null,roomMode:n.mode,routingStatus:WC(t),lastRoutingAt:KC(t)}}function UC(e,t){const n=e.findIndex(s=>s.id===t.id);if(n===-1)return e;const a=[...e];return a[n]=hd(e[n],t),a}function $C(e){const t=ud(e.activeSubscribedIds);if(t.size===0)return e.nextChannels;const n=new Map(e.currentChannels.map(o=>[o.id,o])),a=new Set(e.nextChannels.map(o=>o.id)),s=e.nextChannels.map(o=>{if(!t.has(o.id))return o;const i=n.get(o.id)??o;return e.currentSelectedChannel?.id===o.id?hd(i,e.currentSelectedChannel):i});if(e.insertMissingActive===!1)return s;for(const o of t){if(a.has(o))continue;const i=n.get(o);i&&s.unshift(i)}return s}function HC(e){return new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))}function qC(e,t,n){const a=HC(n);if(a.size===0)return t;const s=e.chat.selectedChannelId&&a.has(e.chat.selectedChannelId);return{...t,chat:{...t.chat,selectedChannelId:s?e.chat.selectedChannelId:t.chat.selectedChannelId,selectedChannel:s?e.chat.selectedChannel:t.chat.selectedChannel,channels:$C({currentChannels:e.chat.channels,nextChannels:t.chat.channels,currentSelectedChannel:e.chat.selectedChannel,activeSubscribedIds:a}),parallelChatGroups:pd(e.chat.parallelChatGroups,t.chat.parallelChatGroups,a)}}}function GC(e,t){let n=t;for(const a of _p())n=Fp(e,n,a.channelId,a.optimisticMessageId);return n}function VC(e,t){const n=e?Date.parse(e):Number.NaN,a=t?Date.parse(t):Number.NaN;return Number.isNaN(n)||Number.isNaN(a)?!0:a>=n}function zC(e){const{enabled:t=!0,fetchAppShell:n=Mo,setState:a,state:s}=e,o=p.useRef(s.status==="ready"?s.payload:null),i=p.useRef(null),d=p.useRef(!1),c=p.useRef(!1);p.useEffect(()=>{o.current=s.status==="ready"?s.payload:null},[s]);const u=p.useCallback(()=>{if(d.current){c.current=!0;return}const h=new AbortController;i.current=h,d.current=!0;const f=()=>{d.current=!1,i.current===h&&(i.current=null),c.current&&(c.current=!1,u())};n(h.signal).then(m=>{if(h.signal.aborted||!VC(o.current?.metadata.generatedAt,m.metadata.generatedAt))return;const v=o.current,C=v?qC(v,m,cd.getActiveSubscribedIds("channel")):m,S=v?GC(v,C):C;o.current=S,p.startTransition(()=>{a({status:"ready",payload:S})})}).catch(()=>{}).finally(f)},[n,a]);return p.useEffect(()=>{if(!t||typeof EventSource>"u")return;let h=0,f=null,m=null;const v=()=>{m=new EventSource("/api/events/chat"),m.addEventListener("connected",()=>{h=0}),m.addEventListener("room_updated",u),m.addEventListener("recents_changed",u),m.addEventListener("unread_changed",u),m.addEventListener("transport_ingress",u),m.onerror=()=>{if(m?.close(),m=null,h<8){const C=Math.min(150*2**h,1e4);h+=1,f=setTimeout(v,C)}}};return v(),()=>{f&&clearTimeout(f),m?.close(),m=null,i.current?.abort(),i.current=null,d.current=!1,c.current=!1}},[t,u]),{refreshAppShell:u}}const YC=[/^cats chat cat creation returned \d+$/u,/^cats channel cat assignment returned \d+$/u,/^cats channel cat removal returned \d+$/u];function JC(e,t){const n=Wp(e,t);if(n)return n;if(e.startsWith("Channel not found:"))return t(l.chatCatAssignmentErrorChannelNotFound);if(e.startsWith("Channel cat assignment not found:"))return t(l.chatCatAssignmentErrorAssignmentNotFound);if(e==="Direct messages can only contain their direct recipient Cat")return t(l.chatCatAssignmentErrorDirectRecipientOnly);const a=e.match(/^Chat participant limit reached \(max (\d+)\)$/u);return a?t(l.chatCatAssignmentErrorParticipantLimitReached,{maxParticipants:a[1]}):null}function Or(e,t,n){if(!(e instanceof Error))return t;const a=JC(e.message,n);return a||(YC.some(s=>s.test(e.message))?t:e.message)}function ll(e){if(!(!e||e===rc))return e}function QC(e){const{state:t,setState:n,catForm:a,emptyCatForm:s,setCatForm:o,setBusy:i,setFeedback:d,setAddCatOpen:c,setDraftCatIds:u,createGlobalCat:h=Kp,assignCatToChannelApi:f=Up,removeCatFromChannelApi:m=$p}=e,{t:v}=Q(),C=p.useCallback(async I=>{if(I.preventDefault(),t.status!=="ready")return;const k=t.payload.chat.selectedChannelId;if(k){i(ya("create-assign"));try{const P=a.name.trim(),A=new Set(t.payload.chat.cats.map(R=>R.id)),M=await h({name:P,provider:a.provider,instance:a.instance||void 0,model:a.model||void 0,modelSelection:a.modelSelection,mcpProfile:ll(a.mcpProfile)});p.startTransition(()=>n({status:"ready",payload:M}));const D=M.chat.cats.find(R=>!A.has(R.id));if(!D){o(s()),d(v(l.chatCatAssignmentCreatedAssignHint)),i(Fe());return}const N=await f(k,{catId:D.id,provider:D.defaultExecutionTarget.provider,instance:D.defaultExecutionTarget.instance??void 0,model:D.defaultExecutionTarget.model??void 0,modelSelection:D.defaultModelSelection??void 0});p.startTransition(()=>{n({status:"ready",payload:N}),o(s()),c(!1),d("")})}catch(P){d(Or(P,v(l.chatCatAssignmentErrorCreateCat),v))}finally{i(Fe())}}},[a.instance,a.modelSelection,a.model,a.name,a.provider,a.mcpProfile,s,c,i,o,d,n,t,v]),S=p.useCallback(async I=>{if(t.status!=="ready")return;const k=t.payload.chat.selectedChannelId;if(k){i(ya("assign",I.id));try{const P=await f(k,{catId:I.id,provider:I.defaultExecutionTarget.provider,instance:I.defaultExecutionTarget.instance??void 0,model:I.defaultExecutionTarget.model??void 0,modelSelection:I.defaultModelSelection??void 0});p.startTransition(()=>{n({status:"ready",payload:P}),d("")})}catch(P){d(Or(P,v(l.chatCatAssignmentErrorAssignCat),v))}finally{i(Fe())}}},[i,d,n,t,v]),y=p.useCallback(async I=>{if(t.status!=="ready")return;const k=t.payload.chat.selectedChannelId;if(k){i(ya("remove",I.id));try{const P=await m(k,I.id);p.startTransition(()=>{n({status:"ready",payload:P}),d("")})}catch(P){d(Or(P,v(l.chatCatAssignmentErrorRemoveCat),v))}finally{i(Fe())}}},[i,d,n,t,v]),g=p.useCallback(I=>{u(k=>k.includes(I)?k.filter(P=>P!==I):[...k,I])},[u]),x=p.useCallback(async I=>{if(I.preventDefault(),t.status==="ready"){i(ya("create-assign"));try{const k=new Set(t.payload.chat.cats.map(M=>M.id)),P=await h({name:a.name.trim(),provider:a.provider,instance:a.instance||void 0,model:a.model||void 0,modelSelection:a.modelSelection,mcpProfile:ll(a.mcpProfile)});p.startTransition(()=>n({status:"ready",payload:P}));const A=P.chat.cats.find(M=>!k.has(M.id));A&&u(M=>[...M,A.id]),o(s()),c(!1),d("")}catch(k){d(Or(k,v(l.chatCatAssignmentErrorCreateCat),v))}finally{i(Fe())}}},[a.instance,a.modelSelection,a.model,a.name,a.provider,a.mcpProfile,s,c,i,o,u,d,n,t,v]);return{onAssignExistingCat:S,onCreateAndAssignCat:C,onCreateAndDraftCat:x,onRemoveAssignedCat:y,toggleDraftCat:g}}const XC=ia("en");function fd(e){return{composerDraft:e.composerDraft,draftCwd:e.draftCwd,draftRuntimeSessionPolicy:e.draftRuntimeSessionPolicy??null,draftAudienceKeys:e.draftAudienceKeys??null,draftWorkflowShape:e.draftWorkflowShape??"sequential",draftFiles:e.draftFiles}}function ZC(e){return!Array.isArray(e)||e.length===0?[]:e.filter((t,n,a)=>typeof t=="string"&&t.trim().length>0&&a.indexOf(t)===n)}function ev(e,t){return e.cwd??t.draftCwd}function tv(e,t){return e.promptOverride==null||e.promptOverride===""?t.composerDraft:e.promptOverride}function nv(e,t){return e.runtimeSessionPolicy??t.draftRuntimeSessionPolicy}function md(e,t){return ZC(e.audienceKeys??t.draftAudienceKeys)}function gd(e,t){return e.workflowShape??t.draftWorkflowShape}function av(e,t){return t.draftFiles}function rv(e,t=XC){const n=e.findIndex(a=>a.attachmentsOverride!=null);if(n!==-1)throw new Error(t(l.chatNewChatDraftBranchAttachmentOverrideError,{branchIndex:n+1}))}function Cd(e,t){return{target:e,effectivePrompt:tv(e,t),effectiveCwd:ev(e,t),effectiveSessionPolicy:nv(e,t),effectiveAudienceKeys:md(e,t),effectiveWorkflowShape:gd(e,t),effectiveAttachments:av(e,t),isDetached:{prompt:e.promptOverride!=null&&e.promptOverride!=="",cwd:e.cwd!=null,sessionPolicy:e.runtimeSessionPolicy!=null,audienceKeys:e.audienceKeys!=null,workflowShape:e.workflowShape!=null}}}const vd=ia("en");function cl(e){return Ro(e)??e.trim()}function sv(e,t){return e.chat.channels.some(n=>n.id===t&&n.routingStatus==="running")}function Id(e,t){return t.some(n=>sv(e,n))}function ov(e){const t=e.t??vd;rv(e.draftParallelChatTargets,t);const n=fd({composerDraft:e.body,draftCwd:e.draftCwd,draftRuntimeSessionPolicy:e.draftSessionPolicy,draftFiles:e.draftFiles??[],draftWorkflowShape:e.draftWorkflowShape,draftAudienceKeys:e.draftAudienceKeys}),a=e.draftParallelChatTargets.map(s=>Cd(s,n));return{title:qp(e.body,e.existingCount,t),originSurface:e.originSurface,repoPath:e.draftCwd??void 0,responseLanguage:e.assistantResponseLanguage,...e.draftSessionPolicy===void 0?{}:{runtimeSessionPolicy:e.draftSessionPolicy},targets:e.draftParallelChatTargets.map((s,o)=>{const i=a[o];return{provider:cl(s.provider),instance:s.instance??null,model:s.model??null,modelSelection:s.modelSelection??null,audienceKeys:i.effectiveAudienceKeys,...s.cwd===void 0?{}:{cwd:s.cwd},...s.runtimeSessionPolicy===void 0?{}:{runtimeSessionPolicy:s.runtimeSessionPolicy}}}),participantCatIds:e.draftParticipantCatIds??[],temporaryParticipants:(e.draftTemporaryParticipants??[]).map(s=>({participantId:s.participantId,name:s.name,provider:cl(s.provider),instance:s.instance??void 0,model:s.model??void 0,modelSelection:s.modelSelection??null,roleHint:s.roleHint??void 0}))}}async function iv({body:e,payload:t,originSurface:n,draftCwd:a,draftSessionPolicy:s,draftFiles:o,draftWorkflowShape:i,draftAudienceKeys:d,draftParallelChatTargets:c,draftParticipantCatIds:u=[],draftTemporaryParticipants:h=[],buildChannelPath:f,t:m=vd,signal:v}){if(c.length<2)throw new Error(m(l.chatComposerErrorChooseTwoParallelChats));const C=fd({composerDraft:e,draftCwd:a,draftRuntimeSessionPolicy:s,draftFiles:o,draftWorkflowShape:i,draftAudienceKeys:d}),S=c.map(k=>Cd(k,C)),y=await Hp(ov({body:e,existingCount:t.chat.channels.length,originSurface:n,draftCwd:a,draftSessionPolicy:s,draftFiles:o,draftWorkflowShape:i,draftAudienceKeys:d,draftParallelChatTargets:c,draftParticipantCatIds:u,draftTemporaryParticipants:h,assistantResponseLanguage:t.language?.assistantResponseLanguage,t:m}),v),g=y.appShell.chat.selectedChannelId?y.appShell.chat.selectedChannelId:y.group.members[0]?.channelId??null;if(!g)throw new Error(m(l.chatComposerErrorNoActiveParallelThread));const x=o.length>0?await sc(o):void 0,I=await oc(y.group.id,{activeChannelId:g,body:e,attachments:x,channelInputs:y.group.memberChannelIds.map((k,P)=>{const A=S[P];if(!A)return{channelId:k};const M=A.effectiveAudienceKeys,D=A.effectiveWorkflowShape,N=M.length>0?mc({draftParticipantCatIds:u,draftTemporaryParticipants:h,draftAudienceKeys:M,maxAudienceParticipants:t.chat.capabilities.maxAudienceParticipants??Number.POSITIVE_INFINITY}):[];return{channelId:k,body:A.effectivePrompt,messageMetadata:N.length>0?{recipientParticipantIds:N,workflowShape:D}:void 0}})},v);return{createdAppShell:y.appShell,dispatchAppShell:I.appShell,rollbackPath:f(g),dispatchRequest:Id(I.appShell,y.group.memberChannelIds)?{kind:"parallel",channelId:g,groupId:y.group.id,channelIds:y.group.memberChannelIds}:null}}async function lv({body:e,payload:t,compareGroupId:n,channelId:a,channelFiles:s,signal:o}){const i=t.chat.parallelChatGroups.find(u=>u.id===n)?.memberChannelIds??[a],d=s.length>0?await sc(s):void 0,c=await oc(n,{activeChannelId:a,body:e,attachments:d},o);return{dispatchAppShell:c.appShell,dispatchRequest:Id(c.appShell,i)?{kind:"parallel",channelId:a,groupId:n,channelIds:i}:null}}const cv=ia("en");function dv(e){return Ro(e)??e.trim()}function uv(e,t){return!e||!t?!1:e.channelKind==="direct_message"&&e.roomRouting?.defaultRecipientId===t}function pv(e){const{wasDraftingNewChat:t,isCatScopedLaneRoute:n,channelId:a,selectedChannel:s,defaultChannelExecutionTarget:o}=e;return t||n||s?.id!==a||!sa(s)?null:{pendingProvider:dv(o.provider),pendingModel:o.model,pendingInstance:o.instance,pendingModelSelection:o.modelSelection}}function hv(e){const{isCatScopedLaneRoute:t,hydratedDirectLane:n,wasDraftingNewChat:a,draftFiles:s,channelFiles:o}=e;return t&&!n?s:n?o:a?s:o}async function fv(e){const{channelId:t,body:n,filesToUpload:a,updateSelectedChannel:s,uploadChannelAttachments:o,signal:i}=e;let{payload:d}=e,c=n;if(a.length===0)return{payload:d,messageBody:c};const u=d.chat.selectedChannel?.id===t?d.chat.selectedChannel:null;!u?.repoPath&&!u?.chatCwd&&(d=await s(t,i));const h=await o(t,a,i);return c=Gp(n,h),{payload:d,messageBody:c}}async function mv(e){const{initialPayload:t,wasDraftingNewChat:n,isCatScopedLaneRoute:a,hydratedDirectLane:s,currentChannelId:o,currentRollbackPath:i,body:d,existingCount:c,draftCwd:u,draftSessionPolicy:h,originSurface:f,draftDefaultRecipientCatId:m,participantCatIds:v,temporaryParticipants:C=[],draftEntryKind:S,draftExecutionTarget:y,assistantResponseLanguage:g,t:x=cv,createChatChannel:I,insertCreatedChannelIntoPayload:k,setState:P,navigate:A,setChannelFiles:M,originalDraftFiles:D,originalChannelFiles:N,buildChannelPath:R,signal:w}=e;let b=t,T=t,E=o,O=i,H=()=>{M(n||a&&!s?D:N)};if(a)if(s)E=s.id,H=()=>{M(N)};else{const U=await I(Si({body:d,existingCount:c,originSurface:f,entryKind:"direct",repoPath:u,draftSessionPolicy:h,t:x,defaultRecipientCatId:m,participantCatIds:v,assistantResponseLanguage:g,temporaryParticipants:C.map(L=>({participantId:L.participantId,name:L.name,provider:L.provider,instance:L.instance??void 0,model:L.model??void 0,modelSelection:L.modelSelection??null,roleHint:L.roleHint??void 0}))}),w);if(E=U.id,!E)throw new Error(x(l.chatComposerErrorNoChatForSending));b=k(t,U),T=b,P({status:"ready",payload:b}),A(O,{replace:!0}),H=()=>{M(D)}}else if(n){const U=await I(Si({body:d,existingCount:c,originSurface:f,entryKind:S,repoPath:u,draftSessionPolicy:h,t:x,defaultRecipientCatId:m,participantCatIds:v,assistantResponseLanguage:g,temporaryParticipants:C.map(L=>({participantId:L.participantId,name:L.name,provider:L.provider,instance:L.instance??void 0,model:L.model??void 0,modelSelection:L.modelSelection??null,roleHint:L.roleHint??void 0})),draftExecutionTarget:y}),w);if(E=U.id,!E)throw new Error(x(l.chatComposerErrorNoChatForSending));O=R(E),b=k(t,U),T=b,P({status:"ready",payload:b}),A(O,{replace:!0}),H=()=>{M(D)}}else{if(!E)throw new Error(x(l.chatComposerErrorNoChatForSending));H=()=>{M(N)}}if(!E)throw new Error(x(l.chatComposerErrorNoChatForSending));return{payload:b,rollbackPayload:T,channelId:E,rollbackPath:O,restoreFiles:H}}async function gv(e){const{initialPayload:t,wasDraftingNewChat:n,isCatScopedLaneRoute:a,hydratedDirectLane:s,currentChannelId:o,currentRollbackPath:i,body:d,existingCount:c,draftCwd:u,draftSessionPolicy:h,originSurface:f,draftDefaultRecipientCatId:m,participantCatIds:v,temporaryParticipants:C,draftEntryKind:S,draftExecutionTarget:y,assistantResponseLanguage:g,t:x,selectedChannel:I,defaultChannelExecutionTarget:k,draftFiles:P,channelFiles:A,createChatChannel:M,insertCreatedChannelIntoPayload:D,setState:N,navigate:R,setChannelFiles:w,originalDraftFiles:b,originalChannelFiles:T,buildChannelPath:E,updateSelectedChannel:O,uploadChannelAttachments:H,signal:U}=e;let L=t;const $=await mv({initialPayload:t,wasDraftingNewChat:n,isCatScopedLaneRoute:a,hydratedDirectLane:s,currentChannelId:o,currentRollbackPath:i,body:d,existingCount:c,draftCwd:u,draftSessionPolicy:h,originSurface:f,draftDefaultRecipientCatId:m,participantCatIds:v,temporaryParticipants:C,draftEntryKind:S,draftExecutionTarget:y,assistantResponseLanguage:g,t:x,createChatChannel:M,insertCreatedChannelIntoPayload:D,setState:N,navigate:R,setChannelFiles:w,originalDraftFiles:b,originalChannelFiles:T,buildChannelPath:E,signal:U});L=$.payload;const X=pv({wasDraftingNewChat:n,isCatScopedLaneRoute:a,channelId:$.channelId,selectedChannel:I,defaultChannelExecutionTarget:k}),ke=hv({isCatScopedLaneRoute:a,hydratedDirectLane:s,wasDraftingNewChat:n,draftFiles:P,channelFiles:A}),z=await fv({payload:L,channelId:$.channelId,body:d,filesToUpload:ke,updateSelectedChannel:O,uploadChannelAttachments:H,signal:U});return L=z.payload,z.payload!==$.payload&&N({status:"ready",payload:L}),{...$,payload:L,rollbackPayload:z.payload!==$.payload?L:$.rollbackPayload,messageBody:z.messageBody,defaultDispatchTarget:X}}function Sd(){const e=globalThis.location;return e?`${e.pathname??""}${e.search??""}`:""}function Cv(e,t){return e==null||e===t}function vv(e){e.current=Sd()}function Iv(e){e.current=null}function Sv(e,t,n){const a=Sd();return Cv(e.current,a)?(t(n,{replace:!0}),e.current=n,!0):!1}function yv(e){return e==="sequential"||e==="concurrent"||e==="converge"||e==="parallel"?e:null}function bv(e){return e==="concurrent"?"concurrent":"sequential"}function xv(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.senderKind==="user")return n}return null}function yd(e){return`cat:${e}`}function Xo(e,t){if(!Number.isFinite(t))return[...e];const n=Math.max(1,Math.trunc(t??Number.POSITIVE_INFINITY));return e.slice(0,n)}function Zo(e){const t=new Set,n=[];for(const a of e){const s=a.trim();!s||t.has(s)||(t.add(s),n.push(s))}return n}function wv(e,t){return Xo(Zo(e.assignedCats.filter(n=>n.status==="active").map(n=>n.catId)),t)}function kv(e){const{audienceKeys:t}=e;if(!t||t.length===0)return[];const n=new Map(e.activeParticipantIds.map(a=>[yd(a),a]));return Xo(Zo(t.map(a=>n.get(a)??"")),e.maxAudienceParticipants)}function Pv(e){const t=bd(e),{selectedChannel:n}=e;return!n||!t?.recipientParticipantIds?.length?null:{audienceKeys:t.recipientParticipantIds.map(a=>yd(a)),workflowShape:bv(t.workflowShape)}}function bd(e){const{selectedChannel:t}=e;if(!t||sa(t)||!co(t))return null;const n=wv(t,e.maxAudienceParticipants);if(n.length===0)return null;const s=xv(t.messages)?.metadata??{},o=kv({activeParticipantIds:n,audienceKeys:e.audienceKeys,maxAudienceParticipants:e.maxAudienceParticipants}),i=Xo(Zo(Array.isArray(s.recipientParticipantIds)?s.recipientParticipantIds.filter(h=>typeof h=="string"):[]).filter(h=>n.includes(h)),e.maxAudienceParticipants);if(n.length<=1&&i.length===0)return null;const d=o.length>0?o:i.length>0?i:n,c=t.roomRouting.workflow.turnHistory[0]??null,u=yv(e.workflowShape??s.workflowShape??t.roomRouting.workflow.activeTurn?.workflowShape??c?.workflowShape??(d.length>1?"sequential":null));return d.length===0&&!u?null:{...d.length>0?{recipientParticipantIds:d}:{},...u?{workflowShape:u}:{}}}function Av({activeDispatchRequestRef:e,cancelPendingAckRequest:t,cancelChannel:n,cancelConcurrentGroup:a,setBusy:s,setFeedback:o,setState:i}){const{t:d}=Q(),c=p.useCallback(async()=>{const h=e.current;if(h){e.current=null,o(""),s(h.kind==="parallel"?Xn("stop"):Yn("stop",Jn(h.channelId)));try{const f=h.kind==="parallel"?await a(h.groupId??"",{activeChannelId:h.channelId}):await n(h.channelId);i({status:"ready",payload:f.appShell})}catch(f){o(Gt(f,d(l.chatComposerErrorStopFailed),d))}finally{s(Fe())}}},[e,n,a,s,o,i,d]);return{onCancelPendingSend:p.useCallback(()=>{t()&&o("")},[t,o]),onStopMessage:c}}function dl(e,t,n){return t.kind==="parallel"?(t.channelIds??[t.channelId]).some(a=>n(e,a)):n(e,t.channelId)}function ul(e,t){return t.kind==="parallel"?In(e,"dispatch"):zm(e)===t.channelId}function Rv(e){const{state:t,busy:n,setBusy:a,setState:s,fetchPayload:o,isChannelDispatchRunning:i,hydratePendingDispatch:d}=e,c=p.useRef(null),u=p.useRef(null),h=p.useRef(1),f=p.useRef(null);p.useEffect(()=>()=>{c.current?.controller.abort(),c.current=null,u.current=null},[]),p.useEffect(()=>{if(!d||t.status!=="ready"||u.current!==null)return;const g=d.kind==="channel"?d.channelId:d.groupId;if(!g||f.current===g)return;if(d.kind==="channel"){const{channelId:P}=d;if(!i(t.payload,P))return;f.current=g,u.current={id:h.current,kind:"channel",channelId:P},h.current+=1,a(Yn("send",Jn(P)));return}const{groupId:x,activeChannelId:I,channelIds:k}=d;k.length===0||!I||k.some(P=>i(t.payload,P))&&(f.current=g,u.current={id:h.current,kind:"parallel",channelId:I,groupId:x,channelIds:k},h.current+=1,a(Xn("dispatch")))},[d,i,a,t]),p.useEffect(()=>{if(t.status!=="ready")return;const g=u.current;!g||Vm(n)||dl(t.payload,g,i)||ul(n,g)&&(u.current=null,a(Fe()))},[n,i,a,t]),p.useEffect(()=>{const g=u.current;if(!g||!ul(n,g))return;let x=!1,I=!1;const k=window.setInterval(async()=>{if(!(x||I)){I=!0;try{const P=await o();if(x)return;s({status:"ready",payload:P});const A=u.current;if(!A||A.id!==g.id)return;dl(P,A,i)||(u.current=null,a(Fe()))}catch{}finally{I=!1}}},4e3);return()=>{x=!0,window.clearInterval(k)}},[n,o,i,a,s]);const m=p.useCallback(()=>{const g={id:h.current,controller:new AbortController};return h.current+=1,c.current=g,g},[]),v=p.useCallback(g=>{c.current?.id===g&&(c.current=null)},[]),C=p.useCallback(()=>{const g=c.current;return g?(c.current=null,g.controller.abort(),g):null},[]),S=p.useCallback(g=>{u.current=g},[]),y=p.useCallback(g=>{u.current?.id===g&&(u.current=null)},[]);return{activeDispatchRequestRef:u,beginAckRequest:m,cancelPendingAckRequest:C,clearAckRequestIfCurrent:v,clearDispatchRequestIfCurrent:y,setActiveDispatchRequest:S}}function Nv(e){const t=p.useCallback(async a=>{a.preventDefault(),await e()},[e]);return{onComposerKeyDown:p.useCallback(async a=>{Gm({key:a.key,shiftKey:a.shiftKey,ctrlKey:a.ctrlKey,metaKey:a.metaKey,altKey:a.altKey,isComposing:a.nativeEvent.isComposing})&&(a.preventDefault(),await e())},[e]),onSendMessage:t}}function Xs(e,t){return e.chat.channels.some(n=>n.id===t&&n.routingStatus==="running")}function pl(e){return e instanceof Error&&e.name==="AbortError"}function Tv(e){const{state:t,setState:n,navigate:a,chatPrefix:s,originSurface:o,currentPath:i,composerDraft:d,setComposerDraft:c,restoreConversationComposer:u,showingNewChatDraft:h,showingMyCatDirectLane:f,draftEntryKind:m="default",draftDefaultRecipientCatId:v,draftCatIds:C,draftTemporaryParticipants:S=[],draftCwd:y,draftSessionPolicy:g=null,draftFiles:x,channelFiles:I,setDraftCwd:k,setDraftCatIds:P,setDraftTemporaryParticipants:A,setDraftHighlightedCatId:M,setDraftCatExecutionTargetOverrides:D,setDraftRuntimeSessionPolicy:N,setDraftFiles:R,setChannelFiles:w,setDraftWorkflowShape:b,setDraftAudienceKeys:T,draftExecutionTarget:E,defaultChannelExecutionTarget:O,showingParallelChatDraft:H=!1,draftParallelChatTargets:U=[],draftWorkflowShape:L="sequential",draftAudienceKeys:$=null,activeWorkflowShape:X="sequential",activeAudienceKeys:ke=null,resetDraftParallelChatTargets:z,compareGroupId:B=null,compareSendScope:ae="active_only",selectedChannel:he,busy:Y,setBusy:G,setFeedback:W,hydratePendingDispatch:ue=null}=e,{t:pe}=Q(),We=p.useRef(null),{activeDispatchRequestRef:Z,beginAckRequest:Ke,cancelPendingAckRequest:et,clearAckRequestIfCurrent:V,clearDispatchRequestIfCurrent:re,setActiveDispatchRequest:ne}=Rv({state:t,busy:Y,setBusy:G,setState:n,fetchPayload:Mo,isChannelDispatchRunning:Xs,hydratePendingDispatch:ue}),{onCancelPendingSend:Oe,onStopMessage:tt}=Av({activeDispatchRequestRef:Z,cancelPendingAckRequest:et,cancelChannel:rh,cancelConcurrentGroup:ah,setBusy:G,setFeedback:W,setState:n}),Ne=p.useCallback(async()=>{if(t.status!=="ready")return;const nt=d.trim(),Ue=x.length>0,fe=I.length>0;if(!nt&&!Ue&&!fe)return;const Le=t.payload,Te=h,ye=!!v&&f,Ce=Jl(Le.chat.selectedChannel??null),Ft=uv(Ce,v)?Ce:null;let Me=Le,lt=Le,Pe=Te||f?Ft?.id??"":Le.chat.selectedChannelId,ht=f?Vp(s,v??""):Te?To(s,v):i;const ft=[...x],Ee=[...I];let Wt=()=>{Te||ye&&!Ft?R(ft):w(Ee)},Lt=null;const Mt=F=>Sv(We,a,F);W("");const{id:ct,controller:Et}=Ke();let st=!1;vv(We);try{if(H&&Te){G(Xn("ack"));const we=await iv({body:nt,payload:Le,originSurface:o,draftCwd:y,draftSessionPolicy:g,draftFiles:x,draftWorkflowShape:L,draftAudienceKeys:$,draftParallelChatTargets:U,draftParticipantCatIds:C,draftTemporaryParticipants:S,buildChannelPath:bn=>Xr(s,bn),t:pe,signal:Et.signal});lt=we.createdAppShell,ht=we.rollbackPath,Pe=we.createdAppShell.chat.selectedChannelId,c(""),R([]),Mt(ht),n({status:"ready",payload:we.createdAppShell}),Wt=()=>{w(ft)},V(ct),lt=we.dispatchAppShell,n({status:"ready",payload:we.dispatchAppShell}),we.dispatchRequest?(ne({id:ct,...we.dispatchRequest}),G(Xn("dispatch")),st=!0):ne(null),W(""),qr({setDraftCwd:k,setDraftCatIds:P,setDraftTemporaryParticipants:A,setDraftHighlightedCatId:M,setDraftCatExecutionTargetOverrides:D,setDraftRuntimeSessionPolicy:N,setDraftFiles:R,setDraftWorkflowShape:b,setDraftAudienceKeys:T}),z?.();return}if(B&&ae==="all_members"&&!Te){if(!Pe)throw new Error(pe(l.chatComposerErrorNoParallelChatForSending));ht=i,c(""),w([]),G(Xn("ack"));const we=await lv({body:nt,payload:Le,compareGroupId:B,channelId:Pe,channelFiles:I,signal:Et.signal});V(ct),lt=we.dispatchAppShell,n({status:"ready",payload:we.dispatchAppShell}),we.dispatchRequest?(ne({id:ct,...we.dispatchRequest}),G(Xn("dispatch")),st=!0):ne(null),W("");return}const F=Pe?Jn(Pe):zp();G(Yn("prepare",F));const le=await gv({initialPayload:Le,wasDraftingNewChat:Te,isCatScopedLaneRoute:ye,hydratedDirectLane:Ft,currentChannelId:Pe,currentRollbackPath:ht,body:nt,existingCount:Le.chat.channels.length,draftCwd:y,draftSessionPolicy:g,originSurface:o,draftDefaultRecipientCatId:v,participantCatIds:C,temporaryParticipants:S,draftEntryKind:m,draftExecutionTarget:E,assistantResponseLanguage:Le.language?.assistantResponseLanguage,selectedChannel:he,defaultChannelExecutionTarget:O,draftFiles:x,channelFiles:I,createChatChannel:Xp,insertCreatedChannelIntoPayload:Qp,setState:n,navigate:a,setChannelFiles:w,originalDraftFiles:ft,originalChannelFiles:Ee,buildChannelPath:we=>Xr(s,we),updateSelectedChannel:Jp,uploadChannelAttachments:Yp,t:pe,signal:Et.signal});Me=le.payload,lt=le.rollbackPayload,Pe=le.channelId,ht=le.rollbackPath,Wt=le.restoreFiles;const{messageBody:xe,defaultDispatchTarget:mt}=le,at=t.status==="ready"?t.payload.chat.capabilities.maxAudienceParticipants:void 0,sn=Te&&m==="group"&&!H?(()=>{const we=mc({draftParticipantCatIds:C,draftTemporaryParticipants:S,draftAudienceKeys:$,maxAudienceParticipants:at});return we.length>0?{recipientParticipantIds:we,workflowShape:L}:null})():null,Jt=Te?null:bd({selectedChannel:he,maxAudienceParticipants:at,audienceKeys:ke,workflowShape:X}),rt=sn??Jt;mt&&(Me=Zp(Me,Pe,mt));const Dt=eh(Me,Pe,xe);Me=Dt.payload,Lt=Dt.optimisticMessageId,th(Pe,Dt.optimisticMessageId),n({status:"ready",payload:Me}),c(""),R([]),w([]),Mt(ht),G(Yn("ack",Jn(Pe)));const gt=await ic(Pe,{body:xe,clientMessageId:Dt.optimisticMessageId,senderName:Me.ownerDisplayName,...mt??{},...rt?{messageMetadata:rt}:{}},Et.signal);yi(Pe,Dt.optimisticMessageId),Lt=null,V(ct),n({status:"ready",payload:gt.appShell}),Xs(gt.appShell,Pe)?(ne({id:ct,kind:"channel",channelId:Pe}),G(Yn("send",Jn(Pe))),st=!0):ne(null),c(""),W(""),Mt(ht),ye?qr({setDraftCwd:k,setDraftCatIds:P,setDraftTemporaryParticipants:A,setDraftHighlightedCatId:M,setDraftCatExecutionTargetOverrides:D,setDraftRuntimeSessionPolicy:N,setDraftFiles:R,setChannelFiles:w,setDraftWorkflowShape:b,setDraftAudienceKeys:T}):Te?(qr({setDraftCwd:k,setDraftCatIds:P,setDraftTemporaryParticipants:A,setDraftHighlightedCatId:M,setDraftCatExecutionTargetOverrides:D,setDraftRuntimeSessionPolicy:N,setDraftFiles:R,setDraftWorkflowShape:b,setDraftAudienceKeys:T}),z?.()):w([])}catch(F){V(ct),Z.current?.id===ct&&ne(null),Lt&&(yi(Pe,Lt),Lt=null),n({status:"ready",payload:lt}),u&&Pe&&lt.chat.channels.some(le=>le.id===Pe)?(c(""),u(Pe,nt,Te||ye&&!Ft?ft:Ee)):(c(nt),Wt()),pl(F)?W(""):W(Gt(F,pe(l.chatComposerErrorSendFailed),pe)),Mt(ht)}finally{st||(V(ct),re(ct),G(Fe())),Iv(We)}},[Z,Ke,I,s,V,re,d,u,i,C,S,y,g?.permissionMode,g?.workspaceAccess,g?.workspaceKind,x,m,v,o,E.instance,E.modelSelection,E.model,E.provider,a,he,ne,G,w,c,P,A,M,D,N,k,R,T,b,W,n,$,U,L,ke,X,B,ae,H,f,h,O.instance,O.modelSelection,O.model,O.provider,z,t,pe]),{onSendMessage:Ot,onComposerKeyDown:Yt}=Nv(Ne),_t=p.useCallback(async nt=>{if(t.status!=="ready"||!he||!nt.trim())return;const Ue=he.id;W("");const{id:fe,controller:Le}=Ke();let Te=!1;try{G(Yn("ack",Jn(Ue)));const ye=await nh(Ue,nt,Le.signal);V(fe),n({status:"ready",payload:ye.appShell}),Xs(ye.appShell,Ue)?(ne({id:fe,kind:"channel",channelId:Ue}),G(Yn("send",Jn(Ue))),Te=!0):ne(null),W("")}catch(ye){V(fe),Z.current?.id===fe&&ne(null),pl(ye)?W(""):W(Gt(ye,pe(l.chatComposerErrorRetryFailed),pe))}finally{Te||(V(fe),re(fe),G(Fe()))}},[Z,Ke,V,re,he,ne,G,W,n,t,pe]);return{onComposerKeyDown:Yt,onCancelPendingSend:Oe,onSendMessage:Ot,onStopMessage:tt,onRetryMessage:_t,submitComposerMessage:Ne}}function jv(e){return function(n){return Tv({...n,chatPrefix:e})}}function Lv(e){const{state:t,setState:n,operatorState:a,setOperatorState:s,setBusy:o,setFeedback:i,sendChatMessage:d=ic}=e,{t:c}=Q(),u=p.useCallback(async(m,v)=>{if(a.snapshot){o(sh(m,v));try{const C=await af({taskId:m,status:v==="approve"?"approved":"rejected",action:v,decidedByActorId:a.snapshot.core.ownerProfile.actorId});p.startTransition(()=>{s({status:"ready",snapshot:C,message:""}),i("")})}catch(C){i(Gt(C,c(l.chatGovernanceErrorUpdateApproval),c))}finally{o(Fe())}}},[a.snapshot,o,i,s,c]),h=p.useCallback(async m=>{if(t.status!=="ready")return;const v=m.channelId;if(v){o(oh(m.choiceResponse.sourceMessageId,m.choiceResponse.status));try{const C=await d(v,{body:m.body,senderName:t.payload.ownerDisplayName,choiceResponse:m.choiceResponse});p.startTransition(()=>{n({status:"ready",payload:C.appShell}),i("")})}catch(C){i(Gt(C,c(l.chatGovernanceErrorSubmitChoiceResponse),c))}finally{o(Fe())}}},[o,i,n,t,c]),f=p.useCallback(async m=>{if(!a.snapshot)return;const v=m.runId??m.taskId??m.checkpointId??m.outcomeId??"global";o(ih(m.action,v));try{const C=await rf({...m,actorId:a.snapshot.core.ownerProfile.actorId});p.startTransition(()=>{s({status:"ready",snapshot:C,message:""}),i("")})}catch(C){i(Gt(C,c(l.chatGovernanceErrorRecordOperatorAction),c))}finally{o(Fe())}},[a.snapshot,o,i,s,c]);return{onApprovalDecision:u,onChoiceSubmit:h,onOperatorAction:f}}function Mv(e,t){const n=e.memberChannelIds.filter(a=>a!==t);return{...e,memberChannelIds:n,members:e.members.filter(a=>a.channelId!==t),memberCount:n.length}}function Ev(e,t){const n=t.selectedChannel.id,a=new Map(t.parallelChatGroups.map(i=>[i.id,i])),s=new Set,o=e.flatMap(i=>{const d=a.get(i.id);return d?(s.add(i.id),[d]):i.memberChannelIds.includes(n)?[Mv(i,n)]:[]});for(const i of t.parallelChatGroups)s.has(i.id)||o.push(i);return pd(o,e,[n])}function Dv(e,t){return e&&UC(e,t.selectedChannel)}function Bv(e,t){return e.chat.selectedChannelId===t.selectedChannelId&&t.selectedChannel.id===t.selectedChannelId}function ei(e,t){if(!Bv(e,t))return e;const n=Dv(e.chat.channels,t);return{...e,chat:{...e.chat,selectedChannelId:t.selectedChannelId,selectedChannel:t.selectedChannel,...n?{channels:n}:{},parallelChatGroups:Ev(e.chat.parallelChatGroups,t)}}}function Ov(e,t){return t.state?ei(e,t.state):e}function _v(e,t){return e.status!=="ready"?e:{status:"ready",payload:ei(e.payload,t)}}function Fv(e,t){return _v(e,t.state)}function Wv(e,t){return e.status!=="ready"?e:{status:"ready",payload:Ov(e.payload,t.patch)}}const Zs={text:"",files:[]},Ln=new Map,ea=new Map,vo=new Set;let ta=0;const ks=(e,t)=>JSON.stringify([e,t]),ss=()=>{for(const e of vo)e()},hl=e=>(vo.add(e),()=>{vo.delete(e)});function xd(){ta+=1,Ln.clear(),ea.clear(),ss()}Lo(xd);function Kv(e,t){for(const n of[Ln,ea])for(const a of n.keys()){const[s,o]=JSON.parse(a);s===e&&o.startsWith("channel:")&&!t.has(o.slice(8))&&n.delete(a)}}function fl(e,t,n,a=ta){a===ta&&(Ln.set(ks(e,t),n),ss())}function Uv(e,t){return ea.get(ks(e,`channel:${t}`))}function $v(e,t,n){ea.set(ks(e,`channel:${t}`),n),ea.size>100&&ea.delete(ea.keys().next().value)}function Hv(e,t){const n=p.useSyncExternalStore(hl,()=>ta,()=>ta),a=ks(e,t),s=p.useCallback(()=>Ln.get(a)??Zs,[a]),o=p.useSyncExternalStore(hl,s,s),i=p.useCallback(c=>{if(n!==ta)return;const u=Ln.get(a)??Zs,h=typeof c=="function"?c(u.text):c;Ln.set(a,{...u,text:h}),ss()},[n,a]),d=p.useCallback(c=>{if(n!==ta)return;const u=Ln.get(a)??Zs,h=typeof c=="function"?c(u.files):c;Ln.set(a,{...u,files:h}),ss()},[n,a]);return{composerDraft:o.text,channelFiles:o.files,setComposerDraft:i,setChannelFiles:d,generation:n}}const cr=["conversation-navigation"],qv=1800*1e3,Gv=24;function En(e){return e.scopeId||`${e.metadata.host}:${e.metadata.port}/${e.chat.id}`}class Vv{constructor(t,n=Gv){this.client=t,this.capacity=n,t.setQueryDefaults(cr,{gcTime:qv})}recent=new Map;listeners=new Set;generation=0;subscribe=t=>(this.listeners.add(t),()=>{this.listeners.delete(t)});read(t,n){const a=this.client.getQueryData([...cr,t,n]);return a&&this.touch(t,n),a}remember(t,n){if(n.selectedChannelId!==n.selectedChannel.id||n.selectedChannel.messages.some(o=>o.metadata?.optimistic===!0))return;const a=[...cr,t,n.selectedChannelId],s=this.client.getQueryData(a);s&&s.selectedChannel.updatedAt>n.selectedChannel.updatedAt||(this.client.setQueryData(a,n),this.touch(t,n.selectedChannelId))}rememberPayload(t){const n=t.chat.selectedChannel;!n||n.id!==t.chat.selectedChannelId||this.remember(En(t),{selectedChannelId:n.id,selectedChannel:n,parallelChatGroups:t.chat.parallelChatGroups.filter(a=>a.memberChannelIds.includes(n.id))})}prune(t,n){Kv(t,n);for(const a of this.recent.values())a.scope===t&&!n.has(a.id)&&this.remove(t,a.id)}remove(t,n){this.recent.delete(JSON.stringify([t,n])),this.client.removeQueries({queryKey:[...cr,t,n],exact:!0})}clear(){this.generation+=1,this.recent.clear(),this.client.removeQueries({queryKey:cr}),xd();for(const t of this.listeners)t()}touch(t,n){const a=JSON.stringify([t,n]);for(this.recent.delete(a),this.recent.set(a,{scope:t,id:n});this.recent.size>this.capacity;){const s=this.recent.values().next().value;s&&this.remove(s.scope,s.id)}}}const wd=new Vv(lh);Lo(()=>wd.clear());function ml(e,t,n){if(!t||!e.chat.channels.some(o=>o.id===t))return e;const a=n.read(En(e),t);if(e.chat.selectedChannel?.id===t&&e.chat.selectedChannelId===t&&(e.chat.selectedChannel.messages.some(o=>o.metadata?.optimistic===!0)||!a||a.selectedChannel.updatedAt<=e.chat.selectedChannel.updatedAt))return e;const s={...e,chat:{...e.chat,selectedChannelId:t,selectedChannel:null}};return a?ei(s,a):s}function zv(e){const t=e.cache??wd,n=p.useSyncExternalStore(t.subscribe,()=>t.generation,()=>t.generation),a=p.useRef(n),s=e.state.status==="ready"?En(e.state.payload):null,o=p.useRef(s),i=e.routeChannelId??(e.directRecipientId&&e.state.status==="ready"?Ql(e.state.payload.chat.channels,e.directRecipientId)?.id??null:null),d=p.useMemo(()=>a.current!==n?{status:"loading"}:e.state.status==="ready"?{status:"ready",payload:ml(e.state.payload,i,t)}:e.state,[t,i,n,e.state]),c=p.useRef({state:d,channelId:i,setter:e.setState});c.current={state:d,channelId:i,setter:e.setState},p.useLayoutEffect(()=>{if(a.current!==n||e.state.status!=="ready")return;o.current&&s!==o.current&&(t.clear(),a.current=t.generation),o.current=s;const h=e.state.payload;t.prune(En(h),new Set(h.chat.channels.map(f=>f.id))),t.rememberPayload(h)},[t,n,e.state,s]);const u=p.useCallback(h=>{const f=c.current;if(n!==t.generation||s&&f.state.status==="ready"&&En(f.state.payload)!==s)return;a.current=n;let m=typeof h=="function"?h(f.state):h;m.status==="ready"&&(t.rememberPayload(m.payload),m={status:"ready",payload:ml(m.payload,f.channelId,t)}),c.current.state=m,f.setter(m)},[t,n,s]);return{state:d,setState:u,channelId:i,subscriptionScope:`${s??""}:${n}`}}function Yv(e,t){return e?.id??t?.id??null}function Jv(e,t){return e??t}function Qv({folderBrowsePath:e,folderBrowseCurrentPath:t,folderBrowseParentPath:n,folderBrowseEntries:a,folderBrowseLoading:s,folderBrowseError:o,onPathChange:i,browseFolder:d,selectCurrentFolder:c}){return{folderBrowsePath:e,folderBrowseCurrentPath:t??"",folderBrowseParentPath:n??"",folderBrowseEntries:[...a],folderBrowseLoading:s,folderBrowseError:o,onPathChange:i,onBrowse:u=>{d(u)},onSelect:c}}const Xv="screenshot_permission_denied",Zv="Screen Recording permission is required to capture a screenshot. Grant Cats screen access in macOS System Settings, then restart Cats.",eI={[Zv]:l.sharedScreenshotCapturePermissionRequired,"Native wlroots screenshot capture requires grim and slurp.":l.sharedScreenshotCaptureWlrootsToolsRequired,"Native wlroots screenshot capture is not available in this session.":l.sharedScreenshotCaptureWlrootsSessionUnsupported,"No displays are available for screenshot capture.":l.sharedScreenshotCaptureNoDisplays,"Could not parse wlroots screenshot selection geometry.":l.sharedScreenshotCaptureWlrootsSelectionParseFailed},la=ia("en"),tI=8e3,nI=8e3,aI=10*1024*1024;let gl="",eo=0;function kd(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getDisplayMedia=="function"&&typeof document<"u"}function rI(){const e=Eo();return e?.screenshotRegionCaptureAvailable===!0&&typeof e.captureScreenshotRegion=="function"}function Pd(){return rI()?"desktop_region":kd()?"web_picker":"unavailable"}function ti(e,t=la){return t(e==="desktop_region"?l.sharedScreenshotCaptureTooltipDesktopRegion:e==="web_picker"?l.sharedScreenshotCaptureTooltipWebPicker:l.sharedScreenshotCaptureTooltipUnavailable)}function sI(e){return e!=="unavailable"}function oI(e,t=la){return e instanceof Error?e.message:t(l.sharedScreenshotCaptureFailed)}class iI extends Error{code=Xv;constructor(t=la(l.sharedScreenshotCapturePermissionRequired)){super(t),this.name="ScreenshotPermissionDeniedError"}}function lI(e,t=la){return{surface:"toast",message:oI(e,t)}}function Sa(e,t){return String(e).padStart(t,"0")}function Cl(e,t){const n=e.trim(),a=eI[n];if(a)return t(a);const s=n.match(/^Screen Recording permission status is unknown: (.+)$/u);return s?t(l.sharedScreenshotCapturePermissionStatusUnknown,{status:s[1]}):e}function Ad(e=new Date){const t=[e.getFullYear(),Sa(e.getMonth()+1,2),Sa(e.getDate(),2),"-",Sa(e.getHours(),2),Sa(e.getMinutes(),2),Sa(e.getSeconds(),2)].join("");return eo=t===gl?eo+1:1,gl=t,`cats-screenshot-${t}-${Sa(eo,3)}.png`}async function cI(e,t){e.readyState>=HTMLMediaElement.HAVE_METADATA&&e.videoWidth>0||await new Promise((n,a)=>{e.onloadedmetadata=()=>n(),e.onerror=()=>a(new Error(t(l.sharedScreenshotCaptureFrameLoadFailed)))})}function dI(e,t){const n=e.videoWidth,a=e.videoHeight;if(n<=0||a<=0)throw new Error(t(l.sharedScreenshotCaptureFrameEmpty));const s=Math.min(1,tI/n,nI/a),o=document.createElement("canvas");o.width=Math.max(1,Math.floor(n*s)),o.height=Math.max(1,Math.floor(a*s));const i=o.getContext("2d");if(!i)throw new Error(t(l.sharedScreenshotCaptureCanvasPrepareFailed));return i.drawImage(e,0,0,o.width,o.height),o}async function vl(e,t){return await new Promise((n,a)=>{e.toBlob(s=>{if(!s){a(new Error(t(l.sharedScreenshotCaptureEncodeFailed)));return}n(s)},"image/png")})}async function uI(e,t){let n=e,a=await vl(n,t);for(;a.size>aI&&n.width>1&&n.height>1;){const s=document.createElement("canvas");s.width=Math.max(1,Math.floor(n.width*.85)),s.height=Math.max(1,Math.floor(n.height*.85));const o=s.getContext("2d");if(!o)throw new Error(t(l.sharedScreenshotCaptureDownscaleFailed));o.drawImage(n,0,0,s.width,s.height),n=s,a=await vl(n,t)}return a}function Il(e){if(e)for(const t of e.getTracks())t.stop()}async function pI(e=la){if(!kd())throw new Error(ti("unavailable",e));const t=navigator.mediaDevices.getDisplayMedia({audio:!1,video:!0});let n=null;try{n=await t;const a=document.createElement("video");a.muted=!0,a.playsInline=!0,a.srcObject=n,await cI(a,e),await a.play();const s=dI(a,e);Il(n),n=null;const o=await uI(s,e);return new File([o],Ad(),{type:"image/png"})}catch(a){if(a instanceof DOMException&&a.name==="NotAllowedError")return null;throw a}finally{Il(n)}}function hI(e,t){if(e.outcome==="cancelled")switch(e.reason){case"unknown_display":return new Error(t(l.sharedScreenshotCaptureDisplayUnavailable));case"too_small":case"user_cancel":return null;default:{const n=e.reason;return new Error(`Unhandled screenshot cancellation reason: ${n}`)}}return e.outcome==="permission_denied"?new iI(e.message?Cl(e.message,t):t(l.sharedScreenshotCapturePermissionRequired)):e.message?new Error(Cl(e.message,t)):e.outcome==="platform_unsupported"?new Error(t(l.sharedScreenshotCaptureRegionUnsupported)):new Error(t(l.sharedScreenshotCaptureFailed))}function fI(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}async function mI(e=la){const t=Eo()?.captureScreenshotRegion;if(!t)throw new Error(ti("unavailable",e));const n=await t();if(n.outcome!=="ok"){const a=hI(n,e);if(!a)return null;throw a}return new File([fI(n.png)],n.filename||Ad(),{type:n.mime})}async function Sl(e=Pd(),t=la){if(e==="desktop_region")return await mI(t);if(e==="web_picker")return await pI(t);throw new Error(ti(e,t))}function gI(e){return{showParallelAddButton:e.showStructuredDraftControls&&(e.advancedDraftControlsEnabled||e.hasVisibleParallelDraftTargets),showGroupAddButton:e.advancedDraftControlsEnabled&&e.showStructuredDraftControls&&e.entryPreset!=="group",hideGroupHint:e.advancedDraftControlsEnabled&&e.showStructuredDraftControls&&e.entryPreset!=="group",hideParallelHint:e.advancedDraftControlsEnabled&&e.showStructuredDraftControls&&e.entryPreset!=="parallel"}}function Mw({productName:e,shellSurface:t,supportsStructuredDraftModes:n=!1,BootShell:a,AppRoutesComponent:s,renderSidebar:o}){const i=bi(t),d=jv(i);return function(){const u=Ta(),{t:h}=Q(),{location:f,settingsMode:m,routeChannelId:v,routeMyCatId:C,showingNewChatDraft:S,newChatPreset:y,draftDefaultRecipientCatId:g,showingMyCatDirectLane:x}=Pg(i),I=n?y:"default",k=I==="parallel",P=S&&!x&&!!g,A=!g,[M,D]=p.useState(t),N=p.useMemo(()=>[I,x?"direct":"public",g??"none"].join(":"),[g,I,x]),R=p.useMemo(()=>hC(f.pathname,f.search),[f.pathname,f.search]),w=p.useMemo(()=>gC({surface:t,path:R}),[R,t]),b=p.useMemo(()=>{if(!w)return null;const j=ld({surface:t,path:R});if(!j?.optimisticState?.pendingExecution)return null;const{entityKind:q,entityId:ee}=j.destination;if(q==="channel"){const de=j.optimisticState.selectedChannelId??w.chat.selectedChannelId??ee??null;return de?{kind:"channel",channelId:de}:null}if(q==="parallel-group"){const de=ee,ve=w.chat.parallelChatGroups.find(je=>je.id===de);if(!ve||ve.memberChannelIds.length===0)return null;const Ie=j.optimisticState.selectedChannelId??w.chat.selectedChannelId??ve.memberChannelIds[0];return{kind:"parallel",groupId:de,activeChannelId:Ie,channelIds:ve.memberChannelIds}}return null},[R,w,t]),{state:T,setState:E,catForm:O,setCatForm:H,busy:U,setBusy:L,feedback:$,setFeedback:X,addCatTab:ke,setAddCatTab:z,greeting:B,draftCwd:ae,setDraftCwd:he,draftFiles:Y,setDraftFiles:G}=kg({initialState:w?{status:"ready",payload:w}:{status:"loading"},createEmptyCatForm:Bs,pickGreeting:()=>ph(h)}),{state:W,setState:ue,channelId:pe,subscriptionScope:We}=zv({state:T,setState:E,routeChannelId:v,directRecipientId:x?g:null}),{composerDraft:Z,setComposerDraft:Ke,channelFiles:et,setChannelFiles:V,generation:re}=Hv(W.status==="ready"?En(W.payload):"",pe?`channel:${pe}`:`draft:${R}`),ne=p.useRef({kind:"lead"}),Oe=p.useRef(null),tt=p.useCallback(j=>{const q=ne.current;if(q.kind==="parallel-branch"){Oe.current?.(q.index,j);return}he(j)},[he]),{draftCatIds:Ne,setDraftCatIds:Ot,draftHighlightedCatId:Yt,setDraftHighlightedCatId:_t,draftCatExecutionTargetOverrides:nt,setDraftCatExecutionTargetOverrides:Ue,onToggleDraftCat:fe,onDraftCatExecutionTargetOverride:Le,resetDraftCats:Te}=xg(),ye=W.status==="ready"?W.payload.chat.capabilities.maxChatParticipants??Number.POSITIVE_INFINITY:Number.POSITIVE_INFINITY,Ce=W.status==="ready"?W.payload.chat.capabilities.maxAudienceParticipants??Number.POSITIVE_INFINITY:Number.POSITIVE_INFINITY,Ft=W.status==="ready"?W.payload.chat.capabilities.maxParallelChats??3:3,[Me,lt]=p.useState("sequential"),[Pe,ht]=p.useState(()=>jo()),[ft,Ee]=p.useState(null),[Wt,Lt]=p.useState("sequential"),[Mt,ct]=p.useState(null),[Et,st]=p.useState("all_members"),{draftTemporaryParticipants:F,setDraftTemporaryParticipants:le,draftParticipants:xe,onAddDraftTemporaryParticipant:mt,onRemoveDraftTemporaryParticipant:at,onUpdateDraftTemporaryParticipant:sn}=wg({state:W,draftDefaultRecipientCatId:g,draftCatIds:Ne,maxDraftGroupParticipants:ye}),{dialog:Jt,confirm:rt,handleClose:Dt}=ch(),{toasts:gt,showToast:we}=lc(),{notifications:bn,dismiss:_n}=_f(),on=Pd(),ca=!sI(on),Re=p.useCallback(j=>{const q=lI(j,h);we(q.message)},[we,h]),$e=p.useCallback(()=>{Sl(on,h).then(q=>{q&&G(ee=>[...ee,q])}).catch(Re)},[on,G,Re,h]),xt=p.useCallback(()=>{Sl(on,h).then(q=>{q&&V(ee=>[...ee,q])}).catch(Re)},[on,V,Re,h]),Ct=eC(ue),{refreshAppShell:ln}=zC({state:W,setState:ue,enabled:W.status==="ready"}),[Fn,xn]=p.useState(!1),Qt=p.useRef(C);p.useEffect(()=>{Qt.current!==C&&(Qt.current=C,xn(!1))},[C]);const wn=t==="chat"&&Fn&&C&&W.status==="ready"?W.payload.chat.cats.find(j=>j.id===C)??null:null,cn=p.useCallback(()=>{xn(j=>!j)},[]),Ea=p.useCallback(j=>{const q=W.status==="ready"?W.payload.chat.channels.find(ee=>ee.channelKind==="direct_message"&&ee.defaultRecipientCatId===j):null;q&&dh(q.id).then(ln)},[ln,W]),Rt=p.useCallback(j=>{const q=W.status==="ready"?W.payload.chat.channels.find(ee=>ee.channelKind==="direct_message"&&ee.defaultRecipientCatId===j):null;q&&fetch(`/api/channels/${encodeURIComponent(q.id)}/deactivate`,{method:"POST",headers:{"content-type":"application/json"}}).catch(()=>{}).then(ln)},[ln,W]),wt=p.useCallback(async(j,q)=>{try{const ee=await Ds(j,{avatarUrl:q});Ct(ee)}catch{}},[Ct]),kn=p.useCallback(j=>{X(Gt(j,h(l.sharedExecutionTargetSaveDirectLaneError),h))},[X,h]),Pn=Yg({updateCatProfile:Ds,publishReadyPayload:Ct,onError:kn}),Wn=p.useCallback((j,q)=>{Le(j,q),Pn(j,q).then(ee=>{Ue(de=>{if(!de.has(j)||ee&&de.get(j)!==q)return de;const ve=new Map(de);return ve.delete(j),ve})})},[Pn,Le,Ue]),{accountMenuOpen:da,setAccountMenuOpen:dn,sidebarOpen:un,overflowMenuOpenId:Da,setOverflowMenuOpenId:Kn,plusMenuOpen:dt,setPlusMenuOpen:An,addCatOpen:se,setAddCatOpen:Qe,channelPlusMenuOpen:kt,setChannelPlusMenuOpen:Kt,accountMenuRef:ua,plusMenuRef:Rn,addCatPanelRef:Ba,fileInputRef:Nn,channelPlusMenuRef:Oa,channelFileInputRef:Ut,autoResize:Xt,onToggleSidebar:_a,onCollapsedSidebarClick:Un}=zf(),{browseFolder:Tn,folderBrowseCurrentPath:$n,folderBrowseEntries:pn,folderBrowseError:Hn,folderBrowseLoading:hn,folderBrowseParentPath:pa,folderBrowsePath:ha,openFolderBrowser:Bt,selectCurrentFolder:fa,setFolderBrowsePath:Fa}=Qf({onSelectPath:tt,surface:t,directLaneCatId:C,initialPreferences:W.status==="ready"?W.payload.chat.folderBrowsePreferences:void 0}),Wa=p.useCallback(async j=>{ne.current={kind:"lead"},await Bt(j)},[Bt]),{toggleAddCatPanel:Ka,toggleChannelPlusMenu:fn,openChannelFilePicker:qn,captureAndAttachChannelScreenshot:Ua,toggleDraftPlusMenu:ot,openDraftFilePicker:$a,captureAndAttachDraftScreenshot:Zt,openDraftFolderPicker:Ha,openDraftAddCatPanel:qa,changeDraftDefaultRecipient:Ga}=tC({addCatOpen:se,channelPlusMenuOpen:kt,plusMenuOpen:dt,draftCwd:ae,draftDefaultRecipientCatId:g,navigate:u,chatPrefix:i,emptyCatForm:Bs,setAddCatOpen:Qe,setAddCatTab:z,setFeedback:X,setCatForm:H,setPlusMenuOpen:An,setChannelPlusMenuOpen:Kt,channelFileInputRef:Ut,fileInputRef:Nn,openFolderBrowser:Wa,onDraftScreenshotCapture:$e,onChannelScreenshotCapture:xt}),Va=p.useCallback(async j=>{const q=W.status==="ready"?W.payload.chat.cats.find(de=>de.id===j)?.name??h(l.sharedSettingsCatsFallbackCatName):h(l.sharedSettingsCatsFallbackCatName);if(await rt({title:h(l.sharedSettingsCatsArchiveConfirmTitle),message:h(l.sharedSettingsCatsArchiveWithTelegramConfirmMessage,{catName:q}),confirmLabel:h(l.sharedSettingsCatsArchiveLabel)})){L(ya("archive",j));try{const de=await Ds(j,{archive:!0});ue({status:"ready",payload:de})}catch(de){X(ac(de,h(l.sharedSettingsCatsArchiveError),h))}finally{L(Fe())}}},[rt,W,h]),{readyPayload:Pt,readyChat:za,readySelectedChannel:Ya,selectedChannelId:Ja,routeChannelExists:Qa,routeChannelTitle:ma,routeDirectLaneSummary:K,selectedChannel:J,selectedDirectLane:Nt,operatorRefreshKey:Ae}=$f({state:W,routeChannelId:v,draftDefaultRecipientCatId:g,showingMyCatDirectLane:x}),{operatorState:De,setOperatorState:it}=zg(Pt,Ae),_e=Pt?uh(Pt.chat.advancedDraftControls,t):!1,{draftExecutionTarget:oe,setDraftExecutionTarget:$t,defaultChannelExecutionTarget:mn,setDefaultChannelExecutionTarget:Xa}=_g({state:W,readyChat:za,readySelectedChannel:Ya,setState:ue,setFeedback:X,updateNewChatDefaultsPreference:hh,updateChannelPendingExecutionTarget:fh}),Za=x?"direct":n&&(I==="group"||P||xe.participantCatIds.length>0||F.length>0)?"group":"default",{draftParallelChatTargets:ze,resetDraftParallelChatTargets:gn,onDraftParallelChatTargetChange:jn,onAddDraftParallelChatTarget:Gn,onRemoveDraftParallelChatTarget:Vn,onSetDraftParallelBranchAudienceKeys:Xe,onSetDraftParallelBranchCwd:ce,onSetDraftParallelBranchRuntimeSessionPolicy:Ht,onToggleDraftParallelBranchWorkflowShape:zn}=$g({draftExecutionTarget:oe,maxParallelChats:Ft,seedCompareTarget:k});p.useEffect(()=>{Oe.current=ce},[ce]);const ga=p.useCallback(j=>{ne.current={kind:"parallel-branch",index:j};const q=ze[j]?.cwd??ae;Bt(q),An(!1)},[ae,ze,Bt,An]),Ye=ze.length>1,Tt=p.useMemo(()=>ze.map(j=>j.audienceKeys??[]),[ze]),Ca=p.useMemo(()=>ze.map(j=>j.workflowShape??"sequential"),[ze]),qt=p.useCallback(()=>mf(oe,ye),[oe.instance,oe.model,oe.modelSelection,oe.provider,ye]),vt=p.useMemo(()=>[...xe.participantCatIds.map(j=>`cat:${j}`),...F.map(j=>`temp:${j.participantId}`)],[xe.participantCatIds,F]),er=p.useCallback((j,q)=>{const ee=j.filter((de,ve,Ie)=>Ie.indexOf(de)===ve);return ee.includes(q)||Number.isFinite(Ce)&&ee.length>=Ce?ee:[...ee,q]},[Ce]),Ar=p.useCallback(()=>{const j=Tt[0];return j&&j.length>0?[...j]:ft&&ft.length>0?[...ft]:Number.isFinite(Ce)?vt.slice(0,Ce):[...vt]},[ft,Tt,vt,Ce]),_=p.useCallback(()=>{if(!n||W.status!=="ready")return;const j=xe.participantCatIds;if(j.length+F.length>=ye)return;const q=j.map(Ie=>W.payload.chat.cats.find(je=>je.id===Ie)?.name??"").filter(Ie=>Ie.trim().length>0),ee=()=>globalThis.crypto?.randomUUID?.()??`participant-${Date.now()}`,de=F.length===0&&j.length===0?Mn({provider:oe.provider,instance:oe.instance,model:oe.model,modelSelection:oe.modelSelection,takenNames:[...q,...F.map(Ie=>Ie.name)],randomUUID:ee}):Ws({baseProvider:oe.provider,existingParticipants:F,takenNames:[...q,...F.map(Ie=>Ie.name)],randomUUID:ee}),ve=de.participantId;le(Ie=>j.length+Ie.length>=ye||Ie.some(je=>je.participantId===ve)?Ie:[...Ie,de]),Ee(Ie=>{const Je=[...j.map(pt=>`cat:${pt}`),...F.map(pt=>`temp:${pt.participantId}`),`temp:${ve}`],He=`temp:${ve}`,bt=(Ie??Je).filter((pt,sr,or)=>or.indexOf(pt)===sr&&Je.includes(pt));return bt.includes(He)||Number.isFinite(Ce)&&bt.length>=Ce?bt:[...bt,He]})},[oe.instance,oe.model,oe.modelSelection,oe.provider,xe.participantCatIds,F,Ce,ye,le,W,n]),ie=p.useCallback(j=>{if(!n){fe(j);return}const q=xe.participantCatIds.includes(j);if(!q&&xe.participantCatIds.length+F.length>=ye)return;if(fe(j),!q){const ve=`cat:${j}`;Ee(Ie=>{const Je=(Ie??vt).filter((He,vn,bt)=>bt.indexOf(He)===vn);return Number.isFinite(Ce)&&Je.length>=Ce?Je:[...Je,ve]});return}const ee=`cat:${j}`,de=vt.filter(ve=>ve!==ee);Ee(ve=>Mr({draftAudienceKeys:ve,previousParticipantKeys:vt,nextParticipantKeys:de,removedParticipantKey:ee,maxAudienceParticipants:Ce})),ze.length>=2&&Tt.forEach((ve,Ie)=>{ve.includes(ee)&&Xe(Ie,Mr({draftAudienceKeys:ve,previousParticipantKeys:vt,nextParticipantKeys:de,removedParticipantKey:ee,maxAudienceParticipants:Ce})??[])})},[vt,xe.participantCatIds,Tt,ze.length,F.length,Ce,ye,fe,Xe,n]),be=p.useCallback(j=>{if(!n){at(j);return}const q=`temp:${j}`,ee=vt.filter(de=>de!==q);at(j),Ee(de=>Mr({draftAudienceKeys:de,previousParticipantKeys:vt,nextParticipantKeys:ee,removedParticipantKey:q,maxAudienceParticipants:Ce})),ze.length>=2&&Tt.forEach((de,ve)=>{de.includes(q)&&Xe(ve,Mr({draftAudienceKeys:de,previousParticipantKeys:vt,nextParticipantKeys:ee,removedParticipantKey:q,maxAudienceParticipants:Ce})??[])})},[vt,Tt,ze.length,Ce,at,Xe,n]),ut=p.useCallback(j=>{if(mt(j),!n)return;S&&I==="group"&&xe.participantCatIds.length===0&&F.length===0&&j.provider.trim()&&$t({provider:j.provider.trim(),model:j.model?.trim()||null,instance:j.instance?.trim()||null,modelSelection:j.modelSelection??null});const ee=`temp:${j.participantId??""}`;!ee||ee==="temp:"||Ee(de=>{const Ie=(de??vt).filter((je,Je,He)=>He.indexOf(je)===Je);return Number.isFinite(Ce)&&Ie.length>=Ce?Ie:[...Ie,ee]})},[vt,xe.participantCatIds.length,F.length,I,Ce,mt,$t,S,n]),yt=p.useCallback((j=null)=>{if(!n||W.status!=="ready")return;const q=j!==null&&ze.length>=2;if(q){const je=Tt[j]??[];if(Number.isFinite(ye)&&je.length>=ye)return}else if(xe.participantCatIds.length+F.length>=ye)return;const de=[...xe.participantCatIds.map(je=>W.payload.chat.cats.find(Je=>Je.id===je)?.name??"").filter(je=>je.trim().length>0),...F.map(je=>je.name)],ve=F.length===0&&xe.participantCatIds.length===0?Mn({provider:oe.provider,instance:oe.instance,model:oe.model,modelSelection:oe.modelSelection,takenNames:de,randomUUID:()=>globalThis.crypto?.randomUUID?.()??`participant-${Date.now()}`}):Ws({baseProvider:oe.provider,existingParticipants:F,takenNames:de,randomUUID:()=>globalThis.crypto?.randomUUID?.()??`participant-${Date.now()}`}),Ie=`temp:${ve.participantId}`;if(le(je=>[...je,ve]),q){const Je=(Tt[j]??[]).filter((vn,bt,pt)=>pt.indexOf(vn)===bt),He=Je.includes(Ie)?Je:[...Je,Ie];Xe(j,He);return}Ee(je=>{const He=[...xe.participantCatIds.map(pt=>`cat:${pt}`),...F.map(pt=>`temp:${pt.participantId}`)],bt=(je??He).filter((pt,sr,or)=>or.indexOf(pt)===sr&&He.includes(pt));return Number.isFinite(Ce)&&bt.length>=Ce?bt:[...bt,Ie]})},[er,oe.instance,oe.model,oe.modelSelection,oe.provider,Tt,ze.length,xe.participantCatIds,F,Ce,ye,Xe,Ee,le,W,n]),va=p.useCallback(j=>{if(!n||W.status!=="ready")return;if(xe.participantCatIds.length===0&&F.length===0){const ee=qt(),de=ee.map(ve=>`temp:${ve.participantId}`);le(ve=>ve.length===0?ee:ve),Xe(j,de);return}if((Tt[j]??[]).length===0){const ee=ze[j]??oe,de=xe.participantCatIds.map(He=>W.payload.chat.cats.find(vn=>vn.id===He)?.name??"").filter(He=>He.trim().length>0),ve=()=>globalThis.crypto?.randomUUID?.()??`participant-${Date.now()}`,Ie=Mn({provider:ee.provider,instance:ee.instance,model:ee.model,modelSelection:ee.modelSelection,takenNames:[...de,...F.map(He=>He.name)],randomUUID:ve}),je=[...F,Ie],Je=Ws({baseProvider:ee.provider,existingParticipants:je,takenNames:[...de,...je.map(He=>He.name)],randomUUID:ve});le(He=>[...He,Ie,Je]),Xe(j,[`temp:${Ie.participantId}`,`temp:${Je.participantId}`]);return}yt(j)},[oe,Tt,ze,xe.participantCatIds,F,yt,Xe,qt,le,W,n]),{onOpenChatsOverview:Rr,onSelect:tr,onRenameChannel:Ts,onDeleteChannel:js,onClearDirectLane:nr,onRenameParallelChatGroup:Cn,onUngroupParallelChatGroup:Ls,onDeleteParallelChatGroup:ar,onNavigateSettings:Iu,onNavigateRuntime:Su,onCreateNewCat:yu,onDirectChatCat:bu,onResetSetup:xu,onStartNewChat:wu,onStartNewGroupChat:ku,onStartNewParallelChat:Pu}=xC({state:W,setState:ue,navigate:u,platformShellSurface:t,navigationSnapshot:W.status==="ready"?W.payload:void 0,setBusy:L,setFeedback:X,setComposerDraft:Ke,setAccountMenuOpen:dn,resetDraftComposer:j=>{W.status==="ready"&&fl(En(W.payload),`draft:${j}`,{text:"",files:[]},re)},setAddCatOpen:Qe,setPlusMenuOpen:An,setChannelPlusMenuOpen:Kt,setDraftCwd:he,setDraftCatIds:Ot,setDraftTemporaryParticipants:le,setDraftHighlightedCatId:_t,setDraftCatExecutionTargetOverrides:Ue,setDraftSurface:D,setDraftWorkflowShape:lt,setDraftRuntimeSessionPolicy:ht,setDraftAudienceKeys:Ee,resetDraftParallelChatTargets:gn,createInitialGroupParticipants:n?qt:void 0,setDraftFiles:G,setChannelFiles:V,confirm:rt}),di=J??Nt??null,Au=bg({channelId:di?.id??null,busy:U,selectedChannel:di,debugTraceEnabled:Pt?.chat.capabilities.debugLiveTrace===!0}),Nr=pe&&Pt?.chat.channels.some(j=>j.id===pe)?pe:null;dd({kind:"channel",id:Nr,scopeKey:We,enabled:W.status==="ready"&&!!Nr,onSnapshot:j=>{j.id===Nr&&p.startTransition(()=>{ue(q=>Fv(q,j))})},onPatch:j=>{j.id===Nr&&p.startTransition(()=>{ue(q=>Wv(q,j))})}}),p.useEffect(()=>{D(t)},[N,t]);const rr=J?.messages?[...J.messages].reverse().find(j=>j.senderKind==="user")??null:null,Ru=Array.isArray(rr?.metadata?.recipientParticipantIds)?rr.metadata.recipientParticipantIds.filter(j=>typeof j=="string").join("|"):"",Nu=typeof rr?.metadata?.workflowShape=="string"?rr.metadata.workflowShape:"",Tu=(J?.assignedParticipants?.length?J.assignedParticipants:J?.assignedCats??[]).filter(j=>j.status==="active").map(j=>j.participantId).join("|"),Tr=p.useMemo(()=>Pt&&J?Pt.chat.parallelChatGroups.find(j=>j.memberChannelIds.includes(J.id))??null:null,[Pt,J]);p.useEffect(()=>{const j=Pv({selectedChannel:J,maxAudienceParticipants:Ce});Lt(j?.workflowShape??"sequential"),ct(j?.audienceKeys??null)},[Tu,rr?.id,Ru,Nu,Ce,J?.id]),p.useEffect(()=>{st("all_members")},[Tr?.id]);const{onComposerKeyDown:ui,onCancelPendingSend:pi,onSendMessage:hi,onStopMessage:ju,onRetryMessage:Lu}=d({state:W,setState:ue,navigate:u,originSurface:M,currentPath:`${f.pathname}${f.search}`,composerDraft:Z,setComposerDraft:Ke,showingNewChatDraft:S,restoreConversationComposer:(j,q,ee)=>{W.status==="ready"&&fl(En(W.payload),`channel:${j}`,{text:q,files:ee},re)},showingMyCatDirectLane:x,draftEntryKind:Za,draftDefaultRecipientCatId:g,draftCatIds:Ne,draftTemporaryParticipants:F,draftCwd:ae,draftSessionPolicy:Pe,draftFiles:Y,channelFiles:et,setDraftCwd:he,setDraftCatIds:Ot,setDraftTemporaryParticipants:le,setDraftHighlightedCatId:_t,setDraftCatExecutionTargetOverrides:Ue,setDraftRuntimeSessionPolicy:ht,setDraftFiles:G,setChannelFiles:V,setDraftWorkflowShape:lt,setDraftAudienceKeys:Ee,draftExecutionTarget:oe,defaultChannelExecutionTarget:mn,showingParallelChatDraft:n&&k,draftParallelChatTargets:ze,draftWorkflowShape:Me,draftAudienceKeys:ft,activeWorkflowShape:Wt,activeAudienceKeys:Mt,resetDraftParallelChatTargets:gn,compareGroupId:Tr?.id??null,compareSendScope:Et,selectedChannel:J,busy:U,setBusy:L,setFeedback:X,hydratePendingDispatch:b}),{onAssignExistingCat:Mu,onCreateAndAssignCat:Eu,onCreateAndDraftCat:Du,onRemoveAssignedCat:Bu}=QC({state:W,setState:ue,catForm:O,emptyCatForm:Bs,setCatForm:H,setBusy:L,setFeedback:X,setAddCatOpen:Qe,setDraftCatIds:Ot}),{onApprovalDecision:Ou,onChoiceSubmit:_u,onOperatorAction:Fu}=Lv({state:W,setState:ue,operatorState:De,setOperatorState:it,setBusy:L,setFeedback:X}),Wu=ro(t,`Cats ${e}`,h);Hg(Wu,ma),p.useEffect(()=>{im(Pt?.chat.capabilities.debugLiveTrace===!0)},[Pt?.chat.capabilities.debugLiveTrace]),Fg(S&&!g,p.useCallback(()=>{Te(),le(j=>n?Pi(I,j,qt):[]),lt("sequential"),Ee(null),gn()},[I,Te,gn,qt,Ee,le,lt,n]),I),p.useEffect(()=>{!n||!S||I!=="group"||le(j=>ki({participants:j,target:oe}))},[oe.instance,oe.model,oe.modelSelection,oe.provider,I,le,S,n]),DC({state:W,setState:ue,navigate:u,busy:U,surface:t,currentPath:R,chatPrefix:i,routeChannelId:v,routeChannelExists:Qa,selectedChannelId:Ja,draftDefaultRecipientCatId:g,showingMyCatDirectLane:x,routeDirectLaneSummary:K,unknownRendererErrorMessage:h(l.sharedProductRendererUnknownError)});const Ku=p.useCallback(j=>{$t(j),n&&S&&I==="group"&&le(q=>ki({participants:q,target:j}))},[I,le,S,n]),Uu=p.useCallback((j,q)=>{jn(j,q),j===0&&$t(q)},[jn,$t]),$u=p.useCallback(()=>{if(n){if((I==="default"||I==="parallel")&&xe.participantCatIds.length===0&&F.length===0){const j=Pi("group",[],qt);le(q=>q.length===0?j:q),Ye?Xe(0,j.map(q=>`temp:${q.participantId}`)):Ee(null);return}if(Ye){yt(0);return}_()}},[xe.participantCatIds.length,F.length,I,_,yt,Xe,Ye,qt,Ee,le,n]),Hu=p.useCallback(()=>{if(!n||W.status!=="ready")return;const j=Ca[0]??Me;if(!Ye){const q=Ar();Xe(0,q)}Gn({seedAudienceKeys:[],seedWorkflowShape:j})},[Ca,Me,Ye,Gn,Xe,Ar,W,n]),qu=Jg({resetChannelContinuity:Ch,publishReadyPayload:Ct,setBusy:L,setFeedback:X}),Gu=Qg({updateChannelParticipantApi:gh,setBusy:L,setFeedback:X,setState:ue}),Vu=Xg({selectedChannel:J,selectedParallelChatGroup:Tr,relayParallelChatMessage:mh,setBusy:L,setFeedback:X,setState:ue});return r.jsxs(r.Fragment,{children:[r.jsx(qf,{state:W,BootShell:a,unavailableTitle:h(l.sharedProductRendererChatUnavailableTitle),renderReady:j=>{const{surface:q,directLaneChannel:ee,activeMyCatId:de,activeAssignedCats:ve,assignedCatIds:Ie,bossCatName:je,bossCatAvatarColor:Je,showBossCatAvatar:He,selectableCats:vn,assignableCatCount:bt,draftCatIdSet:pt,showDirectLaneBoot:sr,showAddCatPanel:or}=Hf({pathname:f.pathname,payload:j,draftDefaultRecipientCatId:g,selectedChannel:J,selectedDirectLane:Nt,routeDirectLaneSummary:K,showingMyCatDirectLane:x,addCatOpen:se,showingNewChatDraft:S,draftCatIds:Ne,t:h}),jr=Yv(J,ee),en=Jv(J,ee);function zu(tn){u(bi(tn))}return r.jsx(Vf,{payload:j,sidebarOpen:un,sidebar:o({payload:j,sidebarOpen:un,accountMenuOpen:da,overflowMenuOpenId:Da,busy:U,surface:q,shellSurface:t,routeChannelId:v,accountMenuRef:ua,onToggleSidebar:_a,onCollapsedSidebarClick:Un,onOpenChatsOverview:Rr,onStartNewChat:wu,onStartNewGroupChat:n?ku:void 0,onStartNewParallelChat:n?Pu:void 0,onSelect:tr,onDeleteChannel:js,onRenameChannel:Ts,onRenameParallelChatGroup:Cn,onUngroupParallelChatGroup:Ls,onDeleteParallelChatGroup:ar,onArchiveCat:Va,onClearDirectLane:nr,onCreateNewCat:yu,onAccountMenuToggle:()=>dn(!da),onOverflowMenuToggle:Kn,onNavigateSettings:Iu,onNavigateRuntime:Su,onSwitchProduct:zu,activeMyCatId:de,onDirectChatCat:bu,navigate:u,confirmDialog:rt}),settingsMode:m,busy:U,appContent:r.jsx(s,{payload:j,routeChannelId:v,selectedChannel:J,directLaneChannel:ee,showDirectLaneBoot:sr,feedback:$,busy:U,chatSurfaceProps:{operatorSnapshot:De.snapshot,operatorLoading:De.status==="loading"&&De.snapshot===null,operatorError:De.status==="error"?De.message:"",composerDraft:Z,busy:U,feedback:$,greeting:B,channelFiles:et,channelPlusMenuOpen:kt,channelPlusMenuRef:Oa,channelFileInputRef:Ut,activeAssignedCats:ve,bossCatName:je,bossCatAvatarColor:Je,showBossCatAvatar:He,onComposerChange:Ke,onComposerKeyDown:ui,onSendMessage:hi,onCancelPendingSend:pi,onStopMessage:ju,onRetryMessage:Lu,onToggleChannelPlusMenu:fn,onChannelFileSelect:qn,onTakeScreenshot:Ua,screenshotCaptureDisabled:ca,onChannelFilesChange:V,onApprovalDecision:Ou,onChoiceSubmit:_u,onStartFresh:jr&&en&&sa(en)?()=>qu(jr):void 0,onRelayMessage:Vu,onUpdateChannelParticipant:jr?(tn,Yu)=>Gu(jr,tn,Yu):void 0,onOperatorAction:Fu,autoResize:Xt,selectedExecutionTarget:en&&sa(en)?mn:void 0,onExecutionTargetChange:en&&sa(en)?Xa:void 0,onDirectLaneExecutionTargetChange:Pn,activeWorkflowShape:Wt,onToggleActiveWorkflowShape:en&&co(en)?()=>Lt(tn=>tn==="concurrent"?"sequential":"concurrent"):void 0,activeAudienceKeys:Mt,onSetActiveAudienceKeys:en&&co(en)?ct:void 0,onSelect:tr,liveIndicator:Au,compareGroup:Tr,compareSendScope:Et,onCompareSendScopeChange:st},draftSurfaceProps:{draftSurface:M,onDraftSurfaceChange:D,composerDraft:Z,busy:U,greeting:B,draftFiles:Y,draftCwd:ae,draftCatIds:Ne,draftTemporaryParticipants:F,plusMenuOpen:dt,plusMenuRef:Rn,fileInputRef:Nn,bossCatName:je,bossCatAvatarColor:Je,onComposerChange:Ke,onComposerKeyDown:ui,onSendMessage:hi,onCancelPendingSend:pi,onTogglePlusMenu:ot,onFileSelect:$a,onTakeScreenshot:Zt,screenshotCaptureDisabled:ca,onPickFolder:Ha,onDraftFilesChange:G,onDraftCwdClear:()=>he(null),onToggleDraftCat:ie,onAddDraftTemporaryParticipant:ut,onQuickAddDraftTemporaryParticipant:n?$u:void 0,onRemoveDraftTemporaryParticipant:be,onUpdateDraftTemporaryParticipant:sn,autoResize:Xt,draftDefaultRecipientCatId:g,entryPreset:I,selectedExecutionTarget:oe,onExecutionTargetChange:Ku,draftHighlightedCatId:Yt,onHighlightDraftCat:_t,draftCatExecutionTargetOverrides:nt,onDraftCatExecutionTargetOverride:Le,onDirectLaneExecutionTargetChange:Wn,parallelTargets:n&&A&&Ye?ze:void 0,onParallelTargetChange:n&&(k||Ye)?Uu:void 0,onAddParallelTarget:n&&A&&(_e||Ye)?Hu:void 0,onRemoveParallelTarget:n&&(k||Ye)?Vn:void 0,parallelBranchActions:{onPickFolder:_e&&n&&A&&Ye?ga:void 0,onSetAudienceKeys:n&&A&&Ye?Xe:void 0,onSetCwd:n&&A&&Ye?ce:void 0,onSetRuntimeSessionPolicy:_e&&n&&A&&Ye?Ht:void 0,onToggleWorkflowShape:n&&A&&Ye?zn:void 0,onQuickAddTemporaryParticipant:_e&&n&&A&&Ye?va:void 0},builderControls:gI({advancedDraftControlsEnabled:_e,entryPreset:I,showStructuredDraftControls:n&&A,hasVisibleParallelDraftTargets:Ye}),draftWorkflowShape:Me,draftRuntimeSessionPolicy:Pe,onDraftRuntimeSessionPolicyChange:ht,onToggleDraftWorkflowShape:n?()=>lt(tn=>tn==="concurrent"?"sequential":"concurrent"):void 0,draftAudienceKeys:ft,onSetAudienceKeys:n?Ee:void 0,onCatAvatarSave:wt},addCatOpen:or,onToggleAddCat:Ka,addCatPanelProps:{panelRef:Ba,selectableCats:vn,assignableCatCount:bt,addCatTab:ke,showingNewChatDraft:S&&!g,draftCatIdSet:pt,assignedCatIds:Ie,catForm:O,onClose:()=>Qe(!1),onTabChange:z,onAssignExistingCat:Mu,onRemoveAssignedCat:Bu,onToggleDraftCat:ie,onCatFormChange:H,onCreateCat:tn=>{if(S&&!g){Du(tn);return}Eu(tn)}},folderBrowserProps:Qv({folderBrowsePath:ha,folderBrowseCurrentPath:$n,folderBrowseParentPath:pa,folderBrowseEntries:pn,folderBrowseLoading:hn,folderBrowseError:Hn,onPathChange:Fa,browseFolder:Tn,selectCurrentFolder:fa}),onOpenDraftAddCat:qa,onChangeDraftDefaultRecipient:Ga,companionMode:Fn,companionCat:wn,onToggleCompanionMode:cn,onCompanionWake:Ea,onCompanionSleep:Rt,onCatAvatarSave:wt}),confirmDialog:Jt,onPayloadUpdate:Ct,onFeedback:X,onBusy:L,onResetSetup:xu,onConfirmClose:Dt})}}),r.jsx(Wf,{notifications:bn,onDismiss:_n}),r.jsx(Do,{toasts:gt})]})}}function na({provider:e,instance:t,model:n,modelSelection:a,onTargetChange:s}){return r.jsx(vh,{provider:e,instance:t,model:n,modelSelection:a,onTargetChange:s,fetchProviderRegistry:Yr,fetchProviderModels:Jr,fetchAdvancedProviderModels:Qr})}function CI({panelRef:e,selectableCats:t,assignableCatCount:n,addCatTab:a,busy:s,feedback:o,showingNewChatDraft:i,draftCatIdSet:d,assignedCatIds:c,catForm:u,onClose:h,onTabChange:f,onAssignExistingCat:m,onRemoveAssignedCat:v,onToggleDraftCat:C,onCatFormChange:S,onCreateCat:y,ProviderModelFieldsComponent:g}){const{t:x}=Q();return r.jsxs("div",{className:"addCatPanel",ref:e,children:[r.jsxs("div",{className:"addCatPanelHeader",children:[r.jsx("h2",{children:x("sharedAddCatPanelTitle")}),r.jsx("button",{className:"addCatClose",type:"button",onClick:h,"aria-label":x("sharedAddCatPanelClose"),children:"x"})]}),r.jsxs("div",{className:"addCatTabs",children:[r.jsx("button",{className:a==="existing"?"addCatTab addCatTabActive":"addCatTab",type:"button",onClick:()=>f("existing"),children:x("sharedAddCatPanelChooseExisting")}),r.jsx("button",{className:a==="new"?"addCatTab addCatTabActive":"addCatTab",type:"button",onClick:()=>f("new"),children:x("sharedAddCatPanelCreateNew")})]}),o?r.jsx("p",{className:"feedbackText",children:o}):null,a==="existing"?r.jsx("div",{className:"addCatList",children:t.length>0?t.map(I=>{const k=so(I.mcpProfile);return r.jsxs("div",{className:"addCatItem",children:[r.jsxs("div",{children:[r.jsx("strong",{children:I.name}),r.jsx("p",{children:Ih(I)}),r.jsx("p",{children:k?x(k):I.mcpProfile})]}),(()=>{const P=i?d.has(I.id):c.has(I.id),A=Lr(s,"assign",I.id),M=Lr(s,"remove",I.id);return r.jsx("button",{className:P?"addCatAssignButton addCatRemoveButton":"addCatAssignButton",type:"button",disabled:A||M,onClick:()=>{if(i){C(I.id);return}if(P){v(I);return}m(I)},children:x(A?"sharedAddCatPanelAdding":M?"sharedAddCatPanelRemoving":P?"sharedAddCatPanelRemove":"sharedAddCatPanelAdd")})})()]},I.id)}):r.jsx("div",{className:"emptyStateCard",children:r.jsx("p",{children:x(n===0?"sharedAddCatPanelNoOtherCats":"sharedAddCatPanelAllCatsInChat")})})}):r.jsx("div",{className:"addCatCreate",children:r.jsxs("form",{className:"stackForm",onSubmit:I=>y(I),children:[r.jsxs("label",{className:"fieldLabel",children:[r.jsx("span",{children:x("sharedAddCatPanelNameLabel")}),r.jsx("input",{className:"textInput",value:u.name,onChange:I=>S({...u,name:I.target.value}),placeholder:x("sharedAddCatPanelNamePlaceholder")})]}),r.jsx(g,{provider:u.provider,instance:u.instance,model:u.model,modelSelection:u.modelSelection,onTargetChange:I=>S({...u,provider:I.provider,instance:I.instance,model:I.model,modelSelection:I.modelSelection??null})}),r.jsxs("div",{className:"fieldLabel",children:[r.jsx("span",{children:x(l.sharedSettingsCatsMcpProfileLabel)}),r.jsx("div",{className:"draftLeadPills",role:"group","aria-label":x(l.sharedSettingsCatsMcpProfileLabel),children:Sh.map(I=>r.jsx("button",{type:"button",className:(u.mcpProfile||rc)===I.value?"draftLeadPill draftLeadPillActive":"draftLeadPill",onClick:()=>S({...u,mcpProfile:I.value}),children:x(I.label)},I.value))})]}),r.jsx("button",{className:"primaryButton",disabled:!u.name.trim()||!u.provider.trim()||!u.model.trim(),type:"submit",children:Lr(s,"create")||Lr(s,"create-assign")?x("sharedAddCatPanelSaving"):x(i?"sharedAddCatPanelCreateAndAdd":"sharedAddCatPanelCreateAndAddToChat")})]})})]})}function Ew({...e}){return r.jsx(CI,{...e,ProviderModelFieldsComponent:na})}const vI=768;function II(e,t){const n=t<vI,a="720px";switch(e){case"default_chat":return{mode:e,sidebarWidth:n?"collapsed":"standard",transcriptMaxWidth:a,secondarySurfacePosition:"hidden",catStatusRowVisible:!1,composerVariant:"default"};case"direct_message":return{mode:e,sidebarWidth:n?"collapsed":"standard",transcriptMaxWidth:a,secondarySurfacePosition:n?"bottom":"side",catStatusRowVisible:!1,composerVariant:"direct"};case"companion":return{mode:e,sidebarWidth:n?"collapsed":"standard",transcriptMaxWidth:a,secondarySurfacePosition:"hidden",catStatusRowVisible:!1,composerVariant:"direct"};case"participant_chat":return{mode:e,sidebarWidth:n?"collapsed":"standard",transcriptMaxWidth:a,secondarySurfacePosition:n?"bottom":"side",catStatusRowVisible:!0,composerVariant:"mention_enabled"}}}const yl=new Set(["artifact_only","commit_only","push_branch","pr_with_checks","deploy_preview"]),Io=new Set(["manual_review_required","owner_approval_required","publish_artifact_required"]),bl=new Set(["chat_default","task_override","room_tightening","approved_exception"]),xl=new Set(["normal","warning","blocked"]),wl=new Set(["runtime_usage","rate_limit_incident","guardrail_state"]),Rd=new Set(["retry","acknowledge"]),SI=new Set(["prepare_artifact","create_commit","push_branch","open_pull_request","wait_for_checks","publish_preview"]),yI=new Set(["queued","running","blocked","completed","failed","cancelled"]),bI=new Set(["not_requested","pending","approved","rejected"]),xI=new Set(["approve","reroute","reject"]),wI=["pending","running","completed","failed","blocked","cancelled","waiting_for_converge"];function qe(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Se(e){return typeof e=="string"&&e.trim().length>0?e:null}function It(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function xr(e){return e===!0}function os(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function jt(e,t){const n=Se(e);return n&&t.has(n)?n:null}function Nd(e){if(!e)return null;const t=jt(e.operatorLastAction,Rd),n=Se(e.operatorLastActionAt),a=Se(e.operatorLastActionBy),s=Se(e.operatorLastActionNotes);return t||n||a||s?{kind:t,at:n,by:a,notes:s}:null}function kI(e){const t={pending:0,running:0,completed:0,failed:0,blocked:0,cancelled:0,waiting_for_converge:0};for(const n of e??[]){const a=Se(n.status);a&&wI.includes(a)&&(t[a]+=1)}return t}function PI(e){switch(e){case"commit_only":return["create_commit"];case"push_branch":return["create_commit","push_branch"];case"pr_with_checks":return["create_commit","push_branch","open_pull_request","wait_for_checks"];case"deploy_preview":return["create_commit","push_branch","publish_preview"];default:return["prepare_artifact"]}}function AI(e){return{runStatus:e.runStatus,stageId:e.stageId,shape:e.shape,reviewRequired:e.reviewRequired,lastCheckpointId:e.lastCheckpointId,convergeTargetId:e.convergeTargetId,continuationCount:e.continuationCount,dispatchCount:e.dispatchCount,targetCount:e.targetCount,branchStatusCounts:kI(e.branchStates)}}function RI(e){return{requestedActions:PI(e.deliveryMode),gates:[...e.deliveryGates],context:{channelId:e.channelId,containerId:e.containerId,conversationId:e.conversationId,taskId:e.taskId,roomMode:e.roomMode,transport:e.transport,workflowStageId:e.workflowStageId,workflowShape:e.workflowShape},strict:e.deliveryGates.length>0||e.deliveryMode==="pr_with_checks"||e.deliveryMode==="deploy_preview"}}function NI(e){return{delivery:e.delivery,budget:e.budget,runtimeDeliveryManifest:e.runtimeDeliveryManifest,approval:{status:e.approval?.status??null,requiresOwnerDecision:e.approval?.status==="pending"||!!e.delivery?.gates.includes("owner_approval_required"),pending:e.approval?.status==="pending",latestDecisionAction:e.approval?.decisionAction??null,notes:e.approval?.notes??null},latestOperatorAction:Nd(e.operatorMetadata??null)}}function ni(e){const t=qe(e?.effectiveDeliveryPolicy);if(t){const s=jt(t.mode,yl),o=jt(t.source,bl);if(s&&o)return{mode:s,gates:os(t.gates).filter(i=>Io.has(i)),source:o,rationale:Se(t.rationale)}}const n=jt(e?.effectiveDeliveryMode,yl),a=jt(e?.effectiveDeliverySource,bl);return!n||!a?null:{mode:n,gates:os(e?.effectiveDeliveryGates).filter(s=>Io.has(s)),source:a,rationale:Se(e?.effectiveDeliveryRationale)}}function ai(e){const t=qe(e?.effectiveBudgetPolicy);if(t){const a=jt(t.alertLevel,xl);if(a)return{alertLevel:a,source:jt(t.source,wl),rationale:Se(t.rationale)}}const n=jt(e?.effectiveBudgetAlertLevel,xl);return n?{alertLevel:n,source:jt(e?.effectiveBudgetAlertSource,wl),rationale:Se(e?.effectiveBudgetRationale)}:null}function Td(e){const t=qe(e?.runtimeDeliveryManifest);return t?{requestedActions:os(t.requestedActions).filter(n=>SI.has(n)),gates:os(t.gates).filter(n=>Io.has(n)),context:{channelId:Se(qe(t.context)?.channelId),containerId:Se(qe(t.context)?.containerId),conversationId:Se(qe(t.context)?.conversationId),taskId:Se(qe(t.context)?.taskId),roomMode:Se(qe(t.context)?.roomMode),transport:Se(qe(t.context)?.transport),workflowStageId:Se(qe(t.context)?.workflowStageId),workflowShape:Se(qe(t.context)?.workflowShape)},strict:xr(t.strict)}:null}function TI(e,t=null){const n=qe(e?.workflowSummary);if(n)return{runStatus:jt(n.runStatus,yI)??t,stageId:Se(n.stageId),shape:Se(n.shape),reviewRequired:xr(n.reviewRequired),lastCheckpointId:Se(n.lastCheckpointId),convergeTargetId:Se(n.convergeTargetId),continuationCount:It(n.continuationCount),dispatchCount:It(n.dispatchCount),targetCount:It(n.targetCount),branchStatusCounts:{pending:It(qe(n.branchStatusCounts)?.pending)??0,running:It(qe(n.branchStatusCounts)?.running)??0,completed:It(qe(n.branchStatusCounts)?.completed)??0,failed:It(qe(n.branchStatusCounts)?.failed)??0,blocked:It(qe(n.branchStatusCounts)?.blocked)??0,cancelled:It(qe(n.branchStatusCounts)?.cancelled)??0,waiting_for_converge:It(qe(n.branchStatusCounts)?.waiting_for_converge)??0}};if(!(Se(e?.workflowStageId)||Se(e?.workflowShape)||It(e?.dispatchCount)!==null||It(e?.continuationCount)!==null||It(e?.targetCount)!==null)&&!t)return null;const s=Array.isArray(e?.branchStates)?e?.branchStates.map(o=>qe(o)??{}):[];return AI({runStatus:t,stageId:Se(e?.workflowStageId),shape:Se(e?.workflowShape),reviewRequired:xr(e?.workflowReviewRequired),lastCheckpointId:Se(e?.workflowLastCheckpointId),convergeTargetId:Se(e?.workflowConvergeTargetId),continuationCount:It(e?.continuationCount),dispatchCount:It(e?.dispatchCount),targetCount:It(e?.targetCount),branchStates:s})}function jI(e){const t=qe(e?.governanceSummary);if(!t)return null;const n=qe(t.approval);return{delivery:ni({effectiveDeliveryPolicy:t.delivery}),budget:ai({effectiveBudgetPolicy:t.budget}),runtimeDeliveryManifest:Td({runtimeDeliveryManifest:t.runtimeDeliveryManifest}),approval:{status:jt(n?.status,bI),requiresOwnerDecision:xr(n?.requiresOwnerDecision),pending:xr(n?.pending),latestDecisionAction:jt(n?.latestDecisionAction,xI),notes:Se(n?.notes)},latestOperatorAction:(()=>{const a=qe(t.latestOperatorAction);return a?{kind:jt(a.kind,Rd),at:Se(a.at),by:Se(a.by),notes:Se(a.notes)}:null})()}}function jd(e,t){if(!e)return null;const n=jI(e.metadata),a=t?.metadata??e.metadata;if(n)return{...n,latestOperatorAction:Nd(a)??n.latestOperatorAction};const s=ni(e.metadata),o=ai(e.metadata),i=Td(e.metadata)??(s?RI({deliveryMode:s.mode,deliveryGates:s.gates,channelId:Se(e.metadata.channelId),containerId:Se(e.metadata.containerId),conversationId:e.conversationId,taskId:e.id,roomMode:Se(e.metadata.roomRoutingMode),transport:Se(e.metadata.transport),workflowStageId:Se(e.metadata.workflowStageId),workflowShape:Se(e.metadata.workflowShape)}):null);return NI({approval:e.approval,delivery:s,budget:o,runtimeDeliveryManifest:i,operatorMetadata:a})}function ri(e){return e?TI(e.metadata,e.status):null}function an(e,t){return t.localeCompare(e)}function Vt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ld(e,t){return e?Vt(e[t]):null}function me(e,t){if(!e)return null;const n=e[t];return typeof n=="string"&&n.trim().length>0?n:null}function Gr(e,t){if(!e)return null;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function Vr(e,t){return e?e[t]===!0:!1}function Md(e,t){if(!e)return[];const n=e[t];return Array.isArray(n)?n.filter(a=>!!a&&typeof a=="object"&&!Array.isArray(a)):[]}function Ed(e,t){if(!e)return[];const n=e[t];return Array.isArray(n)?n.filter(a=>typeof a=="string"&&a.trim().length>0):[]}function LI(e){const t=new Set,n=[];for(const a of e)t.has(a.id)||(t.add(a.id),n.push(a));return n}function Dd(e){return me(e,"replayPhase")}function MI(e){switch(e){case"pending_dispatch_stored":case"replay_blocked":case"startup_recovered":return"attention";case"replay_started":return"progress";case"replay_dispatched":return"success";case"replay_failed":return"error";default:return null}}function EI(e){switch(e.status){case"blocked":return"attention";case"failed":return"error";case"succeeded":return"success";default:return"muted"}}function DI(e){switch(e.kind){case"error":return"error";case"approval":return"attention";case"status":return"progress";default:return"muted"}}function BI(e){const t=MI(Dd(e.metadata));if(t)return t;switch(e.kind){case"approval_requested":return"attention";case"approval_decided":return me(e.metadata,"action")==="approve"?"success":"attention";case"operator_action":return"progress";case"status_change":case"artifact_canvas_show_intent":case"artifact_canvas_clear_intent":return"progress";default:return"muted"}}function OI(e){switch(e.status){case"open":return"attention";case"completed":return"success";default:return"muted"}}function _I(e){const t=Dd(e.metadata);if(t)return t==="startup_recovered"?"Recovery":"Replay";switch(e.kind){case"approval_requested":return"Approval";case"approval_decided":return"Decision";case"operator_action":return"Action";case"checkpoint_recorded":return"Checkpoint";case"status_change":return"Status";case"artifact_recorded":case"artifact_canvas_show_intent":case"artifact_canvas_clear_intent":return"Artifact";case"work_item_updated":return"Update";default:return"Note"}}function FI(e){switch(e.kind){case"approval":return"Approval";case"checkpoint":return"Checkpoint";case"dispatch":return"Dispatch";case"error":return"Error";case"outcome":return"Outcome";case"status":return"Status";default:return"Trace"}}function WI(e){const t={[e.ownerProfile.actorId]:e.ownerProfile.displayName};for(const n of e.actors)t[n.id]=n.name;return t}function Bd(e,t,n,a){const s=a.map(o=>me(o.metadata,"guard")).find(o=>!!o);return me(t?.metadata,"guard")??me(n?.metadata,"guard")??me(e?.metadata,"guard")??s??null}function Od(e,t,n,a){const s=a.map(u=>me(u.metadata,"cooldownLabel")??me(u.metadata,"cooldownReason")??me(u.metadata,"cooldownUntil")).find(u=>!!u),o=Vt(t?.metadata),i=Vt(n?.metadata),d=Vt(e?.metadata),c=me(o,"cooldownUntil")??me(i,"cooldownUntil")??me(d,"cooldownUntil")??s;return c||(Vr(o,"cooldownActive")||Vr(i,"cooldownActive")||Vr(d,"cooldownActive")?"Cooldown active":me(o,"cooldownLabel")??me(o,"cooldownReason")??me(i,"cooldownLabel")??me(i,"cooldownReason")??me(d,"cooldownLabel")??me(d,"cooldownReason")??null)}function KI(e){const t=Vt(e.metadata),n=ri(e);return{dispatchCount:n?.dispatchCount??Gr(t,"dispatchCount"),continuationCount:n?.continuationCount??Gr(t,"continuationCount"),targetCount:n?.targetCount??Gr(t,"targetCount")}}function UI(e,t){const n=Ld(e,t),a=me(n,"assistantTurnId"),s=Ed(n,"messageIds");if(!a||s.length===0)return null;const o=Gr(n,"segmentCount")??s.length;return{assistantTurnId:a,messageIds:s,fullText:me(n,"fullText")??"",segmentCount:o>0?o:s.length}}function $I(e){const t=Vt(e?.metadata);return Md(t,"branchStates").map((n,a)=>({id:me(n,"id")??`branch-${a}`,participantName:me(Vt(n.participant),"participantName")??"Unknown Cat",status:me(n,"status")??"pending",handoffReason:me(n,"handoffReason"),branchStrategy:me(n,"branchStrategy"),parentCheckpointId:me(n,"parentCheckpointId"),response:UI(n,"response"),error:me(n,"error")}))}function _r(e){const t=Ld(e,"workflowRecommendation");if(!t)return null;const n=me(t,"workflowShape"),a=me(t,"source"),s=me(e,"continuationSource"),o=Md(t,"candidateTargets").map(i=>({participantKind:(()=>{const d=me(i,"participantKind");return d==="orchestrator"||d==="cat"?d:null})(),participantId:me(i,"participantId"),participantName:me(i,"participantName")}));return{source:a==="checkpoint"||a==="boss_replan"||a==="system_inference"?a:null,workflowShape:n==="sequential"||n==="concurrent"||n==="converge"?n:n==="parallel"?"concurrent":null,continuationSource:s==="explicit_mentions"||s==="workflow_recommendation"?s:null,branchStrategy:me(t,"branchStrategy"),rationale:me(t,"rationale"),reviewRequired:Vr(t,"reviewRequired"),candidateTargets:o,unresolvedTargets:Ed(e,"unresolvedTargets")}}function _d(e){return _r(e.latestCheckpoint?.metadata)??_r(e.latestOutcome?.metadata)??_r(e.latestRun?.metadata)??e.traces?.map(t=>_r(t.metadata)).find(t=>!!t)??null}const HI=new Set(["manual_review_required","owner_approval_required","publish_artifact_required"]);function qI(e){if(!e)return null;const t=Vt(e.metadata),n=ni(t),a=ai(t);return{deliveryMode:n?.mode??null,deliveryGates:n?.gates??(Array.isArray(t?.effectiveDeliveryGates)?t.effectiveDeliveryGates.filter(s=>typeof s=="string"&&HI.has(s)):[]),deliverySource:n?.source??null,deliveryRationale:n?.rationale??null,budgetAlertLevel:a?.alertLevel??null,budgetAlertSource:a?.source??null,budgetRationale:a?.rationale??null}}function Fd(e){return!e||e.status!=="pending"||!e.requiresOwnerDecision?[]:e.decisionOptions.map(t=>({kind:t.action,label:t.label,description:t.description,disabled:!1,taskId:e.taskId,approvalId:e.id,status:e.status}))}function Wd(e,t,n,a,s,o){if(!t)return[];if(!(t.status==="blocked"||t.status==="failed"||!!s||!!o))return[];const d=Vt(e?.metadata),u=Vt(t.metadata)??{},h=Vt(d?.orchestratorDispatchReplay),f=n?.updatedAt??a?.updatedAt??t.updatedAt,m=me(u,"operatorAcknowledgedAt"),v=me(d,"operatorRetryRequestedAt")??me(u,"operatorRetryRequestedAt"),C=!!(m&&m.localeCompare(f)>=0),S=!!(v&&v.localeCompare(f)>=0),y=me(h,"replayTrigger"),g=me(h,"replayState"),x=me(h,"replayError"),I=S&&y==="retry"?g==="in_progress"?"Retry in progress":g==="failed"?x?`Retry failed: ${x}`:"Retry failed":"Retry dispatched":S?"Retry requested":null;return[{kind:"retry",label:S&&g==="failed"?"Retry Again":S&&g==="in_progress"?"Retrying":S?"Retry Requested":"Request Retry",description:g==="failed"?"Retry failed. Operators can request another replay of the stored dispatch.":"Record that the operator wants this blocked or failed run retried.",disabled:S&&g!=="failed",statusLabel:I,taskId:e?.id??t.taskId,runId:t.id,checkpointId:a?.id??null,outcomeId:n?.id??null},{kind:"acknowledge",label:C?"Acknowledged":"Acknowledge",description:"Record that the operator has seen the current guardrail or incident state.",disabled:C,statusLabel:C?"Acknowledged":null,taskId:e?.id??t.taskId,runId:t.id,checkpointId:a?.id??null,outcomeId:n?.id??null}]}function GI(e,t,n,a,s){const o=e.map(u=>({id:`activity:${u.id}`,label:_I(u),message:u.message,createdAt:u.createdAt,actorId:u.actorId,actorName:u.actorId?s[u.actorId]??null:null,runId:u.runId,taskId:u.taskId,severity:BI(u),source:"activity"})),i=t.filter(u=>u.kind==="status"||u.kind==="approval"||u.kind==="error").map(u=>({id:`trace:${u.id}`,label:FI(u),message:u.message,createdAt:u.createdAt,actorId:u.actorId,actorName:u.actorId?s[u.actorId]??null:null,runId:u.runId,taskId:u.taskId,severity:DI(u),source:"trace"})),d=n.map(u=>({id:`checkpoint:${u.id}`,label:"Checkpoint",message:u.summary??u.label,createdAt:u.updatedAt,actorId:null,actorName:null,runId:u.runId,taskId:u.taskId,severity:OI(u),source:"checkpoint"})),c=a.map(u=>({id:`outcome:${u.id}`,label:"Outcome",message:u.summary??u.title,createdAt:u.updatedAt,actorId:null,actorName:null,runId:u.runId,taskId:u.taskId,severity:EI(u),source:"outcome"}));return LI([...o,...i,...d,...c].sort((u,h)=>an(u.createdAt,h.createdAt)))}function kl(e){return Gc(null,e).conversationId}function VI(e){return typeof e=="string"?{channelId:e,conversationId:kl(e)}:{channelId:e.id,conversationId:e.conversationId?.trim()||kl(e.id)}}function zI(e,t){if(!e)return null;const{channelId:n,conversationId:a}=VI(t),s=`task-channel-${n}`,o=WI(e.core),i=e.core.tasks.find(N=>N.id===s)??null,d=e.approvals.filter(N=>N.conversationId===a||N.taskId===s).sort((N,R)=>an(N.requestedAt??N.decidedAt??"",R.requestedAt??R.decidedAt??"")),c=e.core.runs.filter(N=>N.conversationId===a).sort((N,R)=>an(N.updatedAt,R.updatedAt)),u=e.core.traces.filter(N=>N.conversationId===a).sort((N,R)=>an(N.createdAt,R.createdAt)),h=e.core.checkpoints.filter(N=>N.conversationId===a).sort((N,R)=>an(N.updatedAt,R.updatedAt)),f=e.core.outcomes.filter(N=>N.conversationId===a).sort((N,R)=>an(N.updatedAt,R.updatedAt)),m=e.core.activities.filter(N=>N.conversationId===a).sort((N,R)=>an(N.createdAt,R.createdAt)),v=c[0]??null,C=f[0]??null,S=h[0]??null,y=d[0]??null,g=Bd(v,C,S,u),x=Od(v,C,S,u),I=qI(i),k=ri(v),P=_d({latestCheckpoint:S,latestOutcome:C,latestRun:v,traces:u}),A=jd(i,v),M=Fd(y),D=GI(m,u,h,f,o);return{channelId:n,conversationId:a,actorNameById:o,task:i,approvals:d,runs:c,traces:u,checkpoints:h,outcomes:f,activityFeed:D,latestRun:v,latestOutcome:C,latestCheckpoint:S,latestApproval:y,guardReason:g,cooldownLabel:x,effectivePolicy:I,governanceSummary:A,workflowSummary:k,latestWorkflowRecommendation:P,approvalActions:M,incidentActions:Wd(i,v,C,S,g,x)}}function YI(e,t){if(!e)return null;const n=e.runs.find(S=>S.id===t)??e.latestRun;if(!n)return null;const a=e.traces.filter(S=>S.runId===n.id).sort((S,y)=>an(S.createdAt,y.createdAt)),s=e.checkpoints.filter(S=>S.runId===n.id).sort((S,y)=>an(S.updatedAt,y.updatedAt)),o=e.outcomes.filter(S=>S.runId===n.id).sort((S,y)=>an(S.updatedAt,y.updatedAt)),i=e.approvals.filter(S=>S.taskId===n.taskId),d=o[0]??null,c=s[0]??null,u=Bd(n,d,c,a),h=Od(n,d,c,a),f=ri(n),m=_d({latestCheckpoint:c,latestOutcome:d,latestRun:n,traces:a}),v=jd(e.task,n),C=i[0]??e.latestApproval;return{run:n,traces:a,checkpoints:s,outcomes:o,approvals:i,latestOutcome:d,latestCheckpoint:c,guardReason:u,cooldownLabel:h,metrics:KI(n),workflowSummary:f,governanceSummary:v,workflowStageId:f?.stageId??null,workflowShape:f?.shape??null,reviewRequired:f?.reviewRequired??!1,branchStates:$I(n),latestWorkflowRecommendation:m,approvalActions:Fd(C),incidentActions:Wd(e.task,n,d,c,u,h)}}function JI(e){const t=e.threshold??80;return e.scrollTop+e.clientHeight>=e.scrollHeight-t}const Pl=80,QI=12;function XI(e){return e?.closest(".canvas")}function ZI(e){const t=Number.parseFloat(globalThis.getComputedStyle(e).bottom||"0");return Number.isFinite(t)?Math.max(0,t):0}function eS(e){return e?Math.ceil(Pl+e.getBoundingClientRect().height):Pl}function tS(e){const{channelId:t,scrollKey:n,scrollOnChannelChange:a=!0,scopeKey:s=""}=e,[o,i]=p.useState(null),[d,c]=p.useState(null),[u,h]=p.useState(null),f=p.useRef(null),m=p.useRef(!0),[v,C]=p.useState(!0),S=p.useRef(null),y=p.useRef(null),g=p.useRef(0),x=p.useRef(null),I=p.useRef(null),k=p.useCallback(()=>{const N=f.current;if(!N){m.current=!0,C(!0);return}const R=JI({scrollTop:N.scrollTop,clientHeight:N.clientHeight,scrollHeight:N.scrollHeight,threshold:eS(d)});m.current=R,C(R)},[d]),P=p.useCallback(()=>{if(!o){S.current=null;return}const N=d?Math.ceil(ZI(d)+QI):0;S.current!==N&&(S.current=N,o.style.paddingBottom=N>0?`${N}px`:"")},[d,o]),A=p.useCallback(()=>{if(!d){y.current=null,g.current=0;return}const N=Math.ceil(d.getBoundingClientRect().height);if(N<=0)return;const R=y.current,w=R==null?N:Math.min(R,N);y.current=w;const b=Math.max(0,N-w);if(g.current!==b&&(g.current=b,d.style.marginTop=b>0?`${-b}px`:""),!u){x.current=Math.max(0,b);return}const T=Math.max(0,b);x.current!==T&&(x.current=T,u.style.height=`${T}px`)},[u,d]),M=p.useCallback(()=>{A(),P(),m.current=!0,C(!0);const N=f.current;if(N){N.scrollTo({top:N.scrollHeight});return}u&&u.scrollIntoView({block:"end"})},[u,A,P]),D=p.useCallback(()=>{I.current!==null&&cancelAnimationFrame(I.current),I.current=requestAnimationFrame(()=>{I.current=null,M()})},[M]);return p.useLayoutEffect(()=>{const N=XI(o);if(f.current=N,!N)return;const R=Uv(s,t);a&&R&&!R.nearBottom?(N.scrollTop=R.top,m.current=!1,C(!1)):a?(m.current=!0,D()):k();const w=()=>{k(),$v(s,t,{top:N.scrollTop,nearBottom:m.current})};return N.addEventListener("scroll",w,{passive:!0}),()=>{I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),N.removeEventListener("scroll",w),f.current===N&&(f.current=null)}},[t,s,a,D,k,o]),p.useEffect(()=>(A(),P(),()=>{I.current!==null&&(cancelAnimationFrame(I.current),I.current=null),o&&(o.style.paddingBottom=""),d&&(d.style.marginTop=""),u&&(u.style.height=""),S.current=null,y.current=null,g.current=0,x.current=null}),[u,d,A,P,o]),p.useEffect(()=>{!o||!m.current||D()},[n,D,o]),p.useEffect(()=>{const N=f.current;if(!o||!N||typeof ResizeObserver>"u")return;const R=new ResizeObserver(()=>{A(),P(),m.current&&D()});return R.observe(o),()=>{R.disconnect()}},[D,A,P,o]),p.useEffect(()=>{if(!d||typeof ResizeObserver>"u")return;A();const N=new ResizeObserver(()=>{A()});return N.observe(d),()=>{N.disconnect()}},[d,A]),p.useEffect(()=>{y.current=null,g.current=0,x.current=null,A()},[t,A]),{transcriptListRef:i,composerCardRef:c,bottomSentinelRef:h,isNearBottom:v,scrollToBottom:M}}function Kd(e){return e.assignedParticipants&&e.assignedParticipants.length>0?e.assignedParticipants:e.assignedCats}function nS(e){return Kd(e).filter(t=>t.status==="active")}function aS(e,t){return Kd(e).find(n=>n.participantId===t)??null}function is(e){return"catId"in e&&typeof e.catId=="string"&&e.catId.length>0?e.catId:e.sourceKind==="cat"?e.sourceRefId:null}function rS(e){const{payload:t,selectedChannel:n,activeAssignedCats:a,showBossCatAvatar:s,isDirectLane:o,isDefaultChatComposer:i}=e,d=n.roomRouting.defaultRecipientId,c=p.useMemo(()=>nS(n),[n]),u=d?c.find(w=>w.participantId===d)??null:c[0]??null,h=u?.sourceKind==="cat"?a.find(w=>w.participantId===u.participantId)??null:null,f=p.useMemo(()=>new Map(t.chat.cats.map(w=>[w.id,w])),[t.chat.cats]);function m(w,b,T){if(w)return{backgroundImage:`url(${w})`,backgroundSize:"cover",backgroundPosition:"center"};if(T&&b)return{background:b}}function v(w){if(!w)return null;const b=is(w);return b?f.get(b)??null:null}function C(w,b=v(w)){return!w||b==null}function S(w,b=v(w)){return b?.name??w.name}function y(w,b=v(w)){return b?.avatarUrl??w.avatarUrl??null}function g(w,b=null){return m(b?.avatarUrl??w.avatarUrl??null,b?.avatarColor??w.avatarColor??null,b!=null)}function x(w,b={}){const T=b.catRecord??v(w);return["catAvatar",b.transcript?"transcriptAvatar":"",b.composer?"composerStackAvatar":"",T?.id===t.chat.bossCatId?"catAvatarBoss":"",C(w,T)?"channelParticipantAvatar":""].filter(Boolean).join(" ")}function I(w){const b=w.metadata?.executionLabelSnapshot;return typeof b=="string"&&b.trim()?b.trim():null}function k(w){const b=typeof w.metadata?.targetId=="string"?w.metadata.targetId.trim():"";if(b)return aS(n,b);const T=new Set,E=w.senderName?.trim();E&&!yh(E)&&T.add(E);const O=I(w);return O&&T.add(O),T.size===0?null:c.find(H=>{const U=ra(H);return T.has(H.name)||U!=null&&T.has(U)})??null}const P=o&&h?t.chat.cats.find(w=>w.id===h.catId)??null:null,A=t.chat.bossCatId?t.chat.cats.find(w=>w.id===t.chat.bossCatId)??null:null,M=h?t.chat.cats.find(w=>w.id===h.catId)??null:null,D=p.useMemo(()=>c.map(w=>{const b=is(w);return b?t.chat.cats.find(T=>T.id===b)??null:null}).filter(w=>w!=null),[c,t.chat.cats]),N=p.useMemo(()=>c.filter(w=>w.sourceKind!=="cat"),[c]),R=p.useMemo(()=>{const w=[];if(o){if(M){const b=u?ra(u):null;w.push({key:`participant:${M.id}`,label:M.name,executionLabel:b,avatarColor:M.avatarColor??null,avatarUrl:M.avatarUrl??null,isBoss:M.id===t.chat.bossCatId,useNeutralAvatar:!1,pulseParticipantId:u?.participantId??null,pulseCatId:M.id})}}else{s&&!i&&A&&w.push({key:`participant:${A.id}`,label:A.name,executionLabel:oa(A),avatarColor:A.avatarColor??null,avatarUrl:A.avatarUrl??null,isBoss:!0,useNeutralAvatar:!1,pulseParticipantId:null,pulseCatId:A.id});for(const b of c){const T=v(b);w.push({key:`participant:${b.participantId}`,label:S(b,T),executionLabel:ra(b),avatarColor:T?.avatarColor??b.avatarColor??null,avatarUrl:T?.avatarUrl??b.avatarUrl??null,isBoss:T?.id===t.chat.bossCatId,useNeutralAvatar:C(b,T),pulseParticipantId:b.participantId,pulseCatId:T?.id??null})}}return w},[c,A,M,u?.participantId,o,i,t.chat.bossCatId,C,S,v,s]);return{activeRoomParticipants:c,defaultRecipientParticipant:u,defaultRecipientCat:h,directLaneCat:P,bossCatRecord:A,defaultRecipientCatRecord:M,assignedCatRecords:D,assignedAdhocParticipants:N,topBarParticipants:R,resolveParticipantCatRecord:v,resolveParticipantDisplayName:S,resolveParticipantAvatarUrl:y,buildParticipantAvatarStyle:g,buildParticipantAvatarClassName:x,resolveMessageParticipant:k}}function sS({conversationMode:e,layoutMode:t,composerVariant:n,secondarySurfacePosition:a,layoutStyle:s,hasConversationStarted:o,topBar:i,statusRow:d=null,children:c,sidePanel:u,activeDirectCatId:h=null}){const[f,m]=p.useState(null);return p.useEffect(()=>{if(!h){m(null);return}return m(bh(h)),xh(h,m)},[h]),r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"viewShell viewShellChannel","data-conversation-mode":e,"data-layout-mode":t,"data-composer-variant":n,"data-secondary-surface-position":a,style:s,children:[i,d,r.jsxs("div",{className:"channelWorkspace",children:[f?r.jsx("div",{className:"activeChatCoverBackdrop",style:{backgroundImage:`url(${f})`},"aria-hidden":"true"}):null,r.jsx("section",{className:o?"channelShell":"channelShell channelShellFresh",children:c})]})]}),u]})}function oS({avatars:e,showRosterAvatars:t,isDirectLane:n,topBarTitle:a,sidePanelOpen:s,approvalCount:o,extraActions:i,onToggleSidePanel:d,onOpenCatProfile:c}){const{t:u}=Q();return r.jsxs("header",{className:"channelTopBar",children:[r.jsx("div",{className:"channelTopBarStart",children:t?r.jsx("div",{className:"rosterAvatars rosterAvatarsExpanded",children:e.map(h=>r.jsxs("div",{className:[h.isBoss?"catAvatar catAvatarBoss":"catAvatar",h.useNeutralAvatar?"channelParticipantAvatar":"",h.pulsing?"catAvatarPulsing":""].filter(Boolean).join(" "),"data-tooltip":h.useNeutralAvatar?h.executionLabel||h.label:h.executionLabel?`${h.label} · ${h.executionLabel}`:h.label,style:h.avatarUrl?{backgroundImage:`url(${h.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:!h.useNeutralAvatar&&h.avatarColor?{background:h.avatarColor}:void 0,children:[h.avatarUrl?null:At(h.label),h.showLeadBadge?r.jsx("span",{className:"catAvatarLeadBadge",children:"★"}):null]},h.key))}):null}),r.jsx("div",{className:"channelTopBarCenter",children:r.jsx("span",{className:n?"channelTopBarTitle channelTopBarTitleDirectLane":"channelTopBarTitle",children:a})}),r.jsxs("div",{className:"channelTopBarEnd",children:[i,c?r.jsx("button",{className:"sidePanelToggle",type:"button",onClick:c,"aria-label":u(l.chatTopBarOpenCatProfileAriaLabel),children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M2 8s2.5-5 6-5 6 5 6 5-2.5 5-6 5-6-5-6-5z"}),r.jsx("circle",{cx:"8",cy:"8",r:"2"})]})}):null,r.jsxs("button",{className:"sidePanelToggle",type:"button",onClick:d,"aria-label":u(l.chatTopBarToggleSidePanelAriaLabel),"aria-pressed":s,children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M10 2v12"}),r.jsx("rect",{x:"2",y:"2",width:"12",height:"12",rx:"2"})]}),o>0?r.jsx("span",{className:"sidePanelBadge",children:o}):null]})]})]})}const St=e=>({[l.sharedOperatorNoTimestamp]:"No timestamp",[l.sharedOperatorRunStatusRunning]:"Running",[l.sharedOperatorRunStatusBlocked]:"Blocked",[l.sharedOperatorRunStatusCompleted]:"Completed",[l.sharedOperatorRunStatusFailed]:"Failed",[l.sharedOperatorRunStatusCancelled]:"Cancelled",[l.sharedOperatorRunStatusQueued]:"Queued",[l.sharedOperatorWorkflowStageBlocked]:"Blocked",[l.sharedOperatorWorkflowStageConcurrentFanOut]:"Concurrent fan-out",[l.sharedOperatorWorkflowStageContinuationHandoff]:"Continuation handoff",[l.sharedOperatorWorkflowStageConvergeReview]:"Converge review",[l.sharedOperatorWorkflowStageDispatch]:"Dispatch",[l.sharedOperatorWorkflowStageInitialDispatch]:"Initial dispatch",[l.sharedOperatorWorkflowStageRuntimeError]:"Runtime error",[l.sharedOperatorWorkflowStageStartupRecovery]:"Startup recovery",[l.sharedOperatorWorkflowStageTurnCompleted]:"Turn completed",[l.sharedOperatorBranchStatusPending]:"Pending",[l.sharedOperatorBranchStatusRunning]:"Running",[l.sharedOperatorBranchStatusCompleted]:"Completed",[l.sharedOperatorBranchStatusFailed]:"Failed",[l.sharedOperatorBranchStatusBlocked]:"Blocked",[l.sharedOperatorBranchStatusCancelled]:"Cancelled",[l.sharedOperatorBranchStatusWaitingForConverge]:"Waiting for converge",[l.sharedOperatorCheckpointStatusCompleted]:"Completed",[l.sharedOperatorCheckpointStatusCancelled]:"Cancelled",[l.sharedOperatorCheckpointStatusOpen]:"Open",[l.sharedOperatorOutcomeStatusSucceeded]:"Succeeded",[l.sharedOperatorOutcomeStatusBlocked]:"Blocked",[l.sharedOperatorOutcomeStatusFailed]:"Failed",[l.sharedOperatorOutcomeStatusCancelled]:"Cancelled",[l.sharedOperatorTraceKindApproval]:"Approval",[l.sharedOperatorTraceKindCheckpoint]:"Checkpoint",[l.sharedOperatorTraceKindDispatch]:"Dispatch",[l.sharedOperatorTraceKindError]:"Error",[l.sharedOperatorTraceKindOutcome]:"Outcome",[l.sharedOperatorTraceKindStatus]:"Status",[l.sharedOperatorTraceKindNote]:"Note",[l.sharedOperatorGuardMaxContinuations]:"Max continuations",[l.sharedOperatorGuardMaxDispatches]:"Max dispatches",[l.sharedOperatorGuardMaxTargetVisits]:"Max target visits",[l.sharedOperatorGuardAntiPingPong]:"Anti ping-pong",[l.sharedOperatorCooldownActive]:"Cooldown active",[l.sharedOperatorActivityLabelRecovery]:"Recovery",[l.sharedOperatorActivityLabelReplay]:"Replay",[l.sharedOperatorActivityLabelDecision]:"Decision",[l.sharedOperatorActivityLabelAction]:"Action",[l.sharedOperatorActivityLabelArtifact]:"Artifact",[l.sharedOperatorActivityLabelUpdate]:"Update",[l.sharedOperatorActivityLabelTrace]:"Trace",[l.sharedOperatorDeliveryModeArtifactOnly]:"Artifact only",[l.sharedOperatorDeliveryModeCommitOnly]:"Commit only",[l.sharedOperatorDeliveryModeDeployPreview]:"Deploy preview",[l.sharedOperatorDeliveryModePrWithChecks]:"Pull request with checks",[l.sharedOperatorDeliveryModePushBranch]:"Push branch",[l.sharedOperatorGateManualReviewRequired]:"Manual review required",[l.sharedOperatorGateOwnerApprovalRequired]:"Owner approval required",[l.sharedOperatorGatePublishArtifactRequired]:"Publish artifact required",[l.sharedOperatorBudgetLevelNormal]:"Normal",[l.sharedOperatorBudgetLevelWarning]:"Warning",[l.sharedOperatorBudgetLevelBlocked]:"Blocked",[l.sharedOperatorWorkflowShapeSequential]:"Sequential",[l.sharedOperatorWorkflowShapeConcurrent]:"Concurrent",[l.sharedOperatorWorkflowShapeConverge]:"Converge",[l.sharedOperatorBranchStrategyForkIfPossible]:"Fork if possible",[l.sharedOperatorBranchStrategyFreshNoParent]:"Fresh branch without parent",[l.sharedOperatorBranchStrategySingleTargetReview]:"Single-target review",[l.sharedOperatorBranchStrategyTransplantContext]:"Transplant context",[l.sharedOperatorBranchHandoffExplicitMention]:"Explicit mention",[l.sharedOperatorBranchHandoffOperatorReroute]:"Operator reroute",[l.sharedOperatorBranchHandoffRoomDefault]:"Room default",[l.sharedOperatorBranchHandoffRoomEntry]:"Room entry",[l.sharedOperatorBranchHandoffRuntimeRetry]:"Runtime retry",[l.sharedOperatorBranchHandoffWorkflowContinuation]:"Workflow continuation"})[e]??String(e),iS={Approval:l.sharedOperatorTraceKindApproval,Checkpoint:l.sharedOperatorTraceKindCheckpoint,Dispatch:l.sharedOperatorTraceKindDispatch,Error:l.sharedOperatorTraceKindError,Outcome:l.sharedOperatorTraceKindOutcome,Status:l.sharedOperatorTraceKindStatus,Note:l.sharedOperatorTraceKindNote,Recovery:l.sharedOperatorActivityLabelRecovery,Replay:l.sharedOperatorActivityLabelReplay,Decision:l.sharedOperatorActivityLabelDecision,Action:l.sharedOperatorActivityLabelAction,Artifact:l.sharedOperatorActivityLabelArtifact,Update:l.sharedOperatorActivityLabelUpdate,Trace:l.sharedOperatorActivityLabelTrace};function Aa(e,t=St){if(!e)return t(l.sharedOperatorNoTimestamp);const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString([],{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}function gr(e){switch(e){case"progress":return"isProgress";case"attention":return"isAttention";case"error":return"isError";case"success":return"isSuccess";default:return"isMuted"}}function So(e,t=St){switch(e){case"running":return t(l.sharedOperatorRunStatusRunning);case"blocked":return t(l.sharedOperatorRunStatusBlocked);case"completed":return t(l.sharedOperatorRunStatusCompleted);case"failed":return t(l.sharedOperatorRunStatusFailed);case"cancelled":return t(l.sharedOperatorRunStatusCancelled);default:return t(l.sharedOperatorRunStatusQueued)}}function Ud(e){switch(e){case"running":return"progress";case"blocked":return"attention";case"failed":return"error";case"completed":return"success";default:return"muted"}}function lS(e,t=St){switch(e){case"pending":return t(l.sharedOperatorBranchStatusPending);case"running":return t(l.sharedOperatorBranchStatusRunning);case"completed":return t(l.sharedOperatorBranchStatusCompleted);case"failed":return t(l.sharedOperatorBranchStatusFailed);case"blocked":return t(l.sharedOperatorBranchStatusBlocked);case"cancelled":return t(l.sharedOperatorBranchStatusCancelled);default:return t(l.sharedOperatorBranchStatusWaitingForConverge)}}function cS(e,t=St){switch(e){case"completed":return t(l.sharedOperatorCheckpointStatusCompleted);case"cancelled":return t(l.sharedOperatorCheckpointStatusCancelled);default:return t(l.sharedOperatorCheckpointStatusOpen)}}function dS(e){switch(e){case"completed":return"success";case"cancelled":return"muted";default:return"attention"}}function uS(e,t=St){switch(e){case"succeeded":return t(l.sharedOperatorOutcomeStatusSucceeded);case"blocked":return t(l.sharedOperatorOutcomeStatusBlocked);case"failed":return t(l.sharedOperatorOutcomeStatusFailed);default:return t(l.sharedOperatorOutcomeStatusCancelled)}}function pS(e){switch(e){case"succeeded":return"success";case"blocked":return"attention";case"failed":return"error";default:return"muted"}}function hS(e,t=St){switch(e){case"approval":return t(l.sharedOperatorTraceKindApproval);case"checkpoint":return t(l.sharedOperatorTraceKindCheckpoint);case"dispatch":return t(l.sharedOperatorTraceKindDispatch);case"error":return t(l.sharedOperatorTraceKindError);case"outcome":return t(l.sharedOperatorTraceKindOutcome);case"status":return t(l.sharedOperatorTraceKindStatus);default:return t(l.sharedOperatorTraceKindNote)}}function fS(e,t=St){const n=iS[e];return n?t(n):e}const mS={artifact_only:l.sharedOperatorDeliveryModeArtifactOnly,commit_only:l.sharedOperatorDeliveryModeCommitOnly,deploy_preview:l.sharedOperatorDeliveryModeDeployPreview,pr_with_checks:l.sharedOperatorDeliveryModePrWithChecks,push_branch:l.sharedOperatorDeliveryModePushBranch},gS={manual_review_required:l.sharedOperatorGateManualReviewRequired,owner_approval_required:l.sharedOperatorGateOwnerApprovalRequired,publish_artifact_required:l.sharedOperatorGatePublishArtifactRequired},CS={blocked:l.sharedOperatorBudgetLevelBlocked,normal:l.sharedOperatorBudgetLevelNormal,warning:l.sharedOperatorBudgetLevelWarning},vS={concurrent:l.sharedOperatorWorkflowShapeConcurrent,converge:l.sharedOperatorWorkflowShapeConverge,parallel:l.sharedOperatorWorkflowShapeConcurrent,sequential:l.sharedOperatorWorkflowShapeSequential},IS={blocked:l.sharedOperatorWorkflowStageBlocked,concurrent_fan_out:l.sharedOperatorWorkflowStageConcurrentFanOut,continuation_handoff:l.sharedOperatorWorkflowStageContinuationHandoff,converge_review:l.sharedOperatorWorkflowStageConvergeReview,dispatch:l.sharedOperatorWorkflowStageDispatch,initial_dispatch:l.sharedOperatorWorkflowStageInitialDispatch,runtime_error:l.sharedOperatorWorkflowStageRuntimeError,startup_recovery:l.sharedOperatorWorkflowStageStartupRecovery,turn_completed:l.sharedOperatorWorkflowStageTurnCompleted},SS={fork_if_possible:l.sharedOperatorBranchStrategyForkIfPossible,fresh_no_parent:l.sharedOperatorBranchStrategyFreshNoParent,single_target_review:l.sharedOperatorBranchStrategySingleTargetReview,transplant_context:l.sharedOperatorBranchStrategyTransplantContext},yS={explicit_mention:l.sharedOperatorBranchHandoffExplicitMention,operator_reroute:l.sharedOperatorBranchHandoffOperatorReroute,room_default:l.sharedOperatorBranchHandoffRoomDefault,room_entry:l.sharedOperatorBranchHandoffRoomEntry,runtime_retry:l.sharedOperatorBranchHandoffRuntimeRetry,workflow_continuation:l.sharedOperatorBranchHandoffWorkflowContinuation},bS={anti_ping_pong:l.sharedOperatorGuardAntiPingPong,max_continuations:l.sharedOperatorGuardMaxContinuations,max_dispatches:l.sharedOperatorGuardMaxDispatches,max_target_visits:l.sharedOperatorGuardMaxTargetVisits},xS={"cooldown active":l.sharedOperatorCooldownActive};function wS(e){return e.trim().toLowerCase().replace(/-/gu,"_")}function kS(e){return e.trim().replace(/[_-]+/gu," ").replace(/\s+/gu," ").replace(/\b\w/gu,t=>t.toUpperCase())}function On(e,t,n){const a=e.trim();if(!a)return a;const s=t[wS(a)];return s?n(s):kS(a)}function PS(e,t=St){return On(e,mS,t)}function AS(e,t=St){return On(e,gS,t)}function RS(e,t=St){return On(e,CS,t)}function $d(e,t=St){return On(e,vS,t)}function Hd(e,t=St){return On(e,IS,t)}function NS(e,t=St){return On(e,SS,t)}function TS(e,t=St){return On(e,yS,t)}function qd(e,t=St){return On(e,bS,t)}function Gd(e,t=St){const n=e.trim().toLowerCase(),a=xS[n];return a?t(a):e}function jS({items:e}){const{t}=Q();return r.jsxs("section",{className:"operatorPanel",children:[r.jsx("div",{className:"operatorPanelHeader",children:r.jsxs("div",{children:[r.jsx("p",{className:"operatorEyebrow",children:t(l.chatActivityEyebrow)}),r.jsx("h2",{children:t(l.chatActivityLatestUpdatesHeading)})]})}),e.length===0?r.jsx("p",{className:"operatorEmptyState",children:t(l.chatActivityEmptyState)}):r.jsx("div",{className:"operatorTimeline",children:e.slice(0,8).map(n=>r.jsxs("article",{className:"operatorTimelineItem",children:[r.jsx("div",{className:`operatorTimelineDot ${gr(n.severity)}`}),r.jsxs("div",{className:"operatorTimelineBody",children:[r.jsxs("div",{className:"operatorTimelineHeader",children:[r.jsx("strong",{children:fS(n.label,t)}),r.jsx("span",{children:Aa(n.createdAt,t)})]}),r.jsx("p",{children:n.message}),n.actorName?r.jsx("span",{className:"operatorMetaText",children:t(l.chatActivityByActor,{actorName:n.actorName})}):null]})]},n.id))})]})}const LS={"Request Retry":l.sharedOperatorActionRequestRetry,"Retry Again":l.sharedOperatorActionRetryAgain,Retrying:l.sharedOperatorActionRetrying,"Retry Requested":l.sharedOperatorActionRetryRequested,Acknowledge:l.sharedOperatorActionAcknowledge,Acknowledged:l.sharedOperatorActionAcknowledged},MS={"Retry failed. Operators can request another replay of the stored dispatch.":l.sharedOperatorActionRetryFailedDescription,"Record that the operator wants this blocked or failed run retried.":l.sharedOperatorActionRetryDescription,"Replay the stored dispatch or workflow continuation through the existing operator seam.":l.sharedOperatorActionReplayStoredDispatchDescription,"Record that the operator wants this blocked or failed task retried.":l.sharedOperatorActionRetryTaskDescription,"Record that the operator has seen the current guardrail or incident state.":l.sharedOperatorActionAcknowledgeDescription,"Record that the operator has seen the current blocked or failed state.":l.sharedOperatorActionAcknowledgeBlockedDescription},ES={"Retry in progress":l.sharedOperatorActionStatusRetryInProgress,"Retry failed":l.sharedOperatorActionStatusRetryFailed,"Retry dispatched":l.sharedOperatorActionStatusRetryDispatched,"Retry requested":l.sharedOperatorActionStatusRetryRequested,Acknowledged:l.sharedOperatorActionStatusAcknowledged},DS={approve:l.sharedApprovalActionApprove,reroute:l.sharedApprovalActionReroute,reject:l.sharedApprovalActionReject},BS={approve:l.sharedApprovalActionApproveDescription,reroute:l.sharedApprovalActionRerouteDescription,reject:l.sharedApprovalActionRejectDescription};function OS(e,t){const n=LS[e];return n?t(n):e}function _S(e,t){const n=MS[e];return n?t(n):e}function FS(e,t){if(!e)return null;const n="Retry failed: ";if(e.startsWith(n))return t(l.sharedOperatorActionStatusRetryFailedWithError,{error:e.slice(n.length)});const a=ES[e];return a?t(a):e}function WS(e,t,n){const a=DS[e];return a?n(a):t}function KS(e,t,n){const a=BS[e];return a?n(a):t}function US({approvals:e,actorNameById:t,busy:n,onDecision:a}){const{t:s}=Q();return r.jsxs("section",{className:"operatorPanel",children:[r.jsxs("div",{className:"operatorPanelHeader",children:[r.jsxs("div",{children:[r.jsx("p",{className:"operatorEyebrow",children:s("sharedApprovalEyebrow")}),r.jsx("h2",{children:s("sharedApprovalPendingTitle")})]}),r.jsx("span",{className:"operatorCountBadge",children:e.length})]}),e.length===0?r.jsx("p",{className:"operatorEmptyState",children:s("sharedApprovalEmptyState")}):r.jsx("div",{className:"operatorStack",children:e.map(o=>{const i=wh(n,o.taskId),d=o.requestedByActorId?t[o.requestedByActorId]??s("sharedApprovalRequester"):s("sharedApprovalRequester");return r.jsxs("article",{className:"operatorCard approvalCard",children:[r.jsxs("div",{className:"operatorCardHeader",children:[r.jsxs("div",{children:[r.jsx("strong",{children:o.title}),r.jsx("p",{children:o.summary??s("sharedApprovalSummaryFallback")})]}),r.jsx("span",{className:"operatorMetaText",children:Aa(o.requestedAt,s)})]}),r.jsxs("div",{className:"operatorMetaRow",children:[r.jsx("span",{children:s("sharedApprovalRequestedBy",{requestedBy:d})}),o.notes?r.jsx("span",{children:o.notes}):null]}),r.jsx("div",{className:"operatorActionRow",children:o.decisionOptions.map(c=>r.jsx("button",{className:c.action==="approve"?"operatorActionButton operatorActionButtonPrimary":"operatorActionButton",type:"button",disabled:i,title:KS(c.action,c.description,s),onClick:()=>a(o.taskId,c.action),children:WS(c.action,c.label,s)},`${o.id}:${c.action}`))})]},o.id)})})]})}function $S({inspector:e,effectivePolicy:t,incidentActions:n,pendingApprovalCount:a,guardReason:s,cooldownLabel:o,onInspectRun:i,onOperatorAction:d}){const{t:c}=Q();return r.jsxs("section",{className:"operatorPanel",children:[r.jsx("div",{className:"operatorPanelHeader",children:r.jsxs("div",{children:[r.jsx("p",{className:"operatorEyebrow",children:c(l.sharedOperatorEyebrowProgress)}),r.jsx("h2",{children:c(l.sharedOperatorRunStatusTitle)})]})}),e?r.jsx("div",{className:"operatorStack",children:r.jsxs("article",{className:"operatorCard",children:[r.jsxs("div",{className:"operatorCardHeader",children:[r.jsxs("div",{children:[r.jsx("strong",{children:e.run.title}),r.jsx("p",{children:e.run.summary??c(l.sharedOperatorProgressSummaryFallback)})]}),r.jsx("span",{className:`operatorStatusBadge ${gr(Ud(e.run.status))}`,children:So(e.run.status,c)})]}),r.jsxs("div",{className:"operatorMetricGrid",children:[r.jsxs("div",{className:"operatorMetricCard",children:[r.jsx("span",{className:"operatorMetricLabel",children:c(l.sharedOperatorMetricDispatches)}),r.jsx("strong",{children:e.metrics.dispatchCount??"—"})]}),r.jsxs("div",{className:"operatorMetricCard",children:[r.jsx("span",{className:"operatorMetricLabel",children:c(l.sharedOperatorMetricContinuations)}),r.jsx("strong",{children:e.metrics.continuationCount??"—"})]}),r.jsxs("div",{className:"operatorMetricCard",children:[r.jsx("span",{className:"operatorMetricLabel",children:c(l.sharedOperatorMetricTargets)}),r.jsx("strong",{children:e.metrics.targetCount??"—"})]})]}),r.jsxs("div",{className:"operatorMetaRow",children:[r.jsx("span",{children:c(l.sharedOperatorMetaUpdated,{time:Aa(e.run.updatedAt,c)})}),r.jsx("span",{children:a===1?c(l.sharedOperatorApprovalPendingSingular,{count:a}):c(l.sharedOperatorApprovalPendingPlural,{count:a})})]}),e.workflowStageId||e.workflowShape?r.jsxs("div",{className:"operatorMetaRow",children:[e.workflowStageId?r.jsx("span",{children:c(l.sharedOperatorMetaStage,{stage:Hd(e.workflowStageId,c)})}):null,e.workflowShape?r.jsx("span",{children:c(l.sharedOperatorMetaShape,{shape:$d(e.workflowShape,c)})}):null,e.reviewRequired?r.jsx("span",{children:c(l.sharedOperatorMetaReviewRequired)}):null]}):null,t?r.jsxs("div",{className:"operatorMetaRow",children:[t.deliveryMode?r.jsx("span",{children:c(l.sharedOperatorDeliveryLabel,{deliveryMode:PS(t.deliveryMode,c)})}):null,t.deliveryGates.length>0?r.jsx("span",{children:c(l.sharedOperatorGatesLabel,{gates:t.deliveryGates.map(u=>AS(u,c)).join(", ")})}):null,t.budgetAlertLevel?r.jsx("span",{children:c(l.sharedOperatorBudgetLabel,{budgetLevel:RS(t.budgetAlertLevel,c)})}):null]}):null,s?r.jsx("div",{className:"operatorCallout operatorCalloutAttention",children:c(l.sharedOperatorMetaGuardrail,{guardrail:qd(s,c)})}):null,o?r.jsx("div",{className:"operatorCallout operatorCalloutMuted",children:c(l.sharedOperatorMetaCooldown,{cooldown:Gd(o,c)})}):null,r.jsxs("div",{className:"operatorActionRow",children:[r.jsx("button",{className:"operatorActionButton",type:"button",onClick:()=>i(e.run.id),children:c(l.sharedOperatorInspectRunButton)}),n.map(u=>{const h=_S(u.description,c);return r.jsx("button",{className:u.kind==="retry"?"operatorActionButton operatorActionButtonPrimary":"operatorActionButton",type:"button",disabled:u.disabled,title:h,onClick:()=>d({action:u.kind,taskId:u.taskId,runId:u.runId,checkpointId:u.checkpointId,outcomeId:u.outcomeId}),children:OS(u.label,c)},`${u.kind}:${u.runId??u.taskId??u.checkpointId??u.outcomeId??"global"}`)})]}),n.some(u=>u.statusLabel)?r.jsx("div",{className:"operatorMetaRow",children:n.filter(u=>u.statusLabel).map(u=>r.jsx("span",{children:FS(u.statusLabel,c)},`status:${u.kind}`))}):null]})}):r.jsx("p",{className:"operatorEmptyState",children:c(l.sharedOperatorNoActiveRun)})]})}function HS(e){const t=e;return r.jsx($S,{...t})}function qS({traces:e,actorNameById:t}){const{t:n}=Q();return e.length===0?r.jsx("p",{className:"operatorEmptyState operatorInsetEmpty",children:n(l.sharedOperatorNoTraceRecords)}):r.jsx("div",{className:"operatorList",children:e.slice(0,8).map(a=>r.jsxs("article",{className:"operatorListItem",children:[r.jsxs("div",{className:"operatorListItemHeader",children:[r.jsx("strong",{children:hS(a.kind,n)}),r.jsx("span",{children:Aa(a.createdAt,n)})]}),r.jsx("p",{children:a.message}),a.actorId?r.jsx("span",{className:"operatorMetaText",children:t[a.actorId]??a.actorId}):null]},a.id))})}function GS({runs:e,actorNameById:t,inspector:n,onSelectRun:a}){const{t:s}=Q();return r.jsxs("section",{className:"operatorPanel",children:[r.jsx("div",{className:"operatorPanelHeader",children:r.jsxs("div",{children:[r.jsx("p",{className:"operatorEyebrow",children:s(l.sharedOperatorEyebrowInspector)}),r.jsx("h2",{children:s(l.sharedOperatorRunInspectorTitle)})]})}),e.length===0||!n?r.jsx("p",{className:"operatorEmptyState",children:s(l.sharedOperatorRunInspectorNoHistory)}):r.jsxs("div",{className:"operatorStack",children:[r.jsx("div",{className:"operatorRunTabs",children:e.slice(0,6).map(o=>r.jsxs("button",{className:o.id===n.run.id?"operatorRunTab operatorRunTabActive":"operatorRunTab",type:"button",onClick:()=>a(o.id),children:[r.jsx("span",{children:So(o.status,s)}),r.jsx("strong",{children:o.title})]},o.id))}),r.jsxs("article",{className:"operatorCard",children:[r.jsxs("div",{className:"operatorCardHeader",children:[r.jsxs("div",{children:[r.jsx("strong",{children:n.run.title}),r.jsx("p",{children:n.run.summary??s(l.sharedOperatorRunInspectorSummaryFallback)})]}),r.jsx("span",{className:`operatorStatusBadge ${gr(Ud(n.run.status))}`,children:So(n.run.status,s)})]}),r.jsxs("div",{className:"operatorMetaRow",children:[r.jsx("span",{children:s(l.sharedOperatorMetaStarted,{time:Aa(n.run.startedAt??n.run.createdAt,s)})}),r.jsx("span",{children:s(l.sharedOperatorMetaUpdated,{time:Aa(n.run.updatedAt,s)})})]}),n.workflowStageId||n.workflowShape?r.jsxs("div",{className:"operatorMetaRow",children:[n.workflowStageId?r.jsx("span",{children:s(l.sharedOperatorMetaStage,{stage:Hd(n.workflowStageId,s)})}):null,n.workflowShape?r.jsx("span",{children:s(l.sharedOperatorMetaShape,{shape:$d(n.workflowShape,s)})}):null,n.reviewRequired?r.jsx("span",{children:s(l.sharedOperatorMetaReviewRequired)}):null]}):null,n.guardReason?r.jsx("div",{className:"operatorCallout operatorCalloutAttention",children:s(l.sharedOperatorMetaGuardrail,{guardrail:qd(n.guardReason,s)})}):null,n.cooldownLabel?r.jsx("div",{className:"operatorCallout operatorCalloutMuted",children:s(l.sharedOperatorMetaCooldown,{cooldown:Gd(n.cooldownLabel,s)})}):null,r.jsxs("div",{className:"operatorInspectorSection",children:[r.jsx("div",{className:"operatorInspectorHeader",children:r.jsx("strong",{children:s(l.sharedOperatorSectionTrace)})}),r.jsx(qS,{traces:n.traces,actorNameById:t})]}),r.jsxs("div",{className:"operatorInspectorSection",children:[r.jsx("div",{className:"operatorInspectorHeader",children:r.jsx("strong",{children:s(l.sharedOperatorSectionCheckpoints)})}),n.checkpoints.length===0?r.jsx("p",{className:"operatorEmptyState operatorInsetEmpty",children:s(l.sharedOperatorNoCheckpointsRecorded)}):r.jsx("div",{className:"operatorList",children:n.checkpoints.slice(0,4).map(o=>r.jsxs("article",{className:"operatorListItem",children:[r.jsxs("div",{className:"operatorListItemHeader",children:[r.jsx("strong",{children:o.label}),r.jsx("span",{className:`operatorStatusBadge ${gr(dS(o.status))}`,children:cS(o.status,s)})]}),r.jsx("p",{children:o.summary??s(l.sharedOperatorCheckpointSummaryFallback)})]},o.id))})]}),r.jsxs("div",{className:"operatorInspectorSection",children:[r.jsx("div",{className:"operatorInspectorHeader",children:r.jsx("strong",{children:s(l.sharedOperatorSectionBranches)})}),n.branchStates.length===0?r.jsx("p",{className:"operatorEmptyState operatorInsetEmpty",children:s(l.sharedOperatorNoBranchesRecorded)}):r.jsx("div",{className:"operatorList",children:n.branchStates.slice(0,6).map(o=>r.jsxs("article",{className:"operatorListItem",children:[r.jsxs("div",{className:"operatorListItemHeader",children:[r.jsx("strong",{children:o.participantName}),r.jsx("span",{className:"operatorMetaText",children:lS(o.status,s)})]}),r.jsxs("p",{children:[o.handoffReason?`${s(l.sharedOperatorBranchHandoff,{handoffReason:TS(o.handoffReason,s)})} `:"",o.branchStrategy?`${s(l.sharedOperatorBranchStrategy,{strategy:NS(o.branchStrategy,s)})} `:"",o.parentCheckpointId?s(l.sharedOperatorBranchFromCheckpoint,{checkpointId:o.parentCheckpointId}):s(l.sharedOperatorBranchNoLineage)]}),o.error?r.jsx("p",{children:o.error}):null]},o.id))})]}),r.jsxs("div",{className:"operatorInspectorSection",children:[r.jsx("div",{className:"operatorInspectorHeader",children:r.jsx("strong",{children:s(l.sharedOperatorSectionOutcomes)})}),n.outcomes.length===0?r.jsx("p",{className:"operatorEmptyState operatorInsetEmpty",children:s(l.sharedOperatorNoOutcomesRecorded)}):r.jsx("div",{className:"operatorList",children:n.outcomes.slice(0,3).map(o=>r.jsxs("article",{className:"operatorListItem",children:[r.jsxs("div",{className:"operatorListItemHeader",children:[r.jsx("strong",{children:o.title}),r.jsx("span",{className:`operatorStatusBadge ${gr(pS(o.status))}`,children:uS(o.status,s)})]}),r.jsx("p",{children:o.summary??s(l.sharedOperatorOutcomeSummaryFallback)})]},o.id))})]})]})]})]})}function VS({runs:e,actorNameById:t,inspector:n,onSelectRun:a}){const s={runs:e,actorNameById:t,inspector:n,onSelectRun:a};return r.jsx(GS,{...s})}function yo({cats:e,bossCatId:t,selectedIds:n,highlightedId:a,defaultRecipientCatId:s,toggleable:o,showLeadBadge:i,onToggle:d,onHighlight:c}){const u=kh(e,{bossCatIds:t});if(u.length===0)return null;const h=new Set(n);return r.jsx("div",{className:"catAvatarRow",children:u.map(f=>{const m=h.has(f.id),v=f.id===a,C=f.id===t,S=f.id===s,y=["catAvatar","catAvatarRowItem",C?"catAvatarBoss":"",m?"catAvatarRowItemSelected":"",v?"catAvatarRowItemHighlighted":""].filter(Boolean).join(" ");return r.jsxs("div",{role:"button",tabIndex:0,className:y,style:f.avatarUrl?{backgroundImage:`url(${f.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:f.avatarColor?{background:f.avatarColor}:void 0,"data-tooltip":Ph(f.name,oa(f)),onClick:()=>{o&&d(f.id),!o&&m&&c(f.id)},children:[f.avatarUrl?null:At(f.name),i&&S?r.jsx("span",{className:"catAvatarLeadBadge",children:"★"}):null]},f.id)})})}function zS({assignedCatRecords:e,assignedAdhocParticipants:t,bossCatId:n,defaultRecipientCatId:a,editingParticipantId:s,editingParticipantName:o,busy:i,canRenameParticipants:d,showAddCatButton:c,onEditingParticipantNameChange:u,onBeginParticipantRename:h,onCancelParticipantRename:f,onSubmitParticipantRename:m,onOpenAddCat:v,onCloseSidePanel:C}){const{t:S}=Q(),y=g=>Ah(i,g);return r.jsxs("div",{className:"sidePanelSectionStack",children:[e.length>0?r.jsx(yo,{cats:e,bossCatId:n,selectedIds:e.map(g=>g.id),highlightedId:a,defaultRecipientCatId:a,toggleable:!1,showLeadBadge:!0,onToggle:()=>{},onHighlight:()=>{}}):null,t.length>0?r.jsx("div",{className:"sidePanelParticipantList",children:t.map(g=>r.jsxs("div",{className:"addCatItem",children:[r.jsxs("div",{children:[r.jsx("strong",{children:g.name}),r.jsx("p",{children:Zr(g.execution.target)}),g.roleHint?r.jsx("p",{children:g.roleHint}):null,s===g.participantId?r.jsxs("form",{style:{display:"grid",gap:8,marginTop:8},onSubmit:x=>{x.preventDefault(),m(g.participantId)},children:[r.jsxs("label",{style:{display:"grid",gap:4,fontSize:"0.8rem"},children:[r.jsx("span",{children:S(l.chatParticipantsSectionNameLabel)}),r.jsx("input",{className:"chromeInput",value:o,onChange:x=>u(x.target.value),disabled:y(g.participantId)})]}),r.jsxs("div",{style:{display:"flex",gap:8,flexWrap:"wrap"},children:[r.jsx("button",{type:"submit",className:"addCatAssignButton",disabled:!o.trim()||y(g.participantId),children:S(l.chatParticipantsSectionSaveNameButton)}),r.jsx("button",{type:"button",className:"addCatAssignButton",onClick:f,disabled:y(g.participantId),children:S(l.chatParticipantsSectionCancelButton)})]})]}):null]}),r.jsx("div",{style:{display:"flex",gap:8,alignItems:"center"},children:d?r.jsx("button",{type:"button",className:"addCatAssignButton",disabled:y(g.participantId),onClick:()=>h(g),children:S(l.chatParticipantsSectionRenameButton)}):null})]},g.participantId))}):null,e.length===0&&t.length===0?r.jsx("p",{className:"operatorEmptyState",children:S(l.chatParticipantsSectionNoParticipants)}):null,c?r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>{C(),v?.()},children:S(l.chatParticipantsSectionChooseCatsButton)}):null]})}function YS({payload:e,selectedChannel:t,busy:n,operatorView:a,operatorLoading:s,operatorError:o,assignedCatRecords:i,assignedAdhocParticipants:d,defaultRecipientCatId:c,defaultRecipientParticipant:u,directLaneCat:h,directLaneExecutionTarget:f,isDirectLane:m,isDefaultChatComposer:v,selectedExecutionTarget:C,inspectedRun:S,showAddCatButton:y,editingParticipantId:g,editingParticipantName:x,canRenameParticipants:I,onEditingParticipantNameChange:k,onBeginParticipantRename:P,onCancelParticipantRename:A,onSubmitParticipantRename:M,onOpenAddCat:D,onCloseSidePanel:N,onInspectRun:R,onApprovalDecision:w,onOperatorAction:b,onExecutionTargetChange:T,onStartFresh:E,onDirectLaneExecutionTargetChange:O,onDirectLaneParticipantTargetChange:H,buildParticipantAvatarStyle:U}){const{t:L}=Q(),$=[],X=oo(n,"reset");(y||i.length>0||d.length>0)&&$.push({id:"cats",title:d.length>0?L(l.chatNewChatDraftSidePanelParticipantsGroupTitle):L(l.chatNewChatDraftSidePanelParticipantsCatsTitle),children:r.jsx(zS,{assignedCatRecords:i,assignedAdhocParticipants:d,bossCatId:e.chat.bossCatId,defaultRecipientCatId:c,editingParticipantId:g,editingParticipantName:x,busy:n,canRenameParticipants:I,showAddCatButton:y,onEditingParticipantNameChange:k,onBeginParticipantRename:P,onCancelParticipantRename:A,onSubmitParticipantRename:M,onOpenAddCat:D,onCloseSidePanel:N})});const ke=(()=>{if(m&&h&&f){const B=so(h.mcpProfile),ae=u?{provider:u.execution.target.provider,instance:u.execution.target.instance??null,model:u.execution.target.model??null,modelSelection:u.execution.modelSelection??null}:f;return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"sidePanelSectionStack",children:[r.jsxs("div",{className:"catInspectIdentity",children:[r.jsx("div",{className:h.id===e.chat.bossCatId?"catAvatar catAvatarBoss catInspectAvatar":"catAvatar catInspectAvatar",style:h.avatarUrl?{backgroundImage:`url(${h.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:h.avatarColor?{background:h.avatarColor}:void 0,children:h.avatarUrl?null:At(h.name)}),r.jsxs("div",{children:[r.jsx("strong",{children:h.name}),h.id===e.chat.bossCatId?r.jsx("span",{className:"catInspectBadge",children:L(l.sharedCatInspectBossLabel)}):null]})]}),r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.sharedSettingsCatsMcpProfileLabel)}),r.jsx("span",{children:B?L(B):h.mcpProfile})]})]}),r.jsx(na,{provider:ae.provider,instance:ae.instance??"",model:ae.model??"",modelSelection:ae.modelSelection,onTargetChange:he=>{const Y=wa(he);if(u&&H){H(u.participantId,Y);return}O?.(h.id,Y)}})]})}if(v&&C&&T)return r.jsxs(r.Fragment,{children:[r.jsx(na,{provider:C.provider,instance:C.instance??"",model:C.model??"",modelSelection:C.modelSelection,onTargetChange:B=>{T(wa(B))}}),E?r.jsxs("div",{className:"sidePanelSectionStack",children:[r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>{E()},disabled:X,children:L(X?l.chatSidePanelStartingFreshBusy:l.chatSidePanelStartFresh)}),r.jsx("p",{className:"operatorEmptyState",children:L(l.chatSidePanelStartFreshHint)})]}):null]});if(!v&&u){const B=Ng({provider:u.execution.target.provider,instance:u.execution.target.instance??null,model:u.execution.target.model??null,modelSelection:u.execution.modelSelection??null});if(u.sourceKind!=="cat")return r.jsxs("div",{className:"catInspectPanelBody",children:[r.jsxs("div",{className:"catInspectIdentity",children:[r.jsx("div",{className:"catAvatar catInspectAvatar channelParticipantAvatar",style:U(u),children:u.avatarUrl?null:At(u.name)}),r.jsxs("div",{children:[r.jsx("strong",{children:u.name}),r.jsx("span",{className:"catInspectBadge",children:L(l.chatSidePanelTemporaryParticipantLabel)})]})]}),u.roleHint?r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.chatSidePanelRoleLabel)}),r.jsx("span",{children:u.roleHint})]}):null,r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.chatSidePanelAiServiceLabel)}),r.jsx("span",{children:B.providerLabel})]}),B.instanceLabel?r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.chatSidePanelConnectionLabel)}),r.jsx("span",{children:B.instanceLabel})]}):null,r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.sharedCatInspectModelLabel)}),r.jsx("span",{children:B.modelLabel})]})]});const ae=is(u),he=ae?e.chat.cats.find(G=>G.id===ae)??null:null,Y=so(he?.mcpProfile);return r.jsxs("div",{className:"catInspectPanelBody",children:[r.jsxs("div",{className:"catInspectIdentity",children:[r.jsx("div",{className:ae===e.chat.bossCatId?"catAvatar catAvatarBoss catInspectAvatar":"catAvatar catInspectAvatar",style:he?.avatarUrl?{backgroundImage:`url(${he.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:u.avatarColor?{background:u.avatarColor}:void 0,children:he?.avatarUrl?null:At(u.name)}),r.jsxs("div",{children:[r.jsx("strong",{children:u.name}),ae===e.chat.bossCatId?r.jsx("span",{className:"catInspectBadge",children:L(l.sharedCatInspectBossLabel)}):null]})]}),r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.chatSidePanelAiServiceLabel)}),r.jsx("span",{children:B.providerLabel})]}),B.instanceLabel?r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.chatSidePanelConnectionLabel)}),r.jsx("span",{children:B.instanceLabel})]}):null,r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.sharedCatInspectModelLabel)}),r.jsx("span",{children:B.modelLabel})]}),r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:L(l.sharedSettingsCatsMcpProfileLabel)}),r.jsx("span",{children:Y?L(Y):he?.mcpProfile})]})]})}return r.jsx("p",{className:"operatorEmptyState",children:L(l.chatNewChatDraftSidePanelExecutionEmptyState)})})();$.push({id:"execution",title:L(l.chatNewChatDraftSidePanelExecutionTitle),children:ke});const z=t.repoPath??t.chatCwd;return $.push({id:"cwd",title:L(l.chatNewChatDraftSidePanelFolderTitle),children:z?r.jsxs("div",{style:{display:"grid",gap:8},children:[r.jsx("p",{style:{margin:0,fontSize:"0.85rem",wordBreak:"break-all"},children:z}),r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>{of(z)},children:L(l.chatNewChatDraftFolderActionLabel)})]}):r.jsx("p",{className:"operatorEmptyState",children:L(l.chatNewChatDraftSidePanelFolderEmptyState)})}),$.push({id:"operator",title:L(l.chatSidePanelRunStatusTitle),badge:a?.approvals.length??0,children:r.jsxs(r.Fragment,{children:[o?r.jsxs("section",{className:"operatorPanel operatorPanelError",children:[r.jsx("div",{className:"operatorPanelHeader",children:r.jsxs("div",{children:[r.jsx("p",{className:"operatorEyebrow",children:L(l.chatSidePanelRunStatusTitle)}),r.jsx("h2",{children:L(l.chatSidePanelRunStatusUnavailableTitle)})]})}),r.jsx("p",{className:"operatorEmptyState",children:o})]}):null,s&&!a?r.jsxs("section",{className:"operatorPanel",children:[r.jsx("div",{className:"operatorPanelHeader",children:r.jsxs("div",{children:[r.jsx("p",{className:"operatorEyebrow",children:L(l.chatSidePanelRunStatusTitle)}),r.jsx("h2",{children:L(l.chatSidePanelLoadingTitle)})]})}),r.jsx("p",{className:"operatorEmptyState",children:L(l.chatSidePanelOperatorLoadingState)})]}):null,r.jsx(US,{approvals:a?.approvals??[],actorNameById:a?.actorNameById??{},busy:n,onDecision:w}),r.jsx(HS,{inspector:S,effectivePolicy:a?.effectivePolicy??null,incidentActions:S?.incidentActions??a?.incidentActions??[],pendingApprovalCount:a?.approvals.length??0,guardReason:S?.guardReason??a?.guardReason??null,cooldownLabel:S?.cooldownLabel??a?.cooldownLabel??null,onInspectRun:R,onOperatorAction:b}),r.jsx(jS,{items:a?.activityFeed??[]}),r.jsx(VS,{runs:a?.runs??[],actorNameById:a?.actorNameById??{},inspector:S,onSelectRun:R})]})}),$}const JS=new Set(["cancelled","aborted"]);function QS(){const e=Eo();return!e?.startVoiceCapture||!e.stopVoiceCapture||!e.cancelVoiceCapture||!e.onVoiceCaptureEvent?null:{startVoiceCapture:e.startVoiceCapture,stopVoiceCapture:e.stopVoiceCapture,cancelVoiceCapture:e.cancelVoiceCapture,onVoiceCaptureEvent:e.onVoiceCaptureEvent}}function XS(){return globalThis.crypto?.randomUUID?.()??`voice-${Date.now()}-${Math.random().toString(36).slice(2)}`}function ZS({onTranscript:e,onError:t,lang:n}){const a=p.useMemo(()=>QS(),[]),[s,o]=p.useState("idle"),[i,d]=p.useState(null),c=p.useRef(null),u=p.useRef(e);u.current=e;const h=p.useRef(t);h.current=t;const f=p.useCallback(y=>{c.current===y&&(c.current=null,o("idle"),d(null))},[]);p.useEffect(()=>{if(a)return a.onVoiceCaptureEvent(y=>{if(y.sessionId===c.current)switch(y.type){case"ready":o("ready"),d(y.mode);break;case"partial":break;case"final":u.current(y.text);break;case"error":JS.has(y.reason)||h.current?.(y.reason),f(y.sessionId);break;case"end":f(y.sessionId);break}})},[a,f]);const m=p.useCallback(y=>{const g=c.current;!a||!g||(c.current=null,y&&(o("idle"),d(null)),a.cancelVoiceCapture(g).catch(()=>{}))},[a]),v=p.useCallback(()=>{if(!a||c.current)return;const y=XS();c.current=y,o("starting"),d(null),a.startVoiceCapture({sessionId:y,locale:n}).catch(()=>{c.current===y&&(c.current=null,o("idle"),d(null),h.current?.("engine_unavailable"))})},[a,n]),C=p.useCallback(()=>{const y=c.current;!a||!y||a.stopVoiceCapture(y).catch(()=>{c.current===y&&(c.current=null,o("idle"),d(null),h.current?.("engine_unavailable"))})},[a]),S=p.useCallback(()=>{m(!0)},[m]);return p.useEffect(()=>()=>{m(!1)},[m]),{supported:a!==null,active:s!=="idle",listening:s==="ready",privacyMode:i,start:v,stop:C,cancel:S}}const ey=new Set(["no-speech","aborted"]);function Al(){if(typeof window>"u")return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}function ty({onTranscript:e,onError:t,lang:n}){const[a]=p.useState(()=>Al()!==null),[s,o]=p.useState(!1),i=p.useRef(null),d=p.useRef(0),c=p.useRef(e);c.current=e;const u=p.useRef(t);u.current=t;const h=p.useCallback(()=>{const C=i.current;if(C)try{C.stop()}catch{}},[]),f=p.useCallback(C=>{const S=i.current;if(S){d.current+=1,i.current=null,C&&o(!1);try{S.abort()}catch{}}},[]),m=p.useCallback(()=>{f(!0)},[f]),v=p.useCallback(()=>{if(i.current)return;const C=Al();if(!C)return;const S=new C,y=d.current+1;d.current=y;const g=()=>i.current===S&&d.current===y;S.continuous=!0,S.interimResults=!1,n&&(S.lang=n),S.onresult=x=>{if(!g())return;let I="";for(let k=x.resultIndex;k<x.results.length;k+=1){const P=x.results[k];P?.isFinal&&(I+=P[0]?.transcript??"")}I&&c.current(I)},S.onerror=x=>{if(!g())return;const I=x?.error;I&&(console.warn(`[useWebSpeechInput] recognition error: ${I}`),ey.has(I)||u.current?.(I)),o(!1),i.current=null},S.onend=()=>{g()&&(o(!1),i.current=null)},i.current=S;try{S.start(),o(!0)}catch{i.current=null,o(!1)}},[n]);return p.useEffect(()=>()=>{f(!1)},[f]),{supported:a,listening:s,start:v,stop:h,cancel:m}}const ny={"not-allowed":l.sharedVoiceInputErrorNotAllowed,"service-not-allowed":l.sharedVoiceInputErrorServiceNotAllowed,"audio-capture":l.sharedVoiceInputErrorAudioCapture,network:l.sharedVoiceInputErrorNetwork,"language-not-supported":l.sharedVoiceInputErrorLanguageNotSupported,permission_denied:l.sharedVoiceInputErrorPermissionDenied,permission_not_determined:l.sharedVoiceInputErrorPermissionNotDetermined,mic_unavailable:l.sharedVoiceInputErrorMicUnavailable,language_not_supported:l.sharedVoiceInputErrorLanguageNotSupported,engine_unavailable:l.sharedVoiceInputErrorEngineUnavailable,helper_crashed:l.sharedVoiceInputErrorHelperCrashed};function ay(e,t){const n=ny[e];return n?t(n):t(l.sharedVoiceInputFailedWithKind,{kind:e})}function ry(e,t){return e==="unknown"?t(l.sharedVoiceInputPrivacyUnknown):e==="cloud"?t(l.sharedVoiceInputPrivacyCloud):null}function Vd({value:e,onChange:t,autoResize:n,disabled:a,lang:s}){const{t:o}=Q(),i=p.useRef(null),d=p.useRef(e);d.current=e;const c=p.useRef(!1),u=p.useRef(null);p.useEffect(()=>{const R=i.current;if(!R)return;const w=()=>{c.current=!0,u.current=d.current},b=()=>{c.current=!0,u.current=R.value};return R.addEventListener("focus",w),R.addEventListener("pointerdown",w),R.addEventListener("keydown",w),R.addEventListener("input",b),()=>{R.removeEventListener("focus",w),R.removeEventListener("pointerdown",w),R.removeEventListener("keydown",w),R.removeEventListener("input",b)}},[]),p.useEffect(()=>{u.current===null||u.current===e||(c.current=!1,u.current=null)},[e]);const h=p.useCallback(R=>{const w=R.trim();if(!w)return;const b=d.current,T=i.current,E=!!T&&(typeof document<"u"&&document.activeElement===T?!0:c.current&&u.current===b);let O,H;if(E&&T){const U=T.selectionStart??b.length,L=T.selectionEnd??b.length,$=b.slice(0,U),X=b.slice(L),ke=$.length>0&&!/\s$/.test($),z=X.length>0&&!/^\s/.test(X),B=`${ke?" ":""}${w}${z?" ":""}`;O=`${$}${B}${X}`,H=$.length+B.length-(z?1:0)}else{const U=b&&!/\s$/.test(b)?" ":"";O=`${b}${U}${w}`,H=O.length}c.current=!0,u.current=O,t(O),requestAnimationFrame(()=>{const U=i.current;if(U){n(U);try{U.setSelectionRange(H,H)}catch{}}})},[t,n]),{toasts:f,showToast:m}=lc(),v=p.useCallback(R=>{m(ay(R,o))},[m,o]),C=ZS({onTranscript:h,onError:v,lang:s}),S=ty({onTranscript:h,onError:v,lang:s}),y=C.supported?C:S,g=C.supported?C.active:S.listening,{supported:x,listening:I,start:k,stop:P,cancel:A}=y,M=p.useCallback(()=>{g?P():k()},[g,k,P]);p.useEffect(()=>{a&&g&&A()},[a,g,A]),p.useEffect(()=>{const R=i.current;if(!R)return;const w=b=>{b.key!=="Escape"||!g||(b.preventDefault(),A())};return R.addEventListener("keydown",w),()=>{R.removeEventListener("keydown",w)}},[g,A]);const D=C.supported?C.privacyMode:null,N=ry(D,o);return{supported:x,listening:I,toggle:M,textareaRef:i,toasts:f,privacyMode:D,privacyMessage:N}}const Rl=new RegExp("(?<!\\w)@([\\p{L}\\p{N}._-]+)","gu");function sy(e){return new Set(Array.from(e?.excludedNames??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function zd(e,t){const n=new Set,a=[],s=[],o=sy(t),i=new RegExp(Rl.source,Rl.flags);let d;for(;(d=i.exec(e))!==null;){const c=d[1];o.has(c.toLowerCase())||(s.push({name:c,start:d.index,end:d.index+d[0].length}),n.has(c)||(n.add(c),a.push(c)))}return{names:a,positions:s}}const oy="composerInput composerHighlight";function iy(e,t,n=[]){const a=new Map(t.map(c=>[c.name.toLowerCase(),c])),o=zd(e,{excludedNames:n}).positions.flatMap(c=>{const u=a.get(c.name.toLowerCase());return u?[{...c,avatarColor:u.avatarColor??null}]:[]});if(o.length===0)return[{kind:"text",value:e}];const i=[];let d=0;for(const c of o)c.start>d&&i.push({kind:"text",value:e.slice(d,c.start)}),i.push({kind:"mention",value:e.slice(c.start,c.end),avatarColor:c.avatarColor}),d=c.end;return d<e.length&&i.push({kind:"text",value:e.slice(d)}),i}function ly(e){if(e)return{background:e,boxShadow:`0 0 0 0.16em ${e}`}}function cy({text:e,cats:t,excludedMentionNames:n=[]}){const a=p.useMemo(()=>iy(e,t,n),[n,e,t]);return r.jsxs("div",{className:oy,"aria-hidden":"true",children:[a.map((s,o)=>s.kind==="mention"?r.jsx("span",{className:"composerHighlightMention",style:ly(s.avatarColor),children:s.value},o):r.jsx("span",{children:s.value},o))," "]})}function dy(e){return!!(e.avatarUrl||e.avatarColor||e.isCat||e.participantId)}function uy(e){return!!(e.avatarUrl||e.avatarColor||e.isCat)}function ka({audienceParticipants:e,allParticipants:t=[],onSetAudienceKeys:n,onSingleClick:a,disabled:s,maxSelectedParticipants:o,workflowShape:i="sequential",onToggleWorkflowShape:d}){const{t:c}=Q(),u=e.length>1,h=!!n&&t.length>1,[f,m]=p.useState(!1),v=p.useRef(null),[C,S]=p.useState(null),[y,g]=p.useState(null),x=new Set(e.map(L=>L.key)),I=Number.isFinite(o)?Math.max(1,Math.trunc(o??Number.POSITIVE_INFINITY)):Number.POSITIVE_INFINITY,k=h?[...e,...t.filter(L=>!x.has(L.key))]:[];p.useEffect(()=>{if(!f)return;function L($){v.current&&!v.current.contains($.target)&&m(!1)}return document.addEventListener("mousedown",L),()=>document.removeEventListener("mousedown",L)},[f]);const P=e[0],A=e.length-1,M=p.useCallback(L=>{if(n)if(x.has(L)){if(e.length<=1)return;n(e.filter($=>$.key!==L).map($=>$.key))}else{if(e.length>=I)return;n([...e.map($=>$.key),L])}},[e,x,I,n]),D=p.useCallback((L,$)=>{S($),L.dataTransfer.effectAllowed="move",L.dataTransfer.setData("text/plain",String($))},[]),N=p.useCallback((L,$)=>{L.preventDefault(),L.dataTransfer.dropEffect="move",g($)},[]),R=p.useCallback((L,$)=>{L.preventDefault();const X=C;if(S(null),g(null),!n||X===null||X===$)return;const ke=e[X]?.key;if(!ke)return;const z=[...e.map(B=>B.key)];z.splice(X,1),z.splice($,0,ke),n(z)},[C,e,n]),w=p.useCallback(()=>{S(null),g(null)},[]);if(!P)return null;const b=u?dy(P):uy(P),T=u?`${P.name} +${A}`:P.isCat?P.name:P.executionLabel||P.name,E=P.isCat&&P.executionLabel?`${P.name} · ${P.executionLabel}`:P.executionLabel||P.name,O=u?c(l.sharedAudienceSelectAudienceLabel):E,H=c(i==="sequential"?l.sharedAudienceSwitchToConcurrentModeLabel:l.sharedAudienceSwitchToSequentialModeLabel),U=()=>{h?m(!f):a&&a()};return r.jsxs("div",{className:"audienceChipWrapper",ref:v,children:[r.jsxs("button",{type:"button",className:"audienceChip",disabled:s,onClick:U,"data-tooltip":O,children:[b?r.jsx("div",{className:"audienceChipAvatar",style:P.avatarUrl?{backgroundImage:`url(${P.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:P.isCat?{background:P.avatarColor??"#8B7E74"}:{background:"#fff",color:"#222",border:"1px solid rgba(0, 0, 0, 0.15)"},children:P.avatarUrl?null:At(P.name)}):null,r.jsx("span",{className:"audienceChipLabel",children:T}),r.jsx("svg",{className:"audienceChipChevron",width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2.5 4 5 6.5 7.5 4"})}),u&&d?r.jsx("span",{className:"audienceChipWorkflow",role:"button",tabIndex:s?-1:0,"data-tooltip":c(i==="sequential"?l.sharedAudienceWorkflowSequential:l.sharedAudienceWorkflowConcurrent),"aria-label":H,onClick:L=>{L.stopPropagation(),d()},children:i==="sequential"?r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M3 4h8L3 12h9"}),r.jsx("path",{d:"M10.5 10.5L12 12l-1.5 1.5"})]}):r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M3 5h8"}),r.jsx("path",{d:"M9 3.5L11 5 9 6.5"}),r.jsx("path",{d:"M3 11h8"}),r.jsx("path",{d:"M9 9.5L11 11 9 12.5"})]})}):null]}),f&&h?r.jsxs("div",{className:"audiencePopover",children:[r.jsx("div",{className:"audiencePopoverHeader",children:c(l.sharedAudiencePopoverHeader)}),k.map(L=>{const $=x.has(L.key),X=$?e.findIndex(B=>B.key===L.key):-1,ke=C===X,z=y===X;return r.jsxs("div",{className:`audiencePopoverItem${ke?" isDragging":""}${z?" isDragOver":""}`,"data-tooltip":L.isCat&&L.executionLabel?`${L.name} · ${L.executionLabel}`:L.executionLabel||void 0,draggable:$,onDragStart:$?B=>D(B,X):void 0,onDragOver:$?B=>N(B,X):void 0,onDrop:$?B=>R(B,X):void 0,onDragEnd:w,children:[$?r.jsx("span",{className:"audiencePopoverDragHandle","aria-hidden":"true",children:"⋮⋮"}):r.jsx("span",{className:"audiencePopoverDragHandle audiencePopoverDragHandlePlaceholder","aria-hidden":"true"}),r.jsx("div",{className:"audiencePopoverAvatar",style:L.avatarUrl?{backgroundImage:`url(${L.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:L.isCat?{background:L.avatarColor??"#8B7E74"}:{background:"#fff",color:"#222",border:"1px solid rgba(0, 0, 0, 0.15)"},children:L.avatarUrl?null:At(L.name)}),r.jsx("span",{className:"audiencePopoverName",children:L.name}),r.jsx("label",{className:"audiencePopoverCheck",children:r.jsx("input",{type:"checkbox",checked:$,disabled:$&&e.length<=1||!$&&e.length>=I,onChange:()=>M(L.key)})})]},L.key)})]}):null]})}function si(e){return{key:`cat:${e.id}`,name:e.name,executionLabel:e.defaultExecutionTarget?oa(e):null,avatarColor:e.avatarColor??null,avatarUrl:e.avatarUrl??null,isCat:!0,catId:e.id,participantId:null}}function Yd(e){return{key:`temp:${e.participantId}`,name:e.name,executionLabel:e.provider?wr({provider:e.provider,instance:e.instance??null,model:e.model??null,modelSelection:e.modelSelection??null}):null,avatarColor:null,avatarUrl:null,isCat:!1,catId:null,participantId:e.participantId}}function zr(e,t){const n=Jo(e);return{key:t??"implicit:execution_target",name:n,executionLabel:n,avatarColor:null,avatarUrl:null,isCat:!1,catId:null,participantId:null}}function py(e){const t=e.provider?wr({provider:e.provider,instance:e.instance??null,model:e.model??null,modelSelection:e.modelSelection??null,executionLabel:e.executionLabel??null}):e.executionLabel?.trim()||null;return{key:e.catId??e.participantId??`recipient:${e.name}`,name:e.name,executionLabel:t,avatarColor:e.avatarColor??null,avatarUrl:e.avatarUrl??null,isCat:!!e.catId,catId:e.catId??null,participantId:e.participantId??null}}function hy(e){return{key:`participant:${e.participantId}`,name:e.label,executionLabel:e.executionLabel,avatarColor:e.avatarColor??null,avatarUrl:e.avatarUrl??null,isCat:!e.useNeutralAvatar,catId:null,participantId:e.participantId}}function fy({composerStackParticipants:e,composerBusy:t,activeWorkflowShape:n,onToggleActiveWorkflowShape:a,activeAudienceKeys:s,onSetActiveAudienceKeys:o,maxAudienceParticipants:i,onOpenSection:d}){const c=p.useMemo(()=>e.map(hy),[e]),u=p.useMemo(()=>{if(!s||s.length===0)return c;const h=new Map(c.map(m=>[m.key,m])),f=s.map(m=>h.get(m)).filter(Boolean);return f.length>0?f:c.length>0?[c[0]]:[]},[s,c]);return r.jsx(ka,{audienceParticipants:u,allParticipants:c,onSetAudienceKeys:o,onSingleClick:()=>d("execution"),disabled:t,maxSelectedParticipants:i,workflowShape:n,onToggleWorkflowShape:a})}function Jd({payload:e,composerBusy:t,composerRecipients:n,composerStackParticipants:a,directLaneCat:s,isDirectLane:o,isDefaultChatComposer:i,activeWorkflowShape:d,onToggleActiveWorkflowShape:c,activeAudienceKeys:u,onSetActiveAudienceKeys:h,onOpenSection:f}){if(s)return r.jsx(ka,{audienceParticipants:[si(s)],onSingleClick:()=>f("execution"),disabled:t});if(!i&&a.length>0)return r.jsx(fy,{composerStackParticipants:a,composerBusy:t,activeWorkflowShape:d,onToggleActiveWorkflowShape:c,activeAudienceKeys:u,onSetActiveAudienceKeys:h,maxAudienceParticipants:e.chat.capabilities.maxAudienceParticipants,onOpenSection:f});const m=n.length===1&&n[0]?.kind==="implicit"?n[0]:null;if(m)return r.jsx(ka,{audienceParticipants:[zr({provider:m.provider??"",instance:m.instance??null,model:m.model??null,modelSelection:m.modelSelection??null,executionLabel:m.executionLabel??m.name})],onSingleClick:()=>f("execution"),disabled:t});if(n.length>0){const v=n.map(py);return r.jsx(ka,{audienceParticipants:v,onSingleClick:()=>f(o||i?"execution":"cats"),disabled:t})}return null}function my({hasConversationStarted:e,isCompareGroup:t,isNearBottom:n,payload:a,composerDraft:s,channelFiles:o,channelPlusMenuOpen:i,channelPlusMenuRef:d,channelFileInputRef:c,composerBusy:u,compareBusy:h,stopBusy:f,composerWorkspacePath:m,directLaneExcludedMentionNames:v,composerRecipients:C,defaultRecipientParticipantId:S,composerStackParticipants:y,isDirectLane:g,isDefaultChatComposer:x,activeWorkflowShape:I,onToggleActiveWorkflowShape:k,activeAudienceKeys:P,onSetActiveAudienceKeys:A,compareSendScope:M,showCancelComposerAction:D,showStopComposerAction:N,composerCardRef:R,composerTargetSlot:w,composerHeaderAccessory:b,composerHeaderWhereExtras:T,composerFooterAccessory:E,surfaceTag:O,onOpenSection:H,onComposerChange:U,onComposerKeyDown:L,onSendMessage:$,onToggleChannelPlusMenu:X,onChannelFileSelect:ke,onTakeScreenshot:z,screenshotCaptureDisabled:B=!1,onChannelFilesChange:ae,onScrollToBottom:he,onCompareSendScopeChange:Y,onCancelPendingSend:G,onStopMessage:W,autoResize:ue}){const pe=g&&C.length===1&&C[0]?.kind==="named"?C[0]:null,We=pe?.catId?a.chat.cats.find(fe=>fe.id===pe.catId)??null:null,Z=s.trim().length>0||o.length>0,{supported:Ke,listening:et,toggle:V,textareaRef:re,toasts:ne,privacyMessage:Oe}=Vd({value:s,onChange:U,autoResize:ue,disabled:u}),tt=(()=>{const fe=["composerAreaStack"];return e?(fe.push("composerAreaStackDocked"),t&&fe.push("composerAreaStackDockedParallel")):fe.push("composerAreaStackFresh"),i&&fe.push("composerAreaStackMenuOpen"),fe.join(" ")})(),{t:Ne}=Q(),Ot=Ne(h?l.chatComposerAreaPlaceholderParallelWaiting:e?l.chatComposerAreaPlaceholderReply:l.chatNewChatDraftComposerPlaceholder),Yt=et?Ne(l.chatNewChatDraftStopVoiceInputAria,{privacyMessageSuffix:Oe??""}):Ne(l.chatNewChatDraftStartVoiceInputAria),_t=Ne(M==="all_members"?l.chatNewChatDraftSendAllChatsAria:l.chatComposerAreaSendToThisChatAria),nt=Ne(l.chatComposerAreaStopButtonLabel),Ue=Ne(l.chatComposerAreaSwitchSendModeLabel);return r.jsxs("div",{className:tt,children:[O||m||b||T?r.jsxs("div",{className:"composerHeaderRow",children:[r.jsxs("div",{className:"composerHeaderLeft",children:[O,m?r.jsxs("span",{className:"composerCwdChip composerCwdClickable","data-tooltip":m,role:"button",tabIndex:0,onClick:()=>H("cwd"),children:[r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2 4v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H8L6.5 3H3a1 1 0 0 0-1 1z"})}),r.jsx("span",{children:io(m)})]}):null,T]}),b?r.jsx("div",{className:"composerHeaderRight",children:b}):null]}):null,r.jsxs("form",{ref:R,className:`${e?t?"composerCard composerCardDocked composerCardDockedParallel":"composerCard composerCardDocked":"composerCard composerCardFresh"}${i?" composerCardMenuOpen":""}`,onSubmit:fe=>{$(fe)},children:[e&&!n?r.jsx("button",{className:"scrollToBottomButton",type:"button","aria-label":Ne(l.chatComposerAreaScrollToLatestAria),onClick:he,children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 3v10"}),r.jsx("path",{d:"M3 9l5 5 5-5"})]})}):null,o.length>0?r.jsx("div",{className:"composerAttachments",children:o.map((fe,Le)=>{const Te=fe.type.startsWith("image/");return r.jsxs("div",{className:"attachmentCard",children:[r.jsx("button",{className:"attachmentRemove",type:"button",disabled:u,onClick:()=>ae(o.filter((ye,Ce)=>Ce!==Le)),"aria-label":Ne(l.chatNewChatDraftAttachmentRemoveAria,{fileName:fe.name}),children:"×"}),Te?r.jsx("img",{className:"attachmentPreview",src:URL.createObjectURL(fe),alt:fe.name,onLoad:ye=>URL.revokeObjectURL(ye.target.src)}):r.jsx("div",{className:"attachmentFileIcon",children:r.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("path",{d:"M14 2v6h6"})]})}),r.jsx("span",{className:"attachmentName",children:fe.name})]},`${fe.name}-${fe.size}-${Le}`)})}):null,r.jsxs("div",{className:"composerInputWrapper",children:[r.jsx(cy,{text:s,cats:a.chat.cats,excludedMentionNames:v}),r.jsx("textarea",{ref:re,className:"composerInput composerInputOverlay",rows:1,placeholder:Ot,value:s,disabled:u,onChange:fe=>{U(fe.target.value),ue(fe.target)},onKeyDown:fe=>{L(fe)}})]}),r.jsxs("div",{className:"composerBottomRow",children:[r.jsx("div",{className:"composerLeftGroup",children:r.jsxs("div",{className:"composerPlusWrapper",ref:d,children:[r.jsx("button",{className:"composerPlusButton",type:"button","aria-label":Ne(l.chatComposerAreaAttachAria),disabled:u,onClick:X,children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 3v10"}),r.jsx("path",{d:"M3 8h10"})]})}),i?r.jsxs("div",{className:"composerPlusMenu",children:[r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:u,onClick:ke,children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M14 10v3a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-3"}),r.jsx("path",{d:"M8 2v8"}),r.jsx("path",{d:"M4 6l4-4 4 4"})]}),Ne(l.chatNewChatDraftAddPhotosAndFiles)]}),z?r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:u||B,onClick:z,children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M5 3.5l1-1h4l1 1h2a1 1 0 0 1 1 1v7.5a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4.5a1 1 0 0 1 1-1h2z"}),r.jsx("circle",{cx:"8",cy:"8.5",r:"2.5"})]}),Ne(l.chatNewChatDraftTakeScreenshot)]}):null]}):null]})}),r.jsxs("div",{className:"composerRightGroup",children:[w??r.jsx(Jd,{payload:a,composerBusy:u,composerRecipients:C,defaultRecipientParticipantId:S,composerStackParticipants:y,directLaneCat:We,isDirectLane:g,isDefaultChatComposer:x,activeWorkflowShape:I,onToggleActiveWorkflowShape:k,activeAudienceKeys:P,onSetActiveAudienceKeys:A,onOpenSection:H}),Ke?r.jsxs("button",{className:`composerPlusButton composerVoiceButton${et?" composerVoiceButtonActive":""}`,type:"button","aria-label":Yt,"aria-pressed":et,title:Oe??void 0,disabled:u,onClick:V,children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("rect",{x:"6",y:"2",width:"4",height:"8",rx:"2"}),r.jsx("path",{d:"M3 8a5 5 0 0 0 10 0"}),r.jsx("path",{d:"M8 13v2"}),r.jsx("path",{d:"M6 15h4"})]}),Oe?r.jsx("span",{className:"composerVoicePrivacyBadge","aria-hidden":"true",children:"!"}):null]}):null,D?r.jsx("button",{className:"composerSendButton composerCancelButton",type:"button","aria-label":Ne(l.chatNewChatDraftCancelSendAria),onClick:()=>G?.(),children:r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M4 4l6 6"}),r.jsx("path",{d:"M10 4l-6 6"})]})}):N?r.jsx("button",{className:"composerSendButton composerStopButton",disabled:f,type:"button","aria-label":nt,onClick:()=>{W?.()},children:r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"currentColor","aria-hidden":"true",children:r.jsx("rect",{x:"3",y:"3",width:"8",height:"8",rx:"1.6"})})}):t?r.jsxs("div",{className:"composerSplitSend",children:[r.jsx("button",{className:"composerSplitSendMain",disabled:!Z||u||h,type:"submit","aria-label":_t,children:M==="all_members"?r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M4 13V6"}),r.jsx("path",{d:"M1 9l3-3 3 3"}),r.jsx("path",{d:"M12 13V6"}),r.jsx("path",{d:"M9 9l3-3 3 3"})]}):r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 13V3"}),r.jsx("path",{d:"M3 7l5-5 5 5"})]})}),r.jsx("button",{className:"composerSplitSendToggle",type:"button","aria-label":Ue,onClick:()=>Y?.(M==="all_members"?"active_only":"all_members"),children:r.jsx("svg",{width:"8",height:"8",viewBox:"0 0 8 8",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M1 3l3 3 3-3"})})})]}):r.jsx("button",{className:"composerSendButton",disabled:!Z||u||h,type:"submit","aria-label":Ne(l.chatNewChatDraftSendAria),children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 13V3"}),r.jsx("path",{d:"M3 7l5-5 5 5"})]})})]})]}),r.jsx("input",{ref:c,type:"file",multiple:!0,disabled:u,style:{display:"none"},onChange:fe=>{const Le=fe.currentTarget;if(Le.files&&Le.files.length>0){const Te=Array.from(Le.files);ae([...o,...Te])}Le.value=""}})]}),E?r.jsx("div",{className:"composerFooterRow",children:E}):null,r.jsx(Do,{toasts:ne})]})}function gy(e,t,n){const a=e.provider?.trim()||t,s=e.model?.trim();return a!==t?s?`${a} · ${s}`:a:e.title.trim()||n}function Cy({compareMembers:e,selectedChannelId:t,comparePrevChannelId:n,compareNextChannelId:a,onSelect:s,onNavigatePrev:o,onNavigateNext:i}){const{t:d}=Q(),c=d(l.chatParallelFooterDefaultModelLabel),u=h=>d(l.chatParallelFooterThreadLabel,{threadIndex:h+1});return r.jsxs("nav",{className:"parallelFooterBar","aria-label":d(l.chatParallelFooterNavigationAriaLabel),children:[r.jsx("button",{className:"parallelFooterNavButton",type:"button",disabled:!n,onClick:o,"aria-label":d(l.chatParallelFooterPrevAriaLabel),children:r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("polyline",{points:"15 18 9 12 15 6"})})}),r.jsx("div",{className:"parallelFooterTabs",role:"tablist","aria-label":d(l.chatParallelFooterTabsAriaLabel),children:e.map(h=>{const f=h.channelId===t,m=gy(h,c,u(h.index));return r.jsx("button",{className:f?"parallelFooterTab parallelFooterTabActive":"parallelFooterTab",type:"button",role:"tab","aria-selected":f,title:`${m} · ${pr(h.title,d)}`,onClick:()=>s(h.channelId),children:r.jsx("span",{className:"parallelFooterTabLabel",children:m})},h.channelId)})}),r.jsx("button",{className:"parallelFooterNavButton",type:"button",disabled:!a,onClick:i,"aria-label":d(l.chatParallelFooterNextAriaLabel),children:r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})})]})}const vy=new Set([".png",".jpg",".jpeg",".gif",".webp"]),Iy=/^\[Attached files in working directory:\]\n((?:- [^\n]+\n)+)\n?/;function Sy(e){const t=Iy.exec(e);if(!t)return{attachments:[],textBody:e};const n=t[1],a=[];for(const o of n.split(`
2
+ `)){const i=o.replace(/^- /,"").trim();if(!i)continue;const d=i.slice(i.lastIndexOf(".")).toLowerCase(),c=i.split("/").pop()??i;a.push({filename:c,relativePath:i,isImage:vy.has(d)})}const s=e.slice(t[0].length);return{attachments:a,textBody:s}}const Nl=/https?:\/\/[^\s<>"'\]]+/gi,Tl=/\/(?:work|chat|code)\/[^\s<>"'\]]+/g,yy=new Set([".",",",";"]);function by(e){let t=0;for(const n of e)n==="("?t+=1:n===")"&&(t-=1);return t<0}function jl(e){let t=e;for(;t.length>0;){const n=t.at(-1);if(!n)break;if(yy.has(n)){t=t.slice(0,-1);continue}if(n===")"&&by(t)){t=t.slice(0,-1);continue}break}return t}function Ll(e,t,n,a){return e<a&&n<t}function xy(e,t,n=[]){const a=new Map;for(const g of t)a.set(g.name.toLowerCase(),g);const s=[],o=new RegExp(Nl.source,Nl.flags);let i;for(;(i=o.exec(e))!==null;){const g=i[0],x=jl(g);s.push({kind:"url",start:i.index,end:i.index+x.length,value:x,href:x})}const d=[],c=new RegExp(Tl.source,Tl.flags);let u;for(;(u=c.exec(e))!==null;){const g=u[0],x=jl(g);d.push({kind:"route",start:u.index,end:u.index+x.length,value:x,href:x})}const m=zd(e,{excludedNames:n}).positions.flatMap(g=>{const x=a.get(g.name.toLowerCase())??null;return x?[{kind:"mention",start:g.start,end:g.end,value:e.slice(g.start,g.end),avatarColor:x.avatarColor??null}]:[]}).filter(g=>!s.some(x=>Ll(g.start,g.end,x.start,x.end))),v=d.filter(g=>!s.some(x=>Ll(g.start,g.end,x.start,x.end))),C=[...s,...v,...m].sort((g,x)=>g.start-x.start),S=[];let y=0;for(const g of C)g.start>y&&S.push({kind:"text",value:e.slice(y,g.start)}),g.kind==="url"||g.kind==="route"?S.push({kind:g.kind,value:g.value,href:g.href}):S.push({kind:"mention",value:g.value,avatarColor:g.avatarColor}),y=g.end;return y<e.length&&S.push({kind:"text",value:e.slice(y)}),S}function Qd({body:e,cats:t,channelId:n,disabledMentionNames:a=[]}){const{attachments:s,textBody:o}=p.useMemo(()=>Sy(e),[e]),i=p.useMemo(()=>xy(o,t,a),[a,o,t]),d=s.filter(h=>h.isImage),c=s.filter(h=>!h.isImage),u=encodeURIComponent(n);return r.jsxs("div",{className:"messageBodyWrapper",children:[d.length>0?r.jsx("div",{className:"messageBodyImages",children:d.map(h=>{const f=`/api/channels/${u}/attachments/${encodeURIComponent(h.filename)}`;return r.jsx("a",{className:"messageBodyImageLink",href:f,target:"_blank",rel:"noopener noreferrer",children:r.jsx("img",{className:"messageBodyImage",src:f,alt:h.filename,loading:"lazy"})},h.relativePath)})}):null,c.length>0?r.jsx("div",{className:"messageBodyFiles",children:c.map(h=>r.jsxs("a",{className:"messageBodyFileChip",href:`/api/channels/${u}/attachments/${encodeURIComponent(h.filename)}`,download:h.filename,children:[r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("path",{d:"M14 2v6h6"})]}),h.filename]},h.relativePath))}):null,o?r.jsx("p",{className:"messageBody",children:i.map((h,f)=>{switch(h.kind){case"url":return r.jsx("a",{className:"messageBodyLink",href:h.href,target:"_blank",rel:"noopener noreferrer",children:h.value},f);case"route":return r.jsx(Rh,{className:"messageBodyLink",to:h.href??h.value,children:h.value},f);case"mention":return r.jsx("span",{className:"messageBodyMention",style:h.avatarColor?{background:h.avatarColor}:void 0,children:h.value},f);default:return r.jsx("span",{children:h.value},f)}})}):null]})}const wy="localizedBody",ky=new Set(Object.values(l));function Py(e,t){const n=Ry(e.metadata?.[wy]);return n?Ay(n,t):e.body}function Ay(e,t){const n={...e.values??{}};for(const[a,s]of Object.entries(e.valueKeys??{}))n[a]=t(s);return t(e.key,n)}function Ry(e){if(!oi(e)||!Xd(e.key))return null;const t=Ny(e.values),n=Ty(e.valueKeys);return{key:e.key,...t?{values:t}:{},...n?{valueKeys:n}:{}}}function Ny(e){if(!oi(e))return null;const t={};for(const[n,a]of Object.entries(e))jy(a)&&(t[n]=a);return Object.keys(t).length>0?t:null}function Ty(e){if(!oi(e))return null;const t={};for(const[n,a]of Object.entries(e))Xd(a)&&(t[n]=a);return Object.keys(t).length>0?t:null}function jy(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Xd(e){return typeof e=="string"&&ky.has(e)}function oi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ly(e){const t=e?.companionReferenceSnapshots;if(!Array.isArray(t))return[];const n=[];for(const a of t){const s=Pf(a);s&&n.push(s)}return n}function My(e,t){for(const n of e)if(n.reference.scopeId===t.scopeId&&n.reference.catId===t.catId&&n.reference.type===t.type&&n.reference.targetId===t.targetId)return n;return null}function Ey({body:e,metadata:t}){const{t:n}=Q(),a=p.useMemo(()=>Nf(e),[e]),s=p.useMemo(()=>Ly(t),[t]),o=p.useMemo(()=>{const h=[];for(const f of s){const m=Fo(f.referenceText);m.status==="parsed"&&h.push({start:-1,end:-1,rawText:f.referenceText,parseResult:m})}return h},[s]),i=p.useMemo(()=>{const h=new Set,f=[];for(const m of[...a,...o]){const v=m.parseResult.status==="parsed"?`parsed:${m.parseResult.reference.scopeId}:${m.parseResult.reference.catId}:${m.parseResult.reference.type}:${m.parseResult.reference.targetId}`:`${m.parseResult.status}:${m.rawText}`;h.has(v)||(h.add(v),f.push(m))}return f},[a,o]),[d,c]=p.useState([]),u=p.useRef(null);return p.useEffect(()=>{if(u.current?.abort(),i.length===0){c([]);return}const h=new AbortController;u.current=h;const f=i.map(m=>{if(m.parseResult.status==="parsed"){const v=m.parseResult.reference;return{reference:v,rawText:m.rawText,status:"parsed",loading:!0,preview:null,fallbackSnapshot:My(s,v)}}return m.parseResult.status==="unsupported_version"?{reference:{version:"v1",scopeId:"",catId:"",type:"post",targetId:"",surface:"companion"},rawText:m.rawText,status:"unsupported_version",loading:!1,preview:null,fallbackSnapshot:null,parseUnsupportedVersion:m.parseResult.version}:{reference:{version:"v1",scopeId:"",catId:"",type:"post",targetId:"",surface:"companion"},rawText:m.rawText,status:"invalid",loading:!1,preview:null,fallbackSnapshot:null,parseInvalidReason:m.parseResult.reason}});return c(f),Promise.all(f.map(async(m,v)=>{if(m.status==="parsed")try{const C=await fetch(`/api/cats/${encodeURIComponent(m.reference.catId)}/companion-box/resolve-reference`,{method:"POST",headers:{Accept:"application/json","content-type":"application/json"},body:JSON.stringify({referenceText:m.rawText}),signal:h.signal});if(!C.ok)throw new Error(`resolve-reference returned ${C.status}`);const S=await C.json();if(h.signal.aborted)return;const y=S.preview??null;c(g=>{if(g[v]?.reference!==m.reference)return g;const x=g.slice();return x[v]={...g[v],loading:!1,preview:Ml(y,m.fallbackSnapshot,n)},x})}catch{if(h.signal.aborted)return;c(C=>{if(C[v]?.reference!==m.reference)return C;const S=C.slice();return S[v]={...C[v],loading:!1,preview:Ml(null,m.fallbackSnapshot,n)},S})}})),()=>{h.abort()}},[i,s]),d.length===0?null:r.jsx("ul",{className:"companionMessageReferenceList","aria-label":n(l.chatCompanionMessageReferenceListAria),children:d.map((h,f)=>r.jsx("li",{className:"companionMessageReferenceItem",children:Fy(h,n)},`${h.rawText}-${f}`))})}function Ml(e,t,n){return e?e.availability!=="available"&&t?{...e,title:e.title===""||_y(e.title,e.fallbackReason)?t.title:e.title,subtitle:e.subtitle??t.subtitle,description:e.description??t.description,thumbnailUrl:e.thumbnailUrl??t.thumbnailUrl,catName:e.catName==="Companion"?t.catName:e.catName,snapshot:e.snapshot??t.snapshot}:e.availability!=="available"&&!t?{...e,title:Dy(e.availability,n),catName:e.catName==="Companion"?By(n):e.catName,description:e.availability==="inaccessible"?Oy(e.description,n):e.description}:e:t?{reference:t.reference,availability:"missing",title:t.title,generatedTitleKind:null,fallbackReason:"missing",subtitle:t.subtitle,description:t.description,thumbnailUrl:t.thumbnailUrl,icon:null,catName:t.catName,openRoute:null,snapshot:t.snapshot,resolvedAt:t.capturedAt}:null}function Dy(e,t){return t(e==="missing"?l.chatCompanionMessageReferenceMissingFallbackTitle:e==="deleted"?l.chatCompanionMessageReferenceDeletedFallbackTitle:l.chatCompanionMessageReferenceInaccessibleFallbackTitle)}function By(e){return e(l.chatCompanionMessageReferenceUnknownCompanionLabel)}function Oy(e,t){return e||t(l.chatCompanionMessageReferenceInaccessibleFallbackDescription)}function _y(e,t){return e.length===0||!!t}function Fy(e,t){if(e.status==="unsupported_version")return r.jsxs("div",{className:"companionReferenceCard companionReferenceCardUnsupported",children:[r.jsx("span",{className:"companionReferenceCardLabel",children:t(l.chatCompanionMessageReferenceUnsupportedVersionLabel)}),e.parseUnsupportedVersion?r.jsxs("span",{className:"companionReferenceCardSubtle",children:["(",e.parseUnsupportedVersion,")"]}):null]});if(e.status==="invalid")return r.jsxs("div",{className:"companionReferenceCard companionReferenceCardInvalid",children:[r.jsx("span",{className:"companionReferenceCardLabel",children:t(l.chatCompanionMessageReferenceMalformedLabel)}),e.parseInvalidReason?r.jsxs("span",{className:"companionReferenceCardSubtle",children:["(",Wy(e.parseInvalidReason,t),")"]}):null]});if(e.loading)return r.jsx("div",{className:"companionReferenceCard companionReferenceCardLoading",children:r.jsx("span",{className:"companionReferenceCardLabel",children:t(l.chatCompanionMessageReferenceLoadingLabel)})});const n=e.preview;if(!n)return r.jsx("div",{className:"companionReferenceCard companionReferenceCardError",children:r.jsx("span",{className:"companionReferenceCardLabel",children:t(l.chatCompanionMessageReferenceUnavailableLabel)})});const a=`companionReferenceCard${Uy(n.availability)}`;return r.jsxs("div",{className:`companionReferenceCard ${a}`,"data-availability":n.availability,children:[r.jsxs("div",{className:"companionReferenceCardHeader",children:[r.jsx("span",{className:"companionReferenceCardTitle",children:$y(n,t)}),r.jsx("span",{className:"companionReferenceCardCat",children:n.catName})]}),n.subtitle?r.jsx("span",{className:"companionReferenceCardSubtitle",children:n.subtitle}):null,n.description?r.jsx("p",{className:"companionReferenceCardDescription",children:n.description}):null,n.openRoute?r.jsx("a",{className:"companionReferenceCardOpen",href:n.openRoute,children:t(l.chatCompanionMessageReferenceOpenInCompanionAction)}):null,r.jsx("span",{className:"companionReferenceCardAvailability","data-availability":n.availability,children:Ky(n.availability,t)})]})}function Wy(e,t){switch(e){case"wrong_scheme":return t(l.chatCompanionMessageReferenceInvalidWrongScheme);case"wrong_host":return t(l.chatCompanionMessageReferenceInvalidWrongHost);case"malformed_percent_encoding":return t(l.chatCompanionMessageReferenceInvalidMalformedPercentEncoding);case"bad_segment_count":return t(l.chatCompanionMessageReferenceInvalidBadSegmentCount);case"empty_path_segment":return t(l.chatCompanionMessageReferenceInvalidEmptyPathSegment);case"unknown_target_type":return t(l.chatCompanionMessageReferenceInvalidUnknownTargetType);default:return e}}function Ky(e,t){switch(e){case"available":return t(l.chatCompanionMessageReferenceAvailabilityLivePreview);case"missing":return t(l.chatCompanionMessageReferenceAvailabilityMissing);case"deleted":return t(l.chatCompanionMessageReferenceAvailabilityDeleted);case"inaccessible":return t(l.chatCompanionMessageReferenceAvailabilityInaccessible);default:return""}}function Uy(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}function $y(e,t){return e.generatedTitleKind==="post"?t(l.chatCompanionMessageReferenceUntitledPostTitle):e.generatedTitleKind==="source"?t(l.chatCompanionMessageReferenceUntitledSourceTitle):e.title}function Hy(e,t){return e.status==="skipped"?"Skipped requested choices.":e.answers.map(a=>{const s=t?.find(d=>d.question===a.question),i=[...a.selectedOptionIds.map(d=>s?.options.find(c=>c.id===d)?.label??d),...a.customText?[a.customText]:[]];return`Q: ${a.question}
3
+ A: ${i.length>0?i.join(", "):"Skipped"}`}).join(`
4
+
5
+ `)}function dr(e,t){return e?.answers.find(n=>n.question===t)??null}function qy({channelId:e,messageId:t,choices:n,existingResponse:a,busy:s,onSubmit:o}){const{t:i}=Q(),[d,c]=p.useState(()=>Object.fromEntries(n.map(I=>[I.question,dr(a,I.question)?.selectedOptionIds??[]]))),[u,h]=p.useState(()=>Object.fromEntries(n.map(I=>[I.question,dr(a,I.question)?.customText??""]))),[f,m]=p.useState(()=>Object.fromEntries(n.map(I=>[I.question,!!dr(a,I.question)?.customText]))),v=s||!!a,C=n.some(I=>I.allowSkip);function S(I,k){const P=dr(a,I);return P?P.selectedOptionIds.includes(k):(d[I]??[]).includes(k)}function y(I,k,P=!1){v||c(A=>{const M=new Set(A[I]??[]);return P?(M.has(k)?M.delete(k):M.add(k),{...A,[I]:Array.from(M)}):{...A,[I]:M.has(k)?[]:[k]}})}function g(){return n.every(I=>{const k=d[I.question]??[],P=u[I.question]?.trim()??"";return k.length>0||P.length>0})}function x(I){const k=new Date().toISOString(),P={sourceMessageId:t,status:I,submittedAt:k,answers:n.map(A=>({question:A.question,selectedOptionIds:I==="skipped"?[]:d[A.question]??[],...I==="skipped"?{skipped:!0}:{},...I!=="skipped"&&u[A.question]?.trim()?{customText:u[A.question].trim()}:{}}))};o({channelId:e,body:Hy(P,n),choiceResponse:P})}return r.jsxs("div",{className:"messageChoices",children:[n.map(I=>r.jsxs("section",{className:"messageChoiceSection",children:[r.jsx("p",{className:"messageChoiceQuestion",children:I.question}),r.jsxs("div",{className:"messageChoiceOptions",children:[I.options.map(k=>{const P=S(I.question,k.id);return r.jsx("button",{className:P?"messageChoiceButton messageChoiceButtonSelected":"messageChoiceButton",type:"button",disabled:v,title:k.description,onClick:()=>y(I.question,k.id,I.multiSelect),children:k.label},`${t}:${I.question}:${k.id}`)}),I.allowCustom?r.jsx("button",{className:f[I.question]?"messageChoiceButton messageChoiceButtonSelected":"messageChoiceButton",type:"button",disabled:v,onClick:()=>m(k=>({...k,[I.question]:!k[I.question]})),children:i("sharedMessageChoicesCustom")}):null]}),I.allowCustom&&f[I.question]?r.jsx("textarea",{className:"messageChoiceCustomInput",rows:2,value:a?dr(a,I.question)?.customText??"":u[I.question]??"",disabled:v,placeholder:i("sharedMessageChoicesAddCustomPlaceholder"),onChange:k=>h(P=>({...P,[I.question]:k.target.value}))}):null]},`${t}:${I.question}`)),a?r.jsx("p",{className:"messageChoiceResolved",children:a.status==="skipped"?i("sharedMessageChoicesSkipped"):i("sharedMessageChoicesRecorded")}):r.jsxs("div",{className:"messageChoiceActions",children:[r.jsx("button",{className:"messageChoiceActionButton messageChoiceActionButtonPrimary",type:"button",disabled:s||!g(),onClick:()=>x("submitted"),children:i("sharedMessageChoicesConfirm")}),C?r.jsx("button",{className:"messageChoiceActionButton",type:"button",disabled:s,onClick:()=>x("skipped"),children:i("sharedMessageChoicesSkip")}):null]})]})}function Gy(){return r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[r.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),r.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}function Vy(){return r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[r.jsx("path",{d:"M23 4v6h-6"}),r.jsx("path",{d:"M1 20v-6h6"}),r.jsx("path",{d:"M3.51 9a9 9 0 0 1 14.13-3.36L23 10"}),r.jsx("path",{d:"M20.49 15a9 9 0 0 1-14.13 3.36L1 14"})]})}function Zd(){return r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[r.jsx("path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}),r.jsx("polyline",{points:"16 6 12 2 8 6"}),r.jsx("line",{x1:"12",y1:"2",x2:"12",y2:"15"})]})}function eu({senderKind:e,showDefaultCopyAction:t=!1,copyActionLabel:n,onCopyMessage:a,extraActions:s=[]}){if(e==="system")return null;const o=t&&a!=null;return!o&&s.length===0?null:r.jsxs("div",{className:["messageActions",e==="user"?"messageActionsHoverOnly":"messageActionsPersistent"].join(" "),children:[s.map(i=>i.kind==="menu"?r.jsxs("div",{className:"messageActionMenu",children:[r.jsx("button",{className:"messageActionIcon",type:"button",disabled:i.disabled===!0,title:i.title,"aria-label":i.ariaLabel??i.title,onClick:i.onToggle,children:i.icon??r.jsx(Zd,{})}),i.open?r.jsx("div",{className:"messageActionPopover",children:i.items.map(d=>r.jsxs("div",{children:[d.dividerBefore?r.jsx("div",{className:"messageActionPopoverDivider"}):null,r.jsx("button",{type:"button",disabled:d.disabled===!0,onClick:d.onSelect,children:d.label})]},d.key))}):null]},i.key):r.jsx("button",{className:"messageActionIcon",type:"button",disabled:i.disabled===!0,onClick:i.onSelect,title:i.title,"aria-label":i.ariaLabel??i.title,children:i.icon},i.key)),o?r.jsx("button",{className:"messageActionIcon",type:"button",onClick:a,title:n,"aria-label":n,children:r.jsx(Gy,{})}):null]})}const zy=[{command:"check_this",titleLabel:"chatTranscriptMessageCheckWithOthersLabel"},{command:"synthesize_this",titleLabel:"chatTranscriptMessageSynthesizeWithOthersLabel"},{command:"improve_this",titleLabel:"chatTranscriptMessageImproveWithOthersLabel"},{command:"adopt_this",titleLabel:"chatTranscriptMessageAdoptWithOthersLabel"},{command:"counter_this",titleLabel:"chatTranscriptMessageCounterWithOthersLabel"},{command:"debate_this",titleLabel:"chatTranscriptMessageDebateWithOthersLabel"}];function Yy({message:e,stackClassName:t,cats:n,bossCatId:a,selectedChannelId:s,disabledMentionNames:o,compareBusy:i,choiceBusy:d,isCompareGroup:c,relayMenuOpen:u,userTurnStatus:h,retryBusy:f,existingChoiceResponse:m=null,onChoiceSubmit:v,onRetryMessage:C,onCopyMessage:S,onToggleRelayMenu:y,onCloseRelayMenu:g,onRelayMessage:x,extraActions:I=[],resolveMessageParticipant:k,resolveParticipantCatRecord:P,buildParticipantAvatarClassName:A,buildParticipantAvatarStyle:M,resolveParticipantAvatarUrl:D,resolveParticipantDisplayName:N,showSpeakerHeader:R=!0}){const{t:w}=Q(),b=Nh(e,n,w),T=Py(e,w),E=k(e),O=P(E),H=[...I];return e.senderKind==="user"&&h==="failed"&&C&&H.push({key:`retry:${e.id}`,title:w(l.chatTranscriptMessageRetryResponseLabel),icon:r.jsx(Vy,{}),disabled:f,onSelect:()=>{C(e.id)}}),c&&e.senderKind!=="user"&&x&&H.push({key:`relay:${e.id}`,kind:"menu",title:w(l.chatTranscriptMessageRelayToOthersLabel),icon:r.jsx(Zd,{}),disabled:i,open:u,onToggle:y,items:zy.map((U,L)=>({key:U.command,label:w(U.titleLabel),disabled:i,dividerBefore:L===2||L===4,onSelect:()=>{g(),x(e.id,U.command)}}))}),r.jsxs("article",{className:t,children:[r.jsxs("div",{className:Th(e.senderKind),children:[R&&e.senderKind!=="user"&&e.senderKind!=="system"?E?r.jsxs("div",{className:"transcriptMessageTop",children:[r.jsx("div",{className:A(E,{transcript:!0,catRecord:O}),style:M(E,O),children:D(E,O)?null:At(N(E,O))}),r.jsx("strong",{children:N(E,O)})]}):b.kind==="cat"&&b.cat?r.jsxs("div",{className:"transcriptMessageTop",children:[r.jsx("div",{className:b.cat.id===a?"catAvatar catAvatarBoss transcriptAvatar":"catAvatar transcriptAvatar",style:b.cat.avatarUrl?{backgroundImage:`url(${b.cat.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:b.cat.avatarColor?{background:b.cat.avatarColor}:void 0,children:b.cat.avatarUrl?null:At(b.cat.name)}),r.jsx("strong",{children:b.label})]}):b.label?r.jsx("div",{className:"transcriptMessageTop",children:r.jsx("strong",{children:b.label})}):null:null,T?r.jsx(Qd,{body:T,cats:n,channelId:s,disabledMentionNames:o}):null,r.jsx(Ey,{body:T,metadata:e.metadata}),e.senderKind==="user"&&h==="failed"?r.jsx("div",{className:"userTurnStatus userTurnStatusFailed",children:w(l.chatTranscriptMessageFailedStatusLabel)}):null]}),r.jsx(eu,{senderKind:e.senderKind,showDefaultCopyAction:T.trim().length>0,copyActionLabel:w(l.chatTranscriptMessageCopyLabel),onCopyMessage:()=>{S(T)},extraActions:H}),e.choices&&e.choices.length>0?r.jsx(qy,{channelId:s,messageId:e.id,choices:e.choices,existingResponse:m,busy:d,onSubmit:v}):null]})}const Jy=/^(?:[ \t]*\r?\n)+/u;function Qy(e){return e.replace(Jy,"")}function Xy(e){return e.status==="error"?e.kind!=="status"||e.text.trim().length>0:!1}function Zy(e,t){return e.kind==="text"||t||Xy(e)}function eb(e,t){return e==="streaming"&&t!=null&&t.kind!=="text"&&t.status==="streaming"}function tb(e){switch(e){case"streaming":return"compareCard compareCardStreaming";case"sealed":return"compareCard compareCardSealed";default:return"compareCard"}}function Cr(e,t){return(e%t+t)%t}const nb=2;function ab(e,t){const n=e.length;if(n===0)return{normalizedStartIndex:0,showNav:!1,singleVisibleCard:!1,total:0,visibleIndices:[],visibleItems:[]};const a=Cr(t,n);return n<=nb?{normalizedStartIndex:a,showNav:!1,singleVisibleCard:n===1,total:n,visibleIndices:e.map((s,o)=>o),visibleItems:[...e]}:{normalizedStartIndex:a,showNav:!0,singleVisibleCard:!1,total:n,visibleIndices:[a,Cr(a+1,n)],visibleItems:[e[a],e[Cr(a+1,n)]]}}function rb(){return r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[r.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),r.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}function sb(e){const{segments:t,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i,showProgressDetails:d}=e,{t:c}=Q(),u=t[0]?.id??null,h=t.flatMap(I=>{const k=ds(I,I.id===u,e,c);return k.shouldRender?[{segment:I,presentation:k}]:[]}),[f,m]=p.useState(0),{normalizedStartIndex:v,showNav:C,singleVisibleCard:S,total:y,visibleIndices:g,visibleItems:x}=ab(h,f);return r.jsxs("div",{className:C?"compareCardsCarousel compareCardsCarouselNavVisible":"compareCardsCarousel",children:[C?r.jsx("button",{type:"button",className:"compareCardsNavButton compareCardsNavPrev",onClick:()=>m(Cr(v-1,y)),"aria-label":c(l.chatCompareCardsPrevCardAriaLabel),children:r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("polyline",{points:"15 18 9 12 15 6"})})}):null,r.jsx("div",{className:S?"compareCardsGrid compareCardsGridSingle":"compareCardsGrid",children:x.map(({segment:I,presentation:k})=>{const P=!!(k.segmentParticipant||k.speakerCat||k.speakerLabel),A=ls(I),M=us(k,c);return r.jsxs("article",{className:tb(I.phase),children:[r.jsxs("div",{className:"compareCardHeader",children:[P?r.jsx(ii,{segmentParticipant:k.segmentParticipant,segmentParticipantCat:k.segmentParticipantCat,speakerCat:k.speakerCat,speakerLabel:k.speakerLabel,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i}):null,A?r.jsx("div",{className:"compareCardActions",children:r.jsx("button",{type:"button",className:"compareCardActionIcon",onClick:()=>{cs(A)},"aria-label":M,title:M,children:r.jsx(rb,{})})}):null]}),r.jsx("div",{className:"compareCardBody",children:r.jsx(ps,{segment:I,renderedBlocks:k.renderedBlocks,showTrailingDots:k.showTrailingDots,showProgressDetails:d})})]},I.id)})}),C?r.jsx("button",{type:"button",className:"compareCardsNavButton compareCardsNavNext",onClick:()=>m(Cr(v+1,y)),"aria-label":c(l.chatCompareCardsNextCardAriaLabel),children:r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}):null,y>1?r.jsx("div",{className:"compareCardsPagination",children:h.map(({segment:I},k)=>r.jsx("button",{type:"button",className:g.includes(k)?"compareCardsPaginationDot compareCardsPaginationDotActive":"compareCardsPaginationDot",onClick:()=>m(k),"aria-label":c(l.chatCompareCardsPaginationItemAriaLabel,{cardIndex:k+1})},I.id))}):null]})}function El(){return r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",focusable:"false",children:[r.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2"}),r.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}function ob(e){return!!(e.segmentParticipant||e.speakerCat||e.speakerLabel)}function ib(e,t,n,a){const s=e.segmentParticipantDisplayName??e.segmentParticipantCat?.name??e.speakerCat?.name??e.speakerLabel?.trim()??n;return s===n?a(t?l.chatFocusRailCollapseAnonymousResponseLabel:l.chatFocusRailExpandAnonymousResponseLabel):t?a(l.chatFocusRailCollapseLabeledResponseLabel,{speakerName:s}):a(l.chatFocusRailExpandLabeledResponseLabel,{speakerName:s})}function lb(){return r.jsx("span",{className:"focusRailSecondaryAnonymousIndicator","aria-hidden":"true",children:r.jsx("span",{className:"focusRailSecondaryAnonymousDot"})})}function cb({hasSpeakerIdentity:e,isActive:t,isExpanded:n}){return!e&&(!t||n)}function db(e){const{segments:t,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i,showProgressDetails:d}=e,{t:c}=Q(),[u,h]=p.useState(null),f=c(l.chatFocusRailUnnamedResponseLabel),m=t[0]??null,v=m?t.filter(y=>y.id!==m.id):[],C=m?ds(m,!0,e,c):null,S=C?us(C,c):null;return r.jsxs("div",{className:"focusRailContainer",children:[m&&C?.shouldRender?(()=>{const y=ls(m);return r.jsxs("article",{className:"focusRailPrimary",children:[r.jsxs("div",{className:"focusRailPrimaryHeader",children:[r.jsx(ii,{segmentParticipant:C.segmentParticipant,segmentParticipantCat:C.segmentParticipantCat,speakerCat:C.speakerCat,speakerLabel:C.speakerLabel,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i}),y?r.jsx("div",{className:"focusRailPrimaryActions",children:r.jsx("button",{type:"button",className:"focusRailActionIcon",onClick:()=>{cs(y)},"aria-label":S??void 0,title:S??void 0,children:r.jsx(El,{})})}):null]}),r.jsx(ps,{segment:m,renderedBlocks:C.renderedBlocks,showTrailingDots:C.showTrailingDots,showProgressDetails:d})]})})():null,v.length>0?r.jsx("div",{className:"focusRailSecondaries",children:v.map(y=>{const g=ds(y,!1,e,c);if(!g.shouldRender)return null;const x=ls(y),I=u===y.id,k=y.phase==="streaming"||y.phase==="waiting",P=ob(g),A=k&&!I,M=cb({hasSpeakerIdentity:P,isActive:k,isExpanded:I}),D=ib(g,I,f,c),N=us(g,c);return r.jsxs("div",{className:"focusRailSecondarySlot",children:[r.jsxs("button",{type:"button",className:"focusRailSecondaryHeader",onClick:()=>h(I?null:y.id),"aria-label":D,title:D,"aria-expanded":I,children:[P?r.jsx(hb,{segmentParticipant:g.segmentParticipant,segmentParticipantCat:g.segmentParticipantCat,speakerCat:g.speakerCat,speakerLabel:g.speakerLabel,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i}):M?r.jsx(lb,{}):null,A?r.jsx("span",{className:"focusRailSecondaryDots",children:r.jsxs("span",{className:"typingDots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]})}):null,r.jsx("span",{className:I?"focusRailExpandIcon focusRailExpandIconOpen":"focusRailExpandIcon",children:"›"})]}),I?r.jsxs("div",{className:"focusRailSecondaryBody",children:[r.jsx(ps,{segment:y,renderedBlocks:g.renderedBlocks,showTrailingDots:g.showTrailingDots,showProgressDetails:d}),x?r.jsx("div",{className:"focusRailSecondaryFooter",children:r.jsx("button",{type:"button",className:"focusRailActionIcon",onClick:()=>{cs(x)},"aria-label":N,title:N,children:r.jsx(El,{})})}):null]}):null]},y.id)})}):null]})}function ls(e){return[...e.contentBlocks].sort((t,n)=>t.index-n.index).filter(t=>t.kind==="text"&&t.text.trim()).map(t=>t.text).join(`
6
+ `)}async function cs(e){try{await navigator.clipboard.writeText(e)}catch{}}function ub(e,t,n,a,s,o=Is){if(!Zy(e,s))return null;if(e.kind==="text"){const i=Qy(e.text);return i.trim()?r.jsx(Qd,{body:i,cats:t,channelId:n,disabledMentionNames:a},e.id):null}return e.kind==="tool"?r.jsxs("div",{className:e.status==="streaming"?"toolSegmentChip":"toolSegmentChip toolSegmentChipDone",children:[r.jsx("span",{className:"toolSegmentChipName",children:e.toolName??e.title??o(l.chatConcurrentToolLabel)}),e.text?r.jsx("span",{className:"toolSegmentChipDetail",children:e.text}):null]},e.id):e.kind==="status"&&e.text?r.jsx("p",{className:"typingStatusText",children:tu(e.text,null,o)},e.id):null}function ds(e,t,n,a=Is){const{cats:s,liveSpeakerParticipant:o,liveSpeakerParticipantCat:i,resolveLiveIndicatorSegmentParticipant:d,resolveParticipantCatRecord:c,selectedChannelId:u,disabledMentionNames:h,showProgressDetails:f,resolveParticipantDisplayName:m}=n,v=d(e),C=c(v),S=(()=>{const b=e.speakerLabel?.trim();return e.participantId==="orchestrator"?jh(b):b||null})(),y=!!(v||e.catId||S),g=v??(!y&&t?o:null),x=v?C:!y&&t?i:null,I=g?m(g,x):null,k=e.catId?s.find(b=>b.id===e.catId)??null:null,P=I??x?.name??k?.name??S,A=[...e.contentBlocks].sort((b,T)=>b.index-T.index),M=A.at(-1),D=eb(e.phase,M),N=A.map(b=>ub(b,s,u,h,f,a)).filter(b=>b!=null),R=!!(e.participantId||e.catId||e.speakerLabel),w=e.phase==="waiting"||N.length>0||f&&e.progressText.trim().length>0||e.phase==="streaming"&&(Dc(e)||R)||D;return{segmentParticipant:g,segmentParticipantCat:x,segmentParticipantDisplayName:I,speakerCat:k,speakerLabel:P,renderedBlocks:N,showTrailingDots:D,shouldRender:w}}function pb(e,t=Is){return e.segmentParticipantDisplayName??e.segmentParticipantCat?.name??e.speakerCat?.name??e.speakerLabel?.trim()??t(l.chatFocusRailUnnamedResponseLabel)}function us(e,t=Is){const n=pb(e,t),a=t(l.chatFocusRailUnnamedResponseLabel);return n===a?t(l.chatConcurrentCopyUnnamedResponseLabel):t(l.chatConcurrentCopyLabeledResponseLabel,{speakerName:n})}function ii({segmentParticipant:e,segmentParticipantCat:t,speakerCat:n,speakerLabel:a,bossCatId:s,buildParticipantAvatarClassName:o,buildParticipantAvatarStyle:i,resolveParticipantAvatarUrl:d,resolveParticipantDisplayName:c}){return e?r.jsxs("div",{className:"transcriptMessageTop",children:[r.jsx("div",{className:o(e,{transcript:!0,catRecord:t}),style:i(e,t),children:d(e,t)?null:At(c(e,t))}),r.jsx("strong",{children:c(e,t)})]}):n?r.jsxs("div",{className:"transcriptMessageTop",children:[r.jsx("div",{className:n.id===s?"catAvatar catAvatarBoss transcriptAvatar":"catAvatar transcriptAvatar",style:n.avatarUrl?{backgroundImage:`url(${n.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:n.avatarColor?{background:n.avatarColor}:void 0,children:n.avatarUrl?null:At(n.name)}),r.jsx("strong",{children:n.name})]}):a?r.jsx("div",{className:"transcriptMessageTop",children:r.jsx("strong",{children:a})}):null}function hb({segmentParticipant:e,segmentParticipantCat:t,speakerCat:n,speakerLabel:a,bossCatId:s,buildParticipantAvatarClassName:o,buildParticipantAvatarStyle:i,resolveParticipantAvatarUrl:d,resolveParticipantDisplayName:c}){return e?r.jsxs("span",{className:"focusRailSecondaryIdentity",children:[r.jsx("span",{className:o(e,{transcript:!0,catRecord:t}),style:i(e,t),children:d(e,t)?null:At(c(e,t))}),r.jsx("span",{className:"focusRailSecondaryName",children:c(e,t)})]}):n?r.jsxs("span",{className:"focusRailSecondaryIdentity",children:[r.jsx("span",{className:n.id===s?"catAvatar catAvatarBoss transcriptAvatar":"catAvatar transcriptAvatar",style:n.avatarUrl?{backgroundImage:`url(${n.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:n.avatarColor?{background:n.avatarColor}:void 0,children:n.avatarUrl?null:At(n.name)}),r.jsx("span",{className:"focusRailSecondaryName",children:n.name})]}):a?r.jsx("span",{className:"focusRailSecondaryName",children:a}):null}function ps({segment:e,renderedBlocks:t,showTrailingDots:n,showProgressDetails:a}){const{t:s}=Q();return e.phase==="waiting"?r.jsxs("span",{className:"typingDots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]}):t.length===0?a&&e.progressText?r.jsx("p",{className:"typingStatusText",children:tu(e.progressText,e.progressKind,s)}):e.phase==="streaming"?r.jsxs("span",{className:"typingDots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]}):n?r.jsxs("span",{className:"typingDots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]}):null:r.jsxs(r.Fragment,{children:[t,n?r.jsxs("span",{className:"typingDots",children:[r.jsx("span",{}),r.jsx("span",{}),r.jsx("span",{})]}):null]})}function tu(e,t,n){if(t==="finalizing")return n(l.chatConcurrentProgressFinalizing);switch(e){case"Finalizing...":return n(l.chatConcurrentProgressFinalizing);case"Finishing...":return n(l.chatConcurrentProgressFinishing);case"Runtime stream unavailable":return n(l.chatConcurrentErrorRuntimeStreamUnavailable);case"Proxy error":return n(l.chatConcurrentErrorProxy);default:return e}}function fb(e){const{segments:t,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i,showProgressDetails:d}=e,{t:c}=Q(),u=t.at(-1)?.id??null;return r.jsx(r.Fragment,{children:t.map(h=>{const f=h.id===u,m=ds(h,f,e,c);if(!m.shouldRender)return null;const v=h.phase==="sealed"?ls(h):"",C=v.trim().length>0;return r.jsxs("article",{className:"transcriptMessageStack transcriptMessageStackAgent typingIndicator",children:[r.jsxs("div",{className:"transcriptMessage transcriptMessageAgent",children:[r.jsx(ii,{segmentParticipant:m.segmentParticipant,segmentParticipantCat:m.segmentParticipantCat,speakerCat:m.speakerCat,speakerLabel:m.speakerLabel,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i}),r.jsx(ps,{segment:h,renderedBlocks:m.renderedBlocks,showTrailingDots:m.showTrailingDots,showProgressDetails:d})]}),r.jsx(eu,{senderKind:"agent",showDefaultCopyAction:C,copyActionLabel:us(m,c),onCopyMessage:C?(()=>{cs(v)}):void 0})]},h.id)})})}function mb({actions:e}){return r.jsx("div",{className:"clusterActionBar",children:e.map(t=>r.jsx("button",{type:"button",className:"clusterActionButton",onClick:t.onSelect,title:t.title,disabled:t.disabled===!0,children:t.label},t.key))})}function nu(e){const{mode:t,actions:n=[],...a}=e,s=(()=>{switch(t){case"compare_cards":return r.jsx(sb,{...a});case"focus_rail":return r.jsx(db,{...a});default:return r.jsx(fb,{...a})}})();return n.length===0?s:r.jsxs("div",{className:"clusterActionBarWrapper",children:[s,r.jsx(mb,{actions:n})]})}function Ma(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function gb(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Cb(e){return Ma(e.metadata?.event)}function vb(e){return Ma(e.metadata?.turnId)}function Ib(e){return Ma(e.metadata?.targetStateId)}function Sb(e){return Ma(e.metadata?.laneId)}function yb(e){return Ma(e.metadata?.targetId)}function bb(e){return Ma(e.metadata?.sourceMessageId)}function Dl(e){return gb(e.metadata?.segmentIndex)}function xb(e){return e.workflowShape!=="concurrent"?!1:e.targetStatuses.filter(t=>t.depth===0&&t.source===null).length>1}function wb(e){return e.targetStatuses.filter(t=>t.depth===0&&t.source===null)}function au(e,t){return t.laneId?.trim()||ns(e.id,t.id,t.participant.participantId)}function kb(e,t){return{id:e,index:0,kind:"text",status:"complete",title:null,text:t,toolName:null,toolId:null,metadata:null}}function Pb(e){const{turn:t,target:n,visibleMessages:a}=e,s=new Set(n.response?.messageIds??[]),o=au(t,n);return[...a.filter(d=>{if(Cb(d)!=="assistant_turn_segment")return!1;if(s.has(d.id))return!0;if(vb(d)!==t.id)return!1;const c=Ib(d);if(c&&c===n.id)return!0;const u=Sb(d);return u&&u===o?!0:bb(d)===t.sourceMessageId&&yb(d)===n.participant.participantId})].sort((d,c)=>{const u=Dl(d)??0,h=Dl(c)??0;return u!==h?u-h:d.createdAt.localeCompare(c.createdAt)})}function Ab(e){const{turn:t,visibleMessages:n,visibleMessageIndexById:a}=e,s=wb(t);if(s.length<=1)return null;const o=[],i=new Set;let d=null,c=Number.POSITIVE_INFINITY;for(let h=0;h<s.length;h+=1){const f=s[h],m=Pb({turn:t,target:f,visibleMessages:n}),v=f.response?.fullText??m.map(S=>S.body).join(""),C=v.trim();if(!(!C&&m.length===0)){for(const S of m){i.add(S.id);const y=a.get(S.id)??Number.POSITIVE_INFINITY;y<c&&(c=y,d=S.id)}o.push(Sn({phase:"sealed",sourceMessageId:t.sourceMessageId,laneId:au(t,f),targetStateId:f.id,segmentIndex:h,sessionId:f.sessionId,participantId:f.participant.participantId,speakerLabel:f.participant.participantName,contentBlocks:C?[kb(`${t.id}:${f.id}:text`,v)]:[]}))}}if(o.length<=1||d==null)return null;const u=n.filter(h=>i.has(h.id));return{item:{kind:"concurrent_cluster",key:`concurrent-cluster:${t.id}`,turnId:t.id,sourceMessageId:t.sourceMessageId,segments:o,messages:[...u]},firstVisibleMessageId:d,visibleMessageIds:i}}function Rb(e){const t=new Map(e.visibleMessages.map((a,s)=>[a.id,s]));return[...Array.isArray(e.workflow.turnHistory)?e.workflow.turnHistory:[]].reverse().filter(xb).map(a=>Ab({turn:a,visibleMessages:e.visibleMessages,visibleMessageIndexById:t})).filter(a=>a!=null)}function Nb(e){const t=new Map,n=new Set;for(const s of Rb(e)){s.firstVisibleMessageId&&t.set(s.firstVisibleMessageId,s.item);for(const o of s.visibleMessageIds)n.add(o)}const a=[];for(const s of e.visibleMessages){const o=t.get(s.id);if(o){a.push(o);continue}n.has(s.id)||a.push({kind:"message",key:s.id,message:s})}return a}function Tb(e){const{liveIndicator:t,concurrentPresentationMode:n="inline_stack",concurrentActions:a}=e,s=Ve(t);return s.length===0?null:r.jsx(nu,{mode:s.length>1?n:"inline_stack",segments:s,cats:e.cats,bossCatId:e.bossCatId,selectedChannelId:e.selectedChannelId,disabledMentionNames:e.disabledMentionNames,liveSpeakerParticipant:e.liveSpeakerParticipant,liveSpeakerParticipantCat:e.liveSpeakerParticipantCat,resolveLiveIndicatorSegmentParticipant:e.resolveLiveIndicatorSegmentParticipant,resolveParticipantCatRecord:e.resolveParticipantCatRecord,buildParticipantAvatarClassName:e.buildParticipantAvatarClassName,buildParticipantAvatarStyle:e.buildParticipantAvatarStyle,resolveParticipantAvatarUrl:e.resolveParticipantAvatarUrl,resolveParticipantDisplayName:e.resolveParticipantDisplayName,showProgressDetails:e.showProgressDetails,actions:s.length>1?a:[]})}function jb({hasConversationStarted:e,greeting:t,transcriptListRef:n,bottomSentinelRef:a,selectedChannel:s,visibleMessages:o,workflow:i,cats:d,bossCatId:c,selectedChannelId:u,disabledMentionNames:h,busy:f,compareBusy:m,isCompareGroup:v,choiceResponsesBySource:C,onChoiceSubmit:S,latestUserTurnMessageId:y,latestUserTurnStatus:g,onRetryMessage:x,onRelayMessage:I,liveIndicator:k,liveSpeakerParticipant:P,liveSpeakerParticipantCat:A,resolveLiveIndicatorSegmentParticipant:M,messageStackTone:D,resolveMessageParticipant:N,resolveParticipantCatRecord:R,buildParticipantAvatarClassName:w,buildParticipantAvatarStyle:b,resolveParticipantAvatarUrl:T,resolveParticipantDisplayName:E,showLiveProgressDetails:O=!1,resolveConcurrentClusterPresentationMode:H,buildConcurrentClusterActions:U,buildTranscriptMessageActions:L}){const[$,X]=p.useState(null);p.useEffect(()=>{if(!$)return;function Y(G){G.target?.closest(".messageActionMenu")||X(null)}return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[$]);async function ke(Y){try{await navigator.clipboard.writeText(Y)}catch{}}if(!e)return r.jsx("section",{className:"freshChatIntro",children:r.jsx("div",{className:"draftGreeting",children:r.jsx("h1",{children:t})})});const z=!!(k?.active&&Ve(k).length>0),B=k?.active?Ve(k):[],ae=Nb({visibleMessages:o,workflow:i});function he(Y){return r.jsx(Yy,{message:Y,stackClassName:D(Y.senderKind),cats:d,bossCatId:c,selectedChannelId:u,disabledMentionNames:h,compareBusy:m,choiceBusy:Mh(f,Y.id),isCompareGroup:v,relayMenuOpen:$===Y.id,userTurnStatus:Y.senderKind==="user"&&Y.id===y?g:"idle",retryBusy:Lh(f),existingChoiceResponse:C.get(Y.id)??null,onChoiceSubmit:S,onRetryMessage:x,onCopyMessage:ke,onToggleRelayMenu:()=>X(G=>G===Y.id?null:Y.id),onCloseRelayMenu:()=>X(null),onRelayMessage:I,extraActions:L?.({message:Y,selectedChannel:s})??[],resolveMessageParticipant:N,resolveParticipantCatRecord:R,buildParticipantAvatarClassName:w,buildParticipantAvatarStyle:b,resolveParticipantAvatarUrl:T,resolveParticipantDisplayName:E,showSpeakerHeader:!0},Y.id)}return r.jsx("section",{className:"transcriptPanel",children:r.jsxs("div",{ref:n,className:"transcriptList",children:[ae.map(Y=>{if(Y.kind==="concurrent_cluster"){const G={turnId:Y.turnId,sourceMessageId:Y.sourceMessageId,segmentCount:Y.segments.length,clusterKind:"durable"},W=H(G);if(W==="inline_stack")return Y.messages.map(pe=>he(pe));const ue=U?.({...G,resolvedMode:W})??[];return r.jsx(nu,{mode:W,segments:Y.segments,cats:d,bossCatId:c,selectedChannelId:u,disabledMentionNames:h,liveSpeakerParticipant:null,liveSpeakerParticipantCat:null,resolveLiveIndicatorSegmentParticipant:M,resolveParticipantCatRecord:R,buildParticipantAvatarClassName:w,buildParticipantAvatarStyle:b,resolveParticipantAvatarUrl:T,resolveParticipantDisplayName:E,showProgressDetails:O,actions:ue},Y.key)}return he(Y.message)}),z&&k?r.jsx(Tb,{cats:d,bossCatId:c,selectedChannelId:u,disabledMentionNames:h,liveIndicator:k,liveSpeakerParticipant:P,liveSpeakerParticipantCat:A,resolveLiveIndicatorSegmentParticipant:M,resolveParticipantCatRecord:R,buildParticipantAvatarClassName:w,buildParticipantAvatarStyle:b,resolveParticipantAvatarUrl:T,resolveParticipantDisplayName:E,showProgressDetails:O,concurrentPresentationMode:(()=>{const Y=i.activeTurn?.id;return Y?H({turnId:Y,sourceMessageId:k.sourceMessageId??i.activeTurn?.sourceMessageId??"",segmentCount:B.length,clusterKind:"live"}):"inline_stack"})(),concurrentActions:(()=>{const Y=i.activeTurn?.id;if(!Y||!U)return[];const G=H({turnId:Y,sourceMessageId:k.sourceMessageId??i.activeTurn?.sourceMessageId??"",segmentCount:B.length,clusterKind:"live"});return U({turnId:Y,sourceMessageId:k.sourceMessageId??i.activeTurn?.sourceMessageId??"",segmentCount:B.length,clusterKind:"live",resolvedMode:G})})()}):null,r.jsx("div",{ref:a,className:"transcriptBottomSentinel","aria-hidden":"true"})]})})}const Lb=720,Mb=2,Eb=4;function Db(e){return e.explicitOverride?e.explicitOverride:e.workflowRecommendation?e.workflowRecommendation:e.userDefault!=="adaptive"?e.userDefault:e.viewportWidth>=Lb&&e.segmentCount>=Mb&&e.segmentCount<=Eb?"compare_cards":"inline_stack"}const hs="cats.concurrent-cluster-ui-state",Bb=200,Bl=new Set;function Ob(e,t){return t instanceof Error?`${e}:${t.name||"Error"}`:`${e}:${typeof t}`}function bo(e,t){const n=Ob(e,t);if(Bl.has(n)||(Bl.add(n),typeof console>"u"||typeof console.warn!="function"))return;const a=t instanceof Error?t.message:String(t);console.warn(`[Cats] Failed to ${e} concurrent cluster dismiss state: ${a}`)}function _b(e){if(!e||typeof e!="object")return null;const t=e.presentationOverride;return t!=="inline_stack"?null:{presentationOverride:t}}function Ps(e,t=Bb){const n=Object.entries(e);return n.length<=t?e:Object.fromEntries(n.slice(-t))}function ru(e,t){return`${e}:${t}`}function Fb(e){if(!e)return{};try{const t=JSON.parse(e);if(!t||typeof t!="object")return{};const n={};for(const[a,s]of Object.entries(t)){if(!a||typeof a!="string")continue;const o=_b(s);o&&(n[a]=o)}return Ps(n)}catch{return{}}}function Wb(e){if(!e)return{value:{},requiresPersistedCleanup:!1};let t=null;try{t=e.getItem(hs)}catch(s){return bo("read",s),{value:{},requiresPersistedCleanup:!1}}if(!t)return{value:{},requiresPersistedCleanup:!1};const n=Fb(t),a=JSON.stringify(n)!==t;return{value:n,requiresPersistedCleanup:a}}function Kb(e,t){let n=Object.keys(t).length;for(;n>1;){n=Math.floor(n/2);const a=Ps(t,n);try{return e.setItem(hs,JSON.stringify(a)),a}catch{}}return null}function Ub(e,t){if(!e)return t;const n=Ps(t);try{return e.setItem(hs,JSON.stringify(n)),n}catch(a){const s=Kb(e,n);if(s!==null)return s;if(typeof e.removeItem=="function")try{return e.removeItem(hs),bo("write",a),{}}catch{}return bo("write",a),t}}function $b(e,t){const n=ru(t.channelId,t.turnId),a={presentationOverride:"inline_stack"};return e[n]?.presentationOverride===a.presentationOverride?e:Ps({...e,[n]:a})}function Hb(e){const t=e.uiStateByKey[ru(e.channelId,e.turnId)]??null;return Db({explicitOverride:t?.presentationOverride??null,workflowRecommendation:null,userDefault:e.userDefault,segmentCount:e.segmentCount,viewportWidth:e.viewportWidth})}function Ol(e){if(typeof e!="string")return null;const t=e.trim();return t||null}function qb(e,t){const n=Ol(e);if(n)return n;const a=Ol(t);return a||null}function vr(e){return{kind:"named",participantId:e.participantId,catId:e.catId,name:e.name,executionLabel:e.executionLabel??null,avatarColor:e.avatarColor??null,avatarUrl:e.avatarUrl??null,provider:e.provider??null,instance:e.instance??null,model:e.model??null,modelSelection:No(e.modelSelection),isBoss:e.isBoss??!1}}function Gb(e,t){return vr({catId:e.id,name:e.name,executionLabel:oa(e),avatarColor:e.avatarColor,avatarUrl:e.avatarUrl,provider:e.defaultExecutionTarget?.provider??null,instance:e.defaultExecutionTarget?.instance??null,model:e.defaultExecutionTarget?.model??null,modelSelection:e.defaultModelSelection??null,isBoss:e.id===t})}function Vb(e){const t=wr({provider:e.provider,instance:e.instance??null,model:e.model??null,modelSelection:e.modelSelection??null,executionLabel:e.executionLabel??null});return{kind:"implicit",name:t,executionLabel:t,provider:e.provider,instance:e.instance??null,model:e.model??null,modelSelection:No(e.modelSelection)}}function zb(e,t,n){return t&&e.some(a=>a.channelId===t)?t:e.some(a=>a.channelId===n)?n:e[0]?.channelId??n}function _l(e,t,n){const a=e.findIndex(s=>s.channelId===t);return a<0||e.length<2?null:n==="prev"?e[(a-1+e.length)%e.length]?.channelId??null:e[(a+1)%e.length]?.channelId??null}const su=ia("en");function Yb(e){switch(e){case"user":return"transcriptMessageStack transcriptMessageStackUser";case"orchestrator":return"transcriptMessageStack transcriptMessageStackOrchestrator";case"agent":return"transcriptMessageStack transcriptMessageStackAgent";default:return"transcriptMessageStack transcriptMessageStackSystem"}}function Jb(e){const t=e.compareGroup?.members??[],n=t.length>1,a=zb(t,e.routeChannelId,e.selectedChannelId),s=t.findIndex(c=>c.channelId===a),o=t.map(c=>e.channels.find(u=>u.id===c.channelId)??null).filter(c=>c!=null),i=In(e.busy),d=o.some(c=>c.routingStatus==="running");return{compareMembers:t,isCompareGroup:n,activeCompareChannelId:a,compareMemberIndex:s,compareBusy:i||d,comparePrevChannelId:n&&s>=0?_l(t,a,"prev"):null,compareNextChannelId:n&&s>=0?_l(t,a,"next"):null}}function Qb(e){const t=e.t??su;return e.isDirectLane?e.directLaneCat?.name??e.defaultRecipientCatRecord?.name??pr(e.selectedChannelTitle,t):e.isCompareGroup&&e.compareGroup?pr(e.compareGroup.title,t):pr(e.selectedChannelTitle,t)}function Xb(e){return e.isDirectLane?!!e.defaultRecipientCat:!!(e.showBossCatAvatar&&!e.isDefaultChatComposer||e.activeRoomParticipants.length>0)}function Zb(e){return e.activeRoomParticipants.map(t=>{const n=e.resolveParticipantCatRecord(t),a=ra(t)??(n?.defaultExecutionTarget?oa(n):null);return{participantId:t.participantId,label:e.resolveParticipantDisplayName(t,n),executionLabel:a,avatarColor:n?.avatarColor??t.avatarColor??null,avatarUrl:n?.avatarUrl??t.avatarUrl??null,isBoss:n?.id===e.bossCatId,useNeutralAvatar:n==null}})}function ex(e){const t=new Map;for(const n of e)n.choiceResponse?.sourceMessageId&&t.set(n.choiceResponse.sourceMessageId,n.choiceResponse);return t}function tx(e){const t=e.visibleLiveIndicator?.phase==="streaming",n=!!(t&&(e.visibleLiveIndicator?.speakerLabel||e.visibleLiveIndicator?.catId||(e.visibleLiveIndicator?.activeCatIds.length??0)>0)),a=(()=>{if(!t)return[];const c=e.visibleLiveIndicator?.activeCatIds?.filter(u=>u.trim().length>0)??[];return c.length>0?[...new Set(c)]:e.visibleLiveIndicator?.active&&e.visibleLiveIndicator.catId?[e.visibleLiveIndicator.catId]:[]})(),s=(()=>{if(!t)return[];const u=(e.selectedChannel.roomRouting?.workflow?.activeTurn?.targetStatuses??[]).filter(h=>h.status==="running").map(h=>h.participant.participantId).filter(h=>h.trim().length>0);return u.length>0?[...new Set(u)]:e.visibleLiveIndicator?.active&&!n&&e.selectedChannel.roomRouting?.defaultRecipientId?[e.selectedChannel.roomRouting.defaultRecipientId]:[]})(),o=(()=>{const c=s[0]??null;return c||(t&&e.visibleLiveIndicator?.active&&!n?e.selectedChannel.roomRouting?.defaultRecipientId??null:null)})(),i=e.visibleLiveIndicator?.catId??null,d=o?e.activeRoomParticipants.find(c=>c.participantId===o)??null:i?e.activeRoomParticipants.find(c=>is(c)===i)??null:null;return{activeTopBarCatIds:a,activeTopBarParticipantIds:s,liveSpeakerParticipant:d}}function nx(e){if(e.isDirectLane&&e.directLaneCat)return[vr({participantId:e.defaultRecipientParticipant?.participantId,catId:e.directLaneCat.id,name:e.directLaneCat.name,executionLabel:e.defaultRecipientParticipant?ra(e.defaultRecipientParticipant):oa(e.directLaneCat),avatarColor:e.directLaneCat.avatarColor??null,avatarUrl:e.directLaneCat.avatarUrl??null,provider:e.defaultRecipientParticipant?.execution.target.provider??e.directLaneCat.defaultExecutionTarget.provider,instance:e.defaultRecipientParticipant?.execution.target.instance??e.directLaneCat.defaultExecutionTarget.instance??null,model:e.defaultRecipientParticipant?.execution.target.model??e.directLaneCat.defaultExecutionTarget.model??null,modelSelection:e.defaultRecipientParticipant?.execution.modelSelection??e.directLaneCat.defaultModelSelection??null,isBoss:e.directLaneCat.id===e.bossCatId})];if(e.isDefaultChatComposer&&e.selectedExecutionTarget)return[Vb(e.selectedExecutionTarget)];if(!e.defaultRecipientParticipant)return[];const t=e.resolveParticipantCatRecord(e.defaultRecipientParticipant);return t?[vr({participantId:e.defaultRecipientParticipant.participantId,catId:t.id,name:t.name,executionLabel:ra(e.defaultRecipientParticipant)??oa(t),avatarColor:t.avatarColor??null,avatarUrl:t.avatarUrl??null,provider:e.defaultRecipientParticipant.execution.target.provider,instance:e.defaultRecipientParticipant.execution.target.instance??null,model:e.defaultRecipientParticipant.execution.target.model??null,modelSelection:e.defaultRecipientParticipant.execution.modelSelection??null,isBoss:t.id===e.bossCatId})]:[vr({participantId:e.defaultRecipientParticipant.participantId,name:e.resolveParticipantDisplayName(e.defaultRecipientParticipant,null),executionLabel:ra(e.defaultRecipientParticipant),provider:e.defaultRecipientParticipant.execution.target.provider,instance:e.defaultRecipientParticipant.execution.target.instance??null,model:e.defaultRecipientParticipant.execution.target.model??null,modelSelection:e.defaultRecipientParticipant.execution.modelSelection??null})]}function ax(e){const t=e.t??su,n=In(e.busy,"ack")||Hc(e.busy,e.selectedChannelId),a=In(e.busy),s=Ym(e.busy,e.selectedChannelId),o=n||s||a,i=n&&e.onCancelPendingSend!=null,d=!e.isCompareGroup&&s&&e.onStopMessage!=null,c=e.isCompareGroup&&e.onStopMessage!=null&&(In(e.busy,"dispatch")||In(e.busy,"stop"));return{participantChipLabel:e.activeRoomParticipants.length>0?t(e.activeRoomParticipants.length===1?l.chatParticipantChipCountOne:l.chatParticipantChipCountMany,{count:e.activeRoomParticipants.length}):t(l.chatParticipantChipDefault),directLaneExecutionTarget:e.directLaneCat?{provider:e.directLaneCat.defaultExecutionTarget.provider,model:e.directLaneCat.defaultExecutionTarget.model,instance:e.directLaneCat.defaultExecutionTarget.instance,modelSelection:e.directLaneCat.defaultModelSelection??null}:null,directLaneExcludedMentionNames:e.directLaneCat?.name?[e.directLaneCat.name]:[],composerBusy:o,composerAckBusy:n,showCancelComposerAction:i,showStopComposerAction:!i&&(d||c),composerWorkspacePath:qb(e.repoPath,e.chatCwd)}}let Fr=null,Wr=null;function rx(e){const t=e.contentBlocks.map(a=>{const s=a.kind+"#"+a.index+":"+a.status;if(a.kind==="text"){const o=a.text.trim();return o.length===0?s+"(empty)":o.length<40?s+"(len"+o.length+")":o.length<400?s+"(len~"+Math.floor(o.length/40)*40+")":s+"(len~"+Math.floor(o.length/400)*400+")"}return s}).join("|"),n=[e.targetStateId?"ts:"+e.targetStateId:null,e.sessionId?"sid:"+e.sessionId:null,e.participantId?"pid:"+e.participantId:null,e.speakerLabel?"sp:"+e.speakerLabel:null,e.progressKind?"pk:"+e.progressKind:null,e.progressText?"pt:"+e.progressText:null,e.tools.length>0?"tools:"+e.tools.map(a=>`${a.toolName}:${a.done?"done":"pending"}`).join(","):null,e.events.length>0?"events:"+e.events.map(a=>a.eventType).join(","):null].filter(a=>a!=null&&a.length>0).join("|");return`${e.phase}:si${e.segmentIndex}:${t||n||"empty"}`}function Fl(e){if(!e)return"null";if(!e.active)return"inactive";const t=e.segments?.length?e.segments:[e];return e.phase+":"+t.length+":"+t.map(rx).join(";")}function sx(e,t){(typeof document>"u"?p.useEffect:p.useLayoutEffect)(e,t)}function Dw({payload:e,selectedChannel:t,routeChannelId:n=null,operatorSnapshot:a,operatorLoading:s,operatorError:o,composerDraft:i,busy:d,feedback:c,greeting:u,channelFiles:h,channelPlusMenuOpen:f,channelPlusMenuRef:m,channelFileInputRef:v,activeAssignedCats:C,bossCatName:S,bossCatAvatarColor:y,showBossCatAvatar:g,onComposerChange:x,onComposerKeyDown:I,onSendMessage:k,onCancelPendingSend:P,onStopMessage:A,onToggleChannelPlusMenu:M,onChannelFileSelect:D,onTakeScreenshot:N,screenshotCaptureDisabled:R,onChannelFilesChange:w,onApprovalDecision:b,onChoiceSubmit:T,onRetryMessage:E,onStartFresh:O,onOperatorAction:H,autoResize:U,selectedExecutionTarget:L,onExecutionTargetChange:$,onDirectLaneExecutionTargetChange:X,activeWorkflowShape:ke="sequential",onToggleActiveWorkflowShape:z,activeAudienceKeys:B=null,onSetActiveAudienceKeys:ae,onSelect:he,onOpenAddCat:Y,showAddCatButton:G=!0,behaviorSurface:W="chat",liveIndicator:ue,compareGroup:pe=null,compareSendScope:We="all_members",onCompareSendScopeChange:Z,onRelayMessage:Ke,onUpdateChannelParticipant:et,buildTranscriptMessageActions:V,renderStatusRow:re,renderTopBarExtraActions:ne,renderComposerTargetSlot:Oe,renderComposerHeaderAccessory:tt,renderComposerHeaderWhereExtras:Ne,renderComposerFooterAccessory:Ot,renderComposerSurfaceTag:Yt,buildSidePanelSections:_t,sidePanelTitle:nt=""}){const{t:Ue}=Q(),fe=Ta(),Le=nt||Ue(l.chatNewChatDraftSidePanelTitle),Te=p.useMemo(()=>Eh(e.chat.conversationBehavior,W),[W,e.chat.conversationBehavior]),ye=t.messages.filter(K=>Te.showVerboseMessages||K.metadata?.verbosity!=="verbose"),Ce=ye.length>0,Ft=p.useMemo(()=>Rm(ue,ye,t.roomRouting.workflow.activeTurn?.updatedAt??null,t.messages),[ue,t.messages,t.roomRouting.workflow.activeTurn?.updatedAt,ye]),{visibleLiveIndicator:Me,transcriptScrollKey:lt}=Ft,Pe=es(t),ht=p.useMemo(()=>Jb({compareGroup:pe,channels:e.chat.channels,routeChannelId:n,selectedChannelId:t.id,busy:d}),[d,pe,e.chat.channels,n,t.id]),{compareMembers:ft,isCompareGroup:Ee,activeCompareChannelId:Wt,compareMemberIndex:Lt,compareBusy:Mt,comparePrevChannelId:ct,compareNextChannelId:Et}=ht,st=yc(Pe),F=ts(Pe),{activeRoomParticipants:le,defaultRecipientParticipant:xe,defaultRecipientCat:mt,directLaneCat:at,defaultRecipientCatRecord:sn,assignedCatRecords:Jt,assignedAdhocParticipants:rt,topBarParticipants:Dt,resolveParticipantCatRecord:gt,resolveParticipantDisplayName:we,resolveParticipantAvatarUrl:bn,buildParticipantAvatarStyle:_n,buildParticipantAvatarClassName:on,resolveMessageParticipant:ca}=rS({payload:e,selectedChannel:t,activeAssignedCats:C,showBossCatAvatar:g,isDirectLane:F,isDefaultChatComposer:st}),Re=F?"direct_message":le.length>0?"participant_chat":"default_chat",[$e,xt]=p.useState(!1),[Ct,ln]=p.useState("cats"),[Fn,xn]=p.useState(null),[Qt,wn]=p.useState(""),[cn,Ea]=p.useState(()=>typeof window>"u"?1280:window.innerWidth),[Rt]=p.useState(()=>Wb(typeof window>"u"?null:window.localStorage)),[wt,kn]=p.useState(Rt.value),Pn=p.useRef(Rt.requiresPersistedCleanup),Wn=p.useCallback(K=>Hb({channelId:t.id,turnId:K.turnId,userDefault:Te.concurrentPresentationMode,segmentCount:K.segmentCount,viewportWidth:cn,uiStateByKey:wt}),[Te.concurrentPresentationMode,wt,t.id,cn]),da=p.useCallback(K=>K.resolvedMode==="inline_stack"?[]:[{key:`dismiss:${K.turnId}`,label:Ue(l.chatConcurrentClusterDismissActionLabel),title:Ue(l.chatConcurrentClusterDismissActionTitle),onSelect:()=>{kn(J=>$b(J,{channelId:t.id,turnId:K.turnId}))}}],[t.id]);function dn(K){xt(!0),ln(K)}const un=Qb({isDirectLane:F,directLaneCat:at,defaultRecipientCatRecord:sn,selectedChannelTitle:t.title,isCompareGroup:Ee,compareGroup:pe,t:Ue}),Da=Xb({isDirectLane:F,defaultRecipientCat:mt,showBossCatAvatar:g,isDefaultChatComposer:st,activeRoomParticipants:le}),Kn=p.useMemo(()=>Zb({activeRoomParticipants:le,bossCatId:e.chat.bossCatId,resolveParticipantCatRecord:gt,resolveParticipantDisplayName:we}),[le,e.chat.bossCatId,gt,we]),dt=p.useMemo(()=>zI(a,t),[a,t]),An=p.useMemo(()=>ex(t.messages),[t.messages]),se=p.useMemo(()=>({messageId:t.messages.slice().reverse().find(K=>K.senderKind==="user")?.id??null,status:(()=>{const K=t.messages.slice().reverse().find(ce=>ce.senderKind==="user")??null;if(!K)return"idle";const J=t.roomRouting.workflow.activeTurn??null,Nt=t.roomRouting.lastOutcome??null,Ae=t.messages.findIndex(ce=>ce.id===K.id),De=J?.sourceMessageId??null,it=De?t.messages.findIndex(ce=>ce.id===De):-1,_e=Me?.sourceMessageId??null,$t=(_e?_e===K.id:De===K.id)&&!!(Me?.speakerLabel||Me?.participantId||Me?.catId),mn=t.messages.some((ce,Ht)=>Ht>Ae&&ce.senderKind!=="user"&&ce.senderKind!=="system"&&!(ce.metadata?.verbosity==="verbose"&&Te.showVerboseMessages!==!0)),Xa=J?.targetStatuses?.map(ce=>ce.id)??[],Za=(J?.targetStatuses??[]).map(ce=>{const Ht=ce.laneId?.trim()||null;return Ht||(!J?.id||!ce.id?null:ns(J.id,ce.id,ce.participant.participantId))}).filter(ce=>ce!=null),ze=(J?.targetStatuses??[]).map(ce=>ce.participant.participantId).filter(ce=>typeof ce=="string"&&ce.length>0),gn=t.messages.some((ce,Ht)=>{if(Ht<=Ae||ce.metadata?.kind!=="session_start")return!1;const zn=typeof ce.metadata?.targetStateId=="string"?ce.metadata.targetStateId:null,ga=typeof ce.metadata?.laneId=="string"?ce.metadata.laneId:null,Ye=typeof ce.metadata?.participantId=="string"?ce.metadata.participantId:null;return zn!=null&&Xa.includes(zn)||ga!=null&&Za.includes(ga)||Ye!=null&&ze.includes(Ye)}),jn=(J?.targetStatuses??[]).filter(ce=>ce.status==="running"||ce.status==="completed"),Gn=jn.length>0&&(J?.workflowShape==="concurrent"||jn.some(ce=>ce.status==="completed")||jn.length>1),Vn=J?.sourceMessageId===K.id&&(J.status==="running"||J.status==="pending"),Xe=Ae>-1&&it>-1&&it<Ae&&(J?.status==="running"||J?.status==="pending");return(Vn&&!Gn||Xe)&&!$t&&(Xe||!mn&&!gn)?"processing":Nt?.sourceMessageId===K.id&&Nt.status==="error"?"failed":"idle"})()}),[Te.showVerboseMessages,t,Me]),Qe=p.useMemo(()=>dt?.runs.map(K=>K.id).join("|")??"",[dt]),kt=p.useMemo(()=>tx({visibleLiveIndicator:Me,selectedChannel:t,activeRoomParticipants:le}),[le,t,Me]),{activeTopBarCatIds:Kt,activeTopBarParticipantIds:ua,liveSpeakerParticipant:Rn}=kt,Ba=p.useCallback(K=>{if(K.participantId){const Ae=le.find(De=>De.participantId===K.participantId)??null;if(Ae)return Ae}const J=(()=>{const Ae=K.identityParticipantId?.trim()||null;return!Ae||Ae===K.participantId?null:Wm(K,t.messages)?Ae:null})();if(J){const Ae=le.find(De=>De.participantId===J)??null;if(Ae)return Ae}if(K.catId){const Ae=le.find(De=>gt(De)?.id===K.catId)??null;if(Ae)return Ae}if(K.phase==="sealed"){const Ae=Array.isArray(t.roomRouting.workflow.turnHistory)?t.roomRouting.workflow.turnHistory:[],De=[t.roomRouting.workflow.activeTurn,...Ae].filter(it=>it!=null).flatMap(it=>it.targetStatuses.map(_e=>({participantId:_e.participant.participantId,targetStateId:_e.id,laneId:_e.laneId?.trim()||ns(it.id,_e.id,_e.participant.participantId)}))).find(it=>K.targetStateId!=null&&it.targetStateId===K.targetStateId||K.laneId!=null&&it.laneId===K.laneId);if(De){const it=le.find(_e=>_e.participantId===De.participantId)??null;if(it)return it}}const Nt=K.speakerLabel?.trim();return Nt?le.find(Ae=>{const De=gt(Ae);return we(Ae,De)===Nt})??null:null},[le,gt,we,t.messages,t.roomRouting.workflow.activeTurn,t.roomRouting.workflow.turnHistory]),Nn=p.useMemo(()=>new Set(Kt),[Kt]),Oa=p.useMemo(()=>new Set(ua),[ua]),Ut=p.useMemo(()=>nx({isDirectLane:F,directLaneCat:at,isDefaultChatComposer:st,selectedExecutionTarget:L,defaultRecipientParticipant:xe,bossCatId:e.chat.bossCatId,resolveParticipantCatRecord:gt,resolveParticipantDisplayName:we}),[xe,at,F,st,e.chat.bossCatId,gt,we,L]),Xt=p.useMemo(()=>II(Re,cn),[Re,cn]),_a=p.useMemo(()=>({"--chat-transcript-max-width":Xt.transcriptMaxWidth}),[Xt.transcriptMaxWidth]),[Un,Tn]=p.useState(null);p.useEffect(()=>{Tn(K=>K&&dt?.runs.some(J=>J.id===K)?K:dt?.latestRun?.id??null)},[dt?.latestRun?.id,Qe]),p.useEffect(()=>{if(typeof window>"u")return;function K(){Ea(window.innerWidth)}return window.addEventListener("resize",K),()=>window.removeEventListener("resize",K)},[]),p.useEffect(()=>{if(typeof window>"u")return;if(!Pn.current){Pn.current=!0;return}const K=Ub(window.localStorage,wt);K!==wt&&kn(J=>J===wt?K:J)},[wt]);const $n=p.useMemo(()=>YI(dt,Un),[dt,Un]),{directLaneExecutionTarget:pn,directLaneExcludedMentionNames:Hn,composerBusy:hn,showCancelComposerAction:pa,showStopComposerAction:ha,composerWorkspacePath:Bt}=p.useMemo(()=>ax({activeRoomParticipants:le,directLaneCat:F?at:null,busy:d,isCompareGroup:Ee,selectedChannelId:t.id,onCancelPendingSend:P,onStopMessage:A,repoPath:t.repoPath,chatCwd:t.chatCwd,t:Ue}),[le,d,at,Ee,F,P,A,t.chatCwd,t.id,t.repoPath,Ue]),fa=In(d,"stop"),{transcriptListRef:Fa,composerCardRef:Wa,bottomSentinelRef:Ka,isNearBottom:fn,scrollToBottom:qn}=tS({channelId:t.id,scrollKey:lt,scrollOnChannelChange:!0,scopeKey:e.scopeId});sx(()=>{!Me?.active||!fn||qn()},[fn,qn,lt,Me?.active]);function Ua(K){xn(K.participantId),wn(K.name)}function ot(){xn(null),wn("")}async function $a(K){const J=Qt.trim();!J||!et||(await et(K,{name:J}),ot())}const Zt={payload:e,selectedChannel:t,activeAssignedCats:C,activeRoomParticipants:le,assignedCatRecords:Jt,assignedAdhocParticipants:rt,defaultRecipientParticipant:xe,defaultRecipientCat:mt,directLaneCat:at,directLaneExecutionTarget:pn,operatorView:dt,inspectedRun:$n,isDirectLane:F,isDefaultChatComposer:st,sidePanelOpen:$e,openSidePanelTo:dn},Ha={payload:e,composerBusy:hn,selectedExecutionTarget:L,composerRecipients:Ut,defaultRecipientParticipantId:xe?.participantId??null,composerStackParticipants:Kn,directLaneCat:at,defaultRecipientCat:mt,assignedCatRecords:Jt,leadCatRecord:sn,isDirectLane:F,isDefaultChatComposer:st,activeWorkflowShape:ke,onToggleActiveWorkflowShape:z,activeAudienceKeys:B,onSetActiveAudienceKeys:ae,onOpenSection:dn},qa=Oe?.(Ha)??r.jsx(Jd,{payload:e,composerBusy:hn,composerRecipients:Ut,defaultRecipientParticipantId:xe?.participantId??null,composerStackParticipants:Kn,directLaneCat:at,isDirectLane:F,isDefaultChatComposer:st,activeWorkflowShape:ke,onToggleActiveWorkflowShape:z,activeAudienceKeys:B,onSetActiveAudienceKeys:ae,onOpenSection:dn}),Ga=(_t??YS)({payload:e,selectedChannel:t,busy:d,operatorView:dt,operatorLoading:s,operatorError:o,assignedCatRecords:Jt,assignedAdhocParticipants:rt,defaultRecipientCatId:mt?.catId??null,defaultRecipientParticipant:xe,directLaneCat:at,directLaneExecutionTarget:pn,isDirectLane:F,isDefaultChatComposer:st,selectedExecutionTarget:L,inspectedRun:$n,showAddCatButton:G,editingParticipantId:Fn,editingParticipantName:Qt,canRenameParticipants:et!=null,onEditingParticipantNameChange:wn,onBeginParticipantRename:Ua,onCancelParticipantRename:ot,onSubmitParticipantRename:K=>{$a(K)},onOpenAddCat:Y,onCloseSidePanel:()=>xt(!1),onInspectRun:Tn,onApprovalDecision:b,onOperatorAction:H,onExecutionTargetChange:$,onStartFresh:O,onDirectLaneExecutionTargetChange:X,onDirectLaneParticipantTargetChange:et?(K,J)=>{et(K,{provider:J.provider,instance:J.instance,model:J.model,modelSelection:J.modelSelection})}:void 0,buildParticipantAvatarStyle:_n}),Va=ne?.(Zt)??null,Pt=re?.(Zt)??null,za=tt?.(Zt)??null,Ya=Ne?.(Zt)??null,Ja=Ot?.(Zt)??null,Qa=Yt?.(Zt)??null;function ma(K){const J=K==="prev"?ct:Et;!J||!he||he(J)}return r.jsxs(sS,{conversationMode:Pe,layoutMode:Re,composerVariant:Xt.composerVariant,secondarySurfacePosition:Xt.secondarySurfacePosition,layoutStyle:_a,hasConversationStarted:Ce,activeDirectCatId:F&&Ce?mt?.catId??null:null,topBar:r.jsx(oS,{avatars:Dt.map(K=>({key:K.key,label:K.label,executionLabel:K.executionLabel,avatarColor:K.avatarColor,avatarUrl:K.avatarUrl,isBoss:K.isBoss,useNeutralAvatar:K.useNeutralAvatar,pulsing:!!(K.pulseParticipantId&&Oa.has(K.pulseParticipantId)||K.pulseCatId&&Nn.has(K.pulseCatId))})),showRosterAvatars:Da,isDirectLane:F,topBarTitle:un,sidePanelOpen:$e,approvalCount:dt?.approvals.length??0,extraActions:Va,onToggleSidePanel:()=>xt(!$e),onOpenCatProfile:F&&mt?.catId?()=>fe(`/entities/cats/${encodeURIComponent(mt.catId)}`):void 0}),statusRow:Pt,sidePanel:$e?r.jsx(cc,{title:Le,activeSection:Ct,onSectionToggle:ln,onClose:()=>xt(!1),position:Xt.secondarySurfacePosition==="bottom"?"bottom":"side",className:"chatPaneSidePanel chatPaneSidePanelBelowBar",sections:Ga}):null,children:[r.jsx(jb,{hasConversationStarted:Ce,greeting:u,transcriptListRef:Fa,bottomSentinelRef:Ka,selectedChannel:t,visibleMessages:ye,workflow:t.roomRouting.workflow,cats:e.chat.cats,bossCatId:e.chat.bossCatId,selectedChannelId:t.id,disabledMentionNames:Hn,busy:d,compareBusy:Mt,isCompareGroup:Ee,choiceResponsesBySource:An,onChoiceSubmit:T,latestUserTurnMessageId:se.messageId,latestUserTurnStatus:se.status,onRetryMessage:E,onRelayMessage:Ke,liveIndicator:(()=>{if(kc()){const K=Fl(ue),J=Fl(Me),Nt=t.roomRouting.workflow.activeTurn?.updatedAt??null,Ae=ye.map(_e=>{const oe=_e.body?.trim().length??0,$t=oe===0?"∅":oe<40?"len"+oe:oe<400?"len~"+Math.floor(oe/40)*40:"len~"+Math.floor(oe/400)*400;return`${_e.senderKind}#${_e.id.slice(-6)}:${$t}`}).join(","),De=`raw=${K}|vis=${J}|turn=${Nt??"none"}|msgs=${Ae}`;if(Fr===null&&K==="inactive"&&J==="inactive")Fr=De,Wr=Date.now();else if(De!==Fr){const _e=Date.now(),oe=Wr!=null?_e-Wr:0;Fr=De,Wr=_e,console.log("[CV] li gap="+oe+"ms raw="+K+" vis="+J+" turn="+(Nt??"none")+" msgs["+ye.length+"]="+Ae+" nb="+(fn?"1":"0"))}}return Me??void 0})(),liveSpeakerParticipant:Rn,liveSpeakerParticipantCat:gt(Rn),resolveLiveIndicatorSegmentParticipant:Ba,messageStackTone:Yb,resolveMessageParticipant:ca,resolveParticipantCatRecord:gt,buildParticipantAvatarClassName:on,buildParticipantAvatarStyle:_n,resolveParticipantAvatarUrl:bn,resolveParticipantDisplayName:we,showLiveProgressDetails:Te.showLiveProgressDetails,resolveConcurrentClusterPresentationMode:Wn,buildConcurrentClusterActions:da,buildTranscriptMessageActions:V}),r.jsx(my,{hasConversationStarted:Ce,isCompareGroup:Ee,isNearBottom:fn,payload:e,composerDraft:i,channelFiles:h,channelPlusMenuOpen:f,channelPlusMenuRef:m,channelFileInputRef:v,composerBusy:hn,compareBusy:Mt,stopBusy:fa,composerWorkspacePath:Bt,directLaneExcludedMentionNames:Hn,composerRecipients:Ut,defaultRecipientParticipantId:xe?.participantId??null,composerStackParticipants:Kn,isDirectLane:F,isDefaultChatComposer:st,activeWorkflowShape:ke,onToggleActiveWorkflowShape:z,activeAudienceKeys:B,onSetActiveAudienceKeys:ae,compareSendScope:We,showCancelComposerAction:pa,showStopComposerAction:ha,composerCardRef:Wa,composerTargetSlot:qa,composerHeaderAccessory:za,composerHeaderWhereExtras:Ya,composerFooterAccessory:Ja,surfaceTag:Qa,onOpenSection:dn,onComposerChange:x,onComposerKeyDown:I,onSendMessage:k,onToggleChannelPlusMenu:M,onChannelFileSelect:D,onTakeScreenshot:N,screenshotCaptureDisabled:R,onChannelFilesChange:w,onScrollToBottom:qn,onCompareSendScopeChange:Z,onCancelPendingSend:P,onStopMessage:A,autoResize:U}),ft.length>1&&he?r.jsx(Cy,{compareMembers:ft,selectedChannelId:Wt,comparePrevChannelId:ct,compareNextChannelId:Et,onSelect:he,onNavigatePrev:()=>ma("prev"),onNavigateNext:()=>ma("next")}):null]})}const Bw=Dh,Wl={full:"sharedPermissionModeFullAccess",read_only:"sharedPermissionModeReadOnly"},ox=["full","read_only"];function ix({value:e,onChange:t,disabled:n}){const{t:a}=Q(),[s,o]=p.useState(!1),i=p.useRef(null);return p.useEffect(()=>{if(!s)return;function d(u){i.current&&!i.current.contains(u.target)&&o(!1)}function c(u){u.key==="Escape"&&o(!1)}return document.addEventListener("mousedown",d),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",c)}},[s]),r.jsxs("div",{className:"composerSelectChipWrapper composerPermissionChipWrapper",ref:i,children:[r.jsxs("button",{type:"button",className:"composerSelectChip composerPermissionChip",disabled:n,"aria-haspopup":"listbox","aria-expanded":s,onClick:()=>o(d=>!d),children:[r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M8 1.5l5.5 2v4c0 3.3-2.4 6.2-5.5 7-3.1-.8-5.5-3.7-5.5-7v-4z"})}),r.jsx("span",{children:a(l[Wl[e]])}),r.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2.5 4 5 6.5 7.5 4"})})]}),s?r.jsx("div",{className:"composerSelectChipMenu",role:"listbox",children:ox.map(d=>{const c=d===e;return r.jsxs("button",{type:"button",role:"option","aria-selected":c,className:`composerSelectChipMenuItem${c?" composerSelectChipMenuItemSelected":""}`,onClick:()=>{t(d),o(!1)},children:[r.jsx("span",{className:"composerSelectChipMenuItemCheck","aria-hidden":"true",children:c?r.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2.5 6.5 4.8 8.8 9.5 3.5"})}):null}),r.jsx("span",{children:a(l[Wl[d]])})]},d)})}):null]})}function lx(e,t){return`shadow-${e}-${t.provider}-${t.instance??""}-${t.model??""}`}function ou(e){return{dismissed:!1,lastResetKey:e}}function cx(e,t){return e.lastResetKey===t?e:ou(t)}function dx(e){return e.dismissed?e:{...e,dismissed:!0}}function ux(e){return e.availableChipCount>0&&!e.dismissed}function px(e){return e.length===0?null:JSON.stringify(e.map(t=>[t.id,t.prompt,t.label??null]))}function hx(e){if(e.isDirectLaneContext)return{runtimeChipsRendered:!1,fallbackChipsRendered:!1};const t=e.runtimeChipCount>0;return{runtimeChipsRendered:e.showDraftHelperChips&&t,fallbackChipsRendered:!t&&e.fallbackChipCount>0}}function fx(e){const[t,n]=p.useState(()=>ou(e.resetKey));t.lastResetKey!==e.resetKey&&n(s=>cx(s,e.resetKey));const a=p.useCallback(()=>{n(dx)},[]);return{showDraftHelperChips:ux({availableChipCount:e.availableChipCount,dismissed:t.dismissed}),dismissDraftHelperChips:a}}function mx({folderBrowsePath:e,folderBrowseCurrentPath:t,folderBrowseParentPath:n,folderBrowseEntries:a,folderBrowseLoading:s,folderBrowseError:o,onPathChange:i,onBrowse:d,onSelect:c}){const{t:u}=Q();return r.jsxs("div",{className:"folderBrowserInline",children:[r.jsxs("div",{className:"folderBrowserPathRow",children:[r.jsx("input",{className:"folderBrowserPathInput",type:"text",value:e,onChange:h=>i(h.target.value),onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),d(e))},placeholder:u("sharedFolderBrowserEnterPath")}),r.jsx("button",{className:"folderBrowserNavButton",type:"button",onClick:()=>d(e),disabled:s,"aria-label":u("sharedFolderBrowserGo"),"data-tooltip":u("sharedFolderBrowserGo"),children:r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M3 8h10"}),r.jsx("path",{d:"M9 4l4 4-4 4"})]})})]}),r.jsxs("div",{className:"folderBrowserToolbar",children:[r.jsx("button",{className:"folderBrowserNavButton",type:"button",onClick:()=>d(n),disabled:s||!n||n===t,"aria-label":u("sharedFolderBrowserUpOneLevel"),"data-tooltip":u("sharedFolderBrowserUpOneLevel"),children:r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 13V3"}),r.jsx("path",{d:"M3 7l5-5 5 5"})]})}),r.jsx("button",{className:"folderBrowserNavButton",type:"button",onClick:()=>d(t),disabled:s||!t,"aria-label":u("sharedFolderBrowserRefresh"),"data-tooltip":u("sharedFolderBrowserRefresh"),children:r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M13.5 2.5v4h-4"}),r.jsx("path",{d:"M2.5 8a5.5 5.5 0 0 1 9.37-3.87L13.5 6.5"}),r.jsx("path",{d:"M2.5 13.5v-4h4"}),r.jsx("path",{d:"M13.5 8a5.5 5.5 0 0 1-9.37 3.87L2.5 9.5"})]})}),r.jsx("span",{className:"folderBrowserCurrentPath","data-tooltip":t,children:t||u("sharedFolderBrowserLoading")})]}),r.jsx("div",{className:"folderBrowserListScroll",role:"list",children:s?r.jsx("div",{className:"folderBrowserStatus",children:u("sharedFolderBrowserLoading")}):a.length>0?a.map(h=>r.jsxs("button",{className:"folderBrowserEntry",type:"button",onClick:()=>d(h.path),role:"listitem",children:[r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2 4v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H8L6.5 3H3a1 1 0 0 0-1 1z"})}),r.jsx("span",{children:h.name})]},h.path)):r.jsx("div",{className:"folderBrowserStatus",children:o||u("sharedFolderBrowserNoSubdirectories")})}),o?r.jsx("p",{className:"folderBrowserError",children:o}):null,r.jsx("div",{className:"folderBrowserFooter folderBrowserFooterSticky",children:r.jsx("button",{className:"folderBrowserPrimaryButton",type:"button",onClick:c,disabled:!t||!!o,children:u("sharedFolderBrowserUseThisFolder")})})]})}const gx=e=>({title:e(l.chatNewChatDraftSidePanelTitle),participants:{catsSectionTitle:e(l.chatNewChatDraftSidePanelParticipantsCatsTitle),groupSectionTitle:e(l.chatNewChatDraftSidePanelParticipantsGroupTitle),emptyState:e(l.chatNewChatDraftSidePanelParticipantsEmptyState)},execution:{sectionTitle:e(l.chatNewChatDraftSidePanelExecutionTitle),emptyState:e(l.chatNewChatDraftSidePanelExecutionEmptyState)},folder:{sectionTitle:e(l.chatNewChatDraftSidePanelFolderTitle),emptyState:e(l.chatNewChatDraftSidePanelFolderEmptyState)}});function iu(e,t){const n=gx(t);return{title:e?.title??n.title,participants:{...n.participants,...e?.participants},execution:{...n.execution,...e?.execution},folder:{...n.folder,...e?.folder}}}function Cx(e){const t=[],{t:n}=e,a=iu(e.sidePanelCopy,n);t.push({id:"cats",title:e.isGroupDraft?a.participants.groupSectionTitle:a.participants.catsSectionTitle,children:r.jsxs("div",{className:"sidePanelSectionStack",children:[e.isGroupDraft?r.jsx("p",{className:"operatorEmptyState",style:{margin:0},children:e.groupDraftSelectionLabel}):null,e.chatCats.filter(o=>o.status==="active").length>0?r.jsx(yo,{cats:e.chatCats,bossCatId:e.payload.chat.bossCatId,selectedIds:e.draftCatIds,highlightedId:e.draftHighlightedCatId,defaultRecipientCatId:e.effectiveDefaultRecipientCat?.id??null,toggleable:!0,onToggle:e.onToggleDraftCat,onHighlight:o=>e.onHighlightDraftCat(o)}):r.jsx("p",{className:"operatorEmptyState",children:a.participants.emptyState}),e.isGroupDraft?r.jsxs(r.Fragment,{children:[e.assistantPresets.length>0?r.jsx("div",{className:"addCatList",children:e.assistantPresets.map(o=>{const i=If(e.draftTemporaryParticipants,o.id),d=hf({provider:o.executionTarget.provider,instance:o.executionTarget.instance,model:o.executionTarget.model},void 0,n);let c=n(l.chatNewChatDraftAssistantPresetAdd);return d.requiresActivationReview?c=n(l.chatNewChatDraftAssistantPresetReview):i&&(c=n(l.chatNewChatDraftAssistantPresetAdded)),r.jsxs("div",{className:"addCatItem",children:[r.jsxs("div",{children:[r.jsx("strong",{children:o.name}),r.jsx("p",{children:Zr({provider:o.executionTarget.provider,instance:o.executionTarget.instance,model:o.executionTarget.model})}),r.jsxs("p",{children:[d.capabilityLabel," | ",d.policySummary," | ",d.toolGrantSummary]}),o.roleHint?r.jsx("p",{children:o.roleHint}):null]}),r.jsx("button",{className:"addCatAssignButton",type:"button",title:d.reviewReasons.join(", ")||void 0,disabled:e.isSubmittingFirstTurn||i||e.hasReachedGroupParticipantLimit||d.requiresActivationReview,onClick:()=>e.onAddDraftTemporaryParticipant(ff(o)),children:c})]},o.id)})}):null,e.draftTemporaryParticipants.length>0?r.jsx("div",{className:"addCatList",children:e.draftTemporaryParticipants.map(o=>r.jsxs("div",{className:"addCatItem",children:[r.jsxs("div",{children:[r.jsx("strong",{children:o.name}),r.jsx("p",{children:Zr(o)}),o.roleHint?r.jsx("p",{children:o.roleHint}):null,e.editingTemporaryParticipantId===o.participantId?r.jsxs("form",{className:"stackForm",onSubmit:i=>{i.preventDefault(),e.onSubmitTemporaryParticipantRename(o.participantId)},children:[r.jsxs("label",{className:"fieldLabel",children:[r.jsx("span",{children:n(l.chatNewChatDraftTemporaryParticipantNameLabel)}),r.jsx("input",{className:"textInput",value:e.editingTemporaryParticipantName,onChange:i=>e.onEditingTemporaryParticipantNameChange(i.target.value),placeholder:n(l.chatNewChatDraftTemporaryParticipantNamePlaceholder)})]}),r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{type:"button",className:"operatorActionButton",onClick:e.onCancelTemporaryParticipantRename,children:n(l.chatNewChatDraftTemporaryParticipantCancel)}),r.jsx("button",{type:"submit",className:"primaryButton",disabled:!e.editingTemporaryParticipantName.trim(),children:n(l.chatNewChatDraftTemporaryParticipantSaveName)})]})]}):null]}),r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{className:"addCatAssignButton",type:"button",disabled:e.isSubmittingFirstTurn,onClick:()=>e.onBeginTemporaryParticipantRename(o),children:n(l.chatNewChatDraftTemporaryParticipantRename)}),r.jsx("button",{className:"addCatAssignButton addCatRemoveButton",type:"button",disabled:e.isSubmittingFirstTurn,onClick:()=>{e.editingTemporaryParticipantId===o.participantId&&e.onCancelTemporaryParticipantRename(),e.onRemoveDraftTemporaryParticipant(o.participantId)},children:n(l.chatNewChatDraftTemporaryParticipantRemove)})]})]},o.participantId))}):null,e.temporaryParticipantFormOpen&&!e.hasReachedGroupParticipantLimit?r.jsxs("form",{className:"stackForm",onSubmit:o=>{o.preventDefault(),e.onSubmitTemporaryParticipant()},children:[r.jsx("p",{className:"operatorEmptyState",style:{margin:0},children:n(l.chatNewChatDraftTemporaryParticipantNameHint)}),r.jsxs("label",{className:"fieldLabel",children:[r.jsx("span",{children:n(l.chatNewChatDraftTemporaryParticipantRoleHintLabel)}),r.jsx("input",{className:"textInput",value:e.temporaryParticipantForm.roleHint,onChange:o=>e.onTemporaryParticipantFormChange(i=>({...i,roleHint:o.target.value})),placeholder:n(l.chatNewChatDraftTemporaryParticipantRoleHintPlaceholder)})]}),r.jsx(na,{provider:e.temporaryParticipantForm.provider,instance:e.temporaryParticipantForm.instance,model:e.temporaryParticipantForm.model,modelSelection:e.temporaryParticipantForm.modelSelection,onTargetChange:o=>{e.onTemporaryParticipantFormChange(i=>({...i,provider:o.provider,instance:o.instance,model:o.model,modelSelection:o.modelSelection??null}))}}),r.jsxs("div",{style:{display:"flex",gap:8},children:[r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>{e.onTemporaryParticipantFormChange(e.createTemporaryParticipantFormValue),e.onTemporaryParticipantFormOpenChange(!1)},children:n(l.chatNewChatDraftTemporaryParticipantCancel)}),r.jsx("button",{type:"submit",className:"primaryButton",disabled:e.hasReachedGroupParticipantLimit||!e.temporaryParticipantForm.provider.trim(),children:n(l.chatNewChatDraftTemporaryParticipantSubmit)})]})]}):e.hasReachedGroupParticipantLimit?null:r.jsx("button",{type:"button",className:"operatorActionButton",disabled:e.isSubmittingFirstTurn,onClick:()=>e.onTemporaryParticipantFormOpenChange(!0),children:n(l.chatNewChatDraftTemporaryParticipantOpenForm)})]}):null]})});const s=e.isDirectLaneContext&&e.defaultRecipientCat&&e.activePanelExecutionTarget?r.jsxs(r.Fragment,{children:[r.jsx(yo,{cats:[e.defaultRecipientCat],bossCatId:e.payload.chat.bossCatId,selectedIds:[e.defaultRecipientCat.id],highlightedId:e.defaultRecipientCat.id,defaultRecipientCatId:e.defaultRecipientCat.id,toggleable:!1,onToggle:()=>{},onHighlight:()=>{}}),r.jsx(na,{provider:e.activePanelExecutionTarget.provider,instance:e.activePanelExecutionTarget.instance??"",model:e.activePanelExecutionTarget.model??"",modelSelection:e.activePanelExecutionTarget.modelSelection,onTargetChange:o=>{e.onDirectLaneExecutionTargetChange?.(e.defaultRecipientCat.id,wa(o))}})]}):e.activePanelExecutionTarget?r.jsx("div",{style:e.effectiveDefaultRecipientCat&&!e.isDirectLaneContext?{pointerEvents:"none",opacity:.45}:void 0,children:r.jsx(na,{provider:e.activePanelExecutionTarget.provider,instance:e.activePanelExecutionTarget.instance??"",model:e.activePanelExecutionTarget.model??"",modelSelection:e.activePanelExecutionTarget.modelSelection,onTargetChange:o=>{!e.effectiveDefaultRecipientCat&&e.onExecutionTargetChange&&e.onExecutionTargetChange(wa(o))}})}):r.jsx("p",{className:"operatorEmptyState",children:a.execution.emptyState});return t.push({id:"execution",title:a.execution.sectionTitle,children:s}),e.isParallelMode&&e.parallelTargets&&e.parallelTargets.forEach((o,i)=>{t.push({id:`parallel:${i}`,title:Jo(o),children:r.jsx(na,{provider:o.provider,instance:o.instance??"",model:o.model??"",modelSelection:o.modelSelection,onTargetChange:d=>{e.onParallelTargetChange?.(i,wa(d))}})})}),t.push({id:"cwd",title:a.folder.sectionTitle,children:e.onFolderBrowsePathChange&&e.onFolderBrowse&&e.onFolderBrowseSelect?r.jsx(mx,{folderBrowsePath:e.folderBrowsePath??"",folderBrowseCurrentPath:e.folderBrowseCurrentPath??"",folderBrowseParentPath:e.folderBrowseParentPath??"",folderBrowseEntries:e.folderBrowseEntries??[],folderBrowseLoading:e.folderBrowseLoading??!1,folderBrowseError:e.folderBrowseError??"",onPathChange:e.onFolderBrowsePathChange,onBrowse:e.onFolderBrowse,onSelect:()=>{e.onFolderBrowseSelect?.(),e.onCloseSidePanel()}}):e.draftCwd?r.jsx("p",{style:{margin:0,fontSize:"0.85rem",wordBreak:"break-all"},children:e.draftCwd}):r.jsx("p",{className:"operatorEmptyState",children:a.folder.emptyState})}),t}function Kl({size:e=14}){return r.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("circle",{cx:"6",cy:"5",r:"2.5"}),r.jsx("path",{d:"M1.5 13c0-2.5 2-4.5 4.5-4.5s4.5 2 4.5 4.5"}),r.jsx("path",{d:"M13 4v4"}),r.jsx("path",{d:"M11 6h4"})]})}function lu({size:e=14}){return r.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M1.5 4C1.5 3.17 2.17 2.5 3 2.5H8.5C9.33 2.5 10 3.17 10 4V9C10 9.83 9.33 10.5 8.5 10.5H5L3 12.5V10.5C2.17 10.5 1.5 9.83 1.5 9V4Z"}),r.jsx("path",{d:"M13 4v4"}),r.jsx("path",{d:"M11 6h4"})]})}function vx({accessory:e=null,showParallelAddButton:t=!1,hideParallelHint:n=!1,accentParallelAddButton:a=!1,disabled:s=!1,onAddParallelTarget:o}){const{t:i}=Q(),d=t&&o!=null;return!e&&!d?null:r.jsxs("div",{className:"composerFooterRow",children:[e?r.jsx("div",{className:"composerFooterAccessory",children:e}):null,d?r.jsxs("div",{className:"parallelAddRow parallelAddRowInline",children:[n?null:r.jsx("span",{className:`parallelAddHint${a?" parallelAddHintAccent":""}`,children:i(l.chatNewChatDraftBranchAddCompareHint)}),r.jsx("button",{type:"button",className:`parallelAddButton${a?" parallelAddButtonAccent":""}`,disabled:s,onClick:o,"aria-label":i(l.chatNewChatDraftBranchAddParallelAria),children:r.jsx(lu,{})})]}):null]})}function Ul({audienceParticipants:e,isSubmittingFirstTurn:t,canRemoveParticipant:n,useDangerRemoveHover:a=!1,onAvatarClick:s,onRemoveParticipant:o}){const{t:i}=Q();return e.length<=1?null:r.jsx(r.Fragment,{children:e.map(d=>r.jsxs("div",{className:"composerGroupAvatarSlot",children:[r.jsx("div",{className:"catAvatar",role:t?void 0:"button",tabIndex:t?void 0:0,onClick:t?void 0:s,"data-tooltip":d.isCat&&d.executionLabel?`${d.name} · ${d.executionLabel}`:d.executionLabel||d.name,style:d.avatarUrl?{backgroundImage:`url(${d.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:d.isCat?{background:d.avatarColor??"#8B7E74"}:{background:"#fff",color:"#222",border:"1px solid rgba(0, 0, 0, 0.15)"},children:d.avatarUrl?null:At(d.name)}),n?r.jsx("button",{type:"button",className:`composerGroupAvatarRemove${a?" composerGroupAvatarRemoveDanger":""}`,"aria-label":i(l.chatAudienceRemoveParticipantAria,{name:d.name}),disabled:t,onClick:()=>o(d),children:"×"}):null]},d.key))})}function Ix({cards:e,activeIndex:t,onActiveIndexChange:n,disabled:a=!1,ariaLabel:s}){const{t:o}=Q(),i=e.length,d=s??o(l.chatDraftCompareCarouselAriaLabel),c=p.useCallback(()=>{a||n(Math.max(0,t-1))},[t,a,n]),u=p.useCallback(()=>{a||n(Math.min(i-1,t+1))},[t,a,n,i]);function h(f){f.target instanceof HTMLTextAreaElement||f.target instanceof HTMLInputElement||(f.key==="ArrowLeft"?(f.preventDefault(),c()):f.key==="ArrowRight"&&(f.preventDefault(),u()))}return i===0?null:r.jsxs("div",{className:"draftCompareCarousel",role:"region","aria-label":d,onKeyDown:h,children:[r.jsx("div",{className:"draftCompareCarouselTrack",children:e.map((f,m)=>r.jsx(Sx,{active:m===t,relative:m-t,disabled:a,onPromote:m===t||a?void 0:()=>n(m),children:f.content},f.id))}),i>1?r.jsx("div",{className:"draftCompareCarouselDots","aria-label":o(l.chatDraftCompareCarouselSelectBranchAria),children:e.map((f,m)=>r.jsx("button",{type:"button",className:`draftCompareCarouselDot${m===t?" draftCompareCarouselDotActive":""}`,onClick:()=>n(m),disabled:a,"aria-label":o(l.chatDraftCompareCarouselGoToBranchAria,{branchIndex:`${m+1}`}),"aria-current":m===t?"true":void 0},f.id))}):null]})}function Sx({active:e,relative:t,disabled:n,onPromote:a,children:s}){const o=Math.abs(t),i=t===0?0:t>0?1:-1,d=i*(88+(o-1)*28),c=-i*(38+(o-1)*10),u=Math.max(.38,.55-(o-1)*.12),h=Math.max(.1,.64-(o-1)*.28),f=e?1e3:Math.max(1,900-o*10),m=e?{zIndex:f}:{transform:`translate(${d}%, 0) rotateY(${c}deg) scale(${u.toFixed(3)})`,opacity:h.toFixed(3),zIndex:f},v=e?"draftCompareCarouselCard draftCompareCarouselCardActive":"draftCompareCarouselCard draftCompareCarouselCardPeek";function C(S){e||n||!a||S.target instanceof HTMLElement&&S.target.closest('button, textarea, input, [role="button"]')||a()}return r.jsx("div",{className:v,style:m,"aria-hidden":e?void 0:!0,onClick:C,children:s})}function yx(e){const t=(e.parallelTargetCount??0)>=2,n=e.entryPreset==="group"||e.participantCount>1,a=!e.allowAddCat&&!!e.draftDefaultRecipientCatId&&e.hasDefaultRecipientCat;return{mode:t?"parallel":n?"group":"default",isGroupDraft:n,isDirectLaneContext:a}}function bx(e){return(e??[]).reduce((t,n)=>{const a=n?.id?.trim()??"",s=n?.prompt?.trim()??"";return!a||!s||t.push({id:a,prompt:s}),t},[])}function xx(e){return bx(e.suggestions)}function wx(e){const t=e.payload.chat.newChatAssist??null;if(!t)return{greeting:null,starterSuggestions:void 0};const n=!e.isDirectLaneContext&&t.bundle.provenance.originMode==="runtime";return{greeting:Bh(t,e.t),starterSuggestions:n?t.bundle.content.entryChips.map(a=>({id:a.id,prompt:a.prompt})):void 0}}function kx(e){const t=e.payload.chat.cats.filter(Xl),n=e.payload.assistantPresets??[],a=t.filter(R=>R.status==="active"),s=ed({draftDefaultRecipientCatId:e.draftDefaultRecipientCatId,draftCatIds:e.draftCatIds}),o=e.draftDefaultRecipientCatId?t.find(R=>R.id===e.draftDefaultRecipientCatId&&R.status==="active")??null:null,i=!!(o&&e.payload.chat.botBindings.some(R=>R.platform==="telegram"&&R.status==="active"&&R.catId===o.id)),d=!o&&e.draftCatIds.length>0?t.find(R=>R.id===s.effectiveDefaultRecipientCatId&&R.status==="active")??null:null,c=o??d,u=c?null:e.draftTemporaryParticipants[0]??null,h=s.participantCatIds.length+e.draftTemporaryParticipants.length,f=e.payload.chat.capabilities.maxChatParticipants??Number.POSITIVE_INFINITY,m=h>=f,v=yx({allowAddCat:e.allowAddCat,draftDefaultRecipientCatId:e.draftDefaultRecipientCatId,hasDefaultRecipientCat:!!c,entryPreset:e.entryPreset,participantCount:h,parallelTargetCount:e.parallelTargets?.length??0}),C=wx({payload:e.payload,isDirectLaneContext:v.isDirectLaneContext,t:e.t}),S=s.participantCatIds,y=v.isDirectLaneContext?[]:C.starterSuggestions??[],g=xx({suggestions:y}),x=(()=>{const R=e.greeting?.trim();if(R)return R;const w=C.greeting?.trim();return w||bf({pool:e.greetingPool,t:e.t})})(),I=h===1?e.t(l.chatNewChatDraftGroupDraftSelectionLabelSingle):h>1?e.t(l.chatNewChatDraftGroupDraftSelectionLabelCount,{count:h}):a.length>0||n.length>0?e.t(l.chatNewChatDraftGroupDraftSelectionLabelWithCatsOrAssistants):e.t(l.chatNewChatDraftGroupDraftSelectionLabelWithSettings),k=e.draftHighlightedCatId&&e.draftCatIds.includes(e.draftHighlightedCatId)?t.find(R=>R.id===e.draftHighlightedCatId)??null:null,P=v.isDirectLaneContext&&o?e.draftCatExecutionTargetOverrides.get(o.id)??{provider:o.defaultExecutionTarget.provider,model:o.defaultExecutionTarget.model,instance:o.defaultExecutionTarget.instance,modelSelection:o.defaultModelSelection??null}:k?e.draftCatExecutionTargetOverrides.get(k.id)??{provider:k.defaultExecutionTarget.provider,model:k.defaultExecutionTarget.model,instance:k.defaultExecutionTarget.instance,modelSelection:k.defaultModelSelection??null}:e.selectedExecutionTarget??null,A=qc(e.busy),M=Qm(e.busy)||A,D=c?[Gb(c,e.payload.chat.bossCatId)]:u?[vr({participantId:u.participantId,name:u.name,provider:u.provider,instance:u.instance??null,model:u.model??null})]:[],N=[...S.map(R=>t.find(w=>w.id===R)).filter(R=>R!=null&&R.name.length>0).map(R=>si(R)),...e.draftTemporaryParticipants.map(R=>Yd(R))];return{chatCats:t,assistantPresets:n,activeChatCats:a,draftParticipants:s,defaultRecipientCat:o,hasTelegramBinding:i,effectiveDefaultRecipientCat:c,effectiveDefaultRecipientTemporaryParticipant:u,draftParticipantCount:h,maxGroupParticipants:f,hasReachedGroupParticipantLimit:m,draftSuggestionContext:v,visibleDraftCatIds:S,visibleStarterSuggestions:g,resolvedGreeting:x,groupDraftSelectionLabel:I,activePanelExecutionTarget:P,isAckPending:A,isSubmittingFirstTurn:M,draftComposerRecipients:D,groupComposerParticipants:N}}function Px(e){return e.section==="cwd"&&!e.skipSectionAction&&!e.folderBrowseCurrentPath&&!e.folderBrowseLoading}function Ax(e){function t(){return{roleHint:"",provider:e.payload.chat.newChatDefaults?.provider??"claude",instance:e.payload.chat.newChatDefaults?.instance??"",model:e.payload.chat.newChatDefaults?.model??"",modelSelection:e.payload.chat.newChatDefaults?.modelSelection??null}}const[n,a]=p.useState(!1),[s,o]=p.useState("cats"),[i,d]=p.useState(!1),[c,u]=p.useState(null),[h,f]=p.useState(""),[m,v]=p.useState(t);function C(k){o(k),Px({section:k,folderBrowseCurrentPath:e.folderBrowseCurrentPath,folderBrowseLoading:e.folderBrowseLoading})&&e.onPickFolder()}function S(k,P){if(a(!0),P?.skipSectionAction){o(k);return}C(k)}function y(){if(e.hasReachedGroupParticipantLimit||!m.provider.trim())return;const k=[...e.visibleDraftCatIds.map(P=>e.chatCats.find(A=>A.id===P)?.name??""),...e.draftTemporaryParticipants.map(P=>P.name)].filter(P=>P.trim().length>0);e.onAddDraftTemporaryParticipant(Mn({provider:m.provider.trim(),instance:m.instance.trim()||void 0,model:m.model.trim()||void 0,modelSelection:m.modelSelection,roleHint:m.roleHint.trim()||void 0,takenNames:k})),v(t()),d(!1)}function g(k){u(k.participantId),f(k.name)}function x(){u(null),f("")}function I(k){const P=h.trim();P&&(e.onUpdateDraftTemporaryParticipant(k,{name:P}),x())}return{createTemporaryParticipantFormValue:t,sidePanelOpen:n,setSidePanelOpen:a,sidePanelSection:s,switchSection:C,openSidePanelTo:S,temporaryParticipantFormOpen:i,setTemporaryParticipantFormOpen:d,editingTemporaryParticipantId:c,editingTemporaryParticipantName:h,setEditingTemporaryParticipantName:f,temporaryParticipantForm:m,setTemporaryParticipantForm:v,submitTemporaryParticipant:y,beginTemporaryParticipantRename:g,cancelTemporaryParticipantRename:x,submitTemporaryParticipantRename:I}}const Ow=Oh,$l={current:l.sharedWorkspaceModeCurrentLabel,worktree:l.sharedWorkspaceModeWorktreeLabel},Rx={current:l.sharedWorkspaceModeCurrentTooltip,worktree:l.sharedWorkspaceModeWorktreeTooltip},Nx=["current","worktree"];function Tx({value:e,onChange:t,disabled:n}){const{t:a}=Q(),[s,o]=p.useState(!1),i=p.useRef(null);return p.useEffect(()=>{if(!s)return;function d(u){i.current&&!i.current.contains(u.target)&&o(!1)}function c(u){u.key==="Escape"&&o(!1)}return document.addEventListener("mousedown",d),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",d),document.removeEventListener("keydown",c)}},[s]),r.jsxs("div",{className:"composerSelectChipWrapper composerWorkspaceModeChipWrapper",ref:i,children:[r.jsxs("button",{type:"button",className:"composerSelectChip composerWorkspaceModeChip",disabled:n,"aria-haspopup":"listbox","aria-expanded":s,"data-tooltip":a(Rx[e]),onClick:()=>o(d=>!d),children:[r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 2 2 5l6 3 6-3-6-3z"}),r.jsx("path",{d:"M2 8l6 3 6-3"}),r.jsx("path",{d:"M2 11l6 3 6-3"})]}),r.jsx("span",{children:a($l[e])}),r.jsx("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2.5 4 5 6.5 7.5 4"})})]}),s?r.jsx("div",{className:"composerSelectChipMenu",role:"listbox",children:Nx.map(d=>{const c=d===e;return r.jsxs("button",{type:"button",role:"option","aria-selected":c,className:`composerSelectChipMenuItem${c?" composerSelectChipMenuItemSelected":""}`,onClick:()=>{t(d),o(!1)},children:[r.jsx("span",{className:"composerSelectChipMenuItemCheck","aria-hidden":"true",children:c?r.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2.5 6.5 4.8 8.8 9.5 3.5"})}):null}),r.jsx("span",{children:a($l[d])})]},d)})}):null]})}function jx(e){const[t,n]=p.useState({isRepo:!1,repoRoot:null,branch:null});return p.useEffect(()=>{if(!e){n({isRepo:!1,repoRoot:null,branch:null});return}const a=new AbortController;return sf(e,a.signal).then(s=>{a.signal.aborted||n({isRepo:!!s.isRepo,repoRoot:s.repoRoot??null,branch:s.branch??null})}).catch(()=>{a.signal.aborted||n({isRepo:!1,repoRoot:null,branch:null})}),()=>{a.abort()}},[e]),t}function to(e,t){const n=e.workspaceKind==="worktree"?t(l.chatNewChatDraftBranchPolicyWorkspaceWorktree):e.workspaceKind==="source"?t(l.chatNewChatDraftBranchPolicyWorkspaceSource):t(l.chatNewChatDraftBranchPolicyWorkspaceSandbox),a=e.workspaceAccess==="read_only"?t(l.chatNewChatDraftBranchPolicyAccessReadOnly):t(l.chatNewChatDraftBranchPolicyAccessFull);return`${n} / ${a}`}function Lx(e){return Kh({repoPath:e.target.cwd??e.draftCwd,policy:e.target.runtimeSessionPolicy??e.draftRuntimeSessionPolicy??jo()})}function Mx({branchIndex:e,target:t,draftCwd:n,draftRuntimeSessionPolicy:a,isSubmittingFirstTurn:s,onSetParallelBranchRuntimeSessionPolicy:o}){const{t:i}=Q(),d=t.runtimeSessionPolicy??null,c=o!=null,u=t.cwd??n,{isRepo:h,repoRoot:f}=jx(u),m=!!(u&&h&&f),v=Lx({target:t,draftCwd:n,draftRuntimeSessionPolicy:a});function C(S){const y=t.runtimeSessionPolicy??v;o?.(e,Uh({workspaceKind:y.workspaceKind,workspaceAccess:y.workspaceAccess,permissionMode:y.permissionMode,...S}))}return d&&c?r.jsxs("div",{className:"composerBranchPolicyControl","data-tooltip":to(d,i),children:[m?r.jsx(Tx,{value:Fh(d.workspaceKind),onChange:S=>C({workspaceKind:_h({hasCwd:!!u,isRepo:m,workspaceMode:S})}),disabled:s}):null,r.jsx(ix,{value:Wh(d.workspaceAccess),onChange:S=>C($h(S)),disabled:s}),r.jsx("button",{className:"composerChipClose",type:"button",disabled:s,onClick:()=>o(e,null),"aria-label":i(l.chatNewChatDraftBranchPolicyRelinkAria),children:"×"})]}):d?r.jsxs("span",{className:"composerSelectChip composerPermissionChip composerBranchPolicyChip","data-tooltip":to(d,i),children:[r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r.jsx("path",{d:"M8 1.5l5.5 2v4c0 3.3-2.4 6.2-5.5 7-3.1-.8-5.5-3.7-5.5-7v-4z"})}),r.jsx("span",{children:to(d,i)})]}):c?r.jsxs("button",{type:"button",className:"composerFollowsLeadChip composerFollowsLeadChipClickable",disabled:s,onClick:()=>o(e,v),"aria-label":i(l.chatNewChatDraftBranchPolicyDetachAria),children:[r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r.jsx("path",{d:"M8 1.5l5.5 2v4c0 3.3-2.4 6.2-5.5 7-3.1-.8-5.5-3.7-5.5-7v-4z"})}),r.jsx("span",{children:i(l.chatNewChatDraftBranchPolicyFollowsLeadLabel)})]}):null}function _w({payload:e,composerDraft:t,busy:n,greeting:a=null,greetingPool:s=null,draftFiles:o,draftCwd:i,draftCatIds:d,draftTemporaryParticipants:c,plusMenuOpen:u,plusMenuRef:h,fileInputRef:f,bossCatName:m,bossCatAvatarColor:v,onComposerChange:C,onComposerKeyDown:S,onSendMessage:y,onCancelPendingSend:g,onTogglePlusMenu:x,onFileSelect:I,onTakeScreenshot:k,screenshotCaptureDisabled:P=!1,onPickFolder:A,onOpenAddCat:M,onDraftFilesChange:D,onDraftCwdClear:N,onToggleDraftCat:R,onAddDraftTemporaryParticipant:w,onQuickAddDraftTemporaryParticipant:b,onRemoveDraftTemporaryParticipant:T,onUpdateDraftTemporaryParticipant:E,autoResize:O,draftDefaultRecipientCatId:H,entryPreset:U="default",onDraftDefaultRecipientChange:L,allowAddCat:$=!0,selectedExecutionTarget:X,onExecutionTargetChange:ke,draftHighlightedCatId:z,onHighlightDraftCat:B,draftCatExecutionTargetOverrides:ae,onDraftCatExecutionTargetOverride:he,onDirectLaneExecutionTargetChange:Y,parallelTargets:G,onParallelTargetChange:W,onAddParallelTarget:ue,onRemoveParallelTarget:pe,parallelBranchActions:We,builderControls:Z,folderBrowsePath:Ke="",folderBrowseCurrentPath:et="",folderBrowseParentPath:V="",folderBrowseEntries:re=[],folderBrowseLoading:ne=!1,folderBrowseError:Oe="",onFolderBrowsePathChange:tt,onFolderBrowse:Ne,onFolderBrowseSelect:Ot,draftWorkflowShape:Yt="sequential",onToggleDraftWorkflowShape:_t,draftAudienceKeys:nt,onSetAudienceKeys:Ue,draftRuntimeSessionPolicy:fe=null,onDraftRuntimeSessionPolicyChange:Le,onCatAvatarSave:Te,draftChrome:ye,draftCopy:Ce,starterChips:Ft,sidePanel:Me}){const lt=Ta(),{headerAccessory:Pe=null,headerWhereExtras:ht=null,footerAccessory:ft=null,customRegion:Ee=null,surfaceTag:Wt=null,chooseFolderPlacement:Lt="header"}=ye??{},{showGroupAddButton:Mt=!1,showParallelAddButton:ct=!1,hideGroupHint:Et=!1,hideParallelHint:st=!1}=Z??{},{t:F}=Q(),le=Ce?.composerPlaceholder??F(l.chatNewChatDraftComposerPlaceholder),xe=Ce?.folderActionLabel??F(l.chatNewChatDraftFolderActionLabel),mt=Ce?.sidePanel,at=Ft?.leading,sn=Ft?.preserveOnSelect??!1,Jt=We?.onPickFolder,rt=We?.onSetAudienceKeys,Dt=We?.onSetCwd,gt=We?.onSetRuntimeSessionPolicy,we=We?.onToggleWorkflowShape,bn=We?.onQuickAddTemporaryParticipant,_n=iu(mt,F),on=Me?.title??_n.title,ca=Me?.buildSections??(_=>Cx(_)),Re=(G?.length??0)>=2,[$e,xt]=p.useState(0),Ct=G?.length??0;p.useEffect(()=>{if(!Re){$e!==0&&xt(0);return}$e>=Ct&&xt(Math.max(0,Ct-1))},[$e,Re,Ct]);const[ln,Fn]=p.useState(!1),xn=p.useRef($e);p.useEffect(()=>{if(xn.current===$e)return;xn.current=$e,Fn(!0);const _=setTimeout(()=>Fn(!1),200);return()=>clearTimeout(_)},[$e]);const Qt=e.chat.capabilities.maxAudienceParticipants??3,wn=e.chat.capabilities.maxChatParticipants??Number.POSITIVE_INFINITY,{chatCats:cn,assistantPresets:Ea,defaultRecipientCat:Rt,effectiveDefaultRecipientCat:wt,effectiveDefaultRecipientTemporaryParticipant:kn,draftParticipantCount:Pn,hasReachedGroupParticipantLimit:Wn,draftSuggestionContext:da,visibleDraftCatIds:dn,visibleStarterSuggestions:un,resolvedGreeting:Da,groupDraftSelectionLabel:Kn,activePanelExecutionTarget:dt,isAckPending:An,isSubmittingFirstTurn:se,groupComposerParticipants:Qe}=kx({payload:e,draftDefaultRecipientCatId:H,draftCatIds:d,draftTemporaryParticipants:c,allowAddCat:$,entryPreset:U,parallelTargets:G,greeting:a,greetingPool:s,draftHighlightedCatId:z,draftCatExecutionTargetOverrides:ae,selectedExecutionTarget:X,busy:n,t:F}),{isGroupDraft:kt,isDirectLaneContext:Kt}=da,{supported:ua,listening:Rn,toggle:Ba,textareaRef:Nn,toasts:Oa,privacyMessage:Ut}=Vd({value:t,onChange:C,autoResize:O,disabled:se}),Xt=px(un),{showDraftHelperChips:_a,dismissDraftHelperChips:Un}=fx({availableChipCount:un.length,resetKey:Xt});function Tn(_){return _.length<=Qt?_:_.slice(0,Qt)}const $n={draftAudienceKeys:nt??null,draftWorkflowShape:Yt??"sequential"};function pn(_){const ie=G?.[_];return ie?md(ie,$n):[]}function Hn(_){const ie=G?.[_];return ie?gd(ie,$n):"sequential"}function hn(_){const ie=pn(_);if(Qe.length===0||ie.length===0)return[];const be=new Map(Qe.map(ut=>[ut.key,ut]));return ie.map(ut=>be.get(ut)).filter(Boolean)}function pa(_,ie){const be=hn(_);return be.length===0?[zr(ie,`parallel:${_}`)]:Tn(be)}const ha=(()=>{if(Re&&G?.[0])return pa(0,G[0]);if(kt){if(!nt)return Tn(Qe);const _=new Map(Qe.map(be=>[be.key,be])),ie=nt.map(be=>_.get(be)).filter(Boolean);return ie.length>0?Tn(ie):Qe.length>0?[Qe[0]]:[]}return wt?[si(wt)]:kn?[Yd(kn)]:dt?[zr(dt)]:[]})(),Bt=Re&&Qe.length>0&&pn(0).length>0,fa=Re?hn(0):[],Fa=(()=>{if(!kt)return Re?Bt?()=>ot("cats"):()=>ot("parallel:0"):Kt?()=>ot("execution"):wt||kn?()=>ot("cats"):()=>ot("execution")})(),{createTemporaryParticipantFormValue:Wa,sidePanelOpen:Ka,setSidePanelOpen:fn,sidePanelSection:qn,switchSection:Ua,openSidePanelTo:ot,temporaryParticipantFormOpen:$a,setTemporaryParticipantFormOpen:Zt,editingTemporaryParticipantId:Ha,editingTemporaryParticipantName:qa,setEditingTemporaryParticipantName:Ga,temporaryParticipantForm:Va,setTemporaryParticipantForm:Pt,submitTemporaryParticipant:za,beginTemporaryParticipantRename:Ya,cancelTemporaryParticipantRename:Ja,submitTemporaryParticipantRename:Qa}=Ax({payload:e,folderBrowseCurrentPath:et,folderBrowseLoading:ne,onPickFolder:A,hasReachedGroupParticipantLimit:Wn,visibleDraftCatIds:dn,chatCats:cn,draftTemporaryParticipants:c,onAddDraftTemporaryParticipant:w,onUpdateDraftTemporaryParticipant:E}),ma=An&&g!=null,K=!Kt&&(kt||Mt),J=Re?pn(0).length:Qe.length,Nt=Re?J<wn:!Wn,Ae=Re?J:Qe.length,De=!se&&(U==="group"?Ae>2:Ae>=2);function it(_){return!se&&_>=2}const _e=U==="parallel"?2:1,oe=U==="group",$t=U==="group",mn=U==="parallel",Xa=e.chat.capabilities.maxParallelChats??3;function Za(_){return Nt?r.jsxs("div",{className:_.className??"composerGroupAddRow",children:[r.jsx("button",{type:"button",className:`parallelAddButton${_.accent?" parallelAddButtonAccent":""}`,disabled:se,onClick:()=>{if(b){b();return}ot("cats")},"aria-label":F(l.chatNewChatDraftCollaborateAria),children:r.jsx(Kl,{})}),_.showHint?r.jsx("span",{className:`parallelAddHint${_.accent?" parallelAddHintAccent":""}`,children:F(l.chatNewChatDraftCollaborateHint)}):null]}):null}const ze=Kt&&Rt?r.jsx(xi,{variant:"profile",title:Rt.name,avatarName:Rt.name,avatarUrl:Rt.avatarUrl,avatarColor:Rt.avatarColor,coverStorageKey:Rt.id,readOnlyVisuals:!0,actions:r.jsxs("button",{type:"button",className:"draftHeaderAction",onClick:()=>lt(`/entities/cats/${encodeURIComponent(Rt.id)}`),children:[r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z"}),r.jsx("circle",{cx:"12",cy:"12",r:"3"})]}),F(l.chatNewChatDraftViewCatProfileAction)]})}):r.jsx(xi,{variant:"intro",title:Da}),gn=r.jsxs("div",{className:"composerHeaderRow",children:[r.jsxs("div",{className:"composerHeaderLeft",children:[Wt,i?r.jsxs("span",{className:"composerCwdChip composerCwdClickable","data-tooltip":i,role:"button",tabIndex:se?void 0:0,onClick:se?void 0:()=>ot("cwd"),children:[r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2 4v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H8L6.5 3H3a1 1 0 0 0-1 1z"})}),r.jsx("span",{children:io(i)}),r.jsx("button",{className:"composerChipClose",type:"button",disabled:se,onClick:_=>{_.stopPropagation(),N()},"aria-label":F(l.chatNewChatDraftRemoveFolderAria),children:"×"})]}):Lt==="header"?r.jsxs("button",{type:"button",className:"composerHeaderChooseButton",disabled:se,onClick:()=>ot("cwd"),children:[r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2 4v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H8L6.5 3H3a1 1 0 0 0-1 1z"})}),r.jsx("span",{children:xe})]}):null,ht]}),Pe?r.jsx("div",{className:"composerHeaderRight",children:Pe}):null]}),jn=(G?.length??0)>=2&&pe?r.jsx("button",{type:"button",className:`composerCardBranchRemove${mn?" composerCardBranchRemoveAccent":""}`,disabled:se||(G?.length??0)<=_e,onClick:()=>pe(0),"aria-label":F(l.chatNewChatDraftBranchRemoveAria,{branchIndex:1}),children:r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:r.jsx("path",{d:"M4 4l8 8M12 4l-8 8"})})}):null,Gn=r.jsxs("form",{className:`composerCard composerCardFresh${G?" parallelComposerAnchor":""}${u?" composerCardMenuOpen":""}`,onSubmit:_=>{y(_)},children:[jn,o.length>0?r.jsx("div",{className:"composerAttachments",children:o.map((_,ie)=>{const be=_.type.startsWith("image/");return r.jsxs("div",{className:"attachmentCard",children:[r.jsx("button",{className:"attachmentRemove",type:"button",disabled:se,onClick:()=>D(o.filter((ut,yt)=>yt!==ie)),"aria-label":F(l.chatNewChatDraftAttachmentRemoveAria,{fileName:_.name}),children:"×"}),be?r.jsx("img",{className:"attachmentPreview",src:URL.createObjectURL(_),alt:_.name,onLoad:ut=>URL.revokeObjectURL(ut.target.src)}):r.jsx("div",{className:"attachmentFileIcon",children:r.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"}),r.jsx("path",{d:"M14 2v6h6"})]})}),r.jsx("span",{className:"attachmentName",children:_.name})]},`${_.name}-${_.size}-${ie}`)})}):null,r.jsx("textarea",{ref:Nn,className:"composerInput",rows:1,placeholder:le,value:t,disabled:se,onChange:_=>{C(_.target.value),O(_.target)},onKeyDown:_=>{S(_)}}),r.jsxs("div",{className:"composerBottomRow",children:[r.jsxs("div",{className:"composerLeftGroup",children:[r.jsxs("div",{className:"composerPlusWrapper",ref:h,children:[r.jsx("button",{className:"composerPlusButton",type:"button","aria-label":F(l.chatNewChatDraftBranchAttachAria),disabled:se,onClick:x,children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 3v10"}),r.jsx("path",{d:"M3 8h10"})]})}),u?r.jsxs("div",{className:"composerPlusMenu",children:[r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:se,onClick:I,children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M14 10v3a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1v-3"}),r.jsx("path",{d:"M8 2v8"}),r.jsx("path",{d:"M4 6l4-4 4 4"})]}),F(l.chatNewChatDraftAddPhotosAndFiles)]}),k?r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:se||P,onClick:k,children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M5 3.5l1-1h4l1 1h2a1 1 0 0 1 1 1v7.5a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V4.5a1 1 0 0 1 1-1h2z"}),r.jsx("circle",{cx:"8",cy:"8.5",r:"2.5"})]}),F(l.chatNewChatDraftTakeScreenshot)]}):null,Lt==="plusMenu"?r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:se,onClick:()=>{ot("cwd")},children:[r.jsx("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"M2 4v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H8L6.5 3H3a1 1 0 0 0-1 1z"})}),xe]}):null]}):null]}),K?r.jsxs("div",{className:"composerGroupAddRow",children:[r.jsx(Ul,{audienceParticipants:Re?fa:Qe,isSubmittingFirstTurn:se,canRemoveParticipant:De,useDangerRemoveHover:oe,onAvatarClick:()=>ot("cats"),onRemoveParticipant:_=>{if(Re){if(!rt)return;const ie=fa.filter(be=>be.key!==_.key).map(be=>be.key);rt(0,ie);return}_.isCat&&_.catId?R(_.catId):_.participantId&&T(_.participantId)}}),Za({showHint:!Et,accent:$t})]}):null]}),r.jsxs("div",{className:"composerRightGroup",children:[ha.length>0?r.jsx(ka,{audienceParticipants:ha,allParticipants:Re&&Bt||kt?Qe:void 0,onSetAudienceKeys:Re&&Bt?rt?_=>rt(0,_):void 0:kt?Ue:void 0,onSingleClick:Fa,disabled:se,maxSelectedParticipants:Re&&Bt||kt?Qt:void 0,workflowShape:Re?Hn(0):Yt,onToggleWorkflowShape:Re&&Bt?we?()=>we(0):void 0:kt?_t:void 0}):null,ua?r.jsxs("button",{className:`composerPlusButton composerVoiceButton${Rn?" composerVoiceButtonActive":""}`,type:"button","aria-label":Rn?F(l.chatNewChatDraftStopVoiceInputAria,{privacyMessageSuffix:Ut?`. ${Ut}`:""}):F(l.chatNewChatDraftStartVoiceInputAria),"aria-pressed":Rn,title:Ut??void 0,disabled:se,onClick:Ba,children:[r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("rect",{x:"6",y:"2",width:"4",height:"8",rx:"2"}),r.jsx("path",{d:"M3 8a5 5 0 0 0 10 0"}),r.jsx("path",{d:"M8 13v2"}),r.jsx("path",{d:"M6 15h4"})]}),Ut?r.jsx("span",{className:"composerVoicePrivacyBadge","aria-hidden":"true",children:"!"}):null]}):null,ma?r.jsx("button",{className:"composerSendButton composerCancelButton",type:"button","aria-label":F(l.chatNewChatDraftCancelSendAria),onClick:()=>g?.(),children:r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M4 4l6 6"}),r.jsx("path",{d:"M10 4l-6 6"})]})}):r.jsx("button",{className:"composerSendButton",disabled:!t.trim()&&o.length===0||se||kt&&Pn<2,type:"submit","aria-label":F(Re?l.chatNewChatDraftSendAllChatsAria:l.chatNewChatDraftSendAria),children:Re?r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M4 13V6"}),r.jsx("path",{d:"M1 9l3-3 3 3"}),r.jsx("path",{d:"M12 13V6"}),r.jsx("path",{d:"M9 9l3-3 3 3"})]}):r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 13V3"}),r.jsx("path",{d:"M3 7l5-5 5 5"})]})})]})]}),r.jsx("input",{ref:f,type:"file",multiple:!0,disabled:se,style:{display:"none"},onChange:_=>{const ie=_.currentTarget;if(ie.files&&ie.files.length>0){const be=Array.from(ie.files);D([...o,...be])}ie.value=""}})]}),Vn=p.useRef(!1);p.useEffect(()=>{!Vn.current||Ct<=0||(Vn.current=!1,xt(Ct-1))},[Ct]);const Xe=ue?()=>{Vn.current=!0,ue()}:void 0,ce=p.useRef(!1);p.useEffect(()=>{if(!ce.current||$e!==0)return;ce.current=!1;const _=Nn.current;if(!_)return;const ie=requestAnimationFrame(()=>{_.focus();const be=_.value.length;_.setSelectionRange(be,be)});return()=>cancelAnimationFrame(ie)},[$e,Nn]);function Ht(){ce.current=!0,xt(0)}const zn=r.jsx(vx,{accessory:ft,disabled:se}),ga=(()=>{const{runtimeChipsRendered:_,fallbackChipsRendered:ie}=hx({isDirectLaneContext:Kt,showDraftHelperChips:_a,runtimeChipCount:un.length,fallbackChipCount:at?.length??0});return!_&&!ie?null:r.jsx("div",{className:"draftPromptSuggestions",children:r.jsxs("div",{className:"chipRow",children:[ie?at?.map(be=>r.jsx("button",{className:"promptChip draftPromptChip",type:"button",disabled:se,onClick:()=>{sn||Un(),be.onClick()},children:be.label},be.id)):null,_?un.map(be=>r.jsx("button",{className:"promptChip draftPromptChip",type:"button",disabled:se,onClick:()=>{sn||Un(),C(be.prompt)},children:be.prompt},be.id)):null]})})})(),Ye=Ka?r.jsx(cc,{title:on,activeSection:qn,onSectionToggle:se?()=>{}:Ua,onClose:se?()=>{}:()=>fn(!1),className:"chatPaneSidePanel",sections:ca({t:F,payload:e,chatCats:cn,draftCatIds:d,draftHighlightedCatId:z,effectiveDefaultRecipientCat:wt,isGroupDraft:kt,isDirectLaneContext:Kt,isParallelMode:Re,groupDraftSelectionLabel:Kn,assistantPresets:Ea,draftTemporaryParticipants:c,editingTemporaryParticipantId:Ha,editingTemporaryParticipantName:qa,temporaryParticipantFormOpen:$a,temporaryParticipantForm:Va,hasReachedGroupParticipantLimit:Wn,isSubmittingFirstTurn:se,defaultRecipientCat:Rt,activePanelExecutionTarget:dt,onToggleDraftCat:R,onHighlightDraftCat:B,onAddDraftTemporaryParticipant:w,onRemoveDraftTemporaryParticipant:T,onBeginTemporaryParticipantRename:Ya,onCancelTemporaryParticipantRename:Ja,onSubmitTemporaryParticipantRename:Qa,onEditingTemporaryParticipantNameChange:Ga,onTemporaryParticipantFormChange:_=>Pt(ie=>_(ie)),createTemporaryParticipantFormValue:Wa,onTemporaryParticipantFormOpenChange:Zt,onSubmitTemporaryParticipant:za,selectedExecutionTarget:X,onExecutionTargetChange:ke,onDirectLaneExecutionTargetChange:Y,parallelTargets:G,onParallelTargetChange:W,folderBrowsePath:Ke,folderBrowseCurrentPath:et,folderBrowseParentPath:V,folderBrowseEntries:re,folderBrowseLoading:ne,folderBrowseError:Oe,draftCwd:i,onFolderBrowsePathChange:tt,onFolderBrowse:Ne,onFolderBrowseSelect:Ot,draftRuntimeSessionPolicy:fe,onDraftRuntimeSessionPolicyChange:Le,onCloseSidePanel:()=>fn(!1),sidePanelCopy:_n})}):null;function Tt(_,ie,be=null){const ut=pn(_).length,yt=hn(_),va=ut>1?pa(_,ie):[zr(ie,`parallel:${_}`)],tr=ut<wn&&bn!=null,Ts=Hn(_),js=Ct>_e,nr=ie.cwd?.trim()||null;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"composerHeaderRow",children:r.jsxs("div",{className:"composerHeaderLeft",children:[Wt,nr?r.jsxs("span",{className:"composerCwdChip","data-tooltip":nr,children:[r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r.jsx("path",{d:"M2 4v9a1 1 0 0 0 1 1h10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1H8L6.5 3H3a1 1 0 0 0-1 1z"})}),r.jsx("span",{children:io(nr)}),Dt?r.jsx("button",{className:"composerChipClose",type:"button",disabled:se,onClick:()=>Dt(_,null),"aria-label":F(l.chatNewChatDraftBranchFolderRelinkAria),children:"×"}):null]}):Jt?r.jsxs("button",{type:"button",className:"composerFollowsLeadChip composerFollowsLeadChipClickable",disabled:se,onClick:()=>{Jt(_),ot("cwd",{skipSectionAction:!0})},"aria-label":F(l.chatNewChatDraftBranchFolderChooseAria),children:[r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M6 3l-3 5 3 5"}),r.jsx("path",{d:"M3 8h10"})]}),r.jsx("span",{children:F(l.chatNewChatDraftBranchFollowsLeadLabel)})]}):r.jsxs("span",{className:"composerFollowsLeadChip",children:[r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:[r.jsx("path",{d:"M6 3l-3 5 3 5"}),r.jsx("path",{d:"M3 8h10"})]}),r.jsx("span",{children:F(l.chatNewChatDraftBranchFollowsLeadLabel)})]}),r.jsx(Mx,{branchIndex:_,target:ie,draftCwd:i,draftRuntimeSessionPolicy:fe??null,isSubmittingFirstTurn:se,onSetParallelBranchRuntimeSessionPolicy:gt})]})}),r.jsxs("div",{className:"draftBranchFormAnchor",children:[r.jsxs("form",{className:"composerCard composerCardFresh parallelComposerAnchor",onSubmit:Cn=>Cn.preventDefault(),children:[pe?r.jsx("button",{type:"button",className:`composerCardBranchRemove${mn?" composerCardBranchRemoveAccent":""}`,disabled:se||!js,onClick:()=>pe(_),"aria-label":F(l.chatNewChatDraftBranchRemoveAria,{branchIndex:_+1}),children:r.jsx("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.8",strokeLinecap:"round","aria-hidden":"true",children:r.jsx("path",{d:"M4 4l8 8M12 4l-8 8"})})}):null,r.jsx("textarea",{className:"composerInput composerInputJumpToLead",rows:1,placeholder:le,value:t,disabled:se,readOnly:!0,"data-tooltip":F(l.chatNewChatDraftBranchPromptJumpToLeadTitle),"aria-label":F(l.chatNewChatDraftBranchPromptJumpToLeadAria),onClick:se?void 0:()=>Ht(),onFocus:se?void 0:Cn=>{Cn.currentTarget.blur(),Ht()}}),r.jsxs("div",{className:"composerBottomRow",children:[r.jsxs("div",{className:"composerLeftGroup",children:[r.jsx("div",{className:"composerPlusWrapper",children:r.jsx("button",{type:"button",className:"composerPlusButton","aria-label":F(l.chatNewChatDraftBranchAttachAria),disabled:!0,children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M8 3v10"}),r.jsx("path",{d:"M3 8h10"})]})})}),yt.length>0||tr?r.jsxs("div",{className:"composerGroupAddRow",children:[yt.length>0?r.jsx(Ul,{audienceParticipants:yt,isSubmittingFirstTurn:se,canRemoveParticipant:it(yt.length),useDangerRemoveHover:oe,onAvatarClick:()=>ot("cats"),onRemoveParticipant:Cn=>{if(!rt)return;const Ls=yt.filter(ar=>ar.key!==Cn.key).map(ar=>ar.key);rt(_,Ls)}}):null,tr?r.jsx("button",{type:"button",className:"parallelAddButton",disabled:se,onClick:()=>bn(_),"aria-label":F(l.chatNewChatDraftBranchCollaborateAria),children:r.jsx(Kl,{})}):null]}):null]}),r.jsx("div",{className:"composerRightGroup",children:r.jsx(ka,{audienceParticipants:va,allParticipants:ut>1?Qe:void 0,onSetAudienceKeys:ut>1&&rt?Cn=>rt(_,Cn):void 0,onSingleClick:()=>ot("cats"),disabled:se,maxSelectedParticipants:Qt,workflowShape:Ts,onToggleWorkflowShape:we?()=>we(_):void 0})})]})]}),be]})]})}const Ca=Math.max(Ct,1),qt=Ca-1,vt=Ca<Xa,er=_=>{if(_!==$e)return null;const ie=$e>0,be=$e<qt,ut=$e===qt&&vt&&!!Xe;if(!ie&&!be&&!ut)return null;const yt=ln&&Ca>1,va=Rr=>`draftCompareCarouselNav ${Rr}${yt?" draftCompareCarouselNavDelayed":""}`;return r.jsxs(r.Fragment,{children:[ie?r.jsx("button",{type:"button",className:va("draftCompareCarouselNavPrev"),onClick:()=>xt(Math.max(0,$e-1)),disabled:se,"aria-label":F(l.chatDraftCompareCarouselPreviousBranchAria),children:r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("polyline",{points:"15 18 9 12 15 6"})})}):null,ut?r.jsxs("div",{className:`draftCompareCarouselAddBranchSlot${yt?" draftCompareCarouselAddBranchSlotDelayed":""}`,children:[r.jsx("button",{type:"button",className:`draftCompareCarouselNav draftCompareCarouselAddBranch${mn?" draftCompareCarouselAddBranchAccent":""}`,onClick:Xe,disabled:se,"aria-label":F(l.chatNewChatDraftBranchAddParallelAria),children:r.jsx(lu,{})}),mn?r.jsx("span",{className:"parallelAddHint parallelAddHintAccent",children:F(l.chatNewChatDraftBranchAddCompareHint)}):null]}):be?r.jsx("button",{type:"button",className:va("draftCompareCarouselNavNext"),onClick:()=>xt(Math.min(qt,$e+1)),disabled:se,"aria-label":F(l.chatDraftCompareCarouselNextBranchAria),children:r.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("polyline",{points:"9 18 15 12 9 6"})})}):null]})},Ar=Re&&Array.isArray(G)&&G.length>=2?G.map((_,ie)=>ie===0?{id:`lead-${_.provider}-${_.instance??""}-${_.model??""}`,content:r.jsxs(r.Fragment,{children:[gn,r.jsxs("div",{className:"draftBranchFormAnchor",children:[Gn,er(0)]}),zn]})}:{id:lx(ie,_),content:Tt(ie,_,er(ie))}):[{id:"lead-only",content:r.jsxs(r.Fragment,{children:[gn,r.jsxs("div",{className:"draftBranchFormAnchor",children:[Gn,er(0)]}),zn]})}];return r.jsxs("div",{className:"viewShell viewShellDraft",children:[r.jsxs("section",{className:"draftShell",children:[ze,Ee?r.jsx("div",{className:"draftCustomRegion",children:Ee}):null,r.jsx(Ix,{cards:Ar,activeIndex:$e,onActiveIndexChange:xt,disabled:se}),ga]}),Ye,r.jsx(Do,{toasts:Oa})]})}const Ex={chat:"sharedComposerSurfaceLabelChat",work:"sharedComposerSurfaceLabelWork",code:"sharedComposerSurfaceLabelCode"};function Dx(e){const t={width:12,height:12,viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:1.6,strokeLinecap:"round",strokeLinejoin:"round"};return e==="code"?r.jsxs("svg",{...t,"aria-hidden":"true",children:[r.jsx("path",{d:"M5 4L2 8l3 4"}),r.jsx("path",{d:"M11 4l3 4-3 4"}),r.jsx("path",{d:"M9.5 3l-3 10"})]}):e==="work"?r.jsxs("svg",{...t,"aria-hidden":"true",children:[r.jsx("rect",{x:"2",y:"5",width:"12",height:"8",rx:"1.5"}),r.jsx("path",{d:"M6 5V3.5A1 1 0 0 1 7 2.5h2a1 1 0 0 1 1 1V5"})]}):r.jsx("svg",{...t,"aria-hidden":"true",children:r.jsx("path",{d:"M3 5a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H7l-3 2v-2a1 1 0 0 1-1-1V5z"})})}function Fw({surface:e,onDismiss:t,disabled:n=!1}){const{t:a}=Q(),s=a(l[Ex[e]]);return r.jsxs("span",{className:`composerSurfaceChip composerSurfaceChip${Bx(e)}`,children:[Dx(e),r.jsx("span",{children:s}),t?r.jsx("button",{type:"button",className:"composerChipClose",disabled:n,onClick:t,"aria-label":a(l.sharedComposerSurfaceClearAria,{surfaceLabel:s}),children:"×"}):null]})}function Bx(e){return e.charAt(0).toUpperCase()+e.slice(1)}const cu=["code_task","code_codespace","work_item","work_project","work_task","chat_conversation"],du=["auto","iframe","image","pdf","code"],Ox="/api/canvas/intents/stream",_x="/api/canvas/intents/ack",uu={code_task:"/code/tasks",code_codespace:"/code/codespaces",work_item:"/work/work-items",work_project:"/work/projects",work_task:"/work/tasks",chat_conversation:"/chat/chats"},xo={parentUrl(e){return As(e)},canvasUrl(e,t,n="auto"){return pu(e,t,n)},projectionApiUrl(e,t,n="auto"){return hu(e,t,n)},parse(e){return Wx(e)},parseProjectionApiPath(e){return Kx(e)}};function Fx(e){Rs(e);const t=new URLSearchParams({surfaceKind:e.kind,surfaceId:e.surfaceId});return`${Ox}?${t.toString()}`}function As(e){return Rs(e),`${uu[e.kind]}/${encodeURIComponent(e.surfaceId)}`}function pu(e,t,n="auto"){Rs(e);const a=li(t,"artifactId"),o=`${As(e)}/canvas/${encodeURIComponent(a)}`;return n==="auto"?o:`${o}/view/${n}`}function hu(e,t,n="auto"){Rs(e);const a=li(t,"artifactId"),s=`/api/canvas/${encodeURIComponent(e.kind)}/${encodeURIComponent(e.surfaceId)}/artifacts/${encodeURIComponent(a)}`;return n==="auto"?s:`${s}/view/${n}`}function Wx(e){const t=wo(e);for(const n of cu){const a=wo(uu[n]);if(!$x(t,a))continue;const s=t[a.length];if(!s||t.length<a.length+1)continue;const o={kind:n,surfaceId:decodeURIComponent(s)},i=As(o);if(t.length===a.length+1)return{kind:"parent",surface:o,parentUrl:i};if(t[a.length+1]==="canvas")return fu({surface:o,parentUrl:i,tail:t.slice(a.length+2),composeCanvas:!0})}return null}function Kx(e){const t=wo(e);if(t.length!==6&&t.length!==8||t[0]!=="api"||t[1]!=="canvas"||t[4]!=="artifacts")return null;const n=decodeURIComponent(t[2]??"");if(!mu(n))return null;const a=t[3];if(!a)return null;const s={kind:n,surfaceId:decodeURIComponent(a)},o=As(s);return fu({surface:s,parentUrl:o,tail:t.slice(5),composeCanvas:!1})}function fu(e){const t=e.tail[0];if(!t)return null;let n="auto";if(e.tail.length===3){if(e.tail[1]!=="view"||!Ux(e.tail[2]))return null;n=e.tail[2]}else if(e.tail.length!==1)return null;return{kind:"canvas",surface:e.surface,parentUrl:e.parentUrl,canvasUrl:e.composeCanvas?pu(e.surface,decodeURIComponent(t),n):hu(e.surface,decodeURIComponent(t),n),artifactId:decodeURIComponent(t),presentationRequested:n}}function Rs(e){if(!mu(e.kind))throw new Error(`Unsupported canvas surface kind: ${e.kind}`);li(e.surfaceId,"surfaceId")}function li(e,t){const n=Hx(e);if(!n)throw new Error(`${t} is required.`);return n}function mu(e){return cu.includes(e)}function Ux(e){return du.includes(e)}function wo(e){return e.split("?")[0].split("/").filter(Boolean)}function $x(e,t){return e.length<t.length?!1:t.every((n,a)=>e[a]===n)}function Hx(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ns(e){const t=e?.trim();if(!t)return null;let n;try{n=new URL(t)}catch{return null}return n.protocol==="http:"||n.protocol==="https:"?t:null}function qx({projection:e}){const{t}=Q(),[n,a]=p.useState(()=>e.textContent!==null?{status:"ready",text:e.textContent}:e.safeUrl?{status:"loading"}:{status:"unsupported"});return p.useEffect(()=>{if(e.textContent!==null){a({status:"ready",text:e.textContent});return}const s=Ns(e.safeUrl);if(!s){a({status:"unsupported"});return}let o=!1;return a({status:"loading"}),fetch(s).then(async i=>{if(!i.ok)throw new Error("Unable to load text artifact.");return i.text()}).then(i=>{o||a({status:"ready",text:i})}).catch(()=>{o||a({status:"unsupported"})}),()=>{o=!0}},[e.safeUrl,e.textContent]),n.status==="loading"?r.jsx("div",{className:"artifactCanvasState",children:t(l.sharedArtifactCanvasLoading)}):n.status==="unsupported"?r.jsx("div",{className:"artifactCanvasUnsupported",children:t(l.sharedArtifactCanvasUnsupportedBody)}):r.jsx("pre",{className:"artifactCanvasCodeBlock",children:r.jsx("code",{children:n.text})})}function Gx({projection:e}){const{t}=Q(),n=Ns(e.safeUrl);return n?r.jsx("figure",{className:"artifactCanvasImageFrame",children:r.jsx("img",{className:"artifactCanvasImage",src:n,alt:e.artifact.title,loading:"lazy",decoding:"async"})}):r.jsx("div",{className:"artifactCanvasUnsupported",children:t(l.sharedArtifactCanvasUnsupportedBody)})}const Vx={name:"static",sandbox:"",referrerPolicy:"no-referrer",allow:""};function zx({projection:e,title:t,safeUrl:n,iframeSandboxProfile:a,className:s="artifactCanvasIframe"}){const{t:o}=Q(),i=Yx({title:e?.artifact.title??t??"Artifact",safeUrl:e?.safeUrl??n??null,iframeSandboxProfile:e?.iframeSandboxProfile??a??null});return i.status==="unsupported"?r.jsx("div",{className:"artifactCanvasUnsupported",children:o(l.sharedArtifactCanvasUnsupportedBody)}):r.jsx("iframe",{className:s,title:i.title,src:i.safeUrl,sandbox:i.profile.sandbox,referrerPolicy:i.profile.referrerPolicy,allow:i.profile.allow})}function Yx(e){const t=Ns(e.safeUrl),n=e.iframeSandboxProfile;if(!t||!n)return{status:"unsupported"};if(n.name!=="static"&&n.name!=="scripted-cross-origin")return{status:"unsupported"};const a=typeof window>"u"?null:window.location.origin,s=new URL(t),o=n.name==="scripted-cross-origin"&&a===s.origin?Vx:n;return{status:"ok",title:e.title,safeUrl:t,profile:o}}function Jx({projection:e}){const{t}=Q(),n=Ns(e.safeUrl);return n?r.jsx("object",{className:"artifactCanvasPdf",data:n,type:"application/pdf","aria-label":e.artifact.title,children:r.jsx("a",{className:"operatorActionButton",href:n,target:"_blank",rel:"noreferrer",children:t(l.sharedArtifactCanvasOpenExternal)})}):r.jsx("div",{className:"artifactCanvasUnsupported",children:t(l.sharedArtifactCanvasUnsupportedBody)})}function gu(e,t,n,a){return t==="artifact"&&e!==null&&e!==void 0&&e===n&&e===a}function Qx(e,t){return gu(e,t.kind,t.id,t.state.artifact.id)}function Xx(e,t){return gu(e,t.kind,t.id,t.patch.artifactId)}function Hl(){const e=Ta(),{artifactId:t,presentation:n}=dc(),{t:a}=Q(),{surface:s,parentUrl:o}=uw(),[i,d]=p.useState(!1),[c,u]=p.useState(0),[h,f]=p.useState({status:"loading"}),m=p.useRef(null),v=ew(n),C=p.useMemo(()=>!t||!v?null:xo.projectionApiUrl(s,t,v),[t,v,s]);dd({kind:"artifact",id:t??null,enabled:C!==null,onSnapshot:y=>{if(Qx(t,y)){if(m.current!==C){m.current=C;return}u(g=>g+1)}},onPatch:y=>{Xx(t,y)&&u(g=>g+1)}}),p.useEffect(()=>{if(!C){f({status:"error",message:a(l.sharedArtifactCanvasInvalidRoute)});return}let y=!1;return f({status:"loading"}),fetch(C).then(async g=>{const x=await g.json();if(!g.ok)throw new Error(tw(x)??a(l.sharedArtifactCanvasLoadFailed));return x}).then(g=>{y||f({status:"ready",projection:g})}).catch(g=>{y||f({status:"error",message:g instanceof Error?g.message:a(l.sharedArtifactCanvasLoadFailed)})}),()=>{y=!0}},[C,c,a]);const S=h.status==="ready"?h.projection:null;return r.jsxs("aside",{className:i?"artifactCanvasPane artifactCanvasPane--collapsed":"artifactCanvasPane","aria-label":a(l.sharedArtifactCanvasTitle),children:[r.jsxs("header",{className:"artifactCanvasTopBar",children:[r.jsxs("div",{children:[r.jsx("p",{className:"artifactCanvasEyebrow",children:a(l.sharedArtifactCanvasTitle)}),r.jsx("h2",{className:"artifactCanvasTitle",children:S?.artifact.title??a(l.sharedArtifactCanvasLoading)})]}),r.jsxs("div",{className:"artifactCanvasActions",children:[S?.externalUrl?r.jsx("a",{className:"operatorActionButton",href:S.externalUrl,target:"_blank",rel:"noreferrer",children:a(l.sharedArtifactCanvasOpenExternal)}):null,r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>u(y=>y+1),children:a(l.sharedArtifactCanvasRefresh)}),r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>d(y=>!y),children:a(i?l.sharedArtifactCanvasExpand:l.sharedArtifactCanvasCollapse)}),r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>e(o),children:a(l.sharedArtifactCanvasClose)})]})]}),i?null:r.jsx("div",{className:"artifactCanvasBody",children:Zx(h,a)})]})}function Zx(e,t){if(e.status==="loading")return r.jsx("div",{className:"artifactCanvasState",children:t(l.sharedArtifactCanvasLoading)});if(e.status==="error")return r.jsx("div",{className:"artifactCanvasState artifactCanvasState--error",children:e.message});const n=e.projection;return n.presentationResolved==="image"?r.jsx(Gx,{projection:n}):n.presentationResolved==="pdf"?r.jsx(Jx,{projection:n}):n.presentationResolved==="code"?r.jsx(qx,{projection:n}):n.safeUrl&&n.iframeSandboxProfile&&n.presentationResolved==="iframe"?r.jsx(zx,{projection:n}):r.jsxs("div",{className:"artifactCanvasUnsupported",children:[r.jsx("h3",{children:t(l.sharedArtifactCanvasUnsupportedTitle)}),r.jsx("p",{children:n.error?.message??t(l.sharedArtifactCanvasUnsupportedBody)}),r.jsxs("dl",{children:[r.jsx("dt",{children:t(l.sharedArtifactCanvasPolicyVersion)}),r.jsx("dd",{children:n.policyVersion})]})]})}function ew(e){return e?du.includes(e)?e:null:"auto"}function tw(e){if(!e||typeof e!="object"||Array.isArray(e))return null;const t=e.error;if(!t||typeof t!="object"||Array.isArray(t))return null;const n=t.message;return typeof n=="string"&&n.trim().length>0?n.trim():null}const nw=[250,500,1e3];function aw(e){const t=Ta();p.useEffect(()=>{if(!e||typeof EventSource>"u")return;const n=new EventSource(Fx(e)),a=s=>{const o=sw(s.data);!o||!ow(o.surface,e)||(t(o.targetUrl),globalThis.setTimeout(()=>{rw(o.intentId)},0))};return n.addEventListener("artifact_canvas_intent",a),()=>{n.removeEventListener("artifact_canvas_intent",a),n.close()}},[t,e])}async function rw(e,t=fetch){for(const n of[0,...nw]){n>0&&await iw(n);try{if((await t(_x,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({intentId:e})})).ok)return}catch{}}}function sw(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}const n=no(t),s=no(n?.intent)??n,o=no(s?.surface),i=o?.kind,d=o?.surfaceId,c=s?.intentId,u=s?.targetUrl;return typeof i!="string"||typeof d!="string"||typeof c!="string"||typeof u!="string"?null:s}function ow(e,t){return e.kind===t.kind&&e.surfaceId===t.surfaceId}function no(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function iw(e){return new Promise(t=>{globalThis.setTimeout(t,e)})}const fs=460,ms=320,ko=760,lw=360,cw=32,dw=80;function Ww(e){return r.jsxs(Os,{path:e.path,element:r.jsx(pw,{surfaceKind:e.surfaceKind,surfaceIdParam:e.surfaceIdParam,children:e.element}),children:[r.jsx(Os,{path:"canvas/:artifactId",element:r.jsx(Hl,{})}),r.jsx(Os,{path:"canvas/:artifactId/view/:presentation",element:r.jsx(Hl,{})})]},e.key)}function uw(){return qh()}function pw({surfaceKind:e,surfaceIdParam:t,children:n}){const{t:a}=Q(),s=dc(),o=ec(),i=p.useRef(null),d=s[t],c=p.useMemo(()=>d?{kind:e,surfaceId:d}:null,[d,e]);aw(c);const u=c?xo.parse(o.pathname):null,h=!!(c&&u?.kind==="canvas"&&u.surface.kind===c.kind&&u.surface.surfaceId===c.surfaceId),f=c?gs(c):null,[m,v]=p.useState(fs),[C,S]=p.useState(null);p.useEffect(()=>{if(!c){S(null),v(fs);return}v(hw(c)),S(gs(c))},[c]),p.useEffect(()=>{!c||!h||C!==f||fw(c,m)},[h,C,m,c,f]);const y=p.useMemo(()=>Kr(i.current),[h]),g=p.useCallback(A=>{const M=Kr(i.current);v(D=>Po(D+A,M))},[]),x=p.useCallback(A=>{const M=A.shiftKey?dw:cw;if(A.key==="ArrowLeft"){A.preventDefault(),g(M);return}if(A.key==="ArrowRight"){A.preventDefault(),g(-M);return}if(A.key==="Home"){A.preventDefault(),v(ms);return}A.key==="End"&&(A.preventDefault(),v(Kr(i.current)))},[g]),I=p.useCallback(A=>{if(A.button!==0)return;const M=i.current;if(!M||typeof window>"u")return;A.preventDefault();const D=M.getBoundingClientRect(),N=Kr(M),R=T=>{v(Po(D.right-T,N))},w=T=>{R(T.clientX)},b=()=>{window.removeEventListener("pointermove",w),window.removeEventListener("pointerup",b)};R(A.clientX),window.addEventListener("pointermove",w),window.addEventListener("pointerup",b,{once:!0})},[]);if(!c)return r.jsx(r.Fragment,{children:n});const k=xo.parentUrl(c);if(!h)return r.jsx(r.Fragment,{children:n});const P={"--artifact-canvas-pane-width":`${m}px`};return r.jsxs("div",{className:"artifactCanvasSurfaceFrame",ref:i,style:P,children:[r.jsx("div",{className:"artifactCanvasSurfaceMain",children:n}),r.jsx("div",{className:"artifactCanvasResizeHandle",role:"separator","aria-label":a(l.sharedArtifactCanvasResizePane),"aria-orientation":"vertical","aria-valuemin":ms,"aria-valuemax":y,"aria-valuenow":m,tabIndex:0,onKeyDown:x,onPointerDown:I}),r.jsx(Hh,{context:{surface:c,parentUrl:k}})]})}function hw(e){if(typeof window>"u")return fs;const t=window.localStorage.getItem(gs(e)),n=t?Number.parseInt(t,10):NaN;return Number.isFinite(n)?Po(n,ko):fs}function fw(e,t){typeof window>"u"||window.localStorage.setItem(gs(e),String(t))}function gs(e){return`cats.artifactCanvas.paneWidth.${e.kind}.${e.surfaceId}`}function Kr(e){return e?Math.max(ms,Math.min(ko,e.clientWidth-lw)):ko}function Po(e,t){return Math.min(Math.max(Math.round(e),ms),t)}const Cu=420,Qn=12,ql=8;function mw(){return{position:"fixed",top:0,left:0,width:`min(${Cu}px, calc(100vw - ${Qn*2}px))`,visibility:"hidden",pointerEvents:"none"}}function gw(e){return Math.max(0,Math.min(Cu,e-Qn*2))}function Cw({triggerRect:e,viewportWidth:t,viewportHeight:n,menuWidth:a,menuHeight:s}){const o=gw(t),i=a||o;let d=e.left;d+i>t-Qn&&(d=Math.max(Qn,t-i-Qn));let c=e.bottom+ql;return s>0&&c+s>n-Qn&&(c=Math.max(Qn,e.top-s-ql)),{position:"fixed",top:c,left:d,width:o}}function Gl(e,t,n=uc.flushSync){n(e),t()}const vw=typeof window>"u"?p.useEffect:p.useLayoutEffect;function Iw({activeSurface:e,onSelectSurface:t,activeLabelOverride:n}){const a=Ta(),{t:s}=Q(),[o,i]=p.useState(!1),d=p.useRef(null),c=p.useRef(null),[u,h]=p.useState(),f=p.useMemo(()=>Gh(),[]),m=ro(e,Vh(e),s),v=n??m,C=n!==void 0;p.useEffect(()=>{if(!o)return;function y(x){const I=x.target;!d.current?.contains(I)&&!c.current?.contains(I)&&i(!1)}function g(x){x.key==="Escape"&&i(!1)}return document.addEventListener("mousedown",y),document.addEventListener("keydown",g),()=>{document.removeEventListener("mousedown",y),document.removeEventListener("keydown",g)}},[o]),vw(()=>{if(!o){h(void 0);return}function y(){const g=d.current;if(!g)return;const x=g.getBoundingClientRect();h(Cw({triggerRect:x,viewportWidth:window.innerWidth,viewportHeight:window.innerHeight,menuWidth:c.current?.offsetWidth??0,menuHeight:c.current?.offsetHeight??0}))}return y(),window.addEventListener("resize",y),document.addEventListener("scroll",y,!0),()=>{window.removeEventListener("resize",y),document.removeEventListener("scroll",y,!0)}},[o]);const S=o?r.jsxs("div",{ref:c,className:"platformSurfaceMenu",style:u??mw(),role:"menu","aria-label":s(l.sharedPlatformSurfaceSwitcherMenuLabel),children:[r.jsx("p",{className:"platformSurfaceMenuHeading",children:s(l.appBrandName)}),r.jsx("div",{className:"platformSurfaceMenuList",children:f.map(y=>{const g=!C&&y.id===e,x=`platformSurfaceSwatch platformSurfaceSwatch${y.id[0].toUpperCase()}${y.id.slice(1)}`,I=ro(y.id,y.productName,s),k=zh(y.id,y.subtitle,s);return r.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":g,className:g?"platformSurfaceMenuItem isCurrent":"platformSurfaceMenuItem",onClick:()=>{Gl(()=>i(!1),()=>{g||t(y.id)})},children:[r.jsx("span",{className:x,"aria-hidden":"true"}),r.jsxs("span",{className:"platformSurfaceMenuCopy",children:[r.jsx("span",{className:"platformSurfaceMenuTitleRow",children:r.jsx("span",{className:"platformSurfaceMenuTitle",children:I})}),r.jsx("span",{className:"platformSurfaceMenuSubtitle",children:k})]}),g?r.jsx("span",{className:"platformSurfaceMenuCheck","aria-hidden":"true",children:r.jsx("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:r.jsx("path",{d:"m2.4 6.3 2.1 2.1 5.1-5.1"})})}):null]},y.id)})}),r.jsx("div",{className:"platformSurfaceMenuDivider"}),r.jsx("button",{type:"button",className:"platformSurfaceMenuAction",onClick:()=>{Gl(()=>i(!1),()=>{a("/lobby")})},children:s(l.sharedPlatformSurfaceSwitcherOpenLobby)})]}):null;return r.jsxs("div",{ref:d,className:"platformSurfaceSwitcher",children:[r.jsx("button",{type:"button",className:o?"platformSurfaceTrigger isOpen":"platformSurfaceTrigger","aria-haspopup":"menu","aria-expanded":o,"aria-label":s(l.sharedPlatformSurfaceSwitcherAriaLabel,{productName:v}),onClick:()=>i(y=>!y),children:r.jsxs("span",{className:"platformSurfaceTriggerRow",children:[r.jsx("span",{className:"brandLabel",children:v}),r.jsx("svg",{className:"platformSurfaceChevron",width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":"true",children:r.jsx("path",{d:"M3 4.5 6 7.5 9 4.5"})})]})}),S&&typeof document<"u"?uc.createPortal(S,document.body):null]})}function Sw({activeSurface:e,sidebarOpen:t,primaryActions:n,onToggleSidebar:a,onSwitchProduct:s,surfaceLabelOverride:o}){const{t:i}=Q();return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"brandRow",children:[r.jsx("div",{className:"brandCopy",children:r.jsx(Iw,{activeSurface:e,onSelectSurface:s,activeLabelOverride:o})}),r.jsx("button",{className:"chromeButton",type:"button","aria-label":i(t?l.conversationSidebarCloseSidebarLabel:l.conversationSidebarOpenSidebarLabel),onClick:a,children:r.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("rect",{x:"1",y:"2",width:"14",height:"12",rx:"2"}),r.jsx("path",{d:"M6 2v12"})]})})]}),r.jsx("nav",{className:"navGroup","aria-label":i(l.conversationSidebarPrimaryAriaLabel),children:n.map(d=>r.jsxs("button",{className:d.active?"navItem navItemActive":"navItem",onClick:d.onClick,type:"button",children:[r.jsx("span",{className:"navGlyph","aria-hidden":"true",children:d.icon}),r.jsx("span",{className:"navLabel",children:d.label})]},d.key))})]})}function yw({overflowKey:e,item:t,overflowOpen:n,onOverflowToggle:a}){const s=p.useRef(null),o=p.useRef(null),i=Bo(s,o,n),d=t.overflowActions??[],c=d.length>0;return r.jsxs("article",{className:["recentItemCard","pinnedItemCard",t.isActive?"recentItemSelected":"",n?"recentItemOverflowOpen":""].filter(Boolean).join(" "),onClick:t.onClick,"data-overflow-key":e,children:[r.jsxs("button",{className:"recentSelectButton pinnedSelectButton",type:"button",onClick:u=>{u.stopPropagation(),t.onClick()},children:[t.statusDot?r.jsx("span",{className:t.statusDot.className,"data-tooltip":t.statusDot.title??void 0,"aria-hidden":"true"}):null,r.jsx("strong",{children:t.label})]}),c?r.jsx("span",{className:"recentItemTrailing",children:r.jsx("button",{ref:s,className:"recentOverflowButton",type:"button",onClick:u=>{u.stopPropagation(),a()},children:"⋯"})}):null,n&&c?r.jsx(Oo,{menuRef:o,className:"recentOverflowMenu",style:i,onClick:u=>u.stopPropagation(),children:d.map((u,h)=>{const f=h>0?d[h-1]:void 0,m=u.destructive===!0&&f&&f.destructive!==!0;return r.jsxs(p.Fragment,{children:[m?r.jsx("div",{className:"recentOverflowMenuDivider"}):null,r.jsx("button",{type:"button",disabled:u.disabled===!0,onClick:u.onClick,children:u.label})]},u.key)})}):null]})}function ci(e){return pc(e)}function Ao(e,t){return ci(e.originSurface)===t}function bw(e,t){if(e.kind==="channel")return Ao(e.channel,t)?e:null;const n=e.channels.filter(s=>Ao(s.channel,t));if(n.length===0)return null;const a=e.originSurface??n[0]?.channel.originSurface??null;return ci(a)!==t?null:{...e,channels:n}}function xw(e){const{payload:t,helpers:n,recentEntries:a,currentPath:s,t:o}=e,i=e.shellSurface??Yh(s),d=t.chat.cats.filter(v=>n.isVisibleCat(v)),c=t.runtime??{baseUrl:t.runtimeBaseUrl??"",reachable:t.runtimeReachable,status:null},u=new Set((t.chat.botBindings??[]).filter(v=>v.platform==="telegram"&&v.status==="active").map(v=>v.catId).filter(v=>!!v)),h=t.chat.channels.filter(v=>!n.isDirectLaneSummary(v)&&Ao(v,i)),f=a?a.map(v=>bw(v,i)).filter(v=>v!=null):h.map(v=>({kind:"channel",channel:v})),m=Jh(c);return{activeSurface:i,showMyCats:d.length>0,visibleCats:d,resolvedRuntime:c,telegramBoundCatIds:u,resolvedRecentEntries:f,runtimeFooterStatus:m,runtimeFooterLabel:Qh(m,o)}}function vu({title:e,onRename:t,onBeforeStart:n}){const[a,s]=p.useState(!1),[o,i]=p.useState(""),d=p.useRef(null);function c(){t&&(n?.(),i(e),s(!0),requestAnimationFrame(()=>d.current?.select()))}function u(){if(!t){s(!1);return}const f=o.trim();s(!1),f&&f!==e&&t(f)}function h(){s(!1)}return{renaming:a,renameValue:o,inputRef:d,setRenameValue:i,startRename:c,commitRename:u,cancelRename:h}}function ww(e,t){const n=e.defaultRecipientCatId;if(!n)return null;const a=t.chat.cats.find(s=>s.id===n);return a?{name:a.name,avatarColor:a.avatarColor,avatarUrl:a.avatarUrl??null,isBoss:a.id===t.chat.bossCatId}:null}function kw({channel:e,payload:t,helpers:n,isSelected:a,busy:s,overflowOpen:o,onSelect:i,onRename:d,onDelete:c,onOverflowToggle:u,titleOverride:h,disableRename:f}){const{t:m}=Q(),v=ww(e,t),C=p.useRef(null),S=p.useRef(null),y=Bo(C,S,o),{renaming:g,renameValue:x,inputRef:I,setRenameValue:k,startRename:P,commitRename:A,cancelRename:M}=vu({title:e.title,onRename:f?void 0:d,onBeforeStart:u});return r.jsxs("article",{className:["recentItemCard",a?"recentItemSelected":"",o?"recentItemOverflowOpen":""].filter(Boolean).join(" "),onClick:()=>{g||i()},children:[g?r.jsx("input",{ref:I,className:"recentRenameInput",type:"text",value:x,onChange:D=>k(D.target.value),onKeyDown:D=>{D.key==="Enter"&&A(),D.key==="Escape"&&M()},onBlur:A}):r.jsx("button",{className:"recentSelectButton",onClick:D=>{D.stopPropagation(),i()},type:"button",children:r.jsx("strong",{children:n.presentChannelTitle(h??e.title)})}),g?null:r.jsxs("span",{className:"recentItemTrailing",children:[v?r.jsx("span",{className:v.isBoss?"recentCatAvatar recentCatAvatarBoss":"recentCatAvatar","data-tooltip":v.name,style:v.avatarUrl?{backgroundImage:`url(${v.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:{background:v.avatarColor??"#90A4AE"},children:v.avatarUrl?null:n.catInitials(v.name)}):null,r.jsx("button",{ref:C,className:"recentOverflowButton",type:"button",onClick:D=>{D.stopPropagation(),u()},children:"⋯"})]}),o?r.jsxs(Oo,{menuRef:S,className:"recentOverflowMenu",style:y,onClick:D=>D.stopPropagation(),children:[f?null:r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",onClick:P,children:m(l.conversationSidebarRenameLabel)}),r.jsx("div",{className:"recentOverflowMenuDivider"})]}),r.jsx("button",{type:"button",disabled:oo(s,"delete",e.id),onClick:c,children:oo(s,"delete",e.id)?m(l.conversationSidebarDeletingLabel):m(l.conversationSidebarDeleteLabel)})]}):null]})}function Pw({title:e,isSelected:t,busy:n,overflowOpen:a,onSelect:s,onRename:o,onUngroup:i,onDelete:d,onOverflowToggle:c,renameBusyKey:u,ungroupBusyKey:h,deleteBusyKey:f}){const{t:m}=Q(),v=p.useRef(null),C=p.useRef(null),S=Bo(v,C,a),y=b=>b?.split(":").at(-1),g=u?_s(n,"rename",y(u)):!1,x=h?_s(n,"ungroup",y(h)):!1,I=f?_s(n,"delete",y(f)):!1,k=!!(o||i||d),{renaming:P,renameValue:A,inputRef:M,setRenameValue:D,startRename:N,commitRename:R,cancelRename:w}=vu({title:e,onRename:o,onBeforeStart:c});return r.jsxs("article",{className:["recentItemCard",t?"recentItemSelected":"",a?"recentItemOverflowOpen":""].filter(Boolean).join(" "),onClick:()=>{P||s()},children:[P?r.jsx("input",{ref:M,className:"recentRenameInput",type:"text",value:A,onChange:b=>D(b.target.value),onKeyDown:b=>{b.key==="Enter"&&R(),b.key==="Escape"&&w()},onBlur:R}):r.jsx("button",{className:"recentSelectButton",onClick:b=>{b.stopPropagation(),s()},type:"button",children:r.jsx("strong",{children:e})}),P?null:r.jsxs("span",{className:"recentItemTrailing",children:[r.jsx("span",{className:"recentParallelGlyph",children:r.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round",children:[r.jsx("path",{d:"M2 13V3h12v10H2z"}),r.jsx("path",{d:"M7 3v10"}),r.jsx("path",{d:"M11 3v10"})]})}),k?r.jsx("button",{ref:v,className:"recentOverflowButton",type:"button",onClick:b=>{b.stopPropagation(),c()},children:"⋯"}):null]}),a&&k?r.jsxs(Oo,{menuRef:C,className:"recentOverflowMenu",style:S,onClick:b=>b.stopPropagation(),children:[o?r.jsx("button",{type:"button",disabled:g,onClick:N,children:m(g?l.conversationSidebarRenamingLabel:l.conversationSidebarRenameLabel)}):null,i?r.jsx("button",{type:"button",disabled:x,onClick:()=>{c(),i()},children:m(x?l.conversationSidebarUngroupingLabel:l.conversationSidebarUngroupLabel)}):null,d?r.jsxs(r.Fragment,{children:[o||i?r.jsx("div",{className:"recentOverflowMenuDivider"}):null,r.jsx("button",{type:"button",disabled:I,onClick:d,children:m(I?l.conversationSidebarDeletingLabel:l.conversationSidebarDeleteAllLabel)})]}):null]}):null]})}function Aw({entries:e,emptyStateLabel:t,payload:n,helpers:a,routeChannelId:s,busy:o,overflowMenuOpenId:i,onSelect:d,onDeleteChannel:c,onRenameChannel:u,onOverflowMenuToggle:h}){const{t:f}=Q();function m(C){const S=C.key??C.channel.id;return r.jsx(kw,{channel:C.channel,payload:n,helpers:a,isSelected:s===C.channel.id,busy:o,overflowOpen:i===S,onSelect:()=>d(C.channel.id),onRename:y=>{u(C.channel.id,y)},onDelete:()=>{h(null),c(C.channel.id)},onOverflowToggle:()=>h(i===S?null:S),titleOverride:C.titleOverride,disableRename:C.disableRename},C.key??C.channel.id)}function v(){return e.length===0?r.jsx("div",{className:"recentEmpty",children:r.jsx("p",{children:t??f(l.conversationSidebarNoChatsLabel)})}):e.map(C=>{if(C.kind==="channel")return m(C);const S=C.overflowKey??C.key;return r.jsxs("section",{className:"recentGroupCard",children:[r.jsx(Pw,{title:C.title,isSelected:C.isSelected??!1,busy:o,overflowOpen:i===S,onSelect:C.onSelect,onRename:C.onRename,onUngroup:C.onUngroup,onDelete:C.onDelete,onOverflowToggle:()=>h(i===S?null:S),renameBusyKey:C.renameBusyKey,ungroupBusyKey:C.ungroupBusyKey,deleteBusyKey:C.deleteBusyKey}),r.jsx("div",{className:"recentGroupList",children:C.channels.map(y=>m(y))})]},C.key)})}return r.jsxs("section",{className:"recentSection",children:[r.jsx("div",{className:"recentHeader",children:r.jsx("p",{className:"sectionLabel",children:f(l.conversationSidebarRecentsLabel)})}),r.jsx("div",{className:"recentList",children:v()})]})}function Rw({payload:e,sidebarOpen:t,accountMenuOpen:n,overflowMenuOpenId:a,busy:s,surface:o,shellSurface:i,routeChannelId:d,accountMenuRef:c,primaryActions:u,extraActionGroups:h=[],recentEntries:f,recentEmptyStateLabel:m,myCatsSectionLabel:v,forceShowMyCatsSection:C=!1,myCatsSectionCats:S,myCatsEmptyStatePlaceholder:y,myCatsTerminalActionLabelKey:g,myCatsDisableTerminalActionWhenDraft:x,helpers:I,onToggleSidebar:k,onCollapsedSidebarClick:P,onOpenChatsOverview:A,onSelect:M,onDeleteChannel:D,onRenameChannel:N,onArchiveCat:R,onAccountMenuToggle:w,onOverflowMenuToggle:b,onNavigateSettings:T,onNavigateRuntime:E,onSwitchProduct:O,activeMyCatId:H,onDirectChatCat:U,t:L}){const $=globalThis.location?.pathname??"/",{activeSurface:X,visibleCats:ke,telegramBoundCatIds:z,resolvedRecentEntries:B,runtimeFooterStatus:ae,runtimeFooterLabel:he}=xw({payload:e,helpers:I,recentEntries:f,shellSurface:i,currentPath:$,t:L}),Y=v??L(l.conversationSidebarDirectMessagesLabel),G=S??ke,W=C||y!=null;return r.jsxs("aside",{className:t?"sidebar":"sidebar sidebarCollapsed","data-shell-surface":i??X,onClick:ue=>P(ue),children:[r.jsxs("div",{className:"sidebarInner",children:[r.jsx(Sw,{activeSurface:X,sidebarOpen:t,primaryActions:u,onToggleSidebar:k,onSwitchProduct:O}),r.jsxs("div",{className:"sidebarScrollable",children:[r.jsx("nav",{className:"navGroup navGroupChat","aria-label":L(l.conversationSidebarChatsLabel),children:r.jsxs("button",{className:o==="chats"?"navItem navItemActive":"navItem",onClick:A,type:"button",children:[r.jsx("span",{className:"navGlyph navGlyphSquare","aria-hidden":"true"}),r.jsx("span",{className:"navLabel",children:L(l.conversationSidebarChatsLabel)})]})}),h.map(ue=>r.jsxs("nav",{className:"navGroup","aria-label":ue.ariaLabel,children:[ue.items.map(pe=>r.jsxs("button",{className:pe.active?"navItem navItemActive":"navItem",onClick:pe.onClick,type:"button",children:[r.jsx("span",{className:"navGlyph","aria-hidden":"true",children:pe.icon}),r.jsx("span",{className:"navLabel",children:pe.label})]},pe.key)),ue.pinnedItems&&ue.pinnedItems.length>0?r.jsx("div",{className:"navGroupPinnedList",children:ue.pinnedItems.map(pe=>{const We=`pinned:${ue.key}:${pe.id}`,Z=a===We;return r.jsx(yw,{overflowKey:We,item:pe,overflowOpen:Z,onOverflowToggle:()=>b(Z?null:We)},pe.id)})}):null]},ue.key)),W?r.jsx(Xh,{label:Y,cats:G,bossCatId:e.chat.bossCatId,payloadChannels:e.chat.channels,activeMyCatId:H,telegramBoundCatIds:z,helpers:I,overflowMenuOpenId:a,onOverflowMenuToggle:b,onDirectChatCat:U,onArchiveCat:R,emptyStatePlaceholder:y,terminalActionLabelKey:g,disableTerminalActionWhenDraft:x}):null,r.jsx(Aw,{entries:B,emptyStateLabel:m,payload:e,helpers:I,routeChannelId:d,busy:s,overflowMenuOpenId:a,onSelect:M,onDeleteChannel:D,onRenameChannel:N,onOverflowMenuToggle:b})]})]}),r.jsx(Zh,{slotKind:"workspace"}),r.jsx(ef,{payload:e,accountMenuOpen:n,accountMenuRef:c,runtimeFooterStatus:ae,runtimeFooterLabel:he,onAccountMenuToggle:w,onNavigateSettings:T,onNavigateRuntime:E,catInitials:I.catInitials})]})}function Kw(e){const{t}=Q();return r.jsx(Rw,{...e,t})}const Vl="direct_message";function Nw(e,t){return e.filter(n=>n.channelKind===Vl||n.roomMode===Vl?!1:pc(n.originSurface)===t)}function Uw(e){const t=Nw(e.channels,e.activeSurface),n=(e.parallelChatGroups??[]).filter(c=>c.status==="active"&&ci(c.originSurface)===e.activeSurface),a=new Map;for(const c of n)for(const u of c.memberChannelIds)a.set(u,c);const s=new Map(t.map(c=>[c.id,c])),o=[],i=new Set,d=new Set;for(const c of t){if(i.has(c.id))continue;const u=a.get(c.id);if(u&&!d.has(u.id)){const h=u.memberChannelIds.map(f=>s.get(f)??null).filter(f=>f!=null);if(h.length>1){d.add(u.id),h.forEach(f=>i.add(f.id)),o.push({kind:"group",key:u.id,title:u.title,originSurface:u.originSurface,overflowKey:`group:${u.id}`,isSelected:u.memberChannelIds.includes(e.routeChannelId??""),onSelect:()=>{const f=u.memberChannelIds[0];f&&e.onSelect(f)},onRename:e.onRenameParallelGroup?f=>{e.onRenameParallelGroup?.(u.id,f)}:void 0,onUngroup:e.onUngroupParallelGroup?()=>{e.onUngroupParallelGroup?.(u.id)}:void 0,onDelete:e.onDeleteParallelGroup?()=>{e.onCloseOverflowMenu?.(),e.onDeleteParallelGroup?.(u.id)}:void 0,renameBusyKey:`concurrent-group:rename:${u.id}`,ungroupBusyKey:`concurrent-group:ungroup:${u.id}`,deleteBusyKey:`concurrent-group:delete:${u.id}`,channels:h.map(f=>({channel:f,titleOverride:u.members?.find(m=>m.channelId===f.id)?.title??void 0,disableRename:!0}))});continue}}i.add(c.id),o.push({kind:"channel",channel:c})}return o}export{Ew as A,Fw as C,Bw as D,mx as F,zx as I,_w as N,ix as P,Tx as W,Dw as a,Jd as b,Kw as c,Uw as d,Mw as e,sf as f,Ow as g,Vx as h,Lw as i,qb as j,na as k,Qm as l,Cx as m,ka as n,zr as o,sC as p,yo as q,gI as r,Vd as s,vx as t,jx as u,Kl as v,Ww as w,wa as x};