@cats-inc/cats-platform 0.2.8 → 0.3.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/build/desktop/bootstrapPage.d.ts.map +1 -1
- package/build/desktop/bootstrapPage.js +26 -129
- package/build/desktop/bootstrapPage.js.map +1 -1
- package/build/desktop/cliInventoryProbe.d.ts +6 -0
- package/build/desktop/cliInventoryProbe.d.ts.map +1 -1
- package/build/desktop/cliInventoryProbe.js +6 -3
- package/build/desktop/cliInventoryProbe.js.map +1 -1
- package/build/desktop/contracts.d.ts +2 -0
- package/build/desktop/contracts.d.ts.map +1 -1
- package/build/desktop/contracts.js.map +1 -1
- package/build/desktop/main.js +95 -41
- package/build/desktop/main.js.map +1 -1
- package/build/desktop/preload.cjs +8 -6
- package/build/desktop/preload.cjs.map +1 -1
- package/build/desktop/providerManager.d.ts +46 -0
- package/build/desktop/providerManager.d.ts.map +1 -0
- package/build/desktop/providerManager.js +220 -0
- package/build/desktop/providerManager.js.map +1 -0
- package/build/desktop/providerSelection.d.ts +1 -0
- package/build/desktop/providerSelection.d.ts.map +1 -1
- package/build/desktop/providerSelection.js +7 -1
- package/build/desktop/providerSelection.js.map +1 -1
- package/build/desktop/setupAssets.d.ts.map +1 -1
- package/build/desktop/setupAssets.js +12 -0
- package/build/desktop/setupAssets.js.map +1 -1
- package/build/desktop/setupAudit.d.ts +3 -1
- package/build/desktop/setupAudit.d.ts.map +1 -1
- package/build/desktop/setupAudit.js +12 -8
- package/build/desktop/setupAudit.js.map +1 -1
- package/build/desktop/setupBridge.js +1 -1
- package/build/desktop/setupBridge.js.map +1 -1
- package/build/desktop/setupPrerequisites.d.ts +11 -0
- package/build/desktop/setupPrerequisites.d.ts.map +1 -0
- package/build/desktop/setupPrerequisites.js +47 -0
- package/build/desktop/setupPrerequisites.js.map +1 -0
- package/build/renderer/assets/ActiveSessionPermissionChip-B49WcZBJ.js +1 -0
- package/build/renderer/assets/{App-BZA23O2J.js → App-BpxZB5ym.js} +1 -1
- package/build/renderer/assets/{App-rGw9J8PZ.js → App-DYTUfAl6.js} +1 -1
- package/build/renderer/assets/{App-YqprEL2n.js → App-boB4WrmU.js} +1 -1
- package/build/renderer/assets/{WorkspaceAppRoutes-BCHCikmJ.js → WorkspaceAppRoutes-CPqz85iw.js} +1 -1
- package/build/renderer/assets/app-C52wwCGz.js +85 -0
- package/build/renderer/assets/app-CqnsY5ed.css +1 -0
- package/build/renderer/assets/{client-BdGHAUoK.js → client-DREGSZqQ.js} +1 -1
- package/build/renderer/assets/conversationSidebarRecentEntries-DK0iWS73.js +6 -0
- package/build/renderer/assets/{screenshotOverlay-DfBcolX-.js → screenshotOverlay-EF07cXvw.js} +1 -1
- package/build/renderer/assets/{useDraftSessionChips-D9BX6X92.js → useDraftSessionChips-BdZ_B1gy.js} +1 -1
- package/build/renderer/desktop/overlay/index.html +2 -2
- package/build/renderer/index.html +3 -3
- package/build/server/app/renderer/auth/api.d.ts.map +1 -1
- package/build/server/app/renderer/auth/api.js +4 -1
- package/build/server/app/renderer/auth/api.js.map +1 -1
- package/build/server/app/renderer/providerCatalogClient.d.ts.map +1 -1
- package/build/server/app/renderer/providerCatalogClient.js +19 -6
- package/build/server/app/renderer/providerCatalogClient.js.map +1 -1
- package/build/server/app/renderer/providerClientInvalidation.d.ts +6 -0
- package/build/server/app/renderer/providerClientInvalidation.d.ts.map +1 -0
- package/build/server/app/renderer/providerClientInvalidation.js +12 -0
- package/build/server/app/renderer/providerClientInvalidation.js.map +1 -0
- package/build/server/app/renderer/providerReadLoop.d.ts +5 -0
- package/build/server/app/renderer/providerReadLoop.d.ts.map +1 -0
- package/build/server/app/renderer/providerReadLoop.js +52 -0
- package/build/server/app/renderer/providerReadLoop.js.map +1 -0
- package/build/server/app/renderer/providerRegistryClient.d.ts +2 -1
- package/build/server/app/renderer/providerRegistryClient.d.ts.map +1 -1
- package/build/server/app/renderer/providerRegistryClient.js +33 -17
- package/build/server/app/renderer/providerRegistryClient.js.map +1 -1
- package/build/server/app/server/authGatePolicy.js +7 -0
- package/build/server/app/server/authGatePolicy.js.map +1 -1
- package/build/server/app/server/subscribeRoutes.d.ts.map +1 -1
- package/build/server/app/server/subscribeRoutes.js +5 -3
- package/build/server/app/server/subscribeRoutes.js.map +1 -1
- package/build/server/design/components/providerModelFieldsSupport.d.ts +2 -21
- package/build/server/design/components/providerModelFieldsSupport.d.ts.map +1 -1
- package/build/server/design/components/providerModelFieldsSupport.js +32 -36
- package/build/server/design/components/providerModelFieldsSupport.js.map +1 -1
- package/build/server/design/components/useProviderCatalogState.d.ts +1 -2
- package/build/server/design/components/useProviderCatalogState.d.ts.map +1 -1
- package/build/server/design/components/useProviderCatalogState.js +71 -152
- package/build/server/design/components/useProviderCatalogState.js.map +1 -1
- package/build/server/design/components/useProviderModelFieldActions.js +2 -2
- package/build/server/design/components/useProviderModelFieldActions.js.map +1 -1
- package/build/server/design/components/useProviderRegistryState.d.ts +1 -7
- package/build/server/design/components/useProviderRegistryState.d.ts.map +1 -1
- package/build/server/design/components/useProviderRegistryState.js +41 -91
- package/build/server/design/components/useProviderRegistryState.js.map +1 -1
- package/build/server/design/components/useProviderTargetReconciliation.d.ts +1 -0
- package/build/server/design/components/useProviderTargetReconciliation.d.ts.map +1 -1
- package/build/server/design/components/useProviderTargetReconciliation.js +1 -1
- package/build/server/design/components/useProviderTargetReconciliation.js.map +1 -1
- package/build/server/platform/orchestration/entitySubscriptions/channel.d.ts +2 -1
- package/build/server/platform/orchestration/entitySubscriptions/channel.d.ts.map +1 -1
- package/build/server/platform/orchestration/entitySubscriptions/channel.js +3 -18
- package/build/server/platform/orchestration/entitySubscriptions/channel.js.map +1 -1
- package/build/server/platform/orchestration/entitySubscriptions/index.d.ts +1 -0
- package/build/server/platform/orchestration/entitySubscriptions/index.d.ts.map +1 -1
- package/build/server/platform/orchestration/entitySubscriptions/index.js.map +1 -1
- package/build/server/products/chat/api/routeSupport.d.ts +9 -1
- package/build/server/products/chat/api/routeSupport.d.ts.map +1 -1
- package/build/server/products/chat/api/routeSupport.js +22 -0
- package/build/server/products/chat/api/routeSupport.js.map +1 -1
- package/build/server/products/chat/state/model/readModels.d.ts +1 -0
- package/build/server/products/chat/state/model/readModels.d.ts.map +1 -1
- package/build/server/products/chat/state/model/readModels.js +2 -1
- package/build/server/products/chat/state/model/readModels.js.map +1 -1
- package/build/server/products/shared/renderer/api/appShell.d.ts +1 -0
- package/build/server/products/shared/renderer/api/appShell.d.ts.map +1 -1
- package/build/server/products/shared/renderer/api/appShell.js +9 -0
- package/build/server/products/shared/renderer/api/appShell.js.map +1 -1
- package/build/server/runtime/client.d.ts.map +1 -1
- package/build/server/runtime/client.js +5 -1
- package/build/server/runtime/client.js.map +1 -1
- package/build/server/runtime/setup.d.ts +4 -0
- package/build/server/runtime/setup.d.ts.map +1 -1
- package/build/server/runtime/setup.js +3 -1
- package/build/server/runtime/setup.js.map +1 -1
- package/build/server/server/routes/providers.d.ts.map +1 -1
- package/build/server/server/routes/providers.js +21 -50
- package/build/server/server/routes/providers.js.map +1 -1
- package/build/server/shared/desktopRecoveryBridge.d.ts +2 -1
- package/build/server/shared/desktopRecoveryBridge.d.ts.map +1 -1
- package/build/server/shared/desktopRecoveryBridge.js.map +1 -1
- package/build/server/shared/providerCatalogData.d.ts +128 -57
- package/build/server/shared/providerCatalogData.d.ts.map +1 -1
- package/build/server/shared/providerCatalogData.js +51 -26
- package/build/server/shared/providerCatalogData.js.map +1 -1
- package/build/server/shared/providerRegistryWarnings.d.ts +4 -0
- package/build/server/shared/providerRegistryWarnings.d.ts.map +1 -1
- package/build/server/shared/providerRegistryWarnings.js +7 -0
- package/build/server/shared/providerRegistryWarnings.js.map +1 -1
- package/package.json +12 -5
- package/packages/provider-setup/manager.d.ts +79 -0
- package/packages/provider-setup/manager.js +441 -0
- package/scripts/README.md +23 -0
- package/scripts/build-desktop-installer.mjs +124 -16
- package/scripts/linux/install-github-cli.sh +5 -0
- package/scripts/linux/install-node.sh +9 -3
- package/scripts/linux/node-cli-common.sh +87 -48
- package/scripts/linux/provider-cli-common.sh +80 -105
- package/scripts/linux/provider-version-common.sh +247 -0
- package/scripts/linux/test-linux-package-smoke.sh +2 -0
- package/scripts/linux/verified-npm-update.sh +20 -0
- package/scripts/macos/install-github-cli.sh +5 -0
- package/scripts/macos/install-node.sh +9 -3
- package/scripts/macos/node-cli-common.sh +87 -48
- package/scripts/macos/provider-cli-common.sh +80 -105
- package/scripts/macos/provider-version-common.sh +247 -0
- package/scripts/macos/test-macos-package-smoke.sh +2 -0
- package/scripts/macos/verified-npm-update.sh +20 -0
- package/scripts/testing/conversation-navigation-smoke-electron.cjs +134 -0
- package/scripts/testing/conversation-navigation-smoke-renderer.tsx +102 -0
- package/scripts/testing/conversation-navigation-smoke.mjs +67 -0
- package/scripts/validate-release-assets.mjs +4 -1
- package/scripts/windows/Install-Antigravity.ps1 +26 -3
- package/scripts/windows/Install-ClaudeCode.ps1 +25 -7
- package/scripts/windows/Install-CursorAgent.ps1 +45 -30
- package/scripts/windows/Install-Devin.ps1 +16 -47
- package/scripts/windows/Install-GitHubCli.ps1 +4 -0
- package/scripts/windows/Install-Goose.ps1 +18 -1
- package/scripts/windows/Install-Grok.ps1 +14 -1
- package/scripts/windows/Install-Junie.ps1 +32 -11
- package/scripts/windows/Install-KiroCli.ps1 +37 -13
- package/scripts/windows/Install-MetaCli.ps1 +8 -1
- package/scripts/windows/Install-Node.ps1 +6 -1
- package/scripts/windows/Setup-NodeGlobalPrefix.ps1 +10 -0
- package/scripts/windows/Test-WindowsInstallerSmoke.ps1 +2 -0
- package/scripts/windows/_HiddenProcess.ps1 +14 -3
- package/scripts/windows/_NativeInstallerSupport.ps1 +308 -0
- package/scripts/windows/_NpmCliInstaller.ps1 +35 -14
- package/scripts/windows/_PackagedUninstall.ps1 +9 -1
- package/scripts/windows/_VerifiedNpmUpdate.ps1 +25 -0
- package/build/renderer/assets/ActiveSessionPermissionChip-CAgN-tXv.js +0 -1
- package/build/renderer/assets/app-BV3UAQkR.css +0 -1
- package/build/renderer/assets/app-CVPqqfZo.js +0 -45
- package/build/renderer/assets/conversationSidebarRecentEntries-iqaLqA1n.js +0 -6
- package/build/server/app/renderer/settings/runtimeLifecycleHelpers.d.ts +0 -48
- package/build/server/app/renderer/settings/runtimeLifecycleHelpers.d.ts.map +0 -1
- package/build/server/app/renderer/settings/runtimeLifecycleHelpers.js +0 -535
- package/build/server/app/renderer/settings/runtimeLifecycleHelpers.js.map +0 -1
- package/build/server/design/components/useProviderRegistryAutoRecheck.d.ts +0 -13
- package/build/server/design/components/useProviderRegistryAutoRecheck.d.ts.map +0 -1
- package/build/server/design/components/useProviderRegistryAutoRecheck.js +0 -70
- package/build/server/design/components/useProviderRegistryAutoRecheck.js.map +0 -1
- package/build/server/products/shared/renderer/api/providerCatalogRefreshStore.d.ts +0 -19
- package/build/server/products/shared/renderer/api/providerCatalogRefreshStore.d.ts.map +0 -1
- package/build/server/products/shared/renderer/api/providerCatalogRefreshStore.js +0 -53
- package/build/server/products/shared/renderer/api/providerCatalogRefreshStore.js.map +0 -1
- package/build/server/products/shared/renderer/api/providers.d.ts +0 -17
- package/build/server/products/shared/renderer/api/providers.d.ts.map +0 -1
- package/build/server/products/shared/renderer/api/providers.js +0 -50
- package/build/server/products/shared/renderer/api/providers.js.map +0 -1
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{r as p,j as r}from"./client-BdGHAUoK.js";import{ay as Ml,I as ds,az as Aa,aA as Ra,aB as Xn,aC as Co,aD as El,aE as vr,m as l,V as ea,u as z,aF as Dl,aG as Tu,ae as ju,aH as Lu,ah as Bl,aI as Mu,aJ as Eu,aK as Du,aL as Bu,aM as ti,aN as Ps,aO as Ou,aP as ni,aQ as _u,aR as gn,aS as Fu,aT as Ol,aU as Oe,aV as _l,aW as ai,aX as Wu,aY as Uu,aZ as Ku,a_ as $u,a$ as Hu,b0 as qu,b1 as ri,b2 as Gu,b3 as Fl,b4 as Kr,b5 as $r,b6 as Hr,b7 as Vu,b8 as si,b9 as zu,ba as Yu,bb as Ju,bc as Xu,bd as Qu,am as Zu,be as vo,bf as Wl,ai as ir,bg as Br,bh as ep,bi as zn,bj as Io,bk as tp,E as qr,r as Vs,ar as So,C as lr,bl as np,bm as ap,bn as rp,bo as sp,bp as op,bq as ip,br as lp,bs as va,bt as cp,bu as As,bv as dp,bw as up,bx as Sa,by as Ul,bz as pp,bA as hp,bB as fp,bC as mp,bD as gp,bE as Cp,bF as oi,bG as vp,bH as yo,bI as Ip,bJ as Kl,bK as us,bL as Sp,bM as yp,bN as bp,bO as xp,bP as wp,bQ as kp,bR as $l,bS as Pp,bT as Hl,bU as ql,bV as Ap,bW as ii,bX as Rp,bY as qn,bZ as Gn,F as Np,b_ as Tp,b$ as jp,c0 as Lp,c1 as Mp,c2 as Ep,c3 as Dp,c4 as Bp,c5 as Gl,c6 as li,c7 as Op,c8 as _p,c9 as Fp,ca as Wp,cb as Up,cc as Kp,cd as bo,ce as ci,X as Na,cf as $p,cg as Vl,ch as Hp,ci as Rs,H as qp,cj as zs,ax as xo,ck as Ns,cl as Gp,cm as Vp,cn as zp,co as Yp,cp as Jp,cq as Xp,cr as Qp,cs as Ys,ct as Zp,cu as Pr,cv as eh,cw as Qn,au as Zn,cx as th,cy as nh,cz as ah,n as Rt,cA as rh,ag as sh,at as oh,cB as ih,cC as Js,aw as Xs,_ as lh,cD as ch,cE as dh,a3 as ps,cF as uh,cG as ph,cH as hh,cI as fh,a9 as zl,cJ as mh,an as gh,cK as Ch,av as di,as as vh,ak as Ih,b as Sh,ao as yh,ap as bh,aq as xh,$ as Yl,c as Ts,cL as wh,cM as kh,cN as Ph,cO as Ah,cP as Rh,cQ as Jl,cR as wo,cS as ko,cT as Nh,cU as Th,cV as jh,cW as Xl,cX as js,cY as Lh,cZ as Mh,c_ as Eh}from"./app-CVPqqfZo.js";async function Dh(e){const t=await fetch("/api/core",{headers:{Accept:"application/json"},signal:e});return ds(t,`cats core state returned ${t.status}`)}async function Bh(e){const t=await fetch("/api/core/approvals",{headers:{Accept:"application/json"},signal:e});return(await ds(t,`cats core approvals returned ${t.status}`)).approvals}async function hr(e){const[t,n]=await Promise.all([Dh(e),Bh(e)]);return{core:t,approvals:n}}async function Oh(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 Ml(n,`cats core approval returned ${n.status}`));try{return await hr(t)}catch{return hr()}}async function _h(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 Ml(n,`cats core operator action returned ${n.status}`));try{return await hr(t)}catch{return hr()}}async function ui(e,t){const n=e?`?path=${encodeURIComponent(e)}`:"",a=await fetch(`/api/shell/browse${n}`,{method:"GET",headers:{Accept:"application/json"},signal:t});return ds(a,`directory browse returned ${a.status}`)}async function Fh(e,t){const n=await fetch(`/api/shell/inspect-path?path=${encodeURIComponent(e)}`,{method:"GET",headers:{Accept:"application/json"},signal:t});return ds(n,`inspect path returned ${n.status}`)}async function Wh(e){await fetch("/api/shell/open-folder",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({path:e})})}const Ql=ea("en"),Ls=2;function Rn(e){return Co(e)??e.trim()}function Zl(e){const t=Rn(e.provider);return{provider:t,model:e.model===void 0?Aa(t)||void 0:e.model?.trim()||void 0,instance:e.instance===void 0?Ra(t)||void 0:e.instance?.trim()||void 0,modelSelection:e.modelSelection??null}}function Gr(e){return vr({provider:e.provider,instance:e.instance??null,model:e.model??null})}function Uh(e,t){return t(e==="strong_agent"?l.chatDraftParticipantCapabilityStrongAgent:l.chatDraftParticipantCapabilityConservativeAgent)}function Kh(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 $h(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 Hh(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 qh(e,t){switch(e){case"low":return t(l.chatDraftParticipantApprovalThresholdLow);case"medium":return t(l.chatDraftParticipantApprovalThresholdMedium);case"high":return t(l.chatDraftParticipantApprovalThresholdHigh)}}function Gh(e,t={},n=Ql){const a=t.bootstrapTreatment==="strong_agent",s=Uh(t.bootstrapTreatment,n),o={autonomy:t.autonomy??(a?"milestone_plan":"single_step"),toolScope:t.toolScope??"read_only",approvalThreshold:t.approvalThreshold??"low"},i=Kh(o,n);return{capabilityLabel:s,executionLabel:Gr(e),policySummary:n(l.chatDraftParticipantPolicySummary,{autonomy:$h(o.autonomy,n),approvalThreshold:qh(o.approvalThreshold,n)}),toolGrantSummary:n(l.chatDraftParticipantToolGrantSummary,{toolScope:Hh(o.toolScope,n)}),requiresActivationReview:i.length>0,reviewReasons:i}}function Vh(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 Po(e,t){const n=e.name?.trim();if(n)return n;const a=El(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 Pn(e){return{participantId:e.participantId?.trim()||e.randomUUID?.()||globalThis.crypto?.randomUUID?.()||`participant-${Date.now()}`,presetId:e.presetId?.trim()||void 0,name:Po({name:e.name,provider:e.provider,instance:e.instance},e.takenNames),provider:Rn(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 zh(e,t=Ls){const n=Zl(e),a=Number.isFinite(t)?Math.max(0,t):Ls,s=Math.min(Ls,a),o=[n.provider,...Xn.filter(u=>u!==n.provider)].slice(0,s),i=[];return o.map((u,c)=>{const d=Pn(c===0?{provider:n.provider,instance:n.instance,model:n.model,modelSelection:n.modelSelection,takenNames:i,randomUUID:()=>globalThis.crypto?.randomUUID?.()??`temp-${u}-${Date.now()}`}:{provider:u,instance:Ra(u),model:Aa(u)||void 0,modelSelection:null,takenNames:i,randomUUID:()=>globalThis.crypto?.randomUUID?.()??`temp-${u}-${Date.now()}`});return i.push(d.name),d})}function Yh(e){return e.participant.name===Po({provider:e.participant.provider,instance:e.participant.instance??null},e.siblingNames)}function pi(e){if(e.participants.length===0)return e.participants;const[t,...n]=e.participants;if(t.presetId)return e.participants;const a=Zl(e.target),s=n.map(u=>u.name),o=Yh({participant:t,siblingNames:s})?Po({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 Ms(e){const t=Rn(e.baseProvider)||Xn[0]||"claude",n=[t,...Xn.filter(o=>o!==t)],a=new Map(n.map(o=>[o,0]));e.existingParticipants.forEach(o=>{const i=Rn(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]??Xn[0]??t);return Pn({provider:s,instance:Ra(s),model:Aa(s)||void 0,modelSelection:null,takenNames:e.takenNames??e.existingParticipants.map(o=>o.name),randomUUID:e.randomUUID})}function hi(e,t,n,a={}){return e!=="group"?[]:a.autoSeedGroupParticipants===!1||t.length>0?t:n()}function fi(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 ec(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 fi(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?fi(s,e.maxAudienceParticipants):t[0]?.participantId?[t[0].participantId]:[]}function Ar(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,u,c)=>c.indexOf(i)===u&&n.has(i)).filter(i=>i!==e.removedParticipantKey&&a.has(i));return o.length===0?e.nextParticipantKeys[0]?[e.nextParticipantKeys[0]]:[]:o}function tc(e){const t=Rn(e);return{provider:t,model:Aa(t)||null,instance:Ra(t),modelSelection:null}}function mi(e,t={}){if(t.includeCompareTarget===!1)return[e];const n=Rn(e.provider),a=Xn.find(s=>s!==n)??"codex";return[e,tc(a)]}function Jh(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 Xh(e,t){const n=new Set(e.map(o=>Rn(o.provider))),a=Rn(t.provider),s=Xn.find(o=>!n.has(o))??Xn.find(o=>o!==a)??a;return s===a?{provider:a,model:t.model,instance:t.instance,modelSelection:t.modelSelection}:tc(s)}function Qh(e,t){return e.some(n=>n.presetId===t)}const Zh=[l.chatNewChatDraftDefaultGreeting,l.chatNewChatDraftGreetingNap,l.chatNewChatDraftGreetingKeyboard,l.chatNewChatDraftGreetingLetsGo,l.chatNewChatDraftGreetingStandby,l.chatNewChatDraftGreetingTaskReady,l.chatNewChatDraftGreetingOnDuty];function ef(e){return(e??[]).map(t=>t.trim()).filter(t=>t.length>0)}function tf(e={}){const t=ef(e.pool),n=Zh.map(o=>(e.t??Ql)(o)),a=t.length>0?t:n,s=e.random??Math.random;return a[Math.floor(s()*a.length)]}const nf=["post","photo","video","music","file"],af="v1",Qs="cats:",nc="companion";function Ao(e){const t=typeof e=="string"?e.trim():"";if(!t.toLowerCase().startsWith(`${Qs}//`))return{status:"invalid",rawText:e,reason:"wrong_scheme"};const a=t.slice(`${Qs}//`.length),s=a.indexOf("/");if((s>=0?a.slice(0,s):a).toLowerCase()!==nc)return{status:"invalid",rawText:e,reason:"wrong_host"};const i=s>=0?a.slice(s+1):"",u=i.length===0?[]:i.split("/"),c=[];for(const I of u)try{c.push(decodeURIComponent(I))}catch{return{status:"invalid",rawText:e,reason:"malformed_percent_encoding"}}const d=c[0];if(typeof d=="string"&&d!==af)return{status:"unsupported_version",rawText:e,version:d};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"}:rf(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 rf(e){return nf.includes(e)}const gi=1;function sf(e){if(!Ci(e)||e.schemaVersion!==gi)return null;const t=e.referenceText;if(typeof t!="string")return null;const n=Ao(t);if(n.status!=="parsed")return null;const a=n.reference,s=Ds(e.title)??"",o=Ds(e.capturedAt)??"";return o.length===0?null:{schemaVersion:gi,referenceText:t,reference:a,title:s,subtitle:Es(e.subtitle),description:Es(e.description),thumbnailUrl:Es(e.thumbnailUrl),catName:Ds(e.catName)??"Companion",capturedAt:o,snapshot:Ci(e.snapshot)?e.snapshot:null}}function Ci(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Es(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ds(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}const of=`${Qs}//${nc}/`,lf=/[\s<>'" ]/u;function cf(e){if(typeof e!="string"||e.length===0)return[];const t=[],n=e.toLowerCase(),a=of.toLowerCase();let s=0;for(;s<e.length;){const o=n.indexOf(a,s);if(o===-1)break;const i=df(e,o),u=e.slice(o,i),c=Ao(u);t.push({start:o,end:i,rawText:u,parseResult:c}),s=i}return t}function df(e,t){for(let n=t;n<e.length;n+=1){const a=e.charAt(n);if(lf.test(a))return n}return e.length}function uf(e){return e.filter(t=>t.status==="active").length}function pf(e){return e.roomMode==="direct_message"?"direct_message":"chat_channel"}function ac(e){const t=pf({roomMode:e.roomMode,participants:e.participants});return e.channelKind==="direct_message"||t==="direct_message"?"direct_message":"chat_channel"}function rc(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 hf(e){return uf(rc(e))}function Ro(e){return hf(e)>0}function ff(e){return ac({channelKind:e.channelKind,roomMode:e.roomRouting?.mode==="direct_message"?"direct_message":"chat_channel",participants:rc(e)})}function No(e){return ff(e)==="direct_message"}function sc(e){return!No(e)&&!Ro(e)&&!!e.pendingProvider?.trim()}function An(e){return!No(e)&&!Ro(e)}function mf(e){return!No(e)&&Ro(e)}function Zs(e){return mf(e)}function rw(e){return ac({channelKind:e.channelKind,roomMode:e.roomMode==="direct_message"?"direct_message":"chat_channel",participants:[]})==="direct_message"}const vi=250,gf=4e3;let Cf=1;function vf(){const[e,t]=p.useState([]),n=p.useRef(new Map),a=p.useCallback(i=>{t(c=>c.map(d=>d.id===i?{...d,fading:!0}:d));const u=setTimeout(()=>{t(c=>c.filter(d=>d.id!==i)),n.current.delete(i)},vi);n.current.set(i,u)},[]),s=p.useCallback(i=>{const u=Cf++,c=i.level??"info";if(t(d=>[...d,{id:u,title:i.title,message:i.message,level:c,fading:!1}]),c!=="error"){const d=setTimeout(()=>a(u),gf);n.current.set(u,d)}},[a]),o=p.useCallback(()=>{t(u=>u.map(c=>({...c,fading:!0})));const i=setTimeout(()=>{t([]),n.current.clear()},vi);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 If={info:"notificationInfo",success:"notificationSuccess",warning:"notificationWarning",error:"notificationError"};function Sf({notifications:e,onDismiss:t}){const{t:n}=z();return e.length===0?null:r.jsx("div",{className:"notificationContainer",children:e.map(a=>r.jsxs("div",{className:`notification ${If[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 Vr(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 zr(e){return e==="direct_message"}function oc(e){return e==="default_chat"}const yf=ea("en");function bf(e,t){return!e||!t?!1:zr(Vr(e))&&e.roomRouting.defaultRecipientId===t}function xf(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,u=Dl(i?.selectedChannel??null),c=i?.selectedChannelId??null,d=u?.id??null,h=Tu(u),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?ju(i.channels,t):null,C=n&&u?.id===n?u:null,I=a&&t&&bf(u,t)?u:null,y=i?[i.selectedChannelId,u?.id??"",u?.updatedAt??"",u?.messages.length??0,u?.roomRouting.workflow.activeTurn?.updatedAt??"",i.channels.length].join("|"):"";return{readyPayload:o,readyChat:i,readySelectedChannel:u,selectedChannelId:c,selectedChannelViewId:d,selectedChannelEntryLifecycle:h,routeChannelExists:f,routeChannelTitle:m,routeDirectLaneSummary:v,selectedChannel:C,selectedDirectLane:I,operatorRefreshKey:y}}function wf(e){const{addCatOpen:t,draftCatIds:n,draftDefaultRecipientCatId:a,pathname:s,payload:o,routeDirectLaneSummary:i,selectedChannel:u,selectedDirectLane:c,showingMyCatDirectLane:d,showingNewChatDraft:h,t:f=yf}=e,m=s.startsWith("/settings")?"settings":"chats",v=d?c:null,C=u??v,I=C?Vr(C):null,y=u?Vr(u):null,g=zr(I)?C?.roomRouting.defaultRecipientId??null:null,x=C?.assignedCats.filter(b=>b.status==="active")??[],S=new Set(C?.assignedCats.map(b=>b.catId)??[]),k=Lu(o)??f(l.sharedOrchestratorFallbackName),w=o.chat.cats.find(b=>b.id===o.chat.bossCatId)?.avatarColor??null,P=!!o.chat.bossCatId&&!oc(y)&&!zr(y)&&!x.some(b=>b.catId===o.chat.bossCatId),j=o.chat.cats.filter(b=>b.status==="active"&&b.id!==o.chat.bossCatId&&Bl(b)),N=j.length,D=new Set(n);return{surface:m,directLaneChannel:v,activeConversationMode:I,activeMyCatId:g,activeAssignedCats:x,assignedCatIds:S,bossCatName:k,bossCatAvatarColor:w,showBossCatAvatar:P,selectableCats:j,assignableCatCount:N,draftCatIdSet:D,showDirectLaneBoot:!!(i&&!v),showAddCatPanel:t&&(!!u||h&&!a)}}function kf({state:e,BootShell:t,unavailableTitle:n,renderReady:a}){const{t:s}=z();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 Pf({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(Mu,{dialog:a,onClose:s})]})}function Af({payload:e,sidebarOpen:t,sidebar:n,settingsMode:a,busy:s,appContent:o,confirmDialog:i,onPayloadUpdate:u,onFeedback:c,onBusy:d,onResetSetup:h,onConfirmClose:f}){return r.jsx(Pf,{sidebarOpen:t,sidebar:n,mainContent:a?r.jsx(Eu,{payload:e,onPayloadUpdate:u,busy:s,onFeedback:c,onBusy:d,onResetSetup:h}):o,confirmDialog:i,onConfirmClose:f})}function Rf(){const[e,t]=p.useState(!1),[n,a]=p.useState(()=>Du(typeof window>"u"?null:window.localStorage)),[s,o]=p.useState(null),[i,u]=p.useState(!1),[c,d]=p.useState(!1),[h,f]=p.useState(!1),m=p.useRef(null),v=p.useRef(null),C=p.useRef(null),I=p.useRef(null),y=p.useRef(null),g=p.useRef(null);p.useEffect(()=>{if(!s&&!i&&!h&&!c)return;function w(P){const j=P.target;if(s){const N=document.querySelector(".recentOverflowMenu")??document.querySelector(".myCatOverflowMenu"),D=P.target.closest?.(".recentOverflowButton, .myCatOverflowButton");!N?.contains(j)&&!D&&o(null)}i&&v.current&&!v.current.contains(j)&&u(!1),h&&y.current&&!y.current.contains(j)&&f(!1),c&&C.current&&!C.current.contains(j)&&d(!1)}return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[s,i,h,c]),p.useEffect(()=>{Bu(typeof window>"u"?null:window.localStorage,n)},[n]);const x=p.useCallback(w=>{w.style.height="auto";const P=200;w.scrollHeight>P?(w.style.height=`${P}px`,w.style.overflowY="auto"):(w.style.height=`${w.scrollHeight}px`,w.style.overflowY="hidden")},[]);function S(){a(w=>(w&&t(!1),!w))}function k(w){if(n)return;const P=w.target;P.closest('button, a, input, textarea, select, [role="button"]')||P.closest(".accountMenu")||a(!0)}return{accountMenuOpen:e,setAccountMenuOpen:t,sidebarOpen:n,setSidebarOpen:a,overflowMenuOpenId:s,setOverflowMenuOpenId:o,plusMenuOpen:i,setPlusMenuOpen:u,addCatOpen:c,setAddCatOpen:d,channelPlusMenuOpen:h,setChannelPlusMenuOpen:f,accountMenuRef:m,plusMenuRef:v,addCatPanelRef:C,fileInputRef:I,channelPlusMenuRef:y,channelFileInputRef:g,autoResize:x,onToggleSidebar:S,onCollapsedSidebarClick:k}}const Nf=300;function Tf(e){return e.surface==="chat"&&e.directLaneCatId?`chat:${e.directLaneCatId}`:e.surface}function jf(e){const{t}=z(),{onSelectPath:n,surface:a,directLaneCatId:s=null}=e,[o,i]=p.useState(""),[u,c]=p.useState(""),[d,h]=p.useState(""),[f,m]=p.useState([]),[v,C]=p.useState(!1),[I,y]=p.useState(""),g=p.useRef(ti(e.initialPreferences)),x=p.useRef(new Map),S=p.useRef(new Map),k=p.useRef(null),w=p.useCallback(b=>{let R=b;for(const L of S.current.values())R=Ps(R,L.scope,L.path);for(const L of x.current.values())R=Ps(R,L.scope,L.path);return R},[]);p.useEffect(()=>{const b=ti(e.initialPreferences);g.current=w(b)},[e.initialPreferences,w]);const P=p.useCallback(()=>{for(const[b,R]of x.current)S.current.has(b)||(x.current.delete(b),S.current.set(b,R),Ou({surface:R.scope.surface,directLaneCatId:R.scope.directLaneCatId??null,path:R.path}).catch(()=>{}).finally(()=>{S.current.get(b)===R&&S.current.delete(b),x.current.has(b)&&P()}))},[]),j=p.useCallback(b=>{if(k.current&&(clearTimeout(k.current),k.current=null),b){P();return}k.current=setTimeout(()=>{k.current=null,P()},Nf)},[P]),N=p.useCallback((b,R=!1)=>{const L={surface:a,directLaneCatId:s},O=Tf(L),Y=ni(g.current,L),$=x.current.has(O);Y===b&&!$||(g.current=Ps(g.current,L,b),x.current.set(O,{scope:L,path:b}),j(R))},[s,j,a]);p.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),P()},[P]);const D=p.useCallback(async b=>{C(!0),y("");try{const R=await ui(b);c(R.current),h(R.parent),i(R.current),m(R.entries),y(R.error??""),R.error||N(R.current)}catch(R){y(R instanceof Error?R.message:t(l.sharedFolderBrowserLoadError)),m([]),b&&i(b)}finally{C(!1)}},[N,t]),T=p.useCallback(async b=>{const R=ni(g.current,{surface:a,directLaneCatId:s}),L=b?.trim()?b:R;C(!0),y(""),i(L??"");try{const O=await _u({browse:ui,requestedPath:b??null,rememberedPath:R});c(O.current),h(O.parent),i(O.current),m(O.entries),y(O.error??""),O.error||N(O.current)}catch(O){y(O instanceof Error?O.message:t(l.sharedFolderBrowserLoadError)),m([])}finally{C(!1)}},[s,N,a,t]),A=p.useCallback(()=>{!u||I||(N(u,!0),n(u))},[u,I,n,N]);return{browseFolder:D,folderBrowseCurrentPath:u,folderBrowseEntries:f,folderBrowseError:I,folderBrowseLoading:v,folderBrowseParentPath:d,folderBrowsePath:o,openFolderBrowser:T,selectCurrentFolder:A,setFolderBrowsePath:i}}const Lf="container-chat-root";function ic(e){return`conversation-channel-${e}`}function Mf(e){return Lf}function Yr(e,t,n){return`lane-${e}-${t||n}`}function Ii(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function nr(e){return typeof e=="string"&&e.trim().length>0?e:null}function Ef(e){return e==="text"||e==="tool"||e==="status"?e:null}function Df(e){return e==="streaming"||e==="complete"||e==="error"?e:null}function eo(e){const t=Ii(e.block);if(!t)return null;const n=nr(t.id),a=Ef(t.kind),s=Df(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:nr(t.title),text:nr(t.text)??"",toolName:nr(t.toolName),toolId:nr(t.toolId),metadata:Ii(t.metadata)}}function lc(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function rn(e){return typeof e=="string"&&e.length>0?e:null}function Si(e){return rn(e.toolName)??rn(e.name)}function yi(e){return rn(e.toolId)??rn(e.toolUseId)??rn(e.tool_use_id)??rn(e.id)}function Bf(e){const t=e.toolArgs??e.arguments??e.input;return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function Of(e){return Array.isArray(e)?_f(e).flatMap(t=>{if(typeof t=="string")return t.length>0?[t]:[];const n=lc(t);if(!n)return[];const a=rn(n.text)??rn(n.content)??"";return a.length>0?[a]:[]}).join(""):""}function Bs(e){return rn(e.text)??rn(e.content)??Of(e.content)??""}function _f(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n=="string"){t.push(n);continue}const a=lc(n);if(!a)continue;const s=a.content;if(Array.isArray(s)){t.push(...s);continue}t.push(a)}return t}function cc(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=Bs(t);return s.length>0?{kind:"text",text:s,toolName:null,toolId:null}:null}if(a==="tool_use"){const s=Bf(t);return{kind:"tool_use",text:Bs(t),toolName:Si(t),toolId:yi(t),...s?{toolArgs:s}:{}}}return a==="tool_result"?{kind:"tool_result",text:Bs(t),toolName:Si(t),toolId:yi(t),...typeof t.isError=="boolean"?{isError:t.isError}:{}}:null}const bi=200,xi="__catsLiveTraceStore",Ff="__catsLiveTrace",Wf="__catsLiveTraceEnabled";function Uf(e){const t=To();e&&!t.enabled&&(t.entries.length=0,t.seq=0,t.lastSignature=null),t.enabled=e,jo(t)}function dc(){return To().enabled}function uc(e){const t=To();if(!t.enabled)return;const n=e.signature??qf(e);n&&t.lastSignature===n||(t.lastSignature=n,t.seq+=1,t.entries.push($f("browser",t.seq,e)),Hf(t.entries),jo(t))}function To(){const e=globalThis,t=e[xi];if(Kf(t))return t;const n={enabled:!1,seq:0,entries:[],lastSignature:null};return e[xi]=n,jo(n),n}function Kf(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 jo(e){const t=globalThis;t[Ff]=e.entries,t[Wf]=e.enabled}function $f(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 Hf(e){e.length<=bi||e.splice(0,e.length-bi)}function qf(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 wi=8,ki=220,pc=1200,or={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 Lo(e){const t=he(e.sourceMessageId)??"no-source",n=he(e.laneId)??e.targetStateId??he(e.sessionId)??e.identityParticipantId??e.participantId??e.catId??he(e.speakerLabel)??"anonymous";return`${t}:${n}:segment:${e.segmentIndex}`}function Cn(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()||Lo({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 hc(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=ze(e);return!e?.active||t.length===0?null:t.at(-1)??null}function ze(e){return e?.active?e.segments.length>0?hc(e.segments):e.phase==="idle"?[]:[Cn({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 et(e,t=e.length>0){const n=hc(e),a=n.at(-1)??null;return!a||!t?or:{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 Gf(e,t){return!e.active||e.segments.length===0?et([t]):et([...e.segments.slice(0,-1),t])}function fc(e,t){const n=Ge(e);if(!n)return et([t]);const a=n.phase==="sealed"?n:{...n,phase:"sealed"};return et([...e.segments.slice(0,-1),a,t])}function to(e){return e.identityParticipantId??e.participantId??null}function mc(e,t){return e?hs(e,t):!1}function hs(e,t){const n=e.sourceMessageId??null,a=t.sourceMessageId??null,s=e.laneId??null,o=t.laneId??null,i=e.targetStateId??null,u=t.targetStateId??null,c=to(e),d=to(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&&u!==null?i===u:n===a&&c===d&&h===f&&m===v}function Vf(e){const t=[];for(const n of e){const a=[...n.contentBlocks].sort((u,c)=>u.index-c.index);if(a.length===0){t.push(n);continue}let s=[],o=0;const i=u=>{s.length!==0&&(t.push(Cn({...n,id:Lo({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:u,segmentIndex:n.segmentIndex+o,contentBlocks:s})),o+=1,s=[])};for(let u=0;u<a.length;u+=1){const c=a[u],d=s.some(h=>h.kind==="text");if(c.kind==="text"){if(s.length===0||!d){s.push(c);continue}i("sealed"),s.push(c);continue}if(s.length===0||!d){s.push(c);continue}i("sealed"),s.push(c)}i(n.phase)}return t}function zf(e,t){const n=Ge(e);return n?Gf(e,t(n)):e}function gc(e,t,n){const a=ze(e);return a[t]?et(a.map((o,i)=>i===t?n(o):o)):e}function Yf(e,t,n){const a=ze(e),s=a.findIndex(t);if(s<0)return e;const o=a.map((i,u)=>u===s?n(i):i);return et(o)}function Cc(e,t){const n=ze(e);for(let a=n.length-1;a>=0;a-=1)if(hs(n[a],t))return a;return-1}function Mo(e,t){const n=Eo(e,t),a=Cc(e,n);if(a>=0){const o=ze(e);return{segmentIndex:a,segment:o[a]??null}}const s=Ge(e);return{segmentIndex:s?ze(e).length-1:-1,segment:s}}function vn(e,t,n){const a=Mo(e,t);return a.segmentIndex<0||!a.segment?e:gc(e,a.segmentIndex,n)}function Jf(e,t,n){const a=ze(e),s=a[t];if(!s)return fc(e,n);const o=s.phase==="sealed"?s:{...s,phase:"sealed"};return et([...a.slice(0,t),o,n,...a.slice(t+1)])}function ba(e){return e.contentBlocks.some(t=>t.kind==="text"&&t.text.trim().length>0)}function vc(e){return e.contentBlocks.some(t=>t.kind==="text"&&t.status==="streaming"&&t.text.trim().length>0)}function Xf(e,t){return e.phase==="streaming"&&vc(e)&&e.lastVisibleContentAtMs!=null&&t-e.lastVisibleContentAtMs>=pc}function Qf(e,t=Date.now()){if(!e?.active)return null;const n=ze(e).filter(a=>a.phase==="streaming"&&vc(a)).map(a=>a.lastVisibleContentAtMs).filter(a=>typeof a=="number").map(a=>a+pc).filter(a=>a>t);return n.length===0?null:Math.min(...n)}function Zf(e,t){const n=e[t];if(!n||!ba(n))return null;let a=0;for(let s=0;s<e.length;s+=1){const o=e[s];if(!(!ba(o)||!mc(o,n))){if(s===t)return a;a+=1}}return null}function Ic(e){return e.contentBlocks.length>0&&e.contentBlocks.every(t=>bc(t))}function no(e,t){return e.id===t.id||e.index===t.index&&e.kind===t.kind}function Os(e){return e.contentBlocks.length>0||e.progressText.trim().length>0||e.events.length>0||e.tools.length>0}function em(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 Sc(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 yc(e){const t=e.revealIdentity===!0;return et([Cn({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 Eo(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"),u=Object.prototype.hasOwnProperty.call(t,"laneId"),c=Object.prototype.hasOwnProperty.call(t,"identityParticipantId"),d=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=d?nn(t.participantId):n?.participantId??e.participantId,I=c?nn(t.identityParticipantId):d?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:u?nn(t.laneId)??s:s,targetStateId:m?nn(t.targetStateId)??o:o,identityParticipantId:I,participantId:C,catId:y,activeCatIds:y?[y]:[],speakerLabel:g}}function tm(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 nm(e,t,n,a=Date.now()){if(!e.active)return e;const s=rm(e,t,n);switch(t){case"progress":return cm(s,n,a);case"text":return dm(s,n,a);case"tool_use":return pm(s,n,a);case"tool_result":return hm(s,n,a);case"content_block":return fm(s,n,a);case"result":return Ai(s,n,a);case"session_closed":return Mo(s,n).segment?.phase==="waiting"?s:Ai(s,n,a);case"error":return mm(s,n,a);default:return s}}function am(e,t,n,a){if(!e)return!1;const s=!hs(e,t);if(e.phase==="sealed"){if(n==="content_block"){const o=eo(a);if(o&&e.contentBlocks.some(i=>no(i,o)))return!1}return!0}if(s)return Os(e);if(e.phase==="waiting"&&!Os(e)||e.phase==="streaming"&&!Os(e))return!1;switch(n){case"progress":case"tool_use":case"tool_result":case"error":return ba(e);case"content_block":{const o=eo(a);if(!o)return!1;if(o.kind==="text"){if(Ic(e))return!1;const i=e.contentBlocks.some(u=>u.id===o.id);return ba(e)&&!i}return ba(e)}default:return!1}}function Pi(e,t,n,a){const s=mc(e,t);return Cn({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 rm(e,t,n){const a=Eo(e,n),s=tm(e,n),o=ze(e),i=Cc(e,a),u=i>=0?o[i]??null:Ge(e);if(am(u,a,t,n)){const d=Pi(u,a,s,t==="session_closed"?"waiting":"streaming");return i>=0&&i<o.length-1?Jf(e,i,d):fc(e,d)}if(!u)return et([Pi(null,a,s,"waiting")]);const c=d=>({...d,...a,...s,id:Lo({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:d.segmentIndex})});return i>=0?gc(e,i,c):zf(e,c)}function sm(e){if(!e)return"";const t=ze(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 om(e,t){return(e.phase==="waiting"||e.phase==="streaming")&&e.requiresSessionStartConfirmation&&!wc(t,et([e]),e.sessionStartedAt)?Cn({...e,phase:"waiting",participantId:null,catId:null,activeCatIds:[],catName:null,speakerLabel:null,progressText:"",progressKind:null,tools:[],contentBlocks:[],events:[]}):e}function im(e,t,n,a=t,s=Date.now()){if(!e?.active)return e??null;const o=ze(e),i=Vf(o),u=i.map(g=>om(g,a)),c=u.filter((g,x)=>{const S=u.slice(x+1).some(w=>!hs(g,w)),k=Zf(i,x)??g.segmentIndex;return!(km(t,g,k)||g.phase==="sealed"&&S&&he(g.sourceMessageId)&&ba(g)&&fs(t,g.sourceMessageId,et([g]))||g.phase==="sealed"&&S&&!em(g)||x>0&&!Sc(g))}),d=g=>{if(!n||g.events.some(P=>P.eventType==="result"||P.eventType==="error"))return null;const S=Date.parse(n);if(!Number.isFinite(S))return null;const k=et([g]);return(fr(k)?Rr(t,P=>ao(P,k)):Rr(t))>S?null:Cn({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=d(o.at(-1));if(g)return et([g])}return null}const h=c.at(-1);if(h.phase==="streaming"&&Xf(h,s)){const g=Cn({...h,phase:"sealed"}),x=d(g);x&&(c[c.length-1]=g,c.push(x))}else if(h.phase==="sealed"){const g=d(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:et(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 _s({liveIndicator:m,messages:t,activeTurnUpdatedAt:n,visible:!0,reason:"segment_timeline_visible",latestReplyTimestamp:Number.NEGATIVE_INFINITY}),m;if(fr(m)){const g=Rr(t,S=>ao(S,m)),x=g<v;return _s({liveIndicator:m,messages:t,activeTurnUpdatedAt:n,visible:x,reason:x?"speaker_still_streaming":"same_speaker_reply_visible",latestReplyTimestamp:g}),x?m:null}const I=Rr(t),y=I<v;return _s({liveIndicator:m,messages:t,activeTurnUpdatedAt:n,visible:y,reason:y?"visible_before_identity":"reply_after_active_turn",latestReplyTimestamp:I}),y?m:null}function lm(e,t,n,a=t,s=Date.now()){const o=im(e,t,n,a,s),i=t.at(-1);return{visibleLiveIndicator:o,transcriptScrollKey:[t.length,i?.id??"",i?.createdAt??"",sm(o)].join("::")}}function cm(e,t,n){const a=Ir(t.text),s=Gt(t.metadata),o=typeof s?.kind=="string"?s.kind:null;return a?vn(e,t,i=>({...i,phase:"streaming",progressText:a,progressKind:o,events:Ta(i.events,{eventType:"progress",label:Im(o),text:a,tone:o==="reasoning"?"default":"active",kind:o,toolName:null,toolId:null}),lastActivityAtMs:n,lastVisibleContentAtMs:n})):vn(e,t,i=>({...i,phase:"streaming",...o?{progressKind:o}:{},lastActivityAtMs:n}))}function dm(e,t,n){const a=typeof t.text=="string"?t.text:"",s=Ir(t.text);return!a&&!s?vn(e,t,o=>({...o,phase:"streaming",lastActivityAtMs:n})):vn(e,t,o=>({...o,phase:"streaming",progressText:"",progressKind:null,contentBlocks:um(o.contentBlocks,a),events:s?Ta(o.events,{eventType:"text",label:"Text",text:s,tone:"default",kind:"text",toolName:null,toolId:null}):o.events,lastActivityAtMs:n,lastVisibleContentAtMs:n}))}function um(e,t){if(!t||e.some(s=>!bc(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 bc(e){return e.kind==="text"&&e.metadata?.syntheticTextFallback===!0}function pm(e,t,n){const a=cc({type:"tool_use",...t}),s=(a?.kind==="tool_use"?a.toolName:he(t.toolName))||"tool",o=a?.kind==="tool_use"?a.toolId:he(t.toolId);return vn(e,t,i=>{const u=gm(i.tools,{toolName:s,toolId:o||s});return{...i,phase:"streaming",tools:u,events:Ta(i.events,{eventType:"tool_use",label:"Tool",text:`Started ${s}`,tone:"active",kind:"tool",toolName:s,toolId:o||s}),lastActivityAtMs:n}})}function hm(e,t,n){const a=cc({type:"tool_result",...t}),s=a?.kind==="tool_result"?a.toolId:he(t.toolId),o=Mo(e,t).segment,i=(a?.kind==="tool_result"?a.toolName:he(t.toolName))||vm(o?.tools??[],s)||"tool",u=Ir(a?.kind==="tool_result"?a.text:t.text),c=t.isError===!0,d=u?`${c?"Failed":"Completed"} ${i}: ${u}`:`${c?"Failed":"Completed"} ${i}`;return vn(e,t,h=>({...h,phase:"streaming",tools:Cm(h.tools,s,i),events:Ta(h.events,{eventType:"tool_result",label:c?"Tool Error":"Tool",text:d,tone:c?"error":"success",kind:"tool",toolName:i,toolId:s||i}),lastActivityAtMs:n}))}function Ai(e,t={},n){return vn(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:Ta(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 fm(e,t,n){const a=eo(t);if(!a)return e;const s=i=>{const c=[...(a.kind==="text"&&Ic(i)?[]:i.contentBlocks).filter(d=>!no(d,a)),a].sort((d,h)=>d.index-h.index).slice(-12);return{...i,phase:i.phase==="sealed"?"sealed":"streaming",contentBlocks:c,lastActivityAtMs:n,lastVisibleContentAtMs:n}},o=Yf(e,i=>i.contentBlocks.some(u=>no(u,a)),s);return o!==e?o:vn(e,t,s)}function mm(e,t,n){const a=Ir(t.text)||"Finishing...";return vn(e,t,s=>({...s,phase:"sealed",progressKind:"error",progressText:a,events:Ta(s.events,{eventType:"error",label:"Error",text:a,tone:"error",kind:"error",toolName:null,toolId:null}),lastActivityAtMs:n,lastVisibleContentAtMs:n}))}function gm(e,t){return e.some(n=>n.toolId===t.toolId&&!n.done)?e:[...e,{...t,done:!1}]}function Cm(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 vm(e,t){return t?e.find(n=>n.toolId===t)?.toolName??null:null}function Ta(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=Ir(`${n.text} ${t.text}`),s={...n,text:a};return Ri([...e.slice(0,-1),s])}return Ri([...e,t])}function Ri(e){return e.length<=wi?e:e.slice(e.length-wi)}function Im(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 Ir(e){if(typeof e!="string")return"";const t=e.replace(/\s+/g," ").trim();return t?t.length>ki?`${t.slice(0,ki-1)}…`:t:""}function xc(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 fs(e,t,n){const a=e.findIndex(s=>s.id===t);return a===-1?!1:e.slice(a+1).some(s=>cr(s)&&ao(s,n))}function Rr(e,t){return e.reduce((n,a)=>{if(!cr(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 cr(e){return e.senderKind!=="user"&&e.senderKind!=="system"}function fr(e){return e?.active?!!(he(e.participantId)||he(e.speakerLabel)||e.catId||e.activeCatIds.some(t=>t.trim().length>0)):!1}function ao(e,t){const n=he(t.laneId);if(n&&Bo(e,{laneId:n,sourceMessageId:t.sourceMessageId}))return!0;const a=he(t.targetStateId);if(a)return Ac(e,{targetStateId:a,sessionId:t.sessionId,sourceMessageId:t.sourceMessageId});const s=Do(e),o=he(t.identityParticipantId)??he(t.participantId)??t.catId??t.activeCatIds.find(u=>u.trim().length>0)??null;if(s&&o&&s===o)return!0;if(o)return!1;const i=he(t.speakerLabel);return i?he(e.senderName)===i||xm(e)===i:!1}function wc(e,t,n){const a=he(t.laneId),s=he(t.targetStateId),o=he(t.sessionId),i=!!(a||s),u=(()=>{if(!n)return null;const c=Date.parse(n);return Number.isNaN(c)?null:c})();return e.some(c=>{if(Or(c)!=="session_started")return!1;const d=Date.parse(c.createdAt);if(Number.isNaN(d)||u!=null&&d<u)return!1;let h=!1;if(a&&(h=Bo(c,{laneId:a,sourceMessageId:t.sourceMessageId})),!h&&s&&(h=Ac(c,{targetStateId:s,sessionId:o})),!h&&o){const m=kc(c);h=!!(m&&m===o)}const f=he(t.identityParticipantId)??he(t.participantId);if(f){if(f==="orchestrator")return Ni(c)==="orchestrator";const m=Do(c);return m?m!==f?!1:i?h:!0:h}return h?!0:Ni(c)==="orchestrator"})}function Sm(e,t){return wc(t,et([e]),e.sessionStartedAt)}function _s(e){if(!dc())return;const t=e.messages.at(-1),n=t?.channelId??null;uc({event:"visibility_decision",channelId:n,conversationId:n?ic(n):null,turnId:bm(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 Gt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Do(e){const t=Gt(e.metadata);return he(t?.targetId)||he(t?.sourceRefId)||he(t?.participantId)}function kc(e){const t=Gt(e.metadata);return he(t?.sessionId)}function ym(e){const t=Gt(e.metadata);return he(t?.laneId)}function Pc(e){const t=Gt(e.metadata);return he(t?.targetStateId)}function Ni(e){const t=Gt(e.metadata);return he(t?.targetKind)}function Or(e){const t=Gt(e.metadata);return he(t?.event)}function Jr(e){const t=Gt(e.metadata);return he(t?.sourceMessageId)}function bm(e){if(!e)return null;const t=Gt(e.metadata);return he(t?.turnId)}function Fs(e){const t=Gt(e.metadata);return typeof t?.segmentIndex=="number"&&Number.isFinite(t.segmentIndex)?t.segmentIndex:null}function xm(e){const t=Gt(e.metadata);return he(t?.executionLabelSnapshot)}function Ac(e,t){const n=he(t.targetStateId),a=he(t.sourceMessageId);if(n){const s=Pc(e);if(s&&s===n){if(!a)return!0;const o=Jr(e);return!o||o===a}}return wm(e,{sessionId:t.sessionId,sourceMessageId:a})}function Bo(e,t){const n=he(t.laneId);if(!n)return!1;const a=ym(e);return!(!a||a!==n)}function wm(e,t){const n=he(t.sessionId);if(!n)return!1;const a=kc(e);if(!a||a!==n)return!1;const s=he(t.sourceMessageId);if(!s)return!0;const o=Jr(e);return!o||o===s}function km(e,t,n){const a=he(t.sourceMessageId);if(t.laneId||t.targetStateId)return e.some(i=>cr(i)&&Or(i)==="assistant_turn_segment"&&(Bo(i,{laneId:t.laneId})||t.targetStateId&&(!a||Jr(i)===a)&&Pc(i)===t.targetStateId)&&Fs(i)===n);const s=to(t);if(t.phase==="sealed"&&s&&a)return e.some(i=>cr(i)&&Or(i)==="assistant_turn_segment"&&Jr(i)===a&&Fs(i)===n&&Do(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,u)=>u>o&&cr(i)&&Or(i)==="assistant_turn_segment"&&Fs(i)===n)}function he(e){return typeof e!="string"?null:e.trim()||null}function nn(e){return e==null?null:he(e)}function Pm(e){return e.key==="Enter"&&!e.shiftKey&&!e.ctrlKey&&!e.metaKey&&!e.altKey&&!e.isComposing}function Rc(e){return e?.kind==="composer"&&e.phase==="send"||gn(e,"dispatch")}function Am(e){return e?.kind==="composer"&&e.phase==="stop"||gn(e,"stop")}function Rm(e){return e?.kind==="composer"&&e.phase==="send"&&e.scope.kind==="channel"?e.scope.channelId:null}function Nc(e,t){return e?.kind==="composer"&&(e.phase==="prepare"||e.phase==="ack")&&e.scope.kind==="channel"&&e.scope.channelId===t}function Nm(e,t){return e?.kind==="composer"&&e.phase==="send"&&e.scope.kind==="channel"&&e.scope.channelId===t}function Tm(e,t){return e?.kind==="composer"&&e.phase==="stop"&&e.scope.kind==="channel"&&e.scope.channelId===t}function Tc(e){return e?.kind==="composer"&&(e.phase==="prepare"||e.phase==="ack")&&e.scope.kind==="draft"}function jm(e){return Tc(e)}function Lm(e,t){return!!t&&(Nc(e,t)||Tm(e,t))}function jc(e,t){return{containerId:Mf(),conversationId:ic(t)}}const Mm=150,Em=8;function Dm(e,t,n){return!Rc(t)||!e?!1:!Ol(e)}function Bm(e){const t=e?.pendingProvider?.trim()||null;return!e||e.roomRouting.defaultRecipientId||!t||!sc(e)?null:El(t,e.pendingInstance,null)}function Om(e,t){const n=ee(e?.conversationId);return n||(t?jc(null,t).conversationId:null)}function mr(e,t,n,a=null){const s=a?.trim()||null;if(s)return s;const o=e?.trim()||null,i=t?.trim()||null,u=n?.trim()||null;return o&&i&&u?Yr(o,i,u):null}function _m(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?xc(e?.messages??[],t.sourceMessageId):!1,o=t?.workflowShape==="concurrent"||s;return{sourceMessageId:t?.sourceMessageId?.trim()||null,laneId:mr(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 Fm(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=mr(t.id??null,a.id??null,a.participant.participantId,a.laneId??null),i=Lc(e,a.participant.participantId,a.id?.trim()||null,o);return Cn({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 Ti(e){return e==="ready"||e==="initializing"}function Wm(e,t,n=null){if(!e||!t)return null;if(t==="orchestrator"){const i=ee(e.orchestratorLease?.status),u=ee(e.orchestratorLease?.laneId);return i&&!Ti(i)?{sessionId:null,startedAt:null}:n&&u&&u!==n?{sessionId:null,startedAt:null}:{sessionId:ee(e.orchestratorLease?.sessionId),startedAt:ee(e.orchestratorLease?.startedAt)}}const a=e.assignedParticipants?.find(i=>i.participantId===t)?.execution?.lease??null,s=ee(a?.status),o=ee(a?.laneId);return s&&!Ti(s)?{sessionId:null,startedAt:null}:n&&o&&o!==n?{sessionId:null,startedAt:null}:{sessionId:ee(a?.sessionId),startedAt:ee(a?.startedAt)}}function Lc(e,t,n=null,a=null){const s=ee(e?.roomRouting.workflow.activeTurn?.id),o=ee(e?.roomRouting.workflow.activeTurn?.startedAt),i=e?.roomRouting.workflow.activeTurn?.targetStatuses?.find(v=>{const C=mr(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,u=ee(i?.startedAt)??ee(i?.queuedAt)??o;if(!t||!u)return{sessionStartedAt:null,requiresSessionStartConfirmation:!1};const c=Wm(e,t,a),d=c?.sessionId??null,h=c?.startedAt??null;if(!d||!h)return{sessionStartedAt:u,requiresSessionStartConfirmation:!0};const f=Date.parse(u),m=Date.parse(h);return Number.isNaN(f)||Number.isNaN(m)?{sessionStartedAt:h,requiresSessionStartConfirmation:!1}:{sessionStartedAt:h,requiresSessionStartConfirmation:m>=f}}function Mc(e){return e.contentBlocks.length>0||e.progressText.trim().length>0||e.events.length>0}function Xr(e,t){if(!e.active||e.phase==="waiting"||!Mc(e))return!1;const n=t?.roomRouting.workflow.activeTurn?.sourceMessageId??null;return n?fr(e)||e.laneId||e.targetStateId?!fs(t?.messages??[],n,e):!xc(t?.messages??[],n):!1}function Um(e){return e.previousChannelId!==e.channelId||!e.previous.active?e.waitingState:Xr(e.previous,e.selectedChannel)?e.previous:e.previous.phase==="streaming"?Yn(e.previous,e.waitingState):e.previous.phase==="waiting"&&!Mc(e.previous)?_c(e.previous,e.waitingState):e.previous.phase==="sealed"?gs(e.previous,e.waitingState)&&!Oo(e.selectedChannel)?e.previous:Yn(e.previous,e.waitingState):e.previous}function ms(e,t){return e.segmentIndex===t.segmentIndex&&ka(e,t)}function ka(e,t){const n=e.sourceMessageId??null,a=t.sourceMessageId??null,s=e.laneId??null,o=t.laneId??null,i=e.targetStateId??null,u=t.targetStateId??null,c=Nn(e),d=Nn(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&&u!==null?i===u:n===a&&c===d&&h===f&&m===v}function gs(e,t){const n=Ge(e),a=Ge(t);return n!=null&&a!=null&&ka(n,a)||ka(e,t)}function Ec(e,t){return e.length===t.length&&e.every((n,a)=>n===t[a])}function Dc(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 Bc(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 Oc(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 Km(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&&Ec(e.activeCatIds,t.activeCatIds)&&Bc(e.tools,t.tools)&&Dc(e.contentBlocks,t.contentBlocks)&&Oc(e.events,t.events)}function $m(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||!Ec(e.activeCatIds,t.activeCatIds)||!Bc(e.tools,t.tools)||!Dc(e.contentBlocks,t.contentBlocks)||!Oc(e.events,t.events))return!1;const n=ze(e),a=ze(t);return n.length===a.length&&n.every((s,o)=>{const i=a[o];return i!=null&&Km(s,i)})}function Nn(e){return e.identityParticipantId??e.participantId??null}function Oo(e){return e?sc(e):!1}function Hm(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=Nn(e),a=Nn(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 ji(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 qm(e,t){const a=(e.events?.find(s=>s.kind==="turn_started")??null)?.targets?.map(s=>ji(s)).filter(s=>s!==null)??[];return a.length>0?a:!t||t.turnId!==e.id?[]:t.resolvedTargets?.map(s=>ji(s)).filter(s=>s!==null)??[]}function Gm(e,t){const n=Nn(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 Li(e,t){if(!t)throw new Error("reindexWaitingSegment requires a waiting segment");return Hm(e,t)?Ge(yc({sourceMessageId:t.sourceMessageId,laneId:t.laneId,targetStateId:t.targetStateId,participantId:Nn(t),catId:t.catId,speakerLabel:t.speakerLabel,revealIdentity:!0,segmentIndex:e.segmentIndex+1}))??t:t}function Yn(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(ms(e,t))return e;const i=Li(a,n);return et([...e.segments.slice(0,-1),i])}const s=a.phase==="sealed"?a:{...a,phase:"sealed"},o=Li(s,n);return et([...e.segments.slice(0,-1),s,o])}function _c(e,t){const n=Ge(t);if(!n)return e;const a=Ge(e);return!e.active||!a?t:a.phase!=="waiting"||ms(e,t)||gs(e,t)?e:et([...e.segments.slice(0,-1),n])}function Vm(e,t,n){if(!e.active||e.phase!=="streaming"||!t.active||t.phase!=="waiting"||!fr(t)||ms(e,t)||gs(e,t)&&!Oo(n))return!1;const a=n?.roomRouting.workflow.activeTurn?.sourceMessageId??null;return a?fs(n?.messages??[],a,e):!1}function zm(e,t,n){if(!e.active||e.phase!=="sealed"||!t.active||t.phase!=="waiting"||!fr(t)||ms(e,t)||gs(e,t)&&!Oo(n))return!1;const a=n?.roomRouting.workflow.activeTurn?.sourceMessageId??null;return a?fs(n?.messages??[],a,e):!1}function Ym(e,t){return!(Ge(e)?.phase==="sealed"||Xr(e,t))}function Mi(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(I=>{const y=mr(a.id??null,I.id??null,I.participant.participantId,I.laneId??null);if(n.laneId&&y)return y!==n.laneId;const g=I.id?.trim()||null;if(n.targetStateId&&g)return g!==n.targetStateId;const x=Nn(n),S=I.participant.participantId?.trim()||null;return x&&S?S!==x:(I.participant.participantName?.trim()||null)!==(n.speakerLabel??null)}))return!0;if(n.laneId||n.targetStateId||Nn(n))return!1;const v=n.speakerLabel?.trim()||null;return v?(a.targetStatuses??i).filter(I=>(I.participant.participantName?.trim()||null)===v).length>1:i.length>0}if(a.workflowShape!=="sequential")return!0;const u=t?.roomRouting.lastOutcome??null,c=qm(a,u);if(c.length>0){const m=Gm(c,n);if(m>=0)return m<c.length-1}const h=(a.events?.find(m=>m.kind==="turn_started")??null)?.targets?.length??(u?.turnId===a.id?u?.resolvedTargets?.length:null)??null;if(!h)return!0;const f=new Set(a.targetStatuses?.map(m=>mr(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 Jm(e,t){return Ge(e)?.phase!=="sealed"?!1:!ro(e,t)}function ro(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:!ka(n,a):!0:!1}function Xm(e){return Rc(e.busy)&&!!e.channelId}function Qm(e){return Dm(e.channelId,e.busy,e.routingStatus)}function Zm(e,t){const n=ee(t.sessionId),a=ee(t.laneId),s=ee(t.targetStateId),o=ee(t.sourceMessageId),i=typeof t.streamSeq=="number"&&Number.isFinite(t.streamSeq)?t.streamSeq:null,u=typeof t.streamSeqIndex=="number"&&Number.isFinite(t.streamSeqIndex)?t.streamSeqIndex:null;return!n||i===null||u===null?{accept:!0,cursor:e}:e&&e.sessionId===n&&e.sourceMessageId===o&&eg(e,{laneId:a,targetStateId:s})&&(i<e.streamSeq||i===e.streamSeq&&u<=e.streamSeqIndex)?{accept:!1,cursor:e}:{accept:!0,cursor:{sessionId:n,laneId:a,targetStateId:s,sourceMessageId:o,streamSeq:i,streamSeqIndex:u}}}function eg(e,t){return e.laneId&&t.laneId?e.laneId===t.laneId:(e.targetStateId&&t.targetStateId||e.laneId===t.laneId)&&e.targetStateId===t.targetStateId}function tg(e){return e.phase!=="waiting"||e.contentBlocks.length>0||e.progressText.trim().length>0||e.events.length>0||e.tools.length>0}function Nr(e,t){const n=ze(t);if(n.length<=1)return Yn(e,t);const a=ze(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 d=a[c],h=n.findIndex(v=>ka(d,v));if(h<0){i.push(d);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];ka(C,f)&&(s.add(v),m.push(C))}if(m.some(tg)){i.push(...m);continue}i.push(f)}n.forEach((c,d)=>{o.has(d)||i.push(c)});const u=et(i);return $m(e,u)?e:u}function ng(e){const{channelId:t,busy:n,selectedChannel:a,debugTraceEnabled:s=!1,resolveRoutingStatus:o,shouldShowWaitingIndicator:i=Xm,shouldConnectStream:u=Qm}=e,[c,d]=p.useState(or),h=p.useRef(null),f=p.useRef(or),m=p.useRef(a),v=p.useRef(null),C=p.useRef(null),I=a?.roomRouting.defaultRecipientId??null,y=o?.(a)??null,g=a?.roomRouting.workflow.activeTurn??null,x=I?null:Bm(a),S=p.useMemo(()=>_m(a),[g,a?.messages]),k=p.useMemo(()=>Lc(a,S.participantId,S.targetStateId,S.laneId),[a,S.participantId,S.targetStateId,S.laneId]),w=p.useMemo(()=>({sourceMessageId:S.sourceMessageId,laneId:S.laneId,targetStateId:S.targetStateId,participantId:S.participantId,catId:S.catId,speakerLabel:S.speakerLabel,revealIdentity:S.revealIdentity,defaultRecipientCatId:I,fallbackSpeakerLabel:x,sessionStartedAt:k.sessionStartedAt,requiresSessionStartConfirmation:k.requiresSessionStartConfirmation}),[S.sourceMessageId,S.laneId,I,x,S.catId,S.targetStateId,S.participantId,S.revealIdentity,S.speakerLabel,k.sessionStartedAt,k.requiresSessionStartConfirmation]),P=p.useRef(w);function j(){const T=Fm(m.current);if(T.length>1)return et(T);const A=P.current;return yc({sourceMessageId:A.sourceMessageId,laneId:A.laneId,targetStateId:A.targetStateId,participantId:A.participantId,catId:A.revealIdentity?A.catId:A.defaultRecipientCatId,speakerLabel:A.revealIdentity?A.speakerLabel:A.fallbackSpeakerLabel,revealIdentity:A.revealIdentity,sessionStartedAt:A.sessionStartedAt,requiresSessionStartConfirmation:A.requiresSessionStartConfirmation})}function N(T,A={}){if(!s)return;const b=ee(m.current?.roomRouting.workflow.activeTurn?.id),R=Ge(f.current);uc({event:T,channelId:t,containerId:ee(A.containerId)??ee(m.current?.containerId),conversationId:Om(m.current,t),turnId:ee(A.turnId)??b,laneId:ee(A.laneId)??R?.laneId??f.current.laneId,sourceMessageId:ee(A.sourceMessageId)??R?.sourceMessageId??f.current.sourceMessageId,targetStateId:ee(A.targetStateId)??R?.targetStateId??f.current.targetStateId,sessionId:ee(A.sessionId),participantId:ee(A.participantId),catId:ee(A.catId),speakerLabel:ee(A.speakerLabel),reason:ee(A.reason),details:A.details??null,signature:A.signature??null})}p.useEffect(()=>{f.current=c},[c]),p.useEffect(()=>{m.current=a},[a]),p.useEffect(()=>{P.current=w},[w]),p.useEffect(()=>{const T=i({channelId:t,busy:n,routingStatus:y}),A=v.current;v.current=t;let b=!1,R=null,L=0;function O(K){d(B=>{const ae=K(B);return f.current=ae,ae})}function Y(){R&&(clearTimeout(R),R=null)}function $(){h.current&&(h.current.close(),h.current=null)}function M(){b||L>=Em||!u({channelId:t,busy:n,routingStatus:y})||(L+=1,$(),Y(),R=setTimeout(()=>{R=null,b||J()},Mm))}function F(K){let B;try{B=JSON.parse(K.data)}catch{return}const ae=Zm(C.current,B);if(!ae.accept){N("stream_event_deduped",{turnId:ee(B.turnId),laneId:ee(B.laneId),sourceMessageId:ee(B.sourceMessageId),targetStateId:ee(B.targetStateId),sessionId:ee(B.sessionId),participantId:ee(B.participantId),catId:ee(B.catId),speakerLabel:ee(B.speakerLabel),reason:"stale_replayed_event",details:{eventType:B.type??K.type,streamSeq:typeof B.streamSeq=="number"?B.streamSeq:null,streamSeqIndex:typeof B.streamSeqIndex=="number"?B.streamSeqIndex:null}});return}C.current=ae.cursor,L=0;const be=B.type??K.type,W=j(),q=be==="session_closed"&&u({channelId:t,busy:n,routingStatus:y});Ge(f.current);const _e=q&&ro(f.current,W),le=q&&Mi(f.current,m.current),xe=q&&Xr(f.current,m.current),Ae=q&&Jm(f.current,W)&&!le;N("stream_event",{turnId:ee(B.turnId),laneId:ee(B.laneId),sourceMessageId:ee(B.sourceMessageId),targetStateId:ee(B.targetStateId),sessionId:ee(B.sessionId),participantId:ee(B.participantId),catId:ee(B.catId),speakerLabel:ee(B.speakerLabel),reason:q?"session_close_reconnect":null,details:{eventType:be,busy:n,routingStatus:y}}),O(X=>{if(!X.active)return X;if(q){if(Ae)return N("stream_session_close_ignored",{turnId:ee(B.turnId),laneId:X.laneId,sourceMessageId:X.sourceMessageId,targetStateId:X.targetStateId,participantId:X.participantId,catId:X.catId,speakerLabel:X.speakerLabel,reason:"sealed_segment_already_completed"}),X;if(xe)return N("stream_reply_commit_pending",{turnId:ee(B.turnId),laneId:X.laneId,sourceMessageId:X.sourceMessageId,targetStateId:X.targetStateId,participantId:X.participantId,catId:X.catId,speakerLabel:X.speakerLabel,reason:"pin_until_persisted_reply"}),X;if(!_e&&!le)return N("stream_session_close_no_followup",{turnId:ee(B.turnId),laneId:X.laneId,sourceMessageId:X.sourceMessageId,targetStateId:X.targetStateId,participantId:X.participantId,catId:X.catId,speakerLabel:X.speakerLabel,reason:"no_distinct_followup_target"}),X;if(!_e)return N("stream_session_close_reconnect",{turnId:ee(B.turnId),laneId:X.laneId,sourceMessageId:X.sourceMessageId,targetStateId:X.targetStateId,participantId:X.participantId,catId:X.catId,speakerLabel:X.speakerLabel,reason:"ongoing_workflow_boundary"}),X;const re=Eo(W,B);return N("stream_waiting_restart",{turnId:ee(B.turnId),laneId:re.laneId,sourceMessageId:re.sourceMessageId,targetStateId:re.targetStateId,participantId:ee(B.participantId),catId:re.catId,speakerLabel:re.speakerLabel,reason:"session_close_reconnect"}),ze(W).length>1?Nr(X,W):Yn(X,W)}return nm(X,be,B,Date.now())}),q&&!Ae&&(_e||le)&&M()}function J(){if(b||!u({channelId:t,busy:n,routingStatus:y}))return;$();const K=new EventSource(`/api/channels/${t}/stream`);h.current=K,N("stream_connect",{turnId:g?.id??null,laneId:P.current.laneId,sourceMessageId:P.current.sourceMessageId,targetStateId:P.current.targetStateId,reason:"open_source",details:{busy:n,routingStatus:y}}),K.addEventListener("progress",F),K.addEventListener("text",F),K.addEventListener("tool_use",F),K.addEventListener("tool_result",F),K.addEventListener("content_block",F),K.addEventListener("result",F),K.addEventListener("error",F),K.addEventListener("session_closed",F),K.onerror=()=>{if(b||K!==h.current)return;const B=j(),ae=ro(f.current,B),be=Mi(f.current,m.current);if(!(ae||be||Ym(f.current,m.current))){N("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}}),$();return}ae&&O(q=>ze(B).length>1?Nr(q,B):Yn(q,B)),N("stream_source_error",{turnId:m.current?.roomRouting.workflow.activeTurn?.id??null,laneId:ae?P.current.laneId:f.current.laneId,sourceMessageId:ae?P.current.sourceMessageId:f.current.sourceMessageId,targetStateId:ae?P.current.targetStateId:f.current.targetStateId,reason:ae?"eventsource_terminated_followup_handoff":be?"eventsource_terminated_running_workflow":"eventsource_terminated",details:{busy:n,routingStatus:y}}),$(),M()}}if(!T){if(Y(),$(),Xr(f.current,m.current)){N("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}N("indicator_reset",{turnId:g?.id??null,laneId:P.current.laneId,sourceMessageId:P.current.sourceMessageId,targetStateId:P.current.targetStateId,reason:"waiting_not_needed",details:{busy:n,routingStatus:y},signature:`indicator_reset::${t??""}::${Fu(n)}::${y??""}`}),f.current=or,d(or);return}const me=j();if(A!==t&&(C.current=null),d(K=>{const B=ze(me).length>1?Nr(K,me):Um({previous:K,waitingState:me,selectedChannel:m.current,previousChannelId:A,channelId:t});return f.current=B,B}),N("waiting_started",{turnId:g?.id??null,laneId:w.laneId,sourceMessageId:w.sourceMessageId,targetStateId:w.targetStateId,participantId:w.revealIdentity?w.participantId:null,catId:w.revealIdentity?w.catId:w.defaultRecipientCatId,speakerLabel:w.revealIdentity?w.speakerLabel:w.fallbackSpeakerLabel,reason:u({channelId:t,busy:n,routingStatus:y})?"awaiting_stream_attach":"waiting_without_stream",details:{busy:n,routingStatus:y}}),!u({channelId:t,busy:n,routingStatus:y})){Y(),$();return}return J(),()=>{b=!0,Y(),$()}},[n,t,s,y,u,i]),p.useEffect(()=>{if(!i({channelId:t,busy:n,routingStatus:y}))return;const A=j();d(b=>{if(ze(A).length>1){const L=Nr(b,A);return f.current=L,L}if(Vm(b,A,m.current)){const L=Yn(b,A);return f.current=L,L}if(zm(b,A,m.current)){const L=Yn(b,A);return f.current=L,L}if(!b.active||b.phase!=="waiting")return b;const R=_c(b,A);return f.current=R,R})},[n,t,y,a,i,w]);const D=p.useMemo(()=>Qf(c,Date.now()),[c]);return p.useEffect(()=>{if(D==null)return;const T=Math.max(D-Date.now(),0),A=globalThis.setTimeout(()=>{d(b=>{if(!b.active)return b;const R={...b};return f.current=R,R})},T);return()=>{globalThis.clearTimeout(A)}},[D]),c}function ee(e){return typeof e=="string"&&e.trim().length>0?e.trim():null}function ag(){const[e,t]=p.useState([]),[n,a]=p.useState(null),[s,o]=p.useState(new Map),i=p.useCallback(d=>{t(h=>{const f=h.includes(d),m=f?h.filter(v=>v!==d):[...h,d];return f?(a(v=>v===d?m.length>0?m[0]:null:v),o(v=>{const C=new Map(v);return C.delete(d),C})):a(d),m})},[]),u=p.useCallback((d,h)=>{o(f=>{const m=new Map(f);return m.set(d,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:u,resetDraftCats:c}}function Ei(e){const t=e?.trim();return t||null}function Fc(e){const t=Ei(e.draftDefaultRecipientCatId),n=[],a=new Set;for(const o of e.draftCatIds){const i=Ei(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 rg(e){const{state:t,draftDefaultRecipientCatId:n,draftCatIds:a,maxDraftGroupParticipants:s}=e,[o,i]=p.useState([]),u=p.useMemo(()=>Fc({draftDefaultRecipientCatId:n,draftCatIds:a}),[a,n]),c=p.useCallback(f=>{i(m=>{if(u.participantCatIds.length+m.length>=s)return m;const v=[...u.participantCatIds.map(C=>(t.status==="ready"?t.payload.chat.cats.find(I=>I.id===C)?.name:null)??""),...m.map(C=>C.name)].filter(C=>C.trim().length>0);return[...m,Pn({...f,takenNames:v,randomUUID:()=>window.crypto.randomUUID()})]})},[u.participantCatIds,s,t]),d=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:u,onAddDraftTemporaryParticipant:c,onRemoveDraftTemporaryParticipant:d,onUpdateDraftTemporaryParticipant:h}}function sg(e){const[t,n]=p.useState(e.initialState),[a,s]=p.useState(""),[o,i]=p.useState(e.createEmptyCatForm),[u,c]=p.useState(Oe()),[d,h]=p.useState(""),[f,m]=p.useState("existing"),[v]=p.useState(e.pickGreeting),[C,I]=p.useState(null),[y,g]=p.useState([]),[x,S]=p.useState([]);return{state:t,setState:n,composerDraft:a,setComposerDraft:s,catForm:o,setCatForm:i,busy:u,setBusy:c,feedback:d,setFeedback:h,addCatTab:f,setAddCatTab:m,greeting:v,draftCwd:C,setDraftCwd:I,draftFiles:y,setDraftFiles:g,channelFiles:x,setChannelFiles:S}}function og(e){const t=_l(),n=ai(`${e}/chats/:channelId`),a=ai(`${e}/dm/:catId`),s=n?.params.channelId??null,o=a?.params.catId??null,i=Wu(e,t.pathname),u=i?Uu(t.search):"default",c=o??Ku(t.search);return{location:t,settingsMode:$u(t.pathname),routeChannelId:s,routeMyCatId:o,showingNewChatDraft:i,newChatPreset:u,draftDefaultRecipientCatId:c,showingMyCatDirectLane:!!o}}function ig(e){return e.replace(/\s*\((?:default|recommended)\)\s*/giu," ").trim()}function lg(e){const t=e.model?.trim();if(!t)return"default";const n=qu(e.provider,t)??t,s=ri(e.provider,t)??ri(e.provider,n)??Gu(e.provider).find(o=>o.value===n)?.label;return ig(s??n)}function _o(e,t,n){const a=vr({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 cg(e,t){return{label:_o(e,null,t),providerLabel:Hu(e.provider),instanceLabel:e.instance?.trim()||null,modelLabel:lg(e)}}function xa(e){return{provider:e.provider,model:e.model||null,instance:e.instance||null,modelSelection:e.modelSelection??null,executionLabel:e.executionLabel??null}}const dg=[/^cats new chat defaults update returned \d+$/u,/^cats channel update returned \d+$/u];function Di(e,t,n){if(!(e instanceof Error))return t;const a=Fl(e.message,n);return a||(dg.some(s=>s.test(e.message))?t:e.message)}const Wc=5e3;let Tr=null,ar=null;const Bi=new Map,Ws=new Map;function Oi(e,t){typeof console>"u"||typeof console.warn!="function"||console.warn(`[cats-platform] ${e}`,t instanceof Error?t.stack??t.message:t)}function ug(e){const t=vo(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 _i(e){return JSON.stringify({provider:e.provider.trim(),instance:e.instance??null,model:e.model??null,modelSelection:ug(e.modelSelection)})}function pg(e){return(e.fetchProviderRegistryFn??Kr)===Kr&&(e.fetchProviderModelsFn??$r)===$r&&(e.fetchAdvancedProviderModelsFn??Hr)===Hr}async function hg(e){const t=Date.now();return Tr&&Tr.expiresAt>t?Tr.value:ar||(ar=e().then(n=>(Tr={value:n,expiresAt:Date.now()+Wc},n)).finally(()=>{ar=null}),ar)}async function fg(e){const t=`${e.provider}\0${e.instance??""}`,n=Date.now(),a=Bi.get(t);if(a&&a.expiresAt>n)return a.value;const s=Ws.get(t);if(s)return s;const o=Promise.allSettled([e.fetchProviderModelsFn(e.provider,e.instance),e.fetchAdvancedProviderModelsFn(e.provider,e.instance)]).then(([i,u])=>{if(i.status!=="fulfilled")throw i.reason;const c=i.value,d=Wl({provider:e.provider,instance:e.instance,catalog:c,advancedCatalogResult:u,modelsResult:i}),h={effectiveCatalog:c,effectiveAdvancedCatalog:d};return Bi.set(t,{value:h,expiresAt:Date.now()+Wc}),h}).finally(()=>{Ws.delete(t)});return Ws.set(t,o),o}async function mg(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:Wl({provider:e.provider,instance:e.instance,catalog:t.value,advancedCatalogResult:n,modelsResult:t})}}function gg(e){return{provider:e,model:Aa(e)||null,instance:Ra(e),modelSelection:null,executionLabel:null}}function so(){return gg("claude")}function Fi(e){if(!e)return so();const t=e.provider?.trim()||"claude",n=e.model===void 0?(e.modelSelection?.entryId??Aa(t))||null:e.model??e.modelSelection?.entryId??null;return{provider:t,model:n,instance:e.instance??Ra(t),modelSelection:e.modelSelection??null,executionLabel:null}}function Qr(e,t){return e.provider===t.provider&&(e.instance??null)===(t.instance??null)&&(e.model??null)===(t.model??null)&&Zu(e.modelSelection,t.modelSelection)}function Cg(e,t){return Qr(e,t)&&(e.executionLabel??null)===(t.executionLabel??null)}function rr(e,t){if(!Qr(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 vg(e){return{provider:e.provider,instance:e.instance??"",model:e.model??"",modelSelection:e.modelSelection??null,executionLabel:e.executionLabel??null}}async function Wi(e){const t=e.target.provider.trim();if(!t)return e.target;const n=e.fetchProviderRegistryFn??Kr,a=e.fetchProviderModelsFn??$r,s=e.fetchAdvancedProviderModelsFn??Hr,o=pg(e),u=(o?await hg(n):await n()).providers.find(I=>I.id===t);if(!u)return e.target;const c=Vu(u,e.target.instance??"");let d,h;try{const I=o?await fg({provider:t,instance:c||null,fetchProviderModelsFn:a,fetchAdvancedProviderModelsFn:s}):await mg({provider:t,instance:c||null,fetchProviderModelsFn:a,fetchAdvancedProviderModelsFn:s});d=I.effectiveCatalog,h=I.effectiveAdvancedCatalog}catch{const I={...e.target,instance:c||null,...si(t,e.target.model)?{model:null,modelSelection:null,executionLabel:null}:{}};return Cg(e.target,I)?e.target:I}let f=vg({...e.target,provider:t,instance:c||null});const m=si(t,f.model);if(!(!m&&zu({catalogSource:d.source,advancedCatalogSource:h.source,model:f.model,modelSelection:f.modelSelection}))&&d.models.length>0){const I=!!f.modelSelection||Yu({catalog:d,model:f.model,modelSelection:f.modelSelection});f=Ju({target:Xu({target:f,catalog:d,advancedCatalog:h,preserveCurrentModel:I,preserveCurrentSelection:I}),controls:h.controls})}else m&&(f={...f,model:"",modelSelection:null,modelResolution:null,executionLabel:null});const C=f.model?Qu({target:f,effectiveCatalog:d,effectiveAdvancedCatalog:h}):{...f,executionLabel:null};return xa(C)}function Ui(e,t){return!e||!t||!An(t)?null:{provider:t.pendingProvider??e.globalOrchestrator.executionTarget.provider,model:t.pendingModel??e.globalOrchestrator.executionTarget.model??null,instance:t.pendingInstance??e.globalOrchestrator.executionTarget.instance??null,modelSelection:t.pendingModelSelection??e.globalOrchestrator.executionModelSelection??null,executionLabel:null}}function Ig({state:e,readyChat:t,readySelectedChannel:n,setState:a,setFeedback:s,updateNewChatDefaultsPreference:o,updateChannelPendingExecutionTarget:i,debounceMs:u=150}){const{t:c}=z(),[d,h]=p.useState(so),[f,m]=p.useState(so),v=p.useRef(0),C=p.useRef(null),I=p.useRef(null),y=p.useRef(0),g=p.useRef(null),x=p.useRef(null),S=_i(d),k=_i(f);return p.useEffect(()=>{if(!t)return;const w=Fi(t.newChatDefaults);h(P=>rr(P,w))},[t?.newChatDefaults?.instance,t?.newChatDefaults?.model,t?.newChatDefaults?.modelSelection,t?.newChatDefaults?.provider]),p.useEffect(()=>()=>{C.current&&(clearTimeout(C.current),C.current=null),I.current?.abort(),I.current=null,g.current&&(clearTimeout(g.current),g.current=null),x.current?.abort(),x.current=null},[]),p.useEffect(()=>{const w=Ui(t,n);w&&m(P=>rr(P,w))},[n?.id,n?.channelKind,n?.roomRouting?.mode,n?.pendingProvider,n?.pendingModel,n?.pendingInstance,n?.pendingModelSelection,t?.globalOrchestrator.executionTarget.provider,t?.globalOrchestrator.executionTarget.model,t?.globalOrchestrator.executionTarget.instance,t?.globalOrchestrator.executionModelSelection]),p.useEffect(()=>{if(!n||!An(n)||!n.pendingProvider)return;const w=n.pendingProvider;m(P=>rr(P,{provider:w,model:n.pendingModel??null,instance:n.pendingInstance??null,modelSelection:n.pendingModelSelection??null,executionLabel:null}))},[n?.id]),p.useEffect(()=>{if(e.status!=="ready")return;let w=!1;return Wi({target:d}).then(P=>{w||h(j=>rr(j,P))}).catch(P=>{Oi(`failed to reconcile draft execution target for ${d.provider}:${d.model??"default"}`,P)}),()=>{w=!0}},[S,e.status]),p.useEffect(()=>{if(e.status!=="ready"||!n||!An(n))return;let w=!1;return Wi({target:f}).then(P=>{w||m(j=>rr(j,P))}).catch(P=>{Oi(`failed to reconcile default chat execution target for ${f.provider}:${f.model??"default"}`,P)}),()=>{w=!0}},[n?.id,n?.channelKind,n?.roomRouting?.mode,k,e.status]),p.useEffect(()=>{if(e.status!=="ready")return;const w=Fi(e.payload.chat.newChatDefaults);if(Qr(d,w))return;C.current&&(clearTimeout(C.current),C.current=null),I.current?.abort();const P=v.current+1;v.current=P;const j=new AbortController;I.current=j;const N={provider:d.provider,instance:d.instance,model:d.model,modelSelection:d.modelSelection};return C.current=setTimeout(()=>{C.current=null,o(N,j.signal).then(D=>{j.signal.aborted||v.current!==P||(I.current=null,p.startTransition(()=>a({status:"ready",payload:D})))}).catch(D=>{j.signal.aborted||v.current!==P||(I.current=null,s(Di(D,c(l.sharedExecutionTargetSaveNewChatDefaultsError),c)))})},u),()=>{C.current&&(clearTimeout(C.current),C.current=null),j.abort()}},[u,d.instance,d.model,d.modelSelection,d.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 w=Ui(t,n);if(!n||!w||Qr(f,w))return;g.current&&(clearTimeout(g.current),g.current=null),x.current?.abort();const P=n.id,j=y.current+1;y.current=j;const N=new AbortController;x.current=N;const D={pendingProvider:f.provider,pendingModel:f.model,pendingInstance:f.instance,pendingModelSelection:f.modelSelection};return g.current=setTimeout(()=>{g.current=null,i(P,D,N.signal).then(T=>{N.signal.aborted||y.current!==j||(x.current=null,p.startTransition(()=>a({status:"ready",payload:T})))}).catch(T=>{N.signal.aborted||y.current!==j||(x.current=null,s(Di(T,c(l.sharedExecutionTargetSaveChatReplySettingsError),c)))})},u),()=>{g.current&&(clearTimeout(g.current),g.current=null),N.abort()}},[u,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,f.instance,f.model,f.modelSelection,f.provider,e.status,i]),{draftExecutionTarget:d,setDraftExecutionTarget:h,defaultChannelExecutionTarget:f,setDefaultChannelExecutionTarget:m}}function Sg(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 Cs(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 Uc(e,t,n){return{...e,audienceKeys:[...t],workflowShape:n}}function Ki(e,t){return{...e,audienceKeys:Cs(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 yg(e){const t=Cs(e.audienceKeys),n=e.workflowShape??"sequential";return Uc(e,t,n)}function $i(e,t={}){const n=Cs(t.seedAudienceKeys),a=t.seedWorkflowShape??"sequential";return e.map(s=>Kc(s,{audienceKeys:n,workflowShape:a}))}function Kc(e,t={}){const n=Cs(t.audienceKeys),a=t.workflowShape??"sequential";return Uc(e,n,a)}function ya(e,t,n){return e.map((a,s)=>s===t?yg(n(a)):a)}function bg(e,t,n){return ya(e,t,a=>({...a,cwd:n}))}function xg(e,t,n){return ya(e,t,a=>({...a,runtimeSessionPolicy:n}))}function wg(e){const{draftExecutionTarget:t,maxParallelChats:n,seedCompareTarget:a=!0}=e,[s,o]=p.useState(()=>$i(mi({provider:t.provider,model:t.model,instance:t.instance,modelSelection:t.modelSelection},{includeCompareTarget:a}))),i=p.useCallback(C=>{o($i(mi(t,{includeCompareTarget:C?.includeCompareTarget??a}),{seedAudienceKeys:C?.seedAudienceKeys,seedWorkflowShape:C?.seedWorkflowShape}))},[t,a]);p.useEffect(()=>{o(C=>ya(C,0,I=>Ki(Jh([I],t)[0]??t,I)))},[t]);const u=p.useCallback((C,I)=>{o(y=>ya(y,C,g=>Ki(I,g)))},[]),c=p.useCallback(C=>{o(I=>{if(I.length>=n)return I;const y=I[0]??null,g=C?.seedAudienceKeys??y?.audienceKeys??[],x=C?.seedWorkflowShape??y?.workflowShape??"sequential";return[...I,Kc(Xh(I,t),{audienceKeys:g,workflowShape:x})]})},[t,n]),d=p.useCallback(C=>{o(I=>I.length<=1?I:I.filter((y,g)=>g!==C))},[]),h=p.useCallback((C,I)=>{o(y=>ya(y,C,g=>({...g,audienceKeys:[...I]})))},[]),f=p.useCallback((C,I)=>{o(y=>bg(y,C,I))},[]),m=p.useCallback((C,I)=>{o(y=>xg(y,C,I))},[]),v=p.useCallback(C=>{o(I=>ya(I,C,y=>({...y,workflowShape:y.workflowShape==="concurrent"?"sequential":"concurrent"})))},[]);return{draftParallelChatTargets:s,resetDraftParallelChatTargets:i,onDraftParallelChatTargetChange:u,onAddDraftParallelChatTarget:c,onRemoveDraftParallelChatTarget:d,onSetDraftParallelBranchAudienceKeys:h,onSetDraftParallelBranchCwd:f,onSetDraftParallelBranchRuntimeSessionPolicy:m,onToggleDraftParallelBranchWorkflowShape:v}}function kg(e,t){const{t:n}=z();p.useEffect(()=>{document.title=t?`${ir(t,n)} - ${e}`:e},[e,t,n])}const Pg=[/^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 Ag(e,t){const n=Fl(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 Ht(e,t,n){if(!(e instanceof Error))return t;const a=Ag(e.message,n);return a||(Pg.some(s=>s.test(e.message))?t:e.message)}const Rg=5e3;function Ng(e,t){const{t:n}=z(),[a,s]=p.useState({status:"idle",snapshot:null,message:""}),o=p.useRef(0),i=p.useCallback((u={})=>{if(!e?.setupCompleteAt)return o.current+=1,s({status:"idle",snapshot:null,message:""}),()=>{};const c=new AbortController,d=o.current+1;return o.current=d,u.background||s(h=>({status:"loading",snapshot:h.snapshot,message:""})),hr(c.signal).then(h=>{c.signal.aborted||d!==o.current||p.startTransition(()=>{s({status:"ready",snapshot:h,message:""})})}).catch(h=>{c.signal.aborted||d!==o.current||s(f=>u.background&&f.snapshot?f:{status:"error",snapshot:f.snapshot,message:Ht(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 u=()=>{document.visibilityState!=="hidden"&&i({background:!0})},c=window.setInterval(u,Rg),d=()=>{u()},h=()=>{document.visibilityState==="visible"&&u()};return window.addEventListener("focus",d),document.addEventListener("visibilitychange",h),()=>{window.clearInterval(c),window.removeEventListener("focus",d),document.removeEventListener("visibilitychange",h)}},[e?.setupCompleteAt,i]),{operatorState:a,refreshOperatorSnapshot:i,setOperatorState:s}}function Tg({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}=z();return p.useCallback(async o=>{n(Br("reset")),a("");try{const i=await e(o);p.startTransition(()=>t(i))}catch(i){a(Ht(i,s(l.sharedChannelContinuityStartFreshError),s))}finally{n(Oe())}},[t,e,n,a,s])}function Lg(e){const{updateChannelParticipantApi:t,setBusy:n,setFeedback:a,setState:s}=e,{t:o}=z();return p.useCallback(async(i,u,c)=>{n(ep(u));try{const d=await t(i,u,c);p.startTransition(()=>{s({status:"ready",payload:d}),a("")})}catch(d){a(Ht(d,o(l.chatParticipantsErrorUpdateParticipant),o))}finally{n(Oe())}},[n,a,s,o,t])}function Mg(e){const{selectedChannel:t,selectedParallelChatGroup:n,relayParallelChatMessage:a,setBusy:s,setFeedback:o,setState:i}=e,{locale:u,t:c}=z();return p.useCallback(async(d,h)=>{if(!(!t||!n)){s(zn("relay")),o("");try{const f=await a(n.id,{activeChannelId:t.id,sourceChannelId:t.id,sourceMessageId:d,command:h,targetPolicy:"all_others",locale:u});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(Ht(f,c(l.chatComposerErrorRelayCompareFailed),c))}finally{s(Oe())}}},[a,t,n,s,o,i,u,c])}function Hi(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 Eg(e,t){const n=Hi(e),a=Hi(t);return n===null||a===null?!0:a>=n}function Dg(e){return p.useCallback(t=>{p.startTransition(()=>e(n=>n.status==="ready"&&!Eg(n.payload,t)?n:{status:"ready",payload:t}))},[e])}function Bg(e){const{addCatOpen:t,channelPlusMenuOpen:n,plusMenuOpen:a,draftCwd:s,draftDefaultRecipientCatId:o,navigate:i,chatPrefix:u,emptyCatForm:c,resolveDraftDefaultRecipientPath:d,setAddCatOpen:h,setAddCatTab:f,setFeedback:m,setCatForm:v,setPlusMenuOpen:C,setChannelPlusMenuOpen:I,channelFileInputRef:y,fileInputRef:g,openFolderBrowser:x,onDraftScreenshotCapture:S,onChannelScreenshotCapture:k}=e;function w(){h(!t),f("existing"),m(""),v(c())}function P(){I(!n)}function j(){y.current?.click(),I(!1)}function N(){k?.(),I(!1)}function D(){C(!a)}function T(){g.current?.click(),C(!1)}function A(){S?.(),C(!1)}function b(){x(s),C(!1)}function R(){C(!1),h(!0),f("existing"),v(c()),m("")}function L(O){O!==o&&i(d?.(O)??Io(u,O),{replace:!0})}return{toggleAddCatPanel:w,toggleChannelPlusMenu:P,openChannelFilePicker:j,captureAndAttachChannelScreenshot:N,toggleDraftPlusMenu:D,openDraftFilePicker:T,captureAndAttachDraftScreenshot:A,openDraftFolderPicker:b,openDraftAddCatPanel:R,changeDraftDefaultRecipient:L}}function qi(e,t){return qr(Vs(e),t)}function Og(e){switch(e.entityKind){case"channel":case"conversation":return qi(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 qi(e.surface,t)}default:throw new Error(`No cross-surface navigation path builder is registered for ${e.entityKind}.`)}}function _g(e){return{surface:e.surface,path:Og(e)}}function Fg(e){return typeof e=="string"?e:e.surface}function Wg(e){return tp(Fg(e))}const Ug=6e4,Kg="__catsCrossSurfaceNavigationHandoffTelemetry",De={counters:{stage:0,hit:0,miss:{missing:0,stale:0,invalid:0}},activeStagedTargets:[],latestStage:null,latestHit:null,latestMiss:null};function Fo(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 Sr(){De.activeStagedTargets=[...gr.values()].map(Fo),Gg()}function $g(e){De.counters.stage+=1,De.latestStage=Fo(e),Sr()}function Hg(e,t){De.counters.hit+=1,De.latestHit={...Fo(t),match:{surface:e.surface,path:ja(e.path)}},Sr()}function Us(e,t){De.counters.miss[t]+=1,De.latestMiss={match:{surface:e.surface,path:ja(e.path)},reason:t},Sr()}function qg(){return{counters:{stage:De.counters.stage,hit:De.counters.hit,miss:{missing:De.counters.miss.missing,stale:De.counters.miss.stale,invalid:De.counters.miss.invalid}},activeStagedTargets:De.activeStagedTargets.map(e=>({...e,route:{surface:e.route.surface,path:e.route.path}})),latestStage:De.latestStage?{...De.latestStage,route:{surface:De.latestStage.route.surface,path:De.latestStage.route.path}}:null,latestHit:De.latestHit?{...De.latestHit,route:{surface:De.latestHit.route.surface,path:De.latestHit.route.path},match:{surface:De.latestHit.match.surface,path:De.latestHit.match.path}}:null,latestMiss:De.latestMiss?{reason:De.latestMiss.reason,match:{surface:De.latestMiss.match.surface,path:De.latestMiss.match.path}}:null}}function Gg(){const e=globalThis;e[Kg]=qg()}const gr=new Map,$c=new Set;function Vg(e,t){gr.set(e,t),$c.clear(),Sr()}function Ks(e){const t=gr.delete(e);return t&&($c.clear(),Sr()),t}function Gi(e,t){return e<t?-1:e>t?1:0}function ja(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,u],[c,d])=>i===c?Gi(u,d):Gi(i,c)),o=s.length>0?`?${new URLSearchParams(s).toString()}`:"";return`${a}${o}`}catch{return t}}function zg(e,t=""){return ja(`${e}${t}`)}function Hc(e){return`${e.surface}:${ja(e.path)}`}function Yg(e){const t=Date.parse(e.createdAt);return Number.isNaN(t)?!1:Date.now()-t<=Ug}function qc(e,t){const n=t?.consume===!0,a=Hc(e),s=gr.get(a)??null;return s?Zg(s,e)?Yg(s)?(n&&(Ks(a),Hg(e,s)),s):(n&&(Ks(a),Us(e,"stale")),null):(n&&(Ks(a),Us(e,"invalid")),null):(n&&gr.size>0&&Us(e,"missing"),null)}function Jg(e){const t={...e,destination:{...e.destination,route:{...e.destination.route,path:ja(e.destination.route.path)}}};Vg(Hc(t.destination.route),t),$g(t)}function Gc(e){return qc(e)}function Xg(e){return Gc(e)?.snapshot?.appShellPayload??null}function Qg(e){return eC(e)?.snapshot?.appShellPayload??null}function Zg(e,t){return e.targetSurface===t.surface&&e.destination.route.surface===t.surface&&e.destination.route.path===ja(t.path)}function eC(e){return qc(e,{consume:!0})}function tC(e){const t=e.channelId.trim();if(!t||e.sourceSurface===e.targetSurface)return null;const n=_g({surface:e.targetSurface,entityKind:"conversation",entityId:t});return Jg({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 _r({setDraftCwd:e,setDraftCatIds:t,setDraftHighlightedCatId:n,setDraftCatExecutionTargetOverrides:a,resetDraftSurface:s,setDraftRuntimeSessionPolicy:o,setDraftFiles:i,setDraftTemporaryParticipants:u,setChannelFiles:c,resetDraftParallelChatTargets:d,setDraftWorkflowShape:h,setDraftAudienceKeys:f}){e(null),t([]),u?.([]),n(null),a(new Map),s?.(),o?.(So()),i([]),c?.([]),d?.(),h?.("sequential"),f?.(null)}const nC={deleteChatChannel:lp,deleteGlobalCat:ip,deleteParallelChatGroup:op,renameChatChannel:np,renameParallelChatGroup:sp,resetSetup:rp,ungroupParallelChatGroup:ap};function oo(e){return!!(e&&typeof e=="object"&&"payload"in e&&"runtimeCleanup"in e)}function aC(e,t){if(!oo(e)||e.runtimeCleanup.retainedSessionCount===0)return"";const n=e.runtimeCleanup.retainedSessionCount;return t(n===1?l.sharedWorkspaceNavigationDeleteChannelRuntimeCleanupFeedbackOne:l.sharedWorkspaceNavigationDeleteChannelRuntimeCleanupFeedbackMany,{count:n})}function rC(e){const{state:t,setState:n,navigate:a,platformShellSurface:s,setBusy:o,setFeedback:i,setComposerDraft:u,setAccountMenuOpen:c,setAddCatOpen:d,setPlusMenuOpen:h,setChannelPlusMenuOpen:f,setDraftCwd:m,setDraftCatIds:v,setDraftTemporaryParticipants:C,setDraftHighlightedCatId:I,setDraftCatExecutionTargetOverrides:y,setDraftSurface:g,setDraftRuntimeSessionPolicy:x,setDraftWorkflowShape:S,setDraftAudienceKeys:k,resetDraftParallelChatTargets:w,createInitialGroupParticipants:P,seedInitialGroupParticipants:j=!0,setDraftFiles:N,setChannelFiles:D,navigationApi:T,confirm:A}=e,{t:b}=z(),R=Vs(s),L=T??nC,O=p.useCallback(re=>{d(!1),h(!1),_r({setDraftCwd:m,setDraftCatIds:v,setDraftTemporaryParticipants:C,setDraftHighlightedCatId:I,setDraftCatExecutionTargetOverrides:y,resetDraftSurface:()=>g?.(s),setDraftRuntimeSessionPolicy:x,setDraftWorkflowShape:S,setDraftAudienceKeys:k,resetDraftParallelChatTargets:()=>{w?.({includeCompareTarget:re?.includeCompareTarget??!1})},setDraftFiles:N,setChannelFiles:D}),f(!1)},[d,h,m,v,C,I,y,g,s,x,S,k,w,N,D,f]),Y=p.useCallback(()=>{t.status==="ready"&&(a(lr(R,t.payload.chat.channels,t.payload.chat.selectedChannelId,s)),i(""),d(!1))},[R,a,s,d,i,t]),$=p.useCallback(re=>{const pe=(t.status==="ready"?t.payload.chat.channels.find(Qe=>Qe.id===re)??null:null)?.originSurface??s,Ie=tC({sourceSurface:s,targetSurface:pe,channelId:re});Ie&&Wg(pe),a(Ie?.path??qr(Vs(pe),re)),i(""),d(!1),D([]),f(!1)},[a,s,d,D,f,i,t]),M=p.useCallback(async(re,G)=>{o(Br("rename",re));try{const pe=await L.renameChatChannel(re,G);p.startTransition(()=>{n({status:"ready",payload:pe}),i("")})}catch(pe){i(va(pe,b(l.sharedWorkspaceNavigationRenameChatError),b))}finally{o(Oe())}},[L,o,i,n,b]),F=p.useCallback(async(re,G)=>{o(Br("delete",G));try{const pe=await L.deleteChatChannel(G),Ie=oo(pe)?pe.payload:pe;p.startTransition(()=>{n({status:"ready",payload:Ie}),d(!1),i("")}),a(cp(R,re))}catch(pe){i(va(pe,b(l.sharedWorkspaceNavigationDeleteChatError),b))}finally{o(Oe())}},[R,a,L,d,o,i,n,b]),J=p.useCallback(async re=>{o(Br("delete",re));try{const G=await L.deleteChatChannel(re),pe=oo(G)?G.payload:G,Ie=aC(G,b);p.startTransition(()=>{n({status:"ready",payload:pe}),d(!1),i(Ie)}),a(lr(R,pe.chat.channels,pe.chat.selectedChannelId,s))}catch(G){i(va(G,b(l.sharedWorkspaceNavigationDeleteChatError),b))}finally{o(Oe())}},[R,a,L,s,d,o,i,n,b]),me=p.useCallback(async(re,G)=>{o(As("rename",re));try{const pe=await L.renameParallelChatGroup(re,{title:G});p.startTransition(()=>{n({status:"ready",payload:pe}),i("")})}catch(pe){i(va(pe,b(l.sharedWorkspaceNavigationRenameParallelChatError),b))}finally{o(Oe())}},[L,o,i,n,b]),K=p.useCallback(async re=>{o(As("ungroup",re));try{const G=await L.ungroupParallelChatGroup(re);p.startTransition(()=>{n({status:"ready",payload:G}),i("")})}catch(G){i(va(G,b(l.sharedWorkspaceNavigationUngroupParallelChatError),b))}finally{o(Oe())}},[L,o,i,n,b]),B=p.useCallback(async re=>{const G=b(l.sharedWorkspaceNavigationParallelChatFallbackName),pe=t.status==="ready"?t.payload.chat.parallelChatGroups?.find(Qe=>Qe.id===re)?.title??G:G;if(!A||await A(dp(pe,b))){o(As("delete",re));try{const Qe=await L.deleteParallelChatGroup(re);p.startTransition(()=>{n({status:"ready",payload:Qe}),d(!1),i("")}),a(lr(R,Qe.chat.channels,Qe.chat.selectedChannelId,s))}catch(Qe){i(va(Qe,b(l.sharedWorkspaceNavigationDeleteParallelChatGroupError),b))}finally{o(Oe())}}},[R,A,a,L,s,d,o,i,n,t,b]),ae=p.useCallback(async re=>{const G=t.status==="ready"?t.payload.chat.cats?.find(Ie=>Ie.id===re)?.name??null:null;if(!A||await A(up(G,b))){o(Sa("delete",re));try{const Ie=await L.deleteGlobalCat(re);p.startTransition(()=>n({status:"ready",payload:Ie}))}catch(Ie){i(Ul(Ie,b(l.sharedSettingsCatsDeleteError),b))}finally{o(Oe())}}},[A,L,o,i,n,t,b]),be=p.useCallback(()=>{a("/settings/general",{state:{platformShellSurface:s}}),c(!1),d(!1),i("")},[a,s,c,d,i]),W=p.useCallback(()=>{a("/settings/runtime",{state:{platformShellSurface:s}}),c(!1),d(!1),i("")},[a,s,c,d,i]),q=p.useCallback(()=>{a("/settings/cats/new",{state:{platformShellSurface:s}}),c(!1),d(!1),i("")},[a,s,c,d,i]),_e=p.useCallback(async re=>{if(t.status!=="ready")return;const G=pp(R,t.payload.chat.channels.slice(),re);i(""),O(),a(G.path)},[R,O,a,i,t]),le=p.useCallback(async()=>{if(!A||await A({title:b(l.settingsDataResetAllDataTitle),message:b(l.settingsDataResetAllDataDescription),confirmLabel:b(l.settingsDataResetButtonLabel)})){o(hp());try{const G=await L.resetSetup();fp(),await mp({bootstrapAttemptId:G.bootstrapAttemptId??null,setupCompleteAt:G.setupCompleteAt??null,products:Array.isArray(G.products)?[...G.products]:[]}),window.location.href="/"}catch(G){throw o(Oe()),G}}},[A,L,o,b]),xe=p.useCallback(async()=>{a(Io(R,null)),u(""),O({includeCompareTarget:!1}),i("")},[R,O,a,u,i]),Ae=p.useCallback(async()=>{a(gp(R)),u(""),O({includeCompareTarget:!1}),i(""),j&&C?.(P?.()??[])},[R,O,a,u,C,P,j,i]),X=p.useCallback(async()=>{a(Cp(R)),u(""),O({includeCompareTarget:!0}),i("")},[R,O,a,u,i]);return{onOpenChatsOverview:Y,onSelect:$,onRenameChannel:M,onDeleteChannel:J,onClearDirectLane:F,onRenameParallelChatGroup:me,onUngroupParallelChatGroup:K,onDeleteParallelChatGroup:B,onDeleteCat:ae,onNavigateSettings:be,onNavigateRuntime:W,onCreateNewCat:q,onDirectChatCat:_e,onResetSetup:le,onStartNewChat:xe,onStartNewGroupChat:Ae,onStartNewParallelChat:X}}const sC=5e3;function Vi(e){return!!(e&&typeof e=="object"&&!Array.isArray(e))}function oC(e){return!Vi(e)||!Vi(e.chat)?!1:Array.isArray(e.chat.channels)&&Array.isArray(e.chat.cats)&&(typeof e.chat.selectedChannelId=="string"||e.chat.selectedChannelId===null)}function iC(e){return oC(e)}function lC(e){const t=Qg(e);return iC(t)?t:null}function cC(e){const t=e.consumeWarmPayload?.(e.match)??lC(e.match);return e.initialHadReadyState?null:t}async function dC(e){const t=cC({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(uC(n,e.unknownRendererErrorMessage))}}function uC(e,t){return e instanceof Error?/^cats app shell returned \d+$/u.test(e.message)?t:e.message:t}function pC(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 hC(e,t){return{...e,runtime:t.runtime,runtimeSetup:t.runtimeSetup,metadata:t.metadata,bootstrapAttemptId:t.bootstrapAttemptId}}function fC(e,t){return e.status!=="ready"||!pC(e.payload,t)?e:{status:"ready",payload:hC(e.payload,t)}}function mC(e){const{state:t,setState:n,navigate:a,busy:s,surface:o,currentPath:i,chatPrefix:u,routeChannelId:c,routeChannelExists:d,selectedChannelId:h,selectedChannelViewId:f,selectedChannelEntryLifecycle:m,draftDefaultRecipientCatId:v,showingMyCatDirectLane:C,routeDirectLaneSummary:I,readySelectedChannel:y,unknownRendererErrorMessage:g,fetchAppShell:x=yo,updateSelectedChannel:S=Kl,isRouteSelectionBlocked:k=Lm,resolveMissingDraftDefaultRecipientPath:w}=e,P=t.status==="ready"?t.payload:null,j=P?lr(u,P.chat.channels,h,o):oi(u),N=P&&v?w?.({channels:P.chat.channels,selectedChannelId:P.chat.selectedChannelId,draftDefaultRecipientCatId:v,showingMyCatDirectLane:C})??(C?lr(u,P.chat.channels,P.chat.selectedChannelId,o):oi(u)):null,D=v?P?.chat.cats.some(L=>L.id===v&&L.status==="active"):!1,T=I?.id??null,A=y&&vp(y)?y.roomRouting.defaultRecipientId??null:null,b=p.useRef({surface:o,path:i}),R=p.useRef(t.status==="ready");p.useEffect(()=>{const L=new AbortController;return dC({initialHadReadyState:R.current,match:{surface:b.current.surface,path:b.current.path},fetchAppShell:x,signal:L.signal,unknownRendererErrorMessage:g,onReady:O=>{p.startTransition(()=>{n({status:"ready",payload:O})})},onError:O=>{n({status:"error",message:O})}}),()=>L.abort()},[x,n]),p.useEffect(()=>{if(t.status!=="ready"||typeof window>"u"||typeof document>"u")return;let L=null;const O=()=>{if(document.visibilityState==="hidden"||L)return;const F=new AbortController;L=F,x(F.signal).then(J=>{F.signal.aborted||p.startTransition(()=>{n(me=>fC(me,J))})}).catch(()=>{}).finally(()=>{L===F&&(L=null)})},Y=window.setInterval(O,sC),$=()=>{O()},M=()=>{document.visibilityState==="visible"&&O()};return window.addEventListener("focus",$),document.addEventListener("visibilitychange",M),()=>{L&&L.abort(),window.clearInterval(Y),window.removeEventListener("focus",$),document.removeEventListener("visibilitychange",M)}},[x,n,t.status]),p.useEffect(()=>{if(!P||!c||k(s,c)||Ol(c))return;if(!d){a(j,{replace:!0});return}if(!Ip({routeChannelId:c,routeChannelExists:d,selectedChannelId:h,selectedChannelViewId:f}))return;const L=new AbortController;return S(c,L.signal).then(O=>{L.signal.aborted||p.startTransition(()=>n({status:"ready",payload:O}))}).catch(()=>{L.signal.aborted||a(j,{replace:!0})}),()=>L.abort()},[s,u,a,d,c,j,m,h,f,n,P]),p.useEffect(()=>{!P||!v||!D&&N&&a(N,{replace:!0})},[v,D,N,a,P]),p.useEffect(()=>{if(!P||!C||!v||!T||A&&A===v)return;const L=new AbortController;return S(T,L.signal).then(O=>{L.signal.aborted||p.startTransition(()=>n({status:"ready",payload:O}))}).catch(()=>{}),()=>L.abort()},[v,P,A,T,n,C])}function zi(e,t){return`${e}:${t}`}class gC{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=zi(t.kind,t.id);let a=this.entries.get(n);a||(a={kind:t.kind,id:t.id,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.retryCount=0}),a.addEventListener("snapshot",s=>{const o=JSON.parse(s.data);for(const i of t.callbacks)i.onSnapshot(o)}),a.addEventListener("patch",s=>{const o=JSON.parse(s.data);for(const i of t.callbacks)i.onPatch(o)}),a.addEventListener("close",s=>{const o=JSON.parse(s.data);for(const i of t.callbacks)i.onClose?.(o);this.closeEntry(zi(t.kind,t.id),t)}),a.onerror=()=>{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 Vc=new gC;function zc(e){const t=p.useRef({onSnapshot:e.onSnapshot,onPatch:e.onPatch,onClose:e.onClose});t.current={onSnapshot:e.onSnapshot,onPatch:e.onPatch,onClose:e.onClose},p.useEffect(()=>Vc.subscribe({kind:e.kind,id:e.id,enabled:e.enabled,onSnapshot:n=>t.current.onSnapshot(n),onPatch:n=>t.current.onPatch(n),onClose:n=>t.current.onClose?.(n)}),[e.enabled,e.id,e.kind])}function Yc(e){return new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))}function Yi(e,t,n){const a=[...e];return a.splice(Math.max(0,Math.min(t,a.length)),0,n),a}function CC(e,t,n){let a=[...t.memberChannelIds],s=[...t.members];for(const o of n){const i=e.memberChannelIds.includes(o),u=t.memberChannelIds.includes(o);if(i&&!u){const c=e.memberChannelIds.indexOf(o);a=Yi(a,c,o);const d=e.members.find(h=>h.channelId===o);d&&!s.some(h=>h.channelId===o)&&(s=Yi(s,c,d));continue}!i&&u&&(a=a.filter(c=>c!==o),s=s.filter(c=>c.channelId!==o))}return{...t,memberChannelIds:a,members:s,memberCount:a.length}}function Jc(e,t,n){const a=Yc(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))],u=[];for(const c of i){const d=s.get(c)??null,h=o.get(c)??null;if(d&&h){u.push(CC(d,h,a));continue}if(h){u.push(h);continue}d&&d.memberChannelIds.some(f=>a.has(f))&&u.push(d)}return u}function vC(e){const t=e.assignedParticipants;return Array.isArray(t)&&t.length>0?t:e.assignedCats}function IC(e){const t=us(e.roomRouting),n=vC(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 SC(e){const t=us(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 yC(e){const t=us(e.roomRouting);return t.workflow.activeTurn?.updatedAt??t.workflow.lastOutcomeEvent?.createdAt??t.lastOutcome?.completedAt??t.lastCheckpoint?.createdAt??null}function Xc(e,t){const n=us(t.roomRouting),a=IC(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:SC(t),lastRoutingAt:yC(t)}}function bC(e,t){const n=e.findIndex(s=>s.id===t.id);if(n===-1)return e;const a=[...e];return a[n]=Xc(e[n],t),a}function xC(e){const t=Yc(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?Xc(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 wC(e){return new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))}function kC(e,t,n){const a=wC(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:xC({currentChannels:e.chat.channels,nextChannels:t.chat.channels,currentSelectedChannel:e.chat.selectedChannel,activeSubscribedIds:a}),parallelChatGroups:Jc(e.chat.parallelChatGroups,t.chat.parallelChatGroups,a)}}}function PC(e,t){let n=t;for(const a of Sp())n=yp(e,n,a.channelId,a.optimisticMessageId);return n}function AC(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 RC(e){const{enabled:t=!0,fetchAppShell:n=yo,setState:a,state:s}=e,o=p.useRef(s.status==="ready"?s.payload:null),i=p.useRef(null),u=p.useRef(!1),c=p.useRef(!1);p.useEffect(()=>{o.current=s.status==="ready"?s.payload:null},[s]);const d=p.useCallback(()=>{if(u.current){c.current=!0;return}const h=new AbortController;i.current=h,u.current=!0;const f=()=>{u.current=!1,i.current===h&&(i.current=null),c.current&&(c.current=!1,d())};n(h.signal).then(m=>{if(h.signal.aborted||!AC(o.current?.metadata.generatedAt,m.metadata.generatedAt))return;const v=o.current,C=v?kC(v,m,Vc.getActiveSubscribedIds("channel")):m,I=v?PC(v,C):C;o.current=I,p.startTransition(()=>{a({status:"ready",payload:I})})}).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",d),m.addEventListener("recents_changed",d),m.addEventListener("unread_changed",d),m.addEventListener("transport_ingress",d),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,u.current=!1,c.current=!1}},[t,d]),{refreshAppShell:d}}const NC=[/^cats chat cat creation returned \d+$/u,/^cats channel cat assignment returned \d+$/u,/^cats channel cat removal returned \d+$/u];function TC(e,t){const n=bp(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 jr(e,t,n){if(!(e instanceof Error))return t;const a=TC(e.message,n);return a||(NC.some(s=>s.test(e.message))?t:e.message)}function Ji(e){if(!(!e||e===$l))return e}function jC(e){const{state:t,setState:n,catForm:a,emptyCatForm:s,setCatForm:o,setBusy:i,setFeedback:u,setAddCatOpen:c,setDraftCatIds:d,createGlobalCat:h=xp,assignCatToChannelApi:f=wp,removeCatFromChannelApi:m=kp}=e,{t:v}=z(),C=p.useCallback(async S=>{if(S.preventDefault(),t.status!=="ready")return;const k=t.payload.chat.selectedChannelId;if(k){i(Sa("create-assign"));try{const w=a.name.trim(),P=new Set(t.payload.chat.cats.map(T=>T.id)),j=await h({name:w,provider:a.provider,instance:a.instance||void 0,model:a.model||void 0,modelSelection:a.modelSelection,mcpProfile:Ji(a.mcpProfile)});p.startTransition(()=>n({status:"ready",payload:j}));const N=j.chat.cats.find(T=>!P.has(T.id));if(!N){o(s()),u(v(l.chatCatAssignmentCreatedAssignHint)),i(Oe());return}const D=await f(k,{catId:N.id,provider:N.defaultExecutionTarget.provider,instance:N.defaultExecutionTarget.instance??void 0,model:N.defaultExecutionTarget.model??void 0,modelSelection:N.defaultModelSelection??void 0});p.startTransition(()=>{n({status:"ready",payload:D}),o(s()),c(!1),u("")})}catch(w){u(jr(w,v(l.chatCatAssignmentErrorCreateCat),v))}finally{i(Oe())}}},[a.instance,a.modelSelection,a.model,a.name,a.provider,a.mcpProfile,s,c,i,o,u,n,t,v]),I=p.useCallback(async S=>{if(t.status!=="ready")return;const k=t.payload.chat.selectedChannelId;if(k){i(Sa("assign",S.id));try{const w=await f(k,{catId:S.id,provider:S.defaultExecutionTarget.provider,instance:S.defaultExecutionTarget.instance??void 0,model:S.defaultExecutionTarget.model??void 0,modelSelection:S.defaultModelSelection??void 0});p.startTransition(()=>{n({status:"ready",payload:w}),u("")})}catch(w){u(jr(w,v(l.chatCatAssignmentErrorAssignCat),v))}finally{i(Oe())}}},[i,u,n,t,v]),y=p.useCallback(async S=>{if(t.status!=="ready")return;const k=t.payload.chat.selectedChannelId;if(k){i(Sa("remove",S.id));try{const w=await m(k,S.id);p.startTransition(()=>{n({status:"ready",payload:w}),u("")})}catch(w){u(jr(w,v(l.chatCatAssignmentErrorRemoveCat),v))}finally{i(Oe())}}},[i,u,n,t,v]),g=p.useCallback(S=>{d(k=>k.includes(S)?k.filter(w=>w!==S):[...k,S])},[d]),x=p.useCallback(async S=>{if(S.preventDefault(),t.status==="ready"){i(Sa("create-assign"));try{const k=new Set(t.payload.chat.cats.map(j=>j.id)),w=await h({name:a.name.trim(),provider:a.provider,instance:a.instance||void 0,model:a.model||void 0,modelSelection:a.modelSelection,mcpProfile:Ji(a.mcpProfile)});p.startTransition(()=>n({status:"ready",payload:w}));const P=w.chat.cats.find(j=>!k.has(j.id));P&&d(j=>[...j,P.id]),o(s()),c(!1),u("")}catch(k){u(jr(k,v(l.chatCatAssignmentErrorCreateCat),v))}finally{i(Oe())}}},[a.instance,a.modelSelection,a.model,a.name,a.provider,a.mcpProfile,s,c,i,o,d,u,n,t,v]);return{onAssignExistingCat:I,onCreateAndAssignCat:C,onCreateAndDraftCat:x,onRemoveAssignedCat:y,toggleDraftCat:g}}const LC=ea("en");function Qc(e){return{composerDraft:e.composerDraft,draftCwd:e.draftCwd,draftRuntimeSessionPolicy:e.draftRuntimeSessionPolicy??null,draftAudienceKeys:e.draftAudienceKeys??null,draftWorkflowShape:e.draftWorkflowShape??"sequential",draftFiles:e.draftFiles}}function MC(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 EC(e,t){return e.cwd??t.draftCwd}function DC(e,t){return e.promptOverride==null||e.promptOverride===""?t.composerDraft:e.promptOverride}function BC(e,t){return e.runtimeSessionPolicy??t.draftRuntimeSessionPolicy}function Zc(e,t){return MC(e.audienceKeys??t.draftAudienceKeys)}function ed(e,t){return e.workflowShape??t.draftWorkflowShape}function OC(e,t){return t.draftFiles}function _C(e,t=LC){const n=e.findIndex(a=>a.attachmentsOverride!=null);if(n!==-1)throw new Error(t(l.chatNewChatDraftBranchAttachmentOverrideError,{branchIndex:n+1}))}function td(e,t){return{target:e,effectivePrompt:DC(e,t),effectiveCwd:EC(e,t),effectiveSessionPolicy:BC(e,t),effectiveAudienceKeys:Zc(e,t),effectiveWorkflowShape:ed(e,t),effectiveAttachments:OC(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 nd=ea("en");function Xi(e){return Co(e)??e.trim()}function FC(e,t){return e.chat.channels.some(n=>n.id===t&&n.routingStatus==="running")}function ad(e,t){return t.some(n=>FC(e,n))}function WC(e){const t=e.t??nd;_C(e.draftParallelChatTargets,t);const n=Qc({composerDraft:e.body,draftCwd:e.draftCwd,draftRuntimeSessionPolicy:e.draftSessionPolicy,draftFiles:e.draftFiles??[],draftWorkflowShape:e.draftWorkflowShape,draftAudienceKeys:e.draftAudienceKeys}),a=e.draftParallelChatTargets.map(s=>td(s,n));return{title:Ap(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:Xi(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:Xi(s.provider),instance:s.instance??void 0,model:s.model??void 0,modelSelection:s.modelSelection??null,roleHint:s.roleHint??void 0}))}}async function UC({body:e,payload:t,originSurface:n,draftCwd:a,draftSessionPolicy:s,draftFiles:o,draftWorkflowShape:i,draftAudienceKeys:u,draftParallelChatTargets:c,draftParticipantCatIds:d=[],draftTemporaryParticipants:h=[],buildChannelPath:f,t:m=nd,signal:v}){if(c.length<2)throw new Error(m(l.chatComposerErrorChooseTwoParallelChats));const C=Qc({composerDraft:e,draftCwd:a,draftRuntimeSessionPolicy:s,draftFiles:o,draftWorkflowShape:i,draftAudienceKeys:u}),I=c.map(k=>td(k,C)),y=await Pp(WC({body:e,existingCount:t.chat.channels.length,originSurface:n,draftCwd:a,draftSessionPolicy:s,draftFiles:o,draftWorkflowShape:i,draftAudienceKeys:u,draftParallelChatTargets:c,draftParticipantCatIds:d,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 Hl(o):void 0,S=await ql(y.group.id,{activeChannelId:g,body:e,attachments:x,channelInputs:y.group.memberChannelIds.map((k,w)=>{const P=I[w];if(!P)return{channelId:k};const j=P.effectiveAudienceKeys,N=P.effectiveWorkflowShape,D=j.length>0?ec({draftParticipantCatIds:d,draftTemporaryParticipants:h,draftAudienceKeys:j,maxAudienceParticipants:t.chat.capabilities.maxAudienceParticipants??Number.POSITIVE_INFINITY}):[];return{channelId:k,body:P.effectivePrompt,messageMetadata:D.length>0?{recipientParticipantIds:D,workflowShape:N}:void 0}})},v);return{createdAppShell:y.appShell,dispatchAppShell:S.appShell,rollbackPath:f(g),dispatchRequest:ad(S.appShell,y.group.memberChannelIds)?{kind:"parallel",channelId:g,groupId:y.group.id,channelIds:y.group.memberChannelIds}:null}}async function KC({body:e,payload:t,compareGroupId:n,channelId:a,channelFiles:s,signal:o}){const i=t.chat.parallelChatGroups.find(d=>d.id===n)?.memberChannelIds??[a],u=s.length>0?await Hl(s):void 0,c=await ql(n,{activeChannelId:a,body:e,attachments:u},o);return{dispatchAppShell:c.appShell,dispatchRequest:ad(c.appShell,i)?{kind:"parallel",channelId:a,groupId:n,channelIds:i}:null}}const $C=ea("en");function HC(e){return Co(e)??e.trim()}function qC(e,t){return!e||!t?!1:e.channelKind==="direct_message"&&e.roomRouting?.defaultRecipientId===t}function GC(e){const{wasDraftingNewChat:t,isCatScopedLaneRoute:n,channelId:a,selectedChannel:s,defaultChannelExecutionTarget:o}=e;return t||n||s?.id!==a||!An(s)?null:{pendingProvider:HC(o.provider),pendingModel:o.model,pendingInstance:o.instance,pendingModelSelection:o.modelSelection}}function VC(e){const{isCatScopedLaneRoute:t,hydratedDirectLane:n,wasDraftingNewChat:a,draftFiles:s,channelFiles:o}=e;return t&&!n?s:n?o:a?s:o}async function zC(e){const{channelId:t,body:n,filesToUpload:a,updateSelectedChannel:s,uploadChannelAttachments:o,signal:i}=e;let{payload:u}=e,c=n;if(a.length===0)return{payload:u,messageBody:c};const d=u.chat.selectedChannel?.id===t?u.chat.selectedChannel:null;!d?.repoPath&&!d?.chatCwd&&(u=await s(t,i));const h=await o(t,a,i);return c=Rp(n,h),{payload:u,messageBody:c}}async function YC(e){const{initialPayload:t,wasDraftingNewChat:n,isCatScopedLaneRoute:a,hydratedDirectLane:s,currentChannelId:o,currentRollbackPath:i,body:u,existingCount:c,draftCwd:d,draftSessionPolicy:h,originSurface:f,draftDefaultRecipientCatId:m,participantCatIds:v,temporaryParticipants:C=[],draftEntryKind:I,draftExecutionTarget:y,assistantResponseLanguage:g,t:x=$C,createChatChannel:S,insertCreatedChannelIntoPayload:k,setState:w,navigate:P,setChannelFiles:j,originalDraftFiles:N,originalChannelFiles:D,buildChannelPath:T,signal:A}=e;let b=t,R=t,L=o,O=i,Y=()=>{j(n||a&&!s?N:D)};if(a)if(s)L=s.id,Y=()=>{j(D)};else{const $=await S(ii({body:u,existingCount:c,originSurface:f,entryKind:"direct",repoPath:d,draftSessionPolicy:h,t:x,defaultRecipientCatId:m,participantCatIds:v,assistantResponseLanguage:g,temporaryParticipants:C.map(M=>({participantId:M.participantId,name:M.name,provider:M.provider,instance:M.instance??void 0,model:M.model??void 0,modelSelection:M.modelSelection??null,roleHint:M.roleHint??void 0}))}),A);if(L=$.id,!L)throw new Error(x(l.chatComposerErrorNoChatForSending));b=k(t,$),R=b,w({status:"ready",payload:b}),P(O,{replace:!0}),Y=()=>{j(N)}}else if(n){const $=await S(ii({body:u,existingCount:c,originSurface:f,entryKind:I,repoPath:d,draftSessionPolicy:h,t:x,defaultRecipientCatId:m,participantCatIds:v,assistantResponseLanguage:g,temporaryParticipants:C.map(M=>({participantId:M.participantId,name:M.name,provider:M.provider,instance:M.instance??void 0,model:M.model??void 0,modelSelection:M.modelSelection??null,roleHint:M.roleHint??void 0})),draftExecutionTarget:y}),A);if(L=$.id,!L)throw new Error(x(l.chatComposerErrorNoChatForSending));O=T(L),b=k(t,$),R=b,w({status:"ready",payload:b}),P(O,{replace:!0}),Y=()=>{j(N)}}else{if(!L)throw new Error(x(l.chatComposerErrorNoChatForSending));Y=()=>{j(D)}}if(!L)throw new Error(x(l.chatComposerErrorNoChatForSending));return{payload:b,rollbackPayload:R,channelId:L,rollbackPath:O,restoreFiles:Y}}async function JC(e){const{initialPayload:t,wasDraftingNewChat:n,isCatScopedLaneRoute:a,hydratedDirectLane:s,currentChannelId:o,currentRollbackPath:i,body:u,existingCount:c,draftCwd:d,draftSessionPolicy:h,originSurface:f,draftDefaultRecipientCatId:m,participantCatIds:v,temporaryParticipants:C,draftEntryKind:I,draftExecutionTarget:y,assistantResponseLanguage:g,t:x,selectedChannel:S,defaultChannelExecutionTarget:k,draftFiles:w,channelFiles:P,createChatChannel:j,insertCreatedChannelIntoPayload:N,setState:D,navigate:T,setChannelFiles:A,originalDraftFiles:b,originalChannelFiles:R,buildChannelPath:L,updateSelectedChannel:O,uploadChannelAttachments:Y,signal:$}=e;let M=t;const F=await YC({initialPayload:t,wasDraftingNewChat:n,isCatScopedLaneRoute:a,hydratedDirectLane:s,currentChannelId:o,currentRollbackPath:i,body:u,existingCount:c,draftCwd:d,draftSessionPolicy:h,originSurface:f,draftDefaultRecipientCatId:m,participantCatIds:v,temporaryParticipants:C,draftEntryKind:I,draftExecutionTarget:y,assistantResponseLanguage:g,t:x,createChatChannel:j,insertCreatedChannelIntoPayload:N,setState:D,navigate:T,setChannelFiles:A,originalDraftFiles:b,originalChannelFiles:R,buildChannelPath:L,signal:$});M=F.payload;const J=GC({wasDraftingNewChat:n,isCatScopedLaneRoute:a,channelId:F.channelId,selectedChannel:S,defaultChannelExecutionTarget:k}),me=VC({isCatScopedLaneRoute:a,hydratedDirectLane:s,wasDraftingNewChat:n,draftFiles:w,channelFiles:P}),K=await zC({payload:M,channelId:F.channelId,body:u,filesToUpload:me,updateSelectedChannel:O,uploadChannelAttachments:Y,signal:$});return M=K.payload,K.payload!==F.payload&&D({status:"ready",payload:M}),{...F,payload:M,rollbackPayload:K.payload!==F.payload?M:F.rollbackPayload,messageBody:K.messageBody,defaultDispatchTarget:J}}function rd(){const e=globalThis.location;return e?`${e.pathname??""}${e.search??""}`:""}function XC(e,t){return e==null||e===t}function QC(e){e.current=rd()}function ZC(e){e.current=null}function ev(e,t,n){const a=rd();return XC(e.current,a)?(t(n,{replace:!0}),e.current=n,!0):!1}function tv(e){return e==="sequential"||e==="concurrent"||e==="converge"||e==="parallel"?e:null}function nv(e){return e==="concurrent"?"concurrent":"sequential"}function av(e){for(let t=e.length-1;t>=0;t-=1){const n=e[t];if(n?.senderKind==="user")return n}return null}function sd(e){return`cat:${e}`}function Wo(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 Uo(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 rv(e,t){return Wo(Uo(e.assignedCats.filter(n=>n.status==="active").map(n=>n.catId)),t)}function sv(e){const{audienceKeys:t}=e;if(!t||t.length===0)return[];const n=new Map(e.activeParticipantIds.map(a=>[sd(a),a]));return Wo(Uo(t.map(a=>n.get(a)??"")),e.maxAudienceParticipants)}function ov(e){const t=od(e),{selectedChannel:n}=e;return!n||!t?.recipientParticipantIds?.length?null:{audienceKeys:t.recipientParticipantIds.map(a=>sd(a)),workflowShape:nv(t.workflowShape)}}function od(e){const{selectedChannel:t}=e;if(!t||An(t)||!Zs(t))return null;const n=rv(t,e.maxAudienceParticipants);if(n.length===0)return null;const s=av(t.messages)?.metadata??{},o=sv({activeParticipantIds:n,audienceKeys:e.audienceKeys,maxAudienceParticipants:e.maxAudienceParticipants}),i=Wo(Uo(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 u=o.length>0?o:i.length>0?i:n,c=t.roomRouting.workflow.turnHistory[0]??null,d=tv(e.workflowShape??s.workflowShape??t.roomRouting.workflow.activeTurn?.workflowShape??c?.workflowShape??(u.length>1?"sequential":null));return u.length===0&&!d?null:{...u.length>0?{recipientParticipantIds:u}:{},...d?{workflowShape:d}:{}}}function iv({activeDispatchRequestRef:e,cancelPendingAckRequest:t,cancelChannel:n,cancelConcurrentGroup:a,setBusy:s,setFeedback:o,setState:i}){const{t:u}=z(),c=p.useCallback(async()=>{const h=e.current;if(h){e.current=null,o(""),s(h.kind==="parallel"?zn("stop"):qn("stop",Gn(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(Ht(f,u(l.chatComposerErrorStopFailed),u))}finally{s(Oe())}}},[e,n,a,s,o,i,u]);return{onCancelPendingSend:p.useCallback(()=>{t()&&o("")},[t,o]),onStopMessage:c}}function Qi(e,t,n){return t.kind==="parallel"?(t.channelIds??[t.channelId]).some(a=>n(e,a)):n(e,t.channelId)}function Zi(e,t){return t.kind==="parallel"?gn(e,"dispatch"):Rm(e)===t.channelId}function lv(e){const{state:t,busy:n,setBusy:a,setState:s,fetchPayload:o,isChannelDispatchRunning:i,hydratePendingDispatch:u}=e,c=p.useRef(null),d=p.useRef(null),h=p.useRef(1),f=p.useRef(null);p.useEffect(()=>()=>{c.current?.controller.abort(),c.current=null,d.current=null},[]),p.useEffect(()=>{if(!u||t.status!=="ready"||d.current!==null)return;const g=u.kind==="channel"?u.channelId:u.groupId;if(!g||f.current===g)return;if(u.kind==="channel"){const{channelId:w}=u;if(!i(t.payload,w))return;f.current=g,d.current={id:h.current,kind:"channel",channelId:w},h.current+=1,a(qn("send",Gn(w)));return}const{groupId:x,activeChannelId:S,channelIds:k}=u;k.length===0||!S||k.some(w=>i(t.payload,w))&&(f.current=g,d.current={id:h.current,kind:"parallel",channelId:S,groupId:x,channelIds:k},h.current+=1,a(zn("dispatch")))},[u,i,a,t]),p.useEffect(()=>{if(t.status!=="ready")return;const g=d.current;!g||Am(n)||Qi(t.payload,g,i)||Zi(n,g)&&(d.current=null,a(Oe()))},[n,i,a,t]),p.useEffect(()=>{const g=d.current;if(!g||!Zi(n,g))return;let x=!1,S=!1;const k=window.setInterval(async()=>{if(!(x||S)){S=!0;try{const w=await o();if(x)return;s({status:"ready",payload:w});const P=d.current;if(!P||P.id!==g.id)return;Qi(w,P,i)||(d.current=null,a(Oe()))}catch{}finally{S=!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},[]),I=p.useCallback(g=>{d.current=g},[]),y=p.useCallback(g=>{d.current?.id===g&&(d.current=null)},[]);return{activeDispatchRequestRef:d,beginAckRequest:m,cancelPendingAckRequest:C,clearAckRequestIfCurrent:v,clearDispatchRequestIfCurrent:y,setActiveDispatchRequest:I}}function cv(e){const t=p.useCallback(async a=>{a.preventDefault(),await e()},[e]);return{onComposerKeyDown:p.useCallback(async a=>{Pm({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 $s(e,t){return e.chat.channels.some(n=>n.id===t&&n.routingStatus==="running")}function el(e){return e instanceof Error&&e.name==="AbortError"}function dv(e){const{state:t,setState:n,navigate:a,chatPrefix:s,originSurface:o,currentPath:i,composerDraft:u,setComposerDraft:c,showingNewChatDraft:d,showingMyCatDirectLane:h,draftEntryKind:f="default",draftDefaultRecipientCatId:m,draftCatIds:v,draftTemporaryParticipants:C=[],draftCwd:I,draftSessionPolicy:y=null,draftFiles:g,channelFiles:x,setDraftCwd:S,setDraftCatIds:k,setDraftTemporaryParticipants:w,setDraftHighlightedCatId:P,setDraftCatExecutionTargetOverrides:j,setDraftRuntimeSessionPolicy:N,setDraftFiles:D,setChannelFiles:T,setDraftWorkflowShape:A,setDraftAudienceKeys:b,draftExecutionTarget:R,defaultChannelExecutionTarget:L,showingParallelChatDraft:O=!1,draftParallelChatTargets:Y=[],draftWorkflowShape:$="sequential",draftAudienceKeys:M=null,activeWorkflowShape:F="sequential",activeAudienceKeys:J=null,resetDraftParallelChatTargets:me,compareGroupId:K=null,compareSendScope:B="active_only",selectedChannel:ae,busy:be,setBusy:W,setFeedback:q,hydratePendingDispatch:_e=null}=e,{t:le}=z(),xe=p.useRef(null),{activeDispatchRequestRef:Ae,beginAckRequest:X,cancelPendingAckRequest:re,clearAckRequestIfCurrent:G,clearDispatchRequestIfCurrent:pe,setActiveDispatchRequest:Ie}=lv({state:t,busy:be,setBusy:W,setState:n,fetchPayload:yo,isChannelDispatchRunning:$s,hydratePendingDispatch:_e}),{onCancelPendingSend:Qe,onStopMessage:Nt}=iv({activeDispatchRequestRef:Ae,cancelPendingAckRequest:re,cancelChannel:Fp,cancelConcurrentGroup:_p,setBusy:W,setFeedback:q,setState:n}),Vt=p.useCallback(async()=>{if(t.status!=="ready")return;const ct=u.trim(),Te=g.length>0,se=x.length>0;if(!ct&&!Te&&!se)return;const ce=t.payload,Re=d,Me=!!m&&h,dt=Dl(ce.chat.selectedChannel??null),ot=qC(dt,m)?dt:null;let tt=ce,Se=ce,Fe=Re||h?ot?.id??"":ce.chat.selectedChannelId,it=h?Np(s,m??""):Re?Io(s,m):i;const zt=[...g],Yt=[...x];let St=()=>{Re||Me&&!ot?D(zt):T(Yt)},Tt=null;const ge=Ye=>ev(xe,a,Ye);q("");const{id:ke,controller:Ne}=X();let Dt=!1;QC(xe);try{if(O&&Re){W(zn("ack"));const Pe=await UC({body:ct,payload:ce,originSurface:o,draftCwd:I,draftSessionPolicy:y,draftFiles:g,draftWorkflowShape:$,draftAudienceKeys:M,draftParallelChatTargets:Y,draftParticipantCatIds:v,draftTemporaryParticipants:C,buildChannelPath:rt=>qr(s,rt),t:le,signal:Ne.signal});Se=Pe.createdAppShell,it=Pe.rollbackPath,c(""),D([]),ge(it),n({status:"ready",payload:Pe.createdAppShell}),St=()=>{T(zt)},G(ke),Se=Pe.dispatchAppShell,n({status:"ready",payload:Pe.dispatchAppShell}),Pe.dispatchRequest?(Ie({id:ke,...Pe.dispatchRequest}),W(zn("dispatch")),Dt=!0):Ie(null),q(""),_r({setDraftCwd:S,setDraftCatIds:k,setDraftTemporaryParticipants:w,setDraftHighlightedCatId:P,setDraftCatExecutionTargetOverrides:j,setDraftRuntimeSessionPolicy:N,setDraftFiles:D,setDraftWorkflowShape:A,setDraftAudienceKeys:b}),me?.();return}if(K&&B==="all_members"&&!Re){if(!Fe)throw new Error(le(l.chatComposerErrorNoParallelChatForSending));it=i,c(""),T([]),W(zn("ack"));const Pe=await KC({body:ct,payload:ce,compareGroupId:K,channelId:Fe,channelFiles:x,signal:Ne.signal});G(ke),Se=Pe.dispatchAppShell,n({status:"ready",payload:Pe.dispatchAppShell}),Pe.dispatchRequest?(Ie({id:ke,...Pe.dispatchRequest}),W(zn("dispatch")),Dt=!0):Ie(null),q("");return}const Ye=Fe?Gn(Fe):Tp();W(qn("prepare",Ye));const V=await JC({initialPayload:ce,wasDraftingNewChat:Re,isCatScopedLaneRoute:Me,hydratedDirectLane:ot,currentChannelId:Fe,currentRollbackPath:it,body:ct,existingCount:ce.chat.channels.length,draftCwd:I,draftSessionPolicy:y,originSurface:o,draftDefaultRecipientCatId:m,participantCatIds:v,temporaryParticipants:C,draftEntryKind:f,draftExecutionTarget:R,assistantResponseLanguage:ce.language?.assistantResponseLanguage,selectedChannel:ae,defaultChannelExecutionTarget:L,draftFiles:g,channelFiles:x,createChatChannel:Mp,insertCreatedChannelIntoPayload:Lp,setState:n,navigate:a,setChannelFiles:T,originalDraftFiles:zt,originalChannelFiles:Yt,buildChannelPath:Pe=>qr(s,Pe),updateSelectedChannel:Kl,uploadChannelAttachments:jp,t:le,signal:Ne.signal});tt=V.payload,Se=V.rollbackPayload,Fe=V.channelId,it=V.rollbackPath,St=V.restoreFiles;const{messageBody:Ke,defaultDispatchTarget:nt}=V,xt=t.status==="ready"?t.payload.chat.capabilities.maxAudienceParticipants:void 0,gt=Re&&f==="group"&&!O?(()=>{const Pe=ec({draftParticipantCatIds:v,draftTemporaryParticipants:C,draftAudienceKeys:M,maxAudienceParticipants:xt});return Pe.length>0?{recipientParticipantIds:Pe,workflowShape:$}:null})():null,Jt=Re?null:od({selectedChannel:ae,maxAudienceParticipants:xt,audienceKeys:J,workflowShape:F}),Ut=gt??Jt;nt&&(tt=Ep(tt,Fe,nt));const at=Dp(tt,Fe,Ke);tt=at.payload,Tt=at.optimisticMessageId,Bp(Fe,at.optimisticMessageId),n({status:"ready",payload:tt}),c(""),D([]),T([]),ge(it),W(qn("ack",Gn(Fe)));const jt=await Gl(Fe,{body:Ke,clientMessageId:at.optimisticMessageId,senderName:tt.ownerDisplayName,...nt??{},...Ut?{messageMetadata:Ut}:{}},Ne.signal);li(Fe,at.optimisticMessageId),Tt=null,G(ke),n({status:"ready",payload:jt.appShell}),$s(jt.appShell,Fe)?(Ie({id:ke,kind:"channel",channelId:Fe}),W(qn("send",Gn(Fe))),Dt=!0):Ie(null),c(""),q(""),ge(it),Me?_r({setDraftCwd:S,setDraftCatIds:k,setDraftTemporaryParticipants:w,setDraftHighlightedCatId:P,setDraftCatExecutionTargetOverrides:j,setDraftRuntimeSessionPolicy:N,setDraftFiles:D,setChannelFiles:T,setDraftWorkflowShape:A,setDraftAudienceKeys:b}):Re?(_r({setDraftCwd:S,setDraftCatIds:k,setDraftTemporaryParticipants:w,setDraftHighlightedCatId:P,setDraftCatExecutionTargetOverrides:j,setDraftRuntimeSessionPolicy:N,setDraftFiles:D,setDraftWorkflowShape:A,setDraftAudienceKeys:b}),me?.()):T([])}catch(Ye){G(ke),Ae.current?.id===ke&&Ie(null),Tt&&(li(Fe,Tt),Tt=null),n({status:"ready",payload:Se}),c(ct),St(),el(Ye)?q(""):q(Ht(Ye,le(l.chatComposerErrorSendFailed),le)),ge(it)}finally{Dt||(G(ke),pe(ke),W(Oe())),ZC(xe)}},[Ae,X,x,s,G,pe,u,i,v,C,I,y?.permissionMode,y?.workspaceAccess,y?.workspaceKind,g,f,m,o,R.instance,R.modelSelection,R.model,R.provider,a,ae,Ie,W,T,c,k,w,P,j,N,S,D,b,A,q,n,M,Y,$,J,F,K,B,O,h,d,L.instance,L.modelSelection,L.model,L.provider,me,t,le]),{onSendMessage:Le,onComposerKeyDown:Wt}=cv(Vt),Et=p.useCallback(async ct=>{if(t.status!=="ready"||!ae||!ct.trim())return;const Te=ae.id;q("");const{id:se,controller:ce}=X();let Re=!1;try{W(qn("ack",Gn(Te)));const Me=await Op(Te,ct,ce.signal);G(se),n({status:"ready",payload:Me.appShell}),$s(Me.appShell,Te)?(Ie({id:se,kind:"channel",channelId:Te}),W(qn("send",Gn(Te))),Re=!0):Ie(null),q("")}catch(Me){G(se),Ae.current?.id===se&&Ie(null),el(Me)?q(""):q(Ht(Me,le(l.chatComposerErrorRetryFailed),le))}finally{Re||(G(se),pe(se),W(Oe()))}},[Ae,X,G,pe,ae,Ie,W,q,n,t,le]);return{onComposerKeyDown:Wt,onCancelPendingSend:Qe,onSendMessage:Le,onStopMessage:Nt,onRetryMessage:Et,submitComposerMessage:Vt}}function uv(e){return function(n){return dv({...n,chatPrefix:e})}}function pv(e){const{state:t,setState:n,operatorState:a,setOperatorState:s,setBusy:o,setFeedback:i,sendChatMessage:u=Gl}=e,{t:c}=z(),d=p.useCallback(async(m,v)=>{if(a.snapshot){o(Wp(m,v));try{const C=await Oh({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(Ht(C,c(l.chatGovernanceErrorUpdateApproval),c))}finally{o(Oe())}}},[a.snapshot,o,i,s,c]),h=p.useCallback(async m=>{if(t.status!=="ready")return;const v=m.channelId;if(v){o(Up(m.choiceResponse.sourceMessageId,m.choiceResponse.status));try{const C=await u(v,{body:m.body,senderName:t.payload.ownerDisplayName,choiceResponse:m.choiceResponse});p.startTransition(()=>{n({status:"ready",payload:C.appShell}),i("")})}catch(C){i(Ht(C,c(l.chatGovernanceErrorSubmitChoiceResponse),c))}finally{o(Oe())}}},[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(Kp(m.action,v));try{const C=await _h({...m,actorId:a.snapshot.core.ownerProfile.actorId});p.startTransition(()=>{s({status:"ready",snapshot:C,message:""}),i("")})}catch(C){i(Ht(C,c(l.chatGovernanceErrorRecordOperatorAction),c))}finally{o(Oe())}},[a.snapshot,o,i,s,c]);return{onApprovalDecision:d,onChoiceSubmit:h,onOperatorAction:f}}function hv(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 fv(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 u=a.get(i.id);return u?(s.add(i.id),[u]):i.memberChannelIds.includes(n)?[hv(i,n)]:[]});for(const i of t.parallelChatGroups)s.has(i.id)||o.push(i);return Jc(o,e,[n])}function mv(e,t){return e&&bC(e,t.selectedChannel)}function gv(e,t){return e.chat.selectedChannelId===t.selectedChannelId&&t.selectedChannel.id===t.selectedChannelId}function id(e,t){if(!gv(e,t))return e;const n=mv(e.chat.channels,t);return{...e,chat:{...e.chat,selectedChannelId:t.selectedChannelId,selectedChannel:t.selectedChannel,...n?{channels:n}:{},parallelChatGroups:fv(e.chat.parallelChatGroups,t)}}}function Cv(e,t){return t.state?id(e,t.state):e}function vv(e,t){return e.status!=="ready"?e:{status:"ready",payload:id(e.payload,t)}}function Iv(e,t){return vv(e,t.state)}function Sv(e,t){return e.status!=="ready"?e:{status:"ready",payload:Cv(e.payload,t.patch)}}function yv(e,t){return e?.id??t?.id??null}function bv(e,t){return e??t}function xv({folderBrowsePath:e,folderBrowseCurrentPath:t,folderBrowseParentPath:n,folderBrowseEntries:a,folderBrowseLoading:s,folderBrowseError:o,onPathChange:i,browseFolder:u,selectCurrentFolder:c}){return{folderBrowsePath:e,folderBrowseCurrentPath:t??"",folderBrowseParentPath:n??"",folderBrowseEntries:[...a],folderBrowseLoading:s,folderBrowseError:o,onPathChange:i,onBrowse:d=>{u(d)},onSelect:c}}const wv="screenshot_permission_denied",kv="Screen Recording permission is required to capture a screenshot. Grant Cats screen access in macOS System Settings, then restart Cats.",Pv={[kv]: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},ta=ea("en"),Av=8e3,Rv=8e3,Nv=10*1024*1024;let tl="",Hs=0;function ld(){return typeof navigator<"u"&&typeof navigator.mediaDevices?.getDisplayMedia=="function"&&typeof document<"u"}function Tv(){const e=bo();return e?.screenshotRegionCaptureAvailable===!0&&typeof e.captureScreenshotRegion=="function"}function cd(){return Tv()?"desktop_region":ld()?"web_picker":"unavailable"}function Ko(e,t=ta){return t(e==="desktop_region"?l.sharedScreenshotCaptureTooltipDesktopRegion:e==="web_picker"?l.sharedScreenshotCaptureTooltipWebPicker:l.sharedScreenshotCaptureTooltipUnavailable)}function jv(e){return e!=="unavailable"}function Lv(e,t=ta){return e instanceof Error?e.message:t(l.sharedScreenshotCaptureFailed)}class Mv extends Error{code=wv;constructor(t=ta(l.sharedScreenshotCapturePermissionRequired)){super(t),this.name="ScreenshotPermissionDeniedError"}}function Ev(e,t=ta){return{surface:"toast",message:Lv(e,t)}}function Ia(e,t){return String(e).padStart(t,"0")}function nl(e,t){const n=e.trim(),a=Pv[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 dd(e=new Date){const t=[e.getFullYear(),Ia(e.getMonth()+1,2),Ia(e.getDate(),2),"-",Ia(e.getHours(),2),Ia(e.getMinutes(),2),Ia(e.getSeconds(),2)].join("");return Hs=t===tl?Hs+1:1,tl=t,`cats-screenshot-${t}-${Ia(Hs,3)}.png`}async function Dv(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 Bv(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,Av/n,Rv/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 al(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 Ov(e,t){let n=e,a=await al(n,t);for(;a.size>Nv&&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 al(n,t)}return a}function rl(e){if(e)for(const t of e.getTracks())t.stop()}async function _v(e=ta){if(!ld())throw new Error(Ko("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 Dv(a,e),await a.play();const s=Bv(a,e);rl(n),n=null;const o=await Ov(s,e);return new File([o],dd(),{type:"image/png"})}catch(a){if(a instanceof DOMException&&a.name==="NotAllowedError")return null;throw a}finally{rl(n)}}function Fv(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 Mv(e.message?nl(e.message,t):t(l.sharedScreenshotCapturePermissionRequired)):e.message?new Error(nl(e.message,t)):e.outcome==="platform_unsupported"?new Error(t(l.sharedScreenshotCaptureRegionUnsupported)):new Error(t(l.sharedScreenshotCaptureFailed))}function Wv(e){const t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}async function Uv(e=ta){const t=bo()?.captureScreenshotRegion;if(!t)throw new Error(Ko("unavailable",e));const n=await t();if(n.outcome!=="ok"){const a=Fv(n,e);if(!a)return null;throw a}return new File([Wv(n.png)],n.filename||dd(),{type:n.mime})}async function sl(e=cd(),t=ta){if(e==="desktop_region")return await Uv(t);if(e==="web_picker")return await _v(t);throw new Error(Ko(e,t))}function Kv(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 sw({productName:e,shellSurface:t,supportsStructuredDraftModes:n=!1,BootShell:a,AppRoutesComponent:s,renderSidebar:o}){const i=ci(t),u=uv(i);return function(){const d=Na(),{t:h}=z(),{location:f,settingsMode:m,routeChannelId:v,routeMyCatId:C,showingNewChatDraft:I,newChatPreset:y,draftDefaultRecipientCatId:g,showingMyCatDirectLane:x}=og(i),S=n?y:"default",k=S==="parallel",w=I&&!x&&!!g,P=!g,[j,N]=p.useState(t),D=p.useMemo(()=>[S,x?"direct":"public",g??"none"].join(":"),[g,S,x]),T=p.useMemo(()=>zg(f.pathname,f.search),[f.pathname,f.search]),A=p.useMemo(()=>Xg({surface:t,path:T}),[T,t]),b=p.useMemo(()=>{if(!A)return null;const E=Gc({surface:t,path:T});if(!E?.optimisticState?.pendingExecution)return null;const{entityKind:H,entityId:Z}=E.destination;if(H==="channel"){const ie=E.optimisticState.selectedChannelId??A.chat.selectedChannelId??Z??null;return ie?{kind:"channel",channelId:ie}:null}if(H==="parallel-group"){const ie=Z,fe=A.chat.parallelChatGroups.find(je=>je.id===ie);if(!fe||fe.memberChannelIds.length===0)return null;const Ce=E.optimisticState.selectedChannelId??A.chat.selectedChannelId??fe.memberChannelIds[0];return{kind:"parallel",groupId:ie,activeChannelId:Ce,channelIds:fe.memberChannelIds}}return null},[T,A,t]),{state:R,setState:L,composerDraft:O,setComposerDraft:Y,catForm:$,setCatForm:M,busy:F,setBusy:J,feedback:me,setFeedback:K,addCatTab:B,setAddCatTab:ae,greeting:be,draftCwd:W,setDraftCwd:q,draftFiles:_e,setDraftFiles:le,channelFiles:xe,setChannelFiles:Ae}=sg({initialState:A?{status:"ready",payload:A}:{status:"loading"},createEmptyCatForm:Ns,pickGreeting:()=>Gp(h)}),X=p.useRef({kind:"lead"}),re=p.useRef(null),G=p.useCallback(E=>{const H=X.current;if(H.kind==="parallel-branch"){re.current?.(H.index,E);return}q(E)},[q]),{draftCatIds:pe,setDraftCatIds:Ie,draftHighlightedCatId:Qe,setDraftHighlightedCatId:Nt,draftCatExecutionTargetOverrides:Vt,setDraftCatExecutionTargetOverrides:Le,onToggleDraftCat:Wt,onDraftCatExecutionTargetOverride:Et,resetDraftCats:ct}=ag(),Te=R.status==="ready"?R.payload.chat.capabilities.maxChatParticipants??Number.POSITIVE_INFINITY:Number.POSITIVE_INFINITY,se=R.status==="ready"?R.payload.chat.capabilities.maxAudienceParticipants??Number.POSITIVE_INFINITY:Number.POSITIVE_INFINITY,ce=R.status==="ready"?R.payload.chat.capabilities.maxParallelChats??3:3,[Re,Me]=p.useState("sequential"),[dt,ot]=p.useState(()=>So()),[tt,Se]=p.useState(null),[Fe,it]=p.useState("sequential"),[zt,Yt]=p.useState(null),[St,Tt]=p.useState("all_members"),{draftTemporaryParticipants:ge,setDraftTemporaryParticipants:ke,draftParticipants:Ne,onAddDraftTemporaryParticipant:Dt,onRemoveDraftTemporaryParticipant:Ye,onUpdateDraftTemporaryParticipant:V}=rg({state:R,draftDefaultRecipientCatId:g,draftCatIds:pe,maxDraftGroupParticipants:Te}),{dialog:Ke,confirm:nt,handleClose:xt}=$p(),{toasts:gt,showToast:Jt}=Vl(),{notifications:Ut,dismiss:at}=vf(),jt=cd(),Pe=!jv(jt),rt=p.useCallback(E=>{const H=Ev(E,h);Jt(H.message)},[Jt,h]),na=p.useCallback(()=>{sl(jt,h).then(H=>{H&&le(Z=>[...Z,H])}).catch(rt)},[jt,le,rt,h]),jn=p.useCallback(()=>{sl(jt,h).then(H=>{H&&Ae(Z=>[...Z,H])}).catch(rt)},[jt,Ae,rt,h]),sn=Dg(L),{refreshAppShell:In}=RC({state:R,setState:L,enabled:R.status==="ready"}),[Ee,We]=p.useState(!1),yt=p.useRef(C);p.useEffect(()=>{yt.current!==C&&(yt.current=C,We(!1))},[C]);const Bt=t==="chat"&&Ee&&C&&R.status==="ready"?R.payload.chat.cats.find(E=>E.id===C)??null:null,aa=p.useCallback(()=>{We(E=>!E)},[]),ra=p.useCallback(E=>{const H=R.status==="ready"?R.payload.chat.channels.find(Z=>Z.channelKind==="direct_message"&&Z.defaultRecipientCatId===E):null;H&&Hp(H.id).then(In)},[In,R]),Ln=p.useCallback(E=>{const H=R.status==="ready"?R.payload.chat.channels.find(Z=>Z.channelKind==="direct_message"&&Z.defaultRecipientCatId===E):null;H&&fetch(`/api/channels/${encodeURIComponent(H.id)}/deactivate`,{method:"POST",headers:{"content-type":"application/json"}}).catch(()=>{}).then(In)},[In,R]),Xt=p.useCallback(async(E,H)=>{try{const Z=await Rs(E,{avatarUrl:H});sn(Z)}catch{}},[sn]),Sn=p.useCallback(E=>{K(Ht(E,h(l.sharedExecutionTargetSaveDirectLaneError),h))},[K,h]),Kt=Tg({updateCatProfile:Rs,publishReadyPayload:sn,onError:Sn}),Ma=p.useCallback((E,H)=>{Et(E,H),Kt(E,H).then(Z=>{Le(ie=>{if(!ie.has(E)||Z&&ie.get(E)!==H)return ie;const fe=new Map(ie);return fe.delete(E),fe})})},[Kt,Et,Le]),{accountMenuOpen:wt,setAccountMenuOpen:kt,sidebarOpen:on,overflowMenuOpenId:sa,setOverflowMenuOpenId:Mn,plusMenuOpen:oa,setPlusMenuOpen:$t,addCatOpen:ln,setAddCatOpen:yn,channelPlusMenuOpen:bn,setChannelPlusMenuOpen:ut,accountMenuRef:Ea,plusMenuRef:oe,addCatPanelRef:pt,fileInputRef:Pt,channelPlusMenuRef:Qt,channelFileInputRef:En,autoResize:cn,onToggleSidebar:Da,onCollapsedSidebarClick:Dn}=Rf(),{browseFolder:Ba,folderBrowseCurrentPath:Zt,folderBrowseEntries:dn,folderBrowseError:Oa,folderBrowseLoading:Bn,folderBrowseParentPath:xn,folderBrowsePath:On,openFolderBrowser:Ot,selectCurrentFolder:_n,setFolderBrowsePath:un}=jf({onSelectPath:G,surface:t,directLaneCatId:C,initialPreferences:R.status==="ready"?R.payload.chat.folderBrowsePreferences:void 0}),ia=p.useCallback(async E=>{X.current={kind:"lead"},await Ot(E)},[Ot]),{toggleAddCatPanel:la,toggleChannelPlusMenu:pn,openChannelFilePicker:ca,captureAndAttachChannelScreenshot:_a,toggleDraftPlusMenu:Fa,openDraftFilePicker:Wa,captureAndAttachDraftScreenshot:hn,openDraftFolderPicker:Fn,openDraftAddCatPanel:Ua,changeDraftDefaultRecipient:lt}=Bg({addCatOpen:ln,channelPlusMenuOpen:bn,plusMenuOpen:oa,draftCwd:W,draftDefaultRecipientCatId:g,navigate:d,chatPrefix:i,emptyCatForm:Ns,setAddCatOpen:yn,setAddCatTab:ae,setFeedback:K,setCatForm:M,setPlusMenuOpen:$t,setChannelPlusMenuOpen:ut,channelFileInputRef:En,fileInputRef:Pt,openFolderBrowser:ia,onDraftScreenshotCapture:na,onChannelScreenshotCapture:jn}),Ka=p.useCallback(async E=>{const H=R.status==="ready"?R.payload.chat.cats.find(ie=>ie.id===E)?.name??h(l.sharedSettingsCatsFallbackCatName):h(l.sharedSettingsCatsFallbackCatName);if(await nt({title:h(l.sharedSettingsCatsArchiveConfirmTitle),message:h(l.sharedSettingsCatsArchiveWithTelegramConfirmMessage,{catName:H}),confirmLabel:h(l.sharedSettingsCatsArchiveLabel)})){J(Sa("archive",E));try{const ie=await Rs(E,{archive:!0});L({status:"ready",payload:ie})}catch(ie){K(Ul(ie,h(l.sharedSettingsCatsArchiveError),h))}finally{J(Oe())}}},[nt,R,h]),{readyPayload:st,readyChat:$a,readySelectedChannel:da,selectedChannelId:Ha,selectedChannelViewId:qa,selectedChannelEntryLifecycle:Ga,routeChannelExists:Va,routeChannelTitle:za,routeDirectLaneSummary:ua,selectedChannel:Je,selectedDirectLane:Wn,operatorRefreshKey:U}=xf({state:R,routeChannelId:v,draftDefaultRecipientCatId:g,showingMyCatDirectLane:x}),{operatorState:te,setOperatorState:_t}=Ng(st,U),we=st?qp(st.chat.advancedDraftControls,t):!1,{draftExecutionTarget:Q,setDraftExecutionTarget:Ve,defaultChannelExecutionTarget:$e,setDefaultChannelExecutionTarget:At}=Ig({state:R,readyChat:$a,readySelectedChannel:da,setState:L,setFeedback:K,updateNewChatDefaultsPreference:Vp,updateChannelPendingExecutionTarget:zp}),Un=x?"direct":n&&(S==="group"||w||Ne.participantCatIds.length>0||ge.length>0)?"group":"default",{draftParallelChatTargets:Ue,resetDraftParallelChatTargets:wn,onDraftParallelChatTargetChange:pa,onAddDraftParallelChatTarget:ha,onRemoveDraftParallelChatTarget:fa,onSetDraftParallelBranchAudienceKeys:Ze,onSetDraftParallelBranchCwd:kn,onSetDraftParallelBranchRuntimeSessionPolicy:Kn,onToggleDraftParallelBranchWorkflowShape:$n}=wg({draftExecutionTarget:Q,maxParallelChats:ce,seedCompareTarget:k});p.useEffect(()=>{re.current=kn},[kn]);const de=p.useCallback(E=>{X.current={kind:"parallel-branch",index:E};const H=Ue[E]?.cwd??W;Ot(H),$t(!1)},[W,Ue,Ot,$t]),Be=Ue.length>1,ht=p.useMemo(()=>Ue.map(E=>E.audienceKeys??[]),[Ue]),Hn=p.useMemo(()=>Ue.map(E=>E.workflowShape??"sequential"),[Ue]),Ft=p.useCallback(()=>zh(Q,Te),[Q.instance,Q.model,Q.modelSelection,Q.provider,Te]),Ct=p.useMemo(()=>[...Ne.participantCatIds.map(E=>`cat:${E}`),...ge.map(E=>`temp:${E.participantId}`)],[Ne.participantCatIds,ge]),Ya=p.useCallback((E,H)=>{const Z=E.filter((ie,fe,Ce)=>Ce.indexOf(ie)===fe);return Z.includes(H)||Number.isFinite(se)&&Z.length>=se?Z:[...Z,H]},[se]),ma=p.useCallback(()=>{const E=ht[0];return E&&E.length>0?[...E]:tt&&tt.length>0?[...tt]:Number.isFinite(se)?Ct.slice(0,se):[...Ct]},[tt,ht,Ct,se]),yr=p.useCallback(()=>{if(!n||R.status!=="ready")return;const E=Ne.participantCatIds;if(E.length+ge.length>=Te)return;const H=E.map(Ce=>R.payload.chat.cats.find(je=>je.id===Ce)?.name??"").filter(Ce=>Ce.trim().length>0),Z=()=>globalThis.crypto?.randomUUID?.()??`participant-${Date.now()}`,ie=ge.length===0&&E.length===0?Pn({provider:Q.provider,instance:Q.instance,model:Q.model,modelSelection:Q.modelSelection,takenNames:[...H,...ge.map(Ce=>Ce.name)],randomUUID:Z}):Ms({baseProvider:Q.provider,existingParticipants:ge,takenNames:[...H,...ge.map(Ce=>Ce.name)],randomUUID:Z}),fe=ie.participantId;ke(Ce=>E.length+Ce.length>=Te||Ce.some(je=>je.participantId===fe)?Ce:[...Ce,ie]),Se(Ce=>{const Xe=[...E.map(mt=>`cat:${mt}`),...ge.map(mt=>`temp:${mt.participantId}`),`temp:${fe}`],He=`temp:${fe}`,bt=(Ce??Xe).filter((mt,er,tr)=>tr.indexOf(mt)===er&&Xe.includes(mt));return bt.includes(He)||Number.isFinite(se)&&bt.length>=se?bt:[...bt,He]})},[Q.instance,Q.model,Q.modelSelection,Q.provider,Ne.participantCatIds,ge,se,Te,ke,R,n]),ga=p.useCallback(E=>{if(!n){Wt(E);return}const H=Ne.participantCatIds.includes(E);if(!H&&Ne.participantCatIds.length+ge.length>=Te)return;if(Wt(E),!H){const fe=`cat:${E}`;Se(Ce=>{const Xe=(Ce??Ct).filter((He,mn,bt)=>bt.indexOf(He)===mn);return Number.isFinite(se)&&Xe.length>=se?Xe:[...Xe,fe]});return}const Z=`cat:${E}`,ie=Ct.filter(fe=>fe!==Z);Se(fe=>Ar({draftAudienceKeys:fe,previousParticipantKeys:Ct,nextParticipantKeys:ie,removedParticipantKey:Z,maxAudienceParticipants:se})),Ue.length>=2&&ht.forEach((fe,Ce)=>{fe.includes(Z)&&Ze(Ce,Ar({draftAudienceKeys:fe,previousParticipantKeys:Ct,nextParticipantKeys:ie,removedParticipantKey:Z,maxAudienceParticipants:se})??[])})},[Ct,Ne.participantCatIds,ht,Ue.length,ge.length,se,Te,Wt,Ze,n]),bs=p.useCallback(E=>{if(!n){Ye(E);return}const H=`temp:${E}`,Z=Ct.filter(ie=>ie!==H);Ye(E),Se(ie=>Ar({draftAudienceKeys:ie,previousParticipantKeys:Ct,nextParticipantKeys:Z,removedParticipantKey:H,maxAudienceParticipants:se})),Ue.length>=2&&ht.forEach((ie,fe)=>{ie.includes(H)&&Ze(fe,Ar({draftAudienceKeys:ie,previousParticipantKeys:Ct,nextParticipantKeys:Z,removedParticipantKey:H,maxAudienceParticipants:se})??[])})},[Ct,ht,Ue.length,se,Ye,Ze,n]),_=p.useCallback(E=>{if(Dt(E),!n)return;I&&S==="group"&&Ne.participantCatIds.length===0&&ge.length===0&&E.provider.trim()&&Ve({provider:E.provider.trim(),model:E.model?.trim()||null,instance:E.instance?.trim()||null,modelSelection:E.modelSelection??null});const Z=`temp:${E.participantId??""}`;!Z||Z==="temp:"||Se(ie=>{const Ce=(ie??Ct).filter((je,Xe,He)=>He.indexOf(je)===Xe);return Number.isFinite(se)&&Ce.length>=se?Ce:[...Ce,Z]})},[Ct,Ne.participantCatIds.length,ge.length,S,se,Dt,Ve,I,n]),ne=p.useCallback((E=null)=>{if(!n||R.status!=="ready")return;const H=E!==null&&Ue.length>=2;if(H){const je=ht[E]??[];if(Number.isFinite(Te)&&je.length>=Te)return}else if(Ne.participantCatIds.length+ge.length>=Te)return;const ie=[...Ne.participantCatIds.map(je=>R.payload.chat.cats.find(Xe=>Xe.id===je)?.name??"").filter(je=>je.trim().length>0),...ge.map(je=>je.name)],fe=ge.length===0&&Ne.participantCatIds.length===0?Pn({provider:Q.provider,instance:Q.instance,model:Q.model,modelSelection:Q.modelSelection,takenNames:ie,randomUUID:()=>globalThis.crypto?.randomUUID?.()??`participant-${Date.now()}`}):Ms({baseProvider:Q.provider,existingParticipants:ge,takenNames:ie,randomUUID:()=>globalThis.crypto?.randomUUID?.()??`participant-${Date.now()}`}),Ce=`temp:${fe.participantId}`;if(ke(je=>[...je,fe]),H){const Xe=(ht[E]??[]).filter((mn,bt,mt)=>mt.indexOf(mn)===bt),He=Xe.includes(Ce)?Xe:[...Xe,Ce];Ze(E,He);return}Se(je=>{const He=[...Ne.participantCatIds.map(mt=>`cat:${mt}`),...ge.map(mt=>`temp:${mt.participantId}`)],bt=(je??He).filter((mt,er,tr)=>tr.indexOf(mt)===er&&He.includes(mt));return Number.isFinite(se)&&bt.length>=se?bt:[...bt,Ce]})},[Ya,Q.instance,Q.model,Q.modelSelection,Q.provider,ht,Ue.length,Ne.participantCatIds,ge,se,Te,Ze,Se,ke,R,n]),ye=p.useCallback(E=>{if(!n||R.status!=="ready")return;if(Ne.participantCatIds.length===0&&ge.length===0){const Z=Ft(),ie=Z.map(fe=>`temp:${fe.participantId}`);ke(fe=>fe.length===0?Z:fe),Ze(E,ie);return}if((ht[E]??[]).length===0){const Z=Ue[E]??Q,ie=Ne.participantCatIds.map(He=>R.payload.chat.cats.find(mn=>mn.id===He)?.name??"").filter(He=>He.trim().length>0),fe=()=>globalThis.crypto?.randomUUID?.()??`participant-${Date.now()}`,Ce=Pn({provider:Z.provider,instance:Z.instance,model:Z.model,modelSelection:Z.modelSelection,takenNames:[...ie,...ge.map(He=>He.name)],randomUUID:fe}),je=[...ge,Ce],Xe=Ms({baseProvider:Z.provider,existingParticipants:je,takenNames:[...ie,...je.map(He=>He.name)],randomUUID:fe});ke(He=>[...He,Ce,Xe]),Ze(E,[`temp:${Ce.participantId}`,`temp:${Xe.participantId}`]);return}ne(E)},[Q,ht,Ue,Ne.participantCatIds,ge,ne,Ze,Ft,ke,R,n]),{onOpenChatsOverview:ft,onSelect:Lt,onRenameChannel:Ca,onDeleteChannel:br,onClearDirectLane:xr,onRenameParallelChatGroup:xs,onUngroupParallelChatGroup:ws,onDeleteParallelChatGroup:Ja,onNavigateSettings:fn,onNavigateRuntime:ks,onCreateNewCat:Xa,onDirectChatCat:nu,onResetSetup:au,onStartNewChat:ru,onStartNewGroupChat:su,onStartNewParallelChat:ou}=rC({state:R,setState:L,navigate:d,platformShellSurface:t,setBusy:J,setFeedback:K,setComposerDraft:Y,setAccountMenuOpen:kt,setAddCatOpen:yn,setPlusMenuOpen:$t,setChannelPlusMenuOpen:ut,setDraftCwd:q,setDraftCatIds:Ie,setDraftTemporaryParticipants:ke,setDraftHighlightedCatId:Nt,setDraftCatExecutionTargetOverrides:Le,setDraftSurface:N,setDraftWorkflowShape:Me,setDraftRuntimeSessionPolicy:ot,setDraftAudienceKeys:Se,resetDraftParallelChatTargets:wn,createInitialGroupParticipants:n?Ft:void 0,setDraftFiles:le,setChannelFiles:Ae,confirm:nt}),Qa=Je??Wn??null,iu=ng({channelId:Qa?.id??null,busy:F,selectedChannel:Qa,debugTraceEnabled:st?.chat.capabilities.debugLiveTrace===!0}),Xo=Qa&&st?.chat.selectedChannelId===Qa.id?Qa.id:null;zc({kind:"channel",id:Xo,enabled:R.status==="ready"&&!!Xo,onSnapshot:E=>{p.startTransition(()=>{L(H=>Iv(H,E))})},onPatch:E=>{p.startTransition(()=>{L(H=>Sv(H,E))})}}),p.useEffect(()=>{N(t)},[D,t]);const Za=Je?.messages?[...Je.messages].reverse().find(E=>E.senderKind==="user")??null:null,lu=Array.isArray(Za?.metadata?.recipientParticipantIds)?Za.metadata.recipientParticipantIds.filter(E=>typeof E=="string").join("|"):"",cu=typeof Za?.metadata?.workflowShape=="string"?Za.metadata.workflowShape:"",du=(Je?.assignedParticipants?.length?Je.assignedParticipants:Je?.assignedCats??[]).filter(E=>E.status==="active").map(E=>E.participantId).join("|"),wr=p.useMemo(()=>st&&Je?st.chat.parallelChatGroups.find(E=>E.memberChannelIds.includes(Je.id))??null:null,[st,Je]);p.useEffect(()=>{const E=ov({selectedChannel:Je,maxAudienceParticipants:se});it(E?.workflowShape??"sequential"),Yt(E?.audienceKeys??null)},[du,Za?.id,lu,cu,se,Je?.id]),p.useEffect(()=>{Tt("all_members")},[wr?.id]);const{onComposerKeyDown:Qo,onCancelPendingSend:Zo,onSendMessage:ei,onStopMessage:uu,onRetryMessage:pu}=u({state:R,setState:L,navigate:d,originSurface:j,currentPath:`${f.pathname}${f.search}`,composerDraft:O,setComposerDraft:Y,showingNewChatDraft:I,showingMyCatDirectLane:x,draftEntryKind:Un,draftDefaultRecipientCatId:g,draftCatIds:pe,draftTemporaryParticipants:ge,draftCwd:W,draftSessionPolicy:dt,draftFiles:_e,channelFiles:xe,setDraftCwd:q,setDraftCatIds:Ie,setDraftTemporaryParticipants:ke,setDraftHighlightedCatId:Nt,setDraftCatExecutionTargetOverrides:Le,setDraftRuntimeSessionPolicy:ot,setDraftFiles:le,setChannelFiles:Ae,setDraftWorkflowShape:Me,setDraftAudienceKeys:Se,draftExecutionTarget:Q,defaultChannelExecutionTarget:$e,showingParallelChatDraft:n&&k,draftParallelChatTargets:Ue,draftWorkflowShape:Re,draftAudienceKeys:tt,activeWorkflowShape:Fe,activeAudienceKeys:zt,resetDraftParallelChatTargets:wn,compareGroupId:wr?.id??null,compareSendScope:St,selectedChannel:Je,busy:F,setBusy:J,setFeedback:K,hydratePendingDispatch:b}),{onAssignExistingCat:hu,onCreateAndAssignCat:fu,onCreateAndDraftCat:mu,onRemoveAssignedCat:gu}=jC({state:R,setState:L,catForm:$,emptyCatForm:Ns,setCatForm:M,setBusy:J,setFeedback:K,setAddCatOpen:yn,setDraftCatIds:Ie}),{onApprovalDecision:Cu,onChoiceSubmit:vu,onOperatorAction:Iu}=pv({state:R,setState:L,operatorState:te,setOperatorState:_t,setBusy:J,setFeedback:K}),Su=zs(t,`Cats ${e}`,h);kg(Su,za),p.useEffect(()=>{Uf(st?.chat.capabilities.debugLiveTrace===!0)},[st?.chat.capabilities.debugLiveTrace]),Sg(I&&!g,p.useCallback(()=>{ct(),ke(E=>n?hi(S,E,Ft):[]),Me("sequential"),Se(null),wn()},[S,ct,wn,Ft,Se,ke,Me,n]),S),p.useEffect(()=>{!n||!I||S!=="group"||ke(E=>pi({participants:E,target:Q}))},[Q.instance,Q.model,Q.modelSelection,Q.provider,S,ke,I,n]),mC({state:R,setState:L,navigate:d,busy:F,surface:t,currentPath:T,chatPrefix:i,routeChannelId:v,routeChannelExists:Va,selectedChannelId:Ha,selectedChannelViewId:qa,selectedChannelEntryLifecycle:Ga,draftDefaultRecipientCatId:g,showingMyCatDirectLane:x,routeDirectLaneSummary:ua,readySelectedChannel:da,unknownRendererErrorMessage:h(l.sharedProductRendererUnknownError)});const yu=p.useCallback(E=>{Ve(E),n&&I&&S==="group"&&ke(H=>pi({participants:H,target:E}))},[S,ke,I,n]),bu=p.useCallback((E,H)=>{pa(E,H),E===0&&Ve(H)},[pa,Ve]),xu=p.useCallback(()=>{if(n){if((S==="default"||S==="parallel")&&Ne.participantCatIds.length===0&&ge.length===0){const E=hi("group",[],Ft);ke(H=>H.length===0?E:H),Be?Ze(0,E.map(H=>`temp:${H.participantId}`)):Se(null);return}if(Be){ne(0);return}yr()}},[Ne.participantCatIds.length,ge.length,S,yr,ne,Ze,Be,Ft,Se,ke,n]),wu=p.useCallback(()=>{if(!n||R.status!=="ready")return;const E=Hn[0]??Re;if(!Be){const H=ma();Ze(0,H)}ha({seedAudienceKeys:[],seedWorkflowShape:E})},[Hn,Re,Be,ha,Ze,ma,R,n]),ku=jg({resetChannelContinuity:Xp,publishReadyPayload:sn,setBusy:J,setFeedback:K}),Pu=Lg({updateChannelParticipantApi:Jp,setBusy:J,setFeedback:K,setState:L}),Au=Mg({selectedChannel:Je,selectedParallelChatGroup:wr,relayParallelChatMessage:Yp,setBusy:J,setFeedback:K,setState:L});return r.jsxs(r.Fragment,{children:[r.jsx(kf,{state:R,BootShell:a,unavailableTitle:h(l.sharedProductRendererChatUnavailableTitle),renderReady:E=>{const{surface:H,directLaneChannel:Z,activeMyCatId:ie,activeAssignedCats:fe,assignedCatIds:Ce,bossCatName:je,bossCatAvatarColor:Xe,showBossCatAvatar:He,selectableCats:mn,assignableCatCount:bt,draftCatIdSet:mt,showDirectLaneBoot:er,showAddCatPanel:tr}=wf({pathname:f.pathname,payload:E,draftDefaultRecipientCatId:g,selectedChannel:Je,selectedDirectLane:Wn,routeDirectLaneSummary:ua,showingMyCatDirectLane:x,addCatOpen:ln,showingNewChatDraft:I,draftCatIds:pe,t:h}),kr=yv(Je,Z),en=bv(Je,Z);function Ru(tn){d(ci(tn))}return r.jsx(Af,{payload:E,sidebarOpen:on,sidebar:o({payload:E,sidebarOpen:on,accountMenuOpen:wt,overflowMenuOpenId:sa,busy:F,surface:H,shellSurface:t,routeChannelId:v,accountMenuRef:Ea,onToggleSidebar:Da,onCollapsedSidebarClick:Dn,onOpenChatsOverview:ft,onStartNewChat:ru,onStartNewGroupChat:n?su:void 0,onStartNewParallelChat:n?ou:void 0,onSelect:Lt,onDeleteChannel:br,onRenameChannel:Ca,onRenameParallelChatGroup:xs,onUngroupParallelChatGroup:ws,onDeleteParallelChatGroup:Ja,onArchiveCat:Ka,onClearDirectLane:xr,onCreateNewCat:Xa,onAccountMenuToggle:()=>kt(!wt),onOverflowMenuToggle:Mn,onNavigateSettings:fn,onNavigateRuntime:ks,onSwitchProduct:Ru,activeMyCatId:ie,onDirectChatCat:nu,navigate:d,confirmDialog:nt}),settingsMode:m,busy:F,appContent:r.jsx(s,{payload:E,routeChannelId:v,selectedChannel:Je,directLaneChannel:Z,showDirectLaneBoot:er,feedback:me,busy:F,chatSurfaceProps:{operatorSnapshot:te.snapshot,operatorLoading:te.status==="loading"&&te.snapshot===null,operatorError:te.status==="error"?te.message:"",composerDraft:O,busy:F,feedback:me,greeting:be,channelFiles:xe,channelPlusMenuOpen:bn,channelPlusMenuRef:Qt,channelFileInputRef:En,activeAssignedCats:fe,bossCatName:je,bossCatAvatarColor:Xe,showBossCatAvatar:He,onComposerChange:Y,onComposerKeyDown:Qo,onSendMessage:ei,onCancelPendingSend:Zo,onStopMessage:uu,onRetryMessage:pu,onToggleChannelPlusMenu:pn,onChannelFileSelect:ca,onTakeScreenshot:_a,screenshotCaptureDisabled:Pe,onChannelFilesChange:Ae,onApprovalDecision:Cu,onChoiceSubmit:vu,onStartFresh:kr&&en&&An(en)?()=>ku(kr):void 0,onRelayMessage:Au,onUpdateChannelParticipant:kr?(tn,Nu)=>Pu(kr,tn,Nu):void 0,onOperatorAction:Iu,autoResize:cn,selectedExecutionTarget:en&&An(en)?$e:void 0,onExecutionTargetChange:en&&An(en)?At:void 0,onDirectLaneExecutionTargetChange:Kt,activeWorkflowShape:Fe,onToggleActiveWorkflowShape:en&&Zs(en)?()=>it(tn=>tn==="concurrent"?"sequential":"concurrent"):void 0,activeAudienceKeys:zt,onSetActiveAudienceKeys:en&&Zs(en)?Yt:void 0,onSelect:Lt,liveIndicator:iu,compareGroup:wr,compareSendScope:St,onCompareSendScopeChange:Tt},draftSurfaceProps:{draftSurface:j,onDraftSurfaceChange:N,composerDraft:O,busy:F,greeting:be,draftFiles:_e,draftCwd:W,draftCatIds:pe,draftTemporaryParticipants:ge,plusMenuOpen:oa,plusMenuRef:oe,fileInputRef:Pt,bossCatName:je,bossCatAvatarColor:Xe,onComposerChange:Y,onComposerKeyDown:Qo,onSendMessage:ei,onCancelPendingSend:Zo,onTogglePlusMenu:Fa,onFileSelect:Wa,onTakeScreenshot:hn,screenshotCaptureDisabled:Pe,onPickFolder:Fn,onDraftFilesChange:le,onDraftCwdClear:()=>q(null),onToggleDraftCat:ga,onAddDraftTemporaryParticipant:_,onQuickAddDraftTemporaryParticipant:n?xu:void 0,onRemoveDraftTemporaryParticipant:bs,onUpdateDraftTemporaryParticipant:V,autoResize:cn,draftDefaultRecipientCatId:g,entryPreset:S,selectedExecutionTarget:Q,onExecutionTargetChange:yu,draftHighlightedCatId:Qe,onHighlightDraftCat:Nt,draftCatExecutionTargetOverrides:Vt,onDraftCatExecutionTargetOverride:Et,onDirectLaneExecutionTargetChange:Ma,parallelTargets:n&&P&&Be?Ue:void 0,onParallelTargetChange:n&&(k||Be)?bu:void 0,onAddParallelTarget:n&&P&&(we||Be)?wu:void 0,onRemoveParallelTarget:n&&(k||Be)?fa:void 0,parallelBranchActions:{onPickFolder:we&&n&&P&&Be?de:void 0,onSetAudienceKeys:n&&P&&Be?Ze:void 0,onSetCwd:n&&P&&Be?kn:void 0,onSetRuntimeSessionPolicy:we&&n&&P&&Be?Kn:void 0,onToggleWorkflowShape:n&&P&&Be?$n:void 0,onQuickAddTemporaryParticipant:we&&n&&P&&Be?ye:void 0},builderControls:Kv({advancedDraftControlsEnabled:we,entryPreset:S,showStructuredDraftControls:n&&P,hasVisibleParallelDraftTargets:Be}),draftWorkflowShape:Re,draftRuntimeSessionPolicy:dt,onDraftRuntimeSessionPolicyChange:ot,onToggleDraftWorkflowShape:n?()=>Me(tn=>tn==="concurrent"?"sequential":"concurrent"):void 0,draftAudienceKeys:tt,onSetAudienceKeys:n?Se:void 0,onCatAvatarSave:Xt},addCatOpen:tr,onToggleAddCat:la,addCatPanelProps:{panelRef:pt,selectableCats:mn,assignableCatCount:bt,addCatTab:B,showingNewChatDraft:I&&!g,draftCatIdSet:mt,assignedCatIds:Ce,catForm:$,onClose:()=>yn(!1),onTabChange:ae,onAssignExistingCat:hu,onRemoveAssignedCat:gu,onToggleDraftCat:ga,onCatFormChange:M,onCreateCat:tn=>{if(I&&!g){mu(tn);return}fu(tn)}},folderBrowserProps:xv({folderBrowsePath:On,folderBrowseCurrentPath:Zt,folderBrowseParentPath:xn,folderBrowseEntries:dn,folderBrowseLoading:Bn,folderBrowseError:Oa,onPathChange:un,browseFolder:Ba,selectCurrentFolder:_n}),onOpenDraftAddCat:Ua,onChangeDraftDefaultRecipient:lt,companionMode:Ee,companionCat:Bt,onToggleCompanionMode:aa,onCompanionWake:ra,onCompanionSleep:Ln,onCatAvatarSave:Xt}),confirmDialog:Ke,onPayloadUpdate:sn,onFeedback:K,onBusy:J,onResetSetup:au,onConfirmClose:xt})}}),r.jsx(Sf,{notifications:Ut,onDismiss:at}),r.jsx(xo,{toasts:gt})]})}}function Jn({provider:e,instance:t,model:n,modelSelection:a,onTargetChange:s}){return r.jsx(Qp,{provider:e,instance:t,model:n,modelSelection:a,onTargetChange:s,fetchProviderRegistry:Kr,fetchProviderModels:$r,fetchAdvancedProviderModels:Hr})}function $v({panelRef:e,selectableCats:t,assignableCatCount:n,addCatTab:a,busy:s,feedback:o,showingNewChatDraft:i,draftCatIdSet:u,assignedCatIds:c,catForm:d,onClose:h,onTabChange:f,onAssignExistingCat:m,onRemoveAssignedCat:v,onToggleDraftCat:C,onCatFormChange:I,onCreateCat:y,ProviderModelFieldsComponent:g}){const{t:x}=z();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(S=>{const k=Ys(S.mcpProfile);return r.jsxs("div",{className:"addCatItem",children:[r.jsxs("div",{children:[r.jsx("strong",{children:S.name}),r.jsx("p",{children:Zp(S)}),r.jsx("p",{children:k?x(k):S.mcpProfile})]}),(()=>{const w=i?u.has(S.id):c.has(S.id),P=Pr(s,"assign",S.id),j=Pr(s,"remove",S.id);return r.jsx("button",{className:w?"addCatAssignButton addCatRemoveButton":"addCatAssignButton",type:"button",disabled:P||j,onClick:()=>{if(i){C(S.id);return}if(w){v(S);return}m(S)},children:x(P?"sharedAddCatPanelAdding":j?"sharedAddCatPanelRemoving":w?"sharedAddCatPanelRemove":"sharedAddCatPanelAdd")})})()]},S.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:S=>y(S),children:[r.jsxs("label",{className:"fieldLabel",children:[r.jsx("span",{children:x("sharedAddCatPanelNameLabel")}),r.jsx("input",{className:"textInput",value:d.name,onChange:S=>I({...d,name:S.target.value}),placeholder:x("sharedAddCatPanelNamePlaceholder")})]}),r.jsx(g,{provider:d.provider,instance:d.instance,model:d.model,modelSelection:d.modelSelection,onTargetChange:S=>I({...d,provider:S.provider,instance:S.instance,model:S.model,modelSelection:S.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:eh.map(S=>r.jsx("button",{type:"button",className:(d.mcpProfile||$l)===S.value?"draftLeadPill draftLeadPillActive":"draftLeadPill",onClick:()=>I({...d,mcpProfile:S.value}),children:x(S.label)},S.value))})]}),r.jsx("button",{className:"primaryButton",disabled:!d.name.trim()||!d.provider.trim()||!d.model.trim(),type:"submit",children:Pr(s,"create")||Pr(s,"create-assign")?x("sharedAddCatPanelSaving"):x(i?"sharedAddCatPanelCreateAndAdd":"sharedAddCatPanelCreateAndAddToChat")})]})})]})}function ow({...e}){return r.jsx($v,{...e,ProviderModelFieldsComponent:Jn})}const Hv=768;function qv(e,t){const n=t<Hv,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 ol=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"]),il=new Set(["chat_default","task_override","room_tightening","approved_exception"]),ll=new Set(["normal","warning","blocked"]),cl=new Set(["runtime_usage","rate_limit_incident","guardrail_state"]),ud=new Set(["retry","acknowledge"]),Gv=new Set(["prepare_artifact","create_commit","push_branch","open_pull_request","wait_for_checks","publish_preview"]),Vv=new Set(["queued","running","blocked","completed","failed","cancelled"]),zv=new Set(["not_requested","pending","approved","rejected"]),Yv=new Set(["approve","reroute","reject"]),Jv=["pending","running","completed","failed","blocked","cancelled","waiting_for_converge"];function qe(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ve(e){return typeof e=="string"&&e.trim().length>0?e:null}function vt(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function Cr(e){return e===!0}function Zr(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.trim().length>0):[]}function Mt(e,t){const n=ve(e);return n&&t.has(n)?n:null}function pd(e){if(!e)return null;const t=Mt(e.operatorLastAction,ud),n=ve(e.operatorLastActionAt),a=ve(e.operatorLastActionBy),s=ve(e.operatorLastActionNotes);return t||n||a||s?{kind:t,at:n,by:a,notes:s}:null}function Xv(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=ve(n.status);a&&Jv.includes(a)&&(t[a]+=1)}return t}function Qv(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 Zv(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:Xv(e.branchStates)}}function eI(e){return{requestedActions:Qv(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 tI(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:pd(e.operatorMetadata??null)}}function $o(e){const t=qe(e?.effectiveDeliveryPolicy);if(t){const s=Mt(t.mode,ol),o=Mt(t.source,il);if(s&&o)return{mode:s,gates:Zr(t.gates).filter(i=>io.has(i)),source:o,rationale:ve(t.rationale)}}const n=Mt(e?.effectiveDeliveryMode,ol),a=Mt(e?.effectiveDeliverySource,il);return!n||!a?null:{mode:n,gates:Zr(e?.effectiveDeliveryGates).filter(s=>io.has(s)),source:a,rationale:ve(e?.effectiveDeliveryRationale)}}function Ho(e){const t=qe(e?.effectiveBudgetPolicy);if(t){const a=Mt(t.alertLevel,ll);if(a)return{alertLevel:a,source:Mt(t.source,cl),rationale:ve(t.rationale)}}const n=Mt(e?.effectiveBudgetAlertLevel,ll);return n?{alertLevel:n,source:Mt(e?.effectiveBudgetAlertSource,cl),rationale:ve(e?.effectiveBudgetRationale)}:null}function hd(e){const t=qe(e?.runtimeDeliveryManifest);return t?{requestedActions:Zr(t.requestedActions).filter(n=>Gv.has(n)),gates:Zr(t.gates).filter(n=>io.has(n)),context:{channelId:ve(qe(t.context)?.channelId),containerId:ve(qe(t.context)?.containerId),conversationId:ve(qe(t.context)?.conversationId),taskId:ve(qe(t.context)?.taskId),roomMode:ve(qe(t.context)?.roomMode),transport:ve(qe(t.context)?.transport),workflowStageId:ve(qe(t.context)?.workflowStageId),workflowShape:ve(qe(t.context)?.workflowShape)},strict:Cr(t.strict)}:null}function nI(e,t=null){const n=qe(e?.workflowSummary);if(n)return{runStatus:Mt(n.runStatus,Vv)??t,stageId:ve(n.stageId),shape:ve(n.shape),reviewRequired:Cr(n.reviewRequired),lastCheckpointId:ve(n.lastCheckpointId),convergeTargetId:ve(n.convergeTargetId),continuationCount:vt(n.continuationCount),dispatchCount:vt(n.dispatchCount),targetCount:vt(n.targetCount),branchStatusCounts:{pending:vt(qe(n.branchStatusCounts)?.pending)??0,running:vt(qe(n.branchStatusCounts)?.running)??0,completed:vt(qe(n.branchStatusCounts)?.completed)??0,failed:vt(qe(n.branchStatusCounts)?.failed)??0,blocked:vt(qe(n.branchStatusCounts)?.blocked)??0,cancelled:vt(qe(n.branchStatusCounts)?.cancelled)??0,waiting_for_converge:vt(qe(n.branchStatusCounts)?.waiting_for_converge)??0}};if(!(ve(e?.workflowStageId)||ve(e?.workflowShape)||vt(e?.dispatchCount)!==null||vt(e?.continuationCount)!==null||vt(e?.targetCount)!==null)&&!t)return null;const s=Array.isArray(e?.branchStates)?e?.branchStates.map(o=>qe(o)??{}):[];return Zv({runStatus:t,stageId:ve(e?.workflowStageId),shape:ve(e?.workflowShape),reviewRequired:Cr(e?.workflowReviewRequired),lastCheckpointId:ve(e?.workflowLastCheckpointId),convergeTargetId:ve(e?.workflowConvergeTargetId),continuationCount:vt(e?.continuationCount),dispatchCount:vt(e?.dispatchCount),targetCount:vt(e?.targetCount),branchStates:s})}function aI(e){const t=qe(e?.governanceSummary);if(!t)return null;const n=qe(t.approval);return{delivery:$o({effectiveDeliveryPolicy:t.delivery}),budget:Ho({effectiveBudgetPolicy:t.budget}),runtimeDeliveryManifest:hd({runtimeDeliveryManifest:t.runtimeDeliveryManifest}),approval:{status:Mt(n?.status,zv),requiresOwnerDecision:Cr(n?.requiresOwnerDecision),pending:Cr(n?.pending),latestDecisionAction:Mt(n?.latestDecisionAction,Yv),notes:ve(n?.notes)},latestOperatorAction:(()=>{const a=qe(t.latestOperatorAction);return a?{kind:Mt(a.kind,ud),at:ve(a.at),by:ve(a.by),notes:ve(a.notes)}:null})()}}function fd(e,t){if(!e)return null;const n=aI(e.metadata),a=t?.metadata??e.metadata;if(n)return{...n,latestOperatorAction:pd(a)??n.latestOperatorAction};const s=$o(e.metadata),o=Ho(e.metadata),i=hd(e.metadata)??(s?eI({deliveryMode:s.mode,deliveryGates:s.gates,channelId:ve(e.metadata.channelId),containerId:ve(e.metadata.containerId),conversationId:e.conversationId,taskId:e.id,roomMode:ve(e.metadata.roomRoutingMode),transport:ve(e.metadata.transport),workflowStageId:ve(e.metadata.workflowStageId),workflowShape:ve(e.metadata.workflowShape)}):null);return tI({approval:e.approval,delivery:s,budget:o,runtimeDeliveryManifest:i,operatorMetadata:a})}function qo(e){return e?nI(e.metadata,e.status):null}function an(e,t){return t.localeCompare(e)}function qt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function md(e,t){return e?qt(e[t]):null}function ue(e,t){if(!e)return null;const n=e[t];return typeof n=="string"&&n.trim().length>0?n:null}function Fr(e,t){if(!e)return null;const n=e[t];return typeof n=="number"&&Number.isFinite(n)?n:null}function Wr(e,t){return e?e[t]===!0:!1}function gd(e,t){if(!e)return[];const n=e[t];return Array.isArray(n)?n.filter(a=>!!a&&typeof a=="object"&&!Array.isArray(a)):[]}function Cd(e,t){if(!e)return[];const n=e[t];return Array.isArray(n)?n.filter(a=>typeof a=="string"&&a.trim().length>0):[]}function rI(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 vd(e){return ue(e,"replayPhase")}function sI(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 oI(e){switch(e.status){case"blocked":return"attention";case"failed":return"error";case"succeeded":return"success";default:return"muted"}}function iI(e){switch(e.kind){case"error":return"error";case"approval":return"attention";case"status":return"progress";default:return"muted"}}function lI(e){const t=sI(vd(e.metadata));if(t)return t;switch(e.kind){case"approval_requested":return"attention";case"approval_decided":return ue(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 cI(e){switch(e.status){case"open":return"attention";case"completed":return"success";default:return"muted"}}function dI(e){const t=vd(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 uI(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 pI(e){const t={[e.ownerProfile.actorId]:e.ownerProfile.displayName};for(const n of e.actors)t[n.id]=n.name;return t}function Id(e,t,n,a){const s=a.map(o=>ue(o.metadata,"guard")).find(o=>!!o);return ue(t?.metadata,"guard")??ue(n?.metadata,"guard")??ue(e?.metadata,"guard")??s??null}function Sd(e,t,n,a){const s=a.map(d=>ue(d.metadata,"cooldownLabel")??ue(d.metadata,"cooldownReason")??ue(d.metadata,"cooldownUntil")).find(d=>!!d),o=qt(t?.metadata),i=qt(n?.metadata),u=qt(e?.metadata),c=ue(o,"cooldownUntil")??ue(i,"cooldownUntil")??ue(u,"cooldownUntil")??s;return c||(Wr(o,"cooldownActive")||Wr(i,"cooldownActive")||Wr(u,"cooldownActive")?"Cooldown active":ue(o,"cooldownLabel")??ue(o,"cooldownReason")??ue(i,"cooldownLabel")??ue(i,"cooldownReason")??ue(u,"cooldownLabel")??ue(u,"cooldownReason")??null)}function hI(e){const t=qt(e.metadata),n=qo(e);return{dispatchCount:n?.dispatchCount??Fr(t,"dispatchCount"),continuationCount:n?.continuationCount??Fr(t,"continuationCount"),targetCount:n?.targetCount??Fr(t,"targetCount")}}function fI(e,t){const n=md(e,t),a=ue(n,"assistantTurnId"),s=Cd(n,"messageIds");if(!a||s.length===0)return null;const o=Fr(n,"segmentCount")??s.length;return{assistantTurnId:a,messageIds:s,fullText:ue(n,"fullText")??"",segmentCount:o>0?o:s.length}}function mI(e){const t=qt(e?.metadata);return gd(t,"branchStates").map((n,a)=>({id:ue(n,"id")??`branch-${a}`,participantName:ue(qt(n.participant),"participantName")??"Unknown Cat",status:ue(n,"status")??"pending",handoffReason:ue(n,"handoffReason"),branchStrategy:ue(n,"branchStrategy"),parentCheckpointId:ue(n,"parentCheckpointId"),response:fI(n,"response"),error:ue(n,"error")}))}function Lr(e){const t=md(e,"workflowRecommendation");if(!t)return null;const n=ue(t,"workflowShape"),a=ue(t,"source"),s=ue(e,"continuationSource"),o=gd(t,"candidateTargets").map(i=>({participantKind:(()=>{const u=ue(i,"participantKind");return u==="orchestrator"||u==="cat"?u:null})(),participantId:ue(i,"participantId"),participantName:ue(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:ue(t,"branchStrategy"),rationale:ue(t,"rationale"),reviewRequired:Wr(t,"reviewRequired"),candidateTargets:o,unresolvedTargets:Cd(e,"unresolvedTargets")}}function yd(e){return Lr(e.latestCheckpoint?.metadata)??Lr(e.latestOutcome?.metadata)??Lr(e.latestRun?.metadata)??e.traces?.map(t=>Lr(t.metadata)).find(t=>!!t)??null}const gI=new Set(["manual_review_required","owner_approval_required","publish_artifact_required"]);function CI(e){if(!e)return null;const t=qt(e.metadata),n=$o(t),a=Ho(t);return{deliveryMode:n?.mode??null,deliveryGates:n?.gates??(Array.isArray(t?.effectiveDeliveryGates)?t.effectiveDeliveryGates.filter(s=>typeof s=="string"&&gI.has(s)):[]),deliverySource:n?.source??null,deliveryRationale:n?.rationale??null,budgetAlertLevel:a?.alertLevel??null,budgetAlertSource:a?.source??null,budgetRationale:a?.rationale??null}}function bd(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 xd(e,t,n,a,s,o){if(!t)return[];if(!(t.status==="blocked"||t.status==="failed"||!!s||!!o))return[];const u=qt(e?.metadata),d=qt(t.metadata)??{},h=qt(u?.orchestratorDispatchReplay),f=n?.updatedAt??a?.updatedAt??t.updatedAt,m=ue(d,"operatorAcknowledgedAt"),v=ue(u,"operatorRetryRequestedAt")??ue(d,"operatorRetryRequestedAt"),C=!!(m&&m.localeCompare(f)>=0),I=!!(v&&v.localeCompare(f)>=0),y=ue(h,"replayTrigger"),g=ue(h,"replayState"),x=ue(h,"replayError"),S=I&&y==="retry"?g==="in_progress"?"Retry in progress":g==="failed"?x?`Retry failed: ${x}`:"Retry failed":"Retry dispatched":I?"Retry requested":null;return[{kind:"retry",label:I&&g==="failed"?"Retry Again":I&&g==="in_progress"?"Retrying":I?"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:I&&g!=="failed",statusLabel:S,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 vI(e,t,n,a,s){const o=e.map(d=>({id:`activity:${d.id}`,label:dI(d),message:d.message,createdAt:d.createdAt,actorId:d.actorId,actorName:d.actorId?s[d.actorId]??null:null,runId:d.runId,taskId:d.taskId,severity:lI(d),source:"activity"})),i=t.filter(d=>d.kind==="status"||d.kind==="approval"||d.kind==="error").map(d=>({id:`trace:${d.id}`,label:uI(d),message:d.message,createdAt:d.createdAt,actorId:d.actorId,actorName:d.actorId?s[d.actorId]??null:null,runId:d.runId,taskId:d.taskId,severity:iI(d),source:"trace"})),u=n.map(d=>({id:`checkpoint:${d.id}`,label:"Checkpoint",message:d.summary??d.label,createdAt:d.updatedAt,actorId:null,actorName:null,runId:d.runId,taskId:d.taskId,severity:cI(d),source:"checkpoint"})),c=a.map(d=>({id:`outcome:${d.id}`,label:"Outcome",message:d.summary??d.title,createdAt:d.updatedAt,actorId:null,actorName:null,runId:d.runId,taskId:d.taskId,severity:oI(d),source:"outcome"}));return rI([...o,...i,...u,...c].sort((d,h)=>an(d.createdAt,h.createdAt)))}function dl(e){return jc(null,e).conversationId}function II(e){return typeof e=="string"?{channelId:e,conversationId:dl(e)}:{channelId:e.id,conversationId:e.conversationId?.trim()||dl(e.id)}}function SI(e,t){if(!e)return null;const{channelId:n,conversationId:a}=II(t),s=`task-channel-${n}`,o=pI(e.core),i=e.core.tasks.find(D=>D.id===s)??null,u=e.approvals.filter(D=>D.conversationId===a||D.taskId===s).sort((D,T)=>an(D.requestedAt??D.decidedAt??"",T.requestedAt??T.decidedAt??"")),c=e.core.runs.filter(D=>D.conversationId===a).sort((D,T)=>an(D.updatedAt,T.updatedAt)),d=e.core.traces.filter(D=>D.conversationId===a).sort((D,T)=>an(D.createdAt,T.createdAt)),h=e.core.checkpoints.filter(D=>D.conversationId===a).sort((D,T)=>an(D.updatedAt,T.updatedAt)),f=e.core.outcomes.filter(D=>D.conversationId===a).sort((D,T)=>an(D.updatedAt,T.updatedAt)),m=e.core.activities.filter(D=>D.conversationId===a).sort((D,T)=>an(D.createdAt,T.createdAt)),v=c[0]??null,C=f[0]??null,I=h[0]??null,y=u[0]??null,g=Id(v,C,I,d),x=Sd(v,C,I,d),S=CI(i),k=qo(v),w=yd({latestCheckpoint:I,latestOutcome:C,latestRun:v,traces:d}),P=fd(i,v),j=bd(y),N=vI(m,d,h,f,o);return{channelId:n,conversationId:a,actorNameById:o,task:i,approvals:u,runs:c,traces:d,checkpoints:h,outcomes:f,activityFeed:N,latestRun:v,latestOutcome:C,latestCheckpoint:I,latestApproval:y,guardReason:g,cooldownLabel:x,effectivePolicy:S,governanceSummary:P,workflowSummary:k,latestWorkflowRecommendation:w,approvalActions:j,incidentActions:xd(i,v,C,I,g,x)}}function yI(e,t){if(!e)return null;const n=e.runs.find(I=>I.id===t)??e.latestRun;if(!n)return null;const a=e.traces.filter(I=>I.runId===n.id).sort((I,y)=>an(I.createdAt,y.createdAt)),s=e.checkpoints.filter(I=>I.runId===n.id).sort((I,y)=>an(I.updatedAt,y.updatedAt)),o=e.outcomes.filter(I=>I.runId===n.id).sort((I,y)=>an(I.updatedAt,y.updatedAt)),i=e.approvals.filter(I=>I.taskId===n.taskId),u=o[0]??null,c=s[0]??null,d=Id(n,u,c,a),h=Sd(n,u,c,a),f=qo(n),m=yd({latestCheckpoint:c,latestOutcome:u,latestRun:n,traces:a}),v=fd(e.task,n),C=i[0]??e.latestApproval;return{run:n,traces:a,checkpoints:s,outcomes:o,approvals:i,latestOutcome:u,latestCheckpoint:c,guardReason:d,cooldownLabel:h,metrics:hI(n),workflowSummary:f,governanceSummary:v,workflowStageId:f?.stageId??null,workflowShape:f?.shape??null,reviewRequired:f?.reviewRequired??!1,branchStates:mI(n),latestWorkflowRecommendation:m,approvalActions:bd(C),incidentActions:xd(e.task,n,u,c,d,h)}}function bI(e){const t=e.threshold??80;return e.scrollTop+e.clientHeight>=e.scrollHeight-t}const ul=80,xI=12;function wI(e){return e?.closest(".canvas")}function kI(e){const t=Number.parseFloat(globalThis.getComputedStyle(e).bottom||"0");return Number.isFinite(t)?Math.max(0,t):0}function PI(e){return e?Math.ceil(ul+e.getBoundingClientRect().height):ul}function AI(e){const{channelId:t,scrollKey:n,scrollOnChannelChange:a=!0}=e,[s,o]=p.useState(null),[i,u]=p.useState(null),[c,d]=p.useState(null),h=p.useRef(null),f=p.useRef(!0),[m,v]=p.useState(!0),C=p.useRef(null),I=p.useRef(null),y=p.useRef(0),g=p.useRef(null),x=p.useRef(null),S=p.useCallback(()=>{const N=h.current;if(!N){f.current=!0,v(!0);return}const D=bI({scrollTop:N.scrollTop,clientHeight:N.clientHeight,scrollHeight:N.scrollHeight,threshold:PI(i)});f.current=D,v(D)},[i]),k=p.useCallback(()=>{if(!s){C.current=null;return}const N=i?Math.ceil(kI(i)+xI):0;C.current!==N&&(C.current=N,s.style.paddingBottom=N>0?`${N}px`:"")},[i,s]),w=p.useCallback(()=>{if(!i){I.current=null,y.current=0;return}const N=Math.ceil(i.getBoundingClientRect().height);if(N<=0)return;const D=I.current,T=D==null?N:Math.min(D,N);I.current=T;const A=Math.max(0,N-T);if(y.current!==A&&(y.current=A,i.style.marginTop=A>0?`${-A}px`:""),!c){g.current=Math.max(0,A);return}const b=Math.max(0,A);g.current!==b&&(g.current=b,c.style.height=`${b}px`)},[c,i]),P=p.useCallback(()=>{w(),k(),f.current=!0,v(!0);const N=h.current;if(N){N.scrollTo({top:N.scrollHeight});return}c&&c.scrollIntoView({block:"end"})},[c,w,k]),j=p.useCallback(()=>{x.current!==null&&cancelAnimationFrame(x.current),x.current=requestAnimationFrame(()=>{x.current=null,P()})},[P]);return p.useEffect(()=>{const N=wI(s);if(h.current=N,!N)return;S();const D=()=>{S()};return N.addEventListener("scroll",D,{passive:!0}),()=>{N.removeEventListener("scroll",D),h.current===N&&(h.current=null)}},[S,s]),p.useEffect(()=>(w(),k(),()=>{x.current!==null&&(cancelAnimationFrame(x.current),x.current=null),s&&(s.style.paddingBottom=""),i&&(i.style.marginTop=""),c&&(c.style.height=""),C.current=null,I.current=null,y.current=0,g.current=null}),[c,i,w,k,s]),p.useEffect(()=>{!s||!a||(f.current=!0,j())},[t,a,j,s]),p.useEffect(()=>{!s||!f.current||j()},[n,j,s]),p.useEffect(()=>{const N=h.current;if(!s||!N||typeof ResizeObserver>"u")return;const D=new ResizeObserver(()=>{w(),k(),f.current&&j()});return D.observe(s),()=>{D.disconnect()}},[j,w,k,s]),p.useEffect(()=>{if(!i||typeof ResizeObserver>"u")return;w();const N=new ResizeObserver(()=>{w()});return N.observe(i),()=>{N.disconnect()}},[i,w]),p.useEffect(()=>{I.current=null,y.current=0,g.current=null,w()},[t,w]),{transcriptListRef:o,composerCardRef:u,bottomSentinelRef:d,isNearBottom:m,scrollToBottom:P}}function wd(e){return e.assignedParticipants&&e.assignedParticipants.length>0?e.assignedParticipants:e.assignedCats}function RI(e){return wd(e).filter(t=>t.status==="active")}function NI(e,t){return wd(e).find(n=>n.participantId===t)??null}function es(e){return"catId"in e&&typeof e.catId=="string"&&e.catId.length>0?e.catId:e.sourceKind==="cat"?e.sourceRefId:null}function TI(e){const{payload:t,selectedChannel:n,activeAssignedCats:a,showBossCatAvatar:s,isDirectLane:o,isDefaultChatComposer:i}=e,u=n.roomRouting.defaultRecipientId,c=p.useMemo(()=>RI(n),[n]),d=u?c.find(A=>A.participantId===u)??null:c[0]??null,h=d?.sourceKind==="cat"?a.find(A=>A.participantId===d.participantId)??null:null,f=p.useMemo(()=>new Map(t.chat.cats.map(A=>[A.id,A])),[t.chat.cats]);function m(A,b,R){if(A)return{backgroundImage:`url(${A})`,backgroundSize:"cover",backgroundPosition:"center"};if(R&&b)return{background:b}}function v(A){if(!A)return null;const b=es(A);return b?f.get(b)??null:null}function C(A,b=v(A)){return!A||b==null}function I(A,b=v(A)){return b?.name??A.name}function y(A,b=v(A)){return b?.avatarUrl??A.avatarUrl??null}function g(A,b=null){return m(b?.avatarUrl??A.avatarUrl??null,b?.avatarColor??A.avatarColor??null,b!=null)}function x(A,b={}){const R=b.catRecord??v(A);return["catAvatar",b.transcript?"transcriptAvatar":"",b.composer?"composerStackAvatar":"",R?.id===t.chat.bossCatId?"catAvatarBoss":"",C(A,R)?"channelParticipantAvatar":""].filter(Boolean).join(" ")}function S(A){const b=A.metadata?.executionLabelSnapshot;return typeof b=="string"&&b.trim()?b.trim():null}function k(A){const b=typeof A.metadata?.targetId=="string"?A.metadata.targetId.trim():"";if(b)return NI(n,b);const R=new Set,L=A.senderName?.trim();L&&!th(L)&&R.add(L);const O=S(A);return O&&R.add(O),R.size===0?null:c.find(Y=>{const $=Qn(Y);return R.has(Y.name)||$!=null&&R.has($)})??null}const w=o&&h?t.chat.cats.find(A=>A.id===h.catId)??null:null,P=t.chat.bossCatId?t.chat.cats.find(A=>A.id===t.chat.bossCatId)??null:null,j=h?t.chat.cats.find(A=>A.id===h.catId)??null:null,N=p.useMemo(()=>c.map(A=>{const b=es(A);return b?t.chat.cats.find(R=>R.id===b)??null:null}).filter(A=>A!=null),[c,t.chat.cats]),D=p.useMemo(()=>c.filter(A=>A.sourceKind!=="cat"),[c]),T=p.useMemo(()=>{const A=[];if(o){if(j){const b=d?Qn(d):null;A.push({key:`participant:${j.id}`,label:j.name,executionLabel:b,avatarColor:j.avatarColor??null,avatarUrl:j.avatarUrl??null,isBoss:j.id===t.chat.bossCatId,useNeutralAvatar:!1,pulseParticipantId:d?.participantId??null,pulseCatId:j.id})}}else{s&&!i&&P&&A.push({key:`participant:${P.id}`,label:P.name,executionLabel:Zn(P),avatarColor:P.avatarColor??null,avatarUrl:P.avatarUrl??null,isBoss:!0,useNeutralAvatar:!1,pulseParticipantId:null,pulseCatId:P.id});for(const b of c){const R=v(b);A.push({key:`participant:${b.participantId}`,label:I(b,R),executionLabel:Qn(b),avatarColor:R?.avatarColor??b.avatarColor??null,avatarUrl:R?.avatarUrl??b.avatarUrl??null,isBoss:R?.id===t.chat.bossCatId,useNeutralAvatar:C(b,R),pulseParticipantId:b.participantId,pulseCatId:R?.id??null})}}return A},[c,P,j,d?.participantId,o,i,t.chat.bossCatId,C,I,v,s]);return{activeRoomParticipants:c,defaultRecipientParticipant:d,defaultRecipientCat:h,directLaneCat:w,bossCatRecord:P,defaultRecipientCatRecord:j,assignedCatRecords:N,assignedAdhocParticipants:D,topBarParticipants:T,resolveParticipantCatRecord:v,resolveParticipantDisplayName:I,resolveParticipantAvatarUrl:y,buildParticipantAvatarStyle:g,buildParticipantAvatarClassName:x,resolveMessageParticipant:k}}function jI({conversationMode:e,layoutMode:t,composerVariant:n,secondarySurfacePosition:a,layoutStyle:s,hasConversationStarted:o,topBar:i,statusRow:u=null,children:c,sidePanel:d,activeDirectCatId:h=null}){const[f,m]=p.useState(null);return p.useEffect(()=>{if(!h){m(null);return}return m(nh(h)),ah(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,u,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})]})]}),d]})}function LI({avatars:e,showRosterAvatars:t,isDirectLane:n,topBarTitle:a,sidePanelOpen:s,approvalCount:o,extraActions:i,onToggleSidePanel:u,onOpenCatProfile:c}){const{t:d}=z();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:Rt(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":d(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:u,"aria-label":d(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 It=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),MI={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 Pa(e,t=It){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 dr(e){switch(e){case"progress":return"isProgress";case"attention":return"isAttention";case"error":return"isError";case"success":return"isSuccess";default:return"isMuted"}}function lo(e,t=It){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 kd(e){switch(e){case"running":return"progress";case"blocked":return"attention";case"failed":return"error";case"completed":return"success";default:return"muted"}}function EI(e,t=It){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 DI(e,t=It){switch(e){case"completed":return t(l.sharedOperatorCheckpointStatusCompleted);case"cancelled":return t(l.sharedOperatorCheckpointStatusCancelled);default:return t(l.sharedOperatorCheckpointStatusOpen)}}function BI(e){switch(e){case"completed":return"success";case"cancelled":return"muted";default:return"attention"}}function OI(e,t=It){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 _I(e){switch(e){case"succeeded":return"success";case"blocked":return"attention";case"failed":return"error";default:return"muted"}}function FI(e,t=It){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 WI(e,t=It){const n=MI[e];return n?t(n):e}const UI={artifact_only:l.sharedOperatorDeliveryModeArtifactOnly,commit_only:l.sharedOperatorDeliveryModeCommitOnly,deploy_preview:l.sharedOperatorDeliveryModeDeployPreview,pr_with_checks:l.sharedOperatorDeliveryModePrWithChecks,push_branch:l.sharedOperatorDeliveryModePushBranch},KI={manual_review_required:l.sharedOperatorGateManualReviewRequired,owner_approval_required:l.sharedOperatorGateOwnerApprovalRequired,publish_artifact_required:l.sharedOperatorGatePublishArtifactRequired},$I={blocked:l.sharedOperatorBudgetLevelBlocked,normal:l.sharedOperatorBudgetLevelNormal,warning:l.sharedOperatorBudgetLevelWarning},HI={concurrent:l.sharedOperatorWorkflowShapeConcurrent,converge:l.sharedOperatorWorkflowShapeConverge,parallel:l.sharedOperatorWorkflowShapeConcurrent,sequential:l.sharedOperatorWorkflowShapeSequential},qI={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},GI={fork_if_possible:l.sharedOperatorBranchStrategyForkIfPossible,fresh_no_parent:l.sharedOperatorBranchStrategyFreshNoParent,single_target_review:l.sharedOperatorBranchStrategySingleTargetReview,transplant_context:l.sharedOperatorBranchStrategyTransplantContext},VI={explicit_mention:l.sharedOperatorBranchHandoffExplicitMention,operator_reroute:l.sharedOperatorBranchHandoffOperatorReroute,room_default:l.sharedOperatorBranchHandoffRoomDefault,room_entry:l.sharedOperatorBranchHandoffRoomEntry,runtime_retry:l.sharedOperatorBranchHandoffRuntimeRetry,workflow_continuation:l.sharedOperatorBranchHandoffWorkflowContinuation},zI={anti_ping_pong:l.sharedOperatorGuardAntiPingPong,max_continuations:l.sharedOperatorGuardMaxContinuations,max_dispatches:l.sharedOperatorGuardMaxDispatches,max_target_visits:l.sharedOperatorGuardMaxTargetVisits},YI={"cooldown active":l.sharedOperatorCooldownActive};function JI(e){return e.trim().toLowerCase().replace(/-/gu,"_")}function XI(e){return e.trim().replace(/[_-]+/gu," ").replace(/\s+/gu," ").replace(/\b\w/gu,t=>t.toUpperCase())}function Tn(e,t,n){const a=e.trim();if(!a)return a;const s=t[JI(a)];return s?n(s):XI(a)}function QI(e,t=It){return Tn(e,UI,t)}function ZI(e,t=It){return Tn(e,KI,t)}function eS(e,t=It){return Tn(e,$I,t)}function Pd(e,t=It){return Tn(e,HI,t)}function Ad(e,t=It){return Tn(e,qI,t)}function tS(e,t=It){return Tn(e,GI,t)}function nS(e,t=It){return Tn(e,VI,t)}function Rd(e,t=It){return Tn(e,zI,t)}function Nd(e,t=It){const n=e.trim().toLowerCase(),a=YI[n];return a?t(a):e}function aS({items:e}){const{t}=z();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 ${dr(n.severity)}`}),r.jsxs("div",{className:"operatorTimelineBody",children:[r.jsxs("div",{className:"operatorTimelineHeader",children:[r.jsx("strong",{children:WI(n.label,t)}),r.jsx("span",{children:Pa(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 rS={"Request Retry":l.sharedOperatorActionRequestRetry,"Retry Again":l.sharedOperatorActionRetryAgain,Retrying:l.sharedOperatorActionRetrying,"Retry Requested":l.sharedOperatorActionRetryRequested,Acknowledge:l.sharedOperatorActionAcknowledge,Acknowledged:l.sharedOperatorActionAcknowledged},sS={"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},oS={"Retry in progress":l.sharedOperatorActionStatusRetryInProgress,"Retry failed":l.sharedOperatorActionStatusRetryFailed,"Retry dispatched":l.sharedOperatorActionStatusRetryDispatched,"Retry requested":l.sharedOperatorActionStatusRetryRequested,Acknowledged:l.sharedOperatorActionStatusAcknowledged},iS={approve:l.sharedApprovalActionApprove,reroute:l.sharedApprovalActionReroute,reject:l.sharedApprovalActionReject},lS={approve:l.sharedApprovalActionApproveDescription,reroute:l.sharedApprovalActionRerouteDescription,reject:l.sharedApprovalActionRejectDescription};function cS(e,t){const n=rS[e];return n?t(n):e}function dS(e,t){const n=sS[e];return n?t(n):e}function uS(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=oS[e];return a?t(a):e}function pS(e,t,n){const a=iS[e];return a?n(a):t}function hS(e,t,n){const a=lS[e];return a?n(a):t}function fS({approvals:e,actorNameById:t,busy:n,onDecision:a}){const{t:s}=z();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=rh(n,o.taskId),u=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:Pa(o.requestedAt,s)})]}),r.jsxs("div",{className:"operatorMetaRow",children:[r.jsx("span",{children:s("sharedApprovalRequestedBy",{requestedBy:u})}),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:hS(c.action,c.description,s),onClick:()=>a(o.taskId,c.action),children:pS(c.action,c.label,s)},`${o.id}:${c.action}`))})]},o.id)})})]})}function mS({inspector:e,effectivePolicy:t,incidentActions:n,pendingApprovalCount:a,guardReason:s,cooldownLabel:o,onInspectRun:i,onOperatorAction:u}){const{t:c}=z();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 ${dr(kd(e.run.status))}`,children:lo(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:Pa(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:Ad(e.workflowStageId,c)})}):null,e.workflowShape?r.jsx("span",{children:c(l.sharedOperatorMetaShape,{shape:Pd(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:QI(t.deliveryMode,c)})}):null,t.deliveryGates.length>0?r.jsx("span",{children:c(l.sharedOperatorGatesLabel,{gates:t.deliveryGates.map(d=>ZI(d,c)).join(", ")})}):null,t.budgetAlertLevel?r.jsx("span",{children:c(l.sharedOperatorBudgetLabel,{budgetLevel:eS(t.budgetAlertLevel,c)})}):null]}):null,s?r.jsx("div",{className:"operatorCallout operatorCalloutAttention",children:c(l.sharedOperatorMetaGuardrail,{guardrail:Rd(s,c)})}):null,o?r.jsx("div",{className:"operatorCallout operatorCalloutMuted",children:c(l.sharedOperatorMetaCooldown,{cooldown:Nd(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(d=>{const h=dS(d.description,c);return r.jsx("button",{className:d.kind==="retry"?"operatorActionButton operatorActionButtonPrimary":"operatorActionButton",type:"button",disabled:d.disabled,title:h,onClick:()=>u({action:d.kind,taskId:d.taskId,runId:d.runId,checkpointId:d.checkpointId,outcomeId:d.outcomeId}),children:cS(d.label,c)},`${d.kind}:${d.runId??d.taskId??d.checkpointId??d.outcomeId??"global"}`)})]}),n.some(d=>d.statusLabel)?r.jsx("div",{className:"operatorMetaRow",children:n.filter(d=>d.statusLabel).map(d=>r.jsx("span",{children:uS(d.statusLabel,c)},`status:${d.kind}`))}):null]})}):r.jsx("p",{className:"operatorEmptyState",children:c(l.sharedOperatorNoActiveRun)})]})}function gS(e){const t=e;return r.jsx(mS,{...t})}function CS({traces:e,actorNameById:t}){const{t:n}=z();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:FI(a.kind,n)}),r.jsx("span",{children:Pa(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 vS({runs:e,actorNameById:t,inspector:n,onSelectRun:a}){const{t:s}=z();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:lo(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 ${dr(kd(n.run.status))}`,children:lo(n.run.status,s)})]}),r.jsxs("div",{className:"operatorMetaRow",children:[r.jsx("span",{children:s(l.sharedOperatorMetaStarted,{time:Pa(n.run.startedAt??n.run.createdAt,s)})}),r.jsx("span",{children:s(l.sharedOperatorMetaUpdated,{time:Pa(n.run.updatedAt,s)})})]}),n.workflowStageId||n.workflowShape?r.jsxs("div",{className:"operatorMetaRow",children:[n.workflowStageId?r.jsx("span",{children:s(l.sharedOperatorMetaStage,{stage:Ad(n.workflowStageId,s)})}):null,n.workflowShape?r.jsx("span",{children:s(l.sharedOperatorMetaShape,{shape:Pd(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:Rd(n.guardReason,s)})}):null,n.cooldownLabel?r.jsx("div",{className:"operatorCallout operatorCalloutMuted",children:s(l.sharedOperatorMetaCooldown,{cooldown:Nd(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(CS,{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 ${dr(BI(o.status))}`,children:DI(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:EI(o.status,s)})]}),r.jsxs("p",{children:[o.handoffReason?`${s(l.sharedOperatorBranchHandoff,{handoffReason:nS(o.handoffReason,s)})} `:"",o.branchStrategy?`${s(l.sharedOperatorBranchStrategy,{strategy:tS(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 ${dr(_I(o.status))}`,children:OI(o.status,s)})]}),r.jsx("p",{children:o.summary??s(l.sharedOperatorOutcomeSummaryFallback)})]},o.id))})]})]})]})]})}function IS({runs:e,actorNameById:t,inspector:n,onSelectRun:a}){const s={runs:e,actorNameById:t,inspector:n,onSelectRun:a};return r.jsx(vS,{...s})}function co({cats:e,bossCatId:t,selectedIds:n,highlightedId:a,defaultRecipientCatId:s,toggleable:o,showLeadBadge:i,onToggle:u,onHighlight:c}){const d=sh(e,{bossCatIds:t});if(d.length===0)return null;const h=new Set(n);return r.jsx("div",{className:"catAvatarRow",children:d.map(f=>{const m=h.has(f.id),v=f.id===a,C=f.id===t,I=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":oh(f.name,Zn(f)),onClick:()=>{o&&u(f.id),!o&&m&&c(f.id)},children:[f.avatarUrl?null:Rt(f.name),i&&I?r.jsx("span",{className:"catAvatarLeadBadge",children:"★"}):null]},f.id)})})}function SS({assignedCatRecords:e,assignedAdhocParticipants:t,bossCatId:n,defaultRecipientCatId:a,editingParticipantId:s,editingParticipantName:o,busy:i,canRenameParticipants:u,showAddCatButton:c,onEditingParticipantNameChange:d,onBeginParticipantRename:h,onCancelParticipantRename:f,onSubmitParticipantRename:m,onOpenAddCat:v,onCloseSidePanel:C}){const{t:I}=z(),y=g=>ih(i,g);return r.jsxs("div",{className:"sidePanelSectionStack",children:[e.length>0?r.jsx(co,{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:Gr(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:I(l.chatParticipantsSectionNameLabel)}),r.jsx("input",{className:"chromeInput",value:o,onChange:x=>d(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:I(l.chatParticipantsSectionSaveNameButton)}),r.jsx("button",{type:"button",className:"addCatAssignButton",onClick:f,disabled:y(g.participantId),children:I(l.chatParticipantsSectionCancelButton)})]})]}):null]}),r.jsx("div",{style:{display:"flex",gap:8,alignItems:"center"},children:u?r.jsx("button",{type:"button",className:"addCatAssignButton",disabled:y(g.participantId),onClick:()=>h(g),children:I(l.chatParticipantsSectionRenameButton)}):null})]},g.participantId))}):null,e.length===0&&t.length===0?r.jsx("p",{className:"operatorEmptyState",children:I(l.chatParticipantsSectionNoParticipants)}):null,c?r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>{C(),v?.()},children:I(l.chatParticipantsSectionChooseCatsButton)}):null]})}function yS({payload:e,selectedChannel:t,busy:n,operatorView:a,operatorLoading:s,operatorError:o,assignedCatRecords:i,assignedAdhocParticipants:u,defaultRecipientCatId:c,defaultRecipientParticipant:d,directLaneCat:h,directLaneExecutionTarget:f,isDirectLane:m,isDefaultChatComposer:v,selectedExecutionTarget:C,inspectedRun:I,showAddCatButton:y,editingParticipantId:g,editingParticipantName:x,canRenameParticipants:S,onEditingParticipantNameChange:k,onBeginParticipantRename:w,onCancelParticipantRename:P,onSubmitParticipantRename:j,onOpenAddCat:N,onCloseSidePanel:D,onInspectRun:T,onApprovalDecision:A,onOperatorAction:b,onExecutionTargetChange:R,onStartFresh:L,onDirectLaneExecutionTargetChange:O,onDirectLaneParticipantTargetChange:Y,buildParticipantAvatarStyle:$}){const{t:M}=z(),F=[],J=Js(n,"reset");(y||i.length>0||u.length>0)&&F.push({id:"cats",title:u.length>0?M(l.chatNewChatDraftSidePanelParticipantsGroupTitle):M(l.chatNewChatDraftSidePanelParticipantsCatsTitle),children:r.jsx(SS,{assignedCatRecords:i,assignedAdhocParticipants:u,bossCatId:e.chat.bossCatId,defaultRecipientCatId:c,editingParticipantId:g,editingParticipantName:x,busy:n,canRenameParticipants:S,showAddCatButton:y,onEditingParticipantNameChange:k,onBeginParticipantRename:w,onCancelParticipantRename:P,onSubmitParticipantRename:j,onOpenAddCat:N,onCloseSidePanel:D})});const me=(()=>{if(m&&h&&f){const B=Ys(h.mcpProfile),ae=d?{provider:d.execution.target.provider,instance:d.execution.target.instance??null,model:d.execution.target.model??null,modelSelection:d.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:Rt(h.name)}),r.jsxs("div",{children:[r.jsx("strong",{children:h.name}),h.id===e.chat.bossCatId?r.jsx("span",{className:"catInspectBadge",children:M(l.sharedCatInspectBossLabel)}):null]})]}),r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.sharedSettingsCatsMcpProfileLabel)}),r.jsx("span",{children:B?M(B):h.mcpProfile})]})]}),r.jsx(Jn,{provider:ae.provider,instance:ae.instance??"",model:ae.model??"",modelSelection:ae.modelSelection,onTargetChange:be=>{const W=xa(be);if(d&&Y){Y(d.participantId,W);return}O?.(h.id,W)}})]})}if(v&&C&&R)return r.jsxs(r.Fragment,{children:[r.jsx(Jn,{provider:C.provider,instance:C.instance??"",model:C.model??"",modelSelection:C.modelSelection,onTargetChange:B=>{R(xa(B))}}),L?r.jsxs("div",{className:"sidePanelSectionStack",children:[r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>{L()},disabled:J,children:M(J?l.chatSidePanelStartingFreshBusy:l.chatSidePanelStartFresh)}),r.jsx("p",{className:"operatorEmptyState",children:M(l.chatSidePanelStartFreshHint)})]}):null]});if(!v&&d){const B=cg({provider:d.execution.target.provider,instance:d.execution.target.instance??null,model:d.execution.target.model??null,modelSelection:d.execution.modelSelection??null});if(d.sourceKind!=="cat")return r.jsxs("div",{className:"catInspectPanelBody",children:[r.jsxs("div",{className:"catInspectIdentity",children:[r.jsx("div",{className:"catAvatar catInspectAvatar channelParticipantAvatar",style:$(d),children:d.avatarUrl?null:Rt(d.name)}),r.jsxs("div",{children:[r.jsx("strong",{children:d.name}),r.jsx("span",{className:"catInspectBadge",children:M(l.chatSidePanelTemporaryParticipantLabel)})]})]}),d.roleHint?r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.chatSidePanelRoleLabel)}),r.jsx("span",{children:d.roleHint})]}):null,r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.chatSidePanelAiServiceLabel)}),r.jsx("span",{children:B.providerLabel})]}),B.instanceLabel?r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.chatSidePanelConnectionLabel)}),r.jsx("span",{children:B.instanceLabel})]}):null,r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.sharedCatInspectModelLabel)}),r.jsx("span",{children:B.modelLabel})]})]});const ae=es(d),be=ae?e.chat.cats.find(q=>q.id===ae)??null:null,W=Ys(be?.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:be?.avatarUrl?{backgroundImage:`url(${be.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:d.avatarColor?{background:d.avatarColor}:void 0,children:be?.avatarUrl?null:Rt(d.name)}),r.jsxs("div",{children:[r.jsx("strong",{children:d.name}),ae===e.chat.bossCatId?r.jsx("span",{className:"catInspectBadge",children:M(l.sharedCatInspectBossLabel)}):null]})]}),r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.chatSidePanelAiServiceLabel)}),r.jsx("span",{children:B.providerLabel})]}),B.instanceLabel?r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.chatSidePanelConnectionLabel)}),r.jsx("span",{children:B.instanceLabel})]}):null,r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.sharedCatInspectModelLabel)}),r.jsx("span",{children:B.modelLabel})]}),r.jsxs("div",{className:"catInspectField",children:[r.jsx("span",{className:"catInspectFieldLabel",children:M(l.sharedSettingsCatsMcpProfileLabel)}),r.jsx("span",{children:W?M(W):be?.mcpProfile})]})]})}return r.jsx("p",{className:"operatorEmptyState",children:M(l.chatNewChatDraftSidePanelExecutionEmptyState)})})();F.push({id:"execution",title:M(l.chatNewChatDraftSidePanelExecutionTitle),children:me});const K=t.repoPath??t.chatCwd;return F.push({id:"cwd",title:M(l.chatNewChatDraftSidePanelFolderTitle),children:K?r.jsxs("div",{style:{display:"grid",gap:8},children:[r.jsx("p",{style:{margin:0,fontSize:"0.85rem",wordBreak:"break-all"},children:K}),r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>{Wh(K)},children:M(l.chatNewChatDraftFolderActionLabel)})]}):r.jsx("p",{className:"operatorEmptyState",children:M(l.chatNewChatDraftSidePanelFolderEmptyState)})}),F.push({id:"operator",title:M(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:M(l.chatSidePanelRunStatusTitle)}),r.jsx("h2",{children:M(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:M(l.chatSidePanelRunStatusTitle)}),r.jsx("h2",{children:M(l.chatSidePanelLoadingTitle)})]})}),r.jsx("p",{className:"operatorEmptyState",children:M(l.chatSidePanelOperatorLoadingState)})]}):null,r.jsx(fS,{approvals:a?.approvals??[],actorNameById:a?.actorNameById??{},busy:n,onDecision:A}),r.jsx(gS,{inspector:I,effectivePolicy:a?.effectivePolicy??null,incidentActions:I?.incidentActions??a?.incidentActions??[],pendingApprovalCount:a?.approvals.length??0,guardReason:I?.guardReason??a?.guardReason??null,cooldownLabel:I?.cooldownLabel??a?.cooldownLabel??null,onInspectRun:T,onOperatorAction:b}),r.jsx(aS,{items:a?.activityFeed??[]}),r.jsx(IS,{runs:a?.runs??[],actorNameById:a?.actorNameById??{},inspector:I,onSelectRun:T})]})}),F}const bS=new Set(["cancelled","aborted"]);function xS(){const e=bo();return!e?.startVoiceCapture||!e.stopVoiceCapture||!e.cancelVoiceCapture||!e.onVoiceCaptureEvent?null:{startVoiceCapture:e.startVoiceCapture,stopVoiceCapture:e.stopVoiceCapture,cancelVoiceCapture:e.cancelVoiceCapture,onVoiceCaptureEvent:e.onVoiceCaptureEvent}}function wS(){return globalThis.crypto?.randomUUID?.()??`voice-${Date.now()}-${Math.random().toString(36).slice(2)}`}function kS({onTranscript:e,onError:t,lang:n}){const a=p.useMemo(()=>xS(),[]),[s,o]=p.useState("idle"),[i,u]=p.useState(null),c=p.useRef(null),d=p.useRef(e);d.current=e;const h=p.useRef(t);h.current=t;const f=p.useCallback(y=>{c.current===y&&(c.current=null,o("idle"),u(null))},[]);p.useEffect(()=>{if(a)return a.onVoiceCaptureEvent(y=>{if(y.sessionId===c.current)switch(y.type){case"ready":o("ready"),u(y.mode);break;case"partial":break;case"final":d.current(y.text);break;case"error":bS.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"),u(null)),a.cancelVoiceCapture(g).catch(()=>{}))},[a]),v=p.useCallback(()=>{if(!a||c.current)return;const y=wS();c.current=y,o("starting"),u(null),a.startVoiceCapture({sessionId:y,locale:n}).catch(()=>{c.current===y&&(c.current=null,o("idle"),u(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"),u(null),h.current?.("engine_unavailable"))})},[a]),I=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:I}}const PS=new Set(["no-speech","aborted"]);function pl(){if(typeof window>"u")return null;const e=window;return e.SpeechRecognition??e.webkitSpeechRecognition??null}function AS({onTranscript:e,onError:t,lang:n}){const[a]=p.useState(()=>pl()!==null),[s,o]=p.useState(!1),i=p.useRef(null),u=p.useRef(0),c=p.useRef(e);c.current=e;const d=p.useRef(t);d.current=t;const h=p.useCallback(()=>{const C=i.current;if(C)try{C.stop()}catch{}},[]),f=p.useCallback(C=>{const I=i.current;if(I){u.current+=1,i.current=null,C&&o(!1);try{I.abort()}catch{}}},[]),m=p.useCallback(()=>{f(!0)},[f]),v=p.useCallback(()=>{if(i.current)return;const C=pl();if(!C)return;const I=new C,y=u.current+1;u.current=y;const g=()=>i.current===I&&u.current===y;I.continuous=!0,I.interimResults=!1,n&&(I.lang=n),I.onresult=x=>{if(!g())return;let S="";for(let k=x.resultIndex;k<x.results.length;k+=1){const w=x.results[k];w?.isFinal&&(S+=w[0]?.transcript??"")}S&&c.current(S)},I.onerror=x=>{if(!g())return;const S=x?.error;S&&(console.warn(`[useWebSpeechInput] recognition error: ${S}`),PS.has(S)||d.current?.(S)),o(!1),i.current=null},I.onend=()=>{g()&&(o(!1),i.current=null)},i.current=I;try{I.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 RS={"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 NS(e,t){const n=RS[e];return n?t(n):t(l.sharedVoiceInputFailedWithKind,{kind:e})}function TS(e,t){return e==="unknown"?t(l.sharedVoiceInputPrivacyUnknown):e==="cloud"?t(l.sharedVoiceInputPrivacyCloud):null}function Td({value:e,onChange:t,autoResize:n,disabled:a,lang:s}){const{t:o}=z(),i=p.useRef(null),u=p.useRef(e);u.current=e;const c=p.useRef(!1),d=p.useRef(null);p.useEffect(()=>{const T=i.current;if(!T)return;const A=()=>{c.current=!0,d.current=u.current},b=()=>{c.current=!0,d.current=T.value};return T.addEventListener("focus",A),T.addEventListener("pointerdown",A),T.addEventListener("keydown",A),T.addEventListener("input",b),()=>{T.removeEventListener("focus",A),T.removeEventListener("pointerdown",A),T.removeEventListener("keydown",A),T.removeEventListener("input",b)}},[]),p.useEffect(()=>{d.current===null||d.current===e||(c.current=!1,d.current=null)},[e]);const h=p.useCallback(T=>{const A=T.trim();if(!A)return;const b=u.current,R=i.current,L=!!R&&(typeof document<"u"&&document.activeElement===R?!0:c.current&&d.current===b);let O,Y;if(L&&R){const $=R.selectionStart??b.length,M=R.selectionEnd??b.length,F=b.slice(0,$),J=b.slice(M),me=F.length>0&&!/\s$/.test(F),K=J.length>0&&!/^\s/.test(J),B=`${me?" ":""}${A}${K?" ":""}`;O=`${F}${B}${J}`,Y=F.length+B.length-(K?1:0)}else{const $=b&&!/\s$/.test(b)?" ":"";O=`${b}${$}${A}`,Y=O.length}c.current=!0,d.current=O,t(O),requestAnimationFrame(()=>{const $=i.current;if($){n($);try{$.setSelectionRange(Y,Y)}catch{}}})},[t,n]),{toasts:f,showToast:m}=Vl(),v=p.useCallback(T=>{m(NS(T,o))},[m,o]),C=kS({onTranscript:h,onError:v,lang:s}),I=AS({onTranscript:h,onError:v,lang:s}),y=C.supported?C:I,g=C.supported?C.active:I.listening,{supported:x,listening:S,start:k,stop:w,cancel:P}=y,j=p.useCallback(()=>{g?w():k()},[g,k,w]);p.useEffect(()=>{a&&g&&P()},[a,g,P]),p.useEffect(()=>{const T=i.current;if(!T)return;const A=b=>{b.key!=="Escape"||!g||(b.preventDefault(),P())};return T.addEventListener("keydown",A),()=>{T.removeEventListener("keydown",A)}},[g,P]);const N=C.supported?C.privacyMode:null,D=TS(N,o);return{supported:x,listening:S,toggle:j,textareaRef:i,toasts:f,privacyMode:N,privacyMessage:D}}const hl=new RegExp("(?<!\\w)@([\\p{L}\\p{N}._-]+)","gu");function jS(e){return new Set(Array.from(e?.excludedNames??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function jd(e,t){const n=new Set,a=[],s=[],o=jS(t),i=new RegExp(hl.source,hl.flags);let u;for(;(u=i.exec(e))!==null;){const c=u[1];o.has(c.toLowerCase())||(s.push({name:c,start:u.index,end:u.index+u[0].length}),n.has(c)||(n.add(c),a.push(c)))}return{names:a,positions:s}}const LS="composerInput composerHighlight";function MS(e,t,n=[]){const a=new Map(t.map(c=>[c.name.toLowerCase(),c])),o=jd(e,{excludedNames:n}).positions.flatMap(c=>{const d=a.get(c.name.toLowerCase());return d?[{...c,avatarColor:d.avatarColor??null}]:[]});if(o.length===0)return[{kind:"text",value:e}];const i=[];let u=0;for(const c of o)c.start>u&&i.push({kind:"text",value:e.slice(u,c.start)}),i.push({kind:"mention",value:e.slice(c.start,c.end),avatarColor:c.avatarColor}),u=c.end;return u<e.length&&i.push({kind:"text",value:e.slice(u)}),i}function ES(e){if(e)return{background:e,boxShadow:`0 0 0 0.16em ${e}`}}function DS({text:e,cats:t,excludedMentionNames:n=[]}){const a=p.useMemo(()=>MS(e,t,n),[n,e,t]);return r.jsxs("div",{className:LS,"aria-hidden":"true",children:[a.map((s,o)=>s.kind==="mention"?r.jsx("span",{className:"composerHighlightMention",style:ES(s.avatarColor),children:s.value},o):r.jsx("span",{children:s.value},o))," "]})}function BS(e){return!!(e.avatarUrl||e.avatarColor||e.isCat||e.participantId)}function OS(e){return!!(e.avatarUrl||e.avatarColor||e.isCat)}function wa({audienceParticipants:e,allParticipants:t=[],onSetAudienceKeys:n,onSingleClick:a,disabled:s,maxSelectedParticipants:o,workflowShape:i="sequential",onToggleWorkflowShape:u}){const{t:c}=z(),d=e.length>1,h=!!n&&t.length>1,[f,m]=p.useState(!1),v=p.useRef(null),[C,I]=p.useState(null),[y,g]=p.useState(null),x=new Set(e.map(M=>M.key)),S=Number.isFinite(o)?Math.max(1,Math.trunc(o??Number.POSITIVE_INFINITY)):Number.POSITIVE_INFINITY,k=h?[...e,...t.filter(M=>!x.has(M.key))]:[];p.useEffect(()=>{if(!f)return;function M(F){v.current&&!v.current.contains(F.target)&&m(!1)}return document.addEventListener("mousedown",M),()=>document.removeEventListener("mousedown",M)},[f]);const w=e[0],P=e.length-1,j=p.useCallback(M=>{if(n)if(x.has(M)){if(e.length<=1)return;n(e.filter(F=>F.key!==M).map(F=>F.key))}else{if(e.length>=S)return;n([...e.map(F=>F.key),M])}},[e,x,S,n]),N=p.useCallback((M,F)=>{I(F),M.dataTransfer.effectAllowed="move",M.dataTransfer.setData("text/plain",String(F))},[]),D=p.useCallback((M,F)=>{M.preventDefault(),M.dataTransfer.dropEffect="move",g(F)},[]),T=p.useCallback((M,F)=>{M.preventDefault();const J=C;if(I(null),g(null),!n||J===null||J===F)return;const me=e[J]?.key;if(!me)return;const K=[...e.map(B=>B.key)];K.splice(J,1),K.splice(F,0,me),n(K)},[C,e,n]),A=p.useCallback(()=>{I(null),g(null)},[]);if(!w)return null;const b=d?BS(w):OS(w),R=d?`${w.name} +${P}`:w.isCat?w.name:w.executionLabel||w.name,L=w.isCat&&w.executionLabel?`${w.name} · ${w.executionLabel}`:w.executionLabel||w.name,O=d?c(l.sharedAudienceSelectAudienceLabel):L,Y=c(i==="sequential"?l.sharedAudienceSwitchToConcurrentModeLabel:l.sharedAudienceSwitchToSequentialModeLabel),$=()=>{h?m(!f):a&&a()};return r.jsxs("div",{className:"audienceChipWrapper",ref:v,children:[r.jsxs("button",{type:"button",className:"audienceChip",disabled:s,onClick:$,"data-tooltip":O,children:[b?r.jsx("div",{className:"audienceChipAvatar",style:w.avatarUrl?{backgroundImage:`url(${w.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:w.isCat?{background:w.avatarColor??"#8B7E74"}:{background:"#fff",color:"#222",border:"1px solid rgba(0, 0, 0, 0.15)"},children:w.avatarUrl?null:Rt(w.name)}):null,r.jsx("span",{className:"audienceChipLabel",children:R}),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"})}),d&&u?r.jsx("span",{className:"audienceChipWorkflow",role:"button",tabIndex:s?-1:0,"data-tooltip":c(i==="sequential"?l.sharedAudienceWorkflowSequential:l.sharedAudienceWorkflowConcurrent),"aria-label":Y,onClick:M=>{M.stopPropagation(),u()},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(M=>{const F=x.has(M.key),J=F?e.findIndex(B=>B.key===M.key):-1,me=C===J,K=y===J;return r.jsxs("div",{className:`audiencePopoverItem${me?" isDragging":""}${K?" isDragOver":""}`,"data-tooltip":M.isCat&&M.executionLabel?`${M.name} · ${M.executionLabel}`:M.executionLabel||void 0,draggable:F,onDragStart:F?B=>N(B,J):void 0,onDragOver:F?B=>D(B,J):void 0,onDrop:F?B=>T(B,J):void 0,onDragEnd:A,children:[F?r.jsx("span",{className:"audiencePopoverDragHandle","aria-hidden":"true",children:"⋮⋮"}):r.jsx("span",{className:"audiencePopoverDragHandle audiencePopoverDragHandlePlaceholder","aria-hidden":"true"}),r.jsx("div",{className:"audiencePopoverAvatar",style:M.avatarUrl?{backgroundImage:`url(${M.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:M.isCat?{background:M.avatarColor??"#8B7E74"}:{background:"#fff",color:"#222",border:"1px solid rgba(0, 0, 0, 0.15)"},children:M.avatarUrl?null:Rt(M.name)}),r.jsx("span",{className:"audiencePopoverName",children:M.name}),r.jsx("label",{className:"audiencePopoverCheck",children:r.jsx("input",{type:"checkbox",checked:F,disabled:F&&e.length<=1||!F&&e.length>=S,onChange:()=>j(M.key)})})]},M.key)})]}):null]})}function Go(e){return{key:`cat:${e.id}`,name:e.name,executionLabel:e.defaultExecutionTarget?Zn(e):null,avatarColor:e.avatarColor??null,avatarUrl:e.avatarUrl??null,isCat:!0,catId:e.id,participantId:null}}function Ld(e){return{key:`temp:${e.participantId}`,name:e.name,executionLabel:e.provider?vr({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 Ur(e,t){const n=_o(e);return{key:t??"implicit:execution_target",name:n,executionLabel:n,avatarColor:null,avatarUrl:null,isCat:!1,catId:null,participantId:null}}function _S(e){const t=e.provider?vr({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 FS(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 WS({composerStackParticipants:e,composerBusy:t,activeWorkflowShape:n,onToggleActiveWorkflowShape:a,activeAudienceKeys:s,onSetActiveAudienceKeys:o,maxAudienceParticipants:i,onOpenSection:u}){const c=p.useMemo(()=>e.map(FS),[e]),d=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(wa,{audienceParticipants:d,allParticipants:c,onSetAudienceKeys:o,onSingleClick:()=>u("execution"),disabled:t,maxSelectedParticipants:i,workflowShape:n,onToggleWorkflowShape:a})}function Md({payload:e,composerBusy:t,composerRecipients:n,composerStackParticipants:a,directLaneCat:s,isDirectLane:o,isDefaultChatComposer:i,activeWorkflowShape:u,onToggleActiveWorkflowShape:c,activeAudienceKeys:d,onSetActiveAudienceKeys:h,onOpenSection:f}){if(s)return r.jsx(wa,{audienceParticipants:[Go(s)],onSingleClick:()=>f("execution"),disabled:t});if(!i&&a.length>0)return r.jsx(WS,{composerStackParticipants:a,composerBusy:t,activeWorkflowShape:u,onToggleActiveWorkflowShape:c,activeAudienceKeys:d,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(wa,{audienceParticipants:[Ur({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(_S);return r.jsx(wa,{audienceParticipants:v,onSingleClick:()=>f(o||i?"execution":"cats"),disabled:t})}return null}function US({hasConversationStarted:e,isCompareGroup:t,isNearBottom:n,payload:a,composerDraft:s,channelFiles:o,channelPlusMenuOpen:i,channelPlusMenuRef:u,channelFileInputRef:c,composerBusy:d,compareBusy:h,stopBusy:f,composerWorkspacePath:m,directLaneExcludedMentionNames:v,composerRecipients:C,defaultRecipientParticipantId:I,composerStackParticipants:y,isDirectLane:g,isDefaultChatComposer:x,activeWorkflowShape:S,onToggleActiveWorkflowShape:k,activeAudienceKeys:w,onSetActiveAudienceKeys:P,compareSendScope:j,showCancelComposerAction:N,showStopComposerAction:D,composerCardRef:T,composerTargetSlot:A,composerHeaderAccessory:b,composerHeaderWhereExtras:R,composerFooterAccessory:L,surfaceTag:O,onOpenSection:Y,onComposerChange:$,onComposerKeyDown:M,onSendMessage:F,onToggleChannelPlusMenu:J,onChannelFileSelect:me,onTakeScreenshot:K,screenshotCaptureDisabled:B=!1,onChannelFilesChange:ae,onScrollToBottom:be,onCompareSendScopeChange:W,onCancelPendingSend:q,onStopMessage:_e,autoResize:le}){const xe=g&&C.length===1&&C[0]?.kind==="named"?C[0]:null,Ae=xe?.catId?a.chat.cats.find(ce=>ce.id===xe.catId)??null:null,X=s.trim().length>0||o.length>0,{supported:re,listening:G,toggle:pe,textareaRef:Ie,toasts:Qe,privacyMessage:Nt}=Td({value:s,onChange:$,autoResize:le,disabled:d}),Vt=(()=>{const ce=["composerAreaStack"];return e?(ce.push("composerAreaStackDocked"),t&&ce.push("composerAreaStackDockedParallel")):ce.push("composerAreaStackFresh"),i&&ce.push("composerAreaStackMenuOpen"),ce.join(" ")})(),{t:Le}=z(),Wt=Le(h?l.chatComposerAreaPlaceholderParallelWaiting:e?l.chatComposerAreaPlaceholderReply:l.chatNewChatDraftComposerPlaceholder),Et=G?Le(l.chatNewChatDraftStopVoiceInputAria,{privacyMessageSuffix:Nt??""}):Le(l.chatNewChatDraftStartVoiceInputAria),ct=Le(j==="all_members"?l.chatNewChatDraftSendAllChatsAria:l.chatComposerAreaSendToThisChatAria),Te=Le(l.chatComposerAreaStopButtonLabel),se=Le(l.chatComposerAreaSwitchSendModeLabel);return r.jsxs("div",{className:Vt,children:[O||m||b||R?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:()=>Y("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:Xs(m)})]}):null,R]}),b?r.jsx("div",{className:"composerHeaderRight",children:b}):null]}):null,r.jsxs("form",{ref:T,className:`${e?t?"composerCard composerCardDocked composerCardDockedParallel":"composerCard composerCardDocked":"composerCard composerCardFresh"}${i?" composerCardMenuOpen":""}`,onSubmit:ce=>{F(ce)},children:[e&&!n?r.jsx("button",{className:"scrollToBottomButton",type:"button","aria-label":Le(l.chatComposerAreaScrollToLatestAria),onClick:be,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((ce,Re)=>{const Me=ce.type.startsWith("image/");return r.jsxs("div",{className:"attachmentCard",children:[r.jsx("button",{className:"attachmentRemove",type:"button",disabled:d,onClick:()=>ae(o.filter((dt,ot)=>ot!==Re)),"aria-label":Le(l.chatNewChatDraftAttachmentRemoveAria,{fileName:ce.name}),children:"×"}),Me?r.jsx("img",{className:"attachmentPreview",src:URL.createObjectURL(ce),alt:ce.name,onLoad:dt=>URL.revokeObjectURL(dt.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:ce.name})]},`${ce.name}-${ce.size}-${Re}`)})}):null,r.jsxs("div",{className:"composerInputWrapper",children:[r.jsx(DS,{text:s,cats:a.chat.cats,excludedMentionNames:v}),r.jsx("textarea",{ref:Ie,className:"composerInput composerInputOverlay",rows:1,placeholder:Wt,value:s,disabled:d,onChange:ce=>{$(ce.target.value),le(ce.target)},onKeyDown:ce=>{M(ce)}})]}),r.jsxs("div",{className:"composerBottomRow",children:[r.jsx("div",{className:"composerLeftGroup",children:r.jsxs("div",{className:"composerPlusWrapper",ref:u,children:[r.jsx("button",{className:"composerPlusButton",type:"button","aria-label":Le(l.chatComposerAreaAttachAria),disabled:d,onClick:J,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:d,onClick:me,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"})]}),Le(l.chatNewChatDraftAddPhotosAndFiles)]}),K?r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:d||B,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"})]}),Le(l.chatNewChatDraftTakeScreenshot)]}):null]}):null]})}),r.jsxs("div",{className:"composerRightGroup",children:[A??r.jsx(Md,{payload:a,composerBusy:d,composerRecipients:C,defaultRecipientParticipantId:I,composerStackParticipants:y,directLaneCat:Ae,isDirectLane:g,isDefaultChatComposer:x,activeWorkflowShape:S,onToggleActiveWorkflowShape:k,activeAudienceKeys:w,onSetActiveAudienceKeys:P,onOpenSection:Y}),re?r.jsxs("button",{className:`composerPlusButton composerVoiceButton${G?" composerVoiceButtonActive":""}`,type:"button","aria-label":Et,"aria-pressed":G,title:Nt??void 0,disabled:d,onClick:pe,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"})]}),Nt?r.jsx("span",{className:"composerVoicePrivacyBadge","aria-hidden":"true",children:"!"}):null]}):null,N?r.jsx("button",{className:"composerSendButton composerCancelButton",type:"button","aria-label":Le(l.chatNewChatDraftCancelSendAria),onClick:()=>q?.(),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"})]})}):D?r.jsx("button",{className:"composerSendButton composerStopButton",disabled:f,type:"button","aria-label":Te,onClick:()=>{_e?.()},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:!X||d||h,type:"submit","aria-label":ct,children:j==="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":se,onClick:()=>W?.(j==="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:!X||d||h,type:"submit","aria-label":Le(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:d,style:{display:"none"},onChange:ce=>{const Re=ce.currentTarget;if(Re.files&&Re.files.length>0){const Me=Array.from(Re.files);ae([...o,...Me])}Re.value=""}})]}),L?r.jsx("div",{className:"composerFooterRow",children:L}):null,r.jsx(xo,{toasts:Qe})]})}function KS(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 $S({compareMembers:e,selectedChannelId:t,comparePrevChannelId:n,compareNextChannelId:a,onSelect:s,onNavigatePrev:o,onNavigateNext:i}){const{t:u}=z(),c=u(l.chatParallelFooterDefaultModelLabel),d=h=>u(l.chatParallelFooterThreadLabel,{threadIndex:h+1});return r.jsxs("nav",{className:"parallelFooterBar","aria-label":u(l.chatParallelFooterNavigationAriaLabel),children:[r.jsx("button",{className:"parallelFooterNavButton",type:"button",disabled:!n,onClick:o,"aria-label":u(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":u(l.chatParallelFooterTabsAriaLabel),children:e.map(h=>{const f=h.channelId===t,m=KS(h,c,d(h.index));return r.jsx("button",{className:f?"parallelFooterTab parallelFooterTabActive":"parallelFooterTab",type:"button",role:"tab","aria-selected":f,title:`${m} · ${ir(h.title,u)}`,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":u(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 HS=new Set([".png",".jpg",".jpeg",".gif",".webp"]),qS=/^\[Attached files in working directory:\]\n((?:- [^\n]+\n)+)\n?/;function GS(e){const t=qS.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 u=i.slice(i.lastIndexOf(".")).toLowerCase(),c=i.split("/").pop()??i;a.push({filename:c,relativePath:i,isImage:HS.has(u)})}const s=e.slice(t[0].length);return{attachments:a,textBody:s}}const fl=/https?:\/\/[^\s<>"'\]]+/gi,ml=/\/(?:work|chat|code)\/[^\s<>"'\]]+/g,VS=new Set([".",",",";"]);function zS(e){let t=0;for(const n of e)n==="("?t+=1:n===")"&&(t-=1);return t<0}function gl(e){let t=e;for(;t.length>0;){const n=t.at(-1);if(!n)break;if(VS.has(n)){t=t.slice(0,-1);continue}if(n===")"&&zS(t)){t=t.slice(0,-1);continue}break}return t}function Cl(e,t,n,a){return e<a&&n<t}function YS(e,t,n=[]){const a=new Map;for(const g of t)a.set(g.name.toLowerCase(),g);const s=[],o=new RegExp(fl.source,fl.flags);let i;for(;(i=o.exec(e))!==null;){const g=i[0],x=gl(g);s.push({kind:"url",start:i.index,end:i.index+x.length,value:x,href:x})}const u=[],c=new RegExp(ml.source,ml.flags);let d;for(;(d=c.exec(e))!==null;){const g=d[0],x=gl(g);u.push({kind:"route",start:d.index,end:d.index+x.length,value:x,href:x})}const m=jd(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=>Cl(g.start,g.end,x.start,x.end))),v=u.filter(g=>!s.some(x=>Cl(g.start,g.end,x.start,x.end))),C=[...s,...v,...m].sort((g,x)=>g.start-x.start),I=[];let y=0;for(const g of C)g.start>y&&I.push({kind:"text",value:e.slice(y,g.start)}),g.kind==="url"||g.kind==="route"?I.push({kind:g.kind,value:g.value,href:g.href}):I.push({kind:"mention",value:g.value,avatarColor:g.avatarColor}),y=g.end;return y<e.length&&I.push({kind:"text",value:e.slice(y)}),I}function Ed({body:e,cats:t,channelId:n,disabledMentionNames:a=[]}){const{attachments:s,textBody:o}=p.useMemo(()=>GS(e),[e]),i=p.useMemo(()=>YS(o,t,a),[a,o,t]),u=s.filter(h=>h.isImage),c=s.filter(h=>!h.isImage),d=encodeURIComponent(n);return r.jsxs("div",{className:"messageBodyWrapper",children:[u.length>0?r.jsx("div",{className:"messageBodyImages",children:u.map(h=>{const f=`/api/channels/${d}/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/${d}/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(lh,{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 JS="localizedBody",XS=new Set(Object.values(l));function QS(e,t){const n=ey(e.metadata?.[JS]);return n?ZS(n,t):e.body}function ZS(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 ey(e){if(!Vo(e)||!Dd(e.key))return null;const t=ty(e.values),n=ny(e.valueKeys);return{key:e.key,...t?{values:t}:{},...n?{valueKeys:n}:{}}}function ty(e){if(!Vo(e))return null;const t={};for(const[n,a]of Object.entries(e))ay(a)&&(t[n]=a);return Object.keys(t).length>0?t:null}function ny(e){if(!Vo(e))return null;const t={};for(const[n,a]of Object.entries(e))Dd(a)&&(t[n]=a);return Object.keys(t).length>0?t:null}function ay(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function Dd(e){return typeof e=="string"&&XS.has(e)}function Vo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ry(e){const t=e?.companionReferenceSnapshots;if(!Array.isArray(t))return[];const n=[];for(const a of t){const s=sf(a);s&&n.push(s)}return n}function sy(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 oy({body:e,metadata:t}){const{t:n}=z(),a=p.useMemo(()=>cf(e),[e]),s=p.useMemo(()=>ry(t),[t]),o=p.useMemo(()=>{const h=[];for(const f of s){const m=Ao(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]),[u,c]=p.useState([]),d=p.useRef(null);return p.useEffect(()=>{if(d.current?.abort(),i.length===0){c([]);return}const h=new AbortController;d.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:sy(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 I=await C.json();if(h.signal.aborted)return;const y=I.preview??null;c(g=>{if(g[v]?.reference!==m.reference)return g;const x=g.slice();return x[v]={...g[v],loading:!1,preview:vl(y,m.fallbackSnapshot,n)},x})}catch{if(h.signal.aborted)return;c(C=>{if(C[v]?.reference!==m.reference)return C;const I=C.slice();return I[v]={...C[v],loading:!1,preview:vl(null,m.fallbackSnapshot,n)},I})}})),()=>{h.abort()}},[i,s]),u.length===0?null:r.jsx("ul",{className:"companionMessageReferenceList","aria-label":n(l.chatCompanionMessageReferenceListAria),children:u.map((h,f)=>r.jsx("li",{className:"companionMessageReferenceItem",children:uy(h,n)},`${h.rawText}-${f}`))})}function vl(e,t,n){return e?e.availability!=="available"&&t?{...e,title:e.title===""||dy(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:iy(e.availability,n),catName:e.catName==="Companion"?ly(n):e.catName,description:e.availability==="inaccessible"?cy(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 iy(e,t){return t(e==="missing"?l.chatCompanionMessageReferenceMissingFallbackTitle:e==="deleted"?l.chatCompanionMessageReferenceDeletedFallbackTitle:l.chatCompanionMessageReferenceInaccessibleFallbackTitle)}function ly(e){return e(l.chatCompanionMessageReferenceUnknownCompanionLabel)}function cy(e,t){return e||t(l.chatCompanionMessageReferenceInaccessibleFallbackDescription)}function dy(e,t){return e.length===0||!!t}function uy(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:["(",py(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${fy(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:my(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:hy(n.availability,t)})]})}function py(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 hy(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 fy(e){return e.length===0?e:e.charAt(0).toUpperCase()+e.slice(1)}function my(e,t){return e.generatedTitleKind==="post"?t(l.chatCompanionMessageReferenceUntitledPostTitle):e.generatedTitleKind==="source"?t(l.chatCompanionMessageReferenceUntitledSourceTitle):e.title}function gy(e,t){return e.status==="skipped"?"Skipped requested choices.":e.answers.map(a=>{const s=t?.find(u=>u.question===a.question),i=[...a.selectedOptionIds.map(u=>s?.options.find(c=>c.id===u)?.label??u),...a.customText?[a.customText]:[]];return`Q: ${a.question}
|
|
3
|
-
A: ${i.length>0?i.join(", "):"Skipped"}`}).join(`
|
|
4
|
-
|
|
5
|
-
`)}function sr(e,t){return e?.answers.find(n=>n.question===t)??null}function Cy({channelId:e,messageId:t,choices:n,existingResponse:a,busy:s,onSubmit:o}){const{t:i}=z(),[u,c]=p.useState(()=>Object.fromEntries(n.map(S=>[S.question,sr(a,S.question)?.selectedOptionIds??[]]))),[d,h]=p.useState(()=>Object.fromEntries(n.map(S=>[S.question,sr(a,S.question)?.customText??""]))),[f,m]=p.useState(()=>Object.fromEntries(n.map(S=>[S.question,!!sr(a,S.question)?.customText]))),v=s||!!a,C=n.some(S=>S.allowSkip);function I(S,k){const w=sr(a,S);return w?w.selectedOptionIds.includes(k):(u[S]??[]).includes(k)}function y(S,k,w=!1){v||c(P=>{const j=new Set(P[S]??[]);return w?(j.has(k)?j.delete(k):j.add(k),{...P,[S]:Array.from(j)}):{...P,[S]:j.has(k)?[]:[k]}})}function g(){return n.every(S=>{const k=u[S.question]??[],w=d[S.question]?.trim()??"";return k.length>0||w.length>0})}function x(S){const k=new Date().toISOString(),w={sourceMessageId:t,status:S,submittedAt:k,answers:n.map(P=>({question:P.question,selectedOptionIds:S==="skipped"?[]:u[P.question]??[],...S==="skipped"?{skipped:!0}:{},...S!=="skipped"&&d[P.question]?.trim()?{customText:d[P.question].trim()}:{}}))};o({channelId:e,body:gy(w,n),choiceResponse:w})}return r.jsxs("div",{className:"messageChoices",children:[n.map(S=>r.jsxs("section",{className:"messageChoiceSection",children:[r.jsx("p",{className:"messageChoiceQuestion",children:S.question}),r.jsxs("div",{className:"messageChoiceOptions",children:[S.options.map(k=>{const w=I(S.question,k.id);return r.jsx("button",{className:w?"messageChoiceButton messageChoiceButtonSelected":"messageChoiceButton",type:"button",disabled:v,title:k.description,onClick:()=>y(S.question,k.id,S.multiSelect),children:k.label},`${t}:${S.question}:${k.id}`)}),S.allowCustom?r.jsx("button",{className:f[S.question]?"messageChoiceButton messageChoiceButtonSelected":"messageChoiceButton",type:"button",disabled:v,onClick:()=>m(k=>({...k,[S.question]:!k[S.question]})),children:i("sharedMessageChoicesCustom")}):null]}),S.allowCustom&&f[S.question]?r.jsx("textarea",{className:"messageChoiceCustomInput",rows:2,value:a?sr(a,S.question)?.customText??"":d[S.question]??"",disabled:v,placeholder:i("sharedMessageChoicesAddCustomPlaceholder"),onChange:k=>h(w=>({...w,[S.question]:k.target.value}))}):null]},`${t}:${S.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 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("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 Iy(){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 Bd(){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 Od({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(Bd,{})}),i.open?r.jsx("div",{className:"messageActionPopover",children:i.items.map(u=>r.jsxs("div",{children:[u.dividerBefore?r.jsx("div",{className:"messageActionPopoverDivider"}):null,r.jsx("button",{type:"button",disabled:u.disabled===!0,onClick:u.onSelect,children:u.label})]},u.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(vy,{})}):null]})}const Sy=[{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:u,isCompareGroup:c,relayMenuOpen:d,userTurnStatus:h,retryBusy:f,existingChoiceResponse:m=null,onChoiceSubmit:v,onRetryMessage:C,onCopyMessage:I,onToggleRelayMenu:y,onCloseRelayMenu:g,onRelayMessage:x,extraActions:S=[],resolveMessageParticipant:k,resolveParticipantCatRecord:w,buildParticipantAvatarClassName:P,buildParticipantAvatarStyle:j,resolveParticipantAvatarUrl:N,resolveParticipantDisplayName:D,showSpeakerHeader:T=!0}){const{t:A}=z(),b=ch(e,n,A),R=QS(e,A),L=k(e),O=w(L),Y=[...S];return e.senderKind==="user"&&h==="failed"&&C&&Y.push({key:`retry:${e.id}`,title:A(l.chatTranscriptMessageRetryResponseLabel),icon:r.jsx(Iy,{}),disabled:f,onSelect:()=>{C(e.id)}}),c&&e.senderKind!=="user"&&x&&Y.push({key:`relay:${e.id}`,kind:"menu",title:A(l.chatTranscriptMessageRelayToOthersLabel),icon:r.jsx(Bd,{}),disabled:i,open:d,onToggle:y,items:Sy.map(($,M)=>({key:$.command,label:A($.titleLabel),disabled:i,dividerBefore:M===2||M===4,onSelect:()=>{g(),x(e.id,$.command)}}))}),r.jsxs("article",{className:t,children:[r.jsxs("div",{className:dh(e.senderKind),children:[T&&e.senderKind!=="user"&&e.senderKind!=="system"?L?r.jsxs("div",{className:"transcriptMessageTop",children:[r.jsx("div",{className:P(L,{transcript:!0,catRecord:O}),style:j(L,O),children:N(L,O)?null:Rt(D(L,O))}),r.jsx("strong",{children:D(L,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:Rt(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,R?r.jsx(Ed,{body:R,cats:n,channelId:s,disabledMentionNames:o}):null,r.jsx(oy,{body:R,metadata:e.metadata}),e.senderKind==="user"&&h==="failed"?r.jsx("div",{className:"userTurnStatus userTurnStatusFailed",children:A(l.chatTranscriptMessageFailedStatusLabel)}):null]}),r.jsx(Od,{senderKind:e.senderKind,showDefaultCopyAction:R.trim().length>0,copyActionLabel:A(l.chatTranscriptMessageCopyLabel),onCopyMessage:()=>{I(R)},extraActions:Y}),e.choices&&e.choices.length>0?r.jsx(Cy,{channelId:s,messageId:e.id,choices:e.choices,existingResponse:m,busy:u,onSubmit:v}):null]})}const by=/^(?:[ \t]*\r?\n)+/u;function xy(e){return e.replace(by,"")}function wy(e){return e.status==="error"?e.kind!=="status"||e.text.trim().length>0:!1}function ky(e,t){return e.kind==="text"||t||wy(e)}function Py(e,t){return e==="streaming"&&t!=null&&t.kind!=="text"&&t.status==="streaming"}function Ay(e){switch(e){case"streaming":return"compareCard compareCardStreaming";case"sealed":return"compareCard compareCardSealed";default:return"compareCard"}}function ur(e,t){return(e%t+t)%t}const Ry=2;function Ny(e,t){const n=e.length;if(n===0)return{normalizedStartIndex:0,showNav:!1,singleVisibleCard:!1,total:0,visibleIndices:[],visibleItems:[]};const a=ur(t,n);return n<=Ry?{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,ur(a+1,n)],visibleItems:[e[a],e[ur(a+1,n)]]}}function Ty(){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 jy(e){const{segments:t,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i,showProgressDetails:u}=e,{t:c}=z(),d=t[0]?.id??null,h=t.flatMap(S=>{const k=as(S,S.id===d,e,c);return k.shouldRender?[{segment:S,presentation:k}]:[]}),[f,m]=p.useState(0),{normalizedStartIndex:v,showNav:C,singleVisibleCard:I,total:y,visibleIndices:g,visibleItems:x}=Ny(h,f);return r.jsxs("div",{className:C?"compareCardsCarousel compareCardsCarouselNavVisible":"compareCardsCarousel",children:[C?r.jsx("button",{type:"button",className:"compareCardsNavButton compareCardsNavPrev",onClick:()=>m(ur(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:I?"compareCardsGrid compareCardsGridSingle":"compareCardsGrid",children:x.map(({segment:S,presentation:k})=>{const w=!!(k.segmentParticipant||k.speakerCat||k.speakerLabel),P=ts(S),j=rs(k,c);return r.jsxs("article",{className:Ay(S.phase),children:[r.jsxs("div",{className:"compareCardHeader",children:[w?r.jsx(zo,{segmentParticipant:k.segmentParticipant,segmentParticipantCat:k.segmentParticipantCat,speakerCat:k.speakerCat,speakerLabel:k.speakerLabel,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i}):null,P?r.jsx("div",{className:"compareCardActions",children:r.jsx("button",{type:"button",className:"compareCardActionIcon",onClick:()=>{ns(P)},"aria-label":j,title:j,children:r.jsx(Ty,{})})}):null]}),r.jsx("div",{className:"compareCardBody",children:r.jsx(ss,{segment:S,renderedBlocks:k.renderedBlocks,showTrailingDots:k.showTrailingDots,showProgressDetails:u})})]},S.id)})}),C?r.jsx("button",{type:"button",className:"compareCardsNavButton compareCardsNavNext",onClick:()=>m(ur(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:S},k)=>r.jsx("button",{type:"button",className:g.includes(k)?"compareCardsPaginationDot compareCardsPaginationDotActive":"compareCardsPaginationDot",onClick:()=>m(k),"aria-label":c(l.chatCompareCardsPaginationItemAriaLabel,{cardIndex:k+1})},S.id))}):null]})}function Il(){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 Ly(e){return!!(e.segmentParticipant||e.speakerCat||e.speakerLabel)}function My(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 Ey(){return r.jsx("span",{className:"focusRailSecondaryAnonymousIndicator","aria-hidden":"true",children:r.jsx("span",{className:"focusRailSecondaryAnonymousDot"})})}function Dy({hasSpeakerIdentity:e,isActive:t,isExpanded:n}){return!e&&(!t||n)}function By(e){const{segments:t,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i,showProgressDetails:u}=e,{t:c}=z(),[d,h]=p.useState(null),f=c(l.chatFocusRailUnnamedResponseLabel),m=t[0]??null,v=m?t.filter(y=>y.id!==m.id):[],C=m?as(m,!0,e,c):null,I=C?rs(C,c):null;return r.jsxs("div",{className:"focusRailContainer",children:[m&&C?.shouldRender?(()=>{const y=ts(m);return r.jsxs("article",{className:"focusRailPrimary",children:[r.jsxs("div",{className:"focusRailPrimaryHeader",children:[r.jsx(zo,{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:()=>{ns(y)},"aria-label":I??void 0,title:I??void 0,children:r.jsx(Il,{})})}):null]}),r.jsx(ss,{segment:m,renderedBlocks:C.renderedBlocks,showTrailingDots:C.showTrailingDots,showProgressDetails:u})]})})():null,v.length>0?r.jsx("div",{className:"focusRailSecondaries",children:v.map(y=>{const g=as(y,!1,e,c);if(!g.shouldRender)return null;const x=ts(y),S=d===y.id,k=y.phase==="streaming"||y.phase==="waiting",w=Ly(g),P=k&&!S,j=Dy({hasSpeakerIdentity:w,isActive:k,isExpanded:S}),N=My(g,S,f,c),D=rs(g,c);return r.jsxs("div",{className:"focusRailSecondarySlot",children:[r.jsxs("button",{type:"button",className:"focusRailSecondaryHeader",onClick:()=>h(S?null:y.id),"aria-label":N,title:N,"aria-expanded":S,children:[w?r.jsx(Fy,{segmentParticipant:g.segmentParticipant,segmentParticipantCat:g.segmentParticipantCat,speakerCat:g.speakerCat,speakerLabel:g.speakerLabel,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i}):j?r.jsx(Ey,{}):null,P?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:S?"focusRailExpandIcon focusRailExpandIconOpen":"focusRailExpandIcon",children:"›"})]}),S?r.jsxs("div",{className:"focusRailSecondaryBody",children:[r.jsx(ss,{segment:y,renderedBlocks:g.renderedBlocks,showTrailingDots:g.showTrailingDots,showProgressDetails:u}),x?r.jsx("div",{className:"focusRailSecondaryFooter",children:r.jsx("button",{type:"button",className:"focusRailActionIcon",onClick:()=>{ns(x)},"aria-label":D,title:D,children:r.jsx(Il,{})})}):null]}):null]},y.id)})}):null]})}function ts(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 ns(e){try{await navigator.clipboard.writeText(e)}catch{}}function Oy(e,t,n,a,s,o=ps){if(!ky(e,s))return null;if(e.kind==="text"){const i=xy(e.text);return i.trim()?r.jsx(Ed,{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:_d(e.text,null,o)},e.id):null}function as(e,t,n,a=ps){const{cats:s,liveSpeakerParticipant:o,liveSpeakerParticipantCat:i,resolveLiveIndicatorSegmentParticipant:u,resolveParticipantCatRecord:c,selectedChannelId:d,disabledMentionNames:h,showProgressDetails:f,resolveParticipantDisplayName:m}=n,v=u(e),C=c(v),I=(()=>{const b=e.speakerLabel?.trim();return e.participantId==="orchestrator"?uh(b):b||null})(),y=!!(v||e.catId||I),g=v??(!y&&t?o:null),x=v?C:!y&&t?i:null,S=g?m(g,x):null,k=e.catId?s.find(b=>b.id===e.catId)??null:null,w=S??x?.name??k?.name??I,P=[...e.contentBlocks].sort((b,R)=>b.index-R.index),j=P.at(-1),N=Py(e.phase,j),D=P.map(b=>Oy(b,s,d,h,f,a)).filter(b=>b!=null),T=!!(e.participantId||e.catId||e.speakerLabel),A=e.phase==="waiting"||D.length>0||f&&e.progressText.trim().length>0||e.phase==="streaming"&&(Sc(e)||T)||N;return{segmentParticipant:g,segmentParticipantCat:x,segmentParticipantDisplayName:S,speakerCat:k,speakerLabel:w,renderedBlocks:D,showTrailingDots:N,shouldRender:A}}function _y(e,t=ps){return e.segmentParticipantDisplayName??e.segmentParticipantCat?.name??e.speakerCat?.name??e.speakerLabel?.trim()??t(l.chatFocusRailUnnamedResponseLabel)}function rs(e,t=ps){const n=_y(e,t),a=t(l.chatFocusRailUnnamedResponseLabel);return n===a?t(l.chatConcurrentCopyUnnamedResponseLabel):t(l.chatConcurrentCopyLabeledResponseLabel,{speakerName:n})}function zo({segmentParticipant:e,segmentParticipantCat:t,speakerCat:n,speakerLabel:a,bossCatId:s,buildParticipantAvatarClassName:o,buildParticipantAvatarStyle:i,resolveParticipantAvatarUrl:u,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:u(e,t)?null:Rt(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:Rt(n.name)}),r.jsx("strong",{children:n.name})]}):a?r.jsx("div",{className:"transcriptMessageTop",children:r.jsx("strong",{children:a})}):null}function Fy({segmentParticipant:e,segmentParticipantCat:t,speakerCat:n,speakerLabel:a,bossCatId:s,buildParticipantAvatarClassName:o,buildParticipantAvatarStyle:i,resolveParticipantAvatarUrl:u,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:u(e,t)?null:Rt(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:Rt(n.name)}),r.jsx("span",{className:"focusRailSecondaryName",children:n.name})]}):a?r.jsx("span",{className:"focusRailSecondaryName",children:a}):null}function ss({segment:e,renderedBlocks:t,showTrailingDots:n,showProgressDetails:a}){const{t:s}=z();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:_d(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 _d(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 Wy(e){const{segments:t,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i,showProgressDetails:u}=e,{t:c}=z(),d=t.at(-1)?.id??null;return r.jsx(r.Fragment,{children:t.map(h=>{const f=h.id===d,m=as(h,f,e,c);if(!m.shouldRender)return null;const v=h.phase==="sealed"?ts(h):"",C=v.trim().length>0;return r.jsxs("article",{className:"transcriptMessageStack transcriptMessageStackAgent typingIndicator",children:[r.jsxs("div",{className:"transcriptMessage transcriptMessageAgent",children:[r.jsx(zo,{segmentParticipant:m.segmentParticipant,segmentParticipantCat:m.segmentParticipantCat,speakerCat:m.speakerCat,speakerLabel:m.speakerLabel,bossCatId:n,buildParticipantAvatarClassName:a,buildParticipantAvatarStyle:s,resolveParticipantAvatarUrl:o,resolveParticipantDisplayName:i}),r.jsx(ss,{segment:h,renderedBlocks:m.renderedBlocks,showTrailingDots:m.showTrailingDots,showProgressDetails:u})]}),r.jsx(Od,{senderKind:"agent",showDefaultCopyAction:C,copyActionLabel:rs(m,c),onCopyMessage:C?(()=>{ns(v)}):void 0})]},h.id)})})}function Uy({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 Fd(e){const{mode:t,actions:n=[],...a}=e,s=(()=>{switch(t){case"compare_cards":return r.jsx(jy,{...a});case"focus_rail":return r.jsx(By,{...a});default:return r.jsx(Wy,{...a})}})();return n.length===0?s:r.jsxs("div",{className:"clusterActionBarWrapper",children:[s,r.jsx(Uy,{actions:n})]})}function La(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function Ky(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function $y(e){return La(e.metadata?.event)}function Hy(e){return La(e.metadata?.turnId)}function qy(e){return La(e.metadata?.targetStateId)}function Gy(e){return La(e.metadata?.laneId)}function Vy(e){return La(e.metadata?.targetId)}function zy(e){return La(e.metadata?.sourceMessageId)}function Sl(e){return Ky(e.metadata?.segmentIndex)}function Yy(e){return e.workflowShape!=="concurrent"?!1:e.targetStatuses.filter(t=>t.depth===0&&t.source===null).length>1}function Jy(e){return e.targetStatuses.filter(t=>t.depth===0&&t.source===null)}function Wd(e,t){return t.laneId?.trim()||Yr(e.id,t.id,t.participant.participantId)}function Xy(e,t){return{id:e,index:0,kind:"text",status:"complete",title:null,text:t,toolName:null,toolId:null,metadata:null}}function Qy(e){const{turn:t,target:n,visibleMessages:a}=e,s=new Set(n.response?.messageIds??[]),o=Wd(t,n);return[...a.filter(u=>{if($y(u)!=="assistant_turn_segment")return!1;if(s.has(u.id))return!0;if(Hy(u)!==t.id)return!1;const c=qy(u);if(c&&c===n.id)return!0;const d=Gy(u);return d&&d===o?!0:zy(u)===t.sourceMessageId&&Vy(u)===n.participant.participantId})].sort((u,c)=>{const d=Sl(u)??0,h=Sl(c)??0;return d!==h?d-h:u.createdAt.localeCompare(c.createdAt)})}function Zy(e){const{turn:t,visibleMessages:n,visibleMessageIndexById:a}=e,s=Jy(t);if(s.length<=1)return null;const o=[],i=new Set;let u=null,c=Number.POSITIVE_INFINITY;for(let h=0;h<s.length;h+=1){const f=s[h],m=Qy({turn:t,target:f,visibleMessages:n}),v=f.response?.fullText??m.map(I=>I.body).join(""),C=v.trim();if(!(!C&&m.length===0)){for(const I of m){i.add(I.id);const y=a.get(I.id)??Number.POSITIVE_INFINITY;y<c&&(c=y,u=I.id)}o.push(Cn({phase:"sealed",sourceMessageId:t.sourceMessageId,laneId:Wd(t,f),targetStateId:f.id,segmentIndex:h,sessionId:f.sessionId,participantId:f.participant.participantId,speakerLabel:f.participant.participantName,contentBlocks:C?[Xy(`${t.id}:${f.id}:text`,v)]:[]}))}}if(o.length<=1||u==null)return null;const d=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:[...d]},firstVisibleMessageId:u,visibleMessageIds:i}}function eb(e){const t=new Map(e.visibleMessages.map((a,s)=>[a.id,s]));return[...Array.isArray(e.workflow.turnHistory)?e.workflow.turnHistory:[]].reverse().filter(Yy).map(a=>Zy({turn:a,visibleMessages:e.visibleMessages,visibleMessageIndexById:t})).filter(a=>a!=null)}function tb(e){const t=new Map,n=new Set;for(const s of eb(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 nb(e){const{liveIndicator:t,concurrentPresentationMode:n="inline_stack",concurrentActions:a}=e,s=ze(t);return s.length===0?null:r.jsx(Fd,{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 ab({hasConversationStarted:e,greeting:t,transcriptListRef:n,bottomSentinelRef:a,selectedChannel:s,visibleMessages:o,workflow:i,cats:u,bossCatId:c,selectedChannelId:d,disabledMentionNames:h,busy:f,compareBusy:m,isCompareGroup:v,choiceResponsesBySource:C,onChoiceSubmit:I,latestUserTurnMessageId:y,latestUserTurnStatus:g,onRetryMessage:x,onRelayMessage:S,liveIndicator:k,liveSpeakerParticipant:w,liveSpeakerParticipantCat:P,resolveLiveIndicatorSegmentParticipant:j,messageStackTone:N,resolveMessageParticipant:D,resolveParticipantCatRecord:T,buildParticipantAvatarClassName:A,buildParticipantAvatarStyle:b,resolveParticipantAvatarUrl:R,resolveParticipantDisplayName:L,showLiveProgressDetails:O=!1,resolveConcurrentClusterPresentationMode:Y,buildConcurrentClusterActions:$,buildTranscriptMessageActions:M}){const[F,J]=p.useState(null);p.useEffect(()=>{if(!F)return;function W(q){q.target?.closest(".messageActionMenu")||J(null)}return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[F]);async function me(W){try{await navigator.clipboard.writeText(W)}catch{}}if(!e)return r.jsx("section",{className:"freshChatIntro",children:r.jsx("div",{className:"draftGreeting",children:r.jsx("h1",{children:t})})});const K=!!(k?.active&&ze(k).length>0),B=k?.active?ze(k):[],ae=tb({visibleMessages:o,workflow:i});function be(W){return r.jsx(yy,{message:W,stackClassName:N(W.senderKind),cats:u,bossCatId:c,selectedChannelId:d,disabledMentionNames:h,compareBusy:m,choiceBusy:hh(f,W.id),isCompareGroup:v,relayMenuOpen:F===W.id,userTurnStatus:W.senderKind==="user"&&W.id===y?g:"idle",retryBusy:ph(f),existingChoiceResponse:C.get(W.id)??null,onChoiceSubmit:I,onRetryMessage:x,onCopyMessage:me,onToggleRelayMenu:()=>J(q=>q===W.id?null:W.id),onCloseRelayMenu:()=>J(null),onRelayMessage:S,extraActions:M?.({message:W,selectedChannel:s})??[],resolveMessageParticipant:D,resolveParticipantCatRecord:T,buildParticipantAvatarClassName:A,buildParticipantAvatarStyle:b,resolveParticipantAvatarUrl:R,resolveParticipantDisplayName:L,showSpeakerHeader:!0},W.id)}return r.jsx("section",{className:"transcriptPanel",children:r.jsxs("div",{ref:n,className:"transcriptList",children:[ae.map(W=>{if(W.kind==="concurrent_cluster"){const q={turnId:W.turnId,sourceMessageId:W.sourceMessageId,segmentCount:W.segments.length,clusterKind:"durable"},_e=Y(q);if(_e==="inline_stack")return W.messages.map(xe=>be(xe));const le=$?.({...q,resolvedMode:_e})??[];return r.jsx(Fd,{mode:_e,segments:W.segments,cats:u,bossCatId:c,selectedChannelId:d,disabledMentionNames:h,liveSpeakerParticipant:null,liveSpeakerParticipantCat:null,resolveLiveIndicatorSegmentParticipant:j,resolveParticipantCatRecord:T,buildParticipantAvatarClassName:A,buildParticipantAvatarStyle:b,resolveParticipantAvatarUrl:R,resolveParticipantDisplayName:L,showProgressDetails:O,actions:le},W.key)}return be(W.message)}),K&&k?r.jsx(nb,{cats:u,bossCatId:c,selectedChannelId:d,disabledMentionNames:h,liveIndicator:k,liveSpeakerParticipant:w,liveSpeakerParticipantCat:P,resolveLiveIndicatorSegmentParticipant:j,resolveParticipantCatRecord:T,buildParticipantAvatarClassName:A,buildParticipantAvatarStyle:b,resolveParticipantAvatarUrl:R,resolveParticipantDisplayName:L,showProgressDetails:O,concurrentPresentationMode:(()=>{const W=i.activeTurn?.id;return W?Y({turnId:W,sourceMessageId:k.sourceMessageId??i.activeTurn?.sourceMessageId??"",segmentCount:B.length,clusterKind:"live"}):"inline_stack"})(),concurrentActions:(()=>{const W=i.activeTurn?.id;if(!W||!$)return[];const q=Y({turnId:W,sourceMessageId:k.sourceMessageId??i.activeTurn?.sourceMessageId??"",segmentCount:B.length,clusterKind:"live"});return $({turnId:W,sourceMessageId:k.sourceMessageId??i.activeTurn?.sourceMessageId??"",segmentCount:B.length,clusterKind:"live",resolvedMode:q})})()}):null,r.jsx("div",{ref:a,className:"transcriptBottomSentinel","aria-hidden":"true"})]})})}const rb=720,sb=2,ob=4;function ib(e){return e.explicitOverride?e.explicitOverride:e.workflowRecommendation?e.workflowRecommendation:e.userDefault!=="adaptive"?e.userDefault:e.viewportWidth>=rb&&e.segmentCount>=sb&&e.segmentCount<=ob?"compare_cards":"inline_stack"}const os="cats.concurrent-cluster-ui-state",lb=200,yl=new Set;function cb(e,t){return t instanceof Error?`${e}:${t.name||"Error"}`:`${e}:${typeof t}`}function uo(e,t){const n=cb(e,t);if(yl.has(n)||(yl.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 db(e){if(!e||typeof e!="object")return null;const t=e.presentationOverride;return t!=="inline_stack"?null:{presentationOverride:t}}function vs(e,t=lb){const n=Object.entries(e);return n.length<=t?e:Object.fromEntries(n.slice(-t))}function Ud(e,t){return`${e}:${t}`}function ub(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=db(s);o&&(n[a]=o)}return vs(n)}catch{return{}}}function pb(e){if(!e)return{value:{},requiresPersistedCleanup:!1};let t=null;try{t=e.getItem(os)}catch(s){return uo("read",s),{value:{},requiresPersistedCleanup:!1}}if(!t)return{value:{},requiresPersistedCleanup:!1};const n=ub(t),a=JSON.stringify(n)!==t;return{value:n,requiresPersistedCleanup:a}}function hb(e,t){let n=Object.keys(t).length;for(;n>1;){n=Math.floor(n/2);const a=vs(t,n);try{return e.setItem(os,JSON.stringify(a)),a}catch{}}return null}function fb(e,t){if(!e)return t;const n=vs(t);try{return e.setItem(os,JSON.stringify(n)),n}catch(a){const s=hb(e,n);if(s!==null)return s;if(typeof e.removeItem=="function")try{return e.removeItem(os),uo("write",a),{}}catch{}return uo("write",a),t}}function mb(e,t){const n=Ud(t.channelId,t.turnId),a={presentationOverride:"inline_stack"};return e[n]?.presentationOverride===a.presentationOverride?e:vs({...e,[n]:a})}function gb(e){const t=e.uiStateByKey[Ud(e.channelId,e.turnId)]??null;return ib({explicitOverride:t?.presentationOverride??null,workflowRecommendation:null,userDefault:e.userDefault,segmentCount:e.segmentCount,viewportWidth:e.viewportWidth})}function bl(e){if(typeof e!="string")return null;const t=e.trim();return t||null}function Cb(e,t){const n=bl(e);if(n)return n;const a=bl(t);return a||null}function pr(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:vo(e.modelSelection),isBoss:e.isBoss??!1}}function vb(e,t){return pr({catId:e.id,name:e.name,executionLabel:Zn(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 Ib(e){const t=vr({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:vo(e.modelSelection)}}function Sb(e,t,n){return t&&e.some(a=>a.channelId===t)?t:e.some(a=>a.channelId===n)?n:e[0]?.channelId??n}function xl(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 Kd=ea("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 bb(e){const t=e.compareGroup?.members??[],n=t.length>1,a=Sb(t,e.routeChannelId,e.selectedChannelId),s=t.findIndex(c=>c.channelId===a),o=t.map(c=>e.channels.find(d=>d.id===c.channelId)??null).filter(c=>c!=null),i=gn(e.busy),u=o.some(c=>c.routingStatus==="running");return{compareMembers:t,isCompareGroup:n,activeCompareChannelId:a,compareMemberIndex:s,compareBusy:i||u,comparePrevChannelId:n&&s>=0?xl(t,a,"prev"):null,compareNextChannelId:n&&s>=0?xl(t,a,"next"):null}}function xb(e){const t=e.t??Kd;return e.isDirectLane?e.directLaneCat?.name??e.defaultRecipientCatRecord?.name??ir(e.selectedChannelTitle,t):e.isCompareGroup&&e.compareGroup?ir(e.compareGroup.title,t):ir(e.selectedChannelTitle,t)}function wb(e){return e.isDirectLane?!!e.defaultRecipientCat:!!(e.showBossCatAvatar&&!e.isDefaultChatComposer||e.activeRoomParticipants.length>0)}function kb(e){return e.activeRoomParticipants.map(t=>{const n=e.resolveParticipantCatRecord(t),a=Qn(t)??(n?.defaultExecutionTarget?Zn(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 Pb(e){const t=new Map;for(const n of e)n.choiceResponse?.sourceMessageId&&t.set(n.choiceResponse.sourceMessageId,n.choiceResponse);return t}function Ab(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(d=>d.trim().length>0)??[];return c.length>0?[...new Set(c)]:e.visibleLiveIndicator?.active&&e.visibleLiveIndicator.catId?[e.visibleLiveIndicator.catId]:[]})(),s=(()=>{if(!t)return[];const d=(e.selectedChannel.roomRouting?.workflow?.activeTurn?.targetStatuses??[]).filter(h=>h.status==="running").map(h=>h.participant.participantId).filter(h=>h.trim().length>0);return d.length>0?[...new Set(d)]: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,u=o?e.activeRoomParticipants.find(c=>c.participantId===o)??null:i?e.activeRoomParticipants.find(c=>es(c)===i)??null:null;return{activeTopBarCatIds:a,activeTopBarParticipantIds:s,liveSpeakerParticipant:u}}function Rb(e){if(e.isDirectLane&&e.directLaneCat)return[pr({participantId:e.defaultRecipientParticipant?.participantId,catId:e.directLaneCat.id,name:e.directLaneCat.name,executionLabel:e.defaultRecipientParticipant?Qn(e.defaultRecipientParticipant):Zn(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[Ib(e.selectedExecutionTarget)];if(!e.defaultRecipientParticipant)return[];const t=e.resolveParticipantCatRecord(e.defaultRecipientParticipant);return t?[pr({participantId:e.defaultRecipientParticipant.participantId,catId:t.id,name:t.name,executionLabel:Qn(e.defaultRecipientParticipant)??Zn(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})]:[pr({participantId:e.defaultRecipientParticipant.participantId,name:e.resolveParticipantDisplayName(e.defaultRecipientParticipant,null),executionLabel:Qn(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 Nb(e){const t=e.t??Kd,n=gn(e.busy,"ack")||Nc(e.busy,e.selectedChannelId),a=gn(e.busy),s=Nm(e.busy,e.selectedChannelId),o=n||s||a,i=n&&e.onCancelPendingSend!=null,u=!e.isCompareGroup&&s&&e.onStopMessage!=null,c=e.isCompareGroup&&e.onStopMessage!=null&&(gn(e.busy,"dispatch")||gn(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&&(u||c),composerWorkspacePath:Cb(e.repoPath,e.chatCwd)}}let Mr=null,Er=null;function Tb(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 wl(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(Tb).join(";")}function jb(e,t){(typeof document>"u"?p.useEffect:p.useLayoutEffect)(e,t)}function iw({payload:e,selectedChannel:t,routeChannelId:n=null,operatorSnapshot:a,operatorLoading:s,operatorError:o,composerDraft:i,busy:u,feedback:c,greeting:d,channelFiles:h,channelPlusMenuOpen:f,channelPlusMenuRef:m,channelFileInputRef:v,activeAssignedCats:C,bossCatName:I,bossCatAvatarColor:y,showBossCatAvatar:g,onComposerChange:x,onComposerKeyDown:S,onSendMessage:k,onCancelPendingSend:w,onStopMessage:P,onToggleChannelPlusMenu:j,onChannelFileSelect:N,onTakeScreenshot:D,screenshotCaptureDisabled:T,onChannelFilesChange:A,onApprovalDecision:b,onChoiceSubmit:R,onRetryMessage:L,onStartFresh:O,onOperatorAction:Y,autoResize:$,selectedExecutionTarget:M,onExecutionTargetChange:F,onDirectLaneExecutionTargetChange:J,activeWorkflowShape:me="sequential",onToggleActiveWorkflowShape:K,activeAudienceKeys:B=null,onSetActiveAudienceKeys:ae,onSelect:be,onOpenAddCat:W,showAddCatButton:q=!0,behaviorSurface:_e="chat",liveIndicator:le,compareGroup:xe=null,compareSendScope:Ae="all_members",onCompareSendScopeChange:X,onRelayMessage:re,onUpdateChannelParticipant:G,buildTranscriptMessageActions:pe,renderStatusRow:Ie,renderTopBarExtraActions:Qe,renderComposerTargetSlot:Nt,renderComposerHeaderAccessory:Vt,renderComposerHeaderWhereExtras:Le,renderComposerFooterAccessory:Wt,renderComposerSurfaceTag:Et,buildSidePanelSections:ct,sidePanelTitle:Te=""}){const{t:se}=z(),ce=Na(),Re=Te||se(l.chatNewChatDraftSidePanelTitle),Me=p.useMemo(()=>fh(e.chat.conversationBehavior,_e),[_e,e.chat.conversationBehavior]),dt=t.messages.filter(U=>Me.showVerboseMessages||U.metadata?.verbosity!=="verbose"),ot=dt.length>0,tt=p.useMemo(()=>lm(le,dt,t.roomRouting.workflow.activeTurn?.updatedAt??null,t.messages),[le,t.messages,t.roomRouting.workflow.activeTurn?.updatedAt,dt]),{visibleLiveIndicator:Se,transcriptScrollKey:Fe}=tt,it=Vr(t),zt=p.useMemo(()=>bb({compareGroup:xe,channels:e.chat.channels,routeChannelId:n,selectedChannelId:t.id,busy:u}),[u,xe,e.chat.channels,n,t.id]),{compareMembers:Yt,isCompareGroup:St,activeCompareChannelId:Tt,compareMemberIndex:ge,compareBusy:ke,comparePrevChannelId:Ne,compareNextChannelId:Dt}=zt,Ye=oc(it),V=zr(it),{activeRoomParticipants:Ke,defaultRecipientParticipant:nt,defaultRecipientCat:xt,directLaneCat:gt,defaultRecipientCatRecord:Jt,assignedCatRecords:Ut,assignedAdhocParticipants:at,topBarParticipants:jt,resolveParticipantCatRecord:Pe,resolveParticipantDisplayName:rt,resolveParticipantAvatarUrl:na,buildParticipantAvatarStyle:jn,buildParticipantAvatarClassName:sn,resolveMessageParticipant:In}=TI({payload:e,selectedChannel:t,activeAssignedCats:C,showBossCatAvatar:g,isDirectLane:V,isDefaultChatComposer:Ye}),Ee=V?"direct_message":Ke.length>0?"participant_chat":"default_chat",[We,yt]=p.useState(!1),[Bt,aa]=p.useState("cats"),[ra,Ln]=p.useState(null),[Xt,Sn]=p.useState(""),[Kt,Ma]=p.useState(()=>typeof window>"u"?1280:window.innerWidth),[wt]=p.useState(()=>pb(typeof window>"u"?null:window.localStorage)),[kt,on]=p.useState(wt.value),sa=p.useRef(wt.requiresPersistedCleanup),Mn=p.useCallback(U=>gb({channelId:t.id,turnId:U.turnId,userDefault:Me.concurrentPresentationMode,segmentCount:U.segmentCount,viewportWidth:Kt,uiStateByKey:kt}),[Me.concurrentPresentationMode,kt,t.id,Kt]),oa=p.useCallback(U=>U.resolvedMode==="inline_stack"?[]:[{key:`dismiss:${U.turnId}`,label:se(l.chatConcurrentClusterDismissActionLabel),title:se(l.chatConcurrentClusterDismissActionTitle),onSelect:()=>{on(te=>mb(te,{channelId:t.id,turnId:U.turnId}))}}],[t.id]);function $t(U){yt(!0),aa(U)}const ln=xb({isDirectLane:V,directLaneCat:gt,defaultRecipientCatRecord:Jt,selectedChannelTitle:t.title,isCompareGroup:St,compareGroup:xe,t:se}),yn=wb({isDirectLane:V,defaultRecipientCat:xt,showBossCatAvatar:g,isDefaultChatComposer:Ye,activeRoomParticipants:Ke}),bn=p.useMemo(()=>kb({activeRoomParticipants:Ke,bossCatId:e.chat.bossCatId,resolveParticipantCatRecord:Pe,resolveParticipantDisplayName:rt}),[Ke,e.chat.bossCatId,Pe,rt]),ut=p.useMemo(()=>SI(a,t),[a,t]),Ea=p.useMemo(()=>Pb(t.messages),[t.messages]),oe=p.useMemo(()=>({messageId:t.messages.slice().reverse().find(U=>U.senderKind==="user")?.id??null,status:(()=>{const U=t.messages.slice().reverse().find(de=>de.senderKind==="user")??null;if(!U)return"idle";const te=t.roomRouting.workflow.activeTurn??null,_t=t.roomRouting.lastOutcome??null,we=t.messages.findIndex(de=>de.id===U.id),Q=te?.sourceMessageId??null,Ve=Q?t.messages.findIndex(de=>de.id===Q):-1,$e=Se?.sourceMessageId??null,Un=($e?$e===U.id:Q===U.id)&&!!(Se?.speakerLabel||Se?.participantId||Se?.catId),Ue=t.messages.some((de,Be)=>Be>we&&de.senderKind!=="user"&&de.senderKind!=="system"&&!(de.metadata?.verbosity==="verbose"&&Me.showVerboseMessages!==!0)),wn=te?.targetStatuses?.map(de=>de.id)??[],pa=(te?.targetStatuses??[]).map(de=>{const Be=de.laneId?.trim()||null;return Be||(!te?.id||!de.id?null:Yr(te.id,de.id,de.participant.participantId))}).filter(de=>de!=null),ha=(te?.targetStatuses??[]).map(de=>de.participant.participantId).filter(de=>typeof de=="string"&&de.length>0),fa=t.messages.some((de,Be)=>{if(Be<=we||de.metadata?.kind!=="session_start")return!1;const ht=typeof de.metadata?.targetStateId=="string"?de.metadata.targetStateId:null,Hn=typeof de.metadata?.laneId=="string"?de.metadata.laneId:null,Ft=typeof de.metadata?.participantId=="string"?de.metadata.participantId:null;return ht!=null&&wn.includes(ht)||Hn!=null&&pa.includes(Hn)||Ft!=null&&ha.includes(Ft)}),Ze=(te?.targetStatuses??[]).filter(de=>de.status==="running"||de.status==="completed"),kn=Ze.length>0&&(te?.workflowShape==="concurrent"||Ze.some(de=>de.status==="completed")||Ze.length>1),Kn=te?.sourceMessageId===U.id&&(te.status==="running"||te.status==="pending"),$n=we>-1&&Ve>-1&&Ve<we&&(te?.status==="running"||te?.status==="pending");return(Kn&&!kn||$n)&&!Un&&($n||!Ue&&!fa)?"processing":_t?.sourceMessageId===U.id&&_t.status==="error"?"failed":"idle"})()}),[Me.showVerboseMessages,t,Se]),pt=p.useMemo(()=>ut?.runs.map(U=>U.id).join("|")??"",[ut]),Pt=p.useMemo(()=>Ab({visibleLiveIndicator:Se,selectedChannel:t,activeRoomParticipants:Ke}),[Ke,t,Se]),{activeTopBarCatIds:Qt,activeTopBarParticipantIds:En,liveSpeakerParticipant:cn}=Pt,Da=p.useCallback(U=>{if(U.participantId){const we=Ke.find(Q=>Q.participantId===U.participantId)??null;if(we)return we}const te=(()=>{const we=U.identityParticipantId?.trim()||null;return!we||we===U.participantId?null:Sm(U,t.messages)?we:null})();if(te){const we=Ke.find(Q=>Q.participantId===te)??null;if(we)return we}if(U.catId){const we=Ke.find(Q=>Pe(Q)?.id===U.catId)??null;if(we)return we}if(U.phase==="sealed"){const we=Array.isArray(t.roomRouting.workflow.turnHistory)?t.roomRouting.workflow.turnHistory:[],Q=[t.roomRouting.workflow.activeTurn,...we].filter(Ve=>Ve!=null).flatMap(Ve=>Ve.targetStatuses.map($e=>({participantId:$e.participant.participantId,targetStateId:$e.id,laneId:$e.laneId?.trim()||Yr(Ve.id,$e.id,$e.participant.participantId)}))).find(Ve=>U.targetStateId!=null&&Ve.targetStateId===U.targetStateId||U.laneId!=null&&Ve.laneId===U.laneId);if(Q){const Ve=Ke.find($e=>$e.participantId===Q.participantId)??null;if(Ve)return Ve}}const _t=U.speakerLabel?.trim();return _t?Ke.find(we=>{const Q=Pe(we);return rt(we,Q)===_t})??null:null},[Ke,Pe,rt,t.messages,t.roomRouting.workflow.activeTurn,t.roomRouting.workflow.turnHistory]),Dn=p.useMemo(()=>new Set(Qt),[Qt]),Ba=p.useMemo(()=>new Set(En),[En]),Zt=p.useMemo(()=>Rb({isDirectLane:V,directLaneCat:gt,isDefaultChatComposer:Ye,selectedExecutionTarget:M,defaultRecipientParticipant:nt,bossCatId:e.chat.bossCatId,resolveParticipantCatRecord:Pe,resolveParticipantDisplayName:rt}),[nt,gt,V,Ye,e.chat.bossCatId,Pe,rt,M]),dn=p.useMemo(()=>qv(Ee,Kt),[Ee,Kt]),Oa=p.useMemo(()=>({"--chat-transcript-max-width":dn.transcriptMaxWidth}),[dn.transcriptMaxWidth]),[Bn,xn]=p.useState(null);p.useEffect(()=>{xn(U=>U&&ut?.runs.some(te=>te.id===U)?U:ut?.latestRun?.id??null)},[ut?.latestRun?.id,pt]),p.useEffect(()=>{if(typeof window>"u")return;function U(){Ma(window.innerWidth)}return window.addEventListener("resize",U),()=>window.removeEventListener("resize",U)},[]),p.useEffect(()=>{if(typeof window>"u")return;if(!sa.current){sa.current=!0;return}const U=fb(window.localStorage,kt);U!==kt&&on(te=>te===kt?U:te)},[kt]);const On=p.useMemo(()=>yI(ut,Bn),[ut,Bn]),{directLaneExecutionTarget:Ot,directLaneExcludedMentionNames:_n,composerBusy:un,showCancelComposerAction:ia,showStopComposerAction:la,composerWorkspacePath:pn}=p.useMemo(()=>Nb({activeRoomParticipants:Ke,directLaneCat:V?gt:null,busy:u,isCompareGroup:St,selectedChannelId:t.id,onCancelPendingSend:w,onStopMessage:P,repoPath:t.repoPath,chatCwd:t.chatCwd,t:se}),[Ke,u,gt,St,V,w,P,t.chatCwd,t.id,t.repoPath,se]),ca=gn(u,"stop"),{transcriptListRef:_a,composerCardRef:Fa,bottomSentinelRef:Wa,isNearBottom:hn,scrollToBottom:Fn}=AI({channelId:t.id,scrollKey:Fe,scrollOnChannelChange:!0});jb(()=>{!Se?.active||!hn||Fn()},[hn,Fn,Fe,Se?.active]);function Ua(U){Ln(U.participantId),Sn(U.name)}function lt(){Ln(null),Sn("")}async function Ka(U){const te=Xt.trim();!te||!G||(await G(U,{name:te}),lt())}const st={payload:e,selectedChannel:t,activeAssignedCats:C,activeRoomParticipants:Ke,assignedCatRecords:Ut,assignedAdhocParticipants:at,defaultRecipientParticipant:nt,defaultRecipientCat:xt,directLaneCat:gt,directLaneExecutionTarget:Ot,operatorView:ut,inspectedRun:On,isDirectLane:V,isDefaultChatComposer:Ye,sidePanelOpen:We,openSidePanelTo:$t},$a={payload:e,composerBusy:un,selectedExecutionTarget:M,composerRecipients:Zt,defaultRecipientParticipantId:nt?.participantId??null,composerStackParticipants:bn,directLaneCat:gt,defaultRecipientCat:xt,assignedCatRecords:Ut,leadCatRecord:Jt,isDirectLane:V,isDefaultChatComposer:Ye,activeWorkflowShape:me,onToggleActiveWorkflowShape:K,activeAudienceKeys:B,onSetActiveAudienceKeys:ae,onOpenSection:$t},da=Nt?.($a)??r.jsx(Md,{payload:e,composerBusy:un,composerRecipients:Zt,defaultRecipientParticipantId:nt?.participantId??null,composerStackParticipants:bn,directLaneCat:gt,isDirectLane:V,isDefaultChatComposer:Ye,activeWorkflowShape:me,onToggleActiveWorkflowShape:K,activeAudienceKeys:B,onSetActiveAudienceKeys:ae,onOpenSection:$t}),Ha=(ct??yS)({payload:e,selectedChannel:t,busy:u,operatorView:ut,operatorLoading:s,operatorError:o,assignedCatRecords:Ut,assignedAdhocParticipants:at,defaultRecipientCatId:xt?.catId??null,defaultRecipientParticipant:nt,directLaneCat:gt,directLaneExecutionTarget:Ot,isDirectLane:V,isDefaultChatComposer:Ye,selectedExecutionTarget:M,inspectedRun:On,showAddCatButton:q,editingParticipantId:ra,editingParticipantName:Xt,canRenameParticipants:G!=null,onEditingParticipantNameChange:Sn,onBeginParticipantRename:Ua,onCancelParticipantRename:lt,onSubmitParticipantRename:U=>{Ka(U)},onOpenAddCat:W,onCloseSidePanel:()=>yt(!1),onInspectRun:xn,onApprovalDecision:b,onOperatorAction:Y,onExecutionTargetChange:F,onStartFresh:O,onDirectLaneExecutionTargetChange:J,onDirectLaneParticipantTargetChange:G?(U,te)=>{G(U,{provider:te.provider,instance:te.instance,model:te.model,modelSelection:te.modelSelection})}:void 0,buildParticipantAvatarStyle:jn}),qa=Qe?.(st)??null,Ga=Ie?.(st)??null,Va=Vt?.(st)??null,za=Le?.(st)??null,ua=Wt?.(st)??null,Je=Et?.(st)??null;function Wn(U){const te=U==="prev"?Ne:Dt;!te||!be||be(te)}return r.jsxs(jI,{conversationMode:it,layoutMode:Ee,composerVariant:dn.composerVariant,secondarySurfacePosition:dn.secondarySurfacePosition,layoutStyle:Oa,hasConversationStarted:ot,activeDirectCatId:V&&ot?xt?.catId??null:null,topBar:r.jsx(LI,{avatars:jt.map(U=>({key:U.key,label:U.label,executionLabel:U.executionLabel,avatarColor:U.avatarColor,avatarUrl:U.avatarUrl,isBoss:U.isBoss,useNeutralAvatar:U.useNeutralAvatar,pulsing:!!(U.pulseParticipantId&&Ba.has(U.pulseParticipantId)||U.pulseCatId&&Dn.has(U.pulseCatId))})),showRosterAvatars:yn,isDirectLane:V,topBarTitle:ln,sidePanelOpen:We,approvalCount:ut?.approvals.length??0,extraActions:qa,onToggleSidePanel:()=>yt(!We),onOpenCatProfile:V&&xt?.catId?()=>ce(`/entities/cats/${encodeURIComponent(xt.catId)}`):void 0}),statusRow:Ga,sidePanel:We?r.jsx(zl,{title:Re,activeSection:Bt,onSectionToggle:aa,onClose:()=>yt(!1),position:dn.secondarySurfacePosition==="bottom"?"bottom":"side",className:"chatPaneSidePanel chatPaneSidePanelBelowBar",sections:Ha}):null,children:[r.jsx(ab,{hasConversationStarted:ot,greeting:d,transcriptListRef:_a,bottomSentinelRef:Wa,selectedChannel:t,visibleMessages:dt,workflow:t.roomRouting.workflow,cats:e.chat.cats,bossCatId:e.chat.bossCatId,selectedChannelId:t.id,disabledMentionNames:_n,busy:u,compareBusy:ke,isCompareGroup:St,choiceResponsesBySource:Ea,onChoiceSubmit:R,latestUserTurnMessageId:oe.messageId,latestUserTurnStatus:oe.status,onRetryMessage:L,onRelayMessage:re,liveIndicator:(()=>{if(dc()){const U=wl(le),te=wl(Se),_t=t.roomRouting.workflow.activeTurn?.updatedAt??null,we=dt.map($e=>{const At=$e.body?.trim().length??0,Un=At===0?"∅":At<40?"len"+At:At<400?"len~"+Math.floor(At/40)*40:"len~"+Math.floor(At/400)*400;return`${$e.senderKind}#${$e.id.slice(-6)}:${Un}`}).join(","),Q=`raw=${U}|vis=${te}|turn=${_t??"none"}|msgs=${we}`;if(Mr===null&&U==="inactive"&&te==="inactive")Mr=Q,Er=Date.now();else if(Q!==Mr){const $e=Date.now(),At=Er!=null?$e-Er:0;Mr=Q,Er=$e,console.log("[CV] li gap="+At+"ms raw="+U+" vis="+te+" turn="+(_t??"none")+" msgs["+dt.length+"]="+we+" nb="+(hn?"1":"0"))}}return Se??void 0})(),liveSpeakerParticipant:cn,liveSpeakerParticipantCat:Pe(cn),resolveLiveIndicatorSegmentParticipant:Da,messageStackTone:yb,resolveMessageParticipant:In,resolveParticipantCatRecord:Pe,buildParticipantAvatarClassName:sn,buildParticipantAvatarStyle:jn,resolveParticipantAvatarUrl:na,resolveParticipantDisplayName:rt,showLiveProgressDetails:Me.showLiveProgressDetails,resolveConcurrentClusterPresentationMode:Mn,buildConcurrentClusterActions:oa,buildTranscriptMessageActions:pe}),r.jsx(US,{hasConversationStarted:ot,isCompareGroup:St,isNearBottom:hn,payload:e,composerDraft:i,channelFiles:h,channelPlusMenuOpen:f,channelPlusMenuRef:m,channelFileInputRef:v,composerBusy:un,compareBusy:ke,stopBusy:ca,composerWorkspacePath:pn,directLaneExcludedMentionNames:_n,composerRecipients:Zt,defaultRecipientParticipantId:nt?.participantId??null,composerStackParticipants:bn,isDirectLane:V,isDefaultChatComposer:Ye,activeWorkflowShape:me,onToggleActiveWorkflowShape:K,activeAudienceKeys:B,onSetActiveAudienceKeys:ae,compareSendScope:Ae,showCancelComposerAction:ia,showStopComposerAction:la,composerCardRef:Fa,composerTargetSlot:da,composerHeaderAccessory:Va,composerHeaderWhereExtras:za,composerFooterAccessory:ua,surfaceTag:Je,onOpenSection:$t,onComposerChange:x,onComposerKeyDown:S,onSendMessage:k,onToggleChannelPlusMenu:j,onChannelFileSelect:N,onTakeScreenshot:D,screenshotCaptureDisabled:T,onChannelFilesChange:A,onScrollToBottom:Fn,onCompareSendScopeChange:X,onCancelPendingSend:w,onStopMessage:P,autoResize:$}),Yt.length>1&&be?r.jsx($S,{compareMembers:Yt,selectedChannelId:Tt,comparePrevChannelId:Ne,compareNextChannelId:Dt,onSelect:be,onNavigatePrev:()=>Wn("prev"),onNavigateNext:()=>Wn("next")}):null]})}const lw=mh,kl={full:"sharedPermissionModeFullAccess",read_only:"sharedPermissionModeReadOnly"},Lb=["full","read_only"];function Mb({value:e,onChange:t,disabled:n}){const{t:a}=z(),[s,o]=p.useState(!1),i=p.useRef(null);return p.useEffect(()=>{if(!s)return;function u(d){i.current&&!i.current.contains(d.target)&&o(!1)}function c(d){d.key==="Escape"&&o(!1)}return document.addEventListener("mousedown",u),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",u),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(u=>!u),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[kl[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:Lb.map(u=>{const c=u===e;return r.jsxs("button",{type:"button",role:"option","aria-selected":c,className:`composerSelectChipMenuItem${c?" composerSelectChipMenuItemSelected":""}`,onClick:()=>{t(u),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[kl[u]])})]},u)})}):null]})}function Eb(e,t){return`shadow-${e}-${t.provider}-${t.instance??""}-${t.model??""}`}function $d(e){return{dismissed:!1,lastResetKey:e}}function Db(e,t){return e.lastResetKey===t?e:$d(t)}function Bb(e){return e.dismissed?e:{...e,dismissed:!0}}function Ob(e){return e.availableChipCount>0&&!e.dismissed}function _b(e){return e.length===0?null:JSON.stringify(e.map(t=>[t.id,t.prompt,t.label??null]))}function Fb(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 Wb(e){const[t,n]=p.useState(()=>$d(e.resetKey));t.lastResetKey!==e.resetKey&&n(s=>Db(s,e.resetKey));const a=p.useCallback(()=>{n(Bb)},[]);return{showDraftHelperChips:Ob({availableChipCount:e.availableChipCount,dismissed:t.dismissed}),dismissDraftHelperChips:a}}function Ub({folderBrowsePath:e,folderBrowseCurrentPath:t,folderBrowseParentPath:n,folderBrowseEntries:a,folderBrowseLoading:s,folderBrowseError:o,onPathChange:i,onBrowse:u,onSelect:c}){const{t:d}=z();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(),u(e))},placeholder:d("sharedFolderBrowserEnterPath")}),r.jsx("button",{className:"folderBrowserNavButton",type:"button",onClick:()=>u(e),disabled:s,"aria-label":d("sharedFolderBrowserGo"),"data-tooltip":d("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:()=>u(n),disabled:s||!n||n===t,"aria-label":d("sharedFolderBrowserUpOneLevel"),"data-tooltip":d("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:()=>u(t),disabled:s||!t,"aria-label":d("sharedFolderBrowserRefresh"),"data-tooltip":d("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||d("sharedFolderBrowserLoading")})]}),r.jsx("div",{className:"folderBrowserListScroll",role:"list",children:s?r.jsx("div",{className:"folderBrowserStatus",children:d("sharedFolderBrowserLoading")}):a.length>0?a.map(h=>r.jsxs("button",{className:"folderBrowserEntry",type:"button",onClick:()=>u(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||d("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:d("sharedFolderBrowserUseThisFolder")})})]})}const Kb=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 Hd(e,t){const n=Kb(t);return{title:e?.title??n.title,participants:{...n.participants,...e?.participants},execution:{...n.execution,...e?.execution},folder:{...n.folder,...e?.folder}}}function $b(e){const t=[],{t:n}=e,a=Hd(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(co,{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=Qh(e.draftTemporaryParticipants,o.id),u=Gh({provider:o.executionTarget.provider,instance:o.executionTarget.instance,model:o.executionTarget.model},void 0,n);let c=n(l.chatNewChatDraftAssistantPresetAdd);return u.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:Gr({provider:o.executionTarget.provider,instance:o.executionTarget.instance,model:o.executionTarget.model})}),r.jsxs("p",{children:[u.capabilityLabel," | ",u.policySummary," | ",u.toolGrantSummary]}),o.roleHint?r.jsx("p",{children:o.roleHint}):null]}),r.jsx("button",{className:"addCatAssignButton",type:"button",title:u.reviewReasons.join(", ")||void 0,disabled:e.isSubmittingFirstTurn||i||e.hasReachedGroupParticipantLimit||u.requiresActivationReview,onClick:()=>e.onAddDraftTemporaryParticipant(Vh(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:Gr(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(Jn,{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(co,{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(Jn,{provider:e.activePanelExecutionTarget.provider,instance:e.activePanelExecutionTarget.instance??"",model:e.activePanelExecutionTarget.model??"",modelSelection:e.activePanelExecutionTarget.modelSelection,onTargetChange:o=>{e.onDirectLaneExecutionTargetChange?.(e.defaultRecipientCat.id,xa(o))}})]}):e.activePanelExecutionTarget?r.jsx("div",{style:e.effectiveDefaultRecipientCat&&!e.isDirectLaneContext?{pointerEvents:"none",opacity:.45}:void 0,children:r.jsx(Jn,{provider:e.activePanelExecutionTarget.provider,instance:e.activePanelExecutionTarget.instance??"",model:e.activePanelExecutionTarget.model??"",modelSelection:e.activePanelExecutionTarget.modelSelection,onTargetChange:o=>{!e.effectiveDefaultRecipientCat&&e.onExecutionTargetChange&&e.onExecutionTargetChange(xa(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:_o(o),children:r.jsx(Jn,{provider:o.provider,instance:o.instance??"",model:o.model??"",modelSelection:o.modelSelection,onTargetChange:u=>{e.onParallelTargetChange?.(i,xa(u))}})})}),t.push({id:"cwd",title:a.folder.sectionTitle,children:e.onFolderBrowsePathChange&&e.onFolderBrowse&&e.onFolderBrowseSelect?r.jsx(Ub,{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 Pl({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 qd({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 Hb({accessory:e=null,showParallelAddButton:t=!1,hideParallelHint:n=!1,accentParallelAddButton:a=!1,disabled:s=!1,onAddParallelTarget:o}){const{t:i}=z(),u=t&&o!=null;return!e&&!u?null:r.jsxs("div",{className:"composerFooterRow",children:[e?r.jsx("div",{className:"composerFooterAccessory",children:e}):null,u?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(qd,{})})]}):null]})}function Al({audienceParticipants:e,isSubmittingFirstTurn:t,canRemoveParticipant:n,useDangerRemoveHover:a=!1,onAvatarClick:s,onRemoveParticipant:o}){const{t:i}=z();return e.length<=1?null:r.jsx(r.Fragment,{children:e.map(u=>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":u.isCat&&u.executionLabel?`${u.name} · ${u.executionLabel}`:u.executionLabel||u.name,style:u.avatarUrl?{backgroundImage:`url(${u.avatarUrl})`,backgroundSize:"cover",backgroundPosition:"center"}:u.isCat?{background:u.avatarColor??"#8B7E74"}:{background:"#fff",color:"#222",border:"1px solid rgba(0, 0, 0, 0.15)"},children:u.avatarUrl?null:Rt(u.name)}),n?r.jsx("button",{type:"button",className:`composerGroupAvatarRemove${a?" composerGroupAvatarRemoveDanger":""}`,"aria-label":i(l.chatAudienceRemoveParticipantAria,{name:u.name}),disabled:t,onClick:()=>o(u),children:"×"}):null]},u.key))})}function qb({cards:e,activeIndex:t,onActiveIndexChange:n,disabled:a=!1,ariaLabel:s}){const{t:o}=z(),i=e.length,u=s??o(l.chatDraftCompareCarouselAriaLabel),c=p.useCallback(()=>{a||n(Math.max(0,t-1))},[t,a,n]),d=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(),d()))}return i===0?null:r.jsxs("div",{className:"draftCompareCarousel",role:"region","aria-label":u,onKeyDown:h,children:[r.jsx("div",{className:"draftCompareCarouselTrack",children:e.map((f,m)=>r.jsx(Gb,{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 Gb({active:e,relative:t,disabled:n,onPromote:a,children:s}){const o=Math.abs(t),i=t===0?0:t>0?1:-1,u=i*(88+(o-1)*28),c=-i*(38+(o-1)*10),d=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(${u}%, 0) rotateY(${c}deg) scale(${d.toFixed(3)})`,opacity:h.toFixed(3),zIndex:f},v=e?"draftCompareCarouselCard draftCompareCarouselCardActive":"draftCompareCarouselCard draftCompareCarouselCardPeek";function C(I){e||n||!a||I.target instanceof HTMLElement&&I.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 Vb(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 zb(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 Yb(e){return zb(e.suggestions)}function Jb(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:gh(t,e.t),starterSuggestions:n?t.bundle.content.entryChips.map(a=>({id:a.id,prompt:a.prompt})):void 0}}function Xb(e){const t=e.payload.chat.cats.filter(Bl),n=e.payload.assistantPresets??[],a=t.filter(T=>T.status==="active"),s=Fc({draftDefaultRecipientCatId:e.draftDefaultRecipientCatId,draftCatIds:e.draftCatIds}),o=e.draftDefaultRecipientCatId?t.find(T=>T.id===e.draftDefaultRecipientCatId&&T.status==="active")??null:null,i=!!(o&&e.payload.chat.botBindings.some(T=>T.platform==="telegram"&&T.status==="active"&&T.catId===o.id)),u=!o&&e.draftCatIds.length>0?t.find(T=>T.id===s.effectiveDefaultRecipientCatId&&T.status==="active")??null:null,c=o??u,d=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=Vb({allowAddCat:e.allowAddCat,draftDefaultRecipientCatId:e.draftDefaultRecipientCatId,hasDefaultRecipientCat:!!c,entryPreset:e.entryPreset,participantCount:h,parallelTargetCount:e.parallelTargets?.length??0}),C=Jb({payload:e.payload,isDirectLaneContext:v.isDirectLaneContext,t:e.t}),I=s.participantCatIds,y=v.isDirectLaneContext?[]:C.starterSuggestions??[],g=Yb({suggestions:y}),x=(()=>{const T=e.greeting?.trim();if(T)return T;const A=C.greeting?.trim();return A||tf({pool:e.greetingPool,t:e.t})})(),S=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(T=>T.id===e.draftHighlightedCatId)??null:null,w=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,P=Tc(e.busy),j=jm(e.busy)||P,N=c?[vb(c,e.payload.chat.bossCatId)]:d?[pr({participantId:d.participantId,name:d.name,provider:d.provider,instance:d.instance??null,model:d.model??null})]:[],D=[...I.map(T=>t.find(A=>A.id===T)).filter(T=>T!=null&&T.name.length>0).map(T=>Go(T)),...e.draftTemporaryParticipants.map(T=>Ld(T))];return{chatCats:t,assistantPresets:n,activeChatCats:a,draftParticipants:s,defaultRecipientCat:o,hasTelegramBinding:i,effectiveDefaultRecipientCat:c,effectiveDefaultRecipientTemporaryParticipant:d,draftParticipantCount:h,maxGroupParticipants:f,hasReachedGroupParticipantLimit:m,draftSuggestionContext:v,visibleDraftCatIds:I,visibleStarterSuggestions:g,resolvedGreeting:x,groupDraftSelectionLabel:S,activePanelExecutionTarget:w,isAckPending:P,isSubmittingFirstTurn:j,draftComposerRecipients:N,groupComposerParticipants:D}}function Qb(e){return e.section==="cwd"&&!e.skipSectionAction&&!e.folderBrowseCurrentPath&&!e.folderBrowseLoading}function Zb(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,u]=p.useState(!1),[c,d]=p.useState(null),[h,f]=p.useState(""),[m,v]=p.useState(t);function C(k){o(k),Qb({section:k,folderBrowseCurrentPath:e.folderBrowseCurrentPath,folderBrowseLoading:e.folderBrowseLoading})&&e.onPickFolder()}function I(k,w){if(a(!0),w?.skipSectionAction){o(k);return}C(k)}function y(){if(e.hasReachedGroupParticipantLimit||!m.provider.trim())return;const k=[...e.visibleDraftCatIds.map(w=>e.chatCats.find(P=>P.id===w)?.name??""),...e.draftTemporaryParticipants.map(w=>w.name)].filter(w=>w.trim().length>0);e.onAddDraftTemporaryParticipant(Pn({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()),u(!1)}function g(k){d(k.participantId),f(k.name)}function x(){d(null),f("")}function S(k){const w=h.trim();w&&(e.onUpdateDraftTemporaryParticipant(k,{name:w}),x())}return{createTemporaryParticipantFormValue:t,sidePanelOpen:n,setSidePanelOpen:a,sidePanelSection:s,switchSection:C,openSidePanelTo:I,temporaryParticipantFormOpen:i,setTemporaryParticipantFormOpen:u,editingTemporaryParticipantId:c,editingTemporaryParticipantName:h,setEditingTemporaryParticipantName:f,temporaryParticipantForm:m,setTemporaryParticipantForm:v,submitTemporaryParticipant:y,beginTemporaryParticipantRename:g,cancelTemporaryParticipantRename:x,submitTemporaryParticipantRename:S}}const cw=Ch,Rl={current:l.sharedWorkspaceModeCurrentLabel,worktree:l.sharedWorkspaceModeWorktreeLabel},ex={current:l.sharedWorkspaceModeCurrentTooltip,worktree:l.sharedWorkspaceModeWorktreeTooltip},tx=["current","worktree"];function nx({value:e,onChange:t,disabled:n}){const{t:a}=z(),[s,o]=p.useState(!1),i=p.useRef(null);return p.useEffect(()=>{if(!s)return;function u(d){i.current&&!i.current.contains(d.target)&&o(!1)}function c(d){d.key==="Escape"&&o(!1)}return document.addEventListener("mousedown",u),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",u),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(ex[e]),onClick:()=>o(u=>!u),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(Rl[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:tx.map(u=>{const c=u===e;return r.jsxs("button",{type:"button",role:"option","aria-selected":c,className:`composerSelectChipMenuItem${c?" composerSelectChipMenuItemSelected":""}`,onClick:()=>{t(u),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(Rl[u])})]},u)})}):null]})}function ax(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 Fh(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 qs(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 rx(e){return yh({repoPath:e.target.cwd??e.draftCwd,policy:e.target.runtimeSessionPolicy??e.draftRuntimeSessionPolicy??So()})}function sx({branchIndex:e,target:t,draftCwd:n,draftRuntimeSessionPolicy:a,isSubmittingFirstTurn:s,onSetParallelBranchRuntimeSessionPolicy:o}){const{t:i}=z(),u=t.runtimeSessionPolicy??null,c=o!=null,d=t.cwd??n,{isRepo:h,repoRoot:f}=ax(d),m=!!(d&&h&&f),v=rx({target:t,draftCwd:n,draftRuntimeSessionPolicy:a});function C(I){const y=t.runtimeSessionPolicy??v;o?.(e,bh({workspaceKind:y.workspaceKind,workspaceAccess:y.workspaceAccess,permissionMode:y.permissionMode,...I}))}return u&&c?r.jsxs("div",{className:"composerBranchPolicyControl","data-tooltip":qs(u,i),children:[m?r.jsx(nx,{value:Ih(u.workspaceKind),onChange:I=>C({workspaceKind:vh({hasCwd:!!d,isRepo:m,workspaceMode:I})}),disabled:s}):null,r.jsx(Mb,{value:Sh(u.workspaceAccess),onChange:I=>C(xh(I)),disabled:s}),r.jsx("button",{className:"composerChipClose",type:"button",disabled:s,onClick:()=>o(e,null),"aria-label":i(l.chatNewChatDraftBranchPolicyRelinkAria),children:"×"})]}):u?r.jsxs("span",{className:"composerSelectChip composerPermissionChip composerBranchPolicyChip","data-tooltip":qs(u,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:qs(u,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 dw({payload:e,composerDraft:t,busy:n,greeting:a=null,greetingPool:s=null,draftFiles:o,draftCwd:i,draftCatIds:u,draftTemporaryParticipants:c,plusMenuOpen:d,plusMenuRef:h,fileInputRef:f,bossCatName:m,bossCatAvatarColor:v,onComposerChange:C,onComposerKeyDown:I,onSendMessage:y,onCancelPendingSend:g,onTogglePlusMenu:x,onFileSelect:S,onTakeScreenshot:k,screenshotCaptureDisabled:w=!1,onPickFolder:P,onOpenAddCat:j,onDraftFilesChange:N,onDraftCwdClear:D,onToggleDraftCat:T,onAddDraftTemporaryParticipant:A,onQuickAddDraftTemporaryParticipant:b,onRemoveDraftTemporaryParticipant:R,onUpdateDraftTemporaryParticipant:L,autoResize:O,draftDefaultRecipientCatId:Y,entryPreset:$="default",onDraftDefaultRecipientChange:M,allowAddCat:F=!0,selectedExecutionTarget:J,onExecutionTargetChange:me,draftHighlightedCatId:K,onHighlightDraftCat:B,draftCatExecutionTargetOverrides:ae,onDraftCatExecutionTargetOverride:be,onDirectLaneExecutionTargetChange:W,parallelTargets:q,onParallelTargetChange:_e,onAddParallelTarget:le,onRemoveParallelTarget:xe,parallelBranchActions:Ae,builderControls:X,folderBrowsePath:re="",folderBrowseCurrentPath:G="",folderBrowseParentPath:pe="",folderBrowseEntries:Ie=[],folderBrowseLoading:Qe=!1,folderBrowseError:Nt="",onFolderBrowsePathChange:Vt,onFolderBrowse:Le,onFolderBrowseSelect:Wt,draftWorkflowShape:Et="sequential",onToggleDraftWorkflowShape:ct,draftAudienceKeys:Te,onSetAudienceKeys:se,draftRuntimeSessionPolicy:ce=null,onDraftRuntimeSessionPolicyChange:Re,onCatAvatarSave:Me,draftChrome:dt,draftCopy:ot,starterChips:tt,sidePanel:Se}){const Fe=Na(),{headerAccessory:it=null,headerWhereExtras:zt=null,footerAccessory:Yt=null,customRegion:St=null,surfaceTag:Tt=null,chooseFolderPlacement:ge="header"}=dt??{},{showGroupAddButton:ke=!1,showParallelAddButton:Ne=!1,hideGroupHint:Dt=!1,hideParallelHint:Ye=!1}=X??{},{t:V}=z(),Ke=ot?.composerPlaceholder??V(l.chatNewChatDraftComposerPlaceholder),nt=ot?.folderActionLabel??V(l.chatNewChatDraftFolderActionLabel),xt=ot?.sidePanel,gt=tt?.leading,Jt=tt?.preserveOnSelect??!1,Ut=Ae?.onPickFolder,at=Ae?.onSetAudienceKeys,jt=Ae?.onSetCwd,Pe=Ae?.onSetRuntimeSessionPolicy,rt=Ae?.onToggleWorkflowShape,na=Ae?.onQuickAddTemporaryParticipant,jn=Hd(xt,V),sn=Se?.title??jn.title,In=Se?.buildSections??(_=>$b(_)),Ee=(q?.length??0)>=2,[We,yt]=p.useState(0),Bt=q?.length??0;p.useEffect(()=>{if(!Ee){We!==0&&yt(0);return}We>=Bt&&yt(Math.max(0,Bt-1))},[We,Ee,Bt]);const[aa,ra]=p.useState(!1),Ln=p.useRef(We);p.useEffect(()=>{if(Ln.current===We)return;Ln.current=We,ra(!0);const _=setTimeout(()=>ra(!1),200);return()=>clearTimeout(_)},[We]);const Xt=e.chat.capabilities.maxAudienceParticipants??3,Sn=e.chat.capabilities.maxChatParticipants??Number.POSITIVE_INFINITY,{chatCats:Kt,assistantPresets:Ma,defaultRecipientCat:wt,effectiveDefaultRecipientCat:kt,effectiveDefaultRecipientTemporaryParticipant:on,draftParticipantCount:sa,hasReachedGroupParticipantLimit:Mn,draftSuggestionContext:oa,visibleDraftCatIds:$t,visibleStarterSuggestions:ln,resolvedGreeting:yn,groupDraftSelectionLabel:bn,activePanelExecutionTarget:ut,isAckPending:Ea,isSubmittingFirstTurn:oe,groupComposerParticipants:pt}=Xb({payload:e,draftDefaultRecipientCatId:Y,draftCatIds:u,draftTemporaryParticipants:c,allowAddCat:F,entryPreset:$,parallelTargets:q,greeting:a,greetingPool:s,draftHighlightedCatId:K,draftCatExecutionTargetOverrides:ae,selectedExecutionTarget:J,busy:n,t:V}),{isGroupDraft:Pt,isDirectLaneContext:Qt}=oa,{supported:En,listening:cn,toggle:Da,textareaRef:Dn,toasts:Ba,privacyMessage:Zt}=Td({value:t,onChange:C,autoResize:O,disabled:oe}),dn=_b(ln),{showDraftHelperChips:Oa,dismissDraftHelperChips:Bn}=Wb({availableChipCount:ln.length,resetKey:dn});function xn(_){return _.length<=Xt?_:_.slice(0,Xt)}const On={draftAudienceKeys:Te??null,draftWorkflowShape:Et??"sequential"};function Ot(_){const ne=q?.[_];return ne?Zc(ne,On):[]}function _n(_){const ne=q?.[_];return ne?ed(ne,On):"sequential"}function un(_){const ne=Ot(_);if(pt.length===0||ne.length===0)return[];const ye=new Map(pt.map(ft=>[ft.key,ft]));return ne.map(ft=>ye.get(ft)).filter(Boolean)}function ia(_,ne){const ye=un(_);return ye.length===0?[Ur(ne,`parallel:${_}`)]:xn(ye)}const la=(()=>{if(Ee&&q?.[0])return ia(0,q[0]);if(Pt){if(!Te)return xn(pt);const _=new Map(pt.map(ye=>[ye.key,ye])),ne=Te.map(ye=>_.get(ye)).filter(Boolean);return ne.length>0?xn(ne):pt.length>0?[pt[0]]:[]}return kt?[Go(kt)]:on?[Ld(on)]:ut?[Ur(ut)]:[]})(),pn=Ee&&pt.length>0&&Ot(0).length>0,ca=Ee?un(0):[],_a=(()=>{if(!Pt)return Ee?pn?()=>lt("cats"):()=>lt("parallel:0"):Qt?()=>lt("execution"):kt||on?()=>lt("cats"):()=>lt("execution")})(),{createTemporaryParticipantFormValue:Fa,sidePanelOpen:Wa,setSidePanelOpen:hn,sidePanelSection:Fn,switchSection:Ua,openSidePanelTo:lt,temporaryParticipantFormOpen:Ka,setTemporaryParticipantFormOpen:st,editingTemporaryParticipantId:$a,editingTemporaryParticipantName:da,setEditingTemporaryParticipantName:Ha,temporaryParticipantForm:qa,setTemporaryParticipantForm:Ga,submitTemporaryParticipant:Va,beginTemporaryParticipantRename:za,cancelTemporaryParticipantRename:ua,submitTemporaryParticipantRename:Je}=Zb({payload:e,folderBrowseCurrentPath:G,folderBrowseLoading:Qe,onPickFolder:P,hasReachedGroupParticipantLimit:Mn,visibleDraftCatIds:$t,chatCats:Kt,draftTemporaryParticipants:c,onAddDraftTemporaryParticipant:A,onUpdateDraftTemporaryParticipant:L}),Wn=Ea&&g!=null,U=!Qt&&(Pt||ke),te=Ee?Ot(0).length:pt.length,_t=Ee?te<Sn:!Mn,we=Ee?te:pt.length,Q=!oe&&($==="group"?we>2:we>=2);function Ve(_){return!oe&&_>=2}const $e=$==="parallel"?2:1,At=$==="group",Un=$==="group",Ue=$==="parallel",wn=e.chat.capabilities.maxParallelChats??3;function pa(_){return _t?r.jsxs("div",{className:_.className??"composerGroupAddRow",children:[r.jsx("button",{type:"button",className:`parallelAddButton${_.accent?" parallelAddButtonAccent":""}`,disabled:oe,onClick:()=>{if(b){b();return}lt("cats")},"aria-label":V(l.chatNewChatDraftCollaborateAria),children:r.jsx(Pl,{})}),_.showHint?r.jsx("span",{className:`parallelAddHint${_.accent?" parallelAddHintAccent":""}`,children:V(l.chatNewChatDraftCollaborateHint)}):null]}):null}const ha=Qt&&wt?r.jsx(di,{variant:"profile",title:wt.name,avatarName:wt.name,avatarUrl:wt.avatarUrl,avatarColor:wt.avatarColor,coverStorageKey:wt.id,readOnlyVisuals:!0,actions:r.jsxs("button",{type:"button",className:"draftHeaderAction",onClick:()=>Fe(`/entities/cats/${encodeURIComponent(wt.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"})]}),V(l.chatNewChatDraftViewCatProfileAction)]})}):r.jsx(di,{variant:"intro",title:yn}),fa=r.jsxs("div",{className:"composerHeaderRow",children:[r.jsxs("div",{className:"composerHeaderLeft",children:[Tt,i?r.jsxs("span",{className:"composerCwdChip composerCwdClickable","data-tooltip":i,role:"button",tabIndex:oe?void 0:0,onClick:oe?void 0:()=>lt("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:Xs(i)}),r.jsx("button",{className:"composerChipClose",type:"button",disabled:oe,onClick:_=>{_.stopPropagation(),D()},"aria-label":V(l.chatNewChatDraftRemoveFolderAria),children:"×"})]}):ge==="header"?r.jsxs("button",{type:"button",className:"composerHeaderChooseButton",disabled:oe,onClick:()=>lt("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:nt})]}):null,zt]}),it?r.jsx("div",{className:"composerHeaderRight",children:it}):null]}),Ze=(q?.length??0)>=2&&xe?r.jsx("button",{type:"button",className:`composerCardBranchRemove${Ue?" composerCardBranchRemoveAccent":""}`,disabled:oe||(q?.length??0)<=$e,onClick:()=>xe(0),"aria-label":V(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,kn=r.jsxs("form",{className:`composerCard composerCardFresh${q?" parallelComposerAnchor":""}${d?" composerCardMenuOpen":""}`,onSubmit:_=>{y(_)},children:[Ze,o.length>0?r.jsx("div",{className:"composerAttachments",children:o.map((_,ne)=>{const ye=_.type.startsWith("image/");return r.jsxs("div",{className:"attachmentCard",children:[r.jsx("button",{className:"attachmentRemove",type:"button",disabled:oe,onClick:()=>N(o.filter((ft,Lt)=>Lt!==ne)),"aria-label":V(l.chatNewChatDraftAttachmentRemoveAria,{fileName:_.name}),children:"×"}),ye?r.jsx("img",{className:"attachmentPreview",src:URL.createObjectURL(_),alt:_.name,onLoad:ft=>URL.revokeObjectURL(ft.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}-${ne}`)})}):null,r.jsx("textarea",{ref:Dn,className:"composerInput",rows:1,placeholder:Ke,value:t,disabled:oe,onChange:_=>{C(_.target.value),O(_.target)},onKeyDown:_=>{I(_)}}),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":V(l.chatNewChatDraftBranchAttachAria),disabled:oe,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"})]})}),d?r.jsxs("div",{className:"composerPlusMenu",children:[r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:oe,onClick: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:"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"})]}),V(l.chatNewChatDraftAddPhotosAndFiles)]}),k?r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:oe||w,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"})]}),V(l.chatNewChatDraftTakeScreenshot)]}):null,ge==="plusMenu"?r.jsxs("button",{className:"composerPlusMenuItem",type:"button",disabled:oe,onClick:()=>{lt("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"})}),nt]}):null]}):null]}),U?r.jsxs("div",{className:"composerGroupAddRow",children:[r.jsx(Al,{audienceParticipants:Ee?ca:pt,isSubmittingFirstTurn:oe,canRemoveParticipant:Q,useDangerRemoveHover:At,onAvatarClick:()=>lt("cats"),onRemoveParticipant:_=>{if(Ee){if(!at)return;const ne=ca.filter(ye=>ye.key!==_.key).map(ye=>ye.key);at(0,ne);return}_.isCat&&_.catId?T(_.catId):_.participantId&&R(_.participantId)}}),pa({showHint:!Dt,accent:Un})]}):null]}),r.jsxs("div",{className:"composerRightGroup",children:[la.length>0?r.jsx(wa,{audienceParticipants:la,allParticipants:Ee&&pn||Pt?pt:void 0,onSetAudienceKeys:Ee&&pn?at?_=>at(0,_):void 0:Pt?se:void 0,onSingleClick:_a,disabled:oe,maxSelectedParticipants:Ee&&pn||Pt?Xt:void 0,workflowShape:Ee?_n(0):Et,onToggleWorkflowShape:Ee&&pn?rt?()=>rt(0):void 0:Pt?ct:void 0}):null,En?r.jsxs("button",{className:`composerPlusButton composerVoiceButton${cn?" composerVoiceButtonActive":""}`,type:"button","aria-label":cn?V(l.chatNewChatDraftStopVoiceInputAria,{privacyMessageSuffix:Zt?`. ${Zt}`:""}):V(l.chatNewChatDraftStartVoiceInputAria),"aria-pressed":cn,title:Zt??void 0,disabled:oe,onClick:Da,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"})]}),Zt?r.jsx("span",{className:"composerVoicePrivacyBadge","aria-hidden":"true",children:"!"}):null]}):null,Wn?r.jsx("button",{className:"composerSendButton composerCancelButton",type:"button","aria-label":V(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||oe||Pt&&sa<2,type:"submit","aria-label":V(Ee?l.chatNewChatDraftSendAllChatsAria:l.chatNewChatDraftSendAria),children:Ee?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:oe,style:{display:"none"},onChange:_=>{const ne=_.currentTarget;if(ne.files&&ne.files.length>0){const ye=Array.from(ne.files);N([...o,...ye])}ne.value=""}})]}),Kn=p.useRef(!1);p.useEffect(()=>{!Kn.current||Bt<=0||(Kn.current=!1,yt(Bt-1))},[Bt]);const $n=le?()=>{Kn.current=!0,le()}:void 0,de=p.useRef(!1);p.useEffect(()=>{if(!de.current||We!==0)return;de.current=!1;const _=Dn.current;if(!_)return;const ne=requestAnimationFrame(()=>{_.focus();const ye=_.value.length;_.setSelectionRange(ye,ye)});return()=>cancelAnimationFrame(ne)},[We,Dn]);function Be(){de.current=!0,yt(0)}const ht=r.jsx(Hb,{accessory:Yt,disabled:oe}),Hn=(()=>{const{runtimeChipsRendered:_,fallbackChipsRendered:ne}=Fb({isDirectLaneContext:Qt,showDraftHelperChips:Oa,runtimeChipCount:ln.length,fallbackChipCount:gt?.length??0});return!_&&!ne?null:r.jsx("div",{className:"draftPromptSuggestions",children:r.jsxs("div",{className:"chipRow",children:[ne?gt?.map(ye=>r.jsx("button",{className:"promptChip draftPromptChip",type:"button",disabled:oe,onClick:()=>{Jt||Bn(),ye.onClick()},children:ye.label},ye.id)):null,_?ln.map(ye=>r.jsx("button",{className:"promptChip draftPromptChip",type:"button",disabled:oe,onClick:()=>{Jt||Bn(),C(ye.prompt)},children:ye.prompt},ye.id)):null]})})})(),Ft=Wa?r.jsx(zl,{title:sn,activeSection:Fn,onSectionToggle:oe?()=>{}:Ua,onClose:oe?()=>{}:()=>hn(!1),className:"chatPaneSidePanel",sections:In({t:V,payload:e,chatCats:Kt,draftCatIds:u,draftHighlightedCatId:K,effectiveDefaultRecipientCat:kt,isGroupDraft:Pt,isDirectLaneContext:Qt,isParallelMode:Ee,groupDraftSelectionLabel:bn,assistantPresets:Ma,draftTemporaryParticipants:c,editingTemporaryParticipantId:$a,editingTemporaryParticipantName:da,temporaryParticipantFormOpen:Ka,temporaryParticipantForm:qa,hasReachedGroupParticipantLimit:Mn,isSubmittingFirstTurn:oe,defaultRecipientCat:wt,activePanelExecutionTarget:ut,onToggleDraftCat:T,onHighlightDraftCat:B,onAddDraftTemporaryParticipant:A,onRemoveDraftTemporaryParticipant:R,onBeginTemporaryParticipantRename:za,onCancelTemporaryParticipantRename:ua,onSubmitTemporaryParticipantRename:Je,onEditingTemporaryParticipantNameChange:Ha,onTemporaryParticipantFormChange:_=>Ga(ne=>_(ne)),createTemporaryParticipantFormValue:Fa,onTemporaryParticipantFormOpenChange:st,onSubmitTemporaryParticipant:Va,selectedExecutionTarget:J,onExecutionTargetChange:me,onDirectLaneExecutionTargetChange:W,parallelTargets:q,onParallelTargetChange:_e,folderBrowsePath:re,folderBrowseCurrentPath:G,folderBrowseParentPath:pe,folderBrowseEntries:Ie,folderBrowseLoading:Qe,folderBrowseError:Nt,draftCwd:i,onFolderBrowsePathChange:Vt,onFolderBrowse:Le,onFolderBrowseSelect:Wt,draftRuntimeSessionPolicy:ce,onDraftRuntimeSessionPolicyChange:Re,onCloseSidePanel:()=>hn(!1),sidePanelCopy:jn})}):null;function Ct(_,ne,ye=null){const ft=Ot(_).length,Lt=un(_),Ca=ft>1?ia(_,ne):[Ur(ne,`parallel:${_}`)],xr=ft<Sn&&na!=null,xs=_n(_),ws=Bt>$e,Ja=ne.cwd?.trim()||null;return r.jsxs(r.Fragment,{children:[r.jsx("div",{className:"composerHeaderRow",children:r.jsxs("div",{className:"composerHeaderLeft",children:[Tt,Ja?r.jsxs("span",{className:"composerCwdChip","data-tooltip":Ja,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:Xs(Ja)}),jt?r.jsx("button",{className:"composerChipClose",type:"button",disabled:oe,onClick:()=>jt(_,null),"aria-label":V(l.chatNewChatDraftBranchFolderRelinkAria),children:"×"}):null]}):Ut?r.jsxs("button",{type:"button",className:"composerFollowsLeadChip composerFollowsLeadChipClickable",disabled:oe,onClick:()=>{Ut(_),lt("cwd",{skipSectionAction:!0})},"aria-label":V(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:V(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:V(l.chatNewChatDraftBranchFollowsLeadLabel)})]}),r.jsx(sx,{branchIndex:_,target:ne,draftCwd:i,draftRuntimeSessionPolicy:ce??null,isSubmittingFirstTurn:oe,onSetParallelBranchRuntimeSessionPolicy:Pe})]})}),r.jsxs("div",{className:"draftBranchFormAnchor",children:[r.jsxs("form",{className:"composerCard composerCardFresh parallelComposerAnchor",onSubmit:fn=>fn.preventDefault(),children:[xe?r.jsx("button",{type:"button",className:`composerCardBranchRemove${Ue?" composerCardBranchRemoveAccent":""}`,disabled:oe||!ws,onClick:()=>xe(_),"aria-label":V(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:Ke,value:t,disabled:oe,readOnly:!0,"data-tooltip":V(l.chatNewChatDraftBranchPromptJumpToLeadTitle),"aria-label":V(l.chatNewChatDraftBranchPromptJumpToLeadAria),onClick:oe?void 0:()=>Be(),onFocus:oe?void 0:fn=>{fn.currentTarget.blur(),Be()}}),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":V(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"})]})})}),Lt.length>0||xr?r.jsxs("div",{className:"composerGroupAddRow",children:[Lt.length>0?r.jsx(Al,{audienceParticipants:Lt,isSubmittingFirstTurn:oe,canRemoveParticipant:Ve(Lt.length),useDangerRemoveHover:At,onAvatarClick:()=>lt("cats"),onRemoveParticipant:fn=>{if(!at)return;const ks=Lt.filter(Xa=>Xa.key!==fn.key).map(Xa=>Xa.key);at(_,ks)}}):null,xr?r.jsx("button",{type:"button",className:"parallelAddButton",disabled:oe,onClick:()=>na(_),"aria-label":V(l.chatNewChatDraftBranchCollaborateAria),children:r.jsx(Pl,{})}):null]}):null]}),r.jsx("div",{className:"composerRightGroup",children:r.jsx(wa,{audienceParticipants:Ca,allParticipants:ft>1?pt:void 0,onSetAudienceKeys:ft>1&&at?fn=>at(_,fn):void 0,onSingleClick:()=>lt("cats"),disabled:oe,maxSelectedParticipants:Xt,workflowShape:xs,onToggleWorkflowShape:rt?()=>rt(_):void 0})})]})]}),ye]})]})}const Ya=Math.max(Bt,1),ma=Ya-1,yr=Ya<wn,ga=_=>{if(_!==We)return null;const ne=We>0,ye=We<ma,ft=We===ma&&yr&&!!$n;if(!ne&&!ye&&!ft)return null;const Lt=aa&&Ya>1,Ca=br=>`draftCompareCarouselNav ${br}${Lt?" draftCompareCarouselNavDelayed":""}`;return r.jsxs(r.Fragment,{children:[ne?r.jsx("button",{type:"button",className:Ca("draftCompareCarouselNavPrev"),onClick:()=>yt(Math.max(0,We-1)),disabled:oe,"aria-label":V(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,ft?r.jsxs("div",{className:`draftCompareCarouselAddBranchSlot${Lt?" draftCompareCarouselAddBranchSlotDelayed":""}`,children:[r.jsx("button",{type:"button",className:`draftCompareCarouselNav draftCompareCarouselAddBranch${Ue?" draftCompareCarouselAddBranchAccent":""}`,onClick:$n,disabled:oe,"aria-label":V(l.chatNewChatDraftBranchAddParallelAria),children:r.jsx(qd,{})}),Ue?r.jsx("span",{className:"parallelAddHint parallelAddHintAccent",children:V(l.chatNewChatDraftBranchAddCompareHint)}):null]}):ye?r.jsx("button",{type:"button",className:Ca("draftCompareCarouselNavNext"),onClick:()=>yt(Math.min(ma,We+1)),disabled:oe,"aria-label":V(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]})},bs=Ee&&Array.isArray(q)&&q.length>=2?q.map((_,ne)=>ne===0?{id:`lead-${_.provider}-${_.instance??""}-${_.model??""}`,content:r.jsxs(r.Fragment,{children:[fa,r.jsxs("div",{className:"draftBranchFormAnchor",children:[kn,ga(0)]}),ht]})}:{id:Eb(ne,_),content:Ct(ne,_,ga(ne))}):[{id:"lead-only",content:r.jsxs(r.Fragment,{children:[fa,r.jsxs("div",{className:"draftBranchFormAnchor",children:[kn,ga(0)]}),ht]})}];return r.jsxs("div",{className:"viewShell viewShellDraft",children:[r.jsxs("section",{className:"draftShell",children:[ha,St?r.jsx("div",{className:"draftCustomRegion",children:St}):null,r.jsx(qb,{cards:bs,activeIndex:We,onActiveIndexChange:yt,disabled:oe}),Hn]}),Ft,r.jsx(xo,{toasts:Ba})]})}const ox={chat:"sharedComposerSurfaceLabelChat",work:"sharedComposerSurfaceLabelWork",code:"sharedComposerSurfaceLabelCode"};function ix(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 uw({surface:e,onDismiss:t,disabled:n=!1}){const{t:a}=z(),s=a(l[ox[e]]);return r.jsxs("span",{className:`composerSurfaceChip composerSurfaceChip${lx(e)}`,children:[ix(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 lx(e){return e.charAt(0).toUpperCase()+e.slice(1)}const Gd=["code_task","code_codespace","work_item","work_project","work_task","chat_conversation"],Vd=["auto","iframe","image","pdf","code"],cx="/api/canvas/intents/stream",dx="/api/canvas/intents/ack",zd={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"},po={parentUrl(e){return Is(e)},canvasUrl(e,t,n="auto"){return Yd(e,t,n)},projectionApiUrl(e,t,n="auto"){return Jd(e,t,n)},parse(e){return px(e)},parseProjectionApiPath(e){return hx(e)}};function ux(e){Ss(e);const t=new URLSearchParams({surfaceKind:e.kind,surfaceId:e.surfaceId});return`${cx}?${t.toString()}`}function Is(e){return Ss(e),`${zd[e.kind]}/${encodeURIComponent(e.surfaceId)}`}function Yd(e,t,n="auto"){Ss(e);const a=Yo(t,"artifactId"),o=`${Is(e)}/canvas/${encodeURIComponent(a)}`;return n==="auto"?o:`${o}/view/${n}`}function Jd(e,t,n="auto"){Ss(e);const a=Yo(t,"artifactId"),s=`/api/canvas/${encodeURIComponent(e.kind)}/${encodeURIComponent(e.surfaceId)}/artifacts/${encodeURIComponent(a)}`;return n==="auto"?s:`${s}/view/${n}`}function px(e){const t=ho(e);for(const n of Gd){const a=ho(zd[n]);if(!mx(t,a))continue;const s=t[a.length];if(!s||t.length<a.length+1)continue;const o={kind:n,surfaceId:decodeURIComponent(s)},i=Is(o);if(t.length===a.length+1)return{kind:"parent",surface:o,parentUrl:i};if(t[a.length+1]==="canvas")return Xd({surface:o,parentUrl:i,tail:t.slice(a.length+2),composeCanvas:!0})}return null}function hx(e){const t=ho(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(!Qd(n))return null;const a=t[3];if(!a)return null;const s={kind:n,surfaceId:decodeURIComponent(a)},o=Is(s);return Xd({surface:s,parentUrl:o,tail:t.slice(5),composeCanvas:!1})}function Xd(e){const t=e.tail[0];if(!t)return null;let n="auto";if(e.tail.length===3){if(e.tail[1]!=="view"||!fx(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?Yd(e.surface,decodeURIComponent(t),n):Jd(e.surface,decodeURIComponent(t),n),artifactId:decodeURIComponent(t),presentationRequested:n}}function Ss(e){if(!Qd(e.kind))throw new Error(`Unsupported canvas surface kind: ${e.kind}`);Yo(e.surfaceId,"surfaceId")}function Yo(e,t){const n=gx(e);if(!n)throw new Error(`${t} is required.`);return n}function Qd(e){return Gd.includes(e)}function fx(e){return Vd.includes(e)}function ho(e){return e.split("?")[0].split("/").filter(Boolean)}function mx(e,t){return e.length<t.length?!1:t.every((n,a)=>e[a]===n)}function gx(e){if(typeof e!="string")return null;const t=e.trim();return t.length>0?t:null}function ys(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 Cx({projection:e}){const{t}=z(),[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=ys(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 vx({projection:e}){const{t}=z(),n=ys(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 Ix={name:"static",sandbox:"",referrerPolicy:"no-referrer",allow:""};function Sx({projection:e,title:t,safeUrl:n,iframeSandboxProfile:a,className:s="artifactCanvasIframe"}){const{t:o}=z(),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=ys(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?Ix:n;return{status:"ok",title:e.title,safeUrl:t,profile:o}}function bx({projection:e}){const{t}=z(),n=ys(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 Zd(e,t,n,a){return t==="artifact"&&e!==null&&e!==void 0&&e===n&&e===a}function xx(e,t){return Zd(e,t.kind,t.id,t.state.artifact.id)}function wx(e,t){return Zd(e,t.kind,t.id,t.patch.artifactId)}function Nl(){const e=Na(),{artifactId:t,presentation:n}=Yl(),{t:a}=z(),{surface:s,parentUrl:o}=Ox(),[i,u]=p.useState(!1),[c,d]=p.useState(0),[h,f]=p.useState({status:"loading"}),m=p.useRef(null),v=Px(n),C=p.useMemo(()=>!t||!v?null:po.projectionApiUrl(s,t,v),[t,v,s]);zc({kind:"artifact",id:t??null,enabled:C!==null,onSnapshot:y=>{if(xx(t,y)){if(m.current!==C){m.current=C;return}d(g=>g+1)}},onPatch:y=>{wx(t,y)&&d(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(Ax(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 I=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:I?.artifact.title??a(l.sharedArtifactCanvasLoading)})]}),r.jsxs("div",{className:"artifactCanvasActions",children:[I?.externalUrl?r.jsx("a",{className:"operatorActionButton",href:I.externalUrl,target:"_blank",rel:"noreferrer",children:a(l.sharedArtifactCanvasOpenExternal)}):null,r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>d(y=>y+1),children:a(l.sharedArtifactCanvasRefresh)}),r.jsx("button",{type:"button",className:"operatorActionButton",onClick:()=>u(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:kx(h,a)})]})}function kx(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(vx,{projection:n}):n.presentationResolved==="pdf"?r.jsx(bx,{projection:n}):n.presentationResolved==="code"?r.jsx(Cx,{projection:n}):n.safeUrl&&n.iframeSandboxProfile&&n.presentationResolved==="iframe"?r.jsx(Sx,{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 Px(e){return e?Vd.includes(e)?e:null:"auto"}function Ax(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 Rx=[250,500,1e3];function Nx(e){const t=Na();p.useEffect(()=>{if(!e||typeof EventSource>"u")return;const n=new EventSource(ux(e)),a=s=>{const o=jx(s.data);!o||!Lx(o.surface,e)||(t(o.targetUrl),globalThis.setTimeout(()=>{Tx(o.intentId)},0))};return n.addEventListener("artifact_canvas_intent",a),()=>{n.removeEventListener("artifact_canvas_intent",a),n.close()}},[t,e])}async function Tx(e,t=fetch){for(const n of[0,...Rx]){n>0&&await Mx(n);try{if((await t(dx,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({intentId:e})})).ok)return}catch{}}}function jx(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{return null}const n=Gs(t),s=Gs(n?.intent)??n,o=Gs(s?.surface),i=o?.kind,u=o?.surfaceId,c=s?.intentId,d=s?.targetUrl;return typeof i!="string"||typeof u!="string"||typeof c!="string"||typeof d!="string"?null:s}function Lx(e,t){return e.kind===t.kind&&e.surfaceId===t.surfaceId}function Gs(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:null}function Mx(e){return new Promise(t=>{globalThis.setTimeout(t,e)})}const is=460,ls=320,fo=760,Ex=360,Dx=32,Bx=80;function pw(e){return r.jsxs(Ts,{path:e.path,element:r.jsx(_x,{surfaceKind:e.surfaceKind,surfaceIdParam:e.surfaceIdParam,children:e.element}),children:[r.jsx(Ts,{path:"canvas/:artifactId",element:r.jsx(Nl,{})}),r.jsx(Ts,{path:"canvas/:artifactId/view/:presentation",element:r.jsx(Nl,{})})]},e.key)}function Ox(){return kh()}function _x({surfaceKind:e,surfaceIdParam:t,children:n}){const{t:a}=z(),s=Yl(),o=_l(),i=p.useRef(null),u=s[t],c=p.useMemo(()=>u?{kind:e,surfaceId:u}:null,[u,e]);Nx(c);const d=c?po.parse(o.pathname):null,h=!!(c&&d?.kind==="canvas"&&d.surface.kind===c.kind&&d.surface.surfaceId===c.surfaceId),f=c?cs(c):null,[m,v]=p.useState(is),[C,I]=p.useState(null);p.useEffect(()=>{if(!c){I(null),v(is);return}v(Fx(c)),I(cs(c))},[c]),p.useEffect(()=>{!c||!h||C!==f||Wx(c,m)},[h,C,m,c,f]);const y=p.useMemo(()=>Dr(i.current),[h]),g=p.useCallback(P=>{const j=Dr(i.current);v(N=>mo(N+P,j))},[]),x=p.useCallback(P=>{const j=P.shiftKey?Bx:Dx;if(P.key==="ArrowLeft"){P.preventDefault(),g(j);return}if(P.key==="ArrowRight"){P.preventDefault(),g(-j);return}if(P.key==="Home"){P.preventDefault(),v(ls);return}P.key==="End"&&(P.preventDefault(),v(Dr(i.current)))},[g]),S=p.useCallback(P=>{if(P.button!==0)return;const j=i.current;if(!j||typeof window>"u")return;P.preventDefault();const N=j.getBoundingClientRect(),D=Dr(j),T=R=>{v(mo(N.right-R,D))},A=R=>{T(R.clientX)},b=()=>{window.removeEventListener("pointermove",A),window.removeEventListener("pointerup",b)};T(P.clientX),window.addEventListener("pointermove",A),window.addEventListener("pointerup",b,{once:!0})},[]);if(!c)return r.jsx(r.Fragment,{children:n});const k=po.parentUrl(c);if(!h)return r.jsx(r.Fragment,{children:n});const w={"--artifact-canvas-pane-width":`${m}px`};return r.jsxs("div",{className:"artifactCanvasSurfaceFrame",ref:i,style:w,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":ls,"aria-valuemax":y,"aria-valuenow":m,tabIndex:0,onKeyDown:x,onPointerDown:S}),r.jsx(wh,{context:{surface:c,parentUrl:k}})]})}function Fx(e){if(typeof window>"u")return is;const t=window.localStorage.getItem(cs(e)),n=t?Number.parseInt(t,10):NaN;return Number.isFinite(n)?mo(n,fo):is}function Wx(e,t){typeof window>"u"||window.localStorage.setItem(cs(e),String(t))}function cs(e){return`cats.artifactCanvas.paneWidth.${e.kind}.${e.surfaceId}`}function Dr(e){return e?Math.max(ls,Math.min(fo,e.clientWidth-Ex)):fo}function mo(e,t){return Math.min(Math.max(Math.round(e),ls),t)}const eu=420,Vn=12,Tl=8;function Ux(){return{position:"fixed",top:0,left:0,width:`min(${eu}px, calc(100vw - ${Vn*2}px))`,visibility:"hidden",pointerEvents:"none"}}function Kx(e){return Math.max(0,Math.min(eu,e-Vn*2))}function $x({triggerRect:e,viewportWidth:t,viewportHeight:n,menuWidth:a,menuHeight:s}){const o=Kx(t),i=a||o;let u=e.left;u+i>t-Vn&&(u=Math.max(Vn,t-i-Vn));let c=e.bottom+Tl;return s>0&&c+s>n-Vn&&(c=Math.max(Vn,e.top-s-Tl)),{position:"fixed",top:c,left:u,width:o}}function jl(e,t,n=Jl.flushSync){n(e),t()}const Hx=typeof window>"u"?p.useEffect:p.useLayoutEffect;function qx({activeSurface:e,onSelectSurface:t,activeLabelOverride:n}){const a=Na(),{t:s}=z(),[o,i]=p.useState(!1),u=p.useRef(null),c=p.useRef(null),[d,h]=p.useState(),f=p.useMemo(()=>Ph(),[]),m=zs(e,Ah(e),s),v=n??m,C=n!==void 0;p.useEffect(()=>{if(!o)return;function y(x){const S=x.target;!u.current?.contains(S)&&!c.current?.contains(S)&&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]),Hx(()=>{if(!o){h(void 0);return}function y(){const g=u.current;if(!g)return;const x=g.getBoundingClientRect();h($x({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 I=o?r.jsxs("div",{ref:c,className:"platformSurfaceMenu",style:d??Ux(),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)}`,S=zs(y.id,y.productName,s),k=Rh(y.id,y.subtitle,s);return r.jsxs("button",{type:"button",role:"menuitemradio","aria-checked":g,className:g?"platformSurfaceMenuItem isCurrent":"platformSurfaceMenuItem",onClick:()=>{jl(()=>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:S})}),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:()=>{jl(()=>i(!1),()=>{a("/lobby")})},children:s(l.sharedPlatformSurfaceSwitcherOpenLobby)})]}):null;return r.jsxs("div",{ref:u,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"})})]})}),I&&typeof document<"u"?Jl.createPortal(I,document.body):null]})}function Gx({activeSurface:e,sidebarOpen:t,primaryActions:n,onToggleSidebar:a,onSwitchProduct:s,surfaceLabelOverride:o}){const{t:i}=z();return r.jsxs(r.Fragment,{children:[r.jsxs("div",{className:"brandRow",children:[r.jsx("div",{className:"brandCopy",children:r.jsx(qx,{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(u=>r.jsxs("button",{className:u.active?"navItem navItemActive":"navItem",onClick:u.onClick,type:"button",children:[r.jsx("span",{className:"navGlyph","aria-hidden":"true",children:u.icon}),r.jsx("span",{className:"navLabel",children:u.label})]},u.key))})]})}function Vx({overflowKey:e,item:t,overflowOpen:n,onOverflowToggle:a}){const s=p.useRef(null),o=p.useRef(null),i=wo(s,o,n),u=t.overflowActions??[],c=u.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:d=>{d.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:d=>{d.stopPropagation(),a()},children:"⋯"})}):null,n&&c?r.jsx(ko,{menuRef:o,className:"recentOverflowMenu",style:i,onClick:d=>d.stopPropagation(),children:u.map((d,h)=>{const f=h>0?u[h-1]:void 0,m=d.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:d.disabled===!0,onClick:d.onClick,children:d.label})]},d.key)})}):null]})}function Jo(e){return Xl(e)}function go(e,t){return Jo(e.originSurface)===t}function zx(e,t){if(e.kind==="channel")return go(e.channel,t)?e:null;const n=e.channels.filter(s=>go(s.channel,t));if(n.length===0)return null;const a=e.originSurface??n[0]?.channel.originSurface??null;return Jo(a)!==t?null:{...e,channels:n}}function Yx(e){const{payload:t,helpers:n,recentEntries:a,currentPath:s,t:o}=e,i=e.shellSurface??Nh(s),u=t.chat.cats.filter(v=>n.isVisibleCat(v)),c=t.runtime??{baseUrl:t.runtimeBaseUrl??"",reachable:t.runtimeReachable,status:null},d=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)&&go(v,i)),f=a?a.map(v=>zx(v,i)).filter(v=>v!=null):h.map(v=>({kind:"channel",channel:v})),m=Th(c);return{activeSurface:i,showMyCats:u.length>0,visibleCats:u,resolvedRuntime:c,telegramBoundCatIds:d,resolvedRecentEntries:f,runtimeFooterStatus:m,runtimeFooterLabel:jh(m,o)}}function tu({title:e,onRename:t,onBeforeStart:n}){const[a,s]=p.useState(!1),[o,i]=p.useState(""),u=p.useRef(null);function c(){t&&(n?.(),i(e),s(!0),requestAnimationFrame(()=>u.current?.select()))}function d(){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:u,setRenameValue:i,startRename:c,commitRename:d,cancelRename:h}}function Jx(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 Xx({channel:e,payload:t,helpers:n,isSelected:a,busy:s,overflowOpen:o,onSelect:i,onRename:u,onDelete:c,onOverflowToggle:d,titleOverride:h,disableRename:f}){const{t:m}=z(),v=Jx(e,t),C=p.useRef(null),I=p.useRef(null),y=wo(C,I,o),{renaming:g,renameValue:x,inputRef:S,setRenameValue:k,startRename:w,commitRename:P,cancelRename:j}=tu({title:e.title,onRename:f?void 0:u,onBeforeStart:d});return r.jsxs("article",{className:["recentItemCard",a?"recentItemSelected":"",o?"recentItemOverflowOpen":""].filter(Boolean).join(" "),onClick:()=>{g||i()},children:[g?r.jsx("input",{ref:S,className:"recentRenameInput",type:"text",value:x,onChange:N=>k(N.target.value),onKeyDown:N=>{N.key==="Enter"&&P(),N.key==="Escape"&&j()},onBlur:P}):r.jsx("button",{className:"recentSelectButton",onClick:N=>{N.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:N=>{N.stopPropagation(),d()},children:"⋯"})]}),o?r.jsxs(ko,{menuRef:I,className:"recentOverflowMenu",style:y,onClick:N=>N.stopPropagation(),children:[f?null:r.jsxs(r.Fragment,{children:[r.jsx("button",{type:"button",onClick:w,children:m(l.conversationSidebarRenameLabel)}),r.jsx("div",{className:"recentOverflowMenuDivider"})]}),r.jsx("button",{type:"button",disabled:Js(s,"delete",e.id),onClick:c,children:Js(s,"delete",e.id)?m(l.conversationSidebarDeletingLabel):m(l.conversationSidebarDeleteLabel)})]}):null]})}function Qx({title:e,isSelected:t,busy:n,overflowOpen:a,onSelect:s,onRename:o,onUngroup:i,onDelete:u,onOverflowToggle:c,renameBusyKey:d,ungroupBusyKey:h,deleteBusyKey:f}){const{t:m}=z(),v=p.useRef(null),C=p.useRef(null),I=wo(v,C,a),y=b=>b?.split(":").at(-1),g=d?js(n,"rename",y(d)):!1,x=h?js(n,"ungroup",y(h)):!1,S=f?js(n,"delete",y(f)):!1,k=!!(o||i||u),{renaming:w,renameValue:P,inputRef:j,setRenameValue:N,startRename:D,commitRename:T,cancelRename:A}=tu({title:e,onRename:o,onBeforeStart:c});return r.jsxs("article",{className:["recentItemCard",t?"recentItemSelected":"",a?"recentItemOverflowOpen":""].filter(Boolean).join(" "),onClick:()=>{w||s()},children:[w?r.jsx("input",{ref:j,className:"recentRenameInput",type:"text",value:P,onChange:b=>N(b.target.value),onKeyDown:b=>{b.key==="Enter"&&T(),b.key==="Escape"&&A()},onBlur:T}):r.jsx("button",{className:"recentSelectButton",onClick:b=>{b.stopPropagation(),s()},type:"button",children:r.jsx("strong",{children:e})}),w?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(ko,{menuRef:C,className:"recentOverflowMenu",style:I,onClick:b=>b.stopPropagation(),children:[o?r.jsx("button",{type:"button",disabled:g,onClick:D,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,u?r.jsxs(r.Fragment,{children:[o||i?r.jsx("div",{className:"recentOverflowMenuDivider"}):null,r.jsx("button",{type:"button",disabled:S,onClick:u,children:m(S?l.conversationSidebarDeletingLabel:l.conversationSidebarDeleteAllLabel)})]}):null]}):null]})}function Zx({entries:e,emptyStateLabel:t,payload:n,helpers:a,routeChannelId:s,busy:o,overflowMenuOpenId:i,onSelect:u,onDeleteChannel:c,onRenameChannel:d,onOverflowMenuToggle:h}){const{t:f}=z();function m(C){const I=C.key??C.channel.id;return r.jsx(Xx,{channel:C.channel,payload:n,helpers:a,isSelected:s===C.channel.id,busy:o,overflowOpen:i===I,onSelect:()=>u(C.channel.id),onRename:y=>{d(C.channel.id,y)},onDelete:()=>{h(null),c(C.channel.id)},onOverflowToggle:()=>h(i===I?null:I),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 I=C.overflowKey??C.key;return r.jsxs("section",{className:"recentGroupCard",children:[r.jsx(Qx,{title:C.title,isSelected:C.isSelected??!1,busy:o,overflowOpen:i===I,onSelect:C.onSelect,onRename:C.onRename,onUngroup:C.onUngroup,onDelete:C.onDelete,onOverflowToggle:()=>h(i===I?null:I),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 ew({payload:e,sidebarOpen:t,accountMenuOpen:n,overflowMenuOpenId:a,busy:s,surface:o,shellSurface:i,routeChannelId:u,accountMenuRef:c,primaryActions:d,extraActionGroups:h=[],recentEntries:f,recentEmptyStateLabel:m,myCatsSectionLabel:v,forceShowMyCatsSection:C=!1,myCatsSectionCats:I,myCatsEmptyStatePlaceholder:y,myCatsTerminalActionLabelKey:g,myCatsDisableTerminalActionWhenDraft:x,helpers:S,onToggleSidebar:k,onCollapsedSidebarClick:w,onOpenChatsOverview:P,onSelect:j,onDeleteChannel:N,onRenameChannel:D,onArchiveCat:T,onAccountMenuToggle:A,onOverflowMenuToggle:b,onNavigateSettings:R,onNavigateRuntime:L,onSwitchProduct:O,activeMyCatId:Y,onDirectChatCat:$,t:M}){const F=globalThis.location?.pathname??"/",{activeSurface:J,visibleCats:me,telegramBoundCatIds:K,resolvedRecentEntries:B,runtimeFooterStatus:ae,runtimeFooterLabel:be}=Yx({payload:e,helpers:S,recentEntries:f,shellSurface:i,currentPath:F,t:M}),W=v??M(l.conversationSidebarDirectMessagesLabel),q=I??me,_e=C||y!=null;return r.jsxs("aside",{className:t?"sidebar":"sidebar sidebarCollapsed","data-shell-surface":i??J,onClick:le=>w(le),children:[r.jsxs("div",{className:"sidebarInner",children:[r.jsx(Gx,{activeSurface:J,sidebarOpen:t,primaryActions:d,onToggleSidebar:k,onSwitchProduct:O}),r.jsxs("div",{className:"sidebarScrollable",children:[r.jsx("nav",{className:"navGroup navGroupChat","aria-label":M(l.conversationSidebarChatsLabel),children:r.jsxs("button",{className:o==="chats"?"navItem navItemActive":"navItem",onClick:P,type:"button",children:[r.jsx("span",{className:"navGlyph navGlyphSquare","aria-hidden":"true"}),r.jsx("span",{className:"navLabel",children:M(l.conversationSidebarChatsLabel)})]})}),h.map(le=>r.jsxs("nav",{className:"navGroup","aria-label":le.ariaLabel,children:[le.items.map(xe=>r.jsxs("button",{className:xe.active?"navItem navItemActive":"navItem",onClick:xe.onClick,type:"button",children:[r.jsx("span",{className:"navGlyph","aria-hidden":"true",children:xe.icon}),r.jsx("span",{className:"navLabel",children:xe.label})]},xe.key)),le.pinnedItems&&le.pinnedItems.length>0?r.jsx("div",{className:"navGroupPinnedList",children:le.pinnedItems.map(xe=>{const Ae=`pinned:${le.key}:${xe.id}`,X=a===Ae;return r.jsx(Vx,{overflowKey:Ae,item:xe,overflowOpen:X,onOverflowToggle:()=>b(X?null:Ae)},xe.id)})}):null]},le.key)),_e?r.jsx(Lh,{label:W,cats:q,bossCatId:e.chat.bossCatId,payloadChannels:e.chat.channels,activeMyCatId:Y,telegramBoundCatIds:K,helpers:S,overflowMenuOpenId:a,onOverflowMenuToggle:b,onDirectChatCat:$,onArchiveCat:T,emptyStatePlaceholder:y,terminalActionLabelKey:g,disableTerminalActionWhenDraft:x}):null,r.jsx(Zx,{entries:B,emptyStateLabel:m,payload:e,helpers:S,routeChannelId:u,busy:s,overflowMenuOpenId:a,onSelect:j,onDeleteChannel:N,onRenameChannel:D,onOverflowMenuToggle:b})]})]}),r.jsx(Mh,{slotKind:"workspace"}),r.jsx(Eh,{payload:e,accountMenuOpen:n,accountMenuRef:c,runtimeFooterStatus:ae,runtimeFooterLabel:be,onAccountMenuToggle:A,onNavigateSettings:R,onNavigateRuntime:L,catInitials:S.catInitials})]})}function hw(e){const{t}=z();return r.jsx(ew,{...e,t})}const Ll="direct_message";function tw(e,t){return e.filter(n=>n.channelKind===Ll||n.roomMode===Ll?!1:Xl(n.originSurface)===t)}function fw(e){const t=tw(e.channels,e.activeSurface),n=(e.parallelChatGroups??[]).filter(c=>c.status==="active"&&Jo(c.originSurface)===e.activeSurface),a=new Map;for(const c of n)for(const d of c.memberChannelIds)a.set(d,c);const s=new Map(t.map(c=>[c.id,c])),o=[],i=new Set,u=new Set;for(const c of t){if(i.has(c.id))continue;const d=a.get(c.id);if(d&&!u.has(d.id)){const h=d.memberChannelIds.map(f=>s.get(f)??null).filter(f=>f!=null);if(h.length>1){u.add(d.id),h.forEach(f=>i.add(f.id)),o.push({kind:"group",key:d.id,title:d.title,originSurface:d.originSurface,overflowKey:`group:${d.id}`,isSelected:d.memberChannelIds.includes(e.routeChannelId??""),onSelect:()=>{const f=d.memberChannelIds[0];f&&e.onSelect(f)},onRename:e.onRenameParallelGroup?f=>{e.onRenameParallelGroup?.(d.id,f)}:void 0,onUngroup:e.onUngroupParallelGroup?()=>{e.onUngroupParallelGroup?.(d.id)}:void 0,onDelete:e.onDeleteParallelGroup?()=>{e.onCloseOverflowMenu?.(),e.onDeleteParallelGroup?.(d.id)}:void 0,renameBusyKey:`concurrent-group:rename:${d.id}`,ungroupBusyKey:`concurrent-group:ungroup:${d.id}`,deleteBusyKey:`concurrent-group:delete:${d.id}`,channels:h.map(f=>({channel:f,titleOverride:d.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{ow as A,uw as C,lw as D,Ub as F,Sx as I,dw as N,Mb as P,nx as W,iw as a,Md as b,hw as c,fw as d,sw as e,Fh as f,cw as g,Ix as h,rw as i,Cb as j,Jn as k,jm as l,$b as m,wa as n,Ur as o,Wg as p,co as q,Kv as r,Td as s,Hb as t,ax as u,Pl as v,pw as w,xa as x};
|